@amplitude/segment-session-replay-plugin 0.0.48 → 0.0.50

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.
@@ -1,2 +1,2 @@
1
- function e(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if("default"!==n&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},t(e,n)};function n(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var r,i,o=function(){return o=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},o.apply(this,arguments)};function s(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}function a(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{l(r.next(e))}catch(e){o(e)}}function a(e){try{l(r.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((r=r.apply(e,t||[])).next())})}function l(e,t){var n,r,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(l){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,l])}}}function c(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function u(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s}function d(e,t,n){if(n||2===arguments.length)for(var r,i=0,o=t.length;i<o;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError,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"}(r||(r={})),function(e){e.IDENTIFY="$identify",e.GROUP_IDENTIFY="$groupidentify",e.REVENUE="revenue_amount"}(i||(i={}));var v,h="$default_instance",f="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"}(v||(v={}));var 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},p=d([],u(Array(256).keys()),!1).map(function(e){return e.toString(16).padStart(2,"0")}),m=function(e){var t,n=g();if(!(null===(t=null==n?void 0:n.crypto)||void 0===t?void 0:t.getRandomValues))return function(e){return e?(e^16*Math.random()>>e/4).toString(16):(String(1e7)+String(-1e3)+String(-4e3)+String(-8e3)+String(-1e11)).replace(/[018]/g,m)}(e);var r=n.crypto.getRandomValues(new Uint8Array(16));return r[6]=15&r[6]|64,r[8]=63&r[8]|128,d([],u(r.entries()),!1).map(function(e){var t=u(e,2),n=t[0],r=t[1];return[4,6,8,10].includes(n)?"-".concat(p[r]):p[r]}).join("")},y={},b={get exports(){return y},set exports(e){y=e}},S=Object.prototype.hasOwnProperty;function I(e){return"[Throws: "+(e?e.message:"?")+"]"}function w(e){var t=[];return function e(n){if(null===n||"object"!=typeof n)return n;if(-1!==t.indexOf(n))return"[Circular]";if(t.push(n),"function"==typeof n.toJSON)try{var r=e(n.toJSON());return t.pop(),r}catch(e){return I(e)}if(Array.isArray(n)){var i=n.map(e);return t.pop(),i}var o=Object.keys(n).reduce(function(t,r){return t[r]=e(function(e,t){if(S.call(e,t))try{return e[t]}catch(e){return I(e)}return e[t]}(n,r)),t},{});return t.pop(),o}(e)}b.exports=function(e,t,n){return JSON.stringify(w(e),t,n)};var C,E=y.ensureProperties=w,P=y||e({__proto__:null,ensureProperties:E,get default(){return y}},[y]),k=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"}(C||(C={}));var x="Amplitude Logger ",M=function(){function e(){this.logLevel=C.None}return e.prototype.disable=function(){this.logLevel=C.None},e.prototype.enable=function(e){void 0===e&&(e=C.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<C.Verbose||console.log("".concat(x,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<C.Warn||console.warn("".concat(x,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<C.Error||console.error("".concat(x,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<C.Debug||console.log("".concat(x,"[Debug]: ").concat(e.join(" ")))},e}(),T=function(e){return void 0===e||""===e?h:e},R=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:h,logLevel:C.Warn,loggerProvider:new M,offline:!1,optOut:!1,serverUrl:f,serverZone:"US",useBatch:!1}},O=function(){function e(e){var t,n,r,i;this._optOut=!1;var o=R();this.apiKey=e.apiKey,this.flushIntervalMillis=null!==(t=e.flushIntervalMillis)&&void 0!==t?t:o.flushIntervalMillis,this.flushMaxRetries=e.flushMaxRetries||o.flushMaxRetries,this.flushQueueSize=e.flushQueueSize||o.flushQueueSize,this.instanceName=T(e.instanceName),this.loggerProvider=e.loggerProvider||o.loggerProvider,this.logLevel=null!==(n=e.logLevel)&&void 0!==n?n:o.logLevel,this.minIdLength=e.minIdLength,this.plan=e.plan,this.ingestionMetadata=e.ingestionMetadata,this.offline=void 0!==e.offline?e.offline:o.offline,this.optOut=null!==(r=e.optOut)&&void 0!==r?r:o.optOut,this.serverUrl=e.serverUrl,this.serverZone=e.serverZone||o.serverZone,this.storageProvider=e.storageProvider,this.transportProvider=e.transportProvider,this.useBatch=null!==(i=e.useBatch)&&void 0!==i?i:o.useBatch,this.loggerProvider.enable(this.logLevel);var s=L(e.serverUrl,e.serverZone,e.useBatch);this.serverZone=s.serverZone,this.serverUrl=s.serverUrl}return Object.defineProperty(e.prototype,"optOut",{get:function(){return this._optOut},set:function(e){this._optOut=e},enumerable:!1,configurable:!0}),e}(),_=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":f},L=function(e,t,n){if(void 0===e&&(e=""),void 0===t&&(t=R().serverZone),void 0===n&&(n=R().useBatch),e)return{serverUrl:e,serverZone:void 0};var r=["US","EU"].includes(t)?t:R().serverZone;return{serverZone:r,serverUrl:_(r,n)}};var F=function(e,t,n,r,i){return void 0===i&&(i=null),function(){for(var o=[],s=0;s<arguments.length;s++)o[s]=arguments[s];var a=n(),l=a.logger,c=a.logLevel;if(c&&c<C.Debug||!c||!l)return e.apply(i,o);var u,d={type:"invoke public method",name:t,args:o,stacktrace:(u=1,void 0===u&&(u=0),((new Error).stack||"").split("\n").slice(2+u).map(function(e){return e.trim()})),time:{start:(new Date).toISOString()},states:{}};r&&d.states&&(d.states.before=r());var v=e.apply(i,o);return v&&v.promise?v.promise.then(function(){r&&d.states&&(d.states.after=r()),d.time&&(d.time.end=(new Date).toISOString()),l.debug(JSON.stringify(d,null,2))}):(r&&d.states&&(d.states.after=r()),d.time&&(d.time.end=(new Date).toISOString()),l.debug(JSON.stringify(d,null,2))),v}},D=function(){function e(){}return e.prototype.getApplicationContext=function(){return{versionName:this.versionName,language:q(),platform:"Web",os:void 0,deviceModel:void 0}},e}(),q=function(){return"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||""},A=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}(),j=function(){return j=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},j.apply(this,arguments)};function N(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function U(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s}"function"==typeof SuppressedError&&SuppressedError;var B=function(e,t){var n,r,i=typeof e;if(i!==typeof t)return!1;try{for(var o=N(["string","number","boolean","undefined"]),s=o.next();!s.done;s=o.next()){if(s.value===i)return e===t}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}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(),u=Object.keys(t).sort();if(!B(c,u))return!1;var d=!0;return Object.keys(e).forEach(function(n){B(e[n],t[n])||(d=!1)}),d}for(var v=0;v<e.length;v++)if(!B(e[v],t[v]))return!1;return!0};Object.entries||(Object.entries=function(e){for(var t=Object.keys(e),n=t.length,r=new Array(n);n--;)r[n]=[t[n],e[t[n]]];return r});var W=function(){function e(){this.identity={userProperties:{}},this.listeners=new Set}return e.prototype.editIdentity=function(){var e=this,t=j({},this.identity.userProperties),n=j(j({},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,r,i,o,s,a,l=n.userProperties||{};try{for(var c=N(Object.entries(e)),u=c.next();!u.done;u=c.next()){var d=U(u.value,2),v=d[0],h=d[1];switch(v){case"$set":try{for(var f=(i=void 0,N(Object.entries(h))),g=f.next();!g.done;g=f.next()){var p=U(g.value,2),m=p[0],y=p[1];l[m]=y}}catch(e){i={error:e}}finally{try{g&&!g.done&&(o=f.return)&&o.call(f)}finally{if(i)throw i.error}}break;case"$unset":try{for(var b=(s=void 0,N(Object.keys(h))),S=b.next();!S.done;S=b.next()){delete l[m=S.value]}}catch(e){s={error:e}}finally{try{S&&!S.done&&(a=b.return)&&a.call(b)}finally{if(s)throw s.error}}break;case"$clearAll":l={}}}}catch(e){t={error:e}}finally{try{u&&!u.done&&(r=c.return)&&r.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 j({},this.identity)},e.prototype.setIdentity=function(e){var t=j({},this.identity);this.identity=j({},e),B(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}(),z="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self,K=function(){function e(){this.identityStore=new W,this.eventBridge=new A,this.applicationContextProvider=new D}return e.getInstance=function(t){return z.analyticsConnectorInstances||(z.analyticsConnectorInstances={}),z.analyticsConnectorInstances[t]||(z.analyticsConnectorInstances[t]=new e),z.analyticsConnectorInstances[t]},e}(),H=function(e){var t=0;if(0===e.length)return t;for(var n=0;n<e.length;n++){t=(t<<5)-t+e.charCodeAt(n),t|=0}return t},G=function(){function e(){}return e.prototype.send=function(e,t,n){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,n,r,i,o,s,a,l,c,u,d,h,f,g,p,m,y,b,S,I,w,C;if("object"!=typeof e)return null;var E=e.code||0,P=this.buildStatus(E);switch(P){case v.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!==(r=e.server_upload_time)&&void 0!==r?r:0}};case v.Invalid:return{status:P,statusCode:E,body:{error:null!==(i=e.error)&&void 0!==i?i:"",missingField:null!==(o=e.missing_field)&&void 0!==o?o:"",eventsWithInvalidFields:null!==(s=e.events_with_invalid_fields)&&void 0!==s?s:{},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!==(u=e.exceeded_daily_quota_devices)&&void 0!==u?u:{},silencedDevices:null!==(d=e.silenced_devices)&&void 0!==d?d:[],silencedEvents:null!==(h=e.silenced_events)&&void 0!==h?h:[],throttledDevices:null!==(f=e.throttled_devices)&&void 0!==f?f:{},throttledEvents:null!==(g=e.throttled_events)&&void 0!==g?g:[]}};case v.PayloadTooLarge:return{status:P,statusCode:E,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case v.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!==(b=e.throttled_devices)&&void 0!==b?b:{},throttledUsers:null!==(S=e.throttled_users)&&void 0!==S?S:{},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 v.Timeout:default:return{status:P,statusCode:E}}},e.prototype.buildStatus=function(e){return function(e){return e>=200&&e<300}(e)?v.Success:429===e?v.RateLimit:413===e?v.PayloadTooLarge:408===e?v.Timeout:e>=400&&e<500?v.Invalid:e>=500?v.Failed:v.Unknown},e}(),Q=function(e){function t(t){void 0===t&&(t={});var n=e.call(this)||this;return n.customHeaders=t,n}return n(t,e),t.prototype.send=function(e,t){return a(this,void 0,void 0,function(){var n,r,i;return l(this,function(s){switch(s.label){case 0:if("undefined"==typeof fetch)throw new Error("FetchTransport is not supported");return n={headers:o({"Content-Type":"application/json",Accept:"*/*"},this.customHeaders),body:JSON.stringify(t),method:"POST"},[4,fetch(e,n)];case 1:return[4,(r=s.sent()).text()];case 2:i=s.sent();try{return[2,this.buildResponse(JSON.parse(i))]}catch(e){return[2,this.buildResponse({code:r.status})]}return[2]}})})},t}(G),J=function(){function e(e,t){this.key="AMP_remote_config_".concat(e.substring(0,10)),this.logger=t;try{this.isSupported="undefined"!=typeof localStorage}catch(e){this.logger.debug("Remote config localstorage failed to access: ",e),this.isSupported=!1}}return e.prototype.fetchConfig=function(){var e=null,t={remoteConfig:null,lastFetch:new Date};if(!this.isSupported)return Promise.resolve(t);try{e=localStorage.getItem(this.key)}catch(e){return this.logger.debug("Remote config localstorage failed to access: ",e),Promise.resolve(t)}if(null===e)return this.logger.debug("Remote config localstorage gets null because the key does not exist"),Promise.resolve(t);try{var n=JSON.parse(e);return this.logger.debug("Remote config localstorage parsed successfully: ".concat(P(n))),Promise.resolve({remoteConfig:n.remoteConfig,lastFetch:new Date(n.lastFetch)})}catch(e){return this.logger.debug("Remote config localstorage failed to parse: ",e),localStorage.removeItem(this.key),Promise.resolve(t)}},e.prototype.setConfig=function(e){if(!this.isSupported)return Promise.resolve(!1);try{return localStorage.setItem(this.key,JSON.stringify(e)),this.logger.debug("Remote config localstorage set successfully."),Promise.resolve(!0)}catch(e){this.logger.debug("Remote config localstorage failed to set: ",e)}return Promise.resolve(!1)},e}();var $,Z=401,V=403,X=429,Y=function(){function e(t,n,r,i,o,s,a){void 0===r&&(r="US"),void 0===s&&(s=e.DEFAULT_CONFIG_GROUP),this.callbackInfos=[],this.lastSuccessfulFetch=null,this.fetchPromise=null,this.isLastFetchInvalidApiKey=!1,this.apiKey=t,this.configGroup=s,this.serverUrl=i||("US"===r?"https://sr-client-cfg.amplitude.com/config":"https://sr-client-cfg.eu.amplitude.com/config"),this.logger=n,this.storage=a||new J(t,n),this.customFetch=o}return e.prototype.subscribe=function(e,t,n){var r=m(),i={id:r,key:e,deliveryMode:t,callback:n};return this.callbackInfos.push(i),"all"===t?this.subscribeAll(i):this.subscribeWaitForRemote(i,t.timeout),r},e.prototype.unsubscribe=function(e){var t=this.callbackInfos.findIndex(function(t){return t.id===e});return-1===t?(this.logger.debug("Remote config client unsubscribe failed because callback with id ".concat(e," doesn't exist.")),!1):(this.callbackInfos.splice(t,1),this.logger.debug("Remote config client unsubscribe succeeded removing callback with id ".concat(e,".")),!0)},e.prototype.updateConfigs=function(){return a(this,void 0,void 0,function(){var e,t=this;return l(this,function(n){switch(n.label){case 0:return this.lastSuccessfulFetch&&Date.now()-this.lastSuccessfulFetch<3e5?(this.logger.debug("Remote config client skipping updateConfigs: Too recent"),[2]):[4,this.getOrCreateFetchPromise()];case 1:return e=n.sent(),this.storage.setConfig(e),this.callbackInfos.forEach(function(n){t.sendCallback(n,e,"remote")}),[2]}})})},e.prototype.getOrCreateFetchPromise=function(){var e=this;return this.fetchPromise?this.fetchPromise:this.isLastFetchInvalidApiKey?(this.logger.debug("Remote config client skipping fetch: Invalid API key"),this.fetchPromise=Promise.resolve({remoteConfig:null,lastFetch:new Date}).finally(function(){e.fetchPromise=null}),this.fetchPromise):(this.fetchPromise=this.fetch().then(function(t){return null!==t.remoteConfig&&(e.lastSuccessfulFetch=Date.now()),t}).finally(function(){e.fetchPromise=null}),this.fetchPromise)},e.prototype.subscribeAll=function(e){return a(this,void 0,void 0,function(){var t,n,r,i=this;return l(this,function(o){switch(o.label){case 0:return t=this.getOrCreateFetchPromise().then(function(t){i.logger.debug("Remote config client subscription all mode fetched from remote: ".concat(JSON.stringify(t))),i.sendCallback(e,t,"remote"),i.storage.setConfig(t)}),n=this.storage.fetchConfig().then(function(e){return e}),[4,Promise.race([t,n])];case 1:return void 0!==(r=o.sent())&&(this.logger.debug("Remote config client subscription all mode fetched from cache: ".concat(JSON.stringify(r))),null!==r.remoteConfig?this.sendCallback(e,r,"cache"):this.logger.debug("Remote config client skips sending callback because cache is empty (first time user).")),[4,t];case 2:return o.sent(),[2]}})})},e.prototype.subscribeWaitForRemote=function(e,t){return a(this,void 0,void 0,function(){var n,r;return l(this,function(i){switch(i.label){case 0:n=new Promise(function(e,n){setTimeout(function(){n("Timeout exceeded")},t)}),i.label=1;case 1:return i.trys.push([1,3,,5]),[4,Promise.race([this.getOrCreateFetchPromise(),n])];case 2:return r=i.sent(),this.logger.debug("Remote config client subscription wait for remote mode returns from remote."),this.sendCallback(e,r,"remote"),this.storage.setConfig(r),[3,5];case 3:return i.sent(),this.logger.debug("Remote config client subscription wait for remote mode exceeded timeout. Try to fetch from cache."),[4,this.storage.fetchConfig()];case 4:return null!==(r=i.sent()).remoteConfig?(this.logger.debug("Remote config client subscription wait for remote mode returns a cached copy."),this.sendCallback(e,r,"cache")):(this.logger.debug("Remote config client subscription wait for remote mode failed to fetch cache."),this.sendCallback(e,r,"remote")),[3,5];case 5:return[2]}})})},e.prototype.sendCallback=function(e,t,n){var r;e.lastCallback=new Date,r=e.key?e.key.split(".").reduce(function(e,t){return null===e?e:t in e?e[t]:null},t.remoteConfig):t.remoteConfig,e.callback(r,n,t.lastFetch)},e.prototype.fetch=function(e,t){return void 0===e&&(e=3),void 0===t&&(t=1e3),a(this,void 0,void 0,function(){var n,r,i,o,s,a,c=this;return l(this,function(u){switch(u.label){case 0:n=t/e,r={remoteConfig:null,lastFetch:new Date},i=function(r){var i,s,a,u,d,v,h,f,g;return l(this,function(l){switch(l.label){case 0:i=!0,s=new AbortController,a=setTimeout(function(){return s.abort()},t),l.label=1;case 1:return l.trys.push([1,10,11,12]),u=o.getUrlParams(),d={Accept:"*/*"},o.customFetch?[4,(p=o.customFetch({url:u,method:"GET",headers:d,signal:s.signal}),m=s.signal,new Promise(function(e,t){var n=function(){var e=new Error("Remote config custom fetch aborted by timeout");e.name="AbortError",t(e)};m.addEventListener("abort",n,{once:!0}),p.then(function(t){m.removeEventListener("abort",n),e(t)},function(e){m.removeEventListener("abort",n),t(e)})}))]:[3,3];case 2:return h=l.sent(),[3,5];case 3:return[4,fetch(u,{method:"GET",headers:d,signal:s.signal})];case 4:h=l.sent(),l.label=5;case 5:return(v=h).ok||v.status>=200&&v.status<300?[3,7]:[4,v.text()];case 6:return f=l.sent(),o.logger.debug("Remote config client fetch with retry time ".concat(e," failed with ").concat(v.status,": ").concat(f)),v.status===Z||v.status===V?(o.logger.error("Remote config client fetch failed with ".concat(v.status,". Invalid API key; future fetches will be skipped.")),o.isLastFetchInvalidApiKey=!0,i=!1):v.status>=400&&v.status<500&&v.status!==X&&(i=!1),[3,9];case 7:return[4,v.json()];case 8:return[2,{value:{remoteConfig:l.sent(),lastFetch:new Date}}];case 9:return[3,12];case 10:return(g=l.sent())instanceof Error&&"AbortError"===g.name?o.logger.debug("Remote config client fetch with retry time ".concat(e," timed out after ").concat(t,"ms")):o.logger.debug("Remote config client fetch with retry time ".concat(e," is rejected because: "),g),[3,12];case 11:return clearTimeout(a),[7];case 12:return i?r<e-1?[4,new Promise(function(e){return setTimeout(e,c.getJitterDelay(n))})]:[3,14]:[2,"break"];case 13:l.sent(),l.label=14;case 14:return[2]}var p,m})},o=this,s=0,u.label=1;case 1:return s<e?[5,i(s)]:[3,4];case 2:if("object"==typeof(a=u.sent()))return[2,a.value];if("break"===a)return[3,4];u.label=3;case 3:return s++,[3,1];case 4:return[2,r]}})})},e.prototype.getJitterDelay=function(e){return Math.floor(Math.random()*e)},e.prototype.getUrlParams=function(){var e=encodeURIComponent(this.apiKey),t=new URLSearchParams;return t.append("config_group",this.configGroup),"".concat(this.serverUrl,"/").concat(e,"?").concat(t.toString())},e.DEFAULT_CONFIG_GROUP="browser",e}();!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}($||($={}));var ee,te="https://app.amplitude.com",ne={US:te,EU:"https://app.eu.amplitude.com",STAGING:"https://apps.stag2.amplitude.com"};var re="__AMPLITUDE_MESSENGER_INSTANCE__",ie="__AMPLITUDE_MESSENGER__",oe=function(){function e(e){var t=(void 0===e?{}:e).origin,n=void 0===t?te:t;this[ee]=!0,this.isSetup=!1,this.messageHandler=null,this.requestCallbacks={},this.actionHandlers=new Map,this.pendingMessages=new Map,this.scriptLoadPromises=new Map,this.endpoint=n}return e.prototype.notify=function(e){var t,n,r,i;null===(n=null===(t=this.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Message sent: ",JSON.stringify(e)),null===(i=null===(r=window.opener)||void 0===r?void 0:r.postMessage)||void 0===i||i.call(r,e,this.endpoint)},e.prototype.sendRequest=function(e,t,n){var r=this;void 0===n&&(n={timeout:15e3});var i="".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9)),o={id:i,action:e,args:t};return new Promise(function(t,s){r.requestCallbacks[i]={resolve:t,reject:s},r.notify(o),n.timeout>0&&setTimeout(function(){s(new Error("".concat(e," timed out (id: ").concat(i,")"))),delete r.requestCallbacks[i]},n.timeout)})},e.prototype.handleResponse=function(e){var t;this.requestCallbacks[e.id]?(this.requestCallbacks[e.id].resolve(e.responseData),delete this.requestCallbacks[e.id]):null===(t=this.logger)||void 0===t||t.warn("No callback found for request id: ".concat(e.id))},e.prototype.registerActionHandler=function(e,t){var n,r,i,o;this.actionHandlers.has(e)&&(null===(o=null===(i=this.logger)||void 0===i?void 0:i.warn)||void 0===o||o.call(i,"Overwriting existing action handler for: ".concat(e))),this.actionHandlers.set(e,t);var s=this.pendingMessages.get(e);if(s){this.pendingMessages.delete(e);try{for(var a=c(s),l=a.next();!l.done;l=a.next()){t(l.value)}}catch(e){n={error:e}}finally{try{l&&!l.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}}},e.prototype.loadScriptOnce=function(e){return a(this,void 0,void 0,function(){var t,n,r;return l(this,function(i){switch(i.label){case 0:if(t=this.scriptLoadPromises.get(e))return[2,t];n=function(e){return document.querySelector('script[src="'.concat(CSS.escape(e),'"]'))?Promise.resolve({status:!0}):new Promise(function(t,n){var r;try{var i=document.createElement("script");i.type="text/javascript",i.async=!0,i.src=e,i.addEventListener("load",function(){t({status:!0})},{once:!0}),i.addEventListener("error",function(){n({status:!1,message:"Failed to load the script ".concat(e)})}),null===(r=document.head)||void 0===r||r.appendChild(i)}catch(e){n(e)}})}(e).then(function(){}),this.scriptLoadPromises.set(e,n),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,n];case 2:return i.sent(),[3,4];case 3:throw r=i.sent(),this.scriptLoadPromises.delete(e),r;case 4:return[2]}})})},e.prototype.setup=function(e){var t,n,r=this,i=void 0===e?{}:e,o=i.logger,s=i.endpoint;o&&(this.logger=o),s&&this.endpoint===te&&(this.endpoint=s),this.isSetup||(this.isSetup=!0,null===(n=null===(t=this.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Setting up messenger"),this.messageHandler=function(e){var t,n,i,o,s;if(null===(n=null===(t=r.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Message received: ",JSON.stringify(e)),r.endpoint===e.origin){var a=e.data,l=null==a?void 0:a.action;if(l)if("id"in a&&a.id)null===(o=null===(i=r.logger)||void 0===i?void 0:i.debug)||void 0===o||o.call(i,"Received Response to previous request: ",JSON.stringify(e)),r.handleResponse(a);else{if("ping"===l)return void r.notify({action:"pong"});var c=r.actionHandlers.get(l);if(c)c(a.data);else{var u=null!==(s=r.pendingMessages.get(l))&&void 0!==s?s:[];u.push(a.data),r.pendingMessages.set(l,u)}}}},window.addEventListener("message",this.messageHandler),this.notify({action:"page-loaded"}))},e.prototype.destroy=function(){this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.isSetup=!1,this.actionHandlers.clear(),this.pendingMessages.clear(),this.requestCallbacks={},this.scriptLoadPromises.clear();var e=g();(null==e?void 0:e[ie])===this&&delete e[ie]},e}();function se(e){var t,n=g(),r=null==n?void 0:n[ie];if("object"==typeof(t=r)&&null!==t&&re in t&&!0===t[re])return r;var i=new oe(e);return n&&(n[ie]=i),i}ee=re;var ae=["desktop","tablet","mobile"],le="__AMPLITUDE_BACKGROUND_CAPTURE__";function ce(e,t){var n,r=e;if(!0!==r[le]){r[le]=!0;var i=null!==(n=null==t?void 0:t.scriptUrl)&&void 0!==n?n:"https://cdn.amplitude.com/libs/background-capture-1.1.0.js.gz",s=null,a=function(t,n){var r,i;"background-capture-complete"===t&&(null===(i=null===(r=e.logger)||void 0===r?void 0:r.debug)||void 0===i||i.call(r,"Background capture complete"),e.notify({action:"background-capture-complete",data:n}))};e.registerActionHandler("initialize-background-capture",function(t){var n,r;null===(r=null===(n=e.logger)||void 0===n?void 0:n.debug)||void 0===r||r.call(n,"Initializing background capture (external script)");var l=new URL(i,e.endpoint).toString(),c=t&&"object"==typeof t?function(e){if("string"==typeof e)return ae.includes(e)?e:void 0}(t.deviceMode):void 0;e.loadScriptOnce(l).then(function(){var t,n,r;null===(n=null===(t=e.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Background capture script loaded (external)"),s=null===(r=null===window||void 0===window?void 0:window.amplitudeBackgroundCapture)||void 0===r?void 0:r.call(window,o({messenger:e,onBackgroundCapture:a},void 0!==c?{initialDeviceMode:c}:{})),e.notify({action:"background-capture-loaded"})}).catch(function(){var t;null===(t=e.logger)||void 0===t||t.warn("Failed to initialize background capture")})}),e.registerActionHandler("close-background-capture",function(){var e;null===(e=null==s?void 0:s.close)||void 0===e||e.call(s),s=null})}}var ue,de="[Amplitude]",ve="".concat(de," Session Replay ID"),he=$.US,fe={enabled:!0},ge=1e3,pe="".concat(de," Session Replay Debug"),me="https://api-sr.amplitude.com/sessions/v2/track",ye="https://api-sr.eu.amplitude.com/sessions/v2/track",be="https://api-sr.stag2.amplitude.com/sessions/v2/track",Se=9e6,Ie=/payload.*exceed/i,we=500,Ce=1e4,Ee=1024,Pe="X-Session-Replay-Event-Skipped",ke="amplitude-sr-iframe";!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",e.REPLAY_GATE_DECISION="replay-gate-decision"}(ue||(ue={}));var xe=function(){function e(e){this.logger=e,this.log=this.getSafeMethod("log"),this.warn=this.getSafeMethod("warn"),this.error=this.getSafeMethod("error"),this.debug=this.getSafeMethod("debug")}return e.prototype.getSafeMethod=function(e){var t;if(!this.logger)return function(){};var n=this.logger[e];return"function"==typeof n?(null!==(t=n.__rrweb_original__)&&void 0!==t?t:n).bind(this.logger):function(){}},e.prototype.enable=function(e){this.logger.enable(e)},e.prototype.disable=function(){this.logger.disable()},e}(),Me="medium";var Te=new Map,Re=function(e){var t=Te.get(e);if(t)return t;var n="\0TRAIL\0",r="\0MID\0",i="\0DS\0",o="\0ST\0",s="\0QU\0",a=e;a=(a=(a=(a=(a=(a=(a=(a=(a=(a=(a=a.replace(/\/\*\*$/,n)).replace(/\/\*\*\//g,r)).replace(/\*\*/g,i)).replace(/\*/g,o)).replace(/\?/g,s)).replace(/[.+^${}()|[\]\\]/g,"\\$&")).split(n).join("(/.*)?")).split(r).join("/(.*\\/)?")).split(i).join(".*")).split(o).join(".*")).split(s).join(".");var l=new RegExp("^".concat(a,"$"));return Te.set(e,l),l},Oe=function(e,t,n){switch(t){case"light":if("input"!==e)return!1;var r=n?function(e){var t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?t.toLowerCase():null}(n):"";return!!r&&(!!["password","hidden","email","tel"].includes(r)||!!n.autocomplete.startsWith("cc-"));case"medium":return"input"===e;case"conservative":return!0;default:return Oe(e,Me,n)}},_e=function(e,t){var n,r,i;if(e&&t.urlMaskLevels)try{for(var o=c(t.urlMaskLevels),s=o.next();!s.done;s=o.next()){var a=s.value;if(Re(a.match).test(e))return a.maskLevel}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return null!==(i=t.defaultMaskLevel)&&void 0!==i?i:Me},Le=function(e,t,n,r){var i,o;if(void 0===t&&(t={defaultMaskLevel:Me}),n){if(n.closest(".amp-mask, [data-amp-mask]"))return!0;var s=(null!==(i=t.maskSelector)&&void 0!==i?i:[]).some(function(e){return n.closest(e)});if(s)return!0;if(n.closest(".amp-unmask, [data-amp-unmask]"))return!1;var a=(null!==(o=t.unmaskSelector)&&void 0!==o?o:[]).some(function(e){return n.closest(e)});if(a)return!1}return Oe(e,_e(r,t),n)},Fe=function(e,t,n){return function(r,i){return Le(e,t,i,null==n?void 0:n())?r.replace(/[^\s]/g,"*"):r}},De=function(e,t){return function(n,r,i){var o;if("style"===n)return r;if(!(null!==(o=null==e?void 0:e.maskAttributes)&&void 0!==o?o:[]).includes(n))return r;var s=["INPUT","SELECT","TEXTAREA"].includes(i.tagName)?"input":"text";return Le(s,e,i,null==t?void 0:t())?r.replace(/[^\s]/g,"*"):r}},qe=function(e){var t=null==e?void 0:e.blockSelector;return d(d([],u("string"==typeof t?t?[t]:[]:null!=t?t:[]),!1),["[data-amp-block]"],!1).join(",")},Ae=function(e,t){var n,r;return e&&("conservative"===_e(t,e)||"conservative"===e.defaultMaskLevel||(null===(n=e.urlMaskLevels)||void 0===n?void 0:n.some(function(e){return"conservative"===e.maskLevel})))?"*":d(d([],u(null!==(r=null==e?void 0:e.maskSelector)&&void 0!==r?r:[]),!1),["[data-amp-mask]"],!1).join(",")};function je(e,t){return t||("STAGING"===e?be:"EU"===e?ye:me)}var Ne=function(){var e=g();return(null==e?void 0:e.location)?e.location.href:""},Ue=function(e,t){var n,r;try{for(var i=c(t),o=i.next();!o.done;o=i.next()){var s=o.value,a=Re(s.selector);if(a.test(e))return e.replace(a,s.replacement)}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return e},Be=function(){return a(void 0,void 0,void 0,function(){var e,t,n,r,i,o,s;return l(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),(e=g())?[4,e.navigator.storage.estimate()]:[3,2];case 1:return t=a.sent(),n=t.usage,r=t.quota,i=t.usageDetails,o=n?Math.round(n/Ee):0,s=n&&r?Math.round(1e3*(n/r+Number.EPSILON))/1e3:0,[2,{totalStorageSize:o,percentOfQuota:s,usageDetails:JSON.stringify(i)}];case 2:return[3,4];case 3:return a.sent(),[3,4];case 4:return[2,{totalStorageSize:0,percentOfQuota:0,usageDetails:""}]}})})},We=function(e){var t=o({},e),n=t.apiKey;return t.apiKey="****".concat(n.substring(n.length-4)),t},ze=function(){return{flushMaxRetries:2,logLevel:C.Warn,loggerProvider:new M,transportProvider:new Q}},Ke=function(e){function t(t,n){var r,i,s,a,l,c,v,h,f,g,p,m,y,b,S=this,I=ze();(S=e.call(this,o(o({transportProvider:I.transportProvider,loggerProvider:new xe(n.loggerProvider||I.loggerProvider)},n),{apiKey:t}))||this).flushMaxRetries=void 0!==n.flushMaxRetries&&n.flushMaxRetries<=I.flushMaxRetries?n.flushMaxRetries:I.flushMaxRetries,S.apiKey=t,S.sampleRate=n.sampleRate||0,S.serverZone=n.serverZone||he,S.configServerUrl=n.configServerUrl,S.trackServerUrl=n.trackServerUrl,S.shouldInlineStylesheet=n.shouldInlineStylesheet,S.inlineImages=n.inlineImages,S.version=n.version,S.performanceConfig=n.performanceConfig||fe,S.storeType=null!==(r=n.storeType)&&void 0!==r?r:"memory",S.applyBackgroundColorToBlockedElements=null!==(i=n.applyBackgroundColorToBlockedElements)&&void 0!==i&&i,S.enableUrlChangePolling=null!==(s=n.enableUrlChangePolling)&&void 0!==s&&s,S.urlChangePollingInterval=null!==(a=n.urlChangePollingInterval)&&void 0!==a?a:ge,S.captureDocumentTitle=null!==(l=n.captureDocumentTitle)&&void 0!==l&&l,void 0!==n.fullSnapshotIntervalMs&&(S.fullSnapshotIntervalMs=n.fullSnapshotIntervalMs),void 0!==n.eagerFullSnapshotSend&&(S.eagerFullSnapshotSend=n.eagerFullSnapshotSend),S.captureFullSnapshotOnFocus=null!==(c=n.captureFullSnapshotOnFocus)&&void 0!==c&&c,void 0!==n.maxPersistedEventsSizeBytes&&(S.maxPersistedEventsSizeBytes=$e(n.maxPersistedEventsSizeBytes,Ge,Qe,"maxPersistedEventsSizeBytes",S.loggerProvider)),void 0!==n.maxSingleEventSizeBytes&&(S.maxSingleEventSizeBytes=$e(n.maxSingleEventSizeBytes,Ge,Je,"maxSingleEventSizeBytes",S.loggerProvider)),S.privacyConfig=o(o({},null!==(v=n.privacyConfig)&&void 0!==v?v:{}),{unmaskSelector:Array.from(new Set(d([".".concat("amp-unmask")],u(null!==(f=null===(h=n.privacyConfig)||void 0===h?void 0:h.unmaskSelector)&&void 0!==f?f:[]),!1)))}),n.interactionConfig&&(S.interactionConfig=n.interactionConfig,S.interactionConfig.ugcFilterRules&&function(e){if(!e.every(function(e){return"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(function(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")}(S.interactionConfig.ugcFilterRules)),n.debugMode&&(S.debugMode=n.debugMode);var w=n;return S.useWebWorker=null===(m=null!==(g=n.useWebWorker)&&void 0!==g?g:null===(p=w.experimental)||void 0===p?void 0:p.useWebWorker)||void 0===m||m,S.enableTransportCompression=null===(y=n.enableTransportCompression)||void 0===y||y,S.sendTimeoutMs=n.sendTimeoutMs,S.captureAdoptedStyleSheets=null===(b=n.captureAdoptedStyleSheets)||void 0===b||b,n.crossOriginIframes&&(S.crossOriginIframes=n.crossOriginIframes),n.flushIntervalConfig?S.flushIntervalConfig=function(e,t){var n,r,i={};void 0!==e.minIntervalMs&&(!Number.isFinite(e.minIntervalMs)||e.minIntervalMs<He?(t.warn("flushIntervalConfig.minIntervalMs ".concat(e.minIntervalMs," is below floor ").concat(He,"ms; clamping.")),i.minIntervalMs=He):i.minIntervalMs=e.minIntervalMs);void 0!==e.maxIntervalMs&&(Number.isNaN(e.maxIntervalMs)||e.maxIntervalMs<He?(t.warn("flushIntervalConfig.maxIntervalMs ".concat(e.maxIntervalMs," is below floor ").concat(He,"ms; clamping.")),i.maxIntervalMs=He):i.maxIntervalMs=e.maxIntervalMs);if(void 0!==i.minIntervalMs||void 0!==i.maxIntervalMs){var o=null!==(n=i.minIntervalMs)&&void 0!==n?n:we,s=null!==(r=i.maxIntervalMs)&&void 0!==r?r:Ce;s<o&&(void 0===i.maxIntervalMs?(t.warn("flushIntervalConfig.minIntervalMs (".concat(o,") exceeds the default maxIntervalMs (").concat(Ce,"); raising max to match min.")),i.maxIntervalMs=o):void 0===i.minIntervalMs?(t.warn("flushIntervalConfig.maxIntervalMs (".concat(s,") is below the default minIntervalMs (").concat(we,"); lowering min to match max.")),i.minIntervalMs=s):(t.warn("flushIntervalConfig.maxIntervalMs (".concat(i.maxIntervalMs,") is less than minIntervalMs (").concat(i.minIntervalMs,"); raising max to match min.")),i.maxIntervalMs=i.minIntervalMs))}return i}(n.flushIntervalConfig,S.loggerProvider):S.flushIntervalConfig={minIntervalMs:1e3,maxIntervalMs:1e4},S.handleSendEvents=n.handleSendEvents,S.handleFetchConfig=n.handleFetchConfig,S}return n(t,e),t}(O),He=100,Ge=1e3,Qe=8e6,Je=1e7;function $e(e,t,n,r,i){if(Number.isFinite(e))return e<t?(i.warn("".concat(r," ").concat(e," is below floor ").concat(t,"; clamping.")),t):e>n?(i.warn("".concat(r," ").concat(e," exceeds ceiling ").concat(n,"; clamping.")),n):e;i.warn("".concat(r," value is not a finite number (got ").concat(String(e),"); ignoring."))}var Ze=(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))(Ze||{}),Ve=(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(Ve||{}),Xe=(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))(Xe||{}),Ye=function(e,t){var n=document.createDocumentFragment();return function(e,t,n){var r,i,s=o({},e);try{for(var a=c(["blockSelector","maskSelector","unmaskSelector"]),l=a.next();!l.done;l=a.next()){var u=l.value,d=e[u],v=("string"==typeof d?[d]:null!=d?d:[]).filter(function(e){try{return t(e),!0}catch(t){if(!n)throw new Error("Invalid privacy selector: ".concat(e));return n(e),!1}});s[u]=v.length?v:void 0}}catch(e){r={error:e}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}return s}(e,function(e){n.querySelector(e)},function(e){t.warn('[session-replay-browser] omitting selector "'.concat(e,'" because it is invalid'))})},et=function(){function e(e,t){this.localConfig=t,this.remoteConfigClient=e}return e.prototype.generateJoinedConfig=function(){var e,t,n,r,i,s,v;return a(this,void 0,void 0,function(){var a,h,f,g,p,m,y,b,S,I,w,C,E,P,k,x,M,T=this;return l(this,function(l){switch(l.label){case 0:(a=o({},this.localConfig)).optOut=this.localConfig.optOut,a.captureEnabled=!0,l.label=1;case 1:return l.trys.push([1,3,,4]),[4,new Promise(function(e,t){T.remoteConfigClient.subscribe("configs.sessionReplay",{timeout:1500},function(n,r){var i;if(T.localConfig.loggerProvider.debug("Session Replay remote configuration received from ".concat(r,":"),JSON.stringify(n,null,2)),n){var o=n,s=o.sr_sampling_config,l=o.sr_privacy_config,c=o.sr_targeting_config,u=null===(i=a.interactionConfig)||void 0===i?void 0:i.ugcFilterRules;a.interactionConfig=o.sr_interaction_config,a.interactionConfig&&u&&(a.interactionConfig.ugcFilterRules=u),a.loggingConfig=o.sr_logging_config,(s||l||c)&&(h={},s&&(h.sr_sampling_config=s),l&&(h.sr_privacy_config=l),c&&(h.sr_targeting_config=c)),e()}else t(new Error("No remote config received"))})})];case 2:return l.sent(),[3,4];case 3:return f=l.sent(),this.localConfig.loggerProvider.error("Failed to generate joined config: ",f),a.captureEnabled=!1,[2,{localConfig:this.localConfig,joinedConfig:a,remoteConfig:void 0}];case 4:if(!h)return[2,{localConfig:this.localConfig,joinedConfig:a,remoteConfig:h}];if(g=h.sr_sampling_config,p=h.sr_privacy_config,m=h.sr_targeting_config,g&&Object.keys(g).length>0?(Object.prototype.hasOwnProperty.call(g,"capture_enabled")?a.captureEnabled=g.capture_enabled:a.captureEnabled=!1,Object.prototype.hasOwnProperty.call(g,"sample_rate")&&(a.sampleRate=g.sample_rate),Object.prototype.hasOwnProperty.call(g,"min_session_duration_ms")&&(a.minSessionDurationMs=this.sanitizeMinSessionDurationMs(g.min_session_duration_ms))):(a.captureEnabled=!0,this.localConfig.loggerProvider.debug("Remote config successfully fetched, but no values set for project, Session Replay capture enabled.")),p){y=null!==(e=a.privacyConfig)&&void 0!==e?e:{},b={defaultMaskLevel:null!==(n=null!==(t=p.defaultMaskLevel)&&void 0!==t?t:y.defaultMaskLevel)&&void 0!==n?n:"medium",blockSelector:[],maskSelector:[],unmaskSelector:[],maskAttributes:d([],u(new Set(d(d([],u(null!==(r=y.maskAttributes)&&void 0!==r?r:[]),!1),u(null!==(i=p.maskAttributes)&&void 0!==i?i:[]),!1))),!1),urlMaskLevels:d(d([],u(null!==(s=p.urlMaskLevels)&&void 0!==s?s:[]),!1),u(null!==(v=y.urlMaskLevels)&&void 0!==v?v:[]),!1)},S=function(e){var t,n,r,i,o,s,a,l,u,d={};"string"==typeof e.blockSelector&&(e.blockSelector=[e.blockSelector]);try{for(var v=c(null!==(a=e.blockSelector)&&void 0!==a?a:[]),h=v.next();!h.done;h=v.next()){d[h.value]="block"}}catch(e){t={error:e}}finally{try{h&&!h.done&&(n=v.return)&&n.call(v)}finally{if(t)throw t.error}}try{for(var f=c(null!==(l=e.maskSelector)&&void 0!==l?l:[]),g=f.next();!g.done;g=f.next()){d[g.value]="mask"}}catch(e){r={error:e}}finally{try{g&&!g.done&&(i=f.return)&&i.call(f)}finally{if(r)throw r.error}}try{for(var p=c(null!==(u=e.unmaskSelector)&&void 0!==u?u:[]),m=p.next();!m.done;m=p.next()){d[m.value]="unmask"}}catch(e){o={error:e}}finally{try{m&&!m.done&&(s=p.return)&&s.call(p)}finally{if(o)throw o.error}}return d},I=o(o({},S(y)),S(p));try{for(w=c(Object.entries(I)),C=w.next();!C.done;C=w.next())E=u(C.value,2),P=E[0],"mask"===(k=E[1])?b.maskSelector.push(P):"block"===k?b.blockSelector.push(P):"unmask"===k&&b.unmaskSelector.push(P)}catch(e){x={error:e}}finally{try{C&&!C.done&&(M=w.return)&&M.call(w)}finally{if(x)throw x.error}}a.privacyConfig=Ye(b,this.localConfig.loggerProvider)}return m&&Object.keys(m).length>0&&(a.targetingConfig=m),this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:We(a)},null,2)),[2,{localConfig:this.localConfig,joinedConfig:a,remoteConfig:h}]}})})},e.prototype.sanitizeMinSessionDurationMs=function(e){if("number"==typeof e&&Number.isFinite(e)){if(!(e<0))return e>tt?(this.localConfig.loggerProvider.warn("min_session_duration_ms remote value ".concat(e," exceeds ").concat(tt,"ms ceiling; clamping.")),tt):e;this.localConfig.loggerProvider.warn("min_session_duration_ms remote value is negative (".concat(e,"); ignoring."))}else this.localConfig.loggerProvider.warn("min_session_duration_ms remote value is not a finite number (got ".concat(String(e),"); ignoring."))},e}(),tt=6e4,nt=function(e,t){return a(void 0,void 0,void 0,function(){var n,r;return l(this,function(i){return n=new Ke(e,t),r=new Y(e,n.loggerProvider,n.serverZone,t.configServerUrl,t.handleFetchConfig),[2,new et(r,n)]})})};function rt(e){if(e.type!==Ze.IncrementalSnapshot)return!1;var t=e.data;return t.source===Ve.Mutation&&!t.isAttachIframe}function it(e){var t,n,r=new Map;if(e.forEach(function(e,t){if(e.attributes&&"style"in e.attributes){var n=r.get(e.id);n?n.push(t):r.set(e.id,[t])}}),0===r.size)return e;var i=function(t){return e[t].attributes.style},s=new Set,a=new Map,l=function(e){if(1===e.length)return"continue";var t=-1;e.forEach(function(e,n){var r;("object"!=typeof(r=i(e))||null===r)&&(t=n)});var n=[];if(e.forEach(function(e,r){r!==t&&(s.add(e),r>t&&n.push(e))}),n.length>0){var r=n[n.length-1],o=function(e){var t,n,r,i,o={};try{for(var s=c(e),a=s.next();!a.done;a=s.next()){var l=a.value;try{for(var u=(r=void 0,c(Object.keys(l))),d=u.next();!d.done;d=u.next()){var v=d.value;o[v]=l[v]}}catch(e){r={error:e}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(r)throw r.error}}}}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}return o}(n.map(function(e){return i(e)}));s.delete(r),a.set(r,o)}};try{for(var u=c(r.values()),d=u.next();!d.done;d=u.next()){l(d.value)}}catch(e){t={error:e}}finally{try{d&&!d.done&&(n=u.return)&&n.call(u)}finally{if(t)throw t.error}}if(0===s.size&&0===a.size)return e;var v=[];return e.forEach(function(e,t){var n=a.get(t);if(void 0===n)if(s.has(t)){var r=o({},e.attributes);delete r.style,Object.keys(r).length>0&&v.push(o(o({},e),{attributes:r}))}else v.push(e);else v.push(o(o({},e),{attributes:o(o({},e.attributes),{style:n})}))}),v}function ot(e){var t,n,r,i,s=e[0],a=new Map,l=new Map,d=new Map,v=new Map,h=new Map;e.forEach(function(e,t){var n,r,i,o,s=e.data;try{for(var u=c(s.adds),f=u.next();!f.done;f=u.next()){var g=f.value;a.has(g.node.id)||a.set(g.node.id,t),l.set(g.node.id,t),h.set(g.node.id,g.parentId)}}catch(e){n={error:e}}finally{try{f&&!f.done&&(r=u.return)&&r.call(u)}finally{if(n)throw n.error}}try{for(var p=c(s.removes),m=p.next();!m.done;m=p.next()){var y=m.value;d.has(y.id)||d.set(y.id,t),v.set(y.id,t)}}catch(e){i={error:e}}finally{try{m&&!m.done&&(o=p.return)&&o.call(p)}finally{if(i)throw i.error}}});var f=new Set,g=new Set;try{for(var p=c(a),m=p.next();!m.done;m=p.next()){var y=u(m.value,2),b=y[0],S=y[1],I=d.get(b);if(void 0!==I)l.get(b)>=v.get(b)||(S<I?f.add(b):I<S&&g.add(b))}}catch(e){t={error:e}}finally{try{m&&!m.done&&(n=p.return)&&n.call(p)}finally{if(t)throw t.error}}var w=new Set;if(f.size>0||g.size>0)for(var C=!0;C;){C=!1;try{for(var E=(r=void 0,c(h)),P=E.next();!P.done;P=E.next()){var k=u(P.value,2),x=k[0],M=k[1];if(!f.has(x)&&!g.has(x)&&!w.has(x)&&(f.has(M)||g.has(M)||w.has(M))){var T=d.get(x),R=a.get(x);void 0!==T&&void 0!==R&&T<R?g.add(x):void 0!==T&&void 0!==R&&T===R?w.add(x):f.add(x),C=!0}}}catch(e){r={error:e}}finally{try{P&&!P.done&&(i=E.return)&&i.call(E)}finally{if(r)throw r.error}}}var O=f.size>0||g.size>0||w.size>0,_=[];e.forEach(function(e,t){var n,r;try{for(var i=c(e.data.removes),o=i.next();!o.done;o=i.next()){var s=o.value;f.has(s.id)||(g.has(s.id)&&t>=a.get(s.id)||w.has(s.id)&&(f.has(s.parentId)||g.has(s.parentId)||w.has(s.parentId))||_.push(s))}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}});var L=e.flatMap(function(e){return e.data.adds}),F=e.flatMap(function(e){return e.data.texts}),D=e.flatMap(function(e){return e.data.attributes}),q=O?D.filter(function(e){return!f.has(e.id)&&!g.has(e.id)&&!w.has(e.id)}):D,A={source:Ve.Mutation,removes:_,adds:O?L.filter(function(e){return!f.has(e.node.id)&&!g.has(e.node.id)&&!w.has(e.node.id)}):L,texts:O?F.filter(function(e){return!f.has(e.id)&&!g.has(e.id)&&!w.has(e.id)}):F,attributes:it(q)};return o(o({},s),{data:A})}function st(e){if(e.length<=1)return e;for(var t=[],n=0;n<e.length;)if(rt(e[n])){for(var r=n+1;r<e.length&&rt(e[r]);)r++;t.push(r>n+1?ot(e.slice(n,r)):e[n]),n=r}else t.push(e[n]),n++;return t}var at=function(){function e(e,t,n,r,i){var o,s=this;this.taskQueue=[],this.pendingQueue=[],this.isProcessing=!1,this.compressEvent=function(e){var t=e,n=t.type,r=t.timestamp,i=t.delay,o=t.data;return null!=i?JSON.stringify({type:n,timestamp:r,delay:i,data:o}):JSON.stringify({type:n,timestamp:r,data:o})},this.addCompressedEventToManager=function(e,t){var n,r=new Blob([e]).size;r>(null!==(n=s.config.maxSingleEventSizeBytes)&&void 0!==n?n:Se)?s.config.loggerProvider.warn("Session replay event dropped: serialized size ".concat(Math.round(r/1024)," KB exceeds maximum allowed event size. If this recurs, please open a GitHub issue at https://github.com/amplitude/Amplitude-TypeScript/issues or contact Amplitude support.")):s.eventsManager&&s.deviceId&&s.eventsManager.addEvent({event:{type:"replay",data:e},sessionId:t,deviceId:s.deviceId})},this.addCompressedEvent=function(e,t){if(s.worker)try{s.worker.postMessage({event:e,sessionId:t})}catch(n){"DataCloneError"===n.name?s.worker.postMessage(JSON.stringify({event:e,sessionId:t})):s.config.loggerProvider.warn("Unexpected error while posting message to worker:",n)}else{var n=s.compressEvent(e);s.addCompressedEventToManager(n,t)}},this.flushQueue=function(){var e;for(s.pendingQueue.length>0&&(e=s.taskQueue).push.apply(e,d([],u(s.mergeMutationTasks(s.pendingQueue.splice(0))),!1));s.taskQueue.length>0;){var t=s.taskQueue.shift();if(t){var n=t.event,r=t.sessionId,i=s.compressEvent(n);s.addCompressedEventToManager(i,r)}}s.isProcessing=!1},this.terminate=function(){var e;null===(e=s.worker)||void 0===e||e.terminate()};var a=g();if(this.canUseIdleCallback=a&&"requestIdleCallback"in a,this.eventsManager=e,this.config=t,this.deviceId=n,this.timeout=(null===(o=t.performanceConfig)||void 0===o?void 0:o.timeout)||2e3,this.onFullSnapshotProcessed=i,r){t.loggerProvider.log("Enabling web worker for compression");try{var l=new Blob([r],{type:"application/javascript"}),c=URL.createObjectURL(l),v=new Worker(c);v.onerror=function(e){e.preventDefault(),t.loggerProvider.error("Worker failed, falling back to non-worker compression: ".concat(e.message," (").concat(e.filename,":").concat(e.lineno,")")),v.terminate(),s.worker=void 0},v.onmessage=function(e){var t=e.data,n=t.compressedEvent,r=t.sessionId;s.addCompressedEventToManager(n,r)},this.worker=v}catch(e){t.loggerProvider.error("Failed to create worker, falling back to non-worker compression:",e)}}}return e.prototype.scheduleIdleProcessing=function(){var e=this;this.isProcessing||(this.isProcessing=!0,requestIdleCallback(function(t){e.processQueue(t)},{timeout:this.timeout}))},e.prototype.enqueueEvent=function(e,t){var n,r,i,o;if(e.type===Ze.FullSnapshot){if(this.config.loggerProvider.debug("Processing full snapshot immediately."),this.taskQueue.length>0||this.pendingQueue.length>0){var s=d(d([],u(this.taskQueue.splice(0)),!1),u(this.mergeMutationTasks(this.pendingQueue.splice(0))),!1);try{for(var a=c(s),l=a.next();!l.done;l=a.next()){var v=l.value,h=this.compressEvent(v.event);this.addCompressedEventToManager(h,v.sessionId)}}catch(e){n={error:e}}finally{try{l&&!l.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}this.isProcessing=!1}var f=this.compressEvent(e);return this.addCompressedEventToManager(f,t),void(null===(i=this.onFullSnapshotProcessed)||void 0===i||i.call(this))}this.canUseIdleCallback&&(null===(o=this.config.performanceConfig)||void 0===o?void 0:o.enabled)?(this.config.loggerProvider.debug("Enqueuing event for processing during idle time."),this.pendingQueue.push({event:e,sessionId:t}),this.scheduleIdleProcessing()):(this.config.loggerProvider.debug("Processing event without idle callback."),this.addCompressedEvent(e,t))},e.prototype.processQueue=function(e){var t,n=this;for(this.pendingQueue.length>0&&(t=this.taskQueue).push.apply(t,d([],u(this.mergeMutationTasks(this.pendingQueue.splice(0))),!1));this.taskQueue.length>0&&(e.timeRemaining()>0||e.didTimeout);){var r=this.taskQueue.shift();if(r){var i=r.event,o=r.sessionId;this.addCompressedEvent(i,o)}}this.taskQueue.length>0||this.pendingQueue.length>0?requestIdleCallback(function(e){n.processQueue(e)},{timeout:this.timeout}):this.isProcessing=!1},e.prototype.mergeMutationTasks=function(e){var t,n,r;if(!1===(null===(r=this.config.performanceConfig)||void 0===r?void 0:r.mergeMutations))return e;if(e.length<=1)return e;for(var i=[],o=0;o<e.length;){for(var s=e[o].sessionId,a=o+1;a<e.length&&e[a].sessionId===s;)a++;var l=st(e.slice(o,a).map(function(e){return e.event}));try{for(var u=(t=void 0,c(l)),d=u.next();!d.done;d=u.next()){var v=d.value;i.push({event:v,sessionId:s})}}catch(e){t={error:e}}finally{try{d&&!d.done&&(n=u.return)&&n.call(u)}finally{if(t)throw t.error}}o=a}return i},e}(),lt="Session replay event batch rejected due to exceeded retry count",ct="Failed to store session replay events in IndexedDB",ut="Session replay event batch dropped: server signalled capture disabled or session out of valid range for this session",dt="1.51.0";function vt(e,t){return a(this,void 0,void 0,function(){var n,r,i,o,s,u,d,v,h,f,g,p,m,y,b=this;return l(this,function(S){switch(S.label){case 0:return S.trys.push([0,4,,5]),n=t.CompressionStream,r=new n("gzip"),i=r.writable.getWriter(),o=r.readable.getReader(),s=[],u=a(b,void 0,void 0,function(){var e,t,n;return l(this,function(r){switch(r.label){case 0:return[4,o.read()];case 1:if(e=r.sent(),t=e.done,n=e.value,t)return[3,3];s.push(n),r.label=2;case 2:return[3,0];case 3:return[2]}})}),[4,i.write((new TextEncoder).encode(e))];case 1:return S.sent(),[4,i.close()];case 2:return S.sent(),[4,u];case 3:S.sent(),d=s.reduce(function(e,t){return e+t.length},0),v=new Uint8Array(d),h=0;try{for(f=c(s),g=f.next();!g.done;g=f.next())p=g.value,v.set(p,h),h+=p.length}catch(e){m={error:e}}finally{try{g&&!g.done&&(y=f.return)&&y.call(f)}finally{if(m)throw m.error}}return[2,v];case 4:return S.sent(),[2,null];case 5:return[2]}})})}var ht=function(){function e(e){var t=e.trackServerUrl,n=e.loggerProvider,r=e.payloadBatcher,i=e.workerScript,o=e.enableTransportCompression,s=e.sendTimeoutMs,a=e.handleSendEvents,l=this;if(this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.sendIdCounter=0,this.pendingWorkerRequests=new Map,this.timedOutWorkerRequests=new Map,this.flushPauseUntilMs=0,this.mergeOnNextFlush=!1,this.coalesceNextFlush=!1,this.mergeLogFiredThisPause=!1,this.killedSessions=new Set,this.loggerProvider=n,this.payloadBatcher=r||function(e){return e},this.trackServerUrl=t,this.enableTransportCompression=null==o||o,this.sendTimeoutMs=null!=s?s:1e4,this.handleSendEvents=a,i)try{var d=new Blob([i],{type:"application/javascript"}),v=URL.createObjectURL(d),h=new Worker(v);h.onerror=function(e){var t,r;e.preventDefault(),n.error("Track destination worker failed, falling back to main-thread sending: ".concat(e.message," (").concat(e.filename,":").concat(e.lineno,")")),h.terminate(),l.worker=void 0;try{for(var i=c(l.pendingWorkerRequests),o=i.next();!o.done;o=i.next()){var s=u(o.value,2)[1];s.timeout&&clearTimeout(s.timeout),n.warn("Session replay event send failed due to worker crash: ".concat(e.message)),s.resolve()}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}l.pendingWorkerRequests.clear(),l.timedOutWorkerRequests.clear()},h.onmessage=function(e){var t=e.data;if("log"===t.type)n.log(t.message);else if("warn"===t.type)n.warn(t.message);else if("payload_too_large"===t.type){var r=l.pendingWorkerRequests.get(t.id);if(r)r.timeout&&clearTimeout(r.timeout),l.handlePayloadTooLargeResponse(r.context,t.isWaf),r.resolve(),l.pendingWorkerRequests.delete(t.id);else(i=l.timedOutWorkerRequests.get(t.id))&&(l.timedOutWorkerRequests.delete(t.id),l.handlePayloadTooLargeResponse(i,t.isWaf))}else if("complete"===t.type){var i,o=l.pendingWorkerRequests.get(t.id);if(o)o.timeout&&clearTimeout(o.timeout),void 0!==t.skipCode&&l.applyServerDirective(o.context.sessionId,t.skipCode),l.completeRequest({context:o.context}),o.resolve(),l.pendingWorkerRequests.delete(t.id);else(i=l.timedOutWorkerRequests.get(t.id))&&(l.timedOutWorkerRequests.delete(t.id),void 0!==t.skipCode&&l.applyServerDirective(i.sessionId,t.skipCode),l.completeRequest({context:i}))}else"fetch-request"===t.type&&l.handleDelegatedFetch(h,t).catch(function(e){n.warn("Failed to handle delegated session replay fetch:",e)})},this.worker=h}catch(e){n.error("Failed to create track destination worker, falling back to main-thread sending:",e)}}return e.prototype.sendEventsList=function(e){this.addToQueue(o(o({},e),{attempts:0,timeout:0}))},e.prototype.markCoalesceNextFlush=function(){this.coalesceNextFlush=!0,this.schedule(0)},e.prototype.sendBeacon=function(e){var t,n,r=this,i=e.events,o=e.sessionId,s=e.deviceId,a=e.apiKey,l=e.serverZone,c=function(e){return new Blob([e]).size},u=i,d=JSON.stringify({version:2,events:u});if(c(d)>65536){for(var v=0,h=u.length;v<h;){var f=Math.floor((v+h+1)/2);c(JSON.stringify({version:2,events:u.slice(0,f)}))<=65536?v=f:h=f-1}u=u.slice(0,v),d=JSON.stringify({version:2,events:u}),this.loggerProvider.warn("sendBeacon payload exceeded 64 KB limit, trimmed from ".concat(i.length," to ").concat(u.length," events"))}if(0!==u.length)if(this.handleSendEvents){var p=new URLSearchParams({device_id:s,session_id:String(o),type:"replay"}),m="".concat(je(l,this.trackServerUrl),"?").concat(p.toString()),y={"Content-Type":"application/json",Accept:"*/*",Authorization:"Bearer ".concat(a)};this.loggerProvider.debug("Routing session replay exit batch (".concat(u.length," events) through custom transport for session id ").concat(o,"."));try{this.handleSendEvents({url:m,method:"POST",headers:y,body:d,keepalive:!0}).catch(function(e){r.loggerProvider.warn("Custom transport failed to send session replay exit batch:",e)})}catch(e){this.loggerProvider.warn("Custom transport threw while sending session replay exit batch:",e)}}else{var b=new URLSearchParams({device_id:s,session_id:String(o),type:"replay",api_key:a}),S="".concat(je(l,this.trackServerUrl),"?").concat(b.toString()),I=g();try{var w=new Blob([d],{type:"application/json"});!1===(null===(n=null===(t=null==I?void 0:I.navigator)||void 0===t?void 0:t.sendBeacon)||void 0===n?void 0:n.call(t,S,w))&&this.loggerProvider.warn("sendBeacon failed to queue session replay payload")}catch(e){}}},e.prototype.addToQueue=function(){for(var e=this,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];t.filter(function(t){return e.killedSessions.has(t.sessionId)?(e.completeRequest({context:t,err:ut}),!1):t.attempts<(t.flushMaxRetries||0)?(t.attempts+=1,!0):(e.completeRequest({context:t,err:lt}),!1)}).forEach(function(t){e.queue=e.queue.concat(t),e.schedule(0)})},e.prototype.schedule=function(e){var t=this;if(!this.scheduled){var n=this.flushPauseUntilMs-Date.now(),r=n>e?n:e;n>0&&(this.mergeOnNextFlush=!0),this.scheduled=setTimeout(function(){t.flush(!0).then(function(){t.queue.length>0&&t.schedule(e)})},r)}},e.prototype.flush=function(e){return void 0===e&&(e=!1),a(this,void 0,void 0,function(){var t,n,r,i,o,s,a;return l(this,function(l){switch(l.label){case 0:t=this.queue,this.queue=[],this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null),this.mergeOnNextFlush?(this.mergeOnNextFlush=!1,this.coalesceNextFlush=!1,t=this.mergeQueueAfterThrottle(t)):this.coalesceNextFlush&&(this.coalesceNextFlush=!1,t=this.mergeDrainBacklog(t)),l.label=1;case 1:l.trys.push([1,6,7,8]),n=c(t),r=n.next(),l.label=2;case 2:return r.done?[3,5]:(i=r.value,[4,this.send(i,e)]);case 3:l.sent(),l.label=4;case 4:return r=n.next(),[3,2];case 5:return[3,8];case 6:return o=l.sent(),s={error:o},[3,8];case 7:try{r&&!r.done&&(a=n.return)&&a.call(n)}finally{if(s)throw s.error}return[7];case 8:return[2]}})})},e.prototype.mergeQueueAfterThrottle=function(e){var t=this.coalesceByIdentity(e);return t.length<e.length&&!this.mergeLogFiredThisPause&&(this.mergeLogFiredThisPause=!0,this.loggerProvider.log("Session replay throttle pause ended; merged ".concat(e.length," queued batches into ").concat(t.length," request(s)"))),t},e.prototype.mergeDrainBacklog=function(e){var t=this.coalesceByIdentity(e);return t.length<e.length&&this.loggerProvider.log("Session replay coalesced ".concat(e.length," persisted page-load backlog batches into ").concat(t.length," request(s)")),t},e.prototype.coalesceByIdentity=function(e){var t,n,r,i,s,v,h,f,g,p,m,y=this;if(e.length<=1)return e;var b=new Map;try{for(var S=c(e),I=S.next();!I.done;I=S.next()){var w=I.value,C=[w.sessionId,null!==(s=w.deviceId)&&void 0!==s?s:"",null!==(v=w.apiKey)&&void 0!==v?v:"",w.type,null!==(h=w.serverZone)&&void 0!==h?h:"",w.sampleRate,null!==(g=null===(f=w.version)||void 0===f?void 0:f.type)&&void 0!==g?g:"",null!==(m=null===(p=w.version)||void 0===p?void 0:p.version)&&void 0!==m?m:""].join("|"),E=b.get(C);E?E.push(w):b.set(C,[w])}}catch(e){t={error:e}}finally{try{I&&!I.done&&(n=S.return)&&n.call(S)}finally{if(t)throw t.error}}var P=[],k=function(e){var t,n;if(1===e.length)return P.push(e[0]),"continue";var r=null,i=0,s=function(){r&&P.push(r),r=null,i=0},v=function(e){var t=e.events.reduce(function(e,t){return e+new Blob([t]).size},0);if(null===r)return r=o(o({},e),{events:d([],u(e.events),!1),attempts:0}),i=t,"continue";if(i+t>4e6)return s(),r=o(o({},e),{events:d([],u(e.events),!1),attempts:0}),i=t,"continue";var n=r.onComplete,c=e.onComplete;r.events=r.events.concat(e.events),i+=t,r.onComplete=function(){return a(y,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,Promise.allSettled([n(),c()])];case 1:return e.sent(),[2]}})})}};try{for(var h=(t=void 0,c(e)),f=h.next();!f.done;f=h.next()){v(f.value)}}catch(e){t={error:e}}finally{try{f&&!f.done&&(n=h.return)&&n.call(h)}finally{if(t)throw t.error}}s()};try{for(var x=c(b.values()),M=x.next();!M.done;M=x.next()){k(M.value)}}catch(e){r={error:e}}finally{try{M&&!M.done&&(i=x.return)&&i.call(x)}finally{if(r)throw r.error}}return P},e.prototype.send=function(e,t){return void 0===t&&(t=!0),a(this,void 0,void 0,function(){var n,r,i,o;return l(this,function(s){return this.killedSessions.has(e.sessionId)?[2,this.completeRequest({context:e,err:ut})]:(n=e.apiKey)?(r=e.deviceId)?0===(i=this.payloadBatcher({version:1,events:e.events})).events.length?(this.completeRequest({context:e}),[2]):(o=this.worker)?[2,this.sendViaWorker(o,e,i,t)]:[2,this.sendOnMainThread(n,r,e,i,t)]:[2,this.completeRequest({context:e,err:"Session replay event batch not sent due to missing device ID"})]:[2,this.completeRequest({context:e,err:"Session replay event batch not sent due to missing api key"})]})})},e.prototype.sendViaWorker=function(e,t,n,r){return a(this,void 0,void 0,function(){var i,o=this;return l(this,function(s){return i="".concat(++this.sendIdCounter),[2,new Promise(function(s){var a,l=o.sendTimeoutMs>0?setTimeout(function(){var e=o.pendingWorkerRequests.get(i);e&&(o.pendingWorkerRequests.delete(i),o.rememberTimedOutRequest(i,e.context),o.loggerProvider.warn("Session replay worker send timed out after ".concat(o.sendTimeoutMs,"ms; leaving events for retry")),e.resolve())},o.sendTimeoutMs):void 0;o.pendingWorkerRequests.set(i,{context:t,resolve:s,timeout:l}),e.postMessage({type:"send",id:i,payload:n,useRetry:r,useCustomTransport:!!o.handleSendEvents,context:{apiKey:t.apiKey,deviceId:t.deviceId,sessionId:t.sessionId,events:t.events,eventType:t.type,flushMaxRetries:null!==(a=t.flushMaxRetries)&&void 0!==a?a:0,sampleRate:t.sampleRate,serverZone:t.serverZone,trackServerUrl:o.trackServerUrl,version:t.version,currentUrl:Ne(),sdkVersion:dt,enableTransportCompression:o.enableTransportCompression,sendTimeoutMs:o.sendTimeoutMs}})})]})})},e.prototype.rememberTimedOutRequest=function(e,t){var n,r;if(this.timedOutWorkerRequests.set(e,t),this.timedOutWorkerRequests.size>256)try{for(var i=c(this.timedOutWorkerRequests.keys()),o=i.next();!o.done;o=i.next()){var s=o.value;this.timedOutWorkerRequests.delete(s);break}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}},e.prototype.handleDelegatedFetch=function(e,t){var n,r,i;return a(this,void 0,void 0,function(){var o,s,a,c,u,d,v,h,f,g,p;return l(this,function(l){switch(l.label){case 0:o=t.requestId,s=t.url,a=t.method,c=t.headers,u=t.body,d=t.keepalive,l.label=1;case 1:return l.trys.push([1,10,,11]),v=void 0,this.handleSendEvents?[4,this.handleSendEvents({url:s,method:a,headers:c,body:u,keepalive:d})]:[3,3];case 2:return v=l.sent(),[3,5];case 3:return this.loggerProvider.warn("Delegated session replay fetch received without a custom transport configured; falling back to built-in fetch."),[4,fetch(s,{method:a,headers:c,body:u,keepalive:d})];case 4:v=l.sent(),l.label=5;case 5:if(h=v.status,f=null,g="",h>=200&&h<300&&(f=null!==(i=null===(r=null===(n=v.headers)||void 0===n?void 0:n.get)||void 0===r?void 0:r.call(n,Pe))&&void 0!==i?i:null),413!==h)return[3,9];l.label=6;case 6:return l.trys.push([6,8,,9]),[4,v.text()];case 7:return g=l.sent(),[3,9];case 8:return l.sent(),[3,9];case 9:return this.loggerProvider.debug("Delegated session replay fetch (request ".concat(o,") returned status ").concat(h,".")),e.postMessage({type:"fetch-response",requestId:o,status:h,skipHeader:f,body:g}),[3,11];case 10:return p=l.sent(),this.loggerProvider.debug("Delegated session replay fetch (request ".concat(o,") failed:"),p),e.postMessage({type:"fetch-response",requestId:o,status:0,skipHeader:null,body:String(p),error:!0}),[3,11];case 11:return[2]}})})},e.prototype.sendOnMainThread=function(e,t,n,r,i){var s,c,u,d,v,h,f;return a(this,void 0,void 0,function(){var a,p,m,y,b,S,I,w,C,E,P,k,x,M,T,R,O,_,L,F,D,q;return l(this,function(l){switch(l.label){case 0:a=Ne(),p=dt,m=n.sampleRate,y=new URLSearchParams({device_id:t,session_id:"".concat(n.sessionId),type:"".concat(n.type)}),b="".concat(null!==(c=null===(s=n.version)||void 0===s?void 0:s.type)&&void 0!==c?c:"standalone","/").concat(null!==(d=null===(u=n.version)||void 0===u?void 0:u.version)&&void 0!==d?d:p),l.label=1;case 1:return l.trys.push([1,19,,23]),S=JSON.stringify(r),I=g(),this.enableTransportCompression&&I&&"CompressionStream"in I?[4,vt(S,I)]:[3,3];case 2:return C=l.sent(),[3,4];case 3:C=null,l.label=4;case 4:if(E=(w=C)?w.byteLength:new Blob([S]).size,P=new AbortController,k=o({"Content-Type":"application/json",Accept:"*/*",Authorization:"Bearer ".concat(e),"X-Client-Version":p,"X-Client-Library":b,"X-Client-Url":a.substring(0,1e3),"X-Client-Sample-Rate":"".concat(m),"X-Sampling-Hash-Alg":"xxhash32"},w?{"Content-Encoding":"gzip"}:{}),T={headers:k,body:x=null!=w?w:S,method:"POST",keepalive:M=E<=65536,signal:P.signal},R="".concat(je(n.serverZone,this.trackServerUrl),"?").concat(y.toString()),0===r.events.length)return this.completeRequest({context:n}),[2];O=this.sendTimeoutMs>0?setTimeout(function(){P.abort()},this.sendTimeoutMs):void 0,_=void 0,l.label=5;case 5:return l.trys.push([5,,10,11]),this.handleSendEvents?[4,(A=this.handleSendEvents({url:R,method:"POST",headers:k,body:x,keepalive:M}),j=P.signal,new Promise(function(e,t){var n=function(){var e=new Error("Custom session replay transport aborted by send timeout");e.name="AbortError",t(e)};j.addEventListener("abort",n,{once:!0}),A.then(function(t){j.removeEventListener("abort",n),e(t)},function(e){j.removeEventListener("abort",n),t(e)})}))]:[3,7];case 6:return L=l.sent(),[3,9];case 7:return[4,fetch(R,T)];case 8:L=l.sent(),l.label=9;case 9:return _=L,[3,11];case 10:return O&&clearTimeout(O),[7];case 11:if(null===_)return this.completeRequest({context:n,err:"Unexpected error occurred"}),[2];if(_.status>=200&&_.status<300&&(F=null!==(f=null===(h=null===(v=_.headers)||void 0===v?void 0:v.get)||void 0===h?void 0:h.call(v,Pe))&&void 0!==f?f:null,this.applyServerDirective(n.sessionId,F)),i)return[3,12];D="";try{D=JSON.stringify(_.body,null,2)}catch(e){}return this.completeRequest({context:n,success:"".concat(_.status,": ").concat(D)}),[3,18];case 12:if(D="",413!==_.status)return[3,16];l.label=13;case 13:return l.trys.push([13,15,,16]),[4,_.text()];case 14:return D=l.sent(),[3,16];case 15:return l.sent(),[3,16];case 16:return[4,this.handleReponse(_.status,n,D)];case 17:l.sent(),l.label=18;case 18:return[3,23];case 19:return q=l.sent(),!!q&&"object"==typeof q&&"AbortError"===q.name&&i?[4,this.handleOtherResponse(n)]:[3,21];case 20:return l.sent(),[3,22];case 21:this.completeRequest({context:n,err:q}),l.label=22;case 22:return[3,23];case 23:return[2]}var A,j})})},e.prototype.handleReponse=function(e,t,n){return void 0===n&&(n=""),a(this,void 0,void 0,function(){var r;return l(this,function(i){switch(i.label){case 0:switch(r=(new G).buildStatus(e),r){case v.Success:return[3,1];case v.Failed:case v.Timeout:case v.RateLimit:return[3,2];case v.PayloadTooLarge:return[3,4]}return[3,5];case 1:return this.handleSuccessResponse(t),[3,8];case 2:return[4,this.handleOtherResponse(t)];case 3:return i.sent(),[3,8];case 4:return this.handlePayloadTooLargeResponse(t,Ie.test(n)),[3,8];case 5:return 499!==e?[3,7]:[4,this.handleOtherResponse(t)];case 6:return i.sent(),[3,8];case 7:this.completeRequest({context:t,err:"Network error occurred, event batch rejected"}),i.label=8;case 8:return[2]}})})},e.prototype.handlePayloadTooLargeResponse=function(e,t){var n=t?"WAF (compressed payload too large)":"server (event too large)",r=Math.round(e.events.reduce(function(e,t){return e+t.length},0)/Ee);if(t)if(1!==e.events.length){this.loggerProvider.warn("Session replay event batch rejected by ".concat(n," (").concat(e.events.length," events, ").concat(r," KB total) — splitting and retrying")),e.onComplete();var i=function(){return Promise.resolve()},s=Math.floor(e.events.length/2);this.sendEventsList(o(o({},e),{events:e.events.slice(0,s),onComplete:i})),this.sendEventsList(o(o({},e),{events:e.events.slice(s),onComplete:i}))}else this.completeRequest({context:e,err:"Session replay event dropped: single event (".concat(r," KB, 1 event) rejected by ").concat(n," — cannot split further")});else this.completeRequest({context:e,err:"Session replay event batch dropped: ".concat(n," rejected payload (").concat(e.events.length," events, ").concat(r," KB) — not retrying non-WAF 413")})},e.prototype.handleSuccessResponse=function(e){var t=Math.round(new Blob(e.events).size/Ee);this.completeRequest({context:e,success:"Session replay event batch tracked successfully for session id ".concat(e.sessionId,", size of events: ").concat(t," KB")})},e.prototype.handleOtherResponse=function(e){return a(this,void 0,void 0,function(){var t;return l(this,function(n){switch(n.label){case 0:return t=Math.random()*e.attempts*this.retryTimeout,e.attempts++,e.attempts>(e.flushMaxRetries||0)?(this.completeRequest({context:e,err:lt}),[2]):[4,new Promise(function(e){return setTimeout(e,t)})];case 1:return n.sent(),[4,this.send(e,!0)];case 2:return n.sent(),[2]}})})},e.prototype.completeRequest=function(e){var t=e.context,n=e.err,r=e.success;t.onComplete(),n?this.loggerProvider.warn(n):r&&this.loggerProvider.log(r)},e.prototype.applyServerDirective=function(e,t){if(null===t)return this.flushPauseUntilMs=0,void(this.mergeLogFiredThisPause=!1);if("429"===t){var n=this.flushPauseUntilMs>Date.now();return this.flushPauseUntilMs=Date.now()+6e4,void(n||this.loggerProvider.log("Session replay throttled by server; pausing flush schedule for ".concat(60,"s")))}"4005"!==t&&"4004"!==t||this.killSession(e,t)},e.prototype.killSession=function(e,t){var n,r,i,o;if(!this.killedSessions.has(e)){if(this.killedSessions.add(e),this.killedSessions.size>256)try{for(var s=c(this.killedSessions),a=s.next();!a.done;a=s.next()){var l=a.value;this.killedSessions.delete(l);break}}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}this.loggerProvider.log("Session replay capture stopped for session ".concat(e," by server directive ").concat(t,"; remaining events will be dropped"));var u=[];try{for(var d=c(this.queue),v=d.next();!v.done;v=d.next()){var h=v.value;h.sessionId===e?this.completeRequest({context:h,err:ut}):u.push(h)}}catch(e){i={error:e}}finally{try{v&&!v.done&&(o=d.return)&&o.call(d)}finally{if(i)throw i.error}}this.queue=u}},e}();const ft=(e,t)=>t.some(t=>e instanceof t);let gt,pt;const mt=new WeakMap,yt=new WeakMap,bt=new WeakMap;let St={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return mt.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Et(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function It(e){St=e(St)}function wt(e){return(pt||(pt=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(Pt(this),t),Et(this.request)}:function(...t){return Et(e.apply(Pt(this),t))}}function Ct(e){return"function"==typeof e?wt(e):(e instanceof IDBTransaction&&function(e){if(mt.has(e))return;const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",o),e.removeEventListener("abort",o)},i=()=>{t(),r()},o=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",i),e.addEventListener("error",o),e.addEventListener("abort",o)});mt.set(e,t)}(e),ft(e,gt||(gt=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,St):e)}function Et(e){if(e instanceof IDBRequest)return function(e){const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("success",i),e.removeEventListener("error",o)},i=()=>{t(Et(e.result)),r()},o=()=>{n(e.error),r()};e.addEventListener("success",i),e.addEventListener("error",o)});return bt.set(t,e),t}(e);if(yt.has(e))return yt.get(e);const t=Ct(e);return t!==e&&(yt.set(e,t),bt.set(t,e)),t}const Pt=e=>bt.get(e);function kt(e,t,{blocked:n,upgrade:r,blocking:i,terminated:o}={}){const s=indexedDB.open(e,t),a=Et(s);return r&&s.addEventListener("upgradeneeded",e=>{r(Et(s.result),e.oldVersion,e.newVersion,Et(s.transaction),e)}),n&&s.addEventListener("blocked",e=>n(e.oldVersion,e.newVersion,e)),a.then(e=>{o&&e.addEventListener("close",()=>o()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),a}const xt=["get","getKey","getAll","getAllKeys","count"],Mt=["put","add","delete","clear"],Tt=new Map;function Rt(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(Tt.get(t))return Tt.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=Mt.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!xt.includes(n))return;const o=async function(e,...t){const o=this.transaction(e,i?"readwrite":"readonly");let s=o.store;return r&&(s=s.index(t.shift())),(await Promise.all([s[n](...t),i&&o.done]))[0]};return Tt.set(t,o),o}It(e=>({...e,get:(t,n,r)=>Rt(t,n)||e.get(t,n,r),has:(t,n)=>!!Rt(t,n)||e.has(t,n)}));const Ot=["continue","continuePrimaryKey","advance"],_t={},Lt=new WeakMap,Ft=new WeakMap,Dt={get(e,t){if(!Ot.includes(t))return e[t];let n=_t[t];return n||(n=_t[t]=function(...e){Lt.set(this,Ft.get(this)[t](...e))}),n}};async function*qt(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,Dt);for(Ft.set(n,t),bt.set(n,Pt(t));t;)yield n,t=await(Lt.get(n)||t.continue()),Lt.delete(n)}function At(e,t){return t===Symbol.asyncIterator&&ft(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&ft(e,[IDBIndex,IDBObjectStore])}It(e=>({...e,get:(t,n,r)=>At(t,n)?qt:e.get(t,n,r),has:(t,n)=>At(t,n)||e.has(t,n)}));var jt=function(){function e(e){var t,n,r,i=this;this.minInterval=we,this.maxInterval=Ce,this.maxPersistedEventsSize=6e6,this._timeAtLastSplit=Date.now(),this.shouldSplitEventsList=function(e,t){var n=i.getStringSize(t);return i.getEventsArraySize(e)+n>=i.maxPersistedEventsSize||!!(Date.now()-i.timeAtLastSplit>i.interval&&e.length)&&(i.interval=Math.min(i.maxInterval,i.interval+i.minInterval),i._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!==(r=e.maxPersistedEventsSize)&&void 0!==r?r:this.maxPersistedEventsSize,this.interval=this.minInterval}return Object.defineProperty(e.prototype,"timeAtLastSplit",{get:function(){return this._timeAtLastSplit},enumerable:!1,configurable:!0}),e.prototype.getStringSize=function(e){for(var t=0,n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<=127)t++;else if(r<=2047)t+=2;else if(r>=55296&&r<=56319){var i=n+1<e.length?e.charCodeAt(n+1):NaN;i>=56320&&i<=57343?(t+=4,n++):t+=3}else t+=3}return t},e.prototype.getEventsArraySize=function(e){var t,n,r=0;try{for(var i=c(e),o=i.next();!o.done;o=i.next()){var s=o.value;r+=this.getStringSize(s)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return r+(2+Math.max(0,e.length-1)+2*e.length)},e}(),Nt=function(e,t,n){var r;"object"==typeof(r=n)&&null!==r&&"AbortError"===r.name?e.debug(t):e.warn(t)};var Ut="sessionCurrentSequence",Bt="sequencesToSend",Wt=5e3;function zt(e,t,n){var r=setTimeout(n,t);return e.then(function(){return clearTimeout(r)},function(){return clearTimeout(r)}),function(){return clearTimeout(r)}}var Kt,Ht,Gt,Qt=function(e){var t,n;return e.objectStoreNames.contains(Ut)||(n=e.createObjectStore(Ut,{keyPath:"sessionId"})),e.objectStoreNames.contains(Bt)||(t=e.createObjectStore(Bt,{keyPath:"sequenceId",autoIncrement:!0})).createIndex("sessionId","sessionId"),{sequencesStore:t,currentSequenceStore:n}},Jt=function(e){return a(void 0,void 0,void 0,function(){return l(this,function(t){switch(t.label){case 0:return[4,(n=kt(e,1,{upgrade:Qt}),r=2e3,i="IDB openDB timed out",void 0===i&&(i="IDB operation timed out"),new Promise(function(e,t){var o=setTimeout(function(){return t(new Error("".concat(i," after ").concat(r,"ms")))},r);n.then(function(t){clearTimeout(o),e(t)},function(e){clearTimeout(o),t(e)})}))];case 1:return[2,t.sent()]}var n,r,i})})},$t=function(e){function t(t){var n,r=this;return(r=e.call(this,t)||this).consecutiveFailures=0,r.hasTriggeredFallback=!1,r.emptyFilteredCount=0,r.getSequencesToSend=function(){return a(r,void 0,void 0,function(){var e,t,n,r,i,o,s,a,c,u,d=this;return l(this,function(l){switch(l.label){case 0:e=!1,t=!1,l.label=1;case 1:return l.trys.push([1,9,,10]),n=[],(r=this.db.transaction("sequencesToSend","readwrite")).done.catch(function(n){e||t||(Nt(d.loggerProvider,"".concat(ct,": ").concat(n),n),d.recordFailure())}),i=zt(r.done,Wt,function(){e||t||(t=!0,Nt(d.loggerProvider,"".concat(ct,": transaction timed out")),d.recordFailure())}),[4,r.store.openCursor()];case 2:o=l.sent(),l.label=3;case 3:return o?(s=o.value,a=s.sessionId,0!==(c=s.events).length?[3,5]:(this.maybeLogEmptyFiltered("getSequencesToSend"),[4,o.delete()])):[3,8];case 4:return l.sent(),[3,6];case 5:n.push({events:c,sequenceId:o.key,sessionId:a}),l.label=6;case 6:return[4,o.continue()];case 7:return o=l.sent(),[3,3];case 8:return this.recordSuccess(),i(),[2,n];case 9:return u=l.sent(),t||(e=!0,Nt(this.loggerProvider,"".concat(ct,": ").concat(u),u),this.recordFailure()),[3,10];case 10:return[2,void 0]}})})},r.storeCurrentSequence=function(e){return a(r,void 0,void 0,function(){var t,n,r,i,a,c,u,d,v=this;return l(this,function(l){switch(l.label){case 0:t=!1,n=!1,l.label=1;case 1:return l.trys.push([1,5,,6]),(r=this.db.transaction([Ut,Bt],"readwrite")).done.catch(function(e){t||n||(Nt(v.loggerProvider,"".concat(ct,": ").concat(e),e),v.recordFailure())}),i=zt(r.done,Wt,function(){t||n||(n=!0,Nt(v.loggerProvider,"".concat(ct,": transaction timed out")),v.recordFailure())}),[4,r.objectStore(Ut).get(e)];case 2:return!(a=l.sent())||a.tabId&&a.tabId!==this.tabId?(i(),[2,void 0]):0===a.events.length?(this.maybeLogEmptyFiltered("storeCurrentSequence"),i(),[2,void 0]):[4,r.objectStore(Bt).put({sessionId:e,events:a.events,tabId:this.tabId})];case 3:return c=l.sent(),[4,r.objectStore(Ut).put({sessionId:e,events:[],tabId:this.tabId})];case 4:return l.sent(),this.recordSuccess(),i(),a.tabId,u=s(a,["tabId"]),[2,o(o({},u),{sessionId:e,sequenceId:c})];case 5:return d=l.sent(),n||(t=!0,Nt(this.loggerProvider,"".concat(ct,": ").concat(d),d),this.recordFailure()),[3,6];case 6:return[2,void 0]}})})},r.addEventToCurrentSequence=function(e,t){return a(r,void 0,void 0,function(){var n,r,i,o,s,a,c,u,d,v=this;return l(this,function(l){switch(l.label){case 0:n=!1,r=!1,l.label=1;case 1:return l.trys.push([1,15,,16]),(i=this.db.transaction([Ut,Bt],"readwrite")).done.catch(function(e){n||r||(Nt(v.loggerProvider,"".concat(ct,": ").concat(e),e),v.recordFailure())}),o=zt(i.done,Wt,function(){n||r||(r=!0,Nt(v.loggerProvider,"".concat(ct,": transaction timed out")),v.recordFailure())}),[4,i.objectStore(Ut).get(e)];case 2:return(null==(s=l.sent())?void 0:s.tabId)&&s.tabId!==this.tabId?s.events.length>0?[4,i.objectStore(Bt).put({sessionId:e,events:s.events,tabId:s.tabId})]:[3,4]:[3,6];case 3:l.sent(),l.label=4;case 4:return[4,i.objectStore(Ut).put({sessionId:e,events:[t],tabId:this.tabId})];case 5:return l.sent(),this.recordSuccess(),o(),[2,void 0];case 6:return(a=s)?[3,8]:[4,i.objectStore(Ut).put({sessionId:e,events:[t],tabId:this.tabId})];case 7:return l.sent(),this.recordSuccess(),o(),[2,void 0];case 8:return this.shouldSplitEventsList(a.events,t)?[3,10]:[4,i.objectStore(Ut).put({sessionId:e,events:a.events.concat(t),tabId:this.tabId})];case 9:return l.sent(),this.recordSuccess(),o(),[2,void 0];case 10:return 0!==(c=a.events).length?[3,12]:(this.maybeLogEmptyFiltered("addEventToCurrentSequence"),[4,i.objectStore(Ut).put({sessionId:e,events:[t],tabId:this.tabId})]);case 11:return l.sent(),this.recordSuccess(),o(),[2,void 0];case 12:return[4,i.objectStore(Ut).put({sessionId:e,events:[t],tabId:this.tabId})];case 13:return l.sent(),[4,i.objectStore(Bt).put({sessionId:e,events:c,tabId:this.tabId})];case 14:return u=l.sent(),this.recordSuccess(),o(),[2,{events:c,sessionId:e,sequenceId:u}];case 15:return d=l.sent(),r||(n=!0,Nt(this.loggerProvider,"".concat(ct,": ").concat(d),d),this.recordFailure()),[3,16];case 16:return[2,void 0]}})})},r.storeSendingEvents=function(e,t){return a(r,void 0,void 0,function(){var n,r;return l(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.db.put(Bt,{sessionId:e,events:t,tabId:this.tabId})];case 1:return n=i.sent(),this.recordSuccess(),[2,n];case 2:return r=i.sent(),Nt(this.loggerProvider,"".concat(ct,": ").concat(r),r),this.recordFailure(),[3,3];case 3:return[2,void 0]}})})},r.cleanUpSessionEventsStore=function(e,t){return a(r,void 0,void 0,function(){var e;return l(this,function(n){switch(n.label){case 0:if(!t)return[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.db.delete(Bt,t)];case 2:return n.sent(),this.recordSuccess(),[3,4];case 3:return e=n.sent(),Nt(this.loggerProvider,"".concat(ct,": ").concat(e),e),this.recordFailure(),[3,4];case 4:return[2]}})})},r.db=t.db,r.tabId=t.tabId,r.onPersistentFailure=t.onPersistentFailure,r.consecutiveFailureThreshold=null!==(n=t.consecutiveFailureThreshold)&&void 0!==n?n:1,r}return n(t,e),t.prototype.maybeLogEmptyFiltered=function(e){this.emptyFilteredCount++%100==0&&this.loggerProvider.debug("Filtered empty session replay sequence at ".concat(e," (idb store)"))},t.prototype.recordFailure=function(){var e;this.consecutiveFailures++,!this.hasTriggeredFallback&&this.consecutiveFailures>=this.consecutiveFailureThreshold&&(this.hasTriggeredFallback=!0,null===(e=this.onPersistentFailure)||void 0===e||e.call(this))},t.prototype.recordSuccess=function(){this.consecutiveFailures=0},t.new=function(e,n){var r;return a(this,void 0,void 0,function(){var i,s,a,c,u;return l(this,function(l){switch(l.label){case 0:return l.trys.push([0,2,,3]),i="replay"===e?"":"_".concat(e),s="".concat(n.apiKey.substring(0,10),"_amp_session_replay_events").concat(i),[4,Jt(s)];case 1:return a=l.sent(),c=null!==(r=n.tabId)&&void 0!==r?r:function(){try{return crypto.randomUUID()}catch(e){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}}(),[2,new t(o(o({},n),{db:a,tabId:c}))];case 2:return u=l.sent(),Nt(n.loggerProvider,"".concat(ct,": ").concat(u),u),[3,3];case 3:return[2]}})})},t.prototype.getCurrentSequenceEvents=function(e){return a(this,void 0,void 0,function(){var t,n,r,i,o,a,u,d;return l(this,function(l){switch(l.label){case 0:return e?[4,this.db.get("sessionCurrentSequence",e)]:[3,2];case 1:return(i=l.sent())?i.tabId&&i.tabId!==this.tabId?[2,void 0]:(i.tabId,[2,[o=s(i,["tabId"])]]):[2,void 0];case 2:t=[],l.label=3;case 3:return l.trys.push([3,8,9,10]),[4,this.db.getAll("sessionCurrentSequence")];case 4:n=c.apply(void 0,[l.sent()]),r=n.next(),l.label=5;case 5:if(r.done)return[3,7];if((i=r.value).tabId&&i.tabId!==this.tabId)return[3,6];i.tabId,o=s(i,["tabId"]),t.push(o),l.label=6;case 6:return r=n.next(),[3,5];case 7:return[3,10];case 8:return a=l.sent(),u={error:a},[3,10];case 9:try{r&&!r.done&&(d=n.return)&&d.call(n)}finally{if(u)throw u.error}return[7];case 10:return[2,t]}})})},t}(jt),Zt=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.finalizedSequences={},t.sequences={},t.sequenceId=0,t.emptyFilteredCount=0,t}return n(t,e),t.prototype.resetCurrentSequence=function(e){this.sequences[e]=[]},t.prototype.addSequence=function(e){var t=this.sequenceId++,n=d([],u(this.sequences[e]),!1);return this.finalizedSequences[t]={sessionId:e,events:n},this.resetCurrentSequence(e),{sequenceId:t,events:n,sessionId:e}},t.prototype.maybeLogEmptyFiltered=function(e){this.emptyFilteredCount++%100==0&&this.loggerProvider.debug("Filtered empty session replay sequence at ".concat(e," (in-memory store)"))},t.prototype.getSequencesToSend=function(){return a(this,void 0,void 0,function(){var e,t,n,r,i,o,s,a,d,v;return l(this,function(l){e=[];try{for(t=c(Object.entries(this.finalizedSequences)),n=t.next();!n.done;n=t.next())r=u(n.value,2),i=r[0],o=r[1],s=o.sessionId,0!==(a=o.events).length?e.push({sequenceId:Number(i),sessionId:s,events:a}):(this.maybeLogEmptyFiltered("getSequencesToSend"),delete this.finalizedSequences[Number(i)])}catch(e){d={error:e}}finally{try{n&&!n.done&&(v=t.return)&&v.call(t)}finally{if(d)throw d.error}}return[2,e]})})},t.prototype.storeCurrentSequence=function(e){return a(this,void 0,void 0,function(){var t;return l(this,function(n){return(t=this.sequences[e])?0===t.length?(this.maybeLogEmptyFiltered("storeCurrentSequence"),[2,void 0]):[2,this.addSequence(e)]:[2,void 0]})})},t.prototype.addEventToCurrentSequence=function(e,t){return a(this,void 0,void 0,function(){var n;return l(this,function(r){return this.sequences[e]||this.resetCurrentSequence(e),this.shouldSplitEventsList(this.sequences[e],t)&&(0===this.sequences[e].length?this.maybeLogEmptyFiltered("addEventToCurrentSequence"):n=this.addSequence(e)),this.sequences[e].push(t),[2,n]})})},t.prototype.storeSendingEvents=function(e,t){return a(this,void 0,void 0,function(){return l(this,function(n){return this.finalizedSequences[this.sequenceId]={sessionId:e,events:t},[2,this.sequenceId++]})})},t.prototype.cleanUpSessionEventsStore=function(e,t){return a(this,void 0,void 0,function(){return l(this,function(e){return void 0!==t&&delete this.finalizedSequences[t],[2]})})},t}(jt),Vt=function(e){var t=e.config,n=e.minInterval,r=e.maxInterval,i=e.maxPersistedEventsSize,s=e.type,c=e.payloadBatcher,v=e.storeType,h=e.trackDestinationWorkerScript,f=e.shouldSend;return a(void 0,void 0,void 0,function(){function e(e){return void 0===e&&(e=!1),a(this,void 0,void 0,function(){return l(this,function(t){return[2,p.flush(e)]})})}var g,p,m,y,b,S,I,w,C,E,P,k,x,M,T,R,O;return l(this,function(_){switch(_.label){case 0:return g=null!==(O=t.maxSingleEventSizeBytes)&&void 0!==O?O:Se,p=new ht(o(o({},t),{loggerProvider:t.loggerProvider,payloadBatcher:c,workerScript:h})),m=function(){return new Zt({loggerProvider:t.loggerProvider,maxInterval:r,minInterval:n,maxPersistedEventsSize:i})},b=!1,I=function(){return a(void 0,void 0,void 0,function(){var e,n,r;return l(this,function(i){switch(i.label){case 0:return b?(b=!1,t.loggerProvider.warn("IDB store is experiencing repeated failures; falling back to in-memory event store."),y?[4,S.getSequencesToSend()]:[3,2]):[2];case 1:return n=i.sent(),[3,3];case 2:n=void 0,i.label=3;case 3:return e=n,S=m(),e&&y&&(r=y,e.forEach(function(e){x({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:r})})),[2]}})})},w=function(){return a(void 0,void 0,void 0,function(){var e;return l(this,function(o){switch(o.label){case 0:return[4,$t.new(s,{loggerProvider:t.loggerProvider,minInterval:n,maxInterval:r,maxPersistedEventsSize:i,apiKey:t.apiKey,onPersistentFailure:function(){I()}})];case 1:return(e=o.sent())?(b=!0,[2,e]):(t.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),[2,m()])}})})},"idb"!==v?[3,2]:[4,w()];case 1:return C=_.sent(),[3,3];case 2:C=m(),_.label=3;case 3:return S=C,E=[],P=0,k=function(e){if(!(e<=P)){var t=Math.min(e-P,E.length);t>0&&(E.splice(0,t),P=e)}},x=function(e){var n=e.events,r=e.sessionId,i=e.deviceId,o=e.sequenceId,c=n.map(function(e){return{event:e,bytes:new Blob([e]).size}}),u=c.filter(function(e){return e.bytes>g});u.length>0&&t.loggerProvider.warn("Dropping ".concat(u.length," oversized event(s) from session replay sequence before send. Sizes: ").concat(u.map(function(e){return"".concat(Math.round(e.bytes/1024)," KB")}).join(", "),". If this recurs, please open a GitHub issue at https://github.com/amplitude/Amplitude-TypeScript/issues or contact Amplitude support."));var d=u.length>0?c.filter(function(e){return e.bytes<=g}).map(function(e){return e.event}):n;0!==d.length?(t.debugMode&&Be().then(function(e){var n=e.totalStorageSize,r=e.percentOfQuota,i=e.usageDetails;t.loggerProvider.debug("Total storage size: ".concat(n," KB, percentage of quota: ").concat(r,"%, usage details: ").concat(i))}).catch(function(){}),p.sendEventsList({events:d,sessionId:r,flushMaxRetries:t.flushMaxRetries,apiKey:t.apiKey,deviceId:i,sampleRate:t.sampleRate,serverZone:t.serverZone,version:t.version,type:s,onComplete:function(){return a(void 0,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,S.cleanUpSessionEventsStore(r,o)];case 1:return e.sent(),[2]}})})}})):S.cleanUpSessionEventsStore(r,o).catch(function(e){t.loggerProvider.warn("Failed to clean up session replay events store:",e)})},M=function(e){var n=e.sessionId,r=e.deviceId;if(y=r,!f||f()){var i=P+E.length;S.storeCurrentSequence(n).then(function(e){e&&(k(i),x({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:r}))}).catch(function(e){t.loggerProvider.warn("Failed to get current sequence of session replay events for session:",e)})}},T=function(e){var n=e.deviceId;return a(void 0,void 0,void 0,function(){var e;return l(this,function(r){switch(r.label){case 0:return y=n,[4,S.getSequencesToSend()];case 1:return(null==(e=r.sent())?void 0:e.length)?(t.loggerProvider.log("Draining ".concat(e.length," stored sequence(s) from previous session.")),e.length>1&&p.markCoalesceNextFlush(),e.forEach(function(e){x({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n})}),[2]):[2]}})})},R=function(e){var n=e.event,r=e.sessionId,i=e.deviceId;y=i;var o=!f||f(),s=P+E.length;E.push(n.data),S.addEventToCurrentSequence(r,n.data).then(function(e){if(e){if(!o)return S.cleanUpSessionEventsStore(e.sessionId,e.sequenceId).catch(function(e){t.loggerProvider.warn("Failed to clean up dropped session replay sequence:",e)}),void k(s);k(s),x({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:i})}}).catch(function(e){t.loggerProvider.warn("Failed to add event to session replay capture:",e)})},[2,{sendCurrentSequenceEvents:M,addEvent:R,sendStoredEvents:T,flush:e,getBeaconEvents:function(){return d([],u(E),!1)},dropPendingBeaconEvents:function(){k(P+E.length)},trackDestination:p}]}})})},Xt=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=new Map;e.forEach(function(e){n.set(e.name,e.manager)}),this.managers=n}return e.prototype.sendStoredEvents=function(e){return a(this,void 0,void 0,function(){var t;return l(this,function(n){switch(n.label){case 0:return t=[],this.managers.forEach(function(n){t.push(n.sendStoredEvents(e))}),[4,Promise.all(t)];case 1:return n.sent(),[2]}})})},e.prototype.addEvent=function(e){var t,n=e.sessionId,r=e.event,i=e.deviceId;null===(t=this.managers.get(r.type))||void 0===t||t.addEvent({sessionId:n,event:r,deviceId:i})},e.prototype.sendCurrentSequenceEvents=function(e){var t=e.sessionId,n=e.deviceId;this.managers.forEach(function(e){e.sendCurrentSequenceEvents({sessionId:t,deviceId:n})})},e.prototype.flush=function(e){return a(this,void 0,void 0,function(){var t;return l(this,function(n){switch(n.label){case 0:return t=[],this.managers.forEach(function(n){t.push(n.flush(e))}),[4,Promise.all(t)];case 1:return n.sent(),[2]}})})},e}();function Yt(e,t){if(Gt=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";var n={root:document.body,idName:function(e){return!0},className:function(e){return!0},tagName:function(e){return!0},attr:function(e,t){return!1},seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};Kt=o(o({},n),t),Ht=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(Kt.root,n);var r=en(e,"all",function(){return en(e,"two",function(){return en(e,"one",function(){return en(e,"none")})})});if(r){var i=dn(vn(r,e));return i.length>0&&(r=i[0]),nn(r)}throw new Error("Selector was not found.")}function en(e,t,n){for(var r=null,i=[],o=e,s=0,a=function(){var e,a,l=(new Date).getTime()-Gt.getTime();if(void 0!==Kt.timeoutMs&&l>Kt.timeoutMs)throw new Error("Timeout: Can't find a unique selector after ".concat(l,"ms"));var v=ln(function(e){var t=e.getAttribute("id");if(t&&Kt.idName(t))return{name:"#"+CSS.escape(t),penalty:0};return null}(o))||ln.apply(void 0,d([],u(function(e){var t=Array.from(e.attributes).filter(function(e){return Kt.attr(e.name,e.value)});return t.map(function(e){return{name:"[".concat(CSS.escape(e.name),'="').concat(CSS.escape(e.value),'"]'),penalty:.5}})}(o)),!1))||ln.apply(void 0,d([],u(function(e){var t=Array.from(e.classList).filter(Kt.className);return t.map(function(e){return{name:"."+CSS.escape(e),penalty:1}})}(o)),!1))||ln(function(e){var t=e.tagName.toLowerCase();if(Kt.tagName(t))return{name:t,penalty:2};return null}(o))||[{name:"*",penalty:3}],h=function(e){var t=e.parentNode;if(!t)return null;var n=t.firstChild;if(!n)return null;var r=0;for(;n&&(n.nodeType===Node.ELEMENT_NODE&&r++,n!==e);)n=n.nextSibling;return r}(o);if("all"==t)h&&(v=v.concat(v.filter(an).map(function(e){return sn(e,h)})));else if("two"==t)v=v.slice(0,1),h&&(v=v.concat(v.filter(an).map(function(e){return sn(e,h)})));else if("one"==t){var f=u(v=v.slice(0,1),1)[0];h&&an(f)&&(v=[sn(f,h)])}else"none"==t&&(v=[{name:"*",penalty:3}],h&&(v=[sn(v[0],h)]));try{for(var g=(e=void 0,c(v)),p=g.next();!p.done;p=g.next()){(f=p.value).level=s}}catch(t){e={error:t}}finally{try{p&&!p.done&&(a=g.return)&&a.call(g)}finally{if(e)throw e.error}}if(i.push(v),i.length>=Kt.seedMinLength&&(r=tn(i,n)))return"break";o=o.parentElement,s++};o;){if("break"===a())break}return r||(r=tn(i,n)),!r&&n?n():r}function tn(e,t){var n,r,i=dn(un(e));if(i.length>Kt.threshold)return t?t():null;try{for(var o=c(i),s=o.next();!s.done;s=o.next()){var a=s.value;if(on(a))return a}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return null}function nn(e){for(var t=e[0],n=t.name,r=1;r<e.length;r++){var i=e[r].level||0;n=t.level===i-1?"".concat(e[r].name," > ").concat(n):"".concat(e[r].name," ").concat(n),t=e[r]}return n}function rn(e){return e.map(function(e){return e.penalty}).reduce(function(e,t){return e+t},0)}function on(e){var t=nn(e);switch(Ht.querySelectorAll(t).length){case 0:throw new Error("Can't select any node with this selector: ".concat(t));case 1:return!0;default:return!1}}function sn(e,t){return{name:e.name+":nth-child(".concat(t,")"),penalty:e.penalty+1}}function an(e){return"html"!==e.name&&!e.name.startsWith("#")}function ln(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e.filter(cn);return n.length>0?n:null}function cn(e){return null!=e}function un(e,t){var n,r,i,o,s,a;return void 0===t&&(t=[]),l(this,function(l){switch(l.label){case 0:if(!(e.length>0))return[3,9];l.label=1;case 1:l.trys.push([1,6,7,8]),n=c(e[0]),r=n.next(),l.label=2;case 2:return r.done?[3,5]:(i=r.value,[5,c(un(e.slice(1,e.length),t.concat(i)))]);case 3:l.sent(),l.label=4;case 4:return r=n.next(),[3,2];case 5:return[3,8];case 6:return o=l.sent(),s={error:o},[3,8];case 7:try{r&&!r.done&&(a=n.return)&&a.call(n)}finally{if(s)throw s.error}return[7];case 8:return[3,11];case 9:return[4,t];case 10:l.sent(),l.label=11;case 11:return[2]}})}function dn(e){return d([],u(e),!1).sort(function(e,t){return rn(e)-rn(t)})}function vn(e,t,n){var r,i,o;return void 0===n&&(n={counter:0,visited:new Map}),l(this,function(s){switch(s.label){case 0:if(!(e.length>2&&e.length>Kt.optimizedMinLength))return[3,5];r=1,s.label=1;case 1:return r<e.length-1?n.counter>Kt.maxNumberOfTries?[2]:(n.counter+=1,(i=d([],u(e),!1)).splice(r,1),o=nn(i),n.visited.has(o)?[2]:on(i)&&function(e,t){return Ht.querySelector(nn(e))===t}(i,t)?[4,i]:[3,4]):[3,5];case 2:return s.sent(),n.visited.set(o,!0),[5,c(vn(i,t,n))];case 3:s.sent(),s.label=4;case 4:return r++,[3,1];case 5:return[2]}})}var hn=function(e){var t=e.version,n=e.events,r=[];return n.forEach(function(e){var t=JSON.parse(e);t.count=1,"click"===t.type&&r.push(t)}),{version:t,events:r}},fn=function(e){var t=e.version,n=e.events,r=[];n.forEach(function(e){var t=JSON.parse(e);"click"===t.type&&r.push(t)});var i=r.reduce(function(e,t){var n=t.x,r=t.y,i=t.selector,s=t.timestamp,a=s-s%36e5,l="".concat(n,":").concat(r,":").concat(null!=i?i:"",":").concat(a);return e[l]?e[l].count+=1:e[l]=o(o({},t),{timestamp:a,count:1}),e},{});return{version:t,events:Object.values(i)}},gn=function(e,t){var n=this;this.createHook=function(e){var t=e.eventsManager,r=e.sessionId,i=e.deviceIdFn,o=e.mirror,s=e.ugcFilterRules,a=e.performanceOptions;return function(e){if(e.type===Xe.Click){var l=g();if(l){var c=l.location,u=l.innerHeight,d=l.innerWidth;if(c){var v=e.x,h=e.y;if(void 0!==v&&void 0!==h){var f,p=o.getNode(e.id);if(p)try{f=Yt(p,a)}catch(e){n.logger.debug("error resolving selector from finder")}var m=Ue(c.href,s),y={x:v+n.scrollWatcher.currentScrollX,y:h+n.scrollWatcher.currentScrollY,selector:f,viewportHeight:u,viewportWidth:d,pageUrl:m,timestamp:Date.now(),type:"click"},b=i();b&&t.addEvent({sessionId:r,event:{type:"interaction",data:JSON.stringify(y)},deviceId:b})}}}}}},this.logger=e,this.scrollWatcher=t};function pn(){var e=g();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||0}function mn(){var e=g();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||0}var yn=function(){function e(e,t){var n=g();n&&n.navigator&&"function"==typeof n.navigator.sendBeacon?this.sendBeacon=function(e,t){try{if(n.navigator.sendBeacon(e,JSON.stringify(t)))return!0}catch(e){}return!1}:this.sendBeacon=function(){return!1},this.sendXhr=function(e,t){var n=new XMLHttpRequest;return n.open("POST",e,!0),n.setRequestHeader("Accept","*/*"),n.send(JSON.stringify(t)),!0},this.basePageUrl=je(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e,this.handleSendEvents=t.handleSendEvents,this.loggerProvider=t.loggerProvider}return e.prototype.send=function(e,t){var n,r=this,i=this.context,o=i.sessionId,s=i.type;if(this.handleSendEvents){var a=new URLSearchParams({device_id:e,session_id:String(o),type:String(s)}),l="".concat(this.basePageUrl,"?").concat(a.toString()),c={"Content-Type":"application/json",Accept:"*/*",Authorization:"Bearer ".concat(this.apiKey)};try{this.handleSendEvents({url:l,method:"POST",headers:c,body:JSON.stringify(t),keepalive:!0}).catch(function(e){var t;null===(t=r.loggerProvider)||void 0===t||t.warn("Custom transport failed to send session replay interaction beacon:",e)})}catch(e){null===(n=this.loggerProvider)||void 0===n||n.warn("Custom transport threw while sending session replay interaction beacon:",e)}}else{var u=new URLSearchParams({device_id:e,session_id:String(o),type:String(s),api_key:this.apiKey}),d="".concat(this.basePageUrl,"?").concat(u.toString());this.sendBeacon(d,t)||this.sendXhr(d,t)}},e}(),bn=function(){function e(e,t){var n=this;this.timestamp=Date.now(),this.hook=function(e){n.update(e)},this.send=function(e){return function(t){var r,i,o,s,a=e(),l=g();if(l&&a){var c=null!==(r=l.scrollX)&&void 0!==r?r:0,u=null!==(i=l.scrollY)&&void 0!==i?i:0;(c>0||u>0)&&n.update({id:1,x:c,y:u}),n.transport.send(a,{version:1,events:[{maxScrollX:n._maxScrollX,maxScrollY:n._maxScrollY,maxScrollWidth:n._maxScrollWidth,maxScrollHeight:n._maxScrollHeight,viewportHeight:pn(),viewportWidth:mn(),pageUrl:Ue(l.location.href,null!==(s=null===(o=n.config.interactionConfig)||void 0===o?void 0:o.ugcFilterRules)&&void 0!==s?s:[]),timestamp:n.timestamp,type:"scroll"}]})}}},this._maxScrollX=0,this._maxScrollY=0,this._currentScrollX=0,this._currentScrollY=0,this._maxScrollWidth=mn(),this._maxScrollHeight=pn(),this.config=t,this.transport=e}return e.default=function(t,n){return new e(new yn(t,n),n)},Object.defineProperty(e.prototype,"maxScrollX",{get:function(){return this._maxScrollX},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxScrollY",{get:function(){return this._maxScrollY},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxScrollWidth",{get:function(){return this._maxScrollWidth},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxScrollHeight",{get:function(){return this._maxScrollHeight},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentScrollX",{get:function(){return this._currentScrollX},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentScrollY",{get:function(){return this._currentScrollY},enumerable:!1,configurable:!0}),e.prototype.update=function(e){var t=Date.now();if(this._currentScrollX=e.x,this._currentScrollY=e.y,e.x>this._maxScrollX){var n=mn();this._maxScrollX=e.x;var r=e.x+n;r>this._maxScrollWidth&&(this._maxScrollWidth=r),this.timestamp=t}if(e.y>this._maxScrollY){var i=pn();this._maxScrollY=e.y;var o=e.y+i;o>this._maxScrollHeight&&(this._maxScrollHeight=o),this.timestamp=t}},e}(),Sn=function(e){var t=e.sessionId,n=e.deviceId;this.deviceId=n,this.sessionId=t,t&&n&&(this.sessionReplayId=function(e,t){return"".concat(t,"/").concat(e)}(t,n))},In=864e5,wn=function(e){return"".concat("AMP_SR_START_").concat(e.substring(0,10),"_")},Cn=function(e,t){return"".concat(wn(e)).concat(t)},En=function(){try{var e=g();return null==e?void 0:e.localStorage}catch(e){return}},Pn=function(){var e=this;this.dbs={},this.createStore=function(t){return a(e,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,kt(t,1,{upgrade:function(e){e.objectStoreNames.contains("sessionTargetingMatch")||e.createObjectStore("sessionTargetingMatch",{keyPath:"sessionId"})}})];case 1:return[2,e.sent()]}})})},this.openOrCreateDB=function(t){return a(e,void 0,void 0,function(){var e,n;return l(this,function(r){switch(r.label){case 0:return this.dbs&&this.dbs[t]?[2,this.dbs[t]]:(e="".concat(t.substring(0,10),"_amp_session_replay_targeting"),[4,this.createStore(e)]);case 1:return n=r.sent(),this.dbs[t]=n,[2,n]}})})},this.getTargetingMatchForSession=function(t){var n=t.loggerProvider,r=t.apiKey,i=t.sessionId;return a(e,void 0,void 0,function(){var e,t,o,s;return l(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),[4,this.openOrCreateDB(r)];case 1:return e=a.sent(),t=String(i),[4,e.get("sessionTargetingMatch",t)];case 2:return[2,null==(o=a.sent())?void 0:o.targetingMatch];case 3:return s=a.sent(),Nt(n,"Failed to get targeting match for session id ".concat(i,": ").concat(s),s),[3,4];case 4:return[2,void 0]}})})},this.storeTargetingMatchForSession=function(t){var n=t.loggerProvider,r=t.apiKey,i=t.sessionId,o=t.targetingMatch;return a(e,void 0,void 0,function(){var e,t,s;return l(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),[4,this.openOrCreateDB(r)];case 1:return e=a.sent(),t=String(i),[4,e.put("sessionTargetingMatch",{targetingMatch:o,sessionId:t,lastUpdated:Date.now()})];case 2:return[2,a.sent()];case 3:return s=a.sent(),Nt(n,"Failed to store targeting match for session id ".concat(i,": ").concat(s),s),[3,4];case 4:return[2,void 0]}})})},this.clearStoreOfOldSessions=function(t){var n=t.loggerProvider,r=t.apiKey,i=t.currentSessionId;return a(e,void 0,void 0,function(){var e,t,o,s,a,c,u,d;return l(this,function(l){switch(l.label){case 0:return l.trys.push([0,8,,9]),[4,this.openOrCreateDB(r)];case 1:return e=l.sent(),t=String(i),[4,(o=e.transaction("sessionTargetingMatch","readwrite")).store.getAll()];case 2:s=l.sent(),a=0,l.label=3;case 3:return a<s.length?(c=s[a],u=Date.now()-c.lastUpdated,c.sessionId!==t&&u>1728e5?[4,o.store.delete(c.sessionId)]:[3,5]):[3,6];case 4:l.sent(),l.label=5;case 5:return a++,[3,3];case 6:return[4,o.done];case 7:return l.sent(),[3,9];case 8:return d=l.sent(),Nt(n,"Failed to clear old targeting matches for sessions: ".concat(d),d),[3,9];case 9:return[2]}})})}},kn=new Pn,xn=function(e){var t=e.sessionId,n=e.targetingConfig,r=e.loggerProvider,i=e.apiKey,s=e.targetingParams,c=e.urlChange,u=void 0!==c&&c;return a(void 0,void 0,void 0,function(){var e,a,c,d,v,h;return l(this,function(l){switch(l.label){case 0:return[4,kn.clearStoreOfOldSessions({loggerProvider:r,apiKey:i,currentSessionId:t})];case 1:return l.sent(),[4,kn.getTargetingMatchForSession({loggerProvider:r,apiKey:i,sessionId:t})];case 2:if(!0===l.sent()&&!u)return[2,!0];e=!0,l.label=3;case 3:return l.trys.push([3,6,,7]),[4,import("./index-min3.js")];case 4:return a=l.sent().evaluateTargeting,c=o(o({},s),{flag:n,sessionId:"string"==typeof t?parseInt(t,10):t,apiKey:i,loggerProvider:r}),[4,a(c)];case 5:return(d=l.sent())&&d.sr_targeting_config&&(e="on"===d.sr_targeting_config.key),kn.storeTargetingMatchForSession({loggerProvider:r,apiKey:i,sessionId:t,targetingMatch:e}),[3,7];case 6:return v=l.sent(),h=v,r.warn(h.message),[3,7];case 7:return[2,e]}})})},Mn=2654435761,Tn=2246822519,Rn=3266489917,On=374761393;function _n(e,t){return(e<<t|e>>>32-t)>>>0}function Ln(e,t){return e=_n(e=e+Math.imul(t,Tn)>>>0,13),e=Math.imul(e,Mn)>>>0}function Fn(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function Dn(e,t){void 0===t&&(t=0);var n,r=function(e){for(var t=[],n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r>=55296&&r<=56319&&n+1<e.length){var i=e.charCodeAt(n+1);i>=56320&&i<=57343&&(r=i-56320+(r-55296<<10)+65536,n++)}r<128?t.push(r):r<2048?t.push(192|r>>6,128|63&r):r<65536?t.push(224|r>>12,128|r>>6&63,128|63&r):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}return new Uint8Array(t)}(e),i=r.length,o=0;if(i>=16){for(var s=t+Mn+Tn>>>0,a=t+Tn>>>0,l=t>>>0,c=t-Mn>>>0;o<=i-16;)s=Ln(s,Fn(r,o)),a=Ln(a,Fn(r,o+=4)),l=Ln(l,Fn(r,o+=4)),c=Ln(c,Fn(r,o+=4)),o+=4;n=_n(s,1)+_n(a,7)+_n(l,12)+_n(c,18)>>>0}else n=t+On>>>0;for(n=n+i>>>0;o<=i-4;)n=n+Math.imul(Fn(r,o),Rn)>>>0,n=Math.imul(_n(n,17),668265263)>>>0,o+=4;for(;o<i;)n=n+Math.imul(r[o],On)>>>0,n=Math.imul(_n(n,11),Mn)>>>0,o++;return n^=n>>>15,n=Math.imul(n,Tn)>>>0,n^=n>>>13,n=Math.imul(n,Rn)>>>0,(n^=n>>>16)>>>0}var qn="__amplitude_url_tracking_patched__",An=new WeakMap;function jn(e,t,n){if(void 0===n&&(n={}),!(null==e?void 0:e.location))return function(){};var r=n.enablePolling,i=void 0!==r&&r,o=n.pollingInterval,s=void 0===o?ge:o;if(i){var a=function(){var t;return null!==(t=e.location.href)&&void 0!==t?t:""},l=a(),c=e.setInterval(function(){var e=a();e!==l&&(l=e,t(e))},s);return function(){null!=c&&e.clearInterval(c)}}var u=An.get(e);if(!u){var d=void 0,v=new Set,h=function(){var t=function(){var t;return null!==(t=e.location.href)&&void 0!==t?t:""}();void 0!==d&&t===d||(d=t,v.forEach(function(e){return e(t)}))},f=function(e){var t=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var r=e.apply(this,t);return h(),r};return t[qn]=!0,t},g=e.history;if(null==g?void 0:g.pushState){var p=Reflect.get(g,"pushState");p[qn]||(g.pushState=f(p))}if(null==g?void 0:g.replaceState){var m=Reflect.get(g,"replaceState");m[qn]||(g.replaceState=f(m))}u={callbacks:v,notify:h,onPopStateOrHashChange:function(){return h()},listenersAttached:!1},An.set(e,u)}var y=u;return y.listenersAttached||(e.addEventListener("popstate",y.onPopStateOrHashChange),e.addEventListener("hashchange",y.onPopStateOrHashChange),y.listenersAttached=!0),y.callbacks.add(t),function(){y.callbacks.delete(t),0===y.callbacks.size&&y.listenersAttached&&(e.removeEventListener("popstate",y.onPopStateOrHashChange),e.removeEventListener("hashchange",y.onPopStateOrHashChange),y.listenersAttached=!1)}}function Nn(e){return void 0===e&&(e={}),{name:"amplitude/url-tracking@1",observer:function(t,n,r){var i,s,a,l=o(o({},e),r),c=l.ugcFilterRules||[],u=null!==(i=l.enablePolling)&&void 0!==i&&i,d=null!==(s=l.pollingInterval)&&void 0!==s?s:ge,v=null!==(a=l.captureDocumentTitle)&&void 0!==a&&a;if(!n)return function(){};var h=void 0,f=function(){return n.location&&n.location.href||""},g=function(){var e=f();if(void 0===h||e!==h){h=e;var r=function(){var e=n.innerHeight,t=n.innerWidth,r=n.document,i=f(),o="";return v&&(o=(null==r?void 0:r.title)||""),{href:c.length>0?Ue(i,c):i,title:o,viewportHeight:e,viewportWidth:t,type:"url-change-event"}}();t(r)}},p=jn(n,function(){return g()},u?{enablePolling:!0,pollingInterval:d}:{});return g(),function(){return p()}},options:e}}Nn();var Un=function(){function e(){this.pendingLoadListeners=new Map}return e.prototype.start=function(){var e,t=this;null===(e=this.mutationObserver)||void 0===e||e.disconnect(),g()&&(this.sendToAllIframes({type:ke,action:"start"}),this.mutationObserver=new MutationObserver(function(e){var n,r,i,o,s,a;try{for(var l=c(e),u=l.next();!u.done;u=l.next()){var d=u.value;try{for(var v=(i=void 0,c(Array.from(d.addedNodes))),h=v.next();!h.done;h=v.next()){(p=h.value)instanceof HTMLIFrameElement?t.sendToIframeAfterLoad(p):p instanceof Element&&p.querySelectorAll("iframe").forEach(function(e){t.sendToIframeAfterLoad(e)})}}catch(e){i={error:e}}finally{try{h&&!h.done&&(o=v.return)&&o.call(v)}finally{if(i)throw i.error}}try{for(var f=(s=void 0,c(Array.from(d.removedNodes))),g=f.next();!g.done;g=f.next()){var p;if((p=g.value)instanceof HTMLIFrameElement){var m=t.pendingLoadListeners.get(p);m&&(p.removeEventListener("load",m),t.pendingLoadListeners.delete(p))}}}catch(e){s={error:e}}finally{try{g&&!g.done&&(a=f.return)&&a.call(f)}finally{if(s)throw s.error}}}}catch(e){n={error:e}}finally{try{u&&!u.done&&(r=l.return)&&r.call(l)}finally{if(n)throw n.error}}}),this.mutationObserver.observe(document.documentElement,{childList:!0,subtree:!0}))},e.prototype.stop=function(){var e;null===(e=this.mutationObserver)||void 0===e||e.disconnect(),this.mutationObserver=void 0,this.pendingLoadListeners.forEach(function(e,t){t.removeEventListener("load",e)}),this.pendingLoadListeners.clear(),this.sendToAllIframes({type:ke,action:"stop"})},e.prototype.sendToIframeAfterLoad=function(e){var t=this,n=function(){t.pendingLoadListeners.delete(e),t.sendToIframe(e,{type:ke,action:"start"})};this.pendingLoadListeners.set(e,n),e.addEventListener("load",n,{once:!0})},e.prototype.sendToAllIframes=function(e){var t=this;document.querySelectorAll("iframe").forEach(function(n){return t.sendToIframe(n,e)})},e.prototype.sendToIframe=function(e,t){var n;try{null===(n=e.contentWindow)||void 0===n||n.postMessage(t,"*")}catch(e){}},e}();var Bn=function(){function e(){var e=this;this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.pageLeaveFns=[],this.suppressedSendCount=0,this.hasEmittedGateDecision=!1,this.recordFunction=null,this.recordEventsInFlight=!1,this.recordingEnabled=!0,this.recordingGeneration=0,this.startChildRecordingOnSetup=!1,this.pendingEmitEvents=[],this.currentPageUrl="",this.recordEventsPendingShouldLogMetadata=null,this.urlChangeCleanup=null,this.crossOriginIframeCoordinator=null,this.crossOriginParentSignalCleanup=null,this.latestUrlChangeTargetingEvaluationId=0,this.teardownEventListeners=function(t){var n=g();n&&(n.removeEventListener("blur",e.blurListener),n.removeEventListener("focus",e.focusListener),!t&&n.addEventListener("blur",e.blurListener),!t&&n.addEventListener("focus",e.focusListener),n.self&&"onpagehide"in n.self?(n.removeEventListener("pagehide",e.pageLeaveListener),!t&&n.addEventListener("pagehide",e.pageLeaveListener)):(n.removeEventListener("beforeunload",e.pageLeaveListener),!t&&n.addEventListener("beforeunload",e.pageLeaveListener)))},this.blurListener=function(){e.sendEvents()},this.focusListener=function(){var t;if(e.recordingEnabled)if(e.recordCancelCallback&&e.recordFunction){if(!1===(null===(t=e.config)||void 0===t?void 0:t.captureFullSnapshotOnFocus))return;try{e.recordFunction.takeFullSnapshot(!0)}catch(t){e.loggerProvider.warn("Failed to take full snapshot on focus:",t)}}else e.recordEventsInFlight||e.recordEvents(!1)},this.pageLeaveListener=function(t){var n;null===(n=e.eventCompressor)||void 0===n||n.flushQueue(),e.sendEvents(),e.pageLeaveFns.forEach(function(e){e(t)})},this.evaluateTargetingAndCapture=function(t,n,r,o){return void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===o&&(o=!1),a(e,void 0,void 0,function(){var e,s,a,c,u,d,v,h,f,p,m,y;return l(this,function(l){switch(l.label){case 0:if(!this.identifiers||!this.identifiers.sessionId||!this.config)return 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."),[2];if(!this.config.targetingConfig){if(!n)return this.loggerProvider.log("No targeting config set, skipping initialization/recording for event."),[2];this.loggerProvider.log("Targeting config has not been set yet, cannot evaluate targeting.")}return this.lastTargetingParams=t,e=this.config.targetingConfig,e&&!this.sessionTargetingMatch?(s=o?this.latestUrlChangeTargetingEvaluationId:void 0,(a=t.event)&&Object.values(i).includes(a.event_type)&&(a=void 0),c=null!==(m=null!==(h=null===(v=t.page)||void 0===v?void 0:v.url)&&void 0!==h?h:null===(p=null===(f=g())||void 0===f?void 0:f.location)||void 0===p?void 0:p.href)&&void 0!==m?m:"",u=null!==(y=t.page)&&void 0!==y?y:""!==c?{url:c}:void 0,[4,xn({sessionId:this.identifiers.sessionId,targetingConfig:e,loggerProvider:this.loggerProvider,apiKey:this.config.apiKey,targetingParams:{userProperties:t.userProperties,event:a,page:u},urlChange:o})]):[3,2];case 1:if(d=l.sent(),o&&void 0!==s&&s!==this.latestUrlChangeTargetingEvaluationId)return this.loggerProvider.debug("Ignoring stale URL-change targeting result #".concat(s,"; latest is #").concat(this.latestUrlChangeTargetingEvaluationId,".")),[2];this.sessionTargetingMatch=this.sessionTargetingMatch||d,this.loggerProvider.debug(JSON.stringify({name:"targeted replay capture config",sessionTargetingMatch:this.sessionTargetingMatch,event:a,targetingParams:t},null,2)),l.label=2;case 2:return n?(this.initialize(!0),[3,5]):[3,3];case 3:return!r&&this.recordCancelCallback?[3,5]:(this.loggerProvider.log("Recording events for session due to forceRestart or no ongoing recording."),[4,this.recordEvents()]);case 4:l.sent(),l.label=5;case 5:return[2]}})})},this.addCustomRRWebEvent=function(t,n,r){return void 0===n&&(n={}),void 0===r&&(r=!0),a(e,void 0,void 0,function(){var e,i,s,a;return l(this,function(l){switch(l.label){case 0:return l.trys.push([0,3,,4]),e=void 0,(i=this.config)&&t!==ue.METADATA?(e={config:We(i),version:dt},r?[4,Be()]:[3,2]):[3,2];case 1:s=l.sent(),e=o(o({},s),e),l.label=2;case 2:return this.recordCancelCallback&&this.recordFunction?this.recordFunction.addCustomEvent(t,o(o({},n),e)):this.loggerProvider.debug("Not able to add custom replay capture event ".concat(t," due to no ongoing recording.")),[3,4];case 3:return a=l.sent(),this.loggerProvider.debug("Error while adding custom replay capture event: ",a),[3,4];case 4:return[2]}})})},this.stopRecordingEvents=function(){var t,n,r;try{e.loggerProvider.log("Session Replay capture stopping."),e.recordCancelCallback&&e.recordCancelCallback(),e.recordCancelCallback=null,null===(t=e.networkObservers)||void 0===t||t.stop(),null===(n=e.crossOriginIframeCoordinator)||void 0===n||n.stop(),e.crossOriginIframeCoordinator=null,null===(r=e.crossOriginParentSignalCleanup)||void 0===r||r.call(e),e.crossOriginParentSignalCleanup=null}catch(t){var i=t;e.loggerProvider.warn("Error occurred while stopping replay capture: ".concat(i.toString()))}},this.loggerProvider=new xe(new M)}return e.prototype.init=function(e,t){return k(this._init(e,t))},e.prototype.setupUrlChangeListener=function(){var e,t,n=this;null===(e=this.urlChangeCleanup)||void 0===e||e.call(this);var r=g();if(null==r?void 0:r.location){var i=!!(null===(t=this.config)||void 0===t?void 0:t.targetingConfig),o=jn(r,function(e){if(n.currentPageUrl=e,i){var t=++n.latestUrlChangeTargetingEvaluationId;n.evaluateTargetingAndCapture({userProperties:{},event:void 0,page:{url:e}},!1,!1,!0),n.loggerProvider.debug("Queued URL-change targeting re-evaluation #".concat(t," for ").concat(e,"."))}});this.urlChangeCleanup=function(){o(),n.urlChangeCleanup=null}}},e.prototype.isBelowMinSessionDuration=function(){var e,t=null===(e=this.config)||void 0===e?void 0:e.minSessionDurationMs;return void 0!==t&&void 0!==this.sessionStartTime&&Date.now()-this.sessionStartTime<t},e.prototype.getCurrentPageForTargeting=function(){var e,t,n=null===(t=null===(e=g())||void 0===e?void 0:e.location)||void 0===t?void 0:t.href;return null!=n?{url:n}:void 0},e.prototype._init=function(e,t){var n,r,i,s,v,h,f,p,m,y,b,S,I,w;return a(this,void 0,void 0,function(){var a,C,E,P,k,x,T,R,O,_,L,F,D,q,A,j,N,U,B,W,z,K,H,G,Q,J,$,Z,V,X,Y,ee=this;return l(this,function(l){switch(l.label){case 0:return null===(n=this.urlChangeCleanup)||void 0===n||n.call(this),this.recordingEnabled=!0,this.startChildRecordingOnSetup=!1,this.loggerProvider=new xe(t.loggerProvider||new M),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.currentPageUrl=Ne(),this.identifiers=new Sn({sessionId:t.sessionId,deviceId:t.deviceId}),a=Date.now(),function(e,t,n){var r,i,o=En();if(o){var s=wn(e);try{for(var a=[],l=0;l<o.length;l++)if((f=o.key(l))&&f.startsWith(s)){var u=o.getItem(f);if(null!==u){var d=Number(u);(!Number.isFinite(d)||d<=0||t-d>=In)&&a.push(f)}}try{for(var v=c(a),h=v.next();!h.done;h=v.next()){var f=h.value;o.removeItem(f)}}catch(e){r={error:e}}finally{try{h&&!h.done&&(i=v.return)&&i.call(v)}finally{if(r)throw r.error}}}catch(e){null==n||n.debug("Failed to prune stale replay start times: ".concat(String(e)))}}}(e,a,this.loggerProvider),this.sessionStartTime=void 0!==t.sessionId&&null!==(r=function(e,t,n,r){var i=En();if(i){var o=Cn(e,t);try{var s=i.getItem(o);if(null!==s){var a=Number(s);if(Number.isFinite(a)&&a>0&&a<=n&&n-a<In)return a}return i.setItem(o,String(n)),n}catch(e){return void(null==r||r.debug("Failed to read/write replay start time from storage: ".concat(String(e))))}}}(e,t.sessionId,a,this.loggerProvider))&&void 0!==r?r:a,C=this,[4,nt(e,t)];case 1:return C.joinedConfigGenerator=l.sent(),[4,this.joinedConfigGenerator.generateJoinedConfig()];case 2:return E=l.sent(),P=E.joinedConfig,k=E.localConfig,x=E.remoteConfig,this.config=P,this.setMetadata(t.sessionId,P,k,x,null===(i=t.version)||void 0===i?void 0:i.version,dt,null===(s=t.version)||void 0===s?void 0:s.type),this.pageLeaveFns=[],t.sessionId&&(null===(v=this.config.interactionConfig)||void 0===v?void 0:v.enabled)&&(T=bn.default({sessionId:t.sessionId,type:"interaction"},this.config),this.pageLeaveFns=[T.send(this.getDeviceId.bind(this)).bind(T)],this.scrollHook=T.hook.bind(T),this.clickHandler=new gn(this.loggerProvider,T)),R=[],"idb"!==(O=this.config.storeType)||(null===(h=g())||void 0===h?void 0:h.indexedDB)||(O="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log("Using ".concat(O," for event storage.")),F=g(),this.config.useWebWorker&&F&&F.Worker?[4,import("./index-min2.js")]:[3,4];case 3:D=l.sent(),q=D.compressionScript,A=D.trackDestinationScript,_=q,L=A,l.label=4;case 4:return l.trys.push([4,6,,7]),[4,Vt({config:this.config,type:"replay",minInterval:null===(f=this.config.flushIntervalConfig)||void 0===f?void 0:f.minIntervalMs,maxInterval:null===(p=this.config.flushIntervalConfig)||void 0===p?void 0:p.maxIntervalMs,maxPersistedEventsSize:this.config.maxPersistedEventsSizeBytes,storeType:O,trackDestinationWorkerScript:L,shouldSend:function(){return!ee.isBelowMinSessionDuration()}})];case 5:return j=l.sent(),this.rrwebEventManager=j,R.push({name:"replay",manager:j}),[3,7];case 6:return N=l.sent(),z=N,this.loggerProvider.warn("Error occurred while creating replay events manager: ".concat(z.toString())),[3,7];case 7:if(!(null===(m=this.config.interactionConfig)||void 0===m?void 0:m.enabled))return[3,11];U=this.config.interactionConfig.batch?fn:hn,l.label=8;case 8:return l.trys.push([8,10,,11]),[4,Vt({config:this.config,type:"interaction",minInterval:null!==(y=this.config.interactionConfig.trackEveryNms)&&void 0!==y?y:3e4,maxInterval:6e4,maxPersistedEventsSize:this.config.maxPersistedEventsSizeBytes,payloadBatcher:U,storeType:O,trackDestinationWorkerScript:L})];case 9:return B=l.sent(),R.push({name:"interaction",manager:B}),[3,11];case 10:return W=l.sent(),z=W,this.loggerProvider.warn("Error occurred while creating interaction events manager: ".concat(z.toString())),[3,11];case 11:if(this.eventsManager=new(Xt.bind.apply(Xt,d([void 0],u(R),!1))),this.eventCompressor&&this.eventCompressor.terminate(),K=!0===this.config.eagerFullSnapshotSend?function(){return ee.sendEvents()}:void 0,this.eventCompressor=new at(this.eventsManager,this.config,this.getDeviceId(),_,K),this.pendingEmitEvents.length>0){H=this.pendingEmitEvents.splice(0);try{for(G=c(H),Q=G.next();!Q.done;Q=G.next())J=Q.value,$=J.event,Z=J.sessionId,this.eventCompressor.enqueueEvent($,Z)}catch(e){X={error:e}}finally{try{Q&&!Q.done&&(Y=G.return)&&Y.call(G)}finally{if(X)throw X.error}}}return this.pageLeaveFns=d(d([],u(this.pageLeaveFns),!1),[function(){var e;if(ee.config&&(null===(e=ee.identifiers)||void 0===e?void 0:e.sessionId)&&j){var t=j.getBeaconEvents();if(t.length){var n=ee.getDeviceId();n&&(ee.isBelowMinSessionDuration()||j.trackDestination.sendBeacon({events:t,sessionId:ee.identifiers.sessionId,deviceId:n,apiKey:ee.config.apiKey,serverZone:ee.config.serverZone}))}}}],!1),[4,this.initializeNetworkObservers()];case 12:return l.sent(),(null===(b=g())||void 0===b?void 0:b.opener)&&(ce(V=se()),V.setup(o({logger:this.loggerProvider},this.config.serverZone&&{endpoint:ne[this.config.serverZone]}))),this.loggerProvider.log("Installing @amplitude/session-replay-browser."),this.teardownEventListeners(!1),[4,this.evaluateTargetingAndCapture({userProperties:t.userProperties,page:this.getCurrentPageForTargeting()},!0)];case 13:return l.sent(),(this.config.targetingConfig||(null!==(w=null===(I=null===(S=this.config.privacyConfig)||void 0===S?void 0:S.urlMaskLevels)||void 0===I?void 0:I.length)&&void 0!==w?w:0)>0)&&this.setupUrlChangeListener(),[2]}})})},e.prototype.setSessionId=function(e,t){return k(this.asyncSetSessionId(e,t))},e.prototype.asyncSetSessionId=function(e,t,n){var r,i,o,s;return a(this,void 0,void 0,function(){var a,c,u,d,v;return l(this,function(l){switch(l.label){case 0:return a=null===(r=this.identifiers)||void 0===r?void 0:r.sessionId,c=this.getDeviceId(),void 0===a||a!==e||void 0!==t&&t!==c||void 0!==(null==n?void 0:n.userProperties)&&0!==Object.keys(n.userProperties).length?(this.latestUrlChangeTargetingEvaluationId++,this.sessionTargetingMatch=!1,this.lastShouldRecordDecision=void 0,a&&this.sendEvents(a),(u=a!==e)&&(null===(i=this.rrwebEventManager)||void 0===i||i.dropPendingBeaconEvents()),d=t||this.getDeviceId(),this.identifiers=new Sn({sessionId:e,deviceId:d}),u&&(this.sessionStartTime=Date.now(),this.suppressedSendCount=0,this.hasEmittedGateDecision=!1,(null===(o=this.config)||void 0===o?void 0:o.apiKey)&&(function(e,t,n,r){var i=En();if(i)try{i.setItem(Cn(e,t),String(n))}catch(e){null==r||r.debug("Failed to write replay start time to storage: ".concat(String(e)))}}(this.config.apiKey,e,this.sessionStartTime,this.loggerProvider),void 0!==a&&function(e,t,n){var r=En();if(r)try{r.removeItem(Cn(e,t))}catch(e){null==n||n.debug("Failed to remove replay start time from storage: ".concat(String(e)))}}(this.config.apiKey,a,this.loggerProvider))),this.joinedConfigGenerator&&a?[4,this.joinedConfigGenerator.generateJoinedConfig()]:[3,2]):[2];case 1:v=l.sent().joinedConfig,this.config=v,l.label=2;case 2:return(null===(s=this.config)||void 0===s?void 0:s.targetingConfig)?[4,this.evaluateTargetingAndCapture({userProperties:null==n?void 0:n.userProperties,page:this.getCurrentPageForTargeting()},!1,!0)]:[3,4];case 3:return l.sent(),[3,6];case 4:return[4,this.recordEvents()];case 5:l.sent(),l.label=6;case 6:return[2]}})})},e.prototype.getSessionReplayProperties=function(){var e,t=this.config,n=this.identifiers;if(!t||!n)return this.loggerProvider.warn("Session replay init has not been called, cannot get session replay properties."),{};var r=this.getShouldRecord(),i={};return r&&((e={})[ve]=n.sessionReplayId?n.sessionReplayId:null,i=e,t.debugMode&&(i[pe]=JSON.stringify({appHash:H(t.apiKey).toString()}))),this.addCustomRRWebEvent(ue.GET_SR_PROPS,{shouldRecord:r,eventProperties:i},10===this.eventCount),10===this.eventCount&&(this.eventCount=0),this.eventCount++,i},e.prototype.sendEvents=function(e){var t,n,r=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),i=this.getDeviceId();if(this.eventsManager&&r&&i){if(this.isBelowMinSessionDuration()){var o=this.sessionStartTime,s=this.config.minSessionDurationMs;return this.loggerProvider.log("Session ".concat(r," not sent: duration ").concat(Date.now()-o,"ms is below minimum ").concat(s,"ms.")),void this.suppressedSendCount++}if(!this.hasEmittedGateDecision&&void 0!==(null===(n=this.config)||void 0===n?void 0:n.minSessionDurationMs)&&this.recordCancelCallback&&this.recordFunction){this.hasEmittedGateDecision=!0;var a=void 0!==this.sessionStartTime?Date.now()-this.sessionStartTime:void 0;this.addCustomRRWebEvent(ue.REPLAY_GATE_DECISION,{sessionId:r,suppressedSendCount:this.suppressedSendCount,elapsedMs:a,minSessionDurationMs:this.config.minSessionDurationMs},!1)}this.eventsManager.sendCurrentSequenceEvents({sessionId:r,deviceId:i})}},e.prototype.initialize=function(e){var t;return void 0===e&&(e=!1),a(this,void 0,void 0,function(){var n;return l(this,function(r){return(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId)?(n=this.getDeviceId())?(this.eventsManager&&e&&this.eventsManager.sendStoredEvents({deviceId:n}),[2,this.recordEvents()]):(this.loggerProvider.log("Session is not being recorded due to lack of device id."),[2,Promise.resolve()]):(this.loggerProvider.log("Session is not being recorded due to lack of session id."),[2,Promise.resolve()])})})},e.prototype.shouldOptOut=function(){var e,t,n,r;(null===(e=this.config)||void 0===e?void 0:e.instanceName)&&(n=(r=this.config.instanceName,K.getInstance(T(r))).identityStore.getIdentity().optOut);return void 0!==n?n:null===(t=this.config)||void 0===t?void 0:t.optOut},e.prototype.getShouldRecord=function(){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.recordingEnabled)return this.loggerProvider.log("Session ".concat(this.identifiers.sessionId," not being captured because recording was stopped.")),!1;if(!this.config.captureEnabled)return this.loggerProvider.log("Session ".concat(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 ".concat(this.identifiers.sessionId," out of recording due to optOut config.")),!1;var e,t,n=!1,r="",i=!1;this.config.targetingConfig?this.sessionTargetingMatch?(r="Capturing replays for session ".concat(this.identifiers.sessionId," due to matching targeting conditions."),this.loggerProvider.log(r),n=!0,i=!0):(r="Not capturing replays for session ".concat(this.identifiers.sessionId," due to not matching targeting conditions."),this.loggerProvider.log(r),n=!1,i=!1):(e=this.identifiers.sessionId,t=this.config.sampleRate,Dn(e.toString())%1e6/1e6<t)?(n=!0,i=!0):(r="Opting session ".concat(this.identifiers.sessionId," out of recording due to sample rate."),this.loggerProvider.log(r),n=!1,i=!1);return this.lastShouldRecordDecision!==n&&this.config.targetingConfig&&(this.addCustomRRWebEvent(ue.TARGETING_DECISION,{message:r,sessionId:this.identifiers.sessionId,matched:i,targetingParams:this.lastTargetingParams}),this.lastShouldRecordDecision=n),n},e.prototype.getBlockSelectors=function(){var e;return qe(null===(e=this.config)||void 0===e?void 0:e.privacyConfig)},e.prototype.getMaskTextSelectors=function(){var e;return Ae(null===(e=this.config)||void 0===e?void 0:e.privacyConfig,this.currentPageUrl)},e.prototype.getRecordingPlugins=function(e){var t,n,r,i,o,s;return a(this,void 0,void 0,function(){var a,c,u,d;return l(this,function(l){switch(l.label){case 0:a=[];try{c=Nn({ugcFilterRules:(null===(n=null===(t=this.config)||void 0===t?void 0:t.interactionConfig)||void 0===n?void 0:n.ugcFilterRules)||[],enablePolling:(null===(r=this.config)||void 0===r?void 0:r.enableUrlChangePolling)||!1,pollingInterval:null===(i=this.config)||void 0===i?void 0:i.urlChangePollingInterval,captureDocumentTitle:null===(o=this.config)||void 0===o?void 0:o.captureDocumentTitle}),a.push(c)}catch(e){this.loggerProvider.warn("Failed to create URL tracking plugin:",e)}if(!(null===(s=null==e?void 0:e.console)||void 0===s?void 0:s.enabled))return[3,4];l.label=1;case 1:return l.trys.push([1,3,,4]),[4,import("./rrweb-plugin-console-record-min.js")];case 2:return u=l.sent().getRecordConsolePlugin,a.push(u({level:e.console.levels})),[3,4];case 3:return d=l.sent(),this.loggerProvider.warn("Failed to load console plugin:",d),[3,4];case 4:return[2,a.length>0?a:void 0]}})})},e.prototype.getRecordFunction=function(){return a(this,void 0,void 0,function(){var e,t;return l(this,function(n){switch(n.label){case 0:if(this.recordFunction)return[2,this.recordFunction];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,import("./rrweb-record-min.js")];case 2:return e=n.sent().record,this.recordFunction=e,[2,e];case 3:return t=n.sent(),this.loggerProvider.warn("Failed to load rrweb-record module:",t),[2,null];case 4:return[2]}})})},e.prototype.recordEvents=function(e){return void 0===e&&(e=!0),a(this,void 0,void 0,function(){var t;return l(this,function(n){switch(n.label){case 0:if(this.recordEventsInFlight)return this.recordEventsPendingShouldLogMetadata=e,[2];this.recordEventsInFlight=!0,n.label=1;case 1:return n.trys.push([1,,6,7]),[4,this._recordEvents(e)];case 2:n.sent(),n.label=3;case 3:return null===this.recordEventsPendingShouldLogMetadata?[3,5]:(t=this.recordEventsPendingShouldLogMetadata,this.recordEventsPendingShouldLogMetadata=null,[4,this._recordEvents(t)]);case 4:return n.sent(),[3,3];case 5:return[3,7];case 6:return this.recordEventsInFlight=!1,this.recordEventsPendingShouldLogMetadata=null,[7];case 7:return[2]}})})},e.prototype.shouldAbandonRecordStart=function(e){return!this.recordingEnabled||e!==this.recordingGeneration},e.prototype._recordEvents=function(e){var t,n,r,i,s,c,u,d;return void 0===e&&(e=!0),a(this,void 0,void 0,function(){var a,v,h,f,p,m,y,b,S,I,w,C,E,P,k,x,M,T=this;return l(this,function(l){switch(l.label){case 0:return a=this.config,v=this.getShouldRecord(),h=null===(t=this.identifiers)||void 0===t?void 0:t.sessionId,v&&h&&a?(this.stopRecordingEvents(),f=this.recordingGeneration,[4,this.getRecordFunction()]):[2];case 1:return!(p=l.sent())||this.shouldAbandonRecordStart(f)?[2]:[4,this.initializeNetworkObservers()];case 2:if(l.sent(),this.shouldAbandonRecordStart(f))return[2];m=null===(n=a.loggingConfig)||void 0===n?void 0:n.network,y=je(a.serverZone,a.trackServerUrl),b=[me,ye,be,y],null===(r=this.networkObservers)||void 0===r||r.start(function(e){b.some(function(t){return e.url.startsWith(t)})||T.addCustomRRWebEvent(ue.FETCH_REQUEST,e)},m),S=a.interactionConfig,I=a.loggingConfig,w=(null==S?void 0:S.enabled)?{mouseInteraction:this.eventsManager&&(null===(i=this.clickHandler)||void 0===i?void 0:i.createHook({eventsManager:this.eventsManager,sessionId:h,deviceIdFn:this.getDeviceId.bind(this),mirror:p.mirror,ugcFilterRules:null!==(s=S.ugcFilterRules)&&void 0!==s?s:[],performanceOptions:null===(c=a.performanceConfig)||void 0===c?void 0:c.interaction})),scroll:this.scrollHook}:{},C=(null==S?void 0:S.enabled)&&S.ugcFilterRules?S.ugcFilterRules:[],this.loggerProvider.log("Session Replay capture beginning for ".concat(h,".")),l.label=3;case 3:return l.trys.push([3,5,,6]),E=!!(null===(u=a.crossOriginIframes)||void 0===u?void 0:u.enabled),P=!1!==(null===(d=a.crossOriginIframes)||void 0===d?void 0:d.coordinateChildren),(k=E&&function(){try{var e=g();return!!e&&e.parent!==e}catch(e){return!0}}())&&P?(this.crossOriginParentSignalCleanup=function(e){var t=g();if(!t)return function(){};var n=t.parent;function r(t){if(t.source===n){var r=t.data;(null==r?void 0:r.type)===ke&&("start"===r.action?e.onStart():"stop"===r.action&&e.onStop())}}return t.addEventListener("message",r),function(){return t.removeEventListener("message",r)}}({onStart:function(){T.recordingEnabled&&T._recordEventsInChildMode(p,h,a,w)},onStop:function(){try{T.recordCancelCallback&&T.recordCancelCallback(),T.recordCancelCallback=null}catch(t){var e=t;T.loggerProvider.warn("Error occurred while stopping child iframe replay capture: ".concat(e.toString()))}}}),this.startChildRecordingOnSetup&&(this.startChildRecordingOnSetup=!1,this._recordEventsInChildMode(p,h,a,w)),[2]):(this.startChildRecordingOnSetup=!1,[4,this.getRecordingPlugins(I)]);case 4:return x=l.sent(),this.shouldAbandonRecordStart(f)?[2]:(this.recordCancelCallback=p(o(o({},this.buildRRWebRecordOptions(a,w,function(e){if(T.shouldOptOut()||!T.recordingEnabled)return T.loggerProvider.log(T.shouldOptOut()?"Opting session ".concat(h," out of recording due to optOut config."):"Session Replay capture stopping for ".concat(h,".")),T.stopRecordingEvents(),void T.sendEvents();e.type===Ze.Meta&&(e.data.href=Ue(e.data.href,C)),T.eventCompressor?T.eventCompressor.enqueueEvent(e,h):T.pendingEmitEvents.push({event:e,sessionId:h})},"Error while capturing replay: ")),{plugins:x,recordCrossOriginIframes:E})),E&&!k&&P&&(this.crossOriginIframeCoordinator||(this.crossOriginIframeCoordinator=new Un),this.crossOriginIframeCoordinator.start()),this.addCustomRRWebEvent(ue.DEBUG_INFO),e&&this.addCustomRRWebEvent(ue.METADATA,this.metadata),[3,6]);case 5:return M=l.sent(),this.loggerProvider.warn("Failed to initialize session replay:",M),[3,6];case 6:return[2]}})})},e.prototype.buildRRWebRecordOptions=function(e,t,n,r){var i=this,s=e.privacyConfig;return o(o(o(o({emit:n,inlineStylesheet:e.shouldInlineStylesheet,inlineImages:e.inlineImages,hooks:t},function(e,t){return void 0===t&&(t=function(){return""}),{maskAllInputs:!0,maskTextClass:"amp-mask",blockClass:"amp-block",blockSelector:qe(e),maskTextSelector:Ae(e,t()),maskInputFn:Fe("input",e,t),maskTextFn:Fe("text",e,t),maskAttributeFn:De(e,t)}}(s,function(){return i.currentPageUrl})),{applyBackgroundColorToBlockedElements:e.applyBackgroundColorToBlockedElements}),void 0!==e.fullSnapshotIntervalMs&&{checkoutEveryNms:e.fullSnapshotIntervalMs}),{recordCanvas:!1,captureAdoptedStyleSheets:e.captureAdoptedStyleSheets,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},errorHandler:function(e){var t=e;if(t.message.includes("insertRule")&&t.message.includes("CSSStyleSheet"))throw t;if(t._external_)throw t;return i.loggerProvider.warn(r,t.toString()),!0}})},e.prototype._recordEventsInChildMode=function(e,t,n,r){try{this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null,this.recordCancelCallback=e(o(o({},this.buildRRWebRecordOptions(n,r,function(){},"Error while capturing replay (child iframe): ")),{recordCrossOriginIframes:!0})),this.loggerProvider.log("Session Replay child iframe capture beginning for session ".concat(t,"."))}catch(e){this.loggerProvider.warn("Failed to initialize session replay in child iframe mode:",e)}},e.prototype.getDeviceId=function(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.deviceId},e.prototype.getSessionId=function(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.sessionId},e.prototype.start=function(){return k(this._start())},e.prototype._start=function(){return a(this,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return this.recordingEnabled=!0,this.startChildRecordingOnSetup=!0,[4,this.recordEvents()];case 1:return e.sent(),[2]}})})},e.prototype.stop=function(){this.recordingEnabled=!1,this.startChildRecordingOnSetup=!1,this.recordingGeneration++,this.stopRecordingEvents(),this.sendEvents()},e.prototype.flush=function(e){var t;return void 0===e&&(e=!1),a(this,void 0,void 0,function(){return l(this,function(n){return[2,null===(t=this.eventsManager)||void 0===t?void 0:t.flush(e)]})})},e.prototype.shutdown=function(){var e,t;this.recordingEnabled=!1,this.startChildRecordingOnSetup=!1,this.recordingGeneration++,null===(e=this.urlChangeCleanup)||void 0===e||e.call(this),null===(t=this.crossOriginParentSignalCleanup)||void 0===t||t.call(this),this.crossOriginParentSignalCleanup=null,this.teardownEventListeners(!0),this.stopRecordingEvents(),this.sendEvents()},e.prototype.mapSDKType=function(e){return"plugin"===e?"@amplitude/plugin-session-replay-browser":"segment"===e?"@amplitude/segment-session-replay-plugin":null},e.prototype.setMetadata=function(e,t,n,r,i,o,s){var a=(null==e?void 0:e.toString())?H(e.toString()):void 0;this.metadata={joinedConfig:t,localConfig:n,remoteConfig:r,sessionId:e,hashValue:a,sampleRate:t.sampleRate,replaySDKType:this.mapSDKType(s),replaySDKVersion:i,standaloneSDKType:"@amplitude/session-replay-browser",standaloneSDKVersion:o}},e.prototype.initializeNetworkObservers=function(){var e,t,n;return a(this,void 0,void 0,function(){var r,i;return l(this,function(o){switch(o.label){case 0:if(!(null===(n=null===(t=null===(e=this.config)||void 0===e?void 0:e.loggingConfig)||void 0===t?void 0:t.network)||void 0===n?void 0:n.enabled)||this.networkObservers)return[3,4];o.label=1;case 1:return o.trys.push([1,3,,4]),[4,import("./observers-min.js")];case 2:return r=o.sent().NetworkObservers,this.networkObservers=new r,[3,4];case 3:return i=o.sent(),this.loggerProvider.warn("Failed to import or instantiate NetworkObservers:",i),[3,4];case 4:return[2]}})})},e}(),Wn=function(e){return function(){var t=e.config||ze();return{logger:t.loggerProvider,logLevel:t.logLevel}}},zn=function(){var e=new Bn;return{init:F(e.init.bind(e),"init",Wn(e)),evaluateTargetingAndCapture:F(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",Wn(e)),setSessionId:F(e.setSessionId.bind(e),"setSessionId",Wn(e)),getSessionId:F(e.getSessionId.bind(e),"getSessionId",Wn(e)),getSessionReplayProperties:F(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",Wn(e)),flush:F(e.flush.bind(e),"flush",Wn(e)),start:F(e.start.bind(e),"start",Wn(e)),stop:F(e.stop.bind(e),"stop",Wn(e)),shutdown:F(e.shutdown.bind(e),"shutdown",Wn(e))}}(),Kn=zn.init,Hn=zn.setSessionId,Gn=zn.getSessionId,Qn=zn.getSessionReplayProperties;zn.flush,zn.start,zn.stop,zn.shutdown,zn.evaluateTargetingAndCapture;const Jn="amp_session_id",$n="Amplitude Session Replay Segment Plugin [Debug]:";function Zn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)"__proto__"!==r&&(e[r]=n[r])}return e}var Vn=function e(t,n){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=Zn({},n,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var s in i)i[s]&&(o+="; "+s,!0!==i[s]&&(o+="="+i[s].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+o}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],r={},i=0;i<n.length;i++){var o=n[i].split("="),s=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(a in r||(r[a]=t.read(s,a)),e===a)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",Zn({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,Zn({},this.attributes,t))},withConverter:function(t){return e(Zn({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});const Xn=()=>{const e=Gn()||Vn.get(Jn);if(e){const t=parseInt(e.toString(),10);if(isNaN(t))return;return t}},Yn=(e,t)=>(Vn.set(Jn,e.toString()),Hn(e,t).promise),er=(e,t)=>a(void 0,void 0,void 0,function*(){const n=Xn()||0;let r;e.event.integrations&&e.event.integrations["Actions Amplitude"]&&(r=e.event.integrations["Actions Amplitude"].session_id),r&&n<r&&(yield Yn(r,t));const i=Qn(),o=Object.assign(Object.assign({},i),e.event.properties);return e.updateEvent("properties",o),e}),tr="0.0.48",nr=({amplitudeApiKey:e,sessionReplayOptions:t,segmentInstance:n,enableWrapperDebug:r=!1})=>a(void 0,void 0,void 0,function*(){let i,o=!1,s=null==t?void 0:t.deviceId;const l={name:"Session Replay Events",type:"enrichment",version:tr,isLoaded:()=>o,load:(n,l)=>a(void 0,void 0,void 0,function*(){if(!s){const e=l.user();s=e.anonymousId()||void 0}const n=Xn();r&&console.log(`${$n} initializing session replay with sessionId=${null!=n?n:"undefined"} and deviceId=${null!=s?s:"undefined"}`),i=Kn(e,Object.assign(Object.assign({},t),{sessionId:n,deviceId:s||void 0,version:{type:"segment",version:tr}})).promise,yield i,o=!0}),track:e=>a(void 0,void 0,void 0,function*(){return yield i,yield er(e,s)}),page:e=>a(void 0,void 0,void 0,function*(){return yield i,yield er(e,s)}),identify:e=>a(void 0,void 0,void 0,function*(){yield i;const t=Xn();return t&&(r&&console.log(`${$n} calling setSessionId() with sessionId=${t} and deviceId=${null!=s?s:"undefined"}`),yield Yn(t,s)),e})};yield n.register(l)});export{c as _,d as a,u as b,a as c,l as d,o as e,nr as f,g,kt as o};
1
+ function e(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if("default"!==n&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},t(e,n)};function n(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var r,i,o=function(){return o=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},o.apply(this,arguments)};function s(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}function a(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{l(r.next(e))}catch(e){o(e)}}function a(e){try{l(r.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}l((r=r.apply(e,t||[])).next())})}function l(e,t){var n,r,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(l){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,l])}}}function c(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function u(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s}function d(e,t,n){if(n||2===arguments.length)for(var r,i=0,o=t.length;i<o;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError,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"}(r||(r={})),function(e){e.IDENTIFY="$identify",e.GROUP_IDENTIFY="$groupidentify",e.REVENUE="revenue_amount"}(i||(i={}));var h,v="$default_instance",f="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"}(h||(h={}));var 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},p=d([],u(Array(256).keys()),!1).map(function(e){return e.toString(16).padStart(2,"0")}),m=function(e){var t,n=g();if(!(null===(t=null==n?void 0:n.crypto)||void 0===t?void 0:t.getRandomValues))return function(e){return e?(e^16*Math.random()>>e/4).toString(16):(String(1e7)+String(-1e3)+String(-4e3)+String(-8e3)+String(-1e11)).replace(/[018]/g,m)}(e);var r=n.crypto.getRandomValues(new Uint8Array(16));return r[6]=15&r[6]|64,r[8]=63&r[8]|128,d([],u(r.entries()),!1).map(function(e){var t=u(e,2),n=t[0],r=t[1];return[4,6,8,10].includes(n)?"-".concat(p[r]):p[r]}).join("")},y={},b={get exports(){return y},set exports(e){y=e}},S=Object.prototype.hasOwnProperty;function I(e){return"[Throws: "+(e?e.message:"?")+"]"}function w(e){var t=[];return function e(n){if(null===n||"object"!=typeof n)return n;if(-1!==t.indexOf(n))return"[Circular]";if(t.push(n),"function"==typeof n.toJSON)try{var r=e(n.toJSON());return t.pop(),r}catch(e){return I(e)}if(Array.isArray(n)){var i=n.map(e);return t.pop(),i}var o=Object.keys(n).reduce(function(t,r){return t[r]=e(function(e,t){if(S.call(e,t))try{return e[t]}catch(e){return I(e)}return e[t]}(n,r)),t},{});return t.pop(),o}(e)}b.exports=function(e,t,n){return JSON.stringify(w(e),t,n)};var C,E=y.ensureProperties=w,P=y||e({__proto__:null,ensureProperties:E,get default(){return y}},[y]),k=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"}(C||(C={}));var x="Amplitude Logger ",M=function(){function e(){this.logLevel=C.None}return e.prototype.disable=function(){this.logLevel=C.None},e.prototype.enable=function(e){void 0===e&&(e=C.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<C.Verbose||console.log("".concat(x,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<C.Warn||console.warn("".concat(x,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<C.Error||console.error("".concat(x,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<C.Debug||console.log("".concat(x,"[Debug]: ").concat(e.join(" ")))},e}(),T=function(e){return void 0===e||""===e?v:e},R=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:v,logLevel:C.Warn,loggerProvider:new M,offline:!1,optOut:!1,serverUrl:f,serverZone:"US",useBatch:!1}},O=function(){function e(e){var t,n,r,i;this._optOut=!1;var o=R();this.apiKey=e.apiKey,this.flushIntervalMillis=null!==(t=e.flushIntervalMillis)&&void 0!==t?t:o.flushIntervalMillis,this.flushMaxRetries=e.flushMaxRetries||o.flushMaxRetries,this.flushQueueSize=e.flushQueueSize||o.flushQueueSize,this.instanceName=T(e.instanceName),this.loggerProvider=e.loggerProvider||o.loggerProvider,this.logLevel=null!==(n=e.logLevel)&&void 0!==n?n:o.logLevel,this.minIdLength=e.minIdLength,this.plan=e.plan,this.ingestionMetadata=e.ingestionMetadata,this.offline=void 0!==e.offline?e.offline:o.offline,this.optOut=null!==(r=e.optOut)&&void 0!==r?r:o.optOut,this.serverUrl=e.serverUrl,this.serverZone=e.serverZone||o.serverZone,this.storageProvider=e.storageProvider,this.transportProvider=e.transportProvider,this.useBatch=null!==(i=e.useBatch)&&void 0!==i?i:o.useBatch,this.loggerProvider.enable(this.logLevel);var s=L(e.serverUrl,e.serverZone,e.useBatch);this.serverZone=s.serverZone,this.serverUrl=s.serverUrl}return Object.defineProperty(e.prototype,"optOut",{get:function(){return this._optOut},set:function(e){this._optOut=e},enumerable:!1,configurable:!0}),e}(),_=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":f},L=function(e,t,n){if(void 0===e&&(e=""),void 0===t&&(t=R().serverZone),void 0===n&&(n=R().useBatch),e)return{serverUrl:e,serverZone:void 0};var r=["US","EU"].includes(t)?t:R().serverZone;return{serverZone:r,serverUrl:_(r,n)}};var F=function(e,t,n,r,i){return void 0===i&&(i=null),function(){for(var o=[],s=0;s<arguments.length;s++)o[s]=arguments[s];var a=n(),l=a.logger,c=a.logLevel;if(c&&c<C.Debug||!c||!l)return e.apply(i,o);var u,d={type:"invoke public method",name:t,args:o,stacktrace:(u=1,void 0===u&&(u=0),((new Error).stack||"").split("\n").slice(2+u).map(function(e){return e.trim()})),time:{start:(new Date).toISOString()},states:{}};r&&d.states&&(d.states.before=r());var h=e.apply(i,o);return h&&h.promise?h.promise.then(function(){r&&d.states&&(d.states.after=r()),d.time&&(d.time.end=(new Date).toISOString()),l.debug(JSON.stringify(d,null,2))}):(r&&d.states&&(d.states.after=r()),d.time&&(d.time.end=(new Date).toISOString()),l.debug(JSON.stringify(d,null,2))),h}},D=function(){function e(){}return e.prototype.getApplicationContext=function(){return{versionName:this.versionName,language:q(),platform:"Web",os:void 0,deviceModel:void 0}},e}(),q=function(){return"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||""},A=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}(),B=function(){return B=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},B.apply(this,arguments)};function N(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function j(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)s.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return s}"function"==typeof SuppressedError&&SuppressedError;var U=function(e,t){var n,r,i=typeof e;if(i!==typeof t)return!1;try{for(var o=N(["string","number","boolean","undefined"]),s=o.next();!s.done;s=o.next()){if(s.value===i)return e===t}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}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(),u=Object.keys(t).sort();if(!U(c,u))return!1;var d=!0;return Object.keys(e).forEach(function(n){U(e[n],t[n])||(d=!1)}),d}for(var h=0;h<e.length;h++)if(!U(e[h],t[h]))return!1;return!0};Object.entries||(Object.entries=function(e){for(var t=Object.keys(e),n=t.length,r=new Array(n);n--;)r[n]=[t[n],e[t[n]]];return r});var W=function(){function e(){this.identity={userProperties:{}},this.listeners=new Set}return e.prototype.editIdentity=function(){var e=this,t=B({},this.identity.userProperties),n=B(B({},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,r,i,o,s,a,l=n.userProperties||{};try{for(var c=N(Object.entries(e)),u=c.next();!u.done;u=c.next()){var d=j(u.value,2),h=d[0],v=d[1];switch(h){case"$set":try{for(var f=(i=void 0,N(Object.entries(v))),g=f.next();!g.done;g=f.next()){var p=j(g.value,2),m=p[0],y=p[1];l[m]=y}}catch(e){i={error:e}}finally{try{g&&!g.done&&(o=f.return)&&o.call(f)}finally{if(i)throw i.error}}break;case"$unset":try{for(var b=(s=void 0,N(Object.keys(v))),S=b.next();!S.done;S=b.next()){delete l[m=S.value]}}catch(e){s={error:e}}finally{try{S&&!S.done&&(a=b.return)&&a.call(b)}finally{if(s)throw s.error}}break;case"$clearAll":l={}}}}catch(e){t={error:e}}finally{try{u&&!u.done&&(r=c.return)&&r.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 B({},this.identity)},e.prototype.setIdentity=function(e){var t=B({},this.identity);this.identity=B({},e),U(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}(),z="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self,K=function(){function e(){this.identityStore=new W,this.eventBridge=new A,this.applicationContextProvider=new D}return e.getInstance=function(t){return z.analyticsConnectorInstances||(z.analyticsConnectorInstances={}),z.analyticsConnectorInstances[t]||(z.analyticsConnectorInstances[t]=new e),z.analyticsConnectorInstances[t]},e}(),H=function(e){var t=0;if(0===e.length)return t;for(var n=0;n<e.length;n++){t=(t<<5)-t+e.charCodeAt(n),t|=0}return t},G=function(){function e(){}return e.prototype.send=function(e,t,n){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,n,r,i,o,s,a,l,c,u,d,v,f,g,p,m,y,b,S,I,w,C;if("object"!=typeof e)return null;var E=e.code||0,P=this.buildStatus(E);switch(P){case h.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!==(r=e.server_upload_time)&&void 0!==r?r:0}};case h.Invalid:return{status:P,statusCode:E,body:{error:null!==(i=e.error)&&void 0!==i?i:"",missingField:null!==(o=e.missing_field)&&void 0!==o?o:"",eventsWithInvalidFields:null!==(s=e.events_with_invalid_fields)&&void 0!==s?s:{},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!==(u=e.exceeded_daily_quota_devices)&&void 0!==u?u:{},silencedDevices:null!==(d=e.silenced_devices)&&void 0!==d?d:[],silencedEvents:null!==(v=e.silenced_events)&&void 0!==v?v:[],throttledDevices:null!==(f=e.throttled_devices)&&void 0!==f?f:{},throttledEvents:null!==(g=e.throttled_events)&&void 0!==g?g:[]}};case h.PayloadTooLarge:return{status:P,statusCode:E,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case h.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!==(b=e.throttled_devices)&&void 0!==b?b:{},throttledUsers:null!==(S=e.throttled_users)&&void 0!==S?S:{},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 h.Timeout:default:return{status:P,statusCode:E}}},e.prototype.buildStatus=function(e){return function(e){return e>=200&&e<300}(e)?h.Success:429===e?h.RateLimit:413===e?h.PayloadTooLarge:408===e?h.Timeout:e>=400&&e<500?h.Invalid:e>=500?h.Failed:h.Unknown},e}(),Q=function(e){function t(t){void 0===t&&(t={});var n=e.call(this)||this;return n.customHeaders=t,n}return n(t,e),t.prototype.send=function(e,t){return a(this,void 0,void 0,function(){var n,r,i;return l(this,function(s){switch(s.label){case 0:if("undefined"==typeof fetch)throw new Error("FetchTransport is not supported");return n={headers:o({"Content-Type":"application/json",Accept:"*/*"},this.customHeaders),body:JSON.stringify(t),method:"POST"},[4,fetch(e,n)];case 1:return[4,(r=s.sent()).text()];case 2:i=s.sent();try{return[2,this.buildResponse(JSON.parse(i))]}catch(e){return[2,this.buildResponse({code:r.status})]}return[2]}})})},t}(G),J=function(){function e(e,t){this.key="AMP_remote_config_".concat(e.substring(0,10)),this.logger=t;try{this.isSupported="undefined"!=typeof localStorage}catch(e){this.logger.debug("Remote config localstorage failed to access: ",e),this.isSupported=!1}}return e.prototype.fetchConfig=function(){var e=null,t={remoteConfig:null,lastFetch:new Date};if(!this.isSupported)return Promise.resolve(t);try{e=localStorage.getItem(this.key)}catch(e){return this.logger.debug("Remote config localstorage failed to access: ",e),Promise.resolve(t)}if(null===e)return this.logger.debug("Remote config localstorage gets null because the key does not exist"),Promise.resolve(t);try{var n=JSON.parse(e);return this.logger.debug("Remote config localstorage parsed successfully: ".concat(P(n))),Promise.resolve({remoteConfig:n.remoteConfig,lastFetch:new Date(n.lastFetch)})}catch(e){return this.logger.debug("Remote config localstorage failed to parse: ",e),localStorage.removeItem(this.key),Promise.resolve(t)}},e.prototype.setConfig=function(e){if(!this.isSupported)return Promise.resolve(!1);try{return localStorage.setItem(this.key,JSON.stringify(e)),this.logger.debug("Remote config localstorage set successfully."),Promise.resolve(!0)}catch(e){this.logger.debug("Remote config localstorage failed to set: ",e)}return Promise.resolve(!1)},e}();var $,Z=401,V=403,X=429,Y=function(){function e(t,n,r,i,o,s,a){void 0===r&&(r="US"),void 0===s&&(s=e.DEFAULT_CONFIG_GROUP),this.callbackInfos=[],this.lastSuccessfulFetch=null,this.fetchPromise=null,this.isLastFetchInvalidApiKey=!1,this.apiKey=t,this.configGroup=s,this.serverUrl=i||("US"===r?"https://sr-client-cfg.amplitude.com/config":"https://sr-client-cfg.eu.amplitude.com/config"),this.logger=n,this.storage=a||new J(t,n),this.customFetch=o}return e.prototype.subscribe=function(e,t,n){var r=m(),i={id:r,key:e,deliveryMode:t,callback:n};return this.callbackInfos.push(i),"all"===t?this.subscribeAll(i):this.subscribeWaitForRemote(i,t.timeout),r},e.prototype.unsubscribe=function(e){var t=this.callbackInfos.findIndex(function(t){return t.id===e});return-1===t?(this.logger.debug("Remote config client unsubscribe failed because callback with id ".concat(e," doesn't exist.")),!1):(this.callbackInfos.splice(t,1),this.logger.debug("Remote config client unsubscribe succeeded removing callback with id ".concat(e,".")),!0)},e.prototype.updateConfigs=function(){return a(this,void 0,void 0,function(){var e,t=this;return l(this,function(n){switch(n.label){case 0:return this.lastSuccessfulFetch&&Date.now()-this.lastSuccessfulFetch<3e5?(this.logger.debug("Remote config client skipping updateConfigs: Too recent"),[2]):[4,this.getOrCreateFetchPromise()];case 1:return e=n.sent(),this.storage.setConfig(e),this.callbackInfos.forEach(function(n){t.sendCallback(n,e,"remote")}),[2]}})})},e.prototype.getOrCreateFetchPromise=function(){var e=this;return this.fetchPromise?this.fetchPromise:this.isLastFetchInvalidApiKey?(this.logger.debug("Remote config client skipping fetch: Invalid API key"),this.fetchPromise=Promise.resolve({remoteConfig:null,lastFetch:new Date}).finally(function(){e.fetchPromise=null}),this.fetchPromise):(this.fetchPromise=this.fetch().then(function(t){return null!==t.remoteConfig&&(e.lastSuccessfulFetch=Date.now()),t}).finally(function(){e.fetchPromise=null}),this.fetchPromise)},e.prototype.subscribeAll=function(e){return a(this,void 0,void 0,function(){var t,n,r,i=this;return l(this,function(o){switch(o.label){case 0:return t=this.getOrCreateFetchPromise().then(function(t){i.logger.debug("Remote config client subscription all mode fetched from remote: ".concat(JSON.stringify(t))),i.sendCallback(e,t,"remote"),i.storage.setConfig(t)}),n=this.storage.fetchConfig().then(function(e){return e}),[4,Promise.race([t,n])];case 1:return void 0!==(r=o.sent())&&(this.logger.debug("Remote config client subscription all mode fetched from cache: ".concat(JSON.stringify(r))),null!==r.remoteConfig?this.sendCallback(e,r,"cache"):this.logger.debug("Remote config client skips sending callback because cache is empty (first time user).")),[4,t];case 2:return o.sent(),[2]}})})},e.prototype.subscribeWaitForRemote=function(e,t){return a(this,void 0,void 0,function(){var n,r;return l(this,function(i){switch(i.label){case 0:n=new Promise(function(e,n){setTimeout(function(){n("Timeout exceeded")},t)}),i.label=1;case 1:return i.trys.push([1,3,,5]),[4,Promise.race([this.getOrCreateFetchPromise(),n])];case 2:return r=i.sent(),this.logger.debug("Remote config client subscription wait for remote mode returns from remote."),this.sendCallback(e,r,"remote"),this.storage.setConfig(r),[3,5];case 3:return i.sent(),this.logger.debug("Remote config client subscription wait for remote mode exceeded timeout. Try to fetch from cache."),[4,this.storage.fetchConfig()];case 4:return null!==(r=i.sent()).remoteConfig?(this.logger.debug("Remote config client subscription wait for remote mode returns a cached copy."),this.sendCallback(e,r,"cache")):(this.logger.debug("Remote config client subscription wait for remote mode failed to fetch cache."),this.sendCallback(e,r,"remote")),[3,5];case 5:return[2]}})})},e.prototype.sendCallback=function(e,t,n){var r;e.lastCallback=new Date,r=e.key?e.key.split(".").reduce(function(e,t){return null===e?e:t in e?e[t]:null},t.remoteConfig):t.remoteConfig,e.callback(r,n,t.lastFetch)},e.prototype.fetch=function(e,t){return void 0===e&&(e=3),void 0===t&&(t=1e3),a(this,void 0,void 0,function(){var n,r,i,o,s,a,c=this;return l(this,function(u){switch(u.label){case 0:n=t/e,r={remoteConfig:null,lastFetch:new Date},i=function(r){var i,s,a,u,d,h,v,f,g;return l(this,function(l){switch(l.label){case 0:i=!0,s=new AbortController,a=setTimeout(function(){return s.abort()},t),l.label=1;case 1:return l.trys.push([1,10,11,12]),u=o.getUrlParams(),d={Accept:"*/*"},o.customFetch?[4,(p=o.customFetch({url:u,method:"GET",headers:d,signal:s.signal}),m=s.signal,new Promise(function(e,t){var n=function(){var e=new Error("Remote config custom fetch aborted by timeout");e.name="AbortError",t(e)};m.addEventListener("abort",n,{once:!0}),p.then(function(t){m.removeEventListener("abort",n),e(t)},function(e){m.removeEventListener("abort",n),t(e)})}))]:[3,3];case 2:return v=l.sent(),[3,5];case 3:return[4,fetch(u,{method:"GET",headers:d,signal:s.signal})];case 4:v=l.sent(),l.label=5;case 5:return(h=v).ok||h.status>=200&&h.status<300?[3,7]:[4,h.text()];case 6:return f=l.sent(),o.logger.debug("Remote config client fetch with retry time ".concat(e," failed with ").concat(h.status,": ").concat(f)),h.status===Z||h.status===V?(o.logger.error("Remote config client fetch failed with ".concat(h.status,". Invalid API key; future fetches will be skipped.")),o.isLastFetchInvalidApiKey=!0,i=!1):h.status>=400&&h.status<500&&h.status!==X&&(i=!1),[3,9];case 7:return[4,h.json()];case 8:return[2,{value:{remoteConfig:l.sent(),lastFetch:new Date}}];case 9:return[3,12];case 10:return(g=l.sent())instanceof Error&&"AbortError"===g.name?o.logger.debug("Remote config client fetch with retry time ".concat(e," timed out after ").concat(t,"ms")):o.logger.debug("Remote config client fetch with retry time ".concat(e," is rejected because: "),g),[3,12];case 11:return clearTimeout(a),[7];case 12:return i?r<e-1?[4,new Promise(function(e){return setTimeout(e,c.getJitterDelay(n))})]:[3,14]:[2,"break"];case 13:l.sent(),l.label=14;case 14:return[2]}var p,m})},o=this,s=0,u.label=1;case 1:return s<e?[5,i(s)]:[3,4];case 2:if("object"==typeof(a=u.sent()))return[2,a.value];if("break"===a)return[3,4];u.label=3;case 3:return s++,[3,1];case 4:return[2,r]}})})},e.prototype.getJitterDelay=function(e){return Math.floor(Math.random()*e)},e.prototype.getUrlParams=function(){var e=encodeURIComponent(this.apiKey),t=new URLSearchParams;return t.append("config_group",this.configGroup),"".concat(this.serverUrl,"/").concat(e,"?").concat(t.toString())},e.DEFAULT_CONFIG_GROUP="browser",e}();!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}($||($={}));var ee,te="https://app.amplitude.com",ne={US:te,EU:"https://app.eu.amplitude.com",STAGING:"https://apps.stag2.amplitude.com"};var re="__AMPLITUDE_MESSENGER_INSTANCE__",ie="__AMPLITUDE_MESSENGER__",oe=function(){function e(e){var t=(void 0===e?{}:e).origin,n=void 0===t?te:t;this[ee]=!0,this.isSetup=!1,this.messageHandler=null,this.requestCallbacks={},this.actionHandlers=new Map,this.pendingMessages=new Map,this.scriptLoadPromises=new Map,this.endpoint=n}return e.prototype.notify=function(e){var t,n,r,i;null===(n=null===(t=this.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Message sent: ",JSON.stringify(e)),null===(i=null===(r=window.opener)||void 0===r?void 0:r.postMessage)||void 0===i||i.call(r,e,this.endpoint)},e.prototype.sendRequest=function(e,t,n){var r=this;void 0===n&&(n={timeout:15e3});var i="".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9)),o={id:i,action:e,args:t};return new Promise(function(t,s){r.requestCallbacks[i]={resolve:t,reject:s},r.notify(o),n.timeout>0&&setTimeout(function(){s(new Error("".concat(e," timed out (id: ").concat(i,")"))),delete r.requestCallbacks[i]},n.timeout)})},e.prototype.handleResponse=function(e){var t;this.requestCallbacks[e.id]?(this.requestCallbacks[e.id].resolve(e.responseData),delete this.requestCallbacks[e.id]):null===(t=this.logger)||void 0===t||t.warn("No callback found for request id: ".concat(e.id))},e.prototype.registerActionHandler=function(e,t){var n,r,i,o;this.actionHandlers.has(e)&&(null===(o=null===(i=this.logger)||void 0===i?void 0:i.warn)||void 0===o||o.call(i,"Overwriting existing action handler for: ".concat(e))),this.actionHandlers.set(e,t);var s=this.pendingMessages.get(e);if(s){this.pendingMessages.delete(e);try{for(var a=c(s),l=a.next();!l.done;l=a.next()){t(l.value)}}catch(e){n={error:e}}finally{try{l&&!l.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}}},e.prototype.loadScriptOnce=function(e){return a(this,void 0,void 0,function(){var t,n,r;return l(this,function(i){switch(i.label){case 0:if(t=this.scriptLoadPromises.get(e))return[2,t];n=function(e){return document.querySelector('script[src="'.concat(CSS.escape(e),'"]'))?Promise.resolve({status:!0}):new Promise(function(t,n){var r;try{var i=document.createElement("script");i.type="text/javascript",i.async=!0,i.src=e,i.addEventListener("load",function(){t({status:!0})},{once:!0}),i.addEventListener("error",function(){n({status:!1,message:"Failed to load the script ".concat(e)})}),null===(r=document.head)||void 0===r||r.appendChild(i)}catch(e){n(e)}})}(e).then(function(){}),this.scriptLoadPromises.set(e,n),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,n];case 2:return i.sent(),[3,4];case 3:throw r=i.sent(),this.scriptLoadPromises.delete(e),r;case 4:return[2]}})})},e.prototype.setup=function(e){var t,n,r=this,i=void 0===e?{}:e,o=i.logger,s=i.endpoint;o&&(this.logger=o),s&&this.endpoint===te&&(this.endpoint=s),this.isSetup||(this.isSetup=!0,null===(n=null===(t=this.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Setting up messenger"),this.messageHandler=function(e){var t,n,i,o,s;if(null===(n=null===(t=r.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Message received: ",JSON.stringify(e)),r.endpoint===e.origin){var a=e.data,l=null==a?void 0:a.action;if(l)if("id"in a&&a.id)null===(o=null===(i=r.logger)||void 0===i?void 0:i.debug)||void 0===o||o.call(i,"Received Response to previous request: ",JSON.stringify(e)),r.handleResponse(a);else{if("ping"===l)return void r.notify({action:"pong"});var c=r.actionHandlers.get(l);if(c)c(a.data);else{var u=null!==(s=r.pendingMessages.get(l))&&void 0!==s?s:[];u.push(a.data),r.pendingMessages.set(l,u)}}}},window.addEventListener("message",this.messageHandler),this.notify({action:"page-loaded"}))},e.prototype.destroy=function(){this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.isSetup=!1,this.actionHandlers.clear(),this.pendingMessages.clear(),this.requestCallbacks={},this.scriptLoadPromises.clear();var e=g();(null==e?void 0:e[ie])===this&&delete e[ie]},e}();function se(e){var t,n=g(),r=null==n?void 0:n[ie];if("object"==typeof(t=r)&&null!==t&&re in t&&!0===t[re])return r;var i=new oe(e);return n&&(n[ie]=i),i}ee=re;var ae=["desktop","tablet","mobile"],le="__AMPLITUDE_BACKGROUND_CAPTURE__";function ce(e,t){var n,r=e;if(!0!==r[le]){r[le]=!0;var i=null!==(n=null==t?void 0:t.scriptUrl)&&void 0!==n?n:"https://cdn.amplitude.com/libs/background-capture-1.1.0.js.gz",s=null,a=function(t,n){var r,i;"background-capture-complete"===t&&(null===(i=null===(r=e.logger)||void 0===r?void 0:r.debug)||void 0===i||i.call(r,"Background capture complete"),e.notify({action:"background-capture-complete",data:n}))};e.registerActionHandler("initialize-background-capture",function(t){var n,r;null===(r=null===(n=e.logger)||void 0===n?void 0:n.debug)||void 0===r||r.call(n,"Initializing background capture (external script)");var l=new URL(i,e.endpoint).toString(),c=t&&"object"==typeof t?function(e){if("string"==typeof e)return ae.includes(e)?e:void 0}(t.deviceMode):void 0;e.loadScriptOnce(l).then(function(){var t,n,r;null===(n=null===(t=e.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Background capture script loaded (external)"),s=null===(r=null===window||void 0===window?void 0:window.amplitudeBackgroundCapture)||void 0===r?void 0:r.call(window,o({messenger:e,onBackgroundCapture:a},void 0!==c?{initialDeviceMode:c}:{})),e.notify({action:"background-capture-loaded"})}).catch(function(){var t;null===(t=e.logger)||void 0===t||t.warn("Failed to initialize background capture")})}),e.registerActionHandler("close-background-capture",function(){var e;null===(e=null==s?void 0:s.close)||void 0===e||e.call(s),s=null})}}var ue,de="[Amplitude]",he="".concat(de," Session Replay ID"),ve=$.US,fe={enabled:!0},ge=1e3,pe="".concat(de," Session Replay Debug"),me="https://api-sr.amplitude.com/sessions/v2/track",ye="https://api-sr.eu.amplitude.com/sessions/v2/track",be="https://api-sr.stag2.amplitude.com/sessions/v2/track",Se=9e6,Ie=/payload.*exceed/i,we=500,Ce=1e4,Ee=1024,Pe="X-Session-Replay-Event-Skipped",ke="amplitude-sr-iframe";!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",e.REPLAY_GATE_DECISION="replay-gate-decision"}(ue||(ue={}));var xe=function(){function e(e){this.logger=e,this.log=this.getSafeMethod("log"),this.warn=this.getSafeMethod("warn"),this.error=this.getSafeMethod("error"),this.debug=this.getSafeMethod("debug")}return e.prototype.getSafeMethod=function(e){var t;if(!this.logger)return function(){};var n=this.logger[e];return"function"==typeof n?(null!==(t=n.__rrweb_original__)&&void 0!==t?t:n).bind(this.logger):function(){}},e.prototype.enable=function(e){this.logger.enable(e)},e.prototype.disable=function(){this.logger.disable()},e}(),Me="medium";var Te=new Map,Re=function(e){var t=Te.get(e);if(t)return t;var n="\0TRAIL\0",r="\0MID\0",i="\0DS\0",o="\0ST\0",s="\0QU\0",a=e;a=(a=(a=(a=(a=(a=(a=(a=(a=(a=(a=a.replace(/\/\*\*$/,n)).replace(/\/\*\*\//g,r)).replace(/\*\*/g,i)).replace(/\*/g,o)).replace(/\?/g,s)).replace(/[.+^${}()|[\]\\]/g,"\\$&")).split(n).join("(/.*)?")).split(r).join("/(.*\\/)?")).split(i).join(".*")).split(o).join(".*")).split(s).join(".");var l=new RegExp("^".concat(a,"$"));return Te.set(e,l),l},Oe=function(e,t,n){switch(t){case"light":if("input"!==e)return!1;var r=n?function(e){var t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?t.toLowerCase():null}(n):"";return!!r&&(!!["password","hidden","email","tel"].includes(r)||!!n.autocomplete.startsWith("cc-"));case"medium":return"input"===e;case"conservative":return!0;default:return Oe(e,Me,n)}},_e=function(e,t){var n,r,i;if(e&&t.urlMaskLevels)try{for(var o=c(t.urlMaskLevels),s=o.next();!s.done;s=o.next()){var a=s.value;if(Re(a.match).test(e))return a.maskLevel}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return null!==(i=t.defaultMaskLevel)&&void 0!==i?i:Me},Le=function(e,t,n,r){var i,o;if(void 0===t&&(t={defaultMaskLevel:Me}),n){if(n.closest(".amp-mask, [data-amp-mask]"))return!0;var s=(null!==(i=t.maskSelector)&&void 0!==i?i:[]).some(function(e){return n.closest(e)});if(s)return!0;if(n.closest(".amp-unmask, [data-amp-unmask]"))return!1;var a=(null!==(o=t.unmaskSelector)&&void 0!==o?o:[]).some(function(e){return n.closest(e)});if(a)return!1}return Oe(e,_e(r,t),n)},Fe=function(e,t,n){return function(r,i){return Le(e,t,i,null==n?void 0:n())?r.replace(/[^\s]/g,"*"):r}},De=function(e,t){return function(n,r,i){var o;if("style"===n)return r;if(!(null!==(o=null==e?void 0:e.maskAttributes)&&void 0!==o?o:[]).includes(n))return r;var s=["INPUT","SELECT","TEXTAREA"].includes(i.tagName)?"input":"text";return Le(s,e,i,null==t?void 0:t())?r.replace(/[^\s]/g,"*"):r}},qe=function(e){var t=null==e?void 0:e.blockSelector;return d(d([],u("string"==typeof t?t?[t]:[]:null!=t?t:[]),!1),["[data-amp-block]"],!1).join(",")},Ae=function(e,t){var n,r;return e&&("conservative"===_e(t,e)||"conservative"===e.defaultMaskLevel||(null===(n=e.urlMaskLevels)||void 0===n?void 0:n.some(function(e){return"conservative"===e.maskLevel})))?"*":d(d([],u(null!==(r=null==e?void 0:e.maskSelector)&&void 0!==r?r:[]),!1),["[data-amp-mask]"],!1).join(",")};function Be(e,t){return t||("STAGING"===e?be:"EU"===e?ye:me)}var Ne=function(){var e=g();return(null==e?void 0:e.location)?e.location.href:""},je=function(e,t){var n,r;try{for(var i=c(t),o=i.next();!o.done;o=i.next()){var s=o.value,a=Re(s.selector);if(a.test(e))return e.replace(a,s.replacement)}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return e},Ue=function(){return a(void 0,void 0,void 0,function(){var e,t,n,r,i,o,s;return l(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),(e=g())?[4,e.navigator.storage.estimate()]:[3,2];case 1:return t=a.sent(),n=t.usage,r=t.quota,i=t.usageDetails,o=n?Math.round(n/Ee):0,s=n&&r?Math.round(1e3*(n/r+Number.EPSILON))/1e3:0,[2,{totalStorageSize:o,percentOfQuota:s,usageDetails:JSON.stringify(i)}];case 2:return[3,4];case 3:return a.sent(),[3,4];case 4:return[2,{totalStorageSize:0,percentOfQuota:0,usageDetails:""}]}})})},We=function(e){var t=o({},e),n=t.apiKey;return t.apiKey="****".concat(n.substring(n.length-4)),t},ze=function(){return{flushMaxRetries:2,logLevel:C.Warn,loggerProvider:new M,transportProvider:new Q}},Ke=function(e){function t(t,n){var r,i,s,a,l,c,h,v,f,g,p,m,y,b,S=this,I=ze();(S=e.call(this,o(o({transportProvider:I.transportProvider,loggerProvider:new xe(n.loggerProvider||I.loggerProvider)},n),{apiKey:t}))||this).flushMaxRetries=void 0!==n.flushMaxRetries&&n.flushMaxRetries<=I.flushMaxRetries?n.flushMaxRetries:I.flushMaxRetries,S.apiKey=t,S.sampleRate=n.sampleRate||0,S.serverZone=n.serverZone||ve,S.configServerUrl=n.configServerUrl,S.trackServerUrl=n.trackServerUrl,S.shouldInlineStylesheet=n.shouldInlineStylesheet,S.inlineImages=n.inlineImages,S.version=n.version,S.performanceConfig=n.performanceConfig||fe,S.storeType=null!==(r=n.storeType)&&void 0!==r?r:"memory",S.applyBackgroundColorToBlockedElements=null!==(i=n.applyBackgroundColorToBlockedElements)&&void 0!==i&&i,S.enableUrlChangePolling=null!==(s=n.enableUrlChangePolling)&&void 0!==s&&s,S.urlChangePollingInterval=null!==(a=n.urlChangePollingInterval)&&void 0!==a?a:ge,S.captureDocumentTitle=null!==(l=n.captureDocumentTitle)&&void 0!==l&&l,void 0!==n.fullSnapshotIntervalMs&&(S.fullSnapshotIntervalMs=n.fullSnapshotIntervalMs),void 0!==n.eagerFullSnapshotSend&&(S.eagerFullSnapshotSend=n.eagerFullSnapshotSend),S.captureFullSnapshotOnFocus=null!==(c=n.captureFullSnapshotOnFocus)&&void 0!==c&&c,void 0!==n.maxPersistedEventsSizeBytes&&(S.maxPersistedEventsSizeBytes=$e(n.maxPersistedEventsSizeBytes,Ge,Qe,"maxPersistedEventsSizeBytes",S.loggerProvider)),void 0!==n.maxSingleEventSizeBytes&&(S.maxSingleEventSizeBytes=$e(n.maxSingleEventSizeBytes,Ge,Je,"maxSingleEventSizeBytes",S.loggerProvider)),S.privacyConfig=o(o({},null!==(h=n.privacyConfig)&&void 0!==h?h:{}),{unmaskSelector:Array.from(new Set(d([".".concat("amp-unmask")],u(null!==(f=null===(v=n.privacyConfig)||void 0===v?void 0:v.unmaskSelector)&&void 0!==f?f:[]),!1)))}),n.interactionConfig&&(S.interactionConfig=n.interactionConfig,S.interactionConfig.ugcFilterRules&&function(e){if(!e.every(function(e){return"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(function(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")}(S.interactionConfig.ugcFilterRules)),n.debugMode&&(S.debugMode=n.debugMode);var w=n;return S.useWebWorker=null===(m=null!==(g=n.useWebWorker)&&void 0!==g?g:null===(p=w.experimental)||void 0===p?void 0:p.useWebWorker)||void 0===m||m,S.enableTransportCompression=null===(y=n.enableTransportCompression)||void 0===y||y,S.sendTimeoutMs=n.sendTimeoutMs,S.captureAdoptedStyleSheets=null===(b=n.captureAdoptedStyleSheets)||void 0===b||b,n.crossOriginIframes&&(S.crossOriginIframes=n.crossOriginIframes),n.flushIntervalConfig?S.flushIntervalConfig=function(e,t){var n,r,i={};void 0!==e.minIntervalMs&&(!Number.isFinite(e.minIntervalMs)||e.minIntervalMs<He?(t.warn("flushIntervalConfig.minIntervalMs ".concat(e.minIntervalMs," is below floor ").concat(He,"ms; clamping.")),i.minIntervalMs=He):i.minIntervalMs=e.minIntervalMs);void 0!==e.maxIntervalMs&&(Number.isNaN(e.maxIntervalMs)||e.maxIntervalMs<He?(t.warn("flushIntervalConfig.maxIntervalMs ".concat(e.maxIntervalMs," is below floor ").concat(He,"ms; clamping.")),i.maxIntervalMs=He):i.maxIntervalMs=e.maxIntervalMs);if(void 0!==i.minIntervalMs||void 0!==i.maxIntervalMs){var o=null!==(n=i.minIntervalMs)&&void 0!==n?n:we,s=null!==(r=i.maxIntervalMs)&&void 0!==r?r:Ce;s<o&&(void 0===i.maxIntervalMs?(t.warn("flushIntervalConfig.minIntervalMs (".concat(o,") exceeds the default maxIntervalMs (").concat(Ce,"); raising max to match min.")),i.maxIntervalMs=o):void 0===i.minIntervalMs?(t.warn("flushIntervalConfig.maxIntervalMs (".concat(s,") is below the default minIntervalMs (").concat(we,"); lowering min to match max.")),i.minIntervalMs=s):(t.warn("flushIntervalConfig.maxIntervalMs (".concat(i.maxIntervalMs,") is less than minIntervalMs (").concat(i.minIntervalMs,"); raising max to match min.")),i.maxIntervalMs=i.minIntervalMs))}return i}(n.flushIntervalConfig,S.loggerProvider):S.flushIntervalConfig={minIntervalMs:1e3,maxIntervalMs:1e4},S.handleSendEvents=n.handleSendEvents,S.handleFetchConfig=n.handleFetchConfig,S}return n(t,e),t}(O),He=100,Ge=1e3,Qe=8e6,Je=1e7;function $e(e,t,n,r,i){if(Number.isFinite(e))return e<t?(i.warn("".concat(r," ").concat(e," is below floor ").concat(t,"; clamping.")),t):e>n?(i.warn("".concat(r," ").concat(e," exceeds ceiling ").concat(n,"; clamping.")),n):e;i.warn("".concat(r," value is not a finite number (got ").concat(String(e),"); ignoring."))}var Ze=(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))(Ze||{}),Ve=(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(Ve||{}),Xe=(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))(Xe||{}),Ye=function(e,t){var n=document.createDocumentFragment();return function(e,t,n){var r,i,s=o({},e);try{for(var a=c(["blockSelector","maskSelector","unmaskSelector"]),l=a.next();!l.done;l=a.next()){var u=l.value,d=e[u],h=("string"==typeof d?[d]:null!=d?d:[]).filter(function(e){try{return t(e),!0}catch(t){if(!n)throw new Error("Invalid privacy selector: ".concat(e));return n(e),!1}});s[u]=h.length?h:void 0}}catch(e){r={error:e}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}return s}(e,function(e){n.querySelector(e)},function(e){t.warn('[session-replay-browser] omitting selector "'.concat(e,'" because it is invalid'))})},et=function(){function e(e,t){this.localConfig=t,this.remoteConfigClient=e}return e.prototype.generateJoinedConfig=function(){var e,t,n,r,i,s,h;return a(this,void 0,void 0,function(){var a,v,f,g,p,m,y,b,S,I,w,C,E,P,k,x,M,T=this;return l(this,function(l){switch(l.label){case 0:(a=o({},this.localConfig)).optOut=this.localConfig.optOut,a.captureEnabled=!0,l.label=1;case 1:return l.trys.push([1,3,,4]),[4,new Promise(function(e,t){T.remoteConfigClient.subscribe("configs.sessionReplay",{timeout:1500},function(n,r){var i;if(T.localConfig.loggerProvider.debug("Session Replay remote configuration received from ".concat(r,":"),JSON.stringify(n,null,2)),n){var o=n,s=o.sr_sampling_config,l=o.sr_privacy_config,c=o.sr_targeting_config,u=null===(i=a.interactionConfig)||void 0===i?void 0:i.ugcFilterRules;a.interactionConfig=o.sr_interaction_config,a.interactionConfig&&u&&(a.interactionConfig.ugcFilterRules=u),a.loggingConfig=o.sr_logging_config,(s||l||c)&&(v={},s&&(v.sr_sampling_config=s),l&&(v.sr_privacy_config=l),c&&(v.sr_targeting_config=c)),e()}else t(new Error("No remote config received"))})})];case 2:return l.sent(),[3,4];case 3:return f=l.sent(),this.localConfig.loggerProvider.error("Failed to generate joined config: ",f),a.captureEnabled=!1,[2,{localConfig:this.localConfig,joinedConfig:a,remoteConfig:void 0}];case 4:if(!v)return[2,{localConfig:this.localConfig,joinedConfig:a,remoteConfig:v}];if(g=v.sr_sampling_config,p=v.sr_privacy_config,m=v.sr_targeting_config,g&&Object.keys(g).length>0?(Object.prototype.hasOwnProperty.call(g,"capture_enabled")?a.captureEnabled=g.capture_enabled:a.captureEnabled=!1,Object.prototype.hasOwnProperty.call(g,"sample_rate")&&(a.sampleRate=g.sample_rate),Object.prototype.hasOwnProperty.call(g,"min_session_duration_ms")&&(a.minSessionDurationMs=this.sanitizeMinSessionDurationMs(g.min_session_duration_ms))):(a.captureEnabled=!0,this.localConfig.loggerProvider.debug("Remote config successfully fetched, but no values set for project, Session Replay capture enabled.")),p){y=null!==(e=a.privacyConfig)&&void 0!==e?e:{},b={defaultMaskLevel:null!==(n=null!==(t=p.defaultMaskLevel)&&void 0!==t?t:y.defaultMaskLevel)&&void 0!==n?n:"medium",blockSelector:[],maskSelector:[],unmaskSelector:[],maskAttributes:d([],u(new Set(d(d([],u(null!==(r=y.maskAttributes)&&void 0!==r?r:[]),!1),u(null!==(i=p.maskAttributes)&&void 0!==i?i:[]),!1))),!1),urlMaskLevels:d(d([],u(null!==(s=p.urlMaskLevels)&&void 0!==s?s:[]),!1),u(null!==(h=y.urlMaskLevels)&&void 0!==h?h:[]),!1)},S=function(e){var t,n,r,i,o,s,a,l,u,d={};"string"==typeof e.blockSelector&&(e.blockSelector=[e.blockSelector]);try{for(var h=c(null!==(a=e.blockSelector)&&void 0!==a?a:[]),v=h.next();!v.done;v=h.next()){d[v.value]="block"}}catch(e){t={error:e}}finally{try{v&&!v.done&&(n=h.return)&&n.call(h)}finally{if(t)throw t.error}}try{for(var f=c(null!==(l=e.maskSelector)&&void 0!==l?l:[]),g=f.next();!g.done;g=f.next()){d[g.value]="mask"}}catch(e){r={error:e}}finally{try{g&&!g.done&&(i=f.return)&&i.call(f)}finally{if(r)throw r.error}}try{for(var p=c(null!==(u=e.unmaskSelector)&&void 0!==u?u:[]),m=p.next();!m.done;m=p.next()){d[m.value]="unmask"}}catch(e){o={error:e}}finally{try{m&&!m.done&&(s=p.return)&&s.call(p)}finally{if(o)throw o.error}}return d},I=o(o({},S(y)),S(p));try{for(w=c(Object.entries(I)),C=w.next();!C.done;C=w.next())E=u(C.value,2),P=E[0],"mask"===(k=E[1])?b.maskSelector.push(P):"block"===k?b.blockSelector.push(P):"unmask"===k&&b.unmaskSelector.push(P)}catch(e){x={error:e}}finally{try{C&&!C.done&&(M=w.return)&&M.call(w)}finally{if(x)throw x.error}}a.privacyConfig=Ye(b,this.localConfig.loggerProvider)}return m&&Object.keys(m).length>0&&(a.targetingConfig=m),this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:We(a)},null,2)),[2,{localConfig:this.localConfig,joinedConfig:a,remoteConfig:v}]}})})},e.prototype.sanitizeMinSessionDurationMs=function(e){if("number"==typeof e&&Number.isFinite(e)){if(!(e<0))return e>tt?(this.localConfig.loggerProvider.warn("min_session_duration_ms remote value ".concat(e," exceeds ").concat(tt,"ms ceiling; clamping.")),tt):e;this.localConfig.loggerProvider.warn("min_session_duration_ms remote value is negative (".concat(e,"); ignoring."))}else this.localConfig.loggerProvider.warn("min_session_duration_ms remote value is not a finite number (got ".concat(String(e),"); ignoring."))},e}(),tt=6e4,nt=function(e,t){return a(void 0,void 0,void 0,function(){var n,r;return l(this,function(i){return n=new Ke(e,t),r=new Y(e,n.loggerProvider,n.serverZone,t.configServerUrl,t.handleFetchConfig),[2,new et(r,n)]})})};function rt(e){for(var t=e.length,n=0;n<t&&!(e.charCodeAt(n)>127);n++);if(n===t)return t;for(var r=n;n<t;n++){var i=e.charCodeAt(n);if(i<=127)r++;else if(i<=2047)r+=2;else if(i>=55296&&i<=56319){var o=n+1<t?e.charCodeAt(n+1):NaN;o>=56320&&o<=57343?(r+=4,n++):r+=3}else r+=3}return r}function it(e){for(var t=0,n=0;n<e.length;n++)t+=rt(e[n]);return t}function ot(e,t){if(!(3*e.length<=t)){var n=rt(e);return n>t?n:void 0}}function st(e,t){t<0&&(t=0);for(var n=e.length,r=0,i=0;i<n;i++){var o=e.charCodeAt(i),s=1,a=1;if(o<=127)s=1;else if(o<=2047)s=2;else if(o>=55296&&o<=56319){var l=i+1<n?e.charCodeAt(i+1):NaN;l>=56320&&l<=57343?(s=4,a=2):s=3}else s=3;if(r+s>t)break;r+=s,2===a&&i++}return i>=n?{value:e,truncated:!1}:{value:e.slice(0,i),truncated:!0}}function at(e){if(e.type!==Ze.IncrementalSnapshot)return!1;var t=e.data;return t.source===Ve.Mutation&&!t.isAttachIframe}function lt(e){var t,n,r=new Map;if(e.forEach(function(e,t){if(e.attributes&&"style"in e.attributes){var n=r.get(e.id);n?n.push(t):r.set(e.id,[t])}}),0===r.size)return e;var i=function(t){return e[t].attributes.style},s=new Set,a=new Map,l=function(e){if(1===e.length)return"continue";var t=-1;e.forEach(function(e,n){var r;("object"!=typeof(r=i(e))||null===r)&&(t=n)});var n=[];if(e.forEach(function(e,r){r!==t&&(s.add(e),r>t&&n.push(e))}),n.length>0){var r=n[n.length-1],o=function(e){var t,n,r,i,o={};try{for(var s=c(e),a=s.next();!a.done;a=s.next()){var l=a.value;try{for(var u=(r=void 0,c(Object.keys(l))),d=u.next();!d.done;d=u.next()){var h=d.value;o[h]=l[h]}}catch(e){r={error:e}}finally{try{d&&!d.done&&(i=u.return)&&i.call(u)}finally{if(r)throw r.error}}}}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}return o}(n.map(function(e){return i(e)}));s.delete(r),a.set(r,o)}};try{for(var u=c(r.values()),d=u.next();!d.done;d=u.next()){l(d.value)}}catch(e){t={error:e}}finally{try{d&&!d.done&&(n=u.return)&&n.call(u)}finally{if(t)throw t.error}}if(0===s.size&&0===a.size)return e;var h=[];return e.forEach(function(e,t){var n=a.get(t);if(void 0===n)if(s.has(t)){var r=o({},e.attributes);delete r.style,Object.keys(r).length>0&&h.push(o(o({},e),{attributes:r}))}else h.push(e);else h.push(o(o({},e),{attributes:o(o({},e.attributes),{style:n})}))}),h}function ct(e){var t,n,r,i,s=e[0],a=new Map,l=new Map,d=new Map,h=new Map,v=new Map;e.forEach(function(e,t){var n,r,i,o,s=e.data;try{for(var u=c(s.adds),f=u.next();!f.done;f=u.next()){var g=f.value;a.has(g.node.id)||a.set(g.node.id,t),l.set(g.node.id,t),v.set(g.node.id,g.parentId)}}catch(e){n={error:e}}finally{try{f&&!f.done&&(r=u.return)&&r.call(u)}finally{if(n)throw n.error}}try{for(var p=c(s.removes),m=p.next();!m.done;m=p.next()){var y=m.value;d.has(y.id)||d.set(y.id,t),h.set(y.id,t)}}catch(e){i={error:e}}finally{try{m&&!m.done&&(o=p.return)&&o.call(p)}finally{if(i)throw i.error}}});var f=new Set,g=new Set;try{for(var p=c(a),m=p.next();!m.done;m=p.next()){var y=u(m.value,2),b=y[0],S=y[1],I=d.get(b);if(void 0!==I)l.get(b)>=h.get(b)||(S<I?f.add(b):I<S&&g.add(b))}}catch(e){t={error:e}}finally{try{m&&!m.done&&(n=p.return)&&n.call(p)}finally{if(t)throw t.error}}var w=new Set;if(f.size>0||g.size>0)for(var C=!0;C;){C=!1;try{for(var E=(r=void 0,c(v)),P=E.next();!P.done;P=E.next()){var k=u(P.value,2),x=k[0],M=k[1];if(!f.has(x)&&!g.has(x)&&!w.has(x)&&(f.has(M)||g.has(M)||w.has(M))){var T=d.get(x),R=a.get(x);void 0!==T&&void 0!==R&&T<R?g.add(x):void 0!==T&&void 0!==R&&T===R?w.add(x):f.add(x),C=!0}}}catch(e){r={error:e}}finally{try{P&&!P.done&&(i=E.return)&&i.call(E)}finally{if(r)throw r.error}}}var O=f.size>0||g.size>0||w.size>0,_=[];e.forEach(function(e,t){var n,r;try{for(var i=c(e.data.removes),o=i.next();!o.done;o=i.next()){var s=o.value;f.has(s.id)||(g.has(s.id)&&t>=a.get(s.id)||w.has(s.id)&&(f.has(s.parentId)||g.has(s.parentId)||w.has(s.parentId))||_.push(s))}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}});var L=e.flatMap(function(e){return e.data.adds}),F=e.flatMap(function(e){return e.data.texts}),D=e.flatMap(function(e){return e.data.attributes}),q=O?D.filter(function(e){return!f.has(e.id)&&!g.has(e.id)&&!w.has(e.id)}):D,A={source:Ve.Mutation,removes:_,adds:O?L.filter(function(e){return!f.has(e.node.id)&&!g.has(e.node.id)&&!w.has(e.node.id)}):L,texts:O?F.filter(function(e){return!f.has(e.id)&&!g.has(e.id)&&!w.has(e.id)}):F,attributes:lt(q)};return o(o({},s),{data:A})}function ut(e){if(e.length<=1)return e;for(var t=[],n=0;n<e.length;)if(at(e[n])){for(var r=n+1;r<e.length&&at(e[r]);)r++;t.push(r>n+1?ct(e.slice(n,r)):e[n]),n=r}else t.push(e[n]),n++;return t}var dt=function(){function e(e,t,n,r,i){var o,s=this;this.taskQueue=[],this.pendingQueue=[],this.isProcessing=!1,this.compressEvent=function(e){var t=e,n=t.type,r=t.timestamp,i=t.delay,o=t.data;return null!=i?JSON.stringify({type:n,timestamp:r,delay:i,data:o}):JSON.stringify({type:n,timestamp:r,data:o})},this.addCompressedEventToManager=function(e,t){var n,r=ot(e,null!==(n=s.config.maxSingleEventSizeBytes)&&void 0!==n?n:Se);void 0===r?s.eventsManager&&s.deviceId&&s.eventsManager.addEvent({event:{type:"replay",data:e},sessionId:t,deviceId:s.deviceId}):s.config.loggerProvider.warn("Session replay event dropped: serialized size ".concat(Math.round(r/1024)," KB exceeds maximum allowed event size. If this recurs, please open a GitHub issue at https://github.com/amplitude/Amplitude-TypeScript/issues or contact Amplitude support."))},this.addCompressedEvent=function(e,t){if(s.worker)try{s.worker.postMessage({event:e,sessionId:t})}catch(n){"DataCloneError"===n.name?s.worker.postMessage(JSON.stringify({event:e,sessionId:t})):s.config.loggerProvider.warn("Unexpected error while posting message to worker:",n)}else{var n=s.compressEvent(e);s.addCompressedEventToManager(n,t)}},this.flushQueue=function(){var e;for(s.pendingQueue.length>0&&(e=s.taskQueue).push.apply(e,d([],u(s.mergeMutationTasks(s.pendingQueue.splice(0))),!1));s.taskQueue.length>0;){var t=s.taskQueue.shift();if(t){var n=t.event,r=t.sessionId,i=s.compressEvent(n);s.addCompressedEventToManager(i,r)}}s.isProcessing=!1},this.terminate=function(){var e;null===(e=s.worker)||void 0===e||e.terminate()};var a=g();if(this.canUseIdleCallback=a&&"requestIdleCallback"in a,this.eventsManager=e,this.config=t,this.deviceId=n,this.timeout=(null===(o=t.performanceConfig)||void 0===o?void 0:o.timeout)||2e3,this.onFullSnapshotProcessed=i,r){t.loggerProvider.log("Enabling web worker for compression");try{var l=new Blob([r],{type:"application/javascript"}),c=URL.createObjectURL(l),h=new Worker(c);h.onerror=function(e){e.preventDefault(),t.loggerProvider.error("Worker failed, falling back to non-worker compression: ".concat(e.message," (").concat(e.filename,":").concat(e.lineno,")")),h.terminate(),s.worker=void 0},h.onmessage=function(e){var t=e.data,n=t.compressedEvent,r=t.sessionId;s.addCompressedEventToManager(n,r)},this.worker=h}catch(e){t.loggerProvider.error("Failed to create worker, falling back to non-worker compression:",e)}}}return e.prototype.scheduleIdleProcessing=function(){var e=this;this.isProcessing||(this.isProcessing=!0,requestIdleCallback(function(t){e.processQueue(t)},{timeout:this.timeout}))},e.prototype.enqueueEvent=function(e,t){var n,r,i,o;if(e.type===Ze.FullSnapshot){if(this.config.loggerProvider.debug("Processing full snapshot immediately."),this.taskQueue.length>0||this.pendingQueue.length>0){var s=d(d([],u(this.taskQueue.splice(0)),!1),u(this.mergeMutationTasks(this.pendingQueue.splice(0))),!1);try{for(var a=c(s),l=a.next();!l.done;l=a.next()){var h=l.value,v=this.compressEvent(h.event);this.addCompressedEventToManager(v,h.sessionId)}}catch(e){n={error:e}}finally{try{l&&!l.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}this.isProcessing=!1}var f=this.compressEvent(e);return this.addCompressedEventToManager(f,t),void(null===(i=this.onFullSnapshotProcessed)||void 0===i||i.call(this))}this.canUseIdleCallback&&(null===(o=this.config.performanceConfig)||void 0===o?void 0:o.enabled)?(this.config.loggerProvider.debug("Enqueuing event for processing during idle time."),this.pendingQueue.push({event:e,sessionId:t}),this.scheduleIdleProcessing()):(this.config.loggerProvider.debug("Processing event without idle callback."),this.addCompressedEvent(e,t))},e.prototype.processQueue=function(e){var t,n=this;for(this.pendingQueue.length>0&&(t=this.taskQueue).push.apply(t,d([],u(this.mergeMutationTasks(this.pendingQueue.splice(0))),!1));this.taskQueue.length>0&&(e.timeRemaining()>0||e.didTimeout);){var r=this.taskQueue.shift();if(r){var i=r.event,o=r.sessionId;this.addCompressedEvent(i,o)}}this.taskQueue.length>0||this.pendingQueue.length>0?requestIdleCallback(function(e){n.processQueue(e)},{timeout:this.timeout}):this.isProcessing=!1},e.prototype.mergeMutationTasks=function(e){var t,n,r;if(!1===(null===(r=this.config.performanceConfig)||void 0===r?void 0:r.mergeMutations))return e;if(e.length<=1)return e;for(var i=[],o=0;o<e.length;){for(var s=e[o].sessionId,a=o+1;a<e.length&&e[a].sessionId===s;)a++;var l=ut(e.slice(o,a).map(function(e){return e.event}));try{for(var u=(t=void 0,c(l)),d=u.next();!d.done;d=u.next()){var h=d.value;i.push({event:h,sessionId:s})}}catch(e){t={error:e}}finally{try{d&&!d.done&&(n=u.return)&&n.call(u)}finally{if(t)throw t.error}}o=a}return i},e}(),ht="Session replay event batch rejected due to exceeded retry count",vt="Failed to store session replay events in IndexedDB",ft="Session replay event batch dropped: server signalled capture disabled or session out of valid range for this session",gt="1.51.2";function pt(e,t){return a(this,void 0,void 0,function(){var n,r,i,o,s,u,d,h,v,f,g,p,m,y,b=this;return l(this,function(S){switch(S.label){case 0:return S.trys.push([0,4,,5]),n=t.CompressionStream,r=new n("gzip"),i=r.writable.getWriter(),o=r.readable.getReader(),s=[],u=a(b,void 0,void 0,function(){var e,t,n;return l(this,function(r){switch(r.label){case 0:return[4,o.read()];case 1:if(e=r.sent(),t=e.done,n=e.value,t)return[3,3];s.push(n),r.label=2;case 2:return[3,0];case 3:return[2]}})}),[4,i.write((new TextEncoder).encode(e))];case 1:return S.sent(),[4,i.close()];case 2:return S.sent(),[4,u];case 3:S.sent(),d=s.reduce(function(e,t){return e+t.length},0),h=new Uint8Array(d),v=0;try{for(f=c(s),g=f.next();!g.done;g=f.next())p=g.value,h.set(p,v),v+=p.length}catch(e){m={error:e}}finally{try{g&&!g.done&&(y=f.return)&&y.call(f)}finally{if(m)throw m.error}}return[2,h];case 4:return S.sent(),[2,null];case 5:return[2]}})})}var mt=function(){function e(e){var t=e.trackServerUrl,n=e.loggerProvider,r=e.payloadBatcher,i=e.workerScript,o=e.enableTransportCompression,s=e.sendTimeoutMs,a=e.handleSendEvents,l=this;if(this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.sendIdCounter=0,this.pendingWorkerRequests=new Map,this.timedOutWorkerRequests=new Map,this.flushPauseUntilMs=0,this.mergeOnNextFlush=!1,this.coalesceNextFlush=!1,this.mergeLogFiredThisPause=!1,this.killedSessions=new Set,this.loggerProvider=n,this.payloadBatcher=r||function(e){return e},this.trackServerUrl=t,this.enableTransportCompression=null==o||o,this.sendTimeoutMs=null!=s?s:1e4,this.handleSendEvents=a,i)try{var d=new Blob([i],{type:"application/javascript"}),h=URL.createObjectURL(d),v=new Worker(h);v.onerror=function(e){var t,r;e.preventDefault(),n.error("Track destination worker failed, falling back to main-thread sending: ".concat(e.message," (").concat(e.filename,":").concat(e.lineno,")")),v.terminate(),l.worker=void 0;try{for(var i=c(l.pendingWorkerRequests),o=i.next();!o.done;o=i.next()){var s=u(o.value,2)[1];s.timeout&&clearTimeout(s.timeout),n.warn("Session replay event send failed due to worker crash: ".concat(e.message)),s.resolve()}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}l.pendingWorkerRequests.clear(),l.timedOutWorkerRequests.clear()},v.onmessage=function(e){var t=e.data;if("log"===t.type)n.log(t.message);else if("warn"===t.type)n.warn(t.message);else if("payload_too_large"===t.type){var r=l.pendingWorkerRequests.get(t.id);if(r)r.timeout&&clearTimeout(r.timeout),l.handlePayloadTooLargeResponse(r.context,t.isWaf),r.resolve(),l.pendingWorkerRequests.delete(t.id);else(i=l.timedOutWorkerRequests.get(t.id))&&(l.timedOutWorkerRequests.delete(t.id),l.handlePayloadTooLargeResponse(i,t.isWaf))}else if("complete"===t.type){var i,o=l.pendingWorkerRequests.get(t.id);if(o)o.timeout&&clearTimeout(o.timeout),void 0!==t.skipCode&&l.applyServerDirective(o.context.sessionId,t.skipCode),l.completeRequest({context:o.context}),o.resolve(),l.pendingWorkerRequests.delete(t.id);else(i=l.timedOutWorkerRequests.get(t.id))&&(l.timedOutWorkerRequests.delete(t.id),void 0!==t.skipCode&&l.applyServerDirective(i.sessionId,t.skipCode),l.completeRequest({context:i}))}else"fetch-request"===t.type&&l.handleDelegatedFetch(v,t).catch(function(e){n.warn("Failed to handle delegated session replay fetch:",e)})},this.worker=v}catch(e){n.error("Failed to create track destination worker, falling back to main-thread sending:",e)}}return e.prototype.sendEventsList=function(e){this.addToQueue(o(o({},e),{attempts:0,timeout:0}))},e.prototype.markCoalesceNextFlush=function(){this.coalesceNextFlush=!0,this.schedule(0)},e.prototype.sendBeacon=function(e){var t,n,r=this,i=e.events,o=e.sessionId,s=e.deviceId,a=e.apiKey,l=e.serverZone,c=function(e){return rt(e)},u=i,d=JSON.stringify({version:2,events:u});if(c(d)>65536){for(var h=0,v=u.length;h<v;){var f=Math.floor((h+v+1)/2);c(JSON.stringify({version:2,events:u.slice(0,f)}))<=65536?h=f:v=f-1}u=u.slice(0,h),d=JSON.stringify({version:2,events:u}),this.loggerProvider.warn("sendBeacon payload exceeded 64 KB limit, trimmed from ".concat(i.length," to ").concat(u.length," events"))}if(0!==u.length)if(this.handleSendEvents){var p=new URLSearchParams({device_id:s,session_id:String(o),type:"replay"}),m="".concat(Be(l,this.trackServerUrl),"?").concat(p.toString()),y={"Content-Type":"application/json",Accept:"*/*",Authorization:"Bearer ".concat(a)};this.loggerProvider.debug("Routing session replay exit batch (".concat(u.length," events) through custom transport for session id ").concat(o,"."));try{this.handleSendEvents({url:m,method:"POST",headers:y,body:d,keepalive:!0}).catch(function(e){r.loggerProvider.warn("Custom transport failed to send session replay exit batch:",e)})}catch(e){this.loggerProvider.warn("Custom transport threw while sending session replay exit batch:",e)}}else{var b=new URLSearchParams({device_id:s,session_id:String(o),type:"replay",api_key:a}),S="".concat(Be(l,this.trackServerUrl),"?").concat(b.toString()),I=g();try{var w=new Blob([d],{type:"application/json"});!1===(null===(n=null===(t=null==I?void 0:I.navigator)||void 0===t?void 0:t.sendBeacon)||void 0===n?void 0:n.call(t,S,w))&&this.loggerProvider.warn("sendBeacon failed to queue session replay payload")}catch(e){}}},e.prototype.addToQueue=function(){for(var e=this,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];t.filter(function(t){return e.killedSessions.has(t.sessionId)?(e.completeRequest({context:t,err:ft}),!1):t.attempts<(t.flushMaxRetries||0)?(t.attempts+=1,!0):(e.completeRequest({context:t,err:ht}),!1)}).forEach(function(t){e.queue=e.queue.concat(t),e.schedule(0)})},e.prototype.schedule=function(e){var t=this;if(!this.scheduled){var n=this.flushPauseUntilMs-Date.now(),r=n>e?n:e;n>0&&(this.mergeOnNextFlush=!0),this.scheduled=setTimeout(function(){t.flush(!0).then(function(){t.queue.length>0&&t.schedule(e)})},r)}},e.prototype.flush=function(e){return void 0===e&&(e=!1),a(this,void 0,void 0,function(){var t,n,r,i,o,s,a;return l(this,function(l){switch(l.label){case 0:t=this.queue,this.queue=[],this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null),this.mergeOnNextFlush?(this.mergeOnNextFlush=!1,this.coalesceNextFlush=!1,t=this.mergeQueueAfterThrottle(t)):this.coalesceNextFlush&&(this.coalesceNextFlush=!1,t=this.mergeDrainBacklog(t)),l.label=1;case 1:l.trys.push([1,6,7,8]),n=c(t),r=n.next(),l.label=2;case 2:return r.done?[3,5]:(i=r.value,[4,this.send(i,e)]);case 3:l.sent(),l.label=4;case 4:return r=n.next(),[3,2];case 5:return[3,8];case 6:return o=l.sent(),s={error:o},[3,8];case 7:try{r&&!r.done&&(a=n.return)&&a.call(n)}finally{if(s)throw s.error}return[7];case 8:return[2]}})})},e.prototype.mergeQueueAfterThrottle=function(e){var t=this.coalesceByIdentity(e);return t.length<e.length&&!this.mergeLogFiredThisPause&&(this.mergeLogFiredThisPause=!0,this.loggerProvider.log("Session replay throttle pause ended; merged ".concat(e.length," queued batches into ").concat(t.length," request(s)"))),t},e.prototype.mergeDrainBacklog=function(e){var t=this.coalesceByIdentity(e);return t.length<e.length&&this.loggerProvider.log("Session replay coalesced ".concat(e.length," persisted page-load backlog batches into ").concat(t.length," request(s)")),t},e.prototype.coalesceByIdentity=function(e){var t,n,r,i,s,h,v,f,g,p,m,y=this;if(e.length<=1)return e;var b=new Map;try{for(var S=c(e),I=S.next();!I.done;I=S.next()){var w=I.value,C=[w.sessionId,null!==(s=w.deviceId)&&void 0!==s?s:"",null!==(h=w.apiKey)&&void 0!==h?h:"",w.type,null!==(v=w.serverZone)&&void 0!==v?v:"",w.sampleRate,null!==(g=null===(f=w.version)||void 0===f?void 0:f.type)&&void 0!==g?g:"",null!==(m=null===(p=w.version)||void 0===p?void 0:p.version)&&void 0!==m?m:""].join("|"),E=b.get(C);E?E.push(w):b.set(C,[w])}}catch(e){t={error:e}}finally{try{I&&!I.done&&(n=S.return)&&n.call(S)}finally{if(t)throw t.error}}var P=[],k=function(e){var t,n;if(1===e.length)return P.push(e[0]),"continue";var r=null,i=0,s=function(){r&&P.push(r),r=null,i=0},h=function(e){var t=it(e.events);if(null===r)return r=o(o({},e),{events:d([],u(e.events),!1),attempts:0}),i=t,"continue";if(i+t>4e6)return s(),r=o(o({},e),{events:d([],u(e.events),!1),attempts:0}),i=t,"continue";var n=r.onComplete,c=e.onComplete;r.events=r.events.concat(e.events),i+=t,r.onComplete=function(){return a(y,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,Promise.allSettled([n(),c()])];case 1:return e.sent(),[2]}})})}};try{for(var v=(t=void 0,c(e)),f=v.next();!f.done;f=v.next()){h(f.value)}}catch(e){t={error:e}}finally{try{f&&!f.done&&(n=v.return)&&n.call(v)}finally{if(t)throw t.error}}s()};try{for(var x=c(b.values()),M=x.next();!M.done;M=x.next()){k(M.value)}}catch(e){r={error:e}}finally{try{M&&!M.done&&(i=x.return)&&i.call(x)}finally{if(r)throw r.error}}return P},e.prototype.send=function(e,t){return void 0===t&&(t=!0),a(this,void 0,void 0,function(){var n,r,i,o;return l(this,function(s){return this.killedSessions.has(e.sessionId)?[2,this.completeRequest({context:e,err:ft})]:(n=e.apiKey)?(r=e.deviceId)?0===(i=this.payloadBatcher({version:1,events:e.events})).events.length?(this.completeRequest({context:e}),[2]):(o=this.worker)?[2,this.sendViaWorker(o,e,i,t)]:[2,this.sendOnMainThread(n,r,e,i,t)]:[2,this.completeRequest({context:e,err:"Session replay event batch not sent due to missing device ID"})]:[2,this.completeRequest({context:e,err:"Session replay event batch not sent due to missing api key"})]})})},e.prototype.sendViaWorker=function(e,t,n,r){return a(this,void 0,void 0,function(){var i,o=this;return l(this,function(s){return i="".concat(++this.sendIdCounter),[2,new Promise(function(s){var a,l=o.sendTimeoutMs>0?setTimeout(function(){var e=o.pendingWorkerRequests.get(i);e&&(o.pendingWorkerRequests.delete(i),o.rememberTimedOutRequest(i,e.context),o.loggerProvider.warn("Session replay worker send timed out after ".concat(o.sendTimeoutMs,"ms; leaving events for retry")),e.resolve())},o.sendTimeoutMs):void 0;o.pendingWorkerRequests.set(i,{context:t,resolve:s,timeout:l}),e.postMessage({type:"send",id:i,payload:n,useRetry:r,useCustomTransport:!!o.handleSendEvents,context:{apiKey:t.apiKey,deviceId:t.deviceId,sessionId:t.sessionId,events:t.events,eventType:t.type,flushMaxRetries:null!==(a=t.flushMaxRetries)&&void 0!==a?a:0,sampleRate:t.sampleRate,serverZone:t.serverZone,trackServerUrl:o.trackServerUrl,version:t.version,currentUrl:Ne(),sdkVersion:gt,enableTransportCompression:o.enableTransportCompression,sendTimeoutMs:o.sendTimeoutMs}})})]})})},e.prototype.rememberTimedOutRequest=function(e,t){var n,r;if(this.timedOutWorkerRequests.set(e,t),this.timedOutWorkerRequests.size>256)try{for(var i=c(this.timedOutWorkerRequests.keys()),o=i.next();!o.done;o=i.next()){var s=o.value;this.timedOutWorkerRequests.delete(s);break}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}},e.prototype.handleDelegatedFetch=function(e,t){var n,r,i;return a(this,void 0,void 0,function(){var o,s,a,c,u,d,h,v,f,g,p;return l(this,function(l){switch(l.label){case 0:o=t.requestId,s=t.url,a=t.method,c=t.headers,u=t.body,d=t.keepalive,l.label=1;case 1:return l.trys.push([1,10,,11]),h=void 0,this.handleSendEvents?[4,this.handleSendEvents({url:s,method:a,headers:c,body:u,keepalive:d})]:[3,3];case 2:return h=l.sent(),[3,5];case 3:return this.loggerProvider.warn("Delegated session replay fetch received without a custom transport configured; falling back to built-in fetch."),[4,fetch(s,{method:a,headers:c,body:u,keepalive:d})];case 4:h=l.sent(),l.label=5;case 5:if(v=h.status,f=null,g="",v>=200&&v<300&&(f=null!==(i=null===(r=null===(n=h.headers)||void 0===n?void 0:n.get)||void 0===r?void 0:r.call(n,Pe))&&void 0!==i?i:null),413!==v)return[3,9];l.label=6;case 6:return l.trys.push([6,8,,9]),[4,h.text()];case 7:return g=l.sent(),[3,9];case 8:return l.sent(),[3,9];case 9:return this.loggerProvider.debug("Delegated session replay fetch (request ".concat(o,") returned status ").concat(v,".")),e.postMessage({type:"fetch-response",requestId:o,status:v,skipHeader:f,body:g}),[3,11];case 10:return p=l.sent(),this.loggerProvider.debug("Delegated session replay fetch (request ".concat(o,") failed:"),p),e.postMessage({type:"fetch-response",requestId:o,status:0,skipHeader:null,body:String(p),error:!0}),[3,11];case 11:return[2]}})})},e.prototype.sendOnMainThread=function(e,t,n,r,i){var s,c,u,d,h,v,f;return a(this,void 0,void 0,function(){var a,p,m,y,b,S,I,w,C,E,P,k,x,M,T,R,O,_,L,F,D,q;return l(this,function(l){switch(l.label){case 0:a=Ne(),p=gt,m=n.sampleRate,y=new URLSearchParams({device_id:t,session_id:"".concat(n.sessionId),type:"".concat(n.type)}),b="".concat(null!==(c=null===(s=n.version)||void 0===s?void 0:s.type)&&void 0!==c?c:"standalone","/").concat(null!==(d=null===(u=n.version)||void 0===u?void 0:u.version)&&void 0!==d?d:p),l.label=1;case 1:return l.trys.push([1,19,,23]),S=JSON.stringify(r),I=g(),this.enableTransportCompression&&I&&"CompressionStream"in I?[4,pt(S,I)]:[3,3];case 2:return C=l.sent(),[3,4];case 3:C=null,l.label=4;case 4:if(E=(w=C)?w.byteLength:rt(S),P=new AbortController,k=o({"Content-Type":"application/json",Accept:"*/*",Authorization:"Bearer ".concat(e),"X-Client-Version":p,"X-Client-Library":b,"X-Client-Url":a.substring(0,1e3),"X-Client-Sample-Rate":"".concat(m),"X-Sampling-Hash-Alg":"xxhash32"},w?{"Content-Encoding":"gzip"}:{}),T={headers:k,body:x=null!=w?w:S,method:"POST",keepalive:M=E<=65536,signal:P.signal},R="".concat(Be(n.serverZone,this.trackServerUrl),"?").concat(y.toString()),0===r.events.length)return this.completeRequest({context:n}),[2];O=this.sendTimeoutMs>0?setTimeout(function(){P.abort()},this.sendTimeoutMs):void 0,_=void 0,l.label=5;case 5:return l.trys.push([5,,10,11]),this.handleSendEvents?[4,(A=this.handleSendEvents({url:R,method:"POST",headers:k,body:x,keepalive:M}),B=P.signal,new Promise(function(e,t){var n=function(){var e=new Error("Custom session replay transport aborted by send timeout");e.name="AbortError",t(e)};B.addEventListener("abort",n,{once:!0}),A.then(function(t){B.removeEventListener("abort",n),e(t)},function(e){B.removeEventListener("abort",n),t(e)})}))]:[3,7];case 6:return L=l.sent(),[3,9];case 7:return[4,fetch(R,T)];case 8:L=l.sent(),l.label=9;case 9:return _=L,[3,11];case 10:return O&&clearTimeout(O),[7];case 11:if(null===_)return this.completeRequest({context:n,err:"Unexpected error occurred"}),[2];if(_.status>=200&&_.status<300&&(F=null!==(f=null===(v=null===(h=_.headers)||void 0===h?void 0:h.get)||void 0===v?void 0:v.call(h,Pe))&&void 0!==f?f:null,this.applyServerDirective(n.sessionId,F)),i)return[3,12];D="";try{D=JSON.stringify(_.body,null,2)}catch(e){}return this.completeRequest({context:n,success:"".concat(_.status,": ").concat(D)}),[3,18];case 12:if(D="",413!==_.status)return[3,16];l.label=13;case 13:return l.trys.push([13,15,,16]),[4,_.text()];case 14:return D=l.sent(),[3,16];case 15:return l.sent(),[3,16];case 16:return[4,this.handleReponse(_.status,n,D)];case 17:l.sent(),l.label=18;case 18:return[3,23];case 19:return q=l.sent(),!!q&&"object"==typeof q&&"AbortError"===q.name&&i?[4,this.handleOtherResponse(n)]:[3,21];case 20:return l.sent(),[3,22];case 21:this.completeRequest({context:n,err:q}),l.label=22;case 22:return[3,23];case 23:return[2]}var A,B})})},e.prototype.handleReponse=function(e,t,n){return void 0===n&&(n=""),a(this,void 0,void 0,function(){var r;return l(this,function(i){switch(i.label){case 0:switch(r=(new G).buildStatus(e),r){case h.Success:return[3,1];case h.Failed:case h.Timeout:case h.RateLimit:return[3,2];case h.PayloadTooLarge:return[3,4]}return[3,5];case 1:return this.handleSuccessResponse(t),[3,8];case 2:return[4,this.handleOtherResponse(t)];case 3:return i.sent(),[3,8];case 4:return this.handlePayloadTooLargeResponse(t,Ie.test(n)),[3,8];case 5:return 499!==e?[3,7]:[4,this.handleOtherResponse(t)];case 6:return i.sent(),[3,8];case 7:this.completeRequest({context:t,err:"Network error occurred, event batch rejected"}),i.label=8;case 8:return[2]}})})},e.prototype.handlePayloadTooLargeResponse=function(e,t){var n=t?"WAF (compressed payload too large)":"server (event too large)",r=Math.round(e.events.reduce(function(e,t){return e+t.length},0)/Ee);if(t)if(1!==e.events.length){this.loggerProvider.warn("Session replay event batch rejected by ".concat(n," (").concat(e.events.length," events, ").concat(r," KB total) — splitting and retrying")),e.onComplete();var i=function(){return Promise.resolve()},s=Math.floor(e.events.length/2);this.sendEventsList(o(o({},e),{events:e.events.slice(0,s),onComplete:i})),this.sendEventsList(o(o({},e),{events:e.events.slice(s),onComplete:i}))}else this.completeRequest({context:e,err:"Session replay event dropped: single event (".concat(r," KB, 1 event) rejected by ").concat(n," — cannot split further")});else this.completeRequest({context:e,err:"Session replay event batch dropped: ".concat(n," rejected payload (").concat(e.events.length," events, ").concat(r," KB) — not retrying non-WAF 413")})},e.prototype.handleSuccessResponse=function(e){var t=Math.round(it(e.events)/Ee);this.completeRequest({context:e,success:"Session replay event batch tracked successfully for session id ".concat(e.sessionId,", size of events: ").concat(t," KB")})},e.prototype.handleOtherResponse=function(e){return a(this,void 0,void 0,function(){var t;return l(this,function(n){switch(n.label){case 0:return t=Math.random()*e.attempts*this.retryTimeout,e.attempts++,e.attempts>(e.flushMaxRetries||0)?(this.completeRequest({context:e,err:ht}),[2]):[4,new Promise(function(e){return setTimeout(e,t)})];case 1:return n.sent(),[4,this.send(e,!0)];case 2:return n.sent(),[2]}})})},e.prototype.completeRequest=function(e){var t=e.context,n=e.err,r=e.success;t.onComplete(),n?this.loggerProvider.warn(n):r&&this.loggerProvider.log(r)},e.prototype.applyServerDirective=function(e,t){if(null===t)return this.flushPauseUntilMs=0,void(this.mergeLogFiredThisPause=!1);if("429"===t){var n=this.flushPauseUntilMs>Date.now();return this.flushPauseUntilMs=Date.now()+6e4,void(n||this.loggerProvider.log("Session replay throttled by server; pausing flush schedule for ".concat(60,"s")))}"4005"!==t&&"4004"!==t||this.killSession(e,t)},e.prototype.killSession=function(e,t){var n,r,i,o;if(!this.killedSessions.has(e)){if(this.killedSessions.add(e),this.killedSessions.size>256)try{for(var s=c(this.killedSessions),a=s.next();!a.done;a=s.next()){var l=a.value;this.killedSessions.delete(l);break}}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(n)throw n.error}}this.loggerProvider.log("Session replay capture stopped for session ".concat(e," by server directive ").concat(t,"; remaining events will be dropped"));var u=[];try{for(var d=c(this.queue),h=d.next();!h.done;h=d.next()){var v=h.value;v.sessionId===e?this.completeRequest({context:v,err:ft}):u.push(v)}}catch(e){i={error:e}}finally{try{h&&!h.done&&(o=d.return)&&o.call(d)}finally{if(i)throw i.error}}this.queue=u}},e}();const yt=(e,t)=>t.some(t=>e instanceof t);let bt,St;const It=new WeakMap,wt=new WeakMap,Ct=new WeakMap;let Et={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return It.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Mt(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function Pt(e){Et=e(Et)}function kt(e){return(St||(St=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(Tt(this),t),Mt(this.request)}:function(...t){return Mt(e.apply(Tt(this),t))}}function xt(e){return"function"==typeof e?kt(e):(e instanceof IDBTransaction&&function(e){if(It.has(e))return;const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",o),e.removeEventListener("abort",o)},i=()=>{t(),r()},o=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",i),e.addEventListener("error",o),e.addEventListener("abort",o)});It.set(e,t)}(e),yt(e,bt||(bt=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,Et):e)}function Mt(e){if(e instanceof IDBRequest)return function(e){const t=new Promise((t,n)=>{const r=()=>{e.removeEventListener("success",i),e.removeEventListener("error",o)},i=()=>{t(Mt(e.result)),r()},o=()=>{n(e.error),r()};e.addEventListener("success",i),e.addEventListener("error",o)});return Ct.set(t,e),t}(e);if(wt.has(e))return wt.get(e);const t=xt(e);return t!==e&&(wt.set(e,t),Ct.set(t,e)),t}const Tt=e=>Ct.get(e);function Rt(e,t,{blocked:n,upgrade:r,blocking:i,terminated:o}={}){const s=indexedDB.open(e,t),a=Mt(s);return r&&s.addEventListener("upgradeneeded",e=>{r(Mt(s.result),e.oldVersion,e.newVersion,Mt(s.transaction),e)}),n&&s.addEventListener("blocked",e=>n(e.oldVersion,e.newVersion,e)),a.then(e=>{o&&e.addEventListener("close",()=>o()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),a}const Ot=["get","getKey","getAll","getAllKeys","count"],_t=["put","add","delete","clear"],Lt=new Map;function Ft(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(Lt.get(t))return Lt.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=_t.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!Ot.includes(n))return;const o=async function(e,...t){const o=this.transaction(e,i?"readwrite":"readonly");let s=o.store;return r&&(s=s.index(t.shift())),(await Promise.all([s[n](...t),i&&o.done]))[0]};return Lt.set(t,o),o}Pt(e=>({...e,get:(t,n,r)=>Ft(t,n)||e.get(t,n,r),has:(t,n)=>!!Ft(t,n)||e.has(t,n)}));const Dt=["continue","continuePrimaryKey","advance"],qt={},At=new WeakMap,Bt=new WeakMap,Nt={get(e,t){if(!Dt.includes(t))return e[t];let n=qt[t];return n||(n=qt[t]=function(...e){At.set(this,Bt.get(this)[t](...e))}),n}};async function*jt(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,Nt);for(Bt.set(n,t),Ct.set(n,Tt(t));t;)yield n,t=await(At.get(n)||t.continue()),At.delete(n)}function Ut(e,t){return t===Symbol.asyncIterator&&yt(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&yt(e,[IDBIndex,IDBObjectStore])}Pt(e=>({...e,get:(t,n,r)=>Ut(t,n)?jt:e.get(t,n,r),has:(t,n)=>Ut(t,n)||e.has(t,n)}));var Wt=function(){function e(e){var t,n,r,i=this;this.minInterval=we,this.maxInterval=Ce,this.maxPersistedEventsSize=6e6,this._timeAtLastSplit=Date.now(),this.eventsContentBytes=new WeakMap,this.sequenceContentBytes=new Map,this.shouldSplitEventsList=function(e,t){var n=i.getEventsArraySize(e),r=i.maxPersistedEventsSize-n,o=t.length>=r;return!o&&3*t.length>=r&&(o=rt(t)>=r),!!o||!!(Date.now()-i.timeAtLastSplit>i.interval&&e.length)&&(i.interval=Math.min(i.maxInterval,i.interval+i.minInterval),i._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!==(r=e.maxPersistedEventsSize)&&void 0!==r?r:this.maxPersistedEventsSize,this.interval=this.minInterval}return Object.defineProperty(e.prototype,"timeAtLastSplit",{get:function(){return this._timeAtLastSplit},enumerable:!1,configurable:!0}),e.prototype.isPrefixOf=function(e,t){return!(t.length<e.length)&&(0===e.length||t[e.length-1]===e.tail)},e.prototype.measureContentBytes=function(e,t){if(e&&e.length===t.length&&this.isPrefixOf(e,t))return e;var n=0,r=0;e&&this.isPrefixOf(e,t)&&(n=e.contentBytes,r=e.length);for(var i=r;i<t.length;i++)n+=rt(t[i]);return{length:t.length,contentBytes:n,tail:t.length>0?t[t.length-1]:void 0}},e.prototype.getEventsContentBytes=function(e){var t=this.measureContentBytes(this.eventsContentBytes.get(e),e);return this.eventsContentBytes.set(e,t),t.contentBytes},e.prototype.getEventsArraySize=function(e){return this.getEventsContentBytes(e)+(2+Math.max(0,e.length-1)+2*e.length)},e.prototype.recallSequenceContentBytes=function(e,t){var n=this.sequenceContentBytes.get(e);n&&n.length===t.length&&this.isPrefixOf(n,t)&&this.eventsContentBytes.set(t,n)},e.prototype.rememberSequenceContentBytes=function(e,t){var n=this.measureContentBytes(this.sequenceContentBytes.get(e),t);this.sequenceContentBytes.set(e,n),this.eventsContentBytes.set(t,n)},e.prototype.forgetSequenceContentBytes=function(e){this.sequenceContentBytes.delete(e)},e}(),zt=function(e,t,n){var r;"object"==typeof(r=n)&&null!==r&&"AbortError"===r.name?e.debug(t):e.warn(t)};var Kt="sessionCurrentSequence",Ht="sequencesToSend",Gt=5e3;function Qt(e,t,n){var r=setTimeout(n,t);return e.then(function(){return clearTimeout(r)},function(){return clearTimeout(r)}),function(){return clearTimeout(r)}}var Jt,$t,Zt,Vt=function(e){var t,n;return e.objectStoreNames.contains(Kt)||(n=e.createObjectStore(Kt,{keyPath:"sessionId"})),e.objectStoreNames.contains(Ht)||(t=e.createObjectStore(Ht,{keyPath:"sequenceId",autoIncrement:!0})).createIndex("sessionId","sessionId"),{sequencesStore:t,currentSequenceStore:n}},Xt=function(e){return a(void 0,void 0,void 0,function(){return l(this,function(t){switch(t.label){case 0:return[4,(n=Rt(e,1,{upgrade:Vt}),r=2e3,i="IDB openDB timed out",void 0===i&&(i="IDB operation timed out"),new Promise(function(e,t){var o=setTimeout(function(){return t(new Error("".concat(i," after ").concat(r,"ms")))},r);n.then(function(t){clearTimeout(o),e(t)},function(e){clearTimeout(o),t(e)})}))];case 1:return[2,t.sent()]}var n,r,i})})},Yt=function(e){function t(t){var n,r=this;return(r=e.call(this,t)||this).consecutiveFailures=0,r.hasTriggeredFallback=!1,r.emptyFilteredCount=0,r.getSequencesToSend=function(){return a(r,void 0,void 0,function(){var e,t,n,r,i,o,s,a,c,u,d=this;return l(this,function(l){switch(l.label){case 0:e=!1,t=!1,l.label=1;case 1:return l.trys.push([1,9,,10]),n=[],(r=this.db.transaction("sequencesToSend","readwrite")).done.catch(function(n){e||t||(zt(d.loggerProvider,"".concat(vt,": ").concat(n),n),d.recordFailure())}),i=Qt(r.done,Gt,function(){e||t||(t=!0,zt(d.loggerProvider,"".concat(vt,": transaction timed out")),d.recordFailure())}),[4,r.store.openCursor()];case 2:o=l.sent(),l.label=3;case 3:return o?(s=o.value,a=s.sessionId,0!==(c=s.events).length?[3,5]:(this.maybeLogEmptyFiltered("getSequencesToSend"),[4,o.delete()])):[3,8];case 4:return l.sent(),[3,6];case 5:n.push({events:c,sequenceId:o.key,sessionId:a}),l.label=6;case 6:return[4,o.continue()];case 7:return o=l.sent(),[3,3];case 8:return this.recordSuccess(),i(),[2,n];case 9:return u=l.sent(),t||(e=!0,zt(this.loggerProvider,"".concat(vt,": ").concat(u),u),this.recordFailure()),[3,10];case 10:return[2,void 0]}})})},r.storeCurrentSequence=function(e){return a(r,void 0,void 0,function(){var t,n,r,i,a,c,u,d,h=this;return l(this,function(l){switch(l.label){case 0:t=!1,n=!1,l.label=1;case 1:return l.trys.push([1,5,,6]),(r=this.db.transaction([Kt,Ht],"readwrite")).done.catch(function(e){t||n||(zt(h.loggerProvider,"".concat(vt,": ").concat(e),e),h.recordFailure())}),i=Qt(r.done,Gt,function(){t||n||(n=!0,zt(h.loggerProvider,"".concat(vt,": transaction timed out")),h.recordFailure())}),[4,r.objectStore(Kt).get(e)];case 2:return!(a=l.sent())||a.tabId&&a.tabId!==this.tabId?(i(),[2,void 0]):0===a.events.length?(this.maybeLogEmptyFiltered("storeCurrentSequence"),i(),[2,void 0]):[4,r.objectStore(Ht).put({sessionId:e,events:a.events,tabId:this.tabId})];case 3:return c=l.sent(),[4,r.objectStore(Kt).put({sessionId:e,events:[],tabId:this.tabId})];case 4:return l.sent(),this.rememberSequenceContentBytes(e,[]),this.recordSuccess(),i(),a.tabId,u=s(a,["tabId"]),[2,o(o({},u),{sessionId:e,sequenceId:c})];case 5:return d=l.sent(),this.forgetSequenceContentBytes(e),n||(t=!0,zt(this.loggerProvider,"".concat(vt,": ").concat(d),d),this.recordFailure()),[3,6];case 6:return[2,void 0]}})})},r.addEventToCurrentSequence=function(e,t){return a(r,void 0,void 0,function(){var n,r,i,o,s,a,c,u,d,h,v,f,g,p,m=this;return l(this,function(l){switch(l.label){case 0:n=!1,r=!1,l.label=1;case 1:return l.trys.push([1,15,,16]),(i=this.db.transaction([Kt,Ht],"readwrite")).done.catch(function(e){n||r||(zt(m.loggerProvider,"".concat(vt,": ").concat(e),e),m.recordFailure())}),o=Qt(i.done,Gt,function(){n||r||(r=!0,zt(m.loggerProvider,"".concat(vt,": transaction timed out")),m.recordFailure())}),[4,i.objectStore(Kt).get(e)];case 2:return(null==(s=l.sent())?void 0:s.tabId)&&s.tabId!==this.tabId?s.events.length>0?[4,i.objectStore(Ht).put({sessionId:e,events:s.events,tabId:s.tabId})]:[3,4]:[3,6];case 3:l.sent(),l.label=4;case 4:return a=[t],[4,i.objectStore(Kt).put({sessionId:e,events:a,tabId:this.tabId})];case 5:return l.sent(),this.rememberSequenceContentBytes(e,a),this.recordSuccess(),o(),[2,void 0];case 6:return(c=s)?[3,8]:(u=[t],[4,i.objectStore(Kt).put({sessionId:e,events:u,tabId:this.tabId})]);case 7:return l.sent(),this.rememberSequenceContentBytes(e,u),this.recordSuccess(),o(),[2,void 0];case 8:return this.recallSequenceContentBytes(e,c.events),this.shouldSplitEventsList(c.events,t)?[3,10]:(d=c.events.concat(t),[4,i.objectStore(Kt).put({sessionId:e,events:d,tabId:this.tabId})]);case 9:return l.sent(),this.rememberSequenceContentBytes(e,d),this.recordSuccess(),o(),[2,void 0];case 10:return 0!==(h=c.events).length?[3,12]:(this.maybeLogEmptyFiltered("addEventToCurrentSequence"),v=[t],[4,i.objectStore(Kt).put({sessionId:e,events:v,tabId:this.tabId})]);case 11:return l.sent(),this.rememberSequenceContentBytes(e,v),this.recordSuccess(),o(),[2,void 0];case 12:return f=[t],[4,i.objectStore(Kt).put({sessionId:e,events:f,tabId:this.tabId})];case 13:return l.sent(),this.rememberSequenceContentBytes(e,f),[4,i.objectStore(Ht).put({sessionId:e,events:h,tabId:this.tabId})];case 14:return g=l.sent(),this.recordSuccess(),o(),[2,{events:h,sessionId:e,sequenceId:g}];case 15:return p=l.sent(),this.forgetSequenceContentBytes(e),r||(n=!0,zt(this.loggerProvider,"".concat(vt,": ").concat(p),p),this.recordFailure()),[3,16];case 16:return[2,void 0]}})})},r.storeSendingEvents=function(e,t){return a(r,void 0,void 0,function(){var n,r;return l(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.db.put(Ht,{sessionId:e,events:t,tabId:this.tabId})];case 1:return n=i.sent(),this.recordSuccess(),[2,n];case 2:return r=i.sent(),zt(this.loggerProvider,"".concat(vt,": ").concat(r),r),this.recordFailure(),[3,3];case 3:return[2,void 0]}})})},r.cleanUpSessionEventsStore=function(e,t){return a(r,void 0,void 0,function(){var e;return l(this,function(n){switch(n.label){case 0:if(!t)return[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.db.delete(Ht,t)];case 2:return n.sent(),this.recordSuccess(),[3,4];case 3:return e=n.sent(),zt(this.loggerProvider,"".concat(vt,": ").concat(e),e),this.recordFailure(),[3,4];case 4:return[2]}})})},r.db=t.db,r.tabId=t.tabId,r.onPersistentFailure=t.onPersistentFailure,r.consecutiveFailureThreshold=null!==(n=t.consecutiveFailureThreshold)&&void 0!==n?n:1,r}return n(t,e),t.prototype.maybeLogEmptyFiltered=function(e){this.emptyFilteredCount++%100==0&&this.loggerProvider.debug("Filtered empty session replay sequence at ".concat(e," (idb store)"))},t.prototype.recordFailure=function(){var e;this.consecutiveFailures++,!this.hasTriggeredFallback&&this.consecutiveFailures>=this.consecutiveFailureThreshold&&(this.hasTriggeredFallback=!0,null===(e=this.onPersistentFailure)||void 0===e||e.call(this))},t.prototype.recordSuccess=function(){this.consecutiveFailures=0},t.new=function(e,n){var r;return a(this,void 0,void 0,function(){var i,s,a,c,u;return l(this,function(l){switch(l.label){case 0:return l.trys.push([0,2,,3]),i="replay"===e?"":"_".concat(e),s="".concat(n.apiKey.substring(0,10),"_amp_session_replay_events").concat(i),[4,Xt(s)];case 1:return a=l.sent(),c=null!==(r=n.tabId)&&void 0!==r?r:function(){try{return crypto.randomUUID()}catch(e){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}}(),[2,new t(o(o({},n),{db:a,tabId:c}))];case 2:return u=l.sent(),zt(n.loggerProvider,"".concat(vt,": ").concat(u),u),[3,3];case 3:return[2]}})})},t.prototype.getCurrentSequenceEvents=function(e){return a(this,void 0,void 0,function(){var t,n,r,i,o,a,u,d;return l(this,function(l){switch(l.label){case 0:return e?[4,this.db.get("sessionCurrentSequence",e)]:[3,2];case 1:return(i=l.sent())?i.tabId&&i.tabId!==this.tabId?[2,void 0]:(i.tabId,[2,[o=s(i,["tabId"])]]):[2,void 0];case 2:t=[],l.label=3;case 3:return l.trys.push([3,8,9,10]),[4,this.db.getAll("sessionCurrentSequence")];case 4:n=c.apply(void 0,[l.sent()]),r=n.next(),l.label=5;case 5:if(r.done)return[3,7];if((i=r.value).tabId&&i.tabId!==this.tabId)return[3,6];i.tabId,o=s(i,["tabId"]),t.push(o),l.label=6;case 6:return r=n.next(),[3,5];case 7:return[3,10];case 8:return a=l.sent(),u={error:a},[3,10];case 9:try{r&&!r.done&&(d=n.return)&&d.call(n)}finally{if(u)throw u.error}return[7];case 10:return[2,t]}})})},t}(Wt),en=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.finalizedSequences={},t.sequences={},t.sequenceId=0,t.emptyFilteredCount=0,t}return n(t,e),t.prototype.resetCurrentSequence=function(e){this.sequences[e]=[]},t.prototype.addSequence=function(e){var t=this.sequenceId++,n=d([],u(this.sequences[e]),!1);return this.finalizedSequences[t]={sessionId:e,events:n},this.resetCurrentSequence(e),{sequenceId:t,events:n,sessionId:e}},t.prototype.maybeLogEmptyFiltered=function(e){this.emptyFilteredCount++%100==0&&this.loggerProvider.debug("Filtered empty session replay sequence at ".concat(e," (in-memory store)"))},t.prototype.getSequencesToSend=function(){return a(this,void 0,void 0,function(){var e,t,n,r,i,o,s,a,d,h;return l(this,function(l){e=[];try{for(t=c(Object.entries(this.finalizedSequences)),n=t.next();!n.done;n=t.next())r=u(n.value,2),i=r[0],o=r[1],s=o.sessionId,0!==(a=o.events).length?e.push({sequenceId:Number(i),sessionId:s,events:a}):(this.maybeLogEmptyFiltered("getSequencesToSend"),delete this.finalizedSequences[Number(i)])}catch(e){d={error:e}}finally{try{n&&!n.done&&(h=t.return)&&h.call(t)}finally{if(d)throw d.error}}return[2,e]})})},t.prototype.storeCurrentSequence=function(e){return a(this,void 0,void 0,function(){var t;return l(this,function(n){return(t=this.sequences[e])?0===t.length?(this.maybeLogEmptyFiltered("storeCurrentSequence"),[2,void 0]):[2,this.addSequence(e)]:[2,void 0]})})},t.prototype.addEventToCurrentSequence=function(e,t){return a(this,void 0,void 0,function(){var n;return l(this,function(r){return this.sequences[e]||this.resetCurrentSequence(e),this.shouldSplitEventsList(this.sequences[e],t)&&(0===this.sequences[e].length?this.maybeLogEmptyFiltered("addEventToCurrentSequence"):n=this.addSequence(e)),this.sequences[e].push(t),[2,n]})})},t.prototype.storeSendingEvents=function(e,t){return a(this,void 0,void 0,function(){return l(this,function(n){return this.finalizedSequences[this.sequenceId]={sessionId:e,events:t},[2,this.sequenceId++]})})},t.prototype.cleanUpSessionEventsStore=function(e,t){return a(this,void 0,void 0,function(){return l(this,function(e){return void 0!==t&&delete this.finalizedSequences[t],[2]})})},t}(Wt),tn=function(e){var t=e.config,n=e.minInterval,r=e.maxInterval,i=e.maxPersistedEventsSize,s=e.type,c=e.payloadBatcher,h=e.storeType,v=e.trackDestinationWorkerScript,f=e.shouldSend;return a(void 0,void 0,void 0,function(){function e(e){return void 0===e&&(e=!1),a(this,void 0,void 0,function(){return l(this,function(t){return[2,p.flush(e)]})})}var g,p,m,y,b,S,I,w,C,E,P,k,x,M,T,R,O;return l(this,function(_){switch(_.label){case 0:return g=null!==(O=t.maxSingleEventSizeBytes)&&void 0!==O?O:Se,p=new mt(o(o({},t),{loggerProvider:t.loggerProvider,payloadBatcher:c,workerScript:v})),m=function(){return new en({loggerProvider:t.loggerProvider,maxInterval:r,minInterval:n,maxPersistedEventsSize:i})},b=!1,I=function(){return a(void 0,void 0,void 0,function(){var e,n,r;return l(this,function(i){switch(i.label){case 0:return b?(b=!1,t.loggerProvider.warn("IDB store is experiencing repeated failures; falling back to in-memory event store."),y?[4,S.getSequencesToSend()]:[3,2]):[2];case 1:return n=i.sent(),[3,3];case 2:n=void 0,i.label=3;case 3:return e=n,S=m(),e&&y&&(r=y,e.forEach(function(e){x({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:r})})),[2]}})})},w=function(){return a(void 0,void 0,void 0,function(){var e;return l(this,function(o){switch(o.label){case 0:return[4,Yt.new(s,{loggerProvider:t.loggerProvider,minInterval:n,maxInterval:r,maxPersistedEventsSize:i,apiKey:t.apiKey,onPersistentFailure:function(){I()}})];case 1:return(e=o.sent())?(b=!0,[2,e]):(t.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),[2,m()])}})})},"idb"!==h?[3,2]:[4,w()];case 1:return C=_.sent(),[3,3];case 2:C=m(),_.label=3;case 3:return S=C,E=[],P=0,k=function(e){if(!(e<=P)){var t=Math.min(e-P,E.length);t>0&&(E.splice(0,t),P=e)}},x=function(e){for(var n=e.events,r=e.sessionId,i=e.deviceId,o=e.sequenceId,c=n,u=[],d=0;d<n.length;d++){var h=ot(n[d],g);void 0!==h?(0===u.length&&(c=n.slice(0,d)),u.push(h)):c!==n&&c.push(n[d])}u.length>0&&t.loggerProvider.warn("Dropping ".concat(u.length," oversized event(s) from session replay sequence before send. Sizes: ").concat(u.map(function(e){return"".concat(Math.round(e/1024)," KB")}).join(", "),". If this recurs, please open a GitHub issue at https://github.com/amplitude/Amplitude-TypeScript/issues or contact Amplitude support.")),0!==c.length?(t.debugMode&&Ue().then(function(e){var n=e.totalStorageSize,r=e.percentOfQuota,i=e.usageDetails;t.loggerProvider.debug("Total storage size: ".concat(n," KB, percentage of quota: ").concat(r,"%, usage details: ").concat(i))}).catch(function(){}),p.sendEventsList({events:c,sessionId:r,flushMaxRetries:t.flushMaxRetries,apiKey:t.apiKey,deviceId:i,sampleRate:t.sampleRate,serverZone:t.serverZone,version:t.version,type:s,onComplete:function(){return a(void 0,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,S.cleanUpSessionEventsStore(r,o)];case 1:return e.sent(),[2]}})})}})):S.cleanUpSessionEventsStore(r,o).catch(function(e){t.loggerProvider.warn("Failed to clean up session replay events store:",e)})},M=function(e){var n=e.sessionId,r=e.deviceId;if(y=r,!f||f()){var i=P+E.length;S.storeCurrentSequence(n).then(function(e){e&&(k(i),x({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:r}))}).catch(function(e){t.loggerProvider.warn("Failed to get current sequence of session replay events for session:",e)})}},T=function(e){var n=e.deviceId;return a(void 0,void 0,void 0,function(){var e;return l(this,function(r){switch(r.label){case 0:return y=n,[4,S.getSequencesToSend()];case 1:return(null==(e=r.sent())?void 0:e.length)?(t.loggerProvider.log("Draining ".concat(e.length," stored sequence(s) from previous session.")),e.length>1&&p.markCoalesceNextFlush(),e.forEach(function(e){x({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n})}),[2]):[2]}})})},R=function(e){var n=e.event,r=e.sessionId,i=e.deviceId;y=i;var o=!f||f(),s=P+E.length;E.push(n.data),S.addEventToCurrentSequence(r,n.data).then(function(e){if(e){if(!o)return S.cleanUpSessionEventsStore(e.sessionId,e.sequenceId).catch(function(e){t.loggerProvider.warn("Failed to clean up dropped session replay sequence:",e)}),void k(s);k(s),x({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:i})}}).catch(function(e){t.loggerProvider.warn("Failed to add event to session replay capture:",e)})},[2,{sendCurrentSequenceEvents:M,addEvent:R,sendStoredEvents:T,flush:e,getBeaconEvents:function(){return d([],u(E),!1)},dropPendingBeaconEvents:function(){k(P+E.length)},trackDestination:p}]}})})},nn=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=new Map;e.forEach(function(e){n.set(e.name,e.manager)}),this.managers=n}return e.prototype.sendStoredEvents=function(e){return a(this,void 0,void 0,function(){var t;return l(this,function(n){switch(n.label){case 0:return t=[],this.managers.forEach(function(n){t.push(n.sendStoredEvents(e))}),[4,Promise.all(t)];case 1:return n.sent(),[2]}})})},e.prototype.addEvent=function(e){var t,n=e.sessionId,r=e.event,i=e.deviceId;null===(t=this.managers.get(r.type))||void 0===t||t.addEvent({sessionId:n,event:r,deviceId:i})},e.prototype.sendCurrentSequenceEvents=function(e){var t=e.sessionId,n=e.deviceId;this.managers.forEach(function(e){e.sendCurrentSequenceEvents({sessionId:t,deviceId:n})})},e.prototype.flush=function(e){return a(this,void 0,void 0,function(){var t;return l(this,function(n){switch(n.label){case 0:return t=[],this.managers.forEach(function(n){t.push(n.flush(e))}),[4,Promise.all(t)];case 1:return n.sent(),[2]}})})},e}();function rn(e,t){if(Zt=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";var n={root:document.body,idName:function(e){return!0},className:function(e){return!0},tagName:function(e){return!0},attr:function(e,t){return!1},seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};Jt=o(o({},n),t),$t=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(Jt.root,n);var r=on(e,"all",function(){return on(e,"two",function(){return on(e,"one",function(){return on(e,"none")})})});if(r){var i=gn(pn(r,e));return i.length>0&&(r=i[0]),an(r)}throw new Error("Selector was not found.")}function on(e,t,n){for(var r=null,i=[],o=e,s=0,a=function(){var e,a,l=(new Date).getTime()-Zt.getTime();if(void 0!==Jt.timeoutMs&&l>Jt.timeoutMs)throw new Error("Timeout: Can't find a unique selector after ".concat(l,"ms"));var h=hn(function(e){var t=e.getAttribute("id");if(t&&Jt.idName(t))return{name:"#"+CSS.escape(t),penalty:0};return null}(o))||hn.apply(void 0,d([],u(function(e){var t=Array.from(e.attributes).filter(function(e){return Jt.attr(e.name,e.value)});return t.map(function(e){return{name:"[".concat(CSS.escape(e.name),'="').concat(CSS.escape(e.value),'"]'),penalty:.5}})}(o)),!1))||hn.apply(void 0,d([],u(function(e){var t=Array.from(e.classList).filter(Jt.className);return t.map(function(e){return{name:"."+CSS.escape(e),penalty:1}})}(o)),!1))||hn(function(e){var t=e.tagName.toLowerCase();if(Jt.tagName(t))return{name:t,penalty:2};return null}(o))||[{name:"*",penalty:3}],v=function(e){var t=e.parentNode;if(!t)return null;var n=t.firstChild;if(!n)return null;var r=0;for(;n&&(n.nodeType===Node.ELEMENT_NODE&&r++,n!==e);)n=n.nextSibling;return r}(o);if("all"==t)v&&(h=h.concat(h.filter(dn).map(function(e){return un(e,v)})));else if("two"==t)h=h.slice(0,1),v&&(h=h.concat(h.filter(dn).map(function(e){return un(e,v)})));else if("one"==t){var f=u(h=h.slice(0,1),1)[0];v&&dn(f)&&(h=[un(f,v)])}else"none"==t&&(h=[{name:"*",penalty:3}],v&&(h=[un(h[0],v)]));try{for(var g=(e=void 0,c(h)),p=g.next();!p.done;p=g.next()){(f=p.value).level=s}}catch(t){e={error:t}}finally{try{p&&!p.done&&(a=g.return)&&a.call(g)}finally{if(e)throw e.error}}if(i.push(h),i.length>=Jt.seedMinLength&&(r=sn(i,n)))return"break";o=o.parentElement,s++};o;){if("break"===a())break}return r||(r=sn(i,n)),!r&&n?n():r}function sn(e,t){var n,r,i=gn(fn(e));if(i.length>Jt.threshold)return t?t():null;try{for(var o=c(i),s=o.next();!s.done;s=o.next()){var a=s.value;if(cn(a))return a}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return null}function an(e){for(var t=e[0],n=t.name,r=1;r<e.length;r++){var i=e[r].level||0;n=t.level===i-1?"".concat(e[r].name," > ").concat(n):"".concat(e[r].name," ").concat(n),t=e[r]}return n}function ln(e){return e.map(function(e){return e.penalty}).reduce(function(e,t){return e+t},0)}function cn(e){var t=an(e);switch($t.querySelectorAll(t).length){case 0:throw new Error("Can't select any node with this selector: ".concat(t));case 1:return!0;default:return!1}}function un(e,t){return{name:e.name+":nth-child(".concat(t,")"),penalty:e.penalty+1}}function dn(e){return"html"!==e.name&&!e.name.startsWith("#")}function hn(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e.filter(vn);return n.length>0?n:null}function vn(e){return null!=e}function fn(e,t){var n,r,i,o,s,a;return void 0===t&&(t=[]),l(this,function(l){switch(l.label){case 0:if(!(e.length>0))return[3,9];l.label=1;case 1:l.trys.push([1,6,7,8]),n=c(e[0]),r=n.next(),l.label=2;case 2:return r.done?[3,5]:(i=r.value,[5,c(fn(e.slice(1,e.length),t.concat(i)))]);case 3:l.sent(),l.label=4;case 4:return r=n.next(),[3,2];case 5:return[3,8];case 6:return o=l.sent(),s={error:o},[3,8];case 7:try{r&&!r.done&&(a=n.return)&&a.call(n)}finally{if(s)throw s.error}return[7];case 8:return[3,11];case 9:return[4,t];case 10:l.sent(),l.label=11;case 11:return[2]}})}function gn(e){return d([],u(e),!1).sort(function(e,t){return ln(e)-ln(t)})}function pn(e,t,n){var r,i,o;return void 0===n&&(n={counter:0,visited:new Map}),l(this,function(s){switch(s.label){case 0:if(!(e.length>2&&e.length>Jt.optimizedMinLength))return[3,5];r=1,s.label=1;case 1:return r<e.length-1?n.counter>Jt.maxNumberOfTries?[2]:(n.counter+=1,(i=d([],u(e),!1)).splice(r,1),o=an(i),n.visited.has(o)?[2]:cn(i)&&function(e,t){return $t.querySelector(an(e))===t}(i,t)?[4,i]:[3,4]):[3,5];case 2:return s.sent(),n.visited.set(o,!0),[5,c(pn(i,t,n))];case 3:s.sent(),s.label=4;case 4:return r++,[3,1];case 5:return[2]}})}var mn=function(e){var t=e.version,n=e.events,r=[];return n.forEach(function(e){var t=JSON.parse(e);t.count=1,"click"===t.type&&r.push(t)}),{version:t,events:r}},yn=function(e){var t=e.version,n=e.events,r=[];n.forEach(function(e){var t=JSON.parse(e);"click"===t.type&&r.push(t)});var i=r.reduce(function(e,t){var n=t.x,r=t.y,i=t.selector,s=t.timestamp,a=s-s%36e5,l="".concat(n,":").concat(r,":").concat(null!=i?i:"",":").concat(a);return e[l]?e[l].count+=1:e[l]=o(o({},t),{timestamp:a,count:1}),e},{});return{version:t,events:Object.values(i)}},bn=function(e,t){var n=this;this.createHook=function(e){var t=e.eventsManager,r=e.sessionId,i=e.deviceIdFn,o=e.mirror,s=e.ugcFilterRules,a=e.performanceOptions;return function(e){if(e.type===Xe.Click){var l=g();if(l){var c=l.location,u=l.innerHeight,d=l.innerWidth;if(c){var h=e.x,v=e.y;if(void 0!==h&&void 0!==v){var f,p=o.getNode(e.id);if(p)try{f=rn(p,a)}catch(e){n.logger.debug("error resolving selector from finder")}var m=je(c.href,s),y={x:h+n.scrollWatcher.currentScrollX,y:v+n.scrollWatcher.currentScrollY,selector:f,viewportHeight:u,viewportWidth:d,pageUrl:m,timestamp:Date.now(),type:"click"},b=i();b&&t.addEvent({sessionId:r,event:{type:"interaction",data:JSON.stringify(y)},deviceId:b})}}}}}},this.logger=e,this.scrollWatcher=t};function Sn(){var e=g();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||0}function In(){var e=g();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||0}var wn=function(){function e(e,t){var n=g();n&&n.navigator&&"function"==typeof n.navigator.sendBeacon?this.sendBeacon=function(e,t){try{if(n.navigator.sendBeacon(e,JSON.stringify(t)))return!0}catch(e){}return!1}:this.sendBeacon=function(){return!1},this.sendXhr=function(e,t){var n=new XMLHttpRequest;return n.open("POST",e,!0),n.setRequestHeader("Accept","*/*"),n.send(JSON.stringify(t)),!0},this.basePageUrl=Be(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e,this.handleSendEvents=t.handleSendEvents,this.loggerProvider=t.loggerProvider}return e.prototype.send=function(e,t){var n,r=this,i=this.context,o=i.sessionId,s=i.type;if(this.handleSendEvents){var a=new URLSearchParams({device_id:e,session_id:String(o),type:String(s)}),l="".concat(this.basePageUrl,"?").concat(a.toString()),c={"Content-Type":"application/json",Accept:"*/*",Authorization:"Bearer ".concat(this.apiKey)};try{this.handleSendEvents({url:l,method:"POST",headers:c,body:JSON.stringify(t),keepalive:!0}).catch(function(e){var t;null===(t=r.loggerProvider)||void 0===t||t.warn("Custom transport failed to send session replay interaction beacon:",e)})}catch(e){null===(n=this.loggerProvider)||void 0===n||n.warn("Custom transport threw while sending session replay interaction beacon:",e)}}else{var u=new URLSearchParams({device_id:e,session_id:String(o),type:String(s),api_key:this.apiKey}),d="".concat(this.basePageUrl,"?").concat(u.toString());this.sendBeacon(d,t)||this.sendXhr(d,t)}},e}(),Cn=function(){function e(e,t){var n=this;this.timestamp=Date.now(),this.hook=function(e){n.update(e)},this.send=function(e){return function(t){var r,i,o,s,a=e(),l=g();if(l&&a){var c=null!==(r=l.scrollX)&&void 0!==r?r:0,u=null!==(i=l.scrollY)&&void 0!==i?i:0;(c>0||u>0)&&n.update({id:1,x:c,y:u}),n.transport.send(a,{version:1,events:[{maxScrollX:n._maxScrollX,maxScrollY:n._maxScrollY,maxScrollWidth:n._maxScrollWidth,maxScrollHeight:n._maxScrollHeight,viewportHeight:Sn(),viewportWidth:In(),pageUrl:je(l.location.href,null!==(s=null===(o=n.config.interactionConfig)||void 0===o?void 0:o.ugcFilterRules)&&void 0!==s?s:[]),timestamp:n.timestamp,type:"scroll"}]})}}},this._maxScrollX=0,this._maxScrollY=0,this._currentScrollX=0,this._currentScrollY=0,this._maxScrollWidth=In(),this._maxScrollHeight=Sn(),this.config=t,this.transport=e}return e.default=function(t,n){return new e(new wn(t,n),n)},Object.defineProperty(e.prototype,"maxScrollX",{get:function(){return this._maxScrollX},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxScrollY",{get:function(){return this._maxScrollY},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxScrollWidth",{get:function(){return this._maxScrollWidth},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxScrollHeight",{get:function(){return this._maxScrollHeight},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentScrollX",{get:function(){return this._currentScrollX},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentScrollY",{get:function(){return this._currentScrollY},enumerable:!1,configurable:!0}),e.prototype.update=function(e){var t=Date.now();if(this._currentScrollX=e.x,this._currentScrollY=e.y,e.x>this._maxScrollX){var n=In();this._maxScrollX=e.x;var r=e.x+n;r>this._maxScrollWidth&&(this._maxScrollWidth=r),this.timestamp=t}if(e.y>this._maxScrollY){var i=Sn();this._maxScrollY=e.y;var o=e.y+i;o>this._maxScrollHeight&&(this._maxScrollHeight=o),this.timestamp=t}},e}(),En=function(e){var t=e.sessionId,n=e.deviceId;this.deviceId=n,this.sessionId=t,t&&n&&(this.sessionReplayId=function(e,t){return"".concat(t,"/").concat(e)}(t,n))},Pn=864e5,kn=function(e){return"".concat("AMP_SR_START_").concat(e.substring(0,10),"_")},xn=function(e,t){return"".concat(kn(e)).concat(t)},Mn=function(){try{var e=g();return null==e?void 0:e.localStorage}catch(e){return}},Tn=function(){var e=this;this.dbs={},this.createStore=function(t){return a(e,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return[4,Rt(t,1,{upgrade:function(e){e.objectStoreNames.contains("sessionTargetingMatch")||e.createObjectStore("sessionTargetingMatch",{keyPath:"sessionId"})}})];case 1:return[2,e.sent()]}})})},this.openOrCreateDB=function(t){return a(e,void 0,void 0,function(){var e,n;return l(this,function(r){switch(r.label){case 0:return this.dbs&&this.dbs[t]?[2,this.dbs[t]]:(e="".concat(t.substring(0,10),"_amp_session_replay_targeting"),[4,this.createStore(e)]);case 1:return n=r.sent(),this.dbs[t]=n,[2,n]}})})},this.getTargetingMatchForSession=function(t){var n=t.loggerProvider,r=t.apiKey,i=t.sessionId;return a(e,void 0,void 0,function(){var e,t,o,s;return l(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),[4,this.openOrCreateDB(r)];case 1:return e=a.sent(),t=String(i),[4,e.get("sessionTargetingMatch",t)];case 2:return[2,null==(o=a.sent())?void 0:o.targetingMatch];case 3:return s=a.sent(),zt(n,"Failed to get targeting match for session id ".concat(i,": ").concat(s),s),[3,4];case 4:return[2,void 0]}})})},this.storeTargetingMatchForSession=function(t){var n=t.loggerProvider,r=t.apiKey,i=t.sessionId,o=t.targetingMatch;return a(e,void 0,void 0,function(){var e,t,s;return l(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),[4,this.openOrCreateDB(r)];case 1:return e=a.sent(),t=String(i),[4,e.put("sessionTargetingMatch",{targetingMatch:o,sessionId:t,lastUpdated:Date.now()})];case 2:return[2,a.sent()];case 3:return s=a.sent(),zt(n,"Failed to store targeting match for session id ".concat(i,": ").concat(s),s),[3,4];case 4:return[2,void 0]}})})},this.clearStoreOfOldSessions=function(t){var n=t.loggerProvider,r=t.apiKey,i=t.currentSessionId;return a(e,void 0,void 0,function(){var e,t,o,s,a,c,u,d;return l(this,function(l){switch(l.label){case 0:return l.trys.push([0,8,,9]),[4,this.openOrCreateDB(r)];case 1:return e=l.sent(),t=String(i),[4,(o=e.transaction("sessionTargetingMatch","readwrite")).store.getAll()];case 2:s=l.sent(),a=0,l.label=3;case 3:return a<s.length?(c=s[a],u=Date.now()-c.lastUpdated,c.sessionId!==t&&u>1728e5?[4,o.store.delete(c.sessionId)]:[3,5]):[3,6];case 4:l.sent(),l.label=5;case 5:return a++,[3,3];case 6:return[4,o.done];case 7:return l.sent(),[3,9];case 8:return d=l.sent(),zt(n,"Failed to clear old targeting matches for sessions: ".concat(d),d),[3,9];case 9:return[2]}})})}},Rn=new Tn,On=function(e){var t=e.sessionId,n=e.targetingConfig,r=e.loggerProvider,i=e.apiKey,s=e.targetingParams,c=e.urlChange,u=void 0!==c&&c;return a(void 0,void 0,void 0,function(){var e,a,c,d,h,v;return l(this,function(l){switch(l.label){case 0:return[4,Rn.clearStoreOfOldSessions({loggerProvider:r,apiKey:i,currentSessionId:t})];case 1:return l.sent(),[4,Rn.getTargetingMatchForSession({loggerProvider:r,apiKey:i,sessionId:t})];case 2:if(!0===l.sent()&&!u)return[2,!0];e=!0,l.label=3;case 3:return l.trys.push([3,6,,7]),[4,import("./index-min3.js")];case 4:return a=l.sent().evaluateTargeting,c=o(o({},s),{flag:n,sessionId:"string"==typeof t?parseInt(t,10):t,apiKey:i,loggerProvider:r}),[4,a(c)];case 5:return(d=l.sent())&&d.sr_targeting_config&&(e="on"===d.sr_targeting_config.key),Rn.storeTargetingMatchForSession({loggerProvider:r,apiKey:i,sessionId:t,targetingMatch:e}),[3,7];case 6:return h=l.sent(),v=h,r.warn(v.message),[3,7];case 7:return[2,e]}})})},_n=2654435761,Ln=2246822519,Fn=3266489917,Dn=374761393;function qn(e,t){return(e<<t|e>>>32-t)>>>0}function An(e,t){return e=qn(e=e+Math.imul(t,Ln)>>>0,13),e=Math.imul(e,_n)>>>0}function Bn(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function Nn(e,t){void 0===t&&(t=0);var n,r=function(e){for(var t=[],n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r>=55296&&r<=56319&&n+1<e.length){var i=e.charCodeAt(n+1);i>=56320&&i<=57343&&(r=i-56320+(r-55296<<10)+65536,n++)}r<128?t.push(r):r<2048?t.push(192|r>>6,128|63&r):r<65536?t.push(224|r>>12,128|r>>6&63,128|63&r):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}return new Uint8Array(t)}(e),i=r.length,o=0;if(i>=16){for(var s=t+_n+Ln>>>0,a=t+Ln>>>0,l=t>>>0,c=t-_n>>>0;o<=i-16;)s=An(s,Bn(r,o)),a=An(a,Bn(r,o+=4)),l=An(l,Bn(r,o+=4)),c=An(c,Bn(r,o+=4)),o+=4;n=qn(s,1)+qn(a,7)+qn(l,12)+qn(c,18)>>>0}else n=t+Dn>>>0;for(n=n+i>>>0;o<=i-4;)n=n+Math.imul(Bn(r,o),Fn)>>>0,n=Math.imul(qn(n,17),668265263)>>>0,o+=4;for(;o<i;)n=n+Math.imul(r[o],Dn)>>>0,n=Math.imul(qn(n,11),_n)>>>0,o++;return n^=n>>>15,n=Math.imul(n,Ln)>>>0,n^=n>>>13,n=Math.imul(n,Fn)>>>0,(n^=n>>>16)>>>0}var jn="__amplitude_url_tracking_patched__",Un=new WeakMap;function Wn(e,t,n){if(void 0===n&&(n={}),!(null==e?void 0:e.location))return function(){};var r=n.enablePolling,i=void 0!==r&&r,o=n.pollingInterval,s=void 0===o?ge:o;if(i){var a=function(){var t;return null!==(t=e.location.href)&&void 0!==t?t:""},l=a(),c=e.setInterval(function(){var e=a();e!==l&&(l=e,t(e))},s);return function(){null!=c&&e.clearInterval(c)}}var u=Un.get(e);if(!u){var d=void 0,h=new Set,v=function(){var t=function(){var t;return null!==(t=e.location.href)&&void 0!==t?t:""}();void 0!==d&&t===d||(d=t,h.forEach(function(e){return e(t)}))},f=function(e){var t=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var r=e.apply(this,t);return v(),r};return t[jn]=!0,t},g=e.history;if(null==g?void 0:g.pushState){var p=Reflect.get(g,"pushState");p[jn]||(g.pushState=f(p))}if(null==g?void 0:g.replaceState){var m=Reflect.get(g,"replaceState");m[jn]||(g.replaceState=f(m))}u={callbacks:h,notify:v,onPopStateOrHashChange:function(){return v()},listenersAttached:!1},Un.set(e,u)}var y=u;return y.listenersAttached||(e.addEventListener("popstate",y.onPopStateOrHashChange),e.addEventListener("hashchange",y.onPopStateOrHashChange),y.listenersAttached=!0),y.callbacks.add(t),function(){y.callbacks.delete(t),0===y.callbacks.size&&y.listenersAttached&&(e.removeEventListener("popstate",y.onPopStateOrHashChange),e.removeEventListener("hashchange",y.onPopStateOrHashChange),y.listenersAttached=!1)}}function zn(e){return void 0===e&&(e={}),{name:"amplitude/url-tracking@1",observer:function(t,n,r){var i,s,a,l=o(o({},e),r),c=l.ugcFilterRules||[],u=null!==(i=l.enablePolling)&&void 0!==i&&i,d=null!==(s=l.pollingInterval)&&void 0!==s?s:ge,h=null!==(a=l.captureDocumentTitle)&&void 0!==a&&a;if(!n)return function(){};var v=void 0,f=function(){return n.location&&n.location.href||""},g=function(){var e=f();if(void 0===v||e!==v){v=e;var r=function(){var e=n.innerHeight,t=n.innerWidth,r=n.document,i=f(),o="";return h&&(o=(null==r?void 0:r.title)||""),{href:c.length>0?je(i,c):i,title:o,viewportHeight:e,viewportWidth:t,type:"url-change-event"}}();t(r)}},p=Wn(n,function(){return g()},u?{enablePolling:!0,pollingInterval:d}:{});return g(),function(){return p()}},options:e}}zn();var Kn=function(){function e(){this.pendingLoadListeners=new Map}return e.prototype.start=function(){var e,t=this;null===(e=this.mutationObserver)||void 0===e||e.disconnect(),g()&&(this.sendToAllIframes({type:ke,action:"start"}),this.mutationObserver=new MutationObserver(function(e){var n,r,i,o,s,a;try{for(var l=c(e),u=l.next();!u.done;u=l.next()){var d=u.value;try{for(var h=(i=void 0,c(Array.from(d.addedNodes))),v=h.next();!v.done;v=h.next()){(p=v.value)instanceof HTMLIFrameElement?t.sendToIframeAfterLoad(p):p instanceof Element&&p.querySelectorAll("iframe").forEach(function(e){t.sendToIframeAfterLoad(e)})}}catch(e){i={error:e}}finally{try{v&&!v.done&&(o=h.return)&&o.call(h)}finally{if(i)throw i.error}}try{for(var f=(s=void 0,c(Array.from(d.removedNodes))),g=f.next();!g.done;g=f.next()){var p;if((p=g.value)instanceof HTMLIFrameElement){var m=t.pendingLoadListeners.get(p);m&&(p.removeEventListener("load",m),t.pendingLoadListeners.delete(p))}}}catch(e){s={error:e}}finally{try{g&&!g.done&&(a=f.return)&&a.call(f)}finally{if(s)throw s.error}}}}catch(e){n={error:e}}finally{try{u&&!u.done&&(r=l.return)&&r.call(l)}finally{if(n)throw n.error}}}),this.mutationObserver.observe(document.documentElement,{childList:!0,subtree:!0}))},e.prototype.stop=function(){var e;null===(e=this.mutationObserver)||void 0===e||e.disconnect(),this.mutationObserver=void 0,this.pendingLoadListeners.forEach(function(e,t){t.removeEventListener("load",e)}),this.pendingLoadListeners.clear(),this.sendToAllIframes({type:ke,action:"stop"})},e.prototype.sendToIframeAfterLoad=function(e){var t=this,n=function(){t.pendingLoadListeners.delete(e),t.sendToIframe(e,{type:ke,action:"start"})};this.pendingLoadListeners.set(e,n),e.addEventListener("load",n,{once:!0})},e.prototype.sendToAllIframes=function(e){var t=this;document.querySelectorAll("iframe").forEach(function(n){return t.sendToIframe(n,e)})},e.prototype.sendToIframe=function(e,t){var n;try{null===(n=e.contentWindow)||void 0===n||n.postMessage(t,"*")}catch(e){}},e}();var Hn=function(){function e(){var e=this;this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.pageLeaveFns=[],this.suppressedSendCount=0,this.hasEmittedGateDecision=!1,this.recordFunction=null,this.recordEventsInFlight=!1,this.recordingEnabled=!0,this.recordingGeneration=0,this.startChildRecordingOnSetup=!1,this.pendingEmitEvents=[],this.currentPageUrl="",this.recordEventsPendingShouldLogMetadata=null,this.urlChangeCleanup=null,this.crossOriginIframeCoordinator=null,this.crossOriginParentSignalCleanup=null,this.latestUrlChangeTargetingEvaluationId=0,this.teardownEventListeners=function(t){var n=g();n&&(n.removeEventListener("blur",e.blurListener),n.removeEventListener("focus",e.focusListener),!t&&n.addEventListener("blur",e.blurListener),!t&&n.addEventListener("focus",e.focusListener),n.self&&"onpagehide"in n.self?(n.removeEventListener("pagehide",e.pageLeaveListener),!t&&n.addEventListener("pagehide",e.pageLeaveListener)):(n.removeEventListener("beforeunload",e.pageLeaveListener),!t&&n.addEventListener("beforeunload",e.pageLeaveListener)))},this.blurListener=function(){e.sendEvents()},this.focusListener=function(){var t;if(e.recordingEnabled)if(e.recordCancelCallback&&e.recordFunction){if(!1===(null===(t=e.config)||void 0===t?void 0:t.captureFullSnapshotOnFocus))return;try{e.recordFunction.takeFullSnapshot(!0)}catch(t){e.loggerProvider.warn("Failed to take full snapshot on focus:",t)}}else e.recordEventsInFlight||e.recordEvents(!1)},this.pageLeaveListener=function(t){var n;null===(n=e.eventCompressor)||void 0===n||n.flushQueue(),e.sendEvents(),e.pageLeaveFns.forEach(function(e){e(t)})},this.evaluateTargetingAndCapture=function(t,n,r,o){return void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===o&&(o=!1),a(e,void 0,void 0,function(){var e,s,a,c,u,d,h,v,f,p,m,y;return l(this,function(l){switch(l.label){case 0:if(!this.identifiers||!this.identifiers.sessionId||!this.config)return 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."),[2];if(!this.config.targetingConfig){if(!n)return this.loggerProvider.log("No targeting config set, skipping initialization/recording for event."),[2];this.loggerProvider.log("Targeting config has not been set yet, cannot evaluate targeting.")}return this.lastTargetingParams=t,e=this.config.targetingConfig,e&&!this.sessionTargetingMatch?(s=o?this.latestUrlChangeTargetingEvaluationId:void 0,(a=t.event)&&Object.values(i).includes(a.event_type)&&(a=void 0),c=null!==(m=null!==(v=null===(h=t.page)||void 0===h?void 0:h.url)&&void 0!==v?v:null===(p=null===(f=g())||void 0===f?void 0:f.location)||void 0===p?void 0:p.href)&&void 0!==m?m:"",u=null!==(y=t.page)&&void 0!==y?y:""!==c?{url:c}:void 0,[4,On({sessionId:this.identifiers.sessionId,targetingConfig:e,loggerProvider:this.loggerProvider,apiKey:this.config.apiKey,targetingParams:{userProperties:t.userProperties,event:a,page:u},urlChange:o})]):[3,2];case 1:if(d=l.sent(),o&&void 0!==s&&s!==this.latestUrlChangeTargetingEvaluationId)return this.loggerProvider.debug("Ignoring stale URL-change targeting result #".concat(s,"; latest is #").concat(this.latestUrlChangeTargetingEvaluationId,".")),[2];this.sessionTargetingMatch=this.sessionTargetingMatch||d,this.loggerProvider.debug(JSON.stringify({name:"targeted replay capture config",sessionTargetingMatch:this.sessionTargetingMatch,event:a,targetingParams:t},null,2)),l.label=2;case 2:return n?(this.initialize(!0),[3,5]):[3,3];case 3:return!r&&this.recordCancelCallback?[3,5]:(this.loggerProvider.log("Recording events for session due to forceRestart or no ongoing recording."),[4,this.recordEvents()]);case 4:l.sent(),l.label=5;case 5:return[2]}})})},this.addCustomRRWebEvent=function(t,n,r){return void 0===n&&(n={}),void 0===r&&(r=!0),a(e,void 0,void 0,function(){var e,i,s,a;return l(this,function(l){switch(l.label){case 0:return l.trys.push([0,3,,4]),e=void 0,(i=this.config)&&t!==ue.METADATA?(e={config:We(i),version:gt},r?[4,Ue()]:[3,2]):[3,2];case 1:s=l.sent(),e=o(o({},s),e),l.label=2;case 2:return this.recordCancelCallback&&this.recordFunction?this.recordFunction.addCustomEvent(t,o(o({},n),e)):this.loggerProvider.debug("Not able to add custom replay capture event ".concat(t," due to no ongoing recording.")),[3,4];case 3:return a=l.sent(),this.loggerProvider.debug("Error while adding custom replay capture event: ",a),[3,4];case 4:return[2]}})})},this.stopRecordingEvents=function(){var t,n,r;try{e.loggerProvider.log("Session Replay capture stopping."),e.recordCancelCallback&&e.recordCancelCallback(),e.recordCancelCallback=null,null===(t=e.networkObservers)||void 0===t||t.stop(),null===(n=e.crossOriginIframeCoordinator)||void 0===n||n.stop(),e.crossOriginIframeCoordinator=null,null===(r=e.crossOriginParentSignalCleanup)||void 0===r||r.call(e),e.crossOriginParentSignalCleanup=null}catch(t){var i=t;e.loggerProvider.warn("Error occurred while stopping replay capture: ".concat(i.toString()))}},this.loggerProvider=new xe(new M)}return e.prototype.init=function(e,t){return k(this._init(e,t))},e.prototype.setupUrlChangeListener=function(){var e,t,n=this;null===(e=this.urlChangeCleanup)||void 0===e||e.call(this);var r=g();if(null==r?void 0:r.location){var i=!!(null===(t=this.config)||void 0===t?void 0:t.targetingConfig),o=Wn(r,function(e){if(n.currentPageUrl=e,i){var t=++n.latestUrlChangeTargetingEvaluationId;n.evaluateTargetingAndCapture({userProperties:{},event:void 0,page:{url:e}},!1,!1,!0),n.loggerProvider.debug("Queued URL-change targeting re-evaluation #".concat(t," for ").concat(e,"."))}});this.urlChangeCleanup=function(){o(),n.urlChangeCleanup=null}}},e.prototype.isBelowMinSessionDuration=function(){var e,t=null===(e=this.config)||void 0===e?void 0:e.minSessionDurationMs;return void 0!==t&&void 0!==this.sessionStartTime&&Date.now()-this.sessionStartTime<t},e.prototype.getCurrentPageForTargeting=function(){var e,t,n=null===(t=null===(e=g())||void 0===e?void 0:e.location)||void 0===t?void 0:t.href;return null!=n?{url:n}:void 0},e.prototype._init=function(e,t){var n,r,i,s,h,v,f,p,m,y,b,S,I,w;return a(this,void 0,void 0,function(){var a,C,E,P,k,x,T,R,O,_,L,F,D,q,A,B,N,j,U,W,z,K,H,G,Q,J,$,Z,V,X,Y,ee=this;return l(this,function(l){switch(l.label){case 0:return null===(n=this.urlChangeCleanup)||void 0===n||n.call(this),this.recordingEnabled=!0,this.startChildRecordingOnSetup=!1,this.loggerProvider=new xe(t.loggerProvider||new M),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.currentPageUrl=Ne(),this.identifiers=new En({sessionId:t.sessionId,deviceId:t.deviceId}),a=Date.now(),function(e,t,n){var r,i,o=Mn();if(o){var s=kn(e);try{for(var a=[],l=0;l<o.length;l++)if((f=o.key(l))&&f.startsWith(s)){var u=o.getItem(f);if(null!==u){var d=Number(u);(!Number.isFinite(d)||d<=0||t-d>=Pn)&&a.push(f)}}try{for(var h=c(a),v=h.next();!v.done;v=h.next()){var f=v.value;o.removeItem(f)}}catch(e){r={error:e}}finally{try{v&&!v.done&&(i=h.return)&&i.call(h)}finally{if(r)throw r.error}}}catch(e){null==n||n.debug("Failed to prune stale replay start times: ".concat(String(e)))}}}(e,a,this.loggerProvider),this.sessionStartTime=void 0!==t.sessionId&&null!==(r=function(e,t,n,r){var i=Mn();if(i){var o=xn(e,t);try{var s=i.getItem(o);if(null!==s){var a=Number(s);if(Number.isFinite(a)&&a>0&&a<=n&&n-a<Pn)return a}return i.setItem(o,String(n)),n}catch(e){return void(null==r||r.debug("Failed to read/write replay start time from storage: ".concat(String(e))))}}}(e,t.sessionId,a,this.loggerProvider))&&void 0!==r?r:a,C=this,[4,nt(e,t)];case 1:return C.joinedConfigGenerator=l.sent(),[4,this.joinedConfigGenerator.generateJoinedConfig()];case 2:return E=l.sent(),P=E.joinedConfig,k=E.localConfig,x=E.remoteConfig,this.config=P,this.setMetadata(t.sessionId,P,k,x,null===(i=t.version)||void 0===i?void 0:i.version,gt,null===(s=t.version)||void 0===s?void 0:s.type),this.pageLeaveFns=[],t.sessionId&&(null===(h=this.config.interactionConfig)||void 0===h?void 0:h.enabled)&&(T=Cn.default({sessionId:t.sessionId,type:"interaction"},this.config),this.pageLeaveFns=[T.send(this.getDeviceId.bind(this)).bind(T)],this.scrollHook=T.hook.bind(T),this.clickHandler=new bn(this.loggerProvider,T)),R=[],"idb"!==(O=this.config.storeType)||(null===(v=g())||void 0===v?void 0:v.indexedDB)||(O="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log("Using ".concat(O," for event storage.")),F=g(),this.config.useWebWorker&&F&&F.Worker?[4,import("./index-min2.js")]:[3,4];case 3:D=l.sent(),q=D.compressionScript,A=D.trackDestinationScript,_=q,L=A,l.label=4;case 4:return l.trys.push([4,6,,7]),[4,tn({config:this.config,type:"replay",minInterval:null===(f=this.config.flushIntervalConfig)||void 0===f?void 0:f.minIntervalMs,maxInterval:null===(p=this.config.flushIntervalConfig)||void 0===p?void 0:p.maxIntervalMs,maxPersistedEventsSize:this.config.maxPersistedEventsSizeBytes,storeType:O,trackDestinationWorkerScript:L,shouldSend:function(){return!ee.isBelowMinSessionDuration()}})];case 5:return B=l.sent(),this.rrwebEventManager=B,R.push({name:"replay",manager:B}),[3,7];case 6:return N=l.sent(),z=N,this.loggerProvider.warn("Error occurred while creating replay events manager: ".concat(z.toString())),[3,7];case 7:if(!(null===(m=this.config.interactionConfig)||void 0===m?void 0:m.enabled))return[3,11];j=this.config.interactionConfig.batch?yn:mn,l.label=8;case 8:return l.trys.push([8,10,,11]),[4,tn({config:this.config,type:"interaction",minInterval:null!==(y=this.config.interactionConfig.trackEveryNms)&&void 0!==y?y:3e4,maxInterval:6e4,maxPersistedEventsSize:this.config.maxPersistedEventsSizeBytes,payloadBatcher:j,storeType:O,trackDestinationWorkerScript:L})];case 9:return U=l.sent(),R.push({name:"interaction",manager:U}),[3,11];case 10:return W=l.sent(),z=W,this.loggerProvider.warn("Error occurred while creating interaction events manager: ".concat(z.toString())),[3,11];case 11:if(this.eventsManager=new(nn.bind.apply(nn,d([void 0],u(R),!1))),this.eventCompressor&&this.eventCompressor.terminate(),K=!0===this.config.eagerFullSnapshotSend?function(){return ee.sendEvents()}:void 0,this.eventCompressor=new dt(this.eventsManager,this.config,this.getDeviceId(),_,K),this.pendingEmitEvents.length>0){H=this.pendingEmitEvents.splice(0);try{for(G=c(H),Q=G.next();!Q.done;Q=G.next())J=Q.value,$=J.event,Z=J.sessionId,this.eventCompressor.enqueueEvent($,Z)}catch(e){X={error:e}}finally{try{Q&&!Q.done&&(Y=G.return)&&Y.call(G)}finally{if(X)throw X.error}}}return this.pageLeaveFns=d(d([],u(this.pageLeaveFns),!1),[function(){var e;if(ee.config&&(null===(e=ee.identifiers)||void 0===e?void 0:e.sessionId)&&B){var t=B.getBeaconEvents();if(t.length){var n=ee.getDeviceId();n&&(ee.isBelowMinSessionDuration()||B.trackDestination.sendBeacon({events:t,sessionId:ee.identifiers.sessionId,deviceId:n,apiKey:ee.config.apiKey,serverZone:ee.config.serverZone}))}}}],!1),[4,this.initializeNetworkObservers()];case 12:return l.sent(),(null===(b=g())||void 0===b?void 0:b.opener)&&(ce(V=se()),V.setup(o({logger:this.loggerProvider},this.config.serverZone&&{endpoint:ne[this.config.serverZone]}))),this.loggerProvider.log("Installing @amplitude/session-replay-browser."),this.teardownEventListeners(!1),[4,this.evaluateTargetingAndCapture({userProperties:t.userProperties,page:this.getCurrentPageForTargeting()},!0)];case 13:return l.sent(),(this.config.targetingConfig||(null!==(w=null===(I=null===(S=this.config.privacyConfig)||void 0===S?void 0:S.urlMaskLevels)||void 0===I?void 0:I.length)&&void 0!==w?w:0)>0)&&this.setupUrlChangeListener(),[2]}})})},e.prototype.setSessionId=function(e,t){return k(this.asyncSetSessionId(e,t))},e.prototype.asyncSetSessionId=function(e,t,n){var r,i,o,s;return a(this,void 0,void 0,function(){var a,c,u,d,h;return l(this,function(l){switch(l.label){case 0:return a=null===(r=this.identifiers)||void 0===r?void 0:r.sessionId,c=this.getDeviceId(),void 0===a||a!==e||void 0!==t&&t!==c||void 0!==(null==n?void 0:n.userProperties)&&0!==Object.keys(n.userProperties).length?(this.latestUrlChangeTargetingEvaluationId++,this.sessionTargetingMatch=!1,this.lastShouldRecordDecision=void 0,a&&this.sendEvents(a),(u=a!==e)&&(null===(i=this.rrwebEventManager)||void 0===i||i.dropPendingBeaconEvents()),d=t||this.getDeviceId(),this.identifiers=new En({sessionId:e,deviceId:d}),u&&(this.sessionStartTime=Date.now(),this.suppressedSendCount=0,this.hasEmittedGateDecision=!1,(null===(o=this.config)||void 0===o?void 0:o.apiKey)&&(function(e,t,n,r){var i=Mn();if(i)try{i.setItem(xn(e,t),String(n))}catch(e){null==r||r.debug("Failed to write replay start time to storage: ".concat(String(e)))}}(this.config.apiKey,e,this.sessionStartTime,this.loggerProvider),void 0!==a&&function(e,t,n){var r=Mn();if(r)try{r.removeItem(xn(e,t))}catch(e){null==n||n.debug("Failed to remove replay start time from storage: ".concat(String(e)))}}(this.config.apiKey,a,this.loggerProvider))),this.joinedConfigGenerator&&a?[4,this.joinedConfigGenerator.generateJoinedConfig()]:[3,2]):[2];case 1:h=l.sent().joinedConfig,this.config=h,l.label=2;case 2:return(null===(s=this.config)||void 0===s?void 0:s.targetingConfig)?[4,this.evaluateTargetingAndCapture({userProperties:null==n?void 0:n.userProperties,page:this.getCurrentPageForTargeting()},!1,!0)]:[3,4];case 3:return l.sent(),[3,6];case 4:return[4,this.recordEvents()];case 5:l.sent(),l.label=6;case 6:return[2]}})})},e.prototype.getSessionReplayProperties=function(){var e,t=this.config,n=this.identifiers;if(!t||!n)return this.loggerProvider.warn("Session replay init has not been called, cannot get session replay properties."),{};var r=this.getShouldRecord(),i={};return r&&((e={})[he]=n.sessionReplayId?n.sessionReplayId:null,i=e,t.debugMode&&(i[pe]=JSON.stringify({appHash:H(t.apiKey).toString()}))),this.addCustomRRWebEvent(ue.GET_SR_PROPS,{shouldRecord:r,eventProperties:i},10===this.eventCount),10===this.eventCount&&(this.eventCount=0),this.eventCount++,i},e.prototype.sendEvents=function(e){var t,n,r=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),i=this.getDeviceId();if(this.eventsManager&&r&&i){if(this.isBelowMinSessionDuration()){var o=this.sessionStartTime,s=this.config.minSessionDurationMs;return this.loggerProvider.log("Session ".concat(r," not sent: duration ").concat(Date.now()-o,"ms is below minimum ").concat(s,"ms.")),void this.suppressedSendCount++}if(!this.hasEmittedGateDecision&&void 0!==(null===(n=this.config)||void 0===n?void 0:n.minSessionDurationMs)&&this.recordCancelCallback&&this.recordFunction){this.hasEmittedGateDecision=!0;var a=void 0!==this.sessionStartTime?Date.now()-this.sessionStartTime:void 0;this.addCustomRRWebEvent(ue.REPLAY_GATE_DECISION,{sessionId:r,suppressedSendCount:this.suppressedSendCount,elapsedMs:a,minSessionDurationMs:this.config.minSessionDurationMs},!1)}this.eventsManager.sendCurrentSequenceEvents({sessionId:r,deviceId:i})}},e.prototype.initialize=function(e){var t;return void 0===e&&(e=!1),a(this,void 0,void 0,function(){var n;return l(this,function(r){return(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId)?(n=this.getDeviceId())?(this.eventsManager&&e&&this.eventsManager.sendStoredEvents({deviceId:n}),[2,this.recordEvents()]):(this.loggerProvider.log("Session is not being recorded due to lack of device id."),[2,Promise.resolve()]):(this.loggerProvider.log("Session is not being recorded due to lack of session id."),[2,Promise.resolve()])})})},e.prototype.shouldOptOut=function(){var e,t,n,r;(null===(e=this.config)||void 0===e?void 0:e.instanceName)&&(n=(r=this.config.instanceName,K.getInstance(T(r))).identityStore.getIdentity().optOut);return void 0!==n?n:null===(t=this.config)||void 0===t?void 0:t.optOut},e.prototype.getShouldRecord=function(){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.recordingEnabled)return this.loggerProvider.log("Session ".concat(this.identifiers.sessionId," not being captured because recording was stopped.")),!1;if(!this.config.captureEnabled)return this.loggerProvider.log("Session ".concat(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 ".concat(this.identifiers.sessionId," out of recording due to optOut config.")),!1;var e,t,n=!1,r="",i=!1;this.config.targetingConfig?this.sessionTargetingMatch?(r="Capturing replays for session ".concat(this.identifiers.sessionId," due to matching targeting conditions."),this.loggerProvider.log(r),n=!0,i=!0):(r="Not capturing replays for session ".concat(this.identifiers.sessionId," due to not matching targeting conditions."),this.loggerProvider.log(r),n=!1,i=!1):(e=this.identifiers.sessionId,t=this.config.sampleRate,Nn(e.toString())%1e6/1e6<t)?(n=!0,i=!0):(r="Opting session ".concat(this.identifiers.sessionId," out of recording due to sample rate."),this.loggerProvider.log(r),n=!1,i=!1);return this.lastShouldRecordDecision!==n&&this.config.targetingConfig&&(this.addCustomRRWebEvent(ue.TARGETING_DECISION,{message:r,sessionId:this.identifiers.sessionId,matched:i,targetingParams:this.lastTargetingParams}),this.lastShouldRecordDecision=n),n},e.prototype.getBlockSelectors=function(){var e;return qe(null===(e=this.config)||void 0===e?void 0:e.privacyConfig)},e.prototype.getMaskTextSelectors=function(){var e;return Ae(null===(e=this.config)||void 0===e?void 0:e.privacyConfig,this.currentPageUrl)},e.prototype.getRecordingPlugins=function(e){var t,n,r,i,o,s;return a(this,void 0,void 0,function(){var a,c,u,d;return l(this,function(l){switch(l.label){case 0:a=[];try{c=zn({ugcFilterRules:(null===(n=null===(t=this.config)||void 0===t?void 0:t.interactionConfig)||void 0===n?void 0:n.ugcFilterRules)||[],enablePolling:(null===(r=this.config)||void 0===r?void 0:r.enableUrlChangePolling)||!1,pollingInterval:null===(i=this.config)||void 0===i?void 0:i.urlChangePollingInterval,captureDocumentTitle:null===(o=this.config)||void 0===o?void 0:o.captureDocumentTitle}),a.push(c)}catch(e){this.loggerProvider.warn("Failed to create URL tracking plugin:",e)}if(!(null===(s=null==e?void 0:e.console)||void 0===s?void 0:s.enabled))return[3,4];l.label=1;case 1:return l.trys.push([1,3,,4]),[4,import("./rrweb-plugin-console-record-min.js")];case 2:return u=l.sent().getRecordConsolePlugin,a.push(u({level:e.console.levels})),[3,4];case 3:return d=l.sent(),this.loggerProvider.warn("Failed to load console plugin:",d),[3,4];case 4:return[2,a.length>0?a:void 0]}})})},e.prototype.getRecordFunction=function(){return a(this,void 0,void 0,function(){var e,t;return l(this,function(n){switch(n.label){case 0:if(this.recordFunction)return[2,this.recordFunction];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,import("./rrweb-record-min.js")];case 2:return e=n.sent().record,this.recordFunction=e,[2,e];case 3:return t=n.sent(),this.loggerProvider.warn("Failed to load rrweb-record module:",t),[2,null];case 4:return[2]}})})},e.prototype.recordEvents=function(e){return void 0===e&&(e=!0),a(this,void 0,void 0,function(){var t;return l(this,function(n){switch(n.label){case 0:if(this.recordEventsInFlight)return this.recordEventsPendingShouldLogMetadata=e,[2];this.recordEventsInFlight=!0,n.label=1;case 1:return n.trys.push([1,,6,7]),[4,this._recordEvents(e)];case 2:n.sent(),n.label=3;case 3:return null===this.recordEventsPendingShouldLogMetadata?[3,5]:(t=this.recordEventsPendingShouldLogMetadata,this.recordEventsPendingShouldLogMetadata=null,[4,this._recordEvents(t)]);case 4:return n.sent(),[3,3];case 5:return[3,7];case 6:return this.recordEventsInFlight=!1,this.recordEventsPendingShouldLogMetadata=null,[7];case 7:return[2]}})})},e.prototype.shouldAbandonRecordStart=function(e){return!this.recordingEnabled||e!==this.recordingGeneration},e.prototype._recordEvents=function(e){var t,n,r,i,s,c,u,d;return void 0===e&&(e=!0),a(this,void 0,void 0,function(){var a,h,v,f,p,m,y,b,S,I,w,C,E,P,k,x,M,T=this;return l(this,function(l){switch(l.label){case 0:return a=this.config,h=this.getShouldRecord(),v=null===(t=this.identifiers)||void 0===t?void 0:t.sessionId,h&&v&&a?(this.stopRecordingEvents(),f=this.recordingGeneration,[4,this.getRecordFunction()]):[2];case 1:return!(p=l.sent())||this.shouldAbandonRecordStart(f)?[2]:[4,this.initializeNetworkObservers()];case 2:if(l.sent(),this.shouldAbandonRecordStart(f))return[2];m=null===(n=a.loggingConfig)||void 0===n?void 0:n.network,y=Be(a.serverZone,a.trackServerUrl),b=[me,ye,be,y],null===(r=this.networkObservers)||void 0===r||r.start(function(e){b.some(function(t){return e.url.startsWith(t)})||T.addCustomRRWebEvent(ue.FETCH_REQUEST,e)},m),S=a.interactionConfig,I=a.loggingConfig,w=(null==S?void 0:S.enabled)?{mouseInteraction:this.eventsManager&&(null===(i=this.clickHandler)||void 0===i?void 0:i.createHook({eventsManager:this.eventsManager,sessionId:v,deviceIdFn:this.getDeviceId.bind(this),mirror:p.mirror,ugcFilterRules:null!==(s=S.ugcFilterRules)&&void 0!==s?s:[],performanceOptions:null===(c=a.performanceConfig)||void 0===c?void 0:c.interaction})),scroll:this.scrollHook}:{},C=(null==S?void 0:S.enabled)&&S.ugcFilterRules?S.ugcFilterRules:[],this.loggerProvider.log("Session Replay capture beginning for ".concat(v,".")),l.label=3;case 3:return l.trys.push([3,5,,6]),E=!!(null===(u=a.crossOriginIframes)||void 0===u?void 0:u.enabled),P=!1!==(null===(d=a.crossOriginIframes)||void 0===d?void 0:d.coordinateChildren),(k=E&&function(){try{var e=g();return!!e&&e.parent!==e}catch(e){return!0}}())&&P?(this.crossOriginParentSignalCleanup=function(e){var t=g();if(!t)return function(){};var n=t.parent;function r(t){if(t.source===n){var r=t.data;(null==r?void 0:r.type)===ke&&("start"===r.action?e.onStart():"stop"===r.action&&e.onStop())}}return t.addEventListener("message",r),function(){return t.removeEventListener("message",r)}}({onStart:function(){T.recordingEnabled&&T._recordEventsInChildMode(p,v,a,w)},onStop:function(){try{T.recordCancelCallback&&T.recordCancelCallback(),T.recordCancelCallback=null}catch(t){var e=t;T.loggerProvider.warn("Error occurred while stopping child iframe replay capture: ".concat(e.toString()))}}}),this.startChildRecordingOnSetup&&(this.startChildRecordingOnSetup=!1,this._recordEventsInChildMode(p,v,a,w)),[2]):(this.startChildRecordingOnSetup=!1,[4,this.getRecordingPlugins(I)]);case 4:return x=l.sent(),this.shouldAbandonRecordStart(f)?[2]:(this.recordCancelCallback=p(o(o({},this.buildRRWebRecordOptions(a,w,function(e){if(T.shouldOptOut()||!T.recordingEnabled)return T.loggerProvider.log(T.shouldOptOut()?"Opting session ".concat(v," out of recording due to optOut config."):"Session Replay capture stopping for ".concat(v,".")),T.stopRecordingEvents(),void T.sendEvents();e.type===Ze.Meta&&(e.data.href=je(e.data.href,C)),T.eventCompressor?T.eventCompressor.enqueueEvent(e,v):T.pendingEmitEvents.push({event:e,sessionId:v})},"Error while capturing replay: ")),{plugins:x,recordCrossOriginIframes:E})),E&&!k&&P&&(this.crossOriginIframeCoordinator||(this.crossOriginIframeCoordinator=new Kn),this.crossOriginIframeCoordinator.start()),this.addCustomRRWebEvent(ue.DEBUG_INFO),e&&this.addCustomRRWebEvent(ue.METADATA,this.metadata),[3,6]);case 5:return M=l.sent(),this.loggerProvider.warn("Failed to initialize session replay:",M),[3,6];case 6:return[2]}})})},e.prototype.buildRRWebRecordOptions=function(e,t,n,r){var i=this,s=e.privacyConfig;return o(o(o(o({emit:n,inlineStylesheet:e.shouldInlineStylesheet,inlineImages:e.inlineImages,hooks:t},function(e,t){return void 0===t&&(t=function(){return""}),{maskAllInputs:!0,maskTextClass:"amp-mask",blockClass:"amp-block",blockSelector:qe(e),maskTextSelector:Ae(e,t()),maskInputFn:Fe("input",e,t),maskTextFn:Fe("text",e,t),maskAttributeFn:De(e,t)}}(s,function(){return i.currentPageUrl})),{applyBackgroundColorToBlockedElements:e.applyBackgroundColorToBlockedElements}),void 0!==e.fullSnapshotIntervalMs&&{checkoutEveryNms:e.fullSnapshotIntervalMs}),{recordCanvas:!1,captureAdoptedStyleSheets:e.captureAdoptedStyleSheets,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},errorHandler:function(e){var t=e;if(t.message.includes("insertRule")&&t.message.includes("CSSStyleSheet"))throw t;if(t._external_)throw t;return i.loggerProvider.warn(r,t.toString()),!0}})},e.prototype._recordEventsInChildMode=function(e,t,n,r){try{this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null,this.recordCancelCallback=e(o(o({},this.buildRRWebRecordOptions(n,r,function(){},"Error while capturing replay (child iframe): ")),{recordCrossOriginIframes:!0})),this.loggerProvider.log("Session Replay child iframe capture beginning for session ".concat(t,"."))}catch(e){this.loggerProvider.warn("Failed to initialize session replay in child iframe mode:",e)}},e.prototype.getDeviceId=function(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.deviceId},e.prototype.getSessionId=function(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.sessionId},e.prototype.start=function(){return k(this._start())},e.prototype._start=function(){return a(this,void 0,void 0,function(){return l(this,function(e){switch(e.label){case 0:return this.recordingEnabled=!0,this.startChildRecordingOnSetup=!0,[4,this.recordEvents()];case 1:return e.sent(),[2]}})})},e.prototype.stop=function(){this.recordingEnabled=!1,this.startChildRecordingOnSetup=!1,this.recordingGeneration++,this.stopRecordingEvents(),this.sendEvents()},e.prototype.flush=function(e){var t;return void 0===e&&(e=!1),a(this,void 0,void 0,function(){return l(this,function(n){return[2,null===(t=this.eventsManager)||void 0===t?void 0:t.flush(e)]})})},e.prototype.shutdown=function(){var e,t;this.recordingEnabled=!1,this.startChildRecordingOnSetup=!1,this.recordingGeneration++,null===(e=this.urlChangeCleanup)||void 0===e||e.call(this),null===(t=this.crossOriginParentSignalCleanup)||void 0===t||t.call(this),this.crossOriginParentSignalCleanup=null,this.teardownEventListeners(!0),this.stopRecordingEvents(),this.sendEvents()},e.prototype.mapSDKType=function(e){return"plugin"===e?"@amplitude/plugin-session-replay-browser":"segment"===e?"@amplitude/segment-session-replay-plugin":null},e.prototype.setMetadata=function(e,t,n,r,i,o,s){var a=(null==e?void 0:e.toString())?H(e.toString()):void 0;this.metadata={joinedConfig:t,localConfig:n,remoteConfig:r,sessionId:e,hashValue:a,sampleRate:t.sampleRate,replaySDKType:this.mapSDKType(s),replaySDKVersion:i,standaloneSDKType:"@amplitude/session-replay-browser",standaloneSDKVersion:o}},e.prototype.initializeNetworkObservers=function(){var e,t,n;return a(this,void 0,void 0,function(){var r,i;return l(this,function(o){switch(o.label){case 0:if(!(null===(n=null===(t=null===(e=this.config)||void 0===e?void 0:e.loggingConfig)||void 0===t?void 0:t.network)||void 0===n?void 0:n.enabled)||this.networkObservers)return[3,4];o.label=1;case 1:return o.trys.push([1,3,,4]),[4,import("./observers-min.js")];case 2:return r=o.sent().NetworkObservers,this.networkObservers=new r,[3,4];case 3:return i=o.sent(),this.loggerProvider.warn("Failed to import or instantiate NetworkObservers:",i),[3,4];case 4:return[2]}})})},e}(),Gn=function(e){return function(){var t=e.config||ze();return{logger:t.loggerProvider,logLevel:t.logLevel}}},Qn=function(){var e=new Hn;return{init:F(e.init.bind(e),"init",Gn(e)),evaluateTargetingAndCapture:F(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",Gn(e)),setSessionId:F(e.setSessionId.bind(e),"setSessionId",Gn(e)),getSessionId:F(e.getSessionId.bind(e),"getSessionId",Gn(e)),getSessionReplayProperties:F(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",Gn(e)),flush:F(e.flush.bind(e),"flush",Gn(e)),start:F(e.start.bind(e),"start",Gn(e)),stop:F(e.stop.bind(e),"stop",Gn(e)),shutdown:F(e.shutdown.bind(e),"shutdown",Gn(e))}}(),Jn=Qn.init,$n=Qn.setSessionId,Zn=Qn.getSessionId,Vn=Qn.getSessionReplayProperties;Qn.flush,Qn.start,Qn.stop,Qn.shutdown,Qn.evaluateTargetingAndCapture;const Xn="amp_session_id",Yn="Amplitude Session Replay Segment Plugin [Debug]:";function er(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)"__proto__"!==r&&(e[r]=n[r])}return e}var tr=function e(t,n){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=er({},n,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var s in i)i[s]&&(o+="; "+s,!0!==i[s]&&(o+="="+i[s].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+o}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],r={},i=0;i<n.length;i++){var o=n[i].split("="),s=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(a in r||(r[a]=t.read(s,a)),e===a)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",er({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,er({},this.attributes,t))},withConverter:function(t){return e(er({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});const nr=()=>{const e=Zn()||tr.get(Xn);if(e){const t=parseInt(e.toString(),10);if(isNaN(t))return;return t}},rr=(e,t)=>(tr.set(Xn,e.toString()),$n(e,t).promise),ir=(e,t)=>a(void 0,void 0,void 0,function*(){const n=nr()||0;let r;e.event.integrations&&e.event.integrations["Actions Amplitude"]&&(r=e.event.integrations["Actions Amplitude"].session_id),r&&n<r&&(yield rr(r,t));const i=Vn(),o=Object.assign(Object.assign({},i),e.event.properties);return e.updateEvent("properties",o),e}),or="0.0.50",sr=({amplitudeApiKey:e,sessionReplayOptions:t,segmentInstance:n,enableWrapperDebug:r=!1})=>a(void 0,void 0,void 0,function*(){let i,o=!1,s=null==t?void 0:t.deviceId;const l={name:"Session Replay Events",type:"enrichment",version:or,isLoaded:()=>o,load:(n,l)=>a(void 0,void 0,void 0,function*(){if(!s){const e=l.user();s=e.anonymousId()||void 0}const n=nr();r&&console.log(`${Yn} initializing session replay with sessionId=${null!=n?n:"undefined"} and deviceId=${null!=s?s:"undefined"}`),i=Jn(e,Object.assign(Object.assign({},t),{sessionId:n,deviceId:s||void 0,version:{type:"segment",version:or}})).promise,yield i,o=!0}),track:e=>a(void 0,void 0,void 0,function*(){return yield i,yield ir(e,s)}),page:e=>a(void 0,void 0,void 0,function*(){return yield i,yield ir(e,s)}),identify:e=>a(void 0,void 0,void 0,function*(){yield i;const t=nr();return t&&(r&&console.log(`${Yn} calling setSessionId() with sessionId=${t} and deviceId=${null!=s?s:"undefined"}`),yield rr(t,s)),e})};yield n.register(l)});export{c as _,d as a,u as b,a as c,l as d,o as e,sr as f,g,Rt as o,st as t};
2
2
  //# sourceMappingURL=index-min.js.map