@sprig-technologies/sprig-browser 2.26.4 → 2.26.6
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.
- package/dist/index-CqSba42x.cjs +8 -0
- package/dist/{index-GurVf9fu.js → index-Dc62vWMo.js} +837 -809
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +14 -10
- package/dist/index.js +1 -1
- package/dist/{view-KfdScd8f.js → view-BxLGbeCm.js} +4 -3
- package/dist/{view-TTq-V8ms.cjs → view-qyKPee6i.cjs} +3 -3
- package/package.json +1 -1
- package/dist/index-rCLyJyii.cjs +0 -8
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";var Os=Object.defineProperty;var Rs=(e,t,n)=>t in e?Os(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var F=(e,t,n)=>(Rs(e,typeof t!="symbol"?t+"":t,n),n);var Se=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.PageChange="page.change",e.API="api",e.Override="override",e))(Se||{}),O=(e=>(e.ReplayCapture="replay.capture",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))(O||{}),vt=(e=>(e.SurveyId="survey.id",e))(vt||{});const yr={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"}};var en=(e=>(e.VerifyViewVersion="verify.view.version",e.CurrentQuestion="survey.question",e.ViewPrototypeClick="question.prototype.click",e.ViewAgreementClick="question.agreement.click",e.RecordedTaskStart="recorded.task.start",e.RecordedTaskPermissionScreen="recorded.task.permission.screen",e.SurveyComplete="survey.complete",e))(en||{}),wr=(e=>(e.ViewVersion="view.version",e.QuestionId="qid",e.Props="props",e))(wr||{});let Tt;const Ds=new Uint8Array(16);function Ts(){if(!Tt&&(Tt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Tt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Tt(Ds)}const q=[];for(let e=0;e<256;++e)q.push((e+256).toString(16).slice(1));function Cs(e,t=0){return q[e[t+0]]+q[e[t+1]]+q[e[t+2]]+q[e[t+3]]+"-"+q[e[t+4]]+q[e[t+5]]+"-"+q[e[t+6]]+q[e[t+7]]+"-"+q[e[t+8]]+q[e[t+9]]+"-"+q[e[t+10]]+q[e[t+11]]+q[e[t+12]]+q[e[t+13]]+q[e[t+14]]+q[e[t+15]]}const Bs=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),jr={randomUUID:Bs};function qe(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 Cs(r)}var js=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"}},di=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=di.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 js(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)}},pi=di;pi.defaultMaxListeners=10;const R=new pi;var ut=(e=>(e.BottomLeft="bottomLeft",e.BottomRight="bottomRight",e.Center="center",e.TopLeft="topLeft",e.TopRight="topRight",e))(ut||{}),oe=(e=>(e.Error="x-ul-error",e.EnvironmentID="x-ul-environment-id",e.InstallationMethod="x-ul-installation-method",e.PartnerAnonymousId="x-ul-anonymous-id",e.Platform="userleap-platform",e.PreviewMode="x-ul-preview-mode",e.UserID="x-ul-user-id",e.VisitorID="x-ul-visitor-id",e))(oe||{}),xt=(e=>(e.Email="email",e.Link="link",e.Web="web",e))(xt||{}),Ce=(e=>(e.Npm="web-npm",e.NpmBundled="web-npm-bundled",e.Gtm="web-gtm",e.Segment="web-segment",e.SegmentAndroid="android-segment",e.SegmentReactNative="react-native-segment",e.SegmentIOS="ios-segment",e.Snippet="web-snippet",e))(Ce||{});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 Ns="rgba(255,255,255, 0.95)",Fs="rgba(0,0,0,0.9)",hi="360px",bn="0px",fi=()=>{window.UserLeap.container=document.createElement("div"),window.UserLeap.container.className="ul-container",document.body.appendChild(window.UserLeap.container)},mi=e=>{qs();const t=window.UserLeap.container;if(!(!t||!t.parentNode))try{t.parentNode.removeChild(t),window.UserLeap.container=null,X("trackStartUrl",null),R.emit(O.SurveyLifeCycle,{state:"dismissed"}),R.emit(O.SurveyClosed,{name:O.SurveyClosed,initiator:e})}catch(n){console.warn(`[Sprig] (ERR-412) Error removing UserLeap container by ${e} `+t),n instanceof Error&&window.UserLeap.reportError("dismissActiveSurvey",n)}},yi=()=>{R.on(O.SurveyWillClose,({initiator:e})=>{mi(e)})},Ks=(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"?Ns:Fs,t||(r.margin="auto"),window.UserLeap.container&&Object.assign(window.UserLeap.container.style,r)},Ms=(e,t,n)=>{var a,l;const r={position:"fixed",bottom:"0px",right:bn,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%"},i=Object.assign({},t,window.UserLeap);let s,o=!1;return n?((a=window.UserLeap.windowDimensions)!=null&&a.width?r.width=`${window.UserLeap.windowDimensions.width}px`:r.width="100%",(l=window.UserLeap.windowDimensions)!=null&&l.height?r.maxHeight=`${window.UserLeap.windowDimensions.height-20}px`:window.UserLeap.maxHeight?r.maxHeight=window.UserLeap.maxHeight:r.maxHeight=`${document.body.clientHeight-20}px`,["light","dark"].includes(i.overlayStyleMobile)&&(o=!0)):(r.width=hi,r.maxHeight=window.UserLeap.maxHeight||"66vh",i.framePosition===ut.BottomLeft?s={left:bn}:i.framePosition===ut.TopLeft?s={left:bn,top:0}:i.framePosition===ut.TopRight?s={top:0}:i.framePosition===ut.Center&&(o=!0,s={margin:"auto",position:"static"},r.maxHeight=null)),o&&Ks(i,n),Object.assign(e.style,r,s),o},$s=(e,t,n)=>{var u,c;const r="ul-frame";fi(),Vs();const i=document.createElement("iframe");i.id=r,i.setAttribute("title","Sprig User Feedback Dialog");const s=Ms(i,e,t);yi(),i.setHeight=p=>{parseInt(i.style.height)!=p&&(i.style.height=`${p}px`,R.emit(O.SurveyHeight,{name:O.SurveyHeight,contentFrameHeight:p}))};let o=!1;i.setWidth=p=>{(parseInt(i.style.width)!=p||!o)&&(o=!0,i.style.width=`${p}px`,R.emit(O.SurveyWidth,{name:O.SurveyWidth,contentFrameWidth:p}))},(u=window.UserLeap.container)==null||u.appendChild(i),e&&(t?e.exitOnOverlayClickMobile:e.exitOnOverlayClick)&&window.UserLeap.container&&(window.UserLeap.container.onclick=()=>{R.emit(O.CloseSurveyOnOverlayClick)}),R.emit(O.SurveyLifeCycle,{state:"presented"}),R.emit(O.SurveyPresented,{name:O.SurveyPresented,[vt.SurveyId]:n});const a=(c=i.contentWindow)==null?void 0:c.document;a&&(a.open("text/html","replace"),a.write("<!doctype html><head></head><body></body></html>"),a.close());const l=a==null?void 0:a.head;return{frameId:r,contentWinDocHead:l,contentWindow:i.contentWindow,hasOverlay:s,iframe:i}},wi={[O.SurveyFadingOut]:()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{"background-color":"rgba(0,0,0,0)"})}},Vs=()=>{Object.entries(wi).forEach(([e,t])=>{R.on(e,t)})},qs=()=>{Object.entries(wi).forEach(([e,t])=>{R.off(e,t)})},Ws="!launch_darkly_";class zs{constructor(){F(this,"_ldData",{})}getAllLaunchDarklyVariations(){return this._ldData}setLDFlagsVariations(t){try{return!t||typeof t!="object"||Array.isArray(t)?!1:(Object.keys(this._ldData).forEach(n=>{delete this._ldData[n]}),Object.keys(t).forEach(n=>this._ldData[`${Ws}${n}`]=(t[n]??0)+1),!0)}catch(n){return n instanceof Error&&window.UserLeap.reportError("setAllLDFlagsVariations",n),console.warn("[Sprig] An issue had occured when setting LaunchDarkly flags and variations."),!1}}}const On=new zs;Object.freeze(On);const Gs="!optimizely_experiments_";class Hs{constructor(){F(this,"_optimizelyData",{})}setOptimizelyExperiment(t,n=!0){if(!t||typeof t!="object")return!1;const{experiments:r}=t;try{return n&&Object.keys(this._optimizelyData).map(i=>{delete this._optimizelyData[i]}),r&&r.map(i=>{const{id:s,variation:o}=i,a=this.transformExperimentId(s);o&&typeof o=="string"&&(this._optimizelyData[a]=o)}),!0}catch(i){return i instanceof Error&&window.UserLeap.reportError("setOptimizelyExperiment",i),!1}}getAllOptimizelyExperiments(){return this._optimizelyData}getOptimizelyVariationName(t){return this._optimizelyData[this.transformExperimentId(t)]}transformExperimentId(t){return Gs+t}getAndSetWebOptimizelyExperiments(){var t;try{if(window&&window.optimizely&&typeof window.optimizely.get=="function"){const n=(t=window.optimizely.get("state"))==null?void 0:t.getExperimentStates({isActive:!0});if(n){const r=Object.keys(n).map(i=>{var s,o;return(s=n[i].variation)!=null&&s.name?{id:i,variation:(o=n[i].variation)==null?void 0:o.name}:{id:i,variation:"Original"}});return this.setOptimizelyExperiment({experiments:r},!1),!0}return!1}return!1}catch(n){return n instanceof Error&&window.UserLeap.reportError("getAndSetWebOptimizely",n),!1}}}const Vt=new Hs;Object.freeze(Vt);class Ys{constructor(t,n){F(this,"paused");F(this,"queue");F(this,"ul");this.ul=t,this.paused=!1,this.queue=[],this.flush(n)}flush(t){const n=t.length;if(n)for(let r=0;r<n;r++)this.push(t[r])}isPaused(){return this.paused}pause(){this.paused=!0}unpause(){this.paused=!1;const t=this.queue.slice();this.empty(),this.flush(t)}push(t){if(this.paused)this.queue.push(t);else if(t instanceof Function)t();else{const n=Array.prototype.slice.call(t,1),r=t[0],i=this.ul[r];i instanceof Function?i.apply(this.ul,n):r&&console.warn("[Sprig] (ERR-100) No valid UserLeap action called",r)}}perform(t){if(this.paused){let n=()=>{};const r=new Promise(function(i){n=function(){i(t())}});return this.queue.push(n),r}else return t()}empty(){this.queue.length=0}}var re=(e=>(e.Ready="ready",e.NoSurvey="no survey",e))(re||{}),gi=(e=>(e.Preview="sprigPreviewKey",e))(gi||{});const Js="ul-app";var ke=(e=>(e.Caption="ul-caption",e.CardContainer="ul-card__container",e.CardMainContent="ul-card-main-content",e.Choice="choice",e.ChoiceCheckbox="select-checkbox",e.ChoiceGroup="ul-card__choices",e.ChoiceLabel="select-label",e.ChoiceLabelContainer="choice-label-container",e.ChoiceRadio="select-radio",e.ChoiceTextEntryContainer="choice-text-entry-container",e.ChoiceTextInput="choice-text-input",e.CloseButton="close-btn",e.CloseContainer="close-container",e.ConsentLegalNameInput="ul-consent-legal__name-input",e.CustomStyle="ul-custom-style",e.DesktopSuffix="--desktop",e.FadeInTransition="fade-in-transition",e.LikertNumber="likert-number",e.LikertSmiley="likert-smiley",e.LikertStar="likert-star",e.LoadingSpinner="ul-loading-spinner",e.LoadingSpinnerContainer="ul-loading-spinner-container",e.LoadingSpinnerFirst="first",e.LoadingSpinnerFourth="fourth",e.LoadingSpinnerSecond="second",e.LoadingSpinnerThird="third",e.MobileSuffix="--mobile",e.NPSNumber="nps-number",e.OpenTextInput="ul-card-text__input",e.QuestionHeader="ul-question",e.VideoCard="ul-card--video",e.CheckmarkButton="ul-button-checkmark",e.InactiveButton="ul-button-inactive",e.LeftAlignButton="ul-button-left-align",e.ButtonDisabled="sprig-button-disabled",e.SkipButton="ul-card-skip__button",e))(ke||{});const Qs="#e6e6e6",Xs="#bd282a",Zs=500,eo=1030;var gr=(e=>(e.Video="video",e.Audio="audio",e.Screen="screen",e))(gr||{}),vi=(e=>(e.PermissionStatus="permission.status",e.AvPermission="av.permission",e.ScreenPermission="screen.permission",e.BeginRecording="begin.recording",e.StartTask="start.task",e.FinishTask="finish.task",e))(vi||{}),bi=(e=>(e.Abandoned="abandoned",e.GivenUp="given.up",e.Completed="completed",e))(bi||{}),_i=(e=>(e.ScreenPermissionRequested="screen.permission.requested",e.PermissionDescriptors="permission.descriptors",e.PermissionStatusCallback="permission.status.callback",e.StreamReadyCallback="stream.ready.callback",e.StreamCanceledCallback="stream.canceled.callback",e.TaskCompleteCallback="task.complete.callback",e.TaskResponse="task.response",e.TaskStatus="task.status",e.RecordingMediaTypes="recording.media.types",e.StartRecordingCallback="start.recording.callback",e.PassthroughData="passthrough.data",e.CurrentIndex="current.index",e.UploadCallback="upload.callback",e.ProgressCallback="progress.callback",e.BeginCallback="begin.callback",e))(_i||{}),ee=(e=>(e.Preview="sprig.previewKey",e.Credentials="userleap.ids",e.PageViews="userleap.pageviews",e))(ee||{});const Si=()=>{try{return window.parent.Intercom}catch(e){return console.error(e),null}},to=()=>{const e=Si();e&&(e.ul_wasVisible&&e("update",{hide_default_launcher:!1}),delete e.ul_wasVisible)},no=()=>{const e=Si();e&&(e.ul_wasVisible=!!document.querySelector("iframe.intercom-launcher-frame"),e.ul_wasVisible&&e("update",{hide_default_launcher:!0}))},ro=Object.freeze(Object.defineProperty({__proto__:null,disable:no,enable:to},Symbol.toStringTag,{value:"Module"})),Nr=[ro];class Ei{static disable(){Nr.forEach(t=>t.disable())}static enable(){Nr.forEach(t=>t.enable())}}const io=1,Fr=e=>e instanceof HTMLElement||e instanceof SVGElement,Li=(e,t,n)=>{const r=e.createElement("style");n&&(r.nonce=n),r.textContent=t,r.id=ke.CustomStyle,e.head.appendChild(r)},ki=e=>{const t=e.querySelector(`.${ke.CardContainer}`);let n=600,r=360;if(t){n=t.scrollHeight;const i=getComputedStyle(t),s=parseFloat(i.marginTop)+parseFloat(i.marginBottom),o=parseFloat(i.borderTopWidth)+parseFloat(i.borderBottomWidth);n+=s+o;const a=t.querySelector(".ul-card--matrix_grid");r=a?a.scrollWidth:t.scrollWidth;const l=parseFloat(i.paddingLeft)+parseFloat(i.paddingRight),u=parseFloat(i.marginLeft)+parseFloat(i.marginRight),c=parseFloat(i.borderLeftWidth)+parseFloat(i.borderRightWidth);r+=u+c+l}return[n+io,r]},so=e=>{const t=e.querySelector(`.${ke.CardContainer}`);t&&(t.scrollTop=0)},tn=e=>new Promise(t=>{setTimeout(()=>{t()},e)}),Ii=({"userleap-platform":e})=>e!==xt.Web,oo=(e,t)=>{const n=t?ke.MobileSuffix:ke.DesktopSuffix;return[e+n,e]},ao=(e,t)=>[e,`${e}__${t}`];class Ui{constructor(t){F(this,"storage");F(this,"tempStorage",{});F(this,"isStorageAvailable");this.storage=window[t],this.isStorageAvailable=this.checkIfStorageAvailable()}checkIfStorageAvailable(){try{const t="__storage_test__";return this.storage.setItem(t,t),this.storage.removeItem(t),!0}catch{return!1}}setItem(t,n){this.isStorageAvailable?this.storage.setItem(t,n):this.tempStorage[t]=n}getItem(t){return this.isStorageAvailable?this.storage.getItem(t):this.tempStorage[t]}removeItem(t){this.isStorageAvailable?this.storage.removeItem(t):delete this.tempStorage[t]}clear(){this.isStorageAvailable?this.storage.clear():this.tempStorage={}}}const Ie=new Ui("sessionStorage"),Z=new Ui("localStorage");var lo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ai(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function co(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var n=function r(){return this instanceof r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}),n}var xi={exports:{}};(function(e,t){(function(n,r){e.exports=r()})(lo,function(){var n=function(s,o){if(o=o||{},typeof s!="function")throw new i("fetch must be a function");if(typeof o!="object")throw new i("defaults must be an object");if(o.retries!==void 0&&!r(o.retries))throw new i("retries must be a positive integer");if(o.retryDelay!==void 0&&!r(o.retryDelay)&&typeof o.retryDelay!="function")throw new i("retryDelay must be a positive integer or a function returning a positive integer");if(o.retryOn!==void 0&&!Array.isArray(o.retryOn)&&typeof o.retryOn!="function")throw new i("retryOn property expects an array or function");var a={retries:3,retryDelay:1e3,retryOn:[]};return o=Object.assign(a,o),function(u,c){var p=o.retries,d=o.retryDelay,h=o.retryOn;if(c&&c.retries!==void 0)if(r(c.retries))p=c.retries;else throw new i("retries must be a positive integer");if(c&&c.retryDelay!==void 0)if(r(c.retryDelay)||typeof c.retryDelay=="function")d=c.retryDelay;else throw new i("retryDelay must be a positive integer or a function returning a positive integer");if(c&&c.retryOn)if(Array.isArray(c.retryOn)||typeof c.retryOn=="function")h=c.retryOn;else throw new i("retryOn property expects an array or function");return new Promise(function(w,y){var g=function(f){var v=typeof Request<"u"&&u instanceof Request?u.clone():u;s(v,c).then(function(b){if(Array.isArray(h)&&h.indexOf(b.status)===-1)w(b);else if(typeof h=="function")try{return Promise.resolve(h(f,null,b)).then(function(_){_?m(f,null,b):w(b)}).catch(y)}catch(_){y(_)}else f<p?m(f,null,b):w(b)}).catch(function(b){if(typeof h=="function")try{Promise.resolve(h(f,b,null)).then(function(_){_?m(f,b,null):y(b)}).catch(function(_){y(_)})}catch(_){y(_)}else f<p?m(f,b,null):y(b)})};function m(f,v,b){var _=typeof d=="function"?d(f,v,b):d;setTimeout(function(){g(++f)},_)}g(0)})}};function r(s){return Number.isInteger(s)&&s>=0}function i(s){this.name="ArgumentError",this.message=s}return n})})(xi);var uo=xi.exports;const Pi=Ai(uo),po=Pi(fetch),rt={Error:1,Warn:2,Info:3,Debug:4};let Rn=1e3,nn=rt.Debug,et=[];const ho=e=>{const t=Object.entries(rt).find(n=>n[1]===e);return(t==null?void 0:t[0])??""},fo=e=>e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3}),mo=(e,t)=>`${fo(t)}:${e}`,yo=()=>{et=et.filter(e=>e.level<=nn)},wo=()=>{et.length>Rn&&et.shift()},fn=(e,t)=>{e>nn||(et.push({level:e,line:mo(t,new Date)}),wo())},bt=e=>{fn(rt.Debug,e)},I=e=>{fn(rt.Info,e)},Dn=e=>{fn(rt.Warn,e)},Oi=e=>{fn(rt.Error,e)},go=()=>et.map(e=>e.line),vo=()=>new TextEncoder().encode(go().join(`
|
|
2
|
+
`)),Ri=async e=>{if(!e)return;const t=vo();return po(e,{body:t,method:"PUT",retries:3,retryDelay:n=>Math.pow(2,n)*1e3})},bo=(e,t)=>{e!==void 0&&(Rn=e),t!==void 0&&(nn=t),bt(`Initializing logger with limit of ${Rn} lines and ${ho(nn)} level`),yo()};let Di=!0,vr=!1;const _o=()=>Di=!1,So=()=>vr=!0;var We=(e=>(e.EventQueueLatency="sdk_event_queue_latency_seconds",e.ReplayAddEventBatch="sdk_replay_add_event_batch_seconds",e.ReplayCleanup="sdk_replay_cleanup_seconds",e.ReplayCompression="sdk_replay_compression_seconds",e.ReplayGetEventsBetween="sdk_replay_get_events_between_seconds",e.ReplayFullSnapshot="sdk_replay_snapshot_seconds",e))(We||{});let dt={},Tn;class Eo{constructor(t){F(this,"_values",[]);this.name=t}report(t){if(Di&&this._values.push({time:Date.now(),value:t}),vr)return;const n=this.findExceededThreshold(t);n&&Tn&&Tn(t,n)}collect(){const t=this._values;return this._values=[],t}findExceededThreshold(t){const n=dt[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 Lo=(e,t)=>{dt={},vr=!1,e==null||e.forEach(n=>{var r;n.metric in dt||(dt[n.metric]=[]),(r=dt[n.metric])==null||r.push(n)}),Tn=t},Pt={},mn=e=>{const t=new Eo(e);return Pt[e]=t,t},ko=async(e,t)=>{let n=Pt[e];n||(n=mn(e)),n.report(t)},Io=async e=>{const t=Object.values(Pt).map(n=>({name:n.name,values:n.collect()}));try{await e(JSON.stringify(t))}catch(n){Dn(`Error posting metrics: ${n}`)}},Uo=({reportingIntervalSeconds:e,postMetrics:t})=>{e?setInterval(()=>{Io(t)},e*1e3):_o()},Cn=(e,t)=>{const n=performance.now();document.hidden?setTimeout(()=>Cn(e,t),e):setTimeout(()=>{const r=performance.now()-n;t.report(r/1e3),setTimeout(()=>Cn(e,t),e)},0)},Ao=(e=1e3)=>{const t=mn(We.EventQueueLatency);Cn(e,t)};class xo{constructor(t){F(this,"payload");F(this,"promise");F(this,"reject",()=>{});F(this,"resolve",()=>{});this.payload=t,this.promise=new Promise((n,r)=>{this.reject=r,this.resolve=n})}resolveRequest(t){this.resolve(t)}}const Po={RATELIMIT_RESET_DEFAULT:10};let Ti=!1,Ci="",Ct=!1,Bi=!1,qt=[];const Oo=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?Ce.Gtm:e._segment?Ce.Segment:Ce.Snippet,Bn=e=>{var t;(t=e==null?void 0:e.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(Bi=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`),document.removeEventListener("securitypolicyviolation",Bn))},jn=(e="")=>{Ti=!0,Ci=e};function tt(e={}){const t={"Content-Type":"application/json","userleap-platform":xt.Web,"x-ul-sdk-version":"2.26.6",[oe.InstallationMethod]:Oo(e)};if(e.envId&&(t[oe.EnvironmentID]=e.envId),e.token&&(t.Authorization="Bearer "+e.token),e.userId&&(t[oe.UserID]=e.userId),e.visitorId&&(t[oe.VisitorID]=e.visitorId),e.partnerAnonymousId&&(t[oe.PartnerAnonymousId]=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[oe.PreviewMode]="1"),t}const Kr=async(e,t,n)=>{if(e)return{status:429};{const r=new xo(n);return qt.push(r),r.promise}},Be=async(e,t,n=0,r=!1,i=!1)=>{const s={url:e,options:t,attempt:n,shouldDropOnRateLimit:r};if(Ct&&!i)return Kr(r,i,s);const o={ok:!1,reportError:!1};if(Ti)return console.info(`UserLeap - ${Ci}`),o;try{t.headers=Object.assign(tt(),t.headers);const a=await fetch(e,t);if(a.status===429)if(!Ct&&!r||i){Ct=!0;const u=a.headers.has("ratelimit-reset")?Number(a.headers.get("ratelimit-reset")):Po.RATELIMIT_RESET_DEFAULT;return await tn(u*1e3),Be(e,t,0,r,!0)}else return Kr(r,!1,s);if(Ct=!1,qt.length&&(qt.map(l=>{const{url:u,options:c,attempt:p,shouldDropOnRateLimit:d}=l.payload;Be(u,c,p,d).then(h=>{l.resolveRequest(h)})}),qt=[]),a.ok){if(a.status===249)return jn(),o;const l=await a.text();try{return l&&l!=="OK"&&(a.json=JSON.parse(l)),a}catch{return{ok:!1,reportError:!1,error:new Error(`failed parsing response json for ${e} - ${l}`)}}}return a}catch(a){const l=n+1;return l>5||Bi?{ok:!1,reportError:!1,error:a}:(await tn(Math.pow(2,n)*1e3),Be(e,t,l))}};class Ro{constructor(t){F(this,"awaitingResolvers",[]);F(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 ji=new Ro(2),Do=e=>ji.setLimit(e),To=Pi(fetch),Co=async(e,t=3)=>ji.execute(async()=>{I(`Beginning upload of chunk ${e.chunkIndex} for survey: ${e.surveyId}`);const n=await To(e.uploadUrl,{body:e.data,method:"PUT",retries:t,retryDelay:i=>Math.pow(2,i)*1e3});I(`Completed upload of chunk ${e.chunkIndex} for survey: ${e.surveyId}`);const r=n.headers.get("ETag");if(!r)throw new Error(`Upload response did not include etag for upload ${e.uploadId}, part ${e.chunkIndex}`);return r}),Ni=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}return I(`Marking upload complete for survey: ${t}`),await Be(`${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},0,!1,!0)},j=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,K=Object.keys,z=Array.isArray;function H(e,t){return typeof t!="object"||K(t).forEach(function(n){e[n]=t[n]}),e}typeof Promise>"u"||j.Promise||(j.Promise=Promise);const _t=Object.getPrototypeOf,Bo={}.hasOwnProperty;function te(e,t){return Bo.call(e,t)}function nt(e,t){typeof t=="function"&&(t=t(_t(e))),(typeof Reflect>"u"?K:Reflect.ownKeys)(t).forEach(n=>{me(e,n,t[n])})}const Fi=Object.defineProperty;function me(e,t,n,r){Fi(e,t,H(n&&te(n,"get")&&typeof n.get=="function"?{get:n.get,set:n.set,configurable:!0}:{value:n,configurable:!0,writable:!0},r))}function Qe(e){return{from:function(t){return e.prototype=Object.create(t.prototype),me(e.prototype,"constructor",e),{extend:nt.bind(null,e.prototype)}}}}const jo=Object.getOwnPropertyDescriptor;function br(e,t){let n;return jo(e,t)||(n=_t(e))&&br(n,t)}const No=[].slice;function rn(e,t,n){return No.call(e,t,n)}function Ki(e,t){return t(e)}function pt(e){if(!e)throw new Error("Assertion Failed")}function Mi(e){j.setImmediate?setImmediate(e):setTimeout(e,0)}function $i(e,t){return e.reduce((n,r,i)=>{var s=t(r,i);return s&&(n[s[0]]=s[1]),n},{})}function ye(e,t){if(typeof t=="string"&&te(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=ye(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:ye(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){pt(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?z(e)&&!isNaN(parseInt(o))?e.splice(o,1):delete e[o]:e[o]=n;else{var l=e[o];l&&te(e,o)||(l=e[o]={}),ie(l,a,n)}}else n===void 0?z(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}function Vi(e){var t={};for(var n in e)te(e,n)&&(t[n]=e[n]);return t}const Fo=[].concat;function qi(e){return Fo.apply([],e)}const Wi="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(qi([8,16,32,64].map(e=>["Int","Uint","Float"].map(t=>t+e+"Array")))).filter(e=>j[e]),Ko=Wi.map(e=>j[e]);$i(Wi,e=>[e,!0]);let _e=null;function Ot(e){_e=typeof WeakMap<"u"&&new WeakMap;const t=Nn(e);return _e=null,t}function Nn(e){if(!e||typeof e!="object")return e;let t=_e&&_e.get(e);if(t)return t;if(z(e)){t=[],_e&&_e.set(e,t);for(var n=0,r=e.length;n<r;++n)t.push(Nn(e[n]))}else if(Ko.indexOf(e.constructor)>=0)t=e;else{const s=_t(e);for(var i in t=s===Object.prototype?{}:Object.create(s),_e&&_e.set(e,t),e)te(e,i)&&(t[i]=Nn(e[i]))}return t}const{toString:Mo}={};function Fn(e){return Mo.call(e).slice(8,-1)}const Kn=typeof Symbol<"u"?Symbol.iterator:"@@iterator",$o=typeof Kn=="symbol"?function(e){var t;return e!=null&&(t=e[Kn])&&t.apply(e)}:function(){return null},Je={};function pe(e){var t,n,r,i;if(arguments.length===1){if(z(e))return e.slice();if(this===Je&&typeof e=="string")return[e];if(i=$o(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 zi(e,t){le=e,Gi=t}var Gi=()=>!0;const Vo=!new Error("").stack;function ze(){if(Vo)try{throw ze.arguments,new Error}catch(e){return e}return new Error}function Mn(e,t){var n=e.stack;return n?(t=t||0,n.indexOf(e.name)===0&&(t+=(e.name+e.message).split(`
|
|
3
|
+
`).length),n.split(`
|
|
4
|
+
`).slice(t).filter(Gi).map(r=>`
|
|
5
|
+
`+r).join("")):""}var Hi=["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(Hi),qo={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 Xe(e,t){this._e=ze(),this.name=e,this.message=t}function Yi(e,t){return e+". Errors: "+Object.keys(t).map(n=>t[n].toString()).filter((n,r,i)=>i.indexOf(n)===r).join(`
|
|
6
|
+
`)}function sn(e,t,n,r){this._e=ze(),this.failures=t,this.failedKeys=r,this.successCount=n,this.message=Yi(e,t)}function ft(e,t){this._e=ze(),this.name="BulkError",this.failures=Object.keys(t).map(n=>t[n]),this.failuresByPos=t,this.message=Yi(e,t)}Qe(Xe).from(Error).extend({stack:{get:function(){return this._stack||(this._stack=this.name+": "+this.message+Mn(this._e,2))}},toString:function(){return this.name+": "+this.message}}),Qe(sn).from(Xe),Qe(ft).from(Xe);var Er=Sr.reduce((e,t)=>(e[t]=t+"Error",e),{});const Wo=Xe;var A=Sr.reduce((e,t)=>{var n=t+"Error";function r(i,s){this._e=ze(),this.name=n,i?typeof i=="string"?(this.message=`${i}${s?`
|
|
7
|
+
`+s:""}`,this.inner=s||null):typeof i=="object"&&(this.message=`${i.name} ${i.message}`,this.inner=i):(this.message=qo[t]||n,this.inner=null)}return Qe(r).from(Wo),e[t]=r,e},{});A.Syntax=SyntaxError,A.Type=TypeError,A.Range=RangeError;var Mr=Hi.reduce((e,t)=>(e[t+"Error"]=A[t],e),{}),Wt=Sr.reduce((e,t)=>(["Syntax","Type","Range"].indexOf(t)===-1&&(e[t+"Error"]=A[t]),e),{});function C(){}function St(e){return e}function zo(e,t){return e==null||e===St?t:function(n){return t(e(n))}}function Me(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function Go(e,t){return e===C?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?Me(r,this.onsuccess):r),i&&(this.onerror=this.onerror?Me(i,this.onerror):i),s!==void 0?s:n}}function Ho(e,t){return e===C?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?Me(n,this.onsuccess):n),r&&(this.onerror=this.onerror?Me(r,this.onerror):r)}}function Yo(e,t){return e===C?t:function(n){var r=e.apply(this,arguments);H(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?Me(i,this.onsuccess):i),s&&(this.onerror=this.onerror?Me(s,this.onerror):s),r===void 0?o===void 0?void 0:o:H(r,o)}}function Jo(e,t){return e===C?t:function(){return t.apply(this,arguments)!==!1&&e.apply(this,arguments)}}function Lr(e,t){return e===C?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)}}Wt.ModifyError=sn,Wt.DexieError=Xe,Wt.BulkError=ft;var Et={};const Ji=100,[$n,on,Vn]=typeof Promise>"u"?[]:(()=>{let e=Promise.resolve();if(typeof crypto>"u"||!crypto.subtle)return[e,_t(e),e];const t=crypto.subtle.digest("SHA-512",new Uint8Array([0]));return[t,_t(t),e]})(),Qi=on&&on.then,zt=$n&&$n.constructor,kr=!!Vn;var qn=!1,Qo=Vn?()=>{Vn.then(Bt)}:j.setImmediate?setImmediate.bind(null,Bt):j.MutationObserver?()=>{var e=document.createElement("div");new MutationObserver(()=>{Bt(),e=null}).observe(e,{attributes:!0}),e.setAttribute("i","1")}:()=>{setTimeout(Bt,0)},mt=function(e,t){ht.push([e,t]),an&&(Qo(),an=!1)},Wn=!0,an=!0,je=[],Gt=[],zn=null,Gn=St,Ze={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:qr,pgp:!1,env:{},finalize:function(){this.unhandleds.forEach(e=>{try{qr(e[0],e[1])}catch{}})}},U=Ze,ht=[],Ne=0,Ht=[];function k(e){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this.onuncatched=C,this._lib=!1;var t=this._PSD=U;if(le&&(this._stackHolder=ze(),this._prev=null,this._numPrev=0),typeof e!="function"){if(e!==Et)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,Zi(this,e)}const Hn={get:function(){var e=U,t=ln;function n(r,i){var s=!e.global&&(e!==U||t!==ln);const o=s&&!we();var a=new k((l,u)=>{Ir(this,new Xi(cn(r,e,s,o),cn(i,e,s,o),l,u,e))});return le&&ns(a,this),a}return n.prototype=Et,n},set:function(e){me(this,"then",e&&e.prototype===Et?Hn:{get:function(){return e},set:Hn.set})}};function Xi(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 Zi(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&&Rt();n&&typeof n.then=="function"?Zi(e,(i,s)=>{n instanceof k?n._then(i,s):n.then(i,s)}):(e._state=!0,e._value=n,es(e)),r&&Dt()}},Yn.bind(null,e))}catch(n){Yn(e,n)}}function Yn(e,t){if(Gt.push(t),e._state===null){var n=e._lib&&Rt();t=Gn(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,me(t,"stack",{get:()=>qn?r&&(r.get?r.get.apply(t):r.value):e.stack})}),function(r){je.some(i=>i._value===r._value)||je.push(r)}(e),es(e),n&&Dt()}}function es(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(),Ne===0&&(++Ne,mt(()=>{--Ne==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,++Ne,mt(Xo,[n,e,t])}else e._listeners.push(t)}function Xo(e,t,n){try{zn=t;var r,i=t._value;t._state?r=e(i):(Gt.length&&(Gt=[]),r=e(i),Gt.indexOf(i)===-1&&function(s){for(var o=je.length;o;)if(je[--o]._value===s._value)return void je.splice(o,1)}(t)),n.resolve(r)}catch(s){n.reject(s)}finally{zn=null,--Ne==0&&Ur(),--n.psd.ref||n.psd.finalize()}}function ts(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=Mn(o,0)):(i=o,s=""),t.push(i+(s?": "+s:"")+r)}return le&&((r=Mn(e._stackHolder,2))&&t.indexOf(r)===-1&&t.push(r),e._prev&&ts(e._prev,t,n)),t}function ns(e,t){var n=t?t._numPrev+1:0;n<100&&(e._prev=t,e._numPrev=n)}function Bt(){Rt()&&Dt()}function Rt(){var e=Wn;return Wn=!1,an=!1,e}function Dt(){var e,t,n;do for(;ht.length>0;)for(e=ht,ht=[],n=e.length,t=0;t<n;++t){var r=e[t];r[0].apply(null,r[1])}while(ht.length>0);Wn=!0,an=!0}function Ur(){var e=je;je=[],e.forEach(r=>{r._PSD.onunhandled.call(null,r._value,r)});for(var t=Ht.slice(0),n=t.length;n;)t[--n]()}function jt(e){return new k(Et,!1,e)}function N(e,t){var n=U;return function(){var r=Rt(),i=U;try{return Ae(n,!0),e.apply(this,arguments)}catch(s){t&&t(s)}finally{Ae(i,!1),r&&Dt()}}}nt(k.prototype,{then:Hn,_then:function(e,t){Ir(this,new Xi(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):jt(r)):this.then(null,r=>r&&r.name===t?n(r):jt(r))},finally:function(e){return this.then(t=>(e(),t),t=>(e(),jt(t)))},stack:{get:function(){if(this._stack)return this._stack;try{qn=!0;var e=ts(this,[],20).join(`
|
|
8
|
+
From previous: `);return this._state!==null&&(this._stack=e),e}finally{qn=!1}}},timeout:function(e,t){return e<1/0?new k((n,r)=>{var i=setTimeout(()=>r(new A.Timeout(t)),e);this.then(n,r).finally(clearTimeout.bind(null,i))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&me(k.prototype,Symbol.toStringTag,"Dexie.Promise"),Ze.env=rs(),nt(k,{all:function(){var e=pe.apply(null,arguments).map(Nt);return new k(function(t,n){e.length===0&&t([]);var r=e.length;e.forEach((i,s)=>k.resolve(i).then(o=>{e[s]=o,--r||t(e)},n))})},resolve:e=>{if(e instanceof k)return e;if(e&&typeof e.then=="function")return new k((n,r)=>{e.then(n,r)});var t=new k(Et,!0,e);return ns(t,zn),t},reject:jt,race:function(){var e=pe.apply(null,arguments).map(Nt);return new k((t,n)=>{e.map(r=>k.resolve(r).then(t,n))})},PSD:{get:()=>U,set:e=>U=e},totalEchoes:{get:()=>ln},newPSD:Ue,usePSD:st,scheduler:{get:()=>mt,set:e=>{mt=e}},rejectionMapper:{get:()=>Gn,set:e=>{Gn=e}},follow:(e,t)=>new k((n,r)=>Ue((i,s)=>{var o=U;o.unhandleds=[],o.onunhandled=s,o.finalize=Me(function(){(function(a){function l(){a(),Ht.splice(Ht.indexOf(l),1)}Ht.push(l),++Ne,mt(()=>{--Ne==0&&Ur()},[])})(()=>{this.unhandleds.length===0?i():s(this.unhandleds[0])})},o.finalize),e()},t,n,r))}),zt&&(zt.allSettled&&me(k,"allSettled",function(){const e=pe.apply(null,arguments).map(Nt);return new k(t=>{e.length===0&&t([]);let n=e.length;const r=new Array(n);e.forEach((i,s)=>k.resolve(i).then(o=>r[s]={status:"fulfilled",value:o},o=>r[s]={status:"rejected",reason:o}).then(()=>--n||t(r)))})}),zt.any&&typeof AggregateError<"u"&&me(k,"any",function(){const e=pe.apply(null,arguments).map(Nt);return new k((t,n)=>{e.length===0&&n(new AggregateError([]));let r=e.length;const i=new Array(r);e.forEach((s,o)=>k.resolve(s).then(a=>t(a),a=>{i[o]=a,--r||n(new AggregateError(i))}))})}));const W={awaits:0,echoes:0,id:0};var Zo=0,Yt=[],_n=0,ln=0,ea=0;function Ue(e,t,n,r){var i=U,s=Object.create(i);s.parent=i,s.ref=0,s.global=!1,s.id=++ea;var o=Ze.env;s.env=kr?{Promise:k,PromiseProp:{value:k,configurable:!0,writable:!0},all:k.all,race:k.race,allSettled:k.allSettled,any:k.any,resolve:k.resolve,reject:k.reject,nthen:$r(o.nthen,s),gthen:$r(o.gthen,s)}:{},t&&H(s,t),++i.ref,s.finalize=function(){--this.parent.ref||this.parent.finalize()};var a=st(s,e,n,r);return s.ref===0&&s.finalize(),a}function it(){return W.id||(W.id=++Zo),++W.awaits,W.echoes+=Ji,W.id}function we(){return!!W.awaits&&(--W.awaits==0&&(W.id=0),W.echoes=W.awaits*Ji,!0)}function Nt(e){return W.echoes&&e&&e.constructor===zt?(it(),e.then(t=>(we(),t),t=>(we(),$(t)))):e}function ta(e){++ln,W.echoes&&--W.echoes!=0||(W.echoes=W.id=0),Yt.push(U),Ae(e,!0)}function na(){var e=Yt[Yt.length-1];Yt.pop(),Ae(e,!1)}function Ae(e,t){var n=U;if((t?!W.echoes||_n++&&e===U:!_n||--_n&&e===U)||is(t?ta.bind(null,e):na),e!==U&&(U=e,n===Ze&&(Ze.env=rs()),kr)){var r=Ze.env.Promise,i=e.env;on.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 rs(){var e=j.Promise;return kr?{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:on.then,gthen:e.prototype.then}:{}}function st(e,t,n,r,i){var s=U;try{return Ae(e,!0),t(n,r,i)}finally{Ae(s,!1)}}function is(e){Qi.call($n,e)}function cn(e,t,n,r){return typeof e!="function"?e:function(){var i=U;n&&it(),Ae(t,!0);try{return e.apply(this,arguments)}finally{Ae(i,!1),r&&is(we)}}}function $r(e,t){return function(n,r){return e.call(this,cn(n,t),cn(r,t))}}(""+Qi).indexOf("[native code]")===-1&&(it=we=C);const Vr="unhandledrejection";function qr(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),H(r,i)):j.CustomEvent&&H(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 $=k.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))):$(s)}return i._promise(t,(s,o)=>Ue(()=>(U.trans=i,r(s,o,i)))).then(s=>i._completion.then(()=>s))}if(e._state.openComplete)return $(new A.DatabaseClosed(e._state.dbOpenError));if(!e._state.isBeingOpened){if(!e._options.autoOpen)return $(new A.DatabaseClosed);e.open().catch(C)}return e._state.dbReadyPromise.then(()=>Jn(e,t,n,r))}const Wr="3.2.7",Te="",Qn=-1/0,ce="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",ss="String expected.",yt=[],yn=typeof navigator<"u"&&/(MSIE|Trident|Edge)/.test(navigator.userAgent),ra=yn,ia=yn,os=e=>!/(dexie\.js|dexie\.min\.js)/.test(e),wn="__dbnames",Sn="readonly",En="readwrite";function $e(e,t){return e?t?function(){return e.apply(this,arguments)&&t.apply(this,arguments)}:e:t}const as={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function Ft(e){return typeof e!="string"||/\./.test(e)?t=>t:t=>(t[e]===void 0&&e in t&&delete(t=Ot(t))[e],t)}class sa{_trans(t,n,r){const i=this._tx||U.trans,s=this.name;function o(l,u,c){if(!c.schema[s])throw new A.NotFound("Table "+s+" not part of transaction");return n(c.idbtrans,c)}const a=Rt();try{return i&&i.db===this.db?i===U.trans?i._promise(t,o,r):Ue(()=>i._promise(t,o,r),{trans:i,transless:U.transless||U}):Jn(this.db,t,[this.name],o)}finally{a&&Dt()}}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(z(t))return new this.db.WhereClause(this,`[${t.join("+")}]`);const n=K(t);if(n.length===1)return this.where(n[0]).equals(t[n[0]]);const r=this.schema.indexes.concat(this.schema.primKey).filter(u=>{if(u.compound&&n.every(c=>u.keyPath.indexOf(c)>=0)){for(let c=0;c<n.length;++c)if(n.indexOf(u.keyPath[c])===-1)return!1;return!0}return!1}).sort((u,c)=>u.keyPath.length-c.keyPath.length)[0];if(r&&this.db._maxKey!==Te){const u=r.keyPath.slice(0,n.length);return this.where(u).equals(u.map(c=>t[c]))}!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(u,c){try{return s.cmp(u,c)===0}catch{return!1}}const[a,l]=n.reduce(([u,c],p)=>{const d=i[p],h=t[p];return[u||d,u||!d?$e(c,d&&d.multi?w=>{const y=ye(w,p);return z(y)&&y.some(g=>o(h,g))}:w=>o(h,ye(w,p))):c]},[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,z(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(te(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){H(this,t)})}add(t,n){const{auto:r,keyPath:i}=this.schema.primKey;let s=t;return i&&r&&(s=Ft(i)(t)),this._trans("readwrite",o=>this.core.mutate({trans:o,type:"add",keys:n!=null?[n]:null,values:[s]})).then(o=>o.numFailures?k.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"||z(t))return this.where(":id").equals(t).modify(n);{const r=ye(t,this.schema.primKey.keyPath);if(r===void 0)return $(new A.InvalidArgument("Given object does not contain its primary key"));try{typeof n!="function"?K(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=Ft(i)(t)),this._trans("readwrite",o=>this.core.mutate({trans:o,type:"put",values:[s],keys:n!=null?[n]:null})).then(o=>o.numFailures?k.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?k.reject(n.failures[0]):void 0)}clear(){return this._trans("readwrite",t=>this.core.mutate({trans:t,type:"deleteRange",range:as})).then(t=>t.numFailures?k.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 A.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(i&&i.length!==t.length)throw new A.InvalidArgument("Arguments objects and keys must have the same length");const u=t.length;let c=l&&a?t.map(Ft(l)):t;return this.core.mutate({trans:o,type:"add",keys:i,values:c,wantResults:s}).then(({numFailures:p,results:d,lastResult:h,failures:w})=>{if(p===0)return s?d:h;throw new ft(`${this.name}.bulkAdd(): ${p} of ${u} operations failed`,w)})})}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 A.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(i&&i.length!==t.length)throw new A.InvalidArgument("Arguments objects and keys must have the same length");const u=t.length;let c=l&&a?t.map(Ft(l)):t;return this.core.mutate({trans:o,type:"put",keys:i,values:c,wantResults:s}).then(({numFailures:p,results:d,lastResult:h,failures:w})=>{if(p===0)return s?d:h;throw new ft(`${this.name}.bulkPut(): ${p} of ${u} operations failed`,w)})})}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 ft(`${this.name}.bulkDelete(): ${r} of ${n} operations failed`,s)})}}function wt(e){var t={},n=function(o,a){if(a){for(var l=arguments.length,u=new Array(l-1);--l;)u[l-1]=arguments[l];return t[o].subscribe.apply(null,u),e}if(typeof o=="string")return t[o]};n.addEventType=s;for(var r=1,i=arguments.length;r<i;++r)s(arguments[r]);return n;function s(o,a,l){if(typeof o!="object"){var u;a||(a=Jo),l||(l=C);var c={subscribers:[],fire:l,subscribe:function(p){c.subscribers.indexOf(p)===-1&&(c.subscribers.push(p),c.fire=a(c.fire,p))},unsubscribe:function(p){c.subscribers=c.subscribers.filter(function(d){return d!==p}),c.fire=c.subscribers.reduce(a,l)}};return t[o]=n[o]=c,c}K(u=o).forEach(function(p){var d=u[p];if(z(d))s(p,u[p][0],u[p][1]);else{if(d!=="asap")throw new A.InvalidArgument("Invalid event config");var h=s(p,St,function(){for(var w=arguments.length,y=new Array(w);w--;)y[w]=arguments[w];h.subscribers.forEach(function(g){Mi(function(){g.apply(null,y)})})})}})}}function lt(e,t){return Qe(t).from({prototype:e}),t}function He(e,t){return!(e.filter||e.algorithm||e.or)&&(t?e.justLimit:!e.replayFilter)}function Ln(e,t){e.filter=$e(e.filter,t)}function kn(e,t,n){var r=e.replayFilter;e.replayFilter=r?()=>$e(r(),t()):t,e.justLimit=n&&!r}function Jt(e,t){if(e.isPrimKey)return t.primaryKey;const n=t.getIndexByKeyPath(e.index);if(!n)throw new A.Schema("KeyPath "+e.index+" on object store "+t.name+" is not indexed");return n}function zr(e,t,n){const r=Jt(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 Kt(e,t,n,r){const i=e.replayFilter?$e(e.filter,e.replayFilter()):e.filter;if(e.or){const s={},o=(a,l,u)=>{if(!i||i(l,u,d=>l.stop(d),d=>l.fail(d))){var c=l.primaryKey,p=""+c;p==="[object ArrayBuffer]"&&(p=""+new Uint8Array(c)),te(s,p)||(s[p]=!0,t(a,l,u))}};return Promise.all([e.or._iterate(o,n),Gr(zr(e,r,n),e.algorithm,o,!e.keysOnly&&e.valueMapper)])}return Gr(zr(e,r,n),$e(e.algorithm,i),t,!e.keysOnly&&e.valueMapper)}function Gr(e,t,n,r){var i=N(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=C},a=>{s.fail(a),o=C})||i(s.value,s,a=>o=a),o()})})}function G(e,t){try{const n=Hr(e),r=Hr(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 u=0;u<l;++u)if(i[u]!==s[u])return i[u]<s[u]?-1:1;return o===a?0:o<a?-1:1}(Yr(e),Yr(t));case"Array":return function(i,s){const o=i.length,a=s.length,l=o<a?o:a;for(let u=0;u<l;++u){const c=G(i[u],s[u]);if(c!==0)return c}return o===a?0:o<a?-1:1}(e,t)}}catch{}return NaN}function Hr(e){const t=typeof e;if(t!=="object")return t;if(ArrayBuffer.isView(e))return"binary";const n=Fn(e);return n==="ArrayBuffer"?"binary":n}function Yr(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e)}class oa{_read(t,n){var r=this._ctx;return r.error?r.table._trans(null,$.bind(null,r.error)):r.table._trans("readonly",t).then(n)}_write(t){var n=this._ctx;return n.error?n.table._trans(null,$.bind(null,n.error)):n.table._trans("readwrite",t,"locked")}_addAlgorithm(t){var n=this._ctx;n.algorithm=$e(n.algorithm,t)}_iterate(t,n){return Kt(this._ctx,t,n,this._ctx.table.core)}clone(t){var n=Object.create(this.constructor.prototype),r=Object.create(this._ctx);return t&&H(r,t),n._ctx=r,n}raw(){return this._ctx.valueMapper=null,this}each(t){var n=this._ctx;return this._read(r=>Kt(n,t,r,n.table.core))}count(t){return this._read(n=>{const r=this._ctx,i=r.table.core;if(He(r,!0))return i.count({trans:n,query:{index:Jt(r,i.schema),range:r.range}}).then(o=>Math.min(o,r.limit));var s=0;return Kt(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(u,c){return c?o(u[r[c]],c-1):u[i]}var a=this._ctx.dir==="next"?1:-1;function l(u,c){var p=o(u,s),d=o(c,s);return p<d?-a:p>d?a:0}return this.toArray(function(u){return u.sort(l)}).then(n)}toArray(t){return this._read(n=>{var r=this._ctx;if(r.dir==="next"&&He(r,!0)&&r.limit>0){const{valueMapper:i}=r,s=Jt(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 Kt(r,s=>i.push(s),n,r.table.core).then(()=>i)}},t)}offset(t){var n=this._ctx;return t<=0||(n.offset+=t,He(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 Ln(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 Ln(this._ctx,function(i){return t(i.value)}),n=this._ctx,r=t,n.isMatch=$e(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"&&He(n,!0)&&n.limit>0)return this._read(i=>{var s=Jt(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 Ln(this._ctx,function(i){var s=i.primaryKey.toString(),o=te(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=K(t),o=s.length;i=function(y){for(var g=!1,m=0;m<o;++m){var f=s[m],v=t[f];ye(y,f)!==v&&(ie(y,f,v),g=!0)}return g}}const a=n.table.core,{outbound:l,extractKey:u}=a.schema.primaryKey,c=this.db._options.modifyChunkSize||200,p=[];let d=0;const h=[],w=(y,g)=>{const{failures:m,numFailures:f}=g;d+=y-f;for(let v of K(m))p.push(m[v])};return this.clone().primaryKeys().then(y=>{const g=m=>{const f=Math.min(c,y.length-m);return a.getMany({trans:r,keys:y.slice(m,m+f),cache:"immutable"}).then(v=>{const b=[],_=[],E=l?[]:null,S=[];for(let L=0;L<f;++L){const B=v[L],D={value:Ot(B),primKey:y[m+L]};i.call(D,D.value,D)!==!1&&(D.value==null?S.push(y[m+L]):l||G(u(B),u(D.value))===0?(_.push(D.value),l&&E.push(y[m+L])):(S.push(y[m+L]),b.push(D.value)))}const P=He(n)&&n.limit===1/0&&(typeof t!="function"||t===In)&&{index:n.index,range:n.range};return Promise.resolve(b.length>0&&a.mutate({trans:r,type:"add",values:b}).then(L=>{for(let B in L.failures)S.splice(parseInt(B),1);w(b.length,L)})).then(()=>(_.length>0||P&&typeof t=="object")&&a.mutate({trans:r,type:"put",keys:E,values:_,criteria:P,changeSpec:typeof t!="function"&&t}).then(L=>w(_.length,L))).then(()=>(S.length>0||P&&t===In)&&a.mutate({trans:r,type:"delete",keys:S,criteria:P}).then(L=>w(S.length,L))).then(()=>y.length>m+f&&g(m+c))})};return g(0).then(()=>{if(p.length>0)throw new sn("Error modifying one or more objects",p,d,h);return y.length})})})}delete(){var t=this._ctx,n=t.range;return He(t)&&(t.isPrimKey&&!ia||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:u,numFailures:c})=>{if(c)throw new sn("Could not delete some values",Object.keys(a).map(p=>a[p]),o-c);return o-c}))}):this.modify(In)}}const In=(e,t)=>t.value=null;function aa(e,t){return e<t?-1:e===t?0:1}function la(e,t){return e>t?-1:e===t?0:1}function Q(e,t,n){var r=e instanceof cs?new e.Collection(e):e;return r._ctx.error=n?new n(t):new TypeError(t),r}function Ye(e){return new e.Collection(e,()=>ls("")).limit(0)}function ca(e,t,n,r,i,s){for(var o=Math.min(e.length,r.length),a=-1,l=0;l<o;++l){var u=t[l];if(u!==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],u)<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 Mt(e,t,n,r){var i,s,o,a,l,u,c,p=n.length;if(!n.every(y=>typeof y=="string"))return Q(e,ss);function d(y){i=function(m){return m==="next"?f=>f.toUpperCase():f=>f.toLowerCase()}(y),s=function(m){return m==="next"?f=>f.toLowerCase():f=>f.toUpperCase()}(y),o=y==="next"?aa:la;var g=n.map(function(m){return{lower:s(m),upper:i(m)}}).sort(function(m,f){return o(m.lower,f.lower)});a=g.map(function(m){return m.upper}),l=g.map(function(m){return m.lower}),u=y,c=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 w=0;return h._addAlgorithm(function(y,g,m){var f=y.key;if(typeof f!="string")return!1;var v=s(f);if(t(v,l,w))return!0;for(var b=null,_=w;_<p;++_){var E=ca(f,v,a[_],l[_],o,u);E===null&&b===null?w=_+1:(b===null||o(b,E)>0)&&(b=E)}return g(b!==null?function(){y.continue(b+c)}:m),!1}),h}function be(e,t,n,r){return{type:2,lower:e,upper:t,lowerOpen:n,upperOpen:r}}function ls(e){return{type:1,lower:e,upper:e}}class cs{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)?Ye(this):new this.Collection(this,()=>be(t,n,!r,!i))}catch{return Q(this,ce)}}equals(t){return t==null?Q(this,ce):new this.Collection(this,()=>ls(t))}above(t){return t==null?Q(this,ce):new this.Collection(this,()=>be(t,void 0,!0))}aboveOrEqual(t){return t==null?Q(this,ce):new this.Collection(this,()=>be(t,void 0,!1))}below(t){return t==null?Q(this,ce):new this.Collection(this,()=>be(void 0,t,!1,!0))}belowOrEqual(t){return t==null?Q(this,ce):new this.Collection(this,()=>be(void 0,t))}startsWith(t){return typeof t!="string"?Q(this,ss):this.between(t,t+Te,!0,!0)}startsWithIgnoreCase(t){return t===""?this.startsWith(t):Mt(this,(n,r)=>n.indexOf(r[0])===0,[t],Te)}equalsIgnoreCase(t){return Mt(this,(n,r)=>n===r[0],[t],"")}anyOfIgnoreCase(){var t=pe.apply(Je,arguments);return t.length===0?Ye(this):Mt(this,(n,r)=>r.indexOf(n)!==-1,t,"")}startsWithAnyOfIgnoreCase(){var t=pe.apply(Je,arguments);return t.length===0?Ye(this):Mt(this,(n,r)=>r.some(i=>n.indexOf(i)===0),t,Te)}anyOf(){const t=pe.apply(Je,arguments);let n=this._cmp;try{t.sort(n)}catch{return Q(this,ce)}if(t.length===0)return Ye(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=pe.apply(Je,arguments);if(t.length===0)return new this.Collection(this);try{t.sort(this._ascending)}catch{return Q(this,ce)}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 Ye(this);if(!t.every(f=>f[0]!==void 0&&f[1]!==void 0&&i(f[0],f[1])<=0))return Q(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",A.InvalidArgument);const l=!n||n.includeLowers!==!1,u=n&&n.includeUppers===!0;let c,p=i;function d(f,v){return p(f[0],v[0])}try{c=t.reduce(function(f,v){let b=0,_=f.length;for(;b<_;++b){const E=f[b];if(r(v[0],E[1])<0&&r(v[1],E[0])>0){E[0]=o(E[0],v[0]),E[1]=a(E[1],v[1]);break}}return b===_&&f.push(v),f},[]),c.sort(d)}catch{return Q(this,ce)}let h=0;const w=u?f=>i(f,c[h][1])>0:f=>i(f,c[h][1])>=0,y=l?f=>s(f,c[h][0])>0:f=>s(f,c[h][0])>=0;let g=w;const m=new this.Collection(this,()=>be(c[0][0],c[c.length-1][1],!l,!u));return m._ondirectionchange=f=>{f==="next"?(g=w,p=i):(g=y,p=s),c.sort(d)},m._addAlgorithm((f,v,b)=>{for(var _=f.key;g(_);)if(++h,h===c.length)return v(b),!1;return!!function(E){return!w(E)&&!y(E)}(_)||(this._cmp(_,c[h][1])===0||this._cmp(_,c[h][0])===0||v(()=>{p===i?f.continue(c[h][0]):f.continue(c[h][1])}),!1)}),m}startsWithAnyOf(){const t=pe.apply(Je,arguments);return t.every(n=>typeof n=="string")?t.length===0?Ye(this):this.inAnyRange(t.map(n=>[n,n+Te])):Q(this,"startsWithAnyOf() only works with strings")}}function se(e){return N(function(t){return Lt(t),e(t.target.error),!1})}function Lt(e){e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault()}const kt="storagemutated",Ee="x-storagemutated-1",xe=wt(null,kt);class ua{_lock(){return pt(!U.global),++this._reculock,this._reculock!==1||U.global||(U.lockOwnerFor=this),this}_unlock(){if(pt(!U.global),--this._reculock==0)for(U.global||(U.lockOwnerFor=null);this._blockedFuncs.length>0&&!this._locked();){var t=this._blockedFuncs.shift();try{st(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(pt(!this.idbtrans),!t&&!n)switch(r&&r.name){case"DatabaseClosedError":throw new A.DatabaseClosed(r);case"MissingAPIError":throw new A.MissingAPI(r.message,r);default:throw new A.OpenFailed(r)}if(!this.active)throw new A.TransactionInactive;return pt(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=N(i=>{Lt(i),this._reject(t.error)}),t.onabort=N(i=>{Lt(i),this.active&&this._reject(new A.Abort(t.error)),this.active=!1,this.on("abort").fire(i)}),t.oncomplete=N(()=>{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 $(new A.ReadOnly("Transaction is readonly"));if(!this.active)return $(new A.TransactionInactive);if(this._locked())return new k((s,o)=>{this._blockedFuncs.push([()=>{this._promise(t,n,r).then(s,o)},U])});if(r)return Ue(()=>{var s=new k((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 k((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=k.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 k((o,a)=>{r.then(l=>n._waitingQueue.push(N(o.bind(null,l))),l=>n._waitingQueue.push(N(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 A.Abort))}table(t){const n=this._memoizedTables||(this._memoizedTables={});if(te(n,t))return n[t];const r=this.schema[t];if(!r)throw new A.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?"++":"")+us(t)}}function us(e){return typeof e=="string"?e:e?"["+[].join.call(e,"+")+"]":""}function ds(e,t,n){return{name:e,primKey:t,indexes:n,mappedClass:null,idxByName:$i(n,r=>[r.name,r])}}let It=e=>{try{return e.only([[]]),It=()=>[[]],[[]]}catch{return It=()=>Te,Te}};function Zn(e){return e==null?()=>{}:typeof e=="string"?function(t){return t.split(".").length===1?r=>r[t]:r=>ye(r,t)}(e):t=>ye(t,e)}function Jr(e){return[].slice.call(e)}let da=0;function gt(e){return e==null?":id":typeof e=="string"?e:`[${e.join("+")}]`}function pa(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:u,upper:c,lowerOpen:p,upperOpen:d}=l;return u===void 0?c===void 0?null:t.upperBound(c,!!d):c===void 0?t.lowerBound(u,!!p):t.bound(u,c,!!p,!!d)}const{schema:i,hasGetAll:s}=function(l,u){const c=Jr(l.objectStoreNames);return{schema:{name:l.name,tables:c.map(p=>u.objectStore(p)).map(p=>{const{keyPath:d,autoIncrement:h}=p,w=z(d),y=d==null,g={},m={name:p.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:y,compound:w,keyPath:d,autoIncrement:h,unique:!0,extractKey:Zn(d)},indexes:Jr(p.indexNames).map(f=>p.index(f)).map(f=>{const{name:v,unique:b,multiEntry:_,keyPath:E}=f,S={name:v,compound:z(E),keyPath:E,unique:b,multiEntry:_,extractKey:Zn(E)};return g[gt(E)]=S,S}),getIndexByKeyPath:f=>g[gt(f)]};return g[":id"]=m.primaryKey,d!=null&&(g[gt(d)]=m.primaryKey),m})},hasGetAll:c.length>0&&"getAll"in u.objectStore(c[0])&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604)}}(e,n),o=i.tables.map(l=>function(u){const c=u.name;return{name:c,schema:u,mutate:function({trans:p,type:d,keys:h,values:w,range:y}){return new Promise((g,m)=>{g=N(g);const f=p.objectStore(c),v=f.keyPath==null,b=d==="put"||d==="add";if(!b&&d!=="delete"&&d!=="deleteRange")throw new Error("Invalid operation type: "+d);const{length:_}=h||w||{length:1};if(h&&w&&h.length!==w.length)throw new Error("Given keys array must have same length as given values array.");if(_===0)return g({numFailures:0,failures:{},results:[],lastResult:void 0});let E;const S=[],P=[];let L=0;const B=V=>{++L,Lt(V)};if(d==="deleteRange"){if(y.type===4)return g({numFailures:L,failures:P,results:[],lastResult:void 0});y.type===3?S.push(E=f.clear()):S.push(E=f.delete(r(y)))}else{const[V,M]=b?v?[w,h]:[w,null]:[h,null];if(b)for(let x=0;x<_;++x)S.push(E=M&&M[x]!==void 0?f[d](V[x],M[x]):f[d](V[x])),E.onerror=B;else for(let x=0;x<_;++x)S.push(E=f[d](V[x])),E.onerror=B}const D=V=>{const M=V.target.result;S.forEach((x,ve)=>x.error!=null&&(P[ve]=x.error)),g({numFailures:L,failures:P,results:d==="delete"?h:S.map(x=>x.result),lastResult:M})};E.onerror=V=>{B(V),D(V)},E.onsuccess=D})},getMany:({trans:p,keys:d})=>new Promise((h,w)=>{h=N(h);const y=p.objectStore(c),g=d.length,m=new Array(g);let f,v=0,b=0;const _=S=>{const P=S.target;m[P._pos]=P.result,++b===v&&h(m)},E=se(w);for(let S=0;S<g;++S)d[S]!=null&&(f=y.get(d[S]),f._pos=S,f.onsuccess=_,f.onerror=E,++v);v===0&&h(m)}),get:({trans:p,key:d})=>new Promise((h,w)=>{h=N(h);const y=p.objectStore(c).get(d);y.onsuccess=g=>h(g.target.result),y.onerror=se(w)}),query:function(p){return d=>new Promise((h,w)=>{h=N(h);const{trans:y,values:g,limit:m,query:f}=d,v=m===1/0?void 0:m,{index:b,range:_}=f,E=y.objectStore(c),S=b.isPrimaryKey?E:E.index(b.name),P=r(_);if(m===0)return h({result:[]});if(p){const L=g?S.getAll(P,v):S.getAllKeys(P,v);L.onsuccess=B=>h({result:B.target.result}),L.onerror=se(w)}else{let L=0;const B=g||!("openKeyCursor"in S)?S.openCursor(P):S.openKeyCursor(P),D=[];B.onsuccess=V=>{const M=B.result;return M?(D.push(g?M.value:M.primaryKey),++L===m?h({result:D}):void M.continue()):h({result:D})},B.onerror=se(w)}})}(s),openCursor:function({trans:p,values:d,query:h,reverse:w,unique:y}){return new Promise((g,m)=>{g=N(g);const{index:f,range:v}=h,b=p.objectStore(c),_=f.isPrimaryKey?b:b.index(f.name),E=w?y?"prevunique":"prev":y?"nextunique":"next",S=d||!("openKeyCursor"in _)?_.openCursor(r(v),E):_.openKeyCursor(r(v),E);S.onerror=se(m),S.onsuccess=N(P=>{const L=S.result;if(!L)return void g(null);L.___id=++da,L.done=!1;const B=L.continue.bind(L);let D=L.continuePrimaryKey;D&&(D=D.bind(L));const V=L.advance.bind(L),M=()=>{throw new Error("Cursor not stopped")};L.trans=p,L.stop=L.continue=L.continuePrimaryKey=L.advance=()=>{throw new Error("Cursor not started")},L.fail=N(m),L.next=function(){let x=1;return this.start(()=>x--?this.continue():this.stop()).then(()=>this)},L.start=x=>{const ve=new Promise((J,Pe)=>{J=N(J),S.onerror=se(Pe),L.fail=Pe,L.stop=at=>{L.stop=L.continue=L.continuePrimaryKey=L.advance=M,J(at)}}),Ge=()=>{if(S.result)try{x()}catch(J){L.fail(J)}else L.done=!0,L.start=()=>{throw new Error("Cursor behind last entry")},L.stop()};return S.onsuccess=N(J=>{S.onsuccess=Ge,Ge()}),L.continue=B,L.continuePrimaryKey=D,L.advance=V,Ge(),ve},g(L)},m)})},count({query:p,trans:d}){const{index:h,range:w}=p;return new Promise((y,g)=>{const m=d.objectStore(c),f=h.isPrimaryKey?m:m.index(h.name),v=r(w),b=v?f.count(v):f.count();b.onsuccess=N(_=>y(_.target.result)),b.onerror=se(g)})}}}(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:It(t),schema:i}}function er({_novip:e},t){const n=t.db,r=function(i,s,{IDBKeyRange:o,indexedDB:a},l){return{dbcore:function(c,p){return p.reduce((d,{create:h})=>({...d,...h(d)}),c)}(pa(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 un({_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?me(o,i,{get(){return this.table(i)},set(l){Fi(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 ha(e,t){return e._cfg.version-t._cfg.version}function fa(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;Ue(()=>{U.trans=s,U.transless=a,t===0?(K(i).forEach(l=>{Un(n,l,i[l].primKey,i[l].indexes)}),er(e,n),k.follow(()=>e.on.populate.fire(s)).catch(o)):function({_novip:l},u,c,p){const d=[],h=l._versions;let w=l._dbSchema=rr(l,l.idbdb,p),y=!1;const g=h.filter(f=>f._cfg.version>=u);function m(){return d.length?k.resolve(d.shift()(c.idbtrans)).then(m):k.resolve()}return g.forEach(f=>{d.push(()=>{const v=w,b=f._cfg.dbschema;ir(l,v,p),ir(l,b,p),w=l._dbSchema=b;const _=ps(v,b);_.add.forEach(S=>{Un(p,S[0],S[1].primKey,S[1].indexes)}),_.change.forEach(S=>{if(S.recreate)throw new A.Upgrade("Not yet support for changing primary key");{const P=p.objectStore(S.name);S.add.forEach(L=>nr(P,L)),S.change.forEach(L=>{P.deleteIndex(L.name),nr(P,L)}),S.del.forEach(L=>P.deleteIndex(L))}});const E=f._cfg.contentUpgrade;if(E&&f._cfg.version>u){er(l,p),c._memoizedTables={},y=!0;let S=Vi(b);_.del.forEach(D=>{S[D]=v[D]}),tr(l,[l.Transaction.prototype]),un(l,[l.Transaction.prototype],K(S),S),c.schema=S;const P=_r(E);let L;P&&it();const B=k.follow(()=>{if(L=E(c),L&&P){var D=we.bind(null,null);L.then(D,D)}});return L&&typeof L.then=="function"?k.resolve(L):B.then(()=>L)}}),d.push(v=>{(!y||!ra)&&function(b,_){[].slice.call(_.db.objectStoreNames).forEach(E=>b[E]==null&&_.db.deleteObjectStore(E))}(f._cfg.dbschema,v),tr(l,[l.Transaction.prototype]),un(l,[l.Transaction.prototype],l._storeNames,l._dbSchema),c.schema=l._dbSchema})}),m().then(()=>{var f,v;v=p,K(f=w).forEach(b=>{v.db.objectStoreNames.contains(b)||Un(v,b,f[b].primKey,f[b].indexes)})})}(e,t,s,n).catch(o)})}function ps(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&&!yn)o.recreate=!0,n.change.push(o);else{const a=i.idxByName,l=s.idxByName;let u;for(u in a)l[u]||o.del.push(u);for(u in l){const c=a[u],p=l[u];c?c.src!==p.src&&o.change.push(p):o.add.push(p)}(o.del.length>0||o.add.length>0||o.change.length>0)&&n.change.push(o)}}else n.add.push([r,s])}return n}function Un(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 rn(t.objectStoreNames,0).forEach(i=>{const s=n.objectStore(i);let o=s.keyPath;const a=Xn(us(o),o||"",!1,!1,!!s.autoIncrement,o&&typeof o!="string",!0),l=[];for(let c=0;c<s.indexNames.length;++c){const p=s.index(s.indexNames[c]);o=p.keyPath;var u=Xn(p.name,o,!!p.unique,!!p.multiEntry,!1,o&&typeof o!="string",!1);l.push(u)}r[i]=ds(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],u=o.index(l).keyPath,c=typeof u=="string"?u:"["+rn(u).join("+")+"]";if(t[s]){const p=t[s].idxByName[c];p&&(p.name=l,delete t[s].idxByName[c],t[s].idxByName[l]=p)}}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&j.WorkerGlobalScope&&j instanceof j.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(e._hasGetAll=!1)}class ma{_parseStoresSpec(t,n){K(t).forEach(r=>{if(t[r]!==null){var i=t[r].split(",").map((o,a)=>{const l=(o=o.trim()).replace(/([&*]|\+\+)/g,""),u=/^\[/.test(l)?l.match(/^\[(.*)\]$/)[1].split("+"):l;return Xn(l,u||null,/\&/.test(o),/\*/.test(o),/\+\+/.test(o),z(u),a===0)}),s=i.shift();if(s.multi)throw new A.Schema("Primary key cannot be multi-valued");i.forEach(o=>{if(o.auto)throw new A.Schema("Only primary key can be marked as autoIncrement (++)");if(!o.keyPath)throw new A.Schema("Index must have a name and cannot be an empty string")}),n[r]=ds(r,s,i)}})}stores(t){const n=this.db;this._cfg.storesSource=this._cfg.storesSource?H(this._cfg.storesSource,t):t;const r=n._versions,i={};let s={};return r.forEach(o=>{H(i,o._cfg.storesSource),s=o._cfg.dbschema={},o._parseStoresSpec(i,s)}),n._dbSchema=s,tr(n,[n._allTables,n,n.Transaction.prototype]),un(n,[n._allTables,n,n.Transaction.prototype,this._cfg.tables],K(s),s),n._storeNames=K(s),this}upgrade(t){return this._cfg.contentUpgrade=Lr(this._cfg.contentUpgrade||C,t),this}}function Ar(e,t){let n=e._dbNamesDB;return n||(n=e._dbNamesDB=new Fe(wn,{addons:[],indexedDB:e,IDBKeyRange:t}),n.version(1).stores({dbnames:"name"})),n.table("dbnames")}function xr(e){return e&&typeof e.databases=="function"}function sr(e){return Ue(function(){return U.letThrough=!0,e()})}function ya(){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 wa(e){const t=e._state,{indexedDB:n}=e._deps;if(t.isBeingOpened||e.idbdb)return t.dbReadyPromise.then(()=>t.dbOpenError?$(t.dbOpenError):e);le&&(t.openCanceller._stackHolder=ze()),t.isBeingOpened=!0,t.dbOpenError=null,t.openComplete=!1;const r=t.openCanceller;function i(){if(t.openCanceller!==r)throw new A.DatabaseClosed("db.open() was cancelled")}let s=t.dbReadyResolve,o=null,a=!1;const l=()=>new k((u,c)=>{if(i(),!n)throw new A.MissingAPI;const p=e.name,d=t.autoSchema?n.open(p):n.open(p,Math.round(10*e.verno));if(!d)throw new A.MissingAPI;d.onerror=se(c),d.onblocked=N(e._fireOnBlocked),d.onupgradeneeded=N(h=>{if(o=d.transaction,t.autoSchema&&!e._options.allowEmptyDB){d.onerror=Lt,o.abort(),d.result.close();const y=n.deleteDatabase(p);y.onsuccess=y.onerror=N(()=>{c(new A.NoSuchDatabase(`Database ${p} doesnt exist`))})}else{o.onerror=se(c);var w=h.oldVersion>Math.pow(2,62)?0:h.oldVersion;a=w<1,e._novip.idbdb=d.result,fa(e,w/10,o,c)}},c),d.onsuccess=N(()=>{o=null;const h=e._novip.idbdb=d.result,w=rn(h.objectStoreNames);if(w.length>0)try{const g=h.transaction((y=w).length===1?y[0]:y,"readonly");t.autoSchema?function({_novip:m},f,v){m.verno=f.version/10;const b=m._dbSchema=rr(0,f,v);m._storeNames=rn(f.objectStoreNames,0),un(m,[m._allTables],K(b),b)}(e,h,g):(ir(e,e._dbSchema,g),function(m,f){const v=ps(rr(0,m.idbdb,f),m._dbSchema);return!(v.add.length||v.change.some(b=>b.add.length||b.change.length))}(e,g)||console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.")),er(e,g)}catch{}var y;yt.push(e),h.onversionchange=N(g=>{t.vcFired=!0,e.on("versionchange").fire(g)}),h.onclose=N(g=>{e.on("close").fire(g)}),a&&function({indexedDB:g,IDBKeyRange:m},f){!xr(g)&&f!==wn&&Ar(g,m).put({name:f}).catch(C)}(e._deps,p),u()},c)}).catch(u=>u&&u.name==="UnknownError"&&t.PR1398_maxLoop>0?(t.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),l()):k.reject(u));return k.race([r,(typeof navigator>"u"?k.resolve():ya()).then(l)]).then(()=>(i(),t.onReadyBeingFired=[],k.resolve(sr(()=>e.on.ready.fire(e.vip))).then(function u(){if(t.onReadyBeingFired.length>0){let c=t.onReadyBeingFired.reduce(Lr,C);return t.onReadyBeingFired=[],k.resolve(sr(()=>c(e.vip))).then(u)}}))).finally(()=>{t.onReadyBeingFired=null,t.isBeingOpened=!1}).then(()=>e).catch(u=>{t.dbOpenError=u;try{o&&o.abort()}catch{}return r===t.openCanceller&&e._close(),$(u)}).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):z(l)?Promise.all(l).then(n,r):n(l)}}return i(t)()}function ga(e,t,n){var r=arguments.length;if(r<2)throw new A.InvalidArgument("Too few arguments");for(var i=new Array(r-1);--r;)i[r-1]=arguments[r];return n=i.pop(),[e,qi(i),n]}function hs(e,t,n,r,i){return k.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(()=>hs(e,t,n,null,i))):$(p)}const l=_r(i);let u;l&&it();const c=k.follow(()=>{if(u=i.call(o,o),u)if(l){var p=we.bind(null,null);u.then(p,p)}else typeof u.next=="function"&&typeof u.throw=="function"&&(u=or(u))},a);return(u&&typeof u.then=="function"?k.resolve(u).then(p=>o.active?p:$(new A.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))):c.then(()=>u)).then(p=>(r&&o._resolve(),o._completion.then(()=>p))).catch(p=>(o._reject(p),$(p)))})}function $t(e,t,n){const r=z(e)?e.slice():[e];for(let i=0;i<n;++i)r.push(t);return r}const va={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(c,p,d){const h=gt(c),w=i[h]=i[h]||[],y=c==null?0:typeof c=="string"?1:c.length,g=p>0,m={...d,isVirtual:g,keyTail:p,keyLength:y,extractKey:Zn(c),unique:!g&&d.unique};return w.push(m),m.isPrimaryKey||s.push(m),y>1&&o(y===2?c[0]:c.slice(0,y-1),p+1,d),w.sort((f,v)=>f.keyTail-v.keyTail),m}const a=o(r.primaryKey.keyPath,0,r.primaryKey);i[":id"]=[a];for(const c of r.indexes)o(c.keyPath,0,c);function l(c){const p=c.query.index;return p.isVirtual?{...c,query:{index:p,range:(d=c.query.range,h=p.keyTail,{type:d.type===1?2:d.type,lower:$t(d.lower,d.lowerOpen?e.MAX_KEY:e.MIN_KEY,h),lowerOpen:!0,upper:$t(d.upper,d.upperOpen?e.MIN_KEY:e.MAX_KEY,h),upperOpen:!0})}}:c;var d,h}return{...n,schema:{...r,primaryKey:a,indexes:s,getIndexByKeyPath:function(c){const p=i[gt(c)];return p&&p[0]}},count:c=>n.count(l(c)),query:c=>n.query(l(c)),openCursor(c){const{keyTail:p,isVirtual:d,keyLength:h}=c.query.index;return d?n.openCursor(l(c)).then(w=>w&&function(y){return Object.create(y,{continue:{value:function(m){m!=null?y.continue($t(m,c.reverse?e.MAX_KEY:e.MIN_KEY,p)):c.unique?y.continue(y.key.slice(0,h).concat(c.reverse?e.MIN_KEY:e.MAX_KEY,p)):y.continue()}},continuePrimaryKey:{value(m,f){y.continuePrimaryKey($t(m,e.MAX_KEY,p),f)}},primaryKey:{get:()=>y.primaryKey},key:{get(){const m=y.key;return h===1?m[0]:m.slice(0,h)}},value:{get:()=>y.value}})}(w)):n.openCursor(c)}}}}}};function Pr(e,t,n,r){return n=n||{},r=r||"",K(e).forEach(i=>{if(te(t,i)){var s=e[i],o=t[i];if(typeof s=="object"&&typeof o=="object"&&s&&o){const a=Fn(s);a!==Fn(o)?n[r+i]=t[i]:a==="Object"?Pr(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}),K(t).forEach(i=>{te(e,i)||(n[r+i]=t[i])}),n}const ba={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:u}=o.table(t).hook;switch(s.type){case"add":if(l.fire===C)break;return o._promise("readwrite",()=>c(s),!0);case"put":if(l.fire===C&&u.fire===C)break;return o._promise("readwrite",()=>c(s),!0);case"delete":if(a.fire===C)break;return o._promise("readwrite",()=>c(s),!0);case"deleteRange":if(a.fire===C)break;return o._promise("readwrite",()=>function(d){return p(d.trans,d.range,1e4)}(s),!0)}return n.mutate(s);function c(d){const h=U.trans,w=d.keys||function(y,g){return g.type==="delete"?g.keys:g.keys||g.values.map(y.extractKey)}(r,d);if(!w)throw new Error("Keys missing");return(d=d.type==="add"||d.type==="put"?{...d,keys:w}:{...d}).type!=="delete"&&(d.values=[...d.values]),d.keys&&(d.keys=[...d.keys]),function(y,g,m){return g.type==="add"?Promise.resolve([]):y.getMany({trans:g.trans,keys:m,cache:"immutable"})}(n,d,w).then(y=>{const g=w.map((m,f)=>{const v=y[f],b={onerror:null,onsuccess:null};if(d.type==="delete")a.fire.call(b,m,v,h);else if(d.type==="add"||v===void 0){const _=l.fire.call(b,m,d.values[f],h);m==null&&_!=null&&(m=_,d.keys[f]=m,r.outbound||ie(d.values[f],r.keyPath,m))}else{const _=Pr(v,d.values[f]),E=u.fire.call(b,_,m,v,h);if(E){const S=d.values[f];Object.keys(E).forEach(P=>{te(S,P)?S[P]=E[P]:ie(S,P,E[P])})}}return b});return n.mutate(d).then(({failures:m,results:f,numFailures:v,lastResult:b})=>{for(let _=0;_<w.length;++_){const E=f?f[_]:w[_],S=g[_];E==null?S.onerror&&S.onerror(m[_]):S.onsuccess&&S.onsuccess(d.type==="put"&&y[_]?d.values[_]:E)}return{failures:m,results:f,numFailures:v,lastResult:b}}).catch(m=>(g.forEach(f=>f.onerror&&f.onerror(m)),Promise.reject(m)))})}function p(d,h,w){return n.query({trans:d,values:!1,query:{index:r,range:h},limit:w}).then(({result:y})=>c({type:"delete",keys:y,trans:d}).then(g=>g.numFailures>0?Promise.reject(g.failures[0]):y.length<w?{failures:[],numFailures:0,lastResult:void 0}:p(d,{...h,lower:y[y.length-1],lowerOpen:!0},w)))}}}}})};function fs(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)G(t.keys[i],e[s])===0&&(r.push(n?Ot(t.values[i]):t.values[i]),++s);return r.length===e.length?r:null}catch{return null}}const _a={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=fs(r.keys,r.trans._cache,r.cache==="clone");return i?k.resolve(i):n.getMany(r).then(s=>(r.trans._cache={keys:r.keys,values:r.cache==="clone"?Ot(s):s},s))},mutate:r=>(r.type!=="add"&&(r.trans._cache=null),n.mutate(r))}}})};function Or(e){return!("from"in e)}const ue=function(e,t){if(!this){const n=new ue;return e&&"d"in e&&H(n,e),n}H(this,arguments.length?{d:1,from:e,to:arguments.length>1?t:e}:{d:0})};function Ut(e,t,n){const r=G(t,n);if(isNaN(r))return;if(r>0)throw RangeError();if(Or(e))return H(e,{from:t,to:n,d:1});const i=e.l,s=e.r;if(G(n,e.from)<0)return i?Ut(i,t,n):e.l={from:t,to:n,d:1,l:null,r:null},Qr(e);if(G(t,e.to)>0)return s?Ut(s,t,n):e.r={from:t,to:n,d:1,l:null,r:null},Qr(e);G(t,e.from)<0&&(e.from=t,e.l=null,e.d=s?s.d+1:1),G(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&&dn(e,i),s&&o&&dn(e,s)}function dn(e,t){Or(t)||function n(r,{from:i,to:s,l:o,r:a}){Ut(r,i,s),o&&n(r,o),a&&n(r,a)}(e,t)}function Sa(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(G(a.from,i.to)<=0&&G(a.to,i.from)>=0)return!0;G(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=Or(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&&G(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||G(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 Qr(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=Xr(o)}e.d=Xr(e)}function Xr({r:e,l:t}){return(e?t?Math.max(e.d,t.d):e.d:t?t.d:0)+1}nt(ue.prototype,{add(e){return dn(this,e),this},addKey(e){return Ut(this,e,e),this},addKeys(e){return e.forEach(t=>Ut(this,t,t)),this},[Kn](){return ar(this)}});const Ea={stack:"dbcore",level:0,create:e=>{const t=e.schema.name,n=new ue(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,u={...i,mutate:d=>{const h=d.trans,w=h.mutatedParts||(h.mutatedParts={}),y=E=>{const S=`idb://${t}/${r}/${E}`;return w[S]||(w[S]=new ue)},g=y(""),m=y(":dels"),{type:f}=d;let[v,b]=d.type==="deleteRange"?[d.range]:d.type==="delete"?[d.keys]:d.values.length<50?[[],d.values]:[];const _=d.trans._cache;return i.mutate(d).then(E=>{if(z(v)){f!=="delete"&&(v=E.results),g.addKeys(v);const S=fs(v,_);S||f==="add"||m.addKeys(v),(S||b)&&function(P,L,B,D){function V(M){const x=P(M.name||"");function ve(J){return J!=null?M.extractKey(J):null}const Ge=J=>M.multiEntry&&z(J)?J.forEach(Pe=>x.addKey(Pe)):x.addKey(J);(B||D).forEach((J,Pe)=>{const at=B&&ve(B[Pe]),vn=D&&ve(D[Pe]);G(at,vn)!==0&&(at!=null&&Ge(at),vn!=null&&Ge(vn))})}L.indexes.forEach(V)}(y,s,S,b)}else if(v){const S={from:v.lower,to:v.upper};m.add(S),g.add(S)}else g.add(n),m.add(n),s.indexes.forEach(S=>y(S.name).add(n));return E})}},c=({query:{index:d,range:h}})=>{var w,y;return[d,new ue((w=h.lower)!==null&&w!==void 0?w:e.MIN_KEY,(y=h.upper)!==null&&y!==void 0?y:e.MAX_KEY)]},p={get:d=>[o,new ue(d.key)],getMany:d=>[o,new ue().addKeys(d.keys)],count:c,query:c,openCursor:c};return K(p).forEach(d=>{u[d]=function(h){const{subscr:w}=U;if(w){const y=b=>{const _=`idb://${t}/${r}/${b}`;return w[_]||(w[_]=new ue)},g=y(""),m=y(":dels"),[f,v]=p[d](h);if(y(f.name||"").add(v),!f.isPrimaryKey){if(d!=="count"){const b=d==="query"&&l&&h.values&&i.query({...h,values:!1});return i[d].apply(this,arguments).then(_=>{if(d==="query"){if(l&&h.values)return b.then(({result:S})=>(g.addKeys(S),_));const E=h.values?_.result.map(a):_.result;h.values?g.addKeys(E):m.addKeys(E)}else if(d==="openCursor"){const E=_,S=h.values;return E&&Object.create(E,{key:{get:()=>(m.addKey(E.primaryKey),E.key)},primaryKey:{get(){const P=E.primaryKey;return m.addKey(P),P}},value:{get:()=>(S&&g.addKey(E.primaryKey),E.value)}})}return _})}m.add(n)}}return i[d].apply(this,arguments)}}),u}}}};class Fe{constructor(t,n){this._middlewares={},this.verno=0;const r=Fe.dependencies;this._options=n={addons:Fe.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:C,dbReadyPromise:null,cancelOpen:C,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3};var o;s.dbReadyPromise=new k(a=>{s.dbReadyResolve=a}),s.openCanceller=new k((a,l)=>{s.cancelOpen=l}),this._state=s,this.name=t,this.on=wt(this,"populate","blocked","versionchange","close",{ready:[Lr,C]}),this.on.ready.subscribe=Ki(this.on.ready.subscribe,a=>(l,u)=>{Fe.vip(()=>{const c=this._state;if(c.openComplete)c.dbOpenError||k.resolve().then(l),u&&a(l);else if(c.onReadyBeingFired)c.onReadyBeingFired.push(l),u&&a(l);else{a(l);const p=this;u||a(function d(){p.on.ready.unsubscribe(l),p.on.ready.unsubscribe(d)})}})}),this.Collection=(o=this,lt(oa.prototype,function(a,l){this.db=o;let u=as,c=null;if(l)try{u=l()}catch(w){c=w}const p=a._ctx,d=p.table,h=d.hook.reading.fire;this._ctx={table:d,index:p.index,isPrimKey:!p.index||d.schema.primKey.keyPath&&p.index===d.schema.primKey.name,range:u,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:c,or:p.or,valueMapper:h!==St?h:null}})),this.Table=function(a){return lt(sa.prototype,function(l,u,c){this.db=a,this._tx=c,this.name=l,this.schema=u,this.hook=a._allTables[l]?a._allTables[l].hook:wt(null,{creating:[Go,C],reading:[zo,St],updating:[Yo,C],deleting:[Ho,C]})})}(this),this.Transaction=function(a){return lt(ua.prototype,function(l,u,c,p,d){this.db=a,this.mode=l,this.storeNames=u,this.schema=c,this.chromeTransactionDurability=p,this.idbtrans=null,this.on=wt(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 k((h,w)=>{this._resolve=h,this._reject=w}),this._completion.then(()=>{this.active=!1,this.on.complete.fire()},h=>{var w=this.active;return this.active=!1,this.on.error.fire(h),this.parent?this.parent._reject(h):w&&this.idbtrans&&this.idbtrans.abort(),$(h)})})}(this),this.Version=function(a){return lt(ma.prototype,function(l){this.db=a,this._cfg={version:l,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})}(this),this.WhereClause=function(a){return lt(cs.prototype,function(l,u,c){this.db=a,this._ctx={table:l,index:u===":id"?null:u,or:c};const p=a._deps.indexedDB;if(!p)throw new A.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=It(n.IDBKeyRange),this._createTransaction=(a,l,u,c)=>new this.Transaction(a,l,u,this._options.chromeTransactionDurability,c),this._fireOnBlocked=a=>{this.on("blocked").fire(a),yt.filter(l=>l.name===this.name&&l!==this&&!l._state.vcFired).map(l=>l.on("versionchange").fire(a))},this.use(va),this.use(ba),this.use(Ea),this.use(_a),this.vip=Object.create(this,{_vip:{value:!0}}),i.forEach(a=>a(this))}version(t){if(isNaN(t)||t<.1)throw new A.Type("Given version is not a positive number");if(t=Math.round(10*t)/10,this.idbdb||this._state.isBeingOpened)throw new A.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(ha),r.stores({}),this._state.autoSchema=!1,r)}_whenReady(t){return this.idbdb&&(this._state.openComplete||U.letThrough||this._vip)?t():new k((n,r)=>{if(this._state.openComplete)return r(new A.DatabaseClosed(this._state.dbOpenError));if(!this._state.isBeingOpened){if(!this._options.autoOpen)return void r(new A.DatabaseClosed);this.open().catch(C)}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 wa(this)}_close(){const t=this._state,n=yt.indexOf(this);if(n>=0&&yt.splice(n,1),this.idbdb){try{this.idbdb.close()}catch{}this._novip.idbdb=null}t.dbReadyPromise=new k(r=>{t.dbReadyResolve=r}),t.openCanceller=new k((r,i)=>{t.cancelOpen=i})}close(){this._close();const t=this._state;this._options.autoOpen=!1,t.dbOpenError=new A.DatabaseClosed,t.isBeingOpened&&t.cancelOpen(t.dbOpenError)}delete(){const t=arguments.length>0,n=this._state;return new k((r,i)=>{const s=()=>{this.close();var o=this._deps.indexedDB.deleteDatabase(this.name);o.onsuccess=N(()=>{(function({indexedDB:a,IDBKeyRange:l},u){!xr(a)&&u!==wn&&Ar(a,l).delete(u).catch(C)})(this._deps,this.name),r()}),o.onerror=se(i),o.onblocked=this._fireOnBlocked};if(t)throw new A.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 K(this._allTables).map(t=>this._allTables[t])}transaction(){const t=ga.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(u=>{var c=u instanceof this.Table?u.name:u;if(typeof c!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return c}),t=="r"||t===Sn)o=Sn;else{if(t!="rw"&&t!=En)throw new A.InvalidArgument("Invalid transaction mode: "+t);o=En}if(i){if(i.mode===Sn&&o===En){if(!s)throw new A.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");i=null}i&&a.forEach(u=>{if(i&&i.storeNames.indexOf(u)===-1){if(!s)throw new A.SubTransaction("Table "+u+" not included in parent transaction.");i=null}}),s&&i&&!i.active&&(i=null)}}catch(u){return i?i._promise(null,(c,p)=>{p(u)}):$(u)}const l=hs.bind(null,this,o,a,i,r);return i?i._promise(o,l,"lock"):U.trans?st(U.transless,()=>this._whenReady(l)):this._whenReady(l)}table(t){if(!te(this._allTables,t))throw new A.InvalidTable(`Table ${t} does not exist`);return this._allTables[t]}}const La=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable";class ka{constructor(t){this._subscribe=t}subscribe(t,n,r){return this._subscribe(t&&typeof t!="function"?t:{next:t,error:n,complete:r})}[La](){return this}}function ms(e,t){return K(t).forEach(n=>{dn(e[n]||(e[n]=new ue),t[n])}),e}function Ia(e){let t,n=!1;const r=new ka(i=>{const s=_r(e);let o=!1,a={},l={};const u={get closed(){return o},unsubscribe:()=>{o=!0,xe.storagemutated.unsubscribe(h)}};i.start&&i.start(u);let c=!1,p=!1;function d(){return K(l).some(y=>a[y]&&Sa(a[y],l[y]))}const h=y=>{ms(a,y),d()&&w()},w=()=>{if(c||o)return;a={};const y={},g=function(m){s&&it();const f=()=>Ue(e,{subscr:m,trans:null}),v=U.trans?st(U.transless,f):f();return s&&v.then(we,we),v}(y);p||(xe(kt,h),p=!0),c=!0,Promise.resolve(g).then(m=>{n=!0,t=m,c=!1,o||(d()?w():(a={},l=y,i.next&&i.next(m)))},m=>{c=!1,n=!1,i.error&&i.error(m),u.unsubscribe()})};return w(),u});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 Oe=Fe;function Qt(e){let t=fe;try{fe=!0,xe.storagemutated.fire(e)}finally{fe=t}}nt(Oe,{...Wt,delete:e=>new Oe(e,{addons:[]}).delete(),exists:e=>new Oe(e,{addons:[]}).open().then(t=>(t.close(),!0)).catch("NoSuchDatabaseError",()=>!1),getDatabaseNames(e){try{return function({indexedDB:t,IDBKeyRange:n}){return xr(t)?Promise.resolve(t.databases()).then(r=>r.map(i=>i.name).filter(i=>i!==wn)):Ar(t,n).toCollection().primaryKeys()}(Oe.dependencies).then(e)}catch{return $(new A.MissingAPI)}},defineClass:()=>function(e){H(this,e)},ignoreTransaction:e=>U.trans?st(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:k.resolve(t)}catch(n){return $(n)}}},spawn:function(e,t,n){try{var r=or(e.apply(n,t||[]));return r&&typeof r.then=="function"?r:k.resolve(r)}catch(i){return $(i)}},currentTransaction:{get:()=>U.trans||null},waitFor:function(e,t){const n=k.resolve(typeof e=="function"?Oe.ignoreTransaction(e):e).timeout(t||6e4);return U.trans?U.trans.waitFor(n):n},Promise:k,debug:{get:()=>le,set:e=>{zi(e,e==="dexie"?()=>!0:os)}},derive:Qe,extend:H,props:nt,override:Ki,Events:wt,on:xe,liveQuery:Ia,extendObservabilitySet:ms,getByKeyPath:ye,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:Vi,deepClone:Ot,getObjectDiff:Pr,cmp:G,asap:Mi,minKey:Qn,addons:[],connections:yt,errnames:Er,dependencies:lr,semVer:Wr,version:Wr.split(".").map(e=>parseInt(e)).reduce((e,t,n)=>e+t/Math.pow(10,2*n))}),Oe.maxKey=It(Oe.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(xe(kt,e=>{if(!fe){let t;yn?(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||Qt(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&&Qt(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&&Qt(n.changedParts)}});const e=self.document&&navigator.serviceWorker;e&&e.addEventListener("message",function({data:t}){t&&t.type===Ee&&Qt(t.changedParts)})}k.rejectionMapper=function(e,t){if(!e||e instanceof Xe||e instanceof TypeError||e instanceof SyntaxError||!e.name||!Mr[e.name])return e;var n=new Mr[e.name](t||e.message,e);return"stack"in e&&me(n,"stack",{get:function(){return this.inner.stack}}),n},zi(le,os);var ot=(e=>(e.ReadyForUpload="ReadyForUpload",e.UploadComplete="UploadComplete",e))(ot||{}),Ke=(e=>(e.After="after",e.Before="before",e.BeforeAndAfter="beforeAndAfter",e))(Ke||{});const ys=async(e,t)=>{const n=performance.now();try{await e()}finally{const r=performance.now()-n;let i=Pt[t];i||(i=mn(t)),i.report(r/1e3)}},ws=(e,t)=>{const n=performance.now();try{e()}finally{const r=performance.now()-n;let i=Pt[t];i||(i=mn(t)),i.report(r/1e3)}},cr="sprig.sessionId",gs="sprig.disableReplayRecording",Ua=30,vs=()=>{Ie.setItem(gs,"disabled")},Ve=()=>!!Ie.getItem(gs),Aa=["did not allow mutations","called in an invalid security context"],xa=e=>{if(!e)return!0;for(const t of Aa)if(e.toLowerCase().includes(t))return!1;return!0},Pa=(e,t,{reportError:n=!0,extraInfo:r})=>{Ve()||t instanceof Error&&(vs(),xa(t==null?void 0:t.message)&&(n&&window.UserLeap.reportError(e,t,r),Da()))},Oa=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)}Pa(e,t,{reportError:n,extraInfo:r})},Ra=()=>{const e=Ie.getItem(cr);if(e)return I(`Found saved session id: ${e}`),Ie.removeItem(cr),e;const t=qe();return I(`Generating new uuid: ${t}`),t},Y=Ra();window.addEventListener("beforeunload",()=>{I(`Before page unload saving session id: ${Y}`),Ie.setItem(cr,Y)});const Da=async()=>{try{await Promise.allSettled([T.events.clear(),T.chunkUploads.clear(),T.pendingCaptures.clear()])}catch{}},An=(e,t,n=()=>!0)=>T.table(t).where("timestamp").below(e).and(n).delete(),Ta=()=>{T.events.where("sessionId").equals(Y).delete(),T.pendingCaptures.where("sessionId").equals(Y).delete()},Ca=e=>{const t=e.map(n=>({...n,sessionId:n.sessionId??Y}));return T.events.bulkAdd(t)},Ba=async(e,t)=>{let n=[];return await ys(async()=>{n=await T.events.where("[sessionId+timestamp]").between([Y,e],[Y,t]).toArray()},We.ReplayGetEventsBetween),n},ja=(e,t,n)=>{const r=new Date,i=r.setMinutes(r.getMinutes()+(n??Ua));return T.events.where("[sessionId+timestamp]").between([Y,e],[Y,t]).modify({expiredAt:i})},Na=e=>T.chunkUploads.add({...e,sessionId:e.sessionId??Y}),Fa=(e,t)=>T.chunkUploads.update(e,{data:null,etag:t,status:ot.UploadComplete}),Ka=({status:e,uploadId:t})=>t?T.chunkUploads.where({uploadId:t,status:e}).toArray():T.chunkUploads.where({sessionId:Y,status:e}).toArray(),Ma=e=>T.chunkUploads.where({uploadId:e,status:ot.UploadComplete}).toArray(),$a=e=>T.chunkUploads.where({uploadId:e,status:ot.UploadComplete}).delete(),Va=e=>T.pendingCaptures.add({...e,sessionId:e.sessionId??Y,canUpload:!1}),qa=()=>T.pendingCaptures.where("sessionId").equals(Y).and(e=>e.targetTimestamp<Date.now()).toArray(),Wa=()=>T.pendingCaptures.where("sessionId").equals(Y).toArray(),za=e=>T.pendingCaptures.where("sessionId").equals(Y).and(t=>t.captureParams.responseGroupId===e).modify({canUpload:!0}),Ga=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 Ha extends Fe{constructor(){super("replayStorage",{autoOpen:!1});F(this,"events");F(this,"chunkUploads");F(this,"pendingCaptures")}}const T=new Ha;T.version(1).stores({events:"uuid, timestamp, [sessionId+timestamp]",chunkUploads:"uuid, timestamp, [sessionId+status], [uploadId+status], [sessionId+status+uploadId]",pendingCaptures:"uuid, timestamp, [sessionId+targetTimestamp]"});T.open().catch(e=>{Oi(`Error opening replay storage: ${JSON.stringify(e)}`),vs()});const Ya=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 Zr=1,ur=5e3,Xt=6e4;const Ja=5,ei=1e3,bs=30,pn=bs+Ja,Rr="sprig.pendingCount";let ti=0,ni=Date.now(),gn=!1,Zt;var dr=(e=>(e.Left="left_click",e.Right="right_click",e))(dr||{});const Qa=async(e,t,n,r=2,i)=>{try{if(Ve()){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&&(Zr=i.minAvailableGb),!await Ga(Zr)){Dn("Minimum storage not available");return}I("Initializing replay"),i!=null&&i.minDuration&&(ur=i.minDuration),i!=null&&i.batchDuration&&(Xt=i.batchDuration),Do(r),il(),el(t+pn,30*60,t+pn),tl(),window.rrwebRecord||(I("Loading recording script"),await Ya(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){Dn("Record script failed to set global function");return}let o=!0,a=0;Zt=s({checkoutEveryNms:bs*1e3,sampling:{input:"last",scroll:250,media:800},emit:(l,u)=>{if(Ve())return;if(ni=Date.now(),u&&l.type===4)a=performance.now();else if(u&&a&&l.type===2){const p=performance.now()-a;ko(We.ReplayFullSnapshot,p/1e3)}const c=o||!!u;o=!1,Xa({uuid:qe(),event:JSON.stringify(l),isValidStart:c,timestamp:Date.now()})},...i}),gn=!0,ti||(ti=window.setInterval(()=>{Date.now()-ni>ei&&ge("Sprig_Noop",{})},ei))}catch(s){return ne("Error initializing replay",s)}};let pr=!1,hr=[];const Xa=e=>{hr.push(e),pr||Za()},Za=()=>{pr=!0,setTimeout(async()=>{if(Ve())return;const e=hr;hr=[],pr=!1,ws(async()=>{try{await Ca(e)}catch(t){ne("Error storing replay events",t)}},We.ReplayAddEventBatch)},500)},el=(e=6*60,t=30*60,n=4*60)=>{const r=setInterval(()=>{const i=Date.now();Ve()||(bt(`Performing periodic replay data cleanup / Event Seconds ${e} / Chunk Seconds ${t} / Pending Capture Seconds ${n}`),ys(()=>T.transaction("rw!",T.events,T.chunkUploads,T.pendingCaptures,()=>{An(i-e*1e3,"events",s=>s.expiredAt===void 0||s.expiredAt<i-e*1e3),An(i-t*1e3,"chunkUploads"),An(i-n*1e3,"pendingCaptures",s=>s.canUpload===void 0||s.canUpload===!1)}).catch(s=>{clearInterval(r),ne("Error deleting table rows",s)}),We.ReplayCleanup),I("Cleanup complete"))},3e4)},tl=(e=5)=>{setInterval(cl,e*1e3)},nl=async(e,t,n,r,i)=>{try{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 Ba(e,s);if(!(a!=null&&a.length))return I(`No events found ${o}`),[r,[]];if(!r){I(`Searching for valid start in ${a.length} events ${o}`);let l=-1;if(a==null||a.forEach((c,p)=>{if(!c.isValidStart)return;const d=c.timestamp<=t;(l<0||d)&&(l=p)}),l<0)return I(`No valid start found in ${a.length} events ${o}`),[];const u=a[l].timestamp;return I(`Found valid start at: ${new Date(u).toLocaleTimeString()} in events ${o}`),[!0,a==null?void 0:a.slice(l)]}return[r,a]}catch(s){ne("Error getting events batch",s)}},rl=(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},_s=e=>Promise.all(e.map(async t=>{const n=await Co(t);return await Fa(t.uuid,n),t.uploadId})),Ss=async e=>{I(`Marking upload complete if finished: ${e}`);const t=await Ma(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 Ni({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 $a(e),I(`Done cleaning up chunks for ${e}`)},il=async()=>{try{let e=[];if(await T.transaction("rw",T.chunkUploads,async()=>{e=await Ka({status:ot.ReadyForUpload}).catch(n=>{ne("chunkUploads transaction error",n)})}),!(e!=null&&e.length))return;const t=await _s(e);I(`Finished uploading unfinished chunks for ${t}`),t!=null&&t.length&&await Promise.all(t.map(async n=>{n&&await Ss(n)}))}catch(e){ne("Error getting chunk upload uuids",e)}},sl=async(e,t)=>{await _s(t),I(`Done uploading chunks for uploads: ${e.join(",")}`),await Promise.all(e.map(n=>Ss(n)))},ol=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,[u,c]=[0,0];const p=e-pn*1e3,d=[];let h=[];I(`Getting events between ${new Date(e).toLocaleTimeString()} and ${new Date(t).toLocaleTimeString()}`),I(`Using batch duration: ${Xt}ms`);for(let y=p;y<t;y+=Xt){if([l,h]=await nl(y,e,t,l,Xt),!(h!=null&&h.length)){I("No events found");continue}u===0&&(u=h[0].timestamp),c=h[h.length-1].timestamp,I(`Last event time in batch: ${new Date(c).toLocaleTimeString()}`);const g=`${a?",":"["}${h.map(f=>f.event).join(",")}`,m=r.encode(g);n&&s===null&&(bt("Attempting compression"),o=new window.CompressionStream("gzip"),s=o.writable.getWriter()),ws(()=>{n&&s?s.write(m):d.push(m)},We.ReplayCompression),a=!0}if(c-u<ur)return I(`Replay duration is shorter than minimum of ${ur}ms / Start:${u} / End:${c}`),null;const w=r.encode("]");return bt("Writing final close brace"),s&&o?(s.write(w),s.close(),i=new Uint8Array(await new Response(o.readable).arrayBuffer())):(d.push(w),i=ol(d)),I("Finished generating file data"),i},al=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){if(o instanceof Error&&window.UserLeap.reportError("Error compressing replay",o),n)try{r=await ri(s,i,!1)}catch(a){ne("fileData fallback failed",a)}}return r},ii=async e=>{const{surveyId:t,responseGroupId:n,visitorId:r,apiUrl:i,completeUploadHeaders:s,replayParams:o,triggerTimestamp:a}=e,l=await al(o.replayDurationSeconds*1e3,a);if(l!=null&&l.length)I(`Found file data for survey: ${t}`);else{I(`File data is empty for survey: ${t}`);return}const u=rl(l,o.minimumChunkSizeMb,o.signedUrls.length);I(`Got ${u.length} chunks for survey: ${t}`);const c=await Promise.all(u.map(async(p,d)=>{const h=qe(),w={apiUrl:i,chunkIndex:d+1,completeUploadHeaders:s,etag:null,responseGroupId:n,status:ot.ReadyForUpload,surveyId:t,timestamp:a,totalChunks:u.length,data:p,uploadId:o.uploadId,uploadUrl:o.signedUrls[d].url,uuid:h,visitorId:r};return I(`Recording chunk upload: ${JSON.stringify({index:w.chunkIndex,surveyId:w.surveyId,uploadId:w.uploadId,size:p.length,id:h},null,2)}`),await Na(w),I(`Done creating chunk upload: ${h}`),w}));I(`All chunk records created. Beginning upload for survey: ${t}`),await sl([o.uploadId],c)},Es=async(e,t)=>{try{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)}`),Ve()){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(O.QuestionAnswered,o),0),r.replayDurationType===Ke.Before?await ii(e):await za(s)};if(r.replayDurationType===Ke.After||r.replayDurationType===Ke.BeforeAndAfter){n||(I("Attaching QuestionAnswered listener for non-standalone replay"),R.on(O.QuestionAnswered,o)),I(`Scheduling capture for replay of type: ${r.replayDurationType}`),await ll(e);return}if(n||t)I(`Proceeding to capture replay for survey: ${e.surveyId} / standalone? ${n} / canUpload? ${t}`),await ii(e);else{const a=pn+r.replayDurationSeconds,l=i-a*1e3,u=i;I(`Setting expiry minutes to ${r.expirationTimeLimitMinutes} for events from ${new Date(l).toLocaleTimeString()} to ${new Date(u).toLocaleTimeString()}`),await ja(l,u,r.expirationTimeLimitMinutes),I("Attaching QuestionAnswered listener"),R.on(O.QuestionAnswered,o)}}catch(n){ne("Error scheduling or capturing replay",n)}},si=()=>{if(Ve()){bt("Not clearing user data, replay is disabled");return}try{Ta()}catch(e){ne("Error clearing session event data",e)}};let he=Ie.getItem(Rr);const ll=async e=>{I(`Scheduling replay capture: ${JSON.stringify(e)}`);const{surveyId:t}=e,n=await Wa(),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===Ke.BeforeAndAfter&&(i.replayParams.replayDurationSeconds*=2),i.replayParams.replayDurationType=Ke.Before;const s=e.triggerTimestamp+e.replayParams.replayDurationSeconds*1e3;return i.triggerTimestamp=s,he=he?(parseInt(he)+1).toString():"1",Ie.setItem(Rr,he),Va({uuid:qe(),targetTimestamp:s,timestamp:Date.now(),captureParams:i})},cl=async()=>{try{if(he&&parseInt(he)>0){const e=await qa();e.length&&await Promise.all(e.map(async t=>{await T.pendingCaptures.delete(t.uuid),await Es(t.captureParams,t.canUpload)})),he=(parseInt(he)-e.length).toString(),Ie.setItem(Rr,he)}}catch(e){ne("Error initiating pending captures",e)}},ge=(e,t)=>{var n,r;if(gn)try{(r=(n=window.rrwebRecord)==null?void 0:n.addCustomEvent)==null||r.call(n,e,t)}catch(i){ne("Error recording custom event",i)}},oi=e=>{e.description&&(e.description=Dr(e.description)),ge("Sprig_PageView",e)},ul=e=>{ge("Sprig_TrackEvent",e)},dl=e=>{ge("Sprig_ShowSurvey",e)},pl=e=>{ge("Sprig_SubmitSurvey",e)},hl=e=>{var t;(t=e==null?void 0:e.elementAttributes)!=null&&t.text&&(e.elementAttributes.text=Dr(e.elementAttributes.text)),ge("Sprig_Click",e)},fl=e=>{ge("Sprig_Refresh",e)},ml=e=>{e.currentPageTitle&&(e.currentPageTitle=Dr(e.currentPageTitle)),ge("Sprig_BackForward",e)},yl=e=>{ge("Sprig_Keystroke",e)},ne=(e,t,{reportError:n}={reportError:!0})=>(Zt&&(Zt(),Zt=void 0),gn=!1,Oi(`${e} - ${JSON.stringify(t)}`),Oa(e,t,{reportError:n})),Ls=()=>gn,Dr=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),wl=({reportingIntervalSeconds:e,thresholds:t,postMetrics:n})=>{Lo(t,(r,i)=>{if(Ls()){const s=`Value: ${r} on ${i.metric} violated threshold of ${i.type} ${i.value}`;ne("Threshold violated",new Error(s),{reportError:!1}),So()}}),Uo({reportingIntervalSeconds:e,postMetrics:n}),Ao()},xn={capture:!0},gl=["a","button","input","option","li","link"],vl=["Escape","Enter","Backspace","F5","Tab"],bl=["label","type","role","title","placeholder","errormessage","valuetext","href"],ai="aria-",_l=e=>{if(!e.tagName)return"No tagName";const t=e.getAttribute("type");return t?`${t} ${e.tagName.toLowerCase()}`:e.tagName.toLowerCase()},li=e=>{var r;if(((r=e.tagName)==null?void 0:r.toLowerCase())==="html")return{element:"html"};const t=e.textContent,n=t?{text:t}:{};n.element=_l(e);for(const i of e.attributes){let s=i.name;const o=i.value;s.startsWith(ai)&&(s=s.substring(ai.length)),bl.includes(s)&&(n[s]=o)}return n},Sl=e=>{var i;if(!e)return{};const n={...li(e)},r=e.parentElement;if(r&&gl.includes((i=r.tagName)==null?void 0:i.toLowerCase())){const s=li(r);Object.assign(n,s)}return n},ks=(e,t)=>{hl({x:t.x,y:t.y,type:e,elementAttributes:Sl(t.target)})},El=e=>t=>ks(e,t),Ll=e=>{vl.includes(e.key)&&yl({key:e.key})},kl=()=>{window.performance.getEntriesByType("navigation").map(t=>t.type).includes("reload")&&fl({url:window.location.href,currentPageTitle:document.title})},Il=()=>{window.performance.getEntriesByType("navigation").map(t=>t.type).includes("back_forward")&&ml({curUrl:window.location.href,fromUrl:document.referrer,currentPageTitle:document.title})},Ul=()=>{window.addEventListener("click",El(dr.Left),xn),window.addEventListener("mousedown",e=>{e.button===2&&ks(dr.Right,e)},xn),window.addEventListener("keydown",Ll,xn),kl(),Il()},Al=["popState","pushState","replaceState"],xl={test:"test"},ct="!email",Pl=["ios","android"],Le="environments",fr="pageUrl",Re="visitors",ci="ul-view-sdk-script",ui=Object.freeze({contains:(e,t)=>t.includes(e),notContains:(e,t)=>!t.includes(e),exactly:(e,t)=>t===e,notExactly:(e,t)=>t!==e,startsWith:(e,t)=>t.startsWith(e),endsWith:(e,t)=>t.endsWith(e),regex:(e,t)=>new RegExp(e).test(t),legacy:(e,t)=>new RegExp(e,"i").test(t)});function Tr(e,t){const{matchType:n,pattern:r}=e,i=n?ui[n]:ui.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}function Ol(e,t){const{pageUrlEvents:n,interactiveEvents:r,dismissOnPageChange:i}=window.UserLeap._config;if(!i)return!0;const s=[];n&&n.length&&s.push(...n),r&&r.length&&s.push(...r);const o=e&&s.find(a=>a.id===e);return o?Tr(o,window.location.href):t===window.location.href}function At(e){const{pageUrlEvents:t,interactiveEvents:n,dismissOnPageChange:r,platform:i}=window.UserLeap._config;if(i&&i!==xt.Web)return;const s=De("trackStartUrl"),o=s?String(s):null;t&&xs(window.location.href),n&&(Us(),Rl()),r&&o&&o!==window.location.href&&e&&Al.includes(e.type)&&window.UserLeap("dismissActiveSurvey",Se.PageChange)}const Is={capture:!0},Rl=()=>{const t=window.UserLeap._config.interactiveEvents.filter(r=>Tr(r,window.location.href)).map(r=>{const{name:i,properties:s}=r,{selector:o,innerText:a}=s;return o?l=>{if(Fr(l.target))try{l.target.closest(o)&&window.UserLeap("track",i)}catch{}return!1}:l=>(Fr(l.target)&&l.target.innerText===a&&window.UserLeap("track",i),!1)}),n=r=>t.forEach(i=>i(r));window.UserLeap._config.interactiveEventsHandler=n,window.addEventListener("click",n,Is)},Us=()=>{window.UserLeap._config.interactiveEventsHandler&&window.removeEventListener("click",window.UserLeap._config.interactiveEventsHandler,Is),delete window.UserLeap._config.interactiveEventsHandler};function Dl(){["hashchange","popstate"].forEach(e=>window.addEventListener(e,At,!0))}function Tl(){["hashchange","popstate"].forEach(e=>window.removeEventListener(e,At,!0)),window.UserLeap._config.interactiveEvents&&Us()}function ae(e,t,n){const r=[window.UserLeap._API_URL,"sdk",e];return t&&t.forEach(i=>{r.push(i),i===Le?r.push(window.UserLeap.envId):i===Re&&r.push(Cr())}),n&&r.push(n),r.join("/")}function Cl(e,t){let n=ae("1",[Le],"questions?");return e!=null&&(n+=`&vid=${e}`),t&&(t.surveyId&&(n+=`&surveyid=${t.surveyId}`),t.surveyTemplateId&&(n+=`&surveytemplateid=${t.surveyTemplateId}`),t.previewLanguage&&(n+=`&previewLanguage=${encodeURIComponent(t.previewLanguage)}`)),n}function De(e){const t=Z.getItem(ee.Credentials);if(t)try{const r=JSON.parse(t)[window.UserLeap.envId];return r&&r[e]||null}catch(n){n instanceof Error&&(n.stack=t,window.UserLeap.reportError("Failed to parse local storage credentials",n)),console.warn("[Sprig] (ERR-427) Failed to lookup saved ids",n)}return null}function X(e,t){const n=Z.getItem(ee.Credentials);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{Z.setItem(ee.Credentials,JSON.stringify(r))}catch(s){s instanceof Error&&console.warn(`[Sprig] (ERR-426) Unable to write to Local Storage:: ${s.message}`)}}function As(){window.previewMode||(window.UserLeap.visitorId=qe(),I(`Generating new vid: ${window.UserLeap.visitorId}`),X("vid",window.UserLeap.visitorId),R.emit(O.VisitorIDUpdated,{visitorId:window.UserLeap.visitorId}))}function Cr(){return window.previewMode?"0":window.UserLeap.visitorId||""}function xs(e,t,n){var c;if(e.endsWith("mock_snippet.html"))return;I(`Tracking page view: ${e}`);const r=window.UserLeap._config.pageUrlEvents;let i=!1;if(r&&r.length)for(let p=0;p<r.length&&(i=Tr(r[p],e),!i);p++);if(!i)return;window.UserLeap.debugMode&&console.info("[DEBUG] Sprig trackPageView",e);const s=10,o=1;let a=[];const l={viewedAt:Date.now(),location:e},u=Z.getItem(ee.PageViews);try{if(a=u?JSON.parse(u):[],Array.isArray(a)||(a=[]),a.length>0){const p=a[a.length-1],d=(Date.now()-p.viewedAt)/1e3;if(p.location!=e&&d>o){const h=(c=document==null?void 0:document.querySelector('meta[name="description"]'))==null?void 0:c.getAttribute("content");oi({...h&&{description:h},url:e,referrer:document.referrer,pageTitle:document.title})}(p.location!=e&&d>o||d>s)&&(window.UserLeap._queue.push(["track",fr,t,{url:e},n]),a.push(l))}else window.UserLeap._queue.push(["track",fr,t,{url:e},n]),a.push(l),oi({url:e});a.length>5&&a.splice(0,a.length-5),Z.setItem(ee.PageViews,JSON.stringify(a))}catch(p){p instanceof Error&&window.UserLeap.reportError("trackPageView",p,{pageViewsStorage:u}),console.warn("[Sprig] (ERR-425) Failed to update page views in local storage")}}function Bl(){const e="Backbone"in window&&window.Backbone&&window.Backbone.history?window.Backbone.history:window.history;"pushState"in e&&(e.pushState=(t=>function(...r){const i=t.apply(this,r),s=new Event("pushState");return window.dispatchEvent(s),At(s),i})(e.pushState)),"replaceState"in e&&(e.replaceState=(t=>function(...r){const i=t.apply(this,r),s=new Event("replaceState");return window.dispatchEvent(s),At(s),i})(e.replaceState)),Dl()}async function Pn(e,t){const n=Cr();e&&!t&&(window.UserLeap._config.mode=xl.test);const r=await de(Cl(n,{...e,previewLanguage:window.UserLeap._config.previewLanguage}),{},0,!0);return r.ok?(r.json.delay&&await tn(r.json.delay),Ps(r.json)):(r.reportError&&r.error&&(console.warn("[Sprig] (ERR-414) Failed to request questions from the server",r.error),window.UserLeap.reportError("getQuestions",r.error)),{success:!1,surveyState:re.NoSurvey})}const Ps=async e=>{var V,M;const{context:t,forceBrandedLogo:n,endCard:r,locale:i,productConfig:s,questions:o,responseGroupUid:a,surveyId:l,uuid:u,vid:c,sessionReplay:p}=e,d=tt(window.UserLeap),h=Br(d),w=jl(d);if(I(`Attempting to display survey: ${l}`),p)if(I("Survey has replay attached"),h){const x={mediaRecordingUid:qe(),mediaType:gr.Screen,questionId:1,responseGroupUid:a,surveyId:l,updatedAt:new Date().toISOString(),visitorId:window.UserLeap.visitorId,isReplay:!0};R.emit(O.ReplayCapture,{responseGroupUid:a,hasQuestions:!!(o!=null&&o.length),surveyId:l,uploadId:p.uploadId,replayType:p.replayDurationType??Ke.Before,seconds:p.replayDurationSeconds,generateVideoUploadUrlPayload:x})}else Es({responseGroupId:a,surveyId:l,visitorId:c,replayParams:p,completeUploadHeaders:d,apiUrl:window.UserLeap._API_URL,triggerTimestamp:Date.now(),isStandalone:o.length===0});if(c==null||!o||!o.length)return I(`Not displaying survey: vid: ${c} / questions: ${o}`),{success:!1,message:"[Sprig] no survey found",surveyState:re.NoSurvey};if(window.UserLeap.container){I("Already displaying a survey");const x="[Sprig] (ERR-409) Found an existing Survey container, aborting rendering of this survey";return console.warn(x),{success:!1,message:x,surveyState:re.NoSurvey}}if(c!==window.UserLeap.visitorId&&u!==window.UserLeap.visitorId&&!window.previewMode){const x="Attempted to display survey to a different visitor";return I(x),window.UserLeap.reportError("DisplaySurvey",new Error(x)),{success:!1,message:x,surveyState:re.NoSurvey}}I(`Showing survey: ${l}`),dl({id:l,userAgent:window.navigator.userAgent}),Ei.disable(),R.emit(O.SurveyWillPresent,{name:O.SurveyWillPresent,[vt.SurveyId]:l});let y,g=document.createElement("div"),m,f,v;const b=x=>{const{[wr.ViewVersion]:ve}=x;ve!==d["x-ul-sdk-version"]&&mi(),R.removeListener(en.VerifyViewVersion,b)};R.on(en.VerifyViewVersion,b),Ii(d)?(y="ul-direct-embeded-frame",m=document.head,f=window,v=!1,h&&(fi(),g.id=y,window.UserLeap.container.appendChild(g),yi(),R.emit(O.SurveyLifeCycle,{state:"presented"}),R.emit(O.SurveyPresented,{name:O.SurveyPresented,[vt.SurveyId]:l}))):{frameId:y,contentWinDocHead:m,contentWindow:f,hasOverlay:v,iframe:g}=$s(s,w,l),window.UserLeap.frameId=y,window.UserLeap.useMobileStyling=w;const _=x=>{R.on(O.CloseSurveyOnOverlayClick,x)},E=Object.assign({frame:g,envId:window.UserLeap.envId,surveyId:l,userId:u,visitorAttributes:{externalUserId:window.UserLeap.userId,email:window.UserLeap.email},cards:o,context:t,locale:i,fontFamily:window.UserLeap.fontFamily,fontFamilyURL:window.UserLeap.fontFamilyURL,apiURL:window.UserLeap._API_URL,responseGroupUid:a,headers:d,endCard:r,useMobileStyling:w,mobileSDKVersion:window.UserLeap.mobileSDKVersion,configureExitOnOverlayClick:_,eventEmitFn:R.emit.bind(R),ulEvents:yr,viewDocument:f==null?void 0:f.document,viewWindow:f,tabTitle:document.title,startingQuestionIdx:(V=window.UserLeap.config)==null?void 0:V.startingQuestionIdx,styleNonce:window.UserLeap.styleNonce,previewKey:Z.getItem(ee.Preview),forceBrandedLogo:n},window.UserLeap._config);(M=window.UserLeap.config)!=null&&M.startingQuestionIdx&&(window.UserLeap.config={...window.UserLeap.config,startingQuestionIdx:null}),window.UserLeap.customStyles&&(E.customStyles=window.UserLeap.customStyles),f&&(f.__cfg=E);function S(){const x=document.createElement("script");return window.UserLeap.nonce&&x.setAttribute("nonce",window.UserLeap.nonce),x.id=ci,x}const P=window.UserLeap.viewSDKURL?window.UserLeap.viewSDKURL:E.path,L=document.getElementById(ci);L&&L.remove();const B=S(),D=()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{display:"flex"})};if(E.installationMethod===Ce.Npm||E.installationMethod===Ce.NpmBundled){const{default:x}=await Promise.resolve().then(()=>require("./view-qyKPee6i.cjs"));x.configure(E),v&&window.UserLeap.container&&D()}else P&&(B.src=P,v&&B.addEventListener("load",()=>{window.UserLeap.container&&D()}),f==null||f.addEventListener("error",x=>{x.target instanceof HTMLScriptElement&&x.target.src===P&&window.UserLeap.reportError("loadFrameScript",new Error("Frame script failed to load"))},{capture:!0,once:!0}));return m==null||m.appendChild(B),{success:!0,surveyState:re.Ready,surveyId:l,responseGroupUid:a}};function jl(e){if(window.UserLeap.useMobileStyling!==void 0)return window.UserLeap.useMobileStyling;const t=window.UserLeap.windowDimensions&&window.UserLeap.windowDimensions.width||document.body.clientWidth;return Br(e)||t>10&&t<Zs}function Br(e){return Pl.includes(e[oe.Platform])}function Nl(e){let t=e.length;for(;t;){const n=Math.floor(Math.random()*t);t-=1;const r=e[t];e[t]=e[n],e[n]=r}}function Fl(e){if(!e)return;window.UserLeap._config=e,e.mute&&window.UserLeap._queue.pause();const{interactiveEvents:t,pageUrlEvents:n,dismissOnPageChange:r}=e;t&&Nl(t),(t||n||r)&&(Bl(),At())}async function de(e,t,n=0,r=!1){var s,o;t.headers=Object.assign(tt(window.UserLeap),t.headers);const i=await Be(e,t,n,r);if(i.ok){const a=(s=i.headers)==null?void 0:s.get("Authorization"),l=a?a.split(" "):void 0,u=l&&l.length===2?l[1]:void 0,c=(o=i.headers)==null?void 0:o.get(oe.VisitorID);u&&c&&(c!==window.UserLeap.visitorId||window.UserLeap.token!==u)&&(X("token",u),X("vid",c),R.emit(O.VisitorIDUpdated,{visitorId:c}),window.UserLeap.token=u,window.UserLeap.visitorId=c)}return i.json&&i.json.logMessage&&console.warn(`[Sprig] ${i.json.logMessage}`),i}async function Kl(e,t){var r,i;let n=!0;return t&&((r=e==null?void 0:e.json)!=null&&r.surveyId)&&(window.UserLeap.delayingSurvey=!0,n=await t(e.json.surveyId),window.UserLeap.delayingSurvey=!1,!n)?!1:((i=e==null?void 0:e.json)!=null&&i.delay&&(window.UserLeap.delayingSurvey=!0,await tn(e.json.delay),window.UserLeap.delayingSurvey=!1),n)}const Ml=function(e){if(!window.UserLeap)return;const t=async(r={})=>{var y,g,m,f;const{userId:i,anonymousId:s,metadata:o={},properties:a,showSurveyCallback:l}=r;let{eventName:u}=r;if(window.UserLeap.debugMode&&u!==fr&&console.info("[DEBUG] Sprig track",r),e.mode==="test")return;const c=Z.getItem(ee.Preview)??void 0;if(e.requireUserIdForTracking&&!window.UserLeap.userId&&!i){const v="[Sprig] - Skipping tracking without userId";return console.warn(v),{success:!1,message:v,surveyState:re.NoSurvey}}if(!u||u.trim().length===0){u=u?String(u):"";const v="[Sprig] - Invalid event name "+u;return console.warn(v),{success:!1,message:v,surveyState:re.NoSurvey}}const p=window.location.href;if(o.url||(o.url=p),X("trackStartUrl",p),(g=(y=window.UserLeap)==null?void 0:y._config)!=null&&g.optimizelyEnabled){const v=tt(window.UserLeap);Br(v)||Vt.getAndSetWebOptimizelyExperiments(),o.optimizelyExperiments=Object.assign({},Vt.getAllOptimizelyExperiments())}(f=(m=window.UserLeap)==null?void 0:m._config)!=null&&f.launchDarklyEnabled&&(o.launchDarklyFlags=On.getAllLaunchDarklyVariations()),i&&(window.UserLeap.userId=i),s&&(window.UserLeap.partnerAnonymousId=s),a&&(o.eventProperties=a),ul({name:u,url:o.url}),I(`Tracking event: ${u}`);const d=window.UserLeap.delayingSurvey?await de(ae("1",[Re],"events/batch"),{body:JSON.stringify({events:[{event:u,metadata:o}],previewKey:c}),method:"POST"},0,!0):await de(ae("1",[Re],"events"),{body:JSON.stringify({event:u,metadata:o,previewKey:c}),method:"POST"},0,!0);if(!d.ok){const v="[Sprig] (ERR-421) Failed to track event";return d.reportError&&(console.warn(v,d.error),d.error&&window.UserLeap.reportError("track",d.error)),{success:!1,message:v,error:d.error,surveyState:re.NoSurvey}}i&&X("uid",i),s&&X("aid",s);const h=d.json;return h.invalidPreviewKey&&Z.removeItem(ee.Preview),await Kl(d,l)?Ol(h.eventId,p)?Ps(h):{success:!1,message:"Study should not be displayed after page navigation",surveyState:re.NoSurvey}:{success:!1,message:"[Sprig] Callback returned false, aborting rendering of survey",surveyState:re.NoSurvey}},n={async displaySurvey(r){return console.warn("[Sprig] displaySurvey should only be used to debug your studies; not intended for production usage."),window.UserLeap("dismissActiveSurvey",Se.Override),Pn({surveyId:r},!0)},_previewSurvey(r){window.UserLeap("dismissActiveSurvey",Se.Override),Pn({surveyTemplateId:r},!1)},_reviewSurvey(r){window.UserLeap("dismissActiveSurvey",Se.Override),Pn({surveyId:r},!1)},previewSurvey(r){n._previewSurvey(r)},reviewSurvey(r){n._reviewSurvey(r)},mute(){window.UserLeap._queue.pause()},unmute(){window.UserLeap._queue.unpause()},setVisitorToken(){console.warn("[Sprig] setVisitorToken is deprecated.")},dismissActiveSurvey(r=Se.API){R.emit(O.SurveyWillClose,{name:O.SurveyWillClose,initiator:r})},async setAttribute(r,i){if(!r||!i&&i!==0&&i!==!1){const s="[Sprig] - Disregarding empty attribute / value provided";return console.warn(s),{success:!1,message:s}}return this.setAttributes({[r]:i})},async setAttributes(r){if(r==null||Object.keys(r).length===0){const i="[Sprig] - Disregarding empty attributes provided";return console.warn(i),{success:!1,message:i}}return this.identifyAndSetAttributes({attributes:r})},async identifyAndSetAttributes(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig identifyAndSetAttributes",r),e.mode==="test")return;if(r===null||typeof r!="object"||!(r.userId||r.anonymousId||r.attributes)){const u="[Sprig] - Disregarding empty payload provided";return console.warn(u),{success:!1,message:u}}const{userId:i,anonymousId:s,attributes:o}=r;if(e.requireUserIdForTracking&&!window.UserLeap.userId&&!i){const u="[Sprig] - Skipping tracking without userId";return console.warn(u),{success:!1,message:u}}if(!o&&(!i||window.UserLeap.userId===i)&&(!s||window.UserLeap.partnerAnonymousId===s))return{success:!0};const a={};i&&(a.userId=window.UserLeap.userId=i),s&&(a.partnerAnonymousId=window.UserLeap.partnerAnonymousId=s);let l;return o?(o.email&&!Object.prototype.hasOwnProperty.call(o,ct)&&(o[ct]=o.email,delete o.email),I(`Setting attributes: ${JSON.stringify(o)}`),l=await de(ae("1",[Le,Re],"attributes"),{body:JSON.stringify(o),method:"PUT"}),!l.ok&&l.reportError&&(console.warn("[Sprig] (ERR-432) identifyAndSetAttributes failed",l.error),l.error&&window.UserLeap.reportError("identifyAndSetAttributes",l.error))):l=await de(ae("1",[Le,Re]),{body:JSON.stringify(a),method:"PUT"}),o&&o[ct]&&(window.UserLeap.email=o[ct]),l.ok&&(i&&X("uid",i),s&&X("aid",s)),{success:!!l.ok}},async removeAttributes(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig removeAttributes",r),e.mode==="test")return;if(r==null||r.length===0){const s="[Sprig] - Disregarding empty attributes provided";return console.warn(s),{success:!1,message:s}}if(e.requireUserIdForTracking&&!window.UserLeap.userId){const s="[Sprig] - Skipping tracking without userId";return console.warn(s),{success:!1,message:s}}const i=await de(ae("1",[Le,Re],"attributes"),{body:JSON.stringify({delete:r}),method:"DELETE"});return!i.ok&&i.reportError&&(console.warn("[Sprig] (ERR-433) Remove attributes failed",i.error),i.error&&window.UserLeap.reportError("removeAttributes",i.error)),{success:!!i.ok}},async addSurveyListener(r){R.on(O.SurveyLifeCycle,r)},async removeSurveyListener(r){R.removeListener(O.SurveyLifeCycle,r)},async addListener(r,i){R.on(r,i)},async removeListener(r,i){R.removeListener(r,i)},async removeAllListeners(){R.removeAllListeners()},setPreviewKey(r){!r||typeof r!="string"||Z.isStorageAvailable&&r&&Z.setItem(ee.Preview,r)},async setUserId(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig setUserId",r),r==null){const o=`[Sprig] - Invalid userId ${r}`;return console.warn(o),{success:!1,message:o}}if(e.mode==="test"||r===window.UserLeap.userId)return;window.UserLeap.userId=r;const i=window.UserLeap.visitorId,s=await de(ae("1",[Le,Re]),{body:JSON.stringify({userId:r}),method:"PUT"});if(!s.ok){s.reportError&&(console.warn("[Sprig] (ERR-420) Failed to set user id",s.error),s.error&&window.UserLeap.reportError("setUserId",s.error));return}i!==window.UserLeap.visitorId&&si(),X("uid",r)},async setPartnerAnonymousId(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig setPartnerAnonymousId",r),r==null){const i=`[Sprig] - Invalid partnerAnonymousId ${r}`;return console.warn(i),{success:!1,message:i}}return window.UserLeap.partnerAnonymousId=r,X("aid",r),{success:!0}},async track(r,i,s={},o=void 0){return t({eventName:r,properties:i,metadata:s,showSurveyCallback:o})},async identifyAndTrack(r){return await t(r)},trackPageView(r,i=void 0,s=void 0){xs(r,i,s)},applyStyles(r){if(window.UserLeap.customStyles=r,window.UserLeap.container){const i=window.UserLeap.container.children[0].contentDocument;if(i){const s=i.getElementById(ke.CustomStyle);s?s.textContent=r:Li(i,r,window.UserLeap.styleNonce)}}},setWindowDimensions(r,i){var l,u;const s=typeof r=="string"?parseInt(r,10):r,o=typeof i=="string"?parseInt(i,10):i;if(!isNaN(s)&&!isNaN(o)&&(window.UserLeap.windowDimensions={width:s,height:o}),!window.UserLeap.frameId)return;const a=document.getElementById(window.UserLeap.frameId);a&&(window.UserLeap.useMobileStyling&&((l=window.UserLeap.windowDimensions)!=null&&l.width&&(a.style.width=`${window.UserLeap.windowDimensions.width}px`),(u=window.UserLeap.windowDimensions)!=null&&u.height&&(a.style.maxHeight=`${window.UserLeap.windowDimensions.height-20}px`),a.contentDocument&&(a.style.height=String(ki(a.contentDocument)[0])+"px")),R.emit(O.SurveyDimensions,{name:O.SurveyDimensions,contentFrameWidth:a.clientWidth,contentFrameHeight:a.clientHeight}))},logoutUser(){window.UserLeap.debugMode&&console.info("[DEBUG] Sprig logout"),I(`Logging out user: ${window.UserLeap.userId} / vid: ${window.UserLeap.visitorId}`),window.UserLeap.visitorId=null,window.UserLeap.userId=null,window.UserLeap.partnerAnonymousId=null,window.UserLeap.token=null,window.UserLeap.email=null,Z.removeItem(ee.Credentials),Z.removeItem(ee.PageViews),window.UserLeap._queue.isPaused()&&window.UserLeap._queue.empty(),As(),si(),window.UserLeap._queue.unpause()},teardown(){Tl(),window.UserLeap("dismissActiveSurvey",Se.API),delete window.UserLeap,delete window.Sprig,delete window._Sprig},integrateOptimizely(r,i=!0){var s,o;if(!((o=(s=window.UserLeap)==null?void 0:s._config)!=null&&o.optimizelyEnabled)){console.warn("[SPRIG] Optimizely integration is currently not enabled for your product.");return}try{const a=typeof r=="string"?JSON.parse(r):r;Vt.setOptimizelyExperiment(a,i)}catch(a){console.warn("[Sprig] Error with integrating Optimizely data"),a instanceof Error&&window.UserLeap.reportError("integrateOptimizely",a)}},integrateOptimizelyClient(r){var s,o;if(!((o=(s=window.UserLeap)==null?void 0:s._config)!=null&&o.optimizelyEnabled)){console.warn("[SPRIG] Optimizely integration is currently not enabled for your product.");return}const i=({experiment:a,variation:l})=>{const u={experiments:[{id:a.id,variation:l.key}]};window.UserLeap("integrateOptimizely",u,!1)};r.notificationCenter.addNotificationListener("ACTIVATE:experiment, user_id,attributes, variation, event",i)},importLaunchDarklyData(r){var i,s;if(!((s=(i=window.UserLeap)==null?void 0:i._config)!=null&&s.launchDarklyEnabled)){console.warn("[SPRIG] LaunchDarkly integration is currently not enabled for your product.");return}On.setLDFlagsVariations(r)},setVisitorAttribute(r,i){return console.warn("[Sprig] setVisitorAttribute is deprecated. Please use setAttribute"),n.setAttribute(r,i)},async setEmail(r){return n.setAttribute(ct,r)},async setVisitorEmail(r){return console.warn("[Sprig] setVisitorEmail is deprecated. Please use setEmail"),n.setEmail(r)},async _generateVideoUploadUrl(r){return Wl(r)},async _completeSessionReplay({surveyId:r,responseGroupUuid:i,eventDigest:s}){if(!r||!i)return!1;const o=window.UserLeap._API_URL;try{const a=await Ni({surveyId:r,responseGroupUuid:i,eventDigest:s,apiUrl:o,headers:tt(window.UserLeap)},!0);return!(a!=null&&a.error)}catch(a){return console.warn("[Sprig] Error with completing session replay"),a instanceof Error&&window.UserLeap.reportError("completeSessionReplay",a),!1}}};Object.assign(window.UserLeap,n)};async function $l(e){const t=tt(window.UserLeap);document.addEventListener("securitypolicyviolation",Bn);const n=await Be(ae("1",[Le],"config"),{headers:t}),r="TypeError";if(window.UserLeap.error=n.error,!n.ok&&n.error&&n.error.name===r?(window.UserLeap._API_URL="https://api.sprig.com",window.UserLeap.reportError("sprigDomainRequest",n.error)):document.removeEventListener("securitypolicyviolation",Bn),!n.ok)return n.reportError&&(console.warn("[Sprig] (ERR-422) Failed to load configuration",n.error),n.error&&window.UserLeap.reportError("applyRemoteConfig",n.error)),jn("Disabled: failed to fetch configuration"),e;const i=n.json;return i!=null&&i.disabled?(jn(`Disabled: ${i.disabled}`),{disabled:i.disabled}):Object.assign({},i,e)}const Vl=e=>typeof e=="object"&&e&&"inner"in e&&!!e.inner&&typeof e.inner=="object";async function ql(e,t,n={}){var p,d;const r=window.__cfg&&window.__cfg.mode,i=Cr(),s=window.UserLeap.envId,o=window.document.documentElement,a=Vl(t)?{inner:{message:(p=t.inner)==null?void 0:p.message,stack:(d=t.inner)==null?void 0:d.stack}}:{},l={mode:r,screenWidth:window.screen.width,screenHeight:window.screen.height,clientWidth:o.clientWidth,clientHeight:o.clientHeight,location:window.location.href,language:window.navigator.language,...n,...a},u={action:e,err:{message:t.message,stack:t.stack},meta:l,vid:i,envId:s},c=await de(ae("1",null,"errors"),{method:"POST",headers:{[oe.Error]:window.btoa(`userleap-${Date.now()}-error`)},body:JSON.stringify(u)},0,!0);if(!c.ok)console.warn("[Sprig] (ERR-444) Failed to report error to API",t);else{const{presignedUrl:h}=c.json;Ri(h)}}async function Wl(e){var n;if(!e)return;const t=`${window.UserLeap._API_URL}/2/environments/integrations/upload`;try{const r=await fetch(t,{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(r.ok){const i=await r.json();return(n=i==null?void 0:i.upload)==null?void 0:n.url}else return null}catch(r){console.warn("[Sprig] Error with generating video upload url"),r instanceof Error&&window.UserLeap.reportError("generateVideoUploadUrl",r)}}function zl(e={}){const t=new URLSearchParams(window.location.search).get(gi.Preview)??"";window.UserLeap.UPDATES=yr,window.UserLeap("setPreviewKey",t);async function n(){if(window.UserLeap.loaded)return;if(I("Loading sprig on page load"),window.UserLeap.reportError=ql,window.UserLeap.loaded=!0,window.UserLeap._config=Object.assign({},e,window.UserLeap.config),window.UserLeap.delayingSurvey=!1,window.UserLeap._config&&typeof window.UserLeap._config=="object")for(const a in window.UserLeap._config)window.UserLeap[a]=window.UserLeap._config[a];if(!window.UserLeap.envId)if(window.UserLeap.appId)window.UserLeap.envId=window.UserLeap.appId;else throw new Error("Missing Environment id");window.UserLeap.debugMode&&console.info("[DEBUG] Sprig debug mode enabled");const r=window.UserLeap.sampleRate;if(r){let a=De("sampled");if(a===null&&(a=Math.random()<r,X("sampled",a)),!a)return}else De("sampled")!==null&&X("sampled",null);window.UserLeap._API_URL||(window.UserLeap._API_URL="https://api.sprig.com");const i=[...window.UserLeap._queue];window.UserLeap._queue=new Ys(window.UserLeap,[]),window.UserLeap._queue.pause();for(let a=0;a<i.length;a++)window.UserLeap._queue.push(i[a]);const s=De("token");s?(window.UserLeap.token=s,window.UserLeap.visitorId=De("vid"),window.UserLeap.userId=De("uid"),window.UserLeap.partnerAnonymousId=De("aid")):(Z.removeItem(ee.Credentials),As());const o=await $l(e);wl({reportingIntervalSeconds:o.metricsReportingEnabled?o.metricsReportingIntervalSeconds:0,thresholds:o.metricThresholds,postMetrics:async a=>{await de(ae("1",[Le],"metrics"),{body:a,method:"POST",headers:{"x-ul-replay-enabled":`${Ls()}`}},0,!0)}}),Qa(window.document,o.maxReplayDurationSeconds,window.UserLeap.replayNonce,window.UserLeap.maxInflightReplayRequests,o.replaySettings).then(()=>{Ul()}),bo(o.logBufferLimit,o.logLevel),Ml(o),await Fl(o),window.UserLeap._queue.unpause(),R.emit(O.SDKReady,{maxMobileReplayDurationSeconds:o.maxMobileReplayDurationSeconds,mobileReplaySettings:o.mobileReplaySettings}),R.emit(O.VisitorIDUpdated,{visitorId:window.UserLeap.visitorId})}document.readyState==="complete"?n():window.attachEvent?window.attachEvent("onload",n):window.addEventListener("load",()=>{n()},!1)}class hn{constructor(){F(this,"UPDATES",yr)}displaySurvey(t){window.Sprig("displaySurvey",t)}mute(){window.Sprig("mute")}unmute(){window.Sprig("unmute")}dismissActiveSurvey(){window.Sprig("dismissActiveSurvey")}setAttribute(t,n){window.Sprig("setAttribute",t,n)}setAttributes(t){window.Sprig("setAttributes",t)}identifyAndSetAttributes(t){window.Sprig("identifyAndSetAttributes",t)}removeAttributes(t){window.Sprig("removeAttributes",t)}addListener(t,n){window.Sprig("addListener",t,n)}removeListener(t,n){window.Sprig("removeListener",t,n)}removeAllListeners(){window.Sprig("removeAllListeners")}setEmail(t){window.Sprig("setAttribute","!email",t)}setUserId(t){window.Sprig("setUserId",t)}setPartnerAnonymousId(t){window.Sprig("setPartnerAnonymousId",t)}track(t,n={},r={}){window.Sprig("track",t,n,r)}identifyAndTrack(t){window.Sprig("identifyAndTrack",t)}trackPageView(t,n,r){window.Sprig("trackPageView",t,n,r)}applyStyles(t){window.Sprig("applyStyles",t)}setWindowDimensions(t,n){window.Sprig("setWindowDimensions",t,n)}logoutUser(){window.Sprig("logoutUser")}teardown(){window.Sprig("teardown")}}const mr={configure:e=>{if(!e.envId&&!e.environmentId)throw new Error("Initialization Error: Sprig configure requires an environmentId");if(e.envId||(e.envId=e.environmentId||""),e.installationMethod="web-npm",window.Sprig)return window.Sprig;window.Sprig=function(){window.Sprig._queue.push(arguments)},Object.getOwnPropertyNames(hn.prototype).map(n=>{n!=="constructor"&&(window.Sprig[n]=hn.prototype[n])});const t=window.Sprig;return t.appId=e.envId,t._queue=[],window.UserLeap=t,zl(e),window.Sprig}},Gl={sprig:mr,SprigAPI:hn,configure:mr.configure};exports.APP_ID=Js;exports.ConflictingWidgets=Ei;exports.CssConstant=ke;exports.DEFAULT_BORDER_COLOR=Qs;exports.DEFAULT_WIDTH=hi;exports.DismissReason=Se;exports.EMBED_MOBILE_MAX_WIDTH=eo;exports.ERROR_BORDER_COLOR=Xs;exports.InstallationMethod=Ce;exports.InternalEventData=wr;exports.InternalEventName=en;exports.MediaType=gr;exports.Platform=xt;exports.RecordSurveyComplete=pl;exports.SprigAPI=hn;exports.SprigEvent=O;exports.SprigEventData=vt;exports.SprigRecordingEvent=vi;exports.SprigRecordingEventData=_i;exports.TaskStatus=bi;exports.calculateFrameDimensions=ki;exports.eventEmitter=R;exports.getAugmentedNamespace=co;exports.getClasses=oo;exports.getDefaultExportFromCjs=Ai;exports.getPlatformClass=ao;exports.index=Gl;exports.info=I;exports.overrideStyles=Li;exports.resetScrollPosition=so;exports.shouldDirectEmbed=Ii;exports.sprig=mr;exports.ulFetch=Be;exports.uploadLogfile=Ri;exports.v4=qe;
|