@sprig-technologies/sprig-browser 2.34.0 → 2.35.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{core-i4jnjCfb.cjs → core-CGgKmpNf.cjs} +3 -3
- package/dist/{core-DE6rbUl1.js → core-De2JxeSJ.js} +105 -103
- package/dist/core.cjs +1 -1
- package/dist/core.d.ts +52 -15
- package/dist/core.js +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +52 -15
- package/dist/index.js +2 -2
- package/dist/{metricsReporter-CEzz54S2.js → metricsReporter-BJVpNufn.js} +25 -20
- package/dist/{metricsReporter-Cc-ZSIZD.cjs → metricsReporter-BvLxSPGb.cjs} +1 -1
- package/dist/replay.cjs +1 -1
- package/dist/replay.js +281 -261
- package/dist/view-CCKqaqND.cjs +669 -0
- package/dist/view-kh2hxG3p.js +2979 -0
- package/package.json +1 -1
- package/dist/view-Bze4Vd-1.cjs +0 -669
- package/dist/view-C3KUMRoa.js +0 -2752
package/dist/index.d.ts
CHANGED
|
@@ -1020,7 +1020,7 @@ declare const BOOLEAN_OPERATOR: {
|
|
|
1020
1020
|
};
|
|
1021
1021
|
type BooleanOperator = (typeof BOOLEAN_OPERATOR)[keyof typeof BOOLEAN_OPERATOR];
|
|
1022
1022
|
|
|
1023
|
-
type CardType = "consentlegal" | "likert" | "matrix" | "multiplechoice" | "multipleselect" | "nps" | "open" | "recordedtask" | "texturlprompt" | "thanks" | "uploading" | "videovoice";
|
|
1023
|
+
type CardType = "consentlegal" | "likert" | "matrix" | "multiplechoice" | "multipleselect" | "nps" | "open" | "rankorder" | "recordedtask" | "texturlprompt" | "thanks" | "uploading" | "videovoice";
|
|
1024
1024
|
type ConceptUrl = string | null;
|
|
1025
1025
|
interface BaseCard {
|
|
1026
1026
|
name: number;
|
|
@@ -1028,8 +1028,10 @@ interface BaseCard {
|
|
|
1028
1028
|
updatedAt: string;
|
|
1029
1029
|
value?: unknown;
|
|
1030
1030
|
type: CardType;
|
|
1031
|
+
groupId?: number;
|
|
1031
1032
|
}
|
|
1032
1033
|
type Comparator = "answered" | "contains" | "notcontains" | "list_dni" | "eq" | "given_up" | "gt" | "gte" | "lt" | "lte" | "list_all" | "list_alo" | "list_exact" | "neq" | "partial" | "skipped";
|
|
1034
|
+
type Randomize = "none" | "all";
|
|
1033
1035
|
type DefaultComparator = Extract<Comparator, "answered" | "skipped">;
|
|
1034
1036
|
type RoutingOption<C extends Comparator = DefaultComparator> = OldRoutingOption<C> | GroupRoutingOption;
|
|
1035
1037
|
type OldRoutingOption<C extends Comparator = DefaultComparator> = {
|
|
@@ -1052,7 +1054,12 @@ type RoutingGroupOption = {
|
|
|
1052
1054
|
type RoutingOptions<C extends Comparator = DefaultComparator> = RoutingOption<C | DefaultComparator>[] | null;
|
|
1053
1055
|
/** @example <p>Body</p> */
|
|
1054
1056
|
type RichTextBody = string;
|
|
1055
|
-
|
|
1057
|
+
declare enum PromptActionTypeEnum {
|
|
1058
|
+
CONTINUE = "CONTINUE",
|
|
1059
|
+
EXTERNAL = "EXTERNAL",
|
|
1060
|
+
NO_BUTTON = "NO_BUTTON"
|
|
1061
|
+
}
|
|
1062
|
+
type PromptActionType = keyof typeof PromptActionTypeEnum;
|
|
1056
1063
|
interface TextUrlPromptCard extends BaseCard {
|
|
1057
1064
|
props: {
|
|
1058
1065
|
message: string;
|
|
@@ -1235,7 +1242,7 @@ interface CommonMultipleChoiceProps {
|
|
|
1235
1242
|
* Text when multiple items are selected, such as "2 items selected" / "3 items selected"
|
|
1236
1243
|
*/
|
|
1237
1244
|
dropdownMultiselectedText?: string;
|
|
1238
|
-
randomize:
|
|
1245
|
+
randomize: Randomize;
|
|
1239
1246
|
required: boolean;
|
|
1240
1247
|
};
|
|
1241
1248
|
}
|
|
@@ -1264,7 +1271,7 @@ interface MatrixCard extends BaseCard {
|
|
|
1264
1271
|
label: string;
|
|
1265
1272
|
value: string;
|
|
1266
1273
|
}[];
|
|
1267
|
-
randomize:
|
|
1274
|
+
randomize: Randomize;
|
|
1268
1275
|
required: boolean;
|
|
1269
1276
|
};
|
|
1270
1277
|
};
|
|
@@ -1272,26 +1279,49 @@ interface MatrixCard extends BaseCard {
|
|
|
1272
1279
|
}
|
|
1273
1280
|
interface NPSCard extends BaseCard {
|
|
1274
1281
|
props: {
|
|
1275
|
-
labels:
|
|
1276
|
-
left: string;
|
|
1277
|
-
right: string;
|
|
1278
|
-
};
|
|
1282
|
+
labels: Labels;
|
|
1279
1283
|
message: string;
|
|
1280
1284
|
options: [];
|
|
1281
1285
|
properties: {
|
|
1282
1286
|
buttonText?: string;
|
|
1283
1287
|
captionText: string;
|
|
1284
1288
|
conceptUrl: null;
|
|
1285
|
-
labels:
|
|
1286
|
-
left: string;
|
|
1287
|
-
right: string;
|
|
1288
|
-
};
|
|
1289
|
+
labels: Labels;
|
|
1289
1290
|
required: boolean;
|
|
1290
1291
|
};
|
|
1291
1292
|
routingOptions: RoutingOptions<"eq" | "gt" | "gte" | "lt" | "lte" | "neq">;
|
|
1292
1293
|
};
|
|
1293
1294
|
type: "nps";
|
|
1294
1295
|
}
|
|
1296
|
+
interface RankOrderOption {
|
|
1297
|
+
createdAt: string;
|
|
1298
|
+
deletedAt: null;
|
|
1299
|
+
id: number;
|
|
1300
|
+
label: string;
|
|
1301
|
+
order: number;
|
|
1302
|
+
productId: number;
|
|
1303
|
+
surveyId: number;
|
|
1304
|
+
surveyQuestionId: number;
|
|
1305
|
+
updatedAt: string;
|
|
1306
|
+
value: string;
|
|
1307
|
+
}
|
|
1308
|
+
interface RankOderType extends BaseCard {
|
|
1309
|
+
props: {
|
|
1310
|
+
labels: Labels;
|
|
1311
|
+
message: string;
|
|
1312
|
+
options: RankOrderOption[];
|
|
1313
|
+
properties: {
|
|
1314
|
+
captionText: string;
|
|
1315
|
+
buttonText?: string;
|
|
1316
|
+
conceptUrl: ConceptUrl;
|
|
1317
|
+
labels: Labels;
|
|
1318
|
+
required: boolean;
|
|
1319
|
+
randomize: Randomize;
|
|
1320
|
+
};
|
|
1321
|
+
routingOptions: RoutingOptions<"eq" | "gt" | "gte" | "lt" | "lte" | "neq">;
|
|
1322
|
+
};
|
|
1323
|
+
type: "rankorder";
|
|
1324
|
+
}
|
|
1295
1325
|
interface VideoVoiceCard extends BaseCard {
|
|
1296
1326
|
props: {
|
|
1297
1327
|
message: string;
|
|
@@ -1311,7 +1341,7 @@ interface VideoVoiceCard extends BaseCard {
|
|
|
1311
1341
|
};
|
|
1312
1342
|
type: "videovoice";
|
|
1313
1343
|
}
|
|
1314
|
-
type Card = TextUrlPromptCard | ConsentLegalCard | RecordedTaskCard | LikertCard | OpenTextCard | MatrixCard | MultipleChoiceSingleSelectCard | MultipleChoiceMultiSelectCard | NPSCard | VideoVoiceCard;
|
|
1344
|
+
type Card = TextUrlPromptCard | ConsentLegalCard | RecordedTaskCard | LikertCard | OpenTextCard | MatrixCard | MultipleChoiceSingleSelectCard | MultipleChoiceMultiSelectCard | NPSCard | RankOderType | VideoVoiceCard;
|
|
1315
1345
|
|
|
1316
1346
|
type InteractiveMatchType = "exactly" | "legacy";
|
|
1317
1347
|
type PageUrlMatchType = "contains" | "exactly" | "legacy" | "notContains" | "regex" | "startsWith";
|
|
@@ -1340,7 +1370,7 @@ declare enum DismissReason {
|
|
|
1340
1370
|
API = "api",// JS called Sprig('dismissActiveSurvey')
|
|
1341
1371
|
Override = "override"
|
|
1342
1372
|
}
|
|
1343
|
-
type StudyType = "feedbackButton" | "inProductSurvey";
|
|
1373
|
+
type StudyType = "feedbackButton" | "inProductSurvey" | "longFormSurvey";
|
|
1344
1374
|
declare enum SprigEvent {
|
|
1345
1375
|
ReplayCapture = "replay.capture",
|
|
1346
1376
|
ReplayPaused = "replay.paused",
|
|
@@ -1676,6 +1706,7 @@ interface Config extends MobileReplayConfig {
|
|
|
1676
1706
|
mode?: string;
|
|
1677
1707
|
mute?: boolean;
|
|
1678
1708
|
optimizelyEnabled?: boolean;
|
|
1709
|
+
outstandingTransactionLimit?: number | null;
|
|
1679
1710
|
overlayStyle: "light";
|
|
1680
1711
|
overlayStyleMobile: "none";
|
|
1681
1712
|
pageUrlEvents: PageUrlEvent[];
|
|
@@ -1946,6 +1977,7 @@ declare namespace sprigConfig {
|
|
|
1946
1977
|
locale?: string;
|
|
1947
1978
|
maxHeight?: number | string;
|
|
1948
1979
|
maxInflightReplayRequests?: number;
|
|
1980
|
+
outstandingTransactionLimit?: number | null;
|
|
1949
1981
|
mobileHeadersJSON?: string;
|
|
1950
1982
|
nonce?: string;
|
|
1951
1983
|
partnerAnonymousId: string | null;
|
|
@@ -2032,12 +2064,17 @@ declare class SprigAPI {
|
|
|
2032
2064
|
SURVEY_WILL_PRESENT: SprigEvent;
|
|
2033
2065
|
QUESTION_ANSWERED: SprigEvent;
|
|
2034
2066
|
REPLAY_CAPTURE: SprigEvent;
|
|
2035
|
-
CLOSE_SURVEY_ON_OVERLAY_CLICK: SprigEvent;
|
|
2067
|
+
CLOSE_SURVEY_ON_OVERLAY_CLICK: SprigEvent; /**
|
|
2068
|
+
* Tracks a page view with the provided URL and additional event properties.
|
|
2069
|
+
*/
|
|
2036
2070
|
VISITOR_ID_UPDATED: SprigEvent;
|
|
2037
2071
|
DATA: {
|
|
2038
2072
|
DISMISS_REASONS: {
|
|
2039
2073
|
API: DismissReason;
|
|
2040
2074
|
CLOSED: DismissReason;
|
|
2075
|
+
/**
|
|
2076
|
+
* Apply a css string representing the customized styles
|
|
2077
|
+
*/
|
|
2041
2078
|
COMPLETE: DismissReason;
|
|
2042
2079
|
PAGE_CHANGE: DismissReason;
|
|
2043
2080
|
OVERRIDE: DismissReason;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { S as i, c as o, s as p } from "./core-
|
|
1
|
+
import { S as i, c as o, s as p } from "./core-De2JxeSJ.js";
|
|
2
2
|
import "./replay.js";
|
|
3
|
-
import { D as t, S as m } from "./metricsReporter-
|
|
3
|
+
import { D as t, S as m } from "./metricsReporter-BJVpNufn.js";
|
|
4
4
|
export {
|
|
5
5
|
t as DismissReason,
|
|
6
6
|
i as SprigAPI,
|
|
@@ -183,7 +183,10 @@ class O {
|
|
|
183
183
|
this.isStorageAvailable && this.storage ? this.storage.clear() : this.tempStorage = {};
|
|
184
184
|
}
|
|
185
185
|
}
|
|
186
|
-
const se =
|
|
186
|
+
const se = (e, t) => {
|
|
187
|
+
const s = [e[t]], r = e[t].groupId;
|
|
188
|
+
return r ? e.slice(t).reduce((n, i) => (i.groupId === r && n.push(i), n), []) : s;
|
|
189
|
+
}, re = (e) => e === "longFormSurvey", ne = new O("sessionStorage"), ie = new O("localStorage");
|
|
187
190
|
class q {
|
|
188
191
|
constructor(t) {
|
|
189
192
|
l(this, "payload");
|
|
@@ -200,21 +203,21 @@ class q {
|
|
|
200
203
|
this.resolve(t);
|
|
201
204
|
}
|
|
202
205
|
}
|
|
203
|
-
const k = { replay: null },
|
|
206
|
+
const k = { replay: null }, ae = (e) => {
|
|
204
207
|
k.replay = e;
|
|
205
208
|
}, B = () => {
|
|
206
209
|
const e = [];
|
|
207
210
|
return k.replay && e.push("replay"), e.join(",");
|
|
208
211
|
}, F = 10;
|
|
209
212
|
let U = !1, A = "", y = !1, D = !1, g = [];
|
|
210
|
-
const J = (e) => e._config && e._config.installationMethod ? e._config.installationMethod : e._gtm ? "web-gtm" : e._segment ? "web-segment" : "web-snippet",
|
|
213
|
+
const J = (e) => e._config && e._config.installationMethod ? e._config.installationMethod : e._gtm ? "web-gtm" : e._segment ? "web-segment" : "web-snippet", oe = (e) => {
|
|
211
214
|
var t;
|
|
212
215
|
(t = e == null ? void 0 : e.blockedURI) != null && t.includes(window.UserLeap._API_URL) && (D = !0, console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`));
|
|
213
216
|
}, H = (e = "") => {
|
|
214
217
|
U = !0, A = e;
|
|
215
218
|
};
|
|
216
|
-
function
|
|
217
|
-
const t = { "Content-Type": "application/json", "userleap-platform": "web", "x-ul-sdk-version": "2.
|
|
219
|
+
function ce(e = {}) {
|
|
220
|
+
const t = { "Content-Type": "application/json", "userleap-platform": "web", "x-ul-sdk-version": "2.35.0", "x-ul-installation-method": J(e), "sprig-modules": B() };
|
|
218
221
|
if (e.envId && (t["x-ul-environment-id"] = e.envId), e.token && (t.Authorization = "Bearer " + e.token), e.userId && (t["x-ul-user-id"] = e.userId), e.visitorId && (t["x-ul-visitor-id"] = e.visitorId), e.partnerAnonymousId && (t["x-ul-anonymous-id"] = e.partnerAnonymousId), e.mobileHeadersJSON) {
|
|
219
222
|
const s = JSON.parse(e.mobileHeadersJSON);
|
|
220
223
|
Object.assign(t, s);
|
|
@@ -273,12 +276,12 @@ function $(e, t) {
|
|
|
273
276
|
}
|
|
274
277
|
return i;
|
|
275
278
|
}
|
|
276
|
-
const
|
|
279
|
+
const le = (e) => {
|
|
277
280
|
const { pageUrlEvents: t } = window.UserLeap._config, s = t == null ? void 0 : t.find((r) => r.id === e);
|
|
278
281
|
return !!s && $(s, window.location.href);
|
|
279
282
|
};
|
|
280
283
|
let C = !0, S = !1;
|
|
281
|
-
const
|
|
284
|
+
const de = () => S = !0, K = ["sdk_event_queue_latency_seconds", "sdk_replay_add_event_batch_seconds", "sdk_replay_cleanup_seconds", "sdk_replay_compression_seconds", "sdk_replay_get_events_between_seconds", "sdk_replay_snapshot_seconds", "sdk_mutations_nodes_added", "sdk_mutations_nodes_removed", "sdk_mutations_attributes_changed", "sdk_mutations_character_data", "sdk_dom_nodes_count", "sdk_page_html_characters"];
|
|
282
285
|
let _, p = {};
|
|
283
286
|
class G {
|
|
284
287
|
constructor(t) {
|
|
@@ -303,7 +306,7 @@ class G {
|
|
|
303
306
|
return s.type === "max" ? t > s.value : s.type === "min" && t < s.value;
|
|
304
307
|
}
|
|
305
308
|
}
|
|
306
|
-
const
|
|
309
|
+
const ue = (e, t) => {
|
|
307
310
|
p = {}, S = !1, e == null || e.forEach((s) => {
|
|
308
311
|
var r;
|
|
309
312
|
s.metric in p || (p[s.metric] = []), (r = p[s.metric]) == null || r.push(s);
|
|
@@ -311,10 +314,10 @@ const le = (e, t) => {
|
|
|
311
314
|
}, E = {}, z = (e) => {
|
|
312
315
|
const t = new G(e);
|
|
313
316
|
return E[e] = t, t;
|
|
314
|
-
},
|
|
317
|
+
}, he = (e, t) => {
|
|
315
318
|
let s = E[e];
|
|
316
319
|
return s || (s = z(e)), s.report(t);
|
|
317
|
-
},
|
|
320
|
+
}, pe = ({ reportingIntervalSeconds: e, postMetrics: t }) => {
|
|
318
321
|
e ? setInterval(() => {
|
|
319
322
|
(async (s) => {
|
|
320
323
|
const r = Object.values(E).map((n) => ({ name: n.name, values: n.collect() }));
|
|
@@ -331,24 +334,26 @@ export {
|
|
|
331
334
|
X as E,
|
|
332
335
|
E as P,
|
|
333
336
|
N as S,
|
|
334
|
-
|
|
337
|
+
ne as a,
|
|
335
338
|
Y as b,
|
|
336
|
-
|
|
337
|
-
|
|
339
|
+
le as c,
|
|
340
|
+
he as d,
|
|
338
341
|
ee as e,
|
|
339
|
-
|
|
340
|
-
|
|
342
|
+
ae as f,
|
|
343
|
+
ce as g,
|
|
341
344
|
te as h,
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
345
|
+
ue as i,
|
|
346
|
+
pe as j,
|
|
347
|
+
de as k,
|
|
348
|
+
ie as l,
|
|
346
349
|
k as m,
|
|
347
|
-
|
|
350
|
+
oe as n,
|
|
348
351
|
H as o,
|
|
349
352
|
$ as p,
|
|
350
353
|
L as q,
|
|
351
354
|
z as r,
|
|
352
355
|
v as s,
|
|
356
|
+
re as t,
|
|
357
|
+
se as u,
|
|
353
358
|
Z as v
|
|
354
359
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Y=Object.defineProperty;var j=(e,t,r)=>t in e?Y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var l=(e,t,r)=>j(e,typeof t!="symbol"?t+"":t,r);var U=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.FeedbackClosed="feedback.closed",e.PageChange="page.change",e.API="api",e.Override="override",e))(U||{}),A=(e=>(e.ReplayCapture="replay.capture",e.ReplayPaused="replay.paused",e.ReplayResumed="replay.resumed",e.FeedbackButtonLoaded="feedback.button.loaded",e.SDKReady="sdk.ready",e.SurveyAppeared="survey.appeared",e.SurveyCloseRequested="survey.closeRequested",e.SurveyClosed="survey.closed",e.SurveyDimensions="survey.dimensions",e.SurveyFadingOut="survey.fadingOut",e.SurveyHeight="survey.height",e.SurveyPresented="survey.presented",e.SurveyLifeCycle="survey.lifeCycle",e.SurveyWidth="survey.width",e.SurveyWillClose="survey.willClose",e.SurveyWillPresent="survey.will.present",e.CloseSurveyOnOverlayClick="close.survey.overlayClick",e.VisitorIDUpdated="visitor.id.updated",e.QuestionAnswered="question.answered",e))(A||{});let m;const H=new Uint8Array(16);function q(){if(!m&&(m=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!m))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return m(H)}const a=[];for(let e=0;e<256;++e)a.push((e+256).toString(16).slice(1));const w={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)},b=new class{constructor(){l(this,"breadcrumbs",[])}getTimeStamp(){return new Date().toISOString()}addBreadcrumb(e){this.breadcrumbs.push(e),this.breadcrumbs.length>300&&this.breadcrumbs.shift()}debug(e,t="debug"){this.addBreadcrumb({category:t,level:"info",message:e,timestamp:this.getTimeStamp(),type:"debug"})}error(e,t={}){this.addBreadcrumb({category:"error",data:t,level:"error",message:e,timestamp:this.getTimeStamp(),type:"error"})}http(e,t){this.addBreadcrumb({category:"xhr",data:t,message:e,timestamp:this.getTimeStamp(),type:"http"})}info(e,t={}){this.addBreadcrumb({category:"info",data:t,level:"info",message:e,timestamp:this.getTimeStamp(),type:"info"})}navigation(e,t){this.addBreadcrumb({category:"navigation",data:t,message:e,timestamp:this.getTimeStamp(),type:"navigation"})}};var B=class extends Error{constructor(e,t,r){super(`Possible EventEmitter memory leak detected. ${r} ${t.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`),this.emitter=e,this.type=t,this.count=r,this.name="MaxListenersExceededWarning"}},D=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=D.defaultMaxListeners,this.hasWarnedAboutPotentialMemoryLeak=!1}_emitInternalEvent(e,t,r){this.emit(e,t,r)}_getListeners(e){return Array.prototype.concat.apply([],this.events.get(e))||[]}_removeListener(e,t){const r=e.indexOf(t);return r>-1&&e.splice(r,1),[]}_wrapOnceListener(e,t){const r=(...s)=>(this.removeListener(e,r),t.apply(this,s));return Object.defineProperty(r,"name",{value:t.name}),r}setMaxListeners(e){return this.maxListeners=e,this}getMaxListeners(){return this.maxListeners}eventNames(){return Array.from(this.events.keys())}emit(e,...t){const r=this._getListeners(e);return r.forEach(s=>{s.apply(this,t)}),r.length>0}addListener(e,t){this._emitInternalEvent("newListener",e,t);const r=this._getListeners(e).concat(t);if(this.events.set(e,r),this.maxListeners>0&&this.listenerCount(e)>this.maxListeners&&!this.hasWarnedAboutPotentialMemoryLeak){this.hasWarnedAboutPotentialMemoryLeak=!0;const s=new B(this,e,this.listenerCount(e));console.warn(s)}return this}on(e,t){return this.addListener(e,t)}once(e,t){return this.addListener(e,this._wrapOnceListener(e,t))}prependListener(e,t){const r=this._getListeners(e);if(r.length>0){const s=[t].concat(r);this.events.set(e,s)}else this.events.set(e,r.concat(t));return this}prependOnceListener(e,t){return this.prependListener(e,this._wrapOnceListener(e,t))}removeListener(e,t){const r=this._getListeners(e);return r.length>0&&(this._removeListener(r,t),this.events.set(e,r),this._emitInternalEvent("removeListener",e,t)),this}off(e,t){return this.removeListener(e,t)}removeAllListeners(e){return e?this.events.delete(e):this.events.clear(),this}listeners(e){return Array.from(this._getListeners(e))}listenerCount(e){return this._getListeners(e).length}rawListeners(e){return this.listeners(e)}},C=D;C.defaultMaxListeners=10;const F=new C,S=async e=>{await new Promise(t=>{setTimeout(t,e)})};class x{constructor(t){l(this,"storage");l(this,"tempStorage",{});l(this,"isStorageAvailable");try{this.storage=window[t];const r="__storage_test__";this.storage.setItem(r,r),this.storage.removeItem(r),this.isStorageAvailable=!0}catch{this.isStorageAvailable=!1}}setItem(t,r){this.isStorageAvailable&&this.storage?this.storage.setItem(t,r):this.tempStorage[t]=r}setItemObject(t,r){try{this.setItem(t,JSON.stringify(r))}catch(s){s instanceof Error&&(s.stack=t+": "+r,window.UserLeap.reportError("Failed to save to local storage",s))}}getItem(t){return this.isStorageAvailable&&this.storage?this.storage.getItem(t):this.tempStorage[t]}getItemObject(t){const r=this.getItem(t);if(r)try{return JSON.parse(r)}catch(s){s instanceof Error&&(s.stack=t+": "+r,window.UserLeap.reportError("Failed to parse local storage",s))}return{}}removeItem(t){this.isStorageAvailable&&this.storage?this.storage.removeItem(t):delete this.tempStorage[t]}clear(){this.isStorageAvailable&&this.storage?this.storage.clear():this.tempStorage={}}}const J=new x("sessionStorage"),$=new x("localStorage");class K{constructor(t){l(this,"payload");l(this,"promise");l(this,"reject",()=>{});l(this,"resolve",()=>{});this.payload=t,this.promise=new Promise((r,s)=>{this.reject=s,this.resolve=r})}resolveRequest(t){this.resolve(t)}}const E={replay:null},G=()=>{const e=[];return E.replay&&e.push("replay"),e.join(",")},z=10;let T=!1,M="",g=!1,P=!1,y=[];const Q=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?"web-gtm":e._segment?"web-segment":"web-snippet",N=(e="")=>{T=!0,M=e},R=async({shouldDropOnRateLimit:e,...t})=>{if(e)return{status:429};{const r=new K(t);return y.push(r),r.promise}},v=async(e,t)=>{const{retries:r=0,shouldDropOnRateLimit:s=!1,shouldRetryRequest:i=!1,...n}=t,d={url:e,options:n,retries:r,shouldDropOnRateLimit:s};if(g&&!i)return R(d);const u={ok:!1,reportError:!1};if(T)return console.info(`UserLeap - ${M}`),u;try{const c=await fetch(e,n);if(c.status===429){if(!g&&!s||i){g=!0;const o=c.headers.has("ratelimit-reset")?Number(c.headers.get("ratelimit-reset")):z;return await S(1e3*o),v(e,{...n,shouldDropOnRateLimit:s,shouldRetryRequest:!0})}return R(d)}if(g=!1,y.length&&(y.map(o=>{const h=o.payload;v(h.url,{...h.options,retries:h.retries,shouldDropOnRateLimit:h.shouldDropOnRateLimit}).then(W=>{o.resolveRequest(W)})}),y=[]),c.ok){if(c.status===249)return N(),u;const o=await c.text();try{return o&&o!=="OK"&&(c.json=JSON.parse(o)),c}catch{return{ok:!1,reportError:!1,error:new Error(`failed parsing response json for ${e} - ${o}`)}}}return c}catch(c){const o=r+1;return o>5||P?{ok:!1,reportError:!1,error:c}:(await S(1e3*Math.pow(2,r)),v(e,{...n,retries:o}))}},I=Object.freeze({contains:(e,t)=>t.includes(e),notContains:(e,t)=>!t.includes(e),exactly:(e,t)=>t===e,notExactly:(e,t)=>t!==e,startsWith:(e,t)=>t.startsWith(e),endsWith:(e,t)=>t.endsWith(e),regex:(e,t)=>new RegExp(e).test(t),legacy:(e,t)=>new RegExp(e,"i").test(t)});function k(e,t){const{matchType:r,pattern:s}=e,i=r?I[r]:I.legacy;let n=!1;try{n=i(s,t)}catch(d){const u=`[Sprig] (ERR-445) Failed to check url match with pattern ${s}`;d instanceof Error&&(console.warn(u,d),d.stack=JSON.stringify(e),window.UserLeap.reportError(u,d))}return n}let V=!0,f=!1;const X=["sdk_event_queue_latency_seconds","sdk_replay_add_event_batch_seconds","sdk_replay_cleanup_seconds","sdk_replay_compression_seconds","sdk_replay_get_events_between_seconds","sdk_replay_snapshot_seconds","sdk_mutations_nodes_added","sdk_mutations_nodes_removed","sdk_mutations_attributes_changed","sdk_mutations_character_data","sdk_dom_nodes_count","sdk_page_html_characters"];let L,p={};class Z{constructor(t){l(this,"_values",[]);l(this,"_isWebMetric");this.name=t,this._isWebMetric=X.includes(this.name)}report(t){if(V&&this._values.push({time:Date.now(),value:t}),f||!this._isWebMetric)return;const r=this.findExceededThreshold(t);r&&L&&L(t,r)}collect(){const t=this._values;return this._values=[],t}findExceededThreshold(t){const r=p[this.name];if(r)return r.find(s=>this.valueExceedsThreshold(t,s))}valueExceedsThreshold(t,r){return r.type==="max"?t>r.value:r.type==="min"&&t<r.value}}const _={},O=e=>{const t=new Z(e);return _[e]=t,t};exports.DismissReason=U,exports.EVENTS={FEEDBACK_BUTTON_LOADED:"feedback.button.loaded",SDK_READY:"sdk.ready",SURVEY_APPEARED:"survey.appeared",SURVEY_CLOSED:"survey.closed",SURVEY_DIMENSIONS:"survey.dimensions",SURVEY_FADING_OUT:"survey.fadingOut",SURVEY_HEIGHT:"survey.height",SURVEY_WIDTH:"survey.width",SURVEY_PRESENTED:"survey.presented",SURVEY_LIFE_CYCLE:"survey.lifeCycle",SURVEY_WILL_CLOSE:"survey.willClose",SURVEY_WILL_PRESENT:"survey.will.present",QUESTION_ANSWERED:"question.answered",REPLAY_CAPTURE:"replay.capture",CLOSE_SURVEY_ON_OVERLAY_CLICK:"close.survey.overlayClick",VISITOR_ID_UPDATED:"visitor.id.updated",DATA:{DISMISS_REASONS:{API:"api",CLOSED:"close.click",COMPLETE:"survey.completed",PAGE_CHANGE:"page.change",OVERRIDE:"override"},SURVEY_ID:"survey.id"}},exports.PerformanceMetrics=_,exports.SprigEvent=A,exports.breadcrumbsLogger=b,exports.checkUrlMatch=k,exports.checkUrlStillMatching=e=>{const{pageUrlEvents:t}=window.UserLeap._config,r=t==null?void 0:t.find(s=>s.id===e);return!!r&&k(r,window.location.href)},exports.cspViolationHandler=e=>{var t;(t=e==null?void 0:e.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(P=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`))},exports.delay=S,exports.disableThresholdChecking=()=>f=!0,exports.eventEmitter=F,exports.getHttpHeaders=function(e={}){const t={"Content-Type":"application/json","userleap-platform":"web","x-ul-sdk-version":"2.34.0","x-ul-installation-method":Q(e),"sprig-modules":G()};if(e.envId&&(t["x-ul-environment-id"]=e.envId),e.token&&(t.Authorization="Bearer "+e.token),e.userId&&(t["x-ul-user-id"]=e.userId),e.visitorId&&(t["x-ul-visitor-id"]=e.visitorId),e.partnerAnonymousId&&(t["x-ul-anonymous-id"]=e.partnerAnonymousId),e.mobileHeadersJSON){const r=JSON.parse(e.mobileHeadersJSON);Object.assign(t,r)}return e.locale&&(t["accept-language"]=e.locale),window.previewMode&&(t["x-ul-preview-mode"]="1"),t},exports.initPerformanceReporting=({reportingIntervalSeconds:e,postMetrics:t})=>{e?setInterval(()=>{(async r=>{const s=Object.values(_).map(i=>({name:i.name,values:i.collect()}));if(s.some(i=>i.values.length))try{await r(JSON.stringify(s))}catch(i){i instanceof Error&&b.error("MetricsErr",{error:{message:i.message,name:i.name}})}})(t)},1e3*e):V=!1},exports.killNetworkRequests=N,exports.localStorageHelper=$,exports.modules=E,exports.registerMetric=O,exports.registerReplay=e=>{E.replay=e},exports.registerThresholds=(e,t)=>{p={},f=!1,e==null||e.forEach(r=>{var s;r.metric in p||(p[r.metric]=[]),(s=p[r.metric])==null||s.push(r)}),L=t},exports.reportAndRegister=(e,t)=>{let r=_[e];return r||(r=O(e)),r.report(t)},exports.sessionStorageHelper=J,exports.shouldDirectEmbed=({"userleap-platform":e})=>{var t;return((t=window.UserLeap)==null?void 0:t.forceDirectEmbed)||e!=="web"},exports.sprigFetch=v,exports.v4=function(e,t,r){if(w.randomUUID&&!e)return w.randomUUID();const s=(e=e||{}).random||(e.rng||q)();return s[6]=15&s[6]|64,s[8]=63&s[8]|128,function(i,n=0){return a[i[n+0]]+a[i[n+1]]+a[i[n+2]]+a[i[n+3]]+"-"+a[i[n+4]]+a[i[n+5]]+"-"+a[i[n+6]]+a[i[n+7]]+"-"+a[i[n+8]]+a[i[n+9]]+"-"+a[i[n+10]]+a[i[n+11]]+a[i[n+12]]+a[i[n+13]]+a[i[n+14]]+a[i[n+15]]}(s)};
|
|
1
|
+
"use strict";var Y=Object.defineProperty;var j=(e,t,r)=>t in e?Y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var l=(e,t,r)=>j(e,typeof t!="symbol"?t+"":t,r);var U=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.FeedbackClosed="feedback.closed",e.PageChange="page.change",e.API="api",e.Override="override",e))(U||{}),A=(e=>(e.ReplayCapture="replay.capture",e.ReplayPaused="replay.paused",e.ReplayResumed="replay.resumed",e.FeedbackButtonLoaded="feedback.button.loaded",e.SDKReady="sdk.ready",e.SurveyAppeared="survey.appeared",e.SurveyCloseRequested="survey.closeRequested",e.SurveyClosed="survey.closed",e.SurveyDimensions="survey.dimensions",e.SurveyFadingOut="survey.fadingOut",e.SurveyHeight="survey.height",e.SurveyPresented="survey.presented",e.SurveyLifeCycle="survey.lifeCycle",e.SurveyWidth="survey.width",e.SurveyWillClose="survey.willClose",e.SurveyWillPresent="survey.will.present",e.CloseSurveyOnOverlayClick="close.survey.overlayClick",e.VisitorIDUpdated="visitor.id.updated",e.QuestionAnswered="question.answered",e))(A||{});let m;const F=new Uint8Array(16);function H(){if(!m&&(m=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!m))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return m(F)}const o=[];for(let e=0;e<256;++e)o.push((e+256).toString(16).slice(1));const w={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)},b=new class{constructor(){l(this,"breadcrumbs",[])}getTimeStamp(){return new Date().toISOString()}addBreadcrumb(e){this.breadcrumbs.push(e),this.breadcrumbs.length>300&&this.breadcrumbs.shift()}debug(e,t="debug"){this.addBreadcrumb({category:t,level:"info",message:e,timestamp:this.getTimeStamp(),type:"debug"})}error(e,t={}){this.addBreadcrumb({category:"error",data:t,level:"error",message:e,timestamp:this.getTimeStamp(),type:"error"})}http(e,t){this.addBreadcrumb({category:"xhr",data:t,message:e,timestamp:this.getTimeStamp(),type:"http"})}info(e,t={}){this.addBreadcrumb({category:"info",data:t,level:"info",message:e,timestamp:this.getTimeStamp(),type:"info"})}navigation(e,t){this.addBreadcrumb({category:"navigation",data:t,message:e,timestamp:this.getTimeStamp(),type:"navigation"})}};var q=class extends Error{constructor(e,t,r){super(`Possible EventEmitter memory leak detected. ${r} ${t.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`),this.emitter=e,this.type=t,this.count=r,this.name="MaxListenersExceededWarning"}},C=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=C.defaultMaxListeners,this.hasWarnedAboutPotentialMemoryLeak=!1}_emitInternalEvent(e,t,r){this.emit(e,t,r)}_getListeners(e){return Array.prototype.concat.apply([],this.events.get(e))||[]}_removeListener(e,t){const r=e.indexOf(t);return r>-1&&e.splice(r,1),[]}_wrapOnceListener(e,t){const r=(...s)=>(this.removeListener(e,r),t.apply(this,s));return Object.defineProperty(r,"name",{value:t.name}),r}setMaxListeners(e){return this.maxListeners=e,this}getMaxListeners(){return this.maxListeners}eventNames(){return Array.from(this.events.keys())}emit(e,...t){const r=this._getListeners(e);return r.forEach(s=>{s.apply(this,t)}),r.length>0}addListener(e,t){this._emitInternalEvent("newListener",e,t);const r=this._getListeners(e).concat(t);if(this.events.set(e,r),this.maxListeners>0&&this.listenerCount(e)>this.maxListeners&&!this.hasWarnedAboutPotentialMemoryLeak){this.hasWarnedAboutPotentialMemoryLeak=!0;const s=new q(this,e,this.listenerCount(e));console.warn(s)}return this}on(e,t){return this.addListener(e,t)}once(e,t){return this.addListener(e,this._wrapOnceListener(e,t))}prependListener(e,t){const r=this._getListeners(e);if(r.length>0){const s=[t].concat(r);this.events.set(e,s)}else this.events.set(e,r.concat(t));return this}prependOnceListener(e,t){return this.prependListener(e,this._wrapOnceListener(e,t))}removeListener(e,t){const r=this._getListeners(e);return r.length>0&&(this._removeListener(r,t),this.events.set(e,r),this._emitInternalEvent("removeListener",e,t)),this}off(e,t){return this.removeListener(e,t)}removeAllListeners(e){return e?this.events.delete(e):this.events.clear(),this}listeners(e){return Array.from(this._getListeners(e))}listenerCount(e){return this._getListeners(e).length}rawListeners(e){return this.listeners(e)}},D=C;D.defaultMaxListeners=10;const B=new D,S=async e=>{await new Promise(t=>{setTimeout(t,e)})};class x{constructor(t){l(this,"storage");l(this,"tempStorage",{});l(this,"isStorageAvailable");try{this.storage=window[t];const r="__storage_test__";this.storage.setItem(r,r),this.storage.removeItem(r),this.isStorageAvailable=!0}catch{this.isStorageAvailable=!1}}setItem(t,r){this.isStorageAvailable&&this.storage?this.storage.setItem(t,r):this.tempStorage[t]=r}setItemObject(t,r){try{this.setItem(t,JSON.stringify(r))}catch(s){s instanceof Error&&(s.stack=t+": "+r,window.UserLeap.reportError("Failed to save to local storage",s))}}getItem(t){return this.isStorageAvailable&&this.storage?this.storage.getItem(t):this.tempStorage[t]}getItemObject(t){const r=this.getItem(t);if(r)try{return JSON.parse(r)}catch(s){s instanceof Error&&(s.stack=t+": "+r,window.UserLeap.reportError("Failed to parse local storage",s))}return{}}removeItem(t){this.isStorageAvailable&&this.storage?this.storage.removeItem(t):delete this.tempStorage[t]}clear(){this.isStorageAvailable&&this.storage?this.storage.clear():this.tempStorage={}}}const J=new x("sessionStorage"),$=new x("localStorage");class K{constructor(t){l(this,"payload");l(this,"promise");l(this,"reject",()=>{});l(this,"resolve",()=>{});this.payload=t,this.promise=new Promise((r,s)=>{this.reject=s,this.resolve=r})}resolveRequest(t){this.resolve(t)}}const E={replay:null},G=()=>{const e=[];return E.replay&&e.push("replay"),e.join(",")},z=10;let T=!1,M="",g=!1,P=!1,y=[];const Q=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?"web-gtm":e._segment?"web-segment":"web-snippet",N=(e="")=>{T=!0,M=e},R=async({shouldDropOnRateLimit:e,...t})=>{if(e)return{status:429};{const r=new K(t);return y.push(r),r.promise}},v=async(e,t)=>{const{retries:r=0,shouldDropOnRateLimit:s=!1,shouldRetryRequest:n=!1,...i}=t,d={url:e,options:i,retries:r,shouldDropOnRateLimit:s};if(g&&!n)return R(d);const u={ok:!1,reportError:!1};if(T)return console.info(`UserLeap - ${M}`),u;try{const c=await fetch(e,i);if(c.status===429){if(!g&&!s||n){g=!0;const a=c.headers.has("ratelimit-reset")?Number(c.headers.get("ratelimit-reset")):z;return await S(1e3*a),v(e,{...i,shouldDropOnRateLimit:s,shouldRetryRequest:!0})}return R(d)}if(g=!1,y.length&&(y.map(a=>{const h=a.payload;v(h.url,{...h.options,retries:h.retries,shouldDropOnRateLimit:h.shouldDropOnRateLimit}).then(W=>{a.resolveRequest(W)})}),y=[]),c.ok){if(c.status===249)return N(),u;const a=await c.text();try{return a&&a!=="OK"&&(c.json=JSON.parse(a)),c}catch{return{ok:!1,reportError:!1,error:new Error(`failed parsing response json for ${e} - ${a}`)}}}return c}catch(c){const a=r+1;return a>5||P?{ok:!1,reportError:!1,error:c}:(await S(1e3*Math.pow(2,r)),v(e,{...i,retries:a}))}},I=Object.freeze({contains:(e,t)=>t.includes(e),notContains:(e,t)=>!t.includes(e),exactly:(e,t)=>t===e,notExactly:(e,t)=>t!==e,startsWith:(e,t)=>t.startsWith(e),endsWith:(e,t)=>t.endsWith(e),regex:(e,t)=>new RegExp(e).test(t),legacy:(e,t)=>new RegExp(e,"i").test(t)});function k(e,t){const{matchType:r,pattern:s}=e,n=r?I[r]:I.legacy;let i=!1;try{i=n(s,t)}catch(d){const u=`[Sprig] (ERR-445) Failed to check url match with pattern ${s}`;d instanceof Error&&(console.warn(u,d),d.stack=JSON.stringify(e),window.UserLeap.reportError(u,d))}return i}let V=!0,f=!1;const X=["sdk_event_queue_latency_seconds","sdk_replay_add_event_batch_seconds","sdk_replay_cleanup_seconds","sdk_replay_compression_seconds","sdk_replay_get_events_between_seconds","sdk_replay_snapshot_seconds","sdk_mutations_nodes_added","sdk_mutations_nodes_removed","sdk_mutations_attributes_changed","sdk_mutations_character_data","sdk_dom_nodes_count","sdk_page_html_characters"];let L,p={};class Z{constructor(t){l(this,"_values",[]);l(this,"_isWebMetric");this.name=t,this._isWebMetric=X.includes(this.name)}report(t){if(V&&this._values.push({time:Date.now(),value:t}),f||!this._isWebMetric)return;const r=this.findExceededThreshold(t);r&&L&&L(t,r)}collect(){const t=this._values;return this._values=[],t}findExceededThreshold(t){const r=p[this.name];if(r)return r.find(s=>this.valueExceedsThreshold(t,s))}valueExceedsThreshold(t,r){return r.type==="max"?t>r.value:r.type==="min"&&t<r.value}}const _={},O=e=>{const t=new Z(e);return _[e]=t,t};exports.DismissReason=U,exports.EVENTS={FEEDBACK_BUTTON_LOADED:"feedback.button.loaded",SDK_READY:"sdk.ready",SURVEY_APPEARED:"survey.appeared",SURVEY_CLOSED:"survey.closed",SURVEY_DIMENSIONS:"survey.dimensions",SURVEY_FADING_OUT:"survey.fadingOut",SURVEY_HEIGHT:"survey.height",SURVEY_WIDTH:"survey.width",SURVEY_PRESENTED:"survey.presented",SURVEY_LIFE_CYCLE:"survey.lifeCycle",SURVEY_WILL_CLOSE:"survey.willClose",SURVEY_WILL_PRESENT:"survey.will.present",QUESTION_ANSWERED:"question.answered",REPLAY_CAPTURE:"replay.capture",CLOSE_SURVEY_ON_OVERLAY_CLICK:"close.survey.overlayClick",VISITOR_ID_UPDATED:"visitor.id.updated",DATA:{DISMISS_REASONS:{API:"api",CLOSED:"close.click",COMPLETE:"survey.completed",PAGE_CHANGE:"page.change",OVERRIDE:"override"},SURVEY_ID:"survey.id"}},exports.PerformanceMetrics=_,exports.SprigEvent=A,exports.breadcrumbsLogger=b,exports.checkUrlMatch=k,exports.checkUrlStillMatching=e=>{const{pageUrlEvents:t}=window.UserLeap._config,r=t==null?void 0:t.find(s=>s.id===e);return!!r&&k(r,window.location.href)},exports.cspViolationHandler=e=>{var t;(t=e==null?void 0:e.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(P=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`))},exports.delay=S,exports.disableThresholdChecking=()=>f=!0,exports.eventEmitter=B,exports.getHttpHeaders=function(e={}){const t={"Content-Type":"application/json","userleap-platform":"web","x-ul-sdk-version":"2.35.0","x-ul-installation-method":Q(e),"sprig-modules":G()};if(e.envId&&(t["x-ul-environment-id"]=e.envId),e.token&&(t.Authorization="Bearer "+e.token),e.userId&&(t["x-ul-user-id"]=e.userId),e.visitorId&&(t["x-ul-visitor-id"]=e.visitorId),e.partnerAnonymousId&&(t["x-ul-anonymous-id"]=e.partnerAnonymousId),e.mobileHeadersJSON){const r=JSON.parse(e.mobileHeadersJSON);Object.assign(t,r)}return e.locale&&(t["accept-language"]=e.locale),window.previewMode&&(t["x-ul-preview-mode"]="1"),t},exports.groupCards=(e,t)=>{const r=[e[t]],s=e[t].groupId;return s?e.slice(t).reduce((n,i)=>(i.groupId===s&&n.push(i),n),[]):r},exports.initPerformanceReporting=({reportingIntervalSeconds:e,postMetrics:t})=>{e?setInterval(()=>{(async r=>{const s=Object.values(_).map(n=>({name:n.name,values:n.collect()}));if(s.some(n=>n.values.length))try{await r(JSON.stringify(s))}catch(n){n instanceof Error&&b.error("MetricsErr",{error:{message:n.message,name:n.name}})}})(t)},1e3*e):V=!1},exports.isLongFormSurvey=e=>e==="longFormSurvey",exports.killNetworkRequests=N,exports.localStorageHelper=$,exports.modules=E,exports.registerMetric=O,exports.registerReplay=e=>{E.replay=e},exports.registerThresholds=(e,t)=>{p={},f=!1,e==null||e.forEach(r=>{var s;r.metric in p||(p[r.metric]=[]),(s=p[r.metric])==null||s.push(r)}),L=t},exports.reportAndRegister=(e,t)=>{let r=_[e];return r||(r=O(e)),r.report(t)},exports.sessionStorageHelper=J,exports.shouldDirectEmbed=({"userleap-platform":e})=>{var t;return((t=window.UserLeap)==null?void 0:t.forceDirectEmbed)||e!=="web"},exports.sprigFetch=v,exports.v4=function(e,t,r){if(w.randomUUID&&!e)return w.randomUUID();const s=(e=e||{}).random||(e.rng||H)();return s[6]=15&s[6]|64,s[8]=63&s[8]|128,function(n,i=0){return o[n[i+0]]+o[n[i+1]]+o[n[i+2]]+o[n[i+3]]+"-"+o[n[i+4]]+o[n[i+5]]+"-"+o[n[i+6]]+o[n[i+7]]+"-"+o[n[i+8]]+o[n[i+9]]+"-"+o[n[i+10]]+o[n[i+11]]+o[n[i+12]]+o[n[i+13]]+o[n[i+14]]+o[n[i+15]]}(s)};
|
package/dist/replay.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Ze=Object.defineProperty;var et=(e,t,r)=>t in e?Ze(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var J=(e,t,r)=>et(e,typeof t!="symbol"?t+"":t,r);const o=require("./metricsReporter-Cc-ZSIZD.cjs");var L=(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))(L||{}),k=(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))(k||{});const Y=(e,t)=>t.some(r=>e instanceof r);let we,ye;const Z=new WeakMap,q=new WeakMap,G=new WeakMap;let ee={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return Z.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return B(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&(t==="done"||t==="store")||t in e};function De(e){ee=e(ee)}function tt(e){return(ye||(ye=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(te(this),t),B(this.request)}:function(...t){return B(e.apply(te(this),t))}}function rt(e){return typeof e=="function"?tt(e):(e instanceof IDBTransaction&&function(t){if(Z.has(t))return;const r=new Promise((n,a)=>{const s=()=>{a(t.error||new DOMException("AbortError","AbortError"))};t.oncomplete=()=>{n()},t.onerror=s,t.onabort=s});Z.set(t,r)}(e),Y(e,we||(we=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,ee):e)}function B(e){if(e instanceof IDBRequest)return function(r){const n=new Promise((a,s)=>{r.onsuccess=()=>{a(B(r.result))},r.onerror=()=>{s(r.error)}});return G.set(n,r),n}(e);if(q.has(e))return q.get(e);const t=rt(e);return t!==e&&(q.set(e,t),G.set(t,e)),t}const te=e=>G.get(e);function re(e,{blocked:t}={}){const r=indexedDB.deleteDatabase(e);return t&&(r.onblocked=n=>t(n.oldVersion,n)),B(r).then(()=>{})}const nt=["get","getKey","getAll","getAllKeys","count"],at=["put","add","delete","clear"],z=new Map;function fe(e,t){if(!(e instanceof IDBDatabase)||t in e||typeof t!="string")return;if(z.get(t))return z.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,a=at.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!a&&!nt.includes(r))return;const s=async function(i,...c){const d=this.transaction(i,a?"readwrite":"readonly");let u=d.store;return n&&(u=u.index(c.shift())),(await Promise.all([u[r](...c),a&&d.done]))[0]};return z.set(t,s),s}De(e=>({...e,get:(t,r,n)=>fe(t,r)||e.get(t,r,n),has:(t,r)=>!!fe(t,r)||e.has(t,r)}));const st=["continue","continuePrimaryKey","advance"],he={},ne=new WeakMap,Ee=new WeakMap,ot={get(e,t){if(!st.includes(t))return e[t];let r=he[t];return r||(r=he[t]=function(...n){ne.set(this,Ee.get(this)[t](...n))}),r}};async function*it(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const r=new Proxy(t,ot);for(Ee.set(r,t),G.set(r,te(t));t;)yield r,t=await(ne.get(r)||t.continue()),ne.delete(r)}function Ie(e,t){return t===Symbol.asyncIterator&&Y(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&Y(e,[IDBIndex,IDBObjectStore])}De(e=>({...e,get:(t,r,n)=>Ie(t,r)?it:e.get(t,r,n),has:(t,r)=>Ie(t,r)||e.has(t,r)}));const dt="sprigReplayIframeLoaded",ct="sprigReplayIframeSettings",ut="sprigReplayIframeTakeFullSnapshot",lt="sprigReplayTeardown",le=[],Re=new class{constructor(e){J(this,"awaitingResolvers",[]);J(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),Ce=async({apiUrl:e,surveyId:t,uploadId:r,etags:n,headers:a,responseGroupUuid:s,replayDuration:i,eventDigest:c},d=!1)=>{var w;if(!d&&!r&&!n)return void o.breadcrumbsLogger.error("UploadErr",{isMobile:d,uploadId:r,etags:n});o.breadcrumbsLogger.info("MarkUploadComplete",{surveyId:t});const u=await o.sprigFetch(`${e}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:n,uploadId:r,responseGroupUuid:s,surveyId:t,replayDuration:i,eventDigest:c,userAgent:(w=window==null?void 0:window.navigator)==null?void 0:w.userAgent}),headers:a,shouldRetryRequest:!0});return o.breadcrumbsLogger.info("MarkUploadDone",{surveyId:t}),u},pt=e=>{if(e instanceof Attr)return null;let t=1;for(let r=e.previousSibling;r;r=r.previousSibling)r.nodeName===e.nodeName&&++t;return t},Pe=e=>{if(e===null)return"";const t=[];if(e instanceof Document)return"/";for(let r=e;r&&!(r instanceof Document)&&r!==null;r=r instanceof Attr?r.ownerElement:r.parentElement){const n=t[t.length]={name:void 0,position:null};switch(r.nodeType){case Node.TEXT_NODE:n.name="text()";break;case Node.ATTRIBUTE_NODE:n.name="@"+r.nodeName;break;case Node.PROCESSING_INSTRUCTION_NODE:n.name="processing-instruction()";break;case Node.COMMENT_NODE:n.name="comment()";break;case Node.ELEMENT_NODE:n.name=r.nodeName}n.position=pt(r)}return"/"+t.reverse().map(r=>r.position!==null?`/${r.name}[${r.position}]`:`/${r.name}`).join("")},pe=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),R={capture:!0,passive:!0},gt=["a","button","input","option","li","link"],mt=["Escape","Enter","Backspace","F5","Tab"];let $=!1,S=null,O=null;const ve=e=>{var r;if(((r=e.tagName)==null?void 0:r.toLowerCase())==="html")return{element:"html"};const t={};return t.element=(n=>{if(!n.tagName)return"No tagName";const a=n.getAttribute("type");return a?`${a} ${n.tagName.toLowerCase()}`:n.tagName.toLowerCase()})(e),t},wt=e=>{var n;if(!e)return{};const t={...ve(e)},r=e.parentElement;if(r&>.includes((n=r.tagName)==null?void 0:n.toLowerCase())){const a=ve(r);Object.assign(t,a)}return t},ke=(e,t)=>{var a,s;let r=t.target;var n;t.target===((a=window.document)==null?void 0:a.body)&&window.Sprig.pointerDownTarget&&(r=window.Sprig.pointerDownTarget),n={x:t.x,y:t.y,type:e,elementAttributes:wt(r),windowHeight:window.innerHeight,windowWidth:window.innerWidth,...r instanceof HTMLElement?{rect:r==null?void 0:r.getBoundingClientRect(),xPath:Pe(r)}:{}},(s=n==null?void 0:n.elementAttributes)!=null&&s.text&&(n.elementAttributes.text=pe(n.elementAttributes.text)),S==null||S("Sprig_Click",n)},Ue=e=>{var t;mt.includes(e.key)&&(t={key:e.key},S==null||S("Sprig_Keystroke",t))},yt=()=>{var e;window.performance.getEntriesByType("navigation").map(t=>t.type).includes("reload")&&(e={url:window.location.href,currentPageTitle:document.title},S==null||S("Sprig_Refresh",e))},ft=()=>{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=pe(e.currentPageTitle)),S==null||S("Sprig_BackForward",e))},xe=((e,t)=>{let r;return n=>{clearTimeout(r),r=window.setTimeout(()=>e(n),t)}})(e=>{if(!(e.target instanceof HTMLElement||e.target instanceof Document))return;let t=e.target;"scrollTop"in t||(t=t.documentElement),O==null||O({xPath:Pe(t),x:t.scrollLeft,y:t.scrollTop,elementAttributes:{targetScrollWidth:t.scrollWidth,targetClientWidth:t.clientWidth,targetScrollHeight:t.scrollHeight,targetClientHeight:t.clientHeight}})},750),Le=(be="left_click",e=>ke(be,e));var be;const Be=e=>{e.button===2&&ke("right_click",e)},Te=e=>{window.Sprig&&(window.Sprig.pointerDownTarget=e.target)},g={isRecording:!1,scrollEventUuids:{},stopRecording:()=>{}},Me=()=>window.indexedDB&&window.IDBKeyRange&&window.CompressionStream,h=(()=>{const e=o.sessionStorageHelper.getItem("sprig.sessionId");if(e)return o.breadcrumbsLogger.info("SessionIDFound",{savedSessionId:e}),o.sessionStorageHelper.removeItem("sprig.sessionId"),e;const t=o.v4();return o.breadcrumbsLogger.info("GeneratedSessionID",{uuid:t}),t})(),ae=()=>{o.sessionStorageHelper.setItem("sprig.disableReplayRecording","disabled")},C=()=>!!o.sessionStorageHelper.getItem("sprig.disableReplayRecording"),j=()=>!!o.sessionStorageHelper.getItem("sprig.isReplayPaused");window.addEventListener("beforeunload",()=>{o.breadcrumbsLogger.info("BeforeUnload",{sessionId:h}),o.sessionStorageHelper.setItem("sprig.sessionId",h)});const U=(e,t)=>{var r,n;if(!C()&&g.isRecording&&!j())try{(n=(r=window.rrwebRecord)==null?void 0:r.addCustomEvent)==null||n.call(r,e,t)}catch(a){W("Error recording custom event",a)}},ht=async e=>{const{x:t,xPath:r,y:n}=e,a=g.scrollEventUuids[r];if(a)return b(async()=>{var c,d,u,w;const s=await l.openDB(),i=await s.get("events",a);if(i!=null&&i.event){const p=JSON.parse(i.event),f=t>((d=(c=p.data)==null?void 0:c.payload)==null?void 0:d.x),m=n>((w=(u=p.data)==null?void 0:u.payload)==null?void 0:w.y);if(!f&&!m)return null;f&&(p.data.payload.x=t),m&&(p.data.payload.y=n),p.data.payload.elementAttributes=e.elementAttributes,i.event=JSON.stringify(p),await s.put("events",i)}else U("Sprig_Scroll",e)},"Error updating scroll event");U("Sprig_Scroll",e)},Ae=()=>{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)}),$&&(window.removeEventListener("click",Le,R),window.removeEventListener("pointerdown",Te,R),window.removeEventListener("mousedown",Be,R),window.removeEventListener("keydown",Ue,R),window.removeEventListener("scroll",xe,R),$=!1),le.forEach(e=>{var t;(t=e.source)==null||t.postMessage({type:lt},{targetOrigin:e.origin})})},It=["did not allow mutations","called in an invalid security context"],vt=(e,t,{reportError:r=!0,extraInfo:n={}})=>{if(!C()&&t instanceof Error){if(ae(),t.name==="VersionError")return o.breadcrumbsLogger.error("VersionErr",{message:e}),void l.deleteDB();(a=>{if(!a)return!0;for(const s of It)if(a.toLowerCase().includes(s))return!1;return!0})(t==null?void 0:t.message)&&(r&&window.UserLeap.reportError(e,t,n),l.clearAll())}},W=(e,t,{reportError:r}={reportError:!0})=>{Ae(),o.breadcrumbsLogger.error("ReplayErr",{code:t.code,name:t.name}),vt(e,t,{reportError:r})},b=async(e,t)=>{try{return await e()}catch(r){W(t,r)}},se=()=>{g.isRecording&&(b(()=>{var e,t;return(t=(e=window.rrwebRecord)==null?void 0:e.takeFullSnapshot)==null?void 0:t.call(e,!0)},"Error recording full snapshot"),le.forEach(e=>{var t;(t=e.source)==null||t.postMessage({type:ut},{targetOrigin:e.origin})}))};(async()=>Me()&&Promise.allSettled([re("replayStorage"),re("sprig.replay")]))();const l=new class{openDB(){return function(e,t,{blocked:r,upgrade:n,blocking:a,terminated:s}={}){const i=indexedDB.open(e,t),c=B(i);return n&&(i.onupgradeneeded=d=>{n(B(i.result),d.oldVersion,d.newVersion,B(i.transaction),d)}),r&&(i.onblocked=d=>r(d.oldVersion,d.newVersion,d)),c.then(d=>{s&&(d.onclose=()=>s()),a&&(d.onversionchange=u=>a(u.oldVersion,u.newVersion,u))}).catch(()=>{}),c}("sprigReplay",1,{upgrade:(e,t,r)=>{if(r===0&&o.sessionStorageHelper.setItem("sprig.pendingCount","0"),!e.objectStoreNames.contains("events")){const n=e.createObjectStore("events",{keyPath:"uuid"});n.createIndex("sessionId","sessionId"),n.createIndex("timestamp","timestamp"),n.createIndex("[sessionId+timestamp]",["sessionId","timestamp"])}if(!e.objectStoreNames.contains("chunkUploads")){const n=e.createObjectStore("chunkUploads",{keyPath:"uuid"});n.createIndex("sessionId","sessionId"),n.createIndex("timestamp","timestamp"),n.createIndex("[sessionId+status]",["sessionId","status"]),n.createIndex("[uploadId+status]",["uploadId","status"]),n.createIndex("[sessionId+status+uploadId]",["sessionId","status","uploadId"])}if(!e.objectStoreNames.contains("pendingCaptures")){const n=e.createObjectStore("pendingCaptures",{keyPath:"uuid"});n.createIndex("sessionId","sessionId"),n.createIndex("timestamp","timestamp"),n.createIndex("[sessionId+targetTimestamp]",["sessionId","targetTimestamp"])}}})}async deleteDB(){try{await re("sprigReplay")}catch{}}async bulkAdd(e,t){const r=(await this.openDB()).transaction(e,"readwrite");return Promise.all([...t.map(n=>r.store.add(n)),r.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 r=IDBKeyRange.only(t),n=(await this.openDB()).transaction(e,"readwrite"),a=n.store.index("sessionId");for await(const s of a.iterate(r))await s.delete();await n.done}async updatePartial(e,t,r){const n=(await this.openDB()).transaction(e,"readwrite"),a=await n.store.get(t);a&&await n.store.put({...a,...r}),await n.done}async deleteRowsBefore(e,t,r=()=>!0){const n=IDBKeyRange.upperBound(t,!0),a=(await this.openDB()).transaction(e,"readwrite"),s=a.store.index("timestamp");for await(const i of s.iterate(n))r(i.value)&&await i.delete();await a.done}async getEventsBetween(e,t=Date.now()){if(e>=t)return Promise.resolve([]);const r=IDBKeyRange.bound([h,e],[h,t],!1,!0);return(await this.openDB()).getAllFromIndex("events","[sessionId+timestamp]",r)}async updateEventsExpiredAt(e,t,r=30){const n=new Date,a=n.setMinutes(n.getMinutes()+(r??30)),s=(await this.openDB()).transaction("events","readwrite"),i=s.store.index("[sessionId+timestamp]"),c=IDBKeyRange.bound([h,e],[h,t],!1,!0);for await(const d of i.iterate(c))await d.update({...d.value,expiredAt:a});await s.done}async deleteChunkUploads(e,t){const r=IDBKeyRange.only([t,e]),n=(await this.openDB()).transaction("chunkUploads","readwrite");let s=await n.store.index("[uploadId+status]").openCursor(r);for(;s;)s.delete(),s=await s.continue();await n.done}async getChunkUploadsByStatus({sessionId:e,status:t,uploadId:r}){const n=(await this.openDB()).transaction("chunkUploads","readonly"),a=r?n.store.index("[uploadId+status]"):n.store.index("[sessionId+status]"),s=r?IDBKeyRange.only([r,t]):IDBKeyRange.only([e,t]);return a.getAll(s)}async getPendingCaptures(e={}){return(await(await this.openDB()).getAllFromIndex("pendingCaptures","sessionId",h)).filter(r=>!e.beforePresent||r.targetTimestamp<Date.now()).filter(r=>!e.isBeforeType||r.captureParams.replayParams.replayDurationType==="before").filter(r=>!e.isHeatmap||(r.captureParams.isHeatmap??!1))}async markPendingCaptureToCanUpload(e){const t=(await this.openDB()).transaction("pendingCaptures","readwrite"),r=t.store.index("sessionId");for await(const n of r.iterate(h)){const a=n.value;a.captureParams.responseGroupId===e&&await n.update({...a,canUpload:!0})}await t.done}async markPendingHeatmapsReady(e){if(parseInt(o.sessionStorageHelper.getItem("sprig.pendingCount")??"0")===0)return null;const t=Date.now(),r=(await this.openDB()).transaction("pendingCaptures","readwrite"),n=r.store.index("sessionId");for await(const a of n.iterate(h)){const s=a.value;!s.captureParams.isHeatmap||e&&!e.includes(s.uuid)||await a.update({...s,targetTimestamp:t,captureParams:{...s.captureParams,triggerTimestamp:t,replayParams:{...s.captureParams.replayParams,replayDurationSeconds:Math.floor((t-s.timestamp)/1e3)}}})}await r.done}},x=[];let N,_e,K,He,F,Ne,M=[],_=!1,A=0,V=!1,Oe=!1,ge=[],Q=!1;const H=()=>V&&!_&&Date.now()<=K,bt=({apiUrl:e,config:t,triggerSnapshot:r,forceInit:n=!1})=>{V&&!n||(o.sessionStorageHelper.isStorageAvailable?(M=[],ge.splice(0),x.splice(0),A=0,F=r,_e=e,N={responseGroupUuid:t.responseGroupUuid,surveyId:t.surveyId,userAgent:t.userAgent,sdkVersion:t.sdkVersion},He=t.maxDurationSeconds,Rt(),V||(Ne=window.setInterval(Et,500)),V=!0):_=!0)},St=[k.Drag,k.Input,k.MediaInteraction,k.MouseInteraction,k.MouseMove,k.Scroll,k.Selection,k.TouchMove],Dt=e=>e.type===L.Custom||e.type===L.IncrementalSnapshot&&St.includes(e.data.source),me=e=>e.some(Dt),Et=async()=>{if(!H())return void window.clearInterval(Ne);if(Fe(),!me(x))return;const e=x[0].timestamp;Date.now()-e>35e3&&(F==null||F())},Fe=async()=>{if(M.length||Q)return;Q=!0;const e=await Pt();if(!e)return void(_=!0);ge.splice(0,e.length).forEach(t=>t(e.shift())),e.forEach(t=>M.push(t)),Q=!1},Rt=()=>{const e=o.sessionStorageHelper.getItem("sprig.alwayson.info");if(e){o.breadcrumbsLogger.info("Read stored session state",e);const t=JSON.parse(e);_=t.disabled,N=t.metadata,M=t.uploadUrls,A=t.currentIndex,K=t.expirationTimestamp,t.pendingEventTimestamp&&(o.breadcrumbsLogger.info(`Uploading with pending timestamp: ${t.pendingEventTimestamp}`),Ct(t.pendingEventTimestamp))}else K=1e3*He+Date.now()},Ct=async e=>{const t=Date.now(),r=(await l.getEventsBetween(e,t)).map(a=>JSON.parse(a.event));if(!me(r))return;je(r);const n=await $e();n&&await Ge(n,r)},Ve=async(e,t)=>{try{const r=await e();if(!r.ok)throw new Error(`Error ${t}`);return r}catch{_=!0}},Ge=async(e,t)=>{if(!H()||!e)return;const r=await(async n=>{const a=new TextEncoder,s=new CompressionStream("gzip"),i=s.writable.getWriter(),c=a.encode(JSON.stringify(n));return i.write(c),i.close(),new Uint8Array(await new Response(s.readable).arrayBuffer())})(t);o.breadcrumbsLogger.info("Uploading always-on events with presigned url"),await Ve(()=>o.sprigFetch(e,{body:r,method:"PUT"}),"uploading always-on with presigned url")},Pt=async()=>{if(!H())return;const{surveyId:e,responseGroupUuid:t}=N,r={responseGroupUuid:t,surveyId:e,index:A+1};o.breadcrumbsLogger.info("Fetching always-on upload urls",r);const n=await Ve(()=>o.sprigFetch(`${_e}/sdk/1/replayUrls`,{method:"POST",body:JSON.stringify(r),headers:o.getHttpHeaders(window.UserLeap)}),"fetching always-on signed urls");if(!n)return;const a=n.json.signedUrls;return o.breadcrumbsLogger.info("Fetched more always-on upload urls",{body:r,urls:a}),a},$e=async()=>{if(M.length)return M.shift();const e=new Promise(t=>{ge.push(t)});return Fe(),e},je=e=>{var a,s,i;const t=e.length?e[e.length-1].timestamp:Date.now(),r=A,n=((s=(a=window.UserLeap)==null?void 0:a.config)==null?void 0:s.customMetadata)??((i=window.__cfg)==null?void 0:i.customMetadata);A++,e.push({timestamp:t,type:L.Custom,data:{tag:"Sprig_Meta",payload:{...N,index:r,visitorId:window.UserLeap.visitorId??"",timestamp:t,customMetadata:n}}})},kt=(e,t)=>{H()&&!Oe&&(e||x.length)&&(e&&x.length&&(async()=>{const r=x.splice(0);if(!me(r))return;o.breadcrumbsLogger.info("Capturing always-on event array to upload"),je(r);const n=await $e();n&&await Ge(n,r)})(),x.push(t))};window.addEventListener("beforeunload",async()=>{Oe=!0,H()&&(o.breadcrumbsLogger.info("Always On handle page unload"),(()=>{let e;x.length&&(e=x[0].timestamp);const t={disabled:_,metadata:N,uploadUrls:M,currentIndex:A,pendingEventTimestamp:e,expirationTimestamp:K};o.breadcrumbsLogger.info("Storing session state on unload",t),o.sessionStorageHelper.setItem("sprig.alwayson.info",JSON.stringify(t))})())});const Ke=async(e,t)=>{const r=performance.now();let n;try{n=await e()}finally{const a=performance.now()-r;let s=o.PerformanceMetrics[t];s||(s=o.registerMetric(t)),s.report(a/1e3)}return n},We=(e,t)=>{const r=performance.now();try{e()}finally{const n=performance.now()-r;let a=o.PerformanceMetrics[t];a||(a=o.registerMetric(t)),a.report(n/1e3)}};let Je=5e3,oe=6e4,ie=0,T,de=!1,ce=[];const Ut=e=>{var t,r,n,a;if((t=e.event)!=null&&t.includes("Sprig_Scroll")){const s=(a=(n=(r=JSON.parse(e.event))==null?void 0:r.data)==null?void 0:n.payload)==null?void 0:a.xPath;if(!s)return;g.scrollEventUuids[s]=e.uuid}ce.push(e),de||xt()},xt=()=>{de=!0,setTimeout(async()=>{if(C()||j())return;const e=ce;ce=[],de=!1,We(async()=>{await(async t=>{const r=t.map(n=>({...n,sessionId:n.sessionId??h}));if(r.length!==0)return b(()=>l.bulkAdd("events",r),"Error storing replay events")})(e)},"sdk_replay_add_event_batch_seconds")},500)},Lt=(e,t,r)=>{g.cleanupInterval=window.setInterval(()=>{const n=Date.now();Ke(()=>b(async()=>{C()||await Promise.all([l.deleteRowsBefore("events",n-1e3*e,a=>a.expiredAt===void 0||a.expiredAt<n-1e3*e),l.deleteRowsBefore("chunkUploads",n-1e3*t),l.deleteRowsBefore("pendingCaptures",n-1e3*r,a=>!a.canUpload)])},"Error deleting table rows"),"sdk_replay_cleanup_seconds"),o.breadcrumbsLogger.debug("CleanupComplete")},3e4)},Bt=()=>{g.pendingCheckInterval=window.setInterval(async()=>{b(async()=>{await ue()},"Error initiating pending captures")},5e3)};let X=!1;const ue=async(e=!1)=>{if(!X)try{X=!0;const t=parseInt(T??"0");if(t===0)return;const r=await l.getPendingCaptures({beforePresent:!0,isBeforeType:e}),n=await l.openDB();await Promise.all(r.map(async a=>(await n.delete("pendingCaptures",a.uuid),Qe(a.captureParams,a.canUpload)))),T=(t-r.length).toString(),o.sessionStorageHelper.setItem("sprig.pendingCount",T)}finally{X=!1}},Tt=async(e,t,r,n,a)=>{const s=Math.min(e+a,r),i=await Ke(()=>l.getEventsBetween(e,s),"sdk_replay_get_events_between_seconds");if(!(i!=null&&i.length))return o.breadcrumbsLogger.debug("NoEventsFound"),{validStartFound:n,events:[]};if(!n){o.breadcrumbsLogger.debug("ValidStartSearch");let c=-1;return i==null||i.forEach((d,u)=>{if(!d.isValidStart)return;const w=d.timestamp<=t;(c<0||w)&&(c=u)}),c<0?(o.breadcrumbsLogger.debug("ValidStartNotFound"),{validStartFound:n,events:[]}):{validStartFound:!0,events:i==null?void 0:i.slice(c)}}return{validStartFound:n,events:i}},qe=e=>Promise.all(e.map(async t=>{const r=await(async n=>Re.execute(async()=>{var i;o.breadcrumbsLogger.info("UploadChunkStart",{chunkIndex:n.chunkIndex,surveyId:n.surveyId});const a=await o.sprigFetch(n.uploadUrl,{body:n.data,method:"PUT"});o.breadcrumbsLogger.http("UploadChunkEnd",{url:n.uploadUrl,method:"PUT",status_code:a.status,reason:a.statusText??"OK",chunkIndex:n.chunkIndex,surveyId:n.surveyId});const s=(i=a.headers)==null?void 0:i.get("ETag");if(!s)throw new Error(`Upload response did not include etag for upload ${n.uploadId}, part ${n.chunkIndex}`);return s}))(t);return await l.updatePartial("chunkUploads",t.uuid,{data:null,etag:r,status:"UploadComplete"}),t.uploadId})),ze=async e=>{const t=await l.getChunkUploadsByStatus({status:"UploadComplete",uploadId:e});if(!(t!=null&&t.length))return void o.breadcrumbsLogger.info("NoChunksForUpload",{uploadId:e});const r=t.reduce((s,i)=>(s.find(c=>c.chunkIndex===i.chunkIndex)||s.push(i),s),[]);r.sort((s,i)=>s.chunkIndex-i.chunkIndex);const n=r.map(s=>({ETag:s.etag,PartNumber:s.chunkIndex})).filter(s=>s.ETag!==null),a=r[0];await Ce({apiUrl:a.apiUrl,surveyId:a.surveyId,uploadId:e,responseGroupUuid:a.responseGroupId,etags:n,headers:a.completeUploadHeaders,replayDuration:a.replayDuration}),await l.deleteChunkUploads("UploadComplete",e)},Mt=()=>{b(async()=>{const e=await l.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(r=>{if(r)return ze(r)}))},"Error uploading unfinished chunks")},At=async(e,t)=>{const r=t??Date.now();return(async(n,a)=>{const s=new TextEncoder;let i=null;const c=new CompressionStream("gzip"),d=c.writable.getWriter();let u=!1,w=!1,[p,f]=[0,0],m=[];for(let P=n-35e3;P<a;P+=oe){if({validStartFound:w,events:m}=await Tt(P,n,a,w,oe),!(m!=null&&m.length)){o.breadcrumbsLogger.debug("NoEventsFound");continue}p===0&&(p=m[0].timestamp),f=m[m.length-1].timestamp;const y=m.map(E=>E.event);y.push(`{"timestamp":${a}}`);const I=`${u?",":"["}${y}`,v=s.encode(I);We(()=>{d.write(v)},"sdk_replay_compression_seconds"),u=!0}if(f-p<Je)return o.breadcrumbsLogger.debug("ReplayTooShort"),null;const D=s.encode("]");return d.write(D),d.close(),i=new Uint8Array(await new Response(c.readable).arrayBuffer()),i})(r-e,r)},Se=async e=>{const{surveyId:t,responseGroupId:r,visitorId:n,apiUrl:a,completeUploadHeaders:s,replayParams:i,triggerTimestamp:c}=e,d=await At(1e3*i.replayDurationSeconds,c);if(!(d!=null&&d.length))return void o.breadcrumbsLogger.info("FileDataEmpty",{surveyId:t});const u=((p,f,m)=>{const D=p.length,P=1024*f*1024,y=Math.ceil(D/m),I=Math.max(P,y),v=[];let E=0;for(;E<D;)v.push(p.slice(E,E+I)),E+=I;return v})(d,i.minimumChunkSizeMb,i.signedUrls.length),w=await Promise.all(u.map(async(p,f)=>{const m=o.v4(),D={apiUrl:a,chunkIndex:f+1,completeUploadHeaders:s,etag:null,responseGroupId:r,status:"ReadyForUpload",surveyId:t,timestamp:c,totalChunks:u.length,data:p,uploadId:i.uploadId,uploadUrl:i.signedUrls[f].url,uuid:m,visitorId:n};return await(await l.openDB()).add("chunkUploads",{...D,sessionId:D.sessionId??h}),D}));await(async(p,f)=>{await qe(f),await Promise.all(p.map(m=>ze(m)))})([i.uploadId],w)},Qe=async(e,t)=>{if(C())return o.breadcrumbsLogger.debug("ReplayDisabled-ScheduleOrCapture");const{isHeatmap:r,isStandalone:n,replayParams:a,triggerTimestamp:s,responseGroupId:i}=e,c=async()=>{setTimeout(()=>o.eventEmitter.removeListener(o.SprigEvent.QuestionAnswered,c),0),b(async()=>{a.replayDurationType==="before"?await Se(e):await l.markPendingCaptureToCanUpload(i)},"Error in schedule/capture callback")};b(async()=>{if(a.replayDurationType==="after"||a.replayDurationType==="beforeAndAfter")return!n&&!r&&o.eventEmitter.on(o.SprigEvent.QuestionAnswered,c),void await Ye(e);if(n||r||t)await Se(e),r&&_t();else{const d=35+a.replayDurationSeconds,u=s-1e3*d,w=s;await l.updateEventsExpiredAt(u,w,a.expirationTimeLimitMinutes),o.eventEmitter.on(o.SprigEvent.QuestionAnswered,c)}},"Error in scheduling/capturing replay")},_t=async()=>{parseInt(T??"0")||o.sessionStorageHelper.removeItem("sprig.isCapturingHeatmap"),o.sessionStorageHelper.getItem("sprig.teardownAfterCapture")&&(Ae(),Xe(),o.sessionStorageHelper.removeItem("sprig.teardownAfterCapture"))},Xe=async()=>C()?o.breadcrumbsLogger.debug("ReplayDisabled-ClearData"):Promise.all([l.deleteBySessionId("events",h),l.deleteBySessionId("pendingCaptures",h)]).catch(e=>{W("Error clearing user replay data",e)}),Ye=async e=>{if(C())return;const{isHeatmap:t,surveyId:r}=e,n=await l.getPendingCaptures(),a=n==null?void 0:n.filter(d=>d.captureParams.surveyId===r);if(a!=null&&a.length)return void o.breadcrumbsLogger.info("PendingCaptureExists",{surveyId:r});t&&(se(),o.sessionStorageHelper.setItem("sprig.isCapturingHeatmap","true"),ie=Date.now(),g.inactivityInterval||(g.inactivityInterval=window.setInterval(()=>{var d;d=ie,Date.now()-d>=3e4&&b(()=>l.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 i=e.triggerTimestamp+1e3*e.replayParams.replayDurationSeconds;s.triggerTimestamp=i,T=(parseInt(T??"0")+1).toString(),o.sessionStorageHelper.setItem("sprig.pendingCount",T),await(await l.openDB()).add("pendingCaptures",{canUpload:!1,captureParams:s,sessionId:h,targetTimestamp:i,timestamp:Date.now(),uuid:o.v4()})},Ht=Object.freeze(Object.defineProperty({__proto__:null,RecordEvent:e=>{U("Sprig_TrackEvent",e)},RecordPageView:e=>{e.description&&(e.description=pe(e.description)),U("Sprig_PageView",e)},RecordSurveyShown:e=>{U("Sprig_ShowSurvey",e)},_completeSessionReplay:async({surveyId:e,responseGroupUuid:t,eventDigest:r,headers:n})=>{if(!e||!t)return!1;const a=window.UserLeap._API_URL,s=await Ce({surveyId:e,responseGroupUuid:t,eventDigest:r,apiUrl:a,headers:n},!0);return!(s!=null&&s.error)},checkPendingHeatmapsUrl:()=>C()?o.breadcrumbsLogger.debug("ReplayDisabled-PendingHeatmaps"):b(async()=>{const e=(await l.getPendingCaptures({isHeatmap:!0})).map(t=>({eventId:t.captureParams.eventId,uuid:t.uuid})).filter(({eventId:t})=>!o.checkUrlStillMatching(t)).map(({uuid:t})=>t);return o.breadcrumbsLogger.info("PendingHeatmapsToComplete",{count:e.length}),e.length&&(await l.markPendingHeatmapsReady(e),o.breadcrumbsLogger.info("MarkedPendingHeatmapsReady")),e.length},"Error marking pending heatmaps ready"),clearUserReplayData:Xe,disableRecording:W,initializeReplay:async({maxReplayDurationSeconds:e,maxInflightRequests:t=2,replaySettings:r,teardownAfter:n=!1,apiUrl:a,alwaysOnConfig:s})=>{if(s&&bt({apiUrl:a,config:s,triggerSnapshot:()=>{se()}}),T=o.sessionStorageHelper.getItem("sprig.pendingCount"),g.isRecording)return;if(n&&o.sessionStorageHelper.setItem("sprig.teardownAfterCapture","true"),C())return o.breadcrumbsLogger.debug("ReplayDisabled");if(await(async()=>{var d;if(!Me())return!0;if((d=window.navigator.storage)!=null&&d.estimate)try{const{quota:u=0,usage:w=0}=await window.navigator.storage.estimate(),p=(u-w)/1024**3;return o.breadcrumbsLogger.info("Storage",{availableGb:p}),p<.5}catch{return!0}return!1})())return o.breadcrumbsLogger.debug("IDBNotSupported"),ae();try{const d=await l.openDB();o.breadcrumbsLogger.info("DBVersion",{version:d.version})}catch(d){return o.breadcrumbsLogger.error("ReplayOpenErr",{name:d.name}),d.name==="VersionError"&&l.deleteDB(),ae()}b(async()=>{await ue(!0)},"Error uploading ready pending captures");const i=H()?30:0,c=Math.max(e??0,i);if(!c)return o.breadcrumbsLogger.debug("MissingDuration");o.breadcrumbsLogger.debug("ReplayInit"),await b(async()=>{var d;r!=null&&r.minDuration&&(Je=r.minDuration),r!=null&&r.batchDuration&&(oe=r.batchDuration),d=t,Re.setLimit(d),Mt(),Lt(c+35,1800,c+35),Bt();const u=window.UserLeap.replayLibraryURL??"https://cdn.sprig.com/dependencies/record-2.0.0-alpha.17.min.js";if(!window.rrwebRecord){const{record:y}=await import(u);window.rrwebRecord=y}const w=window.rrwebRecord;if(!w)return o.breadcrumbsLogger.error("RecordScriptFailed");let p=!0,f=0;const m={checkoutEveryNms:3e4,sampling:{input:"last",scroll:250,media:800},...r};var D,P;g.stopRecording=w({emit:(y,I)=>{if(y.type===L.Custom&&(ie=Date.now()),C()||j())return;if(I&&y.type===L.Meta)f=performance.now();else if(I&&f&&y.type===L.FullSnapshot){const E=performance.now()-f;o.reportAndRegister("sdk_replay_snapshot_seconds",E/1e3)}const v=p||!!I&&y.type===L.Meta;p=!1,kt(v,y),Ut({uuid:o.v4(),event:JSON.stringify(y),isValidStart:v,timestamp:Date.now()})},...m}),g.isRecording=!!g.stopRecording,g.isRecording&&(((y,I)=>{window.addEventListener("message",v=>{var E;v.data.type===dt&&(le.push({source:v.source,origin:v.origin}),(E=v.source)==null||E.postMessage({type:ct,settings:y,replayLibraryUrl:I},{targetOrigin:v.origin}))})})(m,u),o.eventEmitter.on("survey.complete",y=>{var I;I={id:y,userAgent:window.navigator.userAgent},U("Sprig_SubmitSurvey",I)}),D=U,P=ht,$||(S=D,O=P,window.addEventListener("click",Le,R),window.addEventListener("pointerdown",Te,R),window.addEventListener("mousedown",Be,R),window.addEventListener("keydown",Ue,R),window.addEventListener("scroll",xe,R),$=!0,yt(),ft()))},"Error initializing replay")},isReplayPaused:j,isReplayRecording:()=>g.isRecording,recordFullSnapshot:se,recordReplayPaused:()=>{U("Sprig_ReplayPaused",{timestamp:Date.now()}),o.sessionStorageHelper.setItem("sprig.isReplayPaused","true")},recordReplayResumed:()=>{o.sessionStorageHelper.removeItem("sprig.isReplayPaused"),U("Sprig_ReplayResumed",{timestamp:Date.now()})},scheduleCapture:Ye,scheduleOrCaptureReplay:Qe,tryReplayAction:b,uploadReadyPendingCaptures:ue},Symbol.toStringTag,{value:"Module"}));o.registerReplay(Ht);
|
|
1
|
+
"use strict";var et=Object.defineProperty;var tt=(e,t,r)=>t in e?et(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var N=(e,t,r)=>tt(e,typeof t!="symbol"?t+"":t,r);const o=require("./metricsReporter-BvLxSPGb.cjs");var L=(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))(L||{}),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 Z=(e,t)=>t.some(r=>e instanceof r);let ye,fe;const ee=new WeakMap,q=new WeakMap,$=new WeakMap;let te={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return ee.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return x(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&(t==="done"||t==="store")||t in e};function Ee(e){te=e(te)}function rt(e){return(fe||(fe=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(re(this),t),x(this.request)}:function(...t){return x(e.apply(re(this),t))}}function nt(e){return typeof e=="function"?rt(e):(e instanceof IDBTransaction&&function(t){if(ee.has(t))return;const r=new Promise((n,a)=>{const s=()=>{a(t.error||new DOMException("AbortError","AbortError"))};t.oncomplete=()=>{n()},t.onerror=s,t.onabort=s});ee.set(t,r)}(e),Z(e,ye||(ye=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,te):e)}function x(e){if(e instanceof IDBRequest)return function(r){const n=new Promise((a,s)=>{r.onsuccess=()=>{a(x(r.result))},r.onerror=()=>{s(r.error)}});return $.set(n,r),n}(e);if(q.has(e))return q.get(e);const t=nt(e);return t!==e&&(q.set(e,t),$.set(t,e)),t}const re=e=>$.get(e);function ne(e,{blocked:t}={}){const r=indexedDB.deleteDatabase(e);return t&&(r.onblocked=n=>t(n.oldVersion,n)),x(r).then(()=>{})}const at=["get","getKey","getAll","getAllKeys","count"],st=["put","add","delete","clear"],z=new Map;function he(e,t){if(!(e instanceof IDBDatabase)||t in e||typeof t!="string")return;if(z.get(t))return z.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,a=st.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!a&&!at.includes(r))return;const s=async function(i,...c){const d=this.transaction(i,a?"readwrite":"readonly");let u=d.store;return n&&(u=u.index(c.shift())),(await Promise.all([u[r](...c),a&&d.done]))[0]};return z.set(t,s),s}Ee(e=>({...e,get:(t,r,n)=>he(t,r)||e.get(t,r,n),has:(t,r)=>!!he(t,r)||e.has(t,r)}));const ot=["continue","continuePrimaryKey","advance"],Ie={},ae=new WeakMap,Re=new WeakMap,it={get(e,t){if(!ot.includes(t))return e[t];let r=Ie[t];return r||(r=Ie[t]=function(...n){ae.set(this,Re.get(this)[t](...n))}),r}};async function*dt(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const r=new Proxy(t,it);for(Re.set(r,t),$.set(r,re(t));t;)yield r,t=await(ae.get(r)||t.continue()),ae.delete(r)}function ve(e,t){return t===Symbol.asyncIterator&&Z(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&Z(e,[IDBIndex,IDBObjectStore])}Ee(e=>({...e,get:(t,r,n)=>ve(t,r)?dt:e.get(t,r,n),has:(t,r)=>ve(t,r)||e.has(t,r)}));const ct="sprigReplayIframeLoaded",ut="sprigReplayIframeSettings",lt="sprigReplayIframeTakeFullSnapshot",pt="sprigReplayTeardown",pe=[],Ce=new class{constructor(e){N(this,"awaitingResolvers",[]);N(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),Te=async({apiUrl:e,surveyId:t,uploadId:r,etags:n,headers:a,responseGroupUuid:s,replayDuration:i,eventDigest:c},d=!1)=>{var w;if(!d&&!r&&!n)return void o.breadcrumbsLogger.error("UploadErr",{isMobile:d,uploadId:r,etags:n});o.breadcrumbsLogger.info("MarkUploadComplete",{surveyId:t});const u=await o.sprigFetch(`${e}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:n,uploadId:r,responseGroupUuid:s,surveyId:t,replayDuration:i,eventDigest:c,userAgent:(w=window==null?void 0:window.navigator)==null?void 0:w.userAgent}),headers:a,shouldRetryRequest:!0});return o.breadcrumbsLogger.info("MarkUploadDone",{surveyId:t}),u},gt=e=>{if(e instanceof Attr)return null;let t=1;for(let r=e.previousSibling;r;r=r.previousSibling)r.nodeName===e.nodeName&&++t;return t},Pe=e=>{if(e===null)return"";const t=[];if(e instanceof Document)return"/";for(let r=e;r&&!(r instanceof Document)&&r!==null;r=r instanceof Attr?r.ownerElement:r.parentElement){const n=t[t.length]={name:void 0,position:null};switch(r.nodeType){case Node.TEXT_NODE:n.name="text()";break;case Node.ATTRIBUTE_NODE:n.name="@"+r.nodeName;break;case Node.PROCESSING_INSTRUCTION_NODE:n.name="processing-instruction()";break;case Node.COMMENT_NODE:n.name="comment()";break;case Node.ELEMENT_NODE:n.name=r.nodeName}n.position=gt(r)}return"/"+t.reverse().map(r=>r.position!==null?`/${r.name}[${r.position}]`:`/${r.name}`).join("")},ge=e=>e&&e.trim().substring(0,500).replace(/\s\s+/g," ").replace(/\r?\n|\r/g," ").substring(0,250),R={capture:!0,passive:!0},mt=["a","button","input","option","li","link"],wt=["Escape","Enter","Backspace","F5","Tab"];let j=!1,S=null,V=null;const be=e=>{var r;if(((r=e.tagName)==null?void 0:r.toLowerCase())==="html")return{element:"html"};const t={};return t.element=(n=>{if(!n.tagName)return"No tagName";const a=n.getAttribute("type");return a?`${a} ${n.tagName.toLowerCase()}`:n.tagName.toLowerCase()})(e),t},yt=e=>{var n;if(!e)return{};const t={...be(e)},r=e.parentElement;if(r&&mt.includes((n=r.tagName)==null?void 0:n.toLowerCase())){const a=be(r);Object.assign(t,a)}return t},ke=(e,t)=>{var a,s;let r=t.target;var n;t.target===((a=window.document)==null?void 0:a.body)&&window.Sprig.pointerDownTarget&&(r=window.Sprig.pointerDownTarget),n={x:t.x,y:t.y,type:e,elementAttributes:yt(r),windowHeight:window.innerHeight,windowWidth:window.innerWidth,...r instanceof HTMLElement?{rect:r==null?void 0:r.getBoundingClientRect(),xPath:Pe(r)}:{}},(s=n==null?void 0:n.elementAttributes)!=null&&s.text&&(n.elementAttributes.text=ge(n.elementAttributes.text)),S==null||S("Sprig_Click",n)},Ue=e=>{var t;wt.includes(e.key)&&(t={key:e.key},S==null||S("Sprig_Keystroke",t))},ft=()=>{var e;window.performance.getEntriesByType("navigation").map(t=>t.type).includes("reload")&&(e={url:window.location.href,currentPageTitle:document.title},S==null||S("Sprig_Refresh",e))},ht=()=>{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=ge(e.currentPageTitle)),S==null||S("Sprig_BackForward",e))},Le=((e,t)=>{let r;return n=>{clearTimeout(r),r=window.setTimeout(()=>e(n),t)}})(e=>{if(!(e.target instanceof HTMLElement||e.target instanceof Document))return;let t=e.target;"scrollTop"in t||(t=t.documentElement),V==null||V({xPath:Pe(t),x:t.scrollLeft,y:t.scrollTop,elementAttributes:{targetScrollWidth:t.scrollWidth,targetClientWidth:t.clientWidth,targetScrollHeight:t.scrollHeight,targetClientHeight:t.clientHeight}})},750),xe=(Se="left_click",e=>ke(Se,e));var Se;const Be=e=>{e.button===2&&ke("right_click",e)},Me=e=>{window.Sprig&&(window.Sprig.pointerDownTarget=e.target)},g={isRecording:!1,scrollEventUuids:{},stopRecording:()=>{}},Ae=()=>window.indexedDB&&window.IDBKeyRange&&window.CompressionStream,h=(()=>{const e=o.sessionStorageHelper.getItem("sprig.sessionId");if(e)return o.breadcrumbsLogger.info("SessionIDFound",{savedSessionId:e}),o.sessionStorageHelper.removeItem("sprig.sessionId"),e;const t=o.v4();return o.breadcrumbsLogger.info("GeneratedSessionID",{uuid:t}),t})(),se=()=>{o.sessionStorageHelper.setItem("sprig.disableReplayRecording","disabled")},C=()=>!!o.sessionStorageHelper.getItem("sprig.disableReplayRecording"),K=()=>!!o.sessionStorageHelper.getItem("sprig.isReplayPaused");window.addEventListener("beforeunload",()=>{o.breadcrumbsLogger.info("BeforeUnload",{sessionId:h}),o.sessionStorageHelper.setItem("sprig.sessionId",h)});const k=(e,t)=>{var r,n;if(!C()&&g.isRecording&&!K())try{(n=(r=window.rrwebRecord)==null?void 0:r.addCustomEvent)==null||n.call(r,e,t)}catch(a){O("Error recording custom event",a)}},It=async e=>{const{x:t,xPath:r,y:n}=e,a=g.scrollEventUuids[r];if(a)return b(async()=>{var c,d,u,w;const s=await l.openDB(),i=await s.get("events",a);if(i!=null&&i.event){const p=JSON.parse(i.event),f=t>((d=(c=p.data)==null?void 0:c.payload)==null?void 0:d.x),m=n>((w=(u=p.data)==null?void 0:u.payload)==null?void 0:w.y);if(!f&&!m)return null;f&&(p.data.payload.x=t),m&&(p.data.payload.y=n),p.data.payload.elementAttributes=e.elementAttributes,i.event=JSON.stringify(p),await s.put("events",i)}else k("Sprig_Scroll",e)},"Error updating scroll event");k("Sprig_Scroll",e)},_e=()=>{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)}),j&&(window.removeEventListener("click",xe,R),window.removeEventListener("pointerdown",Me,R),window.removeEventListener("mousedown",Be,R),window.removeEventListener("keydown",Ue,R),window.removeEventListener("scroll",Le,R),j=!1),pe.forEach(e=>{var t;(t=e.source)==null||t.postMessage({type:pt},{targetOrigin:e.origin})})},vt=["did not allow mutations","called in an invalid security context"],bt=(e,t,{reportError:r=!0,extraInfo:n={}})=>{if(!C()&&t instanceof Error){if(se(),t.name==="VersionError")return o.breadcrumbsLogger.error("VersionErr",{message:e}),void l.deleteDB();(a=>{if(!a)return!0;for(const s of vt)if(a.toLowerCase().includes(s))return!1;return!0})(t==null?void 0:t.message)&&(r&&window.UserLeap.reportError(e,t,n),l.clearAll())}},O=(e,t,{reportError:r}={reportError:!0})=>{_e(),o.breadcrumbsLogger.error("ReplayErr",{code:t.code,name:t.name}),bt(e,t,{reportError:r})},b=async(e,t)=>{try{return await e()}catch(r){O(t,r)}},oe=()=>{g.isRecording&&(b(()=>{var e,t;return(t=(e=window.rrwebRecord)==null?void 0:e.takeFullSnapshot)==null?void 0:t.call(e,!0)},"Error recording full snapshot"),pe.forEach(e=>{var t;(t=e.source)==null||t.postMessage({type:lt},{targetOrigin:e.origin})}))};let Q=0;(async()=>Ae()&&Promise.allSettled([ne("replayStorage"),ne("sprig.replay")]))();const l=new class{constructor(){N(this,"wrapTransactionWithCounter",e=>{var n,a;const t=(a=(n=window.Sprig)==null?void 0:n._config)==null?void 0:a.outstandingTransactionLimit,r=t===void 0?100:t;if(r&&Q>r){const s="Too many outstanding transactions";O(s,new Error(s),{reportError:!1})}Q++,e.done.finally(()=>{Q--})});N(this,"getTransaction",async e=>{const t=(await this.openDB()).transaction(e,"readwrite");return this.wrapTransactionWithCounter(t),t})}openDB(){return function(e,t,{blocked:r,upgrade:n,blocking:a,terminated:s}={}){const i=indexedDB.open(e,t),c=x(i);return n&&(i.onupgradeneeded=d=>{n(x(i.result),d.oldVersion,d.newVersion,x(i.transaction),d)}),r&&(i.onblocked=d=>r(d.oldVersion,d.newVersion,d)),c.then(d=>{s&&(d.onclose=()=>s()),a&&(d.onversionchange=u=>a(u.oldVersion,u.newVersion,u))}).catch(()=>{}),c}("sprigReplay",1,{upgrade:(e,t,r)=>{if(r===0&&o.sessionStorageHelper.setItem("sprig.pendingCount","0"),!e.objectStoreNames.contains("events")){const n=e.createObjectStore("events",{keyPath:"uuid"});n.createIndex("sessionId","sessionId"),n.createIndex("timestamp","timestamp"),n.createIndex("[sessionId+timestamp]",["sessionId","timestamp"])}if(!e.objectStoreNames.contains("chunkUploads")){const n=e.createObjectStore("chunkUploads",{keyPath:"uuid"});n.createIndex("sessionId","sessionId"),n.createIndex("timestamp","timestamp"),n.createIndex("[sessionId+status]",["sessionId","status"]),n.createIndex("[uploadId+status]",["uploadId","status"]),n.createIndex("[sessionId+status+uploadId]",["sessionId","status","uploadId"])}if(!e.objectStoreNames.contains("pendingCaptures")){const n=e.createObjectStore("pendingCaptures",{keyPath:"uuid"});n.createIndex("sessionId","sessionId"),n.createIndex("timestamp","timestamp"),n.createIndex("[sessionId+targetTimestamp]",["sessionId","targetTimestamp"])}}})}async deleteDB(){try{await ne("sprigReplay")}catch{}}async bulkAdd(e,t){const r=await this.getTransaction(e);return Promise.all([...t.map(n=>r.store.add(n)),r.done])}async clearAll(){const e=(await this.openDB()).transaction(["events","chunkUploads","pendingCaptures"],"readwrite");return this.wrapTransactionWithCounter(e),Promise.all([e.objectStore("events").clear(),e.objectStore("chunkUploads").clear(),e.objectStore("pendingCaptures").clear()])}async deleteBySessionId(e,t){const r=IDBKeyRange.only(t),n=await this.getTransaction(e),a=n.store.index("sessionId");for await(const s of a.iterate(r))await s.delete();await n.done}async updatePartial(e,t,r){const n=await this.getTransaction(e),a=await n.store.get(t);a&&await n.store.put({...a,...r}),await n.done}async deleteRowsBefore(e,t,r=()=>!0){const n=IDBKeyRange.upperBound(t,!0),a=await this.getTransaction(e),s=a.store.index("timestamp");for await(const i of s.iterate(n))r(i.value)&&await i.delete();await a.done}async getEventsBetween(e,t=Date.now()){if(e>=t)return Promise.resolve([]);const r=IDBKeyRange.bound([h,e],[h,t],!1,!0);return(await this.openDB()).getAllFromIndex("events","[sessionId+timestamp]",r)}async updateEventsExpiredAt(e,t,r=30){const n=new Date,a=n.setMinutes(n.getMinutes()+(r??30)),s=await this.getTransaction("events"),i=s.store.index("[sessionId+timestamp]"),c=IDBKeyRange.bound([h,e],[h,t],!1,!0);for await(const d of i.iterate(c))await d.update({...d.value,expiredAt:a});await s.done}async deleteChunkUploads(e,t){const r=IDBKeyRange.only([t,e]),n=await this.getTransaction("chunkUploads");let s=await n.store.index("[uploadId+status]").openCursor(r);for(;s;)s.delete(),s=await s.continue();await n.done}async getChunkUploadsByStatus({sessionId:e,status:t,uploadId:r}){const n=(await this.openDB()).transaction("chunkUploads","readonly");this.wrapTransactionWithCounter(n);const a=r?n.store.index("[uploadId+status]"):n.store.index("[sessionId+status]"),s=r?IDBKeyRange.only([r,t]):IDBKeyRange.only([e,t]);return a.getAll(s)}async getPendingCaptures(e={}){return(await(await this.openDB()).getAllFromIndex("pendingCaptures","sessionId",h)).filter(r=>!e.beforePresent||r.targetTimestamp<Date.now()).filter(r=>!e.isBeforeType||r.captureParams.replayParams.replayDurationType==="before").filter(r=>!e.isHeatmap||(r.captureParams.isHeatmap??!1))}async markPendingCaptureToCanUpload(e){const t=await this.getTransaction("pendingCaptures"),r=t.store.index("sessionId");for await(const n of r.iterate(h)){const a=n.value;a.captureParams.responseGroupId===e&&await n.update({...a,canUpload:!0})}await t.done}async markPendingHeatmapsReady(e){if(parseInt(o.sessionStorageHelper.getItem("sprig.pendingCount")??"0")===0)return null;const t=Date.now(),r=await this.getTransaction("pendingCaptures"),n=r.store.index("sessionId");for await(const a of n.iterate(h)){const s=a.value;!s.captureParams.isHeatmap||e&&!e.includes(s.uuid)||await a.update({...s,targetTimestamp:t,captureParams:{...s.captureParams,triggerTimestamp:t,replayParams:{...s.captureParams.replayParams,replayDurationSeconds:Math.floor((t-s.timestamp)/1e3)}}})}await r.done}},U=[];let F,He,J,Ne,G,Oe,M=[],_=!1,A=0,W=!1,Fe=!1,me=[],X=!1;const H=()=>W&&!_&&Date.now()<=J,St=({apiUrl:e,config:t,triggerSnapshot:r,forceInit:n=!1})=>{W&&!n||(o.sessionStorageHelper.isStorageAvailable?(M=[],me.splice(0),U.splice(0),A=0,G=r,He=e,F={responseGroupUuid:t.responseGroupUuid,surveyId:t.surveyId,userAgent:t.userAgent,sdkVersion:t.sdkVersion},Ne=t.maxDurationSeconds,Ct(),W||(Oe=window.setInterval(Rt,500)),W=!0):_=!0)},Dt=[P.Drag,P.Input,P.MediaInteraction,P.MouseInteraction,P.MouseMove,P.Scroll,P.Selection,P.TouchMove],Et=e=>e.type===L.Custom||e.type===L.IncrementalSnapshot&&Dt.includes(e.data.source),we=e=>e.some(Et),Rt=async()=>{if(!H())return void window.clearInterval(Oe);if(Ve(),!we(U))return;const e=U[0].timestamp;Date.now()-e>35e3&&(G==null||G())},Ve=async()=>{if(M.length||X)return;X=!0;const e=await Pt();if(!e)return void(_=!0);me.splice(0,e.length).forEach(t=>t(e.shift())),e.forEach(t=>M.push(t)),X=!1},Ct=()=>{const e=o.sessionStorageHelper.getItem("sprig.alwayson.info");if(e){o.breadcrumbsLogger.info("Read stored session state",e);const t=JSON.parse(e);_=t.disabled,F=t.metadata,M=t.uploadUrls,A=t.currentIndex,J=t.expirationTimestamp,t.pendingEventTimestamp&&(o.breadcrumbsLogger.info(`Uploading with pending timestamp: ${t.pendingEventTimestamp}`),Tt(t.pendingEventTimestamp))}else J=1e3*Ne+Date.now()},Tt=async e=>{const t=Date.now(),r=(await l.getEventsBetween(e,t)).map(a=>JSON.parse(a.event));if(!we(r))return;je(r);const n=await $e();n&&await We(n,r)},Ge=async(e,t)=>{try{const r=await e();if(!r.ok)throw new Error(`Error ${t}`);return r}catch{_=!0}},We=async(e,t)=>{if(!H()||!e)return;const r=await(async n=>{const a=new TextEncoder,s=new CompressionStream("gzip"),i=s.writable.getWriter(),c=a.encode(JSON.stringify(n));return i.write(c),i.close(),new Uint8Array(await new Response(s.readable).arrayBuffer())})(t);o.breadcrumbsLogger.info("Uploading always-on events with presigned url"),await Ge(()=>o.sprigFetch(e,{body:r,method:"PUT"}),"uploading always-on with presigned url")},Pt=async()=>{if(!H())return;const{surveyId:e,responseGroupUuid:t}=F,r={responseGroupUuid:t,surveyId:e,index:A+1};o.breadcrumbsLogger.info("Fetching always-on upload urls",r);const n=await Ge(()=>o.sprigFetch(`${He}/sdk/1/replayUrls`,{method:"POST",body:JSON.stringify(r),headers:o.getHttpHeaders(window.UserLeap)}),"fetching always-on signed urls");if(!n)return;const a=n.json.signedUrls;return o.breadcrumbsLogger.info("Fetched more always-on upload urls",{body:r,urls:a}),a},$e=async()=>{if(M.length)return M.shift();const e=new Promise(t=>{me.push(t)});return Ve(),e},je=e=>{var a,s,i;const t=e.length?e[e.length-1].timestamp:Date.now(),r=A,n=((s=(a=window.UserLeap)==null?void 0:a.config)==null?void 0:s.customMetadata)??((i=window.__cfg)==null?void 0:i.customMetadata);A++,e.push({timestamp:t,type:L.Custom,data:{tag:"Sprig_Meta",payload:{...F,index:r,visitorId:window.UserLeap.visitorId??"",timestamp:t,customMetadata:n}}})},kt=(e,t)=>{H()&&!Fe&&(e||U.length)&&(e&&U.length&&(async()=>{const r=U.splice(0);if(!we(r))return;o.breadcrumbsLogger.info("Capturing always-on event array to upload"),je(r);const n=await $e();n&&await We(n,r)})(),U.push(t))};window.addEventListener("beforeunload",async()=>{Fe=!0,H()&&(o.breadcrumbsLogger.info("Always On handle page unload"),(()=>{let e;U.length&&(e=U[0].timestamp);const t={disabled:_,metadata:F,uploadUrls:M,currentIndex:A,pendingEventTimestamp:e,expirationTimestamp:J};o.breadcrumbsLogger.info("Storing session state on unload",t),o.sessionStorageHelper.setItem("sprig.alwayson.info",JSON.stringify(t))})())});const Ke=async(e,t)=>{const r=performance.now();let n;try{n=await e()}finally{const a=performance.now()-r;let s=o.PerformanceMetrics[t];s||(s=o.registerMetric(t)),s.report(a/1e3)}return n},Je=(e,t)=>{const r=performance.now();try{e()}finally{const n=performance.now()-r;let a=o.PerformanceMetrics[t];a||(a=o.registerMetric(t)),a.report(n/1e3)}};let qe=5e3,ie=6e4,de=0,B,ce=!1,ue=[];const Ut=e=>{var t,r,n,a;if((t=e.event)!=null&&t.includes("Sprig_Scroll")){const s=(a=(n=(r=JSON.parse(e.event))==null?void 0:r.data)==null?void 0:n.payload)==null?void 0:a.xPath;if(!s)return;g.scrollEventUuids[s]=e.uuid}ue.push(e),ce||Lt()},Lt=()=>{ce=!0,setTimeout(async()=>{if(C()||K())return;const e=ue;ue=[],ce=!1,Je(async()=>{await(async t=>{const r=t.map(n=>({...n,sessionId:n.sessionId??h}));if(r.length!==0)return b(()=>l.bulkAdd("events",r),"Error storing replay events")})(e)},"sdk_replay_add_event_batch_seconds")},500)},xt=(e,t,r)=>{g.cleanupInterval=window.setInterval(()=>{const n=Date.now();Ke(()=>b(async()=>{C()||await Promise.all([l.deleteRowsBefore("events",n-1e3*e,a=>a.expiredAt===void 0||a.expiredAt<n-1e3*e),l.deleteRowsBefore("chunkUploads",n-1e3*t),l.deleteRowsBefore("pendingCaptures",n-1e3*r,a=>!a.canUpload)])},"Error deleting table rows"),"sdk_replay_cleanup_seconds"),o.breadcrumbsLogger.debug("CleanupComplete")},3e4)},Bt=()=>{g.pendingCheckInterval=window.setInterval(async()=>{b(async()=>{await le()},"Error initiating pending captures")},5e3)};let Y=!1;const le=async(e=!1)=>{if(!Y)try{Y=!0;const t=parseInt(B??"0");if(t===0)return;const r=await l.getPendingCaptures({beforePresent:!0,isBeforeType:e}),n=await l.openDB();await Promise.all(r.map(async a=>(await n.delete("pendingCaptures",a.uuid),Xe(a.captureParams,a.canUpload)))),B=(t-r.length).toString(),o.sessionStorageHelper.setItem("sprig.pendingCount",B)}finally{Y=!1}},Mt=async(e,t,r,n,a)=>{const s=Math.min(e+a,r),i=await Ke(()=>l.getEventsBetween(e,s),"sdk_replay_get_events_between_seconds");if(!(i!=null&&i.length))return o.breadcrumbsLogger.debug("NoEventsFound"),{validStartFound:n,events:[]};if(!n){o.breadcrumbsLogger.debug("ValidStartSearch");let c=-1;return i==null||i.forEach((d,u)=>{if(!d.isValidStart)return;const w=d.timestamp<=t;(c<0||w)&&(c=u)}),c<0?(o.breadcrumbsLogger.debug("ValidStartNotFound"),{validStartFound:n,events:[]}):{validStartFound:!0,events:i==null?void 0:i.slice(c)}}return{validStartFound:n,events:i}},ze=e=>Promise.all(e.map(async t=>{const r=await(async n=>Ce.execute(async()=>{var i;o.breadcrumbsLogger.info("UploadChunkStart",{chunkIndex:n.chunkIndex,surveyId:n.surveyId});const a=await o.sprigFetch(n.uploadUrl,{body:n.data,method:"PUT"});o.breadcrumbsLogger.http("UploadChunkEnd",{url:n.uploadUrl,method:"PUT",status_code:a.status,reason:a.statusText??"OK",chunkIndex:n.chunkIndex,surveyId:n.surveyId});const s=(i=a.headers)==null?void 0:i.get("ETag");if(!s)throw new Error(`Upload response did not include etag for upload ${n.uploadId}, part ${n.chunkIndex}`);return s}))(t);return await l.updatePartial("chunkUploads",t.uuid,{data:null,etag:r,status:"UploadComplete"}),t.uploadId})),Qe=async e=>{const t=await l.getChunkUploadsByStatus({status:"UploadComplete",uploadId:e});if(!(t!=null&&t.length))return void o.breadcrumbsLogger.info("NoChunksForUpload",{uploadId:e});const r=t.reduce((s,i)=>(s.find(c=>c.chunkIndex===i.chunkIndex)||s.push(i),s),[]);r.sort((s,i)=>s.chunkIndex-i.chunkIndex);const n=r.map(s=>({ETag:s.etag,PartNumber:s.chunkIndex})).filter(s=>s.ETag!==null),a=r[0];await Te({apiUrl:a.apiUrl,surveyId:a.surveyId,uploadId:e,responseGroupUuid:a.responseGroupId,etags:n,headers:a.completeUploadHeaders,replayDuration:a.replayDuration}),await l.deleteChunkUploads("UploadComplete",e)},At=()=>{b(async()=>{const e=await l.getChunkUploadsByStatus({sessionId:h,status:"ReadyForUpload"});if(!(e!=null&&e.length))return;const t=await ze(e);t!=null&&t.length&&await Promise.all(t.map(r=>{if(r)return Qe(r)}))},"Error uploading unfinished chunks")},_t=async(e,t)=>{const r=t??Date.now();return(async(n,a)=>{const s=new TextEncoder;let i=null;const c=new CompressionStream("gzip"),d=c.writable.getWriter();let u=!1,w=!1,[p,f]=[0,0],m=[];for(let T=n-35e3;T<a;T+=ie){if({validStartFound:w,events:m}=await Mt(T,n,a,w,ie),!(m!=null&&m.length)){o.breadcrumbsLogger.debug("NoEventsFound");continue}p===0&&(p=m[0].timestamp),f=m[m.length-1].timestamp;const y=m.map(E=>E.event);y.push(`{"timestamp":${a}}`);const I=`${u?",":"["}${y}`,v=s.encode(I);Je(()=>{d.write(v)},"sdk_replay_compression_seconds"),u=!0}if(f-p<qe)return o.breadcrumbsLogger.debug("ReplayTooShort"),null;const D=s.encode("]");return d.write(D),d.close(),i=new Uint8Array(await new Response(c.readable).arrayBuffer()),i})(r-e,r)},De=async e=>{const{surveyId:t,responseGroupId:r,visitorId:n,apiUrl:a,completeUploadHeaders:s,replayParams:i,triggerTimestamp:c}=e,d=await _t(1e3*i.replayDurationSeconds,c);if(!(d!=null&&d.length))return void o.breadcrumbsLogger.info("FileDataEmpty",{surveyId:t});const u=((p,f,m)=>{const D=p.length,T=1024*f*1024,y=Math.ceil(D/m),I=Math.max(T,y),v=[];let E=0;for(;E<D;)v.push(p.slice(E,E+I)),E+=I;return v})(d,i.minimumChunkSizeMb,i.signedUrls.length),w=await Promise.all(u.map(async(p,f)=>{const m=o.v4(),D={apiUrl:a,chunkIndex:f+1,completeUploadHeaders:s,etag:null,responseGroupId:r,status:"ReadyForUpload",surveyId:t,timestamp:c,totalChunks:u.length,data:p,uploadId:i.uploadId,uploadUrl:i.signedUrls[f].url,uuid:m,visitorId:n};return await(await l.openDB()).add("chunkUploads",{...D,sessionId:D.sessionId??h}),D}));await(async(p,f)=>{await ze(f),await Promise.all(p.map(m=>Qe(m)))})([i.uploadId],w)},Xe=async(e,t)=>{if(C())return o.breadcrumbsLogger.debug("ReplayDisabled-ScheduleOrCapture");const{isHeatmap:r,isStandalone:n,replayParams:a,triggerTimestamp:s,responseGroupId:i}=e,c=async()=>{setTimeout(()=>o.eventEmitter.removeListener(o.SprigEvent.QuestionAnswered,c),0),b(async()=>{a.replayDurationType==="before"?await De(e):await l.markPendingCaptureToCanUpload(i)},"Error in schedule/capture callback")};b(async()=>{if(a.replayDurationType==="after"||a.replayDurationType==="beforeAndAfter")return!n&&!r&&o.eventEmitter.on(o.SprigEvent.QuestionAnswered,c),void await Ze(e);if(n||r||t)await De(e),r&&Ht();else{const d=35+a.replayDurationSeconds,u=s-1e3*d,w=s;await l.updateEventsExpiredAt(u,w,a.expirationTimeLimitMinutes),o.eventEmitter.on(o.SprigEvent.QuestionAnswered,c)}},"Error in scheduling/capturing replay")},Ht=async()=>{parseInt(B??"0")||o.sessionStorageHelper.removeItem("sprig.isCapturingHeatmap"),o.sessionStorageHelper.getItem("sprig.teardownAfterCapture")&&(_e(),Ye(),o.sessionStorageHelper.removeItem("sprig.teardownAfterCapture"))},Ye=async()=>C()?o.breadcrumbsLogger.debug("ReplayDisabled-ClearData"):Promise.all([l.deleteBySessionId("events",h),l.deleteBySessionId("pendingCaptures",h)]).catch(e=>{O("Error clearing user replay data",e)}),Ze=async e=>{if(C())return;const{isHeatmap:t,surveyId:r}=e,n=await l.getPendingCaptures(),a=n==null?void 0:n.filter(d=>d.captureParams.surveyId===r);if(a!=null&&a.length)return void o.breadcrumbsLogger.info("PendingCaptureExists",{surveyId:r});t&&(oe(),o.sessionStorageHelper.setItem("sprig.isCapturingHeatmap","true"),de=Date.now(),g.inactivityInterval||(g.inactivityInterval=window.setInterval(()=>{var d;d=de,Date.now()-d>=3e4&&b(()=>l.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 i=e.triggerTimestamp+1e3*e.replayParams.replayDurationSeconds;s.triggerTimestamp=i,B=(parseInt(B??"0")+1).toString(),o.sessionStorageHelper.setItem("sprig.pendingCount",B),await(await l.openDB()).add("pendingCaptures",{canUpload:!1,captureParams:s,sessionId:h,targetTimestamp:i,timestamp:Date.now(),uuid:o.v4()})},Nt=Object.freeze(Object.defineProperty({__proto__:null,RecordEvent:e=>{k("Sprig_TrackEvent",e)},RecordPageView:e=>{e.description&&(e.description=ge(e.description)),k("Sprig_PageView",e)},RecordSurveyShown:e=>{k("Sprig_ShowSurvey",e)},_completeSessionReplay:async({surveyId:e,responseGroupUuid:t,eventDigest:r,headers:n})=>{if(!e||!t)return!1;const a=window.UserLeap._API_URL,s=await Te({surveyId:e,responseGroupUuid:t,eventDigest:r,apiUrl:a,headers:n},!0);return!(s!=null&&s.error)},checkPendingHeatmapsUrl:()=>C()?o.breadcrumbsLogger.debug("ReplayDisabled-PendingHeatmaps"):b(async()=>{const e=(await l.getPendingCaptures({isHeatmap:!0})).map(t=>({eventId:t.captureParams.eventId,uuid:t.uuid})).filter(({eventId:t})=>!o.checkUrlStillMatching(t)).map(({uuid:t})=>t);return o.breadcrumbsLogger.info("PendingHeatmapsToComplete",{count:e.length}),e.length&&(await l.markPendingHeatmapsReady(e),o.breadcrumbsLogger.info("MarkedPendingHeatmapsReady")),e.length},"Error marking pending heatmaps ready"),clearUserReplayData:Ye,disableRecording:O,initializeReplay:async({maxReplayDurationSeconds:e,maxInflightRequests:t=2,replaySettings:r,teardownAfter:n=!1,apiUrl:a,alwaysOnConfig:s})=>{if(s&&St({apiUrl:a,config:s,triggerSnapshot:()=>{oe()}}),B=o.sessionStorageHelper.getItem("sprig.pendingCount"),g.isRecording)return;if(n&&o.sessionStorageHelper.setItem("sprig.teardownAfterCapture","true"),C())return o.breadcrumbsLogger.debug("ReplayDisabled");if(await(async()=>{var d;if(!Ae())return!0;if((d=window.navigator.storage)!=null&&d.estimate)try{const{quota:u=0,usage:w=0}=await window.navigator.storage.estimate(),p=(u-w)/1024**3;return o.breadcrumbsLogger.info("Storage",{availableGb:p}),p<.5}catch{return!0}return!1})())return o.breadcrumbsLogger.debug("IDBNotSupported"),se();try{const d=await l.openDB();o.breadcrumbsLogger.info("DBVersion",{version:d.version})}catch(d){return o.breadcrumbsLogger.error("ReplayOpenErr",{name:d.name}),d.name==="VersionError"&&l.deleteDB(),se()}b(async()=>{await le(!0)},"Error uploading ready pending captures");const i=H()?30:0,c=Math.max(e??0,i);if(!c)return o.breadcrumbsLogger.debug("MissingDuration");o.breadcrumbsLogger.debug("ReplayInit"),await b(async()=>{var d;r!=null&&r.minDuration&&(qe=r.minDuration),r!=null&&r.batchDuration&&(ie=r.batchDuration),d=t,Ce.setLimit(d),At(),xt(c+35,1800,c+35),Bt();const u=window.UserLeap.replayLibraryURL??"https://cdn.sprig.com/dependencies/record-2.0.0-alpha.17.min.js";if(!window.rrwebRecord){const{record:y}=await import(u);window.rrwebRecord=y}const w=window.rrwebRecord;if(!w)return o.breadcrumbsLogger.error("RecordScriptFailed");let p=!0,f=0;const m={checkoutEveryNms:3e4,sampling:{input:"last",scroll:250,media:800},...r};var D,T;g.stopRecording=w({emit:(y,I)=>{if(y.type===L.Custom&&(de=Date.now()),C()||K())return;if(I&&y.type===L.Meta)f=performance.now();else if(I&&f&&y.type===L.FullSnapshot){const E=performance.now()-f;o.reportAndRegister("sdk_replay_snapshot_seconds",E/1e3)}const v=p||!!I&&y.type===L.Meta;p=!1,kt(v,y),Ut({uuid:o.v4(),event:JSON.stringify(y),isValidStart:v,timestamp:Date.now()})},...m}),g.isRecording=!!g.stopRecording,g.isRecording&&(((y,I)=>{window.addEventListener("message",v=>{var E;v.data.type===ct&&(pe.push({source:v.source,origin:v.origin}),(E=v.source)==null||E.postMessage({type:ut,settings:y,replayLibraryUrl:I},{targetOrigin:v.origin}))})})(m,u),o.eventEmitter.on("survey.complete",y=>{var I;I={id:y,userAgent:window.navigator.userAgent},k("Sprig_SubmitSurvey",I)}),D=k,T=It,j||(S=D,V=T,window.addEventListener("click",xe,R),window.addEventListener("pointerdown",Me,R),window.addEventListener("mousedown",Be,R),window.addEventListener("keydown",Ue,R),window.addEventListener("scroll",Le,R),j=!0,ft(),ht()))},"Error initializing replay")},isReplayPaused:K,isReplayRecording:()=>g.isRecording,recordFullSnapshot:oe,recordReplayPaused:()=>{k("Sprig_ReplayPaused",{timestamp:Date.now()}),o.sessionStorageHelper.setItem("sprig.isReplayPaused","true")},recordReplayResumed:()=>{o.sessionStorageHelper.removeItem("sprig.isReplayPaused"),k("Sprig_ReplayResumed",{timestamp:Date.now()})},scheduleCapture:Ze,scheduleOrCaptureReplay:Xe,tryReplayAction:b,uploadReadyPendingCaptures:le},Symbol.toStringTag,{value:"Module"}));o.registerReplay(Nt);
|