@sprig-technologies/sprig-browser 2.28.0 → 2.28.1

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.
@@ -1,11 +1,11 @@
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 pe=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.FeedbackClosed="feedback.closed",e.PageChange="page.change",e.API="api",e.Override="override",e))(pe||{}),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),jr={randomUUID:Ms};function $e(e,t,n){if(jr.randomUUID&&!t&&!e)return jr.randomUUID();e=e||{};const r=e.random||(e.rng||Ts)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){n=n||0;for(let i=0;i<16;++i)t[n+i]=r[i];return t}return Bs(r)}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}',hi="360px",js="ul-app",Ks="#e6e6e6",Ns="#bd282a",$s=500,qs=1030,fi=()=>{try{return window.parent.Intercom}catch{return null}},Vs=()=>{const e=fi();e&&(e.ul_wasVisible&&e("update",{hide_default_launcher:!1}),delete e.ul_wasVisible)},Ws=()=>{const e=fi();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"})),Kr=[zs];class mi{static disable(){Kr.forEach(t=>t.disable())}static enable(){Kr.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"}},yi=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=yi.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=(...r)=>(this.removeListener(e,n),t.apply(this,r));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(r=>{r.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 r=new Hs(this,e,this.listenerCount(e));console.warn(r)}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 r=[t].concat(n);this.events.set(e,r)}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)}},gi=yi;gi.defaultMaxListeners=10;const R=new gi,Xt=e=>new Promise(t=>{setTimeout(()=>{t()},e)}),wi=({"userleap-platform":e})=>e!=="web";class vi{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 Le=new vi("sessionStorage"),te=new vi("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,r)=>{this.reject=r,this.resolve=n})}resolveRequest(t){this.resolve(t)}}const Ys={RATELIMIT_RESET_DEFAULT:10};let bi=!1,_i="",Dt=!1,Si=!1,Nt=[];const Js=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?"web-gtm":e._segment?"web-segment":"web-snippet",Dn=e=>{var t;(t=e==null?void 0:e.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(Si=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`),document.removeEventListener("securitypolicyviolation",Dn))},Pn=(e="")=>{bi=!0,_i=e};function Fe(e={}){const t={"Content-Type":"application/json","userleap-platform":"web","x-ul-sdk-version":"2.28.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 Nr=async({shouldDropOnRateLimit:e,...t})=>{if(e)return{status:429};{const n=new Gs(t);return Nt.push(n),n.promise}},me=async(e,t)=>{const{retries:n=0,shouldDropOnRateLimit:r=!1,shouldRetryRequest:i=!1,...s}=t,o={url:e,options:s,retries:n,shouldDropOnRateLimit:r};if(Dt&&!i)return Nr(o);const a={ok:!1,reportError:!1};if(bi)return console.info(`UserLeap - ${_i}`),a;try{const l=await fetch(e,s);if(l.status===429)if(!Dt&&!r||i){Dt=!0;const u=l.headers.has("ratelimit-reset")?Number(l.headers.get("ratelimit-reset")):Ys.RATELIMIT_RESET_DEFAULT;return await Xt(u*1e3),me(e,{...s,shouldDropOnRateLimit:r,shouldRetryRequest:!0})}else return Nr(o);if(Dt=!1,Nt.length&&(Nt.map(c=>{const u=c.payload;me(u.url,{...u.options,retries:u.retries,shouldDropOnRateLimit:u.shouldDropOnRateLimit}).then(p=>{c.resolveRequest(p)})}),Nt=[]),l.ok){if(l.status===249)return Pn(),a;const c=await l.text();try{return c&&c!=="OK"&&(l.json=JSON.parse(c)),l}catch{return{ok:!1,reportError:!1,error:new Error(`failed parsing response json for ${e} - ${c}`)}}}return l}catch(l){const c=n+1;return c>5||Si?{ok:!1,reportError:!1,error:l}:(await Xt(Math.pow(2,n)*1e3),me(e,{...s,retries:c}))}},et={Error:1,Warn:2,Info:3,Debug:4};let Tn=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>Tn&&Qe.shift()},pn=(e,t)=>{e>Zt||(Qe.push({level:e,line:Zs(t,new Date)}),to())},vt=e=>{pn(et.Debug,e)},I=e=>{pn(et.Info,e)},Bn=e=>{pn(et.Warn,e)},Ei=e=>{pn(et.Error,e)},no=()=>Qe.map(e=>e.line),ro=()=>new TextEncoder().encode(no().join(`
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 pe=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.FeedbackClosed="feedback.closed",e.PageChange="page.change",e.API="api",e.Override="override",e))(pe||{}),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),jr={randomUUID:Ms};function $e(e,t,n){if(jr.randomUUID&&!t&&!e)return jr.randomUUID();e=e||{};const r=e.random||(e.rng||Ts)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){n=n||0;for(let i=0;i<16;++i)t[n+i]=r[i];return t}return Bs(r)}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}',hi="360px",js="ul-app",Ks="#e6e6e6",Ns="#bd282a",$s=500,qs=1030,fi=()=>{try{return window.parent.Intercom}catch{return null}},Vs=()=>{const e=fi();e&&(e.ul_wasVisible&&e("update",{hide_default_launcher:!1}),delete e.ul_wasVisible)},Ws=()=>{const e=fi();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"})),Kr=[zs];class mi{static disable(){Kr.forEach(t=>t.disable())}static enable(){Kr.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"}},yi=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=yi.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=(...r)=>(this.removeListener(e,n),t.apply(this,r));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(r=>{r.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 r=new Hs(this,e,this.listenerCount(e));console.warn(r)}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 r=[t].concat(n);this.events.set(e,r)}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)}},gi=yi;gi.defaultMaxListeners=10;const R=new gi,Xt=e=>new Promise(t=>{setTimeout(()=>{t()},e)}),wi=({"userleap-platform":e})=>e!=="web";class vi{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 Le=new vi("sessionStorage"),te=new vi("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,r)=>{this.reject=r,this.resolve=n})}resolveRequest(t){this.resolve(t)}}const Ys={RATELIMIT_RESET_DEFAULT:10};let bi=!1,_i="",Dt=!1,Si=!1,Nt=[];const Js=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?"web-gtm":e._segment?"web-segment":"web-snippet",Dn=e=>{var t;(t=e==null?void 0:e.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(Si=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`),document.removeEventListener("securitypolicyviolation",Dn))},Pn=(e="")=>{bi=!0,_i=e};function Fe(e={}){const t={"Content-Type":"application/json","userleap-platform":"web","x-ul-sdk-version":"2.28.1","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 Nr=async({shouldDropOnRateLimit:e,...t})=>{if(e)return{status:429};{const n=new Gs(t);return Nt.push(n),n.promise}},me=async(e,t)=>{const{retries:n=0,shouldDropOnRateLimit:r=!1,shouldRetryRequest:i=!1,...s}=t,o={url:e,options:s,retries:n,shouldDropOnRateLimit:r};if(Dt&&!i)return Nr(o);const a={ok:!1,reportError:!1};if(bi)return console.info(`UserLeap - ${_i}`),a;try{const l=await fetch(e,s);if(l.status===429)if(!Dt&&!r||i){Dt=!0;const u=l.headers.has("ratelimit-reset")?Number(l.headers.get("ratelimit-reset")):Ys.RATELIMIT_RESET_DEFAULT;return await Xt(u*1e3),me(e,{...s,shouldDropOnRateLimit:r,shouldRetryRequest:!0})}else return Nr(o);if(Dt=!1,Nt.length&&(Nt.map(c=>{const u=c.payload;me(u.url,{...u.options,retries:u.retries,shouldDropOnRateLimit:u.shouldDropOnRateLimit}).then(p=>{c.resolveRequest(p)})}),Nt=[]),l.ok){if(l.status===249)return Pn(),a;const c=await l.text();try{return c&&c!=="OK"&&(l.json=JSON.parse(c)),l}catch{return{ok:!1,reportError:!1,error:new Error(`failed parsing response json for ${e} - ${c}`)}}}return l}catch(l){const c=n+1;return c>5||Si?{ok:!1,reportError:!1,error:l}:(await Xt(Math.pow(2,n)*1e3),me(e,{...s,retries:c}))}},et={Error:1,Warn:2,Info:3,Debug:4};let Tn=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>Tn&&Qe.shift()},pn=(e,t)=>{e>Zt||(Qe.push({level:e,line:Zs(t,new Date)}),to())},vt=e=>{pn(et.Debug,e)},I=e=>{pn(et.Info,e)},Bn=e=>{pn(et.Warn,e)},Ei=e=>{pn(et.Error,e)},no=()=>Qe.map(e=>e.line),ro=()=>new TextEncoder().encode(no().join(`
2
2
  `)),ki=async e=>{if(!e)return;const t=ro();return me(e,{body:t,method:"PUT"})},io=(e,t)=>{e!==void 0&&(Tn=e),t!==void 0&&(Zt=t),vt(`Initializing logger with limit of ${Tn} lines and ${Qs(Zt)} level`),eo()};var Mn=(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))(Mn||{});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 Li=new so(2),oo=e=>Li.setLimit(e),ao=async e=>Li.execute(async()=>{var r;I(`Beginning upload of chunk ${e.chunkIndex} for survey: ${e.surveyId}`);const t=await me(e.uploadUrl,{body:e.data,method:"PUT"});I(`Completed upload of chunk ${e.chunkIndex} for survey: ${e.surveyId}`);const n=(r=t.headers)==null?void 0:r.get("ETag");if(!n)throw new Error(`Upload response did not include etag for upload ${e.uploadId}, part ${e.chunkIndex}`);return n}),Ii=async({apiUrl:e,surveyId:t,uploadId:n,etags:r,headers:i,responseGroupUuid:s,replayDuration:o,eventDigest:a},l=!1)=>{var u;if(!l&&!n&&!r){I(`Cannot mark upload complete: isMobile: ${l} / uploadId: ${n} / etags: ${r}`);return}I(`Marking upload complete for survey: ${t}`);const c=await me(`${e}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:r,uploadId:n,responseGroupUuid:s,surveyId:t,replayDuration:o,eventDigest:a,userAgent:(u=window==null?void 0:window.navigator)==null?void 0:u.userAgent}),headers:i,shouldRetryRequest:!0});return I(`Done marking upload complete for survey: ${t}`),c},j=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,$=Object.keys,Y=Array.isArray;function Q(e,t){return typeof t!="object"||$(t).forEach(function(n){e[n]=t[n]}),e}typeof Promise>"u"||j.Promise||(j.Promise=Promise);const bt=Object.getPrototypeOf,lo={}.hasOwnProperty;function ne(e,t){return lo.call(e,t)}function Xe(e,t){typeof t=="function"&&(t=t(bt(e))),(typeof Reflect>"u"?$:Reflect.ownKeys)(t).forEach(n=>{ye(e,n,t[n])})}const Ui=Object.defineProperty;function ye(e,t,n,r){Ui(e,t,Q(n&&ne(n,"get")&&typeof n.get=="function"?{get:n.get,set:n.set,configurable:!0}:{value:n,configurable:!0,writable:!0},r))}function He(e){return{from:function(t){return e.prototype=Object.create(t.prototype),ye(e.prototype,"constructor",e),{extend:Xe.bind(null,e.prototype)}}}}const co=Object.getOwnPropertyDescriptor;function br(e,t){let n;return co(e,t)||(n=bt(e))&&br(n,t)}const uo=[].slice;function en(e,t,n){return uo.call(e,t,n)}function xi(e,t){return t(e)}function at(e){if(!e)throw new Error("Assertion Failed")}function Ai(e){j.setImmediate?setImmediate(e):setTimeout(e,0)}function Ri(e,t){return e.reduce((n,r,i)=>{var s=t(r,i);return s&&(n[s[0]]=s[1]),n},{})}function ge(e,t){if(typeof t=="string"&&ne(e,t))return e[t];if(!t)return e;if(typeof t!="string"){for(var n=[],r=0,i=t.length;r<i;++r){var s=ge(e,t[r]);n.push(s)}return n}var o=t.indexOf(".");if(o!==-1){var a=e[t.substr(0,o)];return a==null?void 0:ge(a,t.substr(o+1))}}function ie(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 r=0,i=t.length;r<i;++r)ie(e,t[r],n[r])}else{var s=t.indexOf(".");if(s!==-1){var o=t.substr(0,s),a=t.substr(s+1);if(a==="")n===void 0?Y(e)&&!isNaN(parseInt(o))?e.splice(o,1):delete e[o]:e[o]=n;else{var l=e[o];l&&ne(e,o)||(l=e[o]={}),ie(l,a,n)}}else n===void 0?Y(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}function Ci(e){var t={};for(var n in e)ne(e,n)&&(t[n]=e[n]);return t}const po=[].concat;function Oi(e){return po.apply([],e)}const Di="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(Oi([8,16,32,64].map(e=>["Int","Uint","Float"].map(t=>t+e+"Array")))).filter(e=>j[e]),ho=Di.map(e=>j[e]);Ri(Di,e=>[e,!0]);let _e=null;function xt(e){_e=typeof WeakMap<"u"&&new WeakMap;const t=Fn(e);return _e=null,t}function Fn(e){if(!e||typeof e!="object")return e;let t=_e&&_e.get(e);if(t)return t;if(Y(e)){t=[],_e&&_e.set(e,t);for(var n=0,r=e.length;n<r;++n)t.push(Fn(e[n]))}else if(ho.indexOf(e.constructor)>=0)t=e;else{const s=bt(e);for(var i in t=s===Object.prototype?{}:Object.create(s),_e&&_e.set(e,t),e)ne(e,i)&&(t[i]=Fn(e[i]))}return t}const{toString:fo}={};function jn(e){return fo.call(e).slice(8,-1)}const Kn=typeof Symbol<"u"?Symbol.iterator:"@@iterator",mo=typeof Kn=="symbol"?function(e){var t;return e!=null&&(t=e[Kn])&&t.apply(e)}:function(){return null},ze={};function he(e){var t,n,r,i;if(arguments.length===1){if(Y(e))return e.slice();if(this===ze&&typeof e=="string")return[e];if(i=mo(e)){for(n=[];!(r=i.next()).done;)n.push(r.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 _r=typeof Symbol<"u"?e=>e[Symbol.toStringTag]==="AsyncFunction":()=>!1;var le=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function Pi(e,t){le=e,Ti=t}var Ti=()=>!0;const yo=!new Error("").stack;function qe(){if(yo)try{throw qe.arguments,new Error}catch(e){return e}return new Error}function Nn(e,t){var n=e.stack;return n?(t=t||0,n.indexOf(e.name)===0&&(t+=(e.name+e.message).split(`
3
3
  `).length),n.split(`
4
4
  `).slice(t).filter(Ti).map(r=>`
5
5
  `+r).join("")):""}var Bi=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],Sr=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(Bi),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 Mi(e,t){return e+". Errors: "+Object.keys(t).map(n=>t[n].toString()).filter((n,r,i)=>i.indexOf(n)===r).join(`
6
6
  `)}function tn(e,t,n,r){this._e=qe(),this.failures=t,this.failedKeys=r,this.successCount=n,this.message=Mi(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=Mi(e,t)}He(Ge).from(Error).extend({stack:{get:function(){return this._stack||(this._stack=this.name+": "+this.message+Nn(this._e,2))}},toString:function(){return this.name+": "+this.message}}),He(tn).from(Ge),He(dt).from(Ge);var Er=Sr.reduce((e,t)=>(e[t]=t+"Error",e),{});const wo=Ge;var x=Sr.reduce((e,t)=>{var n=t+"Error";function r(i,s){this._e=qe(),this.name=n,i?typeof i=="string"?(this.message=`${i}${s?`
7
7
  `+s:""}`,this.inner=s||null):typeof i=="object"&&(this.message=`${i.name} ${i.message}`,this.inner=i):(this.message=go[t]||n,this.inner=null)}return He(r).from(wo),e[t]=r,e},{});x.Syntax=SyntaxError,x.Type=TypeError,x.Range=RangeError;var $r=Bi.reduce((e,t)=>(e[t+"Error"]=x[t],e),{}),$t=Sr.reduce((e,t)=>(["Syntax","Type","Range"].indexOf(t)===-1&&(e[t+"Error"]=x[t]),e),{});function T(){}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===T?t:function(){var n=e.apply(this,arguments);n!==void 0&&(arguments[0]=n);var r=this.onsuccess,i=this.onerror;this.onsuccess=null,this.onerror=null;var s=t.apply(this,arguments);return r&&(this.onsuccess=this.onsuccess?je(r,this.onsuccess):r),i&&(this.onerror=this.onerror?je(i,this.onerror):i),s!==void 0?s:n}}function _o(e,t){return e===T?t:function(){e.apply(this,arguments);var n=this.onsuccess,r=this.onerror;this.onsuccess=this.onerror=null,t.apply(this,arguments),n&&(this.onsuccess=this.onsuccess?je(n,this.onsuccess):n),r&&(this.onerror=this.onerror?je(r,this.onerror):r)}}function So(e,t){return e===T?t:function(n){var r=e.apply(this,arguments);Q(n,r);var i=this.onsuccess,s=this.onerror;this.onsuccess=null,this.onerror=null;var o=t.apply(this,arguments);return i&&(this.onsuccess=this.onsuccess?je(i,this.onsuccess):i),s&&(this.onerror=this.onerror?je(s,this.onerror):s),r===void 0?o===void 0?void 0:o:Q(r,o)}}function Eo(e,t){return e===T?t:function(){return t.apply(this,arguments)!==!1&&e.apply(this,arguments)}}function kr(e,t){return e===T?t:function(){var n=e.apply(this,arguments);if(n&&typeof n.then=="function"){for(var r=this,i=arguments.length,s=new Array(i);i--;)s[i]=arguments[i];return n.then(function(){return t.apply(r,s)})}return t.apply(this,arguments)}}$t.ModifyError=tn,$t.DexieError=Ge,$t.BulkError=dt;var St={};const Fi=100,[$n,nn,qn]=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]})(),ji=nn&&nn.then,qt=$n&&$n.constructor,Lr=!!qn;var Vn=!1,ko=qn?()=>{qn.then(Pt)}:j.setImmediate?setImmediate.bind(null,Pt):j.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)},Wn=!0,rn=!0,Te=[],Vt=[],zn=null,Hn=_t,Ye={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:Wr,pgp:!1,env:{},finalize:function(){this.unhandleds.forEach(e=>{try{Wr(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=T,this._lib=!1;var t=this._PSD=U;if(le&&(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&&Yn(this,this._value))}this._state=null,this._value=null,++t.ref,Ni(this,e)}const Gn={get:function(){var e=U,t=sn;function n(r,i){var s=!e.global&&(e!==U||t!==sn);const o=s&&!we();var a=new L((l,c)=>{Ir(this,new Ki(on(r,e,s,o),on(i,e,s,o),l,c,e))});return le&&Vi(a,this),a}return n.prototype=St,n},set:function(e){ye(this,"then",e&&e.prototype===St?Gn:{get:function(){return e},set:Gn.set})}};function Ki(e,t,n,r,i){this.onFulfilled=typeof e=="function"?e:null,this.onRejected=typeof t=="function"?t:null,this.resolve=n,this.reject=r,this.psd=i}function Ni(e,t){try{t(n=>{if(e._state===null){if(n===e)throw new TypeError("A promise cannot be resolved with itself.");var r=e._lib&&At();n&&typeof n.then=="function"?Ni(e,(i,s)=>{n instanceof L?n._then(i,s):n.then(i,s)}):(e._state=!0,e._value=n,$i(e)),r&&Rt()}},Yn.bind(null,e))}catch(n){Yn(e,n)}}function Yn(e,t){if(Vt.push(t),e._state===null){var n=e._lib&&At();t=Hn(t),e._state=!1,e._value=t,le&&t!==null&&typeof t=="object"&&!t._promise&&function(r,i,s){try{r.apply(null,s)}catch(o){i&&i(o)}}(()=>{var r=br(t,"stack");t._promise=e,ye(t,"stack",{get:()=>Vn?r&&(r.get?r.get.apply(t):r.value):e.stack})}),function(r){Te.some(i=>i._value===r._value)||Te.push(r)}(e),$i(e),n&&Rt()}}function $i(e){var t=e._listeners;e._listeners=[];for(var n=0,r=t.length;n<r;++n)Ir(e,t[n]);var i=e._PSD;--i.ref||i.finalize(),Be===0&&(++Be,pt(()=>{--Be==0&&Ur()},[]))}function Ir(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{zn=t;var r,i=t._value;t._state?r=e(i):(Vt.length&&(Vt=[]),r=e(i),Vt.indexOf(i)===-1&&function(s){for(var o=Te.length;o;)if(Te[--o]._value===s._value)return void Te.splice(o,1)}(t)),n.resolve(r)}catch(s){n.reject(s)}finally{zn=null,--Be==0&&Ur(),--n.psd.ref||n.psd.finalize()}}function qi(e,t,n){if(t.length===n)return t;var r="";if(e._state===!1){var i,s,o=e._value;o!=null?(i=o.name||"Error",s=o.message||o,r=Nn(o,0)):(i=o,s=""),t.push(i+(s?": "+s:"")+r)}return le&&((r=Nn(e._stackHolder,2))&&t.indexOf(r)===-1&&t.push(r),e._prev&&qi(e._prev,t,n)),t}function Vi(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=Wn;return Wn=!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 r=e[t];r[0].apply(null,r[1])}while(lt.length>0);Wn=!0,rn=!0}function Ur(){var e=Te;Te=[],e.forEach(r=>{r._PSD.onunhandled.call(null,r._value,r)});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 r=At(),i=U;try{return Ue(n,!0),e.apply(this,arguments)}catch(s){t&&t(s)}finally{Ue(i,!1),r&&Rt()}}}Xe(L.prototype,{then:Gn,_then:function(e,t){Ir(this,new Ki(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,r=>r instanceof t?n(r):Tt(r)):this.then(null,r=>r&&r.name===t?n(r):Tt(r))},finally:function(e){return this.then(t=>(e(),t),t=>(e(),Tt(t)))},stack:{get:function(){if(this._stack)return this._stack;try{Vn=!0;var e=qi(this,[],20).join(`
8
- From previous: `);return this._state!==null&&(this._stack=e),e}finally{Vn=!1}}},timeout:function(e,t){return e<1/0?new L((n,r)=>{var i=setTimeout(()=>r(new x.Timeout(t)),e);this.then(n,r).finally(clearTimeout.bind(null,i))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&ye(L.prototype,Symbol.toStringTag,"Dexie.Promise"),Ye.env=Wi(),Xe(L,{all:function(){var e=he.apply(null,arguments).map(Bt);return new L(function(t,n){e.length===0&&t([]);var r=e.length;e.forEach((i,s)=>L.resolve(i).then(o=>{e[s]=o,--r||t(e)},n))})},resolve:e=>{if(e instanceof L)return e;if(e&&typeof e.then=="function")return new L((n,r)=>{e.then(n,r)});var t=new L(St,!0,e);return Vi(t,zn),t},reject:Tt,race:function(){var e=he.apply(null,arguments).map(Bt);return new L((t,n)=>{e.map(r=>L.resolve(r).then(t,n))})},PSD:{get:()=>U,set:e=>U=e},totalEchoes:{get:()=>sn},newPSD:Ie,usePSD:nt,scheduler:{get:()=>pt,set:e=>{pt=e}},rejectionMapper:{get:()=>Hn,set:e=>{Hn=e}},follow:(e,t)=>new L((n,r)=>Ie((i,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&&Ur()},[])})(()=>{this.unhandleds.length===0?i():s(this.unhandleds[0])})},o.finalize),e()},t,n,r))}),qt&&(qt.allSettled&&ye(L,"allSettled",function(){const e=he.apply(null,arguments).map(Bt);return new L(t=>{e.length===0&&t([]);let n=e.length;const r=new Array(n);e.forEach((i,s)=>L.resolve(i).then(o=>r[s]={status:"fulfilled",value:o},o=>r[s]={status:"rejected",reason:o}).then(()=>--n||t(r)))})}),qt.any&&typeof AggregateError<"u"&&ye(L,"any",function(){const e=he.apply(null,arguments).map(Bt);return new L((t,n)=>{e.length===0&&n(new AggregateError([]));let r=e.length;const i=new Array(r);e.forEach((s,o)=>L.resolve(s).then(a=>t(a),a=>{i[o]=a,--r||n(new AggregateError(i))}))})}));const G={awaits:0,echoes:0,id:0};var Io=0,zt=[],bn=0,sn=0,Uo=0;function Ie(e,t,n,r){var i=U,s=Object.create(i);s.parent=i,s.ref=0,s.global=!1,s.id=++Uo;var o=Ye.env;s.env=Lr?{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:qr(o.nthen,s),gthen:qr(o.gthen,s)}:{},t&&Q(s,t),++i.ref,s.finalize=function(){--this.parent.ref||this.parent.finalize()};var a=nt(s,e,n,r);return s.ref===0&&s.finalize(),a}function tt(){return G.id||(G.id=++Io),++G.awaits,G.echoes+=Fi,G.id}function we(){return!!G.awaits&&(--G.awaits==0&&(G.id=0),G.echoes=G.awaits*Fi,!0)}function Bt(e){return G.echoes&&e&&e.constructor===qt?(tt(),e.then(t=>(we(),t),t=>(we(),W(t)))):e}function xo(e){++sn,G.echoes&&--G.echoes!=0||(G.echoes=G.id=0),zt.push(U),Ue(e,!0)}function Ao(){var e=zt[zt.length-1];zt.pop(),Ue(e,!1)}function Ue(e,t){var n=U;if((t?!G.echoes||bn++&&e===U:!bn||--bn&&e===U)||zi(t?xo.bind(null,e):Ao),e!==U&&(U=e,n===Ye&&(Ye.env=Wi()),Lr)){var r=Ye.env.Promise,i=e.env;nn.then=i.nthen,r.prototype.then=i.gthen,(n.global||e.global)&&(Object.defineProperty(j,"Promise",i.PromiseProp),r.all=i.all,r.race=i.race,r.resolve=i.resolve,r.reject=i.reject,i.allSettled&&(r.allSettled=i.allSettled),i.any&&(r.any=i.any))}}function Wi(){var e=j.Promise;return Lr?{Promise:e,PromiseProp:Object.getOwnPropertyDescriptor(j,"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,r,i){var s=U;try{return Ue(e,!0),t(n,r,i)}finally{Ue(s,!1)}}function zi(e){ji.call($n,e)}function on(e,t,n,r){return typeof e!="function"?e:function(){var i=U;n&&tt(),Ue(t,!0);try{return e.apply(this,arguments)}finally{Ue(i,!1),r&&zi(we)}}}function qr(e,t){return function(n,r){return e.call(this,on(n,t),on(r,t))}}(""+ji).indexOf("[native code]")===-1&&(tt=we=T);const Vr="unhandledrejection";function Wr(e,t){var n;try{n=t.onuncatched(e)}catch{}if(n!==!1)try{var r,i={promise:t,reason:e};if(j.document&&document.createEvent?((r=document.createEvent("Event")).initEvent(Vr,!0,!0),Q(r,i)):j.CustomEvent&&Q(r=new CustomEvent(Vr,{detail:i}),i),r&&j.dispatchEvent&&(dispatchEvent(r),!j.PromiseRejectionEvent&&j.onunhandledrejection))try{j.onunhandledrejection(r)}catch{}le&&r&&!r.defaultPrevented&&console.warn(`Unhandled rejection: ${e.stack||e}`)}catch{}}var W=L.reject;function Jn(e,t,n,r){if(e.idbdb&&(e._state.openComplete||U.letThrough||e._vip)){var i=e._createTransaction(t,n,e._dbSchema);try{i.create(),e._state.PR1398_maxLoop=3}catch(s){return s.name===Er.InvalidState&&e.isOpen()&&--e._state.PR1398_maxLoop>0?(console.warn("Dexie: Need to reopen db"),e._close(),e.open().then(()=>Jn(e,t,n,r))):W(s)}return i._promise(t,(s,o)=>Ie(()=>(U.trans=i,r(s,o,i)))).then(s=>i._completion.then(()=>s))}if(e._state.openComplete)return W(new x.DatabaseClosed(e._state.dbOpenError));if(!e._state.isBeingOpened){if(!e._options.autoOpen)return W(new x.DatabaseClosed);e.open().catch(T)}return e._state.dbReadyPromise.then(()=>Jn(e,t,n,r))}const zr="3.2.7",De="￿",Qn=-1/0,ue="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",Hi="String expected.",ht=[],hn=typeof navigator<"u"&&/(MSIE|Trident|Edge)/.test(navigator.userAgent),Ro=hn,Co=hn,Gi=e=>!/(dexie\.js|dexie\.min\.js)/.test(e),fn="__dbnames",_n="readonly",Sn="readwrite";function Ke(e,t){return e?t?function(){return e.apply(this,arguments)&&t.apply(this,arguments)}:e:t}const Yi={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,r){const i=this._tx||U.trans,s=this.name;function o(l,c,u){if(!u.schema[s])throw new x.NotFound("Table "+s+" not part of transaction");return n(u.idbtrans,u)}const a=At();try{return i&&i.db===this.db?i===U.trans?i._promise(t,o,r):Ie(()=>i._promise(t,o,r),{trans:i,transless:U.transless||U}):Jn(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",r=>this.core.get({trans:r,key:t}).then(i=>this.hook.reading.fire(i))).then(n)}where(t){if(typeof t=="string")return new this.db.WhereClause(this,t);if(Y(t))return new this.db.WhereClause(this,`[${t.join("+")}]`);const n=$(t);if(n.length===1)return this.where(n[0]).equals(t[n[0]]);const r=this.schema.indexes.concat(this.schema.primKey).filter(c=>{if(c.compound&&n.every(u=>c.keyPath.indexOf(u)>=0)){for(let u=0;u<n.length;++u)if(n.indexOf(c.keyPath[u])===-1)return!1;return!0}return!1}).sort((c,u)=>c.keyPath.length-u.keyPath.length)[0];if(r&&this.db._maxKey!==De){const c=r.keyPath.slice(0,n.length);return this.where(c).equals(c.map(u=>t[u]))}!r&&le&&console.warn(`The query ${JSON.stringify(t)} on ${this.name} would benefit of a compound index [${n.join("+")}]`);const{idxByName:i}=this.schema,s=this.db._deps.indexedDB;function o(c,u){try{return s.cmp(c,u)===0}catch{return!1}}const[a,l]=n.reduce(([c,u],p)=>{const d=i[p],h=t[p];return[c||d,c||!d?Ke(u,d&&d.multi?g=>{const y=ge(g,p);return Y(y)&&y.some(w=>o(h,w))}:g=>o(h,ge(g,p))):u]},[null,null]);return a?this.where(a.name).equals(t[a.keyPath]).filter(l):r?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,Y(t)?`[${t.join("+")}]`:t))}reverse(){return this.toCollection().reverse()}mapToClass(t){this.schema.mappedClass=t;const n=r=>{if(!r)return r;const i=Object.create(t.prototype);for(var s in r)if(ne(r,s))try{i[s]=r[s]}catch{}return i};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){Q(this,t)})}add(t,n){const{auto:r,keyPath:i}=this.schema.primKey;let s=t;return i&&r&&(s=Mt(i)(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(i)try{ie(t,i,o)}catch{}return o})}update(t,n){if(typeof t!="object"||Y(t))return this.where(":id").equals(t).modify(n);{const r=ge(t,this.schema.primKey.keyPath);if(r===void 0)return W(new x.InvalidArgument("Given object does not contain its primary key"));try{typeof n!="function"?$(n).forEach(i=>{ie(t,i,n[i])}):n(t,{value:t,primKey:r})}catch{}return this.where(":id").equals(r).modify(n)}}put(t,n){const{auto:r,keyPath:i}=this.schema.primKey;let s=t;return i&&r&&(s=Mt(i)(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(i)try{ie(t,i,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:Yi})).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(r=>r.map(i=>this.hook.reading.fire(i))))}bulkAdd(t,n,r){const i=Array.isArray(n)?n:void 0,s=(r=r||(i?void 0:n))?r.allKeys:void 0;return this._trans("readwrite",o=>{const{auto:a,keyPath:l}=this.schema.primKey;if(l&&i)throw new x.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(i&&i.length!==t.length)throw new x.InvalidArgument("Arguments objects and keys must have the same length");const c=t.length;let u=l&&a?t.map(Mt(l)):t;return this.core.mutate({trans:o,type:"add",keys:i,values:u,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 ${c} operations failed`,g)})})}bulkPut(t,n,r){const i=Array.isArray(n)?n:void 0,s=(r=r||(i?void 0:n))?r.allKeys:void 0;return this._trans("readwrite",o=>{const{auto:a,keyPath:l}=this.schema.primKey;if(l&&i)throw new x.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(i&&i.length!==t.length)throw new x.InvalidArgument("Arguments objects and keys must have the same length");const c=t.length;let u=l&&a?t.map(Mt(l)):t;return this.core.mutate({trans:o,type:"put",keys:i,values:u,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 ${c} operations failed`,g)})})}bulkDelete(t){const n=t.length;return this._trans("readwrite",r=>this.core.mutate({trans:r,type:"delete",keys:t})).then(({numFailures:r,lastResult:i,failures:s})=>{if(r===0)return i;throw new dt(`${this.name}.bulkDelete(): ${r} of ${n} operations failed`,s)})}}function ft(e){var t={},n=function(o,a){if(a){for(var l=arguments.length,c=new Array(l-1);--l;)c[l-1]=arguments[l];return t[o].subscribe.apply(null,c),e}if(typeof o=="string")return t[o]};n.addEventType=s;for(var r=1,i=arguments.length;r<i;++r)s(arguments[r]);return n;function s(o,a,l){if(typeof o!="object"){var c;a||(a=Eo),l||(l=T);var u={subscribers:[],fire:l,subscribe:function(p){u.subscribers.indexOf(p)===-1&&(u.subscribers.push(p),u.fire=a(u.fire,p))},unsubscribe:function(p){u.subscribers=u.subscribers.filter(function(d){return d!==p}),u.fire=u.subscribers.reduce(a,l)}};return t[o]=n[o]=u,u}$(c=o).forEach(function(p){var d=c[p];if(Y(d))s(p,c[p][0],c[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){Ai(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 En(e,t){e.filter=Ke(e.filter,t)}function kn(e,t,n){var r=e.replayFilter;e.replayFilter=r?()=>Ke(r(),t()):t,e.justLimit=n&&!r}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 Hr(e,t,n){const r=Ht(e,t.schema);return t.openCursor({trans:n,values:!e.keysOnly,reverse:e.dir==="prev",unique:!!e.unique,query:{index:r,range:e.range}})}function Ft(e,t,n,r){const i=e.replayFilter?Ke(e.filter,e.replayFilter()):e.filter;if(e.or){const s={},o=(a,l,c)=>{if(!i||i(l,c,d=>l.stop(d),d=>l.fail(d))){var u=l.primaryKey,p=""+u;p==="[object ArrayBuffer]"&&(p=""+new Uint8Array(u)),ne(s,p)||(s[p]=!0,t(a,l,c))}};return Promise.all([e.or._iterate(o,n),Gr(Hr(e,r,n),e.algorithm,o,!e.keysOnly&&e.valueMapper)])}return Gr(Hr(e,r,n),Ke(e.algorithm,i),t,!e.keysOnly&&e.valueMapper)}function Gr(e,t,n,r){var i=K(r?(s,o,a)=>n(r(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=T},a=>{s.fail(a),o=T})||i(s.value,s,a=>o=a),o()})})}function J(e,t){try{const n=Yr(e),r=Yr(t);if(n!==r)return n==="Array"?1:r==="Array"?-1:n==="binary"?1:r==="binary"?-1:n==="string"?1:r==="string"?-1:n==="Date"?1:r!=="Date"?NaN:-1;switch(n){case"number":case"Date":case"string":return e>t?1:e<t?-1:0;case"binary":return function(i,s){const o=i.length,a=s.length,l=o<a?o:a;for(let c=0;c<l;++c)if(i[c]!==s[c])return i[c]<s[c]?-1:1;return o===a?0:o<a?-1:1}(Jr(e),Jr(t));case"Array":return function(i,s){const o=i.length,a=s.length,l=o<a?o:a;for(let c=0;c<l;++c){const u=J(i[c],s[c]);if(u!==0)return u}return o===a?0:o<a?-1:1}(e,t)}}catch{}return NaN}function Yr(e){const t=typeof e;if(t!=="object")return t;if(ArrayBuffer.isView(e))return"binary";const n=jn(e);return n==="ArrayBuffer"?"binary":n}function Jr(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 r=this._ctx;return r.error?r.table._trans(null,W.bind(null,r.error)):r.table._trans("readonly",t).then(n)}_write(t){var n=this._ctx;return n.error?n.table._trans(null,W.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),r=Object.create(this._ctx);return t&&Q(r,t),n._ctx=r,n}raw(){return this._ctx.valueMapper=null,this}each(t){var n=this._ctx;return this._read(r=>Ft(n,t,r,n.table.core))}count(t){return this._read(n=>{const r=this._ctx,i=r.table.core;if(Ve(r,!0))return i.count({trans:n,query:{index:Ht(r,i.schema),range:r.range}}).then(o=>Math.min(o,r.limit));var s=0;return Ft(r,()=>(++s,!1),n,i).then(()=>s)}).then(t)}sortBy(t,n){const r=t.split(".").reverse(),i=r[0],s=r.length-1;function o(c,u){return u?o(c[r[u]],u-1):c[i]}var a=this._ctx.dir==="next"?1:-1;function l(c,u){var p=o(c,s),d=o(u,s);return p<d?-a:p>d?a:0}return this.toArray(function(c){return c.sort(l)}).then(n)}toArray(t){return this._read(n=>{var r=this._ctx;if(r.dir==="next"&&Ve(r,!0)&&r.limit>0){const{valueMapper:i}=r,s=Ht(r,r.table.core.schema);return r.table.core.query({trans:n,limit:r.limit,values:!0,query:{index:s,range:r.range}}).then(({result:o})=>i?o.map(i):o)}{const i=[];return Ft(r,s=>i.push(s),n,r.table.core).then(()=>i)}},t)}offset(t){var n=this._ctx;return t<=0||(n.offset+=t,Ve(n)?kn(n,()=>{var r=t;return(i,s)=>r===0||(r===1?(--r,!1):(s(()=>{i.advance(r),r=0}),!1))}):kn(n,()=>{var r=t;return()=>--r<0})),this}limit(t){return this._ctx.limit=Math.min(this._ctx.limit,t),kn(this._ctx,()=>{var n=t;return function(r,i,s){return--n<=0&&i(s),n>=0}},!0),this}until(t,n){return En(this._ctx,function(r,i,s){return!t(r.value)||(i(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,r;return En(this._ctx,function(i){return t(i.value)}),n=this._ctx,r=t,n.isMatch=Ke(n.isMatch,r),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(r,i){t(i.key,i)})}eachUniqueKey(t){return this._ctx.unique="unique",this.eachKey(t)}eachPrimaryKey(t){var n=this._ctx;return n.keysOnly=!n.isMatch,this.each(function(r,i){t(i.primaryKey,i)})}keys(t){var n=this._ctx;n.keysOnly=!n.isMatch;var r=[];return this.each(function(i,s){r.push(s.key)}).then(function(){return r}).then(t)}primaryKeys(t){var n=this._ctx;if(n.dir==="next"&&Ve(n,!0)&&n.limit>0)return this._read(i=>{var s=Ht(n,n.table.core.schema);return n.table.core.query({trans:i,values:!1,limit:n.limit,query:{index:s,range:n.range}})}).then(({result:i})=>i).then(t);n.keysOnly=!n.isMatch;var r=[];return this.each(function(i,s){r.push(s.primaryKey)}).then(function(){return r}).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 r={};return En(this._ctx,function(i){var s=i.primaryKey.toString(),o=ne(r,s);return r[s]=!0,!o}),this}modify(t){var n=this._ctx;return this._write(r=>{var i;if(typeof t=="function")i=t;else{var s=$(t),o=s.length;i=function(y){for(var w=!1,f=0;f<o;++f){var m=s[f],b=t[m];ge(y,m)!==b&&(ie(y,m,b),w=!0)}return w}}const a=n.table.core,{outbound:l,extractKey:c}=a.schema.primaryKey,u=this.db._options.modifyChunkSize||200,p=[];let d=0;const h=[],g=(y,w)=>{const{failures:f,numFailures:m}=w;d+=y-m;for(let b of $(f))p.push(f[b])};return this.clone().primaryKeys().then(y=>{const w=f=>{const m=Math.min(u,y.length-f);return a.getMany({trans:r,keys:y.slice(f,f+m),cache:"immutable"}).then(b=>{const v=[],E=[],k=l?[]:null,_=[];for(let S=0;S<m;++S){const B=b[S],D={value:xt(B),primKey:y[f+S]};i.call(D,D.value,D)!==!1&&(D.value==null?_.push(y[f+S]):l||J(c(B),c(D.value))===0?(E.push(D.value),l&&k.push(y[f+S])):(_.push(y[f+S]),v.push(D.value)))}const A=Ve(n)&&n.limit===1/0&&(typeof t!="function"||t===Ln)&&{index:n.index,range:n.range};return Promise.resolve(v.length>0&&a.mutate({trans:r,type:"add",values:v}).then(S=>{for(let B in S.failures)_.splice(parseInt(B),1);g(v.length,S)})).then(()=>(E.length>0||A&&typeof t=="object")&&a.mutate({trans:r,type:"put",keys:k,values:E,criteria:A,changeSpec:typeof t!="function"&&t}).then(S=>g(E.length,S))).then(()=>(_.length>0||A&&t===Ln)&&a.mutate({trans:r,type:"delete",keys:_,criteria:A}).then(S=>g(_.length,S))).then(()=>y.length>f+m&&w(f+u))})};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(r=>{const{primaryKey:i}=t.table.core.schema,s=n;return t.table.core.count({trans:r,query:{index:i,range:s}}).then(o=>t.table.core.mutate({trans:r,type:"deleteRange",range:s}).then(({failures:a,lastResult:l,results:c,numFailures:u})=>{if(u)throw new tn("Could not delete some values",Object.keys(a).map(p=>a[p]),o-u);return o-u}))}):this.modify(Ln)}}const Ln=(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 Z(e,t,n){var r=e instanceof Qi?new e.Collection(e):e;return r._ctx.error=n?new n(t):new TypeError(t),r}function We(e){return new e.Collection(e,()=>Ji("")).limit(0)}function Bo(e,t,n,r,i,s){for(var o=Math.min(e.length,r.length),a=-1,l=0;l<o;++l){var c=t[l];if(c!==r[l])return i(e[l],n[l])<0?e.substr(0,l)+n[l]+n.substr(l+1):i(e[l],r[l])<0?e.substr(0,l)+r[l]+n.substr(l+1):a>=0?e.substr(0,a)+t[a]+n.substr(a+1):null;i(e[l],c)<0&&(a=l)}return o<r.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)+r[a]+n.substr(a+1)}function jt(e,t,n,r){var i,s,o,a,l,c,u,p=n.length;if(!n.every(y=>typeof y=="string"))return Z(e,Hi);function d(y){i=function(f){return f==="next"?m=>m.toUpperCase():m=>m.toLowerCase()}(y),s=function(f){return f==="next"?m=>m.toLowerCase():m=>m.toUpperCase()}(y),o=y==="next"?Po:To;var w=n.map(function(f){return{lower:s(f),upper:i(f)}}).sort(function(f,m){return o(f.lower,m.lower)});a=w.map(function(f){return f.upper}),l=w.map(function(f){return f.lower}),c=y,u=y==="next"?"":r}d("next");var h=new e.Collection(e,()=>be(a[0],l[p-1]+r));h._ondirectionchange=function(y){d(y)};var g=0;return h._addAlgorithm(function(y,w,f){var m=y.key;if(typeof m!="string")return!1;var b=s(m);if(t(b,l,g))return!0;for(var v=null,E=g;E<p;++E){var k=Bo(m,b,a[E],l[E],o,c);k===null&&v===null?g=E+1:(v===null||o(v,k)>0)&&(v=k)}return w(v!==null?function(){y.continue(v+u)}:f),!1}),h}function be(e,t,n,r){return{type:2,lower:e,upper:t,lowerOpen:n,upperOpen:r}}function Ji(e){return{type:1,lower:e,upper:e}}class Qi{get Collection(){return this._ctx.table.db.Collection}between(t,n,r,i){r=r!==!1,i=i===!0;try{return this._cmp(t,n)>0||this._cmp(t,n)===0&&(r||i)&&(!r||!i)?We(this):new this.Collection(this,()=>be(t,n,!r,!i))}catch{return Z(this,ue)}}equals(t){return t==null?Z(this,ue):new this.Collection(this,()=>Ji(t))}above(t){return t==null?Z(this,ue):new this.Collection(this,()=>be(t,void 0,!0))}aboveOrEqual(t){return t==null?Z(this,ue):new this.Collection(this,()=>be(t,void 0,!1))}below(t){return t==null?Z(this,ue):new this.Collection(this,()=>be(void 0,t,!1,!0))}belowOrEqual(t){return t==null?Z(this,ue):new this.Collection(this,()=>be(void 0,t))}startsWith(t){return typeof t!="string"?Z(this,Hi):this.between(t,t+De,!0,!0)}startsWithIgnoreCase(t){return t===""?this.startsWith(t):jt(this,(n,r)=>n.indexOf(r[0])===0,[t],De)}equalsIgnoreCase(t){return jt(this,(n,r)=>n===r[0],[t],"")}anyOfIgnoreCase(){var t=he.apply(ze,arguments);return t.length===0?We(this):jt(this,(n,r)=>r.indexOf(n)!==-1,t,"")}startsWithAnyOfIgnoreCase(){var t=he.apply(ze,arguments);return t.length===0?We(this):jt(this,(n,r)=>r.some(i=>n.indexOf(i)===0),t,De)}anyOf(){const t=he.apply(ze,arguments);let n=this._cmp;try{t.sort(n)}catch{return Z(this,ue)}if(t.length===0)return We(this);const r=new this.Collection(this,()=>be(t[0],t[t.length-1]));r._ondirectionchange=s=>{n=s==="next"?this._ascending:this._descending,t.sort(n)};let i=0;return r._addAlgorithm((s,o,a)=>{const l=s.key;for(;n(l,t[i])>0;)if(++i,i===t.length)return o(a),!1;return n(l,t[i])===0||(o(()=>{s.continue(t[i])}),!1)}),r}notEqual(t){return this.inAnyRange([[Qn,t],[t,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})}noneOf(){const t=he.apply(ze,arguments);if(t.length===0)return new this.Collection(this);try{t.sort(this._ascending)}catch{return Z(this,ue)}const n=t.reduce((r,i)=>r?r.concat([[r[r.length-1][1],i]]):[[Qn,i]],null);return n.push([t[t.length-1],this.db._maxKey]),this.inAnyRange(n,{includeLowers:!1,includeUppers:!1})}inAnyRange(t,n){const r=this._cmp,i=this._ascending,s=this._descending,o=this._min,a=this._max;if(t.length===0)return We(this);if(!t.every(m=>m[0]!==void 0&&m[1]!==void 0&&i(m[0],m[1])<=0))return Z(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,c=n&&n.includeUppers===!0;let u,p=i;function d(m,b){return p(m[0],b[0])}try{u=t.reduce(function(m,b){let v=0,E=m.length;for(;v<E;++v){const k=m[v];if(r(b[0],k[1])<0&&r(b[1],k[0])>0){k[0]=o(k[0],b[0]),k[1]=a(k[1],b[1]);break}}return v===E&&m.push(b),m},[]),u.sort(d)}catch{return Z(this,ue)}let h=0;const g=c?m=>i(m,u[h][1])>0:m=>i(m,u[h][1])>=0,y=l?m=>s(m,u[h][0])>0:m=>s(m,u[h][0])>=0;let w=g;const f=new this.Collection(this,()=>be(u[0][0],u[u.length-1][1],!l,!c));return f._ondirectionchange=m=>{m==="next"?(w=g,p=i):(w=y,p=s),u.sort(d)},f._addAlgorithm((m,b,v)=>{for(var E=m.key;w(E);)if(++h,h===u.length)return b(v),!1;return!!function(k){return!g(k)&&!y(k)}(E)||(this._cmp(E,u[h][1])===0||this._cmp(E,u[h][0])===0||b(()=>{p===i?m.continue(u[h][0]):m.continue(u[h][1])}),!1)}),f}startsWithAnyOf(){const t=he.apply(ze,arguments);return t.every(n=>typeof n=="string")?t.length===0?We(this):this.inAnyRange(t.map(n=>[n,n+De])):Z(this,"startsWithAnyOf() only works with strings")}}function se(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",Ee="x-storagemutated-1",xe=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,r=this.db._state.dbOpenError;if(at(!this.idbtrans),!t&&!n)switch(r&&r.name){case"DatabaseClosedError":throw new x.DatabaseClosed(r);case"MissingAPIError":throw new x.MissingAPI(r.message,r);default:throw new x.OpenFailed(r)}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(i=>{Et(i),this._reject(t.error)}),t.onabort=K(i=>{Et(i),this.active&&this._reject(new x.Abort(t.error)),this.active=!1,this.on("abort").fire(i)}),t.oncomplete=K(()=>{this.active=!1,this._resolve(),"mutatedParts"in t&&xe.storagemutated.fire(t.mutatedParts)}),this}_promise(t,n,r){if(t==="readwrite"&&this.mode!=="readwrite")return W(new x.ReadOnly("Transaction is readonly"));if(!this.active)return W(new x.TransactionInactive);if(this._locked())return new L((s,o)=>{this._blockedFuncs.push([()=>{this._promise(t,n,r).then(s,o)},U])});if(r)return Ie(()=>{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 i=new L((s,o)=>{var a=n(s,o,this);a&&a.then&&a.then(s,o)});return i._lib=!0,i}_root(){return this.parent?this.parent._root():this}waitFor(t){var n=this._root();const r=L.resolve(t);if(n._waitingFor)n._waitingFor=n._waitingFor.then(()=>r);else{n._waitingFor=r,n._waitingQueue=[];var i=n.idbtrans.objectStore(n.storeNames[0]);(function o(){for(++n._spinCount;n._waitingQueue.length;)n._waitingQueue.shift()();n._waitingFor&&(i.get(-1/0).onsuccess=o)})()}var s=n._waitingFor;return new L((o,a)=>{r.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(ne(n,t))return n[t];const r=this.schema[t];if(!r)throw new x.NotFound("Table "+t+" not part of transaction");const i=new this.db.Table(t,r,this);return i.core=this.db.core.table(t),n[t]=i,i}}function Xn(e,t,n,r,i,s,o){return{name:e,keyPath:t,unique:n,multi:r,auto:i,compound:s,src:(n&&!o?"&":"")+(r?"*":"")+(i?"++":"")+Xi(t)}}function Xi(e){return typeof e=="string"?e:e?"["+[].join.call(e,"+")+"]":""}function Zi(e,t,n){return{name:e,primKey:t,indexes:n,mappedClass:null,idxByName:Ri(n,r=>[r.name,r])}}let Lt=e=>{try{return e.only([[]]),Lt=()=>[[]],[[]]}catch{return Lt=()=>De,De}};function Zn(e){return e==null?()=>{}:typeof e=="string"?function(t){return t.split(".").length===1?r=>r[t]:r=>ge(r,t)}(e):t=>ge(t,e)}function Qr(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 r(l){if(l.type===3)return null;if(l.type===4)throw new Error("Cannot convert never type to IDBKeyRange");const{lower:c,upper:u,lowerOpen:p,upperOpen:d}=l;return c===void 0?u===void 0?null:t.upperBound(u,!!d):u===void 0?t.lowerBound(c,!!p):t.bound(c,u,!!p,!!d)}const{schema:i,hasGetAll:s}=function(l,c){const u=Qr(l.objectStoreNames);return{schema:{name:l.name,tables:u.map(p=>c.objectStore(p)).map(p=>{const{keyPath:d,autoIncrement:h}=p,g=Y(d),y=d==null,w={},f={name:p.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:y,compound:g,keyPath:d,autoIncrement:h,unique:!0,extractKey:Zn(d)},indexes:Qr(p.indexNames).map(m=>p.index(m)).map(m=>{const{name:b,unique:v,multiEntry:E,keyPath:k}=m,_={name:b,compound:Y(k),keyPath:k,unique:v,multiEntry:E,extractKey:Zn(k)};return w[mt(k)]=_,_}),getIndexByKeyPath:m=>w[mt(m)]};return w[":id"]=f.primaryKey,d!=null&&(w[mt(d)]=f.primaryKey),f})},hasGetAll:u.length>0&&"getAll"in c.objectStore(u[0])&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604)}}(e,n),o=i.tables.map(l=>function(c){const u=c.name;return{name:u,schema:c,mutate:function({trans:p,type:d,keys:h,values:g,range:y}){return new Promise((w,f)=>{w=K(w);const m=p.objectStore(u),b=m.keyPath==null,v=d==="put"||d==="add";if(!v&&d!=="delete"&&d!=="deleteRange")throw new Error("Invalid operation type: "+d);const{length:E}=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(E===0)return w({numFailures:0,failures:{},results:[],lastResult:void 0});let k;const _=[],A=[];let S=0;const B=q=>{++S,Et(q)};if(d==="deleteRange"){if(y.type===4)return w({numFailures:S,failures:A,results:[],lastResult:void 0});y.type===3?_.push(k=m.clear()):_.push(k=m.delete(r(y)))}else{const[q,V]=v?b?[g,h]:[g,null]:[h,null];if(v)for(let F=0;F<E;++F)_.push(k=V&&V[F]!==void 0?m[d](q[F],V[F]):m[d](q[F])),k.onerror=B;else for(let F=0;F<E;++F)_.push(k=m[d](q[F])),k.onerror=B}const D=q=>{const V=q.target.result;_.forEach((F,ce)=>F.error!=null&&(A[ce]=F.error)),w({numFailures:S,failures:A,results:d==="delete"?h:_.map(F=>F.result),lastResult:V})};k.onerror=q=>{B(q),D(q)},k.onsuccess=D})},getMany:({trans:p,keys:d})=>new Promise((h,g)=>{h=K(h);const y=p.objectStore(u),w=d.length,f=new Array(w);let m,b=0,v=0;const E=_=>{const A=_.target;f[A._pos]=A.result,++v===b&&h(f)},k=se(g);for(let _=0;_<w;++_)d[_]!=null&&(m=y.get(d[_]),m._pos=_,m.onsuccess=E,m.onerror=k,++b);b===0&&h(f)}),get:({trans:p,key:d})=>new Promise((h,g)=>{h=K(h);const y=p.objectStore(u).get(d);y.onsuccess=w=>h(w.target.result),y.onerror=se(g)}),query:function(p){return d=>new Promise((h,g)=>{h=K(h);const{trans:y,values:w,limit:f,query:m}=d,b=f===1/0?void 0:f,{index:v,range:E}=m,k=y.objectStore(u),_=v.isPrimaryKey?k:k.index(v.name),A=r(E);if(f===0)return h({result:[]});if(p){const S=w?_.getAll(A,b):_.getAllKeys(A,b);S.onsuccess=B=>h({result:B.target.result}),S.onerror=se(g)}else{let S=0;const B=w||!("openKeyCursor"in _)?_.openCursor(A):_.openKeyCursor(A),D=[];B.onsuccess=q=>{const V=B.result;return V?(D.push(w?V.value:V.primaryKey),++S===f?h({result:D}):void V.continue()):h({result:D})},B.onerror=se(g)}})}(s),openCursor:function({trans:p,values:d,query:h,reverse:g,unique:y}){return new Promise((w,f)=>{w=K(w);const{index:m,range:b}=h,v=p.objectStore(u),E=m.isPrimaryKey?v:v.index(m.name),k=g?y?"prevunique":"prev":y?"nextunique":"next",_=d||!("openKeyCursor"in E)?E.openCursor(r(b),k):E.openKeyCursor(r(b),k);_.onerror=se(f),_.onsuccess=K(A=>{const S=_.result;if(!S)return void w(null);S.___id=++Fo,S.done=!1;const B=S.continue.bind(S);let D=S.continuePrimaryKey;D&&(D=D.bind(S));const q=S.advance.bind(S),V=()=>{throw new Error("Cursor not stopped")};S.trans=p,S.stop=S.continue=S.continuePrimaryKey=S.advance=()=>{throw new Error("Cursor not started")},S.fail=K(f),S.next=function(){let F=1;return this.start(()=>F--?this.continue():this.stop()).then(()=>this)},S.start=F=>{const ce=new Promise((H,Ae)=>{H=K(H),_.onerror=se(Ae),S.fail=Ae,S.stop=it=>{S.stop=S.continue=S.continuePrimaryKey=S.advance=V,H(it)}}),M=()=>{if(_.result)try{F()}catch(H){S.fail(H)}else S.done=!0,S.start=()=>{throw new Error("Cursor behind last entry")},S.stop()};return _.onsuccess=K(H=>{_.onsuccess=M,M()}),S.continue=B,S.continuePrimaryKey=D,S.advance=q,M(),ce},w(S)},f)})},count({query:p,trans:d}){const{index:h,range:g}=p;return new Promise((y,w)=>{const f=d.objectStore(u),m=h.isPrimaryKey?f:f.index(h.name),b=r(g),v=b?m.count(b):m.count();v.onsuccess=K(E=>y(E.target.result)),v.onerror=se(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:i}}function er({_novip:e},t){const n=t.db,r=function(i,s,{IDBKeyRange:o,indexedDB:a},l){return{dbcore:function(u,p){return p.reduce((d,{create:h})=>({...d,...h(d)}),u)}(jo(s,o,l),i.dbcore)}}(e._middlewares,n,e._deps,t);e.core=r.dbcore,e.tables.forEach(i=>{const s=i.name;e.core.schema.tables.some(o=>o.name===s)&&(i.core=e.core.table(s),e[s]instanceof e.Table&&(e[s].core=i.core))})}function an({_novip:e},t,n,r){n.forEach(i=>{const s=r[i];t.forEach(o=>{const a=br(o,i);(!a||"value"in a&&a.value===void 0)&&(o===e.Transaction.prototype||o instanceof e.Transaction?ye(o,i,{get(){return this.table(i)},set(l){Ui(this,i,{value:l,writable:!0,configurable:!0,enumerable:!0})}}):o[i]=new e.Table(i,s))})})}function tr({_novip:e},t){t.forEach(n=>{for(let r in n)n[r]instanceof e.Table&&delete n[r]})}function Ko(e,t){return e._cfg.version-t._cfg.version}function No(e,t,n,r){const i=e._dbSchema,s=e._createTransaction("readwrite",e._storeNames,i);s.create(n),s._completion.catch(r);const o=s._reject.bind(s),a=U.transless||U;Ie(()=>{U.trans=s,U.transless=a,t===0?($(i).forEach(l=>{In(n,l,i[l].primKey,i[l].indexes)}),er(e,n),L.follow(()=>e.on.populate.fire(s)).catch(o)):function({_novip:l},c,u,p){const d=[],h=l._versions;let g=l._dbSchema=rr(l,l.idbdb,p),y=!1;const w=h.filter(m=>m._cfg.version>=c);function f(){return d.length?L.resolve(d.shift()(u.idbtrans)).then(f):L.resolve()}return w.forEach(m=>{d.push(()=>{const b=g,v=m._cfg.dbschema;ir(l,b,p),ir(l,v,p),g=l._dbSchema=v;const E=es(b,v);E.add.forEach(_=>{In(p,_[0],_[1].primKey,_[1].indexes)}),E.change.forEach(_=>{if(_.recreate)throw new x.Upgrade("Not yet support for changing primary key");{const A=p.objectStore(_.name);_.add.forEach(S=>nr(A,S)),_.change.forEach(S=>{A.deleteIndex(S.name),nr(A,S)}),_.del.forEach(S=>A.deleteIndex(S))}});const k=m._cfg.contentUpgrade;if(k&&m._cfg.version>c){er(l,p),u._memoizedTables={},y=!0;let _=Ci(v);E.del.forEach(D=>{_[D]=b[D]}),tr(l,[l.Transaction.prototype]),an(l,[l.Transaction.prototype],$(_),_),u.schema=_;const A=_r(k);let S;A&&tt();const B=L.follow(()=>{if(S=k(u),S&&A){var D=we.bind(null,null);S.then(D,D)}});return S&&typeof S.then=="function"?L.resolve(S):B.then(()=>S)}}),d.push(b=>{(!y||!Ro)&&function(v,E){[].slice.call(E.db.objectStoreNames).forEach(k=>v[k]==null&&E.db.deleteObjectStore(k))}(m._cfg.dbschema,b),tr(l,[l.Transaction.prototype]),an(l,[l.Transaction.prototype],l._storeNames,l._dbSchema),u.schema=l._dbSchema})}),f().then(()=>{var m,b;b=p,$(m=g).forEach(v=>{b.db.objectStoreNames.contains(v)||In(b,v,m[v].primKey,m[v].indexes)})})}(e,t,s,n).catch(o)})}function es(e,t){const n={del:[],add:[],change:[]};let r;for(r in e)t[r]||n.del.push(r);for(r in t){const i=e[r],s=t[r];if(i){const o={name:r,def:s,recreate:!1,del:[],add:[],change:[]};if(""+(i.primKey.keyPath||"")!=""+(s.primKey.keyPath||"")||i.primKey.auto!==s.primKey.auto&&!hn)o.recreate=!0,n.change.push(o);else{const a=i.idxByName,l=s.idxByName;let c;for(c in a)l[c]||o.del.push(c);for(c in l){const u=a[c],p=l[c];u?u.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([r,s])}return n}function In(e,t,n,r){const i=e.db.createObjectStore(t,n.keyPath?{keyPath:n.keyPath,autoIncrement:n.auto}:{autoIncrement:n.auto});return r.forEach(s=>nr(i,s)),i}function nr(e,t){e.createIndex(t.name,t.keyPath,{unique:t.unique,multiEntry:t.multi})}function rr(e,t,n){const r={};return en(t.objectStoreNames,0).forEach(i=>{const s=n.objectStore(i);let o=s.keyPath;const a=Xn(Xi(o),o||"",!1,!1,!!s.autoIncrement,o&&typeof o!="string",!0),l=[];for(let u=0;u<s.indexNames.length;++u){const p=s.index(s.indexNames[u]);o=p.keyPath;var c=Xn(p.name,o,!!p.unique,!!p.multiEntry,!1,o&&typeof o!="string",!1);l.push(c)}r[i]=Zi(i,a,l)}),r}function ir({_novip:e},t,n){const r=n.db.objectStoreNames;for(let i=0;i<r.length;++i){const s=r[i],o=n.objectStore(s);e._hasGetAll="getAll"in o;for(let a=0;a<o.indexNames.length;++a){const l=o.indexNames[a],c=o.index(l).keyPath,u=typeof c=="string"?c:"["+en(c).join("+")+"]";if(t[s]){const p=t[s].idxByName[u];p&&(p.name=l,delete t[s].idxByName[u],t[s].idxByName[l]=p)}}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&j.WorkerGlobalScope&&j instanceof j.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(e._hasGetAll=!1)}class $o{_parseStoresSpec(t,n){$(t).forEach(r=>{if(t[r]!==null){var i=t[r].split(",").map((o,a)=>{const l=(o=o.trim()).replace(/([&*]|\+\+)/g,""),c=/^\[/.test(l)?l.match(/^\[(.*)\]$/)[1].split("+"):l;return Xn(l,c||null,/\&/.test(o),/\*/.test(o),/\+\+/.test(o),Y(c),a===0)}),s=i.shift();if(s.multi)throw new x.Schema("Primary key cannot be multi-valued");i.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[r]=Zi(r,s,i)}})}stores(t){const n=this.db;this._cfg.storesSource=this._cfg.storesSource?Q(this._cfg.storesSource,t):t;const r=n._versions,i={};let s={};return r.forEach(o=>{Q(i,o._cfg.storesSource),s=o._cfg.dbschema={},o._parseStoresSpec(i,s)}),n._dbSchema=s,tr(n,[n._allTables,n,n.Transaction.prototype]),an(n,[n._allTables,n,n.Transaction.prototype,this._cfg.tables],$(s),s),n._storeNames=$(s),this}upgrade(t){return this._cfg.contentUpgrade=kr(this._cfg.contentUpgrade||T,t),this}}function xr(e,t){let n=e._dbNamesDB;return n||(n=e._dbNamesDB=new Me(fn,{addons:[],indexedDB:e,IDBKeyRange:t}),n.version(1).stores({dbnames:"name"})),n.table("dbnames")}function Ar(e){return e&&typeof e.databases=="function"}function sr(e){return Ie(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?W(t.dbOpenError):e);le&&(t.openCanceller._stackHolder=qe()),t.isBeingOpened=!0,t.dbOpenError=null,t.openComplete=!1;const r=t.openCanceller;function i(){if(t.openCanceller!==r)throw new x.DatabaseClosed("db.open() was cancelled")}let s=t.dbReadyResolve,o=null,a=!1;const l=()=>new L((c,u)=>{if(i(),!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=se(u),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(()=>{u(new x.NoSuchDatabase(`Database ${p} doesnt exist`))})}else{o.onerror=se(u);var g=h.oldVersion>Math.pow(2,62)?0:h.oldVersion;a=g<1,e._novip.idbdb=d.result,No(e,g/10,o,u)}},u),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:f},m,b){f.verno=m.version/10;const v=f._dbSchema=rr(0,m,b);f._storeNames=en(m.objectStoreNames,0),an(f,[f._allTables],$(v),v)}(e,h,w):(ir(e,e._dbSchema,w),function(f,m){const b=es(rr(0,f.idbdb,m),f._dbSchema);return!(b.add.length||b.change.some(v=>v.add.length||v.change.length))}(e,w)||console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.")),er(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:f},m){!Ar(w)&&m!==fn&&xr(w,f).put({name:m}).catch(T)}(e._deps,p),c()},u)}).catch(c=>c&&c.name==="UnknownError"&&t.PR1398_maxLoop>0?(t.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),l()):L.reject(c));return L.race([r,(typeof navigator>"u"?L.resolve():qo()).then(l)]).then(()=>(i(),t.onReadyBeingFired=[],L.resolve(sr(()=>e.on.ready.fire(e.vip))).then(function c(){if(t.onReadyBeingFired.length>0){let u=t.onReadyBeingFired.reduce(kr,T);return t.onReadyBeingFired=[],L.resolve(sr(()=>u(e.vip))).then(c)}}))).finally(()=>{t.onReadyBeingFired=null,t.isBeingOpened=!1}).then(()=>e).catch(c=>{t.dbOpenError=c;try{o&&o.abort()}catch{}return r===t.openCanceller&&e._close(),W(c)}).finally(()=>{t.openComplete=!0,s()})}function or(e){var t=s=>e.next(s),n=i(t),r=i(s=>e.throw(s));function i(s){return o=>{var a=s(o),l=a.value;return a.done?l:l&&typeof l.then=="function"?l.then(n,r):Y(l)?Promise.all(l).then(n,r):n(l)}}return i(t)()}function Wo(e,t,n){var r=arguments.length;if(r<2)throw new x.InvalidArgument("Too few arguments");for(var i=new Array(r-1);--r;)i[r-1]=arguments[r];return n=i.pop(),[e,Oi(i),n]}function ts(e,t,n,r,i){return L.resolve().then(()=>{const s=U.transless||U,o=e._createTransaction(t,n,e._dbSchema,r),a={trans:o,transless:s};if(r)o.idbtrans=r.idbtrans;else try{o.create(),e._state.PR1398_maxLoop=3}catch(p){return p.name===Er.InvalidState&&e.isOpen()&&--e._state.PR1398_maxLoop>0?(console.warn("Dexie: Need to reopen db"),e._close(),e.open().then(()=>ts(e,t,n,null,i))):W(p)}const l=_r(i);let c;l&&tt();const u=L.follow(()=>{if(c=i.call(o,o),c)if(l){var p=we.bind(null,null);c.then(p,p)}else typeof c.next=="function"&&typeof c.throw=="function"&&(c=or(c))},a);return(c&&typeof c.then=="function"?L.resolve(c).then(p=>o.active?p:W(new x.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))):u.then(()=>c)).then(p=>(r&&o._resolve(),o._completion.then(()=>p))).catch(p=>(o._reject(p),W(p)))})}function Kt(e,t,n){const r=Y(e)?e.slice():[e];for(let i=0;i<n;++i)r.push(t);return r}const zo={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(e){return{...e,table(t){const n=e.table(t),{schema:r}=n,i={},s=[];function o(u,p,d){const h=mt(u),g=i[h]=i[h]||[],y=u==null?0:typeof u=="string"?1:u.length,w=p>0,f={...d,isVirtual:w,keyTail:p,keyLength:y,extractKey:Zn(u),unique:!w&&d.unique};return g.push(f),f.isPrimaryKey||s.push(f),y>1&&o(y===2?u[0]:u.slice(0,y-1),p+1,d),g.sort((m,b)=>m.keyTail-b.keyTail),f}const a=o(r.primaryKey.keyPath,0,r.primaryKey);i[":id"]=[a];for(const u of r.indexes)o(u.keyPath,0,u);function l(u){const p=u.query.index;return p.isVirtual?{...u,query:{index:p,range:(d=u.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})}}:u;var d,h}return{...n,schema:{...r,primaryKey:a,indexes:s,getIndexByKeyPath:function(u){const p=i[mt(u)];return p&&p[0]}},count:u=>n.count(l(u)),query:u=>n.query(l(u)),openCursor(u){const{keyTail:p,isVirtual:d,keyLength:h}=u.query.index;return d?n.openCursor(l(u)).then(g=>g&&function(y){return Object.create(y,{continue:{value:function(f){f!=null?y.continue(Kt(f,u.reverse?e.MAX_KEY:e.MIN_KEY,p)):u.unique?y.continue(y.key.slice(0,h).concat(u.reverse?e.MIN_KEY:e.MAX_KEY,p)):y.continue()}},continuePrimaryKey:{value(f,m){y.continuePrimaryKey(Kt(f,e.MAX_KEY,p),m)}},primaryKey:{get:()=>y.primaryKey},key:{get(){const f=y.key;return h===1?f[0]:f.slice(0,h)}},value:{get:()=>y.value}})}(g)):n.openCursor(u)}}}}}};function Rr(e,t,n,r){return n=n||{},r=r||"",$(e).forEach(i=>{if(ne(t,i)){var s=e[i],o=t[i];if(typeof s=="object"&&typeof o=="object"&&s&&o){const a=jn(s);a!==jn(o)?n[r+i]=t[i]:a==="Object"?Rr(s,o,n,r+i+"."):s!==o&&(n[r+i]=t[i])}else s!==o&&(n[r+i]=t[i])}else n[r+i]=void 0}),$(t).forEach(i=>{ne(e,i)||(n[r+i]=t[i])}),n}const Ho={stack:"dbcore",name:"HooksMiddleware",level:2,create:e=>({...e,table(t){const n=e.table(t),{primaryKey:r}=n.schema;return{...n,mutate(s){const o=U.trans,{deleting:a,creating:l,updating:c}=o.table(t).hook;switch(s.type){case"add":if(l.fire===T)break;return o._promise("readwrite",()=>u(s),!0);case"put":if(l.fire===T&&c.fire===T)break;return o._promise("readwrite",()=>u(s),!0);case"delete":if(a.fire===T)break;return o._promise("readwrite",()=>u(s),!0);case"deleteRange":if(a.fire===T)break;return o._promise("readwrite",()=>function(d){return p(d.trans,d.range,1e4)}(s),!0)}return n.mutate(s);function u(d){const h=U.trans,g=d.keys||function(y,w){return w.type==="delete"?w.keys:w.keys||w.values.map(y.extractKey)}(r,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,f){return w.type==="add"?Promise.resolve([]):y.getMany({trans:w.trans,keys:f,cache:"immutable"})}(n,d,g).then(y=>{const w=g.map((f,m)=>{const b=y[m],v={onerror:null,onsuccess:null};if(d.type==="delete")a.fire.call(v,f,b,h);else if(d.type==="add"||b===void 0){const E=l.fire.call(v,f,d.values[m],h);f==null&&E!=null&&(f=E,d.keys[m]=f,r.outbound||ie(d.values[m],r.keyPath,f))}else{const E=Rr(b,d.values[m]),k=c.fire.call(v,E,f,b,h);if(k){const _=d.values[m];Object.keys(k).forEach(A=>{ne(_,A)?_[A]=k[A]:ie(_,A,k[A])})}}return v});return n.mutate(d).then(({failures:f,results:m,numFailures:b,lastResult:v})=>{for(let E=0;E<g.length;++E){const k=m?m[E]:g[E],_=w[E];k==null?_.onerror&&_.onerror(f[E]):_.onsuccess&&_.onsuccess(d.type==="put"&&y[E]?d.values[E]:k)}return{failures:f,results:m,numFailures:b,lastResult:v}}).catch(f=>(w.forEach(m=>m.onerror&&m.onerror(f)),Promise.reject(f)))})}function p(d,h,g){return n.query({trans:d,values:!1,query:{index:r,range:h},limit:g}).then(({result:y})=>u({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 ns(e,t,n){try{if(!t||t.keys.length<e.length)return null;const r=[];for(let i=0,s=0;i<t.keys.length&&s<e.length;++i)J(t.keys[i],e[s])===0&&(r.push(n?xt(t.values[i]):t.values[i]),++s);return r.length===e.length?r:null}catch{return null}}const Go={stack:"dbcore",level:-1,create:e=>({table:t=>{const n=e.table(t);return{...n,getMany:r=>{if(!r.cache)return n.getMany(r);const i=ns(r.keys,r.trans._cache,r.cache==="clone");return i?L.resolve(i):n.getMany(r).then(s=>(r.trans._cache={keys:r.keys,values:r.cache==="clone"?xt(s):s},s))},mutate:r=>(r.type!=="add"&&(r.trans._cache=null),n.mutate(r))}}})};function Cr(e){return!("from"in e)}const de=function(e,t){if(!this){const n=new de;return e&&"d"in e&&Q(n,e),n}Q(this,arguments.length?{d:1,from:e,to:arguments.length>1?t:e}:{d:0})};function It(e,t,n){const r=J(t,n);if(isNaN(r))return;if(r>0)throw RangeError();if(Cr(e))return Q(e,{from:t,to:n,d:1});const i=e.l,s=e.r;if(J(n,e.from)<0)return i?It(i,t,n):e.l={from:t,to:n,d:1,l:null,r:null},Xr(e);if(J(t,e.to)>0)return s?It(s,t,n):e.r={from:t,to:n,d:1,l:null,r:null},Xr(e);J(t,e.from)<0&&(e.from=t,e.l=null,e.d=s?s.d+1:1),J(n,e.to)>0&&(e.to=n,e.r=null,e.d=e.l?e.l.d+1:1);const o=!e.r;i&&!e.l&&ln(e,i),s&&o&&ln(e,s)}function ln(e,t){Cr(t)||function n(r,{from:i,to:s,l:o,r:a}){It(r,i,s),o&&n(r,o),a&&n(r,a)}(e,t)}function Yo(e,t){const n=ar(t);let r=n.next();if(r.done)return!1;let i=r.value;const s=ar(e);let o=s.next(i.from),a=o.value;for(;!r.done&&!o.done;){if(J(a.from,i.to)<=0&&J(a.to,i.from)>=0)return!0;J(i.from,a.from)<0?i=(r=n.next(a.from)).value:a=(o=s.next(i.from)).value}return!1}function ar(e){let t=Cr(e)?null:{s:0,n:e};return{next(n){const r=arguments.length>0;for(;t;)switch(t.s){case 0:if(t.s=1,r)for(;t.n.l&&J(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,!r||J(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 Xr(e){var t,n;const r=(((t=e.r)===null||t===void 0?void 0:t.d)||0)-(((n=e.l)===null||n===void 0?void 0:n.d)||0),i=r>1?"r":r<-1?"l":"";if(i){const s=i==="r"?"l":"r",o={...e},a=e[i];e.from=a.from,e.to=a.to,e[i]=a[i],o[i]=a[s],e[s]=o,o.d=Zr(o)}e.d=Zr(e)}function Zr({r:e,l:t}){return(e?t?Math.max(e.d,t.d):e.d:t?t.d:0)+1}Xe(de.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},[Kn](){return ar(this)}});const Jo={stack:"dbcore",level:0,create:e=>{const t=e.schema.name,n=new de(e.MIN_KEY,e.MAX_KEY);return{...e,table:r=>{const i=e.table(r),{schema:s}=i,{primaryKey:o}=s,{extractKey:a,outbound:l}=o,c={...i,mutate:d=>{const h=d.trans,g=h.mutatedParts||(h.mutatedParts={}),y=k=>{const _=`idb://${t}/${r}/${k}`;return g[_]||(g[_]=new de)},w=y(""),f=y(":dels"),{type:m}=d;let[b,v]=d.type==="deleteRange"?[d.range]:d.type==="delete"?[d.keys]:d.values.length<50?[[],d.values]:[];const E=d.trans._cache;return i.mutate(d).then(k=>{if(Y(b)){m!=="delete"&&(b=k.results),w.addKeys(b);const _=ns(b,E);_||m==="add"||f.addKeys(b),(_||v)&&function(A,S,B,D){function q(V){const F=A(V.name||"");function ce(H){return H!=null?V.extractKey(H):null}const M=H=>V.multiEntry&&Y(H)?H.forEach(Ae=>F.addKey(Ae)):F.addKey(H);(B||D).forEach((H,Ae)=>{const it=B&&ce(B[Ae]),vn=D&&ce(D[Ae]);J(it,vn)!==0&&(it!=null&&M(it),vn!=null&&M(vn))})}S.indexes.forEach(q)}(y,s,_,v)}else if(b){const _={from:b.lower,to:b.upper};f.add(_),w.add(_)}else w.add(n),f.add(n),s.indexes.forEach(_=>y(_.name).add(n));return k})}},u=({query:{index:d,range:h}})=>{var g,y;return[d,new de((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 de(d.key)],getMany:d=>[o,new de().addKeys(d.keys)],count:u,query:u,openCursor:u};return $(p).forEach(d=>{c[d]=function(h){const{subscr:g}=U;if(g){const y=v=>{const E=`idb://${t}/${r}/${v}`;return g[E]||(g[E]=new de)},w=y(""),f=y(":dels"),[m,b]=p[d](h);if(y(m.name||"").add(b),!m.isPrimaryKey){if(d!=="count"){const v=d==="query"&&l&&h.values&&i.query({...h,values:!1});return i[d].apply(this,arguments).then(E=>{if(d==="query"){if(l&&h.values)return v.then(({result:_})=>(w.addKeys(_),E));const k=h.values?E.result.map(a):E.result;h.values?w.addKeys(k):f.addKeys(k)}else if(d==="openCursor"){const k=E,_=h.values;return k&&Object.create(k,{key:{get:()=>(f.addKey(k.primaryKey),k.key)},primaryKey:{get(){const A=k.primaryKey;return f.addKey(A),A}},value:{get:()=>(_&&w.addKey(k.primaryKey),k.value)}})}return E})}f.add(n)}}return i[d].apply(this,arguments)}}),c}}}};class Me{constructor(t,n){this._middlewares={},this.verno=0;const r=Me.dependencies;this._options=n={addons:Me.addons,autoOpen:!0,indexedDB:r.indexedDB,IDBKeyRange:r.IDBKeyRange,...n},this._deps={indexedDB:n.indexedDB,IDBKeyRange:n.IDBKeyRange};const{addons:i}=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:T,dbReadyPromise:null,cancelOpen:T,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:[kr,T]}),this.on.ready.subscribe=xi(this.on.ready.subscribe,a=>(l,c)=>{Me.vip(()=>{const u=this._state;if(u.openComplete)u.dbOpenError||L.resolve().then(l),c&&a(l);else if(u.onReadyBeingFired)u.onReadyBeingFired.push(l),c&&a(l);else{a(l);const p=this;c||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 c=Yi,u=null;if(l)try{c=l()}catch(g){u=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:c,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:u,or:p.or,valueMapper:h!==_t?h:null}})),this.Table=function(a){return st(Oo.prototype,function(l,c,u){this.db=a,this._tx=u,this.name=l,this.schema=c,this.hook=a._allTables[l]?a._allTables[l].hook:ft(null,{creating:[bo,T],reading:[vo,_t],updating:[So,T],deleting:[_o,T]})})}(this),this.Transaction=function(a){return st(Mo.prototype,function(l,c,u,p,d){this.db=a,this.mode=l,this.storeNames=c,this.schema=u,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(),W(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(Qi.prototype,function(l,c,u){this.db=a,this._ctx={table:l,index:c===":id"?null:c,or:u};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,c,u)=>new this.Transaction(a,l,c,this._options.chromeTransactionDurability,u),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}}),i.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 r=n.filter(i=>i._cfg.version===t)[0];return r||(r=new this.Version(t),n.push(r),n.sort(Ko),r.stores({}),this._state.autoSchema=!1,r)}_whenReady(t){return this.idbdb&&(this._state.openComplete||U.letThrough||this._vip)?t():new L((n,r)=>{if(this._state.openComplete)return r(new x.DatabaseClosed(this._state.dbOpenError));if(!this._state.isBeingOpened){if(!this._options.autoOpen)return void r(new x.DatabaseClosed);this.open().catch(T)}this._state.dbReadyPromise.then(n,r)}).then(t)}use({stack:t,create:n,level:r,name:i}){i&&this.unuse({stack:t,name:i});const s=this._middlewares[t]||(this._middlewares[t]=[]);return s.push({stack:t,create:n,level:r??10,name:i}),s.sort((o,a)=>o.level-a.level),this}unuse({stack:t,name:n,create:r}){return t&&this._middlewares[t]&&(this._middlewares[t]=this._middlewares[t].filter(i=>r?i.create!==r:!!n&&i.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(r=>{t.dbReadyResolve=r}),t.openCanceller=new L((r,i)=>{t.cancelOpen=i})}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((r,i)=>{const s=()=>{this.close();var o=this._deps.indexedDB.deleteDatabase(this.name);o.onsuccess=K(()=>{(function({indexedDB:a,IDBKeyRange:l},c){!Ar(a)&&c!==fn&&xr(a,l).delete(c).catch(T)})(this._deps,this.name),r()}),o.onerror=se(i),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 $(this._allTables).map(t=>this._allTables[t])}transaction(){const t=Wo.apply(this,arguments);return this._transaction.apply(this,t)}_transaction(t,n,r){let i=U.trans;i&&i.db===this&&t.indexOf("!")===-1||(i=null);const s=t.indexOf("?")!==-1;let o,a;t=t.replace("!","").replace("?","");try{if(a=n.map(c=>{var u=c instanceof this.Table?c.name:c;if(typeof u!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return u}),t=="r"||t===_n)o=_n;else{if(t!="rw"&&t!=Sn)throw new x.InvalidArgument("Invalid transaction mode: "+t);o=Sn}if(i){if(i.mode===_n&&o===Sn){if(!s)throw new x.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");i=null}i&&a.forEach(c=>{if(i&&i.storeNames.indexOf(c)===-1){if(!s)throw new x.SubTransaction("Table "+c+" not included in parent transaction.");i=null}}),s&&i&&!i.active&&(i=null)}}catch(c){return i?i._promise(null,(u,p)=>{p(c)}):W(c)}const l=ts.bind(null,this,o,a,i,r);return i?i._promise(o,l,"lock"):U.trans?nt(U.transless,()=>this._whenReady(l)):this._whenReady(l)}table(t){if(!ne(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,r){return this._subscribe(t&&typeof t!="function"?t:{next:t,error:n,complete:r})}[Qo](){return this}}function rs(e,t){return $(t).forEach(n=>{ln(e[n]||(e[n]=new de),t[n])}),e}function Zo(e){let t,n=!1;const r=new Xo(i=>{const s=_r(e);let o=!1,a={},l={};const c={get closed(){return o},unsubscribe:()=>{o=!0,xe.storagemutated.unsubscribe(h)}};i.start&&i.start(c);let u=!1,p=!1;function d(){return $(l).some(y=>a[y]&&Yo(a[y],l[y]))}const h=y=>{rs(a,y),d()&&g()},g=()=>{if(u||o)return;a={};const y={},w=function(f){s&&tt();const m=()=>Ie(e,{subscr:f,trans:null}),b=U.trans?nt(U.transless,m):m();return s&&b.then(we,we),b}(y);p||(xe(kt,h),p=!0),u=!0,Promise.resolve(w).then(f=>{n=!0,t=f,u=!1,o||(d()?g():(a={},l=y,i.next&&i.next(f)))},f=>{u=!1,n=!1,i.error&&i.error(f),c.unsubscribe()})};return g(),c});return r.hasValue=()=>n,r.getValue=()=>t,r}let lr;try{lr={indexedDB:j.indexedDB||j.mozIndexedDB||j.webkitIndexedDB||j.msIndexedDB,IDBKeyRange:j.IDBKeyRange||j.webkitIDBKeyRange}}catch{lr={indexedDB:null,IDBKeyRange:null}}const Re=Me;function Gt(e){let t=fe;try{fe=!0,xe.storagemutated.fire(e)}finally{fe=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 Ar(t)?Promise.resolve(t.databases()).then(r=>r.map(i=>i.name).filter(i=>i!==fn)):xr(t,n).toCollection().primaryKeys()}(Re.dependencies).then(e)}catch{return W(new x.MissingAPI)}},defineClass:()=>function(e){Q(this,e)},ignoreTransaction:e=>U.trans?nt(U.transless,e):e(),vip:sr,async:function(e){return function(){try{var t=or(e.apply(this,arguments));return t&&typeof t.then=="function"?t:L.resolve(t)}catch(n){return W(n)}}},spawn:function(e,t,n){try{var r=or(e.apply(n,t||[]));return r&&typeof r.then=="function"?r:L.resolve(r)}catch(i){return W(i)}},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:()=>le,set:e=>{Pi(e,e==="dexie"?()=>!0:Gi)}},derive:He,extend:Q,props:Xe,override:xi,Events:ft,on:xe,liveQuery:Zo,extendObservabilitySet:rs,getByKeyPath:ge,setByKeyPath:ie,delByKeyPath:function(e,t){typeof t=="string"?ie(e,t,void 0):"length"in t&&[].map.call(t,function(n){ie(e,n,void 0)})},shallowClone:Ci,deepClone:xt,getObjectDiff:Rr,cmp:J,asap:Ai,minKey:Qn,addons:[],connections:ht,errnames:Er,dependencies:lr,semVer:zr,version:zr.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"&&(xe(kt,e=>{if(!fe){let t;hn?(t=document.createEvent("CustomEvent"),t.initCustomEvent(Ee,!0,!0,e)):t=new CustomEvent(Ee,{detail:e}),fe=!0,dispatchEvent(t),fe=!1}}),addEventListener(Ee,({detail:e})=>{fe||Gt(e)}));let fe=!1;if(typeof BroadcastChannel<"u"){const e=new BroadcastChannel(Ee);typeof e.unref=="function"&&e.unref(),xe(kt,t=>{fe||e.postMessage(t)}),e.onmessage=t=>{t.data&&Gt(t.data)}}else if(typeof self<"u"&&typeof navigator<"u"){xe(kt,t=>{try{fe||(typeof localStorage<"u"&&localStorage.setItem(Ee,JSON.stringify({trig:Math.random(),changedParts:t})),typeof self.clients=="object"&&[...self.clients.matchAll({includeUncontrolled:!0})].forEach(n=>n.postMessage({type:Ee,changedParts:t})))}catch{}}),typeof addEventListener<"u"&&addEventListener("storage",t=>{if(t.key===Ee){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===Ee&&Gt(t.changedParts)})}L.rejectionMapper=function(e,t){if(!e||e instanceof Ge||e instanceof TypeError||e instanceof SyntaxError||!e.name||!$r[e.name])return e;var n=new $r[e.name](t||e.message,e);return"stack"in e&&ye(n,"stack",{get:function(){return this.inner.stack}}),n},Pi(le,Gi);let is=!0,Or=!1;const ea=()=>is=!1,ta=()=>Or=!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={},cr;class ra{constructor(t){N(this,"_values",[]);N(this,"_isWebMetric");this.name=t,this._isWebMetric=na.includes(this.name)}report(t){if(is&&this._values.push({time:Date.now(),value:t}),Or||!this._isWebMetric)return;const n=this.findExceededThreshold(t);n&&cr&&cr(t,n)}collect(){const t=this._values;return this._values=[],t}findExceededThreshold(t){const n=ct[this.name];if(n)return n.find(r=>this.valueExceedsThreshold(t,r))}valueExceedsThreshold(t,n){return n.type==="max"?t>n.value:n.type==="min"?t<n.value:!1}}const ia=(e,t)=>{ct={},Or=!1,e==null||e.forEach(n=>{var r;n.metric in ct||(ct[n.metric]=[]),(r=ct[n.metric])==null||r.push(n)}),cr=t},Ct={},mn=e=>{const t=new ra(e);return Ct[e]=t,t},ss=(e,t)=>{let n=Ct[e];return n||(n=mn(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){Bn(`Error posting metrics: ${n}`)}},oa=({reportingIntervalSeconds:e,postMetrics:t})=>{e?setInterval(()=>{sa(t)},e*1e3):ea()},os=async(e,t)=>{const n=performance.now();try{await e()}finally{const r=performance.now()-n;let i=Ct[t];i||(i=mn(t)),i.report(r/1e3)}},as=(e,t)=>{const n=performance.now();try{e()}finally{const r=performance.now()-n;let i=Ct[t];i||(i=mn(t)),i.report(r/1e3)}},aa=30,ls=()=>{Le.setItem("sprig.disableReplayRecording","disabled")},Ne=()=>!!Le.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:r})=>{Ne()||t instanceof Error&&(ls(),ca(t==null?void 0:t.message)&&(n&&window.UserLeap.reportError(e,t,r),ha()))},da=async(e,t,{reportError:n}={reportError:!0})=>{var i;let r;try{if(n&&((i=window.navigator.storage)!=null&&i.estimate)){const{quota:s,usage:o}=await window.navigator.storage.estimate();r={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:r})},pa=()=>{const e=Le.getItem("sprig.sessionId");if(e)return I(`Found saved session id: ${e}`),Le.removeItem("sprig.sessionId"),e;const t=$e();return I(`Generating new uuid: ${t}`),t},X=pa();window.addEventListener("beforeunload",()=>{I(`Before page unload saving session id: ${X}`),Le.setItem("sprig.sessionId",X)});const ha=async()=>{O.transaction("rw",O.events,O.chunkUploads,O.pendingCaptures,()=>{O.events.clear(),O.chunkUploads.clear(),O.pendingCaptures.clear()}).catch(()=>{})},Un=(e,t,n=()=>!0)=>O.table(t).where("timestamp").below(e).and(n).delete(),fa=async(e,t)=>{let n=[];return await os(async()=>{n=await O.events.where("[sessionId+timestamp]").between([X,e],[X,t??Date.now()]).toArray()},"sdk_replay_get_events_between_seconds"),n},ma=(e,t,n)=>{const r=new Date,i=r.setMinutes(r.getMinutes()+(n??aa));return O.events.where("[sessionId+timestamp]").between([X,e],[X,t]).modify({expiredAt:i})},ya=e=>O.chunkUploads.add({...e,sessionId:e.sessionId??X}),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:X,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??X,canUpload:!1}),Sa=()=>O.pendingCaptures.where("sessionId").equals(X).and(e=>e.targetTimestamp<Date.now()).toArray(),Ea=()=>O.pendingCaptures.where("sessionId").equals(X).toArray(),ka=e=>O.pendingCaptures.where("sessionId").equals(X).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:r}=await window.navigator.storage.estimate();if(n&&r&&(n-r)/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=>{Ei(`Error opening replay storage: ${JSON.stringify(e)}`),ls()});const Ua=async(e,t,n)=>new Promise((r,i)=>{const s=e.createElement("script");s.src=t,s.onload=r,s.onerror=i,n&&(s.nonce=n),e.head.appendChild(s)});let ei=1,ur=5e3,Yt=6e4;const xa=5,ti=1e3,cs=30,cn=cs+xa,Aa="sprig.pendingCount";let dr,pr,us,ni=Date.now(),yn=!1,Jt;const Ra=async(e,t,n,r=2,i)=>{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(i!=null&&i.minAvailableGb&&(ei=i.minAvailableGb),!await La(ei)){Bn("Minimum storage not available");return}I("Initializing replay"),i!=null&&i.minDuration&&(ur=i.minDuration),i!=null&&i.batchDuration&&(Yt=i.batchDuration),oo(r),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){Bn("Record script failed to set global function");return}let o=!0,a=0;Jt=s({checkoutEveryNms:cs*1e3,sampling:{input:"last",scroll:250,media:800},emit:(l,c)=>{if(Ne())return;if(ni=Date.now(),c&&l.type===Mn.Meta)a=performance.now();else if(c&&a&&l.type===Mn.FullSnapshot){const p=performance.now()-a;ss("sdk_replay_snapshot_seconds",p/1e3)}const u=o||!!c;o=!1,Ca({uuid:$e(),event:JSON.stringify(l),isValidStart:u,timestamp:Date.now()})},...i}),yn=!0,pr||(pr=window.setInterval(()=>{Date.now()-ni>ti&&ve("Sprig_Noop",{})},ti)),R.on("survey.complete",l=>{Wa({id:l,userAgent:window.navigator.userAgent})})},"Error initializing replay")};let hr=!1,fr=[];const Ca=e=>{fr.push(e),hr||Da()},Oa=e=>{const t=e.map(n=>({...n,sessionId:n.sessionId??X}));if(t.length!==0)return O.transaction("rw",O.events,()=>{O.events.bulkAdd(t)}).catch(n=>{rt("Error storing replay events",n)})},Da=()=>{hr=!0,setTimeout(async()=>{if(Ne())return;const e=fr;fr=[],hr=!1,as(async()=>{await Oa(e)},"sdk_replay_add_event_batch_seconds")},500)},Pa=(e=6*60,t=30*60,n=4*60)=>{dr=window.setInterval(()=>{const r=Date.now();Ne()||(vt(`Performing periodic replay data cleanup / Event Seconds ${e} / Chunk Seconds ${t} / Pending Capture Seconds ${n}`),os(()=>O.transaction("rw!",O.events,O.chunkUploads,O.pendingCaptures,()=>{Un(r-e*1e3,"events",i=>i.expiredAt===void 0||i.expiredAt<r-e*1e3),Un(r-t*1e3,"chunkUploads"),Un(r-n*1e3,"pendingCaptures",i=>i.canUpload===void 0||i.canUpload===!1)}).catch(i=>{clearInterval(dr),rt("Error deleting table rows",i)}),"sdk_replay_cleanup_seconds"),I("Cleanup complete"))},30*1e3)},Ta=(e=5)=>{us=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 r=>(await O.pendingCaptures.delete(r.uuid),hs(r.captureParams,r.canUpload)))),Pe=(t-n.length).toString(),Le.setItem(Aa,Pe))},"Error initiating pending captures")},e*1e3)},Ba=async(e,t,n,r,i)=>{const s=Math.min(e+i,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:r,events:[]};if(!r){I(`Searching for valid start in ${a.length} events ${o}`);let l=-1;if(a==null||a.forEach((u,p)=>{if(!u.isValidStart)return;const d=u.timestamp<=t;(l<0||d)&&(l=p)}),l<0)return I(`No valid start found in ${a.length} events ${o}`),{validStartFound:r,events:[]};const c=a[l].timestamp;return I(`Found valid start at: ${new Date(c).toLocaleTimeString()} in events ${o}`),{validStartFound:!0,events:a==null?void 0:a.slice(l)}}return{validStartFound:r,events:a}},Ma=(e,t,n)=>{const r=e.length,i=t*1024*1024,s=Math.ceil(r/n),o=Math.max(i,s);I(`Total file bytes: ${r} / target chunk size: ${o}`);const a=[];let l=0;for(;l<r;)a.push(e.slice(l,l+o)),l+=o;return a},ds=e=>Promise.all(e.map(async t=>{const n=await ao(t);return await ga(t.uuid,n),t.uploadId})),ps=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 r=n.map(s=>({ETag:s.etag,PartNumber:s.chunkIndex})).filter(s=>s.ETag!==null),i=n[0];await Ii({apiUrl:i.apiUrl,surveyId:i.surveyId,uploadId:e,responseGroupUuid:i.responseGroupId,etags:r,headers:i.completeUploadHeaders,replayDuration:i.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 ds(e);I(`Finished uploading unfinished chunks for ${t}`),t!=null&&t.length&&await Promise.all(t.map(n=>{if(n)return ps(n)}))},"Error uploading unfinished chunks")},ja=async(e,t)=>{await ds(t),I(`Done uploading chunks for uploads: ${e.join(",")}`),await Promise.all(e.map(n=>ps(n)))},Ka=e=>{let t=0;e.forEach(i=>{t+=i.length});const n=new Uint8Array(t);let r=0;return e.forEach(i=>{n.set(i,r),r+=i.length}),n},ri=async(e,t,n)=>{const r=new TextEncoder;let i=null,s=null,o=null,a=!1,l=!1,[c,u]=[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}c===0&&(c=h[0].timestamp),u=h[h.length-1].timestamp,I(`Last event time in batch: ${new Date(u).toLocaleTimeString()}`);const w=`${a?",":"["}${h.map(m=>m.event).join(",")}`,f=r.encode(w);n&&s===null&&(vt("Attempting compression"),o=new window.CompressionStream("gzip"),s=o.writable.getWriter()),as(()=>{n&&s?s.write(f):d.push(f)},"sdk_replay_compression_seconds"),a=!0}if(u-c<ur)return I(`Replay duration is shorter than minimum of ${ur}ms / Start:${c} / End:${u}`),null;const g=r.encode("]");return vt("Writing final close brace"),s&&o?(s.write(g),s.close(),i=new Uint8Array(await new Response(o.readable).arrayBuffer())):(d.push(g),i=Ka(d)),I("Finished generating file data"),i},Na=async(e,t)=>{const n=window.CompressionStream!==void 0;let r=null;const i=t??Date.now(),s=i-e;try{r=await ri(s,i,n)}catch(o){o instanceof Error&&window.UserLeap.reportError("Error compressing replay",o),n&&Ze(async()=>{await ri(s,i,!1)},"fileData fallback failed")}return r},ii=async e=>{const{surveyId:t,responseGroupId:n,visitorId:r,apiUrl:i,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 c=Ma(l,o.minimumChunkSizeMb,o.signedUrls.length);I(`Got ${c.length} chunks for survey: ${t}`);const u=await Promise.all(c.map(async(p,d)=>{const h=$e(),g={apiUrl:i,chunkIndex:d+1,completeUploadHeaders:s,etag:null,responseGroupId:n,status:"ReadyForUpload",surveyId:t,timestamp:a,totalChunks:c.length,data:p,uploadId:o.uploadId,uploadUrl:o.signedUrls[d].url,uuid:h,visitorId:r};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],u)},hs=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:r,triggerTimestamp:i,responseGroupId:s}=e,o=async()=>{setTimeout(()=>R.removeListener(C.QuestionAnswered,o),0),Ze(async()=>{r.replayDurationType==="before"?await ii(e):await ka(s)},"Error in schedule/capture callback")};Ze(async()=>{if(r.replayDurationType==="after"||r.replayDurationType==="beforeAndAfter"){n||(I("Attaching QuestionAnswered listener for non-standalone replay"),R.on(C.QuestionAnswered,o)),I(`Scheduling capture for replay of type: ${r.replayDurationType}`),await $a(e);return}if(n||t)I(`Proceeding to capture replay for survey: ${e.surveyId} / standalone? ${n} / canUpload? ${t}`),await ii(e);else{const a=cn+r.replayDurationSeconds,l=i-a*1e3,c=i;I(`Setting expiry minutes to ${r.expirationTimeLimitMinutes} for events from ${new Date(l).toLocaleTimeString()} to ${new Date(c).toLocaleTimeString()}`),await ma(l,c,r.expirationTimeLimitMinutes),I("Attaching QuestionAnswered listener"),R.on(C.QuestionAnswered,o)}},"Error in scheduling/capturing replay")},si=()=>{if(Ne()){vt("Not clearing user data, replay is disabled");return}return O.transaction("rw",O.events,O.pendingCaptures,()=>{O.events.where("sessionId").equals(X).delete(),O.pendingCaptures.where("sessionId").equals(X).delete()}).catch(e=>{rt("Error clearing session event data",e)})};let Pe=Le.getItem("sprig.pendingCount");const $a=async e=>{I(`Scheduling replay capture: ${JSON.stringify(e)}`);const{surveyId:t}=e,n=await Ea(),r=n==null?void 0:n.filter(o=>o.captureParams.surveyId===t);if(r!=null&&r.length){I(`Pending capture exists for survey: ${t}`);return}const i={...e,replayParams:{...e.replayParams}};e.replayParams.replayDurationType==="beforeAndAfter"&&(i.replayParams.replayDurationSeconds*=2),i.replayParams.replayDurationType="before";const s=e.triggerTimestamp+e.replayParams.replayDurationSeconds*1e3;return i.triggerTimestamp=s,Pe=Pe?(parseInt(Pe)+1).toString():"1",Le.setItem("sprig.pendingCount",Pe),_a({uuid:$e(),targetTimestamp:s,timestamp:Date.now(),captureParams:i})},ve=(e,t)=>{var n,r;if(yn)try{(r=(n=window.rrwebRecord)==null?void 0:n.addCustomEvent)==null||r.call(n,e,t)}catch(i){rt("Error recording custom event",i)}},Ze=async(e,t)=>{try{await e()}catch(n){rt(t,n)}},oi=e=>{e.description&&(e.description=Dr(e.description)),ve("Sprig_PageView",e)},qa=e=>{ve("Sprig_TrackEvent",e)},Va=e=>{ve("Sprig_ShowSurvey",e)},Wa=e=>{ve("Sprig_SubmitSurvey",e)},za=e=>{var t;(t=e==null?void 0:e.elementAttributes)!=null&&t.text&&(e.elementAttributes.text=Dr(e.elementAttributes.text)),ve("Sprig_Click",e)},Ha=e=>{ve("Sprig_Refresh",e)},Ga=e=>{e.currentPageTitle&&(e.currentPageTitle=Dr(e.currentPageTitle)),ve("Sprig_BackForward",e)},Ya=e=>{ve("Sprig_Keystroke",e)},rt=(e,t,{reportError:n}={reportError:!0})=>(Jt&&(Jt(),Jt=void 0),yn=!1,[dr,pr,us].forEach(r=>{r&&clearInterval(r)}),Ei(`${e} - ${JSON.stringify(t)}`),da(e,t,{reportError:n})),fs=()=>yn,Dr=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),ai="ul-view-sdk-script",Ja=["ios","android"],Se="visitors",ke="environments",li=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 gn(e,t){const{matchType:n,pattern:r}=e,i=n?li[n]:li.legacy;let s=!1;try{s=i(r,t)}catch(o){const a=`[Sprig] (ERR-445) Failed to check url match with pattern ${r}`;o instanceof Error&&(console.warn(a,o),o.stack=JSON.stringify(e),window.UserLeap.reportError(a,o))}return s}async function oe(e,t){var s,o,a;const{shouldDropOnRateLimit:n,...r}=t;r.headers=Object.assign(Fe(window.UserLeap),r.headers);const i=await me(e,{...r,shouldDropOnRateLimit:n});if(i.ok){const l=(s=i.headers)==null?void 0:s.get("Authorization"),c=l?l.split(" "):void 0,u=c&&c.length===2?c[1]:void 0,p=(o=i.headers)==null?void 0:o.get("x-ul-visitor-id");u&&p&&(p!==window.UserLeap.visitorId||window.UserLeap.token!==u)&&(ee("token",u),ee("vid",p),R.emit(C.VisitorIDUpdated,{visitorId:p}),window.UserLeap.token=u,window.UserLeap.visitorId=p)}return(a=i.json)!=null&&a.logMessage&&console.warn(`[Sprig] ${i.json.logMessage}`),i}function ee(e,t){const n=te.getItem("userleap.ids");let r={};if(n)try{r=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 i=r[window.UserLeap.envId];i?i[e]=t:i={[e]:t},r[window.UserLeap.envId]=i;try{te.setItem("userleap.ids",JSON.stringify(r))}catch(s){s instanceof Error&&console.warn(`[Sprig] (ERR-426) Unable to write to Local Storage:: ${s.message}`)}}function Pr(){return window.previewMode?"0":window.UserLeap.visitorId??""}function re(e,t,n){const r=[window.UserLeap._API_URL,"sdk",e];return t&&t.forEach(i=>{r.push(i),i===ke?r.push(window.UserLeap.envId):i===Se&&r.push(Pr())}),n&&r.push(n),r.join("/")}const yt=async e=>{var F,ce;const{context:t,forceBrandedLogo:n,endCard:r,isFeedback:i=!1,locale:s,productConfig:o,questions:a,responseGroupUid:l,surveyId:c,uuid:u,vid:p,sessionReplay:d,studyType:h}=e,g=Fe(window.UserLeap),y=Br(g),w=Tr(g);if(I(`Attempting to display survey: ${c}`),d&&(I("Survey has replay attached"),y?R.emit(C.ReplayCapture,{responseGroupUid:l,hasQuestions:!!(a!=null&&a.length),surveyId:c,uploadId:d.uploadId,replayType:d.replayDurationType??"before",seconds:d.replayDurationSeconds,generateVideoUploadUrlPayload:{mediaRecordingUid:$e(),mediaType:"screen",questionId:1,responseGroupUid:l,surveyId:c,updatedAt:new Date().toISOString(),visitorId:window.UserLeap.visitorId,isReplay:!0}}):hs({responseGroupId:l,surveyId:c,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 M="[Sprig] (ERR-409) Found an existing Survey container, aborting rendering of this survey";return console.warn(M),{success:!1,message:M,surveyState:"no survey"}}if(p!==window.UserLeap.visitorId&&u!==window.UserLeap.visitorId&&!window.previewMode){const M="Attempted to display survey to a different visitor";return I(M),window.UserLeap.reportError("DisplaySurvey",new Error(M)),{success:!1,message:M,surveyState:"no survey"}}I(`Showing survey: ${c}`),Va({id:c,userAgent:window.navigator.userAgent}),mi.disable(),R.emit(C.SurveyWillPresent,{name:C.SurveyWillPresent,"survey.id":c});let f,m=document.createElement("div"),b,v,E;const k=M=>{const{"view.version":H}=M;H!==g["x-ul-sdk-version"]&&gs(),R.removeListener("verify.view.version",k)};R.on("verify.view.version",k),window.UserLeap.useMobileStyling=w,wi(g)?(f="ul-direct-embeded-frame",b=document.head,v=window,E=!1,y&&(ys(),m.id=f,window.UserLeap.container.appendChild(m),ws(),R.emit(C.SurveyLifeCycle,{state:"presented"}),R.emit(C.SurveyPresented,{name:C.SurveyPresented,"survey.id":c}))):{frameId:f,contentWinDocHead:b,contentWindow:v,hasOverlay:E,iframe:m}=tl({productConfig:o,useMobileStyling:w,surveyId:c,isFeedback:i}),window.UserLeap.frameId=f;const _=M=>{R.once(C.CloseSurveyOnOverlayClick,M)},A={apiURL:window.UserLeap._API_URL,cards:a,configureExitOnOverlayClick:_,context:t,endCard:r,envId:window.UserLeap.envId,eventEmitFn:R.emit.bind(R),fontFamily:window.UserLeap.fontFamily,fontFamilyURL:window.UserLeap.fontFamilyURL,forceBrandedLogo:n,frame:m,headers:g,locale:s,mobileSDKVersion:window.UserLeap.mobileSDKVersion,previewKey:te.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:(F=window.UserLeap.config)==null?void 0:F.startingQuestionIdx,studyType:h,styleNonce:window.UserLeap.styleNonce,surveyId:c,tabTitle:document.title,ulEvents:wt,useMobileStyling:w,userId:u,viewDocument:v==null?void 0:v.document,viewWindow:v,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}),window.UserLeap.customStyles&&(A.customStyles=window.UserLeap.customStyles),v&&(v.__cfg=A);function S(){const M=document.createElement("script");return window.UserLeap.nonce&&M.setAttribute("nonce",window.UserLeap.nonce),M.id=ai,M}const B=window.UserLeap.viewSDKURL?window.UserLeap.viewSDKURL:A.path,D=document.getElementById(ai);D&&D.remove();const q=S(),V=()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{display:"flex"})};if(A.installationMethod==="web-npm"||A.installationMethod==="web-npm-bundled"){const{default:M}=await Promise.resolve().then(()=>require("./view-BMyPvct6.cjs"));M.configure(A),E&&window.UserLeap.container&&V()}else B&&(q.src=B,E&&q.addEventListener("load",()=>{window.UserLeap.container&&V()}),v==null||v.addEventListener("error",M=>{M.target instanceof HTMLScriptElement&&M.target.src===B&&window.UserLeap.reportError("loadFrameScript",new Error("Frame script failed to load"))},{capture:!0,once:!0}));return b==null||b.appendChild(q),{success:!0,surveyState:"ready",surveyId:c,responseGroupUid:l}};function Tr(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 Br(e)||t>10&&t<$s}function Br(e){return Ja.includes(e["userleap-platform"])}const ms="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)",xn="0px",ys=e=>{window.UserLeap.container=document.createElement("div"),window.UserLeap.container.className="ul-container";const t=bs();e&&t&&!window.UserLeap.useMobileStyling?t.appendChild(window.UserLeap.container):document.body.appendChild(window.UserLeap.container)},gs=(e,t)=>{var r;rl();const n=window.UserLeap.container;if(n)try{(r=n.parentNode)==null||r.removeChild(n),window.UserLeap.container=null,ee("trackStartUrl",null),R.emit(C.SurveyLifeCycle,{state:"dismissed"}),R.emit(C.SurveyClosed,{name:C.SurveyClosed,initiator:e,studyType:t})}catch(i){console.warn(`[Sprig] (ERR-412) Error removing UserLeap container by ${e} `+n),i instanceof Error&&window.UserLeap.reportError("dismissActiveSurvey",i)}},ws=()=>{R.once(C.SurveyWillClose,({initiator:e,studyType:t})=>{R.removeAllListeners(C.CloseSurveyOnOverlayClick),gs(e,t)})},Za=(e,t)=>{const r={...{position:"fixed",overflow:"auto",top:"0px",left:"0px",display:"none",height:"100%",width:"100%",transition:"background-color 0.3s ease-out",zIndex:2147483646}},i=t?e.overlayStyleMobile:e.overlayStyle;r["background-color"]=i==="light"?Qa:Xa,t||(r.margin="auto"),window.UserLeap.container&&Object.assign(window.UserLeap.container.style,r)},el=(e,t,n,r)=>{var u,p;const i={position:"fixed",bottom:"0px",right:xn,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,c=!1;if(n)(u=window.UserLeap.windowDimensions)!=null&&u.width?i.width=`${window.UserLeap.windowDimensions.width}px`:i.width="100%",(p=window.UserLeap.windowDimensions)!=null&&p.height?i.maxHeight=`${window.UserLeap.windowDimensions.height-20}px`:window.UserLeap.maxHeight?i.maxHeight=window.UserLeap.maxHeight:i.maxHeight=`${document.body.clientHeight-20}px`,["light","dark"].includes(s.overlayStyleMobile)&&(c=!0);else{i.width=hi,i.maxHeight=window.UserLeap.maxHeight||"66vh";const d=()=>{c=!0,l={margin:"auto",position:"static"}};if(r)a?d():l={position:"relative",height:"300px"};else switch(s.framePosition){case"bottomLeft":l={left:xn};break;case"topLeft":l={left:xn,top:0};break;case"topRight":l={top:0};break;case"center":d();break}}return c&&Za(s,n),Object.assign(e.style,i,l),c},tl=({productConfig:e,useMobileStyling:t,surveyId:n,isFeedback:r})=>{var p,d;const i=ms,s=r&&e.desktopDisplay==="slider";ys(s),nl();const o=document.createElement("iframe");o.id=i,o.setAttribute("title","Sprig User Feedback Dialog");const a=el(o,e,t,r);ws(),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 c=(d=o.contentWindow)==null?void 0:d.document;if(c&&(c.open("text/html","replace"),c.write("<!doctype html><head></head><body></body></html>"),c.close(),!t)){const h=c.body;h.style.display="flex",h.style.alignItems="center"}const u=c==null?void 0:c.head;return{frameId:i,contentWinDocHead:u,contentWindow:o.contentWindow,hasOverlay:a,iframe:o}},vs={[C.SurveyFadingOut]:()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{"background-color":"rgba(0,0,0,0)"})}},nl=()=>{Object.entries(vs).forEach(([e,t])=>{R.on(e,t)})},rl=()=>{Object.entries(vs).forEach(([e,t])=>{R.off(e,t)})},bs=()=>P,Je=()=>document.getElementById("sprig-feedback-container"),Mr=()=>document.getElementById("sprig-feedback-loading-animation"),il=()=>{if(Mr())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=`
8
+ From previous: `);return this._state!==null&&(this._stack=e),e}finally{Vn=!1}}},timeout:function(e,t){return e<1/0?new L((n,r)=>{var i=setTimeout(()=>r(new x.Timeout(t)),e);this.then(n,r).finally(clearTimeout.bind(null,i))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&ye(L.prototype,Symbol.toStringTag,"Dexie.Promise"),Ye.env=Wi(),Xe(L,{all:function(){var e=he.apply(null,arguments).map(Bt);return new L(function(t,n){e.length===0&&t([]);var r=e.length;e.forEach((i,s)=>L.resolve(i).then(o=>{e[s]=o,--r||t(e)},n))})},resolve:e=>{if(e instanceof L)return e;if(e&&typeof e.then=="function")return new L((n,r)=>{e.then(n,r)});var t=new L(St,!0,e);return Vi(t,zn),t},reject:Tt,race:function(){var e=he.apply(null,arguments).map(Bt);return new L((t,n)=>{e.map(r=>L.resolve(r).then(t,n))})},PSD:{get:()=>U,set:e=>U=e},totalEchoes:{get:()=>sn},newPSD:Ie,usePSD:nt,scheduler:{get:()=>pt,set:e=>{pt=e}},rejectionMapper:{get:()=>Hn,set:e=>{Hn=e}},follow:(e,t)=>new L((n,r)=>Ie((i,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&&Ur()},[])})(()=>{this.unhandleds.length===0?i():s(this.unhandleds[0])})},o.finalize),e()},t,n,r))}),qt&&(qt.allSettled&&ye(L,"allSettled",function(){const e=he.apply(null,arguments).map(Bt);return new L(t=>{e.length===0&&t([]);let n=e.length;const r=new Array(n);e.forEach((i,s)=>L.resolve(i).then(o=>r[s]={status:"fulfilled",value:o},o=>r[s]={status:"rejected",reason:o}).then(()=>--n||t(r)))})}),qt.any&&typeof AggregateError<"u"&&ye(L,"any",function(){const e=he.apply(null,arguments).map(Bt);return new L((t,n)=>{e.length===0&&n(new AggregateError([]));let r=e.length;const i=new Array(r);e.forEach((s,o)=>L.resolve(s).then(a=>t(a),a=>{i[o]=a,--r||n(new AggregateError(i))}))})}));const G={awaits:0,echoes:0,id:0};var Io=0,zt=[],bn=0,sn=0,Uo=0;function Ie(e,t,n,r){var i=U,s=Object.create(i);s.parent=i,s.ref=0,s.global=!1,s.id=++Uo;var o=Ye.env;s.env=Lr?{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:qr(o.nthen,s),gthen:qr(o.gthen,s)}:{},t&&Q(s,t),++i.ref,s.finalize=function(){--this.parent.ref||this.parent.finalize()};var a=nt(s,e,n,r);return s.ref===0&&s.finalize(),a}function tt(){return G.id||(G.id=++Io),++G.awaits,G.echoes+=Fi,G.id}function we(){return!!G.awaits&&(--G.awaits==0&&(G.id=0),G.echoes=G.awaits*Fi,!0)}function Bt(e){return G.echoes&&e&&e.constructor===qt?(tt(),e.then(t=>(we(),t),t=>(we(),W(t)))):e}function xo(e){++sn,G.echoes&&--G.echoes!=0||(G.echoes=G.id=0),zt.push(U),Ue(e,!0)}function Ao(){var e=zt[zt.length-1];zt.pop(),Ue(e,!1)}function Ue(e,t){var n=U;if((t?!G.echoes||bn++&&e===U:!bn||--bn&&e===U)||zi(t?xo.bind(null,e):Ao),e!==U&&(U=e,n===Ye&&(Ye.env=Wi()),Lr)){var r=Ye.env.Promise,i=e.env;nn.then=i.nthen,r.prototype.then=i.gthen,(n.global||e.global)&&(Object.defineProperty(j,"Promise",i.PromiseProp),r.all=i.all,r.race=i.race,r.resolve=i.resolve,r.reject=i.reject,i.allSettled&&(r.allSettled=i.allSettled),i.any&&(r.any=i.any))}}function Wi(){var e=j.Promise;return Lr?{Promise:e,PromiseProp:Object.getOwnPropertyDescriptor(j,"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,r,i){var s=U;try{return Ue(e,!0),t(n,r,i)}finally{Ue(s,!1)}}function zi(e){ji.call($n,e)}function on(e,t,n,r){return typeof e!="function"?e:function(){var i=U;n&&tt(),Ue(t,!0);try{return e.apply(this,arguments)}finally{Ue(i,!1),r&&zi(we)}}}function qr(e,t){return function(n,r){return e.call(this,on(n,t),on(r,t))}}(""+ji).indexOf("[native code]")===-1&&(tt=we=T);const Vr="unhandledrejection";function Wr(e,t){var n;try{n=t.onuncatched(e)}catch{}if(n!==!1)try{var r,i={promise:t,reason:e};if(j.document&&document.createEvent?((r=document.createEvent("Event")).initEvent(Vr,!0,!0),Q(r,i)):j.CustomEvent&&Q(r=new CustomEvent(Vr,{detail:i}),i),r&&j.dispatchEvent&&(dispatchEvent(r),!j.PromiseRejectionEvent&&j.onunhandledrejection))try{j.onunhandledrejection(r)}catch{}le&&r&&!r.defaultPrevented&&console.warn(`Unhandled rejection: ${e.stack||e}`)}catch{}}var W=L.reject;function Jn(e,t,n,r){if(e.idbdb&&(e._state.openComplete||U.letThrough||e._vip)){var i=e._createTransaction(t,n,e._dbSchema);try{i.create(),e._state.PR1398_maxLoop=3}catch(s){return s.name===Er.InvalidState&&e.isOpen()&&--e._state.PR1398_maxLoop>0?(console.warn("Dexie: Need to reopen db"),e._close(),e.open().then(()=>Jn(e,t,n,r))):W(s)}return i._promise(t,(s,o)=>Ie(()=>(U.trans=i,r(s,o,i)))).then(s=>i._completion.then(()=>s))}if(e._state.openComplete)return W(new x.DatabaseClosed(e._state.dbOpenError));if(!e._state.isBeingOpened){if(!e._options.autoOpen)return W(new x.DatabaseClosed);e.open().catch(T)}return e._state.dbReadyPromise.then(()=>Jn(e,t,n,r))}const zr="3.2.7",De="￿",Qn=-1/0,ue="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",Hi="String expected.",ht=[],hn=typeof navigator<"u"&&/(MSIE|Trident|Edge)/.test(navigator.userAgent),Ro=hn,Co=hn,Gi=e=>!/(dexie\.js|dexie\.min\.js)/.test(e),fn="__dbnames",_n="readonly",Sn="readwrite";function Ke(e,t){return e?t?function(){return e.apply(this,arguments)&&t.apply(this,arguments)}:e:t}const Yi={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,r){const i=this._tx||U.trans,s=this.name;function o(l,c,u){if(!u.schema[s])throw new x.NotFound("Table "+s+" not part of transaction");return n(u.idbtrans,u)}const a=At();try{return i&&i.db===this.db?i===U.trans?i._promise(t,o,r):Ie(()=>i._promise(t,o,r),{trans:i,transless:U.transless||U}):Jn(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",r=>this.core.get({trans:r,key:t}).then(i=>this.hook.reading.fire(i))).then(n)}where(t){if(typeof t=="string")return new this.db.WhereClause(this,t);if(Y(t))return new this.db.WhereClause(this,`[${t.join("+")}]`);const n=$(t);if(n.length===1)return this.where(n[0]).equals(t[n[0]]);const r=this.schema.indexes.concat(this.schema.primKey).filter(c=>{if(c.compound&&n.every(u=>c.keyPath.indexOf(u)>=0)){for(let u=0;u<n.length;++u)if(n.indexOf(c.keyPath[u])===-1)return!1;return!0}return!1}).sort((c,u)=>c.keyPath.length-u.keyPath.length)[0];if(r&&this.db._maxKey!==De){const c=r.keyPath.slice(0,n.length);return this.where(c).equals(c.map(u=>t[u]))}!r&&le&&console.warn(`The query ${JSON.stringify(t)} on ${this.name} would benefit of a compound index [${n.join("+")}]`);const{idxByName:i}=this.schema,s=this.db._deps.indexedDB;function o(c,u){try{return s.cmp(c,u)===0}catch{return!1}}const[a,l]=n.reduce(([c,u],p)=>{const d=i[p],h=t[p];return[c||d,c||!d?Ke(u,d&&d.multi?g=>{const y=ge(g,p);return Y(y)&&y.some(w=>o(h,w))}:g=>o(h,ge(g,p))):u]},[null,null]);return a?this.where(a.name).equals(t[a.keyPath]).filter(l):r?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,Y(t)?`[${t.join("+")}]`:t))}reverse(){return this.toCollection().reverse()}mapToClass(t){this.schema.mappedClass=t;const n=r=>{if(!r)return r;const i=Object.create(t.prototype);for(var s in r)if(ne(r,s))try{i[s]=r[s]}catch{}return i};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){Q(this,t)})}add(t,n){const{auto:r,keyPath:i}=this.schema.primKey;let s=t;return i&&r&&(s=Mt(i)(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(i)try{ie(t,i,o)}catch{}return o})}update(t,n){if(typeof t!="object"||Y(t))return this.where(":id").equals(t).modify(n);{const r=ge(t,this.schema.primKey.keyPath);if(r===void 0)return W(new x.InvalidArgument("Given object does not contain its primary key"));try{typeof n!="function"?$(n).forEach(i=>{ie(t,i,n[i])}):n(t,{value:t,primKey:r})}catch{}return this.where(":id").equals(r).modify(n)}}put(t,n){const{auto:r,keyPath:i}=this.schema.primKey;let s=t;return i&&r&&(s=Mt(i)(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(i)try{ie(t,i,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:Yi})).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(r=>r.map(i=>this.hook.reading.fire(i))))}bulkAdd(t,n,r){const i=Array.isArray(n)?n:void 0,s=(r=r||(i?void 0:n))?r.allKeys:void 0;return this._trans("readwrite",o=>{const{auto:a,keyPath:l}=this.schema.primKey;if(l&&i)throw new x.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(i&&i.length!==t.length)throw new x.InvalidArgument("Arguments objects and keys must have the same length");const c=t.length;let u=l&&a?t.map(Mt(l)):t;return this.core.mutate({trans:o,type:"add",keys:i,values:u,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 ${c} operations failed`,g)})})}bulkPut(t,n,r){const i=Array.isArray(n)?n:void 0,s=(r=r||(i?void 0:n))?r.allKeys:void 0;return this._trans("readwrite",o=>{const{auto:a,keyPath:l}=this.schema.primKey;if(l&&i)throw new x.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(i&&i.length!==t.length)throw new x.InvalidArgument("Arguments objects and keys must have the same length");const c=t.length;let u=l&&a?t.map(Mt(l)):t;return this.core.mutate({trans:o,type:"put",keys:i,values:u,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 ${c} operations failed`,g)})})}bulkDelete(t){const n=t.length;return this._trans("readwrite",r=>this.core.mutate({trans:r,type:"delete",keys:t})).then(({numFailures:r,lastResult:i,failures:s})=>{if(r===0)return i;throw new dt(`${this.name}.bulkDelete(): ${r} of ${n} operations failed`,s)})}}function ft(e){var t={},n=function(o,a){if(a){for(var l=arguments.length,c=new Array(l-1);--l;)c[l-1]=arguments[l];return t[o].subscribe.apply(null,c),e}if(typeof o=="string")return t[o]};n.addEventType=s;for(var r=1,i=arguments.length;r<i;++r)s(arguments[r]);return n;function s(o,a,l){if(typeof o!="object"){var c;a||(a=Eo),l||(l=T);var u={subscribers:[],fire:l,subscribe:function(p){u.subscribers.indexOf(p)===-1&&(u.subscribers.push(p),u.fire=a(u.fire,p))},unsubscribe:function(p){u.subscribers=u.subscribers.filter(function(d){return d!==p}),u.fire=u.subscribers.reduce(a,l)}};return t[o]=n[o]=u,u}$(c=o).forEach(function(p){var d=c[p];if(Y(d))s(p,c[p][0],c[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){Ai(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 En(e,t){e.filter=Ke(e.filter,t)}function kn(e,t,n){var r=e.replayFilter;e.replayFilter=r?()=>Ke(r(),t()):t,e.justLimit=n&&!r}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 Hr(e,t,n){const r=Ht(e,t.schema);return t.openCursor({trans:n,values:!e.keysOnly,reverse:e.dir==="prev",unique:!!e.unique,query:{index:r,range:e.range}})}function Ft(e,t,n,r){const i=e.replayFilter?Ke(e.filter,e.replayFilter()):e.filter;if(e.or){const s={},o=(a,l,c)=>{if(!i||i(l,c,d=>l.stop(d),d=>l.fail(d))){var u=l.primaryKey,p=""+u;p==="[object ArrayBuffer]"&&(p=""+new Uint8Array(u)),ne(s,p)||(s[p]=!0,t(a,l,c))}};return Promise.all([e.or._iterate(o,n),Gr(Hr(e,r,n),e.algorithm,o,!e.keysOnly&&e.valueMapper)])}return Gr(Hr(e,r,n),Ke(e.algorithm,i),t,!e.keysOnly&&e.valueMapper)}function Gr(e,t,n,r){var i=K(r?(s,o,a)=>n(r(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=T},a=>{s.fail(a),o=T})||i(s.value,s,a=>o=a),o()})})}function J(e,t){try{const n=Yr(e),r=Yr(t);if(n!==r)return n==="Array"?1:r==="Array"?-1:n==="binary"?1:r==="binary"?-1:n==="string"?1:r==="string"?-1:n==="Date"?1:r!=="Date"?NaN:-1;switch(n){case"number":case"Date":case"string":return e>t?1:e<t?-1:0;case"binary":return function(i,s){const o=i.length,a=s.length,l=o<a?o:a;for(let c=0;c<l;++c)if(i[c]!==s[c])return i[c]<s[c]?-1:1;return o===a?0:o<a?-1:1}(Jr(e),Jr(t));case"Array":return function(i,s){const o=i.length,a=s.length,l=o<a?o:a;for(let c=0;c<l;++c){const u=J(i[c],s[c]);if(u!==0)return u}return o===a?0:o<a?-1:1}(e,t)}}catch{}return NaN}function Yr(e){const t=typeof e;if(t!=="object")return t;if(ArrayBuffer.isView(e))return"binary";const n=jn(e);return n==="ArrayBuffer"?"binary":n}function Jr(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 r=this._ctx;return r.error?r.table._trans(null,W.bind(null,r.error)):r.table._trans("readonly",t).then(n)}_write(t){var n=this._ctx;return n.error?n.table._trans(null,W.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),r=Object.create(this._ctx);return t&&Q(r,t),n._ctx=r,n}raw(){return this._ctx.valueMapper=null,this}each(t){var n=this._ctx;return this._read(r=>Ft(n,t,r,n.table.core))}count(t){return this._read(n=>{const r=this._ctx,i=r.table.core;if(Ve(r,!0))return i.count({trans:n,query:{index:Ht(r,i.schema),range:r.range}}).then(o=>Math.min(o,r.limit));var s=0;return Ft(r,()=>(++s,!1),n,i).then(()=>s)}).then(t)}sortBy(t,n){const r=t.split(".").reverse(),i=r[0],s=r.length-1;function o(c,u){return u?o(c[r[u]],u-1):c[i]}var a=this._ctx.dir==="next"?1:-1;function l(c,u){var p=o(c,s),d=o(u,s);return p<d?-a:p>d?a:0}return this.toArray(function(c){return c.sort(l)}).then(n)}toArray(t){return this._read(n=>{var r=this._ctx;if(r.dir==="next"&&Ve(r,!0)&&r.limit>0){const{valueMapper:i}=r,s=Ht(r,r.table.core.schema);return r.table.core.query({trans:n,limit:r.limit,values:!0,query:{index:s,range:r.range}}).then(({result:o})=>i?o.map(i):o)}{const i=[];return Ft(r,s=>i.push(s),n,r.table.core).then(()=>i)}},t)}offset(t){var n=this._ctx;return t<=0||(n.offset+=t,Ve(n)?kn(n,()=>{var r=t;return(i,s)=>r===0||(r===1?(--r,!1):(s(()=>{i.advance(r),r=0}),!1))}):kn(n,()=>{var r=t;return()=>--r<0})),this}limit(t){return this._ctx.limit=Math.min(this._ctx.limit,t),kn(this._ctx,()=>{var n=t;return function(r,i,s){return--n<=0&&i(s),n>=0}},!0),this}until(t,n){return En(this._ctx,function(r,i,s){return!t(r.value)||(i(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,r;return En(this._ctx,function(i){return t(i.value)}),n=this._ctx,r=t,n.isMatch=Ke(n.isMatch,r),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(r,i){t(i.key,i)})}eachUniqueKey(t){return this._ctx.unique="unique",this.eachKey(t)}eachPrimaryKey(t){var n=this._ctx;return n.keysOnly=!n.isMatch,this.each(function(r,i){t(i.primaryKey,i)})}keys(t){var n=this._ctx;n.keysOnly=!n.isMatch;var r=[];return this.each(function(i,s){r.push(s.key)}).then(function(){return r}).then(t)}primaryKeys(t){var n=this._ctx;if(n.dir==="next"&&Ve(n,!0)&&n.limit>0)return this._read(i=>{var s=Ht(n,n.table.core.schema);return n.table.core.query({trans:i,values:!1,limit:n.limit,query:{index:s,range:n.range}})}).then(({result:i})=>i).then(t);n.keysOnly=!n.isMatch;var r=[];return this.each(function(i,s){r.push(s.primaryKey)}).then(function(){return r}).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 r={};return En(this._ctx,function(i){var s=i.primaryKey.toString(),o=ne(r,s);return r[s]=!0,!o}),this}modify(t){var n=this._ctx;return this._write(r=>{var i;if(typeof t=="function")i=t;else{var s=$(t),o=s.length;i=function(y){for(var w=!1,f=0;f<o;++f){var m=s[f],b=t[m];ge(y,m)!==b&&(ie(y,m,b),w=!0)}return w}}const a=n.table.core,{outbound:l,extractKey:c}=a.schema.primaryKey,u=this.db._options.modifyChunkSize||200,p=[];let d=0;const h=[],g=(y,w)=>{const{failures:f,numFailures:m}=w;d+=y-m;for(let b of $(f))p.push(f[b])};return this.clone().primaryKeys().then(y=>{const w=f=>{const m=Math.min(u,y.length-f);return a.getMany({trans:r,keys:y.slice(f,f+m),cache:"immutable"}).then(b=>{const v=[],E=[],k=l?[]:null,_=[];for(let S=0;S<m;++S){const B=b[S],D={value:xt(B),primKey:y[f+S]};i.call(D,D.value,D)!==!1&&(D.value==null?_.push(y[f+S]):l||J(c(B),c(D.value))===0?(E.push(D.value),l&&k.push(y[f+S])):(_.push(y[f+S]),v.push(D.value)))}const A=Ve(n)&&n.limit===1/0&&(typeof t!="function"||t===Ln)&&{index:n.index,range:n.range};return Promise.resolve(v.length>0&&a.mutate({trans:r,type:"add",values:v}).then(S=>{for(let B in S.failures)_.splice(parseInt(B),1);g(v.length,S)})).then(()=>(E.length>0||A&&typeof t=="object")&&a.mutate({trans:r,type:"put",keys:k,values:E,criteria:A,changeSpec:typeof t!="function"&&t}).then(S=>g(E.length,S))).then(()=>(_.length>0||A&&t===Ln)&&a.mutate({trans:r,type:"delete",keys:_,criteria:A}).then(S=>g(_.length,S))).then(()=>y.length>f+m&&w(f+u))})};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(r=>{const{primaryKey:i}=t.table.core.schema,s=n;return t.table.core.count({trans:r,query:{index:i,range:s}}).then(o=>t.table.core.mutate({trans:r,type:"deleteRange",range:s}).then(({failures:a,lastResult:l,results:c,numFailures:u})=>{if(u)throw new tn("Could not delete some values",Object.keys(a).map(p=>a[p]),o-u);return o-u}))}):this.modify(Ln)}}const Ln=(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 Z(e,t,n){var r=e instanceof Qi?new e.Collection(e):e;return r._ctx.error=n?new n(t):new TypeError(t),r}function We(e){return new e.Collection(e,()=>Ji("")).limit(0)}function Bo(e,t,n,r,i,s){for(var o=Math.min(e.length,r.length),a=-1,l=0;l<o;++l){var c=t[l];if(c!==r[l])return i(e[l],n[l])<0?e.substr(0,l)+n[l]+n.substr(l+1):i(e[l],r[l])<0?e.substr(0,l)+r[l]+n.substr(l+1):a>=0?e.substr(0,a)+t[a]+n.substr(a+1):null;i(e[l],c)<0&&(a=l)}return o<r.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)+r[a]+n.substr(a+1)}function jt(e,t,n,r){var i,s,o,a,l,c,u,p=n.length;if(!n.every(y=>typeof y=="string"))return Z(e,Hi);function d(y){i=function(f){return f==="next"?m=>m.toUpperCase():m=>m.toLowerCase()}(y),s=function(f){return f==="next"?m=>m.toLowerCase():m=>m.toUpperCase()}(y),o=y==="next"?Po:To;var w=n.map(function(f){return{lower:s(f),upper:i(f)}}).sort(function(f,m){return o(f.lower,m.lower)});a=w.map(function(f){return f.upper}),l=w.map(function(f){return f.lower}),c=y,u=y==="next"?"":r}d("next");var h=new e.Collection(e,()=>be(a[0],l[p-1]+r));h._ondirectionchange=function(y){d(y)};var g=0;return h._addAlgorithm(function(y,w,f){var m=y.key;if(typeof m!="string")return!1;var b=s(m);if(t(b,l,g))return!0;for(var v=null,E=g;E<p;++E){var k=Bo(m,b,a[E],l[E],o,c);k===null&&v===null?g=E+1:(v===null||o(v,k)>0)&&(v=k)}return w(v!==null?function(){y.continue(v+u)}:f),!1}),h}function be(e,t,n,r){return{type:2,lower:e,upper:t,lowerOpen:n,upperOpen:r}}function Ji(e){return{type:1,lower:e,upper:e}}class Qi{get Collection(){return this._ctx.table.db.Collection}between(t,n,r,i){r=r!==!1,i=i===!0;try{return this._cmp(t,n)>0||this._cmp(t,n)===0&&(r||i)&&(!r||!i)?We(this):new this.Collection(this,()=>be(t,n,!r,!i))}catch{return Z(this,ue)}}equals(t){return t==null?Z(this,ue):new this.Collection(this,()=>Ji(t))}above(t){return t==null?Z(this,ue):new this.Collection(this,()=>be(t,void 0,!0))}aboveOrEqual(t){return t==null?Z(this,ue):new this.Collection(this,()=>be(t,void 0,!1))}below(t){return t==null?Z(this,ue):new this.Collection(this,()=>be(void 0,t,!1,!0))}belowOrEqual(t){return t==null?Z(this,ue):new this.Collection(this,()=>be(void 0,t))}startsWith(t){return typeof t!="string"?Z(this,Hi):this.between(t,t+De,!0,!0)}startsWithIgnoreCase(t){return t===""?this.startsWith(t):jt(this,(n,r)=>n.indexOf(r[0])===0,[t],De)}equalsIgnoreCase(t){return jt(this,(n,r)=>n===r[0],[t],"")}anyOfIgnoreCase(){var t=he.apply(ze,arguments);return t.length===0?We(this):jt(this,(n,r)=>r.indexOf(n)!==-1,t,"")}startsWithAnyOfIgnoreCase(){var t=he.apply(ze,arguments);return t.length===0?We(this):jt(this,(n,r)=>r.some(i=>n.indexOf(i)===0),t,De)}anyOf(){const t=he.apply(ze,arguments);let n=this._cmp;try{t.sort(n)}catch{return Z(this,ue)}if(t.length===0)return We(this);const r=new this.Collection(this,()=>be(t[0],t[t.length-1]));r._ondirectionchange=s=>{n=s==="next"?this._ascending:this._descending,t.sort(n)};let i=0;return r._addAlgorithm((s,o,a)=>{const l=s.key;for(;n(l,t[i])>0;)if(++i,i===t.length)return o(a),!1;return n(l,t[i])===0||(o(()=>{s.continue(t[i])}),!1)}),r}notEqual(t){return this.inAnyRange([[Qn,t],[t,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})}noneOf(){const t=he.apply(ze,arguments);if(t.length===0)return new this.Collection(this);try{t.sort(this._ascending)}catch{return Z(this,ue)}const n=t.reduce((r,i)=>r?r.concat([[r[r.length-1][1],i]]):[[Qn,i]],null);return n.push([t[t.length-1],this.db._maxKey]),this.inAnyRange(n,{includeLowers:!1,includeUppers:!1})}inAnyRange(t,n){const r=this._cmp,i=this._ascending,s=this._descending,o=this._min,a=this._max;if(t.length===0)return We(this);if(!t.every(m=>m[0]!==void 0&&m[1]!==void 0&&i(m[0],m[1])<=0))return Z(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,c=n&&n.includeUppers===!0;let u,p=i;function d(m,b){return p(m[0],b[0])}try{u=t.reduce(function(m,b){let v=0,E=m.length;for(;v<E;++v){const k=m[v];if(r(b[0],k[1])<0&&r(b[1],k[0])>0){k[0]=o(k[0],b[0]),k[1]=a(k[1],b[1]);break}}return v===E&&m.push(b),m},[]),u.sort(d)}catch{return Z(this,ue)}let h=0;const g=c?m=>i(m,u[h][1])>0:m=>i(m,u[h][1])>=0,y=l?m=>s(m,u[h][0])>0:m=>s(m,u[h][0])>=0;let w=g;const f=new this.Collection(this,()=>be(u[0][0],u[u.length-1][1],!l,!c));return f._ondirectionchange=m=>{m==="next"?(w=g,p=i):(w=y,p=s),u.sort(d)},f._addAlgorithm((m,b,v)=>{for(var E=m.key;w(E);)if(++h,h===u.length)return b(v),!1;return!!function(k){return!g(k)&&!y(k)}(E)||(this._cmp(E,u[h][1])===0||this._cmp(E,u[h][0])===0||b(()=>{p===i?m.continue(u[h][0]):m.continue(u[h][1])}),!1)}),f}startsWithAnyOf(){const t=he.apply(ze,arguments);return t.every(n=>typeof n=="string")?t.length===0?We(this):this.inAnyRange(t.map(n=>[n,n+De])):Z(this,"startsWithAnyOf() only works with strings")}}function se(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",Ee="x-storagemutated-1",xe=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,r=this.db._state.dbOpenError;if(at(!this.idbtrans),!t&&!n)switch(r&&r.name){case"DatabaseClosedError":throw new x.DatabaseClosed(r);case"MissingAPIError":throw new x.MissingAPI(r.message,r);default:throw new x.OpenFailed(r)}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(i=>{Et(i),this._reject(t.error)}),t.onabort=K(i=>{Et(i),this.active&&this._reject(new x.Abort(t.error)),this.active=!1,this.on("abort").fire(i)}),t.oncomplete=K(()=>{this.active=!1,this._resolve(),"mutatedParts"in t&&xe.storagemutated.fire(t.mutatedParts)}),this}_promise(t,n,r){if(t==="readwrite"&&this.mode!=="readwrite")return W(new x.ReadOnly("Transaction is readonly"));if(!this.active)return W(new x.TransactionInactive);if(this._locked())return new L((s,o)=>{this._blockedFuncs.push([()=>{this._promise(t,n,r).then(s,o)},U])});if(r)return Ie(()=>{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 i=new L((s,o)=>{var a=n(s,o,this);a&&a.then&&a.then(s,o)});return i._lib=!0,i}_root(){return this.parent?this.parent._root():this}waitFor(t){var n=this._root();const r=L.resolve(t);if(n._waitingFor)n._waitingFor=n._waitingFor.then(()=>r);else{n._waitingFor=r,n._waitingQueue=[];var i=n.idbtrans.objectStore(n.storeNames[0]);(function o(){for(++n._spinCount;n._waitingQueue.length;)n._waitingQueue.shift()();n._waitingFor&&(i.get(-1/0).onsuccess=o)})()}var s=n._waitingFor;return new L((o,a)=>{r.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(ne(n,t))return n[t];const r=this.schema[t];if(!r)throw new x.NotFound("Table "+t+" not part of transaction");const i=new this.db.Table(t,r,this);return i.core=this.db.core.table(t),n[t]=i,i}}function Xn(e,t,n,r,i,s,o){return{name:e,keyPath:t,unique:n,multi:r,auto:i,compound:s,src:(n&&!o?"&":"")+(r?"*":"")+(i?"++":"")+Xi(t)}}function Xi(e){return typeof e=="string"?e:e?"["+[].join.call(e,"+")+"]":""}function Zi(e,t,n){return{name:e,primKey:t,indexes:n,mappedClass:null,idxByName:Ri(n,r=>[r.name,r])}}let Lt=e=>{try{return e.only([[]]),Lt=()=>[[]],[[]]}catch{return Lt=()=>De,De}};function Zn(e){return e==null?()=>{}:typeof e=="string"?function(t){return t.split(".").length===1?r=>r[t]:r=>ge(r,t)}(e):t=>ge(t,e)}function Qr(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 r(l){if(l.type===3)return null;if(l.type===4)throw new Error("Cannot convert never type to IDBKeyRange");const{lower:c,upper:u,lowerOpen:p,upperOpen:d}=l;return c===void 0?u===void 0?null:t.upperBound(u,!!d):u===void 0?t.lowerBound(c,!!p):t.bound(c,u,!!p,!!d)}const{schema:i,hasGetAll:s}=function(l,c){const u=Qr(l.objectStoreNames);return{schema:{name:l.name,tables:u.map(p=>c.objectStore(p)).map(p=>{const{keyPath:d,autoIncrement:h}=p,g=Y(d),y=d==null,w={},f={name:p.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:y,compound:g,keyPath:d,autoIncrement:h,unique:!0,extractKey:Zn(d)},indexes:Qr(p.indexNames).map(m=>p.index(m)).map(m=>{const{name:b,unique:v,multiEntry:E,keyPath:k}=m,_={name:b,compound:Y(k),keyPath:k,unique:v,multiEntry:E,extractKey:Zn(k)};return w[mt(k)]=_,_}),getIndexByKeyPath:m=>w[mt(m)]};return w[":id"]=f.primaryKey,d!=null&&(w[mt(d)]=f.primaryKey),f})},hasGetAll:u.length>0&&"getAll"in c.objectStore(u[0])&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604)}}(e,n),o=i.tables.map(l=>function(c){const u=c.name;return{name:u,schema:c,mutate:function({trans:p,type:d,keys:h,values:g,range:y}){return new Promise((w,f)=>{w=K(w);const m=p.objectStore(u),b=m.keyPath==null,v=d==="put"||d==="add";if(!v&&d!=="delete"&&d!=="deleteRange")throw new Error("Invalid operation type: "+d);const{length:E}=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(E===0)return w({numFailures:0,failures:{},results:[],lastResult:void 0});let k;const _=[],A=[];let S=0;const B=q=>{++S,Et(q)};if(d==="deleteRange"){if(y.type===4)return w({numFailures:S,failures:A,results:[],lastResult:void 0});y.type===3?_.push(k=m.clear()):_.push(k=m.delete(r(y)))}else{const[q,V]=v?b?[g,h]:[g,null]:[h,null];if(v)for(let F=0;F<E;++F)_.push(k=V&&V[F]!==void 0?m[d](q[F],V[F]):m[d](q[F])),k.onerror=B;else for(let F=0;F<E;++F)_.push(k=m[d](q[F])),k.onerror=B}const D=q=>{const V=q.target.result;_.forEach((F,ce)=>F.error!=null&&(A[ce]=F.error)),w({numFailures:S,failures:A,results:d==="delete"?h:_.map(F=>F.result),lastResult:V})};k.onerror=q=>{B(q),D(q)},k.onsuccess=D})},getMany:({trans:p,keys:d})=>new Promise((h,g)=>{h=K(h);const y=p.objectStore(u),w=d.length,f=new Array(w);let m,b=0,v=0;const E=_=>{const A=_.target;f[A._pos]=A.result,++v===b&&h(f)},k=se(g);for(let _=0;_<w;++_)d[_]!=null&&(m=y.get(d[_]),m._pos=_,m.onsuccess=E,m.onerror=k,++b);b===0&&h(f)}),get:({trans:p,key:d})=>new Promise((h,g)=>{h=K(h);const y=p.objectStore(u).get(d);y.onsuccess=w=>h(w.target.result),y.onerror=se(g)}),query:function(p){return d=>new Promise((h,g)=>{h=K(h);const{trans:y,values:w,limit:f,query:m}=d,b=f===1/0?void 0:f,{index:v,range:E}=m,k=y.objectStore(u),_=v.isPrimaryKey?k:k.index(v.name),A=r(E);if(f===0)return h({result:[]});if(p){const S=w?_.getAll(A,b):_.getAllKeys(A,b);S.onsuccess=B=>h({result:B.target.result}),S.onerror=se(g)}else{let S=0;const B=w||!("openKeyCursor"in _)?_.openCursor(A):_.openKeyCursor(A),D=[];B.onsuccess=q=>{const V=B.result;return V?(D.push(w?V.value:V.primaryKey),++S===f?h({result:D}):void V.continue()):h({result:D})},B.onerror=se(g)}})}(s),openCursor:function({trans:p,values:d,query:h,reverse:g,unique:y}){return new Promise((w,f)=>{w=K(w);const{index:m,range:b}=h,v=p.objectStore(u),E=m.isPrimaryKey?v:v.index(m.name),k=g?y?"prevunique":"prev":y?"nextunique":"next",_=d||!("openKeyCursor"in E)?E.openCursor(r(b),k):E.openKeyCursor(r(b),k);_.onerror=se(f),_.onsuccess=K(A=>{const S=_.result;if(!S)return void w(null);S.___id=++Fo,S.done=!1;const B=S.continue.bind(S);let D=S.continuePrimaryKey;D&&(D=D.bind(S));const q=S.advance.bind(S),V=()=>{throw new Error("Cursor not stopped")};S.trans=p,S.stop=S.continue=S.continuePrimaryKey=S.advance=()=>{throw new Error("Cursor not started")},S.fail=K(f),S.next=function(){let F=1;return this.start(()=>F--?this.continue():this.stop()).then(()=>this)},S.start=F=>{const ce=new Promise((H,Ae)=>{H=K(H),_.onerror=se(Ae),S.fail=Ae,S.stop=it=>{S.stop=S.continue=S.continuePrimaryKey=S.advance=V,H(it)}}),M=()=>{if(_.result)try{F()}catch(H){S.fail(H)}else S.done=!0,S.start=()=>{throw new Error("Cursor behind last entry")},S.stop()};return _.onsuccess=K(H=>{_.onsuccess=M,M()}),S.continue=B,S.continuePrimaryKey=D,S.advance=q,M(),ce},w(S)},f)})},count({query:p,trans:d}){const{index:h,range:g}=p;return new Promise((y,w)=>{const f=d.objectStore(u),m=h.isPrimaryKey?f:f.index(h.name),b=r(g),v=b?m.count(b):m.count();v.onsuccess=K(E=>y(E.target.result)),v.onerror=se(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:i}}function er({_novip:e},t){const n=t.db,r=function(i,s,{IDBKeyRange:o,indexedDB:a},l){return{dbcore:function(u,p){return p.reduce((d,{create:h})=>({...d,...h(d)}),u)}(jo(s,o,l),i.dbcore)}}(e._middlewares,n,e._deps,t);e.core=r.dbcore,e.tables.forEach(i=>{const s=i.name;e.core.schema.tables.some(o=>o.name===s)&&(i.core=e.core.table(s),e[s]instanceof e.Table&&(e[s].core=i.core))})}function an({_novip:e},t,n,r){n.forEach(i=>{const s=r[i];t.forEach(o=>{const a=br(o,i);(!a||"value"in a&&a.value===void 0)&&(o===e.Transaction.prototype||o instanceof e.Transaction?ye(o,i,{get(){return this.table(i)},set(l){Ui(this,i,{value:l,writable:!0,configurable:!0,enumerable:!0})}}):o[i]=new e.Table(i,s))})})}function tr({_novip:e},t){t.forEach(n=>{for(let r in n)n[r]instanceof e.Table&&delete n[r]})}function Ko(e,t){return e._cfg.version-t._cfg.version}function No(e,t,n,r){const i=e._dbSchema,s=e._createTransaction("readwrite",e._storeNames,i);s.create(n),s._completion.catch(r);const o=s._reject.bind(s),a=U.transless||U;Ie(()=>{U.trans=s,U.transless=a,t===0?($(i).forEach(l=>{In(n,l,i[l].primKey,i[l].indexes)}),er(e,n),L.follow(()=>e.on.populate.fire(s)).catch(o)):function({_novip:l},c,u,p){const d=[],h=l._versions;let g=l._dbSchema=rr(l,l.idbdb,p),y=!1;const w=h.filter(m=>m._cfg.version>=c);function f(){return d.length?L.resolve(d.shift()(u.idbtrans)).then(f):L.resolve()}return w.forEach(m=>{d.push(()=>{const b=g,v=m._cfg.dbschema;ir(l,b,p),ir(l,v,p),g=l._dbSchema=v;const E=es(b,v);E.add.forEach(_=>{In(p,_[0],_[1].primKey,_[1].indexes)}),E.change.forEach(_=>{if(_.recreate)throw new x.Upgrade("Not yet support for changing primary key");{const A=p.objectStore(_.name);_.add.forEach(S=>nr(A,S)),_.change.forEach(S=>{A.deleteIndex(S.name),nr(A,S)}),_.del.forEach(S=>A.deleteIndex(S))}});const k=m._cfg.contentUpgrade;if(k&&m._cfg.version>c){er(l,p),u._memoizedTables={},y=!0;let _=Ci(v);E.del.forEach(D=>{_[D]=b[D]}),tr(l,[l.Transaction.prototype]),an(l,[l.Transaction.prototype],$(_),_),u.schema=_;const A=_r(k);let S;A&&tt();const B=L.follow(()=>{if(S=k(u),S&&A){var D=we.bind(null,null);S.then(D,D)}});return S&&typeof S.then=="function"?L.resolve(S):B.then(()=>S)}}),d.push(b=>{(!y||!Ro)&&function(v,E){[].slice.call(E.db.objectStoreNames).forEach(k=>v[k]==null&&E.db.deleteObjectStore(k))}(m._cfg.dbschema,b),tr(l,[l.Transaction.prototype]),an(l,[l.Transaction.prototype],l._storeNames,l._dbSchema),u.schema=l._dbSchema})}),f().then(()=>{var m,b;b=p,$(m=g).forEach(v=>{b.db.objectStoreNames.contains(v)||In(b,v,m[v].primKey,m[v].indexes)})})}(e,t,s,n).catch(o)})}function es(e,t){const n={del:[],add:[],change:[]};let r;for(r in e)t[r]||n.del.push(r);for(r in t){const i=e[r],s=t[r];if(i){const o={name:r,def:s,recreate:!1,del:[],add:[],change:[]};if(""+(i.primKey.keyPath||"")!=""+(s.primKey.keyPath||"")||i.primKey.auto!==s.primKey.auto&&!hn)o.recreate=!0,n.change.push(o);else{const a=i.idxByName,l=s.idxByName;let c;for(c in a)l[c]||o.del.push(c);for(c in l){const u=a[c],p=l[c];u?u.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([r,s])}return n}function In(e,t,n,r){const i=e.db.createObjectStore(t,n.keyPath?{keyPath:n.keyPath,autoIncrement:n.auto}:{autoIncrement:n.auto});return r.forEach(s=>nr(i,s)),i}function nr(e,t){e.createIndex(t.name,t.keyPath,{unique:t.unique,multiEntry:t.multi})}function rr(e,t,n){const r={};return en(t.objectStoreNames,0).forEach(i=>{const s=n.objectStore(i);let o=s.keyPath;const a=Xn(Xi(o),o||"",!1,!1,!!s.autoIncrement,o&&typeof o!="string",!0),l=[];for(let u=0;u<s.indexNames.length;++u){const p=s.index(s.indexNames[u]);o=p.keyPath;var c=Xn(p.name,o,!!p.unique,!!p.multiEntry,!1,o&&typeof o!="string",!1);l.push(c)}r[i]=Zi(i,a,l)}),r}function ir({_novip:e},t,n){const r=n.db.objectStoreNames;for(let i=0;i<r.length;++i){const s=r[i],o=n.objectStore(s);e._hasGetAll="getAll"in o;for(let a=0;a<o.indexNames.length;++a){const l=o.indexNames[a],c=o.index(l).keyPath,u=typeof c=="string"?c:"["+en(c).join("+")+"]";if(t[s]){const p=t[s].idxByName[u];p&&(p.name=l,delete t[s].idxByName[u],t[s].idxByName[l]=p)}}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&j.WorkerGlobalScope&&j instanceof j.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(e._hasGetAll=!1)}class $o{_parseStoresSpec(t,n){$(t).forEach(r=>{if(t[r]!==null){var i=t[r].split(",").map((o,a)=>{const l=(o=o.trim()).replace(/([&*]|\+\+)/g,""),c=/^\[/.test(l)?l.match(/^\[(.*)\]$/)[1].split("+"):l;return Xn(l,c||null,/\&/.test(o),/\*/.test(o),/\+\+/.test(o),Y(c),a===0)}),s=i.shift();if(s.multi)throw new x.Schema("Primary key cannot be multi-valued");i.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[r]=Zi(r,s,i)}})}stores(t){const n=this.db;this._cfg.storesSource=this._cfg.storesSource?Q(this._cfg.storesSource,t):t;const r=n._versions,i={};let s={};return r.forEach(o=>{Q(i,o._cfg.storesSource),s=o._cfg.dbschema={},o._parseStoresSpec(i,s)}),n._dbSchema=s,tr(n,[n._allTables,n,n.Transaction.prototype]),an(n,[n._allTables,n,n.Transaction.prototype,this._cfg.tables],$(s),s),n._storeNames=$(s),this}upgrade(t){return this._cfg.contentUpgrade=kr(this._cfg.contentUpgrade||T,t),this}}function xr(e,t){let n=e._dbNamesDB;return n||(n=e._dbNamesDB=new Me(fn,{addons:[],indexedDB:e,IDBKeyRange:t}),n.version(1).stores({dbnames:"name"})),n.table("dbnames")}function Ar(e){return e&&typeof e.databases=="function"}function sr(e){return Ie(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?W(t.dbOpenError):e);le&&(t.openCanceller._stackHolder=qe()),t.isBeingOpened=!0,t.dbOpenError=null,t.openComplete=!1;const r=t.openCanceller;function i(){if(t.openCanceller!==r)throw new x.DatabaseClosed("db.open() was cancelled")}let s=t.dbReadyResolve,o=null,a=!1;const l=()=>new L((c,u)=>{if(i(),!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=se(u),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(()=>{u(new x.NoSuchDatabase(`Database ${p} doesnt exist`))})}else{o.onerror=se(u);var g=h.oldVersion>Math.pow(2,62)?0:h.oldVersion;a=g<1,e._novip.idbdb=d.result,No(e,g/10,o,u)}},u),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:f},m,b){f.verno=m.version/10;const v=f._dbSchema=rr(0,m,b);f._storeNames=en(m.objectStoreNames,0),an(f,[f._allTables],$(v),v)}(e,h,w):(ir(e,e._dbSchema,w),function(f,m){const b=es(rr(0,f.idbdb,m),f._dbSchema);return!(b.add.length||b.change.some(v=>v.add.length||v.change.length))}(e,w)||console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.")),er(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:f},m){!Ar(w)&&m!==fn&&xr(w,f).put({name:m}).catch(T)}(e._deps,p),c()},u)}).catch(c=>c&&c.name==="UnknownError"&&t.PR1398_maxLoop>0?(t.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),l()):L.reject(c));return L.race([r,(typeof navigator>"u"?L.resolve():qo()).then(l)]).then(()=>(i(),t.onReadyBeingFired=[],L.resolve(sr(()=>e.on.ready.fire(e.vip))).then(function c(){if(t.onReadyBeingFired.length>0){let u=t.onReadyBeingFired.reduce(kr,T);return t.onReadyBeingFired=[],L.resolve(sr(()=>u(e.vip))).then(c)}}))).finally(()=>{t.onReadyBeingFired=null,t.isBeingOpened=!1}).then(()=>e).catch(c=>{t.dbOpenError=c;try{o&&o.abort()}catch{}return r===t.openCanceller&&e._close(),W(c)}).finally(()=>{t.openComplete=!0,s()})}function or(e){var t=s=>e.next(s),n=i(t),r=i(s=>e.throw(s));function i(s){return o=>{var a=s(o),l=a.value;return a.done?l:l&&typeof l.then=="function"?l.then(n,r):Y(l)?Promise.all(l).then(n,r):n(l)}}return i(t)()}function Wo(e,t,n){var r=arguments.length;if(r<2)throw new x.InvalidArgument("Too few arguments");for(var i=new Array(r-1);--r;)i[r-1]=arguments[r];return n=i.pop(),[e,Oi(i),n]}function ts(e,t,n,r,i){return L.resolve().then(()=>{const s=U.transless||U,o=e._createTransaction(t,n,e._dbSchema,r),a={trans:o,transless:s};if(r)o.idbtrans=r.idbtrans;else try{o.create(),e._state.PR1398_maxLoop=3}catch(p){return p.name===Er.InvalidState&&e.isOpen()&&--e._state.PR1398_maxLoop>0?(console.warn("Dexie: Need to reopen db"),e._close(),e.open().then(()=>ts(e,t,n,null,i))):W(p)}const l=_r(i);let c;l&&tt();const u=L.follow(()=>{if(c=i.call(o,o),c)if(l){var p=we.bind(null,null);c.then(p,p)}else typeof c.next=="function"&&typeof c.throw=="function"&&(c=or(c))},a);return(c&&typeof c.then=="function"?L.resolve(c).then(p=>o.active?p:W(new x.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))):u.then(()=>c)).then(p=>(r&&o._resolve(),o._completion.then(()=>p))).catch(p=>(o._reject(p),W(p)))})}function Kt(e,t,n){const r=Y(e)?e.slice():[e];for(let i=0;i<n;++i)r.push(t);return r}const zo={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(e){return{...e,table(t){const n=e.table(t),{schema:r}=n,i={},s=[];function o(u,p,d){const h=mt(u),g=i[h]=i[h]||[],y=u==null?0:typeof u=="string"?1:u.length,w=p>0,f={...d,isVirtual:w,keyTail:p,keyLength:y,extractKey:Zn(u),unique:!w&&d.unique};return g.push(f),f.isPrimaryKey||s.push(f),y>1&&o(y===2?u[0]:u.slice(0,y-1),p+1,d),g.sort((m,b)=>m.keyTail-b.keyTail),f}const a=o(r.primaryKey.keyPath,0,r.primaryKey);i[":id"]=[a];for(const u of r.indexes)o(u.keyPath,0,u);function l(u){const p=u.query.index;return p.isVirtual?{...u,query:{index:p,range:(d=u.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})}}:u;var d,h}return{...n,schema:{...r,primaryKey:a,indexes:s,getIndexByKeyPath:function(u){const p=i[mt(u)];return p&&p[0]}},count:u=>n.count(l(u)),query:u=>n.query(l(u)),openCursor(u){const{keyTail:p,isVirtual:d,keyLength:h}=u.query.index;return d?n.openCursor(l(u)).then(g=>g&&function(y){return Object.create(y,{continue:{value:function(f){f!=null?y.continue(Kt(f,u.reverse?e.MAX_KEY:e.MIN_KEY,p)):u.unique?y.continue(y.key.slice(0,h).concat(u.reverse?e.MIN_KEY:e.MAX_KEY,p)):y.continue()}},continuePrimaryKey:{value(f,m){y.continuePrimaryKey(Kt(f,e.MAX_KEY,p),m)}},primaryKey:{get:()=>y.primaryKey},key:{get(){const f=y.key;return h===1?f[0]:f.slice(0,h)}},value:{get:()=>y.value}})}(g)):n.openCursor(u)}}}}}};function Rr(e,t,n,r){return n=n||{},r=r||"",$(e).forEach(i=>{if(ne(t,i)){var s=e[i],o=t[i];if(typeof s=="object"&&typeof o=="object"&&s&&o){const a=jn(s);a!==jn(o)?n[r+i]=t[i]:a==="Object"?Rr(s,o,n,r+i+"."):s!==o&&(n[r+i]=t[i])}else s!==o&&(n[r+i]=t[i])}else n[r+i]=void 0}),$(t).forEach(i=>{ne(e,i)||(n[r+i]=t[i])}),n}const Ho={stack:"dbcore",name:"HooksMiddleware",level:2,create:e=>({...e,table(t){const n=e.table(t),{primaryKey:r}=n.schema;return{...n,mutate(s){const o=U.trans,{deleting:a,creating:l,updating:c}=o.table(t).hook;switch(s.type){case"add":if(l.fire===T)break;return o._promise("readwrite",()=>u(s),!0);case"put":if(l.fire===T&&c.fire===T)break;return o._promise("readwrite",()=>u(s),!0);case"delete":if(a.fire===T)break;return o._promise("readwrite",()=>u(s),!0);case"deleteRange":if(a.fire===T)break;return o._promise("readwrite",()=>function(d){return p(d.trans,d.range,1e4)}(s),!0)}return n.mutate(s);function u(d){const h=U.trans,g=d.keys||function(y,w){return w.type==="delete"?w.keys:w.keys||w.values.map(y.extractKey)}(r,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,f){return w.type==="add"?Promise.resolve([]):y.getMany({trans:w.trans,keys:f,cache:"immutable"})}(n,d,g).then(y=>{const w=g.map((f,m)=>{const b=y[m],v={onerror:null,onsuccess:null};if(d.type==="delete")a.fire.call(v,f,b,h);else if(d.type==="add"||b===void 0){const E=l.fire.call(v,f,d.values[m],h);f==null&&E!=null&&(f=E,d.keys[m]=f,r.outbound||ie(d.values[m],r.keyPath,f))}else{const E=Rr(b,d.values[m]),k=c.fire.call(v,E,f,b,h);if(k){const _=d.values[m];Object.keys(k).forEach(A=>{ne(_,A)?_[A]=k[A]:ie(_,A,k[A])})}}return v});return n.mutate(d).then(({failures:f,results:m,numFailures:b,lastResult:v})=>{for(let E=0;E<g.length;++E){const k=m?m[E]:g[E],_=w[E];k==null?_.onerror&&_.onerror(f[E]):_.onsuccess&&_.onsuccess(d.type==="put"&&y[E]?d.values[E]:k)}return{failures:f,results:m,numFailures:b,lastResult:v}}).catch(f=>(w.forEach(m=>m.onerror&&m.onerror(f)),Promise.reject(f)))})}function p(d,h,g){return n.query({trans:d,values:!1,query:{index:r,range:h},limit:g}).then(({result:y})=>u({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 ns(e,t,n){try{if(!t||t.keys.length<e.length)return null;const r=[];for(let i=0,s=0;i<t.keys.length&&s<e.length;++i)J(t.keys[i],e[s])===0&&(r.push(n?xt(t.values[i]):t.values[i]),++s);return r.length===e.length?r:null}catch{return null}}const Go={stack:"dbcore",level:-1,create:e=>({table:t=>{const n=e.table(t);return{...n,getMany:r=>{if(!r.cache)return n.getMany(r);const i=ns(r.keys,r.trans._cache,r.cache==="clone");return i?L.resolve(i):n.getMany(r).then(s=>(r.trans._cache={keys:r.keys,values:r.cache==="clone"?xt(s):s},s))},mutate:r=>(r.type!=="add"&&(r.trans._cache=null),n.mutate(r))}}})};function Cr(e){return!("from"in e)}const de=function(e,t){if(!this){const n=new de;return e&&"d"in e&&Q(n,e),n}Q(this,arguments.length?{d:1,from:e,to:arguments.length>1?t:e}:{d:0})};function It(e,t,n){const r=J(t,n);if(isNaN(r))return;if(r>0)throw RangeError();if(Cr(e))return Q(e,{from:t,to:n,d:1});const i=e.l,s=e.r;if(J(n,e.from)<0)return i?It(i,t,n):e.l={from:t,to:n,d:1,l:null,r:null},Xr(e);if(J(t,e.to)>0)return s?It(s,t,n):e.r={from:t,to:n,d:1,l:null,r:null},Xr(e);J(t,e.from)<0&&(e.from=t,e.l=null,e.d=s?s.d+1:1),J(n,e.to)>0&&(e.to=n,e.r=null,e.d=e.l?e.l.d+1:1);const o=!e.r;i&&!e.l&&ln(e,i),s&&o&&ln(e,s)}function ln(e,t){Cr(t)||function n(r,{from:i,to:s,l:o,r:a}){It(r,i,s),o&&n(r,o),a&&n(r,a)}(e,t)}function Yo(e,t){const n=ar(t);let r=n.next();if(r.done)return!1;let i=r.value;const s=ar(e);let o=s.next(i.from),a=o.value;for(;!r.done&&!o.done;){if(J(a.from,i.to)<=0&&J(a.to,i.from)>=0)return!0;J(i.from,a.from)<0?i=(r=n.next(a.from)).value:a=(o=s.next(i.from)).value}return!1}function ar(e){let t=Cr(e)?null:{s:0,n:e};return{next(n){const r=arguments.length>0;for(;t;)switch(t.s){case 0:if(t.s=1,r)for(;t.n.l&&J(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,!r||J(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 Xr(e){var t,n;const r=(((t=e.r)===null||t===void 0?void 0:t.d)||0)-(((n=e.l)===null||n===void 0?void 0:n.d)||0),i=r>1?"r":r<-1?"l":"";if(i){const s=i==="r"?"l":"r",o={...e},a=e[i];e.from=a.from,e.to=a.to,e[i]=a[i],o[i]=a[s],e[s]=o,o.d=Zr(o)}e.d=Zr(e)}function Zr({r:e,l:t}){return(e?t?Math.max(e.d,t.d):e.d:t?t.d:0)+1}Xe(de.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},[Kn](){return ar(this)}});const Jo={stack:"dbcore",level:0,create:e=>{const t=e.schema.name,n=new de(e.MIN_KEY,e.MAX_KEY);return{...e,table:r=>{const i=e.table(r),{schema:s}=i,{primaryKey:o}=s,{extractKey:a,outbound:l}=o,c={...i,mutate:d=>{const h=d.trans,g=h.mutatedParts||(h.mutatedParts={}),y=k=>{const _=`idb://${t}/${r}/${k}`;return g[_]||(g[_]=new de)},w=y(""),f=y(":dels"),{type:m}=d;let[b,v]=d.type==="deleteRange"?[d.range]:d.type==="delete"?[d.keys]:d.values.length<50?[[],d.values]:[];const E=d.trans._cache;return i.mutate(d).then(k=>{if(Y(b)){m!=="delete"&&(b=k.results),w.addKeys(b);const _=ns(b,E);_||m==="add"||f.addKeys(b),(_||v)&&function(A,S,B,D){function q(V){const F=A(V.name||"");function ce(H){return H!=null?V.extractKey(H):null}const M=H=>V.multiEntry&&Y(H)?H.forEach(Ae=>F.addKey(Ae)):F.addKey(H);(B||D).forEach((H,Ae)=>{const it=B&&ce(B[Ae]),vn=D&&ce(D[Ae]);J(it,vn)!==0&&(it!=null&&M(it),vn!=null&&M(vn))})}S.indexes.forEach(q)}(y,s,_,v)}else if(b){const _={from:b.lower,to:b.upper};f.add(_),w.add(_)}else w.add(n),f.add(n),s.indexes.forEach(_=>y(_.name).add(n));return k})}},u=({query:{index:d,range:h}})=>{var g,y;return[d,new de((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 de(d.key)],getMany:d=>[o,new de().addKeys(d.keys)],count:u,query:u,openCursor:u};return $(p).forEach(d=>{c[d]=function(h){const{subscr:g}=U;if(g){const y=v=>{const E=`idb://${t}/${r}/${v}`;return g[E]||(g[E]=new de)},w=y(""),f=y(":dels"),[m,b]=p[d](h);if(y(m.name||"").add(b),!m.isPrimaryKey){if(d!=="count"){const v=d==="query"&&l&&h.values&&i.query({...h,values:!1});return i[d].apply(this,arguments).then(E=>{if(d==="query"){if(l&&h.values)return v.then(({result:_})=>(w.addKeys(_),E));const k=h.values?E.result.map(a):E.result;h.values?w.addKeys(k):f.addKeys(k)}else if(d==="openCursor"){const k=E,_=h.values;return k&&Object.create(k,{key:{get:()=>(f.addKey(k.primaryKey),k.key)},primaryKey:{get(){const A=k.primaryKey;return f.addKey(A),A}},value:{get:()=>(_&&w.addKey(k.primaryKey),k.value)}})}return E})}f.add(n)}}return i[d].apply(this,arguments)}}),c}}}};class Me{constructor(t,n){this._middlewares={},this.verno=0;const r=Me.dependencies;this._options=n={addons:Me.addons,autoOpen:!0,indexedDB:r.indexedDB,IDBKeyRange:r.IDBKeyRange,...n},this._deps={indexedDB:n.indexedDB,IDBKeyRange:n.IDBKeyRange};const{addons:i}=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:T,dbReadyPromise:null,cancelOpen:T,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:[kr,T]}),this.on.ready.subscribe=xi(this.on.ready.subscribe,a=>(l,c)=>{Me.vip(()=>{const u=this._state;if(u.openComplete)u.dbOpenError||L.resolve().then(l),c&&a(l);else if(u.onReadyBeingFired)u.onReadyBeingFired.push(l),c&&a(l);else{a(l);const p=this;c||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 c=Yi,u=null;if(l)try{c=l()}catch(g){u=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:c,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:u,or:p.or,valueMapper:h!==_t?h:null}})),this.Table=function(a){return st(Oo.prototype,function(l,c,u){this.db=a,this._tx=u,this.name=l,this.schema=c,this.hook=a._allTables[l]?a._allTables[l].hook:ft(null,{creating:[bo,T],reading:[vo,_t],updating:[So,T],deleting:[_o,T]})})}(this),this.Transaction=function(a){return st(Mo.prototype,function(l,c,u,p,d){this.db=a,this.mode=l,this.storeNames=c,this.schema=u,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(),W(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(Qi.prototype,function(l,c,u){this.db=a,this._ctx={table:l,index:c===":id"?null:c,or:u};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,c,u)=>new this.Transaction(a,l,c,this._options.chromeTransactionDurability,u),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}}),i.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 r=n.filter(i=>i._cfg.version===t)[0];return r||(r=new this.Version(t),n.push(r),n.sort(Ko),r.stores({}),this._state.autoSchema=!1,r)}_whenReady(t){return this.idbdb&&(this._state.openComplete||U.letThrough||this._vip)?t():new L((n,r)=>{if(this._state.openComplete)return r(new x.DatabaseClosed(this._state.dbOpenError));if(!this._state.isBeingOpened){if(!this._options.autoOpen)return void r(new x.DatabaseClosed);this.open().catch(T)}this._state.dbReadyPromise.then(n,r)}).then(t)}use({stack:t,create:n,level:r,name:i}){i&&this.unuse({stack:t,name:i});const s=this._middlewares[t]||(this._middlewares[t]=[]);return s.push({stack:t,create:n,level:r??10,name:i}),s.sort((o,a)=>o.level-a.level),this}unuse({stack:t,name:n,create:r}){return t&&this._middlewares[t]&&(this._middlewares[t]=this._middlewares[t].filter(i=>r?i.create!==r:!!n&&i.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(r=>{t.dbReadyResolve=r}),t.openCanceller=new L((r,i)=>{t.cancelOpen=i})}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((r,i)=>{const s=()=>{this.close();var o=this._deps.indexedDB.deleteDatabase(this.name);o.onsuccess=K(()=>{(function({indexedDB:a,IDBKeyRange:l},c){!Ar(a)&&c!==fn&&xr(a,l).delete(c).catch(T)})(this._deps,this.name),r()}),o.onerror=se(i),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 $(this._allTables).map(t=>this._allTables[t])}transaction(){const t=Wo.apply(this,arguments);return this._transaction.apply(this,t)}_transaction(t,n,r){let i=U.trans;i&&i.db===this&&t.indexOf("!")===-1||(i=null);const s=t.indexOf("?")!==-1;let o,a;t=t.replace("!","").replace("?","");try{if(a=n.map(c=>{var u=c instanceof this.Table?c.name:c;if(typeof u!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return u}),t=="r"||t===_n)o=_n;else{if(t!="rw"&&t!=Sn)throw new x.InvalidArgument("Invalid transaction mode: "+t);o=Sn}if(i){if(i.mode===_n&&o===Sn){if(!s)throw new x.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");i=null}i&&a.forEach(c=>{if(i&&i.storeNames.indexOf(c)===-1){if(!s)throw new x.SubTransaction("Table "+c+" not included in parent transaction.");i=null}}),s&&i&&!i.active&&(i=null)}}catch(c){return i?i._promise(null,(u,p)=>{p(c)}):W(c)}const l=ts.bind(null,this,o,a,i,r);return i?i._promise(o,l,"lock"):U.trans?nt(U.transless,()=>this._whenReady(l)):this._whenReady(l)}table(t){if(!ne(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,r){return this._subscribe(t&&typeof t!="function"?t:{next:t,error:n,complete:r})}[Qo](){return this}}function rs(e,t){return $(t).forEach(n=>{ln(e[n]||(e[n]=new de),t[n])}),e}function Zo(e){let t,n=!1;const r=new Xo(i=>{const s=_r(e);let o=!1,a={},l={};const c={get closed(){return o},unsubscribe:()=>{o=!0,xe.storagemutated.unsubscribe(h)}};i.start&&i.start(c);let u=!1,p=!1;function d(){return $(l).some(y=>a[y]&&Yo(a[y],l[y]))}const h=y=>{rs(a,y),d()&&g()},g=()=>{if(u||o)return;a={};const y={},w=function(f){s&&tt();const m=()=>Ie(e,{subscr:f,trans:null}),b=U.trans?nt(U.transless,m):m();return s&&b.then(we,we),b}(y);p||(xe(kt,h),p=!0),u=!0,Promise.resolve(w).then(f=>{n=!0,t=f,u=!1,o||(d()?g():(a={},l=y,i.next&&i.next(f)))},f=>{u=!1,n=!1,i.error&&i.error(f),c.unsubscribe()})};return g(),c});return r.hasValue=()=>n,r.getValue=()=>t,r}let lr;try{lr={indexedDB:j.indexedDB||j.mozIndexedDB||j.webkitIndexedDB||j.msIndexedDB,IDBKeyRange:j.IDBKeyRange||j.webkitIDBKeyRange}}catch{lr={indexedDB:null,IDBKeyRange:null}}const Re=Me;function Gt(e){let t=fe;try{fe=!0,xe.storagemutated.fire(e)}finally{fe=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 Ar(t)?Promise.resolve(t.databases()).then(r=>r.map(i=>i.name).filter(i=>i!==fn)):xr(t,n).toCollection().primaryKeys()}(Re.dependencies).then(e)}catch{return W(new x.MissingAPI)}},defineClass:()=>function(e){Q(this,e)},ignoreTransaction:e=>U.trans?nt(U.transless,e):e(),vip:sr,async:function(e){return function(){try{var t=or(e.apply(this,arguments));return t&&typeof t.then=="function"?t:L.resolve(t)}catch(n){return W(n)}}},spawn:function(e,t,n){try{var r=or(e.apply(n,t||[]));return r&&typeof r.then=="function"?r:L.resolve(r)}catch(i){return W(i)}},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:()=>le,set:e=>{Pi(e,e==="dexie"?()=>!0:Gi)}},derive:He,extend:Q,props:Xe,override:xi,Events:ft,on:xe,liveQuery:Zo,extendObservabilitySet:rs,getByKeyPath:ge,setByKeyPath:ie,delByKeyPath:function(e,t){typeof t=="string"?ie(e,t,void 0):"length"in t&&[].map.call(t,function(n){ie(e,n,void 0)})},shallowClone:Ci,deepClone:xt,getObjectDiff:Rr,cmp:J,asap:Ai,minKey:Qn,addons:[],connections:ht,errnames:Er,dependencies:lr,semVer:zr,version:zr.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"&&(xe(kt,e=>{if(!fe){let t;hn?(t=document.createEvent("CustomEvent"),t.initCustomEvent(Ee,!0,!0,e)):t=new CustomEvent(Ee,{detail:e}),fe=!0,dispatchEvent(t),fe=!1}}),addEventListener(Ee,({detail:e})=>{fe||Gt(e)}));let fe=!1;if(typeof BroadcastChannel<"u"){const e=new BroadcastChannel(Ee);typeof e.unref=="function"&&e.unref(),xe(kt,t=>{fe||e.postMessage(t)}),e.onmessage=t=>{t.data&&Gt(t.data)}}else if(typeof self<"u"&&typeof navigator<"u"){xe(kt,t=>{try{fe||(typeof localStorage<"u"&&localStorage.setItem(Ee,JSON.stringify({trig:Math.random(),changedParts:t})),typeof self.clients=="object"&&[...self.clients.matchAll({includeUncontrolled:!0})].forEach(n=>n.postMessage({type:Ee,changedParts:t})))}catch{}}),typeof addEventListener<"u"&&addEventListener("storage",t=>{if(t.key===Ee){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===Ee&&Gt(t.changedParts)})}L.rejectionMapper=function(e,t){if(!e||e instanceof Ge||e instanceof TypeError||e instanceof SyntaxError||!e.name||!$r[e.name])return e;var n=new $r[e.name](t||e.message,e);return"stack"in e&&ye(n,"stack",{get:function(){return this.inner.stack}}),n},Pi(le,Gi);let is=!0,Or=!1;const ea=()=>is=!1,ta=()=>Or=!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={},cr;class ra{constructor(t){N(this,"_values",[]);N(this,"_isWebMetric");this.name=t,this._isWebMetric=na.includes(this.name)}report(t){if(is&&this._values.push({time:Date.now(),value:t}),Or||!this._isWebMetric)return;const n=this.findExceededThreshold(t);n&&cr&&cr(t,n)}collect(){const t=this._values;return this._values=[],t}findExceededThreshold(t){const n=ct[this.name];if(n)return n.find(r=>this.valueExceedsThreshold(t,r))}valueExceedsThreshold(t,n){return n.type==="max"?t>n.value:n.type==="min"?t<n.value:!1}}const ia=(e,t)=>{ct={},Or=!1,e==null||e.forEach(n=>{var r;n.metric in ct||(ct[n.metric]=[]),(r=ct[n.metric])==null||r.push(n)}),cr=t},Ct={},mn=e=>{const t=new ra(e);return Ct[e]=t,t},ss=(e,t)=>{let n=Ct[e];return n||(n=mn(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){Bn(`Error posting metrics: ${n}`)}},oa=({reportingIntervalSeconds:e,postMetrics:t})=>{e?setInterval(()=>{sa(t)},e*1e3):ea()},os=async(e,t)=>{const n=performance.now();try{await e()}finally{const r=performance.now()-n;let i=Ct[t];i||(i=mn(t)),i.report(r/1e3)}},as=(e,t)=>{const n=performance.now();try{e()}finally{const r=performance.now()-n;let i=Ct[t];i||(i=mn(t)),i.report(r/1e3)}},aa=30,ls=()=>{Le.setItem("sprig.disableReplayRecording","disabled")},Ne=()=>!!Le.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:r})=>{Ne()||t instanceof Error&&(ls(),ca(t==null?void 0:t.message)&&(n&&window.UserLeap.reportError(e,t,r),ha()))},da=async(e,t,{reportError:n}={reportError:!0})=>{var i;let r;try{if(n&&((i=window.navigator.storage)!=null&&i.estimate)){const{quota:s,usage:o}=await window.navigator.storage.estimate();r={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:r})},pa=()=>{const e=Le.getItem("sprig.sessionId");if(e)return I(`Found saved session id: ${e}`),Le.removeItem("sprig.sessionId"),e;const t=$e();return I(`Generating new uuid: ${t}`),t},X=pa();window.addEventListener("beforeunload",()=>{I(`Before page unload saving session id: ${X}`),Le.setItem("sprig.sessionId",X)});const ha=async()=>{O.transaction("rw",O.events,O.chunkUploads,O.pendingCaptures,()=>{O.events.clear(),O.chunkUploads.clear(),O.pendingCaptures.clear()}).catch(()=>{})},Un=(e,t,n=()=>!0)=>O.table(t).where("timestamp").below(e).and(n).delete(),fa=async(e,t)=>{let n=[];return await os(async()=>{n=await O.events.where("[sessionId+timestamp]").between([X,e],[X,t??Date.now()]).toArray()},"sdk_replay_get_events_between_seconds"),n},ma=(e,t,n)=>{const r=new Date,i=r.setMinutes(r.getMinutes()+(n??aa));return O.events.where("[sessionId+timestamp]").between([X,e],[X,t]).modify({expiredAt:i})},ya=e=>O.chunkUploads.add({...e,sessionId:e.sessionId??X}),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:X,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??X,canUpload:!1}),Sa=()=>O.pendingCaptures.where("sessionId").equals(X).and(e=>e.targetTimestamp<Date.now()).toArray(),Ea=()=>O.pendingCaptures.where("sessionId").equals(X).toArray(),ka=e=>O.pendingCaptures.where("sessionId").equals(X).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:r}=await window.navigator.storage.estimate();if(n&&r&&(n-r)/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=>{Ei(`Error opening replay storage: ${JSON.stringify(e)}`),ls()});const Ua=async(e,t,n)=>new Promise((r,i)=>{const s=e.createElement("script");s.src=t,s.onload=r,s.onerror=i,n&&(s.nonce=n),e.head.appendChild(s)});let ei=1,ur=5e3,Yt=6e4;const xa=5,ti=1e3,cs=30,cn=cs+xa,Aa="sprig.pendingCount";let dr,pr,us,ni=Date.now(),yn=!1,Jt;const Ra=async(e,t,n,r=2,i)=>{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(i!=null&&i.minAvailableGb&&(ei=i.minAvailableGb),!await La(ei)){Bn("Minimum storage not available");return}I("Initializing replay"),i!=null&&i.minDuration&&(ur=i.minDuration),i!=null&&i.batchDuration&&(Yt=i.batchDuration),oo(r),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){Bn("Record script failed to set global function");return}let o=!0,a=0;Jt=s({checkoutEveryNms:cs*1e3,sampling:{input:"last",scroll:250,media:800},emit:(l,c)=>{if(Ne())return;if(ni=Date.now(),c&&l.type===Mn.Meta)a=performance.now();else if(c&&a&&l.type===Mn.FullSnapshot){const p=performance.now()-a;ss("sdk_replay_snapshot_seconds",p/1e3)}const u=o||!!c;o=!1,Ca({uuid:$e(),event:JSON.stringify(l),isValidStart:u,timestamp:Date.now()})},...i}),yn=!0,pr||(pr=window.setInterval(()=>{Date.now()-ni>ti&&ve("Sprig_Noop",{})},ti)),R.on("survey.complete",l=>{Wa({id:l,userAgent:window.navigator.userAgent})})},"Error initializing replay")};let hr=!1,fr=[];const Ca=e=>{fr.push(e),hr||Da()},Oa=e=>{const t=e.map(n=>({...n,sessionId:n.sessionId??X}));if(t.length!==0)return O.transaction("rw",O.events,()=>{O.events.bulkAdd(t)}).catch(n=>{rt("Error storing replay events",n)})},Da=()=>{hr=!0,setTimeout(async()=>{if(Ne())return;const e=fr;fr=[],hr=!1,as(async()=>{await Oa(e)},"sdk_replay_add_event_batch_seconds")},500)},Pa=(e=6*60,t=30*60,n=4*60)=>{dr=window.setInterval(()=>{const r=Date.now();Ne()||(vt(`Performing periodic replay data cleanup / Event Seconds ${e} / Chunk Seconds ${t} / Pending Capture Seconds ${n}`),os(()=>O.transaction("rw!",O.events,O.chunkUploads,O.pendingCaptures,()=>{Un(r-e*1e3,"events",i=>i.expiredAt===void 0||i.expiredAt<r-e*1e3),Un(r-t*1e3,"chunkUploads"),Un(r-n*1e3,"pendingCaptures",i=>i.canUpload===void 0||i.canUpload===!1)}).catch(i=>{clearInterval(dr),rt("Error deleting table rows",i)}),"sdk_replay_cleanup_seconds"),I("Cleanup complete"))},30*1e3)},Ta=(e=5)=>{us=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 r=>(await O.pendingCaptures.delete(r.uuid),hs(r.captureParams,r.canUpload)))),Pe=(t-n.length).toString(),Le.setItem(Aa,Pe))},"Error initiating pending captures")},e*1e3)},Ba=async(e,t,n,r,i)=>{const s=Math.min(e+i,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:r,events:[]};if(!r){I(`Searching for valid start in ${a.length} events ${o}`);let l=-1;if(a==null||a.forEach((u,p)=>{if(!u.isValidStart)return;const d=u.timestamp<=t;(l<0||d)&&(l=p)}),l<0)return I(`No valid start found in ${a.length} events ${o}`),{validStartFound:r,events:[]};const c=a[l].timestamp;return I(`Found valid start at: ${new Date(c).toLocaleTimeString()} in events ${o}`),{validStartFound:!0,events:a==null?void 0:a.slice(l)}}return{validStartFound:r,events:a}},Ma=(e,t,n)=>{const r=e.length,i=t*1024*1024,s=Math.ceil(r/n),o=Math.max(i,s);I(`Total file bytes: ${r} / target chunk size: ${o}`);const a=[];let l=0;for(;l<r;)a.push(e.slice(l,l+o)),l+=o;return a},ds=e=>Promise.all(e.map(async t=>{const n=await ao(t);return await ga(t.uuid,n),t.uploadId})),ps=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 r=n.map(s=>({ETag:s.etag,PartNumber:s.chunkIndex})).filter(s=>s.ETag!==null),i=n[0];await Ii({apiUrl:i.apiUrl,surveyId:i.surveyId,uploadId:e,responseGroupUuid:i.responseGroupId,etags:r,headers:i.completeUploadHeaders,replayDuration:i.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 ds(e);I(`Finished uploading unfinished chunks for ${t}`),t!=null&&t.length&&await Promise.all(t.map(n=>{if(n)return ps(n)}))},"Error uploading unfinished chunks")},ja=async(e,t)=>{await ds(t),I(`Done uploading chunks for uploads: ${e.join(",")}`),await Promise.all(e.map(n=>ps(n)))},Ka=e=>{let t=0;e.forEach(i=>{t+=i.length});const n=new Uint8Array(t);let r=0;return e.forEach(i=>{n.set(i,r),r+=i.length}),n},ri=async(e,t,n)=>{const r=new TextEncoder;let i=null,s=null,o=null,a=!1,l=!1,[c,u]=[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}c===0&&(c=h[0].timestamp),u=h[h.length-1].timestamp,I(`Last event time in batch: ${new Date(u).toLocaleTimeString()}`);const w=`${a?",":"["}${h.map(m=>m.event).join(",")}`,f=r.encode(w);n&&s===null&&(vt("Attempting compression"),o=new window.CompressionStream("gzip"),s=o.writable.getWriter()),as(()=>{n&&s?s.write(f):d.push(f)},"sdk_replay_compression_seconds"),a=!0}if(u-c<ur)return I(`Replay duration is shorter than minimum of ${ur}ms / Start:${c} / End:${u}`),null;const g=r.encode("]");return vt("Writing final close brace"),s&&o?(s.write(g),s.close(),i=new Uint8Array(await new Response(o.readable).arrayBuffer())):(d.push(g),i=Ka(d)),I("Finished generating file data"),i},Na=async(e,t)=>{const n=window.CompressionStream!==void 0;let r=null;const i=t??Date.now(),s=i-e;try{r=await ri(s,i,n)}catch(o){o instanceof Error&&window.UserLeap.reportError("Error compressing replay",o),n&&Ze(async()=>{await ri(s,i,!1)},"fileData fallback failed")}return r},ii=async e=>{const{surveyId:t,responseGroupId:n,visitorId:r,apiUrl:i,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 c=Ma(l,o.minimumChunkSizeMb,o.signedUrls.length);I(`Got ${c.length} chunks for survey: ${t}`);const u=await Promise.all(c.map(async(p,d)=>{const h=$e(),g={apiUrl:i,chunkIndex:d+1,completeUploadHeaders:s,etag:null,responseGroupId:n,status:"ReadyForUpload",surveyId:t,timestamp:a,totalChunks:c.length,data:p,uploadId:o.uploadId,uploadUrl:o.signedUrls[d].url,uuid:h,visitorId:r};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],u)},hs=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:r,triggerTimestamp:i,responseGroupId:s}=e,o=async()=>{setTimeout(()=>R.removeListener(C.QuestionAnswered,o),0),Ze(async()=>{r.replayDurationType==="before"?await ii(e):await ka(s)},"Error in schedule/capture callback")};Ze(async()=>{if(r.replayDurationType==="after"||r.replayDurationType==="beforeAndAfter"){n||(I("Attaching QuestionAnswered listener for non-standalone replay"),R.on(C.QuestionAnswered,o)),I(`Scheduling capture for replay of type: ${r.replayDurationType}`),await $a(e);return}if(n||t)I(`Proceeding to capture replay for survey: ${e.surveyId} / standalone? ${n} / canUpload? ${t}`),await ii(e);else{const a=cn+r.replayDurationSeconds,l=i-a*1e3,c=i;I(`Setting expiry minutes to ${r.expirationTimeLimitMinutes} for events from ${new Date(l).toLocaleTimeString()} to ${new Date(c).toLocaleTimeString()}`),await ma(l,c,r.expirationTimeLimitMinutes),I("Attaching QuestionAnswered listener"),R.on(C.QuestionAnswered,o)}},"Error in scheduling/capturing replay")},si=()=>{if(Ne()){vt("Not clearing user data, replay is disabled");return}return O.transaction("rw",O.events,O.pendingCaptures,()=>{O.events.where("sessionId").equals(X).delete(),O.pendingCaptures.where("sessionId").equals(X).delete()}).catch(e=>{rt("Error clearing session event data",e)})};let Pe=Le.getItem("sprig.pendingCount");const $a=async e=>{I(`Scheduling replay capture: ${JSON.stringify(e)}`);const{surveyId:t}=e,n=await Ea(),r=n==null?void 0:n.filter(o=>o.captureParams.surveyId===t);if(r!=null&&r.length){I(`Pending capture exists for survey: ${t}`);return}const i={...e,replayParams:{...e.replayParams}};e.replayParams.replayDurationType==="beforeAndAfter"&&(i.replayParams.replayDurationSeconds*=2),i.replayParams.replayDurationType="before";const s=e.triggerTimestamp+e.replayParams.replayDurationSeconds*1e3;return i.triggerTimestamp=s,Pe=Pe?(parseInt(Pe)+1).toString():"1",Le.setItem("sprig.pendingCount",Pe),_a({uuid:$e(),targetTimestamp:s,timestamp:Date.now(),captureParams:i})},ve=(e,t)=>{var n,r;if(yn)try{(r=(n=window.rrwebRecord)==null?void 0:n.addCustomEvent)==null||r.call(n,e,t)}catch(i){rt("Error recording custom event",i)}},Ze=async(e,t)=>{try{await e()}catch(n){rt(t,n)}},oi=e=>{e.description&&(e.description=Dr(e.description)),ve("Sprig_PageView",e)},qa=e=>{ve("Sprig_TrackEvent",e)},Va=e=>{ve("Sprig_ShowSurvey",e)},Wa=e=>{ve("Sprig_SubmitSurvey",e)},za=e=>{var t;(t=e==null?void 0:e.elementAttributes)!=null&&t.text&&(e.elementAttributes.text=Dr(e.elementAttributes.text)),ve("Sprig_Click",e)},Ha=e=>{ve("Sprig_Refresh",e)},Ga=e=>{e.currentPageTitle&&(e.currentPageTitle=Dr(e.currentPageTitle)),ve("Sprig_BackForward",e)},Ya=e=>{ve("Sprig_Keystroke",e)},rt=(e,t,{reportError:n}={reportError:!0})=>(Jt&&(Jt(),Jt=void 0),yn=!1,[dr,pr,us].forEach(r=>{r&&clearInterval(r)}),Ei(`${e} - ${JSON.stringify(t)}`),da(e,t,{reportError:n})),fs=()=>yn,Dr=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),ai="ul-view-sdk-script",Ja=["ios","android"],Se="visitors",ke="environments",li=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 gn(e,t){const{matchType:n,pattern:r}=e,i=n?li[n]:li.legacy;let s=!1;try{s=i(r,t)}catch(o){const a=`[Sprig] (ERR-445) Failed to check url match with pattern ${r}`;o instanceof Error&&(console.warn(a,o),o.stack=JSON.stringify(e),window.UserLeap.reportError(a,o))}return s}async function oe(e,t){var s,o,a;const{shouldDropOnRateLimit:n,...r}=t;r.headers=Object.assign(Fe(window.UserLeap),r.headers);const i=await me(e,{...r,shouldDropOnRateLimit:n});if(i.ok){const l=(s=i.headers)==null?void 0:s.get("Authorization"),c=l?l.split(" "):void 0,u=c&&c.length===2?c[1]:void 0,p=(o=i.headers)==null?void 0:o.get("x-ul-visitor-id");u&&p&&(p!==window.UserLeap.visitorId||window.UserLeap.token!==u)&&(ee("token",u),ee("vid",p),R.emit(C.VisitorIDUpdated,{visitorId:p}),window.UserLeap.token=u,window.UserLeap.visitorId=p)}return(a=i.json)!=null&&a.logMessage&&console.warn(`[Sprig] ${i.json.logMessage}`),i}function ee(e,t){const n=te.getItem("userleap.ids");let r={};if(n)try{r=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 i=r[window.UserLeap.envId];i?i[e]=t:i={[e]:t},r[window.UserLeap.envId]=i;try{te.setItem("userleap.ids",JSON.stringify(r))}catch(s){s instanceof Error&&console.warn(`[Sprig] (ERR-426) Unable to write to Local Storage:: ${s.message}`)}}function Pr(){return window.previewMode?"0":window.UserLeap.visitorId??""}function re(e,t,n){const r=[window.UserLeap._API_URL,"sdk",e];return t&&t.forEach(i=>{r.push(i),i===ke?r.push(window.UserLeap.envId):i===Se&&r.push(Pr())}),n&&r.push(n),r.join("/")}const yt=async e=>{var F,ce;const{context:t,forceBrandedLogo:n,endCard:r,isFeedback:i=!1,locale:s,productConfig:o,questions:a,responseGroupUid:l,surveyId:c,uuid:u,vid:p,sessionReplay:d,studyType:h}=e,g=Fe(window.UserLeap),y=Br(g),w=Tr(g);if(I(`Attempting to display survey: ${c}`),d&&(I("Survey has replay attached"),y?R.emit(C.ReplayCapture,{responseGroupUid:l,hasQuestions:!!(a!=null&&a.length),surveyId:c,uploadId:d.uploadId,replayType:d.replayDurationType??"before",seconds:d.replayDurationSeconds,generateVideoUploadUrlPayload:{mediaRecordingUid:$e(),mediaType:"screen",questionId:1,responseGroupUid:l,surveyId:c,updatedAt:new Date().toISOString(),visitorId:window.UserLeap.visitorId,isReplay:!0}}):hs({responseGroupId:l,surveyId:c,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 M="[Sprig] (ERR-409) Found an existing Survey container, aborting rendering of this survey";return console.warn(M),{success:!1,message:M,surveyState:"no survey"}}if(p!==window.UserLeap.visitorId&&u!==window.UserLeap.visitorId&&!window.previewMode){const M="Attempted to display survey to a different visitor";return I(M),window.UserLeap.reportError("DisplaySurvey",new Error(M)),{success:!1,message:M,surveyState:"no survey"}}I(`Showing survey: ${c}`),Va({id:c,userAgent:window.navigator.userAgent}),mi.disable(),R.emit(C.SurveyWillPresent,{name:C.SurveyWillPresent,"survey.id":c});let f,m=document.createElement("div"),b,v,E;const k=M=>{const{"view.version":H}=M;H!==g["x-ul-sdk-version"]&&gs(),R.removeListener("verify.view.version",k)};R.on("verify.view.version",k),window.UserLeap.useMobileStyling=w,wi(g)?(f="ul-direct-embeded-frame",b=document.head,v=window,E=!1,y&&(ys(),m.id=f,window.UserLeap.container.appendChild(m),ws(),R.emit(C.SurveyLifeCycle,{state:"presented"}),R.emit(C.SurveyPresented,{name:C.SurveyPresented,"survey.id":c}))):{frameId:f,contentWinDocHead:b,contentWindow:v,hasOverlay:E,iframe:m}=tl({productConfig:o,useMobileStyling:w,surveyId:c,isFeedback:i}),window.UserLeap.frameId=f;const _=M=>{R.once(C.CloseSurveyOnOverlayClick,M)},A={apiURL:window.UserLeap._API_URL,cards:a,configureExitOnOverlayClick:_,context:t,endCard:r,envId:window.UserLeap.envId,eventEmitFn:R.emit.bind(R),fontFamily:window.UserLeap.fontFamily,fontFamilyURL:window.UserLeap.fontFamilyURL,forceBrandedLogo:n,frame:m,headers:g,locale:s,mobileSDKVersion:window.UserLeap.mobileSDKVersion,previewKey:te.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:(F=window.UserLeap.config)==null?void 0:F.startingQuestionIdx,studyType:h,styleNonce:window.UserLeap.styleNonce,surveyId:c,tabTitle:document.title,ulEvents:wt,useMobileStyling:w,userId:u,viewDocument:v==null?void 0:v.document,viewWindow:v,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}),A.customStyles=o==null?void 0:o.customStyles,v&&(v.__cfg=A);function S(){const M=document.createElement("script");return window.UserLeap.nonce&&M.setAttribute("nonce",window.UserLeap.nonce),M.id=ai,M}const B=window.UserLeap.viewSDKURL?window.UserLeap.viewSDKURL:A.path,D=document.getElementById(ai);D&&D.remove();const q=S(),V=()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{display:"flex"})};if(A.installationMethod==="web-npm"||A.installationMethod==="web-npm-bundled"){const{default:M}=await Promise.resolve().then(()=>require("./view-Bg2sVSsl.cjs"));M.configure(A),E&&window.UserLeap.container&&V()}else B&&(q.src=B,E&&q.addEventListener("load",()=>{window.UserLeap.container&&V()}),v==null||v.addEventListener("error",M=>{M.target instanceof HTMLScriptElement&&M.target.src===B&&window.UserLeap.reportError("loadFrameScript",new Error("Frame script failed to load"))},{capture:!0,once:!0}));return b==null||b.appendChild(q),{success:!0,surveyState:"ready",surveyId:c,responseGroupUid:l}};function Tr(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 Br(e)||t>10&&t<$s}function Br(e){return Ja.includes(e["userleap-platform"])}const ms="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)",xn="0px",ys=e=>{window.UserLeap.container=document.createElement("div"),window.UserLeap.container.className="ul-container";const t=bs();e&&t&&!window.UserLeap.useMobileStyling?t.appendChild(window.UserLeap.container):document.body.appendChild(window.UserLeap.container)},gs=(e,t)=>{var r;rl();const n=window.UserLeap.container;if(n)try{(r=n.parentNode)==null||r.removeChild(n),window.UserLeap.container=null,ee("trackStartUrl",null),R.emit(C.SurveyLifeCycle,{state:"dismissed"}),R.emit(C.SurveyClosed,{name:C.SurveyClosed,initiator:e,studyType:t})}catch(i){console.warn(`[Sprig] (ERR-412) Error removing UserLeap container by ${e} `+n),i instanceof Error&&window.UserLeap.reportError("dismissActiveSurvey",i)}},ws=()=>{R.once(C.SurveyWillClose,({initiator:e,studyType:t})=>{R.removeAllListeners(C.CloseSurveyOnOverlayClick),gs(e,t)})},Za=(e,t)=>{const r={...{position:"fixed",overflow:"auto",top:"0px",left:"0px",display:"none",height:"100%",width:"100%",transition:"background-color 0.3s ease-out",zIndex:2147483646}},i=t?e.overlayStyleMobile:e.overlayStyle;r["background-color"]=i==="light"?Qa:Xa,t||(r.margin="auto"),window.UserLeap.container&&Object.assign(window.UserLeap.container.style,r)},el=(e,t,n,r)=>{var u,p;const i={position:"fixed",bottom:"0px",right:xn,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,c=!1;if(n)(u=window.UserLeap.windowDimensions)!=null&&u.width?i.width=`${window.UserLeap.windowDimensions.width}px`:i.width="100%",(p=window.UserLeap.windowDimensions)!=null&&p.height?i.maxHeight=`${window.UserLeap.windowDimensions.height-20}px`:window.UserLeap.maxHeight?i.maxHeight=window.UserLeap.maxHeight:i.maxHeight=`${document.body.clientHeight-20}px`,["light","dark"].includes(s.overlayStyleMobile)&&(c=!0);else{i.width=hi,i.maxHeight=window.UserLeap.maxHeight||"66vh";const d=()=>{c=!0,l={margin:"auto",position:"static"}};if(r)a?d():l={position:"relative",height:"300px"};else switch(s.framePosition){case"bottomLeft":l={left:xn};break;case"topLeft":l={left:xn,top:0};break;case"topRight":l={top:0};break;case"center":d();break}}return c&&Za(s,n),Object.assign(e.style,i,l),c},tl=({productConfig:e,useMobileStyling:t,surveyId:n,isFeedback:r})=>{var p,d;const i=ms,s=r&&e.desktopDisplay==="slider";ys(s),nl();const o=document.createElement("iframe");o.id=i,o.setAttribute("title","Sprig User Feedback Dialog");const a=el(o,e,t,r);ws(),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 c=(d=o.contentWindow)==null?void 0:d.document;if(c&&(c.open("text/html","replace"),c.write("<!doctype html><head></head><body></body></html>"),c.close(),!t)){const h=c.body;h.style.display="flex",h.style.alignItems="center"}const u=c==null?void 0:c.head;return{frameId:i,contentWinDocHead:u,contentWindow:o.contentWindow,hasOverlay:a,iframe:o}},vs={[C.SurveyFadingOut]:()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{"background-color":"rgba(0,0,0,0)"})}},nl=()=>{Object.entries(vs).forEach(([e,t])=>{R.on(e,t)})},rl=()=>{Object.entries(vs).forEach(([e,t])=>{R.off(e,t)})},bs=()=>P,Je=()=>document.getElementById("sprig-feedback-container"),Mr=()=>document.getElementById("sprig-feedback-loading-animation"),il=()=>{if(Mr())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
9
  <div class="ul-loading-spinner">
10
10
  <div class="first"></div>
11
11
  <div class="second"></div>