@sprig-technologies/sprig-browser 2.40.3 → 2.41.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/conversational-ui-BhbQgh6X.cjs +1 -0
- package/dist/conversational-ui-DlnwFL72.js +593 -0
- package/dist/{core-Bu7SvToK.js → core-CRJIQvxS.js} +3 -3
- package/dist/{core-C6T-kQJo.cjs → core-DY4ohxcP.cjs} +2 -2
- package/dist/core.cjs +1 -1
- package/dist/core.d.ts +64 -5
- package/dist/core.js +2 -2
- package/dist/{getAttributedUrl-Czw_vkQN.js → getAttributedUrl-CVKJ3sRY.js} +14 -7
- package/dist/{getAttributedUrl-HU3np_BZ.cjs → getAttributedUrl-DxxH9aNE.cjs} +2 -2
- package/dist/index-CA0jioLg.cjs +1 -0
- package/dist/index-Dj3ZmhVC.js +749 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +64 -5
- package/dist/index.js +2 -2
- package/dist/{metricsReporter-0SKeVvnG.cjs → metricsReporter-Dq2lxT-9.cjs} +1 -1
- package/dist/{metricsReporter-MLC5Ejl7.js → metricsReporter-uLWRAnwI.js} +1 -1
- package/dist/replay.cjs +1 -1
- package/dist/replay.js +1 -1
- package/dist/view-Bt__MdRk.js +1722 -0
- package/dist/view-KypSYKm-.cjs +1 -0
- package/package.json +1 -1
- package/dist/conversational-ui-Cm0ADZ91.js +0 -579
- package/dist/conversational-ui-DWIDxaCY.cjs +0 -1
- package/dist/index-DKYCbzko.cjs +0 -1
- package/dist/index-H_s2z0Uz.js +0 -695
- package/dist/view-BkptC8BC.js +0 -1503
- package/dist/view-DSm0GsZ1.cjs +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./core-
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./core-DY4ohxcP.cjs");require("./replay.cjs");const r=require("./metricsReporter-Dq2lxT-9.cjs");exports.SprigAPI=e.SprigAPI,exports.default=e.core,exports.sprig=e.sprig,exports.DismissReason=r.DismissReason,exports.SprigEvent=r.SprigEvent;
|
package/dist/index.d.ts
CHANGED
|
@@ -1012,18 +1012,56 @@ interface PassthroughData {
|
|
|
1012
1012
|
type MultiChoiceSecondaryValueType = Record<string, {
|
|
1013
1013
|
userText: string;
|
|
1014
1014
|
}> | null;
|
|
1015
|
+
declare const enum MaxDiffChoice {
|
|
1016
|
+
RIGHT = "right",
|
|
1017
|
+
LEFT = "left"
|
|
1018
|
+
}
|
|
1019
|
+
type MaxDiffValueType = {
|
|
1020
|
+
id: number;
|
|
1021
|
+
option: string;
|
|
1022
|
+
selected: MaxDiffChoice | null;
|
|
1023
|
+
};
|
|
1024
|
+
type MaxDiffResponseType = Array<Array<MaxDiffValueType>>;
|
|
1015
1025
|
interface RecordedTaskResponseValueType {
|
|
1016
1026
|
mediaRecordingUids?: string[] | null;
|
|
1017
1027
|
taskDurationMillisecond?: number;
|
|
1018
1028
|
taskStatus: TaskStatus;
|
|
1019
1029
|
}
|
|
1030
|
+
type TextUrlPromptResponse = undefined | {
|
|
1031
|
+
skipped?: true;
|
|
1032
|
+
};
|
|
1033
|
+
type ConsentLegalResponse = {
|
|
1034
|
+
submitted: true;
|
|
1035
|
+
} | null;
|
|
1036
|
+
type RecordedTaskResponse = {
|
|
1037
|
+
mediaRecordingUids: string[];
|
|
1038
|
+
taskDurationMillisecond: number;
|
|
1039
|
+
taskStatus: TaskStatus;
|
|
1040
|
+
};
|
|
1041
|
+
type LikertResponse = number | null;
|
|
1042
|
+
type OpenTextResponse = string;
|
|
1043
|
+
type AiDynamicFollowUpResponse = string;
|
|
1044
|
+
type MultiChoiceresponse = string | undefined;
|
|
1045
|
+
type MultiSelectResponse = string[];
|
|
1046
|
+
type MatrixResponse = {
|
|
1047
|
+
[rowId: number]: string | null;
|
|
1048
|
+
};
|
|
1049
|
+
type NpsResponse = number | null;
|
|
1050
|
+
type RankOrderResponse = {
|
|
1051
|
+
[optionId: string]: number | null;
|
|
1052
|
+
};
|
|
1053
|
+
type VideoVoiceResponse = {
|
|
1054
|
+
mediaRecordingUid: string;
|
|
1055
|
+
};
|
|
1056
|
+
type CardResponse = TextUrlPromptResponse | ConsentLegalResponse | RecordedTaskResponse | LikertResponse | OpenTextResponse | AiDynamicFollowUpResponse | MultiChoiceresponse | MultiSelectResponse | MatrixResponse | NpsResponse | RankOrderResponse | MaxDiffResponseType | VideoVoiceResponse;
|
|
1057
|
+
|
|
1020
1058
|
declare const BOOLEAN_OPERATOR: {
|
|
1021
1059
|
readonly And: 1;
|
|
1022
1060
|
readonly Or: 2;
|
|
1023
1061
|
};
|
|
1024
1062
|
type BooleanOperator = (typeof BOOLEAN_OPERATOR)[keyof typeof BOOLEAN_OPERATOR];
|
|
1025
1063
|
|
|
1026
|
-
type CardType = "consentlegal" | "likert" | "matrix" | "maxdiff" | "multiplechoice" | "multipleselect" | "nps" | "open" | "rankorder" | "recordedtask" | "texturlprompt" | "thanks" | "uploading" | "videovoice";
|
|
1064
|
+
type CardType = "aidynamicfollowup" | "consentlegal" | "likert" | "matrix" | "maxdiff" | "multiplechoice" | "multipleselect" | "nps" | "open" | "rankorder" | "recordedtask" | "texturlprompt" | "thanks" | "uploading" | "videovoice";
|
|
1027
1065
|
type ConceptUrl = string | null;
|
|
1028
1066
|
type GroupType = "page";
|
|
1029
1067
|
interface BaseCard {
|
|
@@ -1032,9 +1070,11 @@ interface BaseCard {
|
|
|
1032
1070
|
updatedAt: string;
|
|
1033
1071
|
value?: unknown;
|
|
1034
1072
|
type: CardType;
|
|
1035
|
-
groupId?: number;
|
|
1073
|
+
groupId?: number | null;
|
|
1036
1074
|
secondaryValue?: MultiChoiceSecondaryValueType | null;
|
|
1037
1075
|
groupType?: GroupType;
|
|
1076
|
+
childId?: number | null;
|
|
1077
|
+
parentId?: number | null;
|
|
1038
1078
|
}
|
|
1039
1079
|
type Comparator = "answered" | "contains" | "notcontains" | "list_dni" | "eq" | "given_up" | "gt" | "gte" | "lt" | "lte" | "list_all" | "list_alo" | "list_exact" | "neq" | "partial" | "skipped";
|
|
1040
1080
|
type Randomize = "none" | "all";
|
|
@@ -1052,7 +1092,7 @@ type GroupRoutingOption = {
|
|
|
1052
1092
|
};
|
|
1053
1093
|
type RoutingGroupOption = {
|
|
1054
1094
|
comparator: Comparator;
|
|
1055
|
-
questionIndex: number;
|
|
1095
|
+
questionIndex: number | string;
|
|
1056
1096
|
value: number | string | string[] | {
|
|
1057
1097
|
skipped: true;
|
|
1058
1098
|
} | null | undefined;
|
|
@@ -1220,6 +1260,19 @@ interface OpenTextCard extends BaseCard {
|
|
|
1220
1260
|
};
|
|
1221
1261
|
type: "open";
|
|
1222
1262
|
}
|
|
1263
|
+
/**
|
|
1264
|
+
* DynamicQuestionCard loading:
|
|
1265
|
+
* - `true` — DQ network request inflight
|
|
1266
|
+
* - `false` - successful DQ network request
|
|
1267
|
+
* - `undefined` - network call not yet triggered
|
|
1268
|
+
* - `null` - unsuccessful DQ network call
|
|
1269
|
+
*/
|
|
1270
|
+
interface DynamicQuestionCard extends BaseCard {
|
|
1271
|
+
props: OpenTextCard["props"] & {
|
|
1272
|
+
loading?: boolean | null;
|
|
1273
|
+
};
|
|
1274
|
+
type: "aidynamicfollowup";
|
|
1275
|
+
}
|
|
1223
1276
|
interface MultipleChoiceOption {
|
|
1224
1277
|
createdAt: string;
|
|
1225
1278
|
deletedAt: null;
|
|
@@ -1402,7 +1455,7 @@ interface VideoVoiceCard extends BaseCard {
|
|
|
1402
1455
|
};
|
|
1403
1456
|
type: "videovoice";
|
|
1404
1457
|
}
|
|
1405
|
-
type Card = TextUrlPromptCard | ConsentLegalCard | RecordedTaskCard | LikertCard | OpenTextCard | MatrixCard | MaxDiffType | MultipleChoiceSingleSelectCard | MultipleChoiceMultiSelectCard | NPSCard | RankOrderType | VideoVoiceCard;
|
|
1458
|
+
type Card = TextUrlPromptCard | ConsentLegalCard | DynamicQuestionCard | RecordedTaskCard | LikertCard | OpenTextCard | MatrixCard | MaxDiffType | MultipleChoiceSingleSelectCard | MultipleChoiceMultiSelectCard | NPSCard | RankOrderType | VideoVoiceCard;
|
|
1406
1459
|
|
|
1407
1460
|
type InteractiveMatchType = "exactly" | "legacy";
|
|
1408
1461
|
type PageUrlMatchType = "contains" | "exactly" | "legacy" | "notContains" | "regex" | "startsWith";
|
|
@@ -1703,7 +1756,8 @@ interface AppProductConfig {
|
|
|
1703
1756
|
}
|
|
1704
1757
|
interface Config extends MobileReplayConfig {
|
|
1705
1758
|
addResponseGroupMeta?: () => Promise<JSONObject>;
|
|
1706
|
-
allResponses:
|
|
1759
|
+
allResponses: CardResponse[];
|
|
1760
|
+
allResponsesRaw: Record<string | number, string>;
|
|
1707
1761
|
answers?: Answer[];
|
|
1708
1762
|
apiURL: string;
|
|
1709
1763
|
avatars: Avatars;
|
|
@@ -1720,6 +1774,10 @@ interface Config extends MobileReplayConfig {
|
|
|
1720
1774
|
outcome: string;
|
|
1721
1775
|
};
|
|
1722
1776
|
};
|
|
1777
|
+
createDynamicQuestion: (s: {
|
|
1778
|
+
parentQuestionId: number;
|
|
1779
|
+
parentResponseConfig?: Config["allResponsesRaw"];
|
|
1780
|
+
}) => void;
|
|
1723
1781
|
customMetadata?: Record<string, unknown>;
|
|
1724
1782
|
customStyles?: string;
|
|
1725
1783
|
dismissOnPageChange: boolean;
|
|
@@ -2088,6 +2146,7 @@ declare namespace sprigConfig {
|
|
|
2088
2146
|
declare global {
|
|
2089
2147
|
interface Window {
|
|
2090
2148
|
__cfg: Config;
|
|
2149
|
+
__sprigReinitialize?: () => void;
|
|
2091
2150
|
attachEvent?: typeof window.addEventListener;
|
|
2092
2151
|
Backbone: {
|
|
2093
2152
|
history: typeof window.history;
|
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-CRJIQvxS.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-uLWRAnwI.js";
|
|
4
4
|
export {
|
|
5
5
|
t as DismissReason,
|
|
6
6
|
i as SprigAPI,
|
|
@@ -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 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.40.3","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)};
|
|
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.41.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)};
|
|
@@ -217,7 +217,7 @@ const J = (e) => e._config && e._config.installationMethod ? e._config.installat
|
|
|
217
217
|
U = !0, A = e;
|
|
218
218
|
};
|
|
219
219
|
function ce(e = {}) {
|
|
220
|
-
const t = { "Content-Type": "application/json", "userleap-platform": "web", "x-ul-sdk-version": "2.
|
|
220
|
+
const t = { "Content-Type": "application/json", "userleap-platform": "web", "x-ul-sdk-version": "2.41.0", "x-ul-installation-method": J(e), "sprig-modules": B() };
|
|
221
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) {
|
|
222
222
|
const s = JSON.parse(e.mobileHeadersJSON);
|
|
223
223
|
Object.assign(t, s);
|
package/dist/replay.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var et=Object.defineProperty;var tt=(e,t,n)=>t in e?et(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var N=(e,t,n)=>tt(e,typeof t!="symbol"?t+"":t,n);const o=require("./metricsReporter-0SKeVvnG.cjs"),nt=require("./debounce-DsC7462b.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||{}),T=(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))(T||{});const Z=(e,t)=>t.some(n=>e instanceof n);let ye,fe;const ee=new WeakMap,q=new WeakMap,$=new WeakMap;let te={get(e,t,n){if(e instanceof IDBTransaction){if(t==="done")return ee.get(e);if(t==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return x(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&(t==="done"||t==="store")||t in e};function 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(ne(this),t),x(this.request)}:function(...t){return x(e.apply(ne(this),t))}}function at(e){return typeof e=="function"?rt(e):(e instanceof IDBTransaction&&function(t){if(ee.has(t))return;const n=new Promise((r,a)=>{const s=()=>{a(t.error||new DOMException("AbortError","AbortError"))};t.oncomplete=()=>{r()},t.onerror=s,t.onabort=s});ee.set(t,n)}(e),Z(e,ye||(ye=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,te):e)}function x(e){if(e instanceof IDBRequest)return function(n){const r=new Promise((a,s)=>{n.onsuccess=()=>{a(x(n.result))},n.onerror=()=>{s(n.error)}});return $.set(r,n),r}(e);if(q.has(e))return q.get(e);const t=at(e);return t!==e&&(q.set(e,t),$.set(t,e)),t}const ne=e=>$.get(e);function re(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&(n.onblocked=r=>t(r.oldVersion,r)),x(n).then(()=>{})}const st=["get","getKey","getAll","getAllKeys","count"],ot=["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 n=t.replace(/FromIndex$/,""),r=t!==n,a=ot.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!a&&!st.includes(n))return;const s=async function(i,...c){const d=this.transaction(i,a?"readwrite":"readonly");let u=d.store;return r&&(u=u.index(c.shift())),(await Promise.all([u[n](...c),a&&d.done]))[0]};return z.set(t,s),s}Ee(e=>({...e,get:(t,n,r)=>he(t,n)||e.get(t,n,r),has:(t,n)=>!!he(t,n)||e.has(t,n)}));const it=["continue","continuePrimaryKey","advance"],Ie={},ae=new WeakMap,Re=new WeakMap,dt={get(e,t){if(!it.includes(t))return e[t];let n=Ie[t];return n||(n=Ie[t]=function(...r){ae.set(this,Re.get(this)[t](...r))}),n}};async function*ct(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,dt);for(Re.set(n,t),$.set(n,ne(t));t;)yield n,t=await(ae.get(n)||t.continue()),ae.delete(n)}function ve(e,t){return t===Symbol.asyncIterator&&Z(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&Z(e,[IDBIndex,IDBObjectStore])}Ee(e=>({...e,get:(t,n,r)=>ve(t,n)?ct:e.get(t,n,r),has:(t,n)=>ve(t,n)||e.has(t,n)}));const ut="sprigReplayIframeLoaded",lt="sprigReplayIframeSettings",pt="sprigReplayIframeTakeFullSnapshot",gt="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),Pe=async({apiUrl:e,surveyId:t,uploadId:n,etags:r,headers:a,responseGroupUuid:s,replayDuration:i,eventDigest:c},d=!1)=>{var w;if(!d&&!n&&!r)return void o.breadcrumbsLogger.error("UploadErr",{isMobile:d,uploadId:n,etags:r});o.breadcrumbsLogger.info("MarkUploadComplete",{surveyId:t});const u=await o.sprigFetch(`${e}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:r,uploadId:n,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},mt=e=>{if(e instanceof Attr)return null;let t=1;for(let n=e.previousSibling;n;n=n.previousSibling)n.nodeName===e.nodeName&&++t;return t},Te=e=>{if(e===null)return"";const t=[];if(e instanceof Document)return"/";for(let n=e;n&&!(n instanceof Document)&&n!==null;n=n instanceof Attr?n.ownerElement:n.parentElement){const r=t[t.length]={name:void 0,position:null};switch(n.nodeType){case Node.TEXT_NODE:r.name="text()";break;case Node.ATTRIBUTE_NODE:r.name="@"+n.nodeName;break;case Node.PROCESSING_INSTRUCTION_NODE:r.name="processing-instruction()";break;case Node.COMMENT_NODE:r.name="comment()";break;case Node.ELEMENT_NODE:r.name=n.nodeName}r.position=mt(n)}return"/"+t.reverse().map(n=>n.position!==null?`/${n.name}[${n.position}]`:`/${n.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},wt=["a","button","input","option","li","link"],yt=["Escape","Enter","Backspace","F5","Tab"];let K=!1,S=null,j=null;const be=e=>{var n;if(((n=e.tagName)==null?void 0:n.toLowerCase())==="html")return{element:"html"};const t={};return t.element=(r=>{if(!r.tagName)return"No tagName";const a=r.getAttribute("type");return a?`${a} ${r.tagName.toLowerCase()}`:r.tagName.toLowerCase()})(e),t},ft=e=>{var r;if(!e)return{};const t={...be(e)},n=e.parentElement;if(n&&wt.includes((r=n.tagName)==null?void 0:r.toLowerCase())){const a=be(n);Object.assign(t,a)}return t},ke=(e,t)=>{var a,s;let n=t.target;var r;t.target===((a=window.document)==null?void 0:a.body)&&window.Sprig.pointerDownTarget&&(n=window.Sprig.pointerDownTarget),r={x:t.x,y:t.y,type:e,elementAttributes:ft(n),windowHeight:window.innerHeight,windowWidth:window.innerWidth,...n instanceof HTMLElement||n instanceof SVGElement||n instanceof MathMLElement?{rect:n==null?void 0:n.getBoundingClientRect(),xPath:Te(n)}:{}},(s=r==null?void 0:r.elementAttributes)!=null&&s.text&&(r.elementAttributes.text=ge(r.elementAttributes.text)),S==null||S("Sprig_Click",r)},Ue=e=>{var t;yt.includes(e.key)&&(t={key:e.key},S==null||S("Sprig_Keystroke",t))},ht=()=>{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))},It=()=>{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=nt.debounce(e=>{if(!(e.target instanceof HTMLElement||e.target instanceof Document))return;let t=e.target;"scrollTop"in t||(t=t.documentElement),j==null||j({xPath:Te(t),x:t.scrollLeft,y:t.scrollTop,elementAttributes:{targetScrollWidth:t.scrollWidth,targetClientWidth:t.clientWidth,targetScrollHeight:t.scrollHeight,targetClientHeight:t.clientHeight}})},750),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"),V=()=>!!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 n,r;if(!C()&&g.isRecording&&!V())try{(r=(n=window.rrwebRecord)==null?void 0:n.addCustomEvent)==null||r.call(n,e,t)}catch(a){O("Error recording custom event",a)}},vt=async e=>{const{x:t,xPath:n,y:r}=e,a=g.scrollEventUuids[n];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=r>((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=r),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)}),K&&(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),K=!1),pe.forEach(e=>{var t;(t=e.source)==null||t.postMessage({type:gt},{targetOrigin:e.origin})})},bt=["did not allow mutations","called in an invalid security context"],St=(e,t,{reportError:n=!0,extraInfo:r={}})=>{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 bt)if(a.toLowerCase().includes(s))return!1;return!0})(t==null?void 0:t.message)&&(n&&window.UserLeap.reportError(e,t,r),l.clearAll())}},O=(e,t,{reportError:n}={reportError:!0})=>{_e(),o.breadcrumbsLogger.error("ReplayErr",{code:t.code,name:t.name}),St(e,t,{reportError:n})},b=async(e,t)=>{try{return await e()}catch(n){O(t,n)}},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:pt},{targetOrigin:e.origin})}))};let Q=0;(async()=>Ae()&&Promise.allSettled([re("replayStorage"),re("sprig.replay")]))();const l=new class{constructor(){N(this,"wrapTransactionWithCounter",e=>{var r,a;const t=(a=(r=window.Sprig)==null?void 0:r._config)==null?void 0:a.outstandingTransactionLimit,n=t===void 0?100:t;if(n&&Q>n){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:n,upgrade:r,blocking:a,terminated:s}={}){const i=indexedDB.open(e,t),c=x(i);return r&&(i.onupgradeneeded=d=>{r(x(i.result),d.oldVersion,d.newVersion,x(i.transaction),d)}),n&&(i.onblocked=d=>n(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,n)=>{if(n===0&&o.sessionStorageHelper.setItem("sprig.pendingCount","0"),!e.objectStoreNames.contains("events")){const r=e.createObjectStore("events",{keyPath:"uuid"});r.createIndex("sessionId","sessionId"),r.createIndex("timestamp","timestamp"),r.createIndex("[sessionId+timestamp]",["sessionId","timestamp"])}if(!e.objectStoreNames.contains("chunkUploads")){const r=e.createObjectStore("chunkUploads",{keyPath:"uuid"});r.createIndex("sessionId","sessionId"),r.createIndex("timestamp","timestamp"),r.createIndex("[sessionId+status]",["sessionId","status"]),r.createIndex("[uploadId+status]",["uploadId","status"]),r.createIndex("[sessionId+status+uploadId]",["sessionId","status","uploadId"])}if(!e.objectStoreNames.contains("pendingCaptures")){const r=e.createObjectStore("pendingCaptures",{keyPath:"uuid"});r.createIndex("sessionId","sessionId"),r.createIndex("timestamp","timestamp"),r.createIndex("[sessionId+targetTimestamp]",["sessionId","targetTimestamp"])}}})}async deleteDB(){try{await re("sprigReplay")}catch{}}async bulkAdd(e,t){const n=await this.getTransaction(e);return Promise.all([...t.map(r=>n.store.add(r)),n.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 n=IDBKeyRange.only(t),r=await this.getTransaction(e),a=r.store.index("sessionId");for await(const s of a.iterate(n))await s.delete();await r.done}async updatePartial(e,t,n){const r=await this.getTransaction(e),a=await r.store.get(t);a&&await r.store.put({...a,...n}),await r.done}async deleteRowsBefore(e,t,n=()=>!0){const r=IDBKeyRange.upperBound(t,!0),a=await this.getTransaction(e),s=a.store.index("timestamp");for await(const i of s.iterate(r))n(i.value)&&await i.delete();await a.done}async getEventsBetween(e,t=Date.now()){if(e>=t)return Promise.resolve([]);const n=IDBKeyRange.bound([h,e],[h,t],!1,!0);return(await this.openDB()).getAllFromIndex("events","[sessionId+timestamp]",n)}async updateEventsExpiredAt(e,t,n=30){const r=new Date,a=r.setMinutes(r.getMinutes()+(n??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 n=IDBKeyRange.only([t,e]),r=await this.getTransaction("chunkUploads");let s=await r.store.index("[uploadId+status]").openCursor(n);for(;s;)s.delete(),s=await s.continue();await r.done}async getChunkUploadsByStatus({sessionId:e,status:t,uploadId:n}){const r=(await this.openDB()).transaction("chunkUploads","readonly");this.wrapTransactionWithCounter(r);const a=n?r.store.index("[uploadId+status]"):r.store.index("[sessionId+status]"),s=n?IDBKeyRange.only([n,t]):IDBKeyRange.only([e,t]);return a.getAll(s)}async getPendingCaptures(e={}){return(await(await this.openDB()).getAllFromIndex("pendingCaptures","sessionId",h)).filter(n=>!e.beforePresent||n.targetTimestamp<Date.now()).filter(n=>!e.isBeforeType||n.captureParams.replayParams.replayDurationType==="before").filter(n=>!e.isHeatmap||(n.captureParams.isHeatmap??!1))}async markPendingCaptureToCanUpload(e){const t=await this.getTransaction("pendingCaptures"),n=t.store.index("sessionId");for await(const r of n.iterate(h)){const a=r.value;a.captureParams.responseGroupId===e&&await r.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(),n=await this.getTransaction("pendingCaptures"),r=n.store.index("sessionId");for await(const a of r.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 n.done}},U=[];let F,He,M=[],_=!1,A=0,W=!1,Ne=!1;const me=[];let J,Oe,G,Fe,X=!1;const H=()=>W&&!_&&Date.now()<=J,Dt=({apiUrl:e,config:t,triggerSnapshot:n,forceInit:r=!1})=>{W&&!r||(o.sessionStorageHelper.isStorageAvailable?(M=[],me.splice(0),U.splice(0),A=0,G=n,He=e,F={responseGroupUuid:t.responseGroupUuid,surveyId:t.surveyId,userAgent:t.userAgent,sdkVersion:t.sdkVersion},Oe=t.maxDurationSeconds,Pt(),W||(Fe=window.setInterval(Ct,500)),W=!0):_=!0)},Et=[T.Drag,T.Input,T.MediaInteraction,T.MouseInteraction,T.MouseMove,T.Scroll,T.Selection,T.TouchMove],Rt=e=>e.type===L.Custom||e.type===L.IncrementalSnapshot&&Et.includes(e.data.source),we=e=>e.some(Rt),Ct=async()=>{if(!H())return void window.clearInterval(Fe);if(je(),!we(U))return;const e=U[0].timestamp;Date.now()-e>35e3&&(G==null||G())},je=async()=>{if(M.length||X)return;X=!0;const e=await kt();if(!e)return void(_=!0);me.splice(0,e.length).forEach(t=>t(e.shift())),e.forEach(t=>M.push(t)),X=!1},Pt=()=>{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*Oe+Date.now()},Tt=async e=>{const t=Date.now(),n=(await l.getEventsBetween(e,t)).map(a=>JSON.parse(a.event));if(!we(n))return;Ke(n);const r=await $e();r&&await Ge(r,n)},We=async(e,t)=>{try{const n=await e();if(!n.ok)throw new Error(`Error ${t}`);return n}catch{_=!0}},Ge=async(e,t)=>{if(!H()||!e)return;const n=await(async r=>{const a=new TextEncoder,s=new CompressionStream("gzip"),i=s.writable.getWriter(),c=a.encode(JSON.stringify(r));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 We(()=>o.sprigFetch(e,{body:n,method:"PUT"}),"uploading always-on with presigned url")},kt=async()=>{if(!H())return;const{surveyId:e,responseGroupUuid:t}=F,n={responseGroupUuid:t,surveyId:e,index:A+1};o.breadcrumbsLogger.info("Fetching always-on upload urls",n);const r=await We(()=>o.sprigFetch(`${He}/sdk/1/replayUrls`,{method:"POST",body:JSON.stringify(n),headers:o.getHttpHeaders(window.UserLeap)}),"fetching always-on signed urls");if(!r)return;const a=r.json.signedUrls;return o.breadcrumbsLogger.info("Fetched more always-on upload urls",{body:n,urls:a}),a},$e=async()=>{if(M.length)return M.shift();const e=new Promise(t=>{me.push(t)});return je(),e},Ke=e=>{var a,s,i;const t=e.length?e[e.length-1].timestamp:Date.now(),n=A,r=((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:n,visitorId:window.UserLeap.visitorId??"",timestamp:t,customMetadata:r}}})},Ut=(e,t)=>{H()&&!Ne&&(e||U.length)&&(e&&U.length&&(async()=>{const n=U.splice(0);if(!we(n))return;o.breadcrumbsLogger.info("Capturing always-on event array to upload"),Ke(n);const r=await $e();r&&await Ge(r,n)})(),U.push(t))};window.addEventListener("beforeunload",async()=>{Ne=!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 Ve=async(e,t)=>{const n=performance.now();let r;try{r=await e()}finally{const a=performance.now()-n;let s=o.PerformanceMetrics[t];s||(s=o.registerMetric(t)),s.report(a/1e3)}return r},Je=(e,t)=>{const n=performance.now();try{e()}finally{const r=performance.now()-n;let a=o.PerformanceMetrics[t];a||(a=o.registerMetric(t)),a.report(r/1e3)}};let qe=5e3,ie=6e4,de=0,B,ce=!1,ue=[];const Lt=e=>{var t,n,r,a;if((t=e.event)!=null&&t.includes("Sprig_Scroll")){const s=(a=(r=(n=JSON.parse(e.event))==null?void 0:n.data)==null?void 0:r.payload)==null?void 0:a.xPath;if(!s)return;g.scrollEventUuids[s]=e.uuid}ue.push(e),ce||xt()},xt=()=>{ce=!0,setTimeout(async()=>{if(C()||V())return;const e=ue;ue=[],ce=!1,Je(async()=>{await(async t=>{const n=t.map(r=>({...r,sessionId:r.sessionId??h}));if(n.length!==0)return b(()=>l.bulkAdd("events",n),"Error storing replay events")})(e)},"sdk_replay_add_event_batch_seconds")},500)},Bt=(e,t,n)=>{g.cleanupInterval=window.setInterval(()=>{const r=Date.now();Ve(()=>b(async()=>{C()||await Promise.all([l.deleteRowsBefore("events",r-1e3*e,a=>a.expiredAt===void 0||a.expiredAt<r-1e3*e),l.deleteRowsBefore("chunkUploads",r-1e3*t),l.deleteRowsBefore("pendingCaptures",r-1e3*n,a=>!a.canUpload)])},"Error deleting table rows"),"sdk_replay_cleanup_seconds"),o.breadcrumbsLogger.debug("CleanupComplete")},3e4)},Mt=()=>{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 n=await l.getPendingCaptures({beforePresent:!0,isBeforeType:e}),r=await l.openDB();await Promise.all(n.map(async a=>(await r.delete("pendingCaptures",a.uuid),Xe(a.captureParams,a.canUpload)))),B=(t-n.length).toString(),o.sessionStorageHelper.setItem("sprig.pendingCount",B)}finally{Y=!1}},At=async(e,t,n,r,a)=>{const s=Math.min(e+a,n),i=await Ve(()=>l.getEventsBetween(e,s),"sdk_replay_get_events_between_seconds");if(!(i!=null&&i.length))return o.breadcrumbsLogger.debug("NoEventsFound"),{validStartFound:r,events:[]};if(!r){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:r,events:[]}):{validStartFound:!0,events:i==null?void 0:i.slice(c)}}return{validStartFound:r,events:i}},ze=e=>Promise.all(e.map(async t=>{const n=await(async r=>Ce.execute(async()=>{var i;o.breadcrumbsLogger.info("UploadChunkStart",{chunkIndex:r.chunkIndex,surveyId:r.surveyId});const a=await o.sprigFetch(r.uploadUrl,{body:r.data,method:"PUT"});o.breadcrumbsLogger.http("UploadChunkEnd",{url:r.uploadUrl,method:"PUT",status_code:a.status,reason:a.statusText??"OK",chunkIndex:r.chunkIndex,surveyId:r.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 ${r.uploadId}, part ${r.chunkIndex}`);return s}))(t);return await l.updatePartial("chunkUploads",t.uuid,{data:null,etag:n,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 n=t.reduce((s,i)=>(s.find(c=>c.chunkIndex===i.chunkIndex)||s.push(i),s),[]);n.sort((s,i)=>s.chunkIndex-i.chunkIndex);const r=n.map(s=>({ETag:s.etag,PartNumber:s.chunkIndex})).filter(s=>s.ETag!==null),a=n[0];await Pe({apiUrl:a.apiUrl,surveyId:a.surveyId,uploadId:e,responseGroupUuid:a.responseGroupId,etags:r,headers:a.completeUploadHeaders,replayDuration:a.replayDuration}),await l.deleteChunkUploads("UploadComplete",e)},_t=()=>{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(n=>{if(n)return Qe(n)}))},"Error uploading unfinished chunks")},Ht=async(e,t)=>{const n=t??Date.now();return(async(r,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=r-35e3;P<a;P+=ie){if({validStartFound:w,events:m}=await At(P,r,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})(n-e,n)},De=async e=>{const{surveyId:t,responseGroupId:n,visitorId:r,apiUrl:a,completeUploadHeaders:s,replayParams:i,triggerTimestamp:c}=e,d=await Ht(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:n,status:"ReadyForUpload",surveyId:t,timestamp:c,totalChunks:u.length,data:p,uploadId:i.uploadId,uploadUrl:i.signedUrls[f].url,uuid:m,visitorId:r};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:n,isStandalone:r,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!r&&!n&&o.eventEmitter.on(o.SprigEvent.QuestionAnswered,c),void await Ze(e);if(r||n||t)await De(e),n&&Nt();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")},Nt=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:n}=e,r=await l.getPendingCaptures(),a=r==null?void 0:r.filter(d=>d.captureParams.surveyId===n);if(a!=null&&a.length)return void o.breadcrumbsLogger.info("PendingCaptureExists",{surveyId:n});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()})},Ot=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:n,headers:r})=>{if(!e||!t)return!1;const a=window.UserLeap._API_URL,s=await Pe({surveyId:e,responseGroupUuid:t,eventDigest:n,apiUrl:a,headers:r},!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:n,teardownAfter:r=!1,apiUrl:a,alwaysOnConfig:s})=>{if(s&&Dt({apiUrl:a,config:s,triggerSnapshot:()=>{oe()}}),B=o.sessionStorageHelper.getItem("sprig.pendingCount"),g.isRecording)return;if(r&&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;n!=null&&n.minDuration&&(qe=n.minDuration),n!=null&&n.batchDuration&&(ie=n.batchDuration),d=t,Ce.setLimit(d),_t(),Bt(c+35,1800,c+35),Mt();const u=window.UserLeap.replayLibraryURL??"https://cdn.sprig.com/dependencies/record.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},...n,mutationQueueEnabled:n==null?void 0:n.enableMutationQueue};var D,P;g.stopRecording=w({emit:(y,I)=>{if(y.type===L.Custom&&(de=Date.now()),C()||V())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,Ut(v,y),Lt({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===ut&&(pe.push({source:v.source,origin:v.origin}),(E=v.source)==null||E.postMessage({type:lt,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,P=vt,K||(S=D,j=P,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),K=!0,ht(),It()))},"Error initializing replay")},isReplayPaused:V,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(Ot);
|
|
1
|
+
"use strict";var et=Object.defineProperty;var tt=(e,t,n)=>t in e?et(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var N=(e,t,n)=>tt(e,typeof t!="symbol"?t+"":t,n);const o=require("./metricsReporter-Dq2lxT-9.cjs"),nt=require("./debounce-DsC7462b.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||{}),T=(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))(T||{});const Z=(e,t)=>t.some(n=>e instanceof n);let ye,fe;const ee=new WeakMap,q=new WeakMap,$=new WeakMap;let te={get(e,t,n){if(e instanceof IDBTransaction){if(t==="done")return ee.get(e);if(t==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return x(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&(t==="done"||t==="store")||t in e};function 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(ne(this),t),x(this.request)}:function(...t){return x(e.apply(ne(this),t))}}function at(e){return typeof e=="function"?rt(e):(e instanceof IDBTransaction&&function(t){if(ee.has(t))return;const n=new Promise((r,a)=>{const s=()=>{a(t.error||new DOMException("AbortError","AbortError"))};t.oncomplete=()=>{r()},t.onerror=s,t.onabort=s});ee.set(t,n)}(e),Z(e,ye||(ye=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,te):e)}function x(e){if(e instanceof IDBRequest)return function(n){const r=new Promise((a,s)=>{n.onsuccess=()=>{a(x(n.result))},n.onerror=()=>{s(n.error)}});return $.set(r,n),r}(e);if(q.has(e))return q.get(e);const t=at(e);return t!==e&&(q.set(e,t),$.set(t,e)),t}const ne=e=>$.get(e);function re(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&(n.onblocked=r=>t(r.oldVersion,r)),x(n).then(()=>{})}const st=["get","getKey","getAll","getAllKeys","count"],ot=["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 n=t.replace(/FromIndex$/,""),r=t!==n,a=ot.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!a&&!st.includes(n))return;const s=async function(i,...c){const d=this.transaction(i,a?"readwrite":"readonly");let u=d.store;return r&&(u=u.index(c.shift())),(await Promise.all([u[n](...c),a&&d.done]))[0]};return z.set(t,s),s}Ee(e=>({...e,get:(t,n,r)=>he(t,n)||e.get(t,n,r),has:(t,n)=>!!he(t,n)||e.has(t,n)}));const it=["continue","continuePrimaryKey","advance"],Ie={},ae=new WeakMap,Re=new WeakMap,dt={get(e,t){if(!it.includes(t))return e[t];let n=Ie[t];return n||(n=Ie[t]=function(...r){ae.set(this,Re.get(this)[t](...r))}),n}};async function*ct(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,dt);for(Re.set(n,t),$.set(n,ne(t));t;)yield n,t=await(ae.get(n)||t.continue()),ae.delete(n)}function ve(e,t){return t===Symbol.asyncIterator&&Z(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&Z(e,[IDBIndex,IDBObjectStore])}Ee(e=>({...e,get:(t,n,r)=>ve(t,n)?ct:e.get(t,n,r),has:(t,n)=>ve(t,n)||e.has(t,n)}));const ut="sprigReplayIframeLoaded",lt="sprigReplayIframeSettings",pt="sprigReplayIframeTakeFullSnapshot",gt="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),Pe=async({apiUrl:e,surveyId:t,uploadId:n,etags:r,headers:a,responseGroupUuid:s,replayDuration:i,eventDigest:c},d=!1)=>{var w;if(!d&&!n&&!r)return void o.breadcrumbsLogger.error("UploadErr",{isMobile:d,uploadId:n,etags:r});o.breadcrumbsLogger.info("MarkUploadComplete",{surveyId:t});const u=await o.sprigFetch(`${e}/sdk/1/completeSessionReplay`,{method:"POST",body:JSON.stringify({etags:r,uploadId:n,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},mt=e=>{if(e instanceof Attr)return null;let t=1;for(let n=e.previousSibling;n;n=n.previousSibling)n.nodeName===e.nodeName&&++t;return t},Te=e=>{if(e===null)return"";const t=[];if(e instanceof Document)return"/";for(let n=e;n&&!(n instanceof Document)&&n!==null;n=n instanceof Attr?n.ownerElement:n.parentElement){const r=t[t.length]={name:void 0,position:null};switch(n.nodeType){case Node.TEXT_NODE:r.name="text()";break;case Node.ATTRIBUTE_NODE:r.name="@"+n.nodeName;break;case Node.PROCESSING_INSTRUCTION_NODE:r.name="processing-instruction()";break;case Node.COMMENT_NODE:r.name="comment()";break;case Node.ELEMENT_NODE:r.name=n.nodeName}r.position=mt(n)}return"/"+t.reverse().map(n=>n.position!==null?`/${n.name}[${n.position}]`:`/${n.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},wt=["a","button","input","option","li","link"],yt=["Escape","Enter","Backspace","F5","Tab"];let K=!1,S=null,j=null;const be=e=>{var n;if(((n=e.tagName)==null?void 0:n.toLowerCase())==="html")return{element:"html"};const t={};return t.element=(r=>{if(!r.tagName)return"No tagName";const a=r.getAttribute("type");return a?`${a} ${r.tagName.toLowerCase()}`:r.tagName.toLowerCase()})(e),t},ft=e=>{var r;if(!e)return{};const t={...be(e)},n=e.parentElement;if(n&&wt.includes((r=n.tagName)==null?void 0:r.toLowerCase())){const a=be(n);Object.assign(t,a)}return t},ke=(e,t)=>{var a,s;let n=t.target;var r;t.target===((a=window.document)==null?void 0:a.body)&&window.Sprig.pointerDownTarget&&(n=window.Sprig.pointerDownTarget),r={x:t.x,y:t.y,type:e,elementAttributes:ft(n),windowHeight:window.innerHeight,windowWidth:window.innerWidth,...n instanceof HTMLElement||n instanceof SVGElement||n instanceof MathMLElement?{rect:n==null?void 0:n.getBoundingClientRect(),xPath:Te(n)}:{}},(s=r==null?void 0:r.elementAttributes)!=null&&s.text&&(r.elementAttributes.text=ge(r.elementAttributes.text)),S==null||S("Sprig_Click",r)},Ue=e=>{var t;yt.includes(e.key)&&(t={key:e.key},S==null||S("Sprig_Keystroke",t))},ht=()=>{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))},It=()=>{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=nt.debounce(e=>{if(!(e.target instanceof HTMLElement||e.target instanceof Document))return;let t=e.target;"scrollTop"in t||(t=t.documentElement),j==null||j({xPath:Te(t),x:t.scrollLeft,y:t.scrollTop,elementAttributes:{targetScrollWidth:t.scrollWidth,targetClientWidth:t.clientWidth,targetScrollHeight:t.scrollHeight,targetClientHeight:t.clientHeight}})},750),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"),V=()=>!!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 n,r;if(!C()&&g.isRecording&&!V())try{(r=(n=window.rrwebRecord)==null?void 0:n.addCustomEvent)==null||r.call(n,e,t)}catch(a){O("Error recording custom event",a)}},vt=async e=>{const{x:t,xPath:n,y:r}=e,a=g.scrollEventUuids[n];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=r>((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=r),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)}),K&&(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),K=!1),pe.forEach(e=>{var t;(t=e.source)==null||t.postMessage({type:gt},{targetOrigin:e.origin})})},bt=["did not allow mutations","called in an invalid security context"],St=(e,t,{reportError:n=!0,extraInfo:r={}})=>{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 bt)if(a.toLowerCase().includes(s))return!1;return!0})(t==null?void 0:t.message)&&(n&&window.UserLeap.reportError(e,t,r),l.clearAll())}},O=(e,t,{reportError:n}={reportError:!0})=>{_e(),o.breadcrumbsLogger.error("ReplayErr",{code:t.code,name:t.name}),St(e,t,{reportError:n})},b=async(e,t)=>{try{return await e()}catch(n){O(t,n)}},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:pt},{targetOrigin:e.origin})}))};let Q=0;(async()=>Ae()&&Promise.allSettled([re("replayStorage"),re("sprig.replay")]))();const l=new class{constructor(){N(this,"wrapTransactionWithCounter",e=>{var r,a;const t=(a=(r=window.Sprig)==null?void 0:r._config)==null?void 0:a.outstandingTransactionLimit,n=t===void 0?100:t;if(n&&Q>n){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:n,upgrade:r,blocking:a,terminated:s}={}){const i=indexedDB.open(e,t),c=x(i);return r&&(i.onupgradeneeded=d=>{r(x(i.result),d.oldVersion,d.newVersion,x(i.transaction),d)}),n&&(i.onblocked=d=>n(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,n)=>{if(n===0&&o.sessionStorageHelper.setItem("sprig.pendingCount","0"),!e.objectStoreNames.contains("events")){const r=e.createObjectStore("events",{keyPath:"uuid"});r.createIndex("sessionId","sessionId"),r.createIndex("timestamp","timestamp"),r.createIndex("[sessionId+timestamp]",["sessionId","timestamp"])}if(!e.objectStoreNames.contains("chunkUploads")){const r=e.createObjectStore("chunkUploads",{keyPath:"uuid"});r.createIndex("sessionId","sessionId"),r.createIndex("timestamp","timestamp"),r.createIndex("[sessionId+status]",["sessionId","status"]),r.createIndex("[uploadId+status]",["uploadId","status"]),r.createIndex("[sessionId+status+uploadId]",["sessionId","status","uploadId"])}if(!e.objectStoreNames.contains("pendingCaptures")){const r=e.createObjectStore("pendingCaptures",{keyPath:"uuid"});r.createIndex("sessionId","sessionId"),r.createIndex("timestamp","timestamp"),r.createIndex("[sessionId+targetTimestamp]",["sessionId","targetTimestamp"])}}})}async deleteDB(){try{await re("sprigReplay")}catch{}}async bulkAdd(e,t){const n=await this.getTransaction(e);return Promise.all([...t.map(r=>n.store.add(r)),n.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 n=IDBKeyRange.only(t),r=await this.getTransaction(e),a=r.store.index("sessionId");for await(const s of a.iterate(n))await s.delete();await r.done}async updatePartial(e,t,n){const r=await this.getTransaction(e),a=await r.store.get(t);a&&await r.store.put({...a,...n}),await r.done}async deleteRowsBefore(e,t,n=()=>!0){const r=IDBKeyRange.upperBound(t,!0),a=await this.getTransaction(e),s=a.store.index("timestamp");for await(const i of s.iterate(r))n(i.value)&&await i.delete();await a.done}async getEventsBetween(e,t=Date.now()){if(e>=t)return Promise.resolve([]);const n=IDBKeyRange.bound([h,e],[h,t],!1,!0);return(await this.openDB()).getAllFromIndex("events","[sessionId+timestamp]",n)}async updateEventsExpiredAt(e,t,n=30){const r=new Date,a=r.setMinutes(r.getMinutes()+(n??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 n=IDBKeyRange.only([t,e]),r=await this.getTransaction("chunkUploads");let s=await r.store.index("[uploadId+status]").openCursor(n);for(;s;)s.delete(),s=await s.continue();await r.done}async getChunkUploadsByStatus({sessionId:e,status:t,uploadId:n}){const r=(await this.openDB()).transaction("chunkUploads","readonly");this.wrapTransactionWithCounter(r);const a=n?r.store.index("[uploadId+status]"):r.store.index("[sessionId+status]"),s=n?IDBKeyRange.only([n,t]):IDBKeyRange.only([e,t]);return a.getAll(s)}async getPendingCaptures(e={}){return(await(await this.openDB()).getAllFromIndex("pendingCaptures","sessionId",h)).filter(n=>!e.beforePresent||n.targetTimestamp<Date.now()).filter(n=>!e.isBeforeType||n.captureParams.replayParams.replayDurationType==="before").filter(n=>!e.isHeatmap||(n.captureParams.isHeatmap??!1))}async markPendingCaptureToCanUpload(e){const t=await this.getTransaction("pendingCaptures"),n=t.store.index("sessionId");for await(const r of n.iterate(h)){const a=r.value;a.captureParams.responseGroupId===e&&await r.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(),n=await this.getTransaction("pendingCaptures"),r=n.store.index("sessionId");for await(const a of r.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 n.done}},U=[];let F,He,M=[],_=!1,A=0,W=!1,Ne=!1;const me=[];let J,Oe,G,Fe,X=!1;const H=()=>W&&!_&&Date.now()<=J,Dt=({apiUrl:e,config:t,triggerSnapshot:n,forceInit:r=!1})=>{W&&!r||(o.sessionStorageHelper.isStorageAvailable?(M=[],me.splice(0),U.splice(0),A=0,G=n,He=e,F={responseGroupUuid:t.responseGroupUuid,surveyId:t.surveyId,userAgent:t.userAgent,sdkVersion:t.sdkVersion},Oe=t.maxDurationSeconds,Pt(),W||(Fe=window.setInterval(Ct,500)),W=!0):_=!0)},Et=[T.Drag,T.Input,T.MediaInteraction,T.MouseInteraction,T.MouseMove,T.Scroll,T.Selection,T.TouchMove],Rt=e=>e.type===L.Custom||e.type===L.IncrementalSnapshot&&Et.includes(e.data.source),we=e=>e.some(Rt),Ct=async()=>{if(!H())return void window.clearInterval(Fe);if(je(),!we(U))return;const e=U[0].timestamp;Date.now()-e>35e3&&(G==null||G())},je=async()=>{if(M.length||X)return;X=!0;const e=await kt();if(!e)return void(_=!0);me.splice(0,e.length).forEach(t=>t(e.shift())),e.forEach(t=>M.push(t)),X=!1},Pt=()=>{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*Oe+Date.now()},Tt=async e=>{const t=Date.now(),n=(await l.getEventsBetween(e,t)).map(a=>JSON.parse(a.event));if(!we(n))return;Ke(n);const r=await $e();r&&await Ge(r,n)},We=async(e,t)=>{try{const n=await e();if(!n.ok)throw new Error(`Error ${t}`);return n}catch{_=!0}},Ge=async(e,t)=>{if(!H()||!e)return;const n=await(async r=>{const a=new TextEncoder,s=new CompressionStream("gzip"),i=s.writable.getWriter(),c=a.encode(JSON.stringify(r));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 We(()=>o.sprigFetch(e,{body:n,method:"PUT"}),"uploading always-on with presigned url")},kt=async()=>{if(!H())return;const{surveyId:e,responseGroupUuid:t}=F,n={responseGroupUuid:t,surveyId:e,index:A+1};o.breadcrumbsLogger.info("Fetching always-on upload urls",n);const r=await We(()=>o.sprigFetch(`${He}/sdk/1/replayUrls`,{method:"POST",body:JSON.stringify(n),headers:o.getHttpHeaders(window.UserLeap)}),"fetching always-on signed urls");if(!r)return;const a=r.json.signedUrls;return o.breadcrumbsLogger.info("Fetched more always-on upload urls",{body:n,urls:a}),a},$e=async()=>{if(M.length)return M.shift();const e=new Promise(t=>{me.push(t)});return je(),e},Ke=e=>{var a,s,i;const t=e.length?e[e.length-1].timestamp:Date.now(),n=A,r=((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:n,visitorId:window.UserLeap.visitorId??"",timestamp:t,customMetadata:r}}})},Ut=(e,t)=>{H()&&!Ne&&(e||U.length)&&(e&&U.length&&(async()=>{const n=U.splice(0);if(!we(n))return;o.breadcrumbsLogger.info("Capturing always-on event array to upload"),Ke(n);const r=await $e();r&&await Ge(r,n)})(),U.push(t))};window.addEventListener("beforeunload",async()=>{Ne=!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 Ve=async(e,t)=>{const n=performance.now();let r;try{r=await e()}finally{const a=performance.now()-n;let s=o.PerformanceMetrics[t];s||(s=o.registerMetric(t)),s.report(a/1e3)}return r},Je=(e,t)=>{const n=performance.now();try{e()}finally{const r=performance.now()-n;let a=o.PerformanceMetrics[t];a||(a=o.registerMetric(t)),a.report(r/1e3)}};let qe=5e3,ie=6e4,de=0,B,ce=!1,ue=[];const Lt=e=>{var t,n,r,a;if((t=e.event)!=null&&t.includes("Sprig_Scroll")){const s=(a=(r=(n=JSON.parse(e.event))==null?void 0:n.data)==null?void 0:r.payload)==null?void 0:a.xPath;if(!s)return;g.scrollEventUuids[s]=e.uuid}ue.push(e),ce||xt()},xt=()=>{ce=!0,setTimeout(async()=>{if(C()||V())return;const e=ue;ue=[],ce=!1,Je(async()=>{await(async t=>{const n=t.map(r=>({...r,sessionId:r.sessionId??h}));if(n.length!==0)return b(()=>l.bulkAdd("events",n),"Error storing replay events")})(e)},"sdk_replay_add_event_batch_seconds")},500)},Bt=(e,t,n)=>{g.cleanupInterval=window.setInterval(()=>{const r=Date.now();Ve(()=>b(async()=>{C()||await Promise.all([l.deleteRowsBefore("events",r-1e3*e,a=>a.expiredAt===void 0||a.expiredAt<r-1e3*e),l.deleteRowsBefore("chunkUploads",r-1e3*t),l.deleteRowsBefore("pendingCaptures",r-1e3*n,a=>!a.canUpload)])},"Error deleting table rows"),"sdk_replay_cleanup_seconds"),o.breadcrumbsLogger.debug("CleanupComplete")},3e4)},Mt=()=>{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 n=await l.getPendingCaptures({beforePresent:!0,isBeforeType:e}),r=await l.openDB();await Promise.all(n.map(async a=>(await r.delete("pendingCaptures",a.uuid),Xe(a.captureParams,a.canUpload)))),B=(t-n.length).toString(),o.sessionStorageHelper.setItem("sprig.pendingCount",B)}finally{Y=!1}},At=async(e,t,n,r,a)=>{const s=Math.min(e+a,n),i=await Ve(()=>l.getEventsBetween(e,s),"sdk_replay_get_events_between_seconds");if(!(i!=null&&i.length))return o.breadcrumbsLogger.debug("NoEventsFound"),{validStartFound:r,events:[]};if(!r){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:r,events:[]}):{validStartFound:!0,events:i==null?void 0:i.slice(c)}}return{validStartFound:r,events:i}},ze=e=>Promise.all(e.map(async t=>{const n=await(async r=>Ce.execute(async()=>{var i;o.breadcrumbsLogger.info("UploadChunkStart",{chunkIndex:r.chunkIndex,surveyId:r.surveyId});const a=await o.sprigFetch(r.uploadUrl,{body:r.data,method:"PUT"});o.breadcrumbsLogger.http("UploadChunkEnd",{url:r.uploadUrl,method:"PUT",status_code:a.status,reason:a.statusText??"OK",chunkIndex:r.chunkIndex,surveyId:r.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 ${r.uploadId}, part ${r.chunkIndex}`);return s}))(t);return await l.updatePartial("chunkUploads",t.uuid,{data:null,etag:n,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 n=t.reduce((s,i)=>(s.find(c=>c.chunkIndex===i.chunkIndex)||s.push(i),s),[]);n.sort((s,i)=>s.chunkIndex-i.chunkIndex);const r=n.map(s=>({ETag:s.etag,PartNumber:s.chunkIndex})).filter(s=>s.ETag!==null),a=n[0];await Pe({apiUrl:a.apiUrl,surveyId:a.surveyId,uploadId:e,responseGroupUuid:a.responseGroupId,etags:r,headers:a.completeUploadHeaders,replayDuration:a.replayDuration}),await l.deleteChunkUploads("UploadComplete",e)},_t=()=>{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(n=>{if(n)return Qe(n)}))},"Error uploading unfinished chunks")},Ht=async(e,t)=>{const n=t??Date.now();return(async(r,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=r-35e3;P<a;P+=ie){if({validStartFound:w,events:m}=await At(P,r,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})(n-e,n)},De=async e=>{const{surveyId:t,responseGroupId:n,visitorId:r,apiUrl:a,completeUploadHeaders:s,replayParams:i,triggerTimestamp:c}=e,d=await Ht(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:n,status:"ReadyForUpload",surveyId:t,timestamp:c,totalChunks:u.length,data:p,uploadId:i.uploadId,uploadUrl:i.signedUrls[f].url,uuid:m,visitorId:r};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:n,isStandalone:r,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!r&&!n&&o.eventEmitter.on(o.SprigEvent.QuestionAnswered,c),void await Ze(e);if(r||n||t)await De(e),n&&Nt();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")},Nt=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:n}=e,r=await l.getPendingCaptures(),a=r==null?void 0:r.filter(d=>d.captureParams.surveyId===n);if(a!=null&&a.length)return void o.breadcrumbsLogger.info("PendingCaptureExists",{surveyId:n});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()})},Ot=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:n,headers:r})=>{if(!e||!t)return!1;const a=window.UserLeap._API_URL,s=await Pe({surveyId:e,responseGroupUuid:t,eventDigest:n,apiUrl:a,headers:r},!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:n,teardownAfter:r=!1,apiUrl:a,alwaysOnConfig:s})=>{if(s&&Dt({apiUrl:a,config:s,triggerSnapshot:()=>{oe()}}),B=o.sessionStorageHelper.getItem("sprig.pendingCount"),g.isRecording)return;if(r&&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;n!=null&&n.minDuration&&(qe=n.minDuration),n!=null&&n.batchDuration&&(ie=n.batchDuration),d=t,Ce.setLimit(d),_t(),Bt(c+35,1800,c+35),Mt();const u=window.UserLeap.replayLibraryURL??"https://cdn.sprig.com/dependencies/record.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},...n,mutationQueueEnabled:n==null?void 0:n.enableMutationQueue};var D,P;g.stopRecording=w({emit:(y,I)=>{if(y.type===L.Custom&&(de=Date.now()),C()||V())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,Ut(v,y),Lt({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===ut&&(pe.push({source:v.source,origin:v.origin}),(E=v.source)==null||E.postMessage({type:lt,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,P=vt,K||(S=D,j=P,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),K=!0,ht(),It()))},"Error initializing replay")},isReplayPaused:V,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(Ot);
|
package/dist/replay.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var it = Object.defineProperty;
|
|
2
2
|
var dt = (e, t, n) => t in e ? it(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
|
|
3
3
|
var F = (e, t, n) => dt(e, typeof t != "symbol" ? t + "" : t, n);
|
|
4
|
-
import { b as d, s as Q, a as m, v as X, c as ct, g as lt, P as ke, r as Ue, d as ut, e as V, S as Y, f as pt } from "./metricsReporter-
|
|
4
|
+
import { b as d, s as Q, a as m, v as X, c as ct, g as lt, P as ke, r as Ue, d as ut, e as V, S as Y, f as pt } from "./metricsReporter-uLWRAnwI.js";
|
|
5
5
|
import { d as gt } from "./debounce-CMb8f7wh.js";
|
|
6
6
|
var B = ((e) => (e[e.DomContentLoaded = 0] = "DomContentLoaded", e[e.Load = 1] = "Load", e[e.FullSnapshot = 2] = "FullSnapshot", e[e.IncrementalSnapshot = 3] = "IncrementalSnapshot", e[e.Meta = 4] = "Meta", e[e.Custom = 5] = "Custom", e[e.Plugin = 6] = "Plugin", e))(B || {}), 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 || {});
|
|
7
7
|
const re = (e, t) => t.some((n) => e instanceof n);
|