@rudderstack/analytics-js 3.34.2 → 3.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -843,7 +843,7 @@ Object.getOwnPropertyNames(err).forEach(function(key){if(key!=='message'&&key!==
843
843
  }}});return newError;}catch(_unused2){return new Error("".concat(issue,": ").concat(stringifyWithoutCircular(err)));}};var dispatchErrorEvent=function dispatchErrorEvent(error){if(isTypeOfError(error)){var errStack=getStacktrace(error);if(errStack){// eslint-disable-next-line no-param-reassign
844
844
  error.stack="".concat(errStack,"\n").concat(MANUAL_ERROR_IDENTIFIER);}}globalThis.dispatchEvent(new ErrorEvent('error',{error:error,bubbles:true,cancelable:true,composed:true}));};
845
845
 
846
- var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.34.2';var APP_NAMESPACE='com.rudderlabs.javascript';var MODULE_TYPE='npm';var BUILD_VARIANT='legacy-lite';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';
846
+ var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.35.0';var APP_NAMESPACE='com.rudderlabs.javascript';var MODULE_TYPE='npm';var BUILD_VARIANT='legacy-lite';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';
847
847
 
848
848
  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';
849
849
 
@@ -963,7 +963,7 @@ var SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','ses
963
963
 
964
964
  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
965
965
  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="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 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,response){return "".concat(prefix," with status ").concat(status," (").concat(statusText,") for URL: ").concat(url,". Response: ").concat(response.trim());};var XHR_REQUEST_ERROR=function XHR_REQUEST_ERROR(prefix,e,url){return "".concat(prefix," due to timeout or no connection (").concat(e?e.type:'',") at the client side 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_URL_INVALID_ERROR=function DATA_SERVER_URL_INVALID_ERROR(context,url){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The server side cookies functionality is disabled as the provided data server URL, \"").concat(url,"\" is invalid.");};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.";var COLLAPSED_COOKIE_BATCH_ERROR=function COLLAPSED_COOKIE_BATCH_ERROR(missingCookies,batchSize){return "The server did not set ".concat(missingCookies.length," of the ").concat(batchSize," cookies sent in one request: ").concat(missingCookies.join(', '),". A fallback to set them client side was attempted. Check that the data service and any proxy preserve every \"Set-Cookie\" header, and that the cookie domain and SameSite/Secure attributes are valid.");};// WARNING
966
- var STORAGE_TYPE_VALIDATION_WARNING=function STORAGE_TYPE_VALIDATION_WARNING(context,storageType){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 storage type will be used instead.");};var UNSUPPORTED_STORAGE_ENTRY_TYPE_WARNING=function UNSUPPORTED_STORAGE_ENTRY_TYPE_WARNING(context,entry,storageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(storageType,"\" configured for the entry \"").concat(entry,"\" is not supported. Please choose one of the following supported types: \"").concat(SUPPORTED_STORAGE_TYPES,"\". The default storage type 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_ERROR=function SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_ERROR(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 SERVER_SIDE_COOKIE_DATA_SERVICE_HOST_ERROR=function SERVER_SIDE_COOKIE_DATA_SERVICE_HOST_ERROR(context,dataServiceHost,webpageHost){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The data service host (").concat(dataServiceHost,") cannot set cookies for the current webpage (").concat(webpageHost,"). Hence, the cookies will be set client-side instead of server-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 RESERVED_CUSTOM_CONTEXT_KEY_WARNING=function RESERVED_CUSTOM_CONTEXT_KEY_WARNING(logContext,property){return "".concat(logContext).concat(LOG_CONTEXT_SEPARATOR,"The top-level custom context property \"").concat(property,"\" is reserved and was ignored.");};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 INVALID_CUSTOM_CONTEXT_WARNING=function INVALID_CUSTOM_CONTEXT_WARNING(logContext){return "".concat(logContext).concat(LOG_CONTEXT_SEPARATOR,"Invalid custom context. Use a plain object without prototype pollution keys.");};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 CUT_OFF_DURATION_NOT_NUMBER_WARNING=function CUT_OFF_DURATION_NOT_NUMBER_WARNING(context,cutOffDuration,defaultValue){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session cut off duration value \"").concat(cutOffDuration,"\" is not a number. The default cut off duration of ").concat(defaultValue," ms will be used instead.");};var CUT_OFF_DURATION_LESS_THAN_TIMEOUT_WARNING=function CUT_OFF_DURATION_LESS_THAN_TIMEOUT_WARNING(context,cutOffDuration,timeout){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session cut off duration value \"").concat(cutOffDuration,"\" ms is less than the session timeout value \"").concat(timeout,"\" ms. The cut off functionality will be disabled.");};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 DEPRECATED_PRE_CONSENT_STORAGE_STRATEGY=function DEPRECATED_PRE_CONSENT_STORAGE_STRATEGY(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent storage strategy option is deprecated. Please enable \"storage\" in the pre-consent options and use the \"storage\" load API option 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 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(', '),".");};var UNAVAILABLE_PLUGINS_ERROR=function UNAVAILABLE_PLUGINS_ERROR(context,unavailablePlugins){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to load the following unavailable local plugins: ").concat(unavailablePlugins.join(', '),". Some features of the SDK may not work as expected. Make sure you are using the correct SDK bundle variant.");};var CUSTOM_INTEGRATION_CANNOT_BE_ADDED_ERROR=function CUSTOM_INTEGRATION_CANNOT_BE_ADDED_ERROR(context,destinationId){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Cannot add custom integration for destination ID \"").concat(destinationId,"\" after the SDK is loaded.");};
966
+ var STORAGE_TYPE_VALIDATION_WARNING=function STORAGE_TYPE_VALIDATION_WARNING(context,storageType){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 storage type will be used instead.");};var UNSUPPORTED_STORAGE_ENTRY_TYPE_WARNING=function UNSUPPORTED_STORAGE_ENTRY_TYPE_WARNING(context,entry,storageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(storageType,"\" configured for the entry \"").concat(entry,"\" is not supported. Please choose one of the following supported types: \"").concat(SUPPORTED_STORAGE_TYPES,"\". The default storage type 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_ERROR=function SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_ERROR(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 SERVER_SIDE_COOKIE_DATA_SERVICE_HOST_ERROR=function SERVER_SIDE_COOKIE_DATA_SERVICE_HOST_ERROR(context,dataServiceHost,webpageHost){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The data service host (").concat(dataServiceHost,") cannot set cookies for the current webpage (").concat(webpageHost,"). Hence, the cookies will be set client-side instead of server-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 RESERVED_CUSTOM_CONTEXT_KEY_WARNING=function RESERVED_CUSTOM_CONTEXT_KEY_WARNING(logContext,property){return "".concat(logContext).concat(LOG_CONTEXT_SEPARATOR,"The top-level custom context property \"").concat(property,"\" is reserved and was ignored.");};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 INVALID_CUSTOM_CONTEXT_WARNING=function INVALID_CUSTOM_CONTEXT_WARNING(logContext){return "".concat(logContext).concat(LOG_CONTEXT_SEPARATOR,"Invalid custom context. Use a plain object without prototype pollution keys.");};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 CUT_OFF_DURATION_NOT_NUMBER_WARNING=function CUT_OFF_DURATION_NOT_NUMBER_WARNING(context,cutOffDuration,defaultValue){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session cut off duration value \"").concat(cutOffDuration,"\" is not a number. The default cut off duration of ").concat(defaultValue," ms will be used instead.");};var CUT_OFF_DURATION_LESS_THAN_TIMEOUT_WARNING=function CUT_OFF_DURATION_LESS_THAN_TIMEOUT_WARNING(context,cutOffDuration,timeout){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session cut off duration value \"").concat(cutOffDuration,"\" ms is less than the session timeout value \"").concat(timeout,"\" ms. The cut off functionality will be disabled.");};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 POLYFILL_VERIFICATION_ERROR=function POLYFILL_VERIFICATION_ERROR(missingFeatures){return "Failed to apply the polyfills for the following features: ".concat(missingFeatures.join(', '),".");};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 DEPRECATED_PRE_CONSENT_STORAGE_STRATEGY=function DEPRECATED_PRE_CONSENT_STORAGE_STRATEGY(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent storage strategy option is deprecated. Please enable \"storage\" in the pre-consent options and use the \"storage\" load API option 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 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(', '),".");};var REMOTE_PLUGIN_LOAD_ERROR=function REMOTE_PLUGIN_LOAD_ERROR(context,pluginName,reason){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to load plugin \"").concat(pluginName,"\" - ").concat(reason);};var NO_PLUGIN_FACTORY_EXPORTED_REASON='the module exported no plugin factory';var UNAVAILABLE_PLUGINS_ERROR=function UNAVAILABLE_PLUGINS_ERROR(context,unavailablePlugins){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to load the following unavailable local plugins: ").concat(unavailablePlugins.join(', '),". Some features of the SDK may not work as expected. Make sure you are using the correct SDK bundle variant.");};var CUSTOM_INTEGRATION_CANNOT_BE_ADDED_ERROR=function CUSTOM_INTEGRATION_CANNOT_BE_ADDED_ERROR(context,destinationId){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Cannot add custom integration for destination ID \"").concat(destinationId,"\" after the SDK is loaded.");};
967
967
 
968
968
  var DEFAULT_INTEGRATIONS_CONFIG={All:true};
969
969
 
@@ -978,7 +978,9 @@ var CDN_INT_DIR='js-integrations';var CDN_PLUGINS_DIR='plugins';var URL_PATTERN=
978
978
  '(\\#[-a-zA-Z\\d_]*)?$')// fragment locator
979
979
  ;
980
980
 
981
- var BUILD_TYPE='legacy';var SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';var CDN_ARCH_VERSION_DIR='v3';var DEFAULT_INTEGRATION_SDKS_URL="".concat(SDK_CDN_BASE_URL,"/").concat(CDN_ARCH_VERSION_DIR,"/").concat(BUILD_TYPE,"/").concat(CDN_INT_DIR);var DEFAULT_PLUGINS_URL="".concat(SDK_CDN_BASE_URL,"/").concat(CDN_ARCH_VERSION_DIR,"/").concat(BUILD_TYPE,"/").concat(CDN_PLUGINS_DIR);var DEFAULT_CONFIG_BE_URL='https://api.rudderstack.com';
981
+ var BUILD_TYPE='legacy';var SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';var CDN_ARCH_VERSION_DIR='v3';var DEFAULT_INTEGRATION_SDKS_URL="".concat(SDK_CDN_BASE_URL,"/").concat(CDN_ARCH_VERSION_DIR,"/").concat(BUILD_TYPE,"/").concat(CDN_INT_DIR);var DEFAULT_PLUGINS_URL="".concat(SDK_CDN_BASE_URL,"/").concat(CDN_ARCH_VERSION_DIR,"/").concat(BUILD_TYPE,"/").concat(CDN_PLUGINS_DIR);var DEFAULT_CONFIG_BE_URL='https://api.rudderstack.com';// Mirrors remotePluginsExportsFilename in rollup.config.mjs, which builds the URL
982
+ // the generated federation code requests at runtime.
983
+ var REMOTE_PLUGINS_ENTRY_FILE='rsa-plugins.js';
982
984
 
983
985
  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';var CUSTOM_DEVICE_MODE_DESTINATION_DISPLAY_NAME='Custom Device Mode';
984
986
 
@@ -989,7 +991,7 @@ anonymousId:false,initialReferrer:false,initialReferringDomain:false}});var SERV
989
991
 
990
992
  var sessionState={userId:y(DEFAULT_USER_SESSION_VALUES.userId),userTraits:y(DEFAULT_USER_SESSION_VALUES.userTraits),anonymousId:y(DEFAULT_USER_SESSION_VALUES.anonymousId),groupId:y(DEFAULT_USER_SESSION_VALUES.groupId),groupTraits:y(DEFAULT_USER_SESSION_VALUES.groupTraits),initialReferrer:y(DEFAULT_USER_SESSION_VALUES.initialReferrer),initialReferringDomain:y(DEFAULT_USER_SESSION_VALUES.initialReferringDomain),sessionInfo:y(DEFAULT_USER_SESSION_VALUES.sessionInfo),authToken:y(DEFAULT_USER_SESSION_VALUES.authToken)};
991
993
 
992
- var capabilitiesState={isOnline:y(true),storage:{isLocalStorageAvailable:y(false),isCookieStorageAvailable:y(false),isSessionStorageAvailable:y(false)},isBeaconAvailable:y(false),isLegacyDOM:y(false),isUaCHAvailable:y(false),isCryptoAvailable:y(false),isAdBlockerDetectionInProgress:y(false),isAdBlocked:y(undefined),cspBlockedURLs:y([])};
994
+ var capabilitiesState={isOnline:y(true),storage:{isLocalStorageAvailable:y(false),isCookieStorageAvailable:y(false),isSessionStorageAvailable:y(false)},isBeaconAvailable:y(false),isLegacyDOM:y(false),isUaCHAvailable:y(false),isCryptoAvailable:y(false),isAdBlockerDetectionInProgress:y(false),isAdBlocked:y(undefined),cspViolations:y([]),sdkCdnProbe:y({})};
993
995
 
994
996
  var reportingState={isErrorReportingEnabled:y(false),isMetricsReportingEnabled:y(false),breadcrumbs:y([])};
995
997
 
@@ -1023,7 +1025,9 @@ var autoTrackState={enabled:y(false),pageLifecycle:{enabled:y(false),pageViewId:
1023
1025
 
1024
1026
  var defaultStateValues={capabilities:capabilitiesState,consents:consentsState,context:contextState,customContext:customContextState,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));
1025
1027
 
1026
- var CHROME_STACK_LINE_RE=/^\s*at /;var SAFARI_NATIVE_RE=/^(eval@)?(\[native code])?$/;var LOCATION_RE=/(.+?)(?::(\d+))?(?::(\d+))?$/;function extractLocation(urlLike){if(!(urlLike!==null&&urlLike!==void 0&&urlLike.includes(':'))){return [urlLike||undefined,undefined,undefined];}var normalizedUrlLike=urlLike.startsWith('(')&&urlLike.endsWith(')')?urlLike.slice(1,-1):urlLike;var parts=LOCATION_RE.exec(normalizedUrlLike);if(!parts){return [undefined,undefined,undefined];}return [parts[1]||undefined,parts[2]===undefined?undefined:Number(parts[2]),parts[3]===undefined?undefined:Number(parts[3])];}function parseV8Line(line){if(!CHROME_STACK_LINE_RE.test(line)){return null;}if(line.includes('(eval ')){line=line.replaceAll('eval code','eval').replaceAll(/(\(eval at [^()]*)|(,.*$)/g,'');}var sanitized=line.replace(/^\s+/,'').replaceAll('(eval code','(').replace(/^.*?\s+/,'');var parenLoc=/ (\(.+\)$)/.exec(sanitized);var withoutLoc=parenLoc?sanitized.replace(parenLoc[0],''):sanitized;var _extractLocation=extractLocation(parenLoc?parenLoc[1]:sanitized),_extractLocation2=_slicedToArray(_extractLocation,3),rawFile=_extractLocation2[0],lineNumber=_extractLocation2[1],columnNumber=_extractLocation2[2];var functionName=parenLoc&&withoutLoc||undefined;var fileName=rawFile==='eval'||rawFile==='<anonymous>'?undefined:rawFile;return {functionName:functionName,fileName:fileName,lineNumber:lineNumber,columnNumber:columnNumber};}function parseFFSafariLine(line){if(SAFARI_NATIVE_RE.test(line)){return null;}if(line.includes(' > eval')){line=line.replaceAll(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,':$1');}if(!line.includes('@')&&!line.includes(':')){return {functionName:line,fileName:undefined,lineNumber:undefined,columnNumber:undefined};}var atIndex=line.lastIndexOf('@');var functionName=atIndex>0?line.slice(0,atIndex):undefined;var _extractLocation3=extractLocation(line.slice(atIndex+1)),_extractLocation4=_slicedToArray(_extractLocation3,3),fileName=_extractLocation4[0],lineNumber=_extractLocation4[1],columnNumber=_extractLocation4[2];return {functionName:functionName,fileName:fileName,lineNumber:lineNumber,columnNumber:columnNumber};}/**
1028
+ var CHROME_STACK_LINE_RE=/^\s*at /;var SAFARI_NATIVE_RE=/^(eval@)?(\[native code])?$/;var DIGITS_RE=/^\d+$/;function extractLocation(urlLike){if(!(urlLike!==null&&urlLike!==void 0&&urlLike.includes(':'))){return [urlLike||undefined,undefined,undefined];}var normalizedUrlLike=urlLike.startsWith('(')&&urlLike.endsWith(')')?urlLike.slice(1,-1):urlLike;// Take up to two trailing all-digit segments as line and column; whatever is left,
1029
+ // colons included, is the file. A url keeps its scheme because "//host" is not digits.
1030
+ var segments=normalizedUrlLike.split(':');var location=[];while(segments.length>1&&location.length<2&&DIGITS_RE.test(segments[segments.length-1])){location.unshift(Number(segments.pop()));}return [segments.join(':')||undefined,location[0],location[1]];}function parseV8Line(line){if(!CHROME_STACK_LINE_RE.test(line)){return null;}if(line.includes('(eval ')){line=line.replace(/eval code/g,'eval').replace(/\(eval at [^()]*/g,'').replace(/,.*/,'');}var sanitized=line.replace(/^\s+/,'').replace(/\(eval code/g,'(').replace(/^.*?\s+/,'');var parenLoc=/ (\(.+\)$)/.exec(sanitized);var withoutLoc=parenLoc?sanitized.replace(parenLoc[0],''):sanitized;var _extractLocation=extractLocation(parenLoc?parenLoc[1]:sanitized),_extractLocation2=_slicedToArray(_extractLocation,3),rawFile=_extractLocation2[0],lineNumber=_extractLocation2[1],columnNumber=_extractLocation2[2];var functionName=parenLoc&&withoutLoc||undefined;var fileName=rawFile==='eval'||rawFile==='<anonymous>'?undefined:rawFile;return {functionName:functionName,fileName:fileName,lineNumber:lineNumber,columnNumber:columnNumber};}function parseFFSafariLine(line){if(SAFARI_NATIVE_RE.test(line)){return null;}if(line.includes(' > eval')){line=line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,':$1');}if(!line.includes('@')&&!line.includes(':')){return {functionName:line,fileName:undefined,lineNumber:undefined,columnNumber:undefined};}var atIndex=line.lastIndexOf('@');var functionName=atIndex>0?line.slice(0,atIndex):undefined;var _extractLocation3=extractLocation(line.slice(atIndex+1)),_extractLocation4=_slicedToArray(_extractLocation3,3),fileName=_extractLocation4[0],lineNumber=_extractLocation4[1],columnNumber=_extractLocation4[2];return {functionName:functionName,fileName:fileName,lineNumber:lineNumber,columnNumber:columnNumber};}/**
1027
1031
  * Parses an Error object's stack trace into structured frames.
1028
1032
  * Supports V8/Chromium (Chrome, Edge, Node) and SpiderMonkey/WebKit (Firefox, Safari) formats.
1029
1033
  * Throws if the error has no stack property.
@@ -1039,7 +1043,9 @@ try{if(JSON.stringify(f)==='{}')return accum;return accum.concat(f);}catch(_unus
1039
1043
  * Utility to parse XHR JSON response
1040
1044
  */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;};
1041
1045
 
1042
- 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=[/Unable 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\./];var SCRIPT_LOAD_FAILURE_MESSAGES=[].concat(PLUGINS_LOAD_FAILURE_MESSAGES,INTEGRATIONS_LOAD_FAILURE_MESSAGES);var INTEGRATIONS_ERROR_CATEGORY='integrations';var SDK_ERROR_CATEGORY='sdk';var DEFAULT_ERROR_CATEGORY=SDK_ERROR_CATEGORY;
1046
+ var FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';var PLUGINS_LOAD_FAILURE_MESSAGES=[// Chromium
1047
+ /Failed to fetch dynamically imported module: .*/,// Firefox
1048
+ /error loading dynamically imported module: .*/];var INTEGRATIONS_LOAD_FAILURE_MESSAGES=[/Unable 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\./];var SCRIPT_LOAD_FAILURE_MESSAGES=[].concat(PLUGINS_LOAD_FAILURE_MESSAGES,INTEGRATIONS_LOAD_FAILURE_MESSAGES);var INTEGRATIONS_ERROR_CATEGORY='integrations';var SDK_ERROR_CATEGORY='sdk';var DEFAULT_ERROR_CATEGORY=SDK_ERROR_CATEGORY;
1043
1049
 
1044
1050
  var DEFAULT_XHR_REQUEST_OPTIONS={headers:{Accept:'application/json','Content-Type':'application/json;charset=UTF-8'},method:'GET'};/**
1045
1051
  * Utility to create request configuration based on default options
@@ -1057,14 +1063,14 @@ xhr.timeout=timeout;Object.keys(options.headers).forEach(function(headerName){if
1057
1063
  * Service to handle data communication with APIs
1058
1064
  */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;}/**
1059
1065
  * Implement requests in a blocking way
1060
- */},{key:"getData",value:(function(){var _getData=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(config){var url,options,timeout,isRawResponse,data,_t;return _regenerator().w(function(_context){while(1)switch(_context.p=_context.n){case 0:url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;_context.p=1;_context.n=2;return xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout,this.logger);case 2:data=_context.v;return _context.a(2,{data:isRawResponse?data.response:responseTextToJson(data.response,this.onError),details:data});case 3:_context.p=3;_t=_context.v;return _context.a(2,{data:undefined,details:_t});}},_callee,this,[[1,3]]);}));function getData(_x){return _getData.apply(this,arguments);}return getData;}()/**
1066
+ */},{key:"getData",value:(function(){var _getData=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(config){var url,options,timeout,isRawResponse,skipAuthHeader,data,_t;return _regenerator().w(function(_context){while(1)switch(_context.p=_context.n){case 0:url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse,skipAuthHeader=config.skipAuthHeader;_context.p=1;_context.n=2;return xhrRequest(createXhrRequestOptions(url,options,this.getAuthHeader(skipAuthHeader)),timeout,this.logger);case 2:data=_context.v;return _context.a(2,{data:isRawResponse?data.response:responseTextToJson(data.response,this.onError),details:data});case 3:_context.p=3;_t=_context.v;return _context.a(2,{data:undefined,details:_t});}},_callee,this,[[1,3]]);}));function getData(_x){return _getData.apply(this,arguments);}return getData;}()/**
1061
1067
  * Implement requests in a non-blocking way
1062
- */)},{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);}},function(data){if(!isFireAndForget){callback(undefined,data);}})// Exceptions thrown by the callback must never re-enter it
1068
+ */)},{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,skipAuthHeader=config.skipAuthHeader;var isFireAndForget=!isFunction(callback);xhrRequest(createXhrRequestOptions(url,options,this.getAuthHeader(skipAuthHeader)),timeout,this.logger).then(function(data){if(!isFireAndForget){callback(isRawResponse?data.response:responseTextToJson(data.response,_this.onError),data);}},function(data){if(!isFireAndForget){callback(undefined,data);}})// Exceptions thrown by the callback must never re-enter it
1063
1069
  .catch(this.onError);}/**
1064
1070
  * Handle errors
1065
1071
  */},{key:"onError",value:function onError(error,groupingHash){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError({error:error,context:HTTP_CLIENT,groupingHash:groupingHash});}/**
1066
1072
  * Set basic authentication header (eg writekey)
1067
- */},{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);}/**
1073
+ */},{key:"getAuthHeader",value:function getAuthHeader(skipAuthHeader){return skipAuthHeader===true?undefined:this.basicAuthHeader;}},{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);}/**
1068
1074
  * Clear basic authentication header
1069
1075
  */},{key:"resetAuthHeader",value:function resetAuthHeader(){this.basicAuthHeader=undefined;}}]);}();var defaultHttpClient=new HttpClient(defaultLogger);
1070
1076
 
@@ -1079,52 +1085,75 @@ var APP_STATE_EXCLUDE_KEYS=['userId','userTraits','groupId','groupTraits','anony
1079
1085
  'customContext',// customer-provided event context
1080
1086
  'traits','authToken'];var NOTIFIER_NAME='RudderStack JavaScript SDK';var SDK_GITHUB_URL='git+https://github.com/rudderlabs/rudder-sdk-js.git';var SOURCE_NAME='js';
1081
1087
 
1082
- var detectAdBlockers=function detectAdBlockers(httpClient){state.capabilities.isAdBlockerDetectionInProgress.value=true;try{// Apparently, '?view=ad' is a query param that is blocked by majority of adblockers
1083
- // Use source config URL here as it is very unlikely to be blocked by adblockers
1084
- // Only the extra query param should make it vulnerable to adblockers
1085
- // This will work even if the users proxies it.
1086
- // The edge case where this doesn't work is when HEAD method is not allowed by the server (user's)
1087
- 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
1088
- method:'HEAD',headers:{'Content-Type':undefined}},isRawResponse:true,callback:function callback(result,details){var _details$xhr;state.capabilities.isAdBlockerDetectionInProgress.value=false;// not ad blocked if the request is successful or it is not internally redirected on the client side
1089
- // Often adblockers instead of blocking the request, they redirect it to an internal URL
1090
- state.capabilities.isAdBlocked.value=(details===null||details===void 0?void 0:details.error)!==undefined||(details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.responseURL)!==url;}});}catch(err){// Reset the flag to prevent blocking future detection attempts
1091
- state.capabilities.isAdBlockerDetectionInProgress.value=false;// Re-throw the error to be handled by the caller
1092
- throw err;}};
1093
-
1094
1088
  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:{}};};/**
1095
1089
  * A function to get the Bugsnag release stage for the current environment
1096
1090
  * @param getHostName Optional function to get the hostname (primarily for testing)
1097
1091
  * @returns 'development' if the host is empty (for file:// protocol etc.) or a dev host (localhost, 127.0.0.1, etc.), otherwise ''production'' (it'll be replaced with the actual release stage during the build)
1098
- */var getReleaseStage=function getReleaseStage(){var getHostName=arguments.length>0&&arguments[0]!==undefined?arguments[0]:function(){return window.location.hostname;};var host=getHostName();return !host||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===void 0?void 0:_source$value.id)!==null&&_source$value$id!==void 0?_source$value$id:lifecycle.writeKey.value,"..").concat((_session$sessionInfo$=session.sessionInfo.value.id)!==null&&_session$sessionInfo$!==void 0?_session$sessionInfo$:'NA',"..").concat((_autoTrack$pageLifecy=autoTrack.pageLifecycle.pageViewId.value)!==null&&_autoTrack$pageLifecy!==void 0?_autoTrack$pageLifecy:'NA'),name:(_source$value$name=(_source$value2=source.value)===null||_source$value2===void 0?void 0:_source$value2.name)!==null&&_source$value$name!==void 0?_source$value$name:'NA'};};var getDeviceDetails=function getDeviceDetails(locale,userAgent){var _locale$value,_userAgent$value;return {locale:(_locale$value=locale.value)!==null&&_locale$value!==void 0?_locale$value:'NA',userAgent:(_userAgent$value=userAgent.value)!==null&&_userAgent$value!==void 0?_userAgent$value:'NA',time:new Date()};};var getBugsnagErrorEvent=function getBugsnagErrorEvent(exception,errorState,state,groupingHash){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,groupingHash:groupingHash,metaData:_objectSpread2({app:{snippetVersion:library.value.snippetVersion},device:_objectSpread2(_objectSpread2({},screen.value),{},{timezone:timezone.value})},getAppStateForMetadata(state)),user:getUserDetails(source,session,lifecycle,autoTrack)}]};};/**
1099
- * A function to check if adblockers are active. The promise's resolve function
1100
- * is invoked with true if adblockers are not detected and false otherwise.
1101
- * @param {ApplicationState} state The application state
1102
- * @param {IHttpClient} httpClient The HTTP client instance
1103
- * @param {Function} resolve The promise's resolve function
1104
- */var checkIfAdBlockersAreActive=function checkIfAdBlockersAreActive(state,httpClient,resolve){// Initiate ad blocker detection if not done previously and not already in progress.
1105
- if(isUndefined(state.capabilities.isAdBlocked.value)){if(state.capabilities.isAdBlockerDetectionInProgress.value===false){detectAdBlockers(httpClient);}// Wait for the detection to complete.
1106
- var detectionDisposer=j(function(){if(isDefined(state.capabilities.isAdBlocked.value)){// If ad blocker is not detected, notify.
1107
- resolve(state.capabilities.isAdBlocked.value===false);// Cleanup the effect.
1108
- detectionDisposer();}});}else {// If ad blocker is not detected, notify.
1109
- resolve(state.capabilities.isAdBlocked.value===false);}};/**
1092
+ */var getReleaseStage=function getReleaseStage(){var getHostName=arguments.length>0&&arguments[0]!==undefined?arguments[0]:function(){return window.location.hostname;};var host=getHostName();return !host||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===void 0?void 0:_source$value.id)!==null&&_source$value$id!==void 0?_source$value$id:lifecycle.writeKey.value,"..").concat((_session$sessionInfo$=session.sessionInfo.value.id)!==null&&_session$sessionInfo$!==void 0?_session$sessionInfo$:'NA',"..").concat((_autoTrack$pageLifecy=autoTrack.pageLifecycle.pageViewId.value)!==null&&_autoTrack$pageLifecy!==void 0?_autoTrack$pageLifecy:'NA'),name:(_source$value$name=(_source$value2=source.value)===null||_source$value2===void 0?void 0:_source$value2.name)!==null&&_source$value$name!==void 0?_source$value$name:'NA'};};var getDeviceDetails=function getDeviceDetails(locale,userAgent){var _locale$value,_userAgent$value;return {locale:(_locale$value=locale.value)!==null&&_locale$value!==void 0?_locale$value:'NA',userAgent:(_userAgent$value=userAgent.value)!==null&&_userAgent$value!==void 0?_userAgent$value:'NA',time:new Date()};};var getBugsnagErrorEvent=function getBugsnagErrorEvent(exception,errorState,state,groupingHash){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,groupingHash:groupingHash,metaData:_objectSpread2({app:{snippetVersion:library.value.snippetVersion},device:_objectSpread2(_objectSpread2({},screen.value),{},{timezone:timezone.value})},getAppStateForMetadata(state)),user:getUserDetails(source,session,lifecycle,autoTrack)}]};};// A violation only speaks for the kind of load the directive governs. default-src
1093
+ // is the fallback for both, so it counts for either.
1094
+ var SCRIPT_CSP_DIRECTIVES=['script-src-elem','script-src','default-src'];var CONNECT_CSP_DIRECTIVES=['connect-src','default-src'];var hasCspViolation=function hasCspViolation(state,url,directives){return state.capabilities.cspViolations.value.some(function(violation){return directives.includes(violation.directive)&&isSameOrUnder(url,violation.blockedURL);});};/**
1095
+ * Whether a URL is the blocked one or sits beneath it.
1096
+ *
1097
+ * Browsers strip a cross-origin blockedURI down to its origin, so a stored entry
1098
+ * is often a prefix of the failing URL rather than equal to it. Matching on a
1099
+ * bare string prefix is too loose: an origin entry would swallow a look-alike
1100
+ * host, and a script entry would swallow its own source map. The prefix only
1101
+ * counts when the next character starts a new path, query or fragment.
1102
+ */var isSameOrUnder=function isSameOrUnder(url,blockedURL){if(url===blockedURL){return true;}if(!url.startsWith(blockedURL)){return false;}var boundary=url.charAt(blockedURL.length);return boundary==='/'||boundary==='?'||boundary==='#';};// Probes already in flight, keyed by URL. Concurrent failures share one request
1103
+ // rather than each firing its own HEAD and possibly reaching different verdicts
1104
+ // about the same URL.
1105
+ var inFlightProbes=new Map();/**
1106
+ * Probes the URL that failed to load and records what came back, so the report
1107
+ * can tell a request that never left the client from one the CDN answered with
1108
+ * an error. The failed URL is probed rather than a fixed path: plugins and
1109
+ * integrations sit under different prefixes and can be blocked independently.
1110
+ */var probeSdkCdn=function probeSdkCdn(state,httpClient,url,done){if(isDefined(state.capabilities.sdkCdnProbe.value[url])){done();return;}var waiting=inFlightProbes.get(url);if(waiting){waiting.push(done);return;}inFlightProbes.set(url,[done]);httpClient.getAsyncData({url:url,// The CDN refuses preflight, so this has to stay a simple request: a HEAD
1111
+ // carrying none of the headers the client would otherwise add.
1112
+ skipAuthHeader:true,options:{method:'HEAD',headers:{'Content-Type':undefined,Accept:undefined}},isRawResponse:true,callback:function callback(_result,details){var _details$xhr$status,_details$xhr,_details$xhr2,_inFlightProbes$get;// A request that never reached the CDN reports status 0. A blocker that
1113
+ // answers instead of dropping it lands on a URL outside the CDN. An
1114
+ // ordinary redirect that stays under the CDN -- canonicalisation, a signed
1115
+ // URL -- is the CDN answering and must not be mistaken for one.
1116
+ var status=(_details$xhr$status=details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.status)!==null&&_details$xhr$status!==void 0?_details$xhr$status:0;var responseURL=details===null||details===void 0||(_details$xhr2=details.xhr)===null||_details$xhr2===void 0?void 0:_details$xhr2.responseURL;state.capabilities.sdkCdnProbe.value=_objectSpread2(_objectSpread2({},state.capabilities.sdkCdnProbe.value),{},_defineProperty({},url,{status:status,timedOut:(details===null||details===void 0?void 0:details.timedOut)===true,redirectedOffCdn:status!==0&&isString(responseURL)&&responseURL!==url&&!isSameOrUnder(responseURL,SDK_CDN_BASE_URL)}));var waiters=(_inFlightProbes$get=inFlightProbes.get(url))!==null&&_inFlightProbes$get!==void 0?_inFlightProbes$get:[];inFlightProbes.delete(url);waiters.forEach(function(waiter){return waiter();});}});};/**
1110
1117
  * A function to determine whether the error should be promoted to notify or not.
1111
- * For plugin and integration errors from RS CDN, if it is due to CSP blocked URLs or AdBlockers,
1112
- * it will not be promoted to notify.
1113
- * If it is due to other reasons, it will be promoted to notify.
1118
+ * Script load failures from a host other than the RS CDN are not promoted.
1119
+ * For those from the RS CDN, a probe of the failed URL is awaited so its result
1120
+ * is carried in the report, and the error is suppressed in exactly two cases: a
1121
+ * CSP violation covering that URL, or a probe whose shape nothing server side
1122
+ * produces -- a request that never reached the CDN, or one answered by
1123
+ * something else. Any status the CDN itself returned is promoted.
1124
+ * The generic ad blocker signal is deliberately not consulted: it probes the
1125
+ * source config host, and a client that cannot reach the CDN cannot be told
1126
+ * apart from a CDN outage.
1127
+ * Errors from other causes are promoted unless explicitly denylisted.
1114
1128
  * @param {Error} exception The error object
1115
1129
  * @param {ApplicationState} state The application state
1116
1130
  * @param {IHttpClient} httpClient The HTTP client instance
1117
1131
  * @returns A promise that resolves to a boolean indicating whether the error should be promoted to notify or not
1118
1132
  */var checkIfAllowedToBeNotified=function checkIfAllowedToBeNotified(exception,state,httpClient){var errMsg=exception.message;return new Promise(function(resolve){// Filter out script load failures that are not from the RS CDN.
1119
- if(SCRIPT_LOAD_FAILURE_MESSAGES.some(function(regex){return regex.test(errMsg);})){var _exec;var extractedURL=(_exec=/https?:\/\/[^\s"'(),;<>[\]{}]+/.exec(errMsg))===null||_exec===void 0?void 0:_exec[0];if(isString(extractedURL)){if(extractedURL.startsWith(SDK_CDN_BASE_URL)){// Filter out errors that are from CSP blocked URLs.
1120
- if(state.capabilities.cspBlockedURLs.value.includes(extractedURL)){resolve(false);}else {// Filter out errors if adblockers are detected.
1121
- checkIfAdBlockersAreActive(state,httpClient,resolve);}}else {// Filter out errors that are not from the RS CDN.
1133
+ if(SCRIPT_LOAD_FAILURE_MESSAGES.some(function(regex){return regex.test(errMsg);})){var _exec;var extractedURL=(_exec=/https?:\/\/[^\s"'(),;<>[\]{}]+/.exec(errMsg))===null||_exec===void 0?void 0:_exec[0];if(isString(extractedURL)){if(isSameOrUnder(extractedURL,SDK_CDN_BASE_URL)){// Wait for the CDN reachability probe so its result is carried in the
1134
+ // report. The generic ad blocker signal is deliberately not consulted:
1135
+ // it probes the source config host rather than the CDN, and a client
1136
+ // that cannot reach the CDN is indistinguishable from a CDN outage, so
1137
+ // it must not suppress the error.
1138
+ probeSdkCdn(state,httpClient,extractedURL,function(){// Only a script directive can explain a failed script load.
1139
+ var isCspBlocked=hasCspViolation(state,extractedURL,SCRIPT_CSP_DIRECTIVES);// A probe that never reached the CDN, or that was answered by
1140
+ // something else, is a client-side failure: nothing server side
1141
+ // produces either shape. A timeout is not attributable, and any
1142
+ // status the CDN itself returned is worth reporting.
1143
+ var probe=state.capabilities.sdkCdnProbe.value[extractedURL];// Unless CSP stopped the probe itself. connect-src governs the probe
1144
+ // while script-src governs the import, and a page can allow the
1145
+ // import and deny the probe -- then status 0 says nothing about the
1146
+ // load that actually failed, so the probe is inconclusive and the
1147
+ // error stands on its own.
1148
+ var isProbeCspBlocked=hasCspViolation(state,extractedURL,CONNECT_CSP_DIRECTIVES);var isClientSideFailure=probe!==undefined&&!probe.timedOut&&!isProbeCspBlocked&&(probe.status===0||probe.redirectedOffCdn);resolve(!isCspBlocked&&!isClientSideFailure);});}else {// Filter out errors that are not from the RS CDN.
1122
1149
  resolve(false);}}else {// Allow the error to be notified if no URL could be extracted from the error message
1123
1150
  resolve(true);}}else {resolve(!ERROR_MESSAGES_TO_BE_FILTERED.some(function(e){return e.test(errMsg);}));}});};/**
1124
1151
  * A function to get the directory name from a file path.
1125
1152
  * @param {string} filePath The file path
1126
1153
  * @returns The directory name or undefined if the file path is invalid
1127
- */var getDirectoryName=function getDirectoryName(filePath){if(!filePath){return undefined;}var paths=filePath.split('/');return paths.at(-2);};/**
1154
+ */var getDirectoryName=function getDirectoryName(filePath){if(!filePath){return undefined;}var paths=filePath.split('/');// Not `.at(-2)`: Array.prototype.at is neither transpiled nor polyfilled
1155
+ return paths[paths.length-2];// NOSONAR
1156
+ };/**
1128
1157
  * A function to get the top stack path from the exception.
1129
1158
  * @param {Exception} exception The exception object
1130
1159
  * @returns The top stack path or undefined if the exception is invalid
@@ -1151,9 +1180,11 @@ function ErrorHandler(httpClient,logger){_classCallCheck(this,ErrorHandler);_def
1151
1180
  * This method should be called once after construction.
1152
1181
  */return _createClass(ErrorHandler,[{key:"init",value:function init(){if(this.initialized){return;}this.attachErrorListeners();this.initialized=true;}/**
1153
1182
  * Attach error listeners to the global window object
1154
- */},{key:"attachErrorListeners",value:function attachErrorListeners(){var _this=this;globalThis.addEventListener('error',function(event){_this.onError({error:event,context:ERROR_HANDLER,errorType:ErrorType.UNHANDLEDEXCEPTION});});globalThis.addEventListener('unhandledrejection',function(event){_this.onError({error:event,context:ERROR_HANDLER,errorType:ErrorType.UNHANDLEDREJECTION});});// Listen to CSP violations and add the blocked URL to the state
1155
- // if those URLs are from RS CDN.
1156
- document.addEventListener('securitypolicyviolation',function(event){var blockedURL=isString(event.blockedURI)?event.blockedURI:'';if(event.disposition==='enforce'&&blockedURL.startsWith(SDK_CDN_BASE_URL)&&!state.capabilities.cspBlockedURLs.value.includes(blockedURL)){state.capabilities.cspBlockedURLs.value=[].concat(_toConsumableArray(state.capabilities.cspBlockedURLs.value),[blockedURL]);}});}/**
1183
+ */},{key:"attachErrorListeners",value:function attachErrorListeners(){var _this=this;globalThis.addEventListener('error',function(event){_this.onError({error:event,context:ERROR_HANDLER,errorType:ErrorType.UNHANDLEDEXCEPTION});});globalThis.addEventListener('unhandledrejection',function(event){_this.onError({error:event,context:ERROR_HANDLER,errorType:ErrorType.UNHANDLEDREJECTION});});// Listen to CSP violations for RS CDN URLs, recording the directive that
1184
+ // rejected each one. script-src governs a plugin import and connect-src the
1185
+ // reachability probe, so without the directive a probe-only violation looks
1186
+ // identical to one that stopped the script.
1187
+ document.addEventListener('securitypolicyviolation',function(event){var blockedURL=isString(event.blockedURI)?event.blockedURI:'';var directive=isString(event.effectiveDirective)?event.effectiveDirective:'';if(event.disposition!=='enforce'||!isSameOrUnder(blockedURL,SDK_CDN_BASE_URL)){return;}var isAlreadyRecorded=state.capabilities.cspViolations.value.some(function(violation){return violation.blockedURL===blockedURL&&violation.directive===directive;});if(!isAlreadyRecorded){state.capabilities.cspViolations.value=[].concat(_toConsumableArray(state.capabilities.cspViolations.value),[{blockedURL:blockedURL,directive:directive}]);}});}/**
1157
1188
  * Handle errors
1158
1189
  * @param errorInfo - The error information
1159
1190
  * @param errorInfo.error - The error to handle
@@ -1212,7 +1243,8 @@ destination.config.useNativeSDK===true);};var isHybridModeDestination=function i
1212
1243
  * @param id The id of the destination
1213
1244
  *
1214
1245
  * @returns the user friendly id
1215
- */var getDestinationUserFriendlyId=function getDestinationUserFriendlyId(displayName,id){return "".concat(displayName.replaceAll(' ','-'),"___").concat(id);};
1246
+ */var getDestinationUserFriendlyId=function getDestinationUserFriendlyId(displayName,id){return(// displayName comes from the source config response, so it is not guaranteed to be a string
1247
+ "".concat(String(displayName!==null&&displayName!==void 0?displayName:'').replace(/ /g,'-'),"___").concat(id));};
1216
1248
 
1217
1249
  /**
1218
1250
  * List of plugin names that are loaded as dynamic imports in modern builds
@@ -1331,7 +1363,9 @@ var runningQueueIdsByName=new Map();var RetryQueue=/*#__PURE__*/function(){/**
1331
1363
  * @param {StorageType} [storageType] The storage type to use. Defaults to LOCAL_STORAGE
1332
1364
  * @param {ILogger} [logger] The logger to use
1333
1365
  * @param {QueueBatchItemsSizeCalculatorCallback} [queueBatchItemsSizeCalculatorCb] The callback to use to calculate the size of items in the batch queue
1334
- */function RetryQueue(name,options,queueProcessCb,storeManager){var _options$timerScaleFa;var storageType=arguments.length>4&&arguments[4]!==undefined?arguments[4]:LOCAL_STORAGE;var logger=arguments.length>5?arguments[5]:undefined;var queueBatchItemsSizeCalculatorCb=arguments.length>6?arguments[6]:undefined;_classCallCheck(this,RetryQueue);this.storeManager=storeManager;this.logger=logger;this.name=name;this.id=generateUUID();this.processQueueCb=queueProcessCb;this.batchSizeCalcCb=queueBatchItemsSizeCalculatorCb;this.maxItems=options.maxItems||DEFAULT_MAX_ITEMS;this.maxAttempts=options.maxAttempts||DEFAULT_MAX_RETRY_ATTEMPTS;this.batch={enabled:false};this.configureBatchMode(options);this.backoff={minRetryDelay:options.minRetryDelay||DEFAULT_MIN_RETRY_DELAY_MS,maxRetryDelay:options.maxRetryDelay||DEFAULT_MAX_RETRY_DELAY_MS,factor:options.backoffFactor||DEFAULT_BACKOFF_FACTOR,jitter:options.backoffJitter||DEFAULT_BACKOFF_JITTER};// Limit the timer scale factor to the minimum value
1366
+ */function RetryQueue(name,options,queueProcessCb,storeManager){var _options$maxAttempts,_options$backoffJitte,_options$timerScaleFa;var storageType=arguments.length>4&&arguments[4]!==undefined?arguments[4]:LOCAL_STORAGE;var logger=arguments.length>5?arguments[5]:undefined;var queueBatchItemsSizeCalculatorCb=arguments.length>6?arguments[6]:undefined;_classCallCheck(this,RetryQueue);this.storeManager=storeManager;this.logger=logger;this.name=name;this.id=generateUUID();this.processQueueCb=queueProcessCb;this.batchSizeCalcCb=queueBatchItemsSizeCalculatorCb;this.maxItems=options.maxItems||DEFAULT_MAX_ITEMS;this.maxAttempts=(_options$maxAttempts=options.maxAttempts)!==null&&_options$maxAttempts!==void 0?_options$maxAttempts:DEFAULT_MAX_RETRY_ATTEMPTS;this.batch={enabled:false};this.configureBatchMode(options);// `??` keeps an explicit 0 but also keeps NaN, which would make every delay NaN
1367
+ var jitter=(_options$backoffJitte=options.backoffJitter)!==null&&_options$backoffJitte!==void 0?_options$backoffJitte:DEFAULT_BACKOFF_JITTER;this.backoff={minRetryDelay:options.minRetryDelay||DEFAULT_MIN_RETRY_DELAY_MS,maxRetryDelay:options.maxRetryDelay||DEFAULT_MAX_RETRY_DELAY_MS,factor:options.backoffFactor||DEFAULT_BACKOFF_FACTOR,// Clamp so delays stay positive and within maxRetryDelay
1368
+ jitter:Number.isNaN(jitter)?DEFAULT_BACKOFF_JITTER:Math.min(Math.max(jitter,0),1)};// Limit the timer scale factor to the minimum value
1335
1369
  var timerScaleFactor=Math.max((_options$timerScaleFa=options.timerScaleFactor)!==null&&_options$timerScaleFa!==void 0?_options$timerScaleFa:MIN_TIMER_SCALE_FACTOR,MIN_TIMER_SCALE_FACTOR);// Limit the timer scale factor to the maximum value
1336
1370
  timerScaleFactor=Math.min(timerScaleFactor,MAX_TIMER_SCALE_FACTOR);// painstakingly tuned. that's why they're not "easily" configurable
1337
1371
  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
@@ -1359,7 +1393,9 @@ this.scheduleFlushBatch();}}/**
1359
1393
  *
1360
1394
  * @param {Number} attemptNumber The attemptNumber (1 for first retry)
1361
1395
  * @return {Number} The delay in milliseconds to wait before attempting a retry
1362
- */},{key:"getDelay",value:function getDelay(attemptNumber){var ms=this.backoff.minRetryDelay*Math.pow(this.backoff.factor,attemptNumber);if(this.backoff.jitter){var rand=Math.random();var deviation=Math.floor(rand*this.backoff.jitter*ms);if(Math.floor(rand*10)<5){ms-=deviation;}else {ms+=deviation;}}return Number(Math.min(ms,this.backoff.maxRetryDelay).toPrecision(1));}},{key:"enqueue",value:function enqueue(entry){var curEntry;if(this.batch.enabled&&entry.type===SINGLE_QUEUE_ITEM_TYPE){curEntry=this.handleNewItemForBatch(entry);}else {curEntry=entry;}// when batching is enabled, `curEntry` could be `undefined` if the batch criteria is not met
1396
+ */},{key:"getDelay",value:function getDelay(attemptNumber){// Cap leaves headroom for +jitter so the jittered delay never exceeds maxRetryDelay
1397
+ var cap=Math.floor(this.backoff.maxRetryDelay/(1+this.backoff.jitter));var ms=Math.min(// First retry waits the base delay
1398
+ Number((this.backoff.minRetryDelay*Math.pow(this.backoff.factor,attemptNumber-1)).toPrecision(1)),cap);if(this.backoff.jitter){var rand=Math.random();var deviation=Math.floor(rand*this.backoff.jitter*ms);if(Math.floor(rand*10)<5){ms-=deviation;}else {ms+=deviation;}}return Math.min(ms,this.backoff.maxRetryDelay);}},{key:"enqueue",value:function enqueue(entry){var curEntry;if(this.batch.enabled&&entry.type===SINGLE_QUEUE_ITEM_TYPE){curEntry=this.handleNewItemForBatch(entry);}else {curEntry=entry;}// when batching is enabled, `curEntry` could be `undefined` if the batch criteria is not met
1363
1399
  if(curEntry){this.pushToMainQueue(curEntry);}}/**
1364
1400
  * Handles a new item added to the retry queue when batching is enabled
1365
1401
  * @param entry New item added to the retry queue
@@ -1442,8 +1478,8 @@ done(null);}else {// Note: We're not removing the item from the queue as we want
1442
1478
  logger===null||logger===void 0||logger.warn("".concat(BEACON_QUEUE_SEND_ERROR(BEACON_QUEUE_PLUGIN,url)," The event(s) will be retried as the current page is being unloaded."));}}else {// Remove the item from queue as the request was successful
1443
1479
  done(null);}}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError({error:err,context:BEACON_QUEUE_PLUGIN,customMessage:BEACON_QUEUE_DELIVERY_ERROR(url)});// Remove the item from queue
1444
1480
  done(null);}};var eventsQueue=new RetryQueue("".concat(QUEUE_NAME$1,"_").concat(writeKey),{batch:{enabled:true,flushInterval:finalQOpts.flushQueueInterval,maxSize:MAX_BATCH_PAYLOAD_SIZE_BYTES,// set the hard limit
1445
- maxItems:finalQOpts.maxItems}},queueProcessCallback,storeManager,getStorageTypeForEventsPersistence(logger),logger,function(itemData){var currentTime=getCurrentTimeFormatted();var events=itemData.map(function(queueItemData){return queueItemData.event;});// type casting to Blob as we know that the event has already been validated prior to enqueue
1446
- return getBatchDeliveryPayload$1(events,currentTime,logger).size;});return eventsQueue;},/**
1481
+ maxItems:finalQOpts.maxItems}},queueProcessCallback,storeManager,getStorageTypeForEventsPersistence(logger),logger,function(itemData){var _getBatchDeliveryPayl;var currentTime=getCurrentTimeFormatted();var events=itemData.map(function(queueItemData){return queueItemData.event;});// type casting to Blob as we know that the event has already been validated prior to enqueue
1482
+ return (_getBatchDeliveryPayl=getBatchDeliveryPayload$1(events,currentTime,logger))===null||_getBatchDeliveryPayl===void 0?void 0:_getBatchDeliveryPayl.size;});return eventsQueue;},/**
1447
1483
  * Add event to the queue for delivery
1448
1484
  * @param state Application state
1449
1485
  * @param eventsQueue IQueue instance
@@ -1577,7 +1613,8 @@ return true;}catch(err){errorHandler===null||errorHandler===void 0||errorHandler
1577
1613
 
1578
1614
  var pluginName$1='StorageEncryption';var StorageEncryption=function StorageEncryption(){return {name:pluginName$1,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$1]);},storage:{encrypt:function encrypt(value){return encryptBrowser(value);},decrypt:function decrypt(value){return decryptBrowser(value);}}};};
1579
1615
 
1580
- var DEFAULT_RETRY_QUEUE_OPTIONS={maxRetryDelay:360000,minRetryDelay:1000,backoffFactor:2,maxAttempts:10,maxItems:100};var REQUEST_TIMEOUT_MS=30*1000;// 30 seconds
1616
+ var DEFAULT_RETRY_QUEUE_OPTIONS={maxRetryDelay:540000,minRetryDelay:1000,backoffFactor:2,backoffJitter:0.2,maxAttempts:30,// ~3h of retries at these delays
1617
+ maxItems:100};var REQUEST_TIMEOUT_MS=30*1000;// 30 seconds
1581
1618
  var DATA_PLANE_API_VERSION='v1';var QUEUE_NAME='rudder';var XHR_QUEUE_PLUGIN='XhrQueuePlugin';
1582
1619
 
1583
1620
  var EVENT_DELIVERY_FAILURE_ERROR_PREFIX=function EVENT_DELIVERY_FAILURE_ERROR_PREFIX(context,originalErrorMsg){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to deliver event(s). Cause: ").concat(originalErrorMsg,".");};
@@ -1659,8 +1696,26 @@ var availablePlugins=[].concat(_toConsumableArray(Object.keys(pluginsInventory))
1659
1696
  * Register plugins that are direct imports to PluginEngine
1660
1697
  */},{key:"registerLocalPlugins",value:function registerLocalPlugins(){var _this2=this;var unavailablePlugins=[];Object.entries(pluginsInventory).forEach(function(_ref){var _ref2=_slicedToArray(_ref,2),pluginName=_ref2[0],localPlugin=_ref2[1];if(state.plugins.activePlugins.value.includes(pluginName)){if(isFunction(localPlugin)){_this2.register([localPlugin()]);}else {unavailablePlugins.push(pluginName);}}});if(unavailablePlugins.length>0){state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.failedPlugins.value),unavailablePlugins);this.logger.error(UNAVAILABLE_PLUGINS_ERROR(PLUGINS_MANAGER,unavailablePlugins));}}/**
1661
1698
  * Register plugins that are dynamic imports to PluginEngine
1662
- */},{key:"registerRemotePlugins",value:function registerRemotePlugins(){var _this3=this;var remotePluginsList=remotePluginsInventory(state.plugins.activePlugins.value);Promise.all(Object.keys(remotePluginsList).map(/*#__PURE__*/function(){var _ref3=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(remotePluginKey){return _regenerator().w(function(_context){while(1)switch(_context.n){case 0:_context.n=1;return remotePluginsList[remotePluginKey]().then(function(remotePluginModule){return _this3.register([remotePluginModule.default()]);}).catch(function(err){// TODO: add retry here if dynamic import fails
1663
- state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.failedPlugins.value),[remotePluginKey]);_this3.onError(err,"Failed to load plugin \"".concat(remotePluginKey,"\""),err);});case 1:return _context.a(2);}},_callee);}));return function(_x){return _ref3.apply(this,arguments);};}())).catch(function(err){_this3.onError(err);});}/**
1699
+ */},{key:"registerRemotePlugins",value:function registerRemotePlugins(){var _this3=this;var remotePluginsList=remotePluginsInventory(state.plugins.activePlugins.value);var pluginsCDNPath=state.lifecycle.pluginsCDNPath.value;var remoteEntryUrl="".concat(pluginsCDNPath,"/").concat(REMOTE_PLUGINS_ENTRY_FILE);var loadFailures=[];// Kept separate from state.plugins.failedPlugins, which also collects
1700
+ // unknown plugins from setActivePlugins, unavailable local plugins from
1701
+ // registerLocalPlugins and registration failures from register(). Reporting
1702
+ // the global list would attribute those to this remote load incident.
1703
+ var failedRemotePlugins=[];return Promise.all(Object.keys(remotePluginsList).map(/*#__PURE__*/function(){var _ref3=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(remotePluginKey){return _regenerator().w(function(_context){while(1)switch(_context.n){case 0:_context.n=1;return remotePluginsList[remotePluginKey]().then(function(remotePluginModule){// An intercepted chunk can parse yet export nothing; calling the
1704
+ // undefined factory blind reports a per-build minified name.
1705
+ var pluginFactory=remotePluginModule===null||remotePluginModule===void 0?void 0:remotePluginModule.default;if(!isFunction(pluginFactory)){throw new Error(NO_PLUGIN_FACTORY_EXPORTED_REASON);}_this3.register([pluginFactory()]);}).catch(function(err){var _message;// TODO: add retry here if dynamic import fails
1706
+ failedRemotePlugins.push(remotePluginKey);state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.failedPlugins.value),[remotePluginKey]);// A rejection is not guaranteed to be an Error, so without the
1707
+ // fallback the log reads "- undefined".
1708
+ var reason=(_message=err===null||err===void 0?void 0:err.message)!==null&&_message!==void 0?_message:String(err);_this3.logger.error(REMOTE_PLUGIN_LOAD_ERROR(PLUGINS_MANAGER,remotePluginKey,reason));loadFailures.push(err);});case 1:return _context.a(2);}},_callee);}));return function(_x){return _ref3.apply(this,arguments);};}())).then(function(){// A failed remote entry rejects every plugin import at once, so the
1709
+ // fan-out is one incident and gets one report, raised only after every
1710
+ // import has settled so it names all of them.
1711
+ //
1712
+ // An import that never settles therefore means no report. That is
1713
+ // deliberate: a dynamic import has no timeout of its own, and holding a
1714
+ // timer open to salvage a partial report would spend page resources on
1715
+ // error reporting, which is the lowest priority thing the SDK does.
1716
+ if(failedRemotePlugins.length===0){return;}_this3.onError(loadFailures[0],"Failed to load plugins: ".concat(failedRemotePlugins.join(', ')),// Grouping on the message split one bug across two dozen groups: the
1717
+ // federation runtime names its own local, renamed by the host bundler per build.
1718
+ remoteEntryUrl);}).catch(function(err){_this3.onError(err);});}/**
1664
1719
  * Extension point invoke that allows multiple plugins to be registered to it with error handling
1665
1720
  */},{key:"invokeMultiple",value:function invokeMultiple(extPoint){try{var _this$engine;for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key];}return (_this$engine=this.engine).invokeMultiple.apply(_this$engine,[extPoint].concat(args));}catch(e){this.onError(e,extPoint);return [];}}/**
1666
1721
  * Extension point invoke that allows a single plugin to be registered to it with error handling
@@ -1770,7 +1825,7 @@ state.storage.cookie.value={maxage:cookieStorageOptions.maxage,path:cookieStorag
1770
1825
  */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
1771
1826
  var compoundKey;Object.values(validKeys).forEach(function(validKeyName){if(validKeyName===key){compoundKey=noCompoundKey?key:[name,id,key].join('.');}});return compoundKey;}/**
1772
1827
  * Switch to inMemoryEngine, bringing any existing data with.
1773
- */},{key:"swapQueueStoreToInMemoryEngine",value:function swapQueueStoreToInMemoryEngine(){var _this=this;var validKeys=this.validKeys,noCompoundKey=this.noCompoundKey;var inMemoryStorage=getStorageEngine(MEMORY_STORAGE);var durableEngine=this.engine;// grab existing data, but only for this page's queue instance, not all
1828
+ */},{key:"swapQueueStoreToInMemoryEngine",value:function swapQueueStoreToInMemoryEngine(){var _this=this;var validKeys=this.validKeys,noCompoundKey=this.noCompoundKey,durableEngine=this.engine;var inMemoryStorage=getStorageEngine(MEMORY_STORAGE);// grab existing data, but only for this page's queue instance, not all
1774
1829
  // better to keep other queues in localstorage to be flushed later
1775
1830
  // than to pull them into memory and remove them from durable storage
1776
1831
  var existingEntries=Object.values(validKeys).map(function(storeKey){return [storeKey,_this.get(storeKey)];});// Client data stores keep their durable copy. Dropping rl_user_id and the
@@ -1791,8 +1846,18 @@ this.engine.setItem(validKey,this.encrypt(stringifyWithoutCircular(value,false,[
1791
1846
  this.swapQueueStoreToInMemoryEngine();// and save it there
1792
1847
  this.set(key,value);}else {var customMessage=STORE_DATA_SAVE_ERROR(key);this.onError(err,customMessage,customMessage);}}}/**
1793
1848
  * Get by Key.
1794
- */},{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)||decryptedValue===''){return null;}// storejs that is used in localstorage engine already deserializes json strings but swallows errors
1795
- return JSON.parse(decryptedValue);}catch(err){var encryptionPluginName=state.storage.encryptionPluginName.value;// Skip error reporting only when the encryption plugin is configured but failed to load
1849
+ */},{key:"get",value:function get(key){var validKey=this.createValidKey(key);var storedValue;var decryptedValue;var isRetrieved=false;try{if(!validKey){return null;}storedValue=this.engine.getItem(validKey);decryptedValue=this.decrypt(storedValue);if(isNullOrUndefined(decryptedValue)||decryptedValue===''){return null;}isRetrieved=true;// storejs that is used in localstorage engine already deserializes json strings but swallows errors
1850
+ return JSON.parse(decryptedValue);}catch(err){// Both encryption plugins, and `crypto` with no decrypt extension point registered, return
1851
+ // an unrecognised format untouched, so an unchanged value may still be readable; keep it.
1852
+ var isDecrypted=!this.isEncrypted||decryptedValue!==storedValue;// Drop a parse failure so a later read is a clean miss instead of the same error on every
1853
+ // poll, and only while the entry still holds what was read. Web Storage has no conditional
1854
+ // delete, so that narrows rather than closes the window in which another tab's write is
1855
+ // dropped; the cost there is a restarted reclaim handshake, since queued events are written
1856
+ // only by the context that owns the store. The compare is serialized because storejs
1857
+ // deserializes on every read, and uses `JSON.stringify` because `stringifyWithoutCircular`
1858
+ // returns null on failure, which would make two unserializable values compare equal.
1859
+ try{if(isRetrieved&&isDecrypted&&JSON.stringify(this.engine.getItem(validKey))===JSON.stringify(storedValue)){this.remove(key);}}catch(_unused2){// The engine can refuse the re-read or the removal; a later read retries.
1860
+ }var encryptionPluginName=state.storage.encryptionPluginName.value;// Skip error reporting only when the encryption plugin is configured but failed to load
1796
1861
  var shouldReportError=!encryptionPluginName||!state.plugins.failedPlugins.value.includes(encryptionPluginName);if(shouldReportError){var customMessage=STORE_DATA_FETCH_ERROR(key);this.onError(err,customMessage,customMessage);}return null;}}/**
1797
1862
  * Remove by Key.
1798
1863
  */},{key:"remove",value:function remove(key){var validKey=this.createValidKey(key);if(validKey){this.engine.removeItem(validKey);}}/**
@@ -1803,7 +1868,7 @@ var shouldReportError=!encryptionPluginName||!state.plugins.failedPlugins.value.
1803
1868
  * Encrypt value
1804
1869
  */},{key:"encrypt",value:function encrypt(value){return this.crypto(value,'encrypt');}/**
1805
1870
  * Extension point to use with encryption plugins
1806
- */},{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!==void 0?formattedValue:'';}/**
1871
+ */},{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 formattedValue===undefined?value:formattedValue!==null&&formattedValue!==void 0?formattedValue:'';}/**
1807
1872
  * Handle errors
1808
1873
  */},{key:"onError",value:function onError(error,customMessage,groupingHash){this.errorHandler.onError({error:error,context:"Store ".concat(this.id),customMessage:customMessage,groupingHash:groupingHash});}}]);}();
1809
1874
 
@@ -2063,14 +2128,28 @@ var getUserAgentClientHint=function getUserAgentClientHint(callback){var level=a
2063
2128
 
2064
2129
  var isDatasetAvailable=function isDatasetAvailable(){var testElement=globalThis.document.createElement('div');testElement.setAttribute('data-a-b','c');return testElement.dataset?testElement.dataset.aB==='c':false;};var legacyJSEngineRequiredPolyfills={// Ideally, we should separate the checks for URL and URLSearchParams but
2065
2130
  // the polyfill service serves them under the same feature name, "URL".
2066
- URL:function URL(){return !isFunction(globalThis.URL)||!isFunction(globalThis.URLSearchParams);},Promise:function Promise(){return !isFunction(globalThis.Promise);},'Number.isNaN':function NumberIsNaN(){return !isFunction(globalThis.Number.isNaN);},'Number.isInteger':function NumberIsInteger(){return !isFunction(globalThis.Number.isInteger);},'Array.from':function ArrayFrom(){return !isFunction(globalThis.Array.from);},'Array.prototype.find':function ArrayPrototypeFind(){return !isFunction(globalThis.Array.prototype.find);},'Array.prototype.includes':function ArrayPrototypeIncludes(){return !isFunction(globalThis.Array.prototype.includes);},'String.prototype.endsWith':function StringPrototypeEndsWith(){return !isFunction(globalThis.String.prototype.endsWith);},'String.prototype.startsWith':function StringPrototypeStartsWith(){return !isFunction(globalThis.String.prototype.startsWith);},'String.prototype.includes':function StringPrototypeIncludes(){return !isFunction(globalThis.String.prototype.includes);},'String.prototype.replaceAll':function StringPrototypeReplaceAll(){return !isFunction(globalThis.String.prototype.replaceAll);},'String.fromCodePoint':function StringFromCodePoint(){return !isFunction(globalThis.String.fromCodePoint);},'Object.entries':function ObjectEntries(){return !isFunction(globalThis.Object.entries);},'Object.values':function ObjectValues(){return !isFunction(globalThis.Object.values);},'Object.assign':function ObjectAssign(){return !isFunction(globalThis.Object.assign);},'Object.fromEntries':function ObjectFromEntries(){return !isFunction(globalThis.Object.fromEntries);},'Element.prototype.dataset':function ElementPrototypeDataset(){return !isDatasetAvailable();},// Ideally, we should separate the checks for TextEncoder and TextDecoder but
2131
+ URL:function URL(){return !isFunction(globalThis.URL)||!isFunction(globalThis.URLSearchParams);},Promise:function Promise(){return !isFunction(globalThis.Promise);},'Number.isNaN':function NumberIsNaN(){return !isFunction(globalThis.Number.isNaN);},'Number.isInteger':function NumberIsInteger(){return !isFunction(globalThis.Number.isInteger);},'Array.from':function ArrayFrom(){return !isFunction(globalThis.Array.from);},'Array.prototype.find':function ArrayPrototypeFind(){return !isFunction(globalThis.Array.prototype.find);},'Array.prototype.includes':function ArrayPrototypeIncludes(){return !isFunction(globalThis.Array.prototype.includes);},'String.prototype.endsWith':function StringPrototypeEndsWith(){return !isFunction(globalThis.String.prototype.endsWith);},'String.prototype.startsWith':function StringPrototypeStartsWith(){return !isFunction(globalThis.String.prototype.startsWith);},'String.prototype.includes':function StringPrototypeIncludes(){return !isFunction(globalThis.String.prototype.includes);},'String.prototype.replaceAll':function StringPrototypeReplaceAll(){return !isFunction(globalThis.String.prototype.replaceAll);},'String.fromCodePoint':function StringFromCodePoint(){return !isFunction(globalThis.String.fromCodePoint);},'Object.entries':function ObjectEntries(){return !isFunction(globalThis.Object.entries);},'Object.values':function ObjectValues(){return !isFunction(globalThis.Object.values);},// Not used in this package, but the device mode integrations need them
2132
+ 'Object.assign':function ObjectAssign(){return !isFunction(globalThis.Object.assign);},'Object.fromEntries':function ObjectFromEntries(){return !isFunction(globalThis.Object.fromEntries);},'Element.prototype.dataset':function ElementPrototypeDataset(){return !isDatasetAvailable();},// Ideally, we should separate the checks for TextEncoder and TextDecoder but
2067
2133
  // the polyfill service serves them under the same feature name, "TextEncoder".
2068
- TextEncoder:function TextEncoder(){return !isFunction(globalThis.TextEncoder)||!isFunction(globalThis.TextDecoder);},requestAnimationFrame:function requestAnimationFrame(){return !isFunction(globalThis.requestAnimationFrame)||!isFunction(globalThis.cancelAnimationFrame);},CustomEvent:function CustomEvent(){return !isFunction(globalThis.CustomEvent);},'navigator.sendBeacon':function navigatorSendBeacon(){return !isFunction(globalThis.navigator.sendBeacon);},// Note, the polyfill service serves both ArrayBuffer and Uint8Array under the same feature name, "ArrayBuffer".
2069
- ArrayBuffer:function ArrayBuffer(){return !isFunction(globalThis.Uint8Array);},Set:function Set(){return !isFunction(globalThis.Set);},atob:function atob(){return !isFunction(globalThis.atob);}};var isLegacyJSEngine=function isLegacyJSEngine(){var requiredCapabilitiesList=Object.keys(legacyJSEngineRequiredPolyfills);var needsPolyfill=false;/* eslint-disable-next-line unicorn/no-for-loop */for(var i=0;i<requiredCapabilitiesList.length;i++){var isCapabilityMissing=legacyJSEngineRequiredPolyfills[requiredCapabilitiesList[i]];if(isFunction(isCapabilityMissing)&&isCapabilityMissing()){needsPolyfill=true;break;}}return needsPolyfill;};
2134
+ TextEncoder:function TextEncoder(){return !isFunction(globalThis.TextEncoder)||!isFunction(globalThis.TextDecoder);},CustomEvent:function CustomEvent(){return !isFunction(globalThis.CustomEvent);},// Note, the polyfill service serves both ArrayBuffer and Uint8Array under the same feature name, "ArrayBuffer".
2135
+ ArrayBuffer:function ArrayBuffer(){return !isFunction(globalThis.Uint8Array);},Set:function Set(){return !isFunction(globalThis.Set);},Map:function Map(){return !isFunction(globalThis.Map);},atob:function atob(){return !isFunction(globalThis.atob);}};var isLegacyJSEngine=function isLegacyJSEngine(){var requiredCapabilitiesList=Object.keys(legacyJSEngineRequiredPolyfills);var needsPolyfill=false;/* eslint-disable-next-line unicorn/no-for-loop */for(var i=0;i<requiredCapabilitiesList.length;i++){var isCapabilityMissing=legacyJSEngineRequiredPolyfills[requiredCapabilitiesList[i]];if(isFunction(isCapabilityMissing)&&isCapabilityMissing()){needsPolyfill=true;break;}}return needsPolyfill;};
2070
2136
 
2071
- var polyfillIoSdkUrl='https://polyfill-fastly.io/v3/polyfill.min.js';var POLYFILL_URL="".concat(polyfillIoSdkUrl,"?version=3.111.0&features=").concat(Object.keys(legacyJSEngineRequiredPolyfills).join('%2C'));var POLYFILL_LOAD_TIMEOUT=10*1000;// 10 seconds
2137
+ var polyfillIoSdkUrl='https://polyfill-fastly.io/v3/polyfill.min.js';var POLYFILL_URL=// Pure so the modern build, which never reads it, drops it and the detection list
2138
+ "".concat(polyfillIoSdkUrl,"?version=3.111.0&flags=always%2Cgated&features=").concat(/* @__PURE__ */Object.keys(legacyJSEngineRequiredPolyfills).join('%2C'));var POLYFILL_LOAD_TIMEOUT=10*1000;// 10 seconds
2072
2139
  var POLYFILL_SCRIPT_ID='rudderstackPolyfill';
2073
2140
 
2141
+ var detectAdBlockers=function detectAdBlockers(httpClient){state.capabilities.isAdBlockerDetectionInProgress.value=true;try{// Apparently, '?view=ad' is a query param that is blocked by majority of adblockers
2142
+ // Use source config URL here as it is very unlikely to be blocked by adblockers
2143
+ // Only the extra query param should make it vulnerable to adblockers
2144
+ // This will work even if the users proxies it.
2145
+ // The edge case where this doesn't work is when HEAD method is not allowed by the server (user's)
2146
+ 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
2147
+ method:'HEAD',headers:{'Content-Type':undefined}},isRawResponse:true,callback:function callback(result,details){var _details$xhr;state.capabilities.isAdBlockerDetectionInProgress.value=false;// not ad blocked if the request is successful or it is not internally redirected on the client side
2148
+ // Often adblockers instead of blocking the request, they redirect it to an internal URL
2149
+ state.capabilities.isAdBlocked.value=(details===null||details===void 0?void 0:details.error)!==undefined||(details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.responseURL)!==url;}});}catch(err){// Reset the flag to prevent blocking future detection attempts
2150
+ state.capabilities.isAdBlockerDetectionInProgress.value=false;// Re-throw the error to be handled by the caller
2151
+ throw err;}};
2152
+
2074
2153
  var hasCrypto=function hasCrypto(){return !isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);};// eslint-disable-next-line compat/compat -- We are checking for the existence of navigator.userAgentData
2075
2154
  var hasUAClientHints=function hasUAClientHints(){return !isNullOrUndefined(globalThis.navigator.userAgentData);};var hasBeacon=function hasBeacon(){return !isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);};
2076
2155
 
@@ -2085,10 +2164,19 @@ state.capabilities.isBeaconAvailable.value=hasBeacon();state.capabilities.isUaCH
2085
2164
  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
2086
2165
  j(function(){if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(_this.httpClient);}});}/**
2087
2166
  * Detect if polyfills are required and then load script from polyfill URL
2088
- */},{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
2167
+ */},{key:"prepareBrowserCapabilities",value:function prepareBrowserCapabilities(){var _this2=this;// The snippet only hands the modern build to engines that ship every polyfill-list API the
2168
+ 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;// write key specific callback
2089
2169
  // NOTE: we're not putting this into RudderStackGlobals as providing the property path to the callback function in the polyfill URL is not possible
2090
- 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
2091
- 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();}}/**
2170
+ var polyfillCallbackName="RS_polyfillCallback_".concat(state.lifecycle.writeKey.value);// A timed out script stays in the DOM, so a late response can still fire the
2171
+ // callback. Settle once, and drop the handler on failure as well as success.
2172
+ var isPolyfillLoadSettled=false;var installedPolyfillCallback;var settlePolyfillLoad=function settlePolyfillLoad(onSettled){// Only remove our own handler: the name is keyed by write key alone, so the
2173
+ // global may belong to the page or to another in-flight load.
2174
+ if(installedPolyfillCallback&&globalThis[polyfillCallbackName]===installedPolyfillCallback){delete globalThis[polyfillCallbackName];}if(isPolyfillLoadSettled){return;}isPolyfillLoadSettled=true;onSettled();};if(isDefaultPolyfillService){installedPolyfillCallback=function installedPolyfillCallback(){settlePolyfillLoad(function(){return _this2.onPolyfillLoaded();});};globalThis[polyfillCallbackName]=installedPolyfillCallback;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,err){if(!scriptId||err){// Report and stop: the SDK misbehaves on an engine still missing these.
2175
+ settlePolyfillLoad(function(){_this2.onError(new Error(POLYFILL_SCRIPT_LOAD_ERROR(POLYFILL_SCRIPT_ID,polyfillUrl)));});}else if(!isDefaultPolyfillService){settlePolyfillLoad(function(){return _this2.onPolyfillLoaded();});}}});}else {this.onReady();}}/**
2176
+ * Report the features that the polyfill script did not apply and then set the
2177
+ * lifecycle status to next phase
2178
+ */},{key:"onPolyfillLoaded",value:function onPolyfillLoaded(){// Guarded too so the detection list is dropped from the modern bundle
2179
+ if(isLegacyJSEngine()){var missingFeatures=Object.keys(legacyJSEngineRequiredPolyfills).filter(function(feature){var isFeatureMissing=legacyJSEngineRequiredPolyfills[feature];return isFunction(isFeatureMissing)&&isFeatureMissing();});this.onError(new Error(POLYFILL_VERIFICATION_ERROR(missingFeatures)));}this.onReady();}/**
2092
2180
  * Attach listeners to window to observe event that update capabilities state values
2093
2181
  */},{key:"attachWindowListeners",value:function attachWindowListeners(){globalThis.addEventListener('offline',function(){state.capabilities.isOnline.value=false;});globalThis.addEventListener('online',function(){state.capabilities.isOnline.value=true;});globalThis.addEventListener('resize',debounce(function(){state.context.screen.value=getScreenDetails();},this));}/**
2094
2182
  * Set the lifecycle status to next phase
@@ -2096,7 +2184,7 @@ delete globalThis[polyfillCallbackName];};globalThis[polyfillCallbackName]=polyf
2096
2184
  },{key:"onReady",value:function onReady(){this.detectBrowserCapabilities();state.lifecycle.status.value='browserCapabilitiesReady';}/**
2097
2185
  * Handles error
2098
2186
  * @param error The error object
2099
- */},{key:"onError",value:function onError(error,groupingHash){this.errorHandler.onError({error:error,context:CAPABILITIES_MANAGER,groupingHash:groupingHash});}}]);}();
2187
+ */},{key:"onError",value:function onError(error,groupingHash){void this.errorHandler.onError({error:error,context:CAPABILITIES_MANAGER,groupingHash:groupingHash});}}]);}();
2100
2188
 
2101
2189
  var CHANNEL='web';// These are the top-level elements in the standard RudderStack event spec
2102
2190
  var TOP_LEVEL_ELEMENTS=['integrations','anonymousId','originalTimestamp'];// Reserved elements in the context of standard RudderStack event spec