@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.
- package/CHANGELOG.md +41 -0
- package/dist/npm/index.d.cts +9 -0
- package/dist/npm/index.d.mts +9 -0
- package/dist/npm/legacy/bundled/cjs/index.cjs +152 -64
- package/dist/npm/legacy/bundled/esm/index.mjs +152 -64
- package/dist/npm/legacy/bundled/umd/index.js +152 -64
- package/dist/npm/legacy/cjs/index.cjs +152 -64
- package/dist/npm/legacy/content-script/cjs/index.cjs +150 -63
- package/dist/npm/legacy/content-script/esm/index.mjs +150 -63
- package/dist/npm/legacy/content-script/umd/index.js +150 -63
- package/dist/npm/legacy/esm/index.mjs +152 -64
- package/dist/npm/legacy/lite/cjs/index.cjs +151 -63
- package/dist/npm/legacy/lite/esm/index.mjs +151 -63
- package/dist/npm/legacy/lite/umd/index.js +151 -63
- package/dist/npm/legacy/umd/index.js +152 -64
- package/dist/npm/modern/bundled/cjs/index.cjs +457 -327
- package/dist/npm/modern/bundled/esm/index.mjs +457 -327
- package/dist/npm/modern/bundled/umd/index.js +457 -327
- package/dist/npm/modern/cjs/index.cjs +356 -231
- package/dist/npm/modern/content-script/cjs/index.cjs +457 -327
- package/dist/npm/modern/content-script/esm/index.mjs +457 -327
- package/dist/npm/modern/content-script/umd/index.js +457 -327
- package/dist/npm/modern/esm/index.mjs +356 -231
- package/dist/npm/modern/lite/cjs/index.cjs +428 -298
- package/dist/npm/modern/lite/esm/index.mjs +428 -298
- package/dist/npm/modern/lite/umd/index.js +428 -298
- package/dist/npm/modern/umd/index.js +356 -231
- package/package.json +1 -1
|
@@ -2,6 +2,70 @@
|
|
|
2
2
|
|
|
3
3
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
4
4
|
|
|
5
|
+
function _defineProperty(e, r, t) {
|
|
6
|
+
return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
|
|
7
|
+
value: t,
|
|
8
|
+
enumerable: true,
|
|
9
|
+
configurable: true,
|
|
10
|
+
writable: true
|
|
11
|
+
}) : e[r] = t, e;
|
|
12
|
+
}
|
|
13
|
+
function ownKeys(e, r) {
|
|
14
|
+
var t = Object.keys(e);
|
|
15
|
+
if (Object.getOwnPropertySymbols) {
|
|
16
|
+
var o = Object.getOwnPropertySymbols(e);
|
|
17
|
+
r && (o = o.filter(function (r) {
|
|
18
|
+
return Object.getOwnPropertyDescriptor(e, r).enumerable;
|
|
19
|
+
})), t.push.apply(t, o);
|
|
20
|
+
}
|
|
21
|
+
return t;
|
|
22
|
+
}
|
|
23
|
+
function _objectSpread2(e) {
|
|
24
|
+
for (var r = 1; r < arguments.length; r++) {
|
|
25
|
+
var t = null != arguments[r] ? arguments[r] : {};
|
|
26
|
+
r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
|
|
27
|
+
_defineProperty(e, r, t[r]);
|
|
28
|
+
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
|
|
29
|
+
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
return e;
|
|
33
|
+
}
|
|
34
|
+
function _objectWithoutProperties(e, t) {
|
|
35
|
+
if (null == e) return {};
|
|
36
|
+
var o,
|
|
37
|
+
r,
|
|
38
|
+
i = _objectWithoutPropertiesLoose(e, t);
|
|
39
|
+
if (Object.getOwnPropertySymbols) {
|
|
40
|
+
var n = Object.getOwnPropertySymbols(e);
|
|
41
|
+
for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
|
|
42
|
+
}
|
|
43
|
+
return i;
|
|
44
|
+
}
|
|
45
|
+
function _objectWithoutPropertiesLoose(r, e) {
|
|
46
|
+
if (null == r) return {};
|
|
47
|
+
var t = {};
|
|
48
|
+
for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
|
|
49
|
+
if (-1 !== e.indexOf(n)) continue;
|
|
50
|
+
t[n] = r[n];
|
|
51
|
+
}
|
|
52
|
+
return t;
|
|
53
|
+
}
|
|
54
|
+
function _toPrimitive(t, r) {
|
|
55
|
+
if ("object" != typeof t || !t) return t;
|
|
56
|
+
var e = t[Symbol.toPrimitive];
|
|
57
|
+
if (void 0 !== e) {
|
|
58
|
+
var i = e.call(t, r);
|
|
59
|
+
if ("object" != typeof i) return i;
|
|
60
|
+
throw new TypeError("@@toPrimitive must return a primitive value.");
|
|
61
|
+
}
|
|
62
|
+
return ("string" === r ? String : Number)(t);
|
|
63
|
+
}
|
|
64
|
+
function _toPropertyKey(t) {
|
|
65
|
+
var i = _toPrimitive(t, "string");
|
|
66
|
+
return "symbol" == typeof i ? i : i + "";
|
|
67
|
+
}
|
|
68
|
+
|
|
5
69
|
function _isPlaceholder(a){return a!=null&&typeof a==='object'&&a['@@functional/placeholder']===true;}
|
|
6
70
|
|
|
7
71
|
/**
|
|
@@ -374,7 +438,7 @@ if(isString(category)&&!isString(name)){payload.category=undefined;payload.name=
|
|
|
374
438
|
// and set some proper defaults
|
|
375
439
|
// Also, to clone the incoming object type arguments
|
|
376
440
|
if(!isDefined(payload.category)){payload.category=undefined;}if(!isDefined(payload.name)){payload.name=undefined;}payload.properties=payload.properties?clone(payload.properties):{};if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}const nameForProperties=isString(payload.name)?payload.name:payload.properties.name;const categoryForProperties=isString(payload.category)?payload.category:payload.properties.category;// add name and category to properties
|
|
377
|
-
payload.properties=mergeDeepRight(isObjectLiteralAndNotNull(payload.properties)?payload.properties:{},{
|
|
441
|
+
payload.properties=mergeDeepRight(isObjectLiteralAndNotNull(payload.properties)?payload.properties:{},_objectSpread2(_objectSpread2({},nameForProperties&&{name:nameForProperties}),categoryForProperties&&{category:categoryForProperties}));return payload;};/*
|
|
378
442
|
* Normalise the overloaded arguments of the track call facade
|
|
379
443
|
*/const trackArgumentsToCallOptions=(event,properties,options,callback)=>{const payload={name:event,properties:properties,options:options,callback:undefined};if(isFunction(callback)){payload.callback=callback;}if(isFunction(options)){payload.properties=properties;payload.options=undefined;payload.callback=options;}if(isFunction(properties)){payload.properties=undefined;payload.options=undefined;payload.callback=properties;}// Rest of the code is just to clean up undefined values
|
|
380
444
|
// and set some proper defaults
|
|
@@ -431,7 +495,7 @@ const generateUUID=()=>{if(hasCrypto$1()){return v4$1();}return v4();};
|
|
|
431
495
|
/**
|
|
432
496
|
* Determines if the SDK is running inside a chrome extension
|
|
433
497
|
* @returns boolean
|
|
434
|
-
*/const isSDKRunningInChromeExtension=()
|
|
498
|
+
*/const isSDKRunningInChromeExtension=()=>{var _chrome;return !!((_chrome=window.chrome)!==null&&_chrome!==void 0&&(_chrome=_chrome.runtime)!==null&&_chrome!==void 0&&_chrome.id);};const isIE11=()=>isString(globalThis.navigator.userAgent)&&/Trident.*rv:11\./.test(globalThis.navigator.userAgent);
|
|
435
499
|
|
|
436
500
|
/**
|
|
437
501
|
* Registers events to detect page leave scenarios
|
|
@@ -465,25 +529,25 @@ const LOG_CONTEXT_SEPARATOR=':: ';const SCRIPT_ALREADY_EXISTS_ERROR=id=>`A scrip
|
|
|
465
529
|
|
|
466
530
|
const JSON_STRINGIFY='JSONStringify';const JSON_UTIL='JSON';const BIG_INT_PLACEHOLDER='[BigInt]';const CIRCULAR_REFERENCE_PLACEHOLDER='[Circular Reference]';const getCircularReplacer=(excludeNull,excludeKeys,logger)=>{const ancestors=[];// Here we do not want to use arrow function to use "this" in function context
|
|
467
531
|
// eslint-disable-next-line func-names
|
|
468
|
-
return function(key,value){if(excludeKeys
|
|
532
|
+
return function(key,value){if(excludeKeys!==null&&excludeKeys!==void 0&&excludeKeys.includes(key)){return undefined;}if(excludeNull&&isNullOrUndefined(value)){return undefined;}if(typeof value!=='object'||isNull(value)){return value;}// `this` is the object that value is contained in, i.e., its direct parent.
|
|
469
533
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
470
534
|
// @ts-ignore-next-line
|
|
471
|
-
while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();}if(ancestors.includes(value)){logger
|
|
535
|
+
while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();}if(ancestors.includes(value)){logger===null||logger===void 0||logger.warn(CIRCULAR_REFERENCE_WARNING(JSON_STRINGIFY,key));return CIRCULAR_REFERENCE_PLACEHOLDER;}ancestors.push(value);return value;};};/**
|
|
472
536
|
* Utility method for JSON stringify object excluding null values & circular references
|
|
473
537
|
*
|
|
474
538
|
* @param {*} value input
|
|
475
539
|
* @param {boolean} excludeNull if it should exclude nul or not
|
|
476
540
|
* @param {function} logger optional logger methods for warning
|
|
477
541
|
* @returns string
|
|
478
|
-
*/const stringifyWithoutCircular=(value,excludeNull,excludeKeys,logger)=>{try{return JSON.stringify(value,getCircularReplacer(excludeNull,excludeKeys,logger));}catch(err){logger
|
|
542
|
+
*/const stringifyWithoutCircular=(value,excludeNull,excludeKeys,logger)=>{try{return JSON.stringify(value,getCircularReplacer(excludeNull,excludeKeys,logger));}catch(err){logger===null||logger===void 0||logger.warn(JSON_STRINGIFY_WARNING,err);return null;}};const getReplacer=logger=>{const ancestors=[];// Array to track ancestor objects
|
|
479
543
|
// Using a regular function to use `this` for the parent context
|
|
480
|
-
return function replacer(key,value){if(isBigInt(value)){logger
|
|
544
|
+
return function replacer(key,value){if(isBigInt(value)){logger===null||logger===void 0||logger.warn(BAD_DATA_WARNING(JSON_UTIL,key));return BIG_INT_PLACEHOLDER;// Replace BigInt values
|
|
481
545
|
}// `this` is the object that value is contained in, i.e., its direct parent.
|
|
482
546
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
483
547
|
// @ts-ignore-next-line
|
|
484
548
|
while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();// Remove ancestors that are no longer part of the chain
|
|
485
549
|
}// Check for circular references (if the value is already in the ancestors)
|
|
486
|
-
if(ancestors.includes(value)){logger
|
|
550
|
+
if(ancestors.includes(value)){logger===null||logger===void 0||logger.warn(BAD_DATA_WARNING(JSON_UTIL,key));return CIRCULAR_REFERENCE_PLACEHOLDER;}// Add current value to ancestors
|
|
487
551
|
ancestors.push(value);return value;};};const traverseWithThis=(obj,replacer)=>{// Create a new result object or array
|
|
488
552
|
const result=Array.isArray(obj)?[]:{};// Traverse object properties or array elements
|
|
489
553
|
// eslint-disable-next-line no-restricted-syntax
|
|
@@ -506,11 +570,11 @@ const MANUAL_ERROR_IDENTIFIER='[SDK DISPATCHED ERROR]';const getStacktrace=err=>
|
|
|
506
570
|
*/const getMutatedError=(err,issue)=>{if(!isTypeOfError(err)){return new Error(`${issue}: ${stringifyWithoutCircular(err)}`);}try{// Preserve the specific error type (TypeError, ReferenceError, etc.)
|
|
507
571
|
const ErrorConstructor=err.constructor;const newError=new ErrorConstructor(`${issue}: ${err.message}`);// Preserve stack trace
|
|
508
572
|
const stack=getStacktrace(err);if(stack){newError.stack=stack;}// Preserve any other enumerable properties
|
|
509
|
-
Object.getOwnPropertyNames(err).forEach(key=>{if(key!=='message'&&key!=='stack'&&key!=='name'){try{newError[key]=err[key];}catch{// Ignore if property is not writable
|
|
510
|
-
}}});return newError;}catch{return new Error(`${issue}: ${stringifyWithoutCircular(err)}`);}};const dispatchErrorEvent=error=>{if(isTypeOfError(error)){const errStack=getStacktrace(error);if(errStack){// eslint-disable-next-line no-param-reassign
|
|
573
|
+
Object.getOwnPropertyNames(err).forEach(key=>{if(key!=='message'&&key!=='stack'&&key!=='name'){try{newError[key]=err[key];}catch(_unused){// Ignore if property is not writable
|
|
574
|
+
}}});return newError;}catch(_unused2){return new Error(`${issue}: ${stringifyWithoutCircular(err)}`);}};const dispatchErrorEvent=error=>{if(isTypeOfError(error)){const errStack=getStacktrace(error);if(errStack){// eslint-disable-next-line no-param-reassign
|
|
511
575
|
error.stack=`${errStack}\n${MANUAL_ERROR_IDENTIFIER}`;}}globalThis.dispatchEvent(new ErrorEvent('error',{error,bubbles:true,cancelable:true,composed:true}));};
|
|
512
576
|
|
|
513
|
-
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.
|
|
577
|
+
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.35.0';const APP_NAMESPACE='com.rudderlabs.javascript';const MODULE_TYPE='npm';const BUILD_VARIANT='modern';const ADBLOCK_PAGE_CATEGORY='RudderJS-Initiated';const ADBLOCK_PAGE_NAME='ad-block page request';const ADBLOCK_PAGE_PATH='/ad-blocked';const GLOBAL_PRELOAD_BUFFER='preloadedEventsBuffer';const CONSENT_TRACK_EVENT_NAME='Consent Management Interaction';
|
|
514
578
|
|
|
515
579
|
const QUERY_PARAM_TRAIT_PREFIX='ajs_trait_';const QUERY_PARAM_PROPERTY_PREFIX='ajs_prop_';const QUERY_PARAM_ANONYMOUS_ID_KEY='ajs_aid';const QUERY_PARAM_USER_ID_KEY='ajs_uid';const QUERY_PARAM_TRACK_EVENT_NAME_KEY='ajs_event';
|
|
516
580
|
|
|
@@ -578,10 +642,10 @@ const EXTERNAL_SOURCE_LOAD_ORIGIN='RS_JS_SDK';
|
|
|
578
642
|
* @param {*} newScriptElement the script element to add
|
|
579
643
|
*
|
|
580
644
|
* @returns
|
|
581
|
-
*/const insertScript=newScriptElement=>{
|
|
582
|
-
const headElements=document.getElementsByTagName('head');if(headElements.length>0){headElements[0]
|
|
583
|
-
const scriptElements=document.getElementsByTagName('script');if(scriptElements.length>0&&scriptElements[0]
|
|
584
|
-
const headElement=document.createElement('head');headElement.appendChild(newScriptElement);const htmlElement=document.getElementsByTagName('html')[0];htmlElement
|
|
645
|
+
*/const insertScript=newScriptElement=>{var _scriptElements$;// First try to add it to the head
|
|
646
|
+
const headElements=document.getElementsByTagName('head');if(headElements.length>0){var _headElements$,_headElements$2;(_headElements$=headElements[0])===null||_headElements$===void 0||_headElements$.insertBefore(newScriptElement,(_headElements$2=headElements[0])===null||_headElements$2===void 0?void 0:_headElements$2.firstChild);return;}// Else wise add it before the first script tag
|
|
647
|
+
const scriptElements=document.getElementsByTagName('script');if(scriptElements.length>0&&(_scriptElements$=scriptElements[0])!==null&&_scriptElements$!==void 0&&_scriptElements$.parentNode){var _scriptElements$2;(_scriptElements$2=scriptElements[0])===null||_scriptElements$2===void 0||_scriptElements$2.parentNode.insertBefore(newScriptElement,scriptElements[0]);return;}// Create a new head element and add the script as fallback
|
|
648
|
+
const headElement=document.createElement('head');headElement.appendChild(newScriptElement);const htmlElement=document.getElementsByTagName('html')[0];htmlElement===null||htmlElement===void 0||htmlElement.insertBefore(headElement,htmlElement.firstChild);};/**
|
|
585
649
|
* Loads external js file as a script html tag
|
|
586
650
|
*
|
|
587
651
|
* @param {*} url The URL of the script to be loaded
|
|
@@ -609,7 +673,7 @@ var i=Symbol.for("preact-signals");function t(){if(!(v>1)){var i,t=false;!functi
|
|
|
609
673
|
|
|
610
674
|
const LOG_LEVEL_MAP={LOG:0,INFO:1,DEBUG:2,WARN:3,ERROR:4,NONE:5};const DEFAULT_LOG_LEVEL='LOG';const POST_LOAD_LOG_LEVEL='ERROR';const LOG_MSG_PREFIX='RS SDK';const LOG_MSG_PREFIX_STYLE='font-weight: bold; background: black; color: white;';const LOG_MSG_STYLE='font-weight: normal;';/**
|
|
611
675
|
* Service to log messages/data to output provider, default is console
|
|
612
|
-
*/class Logger{constructor(minLogLevel=DEFAULT_LOG_LEVEL,scope='',logProvider=console){this.minLogLevel=LOG_LEVEL_MAP[minLogLevel];this.scope=scope;this.logProvider=logProvider;}log(...data){this.outputLog('LOG',data);}info(...data){this.outputLog('INFO',data);}debug(...data){this.outputLog('DEBUG',data);}warn(...data){this.outputLog('WARN',data);}error(...data){this.outputLog('ERROR',data);}outputLog(logMethod,data){if(this.minLogLevel<=LOG_LEVEL_MAP[logMethod]){this.logProvider[logMethod.toLowerCase()]
|
|
676
|
+
*/class Logger{constructor(minLogLevel=DEFAULT_LOG_LEVEL,scope='',logProvider=console){this.minLogLevel=LOG_LEVEL_MAP[minLogLevel];this.scope=scope;this.logProvider=logProvider;}log(...data){this.outputLog('LOG',data);}info(...data){this.outputLog('INFO',data);}debug(...data){this.outputLog('DEBUG',data);}warn(...data){this.outputLog('WARN',data);}error(...data){this.outputLog('ERROR',data);}outputLog(logMethod,data){if(this.minLogLevel<=LOG_LEVEL_MAP[logMethod]){var _this$logProvider,_this$logProvider2;(_this$logProvider=(_this$logProvider2=this.logProvider)[logMethod.toLowerCase()])===null||_this$logProvider===void 0||_this$logProvider.call(_this$logProvider2,...this.formatLogData(data));}}setScope(scopeVal){this.scope=scopeVal||this.scope;}// TODO: should we allow to change the level via global variable on run time
|
|
613
677
|
// to assist on the fly debugging?
|
|
614
678
|
setMinLogLevel(logLevel){this.minLogLevel=LOG_LEVEL_MAP[logLevel];if(isUndefined(this.minLogLevel)){this.minLogLevel=LOG_LEVEL_MAP[DEFAULT_LOG_LEVEL];}}/**
|
|
615
679
|
* Formats the console message using `scope` and styles
|
|
@@ -630,7 +694,7 @@ const SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','s
|
|
|
630
694
|
|
|
631
695
|
const SOURCE_CONFIG_RESOLUTION_ERROR=`Unable to process/parse source configuration response`;const SOURCE_DISABLED_ERROR=`The source is disabled. Please enable the source in the dashboard to send events.`;const XHR_PAYLOAD_PREP_ERROR=`Failed to prepare data for the request.`;const PLUGIN_EXT_POINT_MISSING_ERROR=`Failed to invoke plugin because the extension point name is missing.`;const PLUGIN_EXT_POINT_INVALID_ERROR=`Failed to invoke plugin because the extension point name is invalid.`;const SOURCE_CONFIG_OPTION_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}The "getSourceConfig" load API option must be a function that returns valid source configuration data.`;const COMPONENT_BASE_URL_ERROR=(context,component,url)=>`${context}${LOG_CONTEXT_SEPARATOR}The base URL "${url}" for ${component} is not valid.`;// ERROR
|
|
632
696
|
const UNSUPPORTED_CONSENT_MANAGER_ERROR=(context,selectedConsentManager,consentManagersToPluginNameMap)=>`${context}${LOG_CONTEXT_SEPARATOR}The consent manager "${selectedConsentManager}" is not supported. Please choose one of the following supported consent managers: "${Object.keys(consentManagersToPluginNameMap)}".`;const NON_ERROR_WARNING=(context,errStr)=>`${context}${LOG_CONTEXT_SEPARATOR}Ignoring a non-error: ${errStr}.`;const BREADCRUMB_ERROR=`Failed to log breadcrumb`;const HANDLE_ERROR_FAILURE=context=>`${context}${LOG_CONTEXT_SEPARATOR}Failed to handle the error.`;const PLUGIN_NAME_MISSING_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin name is missing.`;const PLUGIN_ALREADY_EXISTS_ERROR=(context,pluginName)=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin "${pluginName}" already exists.`;const PLUGIN_NOT_FOUND_ERROR=(context,pluginName)=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin "${pluginName}" not found.`;const PLUGIN_ENGINE_BUG_ERROR=(context,pluginName)=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin "${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.`;const PLUGIN_DEPS_ERROR=(context,pluginName,notExistDeps)=>`${context}${LOG_CONTEXT_SEPARATOR}Plugin "${pluginName}" could not be loaded because some of its dependencies "${notExistDeps}" do not exist.`;const PLUGIN_INVOCATION_ERROR=(context,extPoint,pluginName)=>`${context}${LOG_CONTEXT_SEPARATOR}Failed to invoke the "${extPoint}" extension point of plugin "${pluginName}".`;const SOURCE_CONFIG_FETCH_ERROR='Failed to fetch the source config';const WRITE_KEY_VALIDATION_ERROR=(context,writeKey)=>`${context}${LOG_CONTEXT_SEPARATOR}The write key "${writeKey}" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.`;const DATA_PLANE_URL_VALIDATION_ERROR=(context,dataPlaneUrl)=>`${context}${LOG_CONTEXT_SEPARATOR}The data plane URL "${dataPlaneUrl}" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.`;const INVALID_CALLBACK_FN_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}The provided callback parameter is not a function.`;const XHR_DELIVERY_ERROR=(prefix,status,statusText,url,response)=>`${prefix} with status ${status} (${statusText}) for URL: ${url}. Response: ${response.trim()}`;const XHR_REQUEST_ERROR=(prefix,e,url)=>`${prefix} due to timeout or no connection (${e?e.type:''}) at the client side for URL: ${url}`;const XHR_SEND_ERROR=(prefix,url)=>`${prefix} for URL: ${url}`;const STORE_DATA_SAVE_ERROR=key=>`Failed to save the value for "${key}" to storage`;const STORE_DATA_FETCH_ERROR=key=>`Failed to retrieve or parse data for "${key}" from storage`;const DATA_SERVER_URL_INVALID_ERROR=(context,url)=>`${context}${LOG_CONTEXT_SEPARATOR}The server side cookies functionality is disabled as the provided data server URL, "${url}" is invalid.`;const DATA_SERVER_REQUEST_FAIL_ERROR=status=>`The server responded with status ${status} while setting the cookies. As a fallback, the cookies will be set client side.`;const FAILED_SETTING_COOKIE_FROM_SERVER_ERROR=key=>`The server failed to set the ${key} cookie. As a fallback, the cookies will be set client side.`;const FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR=`Failed to set/remove cookies via server. As a fallback, the cookies will be managed client side.`;const COLLAPSED_COOKIE_BATCH_ERROR=(missingCookies,batchSize)=>`The server did not set ${missingCookies.length} of the ${batchSize} cookies sent in one request: ${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
|
|
633
|
-
const STORAGE_TYPE_VALIDATION_WARNING=(context,storageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage type "${storageType}" is not supported. Please choose one of the following supported types: "${SUPPORTED_STORAGE_TYPES}". The default storage type will be used instead.`;const UNSUPPORTED_STORAGE_ENTRY_TYPE_WARNING=(context,entry,storageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage type "${storageType}" configured for the entry "${entry}" is not supported. Please choose one of the following supported types: "${SUPPORTED_STORAGE_TYPES}". The default storage type will be used instead.`;const UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING=(context,selectedStorageEncryptionVersion,storageEncryptionVersionsToPluginNameMap,defaultVersion)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage encryption version "${selectedStorageEncryptionVersion}" is not supported. Please choose one of the following supported versions: "${Object.keys(storageEncryptionVersionsToPluginNameMap)}". The default version "${defaultVersion}" will be used instead.`;const STORAGE_DATA_MIGRATION_OVERRIDE_WARNING=(context,storageEncryptionVersion,defaultVersion)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage data migration has been disabled because the configured storage encryption version (${storageEncryptionVersion}) is not the latest (${defaultVersion}). To enable storage data migration, please update the storage encryption version to the latest version.`;const SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_ERROR=(context,providedCookieDomain,currentCookieDomain)=>`${context}${LOG_CONTEXT_SEPARATOR}The provided cookie domain (${providedCookieDomain}) does not match the current webpage's domain (${currentCookieDomain}). Hence, the cookies will be set client-side.`;const SERVER_SIDE_COOKIE_DATA_SERVICE_HOST_ERROR=(context,dataServiceHost,webpageHost)=>`${context}${LOG_CONTEXT_SEPARATOR}The data service host (${dataServiceHost}) cannot set cookies for the current webpage (${webpageHost}). Hence, the cookies will be set client-side instead of server-side.`;const RESERVED_KEYWORD_WARNING=(context,property,parentKeyPath,reservedElements)=>`${context}${LOG_CONTEXT_SEPARATOR}The "${property}" property defined under "${parentKeyPath}" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (${reservedElements}).`;const RESERVED_CUSTOM_CONTEXT_KEY_WARNING=(logContext,property)=>`${logContext}${LOG_CONTEXT_SEPARATOR}The top-level custom context property "${property}" is reserved and was ignored.`;const INVALID_CONTEXT_OBJECT_WARNING=logContext=>`${logContext}${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.`;const INVALID_CUSTOM_CONTEXT_WARNING=logContext=>`${logContext}${LOG_CONTEXT_SEPARATOR}Invalid custom context. Use a plain object without prototype pollution keys.`;const UNSUPPORTED_BEACON_API_WARNING=context=>`${context}${LOG_CONTEXT_SEPARATOR}The Beacon API is not supported by your browser. The events will be sent using XHR instead.`;const TIMEOUT_NOT_NUMBER_WARNING=(context,timeout,defaultValue)=>`${context}${LOG_CONTEXT_SEPARATOR}The session timeout value "${timeout}" is not a number. The default timeout of ${defaultValue} ms will be used instead.`;const CUT_OFF_DURATION_NOT_NUMBER_WARNING=(context,cutOffDuration,defaultValue)=>`${context}${LOG_CONTEXT_SEPARATOR}The session cut off duration value "${cutOffDuration}" is not a number. The default cut off duration of ${defaultValue} ms will be used instead.`;const CUT_OFF_DURATION_LESS_THAN_TIMEOUT_WARNING=(context,cutOffDuration,timeout)=>`${context}${LOG_CONTEXT_SEPARATOR}The session cut off duration value "${cutOffDuration}" ms is less than the session timeout value "${timeout}" ms. The cut off functionality will be disabled.`;const TIMEOUT_ZERO_WARNING=context=>`${context}${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.`;const TIMEOUT_NOT_RECOMMENDED_WARNING=(context,timeout,minTimeout)=>`${context}${LOG_CONTEXT_SEPARATOR}The session timeout value ${timeout} ms is less than the recommended minimum of ${minTimeout} ms. Please consider increasing the timeout value to ensure optimal performance and reliability.`;const INVALID_SESSION_ID_WARNING=(context,sessionId,minSessionIdLength)=>`${context}${LOG_CONTEXT_SEPARATOR}The provided session ID (${sessionId}) is either invalid, not a positive integer, or not at least "${minSessionIdLength}" digits long. A new session ID will be auto-generated instead.`;const STORAGE_QUOTA_EXCEEDED_WARNING=context=>`${context}${LOG_CONTEXT_SEPARATOR}The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.`;const STORAGE_UNAVAILABLE_WARNING=(context,entry,selectedStorageType,finalStorageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage type "${selectedStorageType}" is not available for entry "${entry}". The SDK will initialize the entry with "${finalStorageType}" storage type instead.`;const CALLBACK_INVOKE_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}The callback threw an exception`;const INVALID_CONFIG_URL_WARNING=(context,configUrl)=>`${context}${LOG_CONTEXT_SEPARATOR}The provided source config URL "${configUrl}" is invalid. Using the default source config URL instead.`;const
|
|
697
|
+
const STORAGE_TYPE_VALIDATION_WARNING=(context,storageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage type "${storageType}" is not supported. Please choose one of the following supported types: "${SUPPORTED_STORAGE_TYPES}". The default storage type will be used instead.`;const UNSUPPORTED_STORAGE_ENTRY_TYPE_WARNING=(context,entry,storageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage type "${storageType}" configured for the entry "${entry}" is not supported. Please choose one of the following supported types: "${SUPPORTED_STORAGE_TYPES}". The default storage type will be used instead.`;const UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING=(context,selectedStorageEncryptionVersion,storageEncryptionVersionsToPluginNameMap,defaultVersion)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage encryption version "${selectedStorageEncryptionVersion}" is not supported. Please choose one of the following supported versions: "${Object.keys(storageEncryptionVersionsToPluginNameMap)}". The default version "${defaultVersion}" will be used instead.`;const STORAGE_DATA_MIGRATION_OVERRIDE_WARNING=(context,storageEncryptionVersion,defaultVersion)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage data migration has been disabled because the configured storage encryption version (${storageEncryptionVersion}) is not the latest (${defaultVersion}). To enable storage data migration, please update the storage encryption version to the latest version.`;const SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_ERROR=(context,providedCookieDomain,currentCookieDomain)=>`${context}${LOG_CONTEXT_SEPARATOR}The provided cookie domain (${providedCookieDomain}) does not match the current webpage's domain (${currentCookieDomain}). Hence, the cookies will be set client-side.`;const SERVER_SIDE_COOKIE_DATA_SERVICE_HOST_ERROR=(context,dataServiceHost,webpageHost)=>`${context}${LOG_CONTEXT_SEPARATOR}The data service host (${dataServiceHost}) cannot set cookies for the current webpage (${webpageHost}). Hence, the cookies will be set client-side instead of server-side.`;const RESERVED_KEYWORD_WARNING=(context,property,parentKeyPath,reservedElements)=>`${context}${LOG_CONTEXT_SEPARATOR}The "${property}" property defined under "${parentKeyPath}" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (${reservedElements}).`;const RESERVED_CUSTOM_CONTEXT_KEY_WARNING=(logContext,property)=>`${logContext}${LOG_CONTEXT_SEPARATOR}The top-level custom context property "${property}" is reserved and was ignored.`;const INVALID_CONTEXT_OBJECT_WARNING=logContext=>`${logContext}${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.`;const INVALID_CUSTOM_CONTEXT_WARNING=logContext=>`${logContext}${LOG_CONTEXT_SEPARATOR}Invalid custom context. Use a plain object without prototype pollution keys.`;const UNSUPPORTED_BEACON_API_WARNING=context=>`${context}${LOG_CONTEXT_SEPARATOR}The Beacon API is not supported by your browser. The events will be sent using XHR instead.`;const TIMEOUT_NOT_NUMBER_WARNING=(context,timeout,defaultValue)=>`${context}${LOG_CONTEXT_SEPARATOR}The session timeout value "${timeout}" is not a number. The default timeout of ${defaultValue} ms will be used instead.`;const CUT_OFF_DURATION_NOT_NUMBER_WARNING=(context,cutOffDuration,defaultValue)=>`${context}${LOG_CONTEXT_SEPARATOR}The session cut off duration value "${cutOffDuration}" is not a number. The default cut off duration of ${defaultValue} ms will be used instead.`;const CUT_OFF_DURATION_LESS_THAN_TIMEOUT_WARNING=(context,cutOffDuration,timeout)=>`${context}${LOG_CONTEXT_SEPARATOR}The session cut off duration value "${cutOffDuration}" ms is less than the session timeout value "${timeout}" ms. The cut off functionality will be disabled.`;const TIMEOUT_ZERO_WARNING=context=>`${context}${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.`;const TIMEOUT_NOT_RECOMMENDED_WARNING=(context,timeout,minTimeout)=>`${context}${LOG_CONTEXT_SEPARATOR}The session timeout value ${timeout} ms is less than the recommended minimum of ${minTimeout} ms. Please consider increasing the timeout value to ensure optimal performance and reliability.`;const INVALID_SESSION_ID_WARNING=(context,sessionId,minSessionIdLength)=>`${context}${LOG_CONTEXT_SEPARATOR}The provided session ID (${sessionId}) is either invalid, not a positive integer, or not at least "${minSessionIdLength}" digits long. A new session ID will be auto-generated instead.`;const STORAGE_QUOTA_EXCEEDED_WARNING=context=>`${context}${LOG_CONTEXT_SEPARATOR}The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.`;const STORAGE_UNAVAILABLE_WARNING=(context,entry,selectedStorageType,finalStorageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage type "${selectedStorageType}" is not available for entry "${entry}". The SDK will initialize the entry with "${finalStorageType}" storage type instead.`;const CALLBACK_INVOKE_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}The callback threw an exception`;const INVALID_CONFIG_URL_WARNING=(context,configUrl)=>`${context}${LOG_CONTEXT_SEPARATOR}The provided source config URL "${configUrl}" is invalid. Using the default source config URL instead.`;const UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY=(context,selectedStrategy,defaultStrategy)=>`${context}${LOG_CONTEXT_SEPARATOR}The pre-consent storage strategy "${selectedStrategy}" is not supported. Please choose one of the following supported strategies: "none, session, anonymousId". The default strategy "${defaultStrategy}" will be used instead.`;const DEPRECATED_PRE_CONSENT_STORAGE_STRATEGY=context=>`${context}${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.`;const UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE=(context,selectedDeliveryType,defaultDeliveryType)=>`${context}${LOG_CONTEXT_SEPARATOR}The pre-consent events delivery type "${selectedDeliveryType}" is not supported. Please choose one of the following supported types: "immediate, buffer". The default type "${defaultDeliveryType}" will be used instead.`;const DEPRECATED_PLUGIN_WARNING=(context,pluginName)=>`${context}${LOG_CONTEXT_SEPARATOR}${pluginName} plugin is deprecated. Please exclude it from the load API options.`;const generateMisconfiguredPluginsWarning=(context,configurationStatus,missingPlugins,shouldAddMissingPlugins)=>{const isSinglePlugin=missingPlugins.length===1;const pluginsString=isSinglePlugin?` '${missingPlugins[0]}' plugin was`:` ['${missingPlugins.join("', '")}'] plugins were`;const baseWarning=`${context}${LOG_CONTEXT_SEPARATOR}${configurationStatus}, but${pluginsString} not configured to load.`;if(shouldAddMissingPlugins){return `${baseWarning} So, ${isSinglePlugin?'the plugin':'those plugins'} will be loaded automatically.`;}return `${baseWarning} Ignore if this was intentional. Otherwise, consider adding ${isSinglePlugin?'it':'them'} to the 'plugins' load API option.`;};const PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING=context=>`${context}${LOG_CONTEXT_SEPARATOR}Page Unloaded event can only be tracked when the Beacon transport is active. Please enable "useBeacon" load API option.`;const UNKNOWN_PLUGINS_WARNING=(context,unknownPlugins)=>`${context}${LOG_CONTEXT_SEPARATOR}Ignoring unknown plugins: ${unknownPlugins.join(', ')}.`;const REMOTE_PLUGIN_LOAD_ERROR=(context,pluginName,reason)=>`${context}${LOG_CONTEXT_SEPARATOR}Failed to load plugin "${pluginName}" - ${reason}`;const NO_PLUGIN_FACTORY_EXPORTED_REASON='the module exported no plugin factory';const UNAVAILABLE_PLUGINS_ERROR=(context,unavailablePlugins)=>`${context}${LOG_CONTEXT_SEPARATOR}Failed to load the following unavailable local plugins: ${unavailablePlugins.join(', ')}. Some features of the SDK may not work as expected. Make sure you are using the correct SDK bundle variant.`;const CUSTOM_INTEGRATION_CANNOT_BE_ADDED_ERROR=(context,destinationId)=>`${context}${LOG_CONTEXT_SEPARATOR}Cannot add custom integration for destination ID "${destinationId}" after the SDK is loaded.`;
|
|
634
698
|
|
|
635
699
|
const DEFAULT_INTEGRATIONS_CONFIG={All:true};
|
|
636
700
|
|
|
@@ -645,7 +709,9 @@ const CDN_INT_DIR='js-integrations';const CDN_PLUGINS_DIR='plugins';const URL_PA
|
|
|
645
709
|
'(\\#[-a-zA-Z\\d_]*)?$')// fragment locator
|
|
646
710
|
;
|
|
647
711
|
|
|
648
|
-
const BUILD_TYPE='modern';const SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';const CDN_ARCH_VERSION_DIR='v3';const DEFAULT_INTEGRATION_SDKS_URL=`${SDK_CDN_BASE_URL}/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${CDN_INT_DIR}`;const DEFAULT_PLUGINS_URL=`${SDK_CDN_BASE_URL}/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${CDN_PLUGINS_DIR}`;const DEFAULT_CONFIG_BE_URL='https://api.rudderstack.com'
|
|
712
|
+
const BUILD_TYPE='modern';const SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';const CDN_ARCH_VERSION_DIR='v3';const DEFAULT_INTEGRATION_SDKS_URL=`${SDK_CDN_BASE_URL}/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${CDN_INT_DIR}`;const DEFAULT_PLUGINS_URL=`${SDK_CDN_BASE_URL}/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${CDN_PLUGINS_DIR}`;const DEFAULT_CONFIG_BE_URL='https://api.rudderstack.com';// Mirrors remotePluginsExportsFilename in rollup.config.mjs, which builds the URL
|
|
713
|
+
// the generated federation code requests at runtime.
|
|
714
|
+
const REMOTE_PLUGINS_ENTRY_FILE='rsa-plugins.js';
|
|
649
715
|
|
|
650
716
|
const DEFAULT_STORAGE_ENCRYPTION_VERSION='v3';const DEFAULT_DATA_PLANE_EVENTS_TRANSPORT='xhr';const ConsentManagersToPluginNameMap={iubenda:'IubendaConsentManager',oneTrust:'OneTrustConsentManager',ketch:'KetchConsentManager',custom:'CustomConsentManager'};const StorageEncryptionVersionsToPluginNameMap={[DEFAULT_STORAGE_ENCRYPTION_VERSION]:'StorageEncryption',legacy:'StorageEncryptionLegacy'};const DataPlaneEventsTransportToPluginNameMap={[DEFAULT_DATA_PLANE_EVENTS_TRANSPORT]:'XhrQueue',beacon:'BeaconQueue'};const DEFAULT_DATA_SERVICE_ENDPOINT='rsaRequest';const METRICS_SERVICE_ENDPOINT='rsaMetrics';const CUSTOM_DEVICE_MODE_DESTINATION_DISPLAY_NAME='Custom Device Mode';
|
|
651
717
|
|
|
@@ -656,7 +722,7 @@ anonymousId:false,initialReferrer:false,initialReferringDomain:false}});const SE
|
|
|
656
722
|
|
|
657
723
|
const 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)};
|
|
658
724
|
|
|
659
|
-
const 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),
|
|
725
|
+
const 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({})};
|
|
660
726
|
|
|
661
727
|
const reportingState={isErrorReportingEnabled:y(false),isMetricsReportingEnabled:y(false),breadcrumbs:y([])};
|
|
662
728
|
|
|
@@ -688,9 +754,11 @@ const dataPlaneEventsState={eventsQueuePluginName:y(undefined),deliveryEnabled:y
|
|
|
688
754
|
|
|
689
755
|
const autoTrackState={enabled:y(false),pageLifecycle:{enabled:y(false),pageViewId:y(undefined),pageLoadedTimestamp:y(undefined)}};
|
|
690
756
|
|
|
691
|
-
const 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};const state={
|
|
757
|
+
const 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};const state=_objectSpread2({},clone(defaultStateValues));
|
|
692
758
|
|
|
693
|
-
const CHROME_STACK_LINE_RE=/^\s*at /;const SAFARI_NATIVE_RE=/^(eval@)?(\[native code])?$/;const
|
|
759
|
+
const CHROME_STACK_LINE_RE=/^\s*at /;const SAFARI_NATIVE_RE=/^(eval@)?(\[native code])?$/;const DIGITS_RE=/^\d+$/;function extractLocation(urlLike){if(!(urlLike!==null&&urlLike!==void 0&&urlLike.includes(':'))){return [urlLike||undefined,undefined,undefined];}const 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,
|
|
760
|
+
// colons included, is the file. A url keeps its scheme because "//host" is not digits.
|
|
761
|
+
const segments=normalizedUrlLike.split(':');const 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(/,.*/,'');}const sanitized=line.replace(/^\s+/,'').replace(/\(eval code/g,'(').replace(/^.*?\s+/,'');const parenLoc=/ (\(.+\)$)/.exec(sanitized);const withoutLoc=parenLoc?sanitized.replace(parenLoc[0],''):sanitized;const[rawFile,lineNumber,columnNumber]=extractLocation(parenLoc?parenLoc[1]:sanitized);const functionName=parenLoc&&withoutLoc||undefined;const fileName=rawFile==='eval'||rawFile==='<anonymous>'?undefined:rawFile;return {functionName,fileName,lineNumber,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};}const atIndex=line.lastIndexOf('@');const functionName=atIndex>0?line.slice(0,atIndex):undefined;const[fileName,lineNumber,columnNumber]=extractLocation(line.slice(atIndex+1));return {functionName,fileName,lineNumber,columnNumber};}/**
|
|
694
762
|
* Parses an Error object's stack trace into structured frames.
|
|
695
763
|
* Supports V8/Chromium (Chrome, Edge, Node) and SpiderMonkey/WebKit (Firefox, Safari) formats.
|
|
696
764
|
* Throws if the error has no stack property.
|
|
@@ -700,13 +768,15 @@ const GLOBAL_CODE='global code';const normalizeFunctionName=name=>{if(isDefined(
|
|
|
700
768
|
// - non-error exception thrown from global code in FF
|
|
701
769
|
// This adds one.
|
|
702
770
|
if(f.lineNumber&&f.lineNumber>-1&&!f.file&&!f.method){f.file=GLOBAL_CODE;}return f;};const ensureString=str=>isString(str)?str:'';function createException(errorClass,errorMessage,msgPrefix,stacktrace){return {errorClass:ensureString(errorClass),message:`${msgPrefix}${ensureString(errorMessage)}`,type:'browserjs',stacktrace:stacktrace.reduce((accum,frame)=>{const f=formatStackframe(frame);// don't include a stackframe if none of its properties are defined
|
|
703
|
-
try{if(JSON.stringify(f)==='{}')return accum;return accum.concat(f);}catch{return accum;}},[])};}const normalizeError=(maybeError,logger)=>{let error;if(isTypeOfError(maybeError)&&isString(getStacktrace(maybeError))){error=maybeError;}else {logger.warn(NON_ERROR_WARNING(ERROR_HANDLER,stringifyWithoutCircular(maybeError)));error=undefined;}return error;};const createBugsnagException=(error,msgPrefix)=>{try{const stacktrace=parseStackTrace(error);return createException(error.name,error.message,msgPrefix,stacktrace);}catch{return createException(error.name,error.message,msgPrefix,[]);}};
|
|
771
|
+
try{if(JSON.stringify(f)==='{}')return accum;return accum.concat(f);}catch(_unused){return accum;}},[])};}const normalizeError=(maybeError,logger)=>{let error;if(isTypeOfError(maybeError)&&isString(getStacktrace(maybeError))){error=maybeError;}else {logger.warn(NON_ERROR_WARNING(ERROR_HANDLER,stringifyWithoutCircular(maybeError)));error=undefined;}return error;};const createBugsnagException=(error,msgPrefix)=>{try{const stacktrace=parseStackTrace(error);return createException(error.name,error.message,msgPrefix,stacktrace);}catch(_unused2){return createException(error.name,error.message,msgPrefix,[]);}};
|
|
704
772
|
|
|
705
773
|
/**
|
|
706
774
|
* Utility to parse XHR JSON response
|
|
707
775
|
*/const responseTextToJson=(responseText,onError)=>{try{return JSON.parse(responseText||'');}catch(err){const error=getMutatedError(err,'Failed to parse response data');onError(error);}return undefined;};
|
|
708
776
|
|
|
709
|
-
const FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';const PLUGINS_LOAD_FAILURE_MESSAGES=[
|
|
777
|
+
const FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';const PLUGINS_LOAD_FAILURE_MESSAGES=[// Chromium
|
|
778
|
+
/Failed to fetch dynamically imported module: .*/,// Firefox
|
|
779
|
+
/error loading dynamically imported module: .*/];const 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 .*/];const ERROR_MESSAGES_TO_BE_FILTERED=[new RegExp(`${FAILED_REQUEST_ERR_MSG_PREFIX}.*`),/A script with the id .* is already loaded\./];const SCRIPT_LOAD_FAILURE_MESSAGES=[...PLUGINS_LOAD_FAILURE_MESSAGES,...INTEGRATIONS_LOAD_FAILURE_MESSAGES];const INTEGRATIONS_ERROR_CATEGORY='integrations';const SDK_ERROR_CATEGORY='sdk';const DEFAULT_ERROR_CATEGORY=SDK_ERROR_CATEGORY;
|
|
710
780
|
|
|
711
781
|
const DEFAULT_XHR_REQUEST_OPTIONS={headers:{Accept:'application/json','Content-Type':'application/json;charset=UTF-8'},method:'GET'};/**
|
|
712
782
|
* Utility to create request configuration based on default options
|
|
@@ -716,7 +786,7 @@ const DEFAULT_XHR_REQUEST_OPTIONS={headers:{Accept:'application/json','Content-T
|
|
|
716
786
|
* this is not supported by our sourceConfig API
|
|
717
787
|
*/const xhrRequest=(options,timeout=DEFAULT_XHR_TIMEOUT_MS,logger)=>new Promise((resolve,reject)=>{let payload;if(options.sendRawData===true){payload=options.data;}else {payload=stringifyWithoutCircular(options.data,false,[],logger);if(isNull(payload)){reject({error:new Error(XHR_PAYLOAD_PREP_ERROR),undefined,options});// return and don't process further if the payload could not be stringified
|
|
718
788
|
return;}}const xhr=new XMLHttpRequest();// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
719
|
-
const xhrReject=e=>{reject({error:new Error(XHR_DELIVERY_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,xhr.status,xhr.statusText,options.url,xhr.responseText)),xhr,options});};const xhrError=e=>{reject({error:new Error(XHR_REQUEST_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,e,options.url)),xhr,options
|
|
789
|
+
const xhrReject=e=>{reject({error:new Error(XHR_DELIVERY_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,xhr.status,xhr.statusText,options.url,xhr.responseText)),xhr,options});};const xhrError=e=>{reject(_objectSpread2({error:new Error(XHR_REQUEST_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,e,options.url)),xhr,options},(e===null||e===void 0?void 0:e.type)==='timeout'?{timedOut:true}:{}));};xhr.ontimeout=xhrError;xhr.onerror=xhrError;xhr.onload=()=>{if(xhr.status>=200&&xhr.status<400){resolve({response:xhr.responseText,xhr,options});}else {xhrReject();}};xhr.open(options.method,options.url,true);if(options.withCredentials===true){xhr.withCredentials=true;}// The timeout property may be set only in the time interval between a call to the open method
|
|
720
790
|
// and the first call to the send method in legacy browsers
|
|
721
791
|
xhr.timeout=timeout;Object.keys(options.headers).forEach(headerName=>{if(options.headers[headerName]){xhr.setRequestHeader(headerName,options.headers[headerName]);}});try{xhr.send(payload);}catch(err){reject({error:getMutatedError(err,XHR_SEND_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,options.url)),xhr,options});}});
|
|
722
792
|
|
|
@@ -724,14 +794,14 @@ xhr.timeout=timeout;Object.keys(options.headers).forEach(headerName=>{if(options
|
|
|
724
794
|
* Service to handle data communication with APIs
|
|
725
795
|
*/class HttpClient{constructor(logger){this.logger=logger;this.onError=this.onError.bind(this);}init(errorHandler){this.errorHandler=errorHandler;}/**
|
|
726
796
|
* Implement requests in a blocking way
|
|
727
|
-
*/async getData(config){const{url,options,timeout,isRawResponse}=config;try{const data=await xhrRequest(createXhrRequestOptions(url,options,this.
|
|
797
|
+
*/async getData(config){const{url,options,timeout,isRawResponse,skipAuthHeader}=config;try{const data=await xhrRequest(createXhrRequestOptions(url,options,this.getAuthHeader(skipAuthHeader)),timeout,this.logger);return {data:isRawResponse?data.response:responseTextToJson(data.response,this.onError),details:data};}catch(reason){return {data:undefined,details:reason};}}/**
|
|
728
798
|
* Implement requests in a non-blocking way
|
|
729
|
-
*/getAsyncData(config){const{callback,url,options,timeout,isRawResponse}=config;const isFireAndForget=!isFunction(callback);xhrRequest(createXhrRequestOptions(url,options,this.
|
|
799
|
+
*/getAsyncData(config){const{callback,url,options,timeout,isRawResponse,skipAuthHeader}=config;const isFireAndForget=!isFunction(callback);xhrRequest(createXhrRequestOptions(url,options,this.getAuthHeader(skipAuthHeader)),timeout,this.logger).then(data=>{if(!isFireAndForget){callback(isRawResponse?data.response:responseTextToJson(data.response,this.onError),data);}},data=>{if(!isFireAndForget){callback(undefined,data);}})// Exceptions thrown by the callback must never re-enter it
|
|
730
800
|
.catch(this.onError);}/**
|
|
731
801
|
* Handle errors
|
|
732
|
-
*/onError(error,groupingHash){this.errorHandler
|
|
802
|
+
*/onError(error,groupingHash){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError({error,context:HTTP_CLIENT,groupingHash});}/**
|
|
733
803
|
* Set basic authentication header (eg writekey)
|
|
734
|
-
*/setAuthHeader(value,noBtoa=false){const authVal=noBtoa?value:toBase64(`${value}:`);this.basicAuthHeader=`Basic ${authVal}`;}/**
|
|
804
|
+
*/getAuthHeader(skipAuthHeader){return skipAuthHeader===true?undefined:this.basicAuthHeader;}setAuthHeader(value,noBtoa=false){const authVal=noBtoa?value:toBase64(`${value}:`);this.basicAuthHeader=`Basic ${authVal}`;}/**
|
|
735
805
|
* Clear basic authentication header
|
|
736
806
|
*/resetAuthHeader(){this.basicAuthHeader=undefined;}}const defaultHttpClient=new HttpClient(defaultLogger);
|
|
737
807
|
|
|
@@ -746,58 +816,79 @@ const APP_STATE_EXCLUDE_KEYS=['userId','userTraits','groupId','groupTraits','ano
|
|
|
746
816
|
'customContext',// customer-provided event context
|
|
747
817
|
'traits','authToken'];const NOTIFIER_NAME='RudderStack JavaScript SDK';const SDK_GITHUB_URL='git+https://github.com/rudderlabs/rudder-sdk-js.git';const SOURCE_NAME='js';
|
|
748
818
|
|
|
749
|
-
const detectAdBlockers=httpClient=>{state.capabilities.isAdBlockerDetectionInProgress.value=true;try{// Apparently, '?view=ad' is a query param that is blocked by majority of adblockers
|
|
750
|
-
// Use source config URL here as it is very unlikely to be blocked by adblockers
|
|
751
|
-
// Only the extra query param should make it vulnerable to adblockers
|
|
752
|
-
// This will work even if the users proxies it.
|
|
753
|
-
// The edge case where this doesn't work is when HEAD method is not allowed by the server (user's)
|
|
754
|
-
const baseUrl=new URL(state.lifecycle.sourceConfigUrl.value);const url=`${baseUrl.origin}${baseUrl.pathname}?view=ad`;httpClient.getAsyncData({url,options:{// We actually don't need the response from the request, so we are using HEAD
|
|
755
|
-
method:'HEAD',headers:{'Content-Type':undefined}},isRawResponse:true,callback:(result,details)=>{state.capabilities.isAdBlockerDetectionInProgress.value=false;// not ad blocked if the request is successful or it is not internally redirected on the client side
|
|
756
|
-
// Often adblockers instead of blocking the request, they redirect it to an internal URL
|
|
757
|
-
state.capabilities.isAdBlocked.value=details?.error!==undefined||details?.xhr?.responseURL!==url;}});}catch(err){// Reset the flag to prevent blocking future detection attempts
|
|
758
|
-
state.capabilities.isAdBlockerDetectionInProgress.value=false;// Re-throw the error to be handled by the caller
|
|
759
|
-
throw err;}};
|
|
760
|
-
|
|
761
819
|
const getErrInstance=(err,errorType)=>{switch(errorType){case ErrorType.UNHANDLEDEXCEPTION:{const{error}=err;return error||err;}case ErrorType.UNHANDLEDREJECTION:{return err.reason;}case ErrorType.HANDLEDEXCEPTION:default:return err;}};const createNewBreadcrumb=message=>({type:'manual',name:message,timestamp:new Date(),metaData:{}});/**
|
|
762
820
|
* A function to get the Bugsnag release stage for the current environment
|
|
763
821
|
* @param getHostName Optional function to get the hostname (primarily for testing)
|
|
764
822
|
* @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)
|
|
765
|
-
*/const getReleaseStage=(getHostName=()=>window.location.hostname)=>{const host=getHostName();return !host||host&&DEV_HOSTS.includes(host)?'development':'production';};const getAppStateForMetadata=state=>{const stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS);return stateStr!==null?JSON.parse(stateStr):{};};const getURLWithoutQueryString=()=>{const url=globalThis.location.href.split('?');return url[0];};const getUserDetails=(source,session,lifecycle,autoTrack)=>
|
|
766
|
-
//
|
|
767
|
-
|
|
768
|
-
*
|
|
769
|
-
*
|
|
770
|
-
*
|
|
771
|
-
*
|
|
772
|
-
*
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
const
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
823
|
+
*/const getReleaseStage=(getHostName=()=>window.location.hostname)=>{const host=getHostName();return !host||host&&DEV_HOSTS.includes(host)?'development':'production';};const getAppStateForMetadata=state=>{const stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS);return stateStr!==null?JSON.parse(stateStr):{};};const getURLWithoutQueryString=()=>{const url=globalThis.location.href.split('?');return url[0];};const getUserDetails=(source,session,lifecycle,autoTrack)=>{var _source$value$id,_source$value,_session$sessionInfo$,_autoTrack$pageLifecy,_source$value$name,_source$value2;return {id:`${(_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}..${(_session$sessionInfo$=session.sessionInfo.value.id)!==null&&_session$sessionInfo$!==void 0?_session$sessionInfo$:'NA'}..${(_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'};};const 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()};};const getBugsnagErrorEvent=(exception,errorState,state,groupingHash)=>{const{context,lifecycle,session,source,reporting,autoTrack}=state;const{app,locale,userAgent,timezone,screen,library}=context;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,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
|
|
824
|
+
// is the fallback for both, so it counts for either.
|
|
825
|
+
const SCRIPT_CSP_DIRECTIVES=['script-src-elem','script-src','default-src'];const CONNECT_CSP_DIRECTIVES=['connect-src','default-src'];const hasCspViolation=(state,url,directives)=>state.capabilities.cspViolations.value.some(violation=>directives.includes(violation.directive)&&isSameOrUnder(url,violation.blockedURL));/**
|
|
826
|
+
* Whether a URL is the blocked one or sits beneath it.
|
|
827
|
+
*
|
|
828
|
+
* Browsers strip a cross-origin blockedURI down to its origin, so a stored entry
|
|
829
|
+
* is often a prefix of the failing URL rather than equal to it. Matching on a
|
|
830
|
+
* bare string prefix is too loose: an origin entry would swallow a look-alike
|
|
831
|
+
* host, and a script entry would swallow its own source map. The prefix only
|
|
832
|
+
* counts when the next character starts a new path, query or fragment.
|
|
833
|
+
*/const isSameOrUnder=(url,blockedURL)=>{if(url===blockedURL){return true;}if(!url.startsWith(blockedURL)){return false;}const boundary=url.charAt(blockedURL.length);return boundary==='/'||boundary==='?'||boundary==='#';};// Probes already in flight, keyed by URL. Concurrent failures share one request
|
|
834
|
+
// rather than each firing its own HEAD and possibly reaching different verdicts
|
|
835
|
+
// about the same URL.
|
|
836
|
+
const inFlightProbes=new Map();/**
|
|
837
|
+
* Probes the URL that failed to load and records what came back, so the report
|
|
838
|
+
* can tell a request that never left the client from one the CDN answered with
|
|
839
|
+
* an error. The failed URL is probed rather than a fixed path: plugins and
|
|
840
|
+
* integrations sit under different prefixes and can be blocked independently.
|
|
841
|
+
*/const probeSdkCdn=(state,httpClient,url,done)=>{if(isDefined(state.capabilities.sdkCdnProbe.value[url])){done();return;}const waiting=inFlightProbes.get(url);if(waiting){waiting.push(done);return;}inFlightProbes.set(url,[done]);httpClient.getAsyncData({url,// The CDN refuses preflight, so this has to stay a simple request: a HEAD
|
|
842
|
+
// carrying none of the headers the client would otherwise add.
|
|
843
|
+
skipAuthHeader:true,options:{method:'HEAD',headers:{'Content-Type':undefined,Accept:undefined}},isRawResponse:true,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
|
|
844
|
+
// answers instead of dropping it lands on a URL outside the CDN. An
|
|
845
|
+
// ordinary redirect that stays under the CDN -- canonicalisation, a signed
|
|
846
|
+
// URL -- is the CDN answering and must not be mistaken for one.
|
|
847
|
+
const 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;const 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),{},{[url]:{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)}});const waiters=(_inFlightProbes$get=inFlightProbes.get(url))!==null&&_inFlightProbes$get!==void 0?_inFlightProbes$get:[];inFlightProbes.delete(url);waiters.forEach(waiter=>waiter());}});};/**
|
|
779
848
|
* A function to determine whether the error should be promoted to notify or not.
|
|
780
|
-
*
|
|
781
|
-
*
|
|
782
|
-
*
|
|
849
|
+
* Script load failures from a host other than the RS CDN are not promoted.
|
|
850
|
+
* For those from the RS CDN, a probe of the failed URL is awaited so its result
|
|
851
|
+
* is carried in the report, and the error is suppressed in exactly two cases: a
|
|
852
|
+
* CSP violation covering that URL, or a probe whose shape nothing server side
|
|
853
|
+
* produces -- a request that never reached the CDN, or one answered by
|
|
854
|
+
* something else. Any status the CDN itself returned is promoted.
|
|
855
|
+
* The generic ad blocker signal is deliberately not consulted: it probes the
|
|
856
|
+
* source config host, and a client that cannot reach the CDN cannot be told
|
|
857
|
+
* apart from a CDN outage.
|
|
858
|
+
* Errors from other causes are promoted unless explicitly denylisted.
|
|
783
859
|
* @param {Error} exception The error object
|
|
784
860
|
* @param {ApplicationState} state The application state
|
|
785
861
|
* @param {IHttpClient} httpClient The HTTP client instance
|
|
786
862
|
* @returns A promise that resolves to a boolean indicating whether the error should be promoted to notify or not
|
|
787
863
|
*/const checkIfAllowedToBeNotified=(exception,state,httpClient)=>{const errMsg=exception.message;return new Promise(resolve=>{// Filter out script load failures that are not from the RS CDN.
|
|
788
|
-
if(SCRIPT_LOAD_FAILURE_MESSAGES.some(regex=>regex.test(errMsg))){const extractedURL=/https?:\/\/[^\s"'(),;<>[\]{}]+/.exec(errMsg)
|
|
789
|
-
|
|
790
|
-
|
|
864
|
+
if(SCRIPT_LOAD_FAILURE_MESSAGES.some(regex=>regex.test(errMsg))){var _exec;const 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
|
|
865
|
+
// report. The generic ad blocker signal is deliberately not consulted:
|
|
866
|
+
// it probes the source config host rather than the CDN, and a client
|
|
867
|
+
// that cannot reach the CDN is indistinguishable from a CDN outage, so
|
|
868
|
+
// it must not suppress the error.
|
|
869
|
+
probeSdkCdn(state,httpClient,extractedURL,()=>{// Only a script directive can explain a failed script load.
|
|
870
|
+
const isCspBlocked=hasCspViolation(state,extractedURL,SCRIPT_CSP_DIRECTIVES);// A probe that never reached the CDN, or that was answered by
|
|
871
|
+
// something else, is a client-side failure: nothing server side
|
|
872
|
+
// produces either shape. A timeout is not attributable, and any
|
|
873
|
+
// status the CDN itself returned is worth reporting.
|
|
874
|
+
const probe=state.capabilities.sdkCdnProbe.value[extractedURL];// Unless CSP stopped the probe itself. connect-src governs the probe
|
|
875
|
+
// while script-src governs the import, and a page can allow the
|
|
876
|
+
// import and deny the probe -- then status 0 says nothing about the
|
|
877
|
+
// load that actually failed, so the probe is inconclusive and the
|
|
878
|
+
// error stands on its own.
|
|
879
|
+
const isProbeCspBlocked=hasCspViolation(state,extractedURL,CONNECT_CSP_DIRECTIVES);const 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.
|
|
791
880
|
resolve(false);}}else {// Allow the error to be notified if no URL could be extracted from the error message
|
|
792
881
|
resolve(true);}}else {resolve(!ERROR_MESSAGES_TO_BE_FILTERED.some(e=>e.test(errMsg)));}});};/**
|
|
793
882
|
* A function to get the directory name from a file path.
|
|
794
883
|
* @param {string} filePath The file path
|
|
795
884
|
* @returns The directory name or undefined if the file path is invalid
|
|
796
|
-
*/const getDirectoryName=filePath=>{if(!filePath){return undefined;}const paths=filePath.split('/')
|
|
885
|
+
*/const getDirectoryName=filePath=>{if(!filePath){return undefined;}const paths=filePath.split('/');// Not `.at(-2)`: Array.prototype.at is neither transpiled nor polyfilled
|
|
886
|
+
return paths[paths.length-2];// NOSONAR
|
|
887
|
+
};/**
|
|
797
888
|
* A function to get the top stack path from the exception.
|
|
798
889
|
* @param {Exception} exception The exception object
|
|
799
890
|
* @returns The top stack path or undefined if the exception is invalid
|
|
800
|
-
*/const getTopStackPath=exception=>{const errorOrigin=exception.stacktrace[0]
|
|
891
|
+
*/const getTopStackPath=exception=>{var _exception$stacktrace;const errorOrigin=(_exception$stacktrace=exception.stacktrace[0])===null||_exception$stacktrace===void 0?void 0:_exception$stacktrace.file;if(!errorOrigin||typeof errorOrigin!=='string'){return undefined;}return errorOrigin;};/**
|
|
801
892
|
* A function to determine if the error is from Rudder SDK
|
|
802
893
|
* @param {Error} exception
|
|
803
894
|
* @returns
|
|
@@ -814,15 +905,17 @@ resolve(true);}}else {resolve(!ERROR_MESSAGES_TO_BE_FILTERED.some(e=>e.test(errM
|
|
|
814
905
|
|
|
815
906
|
/**
|
|
816
907
|
* A service to handle errors
|
|
817
|
-
*/class ErrorHandler{
|
|
818
|
-
constructor(httpClient,logger){this.httpClient=httpClient;this.logger=logger;}/**
|
|
908
|
+
*/class ErrorHandler{// If no logger is passed errors will be thrown as unhandled error
|
|
909
|
+
constructor(httpClient,logger){_defineProperty(this,"initialized",false);this.httpClient=httpClient;this.logger=logger;}/**
|
|
819
910
|
* Initializes the error handler by attaching global error listeners.
|
|
820
911
|
* This method should be called once after construction.
|
|
821
912
|
*/init(){if(this.initialized){return;}this.attachErrorListeners();this.initialized=true;}/**
|
|
822
913
|
* Attach error listeners to the global window object
|
|
823
|
-
*/attachErrorListeners(){globalThis.addEventListener('error',event=>{this.onError({error:event,context:ERROR_HANDLER,errorType:ErrorType.UNHANDLEDEXCEPTION});});globalThis.addEventListener('unhandledrejection',event=>{this.onError({error:event,context:ERROR_HANDLER,errorType:ErrorType.UNHANDLEDREJECTION});});// Listen to CSP violations
|
|
824
|
-
//
|
|
825
|
-
|
|
914
|
+
*/attachErrorListeners(){globalThis.addEventListener('error',event=>{this.onError({error:event,context:ERROR_HANDLER,errorType:ErrorType.UNHANDLEDEXCEPTION});});globalThis.addEventListener('unhandledrejection',event=>{this.onError({error:event,context:ERROR_HANDLER,errorType:ErrorType.UNHANDLEDREJECTION});});// Listen to CSP violations for RS CDN URLs, recording the directive that
|
|
915
|
+
// rejected each one. script-src governs a plugin import and connect-src the
|
|
916
|
+
// reachability probe, so without the directive a probe-only violation looks
|
|
917
|
+
// identical to one that stopped the script.
|
|
918
|
+
document.addEventListener('securitypolicyviolation',event=>{const blockedURL=isString(event.blockedURI)?event.blockedURI:'';const directive=isString(event.effectiveDirective)?event.effectiveDirective:'';if(event.disposition!=='enforce'||!isSameOrUnder(blockedURL,SDK_CDN_BASE_URL)){return;}const isAlreadyRecorded=state.capabilities.cspViolations.value.some(violation=>violation.blockedURL===blockedURL&&violation.directive===directive);if(!isAlreadyRecorded){state.capabilities.cspViolations.value=[...state.capabilities.cspViolations.value,{blockedURL,directive}];}});}/**
|
|
826
919
|
* Handle errors
|
|
827
920
|
* @param errorInfo - The error information
|
|
828
921
|
* @param errorInfo.error - The error to handle
|
|
@@ -831,7 +924,7 @@ document.addEventListener('securitypolicyviolation',event=>{const blockedURL=isS
|
|
|
831
924
|
* @param errorInfo.errorType - The type of the error (handled or unhandled)
|
|
832
925
|
* @param errorInfo.groupingHash - The grouping hash of the error
|
|
833
926
|
* @param errorInfo.category - The category of the error (sdk or integrations)
|
|
834
|
-
*/async onError(errorInfo){try{const{error,context,customMessage,groupingHash,category}=errorInfo;const errorType=errorInfo.errorType
|
|
927
|
+
*/async onError(errorInfo){try{var _errorInfo$errorType;const{error,context,customMessage,groupingHash,category}=errorInfo;const errorType=(_errorInfo$errorType=errorInfo.errorType)!==null&&_errorInfo$errorType!==void 0?_errorInfo$errorType:ErrorType.HANDLEDEXCEPTION;const errInstance=getErrInstance(error,errorType);const normalizedError=normalizeError(errInstance,this.logger);if(isUndefined(normalizedError)){return;}const customMsgVal=customMessage?`${customMessage} - `:'';const errorMsgPrefix=`${context}${LOG_CONTEXT_SEPARATOR}${customMsgVal}`;const bsException=createBugsnagException(normalizedError,errorMsgPrefix);const stacktrace=getStacktrace(normalizedError);const isSdkDispatched=stacktrace.includes(MANUAL_ERROR_IDENTIFIER);// Filter errors that are not originated in the SDK.
|
|
835
928
|
// In case of NPM installations, the unhandled errors from the SDK cannot be identified
|
|
836
929
|
// and will NOT be reported unless they occur in plugins or integrations.
|
|
837
930
|
if(!isSdkDispatched&&!isSDKError(bsException)&&errorType!==ErrorType.HANDLEDEXCEPTION){return;}if(state.reporting.isErrorReportingEnabled.value){const isAllowed=await checkIfAllowedToBeNotified(bsException,state,this.httpClient);if(isAllowed){const errorState={severity:'error',unhandled:errorType!==ErrorType.HANDLEDEXCEPTION,severityReason:{type:errorType}};// This will allow custom grouping of errors.
|
|
@@ -855,10 +948,10 @@ const defaultErrorHandler=new ErrorHandler(defaultHttpClient,defaultLogger);
|
|
|
855
948
|
// to next or return the value if it is the last one instead of an array per
|
|
856
949
|
// plugin that is the normal invoke
|
|
857
950
|
// TODO: add invoke method for extension point that we know only one plugin can be used. add invokeMultiple and invokeSingle methods
|
|
858
|
-
class PluginEngine{plugins
|
|
951
|
+
class PluginEngine{constructor(logger,options={}){_defineProperty(this,"plugins",[]);_defineProperty(this,"byName",{});_defineProperty(this,"cache",{});_defineProperty(this,"config",{throws:true});this.config=_objectSpread2({throws:true},options);this.logger=logger;}register(plugin,state){if(!plugin.name){const errorMessage=PLUGIN_NAME_MISSING_ERROR(PLUGIN_ENGINE);if(this.config.throws){throw new Error(errorMessage);}else {this.logger.error(errorMessage,plugin);return;}}if(this.byName[plugin.name]){const errorMessage=PLUGIN_ALREADY_EXISTS_ERROR(PLUGIN_ENGINE,plugin.name);if(this.config.throws){throw new Error(errorMessage);}else {this.logger.error(errorMessage);return;}}this.cache={};this.plugins=this.plugins.slice();let pos=this.plugins.length;this.plugins.forEach((pluginItem,index)=>{var _pluginItem$deps;if((_pluginItem$deps=pluginItem.deps)!==null&&_pluginItem$deps!==void 0&&_pluginItem$deps.includes(plugin.name)){pos=Math.min(pos,index);}});this.plugins.splice(pos,0,plugin);this.byName[plugin.name]=plugin;if(isFunction(plugin.initialize)){plugin.initialize(state);}}unregister(name){const plugin=this.byName[name];if(!plugin){const errorMessage=PLUGIN_NOT_FOUND_ERROR(PLUGIN_ENGINE,name);if(this.config.throws){throw new Error(errorMessage);}else {this.logger.error(errorMessage);return;}}const index=this.plugins.indexOf(plugin);if(index===-1){const errorMessage=PLUGIN_ENGINE_BUG_ERROR(PLUGIN_ENGINE,name);if(this.config.throws){throw new Error(errorMessage);}else {this.logger.error(errorMessage);return;}}this.cache={};delete this.byName[name];this.plugins=this.plugins.slice();this.plugins.splice(index,1);}getPlugin(name){return this.byName[name];}getPlugins(extPoint){const lifeCycleName=extPoint!==null&&extPoint!==void 0?extPoint:'.';if(!this.cache[lifeCycleName]){this.cache[lifeCycleName]=this.plugins.filter(plugin=>{var _plugin$deps;if((_plugin$deps=plugin.deps)!==null&&_plugin$deps!==void 0&&_plugin$deps.some(dependency=>!this.byName[dependency])){// If deps not exist, then not load it.
|
|
859
952
|
const notExistDeps=plugin.deps.filter(dependency=>!this.byName[dependency]);this.logger.error(PLUGIN_DEPS_ERROR(PLUGIN_ENGINE,plugin.name,notExistDeps));return false;}return lifeCycleName==='.'?true:hasValueByPath(plugin,lifeCycleName);});}return this.cache[lifeCycleName];}// This method allows to process this.plugins so that it could
|
|
860
953
|
// do some unified pre-process before application starts.
|
|
861
|
-
processRawPlugins(callback){callback(this.plugins);this.cache={};}invoke(extPoint,allowMultiple=true,...args){let extensionPointName=extPoint;if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_MISSING_ERROR);}const noCall=extensionPointName.startsWith('!');const throws=this.config.throws
|
|
954
|
+
processRawPlugins(callback){callback(this.plugins);this.cache={};}invoke(extPoint,allowMultiple=true,...args){var _this$config$throws;let extensionPointName=extPoint;if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_MISSING_ERROR);}const noCall=extensionPointName.startsWith('!');const throws=(_this$config$throws=this.config.throws)!==null&&_this$config$throws!==void 0?_this$config$throws:extensionPointName.endsWith('!');// eslint-disable-next-line unicorn/better-regex
|
|
862
955
|
extensionPointName=extensionPointName.replace(/(^!|!$)/g,'');if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_INVALID_ERROR);}const extensionPointNameParts=extensionPointName.split('.');extensionPointNameParts.pop();const pluginMethodPath=extensionPointNameParts.join('.');const pluginsToInvoke=allowMultiple?this.getPlugins(extensionPointName):[this.getPlugins(extensionPointName)[0]];return pluginsToInvoke.map(plugin=>{const method=getValueByPath(plugin,extensionPointName);if(!isFunction(method)||noCall){return method;}try{return method.apply(getValueByPath(plugin,pluginMethodPath),args);}catch(err){// When a plugin failed, doesn't break the app
|
|
863
956
|
if(throws){throw err;}else {this.logger.error(PLUGIN_INVOCATION_ERROR(PLUGIN_ENGINE,extensionPointName,plugin.name),err);}}return null;});}invokeSingle(extPoint,...args){return this.invoke(extPoint,false,...args)[0];}invokeMultiple(extPoint,...args){return this.invoke(extPoint,true,...args);}}const defaultPluginEngine=new PluginEngine(defaultLogger,{throws:true});
|
|
864
957
|
|
|
@@ -881,14 +974,15 @@ destination.config.useNativeSDK===true);const isHybridModeDestination=destinatio
|
|
|
881
974
|
* @param id The id of the destination
|
|
882
975
|
*
|
|
883
976
|
* @returns the user friendly id
|
|
884
|
-
*/const getDestinationUserFriendlyId=(displayName,id)
|
|
977
|
+
*/const getDestinationUserFriendlyId=(displayName,id)=>// displayName comes from the source config response, so it is not guaranteed to be a string
|
|
978
|
+
`${String(displayName!==null&&displayName!==void 0?displayName:'').replace(/ /g,'-')}___${id}`;
|
|
885
979
|
|
|
886
980
|
/**
|
|
887
981
|
* List of plugin names that are loaded as dynamic imports in modern builds
|
|
888
982
|
*/const pluginNamesList=['BeaconQueue','CustomConsentManager','DeviceModeDestinations','DeviceModeTransformation','ExternalAnonymousId','GoogleLinker','IubendaConsentManager','KetchConsentManager','NativeDestinationQueue','OneTrustConsentManager','StorageEncryption','StorageEncryptionLegacy','StorageMigrator','XhrQueue'];const deprecatedPluginsList=['Bugsnag','ErrorReporting'];
|
|
889
983
|
|
|
890
984
|
const remotesMap = {
|
|
891
|
-
'rudderAnalyticsRemotePlugins':{url:()=>Promise.resolve(window.RudderStackGlobals && window.RudderStackGlobals.app && window.RudderStackGlobals.app.pluginsCDNPath ? `${window.RudderStackGlobals.app.pluginsCDNPath}/rsa-plugins.js` : `https://cdn.rudderlabs.com/v3
|
|
985
|
+
'rudderAnalyticsRemotePlugins':{url:()=>Promise.resolve(window.RudderStackGlobals && window.RudderStackGlobals.app && window.RudderStackGlobals.app.pluginsCDNPath ? `${window.RudderStackGlobals.app.pluginsCDNPath}/rsa-plugins.js` : `https://cdn.rudderlabs.com/v3//rsa-plugins.js`),format:'esm',from:'vite'}
|
|
892
986
|
};
|
|
893
987
|
|
|
894
988
|
function merge(obj1, obj2) {
|
|
@@ -959,7 +1053,7 @@ const remotesMap = {
|
|
|
959
1053
|
* Map of optional plugin names and direct imports for legacy builds
|
|
960
1054
|
*/const getOptionalPluginsMap=()=>{{return {};}};/**
|
|
961
1055
|
* Map of optional plugin names and dynamic imports for modern builds
|
|
962
|
-
*/const getRemotePluginsMap=activePluginNames=>{return federatedModulesBuildPluginImports
|
|
1056
|
+
*/const getRemotePluginsMap=activePluginNames=>{return (federatedModulesBuildPluginImports===null||federatedModulesBuildPluginImports===void 0?void 0:federatedModulesBuildPluginImports(activePluginNames))||{};};const pluginsInventory=_objectSpread2(_objectSpread2({},getMandatoryPluginsMap()),getOptionalPluginsMap());const remotePluginsInventory=activePluginNames=>_objectSpread2({},getRemotePluginsMap(activePluginNames));
|
|
963
1057
|
|
|
964
1058
|
// TODO: add retry mechanism for getting remote plugins
|
|
965
1059
|
// TODO: add timeout error mechanism for marking remote plugins that failed to load as failed in state
|
|
@@ -985,8 +1079,26 @@ const availablePlugins=[...Object.keys(pluginsInventory),...pluginNamesList];con
|
|
|
985
1079
|
* Register plugins that are direct imports to PluginEngine
|
|
986
1080
|
*/registerLocalPlugins(){const unavailablePlugins=[];Object.entries(pluginsInventory).forEach(([pluginName,localPlugin])=>{if(state.plugins.activePlugins.value.includes(pluginName)){if(isFunction(localPlugin)){this.register([localPlugin()]);}else {unavailablePlugins.push(pluginName);}}});if(unavailablePlugins.length>0){state.plugins.failedPlugins.value=[...state.plugins.failedPlugins.value,...unavailablePlugins];this.logger.error(UNAVAILABLE_PLUGINS_ERROR(PLUGINS_MANAGER,unavailablePlugins));}}/**
|
|
987
1081
|
* Register plugins that are dynamic imports to PluginEngine
|
|
988
|
-
*/registerRemotePlugins(){const remotePluginsList=remotePluginsInventory(state.plugins.activePlugins.value);
|
|
989
|
-
|
|
1082
|
+
*/registerRemotePlugins(){const remotePluginsList=remotePluginsInventory(state.plugins.activePlugins.value);const pluginsCDNPath=state.lifecycle.pluginsCDNPath.value;const remoteEntryUrl=`${pluginsCDNPath}/${REMOTE_PLUGINS_ENTRY_FILE}`;const loadFailures=[];// Kept separate from state.plugins.failedPlugins, which also collects
|
|
1083
|
+
// unknown plugins from setActivePlugins, unavailable local plugins from
|
|
1084
|
+
// registerLocalPlugins and registration failures from register(). Reporting
|
|
1085
|
+
// the global list would attribute those to this remote load incident.
|
|
1086
|
+
const failedRemotePlugins=[];return Promise.all(Object.keys(remotePluginsList).map(async remotePluginKey=>{await remotePluginsList[remotePluginKey]().then(remotePluginModule=>{// An intercepted chunk can parse yet export nothing; calling the
|
|
1087
|
+
// undefined factory blind reports a per-build minified name.
|
|
1088
|
+
const pluginFactory=remotePluginModule===null||remotePluginModule===void 0?void 0:remotePluginModule.default;if(!isFunction(pluginFactory)){throw new Error(NO_PLUGIN_FACTORY_EXPORTED_REASON);}this.register([pluginFactory()]);}).catch(err=>{var _message;// TODO: add retry here if dynamic import fails
|
|
1089
|
+
failedRemotePlugins.push(remotePluginKey);state.plugins.failedPlugins.value=[...state.plugins.failedPlugins.value,remotePluginKey];// A rejection is not guaranteed to be an Error, so without the
|
|
1090
|
+
// fallback the log reads "- undefined".
|
|
1091
|
+
const reason=(_message=err===null||err===void 0?void 0:err.message)!==null&&_message!==void 0?_message:String(err);this.logger.error(REMOTE_PLUGIN_LOAD_ERROR(PLUGINS_MANAGER,remotePluginKey,reason));loadFailures.push(err);});})).then(()=>{// A failed remote entry rejects every plugin import at once, so the
|
|
1092
|
+
// fan-out is one incident and gets one report, raised only after every
|
|
1093
|
+
// import has settled so it names all of them.
|
|
1094
|
+
//
|
|
1095
|
+
// An import that never settles therefore means no report. That is
|
|
1096
|
+
// deliberate: a dynamic import has no timeout of its own, and holding a
|
|
1097
|
+
// timer open to salvage a partial report would spend page resources on
|
|
1098
|
+
// error reporting, which is the lowest priority thing the SDK does.
|
|
1099
|
+
if(failedRemotePlugins.length===0){return;}this.onError(loadFailures[0],`Failed to load plugins: ${failedRemotePlugins.join(', ')}`,// Grouping on the message split one bug across two dozen groups: the
|
|
1100
|
+
// federation runtime names its own local, renamed by the host bundler per build.
|
|
1101
|
+
remoteEntryUrl);}).catch(err=>{this.onError(err);});}/**
|
|
990
1102
|
* Extension point invoke that allows multiple plugins to be registered to it with error handling
|
|
991
1103
|
*/invokeMultiple(extPoint,...args){try{return this.engine.invokeMultiple(extPoint,...args);}catch(e){this.onError(e,extPoint);return [];}}/**
|
|
992
1104
|
* Extension point invoke that allows a single plugin to be registered to it with error handling
|
|
@@ -1007,7 +1119,7 @@ const storageClientDataStoreNameMap={[COOKIE_STORAGE]:CLIENT_DATA_STORE_COOKIE,[
|
|
|
1007
1119
|
|
|
1008
1120
|
/**
|
|
1009
1121
|
* Encode.
|
|
1010
|
-
*/const encode=(value,logger)=>{try{return encodeURIComponent(value);}catch(err){logger
|
|
1122
|
+
*/const encode=(value,logger)=>{try{return encodeURIComponent(value);}catch(err){logger===null||logger===void 0||logger.error(COOKIE_DATA_ENCODING_ERROR,err);return undefined;}};/**
|
|
1011
1123
|
* Decode
|
|
1012
1124
|
*/const decode=value=>{try{return decodeURIComponent(value);}catch(err){// Do nothing as non-RS SDK cookies may not be URI encoded
|
|
1013
1125
|
return undefined;}};/**
|
|
@@ -1015,7 +1127,7 @@ return undefined;}};/**
|
|
|
1015
1127
|
*/const parse=str=>{const obj={};const pairs=str.split(/\s*;\s*/);let pair;if(!pairs[0]){return obj;}// TODO: Decode only the cookies that are needed by the SDK
|
|
1016
1128
|
pairs.forEach(pairItem=>{pair=pairItem.split('=');const keyName=pair[0]?decode(pair[0]):undefined;if(keyName){obj[keyName]=pair[1]?decode(pair[1]):undefined;}});return obj;};/**
|
|
1017
1129
|
* Set cookie `name` to `value`
|
|
1018
|
-
*/const set=(name,value,optionsConfig,logger)=>{const options={
|
|
1130
|
+
*/const set=(name,value,optionsConfig,logger)=>{const options=_objectSpread2({},optionsConfig||{});let cookieString=`${encode(name,logger)}=${encode(value,logger)}`;if(isNull(value)){options.maxage=-1;}if(options.maxage){options.expires=new Date(+new Date()+options.maxage);}if(options.path){cookieString+=`; path=${options.path}`;}if(options.domain){cookieString+=`; domain=${options.domain}`;}if(options.expires){cookieString+=`; expires=${options.expires.toUTCString()}`;}if(options.samesite){cookieString+=`; samesite=${options.samesite}`;}if(options.secure){cookieString+=`; secure`;}globalThis.document.cookie=cookieString;};/**
|
|
1019
1131
|
* Return all cookies
|
|
1020
1132
|
*/const all=()=>{const cookieStringValue=globalThis.document.cookie;return parse(cookieStringValue);};/**
|
|
1021
1133
|
* Get cookie `name`
|
|
@@ -1028,8 +1140,8 @@ const legacyGetHostname=href=>{const l=document.createElement('a');l.href=href;r
|
|
|
1028
1140
|
* Levels returns all levels of the given url
|
|
1029
1141
|
*
|
|
1030
1142
|
* The method returns an empty array when the hostname is an ip.
|
|
1031
|
-
*/const levelsFunc=url=>{
|
|
1032
|
-
const host=typeof globalThis.URL!=='function'?legacyGetHostname(url):new URL(url).hostname;const parts=host
|
|
1143
|
+
*/const levelsFunc=url=>{var _host$split;// This is called before the polyfills load thus new URL cannot be used
|
|
1144
|
+
const host=typeof globalThis.URL!=='function'?legacyGetHostname(url):new URL(url).hostname;const parts=(_host$split=host===null||host===void 0?void 0:host.split('.'))!==null&&_host$split!==void 0?_host$split:[];const last=parts[parts.length-1];const levels=[];// Ip address.
|
|
1033
1145
|
if(parts.length===4&&last&&last===parseInt(last,10).toString()){return levels;}// Localhost.
|
|
1034
1146
|
if(parts.length<=1){// Fix to support localhost
|
|
1035
1147
|
if(parts[0]&&parts[0].indexOf('localhost')!==-1){return ['localhost'];}return levels;}// Create levels.
|
|
@@ -1045,16 +1157,16 @@ for(let i=parts.length-2;i>=0;i-=1){levels.push(parts.slice(i).join('.'));}retur
|
|
|
1045
1157
|
for(let i=0;i<levels.length;i+=1){const domain=levels[i];const cname=STORAGE_TEST_TOP_LEVEL_DOMAIN;const opts={domain:`${domain.indexOf('localhost')!==-1?'':'.'}${domain}`};try{// Set cookie on domain
|
|
1046
1158
|
cookie(cname,1,opts);// If successful
|
|
1047
1159
|
if(cookie(cname)){// Remove cookie from domain
|
|
1048
|
-
cookie(cname,null,opts);return domain;}}catch{// Silently continue to next domain level if cookie access is restricted or setting fails
|
|
1160
|
+
cookie(cname,null,opts);return domain;}}catch(_unused){// Silently continue to next domain level if cookie access is restricted or setting fails
|
|
1049
1161
|
// Best-effort cleanup to avoid leaking the test cookie
|
|
1050
|
-
try{cookie(cname,null,opts);}catch{// Ignore if we are unable to delete the cookie
|
|
1162
|
+
try{cookie(cname,null,opts);}catch(_unused2){// Ignore if we are unable to delete the cookie
|
|
1051
1163
|
}}}return '';};
|
|
1052
1164
|
|
|
1053
1165
|
const getDefaultCookieOptions=()=>{const topDomain=`.${domain(globalThis.location.href)}`;return {maxage:DEFAULT_COOKIE_MAX_AGE_MS,path:'/',domain:!topDomain||topDomain==='.'?undefined:topDomain,samesite:'Lax',enabled:true};};const getDefaultLocalStorageOptions=()=>({enabled:true});const getDefaultSessionStorageOptions=()=>({enabled:true});const getDefaultInMemoryStorageOptions=()=>({enabled:true});
|
|
1054
1166
|
|
|
1055
1167
|
/**
|
|
1056
1168
|
* A storage utility to retain values in memory via Storage interface
|
|
1057
|
-
*/class InMemoryStorage{isEnabled
|
|
1169
|
+
*/class InMemoryStorage{constructor(logger){_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);_defineProperty(this,"data",{});this.options=getDefaultInMemoryStorageOptions();this.logger=logger;}configure(options){this.options=mergeDeepRight(this.options,options!==null&&options!==void 0?options:{});this.isEnabled=Boolean(this.options.enabled);return this.options;}setItem(key,value){this.data[key]=value;this.length=Object.keys(this.data).length;return value;}getItem(key){if(key in this.data){return this.data[key];}return null;}removeItem(key){if(key in this.data){delete this.data[key];}this.length=Object.keys(this.data).length;return null;}clear(){this.data={};this.length=0;}key(index){var _curKeys$index;const curKeys=this.keys();return (_curKeys$index=curKeys[index])!==null&&_curKeys$index!==void 0?_curKeys$index:null;}keys(){return Object.keys(this.data);}}const defaultInMemoryStorage=new InMemoryStorage(defaultLogger);
|
|
1058
1170
|
|
|
1059
1171
|
function getDefaultExportFromCjs (x) {
|
|
1060
1172
|
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
|
@@ -1075,8 +1187,8 @@ const store = /*@__PURE__*/getDefaultExportFromCjs(storeExports);
|
|
|
1075
1187
|
const isStorageQuotaExceeded=e=>{const matchingNames=['QuotaExceededError','NS_ERROR_DOM_QUOTA_REACHED'];// Everything except Firefox, Firefox
|
|
1076
1188
|
const matchingCodes=[22,1014];if(e instanceof DOMException){return matchingNames.includes(e.name)||matchingCodes.includes(e.code);}return false;};// TODO: also check for SecurityErrors
|
|
1077
1189
|
// https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage#exceptions
|
|
1078
|
-
const isStorageAvailable=(type=LOCAL_STORAGE,storageInstance,logger)=>{let storage;let testData;const msgPrefix=STORAGE_UNAVAILABILITY_ERROR_PREFIX(CAPABILITIES_MANAGER,type);let reason='unavailable';let isAccessible=true;let errObj;try{switch(type){case MEMORY_STORAGE:return true;case COOKIE_STORAGE:storage=storageInstance;testData=STORAGE_TEST_COOKIE;break;case LOCAL_STORAGE:storage=storageInstance
|
|
1079
|
-
break;case SESSION_STORAGE:storage=storageInstance
|
|
1190
|
+
const isStorageAvailable=(type=LOCAL_STORAGE,storageInstance,logger)=>{let storage;let testData;const msgPrefix=STORAGE_UNAVAILABILITY_ERROR_PREFIX(CAPABILITIES_MANAGER,type);let reason='unavailable';let isAccessible=true;let errObj;try{switch(type){case MEMORY_STORAGE:return true;case COOKIE_STORAGE:storage=storageInstance;testData=STORAGE_TEST_COOKIE;break;case LOCAL_STORAGE:storage=storageInstance!==null&&storageInstance!==void 0?storageInstance:globalThis.localStorage;testData=STORAGE_TEST_LOCAL_STORAGE;// was STORAGE_TEST_LOCAL_STORAGE in ours and generateUUID() in segment retry one
|
|
1191
|
+
break;case SESSION_STORAGE:storage=storageInstance!==null&&storageInstance!==void 0?storageInstance:globalThis.sessionStorage;testData=STORAGE_TEST_SESSION_STORAGE;break;default:return false;}if(storage){storage.setItem(testData,'true');if(storage.getItem(testData)){storage.removeItem(testData);return true;}}isAccessible=false;}catch(err){isAccessible=false;errObj=err;if(isStorageQuotaExceeded(err)){reason='full';}}if(!isAccessible){logger===null||logger===void 0||logger.warn(`${msgPrefix}${reason}.`,errObj);}// if we've have reached here, it means the storage is not available
|
|
1080
1192
|
return false;};
|
|
1081
1193
|
|
|
1082
1194
|
// check if the get, set overloads and search methods are used at all
|
|
@@ -1084,24 +1196,24 @@ return false;};
|
|
|
1084
1196
|
// https://www.npmjs.com/package/storejs
|
|
1085
1197
|
/**
|
|
1086
1198
|
* A storage utility to persist values in localstorage via Storage interface
|
|
1087
|
-
*/class LocalStorage{isSupportAvailable
|
|
1088
|
-
getItem(key){const value=store.get(key);return isUndefined(value)?null:value;}removeItem(key){store.remove(key);this.length=store.len();}clear(){store.clear();this.length=0;}key(index){const curKeys=this.keys();return curKeys[index]
|
|
1199
|
+
*/class LocalStorage{constructor(logger){_defineProperty(this,"isSupportAvailable",true);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);this.options=getDefaultLocalStorageOptions();this.logger=logger;}configure(options){this.options=mergeDeepRight(this.options,options!==null&&options!==void 0?options:{});this.isSupportAvailable=isStorageAvailable(LOCAL_STORAGE);this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}setItem(key,value){store.set(key,value);this.length=store.len();}// eslint-disable-next-line class-methods-use-this
|
|
1200
|
+
getItem(key){const value=store.get(key);return isUndefined(value)?null:value;}removeItem(key){store.remove(key);this.length=store.len();}clear(){store.clear();this.length=0;}key(index){var _curKeys$index;const curKeys=this.keys();return (_curKeys$index=curKeys[index])!==null&&_curKeys$index!==void 0?_curKeys$index:null;}// eslint-disable-next-line class-methods-use-this
|
|
1089
1201
|
keys(){return store.keys();}}const defaultLocalStorage=new LocalStorage(defaultLogger);
|
|
1090
1202
|
|
|
1091
1203
|
/**
|
|
1092
1204
|
* A storage utility to persist values in SessionStorage via Storage interface
|
|
1093
|
-
*/class SessionStorage{isSupportAvailable
|
|
1094
|
-
if(this.isSupportAvailable){this.store=globalThis.sessionStorage;}this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}setItem(key,value){if(!this.store){return;}this.store.setItem(key,value);this.length=this.store.length;}getItem(key){if(!this.store){return null;}const value=this.store.getItem(key);return isUndefined(value)?null:value;}removeItem(key){if(!this.store){return;}this.store.removeItem(key);this.length=this.store.length;}clear(){this.store
|
|
1205
|
+
*/class SessionStorage{constructor(logger){_defineProperty(this,"isSupportAvailable",true);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);this.options=getDefaultSessionStorageOptions();this.logger=logger;}configure(options){this.options=mergeDeepRight(this.options,options!==null&&options!==void 0?options:{});this.isSupportAvailable=isStorageAvailable(SESSION_STORAGE);// when storage is blocked by the user, even accessing the property throws an error
|
|
1206
|
+
if(this.isSupportAvailable){this.store=globalThis.sessionStorage;}this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}setItem(key,value){if(!this.store){return;}this.store.setItem(key,value);this.length=this.store.length;}getItem(key){if(!this.store){return null;}const value=this.store.getItem(key);return isUndefined(value)?null:value;}removeItem(key){if(!this.store){return;}this.store.removeItem(key);this.length=this.store.length;}clear(){var _this$store;(_this$store=this.store)===null||_this$store===void 0||_this$store.clear();this.length=0;}key(index){var _this$store$key,_this$store2;return (_this$store$key=(_this$store2=this.store)===null||_this$store2===void 0?void 0:_this$store2.key(index))!==null&&_this$store$key!==void 0?_this$store$key:null;}keys(){const keys=[];if(!this.store){return keys;}for(let i=0;i<this.store.length;i+=1){const key=this.store.key(i);if(key!==null){keys.push(key);}}return keys;}}const defaultSessionStorage=new SessionStorage(defaultLogger);
|
|
1095
1207
|
|
|
1096
1208
|
/**
|
|
1097
1209
|
* A storage utility to persist values in cookies via Storage interface
|
|
1098
|
-
*/class CookieStorage{isSupportAvailable
|
|
1210
|
+
*/class CookieStorage{constructor(logger){_defineProperty(this,"isSupportAvailable",true);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);this.logger=logger;}configure(options){if(!this.options){this.options=getDefaultCookieOptions();}this.options=mergeDeepRight(this.options,options!==null&&options!==void 0?options:{});if(this.options.sameDomainCookiesOnly){delete this.options.domain;}this.isSupportAvailable=isStorageAvailable(COOKIE_STORAGE,this);this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}setItem(key,value){cookie(key,value,this.options,this.logger);this.length=Object.keys(cookie()).length;return true;}// eslint-disable-next-line class-methods-use-this
|
|
1099
1211
|
getItem(key){const value=cookie(key);return isUndefined(value)?null:value;}removeItem(key){const result=this.setItem(key,null);this.length=Object.keys(cookie()).length;return result;}// eslint-disable-next-line class-methods-use-this
|
|
1100
1212
|
clear(){// Not implemented
|
|
1101
1213
|
// getting a list of all cookie storage keys and remove all values
|
|
1102
1214
|
// sounds risky to do as it will take on all top domain cookies
|
|
1103
1215
|
// better to explicitly clear specific ones if needed
|
|
1104
|
-
}key(index){const curKeys=this.keys();return curKeys[index]
|
|
1216
|
+
}key(index){var _curKeys$index;const curKeys=this.keys();return (_curKeys$index=curKeys[index])!==null&&_curKeys$index!==void 0?_curKeys$index:null;}// eslint-disable-next-line class-methods-use-this
|
|
1105
1217
|
keys(){return Object.keys(cookie());}}const defaultCookieStorage=new CookieStorage(defaultLogger);
|
|
1106
1218
|
|
|
1107
1219
|
/**
|
|
@@ -1121,12 +1233,12 @@ state.storage.cookie.value={maxage:cookieStorageOptions.maxage,path:cookieStorag
|
|
|
1121
1233
|
|
|
1122
1234
|
/**
|
|
1123
1235
|
* Store Implementation with dedicated storage
|
|
1124
|
-
*/class Store{constructor(config,engine,pluginsManager){this.id=config.id;this.name=config.name;this.isEncrypted=config.isEncrypted
|
|
1236
|
+
*/class Store{constructor(config,engine,pluginsManager){var _config$isEncrypted,_config$validKeys;this.id=config.id;this.name=config.name;this.isEncrypted=(_config$isEncrypted=config.isEncrypted)!==null&&_config$isEncrypted!==void 0?_config$isEncrypted:false;this.validKeys=(_config$validKeys=config.validKeys)!==null&&_config$validKeys!==void 0?_config$validKeys:{};this.engine=engine;this.noKeyValidation=Object.keys(this.validKeys).length===0;this.noCompoundKey=config.noCompoundKey;this.noSwapOnQuota=config.noSwapOnQuota;this.originalEngine=this.engine;this.errorHandler=config.errorHandler;this.logger=config.logger;this.pluginsManager=pluginsManager;}/**
|
|
1125
1237
|
* Ensure the key is valid and with correct format
|
|
1126
1238
|
*/createValidKey(key){const{name,id,validKeys,noKeyValidation,noCompoundKey}=this;if(noKeyValidation){return noCompoundKey?key:[name,id,key].join('.');}// validate and return undefined if invalid key
|
|
1127
1239
|
let compoundKey;Object.values(validKeys).forEach(validKeyName=>{if(validKeyName===key){compoundKey=noCompoundKey?key:[name,id,key].join('.');}});return compoundKey;}/**
|
|
1128
1240
|
* Switch to inMemoryEngine, bringing any existing data with.
|
|
1129
|
-
*/swapQueueStoreToInMemoryEngine(){const{validKeys,noCompoundKey}=this;const inMemoryStorage=getStorageEngine(MEMORY_STORAGE)
|
|
1241
|
+
*/swapQueueStoreToInMemoryEngine(){const{validKeys,noCompoundKey,engine:durableEngine}=this;const inMemoryStorage=getStorageEngine(MEMORY_STORAGE);// grab existing data, but only for this page's queue instance, not all
|
|
1130
1242
|
// better to keep other queues in localstorage to be flushed later
|
|
1131
1243
|
// than to pull them into memory and remove them from durable storage
|
|
1132
1244
|
const existingEntries=Object.values(validKeys).map(storeKey=>[storeKey,this.get(storeKey)]);// Client data stores keep their durable copy. Dropping rl_user_id and the
|
|
@@ -1136,7 +1248,7 @@ const canDropDurableCopy=!noCompoundKey&&durableEngine!==inMemoryStorage;this.en
|
|
|
1136
1248
|
this.set(storeKey,value);// Only give up the durable copy once the value is readable from memory:
|
|
1137
1249
|
// set() swallows serialisation and storage failures, and get() returns
|
|
1138
1250
|
// null on a parse or decryption failure.
|
|
1139
|
-
const validKey=this.createValidKey(storeKey);if(canDropDurableCopy&&validKey&&!isNullOrUndefined(this.get(storeKey))){try{durableEngine.removeItem(validKey);}catch{// The durable engine can refuse a removal (NS_ERROR_STORAGE_BUSY). The
|
|
1251
|
+
const validKey=this.createValidKey(storeKey);if(canDropDurableCopy&&validKey&&!isNullOrUndefined(this.get(storeKey))){try{durableEngine.removeItem(validKey);}catch(_unused){// The durable engine can refuse a removal (NS_ERROR_STORAGE_BUSY). The
|
|
1140
1252
|
// value is already safe in memory, so leave the stale copy for a later
|
|
1141
1253
|
// cleanup rather than aborting the migration - this runs inside set()'s
|
|
1142
1254
|
// catch, and throwing here would lose the value that triggered it.
|
|
@@ -1147,8 +1259,18 @@ this.engine.setItem(validKey,this.encrypt(stringifyWithoutCircular(value,false,[
|
|
|
1147
1259
|
this.swapQueueStoreToInMemoryEngine();// and save it there
|
|
1148
1260
|
this.set(key,value);}else {const customMessage=STORE_DATA_SAVE_ERROR(key);this.onError(err,customMessage,customMessage);}}}/**
|
|
1149
1261
|
* Get by Key.
|
|
1150
|
-
*/get(key){const validKey=this.createValidKey(key);let decryptedValue;try{if(!validKey){return null;}
|
|
1151
|
-
return JSON.parse(decryptedValue);}catch(err){
|
|
1262
|
+
*/get(key){const validKey=this.createValidKey(key);let storedValue;let decryptedValue;let 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
|
|
1263
|
+
return JSON.parse(decryptedValue);}catch(err){// Both encryption plugins, and `crypto` with no decrypt extension point registered, return
|
|
1264
|
+
// an unrecognised format untouched, so an unchanged value may still be readable; keep it.
|
|
1265
|
+
const isDecrypted=!this.isEncrypted||decryptedValue!==storedValue;// Drop a parse failure so a later read is a clean miss instead of the same error on every
|
|
1266
|
+
// poll, and only while the entry still holds what was read. Web Storage has no conditional
|
|
1267
|
+
// delete, so that narrows rather than closes the window in which another tab's write is
|
|
1268
|
+
// dropped; the cost there is a restarted reclaim handshake, since queued events are written
|
|
1269
|
+
// only by the context that owns the store. The compare is serialized because storejs
|
|
1270
|
+
// deserializes on every read, and uses `JSON.stringify` because `stringifyWithoutCircular`
|
|
1271
|
+
// returns null on failure, which would make two unserializable values compare equal.
|
|
1272
|
+
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.
|
|
1273
|
+
}const encryptionPluginName=state.storage.encryptionPluginName.value;// Skip error reporting only when the encryption plugin is configured but failed to load
|
|
1152
1274
|
const shouldReportError=!encryptionPluginName||!state.plugins.failedPlugins.value.includes(encryptionPluginName);if(shouldReportError){const customMessage=STORE_DATA_FETCH_ERROR(key);this.onError(err,customMessage,customMessage);}return null;}}/**
|
|
1153
1275
|
* Remove by Key.
|
|
1154
1276
|
*/remove(key){const validKey=this.createValidKey(key);if(validKey){this.engine.removeItem(validKey);}}/**
|
|
@@ -1159,31 +1281,31 @@ const shouldReportError=!encryptionPluginName||!state.plugins.failedPlugins.valu
|
|
|
1159
1281
|
* Encrypt value
|
|
1160
1282
|
*/encrypt(value){return this.crypto(value,'encrypt');}/**
|
|
1161
1283
|
* Extension point to use with encryption plugins
|
|
1162
|
-
*/crypto(value,mode){const noEncryption=!this.isEncrypted||!value||typeof value!=='string'||trim(value)==='';if(noEncryption){return value;}const extensionPointName=`storage.${mode}`;const formattedValue=this.pluginsManager?this.pluginsManager.invokeSingle(extensionPointName,value):value;return
|
|
1284
|
+
*/crypto(value,mode){const noEncryption=!this.isEncrypted||!value||typeof value!=='string'||trim(value)==='';if(noEncryption){return value;}const extensionPointName=`storage.${mode}`;const formattedValue=this.pluginsManager?this.pluginsManager.invokeSingle(extensionPointName,value):value;return formattedValue===undefined?value:formattedValue!==null&&formattedValue!==void 0?formattedValue:'';}/**
|
|
1163
1285
|
* Handle errors
|
|
1164
1286
|
*/onError(error,customMessage,groupingHash){this.errorHandler.onError({error,context:`Store ${this.id}`,customMessage,groupingHash});}}
|
|
1165
1287
|
|
|
1166
|
-
const getStorageTypeFromPreConsentIfApplicable=(state,sessionKey)=>{let overriddenStorageType;if(state.consents.preConsent.value.enabled){switch(state.consents.preConsent.value.storage
|
|
1288
|
+
const getStorageTypeFromPreConsentIfApplicable=(state,sessionKey)=>{let overriddenStorageType;if(state.consents.preConsent.value.enabled){var _state$consents$preCo;switch((_state$consents$preCo=state.consents.preConsent.value.storage)===null||_state$consents$preCo===void 0?void 0:_state$consents$preCo.strategy){case 'none':overriddenStorageType=NO_STORAGE;break;case 'session':if(sessionKey!=='sessionInfo'){overriddenStorageType=NO_STORAGE;}break;case 'anonymousId':if(sessionKey!=='anonymousId'){overriddenStorageType=NO_STORAGE;}break;}}return overriddenStorageType;};
|
|
1167
1289
|
|
|
1168
1290
|
/**
|
|
1169
1291
|
* A service to manage stores & available storage client configurations
|
|
1170
|
-
*/class StoreManager{
|
|
1292
|
+
*/class StoreManager{constructor(pluginsManager,errorHandler,logger){_defineProperty(this,"stores",{});_defineProperty(this,"isInitialized",false);this.errorHandler=errorHandler;this.logger=logger;this.pluginsManager=pluginsManager;}/**
|
|
1171
1293
|
* Configure available storage client instances
|
|
1172
|
-
*/init(){if(this.isInitialized){return;}const loadOptions=state.loadOptions.value;const config={cookieStorageOptions:{samesite:loadOptions.sameSiteCookie,secure:loadOptions.secureCookie,domain:loadOptions.setCookieDomain,sameDomainCookiesOnly:loadOptions.sameDomainCookiesOnly},localStorageOptions:{},inMemoryStorageOptions:{},sessionStorageOptions:{}};configureStorageEngines(removeUndefinedValues(mergeDeepRight(config.cookieStorageOptions
|
|
1294
|
+
*/init(){var _config$cookieStorage,_state$storage$cookie,_state$storage$cookie2;if(this.isInitialized){return;}const loadOptions=state.loadOptions.value;const config={cookieStorageOptions:{samesite:loadOptions.sameSiteCookie,secure:loadOptions.secureCookie,domain:loadOptions.setCookieDomain,sameDomainCookiesOnly:loadOptions.sameDomainCookiesOnly},localStorageOptions:{},inMemoryStorageOptions:{},sessionStorageOptions:{}};configureStorageEngines(removeUndefinedValues(mergeDeepRight((_config$cookieStorage=config.cookieStorageOptions)!==null&&_config$cookieStorage!==void 0?_config$cookieStorage:{},(_state$storage$cookie=(_state$storage$cookie2=state.storage.cookie)===null||_state$storage$cookie2===void 0?void 0:_state$storage$cookie2.value)!==null&&_state$storage$cookie!==void 0?_state$storage$cookie:{})),removeUndefinedValues(config.localStorageOptions),removeUndefinedValues(config.inMemoryStorageOptions),removeUndefinedValues(config.sessionStorageOptions));this.initClientDataStores();this.isInitialized=true;}/**
|
|
1173
1295
|
* Create store to persist data used by the SDK like session, used details etc
|
|
1174
1296
|
*/initClientDataStores(){this.initializeStorageState();// TODO: fill in extra config values and bring them in from StoreManagerOptions if needed
|
|
1175
1297
|
// TODO: should we pass the keys for all in order to validate or leave free as v1.1?
|
|
1176
1298
|
// Initializing all the enabled store because previous user data might be in different storage
|
|
1177
1299
|
// that needs auto migration
|
|
1178
|
-
const storageTypes=[MEMORY_STORAGE,LOCAL_STORAGE,COOKIE_STORAGE,SESSION_STORAGE];storageTypes.forEach(storageType=>{if(getStorageEngine(storageType)
|
|
1179
|
-
const postConsentStorageOpts=state.consents.postConsent.value.storage;if(isDefined(postConsentStorageOpts
|
|
1300
|
+
const storageTypes=[MEMORY_STORAGE,LOCAL_STORAGE,COOKIE_STORAGE,SESSION_STORAGE];storageTypes.forEach(storageType=>{var _getStorageEngine;if((_getStorageEngine=getStorageEngine(storageType))!==null&&_getStorageEngine!==void 0&&_getStorageEngine.isEnabled){this.setStore({id:storageClientDataStoreNameMap[storageType],name:storageClientDataStoreNameMap[storageType],isEncrypted:true,noCompoundKey:true,type:storageType,errorHandler:this.errorHandler,logger:this.logger});}});}initializeStorageState(){var _state$loadOptions$va,_state$loadOptions$va2,_preConsentOpts$stora;let globalStorageType=(_state$loadOptions$va=state.loadOptions.value.storage)===null||_state$loadOptions$va===void 0?void 0:_state$loadOptions$va.type;let entriesOptions=(_state$loadOptions$va2=state.loadOptions.value.storage)===null||_state$loadOptions$va2===void 0?void 0:_state$loadOptions$va2.entries;// Use the storage options from post consent if anything is defined
|
|
1301
|
+
const postConsentStorageOpts=state.consents.postConsent.value.storage;if(isDefined(postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.type)||isDefined(postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.entries)){globalStorageType=postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.type;entriesOptions=postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.entries;}// Without the deprecated pre-consent storage strategy, the storage options decide what is
|
|
1180
1302
|
// persisted before consent is given. Only the fallback changes: nothing is persisted unless
|
|
1181
1303
|
// a storage type has been explicitly configured.
|
|
1182
|
-
const preConsentOpts=state.consents.preConsent.value;const isStorageFromLoadOptionsBeforeConsent=preConsentOpts.enabled===true&&!preConsentOpts.storage
|
|
1304
|
+
const preConsentOpts=state.consents.preConsent.value;const isStorageFromLoadOptionsBeforeConsent=preConsentOpts.enabled===true&&!((_preConsentOpts$stora=preConsentOpts.storage)!==null&&_preConsentOpts$stora!==void 0&&_preConsentOpts$stora.strategy);const defaultStorageType=isStorageFromLoadOptionsBeforeConsent?NO_STORAGE:DEFAULT_STORAGE_TYPE;// The unsupported values are reported where the options enter the SDK, so they are only
|
|
1183
1305
|
// resolved here, against the default that applies to the current consent phase
|
|
1184
|
-
if(globalStorageType!==undefined&&!SUPPORTED_STORAGE_TYPES.includes(globalStorageType)){globalStorageType=undefined;}let trulyAnonymousTracking=true;let storageEntries={};USER_SESSION_KEYS.forEach(sessionKey=>{const key=sessionKey;const storageKey=sessionKey;const configuredStorageType=entriesOptions
|
|
1185
|
-
let storageType=preConsentStorageType
|
|
1186
|
-
if(getStorageEngine(COOKIE_STORAGE)
|
|
1306
|
+
if(globalStorageType!==undefined&&!SUPPORTED_STORAGE_TYPES.includes(globalStorageType)){globalStorageType=undefined;}let trulyAnonymousTracking=true;let storageEntries={};USER_SESSION_KEYS.forEach(sessionKey=>{var _entriesOptions,_ref,_ref2;const key=sessionKey;const storageKey=sessionKey;const configuredStorageType=(_entriesOptions=entriesOptions)===null||_entriesOptions===void 0||(_entriesOptions=_entriesOptions[key])===null||_entriesOptions===void 0?void 0:_entriesOptions.type;const preConsentStorageType=getStorageTypeFromPreConsentIfApplicable(state,sessionKey);// Storage type precedence order: pre-consent strategy > entry type > global type > default
|
|
1307
|
+
let storageType=(_ref=(_ref2=preConsentStorageType!==null&&preConsentStorageType!==void 0?preConsentStorageType:configuredStorageType)!==null&&_ref2!==void 0?_ref2:globalStorageType)!==null&&_ref!==void 0?_ref:defaultStorageType;if(!SUPPORTED_STORAGE_TYPES.includes(storageType)){storageType=defaultStorageType;}const finalStorageType=this.getResolvedStorageTypeForEntry(storageType,sessionKey);if(finalStorageType!==NO_STORAGE){trulyAnonymousTracking=false;}storageEntries=_objectSpread2(_objectSpread2({},storageEntries),{},{[sessionKey]:{type:finalStorageType,key:COOKIE_KEYS[storageKey]}});});n(()=>{state.storage.entries.value=storageEntries;state.storage.trulyAnonymousTracking.value=trulyAnonymousTracking;});}getResolvedStorageTypeForEntry(storageType,sessionKey){var _getStorageEngine2,_getStorageEngine3,_getStorageEngine4,_getStorageEngine5,_getStorageEngine6;let finalStorageType=storageType;switch(storageType){case LOCAL_STORAGE:if(!((_getStorageEngine2=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine2!==void 0&&_getStorageEngine2.isEnabled)){finalStorageType=MEMORY_STORAGE;}break;case SESSION_STORAGE:if(!((_getStorageEngine3=getStorageEngine(SESSION_STORAGE))!==null&&_getStorageEngine3!==void 0&&_getStorageEngine3.isEnabled)){finalStorageType=MEMORY_STORAGE;}break;case MEMORY_STORAGE:case NO_STORAGE:break;case COOKIE_STORAGE:default:// First try setting the storage to cookie else to local storage
|
|
1308
|
+
if((_getStorageEngine4=getStorageEngine(COOKIE_STORAGE))!==null&&_getStorageEngine4!==void 0&&_getStorageEngine4.isEnabled){finalStorageType=COOKIE_STORAGE;}else if((_getStorageEngine5=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine5!==void 0&&_getStorageEngine5.isEnabled){finalStorageType=LOCAL_STORAGE;}else if((_getStorageEngine6=getStorageEngine(SESSION_STORAGE))!==null&&_getStorageEngine6!==void 0&&_getStorageEngine6.isEnabled){finalStorageType=SESSION_STORAGE;}else {finalStorageType=MEMORY_STORAGE;}break;}if(finalStorageType!==storageType){this.logger.warn(STORAGE_UNAVAILABLE_WARNING(STORE_MANAGER,sessionKey,storageType,finalStorageType));}return finalStorageType;}/**
|
|
1187
1309
|
* Create a new store
|
|
1188
1310
|
*/setStore(storeConfig){const storageEngine=getStorageEngine(storeConfig.type);this.stores[storeConfig.id]=new Store(storeConfig,storageEngine,this.pluginsManager);return this.stores[storeConfig.id];}/**
|
|
1189
1311
|
* Retrieve a store
|
|
@@ -1195,7 +1317,7 @@ const isValidSourceConfig=res=>isObjectLiteralAndNotNull(res)&&isObjectLiteralAn
|
|
|
1195
1317
|
* @param storageOpts Storage options from the load API options or the consent API options
|
|
1196
1318
|
* @param context Logger context
|
|
1197
1319
|
* @param logger Logger instance
|
|
1198
|
-
*/const validateStorageOptions=(storageOpts,context,logger)=>{if(!isObjectLiteralAndNotNull(storageOpts)){return;}const{type,entries}=storageOpts;if(isDefined(type)&&!isValidStorageType(type)){logger
|
|
1320
|
+
*/const validateStorageOptions=(storageOpts,context,logger)=>{if(!isObjectLiteralAndNotNull(storageOpts)){return;}const{type,entries}=storageOpts;if(isDefined(type)&&!isValidStorageType(type)){logger===null||logger===void 0||logger.warn(STORAGE_TYPE_VALIDATION_WARNING(context,type));}if(entries){Object.entries(entries).forEach(([entryKey,entryOpts])=>{const entryType=entryOpts===null||entryOpts===void 0?void 0:entryOpts.type;if(isDefined(entryType)&&!isValidStorageType(entryType)){logger===null||logger===void 0||logger.warn(UNSUPPORTED_STORAGE_ENTRY_TYPE_WARNING(context,entryKey,entryType));}});}};/**
|
|
1199
1321
|
* Parses a URL without the URL constructor, which is unavailable on legacy JS engines
|
|
1200
1322
|
* until the polyfills load.
|
|
1201
1323
|
*/const legacyParseUrl=url=>{const anchor=document.createElement('a');anchor.href=url;return {host:anchor.host,protocol:anchor.protocol};};const getTopDomain=url=>{// Extract the host and protocol. This runs before the polyfills load,
|
|
@@ -1219,11 +1341,11 @@ if(hostOnlyCookies||!webpageTopDomain){return dataServiceHostname===globalThis.l
|
|
|
1219
1341
|
* Removes trailing slash from url
|
|
1220
1342
|
* @param url
|
|
1221
1343
|
* @returns url
|
|
1222
|
-
*/const removeTrailingSlashes=url=>url
|
|
1344
|
+
*/const removeTrailingSlashes=url=>url!==null&&url!==void 0&&url.endsWith('/')?removeTrailingSlashes(url.substring(0,url.length-1)):url;const getDomain=url=>{try{const urlObj=new URL(url);return urlObj.host;}catch(error){return null;}};const getHostname=url=>{try{const urlObj=new URL(url);return urlObj.hostname;}catch(error){return null;}};/**
|
|
1223
1345
|
* Get the referring domain from the referrer URL
|
|
1224
1346
|
* @param referrer Page referrer
|
|
1225
1347
|
* @returns Page referring domain
|
|
1226
|
-
*/const getReferringDomain=referrer=>getDomain(referrer)
|
|
1348
|
+
*/const getReferringDomain=referrer=>{var _getDomain;return (_getDomain=getDomain(referrer))!==null&&_getDomain!==void 0?_getDomain:'';};/**
|
|
1227
1349
|
* Extracts UTM parameters from the URL
|
|
1228
1350
|
* @param url Page URL
|
|
1229
1351
|
* @returns UTM parameters
|
|
@@ -1247,7 +1369,7 @@ new URL(url);}return URL_PATTERN.test(url);}catch(e){return false;}};
|
|
|
1247
1369
|
|
|
1248
1370
|
const DEFAULT_PRE_CONSENT_STORAGE_STRATEGY='none';const DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE='immediate';
|
|
1249
1371
|
|
|
1250
|
-
const isErrorReportingEnabled=sourceConfig=>sourceConfig
|
|
1372
|
+
const isErrorReportingEnabled=sourceConfig=>{var _sourceConfig$statsCo;return (sourceConfig===null||sourceConfig===void 0||(_sourceConfig$statsCo=sourceConfig.statsCollection)===null||_sourceConfig$statsCo===void 0||(_sourceConfig$statsCo=_sourceConfig$statsCo.errors)===null||_sourceConfig$statsCo===void 0?void 0:_sourceConfig$statsCo.enabled)===true;};const isMetricsReportingEnabled=sourceConfig=>{var _sourceConfig$statsCo2;return (sourceConfig===null||sourceConfig===void 0||(_sourceConfig$statsCo2=sourceConfig.statsCollection)===null||_sourceConfig$statsCo2===void 0||(_sourceConfig$statsCo2=_sourceConfig$statsCo2.metrics)===null||_sourceConfig$statsCo2===void 0?void 0:_sourceConfig$statsCo2.enabled)===true;};
|
|
1251
1373
|
|
|
1252
1374
|
/**
|
|
1253
1375
|
* Validates and normalizes the consent options provided by the user
|
|
@@ -1271,7 +1393,7 @@ provider=undefined;}return {provider,consentManagerPluginName};};/**
|
|
|
1271
1393
|
* @param consentManagementOpts Consent management options provided by the user
|
|
1272
1394
|
* @param logger logger instance
|
|
1273
1395
|
* @returns An object containing the consent manager plugin name, initialized, enabled and consents data
|
|
1274
|
-
*/const getConsentManagementData=(consentManagementOpts,logger)=>{let consentManagerPluginName;let allowedConsentIds=[];let deniedConsentIds=[];let initialized=false;let provider;let enabled=consentManagementOpts
|
|
1396
|
+
*/const getConsentManagementData=(consentManagementOpts,logger)=>{let consentManagerPluginName;let allowedConsentIds=[];let deniedConsentIds=[];let initialized=false;let provider;let enabled=(consentManagementOpts===null||consentManagementOpts===void 0?void 0:consentManagementOpts.enabled)===true;if(isNonEmptyObject(consentManagementOpts)&&enabled){// Get the corresponding plugin name of the selected consent manager from the supported consent managers
|
|
1275
1397
|
({provider,consentManagerPluginName}=getConsentManagerInfo(consentManagementOpts,logger));if(isValidConsentsData(consentManagementOpts.allowedConsentIds)){allowedConsentIds=consentManagementOpts.allowedConsentIds;initialized=true;}if(isValidConsentsData(consentManagementOpts.deniedConsentIds)){deniedConsentIds=consentManagementOpts.deniedConsentIds;initialized=true;}}const consentsData={allowedConsentIds,deniedConsentIds};// Enable consent management only if consent manager is supported
|
|
1276
1398
|
enabled=enabled&&Boolean(consentManagerPluginName);return {provider,consentManagerPluginName,initialized,enabled,consentsData};};
|
|
1277
1399
|
|
|
@@ -1307,11 +1429,11 @@ const cookieDomain=removeLeadingPeriod(providedCookieDomain).toLowerCase();/**
|
|
|
1307
1429
|
* The cookie domain also has to sit at or below the browser-verified domain of the webpage.
|
|
1308
1430
|
* Anything above it is a public suffix, ex: 'co.uk', which the browser refuses to scope
|
|
1309
1431
|
* cookies to however well it matches as a string suffix.
|
|
1310
|
-
*/if(!isDomainMatch(dataServiceHostname,cookieDomain)||!isDomainMatch(webpage.hostname,cookieDomain)||webpage.topDomain&&!isDomainMatch(cookieDomain,webpage.topDomain)){logger.error(SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_ERROR(CONFIG_MANAGER,providedCookieDomain,webpage.hostname));return false;}return true;};const getServerSideCookiesStateData=logger=>{const{useServerSideCookies,dataServiceEndpoint,storage:storageOptsFromLoad,setCookieDomain,sameDomainCookiesOnly}=state.loadOptions.value;let cookieOptions=storageOptsFromLoad
|
|
1432
|
+
*/if(!isDomainMatch(dataServiceHostname,cookieDomain)||!isDomainMatch(webpage.hostname,cookieDomain)||webpage.topDomain&&!isDomainMatch(cookieDomain,webpage.topDomain)){logger.error(SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_ERROR(CONFIG_MANAGER,providedCookieDomain,webpage.hostname));return false;}return true;};const getServerSideCookiesStateData=logger=>{const{useServerSideCookies,dataServiceEndpoint,storage:storageOptsFromLoad,setCookieDomain,sameDomainCookiesOnly}=state.loadOptions.value;let cookieOptions=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.cookie;let sscEnabled=false;let finalDataServiceUrl;if(useServerSideCookies){var _cookieOptions$domain;sscEnabled=useServerSideCookies;const providedCookieDomain=(_cookieOptions$domain=cookieOptions.domain)!==null&&_cookieOptions$domain!==void 0?_cookieOptions$domain:setCookieDomain;/**
|
|
1311
1433
|
* Based on the following conditions, we decide whether to use the exact domain or not to determine the data service URL:
|
|
1312
1434
|
* 1. If the cookie domain is provided and it is not a top-level domain, then use the exact domain
|
|
1313
1435
|
* 2. If the sameDomainCookiesOnly flag is set to true, then use the exact domain
|
|
1314
|
-
*/const useExactDomain=isDefined(providedCookieDomain)&&!isWebpageTopLevelDomain(removeLeadingPeriod(providedCookieDomain))||sameDomainCookiesOnly;const{hostname:webpageHostname}=globalThis.location;const{topDomain:webpageTopDomain,topHost:webpageTopHost}=getWebpageTopDomain();const dataServiceUrl=getDataServiceUrl(dataServiceEndpoint
|
|
1436
|
+
*/const useExactDomain=isDefined(providedCookieDomain)&&!isWebpageTopLevelDomain(removeLeadingPeriod(providedCookieDomain))||sameDomainCookiesOnly;const{hostname:webpageHostname}=globalThis.location;const{topDomain:webpageTopDomain,topHost:webpageTopHost}=getWebpageTopDomain();const dataServiceUrl=getDataServiceUrl(dataServiceEndpoint!==null&&dataServiceEndpoint!==void 0?dataServiceEndpoint:DEFAULT_DATA_SERVICE_ENDPOINT,useExactDomain,webpageTopHost);// The hostname is unavailable on legacy JS engines without the URL polyfill,
|
|
1315
1437
|
// in which case the data service host cannot be verified
|
|
1316
1438
|
const dataServiceHostname=getHostname(dataServiceUrl);if(isValidURL(dataServiceUrl)&&dataServiceHostname){finalDataServiceUrl=removeTrailingSlashes(dataServiceUrl);sscEnabled=isServerSideCookiesUsable(dataServiceHostname,providedCookieDomain,{hostname:webpageHostname,topDomain:webpageTopDomain},sameDomainCookiesOnly,logger);// If the current hostname is different from the data service hostname, then it is a
|
|
1317
1439
|
// cross-site request. Cookies are not isolated by port, hence it plays no part here.
|
|
@@ -1319,29 +1441,29 @@ const dataServiceHostname=getHostname(dataServiceUrl);if(isValidURL(dataServiceU
|
|
|
1319
1441
|
// One round of cookie options manipulation is taking place here
|
|
1320
1442
|
// Based on these(setCookieDomain/storage.cookie or sameDomainCookiesOnly) two load-options, final cookie options are set in the storage module
|
|
1321
1443
|
// TODO: Refactor the cookie options manipulation logic in one place
|
|
1322
|
-
if(sscEnabled&&webpageHostname!==dataServiceHostname){cookieOptions={
|
|
1323
|
-
logger.error(DATA_SERVER_URL_INVALID_ERROR(CONFIG_MANAGER,dataServiceUrl));sscEnabled=false;}}return {sscEnabled,cookieOptions,finalDataServiceUrl};};const updateStorageStateFromLoadOptions=logger=>{const{storage:storageOptsFromLoad}=state.loadOptions.value;// Only reported here. The applicable default depends on the consent phase, so the unsupported
|
|
1444
|
+
if(sscEnabled&&webpageHostname!==dataServiceHostname){cookieOptions=_objectSpread2(_objectSpread2({},cookieOptions),{},{samesite:'None',secure:true});}}else {// A malformed dataServiceEndpoint reaches here, ex: a typo in an absolute URL
|
|
1445
|
+
logger.error(DATA_SERVER_URL_INVALID_ERROR(CONFIG_MANAGER,dataServiceUrl));sscEnabled=false;}}return {sscEnabled,cookieOptions,finalDataServiceUrl};};const updateStorageStateFromLoadOptions=logger=>{var _storageOptsFromLoad$;const{storage:storageOptsFromLoad}=state.loadOptions.value;// Only reported here. The applicable default depends on the consent phase, so the unsupported
|
|
1324
1446
|
// values are resolved in the store manager.
|
|
1325
|
-
validateStorageOptions(storageOptsFromLoad,CONFIG_MANAGER,logger);let storageEncryptionVersion=storageOptsFromLoad
|
|
1447
|
+
validateStorageOptions(storageOptsFromLoad,CONFIG_MANAGER,logger);let storageEncryptionVersion=storageOptsFromLoad===null||storageOptsFromLoad===void 0||(_storageOptsFromLoad$=storageOptsFromLoad.encryption)===null||_storageOptsFromLoad$===void 0?void 0:_storageOptsFromLoad$.version;const encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
|
|
1326
1448
|
logger.warn(UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(CONFIG_MANAGER,storageEncryptionVersion,StorageEncryptionVersionsToPluginNameMap,DEFAULT_STORAGE_ENCRYPTION_VERSION));storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}else if(isUndefined(storageEncryptionVersion)){storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}// Allow migration only if the configured encryption version is the default encryption version
|
|
1327
|
-
const configuredMigrationValue=storageOptsFromLoad
|
|
1328
|
-
const preConsentOpts=state.loadOptions.value.preConsent;const configuredStrategy=preConsentOpts
|
|
1449
|
+
const configuredMigrationValue=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.migrate;const finalMigrationVal=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&finalMigrationVal!==configuredMigrationValue){logger.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}const{sscEnabled,finalDataServiceUrl,cookieOptions}=getServerSideCookiesStateData(logger);n(()=>{state.storage.cookie.value=cookieOptions;state.serverCookies.isEnabledServerSideCookies.value=sscEnabled;state.serverCookies.dataServiceUrl.value=finalDataServiceUrl;state.storage.encryptionPluginName.value=StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];state.storage.migrate.value=finalMigrationVal;});};const updateConsentsStateFromLoadOptions=logger=>{var _preConsentOpts$stora,_preConsentOpts$stora2,_preConsentOpts$event,_preConsentOpts$event2;const{provider,consentManagerPluginName,initialized,enabled,consentsData}=getConsentManagementData(state.loadOptions.value.consentManagement,logger);// Pre-consent
|
|
1450
|
+
const preConsentOpts=state.loadOptions.value.preConsent;const configuredStrategy=preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$stora=preConsentOpts.storage)===null||_preConsentOpts$stora===void 0?void 0:_preConsentOpts$stora.strategy;if(isDefined(configuredStrategy)){logger.warn(DEPRECATED_PRE_CONSENT_STORAGE_STRATEGY(CONFIG_MANAGER));}// The storage load API options drive the pre-consent phase only when it is explicitly enabled,
|
|
1329
1451
|
// so an existing configuration keeps persisting nothing before consent is given. Enabling it
|
|
1330
1452
|
// takes precedence over the deprecated strategy, otherwise a migration that leaves the strategy
|
|
1331
1453
|
// in place would silently do nothing.
|
|
1332
|
-
let storageStrategy;if(preConsentOpts
|
|
1454
|
+
let storageStrategy;if((preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$stora2=preConsentOpts.storage)===null||_preConsentOpts$stora2===void 0?void 0:_preConsentOpts$stora2.enabled)!==true){storageStrategy=configuredStrategy!==null&&configuredStrategy!==void 0?configuredStrategy:DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;const StorageStrategies=['none','session','anonymousId'];if(!StorageStrategies.includes(storageStrategy)){storageStrategy=DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;logger.warn(UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(CONFIG_MANAGER,configuredStrategy,DEFAULT_PRE_CONSENT_STORAGE_STRATEGY));}}let eventsDeliveryType=(_preConsentOpts$event=preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$event2=preConsentOpts.events)===null||_preConsentOpts$event2===void 0?void 0:_preConsentOpts$event2.delivery)!==null&&_preConsentOpts$event!==void 0?_preConsentOpts$event:DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;const deliveryTypes=['immediate','buffer'];if(isDefined(eventsDeliveryType)&&!deliveryTypes.includes(eventsDeliveryType)){var _preConsentOpts$event3;eventsDeliveryType=DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;logger.warn(UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(CONFIG_MANAGER,preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$event3=preConsentOpts.events)===null||_preConsentOpts$event3===void 0?void 0:_preConsentOpts$event3.delivery,DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE));}n(()=>{var _state$loadOptions$va;state.consents.activeConsentManagerPluginName.value=consentManagerPluginName;state.consents.initialized.value=initialized;state.consents.enabled.value=enabled;state.consents.data.value=consentsData;state.consents.provider.value=provider;state.consents.preConsent.value={// Only enable pre-consent if it is explicitly enabled and
|
|
1333
1455
|
// if it is not already initialized and
|
|
1334
1456
|
// if consent management is enabled
|
|
1335
|
-
enabled:state.loadOptions.value.preConsent
|
|
1457
|
+
enabled:((_state$loadOptions$va=state.loadOptions.value.preConsent)===null||_state$loadOptions$va===void 0?void 0:_state$loadOptions$va.enabled)===true&&initialized===false&&enabled===true,storage:{strategy:storageStrategy},events:{delivery:eventsDeliveryType}};});};/**
|
|
1336
1458
|
* Determines the consent management state variables from the source config data
|
|
1337
1459
|
* @param resp Source config response
|
|
1338
1460
|
* @param logger Logger instance
|
|
1339
|
-
*/const updateConsentsState=resp=>{let resolutionStrategy=state.consents.resolutionStrategy.value;let cmpMetadata;if(isObjectLiteralAndNotNull(resp.consentManagementMetadata)){if(state.consents.provider.value){resolutionStrategy=resp.consentManagementMetadata.providers.find(p=>p.provider===state.consents.provider.value)
|
|
1461
|
+
*/const updateConsentsState=resp=>{let resolutionStrategy=state.consents.resolutionStrategy.value;let cmpMetadata;if(isObjectLiteralAndNotNull(resp.consentManagementMetadata)){if(state.consents.provider.value){var _resp$consentManageme,_resp$consentManageme2;resolutionStrategy=(_resp$consentManageme=(_resp$consentManageme2=resp.consentManagementMetadata.providers.find(p=>p.provider===state.consents.provider.value))===null||_resp$consentManageme2===void 0?void 0:_resp$consentManageme2.resolutionStrategy)!==null&&_resp$consentManageme!==void 0?_resp$consentManageme:state.consents.resolutionStrategy.value;}cmpMetadata=resp.consentManagementMetadata;}// If the provider is custom, then the resolution strategy is not applicable
|
|
1340
1462
|
if(state.consents.provider.value==='custom'){resolutionStrategy=undefined;}n(()=>{state.consents.metadata.value=clone(cmpMetadata);state.consents.resolutionStrategy.value=resolutionStrategy;});};const updateDataPlaneEventsStateFromLoadOptions=logger=>{if(state.dataPlaneEvents.deliveryEnabled.value){const defaultEventsQueuePluginName='XhrQueue';let eventsQueuePluginName=defaultEventsQueuePluginName;if(state.loadOptions.value.useBeacon){if(state.capabilities.isBeaconAvailable.value){eventsQueuePluginName='BeaconQueue';}else {eventsQueuePluginName=defaultEventsQueuePluginName;logger.warn(UNSUPPORTED_BEACON_API_WARNING(CONFIG_MANAGER));}}n(()=>{state.dataPlaneEvents.eventsQueuePluginName.value=eventsQueuePluginName;});}};const getSourceConfigURL=(configUrl,writeKey,lockIntegrationsVersion,lockPluginsVersion,logger)=>{const defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString(),lockPluginsVersion:lockPluginsVersion.toString()});let origin=DEFAULT_CONFIG_BE_URL;let searchParams=defSearchParams;let pathname='/sourceConfig/';let hash='';if(isValidURL(configUrl)){const configUrlInstance=new URL(configUrl);if(!removeTrailingSlashes(configUrlInstance.pathname).endsWith('/sourceConfig')){configUrlInstance.pathname=`${removeTrailingSlashes(configUrlInstance.pathname)}/sourceConfig/`;}configUrlInstance.pathname=removeDuplicateSlashes(configUrlInstance.pathname);defSearchParams.forEach((value,key)=>{if(configUrlInstance.searchParams.get(key)===null){configUrlInstance.searchParams.set(key,value);}});origin=configUrlInstance.origin;pathname=configUrlInstance.pathname;searchParams=configUrlInstance.searchParams;hash=configUrlInstance.hash;}else {logger.warn(INVALID_CONFIG_URL_WARNING(CONFIG_MANAGER,configUrl));}return `${origin}${pathname}?${searchParams}${hash}`;};/**
|
|
1341
1463
|
* Transforms destinations config from source config response to Destination format
|
|
1342
1464
|
* @param destinations Array of destination items from config response
|
|
1343
1465
|
* @returns Array of transformed Destination objects
|
|
1344
|
-
*/const getDestinationsFromConfig=destinations=>destinations.map(destination=>
|
|
1466
|
+
*/const getDestinationsFromConfig=destinations=>destinations.map(destination=>{var _destination$shouldAp,_destination$propagat;return {id:destination.id,displayName:destination.destinationDefinition.displayName,enabled:destination.enabled,config:destination.config,shouldApplyDeviceModeTransformation:(_destination$shouldAp=destination.shouldApplyDeviceModeTransformation)!==null&&_destination$shouldAp!==void 0?_destination$shouldAp:false,propagateEventsUntransformedOnError:(_destination$propagat=destination.propagateEventsUntransformedOnError)!==null&&_destination$propagat!==void 0?_destination$propagat:false,userFriendlyId:getDestinationUserFriendlyId(destination.destinationDefinition.displayName,destination.id),isCustomIntegration:destination.destinationDefinition.displayName===CUSTOM_DEVICE_MODE_DESTINATION_DISPLAY_NAME};});
|
|
1345
1467
|
|
|
1346
1468
|
/**
|
|
1347
1469
|
* A function that determines the base URL for the integrations or plugins SDK
|
|
@@ -1395,10 +1517,10 @@ state.nativeDestinations.loadOnlyIntegrations.value=integrations;});this.getConf
|
|
|
1395
1517
|
if(!isDefined(response)){if(isDefined(details)){this.onError(details.error,SOURCE_CONFIG_FETCH_ERROR);}else {this.onError(new Error(SOURCE_CONFIG_FETCH_ERROR));}return;}let res;try{if(isString(response)){res=JSON.parse(response);}else {res=response;}}catch(err){this.onError(err,SOURCE_CONFIG_RESOLUTION_ERROR);return;}if(!isValidSourceConfig(res)){this.onError(new Error(SOURCE_CONFIG_RESOLUTION_ERROR));return;}// Log error and abort if source is disabled
|
|
1396
1518
|
if(res.source.enabled===false){this.logger.error(SOURCE_DISABLED_ERROR);return;}// set the values in state for reporting slice
|
|
1397
1519
|
updateReportingState(res);const nativeDestinations=res.source.destinations.length>0?getDestinationsFromConfig(res.source.destinations):[];// set in the state --> source, destination, lifecycle, reporting
|
|
1398
|
-
n(()=>{
|
|
1520
|
+
n(()=>{var _state$loadOptions$va;// set source related information in state
|
|
1399
1521
|
state.source.value={config:res.source.config,name:res.source.name,id:res.source.id,workspaceId:res.source.workspaceId};// set device mode destination related information in state
|
|
1400
1522
|
state.nativeDestinations.configuredDestinations.value=nativeDestinations;// set the desired optional plugins
|
|
1401
|
-
state.plugins.pluginsToLoadFromConfig.value=state.loadOptions.value.plugins
|
|
1523
|
+
state.plugins.pluginsToLoadFromConfig.value=(_state$loadOptions$va=state.loadOptions.value.plugins)!==null&&_state$loadOptions$va!==void 0?_state$loadOptions$va:[];updateConsentsState(res);// set application lifecycle state
|
|
1402
1524
|
state.lifecycle.status.value='configured';});}/**
|
|
1403
1525
|
* A function to fetch source config either from /sourceConfig endpoint
|
|
1404
1526
|
* or from getSourceConfig load option
|
|
@@ -1413,19 +1535,19 @@ this.httpClient.getAsyncData({url:state.lifecycle.sourceConfigUrl.value,options:
|
|
|
1413
1535
|
* @returns string
|
|
1414
1536
|
*/const getTimezone=()=>{// Not susceptible to super-linear backtracking
|
|
1415
1537
|
// eslint-disable-next-line sonarjs/slow-regex
|
|
1416
|
-
const timezone=/([A-Z]+[+-]\d+)/.exec(new Date().toString());return timezone
|
|
1538
|
+
const timezone=/([A-Z]+[+-]\d+)/.exec(new Date().toString());return timezone!==null&&timezone!==void 0&&timezone[1]?timezone[1]:'NA';};
|
|
1417
1539
|
|
|
1418
1540
|
/**
|
|
1419
1541
|
* Get the referrer URL
|
|
1420
1542
|
* @returns The referrer URL
|
|
1421
|
-
*/const getReferrer=(getDocument=()=>document)=>getDocument()
|
|
1543
|
+
*/const getReferrer=(getDocument=()=>document)=>{var _getDocument;return ((_getDocument=getDocument())===null||_getDocument===void 0?void 0:_getDocument.referrer)||'$direct';};/**
|
|
1422
1544
|
* To get the canonical URL of the page
|
|
1423
1545
|
* @returns canonical URL
|
|
1424
|
-
*/const getCanonicalUrl=(getDocument=()=>document)=>{const docInstance=getDocument();const tags=docInstance.getElementsByTagName('link');let canonicalUrl='';for(let i=0;tags[i];i+=1){const tag=tags[i];if(tag.getAttribute('rel')==='canonical'&&!canonicalUrl){canonicalUrl=tag.getAttribute('href')
|
|
1546
|
+
*/const getCanonicalUrl=(getDocument=()=>document)=>{const docInstance=getDocument();const tags=docInstance.getElementsByTagName('link');let canonicalUrl='';for(let i=0;tags[i];i+=1){const tag=tags[i];if(tag.getAttribute('rel')==='canonical'&&!canonicalUrl){var _tag$getAttribute;canonicalUrl=(_tag$getAttribute=tag.getAttribute('href'))!==null&&_tag$getAttribute!==void 0?_tag$getAttribute:'';break;}}return canonicalUrl;};const getUserAgent=(getNavigator=()=>globalThis.navigator)=>{const navigator=getNavigator();if(isUndefined(navigator)){return null;}let{userAgent}=navigator;const{brave}=navigator;// For supporting Brave browser detection,
|
|
1425
1547
|
// add "Brave/<version>" to the user agent with the version value from the Chrome component
|
|
1426
1548
|
if(brave&&Object.getPrototypeOf(brave).isBrave){// Example:
|
|
1427
1549
|
// Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36
|
|
1428
|
-
const matchedArr=userAgent.match(/(chrome)\/([\w.]+)/i);if(matchedArr){userAgent=`${userAgent} Brave/${matchedArr[2]}`;}}return userAgent;};const getLanguage=(getNavigator=()=>globalThis.navigator)=>{const navigator=getNavigator();if(isUndefined(navigator)){return null;}return navigator.language
|
|
1550
|
+
const matchedArr=userAgent.match(/(chrome)\/([\w.]+)/i);if(matchedArr){userAgent=`${userAgent} Brave/${matchedArr[2]}`;}}return userAgent;};const getLanguage=(getNavigator=()=>globalThis.navigator)=>{var _navigator$language;const navigator=getNavigator();if(isUndefined(navigator)){return null;}return (_navigator$language=navigator.language)!==null&&_navigator$language!==void 0?_navigator$language:navigator.browserLanguage;};/**
|
|
1429
1551
|
* Default page properties
|
|
1430
1552
|
* @returns Default page properties
|
|
1431
1553
|
*/const getDefaultPageProperties=(getLocation=()=>globalThis.location,getDocument=()=>document)=>{const location=getLocation();const canonicalUrl=getCanonicalUrl(getDocument);let path=location.pathname;const{href:tabUrl}=location;let pageUrl=tabUrl;const{search}=location;// If valid canonical URL is provided use this as page URL.
|
|
@@ -1433,17 +1555,19 @@ if(canonicalUrl){try{const urlObj=new URL(canonicalUrl);// If existing, query pa
|
|
|
1433
1555
|
if(urlObj.search===''){pageUrl=canonicalUrl+search;}else {pageUrl=canonicalUrl;}path=urlObj.pathname;}catch(err){// Do nothing
|
|
1434
1556
|
}}const url=getUrlWithoutHash(pageUrl);const{title}=getDocument();const referrer=getReferrer(getDocument);return {path,referrer,referring_domain:getReferringDomain(referrer),search,title,url,tab_url:tabUrl};};
|
|
1435
1557
|
|
|
1436
|
-
const getUserAgentClientHint=(callback,level='none')=>{if(level==='none'){callback(undefined);}if(level==='default'){callback(navigator.userAgentData);}if(level==='full'){navigator.userAgentData
|
|
1437
|
-
|
|
1438
|
-
const isDatasetAvailable=()=>{const testElement=globalThis.document.createElement('div');testElement.setAttribute('data-a-b','c');return testElement.dataset?testElement.dataset.aB==='c':false;};const legacyJSEngineRequiredPolyfills={// Ideally, we should separate the checks for URL and URLSearchParams but
|
|
1439
|
-
// the polyfill service serves them under the same feature name, "URL".
|
|
1440
|
-
URL:()=>!isFunction(globalThis.URL)||!isFunction(globalThis.URLSearchParams),Promise:()=>!isFunction(globalThis.Promise),'Number.isNaN':()=>!isFunction(globalThis.Number.isNaN),'Number.isInteger':()=>!isFunction(globalThis.Number.isInteger),'Array.from':()=>!isFunction(globalThis.Array.from),'Array.prototype.find':()=>!isFunction(globalThis.Array.prototype.find),'Array.prototype.includes':()=>!isFunction(globalThis.Array.prototype.includes),'String.prototype.endsWith':()=>!isFunction(globalThis.String.prototype.endsWith),'String.prototype.startsWith':()=>!isFunction(globalThis.String.prototype.startsWith),'String.prototype.includes':()=>!isFunction(globalThis.String.prototype.includes),'String.prototype.replaceAll':()=>!isFunction(globalThis.String.prototype.replaceAll),'String.fromCodePoint':()=>!isFunction(globalThis.String.fromCodePoint),'Object.entries':()=>!isFunction(globalThis.Object.entries),'Object.values':()=>!isFunction(globalThis.Object.values),'Object.assign':()=>!isFunction(globalThis.Object.assign),'Object.fromEntries':()=>!isFunction(globalThis.Object.fromEntries),'Element.prototype.dataset':()=>!isDatasetAvailable(),// Ideally, we should separate the checks for TextEncoder and TextDecoder but
|
|
1441
|
-
// the polyfill service serves them under the same feature name, "TextEncoder".
|
|
1442
|
-
TextEncoder:()=>!isFunction(globalThis.TextEncoder)||!isFunction(globalThis.TextDecoder),requestAnimationFrame:()=>!isFunction(globalThis.requestAnimationFrame)||!isFunction(globalThis.cancelAnimationFrame),CustomEvent:()=>!isFunction(globalThis.CustomEvent),'navigator.sendBeacon':()=>!isFunction(globalThis.navigator.sendBeacon),// Note, the polyfill service serves both ArrayBuffer and Uint8Array under the same feature name, "ArrayBuffer".
|
|
1443
|
-
ArrayBuffer:()=>!isFunction(globalThis.Uint8Array),Set:()=>!isFunction(globalThis.Set),atob:()=>!isFunction(globalThis.atob)};const isLegacyJSEngine=()=>{const requiredCapabilitiesList=Object.keys(legacyJSEngineRequiredPolyfills);let needsPolyfill=false;/* eslint-disable-next-line unicorn/no-for-loop */for(let i=0;i<requiredCapabilitiesList.length;i++){const isCapabilityMissing=legacyJSEngineRequiredPolyfills[requiredCapabilitiesList[i]];if(isFunction(isCapabilityMissing)&&isCapabilityMissing()){needsPolyfill=true;break;}}return needsPolyfill;};
|
|
1558
|
+
const getUserAgentClientHint=(callback,level='none')=>{if(level==='none'){callback(undefined);}if(level==='default'){callback(navigator.userAgentData);}if(level==='full'){var _navigator$userAgentD;(_navigator$userAgentD=navigator.userAgentData)===null||_navigator$userAgentD===void 0||_navigator$userAgentD.getHighEntropyValues(['architecture','bitness','brands','mobile','model','platform','platformVersion','uaFullVersion','fullVersionList','wow64']).then(ua=>{callback(ua);}).catch(()=>{callback();});}};
|
|
1444
1559
|
|
|
1445
|
-
const
|
|
1446
|
-
|
|
1560
|
+
const detectAdBlockers=httpClient=>{state.capabilities.isAdBlockerDetectionInProgress.value=true;try{// Apparently, '?view=ad' is a query param that is blocked by majority of adblockers
|
|
1561
|
+
// Use source config URL here as it is very unlikely to be blocked by adblockers
|
|
1562
|
+
// Only the extra query param should make it vulnerable to adblockers
|
|
1563
|
+
// This will work even if the users proxies it.
|
|
1564
|
+
// The edge case where this doesn't work is when HEAD method is not allowed by the server (user's)
|
|
1565
|
+
const baseUrl=new URL(state.lifecycle.sourceConfigUrl.value);const url=`${baseUrl.origin}${baseUrl.pathname}?view=ad`;httpClient.getAsyncData({url,options:{// We actually don't need the response from the request, so we are using HEAD
|
|
1566
|
+
method:'HEAD',headers:{'Content-Type':undefined}},isRawResponse:true,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
|
|
1567
|
+
// Often adblockers instead of blocking the request, they redirect it to an internal URL
|
|
1568
|
+
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
|
|
1569
|
+
state.capabilities.isAdBlockerDetectionInProgress.value=false;// Re-throw the error to be handled by the caller
|
|
1570
|
+
throw err;}};
|
|
1447
1571
|
|
|
1448
1572
|
const hasCrypto=()=>!isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);// eslint-disable-next-line compat/compat -- We are checking for the existence of navigator.userAgentData
|
|
1449
1573
|
const hasUAClientHints=()=>!isNullOrUndefined(globalThis.navigator.userAgentData);const hasBeacon=()=>!isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);
|
|
@@ -1459,10 +1583,13 @@ state.capabilities.isBeaconAvailable.value=hasBeacon();state.capabilities.isUaCH
|
|
|
1459
1583
|
state.context.userAgent.value=getUserAgent();state.context.locale.value=getLanguage();state.context.screen.value=getScreenDetails();state.context.timezone.value=getTimezone();if(hasUAClientHints()){getUserAgentClientHint(uach=>{state.context['ua-ch'].value=uach;},state.loadOptions.value.uaChTrackLevel);}});// Ad blocker detection
|
|
1460
1584
|
j(()=>{if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(this.httpClient);}});}/**
|
|
1461
1585
|
* Detect if polyfills are required and then load script from polyfill URL
|
|
1462
|
-
*/prepareBrowserCapabilities(){
|
|
1463
|
-
//
|
|
1464
|
-
|
|
1465
|
-
|
|
1586
|
+
*/prepareBrowserCapabilities(){// The snippet only hands the modern build to engines that ship every polyfill-list API the
|
|
1587
|
+
// SDK and integrations call (replaceAll is listed but unused), so this is legacy-only.
|
|
1588
|
+
{this.onReady();return;}}/**
|
|
1589
|
+
* Report the features that the polyfill script did not apply and then set the
|
|
1590
|
+
* lifecycle status to next phase
|
|
1591
|
+
*/onPolyfillLoaded(){// Guarded too so the detection list is dropped from the modern bundle
|
|
1592
|
+
this.onReady();}/**
|
|
1466
1593
|
* Attach listeners to window to observe event that update capabilities state values
|
|
1467
1594
|
*/attachWindowListeners(){globalThis.addEventListener('offline',()=>{state.capabilities.isOnline.value=false;});globalThis.addEventListener('online',()=>{state.capabilities.isOnline.value=true;});globalThis.addEventListener('resize',debounce(()=>{state.context.screen.value=getScreenDetails();},this));}/**
|
|
1468
1595
|
* Set the lifecycle status to next phase
|
|
@@ -1470,7 +1597,7 @@ delete globalThis[polyfillCallbackName];};globalThis[polyfillCallbackName]=polyf
|
|
|
1470
1597
|
onReady(){this.detectBrowserCapabilities();state.lifecycle.status.value='browserCapabilitiesReady';}/**
|
|
1471
1598
|
* Handles error
|
|
1472
1599
|
* @param error The error object
|
|
1473
|
-
*/onError(error,groupingHash){this.errorHandler.onError({error,context:CAPABILITIES_MANAGER,groupingHash});}}
|
|
1600
|
+
*/onError(error,groupingHash){void this.errorHandler.onError({error,context:CAPABILITIES_MANAGER,groupingHash});}}
|
|
1474
1601
|
|
|
1475
1602
|
const CHANNEL='web';// These are the top-level elements in the standard RudderStack event spec
|
|
1476
1603
|
const TOP_LEVEL_ELEMENTS=['integrations','anonymousId','originalTimestamp'];// Reserved elements in the context of standard RudderStack event spec
|
|
@@ -1478,7 +1605,7 @@ const TOP_LEVEL_ELEMENTS=['integrations','anonymousId','originalTimestamp'];// R
|
|
|
1478
1605
|
const CONTEXT_RESERVED_ELEMENTS=['library','consentManagement','userAgent','ua-ch','screen'];// Reserved elements in the standard RudderStack event spec
|
|
1479
1606
|
const RESERVED_ELEMENTS=['id','anonymous_id','user_id','sent_at','timestamp','received_at','original_timestamp','event','event_text','channel','context_ip','context_request_ip','context_passed_ip','group_id','previous_id'];
|
|
1480
1607
|
|
|
1481
|
-
const CUSTOM_CONTEXT='CustomContext';const PROTOTYPE_POLLUTION_KEYS=new Set(['__proto__','constructor','prototype']);const OBJECT_CONSTRUCTOR_SOURCE=Function.prototype.toString.call(Object);const isPlainObject=value=>{if(!isObjectLiteralAndNotNull(value)){return false;}const prototype=Object.getPrototypeOf(value);if(prototype===null){return true;}const constructor=Object.prototype.hasOwnProperty.call(prototype,'constructor')?prototype.constructor:undefined;return typeof constructor==='function'&&constructor.prototype===prototype&&Function.prototype.toString.call(constructor)===OBJECT_CONSTRUCTOR_SOURCE;};const containsPrototypePollutionKey=(value,visitedObjects=new Set())=>{if(!isObjectLiteralAndNotNull(value)&&!Array.isArray(value)){return false;}const traversableValue=value;if(visitedObjects.has(traversableValue)){return false;}visitedObjects.add(traversableValue);return Object.keys(traversableValue).some(key=>{return PROTOTYPE_POLLUTION_KEYS.has(key)||containsPrototypePollutionKey(traversableValue[key],visitedObjects);});};const filterReservedCustomContextKeys=(context,logger)=>{const retainedContext={};Object.keys(context).forEach(key=>{if(CONTEXT_RESERVED_ELEMENTS.includes(key)){logger.warn(RESERVED_CUSTOM_CONTEXT_KEY_WARNING(CUSTOM_CONTEXT,key));return;}Object.defineProperty(retainedContext,key,{configurable:true,enumerable:true,value:context[key]===context?retainedContext:context[key],writable:true});});return retainedContext;};const prepareCustomContextUpdate=(input,logger)=>{try{if(!isPlainObject(input)){logger.warn(INVALID_CUSTOM_CONTEXT_WARNING(CUSTOM_CONTEXT));return undefined;}const acceptedInput=filterReservedCustomContextKeys(input,logger);if(containsPrototypePollutionKey(acceptedInput)){logger.warn(INVALID_CUSTOM_CONTEXT_WARNING(CUSTOM_CONTEXT));return undefined;}const sanitizedContext=getSanitizedValue(acceptedInput,logger);return clone(sanitizedContext);}catch{logger.warn(INVALID_CUSTOM_CONTEXT_WARNING(CUSTOM_CONTEXT));return undefined;}};
|
|
1608
|
+
const CUSTOM_CONTEXT='CustomContext';const PROTOTYPE_POLLUTION_KEYS=new Set(['__proto__','constructor','prototype']);const OBJECT_CONSTRUCTOR_SOURCE=Function.prototype.toString.call(Object);const isPlainObject=value=>{if(!isObjectLiteralAndNotNull(value)){return false;}const prototype=Object.getPrototypeOf(value);if(prototype===null){return true;}const constructor=Object.prototype.hasOwnProperty.call(prototype,'constructor')?prototype.constructor:undefined;return typeof constructor==='function'&&constructor.prototype===prototype&&Function.prototype.toString.call(constructor)===OBJECT_CONSTRUCTOR_SOURCE;};const containsPrototypePollutionKey=(value,visitedObjects=new Set())=>{if(!isObjectLiteralAndNotNull(value)&&!Array.isArray(value)){return false;}const traversableValue=value;if(visitedObjects.has(traversableValue)){return false;}visitedObjects.add(traversableValue);return Object.keys(traversableValue).some(key=>{return PROTOTYPE_POLLUTION_KEYS.has(key)||containsPrototypePollutionKey(traversableValue[key],visitedObjects);});};const filterReservedCustomContextKeys=(context,logger)=>{const retainedContext={};Object.keys(context).forEach(key=>{if(CONTEXT_RESERVED_ELEMENTS.includes(key)){logger.warn(RESERVED_CUSTOM_CONTEXT_KEY_WARNING(CUSTOM_CONTEXT,key));return;}Object.defineProperty(retainedContext,key,{configurable:true,enumerable:true,value:context[key]===context?retainedContext:context[key],writable:true});});return retainedContext;};const prepareCustomContextUpdate=(input,logger)=>{try{if(!isPlainObject(input)){logger.warn(INVALID_CUSTOM_CONTEXT_WARNING(CUSTOM_CONTEXT));return undefined;}const acceptedInput=filterReservedCustomContextKeys(input,logger);if(containsPrototypePollutionKey(acceptedInput)){logger.warn(INVALID_CUSTOM_CONTEXT_WARNING(CUSTOM_CONTEXT));return undefined;}const sanitizedContext=getSanitizedValue(acceptedInput,logger);return clone(sanitizedContext);}catch(_unused){logger.warn(INVALID_CUSTOM_CONTEXT_WARNING(CUSTOM_CONTEXT));return undefined;}};
|
|
1482
1609
|
|
|
1483
1610
|
class CustomContextStore{constructor(state,logger){this.state=state;this.logger=logger;}set(context){const update=prepareCustomContextUpdate(context,this.logger);if(!update){return;}const mergedContext=mergeDeepRight(clone(this.state.value),update);this.state.value=removeUndefinedAndNullValues(mergedContext);}get(){return clone(this.state.value);}clear(){this.state.value={};}}
|
|
1484
1611
|
|
|
@@ -1497,7 +1624,7 @@ class CustomContextStore{constructor(state,logger){this.state=state;this.logger=
|
|
|
1497
1624
|
* @returns boolean
|
|
1498
1625
|
*/const isPositiveInteger=num=>isNumber(num)&&num>=0&&Number.isInteger(num);
|
|
1499
1626
|
|
|
1500
|
-
const MIN_SESSION_ID_LENGTH=10;const isCutOffTimeExceeded=sessionInfo=>{const{cutOff}=sessionInfo;const timestamp=Date.now();return Boolean(cutOff
|
|
1627
|
+
const _excluded$1=["entries"];const MIN_SESSION_ID_LENGTH=10;const isCutOffTimeExceeded=sessionInfo=>{const{cutOff}=sessionInfo;const timestamp=Date.now();return Boolean((cutOff===null||cutOff===void 0?void 0:cutOff.enabled)&&cutOff.expiresAt&×tamp>cutOff.expiresAt);};/**
|
|
1501
1628
|
* A function to validate whether the current auto tracking session has expired or not.
|
|
1502
1629
|
* It checks for the current session expiry and the cut off time expiry.
|
|
1503
1630
|
* @param sessionInfo session info
|
|
@@ -1510,13 +1637,13 @@ const MIN_SESSION_ID_LENGTH=10;const isCutOffTimeExceeded=sessionInfo=>{const{cu
|
|
|
1510
1637
|
* @param {number} sessionId
|
|
1511
1638
|
* @param logger logger
|
|
1512
1639
|
* @returns
|
|
1513
|
-
*/const isManualSessionIdValid=(sessionId,logger)=>{if(!sessionId||!isPositiveInteger(sessionId)||!hasMinLength(MIN_SESSION_ID_LENGTH,sessionId)){logger.warn(INVALID_SESSION_ID_WARNING(USER_SESSION_MANAGER,sessionId,MIN_SESSION_ID_LENGTH));return false;}return true;};const getCutOffExpirationTimestamp=cutOff=>{if(!cutOff
|
|
1640
|
+
*/const isManualSessionIdValid=(sessionId,logger)=>{if(!sessionId||!isPositiveInteger(sessionId)||!hasMinLength(MIN_SESSION_ID_LENGTH,sessionId)){logger.warn(INVALID_SESSION_ID_WARNING(USER_SESSION_MANAGER,sessionId,MIN_SESSION_ID_LENGTH));return false;}return true;};const getCutOffExpirationTimestamp=cutOff=>{var _cutOff$expiresAt;if(!(cutOff!==null&&cutOff!==void 0&&cutOff.enabled)){return undefined;}return (_cutOff$expiresAt=cutOff.expiresAt)!==null&&_cutOff$expiresAt!==void 0?_cutOff$expiresAt:isPositiveInteger(cutOff.duration)?Date.now()+cutOff.duration:undefined;};/**
|
|
1514
1641
|
* A function to generate new auto tracking session
|
|
1515
1642
|
* @param sessionInfo session info
|
|
1516
1643
|
* @returns SessionInfo
|
|
1517
|
-
*/const generateAutoTrackingSession=sessionInfo=>{const{timeout,cutOff}=sessionInfo;const timestamp=Date.now();return {id:timestamp,// set the current timestamp
|
|
1644
|
+
*/const generateAutoTrackingSession=sessionInfo=>{const{timeout,cutOff}=sessionInfo;const timestamp=Date.now();return _objectSpread2({id:timestamp,// set the current timestamp
|
|
1518
1645
|
expiresAt:timestamp+timeout,// set the expiry time of the session
|
|
1519
|
-
timeout,autoTrack:true
|
|
1646
|
+
timeout,autoTrack:true},cutOff&&{cutOff});};/**
|
|
1520
1647
|
* A function to generate new manual tracking session
|
|
1521
1648
|
* @param id Provided sessionId
|
|
1522
1649
|
* @param logger Logger module
|
|
@@ -1525,19 +1652,19 @@ timeout,autoTrack:true,...(cutOff&&{cutOff})};};/**
|
|
|
1525
1652
|
* Generate a new anonymousId
|
|
1526
1653
|
* @returns string anonymousID
|
|
1527
1654
|
*/const generateAnonymousId=()=>generateUUID();const isKnownResetEntry=key=>Object.prototype.hasOwnProperty.call(DEFAULT_RESET_OPTIONS.entries,key);const getFinalResetOptions=options=>{// Legacy behavior: toggle only anonymousId without mutating defaults
|
|
1528
|
-
if(isBoolean(options)){const{entries
|
|
1529
|
-
if(isObjectLiteralAndNotNull(options)&&isObjectLiteralAndNotNull(options.entries)){const optionEntries=options.entries;const validEntries=Object.keys(optionEntries).reduce((entries,key)=>{if(isKnownResetEntry(key)){const value=optionEntries[key];if(isBoolean(value)){entries[key]=value;}}return entries;},{});return mergeDeepRight(DEFAULT_RESET_OPTIONS,{entries:validEntries});}return {
|
|
1655
|
+
if(isBoolean(options)){const{entries}=DEFAULT_RESET_OPTIONS,rest=_objectWithoutProperties(DEFAULT_RESET_OPTIONS,_excluded$1);return _objectSpread2(_objectSpread2({},rest),{},{entries:_objectSpread2(_objectSpread2({},entries),{},{anonymousId:options})});}// Override any defaults with the user provided options
|
|
1656
|
+
if(isObjectLiteralAndNotNull(options)&&isObjectLiteralAndNotNull(options.entries)){const optionEntries=options.entries;const validEntries=Object.keys(optionEntries).reduce((entries,key)=>{if(isKnownResetEntry(key)){const value=optionEntries[key];if(isBoolean(value)){entries[key]=value;}}return entries;},{});return mergeDeepRight(DEFAULT_RESET_OPTIONS,{entries:validEntries});}return _objectSpread2({},DEFAULT_RESET_OPTIONS);};
|
|
1530
1657
|
|
|
1531
1658
|
/**
|
|
1532
1659
|
* To get the page properties for context object
|
|
1533
1660
|
* @param pageProps Page properties
|
|
1534
1661
|
* @returns page properties object for context
|
|
1535
1662
|
*/const getContextPageProperties=pageProps=>{// Need to get updated page details on each event as an event to notify on SPA URL changes does not seem to exist
|
|
1536
|
-
const curPageProps=getDefaultPageProperties();const ctxPageProps={};Object.keys(curPageProps).forEach(key=>{ctxPageProps[key]=pageProps
|
|
1663
|
+
const curPageProps=getDefaultPageProperties();const ctxPageProps={};Object.keys(curPageProps).forEach(key=>{ctxPageProps[key]=(pageProps===null||pageProps===void 0?void 0:pageProps[key])||curPageProps[key];});ctxPageProps.initial_referrer=(pageProps===null||pageProps===void 0?void 0:pageProps.initial_referrer)||state.session.initialReferrer.value;ctxPageProps.initial_referring_domain=(pageProps===null||pageProps===void 0?void 0:pageProps.initial_referring_domain)||state.session.initialReferringDomain.value;return ctxPageProps;};/**
|
|
1537
1664
|
* Add any missing default page properties using values from options and defaults
|
|
1538
1665
|
* @param properties Input page properties
|
|
1539
1666
|
* @param options API options
|
|
1540
|
-
*/const getUpdatedPageProperties=(properties,options)=>{const optionsPageProps=options
|
|
1667
|
+
*/const getUpdatedPageProperties=(properties,options)=>{const optionsPageProps=(options===null||options===void 0?void 0:options.page)||{};const pageProps=properties;// Need to get updated page details on each event as an event to notify on SPA URL changes does not seem to exist
|
|
1541
1668
|
const curPageProps=getDefaultPageProperties();Object.keys(curPageProps).forEach(key=>{if(isUndefined(pageProps[key])){pageProps[key]=optionsPageProps[key]||curPageProps[key];}});if(isUndefined(pageProps.initial_referrer)){pageProps.initial_referrer=optionsPageProps.initial_referrer||state.session.initialReferrer.value;}if(isUndefined(pageProps.initial_referring_domain)){pageProps.initial_referring_domain=optionsPageProps.initial_referring_domain||state.session.initialReferringDomain.value;}return pageProps;};/**
|
|
1542
1669
|
* Utility to check for reserved keys in the input object
|
|
1543
1670
|
* @param obj Generic object
|
|
@@ -1570,20 +1697,18 @@ rudderEvent.context=getMergedContext(rudderEvent.context,options,logger);}};/**
|
|
|
1570
1697
|
* Returns the final integrations config for the event based on the global config and event's config
|
|
1571
1698
|
* @param integrationsConfig Event's integrations config
|
|
1572
1699
|
* @returns Final integrations config
|
|
1573
|
-
*/const getEventIntegrationsConfig=integrationsConfig=>{let finalIntgConfig;if(state.loadOptions.value.useGlobalIntegrationsConfigInEvents){
|
|
1574
|
-
finalIntgConfig=state.consents.postConsent.value.integrations
|
|
1700
|
+
*/const getEventIntegrationsConfig=integrationsConfig=>{let finalIntgConfig;if(state.loadOptions.value.useGlobalIntegrationsConfigInEvents){var _state$consents$postC;// Prefer the integrations object from the consent API response over the load API integrations object
|
|
1701
|
+
finalIntgConfig=(_state$consents$postC=state.consents.postConsent.value.integrations)!==null&&_state$consents$postC!==void 0?_state$consents$postC:state.nativeDestinations.loadOnlyIntegrations.value;}else if(integrationsConfig){finalIntgConfig=integrationsConfig;}else {finalIntgConfig=DEFAULT_INTEGRATIONS_CONFIG;}return clone(finalIntgConfig);};/**
|
|
1575
1702
|
* Enrich the base event object with data from state and the API options
|
|
1576
1703
|
* @param rudderEvent RudderEvent object
|
|
1577
1704
|
* @param options API options
|
|
1578
1705
|
* @param pageProps Page properties
|
|
1579
1706
|
* @param logger logger
|
|
1580
1707
|
* @returns Enriched RudderEvent object
|
|
1581
|
-
*/const getEnrichedEvent=(rudderEvent,options,pageProps,logger,customContext={})=>{const commonEventData={channel:CHANNEL,context:{traits:clone(state.session.userTraits.value),sessionId:state.session.sessionInfo.value.id||undefined,sessionStart:state.session.sessionInfo.value.sessionStart||undefined
|
|
1582
|
-
...(state.consents.enabled.value&&{consentManagement:{deniedConsentIds:clone(state.consents.data.value.deniedConsentIds),allowedConsentIds:clone(state.consents.data.value.allowedConsentIds),provider:state.consents.provider.value,resolutionStrategy:state.consents.resolutionStrategy.value}}),'ua-ch':state.context['ua-ch'].value,app:state.context.app.value,library:state.context.library.value,userAgent:state.context.userAgent.value,os:state.context.os.value,locale:state.context.locale.value,screen:state.context.screen.value,campaign:extractUTMParameters(globalThis.location.href),page:getContextPageProperties(pageProps),timezone:state.context.timezone.value,// Add auto tracking information
|
|
1583
|
-
...(state.autoTrack.enabled.value&&{autoTrack:{...(state.autoTrack.pageLifecycle.enabled.value&&{page:{pageViewId:state.autoTrack.pageLifecycle.pageViewId.value}})}})},originalTimestamp:getCurrentTimeFormatted(),messageId:generateUUID(),userId:rudderEvent.userId||state.session.userId.value};if(!isStorageTypeValidForStoringData(state.storage.entries.value.anonymousId?.type)){// Generate new anonymous id for each request
|
|
1708
|
+
*/const getEnrichedEvent=(rudderEvent,options,pageProps,logger,customContext={})=>{var _state$storage$entrie;const commonEventData={channel:CHANNEL,context:_objectSpread2(_objectSpread2({traits:clone(state.session.userTraits.value),sessionId:state.session.sessionInfo.value.id||undefined,sessionStart:state.session.sessionInfo.value.sessionStart||undefined},state.consents.enabled.value&&{consentManagement:{deniedConsentIds:clone(state.consents.data.value.deniedConsentIds),allowedConsentIds:clone(state.consents.data.value.allowedConsentIds),provider:state.consents.provider.value,resolutionStrategy:state.consents.resolutionStrategy.value}}),{},{'ua-ch':state.context['ua-ch'].value,app:state.context.app.value,library:state.context.library.value,userAgent:state.context.userAgent.value,os:state.context.os.value,locale:state.context.locale.value,screen:state.context.screen.value,campaign:extractUTMParameters(globalThis.location.href),page:getContextPageProperties(pageProps),timezone:state.context.timezone.value},state.autoTrack.enabled.value&&{autoTrack:_objectSpread2({},state.autoTrack.pageLifecycle.enabled.value&&{page:{pageViewId:state.autoTrack.pageLifecycle.pageViewId.value}})}),originalTimestamp:getCurrentTimeFormatted(),messageId:generateUUID(),userId:rudderEvent.userId||state.session.userId.value};if(!isStorageTypeValidForStoringData((_state$storage$entrie=state.storage.entries.value.anonymousId)===null||_state$storage$entrie===void 0?void 0:_state$storage$entrie.type)){// Generate new anonymous id for each request
|
|
1584
1709
|
commonEventData.anonymousId=generateAnonymousId();}else {// Type casting to string as the user session manager will take care of initializing the value
|
|
1585
1710
|
commonEventData.anonymousId=state.session.anonymousId.value;}// set truly anonymous tracking flag
|
|
1586
|
-
if(state.storage.trulyAnonymousTracking.value){commonEventData.context.trulyAnonymousTracking=true;}if(rudderEvent.type==='identify'){commonEventData.context.traits=state.storage.entries.value.userTraits
|
|
1711
|
+
if(state.storage.trulyAnonymousTracking.value){commonEventData.context.trulyAnonymousTracking=true;}if(rudderEvent.type==='identify'){var _state$storage$entrie2;commonEventData.context.traits=((_state$storage$entrie2=state.storage.entries.value.userTraits)===null||_state$storage$entrie2===void 0?void 0:_state$storage$entrie2.type)!==NO_STORAGE?clone(state.session.userTraits.value):rudderEvent.context.traits;}if(rudderEvent.type==='group'){if(rudderEvent.groupId||state.session.groupId.value){commonEventData.groupId=rudderEvent.groupId||state.session.groupId.value;}if(rudderEvent.traits||state.session.groupTraits.value){var _state$storage$entrie3;commonEventData.traits=((_state$storage$entrie3=state.storage.entries.value.groupTraits)===null||_state$storage$entrie3===void 0?void 0:_state$storage$entrie3.type)!==NO_STORAGE?clone(state.session.groupTraits.value):rudderEvent.traits;}}const sdkBuiltEvent=mergeDeepRight(rudderEvent,commonEventData);const processedEvent=mergeDeepRight(sdkBuiltEvent,{context:customContext});// Set the default values for the event properties
|
|
1587
1712
|
// matching with v1.1 payload
|
|
1588
1713
|
if(processedEvent.event===undefined){processedEvent.event=null;}if(processedEvent.properties===undefined){processedEvent.properties=null;}processOptions(processedEvent,options,logger);checkForReservedElements(processedEvent,logger);// Update the integrations config for the event
|
|
1589
1714
|
processedEvent.integrations=getEventIntegrationsConfig(processedEvent.integrations);return processedEvent;};
|
|
@@ -1594,7 +1719,7 @@ class RudderEventFactory{constructor(logger){this.logger=logger;}/**
|
|
|
1594
1719
|
* @param name Page name
|
|
1595
1720
|
* @param properties Page properties
|
|
1596
1721
|
* @param options API options
|
|
1597
|
-
*/generatePageEvent(category,name,properties,options,customContext={}){let props=properties
|
|
1722
|
+
*/generatePageEvent(category,name,properties,options,customContext={}){let props=properties!==null&&properties!==void 0?properties:{};props=getUpdatedPageProperties(props,options);const pageEvent={properties:props,name,category,type:'page'};return getEnrichedEvent(pageEvent,options,props,this.logger,customContext);}/**
|
|
1598
1723
|
* Generate a 'track' event based on the user-input fields
|
|
1599
1724
|
* @param event The event name
|
|
1600
1725
|
* @param properties Event properties
|
|
@@ -1610,7 +1735,7 @@ class RudderEventFactory{constructor(logger){this.logger=logger;}/**
|
|
|
1610
1735
|
* @param from Old user ID
|
|
1611
1736
|
* @param options API options
|
|
1612
1737
|
*/generateAliasEvent(to,from,options,customContext={}){const aliasEvent={previousId:from,type:'alias'};const enrichedEvent=getEnrichedEvent(aliasEvent,options,undefined,this.logger,customContext);// override the User ID from the API inputs
|
|
1613
|
-
enrichedEvent.userId=to
|
|
1738
|
+
enrichedEvent.userId=to!==null&&to!==void 0?to:enrichedEvent.userId;return enrichedEvent;}/**
|
|
1614
1739
|
* Generate a 'group' event based on the user-input fields
|
|
1615
1740
|
* @param groupId New group ID
|
|
1616
1741
|
* @param traits new group traits
|
|
@@ -1651,16 +1776,16 @@ class UserSessionManager{/**
|
|
|
1651
1776
|
* Initialize User session with values from storage
|
|
1652
1777
|
*/init(){this.syncStorageDataToState();// Register the effect to sync with storage
|
|
1653
1778
|
this.registerEffects();}syncStorageDataToState(){this.migrateStorageIfNeeded();this.migrateDataFromPreviousStorage();// get the values from storage and set it again
|
|
1654
|
-
this.setUserId(this.getUserId());this.setUserTraits(this.getUserTraits());this.setGroupId(this.getGroupId());this.setGroupTraits(this.getGroupTraits());const{externalAnonymousIdCookieName,anonymousIdOptions}=state.loadOptions.value;let externalAnonymousId;if(isDefinedAndNotNull(externalAnonymousIdCookieName)&&typeof externalAnonymousIdCookieName==='string'){externalAnonymousId=this.getExternalAnonymousIdByCookieName(externalAnonymousIdCookieName);}this.setAnonymousId(externalAnonymousId
|
|
1779
|
+
this.setUserId(this.getUserId());this.setUserTraits(this.getUserTraits());this.setGroupId(this.getGroupId());this.setGroupTraits(this.getGroupTraits());const{externalAnonymousIdCookieName,anonymousIdOptions}=state.loadOptions.value;let externalAnonymousId;if(isDefinedAndNotNull(externalAnonymousIdCookieName)&&typeof externalAnonymousIdCookieName==='string'){externalAnonymousId=this.getExternalAnonymousIdByCookieName(externalAnonymousIdCookieName);}this.setAnonymousId(externalAnonymousId!==null&&externalAnonymousId!==void 0?externalAnonymousId:this.getAnonymousId(anonymousIdOptions));this.setAuthToken(this.getAuthToken());this.setInitialReferrerInfo();this.configureSessionTracking();}configureSessionTracking(){let sessionInfo;if(this.isPersistenceEnabledForStorageEntry('sessionInfo')){var _this$getSessionInfo,_configuredSessionTra;const configuredSessionTrackingInfo=this.getConfiguredSessionTrackingInfo();const initialSessionInfo=(_this$getSessionInfo=this.getSessionInfo())!==null&&_this$getSessionInfo!==void 0?_this$getSessionInfo:DEFAULT_USER_SESSION_VALUES.sessionInfo;// Merge the session info from the storage and the configuration
|
|
1655
1780
|
sessionInfo={// If manualTrack is set to true in the storage, then do not enable auto tracking even if configured.
|
|
1656
1781
|
// Once manual tracking ends (endSession is called), auto tracking will be enabled in the next SDK run.
|
|
1657
1782
|
autoTrack:configuredSessionTrackingInfo.autoTrack&&initialSessionInfo.manualTrack!==true,timeout:configuredSessionTrackingInfo.timeout,manualTrack:initialSessionInfo.manualTrack,expiresAt:initialSessionInfo.expiresAt,id:initialSessionInfo.id,sessionStart:initialSessionInfo.sessionStart};// If both autoTrack and manualTrack are disabled, reset the session info to default values
|
|
1658
|
-
if(!sessionInfo.autoTrack&&sessionInfo.manualTrack!==true){sessionInfo=DEFAULT_USER_SESSION_VALUES.sessionInfo;}else if(configuredSessionTrackingInfo.cutOff
|
|
1659
|
-
if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking(state.session.sessionInfo.value);}}setInitialReferrerInfo(){const persistedInitialReferrer=this.getInitialReferrer();const persistedInitialReferringDomain=this.getInitialReferringDomain();if(persistedInitialReferrer&&persistedInitialReferringDomain){this.setInitialReferrer(persistedInitialReferrer);this.setInitialReferringDomain(persistedInitialReferringDomain);}else {const initialReferrer=persistedInitialReferrer||getReferrer();this.setInitialReferrer(initialReferrer);this.setInitialReferringDomain(getReferringDomain(initialReferrer));}}isPersistenceEnabledForStorageEntry(entryName){return isStorageTypeValidForStoringData(state.storage.entries.value[entryName]
|
|
1783
|
+
if(!sessionInfo.autoTrack&&sessionInfo.manualTrack!==true){sessionInfo=DEFAULT_USER_SESSION_VALUES.sessionInfo;}else if(((_configuredSessionTra=configuredSessionTrackingInfo.cutOff)===null||_configuredSessionTra===void 0?void 0:_configuredSessionTra.enabled)===true){var _initialSessionInfo$c;sessionInfo.cutOff={enabled:true,duration:configuredSessionTrackingInfo.cutOff.duration,expiresAt:(_initialSessionInfo$c=initialSessionInfo.cutOff)===null||_initialSessionInfo$c===void 0?void 0:_initialSessionInfo$c.expiresAt};}}else {sessionInfo=DEFAULT_USER_SESSION_VALUES.sessionInfo;}state.session.sessionInfo.value=sessionInfo;// If auto session tracking is enabled start the session tracking
|
|
1784
|
+
if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking(state.session.sessionInfo.value);}}setInitialReferrerInfo(){const persistedInitialReferrer=this.getInitialReferrer();const persistedInitialReferringDomain=this.getInitialReferringDomain();if(persistedInitialReferrer&&persistedInitialReferringDomain){this.setInitialReferrer(persistedInitialReferrer);this.setInitialReferringDomain(persistedInitialReferringDomain);}else {const initialReferrer=persistedInitialReferrer||getReferrer();this.setInitialReferrer(initialReferrer);this.setInitialReferringDomain(getReferringDomain(initialReferrer));}}isPersistenceEnabledForStorageEntry(entryName){var _state$storage$entrie;return isStorageTypeValidForStoringData((_state$storage$entrie=state.storage.entries.value[entryName])===null||_state$storage$entrie===void 0?void 0:_state$storage$entrie.type);}migrateDataFromPreviousStorage(){const entries=state.storage.entries.value;const storageTypesForMigration=[COOKIE_STORAGE,LOCAL_STORAGE,SESSION_STORAGE];Object.keys(entries).forEach(entry=>{var _entries$key,_this$storeManager;const key=entry;const currentStorage=(_entries$key=entries[key])===null||_entries$key===void 0?void 0:_entries$key.type;const curStore=(_this$storeManager=this.storeManager)===null||_this$storeManager===void 0?void 0:_this$storeManager.getStore(storageClientDataStoreNameMap[currentStorage]);if(curStore){storageTypesForMigration.forEach(storage=>{var _this$storeManager2;const store=(_this$storeManager2=this.storeManager)===null||_this$storeManager2===void 0?void 0:_this$storeManager2.getStore(storageClientDataStoreNameMap[storage]);if(store&&storage!==currentStorage){const value=store.get(COOKIE_KEYS[key]);if(isDefinedNotNullAndNotEmptyString(value)){curStore.set(COOKIE_KEYS[key],value);}store.remove(COOKIE_KEYS[key]);}});}});}migrateStorageIfNeeded(stores,keys){if(!state.storage.migrate.value){return;}let storesToMigrate=stores!==null&&stores!==void 0?stores:[];if(storesToMigrate.length===0){const persistentStoreNames=[CLIENT_DATA_STORE_COOKIE,CLIENT_DATA_STORE_LS,CLIENT_DATA_STORE_SESSION];persistentStoreNames.forEach(storeName=>{var _this$storeManager3;const store=(_this$storeManager3=this.storeManager)===null||_this$storeManager3===void 0?void 0:_this$storeManager3.getStore(storeName);if(store){storesToMigrate.push(store);}});}let keysToMigrate=keys!==null&&keys!==void 0?keys:Object.keys(COOKIE_KEYS);keysToMigrate.forEach(storageKey=>{const storageEntry=COOKIE_KEYS[storageKey];storesToMigrate.forEach(store=>{var _this$pluginsManager;const migratedVal=(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0?void 0:_this$pluginsManager.invokeSingle('storage.migrate',storageEntry,store.engine,this.errorHandler,this.logger);// Skip setting the value if it is null or undefined
|
|
1660
1785
|
// as those values indicate there is no need for migration or
|
|
1661
1786
|
// migration failed
|
|
1662
|
-
if(!isNullOrUndefined(migratedVal)){store.set(storageEntry,migratedVal);}});});}getConfiguredSessionTrackingInfo(){let autoTrack=state.loadOptions.value.sessions.autoTrack!==false;// Do not validate any further if autoTrack is disabled
|
|
1663
|
-
if(!autoTrack){return {autoTrack};}let timeout;const configuredSessionTimeout=state.loadOptions.value.sessions
|
|
1787
|
+
if(!isNullOrUndefined(migratedVal)){store.set(storageEntry,migratedVal);}});});}getConfiguredSessionTrackingInfo(){var _state$loadOptions$va;let autoTrack=state.loadOptions.value.sessions.autoTrack!==false;// Do not validate any further if autoTrack is disabled
|
|
1788
|
+
if(!autoTrack){return {autoTrack};}let timeout;const configuredSessionTimeout=(_state$loadOptions$va=state.loadOptions.value.sessions)===null||_state$loadOptions$va===void 0?void 0:_state$loadOptions$va.timeout;if(!isPositiveInteger(configuredSessionTimeout)){this.logger.warn(TIMEOUT_NOT_NUMBER_WARNING(USER_SESSION_MANAGER,configuredSessionTimeout,DEFAULT_SESSION_TIMEOUT_MS));timeout=DEFAULT_SESSION_TIMEOUT_MS;}else {timeout=configuredSessionTimeout;}if(timeout===0){this.logger.warn(TIMEOUT_ZERO_WARNING(USER_SESSION_MANAGER));autoTrack=false;}// In case user provides a timeout value greater than 0 but less than 10 seconds SDK will show a warning
|
|
1664
1789
|
// and will proceed with it
|
|
1665
1790
|
if(timeout>0&&timeout<MIN_SESSION_TIMEOUT_MS){this.logger.warn(TIMEOUT_NOT_RECOMMENDED_WARNING(USER_SESSION_MANAGER,timeout,MIN_SESSION_TIMEOUT_MS));}const cutOff=this.getCutOffInfo(timeout);return {timeout,autoTrack,cutOff};}getCutOffInfo(sessionTimeout){const cutOff=state.loadOptions.value.sessions.cutOff;let cutOffDuration;let cutOffEnabled=false;if(cutOff.enabled===true){cutOffDuration=cutOff.duration;cutOffEnabled=true;if(!isPositiveInteger(cutOffDuration)){this.logger.warn(CUT_OFF_DURATION_NOT_NUMBER_WARNING(USER_SESSION_MANAGER,cutOffDuration,DEFAULT_SESSION_CUT_OFF_DURATION_MS));// Use the default value for cut off duration
|
|
1666
1791
|
cutOffDuration=DEFAULT_SESSION_CUT_OFF_DURATION_MS;}else if(cutOffDuration<sessionTimeout){this.logger.warn(CUT_OFF_DURATION_LESS_THAN_TIMEOUT_WARNING(USER_SESSION_MANAGER,cutOffDuration,sessionTimeout));cutOffEnabled=false;}}return {enabled:cutOffEnabled,duration:cutOffDuration};}/**
|
|
@@ -1671,23 +1796,23 @@ cutOffDuration=DEFAULT_SESSION_CUT_OFF_DURATION_MS;}else if(cutOffDuration<sessi
|
|
|
1671
1796
|
* @param cookiesData
|
|
1672
1797
|
* @param store
|
|
1673
1798
|
* @returns
|
|
1674
|
-
*/getEncryptedCookieData(cookiesData,store){const encryptedCookieData=[];cookiesData.forEach(cData=>{const encryptedValue=store
|
|
1799
|
+
*/getEncryptedCookieData(cookiesData,store){const encryptedCookieData=[];cookiesData.forEach(cData=>{const encryptedValue=store===null||store===void 0?void 0:store.encrypt(stringifyWithoutCircular(cData.value,false,[],this.logger));if(isDefinedAndNotNull(encryptedValue)){encryptedCookieData.push({name:cData.name,value:encryptedValue});}});return encryptedCookieData;}/**
|
|
1675
1800
|
* A function that makes request to data service to set the cookie
|
|
1676
1801
|
* @param encryptedCookieData
|
|
1677
1802
|
* @param callback
|
|
1678
|
-
*/makeRequestToSetCookie(encryptedCookieData,callback){this.httpClient
|
|
1803
|
+
*/makeRequestToSetCookie(encryptedCookieData,callback){var _this$httpClient,_state$source$value,_state$storage$cookie,_state$storage$cookie2,_state$storage$cookie3,_state$storage$cookie4,_state$storage$cookie5,_state$storage$cookie6;(_this$httpClient=this.httpClient)===null||_this$httpClient===void 0||_this$httpClient.getAsyncData({url:state.serverCookies.dataServiceUrl.value,options:{method:'POST',data:stringifyWithoutCircular({reqType:'setCookies',workspaceId:(_state$source$value=state.source.value)===null||_state$source$value===void 0?void 0:_state$source$value.workspaceId,data:{options:{maxAge:(_state$storage$cookie=state.storage.cookie.value)===null||_state$storage$cookie===void 0?void 0:_state$storage$cookie.maxage,path:(_state$storage$cookie2=state.storage.cookie.value)===null||_state$storage$cookie2===void 0?void 0:_state$storage$cookie2.path,domain:(_state$storage$cookie3=state.storage.cookie.value)===null||_state$storage$cookie3===void 0?void 0:_state$storage$cookie3.domain,sameSite:(_state$storage$cookie4=state.storage.cookie.value)===null||_state$storage$cookie4===void 0?void 0:_state$storage$cookie4.samesite,secure:(_state$storage$cookie5=state.storage.cookie.value)===null||_state$storage$cookie5===void 0?void 0:_state$storage$cookie5.secure,expires:(_state$storage$cookie6=state.storage.cookie.value)===null||_state$storage$cookie6===void 0?void 0:_state$storage$cookie6.expires},cookies:encryptedCookieData}}),sendRawData:true,withCredentials:true},isRawResponse:true,callback});}/**
|
|
1679
1804
|
* A function to make an external request to set the cookie from server side
|
|
1680
1805
|
* @param sessionToCookiesMap map of session key to cookie name
|
|
1681
1806
|
* @param cb callback function to be called when the cookie is set
|
|
1682
1807
|
* @param store store to be used to get the cookie value
|
|
1683
1808
|
*/setServerSideCookies(sessionToCookiesMap,cb,store){// Retrieve the cookie value from the state
|
|
1684
1809
|
const sessionKeys=Object.keys(sessionToCookiesMap);const getCurrentCookieValuesFromState=()=>{return sessionKeys.map(sessionKey=>{return {name:sessionToCookiesMap[sessionKey].name,value:state.session[sessionKey].value};});};// Preserve the current cookie values
|
|
1685
|
-
const originalCookieValues={};sessionKeys.forEach(sessionKey=>{originalCookieValues[sessionToCookiesMap[sessionKey].name]=store
|
|
1810
|
+
const originalCookieValues={};sessionKeys.forEach(sessionKey=>{originalCookieValues[sessionToCookiesMap[sessionKey].name]=store===null||store===void 0?void 0:store.get(sessionToCookiesMap[sessionKey].name);});const clearInProgressFlags=()=>{sessionKeys.forEach(sessionKey=>{this.serverSideCookiesRequestInProgress[sessionKey]=false;});};const setCookiesClientSide=()=>{getCurrentCookieValuesFromState().forEach(each=>{if(cb){cb(each.name,each.value);}});};try{const expectedCookieValues={};sessionKeys.forEach(sessionKey=>{expectedCookieValues[sessionToCookiesMap[sessionKey].name]=state.session[sessionKey].value;});// encrypt cookies values
|
|
1686
1811
|
const encryptedCookieData=this.getEncryptedCookieData(getCurrentCookieValuesFromState(),store);if(encryptedCookieData.length>0){// make request to data service to set the cookie from server side
|
|
1687
|
-
this.makeRequestToSetCookie(encryptedCookieData,(res,details)=>{
|
|
1688
|
-
clearInProgressFlags();if(details
|
|
1812
|
+
this.makeRequestToSetCookie(encryptedCookieData,(res,details)=>{var _details$xhr;// Mark the cookie req status as done
|
|
1813
|
+
clearInProgressFlags();if((details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.status)===200){// Only the cookies that were actually sent can be reported as unapplied, so
|
|
1689
1814
|
// both halves of the diagnostic are drawn from the same set
|
|
1690
|
-
const sentCookieNames=new Set(encryptedCookieData.map(each=>each.name));const unappliedCookies=[];getCurrentCookieValuesFromState().forEach(cData=>{const originalCookieVal=originalCookieValues[cData.name];const currentCookieVal=store
|
|
1815
|
+
const sentCookieNames=new Set(encryptedCookieData.map(each=>each.name));const unappliedCookies=[];getCurrentCookieValuesFromState().forEach(cData=>{const originalCookieVal=originalCookieValues[cData.name];const currentCookieVal=store===null||store===void 0?void 0:store.get(cData.name);// Check if the expected cookie values are set.
|
|
1691
1816
|
if(stringifyWithoutCircular(expectedCookieValues[cData.name],false,[])!==stringifyWithoutCircular(currentCookieVal,false,[])){// It's fine if the values don't match as other active SDK sessions might have updated the cookie values
|
|
1692
1817
|
// or other cookie requests might have updated the cookie value.
|
|
1693
1818
|
// Left exactly as the request found it, so the server did not apply this
|
|
@@ -1705,7 +1830,7 @@ if(isNull(originalCookieVal)&&isNull(currentCookieVal)){this.logger.error(FAILED
|
|
|
1705
1830
|
// attributes usually leave none of them set.
|
|
1706
1831
|
// Counted from what was actually sent, not from the queued keys: encryption can
|
|
1707
1832
|
// drop a key, and reporting it as sent would overstate the batch.
|
|
1708
|
-
if(encryptedCookieData.length>1&&unappliedCookies.length>0&&!state.serverCookies.isCollapsedBatchErrorLogged.value){state.serverCookies.isCollapsedBatchErrorLogged.value=true;this.logger.error(COLLAPSED_COOKIE_BATCH_ERROR(unappliedCookies,encryptedCookieData.length));}}else {this.logger.error(DATA_SERVER_REQUEST_FAIL_ERROR(details
|
|
1833
|
+
if(encryptedCookieData.length>1&&unappliedCookies.length>0&&!state.serverCookies.isCollapsedBatchErrorLogged.value){state.serverCookies.isCollapsedBatchErrorLogged.value=true;this.logger.error(COLLAPSED_COOKIE_BATCH_ERROR(unappliedCookies,encryptedCookieData.length));}}else {var _details$xhr2;this.logger.error(DATA_SERVER_REQUEST_FAIL_ERROR(details===null||details===void 0||(_details$xhr2=details.xhr)===null||_details$xhr2===void 0?void 0:_details$xhr2.status));setCookiesClientSide();}});}else {setCookiesClientSide();// Mark the cookie req status as done
|
|
1709
1834
|
clearInProgressFlags();}}catch(e){this.onError(e,FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR,FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR);setCookiesClientSide();// Mark the cookie req status as done
|
|
1710
1835
|
clearInProgressFlags();}}/**
|
|
1711
1836
|
* A function to send every queued server-side cookie as a single request
|
|
@@ -1713,10 +1838,10 @@ clearInProgressFlags();}}/**
|
|
|
1713
1838
|
this.serverSideCookiesDebounceTimer=0;const sessionToCookiesMap=Object.entries(this.serverSideCookiesPending).reduce((acc,[sessionKey,cookieName])=>{acc[sessionKey]={name:cookieName};return acc;},{});// Drain before sending, so anything that changes while the request is in flight is
|
|
1714
1839
|
// queued for the next batch rather than being sent twice
|
|
1715
1840
|
this.serverSideCookiesPending={};if(Object.keys(sessionToCookiesMap).length===0){return;}// Every batched key is backed by cookie storage by construction, so they share a store
|
|
1716
|
-
const curStore=this.storeManager.getStore(storageClientDataStoreNameMap[COOKIE_STORAGE]);this.setServerSideCookies(sessionToCookiesMap,(cookieName,cookieValue)=>{curStore
|
|
1841
|
+
const curStore=this.storeManager.getStore(storageClientDataStoreNameMap[COOKIE_STORAGE]);this.setServerSideCookies(sessionToCookiesMap,(cookieName,cookieValue)=>{curStore===null||curStore===void 0||curStore.set(cookieName,cookieValue);},curStore);}/**
|
|
1717
1842
|
* A function to sync values in storage
|
|
1718
1843
|
* @param sessionKey
|
|
1719
|
-
*/syncValueToStorage(sessionKey){const entries=state.storage.entries.value;const storageType=entries[sessionKey]
|
|
1844
|
+
*/syncValueToStorage(sessionKey){var _entries$sessionKey;const entries=state.storage.entries.value;const storageType=(_entries$sessionKey=entries[sessionKey])===null||_entries$sessionKey===void 0?void 0:_entries$sessionKey.type;if(isStorageTypeValidForStoringData(storageType)){var _entries$sessionKey2;const curStore=this.storeManager.getStore(storageClientDataStoreNameMap[storageType]);const cookieName=(_entries$sessionKey2=entries[sessionKey])===null||_entries$sessionKey2===void 0?void 0:_entries$sessionKey2.key;const cookieValue=state.session[sessionKey].value;if(cookieValue&&(isString(cookieValue)||isNonEmptyObject(cookieValue))){// if useServerSideCookies load option is set to true
|
|
1720
1845
|
// set the cookie from server side
|
|
1721
1846
|
if(state.serverCookies.isEnabledServerSideCookies.value&&storageType===COOKIE_STORAGE){// Mark the requests as in progress.
|
|
1722
1847
|
this.serverSideCookiesRequestInProgress[sessionKey]=true;// Queue this key and restart the shared debounce, so everything that changes in
|
|
@@ -1725,7 +1850,7 @@ this.serverSideCookiesPending[sessionKey]=cookieName;// Restarting the shared ti
|
|
|
1725
1850
|
// keep postponing the flush for every other key, where per-key timers only ever
|
|
1726
1851
|
// delayed their own. That needs changes arriving closer together than the
|
|
1727
1852
|
// debounce, continuously, so it is accepted rather than capped with a max wait.
|
|
1728
|
-
if(this.serverSideCookiesDebounceTimer){globalThis.clearTimeout(this.serverSideCookiesDebounceTimer);}this.serverSideCookiesDebounceTimer=globalThis.setTimeout(()=>{this.flushServerSideCookies();},SERVER_SIDE_COOKIES_DEBOUNCE_TIME);}else {curStore
|
|
1853
|
+
if(this.serverSideCookiesDebounceTimer){globalThis.clearTimeout(this.serverSideCookiesDebounceTimer);}this.serverSideCookiesDebounceTimer=globalThis.setTimeout(()=>{this.flushServerSideCookies();},SERVER_SIDE_COOKIES_DEBOUNCE_TIME);}else {curStore===null||curStore===void 0||curStore.set(cookieName,cookieValue);}}else {curStore===null||curStore===void 0||curStore.remove(cookieName);}}}/**
|
|
1729
1854
|
* Function to update storage whenever state value changes
|
|
1730
1855
|
*/registerEffects(){// This will work as long as the user session entry key names are same as the state keys
|
|
1731
1856
|
USER_SESSION_KEYS.forEach(sessionKey=>{j(()=>{// Read before syncing so the effect subscribes to the signal, and record after
|
|
@@ -1737,16 +1862,16 @@ const value=state.session[sessionKey].value;this.syncValueToStorage(sessionKey);
|
|
|
1737
1862
|
* 2. rudderAmpLinkerParam: value generated from linker query parm (rudderstack)
|
|
1738
1863
|
* using parseLinker util.
|
|
1739
1864
|
* 3. generateUUID: A new unique id is generated and assigned.
|
|
1740
|
-
*/setAnonymousId(anonymousId,rudderAmpLinkerParam){let finalAnonymousId=anonymousId;if(!isString(anonymousId)||!finalAnonymousId){finalAnonymousId=undefined;}if(this.isPersistenceEnabledForStorageEntry('anonymousId')){if(!finalAnonymousId&&rudderAmpLinkerParam){const linkerPluginsResult=this.pluginsManager
|
|
1865
|
+
*/setAnonymousId(anonymousId,rudderAmpLinkerParam){let finalAnonymousId=anonymousId;if(!isString(anonymousId)||!finalAnonymousId){finalAnonymousId=undefined;}if(this.isPersistenceEnabledForStorageEntry('anonymousId')){if(!finalAnonymousId&&rudderAmpLinkerParam){var _this$pluginsManager2;const linkerPluginsResult=(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===void 0?void 0:_this$pluginsManager2.invokeSingle('userSession.anonymousIdGoogleLinker',rudderAmpLinkerParam);finalAnonymousId=linkerPluginsResult;}finalAnonymousId=finalAnonymousId||generateAnonymousId();}else {finalAnonymousId=DEFAULT_USER_SESSION_VALUES.anonymousId;}state.session.anonymousId.value=finalAnonymousId;}/**
|
|
1741
1866
|
* Fetches anonymousId
|
|
1742
1867
|
* @param options option to fetch it from external source
|
|
1743
1868
|
* @returns anonymousId
|
|
1744
|
-
*/getAnonymousId(options){const storage=state.storage.entries.value.anonymousId
|
|
1745
|
-
if(!persistedAnonymousId||persistedAnonymousId===DEFAULT_USER_SESSION_VALUES.anonymousId){persistedAnonymousId=this.getEntryValue('anonymousId');}if(!persistedAnonymousId&&options){
|
|
1746
|
-
const autoCapturedAnonymousId=this.pluginsManager
|
|
1869
|
+
*/getAnonymousId(options){var _state$storage$entrie2;const storage=(_state$storage$entrie2=state.storage.entries.value.anonymousId)===null||_state$storage$entrie2===void 0?void 0:_state$storage$entrie2.type;if(isStorageTypeValidForStoringData(storage)){let persistedAnonymousId=state.session.anonymousId.value;// If the anonymous ID is the default value, fetch it from storage
|
|
1870
|
+
if(!persistedAnonymousId||persistedAnonymousId===DEFAULT_USER_SESSION_VALUES.anonymousId){persistedAnonymousId=this.getEntryValue('anonymousId');}if(!persistedAnonymousId&&options){var _this$pluginsManager3;// fetch anonymousId from external source
|
|
1871
|
+
const autoCapturedAnonymousId=(_this$pluginsManager3=this.pluginsManager)===null||_this$pluginsManager3===void 0?void 0:_this$pluginsManager3.invokeSingle('storage.getAnonymousId',getStorageEngine,options);persistedAnonymousId=autoCapturedAnonymousId;}state.session.anonymousId.value=persistedAnonymousId||generateAnonymousId();}return state.session.anonymousId.value;}getEntryValue(sessionKey){var _entries$sessionKey3;const entries=state.storage.entries.value;const storageType=(_entries$sessionKey3=entries[sessionKey])===null||_entries$sessionKey3===void 0?void 0:_entries$sessionKey3.type;if(isStorageTypeValidForStoringData(storageType)){var _this$storeManager4,_entries$sessionKey4,_store$get;const store=(_this$storeManager4=this.storeManager)===null||_this$storeManager4===void 0?void 0:_this$storeManager4.getStore(storageClientDataStoreNameMap[storageType]);// Migrate the storage data before fetching the value
|
|
1747
1872
|
// This is needed for entries that are fetched from the storage
|
|
1748
1873
|
// during the current session (for example, session info)
|
|
1749
|
-
this.migrateStorageIfNeeded([store],[sessionKey]);const storageKey=entries[sessionKey]
|
|
1874
|
+
this.migrateStorageIfNeeded([store],[sessionKey]);const storageKey=(_entries$sessionKey4=entries[sessionKey])===null||_entries$sessionKey4===void 0?void 0:_entries$sessionKey4.key;return (_store$get=store===null||store===void 0?void 0:store.get(storageKey))!==null&&_store$get!==void 0?_store$get:null;}return null;}getExternalAnonymousIdByCookieName(key){const storageEngine=getStorageEngine(COOKIE_STORAGE);if(storageEngine!==null&&storageEngine!==void 0&&storageEngine.isEnabled){var _storageEngine$getIte;return (_storageEngine$getIte=storageEngine.getItem(key))!==null&&_storageEngine$getIte!==void 0?_storageEngine$getIte:null;}return null;}/**
|
|
1750
1875
|
* Fetches the value for a session key. Preferably from storage, so that changes made by
|
|
1751
1876
|
* other tabs are picked up. Falls back to the state whenever storage is known to be
|
|
1752
1877
|
* behind it.
|
|
@@ -1795,20 +1920,20 @@ return this.getEntryValue(sessionKey);}/**
|
|
|
1795
1920
|
*/getAuthToken(){return this.getUserSessionValue('authToken');}/**
|
|
1796
1921
|
* If session is active it returns the sessionId
|
|
1797
1922
|
* @returns
|
|
1798
|
-
*/getSessionId(){const sessionInfo=this.getSessionInfo()
|
|
1923
|
+
*/getSessionId(){var _this$getSessionInfo2;const sessionInfo=(_this$getSessionInfo2=this.getSessionInfo())!==null&&_this$getSessionInfo2!==void 0?_this$getSessionInfo2:DEFAULT_USER_SESSION_VALUES.sessionInfo;if(sessionInfo.autoTrack&&!hasSessionExpired(sessionInfo)||sessionInfo.manualTrack){var _sessionInfo$id;return (_sessionInfo$id=sessionInfo.id)!==null&&_sessionInfo$id!==void 0?_sessionInfo$id:null;}return null;}/**
|
|
1799
1924
|
* A function to keep the session information up to date in the state
|
|
1800
1925
|
* before using it for building event payloads.
|
|
1801
|
-
*/refreshSession(){let sessionInfo=this.getSessionInfo()
|
|
1926
|
+
*/refreshSession(){var _this$getSessionInfo3;let sessionInfo=(_this$getSessionInfo3=this.getSessionInfo())!==null&&_this$getSessionInfo3!==void 0?_this$getSessionInfo3:DEFAULT_USER_SESSION_VALUES.sessionInfo;if(sessionInfo.autoTrack||sessionInfo.manualTrack){if(sessionInfo.autoTrack){this.startOrRenewAutoTracking(sessionInfo);sessionInfo=state.session.sessionInfo.value;}// Note that if sessionStart is false, then it's an active session.
|
|
1802
1927
|
// So, we needn't update the session info.
|
|
1803
1928
|
//
|
|
1804
1929
|
// For other scenarios,
|
|
1805
1930
|
// 1. If sessionStart is undefined, then it's a new session.
|
|
1806
1931
|
// Mark it as sessionStart.
|
|
1807
1932
|
// 2. If sessionStart is true, then need to flip it for the future events.
|
|
1808
|
-
if(sessionInfo.sessionStart===undefined){sessionInfo={
|
|
1933
|
+
if(sessionInfo.sessionStart===undefined){sessionInfo=_objectSpread2(_objectSpread2({},sessionInfo),{},{sessionStart:true});}else if(sessionInfo.sessionStart){sessionInfo=_objectSpread2(_objectSpread2({},sessionInfo),{},{sessionStart:false});}}// Always write to state (in-turn to storage) to keep the session info up to date.
|
|
1809
1934
|
state.session.sessionInfo.value=sessionInfo;if(state.lifecycle.status.value!=='readyExecuted'){// Force update the storage as the 'effect' blocks are not getting triggered
|
|
1810
1935
|
// when processing preload buffered requests
|
|
1811
|
-
this.syncValueToStorage('sessionInfo');}}resetAndStartNewSession(){const session=state.session;const{manualTrack,autoTrack,timeout,cutOff}=session.sessionInfo.value;if(autoTrack){const sessionInfo={
|
|
1936
|
+
this.syncValueToStorage('sessionInfo');}}resetAndStartNewSession(){const session=state.session;const{manualTrack,autoTrack,timeout,cutOff}=session.sessionInfo.value;if(autoTrack){const sessionInfo=_objectSpread2(_objectSpread2({},DEFAULT_USER_SESSION_VALUES.sessionInfo),{},{timeout});if(cutOff){sessionInfo.cutOff={enabled:cutOff.enabled,duration:cutOff.duration};}session.sessionInfo.value=sessionInfo;this.startOrRenewAutoTracking(session.sessionInfo.value);}else if(manualTrack){this.startManualTrackingInternal();}}/**
|
|
1812
1937
|
* Reset state values
|
|
1813
1938
|
* @param options options for reset
|
|
1814
1939
|
* @returns
|
|
@@ -1818,13 +1943,13 @@ this.syncValueToStorage('sessionInfo');}}resetAndStartNewSession(){const session
|
|
|
1818
1943
|
*/setUserId(userId){state.session.userId.value=this.isPersistenceEnabledForStorageEntry('userId')&&userId?userId:DEFAULT_USER_SESSION_VALUES.userId;}/**
|
|
1819
1944
|
* Set user traits
|
|
1820
1945
|
* @param traits
|
|
1821
|
-
*/setUserTraits(traits){state.session.userTraits.value=this.isPersistenceEnabledForStorageEntry('userTraits')&&isObjectLiteralAndNotNull(traits)?mergeDeepRight(state.session.userTraits.value
|
|
1946
|
+
*/setUserTraits(traits){var _state$session$userTr;state.session.userTraits.value=this.isPersistenceEnabledForStorageEntry('userTraits')&&isObjectLiteralAndNotNull(traits)?mergeDeepRight((_state$session$userTr=state.session.userTraits.value)!==null&&_state$session$userTr!==void 0?_state$session$userTr:DEFAULT_USER_SESSION_VALUES.userTraits,traits):DEFAULT_USER_SESSION_VALUES.userTraits;}/**
|
|
1822
1947
|
* Set group Id
|
|
1823
1948
|
* @param groupId
|
|
1824
1949
|
*/setGroupId(groupId){state.session.groupId.value=this.isPersistenceEnabledForStorageEntry('groupId')&&groupId?groupId:DEFAULT_USER_SESSION_VALUES.groupId;}/**
|
|
1825
1950
|
* Set group traits
|
|
1826
1951
|
* @param traits
|
|
1827
|
-
*/setGroupTraits(traits){state.session.groupTraits.value=this.isPersistenceEnabledForStorageEntry('groupTraits')&&isObjectLiteralAndNotNull(traits)?mergeDeepRight(state.session.groupTraits.value
|
|
1952
|
+
*/setGroupTraits(traits){var _state$session$groupT;state.session.groupTraits.value=this.isPersistenceEnabledForStorageEntry('groupTraits')&&isObjectLiteralAndNotNull(traits)?mergeDeepRight((_state$session$groupT=state.session.groupTraits.value)!==null&&_state$session$groupT!==void 0?_state$session$groupT:DEFAULT_USER_SESSION_VALUES.groupTraits,traits):DEFAULT_USER_SESSION_VALUES.groupTraits;}/**
|
|
1828
1953
|
* Set initial referrer
|
|
1829
1954
|
* @param referrer
|
|
1830
1955
|
*/setInitialReferrer(referrer){state.session.initialReferrer.value=this.isPersistenceEnabledForStorageEntry('initialReferrer')&&referrer?referrer:DEFAULT_USER_SESSION_VALUES.initialReferrer;}/**
|
|
@@ -1855,7 +1980,7 @@ state.session.sessionInfo.value=finalSessionInfo;}/**
|
|
|
1855
1980
|
const defaultOptionalPluginsList=allOptionalPlugins;
|
|
1856
1981
|
|
|
1857
1982
|
const normalizeLoadOptions=(loadOptionsFromState,loadOptions)=>{// TODO: Maybe add warnings for invalid values
|
|
1858
|
-
const normalizedLoadOpts=clone(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){normalizedLoadOpts.setCookieDomain=undefined;}const cookieSameSiteValues=['Strict','Lax','None'];if(!cookieSameSiteValues.includes(normalizedLoadOpts.sameSiteCookie)){normalizedLoadOpts.sameSiteCookie=undefined;}normalizedLoadOpts.secureCookie=getNormalizedBooleanValue(normalizedLoadOpts.secureCookie,loadOptionsFromState.secureCookie);normalizedLoadOpts.sameDomainCookiesOnly=getNormalizedBooleanValue(normalizedLoadOpts.sameDomainCookiesOnly,loadOptionsFromState.sameDomainCookiesOnly);const uaChTrackLevels=['none','default','full'];if(!uaChTrackLevels.includes(normalizedLoadOpts.uaChTrackLevel)){normalizedLoadOpts.uaChTrackLevel=undefined;}normalizedLoadOpts.integrations=getNormalizedObjectValue(normalizedLoadOpts.integrations);if(!Array.isArray(normalizedLoadOpts.plugins)){normalizedLoadOpts.plugins=defaultOptionalPluginsList;}normalizedLoadOpts.useGlobalIntegrationsConfigInEvents=getNormalizedBooleanValue(normalizedLoadOpts.useGlobalIntegrationsConfigInEvents,loadOptionsFromState.useGlobalIntegrationsConfigInEvents);normalizedLoadOpts.bufferDataPlaneEventsUntilReady=getNormalizedBooleanValue(normalizedLoadOpts.bufferDataPlaneEventsUntilReady,loadOptionsFromState.bufferDataPlaneEventsUntilReady);normalizedLoadOpts.sendAdblockPage=getNormalizedBooleanValue(normalizedLoadOpts.sendAdblockPage,loadOptionsFromState.sendAdblockPage);normalizedLoadOpts.useServerSideCookies=getNormalizedBooleanValue(normalizedLoadOpts.useServerSideCookies,loadOptionsFromState.useServerSideCookies);if(!isString(normalizedLoadOpts.dataServiceEndpoint)){normalizedLoadOpts.dataServiceEndpoint=undefined;}normalizedLoadOpts.sendAdblockPageOptions=getNormalizedObjectValue(normalizedLoadOpts.sendAdblockPageOptions);normalizedLoadOpts.loadIntegration=getNormalizedBooleanValue(normalizedLoadOpts.loadIntegration,loadOptionsFromState.loadIntegration);if(!isNonEmptyObject(normalizedLoadOpts.storage)){normalizedLoadOpts.storage=undefined;}else {normalizedLoadOpts.storage.migrate=getNormalizedBooleanValue(normalizedLoadOpts.storage.migrate,loadOptionsFromState.storage
|
|
1983
|
+
const normalizedLoadOpts=clone(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){normalizedLoadOpts.setCookieDomain=undefined;}const cookieSameSiteValues=['Strict','Lax','None'];if(!cookieSameSiteValues.includes(normalizedLoadOpts.sameSiteCookie)){normalizedLoadOpts.sameSiteCookie=undefined;}normalizedLoadOpts.secureCookie=getNormalizedBooleanValue(normalizedLoadOpts.secureCookie,loadOptionsFromState.secureCookie);normalizedLoadOpts.sameDomainCookiesOnly=getNormalizedBooleanValue(normalizedLoadOpts.sameDomainCookiesOnly,loadOptionsFromState.sameDomainCookiesOnly);const uaChTrackLevels=['none','default','full'];if(!uaChTrackLevels.includes(normalizedLoadOpts.uaChTrackLevel)){normalizedLoadOpts.uaChTrackLevel=undefined;}normalizedLoadOpts.integrations=getNormalizedObjectValue(normalizedLoadOpts.integrations);if(!Array.isArray(normalizedLoadOpts.plugins)){normalizedLoadOpts.plugins=defaultOptionalPluginsList;}normalizedLoadOpts.useGlobalIntegrationsConfigInEvents=getNormalizedBooleanValue(normalizedLoadOpts.useGlobalIntegrationsConfigInEvents,loadOptionsFromState.useGlobalIntegrationsConfigInEvents);normalizedLoadOpts.bufferDataPlaneEventsUntilReady=getNormalizedBooleanValue(normalizedLoadOpts.bufferDataPlaneEventsUntilReady,loadOptionsFromState.bufferDataPlaneEventsUntilReady);normalizedLoadOpts.sendAdblockPage=getNormalizedBooleanValue(normalizedLoadOpts.sendAdblockPage,loadOptionsFromState.sendAdblockPage);normalizedLoadOpts.useServerSideCookies=getNormalizedBooleanValue(normalizedLoadOpts.useServerSideCookies,loadOptionsFromState.useServerSideCookies);if(!isString(normalizedLoadOpts.dataServiceEndpoint)){normalizedLoadOpts.dataServiceEndpoint=undefined;}normalizedLoadOpts.sendAdblockPageOptions=getNormalizedObjectValue(normalizedLoadOpts.sendAdblockPageOptions);normalizedLoadOpts.loadIntegration=getNormalizedBooleanValue(normalizedLoadOpts.loadIntegration,loadOptionsFromState.loadIntegration);if(!isNonEmptyObject(normalizedLoadOpts.storage)){normalizedLoadOpts.storage=undefined;}else {var _loadOptionsFromState;normalizedLoadOpts.storage.migrate=getNormalizedBooleanValue(normalizedLoadOpts.storage.migrate,(_loadOptionsFromState=loadOptionsFromState.storage)===null||_loadOptionsFromState===void 0?void 0:_loadOptionsFromState.migrate);normalizedLoadOpts.storage.cookie=getNormalizedObjectValue(normalizedLoadOpts.storage.cookie);normalizedLoadOpts.storage.encryption=getNormalizedObjectValue(normalizedLoadOpts.storage.encryption);normalizedLoadOpts.storage=removeUndefinedAndNullValues(normalizedLoadOpts.storage);}normalizedLoadOpts.destinationsQueueOptions=getNormalizedObjectValue(normalizedLoadOpts.destinationsQueueOptions);normalizedLoadOpts.queueOptions=getNormalizedObjectValue(normalizedLoadOpts.queueOptions);normalizedLoadOpts.lockIntegrationsVersion=getNormalizedBooleanValue(normalizedLoadOpts.lockIntegrationsVersion,loadOptionsFromState.lockIntegrationsVersion);normalizedLoadOpts.lockPluginsVersion=getNormalizedBooleanValue(normalizedLoadOpts.lockPluginsVersion,loadOptionsFromState.lockPluginsVersion);if(!isNumber(normalizedLoadOpts.dataPlaneEventsBufferTimeout)){normalizedLoadOpts.dataPlaneEventsBufferTimeout=undefined;}normalizedLoadOpts.beaconQueueOptions=getNormalizedObjectValue(normalizedLoadOpts.beaconQueueOptions);normalizedLoadOpts.preConsent=getNormalizedObjectValue(normalizedLoadOpts.preConsent);normalizedLoadOpts.sourceConfigurationOverride=getNormalizedObjectValue(normalizedLoadOpts.sourceConfigurationOverride);const mergedLoadOptions=mergeDeepRight(loadOptionsFromState,removeUndefinedAndNullValues(normalizedLoadOpts));return mergedLoadOptions;};
|
|
1859
1984
|
|
|
1860
1985
|
const DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';const DESTINATIONS_QUEUE_EXT_POINT_PREFIX='destinationsEventsQueue';const DMT_EXT_POINT_PREFIX='transformEvent';
|
|
1861
1986
|
|
|
@@ -1871,7 +1996,7 @@ const DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';const DESTINATION
|
|
|
1871
1996
|
* @returns Mutated event with final integrations config
|
|
1872
1997
|
*/const getFinalEvent=(event,state)=>{const finalEvent=clone(event);// Merge the destination specific integrations config with the event's integrations config
|
|
1873
1998
|
// In general, the preference is given to the event's integrations config
|
|
1874
|
-
const destinationsIntgConfig=state.nativeDestinations.integrationsConfig.value;const overriddenIntgOpts=getOverriddenIntegrationOptions(event.integrations,destinationsIntgConfig);finalEvent.integrations=mergeDeepRight(destinationsIntgConfig,overriddenIntgOpts);return finalEvent;};const shouldBufferEventsForPreConsent=state=>state.consents.preConsent.value.enabled&&state.consents.preConsent.value.events
|
|
1999
|
+
const destinationsIntgConfig=state.nativeDestinations.integrationsConfig.value;const overriddenIntgOpts=getOverriddenIntegrationOptions(event.integrations,destinationsIntgConfig);finalEvent.integrations=mergeDeepRight(destinationsIntgConfig,overriddenIntgOpts);return finalEvent;};const shouldBufferEventsForPreConsent=state=>{var _state$consents$preCo;return state.consents.preConsent.value.enabled&&((_state$consents$preCo=state.consents.preConsent.value.events)===null||_state$consents$preCo===void 0?void 0:_state$consents$preCo.delivery)==='buffer';};
|
|
1875
2000
|
|
|
1876
2001
|
const safelyInvokeCallback=(callback,args,apiName,logger)=>{if(!isDefined(callback)){return;}if(isFunction(callback)){try{callback(...args);}catch(error){logger.error(CALLBACK_INVOKE_ERROR(apiName),error);}}else {logger.error(INVALID_CALLBACK_FN_ERROR(apiName));}};
|
|
1877
2002
|
|
|
@@ -1886,12 +2011,12 @@ const safelyInvokeCallback=(callback,args,apiName,logger)=>{if(!isDefined(callba
|
|
|
1886
2011
|
*/constructor(pluginsManager,storeManager,httpClient,errorHandler,logger){this.pluginsManager=pluginsManager;this.errorHandler=errorHandler;this.httpClient=httpClient;this.logger=logger;this.storeManager=storeManager;}/**
|
|
1887
2012
|
* Initializes the event repository
|
|
1888
2013
|
*/init(){this.dataplaneEventsQueue=this.pluginsManager.invokeSingle(`${DATA_PLANE_QUEUE_EXT_POINT_PREFIX}.init`,state,this.httpClient,this.storeManager,this.errorHandler,this.logger);this.dmtEventsQueue=this.pluginsManager.invokeSingle(`${DMT_EXT_POINT_PREFIX}.init`,state,this.pluginsManager,this.httpClient,this.storeManager,this.errorHandler,this.logger);this.destinationsEventsQueue=this.pluginsManager.invokeSingle(`${DESTINATIONS_QUEUE_EXT_POINT_PREFIX}.init`,state,this.pluginsManager,this.storeManager,this.dmtEventsQueue,this.errorHandler,this.logger);// Start the queue once the client destinations are ready
|
|
1889
|
-
j(()=>{if(state.nativeDestinations.clientDestinationsReady.value===true){this.destinationsEventsQueue
|
|
2014
|
+
j(()=>{if(state.nativeDestinations.clientDestinationsReady.value===true){var _this$destinationsEve,_this$dmtEventsQueue;(_this$destinationsEve=this.destinationsEventsQueue)===null||_this$destinationsEve===void 0||_this$destinationsEve.start();(_this$dmtEventsQueue=this.dmtEventsQueue)===null||_this$dmtEventsQueue===void 0||_this$dmtEventsQueue.start();}});const bufferEventsBeforeConsent=shouldBufferEventsForPreConsent(state);// Start the queue processing only when the destinations are ready or hybrid mode destinations exist
|
|
1890
2015
|
// However, events will be enqueued for now.
|
|
1891
2016
|
// At the time of processing the events, the integrations config data from destinations
|
|
1892
2017
|
// is merged into the event object
|
|
1893
|
-
let timeoutId;j(()=>{const shouldBufferDpEvents=state.loadOptions.value.bufferDataPlaneEventsUntilReady===true&&state.nativeDestinations.clientDestinationsReady.value===false;const hybridDestExist=state.nativeDestinations.activeDestinations.value.some(dest=>isHybridModeDestination(dest));if((hybridDestExist===false||shouldBufferDpEvents===false)&&!bufferEventsBeforeConsent&&this.dataplaneEventsQueue
|
|
1894
|
-
if(state.loadOptions.value.bufferDataPlaneEventsUntilReady===true){timeoutId=globalThis.setTimeout(()=>{if(this.dataplaneEventsQueue
|
|
2018
|
+
let timeoutId;j(()=>{var _this$dataplaneEvents;const shouldBufferDpEvents=state.loadOptions.value.bufferDataPlaneEventsUntilReady===true&&state.nativeDestinations.clientDestinationsReady.value===false;const hybridDestExist=state.nativeDestinations.activeDestinations.value.some(dest=>isHybridModeDestination(dest));if((hybridDestExist===false||shouldBufferDpEvents===false)&&!bufferEventsBeforeConsent&&((_this$dataplaneEvents=this.dataplaneEventsQueue)===null||_this$dataplaneEvents===void 0?void 0:_this$dataplaneEvents.scheduleTimeoutActive)!==true){var _this$dataplaneEvents2;globalThis.clearTimeout(timeoutId);(_this$dataplaneEvents2=this.dataplaneEventsQueue)===null||_this$dataplaneEvents2===void 0||_this$dataplaneEvents2.start();}});// Force start the data plane events queue processing after a timeout
|
|
2019
|
+
if(state.loadOptions.value.bufferDataPlaneEventsUntilReady===true){timeoutId=globalThis.setTimeout(()=>{var _this$dataplaneEvents3;if(((_this$dataplaneEvents3=this.dataplaneEventsQueue)===null||_this$dataplaneEvents3===void 0?void 0:_this$dataplaneEvents3.scheduleTimeoutActive)!==true){var _this$dataplaneEvents4;(_this$dataplaneEvents4=this.dataplaneEventsQueue)===null||_this$dataplaneEvents4===void 0||_this$dataplaneEvents4.start();}},state.loadOptions.value.dataPlaneEventsBufferTimeout);}}resume(){var _this$dataplaneEvents5;if(((_this$dataplaneEvents5=this.dataplaneEventsQueue)===null||_this$dataplaneEvents5===void 0?void 0:_this$dataplaneEvents5.scheduleTimeoutActive)!==true){var _this$dataplaneEvents7;if(state.consents.postConsent.value.discardPreConsentEvents){var _this$dataplaneEvents6,_this$destinationsEve2;(_this$dataplaneEvents6=this.dataplaneEventsQueue)===null||_this$dataplaneEvents6===void 0||_this$dataplaneEvents6.clear();(_this$destinationsEve2=this.destinationsEventsQueue)===null||_this$destinationsEve2===void 0||_this$destinationsEve2.clear();}(_this$dataplaneEvents7=this.dataplaneEventsQueue)===null||_this$dataplaneEvents7===void 0||_this$dataplaneEvents7.start();}}/**
|
|
1895
2020
|
* Enqueues the event for processing
|
|
1896
2021
|
* @param event RudderEvent object
|
|
1897
2022
|
* @param callback API callback function
|
|
@@ -1900,15 +2025,15 @@ const apiName=`${event.type.charAt(0).toUpperCase()}${event.type.slice(1)}${API_
|
|
|
1900
2025
|
|
|
1901
2026
|
const dispatchSDKEvent=event=>{const customEvent=new CustomEvent(event,{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:true,cancelable:true,composed:true});globalThis.document.dispatchEvent(customEvent);};const isWriteKeyValid=writeKey=>isString(writeKey)&&writeKey.trim().length>0;const isDataPlaneUrlValid=dataPlaneUrl=>isValidURL(dataPlaneUrl);
|
|
1902
2027
|
|
|
1903
|
-
|
|
2028
|
+
const _excluded=["context"];/*
|
|
1904
2029
|
* Analytics class with lifecycle based on state ad user triggered events
|
|
1905
2030
|
*/class Analytics{/**
|
|
1906
2031
|
* Initialize services and components or use default ones if singletons
|
|
1907
2032
|
*/constructor(){this.preloadBuffer=new BufferQueue();this.initialized=false;this.errorHandler=defaultErrorHandler;this.logger=defaultLogger;this.customContextStore=new CustomContextStore(state.customContext,this.logger);this.externalSrcLoader=new ExternalSrcLoader(this.logger);this.httpClient=defaultHttpClient;this.httpClient.init(this.errorHandler);this.capabilitiesManager=new CapabilitiesManager(this.httpClient,this.errorHandler,this.logger);}/**
|
|
1908
2033
|
* Start application lifecycle if not already started
|
|
1909
|
-
*/load(writeKey,dataPlaneUrl,loadOptions={}){if(state.lifecycle.status.value){return;}if(!isWriteKeyValid(writeKey)){this.logger.error(WRITE_KEY_VALIDATION_ERROR(ANALYTICS_CORE,writeKey));return;}if(!isDataPlaneUrlValid(dataPlaneUrl)){this.logger.error(DATA_PLANE_URL_VALIDATION_ERROR(ANALYTICS_CORE,dataPlaneUrl));return;}const{context:customContext
|
|
2034
|
+
*/load(writeKey,dataPlaneUrl,loadOptions={}){var _state$loadOptions$va;if(state.lifecycle.status.value){return;}if(!isWriteKeyValid(writeKey)){this.logger.error(WRITE_KEY_VALIDATION_ERROR(ANALYTICS_CORE,writeKey));return;}if(!isDataPlaneUrlValid(dataPlaneUrl)){this.logger.error(DATA_PLANE_URL_VALIDATION_ERROR(ANALYTICS_CORE,dataPlaneUrl));return;}const{context:customContext}=loadOptions,loadOptionsWithoutContext=_objectWithoutProperties(loadOptions,_excluded);const sanitizedLoadOptions=getSanitizedValue(loadOptionsWithoutContext);if(customContext!==undefined){this.customContextStore.set(customContext);}// Set initial state values
|
|
1910
2035
|
n(()=>{state.lifecycle.writeKey.value=clone(writeKey);state.lifecycle.dataPlaneUrl.value=clone(dataPlaneUrl);state.loadOptions.value=normalizeLoadOptions(state.loadOptions.value,sanitizedLoadOptions);state.lifecycle.status.value='mounted';});// set log level as early as possible
|
|
1911
|
-
this.logger.setMinLogLevel(state.loadOptions.value.logLevel
|
|
2036
|
+
this.logger.setMinLogLevel((_state$loadOptions$va=state.loadOptions.value.logLevel)!==null&&_state$loadOptions$va!==void 0?_state$loadOptions$va:POST_LOAD_LOG_LEVEL);// Expose state to global objects
|
|
1912
2037
|
setExposedGlobal('state',state,writeKey);// Configure initial config of any services or components here
|
|
1913
2038
|
// State application lifecycle
|
|
1914
2039
|
this.startLifecycle();}setCustomContext(context){if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,['setCustomContext',context]];return;}this.customContextStore.set(context);}getCustomContext(){return this.customContextStore.get();}clearCustomContext(){if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,['clearCustomContext']];return;}this.customContextStore.clear();}// Start lifecycle methods
|
|
@@ -1924,15 +2049,15 @@ if(state.consents.preConsent.value.enabled===true){state.lifecycle.status.value=
|
|
|
1924
2049
|
* Process the buffer preloaded events by passing their arguments to the respective facade methods
|
|
1925
2050
|
*/processDataInPreloadBuffer(){while(this.preloadBuffer.size()>0){const eventToProcess=this.preloadBuffer.dequeue();if(eventToProcess){consumePreloadBufferedEvent([...eventToProcess],this);}}}prepareInternalServices(){this.pluginsManager=new PluginsManager(defaultPluginEngine,this.errorHandler,this.logger);this.storeManager=new StoreManager(this.pluginsManager,this.errorHandler,this.logger);this.configManager=new ConfigManager(this.httpClient,this.errorHandler,this.logger);this.userSessionManager=new UserSessionManager(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger);this.eventRepository=new EventRepository(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger);this.eventManager=new EventManager(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger);}/**
|
|
1926
2051
|
* Load configuration
|
|
1927
|
-
*/loadConfig(){if(state.lifecycle.writeKey.value){this.httpClient.setAuthHeader(state.lifecycle.writeKey.value);}this.configManager
|
|
2052
|
+
*/loadConfig(){var _this$configManager;if(state.lifecycle.writeKey.value){this.httpClient.setAuthHeader(state.lifecycle.writeKey.value);}(_this$configManager=this.configManager)===null||_this$configManager===void 0||_this$configManager.init();}/**
|
|
1928
2053
|
* Initialize the storage and event queue
|
|
1929
|
-
*/onPluginsReady(){
|
|
1930
|
-
this.storeManager
|
|
1931
|
-
if(state.consents.enabled.value&&!state.consents.initialized.value){this.pluginsManager
|
|
1932
|
-
this.eventManager
|
|
2054
|
+
*/onPluginsReady(){var _this$storeManager,_this$userSessionMana,_this$eventManager;// Initialize storage
|
|
2055
|
+
(_this$storeManager=this.storeManager)===null||_this$storeManager===void 0||_this$storeManager.init();(_this$userSessionMana=this.userSessionManager)===null||_this$userSessionMana===void 0||_this$userSessionMana.init();// Initialize the appropriate consent manager plugin
|
|
2056
|
+
if(state.consents.enabled.value&&!state.consents.initialized.value){var _this$pluginsManager;(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0||_this$pluginsManager.invokeSingle(`consentManager.init`,state,this.logger);if(state.consents.preConsent.value.enabled===false){var _this$pluginsManager2;(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===void 0||_this$pluginsManager2.invokeSingle(`consentManager.updateConsentsInfo`,state,this.storeManager,this.logger);}}// Initialize event manager
|
|
2057
|
+
(_this$eventManager=this.eventManager)===null||_this$eventManager===void 0||_this$eventManager.init();// Mark the SDK as initialized
|
|
1933
2058
|
state.lifecycle.status.value='initialized';}/**
|
|
1934
2059
|
* Load plugins
|
|
1935
|
-
*/onConfigured(){this.pluginsManager
|
|
2060
|
+
*/onConfigured(){var _this$pluginsManager3;(_this$pluginsManager3=this.pluginsManager)===null||_this$pluginsManager3===void 0||_this$pluginsManager3.init();// TODO: are we going to enable custom plugins to be passed as load options?
|
|
1936
2061
|
// registerCustomPlugins(state.loadOptions.value.customPlugins);
|
|
1937
2062
|
}/**
|
|
1938
2063
|
* Trigger onLoaded callback if any is provided in config & emit initialised event
|
|
@@ -1951,12 +2076,12 @@ dispatchSDKEvent('RSA_Ready');}/**
|
|
|
1951
2076
|
*/processBufferedEvents(){// This logic has been intentionally implemented without a simple
|
|
1952
2077
|
// for-loop as the individual events that are processed may
|
|
1953
2078
|
// add more events to the buffer (this is needed for the consent API)
|
|
1954
|
-
let bufferedEvents=state.eventBuffer.toBeProcessedArray.value;while(bufferedEvents.length>0){const bufferedEvent=bufferedEvents.shift();state.eventBuffer.toBeProcessedArray.value=bufferedEvents;if(bufferedEvent){this.processBufferedEvent(bufferedEvent);}bufferedEvents=state.eventBuffer.toBeProcessedArray.value;}}processBufferedEvent(bufferedEvent){switch(bufferedEvent[0]){case 'setCustomContext':this.setCustomContext(bufferedEvent[1]);break;case 'clearCustomContext':this.clearCustomContext();break;case 'ready':this.ready(bufferedEvent[1],true);break;case 'page':this.page(bufferedEvent[1],true,bufferedEvent[2]);break;case 'track':this.track(bufferedEvent[1],true,bufferedEvent[2]);break;case 'identify':this.identify(bufferedEvent[1],true,bufferedEvent[2]);break;case 'alias':this.alias(bufferedEvent[1],true,bufferedEvent[2]);break;case 'group':this.group(bufferedEvent[1],true,bufferedEvent[2]);break;case 'reset':this.reset(bufferedEvent[1],true);break;case 'setAnonymousId':this.setAnonymousId(bufferedEvent[1],bufferedEvent[2],true);break;case 'startSession':this.startSession(bufferedEvent[1],true);break;case 'endSession':this.endSession(true);break;case 'consent':this.consent(bufferedEvent[1],true);break;case 'addCustomIntegration':this.addCustomIntegration(bufferedEvent[1],bufferedEvent[2],true);break;default:{const unsupportedEvent=bufferedEvent;return unsupportedEvent;}}}getInvocationContext(preservedCustomContext){if(preservedCustomContext===undefined){return this.customContextStore.get();}const preparedContext=prepareCustomContextUpdate(preservedCustomContext,this.logger);return preparedContext
|
|
2079
|
+
let bufferedEvents=state.eventBuffer.toBeProcessedArray.value;while(bufferedEvents.length>0){const bufferedEvent=bufferedEvents.shift();state.eventBuffer.toBeProcessedArray.value=bufferedEvents;if(bufferedEvent){this.processBufferedEvent(bufferedEvent);}bufferedEvents=state.eventBuffer.toBeProcessedArray.value;}}processBufferedEvent(bufferedEvent){switch(bufferedEvent[0]){case 'setCustomContext':this.setCustomContext(bufferedEvent[1]);break;case 'clearCustomContext':this.clearCustomContext();break;case 'ready':this.ready(bufferedEvent[1],true);break;case 'page':this.page(bufferedEvent[1],true,bufferedEvent[2]);break;case 'track':this.track(bufferedEvent[1],true,bufferedEvent[2]);break;case 'identify':this.identify(bufferedEvent[1],true,bufferedEvent[2]);break;case 'alias':this.alias(bufferedEvent[1],true,bufferedEvent[2]);break;case 'group':this.group(bufferedEvent[1],true,bufferedEvent[2]);break;case 'reset':this.reset(bufferedEvent[1],true);break;case 'setAnonymousId':this.setAnonymousId(bufferedEvent[1],bufferedEvent[2],true);break;case 'startSession':this.startSession(bufferedEvent[1],true);break;case 'endSession':this.endSession(true);break;case 'consent':this.consent(bufferedEvent[1],true);break;case 'addCustomIntegration':this.addCustomIntegration(bufferedEvent[1],bufferedEvent[2],true);break;default:{const unsupportedEvent=bufferedEvent;return unsupportedEvent;}}}getInvocationContext(preservedCustomContext){var _ref;if(preservedCustomContext===undefined){return this.customContextStore.get();}const preparedContext=prepareCustomContextUpdate(preservedCustomContext,this.logger);return (_ref=preparedContext)!==null&&_ref!==void 0?_ref:{};}/**
|
|
1955
2080
|
* Load device mode destinations
|
|
1956
|
-
*/loadDestinations(){
|
|
2081
|
+
*/loadDestinations(){var _this$pluginsManager4,_this$pluginsManager5;// If the integrations load is already triggered or completed, skip the rest of the logic
|
|
1957
2082
|
if(state.lifecycle.status.value==='destinationsLoading'||state.nativeDestinations.clientDestinationsReady.value===true){return;}// Set in state the desired activeDestinations to inject in DOM
|
|
1958
|
-
this.pluginsManager
|
|
1959
|
-
state.lifecycle.status.value='destinationsLoading';this.pluginsManager
|
|
2083
|
+
(_this$pluginsManager4=this.pluginsManager)===null||_this$pluginsManager4===void 0||_this$pluginsManager4.invokeSingle('nativeDestinations.setActiveDestinations',state,this.pluginsManager,this.errorHandler,this.logger);const totalDestinationsToLoad=state.nativeDestinations.activeDestinations.value.length;if(totalDestinationsToLoad===0){n(()=>{state.nativeDestinations.clientDestinationsReady.value=true;state.lifecycle.status.value='destinationsReady';});return;}// Start loading native integration scripts and create instances
|
|
2084
|
+
state.lifecycle.status.value='destinationsLoading';(_this$pluginsManager5=this.pluginsManager)===null||_this$pluginsManager5===void 0||_this$pluginsManager5.invokeSingle('nativeDestinations.load',state,this.externalSrcLoader,this.errorHandler,this.logger);// Progress to next lifecycle phase if all native destinations are initialized or failed
|
|
1960
2085
|
j(()=>{const areAllDestinationsReady=state.nativeDestinations.initializedDestinations.value.length+state.nativeDestinations.failedDestinations.value.length===totalDestinationsToLoad;if(areAllDestinationsReady){n(()=>{state.lifecycle.status.value='destinationsReady';state.nativeDestinations.clientDestinationsReady.value=true;});}});}/**
|
|
1961
2086
|
* Move to the ready state
|
|
1962
2087
|
*/// eslint-disable-next-line class-methods-use-this
|
|
@@ -1968,31 +2093,31 @@ ready(callback,isBufferedInvocation=false){const type='ready';if(!state.lifecycl
|
|
|
1968
2093
|
* If destinations are loaded or no integration is available for loading
|
|
1969
2094
|
* execute the callback immediately else push the callbacks to a queue that
|
|
1970
2095
|
* will be executed after loading completes
|
|
1971
|
-
*/if(state.lifecycle.status.value==='readyExecuted'){safelyInvokeCallback(callback,[],READY_API,this.logger);}else {state.eventBuffer.readyCallbacksArray.value=[...state.eventBuffer.readyCallbacksArray.value,callback];}}page(payload,isBufferedInvocation=false,preservedCustomContext){const type='page';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}const invocationContext=this.getInvocationContext(preservedCustomContext);this.errorHandler.leaveBreadcrumb(`New ${type} event`);state.metrics.triggered.value+=1;this.eventManager
|
|
2096
|
+
*/if(state.lifecycle.status.value==='readyExecuted'){safelyInvokeCallback(callback,[],READY_API,this.logger);}else {state.eventBuffer.readyCallbacksArray.value=[...state.eventBuffer.readyCallbacksArray.value,callback];}}page(payload,isBufferedInvocation=false,preservedCustomContext){var _this$eventManager2;const type='page';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}const invocationContext=this.getInvocationContext(preservedCustomContext);this.errorHandler.leaveBreadcrumb(`New ${type} event`);state.metrics.triggered.value+=1;(_this$eventManager2=this.eventManager)===null||_this$eventManager2===void 0||_this$eventManager2.addEvent({type:'page',category:payload.category,name:payload.name,properties:payload.properties,options:payload.options,callback:payload.callback},invocationContext);// TODO: Maybe we should alter the behavior to send the ad-block page event even if the SDK is still loaded. It'll be pushed into the to be processed queue.
|
|
1972
2097
|
// Send automatic ad blocked page event if ad-blockers are detected on the page
|
|
1973
2098
|
// Check page category to avoid infinite loop
|
|
1974
2099
|
if(state.capabilities.isAdBlocked.value===true&&payload.category!==ADBLOCK_PAGE_CATEGORY){this.page(pageArgumentsToCallOptions(ADBLOCK_PAGE_CATEGORY,ADBLOCK_PAGE_NAME,{// 'title' is intentionally omitted as it does not make sense
|
|
1975
2100
|
// in v3 implementation
|
|
1976
|
-
path:ADBLOCK_PAGE_PATH},state.loadOptions.value.sendAdblockPageOptions),isBufferedInvocation,invocationContext);}}track(payload,isBufferedInvocation=false,preservedCustomContext){const type='track';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}const invocationContext=this.getInvocationContext(preservedCustomContext);this.errorHandler.leaveBreadcrumb(`New ${type} event - ${payload.name}`);state.metrics.triggered.value+=1;this.eventManager
|
|
1977
|
-
if(!isNull(payload.userId)){this.userSessionManager
|
|
1978
|
-
if(!isNull(payload.groupId)){this.userSessionManager
|
|
1979
|
-
if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,anonymousId,rudderAmpLinkerParam]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);this.userSessionManager
|
|
2101
|
+
path:ADBLOCK_PAGE_PATH},state.loadOptions.value.sendAdblockPageOptions),isBufferedInvocation,invocationContext);}}track(payload,isBufferedInvocation=false,preservedCustomContext){var _this$eventManager3;const type='track';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}const invocationContext=this.getInvocationContext(preservedCustomContext);this.errorHandler.leaveBreadcrumb(`New ${type} event - ${payload.name}`);state.metrics.triggered.value+=1;(_this$eventManager3=this.eventManager)===null||_this$eventManager3===void 0||_this$eventManager3.addEvent({type,name:payload.name||undefined,properties:payload.properties,options:payload.options,callback:payload.callback},invocationContext);}identify(payload,isBufferedInvocation=false,preservedCustomContext){var _this$userSessionMana3,_this$eventManager4;const type='identify';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}const invocationContext=this.getInvocationContext(preservedCustomContext);this.errorHandler.leaveBreadcrumb(`New ${type} event`);state.metrics.triggered.value+=1;const shouldResetSession=Boolean(payload.userId&&state.session.userId.value&&payload.userId!==state.session.userId.value);if(shouldResetSession){this.reset();}// `null` value indicates that previous user ID needs to be retained
|
|
2102
|
+
if(!isNull(payload.userId)){var _this$userSessionMana2;(_this$userSessionMana2=this.userSessionManager)===null||_this$userSessionMana2===void 0||_this$userSessionMana2.setUserId(payload.userId);}(_this$userSessionMana3=this.userSessionManager)===null||_this$userSessionMana3===void 0||_this$userSessionMana3.setUserTraits(payload.traits);(_this$eventManager4=this.eventManager)===null||_this$eventManager4===void 0||_this$eventManager4.addEvent({type,userId:payload.userId,traits:payload.traits,options:payload.options,callback:payload.callback},invocationContext);}alias(payload,isBufferedInvocation=false,preservedCustomContext){var _payload$from,_this$userSessionMana4,_this$eventManager5;const type='alias';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}const invocationContext=this.getInvocationContext(preservedCustomContext);this.errorHandler.leaveBreadcrumb(`New ${type} event`);state.metrics.triggered.value+=1;const previousId=(_payload$from=payload.from)!==null&&_payload$from!==void 0?_payload$from:this.getUserId()||((_this$userSessionMana4=this.userSessionManager)===null||_this$userSessionMana4===void 0?void 0:_this$userSessionMana4.getAnonymousId());(_this$eventManager5=this.eventManager)===null||_this$eventManager5===void 0||_this$eventManager5.addEvent({type,to:payload.to,from:previousId,options:payload.options,callback:payload.callback},invocationContext);}group(payload,isBufferedInvocation=false,preservedCustomContext){var _this$userSessionMana6,_this$eventManager6;const type='group';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,payload]];return;}const invocationContext=this.getInvocationContext(preservedCustomContext);this.errorHandler.leaveBreadcrumb(`New ${type} event`);state.metrics.triggered.value+=1;// `null` value indicates that previous group ID needs to be retained
|
|
2103
|
+
if(!isNull(payload.groupId)){var _this$userSessionMana5;(_this$userSessionMana5=this.userSessionManager)===null||_this$userSessionMana5===void 0||_this$userSessionMana5.setGroupId(payload.groupId);}(_this$userSessionMana6=this.userSessionManager)===null||_this$userSessionMana6===void 0||_this$userSessionMana6.setGroupTraits(payload.traits);(_this$eventManager6=this.eventManager)===null||_this$eventManager6===void 0||_this$eventManager6.addEvent({type,groupId:payload.groupId,traits:payload.traits,options:payload.options,callback:payload.callback},invocationContext);}reset(options,isBufferedInvocation=false){var _this$userSessionMana7;const type='reset';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,options]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);(_this$userSessionMana7=this.userSessionManager)===null||_this$userSessionMana7===void 0||_this$userSessionMana7.reset(options);}getAnonymousId(options){var _this$userSessionMana8;return (_this$userSessionMana8=this.userSessionManager)===null||_this$userSessionMana8===void 0?void 0:_this$userSessionMana8.getAnonymousId(options);}setAnonymousId(anonymousId,rudderAmpLinkerParam,isBufferedInvocation=false){var _this$userSessionMana9;const type='setAnonymousId';// Buffering is needed as setting the anonymous ID may require invoking the GoogleLinker plugin
|
|
2104
|
+
if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,anonymousId,rudderAmpLinkerParam]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);(_this$userSessionMana9=this.userSessionManager)===null||_this$userSessionMana9===void 0||_this$userSessionMana9.setAnonymousId(anonymousId,rudderAmpLinkerParam);}// eslint-disable-next-line class-methods-use-this
|
|
1980
2105
|
getUserId(){return state.session.userId.value;}// eslint-disable-next-line class-methods-use-this
|
|
1981
2106
|
getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
|
|
1982
2107
|
getGroupId(){return state.session.groupId.value;}// eslint-disable-next-line class-methods-use-this
|
|
1983
|
-
getGroupTraits(){return state.session.groupTraits.value;}startSession(sessionId,isBufferedInvocation=false){const type='startSession';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,sessionId]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);this.userSessionManager
|
|
1984
|
-
getSessionId(){const sessionId=this.userSessionManager
|
|
1985
|
-
if(state.consents.enabled.value&&!state.consents.initialized.value){this.pluginsManager
|
|
1986
|
-
this.storeManager
|
|
1987
|
-
this.userSessionManager
|
|
1988
|
-
this.eventManager
|
|
2108
|
+
getGroupTraits(){return state.session.groupTraits.value;}startSession(sessionId,isBufferedInvocation=false){var _this$userSessionMana0;const type='startSession';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,sessionId]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);(_this$userSessionMana0=this.userSessionManager)===null||_this$userSessionMana0===void 0||_this$userSessionMana0.start(sessionId);}endSession(isBufferedInvocation=false){var _this$userSessionMana1;const type='endSession';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type]];return;}this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);(_this$userSessionMana1=this.userSessionManager)===null||_this$userSessionMana1===void 0||_this$userSessionMana1.end();}// eslint-disable-next-line class-methods-use-this
|
|
2109
|
+
getSessionId(){var _this$userSessionMana10;const sessionId=(_this$userSessionMana10=this.userSessionManager)===null||_this$userSessionMana10===void 0?void 0:_this$userSessionMana10.getSessionId();return sessionId!==null&&sessionId!==void 0?sessionId:null;}consent(options,isBufferedInvocation=false){var _this$storeManager2,_this$userSessionMana11,_this$eventManager7;const type='consent';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,options]];return;}this.errorHandler.leaveBreadcrumb(`New consent invocation`);n(()=>{state.consents.preConsent.value=_objectSpread2(_objectSpread2({},state.consents.preConsent.value),{},{enabled:false});state.consents.postConsent.value=getValidPostConsentOptions(options,this.logger);const{initialized,consentsData}=getConsentManagementData(state.consents.postConsent.value.consentManagement,this.logger);state.consents.initialized.value=initialized;state.consents.data.value=consentsData;});// Update consents data in state
|
|
2110
|
+
if(state.consents.enabled.value&&!state.consents.initialized.value){var _this$pluginsManager6;(_this$pluginsManager6=this.pluginsManager)===null||_this$pluginsManager6===void 0||_this$pluginsManager6.invokeSingle(`consentManager.updateConsentsInfo`,state,this.storeManager,this.logger);}// Re-init store manager
|
|
2111
|
+
(_this$storeManager2=this.storeManager)===null||_this$storeManager2===void 0||_this$storeManager2.initializeStorageState();// Re-init user session manager
|
|
2112
|
+
(_this$userSessionMana11=this.userSessionManager)===null||_this$userSessionMana11===void 0||_this$userSessionMana11.syncStorageDataToState();// Resume event manager to process the events to destinations
|
|
2113
|
+
(_this$eventManager7=this.eventManager)===null||_this$eventManager7===void 0||_this$eventManager7.resume();this.loadDestinations();this.sendTrackingEvents(isBufferedInvocation);}sendTrackingEvents(isBufferedInvocation){// If isBufferedInvocation is true, then the tracking events will be added to the end of the
|
|
1989
2114
|
// events buffer array so that any other preload events (mainly from query string API) will be processed first.
|
|
1990
|
-
if(state.consents.postConsent.value.trackConsent){const trackOptions=trackArgumentsToCallOptions(CONSENT_TRACK_EVENT_NAME);if(isBufferedInvocation){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,['track',trackOptions,this.customContextStore.get()]];}else {this.track(trackOptions);}}if(state.consents.postConsent.value.sendPageEvent){const pageOptions=pageArgumentsToCallOptions();if(isBufferedInvocation){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,['page',pageOptions,this.customContextStore.get()]];}else {this.page(pageOptions);}}}setAuthToken(token){this.userSessionManager
|
|
2115
|
+
if(state.consents.postConsent.value.trackConsent){const trackOptions=trackArgumentsToCallOptions(CONSENT_TRACK_EVENT_NAME);if(isBufferedInvocation){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,['track',trackOptions,this.customContextStore.get()]];}else {this.track(trackOptions);}}if(state.consents.postConsent.value.sendPageEvent){const pageOptions=pageArgumentsToCallOptions();if(isBufferedInvocation){state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,['page',pageOptions,this.customContextStore.get()]];}else {this.page(pageOptions);}}}setAuthToken(token){var _this$userSessionMana12;(_this$userSessionMana12=this.userSessionManager)===null||_this$userSessionMana12===void 0||_this$userSessionMana12.setAuthToken(token);}/**
|
|
1991
2116
|
* Add a custom integration for a custom destination.
|
|
1992
2117
|
* @param destinationId - The ID of the custom destination from the RudderStack dashboard.
|
|
1993
2118
|
* @param integration - The custom integration object.
|
|
1994
2119
|
* @param isBufferedInvocation - Whether the invocation is buffered.
|
|
1995
|
-
*/addCustomIntegration(destinationId,integration,isBufferedInvocation=false){const type='addCustomIntegration';if(isBufferedInvocation){this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);this.pluginsManager
|
|
2120
|
+
*/addCustomIntegration(destinationId,integration,isBufferedInvocation=false){const type='addCustomIntegration';if(isBufferedInvocation){var _this$pluginsManager7;this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);(_this$pluginsManager7=this.pluginsManager)===null||_this$pluginsManager7===void 0||_this$pluginsManager7.invokeSingle('nativeDestinations.addCustomIntegration',destinationId,integration,state,this.logger);}else {if(state.lifecycle.loaded.value){this.logger.error(CUSTOM_INTEGRATION_CANNOT_BE_ADDED_ERROR(ANALYTICS_CORE,destinationId));return;}state.eventBuffer.toBeProcessedArray.value=[...state.eventBuffer.toBeProcessedArray.value,[type,destinationId,integration]];}}// End consumer exposed methods
|
|
1996
2121
|
}
|
|
1997
2122
|
|
|
1998
2123
|
/*
|
|
@@ -2000,11 +2125,9 @@ if(state.consents.postConsent.value.trackConsent){const trackOptions=trackArgume
|
|
|
2000
2125
|
* expose overloaded methods
|
|
2001
2126
|
* handle multiple Analytics instances
|
|
2002
2127
|
* consume SDK preload event buffer
|
|
2003
|
-
*/class RudderAnalytics{//
|
|
2004
|
-
//
|
|
2005
|
-
|
|
2006
|
-
analyticsInstances={};defaultAnalyticsKey='';logger=defaultLogger;// Singleton with constructor bind methods
|
|
2007
|
-
constructor(){try{if(RudderAnalytics.globalSingleton){// START-NO-SONAR-SCAN
|
|
2128
|
+
*/class RudderAnalytics{// Singleton with constructor bind methods
|
|
2129
|
+
constructor(){// END-NO-SONAR-SCAN
|
|
2130
|
+
_defineProperty(this,"analyticsInstances",{});_defineProperty(this,"defaultAnalyticsKey",'');_defineProperty(this,"logger",defaultLogger);try{if(RudderAnalytics.globalSingleton){// START-NO-SONAR-SCAN
|
|
2008
2131
|
// eslint-disable-next-line no-constructor-return
|
|
2009
2132
|
return RudderAnalytics.globalSingleton;// END-NO-SONAR-SCAN
|
|
2010
2133
|
}RudderAnalytics.initializeGlobalResources();this.setDefaultInstanceKey=this.setDefaultInstanceKey.bind(this);this.getAnalyticsInstance=this.getAnalyticsInstance.bind(this);this.load=this.load.bind(this);this.ready=this.ready.bind(this);this.triggerBufferedLoadEvent=this.triggerBufferedLoadEvent.bind(this);this.page=this.page.bind(this);this.track=this.track.bind(this);this.identify=this.identify.bind(this);this.alias=this.alias.bind(this);this.group=this.group.bind(this);this.reset=this.reset.bind(this);this.getAnonymousId=this.getAnonymousId.bind(this);this.setAnonymousId=this.setAnonymousId.bind(this);this.getUserId=this.getUserId.bind(this);this.getUserTraits=this.getUserTraits.bind(this);this.getGroupId=this.getGroupId.bind(this);this.getGroupTraits=this.getGroupTraits.bind(this);this.setCustomContext=this.setCustomContext.bind(this);this.getCustomContext=this.getCustomContext.bind(this);this.clearCustomContext=this.clearCustomContext.bind(this);this.startSession=this.startSession.bind(this);this.endSession=this.endSession.bind(this);this.getSessionId=this.getSessionId.bind(this);this.setAuthToken=this.setAuthToken.bind(this);this.consent=this.consent.bind(this);this.addCustomIntegration=this.addCustomIntegration.bind(this);this.createSafeAnalyticsInstance();RudderAnalytics.globalSingleton=this;state.autoTrack.pageLifecycle.pageViewId.value=generateUUID();state.autoTrack.pageLifecycle.pageLoadedTimestamp.value=Date.now();// start loading if a load event was buffered or wait for explicit load call
|
|
@@ -2032,15 +2155,15 @@ if(isString(writeKey)&&writeKey){this.defaultAnalyticsKey=writeKey;}}/**
|
|
|
2032
2155
|
* @param dataPlaneUrl Data plane URL
|
|
2033
2156
|
* @param loadOptions Additional options for loading the SDK
|
|
2034
2157
|
* @returns none
|
|
2035
|
-
*/load(writeKey,dataPlaneUrl,loadOptions){try{if(this.analyticsInstances[writeKey]){return;}this.setDefaultInstanceKey(writeKey);// Track page loaded lifecycle event if enabled
|
|
2158
|
+
*/load(writeKey,dataPlaneUrl,loadOptions){try{var _this$getAnalyticsIns;if(this.analyticsInstances[writeKey]){return;}this.setDefaultInstanceKey(writeKey);// Track page loaded lifecycle event if enabled
|
|
2036
2159
|
this.trackPageLifecycleEvents(loadOptions);// Get the preloaded events array from global buffer instead of window.rudderanalytics
|
|
2037
2160
|
// as the constructor must have already pushed the events to the global buffer
|
|
2038
2161
|
const preloadedEventsArray=getExposedGlobal(GLOBAL_PRELOAD_BUFFER);// The array will be mutated in the below method
|
|
2039
|
-
promotePreloadedConsentEventsToTop(preloadedEventsArray);setExposedGlobal(GLOBAL_PRELOAD_BUFFER,clone(preloadedEventsArray));this.getAnalyticsInstance(writeKey)
|
|
2162
|
+
promotePreloadedConsentEventsToTop(preloadedEventsArray);setExposedGlobal(GLOBAL_PRELOAD_BUFFER,clone(preloadedEventsArray));(_this$getAnalyticsIns=this.getAnalyticsInstance(writeKey))===null||_this$getAnalyticsIns===void 0||_this$getAnalyticsIns.load(writeKey,dataPlaneUrl,loadOptions);}catch(error){dispatchErrorEvent(error);}}/**
|
|
2040
2163
|
* A function to track page lifecycle events like page loaded and page unloaded
|
|
2041
2164
|
* @param loadOptions
|
|
2042
2165
|
* @returns
|
|
2043
|
-
*/trackPageLifecycleEvents(loadOptions){const{autoTrack,useBeacon}=loadOptions
|
|
2166
|
+
*/trackPageLifecycleEvents(loadOptions){const{autoTrack,useBeacon}=loadOptions!==null&&loadOptions!==void 0?loadOptions:{};const{enabled:autoTrackEnabled=false,options:autoTrackOptions={},pageLifecycle}=autoTrack!==null&&autoTrack!==void 0?autoTrack:{};const{events=[PageLifecycleEvents.UNLOADED],enabled:pageLifecycleEnabled=autoTrackEnabled,options=autoTrackOptions}=pageLifecycle!==null&&pageLifecycle!==void 0?pageLifecycle:{};state.autoTrack.pageLifecycle.enabled.value=pageLifecycleEnabled;// Set the autoTrack enabled state
|
|
2044
2167
|
// if at least one of the autoTrack options is enabled
|
|
2045
2168
|
// IMPORTANT: make sure this is done at the end as it depends on the above states
|
|
2046
2169
|
state.autoTrack.enabled.value=autoTrackEnabled||pageLifecycleEnabled;if(!pageLifecycleEnabled){return;}this.setupPageUnloadTracking(events,useBeacon,options);}/**
|
|
@@ -2048,7 +2171,7 @@ state.autoTrack.enabled.value=autoTrackEnabled||pageLifecycleEnabled;if(!pageLif
|
|
|
2048
2171
|
* @param events
|
|
2049
2172
|
* @param useBeacon
|
|
2050
2173
|
* @param options
|
|
2051
|
-
*/setupPageUnloadTracking(events,useBeacon,options){if(events.length===0||events.includes(PageLifecycleEvents.UNLOADED)){if(useBeacon===true){onPageLeave(isAccessible=>{if(isAccessible===false&&state.lifecycle.loaded.value){const pageUnloadedTimestamp=Date.now();const timeOnPage=pageUnloadedTimestamp-state.autoTrack.pageLifecycle.pageLoadedTimestamp.value;this.track(PageLifecycleEvents.UNLOADED,{timeOnPage},{
|
|
2174
|
+
*/setupPageUnloadTracking(events,useBeacon,options){if(events.length===0||events.includes(PageLifecycleEvents.UNLOADED)){if(useBeacon===true){onPageLeave(isAccessible=>{if(isAccessible===false&&state.lifecycle.loaded.value){const pageUnloadedTimestamp=Date.now();const timeOnPage=pageUnloadedTimestamp-state.autoTrack.pageLifecycle.pageLoadedTimestamp.value;this.track(PageLifecycleEvents.UNLOADED,{timeOnPage},_objectSpread2(_objectSpread2({},options),{},{originalTimestamp:getFormattedTimestamp(new Date(pageUnloadedTimestamp))}));}},true);}else {// log warning if beacon is disabled
|
|
2052
2175
|
this.logger.warn(PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(RSA));}}}/**
|
|
2053
2176
|
* Trigger load event in buffer queue if exists and stores the
|
|
2054
2177
|
* remaining preloaded events array in global object
|
|
@@ -2062,22 +2185,22 @@ loadEvent.shift();// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
|
2062
2185
|
// @ts-ignore
|
|
2063
2186
|
this.load.apply(null,loadEvent);}}/**
|
|
2064
2187
|
* Get ready callback arguments and forward to ready call
|
|
2065
|
-
*/ready(callback){try{this.getAnalyticsInstance()
|
|
2188
|
+
*/ready(callback){try{var _this$getAnalyticsIns2;(_this$getAnalyticsIns2=this.getAnalyticsInstance())===null||_this$getAnalyticsIns2===void 0||_this$getAnalyticsIns2.ready(getSanitizedValue(callback));}catch(error){dispatchErrorEvent(error);}}/**
|
|
2066
2189
|
* Process page arguments and forward to page call
|
|
2067
2190
|
*/// These overloads should be same as AnalyticsPageMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
|
2068
|
-
page(category,name,properties,options,callback){try{this.getAnalyticsInstance()
|
|
2191
|
+
page(category,name,properties,options,callback){try{var _this$getAnalyticsIns3;(_this$getAnalyticsIns3=this.getAnalyticsInstance())===null||_this$getAnalyticsIns3===void 0||_this$getAnalyticsIns3.page(pageArgumentsToCallOptions(getSanitizedValue(category),getSanitizedValue(name),getSanitizedValue(properties),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
|
|
2069
2192
|
* Process track arguments and forward to page call
|
|
2070
2193
|
*/// These overloads should be same as AnalyticsTrackMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
|
2071
|
-
track(event,properties,options,callback){try{this.getAnalyticsInstance()
|
|
2194
|
+
track(event,properties,options,callback){try{var _this$getAnalyticsIns4;(_this$getAnalyticsIns4=this.getAnalyticsInstance())===null||_this$getAnalyticsIns4===void 0||_this$getAnalyticsIns4.track(trackArgumentsToCallOptions(getSanitizedValue(event),getSanitizedValue(properties),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
|
|
2072
2195
|
* Process identify arguments and forward to page call
|
|
2073
2196
|
*/// These overloads should be same as AnalyticsIdentifyMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
|
2074
|
-
identify(userId,traits,options,callback){try{this.getAnalyticsInstance()
|
|
2197
|
+
identify(userId,traits,options,callback){try{var _this$getAnalyticsIns5;(_this$getAnalyticsIns5=this.getAnalyticsInstance())===null||_this$getAnalyticsIns5===void 0||_this$getAnalyticsIns5.identify(identifyArgumentsToCallOptions(getSanitizedValue(userId),getSanitizedValue(traits),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
|
|
2075
2198
|
* Process alias arguments and forward to page call
|
|
2076
2199
|
*/// These overloads should be same as AnalyticsAliasMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
|
2077
|
-
alias(to,from,options,callback){try{this.getAnalyticsInstance()
|
|
2200
|
+
alias(to,from,options,callback){try{var _this$getAnalyticsIns6;(_this$getAnalyticsIns6=this.getAnalyticsInstance())===null||_this$getAnalyticsIns6===void 0||_this$getAnalyticsIns6.alias(aliasArgumentsToCallOptions(getSanitizedValue(to),getSanitizedValue(from),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
|
|
2078
2201
|
* Process group arguments and forward to page call
|
|
2079
2202
|
*/// These overloads should be same as AnalyticsGroupMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
|
2080
|
-
group(groupId,traits,options,callback){try{this.getAnalyticsInstance()
|
|
2203
|
+
group(groupId,traits,options,callback){try{var _this$getAnalyticsIns7;(_this$getAnalyticsIns7=this.getAnalyticsInstance())===null||_this$getAnalyticsIns7===void 0||_this$getAnalyticsIns7.group(groupArgumentsToCallOptions(getSanitizedValue(groupId),getSanitizedValue(traits),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
|
|
2081
2204
|
* Reset the analytics instance
|
|
2082
2205
|
* @param options Reset options. Except for anonymousId, initialReferrer, and initialReferringDomain
|
|
2083
2206
|
* all other values will be reset by default.
|
|
@@ -2104,6 +2227,8 @@ group(groupId,traits,options,callback){try{this.getAnalyticsInstance()?.group(gr
|
|
|
2104
2227
|
* @param resetAnonymousId Reset anonymous ID
|
|
2105
2228
|
* @returns none
|
|
2106
2229
|
* @deprecated Use reset(options) instead
|
|
2107
|
-
*/reset(options){try{this.getAnalyticsInstance()
|
|
2230
|
+
*/reset(options){try{var _this$getAnalyticsIns8;(_this$getAnalyticsIns8=this.getAnalyticsInstance())===null||_this$getAnalyticsIns8===void 0||_this$getAnalyticsIns8.reset(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);}}getAnonymousId(options){try{var _this$getAnalyticsIns9;return (_this$getAnalyticsIns9=this.getAnalyticsInstance())===null||_this$getAnalyticsIns9===void 0?void 0:_this$getAnalyticsIns9.getAnonymousId(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);return undefined;}}setAnonymousId(anonymousId,rudderAmpLinkerParam){try{var _this$getAnalyticsIns0;(_this$getAnalyticsIns0=this.getAnalyticsInstance())===null||_this$getAnalyticsIns0===void 0||_this$getAnalyticsIns0.setAnonymousId(getSanitizedValue(anonymousId),getSanitizedValue(rudderAmpLinkerParam));}catch(error){dispatchErrorEvent(error);}}getUserId(){try{var _this$getAnalyticsIns1;return (_this$getAnalyticsIns1=this.getAnalyticsInstance())===null||_this$getAnalyticsIns1===void 0?void 0:_this$getAnalyticsIns1.getUserId();}catch(error){dispatchErrorEvent(error);return undefined;}}getUserTraits(){try{var _this$getAnalyticsIns10;return (_this$getAnalyticsIns10=this.getAnalyticsInstance())===null||_this$getAnalyticsIns10===void 0?void 0:_this$getAnalyticsIns10.getUserTraits();}catch(error){dispatchErrorEvent(error);return undefined;}}getGroupId(){try{var _this$getAnalyticsIns11;return (_this$getAnalyticsIns11=this.getAnalyticsInstance())===null||_this$getAnalyticsIns11===void 0?void 0:_this$getAnalyticsIns11.getGroupId();}catch(error){dispatchErrorEvent(error);return undefined;}}getGroupTraits(){try{var _this$getAnalyticsIns12;return (_this$getAnalyticsIns12=this.getAnalyticsInstance())===null||_this$getAnalyticsIns12===void 0?void 0:_this$getAnalyticsIns12.getGroupTraits();}catch(error){dispatchErrorEvent(error);return undefined;}}setCustomContext(context){try{var _this$getAnalyticsIns13;(_this$getAnalyticsIns13=this.getAnalyticsInstance())===null||_this$getAnalyticsIns13===void 0||_this$getAnalyticsIns13.setCustomContext(context);}catch(error){dispatchErrorEvent(error);}}getCustomContext(){try{var _this$getAnalyticsIns14,_this$getAnalyticsIns15;return (_this$getAnalyticsIns14=(_this$getAnalyticsIns15=this.getAnalyticsInstance())===null||_this$getAnalyticsIns15===void 0?void 0:_this$getAnalyticsIns15.getCustomContext())!==null&&_this$getAnalyticsIns14!==void 0?_this$getAnalyticsIns14:{};}catch(error){dispatchErrorEvent(error);return {};}}clearCustomContext(){try{var _this$getAnalyticsIns16;(_this$getAnalyticsIns16=this.getAnalyticsInstance())===null||_this$getAnalyticsIns16===void 0||_this$getAnalyticsIns16.clearCustomContext();}catch(error){dispatchErrorEvent(error);}}startSession(sessionId){try{var _this$getAnalyticsIns17;(_this$getAnalyticsIns17=this.getAnalyticsInstance())===null||_this$getAnalyticsIns17===void 0||_this$getAnalyticsIns17.startSession(getSanitizedValue(sessionId));}catch(error){dispatchErrorEvent(error);}}endSession(){try{var _this$getAnalyticsIns18;(_this$getAnalyticsIns18=this.getAnalyticsInstance())===null||_this$getAnalyticsIns18===void 0||_this$getAnalyticsIns18.endSession();}catch(error){dispatchErrorEvent(error);}}getSessionId(){try{var _this$getAnalyticsIns19;return (_this$getAnalyticsIns19=this.getAnalyticsInstance())===null||_this$getAnalyticsIns19===void 0?void 0:_this$getAnalyticsIns19.getSessionId();}catch(error){dispatchErrorEvent(error);return undefined;}}setAuthToken(token){try{var _this$getAnalyticsIns20;(_this$getAnalyticsIns20=this.getAnalyticsInstance())===null||_this$getAnalyticsIns20===void 0||_this$getAnalyticsIns20.setAuthToken(getSanitizedValue(token));}catch(error){dispatchErrorEvent(error);}}consent(options){try{var _this$getAnalyticsIns21;(_this$getAnalyticsIns21=this.getAnalyticsInstance())===null||_this$getAnalyticsIns21===void 0||_this$getAnalyticsIns21.consent(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);}}addCustomIntegration(destinationId,integration){try{var _this$getAnalyticsIns22;(_this$getAnalyticsIns22=this.getAnalyticsInstance())===null||_this$getAnalyticsIns22===void 0||_this$getAnalyticsIns22.addCustomIntegration(getSanitizedValue(destinationId),getSanitizedValue(integration));}catch(error){dispatchErrorEvent(error);}}}// START-NO-SONAR-SCAN
|
|
2231
|
+
// eslint-disable-next-line sonarjs/public-static-readonly
|
|
2232
|
+
_defineProperty(RudderAnalytics,"globalSingleton",null);
|
|
2108
2233
|
|
|
2109
2234
|
exports.RudderAnalytics = RudderAnalytics;
|