@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
@@ -8,21 +8,24 @@
|
|
8
8
|
* Represents the options parameter for anonymousId
|
9
9
|
*/ /**
|
10
10
|
* Represents the beacon queue options parameter in loadOptions type
|
11
|
-
*/
|
11
|
+
*/ /**
|
12
12
|
* Represents the queue options parameter in loadOptions type
|
13
13
|
*/ /**
|
14
14
|
* Represents the destinations queue options parameter in loadOptions type
|
15
|
-
*/
|
15
|
+
*/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;}({});/**
|
16
16
|
* Represents the options parameter in the load API
|
17
17
|
*/
|
18
18
|
|
19
|
+
let StorageEncryptionVersion=/*#__PURE__*/function(StorageEncryptionVersion){StorageEncryptionVersion["Legacy"]="legacy";StorageEncryptionVersion["V3"]="v3";return StorageEncryptionVersion;}({});// default
|
20
|
+
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;}({});
|
21
|
+
|
19
22
|
/**
|
20
23
|
* Represents residency server input the options
|
21
24
|
*/let ResidencyServerRegion=/*#__PURE__*/function(ResidencyServerRegion){ResidencyServerRegion["US"]="US";ResidencyServerRegion["EU"]="EU";return ResidencyServerRegion;}({});
|
22
25
|
|
23
26
|
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;}({});
|
24
27
|
|
25
|
-
let PluginName=/*#__PURE__*/function(PluginName){PluginName["BeaconQueue"]="BeaconQueue";PluginName["DeviceModeDestinations"]="DeviceModeDestinations";PluginName["DeviceModeTransformation"]="DeviceModeTransformation";PluginName["ErrorReporting"]="ErrorReporting";PluginName["ExternalAnonymousId"]="ExternalAnonymousId";PluginName["GoogleLinker"]="GoogleLinker";PluginName["
|
28
|
+
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;}({});
|
26
29
|
|
27
30
|
function _isPlaceholder(a){return a!=null&&typeof a==='object'&&a['@@functional/placeholder']===true;}
|
28
31
|
|
@@ -53,57 +56,8 @@
|
|
53
56
|
* @return {Function} The curried function.
|
54
57
|
*/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);}};}
|
55
58
|
|
56
|
-
/**
|
57
|
-
* Tests whether or not an object is an array.
|
58
|
-
*
|
59
|
-
* @private
|
60
|
-
* @param {*} val The object to test.
|
61
|
-
* @return {Boolean} `true` if `val` is an array, `false` otherwise.
|
62
|
-
* @example
|
63
|
-
*
|
64
|
-
* _isArray([]); //=> true
|
65
|
-
* _isArray(null); //=> false
|
66
|
-
* _isArray({}); //=> false
|
67
|
-
*/const _isArray = Array.isArray||function _isArray(val){return val!=null&&val.length>=0&&Object.prototype.toString.call(val)==='[object Array]';};
|
68
|
-
|
69
|
-
function _arrayFromIterator(iter){var list=[];var next;while(!(next=iter.next()).done){list.push(next.value);}return list;}
|
70
|
-
|
71
|
-
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;}
|
72
|
-
|
73
|
-
function _functionName(f){// String(x => x) evaluates to "x => x", so the pattern may not match.
|
74
|
-
var match=String(f).match(/^function (\w*)/);return match==null?'':match[1];}
|
75
|
-
|
76
59
|
function _has(prop,obj){return Object.prototype.hasOwnProperty.call(obj,prop);}
|
77
60
|
|
78
|
-
// Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
|
79
|
-
function _objectIs(a,b){// SameValue algorithm
|
80
|
-
if(a===b){// Steps 1-5, 7-10
|
81
|
-
// Steps 6.b-6.e: +0 != -0
|
82
|
-
return a!==0||1/a===1/b;}else {// Step 6.a: NaN == NaN
|
83
|
-
return a!==a&&b!==b;}}const _objectIs$1 = typeof Object.is==='function'?Object.is:_objectIs;
|
84
|
-
|
85
|
-
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);};}();
|
86
|
-
|
87
|
-
var hasEnumBug=!/*#__PURE__*/{toString:null}.propertyIsEnumerable('toString');var nonEnumerableProps=['constructor','valueOf','isPrototypeOf','toString','propertyIsEnumerable','hasOwnProperty','toLocaleString'];// Safari bug
|
88
|
-
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;};/**
|
89
|
-
* Returns a list containing the names of all the enumerable own properties of
|
90
|
-
* the supplied object.
|
91
|
-
* Note that the order of the output array is not guaranteed to be consistent
|
92
|
-
* across different JS platforms.
|
93
|
-
*
|
94
|
-
* @func
|
95
|
-
* @memberOf R
|
96
|
-
* @since v0.1.0
|
97
|
-
* @category Object
|
98
|
-
* @sig {k: v} -> [k]
|
99
|
-
* @param {Object} obj The object to extract properties from
|
100
|
-
* @return {Array} An array of the object's own properties.
|
101
|
-
* @see R.keysIn, R.values, R.toPairs
|
102
|
-
* @example
|
103
|
-
*
|
104
|
-
* R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c']
|
105
|
-
*/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;});
|
106
|
-
|
107
61
|
/**
|
108
62
|
* Gives a single-word string description of the (native) type of a value,
|
109
63
|
* returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not
|
@@ -130,45 +84,6 @@
|
|
130
84
|
* R.type(undefined); //=> "Undefined"
|
131
85
|
*/var type=/*#__PURE__*/_curry1(function type(val){return val===null?'Null':val===undefined?'Undefined':Object.prototype.toString.call(val).slice(8,-1);});
|
132
86
|
|
133
|
-
/**
|
134
|
-
* private _uniqContentEquals function.
|
135
|
-
* That function is checking equality of 2 iterator contents with 2 assumptions
|
136
|
-
* - iterators lengths are the same
|
137
|
-
* - iterators values are unique
|
138
|
-
*
|
139
|
-
* false-positive result will be returned for comparison of, e.g.
|
140
|
-
* - [1,2,3] and [1,2,3,4]
|
141
|
-
* - [1,1,1] and [1,2,3]
|
142
|
-
* */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*
|
143
|
-
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.
|
144
|
-
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;}
|
145
|
-
|
146
|
-
/**
|
147
|
-
* Returns `true` if its arguments are equivalent, `false` otherwise. Handles
|
148
|
-
* cyclical data structures.
|
149
|
-
*
|
150
|
-
* Dispatches symmetrically to the `equals` methods of both arguments, if
|
151
|
-
* present.
|
152
|
-
*
|
153
|
-
* @func
|
154
|
-
* @memberOf R
|
155
|
-
* @since v0.15.0
|
156
|
-
* @category Relation
|
157
|
-
* @sig a -> b -> Boolean
|
158
|
-
* @param {*} a
|
159
|
-
* @param {*} b
|
160
|
-
* @return {Boolean}
|
161
|
-
* @example
|
162
|
-
*
|
163
|
-
* R.equals(1, 1); //=> true
|
164
|
-
* R.equals(1, '1'); //=> false
|
165
|
-
* R.equals([1, 2, 3], [1, 2, 3]); //=> true
|
166
|
-
*
|
167
|
-
* const a = {}; a.v = a;
|
168
|
-
* const b = {}; b.v = b;
|
169
|
-
* R.equals(a, b); //=> true
|
170
|
-
*/var equals=/*#__PURE__*/_curry2(function equals(a,b){return _equals(a,b,[],[]);});
|
171
|
-
|
172
87
|
function _isObject(x){return Object.prototype.toString.call(x)==='[object Object]';}
|
173
88
|
|
174
89
|
/**
|
@@ -253,71 +168,6 @@
|
|
253
168
|
* objects[0] === objectsClone[0]; //=> false
|
254
169
|
*/var clone=/*#__PURE__*/_curry1(function clone(value){return value!=null&&typeof value.clone==='function'?value.clone():_clone(value,true);});const clone$1 = clone;
|
255
170
|
|
256
|
-
/**
|
257
|
-
* Tests whether or not an object is a typed array.
|
258
|
-
*
|
259
|
-
* @private
|
260
|
-
* @param {*} val The object to test.
|
261
|
-
* @return {Boolean} `true` if `val` is a typed array, `false` otherwise.
|
262
|
-
* @example
|
263
|
-
*
|
264
|
-
* _isTypedArray(new Uint8Array([])); //=> true
|
265
|
-
* _isTypedArray(new Float32Array([])); //=> true
|
266
|
-
* _isTypedArray([]); //=> false
|
267
|
-
* _isTypedArray(null); //=> false
|
268
|
-
* _isTypedArray({}); //=> false
|
269
|
-
*/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]';}
|
270
|
-
|
271
|
-
/**
|
272
|
-
* Returns the empty value of its argument's type. Ramda defines the empty
|
273
|
-
* value of Array (`[]`), Object (`{}`), String (`''`),
|
274
|
-
* TypedArray (`Uint8Array []`, `Float32Array []`, etc), and Arguments. Other
|
275
|
-
* types are supported if they define `<Type>.empty`,
|
276
|
-
* `<Type>.prototype.empty` or implement the
|
277
|
-
* [FantasyLand Monoid spec](https://github.com/fantasyland/fantasy-land#monoid).
|
278
|
-
*
|
279
|
-
* Dispatches to the `empty` method of the first argument, if present.
|
280
|
-
*
|
281
|
-
* @func
|
282
|
-
* @memberOf R
|
283
|
-
* @since v0.3.0
|
284
|
-
* @category Function
|
285
|
-
* @sig a -> a
|
286
|
-
* @param {*} x
|
287
|
-
* @return {*}
|
288
|
-
* @example
|
289
|
-
*
|
290
|
-
* R.empty(Just(42)); //=> Nothing()
|
291
|
-
* R.empty([1, 2, 3]); //=> []
|
292
|
-
* R.empty('unicorns'); //=> ''
|
293
|
-
* R.empty({x: 1, y: 2}); //=> {}
|
294
|
-
* R.empty(Uint8Array.from('123')); //=> Uint8Array []
|
295
|
-
*/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
|
296
|
-
;});
|
297
|
-
|
298
|
-
/**
|
299
|
-
* Returns `true` if the given value is its type's empty value; `false`
|
300
|
-
* otherwise.
|
301
|
-
*
|
302
|
-
* @func
|
303
|
-
* @memberOf R
|
304
|
-
* @since v0.1.0
|
305
|
-
* @category Logic
|
306
|
-
* @sig a -> Boolean
|
307
|
-
* @param {*} x
|
308
|
-
* @return {Boolean}
|
309
|
-
* @see R.empty
|
310
|
-
* @example
|
311
|
-
*
|
312
|
-
* R.isEmpty([1, 2, 3]); //=> false
|
313
|
-
* R.isEmpty([]); //=> true
|
314
|
-
* R.isEmpty(''); //=> true
|
315
|
-
* R.isEmpty(null); //=> false
|
316
|
-
* R.isEmpty({}); //=> true
|
317
|
-
* R.isEmpty({length: 0}); //=> false
|
318
|
-
* R.isEmpty(Uint8Array.from('')); //=> true
|
319
|
-
*/var isEmpty=/*#__PURE__*/_curry1(function isEmpty(x){return x!=null&&equals(x,empty(x));});const isEmpty$1 = isEmpty;
|
320
|
-
|
321
171
|
/**
|
322
172
|
* Retrieves the values at given paths of an object.
|
323
173
|
*
|
@@ -495,6 +345,10 @@
|
|
495
345
|
* @param value input value
|
496
346
|
* @returns boolean
|
497
347
|
*/const isDefinedAndNotNull=value=>!isNullOrUndefined(value);/**
|
348
|
+
* A function to check given value is defined and not null
|
349
|
+
* @param value input value
|
350
|
+
* @returns boolean
|
351
|
+
*/const isDefinedNotNullAndNotEmptyString=value=>isDefinedAndNotNull(value)&&value!=='';/**
|
498
352
|
* Determines if the input is an instance of Error
|
499
353
|
* @param obj input value
|
500
354
|
* @returns true if the input is an instance of Error and false otherwise
|
@@ -581,7 +435,7 @@
|
|
581
435
|
|
582
436
|
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';
|
583
437
|
|
584
|
-
const APP_NAME='RudderLabs JavaScript SDK';const APP_VERSION='3.0.0-beta.
|
438
|
+
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';
|
585
439
|
|
586
440
|
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';
|
587
441
|
|
@@ -689,7 +543,7 @@
|
|
689
543
|
* Handle errors
|
690
544
|
*/onError(error){if(this.hasErrorHandler){this.errorHandler?.onError(error,EXTERNAL_SRC_LOADER);}else {throw error;}}}
|
691
545
|
|
692
|
-
function i(){throw new Error("Cycle detected");}function t(){if(!(
|
546
|
+
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);}
|
693
547
|
|
694
548
|
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;}({});
|
695
549
|
|
@@ -715,45 +569,46 @@
|
|
715
569
|
if(!isString(data[0])){styledLogArgs.push(data[0]);}// append rest of the original arguments
|
716
570
|
styledLogArgs.push(...data.slice(1));return styledLogArgs;}return data;}}const defaultLogger=new Logger();
|
717
571
|
|
718
|
-
let StorageEncryptionVersion=/*#__PURE__*/function(StorageEncryptionVersion){StorageEncryptionVersion["Legacy"]="legacy";StorageEncryptionVersion["V3"]="v3";return StorageEncryptionVersion;}({});// default
|
719
|
-
const SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','sessionStorage','none'];const DEFAULT_STORAGE_TYPE='cookieStorage';
|
720
|
-
|
721
572
|
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
|
722
573
|
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
|
723
|
-
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
|
574
|
+
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
|
575
|
+
|
576
|
+
const CDN_INT_DIR='js-integrations';const CDN_PLUGINS_DIR='plugins';
|
724
577
|
|
725
|
-
const BUILD_TYPE='modern';const SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';const CDN_ARCH_VERSION_DIR='v3';const
|
578
|
+
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
|
726
579
|
// const DEST_SDK_BASE_URL = `${SDK_CDN_BASE_URL}/latest/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${CDN_INT_DIR}`;
|
727
580
|
// const PLUGINS_BASE_URL = `${SDK_CDN_BASE_URL}/latest/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${CDN_PLUGINS_DIR}`;
|
728
581
|
const DEFAULT_CONFIG_BE_URL='https://api.rudderstack.com';
|
729
582
|
|
730
583
|
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};
|
731
584
|
|
732
|
-
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=
|
585
|
+
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));
|
733
586
|
|
734
|
-
const
|
587
|
+
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:{}};
|
735
588
|
|
736
|
-
const
|
589
|
+
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)};
|
737
590
|
|
738
|
-
const
|
591
|
+
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)};
|
739
592
|
|
740
|
-
const
|
593
|
+
const reportingState={isErrorReportingEnabled:d(false),isMetricsReportingEnabled:d(false),errorReportingProviderPluginName:d(undefined)};
|
741
594
|
|
742
|
-
const
|
595
|
+
const sourceConfigState=d(undefined);
|
743
596
|
|
744
|
-
const
|
597
|
+
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)};
|
745
598
|
|
746
|
-
const
|
599
|
+
const consentsState={data:d({initialized:false}),activeConsentManagerPluginName:d(undefined),preConsentOptions:d({enabled:false})};
|
747
600
|
|
748
|
-
const
|
601
|
+
const metricsState={retries:d(0),dropped:d(0),sent:d(0),queued:d(0),triggered:d(0)};
|
749
602
|
|
750
|
-
const
|
603
|
+
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)};
|
751
604
|
|
752
|
-
const
|
605
|
+
const nativeDestinationsState={configuredDestinations:d([]),activeDestinations:d([]),loadOnlyIntegrations:d({}),failedDestinations:d([]),loadIntegration:d(true),initializedDestinations:d([]),clientDestinationsReady:d(false),integrationsConfig:d({})};
|
753
606
|
|
754
|
-
const
|
607
|
+
const eventBufferState={toBeProcessedArray:d([]),readyCallbacksArray:d([])};
|
755
608
|
|
756
|
-
const
|
609
|
+
const pluginsState={ready:d(false),loadedPlugins:d([]),failedPlugins:d([]),pluginsToLoadFromConfig:d([]),activePlugins:d([]),totalPluginsToLoad:d(0)};
|
610
|
+
|
611
|
+
const storageState={encryptionPluginName:d(undefined),migrate:d(false),type:d(undefined),cookie:d(undefined),entries:d({}),trulyAnonymousTracking:d(false)};
|
757
612
|
|
758
613
|
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)};
|
759
614
|
|
@@ -815,7 +670,7 @@
|
|
815
670
|
*/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];
|
816
671
|
|
817
672
|
const remotesMap = {
|
818
|
-
'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.
|
673
|
+
'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'}
|
819
674
|
};
|
820
675
|
const loadJS = async (url, fn) => {
|
821
676
|
const resolvedUrl = typeof url === 'function' ? await url() : url;
|
@@ -887,7 +742,7 @@
|
|
887
742
|
|
888
743
|
/**
|
889
744
|
* Get the lazy loaded dynamic import for a plugin name
|
890
|
-
*/const getFederatedModuleImport=pluginName=>{switch(pluginName){case PluginName.BeaconQueue:return ()=>__federation_method_getRemote("rudderAnalyticsRemotePlugins" , "./BeaconQueue").then(module=>__federation_method_wrapDefault(module, true));case PluginName.
|
745
|
+
*/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;}};/**
|
891
746
|
* Map of active plugin names to their dynamic import
|
892
747
|
*/const modernBuildPluginImports=activePluginNames=>{const remotePlugins={};activePluginNames.forEach(pluginName=>{if(remotePluginNames.includes(pluginName)){const lazyLoadImport=getFederatedModuleImport(pluginName);if(lazyLoadImport){remotePlugins[pluginName]=lazyLoadImport;}}});return remotePlugins;};
|
893
748
|
|
@@ -908,7 +763,7 @@
|
|
908
763
|
{setExposedGlobal('pluginsCDNPath',state.lifecycle.pluginsCDNPath.value);}this.setActivePlugins();this.registerLocalPlugins();this.registerRemotePlugins();this.attachEffects();}/**
|
909
764
|
* Update state based on plugin loaded status
|
910
765
|
*/ // eslint-disable-next-line class-methods-use-this
|
911
|
-
attachEffects(){
|
766
|
+
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.
|
912
767
|
// Should we stop here or should we progress?
|
913
768
|
state.lifecycle.status.value=LifecycleStatus.PluginsReady;});}});}/**
|
914
769
|
* Determine the list of plugins that should be loaded based on sourceConfig & load options
|
@@ -923,7 +778,7 @@
|
|
923
778
|
if(!state.storage.migrate.value){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(pluginName=>pluginName!==PluginName.StorageMigrator);}return [...Object.keys(getMandatoryPluginsMap()),...pluginsToLoadFromConfig];}/**
|
924
779
|
* Determine the list of plugins that should be activated
|
925
780
|
*/setActivePlugins(){const pluginsToLoad=this.getPluginsToLoadBasedOnConfig();// Merging available mandatory and optional plugin name list
|
926
|
-
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(',')}`));}
|
781
|
+
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;});}/**
|
927
782
|
* Register plugins that are direct imports to PluginEngine
|
928
783
|
*/registerLocalPlugins(){Object.values(pluginsInventory).forEach(localPlugin=>{if(state.plugins.activePlugins.value.includes(localPlugin().name)){this.register([localPlugin()]);}});}/**
|
929
784
|
* Register plugins that are dynamic imports to PluginEngine
|
@@ -971,22 +826,11 @@
|
|
971
826
|
|
972
827
|
const COOKIE_STORAGE='cookieStorage';const LOCAL_STORAGE='localStorage';const SESSION_STORAGE='sessionStorage';const MEMORY_STORAGE='memoryStorage';const NO_STORAGE='none';
|
973
828
|
|
974
|
-
|
975
|
-
|
976
|
-
/**
|
977
|
-
* To get the current timestamp in ISO string format
|
978
|
-
* @returns ISO formatted timestamp string
|
979
|
-
*/const getCurrentTimeFormatted=()=>{const curDateTime=new Date().toISOString();return curDateTime;};
|
980
|
-
|
981
|
-
function random(len){return crypto.getRandomValues(new Uint8Array(len));}
|
982
|
-
|
983
|
-
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;}
|
984
|
-
|
985
|
-
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;}
|
829
|
+
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;}({});
|
986
830
|
|
987
|
-
const
|
831
|
+
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';
|
988
832
|
|
989
|
-
const
|
833
|
+
const storageClientDataStoreNameMap={[COOKIE_STORAGE]:CLIENT_DATA_STORE_COOKIE,[LOCAL_STORAGE]:CLIENT_DATA_STORE_LS,[MEMORY_STORAGE]:CLIENT_DATA_STORE_MEMORY};
|
990
834
|
|
991
835
|
const detectAdBlockers=(errorHandler,logger)=>{// Apparently, '?view=ad' is a query param that is blocked by majority of adblockers
|
992
836
|
// Use source config URL here as it is very unlikely to be blocked by adblockers
|
@@ -998,7 +842,7 @@
|
|
998
842
|
// Often adblockers instead of blocking the request, they redirect it to an internal URL
|
999
843
|
state.capabilities.isAdBlocked.value=details?.error!==undefined||details?.xhr?.responseURL!==url;}});};
|
1000
844
|
|
1001
|
-
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\./));
|
845
|
+
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\./));
|
1002
846
|
|
1003
847
|
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();});}};
|
1004
848
|
|
@@ -1086,7 +930,8 @@
|
|
1086
930
|
// Error: QuotaExceededError
|
1087
931
|
function dealIncognito(storage){var _KEY='_Is_Incognit',_VALUE='yes';try{// NOTE: set default storage when not passed in
|
1088
932
|
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
|
1089
|
-
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){
|
933
|
+
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
|
934
|
+
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);
|
1090
935
|
|
1091
936
|
// check if the get, set overloads and search methods are used at all
|
1092
937
|
// if we do, ensure we provide types to support overloads as per storejs docs
|
@@ -1147,12 +992,14 @@
|
|
1147
992
|
* A service to manage stores & available storage client configurations
|
1148
993
|
*/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);}/**
|
1149
994
|
* Configure available storage client instances
|
1150
|
-
*/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;}/**
|
995
|
+
*/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;}/**
|
1151
996
|
* Create store to persist data used by the SDK like session, used details etc
|
1152
|
-
*/initClientDataStore(){const
|
1153
|
-
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));}
|
997
|
+
*/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
|
998
|
+
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
|
1154
999
|
// TODO: should we pass the keys for all in order to validate or leave free as v1.1?
|
1155
|
-
|
1000
|
+
// Initializing all the enabled store because previous user data might be in different storage
|
1001
|
+
// that needs auto migration
|
1002
|
+
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});});}/**
|
1156
1003
|
* Create a new store
|
1157
1004
|
*/setStore(storeConfig){const storageEngine=getStorageEngine(storeConfig.type);this.stores[storeConfig.id]=new Store(storeConfig,storageEngine,this.pluginsManager);return this.stores[storeConfig.id];}/**
|
1158
1005
|
* Retrieve a store
|
@@ -1208,7 +1055,7 @@
|
|
1208
1055
|
*/const isPositiveInteger=num=>isNumber(num)&&num>=0&&Number.isInteger(num);
|
1209
1056
|
|
1210
1057
|
const normalizeLoadOptions=(loadOptionsFromState,loadOptions)=>{// TODO: Maybe add warnings for invalid values
|
1211
|
-
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
|
1058
|
+
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
|
1212
1059
|
// doesn't seem to throw errors for empty URLs
|
1213
1060
|
// TODO: Need to improve this check to find out if the URL is valid or not
|
1214
1061
|
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}`;};
|
@@ -1236,21 +1083,39 @@
|
|
1236
1083
|
if(serverUrl){return serverUrl;}// return undefined if data plane url can not be determined
|
1237
1084
|
return undefined;};
|
1238
1085
|
|
1086
|
+
const DEFAULT_PRE_CONSENT_STORAGE_STRATEGY=StorageStrategy.None;const DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE=DeliveryType.Immediate;
|
1087
|
+
|
1239
1088
|
const isErrorReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.errors?.enabled===true;const getErrorReportingProviderNameFromConfig=sourceConfig=>sourceConfig?.statsCollection?.errors?.provider;const isMetricsReportingEnabled=sourceConfig=>sourceConfig?.statsCollection?.metrics?.enabled===true;
|
1240
1089
|
|
1090
|
+
/**
|
1091
|
+
* A function to get the name of the consent manager with enabled true set in the load options
|
1092
|
+
* @param cookieConsentOptions Input provided as load option
|
1093
|
+
* @returns string|undefined
|
1094
|
+
*
|
1095
|
+
* Example input: {
|
1096
|
+
* oneTrust:{
|
1097
|
+
* enabled: true
|
1098
|
+
* }
|
1099
|
+
* }
|
1100
|
+
*
|
1101
|
+
* Output: 'oneTrust'
|
1102
|
+
*/const getUserSelectedConsentManager=cookieConsentOptions=>{if(!isNonEmptyObject(cookieConsentOptions)){return undefined;}const validCookieConsentOptions=cookieConsentOptions;return Object.keys(validCookieConsentOptions).find(e=>e&&validCookieConsentOptions[e].enabled===true);};
|
1103
|
+
|
1241
1104
|
/**
|
1242
1105
|
* Determines the SDK url
|
1243
1106
|
* @returns sdkURL
|
1244
|
-
*/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;})
|
1245
|
-
return sdkURL;};/**
|
1107
|
+
*/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;};/**
|
1246
1108
|
* Updates the reporting state variables from the source config data
|
1247
1109
|
* @param res Source config
|
1248
1110
|
* @param logger Logger instance
|
1249
1111
|
*/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
|
1250
1112
|
const errReportingProviderPlugin=errReportingProvider?ErrorReportingProvidersToPluginNameMap[errReportingProvider]:undefined;if(!isUndefined(errReportingProvider)&&!errReportingProviderPlugin){// set the default error reporting provider
|
1251
|
-
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=>{
|
1252
|
-
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;}
|
1253
|
-
const configuredMigrationValue=
|
1113
|
+
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
|
1114
|
+
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
|
1115
|
+
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
|
1116
|
+
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
|
1117
|
+
consentManagerPluginName=ConsentManagersToPluginNameMap[selectedConsentManager];if(!consentManagerPluginName){logger?.error(UNSUPPORTED_CONSENT_MANAGER_ERROR(CONFIG_MANAGER,selectedConsentManager,ConsentManagersToPluginNameMap));}}// Pre-consent
|
1118
|
+
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};});};
|
1254
1119
|
|
1255
1120
|
/**
|
1256
1121
|
* A function that determines integration SDK loading path
|
@@ -1269,43 +1134,25 @@
|
|
1269
1134
|
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
|
1270
1135
|
const sdkURL=getSDKUrl();pluginsCDNPath=sdkURL&&isString(sdkURL)?sdkURL.split('/').slice(0,-1).concat(CDN_PLUGINS_DIR).join('/'):PLUGINS_BASE_URL;return pluginsCDNPath;};
|
1271
1136
|
|
1272
|
-
/**
|
1273
|
-
* A function to get the name of the consent manager with enabled true set in the load options
|
1274
|
-
* @param cookieConsentOptions Input provided as load option
|
1275
|
-
* @returns string|undefined
|
1276
|
-
*
|
1277
|
-
* Example input: {
|
1278
|
-
* oneTrust:{
|
1279
|
-
* enabled: true
|
1280
|
-
* }
|
1281
|
-
* }
|
1282
|
-
*
|
1283
|
-
* Output: 'oneTrust'
|
1284
|
-
*/const getUserSelectedConsentManager=cookieConsentOptions=>{if(!isNonEmptyObject(cookieConsentOptions)){return undefined;}const validCookieConsentOptions=cookieConsentOptions;return Object.keys(validCookieConsentOptions).find(e=>e&&validCookieConsentOptions[e].enabled===true);};
|
1285
|
-
|
1286
|
-
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);});}/**
|
1137
|
+
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);});}/**
|
1287
1138
|
* A function to validate, construct and store loadOption, lifecycle, source and destination
|
1288
1139
|
* config related information in global state
|
1289
|
-
*/init(){
|
1140
|
+
*/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
|
1290
1141
|
const intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,state.loadOptions.value.destSDKBaseURL);// determine the path to fetch remote plugins from
|
1291
|
-
const pluginsCDNPath=getPluginsCDNPath(state.loadOptions.value.pluginsSDKBaseURL);//
|
1292
|
-
|
1293
|
-
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
|
1294
|
-
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
|
1295
|
-
state.consents.activeConsentManagerPluginName.value=consentManagerPluginName;// set storage type in state
|
1296
|
-
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();}/**
|
1142
|
+
const pluginsCDNPath=getPluginsCDNPath(state.loadOptions.value.pluginsSDKBaseURL);updateStorageState(this.logger);updateConsentsState(this.logger);// set application lifecycle state in global state
|
1143
|
+
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();}/**
|
1297
1144
|
* Handle errors
|
1298
1145
|
*/onError(error,customMessage,shouldAlwaysThrow){if(this.hasErrorHandler){this.errorHandler?.onError(error,CONFIG_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}/**
|
1299
1146
|
* A callback function that is executed once we fetch the source config response.
|
1300
1147
|
* Use to construct and store information that are dependent on the sourceConfig.
|
1301
1148
|
*/processConfig(response,details){// TODO: add retry logic with backoff based on rejectionDetails.xhr.status
|
1302
1149
|
// We can use isErrRetryable utility method
|
1303
|
-
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;}//
|
1150
|
+
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
|
1151
|
+
updateReportingState(res,this.logger);// determine the dataPlane url
|
1304
1152
|
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
|
1305
|
-
|
1153
|
+
r(()=>{// set source related information in state
|
1306
1154
|
state.source.value={config:res.source.config,id:res.source.id};// set device mode destination related information in state
|
1307
|
-
state.nativeDestinations.configuredDestinations.value=nativeDestinations;// set the
|
1308
|
-
updateReportingState(res,this.logger);// set the desired optional plugins
|
1155
|
+
state.nativeDestinations.configuredDestinations.value=nativeDestinations;// set the desired optional plugins
|
1309
1156
|
state.plugins.pluginsToLoadFromConfig.value=state.loadOptions.value.plugins??[];// set application lifecycle state
|
1310
1157
|
// Cast to string as we are sure that the value is not undefined
|
1311
1158
|
state.lifecycle.activeDataplaneUrl.value=removeTrailingSlashes(dataPlaneUrl);state.lifecycle.status.value=LifecycleStatus.Configured;});}/**
|
@@ -1340,11 +1187,11 @@
|
|
1340
1187
|
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);}}/**
|
1341
1188
|
* Detect supported capabilities and set values in state
|
1342
1189
|
*/ // eslint-disable-next-line class-methods-use-this
|
1343
|
-
detectBrowserCapabilities(){
|
1190
|
+
detectBrowserCapabilities(){r(()=>{// Storage related details
|
1344
1191
|
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
|
1345
|
-
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
|
1192
|
+
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
|
1346
1193
|
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
|
1347
|
-
|
1194
|
+
E(()=>{if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(this.errorHandler,this.logger);}});}/**
|
1348
1195
|
* Detect if polyfills are required and then load script from polyfill URL
|
1349
1196
|
*/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
|
1350
1197
|
// NOTE: we're not putting this into RudderStackGlobals as providing the property path to the callback function in the polyfill URL is not possible
|
@@ -1359,11 +1206,28 @@
|
|
1359
1206
|
* @param error The error object
|
1360
1207
|
*/onError(error){if(this.errorHandler){this.errorHandler.onError(error,CAPABILITIES_MANAGER);}else {throw error;}}}
|
1361
1208
|
|
1209
|
+
function random(len){return crypto.getRandomValues(new Uint8Array(len));}
|
1210
|
+
|
1211
|
+
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;}
|
1212
|
+
|
1213
|
+
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;}
|
1214
|
+
|
1215
|
+
const hasCrypto=()=>!isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);
|
1216
|
+
|
1217
|
+
const generateUUID=()=>{if(hasCrypto()){return v4$1();}return v4();};
|
1218
|
+
|
1219
|
+
/**
|
1220
|
+
* To get the current timestamp in ISO string format
|
1221
|
+
* @returns ISO formatted timestamp string
|
1222
|
+
*/const getCurrentTimeFormatted=()=>{const curDateTime=new Date().toISOString();return curDateTime;};
|
1223
|
+
|
1224
|
+
const DEFAULT_INTEGRATIONS_CONFIG={All:true};
|
1225
|
+
|
1362
1226
|
const CHANNEL='web';// These are the top-level elements in the standard RudderStack event spec
|
1363
1227
|
const TOP_LEVEL_ELEMENTS=['integrations','anonymousId','originalTimestamp'];// Reserved elements in the context of standard RudderStack event spec
|
1364
1228
|
// Typically, these elements are not allowed to be overridden by the user
|
1365
1229
|
const CONTEXT_RESERVED_ELEMENTS=['library','consentManagement','userAgent','ua-ch','screen'];// Reserved elements in the standard RudderStack event spec
|
1366
|
-
const RESERVED_ELEMENTS=['anonymousId','sentAt','receivedAt','timestamp','originalTimestamp','event','messageId','channel'];
|
1230
|
+
const RESERVED_ELEMENTS=['anonymousId','sentAt','receivedAt','timestamp','originalTimestamp','event','messageId','channel'];
|
1367
1231
|
|
1368
1232
|
/**
|
1369
1233
|
* To get the page properties for context object
|
@@ -1378,7 +1242,6 @@
|
|
1378
1242
|
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;};/**
|
1379
1243
|
* Utility to check for reserved keys in the input object
|
1380
1244
|
* @param obj Generic object
|
1381
|
-
* @param eventType Rudder event type
|
1382
1245
|
* @param parentKeyPath Object's parent key path
|
1383
1246
|
* @param logger Logger instance
|
1384
1247
|
*/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));}});}};/**
|
@@ -1418,9 +1281,10 @@
|
|
1418
1281
|
* @param pageProps Page properties
|
1419
1282
|
* @param logger logger
|
1420
1283
|
* @returns Enriched RudderEvent object
|
1421
|
-
*/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.
|
1422
|
-
commonEventData.anonymousId=generateUUID();
|
1423
|
-
commonEventData.anonymousId=state.session.
|
1284
|
+
*/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
|
1285
|
+
commonEventData.anonymousId=generateUUID();}else {// Type casting to string as the user session manager will take care of initializing the value
|
1286
|
+
commonEventData.anonymousId=state.session.anonymousId.value;}// set truly anonymous tracking flag
|
1287
|
+
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
|
1424
1288
|
// matching with v1.1 payload
|
1425
1289
|
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
|
1426
1290
|
checkForReservedElements(processedEvent,logger);// Update the integrations config for the event
|
@@ -1494,17 +1358,15 @@
|
|
1494
1358
|
* @param id Provided sessionId
|
1495
1359
|
* @param logger Logger module
|
1496
1360
|
* @returns SessionInfo
|
1497
|
-
*/const generateManualTrackingSession=(id,logger)=>{const sessionId=isManualSessionIdValid(id,logger)?id:generateSessionId();return {id:sessionId,sessionStart:undefined,manualTrack:true};};
|
1361
|
+
*/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);
|
1498
1362
|
|
1499
|
-
|
1500
|
-
|
1501
|
-
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);}/**
|
1363
|
+
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);}/**
|
1502
1364
|
* Initialize User session with values from storage
|
1503
1365
|
* @param store Selected store
|
1504
|
-
*/init(
|
1505
|
-
this.
|
1506
|
-
this.initializeSessionTracking()
|
1507
|
-
this.registerEffects();}
|
1366
|
+
*/init(){this.migrateStorageIfNeeded();this.migrateDataFromPreviousStorage();// get the values from storage and set it again
|
1367
|
+
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
|
1368
|
+
if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.sessionInfo)){this.initializeSessionTracking();}// Register the effect to sync with storage
|
1369
|
+
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);}});});}/**
|
1508
1370
|
* A function to initialize sessionTracking
|
1509
1371
|
*/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
|
1510
1372
|
// and will proceed with it
|
@@ -1516,87 +1378,90 @@
|
|
1516
1378
|
* A function to sync values in storage
|
1517
1379
|
* @param key
|
1518
1380
|
* @param value
|
1519
|
-
*/syncValueToStorage(
|
1381
|
+
*/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);}}}/**
|
1520
1382
|
* Function to update storage whenever state value changes
|
1521
1383
|
*/registerEffects(){/**
|
1522
1384
|
* Update userId in storage automatically when userId is updated in state
|
1523
|
-
*/
|
1385
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.userId,state.session.userId.value);});/**
|
1524
1386
|
* Update user traits in storage automatically when it is updated in state
|
1525
|
-
*/
|
1387
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.userTraits,state.session.userTraits.value);});/**
|
1526
1388
|
* Update group id in storage automatically when it is updated in state
|
1527
|
-
*/
|
1389
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.groupId,state.session.groupId.value);});/**
|
1528
1390
|
* Update group traits in storage automatically when it is updated in state
|
1529
|
-
*/
|
1391
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.groupTraits,state.session.groupTraits.value);});/**
|
1530
1392
|
* Update anonymous user id in storage automatically when it is updated in state
|
1531
|
-
*/
|
1393
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.anonymousId,state.session.anonymousId.value);});/**
|
1532
1394
|
* Update initial referrer in storage automatically when it is updated in state
|
1533
|
-
*/
|
1395
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.initialReferrer,state.session.initialReferrer.value);});/**
|
1534
1396
|
* Update initial referring domain in storage automatically when it is updated in state
|
1535
|
-
*/
|
1397
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.initialReferringDomain,state.session.initialReferringDomain.value);});/**
|
1536
1398
|
* Update session tracking info in storage automatically when it is updated in state
|
1537
|
-
*/
|
1399
|
+
*/E(()=>{this.syncValueToStorage(UserSessionKeys.sessionInfo,state.session.sessionInfo.value);});}/**
|
1538
1400
|
* Sets anonymous id in the following precedence:
|
1539
1401
|
*
|
1540
1402
|
* 1. anonymousId: Id directly provided to the function.
|
1541
1403
|
* 2. rudderAmpLinkerParam: value generated from linker query parm (rudderstack)
|
1542
1404
|
* using parseLinker util.
|
1543
1405
|
* 3. generateUUID: A new unique id is generated and assigned.
|
1544
|
-
*/setAnonymousId(anonymousId,rudderAmpLinkerParam){
|
1406
|
+
*/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();}}/**
|
1545
1407
|
* Generate a new anonymousId
|
1546
1408
|
* @returns string anonymousID
|
1547
1409
|
*/generateAnonymousId(){return generateUUID();}/**
|
1548
1410
|
* Fetches anonymousId
|
1549
1411
|
* @param options option to fetch it from external source
|
1550
1412
|
* @returns anonymousId
|
1551
|
-
*/getAnonymousId(options){
|
1552
|
-
|
1553
|
-
const autoCapturedAnonymousId=this.pluginsManager?.invokeSingle('storage.getAnonymousId',getStorageEngine,options);persistedAnonymousId=autoCapturedAnonymousId;}state.session.
|
1413
|
+
*/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
|
1414
|
+
if(isStorageTypeValidForStoringData(storage)){const store=this.storeManager?.getStore(storageClientDataStoreNameMap[storage]);persistedAnonymousId=store?.get(key);if(!persistedAnonymousId&&options){// fetch anonymousId from external source
|
1415
|
+
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;}/**
|
1554
1416
|
* Fetches User Id
|
1555
1417
|
* @returns
|
1556
|
-
*/getUserId(){return this.
|
1418
|
+
*/getUserId(){return this.getItem(UserSessionKeys.userId);}/**
|
1557
1419
|
* Fetches User Traits
|
1558
1420
|
* @returns
|
1559
|
-
*/getUserTraits(){return this.
|
1421
|
+
*/getUserTraits(){return this.getItem(UserSessionKeys.userTraits);}/**
|
1560
1422
|
* Fetches Group Id
|
1561
1423
|
* @returns
|
1562
|
-
*/getGroupId(){return this.
|
1424
|
+
*/getGroupId(){return this.getItem(UserSessionKeys.groupId);}/**
|
1563
1425
|
* Fetches Group Traits
|
1564
1426
|
* @returns
|
1565
|
-
*/getGroupTraits(){return this.
|
1427
|
+
*/getGroupTraits(){return this.getItem(UserSessionKeys.groupTraits);}/**
|
1566
1428
|
* Fetches Initial Referrer
|
1567
1429
|
* @returns
|
1568
|
-
*/getInitialReferrer(){return this.
|
1430
|
+
*/getInitialReferrer(){return this.getItem(UserSessionKeys.initialReferrer);}/**
|
1569
1431
|
* Fetches Initial Referring domain
|
1570
1432
|
* @returns
|
1571
|
-
*/getInitialReferringDomain(){return this.
|
1433
|
+
*/getInitialReferringDomain(){return this.getItem(UserSessionKeys.initialReferringDomain);}/**
|
1572
1434
|
* Fetches session tracking information from storage
|
1573
1435
|
* @returns
|
1574
|
-
*/getSessionFromStorage(){return this.
|
1436
|
+
*/getSessionFromStorage(){return this.getItem(UserSessionKeys.sessionInfo);}/**
|
1437
|
+
* If session is active it returns the sessionId
|
1438
|
+
* @returns
|
1439
|
+
*/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;}/**
|
1575
1440
|
* A function to update current session info after each event call
|
1576
1441
|
*/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};}}}/**
|
1577
1442
|
* Reset state values
|
1578
1443
|
* @param resetAnonymousId
|
1579
1444
|
* @param noNewSessionStart
|
1580
1445
|
* @returns
|
1581
|
-
*/reset(resetAnonymousId,noNewSessionStart){const{manualTrack,autoTrack}=state.session.sessionInfo.value;
|
1446
|
+
*/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();}});}/**
|
1582
1447
|
* Set user Id
|
1583
1448
|
* @param userId
|
1584
|
-
*/setUserId(userId){if(this.
|
1449
|
+
*/setUserId(userId){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.userId)){state.session.userId.value=userId;}}/**
|
1585
1450
|
* Set user traits
|
1586
1451
|
* @param traits
|
1587
|
-
*/setUserTraits(traits){if(
|
1452
|
+
*/setUserTraits(traits){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.userTraits)&&traits){state.session.userTraits.value=mergeDeepRight(state.session.userTraits.value??{},traits);}}/**
|
1588
1453
|
* Set group Id
|
1589
1454
|
* @param groupId
|
1590
|
-
*/setGroupId(groupId){if(this.
|
1455
|
+
*/setGroupId(groupId){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.groupId)){state.session.groupId.value=groupId;}}/**
|
1591
1456
|
* Set group traits
|
1592
1457
|
* @param traits
|
1593
|
-
*/setGroupTraits(traits){if(
|
1458
|
+
*/setGroupTraits(traits){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.groupTraits)&&traits){state.session.groupTraits.value=mergeDeepRight(state.session.groupTraits.value??{},traits);}}/**
|
1594
1459
|
* Set initial referrer
|
1595
1460
|
* @param referrer
|
1596
|
-
*/setInitialReferrer(referrer){if(this.
|
1461
|
+
*/setInitialReferrer(referrer){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.initialReferrer)){state.session.initialReferrer.value=referrer;}}/**
|
1597
1462
|
* Set initial referring domain
|
1598
1463
|
* @param referrer
|
1599
|
-
*/setInitialReferringDomain(
|
1464
|
+
*/setInitialReferringDomain(referringDomain){if(this.isPersistenceEnabledForStorageEntry(UserSessionKeys.initialReferringDomain)){state.session.initialReferringDomain.value=referringDomain;}}/**
|
1600
1465
|
* A function to check for existing session details and depending on that create a new session.
|
1601
1466
|
*/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
|
1602
1467
|
});}}/**
|
@@ -1607,10 +1472,7 @@
|
|
1607
1472
|
* An internal function to start manual session
|
1608
1473
|
*/startManualTrackingInternal(){this.start(Date.now());}/**
|
1609
1474
|
* A public method to end an ongoing session.
|
1610
|
-
*/end(){state.session.sessionInfo.value={};}
|
1611
|
-
* Clear storage
|
1612
|
-
* @param resetAnonymousId
|
1613
|
-
*/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);}}}
|
1475
|
+
*/end(){state.session.sessionInfo.value={};}}
|
1614
1476
|
|
1615
1477
|
/**
|
1616
1478
|
* A buffer queue to serve as a store for any type of data
|
@@ -1618,6 +1480,20 @@
|
|
1618
1480
|
|
1619
1481
|
const DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';const DESTINATIONS_QUEUE_EXT_POINT_PREFIX='destinationsEventsQueue';
|
1620
1482
|
|
1483
|
+
/**
|
1484
|
+
* Filters and returns the user supplied integrations config that should take preference over the destination specific integrations config
|
1485
|
+
* @param eventIntgConfig User supplied integrations config at event level
|
1486
|
+
* @param destinationsIntgConfig Cumulative integrations config from all destinations
|
1487
|
+
* @returns Filtered user supplied integrations config
|
1488
|
+
*/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;},{});/**
|
1489
|
+
* Returns the event object with final integrations config
|
1490
|
+
* @param event RudderEvent object
|
1491
|
+
* @param state Application state
|
1492
|
+
* @returns Mutated event with final integrations config
|
1493
|
+
*/const getFinalEvent=(event,state)=>{const finalEvent=clone$1(event);// Merge the destination specific integrations config with the event's integrations config
|
1494
|
+
// In general, the preference is given to the event's integrations config
|
1495
|
+
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;};
|
1496
|
+
|
1621
1497
|
/**
|
1622
1498
|
* Event repository class responsible for queuing events for further processing and delivery
|
1623
1499
|
*/class EventRepository{/**
|
@@ -1629,16 +1505,16 @@
|
|
1629
1505
|
*/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);}/**
|
1630
1506
|
* Initializes the event repository
|
1631
1507
|
*/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
|
1632
|
-
|
1508
|
+
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
|
1633
1509
|
// However, events will be enqueued for now.
|
1634
1510
|
// At the time of processing the events, the integrations config data from destinations
|
1635
1511
|
// is merged into the event object
|
1636
|
-
let timeoutId;
|
1512
|
+
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
|
1637
1513
|
if(state.loadOptions.value.bufferDataPlaneEventsUntilReady===true){timeoutId=globalThis.setTimeout(()=>{if(this.dataplaneEventsQueue?.scheduleTimeoutActive!==true){this.dataplaneEventsQueue?.start();}},state.loadOptions.value.dataPlaneEventsBufferTimeout);}}/**
|
1638
1514
|
* Enqueues the event for processing
|
1639
1515
|
* @param event RudderEvent object
|
1640
1516
|
* @param callback API callback function
|
1641
|
-
*/enqueue(event,callback){const dpQEvent=
|
1517
|
+
*/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
|
1642
1518
|
try{// Using the event sent to the data plane queue here
|
1643
1519
|
// to ensure the mutated (if any) event is sent to the callback
|
1644
1520
|
callback?.(dpQEvent);}catch(error){this.onError(error,API_CALLBACK_INVOKE_ERROR);}}/**
|
@@ -1656,25 +1532,25 @@
|
|
1656
1532
|
* Start application lifecycle if not already started
|
1657
1533
|
*/load(writeKey,dataPlaneUrl,loadOptions={}){if(state.lifecycle.status.value){return;}let clonedDataPlaneUrl=clone$1(dataPlaneUrl);let clonedLoadOptions=clone$1(loadOptions);// dataPlaneUrl is not provided
|
1658
1534
|
if(isObjectAndNotNull(dataPlaneUrl)){clonedLoadOptions=dataPlaneUrl;clonedDataPlaneUrl=undefined;}// Set initial state values
|
1659
|
-
|
1535
|
+
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
|
1660
1536
|
setExposedGlobal('state',state,writeKey);// Configure initial config of any services or components here
|
1661
1537
|
// State application lifecycle
|
1662
1538
|
this.startLifecycle();}// Start lifecycle methods
|
1663
1539
|
/**
|
1664
1540
|
* Orchestrate the lifecycle of the application phases/status
|
1665
|
-
*/startLifecycle(){
|
1541
|
+
*/startLifecycle(){E(()=>{try{switch(state.lifecycle.status.value){case LifecycleStatus.Mounted:this.prepareBrowserCapabilities();break;case LifecycleStatus.BrowserCapabilitiesReady:// initialize the preloaded events enqueuing
|
1666
1542
|
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);}});}/**
|
1667
1543
|
* Load browser polyfill if required
|
1668
1544
|
*/prepareBrowserCapabilities(){this.capabilitiesManager.init();}/**
|
1669
1545
|
* Enqueue in SDK preload buffer events, used from preloadBuffer component
|
1670
1546
|
*/enqueuePreloadBufferEvents(bufferedEvents){if(Array.isArray(bufferedEvents)){bufferedEvents.forEach(bufferedEvent=>this.preloadBuffer.enqueue(clone$1(bufferedEvent)));}}/**
|
1671
1547
|
* Process the buffer preloaded events by passing their arguments to the respective facade methods
|
1672
|
-
*/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);}/**
|
1548
|
+
*/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);}/**
|
1673
1549
|
* Load configuration
|
1674
1550
|
*/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();}/**
|
1675
1551
|
* Initialize the storage and event queue
|
1676
1552
|
*/init(){this.errorHandler.init(this.externalSrcLoader);// Initialize storage
|
1677
|
-
this.storeManager?.init();this.
|
1553
|
+
this.storeManager?.init();this.userSessionManager?.init();// Initialize consent manager
|
1678
1554
|
if(state.consents.activeConsentManagerPluginName.value){this.pluginsManager?.invokeSingle(`consentManager.init`,state,this.storeManager,this.logger);}// Initialize event manager
|
1679
1555
|
this.eventManager?.init();// Mark the SDK as initialized
|
1680
1556
|
state.lifecycle.status.value=LifecycleStatus.Initialized;}/**
|
@@ -1688,7 +1564,7 @@
|
|
1688
1564
|
// as this will prevent us from supporting multiple SDK instances in the same page
|
1689
1565
|
// Execute onLoaded callback if provided in load options
|
1690
1566
|
if(isFunction(state.loadOptions.value.onLoaded)){state.loadOptions.value.onLoaded(globalThis.rudderanalytics);}// Set lifecycle state
|
1691
|
-
|
1567
|
+
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
|
1692
1568
|
const initializedEvent=new CustomEvent('RSA_Initialised',{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:true,cancelable:true,composed:true});globalThis.document.dispatchEvent(initializedEvent);}/**
|
1693
1569
|
* Emit ready event
|
1694
1570
|
*/ // eslint-disable-next-line class-methods-use-this
|
@@ -1701,7 +1577,7 @@
|
|
1701
1577
|
*/loadDestinations(){// Set in state the desired activeDestinations to inject in DOM
|
1702
1578
|
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
|
1703
1579
|
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
|
1704
|
-
|
1580
|
+
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;});}});}/**
|
1705
1581
|
* Invoke the ready callbacks if any exist
|
1706
1582
|
*/ // eslint-disable-next-line class-methods-use-this
|
1707
1583
|
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
|
@@ -1723,7 +1599,7 @@
|
|
1723
1599
|
getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
|
1724
1600
|
getGroupId(){return state.session.groupId.value;}// eslint-disable-next-line class-methods-use-this
|
1725
1601
|
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
|
1726
|
-
getSessionId(){this.userSessionManager?.
|
1602
|
+
getSessionId(){const sessionId=this.userSessionManager?.getSessionId();return sessionId??null;}// End consumer exposed methods
|
1727
1603
|
}
|
1728
1604
|
|
1729
1605
|
/*
|
@@ -1741,7 +1617,7 @@
|
|
1741
1617
|
* Set instance to use if no specific writeKey is provided in methods
|
1742
1618
|
* automatically for the first created instance
|
1743
1619
|
* TODO: to support multiple analytics instances in the near future
|
1744
|
-
*/setDefaultInstanceKey(writeKey){if(
|
1620
|
+
*/setDefaultInstanceKey(writeKey){if(writeKey){this.defaultAnalyticsKey=writeKey;}}/**
|
1745
1621
|
* Retrieve an existing analytics instance
|
1746
1622
|
*/getAnalyticsInstance(writeKey){const instanceId=writeKey??this.defaultAnalyticsKey;const analyticsInstanceExists=Boolean(this.analyticsInstances[instanceId]);if(!analyticsInstanceExists){this.analyticsInstances[instanceId]=new Analytics();}return this.analyticsInstances[instanceId];}/**
|
1747
1623
|
* Create new analytics instance and trigger application lifecycle start
|