@rudderstack/analytics-js 3.13.0 → 3.15.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -851,10 +851,10 @@ var isFunction=function isFunction(value){return typeof value==='function'&&Bool
851
851
  * @param value input value
852
852
  * @returns boolean
853
853
  */var isDefinedNotNullAndNotEmptyString=function isDefinedNotNullAndNotEmptyString(value){return isDefinedAndNotNull(value)&&value!=='';};/**
854
- * Determines if the input is an instance of Error
855
- * @param obj input value
856
- * @returns true if the input is an instance of Error and false otherwise
857
- */var isTypeOfError=function isTypeOfError(obj){return obj instanceof Error;};
854
+ * Determines if the input is of type error
855
+ * @param value input value
856
+ * @returns true if the input is of type error else false
857
+ */var isTypeOfError=function isTypeOfError(value){switch(Object.prototype.toString.call(value)){case '[object Error]':case '[object Exception]':case '[object DOMException]':return true;default:return value instanceof Error;}};
858
858
 
859
859
  var getValueByPath=function getValueByPath(obj,keyPath){var pathParts=keyPath.split('.');return path(pathParts,obj);};var hasValueByPath=function hasValueByPath(obj,path){return Boolean(getValueByPath(obj,path));};var isObject=function isObject(value){return _typeof(value)==='object';};/**
860
860
  * Checks if the input is an object literal or built-in object type and not null
@@ -894,7 +894,7 @@ mergeDeepRight(mergedArray[index],value):value;});return mergedArray;};var merge
894
894
  * getNormalizedBooleanValue(true, false) // returns true
895
895
  */var getNormalizedBooleanValue=function getNormalizedBooleanValue(val,defVal){if(isDefined(defVal)){return isDefined(val)?val===true:defVal;}return val===true;};
896
896
 
897
- var trim=function trim(value){return value.replace(/^\s+|\s+$/gm,'');};var removeDoubleSpaces=function removeDoubleSpaces(value){return value.replace(/ {2,}/g,' ');};var removeLeadingPeriod=function removeLeadingPeriod(value){return value.replace(/^\.+/,'');};/**
897
+ var trim=function trim(value){return value.replace(/^\s+|\s+$/gm,'');};var removeLeadingPeriod=function removeLeadingPeriod(value){return value.replace(/^\.+/,'');};/**
898
898
  * A function to convert values to string
899
899
  * @param val input value
900
900
  * @returns stringified value
@@ -965,7 +965,7 @@ payload.groupId=tryStringify(payload.groupId);if(isObjectLiteralAndNotNull(paylo
965
965
  * Represents the options parameter in the load API
966
966
  */
967
967
 
968
- var CAPABILITIES_MANAGER='CapabilitiesManager';var CONFIG_MANAGER='ConfigManager';var EVENT_MANAGER='EventManager';var PLUGINS_MANAGER='PluginsManager';var USER_SESSION_MANAGER='UserSessionManager';var ERROR_HANDLER='ErrorHandler';var PLUGIN_ENGINE='PluginEngine';var STORE_MANAGER='StoreManager';var READY_API='readyApi';var EVENT_REPOSITORY='EventRepository';var EXTERNAL_SRC_LOADER='ExternalSrcLoader';var HTTP_CLIENT='HttpClient';var RSA='RudderStackAnalytics';var ANALYTICS_CORE='AnalyticsCore';
968
+ var API_SUFFIX='API';var CAPABILITIES_MANAGER='CapabilitiesManager';var CONFIG_MANAGER='ConfigManager';var EVENT_MANAGER='EventManager';var PLUGINS_MANAGER='PluginsManager';var USER_SESSION_MANAGER='UserSessionManager';var ERROR_HANDLER='ErrorHandler';var PLUGIN_ENGINE='PluginEngine';var STORE_MANAGER='StoreManager';var READY_API="Ready".concat(API_SUFFIX);var LOAD_API="Load".concat(API_SUFFIX);var EXTERNAL_SRC_LOADER='ExternalSrcLoader';var HTTP_CLIENT='HttpClient';var RSA='RudderStackAnalytics';var ANALYTICS_CORE='AnalyticsCore';
969
969
 
970
970
  function random(len){return crypto.getRandomValues(new Uint8Array(len));}
971
971
 
@@ -1033,14 +1033,17 @@ if(isObjectLiteralAndNotNull(sanitizedValue)||Array.isArray(sanitizedValue)){res
1033
1033
  */var getSanitizedValue=function getSanitizedValue(value,logger){var replacer=getReplacer();// This is needed for registering the first ancestor
1034
1034
  var newValue=replacer.call(value,'',value);if(isObjectLiteralAndNotNull(value)||Array.isArray(value)){return _traverseWithThis(value,replacer);}return newValue;};
1035
1035
 
1036
- var MANUAL_ERROR_IDENTIFIER='[MANUAL ERROR]';/**
1036
+ var MANUAL_ERROR_IDENTIFIER='[SDK DISPATCHED ERROR]';var getStacktrace=function getStacktrace(err){var _ref;var stack=err.stack,stacktrace=err.stacktrace;var operaSourceloc=err['opera#sourceloc'];var stackString=(_ref=stack!==null&&stack!==undefined?stack:stacktrace)!==null&&_ref!==undefined?_ref:operaSourceloc;if(!!stackString&&typeof stackString==='string'){return stackString;}return undefined;};/**
1037
1037
  * Get mutated error with issue prepended to error message
1038
1038
  * @param err Original error
1039
1039
  * @param issue Issue to prepend to error message
1040
1040
  * @returns Instance of Error with message prepended with issue
1041
- */var getMutatedError=function getMutatedError(err,issue){var finalError=err;if(!isTypeOfError(err)){finalError=new Error("".concat(issue,": ").concat(stringifyWithoutCircular(err)));}else {finalError.message="".concat(issue,": ").concat(err.message);}return finalError;};var dispatchErrorEvent=function dispatchErrorEvent(error){if(isTypeOfError(error)){var _error$stack;error.stack="".concat((_error$stack=error.stack)!==null&&_error$stack!==undefined?_error$stack:'',"\n").concat(MANUAL_ERROR_IDENTIFIER);}globalThis.dispatchEvent(new ErrorEvent('error',{error:error}));};
1041
+ */var getMutatedError=function getMutatedError(err,issue){var finalError=err;if(!isTypeOfError(err)){finalError=new Error("".concat(issue,": ").concat(stringifyWithoutCircular(err)));}else {finalError.message="".concat(issue,": ").concat(err.message);}return finalError;};var dispatchErrorEvent=function dispatchErrorEvent(error){if(isTypeOfError(error)){var errStack=getStacktrace(error);if(errStack){var stack=error.stack,stacktrace=error.stacktrace;var operaSourceloc=error['opera#sourceloc'];switch(errStack){case stack:// eslint-disable-next-line no-param-reassign
1042
+ error.stack="".concat(stack,"\n").concat(MANUAL_ERROR_IDENTIFIER);break;case stacktrace:// eslint-disable-next-line no-param-reassign
1043
+ error.stacktrace="".concat(stacktrace,"\n").concat(MANUAL_ERROR_IDENTIFIER);break;case operaSourceloc:default:// eslint-disable-next-line no-param-reassign
1044
+ error['opera#sourceloc']="".concat(operaSourceloc,"\n").concat(MANUAL_ERROR_IDENTIFIER);break;}}}globalThis.dispatchEvent(new ErrorEvent('error',{error:error,bubbles:true,cancelable:true,composed:true}));};
1042
1045
 
1043
- var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.13.0';var APP_NAMESPACE='com.rudderlabs.javascript';var MODULE_TYPE='npm';var ADBLOCK_PAGE_CATEGORY='RudderJS-Initiated';var ADBLOCK_PAGE_NAME='ad-block page request';var ADBLOCK_PAGE_PATH='/ad-blocked';var GLOBAL_PRELOAD_BUFFER='preloadedEventsBuffer';var CONSENT_TRACK_EVENT_NAME='Consent Management Interaction';
1046
+ var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.15.0';var APP_NAMESPACE='com.rudderlabs.javascript';var MODULE_TYPE='npm';var ADBLOCK_PAGE_CATEGORY='RudderJS-Initiated';var ADBLOCK_PAGE_NAME='ad-block page request';var ADBLOCK_PAGE_PATH='/ad-blocked';var GLOBAL_PRELOAD_BUFFER='preloadedEventsBuffer';var CONSENT_TRACK_EVENT_NAME='Consent Management Interaction';
1044
1047
 
1045
1048
  var QUERY_PARAM_TRAIT_PREFIX='ajs_trait_';var QUERY_PARAM_PROPERTY_PREFIX='ajs_prop_';var QUERY_PARAM_ANONYMOUS_ID_KEY='ajs_aid';var QUERY_PARAM_USER_ID_KEY='ajs_uid';var QUERY_PARAM_TRACK_EVENT_NAME_KEY='ajs_event';
1046
1049
 
@@ -1125,11 +1128,11 @@ timeoutID=globalThis.setTimeout(function(){reject(new Error(SCRIPT_LOAD_TIMEOUT_
1125
1128
 
1126
1129
  /**
1127
1130
  * Service to load external resources/files
1128
- */var ExternalSrcLoader=/*#__PURE__*/function(){function ExternalSrcLoader(errorHandler,logger){var timeout=arguments.length>2&&arguments[2]!==undefined?arguments[2]:DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS;_classCallCheck(this,ExternalSrcLoader);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.timeout=timeout;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);}/**
1131
+ */var ExternalSrcLoader=/*#__PURE__*/function(){function ExternalSrcLoader(errorHandler,logger){var timeout=arguments.length>2&&arguments[2]!==undefined?arguments[2]:DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS;_classCallCheck(this,ExternalSrcLoader);this.errorHandler=errorHandler;this.logger=logger;this.timeout=timeout;this.onError=this.onError.bind(this);}/**
1129
1132
  * Load external resource of type javascript
1130
1133
  */return _createClass(ExternalSrcLoader,[{key:"loadJSFile",value:function loadJSFile(config){var _this=this;var url=config.url,id=config.id,timeout=config.timeout,async=config.async,callback=config.callback,extraAttributes=config.extraAttributes;var isFireAndForget=!isFunction(callback);jsFileLoader(url,id,timeout||this.timeout,async,extraAttributes).then(function(id){if(!isFireAndForget){callback(id);}}).catch(function(err){_this.onError(err);if(!isFireAndForget){callback();}});}/**
1131
1134
  * Handle errors
1132
- */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===undefined||_this$errorHandler.onError(error,EXTERNAL_SRC_LOADER);}else {throw error;}}}]);}();
1135
+ */},{key:"onError",value:function onError(error){this.errorHandler.onError(error,EXTERNAL_SRC_LOADER);}}]);}();
1133
1136
 
1134
1137
  var i$2=Symbol.for("preact-signals");function t$1(){if(!(s>1)){var i,t=false;while(undefined!==h){var r=h;h=undefined;f++;while(undefined!==r){var o=r.o;r.o=undefined;r.f&=-3;if(!(8&r.f)&&c(r))try{r.c();}catch(r){if(!t){i=r;t=true;}}r=o;}}f=0;s--;if(t)throw i;}else s--;}function r(i){if(s>0)return i();s++;try{return i();}finally{t$1();}}var o=undefined;var h=undefined,s=0,f=0,v=0;function e(i){if(undefined!==o){var t=i.n;if(undefined===t||t.t!==o){t={i:0,S:i,p:o.s,n:undefined,t:o,e:undefined,x:undefined,r:t};if(undefined!==o.s)o.s.n=t;o.s=t;i.n=t;if(32&o.f)i.S(t);return t;}else if(-1===t.i){t.i=0;if(undefined!==t.n){t.n.p=t.p;if(undefined!==t.p)t.p.n=t.n;t.p=o.s;t.n=undefined;o.s.n=t;o.s=t;}return t;}}}function u(i){this.v=i;this.i=0;this.n=undefined;this.t=undefined;}u.prototype.brand=i$2;u.prototype.h=function(){return true;};u.prototype.S=function(i){if(this.t!==i&&undefined===i.e){i.x=this.t;if(undefined!==this.t)this.t.e=i;this.t=i;}};u.prototype.U=function(i){if(undefined!==this.t){var t=i.e,r=i.x;if(undefined!==t){t.x=r;i.e=undefined;}if(undefined!==r){r.e=t;i.x=undefined;}if(i===this.t)this.t=r;}};u.prototype.subscribe=function(i){var t=this;return E(function(){var r=t.value,n=o;o=undefined;try{i(r);}finally{o=n;}});};u.prototype.valueOf=function(){return this.value;};u.prototype.toString=function(){return this.value+"";};u.prototype.toJSON=function(){return this.value;};u.prototype.peek=function(){var i=o;o=undefined;try{return this.value;}finally{o=i;}};Object.defineProperty(u.prototype,"value",{get:function get(){var i=e(this);if(undefined!==i)i.i=this.i;return this.v;},set:function set(i){if(i!==this.v){if(f>100)throw new Error("Cycle detected");this.v=i;this.i++;v++;s++;try{for(var r=this.t;void 0!==r;r=r.x)r.t.N();}finally{t$1();}}}});function d$1(i){return new u(i);}function c(i){for(var t=i.s;undefined!==t;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return true;return false;}function a(i){for(var t=i.s;undefined!==t;t=t.n){var r=t.S.n;if(undefined!==r)t.r=r;t.S.n=t;t.i=-1;if(undefined===t.n){i.s=t;break;}}}function l(i){var t=i.s,r=undefined;while(undefined!==t){var o=t.p;if(-1===t.i){t.S.U(t);if(undefined!==o)o.n=t.n;if(undefined!==t.n)t.n.p=o;}else r=t;t.S.n=t.r;if(undefined!==t.r)t.r=undefined;t=o;}i.s=r;}function y(i){u.call(this,undefined);this.x=i;this.s=undefined;this.g=v-1;this.f=4;}(y.prototype=new u()).h=function(){this.f&=-3;if(1&this.f)return false;if(32==(36&this.f))return true;this.f&=-5;if(this.g===v)return true;this.g=v;this.f|=1;if(this.i>0&&!c(this)){this.f&=-2;return true;}var i=o;try{a(this);o=this;var t=this.x();if(16&this.f||this.v!==t||0===this.i){this.v=t;this.f&=-17;this.i++;}}catch(i){this.v=i;this.f|=16;this.i++;}o=i;l(this);this.f&=-2;return true;};y.prototype.S=function(i){if(undefined===this.t){this.f|=36;for(var t=this.s;undefined!==t;t=t.n)t.S.S(t);}u.prototype.S.call(this,i);};y.prototype.U=function(i){if(undefined!==this.t){u.prototype.U.call(this,i);if(undefined===this.t){this.f&=-33;for(var t=this.s;undefined!==t;t=t.n)t.S.U(t);}}};y.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var i=this.t;undefined!==i;i=i.x)i.t.N();}};Object.defineProperty(y.prototype,"value",{get:function get(){if(1&this.f)throw new Error("Cycle detected");var i=e(this);this.h();if(undefined!==i)i.i=this.i;if(16&this.f)throw this.v;return this.v;}});function _(i){var r=i.u;i.u=undefined;if("function"==typeof r){s++;var n=o;o=undefined;try{r();}catch(t){i.f&=-2;i.f|=8;g(i);throw t;}finally{o=n;t$1();}}}function g(i){for(var t=i.s;undefined!==t;t=t.n)t.S.U(t);i.x=undefined;i.s=undefined;_(i);}function p(i){if(o!==this)throw new Error("Out-of-order effect");l(this);o=i;this.f&=-2;if(8&this.f)g(this);t$1();}function b(i){this.x=i;this.u=undefined;this.s=undefined;this.o=undefined;this.f=32;}b.prototype.c=function(){var i=this.S();try{if(8&this.f)return;if(void 0===this.x)return;var t=this.x();if("function"==typeof t)this.u=t;}finally{i();}};b.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1;this.f&=-9;_(this);a(this);s++;var i=o;o=this;return p.bind(this,i);};b.prototype.N=function(){if(!(2&this.f)){this.f|=2;this.o=h;h=this;}};b.prototype.d=function(){this.f|=8;if(!(1&this.f))g(this);};function E(i){var t=new b(i);try{t.c();}catch(i){t.d();throw i;}return t.d.bind(t);}
1135
1138
 
@@ -1158,9 +1161,9 @@ var ErrorType=/*#__PURE__*/function(ErrorType){ErrorType["HANDLEDEXCEPTION"]="ha
1158
1161
  // default is v3
1159
1162
  var SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','sessionStorage','none'];var DEFAULT_STORAGE_TYPE='cookieStorage';
1160
1163
 
1161
- var SOURCE_CONFIG_OPTION_ERROR="\"getSourceConfig\" must be a function. Please make sure that it is defined and returns a valid source configuration object.";var SOURCE_CONFIG_RESOLUTION_ERROR="Unable to process/parse source configuration response.";var SOURCE_DISABLED_ERROR="The source is disabled. Please enable the source in the dashboard to send events.";var XHR_PAYLOAD_PREP_ERROR="Failed to prepare data for the request.";var EVENT_OBJECT_GENERATION_ERROR="Failed to generate the event object.";var PLUGIN_EXT_POINT_MISSING_ERROR="Failed to invoke plugin because the extension point name is missing.";var PLUGIN_EXT_POINT_INVALID_ERROR="Failed to invoke plugin because the extension point name is invalid.";var COMPONENT_BASE_URL_ERROR=function COMPONENT_BASE_URL_ERROR(component,url){return "Failed to load the SDK as the base URL \"".concat(url,"\" for ").concat(component," is not valid.");};// ERROR
1162
- var UNSUPPORTED_CONSENT_MANAGER_ERROR=function UNSUPPORTED_CONSENT_MANAGER_ERROR(context,selectedConsentManager,consentManagersToPluginNameMap){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The consent manager \"").concat(selectedConsentManager,"\" is not supported. Please choose one of the following supported consent managers: \"").concat(Object.keys(consentManagersToPluginNameMap),"\".");};var REPORTING_PLUGIN_INIT_FAILURE_ERROR=function REPORTING_PLUGIN_INIT_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to initialize the error reporting plugin.");};var NOTIFY_FAILURE_ERROR=function NOTIFY_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to notify the error.");};var PLUGIN_NAME_MISSING_ERROR=function PLUGIN_NAME_MISSING_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin name is missing.");};var PLUGIN_ALREADY_EXISTS_ERROR=function PLUGIN_ALREADY_EXISTS_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" already exists.");};var PLUGIN_NOT_FOUND_ERROR=function PLUGIN_NOT_FOUND_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found.");};var PLUGIN_ENGINE_BUG_ERROR=function PLUGIN_ENGINE_BUG_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.");};var PLUGIN_DEPS_ERROR=function PLUGIN_DEPS_ERROR(context,pluginName,notExistDeps){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" could not be loaded because some of its dependencies \"").concat(notExistDeps,"\" do not exist.");};var PLUGIN_INVOCATION_ERROR=function PLUGIN_INVOCATION_ERROR(context,extPoint,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to invoke the \"").concat(extPoint,"\" extension point of plugin \"").concat(pluginName,"\".");};var STORAGE_UNAVAILABILITY_ERROR_PREFIX=function STORAGE_UNAVAILABILITY_ERROR_PREFIX(context,storageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(storageType,"\" storage type is ");};var SOURCE_CONFIG_FETCH_ERROR=function SOURCE_CONFIG_FETCH_ERROR(reason){return "Failed to fetch the source config. Reason: ".concat(reason);};var WRITE_KEY_VALIDATION_ERROR=function WRITE_KEY_VALIDATION_ERROR(context,writeKey){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The write key \"").concat(writeKey,"\" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.");};var DATA_PLANE_URL_VALIDATION_ERROR=function DATA_PLANE_URL_VALIDATION_ERROR(context,dataPlaneUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The data plane URL \"").concat(dataPlaneUrl,"\" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.");};var READY_API_CALLBACK_ERROR=function READY_API_CALLBACK_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided callback is not a function.");};var XHR_DELIVERY_ERROR=function XHR_DELIVERY_ERROR(prefix,status,statusText,url){return "".concat(prefix," with status: ").concat(status,", ").concat(statusText," for URL: ").concat(url,".");};var XHR_REQUEST_ERROR=function XHR_REQUEST_ERROR(prefix,e,url){return "".concat(prefix," due to timeout or no connection (").concat(e?e.type:'',") for URL: ").concat(url,".");};var XHR_SEND_ERROR=function XHR_SEND_ERROR(prefix,url){return "".concat(prefix," for URL: ").concat(url);};var STORE_DATA_SAVE_ERROR=function STORE_DATA_SAVE_ERROR(key){return "Failed to save the value for \"".concat(key,"\" to storage");};var STORE_DATA_FETCH_ERROR=function STORE_DATA_FETCH_ERROR(key){return "Failed to retrieve or parse data for \"".concat(key,"\" from storage");};var DATA_SERVER_REQUEST_FAIL_ERROR=function DATA_SERVER_REQUEST_FAIL_ERROR(status){return "The server responded with status ".concat(status," while setting the cookies. As a fallback, the cookies will be set client side.");};var FAILED_SETTING_COOKIE_FROM_SERVER_ERROR=function FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(key){return "The server failed to set the ".concat(key," cookie. As a fallback, the cookies will be set client side.");};var FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR="Failed to set/remove cookies via server. As a fallback, the cookies will be managed client side.";// WARNING
1163
- var STORAGE_TYPE_VALIDATION_WARNING=function STORAGE_TYPE_VALIDATION_WARNING(context,storageType,defaultStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(storageType,"\" is not supported. Please choose one of the following supported types: \"").concat(SUPPORTED_STORAGE_TYPES,"\". The default type \"").concat(defaultStorageType,"\" will be used instead.");};var UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING=function UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(context,selectedStorageEncryptionVersion,storageEncryptionVersionsToPluginNameMap,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage encryption version \"").concat(selectedStorageEncryptionVersion,"\" is not supported. Please choose one of the following supported versions: \"").concat(Object.keys(storageEncryptionVersionsToPluginNameMap),"\". The default version \"").concat(defaultVersion,"\" will be used instead.");};var STORAGE_DATA_MIGRATION_OVERRIDE_WARNING=function STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(context,storageEncryptionVersion,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage data migration has been disabled because the configured storage encryption version (").concat(storageEncryptionVersion,") is not the latest (").concat(defaultVersion,"). To enable storage data migration, please update the storage encryption version to the latest version.");};var SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING=function SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING(context,providedCookieDomain,currentCookieDomain){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided cookie domain (").concat(providedCookieDomain,") does not match the current webpage's domain (").concat(currentCookieDomain,"). Hence, the cookies will be set client-side.");};var RESERVED_KEYWORD_WARNING=function RESERVED_KEYWORD_WARNING(context,property,parentKeyPath,reservedElements){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(property,"\" property defined under \"").concat(parentKeyPath,"\" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (").concat(reservedElements,").");};var UNSUPPORTED_BEACON_API_WARNING=function UNSUPPORTED_BEACON_API_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The Beacon API is not supported by your browser. The events will be sent using XHR instead.");};var TIMEOUT_NOT_NUMBER_WARNING=function TIMEOUT_NOT_NUMBER_WARNING(context,timeout,defaultValue){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value \"").concat(timeout,"\" is not a number. The default timeout of ").concat(defaultValue," ms will be used instead.");};var TIMEOUT_ZERO_WARNING=function TIMEOUT_ZERO_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value is 0, which disables the automatic session tracking feature. If you want to enable session tracking, please provide a positive integer value for the timeout.");};var TIMEOUT_NOT_RECOMMENDED_WARNING=function TIMEOUT_NOT_RECOMMENDED_WARNING(context,timeout,minTimeout){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value ").concat(timeout," ms is less than the recommended minimum of ").concat(minTimeout," ms. Please consider increasing the timeout value to ensure optimal performance and reliability.");};var INVALID_SESSION_ID_WARNING=function INVALID_SESSION_ID_WARNING(context,sessionId,minSessionIdLength){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided session ID (").concat(sessionId,") is either invalid, not a positive integer, or not at least \"").concat(minSessionIdLength,"\" digits long. A new session ID will be auto-generated instead.");};var STORAGE_QUOTA_EXCEEDED_WARNING=function STORAGE_QUOTA_EXCEEDED_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.");};var STORAGE_UNAVAILABLE_WARNING=function STORAGE_UNAVAILABLE_WARNING(context,entry,selectedStorageType,finalStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(selectedStorageType,"\" is not available for entry \"").concat(entry,"\". The SDK will initialize the entry with \"").concat(finalStorageType,"\" storage type instead.");};var READY_CALLBACK_INVOKE_ERROR="Failed to invoke the ready callback";var API_CALLBACK_INVOKE_ERROR="API Callback Invocation Failed";var NATIVE_DEST_PLUGIN_INITIALIZE_ERROR="NativeDestinationQueuePlugin initialization failed";var DATAPLANE_PLUGIN_INITIALIZE_ERROR="XhrQueuePlugin initialization failed";var DMT_PLUGIN_INITIALIZE_ERROR="DeviceModeTransformationPlugin initialization failed";var NATIVE_DEST_PLUGIN_ENQUEUE_ERROR="NativeDestinationQueuePlugin event enqueue failed";var DATAPLANE_PLUGIN_ENQUEUE_ERROR="XhrQueuePlugin event enqueue failed";var INVALID_CONFIG_URL_WARNING=function INVALID_CONFIG_URL_WARNING(context,configUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided source config URL \"").concat(configUrl,"\" is invalid. Using the default source config URL instead.");};var POLYFILL_SCRIPT_LOAD_ERROR=function POLYFILL_SCRIPT_LOAD_ERROR(scriptId,url){return "Failed to load the polyfill script with ID \"".concat(scriptId,"\" from URL ").concat(url,".");};var UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY=function UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(context,selectedStrategy,defaultStrategy){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent storage strategy \"").concat(selectedStrategy,"\" is not supported. Please choose one of the following supported strategies: \"none, session, anonymousId\". The default strategy \"").concat(defaultStrategy,"\" will be used instead.");};var UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE=function UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(context,selectedDeliveryType,defaultDeliveryType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent events delivery type \"").concat(selectedDeliveryType,"\" is not supported. Please choose one of the following supported types: \"immediate, buffer\". The default type \"").concat(defaultDeliveryType,"\" will be used instead.");};var generateMisconfiguredPluginsWarning=function generateMisconfiguredPluginsWarning(context,configurationStatus,missingPlugins,shouldAddMissingPlugins){var isSinglePlugin=missingPlugins.length===1;var pluginsString=isSinglePlugin?" '".concat(missingPlugins[0],"' plugin was"):" ['".concat(missingPlugins.join("', '"),"'] plugins were");var baseWarning="".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(configurationStatus,", but").concat(pluginsString," not configured to load.");if(shouldAddMissingPlugins){return "".concat(baseWarning," So, ").concat(isSinglePlugin?'the plugin':'those plugins'," will be loaded automatically.");}return "".concat(baseWarning," Ignore if this was intentional. Otherwise, consider adding ").concat(isSinglePlugin?'it':'them'," to the 'plugins' load API option.");};var INVALID_POLYFILL_URL_WARNING=function INVALID_POLYFILL_URL_WARNING(context,customPolyfillUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided polyfill URL \"").concat(customPolyfillUrl,"\" is invalid. The default polyfill URL will be used instead.");};var BAD_COOKIES_WARNING=function BAD_COOKIES_WARNING(key){return "The cookie data for ".concat(key," seems to be encrypted using SDK versions < v3. The data is dropped. This can potentially stem from using SDK versions < v3 on other sites or web pages that can share cookies with this webpage. We recommend using the same SDK (v3) version everywhere or avoid disabling the storage data migration.");};var PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING=function PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Page Unloaded event can only be tracked when the Beacon transport is active. Please enable \"useBeacon\" load API option.");};
1164
+ var SOURCE_CONFIG_RESOLUTION_ERROR="Unable to process/parse source configuration response";var SOURCE_DISABLED_ERROR="The source is disabled. Please enable the source in the dashboard to send events.";var XHR_PAYLOAD_PREP_ERROR="Failed to prepare data for the request.";var PLUGIN_EXT_POINT_MISSING_ERROR="Failed to invoke plugin because the extension point name is missing.";var PLUGIN_EXT_POINT_INVALID_ERROR="Failed to invoke plugin because the extension point name is invalid.";var SOURCE_CONFIG_OPTION_ERROR=function SOURCE_CONFIG_OPTION_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"getSourceConfig\" load API option must be a function that returns valid source configuration data.");};var COMPONENT_BASE_URL_ERROR=function COMPONENT_BASE_URL_ERROR(context,component,url){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The base URL \"").concat(url,"\" for ").concat(component," is not valid.");};// ERROR
1165
+ var UNSUPPORTED_CONSENT_MANAGER_ERROR=function UNSUPPORTED_CONSENT_MANAGER_ERROR(context,selectedConsentManager,consentManagersToPluginNameMap){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The consent manager \"").concat(selectedConsentManager,"\" is not supported. Please choose one of the following supported consent managers: \"").concat(Object.keys(consentManagersToPluginNameMap),"\".");};var NON_ERROR_WARNING=function NON_ERROR_WARNING(context,errStr){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Ignoring a non-error: ").concat(errStr,".");};var BREADCRUMB_ERROR=function BREADCRUMB_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to log breadcrumb.");};var HANDLE_ERROR_FAILURE=function HANDLE_ERROR_FAILURE(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to handle the error.");};var PLUGIN_NAME_MISSING_ERROR=function PLUGIN_NAME_MISSING_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin name is missing.");};var PLUGIN_ALREADY_EXISTS_ERROR=function PLUGIN_ALREADY_EXISTS_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" already exists.");};var PLUGIN_NOT_FOUND_ERROR=function PLUGIN_NOT_FOUND_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found.");};var PLUGIN_ENGINE_BUG_ERROR=function PLUGIN_ENGINE_BUG_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.");};var PLUGIN_DEPS_ERROR=function PLUGIN_DEPS_ERROR(context,pluginName,notExistDeps){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" could not be loaded because some of its dependencies \"").concat(notExistDeps,"\" do not exist.");};var PLUGIN_INVOCATION_ERROR=function PLUGIN_INVOCATION_ERROR(context,extPoint,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to invoke the \"").concat(extPoint,"\" extension point of plugin \"").concat(pluginName,"\".");};var STORAGE_UNAVAILABILITY_ERROR_PREFIX=function STORAGE_UNAVAILABILITY_ERROR_PREFIX(context,storageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(storageType,"\" storage type is ");};var SOURCE_CONFIG_FETCH_ERROR='Failed to fetch the source config';var WRITE_KEY_VALIDATION_ERROR=function WRITE_KEY_VALIDATION_ERROR(context,writeKey){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The write key \"").concat(writeKey,"\" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.");};var DATA_PLANE_URL_VALIDATION_ERROR=function DATA_PLANE_URL_VALIDATION_ERROR(context,dataPlaneUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The data plane URL \"").concat(dataPlaneUrl,"\" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.");};var INVALID_CALLBACK_FN_ERROR=function INVALID_CALLBACK_FN_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided callback parameter is not a function.");};var XHR_DELIVERY_ERROR=function XHR_DELIVERY_ERROR(prefix,status,statusText,url){return "".concat(prefix," with status: ").concat(status,", ").concat(statusText," for URL: ").concat(url,".");};var XHR_REQUEST_ERROR=function XHR_REQUEST_ERROR(prefix,e,url){return "".concat(prefix," due to timeout or no connection (").concat(e?e.type:'',") for URL: ").concat(url,".");};var XHR_SEND_ERROR=function XHR_SEND_ERROR(prefix,url){return "".concat(prefix," for URL: ").concat(url);};var STORE_DATA_SAVE_ERROR=function STORE_DATA_SAVE_ERROR(key){return "Failed to save the value for \"".concat(key,"\" to storage");};var STORE_DATA_FETCH_ERROR=function STORE_DATA_FETCH_ERROR(key){return "Failed to retrieve or parse data for \"".concat(key,"\" from storage");};var DATA_SERVER_REQUEST_FAIL_ERROR=function DATA_SERVER_REQUEST_FAIL_ERROR(status){return "The server responded with status ".concat(status," while setting the cookies. As a fallback, the cookies will be set client side.");};var FAILED_SETTING_COOKIE_FROM_SERVER_ERROR=function FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(key){return "The server failed to set the ".concat(key," cookie. As a fallback, the cookies will be set client side.");};var FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR="Failed to set/remove cookies via server. As a fallback, the cookies will be managed client side.";// WARNING
1166
+ var STORAGE_TYPE_VALIDATION_WARNING=function STORAGE_TYPE_VALIDATION_WARNING(context,storageType,defaultStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(storageType,"\" is not supported. Please choose one of the following supported types: \"").concat(SUPPORTED_STORAGE_TYPES,"\". The default type \"").concat(defaultStorageType,"\" will be used instead.");};var UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING=function UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(context,selectedStorageEncryptionVersion,storageEncryptionVersionsToPluginNameMap,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage encryption version \"").concat(selectedStorageEncryptionVersion,"\" is not supported. Please choose one of the following supported versions: \"").concat(Object.keys(storageEncryptionVersionsToPluginNameMap),"\". The default version \"").concat(defaultVersion,"\" will be used instead.");};var STORAGE_DATA_MIGRATION_OVERRIDE_WARNING=function STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(context,storageEncryptionVersion,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage data migration has been disabled because the configured storage encryption version (").concat(storageEncryptionVersion,") is not the latest (").concat(defaultVersion,"). To enable storage data migration, please update the storage encryption version to the latest version.");};var SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING=function SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING(context,providedCookieDomain,currentCookieDomain){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided cookie domain (").concat(providedCookieDomain,") does not match the current webpage's domain (").concat(currentCookieDomain,"). Hence, the cookies will be set client-side.");};var RESERVED_KEYWORD_WARNING=function RESERVED_KEYWORD_WARNING(context,property,parentKeyPath,reservedElements){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(property,"\" property defined under \"").concat(parentKeyPath,"\" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (").concat(reservedElements,").");};var INVALID_CONTEXT_OBJECT_WARNING=function INVALID_CONTEXT_OBJECT_WARNING(logContext){return "".concat(logContext).concat(LOG_CONTEXT_SEPARATOR,"Please make sure that the \"context\" property in the event API's \"options\" argument is a valid object literal with key-value pairs.");};var UNSUPPORTED_BEACON_API_WARNING=function UNSUPPORTED_BEACON_API_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The Beacon API is not supported by your browser. The events will be sent using XHR instead.");};var TIMEOUT_NOT_NUMBER_WARNING=function TIMEOUT_NOT_NUMBER_WARNING(context,timeout,defaultValue){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value \"").concat(timeout,"\" is not a number. The default timeout of ").concat(defaultValue," ms will be used instead.");};var TIMEOUT_ZERO_WARNING=function TIMEOUT_ZERO_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value is 0, which disables the automatic session tracking feature. If you want to enable session tracking, please provide a positive integer value for the timeout.");};var TIMEOUT_NOT_RECOMMENDED_WARNING=function TIMEOUT_NOT_RECOMMENDED_WARNING(context,timeout,minTimeout){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value ").concat(timeout," ms is less than the recommended minimum of ").concat(minTimeout," ms. Please consider increasing the timeout value to ensure optimal performance and reliability.");};var INVALID_SESSION_ID_WARNING=function INVALID_SESSION_ID_WARNING(context,sessionId,minSessionIdLength){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided session ID (").concat(sessionId,") is either invalid, not a positive integer, or not at least \"").concat(minSessionIdLength,"\" digits long. A new session ID will be auto-generated instead.");};var STORAGE_QUOTA_EXCEEDED_WARNING=function STORAGE_QUOTA_EXCEEDED_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.");};var STORAGE_UNAVAILABLE_WARNING=function STORAGE_UNAVAILABLE_WARNING(context,entry,selectedStorageType,finalStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(selectedStorageType,"\" is not available for entry \"").concat(entry,"\". The SDK will initialize the entry with \"").concat(finalStorageType,"\" storage type instead.");};var CALLBACK_INVOKE_ERROR=function CALLBACK_INVOKE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The callback threw an exception");};var INVALID_CONFIG_URL_WARNING=function INVALID_CONFIG_URL_WARNING(context,configUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided source config URL \"").concat(configUrl,"\" is invalid. Using the default source config URL instead.");};var POLYFILL_SCRIPT_LOAD_ERROR=function POLYFILL_SCRIPT_LOAD_ERROR(scriptId,url){return "Failed to load the polyfill script with ID \"".concat(scriptId,"\" from URL ").concat(url,".");};var UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY=function UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(context,selectedStrategy,defaultStrategy){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent storage strategy \"").concat(selectedStrategy,"\" is not supported. Please choose one of the following supported strategies: \"none, session, anonymousId\". The default strategy \"").concat(defaultStrategy,"\" will be used instead.");};var UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE=function UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(context,selectedDeliveryType,defaultDeliveryType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent events delivery type \"").concat(selectedDeliveryType,"\" is not supported. Please choose one of the following supported types: \"immediate, buffer\". The default type \"").concat(defaultDeliveryType,"\" will be used instead.");};var DEPRECATED_PLUGIN_WARNING=function DEPRECATED_PLUGIN_WARNING(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(pluginName," plugin is deprecated. Please exclude it from the load API options.");};var generateMisconfiguredPluginsWarning=function generateMisconfiguredPluginsWarning(context,configurationStatus,missingPlugins,shouldAddMissingPlugins){var isSinglePlugin=missingPlugins.length===1;var pluginsString=isSinglePlugin?" '".concat(missingPlugins[0],"' plugin was"):" ['".concat(missingPlugins.join("', '"),"'] plugins were");var baseWarning="".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(configurationStatus,", but").concat(pluginsString," not configured to load.");if(shouldAddMissingPlugins){return "".concat(baseWarning," So, ").concat(isSinglePlugin?'the plugin':'those plugins'," will be loaded automatically.");}return "".concat(baseWarning," Ignore if this was intentional. Otherwise, consider adding ").concat(isSinglePlugin?'it':'them'," to the 'plugins' load API option.");};var INVALID_POLYFILL_URL_WARNING=function INVALID_POLYFILL_URL_WARNING(context,customPolyfillUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided polyfill URL \"").concat(customPolyfillUrl,"\" is invalid. The default polyfill URL will be used instead.");};var BAD_COOKIES_WARNING=function BAD_COOKIES_WARNING(key){return "The cookie data for ".concat(key," seems to be encrypted using SDK versions < v3. The data is dropped. This can potentially stem from using SDK versions < v3 on other sites or web pages that can share cookies with this webpage. We recommend using the same SDK (v3) version everywhere or avoid disabling the storage data migration.");};var PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING=function PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Page Unloaded event can only be tracked when the Beacon transport is active. Please enable \"useBeacon\" load API option.");};var UNKNOWN_PLUGINS_WARNING=function UNKNOWN_PLUGINS_WARNING(context,unknownPlugins){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Ignoring unknown plugins: ").concat(unknownPlugins.join(', '),".");};
1164
1167
 
1165
1168
  var DEFAULT_INTEGRATIONS_CONFIG={All:true};
1166
1169
 
@@ -1179,7 +1182,7 @@ var BUILD_TYPE='legacy';var SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';var CD
1179
1182
 
1180
1183
  var DEFAULT_STORAGE_ENCRYPTION_VERSION='v3';var DEFAULT_DATA_PLANE_EVENTS_TRANSPORT='xhr';var ConsentManagersToPluginNameMap={iubenda:'IubendaConsentManager',oneTrust:'OneTrustConsentManager',ketch:'KetchConsentManager',custom:'CustomConsentManager'};var StorageEncryptionVersionsToPluginNameMap=_defineProperty(_defineProperty({},DEFAULT_STORAGE_ENCRYPTION_VERSION,'StorageEncryption'),"legacy",'StorageEncryptionLegacy');var DataPlaneEventsTransportToPluginNameMap=_defineProperty(_defineProperty({},DEFAULT_DATA_PLANE_EVENTS_TRANSPORT,'XhrQueue'),"beacon",'BeaconQueue');var DEFAULT_DATA_SERVICE_ENDPOINT='rsaRequest';var METRICS_SERVICE_ENDPOINT='rsaMetrics';
1181
1184
 
1182
- var defaultLoadOptions={logLevel:'ERROR',configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:DEFAULT_INTEGRATIONS_CONFIG,useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:true,lockPluginsVersion:true,uaChTrackLevel:'none',plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,dataPlaneEventsBufferTimeout:DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:true,cookie:{}},sendAdblockPage:false,sameDomainCookiesOnly:false,secureCookie:false,sendAdblockPageOptions:{},useServerSideCookies:false};var loadOptionsState=d$1(clone(defaultLoadOptions));
1185
+ var defaultLoadOptions={configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:DEFAULT_INTEGRATIONS_CONFIG,useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:true,lockPluginsVersion:true,uaChTrackLevel:'none',plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,dataPlaneEventsBufferTimeout:DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:true,cookie:{}},sendAdblockPage:false,sameDomainCookiesOnly:false,secureCookie:false,sendAdblockPageOptions:{},useServerSideCookies:false};var loadOptionsState=d$1(clone(defaultLoadOptions));
1183
1186
 
1184
1187
  var DEFAULT_USER_SESSION_VALUES={userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{},authToken:null};var SERVER_SIDE_COOKIES_DEBOUNCE_TIME=10;// milliseconds
1185
1188
 
@@ -1187,17 +1190,17 @@ var defaultSessionConfiguration={autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_
1187
1190
 
1188
1191
  var capabilitiesState={isOnline:d$1(true),storage:{isLocalStorageAvailable:d$1(false),isCookieStorageAvailable:d$1(false),isSessionStorageAvailable:d$1(false)},isBeaconAvailable:d$1(false),isLegacyDOM:d$1(false),isUaCHAvailable:d$1(false),isCryptoAvailable:d$1(false),isIE11:d$1(false),isAdBlocked:d$1(false)};
1189
1192
 
1190
- var reportingState={isErrorReportingEnabled:d$1(false),isMetricsReportingEnabled:d$1(false),isErrorReportingPluginLoaded:d$1(false),breadcrumbs:d$1([])};
1193
+ var reportingState={isErrorReportingEnabled:d$1(false),isMetricsReportingEnabled:d$1(false),breadcrumbs:d$1([])};
1191
1194
 
1192
1195
  var sourceConfigState=d$1(undefined);
1193
1196
 
1194
- var lifecycleState={activeDataplaneUrl:d$1(undefined),integrationsCDNPath:d$1(DEFAULT_INTEGRATION_SDKS_URL),pluginsCDNPath:d$1(DEFAULT_PLUGINS_URL),sourceConfigUrl:d$1(undefined),status:d$1(undefined),initialized:d$1(false),logLevel:d$1('ERROR'),loaded:d$1(false),readyCallbacks:d$1([]),writeKey:d$1(undefined),dataPlaneUrl:d$1(undefined)};
1197
+ var lifecycleState={activeDataplaneUrl:d$1(undefined),integrationsCDNPath:d$1(DEFAULT_INTEGRATION_SDKS_URL),pluginsCDNPath:d$1(DEFAULT_PLUGINS_URL),sourceConfigUrl:d$1(undefined),status:d$1(undefined),initialized:d$1(false),logLevel:d$1(POST_LOAD_LOG_LEVEL),loaded:d$1(false),readyCallbacks:d$1([]),writeKey:d$1(undefined),dataPlaneUrl:d$1(undefined)};
1195
1198
 
1196
1199
  var consentsState={enabled:d$1(false),initialized:d$1(false),data:d$1({}),activeConsentManagerPluginName:d$1(undefined),preConsent:d$1({enabled:false}),postConsent:d$1({}),resolutionStrategy:d$1('and'),provider:d$1(undefined),metadata:d$1(undefined)};
1197
1200
 
1198
1201
  var metricsState={retries:d$1(0),dropped:d$1(0),sent:d$1(0),queued:d$1(0),triggered:d$1(0),metricsServiceUrl:d$1(undefined)};
1199
1202
 
1200
- var contextState={app:d$1({name:APP_NAME,namespace:APP_NAMESPACE,version:APP_VERSION,installType:MODULE_TYPE}),traits:d$1(null),library:d$1({name:APP_NAME,version:APP_VERSION,snippetVersion:globalThis.RudderSnippetVersion}),userAgent:d$1(''),device:d$1(null),network:d$1(null),os:d$1({name:'',version:''}),locale:d$1(null),screen:d$1({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),'ua-ch':d$1(undefined),timezone:d$1(undefined)};
1203
+ var contextState={app:d$1({name:APP_NAME,namespace:APP_NAMESPACE,version:APP_VERSION,installType:MODULE_TYPE}),traits:d$1(null),library:d$1({name:APP_NAME,version:APP_VERSION,snippetVersion:globalThis.RudderSnippetVersion}),userAgent:d$1(null),device:d$1(null),network:d$1(null),os:d$1({name:'',version:''}),locale:d$1(null),screen:d$1({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),'ua-ch':d$1(undefined),timezone:d$1(undefined)};
1201
1204
 
1202
1205
  var nativeDestinationsState={configuredDestinations:d$1([]),activeDestinations:d$1([]),loadOnlyIntegrations:d$1({}),failedDestinations:d$1([]),loadIntegration:d$1(true),initializedDestinations:d$1([]),clientDestinationsReady:d$1(false),integrationsConfig:d$1({})};
1203
1206
 
@@ -1216,48 +1219,130 @@ var autoTrackState={enabled:d$1(false),pageLifecycle:{enabled:d$1(false),visitId
1216
1219
 
1217
1220
  var defaultStateValues={capabilities:capabilitiesState,consents:consentsState,context:contextState,eventBuffer:eventBufferState,lifecycle:lifecycleState,loadOptions:loadOptionsState,metrics:metricsState,nativeDestinations:nativeDestinationsState,plugins:pluginsState,reporting:reportingState,session:sessionState,source:sourceConfigState,storage:storageState,serverCookies:serverSideCookiesState,dataPlaneEvents:dataPlaneEventsState,autoTrack:autoTrackState};var state=_objectSpread2({},clone(defaultStateValues));
1218
1221
 
1219
- // to next or return the value if it is the last one instead of an array per
1220
- // plugin that is the normal invoke
1221
- // TODO: add invoke method for extension point that we know only one plugin can be used. add invokeMultiple and invokeSingle methods
1222
- var PluginEngine=/*#__PURE__*/function(){function PluginEngine(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var logger=arguments.length>1?arguments[1]:undefined;_classCallCheck(this,PluginEngine);_defineProperty(this,"plugins",[]);_defineProperty(this,"byName",{});_defineProperty(this,"cache",{});_defineProperty(this,"config",{throws:true});this.config=_objectSpread2({throws:true},options);this.logger=logger;}return _createClass(PluginEngine,[{key:"register",value:function register(plugin,state){if(!plugin.name){var errorMessage=PLUGIN_NAME_MISSING_ERROR(PLUGIN_ENGINE);if(this.config.throws){throw new Error(errorMessage);}else {var _this$logger;(_this$logger=this.logger)===null||_this$logger===undefined||_this$logger.error(errorMessage,plugin);}}if(this.byName[plugin.name]){var _errorMessage=PLUGIN_ALREADY_EXISTS_ERROR(PLUGIN_ENGINE,plugin.name);if(this.config.throws){throw new Error(_errorMessage);}else {var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===undefined||_this$logger2.error(_errorMessage);}}this.cache={};this.plugins=this.plugins.slice();var pos=this.plugins.length;this.plugins.forEach(function(pluginItem,index){var _pluginItem$deps;if((_pluginItem$deps=pluginItem.deps)!==null&&_pluginItem$deps!==undefined&&_pluginItem$deps.includes(plugin.name)){pos=Math.min(pos,index);}});this.plugins.splice(pos,0,plugin);this.byName[plugin.name]=plugin;if(isFunction(plugin.initialize)){plugin.initialize(state);}}},{key:"unregister",value:function unregister(name){var plugin=this.byName[name];if(!plugin){var errorMessage=PLUGIN_NOT_FOUND_ERROR(PLUGIN_ENGINE,name);if(this.config.throws){throw new Error(errorMessage);}else {var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===undefined||_this$logger3.error(errorMessage);}}var index=this.plugins.indexOf(plugin);if(index===-1){var _errorMessage2=PLUGIN_ENGINE_BUG_ERROR(PLUGIN_ENGINE,name);if(this.config.throws){throw new Error(_errorMessage2);}else {var _this$logger4;(_this$logger4=this.logger)===null||_this$logger4===undefined||_this$logger4.error(_errorMessage2);}}this.cache={};delete this.byName[name];this.plugins=this.plugins.slice();this.plugins.splice(index,1);}},{key:"getPlugin",value:function getPlugin(name){return this.byName[name];}},{key:"getPlugins",value:function getPlugins(extPoint){var _this=this;var lifeCycleName=extPoint!==null&&extPoint!==undefined?extPoint:'.';if(!this.cache[lifeCycleName]){this.cache[lifeCycleName]=this.plugins.filter(function(plugin){var _plugin$deps;if((_plugin$deps=plugin.deps)!==null&&_plugin$deps!==undefined&&_plugin$deps.some(function(dependency){return !_this.byName[dependency];})){var _this$logger5;// If deps not exist, then not load it.
1223
- var notExistDeps=plugin.deps.filter(function(dependency){return !_this.byName[dependency];});(_this$logger5=_this.logger)===null||_this$logger5===undefined||_this$logger5.error(PLUGIN_DEPS_ERROR(PLUGIN_ENGINE,plugin.name,notExistDeps));return false;}return lifeCycleName==='.'?true:hasValueByPath(plugin,lifeCycleName);});}return this.cache[lifeCycleName];}// This method allows to process this.plugins so that it could
1224
- // do some unified pre-process before application starts.
1225
- },{key:"processRawPlugins",value:function processRawPlugins(callback){callback(this.plugins);this.cache={};}},{key:"invoke",value:function invoke(extPoint){var _this$config$throws,_this2=this;var allowMultiple=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;for(var _len=arguments.length,args=new Array(_len>2?_len-2:0),_key=2;_key<_len;_key++){args[_key-2]=arguments[_key];}var extensionPointName=extPoint;if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_MISSING_ERROR);}var noCall=extensionPointName.startsWith('!');var throws=(_this$config$throws=this.config.throws)!==null&&_this$config$throws!==undefined?_this$config$throws:extensionPointName.endsWith('!');// eslint-disable-next-line unicorn/better-regex
1226
- extensionPointName=extensionPointName.replace(/(^!|!$)/g,'');if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_INVALID_ERROR);}var extensionPointNameParts=extensionPointName.split('.');extensionPointNameParts.pop();var pluginMethodPath=extensionPointNameParts.join('.');var pluginsToInvoke=allowMultiple?this.getPlugins(extensionPointName):[this.getPlugins(extensionPointName)[0]];return pluginsToInvoke.map(function(plugin){var method=getValueByPath(plugin,extensionPointName);if(!isFunction(method)||noCall){return method;}try{return method.apply(getValueByPath(plugin,pluginMethodPath),args);}catch(err){// When a plugin failed, doesn't break the app
1227
- if(throws){throw err;}else {var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===undefined||_this2$logger.error(PLUGIN_INVOCATION_ERROR(PLUGIN_ENGINE,extensionPointName,plugin.name),err);}}return null;});}},{key:"invokeSingle",value:function invokeSingle(extPoint){for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];}return this.invoke.apply(this,[extPoint,false].concat(args))[0];}},{key:"invokeMultiple",value:function invokeMultiple(extPoint){for(var _len3=arguments.length,args=new Array(_len3>1?_len3-1:0),_key3=1;_key3<_len3;_key3++){args[_key3-1]=arguments[_key3];}return this.invoke.apply(this,[extPoint,true].concat(args));}}]);}();var defaultPluginEngine=new PluginEngine({throws:true},defaultLogger);
1222
+ function getDefaultExportFromCjs (x) {
1223
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
1224
+ }
1225
+
1226
+ var errorStackParser$1 = {exports: {}};
1227
+
1228
+ var stackframe$1 = {exports: {}};
1229
+
1230
+ var stackframe=stackframe$1.exports;var hasRequiredStackframe;function requireStackframe(){if(hasRequiredStackframe)return stackframe$1.exports;hasRequiredStackframe=1;(function(module,exports){(function(root,factory){/* istanbul ignore next */{module.exports=factory();}})(stackframe,function(){function _isNumber(n){return !isNaN(parseFloat(n))&&isFinite(n);}function _capitalize(str){return str.charAt(0).toUpperCase()+str.substring(1);}function _getter(p){return function(){return this[p];};}var booleanProps=['isConstructor','isEval','isNative','isToplevel'];var numericProps=['columnNumber','lineNumber'];var stringProps=['fileName','functionName','source'];var arrayProps=['args'];var objectProps=['evalOrigin'];var props=booleanProps.concat(numericProps,stringProps,arrayProps,objectProps);function StackFrame(obj){if(!obj)return;for(var i=0;i<props.length;i++){if(obj[props[i]]!==undefined){this['set'+_capitalize(props[i])](obj[props[i]]);}}}StackFrame.prototype={getArgs:function getArgs(){return this.args;},setArgs:function setArgs(v){if(Object.prototype.toString.call(v)!=='[object Array]'){throw new TypeError('Args must be an Array');}this.args=v;},getEvalOrigin:function getEvalOrigin(){return this.evalOrigin;},setEvalOrigin:function setEvalOrigin(v){if(v instanceof StackFrame){this.evalOrigin=v;}else if(v instanceof Object){this.evalOrigin=new StackFrame(v);}else {throw new TypeError('Eval Origin must be an Object or StackFrame');}},toString:function toString(){var fileName=this.getFileName()||'';var lineNumber=this.getLineNumber()||'';var columnNumber=this.getColumnNumber()||'';var functionName=this.getFunctionName()||'';if(this.getIsEval()){if(fileName){return '[eval] ('+fileName+':'+lineNumber+':'+columnNumber+')';}return '[eval]:'+lineNumber+':'+columnNumber;}if(functionName){return functionName+' ('+fileName+':'+lineNumber+':'+columnNumber+')';}return fileName+':'+lineNumber+':'+columnNumber;}};StackFrame.fromString=function StackFrame$$fromString(str){var argsStartIndex=str.indexOf('(');var argsEndIndex=str.lastIndexOf(')');var functionName=str.substring(0,argsStartIndex);var args=str.substring(argsStartIndex+1,argsEndIndex).split(',');var locationString=str.substring(argsEndIndex+1);if(locationString.indexOf('@')===0){var parts=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(locationString,'');var fileName=parts[1];var lineNumber=parts[2];var columnNumber=parts[3];}return new StackFrame({functionName:functionName,args:args||undefined,fileName:fileName,lineNumber:lineNumber||undefined,columnNumber:columnNumber||undefined});};for(var i=0;i<booleanProps.length;i++){StackFrame.prototype['get'+_capitalize(booleanProps[i])]=_getter(booleanProps[i]);StackFrame.prototype['set'+_capitalize(booleanProps[i])]=function(p){return function(v){this[p]=Boolean(v);};}(booleanProps[i]);}for(var j=0;j<numericProps.length;j++){StackFrame.prototype['get'+_capitalize(numericProps[j])]=_getter(numericProps[j]);StackFrame.prototype['set'+_capitalize(numericProps[j])]=function(p){return function(v){if(!_isNumber(v)){throw new TypeError(p+' must be a Number');}this[p]=Number(v);};}(numericProps[j]);}for(var k=0;k<stringProps.length;k++){StackFrame.prototype['get'+_capitalize(stringProps[k])]=_getter(stringProps[k]);StackFrame.prototype['set'+_capitalize(stringProps[k])]=function(p){return function(v){this[p]=String(v);};}(stringProps[k]);}return StackFrame;});})(stackframe$1);return stackframe$1.exports;}
1231
+
1232
+ var errorStackParser=errorStackParser$1.exports;var hasRequiredErrorStackParser;function requireErrorStackParser(){if(hasRequiredErrorStackParser)return errorStackParser$1.exports;hasRequiredErrorStackParser=1;(function(module,exports){(function(root,factory){/* istanbul ignore next */{module.exports=factory(requireStackframe());}})(errorStackParser,function ErrorStackParser(StackFrame){var FIREFOX_SAFARI_STACK_REGEXP=/(^|@)\S+:\d+/;var CHROME_IE_STACK_REGEXP=/^\s*at .*(\S+:\d+|\(native\))/m;var SAFARI_NATIVE_CODE_REGEXP=/^(eval@)?(\[native code])?$/;return {/**
1233
+ * Given an Error object, extract the most information from it.
1234
+ *
1235
+ * @param {Error} error object
1236
+ * @return {Array} of StackFrames
1237
+ */parse:function ErrorStackParser$$parse(error){if(typeof error.stacktrace!=='undefined'||typeof error['opera#sourceloc']!=='undefined'){return this.parseOpera(error);}else if(error.stack&&error.stack.match(CHROME_IE_STACK_REGEXP)){return this.parseV8OrIE(error);}else if(error.stack){return this.parseFFOrSafari(error);}else {throw new Error('Cannot parse given Error object');}},// Separate line and column numbers from a string of the form: (URI:Line:Column)
1238
+ extractLocation:function ErrorStackParser$$extractLocation(urlLike){// Fail-fast but return locations like "(native)"
1239
+ if(urlLike.indexOf(':')===-1){return [urlLike];}var regExp=/(.+?)(?::(\d+))?(?::(\d+))?$/;var parts=regExp.exec(urlLike.replace(/[()]/g,''));return [parts[1],parts[2]||undefined,parts[3]||undefined];},parseV8OrIE:function ErrorStackParser$$parseV8OrIE(error){var filtered=error.stack.split('\n').filter(function(line){return !!line.match(CHROME_IE_STACK_REGEXP);},this);return filtered.map(function(line){if(line.indexOf('(eval ')>-1){// Throw away eval information until we implement stacktrace.js/stackframe#8
1240
+ line=line.replace(/eval code/g,'eval').replace(/(\(eval at [^()]*)|(,.*$)/g,'');}var sanitizedLine=line.replace(/^\s+/,'').replace(/\(eval code/g,'(').replace(/^.*?\s+/,'');// capture and preseve the parenthesized location "(/foo/my bar.js:12:87)" in
1241
+ // case it has spaces in it, as the string is split on \s+ later on
1242
+ var location=sanitizedLine.match(/ (\(.+\)$)/);// remove the parenthesized location from the line, if it was matched
1243
+ sanitizedLine=location?sanitizedLine.replace(location[0],''):sanitizedLine;// if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine
1244
+ // because this line doesn't have function name
1245
+ var locationParts=this.extractLocation(location?location[1]:sanitizedLine);var functionName=location&&sanitizedLine||undefined;var fileName=['eval','<anonymous>'].indexOf(locationParts[0])>-1?undefined:locationParts[0];return new StackFrame({functionName:functionName,fileName:fileName,lineNumber:locationParts[1],columnNumber:locationParts[2],source:line});},this);},parseFFOrSafari:function ErrorStackParser$$parseFFOrSafari(error){var filtered=error.stack.split('\n').filter(function(line){return !line.match(SAFARI_NATIVE_CODE_REGEXP);},this);return filtered.map(function(line){// Throw away eval information until we implement stacktrace.js/stackframe#8
1246
+ if(line.indexOf(' > eval')>-1){line=line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,':$1');}if(line.indexOf('@')===-1&&line.indexOf(':')===-1){// Safari eval frames only have function names and nothing else
1247
+ return new StackFrame({functionName:line});}else {var functionNameRegex=/((.*".+"[^@]*)?[^@]*)(?:@)/;var matches=line.match(functionNameRegex);var functionName=matches&&matches[1]?matches[1]:undefined;var locationParts=this.extractLocation(line.replace(functionNameRegex,''));return new StackFrame({functionName:functionName,fileName:locationParts[0],lineNumber:locationParts[1],columnNumber:locationParts[2],source:line});}},this);},parseOpera:function ErrorStackParser$$parseOpera(e){if(!e.stacktrace||e.message.indexOf('\n')>-1&&e.message.split('\n').length>e.stacktrace.split('\n').length){return this.parseOpera9(e);}else if(!e.stack){return this.parseOpera10(e);}else {return this.parseOpera11(e);}},parseOpera9:function ErrorStackParser$$parseOpera9(e){var lineRE=/Line (\d+).*script (?:in )?(\S+)/i;var lines=e.message.split('\n');var result=[];for(var i=2,len=lines.length;i<len;i+=2){var match=lineRE.exec(lines[i]);if(match){result.push(new StackFrame({fileName:match[2],lineNumber:match[1],source:lines[i]}));}}return result;},parseOpera10:function ErrorStackParser$$parseOpera10(e){var lineRE=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i;var lines=e.stacktrace.split('\n');var result=[];for(var i=0,len=lines.length;i<len;i+=2){var match=lineRE.exec(lines[i]);if(match){result.push(new StackFrame({functionName:match[3]||undefined,fileName:match[2],lineNumber:match[1],source:lines[i]}));}}return result;},// Opera 10.65+ Error.stack very similar to FF/Safari
1248
+ parseOpera11:function ErrorStackParser$$parseOpera11(error){var filtered=error.stack.split('\n').filter(function(line){return !!line.match(FIREFOX_SAFARI_STACK_REGEXP)&&!line.match(/^Error created at/);},this);return filtered.map(function(line){var tokens=line.split('@');var locationParts=this.extractLocation(tokens.pop());var functionCall=tokens.shift()||'';var functionName=functionCall.replace(/<anonymous function(: (\w+))?>/,'$2').replace(/\([^)]*\)/g,'')||undefined;var argsRaw;if(functionCall.match(/\(([^)]*)\)/)){argsRaw=functionCall.replace(/^[^(]+\(([^)]*)\)$/,'$1');}var args=argsRaw===undefined||argsRaw==='[arguments not available]'?undefined:argsRaw.split(',');return new StackFrame({functionName:functionName,args:args,fileName:locationParts[0],lineNumber:locationParts[1],columnNumber:locationParts[2],source:line});},this);}};});})(errorStackParser$1);return errorStackParser$1.exports;}
1228
1249
 
1229
- var LOAD_ORIGIN='RS_JS_SDK';
1250
+ var errorStackParserExports = requireErrorStackParser();
1251
+ var ErrorStackParser = /*@__PURE__*/getDefaultExportFromCjs(errorStackParserExports);
1252
+
1253
+ var GLOBAL_CODE='global code';var normalizeFunctionName=function normalizeFunctionName(name){if(isDefined(name)){return /^global code$/i.test(name)?GLOBAL_CODE:name;}return name;};/**
1254
+ * Takes a stacktrace.js style stackframe (https://github.com/stacktracejs/stackframe)
1255
+ * and returns a Bugsnag compatible stackframe (https://docs.bugsnag.com/api/error-reporting/#json-payload)
1256
+ * @param frame
1257
+ * @returns
1258
+ */var formatStackframe=function formatStackframe(frame){var f={file:frame.fileName,method:normalizeFunctionName(frame.functionName),lineNumber:frame.lineNumber,columnNumber:frame.columnNumber};// Some instances result in no file:
1259
+ // - non-error exception thrown from global code in FF
1260
+ // This adds one.
1261
+ if(f.lineNumber&&f.lineNumber>-1&&!f.file&&!f.method){f.file=GLOBAL_CODE;}return f;};var ensureString=function ensureString(str){return isString(str)?str:'';};function createException(errorClass,errorMessage,msgPrefix,stacktrace){return {errorClass:ensureString(errorClass),message:"".concat(msgPrefix).concat(ensureString(errorMessage)),type:'browserjs',stacktrace:stacktrace.reduce(function(accum,frame){var f=formatStackframe(frame);// don't include a stackframe if none of its properties are defined
1262
+ try{if(JSON.stringify(f)==='{}')return accum;return accum.concat(f);}catch(_unused){return accum;}},[])};}var normalizeError=function normalizeError(maybeError,logger){var error;if(isTypeOfError(maybeError)&&isString(getStacktrace(maybeError))){error=maybeError;}else {logger.warn(NON_ERROR_WARNING(ERROR_HANDLER,stringifyWithoutCircular(maybeError)));error=undefined;}return error;};var createBugsnagException=function createBugsnagException(error,msgPrefix){try{var stacktrace=ErrorStackParser.parse(error);return createException(error.name,error.message,msgPrefix,stacktrace);}catch(_unused2){return createException(error.name,error.message,msgPrefix,[]);}};
1263
+
1264
+ /**
1265
+ * Utility to parse XHR JSON response
1266
+ */var responseTextToJson=function responseTextToJson(responseText,onError){try{return JSON.parse(responseText||'');}catch(err){var error=getMutatedError(err,'Failed to parse response data');onError(error);}return undefined;};
1267
+
1268
+ var FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';var PLUGINS_LOAD_FAILURE_MESSAGES=[/Failed to fetch dynamically imported module: .*/];var INTEGRATIONS_LOAD_FAILURE_MESSAGES=[/Failed to load the script with the id .*/,/A timeout of \d+ ms occurred while trying to load the script with id .*/];var ERROR_MESSAGES_TO_BE_FILTERED=[new RegExp("".concat(FAILED_REQUEST_ERR_MSG_PREFIX,".*")),/A script with the id .* is already loaded\./];
1269
+
1270
+ var DEFAULT_XHR_REQUEST_OPTIONS={headers:{Accept:'application/json','Content-Type':'application/json;charset=UTF-8'},method:'GET'};/**
1271
+ * Utility to create request configuration based on default options
1272
+ */var createXhrRequestOptions=function createXhrRequestOptions(url,options,basicAuthHeader){var requestOptions=mergeDeepRight(DEFAULT_XHR_REQUEST_OPTIONS,options||{});if(basicAuthHeader){requestOptions.headers=mergeDeepRight(requestOptions.headers,{Authorization:basicAuthHeader});}requestOptions.url=url;return requestOptions;};/**
1273
+ * Utility implementation of XHR, fetch cannot be used as it requires explicit
1274
+ * origin allowed values and not wildcard for CORS requests with credentials and
1275
+ * this is not supported by our sourceConfig API
1276
+ */var xhrRequest=function xhrRequest(options){var timeout=arguments.length>1&&arguments[1]!==undefined?arguments[1]:DEFAULT_XHR_TIMEOUT_MS;var logger=arguments.length>2?arguments[2]:undefined;return new Promise(function(resolve,reject){var payload;if(options.sendRawData===true){payload=options.data;}else {payload=stringifyWithoutCircular(options.data,false,[],logger);if(isNull(payload)){reject({error:new Error(XHR_PAYLOAD_PREP_ERROR),undefined:undefined,options:options});// return and don't process further if the payload could not be stringified
1277
+ return;}}var xhr=new XMLHttpRequest();// eslint-disable-next-line @typescript-eslint/no-unused-vars
1278
+ var xhrReject=function xhrReject(e){reject({error:new Error(XHR_DELIVERY_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,xhr.status,xhr.statusText,options.url)),xhr:xhr,options:options});};var xhrError=function xhrError(e){reject({error:new Error(XHR_REQUEST_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,e,options.url)),xhr:xhr,options:options});};xhr.ontimeout=xhrError;xhr.onerror=xhrError;xhr.onload=function(){if(xhr.status>=200&&xhr.status<400){resolve({response:xhr.responseText,xhr:xhr,options:options});}else {xhrReject();}};xhr.open(options.method,options.url,true);if(options.withCredentials===true){xhr.withCredentials=true;}// The timeout property may be set only in the time interval between a call to the open method
1279
+ // and the first call to the send method in legacy browsers
1280
+ xhr.timeout=timeout;Object.keys(options.headers).forEach(function(headerName){if(options.headers[headerName]){xhr.setRequestHeader(headerName,options.headers[headerName]);}});try{xhr.send(payload);}catch(err){reject({error:getMutatedError(err,XHR_SEND_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,options.url)),xhr:xhr,options:options});}});};
1230
1281
 
1231
1282
  /**
1232
- * Utility method to normalise errors
1233
- */var processError=function processError(error){var errorMessage;try{if(isString(error)){errorMessage=error;}else if(error instanceof Error){errorMessage=error.message;}else if(error instanceof ErrorEvent){errorMessage=error.message;}else {errorMessage=error.message?error.message:stringifyWithoutCircular(error);}}catch(e){errorMessage="Unknown error: ".concat(e.message);}return errorMessage;};var getNormalizedErrorForUnhandledError=function getNormalizedErrorForUnhandledError(error){try{if(error instanceof Error||error instanceof ErrorEvent||error instanceof PromiseRejectionEvent&&error.reason){return error;}// TODO: remove this block once all device mode integrations start using the v3 script loader module (TS)
1234
- if(error instanceof Event){var eventTarget=error.target;// Discard all the non-script loading errors
1235
- if(eventTarget&&eventTarget.localName!=='script'){return undefined;}// Discard script errors that are not originated at SDK or from native SDKs
1236
- if(eventTarget!==null&&eventTarget!==void 0&&eventTarget.dataset&&(eventTarget.dataset.loader!==LOAD_ORIGIN||eventTarget.dataset.isnonnativesdk!=='true')){return undefined;}var errorMessage="Error in loading a third-party script from URL ".concat(eventTarget===null||eventTarget===void 0?void 0:eventTarget.src," with ID ").concat(eventTarget===null||eventTarget===void 0?void 0:eventTarget.id,".");return Object.create(error,{message:{value:errorMessage}});}return error;}catch(e){return e;}};
1283
+ * Service to handle data communication with APIs
1284
+ */var HttpClient=/*#__PURE__*/function(){function HttpClient(logger){_classCallCheck(this,HttpClient);this.logger=logger;this.onError=this.onError.bind(this);}return _createClass(HttpClient,[{key:"init",value:function init(errorHandler){this.errorHandler=errorHandler;}/**
1285
+ * Implement requests in a blocking way
1286
+ */},{key:"getData",value:(function(){var _getData=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(config){var url,options,timeout,isRawResponse,data;return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;_context.prev=1;_context.next=4;return xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout,this.logger);case 4:data=_context.sent;return _context.abrupt("return",{data:isRawResponse?data.response:responseTextToJson(data.response,this.onError),details:data});case 8:_context.prev=8;_context.t0=_context["catch"](1);return _context.abrupt("return",{data:undefined,details:_context.t0});case 11:case "end":return _context.stop();}},_callee,this,[[1,8]]);}));function getData(_x){return _getData.apply(this,arguments);}return getData;}()/**
1287
+ * Implement requests in a non-blocking way
1288
+ */)},{key:"getAsyncData",value:function getAsyncData(config){var _this=this;var callback=config.callback,url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;var isFireAndForget=!isFunction(callback);xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout,this.logger).then(function(data){if(!isFireAndForget){callback(isRawResponse?data.response:responseTextToJson(data.response,_this.onError),data);}}).catch(function(data){if(!isFireAndForget){callback(undefined,data);}});}/**
1289
+ * Handle errors
1290
+ */},{key:"onError",value:function onError(error){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===undefined||_this$errorHandler.onError(error,HTTP_CLIENT);}/**
1291
+ * Set basic authentication header (eg writekey)
1292
+ */},{key:"setAuthHeader",value:function setAuthHeader(value){var noBtoa=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var authVal=noBtoa?value:toBase64("".concat(value,":"));this.basicAuthHeader="Basic ".concat(authVal);}/**
1293
+ * Clear basic authentication header
1294
+ */},{key:"resetAuthHeader",value:function resetAuthHeader(){this.basicAuthHeader=undefined;}}]);}();var defaultHttpClient=new HttpClient(defaultLogger);
1295
+
1296
+ var METRICS_PAYLOAD_VERSION='1';
1297
+
1298
+ // Errors from the below scripts are NOT allowed to reach Bugsnag
1299
+ var SDK_FILE_NAME_PREFIXES=function SDK_FILE_NAME_PREFIXES(){return ['rsa'// Prefix for all the SDK scripts including plugins and module federated chunks
1300
+ ];};var DEV_HOSTS=['www.test-host.com','localhost','127.0.0.1','[::1]'];// List of keys to exclude from the metadata
1301
+ // Potential PII or sensitive data
1302
+ var APP_STATE_EXCLUDE_KEYS=['userId','userTraits','groupId','groupTraits','anonymousId','config','instance',// destination instance objects
1303
+ 'eventBuffer',// pre-load event buffer (may contain PII)
1304
+ 'traits','authToken'];var NOTIFIER_NAME='RudderStack JavaScript SDK';var SDK_GITHUB_URL='__REPOSITORY_URL__';var SOURCE_NAME='js';
1305
+
1306
+ var getErrInstance=function getErrInstance(err,errorType){switch(errorType){case ErrorType.UNHANDLEDEXCEPTION:{var _ref=err,error=_ref.error;return error||err;}case ErrorType.UNHANDLEDREJECTION:{return err.reason;}case ErrorType.HANDLEDEXCEPTION:default:return err;}};var createNewBreadcrumb=function createNewBreadcrumb(message){return {type:'manual',name:message,timestamp:new Date(),metaData:{}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};var getAppStateForMetadata=function getAppStateForMetadata(state){var stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS);return stateStr!==null?JSON.parse(stateStr):{};};var getURLWithoutQueryString=function getURLWithoutQueryString(){var url=globalThis.location.href.split('?');return url[0];};var getUserDetails=function getUserDetails(source,session,lifecycle,autoTrack){var _source$value$id,_source$value,_session$sessionInfo$,_autoTrack$pageLifecy,_source$value$name,_source$value2;return {id:"".concat((_source$value$id=(_source$value=source.value)===null||_source$value===undefined?undefined:_source$value.id)!==null&&_source$value$id!==undefined?_source$value$id:lifecycle.writeKey.value,"..").concat((_session$sessionInfo$=session.sessionInfo.value.id)!==null&&_session$sessionInfo$!==undefined?_session$sessionInfo$:'NA',"..").concat((_autoTrack$pageLifecy=autoTrack.pageLifecycle.visitId.value)!==null&&_autoTrack$pageLifecy!==undefined?_autoTrack$pageLifecy:'NA'),name:(_source$value$name=(_source$value2=source.value)===null||_source$value2===undefined?undefined:_source$value2.name)!==null&&_source$value$name!==undefined?_source$value$name:'NA'};};var getDeviceDetails=function getDeviceDetails(locale,userAgent){var _locale$value,_userAgent$value;return {locale:(_locale$value=locale.value)!==null&&_locale$value!==undefined?_locale$value:'NA',userAgent:(_userAgent$value=userAgent.value)!==null&&_userAgent$value!==undefined?_userAgent$value:'NA',time:new Date()};};var getBugsnagErrorEvent=function getBugsnagErrorEvent(exception,errorState,state){var context=state.context,lifecycle=state.lifecycle,session=state.session,source=state.source,reporting=state.reporting,autoTrack=state.autoTrack;var app=context.app,locale=context.locale,userAgent=context.userAgent,timezone=context.timezone,screen=context.screen,library=context.library;return {payloadVersion:'5',notifier:{name:NOTIFIER_NAME,version:app.value.version,url:SDK_GITHUB_URL},events:[{exceptions:[clone(exception)],severity:errorState.severity,unhandled:errorState.unhandled,severityReason:errorState.severityReason,app:{version:app.value.version,releaseStage:getReleaseStage(),type:app.value.installType},device:getDeviceDetails(locale,userAgent),request:{url:getURLWithoutQueryString(),clientIp:'[NOT COLLECTED]'},breadcrumbs:clone(reporting.breadcrumbs.value),context:exception.message,metaData:_objectSpread2({app:{snippetVersion:library.value.snippetVersion},device:_objectSpread2(_objectSpread2({},screen.value),{},{timezone:timezone.value})},getAppStateForMetadata(state)),user:getUserDetails(source,session,lifecycle,autoTrack)}]};};/**
1307
+ * A function to determine whether the error should be promoted to notify or not
1308
+ * @param {Error} exception
1309
+ * @returns
1310
+ */var isAllowedToBeNotified=function isAllowedToBeNotified(exception){var errMsg=exception.message;// Filter out plugin load errors from non-RudderStack CDN URLs
1311
+ if(PLUGINS_LOAD_FAILURE_MESSAGES.some(function(regex){return regex.test(errMsg);})){return errMsg.includes(SDK_CDN_BASE_URL);}// Filter out integration load errors from non-RudderStack CDN URLs
1312
+ if(INTEGRATIONS_LOAD_FAILURE_MESSAGES.some(function(regex){return regex.test(errMsg);})){return errMsg.includes(SDK_CDN_BASE_URL);}return !ERROR_MESSAGES_TO_BE_FILTERED.some(function(e){return e.test(errMsg);});};/**
1313
+ * A function to determine if the error is from Rudder SDK
1314
+ * @param {Error} exception
1315
+ * @returns
1316
+ */var isSDKError=function isSDKError(exception){var _exception$stacktrace;var errorOrigin=(_exception$stacktrace=exception.stacktrace[0])===null||_exception$stacktrace===undefined?undefined:_exception$stacktrace.file;if(!errorOrigin||typeof errorOrigin!=='string'){return false;}var srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);var paths=errorOrigin.split('/');// extract the parent folder name from the error origin file path
1317
+ // Ex: parentFolderName will be 'sample' for url: https://example.com/sample/file.min.js
1318
+ var parentFolderName=paths[paths.length-2];return parentFolderName===CDN_INT_DIR||SDK_FILE_NAME_PREFIXES().some(function(prefix){return srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js');});};var getErrorDeliveryPayload=function getErrorDeliveryPayload(payload,state){var data={version:METRICS_PAYLOAD_VERSION,message_id:generateUUID(),source:{name:SOURCE_NAME,sdk_version:state.context.app.value.version,write_key:state.lifecycle.writeKey.value,install_type:state.context.app.value.installType},errors:payload};return stringifyWithoutCircular(data);};
1237
1319
 
1238
1320
  /**
1239
1321
  * A service to handle errors
1240
1322
  */var ErrorHandler=/*#__PURE__*/function(){// If no logger is passed errors will be thrown as unhandled error
1241
- function ErrorHandler(logger,pluginEngine){_classCallCheck(this,ErrorHandler);this.logger=logger;this.pluginEngine=pluginEngine;this.errorBuffer=new BufferQueue();this.attachEffect();}return _createClass(ErrorHandler,[{key:"attachEffect",value:function attachEffect(){if(state.reporting.isErrorReportingPluginLoaded.value===true){while(this.errorBuffer.size()>0){var errorToProcess=this.errorBuffer.dequeue();if(errorToProcess){// send it to the plugin
1242
- this.notifyError(errorToProcess.error,errorToProcess.errorState);}}}}},{key:"attachErrorListeners",value:function attachErrorListeners(){var _this=this;if('addEventListener'in globalThis){globalThis.addEventListener('error',function(event){_this.onError(event,undefined,undefined,undefined,ErrorType.UNHANDLEDEXCEPTION);});globalThis.addEventListener('unhandledrejection',function(event){_this.onError(event,undefined,undefined,undefined,ErrorType.UNHANDLEDREJECTION);});}else {var _this$logger;(_this$logger=this.logger)===null||_this$logger===undefined||_this$logger.debug("Failed to attach global error listeners.");}}},{key:"init",value:function init(httpClient,externalSrcLoader){var _this2=this;this.httpClient=httpClient;// Below lines are only kept for backward compatibility
1243
- // TODO: Remove this in the next major release
1244
- if(!this.pluginEngine){return;}try{var extPoint='errorReporting.init';var errReportingInitVal=this.pluginEngine.invokeSingle(extPoint,state,this.pluginEngine,externalSrcLoader,this.logger,true);if(errReportingInitVal instanceof Promise){errReportingInitVal.then(function(client){_this2.errReportingClient=client;}).catch(function(err){var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0||_this2$logger.error(REPORTING_PLUGIN_INIT_FAILURE_ERROR(ERROR_HANDLER),err);});}}catch(err){this.onError(err,ERROR_HANDLER);}}},{key:"onError",value:function onError(error){var _error;var context=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var customMessage=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'';var shouldAlwaysThrow=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;var errorType=arguments.length>4&&arguments[4]!==undefined?arguments[4]:ErrorType.HANDLEDEXCEPTION;var normalizedError;var errorMessage;if(errorType===ErrorType.HANDLEDEXCEPTION){errorMessage=processError(error);// If no error message after we normalize, then we swallow/ignore the errors
1245
- if(!errorMessage){return;}errorMessage=removeDoubleSpaces("".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(customMessage," ").concat(errorMessage));normalizedError=new Error(errorMessage);if(isTypeOfError(error)){normalizedError=Object.create(error,{message:{value:errorMessage}});}}else {normalizedError=getNormalizedErrorForUnhandledError(error);}var isErrorReportingEnabled=state.reporting.isErrorReportingEnabled.value;var isErrorReportingPluginLoaded=state.reporting.isErrorReportingPluginLoaded.value;try{if(isErrorReportingEnabled){var errorState={severity:'error',unhandled:errorType!==ErrorType.HANDLEDEXCEPTION,severityReason:{type:errorType}};if(!isErrorReportingPluginLoaded){// buffer the error
1246
- this.errorBuffer.enqueue({error:normalizedError,errorState:errorState});}else if(normalizedError){this.notifyError(normalizedError,errorState);}}}catch(e){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===undefined||_this$logger2.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),e);}if(errorType===ErrorType.HANDLEDEXCEPTION){if(this.logger){this.logger.error(errorMessage);if(shouldAlwaysThrow){throw normalizedError;}}else {throw normalizedError;}}else if((_error=error.error)!==null&&_error!==undefined&&(_error=_error.stack)!==null&&_error!==undefined&&_error.includes(MANUAL_ERROR_IDENTIFIER)){var _this$logger3,_error2;(_this$logger3=this.logger)===null||_this$logger3===undefined||_this$logger3.error('An unknown error occurred:',(_error2=error.error)===null||_error2===undefined?undefined:_error2.message);}}/**
1323
+ function ErrorHandler(httpClient,logger){_classCallCheck(this,ErrorHandler);this.httpClient=httpClient;this.logger=logger;this.attachErrorListeners();}return _createClass(ErrorHandler,[{key:"attachErrorListeners",value:function attachErrorListeners(){var _this=this;globalThis.addEventListener('error',function(event){_this.onError(event,ERROR_HANDLER,undefined,ErrorType.UNHANDLEDEXCEPTION);});globalThis.addEventListener('unhandledrejection',function(event){_this.onError(event,ERROR_HANDLER,undefined,ErrorType.UNHANDLEDREJECTION);});}},{key:"onError",value:function onError(error){var context=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var customMessage=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'';var errorType=arguments.length>3&&arguments[3]!==undefined?arguments[3]:ErrorType.HANDLEDEXCEPTION;try{var errInstance=getErrInstance(error,errorType);var normalizedError=normalizeError(errInstance,this.logger);if(isUndefined(normalizedError)){return;}var customMsgVal=customMessage?"".concat(customMessage," - "):'';var errorMsgPrefix="".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(customMsgVal);var bsException=createBugsnagException(normalizedError,errorMsgPrefix);var stacktrace=getStacktrace(normalizedError);var isSdkDispatched=stacktrace.includes(MANUAL_ERROR_IDENTIFIER);// Filter errors that are not originated in the SDK.
1324
+ // In case of NPM installations, the errors from the SDK cannot be identified
1325
+ // and will NOT be reported unless they occur in plugins or integrations.
1326
+ if(!isSdkDispatched&&!isSDKError(bsException)){return;}if(state.reporting.isErrorReportingEnabled.value&&isAllowedToBeNotified(bsException)){var errorState={severity:'error',unhandled:errorType!==ErrorType.HANDLEDEXCEPTION,severityReason:{type:errorType}};// enrich error payload
1327
+ var bugsnagPayload=getBugsnagErrorEvent(bsException,errorState,state);// send it to metrics service
1328
+ this.httpClient.getAsyncData({url:state.metrics.metricsServiceUrl.value,options:{method:'POST',data:getErrorDeliveryPayload(bugsnagPayload,state),sendRawData:true},isRawResponse:true});}// Log handled errors and errors dispatched by the SDK
1329
+ if(errorType===ErrorType.HANDLEDEXCEPTION||isSdkDispatched){this.logger.error(bsException.message);}}catch(err){// If an error occurs while handling an error, log it
1330
+ this.logger.error(HANDLE_ERROR_FAILURE(ERROR_HANDLER),err);}}/**
1247
1331
  * Add breadcrumbs to add insight of a user's journey before an error
1248
1332
  * occurred and send to external error monitoring service via a plugin
1249
1333
  *
1250
1334
  * @param {string} breadcrumb breadcrumbs message
1251
- */},{key:"leaveBreadcrumb",value:function leaveBreadcrumb(breadcrumb){if(this.pluginEngine){try{this.pluginEngine.invokeSingle('errorReporting.breadcrumb',this.pluginEngine,// deprecated parameter
1252
- this.errReportingClient,// deprecated parameter
1253
- breadcrumb,this.logger,state);}catch(err){this.onError(err,ERROR_HANDLER,'errorReporting.breadcrumb');}}}/**
1254
- * Send handled errors to external error monitoring service via a plugin
1255
- *
1256
- * @param {Error} error Error instance from handled error
1257
- */},{key:"notifyError",value:function notifyError(error,errorState){if(this.pluginEngine&&this.httpClient){try{this.pluginEngine.invokeSingle('errorReporting.notify',this.pluginEngine,// deprecated parameter
1258
- this.errReportingClient,// deprecated parameter
1259
- error,state,this.logger,this.httpClient,errorState);}catch(err){var _this$logger4;// Not calling onError here as we don't want to go into infinite loop
1260
- (_this$logger4=this.logger)===null||_this$logger4===undefined||_this$logger4.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),err);}}}}]);}();var defaultErrorHandler=new ErrorHandler(defaultLogger,defaultPluginEngine);
1335
+ */},{key:"leaveBreadcrumb",value:function leaveBreadcrumb(breadcrumb){try{state.reporting.breadcrumbs.value=[].concat(_toConsumableArray(state.reporting.breadcrumbs.value),[createNewBreadcrumb(breadcrumb)]);}catch(err){this.onError(err,BREADCRUMB_ERROR(ERROR_HANDLER));}}}]);}();var defaultErrorHandler=new ErrorHandler(defaultHttpClient,defaultLogger);
1336
+
1337
+ // to next or return the value if it is the last one instead of an array per
1338
+ // plugin that is the normal invoke
1339
+ // TODO: add invoke method for extension point that we know only one plugin can be used. add invokeMultiple and invokeSingle methods
1340
+ var PluginEngine=/*#__PURE__*/function(){function PluginEngine(logger){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,PluginEngine);_defineProperty(this,"plugins",[]);_defineProperty(this,"byName",{});_defineProperty(this,"cache",{});_defineProperty(this,"config",{throws:true});this.config=_objectSpread2({throws:true},options);this.logger=logger;}return _createClass(PluginEngine,[{key:"register",value:function register(plugin,state){if(!plugin.name){var errorMessage=PLUGIN_NAME_MISSING_ERROR(PLUGIN_ENGINE);if(this.config.throws){throw new Error(errorMessage);}else {this.logger.error(errorMessage,plugin);return;}}if(this.byName[plugin.name]){var _errorMessage=PLUGIN_ALREADY_EXISTS_ERROR(PLUGIN_ENGINE,plugin.name);if(this.config.throws){throw new Error(_errorMessage);}else {this.logger.error(_errorMessage);return;}}this.cache={};this.plugins=this.plugins.slice();var pos=this.plugins.length;this.plugins.forEach(function(pluginItem,index){var _pluginItem$deps;if((_pluginItem$deps=pluginItem.deps)!==null&&_pluginItem$deps!==undefined&&_pluginItem$deps.includes(plugin.name)){pos=Math.min(pos,index);}});this.plugins.splice(pos,0,plugin);this.byName[plugin.name]=plugin;if(isFunction(plugin.initialize)){plugin.initialize(state);}}},{key:"unregister",value:function unregister(name){var plugin=this.byName[name];if(!plugin){var errorMessage=PLUGIN_NOT_FOUND_ERROR(PLUGIN_ENGINE,name);if(this.config.throws){throw new Error(errorMessage);}else {this.logger.error(errorMessage);return;}}var index=this.plugins.indexOf(plugin);if(index===-1){var _errorMessage2=PLUGIN_ENGINE_BUG_ERROR(PLUGIN_ENGINE,name);if(this.config.throws){throw new Error(_errorMessage2);}else {this.logger.error(_errorMessage2);return;}}this.cache={};delete this.byName[name];this.plugins=this.plugins.slice();this.plugins.splice(index,1);}},{key:"getPlugin",value:function getPlugin(name){return this.byName[name];}},{key:"getPlugins",value:function getPlugins(extPoint){var _this=this;var lifeCycleName=extPoint!==null&&extPoint!==undefined?extPoint:'.';if(!this.cache[lifeCycleName]){this.cache[lifeCycleName]=this.plugins.filter(function(plugin){var _plugin$deps;if((_plugin$deps=plugin.deps)!==null&&_plugin$deps!==undefined&&_plugin$deps.some(function(dependency){return !_this.byName[dependency];})){// If deps not exist, then not load it.
1341
+ var notExistDeps=plugin.deps.filter(function(dependency){return !_this.byName[dependency];});_this.logger.error(PLUGIN_DEPS_ERROR(PLUGIN_ENGINE,plugin.name,notExistDeps));return false;}return lifeCycleName==='.'?true:hasValueByPath(plugin,lifeCycleName);});}return this.cache[lifeCycleName];}// This method allows to process this.plugins so that it could
1342
+ // do some unified pre-process before application starts.
1343
+ },{key:"processRawPlugins",value:function processRawPlugins(callback){callback(this.plugins);this.cache={};}},{key:"invoke",value:function invoke(extPoint){var _this$config$throws,_this2=this;var allowMultiple=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;for(var _len=arguments.length,args=new Array(_len>2?_len-2:0),_key=2;_key<_len;_key++){args[_key-2]=arguments[_key];}var extensionPointName=extPoint;if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_MISSING_ERROR);}var noCall=extensionPointName.startsWith('!');var throws=(_this$config$throws=this.config.throws)!==null&&_this$config$throws!==undefined?_this$config$throws:extensionPointName.endsWith('!');// eslint-disable-next-line unicorn/better-regex
1344
+ extensionPointName=extensionPointName.replace(/(^!|!$)/g,'');if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_INVALID_ERROR);}var extensionPointNameParts=extensionPointName.split('.');extensionPointNameParts.pop();var pluginMethodPath=extensionPointNameParts.join('.');var pluginsToInvoke=allowMultiple?this.getPlugins(extensionPointName):[this.getPlugins(extensionPointName)[0]];return pluginsToInvoke.map(function(plugin){var method=getValueByPath(plugin,extensionPointName);if(!isFunction(method)||noCall){return method;}try{return method.apply(getValueByPath(plugin,pluginMethodPath),args);}catch(err){// When a plugin failed, doesn't break the app
1345
+ if(throws){throw err;}else {_this2.logger.error(PLUGIN_INVOCATION_ERROR(PLUGIN_ENGINE,extensionPointName,plugin.name),err);}}return null;});}},{key:"invokeSingle",value:function invokeSingle(extPoint){for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];}return this.invoke.apply(this,[extPoint,false].concat(args))[0];}},{key:"invokeMultiple",value:function invokeMultiple(extPoint){for(var _len3=arguments.length,args=new Array(_len3>1?_len3-1:0),_key3=1;_key3<_len3;_key3++){args[_key3-1]=arguments[_key3];}return this.invoke.apply(this,[extPoint,true].concat(args));}}]);}();var defaultPluginEngine=new PluginEngine(defaultLogger,{throws:true});
1261
1346
 
1262
1347
  /**
1263
1348
  * A function to filter and return non cloud mode destinations
@@ -1274,8 +1359,7 @@ destination.config.useNativeSDK===true);};var isHybridModeDestination=function i
1274
1359
 
1275
1360
  /**
1276
1361
  * List of plugin names that are loaded as dynamic imports in modern builds
1277
- */var pluginNamesList=['BeaconQueue','Bugsnag',// deprecated
1278
- 'CustomConsentManager','DeviceModeDestinations','DeviceModeTransformation','ErrorReporting','ExternalAnonymousId','GoogleLinker','IubendaConsentManager','KetchConsentManager','NativeDestinationQueue','OneTrustConsentManager','StorageEncryption','StorageEncryptionLegacy','StorageMigrator','XhrQueue'];
1362
+ */var pluginNamesList=['BeaconQueue','CustomConsentManager','DeviceModeDestinations','DeviceModeTransformation','ExternalAnonymousId','GoogleLinker','IubendaConsentManager','KetchConsentManager','NativeDestinationQueue','OneTrustConsentManager','StorageEncryption','StorageEncryptionLegacy','StorageMigrator','XhrQueue'];var deprecatedPluginsList=['Bugsnag','ErrorReporting'];
1279
1363
 
1280
1364
  var COOKIE_STORAGE='cookieStorage';var LOCAL_STORAGE='localStorage';var SESSION_STORAGE='sessionStorage';var MEMORY_STORAGE='memoryStorage';var NO_STORAGE='none';
1281
1365
 
@@ -1333,10 +1417,6 @@ var EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING=function EVENT_PAYLOAD_SIZE_CHECK_FAIL
1333
1417
  */var getFinalEventForDeliveryMutator=function getFinalEventForDeliveryMutator(event,currentTime){var finalEvent=clone(event);// Update sentAt timestamp to the latest timestamp
1334
1418
  finalEvent.sentAt=currentTime;return finalEvent;};
1335
1419
 
1336
- var METRICS_PAYLOAD_VERSION='1';
1337
-
1338
- var FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';var ERROR_MESSAGES_TO_BE_FILTERED=[FAILED_REQUEST_ERR_MSG_PREFIX];
1339
-
1340
1420
  var QueueStatuses={IN_PROGRESS:'inProgress',QUEUE:'queue',RECLAIM_START:'reclaimStart',RECLAIM_END:'reclaimEnd',ACK:'ack',BATCH_QUEUE:'batchQueue'};
1341
1421
 
1342
1422
  var BEACON_PLUGIN_EVENTS_QUEUE_DEBUG=function BEACON_PLUGIN_EVENTS_QUEUE_DEBUG(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Sending events to data plane.");};var BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR=function BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to convert events batch object to string.");};var BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR=function BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to convert events batch object to Blob.");};var BEACON_QUEUE_SEND_ERROR=function BEACON_QUEUE_SEND_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to send events batch data to the browser's beacon queue. The events will be dropped.");};var BEACON_QUEUE_DELIVERY_ERROR=function BEACON_QUEUE_DELIVERY_ERROR(url){return "Failed to send events batch data to the browser's beacon queue for URL ".concat(url,".");};
@@ -1372,7 +1452,7 @@ var sortByTime=function sortByTime(a,b){return a.time-b.time;};var RETRY_QUEUE='
1372
1452
  var timerScaleFactor=Math.max((_options$timerScaleFa=options.timerScaleFactor)!==null&&_options$timerScaleFa!==undefined?_options$timerScaleFa:MIN_TIMER_SCALE_FACTOR,MIN_TIMER_SCALE_FACTOR);// Limit the timer scale factor to the maximum value
1373
1453
  timerScaleFactor=Math.min(timerScaleFactor,MAX_TIMER_SCALE_FACTOR);// painstakingly tuned. that's why they're not "easily" configurable
1374
1454
  this.timeouts={ackTimer:Math.round(timerScaleFactor*DEFAULT_ACK_TIMER_MS),reclaimTimer:Math.round(timerScaleFactor*DEFAULT_RECLAIM_TIMER_MS),reclaimTimeout:Math.round(timerScaleFactor*DEFAULT_RECLAIM_TIMEOUT_MS),reclaimWait:Math.round(timerScaleFactor*DEFAULT_RECLAIM_WAIT_MS)};this.schedule=new Schedule();this.processId='0';// Set up our empty queues
1375
- this.store=this.storeManager.setStore({id:this.id,name:this.name,validKeys:QueueStatuses,type:storageType});this.setDefaultQueueEntries();// bind recurring tasks for ease of use
1455
+ this.store=this.storeManager.setStore({id:this.id,name:this.name,validKeys:QueueStatuses,type:storageType,errorHandler:this.storeManager.errorHandler,logger:this.storeManager.logger});this.setDefaultQueueEntries();// bind recurring tasks for ease of use
1376
1456
  this.ack=this.ack.bind(this);this.checkReclaim=this.checkReclaim.bind(this);this.processHead=this.processHead.bind(this);this.flushBatch=this.flushBatch.bind(this);this.isPageAccessible=true;// Flush the queue on page leave
1377
1457
  this.flushBatchOnPageLeave();this.scheduleTimeoutActive=false;}return _createClass(RetryQueue,[{key:"setDefaultQueueEntries",value:function setDefaultQueueEntries(){this.setStorageEntry(QueueStatuses.IN_PROGRESS,{});this.setStorageEntry(QueueStatuses.QUEUE,[]);this.setStorageEntry(QueueStatuses.BATCH_QUEUE,[]);}},{key:"configureBatchMode",value:function configureBatchMode(options){this.batchingInProgress=false;if(!isObjectLiteralAndNotNull(options.batch)){return;}var batchOptions=options.batch;this.batch.enabled=batchOptions.enabled===true;if(this.batch.enabled){var _batchOptions$maxSize,_batchOptions$maxItem,_batchOptions$flushIn;// Set upper cap on the batch payload size
1378
1458
  this.batch.maxSize=Math.min((_batchOptions$maxSize=batchOptions.maxSize)!==null&&_batchOptions$maxSize!==undefined?_batchOptions$maxSize:DEFAULT_MAX_BATCH_SIZE_BYTES,DEFAULT_MAX_BATCH_SIZE_BYTES);this.batch.maxItems=(_batchOptions$maxItem=batchOptions.maxItems)!==null&&_batchOptions$maxItem!==undefined?_batchOptions$maxItem:DEFAULT_MAX_BATCH_ITEMS;this.batch.flushInterval=(_batchOptions$flushIn=batchOptions.flushInterval)!==null&&_batchOptions$flushIn!==undefined?_batchOptions$flushIn:DEFAULT_BATCH_FLUSH_INTERVAL_MS;}}},{key:"flushBatchOnPageLeave",value:function flushBatchOnPageLeave(){if(this.batch.enabled){onPageLeave(this.flushBatch);}}},{key:"getStorageEntry",value:function getStorageEntry(name){return this.store.get(name);}// TODO: fix the type of different queues to be the same if possible
@@ -1434,7 +1514,7 @@ if(this.isPageAccessible){// Save this to the in progress map
1434
1514
  inProgress[id]={item:el.item,attemptNumber:el.attemptNumber,time:this.schedule.now(),type:el.type};}enqueueItem(el,id);}}this.setStorageEntry(QueueStatuses.QUEUE,queue);this.setStorageEntry(QueueStatuses.IN_PROGRESS,inProgress);toRun.forEach(function(el){// TODO: handle processQueueCb timeout
1435
1515
  try{var willBeRetried=_this.shouldRetry(el.item,el.attemptNumber+1);_this.processQueueCb(el.item,el.done,el.attemptNumber,_this.maxAttempts,willBeRetried);}catch(err){var _this$logger;(_this$logger=_this.logger)===null||_this$logger===undefined||_this$logger.error(RETRY_QUEUE_PROCESS_ERROR(RETRY_QUEUE),err);}});// re-read the queue in case the process function finished immediately or added another item
1436
1516
  queue=(_ref7=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_ref7!==undefined?_ref7:[];this.schedule.cancel(this.processId);if(queue.length>0){var nextProcessExecutionTime=queue[0].time-now;this.processId=this.schedule.run(this.processHead,nextProcessExecutionTime,ScheduleModes.ASAP);}}// Ack continuously to prevent other tabs from claiming our queue
1437
- },{key:"ack",value:function ack(){this.setStorageEntry(QueueStatuses.ACK,this.schedule.now());if(this.reclaimStartVal!=null){this.reclaimStartVal=null;this.setStorageEntry(QueueStatuses.RECLAIM_START,null);}if(this.reclaimEndVal!=null){this.reclaimEndVal=null;this.setStorageEntry(QueueStatuses.RECLAIM_END,null);}this.schedule.run(this.ack,this.timeouts.ackTimer,ScheduleModes.ASAP);}},{key:"reclaim",value:function reclaim(id){var _this$getStorageEntry,_other$get,_other$get2,_other$get3,_this2=this;var other=this.storeManager.setStore({id:id,name:this.name,validKeys:QueueStatuses,type:LOCAL_STORAGE});var our={queue:(_this$getStorageEntry=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_this$getStorageEntry!==undefined?_this$getStorageEntry:[]};var their={inProgress:(_other$get=other.get(QueueStatuses.IN_PROGRESS))!==null&&_other$get!==undefined?_other$get:{},batchQueue:(_other$get2=other.get(QueueStatuses.BATCH_QUEUE))!==null&&_other$get2!==undefined?_other$get2:[],queue:(_other$get3=other.get(QueueStatuses.QUEUE))!==null&&_other$get3!==undefined?_other$get3:[]};var trackMessageIds=[];var addConcatQueue=function addConcatQueue(queue,incrementAttemptNumberBy){var concatIterator=function concatIterator(el){var _el$id;var id=(_el$id=el.id)!==null&&_el$id!==undefined?_el$id:generateUUID();if(trackMessageIds.includes(id));else {var _el$type;// Hack to determine the item type by the contents of the entry
1517
+ },{key:"ack",value:function ack(){this.setStorageEntry(QueueStatuses.ACK,this.schedule.now());if(this.reclaimStartVal!=null){this.reclaimStartVal=null;this.setStorageEntry(QueueStatuses.RECLAIM_START,null);}if(this.reclaimEndVal!=null){this.reclaimEndVal=null;this.setStorageEntry(QueueStatuses.RECLAIM_END,null);}this.schedule.run(this.ack,this.timeouts.ackTimer,ScheduleModes.ASAP);}},{key:"reclaim",value:function reclaim(id){var _this$getStorageEntry,_other$get,_other$get2,_other$get3,_this2=this;var other=this.storeManager.setStore({id:id,name:this.name,validKeys:QueueStatuses,type:LOCAL_STORAGE,errorHandler:this.storeManager.errorHandler,logger:this.storeManager.logger});var our={queue:(_this$getStorageEntry=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_this$getStorageEntry!==undefined?_this$getStorageEntry:[]};var their={inProgress:(_other$get=other.get(QueueStatuses.IN_PROGRESS))!==null&&_other$get!==undefined?_other$get:{},batchQueue:(_other$get2=other.get(QueueStatuses.BATCH_QUEUE))!==null&&_other$get2!==undefined?_other$get2:[],queue:(_other$get3=other.get(QueueStatuses.QUEUE))!==null&&_other$get3!==undefined?_other$get3:[]};var trackMessageIds=[];var addConcatQueue=function addConcatQueue(queue,incrementAttemptNumberBy){var concatIterator=function concatIterator(el){var _el$id;var id=(_el$id=el.id)!==null&&_el$id!==undefined?_el$id:generateUUID();if(trackMessageIds.includes(id));else {var _el$type;// Hack to determine the item type by the contents of the entry
1438
1518
  // After some point, we can remove this hack as most of the stale data will have been processed
1439
1519
  // and the new entries will have the type field set
1440
1520
  var type=Array.isArray(el.item)?BATCH_QUEUE_ITEM_TYPE:SINGLE_QUEUE_ITEM_TYPE;our.queue.push({item:el.item,attemptNumber:el.attemptNumber+incrementAttemptNumberBy,time:_this2.schedule.now(),id:id,type:(_el$type=el.type)!==null&&_el$type!==undefined?_el$type:type});trackMessageIds.push(id);}};if(Array.isArray(queue)){queue.forEach(concatIterator);}else if(queue){Object.values(queue).forEach(concatIterator);}};// add their queue to ours, resetting run-time to immediate and copying the attempt#
@@ -1449,9 +1529,9 @@ if(entryIdx+1<queueEntryKeys.length){_this3.removeStorageEntry(store,entryIdx+1,
1449
1529
  _this3.removeStorageEntry(store,entryIdx,backoff+40,attempt+1);}else {var _this3$logger;(_this3$logger=_this3.logger)===null||_this3$logger===undefined||_this3$logger.error(RETRY_QUEUE_ENTRY_REMOVE_ERROR(RETRY_QUEUE,entry,attempt),err);}// clear the next entry after we've exhausted our attempts
1450
1530
  if(attempt===maxAttempts&&entryIdx+1<queueEntryKeys.length){_this3.removeStorageEntry(store,entryIdx+1,backoff);}}},backoff);}},{key:"checkReclaim",value:function checkReclaim(){var _this4=this;var createReclaimStartTask=function createReclaimStartTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_END)!==_this4.id){return;}if(store.get(QueueStatuses.RECLAIM_START)!==_this4.id){return;}_this4.reclaim(store.id);};};var createReclaimEndTask=function createReclaimEndTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_START)!==_this4.id){return;}store.set(QueueStatuses.RECLAIM_END,_this4.id);_this4.schedule.run(createReclaimStartTask(store),_this4.timeouts.reclaimWait,ScheduleModes.ABANDON);};};var tryReclaim=function tryReclaim(store){store.set(QueueStatuses.RECLAIM_START,_this4.id);store.set(QueueStatuses.ACK,_this4.schedule.now());_this4.schedule.run(createReclaimEndTask(store),_this4.timeouts.reclaimWait,ScheduleModes.ABANDON);};var findOtherQueues=function findOtherQueues(name){var res=[];var storageEngine=_this4.store.getOriginalEngine();var storageKeys=[];// 'keys' API is not supported by all the core SDK versions
1451
1531
  // Hence, we need this backward compatibility check
1452
- if(isFunction(storageEngine.keys)){storageKeys=storageEngine.keys();}else {for(var i=0;i<storageEngine.length;i++){var key=storageEngine.key(i);if(key){storageKeys.push(key);}}}storageKeys.forEach(function(k){var keyParts=k?k.split('.'):[];if(keyParts.length>=3&&keyParts[0]===name&&keyParts[1]!==_this4.id&&keyParts[2]===QueueStatuses.ACK){res.push(_this4.storeManager.setStore({id:keyParts[1],name:name,validKeys:QueueStatuses,type:LOCAL_STORAGE}));}});return res;};findOtherQueues(this.name).forEach(function(store){if(_this4.schedule.now()-store.get(QueueStatuses.ACK)<_this4.timeouts.reclaimTimeout){return;}tryReclaim(store);});this.schedule.run(this.checkReclaim,this.timeouts.reclaimTimer,ScheduleModes.RESCHEDULE);}},{key:"clear",value:function clear(){this.schedule.cancelAll();this.setDefaultQueueEntries();}}]);}();
1532
+ if(isFunction(storageEngine.keys)){storageKeys=storageEngine.keys();}else {for(var i=0;i<storageEngine.length;i++){var key=storageEngine.key(i);if(key){storageKeys.push(key);}}}storageKeys.forEach(function(k){var keyParts=k?k.split('.'):[];if(keyParts.length>=3&&keyParts[0]===name&&keyParts[1]!==_this4.id&&keyParts[2]===QueueStatuses.ACK){res.push(_this4.storeManager.setStore({id:keyParts[1],name:name,validKeys:QueueStatuses,type:LOCAL_STORAGE,errorHandler:_this4.storeManager.errorHandler,logger:_this4.storeManager.logger}));}});return res;};findOtherQueues(this.name).forEach(function(store){if(_this4.schedule.now()-store.get(QueueStatuses.ACK)<_this4.timeouts.reclaimTimeout){return;}tryReclaim(store);});this.schedule.run(this.checkReclaim,this.timeouts.reclaimTimer,ScheduleModes.RESCHEDULE);}},{key:"clear",value:function clear(){this.schedule.cancelAll();this.setDefaultQueueEntries();}}]);}();
1453
1533
 
1454
- var pluginName$f='BeaconQueue';var BeaconQueue=function BeaconQueue(){return {name:pluginName$f,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$f]);},dataplaneEventsQueue:{/**
1534
+ var pluginName$d='BeaconQueue';var BeaconQueue=function BeaconQueue(){return {name:pluginName$d,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$d]);},dataplaneEventsQueue:{/**
1455
1535
  * Initialize the queue for delivery
1456
1536
  * @param state Application state
1457
1537
  * @param httpClient http client instance
@@ -1475,24 +1555,11 @@ return getBatchDeliveryPayload$1(events,currentTime,logger).size;});return event
1475
1555
  // It'll be updated to the latest timestamp during actual delivery
1476
1556
  event.sentAt=getCurrentTimeFormatted();validateEventPayloadSize(event,logger);eventsQueue.addItem({event:event});}}};};
1477
1557
 
1478
- var BUGSNAG_API_KEY_VALIDATION_ERROR=function BUGSNAG_API_KEY_VALIDATION_ERROR(apiKey){return "The Bugsnag API key (".concat(apiKey,") is invalid or not provided.");};var BUGSNAG_SDK_URL_ERROR='The Bugsnag SDK URL is invalid. Failed to load the Bugsnag SDK.';
1479
-
1480
- var API_KEY='0d96a60df267f4a13f808bbaa54e535c';
1481
-
1482
- var isApiKeyValid=function isApiKeyValid(apiKey){var isAPIKeyValid=!(apiKey.startsWith('{{')||apiKey.endsWith('}}')||apiKey.length===0);return isAPIKeyValid;};
1483
-
1484
- var pluginName$e='Bugsnag';var Bugsnag=function Bugsnag(){return {name:pluginName$e,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$e]);},errorReportingProvider:{init:function init(state,externalSrcLoader,logger){return new Promise(function(resolve,reject){// If API key token is not parsed or invalid, don't proceed to initialize the client
1485
- if(!isApiKeyValid(API_KEY)){reject(new Error(BUGSNAG_API_KEY_VALIDATION_ERROR(API_KEY)));return;}// If SDK URL is empty, don't proceed to initialize the client
1486
- // eslint-disable-next-line no-constant-condition
1487
- // @ts-expect-error we're dynamically filling this value during build
1488
- // eslint-disable-next-line no-constant-condition
1489
- {reject(new Error(BUGSNAG_SDK_URL_ERROR));return;}});},notify:function notify(client,error,state,logger){client.notify(error);},breadcrumb:function breadcrumb(client,message,logger){client===null||client===undefined||client.leaveBreadcrumb(message);}}};};
1490
-
1491
1558
  var CUSTOM_CONSENT_MANAGER_PLUGIN='CustomConsentManagerPlugin';
1492
1559
 
1493
1560
  var DESTINATION_CONSENT_STATUS_ERROR$3="Failed to determine the consent status for the destination. Please check the destination configuration and try again.";
1494
1561
 
1495
- var pluginName$d='CustomConsentManager';var CustomConsentManager=function CustomConsentManager(){return {name:pluginName$d,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$d]);},consentManager:{init:function init(state,logger){// Nothing to initialize
1562
+ var pluginName$c='CustomConsentManager';var CustomConsentManager=function CustomConsentManager(){return {name:pluginName$c,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$c]);},consentManager:{init:function init(state,logger){// Nothing to initialize
1496
1563
  },updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){// Nothing to update. Already provided by the user
1497
1564
  },isDestinationConsented:function isDestinationConsented(state,destConfig,errorHandler,logger){if(!state.consents.initialized.value){return true;}var allowedConsentIds=state.consents.data.value.allowedConsentIds;try{var _cmpConfig$resolution;var consentManagement=destConfig.consentManagement;// If the destination does not have consent management config, events should be sent.
1498
1565
  if(!consentManagement){return true;}// Get the corresponding consents for the destination
@@ -1703,13 +1770,13 @@ var destDisplayNamesToFileNamesMap=(_destDisplayNamesToFi={},_defineProperty(_de
1703
1770
  if(isHybridModeDestination(initializedDestination)){state.nativeDestinations.integrationsConfig.value=getCumulativeIntegrationsConfig(initializedDestination,state.nativeDestinations.integrationsConfig.value,errorHandler);}state.nativeDestinations.initializedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.initializedDestinations.value),[initializedDestination]);}).catch(function(err){state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);// The error message is already formatted in the isDestinationReady function
1704
1771
  logger===null||logger===void 0||logger.error(err);});}catch(err){state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);errorHandler===null||errorHandler===undefined||errorHandler.onError(err,DEVICE_MODE_DESTINATIONS_PLUGIN,DESTINATION_INIT_ERROR(dest.userFriendlyId));}};
1705
1772
 
1706
- var pluginName$c='DeviceModeDestinations';var DeviceModeDestinations=function DeviceModeDestinations(){return {name:pluginName$c,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$c]);},nativeDestinations:{setActiveDestinations:function setActiveDestinations(state,pluginsManager,errorHandler,logger){var _state$consents$postC,_state$consents$postC2;state.nativeDestinations.loadIntegration.value=state.loadOptions.value.loadIntegration;// Filter destination that doesn't have mapping config-->Integration names
1773
+ var pluginName$b='DeviceModeDestinations';var DeviceModeDestinations=function DeviceModeDestinations(){return {name:pluginName$b,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$b]);},nativeDestinations:{setActiveDestinations:function setActiveDestinations(state,pluginsManager,errorHandler,logger){var _state$consents$postC,_state$consents$postC2;state.nativeDestinations.loadIntegration.value=state.loadOptions.value.loadIntegration;// Filter destination that doesn't have mapping config-->Integration names
1707
1774
  var configSupportedDestinations=state.nativeDestinations.configuredDestinations.value.filter(function(configDest){if(destDisplayNamesToFileNamesMap[configDest.displayName]){return true;}errorHandler===null||errorHandler===undefined||errorHandler.onError(new Error(DESTINATION_NOT_SUPPORTED_ERROR(configDest.userFriendlyId)),DEVICE_MODE_DESTINATIONS_PLUGIN);return false;});// Filter destinations that are disabled through load or consent API options
1708
1775
  var destinationsToLoad=filterDestinations((_state$consents$postC=(_state$consents$postC2=state.consents.postConsent.value)===null||_state$consents$postC2===undefined?undefined:_state$consents$postC2.integrations)!==null&&_state$consents$postC!==undefined?_state$consents$postC:state.nativeDestinations.loadOnlyIntegrations.value,configSupportedDestinations);var consentedDestinations=destinationsToLoad.filter(function(dest){var _pluginsManager$invok;return(// if consent manager is not configured, then default to load the destination
1709
1776
  (_pluginsManager$invok=pluginsManager.invokeSingle("consentManager.isDestinationConsented",state,dest.config,errorHandler,logger))!==null&&_pluginsManager$invok!==undefined?_pluginsManager$invok:true);});state.nativeDestinations.activeDestinations.value=consentedDestinations;},load:function load(state,externalSrcLoader,errorHandler,logger,externalScriptOnLoad){var integrationsCDNPath=state.lifecycle.integrationsCDNPath.value;var activeDestinations=state.nativeDestinations.activeDestinations.value;activeDestinations.forEach(function(dest){var sdkName=destDisplayNamesToFileNamesMap[dest.displayName];var destSDKIdentifier="".concat(sdkName,"_RS");// this is the name of the object loaded on the window
1710
1777
  var sdkTypeName=sdkName;if(sdkTypeName&&!isDestinationSDKMounted(destSDKIdentifier,sdkTypeName)){var destSdkURL="".concat(integrationsCDNPath,"/").concat(sdkName,".min.js");externalSrcLoader.loadJSFile({url:destSdkURL,id:dest.userFriendlyId,callback:externalScriptOnLoad!==null&&externalScriptOnLoad!==undefined?externalScriptOnLoad:function(id){if(!id){logger===null||logger===undefined||logger.error(DESTINATION_SDK_LOAD_ERROR(DEVICE_MODE_DESTINATIONS_PLUGIN,dest.userFriendlyId));state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);}else {initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger);}},timeout:SCRIPT_LOAD_TIMEOUT_MS});}else if(sdkTypeName){initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger);}else {logger===null||logger===undefined||logger.error(DESTINATION_SDK_LOAD_ERROR(DEVICE_MODE_DESTINATIONS_PLUGIN,dest.displayName));}});}}};};
1711
1778
 
1712
- var DEFAULT_TRANSFORMATION_QUEUE_OPTIONS={minRetryDelay:500,backoffFactor:2,maxAttempts:3};var REQUEST_TIMEOUT_MS$2=10*1000;// 10 seconds
1779
+ var DEFAULT_TRANSFORMATION_QUEUE_OPTIONS={minRetryDelay:500,backoffFactor:2,maxAttempts:3};var REQUEST_TIMEOUT_MS$1=10*1000;// 10 seconds
1713
1780
  var QUEUE_NAME$2='rudder';var DMT_PLUGIN='DeviceModeTransformationPlugin';
1714
1781
 
1715
1782
  var DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR=function DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR(context,displayName,reason,action){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Event transformation unsuccessful for destination \"").concat(displayName,"\". Reason: ").concat(reason,". ").concat(action,".");};var DMT_REQUEST_FAILED_ERROR=function DMT_REQUEST_FAILED_ERROR(context,displayName,status,action){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"[Destination: ").concat(displayName,"].Transformation request failed with status: ").concat(status,". Retries exhausted. ").concat(action,".");};var DMT_EXCEPTION=function DMT_EXCEPTION(displayName){return "[Destination:".concat(displayName,"].");};var DMT_SERVER_ACCESS_DENIED_WARNING=function DMT_SERVER_ACCESS_DENIED_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Transformation server access is denied. The configuration data seems to be out of sync. Sending untransformed event to the destination.");};
@@ -1721,88 +1788,10 @@ var DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR=function DMT_TRANSFORMATION_UNSUCCESSF
1721
1788
  */var createPayload=function createPayload(event,destinationIds,token){var orderNo=Date.now();var payload={metadata:{'Custom-Authorization':token},batch:[{orderNo:orderNo,destinationIds:destinationIds,event:event}]};return payload;};var sendTransformedEventToDestinations=function sendTransformedEventToDestinations(state,pluginsManager,destinationIds,result,status,event,errorHandler,logger){var NATIVE_DEST_EXT_POINT='destinationsEventsQueue.enqueueEventToDestination';var ACTION_TO_SEND_UNTRANSFORMED_EVENT='Sending untransformed event';var ACTION_TO_DROP_EVENT='Dropping the event';var destinations=state.nativeDestinations.initializedDestinations.value.filter(function(d){return d&&destinationIds.includes(d.id);});destinations.forEach(function(dest){try{var eventsToSend=[];switch(status){case 200:{var response=JSON.parse(result);var destTransformedResult=response.transformedBatch.find(function(e){return e.id===dest.id;});destTransformedResult===null||destTransformedResult===void 0||destTransformedResult.payload.forEach(function(tEvent){if(tEvent.status==='200'){eventsToSend.push(tEvent.event);}else {var reason='Unknown';if(tEvent.status==='410'){reason='Transformation is not available';}var action=ACTION_TO_DROP_EVENT;if(dest.propagateEventsUntransformedOnError===true){action=ACTION_TO_SEND_UNTRANSFORMED_EVENT;eventsToSend.push(event);logger===null||logger===void 0||logger.warn(DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR(DMT_PLUGIN,dest.displayName,reason,action));}else {logger===null||logger===void 0||logger.error(DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR(DMT_PLUGIN,dest.displayName,reason,action));}}});break;}// Transformation server access denied
1722
1789
  case 404:{logger===null||logger===void 0||logger.warn(DMT_SERVER_ACCESS_DENIED_WARNING(DMT_PLUGIN));eventsToSend.push(event);break;}default:{if(dest.propagateEventsUntransformedOnError===true){logger===null||logger===void 0||logger.warn(DMT_REQUEST_FAILED_ERROR(DMT_PLUGIN,dest.displayName,status,ACTION_TO_SEND_UNTRANSFORMED_EVENT));eventsToSend.push(event);}else {logger===null||logger===void 0||logger.error(DMT_REQUEST_FAILED_ERROR(DMT_PLUGIN,dest.displayName,status,ACTION_TO_DROP_EVENT));}break;}}eventsToSend===null||eventsToSend===void 0||eventsToSend.forEach(function(tEvent){if(isNonEmptyObject(tEvent)){pluginsManager.invokeSingle(NATIVE_DEST_EXT_POINT,state,tEvent,dest,errorHandler,logger);}});}catch(e){errorHandler===null||errorHandler===undefined||errorHandler.onError(e,DMT_PLUGIN,DMT_EXCEPTION(dest.displayName));}});};
1723
1790
 
1724
- var pluginName$b='DeviceModeTransformation';var DeviceModeTransformation=function DeviceModeTransformation(){return {name:pluginName$b,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$b]);},transformEvent:{init:function init(state,pluginsManager,httpClient,storeManager,errorHandler,logger){var writeKey=state.lifecycle.writeKey.value;httpClient.setAuthHeader(writeKey);var eventsQueue=new RetryQueue(// adding write key to the queue name to avoid conflicts
1725
- "".concat(QUEUE_NAME$2,"_").concat(writeKey),DEFAULT_TRANSFORMATION_QUEUE_OPTIONS,function(item,done,attemptNumber,maxRetryAttempts){var payload=createPayload(item.event,item.destinationIds,item.token);httpClient.getAsyncData({url:"".concat(state.lifecycle.activeDataplaneUrl.value,"/transform"),options:{method:'POST',data:getDMTDeliveryPayload(payload),sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS$2,callback:function callback(result,details){// null means item will not be requeued
1791
+ var pluginName$a='DeviceModeTransformation';var DeviceModeTransformation=function DeviceModeTransformation(){return {name:pluginName$a,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$a]);},transformEvent:{init:function init(state,pluginsManager,httpClient,storeManager,errorHandler,logger){var writeKey=state.lifecycle.writeKey.value;httpClient.setAuthHeader(writeKey);var eventsQueue=new RetryQueue(// adding write key to the queue name to avoid conflicts
1792
+ "".concat(QUEUE_NAME$2,"_").concat(writeKey),DEFAULT_TRANSFORMATION_QUEUE_OPTIONS,function(item,done,attemptNumber,maxRetryAttempts){var payload=createPayload(item.event,item.destinationIds,item.token);httpClient.getAsyncData({url:"".concat(state.lifecycle.activeDataplaneUrl.value,"/transform"),options:{method:'POST',data:getDMTDeliveryPayload(payload),sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS$1,callback:function callback(result,details){// null means item will not be requeued
1726
1793
  var queueErrResp=isErrRetryable(details)?details:null;if(!queueErrResp||attemptNumber===maxRetryAttempts){var _details$xhr;sendTransformedEventToDestinations(state,pluginsManager,item.destinationIds,result,details===null||details===undefined||(_details$xhr=details.xhr)===null||_details$xhr===undefined?undefined:_details$xhr.status,item.event,errorHandler,logger);}done(queueErrResp,result);}});},storeManager,MEMORY_STORAGE);return eventsQueue;},enqueue:function enqueue(state,eventsQueue,event,destinations){var destinationIds=destinations.map(function(d){return d.id;});eventsQueue.addItem({event:event,destinationIds:destinationIds,token:state.session.authToken.value});}}};};
1727
1794
 
1728
- // Errors from the below scripts are NOT allowed to reach Bugsnag
1729
- var SDK_FILE_NAME_PREFIXES=function SDK_FILE_NAME_PREFIXES(){return ['rsa'// Prefix for all the SDK scripts including plugins and module federated chunks
1730
- ];};var DEV_HOSTS=['www.test-host.com','localhost','127.0.0.1','[::1]'];// List of keys to exclude from the metadata
1731
- // Potential PII or sensitive data
1732
- var APP_STATE_EXCLUDE_KEYS=['userId','userTraits','groupId','groupTraits','anonymousId','config','instance',// destination instance objects
1733
- 'eventBuffer',// pre-load event buffer (may contain PII)
1734
- 'traits','authToken'];var REQUEST_TIMEOUT_MS$1=10*1000;// 10 seconds
1735
- var NOTIFIER_NAME='RudderStack JavaScript SDK Error Notifier';var SDK_GITHUB_URL='https://github.com/rudderlabs/rudder-sdk-js';var SOURCE_NAME='js';var ERROR_REPORTING_PLUGIN='ErrorReportingPlugin';
1736
-
1737
- var getConfigForPayloadCreation=function getConfigForPayloadCreation(err,errorType){switch(errorType){case ErrorType.UNHANDLEDEXCEPTION:{var _ref=err,error=_ref.error;return {component:'unhandledException handler',normalizedError:error||err};}case ErrorType.UNHANDLEDREJECTION:{var _error=err;return {component:'unhandledrejection handler',normalizedError:_error.reason};}case ErrorType.HANDLEDEXCEPTION:default:return {component:'notify()',normalizedError:err};}};var createNewBreadcrumb=function createNewBreadcrumb(message,metaData){return {type:'manual',name:message,timestamp:new Date(),metaData:metaData!==null&&metaData!==undefined?metaData:{}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};var getAppStateForMetadata=function getAppStateForMetadata(state){var stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS);return stateStr!==null?JSON.parse(stateStr):{};};var getURLWithoutQueryString=function getURLWithoutQueryString(){var url=globalThis.location.href.split('?');return url[0];};var getErrorContext=function getErrorContext(event){var message=event.message;var context=message;// Hack for easily grouping the script load errors
1738
- // on the dashboard
1739
- if(message.includes('Error in loading a third-party script')){context='Script load failures';}return context;};var getBugsnagErrorEvent=function getBugsnagErrorEvent(payload,errorState,state){var _state$context$locale,_state$context$userAg,_getAppStateForMetada,_state$source$value$i,_state$source$value,_state$session$sessio,_state$session$sessio2,_state$autoTrack$page,_state$autoTrack;return {notifier:{name:NOTIFIER_NAME,version:state.context.app.value.version,url:SDK_GITHUB_URL},events:[{payloadVersion:'5',exceptions:clone(payload.errors),severity:errorState.severity,unhandled:errorState.unhandled,severityReason:errorState.severityReason,app:{version:state.context.app.value.version,releaseStage:getReleaseStage()},device:{locale:(_state$context$locale=state.context.locale.value)!==null&&_state$context$locale!==undefined?_state$context$locale:undefined,userAgent:(_state$context$userAg=state.context.userAgent.value)!==null&&_state$context$userAg!==undefined?_state$context$userAg:undefined,time:new Date()},request:{url:getURLWithoutQueryString(),clientIp:'[NOT COLLECTED]'},breadcrumbs:clone(state.reporting.breadcrumbs.value),context:getErrorContext(payload.errors[0]),metaData:{sdk:{name:'JS',installType:state.context.app.value.installType},state:(_getAppStateForMetada=getAppStateForMetadata(state))!==null&&_getAppStateForMetada!==undefined?_getAppStateForMetada:{},source:{snippetVersion:globalThis.RudderSnippetVersion}},user:{// Combination of source, session and visit ids
1740
- id:"".concat((_state$source$value$i=(_state$source$value=state.source.value)===null||_state$source$value===undefined?undefined:_state$source$value.id)!==null&&_state$source$value$i!==undefined?_state$source$value$i:state.lifecycle.writeKey.value,"..").concat((_state$session$sessio=(_state$session$sessio2=state.session.sessionInfo.value)===null||_state$session$sessio2===undefined?undefined:_state$session$sessio2.id)!==null&&_state$session$sessio!==undefined?_state$session$sessio:'NA',"..").concat((_state$autoTrack$page=(_state$autoTrack=state.autoTrack)===null||_state$autoTrack===undefined||(_state$autoTrack=_state$autoTrack.pageLifecycle)===null||_state$autoTrack===undefined||(_state$autoTrack=_state$autoTrack.visitId)===null||_state$autoTrack===undefined?undefined:_state$autoTrack.value)!==null&&_state$autoTrack$page!==undefined?_state$autoTrack$page:'NA')}}]};};/**
1741
- * A function to determine whether the error should be promoted to notify or not
1742
- * @param {Error} error
1743
- * @returns
1744
- */var isAllowedToBeNotified=function isAllowedToBeNotified(event){var errorMessage=event.message;if(errorMessage&&typeof errorMessage==='string'){return !ERROR_MESSAGES_TO_BE_FILTERED.some(function(e){return errorMessage.includes(e);});}return true;};/**
1745
- * A function to determine if the error is from Rudder SDK
1746
- * @param {Error} event
1747
- * @returns
1748
- */var isRudderSDKError=function isRudderSDKError(event){var _event$stacktrace;var errorOrigin=(_event$stacktrace=event.stacktrace)===null||_event$stacktrace===undefined||(_event$stacktrace=_event$stacktrace[0])===null||_event$stacktrace===undefined?undefined:_event$stacktrace.file;if(!errorOrigin||typeof errorOrigin!=='string'){return false;}var srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);var paths=errorOrigin.split('/');// extract the parent folder name from the error origin file path
1749
- // Ex: parentFolderName will be 'sample' for url: https://example.com/sample/file.min.js
1750
- var parentFolderName=paths[paths.length-2];return parentFolderName===CDN_INT_DIR||SDK_FILE_NAME_PREFIXES().some(function(prefix){return srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js');});};var getErrorDeliveryPayload=function getErrorDeliveryPayload(payload,state){var data={version:METRICS_PAYLOAD_VERSION,message_id:generateUUID(),source:{name:SOURCE_NAME,sdk_version:state.context.app.value.version,write_key:state.lifecycle.writeKey.value,install_type:state.context.app.value.installType},errors:payload};return stringifyWithoutCircular(data);};
1751
-
1752
- function getDefaultExportFromCjs (x) {
1753
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
1754
- }
1755
-
1756
- var errorStackParser$1 = {exports: {}};
1757
-
1758
- var stackframe$1 = {exports: {}};
1759
-
1760
- var stackframe=stackframe$1.exports;var hasRequiredStackframe;function requireStackframe(){if(hasRequiredStackframe)return stackframe$1.exports;hasRequiredStackframe=1;(function(module,exports){(function(root,factory){/* istanbul ignore next */{module.exports=factory();}})(stackframe,function(){function _isNumber(n){return !isNaN(parseFloat(n))&&isFinite(n);}function _capitalize(str){return str.charAt(0).toUpperCase()+str.substring(1);}function _getter(p){return function(){return this[p];};}var booleanProps=['isConstructor','isEval','isNative','isToplevel'];var numericProps=['columnNumber','lineNumber'];var stringProps=['fileName','functionName','source'];var arrayProps=['args'];var objectProps=['evalOrigin'];var props=booleanProps.concat(numericProps,stringProps,arrayProps,objectProps);function StackFrame(obj){if(!obj)return;for(var i=0;i<props.length;i++){if(obj[props[i]]!==undefined){this['set'+_capitalize(props[i])](obj[props[i]]);}}}StackFrame.prototype={getArgs:function getArgs(){return this.args;},setArgs:function setArgs(v){if(Object.prototype.toString.call(v)!=='[object Array]'){throw new TypeError('Args must be an Array');}this.args=v;},getEvalOrigin:function getEvalOrigin(){return this.evalOrigin;},setEvalOrigin:function setEvalOrigin(v){if(v instanceof StackFrame){this.evalOrigin=v;}else if(v instanceof Object){this.evalOrigin=new StackFrame(v);}else {throw new TypeError('Eval Origin must be an Object or StackFrame');}},toString:function toString(){var fileName=this.getFileName()||'';var lineNumber=this.getLineNumber()||'';var columnNumber=this.getColumnNumber()||'';var functionName=this.getFunctionName()||'';if(this.getIsEval()){if(fileName){return '[eval] ('+fileName+':'+lineNumber+':'+columnNumber+')';}return '[eval]:'+lineNumber+':'+columnNumber;}if(functionName){return functionName+' ('+fileName+':'+lineNumber+':'+columnNumber+')';}return fileName+':'+lineNumber+':'+columnNumber;}};StackFrame.fromString=function StackFrame$$fromString(str){var argsStartIndex=str.indexOf('(');var argsEndIndex=str.lastIndexOf(')');var functionName=str.substring(0,argsStartIndex);var args=str.substring(argsStartIndex+1,argsEndIndex).split(',');var locationString=str.substring(argsEndIndex+1);if(locationString.indexOf('@')===0){var parts=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(locationString,'');var fileName=parts[1];var lineNumber=parts[2];var columnNumber=parts[3];}return new StackFrame({functionName:functionName,args:args||undefined,fileName:fileName,lineNumber:lineNumber||undefined,columnNumber:columnNumber||undefined});};for(var i=0;i<booleanProps.length;i++){StackFrame.prototype['get'+_capitalize(booleanProps[i])]=_getter(booleanProps[i]);StackFrame.prototype['set'+_capitalize(booleanProps[i])]=function(p){return function(v){this[p]=Boolean(v);};}(booleanProps[i]);}for(var j=0;j<numericProps.length;j++){StackFrame.prototype['get'+_capitalize(numericProps[j])]=_getter(numericProps[j]);StackFrame.prototype['set'+_capitalize(numericProps[j])]=function(p){return function(v){if(!_isNumber(v)){throw new TypeError(p+' must be a Number');}this[p]=Number(v);};}(numericProps[j]);}for(var k=0;k<stringProps.length;k++){StackFrame.prototype['get'+_capitalize(stringProps[k])]=_getter(stringProps[k]);StackFrame.prototype['set'+_capitalize(stringProps[k])]=function(p){return function(v){this[p]=String(v);};}(stringProps[k]);}return StackFrame;});})(stackframe$1);return stackframe$1.exports;}
1761
-
1762
- var errorStackParser=errorStackParser$1.exports;var hasRequiredErrorStackParser;function requireErrorStackParser(){if(hasRequiredErrorStackParser)return errorStackParser$1.exports;hasRequiredErrorStackParser=1;(function(module,exports){(function(root,factory){/* istanbul ignore next */{module.exports=factory(requireStackframe());}})(errorStackParser,function ErrorStackParser(StackFrame){var FIREFOX_SAFARI_STACK_REGEXP=/(^|@)\S+:\d+/;var CHROME_IE_STACK_REGEXP=/^\s*at .*(\S+:\d+|\(native\))/m;var SAFARI_NATIVE_CODE_REGEXP=/^(eval@)?(\[native code])?$/;return {/**
1763
- * Given an Error object, extract the most information from it.
1764
- *
1765
- * @param {Error} error object
1766
- * @return {Array} of StackFrames
1767
- */parse:function ErrorStackParser$$parse(error){if(typeof error.stacktrace!=='undefined'||typeof error['opera#sourceloc']!=='undefined'){return this.parseOpera(error);}else if(error.stack&&error.stack.match(CHROME_IE_STACK_REGEXP)){return this.parseV8OrIE(error);}else if(error.stack){return this.parseFFOrSafari(error);}else {throw new Error('Cannot parse given Error object');}},// Separate line and column numbers from a string of the form: (URI:Line:Column)
1768
- extractLocation:function ErrorStackParser$$extractLocation(urlLike){// Fail-fast but return locations like "(native)"
1769
- if(urlLike.indexOf(':')===-1){return [urlLike];}var regExp=/(.+?)(?::(\d+))?(?::(\d+))?$/;var parts=regExp.exec(urlLike.replace(/[()]/g,''));return [parts[1],parts[2]||undefined,parts[3]||undefined];},parseV8OrIE:function ErrorStackParser$$parseV8OrIE(error){var filtered=error.stack.split('\n').filter(function(line){return !!line.match(CHROME_IE_STACK_REGEXP);},this);return filtered.map(function(line){if(line.indexOf('(eval ')>-1){// Throw away eval information until we implement stacktrace.js/stackframe#8
1770
- line=line.replace(/eval code/g,'eval').replace(/(\(eval at [^()]*)|(,.*$)/g,'');}var sanitizedLine=line.replace(/^\s+/,'').replace(/\(eval code/g,'(').replace(/^.*?\s+/,'');// capture and preseve the parenthesized location "(/foo/my bar.js:12:87)" in
1771
- // case it has spaces in it, as the string is split on \s+ later on
1772
- var location=sanitizedLine.match(/ (\(.+\)$)/);// remove the parenthesized location from the line, if it was matched
1773
- sanitizedLine=location?sanitizedLine.replace(location[0],''):sanitizedLine;// if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine
1774
- // because this line doesn't have function name
1775
- var locationParts=this.extractLocation(location?location[1]:sanitizedLine);var functionName=location&&sanitizedLine||undefined;var fileName=['eval','<anonymous>'].indexOf(locationParts[0])>-1?undefined:locationParts[0];return new StackFrame({functionName:functionName,fileName:fileName,lineNumber:locationParts[1],columnNumber:locationParts[2],source:line});},this);},parseFFOrSafari:function ErrorStackParser$$parseFFOrSafari(error){var filtered=error.stack.split('\n').filter(function(line){return !line.match(SAFARI_NATIVE_CODE_REGEXP);},this);return filtered.map(function(line){// Throw away eval information until we implement stacktrace.js/stackframe#8
1776
- if(line.indexOf(' > eval')>-1){line=line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,':$1');}if(line.indexOf('@')===-1&&line.indexOf(':')===-1){// Safari eval frames only have function names and nothing else
1777
- return new StackFrame({functionName:line});}else {var functionNameRegex=/((.*".+"[^@]*)?[^@]*)(?:@)/;var matches=line.match(functionNameRegex);var functionName=matches&&matches[1]?matches[1]:undefined;var locationParts=this.extractLocation(line.replace(functionNameRegex,''));return new StackFrame({functionName:functionName,fileName:locationParts[0],lineNumber:locationParts[1],columnNumber:locationParts[2],source:line});}},this);},parseOpera:function ErrorStackParser$$parseOpera(e){if(!e.stacktrace||e.message.indexOf('\n')>-1&&e.message.split('\n').length>e.stacktrace.split('\n').length){return this.parseOpera9(e);}else if(!e.stack){return this.parseOpera10(e);}else {return this.parseOpera11(e);}},parseOpera9:function ErrorStackParser$$parseOpera9(e){var lineRE=/Line (\d+).*script (?:in )?(\S+)/i;var lines=e.message.split('\n');var result=[];for(var i=2,len=lines.length;i<len;i+=2){var match=lineRE.exec(lines[i]);if(match){result.push(new StackFrame({fileName:match[2],lineNumber:match[1],source:lines[i]}));}}return result;},parseOpera10:function ErrorStackParser$$parseOpera10(e){var lineRE=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i;var lines=e.stacktrace.split('\n');var result=[];for(var i=0,len=lines.length;i<len;i+=2){var match=lineRE.exec(lines[i]);if(match){result.push(new StackFrame({functionName:match[3]||undefined,fileName:match[2],lineNumber:match[1],source:lines[i]}));}}return result;},// Opera 10.65+ Error.stack very similar to FF/Safari
1778
- parseOpera11:function ErrorStackParser$$parseOpera11(error){var filtered=error.stack.split('\n').filter(function(line){return !!line.match(FIREFOX_SAFARI_STACK_REGEXP)&&!line.match(/^Error created at/);},this);return filtered.map(function(line){var tokens=line.split('@');var locationParts=this.extractLocation(tokens.pop());var functionCall=tokens.shift()||'';var functionName=functionCall.replace(/<anonymous function(: (\w+))?>/,'$2').replace(/\([^)]*\)/g,'')||undefined;var argsRaw;if(functionCall.match(/\(([^)]*)\)/)){argsRaw=functionCall.replace(/^[^(]+\(([^)]*)\)$/,'$1');}var args=argsRaw===undefined||argsRaw==='[arguments not available]'?undefined:argsRaw.split(',');return new StackFrame({functionName:functionName,args:args,fileName:locationParts[0],lineNumber:locationParts[1],columnNumber:locationParts[2],source:line});},this);}};});})(errorStackParser$1);return errorStackParser$1.exports;}
1779
-
1780
- var errorStackParserExports = requireErrorStackParser();
1781
- var ErrorStackParser = /*@__PURE__*/getDefaultExportFromCjs(errorStackParserExports);
1782
-
1783
- var hasStack=function hasStack(err){return !!err&&(!!err.stack||!!err.stacktrace||!!err['opera#sourceloc'])&&typeof(err.stack||err.stacktrace||err['opera#sourceloc'])==='string'&&err.stack!=="".concat(err.name,": ").concat(err.message);};var isError=function isError(value){switch(Object.prototype.toString.call(value)){case '[object Error]':case '[object Exception]':case '[object DOMException]':return true;default:return value instanceof Error;}};
1784
-
1785
- var normaliseFunctionName=function normaliseFunctionName(name){return /^global code$/i.test(name)?'global code':name;};// takes a stacktrace.js style stackframe (https://github.com/stacktracejs/stackframe)
1786
- // and returns a Bugsnag compatible stackframe (https://docs.bugsnag.com/api/error-reporting/#json-payload)
1787
- var formatStackframe=function formatStackframe(frame){var f={file:frame.fileName,method:normaliseFunctionName(frame.functionName),lineNumber:frame.lineNumber,columnNumber:frame.columnNumber,code:undefined,inProject:undefined};// Some instances result in no file:
1788
- // - calling notify() from chrome's terminal results in no file/method.
1789
- // - non-error exception thrown from global code in FF
1790
- // This adds one.
1791
- if(f.lineNumber>-1&&!f.file&&!f.method){f.file='global code';}return f;};var ensureString=function ensureString(str){return typeof str==='string'?str:'';};function createBugsnagError(errorClass,errorMessage,stacktrace){return {errorClass:ensureString(errorClass),message:ensureString(errorMessage),type:'browserjs',stacktrace:stacktrace.reduce(function(accum,frame){var f=formatStackframe(frame);// don't include a stackframe if none of its properties are defined
1792
- try{if(JSON.stringify(f)==='{}')return accum;return accum.concat(f);}catch(e){return accum;}},[])};}// Helpers
1793
- var getStacktrace=function getStacktrace(error){if(hasStack(error))return ErrorStackParser.parse(error);return [];};var normaliseError=function normaliseError(maybeError,component,logger){var error;if(isError(maybeError)){error=maybeError;}else {logger===null||logger===undefined||logger.warn("".concat(ERROR_REPORTING_PLUGIN,":: ").concat(component," received a non-error: ").concat(stringifyWithoutCircular(error)));error=undefined;}if(error&&!hasStack(error)){error=undefined;}return error;};var ErrorFormat=/*#__PURE__*/function(){function ErrorFormat(errorClass,errorMessage,stacktrace){_classCallCheck(this,ErrorFormat);this.errors=[createBugsnagError(errorClass,errorMessage,stacktrace)];}return _createClass(ErrorFormat,null,[{key:"create",value:function create(maybeError,component,logger){var error=normaliseError(maybeError,component,logger);if(!error){return undefined;}var event;try{var stacktrace=getStacktrace(error);event=new ErrorFormat(error.name,error.message,stacktrace);}catch(e){event=new ErrorFormat(error.name,error.message,[]);}return event;}}]);}();
1794
-
1795
- var INVALID_SOURCE_CONFIG_ERROR="Invalid source configuration or source id.";
1796
-
1797
- var pluginName$a='ErrorReporting';var ErrorReporting=function ErrorReporting(){return {name:pluginName$a,deps:[],initialize:function initialize(state){var _state$reporting$brea;state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$a]);state.reporting.isErrorReportingPluginLoaded.value=true;if((_state$reporting$brea=state.reporting.breadcrumbs)!==null&&_state$reporting$brea!==undefined&&_state$reporting$brea.value){state.reporting.breadcrumbs.value=[createNewBreadcrumb('Error Reporting Plugin Loaded')];}},errorReporting:{// This extension point is deprecated
1798
- // TODO: Remove this in the next major release
1799
- init:function init(state,pluginEngine,externalSrcLoader,logger,isInvokedFromLatestCore){var _state$source$value,_state$source$value2;if(isInvokedFromLatestCore){return undefined;}if(!((_state$source$value=state.source.value)!==null&&_state$source$value!==undefined&&_state$source$value.config)||!((_state$source$value2=state.source.value)!==null&&_state$source$value2!==undefined&&_state$source$value2.id)){return Promise.reject(new Error(INVALID_SOURCE_CONFIG_ERROR));}return pluginEngine.invokeSingle('errorReportingProvider.init',state,externalSrcLoader,logger);},notify:function notify(pluginEngine,client,error,state,logger,httpClient,errorState){if(httpClient){var _getConfigForPayloadC=getConfigForPayloadCreation(error,errorState===null||errorState===undefined?undefined:errorState.severityReason.type),component=_getConfigForPayloadC.component,normalizedError=_getConfigForPayloadC.normalizedError;// Generate the error payload
1800
- var errorPayload=ErrorFormat.create(normalizedError,component,logger);if(!errorPayload||!isAllowedToBeNotified(errorPayload.errors[0])){return;}// filter errors
1801
- if(!isRudderSDKError(errorPayload.errors[0])){return;}// enrich error payload
1802
- var bugsnagPayload=getBugsnagErrorEvent(errorPayload,errorState,state);// send it to metrics service
1803
- httpClient===null||httpClient===undefined||httpClient.getAsyncData({url:state.metrics.metricsServiceUrl.value,options:{method:'POST',data:getErrorDeliveryPayload(bugsnagPayload,state),sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS$1,callback:function callback(result,details){// do nothing
1804
- }});}else {pluginEngine.invokeSingle('errorReportingProvider.notify',client,error,state,logger);}},breadcrumb:function breadcrumb(pluginEngine,client,message,logger,state,metaData){if(state){state.reporting.breadcrumbs.value=[].concat(_toConsumableArray(state.reporting.breadcrumbs.value),[createNewBreadcrumb(message,metaData)]);}else {pluginEngine.invokeSingle('errorReportingProvider.breadcrumb',client,message,logger);}}}};};
1805
-
1806
1795
  var externallyLoadedSessionStorageKeys={segment:'ajs_anonymous_id'};
1807
1796
 
1808
1797
  var getSegmentAnonymousId=function getSegmentAnonymousId(getStorageEngine){var anonymousId;/**
@@ -1916,7 +1905,7 @@ var _matchedCookie$split=matchedCookie.split('='),_matchedCookie$split2=_slicedT
1916
1905
  * @param storeManager Store manager instance
1917
1906
  * @param logger Logger instance
1918
1907
  * @returns Consent data from the consent cookie
1919
- */var getIubendaConsentData=function getIubendaConsentData(storeManager,logger){var rawConsentCookieData=null;try{var dataStore=storeManager===null||storeManager===void 0?void 0:storeManager.setStore({id:IUBENDA_CONSENT_MANAGER_PLUGIN,name:IUBENDA_CONSENT_MANAGER_PLUGIN,type:COOKIE_STORAGE});rawConsentCookieData=dataStore===null||dataStore===void 0?void 0:dataStore.engine.getItem(getIubendaCookieName(logger));}catch(err){logger===null||logger===undefined||logger.error(IUBENDA_CONSENT_COOKIE_READ_ERROR(IUBENDA_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(isNullOrUndefined(rawConsentCookieData)){return undefined;}// Decode and parse the cookie data to JSON
1908
+ */var getIubendaConsentData=function getIubendaConsentData(storeManager,logger){var rawConsentCookieData=null;try{var dataStore=storeManager===null||storeManager===void 0?void 0:storeManager.setStore({id:IUBENDA_CONSENT_MANAGER_PLUGIN,name:IUBENDA_CONSENT_MANAGER_PLUGIN,type:COOKIE_STORAGE,errorHandler:storeManager===null||storeManager===void 0?void 0:storeManager.errorHandler,logger:storeManager===null||storeManager===void 0?void 0:storeManager.logger});rawConsentCookieData=dataStore===null||dataStore===void 0?void 0:dataStore.engine.getItem(getIubendaCookieName(logger));}catch(err){logger===null||logger===undefined||logger.error(IUBENDA_CONSENT_COOKIE_READ_ERROR(IUBENDA_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(isNullOrUndefined(rawConsentCookieData)){return undefined;}// Decode and parse the cookie data to JSON
1920
1909
  var consentCookieData;try{consentCookieData=JSON.parse(decodeURIComponent(rawConsentCookieData));}catch(err){logger===null||logger===undefined||logger.error(IUBENDA_CONSENT_COOKIE_PARSE_ERROR(IUBENDA_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(!consentCookieData){return undefined;}// Convert the cookie data to consent data
1921
1910
  var consentPurposes=consentCookieData.purposes;return consentPurposes;};/**
1922
1911
  * Gets the consent data in the format expected by the application state
@@ -1949,7 +1938,7 @@ var KETCH_CONSENT_MANAGER_PLUGIN='KetchConsentManagerPlugin';var KETCH_CONSENT_C
1949
1938
  * @param logger Logger instance
1950
1939
  * @returns Consent data from the consent cookie
1951
1940
  */var getKetchConsentData=function getKetchConsentData(storeManager,logger){var rawConsentCookieData=null;try{// Create a data store instance to read the consent cookie
1952
- var dataStore=storeManager===null||storeManager===void 0?void 0:storeManager.setStore({id:KETCH_CONSENT_MANAGER_PLUGIN,name:KETCH_CONSENT_MANAGER_PLUGIN,type:COOKIE_STORAGE});rawConsentCookieData=dataStore===null||dataStore===void 0?void 0:dataStore.engine.getItem(KETCH_CONSENT_COOKIE_NAME_V1);}catch(err){logger===null||logger===undefined||logger.error(KETCH_CONSENT_COOKIE_READ_ERROR(KETCH_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(isNullOrUndefined(rawConsentCookieData)){return undefined;}// Decode and parse the cookie data to JSON
1941
+ var dataStore=storeManager===null||storeManager===void 0?void 0:storeManager.setStore({id:KETCH_CONSENT_MANAGER_PLUGIN,name:KETCH_CONSENT_MANAGER_PLUGIN,type:COOKIE_STORAGE,errorHandler:storeManager===null||storeManager===void 0?void 0:storeManager.errorHandler,logger:storeManager===null||storeManager===void 0?void 0:storeManager.logger});rawConsentCookieData=dataStore===null||dataStore===void 0?void 0:dataStore.engine.getItem(KETCH_CONSENT_COOKIE_NAME_V1);}catch(err){logger===null||logger===undefined||logger.error(KETCH_CONSENT_COOKIE_READ_ERROR(KETCH_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(isNullOrUndefined(rawConsentCookieData)){return undefined;}// Decode and parse the cookie data to JSON
1953
1942
  var consentCookieData;try{consentCookieData=JSON.parse(fromBase64(rawConsentCookieData));}catch(err){logger===null||logger===undefined||logger.error(KETCH_CONSENT_COOKIE_PARSE_ERROR(KETCH_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(!consentCookieData){return undefined;}// Convert the cookie data to consent data
1954
1943
  var consentPurposes={};Object.entries(consentCookieData).forEach(function(pEntry){var purposeCode=pEntry[0];var purposeValue=pEntry[1];consentPurposes[purposeCode]=(purposeValue===null||purposeValue===undefined?undefined:purposeValue.status)==='granted';});return consentPurposes;};/**
1955
1944
  * Gets the consent data in the format expected by the application state
@@ -3088,7 +3077,7 @@ AnonymousId:toBase64(event.anonymousId)};eventsQueue.addItem({url:url,headers:he
3088
3077
 
3089
3078
  /**
3090
3079
  * Map plugin names to direct code imports from plugins package
3091
- */var getBundledBuildPluginImports=function getBundledBuildPluginImports(){return {BeaconQueue:BeaconQueue,Bugsnag:Bugsnag,CustomConsentManager:CustomConsentManager,DeviceModeDestinations:DeviceModeDestinations,DeviceModeTransformation:DeviceModeTransformation,ErrorReporting:ErrorReporting,ExternalAnonymousId:ExternalAnonymousId,GoogleLinker:GoogleLinker,IubendaConsentManager:IubendaConsentManager,KetchConsentManager:KetchConsentManager,NativeDestinationQueue:NativeDestinationQueue,OneTrustConsentManager:OneTrustConsentManager,StorageEncryption:StorageEncryption,StorageEncryptionLegacy:StorageEncryptionLegacy,StorageMigrator:StorageMigrator,XhrQueue:XhrQueue};};
3080
+ */var getBundledBuildPluginImports=function getBundledBuildPluginImports(){return {BeaconQueue:BeaconQueue,CustomConsentManager:CustomConsentManager,DeviceModeDestinations:DeviceModeDestinations,DeviceModeTransformation:DeviceModeTransformation,ExternalAnonymousId:ExternalAnonymousId,GoogleLinker:GoogleLinker,IubendaConsentManager:IubendaConsentManager,KetchConsentManager:KetchConsentManager,NativeDestinationQueue:NativeDestinationQueue,OneTrustConsentManager:OneTrustConsentManager,StorageEncryption:StorageEncryption,StorageEncryptionLegacy:StorageEncryptionLegacy,StorageMigrator:StorageMigrator,XhrQueue:XhrQueue};};
3092
3081
 
3093
3082
  /**
3094
3083
  * Map of mandatory plugin names and direct imports
@@ -3112,21 +3101,12 @@ state.lifecycle.status.value='pluginsReady';});}});}/**
3112
3101
  * Determine the list of plugins that should be loaded based on sourceConfig & load options
3113
3102
  */// eslint-disable-next-line class-methods-use-this
3114
3103
  },{key:"getPluginsToLoadBasedOnConfig",value:function getPluginsToLoadBasedOnConfig(){var _this=this;// This contains the default plugins if load option has been omitted by user
3115
- var pluginsToLoadFromConfig=state.plugins.pluginsToLoadFromConfig.value;if(!pluginsToLoadFromConfig){return [];}// TODO: Uncomment below lines after removing deprecated plugin
3116
- // Filter deprecated plugins
3117
- // pluginsToLoadFromConfig = pluginsToLoadFromConfig.filter(pluginName => {
3118
- // if (deprecatedPluginsList.includes(pluginName)) {
3119
- // this.logger?.warn(DEPRECATED_PLUGIN_WARNING(PLUGINS_MANAGER, pluginName));
3120
- // return false;
3121
- // }
3122
- // return true;
3123
- // });
3124
- var pluginGroupsToProcess=[{configurationStatus:function configurationStatus(){return isDefined(state.dataPlaneEvents.eventsQueuePluginName.value);},configurationStatusStr:'Data plane events delivery is enabled',activePluginName:state.dataPlaneEvents.eventsQueuePluginName.value,supportedPlugins:Object.values(DataPlaneEventsTransportToPluginNameMap),shouldAddMissingPlugins:true},{configurationStatus:function configurationStatus(){return state.reporting.isErrorReportingEnabled.value;},configurationStatusStr:'Error reporting is enabled',supportedPlugins:['ErrorReporting','Bugsnag']// TODO: Remove deprecated plugin- Bugsnag
3125
- },{configurationStatus:function configurationStatus(){return getNonCloudDestinations(state.nativeDestinations.configuredDestinations.value).length>0;},configurationStatusStr:'Device mode destinations are connected to the source',supportedPlugins:['DeviceModeDestinations','NativeDestinationQueue']},{configurationStatus:function configurationStatus(){return getNonCloudDestinations(state.nativeDestinations.configuredDestinations.value).some(function(destination){return destination.shouldApplyDeviceModeTransformation;});},configurationStatusStr:'Device mode transformations are enabled for at least one destination',supportedPlugins:['DeviceModeTransformation']},{configurationStatus:function configurationStatus(){return isDefined(state.consents.activeConsentManagerPluginName.value);},configurationStatusStr:'Consent management is enabled',activePluginName:state.consents.activeConsentManagerPluginName.value,supportedPlugins:Object.values(ConsentManagersToPluginNameMap)},{configurationStatus:function configurationStatus(){return isDefined(state.storage.encryptionPluginName.value);},configurationStatusStr:'Storage encryption is enabled',activePluginName:state.storage.encryptionPluginName.value,supportedPlugins:Object.values(StorageEncryptionVersionsToPluginNameMap)},{configurationStatus:function configurationStatus(){return state.storage.migrate.value;},configurationStatusStr:'Storage migration is enabled',supportedPlugins:['StorageMigrator']}];var addMissingPlugins=false;pluginGroupsToProcess.forEach(function(group){if(group.configurationStatus()){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(group.activePluginName?function(pluginName){return !(pluginName!==group.activePluginName&&group.supportedPlugins.includes(pluginName));}:function(pluginName){return isDefined(pluginName);}// pass through
3126
- );_this.addMissingPlugins(group,addMissingPlugins,pluginsToLoadFromConfig);}else {pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(group.basePlugins!==undefined?function(pluginName){return !(group.basePlugins.includes(pluginName)||group.supportedPlugins.includes(pluginName));}:function(pluginName){return !group.supportedPlugins.includes(pluginName);});}});return [].concat(_toConsumableArray(Object.keys(getMandatoryPluginsMap())),_toConsumableArray(pluginsToLoadFromConfig));}},{key:"addMissingPlugins",value:function addMissingPlugins(group,_addMissingPlugins,pluginsToLoadFromConfig){var shouldAddMissingPlugins=group.shouldAddMissingPlugins||_addMissingPlugins;var pluginsToConfigure;if(group.activePluginName){pluginsToConfigure=[].concat(_toConsumableArray(group.basePlugins||[]),[group.activePluginName]);}else {pluginsToConfigure=_toConsumableArray(group.supportedPlugins);}var missingPlugins=pluginsToConfigure.filter(function(pluginName){return !pluginsToLoadFromConfig.includes(pluginName);});if(missingPlugins.length>0){var _this$logger;if(shouldAddMissingPlugins){pluginsToLoadFromConfig.push.apply(pluginsToLoadFromConfig,_toConsumableArray(missingPlugins));}(_this$logger=this.logger)===null||_this$logger===undefined||_this$logger.warn(generateMisconfiguredPluginsWarning(PLUGINS_MANAGER,group.configurationStatusStr,missingPlugins,shouldAddMissingPlugins));}}/**
3104
+ var pluginsToLoadFromConfig=state.plugins.pluginsToLoadFromConfig.value;if(!pluginsToLoadFromConfig){return [];}// Filter deprecated plugins
3105
+ pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){if(deprecatedPluginsList.includes(pluginName)){_this.logger.warn(DEPRECATED_PLUGIN_WARNING(PLUGINS_MANAGER,pluginName));return false;}return true;});var pluginGroupsToProcess=[{configurationStatus:function configurationStatus(){return isDefined(state.dataPlaneEvents.eventsQueuePluginName.value);},configurationStatusStr:'Data plane events delivery is enabled',activePluginName:state.dataPlaneEvents.eventsQueuePluginName.value,supportedPlugins:Object.values(DataPlaneEventsTransportToPluginNameMap),shouldAddMissingPlugins:true},{configurationStatus:function configurationStatus(){return getNonCloudDestinations(state.nativeDestinations.configuredDestinations.value).length>0;},configurationStatusStr:'Device mode destinations are connected to the source',supportedPlugins:['DeviceModeDestinations','NativeDestinationQueue']},{configurationStatus:function configurationStatus(){return getNonCloudDestinations(state.nativeDestinations.configuredDestinations.value).some(function(destination){return destination.shouldApplyDeviceModeTransformation;});},configurationStatusStr:'Device mode transformations are enabled for at least one destination',supportedPlugins:['DeviceModeTransformation']},{configurationStatus:function configurationStatus(){return isDefined(state.consents.activeConsentManagerPluginName.value);},configurationStatusStr:'Consent management is enabled',activePluginName:state.consents.activeConsentManagerPluginName.value,supportedPlugins:Object.values(ConsentManagersToPluginNameMap)},{configurationStatus:function configurationStatus(){return isDefined(state.storage.encryptionPluginName.value);},configurationStatusStr:'Storage encryption is enabled',activePluginName:state.storage.encryptionPluginName.value,supportedPlugins:Object.values(StorageEncryptionVersionsToPluginNameMap)},{configurationStatus:function configurationStatus(){return state.storage.migrate.value;},configurationStatusStr:'Storage migration is enabled',supportedPlugins:['StorageMigrator']}];var addMissingPlugins=false;pluginGroupsToProcess.forEach(function(group){if(group.configurationStatus()){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(group.activePluginName?function(pluginName){return !(pluginName!==group.activePluginName&&group.supportedPlugins.includes(pluginName));}:function(pluginName){return isDefined(pluginName);}// pass through
3106
+ );_this.addMissingPlugins(group,addMissingPlugins,pluginsToLoadFromConfig);}else {pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(group.basePlugins!==undefined?function(pluginName){return !(group.basePlugins.includes(pluginName)||group.supportedPlugins.includes(pluginName));}:function(pluginName){return !group.supportedPlugins.includes(pluginName);});}});return [].concat(_toConsumableArray(Object.keys(getMandatoryPluginsMap())),_toConsumableArray(pluginsToLoadFromConfig));}},{key:"addMissingPlugins",value:function addMissingPlugins(group,_addMissingPlugins,pluginsToLoadFromConfig){var shouldAddMissingPlugins=group.shouldAddMissingPlugins||_addMissingPlugins;var pluginsToConfigure;if(group.activePluginName){pluginsToConfigure=[].concat(_toConsumableArray(group.basePlugins||[]),[group.activePluginName]);}else {pluginsToConfigure=_toConsumableArray(group.supportedPlugins);}var missingPlugins=pluginsToConfigure.filter(function(pluginName){return !pluginsToLoadFromConfig.includes(pluginName);});if(missingPlugins.length>0){if(shouldAddMissingPlugins){pluginsToLoadFromConfig.push.apply(pluginsToLoadFromConfig,_toConsumableArray(missingPlugins));}this.logger.warn(generateMisconfiguredPluginsWarning(PLUGINS_MANAGER,group.configurationStatusStr,missingPlugins,shouldAddMissingPlugins));}}/**
3127
3107
  * Determine the list of plugins that should be activated
3128
3108
  */},{key:"setActivePlugins",value:function setActivePlugins(){var pluginsToLoad=this.getPluginsToLoadBasedOnConfig();// Merging available mandatory and optional plugin name list
3129
- var availablePlugins=[].concat(_toConsumableArray(Object.keys(pluginsInventory)),_toConsumableArray(pluginNamesList));var activePlugins=[];var failedPlugins=[];pluginsToLoad.forEach(function(pluginName){if(availablePlugins.includes(pluginName)){activePlugins.push(pluginName);}else {failedPlugins.push(pluginName);}});if(failedPlugins.length>0){this.onError(new Error("Ignoring loading of unknown plugins: ".concat(failedPlugins.join(','),". Mandatory plugins: ").concat(Object.keys(getMandatoryPluginsMap()).join(','),". Load option plugins: ").concat(state.plugins.pluginsToLoadFromConfig.value.join(','))));}r(function(){state.plugins.totalPluginsToLoad.value=pluginsToLoad.length;state.plugins.activePlugins.value=activePlugins;state.plugins.failedPlugins.value=failedPlugins;});}/**
3109
+ var availablePlugins=[].concat(_toConsumableArray(Object.keys(pluginsInventory)),_toConsumableArray(pluginNamesList));var activePlugins=[];var failedPlugins=[];pluginsToLoad.forEach(function(pluginName){if(availablePlugins.includes(pluginName)){activePlugins.push(pluginName);}else {failedPlugins.push(pluginName);}});if(failedPlugins.length>0){this.logger.warn(UNKNOWN_PLUGINS_WARNING(PLUGINS_MANAGER,failedPlugins));}r(function(){state.plugins.totalPluginsToLoad.value=pluginsToLoad.length;state.plugins.activePlugins.value=activePlugins;state.plugins.failedPlugins.value=failedPlugins;});}/**
3130
3110
  * Register plugins that are direct imports to PluginEngine
3131
3111
  */},{key:"registerLocalPlugins",value:function registerLocalPlugins(){var _this2=this;Object.values(pluginsInventory).forEach(function(localPlugin){if(isFunction(localPlugin)&&state.plugins.activePlugins.value.includes(localPlugin().name)){_this2.register([localPlugin()]);}});}/**
3132
3112
  * Register plugins that are dynamic imports to PluginEngine
@@ -3140,48 +3120,18 @@ state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.fai
3140
3120
  */},{key:"register",value:function register(plugins){var _this4=this;plugins.forEach(function(plugin){try{_this4.engine.register(plugin,state);}catch(e){state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.failedPlugins.value),[plugin.name]);_this4.onError(e);}});}// TODO: Implement reset API instead
3141
3121
  },{key:"unregisterLocalPlugins",value:function unregisterLocalPlugins(){var _this5=this;Object.values(pluginsInventory).forEach(function(localPlugin){try{_this5.engine.unregister(localPlugin().name);}catch(e){_this5.onError(e);}});}/**
3142
3122
  * Handle errors
3143
- */},{key:"onError",value:function onError(error,customMessage){if(this.errorHandler){this.errorHandler.onError(error,PLUGINS_MANAGER,customMessage);}else {throw error;}}}]);}();
3144
-
3145
- /**
3146
- * Utility to parse XHR JSON response
3147
- */var responseTextToJson=function responseTextToJson(responseText,onError){try{return JSON.parse(responseText||'');}catch(err){var error=getMutatedError(err,'Failed to parse response data');if(isFunction(onError)){onError(error);}else {throw error;}}return undefined;};
3148
-
3149
- var DEFAULT_XHR_REQUEST_OPTIONS={headers:{Accept:'application/json','Content-Type':'application/json;charset=UTF-8'},method:'GET'};/**
3150
- * Utility to create request configuration based on default options
3151
- */var createXhrRequestOptions=function createXhrRequestOptions(url,options,basicAuthHeader){var requestOptions=mergeDeepRight(DEFAULT_XHR_REQUEST_OPTIONS,options||{});if(basicAuthHeader){requestOptions.headers=mergeDeepRight(requestOptions.headers,{Authorization:basicAuthHeader});}requestOptions.url=url;return requestOptions;};/**
3152
- * Utility implementation of XHR, fetch cannot be used as it requires explicit
3153
- * origin allowed values and not wildcard for CORS requests with credentials and
3154
- * this is not supported by our sourceConfig API
3155
- */var xhrRequest=function xhrRequest(options){var timeout=arguments.length>1&&arguments[1]!==undefined?arguments[1]:DEFAULT_XHR_TIMEOUT_MS;var logger=arguments.length>2?arguments[2]:undefined;return new Promise(function(resolve,reject){var payload;if(options.sendRawData===true){payload=options.data;}else {payload=stringifyWithoutCircular(options.data,false,[],logger);if(isNull(payload)){reject({error:new Error(XHR_PAYLOAD_PREP_ERROR),undefined:undefined,options:options});// return and don't process further if the payload could not be stringified
3156
- return;}}var xhr=new XMLHttpRequest();// eslint-disable-next-line @typescript-eslint/no-unused-vars
3157
- var xhrReject=function xhrReject(e){reject({error:new Error(XHR_DELIVERY_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,xhr.status,xhr.statusText,options.url)),xhr:xhr,options:options});};var xhrError=function xhrError(e){reject({error:new Error(XHR_REQUEST_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,e,options.url)),xhr:xhr,options:options});};xhr.ontimeout=xhrError;xhr.onerror=xhrError;xhr.onload=function(){if(xhr.status>=200&&xhr.status<400){resolve({response:xhr.responseText,xhr:xhr,options:options});}else {xhrReject();}};xhr.open(options.method,options.url,true);if(options.withCredentials===true){xhr.withCredentials=true;}// The timeout property may be set only in the time interval between a call to the open method
3158
- // and the first call to the send method in legacy browsers
3159
- xhr.timeout=timeout;Object.keys(options.headers).forEach(function(headerName){if(options.headers[headerName]){xhr.setRequestHeader(headerName,options.headers[headerName]);}});try{xhr.send(payload);}catch(err){reject({error:getMutatedError(err,XHR_SEND_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,options.url)),xhr:xhr,options:options});}});};
3160
-
3161
- /**
3162
- * Service to handle data communication with APIs
3163
- */var HttpClient=/*#__PURE__*/function(){function HttpClient(errorHandler,logger){_classCallCheck(this,HttpClient);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);}/**
3164
- * Implement requests in a blocking way
3165
- */return _createClass(HttpClient,[{key:"getData",value:(function(){var _getData=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(config){var url,options,timeout,isRawResponse,data,_error;return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;_context.prev=1;_context.next=4;return xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout,this.logger);case 4:data=_context.sent;return _context.abrupt("return",{data:isRawResponse?data.response:responseTextToJson(data.response,this.onError),details:data});case 8:_context.prev=8;_context.t0=_context["catch"](1);this.onError((_error=_context.t0.error)!==null&&_error!==undefined?_error:_context.t0);return _context.abrupt("return",{data:undefined,details:_context.t0});case 12:case "end":return _context.stop();}},_callee,this,[[1,8]]);}));function getData(_x){return _getData.apply(this,arguments);}return getData;}()/**
3166
- * Implement requests in a non-blocking way
3167
- */)},{key:"getAsyncData",value:function getAsyncData(config){var _this=this;var callback=config.callback,url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;var isFireAndForget=!isFunction(callback);xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout,this.logger).then(function(data){if(!isFireAndForget){callback(isRawResponse?data.response:responseTextToJson(data.response,_this.onError),data);}}).catch(function(data){var _data$error;_this.onError((_data$error=data.error)!==null&&_data$error!==undefined?_data$error:data);if(!isFireAndForget){callback(undefined,data);}});}/**
3168
- * Handle errors
3169
- */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===undefined||_this$errorHandler.onError(error,HTTP_CLIENT);}else {throw error;}}/**
3170
- * Set basic authentication header (eg writekey)
3171
- */},{key:"setAuthHeader",value:function setAuthHeader(value){var noBtoa=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var authVal=noBtoa?value:toBase64("".concat(value,":"));this.basicAuthHeader="Basic ".concat(authVal);}/**
3172
- * Clear basic authentication header
3173
- */},{key:"resetAuthHeader",value:function resetAuthHeader(){this.basicAuthHeader=undefined;}}]);}();var defaultHttpClient=new HttpClient(defaultErrorHandler,defaultLogger);
3123
+ */},{key:"onError",value:function onError(error,customMessage){this.errorHandler.onError(error,PLUGINS_MANAGER,customMessage);}}]);}();
3174
3124
 
3175
3125
  var STORAGE_TEST_COOKIE='test_rudder_cookie';var STORAGE_TEST_LOCAL_STORAGE='test_rudder_ls';var STORAGE_TEST_SESSION_STORAGE='test_rudder_ss';var STORAGE_TEST_TOP_LEVEL_DOMAIN='__tld__';var CLIENT_DATA_STORE_COOKIE='clientDataInCookie';var CLIENT_DATA_STORE_LS='clientDataInLocalStorage';var CLIENT_DATA_STORE_MEMORY='clientDataInMemory';var CLIENT_DATA_STORE_SESSION='clientDataInSessionStorage';var USER_SESSION_KEYS=['userId','userTraits','anonymousId','groupId','groupTraits','initialReferrer','initialReferringDomain','sessionInfo','authToken'];
3176
3126
 
3177
3127
  var storageClientDataStoreNameMap=_defineProperty(_defineProperty(_defineProperty(_defineProperty({},COOKIE_STORAGE,CLIENT_DATA_STORE_COOKIE),LOCAL_STORAGE,CLIENT_DATA_STORE_LS),MEMORY_STORAGE,CLIENT_DATA_STORE_MEMORY),SESSION_STORAGE,CLIENT_DATA_STORE_SESSION);
3178
3128
 
3179
- var detectAdBlockers=function detectAdBlockers(errorHandler,logger){// Apparently, '?view=ad' is a query param that is blocked by majority of adblockers
3129
+ var detectAdBlockers=function detectAdBlockers(httpClient){// Apparently, '?view=ad' is a query param that is blocked by majority of adblockers
3180
3130
  // Use source config URL here as it is very unlikely to be blocked by adblockers
3181
3131
  // Only the extra query param should make it vulnerable to adblockers
3182
3132
  // This will work even if the users proxies it.
3183
3133
  // The edge case where this doesn't work is when HEAD method is not allowed by the server (user's)
3184
- var baseUrl=new URL(state.lifecycle.sourceConfigUrl.value);var url="".concat(baseUrl.origin).concat(baseUrl.pathname,"?view=ad");var httpClient=new HttpClient(errorHandler,logger);httpClient.setAuthHeader(state.lifecycle.writeKey.value);httpClient.getAsyncData({url:url,options:{// We actually don't need the response from the request, so we are using HEAD
3134
+ var baseUrl=new URL(state.lifecycle.sourceConfigUrl.value);var url="".concat(baseUrl.origin).concat(baseUrl.pathname,"?view=ad");httpClient.getAsyncData({url:url,options:{// We actually don't need the response from the request, so we are using HEAD
3185
3135
  method:'HEAD',headers:{'Content-Type':undefined}},isRawResponse:true,callback:function callback(result,details){var _details$xhr;// not ad blocked if the request is successful or it is not internally redirected on the client side
3186
3136
  // Often adblockers instead of blocking the request, they redirect it to an internal URL
3187
3137
  state.capabilities.isAdBlocked.value=(details===null||details===undefined?undefined:details.error)!==undefined||(details===null||details===undefined||(_details$xhr=details.xhr)===null||_details$xhr===undefined?undefined:_details$xhr.responseURL)!==url;}});};
@@ -3291,7 +3241,7 @@ if(this.isSupportAvailable){this.store=globalThis.sessionStorage;}this.isEnabled
3291
3241
 
3292
3242
  /**
3293
3243
  * Store Implementation with dedicated storage
3294
- */var Store=/*#__PURE__*/function(){function Store(config,engine,pluginsManager){var _config$isEncrypted,_config$validKeys,_config$errorHandler,_config$logger;_classCallCheck(this,Store);_defineProperty(this,"hasErrorHandler",false);this.id=config.id;this.name=config.name;this.isEncrypted=(_config$isEncrypted=config.isEncrypted)!==null&&_config$isEncrypted!==undefined?_config$isEncrypted:false;this.validKeys=(_config$validKeys=config.validKeys)!==null&&_config$validKeys!==undefined?_config$validKeys:{};this.engine=engine!==null&&engine!==undefined?engine:getStorageEngine(LOCAL_STORAGE);this.noKeyValidation=Object.keys(this.validKeys).length===0;this.noCompoundKey=config.noCompoundKey;this.originalEngine=this.engine;this.errorHandler=(_config$errorHandler=config.errorHandler)!==null&&_config$errorHandler!==undefined?_config$errorHandler:defaultErrorHandler;this.hasErrorHandler=Boolean(this.errorHandler);this.logger=(_config$logger=config.logger)!==null&&_config$logger!==undefined?_config$logger:defaultLogger;this.pluginsManager=pluginsManager;}/**
3244
+ */var Store=/*#__PURE__*/function(){function Store(config,engine,pluginsManager){var _config$isEncrypted,_config$validKeys;_classCallCheck(this,Store);this.id=config.id;this.name=config.name;this.isEncrypted=(_config$isEncrypted=config.isEncrypted)!==null&&_config$isEncrypted!==undefined?_config$isEncrypted:false;this.validKeys=(_config$validKeys=config.validKeys)!==null&&_config$validKeys!==undefined?_config$validKeys:{};this.engine=engine!==null&&engine!==undefined?engine:getStorageEngine(LOCAL_STORAGE);this.noKeyValidation=Object.keys(this.validKeys).length===0;this.noCompoundKey=config.noCompoundKey;this.originalEngine=this.engine;this.errorHandler=config.errorHandler;this.logger=config.logger;this.pluginsManager=pluginsManager;}/**
3295
3245
  * Ensure the key is valid and with correct format
3296
3246
  */return _createClass(Store,[{key:"createValidKey",value:function createValidKey(key){var name=this.name,id=this.id,validKeys=this.validKeys,noKeyValidation=this.noKeyValidation,noCompoundKey=this.noCompoundKey;if(noKeyValidation){return noCompoundKey?key:[name,id,key].join('.');}// validate and return undefined if invalid key
3297
3247
  var compoundKey;Object.values(validKeys).forEach(function(validKeyName){if(validKeyName===key){compoundKey=noCompoundKey?key:[name,id,key].join('.');}});return compoundKey;}/**
@@ -3304,13 +3254,13 @@ Object.keys(validKeys).forEach(function(key){var value=_this.get(validKeys[key])
3304
3254
  _this.remove(key);});this.engine=inMemoryStorage;}/**
3305
3255
  * Set value by key.
3306
3256
  */},{key:"set",value:function set(key,value){var validKey=this.createValidKey(key);if(!validKey){return;}try{// storejs that is used in localstorage engine already stringifies json
3307
- this.engine.setItem(validKey,this.encrypt(stringifyWithoutCircular(value,false,[],this.logger)));}catch(err){if(isStorageQuotaExceeded(err)){var _this$logger;(_this$logger=this.logger)===null||_this$logger===undefined||_this$logger.warn(STORAGE_QUOTA_EXCEEDED_WARNING("Store ".concat(this.id)));// switch to inMemory engine
3257
+ this.engine.setItem(validKey,this.encrypt(stringifyWithoutCircular(value,false,[],this.logger)));}catch(err){if(isStorageQuotaExceeded(err)){this.logger.warn(STORAGE_QUOTA_EXCEEDED_WARNING("Store ".concat(this.id)));// switch to inMemory engine
3308
3258
  this.swapQueueStoreToInMemoryEngine();// and save it there
3309
3259
  this.set(key,value);}else {this.onError(getMutatedError(err,STORE_DATA_SAVE_ERROR(key)));}}}/**
3310
3260
  * Get by Key.
3311
3261
  */},{key:"get",value:function get(key){var validKey=this.createValidKey(key);var decryptedValue;try{if(!validKey){return null;}decryptedValue=this.decrypt(this.engine.getItem(validKey));if(isNullOrUndefined(decryptedValue)){return null;}// storejs that is used in localstorage engine already deserializes json strings but swallows errors
3312
3262
  return JSON.parse(decryptedValue);}catch(err){this.onError(new Error("".concat(STORE_DATA_FETCH_ERROR(key),": ").concat(err.message)));// A hack for warning the users of potential partial SDK version migrations
3313
- if(isString(decryptedValue)&&decryptedValue.startsWith('RudderEncrypt:')){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===undefined||_this$logger2.warn(BAD_COOKIES_WARNING(key));}return null;}}/**
3263
+ if(isString(decryptedValue)&&decryptedValue.startsWith('RudderEncrypt:')){this.logger.warn(BAD_COOKIES_WARNING(key));}return null;}}/**
3314
3264
  * Remove by Key.
3315
3265
  */},{key:"remove",value:function remove(key){var validKey=this.createValidKey(key);if(validKey){this.engine.removeItem(validKey);}}/**
3316
3266
  * Get original engine
@@ -3322,13 +3272,13 @@ if(isString(decryptedValue)&&decryptedValue.startsWith('RudderEncrypt:')){var _t
3322
3272
  * Extension point to use with encryption plugins
3323
3273
  */},{key:"crypto",value:function crypto(value,mode){var noEncryption=!this.isEncrypted||!value||typeof value!=='string'||trim(value)==='';if(noEncryption){return value;}var extensionPointName="storage.".concat(mode);var formattedValue=this.pluginsManager?this.pluginsManager.invokeSingle(extensionPointName,value):value;return typeof formattedValue==='undefined'?value:formattedValue!==null&&formattedValue!==undefined?formattedValue:'';}/**
3324
3274
  * Handle errors
3325
- */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===undefined||_this$errorHandler.onError(error,"Store ".concat(this.id));}else {throw error;}}}]);}();
3275
+ */},{key:"onError",value:function onError(error){this.errorHandler.onError(error,"Store ".concat(this.id));}}]);}();
3326
3276
 
3327
3277
  var getStorageTypeFromPreConsentIfApplicable=function getStorageTypeFromPreConsentIfApplicable(state,sessionKey){var overriddenStorageType;if(state.consents.preConsent.value.enabled){var _state$consents$preCo;switch((_state$consents$preCo=state.consents.preConsent.value.storage)===null||_state$consents$preCo===undefined?undefined:_state$consents$preCo.strategy){case 'none':overriddenStorageType=NO_STORAGE;break;case 'session':if(sessionKey!=='sessionInfo'){overriddenStorageType=NO_STORAGE;}break;case 'anonymousId':if(sessionKey!=='anonymousId'){overriddenStorageType=NO_STORAGE;}break;}}return overriddenStorageType;};
3328
3278
 
3329
3279
  /**
3330
3280
  * A service to manage stores & available storage client configurations
3331
- */var StoreManager=/*#__PURE__*/function(){function StoreManager(pluginsManager,errorHandler,logger){_classCallCheck(this,StoreManager);_defineProperty(this,"stores",{});_defineProperty(this,"isInitialized",false);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.hasErrorHandler=Boolean(this.errorHandler);this.pluginsManager=pluginsManager;this.onError=this.onError.bind(this);}/**
3281
+ */var StoreManager=/*#__PURE__*/function(){function StoreManager(pluginsManager,errorHandler,logger){_classCallCheck(this,StoreManager);_defineProperty(this,"stores",{});_defineProperty(this,"isInitialized",false);this.errorHandler=errorHandler;this.logger=logger;this.pluginsManager=pluginsManager;}/**
3332
3282
  * Configure available storage client instances
3333
3283
  */return _createClass(StoreManager,[{key:"init",value:function init(){var _config$cookieStorage,_state$storage$cookie,_state$storage$cookie2;if(this.isInitialized){return;}var loadOptions=state.loadOptions.value;var config={cookieStorageOptions:{samesite:loadOptions.sameSiteCookie,secure:loadOptions.secureCookie,domain:loadOptions.setCookieDomain,sameDomainCookiesOnly:loadOptions.sameDomainCookiesOnly,enabled:true},localStorageOptions:{enabled:true},inMemoryStorageOptions:{enabled:true},sessionStorageOptions:{enabled:true}};configureStorageEngines(_removeUndefinedValues(mergeDeepRight((_config$cookieStorage=config.cookieStorageOptions)!==null&&_config$cookieStorage!==undefined?_config$cookieStorage:{},(_state$storage$cookie=(_state$storage$cookie2=state.storage.cookie)===null||_state$storage$cookie2===undefined?undefined:_state$storage$cookie2.value)!==null&&_state$storage$cookie!==undefined?_state$storage$cookie:{})),_removeUndefinedValues(config.localStorageOptions),_removeUndefinedValues(config.inMemoryStorageOptions),_removeUndefinedValues(config.sessionStorageOptions));this.initClientDataStores();this.isInitialized=true;}/**
3334
3284
  * Create store to persist data used by the SDK like session, used details etc
@@ -3336,16 +3286,14 @@ var getStorageTypeFromPreConsentIfApplicable=function getStorageTypeFromPreConse
3336
3286
  // TODO: should we pass the keys for all in order to validate or leave free as v1.1?
3337
3287
  // Initializing all the enabled store because previous user data might be in different storage
3338
3288
  // that needs auto migration
3339
- var storageTypes=[MEMORY_STORAGE,LOCAL_STORAGE,COOKIE_STORAGE,SESSION_STORAGE];storageTypes.forEach(function(storageType){var _getStorageEngine;if((_getStorageEngine=getStorageEngine(storageType))!==null&&_getStorageEngine!==undefined&&_getStorageEngine.isEnabled){_this.setStore({id:storageClientDataStoreNameMap[storageType],name:storageClientDataStoreNameMap[storageType],isEncrypted:true,noCompoundKey:true,type:storageType});}});}},{key:"initializeStorageState",value:function initializeStorageState(){var _state$loadOptions$va,_this2=this;var globalStorageType=state.storage.type.value;var entriesOptions=(_state$loadOptions$va=state.loadOptions.value.storage)===null||_state$loadOptions$va===undefined?undefined:_state$loadOptions$va.entries;// Use the storage options from post consent if anything is defined
3289
+ var storageTypes=[MEMORY_STORAGE,LOCAL_STORAGE,COOKIE_STORAGE,SESSION_STORAGE];storageTypes.forEach(function(storageType){var _getStorageEngine;if((_getStorageEngine=getStorageEngine(storageType))!==null&&_getStorageEngine!==undefined&&_getStorageEngine.isEnabled){_this.setStore({id:storageClientDataStoreNameMap[storageType],name:storageClientDataStoreNameMap[storageType],isEncrypted:true,noCompoundKey:true,type:storageType,errorHandler:_this.errorHandler,logger:_this.logger});}});}},{key:"initializeStorageState",value:function initializeStorageState(){var _state$loadOptions$va,_this2=this;var globalStorageType=state.storage.type.value;var entriesOptions=(_state$loadOptions$va=state.loadOptions.value.storage)===null||_state$loadOptions$va===undefined?undefined:_state$loadOptions$va.entries;// Use the storage options from post consent if anything is defined
3340
3290
  var postConsentStorageOpts=state.consents.postConsent.value.storage;if(isDefined(postConsentStorageOpts===null||postConsentStorageOpts===undefined?undefined:postConsentStorageOpts.type)||isDefined(postConsentStorageOpts===null||postConsentStorageOpts===undefined?undefined:postConsentStorageOpts.entries)){globalStorageType=postConsentStorageOpts===null||postConsentStorageOpts===undefined?undefined:postConsentStorageOpts.type;entriesOptions=postConsentStorageOpts===null||postConsentStorageOpts===undefined?undefined:postConsentStorageOpts.entries;}var trulyAnonymousTracking=true;var storageEntries={};USER_SESSION_KEYS.forEach(function(sessionKey){var _entriesOptions,_ref,_ref2;var key=sessionKey;var storageKey=sessionKey;var configuredStorageType=(_entriesOptions=entriesOptions)===null||_entriesOptions===undefined||(_entriesOptions=_entriesOptions[key])===null||_entriesOptions===undefined?undefined:_entriesOptions.type;var preConsentStorageType=getStorageTypeFromPreConsentIfApplicable(state,sessionKey);// Storage type precedence order: pre-consent strategy > entry type > global type > default
3341
3291
  var storageType=(_ref=(_ref2=preConsentStorageType!==null&&preConsentStorageType!==undefined?preConsentStorageType:configuredStorageType)!==null&&_ref2!==undefined?_ref2:globalStorageType)!==null&&_ref!==undefined?_ref:DEFAULT_STORAGE_TYPE;var finalStorageType=_this2.getResolvedStorageTypeForEntry(storageType,sessionKey);if(finalStorageType!==NO_STORAGE){trulyAnonymousTracking=false;}storageEntries=_objectSpread2(_objectSpread2({},storageEntries),{},_defineProperty({},sessionKey,{type:finalStorageType,key:COOKIE_KEYS[storageKey]}));});r(function(){state.storage.type.value=globalStorageType;state.storage.entries.value=storageEntries;state.storage.trulyAnonymousTracking.value=trulyAnonymousTracking;});}},{key:"getResolvedStorageTypeForEntry",value:function getResolvedStorageTypeForEntry(storageType,sessionKey){var _getStorageEngine2,_getStorageEngine3,_getStorageEngine4,_getStorageEngine5,_getStorageEngine6;var finalStorageType=storageType;switch(storageType){case LOCAL_STORAGE:if(!((_getStorageEngine2=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine2!==undefined&&_getStorageEngine2.isEnabled)){finalStorageType=MEMORY_STORAGE;}break;case SESSION_STORAGE:if(!((_getStorageEngine3=getStorageEngine(SESSION_STORAGE))!==null&&_getStorageEngine3!==undefined&&_getStorageEngine3.isEnabled)){finalStorageType=MEMORY_STORAGE;}break;case MEMORY_STORAGE:case NO_STORAGE:break;case COOKIE_STORAGE:default:// First try setting the storage to cookie else to local storage
3342
- if((_getStorageEngine4=getStorageEngine(COOKIE_STORAGE))!==null&&_getStorageEngine4!==undefined&&_getStorageEngine4.isEnabled){finalStorageType=COOKIE_STORAGE;}else if((_getStorageEngine5=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine5!==undefined&&_getStorageEngine5.isEnabled){finalStorageType=LOCAL_STORAGE;}else if((_getStorageEngine6=getStorageEngine(SESSION_STORAGE))!==null&&_getStorageEngine6!==undefined&&_getStorageEngine6.isEnabled){finalStorageType=SESSION_STORAGE;}else {finalStorageType=MEMORY_STORAGE;}break;}if(finalStorageType!==storageType){var _this$logger;(_this$logger=this.logger)===null||_this$logger===undefined||_this$logger.warn(STORAGE_UNAVAILABLE_WARNING(STORE_MANAGER,sessionKey,storageType,finalStorageType));}return finalStorageType;}/**
3292
+ if((_getStorageEngine4=getStorageEngine(COOKIE_STORAGE))!==null&&_getStorageEngine4!==undefined&&_getStorageEngine4.isEnabled){finalStorageType=COOKIE_STORAGE;}else if((_getStorageEngine5=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine5!==undefined&&_getStorageEngine5.isEnabled){finalStorageType=LOCAL_STORAGE;}else if((_getStorageEngine6=getStorageEngine(SESSION_STORAGE))!==null&&_getStorageEngine6!==undefined&&_getStorageEngine6.isEnabled){finalStorageType=SESSION_STORAGE;}else {finalStorageType=MEMORY_STORAGE;}break;}if(finalStorageType!==storageType){this.logger.warn(STORAGE_UNAVAILABLE_WARNING(STORE_MANAGER,sessionKey,storageType,finalStorageType));}return finalStorageType;}/**
3343
3293
  * Create a new store
3344
3294
  */},{key:"setStore",value:function setStore(storeConfig){var storageEngine=getStorageEngine(storeConfig.type);this.stores[storeConfig.id]=new Store(storeConfig,storageEngine,this.pluginsManager);return this.stores[storeConfig.id];}/**
3345
3295
  * Retrieve a store
3346
- */},{key:"getStore",value:function getStore(id){return this.stores[id];}/**
3347
- * Handle errors
3348
- */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===undefined||_this$errorHandler.onError(error,STORE_MANAGER);}else {throw error;}}}]);}();
3296
+ */},{key:"getStore",value:function getStore(id){return this.stores[id];}}]);}();
3349
3297
 
3350
3298
  var isValidSourceConfig=function isValidSourceConfig(res){return isObjectLiteralAndNotNull(res)&&isObjectLiteralAndNotNull(res.source)&&!isNullOrUndefined(res.source.id)&&isObjectLiteralAndNotNull(res.source.config)&&Array.isArray(res.source.destinations);};var isValidStorageType=function isValidStorageType(storageType){return typeof storageType==='string'&&SUPPORTED_STORAGE_TYPES.includes(storageType);};var getTopDomain=function getTopDomain(url){// Create a URL object
3351
3299
  var urlObj=new URL(url);// Extract the host and protocol
@@ -3406,7 +3354,7 @@ validOptions.consentManagement=mergeDeepRight(clonedOptions.consentManagement,{e
3406
3354
  * @param consentManagementOpts consent management options
3407
3355
  * @param logger logger instance
3408
3356
  * @returns Corresponding provider and plugin name of the selected consent manager from the supported consent managers
3409
- */var getConsentManagerInfo=function getConsentManagerInfo(consentManagementOpts,logger){var provider=consentManagementOpts.provider;var consentManagerPluginName=provider?ConsentManagersToPluginNameMap[provider]:undefined;if(provider&&!consentManagerPluginName){logger===null||logger===undefined||logger.error(UNSUPPORTED_CONSENT_MANAGER_ERROR(CONFIG_MANAGER,provider,ConsentManagersToPluginNameMap));// Reset the provider value
3357
+ */var getConsentManagerInfo=function getConsentManagerInfo(consentManagementOpts,logger){var provider=consentManagementOpts.provider;var consentManagerPluginName=provider?ConsentManagersToPluginNameMap[provider]:undefined;if(provider&&!consentManagerPluginName){logger.error(UNSUPPORTED_CONSENT_MANAGER_ERROR(CONFIG_MANAGER,provider,ConsentManagersToPluginNameMap));// Reset the provider value
3410
3358
  provider=undefined;}return {provider:provider,consentManagerPluginName:consentManagerPluginName};};/**
3411
3359
  * Validates and converts the consent management options into a normalized format
3412
3360
  * @param consentManagementOpts Consent management options provided by the user
@@ -3442,10 +3390,10 @@ if(curHost!==dataServiceHost){cookieOptions=_objectSpread2(_objectSpread2({},coo
3442
3390
  * If the sameDomainCookiesOnly flag is not set and the cookie domain is provided(not top level domain),
3443
3391
  * and the data service host is different from the provided cookie domain, then we disable server-side cookies
3444
3392
  * ex: provided cookie domain: 'random.com', data service host: 'sub.example.com'
3445
- */if(!sameDomainCookiesOnly&&useExactDomain&&dataServiceHost!==removeLeadingPeriod(providedCookieDomain)){sscEnabled=false;logger===null||logger===undefined||logger.warn(SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING(CONFIG_MANAGER,providedCookieDomain,dataServiceHost));}}else {sscEnabled=false;}}return {sscEnabled:sscEnabled,cookieOptions:cookieOptions,finalDataServiceUrl:finalDataServiceUrl};};var updateStorageStateFromLoadOptions=function updateStorageStateFromLoadOptions(logger){var _storageOptsFromLoad$;var storageOptsFromLoad=state.loadOptions.value.storage;var storageType=storageOptsFromLoad===null||storageOptsFromLoad===undefined?undefined:storageOptsFromLoad.type;if(isDefined(storageType)&&!isValidStorageType(storageType)){logger===null||logger===undefined||logger.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));storageType=DEFAULT_STORAGE_TYPE;}var storageEncryptionVersion=storageOptsFromLoad===null||storageOptsFromLoad===undefined||(_storageOptsFromLoad$=storageOptsFromLoad.encryption)===null||_storageOptsFromLoad$===undefined?undefined:_storageOptsFromLoad$.version;var encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
3446
- logger===null||logger===undefined||logger.warn(UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(CONFIG_MANAGER,storageEncryptionVersion,StorageEncryptionVersionsToPluginNameMap,DEFAULT_STORAGE_ENCRYPTION_VERSION));storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}else if(isUndefined(storageEncryptionVersion)){storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}// Allow migration only if the configured encryption version is the default encryption version
3447
- var configuredMigrationValue=storageOptsFromLoad===null||storageOptsFromLoad===undefined?undefined:storageOptsFromLoad.migrate;var finalMigrationVal=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&finalMigrationVal!==configuredMigrationValue){logger===null||logger===undefined||logger.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}var _getServerSideCookies=getServerSideCookiesStateData(logger),sscEnabled=_getServerSideCookies.sscEnabled,finalDataServiceUrl=_getServerSideCookies.finalDataServiceUrl,cookieOptions=_getServerSideCookies.cookieOptions;r(function(){state.storage.type.value=storageType;state.storage.cookie.value=cookieOptions;state.serverCookies.isEnabledServerSideCookies.value=sscEnabled;state.serverCookies.dataServiceUrl.value=finalDataServiceUrl;state.storage.encryptionPluginName.value=StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];state.storage.migrate.value=finalMigrationVal;});};var updateConsentsStateFromLoadOptions=function updateConsentsStateFromLoadOptions(logger){var _preConsentOpts$stora,_preConsentOpts$stora2,_preConsentOpts$event,_preConsentOpts$event2;var _getConsentManagement=getConsentManagementData(state.loadOptions.value.consentManagement,logger),provider=_getConsentManagement.provider,consentManagerPluginName=_getConsentManagement.consentManagerPluginName,initialized=_getConsentManagement.initialized,enabled=_getConsentManagement.enabled,consentsData=_getConsentManagement.consentsData;// Pre-consent
3448
- var preConsentOpts=state.loadOptions.value.preConsent;var storageStrategy=(_preConsentOpts$stora=preConsentOpts===null||preConsentOpts===undefined||(_preConsentOpts$stora2=preConsentOpts.storage)===null||_preConsentOpts$stora2===undefined?undefined:_preConsentOpts$stora2.strategy)!==null&&_preConsentOpts$stora!==undefined?_preConsentOpts$stora:DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;var StorageStrategies=['none','session','anonymousId'];if(isDefined(storageStrategy)&&!StorageStrategies.includes(storageStrategy)){var _preConsentOpts$stora3;storageStrategy=DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;logger===null||logger===undefined||logger.warn(UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(CONFIG_MANAGER,preConsentOpts===null||preConsentOpts===undefined||(_preConsentOpts$stora3=preConsentOpts.storage)===null||_preConsentOpts$stora3===undefined?undefined:_preConsentOpts$stora3.strategy,DEFAULT_PRE_CONSENT_STORAGE_STRATEGY));}var eventsDeliveryType=(_preConsentOpts$event=preConsentOpts===null||preConsentOpts===undefined||(_preConsentOpts$event2=preConsentOpts.events)===null||_preConsentOpts$event2===undefined?undefined:_preConsentOpts$event2.delivery)!==null&&_preConsentOpts$event!==undefined?_preConsentOpts$event:DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;var deliveryTypes=['immediate','buffer'];if(isDefined(eventsDeliveryType)&&!deliveryTypes.includes(eventsDeliveryType)){var _preConsentOpts$event3;eventsDeliveryType=DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;logger===null||logger===undefined||logger.warn(UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(CONFIG_MANAGER,preConsentOpts===null||preConsentOpts===undefined||(_preConsentOpts$event3=preConsentOpts.events)===null||_preConsentOpts$event3===undefined?undefined:_preConsentOpts$event3.delivery,DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE));}r(function(){var _state$loadOptions$va2;state.consents.activeConsentManagerPluginName.value=consentManagerPluginName;state.consents.initialized.value=initialized;state.consents.enabled.value=enabled;state.consents.data.value=consentsData;state.consents.provider.value=provider;state.consents.preConsent.value={// Only enable pre-consent if it is explicitly enabled and
3393
+ */if(!sameDomainCookiesOnly&&useExactDomain&&dataServiceHost!==removeLeadingPeriod(providedCookieDomain)){sscEnabled=false;logger.warn(SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING(CONFIG_MANAGER,providedCookieDomain,dataServiceHost));}}else {sscEnabled=false;}}return {sscEnabled:sscEnabled,cookieOptions:cookieOptions,finalDataServiceUrl:finalDataServiceUrl};};var updateStorageStateFromLoadOptions=function updateStorageStateFromLoadOptions(logger){var _storageOptsFromLoad$;var storageOptsFromLoad=state.loadOptions.value.storage;var storageType=storageOptsFromLoad===null||storageOptsFromLoad===undefined?undefined:storageOptsFromLoad.type;if(isDefined(storageType)&&!isValidStorageType(storageType)){logger.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));storageType=DEFAULT_STORAGE_TYPE;}var storageEncryptionVersion=storageOptsFromLoad===null||storageOptsFromLoad===undefined||(_storageOptsFromLoad$=storageOptsFromLoad.encryption)===null||_storageOptsFromLoad$===undefined?undefined:_storageOptsFromLoad$.version;var encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
3394
+ logger.warn(UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(CONFIG_MANAGER,storageEncryptionVersion,StorageEncryptionVersionsToPluginNameMap,DEFAULT_STORAGE_ENCRYPTION_VERSION));storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}else if(isUndefined(storageEncryptionVersion)){storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}// Allow migration only if the configured encryption version is the default encryption version
3395
+ var configuredMigrationValue=storageOptsFromLoad===null||storageOptsFromLoad===undefined?undefined:storageOptsFromLoad.migrate;var finalMigrationVal=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&finalMigrationVal!==configuredMigrationValue){logger.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}var _getServerSideCookies=getServerSideCookiesStateData(logger),sscEnabled=_getServerSideCookies.sscEnabled,finalDataServiceUrl=_getServerSideCookies.finalDataServiceUrl,cookieOptions=_getServerSideCookies.cookieOptions;r(function(){state.storage.type.value=storageType;state.storage.cookie.value=cookieOptions;state.serverCookies.isEnabledServerSideCookies.value=sscEnabled;state.serverCookies.dataServiceUrl.value=finalDataServiceUrl;state.storage.encryptionPluginName.value=StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];state.storage.migrate.value=finalMigrationVal;});};var updateConsentsStateFromLoadOptions=function updateConsentsStateFromLoadOptions(logger){var _preConsentOpts$stora,_preConsentOpts$stora2,_preConsentOpts$event,_preConsentOpts$event2;var _getConsentManagement=getConsentManagementData(state.loadOptions.value.consentManagement,logger),provider=_getConsentManagement.provider,consentManagerPluginName=_getConsentManagement.consentManagerPluginName,initialized=_getConsentManagement.initialized,enabled=_getConsentManagement.enabled,consentsData=_getConsentManagement.consentsData;// Pre-consent
3396
+ var preConsentOpts=state.loadOptions.value.preConsent;var storageStrategy=(_preConsentOpts$stora=preConsentOpts===null||preConsentOpts===undefined||(_preConsentOpts$stora2=preConsentOpts.storage)===null||_preConsentOpts$stora2===undefined?undefined:_preConsentOpts$stora2.strategy)!==null&&_preConsentOpts$stora!==undefined?_preConsentOpts$stora:DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;var StorageStrategies=['none','session','anonymousId'];if(isDefined(storageStrategy)&&!StorageStrategies.includes(storageStrategy)){var _preConsentOpts$stora3;storageStrategy=DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;logger.warn(UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(CONFIG_MANAGER,preConsentOpts===null||preConsentOpts===undefined||(_preConsentOpts$stora3=preConsentOpts.storage)===null||_preConsentOpts$stora3===undefined?undefined:_preConsentOpts$stora3.strategy,DEFAULT_PRE_CONSENT_STORAGE_STRATEGY));}var eventsDeliveryType=(_preConsentOpts$event=preConsentOpts===null||preConsentOpts===undefined||(_preConsentOpts$event2=preConsentOpts.events)===null||_preConsentOpts$event2===undefined?undefined:_preConsentOpts$event2.delivery)!==null&&_preConsentOpts$event!==undefined?_preConsentOpts$event:DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;var deliveryTypes=['immediate','buffer'];if(isDefined(eventsDeliveryType)&&!deliveryTypes.includes(eventsDeliveryType)){var _preConsentOpts$event3;eventsDeliveryType=DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;logger.warn(UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(CONFIG_MANAGER,preConsentOpts===null||preConsentOpts===undefined||(_preConsentOpts$event3=preConsentOpts.events)===null||_preConsentOpts$event3===undefined?undefined:_preConsentOpts$event3.delivery,DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE));}r(function(){var _state$loadOptions$va2;state.consents.activeConsentManagerPluginName.value=consentManagerPluginName;state.consents.initialized.value=initialized;state.consents.enabled.value=enabled;state.consents.data.value=consentsData;state.consents.provider.value=provider;state.consents.preConsent.value={// Only enable pre-consent if it is explicitly enabled and
3449
3397
  // if it is not already initialized and
3450
3398
  // if consent management is enabled
3451
3399
  enabled:((_state$loadOptions$va2=state.loadOptions.value.preConsent)===null||_state$loadOptions$va2===void 0?void 0:_state$loadOptions$va2.enabled)===true&&initialized===false&&enabled===true,storage:{strategy:storageStrategy},events:{delivery:eventsDeliveryType}};});};/**
@@ -3453,7 +3401,7 @@ enabled:((_state$loadOptions$va2=state.loadOptions.value.preConsent)===null||_st
3453
3401
  * @param resp Source config response
3454
3402
  * @param logger Logger instance
3455
3403
  */var updateConsentsState=function updateConsentsState(resp){var resolutionStrategy=state.consents.resolutionStrategy.value;var cmpMetadata;if(isObjectLiteralAndNotNull(resp.consentManagementMetadata)){if(state.consents.provider.value){var _resp$consentManageme,_resp$consentManageme2;resolutionStrategy=(_resp$consentManageme=(_resp$consentManageme2=resp.consentManagementMetadata.providers.find(function(p){return p.provider===state.consents.provider.value;}))===null||_resp$consentManageme2===undefined?undefined:_resp$consentManageme2.resolutionStrategy)!==null&&_resp$consentManageme!==undefined?_resp$consentManageme:state.consents.resolutionStrategy.value;}cmpMetadata=resp.consentManagementMetadata;}// If the provider is custom, then the resolution strategy is not applicable
3456
- if(state.consents.provider.value==='custom'){resolutionStrategy=undefined;}r(function(){state.consents.metadata.value=clone(cmpMetadata);state.consents.resolutionStrategy.value=resolutionStrategy;});};var updateDataPlaneEventsStateFromLoadOptions=function updateDataPlaneEventsStateFromLoadOptions(logger){if(state.dataPlaneEvents.deliveryEnabled.value){var defaultEventsQueuePluginName='XhrQueue';var eventsQueuePluginName=defaultEventsQueuePluginName;if(state.loadOptions.value.useBeacon){if(state.capabilities.isBeaconAvailable.value){eventsQueuePluginName='BeaconQueue';}else {eventsQueuePluginName=defaultEventsQueuePluginName;logger===null||logger===undefined||logger.warn(UNSUPPORTED_BEACON_API_WARNING(CONFIG_MANAGER));}}r(function(){state.dataPlaneEvents.eventsQueuePluginName.value=eventsQueuePluginName;});}};var getSourceConfigURL=function getSourceConfigURL(configUrl,writeKey,lockIntegrationsVersion,lockPluginsVersion,logger){var defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey:writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString(),lockPluginsVersion:lockPluginsVersion.toString()});var origin=DEFAULT_CONFIG_BE_URL;var searchParams=defSearchParams;var pathname='/sourceConfig/';var hash='';if(isValidURL(configUrl)){var configUrlInstance=new URL(configUrl);if(!_removeTrailingSlashes(configUrlInstance.pathname).endsWith('/sourceConfig')){configUrlInstance.pathname="".concat(_removeTrailingSlashes(configUrlInstance.pathname),"/sourceConfig/");}configUrlInstance.pathname=removeDuplicateSlashes(configUrlInstance.pathname);defSearchParams.forEach(function(value,key){if(configUrlInstance.searchParams.get(key)===null){configUrlInstance.searchParams.set(key,value);}});origin=configUrlInstance.origin;pathname=configUrlInstance.pathname;searchParams=configUrlInstance.searchParams;hash=configUrlInstance.hash;}else {logger===null||logger===undefined||logger.warn(INVALID_CONFIG_URL_WARNING(CONFIG_MANAGER,configUrl));}return "".concat(origin).concat(pathname,"?").concat(searchParams).concat(hash);};
3404
+ if(state.consents.provider.value==='custom'){resolutionStrategy=undefined;}r(function(){state.consents.metadata.value=clone(cmpMetadata);state.consents.resolutionStrategy.value=resolutionStrategy;});};var updateDataPlaneEventsStateFromLoadOptions=function updateDataPlaneEventsStateFromLoadOptions(logger){if(state.dataPlaneEvents.deliveryEnabled.value){var defaultEventsQueuePluginName='XhrQueue';var eventsQueuePluginName=defaultEventsQueuePluginName;if(state.loadOptions.value.useBeacon){if(state.capabilities.isBeaconAvailable.value){eventsQueuePluginName='BeaconQueue';}else {eventsQueuePluginName=defaultEventsQueuePluginName;logger.warn(UNSUPPORTED_BEACON_API_WARNING(CONFIG_MANAGER));}}r(function(){state.dataPlaneEvents.eventsQueuePluginName.value=eventsQueuePluginName;});}};var getSourceConfigURL=function getSourceConfigURL(configUrl,writeKey,lockIntegrationsVersion,lockPluginsVersion,logger){var defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey:writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString(),lockPluginsVersion:lockPluginsVersion.toString()});var origin=DEFAULT_CONFIG_BE_URL;var searchParams=defSearchParams;var pathname='/sourceConfig/';var hash='';if(isValidURL(configUrl)){var configUrlInstance=new URL(configUrl);if(!_removeTrailingSlashes(configUrlInstance.pathname).endsWith('/sourceConfig')){configUrlInstance.pathname="".concat(_removeTrailingSlashes(configUrlInstance.pathname),"/sourceConfig/");}configUrlInstance.pathname=removeDuplicateSlashes(configUrlInstance.pathname);defSearchParams.forEach(function(value,key){if(configUrlInstance.searchParams.get(key)===null){configUrlInstance.searchParams.set(key,value);}});origin=configUrlInstance.origin;pathname=configUrlInstance.pathname;searchParams=configUrlInstance.searchParams;hash=configUrlInstance.hash;}else {logger.warn(INVALID_CONFIG_URL_WARNING(CONFIG_MANAGER,configUrl));}return "".concat(origin).concat(pathname,"?").concat(searchParams).concat(hash);};
3457
3405
 
3458
3406
  /**
3459
3407
  * A function that determines the base URL for the integrations or plugins SDK
@@ -3463,9 +3411,10 @@ if(state.consents.provider.value==='custom'){resolutionStrategy=undefined;}r(fun
3463
3411
  * @param currentSdkVersion The current version of the SDK
3464
3412
  * @param lockVersion Flag to lock the version of the component
3465
3413
  * @param urlFromLoadOptions The URL provided by the user in the load options
3414
+ * @param logger Logger instance
3466
3415
  * @returns The base URL for the integrations or plugins SDK
3467
- */var getSDKComponentBaseURL=function getSDKComponentBaseURL(componentType,pathSuffix,defaultComponentUrl,currentSdkVersion,lockVersion,urlFromLoadOptions){var sdkComponentBaseURL;// If the user has provided a custom URL, then validate, clean up and use it
3468
- if(urlFromLoadOptions){if(!isValidURL(urlFromLoadOptions)){throw new Error(COMPONENT_BASE_URL_ERROR(componentType,urlFromLoadOptions));}sdkComponentBaseURL=_removeTrailingSlashes(urlFromLoadOptions);}else {sdkComponentBaseURL=defaultComponentUrl;// We can automatically determine the base URL only for CDN installations
3416
+ */var getSDKComponentBaseURL=function getSDKComponentBaseURL(componentType,pathSuffix,defaultComponentUrl,currentSdkVersion,lockVersion,urlFromLoadOptions,logger){var sdkComponentBaseURL;// If the user has provided a custom URL, then validate, clean up and use it
3417
+ if(urlFromLoadOptions){if(!isValidURL(urlFromLoadOptions)){logger.error(COMPONENT_BASE_URL_ERROR(CONFIG_MANAGER,componentType,urlFromLoadOptions));return null;}sdkComponentBaseURL=_removeTrailingSlashes(urlFromLoadOptions);}else {sdkComponentBaseURL=defaultComponentUrl;// We can automatically determine the base URL only for CDN installations
3469
3418
  if(state.context.app.value.installType==='cdn'){var sdkURL=getSDKUrl();if(sdkURL){// Extract the base URL from the core SDK file URL
3470
3419
  // and append the path suffix to it
3471
3420
  sdkComponentBaseURL=sdkURL.split('/').slice(0,-1).concat(pathSuffix).join('/');}}}// If the version needs to be locked, then replace the major version in the URL
@@ -3475,41 +3424,35 @@ if(lockVersion){sdkComponentBaseURL=sdkComponentBaseURL.replace(new RegExp("/".c
3475
3424
  * @param currentSdkVersion Current SDK version
3476
3425
  * @param lockIntegrationsVersion Flag to lock the integrations version
3477
3426
  * @param integrationsUrlFromLoadOptions URL to load the integrations from as provided by the user
3427
+ * @param logger Logger instance
3478
3428
  * @returns
3479
- */var getIntegrationsCDNPath=function getIntegrationsCDNPath(currentSdkVersion,lockIntegrationsVersion,integrationsUrlFromLoadOptions){return getSDKComponentBaseURL('integrations',CDN_INT_DIR,DEFAULT_INTEGRATION_SDKS_URL,currentSdkVersion,lockIntegrationsVersion,integrationsUrlFromLoadOptions);};/**
3480
- * A function that determines plugins SDK loading path
3481
- * @param currentSdkVersion Current SDK version
3482
- * @param lockPluginsVersion Flag to lock the plugins version
3483
- * @param pluginsUrlFromLoadOptions URL to load the plugins from as provided by the user
3484
- * @returns Final plugins CDN path
3485
- */var getPluginsCDNPath=function getPluginsCDNPath(currentSdkVersion,lockPluginsVersion,pluginsUrlFromLoadOptions){return getSDKComponentBaseURL('plugins',CDN_PLUGINS_DIR,DEFAULT_PLUGINS_URL,currentSdkVersion,lockPluginsVersion,pluginsUrlFromLoadOptions);};
3429
+ */var getIntegrationsCDNPath=function getIntegrationsCDNPath(currentSdkVersion,lockIntegrationsVersion,integrationsUrlFromLoadOptions,logger){return getSDKComponentBaseURL('integrations',CDN_INT_DIR,DEFAULT_INTEGRATION_SDKS_URL,currentSdkVersion,lockIntegrationsVersion,integrationsUrlFromLoadOptions,logger);};
3486
3430
 
3487
- var ConfigManager=/*#__PURE__*/function(){function ConfigManager(httpClient,errorHandler,logger){_classCallCheck(this,ConfigManager);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.httpClient=httpClient;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);this.processConfig=this.processConfig.bind(this);}return _createClass(ConfigManager,[{key:"attachEffects",value:function attachEffects(){var _this=this;E(function(){var _this$logger;(_this$logger=_this.logger)===null||_this$logger===undefined||_this$logger.setMinLogLevel(state.lifecycle.logLevel.value);});}/**
3431
+ var ConfigManager=/*#__PURE__*/function(){function ConfigManager(httpClient,errorHandler,logger){_classCallCheck(this,ConfigManager);this.errorHandler=errorHandler;this.logger=logger;this.httpClient=httpClient;this.onError=this.onError.bind(this);this.processConfig=this.processConfig.bind(this);}return _createClass(ConfigManager,[{key:"attachEffects",value:function attachEffects(){var _this=this;E(function(){_this.logger.setMinLogLevel(state.lifecycle.logLevel.value);});}/**
3488
3432
  * A function to validate, construct and store loadOption, lifecycle, source and destination
3489
3433
  * config related information in global state
3490
- */},{key:"init",value:function init(){var _this2=this;this.attachEffects();var _state$loadOptions$va=state.loadOptions.value,logLevel=_state$loadOptions$va.logLevel,configUrl=_state$loadOptions$va.configUrl,lockIntegrationsVersion=_state$loadOptions$va.lockIntegrationsVersion,lockPluginsVersion=_state$loadOptions$va.lockPluginsVersion,destSDKBaseURL=_state$loadOptions$va.destSDKBaseURL,pluginsSDKBaseURL=_state$loadOptions$va.pluginsSDKBaseURL,integrations=_state$loadOptions$va.integrations;state.lifecycle.activeDataplaneUrl.value=_removeTrailingSlashes(state.lifecycle.dataPlaneUrl.value);// determine the path to fetch integration SDK from
3491
- var intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,destSDKBaseURL);// determine the path to fetch remote plugins from
3492
- var pluginsCDNPath=getPluginsCDNPath(APP_VERSION,lockPluginsVersion,pluginsSDKBaseURL);updateStorageStateFromLoadOptions(this.logger);updateConsentsStateFromLoadOptions(this.logger);updateDataPlaneEventsStateFromLoadOptions(this.logger);// set application lifecycle state in global state
3434
+ */},{key:"init",value:function init(){var _this2=this;var _state$loadOptions$va=state.loadOptions.value,logLevel=_state$loadOptions$va.logLevel,configUrl=_state$loadOptions$va.configUrl,lockIntegrationsVersion=_state$loadOptions$va.lockIntegrationsVersion,lockPluginsVersion=_state$loadOptions$va.lockPluginsVersion,destSDKBaseURL=_state$loadOptions$va.destSDKBaseURL;_state$loadOptions$va.pluginsSDKBaseURL;var integrations=_state$loadOptions$va.integrations;// determine the path to fetch integration SDK from
3435
+ var intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,destSDKBaseURL,this.logger);if(isNull(intgCdnUrl)){return;}var pluginsCDNPath;this.attachEffects();state.lifecycle.activeDataplaneUrl.value=_removeTrailingSlashes(state.lifecycle.dataPlaneUrl.value);updateStorageStateFromLoadOptions(this.logger);updateConsentsStateFromLoadOptions(this.logger);updateDataPlaneEventsStateFromLoadOptions(this.logger);// set application lifecycle state in global state
3493
3436
  r(function(){state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycle.pluginsCDNPath.value=pluginsCDNPath;if(logLevel){state.lifecycle.logLevel.value=logLevel;}state.lifecycle.sourceConfigUrl.value=getSourceConfigURL(configUrl,state.lifecycle.writeKey.value,lockIntegrationsVersion,lockPluginsVersion,_this2.logger);state.metrics.metricsServiceUrl.value="".concat(state.lifecycle.activeDataplaneUrl.value,"/").concat(METRICS_SERVICE_ENDPOINT);// Data in the loadOptions state is already normalized
3494
3437
  state.nativeDestinations.loadOnlyIntegrations.value=integrations;});this.getConfig();}/**
3495
3438
  * Handle errors
3496
- */},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===undefined||_this$errorHandler.onError(error,CONFIG_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}/**
3439
+ */},{key:"onError",value:function onError(error,customMessage){this.errorHandler.onError(error,CONFIG_MANAGER,customMessage);}/**
3497
3440
  * A callback function that is executed once we fetch the source config response.
3498
3441
  * Use to construct and store information that are dependent on the sourceConfig.
3499
3442
  */},{key:"processConfig",value:function processConfig(response,details){// TODO: add retry logic with backoff based on rejectionDetails.xhr.status
3500
3443
  // We can use isErrRetryable utility method
3501
- if(!response){this.onError(SOURCE_CONFIG_FETCH_ERROR(details===null||details===undefined?undefined:details.error));return;}var res;try{if(isString(response)){res=JSON.parse(response);}else {res=response;}}catch(err){this.onError(err,SOURCE_CONFIG_RESOLUTION_ERROR,true);return;}if(!isValidSourceConfig(res)){this.onError(new Error(SOURCE_CONFIG_RESOLUTION_ERROR),undefined,true);return;}// Log error and abort if source is disabled
3502
- if(res.source.enabled===false){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===undefined||_this$logger2.error(SOURCE_DISABLED_ERROR);return;}// set the values in state for reporting slice
3444
+ if(!isDefined(response)){if(isDefined(details)){this.onError(details.error,SOURCE_CONFIG_FETCH_ERROR);}else {this.onError(new Error(SOURCE_CONFIG_FETCH_ERROR));}return;}var res;try{if(isString(response)){res=JSON.parse(response);}else {res=response;}}catch(err){this.onError(err,SOURCE_CONFIG_RESOLUTION_ERROR);return;}if(!isValidSourceConfig(res)){this.onError(new Error(SOURCE_CONFIG_RESOLUTION_ERROR));return;}// Log error and abort if source is disabled
3445
+ if(res.source.enabled===false){this.logger.error(SOURCE_DISABLED_ERROR);return;}// set the values in state for reporting slice
3503
3446
  updateReportingState(res);var nativeDestinations=res.source.destinations.length>0?filterEnabledDestination(res.source.destinations):[];// set in the state --> source, destination, lifecycle, reporting
3504
3447
  r(function(){var _state$loadOptions$va2;// set source related information in state
3505
- state.source.value={config:res.source.config,id:res.source.id,workspaceId:res.source.workspaceId};// set device mode destination related information in state
3448
+ state.source.value={config:res.source.config,name:res.source.name,id:res.source.id,workspaceId:res.source.workspaceId};// set device mode destination related information in state
3506
3449
  state.nativeDestinations.configuredDestinations.value=nativeDestinations;// set the desired optional plugins
3507
3450
  state.plugins.pluginsToLoadFromConfig.value=(_state$loadOptions$va2=state.loadOptions.value.plugins)!==null&&_state$loadOptions$va2!==void 0?_state$loadOptions$va2:[];updateConsentsState(res);// set application lifecycle state
3508
3451
  state.lifecycle.status.value='configured';});}/**
3509
3452
  * A function to fetch source config either from /sourceConfig endpoint
3510
3453
  * or from getSourceConfig load option
3511
3454
  * @returns
3512
- */},{key:"getConfig",value:function getConfig(){var _this3=this;var sourceConfigFunc=state.loadOptions.value.getSourceConfig;if(sourceConfigFunc){if(!isFunction(sourceConfigFunc)){throw new Error(SOURCE_CONFIG_OPTION_ERROR);}// Fetch source config from the function
3455
+ */},{key:"getConfig",value:function getConfig(){var _this3=this;var sourceConfigFunc=state.loadOptions.value.getSourceConfig;if(sourceConfigFunc){if(!isFunction(sourceConfigFunc)){this.logger.error(SOURCE_CONFIG_OPTION_ERROR(CONFIG_MANAGER));return;}// Fetch source config from the function
3513
3456
  var res=sourceConfigFunc();if(res instanceof Promise){res.then(function(pRes){return _this3.processConfig(pRes);}).catch(function(err){_this3.onError(err,'SourceConfig');});}else {this.processConfig(res);}}else {// Fetch source configuration from the configured URL
3514
3457
  this.httpClient.getAsyncData({url:state.lifecycle.sourceConfigUrl.value,options:{headers:{'Content-Type':undefined}},callback:this.processConfig});}}}]);}();
3515
3458
 
@@ -3544,16 +3487,16 @@ if(urlObj.search===''){pageUrl=canonicalUrl+search;}else {pageUrl=canonicalUrl;}
3544
3487
  var POLYFILL_URL='';var POLYFILL_LOAD_TIMEOUT=10*1000;// 10 seconds
3545
3488
  var POLYFILL_SCRIPT_ID='rudderstackPolyfill';
3546
3489
 
3547
- var CapabilitiesManager=/*#__PURE__*/function(){function CapabilitiesManager(errorHandler,logger){_classCallCheck(this,CapabilitiesManager);this.logger=logger;this.errorHandler=errorHandler;this.externalSrcLoader=new ExternalSrcLoader(this.errorHandler,this.logger);this.onError=this.onError.bind(this);this.onReady=this.onReady.bind(this);}return _createClass(CapabilitiesManager,[{key:"init",value:function init(){try{this.prepareBrowserCapabilities();this.attachWindowListeners();}catch(err){this.onError(err);}}/**
3490
+ var CapabilitiesManager=/*#__PURE__*/function(){function CapabilitiesManager(httpClient,errorHandler,logger){_classCallCheck(this,CapabilitiesManager);this.httpClient=httpClient;this.errorHandler=errorHandler;this.logger=logger;this.externalSrcLoader=new ExternalSrcLoader(this.errorHandler,this.logger);this.onError=this.onError.bind(this);this.onReady=this.onReady.bind(this);}return _createClass(CapabilitiesManager,[{key:"init",value:function init(){this.prepareBrowserCapabilities();this.attachWindowListeners();}/**
3548
3491
  * Detect supported capabilities and set values in state
3549
3492
  */// eslint-disable-next-line class-methods-use-this
3550
3493
  },{key:"detectBrowserCapabilities",value:function detectBrowserCapabilities(){var _this=this;r(function(){// Storage related details
3551
3494
  state.capabilities.storage.isCookieStorageAvailable.value=isStorageAvailable(COOKIE_STORAGE,getStorageEngine(COOKIE_STORAGE),_this.logger);state.capabilities.storage.isLocalStorageAvailable.value=isStorageAvailable(LOCAL_STORAGE,undefined,_this.logger);state.capabilities.storage.isSessionStorageAvailable.value=isStorageAvailable(SESSION_STORAGE,undefined,_this.logger);// Browser feature detection details
3552
3495
  state.capabilities.isBeaconAvailable.value=hasBeacon();state.capabilities.isUaCHAvailable.value=hasUAClientHints();state.capabilities.isCryptoAvailable.value=hasCrypto();state.capabilities.isIE11.value=isIE11();state.capabilities.isOnline.value=globalThis.navigator.onLine;// Get page context details
3553
3496
  state.context.userAgent.value=getUserAgent();state.context.locale.value=getLanguage();state.context.screen.value=getScreenDetails();state.context.timezone.value=getTimezone();if(hasUAClientHints()){getUserAgentClientHint(function(uach){state.context['ua-ch'].value=uach;},state.loadOptions.value.uaChTrackLevel);}});// Ad blocker detection
3554
- E(function(){if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(_this.errorHandler,_this.logger);}});}/**
3497
+ E(function(){if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(_this.httpClient);}});}/**
3555
3498
  * Detect if polyfills are required and then load script from polyfill URL
3556
- */},{key:"prepareBrowserCapabilities",value:function prepareBrowserCapabilities(){var _this2=this;state.capabilities.isLegacyDOM.value=isLegacyJSEngine();var customPolyfillUrl=state.loadOptions.value.polyfillURL;var polyfillUrl=POLYFILL_URL;if(isDefinedAndNotNull(customPolyfillUrl)){if(isValidURL(customPolyfillUrl)){polyfillUrl=customPolyfillUrl;}else {var _this$logger;(_this$logger=this.logger)===null||_this$logger===undefined||_this$logger.warn(INVALID_POLYFILL_URL_WARNING(CAPABILITIES_MANAGER,customPolyfillUrl));}}var shouldLoadPolyfill=state.loadOptions.value.polyfillIfRequired&&state.capabilities.isLegacyDOM.value&&isValidURL(polyfillUrl);if(shouldLoadPolyfill){var isDefaultPolyfillService=polyfillUrl!==state.loadOptions.value.polyfillURL;if(isDefaultPolyfillService){// write key specific callback
3499
+ */},{key:"prepareBrowserCapabilities",value:function prepareBrowserCapabilities(){var _this2=this;state.capabilities.isLegacyDOM.value=isLegacyJSEngine();var customPolyfillUrl=state.loadOptions.value.polyfillURL;var polyfillUrl=POLYFILL_URL;if(isDefinedAndNotNull(customPolyfillUrl)){if(isValidURL(customPolyfillUrl)){polyfillUrl=customPolyfillUrl;}else {this.logger.warn(INVALID_POLYFILL_URL_WARNING(CAPABILITIES_MANAGER,customPolyfillUrl));}}var shouldLoadPolyfill=state.loadOptions.value.polyfillIfRequired&&state.capabilities.isLegacyDOM.value&&isValidURL(polyfillUrl);if(shouldLoadPolyfill){var isDefaultPolyfillService=polyfillUrl!==state.loadOptions.value.polyfillURL;if(isDefaultPolyfillService){// write key specific callback
3557
3500
  // NOTE: we're not putting this into RudderStackGlobals as providing the property path to the callback function in the polyfill URL is not possible
3558
3501
  var polyfillCallbackName="RS_polyfillCallback_".concat(state.lifecycle.writeKey.value);var polyfillCallback=function polyfillCallback(){_this2.onReady();// Remove the entry from window so we don't leave room for calling it again
3559
3502
  delete globalThis[polyfillCallbackName];};globalThis[polyfillCallbackName]=polyfillCallback;polyfillUrl="".concat(polyfillUrl,"&callback=").concat(polyfillCallbackName);}this.externalSrcLoader.loadJSFile({url:polyfillUrl,id:POLYFILL_SCRIPT_ID,async:true,timeout:POLYFILL_LOAD_TIMEOUT,callback:function callback(scriptId){if(!scriptId){_this2.onError(new Error(POLYFILL_SCRIPT_LOAD_ERROR(POLYFILL_SCRIPT_ID,polyfillUrl)));}else if(!isDefaultPolyfillService){_this2.onReady();}}});}else {this.onReady();}}/**
@@ -3564,7 +3507,7 @@ delete globalThis[polyfillCallbackName];};globalThis[polyfillCallbackName]=polyf
3564
3507
  },{key:"onReady",value:function onReady(){this.detectBrowserCapabilities();state.lifecycle.status.value='browserCapabilitiesReady';}/**
3565
3508
  * Handles error
3566
3509
  * @param error The error object
3567
- */},{key:"onError",value:function onError(error){if(this.errorHandler){this.errorHandler.onError(error,CAPABILITIES_MANAGER);}else {throw error;}}}]);}();
3510
+ */},{key:"onError",value:function onError(error){this.errorHandler.onError(error,CAPABILITIES_MANAGER);}}]);}();
3568
3511
 
3569
3512
  var CHANNEL='web';// These are the top-level elements in the standard RudderStack event spec
3570
3513
  var TOP_LEVEL_ELEMENTS=['integrations','anonymousId','originalTimestamp'];// Reserved elements in the context of standard RudderStack event spec
@@ -3598,7 +3541,7 @@ var MIN_SESSION_ID_LENGTH=10;/**
3598
3541
  * @param {number} sessionId
3599
3542
  * @param logger logger
3600
3543
  * @returns
3601
- */var isManualSessionIdValid=function isManualSessionIdValid(sessionId,logger){if(!sessionId||!isPositiveInteger(sessionId)||!hasMinLength(MIN_SESSION_ID_LENGTH,sessionId)){logger===null||logger===undefined||logger.warn(INVALID_SESSION_ID_WARNING(USER_SESSION_MANAGER,sessionId,MIN_SESSION_ID_LENGTH));return false;}return true;};/**
3544
+ */var isManualSessionIdValid=function isManualSessionIdValid(sessionId,logger){if(!sessionId||!isPositiveInteger(sessionId)||!hasMinLength(MIN_SESSION_ID_LENGTH,sessionId)){logger.warn(INVALID_SESSION_ID_WARNING(USER_SESSION_MANAGER,sessionId,MIN_SESSION_ID_LENGTH));return false;}return true;};/**
3602
3545
  * A function to generate new auto tracking session
3603
3546
  * @param sessionTimeout current timestamp
3604
3547
  * @returns SessionInfo
@@ -3629,7 +3572,7 @@ var curPageProps=getDefaultPageProperties();Object.keys(curPageProps).forEach(fu
3629
3572
  * @param obj Generic object
3630
3573
  * @param parentKeyPath Object's parent key path
3631
3574
  * @param logger Logger instance
3632
- */var checkForReservedElementsInObject=function checkForReservedElementsInObject(obj,parentKeyPath,logger){if(isObjectLiteralAndNotNull(obj)){Object.keys(obj).forEach(function(property){if(RESERVED_ELEMENTS.includes(property)||RESERVED_ELEMENTS.includes(property.toLowerCase())){logger===null||logger===undefined||logger.warn(RESERVED_KEYWORD_WARNING(EVENT_MANAGER,property,parentKeyPath,RESERVED_ELEMENTS));}});}};/**
3575
+ */var checkForReservedElementsInObject=function checkForReservedElementsInObject(obj,parentKeyPath,logger){if(isObjectLiteralAndNotNull(obj)){Object.keys(obj).forEach(function(property){if(RESERVED_ELEMENTS.includes(property)||RESERVED_ELEMENTS.includes(property.toLowerCase())){logger.warn(RESERVED_KEYWORD_WARNING(EVENT_MANAGER,property,parentKeyPath,RESERVED_ELEMENTS));}});}};/**
3633
3576
  * Checks for reserved keys in traits, properties, and contextual traits
3634
3577
  * @param rudderEvent Generated rudder event
3635
3578
  * @param logger Logger instance
@@ -3646,13 +3589,13 @@ rudderEvent.originalTimestamp=options.originalTimestamp;}};/**
3646
3589
  * @param rudderContext Generated rudder event
3647
3590
  * @param options API options
3648
3591
  * @param logger Logger instance
3649
- */var getMergedContext=function getMergedContext(rudderContext,options,logger){var context=rudderContext;Object.keys(options).forEach(function(key){if(!TOP_LEVEL_ELEMENTS.includes(key)&&!CONTEXT_RESERVED_ELEMENTS.includes(key)){if(key!=='context'){context=mergeDeepRight(context,_defineProperty({},key,options[key]));}else if(!isUndefined(options[key])&&isObjectLiteralAndNotNull(options[key])){var tempContext={};Object.keys(options[key]).forEach(function(e){if(!CONTEXT_RESERVED_ELEMENTS.includes(e)){tempContext[e]=options[key][e];}});context=mergeDeepRight(context,_objectSpread2({},tempContext));}else;}});return context;};/**
3592
+ */var getMergedContext=function getMergedContext(rudderContext,options,logger){var context=rudderContext;Object.keys(options).forEach(function(key){if(!TOP_LEVEL_ELEMENTS.includes(key)&&!CONTEXT_RESERVED_ELEMENTS.includes(key)){if(key!=='context'){context=mergeDeepRight(context,_defineProperty({},key,options[key]));}else if(!isUndefined(options[key])&&isObjectLiteralAndNotNull(options[key])){var tempContext={};Object.keys(options[key]).forEach(function(e){if(!CONTEXT_RESERVED_ELEMENTS.includes(e)){tempContext[e]=options[key][e];}});context=mergeDeepRight(context,_objectSpread2({},tempContext));}else {logger.warn(INVALID_CONTEXT_OBJECT_WARNING(EVENT_MANAGER));}}});return context;};/**
3650
3593
  * Updates rudder event object with data from the API options
3651
3594
  * @param rudderEvent Generated rudder event
3652
3595
  * @param options API options
3653
- */var processOptions=function processOptions(rudderEvent,options){// Only allow object type for options
3596
+ */var processOptions=function processOptions(rudderEvent,options,logger){// Only allow object type for options
3654
3597
  if(isObjectLiteralAndNotNull(options)){updateTopLevelEventElements(rudderEvent,options);// eslint-disable-next-line no-param-reassign
3655
- rudderEvent.context=getMergedContext(rudderEvent.context,options);}};/**
3598
+ rudderEvent.context=getMergedContext(rudderEvent.context,options,logger);}};/**
3656
3599
  * Returns the final integrations config for the event based on the global config and event's config
3657
3600
  * @param integrationsConfig Event's integrations config
3658
3601
  * @returns Final integrations config
@@ -3669,7 +3612,7 @@ commonEventData.anonymousId=generateAnonymousId();}else {// Type casting to stri
3669
3612
  commonEventData.anonymousId=state.session.anonymousId.value;}// set truly anonymous tracking flag
3670
3613
  if(state.storage.trulyAnonymousTracking.value){commonEventData.context.trulyAnonymousTracking=true;}if(rudderEvent.type==='identify'){var _state$storage$entrie2;commonEventData.context.traits=((_state$storage$entrie2=state.storage.entries.value.userTraits)===null||_state$storage$entrie2===undefined?undefined:_state$storage$entrie2.type)!==NO_STORAGE?clone(state.session.userTraits.value):rudderEvent.context.traits;}if(rudderEvent.type==='group'){if(rudderEvent.groupId||state.session.groupId.value){commonEventData.groupId=rudderEvent.groupId||state.session.groupId.value;}if(rudderEvent.traits||state.session.groupTraits.value){var _state$storage$entrie3;commonEventData.traits=((_state$storage$entrie3=state.storage.entries.value.groupTraits)===null||_state$storage$entrie3===undefined?undefined:_state$storage$entrie3.type)!==NO_STORAGE?clone(state.session.groupTraits.value):rudderEvent.traits;}}var processedEvent=mergeDeepRight(rudderEvent,commonEventData);// Set the default values for the event properties
3671
3614
  // matching with v1.1 payload
3672
- if(processedEvent.event===undefined){processedEvent.event=null;}if(processedEvent.properties===undefined){processedEvent.properties=null;}processOptions(processedEvent,options);checkForReservedElements(processedEvent,logger);// Update the integrations config for the event
3615
+ if(processedEvent.event===undefined){processedEvent.event=null;}if(processedEvent.properties===undefined){processedEvent.properties=null;}processOptions(processedEvent,options,logger);checkForReservedElements(processedEvent,logger);// Update the integrations config for the event
3673
3616
  processedEvent.integrations=getEventIntegrationsConfig(processedEvent.integrations);return processedEvent;};
3674
3617
 
3675
3618
  var RudderEventFactory=/*#__PURE__*/function(){function RudderEventFactory(logger){_classCallCheck(this,RudderEventFactory);this.logger=logger;}/**
@@ -3703,7 +3646,7 @@ enrichedEvent.userId=to!==null&&to!==undefined?to:enrichedEvent.userId;return en
3703
3646
  * Generates a new RudderEvent object based on the user-input fields
3704
3647
  * @param event API event parameters object
3705
3648
  * @returns A RudderEvent object
3706
- */},{key:"create",value:function create(event){var eventObj;switch(event.type){case 'page':eventObj=this.generatePageEvent(event.category,event.name,event.properties,event.options);break;case 'track':eventObj=this.generateTrackEvent(event.name,event.properties,event.options);break;case 'identify':eventObj=this.generateIdentifyEvent(event.userId,event.traits,event.options);break;case 'alias':eventObj=this.generateAliasEvent(event.to,event.from,event.options);break;case 'group':eventObj=this.generateGroupEvent(event.groupId,event.traits,event.options);break;}return eventObj;}}]);}();
3649
+ */},{key:"create",value:function create(event){var eventObj;switch(event.type){case 'page':eventObj=this.generatePageEvent(event.category,event.name,event.properties,event.options);break;case 'track':eventObj=this.generateTrackEvent(event.name,event.properties,event.options);break;case 'identify':eventObj=this.generateIdentifyEvent(event.userId,event.traits,event.options);break;case 'alias':eventObj=this.generateAliasEvent(event.to,event.from,event.options);break;case 'group':default:eventObj=this.generateGroupEvent(event.groupId,event.traits,event.options);break;}return eventObj;}}]);}();
3707
3650
 
3708
3651
  /**
3709
3652
  * A service to generate valid event payloads and queue them for processing
@@ -3713,17 +3656,14 @@ enrichedEvent.userId=to!==null&&to!==undefined?to:enrichedEvent.userId;return en
3713
3656
  * @param userSessionManager UserSession Manager instance
3714
3657
  * @param errorHandler Error handler object
3715
3658
  * @param logger Logger object
3716
- */function EventManager(eventRepository,userSessionManager,errorHandler,logger){_classCallCheck(this,EventManager);this.eventRepository=eventRepository;this.userSessionManager=userSessionManager;this.errorHandler=errorHandler;this.logger=logger;this.eventFactory=new RudderEventFactory(this.logger);this.onError=this.onError.bind(this);}/**
3659
+ */function EventManager(eventRepository,userSessionManager,errorHandler,logger){_classCallCheck(this,EventManager);this.eventRepository=eventRepository;this.userSessionManager=userSessionManager;this.errorHandler=errorHandler;this.logger=logger;this.eventFactory=new RudderEventFactory(this.logger);}/**
3717
3660
  * Initializes the event manager
3718
3661
  */return _createClass(EventManager,[{key:"init",value:function init(){this.eventRepository.init();}},{key:"resume",value:function resume(){this.eventRepository.resume();}/**
3719
3662
  * Consumes a new incoming event
3720
3663
  * @param event Incoming event data
3721
- */},{key:"addEvent",value:function addEvent(event){this.userSessionManager.refreshSession();var rudderEvent=this.eventFactory.create(event);if(rudderEvent){this.eventRepository.enqueue(rudderEvent,event.callback);}else {this.onError(new Error(EVENT_OBJECT_GENERATION_ERROR));}}/**
3722
- * Handles error
3723
- * @param error The error object
3724
- */},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);}();
3664
+ */},{key:"addEvent",value:function addEvent(event){this.userSessionManager.refreshSession();var rudderEvent=this.eventFactory.create(event);this.eventRepository.enqueue(rudderEvent,event.callback);}}]);}();
3725
3665
 
3726
- var UserSessionManager=/*#__PURE__*/function(){function UserSessionManager(errorHandler,logger,pluginsManager,storeManager,httpClient){_classCallCheck(this,UserSessionManager);this.storeManager=storeManager;this.pluginsManager=pluginsManager;this.logger=logger;this.errorHandler=errorHandler;this.httpClient=httpClient;this.onError=this.onError.bind(this);this.serverSideCookieDebounceFuncs={};}/**
3666
+ var UserSessionManager=/*#__PURE__*/function(){function UserSessionManager(pluginsManager,storeManager,httpClient,errorHandler,logger){_classCallCheck(this,UserSessionManager);this.storeManager=storeManager;this.pluginsManager=pluginsManager;this.logger=logger;this.errorHandler=errorHandler;this.httpClient=httpClient;this.onError=this.onError.bind(this);this.serverSideCookieDebounceFuncs={};}/**
3727
3667
  * Initialize User session with values from storage
3728
3668
  */return _createClass(UserSessionManager,[{key:"init",value:function init(){this.syncStorageDataToState();// Register the effect to sync with storage
3729
3669
  this.registerEffects();}},{key:"syncStorageDataToState",value:function syncStorageDataToState(){var _externalAnonymousId;this.migrateStorageIfNeeded();this.migrateDataFromPreviousStorage();// get the values from storage and set it again
@@ -3734,12 +3674,12 @@ if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking(stat
3734
3674
  // as those values indicate there is no need for migration or
3735
3675
  // migration failed
3736
3676
  if(!isNullOrUndefined(migratedVal)){store.set(storageEntry,migratedVal);}});});}},{key:"getConfiguredSessionTrackingInfo",value:function getConfiguredSessionTrackingInfo(){var _state$loadOptions$va2,_state$loadOptions$va3;var autoTrack=((_state$loadOptions$va2=state.loadOptions.value.sessions)===null||_state$loadOptions$va2===undefined?undefined:_state$loadOptions$va2.autoTrack)!==false;// Do not validate any further if autoTrack is disabled
3737
- if(!autoTrack){return {autoTrack:autoTrack};}var timeout;var configuredSessionTimeout=(_state$loadOptions$va3=state.loadOptions.value.sessions)===null||_state$loadOptions$va3===undefined?undefined:_state$loadOptions$va3.timeout;if(!isPositiveInteger(configuredSessionTimeout)){var _this$logger;(_this$logger=this.logger)===null||_this$logger===undefined||_this$logger.warn(TIMEOUT_NOT_NUMBER_WARNING(USER_SESSION_MANAGER,configuredSessionTimeout,DEFAULT_SESSION_TIMEOUT_MS));timeout=DEFAULT_SESSION_TIMEOUT_MS;}else {timeout=configuredSessionTimeout;}if(timeout===0){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===undefined||_this$logger2.warn(TIMEOUT_ZERO_WARNING(USER_SESSION_MANAGER));autoTrack=false;}// In case user provides a timeout value greater than 0 but less than 10 seconds SDK will show a warning
3677
+ if(!autoTrack){return {autoTrack:autoTrack};}var timeout;var configuredSessionTimeout=(_state$loadOptions$va3=state.loadOptions.value.sessions)===null||_state$loadOptions$va3===undefined?undefined:_state$loadOptions$va3.timeout;if(!isPositiveInteger(configuredSessionTimeout)){this.logger.warn(TIMEOUT_NOT_NUMBER_WARNING(USER_SESSION_MANAGER,configuredSessionTimeout,DEFAULT_SESSION_TIMEOUT_MS));timeout=DEFAULT_SESSION_TIMEOUT_MS;}else {timeout=configuredSessionTimeout;}if(timeout===0){this.logger.warn(TIMEOUT_ZERO_WARNING(USER_SESSION_MANAGER));autoTrack=false;}// In case user provides a timeout value greater than 0 but less than 10 seconds SDK will show a warning
3738
3678
  // and will proceed with it
3739
- if(timeout>0&&timeout<MIN_SESSION_TIMEOUT_MS){var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===undefined||_this$logger3.warn(TIMEOUT_NOT_RECOMMENDED_WARNING(USER_SESSION_MANAGER,timeout,MIN_SESSION_TIMEOUT_MS));}return {timeout:timeout,autoTrack:autoTrack};}/**
3679
+ if(timeout>0&&timeout<MIN_SESSION_TIMEOUT_MS){this.logger.warn(TIMEOUT_NOT_RECOMMENDED_WARNING(USER_SESSION_MANAGER,timeout,MIN_SESSION_TIMEOUT_MS));}return {timeout:timeout,autoTrack:autoTrack};}/**
3740
3680
  * Handles error
3741
3681
  * @param error The error object
3742
- */},{key:"onError",value:function onError(error,customMessage){if(this.errorHandler){this.errorHandler.onError(error,USER_SESSION_MANAGER,customMessage);}else {throw error;}}/**
3682
+ */},{key:"onError",value:function onError(error,customMessage){this.errorHandler.onError(error,USER_SESSION_MANAGER,customMessage);}/**
3743
3683
  * A function to encrypt the cookie value and return the encrypted data
3744
3684
  * @param cookiesData
3745
3685
  * @param store
@@ -3754,7 +3694,7 @@ if(timeout>0&&timeout<MIN_SESSION_TIMEOUT_MS){var _this$logger3;(_this$logger3=t
3754
3694
  * @param value encrypted cookie value
3755
3695
  */},{key:"setServerSideCookies",value:function setServerSideCookies(cookiesData,cb,store){var _this4=this;try{// encrypt cookies values
3756
3696
  var encryptedCookieData=this.getEncryptedCookieData(cookiesData,store);if(encryptedCookieData.length>0){// make request to data service to set the cookie from server side
3757
- this.makeRequestToSetCookie(encryptedCookieData,function(res,details){var _details$xhr;if((details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.status)===200){cookiesData.forEach(function(cData){var cookieValue=store===null||store===void 0?void 0:store.get(cData.name);var before=stringifyWithoutCircular(cData.value,false,[]);var after=stringifyWithoutCircular(cookieValue,false,[]);if(after!==before){var _this4$logger;(_this4$logger=_this4.logger)===null||_this4$logger===void 0||_this4$logger.error(FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(cData.name));if(cb){cb(cData.name,cData.value);}}});}else {var _this4$logger2,_details$xhr2;(_this4$logger2=_this4.logger)===null||_this4$logger2===void 0||_this4$logger2.error(DATA_SERVER_REQUEST_FAIL_ERROR(details===null||details===void 0||(_details$xhr2=details.xhr)===null||_details$xhr2===void 0?void 0:_details$xhr2.status));cookiesData.forEach(function(each){if(cb){cb(each.name,each.value);}});}});}}catch(e){this.onError(e,FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR);cookiesData.forEach(function(each){if(cb){cb(each.name,each.value);}});}}/**
3697
+ this.makeRequestToSetCookie(encryptedCookieData,function(res,details){var _details$xhr;if((details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.status)===200){cookiesData.forEach(function(cData){var cookieValue=store===null||store===void 0?void 0:store.get(cData.name);var before=stringifyWithoutCircular(cData.value,false,[]);var after=stringifyWithoutCircular(cookieValue,false,[]);if(after!==before){_this4.logger.error(FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(cData.name));if(cb){cb(cData.name,cData.value);}}});}else {var _details$xhr2;_this4.logger.error(DATA_SERVER_REQUEST_FAIL_ERROR(details===null||details===void 0||(_details$xhr2=details.xhr)===null||_details$xhr2===void 0?void 0:_details$xhr2.status));cookiesData.forEach(function(each){if(cb){cb(each.name,each.value);}});}});}}catch(e){this.onError(e,FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR);cookiesData.forEach(function(each){if(cb){cb(each.name,each.value);}});}}/**
3758
3698
  * A function to sync values in storage
3759
3699
  * @param sessionKey
3760
3700
  * @param value
@@ -3858,7 +3798,7 @@ _this7.setAnonymousId();}if(noNewSessionStart){return;}if(autoTrack){session.ses
3858
3798
 
3859
3799
  /**
3860
3800
  * Plugins to be loaded in the plugins loadOption is not defined
3861
- */var defaultOptionalPluginsList=['BeaconQueue','Bugsnag','CustomConsentManager','DeviceModeDestinations','DeviceModeTransformation','ErrorReporting','ExternalAnonymousId','GoogleLinker','IubendaConsentManager','KetchConsentManager','NativeDestinationQueue','OneTrustConsentManager','StorageEncryption','StorageEncryptionLegacy','StorageMigrator','XhrQueue'];
3801
+ */var defaultOptionalPluginsList=['BeaconQueue','CustomConsentManager','DeviceModeDestinations','DeviceModeTransformation','ExternalAnonymousId','GoogleLinker','IubendaConsentManager','KetchConsentManager','NativeDestinationQueue','OneTrustConsentManager','StorageEncryption','StorageEncryptionLegacy','StorageMigrator','XhrQueue'];
3862
3802
 
3863
3803
  var normalizeLoadOptions=function normalizeLoadOptions(loadOptionsFromState,loadOptions){// TODO: Maybe add warnings for invalid values
3864
3804
  var normalizedLoadOpts=clone(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){normalizedLoadOpts.setCookieDomain=undefined;}var cookieSameSiteValues=['Strict','Lax','None'];if(!cookieSameSiteValues.includes(normalizedLoadOpts.sameSiteCookie)){normalizedLoadOpts.sameSiteCookie=undefined;}normalizedLoadOpts.secureCookie=getNormalizedBooleanValue(normalizedLoadOpts.secureCookie,loadOptionsFromState.secureCookie);normalizedLoadOpts.sameDomainCookiesOnly=getNormalizedBooleanValue(normalizedLoadOpts.sameDomainCookiesOnly,loadOptionsFromState.sameDomainCookiesOnly);var uaChTrackLevels=['none','default','full'];if(!uaChTrackLevels.includes(normalizedLoadOpts.uaChTrackLevel)){normalizedLoadOpts.uaChTrackLevel=undefined;}normalizedLoadOpts.integrations=getNormalizedObjectValue(normalizedLoadOpts.integrations);if(!Array.isArray(normalizedLoadOpts.plugins)){normalizedLoadOpts.plugins=defaultOptionalPluginsList;}normalizedLoadOpts.useGlobalIntegrationsConfigInEvents=getNormalizedBooleanValue(normalizedLoadOpts.useGlobalIntegrationsConfigInEvents,loadOptionsFromState.useGlobalIntegrationsConfigInEvents);normalizedLoadOpts.bufferDataPlaneEventsUntilReady=getNormalizedBooleanValue(normalizedLoadOpts.bufferDataPlaneEventsUntilReady,loadOptionsFromState.bufferDataPlaneEventsUntilReady);normalizedLoadOpts.sendAdblockPage=getNormalizedBooleanValue(normalizedLoadOpts.sendAdblockPage,loadOptionsFromState.sendAdblockPage);normalizedLoadOpts.useServerSideCookies=getNormalizedBooleanValue(normalizedLoadOpts.useServerSideCookies,loadOptionsFromState.useServerSideCookies);if(!isString(normalizedLoadOpts.dataServiceEndpoint)){normalizedLoadOpts.dataServiceEndpoint=undefined;}normalizedLoadOpts.sendAdblockPageOptions=getNormalizedObjectValue(normalizedLoadOpts.sendAdblockPageOptions);normalizedLoadOpts.loadIntegration=getNormalizedBooleanValue(normalizedLoadOpts.loadIntegration,loadOptionsFromState.loadIntegration);if(!isNonEmptyObject(normalizedLoadOpts.storage)){normalizedLoadOpts.storage=undefined;}else {var _loadOptionsFromState;normalizedLoadOpts.storage.migrate=getNormalizedBooleanValue(normalizedLoadOpts.storage.migrate,(_loadOptionsFromState=loadOptionsFromState.storage)===null||_loadOptionsFromState===undefined?undefined:_loadOptionsFromState.migrate);normalizedLoadOpts.storage.cookie=getNormalizedObjectValue(normalizedLoadOpts.storage.cookie);normalizedLoadOpts.storage.encryption=getNormalizedObjectValue(normalizedLoadOpts.storage.encryption);normalizedLoadOpts.storage=_removeUndefinedAndNullValues(normalizedLoadOpts.storage);}normalizedLoadOpts.destinationsQueueOptions=getNormalizedObjectValue(normalizedLoadOpts.destinationsQueueOptions);normalizedLoadOpts.queueOptions=getNormalizedObjectValue(normalizedLoadOpts.queueOptions);normalizedLoadOpts.lockIntegrationsVersion=getNormalizedBooleanValue(normalizedLoadOpts.lockIntegrationsVersion,loadOptionsFromState.lockIntegrationsVersion);normalizedLoadOpts.lockPluginsVersion=getNormalizedBooleanValue(normalizedLoadOpts.lockPluginsVersion,loadOptionsFromState.lockPluginsVersion);if(!isNumber(normalizedLoadOpts.dataPlaneEventsBufferTimeout)){normalizedLoadOpts.dataPlaneEventsBufferTimeout=undefined;}normalizedLoadOpts.beaconQueueOptions=getNormalizedObjectValue(normalizedLoadOpts.beaconQueueOptions);normalizedLoadOpts.preConsent=getNormalizedObjectValue(normalizedLoadOpts.preConsent);var mergedLoadOptions=mergeDeepRight(loadOptionsFromState,_removeUndefinedAndNullValues(normalizedLoadOpts));return mergedLoadOptions;};
@@ -3879,6 +3819,8 @@ var DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';var DESTINATIONS_QU
3879
3819
  // In general, the preference is given to the event's integrations config
3880
3820
  var destinationsIntgConfig=state.nativeDestinations.integrationsConfig.value;var overriddenIntgOpts=getOverriddenIntegrationOptions(event.integrations,destinationsIntgConfig);finalEvent.integrations=mergeDeepRight(destinationsIntgConfig,overriddenIntgOpts);return finalEvent;};var shouldBufferEventsForPreConsent=function shouldBufferEventsForPreConsent(state){var _state$consents$preCo,_state$consents$preCo2,_state$consents$preCo3;return state.consents.preConsent.value.enabled&&((_state$consents$preCo=state.consents.preConsent.value.events)===null||_state$consents$preCo===undefined?undefined:_state$consents$preCo.delivery)==='buffer'&&(((_state$consents$preCo2=state.consents.preConsent.value.storage)===null||_state$consents$preCo2===undefined?undefined:_state$consents$preCo2.strategy)==='session'||((_state$consents$preCo3=state.consents.preConsent.value.storage)===null||_state$consents$preCo3===undefined?undefined:_state$consents$preCo3.strategy)==='none');};
3881
3821
 
3822
+ var safelyInvokeCallback=function safelyInvokeCallback(callback,args,apiName,logger){if(!isDefined(callback)){return;}if(isFunction(callback)){try{callback.apply(void 0,_toConsumableArray(args));}catch(error){logger.error(CALLBACK_INVOKE_ERROR(apiName),error);}}else {logger.error(INVALID_CALLBACK_FN_ERROR(apiName));}};
3823
+
3882
3824
  /**
3883
3825
  * Event repository class responsible for queuing events for further processing and delivery
3884
3826
  */var EventRepository=/*#__PURE__*/function(){/**
@@ -3887,9 +3829,9 @@ var destinationsIntgConfig=state.nativeDestinations.integrationsConfig.value;var
3887
3829
  * @param storeManager Store Manager instance
3888
3830
  * @param errorHandler Error handler object
3889
3831
  * @param logger Logger object
3890
- */function EventRepository(pluginsManager,storeManager,errorHandler,logger){_classCallCheck(this,EventRepository);this.pluginsManager=pluginsManager;this.errorHandler=errorHandler;this.logger=logger;this.httpClient=new HttpClient(errorHandler,logger);this.storeManager=storeManager;this.onError=this.onError.bind(this);}/**
3832
+ */function EventRepository(pluginsManager,storeManager,httpClient,errorHandler,logger){_classCallCheck(this,EventRepository);this.pluginsManager=pluginsManager;this.errorHandler=errorHandler;this.httpClient=httpClient;this.logger=logger;this.storeManager=storeManager;}/**
3891
3833
  * Initializes the event repository
3892
- */return _createClass(EventRepository,[{key:"init",value:function init(){var _this=this;try{this.dataplaneEventsQueue=this.pluginsManager.invokeSingle("".concat(DATA_PLANE_QUEUE_EXT_POINT_PREFIX,".init"),state,this.httpClient,this.storeManager,this.errorHandler,this.logger);}catch(e){this.onError(e,DATAPLANE_PLUGIN_INITIALIZE_ERROR);}try{this.dmtEventsQueue=this.pluginsManager.invokeSingle("".concat(DMT_EXT_POINT_PREFIX,".init"),state,this.pluginsManager,this.httpClient,this.storeManager,this.errorHandler,this.logger);}catch(e){this.onError(e,DMT_PLUGIN_INITIALIZE_ERROR);}try{this.destinationsEventsQueue=this.pluginsManager.invokeSingle("".concat(DESTINATIONS_QUEUE_EXT_POINT_PREFIX,".init"),state,this.pluginsManager,this.storeManager,this.dmtEventsQueue,this.errorHandler,this.logger);}catch(e){this.onError(e,NATIVE_DEST_PLUGIN_INITIALIZE_ERROR);}// Start the queue once the client destinations are ready
3834
+ */return _createClass(EventRepository,[{key:"init",value:function init(){var _this=this;this.dataplaneEventsQueue=this.pluginsManager.invokeSingle("".concat(DATA_PLANE_QUEUE_EXT_POINT_PREFIX,".init"),state,this.httpClient,this.storeManager,this.errorHandler,this.logger);this.dmtEventsQueue=this.pluginsManager.invokeSingle("".concat(DMT_EXT_POINT_PREFIX,".init"),state,this.pluginsManager,this.httpClient,this.storeManager,this.errorHandler,this.logger);this.destinationsEventsQueue=this.pluginsManager.invokeSingle("".concat(DESTINATIONS_QUEUE_EXT_POINT_PREFIX,".init"),state,this.pluginsManager,this.storeManager,this.dmtEventsQueue,this.errorHandler,this.logger);// Start the queue once the client destinations are ready
3893
3835
  E(function(){if(state.nativeDestinations.clientDestinationsReady.value===true){var _this$destinationsEve,_this$dmtEventsQueue;(_this$destinationsEve=_this.destinationsEventsQueue)===null||_this$destinationsEve===undefined||_this$destinationsEve.start();(_this$dmtEventsQueue=_this.dmtEventsQueue)===null||_this$dmtEventsQueue===undefined||_this$dmtEventsQueue.start();}});var bufferEventsBeforeConsent=shouldBufferEventsForPreConsent(state);// Start the queue processing only when the destinations are ready or hybrid mode destinations exist
3894
3836
  // However, events will be enqueued for now.
3895
3837
  // At the time of processing the events, the integrations config data from destinations
@@ -3899,15 +3841,8 @@ if(state.loadOptions.value.bufferDataPlaneEventsUntilReady===true){timeoutId=glo
3899
3841
  * Enqueues the event for processing
3900
3842
  * @param event RudderEvent object
3901
3843
  * @param callback API callback function
3902
- */},{key:"enqueue",value:function enqueue(event,callback){var dpQEvent;try{dpQEvent=getFinalEvent(event,state);this.pluginsManager.invokeSingle("".concat(DATA_PLANE_QUEUE_EXT_POINT_PREFIX,".enqueue"),state,this.dataplaneEventsQueue,dpQEvent,this.errorHandler,this.logger);}catch(e){this.onError(e,DATAPLANE_PLUGIN_ENQUEUE_ERROR);}try{var dQEvent=clone(event);this.pluginsManager.invokeSingle("".concat(DESTINATIONS_QUEUE_EXT_POINT_PREFIX,".enqueue"),state,this.destinationsEventsQueue,dQEvent,this.errorHandler,this.logger);}catch(e){this.onError(e,NATIVE_DEST_PLUGIN_ENQUEUE_ERROR);}// Invoke the callback if it exists
3903
- try{// Using the event sent to the data plane queue here
3904
- // to ensure the mutated (if any) event is sent to the callback
3905
- callback===null||callback===void 0||callback(dpQEvent);}catch(error){this.onError(error,API_CALLBACK_INVOKE_ERROR);}}/**
3906
- * Handles error
3907
- * @param error The error object
3908
- * @param customMessage a message
3909
- * @param shouldAlwaysThrow if it should throw or use logger
3910
- */},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_REPOSITORY,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);}();
3844
+ */},{key:"enqueue",value:function enqueue(event,callback){var dpQEvent=getFinalEvent(event,state);this.pluginsManager.invokeSingle("".concat(DATA_PLANE_QUEUE_EXT_POINT_PREFIX,".enqueue"),state,this.dataplaneEventsQueue,dpQEvent,this.errorHandler,this.logger);var dQEvent=clone(event);this.pluginsManager.invokeSingle("".concat(DESTINATIONS_QUEUE_EXT_POINT_PREFIX,".enqueue"),state,this.destinationsEventsQueue,dQEvent,this.errorHandler,this.logger);// Invoke the callback if it exists
3845
+ var apiName="".concat(event.type.charAt(0).toUpperCase()).concat(event.type.slice(1)).concat(API_SUFFIX);safelyInvokeCallback(callback,[dpQEvent],apiName,this.logger);}}]);}();
3911
3846
 
3912
3847
  var dispatchSDKEvent=function dispatchSDKEvent(event){var customEvent=new CustomEvent(event,{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:true,cancelable:true,composed:true});globalThis.document.dispatchEvent(customEvent);};var isWriteKeyValid=function isWriteKeyValid(writeKey){return isString(writeKey)&&writeKey.trim().length>0;};var isDataPlaneUrlValid=function isDataPlaneUrlValid(dataPlaneUrl){return isValidURL(dataPlaneUrl);};
3913
3848
 
@@ -3915,11 +3850,11 @@ var dispatchSDKEvent=function dispatchSDKEvent(event){var customEvent=new Custom
3915
3850
  * Analytics class with lifecycle based on state ad user triggered events
3916
3851
  */var Analytics=/*#__PURE__*/function(){/**
3917
3852
  * Initialize services and components or use default ones if singletons
3918
- */function Analytics(){_classCallCheck(this,Analytics);this.preloadBuffer=new BufferQueue();this.initialized=false;this.errorHandler=defaultErrorHandler;this.logger=defaultLogger;this.externalSrcLoader=new ExternalSrcLoader(this.errorHandler,this.logger);this.capabilitiesManager=new CapabilitiesManager(this.errorHandler,this.logger);this.httpClient=defaultHttpClient;}/**
3853
+ */function Analytics(){_classCallCheck(this,Analytics);this.preloadBuffer=new BufferQueue();this.initialized=false;this.errorHandler=defaultErrorHandler;this.logger=defaultLogger;this.externalSrcLoader=new ExternalSrcLoader(this.errorHandler,this.logger);this.httpClient=defaultHttpClient;this.httpClient.init(this.errorHandler);this.capabilitiesManager=new CapabilitiesManager(this.httpClient,this.errorHandler,this.logger);}/**
3919
3854
  * Start application lifecycle if not already started
3920
- */return _createClass(Analytics,[{key:"load",value:function load(writeKey,dataPlaneUrl){var _this$logger,_state$loadOptions$va;var loadOptions=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};if(state.lifecycle.status.value){return;}if(!isWriteKeyValid(writeKey)){this.logger.error(WRITE_KEY_VALIDATION_ERROR(ANALYTICS_CORE,writeKey));return;}if(!isDataPlaneUrlValid(dataPlaneUrl)){this.logger.error(DATA_PLANE_URL_VALIDATION_ERROR(ANALYTICS_CORE,dataPlaneUrl));return;}// Set initial state values
3855
+ */return _createClass(Analytics,[{key:"load",value:function load(writeKey,dataPlaneUrl){var _state$loadOptions$va;var loadOptions=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};if(state.lifecycle.status.value){return;}if(!isWriteKeyValid(writeKey)){this.logger.error(WRITE_KEY_VALIDATION_ERROR(ANALYTICS_CORE,writeKey));return;}if(!isDataPlaneUrlValid(dataPlaneUrl)){this.logger.error(DATA_PLANE_URL_VALIDATION_ERROR(ANALYTICS_CORE,dataPlaneUrl));return;}// Set initial state values
3921
3856
  r(function(){state.lifecycle.writeKey.value=clone(writeKey);state.lifecycle.dataPlaneUrl.value=clone(dataPlaneUrl);state.loadOptions.value=normalizeLoadOptions(state.loadOptions.value,loadOptions);state.lifecycle.status.value='mounted';});// set log level as early as possible
3922
- (_this$logger=this.logger)===null||_this$logger===undefined||_this$logger.setMinLogLevel((_state$loadOptions$va=state.loadOptions.value.logLevel)!==null&&_state$loadOptions$va!==undefined?_state$loadOptions$va:POST_LOAD_LOG_LEVEL);// Expose state to global objects
3857
+ this.logger.setMinLogLevel((_state$loadOptions$va=state.loadOptions.value.logLevel)!==null&&_state$loadOptions$va!==undefined?_state$loadOptions$va:POST_LOAD_LOG_LEVEL);// Expose state to global objects
3923
3858
  setExposedGlobal('state',state,writeKey);// Configure initial config of any services or components here
3924
3859
  // State application lifecycle
3925
3860
  this.startLifecycle();}// Start lifecycle methods
@@ -3933,11 +3868,11 @@ if(state.consents.preConsent.value.enabled===true){state.lifecycle.status.value=
3933
3868
  * Enqueue in SDK preload buffer events, used from preloadBuffer component
3934
3869
  */},{key:"enqueuePreloadBufferEvents",value:function enqueuePreloadBufferEvents(bufferedEvents){var _this2=this;if(Array.isArray(bufferedEvents)){bufferedEvents.forEach(function(bufferedEvent){return _this2.preloadBuffer.enqueue(clone(bufferedEvent));});}}/**
3935
3870
  * Process the buffer preloaded events by passing their arguments to the respective facade methods
3936
- */},{key:"processDataInPreloadBuffer",value:function processDataInPreloadBuffer(){while(this.preloadBuffer.size()>0){var eventToProcess=this.preloadBuffer.dequeue();if(eventToProcess){consumePreloadBufferedEvent(_toConsumableArray(eventToProcess),this);}}}},{key:"prepareInternalServices",value:function prepareInternalServices(){this.pluginsManager=new PluginsManager(defaultPluginEngine,this.errorHandler,this.logger);this.storeManager=new StoreManager(this.pluginsManager,this.errorHandler,this.logger);this.configManager=new ConfigManager(this.httpClient,this.errorHandler,this.logger);this.userSessionManager=new UserSessionManager(this.errorHandler,this.logger,this.pluginsManager,this.storeManager,this.httpClient);this.eventRepository=new EventRepository(this.pluginsManager,this.storeManager,this.errorHandler,this.logger);this.eventManager=new EventManager(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger);}/**
3871
+ */},{key:"processDataInPreloadBuffer",value:function processDataInPreloadBuffer(){while(this.preloadBuffer.size()>0){var eventToProcess=this.preloadBuffer.dequeue();if(eventToProcess){consumePreloadBufferedEvent(_toConsumableArray(eventToProcess),this);}}}},{key:"prepareInternalServices",value:function prepareInternalServices(){this.pluginsManager=new PluginsManager(defaultPluginEngine,this.errorHandler,this.logger);this.storeManager=new StoreManager(this.pluginsManager,this.errorHandler,this.logger);this.configManager=new ConfigManager(this.httpClient,this.errorHandler,this.logger);this.userSessionManager=new UserSessionManager(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger);this.eventRepository=new EventRepository(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger);this.eventManager=new EventManager(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger);}/**
3937
3872
  * Load configuration
3938
3873
  */},{key:"loadConfig",value:function loadConfig(){var _this$configManager;if(state.lifecycle.writeKey.value){this.httpClient.setAuthHeader(state.lifecycle.writeKey.value);}(_this$configManager=this.configManager)===null||_this$configManager===undefined||_this$configManager.init();}/**
3939
3874
  * Initialize the storage and event queue
3940
- */},{key:"onPluginsReady",value:function onPluginsReady(){var _this$storeManager,_this$userSessionMana,_this$eventManager;this.errorHandler.init(this.httpClient,this.externalSrcLoader);// Initialize storage
3875
+ */},{key:"onPluginsReady",value:function onPluginsReady(){var _this$storeManager,_this$userSessionMana,_this$eventManager;// Initialize storage
3941
3876
  (_this$storeManager=this.storeManager)===null||_this$storeManager===undefined||_this$storeManager.init();(_this$userSessionMana=this.userSessionManager)===null||_this$userSessionMana===undefined||_this$userSessionMana.init();// Initialize the appropriate consent manager plugin
3942
3877
  if(state.consents.enabled.value&&!state.consents.initialized.value){var _this$pluginsManager;(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===undefined||_this$pluginsManager.invokeSingle("consentManager.init",state,this.logger);if(state.consents.preConsent.value.enabled===false){var _this$pluginsManager2;(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===undefined||_this$pluginsManager2.invokeSingle("consentManager.updateConsentsInfo",state,this.storeManager,this.logger);}}// Initialize event manager
3943
3878
  (_this$eventManager=this.eventManager)===null||_this$eventManager===undefined||_this$eventManager.init();// Mark the SDK as initialized
@@ -3948,15 +3883,15 @@ state.lifecycle.status.value='initialized';}/**
3948
3883
  }/**
3949
3884
  * Trigger onLoaded callback if any is provided in config & emit initialised event
3950
3885
  */},{key:"onInitialized",value:function onInitialized(){// Process any preloaded events
3951
- this.processDataInPreloadBuffer();// TODO: we need to avoid passing the window object to the callback function
3886
+ this.processDataInPreloadBuffer();// Execute onLoaded callback if provided in load options
3887
+ var onLoadedCallbackFn=state.loadOptions.value.onLoaded;// TODO: we need to avoid passing the window object to the callback function
3952
3888
  // as this will prevent us from supporting multiple SDK instances in the same page
3953
- // Execute onLoaded callback if provided in load options
3954
- if(isFunction(state.loadOptions.value.onLoaded)){state.loadOptions.value.onLoaded(globalThis.rudderanalytics);}// Set lifecycle state
3889
+ safelyInvokeCallback(onLoadedCallbackFn,[globalThis.rudderanalytics],LOAD_API,this.logger);// Set lifecycle state
3955
3890
  r(function(){state.lifecycle.loaded.value=true;state.lifecycle.status.value='loaded';});this.initialized=true;// Emit an event to use as substitute to the onLoaded callback
3956
3891
  dispatchSDKEvent('RSA_Initialised');}/**
3957
3892
  * Emit ready event
3958
3893
  */// eslint-disable-next-line class-methods-use-this
3959
- },{key:"onReady",value:function onReady(){var _this3=this;state.lifecycle.status.value='readyExecuted';state.eventBuffer.readyCallbacksArray.value.forEach(function(callback){try{callback();}catch(err){_this3.errorHandler.onError(err,ANALYTICS_CORE,READY_CALLBACK_INVOKE_ERROR);}});// Emit an event to use as substitute to the ready callback
3894
+ },{key:"onReady",value:function onReady(){var _this3=this;state.lifecycle.status.value='readyExecuted';state.eventBuffer.readyCallbacksArray.value.forEach(function(callback){safelyInvokeCallback(callback,[],READY_API,_this3.logger);});// Emit an event to use as substitute to the ready callback
3960
3895
  dispatchSDKEvent('RSA_Ready');}/**
3961
3896
  * Consume preloaded events buffer
3962
3897
  */},{key:"processBufferedEvents",value:function processBufferedEvents(){// This logic has been intentionally implemented without a simple
@@ -3975,11 +3910,11 @@ E(function(){var areAllDestinationsReady=totalDestinationsToLoad===0||state.nati
3975
3910
  // Mark the ready status if not already done
3976
3911
  if(state.lifecycle.status.value!=='ready'){state.lifecycle.status.value='ready';}}// End lifecycle methods
3977
3912
  // Start consumer exposed methods
3978
- },{key:"ready",value:function ready(callback){var type='ready';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,callback]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));if(!isFunction(callback)){this.logger.error(READY_API_CALLBACK_ERROR(READY_API));return;}/**
3913
+ },{key:"ready",value:function ready(callback){var type='ready';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,callback]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));if(!isFunction(callback)){this.logger.error(INVALID_CALLBACK_FN_ERROR(READY_API));return;}/**
3979
3914
  * If destinations are loaded or no integration is available for loading
3980
3915
  * execute the callback immediately else push the callbacks to a queue that
3981
3916
  * will be executed after loading completes
3982
- */if(state.lifecycle.status.value==='readyExecuted'){try{callback();}catch(err){this.errorHandler.onError(err,ANALYTICS_CORE,READY_CALLBACK_INVOKE_ERROR);}}else {state.eventBuffer.readyCallbacksArray.value=[].concat(_toConsumableArray(state.eventBuffer.readyCallbacksArray.value),[callback]);}}},{key:"page",value:function page(payload){var _this$eventManager2;var type='page';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;(_this$eventManager2=this.eventManager)===null||_this$eventManager2===undefined||_this$eventManager2.addEvent({type:'page',category:payload.category,name:payload.name,properties:payload.properties,options:payload.options,callback:payload.callback});// TODO: Maybe we should alter the behavior to send the ad-block page event even if the SDK is still loaded. It'll be pushed into the to be processed queue.
3917
+ */if(state.lifecycle.status.value==='readyExecuted'){safelyInvokeCallback(callback,[],READY_API,this.logger);}else {state.eventBuffer.readyCallbacksArray.value=[].concat(_toConsumableArray(state.eventBuffer.readyCallbacksArray.value),[callback]);}}},{key:"page",value:function page(payload){var _this$eventManager2;var type='page';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;(_this$eventManager2=this.eventManager)===null||_this$eventManager2===undefined||_this$eventManager2.addEvent({type:'page',category:payload.category,name:payload.name,properties:payload.properties,options:payload.options,callback:payload.callback});// TODO: Maybe we should alter the behavior to send the ad-block page event even if the SDK is still loaded. It'll be pushed into the to be processed queue.
3983
3918
  // Send automatic ad blocked page event if ad-blockers are detected on the page
3984
3919
  // Check page category to avoid infinite loop
3985
3920
  if(state.capabilities.isAdBlocked.value===true&&payload.category!==ADBLOCK_PAGE_CATEGORY){this.page(pageArgumentsToCallOptions(ADBLOCK_PAGE_CATEGORY,ADBLOCK_PAGE_NAME,{// 'title' is intentionally omitted as it does not make sense
@@ -4011,7 +3946,7 @@ function RudderAnalytics(){_classCallCheck(this,RudderAnalytics);// END-NO-SONAR
4011
3946
  _defineProperty(this,"analyticsInstances",{});_defineProperty(this,"defaultAnalyticsKey",'');_defineProperty(this,"logger",defaultLogger);try{if(RudderAnalytics.globalSingleton){// START-NO-SONAR-SCAN
4012
3947
  // eslint-disable-next-line no-constructor-return
4013
3948
  return RudderAnalytics.globalSingleton;// END-NO-SONAR-SCAN
4014
- }defaultErrorHandler.attachErrorListeners();this.setDefaultInstanceKey=this.setDefaultInstanceKey.bind(this);this.getAnalyticsInstance=this.getAnalyticsInstance.bind(this);this.load=this.load.bind(this);this.ready=this.ready.bind(this);this.triggerBufferedLoadEvent=this.triggerBufferedLoadEvent.bind(this);this.page=this.page.bind(this);this.track=this.track.bind(this);this.identify=this.identify.bind(this);this.alias=this.alias.bind(this);this.group=this.group.bind(this);this.reset=this.reset.bind(this);this.getAnonymousId=this.getAnonymousId.bind(this);this.setAnonymousId=this.setAnonymousId.bind(this);this.getUserId=this.getUserId.bind(this);this.getUserTraits=this.getUserTraits.bind(this);this.getGroupId=this.getGroupId.bind(this);this.getGroupTraits=this.getGroupTraits.bind(this);this.startSession=this.startSession.bind(this);this.endSession=this.endSession.bind(this);this.getSessionId=this.getSessionId.bind(this);this.setAuthToken=this.setAuthToken.bind(this);this.consent=this.consent.bind(this);RudderAnalytics.globalSingleton=this;state.autoTrack.pageLifecycle.visitId.value=generateUUID();state.autoTrack.pageLifecycle.pageLoadedTimestamp.value=Date.now();// start loading if a load event was buffered or wait for explicit load call
3949
+ }this.setDefaultInstanceKey=this.setDefaultInstanceKey.bind(this);this.getAnalyticsInstance=this.getAnalyticsInstance.bind(this);this.load=this.load.bind(this);this.ready=this.ready.bind(this);this.triggerBufferedLoadEvent=this.triggerBufferedLoadEvent.bind(this);this.page=this.page.bind(this);this.track=this.track.bind(this);this.identify=this.identify.bind(this);this.alias=this.alias.bind(this);this.group=this.group.bind(this);this.reset=this.reset.bind(this);this.getAnonymousId=this.getAnonymousId.bind(this);this.setAnonymousId=this.setAnonymousId.bind(this);this.getUserId=this.getUserId.bind(this);this.getUserTraits=this.getUserTraits.bind(this);this.getGroupId=this.getGroupId.bind(this);this.getGroupTraits=this.getGroupTraits.bind(this);this.startSession=this.startSession.bind(this);this.endSession=this.endSession.bind(this);this.getSessionId=this.getSessionId.bind(this);this.setAuthToken=this.setAuthToken.bind(this);this.consent=this.consent.bind(this);RudderAnalytics.globalSingleton=this;state.autoTrack.pageLifecycle.visitId.value=generateUUID();state.autoTrack.pageLifecycle.pageLoadedTimestamp.value=Date.now();// start loading if a load event was buffered or wait for explicit load call
4015
3950
  this.triggerBufferedLoadEvent();// Assign to global "rudderanalytics" object after processing the preload buffer (if any exists)
4016
3951
  // for CDN bundling IIFE exports covers this but for npm ESM and CJS bundling has to be done explicitly
4017
3952
  globalThis.rudderanalytics=this;}catch(error){dispatchErrorEvent(error);}}/**
@@ -4053,7 +3988,7 @@ state.autoTrack.enabled.value=autoTrackEnabled||pageLifecycleEnabled;if(!pageLif
4053
3988
  * @param events
4054
3989
  * @param useBeacon
4055
3990
  * @param options
4056
- */},{key:"setupPageUnloadTracking",value:function setupPageUnloadTracking(events,useBeacon,options){var _this=this;if(events.length===0||events.includes(PageLifecycleEvents.UNLOADED)){if(useBeacon===true){onPageLeave(function(isAccessible){if(isAccessible===false&&state.lifecycle.loaded.value){var pageUnloadedTimestamp=Date.now();var visitDuration=pageUnloadedTimestamp-state.autoTrack.pageLifecycle.pageLoadedTimestamp.value;_this.track(PageLifecycleEvents.UNLOADED,{visitDuration:visitDuration},_objectSpread2(_objectSpread2({},options),{},{originalTimestamp:getFormattedTimestamp(new Date(pageUnloadedTimestamp))}));}});}else {// throw warning if beacon is disabled
3991
+ */},{key:"setupPageUnloadTracking",value:function setupPageUnloadTracking(events,useBeacon,options){var _this=this;if(events.length===0||events.includes(PageLifecycleEvents.UNLOADED)){if(useBeacon===true){onPageLeave(function(isAccessible){if(isAccessible===false&&state.lifecycle.loaded.value){var pageUnloadedTimestamp=Date.now();var visitDuration=pageUnloadedTimestamp-state.autoTrack.pageLifecycle.pageLoadedTimestamp.value;_this.track(PageLifecycleEvents.UNLOADED,{visitDuration:visitDuration},_objectSpread2(_objectSpread2({},options),{},{originalTimestamp:getFormattedTimestamp(new Date(pageUnloadedTimestamp))}));}});}else {// log warning if beacon is disabled
4057
3992
  this.logger.warn(PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(RSA));}}}/**
4058
3993
  * Trigger load event in buffer queue if exists and stores the
4059
3994
  * remaining preloaded events array in global object