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