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