UNPKG

@sprig-technologies/sprig-browser

Version:

npm package for the sprig web sdk

698 lines (697 loc) 37.3 kB
var st = Object.defineProperty; var it = (e, t, n) => t in e ? st(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n; var X = (e, t, n) => it(e, typeof t != "symbol" ? t + "" : t, n); import { b as d, s as z, a as m, v as q, c as dt, g as lt, P as ke, r as Ue, d as ut, e as H, S as Z, f as ct } from "./metricsReporter-CEzz54S2.js"; var B = ((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))(B || {}), U = ((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))(U || {}); const ae = (e, t) => t.some((n) => e instanceof n); let ve, Se; const re = /* @__PURE__ */ new WeakMap(), Y = /* @__PURE__ */ new WeakMap(), $ = /* @__PURE__ */ new WeakMap(); let oe = { get(e, t, n) { if (e instanceof IDBTransaction) { if (t === "done") return re.get(e); if (t === "store") return n.objectStoreNames[1] ? void 0 : n.objectStore(n.objectStoreNames[0]); } return M(e[t]); }, set: (e, t, n) => (e[t] = n, !0), has: (e, t) => e instanceof IDBTransaction && (t === "done" || t === "store") || t in e }; function xe(e) { oe = e(oe); } function pt(e) { return (Se || (Se = [IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey])).includes(e) ? function(...t) { return e.apply(se(this), t), M(this.request); } : function(...t) { return M(e.apply(se(this), t)); }; } function gt(e) { return typeof e == "function" ? pt(e) : (e instanceof IDBTransaction && function(t) { if (re.has(t)) return; const n = new Promise((a, r) => { const o = () => { r(t.error || new DOMException("AbortError", "AbortError")); }; t.oncomplete = () => { a(); }, t.onerror = o, t.onabort = o; }); re.set(t, n); }(e), ae(e, ve || (ve = [IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction])) ? new Proxy(e, oe) : e); } function M(e) { if (e instanceof IDBRequest) return function(n) { const a = new Promise((r, o) => { n.onsuccess = () => { r(M(n.result)); }, n.onerror = () => { o(n.error); }; }); return $.set(a, n), a; }(e); if (Y.has(e)) return Y.get(e); const t = gt(e); return t !== e && (Y.set(e, t), $.set(t, e)), t; } const se = (e) => $.get(e); function ie(e, { blocked: t } = {}) { const n = indexedDB.deleteDatabase(e); return t && (n.onblocked = (a) => t(a.oldVersion, a)), M(n).then(() => { }); } const mt = ["get", "getKey", "getAll", "getAllKeys", "count"], wt = ["put", "add", "delete", "clear"], ee = /* @__PURE__ */ new Map(); function De(e, t) { if (!(e instanceof IDBDatabase) || t in e || typeof t != "string") return; if (ee.get(t)) return ee.get(t); const n = t.replace(/FromIndex$/, ""), a = t !== n, r = wt.includes(n); if (!(n in (a ? IDBIndex : IDBObjectStore).prototype) || !r && !mt.includes(n)) return; const o = async function(s, ...l) { const i = this.transaction(s, r ? "readwrite" : "readonly"); let u = i.store; return a && (u = u.index(l.shift())), (await Promise.all([u[n](...l), r && i.done]))[0]; }; return ee.set(t, o), o; } xe((e) => ({ ...e, get: (t, n, a) => De(t, n) || e.get(t, n, a), has: (t, n) => !!De(t, n) || e.has(t, n) })); const yt = ["continue", "continuePrimaryKey", "advance"], be = {}, de = /* @__PURE__ */ new WeakMap(), Te = /* @__PURE__ */ new WeakMap(), ft = { get(e, t) { if (!yt.includes(t)) return e[t]; let n = be[t]; return n || (n = be[t] = function(...a) { de.set(this, Te.get(this)[t](...a)); }), n; } }; async function* ht(...e) { let t = this; if (t instanceof IDBCursor || (t = await t.openCursor(...e)), !t) return; const n = new Proxy(t, ft); for (Te.set(n, t), $.set(n, se(t)); t; ) yield n, t = await (de.get(n) || t.continue()), de.delete(n); } function Ee(e, t) { return t === Symbol.asyncIterator && ae(e, [IDBIndex, IDBObjectStore, IDBCursor]) || t === "iterate" && ae(e, [IDBIndex, IDBObjectStore]); } xe((e) => ({ ...e, get: (t, n, a) => Ee(t, n) ? ht : e.get(t, n, a), has: (t, n) => Ee(t, n) || e.has(t, n) })); const It = "sprigReplayIframeLoaded", vt = "sprigReplayIframeSettings", St = "sprigReplayIframeTakeFullSnapshot", Dt = "sprigReplayTeardown", ye = [], Be = new class { constructor(e) { X(this, "awaitingResolvers", []); X(this, "activeCount", 0); this.capacity = e; } async acquire() { if (!(this.activeCount < this.capacity)) return new Promise((e) => { this.awaitingResolvers.push(e); }); this.activeCount++; } release() { const e = this.awaitingResolvers.shift(); e && this.activeCount <= this.capacity ? e() : this.activeCount--; } async execute(e) { try { return await this.acquire(), await e(); } finally { this.release(); } } setLimit(e) { this.capacity = e; } }(2), Me = async ({ apiUrl: e, surveyId: t, uploadId: n, etags: a, headers: r, responseGroupUuid: o, replayDuration: s, eventDigest: l }, i = !1) => { var y; if (!i && !n && !a) return void d.error("UploadErr", { isMobile: i, uploadId: n, etags: a }); d.info("MarkUploadComplete", { surveyId: t }); const u = await z(`${e}/sdk/1/completeSessionReplay`, { method: "POST", body: JSON.stringify({ etags: a, uploadId: n, responseGroupUuid: o, surveyId: t, replayDuration: s, eventDigest: l, userAgent: (y = window == null ? void 0 : window.navigator) == null ? void 0 : y.userAgent }), headers: r, shouldRetryRequest: !0 }); return d.info("MarkUploadDone", { surveyId: t }), u; }, bt = (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; }, Ae = (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; } a.position = bt(n); } return "/" + t.reverse().map((n) => n.position !== null ? `/${n.name}[${n.position}]` : `/${n.name}`).join(""); }, fe = (e) => e && e.trim().substring(0, 500).replace(/\s\s+/g, " ").replace(/\r?\n|\r/g, " ").substring(0, 250), C = { capture: !0, passive: !0 }, Et = ["a", "button", "input", "option", "li", "link"], Rt = ["Escape", "Enter", "Backspace", "F5", "Tab"]; let K = !1, b = null, j = null; const Re = (e) => { var n; if (((n = e.tagName) == null ? void 0 : n.toLowerCase()) === "html") return { element: "html" }; const t = {}; return t.element = ((a) => { if (!a.tagName) return "No tagName"; const r = a.getAttribute("type"); return r ? `${r} ${a.tagName.toLowerCase()}` : a.tagName.toLowerCase(); })(e), t; }, Ct = (e) => { var a; if (!e) return {}; const t = { ...Re(e) }, n = e.parentElement; if (n && Et.includes((a = n.tagName) == null ? void 0 : a.toLowerCase())) { const r = Re(n); Object.assign(t, r); } return t; }, _e = (e, t) => { var r, o; let n = t.target; var a; t.target === ((r = window.document) == null ? void 0 : r.body) && window.Sprig.pointerDownTarget && (n = window.Sprig.pointerDownTarget), a = { x: t.x, y: t.y, type: e, elementAttributes: Ct(n), windowHeight: window.innerHeight, windowWidth: window.innerWidth, ...n instanceof HTMLElement ? { rect: n == null ? void 0 : n.getBoundingClientRect(), xPath: Ae(n) } : {} }, (o = a == null ? void 0 : a.elementAttributes) != null && o.text && (a.elementAttributes.text = fe(a.elementAttributes.text)), b == null || b("Sprig_Click", a); }, Ne = (e) => { var t; Rt.includes(e.key) && (t = { key: e.key }, b == null || b("Sprig_Keystroke", t)); }, Pt = () => { var e; window.performance.getEntriesByType("navigation").map((t) => t.type).includes("reload") && (e = { url: window.location.href, currentPageTitle: document.title }, b == null || b("Sprig_Refresh", e)); }, kt = () => { var e; window.performance.getEntriesByType("navigation").map((t) => t.type).includes("back_forward") && ((e = { curUrl: window.location.href, fromUrl: document.referrer, currentPageTitle: document.title }).currentPageTitle && (e.currentPageTitle = fe(e.currentPageTitle)), b == null || b("Sprig_BackForward", e)); }, Le = /* @__PURE__ */ ((e, t) => { let n; return (a) => { clearTimeout(n), n = window.setTimeout(() => e(a), t); }; })((e) => { if (!(e.target instanceof HTMLElement || e.target instanceof Document)) return; let t = e.target; "scrollTop" in t || (t = t.documentElement), j == null || j({ xPath: Ae(t), x: t.scrollLeft, y: t.scrollTop, elementAttributes: { targetScrollWidth: t.scrollWidth, targetClientWidth: t.clientWidth, targetScrollHeight: t.scrollHeight, targetClientHeight: t.clientHeight } }); }, 750), Oe = (Ce = "left_click", (e) => _e(Ce, e)); var Ce; const Fe = (e) => { e.button === 2 && _e("right_click", e); }, He = (e) => { window.Sprig && (window.Sprig.pointerDownTarget = e.target); }, g = { isRecording: !1, scrollEventUuids: {}, stopRecording: () => { } }, je = () => window.indexedDB && window.IDBKeyRange && window.CompressionStream, I = (() => { const e = m.getItem("sprig.sessionId"); if (e) return d.info("SessionIDFound", { savedSessionId: e }), m.removeItem("sprig.sessionId"), e; const t = q(); return d.info("GeneratedSessionID", { uuid: t }), t; })(), le = () => { m.setItem("sprig.disableReplayRecording", "disabled"); }, P = () => !!m.getItem("sprig.disableReplayRecording"), W = () => !!m.getItem("sprig.isReplayPaused"); window.addEventListener("beforeunload", () => { d.info("BeforeUnload", { sessionId: I }), m.setItem("sprig.sessionId", I); }); const x = (e, t) => { var n, a; if (!P() && g.isRecording && !W()) try { (a = (n = window.rrwebRecord) == null ? void 0 : n.addCustomEvent) == null || a.call(n, e, t); } catch (r) { Q("Error recording custom event", r); } }, Ut = async (e) => { const { x: t, xPath: n, y: a } = e, r = g.scrollEventUuids[n]; if (r) return D(async () => { var l, i, u, y; const o = await c.openDB(), s = await o.get("events", r); if (s != null && s.event) { const p = JSON.parse(s.event), h = t > ((i = (l = p.data) == null ? void 0 : l.payload) == null ? void 0 : i.x), w = a > ((y = (u = p.data) == null ? void 0 : u.payload) == null ? void 0 : y.y); if (!h && !w) return null; h && (p.data.payload.x = t), w && (p.data.payload.y = a), p.data.payload.elementAttributes = e.elementAttributes, s.event = JSON.stringify(p), await o.put("events", s); } else x("Sprig_Scroll", e); }, "Error updating scroll event"); x("Sprig_Scroll", e); }, Ve = () => { g.stopRecording && (g.stopRecording(), g.stopRecording = void 0), g.isRecording = !1, ["cleanupInterval", "inactivityInterval", "pendingCheckInterval"].forEach((e) => { g[e] && (clearInterval(g[e]), g[e] = void 0); }), K && (window.removeEventListener("click", Oe, C), window.removeEventListener("pointerdown", He, C), window.removeEventListener("mousedown", Fe, C), window.removeEventListener("keydown", Ne, C), window.removeEventListener("scroll", Le, C), K = !1), ye.forEach((e) => { var t; (t = e.source) == null || t.postMessage({ type: Dt }, { targetOrigin: e.origin }); }); }, xt = ["did not allow mutations", "called in an invalid security context"], Tt = (e, t, { reportError: n = !0, extraInfo: a = {} }) => { if (!P() && t instanceof Error) { if (le(), t.name === "VersionError") return d.error("VersionErr", { message: e }), void c.deleteDB(); ((r) => { if (!r) return !0; for (const o of xt) if (r.toLowerCase().includes(o)) return !1; return !0; })(t == null ? void 0 : t.message) && (n && window.UserLeap.reportError(e, t, a), c.clearAll()); } }, Q = (e, t, { reportError: n } = { reportError: !0 }) => { Ve(), d.error("ReplayErr", { code: t.code, name: t.name }), Tt(e, t, { reportError: n }); }, D = async (e, t) => { try { return await e(); } catch (n) { Q(t, n); } }, ue = () => { g.isRecording && (D(() => { var e, t; return (t = (e = window.rrwebRecord) == null ? void 0 : e.takeFullSnapshot) == null ? void 0 : t.call(e, !0); }, "Error recording full snapshot"), ye.forEach((e) => { var t; (t = e.source) == null || t.postMessage({ type: St }, { targetOrigin: e.origin }); })); }; (async () => je() && Promise.allSettled([ie("replayStorage"), ie("sprig.replay")]))(); const c = new class { openDB() { return function(e, t, { blocked: n, upgrade: a, blocking: r, terminated: o } = {}) { const s = indexedDB.open(e, t), l = M(s); return a && (s.onupgradeneeded = (i) => { a(M(s.result), i.oldVersion, i.newVersion, M(s.transaction), i); }), n && (s.onblocked = (i) => n(i.oldVersion, i.newVersion, i)), l.then((i) => { o && (i.onclose = () => o()), r && (i.onversionchange = (u) => r(u.oldVersion, u.newVersion, u)); }).catch(() => { }), l; }("sprigReplay", 1, { upgrade: (e, t, n) => { if (n === 0 && m.setItem("sprig.pendingCount", "0"), !e.objectStoreNames.contains("events")) { const a = e.createObjectStore("events", { keyPath: "uuid" }); a.createIndex("sessionId", "sessionId"), a.createIndex("timestamp", "timestamp"), a.createIndex("[sessionId+timestamp]", ["sessionId", "timestamp"]); } if (!e.objectStoreNames.contains("chunkUploads")) { const a = e.createObjectStore("chunkUploads", { keyPath: "uuid" }); 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"]); } if (!e.objectStoreNames.contains("pendingCaptures")) { const a = e.createObjectStore("pendingCaptures", { keyPath: "uuid" }); a.createIndex("sessionId", "sessionId"), a.createIndex("timestamp", "timestamp"), a.createIndex("[sessionId+targetTimestamp]", ["sessionId", "targetTimestamp"]); } } }); } async deleteDB() { try { await ie("sprigReplay"); } catch { } } async bulkAdd(e, t) { const n = (await this.openDB()).transaction(e, "readwrite"); return Promise.all([...t.map((a) => n.store.add(a)), n.done]); } async clearAll() { const e = (await this.openDB()).transaction(["events", "chunkUploads", "pendingCaptures"], "readwrite"); return Promise.all([e.objectStore("events").clear(), e.objectStore("chunkUploads").clear(), e.objectStore("pendingCaptures").clear()]); } async deleteBySessionId(e, t) { const n = IDBKeyRange.only(t), a = (await this.openDB()).transaction(e, "readwrite"), r = a.store.index("sessionId"); for await (const o of r.iterate(n)) await o.delete(); await a.done; } async updatePartial(e, t, n) { const a = (await this.openDB()).transaction(e, "readwrite"), r = await a.store.get(t); r && await a.store.put({ ...r, ...n }), await a.done; } async deleteRowsBefore(e, t, n = () => !0) { const a = IDBKeyRange.upperBound(t, !0), r = (await this.openDB()).transaction(e, "readwrite"), o = r.store.index("timestamp"); for await (const s of o.iterate(a)) n(s.value) && await s.delete(); await r.done; } async getEventsBetween(e, t = Date.now()) { if (e >= t) return Promise.resolve([]); const n = IDBKeyRange.bound([I, e], [I, t], !1, !0); return (await this.openDB()).getAllFromIndex("events", "[sessionId+timestamp]", n); } async updateEventsExpiredAt(e, t, n = 30) { const a = /* @__PURE__ */ new Date(), r = a.setMinutes(a.getMinutes() + (n ?? 30)), o = (await this.openDB()).transaction("events", "readwrite"), s = o.store.index("[sessionId+timestamp]"), l = IDBKeyRange.bound([I, e], [I, t], !1, !0); for await (const i of s.iterate(l)) await i.update({ ...i.value, expiredAt: r }); await o.done; } async deleteChunkUploads(e, t) { const n = IDBKeyRange.only([t, e]), a = (await this.openDB()).transaction("chunkUploads", "readwrite"); let o = await a.store.index("[uploadId+status]").openCursor(n); for (; o; ) o.delete(), o = await o.continue(); await a.done; } async getChunkUploadsByStatus({ sessionId: e, status: t, uploadId: n }) { const a = (await this.openDB()).transaction("chunkUploads", "readonly"), r = n ? a.store.index("[uploadId+status]") : a.store.index("[sessionId+status]"), o = n ? IDBKeyRange.only([n, t]) : IDBKeyRange.only([e, t]); return r.getAll(o); } async getPendingCaptures(e = {}) { return (await (await this.openDB()).getAllFromIndex("pendingCaptures", "sessionId", I)).filter((n) => !e.beforePresent || n.targetTimestamp < Date.now()).filter((n) => !e.isBeforeType || n.captureParams.replayParams.replayDurationType === "before").filter((n) => !e.isHeatmap || (n.captureParams.isHeatmap ?? !1)); } async markPendingCaptureToCanUpload(e) { const t = (await this.openDB()).transaction("pendingCaptures", "readwrite"), n = t.store.index("sessionId"); for await (const a of n.iterate(I)) { const r = a.value; r.captureParams.responseGroupId === e && await a.update({ ...r, canUpload: !0 }); } await t.done; } async markPendingHeatmapsReady(e) { if (parseInt(m.getItem("sprig.pendingCount") ?? "0") === 0) return null; const t = Date.now(), n = (await this.openDB()).transaction("pendingCaptures", "readwrite"), a = n.store.index("sessionId"); for await (const r of a.iterate(I)) { const o = r.value; !o.captureParams.isHeatmap || e && !e.includes(o.uuid) || await r.update({ ...o, targetTimestamp: t, captureParams: { ...o.captureParams, triggerTimestamp: t, replayParams: { ...o.captureParams.replayParams, replayDurationSeconds: Math.floor((t - o.timestamp) / 1e3) } } }); } await n.done; } }(), T = []; let F, Ge, J, $e, V, Ke, _ = [], L = !1, N = 0, G = !1, We = !1, he = [], te = !1; const O = () => G && !L && Date.now() <= J, Bt = ({ apiUrl: e, config: t, triggerSnapshot: n, forceInit: a = !1 }) => { G && !a || (m.isStorageAvailable ? (_ = [], he.splice(0), T.splice(0), N = 0, V = n, Ge = e, F = { responseGroupUuid: t.responseGroupUuid, surveyId: t.surveyId, userAgent: t.userAgent, sdkVersion: t.sdkVersion }, $e = t.maxDurationSeconds, Nt(), G || (Ke = window.setInterval(_t, 500)), G = !0) : L = !0); }, Mt = [U.Drag, U.Input, U.MediaInteraction, U.MouseInteraction, U.MouseMove, U.Scroll, U.Selection, U.TouchMove], At = (e) => e.type === B.Custom || e.type === B.IncrementalSnapshot && Mt.includes(e.data.source), Ie = (e) => e.some(At), _t = async () => { if (!O()) return void window.clearInterval(Ke); if (Je(), !Ie(T)) return; const e = T[0].timestamp; Date.now() - e > 35e3 && (V == null || V()); }, Je = async () => { if (_.length || te) return; te = !0; const e = await Ot(); if (!e) return void (L = !0); he.splice(0, e.length).forEach((t) => t(e.shift())), e.forEach((t) => _.push(t)), te = !1; }, Nt = () => { const e = m.getItem("sprig.alwayson.info"); if (e) { d.info("Read stored session state", e); const t = JSON.parse(e); L = t.disabled, F = t.metadata, _ = t.uploadUrls, N = t.currentIndex, J = t.expirationTimestamp, t.pendingEventTimestamp && (d.info(`Uploading with pending timestamp: ${t.pendingEventTimestamp}`), Lt(t.pendingEventTimestamp)); } else J = 1e3 * $e + Date.now(); }, Lt = async (e) => { const t = Date.now(), n = (await c.getEventsBetween(e, t)).map((r) => JSON.parse(r.event)); if (!Ie(n)) return; Xe(n); const a = await Qe(); a && await qe(a, n); }, ze = async (e, t) => { try { const n = await e(); if (!n.ok) throw new Error(`Error ${t}`); return n; } catch { L = !0; } }, qe = async (e, t) => { if (!O() || !e) return; const n = await (async (a) => { const r = new TextEncoder(), o = new CompressionStream("gzip"), s = o.writable.getWriter(), l = r.encode(JSON.stringify(a)); return s.write(l), s.close(), new Uint8Array(await new Response(o.readable).arrayBuffer()); })(t); d.info("Uploading always-on events with presigned url"), await ze(() => z(e, { body: n, method: "PUT" }), "uploading always-on with presigned url"); }, Ot = async () => { if (!O()) return; const { surveyId: e, responseGroupUuid: t } = F, n = { responseGroupUuid: t, surveyId: e, index: N + 1 }; d.info("Fetching always-on upload urls", n); const a = await ze(() => z(`${Ge}/sdk/1/replayUrls`, { method: "POST", body: JSON.stringify(n), headers: lt(window.UserLeap) }), "fetching always-on signed urls"); if (!a) return; const r = a.json.signedUrls; return d.info("Fetched more always-on upload urls", { body: n, urls: r }), r; }, Qe = async () => { if (_.length) return _.shift(); const e = new Promise((t) => { he.push(t); }); return Je(), e; }, Xe = (e) => { var r, o, s; const t = e.length ? e[e.length - 1].timestamp : Date.now(), n = N, a = ((o = (r = window.UserLeap) == null ? void 0 : r.config) == null ? void 0 : o.customMetadata) ?? ((s = window.__cfg) == null ? void 0 : s.customMetadata); N++, e.push({ timestamp: t, type: B.Custom, data: { tag: "Sprig_Meta", payload: { ...F, index: n, visitorId: window.UserLeap.visitorId ?? "", timestamp: t, customMetadata: a } } }); }, Ft = (e, t) => { O() && !We && (e || T.length) && (e && T.length && (async () => { const n = T.splice(0); if (!Ie(n)) return; d.info("Capturing always-on event array to upload"), Xe(n); const a = await Qe(); a && await qe(a, n); })(), T.push(t)); }; window.addEventListener("beforeunload", async () => { We = !0, O() && (d.info("Always On handle page unload"), (() => { let e; T.length && (e = T[0].timestamp); const t = { disabled: L, metadata: F, uploadUrls: _, currentIndex: N, pendingEventTimestamp: e, expirationTimestamp: J }; d.info("Storing session state on unload", t), m.setItem("sprig.alwayson.info", JSON.stringify(t)); })()); }); const Ze = async (e, t) => { const n = performance.now(); let a; try { a = await e(); } finally { const r = performance.now() - n; let o = ke[t]; o || (o = Ue(t)), o.report(r / 1e3); } return a; }, Ye = (e, t) => { const n = performance.now(); try { e(); } finally { const a = performance.now() - n; let r = ke[t]; r || (r = Ue(t)), r.report(a / 1e3); } }; let et = 5e3, ce = 6e4, pe = 0, A, ge = !1, me = []; const Ht = (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; g.scrollEventUuids[o] = e.uuid; } me.push(e), ge || jt(); }, jt = () => { ge = !0, setTimeout(async () => { if (P() || W()) return; const e = me; me = [], ge = !1, Ye(async () => { await (async (t) => { const n = t.map((a) => ({ ...a, sessionId: a.sessionId ?? I })); if (n.length !== 0) return D(() => c.bulkAdd("events", n), "Error storing replay events"); })(e); }, "sdk_replay_add_event_batch_seconds"); }, 500); }, Vt = (e, t, n) => { g.cleanupInterval = window.setInterval(() => { const a = Date.now(); Ze(() => D(async () => { P() || await Promise.all([c.deleteRowsBefore("events", a - 1e3 * e, (r) => r.expiredAt === void 0 || r.expiredAt < a - 1e3 * e), c.deleteRowsBefore("chunkUploads", a - 1e3 * t), c.deleteRowsBefore("pendingCaptures", a - 1e3 * n, (r) => !r.canUpload)]); }, "Error deleting table rows"), "sdk_replay_cleanup_seconds"), d.debug("CleanupComplete"); }, 3e4); }, Gt = () => { g.pendingCheckInterval = window.setInterval(async () => { D(async () => { await we(); }, "Error initiating pending captures"); }, 5e3); }; let ne = !1; const we = async (e = !1) => { if (!ne) try { ne = !0; const t = parseInt(A ?? "0"); if (t === 0) return; const n = await c.getPendingCaptures({ beforePresent: !0, isBeforeType: e }), a = await c.openDB(); await Promise.all(n.map(async (r) => (await a.delete("pendingCaptures", r.uuid), at(r.captureParams, r.canUpload)))), A = (t - n.length).toString(), m.setItem("sprig.pendingCount", A); } finally { ne = !1; } }, $t = async (e, t, n, a, r) => { const o = Math.min(e + r, n), s = await Ze(() => c.getEventsBetween(e, o), "sdk_replay_get_events_between_seconds"); if (!(s != null && s.length)) return d.debug("NoEventsFound"), { validStartFound: a, events: [] }; if (!a) { d.debug("ValidStartSearch"); let l = -1; return s == null || s.forEach((i, u) => { if (!i.isValidStart) return; const y = i.timestamp <= t; (l < 0 || y) && (l = u); }), l < 0 ? (d.debug("ValidStartNotFound"), { validStartFound: a, events: [] }) : { validStartFound: !0, events: s == null ? void 0 : s.slice(l) }; } return { validStartFound: a, events: s }; }, tt = (e) => Promise.all(e.map(async (t) => { const n = await (async (a) => Be.execute(async () => { var s; d.info("UploadChunkStart", { chunkIndex: a.chunkIndex, surveyId: a.surveyId }); const r = await z(a.uploadUrl, { body: a.data, method: "PUT" }); d.http("UploadChunkEnd", { url: a.uploadUrl, method: "PUT", status_code: r.status, reason: r.statusText ?? "OK", chunkIndex: a.chunkIndex, surveyId: a.surveyId }); const o = (s = r.headers) == null ? void 0 : s.get("ETag"); if (!o) throw new Error(`Upload response did not include etag for upload ${a.uploadId}, part ${a.chunkIndex}`); return o; }))(t); return await c.updatePartial("chunkUploads", t.uuid, { data: null, etag: n, status: "UploadComplete" }), t.uploadId; })), nt = async (e) => { const t = await c.getChunkUploadsByStatus({ status: "UploadComplete", uploadId: e }); if (!(t != null && t.length)) return void d.info("NoChunksForUpload", { uploadId: e }); const n = t.reduce((o, s) => (o.find((l) => l.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 Me({ apiUrl: r.apiUrl, surveyId: r.surveyId, uploadId: e, responseGroupUuid: r.responseGroupId, etags: a, headers: r.completeUploadHeaders, replayDuration: r.replayDuration }), await c.deleteChunkUploads("UploadComplete", e); }, Kt = () => { D(async () => { const e = await c.getChunkUploadsByStatus({ sessionId: I, status: "ReadyForUpload" }); if (!(e != null && e.length)) return; const t = await tt(e); t != null && t.length && await Promise.all(t.map((n) => { if (n) return nt(n); })); }, "Error uploading unfinished chunks"); }, Wt = async (e, t) => { const n = t ?? Date.now(); return (async (a, r) => { const o = new TextEncoder(); let s = null; const l = new CompressionStream("gzip"), i = l.writable.getWriter(); let u = !1, y = !1, [p, h] = [0, 0], w = []; for (let k = a - 35e3; k < r; k += ce) { if ({ validStartFound: y, events: w } = await $t(k, a, r, y, ce), !(w != null && w.length)) { d.debug("NoEventsFound"); continue; } p === 0 && (p = w[0].timestamp), h = w[w.length - 1].timestamp; const f = w.map((R) => R.event); f.push(`{"timestamp":${r}}`); const v = `${u ? "," : "["}${f}`, S = o.encode(v); Ye(() => { i.write(S); }, "sdk_replay_compression_seconds"), u = !0; } if (h - p < et) return d.debug("ReplayTooShort"), null; const E = o.encode("]"); return i.write(E), i.close(), s = new Uint8Array(await new Response(l.readable).arrayBuffer()), s; })(n - e, n); }, Pe = async (e) => { const { surveyId: t, responseGroupId: n, visitorId: a, apiUrl: r, completeUploadHeaders: o, replayParams: s, triggerTimestamp: l } = e, i = await Wt(1e3 * s.replayDurationSeconds, l); if (!(i != null && i.length)) return void d.info("FileDataEmpty", { surveyId: t }); const u = ((p, h, w) => { const E = p.length, k = 1024 * h * 1024, f = Math.ceil(E / w), v = Math.max(k, f), S = []; let R = 0; for (; R < E; ) S.push(p.slice(R, R + v)), R += v; return S; })(i, s.minimumChunkSizeMb, s.signedUrls.length), y = await Promise.all(u.map(async (p, h) => { const w = q(), E = { apiUrl: r, chunkIndex: h + 1, completeUploadHeaders: o, etag: null, responseGroupId: n, status: "ReadyForUpload", surveyId: t, timestamp: l, totalChunks: u.length, data: p, uploadId: s.uploadId, uploadUrl: s.signedUrls[h].url, uuid: w, visitorId: a }; return await (await c.openDB()).add("chunkUploads", { ...E, sessionId: E.sessionId ?? I }), E; })); await (async (p, h) => { await tt(h), await Promise.all(p.map((w) => nt(w))); })([s.uploadId], y); }, at = async (e, t) => { if (P()) return d.debug("ReplayDisabled-ScheduleOrCapture"); const { isHeatmap: n, isStandalone: a, replayParams: r, triggerTimestamp: o, responseGroupId: s } = e, l = async () => { setTimeout(() => H.removeListener(Z.QuestionAnswered, l), 0), D(async () => { r.replayDurationType === "before" ? await Pe(e) : await c.markPendingCaptureToCanUpload(s); }, "Error in schedule/capture callback"); }; D(async () => { if (r.replayDurationType === "after" || r.replayDurationType === "beforeAndAfter") return !a && !n && H.on(Z.QuestionAnswered, l), void await ot(e); if (a || n || t) await Pe(e), n && Jt(); else { const i = 35 + r.replayDurationSeconds, u = o - 1e3 * i, y = o; await c.updateEventsExpiredAt(u, y, r.expirationTimeLimitMinutes), H.on(Z.QuestionAnswered, l); } }, "Error in scheduling/capturing replay"); }, Jt = async () => { parseInt(A ?? "0") || m.removeItem("sprig.isCapturingHeatmap"), m.getItem("sprig.teardownAfterCapture") && (Ve(), rt(), m.removeItem("sprig.teardownAfterCapture")); }, rt = async () => P() ? d.debug("ReplayDisabled-ClearData") : Promise.all([c.deleteBySessionId("events", I), c.deleteBySessionId("pendingCaptures", I)]).catch((e) => { Q("Error clearing user replay data", e); }), ot = async (e) => { if (P()) return; const { isHeatmap: t, surveyId: n } = e, a = await c.getPendingCaptures(), r = a == null ? void 0 : a.filter((i) => i.captureParams.surveyId === n); if (r != null && r.length) return void d.info("PendingCaptureExists", { surveyId: n }); t && (ue(), m.setItem("sprig.isCapturingHeatmap", "true"), pe = Date.now(), g.inactivityInterval || (g.inactivityInterval = window.setInterval(() => { var i; i = pe, Date.now() - i >= 3e4 && D(() => c.markPendingHeatmapsReady(), "Error in heatmap inactivity"); }, 1e3))); const o = { ...e, replayParams: { ...e.replayParams } }; e.replayParams.replayDurationType === "beforeAndAfter" && (o.replayParams.replayDurationSeconds *= 2), o.replayParams.replayDurationType = "before"; const s = e.triggerTimestamp + 1e3 * e.replayParams.replayDurationSeconds; o.triggerTimestamp = s, A = (parseInt(A ?? "0") + 1).toString(), m.setItem("sprig.pendingCount", A), await (await c.openDB()).add("pendingCaptures", { canUpload: !1, captureParams: o, sessionId: I, targetTimestamp: s, timestamp: Date.now(), uuid: q() }); }, zt = Object.freeze(Object.defineProperty({ __proto__: null, RecordEvent: (e) => { x("Sprig_TrackEvent", e); }, RecordPageView: (e) => { e.description && (e.description = fe(e.description)), x("Sprig_PageView", e); }, RecordSurveyShown: (e) => { x("Sprig_ShowSurvey", e); }, _completeSessionReplay: async ({ surveyId: e, responseGroupUuid: t, eventDigest: n, headers: a }) => { if (!e || !t) return !1; const r = window.UserLeap._API_URL, o = await Me({ surveyId: e, responseGroupUuid: t, eventDigest: n, apiUrl: r, headers: a }, !0); return !(o != null && o.error); }, checkPendingHeatmapsUrl: () => P() ? d.debug("ReplayDisabled-PendingHeatmaps") : D(async () => { const e = (await c.getPendingCaptures({ isHeatmap: !0 })).map((t) => ({ eventId: t.captureParams.eventId, uuid: t.uuid })).filter(({ eventId: t }) => !dt(t)).map(({ uuid: t }) => t); return d.info("PendingHeatmapsToComplete", { count: e.length }), e.length && (await c.markPendingHeatmapsReady(e), d.info("MarkedPendingHeatmapsReady")), e.length; }, "Error marking pending heatmaps ready"), clearUserReplayData: rt, disableRecording: Q, initializeReplay: async ({ maxReplayDurationSeconds: e, maxInflightRequests: t = 2, replaySettings: n, teardownAfter: a = !1, apiUrl: r, alwaysOnConfig: o }) => { if (o && Bt({ apiUrl: r, config: o, triggerSnapshot: () => { ue(); } }), A = m.getItem("sprig.pendingCount"), g.isRecording) return; if (a && m.setItem("sprig.teardownAfterCapture", "true"), P()) return d.debug("ReplayDisabled"); if (await (async () => { var i; if (!je()) return !0; if ((i = window.navigator.storage) != null && i.estimate) try { const { quota: u = 0, usage: y = 0 } = await window.navigator.storage.estimate(), p = (u - y) / 1024 ** 3; return d.info("Storage", { availableGb: p }), p < 0.5; } catch { return !0; } return !1; })()) return d.debug("IDBNotSupported"), le(); try { const i = await c.openDB(); d.info("DBVersion", { version: i.version }); } catch (i) { return d.error("ReplayOpenErr", { name: i.name }), i.name === "VersionError" && c.deleteDB(), le(); } D(async () => { await we(!0); }, "Error uploading ready pending captures"); const s = O() ? 30 : 0, l = Math.max(e ?? 0, s); if (!l) return d.debug("MissingDuration"); d.debug("ReplayInit"), await D(async () => { var i; n != null && n.minDuration && (et = n.minDuration), n != null && n.batchDuration && (ce = n.batchDuration), i = t, Be.setLimit(i), Kt(), Vt(l + 35, 1800, l + 35), Gt(); const u = window.UserLeap.replayLibraryURL ?? "https://cdn.sprig.com/dependencies/record-2.0.0-alpha.17.min.js"; if (!window.rrwebRecord) { const { record: f } = await import( /* webpackIgnore: true */ /* @vite-ignore */ u ); window.rrwebRecord = f; } const y = window.rrwebRecord; if (!y) return d.error("RecordScriptFailed"); let p = !0, h = 0; const w = { checkoutEveryNms: 3e4, sampling: { input: "last", scroll: 250, media: 800 }, ...n }; var E, k; g.stopRecording = y({ emit: (f, v) => { if (f.type === B.Custom && (pe = Date.now()), P() || W()) return; if (v && f.type === B.Meta) h = performance.now(); else if (v && h && f.type === B.FullSnapshot) { const R = performance.now() - h; ut("sdk_replay_snapshot_seconds", R / 1e3); } const S = p || !!v && f.type === B.Meta; p = !1, Ft(S, f), Ht({ uuid: q(), event: JSON.stringify(f), isValidStart: S, timestamp: Date.now() }); }, ...w }), g.isRecording = !!g.stopRecording, g.isRecording && (((f, v) => { window.addEventListener("message", (S) => { var R; S.data.type === It && (ye.push({ source: S.source, origin: S.origin }), (R = S.source) == null || R.postMessage({ type: vt, settings: f, replayLibraryUrl: v }, { targetOrigin: S.origin })); }); })(w, u), H.on("survey.complete", (f) => { var v; v = { id: f, userAgent: window.navigator.userAgent }, x("Sprig_SubmitSurvey", v); }), E = x, k = Ut, K || (b = E, j = k, window.addEventListener("click", Oe, C), window.addEventListener("pointerdown", He, C), window.addEventListener("mousedown", Fe, C), window.addEventListener("keydown", Ne, C), window.addEventListener("scroll", Le, C), K = !0, Pt(), kt())); }, "Error initializing replay"); }, isReplayPaused: W, isReplayRecording: () => g.isRecording, recordFullSnapshot: ue, recordReplayPaused: () => { x("Sprig_ReplayPaused", { timestamp: Date.now() }), m.setItem("sprig.isReplayPaused", "true"); }, recordReplayResumed: () => { m.removeItem("sprig.isReplayPaused"), x("Sprig_ReplayResumed", { timestamp: Date.now() }); }, scheduleCapture: ot, scheduleOrCaptureReplay: at, tryReplayAction: D, uploadReadyPendingCaptures: we }, Symbol.toStringTag, { value: "Module" })); ct(zt);