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