@rudderstack/analytics-js 3.0.0-beta.6 → 3.0.0-beta.9
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 +24 -3
- package/dist/npm/index.d.ts +1229 -0
- package/{legacy → dist/npm/legacy}/cjs/index.js +371 -509
- package/{legacy → dist/npm/legacy}/esm/index.js +371 -509
- package/{legacy → dist/npm/legacy}/umd/index.js +371 -509
- package/{modern → dist/npm/modern}/cjs/index.js +166 -290
- package/{modern → dist/npm/modern}/esm/index.js +166 -290
- package/{modern → dist/npm/modern}/umd/index.js +166 -290
- package/package.json +28 -107
- package/index.d.ts +0 -387
@@ -2,21 +2,24 @@ let UaChTrackLevel=/*#__PURE__*/function(UaChTrackLevel){UaChTrackLevel["None"]=
|
|
2
2
|
* Represents the options parameter for anonymousId
|
3
3
|
*/ /**
|
4
4
|
* Represents the beacon queue options parameter in loadOptions type
|
5
|
-
*/
|
5
|
+
*/ /**
|
6
6
|
* Represents the queue options parameter in loadOptions type
|
7
7
|
*/ /**
|
8
8
|
* Represents the destinations queue options parameter in loadOptions type
|
9
|
-
*/
|
9
|
+
*/let DeliveryType=/*#__PURE__*/function(DeliveryType){DeliveryType["Immediate"]="immediate";DeliveryType["Buffer"]="buffer";return DeliveryType;}({});let StorageStrategy=/*#__PURE__*/function(StorageStrategy){StorageStrategy["None"]="none";StorageStrategy["Session"]="session";StorageStrategy["AnonymousId"]="anonymousId";return StorageStrategy;}({});/**
|
10
10
|
* Represents the options parameter in the load API
|
11
11
|
*/
|
12
12
|
|
13
|
+
let StorageEncryptionVersion=/*#__PURE__*/function(StorageEncryptionVersion){StorageEncryptionVersion["Legacy"]="legacy";StorageEncryptionVersion["V3"]="v3";return StorageEncryptionVersion;}({});// default
|
14
|
+
const SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','sessionStorage','none'];const DEFAULT_STORAGE_TYPE='cookieStorage';let CookieSameSite=/*#__PURE__*/function(CookieSameSite){CookieSameSite["Strict"]="Strict";CookieSameSite["Lax"]="Lax";CookieSameSite["None"]="None";return CookieSameSite;}({});
|
15
|
+
|
13
16
|
/**
|
14
17
|
* Represents residency server input the options
|
15
18
|
*/let ResidencyServerRegion=/*#__PURE__*/function(ResidencyServerRegion){ResidencyServerRegion["US"]="US";ResidencyServerRegion["EU"]="EU";return ResidencyServerRegion;}({});
|
16
19
|
|
17
20
|
let LogLevel=/*#__PURE__*/function(LogLevel){LogLevel["Log"]="LOG";LogLevel["Info"]="INFO";LogLevel["Debug"]="DEBUG";LogLevel["Warn"]="WARN";LogLevel["Error"]="ERROR";LogLevel["None"]="NONE";return LogLevel;}({});
|
18
21
|
|
19
|
-
let PluginName=/*#__PURE__*/function(PluginName){PluginName["BeaconQueue"]="BeaconQueue";PluginName["DeviceModeDestinations"]="DeviceModeDestinations";PluginName["DeviceModeTransformation"]="DeviceModeTransformation";PluginName["ErrorReporting"]="ErrorReporting";PluginName["ExternalAnonymousId"]="ExternalAnonymousId";PluginName["GoogleLinker"]="GoogleLinker";PluginName["
|
22
|
+
let PluginName=/*#__PURE__*/function(PluginName){PluginName["BeaconQueue"]="BeaconQueue";PluginName["Bugsnag"]="Bugsnag";PluginName["DeviceModeDestinations"]="DeviceModeDestinations";PluginName["DeviceModeTransformation"]="DeviceModeTransformation";PluginName["ErrorReporting"]="ErrorReporting";PluginName["ExternalAnonymousId"]="ExternalAnonymousId";PluginName["GoogleLinker"]="GoogleLinker";PluginName["KetchConsentManager"]="KetchConsentManager";PluginName["NativeDestinationQueue"]="NativeDestinationQueue";PluginName["OneTrustConsentManager"]="OneTrustConsentManager";PluginName["StorageEncryption"]="StorageEncryption";PluginName["StorageEncryptionLegacy"]="StorageEncryptionLegacy";PluginName["StorageMigrator"]="StorageMigrator";PluginName["XhrQueue"]="XhrQueue";return PluginName;}({});
|
20
23
|
|
21
24
|
function _isPlaceholder(a){return a!=null&&typeof a==='object'&&a['@@functional/placeholder']===true;}
|
22
25
|
|
@@ -47,57 +50,8 @@ function _isPlaceholder(a){return a!=null&&typeof a==='object'&&a['@@functional/
|
|
47
50
|
* @return {Function} The curried function.
|
48
51
|
*/function _curry3(fn){return function f3(a,b,c){switch(arguments.length){case 0:return f3;case 1:return _isPlaceholder(a)?f3:_curry2(function(_b,_c){return fn(a,_b,_c);});case 2:return _isPlaceholder(a)&&_isPlaceholder(b)?f3:_isPlaceholder(a)?_curry2(function(_a,_c){return fn(_a,b,_c);}):_isPlaceholder(b)?_curry2(function(_b,_c){return fn(a,_b,_c);}):_curry1(function(_c){return fn(a,b,_c);});default:return _isPlaceholder(a)&&_isPlaceholder(b)&&_isPlaceholder(c)?f3:_isPlaceholder(a)&&_isPlaceholder(b)?_curry2(function(_a,_b){return fn(_a,_b,c);}):_isPlaceholder(a)&&_isPlaceholder(c)?_curry2(function(_a,_c){return fn(_a,b,_c);}):_isPlaceholder(b)&&_isPlaceholder(c)?_curry2(function(_b,_c){return fn(a,_b,_c);}):_isPlaceholder(a)?_curry1(function(_a){return fn(_a,b,c);}):_isPlaceholder(b)?_curry1(function(_b){return fn(a,_b,c);}):_isPlaceholder(c)?_curry1(function(_c){return fn(a,b,_c);}):fn(a,b,c);}};}
|
49
52
|
|
50
|
-
/**
|
51
|
-
* Tests whether or not an object is an array.
|
52
|
-
*
|
53
|
-
* @private
|
54
|
-
* @param {*} val The object to test.
|
55
|
-
* @return {Boolean} `true` if `val` is an array, `false` otherwise.
|
56
|
-
* @example
|
57
|
-
*
|
58
|
-
* _isArray([]); //=> true
|
59
|
-
* _isArray(null); //=> false
|
60
|
-
* _isArray({}); //=> false
|
61
|
-
*/const _isArray = Array.isArray||function _isArray(val){return val!=null&&val.length>=0&&Object.prototype.toString.call(val)==='[object Array]';};
|
62
|
-
|
63
|
-
function _arrayFromIterator(iter){var list=[];var next;while(!(next=iter.next()).done){list.push(next.value);}return list;}
|
64
|
-
|
65
|
-
function _includesWith(pred,x,list){var idx=0;var len=list.length;while(idx<len){if(pred(x,list[idx])){return true;}idx+=1;}return false;}
|
66
|
-
|
67
|
-
function _functionName(f){// String(x => x) evaluates to "x => x", so the pattern may not match.
|
68
|
-
var match=String(f).match(/^function (\w*)/);return match==null?'':match[1];}
|
69
|
-
|
70
53
|
function _has(prop,obj){return Object.prototype.hasOwnProperty.call(obj,prop);}
|
71
54
|
|
72
|
-
// Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
|
73
|
-
function _objectIs(a,b){// SameValue algorithm
|
74
|
-
if(a===b){// Steps 1-5, 7-10
|
75
|
-
// Steps 6.b-6.e: +0 != -0
|
76
|
-
return a!==0||1/a===1/b;}else {// Step 6.a: NaN == NaN
|
77
|
-
return a!==a&&b!==b;}}const _objectIs$1 = typeof Object.is==='function'?Object.is:_objectIs;
|
78
|
-
|
79
|
-
var toString=Object.prototype.toString;var _isArguments=/*#__PURE__*/function(){return toString.call(arguments)==='[object Arguments]'?function _isArguments(x){return toString.call(x)==='[object Arguments]';}:function _isArguments(x){return _has('callee',x);};}();
|
80
|
-
|
81
|
-
var hasEnumBug=!/*#__PURE__*/{toString:null}.propertyIsEnumerable('toString');var nonEnumerableProps=['constructor','valueOf','isPrototypeOf','toString','propertyIsEnumerable','hasOwnProperty','toLocaleString'];// Safari bug
|
82
|
-
var hasArgsEnumBug=/*#__PURE__*/function(){return arguments.propertyIsEnumerable('length');}();var contains=function contains(list,item){var idx=0;while(idx<list.length){if(list[idx]===item){return true;}idx+=1;}return false;};/**
|
83
|
-
* Returns a list containing the names of all the enumerable own properties of
|
84
|
-
* the supplied object.
|
85
|
-
* Note that the order of the output array is not guaranteed to be consistent
|
86
|
-
* across different JS platforms.
|
87
|
-
*
|
88
|
-
* @func
|
89
|
-
* @memberOf R
|
90
|
-
* @since v0.1.0
|
91
|
-
* @category Object
|
92
|
-
* @sig {k: v} -> [k]
|
93
|
-
* @param {Object} obj The object to extract properties from
|
94
|
-
* @return {Array} An array of the object's own properties.
|
95
|
-
* @see R.keysIn, R.values, R.toPairs
|
96
|
-
* @example
|
97
|
-
*
|
98
|
-
* R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c']
|
99
|
-
*/var keys=typeof Object.keys==='function'&&!hasArgsEnumBug?/*#__PURE__*/_curry1(function keys(obj){return Object(obj)!==obj?[]:Object.keys(obj);}):/*#__PURE__*/_curry1(function keys(obj){if(Object(obj)!==obj){return [];}var prop,nIdx;var ks=[];var checkArgsLength=hasArgsEnumBug&&_isArguments(obj);for(prop in obj){if(_has(prop,obj)&&(!checkArgsLength||prop!=='length')){ks[ks.length]=prop;}}if(hasEnumBug){nIdx=nonEnumerableProps.length-1;while(nIdx>=0){prop=nonEnumerableProps[nIdx];if(_has(prop,obj)&&!contains(ks,prop)){ks[ks.length]=prop;}nIdx-=1;}}return ks;});
|
100
|
-
|
101
55
|
/**
|
102
56
|
* Gives a single-word string description of the (native) type of a value,
|
103
57
|
* returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not
|
@@ -124,45 +78,6 @@ var hasArgsEnumBug=/*#__PURE__*/function(){return arguments.propertyIsEnumerable
|
|
124
78
|
* R.type(undefined); //=> "Undefined"
|
125
79
|
*/var type=/*#__PURE__*/_curry1(function type(val){return val===null?'Null':val===undefined?'Undefined':Object.prototype.toString.call(val).slice(8,-1);});
|
126
80
|
|
127
|
-
/**
|
128
|
-
* private _uniqContentEquals function.
|
129
|
-
* That function is checking equality of 2 iterator contents with 2 assumptions
|
130
|
-
* - iterators lengths are the same
|
131
|
-
* - iterators values are unique
|
132
|
-
*
|
133
|
-
* false-positive result will be returned for comparison of, e.g.
|
134
|
-
* - [1,2,3] and [1,2,3,4]
|
135
|
-
* - [1,1,1] and [1,2,3]
|
136
|
-
* */function _uniqContentEquals(aIterator,bIterator,stackA,stackB){var a=_arrayFromIterator(aIterator);var b=_arrayFromIterator(bIterator);function eq(_a,_b){return _equals(_a,_b,stackA.slice(),stackB.slice());}// if *a* array contains any element that is not included in *b*
|
137
|
-
return !_includesWith(function(b,aItem){return !_includesWith(eq,aItem,b);},b,a);}function _equals(a,b,stackA,stackB){if(_objectIs$1(a,b)){return true;}var typeA=type(a);if(typeA!==type(b)){return false;}if(typeof a['fantasy-land/equals']==='function'||typeof b['fantasy-land/equals']==='function'){return typeof a['fantasy-land/equals']==='function'&&a['fantasy-land/equals'](b)&&typeof b['fantasy-land/equals']==='function'&&b['fantasy-land/equals'](a);}if(typeof a.equals==='function'||typeof b.equals==='function'){return typeof a.equals==='function'&&a.equals(b)&&typeof b.equals==='function'&&b.equals(a);}switch(typeA){case'Arguments':case'Array':case'Object':if(typeof a.constructor==='function'&&_functionName(a.constructor)==='Promise'){return a===b;}break;case'Boolean':case'Number':case'String':if(!(typeof a===typeof b&&_objectIs$1(a.valueOf(),b.valueOf()))){return false;}break;case'Date':if(!_objectIs$1(a.valueOf(),b.valueOf())){return false;}break;case'Error':return a.name===b.name&&a.message===b.message;case'RegExp':if(!(a.source===b.source&&a.global===b.global&&a.ignoreCase===b.ignoreCase&&a.multiline===b.multiline&&a.sticky===b.sticky&&a.unicode===b.unicode)){return false;}break;}var idx=stackA.length-1;while(idx>=0){if(stackA[idx]===a){return stackB[idx]===b;}idx-=1;}switch(typeA){case'Map':if(a.size!==b.size){return false;}return _uniqContentEquals(a.entries(),b.entries(),stackA.concat([a]),stackB.concat([b]));case'Set':if(a.size!==b.size){return false;}return _uniqContentEquals(a.values(),b.values(),stackA.concat([a]),stackB.concat([b]));case'Arguments':case'Array':case'Object':case'Boolean':case'Number':case'String':case'Date':case'Error':case'RegExp':case'Int8Array':case'Uint8Array':case'Uint8ClampedArray':case'Int16Array':case'Uint16Array':case'Int32Array':case'Uint32Array':case'Float32Array':case'Float64Array':case'ArrayBuffer':break;default:// Values of other types are only equal if identical.
|
138
|
-
return false;}var keysA=keys(a);if(keysA.length!==keys(b).length){return false;}var extendedStackA=stackA.concat([a]);var extendedStackB=stackB.concat([b]);idx=keysA.length-1;while(idx>=0){var key=keysA[idx];if(!(_has(key,b)&&_equals(b[key],a[key],extendedStackA,extendedStackB))){return false;}idx-=1;}return true;}
|
139
|
-
|
140
|
-
/**
|
141
|
-
* Returns `true` if its arguments are equivalent, `false` otherwise. Handles
|
142
|
-
* cyclical data structures.
|
143
|
-
*
|
144
|
-
* Dispatches symmetrically to the `equals` methods of both arguments, if
|
145
|
-
* present.
|
146
|
-
*
|
147
|
-
* @func
|
148
|
-
* @memberOf R
|
149
|
-
* @since v0.15.0
|
150
|
-
* @category Relation
|
151
|
-
* @sig a -> b -> Boolean
|
152
|
-
* @param {*} a
|
153
|
-
* @param {*} b
|
154
|
-
* @return {Boolean}
|
155
|
-
* @example
|
156
|
-
*
|
157
|
-
* R.equals(1, 1); //=> true
|
158
|
-
* R.equals(1, '1'); //=> false
|
159
|
-
* R.equals([1, 2, 3], [1, 2, 3]); //=> true
|
160
|
-
*
|
161
|
-
* const a = {}; a.v = a;
|
162
|
-
* const b = {}; b.v = b;
|
163
|
-
* R.equals(a, b); //=> true
|
164
|
-
*/var equals=/*#__PURE__*/_curry2(function equals(a,b){return _equals(a,b,[],[]);});
|
165
|
-
|
166
81
|
function _isObject(x){return Object.prototype.toString.call(x)==='[object Object]';}
|
167
82
|
|
168
83
|
/**
|
@@ -247,71 +162,6 @@ var cachedCopy=map.get(value);if(cachedCopy){return cachedCopy;}map.set(value,co
|
|
247
162
|
* objects[0] === objectsClone[0]; //=> false
|
248
163
|
*/var clone=/*#__PURE__*/_curry1(function clone(value){return value!=null&&typeof value.clone==='function'?value.clone():_clone(value,true);});const clone$1 = clone;
|
249
164
|
|
250
|
-
/**
|
251
|
-
* Tests whether or not an object is a typed array.
|
252
|
-
*
|
253
|
-
* @private
|
254
|
-
* @param {*} val The object to test.
|
255
|
-
* @return {Boolean} `true` if `val` is a typed array, `false` otherwise.
|
256
|
-
* @example
|
257
|
-
*
|
258
|
-
* _isTypedArray(new Uint8Array([])); //=> true
|
259
|
-
* _isTypedArray(new Float32Array([])); //=> true
|
260
|
-
* _isTypedArray([]); //=> false
|
261
|
-
* _isTypedArray(null); //=> false
|
262
|
-
* _isTypedArray({}); //=> false
|
263
|
-
*/function _isTypedArray(val){var type=Object.prototype.toString.call(val);return type==='[object Uint8ClampedArray]'||type==='[object Int8Array]'||type==='[object Uint8Array]'||type==='[object Int16Array]'||type==='[object Uint16Array]'||type==='[object Int32Array]'||type==='[object Uint32Array]'||type==='[object Float32Array]'||type==='[object Float64Array]'||type==='[object BigInt64Array]'||type==='[object BigUint64Array]';}
|
264
|
-
|
265
|
-
/**
|
266
|
-
* Returns the empty value of its argument's type. Ramda defines the empty
|
267
|
-
* value of Array (`[]`), Object (`{}`), String (`''`),
|
268
|
-
* TypedArray (`Uint8Array []`, `Float32Array []`, etc), and Arguments. Other
|
269
|
-
* types are supported if they define `<Type>.empty`,
|
270
|
-
* `<Type>.prototype.empty` or implement the
|
271
|
-
* [FantasyLand Monoid spec](https://github.com/fantasyland/fantasy-land#monoid).
|
272
|
-
*
|
273
|
-
* Dispatches to the `empty` method of the first argument, if present.
|
274
|
-
*
|
275
|
-
* @func
|
276
|
-
* @memberOf R
|
277
|
-
* @since v0.3.0
|
278
|
-
* @category Function
|
279
|
-
* @sig a -> a
|
280
|
-
* @param {*} x
|
281
|
-
* @return {*}
|
282
|
-
* @example
|
283
|
-
*
|
284
|
-
* R.empty(Just(42)); //=> Nothing()
|
285
|
-
* R.empty([1, 2, 3]); //=> []
|
286
|
-
* R.empty('unicorns'); //=> ''
|
287
|
-
* R.empty({x: 1, y: 2}); //=> {}
|
288
|
-
* R.empty(Uint8Array.from('123')); //=> Uint8Array []
|
289
|
-
*/var empty=/*#__PURE__*/_curry1(function empty(x){return x!=null&&typeof x['fantasy-land/empty']==='function'?x['fantasy-land/empty']():x!=null&&x.constructor!=null&&typeof x.constructor['fantasy-land/empty']==='function'?x.constructor['fantasy-land/empty']():x!=null&&typeof x.empty==='function'?x.empty():x!=null&&x.constructor!=null&&typeof x.constructor.empty==='function'?x.constructor.empty():_isArray(x)?[]:_isString(x)?'':_isObject(x)?{}:_isArguments(x)?function(){return arguments;}():_isTypedArray(x)?x.constructor.from(''):void 0// else
|
290
|
-
;});
|
291
|
-
|
292
|
-
/**
|
293
|
-
* Returns `true` if the given value is its type's empty value; `false`
|
294
|
-
* otherwise.
|
295
|
-
*
|
296
|
-
* @func
|
297
|
-
* @memberOf R
|
298
|
-
* @since v0.1.0
|
299
|
-
* @category Logic
|
300
|
-
* @sig a -> Boolean
|
301
|
-
* @param {*} x
|
302
|
-
* @return {Boolean}
|
303
|
-
* @see R.empty
|
304
|
-
* @example
|
305
|
-
*
|
306
|
-
* R.isEmpty([1, 2, 3]); //=> false
|
307
|
-
* R.isEmpty([]); //=> true
|
308
|
-
* R.isEmpty(''); //=> true
|
309
|
-
* R.isEmpty(null); //=> false
|
310
|
-
* R.isEmpty({}); //=> true
|
311
|
-
* R.isEmpty({length: 0}); //=> false
|
312
|
-
* R.isEmpty(Uint8Array.from('')); //=> true
|
313
|
-
*/var isEmpty=/*#__PURE__*/_curry1(function isEmpty(x){return x!=null&&equals(x,empty(x));});const isEmpty$1 = isEmpty;
|
314
|
-
|
315
165
|
/**
|
316
166
|
* Retrieves the values at given paths of an object.
|
317
167
|
*
|
@@ -489,6 +339,10 @@ var cachedCopy=map.get(value);if(cachedCopy){return cachedCopy;}map.set(value,co
|
|
489
339
|
* @param value input value
|
490
340
|
* @returns boolean
|
491
341
|
*/const isDefinedAndNotNull=value=>!isNullOrUndefined(value);/**
|
342
|
+
* A function to check given value is defined and not null
|
343
|
+
* @param value input value
|
344
|
+
* @returns boolean
|
345
|
+
*/const isDefinedNotNullAndNotEmptyString=value=>isDefinedAndNotNull(value)&&value!=='';/**
|
492
346
|
* Determines if the input is an instance of Error
|
493
347
|
* @param obj input value
|
494
348
|
* @returns true if the input is an instance of Error and false otherwise
|
@@ -575,7 +429,7 @@ if(isDefined(payload.groupId)){payload.groupId=tryStringify(payload.groupId);}el
|
|
575
429
|
|
576
430
|
const CAPABILITIES_MANAGER='CapabilitiesManager';const CONFIG_MANAGER='ConfigManager';const EVENT_MANAGER='EventManager';const PLUGINS_MANAGER='PluginsManager';const USER_SESSION_MANAGER='UserSessionManager';const ERROR_HANDLER='ErrorHandler';const PLUGIN_ENGINE='PluginEngine';const STORE_MANAGER='StoreManager';const READY_API='readyApi';const LOAD_CONFIGURATION='LoadConfiguration';const EVENT_REPOSITORY='EventRepository';const EXTERNAL_SRC_LOADER='ExternalSrcLoader';const HTTP_CLIENT='HttpClient';const RS_APP='RudderStackApplication';const ANALYTICS_CORE='AnalyticsCore';
|
577
431
|
|
578
|
-
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.0.0-beta.
|
432
|
+
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.0.0-beta.9';const APP_NAMESPACE='com.rudderlabs.javascript';const MODULE_TYPE='npm';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';
|
579
433
|
|
580
434
|
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';
|
581
435
|
|
@@ -683,7 +537,7 @@ timeoutID=globalThis.setTimeout(()=>{reject(new Error(SCRIPT_LOAD_TIMEOUT_ERROR(
|
|
683
537
|
* Handle errors
|
684
538
|
*/onError(error){if(this.hasErrorHandler){this.errorHandler?.onError(error,EXTERNAL_SRC_LOADER);}else {throw error;}}}
|
685
539
|
|
686
|
-
function i(){throw new Error("Cycle detected");}function t(){if(!(
|
540
|
+
function i(){throw new Error("Cycle detected");}function t(){if(!(f>1)){var i,t=!1;while(void 0!==s){var r=s;s=void 0;v++;while(void 0!==r){var n=r.o;r.o=void 0;r.f&=-3;if(!(8&r.f)&&a(r))try{r.c();}catch(r){if(!t){i=r;t=!0;}}r=n;}}v=0;f--;if(t)throw i;}else f--;}function r(i){if(f>0)return i();f++;try{return i();}finally{t();}}var n=void 0;var s=void 0,f=0,v=0,e=0;function u(i){if(void 0!==n){var t=i.n;if(void 0===t||t.t!==n){t={i:0,S:i,p:n.s,n:void 0,t:n,e:void 0,x:void 0,r:t};if(void 0!==n.s)n.s.n=t;n.s=t;i.n=t;if(32&n.f)i.S(t);return t;}else if(-1===t.i){t.i=0;if(void 0!==t.n){t.n.p=t.p;if(void 0!==t.p)t.p.n=t.n;t.p=n.s;t.n=void 0;n.s.n=t;n.s=t;}return t;}}}function c(i){this.v=i;this.i=0;this.n=void 0;this.t=void 0;}c.prototype.h=function(){return !0;};c.prototype.S=function(i){if(this.t!==i&&void 0===i.e){i.x=this.t;if(void 0!==this.t)this.t.e=i;this.t=i;}};c.prototype.U=function(i){if(void 0!==this.t){var t=i.e,r=i.x;if(void 0!==t){t.x=r;i.e=void 0;}if(void 0!==r){r.e=t;i.x=void 0;}if(i===this.t)this.t=r;}};c.prototype.subscribe=function(i){var t=this;return E(function(){var r=t.value,n=32&this.f;this.f&=-33;try{i(r);}finally{this.f|=n;}});};c.prototype.valueOf=function(){return this.value;};c.prototype.toString=function(){return this.value+"";};c.prototype.toJSON=function(){return this.value;};c.prototype.peek=function(){return this.v;};Object.defineProperty(c.prototype,"value",{get:function(){var i=u(this);if(void 0!==i)i.i=this.i;return this.v;},set:function(r){if(n instanceof y)!function(){throw new Error("Computed cannot have side-effects");}();if(r!==this.v){if(v>100)i();this.v=r;this.i++;e++;f++;try{for(var o=this.t;void 0!==o;o=o.x)o.t.N();}finally{t();}}}});function d(i){return new c(i);}function a(i){for(var t=i.s;void 0!==t;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return !0;return !1;}function l(i){for(var t=i.s;void 0!==t;t=t.n){var r=t.S.n;if(void 0!==r)t.r=r;t.S.n=t;t.i=-1;if(void 0===t.n){i.s=t;break;}}}function w(i){var t=i.s,r=void 0;while(void 0!==t){var n=t.p;if(-1===t.i){t.S.U(t);if(void 0!==n)n.n=t.n;if(void 0!==t.n)t.n.p=n;}else r=t;t.S.n=t.r;if(void 0!==t.r)t.r=void 0;t=n;}i.s=r;}function y(i){c.call(this,void 0);this.x=i;this.s=void 0;this.g=e-1;this.f=4;}(y.prototype=new c()).h=function(){this.f&=-3;if(1&this.f)return !1;if(32==(36&this.f))return !0;this.f&=-5;if(this.g===e)return !0;this.g=e;this.f|=1;if(this.i>0&&!a(this)){this.f&=-2;return !0;}var i=n;try{l(this);n=this;var t=this.x();if(16&this.f||this.v!==t||0===this.i){this.v=t;this.f&=-17;this.i++;}}catch(i){this.v=i;this.f|=16;this.i++;}n=i;w(this);this.f&=-2;return !0;};y.prototype.S=function(i){if(void 0===this.t){this.f|=36;for(var t=this.s;void 0!==t;t=t.n)t.S.S(t);}c.prototype.S.call(this,i);};y.prototype.U=function(i){if(void 0!==this.t){c.prototype.U.call(this,i);if(void 0===this.t){this.f&=-33;for(var t=this.s;void 0!==t;t=t.n)t.S.U(t);}}};y.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var i=this.t;void 0!==i;i=i.x)i.t.N();}};y.prototype.peek=function(){if(!this.h())i();if(16&this.f)throw this.v;return this.v;};Object.defineProperty(y.prototype,"value",{get:function(){if(1&this.f)i();var t=u(this);this.h();if(void 0!==t)t.i=this.i;if(16&this.f)throw this.v;return this.v;}});function p(i){var r=i.u;i.u=void 0;if("function"==typeof r){f++;var o=n;n=void 0;try{r();}catch(t){i.f&=-2;i.f|=8;g(i);throw t;}finally{n=o;t();}}}function g(i){for(var t=i.s;void 0!==t;t=t.n)t.S.U(t);i.x=void 0;i.s=void 0;p(i);}function b(i){if(n!==this)throw new Error("Out-of-order effect");w(this);n=i;this.f&=-2;if(8&this.f)g(this);t();}function x(i){this.x=i;this.u=void 0;this.s=void 0;this.o=void 0;this.f=32;}x.prototype.c=function(){var i=this.S();try{if(8&this.f)return;if(void 0===this.x)return;var t=this.x();if("function"==typeof t)this.u=t;}finally{i();}};x.prototype.S=function(){if(1&this.f)i();this.f|=1;this.f&=-9;p(this);l(this);f++;var t=n;n=this;return b.bind(this,t);};x.prototype.N=function(){if(!(2&this.f)){this.f|=2;this.o=s;s=this;}};x.prototype.d=function(){this.f|=8;if(!(1&this.f))g(this);};function E(i){var t=new x(i);try{t.c();}catch(i){t.d();throw i;}return t.d.bind(t);}
|
687
541
|
|
688
542
|
let LifecycleStatus=/*#__PURE__*/function(LifecycleStatus){LifecycleStatus["Mounted"]="mounted";LifecycleStatus["BrowserCapabilitiesReady"]="browserCapabilitiesReady";LifecycleStatus["Configured"]="configured";LifecycleStatus["PluginsLoading"]="pluginsLoading";LifecycleStatus["PluginsReady"]="pluginsReady";LifecycleStatus["Initialized"]="initialized";LifecycleStatus["Loaded"]="loaded";LifecycleStatus["DestinationsLoading"]="destinationsLoading";LifecycleStatus["DestinationsReady"]="destinationsReady";LifecycleStatus["Ready"]="ready";return LifecycleStatus;}({});
|
689
543
|
|
@@ -709,45 +563,46 @@ LOG_MSG_STYLE// reset the style for the actual message
|
|
709
563
|
if(!isString(data[0])){styledLogArgs.push(data[0]);}// append rest of the original arguments
|
710
564
|
styledLogArgs.push(...data.slice(1));return styledLogArgs;}return data;}}const defaultLogger=new Logger();
|
711
565
|
|
712
|
-
let StorageEncryptionVersion=/*#__PURE__*/function(StorageEncryptionVersion){StorageEncryptionVersion["Legacy"]="legacy";StorageEncryptionVersion["V3"]="v3";return StorageEncryptionVersion;}({});// default
|
713
|
-
const SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','sessionStorage','none'];const DEFAULT_STORAGE_TYPE='cookieStorage';
|
714
|
-
|
715
566
|
const SOURCE_CONFIG_OPTION_ERROR=`"getSourceConfig" must be a function. Please make sure that it is defined and returns a valid source configuration object.`;const INTG_CDN_BASE_URL_ERROR=`Failed to load the SDK as the CDN base URL for integrations is not valid.`;const PLUGINS_CDN_BASE_URL_ERROR=`Failed to load the SDK as the CDN base URL for plugins is not valid.`;const DATA_PLANE_URL_ERROR=`Failed to load the SDK as the data plane URL could not be determined. Please check that the data plane URL is set correctly and try again.`;const XHR_PAYLOAD_PREP_ERROR=`Failed to prepare data for the request.`;const EVENT_OBJECT_GENERATION_ERROR=`Failed to generate the event object.`;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.`;// ERROR
|
716
567
|
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 REPORTING_PLUGIN_INIT_FAILURE_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}Failed to initialize the error reporting plugin.`;const NOTIFY_FAILURE_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}Failed to notify 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 STORAGE_UNAVAILABILITY_ERROR_PREFIX=(context,storageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The "${storageType}" storage type is `;const SOURCE_CONFIG_FETCH_ERROR=reason=>`Failed to fetch the source config. Reason: ${reason}`;const WRITE_KEY_VALIDATION_ERROR=writeKey=>`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=dataPlaneUrl=>`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 READY_API_CALLBACK_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}The callback is not a function.`;const XHR_DELIVERY_ERROR=(prefix,status,statusText,url)=>`${prefix} with status: ${status}, ${statusText} for URL: ${url}.`;const XHR_REQUEST_ERROR=(prefix,e,url)=>`${prefix} due to timeout or no connection (${e?e.type:''}) 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`;// WARNING
|
717
|
-
const STORAGE_TYPE_VALIDATION_WARNING=(context,storageType,defaultStorageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage type "${storageType}" is not supported. Please choose one of the following supported
|
568
|
+
const STORAGE_TYPE_VALIDATION_WARNING=(context,storageType,defaultStorageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage type "${storageType}" is not supported. Please choose one of the following supported types: "${SUPPORTED_STORAGE_TYPES}". The default type "${defaultStorageType}" will be used instead.`;const UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING=(context,selectedErrorReportingProvider,errorReportingProvidersToPluginNameMap,defaultProvider)=>`${context}${LOG_CONTEXT_SEPARATOR}The error reporting provider "${selectedErrorReportingProvider}" is not supported. Please choose one of the following supported providers: "${Object.keys(errorReportingProvidersToPluginNameMap)}". The default provider "${defaultProvider}" 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 UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING=(context,selectedResidencyServerRegion,defaultRegion)=>`${context}${LOG_CONTEXT_SEPARATOR}The residency server region "${selectedResidencyServerRegion}" is not supported. Please choose one of the following supported regions: "${Object.values(ResidencyServerRegion)}". The default region "${defaultRegion}" will be used instead.`;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 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 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 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,selectedStorageType,finalStorageType)=>`${context}${LOG_CONTEXT_SEPARATOR}The storage type "${selectedStorageType}" is not available. The SDK will be initialized with "${finalStorageType}" instead.`;const WRITE_KEY_NOT_A_STRING_ERROR=(context,writeKey)=>`${context}${LOG_CONTEXT_SEPARATOR}The write key "${writeKey}" is not a string. Please check that the write key is correct and try again.`;const EMPTY_GROUP_CALL_ERROR=context=>`${context}${LOG_CONTEXT_SEPARATOR}The group() method must be called with at least one argument.`;const READY_CALLBACK_INVOKE_ERROR=`Failed to invoke the ready callback`;const API_CALLBACK_INVOKE_ERROR=`API Callback Invocation Failed`;const INVALID_CONFIG_URL_WARNING=(context,configUrl)=>`${context}${LOG_CONTEXT_SEPARATOR}The provided config URL "${configUrl}" is invalid. Using the default value instead.`;const POLYFILL_SCRIPT_LOAD_ERROR=(scriptId,url)=>`Failed to load the polyfill script with ID "${scriptId}" from URL ${url}.`;const COOKIE_DATA_ENCODING_ERROR=`Failed to encode the cookie data.`;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: "${Object.values(StorageStrategy)}". The default strategy "${defaultStrategy}" will be used 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: "${Object.values(DeliveryType)}". The default type "${defaultDeliveryType}" will be used instead.`;// DEBUG
|
569
|
+
|
570
|
+
const CDN_INT_DIR='js-integrations';const CDN_PLUGINS_DIR='plugins';
|
718
571
|
|
719
|
-
const BUILD_TYPE='modern';const SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';const CDN_ARCH_VERSION_DIR='v3';const
|
572
|
+
const BUILD_TYPE='modern';const SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';const CDN_ARCH_VERSION_DIR='v3';const DEST_SDK_BASE_URL=`${SDK_CDN_BASE_URL}/beta/3.0.0-beta/${BUILD_TYPE}/${CDN_INT_DIR}`;const PLUGINS_BASE_URL=`${SDK_CDN_BASE_URL}/beta/3.0.0-beta/${BUILD_TYPE}/${CDN_PLUGINS_DIR}`;// TODO: change the above to production URLs when beta phase is done
|
720
573
|
// const DEST_SDK_BASE_URL = `${SDK_CDN_BASE_URL}/latest/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${CDN_INT_DIR}`;
|
721
574
|
// const PLUGINS_BASE_URL = `${SDK_CDN_BASE_URL}/latest/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${CDN_PLUGINS_DIR}`;
|
722
575
|
const DEFAULT_CONFIG_BE_URL='https://api.rudderstack.com';
|
723
576
|
|
724
577
|
const DEFAULT_ERROR_REPORTING_PROVIDER='bugsnag';const DEFAULT_STORAGE_ENCRYPTION_VERSION=StorageEncryptionVersion.V3;const ConsentManagersToPluginNameMap={oneTrust:PluginName.OneTrustConsentManager,ketch:PluginName.KetchConsentManager};const ErrorReportingProvidersToPluginNameMap={[DEFAULT_ERROR_REPORTING_PROVIDER]:PluginName.Bugsnag};const StorageEncryptionVersionsToPluginNameMap={[DEFAULT_STORAGE_ENCRYPTION_VERSION]:PluginName.StorageEncryption,[StorageEncryptionVersion.Legacy]:PluginName.StorageEncryptionLegacy};
|
725
578
|
|
726
|
-
const defaultLoadOptions={logLevel:LogLevel.Error,configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS},sameSiteCookie:CookieSameSite.Lax,polyfillIfRequired:true,integrations:{All:true},useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:false,uaChTrackLevel:UaChTrackLevel.None,plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,dataPlaneEventsBufferTimeout:DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:false},sendAdblockPageOptions:{}};const loadOptionsState=
|
579
|
+
const defaultLoadOptions={logLevel:LogLevel.Error,configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS},sameSiteCookie:CookieSameSite.Lax,polyfillIfRequired:true,integrations:{All:true},useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:false,uaChTrackLevel:UaChTrackLevel.None,plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,dataPlaneEventsBufferTimeout:DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:false},sendAdblockPageOptions:{}};const loadOptionsState=d(clone$1(defaultLoadOptions));
|
727
580
|
|
728
|
-
const
|
581
|
+
const userSessionStorageKeys={userId:'rl_user_id',userTraits:'rl_trait',anonymousId:'rl_anonymous_id',groupId:'rl_group_id',groupTraits:'rl_group_trait',initialReferrer:'rl_page_init_referrer',initialReferringDomain:'rl_page_init_referring_domain',sessionInfo:'rl_session'};const defaultUserSessionValues={userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{}};
|
729
582
|
|
730
|
-
const
|
583
|
+
const defaultSessionInfo={autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS};const sessionState={userId:d(defaultUserSessionValues.userId),userTraits:d(defaultUserSessionValues.userTraits),anonymousId:d(defaultUserSessionValues.anonymousId),groupId:d(defaultUserSessionValues.groupId),groupTraits:d(defaultUserSessionValues.groupTraits),initialReferrer:d(defaultUserSessionValues.initialReferrer),initialReferringDomain:d(defaultUserSessionValues.initialReferringDomain),sessionInfo:d(defaultUserSessionValues.sessionInfo)};
|
731
584
|
|
732
|
-
const
|
585
|
+
const capabilitiesState={isOnline:d(true),storage:{isLocalStorageAvailable:d(false),isCookieStorageAvailable:d(false),isSessionStorageAvailable:d(false)},isBeaconAvailable:d(false),isLegacyDOM:d(false),isUaCHAvailable:d(false),isCryptoAvailable:d(false),isIE11:d(false),isAdBlocked:d(false)};
|
733
586
|
|
734
|
-
const
|
587
|
+
const reportingState={isErrorReportingEnabled:d(false),isMetricsReportingEnabled:d(false),errorReportingProviderPluginName:d(undefined)};
|
735
588
|
|
736
|
-
const
|
589
|
+
const sourceConfigState=d(undefined);
|
737
590
|
|
738
|
-
const
|
591
|
+
const lifecycleState={activeDataplaneUrl:d(undefined),integrationsCDNPath:d(DEST_SDK_BASE_URL),pluginsCDNPath:d(PLUGINS_BASE_URL),sourceConfigUrl:d(undefined),status:d(undefined),initialized:d(false),logLevel:d(LogLevel.Error),loaded:d(false),readyCallbacks:d([]),writeKey:d(undefined),dataPlaneUrl:d(undefined)};
|
739
592
|
|
740
|
-
const
|
593
|
+
const consentsState={data:d({initialized:false}),activeConsentManagerPluginName:d(undefined),preConsentOptions:d({enabled:false})};
|
741
594
|
|
742
|
-
const
|
595
|
+
const metricsState={retries:d(0),dropped:d(0),sent:d(0),queued:d(0),triggered:d(0)};
|
743
596
|
|
744
|
-
const
|
597
|
+
const contextState={app:d({name:APP_NAME,namespace:APP_NAMESPACE,version:APP_VERSION}),traits:d(null),library:d({name:APP_NAME,version:APP_VERSION}),userAgent:d(''),device:d(null),network:d(null),os:d({name:'',version:''}),locale:d(null),screen:d({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),'ua-ch':d(undefined)};
|
745
598
|
|
746
|
-
const
|
599
|
+
const nativeDestinationsState={configuredDestinations:d([]),activeDestinations:d([]),loadOnlyIntegrations:d({}),failedDestinations:d([]),loadIntegration:d(true),initializedDestinations:d([]),clientDestinationsReady:d(false),integrationsConfig:d({})};
|
747
600
|
|
748
|
-
const
|
601
|
+
const eventBufferState={toBeProcessedArray:d([]),readyCallbacksArray:d([])};
|
749
602
|
|
750
|
-
const
|
603
|
+
const pluginsState={ready:d(false),loadedPlugins:d([]),failedPlugins:d([]),pluginsToLoadFromConfig:d([]),activePlugins:d([]),totalPluginsToLoad:d(0)};
|
604
|
+
|
605
|
+
const storageState={encryptionPluginName:d(undefined),migrate:d(false),type:d(undefined),cookie:d(undefined),entries:d({}),trulyAnonymousTracking:d(false)};
|
751
606
|
|
752
607
|
const defaultStateValues={capabilities:capabilitiesState,consents:consentsState,context:contextState,eventBuffer:eventBufferState,lifecycle:lifecycleState,loadOptions:loadOptionsState,metrics:metricsState,nativeDestinations:nativeDestinationsState,plugins:pluginsState,reporting:reportingState,session:sessionState,source:sourceConfigState,storage:storageState};const state={...clone$1(defaultStateValues)};
|
753
608
|
|
@@ -809,7 +664,7 @@ destination.config.useNativeSDK===true);const isHybridModeDestination=destinatio
|
|
809
664
|
*/const remotePluginNames=[PluginName.BeaconQueue,PluginName.DeviceModeTransformation,PluginName.DeviceModeDestinations,PluginName.ErrorReporting,PluginName.ExternalAnonymousId,PluginName.GoogleLinker,PluginName.NativeDestinationQueue,PluginName.StorageEncryption,PluginName.StorageEncryptionLegacy,PluginName.StorageMigrator,PluginName.XhrQueue,PluginName.OneTrustConsentManager,PluginName.KetchConsentManager,PluginName.Bugsnag];
|
810
665
|
|
811
666
|
const remotesMap = {
|
812
|
-
'rudderAnalyticsRemotePlugins':{url:()=>Promise.resolve(window.RudderStackGlobals && window.RudderStackGlobals.app && window.RudderStackGlobals.app.pluginsCDNPath ? "" + window.RudderStackGlobals.app.pluginsCDNPath + "/rsa-plugins.js" : "https://cdn.rudderlabs.com/3.0.0-beta.
|
667
|
+
'rudderAnalyticsRemotePlugins':{url:()=>Promise.resolve(window.RudderStackGlobals && window.RudderStackGlobals.app && window.RudderStackGlobals.app.pluginsCDNPath ? "" + window.RudderStackGlobals.app.pluginsCDNPath + "/rsa-plugins.js" : "https://cdn.rudderlabs.com/3.0.0-beta.9/modern/plugins/rsa-plugins.js"),format:'esm',from:'vite'}
|
813
668
|
};
|
814
669
|
const loadJS = async (url, fn) => {
|
815
670
|
const resolvedUrl = typeof url === 'function' ? await url() : url;
|
@@ -881,7 +736,7 @@ const remotesMap = {
|
|
881
736
|
|
882
737
|
/**
|
883
738
|
* Get the lazy loaded dynamic import for a plugin name
|
884
|
-
*/const getFederatedModuleImport=pluginName=>{switch(pluginName){case PluginName.BeaconQueue:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./BeaconQueue").then(module=>__federation_method_wrapDefault(module, true));case PluginName.
|
739
|
+
*/const getFederatedModuleImport=pluginName=>{switch(pluginName){case PluginName.BeaconQueue:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./BeaconQueue").then(module=>__federation_method_wrapDefault(module, true));case PluginName.Bugsnag:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./Bugsnag").then(module=>__federation_method_wrapDefault(module, true));case PluginName.DeviceModeDestinations:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./DeviceModeDestinations").then(module=>__federation_method_wrapDefault(module, true));case PluginName.DeviceModeTransformation:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./DeviceModeTransformation").then(module=>__federation_method_wrapDefault(module, true));case PluginName.ErrorReporting:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./ErrorReporting").then(module=>__federation_method_wrapDefault(module, true));case PluginName.ExternalAnonymousId:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./ExternalAnonymousId").then(module=>__federation_method_wrapDefault(module, true));case PluginName.GoogleLinker:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./GoogleLinker").then(module=>__federation_method_wrapDefault(module, true));case PluginName.KetchConsentManager:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./KetchConsentManager").then(module=>__federation_method_wrapDefault(module, true));case PluginName.NativeDestinationQueue:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./NativeDestinationQueue").then(module=>__federation_method_wrapDefault(module, true));case PluginName.OneTrustConsentManager:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./OneTrustConsentManager").then(module=>__federation_method_wrapDefault(module, true));case PluginName.StorageEncryption:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./StorageEncryption").then(module=>__federation_method_wrapDefault(module, true));case PluginName.StorageEncryptionLegacy:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./StorageEncryptionLegacy").then(module=>__federation_method_wrapDefault(module, true));case PluginName.StorageMigrator:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./StorageMigrator").then(module=>__federation_method_wrapDefault(module, true));case PluginName.XhrQueue:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./XhrQueue").then(module=>__federation_method_wrapDefault(module, true));default:return undefined;}};/**
|
885
740
|
* Map of active plugin names to their dynamic import
|
886
741
|
*/const modernBuildPluginImports=activePluginNames=>{const remotePlugins={};activePluginNames.forEach(pluginName=>{if(remotePluginNames.includes(pluginName)){const lazyLoadImport=getFederatedModuleImport(pluginName);if(lazyLoadImport){remotePlugins[pluginName]=lazyLoadImport;}}});return remotePlugins;};
|
887
742
|
|
@@ -902,7 +757,7 @@ class PluginsManager{constructor(engine,errorHandler,logger){this.engine=engine;
|
|
902
757
|
{setExposedGlobal('pluginsCDNPath',state.lifecycle.pluginsCDNPath.value);}this.setActivePlugins();this.registerLocalPlugins();this.registerRemotePlugins();this.attachEffects();}/**
|
903
758
|
* Update state based on plugin loaded status
|
904
759
|
*/ // eslint-disable-next-line class-methods-use-this
|
905
|
-
attachEffects(){
|
760
|
+
attachEffects(){E(()=>{const isAllPluginsReady=state.plugins.activePlugins.value.length===0||state.plugins.loadedPlugins.value.length+state.plugins.failedPlugins.value.length===state.plugins.totalPluginsToLoad.value;if(isAllPluginsReady){r(()=>{state.plugins.ready.value=true;// TODO: decide what to do if a plugin fails to load for any reason.
|
906
761
|
// Should we stop here or should we progress?
|
907
762
|
state.lifecycle.status.value=LifecycleStatus.PluginsReady;});}});}/**
|
908
763
|
* Determine the list of plugins that should be loaded based on sourceConfig & load options
|
@@ -917,7 +772,7 @@ const supportedStorageEncryptionPlugins=Object.values(StorageEncryptionVersionsT
|
|
917
772
|
if(!state.storage.migrate.value){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(pluginName=>pluginName!==PluginName.StorageMigrator);}return [...Object.keys(getMandatoryPluginsMap()),...pluginsToLoadFromConfig];}/**
|
918
773
|
* Determine the list of plugins that should be activated
|
919
774
|
*/setActivePlugins(){const pluginsToLoad=this.getPluginsToLoadBasedOnConfig();// Merging available mandatory and optional plugin name list
|
920
|
-
const availablePlugins=[...Object.keys(pluginsInventory),...remotePluginNames];const activePlugins=[];const failedPlugins=[];pluginsToLoad.forEach(pluginName=>{if(availablePlugins.includes(pluginName)){activePlugins.push(pluginName);}else {failedPlugins.push(pluginName);}});if(failedPlugins.length>0){this.onError(new Error(`Ignoring loading of unknown plugins: ${failedPlugins.join(',')}. Mandatory plugins: ${Object.keys(getMandatoryPluginsMap()).join(',')}. Load option plugins: ${state.plugins.pluginsToLoadFromConfig.value.join(',')}`));}
|
775
|
+
const availablePlugins=[...Object.keys(pluginsInventory),...remotePluginNames];const activePlugins=[];const failedPlugins=[];pluginsToLoad.forEach(pluginName=>{if(availablePlugins.includes(pluginName)){activePlugins.push(pluginName);}else {failedPlugins.push(pluginName);}});if(failedPlugins.length>0){this.onError(new Error(`Ignoring loading of unknown plugins: ${failedPlugins.join(',')}. Mandatory plugins: ${Object.keys(getMandatoryPluginsMap()).join(',')}. Load option plugins: ${state.plugins.pluginsToLoadFromConfig.value.join(',')}`));}r(()=>{state.plugins.totalPluginsToLoad.value=pluginsToLoad.length;state.plugins.activePlugins.value=activePlugins;state.plugins.failedPlugins.value=failedPlugins;});}/**
|
921
776
|
* Register plugins that are direct imports to PluginEngine
|
922
777
|
*/registerLocalPlugins(){Object.values(pluginsInventory).forEach(localPlugin=>{if(state.plugins.activePlugins.value.includes(localPlugin().name)){this.register([localPlugin()]);}});}/**
|
923
778
|
* Register plugins that are dynamic imports to PluginEngine
|
@@ -965,22 +820,11 @@ xhr.timeout=timeout;Object.keys(options.headers).forEach(headerName=>{if(options
|
|
965
820
|
|
966
821
|
const COOKIE_STORAGE='cookieStorage';const LOCAL_STORAGE='localStorage';const SESSION_STORAGE='sessionStorage';const MEMORY_STORAGE='memoryStorage';const NO_STORAGE='none';
|
967
822
|
|
968
|
-
|
969
|
-
|
970
|
-
/**
|
971
|
-
* To get the current timestamp in ISO string format
|
972
|
-
* @returns ISO formatted timestamp string
|
973
|
-
*/const getCurrentTimeFormatted=()=>{const curDateTime=new Date().toISOString();return curDateTime;};
|
974
|
-
|
975
|
-
function random(len){return crypto.getRandomValues(new Uint8Array(len));}
|
976
|
-
|
977
|
-
var SIZE=4096,HEX$1=[],IDX$1=0,BUFFER$1;for(;IDX$1<256;IDX$1++){HEX$1[IDX$1]=(IDX$1+256).toString(16).substring(1);}function v4$1(){if(!BUFFER$1||IDX$1+16>SIZE){BUFFER$1=random(SIZE);IDX$1=0;}var i=0,tmp,out='';for(;i<16;i++){tmp=BUFFER$1[IDX$1+i];if(i==6)out+=HEX$1[tmp&15|64];else if(i==8)out+=HEX$1[tmp&63|128];else out+=HEX$1[tmp];if(i&1&&i>1&&i<11)out+='-';}IDX$1+=16;return out;}
|
978
|
-
|
979
|
-
var IDX=256,HEX=[],BUFFER;while(IDX--)HEX[IDX]=(IDX+256).toString(16).substring(1);function v4(){var i=0,num,out='';if(!BUFFER||IDX+16>256){BUFFER=Array(i=256);while(i--)BUFFER[i]=256*Math.random()|0;i=IDX=0;}for(;i<16;i++){num=BUFFER[IDX+i];if(i==6)out+=HEX[num&15|64];else if(i==8)out+=HEX[num&63|128];else out+=HEX[num];if(i&1&&i>1&&i<11)out+='-';}IDX++;return out;}
|
823
|
+
let UserSessionKeys=/*#__PURE__*/function(UserSessionKeys){UserSessionKeys["userId"]="userId";UserSessionKeys["userTraits"]="userTraits";UserSessionKeys["anonymousId"]="anonymousId";UserSessionKeys["groupId"]="groupId";UserSessionKeys["groupTraits"]="groupTraits";UserSessionKeys["initialReferrer"]="initialReferrer";UserSessionKeys["initialReferringDomain"]="initialReferringDomain";UserSessionKeys["sessionInfo"]="sessionInfo";return UserSessionKeys;}({});
|
980
824
|
|
981
|
-
const
|
825
|
+
const STORAGE_TEST_COOKIE='test_rudder_cookie';const STORAGE_TEST_LOCAL_STORAGE='test_rudder_ls';const STORAGE_TEST_SESSION_STORAGE='test_rudder_ss';const STORAGE_TEST_TOP_LEVEL_DOMAIN='__tld__';const CLIENT_DATA_STORE_COOKIE='clientDataInCookie';const CLIENT_DATA_STORE_LS='clientDataInLocalStorage';const CLIENT_DATA_STORE_MEMORY='clientDataInMemory';
|
982
826
|
|
983
|
-
const
|
827
|
+
const storageClientDataStoreNameMap={[COOKIE_STORAGE]:CLIENT_DATA_STORE_COOKIE,[LOCAL_STORAGE]:CLIENT_DATA_STORE_LS,[MEMORY_STORAGE]:CLIENT_DATA_STORE_MEMORY};
|
984
828
|
|
985
829
|
const detectAdBlockers=(errorHandler,logger)=>{// Apparently, '?view=ad' is a query param that is blocked by majority of adblockers
|
986
830
|
// Use source config URL here as it is very unlikely to be blocked by adblockers
|
@@ -992,7 +836,7 @@ method:'HEAD',headers:{'Content-Type':undefined}},isRawResponse:true,callback:(r
|
|
992
836
|
// Often adblockers instead of blocking the request, they redirect it to an internal URL
|
993
837
|
state.capabilities.isAdBlocked.value=details?.error!==undefined||details?.xhr?.responseURL!==url;}});};
|
994
838
|
|
995
|
-
const hasCrypto=()=>!isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);const hasUAClientHints=()=>!isNullOrUndefined(globalThis.navigator.userAgentData);const hasBeacon=()=>!isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);const isIE11=()=>Boolean(globalThis.navigator.userAgent.match(/Trident.*rv:11\./));
|
839
|
+
const hasCrypto$1=()=>!isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);const hasUAClientHints=()=>!isNullOrUndefined(globalThis.navigator.userAgentData);const hasBeacon=()=>!isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);const isIE11=()=>Boolean(globalThis.navigator.userAgent.match(/Trident.*rv:11\./));
|
996
840
|
|
997
841
|
const getUserAgentClientHint=(callback,level='none')=>{if(level==='none'){callback(undefined);}if(level==='default'){callback(navigator.userAgentData);}if(level==='full'){navigator.userAgentData?.getHighEntropyValues(['architecture','bitness','brands','mobile','model','platform','platformVersion','uaFullVersion','fullVersionList','wow64']).then(ua=>{callback(ua);}).catch(()=>{callback();});}};
|
998
842
|
|
@@ -1080,7 +924,8 @@ var store$1 = {exports: {}};
|
|
1080
924
|
// Error: QuotaExceededError
|
1081
925
|
function dealIncognito(storage){var _KEY='_Is_Incognit',_VALUE='yes';try{// NOTE: set default storage when not passed in
|
1082
926
|
if(!storage){storage=window.localStorage;}storage.setItem(_KEY,_VALUE);storage.removeItem(_KEY);}catch(e){var inMemoryStorage={};inMemoryStorage._data={};inMemoryStorage.setItem=function(id,val){return inMemoryStorage._data[id]=String(val);};inMemoryStorage.getItem=function(id){return inMemoryStorage._data.hasOwnProperty(id)?inMemoryStorage._data[id]:undefined;};inMemoryStorage.removeItem=function(id){return delete inMemoryStorage._data[id];};inMemoryStorage.clear=function(){return inMemoryStorage._data={};};storage=inMemoryStorage;}finally{if(storage.getItem(_KEY)===_VALUE)storage.removeItem(_KEY);}return storage;}// deal QuotaExceededError if user use incognito mode in browser
|
1083
|
-
var storage=dealIncognito();function Store(){if(!(this instanceof Store)){return new Store();}}Store.prototype={set:function set(key,val){if(key&&!isJSON(key)){storage.setItem(key,stringify(val));}else if(isJSON(key)){for(var a in key)this.set(a,key[a]);}return this;},get:function get(key){
|
927
|
+
var storage=dealIncognito();function Store(){if(!(this instanceof Store)){return new Store();}}Store.prototype={set:function set(key,val){if(key&&!isJSON(key)){storage.setItem(key,stringify(val));}else if(isJSON(key)){for(var a in key)this.set(a,key[a]);}return this;},get:function get(key){// Return all entries if no key
|
928
|
+
if(key===undefined){var ret={};this.forEach(function(key,val){return ret[key]=val;});return ret;}if(key.charAt(0)==='?'){return this.has(key.substr(1));}var args=arguments;if(args.length>1){var dt={};for(var i=0,len=args.length;i<len;i++){var value=deserialize(storage.getItem(args[i]));if(this.has(args[i])){dt[args[i]]=value;}}return dt;}return deserialize(storage.getItem(key));},clear:function clear(){storage.clear();return this;},remove:function remove(key){var val=this.get(key);storage.removeItem(key);return val;},has:function has(key){return {}.hasOwnProperty.call(this.get(),key);},keys:function keys(){var d=[];this.forEach(function(k){d.push(k);});return d;},forEach:function forEach(callback){for(var i=0,len=storage.length;i<len;i++){var key=storage.key(i);callback(key,this.get(key));}return this;},search:function search(str){var arr=this.keys(),dt={};for(var i=0,len=arr.length;i<len;i++){if(arr[i].indexOf(str)>-1)dt[arr[i]]=this.get(arr[i]);}return dt;}};var _Store=null;function store(key,data){var argm=arguments;var dt=null;if(!_Store)_Store=Store();if(argm.length===0)return _Store.get();if(argm.length===1){if(typeof key==="string")return _Store.get(key);if(isJSON(key))return _Store.set(key);}if(argm.length===2&&typeof key==="string"){if(!data)return _Store.remove(key);if(data&&typeof data==="string")return _Store.set(key,data);if(data&&isFunction(data)){dt=null;dt=data(key,_Store.get(key));store.set(key,dt);}}if(argm.length===2&&isArray(key)&&isFunction(data)){for(var i=0,len=key.length;i<len;i++){dt=data(key[i],_Store.get(key[i]));store.set(key[i],dt);}}return store;}for(var a in Store.prototype)store[a]=Store.prototype[a];return store;});})(store$1);var storeExports=store$1.exports;const store = /*@__PURE__*/getDefaultExportFromCjs(storeExports);
|
1084
929
|
|
1085
930
|
// check if the get, set overloads and search methods are used at all
|
1086
931
|
// if we do, ensure we provide types to support overloads as per storejs docs
|
@@ -1141,12 +986,14 @@ return JSON.parse(str);}catch(err){this.onError(new Error(`${STORE_DATA_FETCH_ER
|
|
1141
986
|
* A service to manage stores & available storage client configurations
|
1142
987
|
*/class StoreManager{stores={};isInitialized=false;hasErrorHandler=false;constructor(pluginsManager,errorHandler,logger){this.errorHandler=errorHandler;this.logger=logger;this.hasErrorHandler=Boolean(this.errorHandler);this.pluginsManager=pluginsManager;this.onError=this.onError.bind(this);}/**
|
1143
988
|
* Configure available storage client instances
|
1144
|
-
*/init(){if(this.isInitialized){return;}const config={cookieOptions:{samesite:state.loadOptions.value.sameSiteCookie,secure:state.loadOptions.value.secureCookie,domain:state.loadOptions.value.setCookieDomain,enabled:true},localStorageOptions:{enabled:true},inMemoryStorageOptions:{enabled:true}};configureStorageEngines(removeUndefinedValues(config.cookieOptions),removeUndefinedValues(config.localStorageOptions),removeUndefinedValues(config.inMemoryStorageOptions));this.initClientDataStore();this.isInitialized=true;}/**
|
989
|
+
*/init(){if(this.isInitialized){return;}const config={cookieOptions:{samesite:state.loadOptions.value.sameSiteCookie,secure:state.loadOptions.value.secureCookie,domain:state.loadOptions.value.setCookieDomain,enabled:true},localStorageOptions:{enabled:true},inMemoryStorageOptions:{enabled:true}};configureStorageEngines(removeUndefinedValues(mergeDeepRight(config.cookieOptions||{},state.storage.cookie?.value||{})),removeUndefinedValues(config.localStorageOptions),removeUndefinedValues(config.inMemoryStorageOptions));this.initClientDataStore();this.isInitialized=true;}/**
|
1145
990
|
* Create store to persist data used by the SDK like session, used details etc
|
1146
|
-
*/initClientDataStore(){const
|
1147
|
-
if(getStorageEngine(COOKIE_STORAGE)?.isEnabled){finalStorageType=COOKIE_STORAGE;}else if(getStorageEngine(LOCAL_STORAGE)?.isEnabled){finalStorageType=LOCAL_STORAGE;}else {finalStorageType=MEMORY_STORAGE;}break;}if(finalStorageType!==storageType){this.logger?.warn(STORAGE_UNAVAILABLE_WARNING(STORE_MANAGER,storageType,finalStorageType));}
|
991
|
+
*/initClientDataStore(){const globalStorageType=state.storage.type.value;let trulyAnonymousTracking=true;const entries=state.loadOptions.value.storage?.entries;Object.keys(UserSessionKeys).forEach(sessionKey=>{const key=sessionKey;const storageKey=sessionKey;const providedStorageType=entries?.[key]?.type;const storageType=providedStorageType||globalStorageType||DEFAULT_STORAGE_TYPE;let finalStorageType=storageType;switch(storageType){case LOCAL_STORAGE:if(!getStorageEngine(LOCAL_STORAGE)?.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
|
992
|
+
if(getStorageEngine(COOKIE_STORAGE)?.isEnabled){finalStorageType=COOKIE_STORAGE;}else if(getStorageEngine(LOCAL_STORAGE)?.isEnabled){finalStorageType=LOCAL_STORAGE;}else {finalStorageType=MEMORY_STORAGE;}break;}if(finalStorageType!==storageType){this.logger?.warn(STORAGE_UNAVAILABLE_WARNING(STORE_MANAGER,storageType,finalStorageType));}if(finalStorageType!==NO_STORAGE){trulyAnonymousTracking=false;}const storageState=state.storage.entries.value;state.storage.entries.value={...storageState,[sessionKey]:{type:finalStorageType,key:userSessionStorageKeys[storageKey]}};});state.storage.trulyAnonymousTracking.value=trulyAnonymousTracking;// TODO: fill in extra config values and bring them in from StoreManagerOptions if needed
|
1148
993
|
// TODO: should we pass the keys for all in order to validate or leave free as v1.1?
|
1149
|
-
|
994
|
+
// Initializing all the enabled store because previous user data might be in different storage
|
995
|
+
// that needs auto migration
|
996
|
+
const storageTypesRequiringInitialization=[MEMORY_STORAGE];if(getStorageEngine(LOCAL_STORAGE)?.isEnabled){storageTypesRequiringInitialization.push(LOCAL_STORAGE);}if(getStorageEngine(COOKIE_STORAGE)?.isEnabled){storageTypesRequiringInitialization.push(COOKIE_STORAGE);}storageTypesRequiringInitialization.forEach(storageType=>{this.setStore({id:storageClientDataStoreNameMap[storageType],name:storageClientDataStoreNameMap[storageType],isEncrypted:true,noCompoundKey:true,type:storageType});});}/**
|
1150
997
|
* Create a new store
|
1151
998
|
*/setStore(storeConfig){const storageEngine=getStorageEngine(storeConfig.type);this.stores[storeConfig.id]=new Store(storeConfig,storageEngine,this.pluginsManager);return this.stores[storeConfig.id];}/**
|
1152
999
|
* Retrieve a store
|
@@ -1202,7 +1049,7 @@ const defaultOptionalPluginsList=[PluginName.Bugsnag,PluginName.DeviceModeDestin
|
|
1202
1049
|
*/const isPositiveInteger=num=>isNumber(num)&&num>=0&&Number.isInteger(num);
|
1203
1050
|
|
1204
1051
|
const normalizeLoadOptions=(loadOptionsFromState,loadOptions)=>{// TODO: Maybe add warnings for invalid values
|
1205
|
-
const normalizedLoadOpts=clone$1(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){delete normalizedLoadOpts.setCookieDomain;}if(!getObjectValues(CookieSameSite).includes(normalizedLoadOpts.sameSiteCookie)){delete normalizedLoadOpts.sameSiteCookie;}normalizedLoadOpts.secureCookie=normalizedLoadOpts.secureCookie===true;if(!getObjectValues(UaChTrackLevel).includes(normalizedLoadOpts.uaChTrackLevel)){delete normalizedLoadOpts.uaChTrackLevel;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.integrations)){delete normalizedLoadOpts.integrations;}normalizedLoadOpts.plugins=normalizedLoadOpts.plugins??defaultOptionalPluginsList;normalizedLoadOpts.useGlobalIntegrationsConfigInEvents=normalizedLoadOpts.useGlobalIntegrationsConfigInEvents===true;normalizedLoadOpts.bufferDataPlaneEventsUntilReady=normalizedLoadOpts.bufferDataPlaneEventsUntilReady===true;normalizedLoadOpts.sendAdblockPage=normalizedLoadOpts.sendAdblockPage===true;if(!isObjectLiteralAndNotNull(normalizedLoadOpts.sendAdblockPageOptions)){delete normalizedLoadOpts.sendAdblockPageOptions;}if(!isDefined(normalizedLoadOpts.loadIntegration)){delete normalizedLoadOpts.loadIntegration;}else {normalizedLoadOpts.loadIntegration=normalizedLoadOpts.loadIntegration===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.storage)){delete normalizedLoadOpts.storage;}else {normalizedLoadOpts.storage=removeUndefinedAndNullValues(normalizedLoadOpts.storage);normalizedLoadOpts.storage.migrate=normalizedLoadOpts.storage?.migrate===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.beaconQueueOptions)){delete normalizedLoadOpts.beaconQueueOptions;}else {normalizedLoadOpts.beaconQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.beaconQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.destinationsQueueOptions)){delete normalizedLoadOpts.destinationsQueueOptions;}else {normalizedLoadOpts.destinationsQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.destinationsQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.queueOptions)){delete normalizedLoadOpts.queueOptions;}else {normalizedLoadOpts.queueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.queueOptions);}normalizedLoadOpts.lockIntegrationsVersion=normalizedLoadOpts.lockIntegrationsVersion===true;if(!isNumber(normalizedLoadOpts.dataPlaneEventsBufferTimeout)){delete normalizedLoadOpts.dataPlaneEventsBufferTimeout;}const mergedLoadOptions=mergeDeepRight(loadOptionsFromState,normalizedLoadOpts);return mergedLoadOptions;};const getSourceConfigURL=(configUrl,writeKey,lockIntegrationsVersion,logger)=>{const defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString()});let origin=DEFAULT_CONFIG_BE_URL;let searchParams=defSearchParams;let pathname='/sourceConfig/';let hash='';// Ideally, this check is not required but URL polyfill
|
1052
|
+
const normalizedLoadOpts=clone$1(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){delete normalizedLoadOpts.setCookieDomain;}if(!getObjectValues(CookieSameSite).includes(normalizedLoadOpts.sameSiteCookie)){delete normalizedLoadOpts.sameSiteCookie;}normalizedLoadOpts.secureCookie=normalizedLoadOpts.secureCookie===true;if(!getObjectValues(UaChTrackLevel).includes(normalizedLoadOpts.uaChTrackLevel)){delete normalizedLoadOpts.uaChTrackLevel;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.integrations)){delete normalizedLoadOpts.integrations;}normalizedLoadOpts.plugins=normalizedLoadOpts.plugins??defaultOptionalPluginsList;normalizedLoadOpts.useGlobalIntegrationsConfigInEvents=normalizedLoadOpts.useGlobalIntegrationsConfigInEvents===true;normalizedLoadOpts.bufferDataPlaneEventsUntilReady=normalizedLoadOpts.bufferDataPlaneEventsUntilReady===true;normalizedLoadOpts.sendAdblockPage=normalizedLoadOpts.sendAdblockPage===true;if(!isObjectLiteralAndNotNull(normalizedLoadOpts.sendAdblockPageOptions)){delete normalizedLoadOpts.sendAdblockPageOptions;}if(!isDefined(normalizedLoadOpts.loadIntegration)){delete normalizedLoadOpts.loadIntegration;}else {normalizedLoadOpts.loadIntegration=normalizedLoadOpts.loadIntegration===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.storage)){delete normalizedLoadOpts.storage;}else {normalizedLoadOpts.storage=removeUndefinedAndNullValues(normalizedLoadOpts.storage);normalizedLoadOpts.storage.migrate=normalizedLoadOpts.storage?.migrate===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.beaconQueueOptions)){delete normalizedLoadOpts.beaconQueueOptions;}else {normalizedLoadOpts.beaconQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.beaconQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.destinationsQueueOptions)){delete normalizedLoadOpts.destinationsQueueOptions;}else {normalizedLoadOpts.destinationsQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.destinationsQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.queueOptions)){delete normalizedLoadOpts.queueOptions;}else {normalizedLoadOpts.queueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.queueOptions);}normalizedLoadOpts.lockIntegrationsVersion=normalizedLoadOpts.lockIntegrationsVersion===true;if(!isNumber(normalizedLoadOpts.dataPlaneEventsBufferTimeout)){delete normalizedLoadOpts.dataPlaneEventsBufferTimeout;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.storage?.cookie)){delete normalizedLoadOpts.storage?.cookie;}else {normalizedLoadOpts.storage.cookie=removeUndefinedAndNullValues(normalizedLoadOpts.storage?.cookie);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.preConsent)){delete normalizedLoadOpts.preConsent;}else {normalizedLoadOpts.preConsent=removeUndefinedAndNullValues(normalizedLoadOpts.preConsent);}const mergedLoadOptions=mergeDeepRight(loadOptionsFromState,normalizedLoadOpts);return mergedLoadOptions;};const getSourceConfigURL=(configUrl,writeKey,lockIntegrationsVersion,logger)=>{const defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString()});let origin=DEFAULT_CONFIG_BE_URL;let searchParams=defSearchParams;let pathname='/sourceConfig/';let hash='';// Ideally, this check is not required but URL polyfill
|
1206
1053
|
// doesn't seem to throw errors for empty URLs
|
1207
1054
|
// TODO: Need to improve this check to find out if the URL is valid or not
|
1208
1055
|
if(configUrl){try{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;}catch(err){logger?.warn(INVALID_CONFIG_URL_WARNING(CONFIG_MANAGER,configUrl));}}return `${origin}${pathname}?${searchParams}${hash}`;};
|
@@ -1230,21 +1077,39 @@ if(dataplanes&&Object.keys(dataplanes).length>0){const region=validateResidencyS
|
|
1230
1077
|
if(serverUrl){return serverUrl;}// return undefined if data plane url can not be determined
|
1231
1078
|
return undefined;};
|
1232
1079
|
|
1080
|
+
const DEFAULT_PRE_CONSENT_STORAGE_STRATEGY=StorageStrategy.None;const DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE=DeliveryType.Immediate;
|
1081
|
+
|
1233
1082
|
const isErrorReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.errors?.enabled===true;const getErrorReportingProviderNameFromConfig=sourceConfig=>sourceConfig?.statsCollection?.errors?.provider;const isMetricsReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.metrics?.enabled===true;
|
1234
1083
|
|
1084
|
+
/**
|
1085
|
+
* A function to get the name of the consent manager with enabled true set in the load options
|
1086
|
+
* @param cookieConsentOptions Input provided as load option
|
1087
|
+
* @returns string|undefined
|
1088
|
+
*
|
1089
|
+
* Example input: {
|
1090
|
+
* oneTrust:{
|
1091
|
+
* enabled: true
|
1092
|
+
* }
|
1093
|
+
* }
|
1094
|
+
*
|
1095
|
+
* Output: 'oneTrust'
|
1096
|
+
*/const getUserSelectedConsentManager=cookieConsentOptions=>{if(!isNonEmptyObject(cookieConsentOptions)){return undefined;}const validCookieConsentOptions=cookieConsentOptions;return Object.keys(validCookieConsentOptions).find(e=>e&&validCookieConsentOptions[e].enabled===true);};
|
1097
|
+
|
1235
1098
|
/**
|
1236
1099
|
* Determines the SDK url
|
1237
1100
|
* @returns sdkURL
|
1238
|
-
*/const getSDKUrl=()=>{const scripts=document.getElementsByTagName('script');let sdkURL;const scriptList=Array.prototype.slice.call(scripts);scriptList.some(script=>{const curScriptSrc=removeTrailingSlashes(script.getAttribute('src'));if(curScriptSrc){const urlMatches=curScriptSrc.match(/^.*rsa?(\.min)?\.js$/);if(urlMatches){sdkURL=curScriptSrc;return true;}}return false;})
|
1239
|
-
return sdkURL;};/**
|
1101
|
+
*/const getSDKUrl=()=>{const scripts=document.getElementsByTagName('script');let sdkURL;const scriptList=Array.prototype.slice.call(scripts);scriptList.some(script=>{const curScriptSrc=removeTrailingSlashes(script.getAttribute('src'));if(curScriptSrc){const urlMatches=curScriptSrc.match(/^.*rsa?(\.min)?\.js$/);if(urlMatches){sdkURL=curScriptSrc;return true;}}return false;});return sdkURL;};/**
|
1240
1102
|
* Updates the reporting state variables from the source config data
|
1241
1103
|
* @param res Source config
|
1242
1104
|
* @param logger Logger instance
|
1243
1105
|
*/const updateReportingState=(res,logger)=>{state.reporting.isErrorReportingEnabled.value=isErrorReportingEnabled(res.source.config);state.reporting.isMetricsReportingEnabled.value=isMetricsReportingEnabled(res.source.config);if(state.reporting.isErrorReportingEnabled.value){const errReportingProvider=getErrorReportingProviderNameFromConfig(res.source.config);// Get the corresponding plugin name of the selected error reporting provider from the supported error reporting providers
|
1244
1106
|
const errReportingProviderPlugin=errReportingProvider?ErrorReportingProvidersToPluginNameMap[errReportingProvider]:undefined;if(!isUndefined(errReportingProvider)&&!errReportingProviderPlugin){// set the default error reporting provider
|
1245
|
-
logger?.warn(UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(CONFIG_MANAGER,errReportingProvider,ErrorReportingProvidersToPluginNameMap,DEFAULT_ERROR_REPORTING_PROVIDER));}state.reporting.errorReportingProviderPluginName.value=errReportingProviderPlugin??ErrorReportingProvidersToPluginNameMap[DEFAULT_ERROR_REPORTING_PROVIDER];}};const updateStorageState=logger=>{
|
1246
|
-
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;}
|
1247
|
-
const configuredMigrationValue=
|
1107
|
+
logger?.warn(UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(CONFIG_MANAGER,errReportingProvider,ErrorReportingProvidersToPluginNameMap,DEFAULT_ERROR_REPORTING_PROVIDER));}state.reporting.errorReportingProviderPluginName.value=errReportingProviderPlugin??ErrorReportingProvidersToPluginNameMap[DEFAULT_ERROR_REPORTING_PROVIDER];}};const updateStorageState=logger=>{const storageOptsFromLoad=state.loadOptions.value.storage;let storageType=storageOptsFromLoad?.type;if(isDefined(storageType)&&!isValidStorageType(storageType)){logger?.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));storageType=DEFAULT_STORAGE_TYPE;}let storageEncryptionVersion=storageOptsFromLoad?.encryption?.version;const encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
|
1108
|
+
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
|
1109
|
+
const configuredMigrationValue=storageOptsFromLoad?.migrate;const finalMigrationVal=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&state.storage.migrate.value!==configuredMigrationValue){logger?.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}r(()=>{state.storage.type.value=storageType;state.storage.cookie.value=storageOptsFromLoad?.cookie;state.storage.encryptionPluginName.value=StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];state.storage.migrate.value=finalMigrationVal;});};const updateConsentsState=logger=>{// Get the consent manager if provided as load option
|
1110
|
+
const selectedConsentManager=getUserSelectedConsentManager(state.loadOptions.value.cookieConsentManager);let consentManagerPluginName;if(selectedConsentManager){// Get the corresponding plugin name of the selected consent manager from the supported consent managers
|
1111
|
+
consentManagerPluginName=ConsentManagersToPluginNameMap[selectedConsentManager];if(!consentManagerPluginName){logger?.error(UNSUPPORTED_CONSENT_MANAGER_ERROR(CONFIG_MANAGER,selectedConsentManager,ConsentManagersToPluginNameMap));}}// Pre-consent
|
1112
|
+
const preConsentOpts=state.loadOptions.value.preConsent;let storageStrategy=preConsentOpts?.storage?.strategy??DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;if(isDefined(storageStrategy)&&!Object.values(StorageStrategy).includes(storageStrategy)){storageStrategy=DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;logger?.warn(UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(CONFIG_MANAGER,preConsentOpts?.storage?.strategy,DEFAULT_PRE_CONSENT_STORAGE_STRATEGY));}let eventsDeliveryType=preConsentOpts?.events?.delivery??DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;if(isDefined(eventsDeliveryType)&&!Object.values(DeliveryType).includes(eventsDeliveryType)){eventsDeliveryType=DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;logger?.warn(UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(CONFIG_MANAGER,preConsentOpts?.events?.delivery,DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE));}r(()=>{state.consents.activeConsentManagerPluginName.value=consentManagerPluginName;state.consents.preConsentOptions.value={enabled:state.loadOptions.value.preConsent?.enabled===true,storage:{strategy:storageStrategy},events:{delivery:eventsDeliveryType},trackConsent:state.loadOptions.value.preConsent?.trackConsent===true};});};
|
1248
1113
|
|
1249
1114
|
/**
|
1250
1115
|
* A function that determines integration SDK loading path
|
@@ -1263,43 +1128,25 @@ if(lockIntegrationsVersion){integrationsCDNPath=integrationsCDNPath.replace(CDN_
|
|
1263
1128
|
if(customPluginsCDNPath){pluginsCDNPath=removeTrailingSlashes(customPluginsCDNPath);if(!pluginsCDNPath||pluginsCDNPath&&!isValidUrl(pluginsCDNPath)){throw new Error(PLUGINS_CDN_BASE_URL_ERROR);}return pluginsCDNPath;}// Get the base path from the SDK script tag src attribute or use the default path
|
1264
1129
|
const sdkURL=getSDKUrl();pluginsCDNPath=sdkURL&&isString(sdkURL)?sdkURL.split('/').slice(0,-1).concat(CDN_PLUGINS_DIR).join('/'):PLUGINS_BASE_URL;return pluginsCDNPath;};
|
1265
1130
|
|
1266
|
-
/**
|
1267
|
-
* A function to get the name of the consent manager with enabled true set in the load options
|
1268
|
-
* @param cookieConsentOptions Input provided as load option
|
1269
|
-
* @returns string|undefined
|
1270
|
-
*
|
1271
|
-
* Example input: {
|
1272
|
-
* oneTrust:{
|
1273
|
-
* enabled: true
|
1274
|
-
* }
|
1275
|
-
* }
|
1276
|
-
*
|
1277
|
-
* Output: 'oneTrust'
|
1278
|
-
*/const getUserSelectedConsentManager=cookieConsentOptions=>{if(!isNonEmptyObject(cookieConsentOptions)){return undefined;}const validCookieConsentOptions=cookieConsentOptions;return Object.keys(validCookieConsentOptions).find(e=>e&&validCookieConsentOptions[e].enabled===true);};
|
1279
|
-
|
1280
|
-
class ConfigManager{hasErrorHandler=false;constructor(httpClient,errorHandler,logger){this.errorHandler=errorHandler;this.logger=logger;this.httpClient=httpClient;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);this.processConfig=this.processConfig.bind(this);}attachEffects(){b(()=>{this.logger?.setMinLogLevel(state.lifecycle.logLevel.value);});}/**
|
1131
|
+
class ConfigManager{hasErrorHandler=false;constructor(httpClient,errorHandler,logger){this.errorHandler=errorHandler;this.logger=logger;this.httpClient=httpClient;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);this.processConfig=this.processConfig.bind(this);}attachEffects(){E(()=>{this.logger?.setMinLogLevel(state.lifecycle.logLevel.value);});}/**
|
1281
1132
|
* A function to validate, construct and store loadOption, lifecycle, source and destination
|
1282
1133
|
* config related information in global state
|
1283
|
-
*/init(){
|
1134
|
+
*/init(){this.attachEffects();const lockIntegrationsVersion=state.loadOptions.value.lockIntegrationsVersion;validateLoadArgs(state.lifecycle.writeKey.value,state.lifecycle.dataPlaneUrl.value);// determine the path to fetch integration SDK from
|
1284
1135
|
const intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,state.loadOptions.value.destSDKBaseURL);// determine the path to fetch remote plugins from
|
1285
|
-
const pluginsCDNPath=getPluginsCDNPath(state.loadOptions.value.pluginsSDKBaseURL);//
|
1286
|
-
|
1287
|
-
consentManagerPluginName=ConsentManagersToPluginNameMap[selectedConsentManager];if(!consentManagerPluginName){this.logger?.error(UNSUPPORTED_CONSENT_MANAGER_ERROR(CONFIG_MANAGER,selectedConsentManager,ConsentManagersToPluginNameMap));}}updateStorageState(this.logger);// set application lifecycle state in global state
|
1288
|
-
o(()=>{state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycle.pluginsCDNPath.value=pluginsCDNPath;if(state.loadOptions.value.logLevel){state.lifecycle.logLevel.value=state.loadOptions.value.logLevel;}state.lifecycle.sourceConfigUrl.value=getSourceConfigURL(state.loadOptions.value.configUrl,state.lifecycle.writeKey.value,lockIntegrationsVersion,this.logger);// Set consent manager plugin name in state
|
1289
|
-
state.consents.activeConsentManagerPluginName.value=consentManagerPluginName;// set storage type in state
|
1290
|
-
const storageType=state.loadOptions.value.storage?.type;if(!isValidStorageType(storageType)){this.logger?.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));state.storage.type.value=DEFAULT_STORAGE_TYPE;}else {state.storage.type.value=storageType;}});this.getConfig();}/**
|
1136
|
+
const pluginsCDNPath=getPluginsCDNPath(state.loadOptions.value.pluginsSDKBaseURL);updateStorageState(this.logger);updateConsentsState(this.logger);// set application lifecycle state in global state
|
1137
|
+
r(()=>{state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycle.pluginsCDNPath.value=pluginsCDNPath;if(state.loadOptions.value.logLevel){state.lifecycle.logLevel.value=state.loadOptions.value.logLevel;}state.lifecycle.sourceConfigUrl.value=getSourceConfigURL(state.loadOptions.value.configUrl,state.lifecycle.writeKey.value,lockIntegrationsVersion,this.logger);});this.getConfig();}/**
|
1291
1138
|
* Handle errors
|
1292
1139
|
*/onError(error,customMessage,shouldAlwaysThrow){if(this.hasErrorHandler){this.errorHandler?.onError(error,CONFIG_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}/**
|
1293
1140
|
* A callback function that is executed once we fetch the source config response.
|
1294
1141
|
* Use to construct and store information that are dependent on the sourceConfig.
|
1295
1142
|
*/processConfig(response,details){// TODO: add retry logic with backoff based on rejectionDetails.xhr.status
|
1296
1143
|
// We can use isErrRetryable utility method
|
1297
|
-
if(!response){this.onError(SOURCE_CONFIG_FETCH_ERROR(details?.error));return;}let res;const errMessage='Unable to process/parse source config';try{if(isString(response)){res=JSON.parse(response);}else {res=response;}}catch(e){this.onError(e,errMessage,true);return;}if(!isValidSourceConfig(res)){this.onError(new Error(errMessage),undefined,true);return;}//
|
1144
|
+
if(!response){this.onError(SOURCE_CONFIG_FETCH_ERROR(details?.error));return;}let res;const errMessage='Unable to process/parse source config';try{if(isString(response)){res=JSON.parse(response);}else {res=response;}}catch(e){this.onError(e,errMessage,true);return;}if(!isValidSourceConfig(res)){this.onError(new Error(errMessage),undefined,true);return;}// set the values in state for reporting slice
|
1145
|
+
updateReportingState(res,this.logger);// determine the dataPlane url
|
1298
1146
|
const dataPlaneUrl=resolveDataPlaneUrl(res.source.dataplanes,state.lifecycle.dataPlaneUrl.value,state.loadOptions.value.residencyServer,this.logger);if(!dataPlaneUrl){this.onError(new Error(DATA_PLANE_URL_ERROR),undefined,true);return;}const nativeDestinations=res.source.destinations.length>0?filterEnabledDestination(res.source.destinations):[];// set in the state --> source, destination, lifecycle, reporting
|
1299
|
-
|
1147
|
+
r(()=>{// set source related information in state
|
1300
1148
|
state.source.value={config:res.source.config,id:res.source.id};// set device mode destination related information in state
|
1301
|
-
state.nativeDestinations.configuredDestinations.value=nativeDestinations;// set the
|
1302
|
-
updateReportingState(res,this.logger);// set the desired optional plugins
|
1149
|
+
state.nativeDestinations.configuredDestinations.value=nativeDestinations;// set the desired optional plugins
|
1303
1150
|
state.plugins.pluginsToLoadFromConfig.value=state.loadOptions.value.plugins??[];// set application lifecycle state
|
1304
1151
|
// Cast to string as we are sure that the value is not undefined
|
1305
1152
|
state.lifecycle.activeDataplaneUrl.value=removeTrailingSlashes(dataPlaneUrl);state.lifecycle.status.value=LifecycleStatus.Configured;});}/**
|
@@ -1334,11 +1181,11 @@ const POLYFILL_SCRIPT_ID='rudderstackPolyfill';
|
|
1334
1181
|
class CapabilitiesManager{constructor(errorHandler,logger){this.logger=logger;this.errorHandler=errorHandler;this.externalSrcLoader=new ExternalSrcLoader(this.errorHandler,this.logger);this.onError=this.onError.bind(this);this.onReady=this.onReady.bind(this);}init(){try{this.prepareBrowserCapabilities();this.attachWindowListeners();}catch(err){this.onError(err);}}/**
|
1335
1182
|
* Detect supported capabilities and set values in state
|
1336
1183
|
*/ // eslint-disable-next-line class-methods-use-this
|
1337
|
-
detectBrowserCapabilities(){
|
1184
|
+
detectBrowserCapabilities(){r(()=>{// Storage related details
|
1338
1185
|
state.capabilities.storage.isCookieStorageAvailable.value=isStorageAvailable(COOKIE_STORAGE,getStorageEngine(COOKIE_STORAGE),this.logger);state.capabilities.storage.isLocalStorageAvailable.value=isStorageAvailable(LOCAL_STORAGE,undefined,this.logger);state.capabilities.storage.isSessionStorageAvailable.value=isStorageAvailable(SESSION_STORAGE,undefined,this.logger);// Browser feature detection details
|
1339
|
-
state.capabilities.isBeaconAvailable.value=hasBeacon();state.capabilities.isUaCHAvailable.value=hasUAClientHints();state.capabilities.isCryptoAvailable.value=hasCrypto();state.capabilities.isIE11.value=isIE11();state.capabilities.isOnline.value=globalThis.navigator.onLine;// Get page context details
|
1186
|
+
state.capabilities.isBeaconAvailable.value=hasBeacon();state.capabilities.isUaCHAvailable.value=hasUAClientHints();state.capabilities.isCryptoAvailable.value=hasCrypto$1();state.capabilities.isIE11.value=isIE11();state.capabilities.isOnline.value=globalThis.navigator.onLine;// Get page context details
|
1340
1187
|
state.context.userAgent.value=getUserAgent();state.context.locale.value=getLanguage();state.context.screen.value=getScreenDetails();if(hasUAClientHints()){getUserAgentClientHint(uach=>{state.context['ua-ch'].value=uach;},state.loadOptions.value.uaChTrackLevel);}});// Ad blocker detection
|
1341
|
-
|
1188
|
+
E(()=>{if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(this.errorHandler,this.logger);}});}/**
|
1342
1189
|
* Detect if polyfills are required and then load script from polyfill URL
|
1343
1190
|
*/prepareBrowserCapabilities(){state.capabilities.isLegacyDOM.value=isLegacyJSEngine();let polyfillUrl=state.loadOptions.value.polyfillURL??POLYFILL_URL;const shouldLoadPolyfill=state.loadOptions.value.polyfillIfRequired&&state.capabilities.isLegacyDOM.value&&Boolean(polyfillUrl);if(shouldLoadPolyfill){const isDefaultPolyfillService=polyfillUrl!==state.loadOptions.value.polyfillURL;if(isDefaultPolyfillService){const polyfillCallback=()=>this.onReady();// write key specific callback
|
1344
1191
|
// NOTE: we're not putting this into RudderStackGlobals as providing the property path to the callback function in the polyfill URL is not possible
|
@@ -1353,11 +1200,28 @@ onReady(){this.detectBrowserCapabilities();state.lifecycle.status.value=Lifecycl
|
|
1353
1200
|
* @param error The error object
|
1354
1201
|
*/onError(error){if(this.errorHandler){this.errorHandler.onError(error,CAPABILITIES_MANAGER);}else {throw error;}}}
|
1355
1202
|
|
1203
|
+
function random(len){return crypto.getRandomValues(new Uint8Array(len));}
|
1204
|
+
|
1205
|
+
var SIZE=4096,HEX$1=[],IDX$1=0,BUFFER$1;for(;IDX$1<256;IDX$1++){HEX$1[IDX$1]=(IDX$1+256).toString(16).substring(1);}function v4$1(){if(!BUFFER$1||IDX$1+16>SIZE){BUFFER$1=random(SIZE);IDX$1=0;}var i=0,tmp,out='';for(;i<16;i++){tmp=BUFFER$1[IDX$1+i];if(i==6)out+=HEX$1[tmp&15|64];else if(i==8)out+=HEX$1[tmp&63|128];else out+=HEX$1[tmp];if(i&1&&i>1&&i<11)out+='-';}IDX$1+=16;return out;}
|
1206
|
+
|
1207
|
+
var IDX=256,HEX=[],BUFFER;while(IDX--)HEX[IDX]=(IDX+256).toString(16).substring(1);function v4(){var i=0,num,out='';if(!BUFFER||IDX+16>256){BUFFER=Array(i=256);while(i--)BUFFER[i]=256*Math.random()|0;i=IDX=0;}for(;i<16;i++){num=BUFFER[IDX+i];if(i==6)out+=HEX[num&15|64];else if(i==8)out+=HEX[num&63|128];else out+=HEX[num];if(i&1&&i>1&&i<11)out+='-';}IDX++;return out;}
|
1208
|
+
|
1209
|
+
const hasCrypto=()=>!isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);
|
1210
|
+
|
1211
|
+
const generateUUID=()=>{if(hasCrypto()){return v4$1();}return v4();};
|
1212
|
+
|
1213
|
+
/**
|
1214
|
+
* To get the current timestamp in ISO string format
|
1215
|
+
* @returns ISO formatted timestamp string
|
1216
|
+
*/const getCurrentTimeFormatted=()=>{const curDateTime=new Date().toISOString();return curDateTime;};
|
1217
|
+
|
1218
|
+
const DEFAULT_INTEGRATIONS_CONFIG={All:true};
|
1219
|
+
|
1356
1220
|
const CHANNEL='web';// These are the top-level elements in the standard RudderStack event spec
|
1357
1221
|
const TOP_LEVEL_ELEMENTS=['integrations','anonymousId','originalTimestamp'];// Reserved elements in the context of standard RudderStack event spec
|
1358
1222
|
// Typically, these elements are not allowed to be overridden by the user
|
1359
1223
|
const CONTEXT_RESERVED_ELEMENTS=['library','consentManagement','userAgent','ua-ch','screen'];// Reserved elements in the standard RudderStack event spec
|
1360
|
-
const RESERVED_ELEMENTS=['anonymousId','sentAt','receivedAt','timestamp','originalTimestamp','event','messageId','channel'];
|
1224
|
+
const RESERVED_ELEMENTS=['anonymousId','sentAt','receivedAt','timestamp','originalTimestamp','event','messageId','channel'];
|
1361
1225
|
|
1362
1226
|
/**
|
1363
1227
|
* To get the page properties for context object
|
@@ -1372,7 +1236,6 @@ const curPageProps=getDefaultPageProperties();const ctxPageProps={};Object.keys(
|
|
1372
1236
|
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;};/**
|
1373
1237
|
* Utility to check for reserved keys in the input object
|
1374
1238
|
* @param obj Generic object
|
1375
|
-
* @param eventType Rudder event type
|
1376
1239
|
* @param parentKeyPath Object's parent key path
|
1377
1240
|
* @param logger Logger instance
|
1378
1241
|
*/const checkForReservedElementsInObject=(obj,parentKeyPath,logger)=>{if(isObjectLiteralAndNotNull(obj)){Object.keys(obj).forEach(property=>{if(RESERVED_ELEMENTS.includes(property)||RESERVED_ELEMENTS.includes(property.toLowerCase())){logger?.warn(RESERVED_KEYWORD_WARNING(EVENT_MANAGER,property,parentKeyPath,RESERVED_ELEMENTS));}});}};/**
|
@@ -1412,9 +1275,10 @@ rudderEvent.context=getMergedContext(rudderEvent.context,options);}};/**
|
|
1412
1275
|
* @param pageProps Page properties
|
1413
1276
|
* @param logger logger
|
1414
1277
|
* @returns Enriched RudderEvent object
|
1415
|
-
*/const getEnrichedEvent=(rudderEvent,options,pageProps,logger)=>{const commonEventData={channel:CHANNEL,context:{traits:clone$1(state.session.userTraits.value),sessionId:state.session.sessionInfo.value.id||undefined,sessionStart:state.session.sessionInfo.value.sessionStart||undefined,consentManagement:{deniedConsentIds:clone$1(state.consents.data.value.deniedConsentIds)},'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)},originalTimestamp:getCurrentTimeFormatted(),integrations:DEFAULT_INTEGRATIONS_CONFIG,messageId:generateUUID(),userId:rudderEvent.userId||state.session.userId.value};if(state.storage.
|
1416
|
-
commonEventData.anonymousId=generateUUID();
|
1417
|
-
commonEventData.anonymousId=state.session.
|
1278
|
+
*/const getEnrichedEvent=(rudderEvent,options,pageProps,logger)=>{const commonEventData={channel:CHANNEL,context:{traits:clone$1(state.session.userTraits.value),sessionId:state.session.sessionInfo.value.id||undefined,sessionStart:state.session.sessionInfo.value.sessionStart||undefined,consentManagement:{deniedConsentIds:clone$1(state.consents.data.value.deniedConsentIds)},'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)},originalTimestamp:getCurrentTimeFormatted(),integrations:DEFAULT_INTEGRATIONS_CONFIG,messageId:generateUUID(),userId:rudderEvent.userId||state.session.userId.value};if(state.storage.entries.value.anonymousId?.type===NO_STORAGE){// Generate new anonymous id for each request
|
1279
|
+
commonEventData.anonymousId=generateUUID();}else {// Type casting to string as the user session manager will take care of initializing the value
|
1280
|
+
commonEventData.anonymousId=state.session.anonymousId.value;}// set truly anonymous tracking flag
|
1281
|
+
if(state.storage.trulyAnonymousTracking.value){commonEventData.context.trulyAnonymousTracking=true;}if(rudderEvent.type===RudderEventType.Identify){commonEventData.context.traits=state.storage.entries.value.userTraits?.type!==NO_STORAGE?clone$1(state.session.userTraits.value):rudderEvent.context.traits;}if(rudderEvent.type===RudderEventType.Group){if(rudderEvent.groupId||state.session.groupId.value){commonEventData.groupId=rudderEvent.groupId||state.session.groupId.value;}if(rudderEvent.traits||state.session.groupTraits.value){commonEventData.traits=state.storage.entries.value.groupTraits?.type!==NO_STORAGE?clone$1(state.session.groupTraits.value):rudderEvent.traits;}}const processedEvent=mergeDeepRight(rudderEvent,commonEventData);// Set the default values for the event properties
|
1418
1282
|
// matching with v1.1 payload
|
1419
1283
|
if(processedEvent.event===undefined){processedEvent.event=null;}if(processedEvent.properties===undefined){processedEvent.properties=null;}processOptions(processedEvent,options);// TODO: We might not need this check altogether
|
1420
1284
|
checkForReservedElements(processedEvent,logger);// Update the integrations config for the event
|
@@ -1488,17 +1352,15 @@ timeout,sessionStart:undefined,autoTrack:true};};/**
|
|
1488
1352
|
* @param id Provided sessionId
|
1489
1353
|
* @param logger Logger module
|
1490
1354
|
* @returns SessionInfo
|
1491
|
-
*/const generateManualTrackingSession=(id,logger)=>{const sessionId=isManualSessionIdValid(id,logger)?id:generateSessionId();return {id:sessionId,sessionStart:undefined,manualTrack:true};};
|
1355
|
+
*/const generateManualTrackingSession=(id,logger)=>{const sessionId=isManualSessionIdValid(id,logger)?id:generateSessionId();return {id:sessionId,sessionStart:undefined,manualTrack:true};};const isStorageTypeValidForStoringData=storageType=>!!(storageType===COOKIE_STORAGE||storageType===LOCAL_STORAGE||storageType===MEMORY_STORAGE);
|
1492
1356
|
|
1493
|
-
|
1494
|
-
|
1495
|
-
class UserSessionManager{constructor(errorHandler,logger,pluginsManager,store){this.store=store;this.pluginsManager=pluginsManager;this.logger=logger;this.errorHandler=errorHandler;this.onError=this.onError.bind(this);}/**
|
1357
|
+
class UserSessionManager{constructor(errorHandler,logger,pluginsManager,storeManager){this.storeManager=storeManager;this.pluginsManager=pluginsManager;this.logger=logger;this.errorHandler=errorHandler;this.onError=this.onError.bind(this);}/**
|
1496
1358
|
* Initialize User session with values from storage
|
1497
1359
|
* @param store Selected store
|
1498
|
-
*/init(
|
1499
|
-
this.
|
1500
|
-
this.initializeSessionTracking()
|
1501
|
-
this.registerEffects();}
|
1360
|
+
*/init(){this.migrateStorageIfNeeded();this.migrateDataFromPreviousStorage();// get the values from storage and set it again
|
1361
|
+
const userId=this.getUserId();const userTraits=this.getUserTraits();const groupId=this.getGroupId();const groupTraits=this.getGroupTraits();const anonymousId=this.getAnonymousId();if(userId){this.setUserId(userId);}if(userTraits){this.setUserTraits(userTraits);}if(groupId){this.setGroupId(groupId);}if(groupTraits){this.setGroupTraits(groupTraits);}if(anonymousId){this.setAnonymousId(anonymousId);}const initialReferrer=this.getInitialReferrer();const initialReferringDomain=this.getInitialReferringDomain();if(initialReferrer&&initialReferringDomain){this.setInitialReferrer(initialReferrer);this.setInitialReferringDomain(initialReferringDomain);}else if(initialReferrer){this.setInitialReferrer(initialReferrer);this.setInitialReferringDomain(getReferringDomain(initialReferrer));}else {const referrer=getReferrer();this.setInitialReferrer(referrer);this.setInitialReferringDomain(getReferringDomain(referrer));}// Initialize session tracking
|
1362
|
+
if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.sessionInfo)){this.initializeSessionTracking();}// Register the effect to sync with storage
|
1363
|
+
this.registerEffects();}isPersistenceEnabledForStorageEntry(entryName){const entries=state.storage.entries.value;return isStorageTypeValidForStoringData(entries[entryName]?.type);}migrateDataFromPreviousStorage(){const entries=state.storage.entries.value;Object.keys(entries).forEach(entry=>{const key=entry;const currentStorage=entries[key]?.type;const curStore=this.storeManager?.getStore(storageClientDataStoreNameMap[currentStorage]);const storages=[COOKIE_STORAGE,LOCAL_STORAGE];storages.forEach(storage=>{const store=this.storeManager?.getStore(storageClientDataStoreNameMap[storage]);if(storage!==currentStorage&&store){if(curStore){const value=store?.get(userSessionStorageKeys[key]);if(isDefinedNotNullAndNotEmptyString(value)){curStore?.set(userSessionStorageKeys[key],value);}}store?.remove(userSessionStorageKeys[key]);}});});}migrateStorageIfNeeded(){if(!state.storage.migrate.value){return;}const cookieStorage=this.storeManager?.getStore(CLIENT_DATA_STORE_COOKIE);const localStorage=this.storeManager?.getStore(CLIENT_DATA_STORE_LS);const stores=[];if(cookieStorage){stores.push(cookieStorage);}if(localStorage){stores.push(localStorage);}Object.keys(userSessionStorageKeys).forEach(storageEntryKey=>{const key=storageEntryKey;const storageEntry=userSessionStorageKeys[key];stores.forEach(store=>{const migratedVal=this.pluginsManager?.invokeSingle('storage.migrate',storageEntry,store.engine,this.errorHandler,this.logger);if(migratedVal){store.set(storageEntry,migratedVal);}});});}/**
|
1502
1364
|
* A function to initialize sessionTracking
|
1503
1365
|
*/initializeSessionTracking(){const sessionInfo=this.getSessionFromStorage()??defaultSessionInfo;let finalAutoTrackingStatus=!(state.loadOptions.value.sessions.autoTrack===false||sessionInfo.manualTrack===true);let sessionTimeout;const configuredSessionTimeout=state.loadOptions.value.sessions.timeout;if(!isPositiveInteger(configuredSessionTimeout)){this.logger?.warn(TIMEOUT_NOT_NUMBER_WARNING(USER_SESSION_MANAGER,configuredSessionTimeout,DEFAULT_SESSION_TIMEOUT_MS));sessionTimeout=DEFAULT_SESSION_TIMEOUT_MS;}else {sessionTimeout=configuredSessionTimeout;}if(sessionTimeout===0){this.logger?.warn(TIMEOUT_ZERO_WARNING(USER_SESSION_MANAGER));finalAutoTrackingStatus=false;}// In case user provides a timeout value greater than 0 but less than 10 seconds SDK will show a warning
|
1504
1366
|
// and will proceed with it
|
@@ -1510,87 +1372,90 @@ if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}}
|
|
1510
1372
|
* A function to sync values in storage
|
1511
1373
|
* @param key
|
1512
1374
|
* @param value
|
1513
|
-
*/syncValueToStorage(
|
1375
|
+
*/syncValueToStorage(sessionKey,value){const entries=state.storage.entries.value;const storage=entries[sessionKey]?.type;const key=entries[sessionKey]?.key;if(isStorageTypeValidForStoringData(storage)){const curStore=this.storeManager?.getStore(storageClientDataStoreNameMap[storage]);if(value&&isString(value)||isNonEmptyObject(value)){curStore?.set(key,value);}else {curStore?.remove(key);}}}/**
|
1514
1376
|
* Function to update storage whenever state value changes
|
1515
1377
|
*/registerEffects(){/**
|
1516
1378
|
* Update userId in storage automatically when userId is updated in state
|
1517
|
-
*/
|
1379
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.userId,state.session.userId.value);});/**
|
1518
1380
|
* Update user traits in storage automatically when it is updated in state
|
1519
|
-
*/
|
1381
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.userTraits,state.session.userTraits.value);});/**
|
1520
1382
|
* Update group id in storage automatically when it is updated in state
|
1521
|
-
*/
|
1383
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.groupId,state.session.groupId.value);});/**
|
1522
1384
|
* Update group traits in storage automatically when it is updated in state
|
1523
|
-
*/
|
1385
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.groupTraits,state.session.groupTraits.value);});/**
|
1524
1386
|
* Update anonymous user id in storage automatically when it is updated in state
|
1525
|
-
*/
|
1387
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.anonymousId,state.session.anonymousId.value);});/**
|
1526
1388
|
* Update initial referrer in storage automatically when it is updated in state
|
1527
|
-
*/
|
1389
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.initialReferrer,state.session.initialReferrer.value);});/**
|
1528
1390
|
* Update initial referring domain in storage automatically when it is updated in state
|
1529
|
-
*/
|
1391
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.initialReferringDomain,state.session.initialReferringDomain.value);});/**
|
1530
1392
|
* Update session tracking info in storage automatically when it is updated in state
|
1531
|
-
*/
|
1393
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.sessionInfo,state.session.sessionInfo.value);});}/**
|
1532
1394
|
* Sets anonymous id in the following precedence:
|
1533
1395
|
*
|
1534
1396
|
* 1. anonymousId: Id directly provided to the function.
|
1535
1397
|
* 2. rudderAmpLinkerParam: value generated from linker query parm (rudderstack)
|
1536
1398
|
* using parseLinker util.
|
1537
1399
|
* 3. generateUUID: A new unique id is generated and assigned.
|
1538
|
-
*/setAnonymousId(anonymousId,rudderAmpLinkerParam){
|
1400
|
+
*/setAnonymousId(anonymousId,rudderAmpLinkerParam){let finalAnonymousId=anonymousId;const storage=state.storage.entries.value.anonymousId?.type;if(isStorageTypeValidForStoringData(storage)){if(!finalAnonymousId&&rudderAmpLinkerParam){const linkerPluginsResult=this.pluginsManager?.invokeMultiple('userSession.anonymousIdGoogleLinker',rudderAmpLinkerParam);finalAnonymousId=linkerPluginsResult?.[0];}state.session.anonymousId.value=finalAnonymousId||this.generateAnonymousId();}}/**
|
1539
1401
|
* Generate a new anonymousId
|
1540
1402
|
* @returns string anonymousID
|
1541
1403
|
*/generateAnonymousId(){return generateUUID();}/**
|
1542
1404
|
* Fetches anonymousId
|
1543
1405
|
* @param options option to fetch it from external source
|
1544
1406
|
* @returns anonymousId
|
1545
|
-
*/getAnonymousId(options){
|
1546
|
-
|
1547
|
-
const autoCapturedAnonymousId=this.pluginsManager?.invokeSingle('storage.getAnonymousId',getStorageEngine,options);persistedAnonymousId=autoCapturedAnonymousId;}state.session.
|
1407
|
+
*/getAnonymousId(options){const storage=state.storage.entries.value.anonymousId?.type;const key=state.storage.entries.value.anonymousId?.key;let persistedAnonymousId;// fetch the anonymousId from storage
|
1408
|
+
if(isStorageTypeValidForStoringData(storage)){const store=this.storeManager?.getStore(storageClientDataStoreNameMap[storage]);persistedAnonymousId=store?.get(key);if(!persistedAnonymousId&&options){// fetch anonymousId from external source
|
1409
|
+
const autoCapturedAnonymousId=this.pluginsManager?.invokeSingle('storage.getAnonymousId',getStorageEngine,options);persistedAnonymousId=autoCapturedAnonymousId;}state.session.anonymousId.value=persistedAnonymousId||this.generateAnonymousId();}return state.session.anonymousId.value;}getItem(sessionKey){const entries=state.storage.entries.value;const storage=entries[sessionKey]?.type;const key=entries[sessionKey]?.key;if(isStorageTypeValidForStoringData(storage)){const store=this.storeManager?.getStore(storageClientDataStoreNameMap[storage]);return store?.get(key)??null;}return null;}/**
|
1548
1410
|
* Fetches User Id
|
1549
1411
|
* @returns
|
1550
|
-
*/getUserId(){return this.
|
1412
|
+
*/getUserId(){return this.getItem(UserSessionKeys.userId);}/**
|
1551
1413
|
* Fetches User Traits
|
1552
1414
|
* @returns
|
1553
|
-
*/getUserTraits(){return this.
|
1415
|
+
*/getUserTraits(){return this.getItem(UserSessionKeys.userTraits);}/**
|
1554
1416
|
* Fetches Group Id
|
1555
1417
|
* @returns
|
1556
|
-
*/getGroupId(){return this.
|
1418
|
+
*/getGroupId(){return this.getItem(UserSessionKeys.groupId);}/**
|
1557
1419
|
* Fetches Group Traits
|
1558
1420
|
* @returns
|
1559
|
-
*/getGroupTraits(){return this.
|
1421
|
+
*/getGroupTraits(){return this.getItem(UserSessionKeys.groupTraits);}/**
|
1560
1422
|
* Fetches Initial Referrer
|
1561
1423
|
* @returns
|
1562
|
-
*/getInitialReferrer(){return this.
|
1424
|
+
*/getInitialReferrer(){return this.getItem(UserSessionKeys.initialReferrer);}/**
|
1563
1425
|
* Fetches Initial Referring domain
|
1564
1426
|
* @returns
|
1565
|
-
*/getInitialReferringDomain(){return this.
|
1427
|
+
*/getInitialReferringDomain(){return this.getItem(UserSessionKeys.initialReferringDomain);}/**
|
1566
1428
|
* Fetches session tracking information from storage
|
1567
1429
|
* @returns
|
1568
|
-
*/getSessionFromStorage(){return this.
|
1430
|
+
*/getSessionFromStorage(){return this.getItem(UserSessionKeys.sessionInfo);}/**
|
1431
|
+
* If session is active it returns the sessionId
|
1432
|
+
* @returns
|
1433
|
+
*/getSessionId(){if(state.session.sessionInfo.value.autoTrack&&!hasSessionExpired(state.session.sessionInfo.value.expiresAt)||state.session.sessionInfo.value.manualTrack){return state.session.sessionInfo.value.id||null;}return null;}/**
|
1569
1434
|
* A function to update current session info after each event call
|
1570
1435
|
*/refreshSession(){if(state.session.sessionInfo.value.autoTrack||state.session.sessionInfo.value.manualTrack){if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}if(state.session.sessionInfo.value.sessionStart===undefined){state.session.sessionInfo.value={...state.session.sessionInfo.value,sessionStart:true};}else if(state.session.sessionInfo.value.sessionStart){state.session.sessionInfo.value={...state.session.sessionInfo.value,sessionStart:false};}}}/**
|
1571
1436
|
* Reset state values
|
1572
1437
|
* @param resetAnonymousId
|
1573
1438
|
* @param noNewSessionStart
|
1574
1439
|
* @returns
|
1575
|
-
*/reset(resetAnonymousId,noNewSessionStart){const{manualTrack,autoTrack}=state.session.sessionInfo.value;
|
1440
|
+
*/reset(resetAnonymousId,noNewSessionStart){const{manualTrack,autoTrack}=state.session.sessionInfo.value;r(()=>{state.session.userId.value=defaultUserSessionValues.userId;state.session.userTraits.value=defaultUserSessionValues.userTraits;state.session.groupId.value=defaultUserSessionValues.groupId;state.session.groupTraits.value=defaultUserSessionValues.groupTraits;if(resetAnonymousId){state.session.anonymousId.value=defaultUserSessionValues.anonymousId;}if(noNewSessionStart){return;}if(autoTrack){state.session.sessionInfo.value=defaultUserSessionValues.sessionInfo;this.startOrRenewAutoTracking();}else if(manualTrack){this.startManualTrackingInternal();}});}/**
|
1576
1441
|
* Set user Id
|
1577
1442
|
* @param userId
|
1578
|
-
*/setUserId(userId){if(this.
|
1443
|
+
*/setUserId(userId){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.userId)){state.session.userId.value=userId;}}/**
|
1579
1444
|
* Set user traits
|
1580
1445
|
* @param traits
|
1581
|
-
*/setUserTraits(traits){if(
|
1446
|
+
*/setUserTraits(traits){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.userTraits)&&traits){state.session.userTraits.value=mergeDeepRight(state.session.userTraits.value??{},traits);}}/**
|
1582
1447
|
* Set group Id
|
1583
1448
|
* @param groupId
|
1584
|
-
*/setGroupId(groupId){if(this.
|
1449
|
+
*/setGroupId(groupId){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.groupId)){state.session.groupId.value=groupId;}}/**
|
1585
1450
|
* Set group traits
|
1586
1451
|
* @param traits
|
1587
|
-
*/setGroupTraits(traits){if(
|
1452
|
+
*/setGroupTraits(traits){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.groupTraits)&&traits){state.session.groupTraits.value=mergeDeepRight(state.session.groupTraits.value??{},traits);}}/**
|
1588
1453
|
* Set initial referrer
|
1589
1454
|
* @param referrer
|
1590
|
-
*/setInitialReferrer(referrer){if(this.
|
1455
|
+
*/setInitialReferrer(referrer){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.initialReferrer)){state.session.initialReferrer.value=referrer;}}/**
|
1591
1456
|
* Set initial referring domain
|
1592
1457
|
* @param referrer
|
1593
|
-
*/setInitialReferringDomain(
|
1458
|
+
*/setInitialReferringDomain(referringDomain){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.initialReferringDomain)){state.session.initialReferringDomain.value=referringDomain;}}/**
|
1594
1459
|
* A function to check for existing session details and depending on that create a new session.
|
1595
1460
|
*/startOrRenewAutoTracking(){if(hasSessionExpired(state.session.sessionInfo.value.expiresAt)){state.session.sessionInfo.value=generateAutoTrackingSession(state.session.sessionInfo.value.timeout);}else {const timestamp=Date.now();const timeout=state.session.sessionInfo.value.timeout;state.session.sessionInfo.value=mergeDeepRight(state.session.sessionInfo.value,{expiresAt:timestamp+timeout// set the expiry time of the session
|
1596
1461
|
});}}/**
|
@@ -1601,10 +1466,7 @@ const autoCapturedAnonymousId=this.pluginsManager?.invokeSingle('storage.getAnon
|
|
1601
1466
|
* An internal function to start manual session
|
1602
1467
|
*/startManualTrackingInternal(){this.start(Date.now());}/**
|
1603
1468
|
* A public method to end an ongoing session.
|
1604
|
-
*/end(){state.session.sessionInfo.value={};}
|
1605
|
-
* Clear storage
|
1606
|
-
* @param resetAnonymousId
|
1607
|
-
*/clearUserSessionStorage(resetAnonymousId){this.store?.remove(userSessionStorageKeys.userId);this.store?.remove(userSessionStorageKeys.userTraits);this.store?.remove(userSessionStorageKeys.groupId);this.store?.remove(userSessionStorageKeys.groupTraits);if(resetAnonymousId){this.store?.remove(userSessionStorageKeys.anonymousUserId);}}}
|
1469
|
+
*/end(){state.session.sessionInfo.value={};}}
|
1608
1470
|
|
1609
1471
|
/**
|
1610
1472
|
* A buffer queue to serve as a store for any type of data
|
@@ -1612,6 +1474,20 @@ const autoCapturedAnonymousId=this.pluginsManager?.invokeSingle('storage.getAnon
|
|
1612
1474
|
|
1613
1475
|
const DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';const DESTINATIONS_QUEUE_EXT_POINT_PREFIX='destinationsEventsQueue';
|
1614
1476
|
|
1477
|
+
/**
|
1478
|
+
* Filters and returns the user supplied integrations config that should take preference over the destination specific integrations config
|
1479
|
+
* @param eventIntgConfig User supplied integrations config at event level
|
1480
|
+
* @param destinationsIntgConfig Cumulative integrations config from all destinations
|
1481
|
+
* @returns Filtered user supplied integrations config
|
1482
|
+
*/const getOverriddenIntegrationOptions=(eventIntgConfig,destinationsIntgConfig)=>Object.keys(eventIntgConfig).filter(intgName=>eventIntgConfig[intgName]!==true||!destinationsIntgConfig[intgName]).reduce((obj,key)=>{const retVal=clone$1(obj);retVal[key]=eventIntgConfig[key];return retVal;},{});/**
|
1483
|
+
* Returns the event object with final integrations config
|
1484
|
+
* @param event RudderEvent object
|
1485
|
+
* @param state Application state
|
1486
|
+
* @returns Mutated event with final integrations config
|
1487
|
+
*/const getFinalEvent=(event,state)=>{const finalEvent=clone$1(event);// Merge the destination specific integrations config with the event's integrations config
|
1488
|
+
// In general, the preference is given to the event's integrations config
|
1489
|
+
const eventIntgConfig=event.integrations??DEFAULT_INTEGRATIONS_CONFIG;const destinationsIntgConfig=state.nativeDestinations.integrationsConfig.value;const overriddenIntgOpts=getOverriddenIntegrationOptions(eventIntgConfig,destinationsIntgConfig);finalEvent.integrations=mergeDeepRight(destinationsIntgConfig,overriddenIntgOpts);return finalEvent;};
|
1490
|
+
|
1615
1491
|
/**
|
1616
1492
|
* Event repository class responsible for queuing events for further processing and delivery
|
1617
1493
|
*/class EventRepository{/**
|
@@ -1623,16 +1499,16 @@ const DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';const DESTINATION
|
|
1623
1499
|
*/constructor(pluginsManager,storeManager,errorHandler,logger){this.pluginsManager=pluginsManager;this.errorHandler=errorHandler;this.logger=logger;this.httpClient=new HttpClient(errorHandler,logger);this.storeManager=storeManager;this.onError=this.onError.bind(this);}/**
|
1624
1500
|
* Initializes the event repository
|
1625
1501
|
*/init(){this.dataplaneEventsQueue=this.pluginsManager.invokeSingle(`${DATA_PLANE_QUEUE_EXT_POINT_PREFIX}.init`,state,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.errorHandler,this.logger);// Start the queue once the client destinations are ready
|
1626
|
-
|
1502
|
+
E(()=>{if(state.nativeDestinations.clientDestinationsReady.value===true){this.destinationsEventsQueue?.start();}});// Start the queue processing only when the destinations are ready or hybrid mode destinations exist
|
1627
1503
|
// However, events will be enqueued for now.
|
1628
1504
|
// At the time of processing the events, the integrations config data from destinations
|
1629
1505
|
// is merged into the event object
|
1630
|
-
let timeoutId;
|
1506
|
+
let timeoutId;E(()=>{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)&&this.dataplaneEventsQueue?.scheduleTimeoutActive!==true){globalThis.clearTimeout(timeoutId);this.dataplaneEventsQueue?.start();}});// Force start the data plane events queue processing after a timeout
|
1631
1507
|
if(state.loadOptions.value.bufferDataPlaneEventsUntilReady===true){timeoutId=globalThis.setTimeout(()=>{if(this.dataplaneEventsQueue?.scheduleTimeoutActive!==true){this.dataplaneEventsQueue?.start();}},state.loadOptions.value.dataPlaneEventsBufferTimeout);}}/**
|
1632
1508
|
* Enqueues the event for processing
|
1633
1509
|
* @param event RudderEvent object
|
1634
1510
|
* @param callback API callback function
|
1635
|
-
*/enqueue(event,callback){const dpQEvent=
|
1511
|
+
*/enqueue(event,callback){const dpQEvent=getFinalEvent(event,state);this.pluginsManager.invokeSingle(`${DATA_PLANE_QUEUE_EXT_POINT_PREFIX}.enqueue`,state,this.dataplaneEventsQueue,dpQEvent,this.errorHandler,this.logger);const dQEvent=clone$1(event);this.pluginsManager.invokeSingle(`${DESTINATIONS_QUEUE_EXT_POINT_PREFIX}.enqueue`,state,this.destinationsEventsQueue,dQEvent,this.errorHandler,this.logger);// Invoke the callback if it exists
|
1636
1512
|
try{// Using the event sent to the data plane queue here
|
1637
1513
|
// to ensure the mutated (if any) event is sent to the callback
|
1638
1514
|
callback?.(dpQEvent);}catch(error){this.onError(error,API_CALLBACK_INVOKE_ERROR);}}/**
|
@@ -1650,25 +1526,25 @@ callback?.(dpQEvent);}catch(error){this.onError(error,API_CALLBACK_INVOKE_ERROR)
|
|
1650
1526
|
* Start application lifecycle if not already started
|
1651
1527
|
*/load(writeKey,dataPlaneUrl,loadOptions={}){if(state.lifecycle.status.value){return;}let clonedDataPlaneUrl=clone$1(dataPlaneUrl);let clonedLoadOptions=clone$1(loadOptions);// dataPlaneUrl is not provided
|
1652
1528
|
if(isObjectAndNotNull(dataPlaneUrl)){clonedLoadOptions=dataPlaneUrl;clonedDataPlaneUrl=undefined;}// Set initial state values
|
1653
|
-
|
1529
|
+
r(()=>{state.lifecycle.writeKey.value=writeKey;state.lifecycle.dataPlaneUrl.value=clonedDataPlaneUrl;state.loadOptions.value=normalizeLoadOptions(state.loadOptions.value,clonedLoadOptions);state.lifecycle.status.value=LifecycleStatus.Mounted;});// Expose state to global objects
|
1654
1530
|
setExposedGlobal('state',state,writeKey);// Configure initial config of any services or components here
|
1655
1531
|
// State application lifecycle
|
1656
1532
|
this.startLifecycle();}// Start lifecycle methods
|
1657
1533
|
/**
|
1658
1534
|
* Orchestrate the lifecycle of the application phases/status
|
1659
|
-
*/startLifecycle(){
|
1535
|
+
*/startLifecycle(){E(()=>{try{switch(state.lifecycle.status.value){case LifecycleStatus.Mounted:this.prepareBrowserCapabilities();break;case LifecycleStatus.BrowserCapabilitiesReady:// initialize the preloaded events enqueuing
|
1660
1536
|
retrievePreloadBufferEvents(this);this.prepareInternalServices();this.loadConfig();break;case LifecycleStatus.Configured:this.loadPlugins();break;case LifecycleStatus.PluginsLoading:break;case LifecycleStatus.PluginsReady:this.init();break;case LifecycleStatus.Initialized:this.onInitialized();break;case LifecycleStatus.Loaded:this.loadDestinations();this.processBufferedEvents();break;case LifecycleStatus.DestinationsLoading:break;case LifecycleStatus.DestinationsReady:this.onDestinationsReady();break;case LifecycleStatus.Ready:this.onReady();break;default:break;}}catch(err){const issue='Failed to load the SDK';this.errorHandler.onError(getMutatedError(err,issue),ANALYTICS_CORE);}});}/**
|
1661
1537
|
* Load browser polyfill if required
|
1662
1538
|
*/prepareBrowserCapabilities(){this.capabilitiesManager.init();}/**
|
1663
1539
|
* Enqueue in SDK preload buffer events, used from preloadBuffer component
|
1664
1540
|
*/enqueuePreloadBufferEvents(bufferedEvents){if(Array.isArray(bufferedEvents)){bufferedEvents.forEach(bufferedEvent=>this.preloadBuffer.enqueue(clone$1(bufferedEvent)));}}/**
|
1665
1541
|
* Process the buffer preloaded events by passing their arguments to the respective facade methods
|
1666
|
-
*/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.errorHandler,this.logger,this.pluginsManager);this.eventRepository=new EventRepository(this.pluginsManager,this.storeManager,this.errorHandler,this.logger);this.eventManager=new EventManager(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger);}/**
|
1542
|
+
*/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.errorHandler,this.logger,this.pluginsManager,this.storeManager);this.eventRepository=new EventRepository(this.pluginsManager,this.storeManager,this.errorHandler,this.logger);this.eventManager=new EventManager(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger);}/**
|
1667
1543
|
* Load configuration
|
1668
1544
|
*/loadConfig(){if(!state.lifecycle.writeKey.value){this.errorHandler.onError(new Error('A write key is required to load the SDK. Please provide a valid write key.'),LOAD_CONFIGURATION);return;}this.httpClient.setAuthHeader(state.lifecycle.writeKey.value);this.configManager?.init();}/**
|
1669
1545
|
* Initialize the storage and event queue
|
1670
1546
|
*/init(){this.errorHandler.init(this.externalSrcLoader);// Initialize storage
|
1671
|
-
this.storeManager?.init();this.
|
1547
|
+
this.storeManager?.init();this.userSessionManager?.init();// Initialize consent manager
|
1672
1548
|
if(state.consents.activeConsentManagerPluginName.value){this.pluginsManager?.invokeSingle(`consentManager.init`,state,this.storeManager,this.logger);}// Initialize event manager
|
1673
1549
|
this.eventManager?.init();// Mark the SDK as initialized
|
1674
1550
|
state.lifecycle.status.value=LifecycleStatus.Initialized;}/**
|
@@ -1682,7 +1558,7 @@ this.processDataInPreloadBuffer();// TODO: we need to avoid passing the window o
|
|
1682
1558
|
// as this will prevent us from supporting multiple SDK instances in the same page
|
1683
1559
|
// Execute onLoaded callback if provided in load options
|
1684
1560
|
if(isFunction(state.loadOptions.value.onLoaded)){state.loadOptions.value.onLoaded(globalThis.rudderanalytics);}// Set lifecycle state
|
1685
|
-
|
1561
|
+
r(()=>{state.lifecycle.loaded.value=true;state.lifecycle.status.value=LifecycleStatus.Loaded;});this.initialized=true;// Emit an event to use as substitute to the onLoaded callback
|
1686
1562
|
const initializedEvent=new CustomEvent('RSA_Initialised',{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:true,cancelable:true,composed:true});globalThis.document.dispatchEvent(initializedEvent);}/**
|
1687
1563
|
* Emit ready event
|
1688
1564
|
*/ // eslint-disable-next-line class-methods-use-this
|
@@ -1695,7 +1571,7 @@ state.eventBuffer.toBeProcessedArray.value.forEach(bufferedItem=>{const methodNa
|
|
1695
1571
|
*/loadDestinations(){// Set in state the desired activeDestinations to inject in DOM
|
1696
1572
|
this.pluginsManager?.invokeSingle('nativeDestinations.setActiveDestinations',state,this.pluginsManager,this.errorHandler,this.logger);const totalDestinationsToLoad=state.nativeDestinations.activeDestinations.value.length;if(totalDestinationsToLoad===0){state.lifecycle.status.value=LifecycleStatus.DestinationsReady;return;}// Start loading native integration scripts and create instances
|
1697
1573
|
state.lifecycle.status.value=LifecycleStatus.DestinationsLoading;this.pluginsManager?.invokeSingle('nativeDestinations.load',state,this.externalSrcLoader,this.errorHandler,this.logger);// Progress to next lifecycle phase if all native destinations are initialized or failed
|
1698
|
-
|
1574
|
+
E(()=>{const areAllDestinationsReady=totalDestinationsToLoad===0||state.nativeDestinations.initializedDestinations.value.length+state.nativeDestinations.failedDestinations.value.length===totalDestinationsToLoad;if(areAllDestinationsReady){r(()=>{state.lifecycle.status.value=LifecycleStatus.DestinationsReady;state.nativeDestinations.clientDestinationsReady.value=true;});}});}/**
|
1699
1575
|
* Invoke the ready callbacks if any exist
|
1700
1576
|
*/ // eslint-disable-next-line class-methods-use-this
|
1701
1577
|
onDestinationsReady(){state.eventBuffer.readyCallbacksArray.value.forEach(callback=>{try{callback();}catch(err){this.errorHandler.onError(err,ANALYTICS_CORE,READY_CALLBACK_INVOKE_ERROR);}});state.lifecycle.status.value=LifecycleStatus.Ready;}// End lifecycle methods
|
@@ -1717,7 +1593,7 @@ getUserId(){return state.session.userId.value;}// eslint-disable-next-line class
|
|
1717
1593
|
getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
|
1718
1594
|
getGroupId(){return state.session.groupId.value;}// eslint-disable-next-line class-methods-use-this
|
1719
1595
|
getGroupTraits(){return state.session.groupTraits.value;}startSession(sessionId){const type='startSession';this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,sessionId]);return;}this.userSessionManager?.start(sessionId);}endSession(){const type='endSession';this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type]);return;}this.userSessionManager?.end();}// eslint-disable-next-line class-methods-use-this
|
1720
|
-
getSessionId(){this.userSessionManager?.
|
1596
|
+
getSessionId(){const sessionId=this.userSessionManager?.getSessionId();return sessionId??null;}// End consumer exposed methods
|
1721
1597
|
}
|
1722
1598
|
|
1723
1599
|
/*
|
@@ -1735,7 +1611,7 @@ this.triggerBufferedLoadEvent();}/**
|
|
1735
1611
|
* Set instance to use if no specific writeKey is provided in methods
|
1736
1612
|
* automatically for the first created instance
|
1737
1613
|
* TODO: to support multiple analytics instances in the near future
|
1738
|
-
*/setDefaultInstanceKey(writeKey){if(
|
1614
|
+
*/setDefaultInstanceKey(writeKey){if(writeKey){this.defaultAnalyticsKey=writeKey;}}/**
|
1739
1615
|
* Retrieve an existing analytics instance
|
1740
1616
|
*/getAnalyticsInstance(writeKey){const instanceId=writeKey??this.defaultAnalyticsKey;const analyticsInstanceExists=Boolean(this.analyticsInstances[instanceId]);if(!analyticsInstanceExists){this.analyticsInstances[instanceId]=new Analytics();}return this.analyticsInstances[instanceId];}/**
|
1741
1617
|
* Create new analytics instance and trigger application lifecycle start
|