@rudderstack/analytics-js 3.34.3 → 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 +28 -0
- package/dist/npm/index.d.cts +3 -0
- package/dist/npm/index.d.mts +3 -0
- package/dist/npm/legacy/bundled/cjs/index.cjs +66 -30
- package/dist/npm/legacy/bundled/esm/index.mjs +66 -30
- package/dist/npm/legacy/bundled/umd/index.js +66 -30
- package/dist/npm/legacy/cjs/index.cjs +66 -30
- package/dist/npm/legacy/content-script/cjs/index.cjs +64 -29
- package/dist/npm/legacy/content-script/esm/index.mjs +64 -29
- package/dist/npm/legacy/content-script/umd/index.js +64 -29
- package/dist/npm/legacy/esm/index.mjs +66 -30
- package/dist/npm/legacy/lite/cjs/index.cjs +66 -30
- package/dist/npm/legacy/lite/esm/index.mjs +66 -30
- package/dist/npm/legacy/lite/umd/index.js +66 -30
- package/dist/npm/legacy/umd/index.js +66 -30
- package/dist/npm/modern/bundled/cjs/index.cjs +379 -301
- package/dist/npm/modern/bundled/esm/index.mjs +379 -301
- package/dist/npm/modern/bundled/umd/index.js +379 -301
- package/dist/npm/modern/cjs/index.cjs +277 -204
- package/dist/npm/modern/content-script/cjs/index.cjs +379 -301
- package/dist/npm/modern/content-script/esm/index.mjs +379 -301
- package/dist/npm/modern/content-script/umd/index.js +379 -301
- package/dist/npm/modern/esm/index.mjs +277 -204
- package/dist/npm/modern/lite/cjs/index.cjs +350 -272
- package/dist/npm/modern/lite/esm/index.mjs +350 -272
- package/dist/npm/modern/lite/umd/index.js +350 -272
- package/dist/npm/modern/umd/index.js +277 -204
- 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
|
|
|
@@ -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,7 +768,7 @@ 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
|
|
@@ -718,7 +786,7 @@ const DEFAULT_XHR_REQUEST_OPTIONS={headers:{Accept:'application/json','Content-T
|
|
|
718
786
|
* this is not supported by our sourceConfig API
|
|
719
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
|
|
720
788
|
return;}}const xhr=new XMLHttpRequest();// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
721
|
-
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
|
|
722
790
|
// and the first call to the send method in legacy browsers
|
|
723
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});}});
|
|
724
792
|
|
|
@@ -731,7 +799,7 @@ xhr.timeout=timeout;Object.keys(options.headers).forEach(headerName=>{if(options
|
|
|
731
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
|
|
732
800
|
.catch(this.onError);}/**
|
|
733
801
|
* Handle errors
|
|
734
|
-
*/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});}/**
|
|
735
803
|
* Set basic authentication header (eg writekey)
|
|
736
804
|
*/getAuthHeader(skipAuthHeader){return skipAuthHeader===true?undefined:this.basicAuthHeader;}setAuthHeader(value,noBtoa=false){const authVal=noBtoa?value:toBase64(`${value}:`);this.basicAuthHeader=`Basic ${authVal}`;}/**
|
|
737
805
|
* Clear basic authentication header
|
|
@@ -752,9 +820,7 @@ const getErrInstance=(err,errorType)=>{switch(errorType){case ErrorType.UNHANDLE
|
|
|
752
820
|
* A function to get the Bugsnag release stage for the current environment
|
|
753
821
|
* @param getHostName Optional function to get the hostname (primarily for testing)
|
|
754
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)
|
|
755
|
-
*/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)=>
|
|
756
|
-
// so that they show up as separate tabs in the dashboard
|
|
757
|
-
...getAppStateForMetadata(state)},user:getUserDetails(source,session,lifecycle,autoTrack)}]};};// A violation only speaks for the kind of load the directive governs. default-src
|
|
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
|
|
758
824
|
// is the fallback for both, so it counts for either.
|
|
759
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));/**
|
|
760
826
|
* Whether a URL is the blocked one or sits beneath it.
|
|
@@ -774,11 +840,11 @@ const inFlightProbes=new Map();/**
|
|
|
774
840
|
* integrations sit under different prefixes and can be blocked independently.
|
|
775
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
|
|
776
842
|
// carrying none of the headers the client would otherwise add.
|
|
777
|
-
skipAuthHeader:true,options:{method:'HEAD',headers:{'Content-Type':undefined,Accept:undefined}},isRawResponse:true,callback:(_result,details)=>{
|
|
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
|
|
778
844
|
// answers instead of dropping it lands on a URL outside the CDN. An
|
|
779
845
|
// ordinary redirect that stays under the CDN -- canonicalisation, a signed
|
|
780
846
|
// URL -- is the CDN answering and must not be mistaken for one.
|
|
781
|
-
const status=details
|
|
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());}});};/**
|
|
782
848
|
* A function to determine whether the error should be promoted to notify or not.
|
|
783
849
|
* Script load failures from a host other than the RS CDN are not promoted.
|
|
784
850
|
* For those from the RS CDN, a probe of the failed URL is awaited so its result
|
|
@@ -795,7 +861,7 @@ const status=details?.xhr?.status??0;const responseURL=details?.xhr?.responseURL
|
|
|
795
861
|
* @param {IHttpClient} httpClient The HTTP client instance
|
|
796
862
|
* @returns A promise that resolves to a boolean indicating whether the error should be promoted to notify or not
|
|
797
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.
|
|
798
|
-
if(SCRIPT_LOAD_FAILURE_MESSAGES.some(regex=>regex.test(errMsg))){const extractedURL=/https?:\/\/[^\s"'(),;<>[\]{}]+/.exec(errMsg)
|
|
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
|
|
799
865
|
// report. The generic ad blocker signal is deliberately not consulted:
|
|
800
866
|
// it probes the source config host rather than the CDN, and a client
|
|
801
867
|
// that cannot reach the CDN is indistinguishable from a CDN outage, so
|
|
@@ -816,11 +882,13 @@ resolve(true);}}else {resolve(!ERROR_MESSAGES_TO_BE_FILTERED.some(e=>e.test(errM
|
|
|
816
882
|
* A function to get the directory name from a file path.
|
|
817
883
|
* @param {string} filePath The file path
|
|
818
884
|
* @returns The directory name or undefined if the file path is invalid
|
|
819
|
-
*/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
|
+
};/**
|
|
820
888
|
* A function to get the top stack path from the exception.
|
|
821
889
|
* @param {Exception} exception The exception object
|
|
822
890
|
* @returns The top stack path or undefined if the exception is invalid
|
|
823
|
-
*/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;};/**
|
|
824
892
|
* A function to determine if the error is from Rudder SDK
|
|
825
893
|
* @param {Error} exception
|
|
826
894
|
* @returns
|
|
@@ -837,8 +905,8 @@ resolve(true);}}else {resolve(!ERROR_MESSAGES_TO_BE_FILTERED.some(e=>e.test(errM
|
|
|
837
905
|
|
|
838
906
|
/**
|
|
839
907
|
* A service to handle errors
|
|
840
|
-
*/class ErrorHandler{
|
|
841
|
-
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;}/**
|
|
842
910
|
* Initializes the error handler by attaching global error listeners.
|
|
843
911
|
* This method should be called once after construction.
|
|
844
912
|
*/init(){if(this.initialized){return;}this.attachErrorListeners();this.initialized=true;}/**
|
|
@@ -856,7 +924,7 @@ document.addEventListener('securitypolicyviolation',event=>{const blockedURL=isS
|
|
|
856
924
|
* @param errorInfo.errorType - The type of the error (handled or unhandled)
|
|
857
925
|
* @param errorInfo.groupingHash - The grouping hash of the error
|
|
858
926
|
* @param errorInfo.category - The category of the error (sdk or integrations)
|
|
859
|
-
*/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.
|
|
860
928
|
// In case of NPM installations, the unhandled errors from the SDK cannot be identified
|
|
861
929
|
// and will NOT be reported unless they occur in plugins or integrations.
|
|
862
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.
|
|
@@ -880,10 +948,10 @@ const defaultErrorHandler=new ErrorHandler(defaultHttpClient,defaultLogger);
|
|
|
880
948
|
// to next or return the value if it is the last one instead of an array per
|
|
881
949
|
// plugin that is the normal invoke
|
|
882
950
|
// TODO: add invoke method for extension point that we know only one plugin can be used. add invokeMultiple and invokeSingle methods
|
|
883
|
-
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.
|
|
884
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
|
|
885
953
|
// do some unified pre-process before application starts.
|
|
886
|
-
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
|
|
887
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
|
|
888
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});
|
|
889
957
|
|
|
@@ -906,7 +974,8 @@ destination.config.useNativeSDK===true);const isHybridModeDestination=destinatio
|
|
|
906
974
|
* @param id The id of the destination
|
|
907
975
|
*
|
|
908
976
|
* @returns the user friendly id
|
|
909
|
-
*/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}`;
|
|
910
979
|
|
|
911
980
|
/**
|
|
912
981
|
* List of plugin names that are loaded as dynamic imports in modern builds
|
|
@@ -984,7 +1053,7 @@ const remotesMap = {
|
|
|
984
1053
|
* Map of optional plugin names and direct imports for legacy builds
|
|
985
1054
|
*/const getOptionalPluginsMap=()=>{{return {};}};/**
|
|
986
1055
|
* Map of optional plugin names and dynamic imports for modern builds
|
|
987
|
-
*/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));
|
|
988
1057
|
|
|
989
1058
|
// TODO: add retry mechanism for getting remote plugins
|
|
990
1059
|
// TODO: add timeout error mechanism for marking remote plugins that failed to load as failed in state
|
|
@@ -1010,15 +1079,16 @@ const availablePlugins=[...Object.keys(pluginsInventory),...pluginNamesList];con
|
|
|
1010
1079
|
* Register plugins that are direct imports to PluginEngine
|
|
1011
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));}}/**
|
|
1012
1081
|
* Register plugins that are dynamic imports to PluginEngine
|
|
1013
|
-
*/registerRemotePlugins(){const remotePluginsList=remotePluginsInventory(state.plugins.activePlugins.value);const loadFailures=[];// Kept separate from state.plugins.failedPlugins, which also collects
|
|
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
|
|
1014
1083
|
// unknown plugins from setActivePlugins, unavailable local plugins from
|
|
1015
1084
|
// registerLocalPlugins and registration failures from register(). Reporting
|
|
1016
1085
|
// the global list would attribute those to this remote load incident.
|
|
1017
|
-
const failedRemotePlugins=[];return Promise.all(Object.keys(remotePluginsList).map(async remotePluginKey=>{await remotePluginsList[remotePluginKey]().then(remotePluginModule=>
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
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
|
|
1022
1092
|
// fan-out is one incident and gets one report, raised only after every
|
|
1023
1093
|
// import has settled so it names all of them.
|
|
1024
1094
|
//
|
|
@@ -1026,7 +1096,9 @@ err?.message??String(err)));loadFailures.push(err);});})).then(()=>{// A failed
|
|
|
1026
1096
|
// deliberate: a dynamic import has no timeout of its own, and holding a
|
|
1027
1097
|
// timer open to salvage a partial report would spend page resources on
|
|
1028
1098
|
// error reporting, which is the lowest priority thing the SDK does.
|
|
1029
|
-
if(failedRemotePlugins.length===0){return;}
|
|
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);});}/**
|
|
1030
1102
|
* Extension point invoke that allows multiple plugins to be registered to it with error handling
|
|
1031
1103
|
*/invokeMultiple(extPoint,...args){try{return this.engine.invokeMultiple(extPoint,...args);}catch(e){this.onError(e,extPoint);return [];}}/**
|
|
1032
1104
|
* Extension point invoke that allows a single plugin to be registered to it with error handling
|
|
@@ -1047,7 +1119,7 @@ const storageClientDataStoreNameMap={[COOKIE_STORAGE]:CLIENT_DATA_STORE_COOKIE,[
|
|
|
1047
1119
|
|
|
1048
1120
|
/**
|
|
1049
1121
|
* Encode.
|
|
1050
|
-
*/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;}};/**
|
|
1051
1123
|
* Decode
|
|
1052
1124
|
*/const decode=value=>{try{return decodeURIComponent(value);}catch(err){// Do nothing as non-RS SDK cookies may not be URI encoded
|
|
1053
1125
|
return undefined;}};/**
|
|
@@ -1055,7 +1127,7 @@ return undefined;}};/**
|
|
|
1055
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
|
|
1056
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;};/**
|
|
1057
1129
|
* Set cookie `name` to `value`
|
|
1058
|
-
*/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;};/**
|
|
1059
1131
|
* Return all cookies
|
|
1060
1132
|
*/const all=()=>{const cookieStringValue=globalThis.document.cookie;return parse(cookieStringValue);};/**
|
|
1061
1133
|
* Get cookie `name`
|
|
@@ -1068,8 +1140,8 @@ const legacyGetHostname=href=>{const l=document.createElement('a');l.href=href;r
|
|
|
1068
1140
|
* Levels returns all levels of the given url
|
|
1069
1141
|
*
|
|
1070
1142
|
* The method returns an empty array when the hostname is an ip.
|
|
1071
|
-
*/const levelsFunc=url=>{
|
|
1072
|
-
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.
|
|
1073
1145
|
if(parts.length===4&&last&&last===parseInt(last,10).toString()){return levels;}// Localhost.
|
|
1074
1146
|
if(parts.length<=1){// Fix to support localhost
|
|
1075
1147
|
if(parts[0]&&parts[0].indexOf('localhost')!==-1){return ['localhost'];}return levels;}// Create levels.
|
|
@@ -1085,16 +1157,16 @@ for(let i=parts.length-2;i>=0;i-=1){levels.push(parts.slice(i).join('.'));}retur
|
|
|
1085
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
|
|
1086
1158
|
cookie(cname,1,opts);// If successful
|
|
1087
1159
|
if(cookie(cname)){// Remove cookie from domain
|
|
1088
|
-
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
|
|
1089
1161
|
// Best-effort cleanup to avoid leaking the test cookie
|
|
1090
|
-
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
|
|
1091
1163
|
}}}return '';};
|
|
1092
1164
|
|
|
1093
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});
|
|
1094
1166
|
|
|
1095
1167
|
/**
|
|
1096
1168
|
* A storage utility to retain values in memory via Storage interface
|
|
1097
|
-
*/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);
|
|
1098
1170
|
|
|
1099
1171
|
function getDefaultExportFromCjs (x) {
|
|
1100
1172
|
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
|
@@ -1115,8 +1187,8 @@ const store = /*@__PURE__*/getDefaultExportFromCjs(storeExports);
|
|
|
1115
1187
|
const isStorageQuotaExceeded=e=>{const matchingNames=['QuotaExceededError','NS_ERROR_DOM_QUOTA_REACHED'];// Everything except Firefox, Firefox
|
|
1116
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
|
|
1117
1189
|
// https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage#exceptions
|
|
1118
|
-
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
|
|
1119
|
-
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
|
|
1120
1192
|
return false;};
|
|
1121
1193
|
|
|
1122
1194
|
// check if the get, set overloads and search methods are used at all
|
|
@@ -1124,24 +1196,24 @@ return false;};
|
|
|
1124
1196
|
// https://www.npmjs.com/package/storejs
|
|
1125
1197
|
/**
|
|
1126
1198
|
* A storage utility to persist values in localstorage via Storage interface
|
|
1127
|
-
*/class LocalStorage{isSupportAvailable
|
|
1128
|
-
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
|
|
1129
1201
|
keys(){return store.keys();}}const defaultLocalStorage=new LocalStorage(defaultLogger);
|
|
1130
1202
|
|
|
1131
1203
|
/**
|
|
1132
1204
|
* A storage utility to persist values in SessionStorage via Storage interface
|
|
1133
|
-
*/class SessionStorage{isSupportAvailable
|
|
1134
|
-
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);
|
|
1135
1207
|
|
|
1136
1208
|
/**
|
|
1137
1209
|
* A storage utility to persist values in cookies via Storage interface
|
|
1138
|
-
*/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
|
|
1139
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
|
|
1140
1212
|
clear(){// Not implemented
|
|
1141
1213
|
// getting a list of all cookie storage keys and remove all values
|
|
1142
1214
|
// sounds risky to do as it will take on all top domain cookies
|
|
1143
1215
|
// better to explicitly clear specific ones if needed
|
|
1144
|
-
}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
|
|
1145
1217
|
keys(){return Object.keys(cookie());}}const defaultCookieStorage=new CookieStorage(defaultLogger);
|
|
1146
1218
|
|
|
1147
1219
|
/**
|
|
@@ -1161,12 +1233,12 @@ state.storage.cookie.value={maxage:cookieStorageOptions.maxage,path:cookieStorag
|
|
|
1161
1233
|
|
|
1162
1234
|
/**
|
|
1163
1235
|
* Store Implementation with dedicated storage
|
|
1164
|
-
*/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;}/**
|
|
1165
1237
|
* Ensure the key is valid and with correct format
|
|
1166
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
|
|
1167
1239
|
let compoundKey;Object.values(validKeys).forEach(validKeyName=>{if(validKeyName===key){compoundKey=noCompoundKey?key:[name,id,key].join('.');}});return compoundKey;}/**
|
|
1168
1240
|
* Switch to inMemoryEngine, bringing any existing data with.
|
|
1169
|
-
*/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
|
|
1170
1242
|
// better to keep other queues in localstorage to be flushed later
|
|
1171
1243
|
// than to pull them into memory and remove them from durable storage
|
|
1172
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
|
|
@@ -1176,7 +1248,7 @@ const canDropDurableCopy=!noCompoundKey&&durableEngine!==inMemoryStorage;this.en
|
|
|
1176
1248
|
this.set(storeKey,value);// Only give up the durable copy once the value is readable from memory:
|
|
1177
1249
|
// set() swallows serialisation and storage failures, and get() returns
|
|
1178
1250
|
// null on a parse or decryption failure.
|
|
1179
|
-
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
|
|
1180
1252
|
// value is already safe in memory, so leave the stale copy for a later
|
|
1181
1253
|
// cleanup rather than aborting the migration - this runs inside set()'s
|
|
1182
1254
|
// catch, and throwing here would lose the value that triggered it.
|
|
@@ -1187,8 +1259,18 @@ this.engine.setItem(validKey,this.encrypt(stringifyWithoutCircular(value,false,[
|
|
|
1187
1259
|
this.swapQueueStoreToInMemoryEngine();// and save it there
|
|
1188
1260
|
this.set(key,value);}else {const customMessage=STORE_DATA_SAVE_ERROR(key);this.onError(err,customMessage,customMessage);}}}/**
|
|
1189
1261
|
* Get by Key.
|
|
1190
|
-
*/get(key){const validKey=this.createValidKey(key);let decryptedValue;try{if(!validKey){return null;}
|
|
1191
|
-
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
|
|
1192
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;}}/**
|
|
1193
1275
|
* Remove by Key.
|
|
1194
1276
|
*/remove(key){const validKey=this.createValidKey(key);if(validKey){this.engine.removeItem(validKey);}}/**
|
|
@@ -1199,31 +1281,31 @@ const shouldReportError=!encryptionPluginName||!state.plugins.failedPlugins.valu
|
|
|
1199
1281
|
* Encrypt value
|
|
1200
1282
|
*/encrypt(value){return this.crypto(value,'encrypt');}/**
|
|
1201
1283
|
* Extension point to use with encryption plugins
|
|
1202
|
-
*/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:'';}/**
|
|
1203
1285
|
* Handle errors
|
|
1204
1286
|
*/onError(error,customMessage,groupingHash){this.errorHandler.onError({error,context:`Store ${this.id}`,customMessage,groupingHash});}}
|
|
1205
1287
|
|
|
1206
|
-
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;};
|
|
1207
1289
|
|
|
1208
1290
|
/**
|
|
1209
1291
|
* A service to manage stores & available storage client configurations
|
|
1210
|
-
*/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;}/**
|
|
1211
1293
|
* Configure available storage client instances
|
|
1212
|
-
*/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;}/**
|
|
1213
1295
|
* Create store to persist data used by the SDK like session, used details etc
|
|
1214
1296
|
*/initClientDataStores(){this.initializeStorageState();// TODO: fill in extra config values and bring them in from StoreManagerOptions if needed
|
|
1215
1297
|
// TODO: should we pass the keys for all in order to validate or leave free as v1.1?
|
|
1216
1298
|
// Initializing all the enabled store because previous user data might be in different storage
|
|
1217
1299
|
// that needs auto migration
|
|
1218
|
-
const storageTypes=[MEMORY_STORAGE,LOCAL_STORAGE,COOKIE_STORAGE,SESSION_STORAGE];storageTypes.forEach(storageType=>{if(getStorageEngine(storageType)
|
|
1219
|
-
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
|
|
1220
1302
|
// persisted before consent is given. Only the fallback changes: nothing is persisted unless
|
|
1221
1303
|
// a storage type has been explicitly configured.
|
|
1222
|
-
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
|
|
1223
1305
|
// resolved here, against the default that applies to the current consent phase
|
|
1224
|
-
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
|
|
1225
|
-
let storageType=preConsentStorageType
|
|
1226
|
-
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;}/**
|
|
1227
1309
|
* Create a new store
|
|
1228
1310
|
*/setStore(storeConfig){const storageEngine=getStorageEngine(storeConfig.type);this.stores[storeConfig.id]=new Store(storeConfig,storageEngine,this.pluginsManager);return this.stores[storeConfig.id];}/**
|
|
1229
1311
|
* Retrieve a store
|
|
@@ -1235,7 +1317,7 @@ const isValidSourceConfig=res=>isObjectLiteralAndNotNull(res)&&isObjectLiteralAn
|
|
|
1235
1317
|
* @param storageOpts Storage options from the load API options or the consent API options
|
|
1236
1318
|
* @param context Logger context
|
|
1237
1319
|
* @param logger Logger instance
|
|
1238
|
-
*/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));}});}};/**
|
|
1239
1321
|
* Parses a URL without the URL constructor, which is unavailable on legacy JS engines
|
|
1240
1322
|
* until the polyfills load.
|
|
1241
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,
|
|
@@ -1259,11 +1341,11 @@ if(hostOnlyCookies||!webpageTopDomain){return dataServiceHostname===globalThis.l
|
|
|
1259
1341
|
* Removes trailing slash from url
|
|
1260
1342
|
* @param url
|
|
1261
1343
|
* @returns url
|
|
1262
|
-
*/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;}};/**
|
|
1263
1345
|
* Get the referring domain from the referrer URL
|
|
1264
1346
|
* @param referrer Page referrer
|
|
1265
1347
|
* @returns Page referring domain
|
|
1266
|
-
*/const getReferringDomain=referrer=>getDomain(referrer)
|
|
1348
|
+
*/const getReferringDomain=referrer=>{var _getDomain;return (_getDomain=getDomain(referrer))!==null&&_getDomain!==void 0?_getDomain:'';};/**
|
|
1267
1349
|
* Extracts UTM parameters from the URL
|
|
1268
1350
|
* @param url Page URL
|
|
1269
1351
|
* @returns UTM parameters
|
|
@@ -1287,7 +1369,7 @@ new URL(url);}return URL_PATTERN.test(url);}catch(e){return false;}};
|
|
|
1287
1369
|
|
|
1288
1370
|
const DEFAULT_PRE_CONSENT_STORAGE_STRATEGY='none';const DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE='immediate';
|
|
1289
1371
|
|
|
1290
|
-
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;};
|
|
1291
1373
|
|
|
1292
1374
|
/**
|
|
1293
1375
|
* Validates and normalizes the consent options provided by the user
|
|
@@ -1311,7 +1393,7 @@ provider=undefined;}return {provider,consentManagerPluginName};};/**
|
|
|
1311
1393
|
* @param consentManagementOpts Consent management options provided by the user
|
|
1312
1394
|
* @param logger logger instance
|
|
1313
1395
|
* @returns An object containing the consent manager plugin name, initialized, enabled and consents data
|
|
1314
|
-
*/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
|
|
1315
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
|
|
1316
1398
|
enabled=enabled&&Boolean(consentManagerPluginName);return {provider,consentManagerPluginName,initialized,enabled,consentsData};};
|
|
1317
1399
|
|
|
@@ -1347,11 +1429,11 @@ const cookieDomain=removeLeadingPeriod(providedCookieDomain).toLowerCase();/**
|
|
|
1347
1429
|
* The cookie domain also has to sit at or below the browser-verified domain of the webpage.
|
|
1348
1430
|
* Anything above it is a public suffix, ex: 'co.uk', which the browser refuses to scope
|
|
1349
1431
|
* cookies to however well it matches as a string suffix.
|
|
1350
|
-
*/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;/**
|
|
1351
1433
|
* Based on the following conditions, we decide whether to use the exact domain or not to determine the data service URL:
|
|
1352
1434
|
* 1. If the cookie domain is provided and it is not a top-level domain, then use the exact domain
|
|
1353
1435
|
* 2. If the sameDomainCookiesOnly flag is set to true, then use the exact domain
|
|
1354
|
-
*/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,
|
|
1355
1437
|
// in which case the data service host cannot be verified
|
|
1356
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
|
|
1357
1439
|
// cross-site request. Cookies are not isolated by port, hence it plays no part here.
|
|
@@ -1359,29 +1441,29 @@ const dataServiceHostname=getHostname(dataServiceUrl);if(isValidURL(dataServiceU
|
|
|
1359
1441
|
// One round of cookie options manipulation is taking place here
|
|
1360
1442
|
// Based on these(setCookieDomain/storage.cookie or sameDomainCookiesOnly) two load-options, final cookie options are set in the storage module
|
|
1361
1443
|
// TODO: Refactor the cookie options manipulation logic in one place
|
|
1362
|
-
if(sscEnabled&&webpageHostname!==dataServiceHostname){cookieOptions={
|
|
1363
|
-
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
|
|
1364
1446
|
// values are resolved in the store manager.
|
|
1365
|
-
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
|
|
1366
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
|
|
1367
|
-
const configuredMigrationValue=storageOptsFromLoad
|
|
1368
|
-
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,
|
|
1369
1451
|
// so an existing configuration keeps persisting nothing before consent is given. Enabling it
|
|
1370
1452
|
// takes precedence over the deprecated strategy, otherwise a migration that leaves the strategy
|
|
1371
1453
|
// in place would silently do nothing.
|
|
1372
|
-
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
|
|
1373
1455
|
// if it is not already initialized and
|
|
1374
1456
|
// if consent management is enabled
|
|
1375
|
-
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}};});};/**
|
|
1376
1458
|
* Determines the consent management state variables from the source config data
|
|
1377
1459
|
* @param resp Source config response
|
|
1378
1460
|
* @param logger Logger instance
|
|
1379
|
-
*/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
|
|
1380
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}`;};/**
|
|
1381
1463
|
* Transforms destinations config from source config response to Destination format
|
|
1382
1464
|
* @param destinations Array of destination items from config response
|
|
1383
1465
|
* @returns Array of transformed Destination objects
|
|
1384
|
-
*/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};});
|
|
1385
1467
|
|
|
1386
1468
|
/**
|
|
1387
1469
|
* A function that determines the base URL for the integrations or plugins SDK
|
|
@@ -1435,10 +1517,10 @@ state.nativeDestinations.loadOnlyIntegrations.value=integrations;});this.getConf
|
|
|
1435
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
|
|
1436
1518
|
if(res.source.enabled===false){this.logger.error(SOURCE_DISABLED_ERROR);return;}// set the values in state for reporting slice
|
|
1437
1519
|
updateReportingState(res);const nativeDestinations=res.source.destinations.length>0?getDestinationsFromConfig(res.source.destinations):[];// set in the state --> source, destination, lifecycle, reporting
|
|
1438
|
-
n(()=>{
|
|
1520
|
+
n(()=>{var _state$loadOptions$va;// set source related information in state
|
|
1439
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
|
|
1440
1522
|
state.nativeDestinations.configuredDestinations.value=nativeDestinations;// set the desired optional plugins
|
|
1441
|
-
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
|
|
1442
1524
|
state.lifecycle.status.value='configured';});}/**
|
|
1443
1525
|
* A function to fetch source config either from /sourceConfig endpoint
|
|
1444
1526
|
* or from getSourceConfig load option
|
|
@@ -1453,19 +1535,19 @@ this.httpClient.getAsyncData({url:state.lifecycle.sourceConfigUrl.value,options:
|
|
|
1453
1535
|
* @returns string
|
|
1454
1536
|
*/const getTimezone=()=>{// Not susceptible to super-linear backtracking
|
|
1455
1537
|
// eslint-disable-next-line sonarjs/slow-regex
|
|
1456
|
-
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';};
|
|
1457
1539
|
|
|
1458
1540
|
/**
|
|
1459
1541
|
* Get the referrer URL
|
|
1460
1542
|
* @returns The referrer URL
|
|
1461
|
-
*/const getReferrer=(getDocument=()=>document)=>getDocument()
|
|
1543
|
+
*/const getReferrer=(getDocument=()=>document)=>{var _getDocument;return ((_getDocument=getDocument())===null||_getDocument===void 0?void 0:_getDocument.referrer)||'$direct';};/**
|
|
1462
1544
|
* To get the canonical URL of the page
|
|
1463
1545
|
* @returns canonical URL
|
|
1464
|
-
*/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,
|
|
1465
1547
|
// add "Brave/<version>" to the user agent with the version value from the Chrome component
|
|
1466
1548
|
if(brave&&Object.getPrototypeOf(brave).isBrave){// Example:
|
|
1467
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
|
|
1468
|
-
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;};/**
|
|
1469
1551
|
* Default page properties
|
|
1470
1552
|
* @returns Default page properties
|
|
1471
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.
|
|
@@ -1473,17 +1555,7 @@ if(canonicalUrl){try{const urlObj=new URL(canonicalUrl);// If existing, query pa
|
|
|
1473
1555
|
if(urlObj.search===''){pageUrl=canonicalUrl+search;}else {pageUrl=canonicalUrl;}path=urlObj.pathname;}catch(err){// Do nothing
|
|
1474
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};};
|
|
1475
1557
|
|
|
1476
|
-
const getUserAgentClientHint=(callback,level='none')=>{if(level==='none'){callback(undefined);}if(level==='default'){callback(navigator.userAgentData);}if(level==='full'){navigator.userAgentData
|
|
1477
|
-
|
|
1478
|
-
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
|
|
1479
|
-
// the polyfill service serves them under the same feature name, "URL".
|
|
1480
|
-
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
|
|
1481
|
-
// the polyfill service serves them under the same feature name, "TextEncoder".
|
|
1482
|
-
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".
|
|
1483
|
-
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;};
|
|
1484
|
-
|
|
1485
|
-
const polyfillIoSdkUrl='https://polyfill-fastly.io/v3/polyfill.min.js';const POLYFILL_URL=`${polyfillIoSdkUrl}?version=3.111.0&features=${Object.keys(legacyJSEngineRequiredPolyfills).join('%2C')}`;const POLYFILL_LOAD_TIMEOUT=10*1000;// 10 seconds
|
|
1486
|
-
const POLYFILL_SCRIPT_ID='rudderstackPolyfill';
|
|
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();});}};
|
|
1487
1559
|
|
|
1488
1560
|
const detectAdBlockers=httpClient=>{state.capabilities.isAdBlockerDetectionInProgress.value=true;try{// Apparently, '?view=ad' is a query param that is blocked by majority of adblockers
|
|
1489
1561
|
// Use source config URL here as it is very unlikely to be blocked by adblockers
|
|
@@ -1491,9 +1563,9 @@ const detectAdBlockers=httpClient=>{state.capabilities.isAdBlockerDetectionInPro
|
|
|
1491
1563
|
// This will work even if the users proxies it.
|
|
1492
1564
|
// The edge case where this doesn't work is when HEAD method is not allowed by the server (user's)
|
|
1493
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
|
|
1494
|
-
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
|
|
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
|
|
1495
1567
|
// Often adblockers instead of blocking the request, they redirect it to an internal URL
|
|
1496
|
-
state.capabilities.isAdBlocked.value=details
|
|
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
|
|
1497
1569
|
state.capabilities.isAdBlockerDetectionInProgress.value=false;// Re-throw the error to be handled by the caller
|
|
1498
1570
|
throw err;}};
|
|
1499
1571
|
|
|
@@ -1511,10 +1583,13 @@ state.capabilities.isBeaconAvailable.value=hasBeacon();state.capabilities.isUaCH
|
|
|
1511
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
|
|
1512
1584
|
j(()=>{if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(this.httpClient);}});}/**
|
|
1513
1585
|
* Detect if polyfills are required and then load script from polyfill URL
|
|
1514
|
-
*/prepareBrowserCapabilities(){
|
|
1515
|
-
//
|
|
1516
|
-
|
|
1517
|
-
|
|
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();}/**
|
|
1518
1593
|
* Attach listeners to window to observe event that update capabilities state values
|
|
1519
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));}/**
|
|
1520
1595
|
* Set the lifecycle status to next phase
|
|
@@ -1522,7 +1597,7 @@ delete globalThis[polyfillCallbackName];};globalThis[polyfillCallbackName]=polyf
|
|
|
1522
1597
|
onReady(){this.detectBrowserCapabilities();state.lifecycle.status.value='browserCapabilitiesReady';}/**
|
|
1523
1598
|
* Handles error
|
|
1524
1599
|
* @param error The error object
|
|
1525
|
-
*/onError(error,groupingHash){this.errorHandler.onError({error,context:CAPABILITIES_MANAGER,groupingHash});}}
|
|
1600
|
+
*/onError(error,groupingHash){void this.errorHandler.onError({error,context:CAPABILITIES_MANAGER,groupingHash});}}
|
|
1526
1601
|
|
|
1527
1602
|
const CHANNEL='web';// These are the top-level elements in the standard RudderStack event spec
|
|
1528
1603
|
const TOP_LEVEL_ELEMENTS=['integrations','anonymousId','originalTimestamp'];// Reserved elements in the context of standard RudderStack event spec
|
|
@@ -1530,7 +1605,7 @@ const TOP_LEVEL_ELEMENTS=['integrations','anonymousId','originalTimestamp'];// R
|
|
|
1530
1605
|
const CONTEXT_RESERVED_ELEMENTS=['library','consentManagement','userAgent','ua-ch','screen'];// Reserved elements in the standard RudderStack event spec
|
|
1531
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'];
|
|
1532
1607
|
|
|
1533
|
-
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;}};
|
|
1534
1609
|
|
|
1535
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={};}}
|
|
1536
1611
|
|
|
@@ -1549,7 +1624,7 @@ class CustomContextStore{constructor(state,logger){this.state=state;this.logger=
|
|
|
1549
1624
|
* @returns boolean
|
|
1550
1625
|
*/const isPositiveInteger=num=>isNumber(num)&&num>=0&&Number.isInteger(num);
|
|
1551
1626
|
|
|
1552
|
-
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);};/**
|
|
1553
1628
|
* A function to validate whether the current auto tracking session has expired or not.
|
|
1554
1629
|
* It checks for the current session expiry and the cut off time expiry.
|
|
1555
1630
|
* @param sessionInfo session info
|
|
@@ -1562,13 +1637,13 @@ const MIN_SESSION_ID_LENGTH=10;const isCutOffTimeExceeded=sessionInfo=>{const{cu
|
|
|
1562
1637
|
* @param {number} sessionId
|
|
1563
1638
|
* @param logger logger
|
|
1564
1639
|
* @returns
|
|
1565
|
-
*/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;};/**
|
|
1566
1641
|
* A function to generate new auto tracking session
|
|
1567
1642
|
* @param sessionInfo session info
|
|
1568
1643
|
* @returns SessionInfo
|
|
1569
|
-
*/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
|
|
1570
1645
|
expiresAt:timestamp+timeout,// set the expiry time of the session
|
|
1571
|
-
timeout,autoTrack:true
|
|
1646
|
+
timeout,autoTrack:true},cutOff&&{cutOff});};/**
|
|
1572
1647
|
* A function to generate new manual tracking session
|
|
1573
1648
|
* @param id Provided sessionId
|
|
1574
1649
|
* @param logger Logger module
|
|
@@ -1577,19 +1652,19 @@ timeout,autoTrack:true,...(cutOff&&{cutOff})};};/**
|
|
|
1577
1652
|
* Generate a new anonymousId
|
|
1578
1653
|
* @returns string anonymousID
|
|
1579
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
|
|
1580
|
-
if(isBoolean(options)){const{entries
|
|
1581
|
-
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);};
|
|
1582
1657
|
|
|
1583
1658
|
/**
|
|
1584
1659
|
* To get the page properties for context object
|
|
1585
1660
|
* @param pageProps Page properties
|
|
1586
1661
|
* @returns page properties object for context
|
|
1587
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
|
|
1588
|
-
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;};/**
|
|
1589
1664
|
* Add any missing default page properties using values from options and defaults
|
|
1590
1665
|
* @param properties Input page properties
|
|
1591
1666
|
* @param options API options
|
|
1592
|
-
*/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
|
|
1593
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;};/**
|
|
1594
1669
|
* Utility to check for reserved keys in the input object
|
|
1595
1670
|
* @param obj Generic object
|
|
@@ -1622,20 +1697,18 @@ rudderEvent.context=getMergedContext(rudderEvent.context,options,logger);}};/**
|
|
|
1622
1697
|
* Returns the final integrations config for the event based on the global config and event's config
|
|
1623
1698
|
* @param integrationsConfig Event's integrations config
|
|
1624
1699
|
* @returns Final integrations config
|
|
1625
|
-
*/const getEventIntegrationsConfig=integrationsConfig=>{let finalIntgConfig;if(state.loadOptions.value.useGlobalIntegrationsConfigInEvents){
|
|
1626
|
-
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);};/**
|
|
1627
1702
|
* Enrich the base event object with data from state and the API options
|
|
1628
1703
|
* @param rudderEvent RudderEvent object
|
|
1629
1704
|
* @param options API options
|
|
1630
1705
|
* @param pageProps Page properties
|
|
1631
1706
|
* @param logger logger
|
|
1632
1707
|
* @returns Enriched RudderEvent object
|
|
1633
|
-
*/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
|
|
1634
|
-
...(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
|
|
1635
|
-
...(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
|
|
1636
1709
|
commonEventData.anonymousId=generateAnonymousId();}else {// Type casting to string as the user session manager will take care of initializing the value
|
|
1637
1710
|
commonEventData.anonymousId=state.session.anonymousId.value;}// set truly anonymous tracking flag
|
|
1638
|
-
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
|
|
1639
1712
|
// matching with v1.1 payload
|
|
1640
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
|
|
1641
1714
|
processedEvent.integrations=getEventIntegrationsConfig(processedEvent.integrations);return processedEvent;};
|
|
@@ -1646,7 +1719,7 @@ class RudderEventFactory{constructor(logger){this.logger=logger;}/**
|
|
|
1646
1719
|
* @param name Page name
|
|
1647
1720
|
* @param properties Page properties
|
|
1648
1721
|
* @param options API options
|
|
1649
|
-
*/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);}/**
|
|
1650
1723
|
* Generate a 'track' event based on the user-input fields
|
|
1651
1724
|
* @param event The event name
|
|
1652
1725
|
* @param properties Event properties
|
|
@@ -1662,7 +1735,7 @@ class RudderEventFactory{constructor(logger){this.logger=logger;}/**
|
|
|
1662
1735
|
* @param from Old user ID
|
|
1663
1736
|
* @param options API options
|
|
1664
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
|
|
1665
|
-
enrichedEvent.userId=to
|
|
1738
|
+
enrichedEvent.userId=to!==null&&to!==void 0?to:enrichedEvent.userId;return enrichedEvent;}/**
|
|
1666
1739
|
* Generate a 'group' event based on the user-input fields
|
|
1667
1740
|
* @param groupId New group ID
|
|
1668
1741
|
* @param traits new group traits
|
|
@@ -1703,16 +1776,16 @@ class UserSessionManager{/**
|
|
|
1703
1776
|
* Initialize User session with values from storage
|
|
1704
1777
|
*/init(){this.syncStorageDataToState();// Register the effect to sync with storage
|
|
1705
1778
|
this.registerEffects();}syncStorageDataToState(){this.migrateStorageIfNeeded();this.migrateDataFromPreviousStorage();// get the values from storage and set it again
|
|
1706
|
-
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
|
|
1707
1780
|
sessionInfo={// If manualTrack is set to true in the storage, then do not enable auto tracking even if configured.
|
|
1708
1781
|
// Once manual tracking ends (endSession is called), auto tracking will be enabled in the next SDK run.
|
|
1709
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
|
|
1710
|
-
if(!sessionInfo.autoTrack&&sessionInfo.manualTrack!==true){sessionInfo=DEFAULT_USER_SESSION_VALUES.sessionInfo;}else if(configuredSessionTrackingInfo.cutOff
|
|
1711
|
-
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
|
|
1712
1785
|
// as those values indicate there is no need for migration or
|
|
1713
1786
|
// migration failed
|
|
1714
|
-
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
|
|
1715
|
-
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
|
|
1716
1789
|
// and will proceed with it
|
|
1717
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
|
|
1718
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};}/**
|
|
@@ -1723,23 +1796,23 @@ cutOffDuration=DEFAULT_SESSION_CUT_OFF_DURATION_MS;}else if(cutOffDuration<sessi
|
|
|
1723
1796
|
* @param cookiesData
|
|
1724
1797
|
* @param store
|
|
1725
1798
|
* @returns
|
|
1726
|
-
*/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;}/**
|
|
1727
1800
|
* A function that makes request to data service to set the cookie
|
|
1728
1801
|
* @param encryptedCookieData
|
|
1729
1802
|
* @param callback
|
|
1730
|
-
*/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});}/**
|
|
1731
1804
|
* A function to make an external request to set the cookie from server side
|
|
1732
1805
|
* @param sessionToCookiesMap map of session key to cookie name
|
|
1733
1806
|
* @param cb callback function to be called when the cookie is set
|
|
1734
1807
|
* @param store store to be used to get the cookie value
|
|
1735
1808
|
*/setServerSideCookies(sessionToCookiesMap,cb,store){// Retrieve the cookie value from the state
|
|
1736
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
|
|
1737
|
-
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
|
|
1738
1811
|
const encryptedCookieData=this.getEncryptedCookieData(getCurrentCookieValuesFromState(),store);if(encryptedCookieData.length>0){// make request to data service to set the cookie from server side
|
|
1739
|
-
this.makeRequestToSetCookie(encryptedCookieData,(res,details)=>{
|
|
1740
|
-
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
|
|
1741
1814
|
// both halves of the diagnostic are drawn from the same set
|
|
1742
|
-
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.
|
|
1743
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
|
|
1744
1817
|
// or other cookie requests might have updated the cookie value.
|
|
1745
1818
|
// Left exactly as the request found it, so the server did not apply this
|
|
@@ -1757,7 +1830,7 @@ if(isNull(originalCookieVal)&&isNull(currentCookieVal)){this.logger.error(FAILED
|
|
|
1757
1830
|
// attributes usually leave none of them set.
|
|
1758
1831
|
// Counted from what was actually sent, not from the queued keys: encryption can
|
|
1759
1832
|
// drop a key, and reporting it as sent would overstate the batch.
|
|
1760
|
-
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
|
|
1761
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
|
|
1762
1835
|
clearInProgressFlags();}}/**
|
|
1763
1836
|
* A function to send every queued server-side cookie as a single request
|
|
@@ -1765,10 +1838,10 @@ clearInProgressFlags();}}/**
|
|
|
1765
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
|
|
1766
1839
|
// queued for the next batch rather than being sent twice
|
|
1767
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
|
|
1768
|
-
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);}/**
|
|
1769
1842
|
* A function to sync values in storage
|
|
1770
1843
|
* @param sessionKey
|
|
1771
|
-
*/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
|
|
1772
1845
|
// set the cookie from server side
|
|
1773
1846
|
if(state.serverCookies.isEnabledServerSideCookies.value&&storageType===COOKIE_STORAGE){// Mark the requests as in progress.
|
|
1774
1847
|
this.serverSideCookiesRequestInProgress[sessionKey]=true;// Queue this key and restart the shared debounce, so everything that changes in
|
|
@@ -1777,7 +1850,7 @@ this.serverSideCookiesPending[sessionKey]=cookieName;// Restarting the shared ti
|
|
|
1777
1850
|
// keep postponing the flush for every other key, where per-key timers only ever
|
|
1778
1851
|
// delayed their own. That needs changes arriving closer together than the
|
|
1779
1852
|
// debounce, continuously, so it is accepted rather than capped with a max wait.
|
|
1780
|
-
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);}}}/**
|
|
1781
1854
|
* Function to update storage whenever state value changes
|
|
1782
1855
|
*/registerEffects(){// This will work as long as the user session entry key names are same as the state keys
|
|
1783
1856
|
USER_SESSION_KEYS.forEach(sessionKey=>{j(()=>{// Read before syncing so the effect subscribes to the signal, and record after
|
|
@@ -1789,16 +1862,16 @@ const value=state.session[sessionKey].value;this.syncValueToStorage(sessionKey);
|
|
|
1789
1862
|
* 2. rudderAmpLinkerParam: value generated from linker query parm (rudderstack)
|
|
1790
1863
|
* using parseLinker util.
|
|
1791
1864
|
* 3. generateUUID: A new unique id is generated and assigned.
|
|
1792
|
-
*/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;}/**
|
|
1793
1866
|
* Fetches anonymousId
|
|
1794
1867
|
* @param options option to fetch it from external source
|
|
1795
1868
|
* @returns anonymousId
|
|
1796
|
-
*/getAnonymousId(options){const storage=state.storage.entries.value.anonymousId
|
|
1797
|
-
if(!persistedAnonymousId||persistedAnonymousId===DEFAULT_USER_SESSION_VALUES.anonymousId){persistedAnonymousId=this.getEntryValue('anonymousId');}if(!persistedAnonymousId&&options){
|
|
1798
|
-
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
|
|
1799
1872
|
// This is needed for entries that are fetched from the storage
|
|
1800
1873
|
// during the current session (for example, session info)
|
|
1801
|
-
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;}/**
|
|
1802
1875
|
* Fetches the value for a session key. Preferably from storage, so that changes made by
|
|
1803
1876
|
* other tabs are picked up. Falls back to the state whenever storage is known to be
|
|
1804
1877
|
* behind it.
|
|
@@ -1847,20 +1920,20 @@ return this.getEntryValue(sessionKey);}/**
|
|
|
1847
1920
|
*/getAuthToken(){return this.getUserSessionValue('authToken');}/**
|
|
1848
1921
|
* If session is active it returns the sessionId
|
|
1849
1922
|
* @returns
|
|
1850
|
-
*/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;}/**
|
|
1851
1924
|
* A function to keep the session information up to date in the state
|
|
1852
1925
|
* before using it for building event payloads.
|
|
1853
|
-
*/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.
|
|
1854
1927
|
// So, we needn't update the session info.
|
|
1855
1928
|
//
|
|
1856
1929
|
// For other scenarios,
|
|
1857
1930
|
// 1. If sessionStart is undefined, then it's a new session.
|
|
1858
1931
|
// Mark it as sessionStart.
|
|
1859
1932
|
// 2. If sessionStart is true, then need to flip it for the future events.
|
|
1860
|
-
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.
|
|
1861
1934
|
state.session.sessionInfo.value=sessionInfo;if(state.lifecycle.status.value!=='readyExecuted'){// Force update the storage as the 'effect' blocks are not getting triggered
|
|
1862
1935
|
// when processing preload buffered requests
|
|
1863
|
-
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();}}/**
|
|
1864
1937
|
* Reset state values
|
|
1865
1938
|
* @param options options for reset
|
|
1866
1939
|
* @returns
|
|
@@ -1870,13 +1943,13 @@ this.syncValueToStorage('sessionInfo');}}resetAndStartNewSession(){const session
|
|
|
1870
1943
|
*/setUserId(userId){state.session.userId.value=this.isPersistenceEnabledForStorageEntry('userId')&&userId?userId:DEFAULT_USER_SESSION_VALUES.userId;}/**
|
|
1871
1944
|
* Set user traits
|
|
1872
1945
|
* @param traits
|
|
1873
|
-
*/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;}/**
|
|
1874
1947
|
* Set group Id
|
|
1875
1948
|
* @param groupId
|
|
1876
1949
|
*/setGroupId(groupId){state.session.groupId.value=this.isPersistenceEnabledForStorageEntry('groupId')&&groupId?groupId:DEFAULT_USER_SESSION_VALUES.groupId;}/**
|
|
1877
1950
|
* Set group traits
|
|
1878
1951
|
* @param traits
|
|
1879
|
-
*/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;}/**
|
|
1880
1953
|
* Set initial referrer
|
|
1881
1954
|
* @param referrer
|
|
1882
1955
|
*/setInitialReferrer(referrer){state.session.initialReferrer.value=this.isPersistenceEnabledForStorageEntry('initialReferrer')&&referrer?referrer:DEFAULT_USER_SESSION_VALUES.initialReferrer;}/**
|
|
@@ -1907,7 +1980,7 @@ state.session.sessionInfo.value=finalSessionInfo;}/**
|
|
|
1907
1980
|
const defaultOptionalPluginsList=allOptionalPlugins;
|
|
1908
1981
|
|
|
1909
1982
|
const normalizeLoadOptions=(loadOptionsFromState,loadOptions)=>{// TODO: Maybe add warnings for invalid values
|
|
1910
|
-
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;};
|
|
1911
1984
|
|
|
1912
1985
|
const DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';const DESTINATIONS_QUEUE_EXT_POINT_PREFIX='destinationsEventsQueue';const DMT_EXT_POINT_PREFIX='transformEvent';
|
|
1913
1986
|
|
|
@@ -1923,7 +1996,7 @@ const DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';const DESTINATION
|
|
|
1923
1996
|
* @returns Mutated event with final integrations config
|
|
1924
1997
|
*/const getFinalEvent=(event,state)=>{const finalEvent=clone(event);// Merge the destination specific integrations config with the event's integrations config
|
|
1925
1998
|
// In general, the preference is given to the event's integrations config
|
|
1926
|
-
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';};
|
|
1927
2000
|
|
|
1928
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));}};
|
|
1929
2002
|
|
|
@@ -1938,12 +2011,12 @@ const safelyInvokeCallback=(callback,args,apiName,logger)=>{if(!isDefined(callba
|
|
|
1938
2011
|
*/constructor(pluginsManager,storeManager,httpClient,errorHandler,logger){this.pluginsManager=pluginsManager;this.errorHandler=errorHandler;this.httpClient=httpClient;this.logger=logger;this.storeManager=storeManager;}/**
|
|
1939
2012
|
* Initializes the event repository
|
|
1940
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
|
|
1941
|
-
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
|
|
1942
2015
|
// However, events will be enqueued for now.
|
|
1943
2016
|
// At the time of processing the events, the integrations config data from destinations
|
|
1944
2017
|
// is merged into the event object
|
|
1945
|
-
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
|
|
1946
|
-
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();}}/**
|
|
1947
2020
|
* Enqueues the event for processing
|
|
1948
2021
|
* @param event RudderEvent object
|
|
1949
2022
|
* @param callback API callback function
|
|
@@ -1952,15 +2025,15 @@ const apiName=`${event.type.charAt(0).toUpperCase()}${event.type.slice(1)}${API_
|
|
|
1952
2025
|
|
|
1953
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);
|
|
1954
2027
|
|
|
1955
|
-
|
|
2028
|
+
const _excluded=["context"];/*
|
|
1956
2029
|
* Analytics class with lifecycle based on state ad user triggered events
|
|
1957
2030
|
*/class Analytics{/**
|
|
1958
2031
|
* Initialize services and components or use default ones if singletons
|
|
1959
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);}/**
|
|
1960
2033
|
* Start application lifecycle if not already started
|
|
1961
|
-
*/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
|
|
1962
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
|
|
1963
|
-
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
|
|
1964
2037
|
setExposedGlobal('state',state,writeKey);// Configure initial config of any services or components here
|
|
1965
2038
|
// State application lifecycle
|
|
1966
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
|
|
@@ -1976,15 +2049,15 @@ if(state.consents.preConsent.value.enabled===true){state.lifecycle.status.value=
|
|
|
1976
2049
|
* Process the buffer preloaded events by passing their arguments to the respective facade methods
|
|
1977
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);}/**
|
|
1978
2051
|
* Load configuration
|
|
1979
|
-
*/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();}/**
|
|
1980
2053
|
* Initialize the storage and event queue
|
|
1981
|
-
*/onPluginsReady(){
|
|
1982
|
-
this.storeManager
|
|
1983
|
-
if(state.consents.enabled.value&&!state.consents.initialized.value){this.pluginsManager
|
|
1984
|
-
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
|
|
1985
2058
|
state.lifecycle.status.value='initialized';}/**
|
|
1986
2059
|
* Load plugins
|
|
1987
|
-
*/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?
|
|
1988
2061
|
// registerCustomPlugins(state.loadOptions.value.customPlugins);
|
|
1989
2062
|
}/**
|
|
1990
2063
|
* Trigger onLoaded callback if any is provided in config & emit initialised event
|
|
@@ -2003,12 +2076,12 @@ dispatchSDKEvent('RSA_Ready');}/**
|
|
|
2003
2076
|
*/processBufferedEvents(){// This logic has been intentionally implemented without a simple
|
|
2004
2077
|
// for-loop as the individual events that are processed may
|
|
2005
2078
|
// add more events to the buffer (this is needed for the consent API)
|
|
2006
|
-
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:{};}/**
|
|
2007
2080
|
* Load device mode destinations
|
|
2008
|
-
*/loadDestinations(){
|
|
2081
|
+
*/loadDestinations(){var _this$pluginsManager4,_this$pluginsManager5;// If the integrations load is already triggered or completed, skip the rest of the logic
|
|
2009
2082
|
if(state.lifecycle.status.value==='destinationsLoading'||state.nativeDestinations.clientDestinationsReady.value===true){return;}// Set in state the desired activeDestinations to inject in DOM
|
|
2010
|
-
this.pluginsManager
|
|
2011
|
-
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
|
|
2012
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;});}});}/**
|
|
2013
2086
|
* Move to the ready state
|
|
2014
2087
|
*/// eslint-disable-next-line class-methods-use-this
|
|
@@ -2020,31 +2093,31 @@ ready(callback,isBufferedInvocation=false){const type='ready';if(!state.lifecycl
|
|
|
2020
2093
|
* If destinations are loaded or no integration is available for loading
|
|
2021
2094
|
* execute the callback immediately else push the callbacks to a queue that
|
|
2022
2095
|
* will be executed after loading completes
|
|
2023
|
-
*/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.
|
|
2024
2097
|
// Send automatic ad blocked page event if ad-blockers are detected on the page
|
|
2025
2098
|
// Check page category to avoid infinite loop
|
|
2026
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
|
|
2027
2100
|
// in v3 implementation
|
|
2028
|
-
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
|
|
2029
|
-
if(!isNull(payload.userId)){this.userSessionManager
|
|
2030
|
-
if(!isNull(payload.groupId)){this.userSessionManager
|
|
2031
|
-
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
|
|
2032
2105
|
getUserId(){return state.session.userId.value;}// eslint-disable-next-line class-methods-use-this
|
|
2033
2106
|
getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
|
|
2034
2107
|
getGroupId(){return state.session.groupId.value;}// eslint-disable-next-line class-methods-use-this
|
|
2035
|
-
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
|
|
2036
|
-
getSessionId(){const sessionId=this.userSessionManager
|
|
2037
|
-
if(state.consents.enabled.value&&!state.consents.initialized.value){this.pluginsManager
|
|
2038
|
-
this.storeManager
|
|
2039
|
-
this.userSessionManager
|
|
2040
|
-
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
|
|
2041
2114
|
// events buffer array so that any other preload events (mainly from query string API) will be processed first.
|
|
2042
|
-
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);}/**
|
|
2043
2116
|
* Add a custom integration for a custom destination.
|
|
2044
2117
|
* @param destinationId - The ID of the custom destination from the RudderStack dashboard.
|
|
2045
2118
|
* @param integration - The custom integration object.
|
|
2046
2119
|
* @param isBufferedInvocation - Whether the invocation is buffered.
|
|
2047
|
-
*/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
|
|
2048
2121
|
}
|
|
2049
2122
|
|
|
2050
2123
|
/*
|
|
@@ -2052,11 +2125,9 @@ if(state.consents.postConsent.value.trackConsent){const trackOptions=trackArgume
|
|
|
2052
2125
|
* expose overloaded methods
|
|
2053
2126
|
* handle multiple Analytics instances
|
|
2054
2127
|
* consume SDK preload event buffer
|
|
2055
|
-
*/class RudderAnalytics{//
|
|
2056
|
-
//
|
|
2057
|
-
|
|
2058
|
-
analyticsInstances={};defaultAnalyticsKey='';logger=defaultLogger;// Singleton with constructor bind methods
|
|
2059
|
-
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
|
|
2060
2131
|
// eslint-disable-next-line no-constructor-return
|
|
2061
2132
|
return RudderAnalytics.globalSingleton;// END-NO-SONAR-SCAN
|
|
2062
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
|
|
@@ -2084,15 +2155,15 @@ if(isString(writeKey)&&writeKey){this.defaultAnalyticsKey=writeKey;}}/**
|
|
|
2084
2155
|
* @param dataPlaneUrl Data plane URL
|
|
2085
2156
|
* @param loadOptions Additional options for loading the SDK
|
|
2086
2157
|
* @returns none
|
|
2087
|
-
*/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
|
|
2088
2159
|
this.trackPageLifecycleEvents(loadOptions);// Get the preloaded events array from global buffer instead of window.rudderanalytics
|
|
2089
2160
|
// as the constructor must have already pushed the events to the global buffer
|
|
2090
2161
|
const preloadedEventsArray=getExposedGlobal(GLOBAL_PRELOAD_BUFFER);// The array will be mutated in the below method
|
|
2091
|
-
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);}}/**
|
|
2092
2163
|
* A function to track page lifecycle events like page loaded and page unloaded
|
|
2093
2164
|
* @param loadOptions
|
|
2094
2165
|
* @returns
|
|
2095
|
-
*/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
|
|
2096
2167
|
// if at least one of the autoTrack options is enabled
|
|
2097
2168
|
// IMPORTANT: make sure this is done at the end as it depends on the above states
|
|
2098
2169
|
state.autoTrack.enabled.value=autoTrackEnabled||pageLifecycleEnabled;if(!pageLifecycleEnabled){return;}this.setupPageUnloadTracking(events,useBeacon,options);}/**
|
|
@@ -2100,7 +2171,7 @@ state.autoTrack.enabled.value=autoTrackEnabled||pageLifecycleEnabled;if(!pageLif
|
|
|
2100
2171
|
* @param events
|
|
2101
2172
|
* @param useBeacon
|
|
2102
2173
|
* @param options
|
|
2103
|
-
*/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
|
|
2104
2175
|
this.logger.warn(PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(RSA));}}}/**
|
|
2105
2176
|
* Trigger load event in buffer queue if exists and stores the
|
|
2106
2177
|
* remaining preloaded events array in global object
|
|
@@ -2114,22 +2185,22 @@ loadEvent.shift();// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
|
2114
2185
|
// @ts-ignore
|
|
2115
2186
|
this.load.apply(null,loadEvent);}}/**
|
|
2116
2187
|
* Get ready callback arguments and forward to ready call
|
|
2117
|
-
*/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);}}/**
|
|
2118
2189
|
* Process page arguments and forward to page call
|
|
2119
2190
|
*/// These overloads should be same as AnalyticsPageMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
|
2120
|
-
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);}}/**
|
|
2121
2192
|
* Process track arguments and forward to page call
|
|
2122
2193
|
*/// These overloads should be same as AnalyticsTrackMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
|
2123
|
-
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);}}/**
|
|
2124
2195
|
* Process identify arguments and forward to page call
|
|
2125
2196
|
*/// These overloads should be same as AnalyticsIdentifyMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
|
2126
|
-
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);}}/**
|
|
2127
2198
|
* Process alias arguments and forward to page call
|
|
2128
2199
|
*/// These overloads should be same as AnalyticsAliasMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
|
2129
|
-
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);}}/**
|
|
2130
2201
|
* Process group arguments and forward to page call
|
|
2131
2202
|
*/// These overloads should be same as AnalyticsGroupMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
|
|
2132
|
-
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);}}/**
|
|
2133
2204
|
* Reset the analytics instance
|
|
2134
2205
|
* @param options Reset options. Except for anonymousId, initialReferrer, and initialReferringDomain
|
|
2135
2206
|
* all other values will be reset by default.
|
|
@@ -2156,6 +2227,8 @@ group(groupId,traits,options,callback){try{this.getAnalyticsInstance()?.group(gr
|
|
|
2156
2227
|
* @param resetAnonymousId Reset anonymous ID
|
|
2157
2228
|
* @returns none
|
|
2158
2229
|
* @deprecated Use reset(options) instead
|
|
2159
|
-
*/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);
|
|
2160
2233
|
|
|
2161
2234
|
exports.RudderAnalytics = RudderAnalytics;
|