@amplitude/session-replay-browser 1.28.15 → 1.29.0-fixsdk-init.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/lib/cjs/session-replay.d.ts +5 -2
- package/lib/cjs/session-replay.d.ts.map +1 -1
- package/lib/cjs/session-replay.js +50 -37
- package/lib/cjs/session-replay.js.map +1 -1
- package/lib/cjs/version.d.ts +1 -1
- package/lib/cjs/version.d.ts.map +1 -1
- package/lib/cjs/version.js +1 -1
- package/lib/cjs/version.js.map +1 -1
- package/lib/esm/session-replay.d.ts +5 -2
- package/lib/esm/session-replay.d.ts.map +1 -1
- package/lib/esm/session-replay.js +50 -37
- package/lib/esm/session-replay.js.map +1 -1
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.d.ts.map +1 -1
- package/lib/esm/version.js +1 -1
- package/lib/esm/version.js.map +1 -1
- package/lib/scripts/index-min.js +1 -1
- package/lib/scripts/index-min.js.gz +0 -0
- package/lib/scripts/index-min.js.map +1 -1
- package/lib/scripts/session-replay-browser-min.js +1 -1
- package/lib/scripts/session-replay-browser-min.js.gz +0 -0
- package/lib/scripts/session-replay-browser-min.js.map +1 -1
- package/package.json +4 -4
package/lib/scripts/index-min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{_ as e,a as t,b as n,c as i,d as r,o as s}from"./targeting-min.js";var o,a;!function(e){e.SET="$set",e.SET_ONCE="$setOnce",e.ADD="$add",e.APPEND="$append",e.PREPEND="$prepend",e.REMOVE="$remove",e.PREINSERT="$preInsert",e.POSTINSERT="$postInsert",e.UNSET="$unset",e.CLEAR_ALL="$clearAll"}(o||(o={})),function(e){e.IDENTIFY="$identify",e.GROUP_IDENTIFY="$groupidentify",e.REVENUE="revenue_amount"}(a||(a={}));var l,c="".concat("AMP","_unsent"),d="$default_instance",u="https://api2.amplitude.com/2/httpapi";!function(e){e.Unknown="unknown",e.Skipped="skipped",e.Success="success",e.RateLimit="rate_limit",e.PayloadTooLarge="payload_too_large",e.Invalid="invalid",e.Failed="failed",e.Timeout="Timeout",e.SystemError="SystemError"}(l||(l={}));var h,v=function(){var e="ampIntegrationContext";return"undefined"!=typeof globalThis&&void 0!==globalThis[e]?globalThis[e]:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0},g=function(e){return{promise:e||Promise.resolve()}};!function(e){e[e.None=0]="None",e[e.Error=1]="Error",e[e.Warn=2]="Warn",e[e.Verbose=3]="Verbose",e[e.Debug=4]="Debug"}(h||(h={}));var f="Amplitude Logger ",p=function(){function e(){this.logLevel=h.None}return e.prototype.disable=function(){this.logLevel=h.None},e.prototype.enable=function(e){void 0===e&&(e=h.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Verbose||console.log("".concat(f,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Warn||console.warn("".concat(f,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Error||console.error("".concat(f,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Debug||console.log("".concat(f,"[Debug]: ").concat(e.join(" ")))},e}(),m=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:d,logLevel:h.Warn,loggerProvider:new p,offline:!1,optOut:!1,serverUrl:u,serverZone:"US",useBatch:!1}},y=function(){function e(e){var t,n,i,r;this._optOut=!1;var s=m();this.apiKey=e.apiKey,this.flushIntervalMillis=null!==(t=e.flushIntervalMillis)&&void 0!==t?t:s.flushIntervalMillis,this.flushMaxRetries=e.flushMaxRetries||s.flushMaxRetries,this.flushQueueSize=e.flushQueueSize||s.flushQueueSize,this.instanceName=e.instanceName||s.instanceName,this.loggerProvider=e.loggerProvider||s.loggerProvider,this.logLevel=null!==(n=e.logLevel)&&void 0!==n?n:s.logLevel,this.minIdLength=e.minIdLength,this.plan=e.plan,this.ingestionMetadata=e.ingestionMetadata,this.offline=void 0!==e.offline?e.offline:s.offline,this.optOut=null!==(i=e.optOut)&&void 0!==i?i:s.optOut,this.serverUrl=e.serverUrl,this.serverZone=e.serverZone||s.serverZone,this.storageProvider=e.storageProvider,this.transportProvider=e.transportProvider,this.useBatch=null!==(r=e.useBatch)&&void 0!==r?r:s.useBatch,this.loggerProvider.enable(this.logLevel);var o=b(e.serverUrl,e.serverZone,e.useBatch);this.serverZone=o.serverZone,this.serverUrl=o.serverUrl}return Object.defineProperty(e.prototype,"optOut",{get:function(){return this._optOut},set:function(e){this._optOut=e},enumerable:!1,configurable:!0}),e}(),S=function(e,t){return"EU"===e?t?"https://api.eu.amplitude.com/batch":"https://api.eu.amplitude.com/2/httpapi":t?"https://api2.amplitude.com/batch":u},b=function(e,t,n){if(void 0===e&&(e=""),void 0===t&&(t=m().serverZone),void 0===n&&(n=m().useBatch),e)return{serverUrl:e,serverZone:void 0};var i=["US","EU"].includes(t)?t:m().serverZone;return{serverZone:i,serverUrl:S(i,n)}},I=function(){function e(){}return e.prototype.getApplicationContext=function(){return{versionName:this.versionName,language:w(),platform:"Web",os:void 0,deviceModel:void 0}},e}(),w=function(){return"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||""},C=function(){function e(){this.queue=[]}return e.prototype.logEvent=function(e){this.receiver?this.receiver(e):this.queue.length<512&&this.queue.push(e)},e.prototype.setEventReceiver=function(e){this.receiver=e,this.queue.length>0&&(this.queue.forEach((function(t){e(t)})),this.queue=[])},e}(),E=function(){return E=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},E.apply(this,arguments)};function P(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function T(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var i,r,s=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(i=s.next()).done;)o.push(i.value)}catch(e){r={error:e}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return o}"function"==typeof SuppressedError&&SuppressedError;var _=function(e,t){var n,i,r=typeof e;if(r!==typeof t)return!1;try{for(var s=P(["string","number","boolean","undefined"]),o=s.next();!o.done;o=s.next()){if(o.value===r)return e===t}}catch(e){n={error:e}}finally{try{o&&!o.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}if(null==e&&null==t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;var a=Array.isArray(e),l=Array.isArray(t);if(a!==l)return!1;if(!a||!l){var c=Object.keys(e).sort(),d=Object.keys(t).sort();if(!_(c,d))return!1;var u=!0;return Object.keys(e).forEach((function(n){_(e[n],t[n])||(u=!1)})),u}for(var h=0;h<e.length;h++)if(!_(e[h],t[h]))return!1;return!0};Object.entries||(Object.entries=function(e){for(var t=Object.keys(e),n=t.length,i=new Array(n);n--;)i[n]=[t[n],e[t[n]]];return i});var k,R=function(){function e(){this.identity={userProperties:{}},this.listeners=new Set}return e.prototype.editIdentity=function(){var e=this,t=E({},this.identity.userProperties),n=E(E({},this.identity),{userProperties:t});return{setUserId:function(e){return n.userId=e,this},setDeviceId:function(e){return n.deviceId=e,this},setUserProperties:function(e){return n.userProperties=e,this},setOptOut:function(e){return n.optOut=e,this},updateUserProperties:function(e){var t,i,r,s,o,a,l=n.userProperties||{};try{for(var c=P(Object.entries(e)),d=c.next();!d.done;d=c.next()){var u=T(d.value,2),h=u[0],v=u[1];switch(h){case"$set":try{for(var g=(r=void 0,P(Object.entries(v))),f=g.next();!f.done;f=g.next()){var p=T(f.value,2),m=p[0],y=p[1];l[m]=y}}catch(e){r={error:e}}finally{try{f&&!f.done&&(s=g.return)&&s.call(g)}finally{if(r)throw r.error}}break;case"$unset":try{for(var S=(o=void 0,P(Object.keys(v))),b=S.next();!b.done;b=S.next()){delete l[m=b.value]}}catch(e){o={error:e}}finally{try{b&&!b.done&&(a=S.return)&&a.call(S)}finally{if(o)throw o.error}}break;case"$clearAll":l={}}}}catch(e){t={error:e}}finally{try{d&&!d.done&&(i=c.return)&&i.call(c)}finally{if(t)throw t.error}}return n.userProperties=l,this},commit:function(){return e.setIdentity(n),this}}},e.prototype.getIdentity=function(){return E({},this.identity)},e.prototype.setIdentity=function(e){var t=E({},this.identity);this.identity=E({},e),_(t,this.identity)||this.listeners.forEach((function(t){t(e)}))},e.prototype.addIdentityListener=function(e){this.listeners.add(e)},e.prototype.removeIdentityListener=function(e){this.listeners.delete(e)},e}(),O="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self,x=function(){function e(){this.identityStore=new R,this.eventBridge=new C,this.applicationContextProvider=new I}return e.getInstance=function(t){return O.analyticsConnectorInstances||(O.analyticsConnectorInstances={}),O.analyticsConnectorInstances[t]||(O.analyticsConnectorInstances[t]=new e),O.analyticsConnectorInstances[t]},e}(),M=function(e,t,n,i,r){return void 0===r&&(r=null),function(){for(var s=[],o=0;o<arguments.length;o++)s[o]=arguments[o];var a=n(),l=a.logger,c=a.logLevel;if(c&&c<h.Debug||!c||!l)return e.apply(r,s);var d,u={type:"invoke public method",name:t,args:s,stacktrace:(d=1,void 0===d&&(d=0),((new Error).stack||"").split("\n").slice(2+d).map((function(e){return e.trim()}))),time:{start:(new Date).toISOString()},states:{}};i&&u.states&&(u.states.before=i());var v=e.apply(r,s);return v&&v.promise?v.promise.then((function(){i&&u.states&&(u.states.after=i()),u.time&&(u.time.end=(new Date).toISOString()),l.debug(JSON.stringify(u,null,2))})):(i&&u.states&&(u.states.after=i()),u.time&&(u.time.end=(new Date).toISOString()),l.debug(JSON.stringify(u,null,2))),v}},L=function(){function e(){}return e.prototype.send=function(e,t){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,n,i,r,s,o,a,c,d,u,h,v,g,f,p,m,y,S,b,I,w,C;if("object"!=typeof e)return null;var E=e.code||0,P=this.buildStatus(E);switch(P){case l.Success:return{status:P,statusCode:E,body:{eventsIngested:null!==(t=e.events_ingested)&&void 0!==t?t:0,payloadSizeBytes:null!==(n=e.payload_size_bytes)&&void 0!==n?n:0,serverUploadTime:null!==(i=e.server_upload_time)&&void 0!==i?i:0}};case l.Invalid:return{status:P,statusCode:E,body:{error:null!==(r=e.error)&&void 0!==r?r:"",missingField:null!==(s=e.missing_field)&&void 0!==s?s:"",eventsWithInvalidFields:null!==(o=e.events_with_invalid_fields)&&void 0!==o?o:{},eventsWithMissingFields:null!==(a=e.events_with_missing_fields)&&void 0!==a?a:{},eventsWithInvalidIdLengths:null!==(c=e.events_with_invalid_id_lengths)&&void 0!==c?c:{},epsThreshold:null!==(d=e.eps_threshold)&&void 0!==d?d:0,exceededDailyQuotaDevices:null!==(u=e.exceeded_daily_quota_devices)&&void 0!==u?u:{},silencedDevices:null!==(h=e.silenced_devices)&&void 0!==h?h:[],silencedEvents:null!==(v=e.silenced_events)&&void 0!==v?v:[],throttledDevices:null!==(g=e.throttled_devices)&&void 0!==g?g:{},throttledEvents:null!==(f=e.throttled_events)&&void 0!==f?f:[]}};case l.PayloadTooLarge:return{status:P,statusCode:E,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case l.RateLimit:return{status:P,statusCode:E,body:{error:null!==(m=e.error)&&void 0!==m?m:"",epsThreshold:null!==(y=e.eps_threshold)&&void 0!==y?y:0,throttledDevices:null!==(S=e.throttled_devices)&&void 0!==S?S:{},throttledUsers:null!==(b=e.throttled_users)&&void 0!==b?b:{},exceededDailyQuotaDevices:null!==(I=e.exceeded_daily_quota_devices)&&void 0!==I?I:{},exceededDailyQuotaUsers:null!==(w=e.exceeded_daily_quota_users)&&void 0!==w?w:{},throttledEvents:null!==(C=e.throttled_events)&&void 0!==C?C:[]}};case l.Timeout:default:return{status:P,statusCode:E}}},e.prototype.buildStatus=function(e){return e>=200&&e<300?l.Success:429===e?l.RateLimit:413===e?l.PayloadTooLarge:408===e?l.Timeout:e>=400&&e<500?l.Invalid:e>=500?l.Failed:l.Unknown},e}(),q=function(i){function r(){return null!==i&&i.apply(this,arguments)||this}return e(r,i),r.prototype.send=function(e,i){return t(this,void 0,void 0,(function(){var t,r,s;return n(this,(function(n){switch(n.label){case 0:if("undefined"==typeof fetch)throw new Error("FetchTransport is not supported");return t={headers:{"Content-Type":"application/json",Accept:"*/*"},body:JSON.stringify(i),method:"POST"},[4,fetch(e,t)];case 1:return[4,(r=n.sent()).text()];case 2:s=n.sent();try{return[2,this.buildResponse(JSON.parse(s))]}catch(e){return[2,this.buildResponse({code:r.status})]}return[2]}}))}))},r}(L);!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(k||(k={}));const D="[Amplitude]",N=`${D} Session Replay ID`,$=k.US,j={enabled:!0},U=`${D} Session Replay Debug`,F="amp-mask";var A;!function(e){e.GET_SR_PROPS="get-sr-props",e.DEBUG_INFO="debug-info",e.FETCH_REQUEST="fetch-request",e.METADATA="metadata",e.TARGETING_DECISION="targeting-decision"}(A||(A={}));class B{constructor(e){this.logger=e,this.log=this.getSafeMethod("log"),this.warn=this.getSafeMethod("warn"),this.error=this.getSafeMethod("error"),this.debug=this.getSafeMethod("debug")}getSafeMethod(e){var t;if(!this.logger)return()=>{};const n=this.logger[e];if("function"==typeof n){return(null!==(t=n.__rrweb_original__)&&void 0!==t?t:n).bind(this.logger)}return()=>{}}enable(e){this.logger.enable(e)}disable(){this.logger.disable()}}const K="medium";const W=(e,t,n)=>{switch(t){case"light":{if("input"!==e)return!0;const t=n?function(e){const t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?t.toLowerCase():null}(n):"";return!!t&&(!!["password","hidden","email","tel"].includes(t)||!!n.autocomplete.startsWith("cc-"))}case"medium":case"conservative":return!0;default:return W(e,K,n)}},z=(e,t)=>(n,i)=>((e,t={defaultMaskLevel:K},n)=>{var i,r,s;if(n){if(n.closest("."+F))return!0;const e=(null!==(i=t.maskSelector)&&void 0!==i?i:[]).some((e=>n.closest(e)));if(e)return!0;if(n.closest(".amp-unmask"))return!1;const s=(null!==(r=t.unmaskSelector)&&void 0!==r?r:[]).some((e=>n.closest(e)));if(s)return!1}return W(e,null!==(s=t.defaultMaskLevel)&&void 0!==s?s:K,n)})(e,t,i)?n.replace(/[^\s]/g,"*"):n,G=function(e){let t=0;if(0===e.length)return t;for(let n=0;n<e.length;n++){t=(t<<5)-t+e.charCodeAt(n),t|=0}return t},Q=(e,t)=>t||(e===k.STAGING?"https://api-sr.stag2.amplitude.com/sessions/v2/track":e===k.EU?"https://api-sr.eu.amplitude.com/sessions/v2/track":"https://api-sr.amplitude.com/sessions/v2/track"),H=e=>{const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${t}$`)},J=(e,t)=>{for(const n of t){const t=H(n.selector);if(t.test(e))return e.replace(t,n.replacement)}return e},Z=()=>t(void 0,void 0,void 0,(function*(){try{const e=v();if(e){const{usage:t,quota:n,usageDetails:i}=yield e.navigator.storage.estimate(),r=t?Math.round(t/1024):0;return{totalStorageSize:r,percentOfQuota:t&&n?Math.round(1e3*(t/n+Number.EPSILON))/1e3:0,usageDetails:JSON.stringify(i)}}}catch(e){}return{totalStorageSize:0,percentOfQuota:0,usageDetails:""}})),X=e=>{const t=Object.assign({},e),{apiKey:n}=t;return t.apiKey=`****${n.substring(n.length-4)}`,t},V=()=>({flushMaxRetries:2,logLevel:h.Warn,loggerProvider:new p,transportProvider:new q});class Y extends y{constructor(e,t){var n,i,r,s,o;const a=V();super(Object.assign(Object.assign({transportProvider:a.transportProvider,loggerProvider:new B(t.loggerProvider||a.loggerProvider)},t),{apiKey:e})),this.flushMaxRetries=void 0!==t.flushMaxRetries&&t.flushMaxRetries<=a.flushMaxRetries?t.flushMaxRetries:a.flushMaxRetries,this.apiKey=e,this.sampleRate=t.sampleRate||0,this.serverZone=t.serverZone||$,this.configServerUrl=t.configServerUrl,this.trackServerUrl=t.trackServerUrl,this.shouldInlineStylesheet=t.shouldInlineStylesheet,this.version=t.version,this.performanceConfig=t.performanceConfig||j,this.storeType=null!==(n=t.storeType)&&void 0!==n?n:"idb",this.applyBackgroundColorToBlockedElements=null!==(i=t.applyBackgroundColorToBlockedElements)&&void 0!==i&&i,this.enableUrlChangePolling=null!==(r=t.enableUrlChangePolling)&&void 0!==r&&r,this.urlChangePollingInterval=null!==(s=t.urlChangePollingInterval)&&void 0!==s?s:1e3,this.captureDocumentTitle=null!==(o=t.captureDocumentTitle)&&void 0!==o&&o,t.privacyConfig&&(this.privacyConfig=t.privacyConfig),t.interactionConfig&&(this.interactionConfig=t.interactionConfig,this.interactionConfig.ugcFilterRules&&(e=>{if(!e.every((e=>"string"==typeof e.selector&&"string"==typeof e.replacement)))throw new Error("ugcFilterRules must be an array of objects with selector and replacement properties");if(!e.every((e=>{return"string"==typeof(t=e.selector)&&""!==t.trim()&&!!/^\/|^https?:\/\/[^\s]+$/.test(t);var t})))throw new Error("ugcFilterRules must be an array of objects with valid globs")})(this.interactionConfig.ugcFilterRules)),t.debugMode&&(this.debugMode=t.debugMode),t.experimental&&(this.experimental=t.experimental),t.omitElementTags&&(this.omitElementTags=t.omitElementTags)}}var ee,te,ne=(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))(ne||{}),ie=(e=>(e[e.MouseUp=0]="MouseUp",e[e.MouseDown=1]="MouseDown",e[e.Click=2]="Click",e[e.ContextMenu=3]="ContextMenu",e[e.DblClick=4]="DblClick",e[e.Focus=5]="Focus",e[e.Blur=6]="Blur",e[e.TouchStart=7]="TouchStart",e[e.TouchMove_Departed=8]="TouchMove_Departed",e[e.TouchEnd=9]="TouchEnd",e[e.TouchCancel=10]="TouchCancel",e))(ie||{});!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(ee||(ee={})),function(e){e.Unknown="unknown",e.Skipped="skipped",e.Success="success",e.RateLimit="rate_limit",e.PayloadTooLarge="payload_too_large",e.Invalid="invalid",e.Failed="failed",e.Timeout="Timeout",e.SystemError="SystemError"}(te||(te={}));var re=function(){function e(){}return e.prototype.send=function(e,t){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,n,i,r,s,o,a,l,c,d,u,h,v,g,f,p,m,y,S,b,I,w;if("object"!=typeof e)return null;var C=e.code||0,E=this.buildStatus(C);switch(E){case te.Success:return{status:E,statusCode:C,body:{eventsIngested:null!==(t=e.events_ingested)&&void 0!==t?t:0,payloadSizeBytes:null!==(n=e.payload_size_bytes)&&void 0!==n?n:0,serverUploadTime:null!==(i=e.server_upload_time)&&void 0!==i?i:0}};case te.Invalid:return{status:E,statusCode:C,body:{error:null!==(r=e.error)&&void 0!==r?r:"",missingField:null!==(s=e.missing_field)&&void 0!==s?s:"",eventsWithInvalidFields:null!==(o=e.events_with_invalid_fields)&&void 0!==o?o:{},eventsWithMissingFields:null!==(a=e.events_with_missing_fields)&&void 0!==a?a:{},eventsWithInvalidIdLengths:null!==(l=e.events_with_invalid_id_lengths)&&void 0!==l?l:{},epsThreshold:null!==(c=e.eps_threshold)&&void 0!==c?c:0,exceededDailyQuotaDevices:null!==(d=e.exceeded_daily_quota_devices)&&void 0!==d?d:{},silencedDevices:null!==(u=e.silenced_devices)&&void 0!==u?u:[],silencedEvents:null!==(h=e.silenced_events)&&void 0!==h?h:[],throttledDevices:null!==(v=e.throttled_devices)&&void 0!==v?v:{},throttledEvents:null!==(g=e.throttled_events)&&void 0!==g?g:[]}};case te.PayloadTooLarge:return{status:E,statusCode:C,body:{error:null!==(f=e.error)&&void 0!==f?f:""}};case te.RateLimit:return{status:E,statusCode:C,body:{error:null!==(p=e.error)&&void 0!==p?p:"",epsThreshold:null!==(m=e.eps_threshold)&&void 0!==m?m:0,throttledDevices:null!==(y=e.throttled_devices)&&void 0!==y?y:{},throttledUsers:null!==(S=e.throttled_users)&&void 0!==S?S:{},exceededDailyQuotaDevices:null!==(b=e.exceeded_daily_quota_devices)&&void 0!==b?b:{},exceededDailyQuotaUsers:null!==(I=e.exceeded_daily_quota_users)&&void 0!==I?I:{},throttledEvents:null!==(w=e.throttled_events)&&void 0!==w?w:[]}};case te.Timeout:default:return{status:E,statusCode:C}}},e.prototype.buildStatus=function(e){return e>=200&&e<300?te.Success:429===e?te.RateLimit:413===e?te.PayloadTooLarge:408===e?te.Timeout:e>=400&&e<500?te.Invalid:e>=500?te.Failed:te.Unknown},e}(),se="Remote config fetch rejected due to timeout after 5 seconds",oe="Unexpected error occurred",ae=function(){function e(e){var s=e.localConfig,o=e.configKeys,a=this;this.retryTimeout=1e3,this.attempts=0,this.sessionTargetingMatch=!1,this.metrics={},this.getRemoteNamespaceConfig=function(e,i){return t(a,void 0,void 0,(function(){var t,r,s;return n(this,(function(n){switch(n.label){case 0:return t=Date.now(),[4,this.fetchWithTimeout(i)];case 1:return(r=n.sent())&&(s=r.configs&&r.configs[e])?(this.metrics.fetchTimeAPISuccess=Date.now()-t,[2,s]):(this.metrics.fetchTimeAPIFail=Date.now()-t,[2,void 0])}}))}))},this.getRemoteConfig=function(e,i,r){return t(a,void 0,void 0,(function(){var t;return n(this,(function(n){switch(n.label){case 0:return[4,this.getRemoteNamespaceConfig(e,r)];case 1:return[2,null==(t=n.sent())?void 0:t[i]]}}))}))},this.fetchWithTimeout=function(e){return t(a,void 0,void 0,(function(){var t,i,r;return n(this,(function(n){switch(n.label){case 0:return t=new AbortController,i=setTimeout((function(){return t.abort()}),5e3),[4,this.fetchRemoteConfig(t.signal,e)];case 1:return r=n.sent(),clearTimeout(i),[2,r]}}))}))},this.fetchRemoteConfig=function(e,s){return t(a,void 0,void 0,(function(){var t,o,a,l,c,d,u,h,v,g,f,p;return n(this,(function(n){switch(n.label){case 0:if(s===this.lastFetchedSessionId&&this.attempts>=this.localConfig.flushMaxRetries)return[2,this.completeRequest({err:"Remote config fetch rejected due to exceeded retry count"})];if(e.aborted)return[2,this.completeRequest({err:se})];s!==this.lastFetchedSessionId&&(this.lastFetchedSessionId=s,this.attempts=0),n.label=1;case 1:n.trys.push([1,3,,4]),t=new URLSearchParams({api_key:this.localConfig.apiKey});try{for(o=i(this.configKeys),a=o.next();!a.done;a=o.next())l=a.value,t.append("config_keys",l)}catch(e){g={error:e}}finally{try{a&&!a.done&&(f=o.return)&&f.call(o)}finally{if(g)throw g.error}}return s&&t.set("session_id",String(s)),c={headers:{Accept:"*/*"},method:"GET"},d="".concat(this.getServerUrl(),"?").concat(t.toString()),this.attempts+=1,[4,fetch(d,r(r({},c),{signal:e}))];case 2:if(null===(u=n.sent()))return[2,this.completeRequest({err:oe})];switch((new re).buildStatus(u.status)){case te.Success:return this.attempts=0,[2,this.parseAndStoreConfig(u)];case te.Failed:return[2,this.retryFetch(e,s)];default:return[2,this.completeRequest({err:"Network error occurred, remote config fetch failed"})]}case 3:return h=n.sent(),v=h,e.aborted?[2,this.completeRequest({err:se})]:[2,this.completeRequest({err:null!==(p=v.message)&&void 0!==p?p:oe})];case 4:return[2]}}))}))},this.retryFetch=function(e,i){return t(a,void 0,void 0,(function(){var t=this;return n(this,(function(n){switch(n.label){case 0:return[4,new Promise((function(e){return setTimeout(e,t.attempts*t.retryTimeout)}))];case 1:return n.sent(),[2,this.fetchRemoteConfig(e,i)]}}))}))},this.parseAndStoreConfig=function(e){return t(a,void 0,void 0,(function(){var t;return n(this,(function(n){switch(n.label){case 0:return[4,e.json()];case 1:return t=n.sent(),this.completeRequest({success:"Remote config successfully fetched"}),[2,t]}}))}))},this.localConfig=s,this.configKeys=o}return e.prototype.getServerUrl=function(){return this.localConfig.configServerUrl?this.localConfig.configServerUrl:this.localConfig.serverZone===ee.STAGING?"https://sr-client-cfg.stag2.amplitude.com/config":this.localConfig.serverZone===ee.EU?"https://sr-client-cfg.eu.amplitude.com/config":"https://sr-client-cfg.amplitude.com/config"},e.prototype.completeRequest=function(e){var t=e.err,n=e.success;if(t)throw new Error(t);n&&this.localConfig.loggerProvider.log(n)},e}(),le=function(e){var i=e.localConfig,r=e.configKeys;return t(void 0,void 0,void 0,(function(){return n(this,(function(e){return[2,new ae({localConfig:i,configKeys:r})]}))}))};class ce{constructor(e,t){this.localConfig=t,this.remoteConfigFetch=e}generateJoinedConfig(e){var n,i,r,s;return t(this,void 0,void 0,(function*(){const t=Object.assign({},this.localConfig);let o;t.optOut=this.localConfig.optOut,t.captureEnabled=!0;try{const i=yield this.remoteConfigFetch.getRemoteNamespaceConfig("sessionReplay",e);if(i){const e=i.sr_sampling_config,r=i.sr_privacy_config,s=i.sr_targeting_config,a=null===(n=t.interactionConfig)||void 0===n?void 0:n.ugcFilterRules;t.interactionConfig=i.sr_interaction_config,t.interactionConfig&&a&&(t.interactionConfig.ugcFilterRules=a),t.loggingConfig=i.sr_logging_config,(e||r||s)&&(o={},e&&(o.sr_sampling_config=e),r&&(o.sr_privacy_config=r),s&&(o.sr_targeting_config=s))}}catch(e){const n=e;this.localConfig.loggerProvider.warn(n.message),t.captureEnabled=!1}if(!o)return{localConfig:this.localConfig,joinedConfig:t,remoteConfig:o};const{sr_sampling_config:a,sr_privacy_config:l,sr_targeting_config:c}=o;if(a&&Object.keys(a).length>0?(Object.prototype.hasOwnProperty.call(a,"capture_enabled")?t.captureEnabled=a.capture_enabled:t.captureEnabled=!1,Object.prototype.hasOwnProperty.call(a,"sample_rate")&&(t.sampleRate=a.sample_rate)):(t.captureEnabled=!0,this.localConfig.loggerProvider.debug("Remote config successfully fetched, but no values set for project, Session Replay capture enabled.")),l){const e=null!==(i=t.privacyConfig)&&void 0!==i?i:{},n={defaultMaskLevel:null!==(s=null!==(r=l.defaultMaskLevel)&&void 0!==r?r:e.defaultMaskLevel)&&void 0!==s?s:"medium",blockSelector:[],maskSelector:[],unmaskSelector:[]},o=e=>{var t,n,i;const r={};"string"==typeof e.blockSelector&&(e.blockSelector=[e.blockSelector]);for(const n of null!==(t=e.blockSelector)&&void 0!==t?t:[])r[n]="block";for(const t of null!==(n=e.maskSelector)&&void 0!==n?n:[])r[t]="mask";for(const t of null!==(i=e.unmaskSelector)&&void 0!==i?i:[])r[t]="unmask";return r},a=Object.assign(Object.assign({},o(e)),o(l));for(const[e,t]of Object.entries(a))"mask"===t?n.maskSelector.push(e):"block"===t?n.blockSelector.push(e):"unmask"===t&&n.unmaskSelector.push(e);t.privacyConfig=((e,t)=>{const n=document.createDocumentFragment(),i=(e=[])=>{if("string"==typeof e&&(e=[e]),e=e.filter((e=>{try{n.querySelector(e)}catch(n){return t.warn(`[session-replay-browser] omitting selector "${e}" because it is invalid`),!1}return!0})),0!==e.length)return e};return e.blockSelector=i(e.blockSelector),e.maskSelector=i(e.maskSelector),e.unmaskSelector=i(e.unmaskSelector),e})(n,this.localConfig.loggerProvider)}return c&&Object.keys(c).length>0&&(t.targetingConfig=c),this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:X(t)},null,2)),{localConfig:this.localConfig,joinedConfig:t,remoteConfig:o}}))}}var de=Uint8Array,ue=Uint16Array,he=Uint32Array,ve=new de([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ge=new de([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),fe=new de([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),pe=function(e,t){for(var n=new ue(31),i=0;i<31;++i)n[i]=t+=1<<e[i-1];var r=new he(n[30]);for(i=1;i<30;++i)for(var s=n[i];s<n[i+1];++s)r[s]=s-n[i]<<5|i;return[n,r]},me=pe(ve,2),ye=me[0],Se=me[1];ye[28]=258,Se[258]=28;for(var be=pe(ge,0)[1],Ie=new ue(32768),we=0;we<32768;++we){var Ce=(43690&we)>>>1|(21845&we)<<1;Ce=(61680&(Ce=(52428&Ce)>>>2|(13107&Ce)<<2))>>>4|(3855&Ce)<<4,Ie[we]=((65280&Ce)>>>8|(255&Ce)<<8)>>>1}var Ee=function(e,t,n){for(var i=e.length,r=0,s=new ue(t);r<i;++r)++s[e[r]-1];var o,a=new ue(t);for(r=0;r<t;++r)a[r]=a[r-1]+s[r-1]<<1;if(n){o=new ue(1<<t);var l=15-t;for(r=0;r<i;++r)if(e[r])for(var c=r<<4|e[r],d=t-e[r],u=a[e[r]-1]++<<d,h=u|(1<<d)-1;u<=h;++u)o[Ie[u]>>>l]=c}else for(o=new ue(i),r=0;r<i;++r)o[r]=Ie[a[e[r]-1]++]>>>15-e[r];return o},Pe=new de(288);for(we=0;we<144;++we)Pe[we]=8;for(we=144;we<256;++we)Pe[we]=9;for(we=256;we<280;++we)Pe[we]=7;for(we=280;we<288;++we)Pe[we]=8;var Te=new de(32);for(we=0;we<32;++we)Te[we]=5;var _e=Ee(Pe,9,0),ke=Ee(Te,5,0),Re=function(e){return(e/8|0)+(7&e&&1)},Oe=function(e,t,n){(null==n||n>e.length)&&(n=e.length);var i=new(e instanceof ue?ue:e instanceof he?he:de)(n-t);return i.set(e.subarray(t,n)),i},xe=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>>8},Me=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>>8,e[i+2]|=n>>>16},Le=function(e,t){for(var n=[],i=0;i<e.length;++i)e[i]&&n.push({s:i,f:e[i]});var r=n.length,s=n.slice();if(!r)return[new de(0),0];if(1==r){var o=new de(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(e,t){return e.f-t.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],c=0,d=1,u=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};d!=r-1;)a=n[n[c].f<n[u].f?c++:u++],l=n[c!=d&&n[c].f<n[u].f?c++:u++],n[d++]={s:-1,f:a.f+l.f,l:a,r:l};var h=s[0].s;for(i=1;i<r;++i)s[i].s>h&&(h=s[i].s);var v=new ue(h+1),g=qe(n[d-1],v,0);if(g>t){i=0;var f=0,p=g-t,m=1<<p;for(s.sort((function(e,t){return v[t.s]-v[e.s]||e.f-t.f}));i<r;++i){var y=s[i].s;if(!(v[y]>t))break;f+=m-(1<<g-v[y]),v[y]=t}for(f>>>=p;f>0;){var S=s[i].s;v[S]<t?f-=1<<t-v[S]++-1:++i}for(;i>=0&&f;--i){var b=s[i].s;v[b]==t&&(--v[b],++f)}g=t}return[new de(v),g]},qe=function(e,t,n){return-1==e.s?Math.max(qe(e.l,t,n+1),qe(e.r,t,n+1)):t[e.s]=n},De=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new ue(++t),i=0,r=e[0],s=1,o=function(e){n[i++]=e},a=1;a<=t;++a)if(e[a]==r&&a!=t)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=e[a]}return[n.subarray(0,i),t]},Ne=function(e,t){for(var n=0,i=0;i<t.length;++i)n+=e[i]*t[i];return n},$e=function(e,t,n){var i=n.length,r=Re(t+2);e[r]=255&i,e[r+1]=i>>>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var s=0;s<i;++s)e[r+s+4]=n[s];return 8*(r+4+i)},je=function(e,t,n,i,r,s,o,a,l,c,d){xe(t,d++,n),++r[256];for(var u=Le(r,15),h=u[0],v=u[1],g=Le(s,15),f=g[0],p=g[1],m=De(h),y=m[0],S=m[1],b=De(f),I=b[0],w=b[1],C=new ue(19),E=0;E<y.length;++E)C[31&y[E]]++;for(E=0;E<I.length;++E)C[31&I[E]]++;for(var P=Le(C,7),T=P[0],_=P[1],k=19;k>4&&!T[fe[k-1]];--k);var R,O,x,M,L=c+5<<3,q=Ne(r,Pe)+Ne(s,Te)+o,D=Ne(r,h)+Ne(s,f)+o+14+3*k+Ne(C,T)+(2*C[16]+3*C[17]+7*C[18]);if(L<=q&&L<=D)return $e(t,d,e.subarray(l,l+c));if(xe(t,d,1+(D<q)),d+=2,D<q){R=Ee(h,v,0),O=h,x=Ee(f,p,0),M=f;var N=Ee(T,_,0);xe(t,d,S-257),xe(t,d+5,w-1),xe(t,d+10,k-4),d+=14;for(E=0;E<k;++E)xe(t,d+3*E,T[fe[E]]);d+=3*k;for(var $=[y,I],j=0;j<2;++j){var U=$[j];for(E=0;E<U.length;++E){var F=31&U[E];xe(t,d,N[F]),d+=T[F],F>15&&(xe(t,d,U[E]>>>5&127),d+=U[E]>>>12)}}}else R=_e,O=Pe,x=ke,M=Te;for(E=0;E<a;++E)if(i[E]>255){F=i[E]>>>18&31;Me(t,d,R[F+257]),d+=O[F+257],F>7&&(xe(t,d,i[E]>>>23&31),d+=ve[F]);var A=31&i[E];Me(t,d,x[A]),d+=M[A],A>3&&(Me(t,d,i[E]>>>5&8191),d+=ge[A])}else Me(t,d,R[i[E]]),d+=O[i[E]];return Me(t,d,R[256]),d+O[256]},Ue=new he([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Fe=function(e,t,n,i,r){return function(e,t,n,i,r,s){var o=e.length,a=new de(i+o+5*(1+Math.floor(o/7e3))+r),l=a.subarray(i,a.length-r),c=0;if(!t||o<8)for(var d=0;d<=o;d+=65535){var u=d+65535;u<o?c=$e(l,c,e.subarray(d,u)):(l[d]=s,c=$e(l,c,e.subarray(d,o)))}else{for(var h=Ue[t-1],v=h>>>13,g=8191&h,f=(1<<n)-1,p=new ue(32768),m=new ue(f+1),y=Math.ceil(n/3),S=2*y,b=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<S)&f},I=new he(25e3),w=new ue(288),C=new ue(32),E=0,P=0,T=(d=0,0),_=0,k=0;d<o;++d){var R=b(d),O=32767&d,x=m[R];if(p[O]=x,m[R]=O,_<=d){var M=o-d;if((E>7e3||T>24576)&&M>423){c=je(e,l,0,I,w,C,P,T,k,d-k,c),T=E=P=0,k=d;for(var L=0;L<286;++L)w[L]=0;for(L=0;L<30;++L)C[L]=0}var q=2,D=0,N=g,$=O-x&32767;if(M>2&&R==b(d-$))for(var j=Math.min(v,M)-1,U=Math.min(32767,d),F=Math.min(258,M);$<=U&&--N&&O!=x;){if(e[d+q]==e[d+q-$]){for(var A=0;A<F&&e[d+A]==e[d+A-$];++A);if(A>q){if(q=A,D=$,A>j)break;var B=Math.min($,A-2),K=0;for(L=0;L<B;++L){var W=d-$+L+32768&32767,z=W-p[W]+32768&32767;z>K&&(K=z,x=W)}}}$+=(O=x)-(x=p[O])+32768&32767}if(D){I[T++]=268435456|Se[q]<<18|be[D];var G=31&Se[q],Q=31&be[D];P+=ve[G]+ge[Q],++w[257+G],++C[Q],_=d+q,++E}else I[T++]=e[d],++w[e[d]]}}c=je(e,l,s,I,w,C,P,T,k,d-k,c)}return Oe(a,0,i+Re(c)+r)}(e,null==t.level?6:t.level,null==t.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,n,i,!r)};function Ae(e,t){void 0===t&&(t={});var n=function(){var e=1,t=0;return{p:function(n){for(var i=e,r=t,s=n.length,o=0;o!=s;){for(var a=Math.min(o+5552,s);o<a;++o)r+=i+=n[o];i%=65521,r%=65521}e=i,t=r},d:function(){return(e>>>8<<16|(255&t)<<8|t>>>8)+2*((255&e)<<23)}}}();n.p(e);var i,r,s,o=Fe(e,t,2,4);return i=o,r=t.level,s=0==r?0:r<6?1:9==r?3:2,i[0]=120,i[1]=s<<6|(s?32-2*s:1),function(e,t,n){for(;n;++t)e[t]=n,n>>>=8}(o,o.length-4,n.d()),o}const Be=e=>{const t={...e,v:"v1"};return function(e,t){var n="";if(!t&&"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);for(var i=0;i<e.length;){var r=e[i++];r<128||t?n+=String.fromCharCode(r):r<224?n+=String.fromCharCode((31&r)<<6|63&e[i++]):r<240?n+=String.fromCharCode((15&r)<<12|(63&e[i++])<<6|63&e[i++]):(r=((15&r)<<18|(63&e[i++])<<12|(63&e[i++])<<6|63&e[i++])-65536,n+=String.fromCharCode(55296|r>>10,56320|1023&r))}return n}(Ae(function(e,t){var n=e.length;if(!t&&"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var i=new de(e.length+(e.length>>>1)),r=0,s=function(e){i[r++]=e},o=0;o<n;++o){if(r+5>i.length){var a=new de(r+8+(n-o<<1));a.set(i),i=a}var l=e.charCodeAt(o);l<128||t?s(l):l<2048?(s(192|l>>>6),s(128|63&l)):l>55295&&l<57344?(s(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++o))>>>18),s(128|l>>>12&63),s(128|l>>>6&63),s(128|63&l)):(s(224|l>>>12),s(128|l>>>6&63),s(128|63&l))}return Oe(i,0,r)}(JSON.stringify(t))),!0)};class Ke{constructor(e,t,n,i){var r;this.taskQueue=[],this.isProcessing=!1,this.compressEvent=e=>{const t=Be(e);return JSON.stringify(t)},this.addCompressedEventToManager=(e,t)=>{this.eventsManager&&this.deviceId&&this.eventsManager.addEvent({event:{type:"replay",data:e},sessionId:t,deviceId:this.deviceId})},this.addCompressedEvent=(e,t)=>{if(this.worker)try{this.worker.postMessage({event:e,sessionId:t})}catch(n){"DataCloneError"===n.name?this.worker.postMessage(JSON.stringify({event:e,sessionId:t})):this.config.loggerProvider.warn("Unexpected error while posting message to worker:",n)}else{const n=this.compressEvent(e);this.addCompressedEventToManager(n,t)}},this.terminate=()=>{var e;null===(e=this.worker)||void 0===e||e.terminate()};const s=v();if(this.canUseIdleCallback=s&&"requestIdleCallback"in s,this.eventsManager=e,this.config=t,this.deviceId=n,this.timeout=(null===(r=t.performanceConfig)||void 0===r?void 0:r.timeout)||2e3,i){t.loggerProvider.log("[Experimental] Enabling web worker for compression");const e=new Worker(URL.createObjectURL(new Blob([i],{type:"application/javascript"})));e.onerror=e=>{t.loggerProvider.error(e)},e.onmessage=e=>{const{compressedEvent:t,sessionId:n}=e.data;this.addCompressedEventToManager(t,n)},this.worker=e}}scheduleIdleProcessing(){this.isProcessing||(this.isProcessing=!0,requestIdleCallback((e=>{this.processQueue(e)}),{timeout:this.timeout}))}enqueueEvent(e,t){var n;this.canUseIdleCallback&&(null===(n=this.config.performanceConfig)||void 0===n?void 0:n.enabled)?(this.config.loggerProvider.debug("Enqueuing event for processing during idle time."),this.taskQueue.push({event:e,sessionId:t}),this.scheduleIdleProcessing()):(this.config.loggerProvider.debug("Processing event without idle callback."),this.addCompressedEvent(e,t))}processQueue(e){for(;this.taskQueue.length>0&&(e.timeRemaining()>0||e.didTimeout);){const e=this.taskQueue.shift();if(e){const{event:t,sessionId:n}=e;this.addCompressedEvent(t,n)}}this.taskQueue.length>0?requestIdleCallback((e=>{this.processQueue(e)}),{timeout:this.timeout}):this.isProcessing=!1}}const We="Failed to store session replay events in IndexedDB",ze="1.28.15";class Ge{constructor({trackServerUrl:e,loggerProvider:t,payloadBatcher:n}){this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.loggerProvider=t,this.payloadBatcher=n||(e=>e),this.trackServerUrl=e}sendEventsList(e){this.addToQueue(Object.assign(Object.assign({},e),{attempts:0,timeout:0}))}addToQueue(...e){e.filter((e=>e.attempts<(e.flushMaxRetries||0)?(e.attempts+=1,!0):(this.completeRequest({context:e,err:"Session replay event batch rejected due to exceeded retry count"}),!1))).forEach((e=>{this.queue=this.queue.concat(e),0!==e.timeout?setTimeout((()=>{e.timeout=0,this.schedule(0)}),e.timeout):this.schedule(0)}))}schedule(e){this.scheduled||(this.scheduled=setTimeout((()=>{this.flush(!0).then((()=>{this.queue.length>0&&this.schedule(e)}))}),e))}flush(e=!1){return t(this,void 0,void 0,(function*(){const t=[],n=[];this.queue.forEach((e=>0===e.timeout?t.push(e):n.push(e))),this.queue=n,this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null),yield Promise.all(t.map((t=>this.send(t,e))))}))}send(e,n=!0){var i,r;return t(this,void 0,void 0,(function*(){const t=e.apiKey;if(!t)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing api key"});const s=e.deviceId;if(!s)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing device ID"});const o=(()=>{const e=v();return(null==e?void 0:e.location)?e.location.href:""})(),a=ze,l=e.sampleRate,c=new URLSearchParams({device_id:s,session_id:`${e.sessionId}`,type:`${e.type}`}),d=`${(null===(i=e.version)||void 0===i?void 0:i.type)||"standalone"}/${(null===(r=e.version)||void 0===r?void 0:r.version)||a}`,u=this.payloadBatcher({version:1,events:e.events});if(0!==u.events.length)try{const i={headers:{"Content-Type":"application/json",Accept:"*/*",Authorization:`Bearer ${t}`,"X-Client-Version":a,"X-Client-Library":d,"X-Client-Url":o.substring(0,1e3),"X-Client-Sample-Rate":`${l}`},body:JSON.stringify(u),method:"POST"},r=`${Q(e.serverZone,this.trackServerUrl)}?${c.toString()}`,s=yield fetch(r,i);if(null===s)return void this.completeRequest({context:e,err:"Unexpected error occurred"});if(n)this.handleReponse(s.status,e);else{let t="";try{t=JSON.stringify(s.body,null,2)}catch(e){}this.completeRequest({context:e,success:`${s.status}: ${t}`})}}catch(t){this.completeRequest({context:e,err:t})}else this.completeRequest({context:e})}))}handleReponse(e,t){switch((new L).buildStatus(e)){case l.Success:this.handleSuccessResponse(t);break;case l.Failed:this.handleOtherResponse(t);break;default:this.completeRequest({context:t,err:"Network error occurred, event batch rejected"})}}handleSuccessResponse(e){const t=Math.round(new Blob(e.events).size/1024);this.completeRequest({context:e,success:`Session replay event batch tracked successfully for session id ${e.sessionId}, size of events: ${t} KB`})}handleOtherResponse(e){this.addToQueue(Object.assign(Object.assign({},e),{timeout:e.attempts*this.retryTimeout}))}completeRequest({context:e,err:t,success:n}){e.onComplete(),t?this.loggerProvider.warn(t):n&&this.loggerProvider.log(n)}}class Qe{get timeAtLastSplit(){return this._timeAtLastSplit}constructor(e){var t,n,i;this.minInterval=500,this.maxInterval=1e4,this.maxPersistedEventsSize=1e6,this.interval=this.minInterval,this._timeAtLastSplit=Date.now(),this.shouldSplitEventsList=(e,t)=>{const n=this.getStringSize(t);return this.getEventsArraySize(e)+n>=this.maxPersistedEventsSize||!!(Date.now()-this.timeAtLastSplit>this.interval&&e.length)&&(this.interval=Math.min(this.maxInterval,this.interval+this.minInterval),this._timeAtLastSplit=Date.now(),!0)},this.loggerProvider=e.loggerProvider,this.minInterval=null!==(t=e.minInterval)&&void 0!==t?t:this.minInterval,this.maxInterval=null!==(n=e.maxInterval)&&void 0!==n?n:this.maxInterval,this.maxPersistedEventsSize=null!==(i=e.maxPersistedEventsSize)&&void 0!==i?i:this.maxPersistedEventsSize}getStringSize(e){return e.length}getEventsArraySize(e){let t=0;for(const n of e)t+=this.getStringSize(n);return t+(2+Math.max(0,e.length-1)+2*e.length)}}var He;!function(e){e.RECORDING="recording",e.SENT="sent"}(He||(He={}));const Je="sessionCurrentSequence",Ze="sequencesToSend",Xe=e=>t(void 0,void 0,void 0,(function*(){for(;e.length>0;){const t=10,n=e.splice(0,t);yield Promise.all(n)}})),Ve=e=>{let t,n;return e.objectStoreNames.contains(Je)||(n=e.createObjectStore(Je,{keyPath:"sessionId"})),e.objectStoreNames.contains(Ze)||(t=e.createObjectStore(Ze,{keyPath:"sequenceId",autoIncrement:!0}),t.createIndex("sessionId","sessionId")),{sequencesStore:t,currentSequenceStore:n}};class Ye extends Qe{constructor(e){super(e),this.getSequencesToSend=()=>t(this,void 0,void 0,(function*(){try{const e=[];let t=yield this.db.transaction("sequencesToSend").store.openCursor();for(;t;){const{sessionId:n,events:i}=t.value;e.push({events:i,sequenceId:t.key,sessionId:n}),t=yield t.continue()}return e}catch(e){this.loggerProvider.warn(`${We}: ${e}`)}})),this.storeCurrentSequence=e=>t(this,void 0,void 0,(function*(){try{const t=yield this.db.get(Je,e);if(!t)return;const n=yield this.db.put(Ze,{sessionId:e,events:t.events});return yield this.db.put(Je,{sessionId:e,events:[]}),Object.assign(Object.assign({},t),{sessionId:e,sequenceId:n})}catch(e){this.loggerProvider.warn(`${We}: ${e}`)}})),this.addEventToCurrentSequence=(e,n)=>t(this,void 0,void 0,(function*(){try{const t=this.db.transaction(Je,"readwrite"),i=yield t.store.get(e);if(!i)return void(yield t.store.put({sessionId:e,events:[n]}));let r;if(this.shouldSplitEventsList(i.events,n))r=i.events,yield t.store.put({sessionId:e,events:[n]});else{const r=i.events.concat(n);yield t.store.put({sessionId:e,events:r})}if(yield t.done,!r)return;const s=yield this.storeSendingEvents(e,r);if(!s)return;return{events:r,sessionId:e,sequenceId:s}}catch(e){this.loggerProvider.warn(`${We}: ${e}`)}})),this.storeSendingEvents=(e,n)=>t(this,void 0,void 0,(function*(){try{return yield this.db.put(Ze,{sessionId:e,events:n})}catch(e){this.loggerProvider.warn(`${We}: ${e}`)}})),this.cleanUpSessionEventsStore=(e,n)=>t(this,void 0,void 0,(function*(){if(n)try{yield this.db.delete(Ze,n)}catch(e){this.loggerProvider.warn(`${We}: ${e}`)}})),this.transitionFromKeyValStore=e=>t(this,void 0,void 0,(function*(){try{const n=yield function(){const e=v();return new Promise(((t,n)=>{if(!e)return n(new Error("Global scope not found"));if(!e.indexedDB)return n(new Error("Session Replay: cannot find indexedDB"));try{const i=e.indexedDB.open("keyval-store");i.onupgradeneeded=function(){1===i.result.version&&(i.result.close(),i.transaction&&i.transaction.abort(),e.indexedDB.deleteDatabase("keyval-store"),t())},i.onsuccess=function(){t(i.result)},i.onerror=function(){n(i.error)}}catch(e){n(e)}}))}();if(!n)return;const i=(e,n)=>t(this,void 0,void 0,(function*(){const i=n.sessionSequences,r=[];Object.keys(i).forEach((s=>{const o=parseInt(s,10),a=i[o];if(o===n.currentSequenceId){const n=a.events.map((n=>t(this,void 0,void 0,(function*(){return this.addEventToCurrentSequence(e,n)}))));r.push(...n)}else a.status!==He.SENT&&r.push(this.storeSendingEvents(e,a.events))})),yield Xe(r)})),r=`${c}_${this.apiKey.substring(0,10)}`;try{const s=n.transaction("keyval").objectStore("keyval").getAll(r),o=new Promise((n=>{s.onsuccess=r=>t(this,void 0,void 0,(function*(){const t=r&&r.target.result,s=t&&t[0];if(s){const t=[];Object.keys(s).forEach((n=>{const r=parseInt(n,10),o=s[r];if(e===r)t.push(i(r,o));else{const e=o.sessionSequences;Object.keys(e).forEach((n=>{const i=parseInt(n,10);e[i].status!==He.SENT&&t.push(this.storeSendingEvents(r,e[i].events))}))}})),yield Xe(t)}n()}))}));yield o;const a=v();a&&a.indexedDB.deleteDatabase("keyval-store")}catch(e){this.loggerProvider.warn(`Failed to transition session replay events from keyval to new store: ${e}`)}}catch(e){this.loggerProvider.warn(`Failed to access keyval store: ${e}. For more information, visit: https://www.docs.developers.amplitude.com/session-replay/sdks/standalone/#indexeddb-best-practices`)}})),this.apiKey=e.apiKey,this.db=e.db}static new(e,n,i){return t(this,void 0,void 0,(function*(){try{const r="replay"===e?"":`_${e}`,o=`${n.apiKey.substring(0,10)}_amp_session_replay_events${r}`,a=yield(e=>t(void 0,void 0,void 0,(function*(){return yield s(e,1,{upgrade:Ve})})))(o),l=new Ye(Object.assign(Object.assign({},n),{db:a}));return yield l.transitionFromKeyValStore(i),l}catch(e){n.loggerProvider.warn(`${We}: ${e}`)}}))}getCurrentSequenceEvents(e){return t(this,void 0,void 0,(function*(){if(e){const t=yield this.db.get("sessionCurrentSequence",e);if(!t)return;return[t]}const t=[];for(const e of yield this.db.getAll("sessionCurrentSequence"))t.push(e);return t}))}}class et extends Qe{constructor(){super(...arguments),this.finalizedSequences={},this.sequences={},this.sequenceId=0}resetCurrentSequence(e){this.sequences[e]=[]}addSequence(e){const t=this.sequenceId++,n=[...this.sequences[e]];return this.finalizedSequences[t]={sessionId:e,events:n},this.resetCurrentSequence(e),{sequenceId:t,events:n,sessionId:e}}getSequencesToSend(){return t(this,void 0,void 0,(function*(){return Object.entries(this.finalizedSequences).map((([e,{sessionId:t,events:n}])=>({sequenceId:Number(e),sessionId:t,events:n})))}))}storeCurrentSequence(e){return t(this,void 0,void 0,(function*(){if(this.sequences[e])return this.addSequence(e)}))}addEventToCurrentSequence(e,n){return t(this,void 0,void 0,(function*(){let t;return this.sequences[e]||this.resetCurrentSequence(e),this.shouldSplitEventsList(this.sequences[e],n)&&(t=this.addSequence(e)),this.sequences[e].push(n),t}))}storeSendingEvents(e,n){return t(this,void 0,void 0,(function*(){return this.finalizedSequences[this.sequenceId]={sessionId:e,events:n},this.sequenceId++}))}cleanUpSessionEventsStore(e,n){return t(this,void 0,void 0,(function*(){void 0!==n&&delete this.finalizedSequences[n]}))}}const tt=({config:e,sessionId:n,minInterval:i,maxInterval:r,type:s,payloadBatcher:o,storeType:a})=>t(void 0,void 0,void 0,(function*(){const l=new Ge(Object.assign(Object.assign({},e),{loggerProvider:e.loggerProvider,payloadBatcher:o})),c=()=>new et({loggerProvider:e.loggerProvider,maxInterval:r,minInterval:i}),d="idb"===a?yield t(void 0,void 0,void 0,(function*(){const t=yield Ye.new(s,{loggerProvider:e.loggerProvider,minInterval:i,maxInterval:r,apiKey:e.apiKey},n);return e.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),null!=t?t:c()})):c(),u=({events:n,sessionId:i,deviceId:r,sequenceId:o})=>{e.debugMode&&Z().then((({totalStorageSize:t,percentOfQuota:n,usageDetails:i})=>{e.loggerProvider.debug(`Total storage size: ${t} KB, percentage of quota: ${n}%, usage details: ${i}`)})).catch((()=>{})),l.sendEventsList({events:n,sessionId:i,flushMaxRetries:e.flushMaxRetries,apiKey:e.apiKey,deviceId:r,sampleRate:e.sampleRate,serverZone:e.serverZone,version:e.version,type:s,onComplete:()=>t(void 0,void 0,void 0,(function*(){yield d.cleanUpSessionEventsStore(i,o)}))})};return{sendCurrentSequenceEvents:({sessionId:t,deviceId:n})=>{d.storeCurrentSequence(t).then((e=>{e&&u({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n})})).catch((t=>{e.loggerProvider.warn("Failed to get current sequence of session replay events for session:",t)}))},addEvent:({event:t,sessionId:n,deviceId:i})=>{d.addEventToCurrentSequence(n,t.data).then((e=>e&&u({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:i}))).catch((t=>{e.loggerProvider.warn("Failed to add event to session replay capture:",t)}))},sendStoredEvents:({deviceId:e})=>t(void 0,void 0,void 0,(function*(){const t=yield d.getSequencesToSend();t&&t.forEach((t=>{u({sequenceId:t.sequenceId,events:t.events,sessionId:t.sessionId,deviceId:e})}))})),flush:function(e=!1){return t(this,void 0,void 0,(function*(){return l.flush(e)}))}}}));class nt{constructor(...e){const t=new Map;e.forEach((e=>{t.set(e.name,e.manager)})),this.managers=t}sendStoredEvents(e){return t(this,void 0,void 0,(function*(){const t=[];this.managers.forEach((n=>{t.push(n.sendStoredEvents(e))})),yield Promise.all(t)}))}addEvent({sessionId:e,event:t,deviceId:n}){var i;null===(i=this.managers.get(t.type))||void 0===i||i.addEvent({sessionId:e,event:t,deviceId:n})}sendCurrentSequenceEvents({sessionId:e,deviceId:t}){this.managers.forEach((n=>{n.sendCurrentSequenceEvents({sessionId:e,deviceId:t})}))}flush(e){return t(this,void 0,void 0,(function*(){const t=[];this.managers.forEach((n=>{t.push(n.flush(e))})),yield Promise.all(t)}))}}const it={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},rt={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},st={};function ot(e){if(st[e])return st[e];const t=function(e){var t,n;const i=null==(n=null==(t=null==globalThis?void 0:globalThis.Zone)?void 0:t.__symbol__)?void 0:n.call(t,e);return i&&globalThis[i]?globalThis[i]:void 0}(e)||globalThis[e],n=t.prototype,i=e in it?it[e]:void 0,r=Boolean(i&&i.every((e=>{var t,i;return Boolean(null==(i=null==(t=Object.getOwnPropertyDescriptor(n,e))?void 0:t.get)?void 0:i.toString().includes("[native code]"))}))),s=e in rt?rt[e]:void 0,o=Boolean(s&&s.every((e=>{var t;return"function"==typeof n[e]&&(null==(t=n[e])?void 0:t.toString().includes("[native code]"))})));if(r&&o)return st[e]=t.prototype,t.prototype;try{const i=document.createElement("iframe");document.body.appendChild(i);const r=i.contentWindow;if(!r)return t.prototype;const s=r[e].prototype;return document.body.removeChild(i),s?st[e]=s:n}catch{return n}}const at={};function lt(e,t,n){var i;const r=`${e}.${String(n)}`;if(at[r])return at[r].call(t);const s=ot(e),o=null==(i=Object.getOwnPropertyDescriptor(s,n))?void 0:i.get;return o?(at[r]=o,o.call(t)):t[n]}const ct={};function dt(e,t,n){const i=`${e}.${String(n)}`;if(ct[i])return ct[i].bind(t);const r=ot(e)[n];return"function"!=typeof r?t[n]:(ct[i]=r,r.bind(t))}const ut={childNodes:function(e){return lt("Node",e,"childNodes")},parentNode:function(e){return lt("Node",e,"parentNode")},parentElement:function(e){return lt("Node",e,"parentElement")},textContent:function(e){return lt("Node",e,"textContent")},contains:function(e,t){return dt("Node",e,"contains")(t)},getRootNode:function(e){return dt("Node",e,"getRootNode")()},host:function(e){return e&&"host"in e?lt("ShadowRoot",e,"host"):null},styleSheets:function(e){return e.styleSheets},shadowRoot:function(e){return e&&"shadowRoot"in e?lt("Element",e,"shadowRoot"):null},querySelector:function(e,t){return lt("Element",e,"querySelector")(t)},querySelectorAll:function(e,t){return lt("Element",e,"querySelectorAll")(t)},mutationObserver:function(){return ot("MutationObserver").constructor}};function ht(){const e=v();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight||0}function vt(){const e=v();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth||0}let gt,ft,pt;function mt(e,t){if(pt=new Date,e.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if("html"===e.tagName.toLowerCase())return"html";const n={root:document.body,idName:e=>!0,className:e=>!0,tagName:e=>!0,attr:(e,t)=>!1,seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};gt=Object.assign(Object.assign({},n),t),ft=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(gt.root,n);let i=yt(e,"all",(()=>yt(e,"two",(()=>yt(e,"one",(()=>yt(e,"none")))))));if(i){const t=Lt(qt(i,e));return t.length>0&&(i=t[0]),bt(i)}throw new Error("Selector was not found.")}function yt(e,t,n){let i=null,r=[],s=e,o=0;for(;s;){const e=(new Date).getTime()-pt.getTime();if(void 0!==gt.timeoutMs&&e>gt.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${e}ms`);let a=Ot(Ct(s))||Ot(...Et(s))||Ot(...Pt(s))||Ot(Tt(s))||[{name:"*",penalty:3}];const l=_t(s);if("all"==t)l&&(a=a.concat(a.filter(Rt).map((e=>kt(e,l)))));else if("two"==t)a=a.slice(0,1),l&&(a=a.concat(a.filter(Rt).map((e=>kt(e,l)))));else if("one"==t){const[e]=a=a.slice(0,1);l&&Rt(e)&&(a=[kt(e,l)])}else"none"==t&&(a=[{name:"*",penalty:3}],l&&(a=[kt(a[0],l)]));for(let e of a)e.level=o;if(r.push(a),r.length>=gt.seedMinLength&&(i=St(r,n),i))break;s=s.parentElement,o++}return i||(i=St(r,n)),!i&&n?n():i}function St(e,t){const n=Lt(Mt(e));if(n.length>gt.threshold)return t?t():null;for(let e of n)if(wt(e))return e;return null}function bt(e){let t=e[0],n=t.name;for(let i=1;i<e.length;i++){const r=e[i].level||0;n=t.level===r-1?`${e[i].name} > ${n}`:`${e[i].name} ${n}`,t=e[i]}return n}function It(e){return e.map((e=>e.penalty)).reduce(((e,t)=>e+t),0)}function wt(e){const t=bt(e);switch(ft.querySelectorAll(t).length){case 0:throw new Error(`Can't select any node with this selector: ${t}`);case 1:return!0;default:return!1}}function Ct(e){const t=e.getAttribute("id");return t&>.idName(t)?{name:"#"+CSS.escape(t),penalty:0}:null}function Et(e){const t=Array.from(e.attributes).filter((e=>gt.attr(e.name,e.value)));return t.map((e=>({name:`[${CSS.escape(e.name)}="${CSS.escape(e.value)}"]`,penalty:.5})))}function Pt(e){return Array.from(e.classList).filter(gt.className).map((e=>({name:"."+CSS.escape(e),penalty:1})))}function Tt(e){const t=e.tagName.toLowerCase();return gt.tagName(t)?{name:t,penalty:2}:null}function _t(e){const t=e.parentNode;if(!t)return null;let n=t.firstChild;if(!n)return null;let i=0;for(;n&&(n.nodeType===Node.ELEMENT_NODE&&i++,n!==e);)n=n.nextSibling;return i}function kt(e,t){return{name:e.name+`:nth-child(${t})`,penalty:e.penalty+1}}function Rt(e){return"html"!==e.name&&!e.name.startsWith("#")}function Ot(...e){const t=e.filter(xt);return t.length>0?t:null}function xt(e){return null!=e}function*Mt(e,t=[]){if(e.length>0)for(let n of e[0])yield*Mt(e.slice(1,e.length),t.concat(n));else yield t}function Lt(e){return[...e].sort(((e,t)=>It(e)-It(t)))}function*qt(e,t,n={counter:0,visited:new Map}){if(e.length>2&&e.length>gt.optimizedMinLength)for(let i=1;i<e.length-1;i++){if(n.counter>gt.maxNumberOfTries)return;n.counter+=1;const r=[...e];r.splice(i,1);const s=bt(r);if(n.visited.has(s))return;wt(r)&&Dt(r,t)&&(yield r,n.visited.set(s,!0),yield*qt(r,t,n))}}function Dt(e,t){return ft.querySelector(bt(e))===t}const Nt=({version:e,events:t})=>{const n=[];return t.forEach((e=>{const t=JSON.parse(e);t.count=1,"click"===t.type&&n.push(t)})),{version:e,events:n}},$t=({version:e,events:t})=>{const n=[];t.forEach((e=>{const t=JSON.parse(e);"click"===t.type&&n.push(t)}));const i=n.reduce(((e,t)=>{const{x:n,y:i,selector:r,timestamp:s}=t,o=s-s%36e5,a=`${n}:${i}:${null!=r?r:""}:${o}`;return e[a]?e[a].count+=1:e[a]=Object.assign(Object.assign({},t),{timestamp:o,count:1}),e}),{});return{version:e,events:Object.values(i)}},jt=(e,{eventsManager:t,sessionId:n,deviceIdFn:i,mirror:r,ugcFilterRules:s})=>o=>{if(o.type!==ie.Click)return;const a=v();if(!a)return;const{location:l,innerHeight:c,innerWidth:d}=a;if(!l)return;const{x:u,y:h}=o;if(void 0===u||void 0===h)return;const g=r.getNode(o.id);let f;if(g)try{f=mt(g)}catch(t){e.debug("error resolving selector from finder")}const{left:p,top:m}=function(e){var t,n,i,r;const s=e.document;return{left:s.scrollingElement?s.scrollingElement.scrollLeft:void 0!==e.pageXOffset?e.pageXOffset:s.documentElement.scrollLeft||(null==s?void 0:s.body)&&(null===(t=ut.parentElement(s.body))||void 0===t?void 0:t.scrollLeft)||(null===(n=null==s?void 0:s.body)||void 0===n?void 0:n.scrollLeft)||0,top:s.scrollingElement?s.scrollingElement.scrollTop:void 0!==e.pageYOffset?e.pageYOffset:(null==s?void 0:s.documentElement.scrollTop)||(null==s?void 0:s.body)&&(null===(i=ut.parentElement(s.body))||void 0===i?void 0:i.scrollTop)||(null===(r=null==s?void 0:s.body)||void 0===r?void 0:r.scrollTop)||0}}(a),y={x:u+p,y:h+m,selector:f,viewportHeight:c,viewportWidth:d,pageUrl:J(l.href,s),timestamp:Date.now(),type:"click"},S=i();S&&t.addEvent({sessionId:n,event:{type:"interaction",data:JSON.stringify(y)},deviceId:S})};class Ut{constructor(e,t){const n=v();n&&n.navigator&&"function"==typeof n.navigator.sendBeacon?this.sendBeacon=(e,t)=>{try{if(n.navigator.sendBeacon(e,JSON.stringify(t)))return!0}catch(e){}return!1}:this.sendBeacon=()=>!1,this.sendXhr=(e,t)=>{const n=new XMLHttpRequest;return n.open("POST",e,!0),n.setRequestHeader("Accept","*/*"),n.send(JSON.stringify(t)),!0},this.basePageUrl=Q(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e}send(e,t){const{sessionId:n,type:i}=this.context,r=new URLSearchParams({device_id:e,session_id:String(n),type:String(i),api_key:this.apiKey}),s=`${this.basePageUrl}?${r.toString()}`;this.sendBeacon(s,t)||this.sendXhr(s,t)}}class Ft{static default(e,t){return new Ft(new Ut(e,t),t)}constructor(e,t){this.timestamp=Date.now(),this.hook=e=>{this.update(e)},this.send=e=>t=>{var n,i;const r=e(),s=v();s&&r&&this.transport.send(r,{version:1,events:[{maxScrollX:this._maxScrollX,maxScrollY:this._maxScrollY,maxScrollWidth:this._maxScrollWidth,maxScrollHeight:this._maxScrollHeight,viewportHeight:ht(),viewportWidth:vt(),pageUrl:J(s.location.href,null!==(i=null===(n=this.config.interactionConfig)||void 0===n?void 0:n.ugcFilterRules)&&void 0!==i?i:[]),timestamp:this.timestamp,type:"scroll"}]})},this._maxScrollX=0,this._maxScrollY=0,this._maxScrollWidth=vt(),this._maxScrollHeight=ht(),this.config=t,this.transport=e}get maxScrollX(){return this._maxScrollX}get maxScrollY(){return this._maxScrollY}get maxScrollWidth(){return this._maxScrollWidth}get maxScrollHeight(){return this._maxScrollHeight}update(e){const t=Date.now();if(e.x>this._maxScrollX){const n=vt();this._maxScrollX=e.x;const i=e.x+n;i>this._maxScrollWidth&&(this._maxScrollWidth=i),this.timestamp=t}if(e.y>this._maxScrollY){const n=ht();this._maxScrollY=e.y;const i=e.y+n;i>this._maxScrollHeight&&(this._maxScrollHeight=i),this.timestamp=t}}}class At{constructor({sessionId:e,deviceId:t}){this.deviceId=t,this.sessionId=e,e&&t&&(this.sessionReplayId=((e,t)=>`${t}/${e}`)(e,t))}}const Bt=new class{constructor(){this.dbs={},this.createStore=e=>t(this,void 0,void 0,(function*(){return yield s(e,1,{upgrade:e=>{e.objectStoreNames.contains("sessionTargetingMatch")||e.createObjectStore("sessionTargetingMatch",{keyPath:"sessionId"})}})})),this.openOrCreateDB=e=>t(this,void 0,void 0,(function*(){if(this.dbs&&this.dbs[e])return this.dbs[e];const t=`${e.substring(0,10)}_amp_session_replay_targeting`,n=yield this.createStore(t);return this.dbs[e]=n,n})),this.getTargetingMatchForSession=({loggerProvider:e,apiKey:n,sessionId:i})=>t(this,void 0,void 0,(function*(){try{const e=yield this.openOrCreateDB(n),t=String(i),r=yield e.get("sessionTargetingMatch",t);return null==r?void 0:r.targetingMatch}catch(t){e.warn(`Failed to get targeting match for session id ${i}: ${t}`)}})),this.storeTargetingMatchForSession=({loggerProvider:e,apiKey:n,sessionId:i,targetingMatch:r})=>t(this,void 0,void 0,(function*(){try{const e=yield this.openOrCreateDB(n),t=String(i);return yield e.put("sessionTargetingMatch",{targetingMatch:r,sessionId:t,lastUpdated:Date.now()})}catch(t){e.warn(`Failed to store targeting match for session id ${i}: ${t}`)}})),this.clearStoreOfOldSessions=({loggerProvider:e,apiKey:n,currentSessionId:i})=>t(this,void 0,void 0,(function*(){try{const e=yield this.openOrCreateDB(n),t=String(i),r=e.transaction("sessionTargetingMatch","readwrite"),s=yield r.store.getAll();for(let e=0;e<s.length;e++){const n=s[e],i=Date.now()-n.lastUpdated;n.sessionId!==t&&i>1728e5&&(yield r.store.delete(n.sessionId))}yield r.done}catch(t){e.warn(`Failed to clear old targeting matches for sessions: ${t}`)}}))}};function Kt(e={}){return{name:"amplitude/url-tracking@1",observer(t,n,i){var r,s,o;const a=Object.assign(Object.assign({},e),i),l=a.ugcFilterRules||[],c=null!==(r=a.enablePolling)&&void 0!==r&&r,d=null!==(s=a.pollingInterval)&&void 0!==s?s:1e3,u=null!==(o=a.captureDocumentTitle)&&void 0!==o&&o;if(!n)return()=>{};let h;const v=()=>n.location&&n.location.href||"",g=()=>{const e=v();if(void 0===h||e!==h){h=e;const i=(()=>{const{innerHeight:e,innerWidth:t,document:i}=n,r=v();let s="";return u&&(s=(null==i?void 0:i.title)||""),{href:l.length>0?J(r,l):r,title:s,viewportHeight:e,viewportWidth:t,type:"url-change-event"}})();t(i)}},f=e=>function(...t){const n=e.apply(this,t);return g(),n},p=()=>{g()};if(c){const e=n.setInterval((()=>{g()}),d);return g(),()=>{e&&n.clearInterval(e)}}if(n.history){const e=n.history.pushState.bind(n.history),t=n.history.replaceState.bind(n.history);return(()=>{n.history.pushState=f(e),n.history.replaceState=f(t)})(),n.addEventListener("popstate",g),n.addEventListener("hashchange",p),g(),()=>{n.history.pushState=e,n.history.replaceState=t,n.removeEventListener("popstate",g),n.removeEventListener("hashchange",p)}}return n.addEventListener("hashchange",p),g(),()=>{n.removeEventListener("hashchange",p)}},options:e}}class Wt{constructor(){this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.pageLeaveFns=[],this.recordFunction=null,this.teardownEventListeners=e=>{const t=v();t&&(t.removeEventListener("blur",this.blurListener),t.removeEventListener("focus",this.focusListener),!e&&t.addEventListener("blur",this.blurListener),!e&&t.addEventListener("focus",this.focusListener),t.self&&"onpagehide"in t.self?(t.removeEventListener("pagehide",this.pageLeaveListener),!e&&t.addEventListener("pagehide",this.pageLeaveListener)):(t.removeEventListener("beforeunload",this.pageLeaveListener),!e&&t.addEventListener("beforeunload",this.pageLeaveListener)))},this.blurListener=()=>{this.sendEvents()},this.focusListener=()=>{this.recordEvents(!1)},this.pageLeaveListener=e=>{this.pageLeaveFns.forEach((t=>{t(e)}))},this.evaluateTargetingAndCapture=(e,n=!1)=>t(this,void 0,void 0,(function*(){if(this.identifiers&&this.identifiers.sessionId&&this.config){if(!this.config.targetingConfig){if(!n)return void this.loggerProvider.log("No targeting config set, skipping initialization/recording for event.");this.loggerProvider.log("Targeting config has not been set yet, cannot evaluate targeting.")}if(this.lastTargetingParams=e,this.config.targetingConfig&&!this.sessionTargetingMatch){let n=e.event;n&&Object.values(a).includes(n.event_type)&&(n=void 0),this.sessionTargetingMatch=yield(({sessionId:e,targetingConfig:n,loggerProvider:i,apiKey:r,targetingParams:s})=>t(void 0,void 0,void 0,(function*(){if(yield Bt.clearStoreOfOldSessions({loggerProvider:i,apiKey:r,currentSessionId:e}),!0===(yield Bt.getTargetingMatchForSession({loggerProvider:i,apiKey:r,sessionId:e})))return!0;let t=!0;try{const{evaluateTargeting:o}=yield import("./targeting-min.js").then((function(e){return e.i})),a=yield o(Object.assign(Object.assign({},s),{flag:n,sessionId:e,apiKey:r,loggerProvider:i}));a&&a.sr_targeting_config&&(t="on"===a.sr_targeting_config.key),Bt.storeTargetingMatchForSession({loggerProvider:i,apiKey:r,sessionId:e,targetingMatch:t})}catch(e){const t=e;i.warn(t.message)}return t})))({sessionId:this.identifiers.sessionId,targetingConfig:this.config.targetingConfig,loggerProvider:this.loggerProvider,apiKey:this.config.apiKey,targetingParams:{userProperties:e.userProperties,event:n}}),this.loggerProvider.debug(JSON.stringify({name:"targeted replay capture config",sessionTargetingMatch:this.sessionTargetingMatch,event:n,targetingParams:e},null,2))}n?this.initialize(!0):yield this.recordEvents()}else this.identifiers&&!this.identifiers.sessionId?this.loggerProvider.log("Session ID has not been set yet, cannot evaluate targeting for Session Replay."):this.loggerProvider.warn("Session replay init has not been called, cannot evaluate targeting.")})),this.addCustomRRWebEvent=(e,n={},i=!0)=>t(this,void 0,void 0,(function*(){try{let t;const r=this.config;if(r&&e!==A.METADATA&&(t={config:X(r),version:ze},i)){const e=yield Z();t=Object.assign(Object.assign({},e),t)}this.recordCancelCallback&&this.recordFunction?this.recordFunction.addCustomEvent(e,Object.assign(Object.assign({},n),t)):this.loggerProvider.debug(`Not able to add custom replay capture event ${e} due to no ongoing recording.`)}catch(e){this.loggerProvider.debug("Error while adding custom replay capture event: ",e)}})),this.stopRecordingEvents=()=>{var e;try{this.loggerProvider.log("Session Replay capture stopping."),this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null,null===(e=this.networkObservers)||void 0===e||e.stop()}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while stopping replay capture: ${t.toString()}`)}},this.loggerProvider=new B(new p)}init(e,t){return g(this._init(e,t))}_init(e,n){var i,r,s,o,a,l,c;return t(this,void 0,void 0,(function*(){this.loggerProvider=new B(n.loggerProvider||new p),Object.prototype.hasOwnProperty.call(n,"logLevel")&&this.loggerProvider.enable(n.logLevel),this.identifiers=new At({sessionId:n.sessionId,deviceId:n.deviceId}),this.joinedConfigGenerator=yield((e,n)=>t(void 0,void 0,void 0,(function*(){const t=new Y(e,n),i=yield le({localConfig:t,configKeys:["sessionReplay"]});return new ce(i,t)})))(e,n);const{joinedConfig:d,localConfig:u,remoteConfig:h}=yield this.joinedConfigGenerator.generateJoinedConfig(this.identifiers.sessionId);if(this.config=d,this.setMetadata(n.sessionId,d,u,h,null===(i=n.version)||void 0===i?void 0:i.version,ze,null===(r=n.version)||void 0===r?void 0:r.type),n.sessionId&&(null===(s=this.config.interactionConfig)||void 0===s?void 0:s.enabled)){const e=Ft.default({sessionId:n.sessionId,type:"interaction"},this.config);this.pageLeaveFns=[e.send(this.getDeviceId.bind(this)).bind(e)],this.scrollHook=e.hook.bind(e)}const g=[];let f,{storeType:m}=this.config;"idb"!==m||(null===(o=v())||void 0===o?void 0:o.indexedDB)||(m="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log(`Using ${m} for event storage.`);try{const e=yield tt({config:this.config,sessionId:this.identifiers.sessionId,type:"replay",storeType:m});g.push({name:"replay",manager:e})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating replay events manager: ${t.toString()}`)}if(null===(a=this.config.interactionConfig)||void 0===a?void 0:a.enabled){const e=this.config.interactionConfig.batch?$t:Nt;try{const t=yield tt({config:this.config,sessionId:this.identifiers.sessionId,type:"interaction",minInterval:null!==(l=this.config.interactionConfig.trackEveryNms)&&void 0!==l?l:3e4,maxInterval:6e4,payloadBatcher:e,storeType:m});g.push({name:"interaction",manager:t})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating interaction events manager: ${t.toString()}`)}}this.eventsManager=new nt(...g),this.eventCompressor&&this.eventCompressor.terminate();const y=v();if((null===(c=this.config.experimental)||void 0===c?void 0:c.useWebWorker)&&y&&y.Worker){const{compressionScript:e}=yield import("./worker-min.js");f=e}this.eventCompressor=new Ke(this.eventsManager,this.config,this.getDeviceId(),f),yield this.initializeNetworkObservers(),this.loggerProvider.log("Installing @amplitude/session-replay-browser."),this.teardownEventListeners(!1),yield this.evaluateTargetingAndCapture({userProperties:n.userProperties},!0)}))}setSessionId(e,t){return g(this.asyncSetSessionId(e,t))}asyncSetSessionId(e,n,i){var r;return t(this,void 0,void 0,(function*(){this.sessionTargetingMatch=!1,this.lastShouldRecordDecision=void 0;const t=this.identifiers&&this.identifiers.sessionId;t&&this.sendEvents(t);const s=n||this.getDeviceId();if(this.identifiers=new At({sessionId:e,deviceId:s}),this.joinedConfigGenerator&&t){const{joinedConfig:e}=yield this.joinedConfigGenerator.generateJoinedConfig(this.identifiers.sessionId);this.config=e}(null===(r=this.config)||void 0===r?void 0:r.targetingConfig)?yield this.evaluateTargetingAndCapture({userProperties:null==i?void 0:i.userProperties}):yield this.recordEvents()}))}getSessionReplayProperties(){const e=this.config,t=this.identifiers;if(!e||!t)return this.loggerProvider.warn("Session replay init has not been called, cannot get session replay properties."),{};const n=this.getShouldRecord();let i={};return n&&(i={[N]:t.sessionReplayId?t.sessionReplayId:null},e.debugMode&&(i[U]=JSON.stringify({appHash:G(e.apiKey).toString()}))),this.addCustomRRWebEvent(A.GET_SR_PROPS,{shouldRecord:n,eventProperties:i},10===this.eventCount),10===this.eventCount&&(this.eventCount=0),this.eventCount++,i}sendEvents(e){var t;const n=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),i=this.getDeviceId();this.eventsManager&&n&&i&&this.eventsManager.sendCurrentSequenceEvents({sessionId:n,deviceId:i})}initialize(e=!1){var n;return t(this,void 0,void 0,(function*(){if(!(null===(n=this.identifiers)||void 0===n?void 0:n.sessionId))return this.loggerProvider.log("Session is not being recorded due to lack of session id."),Promise.resolve();const t=this.getDeviceId();return t?(this.eventsManager&&e&&this.eventsManager.sendStoredEvents({deviceId:t}),this.recordEvents()):(this.loggerProvider.log("Session is not being recorded due to lack of device id."),Promise.resolve())}))}shouldOptOut(){var e,t;let n;if(null===(e=this.config)||void 0===e?void 0:e.instanceName){n=(i=this.config.instanceName,void 0===i&&(i=d),x.getInstance(i)).identityStore.getIdentity().optOut}var i;return void 0!==n?n:null===(t=this.config)||void 0===t?void 0:t.optOut}getShouldRecord(){if(!this.identifiers||!this.config||!this.identifiers.sessionId)return this.loggerProvider.warn("Session is not being recorded due to lack of config, please call sessionReplay.init."),!1;if(!this.config.captureEnabled)return this.loggerProvider.log(`Session ${this.identifiers.sessionId} not being captured due to capture being disabled for project or because the remote config could not be fetched.`),!1;if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${this.identifiers.sessionId} out of recording due to optOut config.`),!1;let e=!1,t="",n=!1;if(this.config.targetingConfig)this.sessionTargetingMatch?(t=`Capturing replays for session ${this.identifiers.sessionId} due to matching targeting conditions.`,this.loggerProvider.log(t),e=!0,n=!0):(t=`Not capturing replays for session ${this.identifiers.sessionId} due to not matching targeting conditions.`,this.loggerProvider.log(t),e=!1,n=!1);else{(function(e,t){const n=G(e.toString());return 31*Math.abs(n)%1e6/1e6<t})(this.identifiers.sessionId,this.config.sampleRate)?(e=!0,n=!0):(t=`Opting session ${this.identifiers.sessionId} out of recording due to sample rate.`,this.loggerProvider.log(t),e=!1,n=!1)}return this.lastShouldRecordDecision!==e&&this.config.targetingConfig&&(this.addCustomRRWebEvent(A.TARGETING_DECISION,{message:t,sessionId:this.identifiers.sessionId,matched:n,targetingParams:this.lastTargetingParams}),this.lastShouldRecordDecision=e),e}getBlockSelectors(){var e,t,n;const i=null!==(n=null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.blockSelector)&&void 0!==n?n:[];if(0!==i.length)return i}getMaskTextSelectors(){var e,t,n,i;if("conservative"===(null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.defaultMaskLevel))return"*";const r=null===(i=null===(n=this.config)||void 0===n?void 0:n.privacyConfig)||void 0===i?void 0:i.maskSelector;return r||void 0}getRecordingPlugins(e){var n,i,r,s,o,a;return t(this,void 0,void 0,(function*(){const t=[];try{const e=Kt({ugcFilterRules:(null===(i=null===(n=this.config)||void 0===n?void 0:n.interactionConfig)||void 0===i?void 0:i.ugcFilterRules)||[],enablePolling:(null===(r=this.config)||void 0===r?void 0:r.enableUrlChangePolling)||!1,pollingInterval:null===(s=this.config)||void 0===s?void 0:s.urlChangePollingInterval,captureDocumentTitle:null===(o=this.config)||void 0===o?void 0:o.captureDocumentTitle});t.push(e)}catch(e){this.loggerProvider.warn("Failed to create URL tracking plugin:",e)}if(null===(a=null==e?void 0:e.console)||void 0===a?void 0:a.enabled)try{const{getRecordConsolePlugin:n}=yield import("./console-plugin-min.js");t.push(n({level:e.console.levels}))}catch(e){this.loggerProvider.warn("Failed to load console plugin:",e)}return t.length>0?t:void 0}))}getRecordFunction(){return t(this,void 0,void 0,(function*(){if(this.recordFunction)return this.recordFunction;try{const{record:e}=yield import("./rrweb-record-min.js");return this.recordFunction=e,e}catch(e){return this.loggerProvider.warn("Failed to load rrweb-record module:",e),null}}))}recordEvents(e=!0){var n,i,r,s,o;return t(this,void 0,void 0,(function*(){const t=this.config,a=this.getShouldRecord(),l=null===(n=this.identifiers)||void 0===n?void 0:n.sessionId;if(!a||!l||!t)return;this.stopRecordingEvents();const c=yield this.getRecordFunction();if(!c)return;yield this.initializeNetworkObservers(),null===(i=this.networkObservers)||void 0===i||i.start((e=>{this.addCustomRRWebEvent(A.FETCH_REQUEST,e)}));const{privacyConfig:d,interactionConfig:u,loggingConfig:h}=t,v=(null==u?void 0:u.enabled)?{mouseInteraction:this.eventsManager&&jt(this.loggerProvider,{eventsManager:this.eventsManager,sessionId:l,deviceIdFn:this.getDeviceId.bind(this),mirror:c.mirror,ugcFilterRules:null!==(r=u.ugcFilterRules)&&void 0!==r?r:[]}),scroll:this.scrollHook}:{},g=(null==u?void 0:u.enabled)&&u.ugcFilterRules?u.ugcFilterRules:[];this.loggerProvider.log(`Session Replay capture beginning for ${l}.`);try{this.recordCancelCallback=c({emit:e=>{if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${l} out of recording due to optOut config.`),this.stopRecordingEvents(),void this.sendEvents();e.type===ne.Meta&&(e.data.href=J(e.data.href,g)),this.eventCompressor&&this.eventCompressor.enqueueEvent(e,l)},inlineStylesheet:t.shouldInlineStylesheet,hooks:v,maskAllInputs:!0,maskTextClass:F,blockClass:"amp-block",blockSelector:this.getBlockSelectors(),applyBackgroundColorToBlockedElements:t.applyBackgroundColorToBlockedElements,maskInputFn:z("input",d),maskTextFn:z("text",d),maskTextSelector:this.getMaskTextSelectors(),recordCanvas:!1,slimDOMOptions:{script:null===(s=t.omitElementTags)||void 0===s?void 0:s.script,comment:null===(o=t.omitElementTags)||void 0===o?void 0:o.comment},errorHandler:e=>{const t=e;if(t.message.includes("insertRule")&&t.message.includes("CSSStyleSheet"))throw t;if(t._external_)throw t;return this.loggerProvider.warn("Error while capturing replay: ",t.toString()),!0},plugins:yield this.getRecordingPlugins(h)}),this.addCustomRRWebEvent(A.DEBUG_INFO),e&&this.addCustomRRWebEvent(A.METADATA,this.metadata)}catch(e){this.loggerProvider.warn("Failed to initialize session replay:",e)}}))}getDeviceId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.deviceId}getSessionId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.sessionId}flush(e=!1){var n;return t(this,void 0,void 0,(function*(){return null===(n=this.eventsManager)||void 0===n?void 0:n.flush(e)}))}shutdown(){this.teardownEventListeners(!0),this.stopRecordingEvents(),this.sendEvents()}mapSDKType(e){return"plugin"===e?"@amplitude/plugin-session-replay-browser":"segment"===e?"@amplitude/segment-session-replay-plugin":null}setMetadata(e,t,n,i,r,s,o){const a=(null==e?void 0:e.toString())?G(e.toString()):void 0;this.metadata={joinedConfig:t,localConfig:n,remoteConfig:i,sessionId:e,hashValue:a,sampleRate:t.sampleRate,replaySDKType:this.mapSDKType(o),replaySDKVersion:r,standaloneSDKType:"@amplitude/session-replay-browser",standaloneSDKVersion:s}}initializeNetworkObservers(){var e,n,i;return t(this,void 0,void 0,(function*(){if((null===(i=null===(n=null===(e=this.config)||void 0===e?void 0:e.loggingConfig)||void 0===n?void 0:n.network)||void 0===i?void 0:i.enabled)&&!this.networkObservers)try{const{NetworkObservers:e}=yield import("./observers-min.js");this.networkObservers=new e}catch(e){this.loggerProvider.warn("Failed to import or instantiate NetworkObservers:",e)}}))}}const zt=e=>()=>{const{config:t}=e,{loggerProvider:n,logLevel:i}=t||V();return{logger:n,logLevel:i}};var Gt=(()=>{const e=new Wt;return{init:M(e.init.bind(e),"init",zt(e)),evaluateTargetingAndCapture:M(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",zt(e)),setSessionId:M(e.setSessionId.bind(e),"setSessionId",zt(e)),getSessionId:M(e.getSessionId.bind(e),"getSessionId",zt(e)),getSessionReplayProperties:M(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",zt(e)),flush:M(e.flush.bind(e),"flush",zt(e)),shutdown:M(e.shutdown.bind(e),"shutdown",zt(e))}})();const{init:Qt,setSessionId:Ht,getSessionId:Jt,getSessionReplayProperties:Zt,flush:Xt,shutdown:Vt,evaluateTargetingAndCapture:Yt}=Gt;export{B as S,Jt as a,Zt as b,Vt as c,Yt as e,Xt as f,v as g,Qt as i,Ht as s};
|
|
1
|
+
import{_ as e,a as t,b as n,c as i,d as r,o as s}from"./targeting-min.js";var o,a;!function(e){e.SET="$set",e.SET_ONCE="$setOnce",e.ADD="$add",e.APPEND="$append",e.PREPEND="$prepend",e.REMOVE="$remove",e.PREINSERT="$preInsert",e.POSTINSERT="$postInsert",e.UNSET="$unset",e.CLEAR_ALL="$clearAll"}(o||(o={})),function(e){e.IDENTIFY="$identify",e.GROUP_IDENTIFY="$groupidentify",e.REVENUE="revenue_amount"}(a||(a={}));var l,c="".concat("AMP","_unsent"),d="$default_instance",u="https://api2.amplitude.com/2/httpapi";!function(e){e.Unknown="unknown",e.Skipped="skipped",e.Success="success",e.RateLimit="rate_limit",e.PayloadTooLarge="payload_too_large",e.Invalid="invalid",e.Failed="failed",e.Timeout="Timeout",e.SystemError="SystemError"}(l||(l={}));var h,g=function(){var e="ampIntegrationContext";return"undefined"!=typeof globalThis&&void 0!==globalThis[e]?globalThis[e]:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0},v=function(e){return{promise:e||Promise.resolve()}};!function(e){e[e.None=0]="None",e[e.Error=1]="Error",e[e.Warn=2]="Warn",e[e.Verbose=3]="Verbose",e[e.Debug=4]="Debug"}(h||(h={}));var f="Amplitude Logger ",p=function(){function e(){this.logLevel=h.None}return e.prototype.disable=function(){this.logLevel=h.None},e.prototype.enable=function(e){void 0===e&&(e=h.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Verbose||console.log("".concat(f,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Warn||console.warn("".concat(f,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Error||console.error("".concat(f,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Debug||console.log("".concat(f,"[Debug]: ").concat(e.join(" ")))},e}(),m=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:d,logLevel:h.Warn,loggerProvider:new p,offline:!1,optOut:!1,serverUrl:u,serverZone:"US",useBatch:!1}},y=function(){function e(e){var t,n,i,r;this._optOut=!1;var s=m();this.apiKey=e.apiKey,this.flushIntervalMillis=null!==(t=e.flushIntervalMillis)&&void 0!==t?t:s.flushIntervalMillis,this.flushMaxRetries=e.flushMaxRetries||s.flushMaxRetries,this.flushQueueSize=e.flushQueueSize||s.flushQueueSize,this.instanceName=e.instanceName||s.instanceName,this.loggerProvider=e.loggerProvider||s.loggerProvider,this.logLevel=null!==(n=e.logLevel)&&void 0!==n?n:s.logLevel,this.minIdLength=e.minIdLength,this.plan=e.plan,this.ingestionMetadata=e.ingestionMetadata,this.offline=void 0!==e.offline?e.offline:s.offline,this.optOut=null!==(i=e.optOut)&&void 0!==i?i:s.optOut,this.serverUrl=e.serverUrl,this.serverZone=e.serverZone||s.serverZone,this.storageProvider=e.storageProvider,this.transportProvider=e.transportProvider,this.useBatch=null!==(r=e.useBatch)&&void 0!==r?r:s.useBatch,this.loggerProvider.enable(this.logLevel);var o=b(e.serverUrl,e.serverZone,e.useBatch);this.serverZone=o.serverZone,this.serverUrl=o.serverUrl}return Object.defineProperty(e.prototype,"optOut",{get:function(){return this._optOut},set:function(e){this._optOut=e},enumerable:!1,configurable:!0}),e}(),S=function(e,t){return"EU"===e?t?"https://api.eu.amplitude.com/batch":"https://api.eu.amplitude.com/2/httpapi":t?"https://api2.amplitude.com/batch":u},b=function(e,t,n){if(void 0===e&&(e=""),void 0===t&&(t=m().serverZone),void 0===n&&(n=m().useBatch),e)return{serverUrl:e,serverZone:void 0};var i=["US","EU"].includes(t)?t:m().serverZone;return{serverZone:i,serverUrl:S(i,n)}},I=function(){function e(){}return e.prototype.getApplicationContext=function(){return{versionName:this.versionName,language:w(),platform:"Web",os:void 0,deviceModel:void 0}},e}(),w=function(){return"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||""},C=function(){function e(){this.queue=[]}return e.prototype.logEvent=function(e){this.receiver?this.receiver(e):this.queue.length<512&&this.queue.push(e)},e.prototype.setEventReceiver=function(e){this.receiver=e,this.queue.length>0&&(this.queue.forEach((function(t){e(t)})),this.queue=[])},e}(),E=function(){return E=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},E.apply(this,arguments)};function P(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function T(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var i,r,s=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(i=s.next()).done;)o.push(i.value)}catch(e){r={error:e}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return o}"function"==typeof SuppressedError&&SuppressedError;var _=function(e,t){var n,i,r=typeof e;if(r!==typeof t)return!1;try{for(var s=P(["string","number","boolean","undefined"]),o=s.next();!o.done;o=s.next()){if(o.value===r)return e===t}}catch(e){n={error:e}}finally{try{o&&!o.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}if(null==e&&null==t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;var a=Array.isArray(e),l=Array.isArray(t);if(a!==l)return!1;if(!a||!l){var c=Object.keys(e).sort(),d=Object.keys(t).sort();if(!_(c,d))return!1;var u=!0;return Object.keys(e).forEach((function(n){_(e[n],t[n])||(u=!1)})),u}for(var h=0;h<e.length;h++)if(!_(e[h],t[h]))return!1;return!0};Object.entries||(Object.entries=function(e){for(var t=Object.keys(e),n=t.length,i=new Array(n);n--;)i[n]=[t[n],e[t[n]]];return i});var R,k=function(){function e(){this.identity={userProperties:{}},this.listeners=new Set}return e.prototype.editIdentity=function(){var e=this,t=E({},this.identity.userProperties),n=E(E({},this.identity),{userProperties:t});return{setUserId:function(e){return n.userId=e,this},setDeviceId:function(e){return n.deviceId=e,this},setUserProperties:function(e){return n.userProperties=e,this},setOptOut:function(e){return n.optOut=e,this},updateUserProperties:function(e){var t,i,r,s,o,a,l=n.userProperties||{};try{for(var c=P(Object.entries(e)),d=c.next();!d.done;d=c.next()){var u=T(d.value,2),h=u[0],g=u[1];switch(h){case"$set":try{for(var v=(r=void 0,P(Object.entries(g))),f=v.next();!f.done;f=v.next()){var p=T(f.value,2),m=p[0],y=p[1];l[m]=y}}catch(e){r={error:e}}finally{try{f&&!f.done&&(s=v.return)&&s.call(v)}finally{if(r)throw r.error}}break;case"$unset":try{for(var S=(o=void 0,P(Object.keys(g))),b=S.next();!b.done;b=S.next()){delete l[m=b.value]}}catch(e){o={error:e}}finally{try{b&&!b.done&&(a=S.return)&&a.call(S)}finally{if(o)throw o.error}}break;case"$clearAll":l={}}}}catch(e){t={error:e}}finally{try{d&&!d.done&&(i=c.return)&&i.call(c)}finally{if(t)throw t.error}}return n.userProperties=l,this},commit:function(){return e.setIdentity(n),this}}},e.prototype.getIdentity=function(){return E({},this.identity)},e.prototype.setIdentity=function(e){var t=E({},this.identity);this.identity=E({},e),_(t,this.identity)||this.listeners.forEach((function(t){t(e)}))},e.prototype.addIdentityListener=function(e){this.listeners.add(e)},e.prototype.removeIdentityListener=function(e){this.listeners.delete(e)},e}(),O="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self,x=function(){function e(){this.identityStore=new k,this.eventBridge=new C,this.applicationContextProvider=new I}return e.getInstance=function(t){return O.analyticsConnectorInstances||(O.analyticsConnectorInstances={}),O.analyticsConnectorInstances[t]||(O.analyticsConnectorInstances[t]=new e),O.analyticsConnectorInstances[t]},e}(),M=function(e,t,n,i,r){return void 0===r&&(r=null),function(){for(var s=[],o=0;o<arguments.length;o++)s[o]=arguments[o];var a=n(),l=a.logger,c=a.logLevel;if(c&&c<h.Debug||!c||!l)return e.apply(r,s);var d,u={type:"invoke public method",name:t,args:s,stacktrace:(d=1,void 0===d&&(d=0),((new Error).stack||"").split("\n").slice(2+d).map((function(e){return e.trim()}))),time:{start:(new Date).toISOString()},states:{}};i&&u.states&&(u.states.before=i());var g=e.apply(r,s);return g&&g.promise?g.promise.then((function(){i&&u.states&&(u.states.after=i()),u.time&&(u.time.end=(new Date).toISOString()),l.debug(JSON.stringify(u,null,2))})):(i&&u.states&&(u.states.after=i()),u.time&&(u.time.end=(new Date).toISOString()),l.debug(JSON.stringify(u,null,2))),g}},L=function(){function e(){}return e.prototype.send=function(e,t){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,n,i,r,s,o,a,c,d,u,h,g,v,f,p,m,y,S,b,I,w,C;if("object"!=typeof e)return null;var E=e.code||0,P=this.buildStatus(E);switch(P){case l.Success:return{status:P,statusCode:E,body:{eventsIngested:null!==(t=e.events_ingested)&&void 0!==t?t:0,payloadSizeBytes:null!==(n=e.payload_size_bytes)&&void 0!==n?n:0,serverUploadTime:null!==(i=e.server_upload_time)&&void 0!==i?i:0}};case l.Invalid:return{status:P,statusCode:E,body:{error:null!==(r=e.error)&&void 0!==r?r:"",missingField:null!==(s=e.missing_field)&&void 0!==s?s:"",eventsWithInvalidFields:null!==(o=e.events_with_invalid_fields)&&void 0!==o?o:{},eventsWithMissingFields:null!==(a=e.events_with_missing_fields)&&void 0!==a?a:{},eventsWithInvalidIdLengths:null!==(c=e.events_with_invalid_id_lengths)&&void 0!==c?c:{},epsThreshold:null!==(d=e.eps_threshold)&&void 0!==d?d:0,exceededDailyQuotaDevices:null!==(u=e.exceeded_daily_quota_devices)&&void 0!==u?u:{},silencedDevices:null!==(h=e.silenced_devices)&&void 0!==h?h:[],silencedEvents:null!==(g=e.silenced_events)&&void 0!==g?g:[],throttledDevices:null!==(v=e.throttled_devices)&&void 0!==v?v:{},throttledEvents:null!==(f=e.throttled_events)&&void 0!==f?f:[]}};case l.PayloadTooLarge:return{status:P,statusCode:E,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case l.RateLimit:return{status:P,statusCode:E,body:{error:null!==(m=e.error)&&void 0!==m?m:"",epsThreshold:null!==(y=e.eps_threshold)&&void 0!==y?y:0,throttledDevices:null!==(S=e.throttled_devices)&&void 0!==S?S:{},throttledUsers:null!==(b=e.throttled_users)&&void 0!==b?b:{},exceededDailyQuotaDevices:null!==(I=e.exceeded_daily_quota_devices)&&void 0!==I?I:{},exceededDailyQuotaUsers:null!==(w=e.exceeded_daily_quota_users)&&void 0!==w?w:{},throttledEvents:null!==(C=e.throttled_events)&&void 0!==C?C:[]}};case l.Timeout:default:return{status:P,statusCode:E}}},e.prototype.buildStatus=function(e){return e>=200&&e<300?l.Success:429===e?l.RateLimit:413===e?l.PayloadTooLarge:408===e?l.Timeout:e>=400&&e<500?l.Invalid:e>=500?l.Failed:l.Unknown},e}(),q=function(i){function r(){return null!==i&&i.apply(this,arguments)||this}return e(r,i),r.prototype.send=function(e,i){return t(this,void 0,void 0,(function(){var t,r,s;return n(this,(function(n){switch(n.label){case 0:if("undefined"==typeof fetch)throw new Error("FetchTransport is not supported");return t={headers:{"Content-Type":"application/json",Accept:"*/*"},body:JSON.stringify(i),method:"POST"},[4,fetch(e,t)];case 1:return[4,(r=n.sent()).text()];case 2:s=n.sent();try{return[2,this.buildResponse(JSON.parse(s))]}catch(e){return[2,this.buildResponse({code:r.status})]}return[2]}}))}))},r}(L);!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(R||(R={}));const D="[Amplitude]",N=`${D} Session Replay ID`,$=R.US,j={enabled:!0},U=`${D} Session Replay Debug`,F="amp-mask";var A;!function(e){e.GET_SR_PROPS="get-sr-props",e.DEBUG_INFO="debug-info",e.FETCH_REQUEST="fetch-request",e.METADATA="metadata",e.TARGETING_DECISION="targeting-decision"}(A||(A={}));class B{constructor(e){this.logger=e,this.log=this.getSafeMethod("log"),this.warn=this.getSafeMethod("warn"),this.error=this.getSafeMethod("error"),this.debug=this.getSafeMethod("debug")}getSafeMethod(e){var t;if(!this.logger)return()=>{};const n=this.logger[e];if("function"==typeof n){return(null!==(t=n.__rrweb_original__)&&void 0!==t?t:n).bind(this.logger)}return()=>{}}enable(e){this.logger.enable(e)}disable(){this.logger.disable()}}const K="medium";const W=(e,t,n)=>{switch(t){case"light":{if("input"!==e)return!0;const t=n?function(e){const t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?t.toLowerCase():null}(n):"";return!!t&&(!!["password","hidden","email","tel"].includes(t)||!!n.autocomplete.startsWith("cc-"))}case"medium":case"conservative":return!0;default:return W(e,K,n)}},z=(e,t)=>(n,i)=>((e,t={defaultMaskLevel:K},n)=>{var i,r,s;if(n){if(n.closest("."+F))return!0;const e=(null!==(i=t.maskSelector)&&void 0!==i?i:[]).some((e=>n.closest(e)));if(e)return!0;if(n.closest(".amp-unmask"))return!1;const s=(null!==(r=t.unmaskSelector)&&void 0!==r?r:[]).some((e=>n.closest(e)));if(s)return!1}return W(e,null!==(s=t.defaultMaskLevel)&&void 0!==s?s:K,n)})(e,t,i)?n.replace(/[^\s]/g,"*"):n,G=function(e){let t=0;if(0===e.length)return t;for(let n=0;n<e.length;n++){t=(t<<5)-t+e.charCodeAt(n),t|=0}return t},Q=(e,t)=>t||(e===R.STAGING?"https://api-sr.stag2.amplitude.com/sessions/v2/track":e===R.EU?"https://api-sr.eu.amplitude.com/sessions/v2/track":"https://api-sr.amplitude.com/sessions/v2/track"),H=e=>{const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${t}$`)},J=(e,t)=>{for(const n of t){const t=H(n.selector);if(t.test(e))return e.replace(t,n.replacement)}return e},Z=()=>t(void 0,void 0,void 0,(function*(){try{const e=g();if(e){const{usage:t,quota:n,usageDetails:i}=yield e.navigator.storage.estimate(),r=t?Math.round(t/1024):0;return{totalStorageSize:r,percentOfQuota:t&&n?Math.round(1e3*(t/n+Number.EPSILON))/1e3:0,usageDetails:JSON.stringify(i)}}}catch(e){}return{totalStorageSize:0,percentOfQuota:0,usageDetails:""}})),X=e=>{const t=Object.assign({},e),{apiKey:n}=t;return t.apiKey=`****${n.substring(n.length-4)}`,t},V=()=>({flushMaxRetries:2,logLevel:h.Warn,loggerProvider:new p,transportProvider:new q});class Y extends y{constructor(e,t){var n,i,r,s,o;const a=V();super(Object.assign(Object.assign({transportProvider:a.transportProvider,loggerProvider:new B(t.loggerProvider||a.loggerProvider)},t),{apiKey:e})),this.flushMaxRetries=void 0!==t.flushMaxRetries&&t.flushMaxRetries<=a.flushMaxRetries?t.flushMaxRetries:a.flushMaxRetries,this.apiKey=e,this.sampleRate=t.sampleRate||0,this.serverZone=t.serverZone||$,this.configServerUrl=t.configServerUrl,this.trackServerUrl=t.trackServerUrl,this.shouldInlineStylesheet=t.shouldInlineStylesheet,this.version=t.version,this.performanceConfig=t.performanceConfig||j,this.storeType=null!==(n=t.storeType)&&void 0!==n?n:"idb",this.applyBackgroundColorToBlockedElements=null!==(i=t.applyBackgroundColorToBlockedElements)&&void 0!==i&&i,this.enableUrlChangePolling=null!==(r=t.enableUrlChangePolling)&&void 0!==r&&r,this.urlChangePollingInterval=null!==(s=t.urlChangePollingInterval)&&void 0!==s?s:1e3,this.captureDocumentTitle=null!==(o=t.captureDocumentTitle)&&void 0!==o&&o,t.privacyConfig&&(this.privacyConfig=t.privacyConfig),t.interactionConfig&&(this.interactionConfig=t.interactionConfig,this.interactionConfig.ugcFilterRules&&(e=>{if(!e.every((e=>"string"==typeof e.selector&&"string"==typeof e.replacement)))throw new Error("ugcFilterRules must be an array of objects with selector and replacement properties");if(!e.every((e=>{return"string"==typeof(t=e.selector)&&""!==t.trim()&&!!/^\/|^https?:\/\/[^\s]+$/.test(t);var t})))throw new Error("ugcFilterRules must be an array of objects with valid globs")})(this.interactionConfig.ugcFilterRules)),t.debugMode&&(this.debugMode=t.debugMode),t.experimental&&(this.experimental=t.experimental),t.omitElementTags&&(this.omitElementTags=t.omitElementTags)}}var ee,te,ne=(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))(ne||{}),ie=(e=>(e[e.MouseUp=0]="MouseUp",e[e.MouseDown=1]="MouseDown",e[e.Click=2]="Click",e[e.ContextMenu=3]="ContextMenu",e[e.DblClick=4]="DblClick",e[e.Focus=5]="Focus",e[e.Blur=6]="Blur",e[e.TouchStart=7]="TouchStart",e[e.TouchMove_Departed=8]="TouchMove_Departed",e[e.TouchEnd=9]="TouchEnd",e[e.TouchCancel=10]="TouchCancel",e))(ie||{});!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(ee||(ee={})),function(e){e.Unknown="unknown",e.Skipped="skipped",e.Success="success",e.RateLimit="rate_limit",e.PayloadTooLarge="payload_too_large",e.Invalid="invalid",e.Failed="failed",e.Timeout="Timeout",e.SystemError="SystemError"}(te||(te={}));var re=function(){function e(){}return e.prototype.send=function(e,t){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,n,i,r,s,o,a,l,c,d,u,h,g,v,f,p,m,y,S,b,I,w;if("object"!=typeof e)return null;var C=e.code||0,E=this.buildStatus(C);switch(E){case te.Success:return{status:E,statusCode:C,body:{eventsIngested:null!==(t=e.events_ingested)&&void 0!==t?t:0,payloadSizeBytes:null!==(n=e.payload_size_bytes)&&void 0!==n?n:0,serverUploadTime:null!==(i=e.server_upload_time)&&void 0!==i?i:0}};case te.Invalid:return{status:E,statusCode:C,body:{error:null!==(r=e.error)&&void 0!==r?r:"",missingField:null!==(s=e.missing_field)&&void 0!==s?s:"",eventsWithInvalidFields:null!==(o=e.events_with_invalid_fields)&&void 0!==o?o:{},eventsWithMissingFields:null!==(a=e.events_with_missing_fields)&&void 0!==a?a:{},eventsWithInvalidIdLengths:null!==(l=e.events_with_invalid_id_lengths)&&void 0!==l?l:{},epsThreshold:null!==(c=e.eps_threshold)&&void 0!==c?c:0,exceededDailyQuotaDevices:null!==(d=e.exceeded_daily_quota_devices)&&void 0!==d?d:{},silencedDevices:null!==(u=e.silenced_devices)&&void 0!==u?u:[],silencedEvents:null!==(h=e.silenced_events)&&void 0!==h?h:[],throttledDevices:null!==(g=e.throttled_devices)&&void 0!==g?g:{},throttledEvents:null!==(v=e.throttled_events)&&void 0!==v?v:[]}};case te.PayloadTooLarge:return{status:E,statusCode:C,body:{error:null!==(f=e.error)&&void 0!==f?f:""}};case te.RateLimit:return{status:E,statusCode:C,body:{error:null!==(p=e.error)&&void 0!==p?p:"",epsThreshold:null!==(m=e.eps_threshold)&&void 0!==m?m:0,throttledDevices:null!==(y=e.throttled_devices)&&void 0!==y?y:{},throttledUsers:null!==(S=e.throttled_users)&&void 0!==S?S:{},exceededDailyQuotaDevices:null!==(b=e.exceeded_daily_quota_devices)&&void 0!==b?b:{},exceededDailyQuotaUsers:null!==(I=e.exceeded_daily_quota_users)&&void 0!==I?I:{},throttledEvents:null!==(w=e.throttled_events)&&void 0!==w?w:[]}};case te.Timeout:default:return{status:E,statusCode:C}}},e.prototype.buildStatus=function(e){return e>=200&&e<300?te.Success:429===e?te.RateLimit:413===e?te.PayloadTooLarge:408===e?te.Timeout:e>=400&&e<500?te.Invalid:e>=500?te.Failed:te.Unknown},e}(),se="Remote config fetch rejected due to timeout after 5 seconds",oe="Unexpected error occurred",ae=function(){function e(e){var s=e.localConfig,o=e.configKeys,a=this;this.retryTimeout=1e3,this.attempts=0,this.sessionTargetingMatch=!1,this.metrics={},this.getRemoteNamespaceConfig=function(e,i){return t(a,void 0,void 0,(function(){var t,r,s;return n(this,(function(n){switch(n.label){case 0:return t=Date.now(),[4,this.fetchWithTimeout(i)];case 1:return(r=n.sent())&&(s=r.configs&&r.configs[e])?(this.metrics.fetchTimeAPISuccess=Date.now()-t,[2,s]):(this.metrics.fetchTimeAPIFail=Date.now()-t,[2,void 0])}}))}))},this.getRemoteConfig=function(e,i,r){return t(a,void 0,void 0,(function(){var t;return n(this,(function(n){switch(n.label){case 0:return[4,this.getRemoteNamespaceConfig(e,r)];case 1:return[2,null==(t=n.sent())?void 0:t[i]]}}))}))},this.fetchWithTimeout=function(e){return t(a,void 0,void 0,(function(){var t,i,r;return n(this,(function(n){switch(n.label){case 0:return t=new AbortController,i=setTimeout((function(){return t.abort()}),5e3),[4,this.fetchRemoteConfig(t.signal,e)];case 1:return r=n.sent(),clearTimeout(i),[2,r]}}))}))},this.fetchRemoteConfig=function(e,s){return t(a,void 0,void 0,(function(){var t,o,a,l,c,d,u,h,g,v,f,p;return n(this,(function(n){switch(n.label){case 0:if(s===this.lastFetchedSessionId&&this.attempts>=this.localConfig.flushMaxRetries)return[2,this.completeRequest({err:"Remote config fetch rejected due to exceeded retry count"})];if(e.aborted)return[2,this.completeRequest({err:se})];s!==this.lastFetchedSessionId&&(this.lastFetchedSessionId=s,this.attempts=0),n.label=1;case 1:n.trys.push([1,3,,4]),t=new URLSearchParams({api_key:this.localConfig.apiKey});try{for(o=i(this.configKeys),a=o.next();!a.done;a=o.next())l=a.value,t.append("config_keys",l)}catch(e){v={error:e}}finally{try{a&&!a.done&&(f=o.return)&&f.call(o)}finally{if(v)throw v.error}}return s&&t.set("session_id",String(s)),c={headers:{Accept:"*/*"},method:"GET"},d="".concat(this.getServerUrl(),"?").concat(t.toString()),this.attempts+=1,[4,fetch(d,r(r({},c),{signal:e}))];case 2:if(null===(u=n.sent()))return[2,this.completeRequest({err:oe})];switch((new re).buildStatus(u.status)){case te.Success:return this.attempts=0,[2,this.parseAndStoreConfig(u)];case te.Failed:return[2,this.retryFetch(e,s)];default:return[2,this.completeRequest({err:"Network error occurred, remote config fetch failed"})]}case 3:return h=n.sent(),g=h,e.aborted?[2,this.completeRequest({err:se})]:[2,this.completeRequest({err:null!==(p=g.message)&&void 0!==p?p:oe})];case 4:return[2]}}))}))},this.retryFetch=function(e,i){return t(a,void 0,void 0,(function(){var t=this;return n(this,(function(n){switch(n.label){case 0:return[4,new Promise((function(e){return setTimeout(e,t.attempts*t.retryTimeout)}))];case 1:return n.sent(),[2,this.fetchRemoteConfig(e,i)]}}))}))},this.parseAndStoreConfig=function(e){return t(a,void 0,void 0,(function(){var t;return n(this,(function(n){switch(n.label){case 0:return[4,e.json()];case 1:return t=n.sent(),this.completeRequest({success:"Remote config successfully fetched"}),[2,t]}}))}))},this.localConfig=s,this.configKeys=o}return e.prototype.getServerUrl=function(){return this.localConfig.configServerUrl?this.localConfig.configServerUrl:this.localConfig.serverZone===ee.STAGING?"https://sr-client-cfg.stag2.amplitude.com/config":this.localConfig.serverZone===ee.EU?"https://sr-client-cfg.eu.amplitude.com/config":"https://sr-client-cfg.amplitude.com/config"},e.prototype.completeRequest=function(e){var t=e.err,n=e.success;if(t)throw new Error(t);n&&this.localConfig.loggerProvider.log(n)},e}(),le=function(e){var i=e.localConfig,r=e.configKeys;return t(void 0,void 0,void 0,(function(){return n(this,(function(e){return[2,new ae({localConfig:i,configKeys:r})]}))}))};class ce{constructor(e,t){this.localConfig=t,this.remoteConfigFetch=e}generateJoinedConfig(e){var n,i,r,s;return t(this,void 0,void 0,(function*(){const t=Object.assign({},this.localConfig);let o;t.optOut=this.localConfig.optOut,t.captureEnabled=!0;try{const i=yield this.remoteConfigFetch.getRemoteNamespaceConfig("sessionReplay",e);if(i){const e=i.sr_sampling_config,r=i.sr_privacy_config,s=i.sr_targeting_config,a=null===(n=t.interactionConfig)||void 0===n?void 0:n.ugcFilterRules;t.interactionConfig=i.sr_interaction_config,t.interactionConfig&&a&&(t.interactionConfig.ugcFilterRules=a),t.loggingConfig=i.sr_logging_config,(e||r||s)&&(o={},e&&(o.sr_sampling_config=e),r&&(o.sr_privacy_config=r),s&&(o.sr_targeting_config=s))}}catch(e){const n=e;this.localConfig.loggerProvider.warn(n.message),t.captureEnabled=!1}if(!o)return{localConfig:this.localConfig,joinedConfig:t,remoteConfig:o};const{sr_sampling_config:a,sr_privacy_config:l,sr_targeting_config:c}=o;if(a&&Object.keys(a).length>0?(Object.prototype.hasOwnProperty.call(a,"capture_enabled")?t.captureEnabled=a.capture_enabled:t.captureEnabled=!1,Object.prototype.hasOwnProperty.call(a,"sample_rate")&&(t.sampleRate=a.sample_rate)):(t.captureEnabled=!0,this.localConfig.loggerProvider.debug("Remote config successfully fetched, but no values set for project, Session Replay capture enabled.")),l){const e=null!==(i=t.privacyConfig)&&void 0!==i?i:{},n={defaultMaskLevel:null!==(s=null!==(r=l.defaultMaskLevel)&&void 0!==r?r:e.defaultMaskLevel)&&void 0!==s?s:"medium",blockSelector:[],maskSelector:[],unmaskSelector:[]},o=e=>{var t,n,i;const r={};"string"==typeof e.blockSelector&&(e.blockSelector=[e.blockSelector]);for(const n of null!==(t=e.blockSelector)&&void 0!==t?t:[])r[n]="block";for(const t of null!==(n=e.maskSelector)&&void 0!==n?n:[])r[t]="mask";for(const t of null!==(i=e.unmaskSelector)&&void 0!==i?i:[])r[t]="unmask";return r},a=Object.assign(Object.assign({},o(e)),o(l));for(const[e,t]of Object.entries(a))"mask"===t?n.maskSelector.push(e):"block"===t?n.blockSelector.push(e):"unmask"===t&&n.unmaskSelector.push(e);t.privacyConfig=((e,t)=>{const n=document.createDocumentFragment(),i=(e=[])=>{if("string"==typeof e&&(e=[e]),e=e.filter((e=>{try{n.querySelector(e)}catch(n){return t.warn(`[session-replay-browser] omitting selector "${e}" because it is invalid`),!1}return!0})),0!==e.length)return e};return e.blockSelector=i(e.blockSelector),e.maskSelector=i(e.maskSelector),e.unmaskSelector=i(e.unmaskSelector),e})(n,this.localConfig.loggerProvider)}return c&&Object.keys(c).length>0&&(t.targetingConfig=c),this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:X(t)},null,2)),{localConfig:this.localConfig,joinedConfig:t,remoteConfig:o}}))}}var de=Uint8Array,ue=Uint16Array,he=Uint32Array,ge=new de([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ve=new de([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),fe=new de([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),pe=function(e,t){for(var n=new ue(31),i=0;i<31;++i)n[i]=t+=1<<e[i-1];var r=new he(n[30]);for(i=1;i<30;++i)for(var s=n[i];s<n[i+1];++s)r[s]=s-n[i]<<5|i;return[n,r]},me=pe(ge,2),ye=me[0],Se=me[1];ye[28]=258,Se[258]=28;for(var be=pe(ve,0)[1],Ie=new ue(32768),we=0;we<32768;++we){var Ce=(43690&we)>>>1|(21845&we)<<1;Ce=(61680&(Ce=(52428&Ce)>>>2|(13107&Ce)<<2))>>>4|(3855&Ce)<<4,Ie[we]=((65280&Ce)>>>8|(255&Ce)<<8)>>>1}var Ee=function(e,t,n){for(var i=e.length,r=0,s=new ue(t);r<i;++r)++s[e[r]-1];var o,a=new ue(t);for(r=0;r<t;++r)a[r]=a[r-1]+s[r-1]<<1;if(n){o=new ue(1<<t);var l=15-t;for(r=0;r<i;++r)if(e[r])for(var c=r<<4|e[r],d=t-e[r],u=a[e[r]-1]++<<d,h=u|(1<<d)-1;u<=h;++u)o[Ie[u]>>>l]=c}else for(o=new ue(i),r=0;r<i;++r)o[r]=Ie[a[e[r]-1]++]>>>15-e[r];return o},Pe=new de(288);for(we=0;we<144;++we)Pe[we]=8;for(we=144;we<256;++we)Pe[we]=9;for(we=256;we<280;++we)Pe[we]=7;for(we=280;we<288;++we)Pe[we]=8;var Te=new de(32);for(we=0;we<32;++we)Te[we]=5;var _e=Ee(Pe,9,0),Re=Ee(Te,5,0),ke=function(e){return(e/8|0)+(7&e&&1)},Oe=function(e,t,n){(null==n||n>e.length)&&(n=e.length);var i=new(e instanceof ue?ue:e instanceof he?he:de)(n-t);return i.set(e.subarray(t,n)),i},xe=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>>8},Me=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>>8,e[i+2]|=n>>>16},Le=function(e,t){for(var n=[],i=0;i<e.length;++i)e[i]&&n.push({s:i,f:e[i]});var r=n.length,s=n.slice();if(!r)return[new de(0),0];if(1==r){var o=new de(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(e,t){return e.f-t.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],c=0,d=1,u=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};d!=r-1;)a=n[n[c].f<n[u].f?c++:u++],l=n[c!=d&&n[c].f<n[u].f?c++:u++],n[d++]={s:-1,f:a.f+l.f,l:a,r:l};var h=s[0].s;for(i=1;i<r;++i)s[i].s>h&&(h=s[i].s);var g=new ue(h+1),v=qe(n[d-1],g,0);if(v>t){i=0;var f=0,p=v-t,m=1<<p;for(s.sort((function(e,t){return g[t.s]-g[e.s]||e.f-t.f}));i<r;++i){var y=s[i].s;if(!(g[y]>t))break;f+=m-(1<<v-g[y]),g[y]=t}for(f>>>=p;f>0;){var S=s[i].s;g[S]<t?f-=1<<t-g[S]++-1:++i}for(;i>=0&&f;--i){var b=s[i].s;g[b]==t&&(--g[b],++f)}v=t}return[new de(g),v]},qe=function(e,t,n){return-1==e.s?Math.max(qe(e.l,t,n+1),qe(e.r,t,n+1)):t[e.s]=n},De=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new ue(++t),i=0,r=e[0],s=1,o=function(e){n[i++]=e},a=1;a<=t;++a)if(e[a]==r&&a!=t)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=e[a]}return[n.subarray(0,i),t]},Ne=function(e,t){for(var n=0,i=0;i<t.length;++i)n+=e[i]*t[i];return n},$e=function(e,t,n){var i=n.length,r=ke(t+2);e[r]=255&i,e[r+1]=i>>>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var s=0;s<i;++s)e[r+s+4]=n[s];return 8*(r+4+i)},je=function(e,t,n,i,r,s,o,a,l,c,d){xe(t,d++,n),++r[256];for(var u=Le(r,15),h=u[0],g=u[1],v=Le(s,15),f=v[0],p=v[1],m=De(h),y=m[0],S=m[1],b=De(f),I=b[0],w=b[1],C=new ue(19),E=0;E<y.length;++E)C[31&y[E]]++;for(E=0;E<I.length;++E)C[31&I[E]]++;for(var P=Le(C,7),T=P[0],_=P[1],R=19;R>4&&!T[fe[R-1]];--R);var k,O,x,M,L=c+5<<3,q=Ne(r,Pe)+Ne(s,Te)+o,D=Ne(r,h)+Ne(s,f)+o+14+3*R+Ne(C,T)+(2*C[16]+3*C[17]+7*C[18]);if(L<=q&&L<=D)return $e(t,d,e.subarray(l,l+c));if(xe(t,d,1+(D<q)),d+=2,D<q){k=Ee(h,g,0),O=h,x=Ee(f,p,0),M=f;var N=Ee(T,_,0);xe(t,d,S-257),xe(t,d+5,w-1),xe(t,d+10,R-4),d+=14;for(E=0;E<R;++E)xe(t,d+3*E,T[fe[E]]);d+=3*R;for(var $=[y,I],j=0;j<2;++j){var U=$[j];for(E=0;E<U.length;++E){var F=31&U[E];xe(t,d,N[F]),d+=T[F],F>15&&(xe(t,d,U[E]>>>5&127),d+=U[E]>>>12)}}}else k=_e,O=Pe,x=Re,M=Te;for(E=0;E<a;++E)if(i[E]>255){F=i[E]>>>18&31;Me(t,d,k[F+257]),d+=O[F+257],F>7&&(xe(t,d,i[E]>>>23&31),d+=ge[F]);var A=31&i[E];Me(t,d,x[A]),d+=M[A],A>3&&(Me(t,d,i[E]>>>5&8191),d+=ve[A])}else Me(t,d,k[i[E]]),d+=O[i[E]];return Me(t,d,k[256]),d+O[256]},Ue=new he([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Fe=function(e,t,n,i,r){return function(e,t,n,i,r,s){var o=e.length,a=new de(i+o+5*(1+Math.floor(o/7e3))+r),l=a.subarray(i,a.length-r),c=0;if(!t||o<8)for(var d=0;d<=o;d+=65535){var u=d+65535;u<o?c=$e(l,c,e.subarray(d,u)):(l[d]=s,c=$e(l,c,e.subarray(d,o)))}else{for(var h=Ue[t-1],g=h>>>13,v=8191&h,f=(1<<n)-1,p=new ue(32768),m=new ue(f+1),y=Math.ceil(n/3),S=2*y,b=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<S)&f},I=new he(25e3),w=new ue(288),C=new ue(32),E=0,P=0,T=(d=0,0),_=0,R=0;d<o;++d){var k=b(d),O=32767&d,x=m[k];if(p[O]=x,m[k]=O,_<=d){var M=o-d;if((E>7e3||T>24576)&&M>423){c=je(e,l,0,I,w,C,P,T,R,d-R,c),T=E=P=0,R=d;for(var L=0;L<286;++L)w[L]=0;for(L=0;L<30;++L)C[L]=0}var q=2,D=0,N=v,$=O-x&32767;if(M>2&&k==b(d-$))for(var j=Math.min(g,M)-1,U=Math.min(32767,d),F=Math.min(258,M);$<=U&&--N&&O!=x;){if(e[d+q]==e[d+q-$]){for(var A=0;A<F&&e[d+A]==e[d+A-$];++A);if(A>q){if(q=A,D=$,A>j)break;var B=Math.min($,A-2),K=0;for(L=0;L<B;++L){var W=d-$+L+32768&32767,z=W-p[W]+32768&32767;z>K&&(K=z,x=W)}}}$+=(O=x)-(x=p[O])+32768&32767}if(D){I[T++]=268435456|Se[q]<<18|be[D];var G=31&Se[q],Q=31&be[D];P+=ge[G]+ve[Q],++w[257+G],++C[Q],_=d+q,++E}else I[T++]=e[d],++w[e[d]]}}c=je(e,l,s,I,w,C,P,T,R,d-R,c)}return Oe(a,0,i+ke(c)+r)}(e,null==t.level?6:t.level,null==t.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,n,i,!r)};function Ae(e,t){void 0===t&&(t={});var n=function(){var e=1,t=0;return{p:function(n){for(var i=e,r=t,s=n.length,o=0;o!=s;){for(var a=Math.min(o+5552,s);o<a;++o)r+=i+=n[o];i%=65521,r%=65521}e=i,t=r},d:function(){return(e>>>8<<16|(255&t)<<8|t>>>8)+2*((255&e)<<23)}}}();n.p(e);var i,r,s,o=Fe(e,t,2,4);return i=o,r=t.level,s=0==r?0:r<6?1:9==r?3:2,i[0]=120,i[1]=s<<6|(s?32-2*s:1),function(e,t,n){for(;n;++t)e[t]=n,n>>>=8}(o,o.length-4,n.d()),o}const Be=e=>{const t={...e,v:"v1"};return function(e,t){var n="";if(!t&&"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);for(var i=0;i<e.length;){var r=e[i++];r<128||t?n+=String.fromCharCode(r):r<224?n+=String.fromCharCode((31&r)<<6|63&e[i++]):r<240?n+=String.fromCharCode((15&r)<<12|(63&e[i++])<<6|63&e[i++]):(r=((15&r)<<18|(63&e[i++])<<12|(63&e[i++])<<6|63&e[i++])-65536,n+=String.fromCharCode(55296|r>>10,56320|1023&r))}return n}(Ae(function(e,t){var n=e.length;if(!t&&"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var i=new de(e.length+(e.length>>>1)),r=0,s=function(e){i[r++]=e},o=0;o<n;++o){if(r+5>i.length){var a=new de(r+8+(n-o<<1));a.set(i),i=a}var l=e.charCodeAt(o);l<128||t?s(l):l<2048?(s(192|l>>>6),s(128|63&l)):l>55295&&l<57344?(s(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++o))>>>18),s(128|l>>>12&63),s(128|l>>>6&63),s(128|63&l)):(s(224|l>>>12),s(128|l>>>6&63),s(128|63&l))}return Oe(i,0,r)}(JSON.stringify(t))),!0)};class Ke{constructor(e,t,n,i){var r;this.taskQueue=[],this.isProcessing=!1,this.compressEvent=e=>{const t=Be(e);return JSON.stringify(t)},this.addCompressedEventToManager=(e,t)=>{this.eventsManager&&this.deviceId&&this.eventsManager.addEvent({event:{type:"replay",data:e},sessionId:t,deviceId:this.deviceId})},this.addCompressedEvent=(e,t)=>{if(this.worker)try{this.worker.postMessage({event:e,sessionId:t})}catch(n){"DataCloneError"===n.name?this.worker.postMessage(JSON.stringify({event:e,sessionId:t})):this.config.loggerProvider.warn("Unexpected error while posting message to worker:",n)}else{const n=this.compressEvent(e);this.addCompressedEventToManager(n,t)}},this.terminate=()=>{var e;null===(e=this.worker)||void 0===e||e.terminate()};const s=g();if(this.canUseIdleCallback=s&&"requestIdleCallback"in s,this.eventsManager=e,this.config=t,this.deviceId=n,this.timeout=(null===(r=t.performanceConfig)||void 0===r?void 0:r.timeout)||2e3,i){t.loggerProvider.log("[Experimental] Enabling web worker for compression");const e=new Worker(URL.createObjectURL(new Blob([i],{type:"application/javascript"})));e.onerror=e=>{t.loggerProvider.error(e)},e.onmessage=e=>{const{compressedEvent:t,sessionId:n}=e.data;this.addCompressedEventToManager(t,n)},this.worker=e}}scheduleIdleProcessing(){this.isProcessing||(this.isProcessing=!0,requestIdleCallback((e=>{this.processQueue(e)}),{timeout:this.timeout}))}enqueueEvent(e,t){var n;this.canUseIdleCallback&&(null===(n=this.config.performanceConfig)||void 0===n?void 0:n.enabled)?(this.config.loggerProvider.debug("Enqueuing event for processing during idle time."),this.taskQueue.push({event:e,sessionId:t}),this.scheduleIdleProcessing()):(this.config.loggerProvider.debug("Processing event without idle callback."),this.addCompressedEvent(e,t))}processQueue(e){for(;this.taskQueue.length>0&&(e.timeRemaining()>0||e.didTimeout);){const e=this.taskQueue.shift();if(e){const{event:t,sessionId:n}=e;this.addCompressedEvent(t,n)}}this.taskQueue.length>0?requestIdleCallback((e=>{this.processQueue(e)}),{timeout:this.timeout}):this.isProcessing=!1}}const We="Failed to store session replay events in IndexedDB",ze="1.29.0-fixsdk-init.0";class Ge{constructor({trackServerUrl:e,loggerProvider:t,payloadBatcher:n}){this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.loggerProvider=t,this.payloadBatcher=n||(e=>e),this.trackServerUrl=e}sendEventsList(e){this.addToQueue(Object.assign(Object.assign({},e),{attempts:0,timeout:0}))}addToQueue(...e){e.filter((e=>e.attempts<(e.flushMaxRetries||0)?(e.attempts+=1,!0):(this.completeRequest({context:e,err:"Session replay event batch rejected due to exceeded retry count"}),!1))).forEach((e=>{this.queue=this.queue.concat(e),0!==e.timeout?setTimeout((()=>{e.timeout=0,this.schedule(0)}),e.timeout):this.schedule(0)}))}schedule(e){this.scheduled||(this.scheduled=setTimeout((()=>{this.flush(!0).then((()=>{this.queue.length>0&&this.schedule(e)}))}),e))}flush(e=!1){return t(this,void 0,void 0,(function*(){const t=[],n=[];this.queue.forEach((e=>0===e.timeout?t.push(e):n.push(e))),this.queue=n,this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null),yield Promise.all(t.map((t=>this.send(t,e))))}))}send(e,n=!0){var i,r;return t(this,void 0,void 0,(function*(){const t=e.apiKey;if(!t)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing api key"});const s=e.deviceId;if(!s)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing device ID"});const o=(()=>{const e=g();return(null==e?void 0:e.location)?e.location.href:""})(),a=ze,l=e.sampleRate,c=new URLSearchParams({device_id:s,session_id:`${e.sessionId}`,type:`${e.type}`}),d=`${(null===(i=e.version)||void 0===i?void 0:i.type)||"standalone"}/${(null===(r=e.version)||void 0===r?void 0:r.version)||a}`,u=this.payloadBatcher({version:1,events:e.events});if(0!==u.events.length)try{const i={headers:{"Content-Type":"application/json",Accept:"*/*",Authorization:`Bearer ${t}`,"X-Client-Version":a,"X-Client-Library":d,"X-Client-Url":o.substring(0,1e3),"X-Client-Sample-Rate":`${l}`},body:JSON.stringify(u),method:"POST"},r=`${Q(e.serverZone,this.trackServerUrl)}?${c.toString()}`,s=yield fetch(r,i);if(null===s)return void this.completeRequest({context:e,err:"Unexpected error occurred"});if(n)this.handleReponse(s.status,e);else{let t="";try{t=JSON.stringify(s.body,null,2)}catch(e){}this.completeRequest({context:e,success:`${s.status}: ${t}`})}}catch(t){this.completeRequest({context:e,err:t})}else this.completeRequest({context:e})}))}handleReponse(e,t){switch((new L).buildStatus(e)){case l.Success:this.handleSuccessResponse(t);break;case l.Failed:this.handleOtherResponse(t);break;default:this.completeRequest({context:t,err:"Network error occurred, event batch rejected"})}}handleSuccessResponse(e){const t=Math.round(new Blob(e.events).size/1024);this.completeRequest({context:e,success:`Session replay event batch tracked successfully for session id ${e.sessionId}, size of events: ${t} KB`})}handleOtherResponse(e){this.addToQueue(Object.assign(Object.assign({},e),{timeout:e.attempts*this.retryTimeout}))}completeRequest({context:e,err:t,success:n}){e.onComplete(),t?this.loggerProvider.warn(t):n&&this.loggerProvider.log(n)}}class Qe{get timeAtLastSplit(){return this._timeAtLastSplit}constructor(e){var t,n,i;this.minInterval=500,this.maxInterval=1e4,this.maxPersistedEventsSize=1e6,this.interval=this.minInterval,this._timeAtLastSplit=Date.now(),this.shouldSplitEventsList=(e,t)=>{const n=this.getStringSize(t);return this.getEventsArraySize(e)+n>=this.maxPersistedEventsSize||!!(Date.now()-this.timeAtLastSplit>this.interval&&e.length)&&(this.interval=Math.min(this.maxInterval,this.interval+this.minInterval),this._timeAtLastSplit=Date.now(),!0)},this.loggerProvider=e.loggerProvider,this.minInterval=null!==(t=e.minInterval)&&void 0!==t?t:this.minInterval,this.maxInterval=null!==(n=e.maxInterval)&&void 0!==n?n:this.maxInterval,this.maxPersistedEventsSize=null!==(i=e.maxPersistedEventsSize)&&void 0!==i?i:this.maxPersistedEventsSize}getStringSize(e){return e.length}getEventsArraySize(e){let t=0;for(const n of e)t+=this.getStringSize(n);return t+(2+Math.max(0,e.length-1)+2*e.length)}}var He;!function(e){e.RECORDING="recording",e.SENT="sent"}(He||(He={}));const Je="sessionCurrentSequence",Ze="sequencesToSend",Xe=e=>t(void 0,void 0,void 0,(function*(){for(;e.length>0;){const t=10,n=e.splice(0,t);yield Promise.all(n)}})),Ve=e=>{let t,n;return e.objectStoreNames.contains(Je)||(n=e.createObjectStore(Je,{keyPath:"sessionId"})),e.objectStoreNames.contains(Ze)||(t=e.createObjectStore(Ze,{keyPath:"sequenceId",autoIncrement:!0}),t.createIndex("sessionId","sessionId")),{sequencesStore:t,currentSequenceStore:n}};class Ye extends Qe{constructor(e){super(e),this.getSequencesToSend=()=>t(this,void 0,void 0,(function*(){try{const e=[];let t=yield this.db.transaction("sequencesToSend").store.openCursor();for(;t;){const{sessionId:n,events:i}=t.value;e.push({events:i,sequenceId:t.key,sessionId:n}),t=yield t.continue()}return e}catch(e){this.loggerProvider.warn(`${We}: ${e}`)}})),this.storeCurrentSequence=e=>t(this,void 0,void 0,(function*(){try{const t=yield this.db.get(Je,e);if(!t)return;const n=yield this.db.put(Ze,{sessionId:e,events:t.events});return yield this.db.put(Je,{sessionId:e,events:[]}),Object.assign(Object.assign({},t),{sessionId:e,sequenceId:n})}catch(e){this.loggerProvider.warn(`${We}: ${e}`)}})),this.addEventToCurrentSequence=(e,n)=>t(this,void 0,void 0,(function*(){try{const t=this.db.transaction(Je,"readwrite"),i=yield t.store.get(e);if(!i)return void(yield t.store.put({sessionId:e,events:[n]}));let r;if(this.shouldSplitEventsList(i.events,n))r=i.events,yield t.store.put({sessionId:e,events:[n]});else{const r=i.events.concat(n);yield t.store.put({sessionId:e,events:r})}if(yield t.done,!r)return;const s=yield this.storeSendingEvents(e,r);if(!s)return;return{events:r,sessionId:e,sequenceId:s}}catch(e){this.loggerProvider.warn(`${We}: ${e}`)}})),this.storeSendingEvents=(e,n)=>t(this,void 0,void 0,(function*(){try{return yield this.db.put(Ze,{sessionId:e,events:n})}catch(e){this.loggerProvider.warn(`${We}: ${e}`)}})),this.cleanUpSessionEventsStore=(e,n)=>t(this,void 0,void 0,(function*(){if(n)try{yield this.db.delete(Ze,n)}catch(e){this.loggerProvider.warn(`${We}: ${e}`)}})),this.transitionFromKeyValStore=e=>t(this,void 0,void 0,(function*(){try{const n=yield function(){const e=g();return new Promise(((t,n)=>{if(!e)return n(new Error("Global scope not found"));if(!e.indexedDB)return n(new Error("Session Replay: cannot find indexedDB"));try{const i=e.indexedDB.open("keyval-store");i.onupgradeneeded=function(){1===i.result.version&&(i.result.close(),i.transaction&&i.transaction.abort(),e.indexedDB.deleteDatabase("keyval-store"),t())},i.onsuccess=function(){t(i.result)},i.onerror=function(){n(i.error)}}catch(e){n(e)}}))}();if(!n)return;const i=(e,n)=>t(this,void 0,void 0,(function*(){const i=n.sessionSequences,r=[];Object.keys(i).forEach((s=>{const o=parseInt(s,10),a=i[o];if(o===n.currentSequenceId){const n=a.events.map((n=>t(this,void 0,void 0,(function*(){return this.addEventToCurrentSequence(e,n)}))));r.push(...n)}else a.status!==He.SENT&&r.push(this.storeSendingEvents(e,a.events))})),yield Xe(r)})),r=`${c}_${this.apiKey.substring(0,10)}`;try{const s=n.transaction("keyval").objectStore("keyval").getAll(r),o=new Promise((n=>{s.onsuccess=r=>t(this,void 0,void 0,(function*(){const t=r&&r.target.result,s=t&&t[0];if(s){const t=[];Object.keys(s).forEach((n=>{const r=parseInt(n,10),o=s[r];if(e===r)t.push(i(r,o));else{const e=o.sessionSequences;Object.keys(e).forEach((n=>{const i=parseInt(n,10);e[i].status!==He.SENT&&t.push(this.storeSendingEvents(r,e[i].events))}))}})),yield Xe(t)}n()}))}));yield o;const a=g();a&&a.indexedDB.deleteDatabase("keyval-store")}catch(e){this.loggerProvider.warn(`Failed to transition session replay events from keyval to new store: ${e}`)}}catch(e){this.loggerProvider.warn(`Failed to access keyval store: ${e}. For more information, visit: https://www.docs.developers.amplitude.com/session-replay/sdks/standalone/#indexeddb-best-practices`)}})),this.apiKey=e.apiKey,this.db=e.db}static new(e,n,i){return t(this,void 0,void 0,(function*(){try{const r="replay"===e?"":`_${e}`,o=`${n.apiKey.substring(0,10)}_amp_session_replay_events${r}`,a=yield(e=>t(void 0,void 0,void 0,(function*(){return yield s(e,1,{upgrade:Ve})})))(o),l=new Ye(Object.assign(Object.assign({},n),{db:a}));return yield l.transitionFromKeyValStore(i),l}catch(e){n.loggerProvider.warn(`${We}: ${e}`)}}))}getCurrentSequenceEvents(e){return t(this,void 0,void 0,(function*(){if(e){const t=yield this.db.get("sessionCurrentSequence",e);if(!t)return;return[t]}const t=[];for(const e of yield this.db.getAll("sessionCurrentSequence"))t.push(e);return t}))}}class et extends Qe{constructor(){super(...arguments),this.finalizedSequences={},this.sequences={},this.sequenceId=0}resetCurrentSequence(e){this.sequences[e]=[]}addSequence(e){const t=this.sequenceId++,n=[...this.sequences[e]];return this.finalizedSequences[t]={sessionId:e,events:n},this.resetCurrentSequence(e),{sequenceId:t,events:n,sessionId:e}}getSequencesToSend(){return t(this,void 0,void 0,(function*(){return Object.entries(this.finalizedSequences).map((([e,{sessionId:t,events:n}])=>({sequenceId:Number(e),sessionId:t,events:n})))}))}storeCurrentSequence(e){return t(this,void 0,void 0,(function*(){if(this.sequences[e])return this.addSequence(e)}))}addEventToCurrentSequence(e,n){return t(this,void 0,void 0,(function*(){let t;return this.sequences[e]||this.resetCurrentSequence(e),this.shouldSplitEventsList(this.sequences[e],n)&&(t=this.addSequence(e)),this.sequences[e].push(n),t}))}storeSendingEvents(e,n){return t(this,void 0,void 0,(function*(){return this.finalizedSequences[this.sequenceId]={sessionId:e,events:n},this.sequenceId++}))}cleanUpSessionEventsStore(e,n){return t(this,void 0,void 0,(function*(){void 0!==n&&delete this.finalizedSequences[n]}))}}const tt=({config:e,sessionId:n,minInterval:i,maxInterval:r,type:s,payloadBatcher:o,storeType:a})=>t(void 0,void 0,void 0,(function*(){const l=new Ge(Object.assign(Object.assign({},e),{loggerProvider:e.loggerProvider,payloadBatcher:o})),c=()=>new et({loggerProvider:e.loggerProvider,maxInterval:r,minInterval:i}),d="idb"===a?yield t(void 0,void 0,void 0,(function*(){const t=yield Ye.new(s,{loggerProvider:e.loggerProvider,minInterval:i,maxInterval:r,apiKey:e.apiKey},n);return e.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),null!=t?t:c()})):c(),u=({events:n,sessionId:i,deviceId:r,sequenceId:o})=>{e.debugMode&&Z().then((({totalStorageSize:t,percentOfQuota:n,usageDetails:i})=>{e.loggerProvider.debug(`Total storage size: ${t} KB, percentage of quota: ${n}%, usage details: ${i}`)})).catch((()=>{})),l.sendEventsList({events:n,sessionId:i,flushMaxRetries:e.flushMaxRetries,apiKey:e.apiKey,deviceId:r,sampleRate:e.sampleRate,serverZone:e.serverZone,version:e.version,type:s,onComplete:()=>t(void 0,void 0,void 0,(function*(){yield d.cleanUpSessionEventsStore(i,o)}))})};return{sendCurrentSequenceEvents:({sessionId:t,deviceId:n})=>{d.storeCurrentSequence(t).then((e=>{e&&u({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n})})).catch((t=>{e.loggerProvider.warn("Failed to get current sequence of session replay events for session:",t)}))},addEvent:({event:t,sessionId:n,deviceId:i})=>{d.addEventToCurrentSequence(n,t.data).then((e=>e&&u({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:i}))).catch((t=>{e.loggerProvider.warn("Failed to add event to session replay capture:",t)}))},sendStoredEvents:({deviceId:e})=>t(void 0,void 0,void 0,(function*(){const t=yield d.getSequencesToSend();t&&t.forEach((t=>{u({sequenceId:t.sequenceId,events:t.events,sessionId:t.sessionId,deviceId:e})}))})),flush:function(e=!1){return t(this,void 0,void 0,(function*(){return l.flush(e)}))}}}));class nt{constructor(...e){const t=new Map;e.forEach((e=>{t.set(e.name,e.manager)})),this.managers=t}sendStoredEvents(e){return t(this,void 0,void 0,(function*(){const t=[];this.managers.forEach((n=>{t.push(n.sendStoredEvents(e))})),yield Promise.all(t)}))}addEvent({sessionId:e,event:t,deviceId:n}){var i;null===(i=this.managers.get(t.type))||void 0===i||i.addEvent({sessionId:e,event:t,deviceId:n})}sendCurrentSequenceEvents({sessionId:e,deviceId:t}){this.managers.forEach((n=>{n.sendCurrentSequenceEvents({sessionId:e,deviceId:t})}))}flush(e){return t(this,void 0,void 0,(function*(){const t=[];this.managers.forEach((n=>{t.push(n.flush(e))})),yield Promise.all(t)}))}}const it={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},rt={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},st={};function ot(e){if(st[e])return st[e];const t=function(e){var t,n;const i=null==(n=null==(t=null==globalThis?void 0:globalThis.Zone)?void 0:t.__symbol__)?void 0:n.call(t,e);return i&&globalThis[i]?globalThis[i]:void 0}(e)||globalThis[e],n=t.prototype,i=e in it?it[e]:void 0,r=Boolean(i&&i.every((e=>{var t,i;return Boolean(null==(i=null==(t=Object.getOwnPropertyDescriptor(n,e))?void 0:t.get)?void 0:i.toString().includes("[native code]"))}))),s=e in rt?rt[e]:void 0,o=Boolean(s&&s.every((e=>{var t;return"function"==typeof n[e]&&(null==(t=n[e])?void 0:t.toString().includes("[native code]"))})));if(r&&o)return st[e]=t.prototype,t.prototype;try{const i=document.createElement("iframe");document.body.appendChild(i);const r=i.contentWindow;if(!r)return t.prototype;const s=r[e].prototype;return document.body.removeChild(i),s?st[e]=s:n}catch{return n}}const at={};function lt(e,t,n){var i;const r=`${e}.${String(n)}`;if(at[r])return at[r].call(t);const s=ot(e),o=null==(i=Object.getOwnPropertyDescriptor(s,n))?void 0:i.get;return o?(at[r]=o,o.call(t)):t[n]}const ct={};function dt(e,t,n){const i=`${e}.${String(n)}`;if(ct[i])return ct[i].bind(t);const r=ot(e)[n];return"function"!=typeof r?t[n]:(ct[i]=r,r.bind(t))}const ut={childNodes:function(e){return lt("Node",e,"childNodes")},parentNode:function(e){return lt("Node",e,"parentNode")},parentElement:function(e){return lt("Node",e,"parentElement")},textContent:function(e){return lt("Node",e,"textContent")},contains:function(e,t){return dt("Node",e,"contains")(t)},getRootNode:function(e){return dt("Node",e,"getRootNode")()},host:function(e){return e&&"host"in e?lt("ShadowRoot",e,"host"):null},styleSheets:function(e){return e.styleSheets},shadowRoot:function(e){return e&&"shadowRoot"in e?lt("Element",e,"shadowRoot"):null},querySelector:function(e,t){return lt("Element",e,"querySelector")(t)},querySelectorAll:function(e,t){return lt("Element",e,"querySelectorAll")(t)},mutationObserver:function(){return ot("MutationObserver").constructor}};function ht(){const e=g();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight||0}function gt(){const e=g();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth||0}let vt,ft,pt;function mt(e,t){if(pt=new Date,e.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if("html"===e.tagName.toLowerCase())return"html";const n={root:document.body,idName:e=>!0,className:e=>!0,tagName:e=>!0,attr:(e,t)=>!1,seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};vt=Object.assign(Object.assign({},n),t),ft=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(vt.root,n);let i=yt(e,"all",(()=>yt(e,"two",(()=>yt(e,"one",(()=>yt(e,"none")))))));if(i){const t=Lt(qt(i,e));return t.length>0&&(i=t[0]),bt(i)}throw new Error("Selector was not found.")}function yt(e,t,n){let i=null,r=[],s=e,o=0;for(;s;){const e=(new Date).getTime()-pt.getTime();if(void 0!==vt.timeoutMs&&e>vt.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${e}ms`);let a=Ot(Ct(s))||Ot(...Et(s))||Ot(...Pt(s))||Ot(Tt(s))||[{name:"*",penalty:3}];const l=_t(s);if("all"==t)l&&(a=a.concat(a.filter(kt).map((e=>Rt(e,l)))));else if("two"==t)a=a.slice(0,1),l&&(a=a.concat(a.filter(kt).map((e=>Rt(e,l)))));else if("one"==t){const[e]=a=a.slice(0,1);l&&kt(e)&&(a=[Rt(e,l)])}else"none"==t&&(a=[{name:"*",penalty:3}],l&&(a=[Rt(a[0],l)]));for(let e of a)e.level=o;if(r.push(a),r.length>=vt.seedMinLength&&(i=St(r,n),i))break;s=s.parentElement,o++}return i||(i=St(r,n)),!i&&n?n():i}function St(e,t){const n=Lt(Mt(e));if(n.length>vt.threshold)return t?t():null;for(let e of n)if(wt(e))return e;return null}function bt(e){let t=e[0],n=t.name;for(let i=1;i<e.length;i++){const r=e[i].level||0;n=t.level===r-1?`${e[i].name} > ${n}`:`${e[i].name} ${n}`,t=e[i]}return n}function It(e){return e.map((e=>e.penalty)).reduce(((e,t)=>e+t),0)}function wt(e){const t=bt(e);switch(ft.querySelectorAll(t).length){case 0:throw new Error(`Can't select any node with this selector: ${t}`);case 1:return!0;default:return!1}}function Ct(e){const t=e.getAttribute("id");return t&&vt.idName(t)?{name:"#"+CSS.escape(t),penalty:0}:null}function Et(e){const t=Array.from(e.attributes).filter((e=>vt.attr(e.name,e.value)));return t.map((e=>({name:`[${CSS.escape(e.name)}="${CSS.escape(e.value)}"]`,penalty:.5})))}function Pt(e){return Array.from(e.classList).filter(vt.className).map((e=>({name:"."+CSS.escape(e),penalty:1})))}function Tt(e){const t=e.tagName.toLowerCase();return vt.tagName(t)?{name:t,penalty:2}:null}function _t(e){const t=e.parentNode;if(!t)return null;let n=t.firstChild;if(!n)return null;let i=0;for(;n&&(n.nodeType===Node.ELEMENT_NODE&&i++,n!==e);)n=n.nextSibling;return i}function Rt(e,t){return{name:e.name+`:nth-child(${t})`,penalty:e.penalty+1}}function kt(e){return"html"!==e.name&&!e.name.startsWith("#")}function Ot(...e){const t=e.filter(xt);return t.length>0?t:null}function xt(e){return null!=e}function*Mt(e,t=[]){if(e.length>0)for(let n of e[0])yield*Mt(e.slice(1,e.length),t.concat(n));else yield t}function Lt(e){return[...e].sort(((e,t)=>It(e)-It(t)))}function*qt(e,t,n={counter:0,visited:new Map}){if(e.length>2&&e.length>vt.optimizedMinLength)for(let i=1;i<e.length-1;i++){if(n.counter>vt.maxNumberOfTries)return;n.counter+=1;const r=[...e];r.splice(i,1);const s=bt(r);if(n.visited.has(s))return;wt(r)&&Dt(r,t)&&(yield r,n.visited.set(s,!0),yield*qt(r,t,n))}}function Dt(e,t){return ft.querySelector(bt(e))===t}const Nt=({version:e,events:t})=>{const n=[];return t.forEach((e=>{const t=JSON.parse(e);t.count=1,"click"===t.type&&n.push(t)})),{version:e,events:n}},$t=({version:e,events:t})=>{const n=[];t.forEach((e=>{const t=JSON.parse(e);"click"===t.type&&n.push(t)}));const i=n.reduce(((e,t)=>{const{x:n,y:i,selector:r,timestamp:s}=t,o=s-s%36e5,a=`${n}:${i}:${null!=r?r:""}:${o}`;return e[a]?e[a].count+=1:e[a]=Object.assign(Object.assign({},t),{timestamp:o,count:1}),e}),{});return{version:e,events:Object.values(i)}},jt=(e,{eventsManager:t,sessionId:n,deviceIdFn:i,mirror:r,ugcFilterRules:s})=>o=>{if(o.type!==ie.Click)return;const a=g();if(!a)return;const{location:l,innerHeight:c,innerWidth:d}=a;if(!l)return;const{x:u,y:h}=o;if(void 0===u||void 0===h)return;const v=r.getNode(o.id);let f;if(v)try{f=mt(v)}catch(t){e.debug("error resolving selector from finder")}const{left:p,top:m}=function(e){var t,n,i,r;const s=e.document;return{left:s.scrollingElement?s.scrollingElement.scrollLeft:void 0!==e.pageXOffset?e.pageXOffset:s.documentElement.scrollLeft||(null==s?void 0:s.body)&&(null===(t=ut.parentElement(s.body))||void 0===t?void 0:t.scrollLeft)||(null===(n=null==s?void 0:s.body)||void 0===n?void 0:n.scrollLeft)||0,top:s.scrollingElement?s.scrollingElement.scrollTop:void 0!==e.pageYOffset?e.pageYOffset:(null==s?void 0:s.documentElement.scrollTop)||(null==s?void 0:s.body)&&(null===(i=ut.parentElement(s.body))||void 0===i?void 0:i.scrollTop)||(null===(r=null==s?void 0:s.body)||void 0===r?void 0:r.scrollTop)||0}}(a),y={x:u+p,y:h+m,selector:f,viewportHeight:c,viewportWidth:d,pageUrl:J(l.href,s),timestamp:Date.now(),type:"click"},S=i();S&&t.addEvent({sessionId:n,event:{type:"interaction",data:JSON.stringify(y)},deviceId:S})};class Ut{constructor(e,t){const n=g();n&&n.navigator&&"function"==typeof n.navigator.sendBeacon?this.sendBeacon=(e,t)=>{try{if(n.navigator.sendBeacon(e,JSON.stringify(t)))return!0}catch(e){}return!1}:this.sendBeacon=()=>!1,this.sendXhr=(e,t)=>{const n=new XMLHttpRequest;return n.open("POST",e,!0),n.setRequestHeader("Accept","*/*"),n.send(JSON.stringify(t)),!0},this.basePageUrl=Q(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e}send(e,t){const{sessionId:n,type:i}=this.context,r=new URLSearchParams({device_id:e,session_id:String(n),type:String(i),api_key:this.apiKey}),s=`${this.basePageUrl}?${r.toString()}`;this.sendBeacon(s,t)||this.sendXhr(s,t)}}class Ft{static default(e,t){return new Ft(new Ut(e,t),t)}constructor(e,t){this.timestamp=Date.now(),this.hook=e=>{this.update(e)},this.send=e=>t=>{var n,i;const r=e(),s=g();s&&r&&this.transport.send(r,{version:1,events:[{maxScrollX:this._maxScrollX,maxScrollY:this._maxScrollY,maxScrollWidth:this._maxScrollWidth,maxScrollHeight:this._maxScrollHeight,viewportHeight:ht(),viewportWidth:gt(),pageUrl:J(s.location.href,null!==(i=null===(n=this.config.interactionConfig)||void 0===n?void 0:n.ugcFilterRules)&&void 0!==i?i:[]),timestamp:this.timestamp,type:"scroll"}]})},this._maxScrollX=0,this._maxScrollY=0,this._maxScrollWidth=gt(),this._maxScrollHeight=ht(),this.config=t,this.transport=e}get maxScrollX(){return this._maxScrollX}get maxScrollY(){return this._maxScrollY}get maxScrollWidth(){return this._maxScrollWidth}get maxScrollHeight(){return this._maxScrollHeight}update(e){const t=Date.now();if(e.x>this._maxScrollX){const n=gt();this._maxScrollX=e.x;const i=e.x+n;i>this._maxScrollWidth&&(this._maxScrollWidth=i),this.timestamp=t}if(e.y>this._maxScrollY){const n=ht();this._maxScrollY=e.y;const i=e.y+n;i>this._maxScrollHeight&&(this._maxScrollHeight=i),this.timestamp=t}}}class At{constructor({sessionId:e,deviceId:t}){this.deviceId=t,this.sessionId=e,e&&t&&(this.sessionReplayId=((e,t)=>`${t}/${e}`)(e,t))}}const Bt=new class{constructor(){this.dbs={},this.createStore=e=>t(this,void 0,void 0,(function*(){return yield s(e,1,{upgrade:e=>{e.objectStoreNames.contains("sessionTargetingMatch")||e.createObjectStore("sessionTargetingMatch",{keyPath:"sessionId"})}})})),this.openOrCreateDB=e=>t(this,void 0,void 0,(function*(){if(this.dbs&&this.dbs[e])return this.dbs[e];const t=`${e.substring(0,10)}_amp_session_replay_targeting`,n=yield this.createStore(t);return this.dbs[e]=n,n})),this.getTargetingMatchForSession=({loggerProvider:e,apiKey:n,sessionId:i})=>t(this,void 0,void 0,(function*(){try{const e=yield this.openOrCreateDB(n),t=String(i),r=yield e.get("sessionTargetingMatch",t);return null==r?void 0:r.targetingMatch}catch(t){e.warn(`Failed to get targeting match for session id ${i}: ${t}`)}})),this.storeTargetingMatchForSession=({loggerProvider:e,apiKey:n,sessionId:i,targetingMatch:r})=>t(this,void 0,void 0,(function*(){try{const e=yield this.openOrCreateDB(n),t=String(i);return yield e.put("sessionTargetingMatch",{targetingMatch:r,sessionId:t,lastUpdated:Date.now()})}catch(t){e.warn(`Failed to store targeting match for session id ${i}: ${t}`)}})),this.clearStoreOfOldSessions=({loggerProvider:e,apiKey:n,currentSessionId:i})=>t(this,void 0,void 0,(function*(){try{const e=yield this.openOrCreateDB(n),t=String(i),r=e.transaction("sessionTargetingMatch","readwrite"),s=yield r.store.getAll();for(let e=0;e<s.length;e++){const n=s[e],i=Date.now()-n.lastUpdated;n.sessionId!==t&&i>1728e5&&(yield r.store.delete(n.sessionId))}yield r.done}catch(t){e.warn(`Failed to clear old targeting matches for sessions: ${t}`)}}))}};function Kt(e={}){return{name:"amplitude/url-tracking@1",observer(t,n,i){var r,s,o;const a=Object.assign(Object.assign({},e),i),l=a.ugcFilterRules||[],c=null!==(r=a.enablePolling)&&void 0!==r&&r,d=null!==(s=a.pollingInterval)&&void 0!==s?s:1e3,u=null!==(o=a.captureDocumentTitle)&&void 0!==o&&o;if(!n)return()=>{};let h;const g=()=>n.location&&n.location.href||"",v=()=>{const e=g();if(void 0===h||e!==h){h=e;const i=(()=>{const{innerHeight:e,innerWidth:t,document:i}=n,r=g();let s="";return u&&(s=(null==i?void 0:i.title)||""),{href:l.length>0?J(r,l):r,title:s,viewportHeight:e,viewportWidth:t,type:"url-change-event"}})();t(i)}},f=e=>function(...t){const n=e.apply(this,t);return v(),n},p=()=>{v()};if(c){const e=n.setInterval((()=>{v()}),d);return v(),()=>{e&&n.clearInterval(e)}}if(n.history){const e=n.history.pushState.bind(n.history),t=n.history.replaceState.bind(n.history);return(()=>{n.history.pushState=f(e),n.history.replaceState=f(t)})(),n.addEventListener("popstate",v),n.addEventListener("hashchange",p),v(),()=>{n.history.pushState=e,n.history.replaceState=t,n.removeEventListener("popstate",v),n.removeEventListener("hashchange",p)}}return n.addEventListener("hashchange",p),v(),()=>{n.removeEventListener("hashchange",p)}},options:e}}class Wt{constructor(){this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.pageLeaveFns=[],this.recordFunction=null,this.teardownEventListeners=e=>{const t=g();t&&(t.removeEventListener("blur",this.blurListener),t.removeEventListener("focus",this.focusListener),!e&&t.addEventListener("blur",this.blurListener),!e&&t.addEventListener("focus",this.focusListener),t.self&&"onpagehide"in t.self?(t.removeEventListener("pagehide",this.pageLeaveListener),!e&&t.addEventListener("pagehide",this.pageLeaveListener)):(t.removeEventListener("beforeunload",this.pageLeaveListener),!e&&t.addEventListener("beforeunload",this.pageLeaveListener)))},this.blurListener=()=>{this.sendEvents()},this.focusListener=()=>{this.recordEvents({shouldLogMetadata:!1,forceRestart:!0})},this.pageLeaveListener=e=>{this.pageLeaveFns.forEach((t=>{t(e)}))},this.evaluateTargetingAndCapture=(e,n=!1)=>t(this,void 0,void 0,(function*(){if(!this.identifiers||!this.identifiers.sessionId||!this.config)return void(this.identifiers&&!this.identifiers.sessionId?this.loggerProvider.log("Session ID has not been set yet, cannot evaluate targeting for Session Replay."):this.loggerProvider.warn("Session replay init has not been called, cannot evaluate targeting."));if(!this.config.targetingConfig){if(!n)return void this.loggerProvider.log("No targeting config set, skipping initialization/recording for event.");this.loggerProvider.log("Targeting config has not been set yet, cannot evaluate targeting.")}if(this.lastTargetingParams=e,this.config.targetingConfig&&!this.sessionTargetingMatch){let n=e.event;n&&Object.values(a).includes(n.event_type)&&(n=void 0),this.sessionTargetingMatch=yield(({sessionId:e,targetingConfig:n,loggerProvider:i,apiKey:r,targetingParams:s})=>t(void 0,void 0,void 0,(function*(){if(yield Bt.clearStoreOfOldSessions({loggerProvider:i,apiKey:r,currentSessionId:e}),!0===(yield Bt.getTargetingMatchForSession({loggerProvider:i,apiKey:r,sessionId:e})))return!0;let t=!0;try{const{evaluateTargeting:o}=yield import("./targeting-min.js").then((function(e){return e.i})),a=yield o(Object.assign(Object.assign({},s),{flag:n,sessionId:e,apiKey:r,loggerProvider:i}));a&&a.sr_targeting_config&&(t="on"===a.sr_targeting_config.key),Bt.storeTargetingMatchForSession({loggerProvider:i,apiKey:r,sessionId:e,targetingMatch:t})}catch(e){const t=e;i.warn(t.message)}return t})))({sessionId:this.identifiers.sessionId,targetingConfig:this.config.targetingConfig,loggerProvider:this.loggerProvider,apiKey:this.config.apiKey,targetingParams:{userProperties:e.userProperties,event:n}}),this.loggerProvider.debug(JSON.stringify({name:"targeted replay capture config",sessionTargetingMatch:this.sessionTargetingMatch,event:n,targetingParams:e},null,2))}const i=n,r=n;this.initialize(i,r)})),this.addCustomRRWebEvent=(e,n={},i=!0)=>t(this,void 0,void 0,(function*(){try{let t;const r=this.config;if(r&&e!==A.METADATA&&(t={config:X(r),version:ze},i)){const e=yield Z();t=Object.assign(Object.assign({},e),t)}this.recordCancelCallback&&this.recordFunction?this.recordFunction.addCustomEvent(e,Object.assign(Object.assign({},n),t)):this.loggerProvider.debug(`Not able to add custom replay capture event ${e} due to no ongoing recording.`)}catch(e){this.loggerProvider.debug("Error while adding custom replay capture event: ",e)}})),this.stopRecordingEvents=()=>{var e;try{this.loggerProvider.log("Session Replay capture stopping."),this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null,null===(e=this.networkObservers)||void 0===e||e.stop()}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while stopping replay capture: ${t.toString()}`)}},this.loggerProvider=new B(new p)}init(e,t){return v(this._init(e,t))}_init(e,n){var i,r,s,o,a,l,c;return t(this,void 0,void 0,(function*(){this.loggerProvider=new B(n.loggerProvider||new p),Object.prototype.hasOwnProperty.call(n,"logLevel")&&this.loggerProvider.enable(n.logLevel),this.identifiers=new At({sessionId:n.sessionId,deviceId:n.deviceId}),this.joinedConfigGenerator=yield((e,n)=>t(void 0,void 0,void 0,(function*(){const t=new Y(e,n),i=yield le({localConfig:t,configKeys:["sessionReplay"]});return new ce(i,t)})))(e,n);const{joinedConfig:d,localConfig:u,remoteConfig:h}=yield this.joinedConfigGenerator.generateJoinedConfig(this.identifiers.sessionId);if(this.config=d,this.setMetadata(n.sessionId,d,u,h,null===(i=n.version)||void 0===i?void 0:i.version,ze,null===(r=n.version)||void 0===r?void 0:r.type),n.sessionId&&(null===(s=this.config.interactionConfig)||void 0===s?void 0:s.enabled)){const e=Ft.default({sessionId:n.sessionId,type:"interaction"},this.config);this.pageLeaveFns=[e.send(this.getDeviceId.bind(this)).bind(e)],this.scrollHook=e.hook.bind(e)}const v=[];let f,{storeType:m}=this.config;"idb"!==m||(null===(o=g())||void 0===o?void 0:o.indexedDB)||(m="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log(`Using ${m} for event storage.`);try{const e=yield tt({config:this.config,sessionId:this.identifiers.sessionId,type:"replay",storeType:m});v.push({name:"replay",manager:e})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating replay events manager: ${t.toString()}`)}if(null===(a=this.config.interactionConfig)||void 0===a?void 0:a.enabled){const e=this.config.interactionConfig.batch?$t:Nt;try{const t=yield tt({config:this.config,sessionId:this.identifiers.sessionId,type:"interaction",minInterval:null!==(l=this.config.interactionConfig.trackEveryNms)&&void 0!==l?l:3e4,maxInterval:6e4,payloadBatcher:e,storeType:m});v.push({name:"interaction",manager:t})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating interaction events manager: ${t.toString()}`)}}this.eventsManager=new nt(...v),this.eventCompressor&&this.eventCompressor.terminate();const y=g();if((null===(c=this.config.experimental)||void 0===c?void 0:c.useWebWorker)&&y&&y.Worker){const{compressionScript:e}=yield import("./worker-min.js");f=e}this.eventCompressor=new Ke(this.eventsManager,this.config,this.getDeviceId(),f),yield this.initializeNetworkObservers(),this.loggerProvider.log("Installing @amplitude/session-replay-browser."),this.teardownEventListeners(!1),yield this.evaluateTargetingAndCapture({userProperties:n.userProperties},!0)}))}setSessionId(e,t){return v(this.asyncSetSessionId(e,t))}asyncSetSessionId(e,n,i){var r;return t(this,void 0,void 0,(function*(){this.sessionTargetingMatch=!1,this.lastShouldRecordDecision=void 0;const t=this.identifiers&&this.identifiers.sessionId;t&&this.sendEvents(t);const s=n||this.getDeviceId();if(this.identifiers=new At({sessionId:e,deviceId:s}),this.joinedConfigGenerator&&t){const{joinedConfig:e}=yield this.joinedConfigGenerator.generateJoinedConfig(this.identifiers.sessionId);this.config=e}if(null===(r=this.config)||void 0===r?void 0:r.targetingConfig){const e=!0;yield this.evaluateTargetingAndCapture({userProperties:null==i?void 0:i.userProperties},e)}else yield this.recordEvents({forceRestart:!0,shouldLogMetadata:!0})}))}getSessionReplayProperties(){const e=this.config,t=this.identifiers;if(!e||!t)return this.loggerProvider.warn("Session replay init has not been called, cannot get session replay properties."),{};const n=this.getShouldRecord();let i={};return n&&(i={[N]:t.sessionReplayId?t.sessionReplayId:null},e.debugMode&&(i[U]=JSON.stringify({appHash:G(e.apiKey).toString()}))),this.addCustomRRWebEvent(A.GET_SR_PROPS,{shouldRecord:n,eventProperties:i},10===this.eventCount),10===this.eventCount&&(this.eventCount=0),this.eventCount++,i}sendEvents(e){var t;const n=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),i=this.getDeviceId();this.eventsManager&&n&&i&&this.eventsManager.sendCurrentSequenceEvents({sessionId:n,deviceId:i})}initialize(e=!1,n=!0){var i;return t(this,void 0,void 0,(function*(){if(!(null===(i=this.identifiers)||void 0===i?void 0:i.sessionId))return this.loggerProvider.log("Session is not being recorded due to lack of session id."),Promise.resolve();const t=this.getDeviceId();return t?(this.eventsManager&&e&&this.eventsManager.sendStoredEvents({deviceId:t}),this.recordEvents({forceRestart:n,shouldLogMetadata:!0})):(this.loggerProvider.log("Session is not being recorded due to lack of device id."),Promise.resolve())}))}shouldOptOut(){var e,t;let n;if(null===(e=this.config)||void 0===e?void 0:e.instanceName){n=(i=this.config.instanceName,void 0===i&&(i=d),x.getInstance(i)).identityStore.getIdentity().optOut}var i;return void 0!==n?n:null===(t=this.config)||void 0===t?void 0:t.optOut}getShouldRecord(){if(!this.identifiers||!this.config||!this.identifiers.sessionId)return this.loggerProvider.warn("Session is not being recorded due to lack of config, please call sessionReplay.init."),!1;if(!this.config.captureEnabled)return this.loggerProvider.log(`Session ${this.identifiers.sessionId} not being captured due to capture being disabled for project or because the remote config could not be fetched.`),!1;if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${this.identifiers.sessionId} out of recording due to optOut config.`),!1;let e=!1,t="",n=!1;if(this.config.targetingConfig)this.sessionTargetingMatch?(t=`Capturing replays for session ${this.identifiers.sessionId} due to matching targeting conditions.`,this.loggerProvider.log(t),e=!0,n=!0):(t=`Not capturing replays for session ${this.identifiers.sessionId} due to not matching targeting conditions.`,this.loggerProvider.log(t),e=!1,n=!1);else{(function(e,t){const n=G(e.toString());return 31*Math.abs(n)%1e6/1e6<t})(this.identifiers.sessionId,this.config.sampleRate)?(e=!0,n=!0):(t=`Opting session ${this.identifiers.sessionId} out of recording due to sample rate.`,this.loggerProvider.log(t),e=!1,n=!1)}return this.lastShouldRecordDecision!==e&&this.config.targetingConfig&&(this.addCustomRRWebEvent(A.TARGETING_DECISION,{message:t,sessionId:this.identifiers.sessionId,matched:n,targetingParams:this.lastTargetingParams}),this.lastShouldRecordDecision=e),e}getBlockSelectors(){var e,t,n;const i=null!==(n=null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.blockSelector)&&void 0!==n?n:[];if(0!==i.length)return i}getMaskTextSelectors(){var e,t,n,i;if("conservative"===(null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.defaultMaskLevel))return"*";const r=null===(i=null===(n=this.config)||void 0===n?void 0:n.privacyConfig)||void 0===i?void 0:i.maskSelector;return r||void 0}getRecordingPlugins(e){var n,i,r,s,o,a;return t(this,void 0,void 0,(function*(){const t=[];try{const e=Kt({ugcFilterRules:(null===(i=null===(n=this.config)||void 0===n?void 0:n.interactionConfig)||void 0===i?void 0:i.ugcFilterRules)||[],enablePolling:(null===(r=this.config)||void 0===r?void 0:r.enableUrlChangePolling)||!1,pollingInterval:null===(s=this.config)||void 0===s?void 0:s.urlChangePollingInterval,captureDocumentTitle:null===(o=this.config)||void 0===o?void 0:o.captureDocumentTitle});t.push(e)}catch(e){this.loggerProvider.warn("Failed to create URL tracking plugin:",e)}if(null===(a=null==e?void 0:e.console)||void 0===a?void 0:a.enabled)try{const{getRecordConsolePlugin:n}=yield import("./console-plugin-min.js");t.push(n({level:e.console.levels}))}catch(e){this.loggerProvider.warn("Failed to load console plugin:",e)}return t.length>0?t:void 0}))}getRecordFunction(){return t(this,void 0,void 0,(function*(){if(this.recordFunction)return this.recordFunction;try{const{record:e}=yield import("./rrweb-record-min.js");return this.recordFunction=e,e}catch(e){return this.loggerProvider.warn("Failed to load rrweb-record module:",e),null}}))}recordEvents({shouldLogMetadata:e,forceRestart:n}){var i,r,s,o,a;return t(this,void 0,void 0,(function*(){const t=this.config,l=this.getShouldRecord(),c=null===(i=this.identifiers)||void 0===i?void 0:i.sessionId;if(!l||!c||!t)return;if(this.recordCancelCallback&&!n)return void this.loggerProvider.debug("A capture is already in progress and forceRestart is false. Not restarting.");this.loggerProvider.debug(`Starting new capture for session with sessionId=${c}.`),this.stopRecordingEvents();const d=yield this.getRecordFunction();if(!d)return;yield this.initializeNetworkObservers(),null===(r=this.networkObservers)||void 0===r||r.start((e=>{this.addCustomRRWebEvent(A.FETCH_REQUEST,e)}));const{privacyConfig:u,interactionConfig:h,loggingConfig:g}=t,v=(null==h?void 0:h.enabled)?{mouseInteraction:this.eventsManager&&jt(this.loggerProvider,{eventsManager:this.eventsManager,sessionId:c,deviceIdFn:this.getDeviceId.bind(this),mirror:d.mirror,ugcFilterRules:null!==(s=h.ugcFilterRules)&&void 0!==s?s:[]}),scroll:this.scrollHook}:{},f=(null==h?void 0:h.enabled)&&h.ugcFilterRules?h.ugcFilterRules:[];this.loggerProvider.log(`Session Replay capture beginning for ${c}.`);try{this.recordCancelCallback=d({emit:e=>{if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${c} out of recording due to optOut config.`),this.stopRecordingEvents(),void this.sendEvents();e.type===ne.Meta&&(e.data.href=J(e.data.href,f)),this.eventCompressor&&this.eventCompressor.enqueueEvent(e,c)},inlineStylesheet:t.shouldInlineStylesheet,hooks:v,maskAllInputs:!0,maskTextClass:F,blockClass:"amp-block",blockSelector:this.getBlockSelectors(),applyBackgroundColorToBlockedElements:t.applyBackgroundColorToBlockedElements,maskInputFn:z("input",u),maskTextFn:z("text",u),maskTextSelector:this.getMaskTextSelectors(),recordCanvas:!1,slimDOMOptions:{script:null===(o=t.omitElementTags)||void 0===o?void 0:o.script,comment:null===(a=t.omitElementTags)||void 0===a?void 0:a.comment},errorHandler:e=>{const t=e;if(t.message.includes("insertRule")&&t.message.includes("CSSStyleSheet"))throw t;if(t._external_)throw t;return this.loggerProvider.warn("Error while capturing replay: ",t.toString()),!0},plugins:yield this.getRecordingPlugins(g)}),this.addCustomRRWebEvent(A.DEBUG_INFO),e&&this.addCustomRRWebEvent(A.METADATA,this.metadata)}catch(e){this.loggerProvider.warn("Failed to initialize session replay:",e)}}))}getDeviceId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.deviceId}getSessionId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.sessionId}flush(e=!1){var n;return t(this,void 0,void 0,(function*(){return null===(n=this.eventsManager)||void 0===n?void 0:n.flush(e)}))}shutdown(){this.teardownEventListeners(!0),this.stopRecordingEvents(),this.sendEvents()}mapSDKType(e){return"plugin"===e?"@amplitude/plugin-session-replay-browser":"segment"===e?"@amplitude/segment-session-replay-plugin":null}setMetadata(e,t,n,i,r,s,o){const a=(null==e?void 0:e.toString())?G(e.toString()):void 0;this.metadata={joinedConfig:t,localConfig:n,remoteConfig:i,sessionId:e,hashValue:a,sampleRate:t.sampleRate,replaySDKType:this.mapSDKType(o),replaySDKVersion:r,standaloneSDKType:"@amplitude/session-replay-browser",standaloneSDKVersion:s}}initializeNetworkObservers(){var e,n,i;return t(this,void 0,void 0,(function*(){if((null===(i=null===(n=null===(e=this.config)||void 0===e?void 0:e.loggingConfig)||void 0===n?void 0:n.network)||void 0===i?void 0:i.enabled)&&!this.networkObservers)try{const{NetworkObservers:e}=yield import("./observers-min.js");this.networkObservers=new e}catch(e){this.loggerProvider.warn("Failed to import or instantiate NetworkObservers:",e)}}))}}const zt=e=>()=>{const{config:t}=e,{loggerProvider:n,logLevel:i}=t||V();return{logger:n,logLevel:i}};var Gt=(()=>{const e=new Wt;return{init:M(e.init.bind(e),"init",zt(e)),evaluateTargetingAndCapture:M(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",zt(e)),setSessionId:M(e.setSessionId.bind(e),"setSessionId",zt(e)),getSessionId:M(e.getSessionId.bind(e),"getSessionId",zt(e)),getSessionReplayProperties:M(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",zt(e)),flush:M(e.flush.bind(e),"flush",zt(e)),shutdown:M(e.shutdown.bind(e),"shutdown",zt(e))}})();const{init:Qt,setSessionId:Ht,getSessionId:Jt,getSessionReplayProperties:Zt,flush:Xt,shutdown:Vt,evaluateTargetingAndCapture:Yt}=Gt;export{B as S,Jt as a,Zt as b,Vt as c,Yt as e,Xt as f,g,Qt as i,Ht as s};
|
|
2
2
|
//# sourceMappingURL=index-min.js.map
|
|
Binary file
|