!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3ee33bc3-6790-5799-9ea2-95e23e36e707")}catch(e){}}(); var fo=Object.defineProperty;var go=(V,G,ce)=>G in V?fo(V,G,{enumerable:!0,configurable:!0,writable:!0,value:ce}):V[G]=ce;var k=(V,G,ce)=>go(V,typeof G!="symbol"?G+"":G,ce);(function(){"use strict";let V;const G=new Uint8Array(16);function ce(){if(!V&&(V=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!V))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return V(G)}const _=[];for(let e=0;e<256;++e)_.push((e+256).toString(16).slice(1));function Ir(e,t=0){return _[e[t+0]]+_[e[t+1]]+_[e[t+2]]+_[e[t+3]]+"-"+_[e[t+4]]+_[e[t+5]]+"-"+_[e[t+6]]+_[e[t+7]]+"-"+_[e[t+8]]+_[e[t+9]]+"-"+_[e[t+10]]+_[e[t+11]]+_[e[t+12]]+_[e[t+13]]+_[e[t+14]]+_[e[t+15]]}const Ht={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function le(e,t,n){if(Ht.randomUUID&&!e)return Ht.randomUUID();e=e||{};const i=e.random||(e.rng||ce)();return i[6]=i[6]&15|64,i[8]=i[8]&63|128,Ir(i)}const Er='.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}',kr="360px",_r=500;var W=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.FeedbackClosed="feedback.closed",e.PageChange="page.change",e.API="api",e.Override="override",e))(W||{}),f=(e=>(e.ReplayCapture="replay.capture",e.FeedbackButtonLoaded="feedback.button.loaded",e.SDKReady="sdk.ready",e.SurveyAppeared="survey.appeared",e.SurveyCloseRequested="survey.closeRequested",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))(f||{});const Re={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"}},Rr=300;class Dr{constructor(){k(this,"breadcrumbs",[])}getTimeStamp(){return new Date().toISOString()}addBreadcrumb(t){this.breadcrumbs.push(t),this.breadcrumbs.length>Rr&&this.breadcrumbs.shift()}debug(t,n="debug"){this.addBreadcrumb({category:n,level:"info",message:t,timestamp:this.getTimeStamp(),type:"debug"})}error(t,n={}){this.addBreadcrumb({category:"error",data:n,level:"error",message:t,timestamp:this.getTimeStamp(),type:"error"})}http(t,n){this.addBreadcrumb({category:"xhr",data:n,message:t,timestamp:this.getTimeStamp(),type:"http"})}info(t,n={}){this.addBreadcrumb({category:"info",data:n,level:"info",message:t,timestamp:this.getTimeStamp(),type:"info"})}navigation(t,n){this.addBreadcrumb({category:"navigation",data:n,message:t,timestamp:this.getTimeStamp(),type:"navigation"})}}const p=new Dr,Vt=()=>{try{return window.parent.Intercom}catch{return null}},Wt=[Object.freeze(Object.defineProperty({__proto__:null,disable:()=>{const e=Vt();e&&(e.ul_wasVisible=!!document.querySelector("iframe.intercom-launcher-frame"),e.ul_wasVisible&&e("update",{hide_default_launcher:!0}))},enable:()=>{const e=Vt();e&&(e.ul_wasVisible&&e("update",{hide_default_launcher:!1}),delete e.ul_wasVisible)}},Symbol.toStringTag,{value:"Module"}))];class Cr{static disable(){Wt.forEach(t=>t.disable())}static enable(){Wt.forEach(t=>t.enable())}}var xr=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"}},jt=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=jt.defaultMaxListeners,this.hasWarnedAboutPotentialMemoryLeak=!1}_emitInternalEvent(e,t,n){this.emit(e,t,n)}_getListeners(e){return Array.prototype.concat.apply([],this.events.get(e))||[]}_removeListener(e,t){const n=e.indexOf(t);return n>-1&&e.splice(n,1),[]}_wrapOnceListener(e,t){const n=(...i)=>(this.removeListener(e,n),t.apply(this,i));return Object.defineProperty(n,"name",{value:t.name}),n}setMaxListeners(e){return this.maxListeners=e,this}getMaxListeners(){return this.maxListeners}eventNames(){return Array.from(this.events.keys())}emit(e,...t){const n=this._getListeners(e);return n.forEach(i=>{i.apply(this,t)}),n.length>0}addListener(e,t){this._emitInternalEvent("newListener",e,t);const n=this._getListeners(e).concat(t);if(this.events.set(e,n),this.maxListeners>0&&this.listenerCount(e)>this.maxListeners&&!this.hasWarnedAboutPotentialMemoryLeak){this.hasWarnedAboutPotentialMemoryLeak=!0;const i=new xr(this,e,this.listenerCount(e));console.warn(i)}return this}on(e,t){return this.addListener(e,t)}once(e,t){return this.addListener(e,this._wrapOnceListener(e,t))}prependListener(e,t){const n=this._getListeners(e);if(n.length>0){const i=[t].concat(n);this.events.set(e,i)}else this.events.set(e,n.concat(t));return this}prependOnceListener(e,t){return this.prependListener(e,this._wrapOnceListener(e,t))}removeListener(e,t){const n=this._getListeners(e);return n.length>0&&(this._removeListener(n,t),this.events.set(e,n),this._emitInternalEvent("removeListener",e,t)),this}off(e,t){return this.removeListener(e,t)}removeAllListeners(e){return e?this.events.delete(e):this.events.clear(),this}listeners(e){return Array.from(this._getListeners(e))}listenerCount(e){return this._getListeners(e).length}rawListeners(e){return this.listeners(e)}},qt=jt;qt.defaultMaxListeners=10;const m=new qt,De=async e=>{await new Promise(t=>{setTimeout(t,e)})},$t=({"userleap-platform":e})=>{var t;return((t=window.UserLeap)==null?void 0:t.forceDirectEmbed)||e!=="web"};class zt{constructor(t){k(this,"storage");k(this,"tempStorage",{});k(this,"isStorageAvailable");try{this.storage=window[t];const n="__storage_test__";this.storage.setItem(n,n),this.storage.removeItem(n),this.isStorageAvailable=!0}catch{this.isStorageAvailable=!1}}setItem(t,n){this.isStorageAvailable&&this.storage?this.storage.setItem(t,n):this.tempStorage[t]=n}setItemObject(t,n){try{this.setItem(t,JSON.stringify(n))}catch(i){i instanceof Error&&(i.stack=t+": "+n,window.UserLeap.reportError("Failed to save to local storage",i))}}getItem(t){return this.isStorageAvailable&&this.storage?this.storage.getItem(t):this.tempStorage[t]}getItemObject(t){const n=this.getItem(t);if(n)try{return JSON.parse(n)}catch(i){i instanceof Error&&(i.stack=t+": "+n,window.UserLeap.reportError("Failed to parse local storage",i))}return{}}removeItem(t){this.isStorageAvailable&&this.storage?this.storage.removeItem(t):delete this.tempStorage[t]}clear(){this.isStorageAvailable&&this.storage?this.storage.clear():this.tempStorage={}}}const I=new zt("sessionStorage"),A=new zt("localStorage");class Ar{constructor(t){k(this,"payload");k(this,"promise");k(this,"reject",()=>{});k(this,"resolve",()=>{});this.payload=t,this.promise=new Promise((n,i)=>{this.reject=i,this.resolve=n})}resolveRequest(t){this.resolve(t)}}const L={replay:null},Tr=e=>{L.replay=e},Or=()=>{const e=[];return L.replay&&e.push("replay"),e.join(",")},Pr={RATELIMIT_RESET_DEFAULT:10};let Kt=!1,Gt="",Ce=!1,Yt=!1,xe=[];const Mr=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?"web-gtm":e._segment?"web-segment":"web-snippet",Jt=e=>{var t;(t=e==null?void 0:e.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(Yt=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`))},Ze=(e="")=>{Kt=!0,Gt=e};function N(e={}){const t={"Content-Type":"application/json","userleap-platform":"web","x-ul-sdk-version":"2.33.3","x-ul-installation-method":Mr(e),"sprig-modules":Or()};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 Qt=async({shouldDropOnRateLimit:e,...t})=>{if(e)return{status:429};{const n=new Ar(t);return xe.push(n),n.promise}},Y=async(e,t)=>{const{retries:n=0,shouldDropOnRateLimit:i=!1,shouldRetryRequest:r=!1,...s}=t,o={url:e,options:s,retries:n,shouldDropOnRateLimit:i};if(Ce&&!r)return Qt(o);const a={ok:!1,reportError:!1};if(Kt)return console.info(`UserLeap - ${Gt}`),a;try{const d=await fetch(e,s);if(d.status===429)if(!Ce&&!i||r){Ce=!0;const u=d.headers.has("ratelimit-reset")?Number(d.headers.get("ratelimit-reset")):Pr.RATELIMIT_RESET_DEFAULT;return await De(u*1e3),Y(e,{...s,shouldDropOnRateLimit:i,shouldRetryRequest:!0})}else return Qt(o);if(Ce=!1,xe.length&&(xe.map(l=>{const u=l.payload;Y(u.url,{...u.options,retries:u.retries,shouldDropOnRateLimit:u.shouldDropOnRateLimit}).then(c=>{l.resolveRequest(c)})}),xe=[]),d.ok){if(d.status===249)return Ze(),a;const l=await d.text();try{return l&&l!=="OK"&&(d.json=JSON.parse(l)),d}catch{return{ok:!1,reportError:!1,error:new Error(`failed parsing response json for ${e} - ${l}`)}}}return d}catch(d){const l=n+1;return l>5||Yt?{ok:!1,reportError:!1,error:d}:(await De(Math.pow(2,n)*1e3),Y(e,{...s,retries:l}))}},Xt="ul-view-sdk-script",Br=["ios","android"],ee="visitors",te="environments";async function j(e,t){var s,o,a;const{shouldDropOnRateLimit:n,...i}=t;i.headers=Object.assign(N(window.UserLeap),i.headers);const r=await Y(e,{...i,shouldDropOnRateLimit:n});if(r.ok){const d=(s=r.headers)==null?void 0:s.get("Authorization"),l=d?d.split(" "):void 0,u=l&&l.length===2?l[1]:void 0,c=(o=r.headers)==null?void 0:o.get("x-ul-visitor-id");if(window.UserLeap.userId&&c===window.UserLeap.visitorId){const y=A.getItemObject("sprig.anon.env.vid.map");y&&y[window.UserLeap.envId]===c&&(delete y[window.UserLeap.envId],A.setItemObject("sprig.anon.env.vid.map",y))}u&&c&&(c!==window.UserLeap.visitorId||window.UserLeap.token!==u)&&(T("token",u),T("vid",c),m.emit(f.VisitorIDUpdated,{visitorId:c}),window.UserLeap.token=u,window.UserLeap.visitorId=c)}return(a=r.json)!=null&&a.logMessage&&console.warn(`[Sprig] ${r.json.logMessage}`),r}function T(e,t){const n=A.getItemObject("userleap.ids");let i=n[window.UserLeap.envId];i?i[e]=t:i={[e]:t},n[window.UserLeap.envId]=i,A.setItemObject("userleap.ids",n)}function et(){return window.previewMode?"0":window.UserLeap.visitorId??""}function F(e,t,n){const i=[window.UserLeap._API_URL,"sdk",e];return t&&t.forEach(r=>{i.push(r),r===te?i.push(window.UserLeap.envId):r===ee&&i.push(et())}),n&&i.push(n),i.join("/")}const Nr=()=>{const e=N(window.UserLeap),t=he(e),n=window.UserLeap.forceDirectEmbed,i=e["userleap-platform"]==="web";return t||n&&i},ye=async(e,t,n)=>{var br,Lr,Sr;const{context:i,delay:r,forceBrandedLogo:s,endCard:o,isFeedback:a=!1,heatmap:d,locale:l,previewMode:u,productConfig:c,questions:y,responseGroupUid:w,surveyId:g,uuid:E,vid:x,sessionReplay:M,studyType:b}=e,R=N(window.UserLeap),_e=he(R),Z=Ae(R);if(M)if(_e)m.emit(f.ReplayCapture,{responseGroupUid:w,hasQuestions:!!(y!=null&&y.length),surveyId:g,uploadId:M.uploadId,replayType:M.replayDurationType??"before",seconds:M.replayDurationSeconds,generateVideoUploadUrlPayload:{mediaRecordingUid:le(),mediaType:"screen",questionId:1,responseGroupUid:w,surveyId:g,updatedAt:new Date().toISOString(),visitorId:window.UserLeap.visitorId,isReplay:!0}});else{if(!L.replay)return window.UserLeap.reportError("displayQuestions",new Error("Replay module not registered")),{success:!1,message:"Replay module not registered",surveyState:"no survey"};L.replay.scheduleOrCaptureReplay({responseGroupId:w,surveyId:g,visitorId:x,replayParams:M,completeUploadHeaders:R,apiUrl:window.UserLeap._API_URL,triggerTimestamp:Date.now(),isStandalone:y.length===0})}if(d){if(!L.replay)return window.UserLeap.reportError("displayQuestions",new Error("Replay module not registered")),{success:!1,message:"Replay module not registered",surveyState:"no survey"};const{eventId:U,replayParams:Ft,responseGroupUid:po,surveyId:wo}=d;await L.replay.initializeReplay({maxReplayDurationSeconds:300,maxInflightRequests:window.UserLeap.maxInflightReplayRequests,teardownAfter:!0,apiUrl:window.UserLeap._API_URL,replaySettings:n}),L.replay.tryReplayAction(()=>{var Ur;return(Ur=L.replay)==null?void 0:Ur.scheduleCapture({apiUrl:window.UserLeap._API_URL,completeUploadHeaders:R,eventId:U,isHeatmap:!0,replayParams:Ft,responseGroupId:po,surveyId:wo,triggerTimestamp:Date.now(),visitorId:x})},"Error in scheduling/capturing replay")}if(x==null||!(y!=null&&y.length))return p.info("CannotDisplaySurvey",{vid:x}),{success:!1,message:"[Sprig] no survey found",surveyState:"no survey"};if(window.UserLeap.container){p.info("AlreadyDisplayingSurvey");const U="[Sprig] (ERR-409) Found an existing Survey container, aborting rendering of this survey";return console.warn(U),{success:!1,message:U,surveyState:"no survey"}}if(x!==window.UserLeap.visitorId&&E!==window.UserLeap.visitorId&&!window.previewMode){const U="Attempted to display survey to a different visitor";return window.UserLeap.reportError("DisplaySurvey",new Error(U)),{success:!1,message:U,surveyState:"no survey"}}p.info("ShowingSurvey",{surveyId:g}),(br=L.replay)==null||br.RecordSurveyShown({id:g,userAgent:window.navigator.userAgent}),Cr.disable(),m.emit(f.SurveyWillPresent,{name:f.SurveyWillPresent,"survey.id":g});let B,D=document.createElement("div"),ge,H,Xe;const mr=U=>{const{"view.version":Ft}=U;Ft!==R["x-ul-sdk-version"]&&en(),m.removeListener("verify.view.version",mr)};m.on("verify.view.version",mr),window.UserLeap.useMobileStyling=Z,$t(R)?(B="ul-direct-embeded-frame",ge=document.head,H=window,Xe=!1,Nr()&&(Zt(g,a),D.id=B,window.UserLeap.container.appendChild(D),tn(),m.emit(f.SurveyLifeCycle,{state:"presented"}),m.emit(f.SurveyPresented,{name:f.SurveyPresented,"survey.id":g}))):{frameId:B,contentWinDocHead:ge,contentWindow:H,hasOverlay:Xe,iframe:D}=jr({productConfig:c,useMobileStyling:Z,surveyId:g,isFeedback:a}),window.UserLeap.frameId=B;const co=U=>{m.once(f.CloseSurveyOnOverlayClick,U)},me={apiURL:window.UserLeap._API_URL,cards:y,configureExitOnOverlayClick:co,context:i,endCard:o,envId:window.UserLeap.envId,eventEmitFn:m.emit.bind(m),fontFamily:window.UserLeap.fontFamily,fontFamilyURL:window.UserLeap.fontFamilyURL,forceBrandedLogo:s,frame:D,headers:R,locale:l,mobileSDKVersion:window.UserLeap.mobileSDKVersion,previewKey:A.getItem("sprig.previewKey"),previewMode:u,productConfig:{framePosition:c==null?void 0:c.framePosition,desktopDisplay:c==null?void 0:c.desktopDisplay,placement:c==null?void 0:c.placement},responseGroupUid:w,startingQuestionIdx:(Lr=window.UserLeap.config)==null?void 0:Lr.startingQuestionIdx,studyType:b,styleNonce:window.UserLeap.styleNonce,surveyId:g,tabTitle:document.title,trackPageViewUrl:t,ulEvents:Re,upchunkLibraryURL:window.UserLeap.upchunkLibraryURL,useMobileStyling:Z,userId:E,viewDocument:H==null?void 0:H.document,viewWindow:H,visitorAttributes:{externalUserId:window.UserLeap.userId,email:window.UserLeap.email},...window.UserLeap._config};(Sr=window.UserLeap._config)!=null&&Sr.startingQuestionIdx&&(window.UserLeap._config={...window.UserLeap._config,startingQuestionIdx:null});const lo=(a?window.UserLeap.feedbackCustomStyles:window.UserLeap.customStyles)??c.customStyles;me.customStyles=lo,H&&(H.__cfg=me);function uo(){const U=document.createElement("script");return window.UserLeap.nonce&&U.setAttribute("nonce",window.UserLeap.nonce),U.id=Xt,U}const Bt=window.UserLeap.viewSDKURL?window.UserLeap.viewSDKURL:me.path,yr=document.getElementById(Xt);yr&&yr.remove();const Nt=uo(),hr=()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{display:"flex"})};if(me.installationMethod==="web-npm"||me.installationMethod==="web-npm-bundled"){const{default:U}=await import("../view/view.tsx");U.configure(me),Xe&&window.UserLeap.container&&hr()}else Bt&&(Nt.src=Bt,Xe&&Nt.addEventListener("load",()=>{window.UserLeap.container&&hr()}),H==null||H.addEventListener("error",U=>{U.target instanceof HTMLScriptElement&&U.target.src===Bt&&window.UserLeap.reportError("loadFrameScript",new Error("Frame script failed to load"))},{capture:!0,once:!0}));ge==null||ge.appendChild(Nt);const vr={success:!0,surveyState:"ready",surveyId:g,responseGroupUid:w};return window.UserLeap.isMobileSDK&&r&&(vr.delay=r),vr};function Ae(e){var n;if(window.UserLeap.useMobileStyling!==void 0)return window.UserLeap.useMobileStyling;const t=((n=window.UserLeap.windowDimensions)==null?void 0:n.width)??document.body.clientWidth;return he(e)||t>10&&t<_r}function he(e){return Br.includes(e["userleap-platform"])}const tt="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 Fr="rgba(255,255,255, 0.95)",Hr="rgba(0,0,0,0.9)",nt="0px",Zt=(e,t,n)=>{window.UserLeap.container=document.createElement("div"),window.UserLeap.container.className=`ul-container${t?" ul-container-feedback":""}`,e&&(window.UserLeap.container.dataset.studyId=e.toString());const i=cn();n&&i&&!window.UserLeap.useMobileStyling?i.appendChild(window.UserLeap.container):document.body.appendChild(window.UserLeap.container)},en=(e,t)=>{var i;$r();const n=window.UserLeap.container;if(n)try{(i=n.parentNode)==null||i.removeChild(n),window.UserLeap.container=null,T("trackStartUrl",null),m.emit(f.SurveyLifeCycle,{state:"dismissed"}),m.emit(f.SurveyClosed,{name:f.SurveyClosed,initiator:e,"survey.id":parseInt(n.dataset.studyId),...t&&{studyType:t}})}catch(r){console.warn(`[Sprig] (ERR-412) Error removing UserLeap container by ${e} `+n),r instanceof Error&&window.UserLeap.reportError("dismissActiveSurvey",r)}},tn=()=>{m.once(f.SurveyWillClose,({initiator:e,studyType:t})=>{m.removeAllListeners(f.CloseSurveyOnOverlayClick),en(e,t)})},Vr=(e,t)=>{const i={...{position:"fixed",overflow:"auto",top:"0px",left:"0px",display:"none",height:"100%",width:"100%",transition:"background-color 0.3s ease-out",zIndex:2147483646}},r=t?e.overlayStyleMobile:e.overlayStyle;i["background-color"]=r==="light"?Fr:Hr,t||(i.margin="auto"),window.UserLeap.container&&Object.assign(window.UserLeap.container.style,i)},Wr=(e,t,n,i)=>{var u,c;const r={position:"fixed",bottom:"0px",right:nt,border:0,backgroundColor:"rgba(0,0,0,0)",zIndex:2147483646,transition:"height 0.2s ease-in-out",maxWidth:"100%"},s=Object.assign({},t,window.UserLeap),{desktopDisplay:o}=t||{},a=o==="center-modal";a&&(s.framePosition="center");let d,l=!1;if(n)(u=window.UserLeap.windowDimensions)!=null&&u.width?r.width=`${window.UserLeap.windowDimensions.width}px`:r.width="100%",(c=window.UserLeap.windowDimensions)!=null&&c.height?r.maxHeight=`${window.UserLeap.windowDimensions.height-20}px`:window.UserLeap.maxHeight?r.maxHeight=window.UserLeap.maxHeight:r.maxHeight=`${document.body.clientHeight-20}px`,["light","dark"].includes(s.overlayStyleMobile)&&(l=!0);else{r.width=kr,r.maxHeight=window.UserLeap.maxHeight||"66vh";const y=()=>{l=!0,d={margin:"auto",position:"static"}};if(i)a?y():d={position:"relative",height:"300px"};else switch(s.framePosition){case"bottomLeft":d={left:nt};break;case"topLeft":d={left:nt,top:0};break;case"topRight":d={top:0};break;case"center":y();break}}return l&&Vr(s,n),Object.assign(e.style,r,d),l},jr=({productConfig:e,useMobileStyling:t,surveyId:n,isFeedback:i})=>{var y,w;const r=tt,s=i&&e.desktopDisplay==="slider";Zt(n,i,s),qr();const o=document.createElement("iframe");o.id=r,o.setAttribute("title","Sprig User Feedback Dialog");const a=Wr(o,e,t,i);tn();let d=!1;o.setHeight=g=>{(parseInt(o.style.height)!=g||!d)&&(d=!0,o.style.height=`${g}px`,m.emit(f.SurveyHeight,{name:f.SurveyHeight,contentFrameHeight:g,"survey.id":n}))};let l=!1;o.setWidth=g=>{(parseInt(o.style.width)!=g||!l)&&(l=!0,o.style.width=`${g}px`,m.emit(f.SurveyWidth,{name:f.SurveyWidth,contentFrameWidth:g,"survey.id":n}))},(y=window.UserLeap.container)==null||y.appendChild(o),e&&(t?e.exitOnOverlayClickMobile:e.exitOnOverlayClick)&&window.UserLeap.container&&(window.UserLeap.container.onclick=()=>{m.emit(f.CloseSurveyOnOverlayClick)}),m.emit(f.SurveyLifeCycle,{state:"presented"}),m.emit(f.SurveyPresented,{name:f.SurveyPresented,"survey.id":n});const u=(w=o.contentWindow)==null?void 0:w.document;if(u&&(u.open("text/html","replace"),u.write(""),u.close(),!t)){const g=u.body;g.style.display="flex",g.style.alignItems="center"}const c=u==null?void 0:u.head;return{frameId:r,contentWinDocHead:c,contentWindow:o.contentWindow,hasOverlay:a,iframe:o}},nn={[f.SurveyFadingOut]:()=>{window.UserLeap.container&&Object.assign(window.UserLeap.container.style,{"background-color":"rgba(0,0,0,0)"})}},qr=()=>{Object.entries(nn).forEach(([e,t])=>{m.on(e,t)})},$r=()=>{Object.entries(nn).forEach(([e,t])=>{m.off(e,t)})},rn=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 rt(e,t){const{matchType:n,pattern:i}=e,r=n?rn[n]:rn.legacy;let s=!1;try{s=r(i,t)}catch(o){const a=`[Sprig] (ERR-445) Failed to check url match with pattern ${i}`;o instanceof Error&&(console.warn(a,o),o.stack=JSON.stringify(e),window.UserLeap.reportError(a,o))}return s}const sn=e=>{const{pageUrlEvents:t}=window.UserLeap._config,n=t==null?void 0:t.find(i=>i.id===e);return n?rt(n,window.location.href):!1},J=e=>e?e.nodeType===Node.ELEMENT_NODE:!1,zr=1,on=e=>e instanceof HTMLElement||e instanceof SVGElement,Te=({document:e,elementId:t,styleString:n,nonce:i})=>{const r=e.getElementById(t);if(r){r.textContent=n;return}const s=e.createElement("style");i&&(s.nonce=i),s.textContent=n,s.id=t,e.head.appendChild(s)},Kr=e=>{const t=e.querySelector(".sprig-question-body"),n=e.querySelector(".ul-card"),i=e.querySelector(".ul-card-main-content"),r=e.querySelector(".ul-footer"),s=e.querySelector(".sprig-container");let o=0;return J(n)&&(o+=n.scrollHeight-n.clientHeight),J(i)&&(o+=i.scrollHeight-i.clientHeight),J(t)&&(o+=t.scrollHeight-t.clientHeight),J(r)&&J(s)&&s.clientHeight===0&&(o+=r.clientHeight),o},an=100,Gr=(e,t)=>{const n=t.querySelector(".sprig-question-body");if(!J(n))return e;const i=n.scrollHeight;return i{const n=t.querySelector(e);if(!J(n))return 0;const i=getComputedStyle(n),r=parseFloat(i.paddingLeft)+parseFloat(i.paddingRight),s=parseFloat(i.marginLeft)+parseFloat(i.marginRight),o=parseFloat(i.borderLeftWidth)+parseFloat(i.borderRightWidth);return r+s+o},Yr=(e,t,n)=>{const i=e.querySelector(".ul-card__container"),r=e.querySelector(".ul-app");let s=600,o=360,a=0;if(J(i)&&J(r)){const l=i.querySelector(".ul-card--matrix_grid"),u=!l&&t&&n;try{u&&(r.style.width="360px"),s=i.clientHeight,s+=Kr(e);const c=getComputedStyle(i);a=s;const y=parseFloat(c.marginTop)+parseFloat(c.marginBottom),w=parseFloat(c.borderTopWidth)+parseFloat(c.borderBottomWidth);s+=y+w,l&&(o=l.scrollWidth,o+=dn(".ul-card__container",e),o+=dn(".sprig-question-body",e))}finally{u&&r.style.removeProperty("width")}}return[s+zr,o,Gr(a,e)]},cn=()=>h,ue=()=>document.getElementById("sprig-feedback-container"),it=()=>document.getElementById("sprig-feedback-loading-animation"),Jr=()=>{if(it())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=`
`,e},ln=()=>!!document.getElementById(tt);let un=!1,h=null,q=null,st=!1,ve=null,se=null;const Qr=["bottom-left","bottom-right","center-left","center-right"],Xr=e=>{if(ue()||!Qr.includes(e))return;const[t,n]=e.split("-"),i=document.createElement("div");i.id="sprig-feedback-container",i.classList.add(`sprig-feedback-container-${n}`,`sprig-feedback-container-${t}`),document.body.appendChild(i)},Oe=()=>{var t;const e=window.UserLeap.container;return((t=e==null?void 0:e.parentElement)==null?void 0:t.id)==="sprig-feedback-loading-container"},pn=()=>document.getElementById("sprig-feedback-error-container"),wn=()=>{if(!h)return 0;const e=h==null?void 0:h.clientWidth,t=window.getComputedStyle(h),n=parseInt(t.borderRightWidth||"0"),i=parseInt(t.borderLeftWidth||"0");return e+n+i},Pe=e=>{const t=ue();t&&(se!=null&&se.endsWith("right")?t.style.right=`${e}px`:se!=null&&se.endsWith("left")&&(t.style.left=`${e}px`))},ot=()=>{if(h&&(Oe()||pn())){m.off(f.SurveyAppeared,be),at();const e=wn();return Pe(-e),!0}return!1},be=()=>{if(!h||!q)return;const e=it();e&&e.remove(),h.style.height="auto",h.style.width="auto",q.disabled=!1,st=!1},at=()=>{if(!h)return;if(!it()){const t=Jr();t&&(h.style.height="300px",h.style.width="360px",h.appendChild(t))}},fn=()=>{!h||!q||(Pe(0),q.disabled=!0,st=!0)},Zr=async e=>{const t=await j(F("1",[ee],"startFeedbackStudy"),{body:JSON.stringify({surveyUuid:e}),method:"POST"});return t.ok?t.json:null},gn=async(e,t,n)=>{const{buttonTheme:i,customStyles:r,eventId:s,placement:o,desktopDisplay:a,feedbackLabel:d,surveyUuid:l,surveyId:u}=e;window.UserLeap.feedbackCustomStyles=void 0;let c=ue();if(c){if(!t&&s===ve)return;c.remove(),m.off(Re.SURVEY_FADING_OUT,ot)}ve=s,Te({document,elementId:"sprig-feedback-style",styleString:Er,nonce:window.UserLeap.styleNonce}),Te({document,elementId:"ul-custom-style",styleString:r??"",nonce:window.UserLeap.styleNonce}),un=a==="center-modal",se=o;const[w,g]=o.split("-");Xr(o),c=ue(),q=document.createElement("button");const E=document.createElement("div");E.className="sprig-feedback-button-label",E.innerText=d,q.appendChild(E),q.id="sprig-feedback-button",q.classList.add(`sprig-feedback-button-${g}`,`sprig-feedback-button-${w}`,`sprig-feedback-button-${i}`,"fade-in-transition"),m.on(Re.SURVEY_FADING_OUT,ot),q.addEventListener("click",async()=>{const b=document.getElementById("sprig-feedback-error-container");if(ln()||pn()){if(ot()){m.emit(f.SurveyCloseRequested,{name:f.SurveyCloseRequested,initiator:W.FeedbackClosed,studyType:"feedbackButton","survey.id":u}),m.emit(f.SurveyWillClose,{name:f.SurveyWillClose,initiator:W.FeedbackClosed,studyType:"feedbackButton","survey.id":u});const B=ue();b&&B&&(B.remove(),ve=null,h=null)}return}const R=N(window.UserLeap);if(!Ae(R)&&!st&&fn(),t){h&&h.classList.add("sprig-feedback-loading-container-previews"),await ye(t),be();return}const Z=await Zr(l);if(Z)m.once(f.SurveyAppeared,be),ye({...Z,studyType:"feedbackButton"},n);else if(h){const B=ti();h.appendChild(B),be(),h.style.height="300px",h.style.width="360px"}}),c==null||c.appendChild(q),m.emit(f.FeedbackButtonLoaded,{name:f.FeedbackButtonLoaded,"survey.id":u});const{useMobileStyling:x,_config:{border:M}}=window.UserLeap;if(!un&&!x){const b=document.createElement("div");b.id="sprig-feedback-loading-container",b.className=`sprig-feedback-loading-container sprig-feedback-loading-container-${g}`,b.style.setProperty("--feedback-border",M),h=b,at(),c==null||c.appendChild(b);const R=wn();Pe(-R)}else Pe(0);window.UserLeap._config.isOnQuestionsTab&&t&&!Oe()&&h&&(fn(),at(),h&&h.classList.add("sprig-feedback-loading-container-previews"),ye(t),be())},ei=()=>{if(Oe())return;const e=ue();if(!e)return;sn(ve)||(e.remove(),ve=null,h=null)},ti=()=>{const e=document.createElement("div");e.id="sprig-feedback-error-container",e.innerHTML=` `;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},ni="!launch_darkly_";class ri{constructor(){k(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[`${ni}${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 dt=new ri;Object.freeze(dt);const ii="!optimizely_experiments_";class si{constructor(){k(this,"_optimizelyData",{})}setOptimizelyExperiment(t,n=!0){if(!t||typeof t!="object")return!1;const{experiments:i}=t;try{return n&&Object.keys(this._optimizelyData).map(r=>{delete this._optimizelyData[r]}),i&&i.map(r=>{const{id:s,variation:o}=r,a=this.transformExperimentId(s);o&&typeof o=="string"&&(this._optimizelyData[a]=o)}),!0}catch(r){return r instanceof Error&&window.UserLeap.reportError("setOptimizelyExperiment",r),!1}}getAllOptimizelyExperiments(){return this._optimizelyData}getOptimizelyVariationName(t){return this._optimizelyData[this.transformExperimentId(t)]}transformExperimentId(t){return ii+t}getAndSetWebOptimizelyExperiments(){var t;try{if(window&&window.optimizely&&typeof window.optimizely.get=="function"){const n=(t=window.optimizely.get("state"))==null?void 0:t.getExperimentStates({isActive:!0});if(n){const i=Object.keys(n).map(r=>{var s,o;return(s=n[r].variation)!=null&&s.name?{id:r,variation:(o=n[r].variation)==null?void 0:o.name}:{id:r,variation:"Original"}});return this.setOptimizelyExperiment({experiments:i},!1),!0}return!1}return!1}catch(n){return n instanceof Error&&window.UserLeap.reportError("getAndSetWebOptimizely",n),!1}}}const Me=new si;Object.freeze(Me);class oi{constructor(t,n){k(this,"paused");k(this,"queue");k(this,"ul");this.ul=t,this.paused=!1,this.queue=[],this.flush(n)}flush(t){const n=t.length;if(n)for(let i=0;i{};const i=new Promise(function(r){n=function(){r(t())}});return this.queue.push(n),i}else return t()}empty(){this.queue.length=0}}let mn=!0,ct=!1;const ai=()=>mn=!1,di=()=>ct=!0,ci=["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","sdk_mutations_nodes_added","sdk_mutations_nodes_removed","sdk_mutations_attributes_changed","sdk_mutations_character_data","sdk_dom_nodes_count","sdk_page_html_characters"];let Le={},lt;class li{constructor(t){k(this,"_values",[]);k(this,"_isWebMetric");this.name=t,this._isWebMetric=ci.includes(this.name)}report(t){if(mn&&this._values.push({time:Date.now(),value:t}),ct||!this._isWebMetric)return;const n=this.findExceededThreshold(t);n&<&<(t,n)}collect(){const t=this._values;return this._values=[],t}findExceededThreshold(t){const n=Le[this.name];if(n)return n.find(i=>this.valueExceedsThreshold(t,i))}valueExceedsThreshold(t,n){return n.type==="max"?t>n.value:n.type==="min"?t{Le={},ct=!1,e==null||e.forEach(n=>{var i;n.metric in Le||(Le[n.metric]=[]),(i=Le[n.metric])==null||i.push(n)}),lt=t},Se={},$=e=>{const t=new li(e);return Se[e]=t,t},yn=(e,t)=>{let n=Se[e];return n||(n=$(e)),n.report(t)},pi=async e=>{const t=Object.values(Se).map(n=>({name:n.name,values:n.collect()}));if(t.some(n=>n.values.length))try{await e(JSON.stringify(t))}catch(n){n instanceof Error&&p.error("MetricsErr",{error:{message:n.message,name:n.name}})}},wi=({reportingIntervalSeconds:e,postMetrics:t})=>{e?setInterval(()=>{pi(t)},e*1e3):ai()};let hn,vn;const ut=e=>{let t=0,n=e.firstElementChild;for(;n;)t+=ut(n),n.shadowRoot&&(t+=ut(n.shadowRoot)),n=n.nextElementSibling,t++;return t},fi=()=>document.documentElement.innerHTML.length,bn=()=>{hn.report(ut(document.body)),vn.report(fi())},gi=(e=10*1e3)=>{hn=$("sdk_dom_nodes_count"),vn=$("sdk_page_html_characters"),bn(),setInterval(bn,e)},pt=(e,t)=>{const n=performance.now();document.hidden?setTimeout(()=>pt(e,t),e):setTimeout(()=>{const i=performance.now()-n;t.report(i/1e3),setTimeout(()=>pt(e,t),e)},0)},mi=(e=1e3)=>{const t=$("sdk_event_queue_latency_seconds");pt(e,t)};let Be,Ne,Fe,He,oe={},Ln;const Ve=(e,t=1)=>{const{name:n}=e;oe[n]=(oe[n]||0)+t},Sn=e=>{let t=1;return e.childNodes.forEach(n=>{t+=Sn(n)}),t},Un=e=>{let t=0;return e.forEach(n=>{t+=Sn(n)}),t},yi=e=>{switch(e.type){case"childList":Ve(Be,Un(e.addedNodes)),Ve(Ne,Un(e.removedNodes));return;case"attributes":Ve(Fe);return;case"characterData":Ve(He);return}},hi=e=>e.forEach(yi),vi=()=>{Ln=new MutationObserver(hi),Ln.observe(document,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0})},bi=()=>{Be.report(oe[Be.name]||0),Ne.report(oe[Ne.name]||0),Fe.report(oe[Fe.name]||0),He.report(oe[He.name]||0),oe={}},Li=(e=1*1e3)=>{Be=$("sdk_mutations_nodes_added"),Ne=$("sdk_mutations_nodes_removed"),Fe=$("sdk_mutations_attributes_changed"),He=$("sdk_mutations_character_data"),vi(),setInterval(bi,e)},Si=({isWeb:e,reportingIntervalSeconds:t,thresholds:n,postMetrics:i})=>{ui(n,(r,s)=>{var o,a;if((o=L.replay)!=null&&o.isReplayRecording()){const d=`Value: ${r} on ${s.metric} violated threshold of ${s.type} ${s.value}`;(a=L.replay)==null||a.disableRecording("Threshold violated",new Error(d),{reportError:!1}),window.UserLeap.reportError("Sdk Performance Metric threshold violated",new Error("Sdk Performance Metric threshold violated"),{metricName:s.metric,type:s.type,value:s.value},{metricName:s.metric}),di()}}),wi({reportingIntervalSeconds:t,postMetrics:i}),e&&(mi(),gi(),Li())},Ui={test:"test"},Ii=["popState","pushState","replaceState"];let wt,Ue;const We={},Ie="!email",In="pageUrl";function Ei(e){if(!window.UserLeap._config.dismissOnPageChange)return!0;const t=new URL(e),n=new URL(Ue??window.location.href);return t.hostname===n.hostname&&t.pathname===n.pathname}let ft=window.location.href;function Ee(e){var d,l;const{pageUrlEvents:t,interactiveEvents:n,dismissOnPageChange:i,platform:r}=window.UserLeap._config;if(r&&r!=="web")return;ft!==window.location.href&&p.navigation("LocationChange",{from:ft,to:window.location.href}),ft=window.location.href;const o=_n().trackStartUrl,a=o?String(o):null;t&&Dn(window.location.href),n&&(kn(),ki()),cn()&&ei(),I.getItem("sprig.isCapturingHeatmap")&&((l=(d=L.replay)==null?void 0:d.checkPendingHeatmapsUrl())==null||l.then(u=>{var c;u&&((c=L.replay)==null||c.uploadReadyPendingCaptures(!0))})),!Oe()&&i&&a&&a!==window.location.href&&e&&Ii.includes(e.type)&&window.UserLeap("dismissActiveSurvey",W.PageChange)}const En={capture:!0},ki=()=>{const t=window.UserLeap._config.interactiveEvents.filter(i=>rt(i,window.location.href)).map(i=>{const{name:r,properties:s}=i,{selector:o,innerText:a}=s;return o?d=>{if(on(d.target))try{d.target.closest(o)&&window.UserLeap("track",r)}catch{}return!1}:d=>(on(d.target)&&d.target.innerText===a&&window.UserLeap("track",r),!1)}),n=i=>t.forEach(r=>r(i));window.UserLeap._config.interactiveEventsHandler=n,window.addEventListener("click",n,En)},kn=()=>{window.UserLeap._config.interactiveEventsHandler&&window.removeEventListener("click",window.UserLeap._config.interactiveEventsHandler,En),delete window.UserLeap._config.interactiveEventsHandler};function _i(){["hashchange","popstate"].forEach(e=>window.addEventListener(e,Ee,!0))}function Ri(){["hashchange","popstate"].forEach(e=>window.removeEventListener(e,Ee,!0)),window.UserLeap._config.interactiveEvents&&kn()}function Di(e){const t=new URL(F("1",[te],"questions"));return Object.entries(e||{}).forEach(([n,i])=>{i&&t.searchParams.append(n,String(i))}),t.toString()}function _n(){const e=A.getItemObject("userleap.ids");return e&&e[window.UserLeap.envId]||{}}function Rn(){if(window.previewMode)return;const e=A.getItemObject("sprig.anon.env.vid.map")||{},t=e[window.UserLeap.envId];window.UserLeap.visitorId=t||le(),p.info("NewVid",{vid:window.UserLeap.visitorId}),T("vid",window.UserLeap.visitorId),t||(e[window.UserLeap.envId]=window.UserLeap.visitorId,A.setItemObject("sprig.anon.env.vid.map",e)),m.emit(f.VisitorIDUpdated,{visitorId:window.UserLeap.visitorId})}function Dn(e,t,n,i){var r,s;try{if(e.endsWith("mock_snippet.html"))return;p.info("PageView",{url:e});const o=(r=document==null?void 0:document.querySelector('meta[name="description"]'))==null?void 0:r.getAttribute("content");(s=L.replay)==null||s.RecordPageView({...o&&{description:o},url:e,referrer:document.referrer,pageTitle:document.title});const a=window.UserLeap._config.pageUrlEvents;let d=!1;if(a&&a.length)for(let u=0;ufunction(...i){const r=t.apply(this,i),s=new Event("pushState");return window.dispatchEvent(s),Ee(s),r})(e.pushState)),"replaceState"in e&&(e.replaceState=(t=>function(...i){const r=t.apply(this,i),s=new Event("replaceState");return window.dispatchEvent(s),Ee(s),r})(e.replaceState)),_i()}async function gt(e,t){const n=et();e&&!t&&(window.UserLeap._config.mode=Ui.test);const i=N(window.UserLeap),r=Ae(i),s=await j(Di({desktopDisplay:window.UserLeap._config.desktopDisplay,isMobile:r,previewLanguage:window.UserLeap._config.previewLanguage,surveyid:e==null?void 0:e.surveyId,surveytemplateid:e==null?void 0:e.surveyTemplateId,vid:n}),{shouldDropOnRateLimit:!0});if(!s.ok)return s.reportError&&s.error&&(console.warn("[Sprig] (ERR-414) Failed to request questions from the server",s.error),window.UserLeap.reportError("getQuestions",s.error)),{success:!1,surveyState:"no survey"};if(s.json.delay&&await De(s.json.delay),s.json.isFeedback){const{feedbackLabel:o,productConfig:a,surveyUuid:d,feedbackCustomStyles:l}=s.json,{buttonTheme:u,placement:c,desktopDisplay:y}=a,w={customStyles:l,buttonTheme:u,desktopDisplay:y,eventId:0,feedbackLabel:o,placement:c,surveyUuid:d,surveyId:e==null?void 0:e.surveyId};gn(w,s.json)}else return ye(s.json,Ue,wt)}function xi(e){let t=e.length;for(;t;){const n=Math.floor(Math.random()*t);t-=1;const i=e[t];e[t]=e[n],e[n]=i}}function Ai(e){if(!e)return;window.UserLeap._config=e,e.mute&&window.UserLeap._queue.pause();const{interactiveEvents:t,pageUrlEvents:n,dismissOnPageChange:i}=e;t&&xi(t),(t||n||i)&&(Ci(),Ee())}async function Ti(e,t){var i,r;let n=!0;return t&&((i=e==null?void 0:e.json)!=null&&i.surveyId)&&(window.UserLeap.delayingSurvey=!0,n=await t(e.json.surveyId),window.UserLeap.delayingSurvey=!1,!n)?!1:((r=e==null?void 0:e.json)!=null&&r.delay&&!window.UserLeap.isMobileSDK&&(window.UserLeap.delayingSurvey=!0,await De(e.json.delay),window.UserLeap.delayingSurvey=!1),n)}const Oi=function(e){if(!window.UserLeap)return;const t=async(r={})=>{var b,R,_e,Z,B;const{userId:s,anonymousId:o,metadata:a={},properties:d,showSurveyCallback:l}=r;let{eventName:u}=r;if(window.UserLeap.debugMode&&u!==In&&console.info("[DEBUG] Sprig track",r),e.mode==="test")return;const c=A.getItem("sprig.previewKey")??void 0;if(e.requireUserIdForTracking&&!window.UserLeap.userId&&!s){const D="[Sprig] - Skipping tracking without userId";return console.warn(D),{success:!1,message:D,surveyState:"no survey"}}if(!u||u.trim().length===0){u=u?String(u):"";const D="[Sprig] - Invalid event name "+u;return console.warn(D),{success:!1,message:D,surveyState:"no survey"}}const y=Ue??window.location.href;if(a.url||(a.url=y),T("trackStartUrl",y),(R=(b=window.UserLeap)==null?void 0:b._config)!=null&&R.optimizelyEnabled){const D=N(window.UserLeap);he(D)||Me.getAndSetWebOptimizelyExperiments(),a.optimizelyExperiments=Object.assign({},Me.getAllOptimizelyExperiments())}(Z=(_e=window.UserLeap)==null?void 0:_e._config)!=null&&Z.launchDarklyEnabled&&(a.launchDarklyFlags=dt.getAllLaunchDarklyVariations()),s&&(window.UserLeap.userId=s),o&&(window.UserLeap.partnerAnonymousId=o),d&&(a.eventProperties=d),(B=L.replay)==null||B.RecordEvent({name:u,url:a.url}),p.info("TrackEvent",{eventName:u});const w=window.UserLeap.delayingSurvey||ln()?await j(F("1",[ee],"events/batch"),{body:JSON.stringify({events:[{event:u,metadata:a}],previewKey:c}),method:"POST",shouldDropOnRateLimit:!0}):await j(F("1",[ee],"events"),{body:JSON.stringify({event:u,metadata:a,previewKey:c}),method:"POST",shouldDropOnRateLimit:!0});if(!w.ok){const D="[Sprig] (ERR-421) Failed to track event";return w.reportError&&(console.warn(D,w.error),w.error&&window.UserLeap.reportError("track",w.error)),{success:!1,message:D,error:w.error,surveyState:"no survey"}}s&&T("uid",s),o&&T("aid",o);const g=w.json;g.invalidPreviewKey&&A.removeItem("sprig.previewKey");const E=a.trackPageView?a.url:void 0;return!!(g!=null&&g.feedbackButton)&&gn(g.feedbackButton,void 0,E),await Ti(w,l)?Ei(y)?ye(g,E,wt):{success:!1,message:"Study should not be displayed after page navigation",surveyState:"no survey"}:{success:!1,message:"[Sprig] Callback returned false, aborting rendering of survey",surveyState:"no survey"}},n=(r,s)=>{var a;const o=(a=r==null?void 0:r.querySelector(`[id="${tt}"]`))==null?void 0:a.contentDocument;o&&Te({document:o,elementId:"ul-custom-style",styleString:s})},i={async displaySurvey(r){return console.warn("[Sprig] displaySurvey should only be used to debug your studies; not intended for production usage."),window.UserLeap("dismissActiveSurvey",W.Override),gt({surveyId:r},!0)},_previewSurvey(r){window.UserLeap("dismissActiveSurvey",W.Override),gt({surveyTemplateId:r},!1)},_reviewSurvey(r){window.UserLeap("dismissActiveSurvey",W.Override),gt({surveyId:r},!1)},previewSurvey(r){i._previewSurvey(r)},reviewSurvey(r){i._reviewSurvey(r)},mute(){window.UserLeap._queue.pause()},unmute(){window.UserLeap._queue.unpause()},setVisitorToken(){console.warn("[Sprig] setVisitorToken is deprecated.")},dismissActiveSurvey(r=W.API){window.UserLeap.container&&(r===W.Closed&&window.Sprig.trackHistory&&window.Sprig.trackHistory({event:"closed"}),m.emit(f.SurveyCloseRequested,{name:f.SurveyCloseRequested,initiator:r,"survey.id":parseInt(window.UserLeap.container.dataset.studyId)}),m.emit(f.SurveyWillClose,{name:f.SurveyWillClose,initiator:r,"survey.id":parseInt(window.UserLeap.container.dataset.studyId)}))},async setAttribute(r,s){if(!r||!s&&s!==0&&s!==!1){const o="[Sprig] - Disregarding empty attribute / value provided";return console.warn(o),{success:!1,message:o}}return this.setAttributes({[r]:s})},async setAttributes(r){if(r==null||Object.keys(r).length===0){const s="[Sprig] - Disregarding empty attributes provided";return console.warn(s),{success:!1,message:s}}return this.identifyAndSetAttributes({attributes:r})},async identifyAndSetAttributes(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig identifyAndSetAttributes",r),e.mode==="test")return;if(r===null||typeof r!="object"||!(r.userId||r.anonymousId||r.attributes)){const u="[Sprig] - Disregarding empty payload provided";return console.warn(u),{success:!1,message:u}}const{userId:s,anonymousId:o,attributes:a}=r;if(e.requireUserIdForTracking&&!window.UserLeap.userId&&!s){const u="[Sprig] - Skipping tracking without userId";return console.warn(u),{success:!1,message:u}}if(a){a.email&&!a[Ie]&&(a[Ie]=a.email,delete a.email);const u=Object.keys(a);for(const c of u)a[c]===We[c]&&delete a[c]}if((!a||Object.keys(a).length===0)&&(!s||window.UserLeap.userId===s)&&(!o||window.UserLeap.partnerAnonymousId===o))return{success:!0};const d={};s&&(d.userId=window.UserLeap.userId=s),o&&(d.partnerAnonymousId=window.UserLeap.partnerAnonymousId=o);let l;return a&&Object.keys(a).length>0?(l=await j(F("1",[te,ee],"attributes"),{body:JSON.stringify(a),method:"PUT"}),l.ok?Object.assign(We,a):l.reportError&&(console.warn("[Sprig] (ERR-432) identifyAndSetAttributes failed",l.error),l.error&&window.UserLeap.reportError("identifyAndSetAttributes",l.error))):l=await j(F("1",[te,ee]),{body:JSON.stringify(d),method:"PUT"}),a&&a[Ie]&&(window.UserLeap.email=a[Ie]),l.ok&&(s&&T("uid",s),o&&T("aid",o)),{success:!!l.ok}},async removeAttributes(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig removeAttributes",r),e.mode==="test")return;if(r==null||r.length===0){const 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 j(F("1",[te,ee],"attributes"),{body:JSON.stringify({delete:r}),method:"DELETE"});return!s.ok&&s.reportError&&(console.warn("[Sprig] (ERR-433) Remove attributes failed",s.error),s.error&&window.UserLeap.reportError("removeAttributes",s.error)),{success:!!s.ok}},async addSurveyListener(r){m.on(f.SurveyLifeCycle,r)},async removeSurveyListener(r){m.removeListener(f.SurveyLifeCycle,r)},async addListener(r,s){m.on(r,s)},async removeListener(r,s){m.removeListener(r,s)},async removeAllListeners(){m.removeAllListeners()},setPreviewKey(r){!r||typeof r!="string"||A.isStorageAvailable&&r&&A.setItem("sprig.previewKey",r)},async setUserId(r){var a;if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig setUserId",r),r==null){const d=`[Sprig] - Invalid userId ${r}`;return console.warn(d),{success:!1,message:d}}if(e.mode==="test"||r===window.UserLeap.userId)return;window.UserLeap.userId=r;const s=window.UserLeap.visitorId,o=await j(F("1",[te,ee]),{body:JSON.stringify({userId:r}),method:"PUT"});if(!o.ok){o.reportError&&(console.warn("[Sprig] (ERR-420) Failed to set user id",o.error),o.error&&window.UserLeap.reportError("setUserId",o.error));return}s!==window.UserLeap.visitorId&&((a=L.replay)==null||a.clearUserReplayData()),T("uid",r)},async setPartnerAnonymousId(r){if(window.UserLeap.debugMode&&console.info("[DEBUG] Sprig setPartnerAnonymousId",r),r==null){const s=`[Sprig] - Invalid partnerAnonymousId ${r}`;return console.warn(s),{success:!1,message:s}}return window.UserLeap.partnerAnonymousId=r,T("aid",r),{success:!0}},async track(r,s,o={},a=void 0){return t({eventName:r,properties:s,metadata:o,showSurveyCallback:a})},async identifyAndTrack(r){return await t(r)},trackPageView(r,s=void 0,o=void 0,a=!0){Ue=r,Dn(r,s,o,a)},applyFeedbackStyles({button:r="",view:s=""}){window.UserLeap.feedbackCustomStyles=s,document.getElementById("sprig-feedback-style")&&Te({document,elementId:"ul-custom-style",styleString:r,nonce:window.UserLeap.styleNonce}),n(document.querySelector(".ul-container-feedback"),s)},applyStyles(r){window.UserLeap.customStyles=r,n(window.UserLeap.container,r)},setWindowDimensions(r,s){var y,w;const o=typeof r=="string"?parseInt(r,10):r,a=typeof s=="string"?parseInt(s,10):s;!isNaN(o)&&!isNaN(a)&&(window.UserLeap.windowDimensions={width:o,height:a});const d=N(window.UserLeap),l=Ae(d),u=d["userleap-platform"]==="web";if(!window.UserLeap.frameId)return;const c=document.getElementById(window.UserLeap.frameId);c&&(window.UserLeap.useMobileStyling&&((y=window.UserLeap.windowDimensions)!=null&&y.width&&(c.style.width=`${window.UserLeap.windowDimensions.width}px`),(w=window.UserLeap.windowDimensions)!=null&&w.height&&(c.style.maxHeight=`${window.UserLeap.windowDimensions.height-20}px`),c.contentDocument&&(c.style.height=String(Yr(c.contentDocument,u&&!l,$t(d))[0])+"px")),m.emit(f.SurveyDimensions,{name:f.SurveyDimensions,contentFrameWidth:c.clientWidth,contentFrameHeight:c.clientHeight,"survey.id":parseInt(window.UserLeap.container.dataset.studyId)}))},logoutUser(){var r;window.UserLeap.debugMode&&console.info("[DEBUG] Sprig logout"),p.info("LogOut",{vid:window.UserLeap.visitorId,userId:window.UserLeap.userId}),window.UserLeap.visitorId=null,window.UserLeap.userId=null,window.UserLeap.partnerAnonymousId=null,window.UserLeap.token=null,window.UserLeap.email=null,A.removeItem("userleap.ids"),window.UserLeap._queue.isPaused()&&window.UserLeap._queue.empty(),Rn(),(r=L.replay)==null||r.clearUserReplayData(),window.UserLeap._queue.unpause()},teardown(){Ri(),window.UserLeap("dismissActiveSurvey",W.API),delete window.UserLeap,delete window.Sprig,delete window._Sprig},integrateOptimizely(r,s=!0){var o,a;if(!((a=(o=window.UserLeap)==null?void 0:o._config)!=null&&a.optimizelyEnabled)){console.warn("[SPRIG] Optimizely integration is currently not enabled for your product.");return}try{const d=typeof r=="string"?JSON.parse(r):r;Me.setOptimizelyExperiment(d,s)}catch(d){console.warn("[Sprig] Error with integrating Optimizely data"),d instanceof Error&&window.UserLeap.reportError("integrateOptimizely",d)}},integrateOptimizelyClient(r){var o,a;if(!((a=(o=window.UserLeap)==null?void 0:o._config)!=null&&a.optimizelyEnabled)){console.warn("[SPRIG] Optimizely integration is currently not enabled for your product.");return}const s=({experiment:d,variation:l})=>{const u={experiments:[{id:d.id,variation:l.key}]};window.UserLeap("integrateOptimizely",u,!1)};r.notificationCenter.addNotificationListener("ACTIVATE:experiment, user_id,attributes, variation, event",s)},importLaunchDarklyData(r){var s,o;if(!((o=(s=window.UserLeap)==null?void 0:s._config)!=null&&o.launchDarklyEnabled)){console.warn("[SPRIG] LaunchDarkly integration is currently not enabled for your product.");return}dt.setLDFlagsVariations(r)},setVisitorAttribute(r,s){return console.warn("[Sprig] setVisitorAttribute is deprecated. Please use setAttribute"),i.setAttribute(r,s)},async setEmail(r){return i.setAttribute(Ie,r)},async setVisitorEmail(r){return console.warn("[Sprig] setVisitorEmail is deprecated. Please use setEmail"),i.setEmail(r)},async _generateVideoUploadUrl(r){return Bi(r)},_reportMetric(r,s){yn(r,s)},async _completeSessionReplay({surveyId:r,responseGroupUuid:s,eventDigest:o}){var a;return L.replay?(a=L.replay)==null?void 0:a._completeSessionReplay({surveyId:r,responseGroupUuid:s,eventDigest:o,headers:N(window.UserLeap)}):(window.UserLeap.reportError("_completeSessionReplay",new Error("Replay module not registered")),!1)}};Object.assign(window.UserLeap,i)};async function Pi(e){var s,o;const t=N(window.UserLeap);document.addEventListener("securitypolicyviolation",Jt);const n=await Y(F("1",[te],"config"),{headers:t});if(document.removeEventListener("securitypolicyviolation",Jt),!n.ok)return(s=window.SprigLoggerCallback)==null||s.call(window,"Sprig config fetch failed"),n.reportError&&(console.warn("[Sprig] (ERR-422) Failed to load configuration",n.error),n.error&&window.UserLeap.reportError("applyRemoteConfig",n.error)),Ze("Disabled: failed to fetch configuration"),e;const i=n.json;return i!=null&&i.disabled?((o=window.SprigLoggerCallback)==null||o.call(window,"Sprig config fetch disabled"),Ze(`Disabled: ${i.disabled}`),{disabled:i.disabled}):Object.assign({},i,e)}async function Mi(e,t,n={},i={}){const r=window.__cfg&&window.__cfg.mode,s=et(),o=window.UserLeap.envId,a=window.document.documentElement,d={mode:r,screenWidth:window.screen.width,screenHeight:window.screen.height,clientWidth:a.clientWidth,clientHeight:a.clientHeight,location:Ue??window.location.href,language:window.navigator.language,...n},l={action:e,breadcrumbs:p.breadcrumbs,err:{message:`${t==null?void 0:t.name} - ${t==null?void 0:t.message}`,stack:t==null?void 0:t.stack},meta:d,vid:s,envId:o,...i};(await j(F("1",null,"errors"),{method:"POST",headers:{"x-ul-error":window.btoa(`userleap-${Date.now()}-error`)},body:JSON.stringify(l),shouldDropOnRateLimit:!0})).ok||console.warn("[Sprig] (ERR-444) Failed to report error to API",t)}async function Bi(e){var n;if(!e)return;const t=`${window.UserLeap._API_URL}/2/environments/integrations/upload`;try{const i=await fetch(t,{method:"POST",cache:"no-cache",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(i.ok){const r=await i.json();return(n=r==null?void 0:r.upload)==null?void 0:n.url}else return null}catch(i){console.warn("[Sprig] Error with generating video upload url"),i instanceof Error&&window.UserLeap.reportError("generateVideoUploadUrl",i)}}function Ni(e={}){var i;(i=window.SprigLoggerCallback)==null||i.call(window,"Initializing Sprig");const t=new URLSearchParams(window.location.search).get("sprigPreviewKey")??"";window.UserLeap.UPDATES=Re,window.UserLeap("setPreviewKey",t);async function n(){var w,g,E,x,M;if(window.UserLeap.loaded)return;if((w=window.SprigLoggerCallback)==null||w.call(window,"Loading Sprig"),window.UserLeap.reportError=Mi,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 b in window.UserLeap._config)window.UserLeap[b]=window.UserLeap._config[b];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=_n(),s=window.UserLeap.sampleRate;let o=r.sampled;if(s){if(o===null&&(o=Math.random(){var R;await j(F("1",[te],"metrics"),{body:b,method:"POST",headers:{"x-ul-replay-enabled":`${!!((R=L.replay)!=null&&R.isReplayRecording())}`},shouldDropOnRateLimit:!0})}});const y=c.alwaysOnReplay?{userAgent:window.navigator.userAgent,surveyId:c.alwaysOnReplay.surveyId,responseGroupUuid:c.alwaysOnReplay.responseGroupUuid,sdkVersion:"2.33.3",maxDurationSeconds:c.alwaysOnReplay.maxDurationSeconds}:void 0;await((x=L.replay)==null?void 0:x.initializeReplay({maxReplayDurationSeconds:c.maxReplayDurationSeconds,maxInflightRequests:window.UserLeap.maxInflightReplayRequests??2,replaySettings:c.replaySettings,apiUrl:window.UserLeap._API_URL,alwaysOnConfig:y})),wt=c.replaySettings,Oi(c),await Ai(c),window.UserLeap._queue.unpause(),(M=window.SprigLoggerCallback)==null||M.call(window,"SdkReady"),m.emit(f.SDKReady,{mobileMetricsReportingEnabled:!!c.mobileMetricsReportingEnabled,metricsReportingInterval:c.metricsReportingIntervalSeconds||0,metricsThresholds:c.metricThresholds||[],maxMobileReplayDurationSeconds:c.maxMobileReplayDurationSeconds,mobileReplaySettings:c.mobileReplaySettings}),m.emit(f.VisitorIDUpdated,{visitorId:window.UserLeap.visitorId}),m.on(f.VisitorIDUpdated,()=>{for(const b in We)delete We[b]})}document.readyState==="complete"?n():window.attachEvent?window.attachEvent("onload",n):window.addEventListener("load",()=>{n()},!1)}var ne=(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))(ne||{}),Q=(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(Q||{});const mt=(e,t)=>t.some(n=>e instanceof n);let Cn,xn;function Fi(){return Cn||(Cn=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Hi(){return xn||(xn=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const yt=new WeakMap,ht=new WeakMap,je=new WeakMap;function Vi(e){const t=new Promise((n,i)=>{const r=()=>{n(re(e.result))},s=()=>{i(e.error)};e.onsuccess=r,e.onerror=s});return je.set(t,e),t}function Wi(e){if(yt.has(e))return;const t=new Promise((n,i)=>{const r=()=>{n()},s=()=>{i(e.error||new DOMException("AbortError","AbortError"))};e.oncomplete=r,e.onerror=s,e.onabort=s});yt.set(e,t)}let vt={get(e,t,n){if(e instanceof IDBTransaction){if(t==="done")return yt.get(e);if(t==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return re(e[t])},set(e,t,n){return e[t]=n,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function An(e){vt=e(vt)}function ji(e){return Hi().includes(e)?function(...t){return e.apply(bt(this),t),re(this.request)}:function(...t){return re(e.apply(bt(this),t))}}function qi(e){return typeof e=="function"?ji(e):(e instanceof IDBTransaction&&Wi(e),mt(e,Fi())?new Proxy(e,vt):e)}function re(e){if(e instanceof IDBRequest)return Vi(e);if(ht.has(e))return ht.get(e);const t=qi(e);return t!==e&&(ht.set(e,t),je.set(t,e)),t}const bt=e=>je.get(e);function $i(e,t,{blocked:n,upgrade:i,blocking:r,terminated:s}={}){const o=indexedDB.open(e,t),a=re(o);return i&&(o.onupgradeneeded=d=>{i(re(o.result),d.oldVersion,d.newVersion,re(o.transaction),d)}),n&&(o.onblocked=d=>n(d.oldVersion,d.newVersion,d)),a.then(d=>{s&&(d.onclose=()=>s()),r&&(d.onversionchange=l=>r(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}function Lt(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&(n.onblocked=i=>t(i.oldVersion,i)),re(n).then(()=>{})}const zi=["get","getKey","getAll","getAllKeys","count"],Ki=["put","add","delete","clear"],St=new Map;function Tn(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(St.get(t))return St.get(t);const n=t.replace(/FromIndex$/,""),i=t!==n,r=Ki.includes(n);if(!(n in(i?IDBIndex:IDBObjectStore).prototype)||!(r||zi.includes(n)))return;const s=async function(o,...a){const d=this.transaction(o,r?"readwrite":"readonly");let l=d.store;return i&&(l=l.index(a.shift())),(await Promise.all([l[n](...a),r&&d.done]))[0]};return St.set(t,s),s}An(e=>({...e,get:(t,n,i)=>Tn(t,n)||e.get(t,n,i),has:(t,n)=>!!Tn(t,n)||e.has(t,n)}));const Gi=["continue","continuePrimaryKey","advance"],On={},Ut=new WeakMap,Pn=new WeakMap,Yi={get(e,t){if(!Gi.includes(t))return e[t];let n=On[t];return n||(n=On[t]=function(...i){Ut.set(this,Pn.get(this)[t](...i))}),n}};async function*Ji(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;const n=new Proxy(t,Yi);for(Pn.set(n,t),je.set(n,bt(t));t;)yield n,t=await(Ut.get(n)||t.continue()),Ut.delete(n)}function Mn(e,t){return t===Symbol.asyncIterator&&mt(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&mt(e,[IDBIndex,IDBObjectStore])}An(e=>({...e,get(t,n,i){return Mn(t,n)?Ji:e.get(t,n,i)},has(t,n){return Mn(t,n)||e.has(t,n)}}));const qe={Loaded:"sprigReplayIframeLoaded",Settings:"sprigReplayIframeSettings",Snapshot:"sprigReplayIframeTakeFullSnapshot",Teardown:"sprigReplayTeardown"},It=[],Qi=(e,t)=>{window.addEventListener("message",n=>{var i;n.data.type===qe.Loaded&&(It.push({source:n.source,origin:n.origin}),(i=n.source)==null||i.postMessage({type:qe.Settings,settings:e,replayLibraryUrl:t},{targetOrigin:n.origin}))})},Xi=()=>{It.forEach(e=>{var t;(t=e.source)==null||t.postMessage({type:qe.Snapshot},{targetOrigin:e.origin})})},Zi=()=>{It.forEach(e=>{var t;(t=e.source)==null||t.postMessage({type:qe.Teardown},{targetOrigin:e.origin})})};class es{constructor(t){k(this,"awaitingResolvers",[]);k(this,"activeCount",0);this.capacity=t}async acquire(){if(this.activeCount{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 Bn=new es(2),ts=e=>Bn.setLimit(e),ns=async e=>Bn.execute(async()=>{var i;p.info("UploadChunkStart",{chunkIndex:e.chunkIndex,surveyId:e.surveyId});const t=await Y(e.uploadUrl,{body:e.data,method:"PUT"});p.http("UploadChunkEnd",{url:e.uploadUrl,method:"PUT",status_code:t.status,reason:t.statusText??"OK",chunkIndex:e.chunkIndex,surveyId:e.surveyId});const n=(i=t.headers)==null?void 0:i.get("ETag");if(!n)throw new Error(`Upload response did not include etag for upload ${e.uploadId}, part ${e.chunkIndex}`);return n}),Nn=async({apiUrl:e,surveyId:t,uploadId:n,etags:i,headers:r,responseGroupUuid:s,replayDuration:o,eventDigest:a},d=!1)=>{var u;if(!d&&!n&&!i){p.error("UploadErr",{isMobile:d,uploadId:n,etags:i});return}p.info("MarkUploadComplete",{surveyId:t});const l=await Y(`${e}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:i,uploadId:n,responseGroupUuid:s,surveyId:t,replayDuration:o,eventDigest:a,userAgent:(u=window==null?void 0:window.navigator)==null?void 0:u.userAgent}),headers:r,shouldRetryRequest:!0});return p.info("MarkUploadDone",{surveyId:t}),l},rs=e=>{if(e instanceof Attr)return null;let t=1;for(let n=e.previousSibling;n;n=n.previousSibling)n.nodeName===e.nodeName&&++t;return t},Fn=e=>{if(e===null)return"";const t=[];if(e instanceof Document)return"/";for(let n=e;n&&!(n instanceof Document)&&n!==null;n=n instanceof Attr?n.ownerElement:n.parentElement){const i=t[t.length]={name:void 0,position:null};switch(n.nodeType){case Node.TEXT_NODE:i.name="text()";break;case Node.ATTRIBUTE_NODE:i.name="@"+n.nodeName;break;case Node.PROCESSING_INSTRUCTION_NODE:i.name="processing-instruction()";break;case Node.COMMENT_NODE:i.name="comment()";break;case Node.ELEMENT_NODE:i.name=n.nodeName;break}i.position=rs(n)}return"/"+t.reverse().map(n=>n.position!==null?`/${n.name}[${n.position}]`:`/${n.name}`).join("")},Et=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),z={capture:!0,passive:!0},is=["a","button","input","option","li","link"],ss=["Escape","Enter","Backspace","F5","Tab"];let $e=!1,O=null,ze=null;const os=e=>{e.currentPageTitle&&(e.currentPageTitle=Et(e.currentPageTitle)),O==null||O("Sprig_BackForward",e)},as=e=>{var t;(t=e==null?void 0:e.elementAttributes)!=null&&t.text&&(e.elementAttributes.text=Et(e.elementAttributes.text)),O==null||O("Sprig_Click",e)},ds=e=>{O==null||O("Sprig_Refresh",e)},cs=e=>{O==null||O("Sprig_Keystroke",e)},ls=e=>{if(!e.tagName)return"No tagName";const t=e.getAttribute("type");return t?`${t} ${e.tagName.toLowerCase()}`:e.tagName.toLowerCase()},Hn=e=>{var n;if(((n=e.tagName)==null?void 0:n.toLowerCase())==="html")return{element:"html"};const t={};return t.element=ls(e),t},us=e=>{var r;if(!e)return{};const n={...Hn(e)},i=e.parentElement;if(i&&is.includes((r=i.tagName)==null?void 0:r.toLowerCase())){const s=Hn(i);Object.assign(n,s)}return n},Vn=(e,t)=>{var i;let n=t.target;t.target===((i=window.document)==null?void 0:i.body)&&window.Sprig.pointerDownTarget&&(n=window.Sprig.pointerDownTarget),as({x:t.x,y:t.y,type:e,elementAttributes:us(n),windowHeight:window.innerHeight,windowWidth:window.innerWidth,...n instanceof HTMLElement?{rect:n==null?void 0:n.getBoundingClientRect(),xPath:Fn(n)}:{}})},ps=e=>t=>Vn(e,t),Wn=e=>{ss.includes(e.key)&&cs({key:e.key})},ws=()=>{window.performance.getEntriesByType("navigation").map(t=>t.type).includes("reload")&&ds({url:window.location.href,currentPageTitle:document.title})},fs=()=>{window.performance.getEntriesByType("navigation").map(t=>t.type).includes("back_forward")&&os({curUrl:window.location.href,fromUrl:document.referrer,currentPageTitle:document.title})},jn=((e,t)=>{let n;return i=>{clearTimeout(n),n=window.setTimeout(()=>e(i),t)}})(e=>{if(!(e.target instanceof HTMLElement||e.target instanceof Document))return;let t=e.target;"scrollTop"in t||(t=t.documentElement),ze==null||ze({xPath:Fn(t),x:t.scrollLeft,y:t.scrollTop,elementAttributes:{targetScrollWidth:t.scrollWidth,targetClientWidth:t.clientWidth,targetScrollHeight:t.scrollHeight,targetClientHeight:t.clientHeight}})},750),qn=ps("left_click"),$n=e=>{e.button===2&&Vn("right_click",e)},zn=e=>{window.Sprig&&(window.Sprig.pointerDownTarget=e.target)},gs=(e,t)=>{$e||(O=e,ze=t,window.addEventListener("click",qn,z),window.addEventListener("pointerdown",zn,z),window.addEventListener("mousedown",$n,z),window.addEventListener("keydown",Wn,z),window.addEventListener("scroll",jn,z),$e=!0,ws(),fs())},ms=()=>{$e&&(window.removeEventListener("click",qn,z),window.removeEventListener("pointerdown",zn,z),window.removeEventListener("mousedown",$n,z),window.removeEventListener("keydown",Wn,z),window.removeEventListener("scroll",jn,z),$e=!1)},ys=3e4,S={isRecording:!1,scrollEventUuids:{},stopRecording:()=>{}},Kn=()=>window.indexedDB&&window.IDBKeyRange&&window.CompressionStream,hs=.5,vs=async()=>{var e;if(!Kn())return!0;if((e=window.navigator.storage)!=null&&e.estimate)try{const{quota:t=0,usage:n=0}=await window.navigator.storage.estimate(),i=(t-n)/1024**3;return p.info("Storage",{availableGb:i}),i{const e=I.getItem("sprig.sessionId");if(e)return p.info("SessionIDFound",{savedSessionId:e}),I.removeItem("sprig.sessionId"),e;const t=le();return p.info("GeneratedSessionID",{uuid:t}),t})(),kt=()=>{I.setItem("sprig.disableReplayRecording","disabled")},K=()=>!!I.getItem("sprig.disableReplayRecording");window.addEventListener("beforeunload",()=>{p.info("BeforeUnload",{sessionId:C}),I.setItem("sprig.sessionId",C)});const bs=()=>K()?p.debug("ReplayDisabled-PendingHeatmaps"):P(async()=>{const t=(await v.getPendingCaptures({isHeatmap:!0})).map(n=>({eventId:n.captureParams.eventId,uuid:n.uuid})).filter(({eventId:n})=>!sn(n)).map(({uuid:n})=>n);return p.info("PendingHeatmapsToComplete",{count:t.length}),t.length&&(await v.markPendingHeatmapsReady(t),p.info("MarkedPendingHeatmapsReady")),t.length},"Error marking pending heatmaps ready"),Ls=e=>{Date.now()-e>=ys&&P(()=>v.markPendingHeatmapsReady(),"Error in heatmap inactivity")},ae=(e,t)=>{var n,i;if(!(K()||!S.isRecording))try{(i=(n=window.rrwebRecord)==null?void 0:n.addCustomEvent)==null||i.call(n,e,t)}catch(r){Ke("Error recording custom event",r)}},Ss=e=>{e.description&&(e.description=Et(e.description)),ae("Sprig_PageView",e)},Us=e=>{ae("Sprig_TrackEvent",e)},Is=e=>{ae("Sprig_ShowSurvey",e)},Es=e=>{ae("Sprig_SubmitSurvey",e)},ks=async e=>{const{x:t,xPath:n,y:i}=e,r=S.scrollEventUuids[n];if(r)return P(async()=>{var a,d,l,u;const s=await v.openDB(),o=await s.get("events",r);if(o!=null&&o.event){const c=JSON.parse(o.event),y=t>((d=(a=c.data)==null?void 0:a.payload)==null?void 0:d.x),w=i>((u=(l=c.data)==null?void 0:l.payload)==null?void 0:u.y);if(!(y||w))return null;y&&(c.data.payload.x=t),w&&(c.data.payload.y=i),c.data.payload.elementAttributes=e.elementAttributes,o.event=JSON.stringify(c),await s.put("events",o)}else ae("Sprig_Scroll",e)},"Error updating scroll event");ae("Sprig_Scroll",e)},_s=()=>S.isRecording,Gn=()=>{S.stopRecording&&(S.stopRecording(),S.stopRecording=void 0),S.isRecording=!1,["cleanupInterval","inactivityInterval","pendingCheckInterval"].forEach(e=>{S[e]&&(clearInterval(S[e]),S[e]=void 0)}),ms(),Zi()},Rs=["did not allow mutations","called in an invalid security context"],Ds=e=>{if(!e)return!0;for(const t of Rs)if(e.toLowerCase().includes(t))return!1;return!0},Cs=(e,t,{reportError:n=!0,extraInfo:i={}})=>{if(!(K()||!(t instanceof Error))){if(kt(),t.name==="VersionError"){p.error("VersionErr",{message:e}),v.deleteDB();return}Ds(t==null?void 0:t.message)&&(n&&window.UserLeap.reportError(e,t,i),v.clearAll())}},Ke=(e,t,{reportError:n}={reportError:!0})=>{Gn(),p.error("ReplayErr",{code:t.code,name:t.name}),Cs(e,t,{reportError:n})},P=async(e,t)=>{try{return await e()}catch(n){Ke(t,n)}},Yn=()=>{S.isRecording&&(P(()=>{var e,t;return(t=(e=window.rrwebRecord)==null?void 0:e.takeFullSnapshot)==null?void 0:t.call(e,!0)},"Error recording full snapshot"),Xi())},xs=async({surveyId:e,responseGroupUuid:t,eventDigest:n,headers:i})=>{if(!e||!t)return!1;const r=window.UserLeap._API_URL,s=await Nn({surveyId:e,responseGroupUuid:t,eventDigest:n,apiUrl:r,headers:i},!0);return!(s!=null&&s.error)},Jn=30,As=1;(async()=>{Kn()&&Promise.allSettled([Lt("replayStorage"),Lt("sprig.replay")])})();class Ts{openDB(){return $i("sprigReplay",As,{upgrade:(t,n,i)=>{if(i===0&&I.setItem("sprig.pendingCount","0"),!t.objectStoreNames.contains("events")){const r=t.createObjectStore("events",{keyPath:"uuid"});r.createIndex("sessionId","sessionId"),r.createIndex("timestamp","timestamp"),r.createIndex("[sessionId+timestamp]",["sessionId","timestamp"])}if(!t.objectStoreNames.contains("chunkUploads")){const r=t.createObjectStore("chunkUploads",{keyPath:"uuid"});r.createIndex("sessionId","sessionId"),r.createIndex("timestamp","timestamp"),r.createIndex("[sessionId+status]",["sessionId","status"]),r.createIndex("[uploadId+status]",["uploadId","status"]),r.createIndex("[sessionId+status+uploadId]",["sessionId","status","uploadId"])}if(!t.objectStoreNames.contains("pendingCaptures")){const r=t.createObjectStore("pendingCaptures",{keyPath:"uuid"});r.createIndex("sessionId","sessionId"),r.createIndex("timestamp","timestamp"),r.createIndex("[sessionId+targetTimestamp]",["sessionId","targetTimestamp"])}}})}async deleteDB(){try{await Lt("sprigReplay")}catch{}}async bulkAdd(t,n){const i=(await this.openDB()).transaction(t,"readwrite");return Promise.all([...n.map(r=>i.store.add(r)),i.done])}async clearAll(){const t=(await this.openDB()).transaction(["events","chunkUploads","pendingCaptures"],"readwrite");return Promise.all([t.objectStore("events").clear(),t.objectStore("chunkUploads").clear(),t.objectStore("pendingCaptures").clear()])}async deleteBySessionId(t,n){const i=IDBKeyRange.only(n),r=(await this.openDB()).transaction(t,"readwrite"),s=r.store.index("sessionId");for await(const o of s.iterate(i))await o.delete();await r.done}async updatePartial(t,n,i){const s=(await this.openDB()).transaction(t,"readwrite"),o=await s.store.get(n);o&&await s.store.put({...o,...i}),await s.done}async deleteRowsBefore(t,n,i=()=>!0){const r=IDBKeyRange.upperBound(n,!0),s=(await this.openDB()).transaction(t,"readwrite"),o=s.store.index("timestamp");for await(const a of o.iterate(r))i(a.value)&&await a.delete();await s.done}async getEventsBetween(t,n=Date.now()){if(t>=n)return Promise.resolve([]);const i=IDBKeyRange.bound([C,t],[C,n],!1,!0);return(await this.openDB()).getAllFromIndex("events","[sessionId+timestamp]",i)}async updateEventsExpiredAt(t,n,i=Jn){const r=new Date,s=r.setMinutes(r.getMinutes()+(i??Jn)),o=(await this.openDB()).transaction("events","readwrite"),a=o.store.index("[sessionId+timestamp]"),d=IDBKeyRange.bound([C,t],[C,n],!1,!0);for await(const l of a.iterate(d))await l.update({...l.value,expiredAt:s});await o.done}async deleteChunkUploads(t,n){const i=IDBKeyRange.only([n,t]),r=(await this.openDB()).transaction("chunkUploads","readwrite");let o=await r.store.index("[uploadId+status]").openCursor(i);for(;o;)o.delete(),o=await o.continue();await r.done}async getChunkUploadsByStatus({sessionId:t,status:n,uploadId:i}){const s=(await this.openDB()).transaction("chunkUploads","readonly"),o=i?s.store.index("[uploadId+status]"):s.store.index("[sessionId+status]"),a=i?IDBKeyRange.only([i,n]):IDBKeyRange.only([t,n]);return o.getAll(a)}async getPendingCaptures(t={}){return(await(await this.openDB()).getAllFromIndex("pendingCaptures","sessionId",C)).filter(r=>!t.beforePresent||r.targetTimestamp!t.isBeforeType||r.captureParams.replayParams.replayDurationType==="before").filter(r=>!t.isHeatmap||(r.captureParams.isHeatmap??!1))}async markPendingCaptureToCanUpload(t){const n=(await this.openDB()).transaction("pendingCaptures","readwrite"),i=n.store.index("sessionId");for await(const r of i.iterate(C)){const s=r.value;s.captureParams.responseGroupId===t&&await r.update({...s,canUpload:!0})}await n.done}async markPendingHeatmapsReady(t){if(parseInt(I.getItem("sprig.pendingCount")??"0")===0)return null;const i=Date.now(),r=(await this.openDB()).transaction("pendingCaptures","readwrite"),s=r.store.index("sessionId");for await(const o of s.iterate(C)){const a=o.value;a.captureParams.isHeatmap&&(!t||t.includes(a.uuid))&&await o.update({...a,targetTimestamp:i,captureParams:{...a.captureParams,triggerTimestamp:i,replayParams:{...a.captureParams.replayParams,replayDurationSeconds:Math.floor((i-a.timestamp)/1e3)}}})}await r.done}}const v=new Ts,Os=35*1e3,X=[];let de=[],pe=!1,ke,Qn,we=0,Ge=!1,Xn=!1,_t=[],Rt=!1,Ye,Zn,Je,er;const fe=()=>Ge&&!pe&&Date.now()<=Ye,Ps=({apiUrl:e,config:t,triggerSnapshot:n,forceInit:i=!1})=>{if(!(Ge&&!i)){if(!I.isStorageAvailable){pe=!0;return}de=[],_t.splice(0),X.splice(0),we=0,Je=n,Qn=e,ke={responseGroupUuid:t.responseGroupUuid,surveyId:t.surveyId,userAgent:t.userAgent,sdkVersion:t.sdkVersion},Zn=t.maxDurationSeconds,Fs(),Ge||(er=window.setInterval(Ns,500)),Ge=!0}},Ms=[Q.Drag,Q.Input,Q.MediaInteraction,Q.MouseInteraction,Q.MouseMove,Q.Scroll,Q.Selection,Q.TouchMove],Bs=e=>e.type===ne.Custom||e.type===ne.IncrementalSnapshot&&Ms.includes(e.data.source),Dt=e=>e.some(Bs),Ns=async()=>{if(!fe()){window.clearInterval(er);return}if(tr(),!Dt(X))return;const e=X[0].timestamp;Date.now()-e>Os&&(Je==null||Je())},tr=async()=>{if(de.length||Rt)return;Rt=!0;const e=await js();if(!e){pe=!0;return}_t.splice(0,e.length).forEach(n=>n(e.shift())),e.forEach(n=>de.push(n)),Rt=!1},Fs=()=>{const e=I.getItem("sprig.alwayson.info");if(e){p.info("Read stored session state",e);const t=JSON.parse(e);pe=t.disabled,ke=t.metadata,de=t.uploadUrls,we=t.currentIndex,Ye=t.expirationTimestamp,t.pendingEventTimestamp&&(p.info(`Uploading with pending timestamp: ${t.pendingEventTimestamp}`),Hs(t.pendingEventTimestamp))}else Ye=Zn*1e3+Date.now()},Hs=async e=>{const t=Date.now(),i=(await v.getEventsBetween(e,t)).map(s=>JSON.parse(s.event));if(!Dt(i))return;sr(i);const r=await ir();r&&await rr(r,i)},Vs=()=>{let e;X.length&&(e=X[0].timestamp);const t={disabled:pe,metadata:ke,uploadUrls:de,currentIndex:we,pendingEventTimestamp:e,expirationTimestamp:Ye};p.info("Storing session state on unload",t),I.setItem("sprig.alwayson.info",JSON.stringify(t))},Ws=async e=>{const t=new TextEncoder,n=new CompressionStream("gzip"),i=n.writable.getWriter(),r=t.encode(JSON.stringify(e));return i.write(r),i.close(),new Uint8Array(await new Response(n.readable).arrayBuffer())},nr=async(e,t)=>{try{const n=await e();if(!n.ok)throw new Error(`Error ${t}`);return n}catch{pe=!0}},rr=async(e,t)=>{if(!fe()||!e)return;const n=await Ws(t);p.info("Uploading always-on events with presigned url"),await nr(()=>Y(e,{body:n,method:"PUT"}),"uploading always-on with presigned url")},js=async()=>{if(!fe())return;const{surveyId:e,responseGroupUuid:t}=ke,n={responseGroupUuid:t,surveyId:e,index:we+1};p.info("Fetching always-on upload urls",n);const i=await nr(()=>Y(`${Qn}/sdk/1/replayUrls`,{method:"POST",body:JSON.stringify(n),headers:N(window.UserLeap)}),"fetching always-on signed urls");if(!i)return;const r=i.json.signedUrls;return p.info("Fetched more always-on upload urls",{body:n,urls:r}),r},ir=async()=>{if(de.length)return de.shift();const e=new Promise(t=>{_t.push(t)});return tr(),e},qs=async()=>{const e=X.splice(0);if(!Dt(e))return;p.info("Capturing always-on event array to upload"),sr(e);const t=await ir();t&&await rr(t,e)},sr=e=>{var r,s,o;const t=e.length?e[e.length-1].timestamp:Date.now(),n=we,i=((s=(r=window.UserLeap)==null?void 0:r.config)==null?void 0:s.customMetadata)??((o=window.__cfg)==null?void 0:o.customMetadata);we++,e.push({timestamp:t,type:ne.Custom,data:{tag:"Sprig_Meta",payload:{...ke,index:n,visitorId:window.UserLeap.visitorId??"",timestamp:t,customMetadata:i}}})},$s=async()=>{Xn=!0,fe()&&(p.info("Always On handle page unload"),Vs())},zs=(e,t)=>{!fe()||Xn||!e&&!X.length||(e&&X.length&&qs(),X.push(t))};window.addEventListener("beforeunload",$s);const or=async(e,t)=>{const n=performance.now();let i;try{i=await e()}finally{const r=performance.now()-n;let s=Se[t];s||(s=$(t)),s.report(r/1e3)}return i},ar=(e,t)=>{const n=performance.now();try{e()}finally{const i=performance.now()-n;let r=Se[t];r||(r=$(t)),r.report(i/1e3)}};let dr=5e3,Ct=6e4,xt=0;const Ks=5,At=30,Qe=At+Ks;let ie,Tt=!1,Ot=[];const Gs=async({maxReplayDurationSeconds:e,maxInflightRequests:t=2,replaySettings:n,teardownAfter:i=!1,apiUrl:r,alwaysOnConfig:s})=>{if(s&&Ps({apiUrl:r,config:s,triggerSnapshot:()=>{Yn()}}),ie=I.getItem("sprig.pendingCount"),S.isRecording)return;if(i&&I.setItem("sprig.teardownAfterCapture","true"),K())return p.debug("ReplayDisabled");if(await vs())return p.debug("IDBNotSupported"),kt();try{const d=await v.openDB();p.info("DBVersion",{version:d.version})}catch(d){return p.error("ReplayOpenErr",{name:d.name}),d.name==="VersionError"&&v.deleteDB(),kt()}P(async()=>{await Mt(!0)},"Error uploading ready pending captures");const o=fe()?At:0,a=Math.max(e??0,o);if(!a)return p.debug("MissingDuration");p.debug("ReplayInit"),await P(async()=>{n!=null&&n.minDuration&&(dr=n.minDuration),n!=null&&n.batchDuration&&(Ct=n.batchDuration),ts(t),no(),Xs(a+Qe,30*60,a+Qe),Zs();const d=window.UserLeap.replayLibraryURL??"https://cdn.sprig.com/dependencies/record-2.0.0-alpha.17.min.js";if(!window.rrwebRecord){const{record:w}=await import(d);window.rrwebRecord=w}const l=window.rrwebRecord;if(!l)return p.error("RecordScriptFailed");let u=!0,c=0;const y={checkoutEveryNms:At*1e3,sampling:{input:"last",scroll:250,media:800},...n};S.stopRecording=l({emit:(w,g)=>{if(w.type===ne.Custom&&(xt=Date.now()),K())return;if(g&&w.type===ne.Meta)c=performance.now();else if(g&&c&&w.type===ne.FullSnapshot){const x=performance.now()-c;yn("sdk_replay_snapshot_seconds",x/1e3)}const E=u||!!g&&w.type===ne.Meta;u=!1,zs(E,w),Ys({uuid:le(),event:JSON.stringify(w),isValidStart:E,timestamp:Date.now()})},...y}),S.isRecording=!!S.stopRecording,S.isRecording&&(Qi(y,d),m.on("survey.complete",w=>{Es({id:w,userAgent:window.navigator.userAgent})}),gs(ae,ks))},"Error initializing replay")},Ys=e=>{var t,n,i,r;if((t=e.event)!=null&&t.includes("Sprig_Scroll")){const s=(r=(i=(n=JSON.parse(e.event))==null?void 0:n.data)==null?void 0:i.payload)==null?void 0:r.xPath;if(!s)return;S.scrollEventUuids[s]=e.uuid}Ot.push(e),Tt||Qs()},Js=async e=>{const t=e.map(n=>({...n,sessionId:n.sessionId??C}));if(t.length!==0)return P(()=>v.bulkAdd("events",t),"Error storing replay events")},Qs=()=>{Tt=!0,setTimeout(async()=>{if(K())return;const e=Ot;Ot=[],Tt=!1,ar(async()=>{await Js(e)},"sdk_replay_add_event_batch_seconds")},500)},Xs=(e,t,n)=>{S.cleanupInterval=window.setInterval(()=>{const i=Date.now();or(()=>P(async()=>{K()||await Promise.all([v.deleteRowsBefore("events",i-e*1e3,r=>r.expiredAt===void 0||r.expiredAt!r.canUpload)])},"Error deleting table rows"),"sdk_replay_cleanup_seconds"),p.debug("CleanupComplete")},3e4)},Zs=()=>{S.pendingCheckInterval=window.setInterval(async()=>{P(async()=>{await Mt()},"Error initiating pending captures")},5e3)};let Pt=!1;const Mt=async(e=!1)=>{if(!Pt)try{Pt=!0;const t=parseInt(ie??"0");if(t===0)return;const n=await v.getPendingCaptures({beforePresent:!0,isBeforeType:e}),i=await v.openDB();await Promise.all(n.map(async r=>(await i.delete("pendingCaptures",r.uuid),pr(r.captureParams,r.canUpload)))),ie=(t-n.length).toString(),I.setItem("sprig.pendingCount",ie)}finally{Pt=!1}},eo=async(e,t,n,i,r)=>{const s=Math.min(e+r,n),o=await or(()=>v.getEventsBetween(e,s),"sdk_replay_get_events_between_seconds");if(!(o!=null&&o.length))return p.debug("NoEventsFound"),{validStartFound:i,events:[]};if(!i){p.debug("ValidStartSearch");let a=-1;return o==null||o.forEach((d,l)=>{if(!d.isValidStart)return;const u=d.timestamp<=t;(a<0||u)&&(a=l)}),a<0?(p.debug("ValidStartNotFound"),{validStartFound:i,events:[]}):{validStartFound:!0,events:o==null?void 0:o.slice(a)}}return{validStartFound:i,events:o}},to=(e,t,n)=>{const i=e.length,r=t*1024*1024,s=Math.ceil(i/n),o=Math.max(r,s),a=[];let d=0;for(;dPromise.all(e.map(async t=>{const n=await ns(t);return await v.updatePartial("chunkUploads",t.uuid,{data:null,etag:n,status:"UploadComplete"}),t.uploadId})),lr=async e=>{const t=await v.getChunkUploadsByStatus({status:"UploadComplete",uploadId:e});if(!(t!=null&&t.length)){p.info("NoChunksForUpload",{uploadId:e});return}const n=t.reduce((s,o)=>(s.find(a=>a.chunkIndex===o.chunkIndex)||s.push(o),s),[]);n.sort((s,o)=>s.chunkIndex-o.chunkIndex);const i=n.map(s=>({ETag:s.etag,PartNumber:s.chunkIndex})).filter(s=>s.ETag!==null),r=n[0];await Nn({apiUrl:r.apiUrl,surveyId:r.surveyId,uploadId:e,responseGroupUuid:r.responseGroupId,etags:i,headers:r.completeUploadHeaders,replayDuration:r.replayDuration}),await v.deleteChunkUploads("UploadComplete",e)},no=()=>{P(async()=>{const e=await v.getChunkUploadsByStatus({sessionId:C,status:"ReadyForUpload"});if(!(e!=null&&e.length))return;const t=await cr(e);t!=null&&t.length&&await Promise.all(t.map(n=>{if(n)return lr(n)}))},"Error uploading unfinished chunks")},ro=async(e,t)=>{await cr(t),await Promise.all(e.map(n=>lr(n)))},io=async(e,t)=>{const n=new TextEncoder;let i=null;const r=new CompressionStream("gzip"),s=r.writable.getWriter();let o=!1,a=!1,[d,l]=[0,0];const u=e-Qe*1e3;let c=[];for(let w=u;wM.event);g.push(`{"timestamp":${t}}`);const E=`${o?",":"["}${g}`,x=n.encode(E);ar(()=>{s.write(x)},"sdk_replay_compression_seconds"),o=!0}if(l-d{const n=t??Date.now(),i=n-e;return io(i,n)},ur=async e=>{const{surveyId:t,responseGroupId:n,visitorId:i,apiUrl:r,completeUploadHeaders:s,replayParams:o,triggerTimestamp:a}=e,d=await so(o.replayDurationSeconds*1e3,a);if(!(d!=null&&d.length)){p.info("FileDataEmpty",{surveyId:t});return}const l=to(d,o.minimumChunkSizeMb,o.signedUrls.length),u=await Promise.all(l.map(async(c,y)=>{const w=le(),g={apiUrl:r,chunkIndex:y+1,completeUploadHeaders:s,etag:null,responseGroupId:n,status:"ReadyForUpload",surveyId:t,timestamp:a,totalChunks:l.length,data:c,uploadId:o.uploadId,uploadUrl:o.signedUrls[y].url,uuid:w,visitorId:i};return await(await v.openDB()).add("chunkUploads",{...g,sessionId:g.sessionId??C}),g}));await ro([o.uploadId],u)},pr=async(e,t)=>{if(K())return p.debug("ReplayDisabled-ScheduleOrCapture");const{isHeatmap:n,isStandalone:i,replayParams:r,triggerTimestamp:s,responseGroupId:o}=e,a=async()=>{setTimeout(()=>m.removeListener(f.QuestionAnswered,a),0),P(async()=>{r.replayDurationType==="before"?await ur(e):await v.markPendingCaptureToCanUpload(o)},"Error in schedule/capture callback")};P(async()=>{if(r.replayDurationType==="after"||r.replayDurationType==="beforeAndAfter"){!i&&!n&&m.on(f.QuestionAnswered,a),await fr(e);return}if(i||n||t)await ur(e),n&&oo();else{const l=Qe+r.replayDurationSeconds,u=s-l*1e3,c=s;await v.updateEventsExpiredAt(u,c,r.expirationTimeLimitMinutes),m.on(f.QuestionAnswered,a)}},"Error in scheduling/capturing replay")},oo=async()=>{parseInt(ie??"0")||I.removeItem("sprig.isCapturingHeatmap"),I.getItem("sprig.teardownAfterCapture")&&(Gn(),wr(),I.removeItem("sprig.teardownAfterCapture"))},wr=async()=>K()?p.debug("ReplayDisabled-ClearData"):Promise.all([v.deleteBySessionId("events",C),v.deleteBySessionId("pendingCaptures",C)]).catch(e=>{Ke("Error clearing user replay data",e)}),fr=async e=>{if(K())return;const{isHeatmap:t,surveyId:n}=e,i=await v.getPendingCaptures(),r=i==null?void 0:i.filter(d=>d.captureParams.surveyId===n);if(r!=null&&r.length){p.info("PendingCaptureExists",{surveyId:n});return}t&&(Yn(),I.setItem("sprig.isCapturingHeatmap","true"),xt=Date.now(),S.inactivityInterval||(S.inactivityInterval=window.setInterval(()=>{Ls(xt)},1e3)));const s={...e,replayParams:{...e.replayParams}};e.replayParams.replayDurationType==="beforeAndAfter"&&(s.replayParams.replayDurationSeconds*=2),s.replayParams.replayDurationType="before";const o=e.triggerTimestamp+e.replayParams.replayDurationSeconds*1e3;s.triggerTimestamp=o,ie=(parseInt(ie??"0")+1).toString(),I.setItem("sprig.pendingCount",ie),await(await v.openDB()).add("pendingCaptures",{canUpload:!1,captureParams:s,sessionId:C,targetTimestamp:o,timestamp:Date.now(),uuid:le()})};Tr(Object.freeze(Object.defineProperty({__proto__:null,RecordEvent:Us,RecordPageView:Ss,RecordSurveyShown:Is,_completeSessionReplay:xs,checkPendingHeatmapsUrl:bs,clearUserReplayData:wr,disableRecording:Ke,initializeReplay:Gs,isReplayRecording:_s,scheduleCapture:fr,scheduleOrCaptureReplay:pr,tryReplayAction:P,uploadReadyPendingCaptures:Mt},Symbol.toStringTag,{value:"Module"})));const ao="sprig-web-view-sdk";let gr;gr={path:`https://cdn.sprig.com/${ao}-v2.33.3.js`},Ni(gr)})(); //# debugId=3ee33bc3-6790-5799-9ea2-95e23e36e707