@amplitude/session-replay-browser 1.32.1 → 1.32.2

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
- export declare const VERSION = "1.32.1";
1
+ export declare const VERSION = "1.32.2";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -2,5 +2,5 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VERSION = void 0;
4
4
  // Autogenerated by `pnpm version-file`. DO NOT EDIT
5
- exports.VERSION = '1.32.1';
5
+ exports.VERSION = '1.32.2';
6
6
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";;;AAAA,oDAAoD;AACvC,QAAA,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["// Autogenerated by `pnpm version-file`. DO NOT EDIT\nexport const VERSION = '1.32.1';\n"]}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";;;AAAA,oDAAoD;AACvC,QAAA,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["// Autogenerated by `pnpm version-file`. DO NOT EDIT\nexport const VERSION = '1.32.2';\n"]}
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "1.32.1";
1
+ export declare const VERSION = "1.32.2";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -1,3 +1,3 @@
1
1
  // Autogenerated by `pnpm version-file`. DO NOT EDIT
2
- export var VERSION = '1.32.1';
2
+ export var VERSION = '1.32.2';
3
3
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,oDAAoD;AACpD,MAAM,CAAC,IAAM,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["// Autogenerated by `pnpm version-file`. DO NOT EDIT\nexport const VERSION = '1.32.1';\n"]}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,oDAAoD;AACpD,MAAM,CAAC,IAAM,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["// Autogenerated by `pnpm version-file`. DO NOT EDIT\nexport const VERSION = '1.32.2';\n"]}
@@ -1,2 +1,2 @@
1
- import{_ as e,a as t,b as n,c as i,d as r,e as s,f as o,o as a}from"./targeting-min.js";var l,c;!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"}(l||(l={})),function(e){e.IDENTIFY="$identify",e.GROUP_IDENTIFY="$groupidentify",e.REVENUE="revenue_amount"}(c||(c={}));var u,d="$default_instance",g="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"}(u||(u={}));var h,v=function(){var e="ampIntegrationContext";return"undefined"!=typeof globalThis&&void 0!==globalThis[e]?globalThis[e]:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0},f=e([],t(Array(256).keys()),!1).map(function(e){return e.toString(16).padStart(2,"0")}),p=function(n){var i,r=v();if(!(null===(i=null==r?void 0:r.crypto)||void 0===i?void 0:i.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,p)}(n);var s=r.crypto.getRandomValues(new Uint8Array(16));return s[6]=15&s[6]|64,s[8]=63&s[8]|128,e([],t(s.entries()),!1).map(function(e){var n=t(e,2),i=n[0],r=n[1];return[4,6,8,10].includes(i)?"-".concat(f[r]):f[r]}).join("")},m=function(e){return{promise:e||Promise.resolve()}};!function(e){e[e.None=0]="None",e[e.Error=1]="Error",e[e.Warn=2]="Warn",e[e.Verbose=3]="Verbose",e[e.Debug=4]="Debug"}(h||(h={}));var y="Amplitude Logger ",b=function(){function e(){this.logLevel=h.None}return e.prototype.disable=function(){this.logLevel=h.None},e.prototype.enable=function(e){void 0===e&&(e=h.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Verbose||console.log("".concat(y,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Warn||console.warn("".concat(y,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Error||console.error("".concat(y,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Debug||console.log("".concat(y,"[Debug]: ").concat(e.join(" ")))},e}(),S=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:d,logLevel:h.Warn,loggerProvider:new b,offline:!1,optOut:!1,serverUrl:g,serverZone:"US",useBatch:!1}},C=function(){function e(e){var t,n,i,r;this._optOut=!1;var s=S();this.apiKey=e.apiKey,this.flushIntervalMillis=null!==(t=e.flushIntervalMillis)&&void 0!==t?t:s.flushIntervalMillis,this.flushMaxRetries=e.flushMaxRetries||s.flushMaxRetries,this.flushQueueSize=e.flushQueueSize||s.flushQueueSize,this.instanceName=e.instanceName||s.instanceName,this.loggerProvider=e.loggerProvider||s.loggerProvider,this.logLevel=null!==(n=e.logLevel)&&void 0!==n?n:s.logLevel,this.minIdLength=e.minIdLength,this.plan=e.plan,this.ingestionMetadata=e.ingestionMetadata,this.offline=void 0!==e.offline?e.offline:s.offline,this.optOut=null!==(i=e.optOut)&&void 0!==i?i:s.optOut,this.serverUrl=e.serverUrl,this.serverZone=e.serverZone||s.serverZone,this.storageProvider=e.storageProvider,this.transportProvider=e.transportProvider,this.useBatch=null!==(r=e.useBatch)&&void 0!==r?r:s.useBatch,this.loggerProvider.enable(this.logLevel);var o=I(e.serverUrl,e.serverZone,e.useBatch);this.serverZone=o.serverZone,this.serverUrl=o.serverUrl}return Object.defineProperty(e.prototype,"optOut",{get:function(){return this._optOut},set:function(e){this._optOut=e},enumerable:!1,configurable:!0}),e}(),w=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":g},I=function(e,t,n){if(void 0===e&&(e=""),void 0===t&&(t=S().serverZone),void 0===n&&(n=S().useBatch),e)return{serverUrl:e,serverZone:void 0};var i=["US","EU"].includes(t)?t:S().serverZone;return{serverZone:i,serverUrl:w(i,n)}};var P=function(e,t,n,i,r){return void 0===r&&(r=null),function(){for(var s=[],o=0;o<arguments.length;o++)s[o]=arguments[o];var a=n(),l=a.logger,c=a.logLevel;if(c&&c<h.Debug||!c||!l)return e.apply(r,s);var u,d={type:"invoke public method",name:t,args:s,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:{}};i&&d.states&&(d.states.before=i());var g=e.apply(r,s);return g&&g.promise?g.promise.then(function(){i&&d.states&&(d.states.after=i()),d.time&&(d.time.end=(new Date).toISOString()),l.debug(JSON.stringify(d,null,2))}):(i&&d.states&&(d.states.after=i()),d.time&&(d.time.end=(new Date).toISOString()),l.debug(JSON.stringify(d,null,2))),g}},k=function(){function e(){}return e.prototype.getApplicationContext=function(){return{versionName:this.versionName,language:E(),platform:"Web",os:void 0,deviceModel:void 0}},e}(),E=function(){return"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||""},R=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}(),T=function(){return T=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},T.apply(this,arguments)};function O(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function _(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var i,r,s=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(i=s.next()).done;)o.push(i.value)}catch(e){r={error:e}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return o}"function"==typeof SuppressedError&&SuppressedError;var M=function(e,t){var n,i,r=typeof e;if(r!==typeof t)return!1;try{for(var s=O(["string","number","boolean","undefined"]),o=s.next();!o.done;o=s.next()){if(o.value===r)return e===t}}catch(e){n={error:e}}finally{try{o&&!o.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}if(null==e&&null==t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;var a=Array.isArray(e),l=Array.isArray(t);if(a!==l)return!1;if(!a||!l){var c=Object.keys(e).sort(),u=Object.keys(t).sort();if(!M(c,u))return!1;var d=!0;return Object.keys(e).forEach(function(n){M(e[n],t[n])||(d=!1)}),d}for(var g=0;g<e.length;g++)if(!M(e[g],t[g]))return!1;return!0};Object.entries||(Object.entries=function(e){for(var t=Object.keys(e),n=t.length,i=new Array(n);n--;)i[n]=[t[n],e[t[n]]];return i});var x,L=function(){function e(){this.identity={userProperties:{}},this.listeners=new Set}return e.prototype.editIdentity=function(){var e=this,t=T({},this.identity.userProperties),n=T(T({},this.identity),{userProperties:t});return{setUserId:function(e){return n.userId=e,this},setDeviceId:function(e){return n.deviceId=e,this},setUserProperties:function(e){return n.userProperties=e,this},setOptOut:function(e){return n.optOut=e,this},updateUserProperties:function(e){var t,i,r,s,o,a,l=n.userProperties||{};try{for(var c=O(Object.entries(e)),u=c.next();!u.done;u=c.next()){var d=_(u.value,2),g=d[0],h=d[1];switch(g){case"$set":try{for(var v=(r=void 0,O(Object.entries(h))),f=v.next();!f.done;f=v.next()){var p=_(f.value,2),m=p[0],y=p[1];l[m]=y}}catch(e){r={error:e}}finally{try{f&&!f.done&&(s=v.return)&&s.call(v)}finally{if(r)throw r.error}}break;case"$unset":try{for(var b=(o=void 0,O(Object.keys(h))),S=b.next();!S.done;S=b.next()){delete l[m=S.value]}}catch(e){o={error:e}}finally{try{S&&!S.done&&(a=b.return)&&a.call(b)}finally{if(o)throw o.error}}break;case"$clearAll":l={}}}}catch(e){t={error:e}}finally{try{u&&!u.done&&(i=c.return)&&i.call(c)}finally{if(t)throw t.error}}return n.userProperties=l,this},commit:function(){return e.setIdentity(n),this}}},e.prototype.getIdentity=function(){return T({},this.identity)},e.prototype.setIdentity=function(e){var t=T({},this.identity);this.identity=T({},e),M(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}(),D="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self,q=function(){function e(){this.identityStore=new L,this.eventBridge=new R,this.applicationContextProvider=new k}return e.getInstance=function(t){return D.analyticsConnectorInstances||(D.analyticsConnectorInstances={}),D.analyticsConnectorInstances[t]||(D.analyticsConnectorInstances[t]=new e),D.analyticsConnectorInstances[t]},e}(),N=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},U=function(){function e(){}return e.prototype.send=function(e,t,n){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,n,i,r,s,o,a,l,c,d,g,h,v,f,p,m,y,b,S,C,w,I;if("object"!=typeof e)return null;var P=e.code||0,k=this.buildStatus(P);switch(k){case u.Success:return{status:k,statusCode:P,body:{eventsIngested:null!==(t=e.events_ingested)&&void 0!==t?t:0,payloadSizeBytes:null!==(n=e.payload_size_bytes)&&void 0!==n?n:0,serverUploadTime:null!==(i=e.server_upload_time)&&void 0!==i?i:0}};case u.Invalid:return{status:k,statusCode:P,body:{error:null!==(r=e.error)&&void 0!==r?r:"",missingField:null!==(s=e.missing_field)&&void 0!==s?s:"",eventsWithInvalidFields:null!==(o=e.events_with_invalid_fields)&&void 0!==o?o:{},eventsWithMissingFields:null!==(a=e.events_with_missing_fields)&&void 0!==a?a:{},eventsWithInvalidIdLengths:null!==(l=e.events_with_invalid_id_lengths)&&void 0!==l?l:{},epsThreshold:null!==(c=e.eps_threshold)&&void 0!==c?c:0,exceededDailyQuotaDevices:null!==(d=e.exceeded_daily_quota_devices)&&void 0!==d?d:{},silencedDevices:null!==(g=e.silenced_devices)&&void 0!==g?g:[],silencedEvents:null!==(h=e.silenced_events)&&void 0!==h?h:[],throttledDevices:null!==(v=e.throttled_devices)&&void 0!==v?v:{},throttledEvents:null!==(f=e.throttled_events)&&void 0!==f?f:[]}};case u.PayloadTooLarge:return{status:k,statusCode:P,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case u.RateLimit:return{status:k,statusCode:P,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!==(C=e.exceeded_daily_quota_devices)&&void 0!==C?C:{},exceededDailyQuotaUsers:null!==(w=e.exceeded_daily_quota_users)&&void 0!==w?w:{},throttledEvents:null!==(I=e.throttled_events)&&void 0!==I?I:[]}};case u.Timeout:default:return{status:k,statusCode:P}}},e.prototype.buildStatus=function(e){return function(e){return e>=200&&e<300}(e)?u.Success:429===e?u.RateLimit:413===e?u.PayloadTooLarge:408===e?u.Timeout:e>=400&&e<500?u.Invalid:e>=500?u.Failed:u.Unknown},e}(),j=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 i(this,void 0,void 0,function(){var n,i,o;return r(this,function(r){switch(r.label){case 0:if("undefined"==typeof fetch)throw new Error("FetchTransport is not supported");return n={headers:s({"Content-Type":"application/json",Accept:"*/*"},this.customHeaders),body:JSON.stringify(t),method:"POST"},[4,fetch(e,n)];case 1:return[4,(i=r.sent()).text()];case 2:o=r.sent();try{return[2,this.buildResponse(JSON.parse(o))]}catch(e){return[2,this.buildResponse({code:i.status})]}return[2]}})})},t}(U),F=function(){function e(e,t){this.key="AMP_remote_config_".concat(e.substring(0,10)),this.logger=t}return e.prototype.fetchConfig=function(){var e=null,t={remoteConfig:null,lastFetch:new Date};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(JSON.stringify(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){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}(),$=401,A=429,W=function(){function e(e,t,n,i){void 0===n&&(n="US"),this.callbackInfos=[],this.lastSuccessfulFetch=null,this.fetchPromise=null,this.isLastFetchInvalidApiKey=!1,this.apiKey=e,this.serverUrl=i||("US"===n?"https://sr-client-cfg.amplitude.com/config":"https://sr-client-cfg.eu.amplitude.com/config"),this.logger=t,this.storage=new F(e,t)}return e.prototype.subscribe=function(e,t,n){var i=p(),r={id:i,key:e,deliveryMode:t,callback:n};return this.callbackInfos.push(r),"all"===t?this.subscribeAll(r):this.subscribeWaitForRemote(r,t.timeout),i},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 i(this,void 0,void 0,function(){var e,t=this;return r(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 i(this,void 0,void 0,function(){var t,n,i,s=this;return r(this,function(r){switch(r.label){case 0:return t=this.getOrCreateFetchPromise().then(function(t){s.logger.debug("Remote config client subscription all mode fetched from remote: ".concat(JSON.stringify(t))),s.sendCallback(e,t,"remote"),s.storage.setConfig(t)}),n=this.storage.fetchConfig().then(function(e){return e}),[4,Promise.race([t,n])];case 1:return void 0!==(i=r.sent())&&(this.logger.debug("Remote config client subscription all mode fetched from cache: ".concat(JSON.stringify(i))),null!==i.remoteConfig?this.sendCallback(e,i,"cache"):this.logger.debug("Remote config client skips sending callback because cache is empty (first time user).")),[4,t];case 2:return r.sent(),[2]}})})},e.prototype.subscribeWaitForRemote=function(e,t){return i(this,void 0,void 0,function(){var n,i;return r(this,function(r){switch(r.label){case 0:n=new Promise(function(e,n){setTimeout(function(){n("Timeout exceeded")},t)}),r.label=1;case 1:return r.trys.push([1,3,,5]),[4,Promise.race([this.getOrCreateFetchPromise(),n])];case 2:return i=r.sent(),this.logger.debug("Remote config client subscription wait for remote mode returns from remote."),this.sendCallback(e,i,"remote"),this.storage.setConfig(i),[3,5];case 3:return r.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!==(i=r.sent()).remoteConfig?(this.logger.debug("Remote config client subscription wait for remote mode returns a cached copy."),this.sendCallback(e,i,"cache")):(this.logger.debug("Remote config client subscription wait for remote mode failed to fetch cache."),this.sendCallback(e,i,"remote")),[3,5];case 5:return[2]}})})},e.prototype.sendCallback=function(e,t,n){var i;e.lastCallback=new Date,i=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(i,n,t.lastFetch)},e.prototype.fetch=function(e,t){return void 0===e&&(e=3),void 0===t&&(t=1e3),i(this,void 0,void 0,function(){var n,i,s,o,a,l,c=this;return r(this,function(u){switch(u.label){case 0:n=t/e,i={remoteConfig:null,lastFetch:new Date},s=function(i){var s,a,l,u,d,g;return r(this,function(r){switch(r.label){case 0:s=!0,a=new AbortController,l=setTimeout(function(){return a.abort()},t),r.label=1;case 1:return r.trys.push([1,7,8,9]),[4,fetch(o.getUrlParams(),{method:"GET",headers:{Accept:"*/*"},signal:a.signal})];case 2:return(u=r.sent()).ok?[3,4]:[4,u.text()];case 3:return d=r.sent(),o.logger.debug("Remote config client fetch with retry time ".concat(e," failed with ").concat(u.status,": ").concat(d)),u.status===$?(o.logger.error("Remote config client fetch failed with ".concat($,". Invalid API key; future fetches will be skipped.")),o.isLastFetchInvalidApiKey=!0,s=!1):u.status>=400&&u.status<500&&u.status!==A&&(s=!1),[3,6];case 4:return[4,u.json()];case 5:return[2,{value:{remoteConfig:r.sent(),lastFetch:new Date}}];case 6:return[3,9];case 7:return(g=r.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,9];case 8:return clearTimeout(l),[7];case 9:return s?i<e-1?[4,new Promise(function(e){return setTimeout(e,c.getJitterDelay(n))})]:[3,11]:[2,"break"];case 10:r.sent(),r.label=11;case 11:return[2]}})},o=this,a=0,u.label=1;case 1:return a<e?[5,s(a)]:[3,4];case 2:if("object"==typeof(l=u.sent()))return[2,l.value];if("break"===l)return[3,4];u.label=3;case 3:return a++,[3,1];case 4:return[2,i]}})})},e.prototype.getJitterDelay=function(e){return Math.floor(Math.random()*e)},e.prototype.getUrlParams=function(){var t=encodeURIComponent(this.apiKey),n=new URLSearchParams;return n.append("config_group",e.CONFIG_GROUP),"".concat(this.serverUrl,"/").concat(t,"?").concat(n.toString())},e.CONFIG_GROUP="browser",e}();!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(x||(x={}));var B,H="https://app.amplitude.com",z={US:H,EU:"https://app.eu.amplitude.com",STAGING:"https://apps.stag2.amplitude.com"};var K="__AMPLITUDE_MESSENGER_INSTANCE__",J="__AMPLITUDE_MESSENGER__",G=function(){function e(e){var t=(void 0===e?{}:e).origin,n=void 0===t?H:t;this[B]=!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,i,r;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===(r=null===(i=window.opener)||void 0===i?void 0:i.postMessage)||void 0===r||r.call(i,e,this.endpoint)},e.prototype.sendRequest=function(e,t,n){var i=this;void 0===n&&(n={timeout:15e3});var r="".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9)),s={id:r,action:e,args:t};return new Promise(function(t,o){i.requestCallbacks[r]={resolve:t,reject:o},i.notify(s),n.timeout>0&&setTimeout(function(){o(new Error("".concat(e," timed out (id: ").concat(r,")"))),delete i.requestCallbacks[r]},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,i,r,s;this.actionHandlers.has(e)&&(null===(s=null===(r=this.logger)||void 0===r?void 0:r.warn)||void 0===s||s.call(r,"Overwriting existing action handler for: ".concat(e))),this.actionHandlers.set(e,t);var a=this.pendingMessages.get(e);if(a){this.pendingMessages.delete(e);try{for(var l=o(a),c=l.next();!c.done;c=l.next()){t(c.value)}}catch(e){n={error:e}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}}},e.prototype.loadScriptOnce=function(e){return i(this,void 0,void 0,function(){var t,n,i;return r(this,function(r){switch(r.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 i;try{var r=document.createElement("script");r.type="text/javascript",r.async=!0,r.src=e,r.addEventListener("load",function(){t({status:!0})},{once:!0}),r.addEventListener("error",function(){n({status:!1,message:"Failed to load the script ".concat(e)})}),null===(i=document.head)||void 0===i||i.appendChild(r)}catch(e){n(e)}})}(e).then(function(){}),this.scriptLoadPromises.set(e,n),r.label=1;case 1:return r.trys.push([1,3,,4]),[4,n];case 2:return r.sent(),[3,4];case 3:throw i=r.sent(),this.scriptLoadPromises.delete(e),i;case 4:return[2]}})})},e.prototype.setup=function(e){var t,n,i=this,r=void 0===e?{}:e,s=r.logger,o=r.endpoint;s&&(this.logger=s),o&&this.endpoint===H&&(this.endpoint=o),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,r,s,o;if(null===(n=null===(t=i.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Message received: ",JSON.stringify(e)),i.endpoint===e.origin){var a=e.data,l=null==a?void 0:a.action;if(l)if("id"in a&&a.id)null===(s=null===(r=i.logger)||void 0===r?void 0:r.debug)||void 0===s||s.call(r,"Received Response to previous request: ",JSON.stringify(e)),i.handleResponse(a);else{if("ping"===l)return void i.notify({action:"pong"});var c=i.actionHandlers.get(l);if(c)c(a.data);else{var u=null!==(o=i.pendingMessages.get(l))&&void 0!==o?o:[];u.push(a.data),i.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=v();(null==e?void 0:e[J])===this&&delete e[J]},e}();function Q(e){var t,n=v(),i=null==n?void 0:n[J];if("object"==typeof(t=i)&&null!==t&&K in t&&!0===t[K])return i;var r=new G(e);return n&&(n[J]=r),r}B=K;var Z="__AMPLITUDE_BACKGROUND_CAPTURE__";const X="[Amplitude]",Y=`${X} Session Replay ID`,V=x.US,ee={enabled:!0},te=1e3,ne=`${X} Session Replay Debug`,ie="amp-mask";var re;!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"}(re||(re={}));class se{constructor(e){this.logger=e,this.log=this.getSafeMethod("log"),this.warn=this.getSafeMethod("warn"),this.error=this.getSafeMethod("error"),this.debug=this.getSafeMethod("debug")}getSafeMethod(e){var t;if(!this.logger)return()=>{};const n=this.logger[e];if("function"==typeof n){return(null!==(t=n.__rrweb_original__)&&void 0!==t?t:n).bind(this.logger)}return()=>{}}enable(e){this.logger.enable(e)}disable(){this.logger.disable()}}const oe="medium";const ae=(e,t,n)=>{switch(t){case"light":{if("input"!==e)return!0;const t=n?function(e){const t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?t.toLowerCase():null}(n):"";return!!t&&(!!["password","hidden","email","tel"].includes(t)||!!n.autocomplete.startsWith("cc-"))}case"medium":case"conservative":return!0;default:return ae(e,oe,n)}},le=(e,t)=>(n,i)=>((e,t={defaultMaskLevel:oe},n)=>{var i,r,s;if(n){if(n.closest("."+ie))return!0;const e=(null!==(i=t.maskSelector)&&void 0!==i?i:[]).some(e=>n.closest(e));if(e)return!0;if(n.closest(".amp-unmask"))return!1;const s=(null!==(r=t.unmaskSelector)&&void 0!==r?r:[]).some(e=>n.closest(e));if(s)return!1}return ae(e,null!==(s=t.defaultMaskLevel)&&void 0!==s?s:oe,n)})(e,t,i)?n.replace(/[^\s]/g,"*"):n,ce=(e,t)=>t||(e===x.STAGING?"https://api-sr.stag2.amplitude.com/sessions/v2/track":e===x.EU?"https://api-sr.eu.amplitude.com/sessions/v2/track":"https://api-sr.amplitude.com/sessions/v2/track"),ue=e=>{const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${t}$`)},de=(e,t)=>{for(const n of t){const t=ue(n.selector);if(t.test(e))return e.replace(t,n.replacement)}return e},ge=()=>i(void 0,void 0,void 0,function*(){try{const e=v();if(e){const{usage:t,quota:n,usageDetails:i}=yield e.navigator.storage.estimate(),r=t?Math.round(t/1024):0;return{totalStorageSize:r,percentOfQuota:t&&n?Math.round(1e3*(t/n+Number.EPSILON))/1e3:0,usageDetails:JSON.stringify(i)}}}catch(e){}return{totalStorageSize:0,percentOfQuota:0,usageDetails:""}}),he=e=>{const t=Object.assign({},e),{apiKey:n}=t;return t.apiKey=`****${n.substring(n.length-4)}`,t},ve=()=>({flushMaxRetries:2,logLevel:h.Warn,loggerProvider:new b,transportProvider:new j});class fe extends C{constructor(e,t){var n,i,r,s,o,a;const l=ve();if(super(Object.assign(Object.assign({transportProvider:l.transportProvider,loggerProvider:new se(t.loggerProvider||l.loggerProvider)},t),{apiKey:e})),this.flushMaxRetries=void 0!==t.flushMaxRetries&&t.flushMaxRetries<=l.flushMaxRetries?t.flushMaxRetries:l.flushMaxRetries,this.apiKey=e,this.sampleRate=t.sampleRate||0,this.serverZone=t.serverZone||V,this.configServerUrl=t.configServerUrl,this.trackServerUrl=t.trackServerUrl,this.shouldInlineStylesheet=t.shouldInlineStylesheet,this.version=t.version,this.performanceConfig=t.performanceConfig||ee,this.storeType=null!==(n=t.storeType)&&void 0!==n?n:"idb",this.applyBackgroundColorToBlockedElements=null!==(i=t.applyBackgroundColorToBlockedElements)&&void 0!==i&&i,this.enableUrlChangePolling=null!==(r=t.enableUrlChangePolling)&&void 0!==r&&r,this.urlChangePollingInterval=null!==(s=t.urlChangePollingInterval)&&void 0!==s?s:te,this.captureDocumentTitle=null!==(o=t.captureDocumentTitle)&&void 0!==o&&o,t.privacyConfig&&(this.privacyConfig=t.privacyConfig),t.interactionConfig&&(this.interactionConfig=t.interactionConfig,this.interactionConfig.ugcFilterRules&&(e=>{if(!e.every(e=>"string"==typeof e.selector&&"string"==typeof e.replacement))throw new Error("ugcFilterRules must be an array of objects with selector and replacement properties");if(!e.every(e=>{return"string"==typeof(t=e.selector)&&""!==t.trim()&&!!/^\/|^https?:\/\/[^\s]+$/.test(t);var t}))throw new Error("ugcFilterRules must be an array of objects with valid globs")})(this.interactionConfig.ugcFilterRules)),t.debugMode&&(this.debugMode=t.debugMode),void 0!==t.useWebWorker)this.useWebWorker=t.useWebWorker;else{const e=t;void 0!==(null===(a=e.experimental)||void 0===a?void 0:a.useWebWorker)&&(this.useWebWorker=e.experimental.useWebWorker)}t.omitElementTags&&(this.omitElementTags=t.omitElementTags)}}var pe=(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))(pe||{}),me=(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))(me||{});class ye{constructor(e,t){this.localConfig=t,this.remoteConfigClient=e}generateJoinedConfig(){return i(this,void 0,void 0,function*(){var e,t,n;const i=Object.assign({},this.localConfig);let r;i.optOut=this.localConfig.optOut,i.captureEnabled=!0;try{yield new Promise((e,t)=>{this.remoteConfigClient.subscribe("configs.sessionReplay","all",(n,s)=>{var o;if(this.localConfig.loggerProvider.debug(`Session Replay remote configuration received from ${s}:`,JSON.stringify(n,null,2)),!n)return void t(new Error("No remote config received"));const a=n,l=a.sr_sampling_config,c=a.sr_privacy_config,u=a.sr_targeting_config,d=null===(o=i.interactionConfig)||void 0===o?void 0:o.ugcFilterRules;i.interactionConfig=a.sr_interaction_config,i.interactionConfig&&d&&(i.interactionConfig.ugcFilterRules=d),i.loggingConfig=a.sr_logging_config,(l||c||u)&&(r={},l&&(r.sr_sampling_config=l),c&&(r.sr_privacy_config=c),u&&(r.sr_targeting_config=u)),e()})})}catch(e){return this.localConfig.loggerProvider.error("Failed to generate joined config: ",e),i.captureEnabled=!1,{localConfig:this.localConfig,joinedConfig:i,remoteConfig:void 0}}if(!r)return{localConfig:this.localConfig,joinedConfig:i,remoteConfig:r};const{sr_sampling_config:s,sr_privacy_config:o,sr_targeting_config:a}=r;if(s&&Object.keys(s).length>0?(Object.prototype.hasOwnProperty.call(s,"capture_enabled")?i.captureEnabled=s.capture_enabled:i.captureEnabled=!1,Object.prototype.hasOwnProperty.call(s,"sample_rate")&&(i.sampleRate=s.sample_rate)):(i.captureEnabled=!0,this.localConfig.loggerProvider.debug("Remote config successfully fetched, but no values set for project, Session Replay capture enabled.")),o){const r=null!==(e=i.privacyConfig)&&void 0!==e?e:{},s={defaultMaskLevel:null!==(n=null!==(t=o.defaultMaskLevel)&&void 0!==t?t:r.defaultMaskLevel)&&void 0!==n?n:"medium",blockSelector:[],maskSelector:[],unmaskSelector:[]},a=e=>{var t,n,i;const r={};"string"==typeof e.blockSelector&&(e.blockSelector=[e.blockSelector]);for(const n of null!==(t=e.blockSelector)&&void 0!==t?t:[])r[n]="block";for(const t of null!==(n=e.maskSelector)&&void 0!==n?n:[])r[t]="mask";for(const t of null!==(i=e.unmaskSelector)&&void 0!==i?i:[])r[t]="unmask";return r},l=Object.assign(Object.assign({},a(r)),a(o));for(const[e,t]of Object.entries(l))"mask"===t?s.maskSelector.push(e):"block"===t?s.blockSelector.push(e):"unmask"===t&&s.unmaskSelector.push(e);i.privacyConfig=((e,t)=>{const n=document.createDocumentFragment(),i=(e=[])=>{if("string"==typeof e&&(e=[e]),e=e.filter(e=>{try{n.querySelector(e)}catch(n){return t.warn(`[session-replay-browser] omitting selector "${e}" because it is invalid`),!1}return!0}),0!==e.length)return e};return e.blockSelector=i(e.blockSelector),e.maskSelector=i(e.maskSelector),e.unmaskSelector=i(e.unmaskSelector),e})(s,this.localConfig.loggerProvider)}return a&&Object.keys(a).length>0&&(i.targetingConfig=a),this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:he(i)},null,2)),{localConfig:this.localConfig,joinedConfig:i,remoteConfig:r}})}}var be=Uint8Array,Se=Uint16Array,Ce=Uint32Array,we=new be([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ie=new be([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Pe=new be([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ke=function(e,t){for(var n=new Se(31),i=0;i<31;++i)n[i]=t+=1<<e[i-1];var r=new Ce(n[30]);for(i=1;i<30;++i)for(var s=n[i];s<n[i+1];++s)r[s]=s-n[i]<<5|i;return[n,r]},Ee=ke(we,2),Re=Ee[0],Te=Ee[1];Re[28]=258,Te[258]=28;for(var Oe=ke(Ie,0)[1],_e=new Se(32768),Me=0;Me<32768;++Me){var xe=(43690&Me)>>>1|(21845&Me)<<1;xe=(61680&(xe=(52428&xe)>>>2|(13107&xe)<<2))>>>4|(3855&xe)<<4,_e[Me]=((65280&xe)>>>8|(255&xe)<<8)>>>1}var Le=function(e,t,n){for(var i=e.length,r=0,s=new Se(t);r<i;++r)++s[e[r]-1];var o,a=new Se(t);for(r=0;r<t;++r)a[r]=a[r-1]+s[r-1]<<1;if(n){o=new Se(1<<t);var l=15-t;for(r=0;r<i;++r)if(e[r])for(var c=r<<4|e[r],u=t-e[r],d=a[e[r]-1]++<<u,g=d|(1<<u)-1;d<=g;++d)o[_e[d]>>>l]=c}else for(o=new Se(i),r=0;r<i;++r)o[r]=_e[a[e[r]-1]++]>>>15-e[r];return o},De=new be(288);for(Me=0;Me<144;++Me)De[Me]=8;for(Me=144;Me<256;++Me)De[Me]=9;for(Me=256;Me<280;++Me)De[Me]=7;for(Me=280;Me<288;++Me)De[Me]=8;var qe=new be(32);for(Me=0;Me<32;++Me)qe[Me]=5;var Ne=Le(De,9,0),Ue=Le(qe,5,0),je=function(e){return(e/8|0)+(7&e&&1)},Fe=function(e,t,n){(null==n||n>e.length)&&(n=e.length);var i=new(e instanceof Se?Se:e instanceof Ce?Ce:be)(n-t);return i.set(e.subarray(t,n)),i},$e=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>>8},Ae=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>>8,e[i+2]|=n>>>16},We=function(e,t){for(var n=[],i=0;i<e.length;++i)e[i]&&n.push({s:i,f:e[i]});var r=n.length,s=n.slice();if(!r)return[new be(0),0];if(1==r){var o=new be(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort(function(e,t){return e.f-t.f}),n.push({s:-1,f:25001});var a=n[0],l=n[1],c=0,u=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};u!=r-1;)a=n[n[c].f<n[d].f?c++:d++],l=n[c!=u&&n[c].f<n[d].f?c++:d++],n[u++]={s:-1,f:a.f+l.f,l:a,r:l};var g=s[0].s;for(i=1;i<r;++i)s[i].s>g&&(g=s[i].s);var h=new Se(g+1),v=Be(n[u-1],h,0);if(v>t){i=0;var f=0,p=v-t,m=1<<p;for(s.sort(function(e,t){return h[t.s]-h[e.s]||e.f-t.f});i<r;++i){var y=s[i].s;if(!(h[y]>t))break;f+=m-(1<<v-h[y]),h[y]=t}for(f>>>=p;f>0;){var b=s[i].s;h[b]<t?f-=1<<t-h[b]++-1:++i}for(;i>=0&&f;--i){var S=s[i].s;h[S]==t&&(--h[S],++f)}v=t}return[new be(h),v]},Be=function(e,t,n){return-1==e.s?Math.max(Be(e.l,t,n+1),Be(e.r,t,n+1)):t[e.s]=n},He=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new Se(++t),i=0,r=e[0],s=1,o=function(e){n[i++]=e},a=1;a<=t;++a)if(e[a]==r&&a!=t)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=e[a]}return[n.subarray(0,i),t]},ze=function(e,t){for(var n=0,i=0;i<t.length;++i)n+=e[i]*t[i];return n},Ke=function(e,t,n){var i=n.length,r=je(t+2);e[r]=255&i,e[r+1]=i>>>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var s=0;s<i;++s)e[r+s+4]=n[s];return 8*(r+4+i)},Je=function(e,t,n,i,r,s,o,a,l,c,u){$e(t,u++,n),++r[256];for(var d=We(r,15),g=d[0],h=d[1],v=We(s,15),f=v[0],p=v[1],m=He(g),y=m[0],b=m[1],S=He(f),C=S[0],w=S[1],I=new Se(19),P=0;P<y.length;++P)I[31&y[P]]++;for(P=0;P<C.length;++P)I[31&C[P]]++;for(var k=We(I,7),E=k[0],R=k[1],T=19;T>4&&!E[Pe[T-1]];--T);var O,_,M,x,L=c+5<<3,D=ze(r,De)+ze(s,qe)+o,q=ze(r,g)+ze(s,f)+o+14+3*T+ze(I,E)+(2*I[16]+3*I[17]+7*I[18]);if(L<=D&&L<=q)return Ke(t,u,e.subarray(l,l+c));if($e(t,u,1+(q<D)),u+=2,q<D){O=Le(g,h,0),_=g,M=Le(f,p,0),x=f;var N=Le(E,R,0);$e(t,u,b-257),$e(t,u+5,w-1),$e(t,u+10,T-4),u+=14;for(P=0;P<T;++P)$e(t,u+3*P,E[Pe[P]]);u+=3*T;for(var U=[y,C],j=0;j<2;++j){var F=U[j];for(P=0;P<F.length;++P){var $=31&F[P];$e(t,u,N[$]),u+=E[$],$>15&&($e(t,u,F[P]>>>5&127),u+=F[P]>>>12)}}}else O=Ne,_=De,M=Ue,x=qe;for(P=0;P<a;++P)if(i[P]>255){$=i[P]>>>18&31;Ae(t,u,O[$+257]),u+=_[$+257],$>7&&($e(t,u,i[P]>>>23&31),u+=we[$]);var A=31&i[P];Ae(t,u,M[A]),u+=x[A],A>3&&(Ae(t,u,i[P]>>>5&8191),u+=Ie[A])}else Ae(t,u,O[i[P]]),u+=_[i[P]];return Ae(t,u,O[256]),u+_[256]},Ge=new Ce([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Qe=function(e,t,n,i,r){return function(e,t,n,i,r,s){var o=e.length,a=new be(i+o+5*(1+Math.floor(o/7e3))+r),l=a.subarray(i,a.length-r),c=0;if(!t||o<8)for(var u=0;u<=o;u+=65535){var d=u+65535;d<o?c=Ke(l,c,e.subarray(u,d)):(l[u]=s,c=Ke(l,c,e.subarray(u,o)))}else{for(var g=Ge[t-1],h=g>>>13,v=8191&g,f=(1<<n)-1,p=new Se(32768),m=new Se(f+1),y=Math.ceil(n/3),b=2*y,S=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<b)&f},C=new Ce(25e3),w=new Se(288),I=new Se(32),P=0,k=0,E=(u=0,0),R=0,T=0;u<o;++u){var O=S(u),_=32767&u,M=m[O];if(p[_]=M,m[O]=_,R<=u){var x=o-u;if((P>7e3||E>24576)&&x>423){c=Je(e,l,0,C,w,I,k,E,T,u-T,c),E=P=k=0,T=u;for(var L=0;L<286;++L)w[L]=0;for(L=0;L<30;++L)I[L]=0}var D=2,q=0,N=v,U=_-M&32767;if(x>2&&O==S(u-U))for(var j=Math.min(h,x)-1,F=Math.min(32767,u),$=Math.min(258,x);U<=F&&--N&&_!=M;){if(e[u+D]==e[u+D-U]){for(var A=0;A<$&&e[u+A]==e[u+A-U];++A);if(A>D){if(D=A,q=U,A>j)break;var W=Math.min(U,A-2),B=0;for(L=0;L<W;++L){var H=u-U+L+32768&32767,z=H-p[H]+32768&32767;z>B&&(B=z,M=H)}}}U+=(_=M)-(M=p[_])+32768&32767}if(q){C[E++]=268435456|Te[D]<<18|Oe[q];var K=31&Te[D],J=31&Oe[q];k+=we[K]+Ie[J],++w[257+K],++I[J],R=u+D,++P}else C[E++]=e[u],++w[e[u]]}}c=Je(e,l,s,C,w,I,k,E,T,u-T,c)}return Fe(a,0,i+je(c)+r)}(e,null==t.level?6:t.level,null==t.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,n,i,!0)};function Ze(e,t){void 0===t&&(t={});var n=function(){var e=1,t=0;return{p:function(n){for(var i=e,r=t,s=n.length,o=0;o!=s;){for(var a=Math.min(o+5552,s);o<a;++o)r+=i+=n[o];i%=65521,r%=65521}e=i,t=r},d:function(){return(e>>>8<<16|(255&t)<<8|t>>>8)+2*((255&e)<<23)}}}();n.p(e);var i,r,s,o=Qe(e,t,2,4);return i=o,r=t.level,s=0==r?0:r<6?1:9==r?3:2,i[0]=120,i[1]=s<<6|(s?32-2*s:1),function(e,t,n){for(;n;++t)e[t]=n,n>>>=8}(o,o.length-4,n.d()),o}const Xe=e=>{const t={...e,v:"v1"};return function(e,t){var n="";if(!t&&"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);for(var i=0;i<e.length;){var r=e[i++];r<128||t?n+=String.fromCharCode(r):r<224?n+=String.fromCharCode((31&r)<<6|63&e[i++]):r<240?n+=String.fromCharCode((15&r)<<12|(63&e[i++])<<6|63&e[i++]):(r=((15&r)<<18|(63&e[i++])<<12|(63&e[i++])<<6|63&e[i++])-65536,n+=String.fromCharCode(55296|r>>10,56320|1023&r))}return n}(Ze(function(e,t){var n=e.length;if(!t&&"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var i=new be(e.length+(e.length>>>1)),r=0,s=function(e){i[r++]=e},o=0;o<n;++o){if(r+5>i.length){var a=new be(r+8+(n-o<<1));a.set(i),i=a}var l=e.charCodeAt(o);l<128||t?s(l):l<2048?(s(192|l>>>6),s(128|63&l)):l>55295&&l<57344?(s(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++o))>>>18),s(128|l>>>12&63),s(128|l>>>6&63),s(128|63&l)):(s(224|l>>>12),s(128|l>>>6&63),s(128|63&l))}return Fe(i,0,r)}(JSON.stringify(t))),!0)};class Ye{constructor(e,t,n,i){var r;this.taskQueue=[],this.isProcessing=!1,this.compressEvent=e=>{const t=Xe(e);return JSON.stringify(t)},this.addCompressedEventToManager=(e,t)=>{this.eventsManager&&this.deviceId&&this.eventsManager.addEvent({event:{type:"replay",data:e},sessionId:t,deviceId:this.deviceId})},this.addCompressedEvent=(e,t)=>{if(this.worker)try{this.worker.postMessage({event:e,sessionId:t})}catch(n){"DataCloneError"===n.name?this.worker.postMessage(JSON.stringify({event:e,sessionId:t})):this.config.loggerProvider.warn("Unexpected error while posting message to worker:",n)}else{const n=this.compressEvent(e);this.addCompressedEventToManager(n,t)}},this.terminate=()=>{var e;null===(e=this.worker)||void 0===e||e.terminate()};const s=v();if(this.canUseIdleCallback=s&&"requestIdleCallback"in s,this.eventsManager=e,this.config=t,this.deviceId=n,this.timeout=(null===(r=t.performanceConfig)||void 0===r?void 0:r.timeout)||2e3,i){t.loggerProvider.log("Enabling web worker for compression");try{const e=new Blob([i],{type:"application/javascript"}),n=URL.createObjectURL(e),r=new Worker(n);r.onerror=e=>{e.preventDefault(),t.loggerProvider.error("Worker failed, falling back to non-worker compression:",e),r.terminate(),this.worker=void 0},r.onmessage=e=>{const{compressedEvent:t,sessionId:n}=e.data;this.addCompressedEventToManager(t,n)},this.worker=r}catch(e){t.loggerProvider.error("Failed to create worker, falling back to non-worker compression:",e)}}}scheduleIdleProcessing(){this.isProcessing||(this.isProcessing=!0,requestIdleCallback(e=>{this.processQueue(e)},{timeout:this.timeout}))}enqueueEvent(e,t){var n;this.canUseIdleCallback&&(null===(n=this.config.performanceConfig)||void 0===n?void 0:n.enabled)?(this.config.loggerProvider.debug("Enqueuing event for processing during idle time."),this.taskQueue.push({event:e,sessionId:t}),this.scheduleIdleProcessing()):(this.config.loggerProvider.debug("Processing event without idle callback."),this.addCompressedEvent(e,t))}processQueue(e){for(;this.taskQueue.length>0&&(e.timeRemaining()>0||e.didTimeout);){const e=this.taskQueue.shift();if(e){const{event:t,sessionId:n}=e;this.addCompressedEvent(t,n)}}this.taskQueue.length>0?requestIdleCallback(e=>{this.processQueue(e)},{timeout:this.timeout}):this.isProcessing=!1}}const Ve="Session replay event batch rejected due to exceeded retry count",et="Failed to store session replay events in IndexedDB",tt="1.32.1";class nt{constructor({trackServerUrl:e,loggerProvider:t,payloadBatcher:n}){this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.loggerProvider=t,this.payloadBatcher=n||(e=>e),this.trackServerUrl=e}sendEventsList(e){this.addToQueue(Object.assign(Object.assign({},e),{attempts:0,timeout:0}))}addToQueue(...e){e.filter(e=>e.attempts<(e.flushMaxRetries||0)?(e.attempts+=1,!0):(this.completeRequest({context:e,err:Ve}),!1)).forEach(e=>{this.queue=this.queue.concat(e),this.schedule(0)})}schedule(e){this.scheduled||(this.scheduled=setTimeout(()=>{this.flush(!0).then(()=>{this.queue.length>0&&this.schedule(e)})},e))}flush(){return i(this,arguments,void 0,function*(e=!1){const t=this.queue;this.queue=[],this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null);for(const n of t)yield this.send(n,e)})}send(e){return i(this,arguments,void 0,function*(e,t=!0){var n,i;const r=e.apiKey;if(!r)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing api key"});const s=e.deviceId;if(!s)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing device ID"});const o=(()=>{const e=v();return(null==e?void 0:e.location)?e.location.href:""})(),a=tt,l=e.sampleRate,c=new URLSearchParams({device_id:s,session_id:`${e.sessionId}`,type:`${e.type}`}),u=`${(null===(n=e.version)||void 0===n?void 0:n.type)||"standalone"}/${(null===(i=e.version)||void 0===i?void 0:i.version)||a}`,d=this.payloadBatcher({version:1,events:e.events});if(0!==d.events.length)try{const n={headers:{"Content-Type":"application/json",Accept:"*/*",Authorization:`Bearer ${r}`,"X-Client-Version":a,"X-Client-Library":u,"X-Client-Url":o.substring(0,1e3),"X-Client-Sample-Rate":`${l}`},body:JSON.stringify(d),method:"POST"},i=`${ce(e.serverZone,this.trackServerUrl)}?${c.toString()}`,s=yield fetch(i,n);if(null===s)return void this.completeRequest({context:e,err:"Unexpected error occurred"});if(t)yield this.handleReponse(s.status,e);else{let t="";try{t=JSON.stringify(s.body,null,2)}catch(e){}this.completeRequest({context:e,success:`${s.status}: ${t}`})}}catch(t){this.completeRequest({context:e,err:t})}else this.completeRequest({context:e})})}handleReponse(e,t){return i(this,void 0,void 0,function*(){switch((new U).buildStatus(e)){case u.Success:this.handleSuccessResponse(t);break;case u.Failed:yield this.handleOtherResponse(t);break;default:this.completeRequest({context:t,err:"Network error occurred, event batch rejected"})}})}handleSuccessResponse(e){const t=Math.round(new Blob(e.events).size/1024);this.completeRequest({context:e,success:`Session replay event batch tracked successfully for session id ${e.sessionId}, size of events: ${t} KB`})}handleOtherResponse(e){return i(this,void 0,void 0,function*(){const t=e.attempts*this.retryTimeout;e.attempts++,e.attempts>(e.flushMaxRetries||0)?this.completeRequest({context:e,err:Ve}):(yield new Promise(e=>setTimeout(e,t)),yield this.send(e,!0))})}completeRequest({context:e,err:t,success:n}){e.onComplete(),t?this.loggerProvider.warn(t):n&&this.loggerProvider.log(n)}}class it{get timeAtLastSplit(){return this._timeAtLastSplit}constructor(e){var t,n,i;this.minInterval=500,this.maxInterval=1e4,this.maxPersistedEventsSize=1e6,this.interval=this.minInterval,this._timeAtLastSplit=Date.now(),this.shouldSplitEventsList=(e,t)=>{const n=this.getStringSize(t);return this.getEventsArraySize(e)+n>=this.maxPersistedEventsSize||!!(Date.now()-this.timeAtLastSplit>this.interval&&e.length)&&(this.interval=Math.min(this.maxInterval,this.interval+this.minInterval),this._timeAtLastSplit=Date.now(),!0)},this.loggerProvider=e.loggerProvider,this.minInterval=null!==(t=e.minInterval)&&void 0!==t?t:this.minInterval,this.maxInterval=null!==(n=e.maxInterval)&&void 0!==n?n:this.maxInterval,this.maxPersistedEventsSize=null!==(i=e.maxPersistedEventsSize)&&void 0!==i?i:this.maxPersistedEventsSize}getStringSize(e){return e.length}getEventsArraySize(e){let t=0;for(const n of e)t+=this.getStringSize(n);return t+(2+Math.max(0,e.length-1)+2*e.length)}}const rt=(e,t,n)=>{var i;"object"==typeof(i=n)&&null!==i&&"AbortError"===i.name?e.debug(t):e.warn(t)},st="sessionCurrentSequence",ot="sequencesToSend",at=e=>{let t,n;return e.objectStoreNames.contains(st)||(n=e.createObjectStore(st,{keyPath:"sessionId"})),e.objectStoreNames.contains(ot)||(t=e.createObjectStore(ot,{keyPath:"sequenceId",autoIncrement:!0}),t.createIndex("sessionId","sessionId")),{sequencesStore:t,currentSequenceStore:n}};class lt extends it{constructor(e){super(e),this.getSequencesToSend=()=>i(this,void 0,void 0,function*(){try{const e=[];let t=yield this.db.transaction("sequencesToSend").store.openCursor();for(;t;){const{sessionId:n,events:i}=t.value;e.push({events:i,sequenceId:t.key,sessionId:n}),t=yield t.continue()}return e}catch(e){rt(this.loggerProvider,`${et}: ${e}`,e)}}),this.storeCurrentSequence=e=>i(this,void 0,void 0,function*(){try{const t=yield this.db.get(st,e);if(!t)return;const n=yield this.db.put(ot,{sessionId:e,events:t.events});return yield this.db.put(st,{sessionId:e,events:[]}),Object.assign(Object.assign({},t),{sessionId:e,sequenceId:n})}catch(e){rt(this.loggerProvider,`${et}: ${e}`,e)}}),this.addEventToCurrentSequence=(e,t)=>i(this,void 0,void 0,function*(){try{const n=this.db.transaction(st,"readwrite"),i=yield n.store.get(e);if(!i)return void(yield n.store.put({sessionId:e,events:[t]}));let r;if(this.shouldSplitEventsList(i.events,t))r=i.events,yield n.store.put({sessionId:e,events:[t]});else{const r=i.events.concat(t);yield n.store.put({sessionId:e,events:r})}if(yield n.done,!r)return;const s=yield this.storeSendingEvents(e,r);if(!s)return;return{events:r,sessionId:e,sequenceId:s}}catch(e){rt(this.loggerProvider,`${et}: ${e}`,e)}}),this.storeSendingEvents=(e,t)=>i(this,void 0,void 0,function*(){try{return yield this.db.put(ot,{sessionId:e,events:t})}catch(e){rt(this.loggerProvider,`${et}: ${e}`,e)}}),this.cleanUpSessionEventsStore=(e,t)=>i(this,void 0,void 0,function*(){if(t)try{yield this.db.delete(ot,t)}catch(e){rt(this.loggerProvider,`${et}: ${e}`,e)}}),this.db=e.db}static new(e,t){return i(this,void 0,void 0,function*(){try{const n="replay"===e?"":`_${e}`,r=`${t.apiKey.substring(0,10)}_amp_session_replay_events${n}`,s=yield(e=>i(void 0,void 0,void 0,function*(){return yield a(e,1,{upgrade:at})}))(r);return new lt(Object.assign(Object.assign({},t),{db:s}))}catch(e){rt(t.loggerProvider,`${et}: ${e}`,e)}})}getCurrentSequenceEvents(e){return i(this,void 0,void 0,function*(){if(e){const t=yield this.db.get("sessionCurrentSequence",e);if(!t)return;return[t]}const t=[];for(const e of yield this.db.getAll("sessionCurrentSequence"))t.push(e);return t})}}class ct extends it{constructor(){super(...arguments),this.finalizedSequences={},this.sequences={},this.sequenceId=0}resetCurrentSequence(e){this.sequences[e]=[]}addSequence(e){const t=this.sequenceId++,n=[...this.sequences[e]];return this.finalizedSequences[t]={sessionId:e,events:n},this.resetCurrentSequence(e),{sequenceId:t,events:n,sessionId:e}}getSequencesToSend(){return i(this,void 0,void 0,function*(){return Object.entries(this.finalizedSequences).map(([e,{sessionId:t,events:n}])=>({sequenceId:Number(e),sessionId:t,events:n}))})}storeCurrentSequence(e){return i(this,void 0,void 0,function*(){if(this.sequences[e])return this.addSequence(e)})}addEventToCurrentSequence(e,t){return i(this,void 0,void 0,function*(){let n;return this.sequences[e]||this.resetCurrentSequence(e),this.shouldSplitEventsList(this.sequences[e],t)&&(n=this.addSequence(e)),this.sequences[e].push(t),n})}storeSendingEvents(e,t){return i(this,void 0,void 0,function*(){return this.finalizedSequences[this.sequenceId]={sessionId:e,events:t},this.sequenceId++})}cleanUpSessionEventsStore(e,t){return i(this,void 0,void 0,function*(){void 0!==t&&delete this.finalizedSequences[t]})}}const ut=e=>i(void 0,[e],void 0,function*({config:e,minInterval:t,maxInterval:n,type:r,payloadBatcher:s,storeType:o}){const a=new nt(Object.assign(Object.assign({},e),{loggerProvider:e.loggerProvider,payloadBatcher:s})),l=()=>new ct({loggerProvider:e.loggerProvider,maxInterval:n,minInterval:t}),c="idb"===o?yield i(void 0,void 0,void 0,function*(){const i=yield lt.new(r,{loggerProvider:e.loggerProvider,minInterval:t,maxInterval:n,apiKey:e.apiKey});return i||(e.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),l())}):l(),u=({events:t,sessionId:n,deviceId:s,sequenceId:o})=>{e.debugMode&&ge().then(({totalStorageSize:t,percentOfQuota:n,usageDetails:i})=>{e.loggerProvider.debug(`Total storage size: ${t} KB, percentage of quota: ${n}%, usage details: ${i}`)}).catch(()=>{}),a.sendEventsList({events:t,sessionId:n,flushMaxRetries:e.flushMaxRetries,apiKey:e.apiKey,deviceId:s,sampleRate:e.sampleRate,serverZone:e.serverZone,version:e.version,type:r,onComplete:()=>i(void 0,void 0,void 0,function*(){yield c.cleanUpSessionEventsStore(n,o)})})};return{sendCurrentSequenceEvents:({sessionId:t,deviceId:n})=>{c.storeCurrentSequence(t).then(e=>{e&&u({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n})}).catch(t=>{e.loggerProvider.warn("Failed to get current sequence of session replay events for session:",t)})},addEvent:({event:t,sessionId:n,deviceId:i})=>{c.addEventToCurrentSequence(n,t.data).then(e=>e&&u({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:i})).catch(t=>{e.loggerProvider.warn("Failed to add event to session replay capture:",t)})},sendStoredEvents:e=>i(void 0,[e],void 0,function*({deviceId:e}){const t=yield c.getSequencesToSend();t&&t.forEach(t=>{u({sequenceId:t.sequenceId,events:t.events,sessionId:t.sessionId,deviceId:e})})}),flush:function(){return i(this,arguments,void 0,function*(e=!1){return a.flush(e)})}}});class dt{constructor(...e){const t=new Map;e.forEach(e=>{t.set(e.name,e.manager)}),this.managers=t}sendStoredEvents(e){return i(this,void 0,void 0,function*(){const t=[];this.managers.forEach(n=>{t.push(n.sendStoredEvents(e))}),yield Promise.all(t)})}addEvent({sessionId:e,event:t,deviceId:n}){var i;null===(i=this.managers.get(t.type))||void 0===i||i.addEvent({sessionId:e,event:t,deviceId:n})}sendCurrentSequenceEvents({sessionId:e,deviceId:t}){this.managers.forEach(n=>{n.sendCurrentSequenceEvents({sessionId:e,deviceId:t})})}flush(e){return i(this,void 0,void 0,function*(){const t=[];this.managers.forEach(n=>{t.push(n.flush(e))}),yield Promise.all(t)})}}let gt,ht,vt;function ft(e,t){if(vt=new Date,e.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if("html"===e.tagName.toLowerCase())return"html";const n={root:document.body,idName:e=>!0,className:e=>!0,tagName:e=>!0,attr:(e,t)=>!1,seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};gt=Object.assign(Object.assign({},n),t),ht=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(gt.root,n);let i=pt(e,"all",()=>pt(e,"two",()=>pt(e,"one",()=>pt(e,"none"))));if(i){const t=xt(Lt(i,e));return t.length>0&&(i=t[0]),yt(i)}throw new Error("Selector was not found.")}function pt(e,t,n){let i=null,r=[],s=e,o=0;for(;s;){const e=(new Date).getTime()-vt.getTime();if(void 0!==gt.timeoutMs&&e>gt.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${e}ms`);let a=Ot(Ct(s))||Ot(...wt(s))||Ot(...It(s))||Ot(Pt(s))||[kt()];const l=Et(s);if("all"==t)l&&(a=a.concat(a.filter(Tt).map(e=>Rt(e,l))));else if("two"==t)a=a.slice(0,1),l&&(a=a.concat(a.filter(Tt).map(e=>Rt(e,l))));else if("one"==t){const[e]=a=a.slice(0,1);l&&Tt(e)&&(a=[Rt(e,l)])}else"none"==t&&(a=[kt()],l&&(a=[Rt(a[0],l)]));for(let e of a)e.level=o;if(r.push(a),r.length>=gt.seedMinLength&&(i=mt(r,n),i))break;s=s.parentElement,o++}return i||(i=mt(r,n)),!i&&n?n():i}function mt(e,t){const n=xt(Mt(e));if(n.length>gt.threshold)return t?t():null;for(let e of n)if(St(e))return e;return null}function yt(e){let t=e[0],n=t.name;for(let i=1;i<e.length;i++){const r=e[i].level||0;n=t.level===r-1?`${e[i].name} > ${n}`:`${e[i].name} ${n}`,t=e[i]}return n}function bt(e){return e.map(e=>e.penalty).reduce((e,t)=>e+t,0)}function St(e){const t=yt(e);switch(ht.querySelectorAll(t).length){case 0:throw new Error(`Can't select any node with this selector: ${t}`);case 1:return!0;default:return!1}}function Ct(e){const t=e.getAttribute("id");return t&&gt.idName(t)?{name:"#"+CSS.escape(t),penalty:0}:null}function wt(e){const t=Array.from(e.attributes).filter(e=>gt.attr(e.name,e.value));return t.map(e=>({name:`[${CSS.escape(e.name)}="${CSS.escape(e.value)}"]`,penalty:.5}))}function It(e){return Array.from(e.classList).filter(gt.className).map(e=>({name:"."+CSS.escape(e),penalty:1}))}function Pt(e){const t=e.tagName.toLowerCase();return gt.tagName(t)?{name:t,penalty:2}:null}function kt(){return{name:"*",penalty:3}}function Et(e){const t=e.parentNode;if(!t)return null;let n=t.firstChild;if(!n)return null;let i=0;for(;n&&(n.nodeType===Node.ELEMENT_NODE&&i++,n!==e);)n=n.nextSibling;return i}function Rt(e,t){return{name:e.name+`:nth-child(${t})`,penalty:e.penalty+1}}function Tt(e){return"html"!==e.name&&!e.name.startsWith("#")}function Ot(...e){const t=e.filter(_t);return t.length>0?t:null}function _t(e){return null!=e}function*Mt(e,t=[]){if(e.length>0)for(let n of e[0])yield*Mt(e.slice(1,e.length),t.concat(n));else yield t}function xt(e){return[...e].sort((e,t)=>bt(e)-bt(t))}function*Lt(e,t,n={counter:0,visited:new Map}){if(e.length>2&&e.length>gt.optimizedMinLength)for(let i=1;i<e.length-1;i++){if(n.counter>gt.maxNumberOfTries)return;n.counter+=1;const r=[...e];r.splice(i,1);const s=yt(r);if(n.visited.has(s))return;St(r)&&Dt(r,t)&&(yield r,n.visited.set(s,!0),yield*Lt(r,t,n))}}function Dt(e,t){return ht.querySelector(yt(e))===t}const qt=({version:e,events:t})=>{const n=[];return t.forEach(e=>{const t=JSON.parse(e);t.count=1,"click"===t.type&&n.push(t)}),{version:e,events:n}},Nt=({version:e,events:t})=>{const n=[];t.forEach(e=>{const t=JSON.parse(e);"click"===t.type&&n.push(t)});const i=n.reduce((e,t)=>{const{x:n,y:i,selector:r,timestamp:s}=t,o=s-s%36e5,a=`${n}:${i}:${null!=r?r:""}:${o}`;return e[a]?e[a].count+=1:e[a]=Object.assign(Object.assign({},t),{timestamp:o,count:1}),e},{});return{version:e,events:Object.values(i)}};class Ut{constructor(e,t){this.createHook=({eventsManager:e,sessionId:t,deviceIdFn:n,mirror:i,ugcFilterRules:r,performanceOptions:s})=>o=>{if(o.type!==me.Click)return;const a=v();if(!a)return;const{location:l,innerHeight:c,innerWidth:u}=a;if(!l)return;const{x:d,y:g}=o;if(void 0===d||void 0===g)return;const h=i.getNode(o.id);let f;if(h)try{f=ft(h,s)}catch(e){this.logger.debug("error resolving selector from finder")}const p=de(l.href,r),m={x:d+this.scrollWatcher.currentScrollX,y:g+this.scrollWatcher.currentScrollY,selector:f,viewportHeight:c,viewportWidth:u,pageUrl:p,timestamp:Date.now(),type:"click"},y=n();y&&e.addEvent({sessionId:t,event:{type:"interaction",data:JSON.stringify(m)},deviceId:y})},this.logger=e,this.scrollWatcher=t}}function jt(){const e=v();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||0}function Ft(){const e=v();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||0}class $t{constructor(e,t){const n=v();n&&n.navigator&&"function"==typeof n.navigator.sendBeacon?this.sendBeacon=(e,t)=>{try{if(n.navigator.sendBeacon(e,JSON.stringify(t)))return!0}catch(e){}return!1}:this.sendBeacon=()=>!1,this.sendXhr=(e,t)=>{const n=new XMLHttpRequest;return n.open("POST",e,!0),n.setRequestHeader("Accept","*/*"),n.send(JSON.stringify(t)),!0},this.basePageUrl=ce(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e}send(e,t){const{sessionId:n,type:i}=this.context,r=new URLSearchParams({device_id:e,session_id:String(n),type:String(i),api_key:this.apiKey}),s=`${this.basePageUrl}?${r.toString()}`;this.sendBeacon(s,t)||this.sendXhr(s,t)}}class At{static default(e,t){return new At(new $t(e,t),t)}constructor(e,t){this.timestamp=Date.now(),this.hook=e=>{this.update(e)},this.send=e=>t=>{var n,i;const r=e(),s=v();s&&r&&this.transport.send(r,{version:1,events:[{maxScrollX:this._maxScrollX,maxScrollY:this._maxScrollY,maxScrollWidth:this._maxScrollWidth,maxScrollHeight:this._maxScrollHeight,viewportHeight:jt(),viewportWidth:Ft(),pageUrl:de(s.location.href,null!==(i=null===(n=this.config.interactionConfig)||void 0===n?void 0:n.ugcFilterRules)&&void 0!==i?i:[]),timestamp:this.timestamp,type:"scroll"}]})},this._maxScrollX=0,this._maxScrollY=0,this._currentScrollX=0,this._currentScrollY=0,this._maxScrollWidth=Ft(),this._maxScrollHeight=jt(),this.config=t,this.transport=e}get maxScrollX(){return this._maxScrollX}get maxScrollY(){return this._maxScrollY}get maxScrollWidth(){return this._maxScrollWidth}get maxScrollHeight(){return this._maxScrollHeight}get currentScrollX(){return this._currentScrollX}get currentScrollY(){return this._currentScrollY}update(e){const t=Date.now();if(this._currentScrollX=e.x,this._currentScrollY=e.y,e.x>this._maxScrollX){const n=Ft();this._maxScrollX=e.x;const i=e.x+n;i>this._maxScrollWidth&&(this._maxScrollWidth=i),this.timestamp=t}if(e.y>this._maxScrollY){const n=jt();this._maxScrollY=e.y;const i=e.y+n;i>this._maxScrollHeight&&(this._maxScrollHeight=i),this.timestamp=t}}}class Wt{constructor({sessionId:e,deviceId:t}){this.deviceId=t,this.sessionId=e,e&&t&&(this.sessionReplayId=((e,t)=>`${t}/${e}`)(e,t))}}const Bt=new class{constructor(){this.dbs={},this.createStore=e=>i(this,void 0,void 0,function*(){return yield a(e,1,{upgrade:e=>{e.objectStoreNames.contains("sessionTargetingMatch")||e.createObjectStore("sessionTargetingMatch",{keyPath:"sessionId"})}})}),this.openOrCreateDB=e=>i(this,void 0,void 0,function*(){if(this.dbs&&this.dbs[e])return this.dbs[e];const t=`${e.substring(0,10)}_amp_session_replay_targeting`,n=yield this.createStore(t);return this.dbs[e]=n,n}),this.getTargetingMatchForSession=e=>i(this,[e],void 0,function*({loggerProvider:e,apiKey:t,sessionId:n}){try{const e=yield this.openOrCreateDB(t),i=String(n),r=yield e.get("sessionTargetingMatch",i);return null==r?void 0:r.targetingMatch}catch(t){rt(e,`Failed to get targeting match for session id ${n}: ${t}`,t)}}),this.storeTargetingMatchForSession=e=>i(this,[e],void 0,function*({loggerProvider:e,apiKey:t,sessionId:n,targetingMatch:i}){try{const e=yield this.openOrCreateDB(t),r=String(n);return yield e.put("sessionTargetingMatch",{targetingMatch:i,sessionId:r,lastUpdated:Date.now()})}catch(t){rt(e,`Failed to store targeting match for session id ${n}: ${t}`,t)}}),this.clearStoreOfOldSessions=e=>i(this,[e],void 0,function*({loggerProvider:e,apiKey:t,currentSessionId:n}){try{const e=yield this.openOrCreateDB(t),i=String(n),r=e.transaction("sessionTargetingMatch","readwrite"),s=yield r.store.getAll();for(let e=0;e<s.length;e++){const t=s[e],n=Date.now()-t.lastUpdated;t.sessionId!==i&&n>1728e5&&(yield r.store.delete(t.sessionId))}yield r.done}catch(t){rt(e,`Failed to clear old targeting matches for sessions: ${t}`,t)}})}},Ht="__amplitude_url_tracking_patched__",zt=new WeakMap;function Kt(e,t,n={}){if(!(null==e?void 0:e.location))return()=>{};const{enablePolling:i=!1,pollingInterval:r=te}=n;if(i){const n=()=>{var t;return null!==(t=e.location.href)&&void 0!==t?t:""};let i=n();const s=e.setInterval(()=>{const e=n();e!==i&&(i=e,t(e))},r);return()=>{null!=s&&e.clearInterval(s)}}let s=zt.get(e);if(!s){let t;const n=new Set,i=()=>{var t;return null!==(t=e.location.href)&&void 0!==t?t:""},r=()=>{const e=i();void 0!==t&&e===t||(t=e,n.forEach(t=>t(e)))},o=e=>{const t=function(...t){const n=e.apply(this,t);return r(),n};return t[Ht]=!0,t},a=e.history;if(null==a?void 0:a.pushState){const e=Reflect.get(a,"pushState");e[Ht]||(a.pushState=o(e))}if(null==a?void 0:a.replaceState){const e=Reflect.get(a,"replaceState");e[Ht]||(a.replaceState=o(e))}s={callbacks:n,notify:r,onPopStateOrHashChange:()=>r(),listenersAttached:!1},zt.set(e,s)}const o=s;return o.listenersAttached||(e.addEventListener("popstate",o.onPopStateOrHashChange),e.addEventListener("hashchange",o.onPopStateOrHashChange),o.listenersAttached=!0),o.callbacks.add(t),()=>{o.callbacks.delete(t),0===o.callbacks.size&&o.listenersAttached&&(e.removeEventListener("popstate",o.onPopStateOrHashChange),e.removeEventListener("hashchange",o.onPopStateOrHashChange),o.listenersAttached=!1)}}function Jt(e={}){return{name:"amplitude/url-tracking@1",observer(t,n,i){var r,s,o;const a=Object.assign(Object.assign({},e),i),l=a.ugcFilterRules||[],c=null!==(r=a.enablePolling)&&void 0!==r&&r,u=null!==(s=a.pollingInterval)&&void 0!==s?s:te,d=null!==(o=a.captureDocumentTitle)&&void 0!==o&&o;if(!n)return()=>{};let g;const h=()=>n.location&&n.location.href||"",v=()=>{const e=h();if(void 0===g||e!==g){g=e;const i=(()=>{const{innerHeight:e,innerWidth:t,document:i}=n,r=h();let s="";return d&&(s=(null==i?void 0:i.title)||""),{href:l.length>0?de(r,l):r,title:s,viewportHeight:e,viewportWidth:t,type:"url-change-event"}})();t(i)}},f=Kt(n,()=>v(),c?{enablePolling:!0,pollingInterval:u}:{});return v(),()=>f()},options:e}}class Gt{constructor(){this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.pageLeaveFns=[],this.recordFunction=null,this.urlChangeCleanup=null,this.latestUrlChangeTargetingEvaluationId=0,this.teardownEventListeners=e=>{const t=v();t&&(t.removeEventListener("blur",this.blurListener),t.removeEventListener("focus",this.focusListener),!e&&t.addEventListener("blur",this.blurListener),!e&&t.addEventListener("focus",this.focusListener),t.self&&"onpagehide"in t.self?(t.removeEventListener("pagehide",this.pageLeaveListener),!e&&t.addEventListener("pagehide",this.pageLeaveListener)):(t.removeEventListener("beforeunload",this.pageLeaveListener),!e&&t.addEventListener("beforeunload",this.pageLeaveListener)))},this.blurListener=()=>{this.sendEvents()},this.focusListener=()=>{this.recordEvents(!1)},this.pageLeaveListener=e=>{this.pageLeaveFns.forEach(t=>{t(e)})},this.evaluateTargetingAndCapture=(e,...t)=>i(this,[e,...t],void 0,function*(e,t=!1,n=!1,r=!1){var s,o,a,l,u,d;if(!this.identifiers||!this.identifiers.sessionId||!this.config)return void(this.identifiers&&!this.identifiers.sessionId?this.loggerProvider.log("Session ID has not been set yet, cannot evaluate targeting for Session Replay."):this.loggerProvider.warn("Session replay init has not been called, cannot evaluate targeting."));if(!this.config.targetingConfig){if(!t)return void this.loggerProvider.log("No targeting config set, skipping initialization/recording for event.");this.loggerProvider.log("Targeting config has not been set yet, cannot evaluate targeting.")}this.lastTargetingParams=e;const g=this.config.targetingConfig;if(g&&!this.sessionTargetingMatch){const t=r?this.latestUrlChangeTargetingEvaluationId:void 0;let n=e.event;n&&Object.values(c).includes(n.event_type)&&(n=void 0);const h=null!==(u=null!==(o=null===(s=e.page)||void 0===s?void 0:s.url)&&void 0!==o?o:null===(l=null===(a=v())||void 0===a?void 0:a.location)||void 0===l?void 0:l.href)&&void 0!==u?u:"",f=null!==(d=e.page)&&void 0!==d?d:""!==h?{url:h}:void 0,p=yield(e=>i(void 0,[e],void 0,function*({sessionId:e,targetingConfig:t,loggerProvider:n,apiKey:i,targetingParams:r,urlChange:s=!1}){if(yield Bt.clearStoreOfOldSessions({loggerProvider:n,apiKey:i,currentSessionId:e}),!0===(yield Bt.getTargetingMatchForSession({loggerProvider:n,apiKey:i,sessionId:e}))&&!s)return!0;let o=!0;try{const{evaluateTargeting:s}=yield import("./targeting-min.js").then(function(e){return e.i}),a=Object.assign(Object.assign({},r),{flag:t,sessionId:"string"==typeof e?parseInt(e,10):e,apiKey:i,loggerProvider:n}),l=yield s(a);l&&l.sr_targeting_config&&(o="on"===l.sr_targeting_config.key),Bt.storeTargetingMatchForSession({loggerProvider:n,apiKey:i,sessionId:e,targetingMatch:o})}catch(e){const t=e;n.warn(t.message)}return o}))({sessionId:this.identifiers.sessionId,targetingConfig:g,loggerProvider:this.loggerProvider,apiKey:this.config.apiKey,targetingParams:{userProperties:e.userProperties,event:n,page:f},urlChange:r});if(r&&void 0!==t&&t!==this.latestUrlChangeTargetingEvaluationId)return void this.loggerProvider.debug(`Ignoring stale URL-change targeting result #${t}; latest is #${this.latestUrlChangeTargetingEvaluationId}.`);this.sessionTargetingMatch=this.sessionTargetingMatch||p,this.loggerProvider.debug(JSON.stringify({name:"targeted replay capture config",sessionTargetingMatch:this.sessionTargetingMatch,event:n,targetingParams:e},null,2))}t?this.initialize(!0):!n&&this.recordCancelCallback||(this.loggerProvider.log("Recording events for session due to forceRestart or no ongoing recording."),yield this.recordEvents())}),this.addCustomRRWebEvent=(e,...t)=>i(this,[e,...t],void 0,function*(e,t={},n=!0){try{let i;const r=this.config;if(r&&e!==re.METADATA&&(i={config:he(r),version:tt},n)){const e=yield ge();i=Object.assign(Object.assign({},e),i)}this.recordCancelCallback&&this.recordFunction?this.recordFunction.addCustomEvent(e,Object.assign(Object.assign({},t),i)):this.loggerProvider.debug(`Not able to add custom replay capture event ${e} due to no ongoing recording.`)}catch(e){this.loggerProvider.debug("Error while adding custom replay capture event: ",e)}}),this.stopRecordingEvents=()=>{var e;try{this.loggerProvider.log("Session Replay capture stopping."),this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null,null===(e=this.networkObservers)||void 0===e||e.stop()}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while stopping replay capture: ${t.toString()}`)}},this.loggerProvider=new se(new b)}init(e,t){return m(this._init(e,t))}setupUrlChangeListenerForTargeting(){var e;null===(e=this.urlChangeCleanup)||void 0===e||e.call(this);const t=v();if(!(null==t?void 0:t.location))return;const n=Kt(t,e=>{const t=++this.latestUrlChangeTargetingEvaluationId;this.evaluateTargetingAndCapture({userProperties:{},event:void 0,page:{url:e}},!1,!1,!0),this.loggerProvider.debug(`Queued URL-change targeting re-evaluation #${t} for ${e}.`)});this.urlChangeCleanup=()=>{n(),this.urlChangeCleanup=null}}getCurrentPageForTargeting(){var e,t;const n=null===(t=null===(e=v())||void 0===e?void 0:e.location)||void 0===t?void 0:t.href;return null!=n?{url:n}:void 0}_init(e,t){return i(this,void 0,void 0,function*(){var n,r,s,o,a,l,c,u;null===(n=this.urlChangeCleanup)||void 0===n||n.call(this),this.loggerProvider=new se(t.loggerProvider||new b),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.identifiers=new Wt({sessionId:t.sessionId,deviceId:t.deviceId}),this.joinedConfigGenerator=yield((e,t)=>i(void 0,void 0,void 0,function*(){const n=new fe(e,t),i=new W(e,n.loggerProvider,n.serverZone,t.configServerUrl);return new ye(i,n)}))(e,t);const{joinedConfig:d,localConfig:g,remoteConfig:h}=yield this.joinedConfigGenerator.generateJoinedConfig();if(this.config=d,this.setMetadata(t.sessionId,d,g,h,null===(r=t.version)||void 0===r?void 0:r.version,tt,null===(s=t.version)||void 0===s?void 0:s.type),t.sessionId&&(null===(o=this.config.interactionConfig)||void 0===o?void 0:o.enabled)){const e=At.default({sessionId:t.sessionId,type:"interaction"},this.config);this.pageLeaveFns=[e.send(this.getDeviceId.bind(this)).bind(e)],this.scrollHook=e.hook.bind(e),this.clickHandler=new Ut(this.loggerProvider,e)}const f=[];let p,{storeType:m}=this.config;"idb"!==m||(null===(a=v())||void 0===a?void 0:a.indexedDB)||(m="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log(`Using ${m} for event storage.`);try{const e=yield ut({config:this.config,type:"replay",storeType:m});f.push({name:"replay",manager:e})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating replay events manager: ${t.toString()}`)}if(null===(l=this.config.interactionConfig)||void 0===l?void 0:l.enabled){const e=this.config.interactionConfig.batch?Nt:qt;try{const t=yield ut({config:this.config,type:"interaction",minInterval:null!==(c=this.config.interactionConfig.trackEveryNms)&&void 0!==c?c:3e4,maxInterval:6e4,payloadBatcher:e,storeType:m});f.push({name:"interaction",manager:t})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating interaction events manager: ${t.toString()}`)}}this.eventsManager=new dt(...f),this.eventCompressor&&this.eventCompressor.terminate();const y=v();if(this.config.useWebWorker&&y&&y.Worker){const{compressionScript:e}=yield import("./worker-min.js");p=e}if(this.eventCompressor=new Ye(this.eventsManager,this.config,this.getDeviceId(),p),yield this.initializeNetworkObservers(),null===(u=v())||void 0===u?void 0:u.opener){const e=Q();!function(e,t){var n,i=e;if(!0!==i[Z]){i[Z]=!0;var r=null!==(n=null==t?void 0:t.scriptUrl)&&void 0!==n?n:"https://cdn.amplitude.com/libs/background-capture-1.0.0-alpha.2.js.gz",s=null,o=function(t,n){var i,r;"background-capture-complete"===t&&(null===(r=null===(i=e.logger)||void 0===i?void 0:i.debug)||void 0===r||r.call(i,"Background capture complete"),e.notify({action:"background-capture-complete",data:n}))};e.registerActionHandler("initialize-background-capture",function(){var t,n;null===(n=null===(t=e.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Initializing background capture (external script)");var i=new URL(r,e.endpoint).toString();e.loadScriptOnce(i).then(function(){var t,n,i;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===(i=null===window||void 0===window?void 0:window.amplitudeBackgroundCapture)||void 0===i?void 0:i.call(window,{messenger:e,onBackgroundCapture:o}),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})}}(e),e.setup(Object.assign({logger:this.loggerProvider},this.config.serverZone&&{endpoint:z[this.config.serverZone]}))}this.loggerProvider.log("Installing @amplitude/session-replay-browser."),this.teardownEventListeners(!1),yield this.evaluateTargetingAndCapture({userProperties:t.userProperties,page:this.getCurrentPageForTargeting()},!0),this.config.targetingConfig&&this.setupUrlChangeListenerForTargeting()})}setSessionId(e,t){return m(this.asyncSetSessionId(e,t))}asyncSetSessionId(e,t,n){return i(this,void 0,void 0,function*(){var i;this.latestUrlChangeTargetingEvaluationId++,this.sessionTargetingMatch=!1,this.lastShouldRecordDecision=void 0;const r=this.identifiers&&this.identifiers.sessionId;r&&this.sendEvents(r);const s=t||this.getDeviceId();if(this.identifiers=new Wt({sessionId:e,deviceId:s}),this.joinedConfigGenerator&&r){const{joinedConfig:e}=yield this.joinedConfigGenerator.generateJoinedConfig();this.config=e}(null===(i=this.config)||void 0===i?void 0:i.targetingConfig)?yield this.evaluateTargetingAndCapture({userProperties:null==n?void 0:n.userProperties,page:this.getCurrentPageForTargeting()},!1,!0):yield this.recordEvents()})}getSessionReplayProperties(){const e=this.config,t=this.identifiers;if(!e||!t)return this.loggerProvider.warn("Session replay init has not been called, cannot get session replay properties."),{};const n=this.getShouldRecord();let i={};return n&&(i={[Y]:t.sessionReplayId?t.sessionReplayId:null},e.debugMode&&(i[ne]=JSON.stringify({appHash:N(e.apiKey).toString()}))),this.addCustomRRWebEvent(re.GET_SR_PROPS,{shouldRecord:n,eventProperties:i},10===this.eventCount),10===this.eventCount&&(this.eventCount=0),this.eventCount++,i}sendEvents(e){var t;const n=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),i=this.getDeviceId();this.eventsManager&&n&&i&&this.eventsManager.sendCurrentSequenceEvents({sessionId:n,deviceId:i})}initialize(){return i(this,arguments,void 0,function*(e=!1){var t;if(!(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId))return this.loggerProvider.log("Session is not being recorded due to lack of session id."),Promise.resolve();const n=this.getDeviceId();return n?(this.eventsManager&&e&&this.eventsManager.sendStoredEvents({deviceId:n}),this.recordEvents()):(this.loggerProvider.log("Session is not being recorded due to lack of device id."),Promise.resolve())})}shouldOptOut(){var e,t;let n;if(null===(e=this.config)||void 0===e?void 0:e.instanceName){n=(i=this.config.instanceName,void 0===i&&(i=d),q.getInstance(i)).identityStore.getIdentity().optOut}var i;return void 0!==n?n:null===(t=this.config)||void 0===t?void 0:t.optOut}getShouldRecord(){if(!this.identifiers||!this.config||!this.identifiers.sessionId)return this.loggerProvider.warn("Session is not being recorded due to lack of config, please call sessionReplay.init."),!1;if(!this.config.captureEnabled)return this.loggerProvider.log(`Session ${this.identifiers.sessionId} not being captured due to capture being disabled for project or because the remote config could not be fetched.`),!1;if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${this.identifiers.sessionId} out of recording due to optOut config.`),!1;let e=!1,t="",n=!1;if(this.config.targetingConfig)this.sessionTargetingMatch?(t=`Capturing replays for session ${this.identifiers.sessionId} due to matching targeting conditions.`,this.loggerProvider.log(t),e=!0,n=!0):(t=`Not capturing replays for session ${this.identifiers.sessionId} due to not matching targeting conditions.`,this.loggerProvider.log(t),e=!1,n=!1);else{(i=this.identifiers.sessionId,r=this.config.sampleRate,s=N(i.toString()),31*Math.abs(s)%1e6/1e6<r)?(e=!0,n=!0):(t=`Opting session ${this.identifiers.sessionId} out of recording due to sample rate.`,this.loggerProvider.log(t),e=!1,n=!1)}var i,r,s;return this.lastShouldRecordDecision!==e&&this.config.targetingConfig&&(this.addCustomRRWebEvent(re.TARGETING_DECISION,{message:t,sessionId:this.identifiers.sessionId,matched:n,targetingParams:this.lastTargetingParams}),this.lastShouldRecordDecision=e),e}getBlockSelectors(){var e,t,n;const i=null!==(n=null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.blockSelector)&&void 0!==n?n:[];if(0!==i.length)return i}getMaskTextSelectors(){var e,t,n,i;if("conservative"===(null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.defaultMaskLevel))return"*";const r=null===(i=null===(n=this.config)||void 0===n?void 0:n.privacyConfig)||void 0===i?void 0:i.maskSelector;return r||void 0}getRecordingPlugins(e){return i(this,void 0,void 0,function*(){var t,n,i,r,s,o;const a=[];try{const e=Jt({ugcFilterRules:(null===(n=null===(t=this.config)||void 0===t?void 0:t.interactionConfig)||void 0===n?void 0:n.ugcFilterRules)||[],enablePolling:(null===(i=this.config)||void 0===i?void 0:i.enableUrlChangePolling)||!1,pollingInterval:null===(r=this.config)||void 0===r?void 0:r.urlChangePollingInterval,captureDocumentTitle:null===(s=this.config)||void 0===s?void 0:s.captureDocumentTitle});a.push(e)}catch(e){this.loggerProvider.warn("Failed to create URL tracking plugin:",e)}if(null===(o=null==e?void 0:e.console)||void 0===o?void 0:o.enabled)try{const{getRecordConsolePlugin:t}=yield import("./console-plugin-min.js");a.push(t({level:e.console.levels}))}catch(e){this.loggerProvider.warn("Failed to load console plugin:",e)}return a.length>0?a:void 0})}getRecordFunction(){return i(this,void 0,void 0,function*(){if(this.recordFunction)return this.recordFunction;try{const{record:e}=yield import("./rrweb-record-min.js");return this.recordFunction=e,e}catch(e){return this.loggerProvider.warn("Failed to load rrweb-record module:",e),null}})}recordEvents(){return i(this,arguments,void 0,function*(e=!0){var t,n,i,r,s,o,a;const l=this.config,c=this.getShouldRecord(),u=null===(t=this.identifiers)||void 0===t?void 0:t.sessionId;if(!c||!u||!l)return;this.stopRecordingEvents();const d=yield this.getRecordFunction();if(!d)return;yield this.initializeNetworkObservers(),null===(n=this.networkObservers)||void 0===n||n.start(e=>{this.addCustomRRWebEvent(re.FETCH_REQUEST,e)});const{privacyConfig:g,interactionConfig:h,loggingConfig:v}=l,f=(null==h?void 0:h.enabled)?{mouseInteraction:this.eventsManager&&(null===(i=this.clickHandler)||void 0===i?void 0:i.createHook({eventsManager:this.eventsManager,sessionId:u,deviceIdFn:this.getDeviceId.bind(this),mirror:d.mirror,ugcFilterRules:null!==(r=h.ugcFilterRules)&&void 0!==r?r:[],performanceOptions:null===(s=l.performanceConfig)||void 0===s?void 0:s.interaction})),scroll:this.scrollHook}:{},p=(null==h?void 0:h.enabled)&&h.ugcFilterRules?h.ugcFilterRules:[];this.loggerProvider.log(`Session Replay capture beginning for ${u}.`);try{this.recordCancelCallback=d({emit:e=>{if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${u} out of recording due to optOut config.`),this.stopRecordingEvents(),void this.sendEvents();e.type===pe.Meta&&(e.data.href=de(e.data.href,p)),this.eventCompressor&&this.eventCompressor.enqueueEvent(e,u)},inlineStylesheet:l.shouldInlineStylesheet,hooks:f,maskAllInputs:!0,maskTextClass:ie,blockClass:"amp-block",blockSelector:this.getBlockSelectors(),applyBackgroundColorToBlockedElements:l.applyBackgroundColorToBlockedElements,maskInputFn:le("input",g),maskTextFn:le("text",g),maskTextSelector:this.getMaskTextSelectors(),recordCanvas:!1,slimDOMOptions:{script:null===(o=l.omitElementTags)||void 0===o?void 0:o.script,comment:null===(a=l.omitElementTags)||void 0===a?void 0:a.comment},errorHandler:e=>{const t=e;if(t.message.includes("insertRule")&&t.message.includes("CSSStyleSheet"))throw t;if(t._external_)throw t;return this.loggerProvider.warn("Error while capturing replay: ",t.toString()),!0},plugins:yield this.getRecordingPlugins(v)}),this.addCustomRRWebEvent(re.DEBUG_INFO),e&&this.addCustomRRWebEvent(re.METADATA,this.metadata)}catch(e){this.loggerProvider.warn("Failed to initialize session replay:",e)}})}getDeviceId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.deviceId}getSessionId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.sessionId}flush(){return i(this,arguments,void 0,function*(e=!1){var t;return null===(t=this.eventsManager)||void 0===t?void 0:t.flush(e)})}shutdown(){var e;null===(e=this.urlChangeCleanup)||void 0===e||e.call(this),this.teardownEventListeners(!0),this.stopRecordingEvents(),this.sendEvents()}mapSDKType(e){return"plugin"===e?"@amplitude/plugin-session-replay-browser":"segment"===e?"@amplitude/segment-session-replay-plugin":null}setMetadata(e,t,n,i,r,s,o){const a=(null==e?void 0:e.toString())?N(e.toString()):void 0;this.metadata={joinedConfig:t,localConfig:n,remoteConfig:i,sessionId:e,hashValue:a,sampleRate:t.sampleRate,replaySDKType:this.mapSDKType(o),replaySDKVersion:r,standaloneSDKType:"@amplitude/session-replay-browser",standaloneSDKVersion:s}}initializeNetworkObservers(){return i(this,void 0,void 0,function*(){var e,t,n;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)try{const{NetworkObservers:e}=yield import("./observers-min.js");this.networkObservers=new e}catch(e){this.loggerProvider.warn("Failed to import or instantiate NetworkObservers:",e)}})}}const Qt=e=>()=>{const{config:t}=e,{loggerProvider:n,logLevel:i}=t||ve();return{logger:n,logLevel:i}};var Zt=(()=>{const e=new Gt;return{init:P(e.init.bind(e),"init",Qt(e)),evaluateTargetingAndCapture:P(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",Qt(e)),setSessionId:P(e.setSessionId.bind(e),"setSessionId",Qt(e)),getSessionId:P(e.getSessionId.bind(e),"getSessionId",Qt(e)),getSessionReplayProperties:P(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",Qt(e)),flush:P(e.flush.bind(e),"flush",Qt(e)),shutdown:P(e.shutdown.bind(e),"shutdown",Qt(e))}})();const{init:Xt,setSessionId:Yt,getSessionId:Vt,getSessionReplayProperties:en,flush:tn,shutdown:nn,evaluateTargetingAndCapture:rn}=Zt;export{se as S,Vt as a,en as b,nn as c,rn as e,tn as f,v as g,Xt as i,Yt as s};
1
+ import{_ as e,a as t,b as n,c as i,d as r,e as s,f as o,o as a}from"./targeting-min.js";var l,c;!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"}(l||(l={})),function(e){e.IDENTIFY="$identify",e.GROUP_IDENTIFY="$groupidentify",e.REVENUE="revenue_amount"}(c||(c={}));var u,d="$default_instance",g="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"}(u||(u={}));var h,v=function(){var e="ampIntegrationContext";return"undefined"!=typeof globalThis&&void 0!==globalThis[e]?globalThis[e]:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0},f=e([],t(Array(256).keys()),!1).map(function(e){return e.toString(16).padStart(2,"0")}),p=function(n){var i,r=v();if(!(null===(i=null==r?void 0:r.crypto)||void 0===i?void 0:i.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,p)}(n);var s=r.crypto.getRandomValues(new Uint8Array(16));return s[6]=15&s[6]|64,s[8]=63&s[8]|128,e([],t(s.entries()),!1).map(function(e){var n=t(e,2),i=n[0],r=n[1];return[4,6,8,10].includes(i)?"-".concat(f[r]):f[r]}).join("")},m=function(e){return{promise:e||Promise.resolve()}};!function(e){e[e.None=0]="None",e[e.Error=1]="Error",e[e.Warn=2]="Warn",e[e.Verbose=3]="Verbose",e[e.Debug=4]="Debug"}(h||(h={}));var y="Amplitude Logger ",b=function(){function e(){this.logLevel=h.None}return e.prototype.disable=function(){this.logLevel=h.None},e.prototype.enable=function(e){void 0===e&&(e=h.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Verbose||console.log("".concat(y,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Warn||console.warn("".concat(y,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Error||console.error("".concat(y,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<h.Debug||console.log("".concat(y,"[Debug]: ").concat(e.join(" ")))},e}(),S=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:d,logLevel:h.Warn,loggerProvider:new b,offline:!1,optOut:!1,serverUrl:g,serverZone:"US",useBatch:!1}},C=function(){function e(e){var t,n,i,r;this._optOut=!1;var s=S();this.apiKey=e.apiKey,this.flushIntervalMillis=null!==(t=e.flushIntervalMillis)&&void 0!==t?t:s.flushIntervalMillis,this.flushMaxRetries=e.flushMaxRetries||s.flushMaxRetries,this.flushQueueSize=e.flushQueueSize||s.flushQueueSize,this.instanceName=e.instanceName||s.instanceName,this.loggerProvider=e.loggerProvider||s.loggerProvider,this.logLevel=null!==(n=e.logLevel)&&void 0!==n?n:s.logLevel,this.minIdLength=e.minIdLength,this.plan=e.plan,this.ingestionMetadata=e.ingestionMetadata,this.offline=void 0!==e.offline?e.offline:s.offline,this.optOut=null!==(i=e.optOut)&&void 0!==i?i:s.optOut,this.serverUrl=e.serverUrl,this.serverZone=e.serverZone||s.serverZone,this.storageProvider=e.storageProvider,this.transportProvider=e.transportProvider,this.useBatch=null!==(r=e.useBatch)&&void 0!==r?r:s.useBatch,this.loggerProvider.enable(this.logLevel);var o=I(e.serverUrl,e.serverZone,e.useBatch);this.serverZone=o.serverZone,this.serverUrl=o.serverUrl}return Object.defineProperty(e.prototype,"optOut",{get:function(){return this._optOut},set:function(e){this._optOut=e},enumerable:!1,configurable:!0}),e}(),w=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":g},I=function(e,t,n){if(void 0===e&&(e=""),void 0===t&&(t=S().serverZone),void 0===n&&(n=S().useBatch),e)return{serverUrl:e,serverZone:void 0};var i=["US","EU"].includes(t)?t:S().serverZone;return{serverZone:i,serverUrl:w(i,n)}};var P=function(e,t,n,i,r){return void 0===r&&(r=null),function(){for(var s=[],o=0;o<arguments.length;o++)s[o]=arguments[o];var a=n(),l=a.logger,c=a.logLevel;if(c&&c<h.Debug||!c||!l)return e.apply(r,s);var u,d={type:"invoke public method",name:t,args:s,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:{}};i&&d.states&&(d.states.before=i());var g=e.apply(r,s);return g&&g.promise?g.promise.then(function(){i&&d.states&&(d.states.after=i()),d.time&&(d.time.end=(new Date).toISOString()),l.debug(JSON.stringify(d,null,2))}):(i&&d.states&&(d.states.after=i()),d.time&&(d.time.end=(new Date).toISOString()),l.debug(JSON.stringify(d,null,2))),g}},k=function(){function e(){}return e.prototype.getApplicationContext=function(){return{versionName:this.versionName,language:E(),platform:"Web",os:void 0,deviceModel:void 0}},e}(),E=function(){return"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||""},R=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}(),T=function(){return T=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},T.apply(this,arguments)};function O(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function _(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var i,r,s=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(i=s.next()).done;)o.push(i.value)}catch(e){r={error:e}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return o}"function"==typeof SuppressedError&&SuppressedError;var M=function(e,t){var n,i,r=typeof e;if(r!==typeof t)return!1;try{for(var s=O(["string","number","boolean","undefined"]),o=s.next();!o.done;o=s.next()){if(o.value===r)return e===t}}catch(e){n={error:e}}finally{try{o&&!o.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}if(null==e&&null==t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;var a=Array.isArray(e),l=Array.isArray(t);if(a!==l)return!1;if(!a||!l){var c=Object.keys(e).sort(),u=Object.keys(t).sort();if(!M(c,u))return!1;var d=!0;return Object.keys(e).forEach(function(n){M(e[n],t[n])||(d=!1)}),d}for(var g=0;g<e.length;g++)if(!M(e[g],t[g]))return!1;return!0};Object.entries||(Object.entries=function(e){for(var t=Object.keys(e),n=t.length,i=new Array(n);n--;)i[n]=[t[n],e[t[n]]];return i});var x,L=function(){function e(){this.identity={userProperties:{}},this.listeners=new Set}return e.prototype.editIdentity=function(){var e=this,t=T({},this.identity.userProperties),n=T(T({},this.identity),{userProperties:t});return{setUserId:function(e){return n.userId=e,this},setDeviceId:function(e){return n.deviceId=e,this},setUserProperties:function(e){return n.userProperties=e,this},setOptOut:function(e){return n.optOut=e,this},updateUserProperties:function(e){var t,i,r,s,o,a,l=n.userProperties||{};try{for(var c=O(Object.entries(e)),u=c.next();!u.done;u=c.next()){var d=_(u.value,2),g=d[0],h=d[1];switch(g){case"$set":try{for(var v=(r=void 0,O(Object.entries(h))),f=v.next();!f.done;f=v.next()){var p=_(f.value,2),m=p[0],y=p[1];l[m]=y}}catch(e){r={error:e}}finally{try{f&&!f.done&&(s=v.return)&&s.call(v)}finally{if(r)throw r.error}}break;case"$unset":try{for(var b=(o=void 0,O(Object.keys(h))),S=b.next();!S.done;S=b.next()){delete l[m=S.value]}}catch(e){o={error:e}}finally{try{S&&!S.done&&(a=b.return)&&a.call(b)}finally{if(o)throw o.error}}break;case"$clearAll":l={}}}}catch(e){t={error:e}}finally{try{u&&!u.done&&(i=c.return)&&i.call(c)}finally{if(t)throw t.error}}return n.userProperties=l,this},commit:function(){return e.setIdentity(n),this}}},e.prototype.getIdentity=function(){return T({},this.identity)},e.prototype.setIdentity=function(e){var t=T({},this.identity);this.identity=T({},e),M(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}(),D="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self,q=function(){function e(){this.identityStore=new L,this.eventBridge=new R,this.applicationContextProvider=new k}return e.getInstance=function(t){return D.analyticsConnectorInstances||(D.analyticsConnectorInstances={}),D.analyticsConnectorInstances[t]||(D.analyticsConnectorInstances[t]=new e),D.analyticsConnectorInstances[t]},e}(),N=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},U=function(){function e(){}return e.prototype.send=function(e,t,n){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,n,i,r,s,o,a,l,c,d,g,h,v,f,p,m,y,b,S,C,w,I;if("object"!=typeof e)return null;var P=e.code||0,k=this.buildStatus(P);switch(k){case u.Success:return{status:k,statusCode:P,body:{eventsIngested:null!==(t=e.events_ingested)&&void 0!==t?t:0,payloadSizeBytes:null!==(n=e.payload_size_bytes)&&void 0!==n?n:0,serverUploadTime:null!==(i=e.server_upload_time)&&void 0!==i?i:0}};case u.Invalid:return{status:k,statusCode:P,body:{error:null!==(r=e.error)&&void 0!==r?r:"",missingField:null!==(s=e.missing_field)&&void 0!==s?s:"",eventsWithInvalidFields:null!==(o=e.events_with_invalid_fields)&&void 0!==o?o:{},eventsWithMissingFields:null!==(a=e.events_with_missing_fields)&&void 0!==a?a:{},eventsWithInvalidIdLengths:null!==(l=e.events_with_invalid_id_lengths)&&void 0!==l?l:{},epsThreshold:null!==(c=e.eps_threshold)&&void 0!==c?c:0,exceededDailyQuotaDevices:null!==(d=e.exceeded_daily_quota_devices)&&void 0!==d?d:{},silencedDevices:null!==(g=e.silenced_devices)&&void 0!==g?g:[],silencedEvents:null!==(h=e.silenced_events)&&void 0!==h?h:[],throttledDevices:null!==(v=e.throttled_devices)&&void 0!==v?v:{},throttledEvents:null!==(f=e.throttled_events)&&void 0!==f?f:[]}};case u.PayloadTooLarge:return{status:k,statusCode:P,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case u.RateLimit:return{status:k,statusCode:P,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!==(C=e.exceeded_daily_quota_devices)&&void 0!==C?C:{},exceededDailyQuotaUsers:null!==(w=e.exceeded_daily_quota_users)&&void 0!==w?w:{},throttledEvents:null!==(I=e.throttled_events)&&void 0!==I?I:[]}};case u.Timeout:default:return{status:k,statusCode:P}}},e.prototype.buildStatus=function(e){return function(e){return e>=200&&e<300}(e)?u.Success:429===e?u.RateLimit:413===e?u.PayloadTooLarge:408===e?u.Timeout:e>=400&&e<500?u.Invalid:e>=500?u.Failed:u.Unknown},e}(),j=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 i(this,void 0,void 0,function(){var n,i,o;return r(this,function(r){switch(r.label){case 0:if("undefined"==typeof fetch)throw new Error("FetchTransport is not supported");return n={headers:s({"Content-Type":"application/json",Accept:"*/*"},this.customHeaders),body:JSON.stringify(t),method:"POST"},[4,fetch(e,n)];case 1:return[4,(i=r.sent()).text()];case 2:o=r.sent();try{return[2,this.buildResponse(JSON.parse(o))]}catch(e){return[2,this.buildResponse({code:i.status})]}return[2]}})})},t}(U),F=function(){function e(e,t){this.key="AMP_remote_config_".concat(e.substring(0,10)),this.logger=t}return e.prototype.fetchConfig=function(){var e=null,t={remoteConfig:null,lastFetch:new Date};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(JSON.stringify(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){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}(),$=401,A=429,W=function(){function e(e,t,n,i){void 0===n&&(n="US"),this.callbackInfos=[],this.lastSuccessfulFetch=null,this.fetchPromise=null,this.isLastFetchInvalidApiKey=!1,this.apiKey=e,this.serverUrl=i||("US"===n?"https://sr-client-cfg.amplitude.com/config":"https://sr-client-cfg.eu.amplitude.com/config"),this.logger=t,this.storage=new F(e,t)}return e.prototype.subscribe=function(e,t,n){var i=p(),r={id:i,key:e,deliveryMode:t,callback:n};return this.callbackInfos.push(r),"all"===t?this.subscribeAll(r):this.subscribeWaitForRemote(r,t.timeout),i},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 i(this,void 0,void 0,function(){var e,t=this;return r(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 i(this,void 0,void 0,function(){var t,n,i,s=this;return r(this,function(r){switch(r.label){case 0:return t=this.getOrCreateFetchPromise().then(function(t){s.logger.debug("Remote config client subscription all mode fetched from remote: ".concat(JSON.stringify(t))),s.sendCallback(e,t,"remote"),s.storage.setConfig(t)}),n=this.storage.fetchConfig().then(function(e){return e}),[4,Promise.race([t,n])];case 1:return void 0!==(i=r.sent())&&(this.logger.debug("Remote config client subscription all mode fetched from cache: ".concat(JSON.stringify(i))),null!==i.remoteConfig?this.sendCallback(e,i,"cache"):this.logger.debug("Remote config client skips sending callback because cache is empty (first time user).")),[4,t];case 2:return r.sent(),[2]}})})},e.prototype.subscribeWaitForRemote=function(e,t){return i(this,void 0,void 0,function(){var n,i;return r(this,function(r){switch(r.label){case 0:n=new Promise(function(e,n){setTimeout(function(){n("Timeout exceeded")},t)}),r.label=1;case 1:return r.trys.push([1,3,,5]),[4,Promise.race([this.getOrCreateFetchPromise(),n])];case 2:return i=r.sent(),this.logger.debug("Remote config client subscription wait for remote mode returns from remote."),this.sendCallback(e,i,"remote"),this.storage.setConfig(i),[3,5];case 3:return r.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!==(i=r.sent()).remoteConfig?(this.logger.debug("Remote config client subscription wait for remote mode returns a cached copy."),this.sendCallback(e,i,"cache")):(this.logger.debug("Remote config client subscription wait for remote mode failed to fetch cache."),this.sendCallback(e,i,"remote")),[3,5];case 5:return[2]}})})},e.prototype.sendCallback=function(e,t,n){var i;e.lastCallback=new Date,i=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(i,n,t.lastFetch)},e.prototype.fetch=function(e,t){return void 0===e&&(e=3),void 0===t&&(t=1e3),i(this,void 0,void 0,function(){var n,i,s,o,a,l,c=this;return r(this,function(u){switch(u.label){case 0:n=t/e,i={remoteConfig:null,lastFetch:new Date},s=function(i){var s,a,l,u,d,g;return r(this,function(r){switch(r.label){case 0:s=!0,a=new AbortController,l=setTimeout(function(){return a.abort()},t),r.label=1;case 1:return r.trys.push([1,7,8,9]),[4,fetch(o.getUrlParams(),{method:"GET",headers:{Accept:"*/*"},signal:a.signal})];case 2:return(u=r.sent()).ok?[3,4]:[4,u.text()];case 3:return d=r.sent(),o.logger.debug("Remote config client fetch with retry time ".concat(e," failed with ").concat(u.status,": ").concat(d)),u.status===$?(o.logger.error("Remote config client fetch failed with ".concat($,". Invalid API key; future fetches will be skipped.")),o.isLastFetchInvalidApiKey=!0,s=!1):u.status>=400&&u.status<500&&u.status!==A&&(s=!1),[3,6];case 4:return[4,u.json()];case 5:return[2,{value:{remoteConfig:r.sent(),lastFetch:new Date}}];case 6:return[3,9];case 7:return(g=r.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,9];case 8:return clearTimeout(l),[7];case 9:return s?i<e-1?[4,new Promise(function(e){return setTimeout(e,c.getJitterDelay(n))})]:[3,11]:[2,"break"];case 10:r.sent(),r.label=11;case 11:return[2]}})},o=this,a=0,u.label=1;case 1:return a<e?[5,s(a)]:[3,4];case 2:if("object"==typeof(l=u.sent()))return[2,l.value];if("break"===l)return[3,4];u.label=3;case 3:return a++,[3,1];case 4:return[2,i]}})})},e.prototype.getJitterDelay=function(e){return Math.floor(Math.random()*e)},e.prototype.getUrlParams=function(){var t=encodeURIComponent(this.apiKey),n=new URLSearchParams;return n.append("config_group",e.CONFIG_GROUP),"".concat(this.serverUrl,"/").concat(t,"?").concat(n.toString())},e.CONFIG_GROUP="browser",e}();!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(x||(x={}));var B,H="https://app.amplitude.com",z={US:H,EU:"https://app.eu.amplitude.com",STAGING:"https://apps.stag2.amplitude.com"};var K="__AMPLITUDE_MESSENGER_INSTANCE__",J="__AMPLITUDE_MESSENGER__",G=function(){function e(e){var t=(void 0===e?{}:e).origin,n=void 0===t?H:t;this[B]=!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,i,r;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===(r=null===(i=window.opener)||void 0===i?void 0:i.postMessage)||void 0===r||r.call(i,e,this.endpoint)},e.prototype.sendRequest=function(e,t,n){var i=this;void 0===n&&(n={timeout:15e3});var r="".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9)),s={id:r,action:e,args:t};return new Promise(function(t,o){i.requestCallbacks[r]={resolve:t,reject:o},i.notify(s),n.timeout>0&&setTimeout(function(){o(new Error("".concat(e," timed out (id: ").concat(r,")"))),delete i.requestCallbacks[r]},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,i,r,s;this.actionHandlers.has(e)&&(null===(s=null===(r=this.logger)||void 0===r?void 0:r.warn)||void 0===s||s.call(r,"Overwriting existing action handler for: ".concat(e))),this.actionHandlers.set(e,t);var a=this.pendingMessages.get(e);if(a){this.pendingMessages.delete(e);try{for(var l=o(a),c=l.next();!c.done;c=l.next()){t(c.value)}}catch(e){n={error:e}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}}},e.prototype.loadScriptOnce=function(e){return i(this,void 0,void 0,function(){var t,n,i;return r(this,function(r){switch(r.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 i;try{var r=document.createElement("script");r.type="text/javascript",r.async=!0,r.src=e,r.addEventListener("load",function(){t({status:!0})},{once:!0}),r.addEventListener("error",function(){n({status:!1,message:"Failed to load the script ".concat(e)})}),null===(i=document.head)||void 0===i||i.appendChild(r)}catch(e){n(e)}})}(e).then(function(){}),this.scriptLoadPromises.set(e,n),r.label=1;case 1:return r.trys.push([1,3,,4]),[4,n];case 2:return r.sent(),[3,4];case 3:throw i=r.sent(),this.scriptLoadPromises.delete(e),i;case 4:return[2]}})})},e.prototype.setup=function(e){var t,n,i=this,r=void 0===e?{}:e,s=r.logger,o=r.endpoint;s&&(this.logger=s),o&&this.endpoint===H&&(this.endpoint=o),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,r,s,o;if(null===(n=null===(t=i.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Message received: ",JSON.stringify(e)),i.endpoint===e.origin){var a=e.data,l=null==a?void 0:a.action;if(l)if("id"in a&&a.id)null===(s=null===(r=i.logger)||void 0===r?void 0:r.debug)||void 0===s||s.call(r,"Received Response to previous request: ",JSON.stringify(e)),i.handleResponse(a);else{if("ping"===l)return void i.notify({action:"pong"});var c=i.actionHandlers.get(l);if(c)c(a.data);else{var u=null!==(o=i.pendingMessages.get(l))&&void 0!==o?o:[];u.push(a.data),i.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=v();(null==e?void 0:e[J])===this&&delete e[J]},e}();function Q(e){var t,n=v(),i=null==n?void 0:n[J];if("object"==typeof(t=i)&&null!==t&&K in t&&!0===t[K])return i;var r=new G(e);return n&&(n[J]=r),r}B=K;var Z="__AMPLITUDE_BACKGROUND_CAPTURE__";const X="[Amplitude]",Y=`${X} Session Replay ID`,V=x.US,ee={enabled:!0},te=1e3,ne=`${X} Session Replay Debug`,ie="amp-mask";var re;!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"}(re||(re={}));class se{constructor(e){this.logger=e,this.log=this.getSafeMethod("log"),this.warn=this.getSafeMethod("warn"),this.error=this.getSafeMethod("error"),this.debug=this.getSafeMethod("debug")}getSafeMethod(e){var t;if(!this.logger)return()=>{};const n=this.logger[e];if("function"==typeof n){return(null!==(t=n.__rrweb_original__)&&void 0!==t?t:n).bind(this.logger)}return()=>{}}enable(e){this.logger.enable(e)}disable(){this.logger.disable()}}const oe="medium";const ae=(e,t,n)=>{switch(t){case"light":{if("input"!==e)return!0;const t=n?function(e){const t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?t.toLowerCase():null}(n):"";return!!t&&(!!["password","hidden","email","tel"].includes(t)||!!n.autocomplete.startsWith("cc-"))}case"medium":case"conservative":return!0;default:return ae(e,oe,n)}},le=(e,t)=>(n,i)=>((e,t={defaultMaskLevel:oe},n)=>{var i,r,s;if(n){if(n.closest("."+ie))return!0;const e=(null!==(i=t.maskSelector)&&void 0!==i?i:[]).some(e=>n.closest(e));if(e)return!0;if(n.closest(".amp-unmask"))return!1;const s=(null!==(r=t.unmaskSelector)&&void 0!==r?r:[]).some(e=>n.closest(e));if(s)return!1}return ae(e,null!==(s=t.defaultMaskLevel)&&void 0!==s?s:oe,n)})(e,t,i)?n.replace(/[^\s]/g,"*"):n,ce=(e,t)=>t||(e===x.STAGING?"https://api-sr.stag2.amplitude.com/sessions/v2/track":e===x.EU?"https://api-sr.eu.amplitude.com/sessions/v2/track":"https://api-sr.amplitude.com/sessions/v2/track"),ue=e=>{const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${t}$`)},de=(e,t)=>{for(const n of t){const t=ue(n.selector);if(t.test(e))return e.replace(t,n.replacement)}return e},ge=()=>i(void 0,void 0,void 0,function*(){try{const e=v();if(e){const{usage:t,quota:n,usageDetails:i}=yield e.navigator.storage.estimate(),r=t?Math.round(t/1024):0;return{totalStorageSize:r,percentOfQuota:t&&n?Math.round(1e3*(t/n+Number.EPSILON))/1e3:0,usageDetails:JSON.stringify(i)}}}catch(e){}return{totalStorageSize:0,percentOfQuota:0,usageDetails:""}}),he=e=>{const t=Object.assign({},e),{apiKey:n}=t;return t.apiKey=`****${n.substring(n.length-4)}`,t},ve=()=>({flushMaxRetries:2,logLevel:h.Warn,loggerProvider:new b,transportProvider:new j});class fe extends C{constructor(e,t){var n,i,r,s,o,a;const l=ve();if(super(Object.assign(Object.assign({transportProvider:l.transportProvider,loggerProvider:new se(t.loggerProvider||l.loggerProvider)},t),{apiKey:e})),this.flushMaxRetries=void 0!==t.flushMaxRetries&&t.flushMaxRetries<=l.flushMaxRetries?t.flushMaxRetries:l.flushMaxRetries,this.apiKey=e,this.sampleRate=t.sampleRate||0,this.serverZone=t.serverZone||V,this.configServerUrl=t.configServerUrl,this.trackServerUrl=t.trackServerUrl,this.shouldInlineStylesheet=t.shouldInlineStylesheet,this.version=t.version,this.performanceConfig=t.performanceConfig||ee,this.storeType=null!==(n=t.storeType)&&void 0!==n?n:"idb",this.applyBackgroundColorToBlockedElements=null!==(i=t.applyBackgroundColorToBlockedElements)&&void 0!==i&&i,this.enableUrlChangePolling=null!==(r=t.enableUrlChangePolling)&&void 0!==r&&r,this.urlChangePollingInterval=null!==(s=t.urlChangePollingInterval)&&void 0!==s?s:te,this.captureDocumentTitle=null!==(o=t.captureDocumentTitle)&&void 0!==o&&o,t.privacyConfig&&(this.privacyConfig=t.privacyConfig),t.interactionConfig&&(this.interactionConfig=t.interactionConfig,this.interactionConfig.ugcFilterRules&&(e=>{if(!e.every(e=>"string"==typeof e.selector&&"string"==typeof e.replacement))throw new Error("ugcFilterRules must be an array of objects with selector and replacement properties");if(!e.every(e=>{return"string"==typeof(t=e.selector)&&""!==t.trim()&&!!/^\/|^https?:\/\/[^\s]+$/.test(t);var t}))throw new Error("ugcFilterRules must be an array of objects with valid globs")})(this.interactionConfig.ugcFilterRules)),t.debugMode&&(this.debugMode=t.debugMode),void 0!==t.useWebWorker)this.useWebWorker=t.useWebWorker;else{const e=t;void 0!==(null===(a=e.experimental)||void 0===a?void 0:a.useWebWorker)&&(this.useWebWorker=e.experimental.useWebWorker)}t.omitElementTags&&(this.omitElementTags=t.omitElementTags)}}var pe=(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))(pe||{}),me=(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))(me||{});class ye{constructor(e,t){this.localConfig=t,this.remoteConfigClient=e}generateJoinedConfig(){return i(this,void 0,void 0,function*(){var e,t,n;const i=Object.assign({},this.localConfig);let r;i.optOut=this.localConfig.optOut,i.captureEnabled=!0;try{yield new Promise((e,t)=>{this.remoteConfigClient.subscribe("configs.sessionReplay","all",(n,s)=>{var o;if(this.localConfig.loggerProvider.debug(`Session Replay remote configuration received from ${s}:`,JSON.stringify(n,null,2)),!n)return void t(new Error("No remote config received"));const a=n,l=a.sr_sampling_config,c=a.sr_privacy_config,u=a.sr_targeting_config,d=null===(o=i.interactionConfig)||void 0===o?void 0:o.ugcFilterRules;i.interactionConfig=a.sr_interaction_config,i.interactionConfig&&d&&(i.interactionConfig.ugcFilterRules=d),i.loggingConfig=a.sr_logging_config,(l||c||u)&&(r={},l&&(r.sr_sampling_config=l),c&&(r.sr_privacy_config=c),u&&(r.sr_targeting_config=u)),e()})})}catch(e){return this.localConfig.loggerProvider.error("Failed to generate joined config: ",e),i.captureEnabled=!1,{localConfig:this.localConfig,joinedConfig:i,remoteConfig:void 0}}if(!r)return{localConfig:this.localConfig,joinedConfig:i,remoteConfig:r};const{sr_sampling_config:s,sr_privacy_config:o,sr_targeting_config:a}=r;if(s&&Object.keys(s).length>0?(Object.prototype.hasOwnProperty.call(s,"capture_enabled")?i.captureEnabled=s.capture_enabled:i.captureEnabled=!1,Object.prototype.hasOwnProperty.call(s,"sample_rate")&&(i.sampleRate=s.sample_rate)):(i.captureEnabled=!0,this.localConfig.loggerProvider.debug("Remote config successfully fetched, but no values set for project, Session Replay capture enabled.")),o){const r=null!==(e=i.privacyConfig)&&void 0!==e?e:{},s={defaultMaskLevel:null!==(n=null!==(t=o.defaultMaskLevel)&&void 0!==t?t:r.defaultMaskLevel)&&void 0!==n?n:"medium",blockSelector:[],maskSelector:[],unmaskSelector:[]},a=e=>{var t,n,i;const r={};"string"==typeof e.blockSelector&&(e.blockSelector=[e.blockSelector]);for(const n of null!==(t=e.blockSelector)&&void 0!==t?t:[])r[n]="block";for(const t of null!==(n=e.maskSelector)&&void 0!==n?n:[])r[t]="mask";for(const t of null!==(i=e.unmaskSelector)&&void 0!==i?i:[])r[t]="unmask";return r},l=Object.assign(Object.assign({},a(r)),a(o));for(const[e,t]of Object.entries(l))"mask"===t?s.maskSelector.push(e):"block"===t?s.blockSelector.push(e):"unmask"===t&&s.unmaskSelector.push(e);i.privacyConfig=((e,t)=>{const n=document.createDocumentFragment(),i=(e=[])=>{if("string"==typeof e&&(e=[e]),e=e.filter(e=>{try{n.querySelector(e)}catch(n){return t.warn(`[session-replay-browser] omitting selector "${e}" because it is invalid`),!1}return!0}),0!==e.length)return e};return e.blockSelector=i(e.blockSelector),e.maskSelector=i(e.maskSelector),e.unmaskSelector=i(e.unmaskSelector),e})(s,this.localConfig.loggerProvider)}return a&&Object.keys(a).length>0&&(i.targetingConfig=a),this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:he(i)},null,2)),{localConfig:this.localConfig,joinedConfig:i,remoteConfig:r}})}}var be=Uint8Array,Se=Uint16Array,Ce=Uint32Array,we=new be([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ie=new be([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Pe=new be([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ke=function(e,t){for(var n=new Se(31),i=0;i<31;++i)n[i]=t+=1<<e[i-1];var r=new Ce(n[30]);for(i=1;i<30;++i)for(var s=n[i];s<n[i+1];++s)r[s]=s-n[i]<<5|i;return[n,r]},Ee=ke(we,2),Re=Ee[0],Te=Ee[1];Re[28]=258,Te[258]=28;for(var Oe=ke(Ie,0)[1],_e=new Se(32768),Me=0;Me<32768;++Me){var xe=(43690&Me)>>>1|(21845&Me)<<1;xe=(61680&(xe=(52428&xe)>>>2|(13107&xe)<<2))>>>4|(3855&xe)<<4,_e[Me]=((65280&xe)>>>8|(255&xe)<<8)>>>1}var Le=function(e,t,n){for(var i=e.length,r=0,s=new Se(t);r<i;++r)++s[e[r]-1];var o,a=new Se(t);for(r=0;r<t;++r)a[r]=a[r-1]+s[r-1]<<1;if(n){o=new Se(1<<t);var l=15-t;for(r=0;r<i;++r)if(e[r])for(var c=r<<4|e[r],u=t-e[r],d=a[e[r]-1]++<<u,g=d|(1<<u)-1;d<=g;++d)o[_e[d]>>>l]=c}else for(o=new Se(i),r=0;r<i;++r)o[r]=_e[a[e[r]-1]++]>>>15-e[r];return o},De=new be(288);for(Me=0;Me<144;++Me)De[Me]=8;for(Me=144;Me<256;++Me)De[Me]=9;for(Me=256;Me<280;++Me)De[Me]=7;for(Me=280;Me<288;++Me)De[Me]=8;var qe=new be(32);for(Me=0;Me<32;++Me)qe[Me]=5;var Ne=Le(De,9,0),Ue=Le(qe,5,0),je=function(e){return(e/8|0)+(7&e&&1)},Fe=function(e,t,n){(null==n||n>e.length)&&(n=e.length);var i=new(e instanceof Se?Se:e instanceof Ce?Ce:be)(n-t);return i.set(e.subarray(t,n)),i},$e=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>>8},Ae=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>>8,e[i+2]|=n>>>16},We=function(e,t){for(var n=[],i=0;i<e.length;++i)e[i]&&n.push({s:i,f:e[i]});var r=n.length,s=n.slice();if(!r)return[new be(0),0];if(1==r){var o=new be(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort(function(e,t){return e.f-t.f}),n.push({s:-1,f:25001});var a=n[0],l=n[1],c=0,u=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};u!=r-1;)a=n[n[c].f<n[d].f?c++:d++],l=n[c!=u&&n[c].f<n[d].f?c++:d++],n[u++]={s:-1,f:a.f+l.f,l:a,r:l};var g=s[0].s;for(i=1;i<r;++i)s[i].s>g&&(g=s[i].s);var h=new Se(g+1),v=Be(n[u-1],h,0);if(v>t){i=0;var f=0,p=v-t,m=1<<p;for(s.sort(function(e,t){return h[t.s]-h[e.s]||e.f-t.f});i<r;++i){var y=s[i].s;if(!(h[y]>t))break;f+=m-(1<<v-h[y]),h[y]=t}for(f>>>=p;f>0;){var b=s[i].s;h[b]<t?f-=1<<t-h[b]++-1:++i}for(;i>=0&&f;--i){var S=s[i].s;h[S]==t&&(--h[S],++f)}v=t}return[new be(h),v]},Be=function(e,t,n){return-1==e.s?Math.max(Be(e.l,t,n+1),Be(e.r,t,n+1)):t[e.s]=n},He=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new Se(++t),i=0,r=e[0],s=1,o=function(e){n[i++]=e},a=1;a<=t;++a)if(e[a]==r&&a!=t)++s;else{if(!r&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(r),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(r);s=1,r=e[a]}return[n.subarray(0,i),t]},ze=function(e,t){for(var n=0,i=0;i<t.length;++i)n+=e[i]*t[i];return n},Ke=function(e,t,n){var i=n.length,r=je(t+2);e[r]=255&i,e[r+1]=i>>>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var s=0;s<i;++s)e[r+s+4]=n[s];return 8*(r+4+i)},Je=function(e,t,n,i,r,s,o,a,l,c,u){$e(t,u++,n),++r[256];for(var d=We(r,15),g=d[0],h=d[1],v=We(s,15),f=v[0],p=v[1],m=He(g),y=m[0],b=m[1],S=He(f),C=S[0],w=S[1],I=new Se(19),P=0;P<y.length;++P)I[31&y[P]]++;for(P=0;P<C.length;++P)I[31&C[P]]++;for(var k=We(I,7),E=k[0],R=k[1],T=19;T>4&&!E[Pe[T-1]];--T);var O,_,M,x,L=c+5<<3,D=ze(r,De)+ze(s,qe)+o,q=ze(r,g)+ze(s,f)+o+14+3*T+ze(I,E)+(2*I[16]+3*I[17]+7*I[18]);if(L<=D&&L<=q)return Ke(t,u,e.subarray(l,l+c));if($e(t,u,1+(q<D)),u+=2,q<D){O=Le(g,h,0),_=g,M=Le(f,p,0),x=f;var N=Le(E,R,0);$e(t,u,b-257),$e(t,u+5,w-1),$e(t,u+10,T-4),u+=14;for(P=0;P<T;++P)$e(t,u+3*P,E[Pe[P]]);u+=3*T;for(var U=[y,C],j=0;j<2;++j){var F=U[j];for(P=0;P<F.length;++P){var $=31&F[P];$e(t,u,N[$]),u+=E[$],$>15&&($e(t,u,F[P]>>>5&127),u+=F[P]>>>12)}}}else O=Ne,_=De,M=Ue,x=qe;for(P=0;P<a;++P)if(i[P]>255){$=i[P]>>>18&31;Ae(t,u,O[$+257]),u+=_[$+257],$>7&&($e(t,u,i[P]>>>23&31),u+=we[$]);var A=31&i[P];Ae(t,u,M[A]),u+=x[A],A>3&&(Ae(t,u,i[P]>>>5&8191),u+=Ie[A])}else Ae(t,u,O[i[P]]),u+=_[i[P]];return Ae(t,u,O[256]),u+_[256]},Ge=new Ce([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Qe=function(e,t,n,i,r){return function(e,t,n,i,r,s){var o=e.length,a=new be(i+o+5*(1+Math.floor(o/7e3))+r),l=a.subarray(i,a.length-r),c=0;if(!t||o<8)for(var u=0;u<=o;u+=65535){var d=u+65535;d<o?c=Ke(l,c,e.subarray(u,d)):(l[u]=s,c=Ke(l,c,e.subarray(u,o)))}else{for(var g=Ge[t-1],h=g>>>13,v=8191&g,f=(1<<n)-1,p=new Se(32768),m=new Se(f+1),y=Math.ceil(n/3),b=2*y,S=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<b)&f},C=new Ce(25e3),w=new Se(288),I=new Se(32),P=0,k=0,E=(u=0,0),R=0,T=0;u<o;++u){var O=S(u),_=32767&u,M=m[O];if(p[_]=M,m[O]=_,R<=u){var x=o-u;if((P>7e3||E>24576)&&x>423){c=Je(e,l,0,C,w,I,k,E,T,u-T,c),E=P=k=0,T=u;for(var L=0;L<286;++L)w[L]=0;for(L=0;L<30;++L)I[L]=0}var D=2,q=0,N=v,U=_-M&32767;if(x>2&&O==S(u-U))for(var j=Math.min(h,x)-1,F=Math.min(32767,u),$=Math.min(258,x);U<=F&&--N&&_!=M;){if(e[u+D]==e[u+D-U]){for(var A=0;A<$&&e[u+A]==e[u+A-U];++A);if(A>D){if(D=A,q=U,A>j)break;var W=Math.min(U,A-2),B=0;for(L=0;L<W;++L){var H=u-U+L+32768&32767,z=H-p[H]+32768&32767;z>B&&(B=z,M=H)}}}U+=(_=M)-(M=p[_])+32768&32767}if(q){C[E++]=268435456|Te[D]<<18|Oe[q];var K=31&Te[D],J=31&Oe[q];k+=we[K]+Ie[J],++w[257+K],++I[J],R=u+D,++P}else C[E++]=e[u],++w[e[u]]}}c=Je(e,l,s,C,w,I,k,E,T,u-T,c)}return Fe(a,0,i+je(c)+r)}(e,null==t.level?6:t.level,null==t.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,n,i,!0)};function Ze(e,t){void 0===t&&(t={});var n=function(){var e=1,t=0;return{p:function(n){for(var i=e,r=t,s=n.length,o=0;o!=s;){for(var a=Math.min(o+5552,s);o<a;++o)r+=i+=n[o];i%=65521,r%=65521}e=i,t=r},d:function(){return(e>>>8<<16|(255&t)<<8|t>>>8)+2*((255&e)<<23)}}}();n.p(e);var i,r,s,o=Qe(e,t,2,4);return i=o,r=t.level,s=0==r?0:r<6?1:9==r?3:2,i[0]=120,i[1]=s<<6|(s?32-2*s:1),function(e,t,n){for(;n;++t)e[t]=n,n>>>=8}(o,o.length-4,n.d()),o}const Xe=e=>{const t={...e,v:"v1"};return function(e,t){var n="";if(!t&&"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);for(var i=0;i<e.length;){var r=e[i++];r<128||t?n+=String.fromCharCode(r):r<224?n+=String.fromCharCode((31&r)<<6|63&e[i++]):r<240?n+=String.fromCharCode((15&r)<<12|(63&e[i++])<<6|63&e[i++]):(r=((15&r)<<18|(63&e[i++])<<12|(63&e[i++])<<6|63&e[i++])-65536,n+=String.fromCharCode(55296|r>>10,56320|1023&r))}return n}(Ze(function(e,t){var n=e.length;if(!t&&"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var i=new be(e.length+(e.length>>>1)),r=0,s=function(e){i[r++]=e},o=0;o<n;++o){if(r+5>i.length){var a=new be(r+8+(n-o<<1));a.set(i),i=a}var l=e.charCodeAt(o);l<128||t?s(l):l<2048?(s(192|l>>>6),s(128|63&l)):l>55295&&l<57344?(s(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++o))>>>18),s(128|l>>>12&63),s(128|l>>>6&63),s(128|63&l)):(s(224|l>>>12),s(128|l>>>6&63),s(128|63&l))}return Fe(i,0,r)}(JSON.stringify(t))),!0)};class Ye{constructor(e,t,n,i){var r;this.taskQueue=[],this.isProcessing=!1,this.compressEvent=e=>{const t=Xe(e);return JSON.stringify(t)},this.addCompressedEventToManager=(e,t)=>{this.eventsManager&&this.deviceId&&this.eventsManager.addEvent({event:{type:"replay",data:e},sessionId:t,deviceId:this.deviceId})},this.addCompressedEvent=(e,t)=>{if(this.worker)try{this.worker.postMessage({event:e,sessionId:t})}catch(n){"DataCloneError"===n.name?this.worker.postMessage(JSON.stringify({event:e,sessionId:t})):this.config.loggerProvider.warn("Unexpected error while posting message to worker:",n)}else{const n=this.compressEvent(e);this.addCompressedEventToManager(n,t)}},this.terminate=()=>{var e;null===(e=this.worker)||void 0===e||e.terminate()};const s=v();if(this.canUseIdleCallback=s&&"requestIdleCallback"in s,this.eventsManager=e,this.config=t,this.deviceId=n,this.timeout=(null===(r=t.performanceConfig)||void 0===r?void 0:r.timeout)||2e3,i){t.loggerProvider.log("Enabling web worker for compression");try{const e=new Blob([i],{type:"application/javascript"}),n=URL.createObjectURL(e),r=new Worker(n);r.onerror=e=>{e.preventDefault(),t.loggerProvider.error("Worker failed, falling back to non-worker compression:",e),r.terminate(),this.worker=void 0},r.onmessage=e=>{const{compressedEvent:t,sessionId:n}=e.data;this.addCompressedEventToManager(t,n)},this.worker=r}catch(e){t.loggerProvider.error("Failed to create worker, falling back to non-worker compression:",e)}}}scheduleIdleProcessing(){this.isProcessing||(this.isProcessing=!0,requestIdleCallback(e=>{this.processQueue(e)},{timeout:this.timeout}))}enqueueEvent(e,t){var n;this.canUseIdleCallback&&(null===(n=this.config.performanceConfig)||void 0===n?void 0:n.enabled)?(this.config.loggerProvider.debug("Enqueuing event for processing during idle time."),this.taskQueue.push({event:e,sessionId:t}),this.scheduleIdleProcessing()):(this.config.loggerProvider.debug("Processing event without idle callback."),this.addCompressedEvent(e,t))}processQueue(e){for(;this.taskQueue.length>0&&(e.timeRemaining()>0||e.didTimeout);){const e=this.taskQueue.shift();if(e){const{event:t,sessionId:n}=e;this.addCompressedEvent(t,n)}}this.taskQueue.length>0?requestIdleCallback(e=>{this.processQueue(e)},{timeout:this.timeout}):this.isProcessing=!1}}const Ve="Session replay event batch rejected due to exceeded retry count",et="Failed to store session replay events in IndexedDB",tt="1.32.2";class nt{constructor({trackServerUrl:e,loggerProvider:t,payloadBatcher:n}){this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.loggerProvider=t,this.payloadBatcher=n||(e=>e),this.trackServerUrl=e}sendEventsList(e){this.addToQueue(Object.assign(Object.assign({},e),{attempts:0,timeout:0}))}addToQueue(...e){e.filter(e=>e.attempts<(e.flushMaxRetries||0)?(e.attempts+=1,!0):(this.completeRequest({context:e,err:Ve}),!1)).forEach(e=>{this.queue=this.queue.concat(e),this.schedule(0)})}schedule(e){this.scheduled||(this.scheduled=setTimeout(()=>{this.flush(!0).then(()=>{this.queue.length>0&&this.schedule(e)})},e))}flush(){return i(this,arguments,void 0,function*(e=!1){const t=this.queue;this.queue=[],this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null);for(const n of t)yield this.send(n,e)})}send(e){return i(this,arguments,void 0,function*(e,t=!0){var n,i;const r=e.apiKey;if(!r)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing api key"});const s=e.deviceId;if(!s)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing device ID"});const o=(()=>{const e=v();return(null==e?void 0:e.location)?e.location.href:""})(),a=tt,l=e.sampleRate,c=new URLSearchParams({device_id:s,session_id:`${e.sessionId}`,type:`${e.type}`}),u=`${(null===(n=e.version)||void 0===n?void 0:n.type)||"standalone"}/${(null===(i=e.version)||void 0===i?void 0:i.version)||a}`,d=this.payloadBatcher({version:1,events:e.events});if(0!==d.events.length)try{const n={headers:{"Content-Type":"application/json",Accept:"*/*",Authorization:`Bearer ${r}`,"X-Client-Version":a,"X-Client-Library":u,"X-Client-Url":o.substring(0,1e3),"X-Client-Sample-Rate":`${l}`},body:JSON.stringify(d),method:"POST"},i=`${ce(e.serverZone,this.trackServerUrl)}?${c.toString()}`,s=yield fetch(i,n);if(null===s)return void this.completeRequest({context:e,err:"Unexpected error occurred"});if(t)yield this.handleReponse(s.status,e);else{let t="";try{t=JSON.stringify(s.body,null,2)}catch(e){}this.completeRequest({context:e,success:`${s.status}: ${t}`})}}catch(t){this.completeRequest({context:e,err:t})}else this.completeRequest({context:e})})}handleReponse(e,t){return i(this,void 0,void 0,function*(){switch((new U).buildStatus(e)){case u.Success:this.handleSuccessResponse(t);break;case u.Failed:yield this.handleOtherResponse(t);break;default:this.completeRequest({context:t,err:"Network error occurred, event batch rejected"})}})}handleSuccessResponse(e){const t=Math.round(new Blob(e.events).size/1024);this.completeRequest({context:e,success:`Session replay event batch tracked successfully for session id ${e.sessionId}, size of events: ${t} KB`})}handleOtherResponse(e){return i(this,void 0,void 0,function*(){const t=e.attempts*this.retryTimeout;e.attempts++,e.attempts>(e.flushMaxRetries||0)?this.completeRequest({context:e,err:Ve}):(yield new Promise(e=>setTimeout(e,t)),yield this.send(e,!0))})}completeRequest({context:e,err:t,success:n}){e.onComplete(),t?this.loggerProvider.warn(t):n&&this.loggerProvider.log(n)}}class it{get timeAtLastSplit(){return this._timeAtLastSplit}constructor(e){var t,n,i;this.minInterval=500,this.maxInterval=1e4,this.maxPersistedEventsSize=1e6,this.interval=this.minInterval,this._timeAtLastSplit=Date.now(),this.shouldSplitEventsList=(e,t)=>{const n=this.getStringSize(t);return this.getEventsArraySize(e)+n>=this.maxPersistedEventsSize||!!(Date.now()-this.timeAtLastSplit>this.interval&&e.length)&&(this.interval=Math.min(this.maxInterval,this.interval+this.minInterval),this._timeAtLastSplit=Date.now(),!0)},this.loggerProvider=e.loggerProvider,this.minInterval=null!==(t=e.minInterval)&&void 0!==t?t:this.minInterval,this.maxInterval=null!==(n=e.maxInterval)&&void 0!==n?n:this.maxInterval,this.maxPersistedEventsSize=null!==(i=e.maxPersistedEventsSize)&&void 0!==i?i:this.maxPersistedEventsSize}getStringSize(e){return e.length}getEventsArraySize(e){let t=0;for(const n of e)t+=this.getStringSize(n);return t+(2+Math.max(0,e.length-1)+2*e.length)}}const rt=(e,t,n)=>{var i;"object"==typeof(i=n)&&null!==i&&"AbortError"===i.name?e.debug(t):e.warn(t)},st="sessionCurrentSequence",ot="sequencesToSend",at=e=>{let t,n;return e.objectStoreNames.contains(st)||(n=e.createObjectStore(st,{keyPath:"sessionId"})),e.objectStoreNames.contains(ot)||(t=e.createObjectStore(ot,{keyPath:"sequenceId",autoIncrement:!0}),t.createIndex("sessionId","sessionId")),{sequencesStore:t,currentSequenceStore:n}};class lt extends it{constructor(e){super(e),this.getSequencesToSend=()=>i(this,void 0,void 0,function*(){try{const e=[];let t=yield this.db.transaction("sequencesToSend").store.openCursor();for(;t;){const{sessionId:n,events:i}=t.value;e.push({events:i,sequenceId:t.key,sessionId:n}),t=yield t.continue()}return e}catch(e){rt(this.loggerProvider,`${et}: ${e}`,e)}}),this.storeCurrentSequence=e=>i(this,void 0,void 0,function*(){try{const t=yield this.db.get(st,e);if(!t)return;const n=yield this.db.put(ot,{sessionId:e,events:t.events});return yield this.db.put(st,{sessionId:e,events:[]}),Object.assign(Object.assign({},t),{sessionId:e,sequenceId:n})}catch(e){rt(this.loggerProvider,`${et}: ${e}`,e)}}),this.addEventToCurrentSequence=(e,t)=>i(this,void 0,void 0,function*(){try{const n=this.db.transaction(st,"readwrite"),i=yield n.store.get(e);if(!i)return void(yield n.store.put({sessionId:e,events:[t]}));let r;if(this.shouldSplitEventsList(i.events,t))r=i.events,yield n.store.put({sessionId:e,events:[t]});else{const r=i.events.concat(t);yield n.store.put({sessionId:e,events:r})}if(yield n.done,!r)return;const s=yield this.storeSendingEvents(e,r);if(!s)return;return{events:r,sessionId:e,sequenceId:s}}catch(e){rt(this.loggerProvider,`${et}: ${e}`,e)}}),this.storeSendingEvents=(e,t)=>i(this,void 0,void 0,function*(){try{return yield this.db.put(ot,{sessionId:e,events:t})}catch(e){rt(this.loggerProvider,`${et}: ${e}`,e)}}),this.cleanUpSessionEventsStore=(e,t)=>i(this,void 0,void 0,function*(){if(t)try{yield this.db.delete(ot,t)}catch(e){rt(this.loggerProvider,`${et}: ${e}`,e)}}),this.db=e.db}static new(e,t){return i(this,void 0,void 0,function*(){try{const n="replay"===e?"":`_${e}`,r=`${t.apiKey.substring(0,10)}_amp_session_replay_events${n}`,s=yield(e=>i(void 0,void 0,void 0,function*(){return yield a(e,1,{upgrade:at})}))(r);return new lt(Object.assign(Object.assign({},t),{db:s}))}catch(e){rt(t.loggerProvider,`${et}: ${e}`,e)}})}getCurrentSequenceEvents(e){return i(this,void 0,void 0,function*(){if(e){const t=yield this.db.get("sessionCurrentSequence",e);if(!t)return;return[t]}const t=[];for(const e of yield this.db.getAll("sessionCurrentSequence"))t.push(e);return t})}}class ct extends it{constructor(){super(...arguments),this.finalizedSequences={},this.sequences={},this.sequenceId=0}resetCurrentSequence(e){this.sequences[e]=[]}addSequence(e){const t=this.sequenceId++,n=[...this.sequences[e]];return this.finalizedSequences[t]={sessionId:e,events:n},this.resetCurrentSequence(e),{sequenceId:t,events:n,sessionId:e}}getSequencesToSend(){return i(this,void 0,void 0,function*(){return Object.entries(this.finalizedSequences).map(([e,{sessionId:t,events:n}])=>({sequenceId:Number(e),sessionId:t,events:n}))})}storeCurrentSequence(e){return i(this,void 0,void 0,function*(){if(this.sequences[e])return this.addSequence(e)})}addEventToCurrentSequence(e,t){return i(this,void 0,void 0,function*(){let n;return this.sequences[e]||this.resetCurrentSequence(e),this.shouldSplitEventsList(this.sequences[e],t)&&(n=this.addSequence(e)),this.sequences[e].push(t),n})}storeSendingEvents(e,t){return i(this,void 0,void 0,function*(){return this.finalizedSequences[this.sequenceId]={sessionId:e,events:t},this.sequenceId++})}cleanUpSessionEventsStore(e,t){return i(this,void 0,void 0,function*(){void 0!==t&&delete this.finalizedSequences[t]})}}const ut=e=>i(void 0,[e],void 0,function*({config:e,minInterval:t,maxInterval:n,type:r,payloadBatcher:s,storeType:o}){const a=new nt(Object.assign(Object.assign({},e),{loggerProvider:e.loggerProvider,payloadBatcher:s})),l=()=>new ct({loggerProvider:e.loggerProvider,maxInterval:n,minInterval:t}),c="idb"===o?yield i(void 0,void 0,void 0,function*(){const i=yield lt.new(r,{loggerProvider:e.loggerProvider,minInterval:t,maxInterval:n,apiKey:e.apiKey});return i||(e.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),l())}):l(),u=({events:t,sessionId:n,deviceId:s,sequenceId:o})=>{e.debugMode&&ge().then(({totalStorageSize:t,percentOfQuota:n,usageDetails:i})=>{e.loggerProvider.debug(`Total storage size: ${t} KB, percentage of quota: ${n}%, usage details: ${i}`)}).catch(()=>{}),a.sendEventsList({events:t,sessionId:n,flushMaxRetries:e.flushMaxRetries,apiKey:e.apiKey,deviceId:s,sampleRate:e.sampleRate,serverZone:e.serverZone,version:e.version,type:r,onComplete:()=>i(void 0,void 0,void 0,function*(){yield c.cleanUpSessionEventsStore(n,o)})})};return{sendCurrentSequenceEvents:({sessionId:t,deviceId:n})=>{c.storeCurrentSequence(t).then(e=>{e&&u({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n})}).catch(t=>{e.loggerProvider.warn("Failed to get current sequence of session replay events for session:",t)})},addEvent:({event:t,sessionId:n,deviceId:i})=>{c.addEventToCurrentSequence(n,t.data).then(e=>e&&u({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:i})).catch(t=>{e.loggerProvider.warn("Failed to add event to session replay capture:",t)})},sendStoredEvents:e=>i(void 0,[e],void 0,function*({deviceId:e}){const t=yield c.getSequencesToSend();t&&t.forEach(t=>{u({sequenceId:t.sequenceId,events:t.events,sessionId:t.sessionId,deviceId:e})})}),flush:function(){return i(this,arguments,void 0,function*(e=!1){return a.flush(e)})}}});class dt{constructor(...e){const t=new Map;e.forEach(e=>{t.set(e.name,e.manager)}),this.managers=t}sendStoredEvents(e){return i(this,void 0,void 0,function*(){const t=[];this.managers.forEach(n=>{t.push(n.sendStoredEvents(e))}),yield Promise.all(t)})}addEvent({sessionId:e,event:t,deviceId:n}){var i;null===(i=this.managers.get(t.type))||void 0===i||i.addEvent({sessionId:e,event:t,deviceId:n})}sendCurrentSequenceEvents({sessionId:e,deviceId:t}){this.managers.forEach(n=>{n.sendCurrentSequenceEvents({sessionId:e,deviceId:t})})}flush(e){return i(this,void 0,void 0,function*(){const t=[];this.managers.forEach(n=>{t.push(n.flush(e))}),yield Promise.all(t)})}}let gt,ht,vt;function ft(e,t){if(vt=new Date,e.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if("html"===e.tagName.toLowerCase())return"html";const n={root:document.body,idName:e=>!0,className:e=>!0,tagName:e=>!0,attr:(e,t)=>!1,seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};gt=Object.assign(Object.assign({},n),t),ht=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(gt.root,n);let i=pt(e,"all",()=>pt(e,"two",()=>pt(e,"one",()=>pt(e,"none"))));if(i){const t=xt(Lt(i,e));return t.length>0&&(i=t[0]),yt(i)}throw new Error("Selector was not found.")}function pt(e,t,n){let i=null,r=[],s=e,o=0;for(;s;){const e=(new Date).getTime()-vt.getTime();if(void 0!==gt.timeoutMs&&e>gt.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${e}ms`);let a=Ot(Ct(s))||Ot(...wt(s))||Ot(...It(s))||Ot(Pt(s))||[kt()];const l=Et(s);if("all"==t)l&&(a=a.concat(a.filter(Tt).map(e=>Rt(e,l))));else if("two"==t)a=a.slice(0,1),l&&(a=a.concat(a.filter(Tt).map(e=>Rt(e,l))));else if("one"==t){const[e]=a=a.slice(0,1);l&&Tt(e)&&(a=[Rt(e,l)])}else"none"==t&&(a=[kt()],l&&(a=[Rt(a[0],l)]));for(let e of a)e.level=o;if(r.push(a),r.length>=gt.seedMinLength&&(i=mt(r,n),i))break;s=s.parentElement,o++}return i||(i=mt(r,n)),!i&&n?n():i}function mt(e,t){const n=xt(Mt(e));if(n.length>gt.threshold)return t?t():null;for(let e of n)if(St(e))return e;return null}function yt(e){let t=e[0],n=t.name;for(let i=1;i<e.length;i++){const r=e[i].level||0;n=t.level===r-1?`${e[i].name} > ${n}`:`${e[i].name} ${n}`,t=e[i]}return n}function bt(e){return e.map(e=>e.penalty).reduce((e,t)=>e+t,0)}function St(e){const t=yt(e);switch(ht.querySelectorAll(t).length){case 0:throw new Error(`Can't select any node with this selector: ${t}`);case 1:return!0;default:return!1}}function Ct(e){const t=e.getAttribute("id");return t&&gt.idName(t)?{name:"#"+CSS.escape(t),penalty:0}:null}function wt(e){const t=Array.from(e.attributes).filter(e=>gt.attr(e.name,e.value));return t.map(e=>({name:`[${CSS.escape(e.name)}="${CSS.escape(e.value)}"]`,penalty:.5}))}function It(e){return Array.from(e.classList).filter(gt.className).map(e=>({name:"."+CSS.escape(e),penalty:1}))}function Pt(e){const t=e.tagName.toLowerCase();return gt.tagName(t)?{name:t,penalty:2}:null}function kt(){return{name:"*",penalty:3}}function Et(e){const t=e.parentNode;if(!t)return null;let n=t.firstChild;if(!n)return null;let i=0;for(;n&&(n.nodeType===Node.ELEMENT_NODE&&i++,n!==e);)n=n.nextSibling;return i}function Rt(e,t){return{name:e.name+`:nth-child(${t})`,penalty:e.penalty+1}}function Tt(e){return"html"!==e.name&&!e.name.startsWith("#")}function Ot(...e){const t=e.filter(_t);return t.length>0?t:null}function _t(e){return null!=e}function*Mt(e,t=[]){if(e.length>0)for(let n of e[0])yield*Mt(e.slice(1,e.length),t.concat(n));else yield t}function xt(e){return[...e].sort((e,t)=>bt(e)-bt(t))}function*Lt(e,t,n={counter:0,visited:new Map}){if(e.length>2&&e.length>gt.optimizedMinLength)for(let i=1;i<e.length-1;i++){if(n.counter>gt.maxNumberOfTries)return;n.counter+=1;const r=[...e];r.splice(i,1);const s=yt(r);if(n.visited.has(s))return;St(r)&&Dt(r,t)&&(yield r,n.visited.set(s,!0),yield*Lt(r,t,n))}}function Dt(e,t){return ht.querySelector(yt(e))===t}const qt=({version:e,events:t})=>{const n=[];return t.forEach(e=>{const t=JSON.parse(e);t.count=1,"click"===t.type&&n.push(t)}),{version:e,events:n}},Nt=({version:e,events:t})=>{const n=[];t.forEach(e=>{const t=JSON.parse(e);"click"===t.type&&n.push(t)});const i=n.reduce((e,t)=>{const{x:n,y:i,selector:r,timestamp:s}=t,o=s-s%36e5,a=`${n}:${i}:${null!=r?r:""}:${o}`;return e[a]?e[a].count+=1:e[a]=Object.assign(Object.assign({},t),{timestamp:o,count:1}),e},{});return{version:e,events:Object.values(i)}};class Ut{constructor(e,t){this.createHook=({eventsManager:e,sessionId:t,deviceIdFn:n,mirror:i,ugcFilterRules:r,performanceOptions:s})=>o=>{if(o.type!==me.Click)return;const a=v();if(!a)return;const{location:l,innerHeight:c,innerWidth:u}=a;if(!l)return;const{x:d,y:g}=o;if(void 0===d||void 0===g)return;const h=i.getNode(o.id);let f;if(h)try{f=ft(h,s)}catch(e){this.logger.debug("error resolving selector from finder")}const p=de(l.href,r),m={x:d+this.scrollWatcher.currentScrollX,y:g+this.scrollWatcher.currentScrollY,selector:f,viewportHeight:c,viewportWidth:u,pageUrl:p,timestamp:Date.now(),type:"click"},y=n();y&&e.addEvent({sessionId:t,event:{type:"interaction",data:JSON.stringify(m)},deviceId:y})},this.logger=e,this.scrollWatcher=t}}function jt(){const e=v();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||0}function Ft(){const e=v();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||0}class $t{constructor(e,t){const n=v();n&&n.navigator&&"function"==typeof n.navigator.sendBeacon?this.sendBeacon=(e,t)=>{try{if(n.navigator.sendBeacon(e,JSON.stringify(t)))return!0}catch(e){}return!1}:this.sendBeacon=()=>!1,this.sendXhr=(e,t)=>{const n=new XMLHttpRequest;return n.open("POST",e,!0),n.setRequestHeader("Accept","*/*"),n.send(JSON.stringify(t)),!0},this.basePageUrl=ce(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e}send(e,t){const{sessionId:n,type:i}=this.context,r=new URLSearchParams({device_id:e,session_id:String(n),type:String(i),api_key:this.apiKey}),s=`${this.basePageUrl}?${r.toString()}`;this.sendBeacon(s,t)||this.sendXhr(s,t)}}class At{static default(e,t){return new At(new $t(e,t),t)}constructor(e,t){this.timestamp=Date.now(),this.hook=e=>{this.update(e)},this.send=e=>t=>{var n,i;const r=e(),s=v();s&&r&&this.transport.send(r,{version:1,events:[{maxScrollX:this._maxScrollX,maxScrollY:this._maxScrollY,maxScrollWidth:this._maxScrollWidth,maxScrollHeight:this._maxScrollHeight,viewportHeight:jt(),viewportWidth:Ft(),pageUrl:de(s.location.href,null!==(i=null===(n=this.config.interactionConfig)||void 0===n?void 0:n.ugcFilterRules)&&void 0!==i?i:[]),timestamp:this.timestamp,type:"scroll"}]})},this._maxScrollX=0,this._maxScrollY=0,this._currentScrollX=0,this._currentScrollY=0,this._maxScrollWidth=Ft(),this._maxScrollHeight=jt(),this.config=t,this.transport=e}get maxScrollX(){return this._maxScrollX}get maxScrollY(){return this._maxScrollY}get maxScrollWidth(){return this._maxScrollWidth}get maxScrollHeight(){return this._maxScrollHeight}get currentScrollX(){return this._currentScrollX}get currentScrollY(){return this._currentScrollY}update(e){const t=Date.now();if(this._currentScrollX=e.x,this._currentScrollY=e.y,e.x>this._maxScrollX){const n=Ft();this._maxScrollX=e.x;const i=e.x+n;i>this._maxScrollWidth&&(this._maxScrollWidth=i),this.timestamp=t}if(e.y>this._maxScrollY){const n=jt();this._maxScrollY=e.y;const i=e.y+n;i>this._maxScrollHeight&&(this._maxScrollHeight=i),this.timestamp=t}}}class Wt{constructor({sessionId:e,deviceId:t}){this.deviceId=t,this.sessionId=e,e&&t&&(this.sessionReplayId=((e,t)=>`${t}/${e}`)(e,t))}}const Bt=new class{constructor(){this.dbs={},this.createStore=e=>i(this,void 0,void 0,function*(){return yield a(e,1,{upgrade:e=>{e.objectStoreNames.contains("sessionTargetingMatch")||e.createObjectStore("sessionTargetingMatch",{keyPath:"sessionId"})}})}),this.openOrCreateDB=e=>i(this,void 0,void 0,function*(){if(this.dbs&&this.dbs[e])return this.dbs[e];const t=`${e.substring(0,10)}_amp_session_replay_targeting`,n=yield this.createStore(t);return this.dbs[e]=n,n}),this.getTargetingMatchForSession=e=>i(this,[e],void 0,function*({loggerProvider:e,apiKey:t,sessionId:n}){try{const e=yield this.openOrCreateDB(t),i=String(n),r=yield e.get("sessionTargetingMatch",i);return null==r?void 0:r.targetingMatch}catch(t){rt(e,`Failed to get targeting match for session id ${n}: ${t}`,t)}}),this.storeTargetingMatchForSession=e=>i(this,[e],void 0,function*({loggerProvider:e,apiKey:t,sessionId:n,targetingMatch:i}){try{const e=yield this.openOrCreateDB(t),r=String(n);return yield e.put("sessionTargetingMatch",{targetingMatch:i,sessionId:r,lastUpdated:Date.now()})}catch(t){rt(e,`Failed to store targeting match for session id ${n}: ${t}`,t)}}),this.clearStoreOfOldSessions=e=>i(this,[e],void 0,function*({loggerProvider:e,apiKey:t,currentSessionId:n}){try{const e=yield this.openOrCreateDB(t),i=String(n),r=e.transaction("sessionTargetingMatch","readwrite"),s=yield r.store.getAll();for(let e=0;e<s.length;e++){const t=s[e],n=Date.now()-t.lastUpdated;t.sessionId!==i&&n>1728e5&&(yield r.store.delete(t.sessionId))}yield r.done}catch(t){rt(e,`Failed to clear old targeting matches for sessions: ${t}`,t)}})}},Ht="__amplitude_url_tracking_patched__",zt=new WeakMap;function Kt(e,t,n={}){if(!(null==e?void 0:e.location))return()=>{};const{enablePolling:i=!1,pollingInterval:r=te}=n;if(i){const n=()=>{var t;return null!==(t=e.location.href)&&void 0!==t?t:""};let i=n();const s=e.setInterval(()=>{const e=n();e!==i&&(i=e,t(e))},r);return()=>{null!=s&&e.clearInterval(s)}}let s=zt.get(e);if(!s){let t;const n=new Set,i=()=>{var t;return null!==(t=e.location.href)&&void 0!==t?t:""},r=()=>{const e=i();void 0!==t&&e===t||(t=e,n.forEach(t=>t(e)))},o=e=>{const t=function(...t){const n=e.apply(this,t);return r(),n};return t[Ht]=!0,t},a=e.history;if(null==a?void 0:a.pushState){const e=Reflect.get(a,"pushState");e[Ht]||(a.pushState=o(e))}if(null==a?void 0:a.replaceState){const e=Reflect.get(a,"replaceState");e[Ht]||(a.replaceState=o(e))}s={callbacks:n,notify:r,onPopStateOrHashChange:()=>r(),listenersAttached:!1},zt.set(e,s)}const o=s;return o.listenersAttached||(e.addEventListener("popstate",o.onPopStateOrHashChange),e.addEventListener("hashchange",o.onPopStateOrHashChange),o.listenersAttached=!0),o.callbacks.add(t),()=>{o.callbacks.delete(t),0===o.callbacks.size&&o.listenersAttached&&(e.removeEventListener("popstate",o.onPopStateOrHashChange),e.removeEventListener("hashchange",o.onPopStateOrHashChange),o.listenersAttached=!1)}}function Jt(e={}){return{name:"amplitude/url-tracking@1",observer(t,n,i){var r,s,o;const a=Object.assign(Object.assign({},e),i),l=a.ugcFilterRules||[],c=null!==(r=a.enablePolling)&&void 0!==r&&r,u=null!==(s=a.pollingInterval)&&void 0!==s?s:te,d=null!==(o=a.captureDocumentTitle)&&void 0!==o&&o;if(!n)return()=>{};let g;const h=()=>n.location&&n.location.href||"",v=()=>{const e=h();if(void 0===g||e!==g){g=e;const i=(()=>{const{innerHeight:e,innerWidth:t,document:i}=n,r=h();let s="";return d&&(s=(null==i?void 0:i.title)||""),{href:l.length>0?de(r,l):r,title:s,viewportHeight:e,viewportWidth:t,type:"url-change-event"}})();t(i)}},f=Kt(n,()=>v(),c?{enablePolling:!0,pollingInterval:u}:{});return v(),()=>f()},options:e}}class Gt{constructor(){this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.pageLeaveFns=[],this.recordFunction=null,this.urlChangeCleanup=null,this.latestUrlChangeTargetingEvaluationId=0,this.teardownEventListeners=e=>{const t=v();t&&(t.removeEventListener("blur",this.blurListener),t.removeEventListener("focus",this.focusListener),!e&&t.addEventListener("blur",this.blurListener),!e&&t.addEventListener("focus",this.focusListener),t.self&&"onpagehide"in t.self?(t.removeEventListener("pagehide",this.pageLeaveListener),!e&&t.addEventListener("pagehide",this.pageLeaveListener)):(t.removeEventListener("beforeunload",this.pageLeaveListener),!e&&t.addEventListener("beforeunload",this.pageLeaveListener)))},this.blurListener=()=>{this.sendEvents()},this.focusListener=()=>{this.recordEvents(!1)},this.pageLeaveListener=e=>{this.pageLeaveFns.forEach(t=>{t(e)})},this.evaluateTargetingAndCapture=(e,...t)=>i(this,[e,...t],void 0,function*(e,t=!1,n=!1,r=!1){var s,o,a,l,u,d;if(!this.identifiers||!this.identifiers.sessionId||!this.config)return void(this.identifiers&&!this.identifiers.sessionId?this.loggerProvider.log("Session ID has not been set yet, cannot evaluate targeting for Session Replay."):this.loggerProvider.warn("Session replay init has not been called, cannot evaluate targeting."));if(!this.config.targetingConfig){if(!t)return void this.loggerProvider.log("No targeting config set, skipping initialization/recording for event.");this.loggerProvider.log("Targeting config has not been set yet, cannot evaluate targeting.")}this.lastTargetingParams=e;const g=this.config.targetingConfig;if(g&&!this.sessionTargetingMatch){const t=r?this.latestUrlChangeTargetingEvaluationId:void 0;let n=e.event;n&&Object.values(c).includes(n.event_type)&&(n=void 0);const h=null!==(u=null!==(o=null===(s=e.page)||void 0===s?void 0:s.url)&&void 0!==o?o:null===(l=null===(a=v())||void 0===a?void 0:a.location)||void 0===l?void 0:l.href)&&void 0!==u?u:"",f=null!==(d=e.page)&&void 0!==d?d:""!==h?{url:h}:void 0,p=yield(e=>i(void 0,[e],void 0,function*({sessionId:e,targetingConfig:t,loggerProvider:n,apiKey:i,targetingParams:r,urlChange:s=!1}){if(yield Bt.clearStoreOfOldSessions({loggerProvider:n,apiKey:i,currentSessionId:e}),!0===(yield Bt.getTargetingMatchForSession({loggerProvider:n,apiKey:i,sessionId:e}))&&!s)return!0;let o=!0;try{const{evaluateTargeting:s}=yield import("./targeting-min.js").then(function(e){return e.i}),a=Object.assign(Object.assign({},r),{flag:t,sessionId:"string"==typeof e?parseInt(e,10):e,apiKey:i,loggerProvider:n}),l=yield s(a);l&&l.sr_targeting_config&&(o="on"===l.sr_targeting_config.key),Bt.storeTargetingMatchForSession({loggerProvider:n,apiKey:i,sessionId:e,targetingMatch:o})}catch(e){const t=e;n.warn(t.message)}return o}))({sessionId:this.identifiers.sessionId,targetingConfig:g,loggerProvider:this.loggerProvider,apiKey:this.config.apiKey,targetingParams:{userProperties:e.userProperties,event:n,page:f},urlChange:r});if(r&&void 0!==t&&t!==this.latestUrlChangeTargetingEvaluationId)return void this.loggerProvider.debug(`Ignoring stale URL-change targeting result #${t}; latest is #${this.latestUrlChangeTargetingEvaluationId}.`);this.sessionTargetingMatch=this.sessionTargetingMatch||p,this.loggerProvider.debug(JSON.stringify({name:"targeted replay capture config",sessionTargetingMatch:this.sessionTargetingMatch,event:n,targetingParams:e},null,2))}t?this.initialize(!0):!n&&this.recordCancelCallback||(this.loggerProvider.log("Recording events for session due to forceRestart or no ongoing recording."),yield this.recordEvents())}),this.addCustomRRWebEvent=(e,...t)=>i(this,[e,...t],void 0,function*(e,t={},n=!0){try{let i;const r=this.config;if(r&&e!==re.METADATA&&(i={config:he(r),version:tt},n)){const e=yield ge();i=Object.assign(Object.assign({},e),i)}this.recordCancelCallback&&this.recordFunction?this.recordFunction.addCustomEvent(e,Object.assign(Object.assign({},t),i)):this.loggerProvider.debug(`Not able to add custom replay capture event ${e} due to no ongoing recording.`)}catch(e){this.loggerProvider.debug("Error while adding custom replay capture event: ",e)}}),this.stopRecordingEvents=()=>{var e;try{this.loggerProvider.log("Session Replay capture stopping."),this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null,null===(e=this.networkObservers)||void 0===e||e.stop()}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while stopping replay capture: ${t.toString()}`)}},this.loggerProvider=new se(new b)}init(e,t){return m(this._init(e,t))}setupUrlChangeListenerForTargeting(){var e;null===(e=this.urlChangeCleanup)||void 0===e||e.call(this);const t=v();if(!(null==t?void 0:t.location))return;const n=Kt(t,e=>{const t=++this.latestUrlChangeTargetingEvaluationId;this.evaluateTargetingAndCapture({userProperties:{},event:void 0,page:{url:e}},!1,!1,!0),this.loggerProvider.debug(`Queued URL-change targeting re-evaluation #${t} for ${e}.`)});this.urlChangeCleanup=()=>{n(),this.urlChangeCleanup=null}}getCurrentPageForTargeting(){var e,t;const n=null===(t=null===(e=v())||void 0===e?void 0:e.location)||void 0===t?void 0:t.href;return null!=n?{url:n}:void 0}_init(e,t){return i(this,void 0,void 0,function*(){var n,r,s,o,a,l,c,u;null===(n=this.urlChangeCleanup)||void 0===n||n.call(this),this.loggerProvider=new se(t.loggerProvider||new b),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.identifiers=new Wt({sessionId:t.sessionId,deviceId:t.deviceId}),this.joinedConfigGenerator=yield((e,t)=>i(void 0,void 0,void 0,function*(){const n=new fe(e,t),i=new W(e,n.loggerProvider,n.serverZone,t.configServerUrl);return new ye(i,n)}))(e,t);const{joinedConfig:d,localConfig:g,remoteConfig:h}=yield this.joinedConfigGenerator.generateJoinedConfig();if(this.config=d,this.setMetadata(t.sessionId,d,g,h,null===(r=t.version)||void 0===r?void 0:r.version,tt,null===(s=t.version)||void 0===s?void 0:s.type),t.sessionId&&(null===(o=this.config.interactionConfig)||void 0===o?void 0:o.enabled)){const e=At.default({sessionId:t.sessionId,type:"interaction"},this.config);this.pageLeaveFns=[e.send(this.getDeviceId.bind(this)).bind(e)],this.scrollHook=e.hook.bind(e),this.clickHandler=new Ut(this.loggerProvider,e)}const f=[];let p,{storeType:m}=this.config;"idb"!==m||(null===(a=v())||void 0===a?void 0:a.indexedDB)||(m="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log(`Using ${m} for event storage.`);try{const e=yield ut({config:this.config,type:"replay",storeType:m});f.push({name:"replay",manager:e})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating replay events manager: ${t.toString()}`)}if(null===(l=this.config.interactionConfig)||void 0===l?void 0:l.enabled){const e=this.config.interactionConfig.batch?Nt:qt;try{const t=yield ut({config:this.config,type:"interaction",minInterval:null!==(c=this.config.interactionConfig.trackEveryNms)&&void 0!==c?c:3e4,maxInterval:6e4,payloadBatcher:e,storeType:m});f.push({name:"interaction",manager:t})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating interaction events manager: ${t.toString()}`)}}this.eventsManager=new dt(...f),this.eventCompressor&&this.eventCompressor.terminate();const y=v();if(this.config.useWebWorker&&y&&y.Worker){const{compressionScript:e}=yield import("./worker-min.js");p=e}if(this.eventCompressor=new Ye(this.eventsManager,this.config,this.getDeviceId(),p),yield this.initializeNetworkObservers(),null===(u=v())||void 0===u?void 0:u.opener){const e=Q();!function(e,t){var n,i=e;if(!0!==i[Z]){i[Z]=!0;var r=null!==(n=null==t?void 0:t.scriptUrl)&&void 0!==n?n:"https://cdn.amplitude.com/libs/background-capture-1.0.0-alpha.2.js.gz",s=null,o=function(t,n){var i,r;"background-capture-complete"===t&&(null===(r=null===(i=e.logger)||void 0===i?void 0:i.debug)||void 0===r||r.call(i,"Background capture complete"),e.notify({action:"background-capture-complete",data:n}))};e.registerActionHandler("initialize-background-capture",function(){var t,n;null===(n=null===(t=e.logger)||void 0===t?void 0:t.debug)||void 0===n||n.call(t,"Initializing background capture (external script)");var i=new URL(r,e.endpoint).toString();e.loadScriptOnce(i).then(function(){var t,n,i;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===(i=null===window||void 0===window?void 0:window.amplitudeBackgroundCapture)||void 0===i?void 0:i.call(window,{messenger:e,onBackgroundCapture:o}),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})}}(e),e.setup(Object.assign({logger:this.loggerProvider},this.config.serverZone&&{endpoint:z[this.config.serverZone]}))}this.loggerProvider.log("Installing @amplitude/session-replay-browser."),this.teardownEventListeners(!1),yield this.evaluateTargetingAndCapture({userProperties:t.userProperties,page:this.getCurrentPageForTargeting()},!0),this.config.targetingConfig&&this.setupUrlChangeListenerForTargeting()})}setSessionId(e,t){return m(this.asyncSetSessionId(e,t))}asyncSetSessionId(e,t,n){return i(this,void 0,void 0,function*(){var i;this.latestUrlChangeTargetingEvaluationId++,this.sessionTargetingMatch=!1,this.lastShouldRecordDecision=void 0;const r=this.identifiers&&this.identifiers.sessionId;r&&this.sendEvents(r);const s=t||this.getDeviceId();if(this.identifiers=new Wt({sessionId:e,deviceId:s}),this.joinedConfigGenerator&&r){const{joinedConfig:e}=yield this.joinedConfigGenerator.generateJoinedConfig();this.config=e}(null===(i=this.config)||void 0===i?void 0:i.targetingConfig)?yield this.evaluateTargetingAndCapture({userProperties:null==n?void 0:n.userProperties,page:this.getCurrentPageForTargeting()},!1,!0):yield this.recordEvents()})}getSessionReplayProperties(){const e=this.config,t=this.identifiers;if(!e||!t)return this.loggerProvider.warn("Session replay init has not been called, cannot get session replay properties."),{};const n=this.getShouldRecord();let i={};return n&&(i={[Y]:t.sessionReplayId?t.sessionReplayId:null},e.debugMode&&(i[ne]=JSON.stringify({appHash:N(e.apiKey).toString()}))),this.addCustomRRWebEvent(re.GET_SR_PROPS,{shouldRecord:n,eventProperties:i},10===this.eventCount),10===this.eventCount&&(this.eventCount=0),this.eventCount++,i}sendEvents(e){var t;const n=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),i=this.getDeviceId();this.eventsManager&&n&&i&&this.eventsManager.sendCurrentSequenceEvents({sessionId:n,deviceId:i})}initialize(){return i(this,arguments,void 0,function*(e=!1){var t;if(!(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId))return this.loggerProvider.log("Session is not being recorded due to lack of session id."),Promise.resolve();const n=this.getDeviceId();return n?(this.eventsManager&&e&&this.eventsManager.sendStoredEvents({deviceId:n}),this.recordEvents()):(this.loggerProvider.log("Session is not being recorded due to lack of device id."),Promise.resolve())})}shouldOptOut(){var e,t;let n;if(null===(e=this.config)||void 0===e?void 0:e.instanceName){n=(i=this.config.instanceName,void 0===i&&(i=d),q.getInstance(i)).identityStore.getIdentity().optOut}var i;return void 0!==n?n:null===(t=this.config)||void 0===t?void 0:t.optOut}getShouldRecord(){if(!this.identifiers||!this.config||!this.identifiers.sessionId)return this.loggerProvider.warn("Session is not being recorded due to lack of config, please call sessionReplay.init."),!1;if(!this.config.captureEnabled)return this.loggerProvider.log(`Session ${this.identifiers.sessionId} not being captured due to capture being disabled for project or because the remote config could not be fetched.`),!1;if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${this.identifiers.sessionId} out of recording due to optOut config.`),!1;let e=!1,t="",n=!1;if(this.config.targetingConfig)this.sessionTargetingMatch?(t=`Capturing replays for session ${this.identifiers.sessionId} due to matching targeting conditions.`,this.loggerProvider.log(t),e=!0,n=!0):(t=`Not capturing replays for session ${this.identifiers.sessionId} due to not matching targeting conditions.`,this.loggerProvider.log(t),e=!1,n=!1);else{(i=this.identifiers.sessionId,r=this.config.sampleRate,s=N(i.toString()),31*Math.abs(s)%1e6/1e6<r)?(e=!0,n=!0):(t=`Opting session ${this.identifiers.sessionId} out of recording due to sample rate.`,this.loggerProvider.log(t),e=!1,n=!1)}var i,r,s;return this.lastShouldRecordDecision!==e&&this.config.targetingConfig&&(this.addCustomRRWebEvent(re.TARGETING_DECISION,{message:t,sessionId:this.identifiers.sessionId,matched:n,targetingParams:this.lastTargetingParams}),this.lastShouldRecordDecision=e),e}getBlockSelectors(){var e,t,n;const i=null!==(n=null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.blockSelector)&&void 0!==n?n:[];if(0!==i.length)return i}getMaskTextSelectors(){var e,t,n,i;if("conservative"===(null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.defaultMaskLevel))return"*";const r=null===(i=null===(n=this.config)||void 0===n?void 0:n.privacyConfig)||void 0===i?void 0:i.maskSelector;return r||void 0}getRecordingPlugins(e){return i(this,void 0,void 0,function*(){var t,n,i,r,s,o;const a=[];try{const e=Jt({ugcFilterRules:(null===(n=null===(t=this.config)||void 0===t?void 0:t.interactionConfig)||void 0===n?void 0:n.ugcFilterRules)||[],enablePolling:(null===(i=this.config)||void 0===i?void 0:i.enableUrlChangePolling)||!1,pollingInterval:null===(r=this.config)||void 0===r?void 0:r.urlChangePollingInterval,captureDocumentTitle:null===(s=this.config)||void 0===s?void 0:s.captureDocumentTitle});a.push(e)}catch(e){this.loggerProvider.warn("Failed to create URL tracking plugin:",e)}if(null===(o=null==e?void 0:e.console)||void 0===o?void 0:o.enabled)try{const{getRecordConsolePlugin:t}=yield import("./console-plugin-min.js");a.push(t({level:e.console.levels}))}catch(e){this.loggerProvider.warn("Failed to load console plugin:",e)}return a.length>0?a:void 0})}getRecordFunction(){return i(this,void 0,void 0,function*(){if(this.recordFunction)return this.recordFunction;try{const{record:e}=yield import("./rrweb-record-min.js");return this.recordFunction=e,e}catch(e){return this.loggerProvider.warn("Failed to load rrweb-record module:",e),null}})}recordEvents(){return i(this,arguments,void 0,function*(e=!0){var t,n,i,r,s,o,a;const l=this.config,c=this.getShouldRecord(),u=null===(t=this.identifiers)||void 0===t?void 0:t.sessionId;if(!c||!u||!l)return;this.stopRecordingEvents();const d=yield this.getRecordFunction();if(!d)return;yield this.initializeNetworkObservers(),null===(n=this.networkObservers)||void 0===n||n.start(e=>{this.addCustomRRWebEvent(re.FETCH_REQUEST,e)});const{privacyConfig:g,interactionConfig:h,loggingConfig:v}=l,f=(null==h?void 0:h.enabled)?{mouseInteraction:this.eventsManager&&(null===(i=this.clickHandler)||void 0===i?void 0:i.createHook({eventsManager:this.eventsManager,sessionId:u,deviceIdFn:this.getDeviceId.bind(this),mirror:d.mirror,ugcFilterRules:null!==(r=h.ugcFilterRules)&&void 0!==r?r:[],performanceOptions:null===(s=l.performanceConfig)||void 0===s?void 0:s.interaction})),scroll:this.scrollHook}:{},p=(null==h?void 0:h.enabled)&&h.ugcFilterRules?h.ugcFilterRules:[];this.loggerProvider.log(`Session Replay capture beginning for ${u}.`);try{this.recordCancelCallback=d({emit:e=>{if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${u} out of recording due to optOut config.`),this.stopRecordingEvents(),void this.sendEvents();e.type===pe.Meta&&(e.data.href=de(e.data.href,p)),this.eventCompressor&&this.eventCompressor.enqueueEvent(e,u)},inlineStylesheet:l.shouldInlineStylesheet,hooks:f,maskAllInputs:!0,maskTextClass:ie,blockClass:"amp-block",blockSelector:this.getBlockSelectors(),applyBackgroundColorToBlockedElements:l.applyBackgroundColorToBlockedElements,maskInputFn:le("input",g),maskTextFn:le("text",g),maskTextSelector:this.getMaskTextSelectors(),recordCanvas:!1,slimDOMOptions:{script:null===(o=l.omitElementTags)||void 0===o?void 0:o.script,comment:null===(a=l.omitElementTags)||void 0===a?void 0:a.comment},errorHandler:e=>{const t=e;if(t.message.includes("insertRule")&&t.message.includes("CSSStyleSheet"))throw t;if(t._external_)throw t;return this.loggerProvider.warn("Error while capturing replay: ",t.toString()),!0},plugins:yield this.getRecordingPlugins(v)}),this.addCustomRRWebEvent(re.DEBUG_INFO),e&&this.addCustomRRWebEvent(re.METADATA,this.metadata)}catch(e){this.loggerProvider.warn("Failed to initialize session replay:",e)}})}getDeviceId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.deviceId}getSessionId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.sessionId}flush(){return i(this,arguments,void 0,function*(e=!1){var t;return null===(t=this.eventsManager)||void 0===t?void 0:t.flush(e)})}shutdown(){var e;null===(e=this.urlChangeCleanup)||void 0===e||e.call(this),this.teardownEventListeners(!0),this.stopRecordingEvents(),this.sendEvents()}mapSDKType(e){return"plugin"===e?"@amplitude/plugin-session-replay-browser":"segment"===e?"@amplitude/segment-session-replay-plugin":null}setMetadata(e,t,n,i,r,s,o){const a=(null==e?void 0:e.toString())?N(e.toString()):void 0;this.metadata={joinedConfig:t,localConfig:n,remoteConfig:i,sessionId:e,hashValue:a,sampleRate:t.sampleRate,replaySDKType:this.mapSDKType(o),replaySDKVersion:r,standaloneSDKType:"@amplitude/session-replay-browser",standaloneSDKVersion:s}}initializeNetworkObservers(){return i(this,void 0,void 0,function*(){var e,t,n;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)try{const{NetworkObservers:e}=yield import("./observers-min.js");this.networkObservers=new e}catch(e){this.loggerProvider.warn("Failed to import or instantiate NetworkObservers:",e)}})}}const Qt=e=>()=>{const{config:t}=e,{loggerProvider:n,logLevel:i}=t||ve();return{logger:n,logLevel:i}};var Zt=(()=>{const e=new Gt;return{init:P(e.init.bind(e),"init",Qt(e)),evaluateTargetingAndCapture:P(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",Qt(e)),setSessionId:P(e.setSessionId.bind(e),"setSessionId",Qt(e)),getSessionId:P(e.getSessionId.bind(e),"getSessionId",Qt(e)),getSessionReplayProperties:P(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",Qt(e)),flush:P(e.flush.bind(e),"flush",Qt(e)),shutdown:P(e.shutdown.bind(e),"shutdown",Qt(e))}})();const{init:Xt,setSessionId:Yt,getSessionId:Vt,getSessionReplayProperties:en,flush:tn,shutdown:nn,evaluateTargetingAndCapture:rn}=Zt;export{se as S,Vt as a,en as b,nn as c,rn as e,tn as f,v as g,Xt as i,Yt as s};
2
2
  //# sourceMappingURL=index-min.js.map
Binary file