@sprig-technologies/sprig-browser 2.32.0 → 2.32.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/replay.js CHANGED
@@ -1 +1,651 @@
1
- var Be=Object.defineProperty,Ue=(e,t,n)=>t in e?Be(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,z=(e,t,n)=>(Ue(e,typeof t!="symbol"?t+"":t,n),n);import{b as l,s as J,a as w,v as R,c as Te,P as Q,r as X,d as _e,e as P,S as A,f as Ae}from"./metricsReporter-pb5Px0rg.js";var C=(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))(C||{});class Ne{constructor(t){z(this,"awaitingResolvers",[]),z(this,"activeCount",0),this.capacity=t}async acquire(){if(this.activeCount<this.capacity){this.activeCount++;return}return new Promise(t=>{this.awaitingResolvers.push(t)})}release(){const t=this.awaitingResolvers.shift();t&&this.activeCount<=this.capacity?t():this.activeCount--}async execute(t){try{return await this.acquire(),await t()}finally{this.release()}}setLimit(t){this.capacity=t}}const Y=new Ne(2),Le=e=>Y.setLimit(e),Oe=async e=>Y.execute(async()=>{var t;l.info("UploadChunkStart",{chunkIndex:e.chunkIndex,surveyId:e.surveyId});const n=await J(e.uploadUrl,{body:e.data,method:"PUT"});l.http("UploadChunkEnd",{url:e.uploadUrl,method:"PUT",status_code:n.status,reason:n.statusText??"OK",chunkIndex:e.chunkIndex,surveyId:e.surveyId});const a=(t=n.headers)==null?void 0:t.get("ETag");if(!a)throw new Error(`Upload response did not include etag for upload ${e.uploadId}, part ${e.chunkIndex}`);return a}),Z=async({apiUrl:e,surveyId:t,uploadId:n,etags:a,headers:r,responseGroupUuid:o,replayDuration:s,eventDigest:i},d=!1)=>{var u;if(!d&&!n&&!a){l.error("UploadErr",{isMobile:d,uploadId:n,etags:a});return}l.info("MarkUploadComplete",{surveyId:t});const g=await J(`${e}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:a,uploadId:n,responseGroupUuid:o,surveyId:t,replayDuration:s,eventDigest:i,userAgent:(u=window?.navigator)==null?void 0:u.userAgent}),headers:r,shouldRetryRequest:!0});return l.info("MarkUploadDone",{surveyId:t}),g},N=(e,t)=>t.some(n=>e instanceof n);let ee,te;function Me(){return ee||(ee=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Fe(){return te||(te=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const L=new WeakMap,O=new WeakMap,x=new WeakMap;function He(e){const t=new Promise((n,a)=>{const r=()=>{n(D(e.result))},o=()=>{a(e.error)};e.onsuccess=r,e.onerror=o});return x.set(t,e),t}function je(e){if(L.has(e))return;const t=new Promise((n,a)=>{const r=()=>{n()},o=()=>{a(e.error||new DOMException("AbortError","AbortError"))};e.oncomplete=r,e.onerror=o,e.onabort=o});L.set(e,t)}let M={get(e,t,n){if(e instanceof IDBTransaction){if(t==="done")return L.get(e);if(t==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return D(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 ne(e){M=e(M)}function Ve(e){return Fe().includes(e)?function(...t){return e.apply(F(this),t),D(this.request)}:function(...t){return D(e.apply(F(this),t))}}function Ke(e){return typeof e=="function"?Ve(e):(e instanceof IDBTransaction&&je(e),N(e,Me())?new Proxy(e,M):e)}function D(e){if(e instanceof IDBRequest)return He(e);if(O.has(e))return O.get(e);const t=Ke(e);return t!==e&&(O.set(e,t),x.set(t,e)),t}const F=e=>x.get(e);function Ge(e,t,{blocked:n,upgrade:a,blocking:r,terminated:o}={}){const s=indexedDB.open(e,t),i=D(s);return a&&(s.onupgradeneeded=d=>{a(D(s.result),d.oldVersion,d.newVersion,D(s.transaction),d)}),n&&(s.onblocked=d=>n(d.oldVersion,d.newVersion,d)),i.then(d=>{o&&(d.onclose=()=>o()),r&&(d.onversionchange=u=>r(u.oldVersion,u.newVersion,u))}).catch(()=>{}),i}function H(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&(n.onblocked=a=>t(a.oldVersion,a)),D(n).then(()=>{})}const We=["get","getKey","getAll","getAllKeys","count"],$e=["put","add","delete","clear"],j=new Map;function ae(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(j.get(t))return j.get(t);const n=t.replace(/FromIndex$/,""),a=t!==n,r=$e.includes(n);if(!(n in(a?IDBIndex:IDBObjectStore).prototype)||!(r||We.includes(n)))return;const o=async function(s,...i){const d=this.transaction(s,r?"readwrite":"readonly");let u=d.store;return a&&(u=u.index(i.shift())),(await Promise.all([u[n](...i),r&&d.done]))[0]};return j.set(t,o),o}ne(e=>({...e,get:(t,n,a)=>ae(t,n)||e.get(t,n,a),has:(t,n)=>!!ae(t,n)||e.has(t,n)}));const qe=["continue","continuePrimaryKey","advance"],re={},V=new WeakMap,oe=new WeakMap,ze={get(e,t){if(!qe.includes(t))return e[t];let n=re[t];return n||(n=re[t]=function(...a){V.set(this,oe.get(this)[t](...a))}),n}};async function*Je(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;const n=new Proxy(t,ze);for(oe.set(n,t),x.set(n,F(t));t;)yield n,t=await(V.get(n)||t.continue()),V.delete(n)}function se(e,t){return t===Symbol.asyncIterator&&N(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&N(e,[IDBIndex,IDBObjectStore])}ne(e=>({...e,get(t,n,a){return se(t,n)?Je:e.get(t,n,a)},has(t,n){return se(t,n)||e.has(t,n)}}));const Qe=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},ie=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 a=t[t.length]={name:void 0,position:null};switch(n.nodeType){case Node.TEXT_NODE:a.name="text()";break;case Node.ATTRIBUTE_NODE:a.name="@"+n.nodeName;break;case Node.PROCESSING_INSTRUCTION_NODE:a.name="processing-instruction()";break;case Node.COMMENT_NODE:a.name="comment()";break;case Node.ELEMENT_NODE:a.name=n.nodeName;break}a.position=Qe(n)}return"/"+t.reverse().map(n=>n.position!==null?`/${n.name}[${n.position}]`:`/${n.name}`).join("")},b={capture:!0,passive:!0},Xe=["a","button","input","option","li","link"],Ye=["Escape","Enter","Backspace","F5","Tab"];let B=!1;const Ze=["label","type","role","title","placeholder","errormessage","valuetext","href"],de="aria-",et=e=>{if(!e.tagName)return"No tagName";const t=e.getAttribute("type");return t?`${t} ${e.tagName.toLowerCase()}`:e.tagName.toLowerCase()},le=e=>{var t;if(((t=e.tagName)==null?void 0:t.toLowerCase())==="html")return{element:"html"};const n=e.textContent,a=n?{text:n}:{};a.element=et(e);for(const r of e.attributes){let o=r.name;const s=r.value;o.startsWith(de)&&(o=o.substring(de.length)),Ze.includes(o)&&(a[o]=s)}return a},tt=e=>{var t;if(!e)return{};const n={...le(e)},a=e.parentElement;if(a&&Xe.includes((t=a.tagName)==null?void 0:t.toLowerCase())){const r=le(a);Object.assign(n,r)}return n},ue=(e,t)=>{var n;yt({x:t.x,y:t.y,type:e,elementAttributes:tt(t.target),windowHeight:window.innerHeight,windowWidth:window.innerWidth,...t.target instanceof HTMLElement?{rect:(n=t.target)==null?void 0:n.getBoundingClientRect(),xPath:ie(t.target)}:{}})},nt=e=>t=>ue(e,t),ce=e=>{Ye.includes(e.key)&&bt({key:e.key})},at=()=>{window.performance.getEntriesByType("navigation").map(e=>e.type).includes("reload")&&ht({url:window.location.href,currentPageTitle:document.title})},rt=()=>{window.performance.getEntriesByType("navigation").map(e=>e.type).includes("back_forward")&&Dt({curUrl:window.location.href,fromUrl:document.referrer,currentPageTitle:document.title})},ot=(e,t)=>{let n;return a=>{clearTimeout(n),n=window.setTimeout(()=>e(a),t)}},st=e=>{if(!(e.target instanceof HTMLElement||e.target instanceof Document))return;let t=e.target;"scrollTop"in t||(t=t.documentElement),St({xPath:ie(t),x:t.scrollLeft,y:t.scrollTop,elementAttributes:{targetScrollWidth:t.scrollWidth,targetClientWidth:t.clientWidth,targetScrollHeight:t.scrollHeight,targetClientHeight:t.clientHeight}})},pe=ot(st,750),ge=nt("left_click"),me=e=>{e.button===2&&ue("right_click",e)},it=()=>{B||(window.addEventListener("click",ge,b),window.addEventListener("mousedown",me,b),window.addEventListener("keydown",ce,b),window.addEventListener("scroll",pe,b),B=!0,at(),rt())},dt=()=>{B&&(window.removeEventListener("click",ge,b),window.removeEventListener("mousedown",me,b),window.removeEventListener("keydown",ce,b),window.removeEventListener("scroll",pe,b),B=!1)},lt=3e4,p={isRecording:!1,scrollEventUuids:{},stopRecording:()=>{}},ut=.5,ct=async()=>{var e;if(!window.indexedDB||!window.IDBKeyRange||!window.CompressionStream)return!0;if((e=window.navigator.storage)!=null&&e.estimate)try{const{quota:t=0,usage:n=0}=await window.navigator.storage.estimate(),a=(t-n)/1024**3;return l.info("Storage",{availableGb:a}),a<ut}catch{return!0}return!1},pt=()=>{const e=w.getItem("sprig.sessionId");if(e)return l.info("SessionIDFound",{savedSessionId:e}),w.removeItem("sprig.sessionId"),e;const t=R();return l.info("GeneratedSessionID",{uuid:t}),t},y=pt(),U=()=>{w.setItem("sprig.disableReplayRecording","disabled")},v=()=>!!w.getItem("sprig.disableReplayRecording");window.addEventListener("beforeunload",()=>{l.info("BeforeUnload",{sessionId:y}),w.setItem("sprig.sessionId",y)});const gt=()=>v()?l.debug("ReplayDisabled-PendingHeatmaps"):f(async()=>{const e=(await c.getPendingCaptures({isHeatmap:!0})).map(n=>({eventId:n.captureParams.eventId,uuid:n.uuid})),t=[];e.forEach(({eventId:n,uuid:a})=>{Te(n)||t.push(a)}),t.length&&await c.markPendingHeatmapsReady(t)},"Error marking pending heatmaps ready"),mt=e=>{Date.now()-e>=lt&&f(()=>c.markPendingHeatmapsReady(),"Error in heatmap inactivity")},K=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),I=(e,t)=>{var n,a;if(!(v()||!p.isRecording))try{(a=(n=window.rrwebRecord)==null?void 0:n.addCustomEvent)==null||a.call(n,e,t)}catch(r){T("Error recording custom event",r)}},wt=e=>{e.description&&(e.description=K(e.description)),I("Sprig_PageView",e)},yt=e=>{var t;(t=e?.elementAttributes)!=null&&t.text&&(e.elementAttributes.text=K(e.elementAttributes.text)),I("Sprig_Click",e)},ft=e=>{I("Sprig_TrackEvent",e)},vt=e=>{I("Sprig_ShowSurvey",e)},It=e=>{I("Sprig_SubmitSurvey",e)},ht=e=>{I("Sprig_Refresh",e)},Dt=e=>{e.currentPageTitle&&(e.currentPageTitle=K(e.currentPageTitle)),I("Sprig_BackForward",e)},bt=e=>{I("Sprig_Keystroke",e)},St=async e=>{const{x:t,xPath:n,y:a}=e,r=p.scrollEventUuids[n];if(r)return f(async()=>{var o,s,i,d;const u=await c.openDB(),g=await u.get("events",r);if(g!=null&&g.event){const m=JSON.parse(g.event),E=t>((s=(o=m.data)==null?void 0:o.payload)==null?void 0:s.x),h=a>((d=(i=m.data)==null?void 0:i.payload)==null?void 0:d.y);if(!(E||h))return null;E&&(m.data.payload.x=t),h&&(m.data.payload.y=a),m.data.payload.elementAttributes=e.elementAttributes,g.event=JSON.stringify(m),await u.put("events",g)}else I("Sprig_Scroll",e)},"Error updating scroll event");I("Sprig_Scroll",e)},Et=()=>p.isRecording,we=()=>{p.stopRecording&&(p.stopRecording(),p.stopRecording=void 0),p.isRecording=!1,["cleanupInterval","inactivityInterval","pendingCheckInterval"].forEach(e=>{p[e]&&(clearInterval(p[e]),p[e]=void 0)}),dt()},kt=["did not allow mutations","called in an invalid security context"],Ct=e=>{if(!e)return!0;for(const t of kt)if(e.toLowerCase().includes(t))return!1;return!0},Rt=(e,t,{reportError:n=!0,extraInfo:a={}})=>{if(!v()&&t instanceof Error){if(U(),t.name==="VersionError")return l.error("VersionErr",{message:e}),c.deleteDB();Ct(t?.message)&&(n&&window.UserLeap.reportError(e,t,a),c.clearAll())}},T=(e,t,{reportError:n}={reportError:!0})=>{we(),l.error("ReplayErr",{code:t.code,name:t.name}),Rt(e,t,{reportError:n})},f=async(e,t)=>{try{await e()}catch(n){T(t,n)}},Pt=()=>{p.isRecording&&f(()=>{var e,t;return(t=(e=window.rrwebRecord)==null?void 0:e.takeFullSnapshot)==null?void 0:t.call(e,!0)},"Error recording full snapshot")},xt=async({surveyId:e,responseGroupUuid:t,eventDigest:n,headers:a})=>{if(!e||!t)return!1;const r=window.UserLeap._API_URL,o=await Z({surveyId:e,responseGroupUuid:t,eventDigest:n,apiUrl:r,headers:a},!0);return!(o!=null&&o.error)},ye=30,Bt=1;H("replayStorage").catch(console.error),H("sprig.replay").catch(console.error);class Ut{openDB(){return Ge("sprigReplay",Bt,{upgrade:(t,n,a)=>{if(a===0&&w.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"])}}})}deleteDB(){return H("sprigReplay").catch(console.error)}async bulkAdd(t,n){const a=(await this.openDB()).transaction(t,"readwrite");return Promise.all([...n.map(r=>a.store.add(r)),a.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 a=IDBKeyRange.only(n),r=(await this.openDB()).transaction(t,"readwrite"),o=r.store.index("sessionId");for await(const s of o.iterate(a))await s.delete();await r.done}async updatePartial(t,n,a){const r=(await this.openDB()).transaction(t,"readwrite"),o=await r.store.get(n);o&&await r.store.put({...o,...a}),await r.done}async deleteRowsBefore(t,n,a=()=>!0){const r=IDBKeyRange.upperBound(n,!0),o=(await this.openDB()).transaction(t,"readwrite"),s=o.store.index("timestamp");for await(const i of s.iterate(r))a(i.value)&&await i.delete();await o.done}async getEventsBetween(t,n=Date.now()){if(t>=n)return Promise.resolve([]);const a=IDBKeyRange.bound([y,t],[y,n],!1,!0);return(await this.openDB()).getAllFromIndex("events","[sessionId+timestamp]",a)}async updateEventsExpiredAt(t,n,a=ye){const r=new Date,o=r.setMinutes(r.getMinutes()+(a??ye)),s=(await this.openDB()).transaction("events","readwrite"),i=s.store.index("[sessionId+timestamp]"),d=IDBKeyRange.bound([y,t],[y,n],!1,!0);for await(const u of i.iterate(d))await u.update({...u.value,expiredAt:o});await s.done}async deleteChunkUploads(t,n){const a=IDBKeyRange.only([n,t]),r=(await this.openDB()).transaction("chunkUploads","readwrite");let o=await r.store.index("[uploadId+status]").openCursor(a);for(;o;)o.delete(),o=await o.continue();await r.done}async getChunkUploadsByStatus({sessionId:t,status:n,uploadId:a}){const r=(await this.openDB()).transaction("chunkUploads","readonly"),o=a?r.store.index("[uploadId+status]"):r.store.index("[sessionId+status]"),s=a?IDBKeyRange.only([a,n]):IDBKeyRange.only([t,n]);return o.getAll(s)}async getPendingCaptures(t={}){return(await(await this.openDB()).getAllFromIndex("pendingCaptures","sessionId",y)).filter(n=>!t.beforePresent||n.targetTimestamp<Date.now()).filter(n=>!t.isHeatmap||(n.captureParams.isHeatmap??!1))}async markPendingCaptureToCanUpload(t){const n=(await this.openDB()).transaction("pendingCaptures","readwrite"),a=n.store.index("sessionId");for await(const r of a.iterate(y)){const o=r.value;o.captureParams.responseGroupId===t&&await r.update({...o,canUpload:!0})}await n.done}async markPendingHeatmapsReady(t){if(parseInt(w.getItem("sprig.pendingCount")??"0")===0)return null;const n=Date.now(),a=(await this.openDB()).transaction("pendingCaptures","readwrite"),r=a.store.index("sessionId");for await(const o of r.iterate(y)){const s=o.value;s.captureParams.isHeatmap&&(!t||t.includes(s.uuid))&&await o.update({...s,targetTimestamp:n,captureParams:{...s.captureParams,triggerTimestamp:n,replayParams:{...s.captureParams.replayParams,replayDurationSeconds:Math.floor((n-s.timestamp)/1e3)}}})}await a.done}}const c=new Ut,fe=async(e,t)=>{const n=performance.now();let a;try{a=await e()}finally{const r=performance.now()-n;let o=Q[t];o||(o=X(t)),o.report(r/1e3)}return a},ve=(e,t)=>{const n=performance.now();try{e()}finally{const a=performance.now()-n;let r=Q[t];r||(r=X(t)),r.report(a/1e3)}};var Tt={VITE_NPM_BUNDLE:"",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};let Ie=5e3,G=6e4,W=0;const _t=5,he=30,_=he+_t;let S,$=!1,q=[];const At=async({maxReplayDurationSeconds:e,maxInflightRequests:t=2,replaySettings:n,teardownAfter:a=!1})=>{if(S=w.getItem("sprig.pendingCount"),!p.isRecording){if(a&&w.setItem("sprig.teardownAfterCapture","true"),v())return l.debug("ReplayDisabled");if(await ct())return l.debug("IDBNotSupported"),U();try{const r=await c.openDB();l.info("DBVersion",{version:r.version})}catch(r){return l.error("ReplayOpenErr",{name:r.name}),r.name==="VersionError"&&c.deleteDB(),U()}if(!e)return l.debug("MissingDuration");l.debug("ReplayInit"),await f(async()=>{if(n!=null&&n.minDuration&&(Ie=n.minDuration),n!=null&&n.batchDuration&&(G=n.batchDuration),Le(t),Vt(),Mt(e+_,30*60,e+_),Ft(),!window.rrwebRecord)try{const{record:i}=await import(window.UserLeap.replayLibraryURL??`${Tt.VITE_CDN}/dependencies/record-2.0.0-alpha.17.min.js`);window.rrwebRecord=i}catch{return U(),l.error("LoadRecordFailed")}const r=window.rrwebRecord;if(!r)return l.error("RecordScriptFailed");let o=!0,s=0;p.stopRecording=r({checkoutEveryNms:he*1e3,sampling:{input:"last",scroll:250,media:800},emit:(i,d)=>{if(i.type===C.Custom&&(W=Date.now()),v())return;if(d&&i.type===C.Meta)s=performance.now();else if(d&&s&&i.type===C.FullSnapshot){const g=performance.now()-s;_e("sdk_replay_snapshot_seconds",g/1e3)}const u=o||!!d&&i.type===C.Meta;o=!1,Nt({uuid:R(),event:JSON.stringify(i),isValidStart:u,timestamp:Date.now()})},...n}),p.isRecording=!!p.stopRecording,p.isRecording&&(P.on("survey.complete",i=>{It({id:i,userAgent:window.navigator.userAgent})}),it())},"Error initializing replay")}},Nt=e=>{var t,n,a,r;if((t=e.event)!=null&&t.includes("Sprig_Scroll")){const o=(r=(a=(n=JSON.parse(e.event))==null?void 0:n.data)==null?void 0:a.payload)==null?void 0:r.xPath;if(!o)return;p.scrollEventUuids[o]=e.uuid}q.push(e),$||Ot()},Lt=async e=>{const t=e.map(n=>({...n,sessionId:n.sessionId??y}));if(t.length!==0)return f(()=>c.bulkAdd("events",t),"Error storing replay events")},Ot=()=>{$=!0,setTimeout(async()=>{if(v())return;const e=q;q=[],$=!1,ve(async()=>{await Lt(e)},"sdk_replay_add_event_batch_seconds")},500)},Mt=(e,t,n)=>{p.cleanupInterval=window.setInterval(()=>{const a=Date.now();fe(()=>f(async()=>{v()||await Promise.all([c.deleteRowsBefore("events",a-e*1e3,r=>r.expiredAt===void 0||r.expiredAt<a-e*1e3),c.deleteRowsBefore("chunkUploads",a-t*1e3),c.deleteRowsBefore("pendingCaptures",a-n*1e3,r=>!r.canUpload)])},"Error deleting table rows"),"sdk_replay_cleanup_seconds"),l.debug("CleanupComplete")},3e4)},Ft=()=>{p.pendingCheckInterval=window.setInterval(async()=>{f(async()=>{const e=parseInt(S??"0");if(e===0)return;const t=await c.getPendingCaptures({beforePresent:!0}),n=await c.openDB();await Promise.all(t.map(async a=>(await n.delete("pendingCaptures",a.uuid),Ee(a.captureParams,a.canUpload)))),S=(e-t.length).toString(),w.setItem("sprig.pendingCount",S)},"Error initiating pending captures")},5e3)},Ht=async(e,t,n,a,r)=>{const o=Math.min(e+r,n),s=await fe(()=>c.getEventsBetween(e,o),"sdk_replay_get_events_between_seconds");if(!(s!=null&&s.length))return l.debug("NoEventsFound"),{validStartFound:a,events:[]};if(!a){l.debug("ValidStartSearch");let i=-1;return s?.forEach((d,u)=>{if(!d.isValidStart)return;const g=d.timestamp<=t;(i<0||g)&&(i=u)}),i<0?(l.debug("ValidStartNotFound"),{validStartFound:a,events:[]}):{validStartFound:!0,events:s?.slice(i)}}return{validStartFound:a,events:s}},jt=(e,t,n)=>{const a=e.length,r=t*1024*1024,o=Math.ceil(a/n),s=Math.max(r,o),i=[];let d=0;for(;d<a;)i.push(e.slice(d,d+s)),d+=s;return i},De=e=>Promise.all(e.map(async t=>{const n=await Oe(t);return await c.updatePartial("chunkUploads",t.uuid,{data:null,etag:n,status:"UploadComplete"}),t.uploadId})),be=async e=>{const t=await c.getChunkUploadsByStatus({status:"UploadComplete",uploadId:e});if(!(t!=null&&t.length)){l.info("NoChunksForUpload",{uploadId:e});return}const n=t.reduce((o,s)=>(o.find(i=>i.chunkIndex===s.chunkIndex)||o.push(s),o),[]);n.sort((o,s)=>o.chunkIndex-s.chunkIndex);const a=n.map(o=>({ETag:o.etag,PartNumber:o.chunkIndex})).filter(o=>o.ETag!==null),r=n[0];await Z({apiUrl:r.apiUrl,surveyId:r.surveyId,uploadId:e,responseGroupUuid:r.responseGroupId,etags:a,headers:r.completeUploadHeaders,replayDuration:r.replayDuration}),await c.deleteChunkUploads("UploadComplete",e)},Vt=()=>{f(async()=>{const e=await c.getChunkUploadsByStatus({sessionId:y,status:"ReadyForUpload"});if(!(e!=null&&e.length))return;const t=await De(e);t!=null&&t.length&&await Promise.all(t.map(n=>{if(n)return be(n)}))},"Error uploading unfinished chunks")},Kt=async(e,t)=>{await De(t),await Promise.all(e.map(n=>be(n)))},Gt=async(e,t)=>{const n=new TextEncoder;let a=null;const r=new CompressionStream("gzip"),o=r.writable.getWriter();let s=!1,i=!1,[d,u]=[0,0];const g=e-_*1e3;let m=[];for(let h=g;h<t;h+=G){if({validStartFound:i,events:m}=await Ht(h,e,t,i,G),!(m!=null&&m.length)){l.debug("NoEventsFound");continue}d===0&&(d=m[0].timestamp),u=m[m.length-1].timestamp;const k=m.map(xe=>xe.event);k.push(`{"timestamp":${t}}`);const Re=`${s?",":"["}${k}`,Pe=n.encode(Re);ve(()=>{o.write(Pe)},"sdk_replay_compression_seconds"),s=!0}if(u-d<Ie)return l.debug("ReplayTooShort"),null;const E=n.encode("]");return o.write(E),o.close(),a=new Uint8Array(await new Response(r.readable).arrayBuffer()),a},Wt=async(e,t)=>{const n=t??Date.now(),a=n-e;return Gt(a,n)},Se=async e=>{const{surveyId:t,responseGroupId:n,visitorId:a,apiUrl:r,completeUploadHeaders:o,replayParams:s,triggerTimestamp:i}=e,d=await Wt(s.replayDurationSeconds*1e3,i);if(!(d!=null&&d.length)){l.info("FileDataEmpty",{surveyId:t});return}const u=jt(d,s.minimumChunkSizeMb,s.signedUrls.length),g=await Promise.all(u.map(async(m,E)=>{const h=R(),k={apiUrl:r,chunkIndex:E+1,completeUploadHeaders:o,etag:null,responseGroupId:n,status:"ReadyForUpload",surveyId:t,timestamp:i,totalChunks:u.length,data:m,uploadId:s.uploadId,uploadUrl:s.signedUrls[E].url,uuid:h,visitorId:a};return await(await c.openDB()).add("chunkUploads",{...k,sessionId:k.sessionId??y}),k}));await Kt([s.uploadId],g)},Ee=async(e,t)=>{if(v())return l.debug("ReplayDisabled-ScheduleOrCapture");const{isHeatmap:n,isStandalone:a,replayParams:r,triggerTimestamp:o,responseGroupId:s}=e,i=async()=>{setTimeout(()=>P.removeListener(A.QuestionAnswered,i),0),f(async()=>{r.replayDurationType==="before"?await Se(e):await c.markPendingCaptureToCanUpload(s)},"Error in schedule/capture callback")};f(async()=>{if(r.replayDurationType==="after"||r.replayDurationType==="beforeAndAfter"){!a&&!n&&P.on(A.QuestionAnswered,i),await Ce(e);return}if(a||n||t)await Se(e),n&&$t();else{const d=_+r.replayDurationSeconds,u=o-d*1e3,g=o;await c.updateEventsExpiredAt(u,g,r.expirationTimeLimitMinutes),P.on(A.QuestionAnswered,i)}},"Error in scheduling/capturing replay")},$t=async()=>{parseInt(S??"0")||w.removeItem("sprig.isCapturingHeatmap"),w.getItem("sprig.teardownAfterCapture")&&(we(),ke(),w.removeItem("sprig.teardownAfterCapture"))},ke=async()=>v()?l.debug("ReplayDisabled-ClearData"):Promise.all([c.deleteBySessionId("events",y),c.deleteBySessionId("pendingCaptures",y)]).catch(e=>{T("Error clearing user replay data",e)}),Ce=async e=>{if(v())return;const{isHeatmap:t,surveyId:n}=e,a=await c.getPendingCaptures(),r=a?.filter(i=>i.captureParams.surveyId===n);if(r!=null&&r.length){l.info("PendingCaptureExists",{surveyId:n});return}t&&(Pt(),w.setItem("sprig.isCapturingHeatmap","true"),W=Date.now(),p.inactivityInterval||(p.inactivityInterval=window.setInterval(()=>{mt(W)},1e3)));const o={...e,replayParams:{...e.replayParams}};e.replayParams.replayDurationType==="beforeAndAfter"&&(o.replayParams.replayDurationSeconds*=2),o.replayParams.replayDurationType="before";const s=e.triggerTimestamp+e.replayParams.replayDurationSeconds*1e3;o.triggerTimestamp=s,S=(parseInt(S??"0")+1).toString(),w.setItem("sprig.pendingCount",S),await(await c.openDB()).add("pendingCaptures",{canUpload:!1,captureParams:o,sessionId:y,targetTimestamp:s,timestamp:Date.now(),uuid:R()})},qt=Object.freeze(Object.defineProperty({__proto__:null,RecordEvent:ft,RecordPageView:wt,RecordSurveyShown:vt,_completeSessionReplay:xt,checkPendingHeatmapsUrl:gt,clearUserReplayData:ke,disableRecording:T,initializeReplay:At,isReplayRecording:Et,scheduleCapture:Ce,scheduleOrCaptureReplay:Ee,tryReplayAction:f},Symbol.toStringTag,{value:"Module"}));Ae(qt);
1
+ var xe = Object.defineProperty;
2
+ var Be = (e, t, n) => t in e ? xe(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
+ var M = (e, t, n) => (Be(e, typeof t != "symbol" ? t + "" : t, n), n);
4
+ import { b as u, s as ie, a as f, v as N, c as Ue, P as de, r as ce, d as Te, e as T, S as O, f as _e } from "./metricsReporter-D0VZ2ZgI.js";
5
+ var P = ((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))(P || {});
6
+ const ue = new class {
7
+ constructor(e) {
8
+ M(this, "awaitingResolvers", []);
9
+ M(this, "activeCount", 0);
10
+ this.capacity = e;
11
+ }
12
+ async acquire() {
13
+ if (!(this.activeCount < this.capacity))
14
+ return new Promise((e) => {
15
+ this.awaitingResolvers.push(e);
16
+ });
17
+ this.activeCount++;
18
+ }
19
+ release() {
20
+ const e = this.awaitingResolvers.shift();
21
+ e && this.activeCount <= this.capacity ? e() : this.activeCount--;
22
+ }
23
+ async execute(e) {
24
+ try {
25
+ return await this.acquire(), await e();
26
+ } finally {
27
+ this.release();
28
+ }
29
+ }
30
+ setLimit(e) {
31
+ this.capacity = e;
32
+ }
33
+ }(2), le = async ({ apiUrl: e, surveyId: t, uploadId: n, etags: a, headers: r, responseGroupUuid: s, replayDuration: o, eventDigest: d }, i = !1) => {
34
+ var w;
35
+ if (!i && !n && !a)
36
+ return void u.error("UploadErr", { isMobile: i, uploadId: n, etags: a });
37
+ u.info("MarkUploadComplete", { surveyId: t });
38
+ const c = await ie(`${e}/sdk/1/completeSessionReplay`, { method: "POST", body: JSON.stringify({ etags: a, uploadId: n, responseGroupUuid: s, surveyId: t, replayDuration: o, eventDigest: d, userAgent: (w = window == null ? void 0 : window.navigator) == null ? void 0 : w.userAgent }), headers: r, shouldRetryRequest: !0 });
39
+ return u.info("MarkUploadDone", { surveyId: t }), c;
40
+ }, j = (e, t) => t.some((n) => e instanceof n);
41
+ let Z, ee;
42
+ const V = /* @__PURE__ */ new WeakMap(), H = /* @__PURE__ */ new WeakMap(), _ = /* @__PURE__ */ new WeakMap();
43
+ let K = { get(e, t, n) {
44
+ if (e instanceof IDBTransaction) {
45
+ if (t === "done")
46
+ return V.get(e);
47
+ if (t === "store")
48
+ return n.objectStoreNames[1] ? void 0 : n.objectStore(n.objectStoreNames[0]);
49
+ }
50
+ return k(e[t]);
51
+ }, set: (e, t, n) => (e[t] = n, !0), has: (e, t) => e instanceof IDBTransaction && (t === "done" || t === "store") || t in e };
52
+ function pe(e) {
53
+ K = e(K);
54
+ }
55
+ function Ae(e) {
56
+ return (ee || (ee = [IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey])).includes(e) ? function(...t) {
57
+ return e.apply(G(this), t), k(this.request);
58
+ } : function(...t) {
59
+ return k(e.apply(G(this), t));
60
+ };
61
+ }
62
+ function Ne(e) {
63
+ return typeof e == "function" ? Ae(e) : (e instanceof IDBTransaction && function(t) {
64
+ if (V.has(t))
65
+ return;
66
+ const n = new Promise((a, r) => {
67
+ const s = () => {
68
+ r(t.error || new DOMException("AbortError", "AbortError"));
69
+ };
70
+ t.oncomplete = () => {
71
+ a();
72
+ }, t.onerror = s, t.onabort = s;
73
+ });
74
+ V.set(t, n);
75
+ }(e), j(e, Z || (Z = [IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction])) ? new Proxy(e, K) : e);
76
+ }
77
+ function k(e) {
78
+ if (e instanceof IDBRequest)
79
+ return function(n) {
80
+ const a = new Promise((r, s) => {
81
+ n.onsuccess = () => {
82
+ r(k(n.result));
83
+ }, n.onerror = () => {
84
+ s(n.error);
85
+ };
86
+ });
87
+ return _.set(a, n), a;
88
+ }(e);
89
+ if (H.has(e))
90
+ return H.get(e);
91
+ const t = Ne(e);
92
+ return t !== e && (H.set(e, t), _.set(t, e)), t;
93
+ }
94
+ const G = (e) => _.get(e);
95
+ function W(e, { blocked: t } = {}) {
96
+ const n = indexedDB.deleteDatabase(e);
97
+ return t && (n.onblocked = (a) => t(a.oldVersion, a)), k(n).then(() => {
98
+ });
99
+ }
100
+ const Le = ["get", "getKey", "getAll", "getAllKeys", "count"], Me = ["put", "add", "delete", "clear"], F = /* @__PURE__ */ new Map();
101
+ function te(e, t) {
102
+ if (!(e instanceof IDBDatabase) || t in e || typeof t != "string")
103
+ return;
104
+ if (F.get(t))
105
+ return F.get(t);
106
+ const n = t.replace(/FromIndex$/, ""), a = t !== n, r = Me.includes(n);
107
+ if (!(n in (a ? IDBIndex : IDBObjectStore).prototype) || !r && !Le.includes(n))
108
+ return;
109
+ const s = async function(o, ...d) {
110
+ const i = this.transaction(o, r ? "readwrite" : "readonly");
111
+ let c = i.store;
112
+ return a && (c = c.index(d.shift())), (await Promise.all([c[n](...d), r && i.done]))[0];
113
+ };
114
+ return F.set(t, s), s;
115
+ }
116
+ pe((e) => ({ ...e, get: (t, n, a) => te(t, n) || e.get(t, n, a), has: (t, n) => !!te(t, n) || e.has(t, n) }));
117
+ const Oe = ["continue", "continuePrimaryKey", "advance"], ne = {}, $ = /* @__PURE__ */ new WeakMap(), me = /* @__PURE__ */ new WeakMap(), He = { get(e, t) {
118
+ if (!Oe.includes(t))
119
+ return e[t];
120
+ let n = ne[t];
121
+ return n || (n = ne[t] = function(...a) {
122
+ $.set(this, me.get(this)[t](...a));
123
+ }), n;
124
+ } };
125
+ async function* Fe(...e) {
126
+ let t = this;
127
+ if (t instanceof IDBCursor || (t = await t.openCursor(...e)), !t)
128
+ return;
129
+ const n = new Proxy(t, He);
130
+ for (me.set(n, t), _.set(n, G(t)); t; )
131
+ yield n, t = await ($.get(n) || t.continue()), $.delete(n);
132
+ }
133
+ function ae(e, t) {
134
+ return t === Symbol.asyncIterator && j(e, [IDBIndex, IDBObjectStore, IDBCursor]) || t === "iterate" && j(e, [IDBIndex, IDBObjectStore]);
135
+ }
136
+ pe((e) => ({ ...e, get: (t, n, a) => ae(t, n) ? Fe : e.get(t, n, a), has: (t, n) => ae(t, n) || e.has(t, n) }));
137
+ const je = (e) => {
138
+ if (e instanceof Attr)
139
+ return null;
140
+ let t = 1;
141
+ for (let n = e.previousSibling; n; n = n.previousSibling)
142
+ n.nodeName === e.nodeName && ++t;
143
+ return t;
144
+ }, ge = (e) => {
145
+ if (e === null)
146
+ return "";
147
+ const t = [];
148
+ if (e instanceof Document)
149
+ return "/";
150
+ for (let n = e; n && !(n instanceof Document) && n !== null; n = n instanceof Attr ? n.ownerElement : n.parentElement) {
151
+ const a = t[t.length] = { name: void 0, position: null };
152
+ switch (n.nodeType) {
153
+ case Node.TEXT_NODE:
154
+ a.name = "text()";
155
+ break;
156
+ case Node.ATTRIBUTE_NODE:
157
+ a.name = "@" + n.nodeName;
158
+ break;
159
+ case Node.PROCESSING_INSTRUCTION_NODE:
160
+ a.name = "processing-instruction()";
161
+ break;
162
+ case Node.COMMENT_NODE:
163
+ a.name = "comment()";
164
+ break;
165
+ case Node.ELEMENT_NODE:
166
+ a.name = n.nodeName;
167
+ }
168
+ a.position = je(n);
169
+ }
170
+ return "/" + t.reverse().map((n) => n.position !== null ? `/${n.name}[${n.position}]` : `/${n.name}`).join("");
171
+ }, S = { capture: !0, passive: !0 }, Ve = ["a", "button", "input", "option", "li", "link"], Ke = ["Escape", "Enter", "Backspace", "F5", "Tab"];
172
+ let A = !1;
173
+ const Ge = ["label", "type", "role", "title", "placeholder", "errormessage", "valuetext", "href"], We = "aria-", re = (e) => {
174
+ var a;
175
+ if (((a = e.tagName) == null ? void 0 : a.toLowerCase()) === "html")
176
+ return { element: "html" };
177
+ const t = e.textContent, n = t ? { text: t } : {};
178
+ n.element = ((r) => {
179
+ if (!r.tagName)
180
+ return "No tagName";
181
+ const s = r.getAttribute("type");
182
+ return s ? `${s} ${r.tagName.toLowerCase()}` : r.tagName.toLowerCase();
183
+ })(e);
184
+ for (const r of e.attributes) {
185
+ let s = r.name;
186
+ const o = r.value;
187
+ s.startsWith(We) && (s = s.substring(5)), Ge.includes(s) && (n[s] = o);
188
+ }
189
+ return n;
190
+ }, $e = (e) => {
191
+ var a;
192
+ if (!e)
193
+ return {};
194
+ const t = { ...re(e) }, n = e.parentElement;
195
+ if (n && Ve.includes((a = n.tagName) == null ? void 0 : a.toLowerCase())) {
196
+ const r = re(n);
197
+ Object.assign(t, r);
198
+ }
199
+ return t;
200
+ }, we = (e, t) => {
201
+ var n;
202
+ ze({ x: t.x, y: t.y, type: e, elementAttributes: $e(t.target), windowHeight: window.innerHeight, windowWidth: window.innerWidth, ...t.target instanceof HTMLElement ? { rect: (n = t.target) == null ? void 0 : n.getBoundingClientRect(), xPath: ge(t.target) } : {} });
203
+ }, ye = (e) => {
204
+ Ke.includes(e.key) && Xe({ key: e.key });
205
+ }, fe = /* @__PURE__ */ ((e, t) => {
206
+ let n;
207
+ return (a) => {
208
+ clearTimeout(n), n = window.setTimeout(() => e(a), t);
209
+ };
210
+ })((e) => {
211
+ if (!(e.target instanceof HTMLElement || e.target instanceof Document))
212
+ return;
213
+ let t = e.target;
214
+ "scrollTop" in t || (t = t.documentElement), Ye({ xPath: ge(t), x: t.scrollLeft, y: t.scrollTop, elementAttributes: { targetScrollWidth: t.scrollWidth, targetClientWidth: t.clientWidth, targetScrollHeight: t.scrollHeight, targetClientHeight: t.clientHeight } });
215
+ }, 750), Ie = (se = "left_click", (e) => we(se, e));
216
+ var se;
217
+ const he = (e) => {
218
+ e.button === 2 && we("right_click", e);
219
+ }, qe = () => {
220
+ A || (window.addEventListener("click", Ie, S), window.addEventListener("mousedown", he, S), window.addEventListener("keydown", ye, S), window.addEventListener("scroll", fe, S), A = !0, window.performance.getEntriesByType("navigation").map((e) => e.type).includes("reload") && Je({ url: window.location.href, currentPageTitle: document.title }), window.performance.getEntriesByType("navigation").map((e) => e.type).includes("back_forward") && Qe({ curUrl: window.location.href, fromUrl: document.referrer, currentPageTitle: document.title }));
221
+ }, p = { isRecording: !1, scrollEventUuids: {}, stopRecording: () => {
222
+ } }, y = (() => {
223
+ const e = f.getItem("sprig.sessionId");
224
+ if (e)
225
+ return u.info("SessionIDFound", { savedSessionId: e }), f.removeItem("sprig.sessionId"), e;
226
+ const t = N();
227
+ return u.info("GeneratedSessionID", { uuid: t }), t;
228
+ })(), q = () => {
229
+ f.setItem("sprig.disableReplayRecording", "disabled");
230
+ }, D = () => !!f.getItem("sprig.disableReplayRecording");
231
+ window.addEventListener("beforeunload", () => {
232
+ u.info("BeforeUnload", { sessionId: y }), f.setItem("sprig.sessionId", y);
233
+ });
234
+ const Y = (e) => e && e.trim().substring(0, 500).replace(/\s\s+/g, " ").replace(/\r?\n|\r/g, " ").substring(0, 250), v = (e, t) => {
235
+ var n, a;
236
+ if (!D() && p.isRecording)
237
+ try {
238
+ (a = (n = window.rrwebRecord) == null ? void 0 : n.addCustomEvent) == null || a.call(n, e, t);
239
+ } catch (r) {
240
+ L("Error recording custom event", r);
241
+ }
242
+ }, ze = (e) => {
243
+ var t;
244
+ (t = e == null ? void 0 : e.elementAttributes) != null && t.text && (e.elementAttributes.text = Y(e.elementAttributes.text)), v("Sprig_Click", e);
245
+ }, Je = (e) => {
246
+ v("Sprig_Refresh", e);
247
+ }, Qe = (e) => {
248
+ e.currentPageTitle && (e.currentPageTitle = Y(e.currentPageTitle)), v("Sprig_BackForward", e);
249
+ }, Xe = (e) => {
250
+ v("Sprig_Keystroke", e);
251
+ }, Ye = async (e) => {
252
+ const { x: t, xPath: n, y: a } = e, r = p.scrollEventUuids[n];
253
+ if (r)
254
+ return h(async () => {
255
+ var d, i, c, w;
256
+ const s = await l.openDB(), o = await s.get("events", r);
257
+ if (o != null && o.event) {
258
+ const m = JSON.parse(o.event), I = t > ((i = (d = m.data) == null ? void 0 : d.payload) == null ? void 0 : i.x), g = a > ((w = (c = m.data) == null ? void 0 : c.payload) == null ? void 0 : w.y);
259
+ if (!I && !g)
260
+ return null;
261
+ I && (m.data.payload.x = t), g && (m.data.payload.y = a), m.data.payload.elementAttributes = e.elementAttributes, o.event = JSON.stringify(m), await s.put("events", o);
262
+ } else
263
+ v("Sprig_Scroll", e);
264
+ }, "Error updating scroll event");
265
+ v("Sprig_Scroll", e);
266
+ }, ve = () => {
267
+ p.stopRecording && (p.stopRecording(), p.stopRecording = void 0), p.isRecording = !1, ["cleanupInterval", "inactivityInterval", "pendingCheckInterval"].forEach((e) => {
268
+ p[e] && (clearInterval(p[e]), p[e] = void 0);
269
+ }), A && (window.removeEventListener("click", Ie, S), window.removeEventListener("mousedown", he, S), window.removeEventListener("keydown", ye, S), window.removeEventListener("scroll", fe, S), A = !1);
270
+ }, Ze = ["did not allow mutations", "called in an invalid security context"], et = (e, t, { reportError: n = !0, extraInfo: a = {} }) => {
271
+ if (!D() && t instanceof Error) {
272
+ if (q(), t.name === "VersionError")
273
+ return u.error("VersionErr", { message: e }), l.deleteDB();
274
+ ((r) => {
275
+ if (!r)
276
+ return !0;
277
+ for (const s of Ze)
278
+ if (r.toLowerCase().includes(s))
279
+ return !1;
280
+ return !0;
281
+ })(t == null ? void 0 : t.message) && (n && window.UserLeap.reportError(e, t, a), l.clearAll());
282
+ }
283
+ }, L = (e, t, { reportError: n } = { reportError: !0 }) => {
284
+ ve(), u.error("ReplayErr", { code: t.code, name: t.name }), et(e, t, { reportError: n });
285
+ }, h = async (e, t) => {
286
+ try {
287
+ await e();
288
+ } catch (n) {
289
+ L(t, n);
290
+ }
291
+ };
292
+ W("replayStorage").catch(console.error), W("sprig.replay").catch(console.error);
293
+ const l = new class {
294
+ openDB() {
295
+ return function(e, t, { blocked: n, upgrade: a, blocking: r, terminated: s } = {}) {
296
+ const o = indexedDB.open(e, t), d = k(o);
297
+ return a && (o.onupgradeneeded = (i) => {
298
+ a(k(o.result), i.oldVersion, i.newVersion, k(o.transaction), i);
299
+ }), n && (o.onblocked = (i) => n(i.oldVersion, i.newVersion, i)), d.then((i) => {
300
+ s && (i.onclose = () => s()), r && (i.onversionchange = (c) => r(c.oldVersion, c.newVersion, c));
301
+ }).catch(() => {
302
+ }), d;
303
+ }("sprigReplay", 1, { upgrade: (e, t, n) => {
304
+ if (n === 0 && f.setItem("sprig.pendingCount", "0"), !e.objectStoreNames.contains("events")) {
305
+ const a = e.createObjectStore("events", { keyPath: "uuid" });
306
+ a.createIndex("sessionId", "sessionId"), a.createIndex("timestamp", "timestamp"), a.createIndex("[sessionId+timestamp]", ["sessionId", "timestamp"]);
307
+ }
308
+ if (!e.objectStoreNames.contains("chunkUploads")) {
309
+ const a = e.createObjectStore("chunkUploads", { keyPath: "uuid" });
310
+ a.createIndex("sessionId", "sessionId"), a.createIndex("timestamp", "timestamp"), a.createIndex("[sessionId+status]", ["sessionId", "status"]), a.createIndex("[uploadId+status]", ["uploadId", "status"]), a.createIndex("[sessionId+status+uploadId]", ["sessionId", "status", "uploadId"]);
311
+ }
312
+ if (!e.objectStoreNames.contains("pendingCaptures")) {
313
+ const a = e.createObjectStore("pendingCaptures", { keyPath: "uuid" });
314
+ a.createIndex("sessionId", "sessionId"), a.createIndex("timestamp", "timestamp"), a.createIndex("[sessionId+targetTimestamp]", ["sessionId", "targetTimestamp"]);
315
+ }
316
+ } });
317
+ }
318
+ deleteDB() {
319
+ return W("sprigReplay").catch(console.error);
320
+ }
321
+ async bulkAdd(e, t) {
322
+ const n = (await this.openDB()).transaction(e, "readwrite");
323
+ return Promise.all([...t.map((a) => n.store.add(a)), n.done]);
324
+ }
325
+ async clearAll() {
326
+ const e = (await this.openDB()).transaction(["events", "chunkUploads", "pendingCaptures"], "readwrite");
327
+ return Promise.all([e.objectStore("events").clear(), e.objectStore("chunkUploads").clear(), e.objectStore("pendingCaptures").clear()]);
328
+ }
329
+ async deleteBySessionId(e, t) {
330
+ const n = IDBKeyRange.only(t), a = (await this.openDB()).transaction(e, "readwrite"), r = a.store.index("sessionId");
331
+ for await (const s of r.iterate(n))
332
+ await s.delete();
333
+ await a.done;
334
+ }
335
+ async updatePartial(e, t, n) {
336
+ const a = (await this.openDB()).transaction(e, "readwrite"), r = await a.store.get(t);
337
+ r && await a.store.put({ ...r, ...n }), await a.done;
338
+ }
339
+ async deleteRowsBefore(e, t, n = () => !0) {
340
+ const a = IDBKeyRange.upperBound(t, !0), r = (await this.openDB()).transaction(e, "readwrite"), s = r.store.index("timestamp");
341
+ for await (const o of s.iterate(a))
342
+ n(o.value) && await o.delete();
343
+ await r.done;
344
+ }
345
+ async getEventsBetween(e, t = Date.now()) {
346
+ if (e >= t)
347
+ return Promise.resolve([]);
348
+ const n = IDBKeyRange.bound([y, e], [y, t], !1, !0);
349
+ return (await this.openDB()).getAllFromIndex("events", "[sessionId+timestamp]", n);
350
+ }
351
+ async updateEventsExpiredAt(e, t, n = 30) {
352
+ const a = /* @__PURE__ */ new Date(), r = a.setMinutes(a.getMinutes() + (n ?? 30)), s = (await this.openDB()).transaction("events", "readwrite"), o = s.store.index("[sessionId+timestamp]"), d = IDBKeyRange.bound([y, e], [y, t], !1, !0);
353
+ for await (const i of o.iterate(d))
354
+ await i.update({ ...i.value, expiredAt: r });
355
+ await s.done;
356
+ }
357
+ async deleteChunkUploads(e, t) {
358
+ const n = IDBKeyRange.only([t, e]), a = (await this.openDB()).transaction("chunkUploads", "readwrite");
359
+ let s = await a.store.index("[uploadId+status]").openCursor(n);
360
+ for (; s; )
361
+ s.delete(), s = await s.continue();
362
+ await a.done;
363
+ }
364
+ async getChunkUploadsByStatus({ sessionId: e, status: t, uploadId: n }) {
365
+ const a = (await this.openDB()).transaction("chunkUploads", "readonly"), r = n ? a.store.index("[uploadId+status]") : a.store.index("[sessionId+status]"), s = n ? IDBKeyRange.only([n, t]) : IDBKeyRange.only([e, t]);
366
+ return r.getAll(s);
367
+ }
368
+ async getPendingCaptures(e = {}) {
369
+ return (await (await this.openDB()).getAllFromIndex("pendingCaptures", "sessionId", y)).filter((n) => !e.beforePresent || n.targetTimestamp < Date.now()).filter((n) => !e.isHeatmap || (n.captureParams.isHeatmap ?? !1));
370
+ }
371
+ async markPendingCaptureToCanUpload(e) {
372
+ const t = (await this.openDB()).transaction("pendingCaptures", "readwrite"), n = t.store.index("sessionId");
373
+ for await (const a of n.iterate(y)) {
374
+ const r = a.value;
375
+ r.captureParams.responseGroupId === e && await a.update({ ...r, canUpload: !0 });
376
+ }
377
+ await t.done;
378
+ }
379
+ async markPendingHeatmapsReady(e) {
380
+ if (parseInt(f.getItem("sprig.pendingCount") ?? "0") === 0)
381
+ return null;
382
+ const t = Date.now(), n = (await this.openDB()).transaction("pendingCaptures", "readwrite"), a = n.store.index("sessionId");
383
+ for await (const r of a.iterate(y)) {
384
+ const s = r.value;
385
+ !s.captureParams.isHeatmap || e && !e.includes(s.uuid) || await r.update({ ...s, targetTimestamp: t, captureParams: { ...s.captureParams, triggerTimestamp: t, replayParams: { ...s.captureParams.replayParams, replayDurationSeconds: Math.floor((t - s.timestamp) / 1e3) } } });
386
+ }
387
+ await n.done;
388
+ }
389
+ }(), De = async (e, t) => {
390
+ const n = performance.now();
391
+ let a;
392
+ try {
393
+ a = await e();
394
+ } finally {
395
+ const r = performance.now() - n;
396
+ let s = de[t];
397
+ s || (s = ce(t)), s.report(r / 1e3);
398
+ }
399
+ return a;
400
+ }, be = (e, t) => {
401
+ const n = performance.now();
402
+ try {
403
+ e();
404
+ } finally {
405
+ const a = performance.now() - n;
406
+ let r = de[t];
407
+ r || (r = ce(t)), r.report(a / 1e3);
408
+ }
409
+ };
410
+ let Se = 5e3, z = 6e4, J = 0, C, Q = !1, X = [];
411
+ const tt = (e) => {
412
+ var t, n, a, r;
413
+ if ((t = e.event) != null && t.includes("Sprig_Scroll")) {
414
+ const s = (r = (a = (n = JSON.parse(e.event)) == null ? void 0 : n.data) == null ? void 0 : a.payload) == null ? void 0 : r.xPath;
415
+ if (!s)
416
+ return;
417
+ p.scrollEventUuids[s] = e.uuid;
418
+ }
419
+ X.push(e), Q || nt();
420
+ }, nt = () => {
421
+ Q = !0, setTimeout(async () => {
422
+ if (D())
423
+ return;
424
+ const e = X;
425
+ X = [], Q = !1, be(async () => {
426
+ await (async (t) => {
427
+ const n = t.map((a) => ({ ...a, sessionId: a.sessionId ?? y }));
428
+ if (n.length !== 0)
429
+ return h(() => l.bulkAdd("events", n), "Error storing replay events");
430
+ })(e);
431
+ }, "sdk_replay_add_event_batch_seconds");
432
+ }, 500);
433
+ }, at = (e, t, n) => {
434
+ p.cleanupInterval = window.setInterval(() => {
435
+ const a = Date.now();
436
+ De(() => h(async () => {
437
+ D() || await Promise.all([l.deleteRowsBefore("events", a - 1e3 * e, (r) => r.expiredAt === void 0 || r.expiredAt < a - 1e3 * e), l.deleteRowsBefore("chunkUploads", a - 1e3 * t), l.deleteRowsBefore("pendingCaptures", a - 1e3 * n, (r) => !r.canUpload)]);
438
+ }, "Error deleting table rows"), "sdk_replay_cleanup_seconds"), u.debug("CleanupComplete");
439
+ }, 3e4);
440
+ }, rt = () => {
441
+ p.pendingCheckInterval = window.setInterval(async () => {
442
+ h(async () => {
443
+ const e = parseInt(C ?? "0");
444
+ if (e === 0)
445
+ return;
446
+ const t = await l.getPendingCaptures({ beforePresent: !0 }), n = await l.openDB();
447
+ await Promise.all(t.map(async (a) => (await n.delete("pendingCaptures", a.uuid), Ee(a.captureParams, a.canUpload)))), C = (e - t.length).toString(), f.setItem("sprig.pendingCount", C);
448
+ }, "Error initiating pending captures");
449
+ }, 5e3);
450
+ }, st = async (e, t, n, a, r) => {
451
+ const s = Math.min(e + r, n), o = await De(() => l.getEventsBetween(e, s), "sdk_replay_get_events_between_seconds");
452
+ if (!(o != null && o.length))
453
+ return u.debug("NoEventsFound"), { validStartFound: a, events: [] };
454
+ if (!a) {
455
+ u.debug("ValidStartSearch");
456
+ let d = -1;
457
+ return o == null || o.forEach((i, c) => {
458
+ if (!i.isValidStart)
459
+ return;
460
+ const w = i.timestamp <= t;
461
+ (d < 0 || w) && (d = c);
462
+ }), d < 0 ? (u.debug("ValidStartNotFound"), { validStartFound: a, events: [] }) : { validStartFound: !0, events: o == null ? void 0 : o.slice(d) };
463
+ }
464
+ return { validStartFound: a, events: o };
465
+ }, ke = (e) => Promise.all(e.map(async (t) => {
466
+ const n = await (async (a) => ue.execute(async () => {
467
+ var o;
468
+ u.info("UploadChunkStart", { chunkIndex: a.chunkIndex, surveyId: a.surveyId });
469
+ const r = await ie(a.uploadUrl, { body: a.data, method: "PUT" });
470
+ u.http("UploadChunkEnd", { url: a.uploadUrl, method: "PUT", status_code: r.status, reason: r.statusText ?? "OK", chunkIndex: a.chunkIndex, surveyId: a.surveyId });
471
+ const s = (o = r.headers) == null ? void 0 : o.get("ETag");
472
+ if (!s)
473
+ throw new Error(`Upload response did not include etag for upload ${a.uploadId}, part ${a.chunkIndex}`);
474
+ return s;
475
+ }))(t);
476
+ return await l.updatePartial("chunkUploads", t.uuid, { data: null, etag: n, status: "UploadComplete" }), t.uploadId;
477
+ })), Ce = async (e) => {
478
+ const t = await l.getChunkUploadsByStatus({ status: "UploadComplete", uploadId: e });
479
+ if (!(t != null && t.length))
480
+ return void u.info("NoChunksForUpload", { uploadId: e });
481
+ const n = t.reduce((s, o) => (s.find((d) => d.chunkIndex === o.chunkIndex) || s.push(o), s), []);
482
+ n.sort((s, o) => s.chunkIndex - o.chunkIndex);
483
+ const a = n.map((s) => ({ ETag: s.etag, PartNumber: s.chunkIndex })).filter((s) => s.ETag !== null), r = n[0];
484
+ await le({ apiUrl: r.apiUrl, surveyId: r.surveyId, uploadId: e, responseGroupUuid: r.responseGroupId, etags: a, headers: r.completeUploadHeaders, replayDuration: r.replayDuration }), await l.deleteChunkUploads("UploadComplete", e);
485
+ }, ot = () => {
486
+ h(async () => {
487
+ const e = await l.getChunkUploadsByStatus({ sessionId: y, status: "ReadyForUpload" });
488
+ if (!(e != null && e.length))
489
+ return;
490
+ const t = await ke(e);
491
+ t != null && t.length && await Promise.all(t.map((n) => {
492
+ if (n)
493
+ return Ce(n);
494
+ }));
495
+ }, "Error uploading unfinished chunks");
496
+ }, it = async (e, t) => {
497
+ const n = t ?? Date.now();
498
+ return (async (a, r) => {
499
+ const s = new TextEncoder();
500
+ let o = null;
501
+ const d = new CompressionStream("gzip"), i = d.writable.getWriter();
502
+ let c = !1, w = !1, [m, I] = [0, 0], g = [];
503
+ for (let E = a - 35e3; E < r; E += z) {
504
+ if ({ validStartFound: w, events: g } = await st(E, a, r, w, z), !(g != null && g.length)) {
505
+ u.debug("NoEventsFound");
506
+ continue;
507
+ }
508
+ m === 0 && (m = g[0].timestamp), I = g[g.length - 1].timestamp;
509
+ const x = g.map((R) => R.event);
510
+ x.push(`{"timestamp":${r}}`);
511
+ const B = `${c ? "," : "["}${x}`, U = s.encode(B);
512
+ be(() => {
513
+ i.write(U);
514
+ }, "sdk_replay_compression_seconds"), c = !0;
515
+ }
516
+ if (I - m < Se)
517
+ return u.debug("ReplayTooShort"), null;
518
+ const b = s.encode("]");
519
+ return i.write(b), i.close(), o = new Uint8Array(await new Response(d.readable).arrayBuffer()), o;
520
+ })(n - e, n);
521
+ }, oe = async (e) => {
522
+ const { surveyId: t, responseGroupId: n, visitorId: a, apiUrl: r, completeUploadHeaders: s, replayParams: o, triggerTimestamp: d } = e, i = await it(1e3 * o.replayDurationSeconds, d);
523
+ if (!(i != null && i.length))
524
+ return void u.info("FileDataEmpty", { surveyId: t });
525
+ const c = ((m, I, g) => {
526
+ const b = m.length, E = 1024 * I * 1024, x = Math.ceil(b / g), B = Math.max(E, x), U = [];
527
+ let R = 0;
528
+ for (; R < b; )
529
+ U.push(m.slice(R, R + B)), R += B;
530
+ return U;
531
+ })(i, o.minimumChunkSizeMb, o.signedUrls.length), w = await Promise.all(c.map(async (m, I) => {
532
+ const g = N(), b = { apiUrl: r, chunkIndex: I + 1, completeUploadHeaders: s, etag: null, responseGroupId: n, status: "ReadyForUpload", surveyId: t, timestamp: d, totalChunks: c.length, data: m, uploadId: o.uploadId, uploadUrl: o.signedUrls[I].url, uuid: g, visitorId: a };
533
+ return await (await l.openDB()).add("chunkUploads", { ...b, sessionId: b.sessionId ?? y }), b;
534
+ }));
535
+ await (async (m, I) => {
536
+ await ke(I), await Promise.all(m.map((g) => Ce(g)));
537
+ })([o.uploadId], w);
538
+ }, Ee = async (e, t) => {
539
+ if (D())
540
+ return u.debug("ReplayDisabled-ScheduleOrCapture");
541
+ const { isHeatmap: n, isStandalone: a, replayParams: r, triggerTimestamp: s, responseGroupId: o } = e, d = async () => {
542
+ setTimeout(() => T.removeListener(O.QuestionAnswered, d), 0), h(async () => {
543
+ r.replayDurationType === "before" ? await oe(e) : await l.markPendingCaptureToCanUpload(o);
544
+ }, "Error in schedule/capture callback");
545
+ };
546
+ h(async () => {
547
+ if (r.replayDurationType === "after" || r.replayDurationType === "beforeAndAfter")
548
+ return !a && !n && T.on(O.QuestionAnswered, d), void await Pe(e);
549
+ if (a || n || t)
550
+ await oe(e), n && dt();
551
+ else {
552
+ const i = 35 + r.replayDurationSeconds, c = s - 1e3 * i, w = s;
553
+ await l.updateEventsExpiredAt(c, w, r.expirationTimeLimitMinutes), T.on(O.QuestionAnswered, d);
554
+ }
555
+ }, "Error in scheduling/capturing replay");
556
+ }, dt = async () => {
557
+ parseInt(C ?? "0") || f.removeItem("sprig.isCapturingHeatmap"), f.getItem("sprig.teardownAfterCapture") && (ve(), Re(), f.removeItem("sprig.teardownAfterCapture"));
558
+ }, Re = async () => D() ? u.debug("ReplayDisabled-ClearData") : Promise.all([l.deleteBySessionId("events", y), l.deleteBySessionId("pendingCaptures", y)]).catch((e) => {
559
+ L("Error clearing user replay data", e);
560
+ }), Pe = async (e) => {
561
+ if (D())
562
+ return;
563
+ const { isHeatmap: t, surveyId: n } = e, a = await l.getPendingCaptures(), r = a == null ? void 0 : a.filter((i) => i.captureParams.surveyId === n);
564
+ if (r != null && r.length)
565
+ return void u.info("PendingCaptureExists", { surveyId: n });
566
+ t && (p.isRecording && h(() => {
567
+ var i, c;
568
+ return (c = (i = window.rrwebRecord) == null ? void 0 : i.takeFullSnapshot) == null ? void 0 : c.call(i, !0);
569
+ }, "Error recording full snapshot"), f.setItem("sprig.isCapturingHeatmap", "true"), J = Date.now(), p.inactivityInterval || (p.inactivityInterval = window.setInterval(() => {
570
+ var i;
571
+ i = J, Date.now() - i >= 3e4 && h(() => l.markPendingHeatmapsReady(), "Error in heatmap inactivity");
572
+ }, 1e3)));
573
+ const s = { ...e, replayParams: { ...e.replayParams } };
574
+ e.replayParams.replayDurationType === "beforeAndAfter" && (s.replayParams.replayDurationSeconds *= 2), s.replayParams.replayDurationType = "before";
575
+ const o = e.triggerTimestamp + 1e3 * e.replayParams.replayDurationSeconds;
576
+ s.triggerTimestamp = o, C = (parseInt(C ?? "0") + 1).toString(), f.setItem("sprig.pendingCount", C), await (await l.openDB()).add("pendingCaptures", { canUpload: !1, captureParams: s, sessionId: y, targetTimestamp: o, timestamp: Date.now(), uuid: N() });
577
+ };
578
+ _e(Object.freeze(Object.defineProperty({ __proto__: null, RecordEvent: (e) => {
579
+ v("Sprig_TrackEvent", e);
580
+ }, RecordPageView: (e) => {
581
+ e.description && (e.description = Y(e.description)), v("Sprig_PageView", e);
582
+ }, RecordSurveyShown: (e) => {
583
+ v("Sprig_ShowSurvey", e);
584
+ }, _completeSessionReplay: async ({ surveyId: e, responseGroupUuid: t, eventDigest: n, headers: a }) => {
585
+ if (!e || !t)
586
+ return !1;
587
+ const r = window.UserLeap._API_URL, s = await le({ surveyId: e, responseGroupUuid: t, eventDigest: n, apiUrl: r, headers: a }, !0);
588
+ return !(s != null && s.error);
589
+ }, checkPendingHeatmapsUrl: () => D() ? u.debug("ReplayDisabled-PendingHeatmaps") : h(async () => {
590
+ const e = (await l.getPendingCaptures({ isHeatmap: !0 })).map((n) => ({ eventId: n.captureParams.eventId, uuid: n.uuid })), t = [];
591
+ e.forEach(({ eventId: n, uuid: a }) => {
592
+ Ue(n) || t.push(a);
593
+ }), t.length && await l.markPendingHeatmapsReady(t);
594
+ }, "Error marking pending heatmaps ready"), clearUserReplayData: Re, disableRecording: L, initializeReplay: async ({ maxReplayDurationSeconds: e, maxInflightRequests: t = 2, replaySettings: n, teardownAfter: a = !1 }) => {
595
+ if (C = f.getItem("sprig.pendingCount"), !p.isRecording) {
596
+ if (a && f.setItem("sprig.teardownAfterCapture", "true"), D())
597
+ return u.debug("ReplayDisabled");
598
+ if (await (async () => {
599
+ var r;
600
+ if (!window.indexedDB || !window.IDBKeyRange || !window.CompressionStream)
601
+ return !0;
602
+ if ((r = window.navigator.storage) != null && r.estimate)
603
+ try {
604
+ const { quota: s = 0, usage: o = 0 } = await window.navigator.storage.estimate(), d = (s - o) / 1024 ** 3;
605
+ return u.info("Storage", { availableGb: d }), d < 0.5;
606
+ } catch {
607
+ return !0;
608
+ }
609
+ return !1;
610
+ })())
611
+ return u.debug("IDBNotSupported"), q();
612
+ try {
613
+ const r = await l.openDB();
614
+ u.info("DBVersion", { version: r.version });
615
+ } catch (r) {
616
+ return u.error("ReplayOpenErr", { name: r.name }), r.name === "VersionError" && l.deleteDB(), q();
617
+ }
618
+ if (!e)
619
+ return u.debug("MissingDuration");
620
+ u.debug("ReplayInit"), await h(async () => {
621
+ var r;
622
+ if (n != null && n.minDuration && (Se = n.minDuration), n != null && n.batchDuration && (z = n.batchDuration), r = t, ue.setLimit(r), ot(), at(e + 35, 1800, e + 35), rt(), !window.rrwebRecord) {
623
+ const { record: i } = await import(
624
+ /* webpackIgnore: true */
625
+ /* @vite-ignore */
626
+ window.UserLeap.replayLibraryURL ?? "https://cdn.sprig.com/dependencies/record-2.0.0-alpha.17.min.js"
627
+ );
628
+ window.rrwebRecord = i;
629
+ }
630
+ const s = window.rrwebRecord;
631
+ if (!s)
632
+ return u.error("RecordScriptFailed");
633
+ let o = !0, d = 0;
634
+ p.stopRecording = s({ checkoutEveryNms: 3e4, sampling: { input: "last", scroll: 250, media: 800 }, emit: (i, c) => {
635
+ if (i.type === P.Custom && (J = Date.now()), D())
636
+ return;
637
+ if (c && i.type === P.Meta)
638
+ d = performance.now();
639
+ else if (c && d && i.type === P.FullSnapshot) {
640
+ const m = performance.now() - d;
641
+ Te("sdk_replay_snapshot_seconds", m / 1e3);
642
+ }
643
+ const w = o || !!c && i.type === P.Meta;
644
+ o = !1, tt({ uuid: N(), event: JSON.stringify(i), isValidStart: w, timestamp: Date.now() });
645
+ }, ...n }), p.isRecording = !!p.stopRecording, p.isRecording && (T.on("survey.complete", (i) => {
646
+ var c;
647
+ c = { id: i, userAgent: window.navigator.userAgent }, v("Sprig_SubmitSurvey", c);
648
+ }), qe());
649
+ }, "Error initializing replay");
650
+ }
651
+ }, isReplayRecording: () => p.isRecording, scheduleCapture: Pe, scheduleOrCaptureReplay: Ee, tryReplayAction: h }, Symbol.toStringTag, { value: "Module" })));