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