@rudderstack/analytics-js 3.28.1 → 3.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2588 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.rudderanalytics = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ function _arrayLikeToArray(r, a) {
8
+ (null == a || a > r.length) && (a = r.length);
9
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
10
+ return n;
11
+ }
12
+ function _arrayWithHoles(r) {
13
+ if (Array.isArray(r)) return r;
14
+ }
15
+ function _arrayWithoutHoles(r) {
16
+ if (Array.isArray(r)) return _arrayLikeToArray(r);
17
+ }
18
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
19
+ try {
20
+ var i = n[a](c),
21
+ u = i.value;
22
+ } catch (n) {
23
+ return void e(n);
24
+ }
25
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
26
+ }
27
+ function _asyncToGenerator(n) {
28
+ return function () {
29
+ var t = this,
30
+ e = arguments;
31
+ return new Promise(function (r, o) {
32
+ var a = n.apply(t, e);
33
+ function _next(n) {
34
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
35
+ }
36
+ function _throw(n) {
37
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
38
+ }
39
+ _next(void 0);
40
+ });
41
+ };
42
+ }
43
+ function _classCallCheck(a, n) {
44
+ if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
45
+ }
46
+ function _defineProperties(e, r) {
47
+ for (var t = 0; t < r.length; t++) {
48
+ var o = r[t];
49
+ o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
50
+ }
51
+ }
52
+ function _createClass(e, r, t) {
53
+ return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
54
+ writable: false
55
+ }), e;
56
+ }
57
+ function _createForOfIteratorHelper(r, e) {
58
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
59
+ if (!t) {
60
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
61
+ t && (r = t);
62
+ var n = 0,
63
+ F = function () {};
64
+ return {
65
+ s: F,
66
+ n: function () {
67
+ return n >= r.length ? {
68
+ done: true
69
+ } : {
70
+ done: false,
71
+ value: r[n++]
72
+ };
73
+ },
74
+ e: function (r) {
75
+ throw r;
76
+ },
77
+ f: F
78
+ };
79
+ }
80
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
81
+ }
82
+ var o,
83
+ a = true,
84
+ u = false;
85
+ return {
86
+ s: function () {
87
+ t = t.call(r);
88
+ },
89
+ n: function () {
90
+ var r = t.next();
91
+ return a = r.done, r;
92
+ },
93
+ e: function (r) {
94
+ u = true, o = r;
95
+ },
96
+ f: function () {
97
+ try {
98
+ a || null == t.return || t.return();
99
+ } finally {
100
+ if (u) throw o;
101
+ }
102
+ }
103
+ };
104
+ }
105
+ function _defineProperty(e, r, t) {
106
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
107
+ value: t,
108
+ enumerable: true,
109
+ configurable: true,
110
+ writable: true
111
+ }) : e[r] = t, e;
112
+ }
113
+ function _iterableToArray(r) {
114
+ if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
115
+ }
116
+ function _iterableToArrayLimit(r, l) {
117
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
118
+ if (null != t) {
119
+ var e,
120
+ n,
121
+ i,
122
+ u,
123
+ a = [],
124
+ f = true,
125
+ o = false;
126
+ try {
127
+ if (i = (t = t.call(r)).next, 0 === l) {
128
+ if (Object(t) !== t) return;
129
+ f = !1;
130
+ } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
131
+ } catch (r) {
132
+ o = true, n = r;
133
+ } finally {
134
+ try {
135
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
136
+ } finally {
137
+ if (o) throw n;
138
+ }
139
+ }
140
+ return a;
141
+ }
142
+ }
143
+ function _nonIterableRest() {
144
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
145
+ }
146
+ function _nonIterableSpread() {
147
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
148
+ }
149
+ function ownKeys(e, r) {
150
+ var t = Object.keys(e);
151
+ if (Object.getOwnPropertySymbols) {
152
+ var o = Object.getOwnPropertySymbols(e);
153
+ r && (o = o.filter(function (r) {
154
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
155
+ })), t.push.apply(t, o);
156
+ }
157
+ return t;
158
+ }
159
+ function _objectSpread2(e) {
160
+ for (var r = 1; r < arguments.length; r++) {
161
+ var t = null != arguments[r] ? arguments[r] : {};
162
+ r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
163
+ _defineProperty(e, r, t[r]);
164
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
165
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
166
+ });
167
+ }
168
+ return e;
169
+ }
170
+ function _objectWithoutProperties(e, t) {
171
+ if (null == e) return {};
172
+ var o,
173
+ r,
174
+ i = _objectWithoutPropertiesLoose(e, t);
175
+ if (Object.getOwnPropertySymbols) {
176
+ var n = Object.getOwnPropertySymbols(e);
177
+ for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
178
+ }
179
+ return i;
180
+ }
181
+ function _objectWithoutPropertiesLoose(r, e) {
182
+ if (null == r) return {};
183
+ var t = {};
184
+ for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
185
+ if (-1 !== e.indexOf(n)) continue;
186
+ t[n] = r[n];
187
+ }
188
+ return t;
189
+ }
190
+ function _regenerator() {
191
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
192
+ var e,
193
+ t,
194
+ r = "function" == typeof Symbol ? Symbol : {},
195
+ n = r.iterator || "@@iterator",
196
+ o = r.toStringTag || "@@toStringTag";
197
+ function i(r, n, o, i) {
198
+ var c = n && n.prototype instanceof Generator ? n : Generator,
199
+ u = Object.create(c.prototype);
200
+ return _regeneratorDefine(u, "_invoke", function (r, n, o) {
201
+ var i,
202
+ c,
203
+ u,
204
+ f = 0,
205
+ p = o || [],
206
+ y = false,
207
+ G = {
208
+ p: 0,
209
+ n: 0,
210
+ v: e,
211
+ a: d,
212
+ f: d.bind(e, 4),
213
+ d: function (t, r) {
214
+ return i = t, c = 0, u = e, G.n = r, a;
215
+ }
216
+ };
217
+ function d(r, n) {
218
+ for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
219
+ var o,
220
+ i = p[t],
221
+ d = G.p,
222
+ l = i[2];
223
+ r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
224
+ }
225
+ if (o || r > 1) return a;
226
+ throw y = true, n;
227
+ }
228
+ return function (o, p, l) {
229
+ if (f > 1) throw TypeError("Generator is already running");
230
+ for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
231
+ i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
232
+ try {
233
+ if (f = 2, i) {
234
+ if (c || (o = "next"), t = i[o]) {
235
+ if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
236
+ if (!t.done) return t;
237
+ u = t.value, c < 2 && (c = 0);
238
+ } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
239
+ i = e;
240
+ } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
241
+ } catch (t) {
242
+ i = e, c = 1, u = t;
243
+ } finally {
244
+ f = 1;
245
+ }
246
+ }
247
+ return {
248
+ value: t,
249
+ done: y
250
+ };
251
+ };
252
+ }(r, o, i), true), u;
253
+ }
254
+ var a = {};
255
+ function Generator() {}
256
+ function GeneratorFunction() {}
257
+ function GeneratorFunctionPrototype() {}
258
+ t = Object.getPrototypeOf;
259
+ var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
260
+ return this;
261
+ }), t),
262
+ u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
263
+ function f(e) {
264
+ return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
265
+ }
266
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
267
+ return this;
268
+ }), _regeneratorDefine(u, "toString", function () {
269
+ return "[object Generator]";
270
+ }), (_regenerator = function () {
271
+ return {
272
+ w: i,
273
+ m: f
274
+ };
275
+ })();
276
+ }
277
+ function _regeneratorDefine(e, r, n, t) {
278
+ var i = Object.defineProperty;
279
+ try {
280
+ i({}, "", {});
281
+ } catch (e) {
282
+ i = 0;
283
+ }
284
+ _regeneratorDefine = function (e, r, n, t) {
285
+ function o(r, n) {
286
+ _regeneratorDefine(e, r, function (e) {
287
+ return this._invoke(r, n, e);
288
+ });
289
+ }
290
+ r ? i ? i(e, r, {
291
+ value: n,
292
+ enumerable: !t,
293
+ configurable: !t,
294
+ writable: !t
295
+ }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
296
+ }, _regeneratorDefine(e, r, n, t);
297
+ }
298
+ function _slicedToArray(r, e) {
299
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
300
+ }
301
+ function _toConsumableArray(r) {
302
+ return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
303
+ }
304
+ function _toPrimitive(t, r) {
305
+ if ("object" != typeof t || !t) return t;
306
+ var e = t[Symbol.toPrimitive];
307
+ if (void 0 !== e) {
308
+ var i = e.call(t, r);
309
+ if ("object" != typeof i) return i;
310
+ throw new TypeError("@@toPrimitive must return a primitive value.");
311
+ }
312
+ return (String )(t);
313
+ }
314
+ function _toPropertyKey(t) {
315
+ var i = _toPrimitive(t, "string");
316
+ return "symbol" == typeof i ? i : i + "";
317
+ }
318
+ function _typeof(o) {
319
+ "@babel/helpers - typeof";
320
+
321
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
322
+ return typeof o;
323
+ } : function (o) {
324
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
325
+ }, _typeof(o);
326
+ }
327
+ function _unsupportedIterableToArray(r, a) {
328
+ if (r) {
329
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
330
+ var t = {}.toString.call(r).slice(8, -1);
331
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
332
+ }
333
+ }
334
+
335
+ function _isPlaceholder(a){return a!=null&&_typeof(a)==='object'&&a['@@functional/placeholder']===true;}
336
+
337
+ /**
338
+ * Optimized internal one-arity curry function.
339
+ *
340
+ * @private
341
+ * @category Function
342
+ * @param {Function} fn The function to curry.
343
+ * @return {Function} The curried function.
344
+ */function _curry1(fn){return function f1(a){if(arguments.length===0||_isPlaceholder(a)){return f1;}else {return fn.apply(this,arguments);}};}
345
+
346
+ /**
347
+ * Optimized internal two-arity curry function.
348
+ *
349
+ * @private
350
+ * @category Function
351
+ * @param {Function} fn The function to curry.
352
+ * @return {Function} The curried function.
353
+ */function _curry2(fn){return function f2(a,b){switch(arguments.length){case 0:return f2;case 1:return _isPlaceholder(a)?f2:_curry1(function(_b){return fn(a,_b);});default:return _isPlaceholder(a)&&_isPlaceholder(b)?f2:_isPlaceholder(a)?_curry1(function(_a){return fn(_a,b);}):_isPlaceholder(b)?_curry1(function(_b){return fn(a,_b);}):fn(a,b);}};}
354
+
355
+ /**
356
+ * Optimized internal three-arity curry function.
357
+ *
358
+ * @private
359
+ * @category Function
360
+ * @param {Function} fn The function to curry.
361
+ * @return {Function} The curried function.
362
+ */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);}};}
363
+
364
+ function _has(prop,obj){return Object.prototype.hasOwnProperty.call(obj,prop);}
365
+
366
+ /**
367
+ * Gives a single-word string description of the (native) type of a value,
368
+ * returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not
369
+ * attempt to distinguish user Object types any further, reporting them all as
370
+ * 'Object'.
371
+ *
372
+ * @func
373
+ * @memberOf R
374
+ * @since v0.8.0
375
+ * @category Type
376
+ * @sig * -> String
377
+ * @param {*} val The value to test
378
+ * @return {String}
379
+ * @example
380
+ *
381
+ * R.type({}); //=> "Object"
382
+ * R.type(new Map); //=> "Map"
383
+ * R.type(new Set); //=> "Set"
384
+ * R.type(1); //=> "Number"
385
+ * R.type(false); //=> "Boolean"
386
+ * R.type('s'); //=> "String"
387
+ * R.type(null); //=> "Null"
388
+ * R.type([]); //=> "Array"
389
+ * R.type(/[A-z]/); //=> "RegExp"
390
+ * R.type(() => {}); //=> "Function"
391
+ * R.type(async () => {}); //=> "AsyncFunction"
392
+ * R.type(undefined); //=> "Undefined"
393
+ * R.type(BigInt(123)); //=> "BigInt"
394
+ */var type=/*#__PURE__*/_curry1(function type(val){return val===null?'Null':val===undefined?'Undefined':Object.prototype.toString.call(val).slice(8,-1);});
395
+
396
+ function _isObject(x){return Object.prototype.toString.call(x)==='[object Object]';}
397
+
398
+ /**
399
+ * Determine if the passed argument is an integer.
400
+ *
401
+ * @private
402
+ * @param {*} n
403
+ * @category Type
404
+ * @return {Boolean}
405
+ */var _isInteger = Number.isInteger||function _isInteger(n){return n<<0===n;};
406
+
407
+ function _nth(offset,list){var idx=offset<0?list.length+offset:offset;return list[idx];}
408
+
409
+ function _cloneRegExp(pattern){return new RegExp(pattern.source,pattern.flags?pattern.flags:(pattern.global?'g':'')+(pattern.ignoreCase?'i':'')+(pattern.multiline?'m':'')+(pattern.sticky?'y':'')+(pattern.unicode?'u':'')+(pattern.dotAll?'s':''));}
410
+
411
+ /**
412
+ * Copies an object.
413
+ *
414
+ * @private
415
+ * @param {*} value The value to be copied
416
+ * @param {Boolean} deep Whether or not to perform deep cloning.
417
+ * @return {*} The copied value.
418
+ */function _clone(value,deep,map){map||(map=new _ObjectMap());// this avoids the slower switch with a quick if decision removing some milliseconds in each run.
419
+ if(_isPrimitive(value)){return value;}var copy=function copy(copiedValue){// Check for circular and same references on the object graph and return its corresponding clone.
420
+ var cachedCopy=map.get(value);if(cachedCopy){return cachedCopy;}map.set(value,copiedValue);for(var key in value){if(Object.prototype.hasOwnProperty.call(value,key)){copiedValue[key]=_clone(value[key],true,map);}}return copiedValue;};switch(type(value)){case 'Object':return copy(Object.create(Object.getPrototypeOf(value)));case 'Array':return copy(Array(value.length));case 'Date':return new Date(value.valueOf());case 'RegExp':return _cloneRegExp(value);case 'Int8Array':case 'Uint8Array':case 'Uint8ClampedArray':case 'Int16Array':case 'Uint16Array':case 'Int32Array':case 'Uint32Array':case 'Float32Array':case 'Float64Array':case 'BigInt64Array':case 'BigUint64Array':return value.slice();default:return value;}}function _isPrimitive(param){var type=_typeof(param);return param==null||type!='object'&&type!='function';}var _ObjectMap=/*#__PURE__*/function(){function _ObjectMap(){this.map={};this.length=0;}_ObjectMap.prototype.set=function(key,value){var hashedKey=this.hash(key);var bucket=this.map[hashedKey];if(!bucket){this.map[hashedKey]=bucket=[];}bucket.push([key,value]);this.length+=1;};_ObjectMap.prototype.hash=function(key){var hashedKey=[];for(var value in key){hashedKey.push(Object.prototype.toString.call(key[value]));}return hashedKey.join();};_ObjectMap.prototype.get=function(key){/**
421
+ * depending on the number of objects to be cloned is faster to just iterate over the items in the map just because the hash function is so costly,
422
+ * on my tests this number is 180, anything above that using the hash function is faster.
423
+ */if(this.length<=180){for(var p in this.map){var bucket=this.map[p];for(var i=0;i<bucket.length;i+=1){var element=bucket[i];if(element[0]===key){return element[1];}}}return;}var hashedKey=this.hash(key);var bucket=this.map[hashedKey];if(!bucket){return;}for(var i=0;i<bucket.length;i+=1){var element=bucket[i];if(element[0]===key){return element[1];}}};return _ObjectMap;}();
424
+
425
+ /**
426
+ * Creates a deep copy of the source that can be used in place of the source
427
+ * object without retaining any references to it.
428
+ * The source object may contain (nested) `Array`s and `Object`s,
429
+ * `Number`s, `String`s, `Boolean`s and `Date`s.
430
+ * `Function`s are assigned by reference rather than copied.
431
+ *
432
+ * Dispatches to a `clone` method if present.
433
+ *
434
+ * Note that if the source object has multiple nodes that share a reference,
435
+ * the returned object will have the same structure, but the references will
436
+ * be pointed to the location within the cloned value.
437
+ *
438
+ * @func
439
+ * @memberOf R
440
+ * @since v0.1.0
441
+ * @category Object
442
+ * @sig {*} -> {*}
443
+ * @param {*} value The object or array to clone
444
+ * @return {*} A deeply cloned copy of `val`
445
+ * @example
446
+ *
447
+ * const objects = [{}, {}, {}];
448
+ * const objectsClone = R.clone(objects);
449
+ * objects === objectsClone; //=> false
450
+ * objects[0] === objectsClone[0]; //=> false
451
+ */var clone=/*#__PURE__*/_curry1(function clone(value){return value!=null&&typeof value.clone==='function'?value.clone():_clone(value);});
452
+
453
+ function _path(pathAr,obj){var val=obj;for(var i=0;i<pathAr.length;i+=1){if(val==null){return undefined;}var p=pathAr[i];if(_isInteger(p)){val=_nth(p,val);}else {val=val[p];}}return val;}
454
+
455
+ /**
456
+ * Creates a new object with the own properties of the two provided objects. If
457
+ * a key exists in both objects, the provided function is applied to the key
458
+ * and the values associated with the key in each object, with the result being
459
+ * used as the value associated with the key in the returned object.
460
+ *
461
+ * @func
462
+ * @memberOf R
463
+ * @since v0.19.0
464
+ * @category Object
465
+ * @sig ((String, a, a) -> a) -> {a} -> {a} -> {a}
466
+ * @param {Function} fn
467
+ * @param {Object} l
468
+ * @param {Object} r
469
+ * @return {Object}
470
+ * @see R.mergeDeepWithKey, R.mergeWith
471
+ * @example
472
+ *
473
+ * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r
474
+ * R.mergeWithKey(concatValues,
475
+ * { a: true, thing: 'foo', values: [10, 20] },
476
+ * { b: true, thing: 'bar', values: [15, 35] });
477
+ * //=> { a: true, b: true, thing: 'bar', values: [10, 20, 15, 35] }
478
+ * @symb R.mergeWithKey(f, { x: 1, y: 2 }, { y: 5, z: 3 }) = { x: 1, y: f('y', 2, 5), z: 3 }
479
+ */var mergeWithKey=/*#__PURE__*/_curry3(function mergeWithKey(fn,l,r){var result={};var k;l=l||{};r=r||{};for(k in l){if(_has(k,l)){result[k]=_has(k,r)?fn(k,l[k],r[k]):l[k];}}for(k in r){if(_has(k,r)&&!_has(k,result)){result[k]=r[k];}}return result;});
480
+
481
+ /**
482
+ * Creates a new object with the own properties of the two provided objects.
483
+ * If a key exists in both objects:
484
+ * - and both associated values are also objects then the values will be
485
+ * recursively merged.
486
+ * - otherwise the provided function is applied to the key and associated values
487
+ * using the resulting value as the new value associated with the key.
488
+ * If a key only exists in one object, the value will be associated with the key
489
+ * of the resulting object.
490
+ *
491
+ * @func
492
+ * @memberOf R
493
+ * @since v0.24.0
494
+ * @category Object
495
+ * @sig ((String, a, a) -> a) -> {a} -> {a} -> {a}
496
+ * @param {Function} fn
497
+ * @param {Object} lObj
498
+ * @param {Object} rObj
499
+ * @return {Object}
500
+ * @see R.mergeWithKey, R.mergeDeepWith
501
+ * @example
502
+ *
503
+ * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r
504
+ * R.mergeDeepWithKey(concatValues,
505
+ * { a: true, c: { thing: 'foo', values: [10, 20] }},
506
+ * { b: true, c: { thing: 'bar', values: [15, 35] }});
507
+ * //=> { a: true, b: true, c: { thing: 'bar', values: [10, 20, 15, 35] }}
508
+ */var mergeDeepWithKey=/*#__PURE__*/_curry3(function mergeDeepWithKey(fn,lObj,rObj){return mergeWithKey(function(k,lVal,rVal){if(_isObject(lVal)&&_isObject(rVal)){return mergeDeepWithKey(fn,lVal,rVal);}else {return fn(k,lVal,rVal);}},lObj,rObj);});
509
+
510
+ /**
511
+ * Creates a new object with the own properties of the two provided objects.
512
+ * If a key exists in both objects:
513
+ * - and both associated values are also objects then the values will be
514
+ * recursively merged.
515
+ * - otherwise the provided function is applied to associated values using the
516
+ * resulting value as the new value associated with the key.
517
+ * If a key only exists in one object, the value will be associated with the key
518
+ * of the resulting object.
519
+ *
520
+ * @func
521
+ * @memberOf R
522
+ * @since v0.24.0
523
+ * @category Object
524
+ * @sig ((a, a) -> a) -> {a} -> {a} -> {a}
525
+ * @param {Function} fn
526
+ * @param {Object} lObj
527
+ * @param {Object} rObj
528
+ * @return {Object}
529
+ * @see R.mergeWith, R.mergeDeepWithKey
530
+ * @example
531
+ *
532
+ * R.mergeDeepWith(R.concat,
533
+ * { a: true, c: { values: [10, 20] }},
534
+ * { b: true, c: { values: [15, 35] }});
535
+ * //=> { a: true, b: true, c: { values: [10, 20, 15, 35] }}
536
+ */var mergeDeepWith=/*#__PURE__*/_curry3(function mergeDeepWith(fn,lObj,rObj){return mergeDeepWithKey(function(k,lVal,rVal){return fn(lVal,rVal);},lObj,rObj);});
537
+
538
+ /**
539
+ * Retrieves the value at a given path. The nodes of the path can be arbitrary strings or non-negative integers.
540
+ * For anything else, the value is unspecified. Integer paths are meant to index arrays, strings are meant for objects.
541
+ *
542
+ * @func
543
+ * @memberOf R
544
+ * @since v0.2.0
545
+ * @category Object
546
+ * @typedefn Idx = String | Int | Symbol
547
+ * @sig [Idx] -> {a} -> a | Undefined
548
+ * @sig Idx = String | NonNegativeInt
549
+ * @param {Array} path The path to use.
550
+ * @param {Object} obj The object or array to retrieve the nested property from.
551
+ * @return {*} The data at `path`.
552
+ * @see R.prop, R.nth, R.assocPath, R.dissocPath
553
+ * @example
554
+ *
555
+ * R.path(['a', 'b'], {a: {b: 2}}); //=> 2
556
+ * R.path(['a', 'b'], {c: {b: 2}}); //=> undefined
557
+ * R.path(['a', 'b', 0], {a: {b: [1, 2, 3]}}); //=> 1
558
+ * R.path(['a', 'b', -2], {a: {b: [1, 2, 3]}}); //=> 2
559
+ * R.path([2], {'2': 2}); //=> 2
560
+ * R.path([-2], {'-2': 'a'}); //=> undefined
561
+ */var path=/*#__PURE__*/_curry2(_path);
562
+
563
+ /**
564
+ * Returns a partial copy of an object containing only the keys that satisfy
565
+ * the supplied predicate.
566
+ *
567
+ * @func
568
+ * @memberOf R
569
+ * @since v0.8.0
570
+ * @category Object
571
+ * @sig ((v, k) -> Boolean) -> {k: v} -> {k: v}
572
+ * @param {Function} pred A predicate to determine whether or not a key
573
+ * should be included on the output object.
574
+ * @param {Object} obj The object to copy from
575
+ * @return {Object} A new object with only properties that satisfy `pred`
576
+ * on it.
577
+ * @see R.pick, R.filter
578
+ * @example
579
+ *
580
+ * const isUpperCase = (val, key) => key.toUpperCase() === key;
581
+ * R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4}
582
+ */var pickBy=/*#__PURE__*/_curry2(function pickBy(test,obj){var result={};for(var prop in obj){if(test(obj[prop],prop,obj)){result[prop]=obj[prop];}}return result;});
583
+
584
+ /**
585
+ * A function to check given value is a function
586
+ * @param value input value
587
+ * @returns boolean
588
+ */var isFunction=function isFunction(value){return typeof value==='function'&&Boolean(value.constructor&&value.call&&value.apply);};/**
589
+ * A function to check given value is a string
590
+ * @param value input value
591
+ * @returns boolean
592
+ */var isString=function isString(value){return typeof value==='string';};/**
593
+ * A function to check given value is null or not
594
+ * @param value input value
595
+ * @returns boolean
596
+ */var isNull=function isNull(value){return value===null;};/**
597
+ * A function to check given value is undefined
598
+ * @param value input value
599
+ * @returns boolean
600
+ */var isUndefined=function isUndefined(value){return typeof value==='undefined';};/**
601
+ * A function to check given value is null or undefined
602
+ * @param value input value
603
+ * @returns boolean
604
+ */var isNullOrUndefined=function isNullOrUndefined(value){return isNull(value)||isUndefined(value);};/**
605
+ * Checks if the input is a BigInt
606
+ * @param value input value
607
+ * @returns True if the input is a BigInt
608
+ */var isBigInt=function isBigInt(value){return typeof value==='bigint';};/**
609
+ * A function to check given value is defined
610
+ * @param value input value
611
+ * @returns boolean
612
+ */var isDefined=function isDefined(value){return !isUndefined(value);};/**
613
+ * A function to check given value is defined and not null
614
+ * @param value input value
615
+ * @returns boolean
616
+ */var isDefinedAndNotNull=function isDefinedAndNotNull(value){return !isNullOrUndefined(value);};/**
617
+ * A function to check given value is defined and not null
618
+ * @param value input value
619
+ * @returns boolean
620
+ */var isDefinedNotNullAndNotEmptyString=function isDefinedNotNullAndNotEmptyString(value){return isDefinedAndNotNull(value)&&value!=='';};/**
621
+ * Determines if the input is of type error
622
+ * @param value input value
623
+ * @returns true if the input is of type error else false
624
+ */var isTypeOfError=function isTypeOfError(value){switch(Object.prototype.toString.call(value)){case '[object Error]':case '[object Exception]':case '[object DOMException]':return true;default:return value instanceof Error;}};/**
625
+ * A function to check given value is a boolean
626
+ * @param value input value
627
+ * @returns boolean
628
+ */var isBoolean=function isBoolean(value){return typeof value==='boolean';};
629
+
630
+ var getValueByPath=function getValueByPath(obj,keyPath){var pathParts=keyPath.split('.');return path(pathParts,obj);};var hasValueByPath=function hasValueByPath(obj,path){return Boolean(getValueByPath(obj,path));};var isObject=function isObject(value){return _typeof(value)==='object';};/**
631
+ * Checks if the input is an object literal or built-in object type and not null
632
+ * @param value Input value
633
+ * @returns true if the input is an object and not null
634
+ */var isObjectAndNotNull=function isObjectAndNotNull(value){return !isNull(value)&&isObject(value)&&!Array.isArray(value);};/**
635
+ * Checks if the input is an object literal and not null
636
+ * @param value Input value
637
+ * @returns true if the input is an object and not null
638
+ */var isObjectLiteralAndNotNull=function isObjectLiteralAndNotNull(value){return !isNull(value)&&Object.prototype.toString.call(value)==='[object Object]';};/**
639
+ * Merges two arrays deeply, right-to-left
640
+ * In the case of conflicts, the right array's values replace the left array's values in the
641
+ * same index position
642
+ * @param leftValue - The left array
643
+ * @param rightValue - The right array
644
+ * @returns The merged array
645
+ */var mergeDeepRightObjectArrays=function mergeDeepRightObjectArrays(leftValue,rightValue){if(!Array.isArray(leftValue)||!Array.isArray(rightValue)){return clone(rightValue);}var mergedArray=clone(leftValue);rightValue.forEach(function(value,index){mergedArray[index]=Array.isArray(value)||isObjectAndNotNull(value)?// eslint-disable-next-line @typescript-eslint/no-use-before-define
646
+ mergeDeepRight(mergedArray[index],value):value;});return mergedArray;};/**
647
+ * Merges two objects deeply, right-to-left.
648
+ * In the case of conflicts, the right object's values take precedence.
649
+ * For arrays, the right array's values replace the left array's values in the
650
+ * same index position keeping the remaining left array's values in the resultant array.
651
+ * @param leftObject - The left object
652
+ * @param rightObject - The right object
653
+ * @returns The merged object
654
+ */var mergeDeepRight=function mergeDeepRight(leftObject,rightObject){return mergeDeepWith(mergeDeepRightObjectArrays,leftObject,rightObject);};/**
655
+ Checks if the input is a non-empty object literal type and not undefined or null
656
+ * @param value input any
657
+ * @returns boolean
658
+ */var isNonEmptyObject=function isNonEmptyObject(value){return isObjectLiteralAndNotNull(value)&&Object.keys(value).length>0;};/**
659
+ * A utility to recursively remove undefined values from an object
660
+ * @param obj input object
661
+ * @returns a new object
662
+ */var _removeUndefinedValues=function removeUndefinedValues(obj){var result=pickBy(isDefined,obj);Object.keys(result).forEach(function(key){var value=result[key];if(isObjectLiteralAndNotNull(value)){result[key]=_removeUndefinedValues(value);}});return result;};/**
663
+ * A utility to recursively remove undefined and null values from an object
664
+ * @param obj input object
665
+ * @returns a new object
666
+ */var _removeUndefinedAndNullValues=function removeUndefinedAndNullValues(obj){var result=pickBy(isDefinedAndNotNull,obj);Object.keys(result).forEach(function(key){var value=result[key];if(isObjectLiteralAndNotNull(value)){result[key]=_removeUndefinedAndNullValues(value);}});return result;};/**
667
+ * Normalizes an object by removing undefined and null values.
668
+ * @param val - The value to normalize
669
+ * @returns The normalized object, or undefined if input is not a non-empty object
670
+ * @example
671
+ * getNormalizedObjectValue({ a: 1, b: null, c: undefined }) // returns { a: 1 }
672
+ * getNormalizedObjectValue({}) // returns undefined
673
+ * getNormalizedObjectValue(null) // returns undefined
674
+ */var getNormalizedObjectValue=function getNormalizedObjectValue(val){if(!isNonEmptyObject(val)){return undefined;}return _removeUndefinedAndNullValues(val);};/**
675
+ * Normalizes a value to a boolean, with support for a default value
676
+ * @param val Input value
677
+ * @param defVal Default value
678
+ * @returns Returns the input value if it is a boolean, otherwise returns the default value
679
+ * @example
680
+ * getNormalizedBooleanValue(true, false) // returns true
681
+ */var getNormalizedBooleanValue=function getNormalizedBooleanValue(val,defVal){return typeof val==='boolean'?val:defVal;};var _deepFreeze=function deepFreeze(obj){Object.getOwnPropertyNames(obj).forEach(function(prop){if(obj[prop]&&_typeof(obj[prop])==='object'){_deepFreeze(obj[prop]);}});return Object.freeze(obj);};
682
+
683
+ var trim=function trim(value){return value.replace(/^\s+|\s+$/gm,'');};var removeLeadingPeriod=function removeLeadingPeriod(value){return value.replace(/^\.+/,'');};/**
684
+ * A function to convert values to string
685
+ * @param val input value
686
+ * @returns stringified value
687
+ */var tryStringify=function tryStringify(val){var retVal=val;if(!isString(val)&&!isNullOrUndefined(val)){try{retVal=JSON.stringify(val);}catch(e){retVal=null;}}return retVal;};// The following text encoding and decoding is done before base64 encoding to prevent
688
+ // https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem
689
+ /**
690
+ * Converts a base64 encoded string to bytes array
691
+ * @param base64Str base64 encoded string
692
+ * @returns bytes array
693
+ */var base64ToBytes=function base64ToBytes(base64Str){var binString=globalThis.atob(base64Str);var bytes=binString.split('').map(function(char){return char.charCodeAt(0);});return new Uint8Array(bytes);};/**
694
+ * Converts a bytes array to base64 encoded string
695
+ * @param bytes bytes array to be converted to base64
696
+ * @returns base64 encoded string
697
+ */var bytesToBase64=function bytesToBase64(bytes){var binString=Array.from(bytes,function(x){return String.fromCodePoint(x);}).join('');return globalThis.btoa(binString);};/**
698
+ * Encodes a string to base64 even with unicode characters
699
+ * @param value input string
700
+ * @returns base64 encoded string
701
+ */var toBase64=function toBase64(value){return bytesToBase64(new TextEncoder().encode(value));};/**
702
+ * Decodes a base64 encoded string
703
+ * @param value base64 encoded string
704
+ * @returns decoded string
705
+ */var fromBase64=function fromBase64(value){return new TextDecoder().decode(base64ToBytes(value));};
706
+
707
+ // if yes make them null instead of omitting in overloaded cases
708
+ /*
709
+ * Normalise the overloaded arguments of the page call facade
710
+ */var pageArgumentsToCallOptions=function pageArgumentsToCallOptions(category,name,properties,options,callback){var payload={category:category,name:name,properties:properties,options:options,callback:undefined};if(isFunction(callback)){payload.callback=callback;}if(isFunction(options)){payload.category=category;payload.name=name;payload.properties=properties;payload.options=undefined;payload.callback=options;}if(isFunction(properties)){payload.category=category;payload.name=name;payload.properties=undefined;payload.options=undefined;payload.callback=properties;}if(isFunction(name)){payload.category=category;payload.name=undefined;payload.properties=undefined;payload.options=undefined;payload.callback=name;}if(isFunction(category)){payload.category=undefined;payload.name=undefined;payload.properties=undefined;payload.options=undefined;payload.callback=category;}if(isObjectLiteralAndNotNull(category)){payload.name=undefined;payload.category=undefined;payload.properties=category;if(!isFunction(name)){payload.options=name;}else {payload.options=undefined;}}else if(isObjectLiteralAndNotNull(name)){payload.name=undefined;payload.properties=name;if(!isFunction(properties)){payload.options=properties;}else {payload.options=undefined;}}// if the category argument alone is provided b/w category and name,
711
+ // use it as name and set category to undefined
712
+ if(isString(category)&&!isString(name)){payload.category=undefined;payload.name=category;}// Rest of the code is just to clean up undefined values
713
+ // and set some proper defaults
714
+ // Also, to clone the incoming object type arguments
715
+ if(!isDefined(payload.category)){payload.category=undefined;}if(!isDefined(payload.name)){payload.name=undefined;}payload.properties=payload.properties?clone(payload.properties):{};if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}var nameForProperties=isString(payload.name)?payload.name:payload.properties.name;var categoryForProperties=isString(payload.category)?payload.category:payload.properties.category;// add name and category to properties
716
+ payload.properties=mergeDeepRight(isObjectLiteralAndNotNull(payload.properties)?payload.properties:{},_objectSpread2(_objectSpread2({},nameForProperties&&{name:nameForProperties}),categoryForProperties&&{category:categoryForProperties}));return payload;};/*
717
+ * Normalise the overloaded arguments of the track call facade
718
+ */var trackArgumentsToCallOptions=function trackArgumentsToCallOptions(event,properties,options,callback){var payload={name:event,properties:properties,options:options,callback:undefined};if(isFunction(callback)){payload.callback=callback;}if(isFunction(options)){payload.properties=properties;payload.options=undefined;payload.callback=options;}if(isFunction(properties)){payload.properties=undefined;payload.options=undefined;payload.callback=properties;}// Rest of the code is just to clean up undefined values
719
+ // and set some proper defaults
720
+ // Also, to clone the incoming object type arguments
721
+ payload.properties=isDefinedAndNotNull(payload.properties)?clone(payload.properties):{};if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}return payload;};/*
722
+ * Normalise the overloaded arguments of the identify call facade
723
+ */var identifyArgumentsToCallOptions=function identifyArgumentsToCallOptions(userId,traits,options,callback){var payload={userId:userId,traits:traits,options:options,callback:undefined};if(isFunction(callback)){payload.callback=callback;}if(isFunction(options)){payload.userId=userId;payload.traits=traits;payload.options=undefined;payload.callback=options;}if(isFunction(traits)){payload.userId=userId;payload.traits=undefined;payload.options=undefined;payload.callback=traits;}if(isObjectLiteralAndNotNull(userId)||isNull(userId)){// Explicitly set null to prevent resetting the existing value
724
+ // in the Analytics class
725
+ payload.userId=null;payload.traits=userId;if(!isFunction(traits)){payload.options=traits;}else {payload.options=undefined;}}// Rest of the code is just to clean up undefined values
726
+ // and set some proper defaults
727
+ // Also, to clone the incoming object type arguments
728
+ payload.userId=tryStringify(payload.userId);if(isObjectLiteralAndNotNull(payload.traits)){payload.traits=clone(payload.traits);}else {payload.traits=undefined;}if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}return payload;};/*
729
+ * Normalise the overloaded arguments of the alias call facade
730
+ */var aliasArgumentsToCallOptions=function aliasArgumentsToCallOptions(to,from,options,callback){var payload={to:to,from:from,options:options,callback:undefined};if(isFunction(callback)){payload.callback=callback;}if(isFunction(options)){payload.to=to;payload.from=from;payload.options=undefined;payload.callback=options;}if(isFunction(from)){payload.to=to;payload.from=undefined;payload.options=undefined;payload.callback=from;}else if(isObjectLiteralAndNotNull(from)||isNull(from)){payload.to=to;payload.from=undefined;payload.options=from;}// Rest of the code is just to clean up undefined values
731
+ // and set some proper defaults
732
+ // Also, to clone the incoming object type arguments
733
+ if(isDefined(payload.to)){payload.to=tryStringify(payload.to);}if(isDefined(payload.from)){payload.from=tryStringify(payload.from);}else {payload.from=undefined;}if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}return payload;};/*
734
+ * Normalise the overloaded arguments of the group call facade
735
+ */var groupArgumentsToCallOptions=function groupArgumentsToCallOptions(groupId,traits,options,callback){var payload={groupId:groupId,traits:traits,options:options,callback:undefined};if(isFunction(callback)){payload.callback=callback;}if(isFunction(options)){payload.groupId=groupId;payload.traits=traits;payload.options=undefined;payload.callback=options;}if(isFunction(traits)){payload.groupId=groupId;payload.traits=undefined;payload.options=undefined;payload.callback=traits;}if(isObjectLiteralAndNotNull(groupId)||isNull(groupId)){// Explicitly set null to prevent resetting the existing value
736
+ // in the Analytics class
737
+ payload.groupId=null;payload.traits=groupId;if(!isFunction(traits)){payload.options=traits;}else {payload.options=undefined;}}// Rest of the code is just to clean up undefined values
738
+ // and set some proper defaults
739
+ // Also, to clone the incoming object type arguments
740
+ payload.groupId=tryStringify(payload.groupId);if(isObjectLiteralAndNotNull(payload.traits)){payload.traits=clone(payload.traits);}else {payload.traits=undefined;}if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}return payload;};
741
+
742
+ /**
743
+ * Represents the options parameter for anonymousId
744
+ *//**
745
+ * Represents the beacon queue options parameter in loadOptions type
746
+ *//**
747
+ * Represents the queue options parameter in loadOptions type
748
+ *//**
749
+ * Represents the destinations queue options parameter in loadOptions type
750
+ */var PageLifecycleEvents=/*#__PURE__*/function(PageLifecycleEvents){PageLifecycleEvents["UNLOADED"]="Page Unloaded";return PageLifecycleEvents;}({});/**
751
+ * Represents the source configuration override options for destinations
752
+ *//**
753
+ * Represents the options parameter in the load API
754
+ */
755
+
756
+ var API_SUFFIX='API';var CAPABILITIES_MANAGER='CapabilitiesManager';var CONFIG_MANAGER='ConfigManager';var EVENT_MANAGER='EventManager';var PLUGINS_MANAGER='PluginsManager';var USER_SESSION_MANAGER='UserSessionManager';var ERROR_HANDLER='ErrorHandler';var PLUGIN_ENGINE='PluginEngine';var STORE_MANAGER='StoreManager';var READY_API="Ready".concat(API_SUFFIX);var LOAD_API="Load".concat(API_SUFFIX);var HTTP_CLIENT='HttpClient';var RSA='RudderStackAnalytics';var ANALYTICS_CORE='AnalyticsCore';
757
+
758
+ function random(len){return crypto.getRandomValues(new Uint8Array(len));}
759
+
760
+ 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;}
761
+
762
+ 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;}
763
+
764
+ var hasCrypto$1=function hasCrypto(){return !isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);};
765
+
766
+ var generateUUID=function generateUUID(){if(hasCrypto$1()){return v4$1();}return v4();};
767
+
768
+ /**
769
+ * Determines if the SDK is running inside a chrome extension
770
+ * @returns boolean
771
+ */var isSDKRunningInChromeExtension=function isSDKRunningInChromeExtension(){var _chrome;return !!((_chrome=window.chrome)!==null&&_chrome!==void 0&&(_chrome=_chrome.runtime)!==null&&_chrome!==void 0&&_chrome.id);};var isIE11=function isIE11(){return isString(globalThis.navigator.userAgent)&&/Trident.*rv:11\./.test(globalThis.navigator.userAgent);};
772
+
773
+ /**
774
+ * Registers events to detect page leave scenarios
775
+ * @param callback Callback function
776
+ * @param avoidBfCacheOptimization When `true`, forcefully subscribes to beforeunload event, compromising on the bfcache optimization
777
+ */var onPageLeave=function onPageLeave(callback){var avoidBfCacheOptimization=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;// To ensure the callback is only called once even if more than one events
778
+ // are fired at once.
779
+ var pageLeft=false;var isAccessible=false;function handleOnLeave(){if(pageLeft){return;}pageLeft=true;callback(isAccessible);// Reset pageLeft on the next tick
780
+ // to ensure callback executes for other listeners
781
+ // when closing an inactive browser tab.
782
+ setTimeout(function(){pageLeft=false;},0);}// Catches the unloading of the page (e.g., closing the tab or navigating away).
783
+ // Includes user actions like clicking a link, entering a new URL,
784
+ // refreshing the page, or closing the browser tab
785
+ // Note that 'pagehide' is not supported in IE.
786
+ // Registering this event conditionally for IE11 also because
787
+ // it affects bfcache optimization on modern browsers otherwise.
788
+ // However, if optimization is disabled, force subscribe the event
789
+ if(avoidBfCacheOptimization||isIE11()){globalThis.addEventListener('beforeunload',function(){isAccessible=false;handleOnLeave();});}// This is important for iOS Safari browser as it does not
790
+ // fire the regular pagehide and visibilitychange events
791
+ // when user goes to tablist view and closes the tab.
792
+ globalThis.addEventListener('blur',function(){isAccessible=true;handleOnLeave();});globalThis.addEventListener('focus',function(){pageLeft=false;});// Catches the page being hidden, including scenarios like closing the tab.
793
+ document.addEventListener('pagehide',function(){isAccessible=document.visibilityState==='hidden';handleOnLeave();});// Catches visibility changes, such as switching tabs or minimizing the browser.
794
+ document.addEventListener('visibilitychange',function(){isAccessible=true;if(document.visibilityState==='hidden'){handleOnLeave();}else {pageLeft=false;}});};
795
+
796
+ var getFormattedTimestamp=function getFormattedTimestamp(date){return date.toISOString();};/**
797
+ * To get the current timestamp in ISO string format
798
+ * @returns ISO formatted timestamp string
799
+ */var getCurrentTimeFormatted=function getCurrentTimeFormatted(){return getFormattedTimestamp(new Date());};
800
+
801
+ var LOG_CONTEXT_SEPARATOR=':: ';var SCRIPT_ALREADY_EXISTS_ERROR=function SCRIPT_ALREADY_EXISTS_ERROR(id){return "A script with the id \"".concat(id,"\" is already loaded. Skipping the loading of this script to prevent conflicts");};var SCRIPT_LOAD_ERROR=function SCRIPT_LOAD_ERROR(id,url,ev){return "Unable to load (".concat(isString(ev)?ev:ev.type,") the script with the id \"").concat(id,"\" from URL \"").concat(url,"\"");};var SCRIPT_LOAD_TIMEOUT_ERROR=function SCRIPT_LOAD_TIMEOUT_ERROR(id,url,timeout){return "A timeout of ".concat(timeout," ms occurred while trying to load the script with id \"").concat(id,"\" from URL \"").concat(url,"\"");};var CIRCULAR_REFERENCE_WARNING=function CIRCULAR_REFERENCE_WARNING(context,key){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"A circular reference has been detected in the object and the property \"").concat(key,"\" has been dropped from the output.");};var JSON_STRINGIFY_WARNING="Failed to convert the value to a JSON string.";var COOKIE_DATA_ENCODING_ERROR="Failed to encode the cookie data.";var STORAGE_UNAVAILABILITY_ERROR_PREFIX=function STORAGE_UNAVAILABILITY_ERROR_PREFIX(context,storageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(storageType,"\" storage type is ");};
802
+
803
+ var JSON_STRINGIFY='JSONStringify';var BIG_INT_PLACEHOLDER='[BigInt]';var CIRCULAR_REFERENCE_PLACEHOLDER='[Circular Reference]';var getCircularReplacer=function getCircularReplacer(excludeNull,excludeKeys,logger){var ancestors=[];// Here we do not want to use arrow function to use "this" in function context
804
+ // eslint-disable-next-line func-names
805
+ return function(key,value){if(excludeKeys!==null&&excludeKeys!==void 0&&excludeKeys.includes(key)){return undefined;}if(excludeNull&&isNullOrUndefined(value)){return undefined;}if(_typeof(value)!=='object'||isNull(value)){return value;}// `this` is the object that value is contained in, i.e., its direct parent.
806
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
807
+ // @ts-ignore-next-line
808
+ while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();}if(ancestors.includes(value)){logger===null||logger===void 0||logger.warn(CIRCULAR_REFERENCE_WARNING(JSON_STRINGIFY,key));return CIRCULAR_REFERENCE_PLACEHOLDER;}ancestors.push(value);return value;};};/**
809
+ * Utility method for JSON stringify object excluding null values & circular references
810
+ *
811
+ * @param {*} value input
812
+ * @param {boolean} excludeNull if it should exclude nul or not
813
+ * @param {function} logger optional logger methods for warning
814
+ * @returns string
815
+ */var stringifyWithoutCircular=function stringifyWithoutCircular(value,excludeNull,excludeKeys,logger){try{return JSON.stringify(value,getCircularReplacer(excludeNull,excludeKeys,logger));}catch(err){logger===null||logger===void 0||logger.warn(JSON_STRINGIFY_WARNING,err);return null;}};var getReplacer=function getReplacer(logger){var ancestors=[];// Array to track ancestor objects
816
+ // Using a regular function to use `this` for the parent context
817
+ return function replacer(key,value){if(isBigInt(value)){return BIG_INT_PLACEHOLDER;// Replace BigInt values
818
+ }// `this` is the object that value is contained in, i.e., its direct parent.
819
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
820
+ // @ts-ignore-next-line
821
+ while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();// Remove ancestors that are no longer part of the chain
822
+ }// Check for circular references (if the value is already in the ancestors)
823
+ if(ancestors.includes(value)){return CIRCULAR_REFERENCE_PLACEHOLDER;}// Add current value to ancestors
824
+ ancestors.push(value);return value;};};var _traverseWithThis=function traverseWithThis(obj,replacer){// Create a new result object or array
825
+ var result=Array.isArray(obj)?[]:{};// Traverse object properties or array elements
826
+ // eslint-disable-next-line no-restricted-syntax
827
+ for(var key in obj){if(Object.hasOwnProperty.call(obj,key)){var value=obj[key];// Recursively apply the replacer and traversal
828
+ var sanitizedValue=replacer.call(obj,key,value);// If the value is an object or array, continue traversal
829
+ if(isObjectLiteralAndNotNull(sanitizedValue)||Array.isArray(sanitizedValue)){result[key]=_traverseWithThis(sanitizedValue,replacer);}else {result[key]=sanitizedValue;}}}return result;};/**
830
+ * Recursively traverses an object similar to JSON.stringify,
831
+ * sanitizing BigInts and circular references
832
+ * @param value Input object
833
+ * @param logger Logger instance
834
+ * @returns Sanitized value
835
+ */var getSanitizedValue=function getSanitizedValue(value,logger){var replacer=getReplacer();// This is needed for registering the first ancestor
836
+ var newValue=replacer.call(value,'',value);if(isObjectLiteralAndNotNull(value)||Array.isArray(value)){return _traverseWithThis(value,replacer);}return newValue;};
837
+
838
+ var MANUAL_ERROR_IDENTIFIER='[SDK DISPATCHED ERROR]';var getStacktrace=function getStacktrace(err){var _ref;var stack=err.stack,stacktrace=err.stacktrace,operaSourceloc=err['opera#sourceloc'];var stackString=(_ref=stack!==null&&stack!==void 0?stack:stacktrace)!==null&&_ref!==void 0?_ref:operaSourceloc;if(!!stackString&&typeof stackString==='string'){return stackString;}return undefined;};/**
839
+ * Get mutated error with issue prepended to error message
840
+ * @param err Original error
841
+ * @param issue Issue to prepend to error message
842
+ * @returns Instance of Error with message prepended with issue
843
+ */var getMutatedError=function getMutatedError(err,issue){if(!isTypeOfError(err)){return new Error("".concat(issue,": ").concat(stringifyWithoutCircular(err)));}try{// Preserve the specific error type (TypeError, ReferenceError, etc.)
844
+ var ErrorConstructor=err.constructor;var newError=new ErrorConstructor("".concat(issue,": ").concat(err.message));// Preserve stack trace
845
+ var stack=getStacktrace(err);if(stack){newError.stack=stack;}// Preserve any other enumerable properties
846
+ Object.getOwnPropertyNames(err).forEach(function(key){if(key!=='message'&&key!=='stack'&&key!=='name'){try{newError[key]=err[key];}catch(_unused){// Ignore if property is not writable
847
+ }}});return newError;}catch(_unused2){return new Error("".concat(issue,": ").concat(stringifyWithoutCircular(err)));}};var dispatchErrorEvent=function dispatchErrorEvent(error){if(isTypeOfError(error)){var errStack=getStacktrace(error);if(errStack){var stack=error.stack,stacktrace=error.stacktrace,operaSourceloc=error['opera#sourceloc'];switch(errStack){case stack:// eslint-disable-next-line no-param-reassign
848
+ error.stack="".concat(stack,"\n").concat(MANUAL_ERROR_IDENTIFIER);break;case stacktrace:// eslint-disable-next-line no-param-reassign
849
+ error.stacktrace="".concat(stacktrace,"\n").concat(MANUAL_ERROR_IDENTIFIER);break;case operaSourceloc:default:// eslint-disable-next-line no-param-reassign
850
+ error['opera#sourceloc']="".concat(operaSourceloc,"\n").concat(MANUAL_ERROR_IDENTIFIER);break;}}}globalThis.dispatchEvent(new ErrorEvent('error',{error:error,bubbles:true,cancelable:true,composed:true}));};
851
+
852
+ var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.29.0';var APP_NAMESPACE='com.rudderlabs.javascript';var MODULE_TYPE='npm';var BUILD_VARIANT='legacy-lite';var ADBLOCK_PAGE_CATEGORY='RudderJS-Initiated';var ADBLOCK_PAGE_NAME='ad-block page request';var ADBLOCK_PAGE_PATH='/ad-blocked';var GLOBAL_PRELOAD_BUFFER='preloadedEventsBuffer';var CONSENT_TRACK_EVENT_NAME='Consent Management Interaction';
853
+
854
+ var QUERY_PARAM_TRAIT_PREFIX='ajs_trait_';var QUERY_PARAM_PROPERTY_PREFIX='ajs_prop_';var QUERY_PARAM_ANONYMOUS_ID_KEY='ajs_aid';var QUERY_PARAM_USER_ID_KEY='ajs_uid';var QUERY_PARAM_TRACK_EVENT_NAME_KEY='ajs_event';
855
+
856
+ var DEFAULT_XHR_TIMEOUT_MS=10*1000;// 10 seconds
857
+ var DEFAULT_COOKIE_MAX_AGE_MS=31536000*1000;// 1 year
858
+ var DEFAULT_SESSION_CUT_OFF_DURATION_MS=12*60*60*1000;// 12 hours
859
+ var DEFAULT_SESSION_TIMEOUT_MS=30*60*1000;// 30 minutes
860
+ var MIN_SESSION_TIMEOUT_MS=10*1000;// 10 seconds
861
+ var DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS=10*1000;// 10 seconds
862
+ var DEBOUNCED_TIMEOUT_MS=250;// 250 milliseconds
863
+
864
+ /**
865
+ * Create globally accessible RudderStackGlobals object
866
+ */var createExposedGlobals=function createExposedGlobals(){var analyticsInstanceId=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'app';if(!globalThis.RudderStackGlobals){globalThis.RudderStackGlobals={};}if(!globalThis.RudderStackGlobals[analyticsInstanceId]){globalThis.RudderStackGlobals[analyticsInstanceId]={};}};/**
867
+ * Add move values to globally accessible RudderStackGlobals object per analytics instance
868
+ */var setExposedGlobal=function setExposedGlobal(keyName,value){var analyticsInstanceId=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'app';createExposedGlobals(analyticsInstanceId);globalThis.RudderStackGlobals[analyticsInstanceId][keyName]=value;};/**
869
+ * Get values from globally accessible RudderStackGlobals object by analytics instance
870
+ */var getExposedGlobal=function getExposedGlobal(keyName){var analyticsInstanceId=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'app';createExposedGlobals(analyticsInstanceId);return globalThis.RudderStackGlobals[analyticsInstanceId][keyName];};function debounce(func,thisArg){var delay=arguments.length>2&&arguments[2]!==undefined?arguments[2]:DEBOUNCED_TIMEOUT_MS;var timeoutId;return function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}globalThis.clearTimeout(timeoutId);timeoutId=globalThis.setTimeout(function(){func.apply(thisArg,args);},delay);};}
871
+
872
+ /**
873
+ * Parse query string params into object values for keys that start with a defined prefix
874
+ */var getEventDataFromQueryString=function getEventDataFromQueryString(params,dataTypeNamePrefix){var data={};params.forEach(function(value,key){if(key.startsWith(dataTypeNamePrefix)){// remove prefix from key name
875
+ var dataKey=key.substring(dataTypeNamePrefix.length);// add new key value pair in generated object
876
+ data[dataKey]=params.get(key);}});return data;};/**
877
+ * Parse query string into preload buffer events & push into existing array before any other events
878
+ */var retrieveEventsFromQueryString=function retrieveEventsFromQueryString(){var argumentsArray=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];// Mapping for trait and properties values based on key prefix
879
+ var eventArgumentToQueryParamMap={trait:QUERY_PARAM_TRAIT_PREFIX,properties:QUERY_PARAM_PROPERTY_PREFIX};var queryObject=new URLSearchParams(globalThis.location.search);// Add track events with name and properties
880
+ if(queryObject.get(QUERY_PARAM_TRACK_EVENT_NAME_KEY)){argumentsArray.unshift(['track',queryObject.get(QUERY_PARAM_TRACK_EVENT_NAME_KEY),getEventDataFromQueryString(queryObject,eventArgumentToQueryParamMap.properties)]);}// Send identify event
881
+ var userId=queryObject.get(QUERY_PARAM_USER_ID_KEY);var userTraits=getEventDataFromQueryString(queryObject,eventArgumentToQueryParamMap.trait);if(userId||isNonEmptyObject(userTraits)){// In identify API, user ID is optional
882
+ var identifyApiArgs=[].concat(_toConsumableArray(userId?[userId]:[]),[userTraits]);argumentsArray.unshift(['identify'].concat(_toConsumableArray(identifyApiArgs)));}// Set anonymousID
883
+ if(queryObject.get(QUERY_PARAM_ANONYMOUS_ID_KEY)){argumentsArray.unshift(['setAnonymousId',queryObject.get(QUERY_PARAM_ANONYMOUS_ID_KEY)]);}};/**
884
+ * Retrieve an existing buffered load method call and remove from the existing array
885
+ */var getPreloadedLoadEvent=function getPreloadedLoadEvent(preloadedEventsArray){var loadMethodName='load';var loadEvent=[];/**
886
+ * Iterate the buffered API calls until we find load call and process it separately
887
+ */var i=0;while(i<preloadedEventsArray.length){if(preloadedEventsArray[i]&&preloadedEventsArray[i][0]===loadMethodName){loadEvent=clone(preloadedEventsArray[i]);preloadedEventsArray.splice(i,1);break;}i+=1;}return loadEvent;};/**
888
+ * Promote consent events to the top of the preloaded events array
889
+ * @param preloadedEventsArray Preloaded events array
890
+ * @returns None
891
+ */var promotePreloadedConsentEventsToTop=function promotePreloadedConsentEventsToTop(preloadedEventsArray){var consentMethodName='consent';var consentEvents=preloadedEventsArray.filter(function(bufferedEvent){return bufferedEvent[0]===consentMethodName;});var nonConsentEvents=preloadedEventsArray.filter(function(bufferedEvent){return bufferedEvent[0]!==consentMethodName;});// Remove all elements and add consent events first followed by non consent events
892
+ // eslint-disable-next-line unicorn/no-useless-spread
893
+ preloadedEventsArray.splice.apply(preloadedEventsArray,[0,preloadedEventsArray.length].concat(_toConsumableArray(consentEvents),_toConsumableArray(nonConsentEvents)));};/**
894
+ * Retrieve any existing events that were triggered before SDK load and enqueue in buffer
895
+ */var retrievePreloadBufferEvents=function retrievePreloadBufferEvents(instance){var preloadedEventsArray=getExposedGlobal(GLOBAL_PRELOAD_BUFFER)||[];// Get events that are pre-populated via query string params
896
+ retrieveEventsFromQueryString(preloadedEventsArray);// Enqueue the non load events in the buffer of the global rudder analytics singleton
897
+ if(preloadedEventsArray.length>0){instance.enqueuePreloadBufferEvents(preloadedEventsArray);setExposedGlobal(GLOBAL_PRELOAD_BUFFER,[]);}};var consumePreloadBufferedEvent=function consumePreloadBufferedEvent(event,analyticsInstance){var _ref;var methodName=event.shift();var callOptions;if(isFunction(analyticsInstance[methodName])){switch(methodName){case 'page':callOptions=pageArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;case 'track':callOptions=trackArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;case 'identify':callOptions=identifyArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;case 'alias':callOptions=aliasArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;case 'group':callOptions=groupArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;default:(_ref=analyticsInstance)[methodName].apply(_ref,_toConsumableArray(event));break;}if(callOptions){analyticsInstance[methodName](callOptions);}}};
898
+
899
+ var DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS=10*1000;// 10 seconds
900
+
901
+ var EXTERNAL_SOURCE_LOAD_ORIGIN='RS_JS_SDK';
902
+
903
+ /**
904
+ * Create the DOM element to load a script marked as RS SDK originated
905
+ *
906
+ * @param {*} url The URL of the script to be loaded
907
+ * @param {*} id ID for the script tag
908
+ * @param {*} async Whether to load the script in async mode. Defaults to `true` [optional]
909
+ * @param {*} onload callback to invoke onload [optional]
910
+ * @param {*} onerror callback to invoke onerror [optional]
911
+ * @param {*} extraAttributes key/value pair with html attributes to add in html tag [optional]
912
+ *
913
+ * @returns HTMLScriptElement
914
+ */var createScriptElement=function createScriptElement(url,id){var async=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;var onload=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;var onerror=arguments.length>4&&arguments[4]!==undefined?arguments[4]:null;var extraAttributes=arguments.length>5&&arguments[5]!==undefined?arguments[5]:{};var scriptElement=document.createElement('script');scriptElement.type='text/javascript';scriptElement.onload=onload;scriptElement.onerror=onerror;scriptElement.src=url;scriptElement.id=id;scriptElement.async=async;Object.keys(extraAttributes).forEach(function(attributeName){scriptElement.setAttribute(attributeName,extraAttributes[attributeName]);});scriptElement.setAttribute('data-loader',EXTERNAL_SOURCE_LOAD_ORIGIN);return scriptElement;};/**
915
+ * Add script DOM element to DOM
916
+ *
917
+ * @param {*} newScriptElement the script element to add
918
+ *
919
+ * @returns
920
+ */var insertScript=function insertScript(newScriptElement){var _scriptElements$;// First try to add it to the head
921
+ var headElements=document.getElementsByTagName('head');if(headElements.length>0){var _headElements$,_headElements$2;(_headElements$=headElements[0])===null||_headElements$===void 0||_headElements$.insertBefore(newScriptElement,(_headElements$2=headElements[0])===null||_headElements$2===void 0?void 0:_headElements$2.firstChild);return;}// Else wise add it before the first script tag
922
+ var scriptElements=document.getElementsByTagName('script');if(scriptElements.length>0&&(_scriptElements$=scriptElements[0])!==null&&_scriptElements$!==void 0&&_scriptElements$.parentNode){var _scriptElements$2;(_scriptElements$2=scriptElements[0])===null||_scriptElements$2===void 0||_scriptElements$2.parentNode.insertBefore(newScriptElement,scriptElements[0]);return;}// Create a new head element and add the script as fallback
923
+ var headElement=document.createElement('head');headElement.appendChild(newScriptElement);var htmlElement=document.getElementsByTagName('html')[0];htmlElement===null||htmlElement===void 0||htmlElement.insertBefore(headElement,htmlElement.firstChild);};/**
924
+ * Loads external js file as a script html tag
925
+ *
926
+ * @param {*} url The URL of the script to be loaded
927
+ * @param {*} id ID for the script tag
928
+ * @param {*} timeout loading timeout
929
+ * @param {*} async Whether to load the script in async mode. Defaults to `true` [optional]
930
+ * @param {*} extraAttributes key/value pair with html attributes to add in html tag [optional]
931
+ *
932
+ * @returns
933
+ */var jsFileLoader=function jsFileLoader(url,id,timeout){var async=arguments.length>3&&arguments[3]!==undefined?arguments[3]:true;var extraAttributes=arguments.length>4?arguments[4]:undefined;return new Promise(function(resolve,reject){var scriptExists=document.getElementById(id);if(scriptExists){reject(new Error(SCRIPT_ALREADY_EXISTS_ERROR(id)));}try{var timeoutID;var onload=function onload(){globalThis.clearTimeout(timeoutID);resolve(id);};var onerror=function onerror(ev){globalThis.clearTimeout(timeoutID);reject(new Error(SCRIPT_LOAD_ERROR(id,url,ev)));};// Create the DOM element to load the script and add it to the DOM
934
+ insertScript(createScriptElement(url,id,async,onload,onerror,extraAttributes));// Reject on timeout
935
+ timeoutID=globalThis.setTimeout(function(){reject(new Error(SCRIPT_LOAD_TIMEOUT_ERROR(id,url,timeout)));},timeout);}catch(err){reject(getMutatedError(err,SCRIPT_LOAD_ERROR(id,url,'unknown')));}});};
936
+
937
+ /**
938
+ * Service to load external resources/files
939
+ */var ExternalSrcLoader=/*#__PURE__*/function(){function ExternalSrcLoader(logger){var timeout=arguments.length>1&&arguments[1]!==undefined?arguments[1]:DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS;_classCallCheck(this,ExternalSrcLoader);this.logger=logger;this.timeout=timeout;}/**
940
+ * Load external resource of type javascript
941
+ */return _createClass(ExternalSrcLoader,[{key:"loadJSFile",value:function loadJSFile(config){var url=config.url,id=config.id,timeout=config.timeout,async=config.async,callback=config.callback,extraAttributes=config.extraAttributes;var isFireAndForget=!isFunction(callback);jsFileLoader(url,id,timeout||this.timeout,async,extraAttributes).then(function(id){if(!isFireAndForget){callback(id);}}).catch(function(err){if(!isFireAndForget){callback(id,err);}});}}]);}();
942
+
943
+ var i=Symbol.for("preact-signals");function t(){if(!(s>1)){var i,t=false;while(void 0!==h){var n=h;h=void 0;v++;while(void 0!==n){var r=n.o;n.o=void 0;n.f&=-3;if(!(8&n.f)&&a(n))try{n.c();}catch(n){if(!t){i=n;t=true;}}n=r;}}v=0;s--;if(t)throw i;}else s--;}function n(i){if(s>0)return i();s++;try{return i();}finally{t();}}var r=void 0;function o(i){var t=r;r=void 0;try{return i();}finally{r=t;}}var h=void 0,s=0,v=0,u=0;function e(i){if(void 0!==r){var t=i.n;if(void 0===t||t.t!==r){t={i:0,S:i,p:r.s,n:void 0,t:r,e:void 0,x:void 0,r:t};if(void 0!==r.s)r.s.n=t;r.s=t;i.n=t;if(32&r.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=r.s;t.n=void 0;r.s.n=t;r.s=t;}return t;}}}function d(i,t){this.v=i;this.i=0;this.n=void 0;this.t=void 0;this.W=null==t?void 0:t.watched;this.Z=null==t?void 0:t.unwatched;this.name=null==t?void 0:t.name;}d.prototype.brand=i;d.prototype.h=function(){return true;};d.prototype.S=function(i){var t=this,n=this.t;if(n!==i&&void 0===i.e){i.x=n;this.t=i;if(void 0!==n)n.e=i;else o(function(){var i;null==(i=t.W)||i.call(t);});}};d.prototype.U=function(i){var t=this;if(void 0!==this.t){var n=i.e,r=i.x;if(void 0!==n){n.x=r;i.e=void 0;}if(void 0!==r){r.e=n;i.x=void 0;}if(i===this.t){this.t=r;if(void 0===r)o(function(){var i;null==(i=t.Z)||i.call(t);});}}};d.prototype.subscribe=function(i){var t=this;return m(function(){var n=t.value,o=r;r=void 0;try{i(n);}finally{r=o;}},{name:"sub"});};d.prototype.valueOf=function(){return this.value;};d.prototype.toString=function(){return this.value+"";};d.prototype.toJSON=function(){return this.value;};d.prototype.peek=function(){var i=r;r=void 0;try{return this.value;}finally{r=i;}};Object.defineProperty(d.prototype,"value",{get:function get(){var i=e(this);if(void 0!==i)i.i=this.i;return this.v;},set:function set(i){if(i!==this.v){if(v>100)throw new Error("Cycle detected");this.v=i;this.i++;u++;s++;try{for(var n=this.t;void 0!==n;n=n.x)n.t.N();}finally{t();}}}});function c(i,t){return new d(i,t);}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 true;return false;}function l(i){for(var t=i.s;void 0!==t;t=t.n){var n=t.S.n;if(void 0!==n)t.r=n;t.S.n=t;t.i=-1;if(void 0===t.n){i.s=t;break;}}}function y(i){var t=i.s,n=void 0;while(void 0!==t){var r=t.p;if(-1===t.i){t.S.U(t);if(void 0!==r)r.n=t.n;if(void 0!==t.n)t.n.p=r;}else n=t;t.S.n=t.r;if(void 0!==t.r)t.r=void 0;t=r;}i.s=n;}function w(i,t){d.call(this,void 0);this.x=i;this.s=void 0;this.g=u-1;this.f=4;this.W=null==t?void 0:t.watched;this.Z=null==t?void 0:t.unwatched;this.name=null==t?void 0:t.name;}w.prototype=new d();w.prototype.h=function(){this.f&=-3;if(1&this.f)return false;if(32==(36&this.f))return true;this.f&=-5;if(this.g===u)return true;this.g=u;this.f|=1;if(this.i>0&&!a(this)){this.f&=-2;return true;}var i=r;try{l(this);r=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++;}r=i;y(this);this.f&=-2;return true;};w.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);}d.prototype.S.call(this,i);};w.prototype.U=function(i){if(void 0!==this.t){d.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);}}};w.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var i=this.t;void 0!==i;i=i.x)i.t.N();}};Object.defineProperty(w.prototype,"value",{get:function get(){if(1&this.f)throw new Error("Cycle detected");var i=e(this);this.h();if(void 0!==i)i.i=this.i;if(16&this.f)throw this.v;return this.v;}});function _(i){var n=i.u;i.u=void 0;if("function"==typeof n){s++;var o=r;r=void 0;try{n();}catch(t){i.f&=-2;i.f|=8;p(i);throw t;}finally{r=o;t();}}}function p(i){for(var t=i.s;void 0!==t;t=t.n)t.S.U(t);i.x=void 0;i.s=void 0;_(i);}function g(i){if(r!==this)throw new Error("Out-of-order effect");y(this);r=i;this.f&=-2;if(8&this.f)p(this);t();}function S(i,t){this.x=i;this.u=void 0;this.s=void 0;this.o=void 0;this.f=32;this.name=null==t?void 0:t.name;}S.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();}};S.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1;this.f&=-9;_(this);l(this);s++;var i=r;r=this;return g.bind(this,i);};S.prototype.N=function(){if(!(2&this.f)){this.f|=2;this.o=h;h=this;}};S.prototype.d=function(){this.f|=8;if(!(1&this.f))p(this);};S.prototype.dispose=function(){this.d();};function m(i,t){var n=new S(i,t);try{n.c();}catch(i){n.d();throw i;}var r=n.d.bind(n);r[Symbol.dispose]=r;return r;}
944
+
945
+ /**
946
+ * A buffer queue to serve as a store for any type of data
947
+ */var BufferQueue=/*#__PURE__*/function(){function BufferQueue(){_classCallCheck(this,BufferQueue);this.items=[];}return _createClass(BufferQueue,[{key:"enqueue",value:function enqueue(item){this.items.push(item);}},{key:"dequeue",value:function dequeue(){if(this.items.length===0){return null;}return this.items.shift();}},{key:"isEmpty",value:function isEmpty(){return this.items.length===0;}},{key:"size",value:function size(){return this.items.length;}},{key:"clear",value:function clear(){this.items=[];}}]);}();
948
+
949
+ var LOG_LEVEL_MAP={LOG:0,INFO:1,DEBUG:2,WARN:3,ERROR:4,NONE:5};var DEFAULT_LOG_LEVEL='LOG';var POST_LOAD_LOG_LEVEL='ERROR';var LOG_MSG_PREFIX='RS SDK';var LOG_MSG_PREFIX_STYLE='font-weight: bold; background: black; color: white;';var LOG_MSG_STYLE='font-weight: normal;';/**
950
+ * Service to log messages/data to output provider, default is console
951
+ */var Logger=/*#__PURE__*/function(){function Logger(){var minLogLevel=arguments.length>0&&arguments[0]!==undefined?arguments[0]:DEFAULT_LOG_LEVEL;var scope=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var logProvider=arguments.length>2&&arguments[2]!==undefined?arguments[2]:console;_classCallCheck(this,Logger);this.minLogLevel=LOG_LEVEL_MAP[minLogLevel];this.scope=scope;this.logProvider=logProvider;}return _createClass(Logger,[{key:"log",value:function log(){for(var _len=arguments.length,data=new Array(_len),_key=0;_key<_len;_key++){data[_key]=arguments[_key];}this.outputLog('LOG',data);}},{key:"info",value:function info(){for(var _len2=arguments.length,data=new Array(_len2),_key2=0;_key2<_len2;_key2++){data[_key2]=arguments[_key2];}this.outputLog('INFO',data);}},{key:"debug",value:function debug(){for(var _len3=arguments.length,data=new Array(_len3),_key3=0;_key3<_len3;_key3++){data[_key3]=arguments[_key3];}this.outputLog('DEBUG',data);}},{key:"warn",value:function warn(){for(var _len4=arguments.length,data=new Array(_len4),_key4=0;_key4<_len4;_key4++){data[_key4]=arguments[_key4];}this.outputLog('WARN',data);}},{key:"error",value:function error(){for(var _len5=arguments.length,data=new Array(_len5),_key5=0;_key5<_len5;_key5++){data[_key5]=arguments[_key5];}this.outputLog('ERROR',data);}},{key:"outputLog",value:function outputLog(logMethod,data){if(this.minLogLevel<=LOG_LEVEL_MAP[logMethod]){var _this$logProvider,_this$logProvider2;(_this$logProvider=(_this$logProvider2=this.logProvider)[logMethod.toLowerCase()])===null||_this$logProvider===void 0||_this$logProvider.call.apply(_this$logProvider,[_this$logProvider2].concat(_toConsumableArray(this.formatLogData(data))));}}},{key:"setScope",value:function setScope(scopeVal){this.scope=scopeVal||this.scope;}// TODO: should we allow to change the level via global variable on run time
952
+ // to assist on the fly debugging?
953
+ },{key:"setMinLogLevel",value:function setMinLogLevel(logLevel){this.minLogLevel=LOG_LEVEL_MAP[logLevel];if(isUndefined(this.minLogLevel)){this.minLogLevel=LOG_LEVEL_MAP[DEFAULT_LOG_LEVEL];}}/**
954
+ * Formats the console message using `scope` and styles
955
+ */},{key:"formatLogData",value:function formatLogData(data){if(Array.isArray(data)&&data.length>0){// prefix SDK identifier
956
+ var msg="%c ".concat(LOG_MSG_PREFIX);// format the log message using `scope`
957
+ if(this.scope){msg="".concat(msg," - ").concat(this.scope);}// trim whitespaces for original message
958
+ var originalMsg=isString(data[0])?data[0].trim():'';// prepare the final message
959
+ msg="".concat(msg," %c ").concat(originalMsg);var styledLogArgs=[msg,LOG_MSG_PREFIX_STYLE,// add style for the prefix
960
+ LOG_MSG_STYLE// reset the style for the actual message
961
+ ];// add first it if it was not a string msg
962
+ if(!isString(data[0])){styledLogArgs.push(data[0]);}// append rest of the original arguments
963
+ styledLogArgs.push.apply(styledLogArgs,_toConsumableArray(data.slice(1)));return styledLogArgs;}return data;}}]);}();var defaultLogger=new Logger();
964
+
965
+ var ErrorType=/*#__PURE__*/function(ErrorType){ErrorType["HANDLEDEXCEPTION"]="handledException";ErrorType["UNHANDLEDEXCEPTION"]="unhandledException";ErrorType["UNHANDLEDREJECTION"]="unhandledPromiseRejection";return ErrorType;}({});
966
+
967
+ // default is v3
968
+ var SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','sessionStorage','none'];var DEFAULT_STORAGE_TYPE='cookieStorage';
969
+
970
+ var SOURCE_CONFIG_RESOLUTION_ERROR="Unable to process/parse source configuration response";var SOURCE_DISABLED_ERROR="The source is disabled. Please enable the source in the dashboard to send events.";var XHR_PAYLOAD_PREP_ERROR="Failed to prepare data for the request.";var PLUGIN_EXT_POINT_MISSING_ERROR="Failed to invoke plugin because the extension point name is missing.";var PLUGIN_EXT_POINT_INVALID_ERROR="Failed to invoke plugin because the extension point name is invalid.";var SOURCE_CONFIG_OPTION_ERROR=function SOURCE_CONFIG_OPTION_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"getSourceConfig\" load API option must be a function that returns valid source configuration data.");};var COMPONENT_BASE_URL_ERROR=function COMPONENT_BASE_URL_ERROR(context,component,url){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The base URL \"").concat(url,"\" for ").concat(component," is not valid.");};// ERROR
971
+ var UNSUPPORTED_CONSENT_MANAGER_ERROR=function UNSUPPORTED_CONSENT_MANAGER_ERROR(context,selectedConsentManager,consentManagersToPluginNameMap){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The consent manager \"").concat(selectedConsentManager,"\" is not supported. Please choose one of the following supported consent managers: \"").concat(Object.keys(consentManagersToPluginNameMap),"\".");};var NON_ERROR_WARNING=function NON_ERROR_WARNING(context,errStr){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Ignoring a non-error: ").concat(errStr,".");};var BREADCRUMB_ERROR="Failed to log breadcrumb";var HANDLE_ERROR_FAILURE=function HANDLE_ERROR_FAILURE(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to handle the error.");};var PLUGIN_NAME_MISSING_ERROR=function PLUGIN_NAME_MISSING_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin name is missing.");};var PLUGIN_ALREADY_EXISTS_ERROR=function PLUGIN_ALREADY_EXISTS_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" already exists.");};var PLUGIN_NOT_FOUND_ERROR=function PLUGIN_NOT_FOUND_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found.");};var PLUGIN_ENGINE_BUG_ERROR=function PLUGIN_ENGINE_BUG_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.");};var PLUGIN_DEPS_ERROR=function PLUGIN_DEPS_ERROR(context,pluginName,notExistDeps){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" could not be loaded because some of its dependencies \"").concat(notExistDeps,"\" do not exist.");};var PLUGIN_INVOCATION_ERROR=function PLUGIN_INVOCATION_ERROR(context,extPoint,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to invoke the \"").concat(extPoint,"\" extension point of plugin \"").concat(pluginName,"\".");};var SOURCE_CONFIG_FETCH_ERROR='Failed to fetch the source config';var WRITE_KEY_VALIDATION_ERROR=function WRITE_KEY_VALIDATION_ERROR(context,writeKey){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The write key \"").concat(writeKey,"\" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.");};var DATA_PLANE_URL_VALIDATION_ERROR=function DATA_PLANE_URL_VALIDATION_ERROR(context,dataPlaneUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The data plane URL \"").concat(dataPlaneUrl,"\" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.");};var INVALID_CALLBACK_FN_ERROR=function INVALID_CALLBACK_FN_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided callback parameter is not a function.");};var XHR_DELIVERY_ERROR=function XHR_DELIVERY_ERROR(prefix,status,statusText,url,response){return "".concat(prefix," with status ").concat(status," (").concat(statusText,") for URL: ").concat(url,". Response: ").concat(response.trim());};var XHR_REQUEST_ERROR=function XHR_REQUEST_ERROR(prefix,e,url){return "".concat(prefix," due to timeout or no connection (").concat(e?e.type:'',") at the client side for URL: ").concat(url);};var XHR_SEND_ERROR=function XHR_SEND_ERROR(prefix,url){return "".concat(prefix," for URL: ").concat(url);};var STORE_DATA_SAVE_ERROR=function STORE_DATA_SAVE_ERROR(key){return "Failed to save the value for \"".concat(key,"\" to storage");};var STORE_DATA_FETCH_ERROR=function STORE_DATA_FETCH_ERROR(key){return "Failed to retrieve or parse data for \"".concat(key,"\" from storage");};var DATA_SERVER_REQUEST_FAIL_ERROR=function DATA_SERVER_REQUEST_FAIL_ERROR(status){return "The server responded with status ".concat(status," while setting the cookies. As a fallback, the cookies will be set client side.");};var FAILED_SETTING_COOKIE_FROM_SERVER_ERROR=function FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(key){return "The server failed to set the ".concat(key," cookie. As a fallback, the cookies will be set client side.");};var FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR="Failed to set/remove cookies via server. As a fallback, the cookies will be managed client side.";// WARNING
972
+ var STORAGE_TYPE_VALIDATION_WARNING=function STORAGE_TYPE_VALIDATION_WARNING(context,storageType,defaultStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(storageType,"\" is not supported. Please choose one of the following supported types: \"").concat(SUPPORTED_STORAGE_TYPES,"\". The default type \"").concat(defaultStorageType,"\" will be used instead.");};var UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING=function UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(context,selectedStorageEncryptionVersion,storageEncryptionVersionsToPluginNameMap,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage encryption version \"").concat(selectedStorageEncryptionVersion,"\" is not supported. Please choose one of the following supported versions: \"").concat(Object.keys(storageEncryptionVersionsToPluginNameMap),"\". The default version \"").concat(defaultVersion,"\" will be used instead.");};var STORAGE_DATA_MIGRATION_OVERRIDE_WARNING=function STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(context,storageEncryptionVersion,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage data migration has been disabled because the configured storage encryption version (").concat(storageEncryptionVersion,") is not the latest (").concat(defaultVersion,"). To enable storage data migration, please update the storage encryption version to the latest version.");};var SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING=function SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING(context,providedCookieDomain,currentCookieDomain){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided cookie domain (").concat(providedCookieDomain,") does not match the current webpage's domain (").concat(currentCookieDomain,"). Hence, the cookies will be set client-side.");};var RESERVED_KEYWORD_WARNING=function RESERVED_KEYWORD_WARNING(context,property,parentKeyPath,reservedElements){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(property,"\" property defined under \"").concat(parentKeyPath,"\" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (").concat(reservedElements,").");};var INVALID_CONTEXT_OBJECT_WARNING=function INVALID_CONTEXT_OBJECT_WARNING(logContext){return "".concat(logContext).concat(LOG_CONTEXT_SEPARATOR,"Please make sure that the \"context\" property in the event API's \"options\" argument is a valid object literal with key-value pairs.");};var UNSUPPORTED_BEACON_API_WARNING=function UNSUPPORTED_BEACON_API_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The Beacon API is not supported by your browser. The events will be sent using XHR instead.");};var TIMEOUT_NOT_NUMBER_WARNING=function TIMEOUT_NOT_NUMBER_WARNING(context,timeout,defaultValue){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value \"").concat(timeout,"\" is not a number. The default timeout of ").concat(defaultValue," ms will be used instead.");};var CUT_OFF_DURATION_NOT_NUMBER_WARNING=function CUT_OFF_DURATION_NOT_NUMBER_WARNING(context,cutOffDuration,defaultValue){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session cut off duration value \"").concat(cutOffDuration,"\" is not a number. The default cut off duration of ").concat(defaultValue," ms will be used instead.");};var CUT_OFF_DURATION_LESS_THAN_TIMEOUT_WARNING=function CUT_OFF_DURATION_LESS_THAN_TIMEOUT_WARNING(context,cutOffDuration,timeout){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session cut off duration value \"").concat(cutOffDuration,"\" ms is less than the session timeout value \"").concat(timeout,"\" ms. The cut off functionality will be disabled.");};var TIMEOUT_ZERO_WARNING=function TIMEOUT_ZERO_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value is 0, which disables the automatic session tracking feature. If you want to enable session tracking, please provide a positive integer value for the timeout.");};var TIMEOUT_NOT_RECOMMENDED_WARNING=function TIMEOUT_NOT_RECOMMENDED_WARNING(context,timeout,minTimeout){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value ").concat(timeout," ms is less than the recommended minimum of ").concat(minTimeout," ms. Please consider increasing the timeout value to ensure optimal performance and reliability.");};var INVALID_SESSION_ID_WARNING=function INVALID_SESSION_ID_WARNING(context,sessionId,minSessionIdLength){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided session ID (").concat(sessionId,") is either invalid, not a positive integer, or not at least \"").concat(minSessionIdLength,"\" digits long. A new session ID will be auto-generated instead.");};var STORAGE_QUOTA_EXCEEDED_WARNING=function STORAGE_QUOTA_EXCEEDED_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.");};var STORAGE_UNAVAILABLE_WARNING=function STORAGE_UNAVAILABLE_WARNING(context,entry,selectedStorageType,finalStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(selectedStorageType,"\" is not available for entry \"").concat(entry,"\". The SDK will initialize the entry with \"").concat(finalStorageType,"\" storage type instead.");};var CALLBACK_INVOKE_ERROR=function CALLBACK_INVOKE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The callback threw an exception");};var INVALID_CONFIG_URL_WARNING=function INVALID_CONFIG_URL_WARNING(context,configUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided source config URL \"").concat(configUrl,"\" is invalid. Using the default source config URL instead.");};var POLYFILL_SCRIPT_LOAD_ERROR=function POLYFILL_SCRIPT_LOAD_ERROR(scriptId,url){return "Failed to load the polyfill script with ID \"".concat(scriptId,"\" from URL ").concat(url,".");};var UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY=function UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(context,selectedStrategy,defaultStrategy){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent storage strategy \"").concat(selectedStrategy,"\" is not supported. Please choose one of the following supported strategies: \"none, session, anonymousId\". The default strategy \"").concat(defaultStrategy,"\" will be used instead.");};var UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE=function UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(context,selectedDeliveryType,defaultDeliveryType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent events delivery type \"").concat(selectedDeliveryType,"\" is not supported. Please choose one of the following supported types: \"immediate, buffer\". The default type \"").concat(defaultDeliveryType,"\" will be used instead.");};var DEPRECATED_PLUGIN_WARNING=function DEPRECATED_PLUGIN_WARNING(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(pluginName," plugin is deprecated. Please exclude it from the load API options.");};var generateMisconfiguredPluginsWarning=function generateMisconfiguredPluginsWarning(context,configurationStatus,missingPlugins,shouldAddMissingPlugins){var isSinglePlugin=missingPlugins.length===1;var pluginsString=isSinglePlugin?" '".concat(missingPlugins[0],"' plugin was"):" ['".concat(missingPlugins.join("', '"),"'] plugins were");var baseWarning="".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(configurationStatus,", but").concat(pluginsString," not configured to load.");if(shouldAddMissingPlugins){return "".concat(baseWarning," So, ").concat(isSinglePlugin?'the plugin':'those plugins'," will be loaded automatically.");}return "".concat(baseWarning," Ignore if this was intentional. Otherwise, consider adding ").concat(isSinglePlugin?'it':'them'," to the 'plugins' load API option.");};var INVALID_POLYFILL_URL_WARNING=function INVALID_POLYFILL_URL_WARNING(context,customPolyfillUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided polyfill URL \"").concat(customPolyfillUrl,"\" is invalid. The default polyfill URL will be used instead.");};var PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING=function PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Page Unloaded event can only be tracked when the Beacon transport is active. Please enable \"useBeacon\" load API option.");};var UNKNOWN_PLUGINS_WARNING=function UNKNOWN_PLUGINS_WARNING(context,unknownPlugins){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Ignoring unknown plugins: ").concat(unknownPlugins.join(', '),".");};var UNAVAILABLE_PLUGINS_ERROR=function UNAVAILABLE_PLUGINS_ERROR(context,unavailablePlugins){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to load the following unavailable local plugins: ").concat(unavailablePlugins.join(', '),". Some features of the SDK may not work as expected. Make sure you are using the correct SDK bundle variant.");};var CUSTOM_INTEGRATION_CANNOT_BE_ADDED_ERROR=function CUSTOM_INTEGRATION_CANNOT_BE_ADDED_ERROR(context,destinationId){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Cannot add custom integration for destination ID \"").concat(destinationId,"\" after the SDK is loaded.");};
973
+
974
+ var DEFAULT_INTEGRATIONS_CONFIG={All:true};
975
+
976
+ var CDN_INT_DIR='js-integrations';var CDN_PLUGINS_DIR='plugins';var URL_PATTERN=new RegExp('^(https?:\\/\\/)'+// protocol
977
+ '('+'((([a-zA-Z\\d]([a-zA-Z\\d-]*[a-zA-Z\\d])*)\\.)+[a-zA-Z]{2,}|'+// domain name
978
+ 'localhost|'+// localhost
979
+ '((25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9]?)\\.){3}'+// OR IP (v4) address first 3 octets
980
+ '(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9]?))'+// last octet of IP address
981
+ ')'+'(\\:\\d+)?'+// port
982
+ '(\\/[-a-zA-Z\\d%_.~+]*)*'+// path
983
+ '(\\?[;&a-zA-Z\\d%_.~+=-]*)?'+// query string
984
+ '(\\#[-a-zA-Z\\d_]*)?$')// fragment locator
985
+ ;
986
+
987
+ var BUILD_TYPE='legacy';var SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';var CDN_ARCH_VERSION_DIR='v3';var DEFAULT_INTEGRATION_SDKS_URL="".concat(SDK_CDN_BASE_URL,"/").concat(CDN_ARCH_VERSION_DIR,"/").concat(BUILD_TYPE,"/").concat(CDN_INT_DIR);var DEFAULT_PLUGINS_URL="".concat(SDK_CDN_BASE_URL,"/").concat(CDN_ARCH_VERSION_DIR,"/").concat(BUILD_TYPE,"/").concat(CDN_PLUGINS_DIR);var DEFAULT_CONFIG_BE_URL='https://api.rudderstack.com';
988
+
989
+ var DEFAULT_STORAGE_ENCRYPTION_VERSION='v3';var DEFAULT_DATA_PLANE_EVENTS_TRANSPORT='xhr';var ConsentManagersToPluginNameMap={iubenda:'IubendaConsentManager',oneTrust:'OneTrustConsentManager',ketch:'KetchConsentManager',custom:'CustomConsentManager'};var StorageEncryptionVersionsToPluginNameMap=_defineProperty(_defineProperty({},DEFAULT_STORAGE_ENCRYPTION_VERSION,'StorageEncryption'),"legacy",'StorageEncryptionLegacy');var DataPlaneEventsTransportToPluginNameMap=_defineProperty(_defineProperty({},DEFAULT_DATA_PLANE_EVENTS_TRANSPORT,'XhrQueue'),"beacon",'BeaconQueue');var DEFAULT_DATA_SERVICE_ENDPOINT='rsaRequest';var METRICS_SERVICE_ENDPOINT='rsaMetrics';var CUSTOM_DEVICE_MODE_DESTINATION_DISPLAY_NAME='Custom Device Mode';
990
+
991
+ var defaultLoadOptions={configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS,cutOff:{enabled:false}},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:DEFAULT_INTEGRATIONS_CONFIG,useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:true,lockPluginsVersion:true,uaChTrackLevel:'none',plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,dataPlaneEventsBufferTimeout:DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:false,cookie:{}},sendAdblockPage:false,sameDomainCookiesOnly:false,secureCookie:false,sendAdblockPageOptions:{},useServerSideCookies:false};var loadOptionsState=c(clone(defaultLoadOptions));
992
+
993
+ var DEFAULT_USER_SESSION_VALUES=_deepFreeze({userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{},authToken:null});var DEFAULT_RESET_OPTIONS=_deepFreeze({entries:{userId:true,userTraits:true,groupId:true,groupTraits:true,sessionInfo:true,authToken:true,// These are not reset by default
994
+ anonymousId:false,initialReferrer:false,initialReferringDomain:false}});var SERVER_SIDE_COOKIES_DEBOUNCE_TIME=10;// milliseconds
995
+
996
+ var sessionState={userId:c(DEFAULT_USER_SESSION_VALUES.userId),userTraits:c(DEFAULT_USER_SESSION_VALUES.userTraits),anonymousId:c(DEFAULT_USER_SESSION_VALUES.anonymousId),groupId:c(DEFAULT_USER_SESSION_VALUES.groupId),groupTraits:c(DEFAULT_USER_SESSION_VALUES.groupTraits),initialReferrer:c(DEFAULT_USER_SESSION_VALUES.initialReferrer),initialReferringDomain:c(DEFAULT_USER_SESSION_VALUES.initialReferringDomain),sessionInfo:c(DEFAULT_USER_SESSION_VALUES.sessionInfo),authToken:c(DEFAULT_USER_SESSION_VALUES.authToken)};
997
+
998
+ var capabilitiesState={isOnline:c(true),storage:{isLocalStorageAvailable:c(false),isCookieStorageAvailable:c(false),isSessionStorageAvailable:c(false)},isBeaconAvailable:c(false),isLegacyDOM:c(false),isUaCHAvailable:c(false),isCryptoAvailable:c(false),isIE11:c(false),isAdBlockerDetectionInProgress:c(false),isAdBlocked:c(undefined),cspBlockedURLs:c([])};
999
+
1000
+ var reportingState={isErrorReportingEnabled:c(false),isMetricsReportingEnabled:c(false),breadcrumbs:c([])};
1001
+
1002
+ var sourceConfigState=c(undefined);
1003
+
1004
+ var lifecycleState={activeDataplaneUrl:c(undefined),integrationsCDNPath:c(DEFAULT_INTEGRATION_SDKS_URL),pluginsCDNPath:c(DEFAULT_PLUGINS_URL),sourceConfigUrl:c(undefined),status:c(undefined),initialized:c(false),logLevel:c(POST_LOAD_LOG_LEVEL),loaded:c(false),readyCallbacks:c([]),writeKey:c(undefined),dataPlaneUrl:c(undefined),safeAnalyticsInstance:c(undefined)};
1005
+
1006
+ var consentsState={enabled:c(false),initialized:c(false),data:c({}),activeConsentManagerPluginName:c(undefined),preConsent:c({enabled:false}),postConsent:c({}),resolutionStrategy:c('and'),provider:c(undefined),metadata:c(undefined)};
1007
+
1008
+ var metricsState={retries:c(0),dropped:c(0),sent:c(0),queued:c(0),triggered:c(0),metricsServiceUrl:c(undefined)};
1009
+
1010
+ var getVariantValue=function getVariantValue(){// For CDN builds, use runtime window.rudderAnalyticsBuildType
1011
+ return BUILD_VARIANT;};var contextState={app:c({name:APP_NAME,namespace:APP_NAMESPACE,version:APP_VERSION,installType:MODULE_TYPE}),traits:c(null),library:c({name:APP_NAME,version:APP_VERSION,snippetVersion:globalThis.RudderSnippetVersion,variant:getVariantValue()}),userAgent:c(null),device:c(null),network:c(null),os:c({name:'',version:''}),locale:c(null),screen:c({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),'ua-ch':c(undefined),timezone:c(undefined)};
1012
+
1013
+ var nativeDestinationsState={configuredDestinations:c([]),activeDestinations:c([]),loadOnlyIntegrations:c({}),failedDestinations:c([]),loadIntegration:c(true),initializedDestinations:c([]),clientDestinationsReady:c(false),integrationsConfig:c({})};
1014
+
1015
+ var eventBufferState={toBeProcessedArray:c([]),readyCallbacksArray:c([])};
1016
+
1017
+ var pluginsState={ready:c(false),loadedPlugins:c([]),failedPlugins:c([]),pluginsToLoadFromConfig:c([]),activePlugins:c([]),totalPluginsToLoad:c(0)};
1018
+
1019
+ var storageState={encryptionPluginName:c(undefined),migrate:c(false),type:c(undefined),cookie:c(undefined),entries:c({}),trulyAnonymousTracking:c(false)};
1020
+
1021
+ var serverSideCookiesState={isEnabledServerSideCookies:c(false),dataServiceUrl:c(undefined)};
1022
+
1023
+ var dataPlaneEventsState={eventsQueuePluginName:c(undefined),deliveryEnabled:c(true)// Delivery should always happen
1024
+ };
1025
+
1026
+ var autoTrackState={enabled:c(false),pageLifecycle:{enabled:c(false),pageViewId:c(undefined),pageLoadedTimestamp:c(undefined)}};
1027
+
1028
+ var 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,serverCookies:serverSideCookiesState,dataPlaneEvents:dataPlaneEventsState,autoTrack:autoTrackState};var state=_objectSpread2({},clone(defaultStateValues));
1029
+
1030
+ function getDefaultExportFromCjs (x) {
1031
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
1032
+ }
1033
+
1034
+ var errorStackParser$1 = {exports: {}};
1035
+
1036
+ var stackframe$1 = {exports: {}};
1037
+
1038
+ var stackframe=stackframe$1.exports;var hasRequiredStackframe;function requireStackframe(){if(hasRequiredStackframe)return stackframe$1.exports;hasRequiredStackframe=1;(function(module,exports$1){(function(root,factory){/* istanbul ignore next */{module.exports=factory();}})(stackframe,function(){function _isNumber(n){return !isNaN(parseFloat(n))&&isFinite(n);}function _capitalize(str){return str.charAt(0).toUpperCase()+str.substring(1);}function _getter(p){return function(){return this[p];};}var booleanProps=['isConstructor','isEval','isNative','isToplevel'];var numericProps=['columnNumber','lineNumber'];var stringProps=['fileName','functionName','source'];var arrayProps=['args'];var objectProps=['evalOrigin'];var props=booleanProps.concat(numericProps,stringProps,arrayProps,objectProps);function StackFrame(obj){if(!obj)return;for(var i=0;i<props.length;i++){if(obj[props[i]]!==undefined){this['set'+_capitalize(props[i])](obj[props[i]]);}}}StackFrame.prototype={getArgs:function getArgs(){return this.args;},setArgs:function setArgs(v){if(Object.prototype.toString.call(v)!=='[object Array]'){throw new TypeError('Args must be an Array');}this.args=v;},getEvalOrigin:function getEvalOrigin(){return this.evalOrigin;},setEvalOrigin:function setEvalOrigin(v){if(v instanceof StackFrame){this.evalOrigin=v;}else if(v instanceof Object){this.evalOrigin=new StackFrame(v);}else {throw new TypeError('Eval Origin must be an Object or StackFrame');}},toString:function toString(){var fileName=this.getFileName()||'';var lineNumber=this.getLineNumber()||'';var columnNumber=this.getColumnNumber()||'';var functionName=this.getFunctionName()||'';if(this.getIsEval()){if(fileName){return '[eval] ('+fileName+':'+lineNumber+':'+columnNumber+')';}return '[eval]:'+lineNumber+':'+columnNumber;}if(functionName){return functionName+' ('+fileName+':'+lineNumber+':'+columnNumber+')';}return fileName+':'+lineNumber+':'+columnNumber;}};StackFrame.fromString=function StackFrame$$fromString(str){var argsStartIndex=str.indexOf('(');var argsEndIndex=str.lastIndexOf(')');var functionName=str.substring(0,argsStartIndex);var args=str.substring(argsStartIndex+1,argsEndIndex).split(',');var locationString=str.substring(argsEndIndex+1);if(locationString.indexOf('@')===0){var parts=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(locationString,'');var fileName=parts[1];var lineNumber=parts[2];var columnNumber=parts[3];}return new StackFrame({functionName:functionName,args:args||undefined,fileName:fileName,lineNumber:lineNumber||undefined,columnNumber:columnNumber||undefined});};for(var i=0;i<booleanProps.length;i++){StackFrame.prototype['get'+_capitalize(booleanProps[i])]=_getter(booleanProps[i]);StackFrame.prototype['set'+_capitalize(booleanProps[i])]=function(p){return function(v){this[p]=Boolean(v);};}(booleanProps[i]);}for(var j=0;j<numericProps.length;j++){StackFrame.prototype['get'+_capitalize(numericProps[j])]=_getter(numericProps[j]);StackFrame.prototype['set'+_capitalize(numericProps[j])]=function(p){return function(v){if(!_isNumber(v)){throw new TypeError(p+' must be a Number');}this[p]=Number(v);};}(numericProps[j]);}for(var k=0;k<stringProps.length;k++){StackFrame.prototype['get'+_capitalize(stringProps[k])]=_getter(stringProps[k]);StackFrame.prototype['set'+_capitalize(stringProps[k])]=function(p){return function(v){this[p]=String(v);};}(stringProps[k]);}return StackFrame;});})(stackframe$1);return stackframe$1.exports;}
1039
+
1040
+ var errorStackParser=errorStackParser$1.exports;var hasRequiredErrorStackParser;function requireErrorStackParser(){if(hasRequiredErrorStackParser)return errorStackParser$1.exports;hasRequiredErrorStackParser=1;(function(module,exports$1){(function(root,factory){/* istanbul ignore next */{module.exports=factory(requireStackframe());}})(errorStackParser,function ErrorStackParser(StackFrame){var FIREFOX_SAFARI_STACK_REGEXP=/(^|@)\S+:\d+/;var CHROME_IE_STACK_REGEXP=/^\s*at .*(\S+:\d+|\(native\))/m;var SAFARI_NATIVE_CODE_REGEXP=/^(eval@)?(\[native code])?$/;return {/**
1041
+ * Given an Error object, extract the most information from it.
1042
+ *
1043
+ * @param {Error} error object
1044
+ * @return {Array} of StackFrames
1045
+ */parse:function ErrorStackParser$$parse(error){if(typeof error.stacktrace!=='undefined'||typeof error['opera#sourceloc']!=='undefined'){return this.parseOpera(error);}else if(error.stack&&error.stack.match(CHROME_IE_STACK_REGEXP)){return this.parseV8OrIE(error);}else if(error.stack){return this.parseFFOrSafari(error);}else {throw new Error('Cannot parse given Error object');}},// Separate line and column numbers from a string of the form: (URI:Line:Column)
1046
+ extractLocation:function ErrorStackParser$$extractLocation(urlLike){// Fail-fast but return locations like "(native)"
1047
+ if(urlLike.indexOf(':')===-1){return [urlLike];}var regExp=/(.+?)(?::(\d+))?(?::(\d+))?$/;var parts=regExp.exec(urlLike.replace(/[()]/g,''));return [parts[1],parts[2]||undefined,parts[3]||undefined];},parseV8OrIE:function ErrorStackParser$$parseV8OrIE(error){var filtered=error.stack.split('\n').filter(function(line){return !!line.match(CHROME_IE_STACK_REGEXP);},this);return filtered.map(function(line){if(line.indexOf('(eval ')>-1){// Throw away eval information until we implement stacktrace.js/stackframe#8
1048
+ line=line.replace(/eval code/g,'eval').replace(/(\(eval at [^()]*)|(,.*$)/g,'');}var sanitizedLine=line.replace(/^\s+/,'').replace(/\(eval code/g,'(').replace(/^.*?\s+/,'');// capture and preseve the parenthesized location "(/foo/my bar.js:12:87)" in
1049
+ // case it has spaces in it, as the string is split on \s+ later on
1050
+ var location=sanitizedLine.match(/ (\(.+\)$)/);// remove the parenthesized location from the line, if it was matched
1051
+ sanitizedLine=location?sanitizedLine.replace(location[0],''):sanitizedLine;// if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine
1052
+ // because this line doesn't have function name
1053
+ var locationParts=this.extractLocation(location?location[1]:sanitizedLine);var functionName=location&&sanitizedLine||undefined;var fileName=['eval','<anonymous>'].indexOf(locationParts[0])>-1?undefined:locationParts[0];return new StackFrame({functionName:functionName,fileName:fileName,lineNumber:locationParts[1],columnNumber:locationParts[2],source:line});},this);},parseFFOrSafari:function ErrorStackParser$$parseFFOrSafari(error){var filtered=error.stack.split('\n').filter(function(line){return !line.match(SAFARI_NATIVE_CODE_REGEXP);},this);return filtered.map(function(line){// Throw away eval information until we implement stacktrace.js/stackframe#8
1054
+ if(line.indexOf(' > eval')>-1){line=line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,':$1');}if(line.indexOf('@')===-1&&line.indexOf(':')===-1){// Safari eval frames only have function names and nothing else
1055
+ return new StackFrame({functionName:line});}else {var functionNameRegex=/((.*".+"[^@]*)?[^@]*)(?:@)/;var matches=line.match(functionNameRegex);var functionName=matches&&matches[1]?matches[1]:undefined;var locationParts=this.extractLocation(line.replace(functionNameRegex,''));return new StackFrame({functionName:functionName,fileName:locationParts[0],lineNumber:locationParts[1],columnNumber:locationParts[2],source:line});}},this);},parseOpera:function ErrorStackParser$$parseOpera(e){if(!e.stacktrace||e.message.indexOf('\n')>-1&&e.message.split('\n').length>e.stacktrace.split('\n').length){return this.parseOpera9(e);}else if(!e.stack){return this.parseOpera10(e);}else {return this.parseOpera11(e);}},parseOpera9:function ErrorStackParser$$parseOpera9(e){var lineRE=/Line (\d+).*script (?:in )?(\S+)/i;var lines=e.message.split('\n');var result=[];for(var i=2,len=lines.length;i<len;i+=2){var match=lineRE.exec(lines[i]);if(match){result.push(new StackFrame({fileName:match[2],lineNumber:match[1],source:lines[i]}));}}return result;},parseOpera10:function ErrorStackParser$$parseOpera10(e){var lineRE=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i;var lines=e.stacktrace.split('\n');var result=[];for(var i=0,len=lines.length;i<len;i+=2){var match=lineRE.exec(lines[i]);if(match){result.push(new StackFrame({functionName:match[3]||undefined,fileName:match[2],lineNumber:match[1],source:lines[i]}));}}return result;},// Opera 10.65+ Error.stack very similar to FF/Safari
1056
+ parseOpera11:function ErrorStackParser$$parseOpera11(error){var filtered=error.stack.split('\n').filter(function(line){return !!line.match(FIREFOX_SAFARI_STACK_REGEXP)&&!line.match(/^Error created at/);},this);return filtered.map(function(line){var tokens=line.split('@');var locationParts=this.extractLocation(tokens.pop());var functionCall=tokens.shift()||'';var functionName=functionCall.replace(/<anonymous function(: (\w+))?>/,'$2').replace(/\([^)]*\)/g,'')||undefined;var argsRaw;if(functionCall.match(/\(([^)]*)\)/)){argsRaw=functionCall.replace(/^[^(]+\(([^)]*)\)$/,'$1');}var args=argsRaw===undefined||argsRaw==='[arguments not available]'?undefined:argsRaw.split(',');return new StackFrame({functionName:functionName,args:args,fileName:locationParts[0],lineNumber:locationParts[1],columnNumber:locationParts[2],source:line});},this);}};});})(errorStackParser$1);return errorStackParser$1.exports;}
1057
+
1058
+ var errorStackParserExports = requireErrorStackParser();
1059
+ var ErrorStackParser = /*@__PURE__*/getDefaultExportFromCjs(errorStackParserExports);
1060
+
1061
+ var GLOBAL_CODE='global code';var normalizeFunctionName=function normalizeFunctionName(name){if(isDefined(name)){return /^global code$/i.test(name)?GLOBAL_CODE:name;}return name;};/**
1062
+ * Takes a stacktrace.js style stackframe (https://github.com/stacktracejs/stackframe)
1063
+ * and returns a Bugsnag compatible stackframe (https://docs.bugsnag.com/api/error-reporting/#json-payload)
1064
+ * @param frame
1065
+ * @returns
1066
+ */var formatStackframe=function formatStackframe(frame){var f={file:frame.fileName,method:normalizeFunctionName(frame.functionName),lineNumber:frame.lineNumber,columnNumber:frame.columnNumber};// Some instances result in no file:
1067
+ // - non-error exception thrown from global code in FF
1068
+ // This adds one.
1069
+ if(f.lineNumber&&f.lineNumber>-1&&!f.file&&!f.method){f.file=GLOBAL_CODE;}return f;};var ensureString=function ensureString(str){return isString(str)?str:'';};function createException(errorClass,errorMessage,msgPrefix,stacktrace){return {errorClass:ensureString(errorClass),message:"".concat(msgPrefix).concat(ensureString(errorMessage)),type:'browserjs',stacktrace:stacktrace.reduce(function(accum,frame){var f=formatStackframe(frame);// don't include a stackframe if none of its properties are defined
1070
+ try{if(JSON.stringify(f)==='{}')return accum;return accum.concat(f);}catch(_unused){return accum;}},[])};}var normalizeError=function normalizeError(maybeError,logger){var error;if(isTypeOfError(maybeError)&&isString(getStacktrace(maybeError))){error=maybeError;}else {logger.warn(NON_ERROR_WARNING(ERROR_HANDLER,stringifyWithoutCircular(maybeError)));error=undefined;}return error;};var createBugsnagException=function createBugsnagException(error,msgPrefix){try{var stacktrace=ErrorStackParser.parse(error);return createException(error.name,error.message,msgPrefix,stacktrace);}catch(_unused2){return createException(error.name,error.message,msgPrefix,[]);}};
1071
+
1072
+ /**
1073
+ * Utility to parse XHR JSON response
1074
+ */var responseTextToJson=function responseTextToJson(responseText,onError){try{return JSON.parse(responseText||'');}catch(err){var error=getMutatedError(err,'Failed to parse response data');onError(error);}return undefined;};
1075
+
1076
+ var FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';var PLUGINS_LOAD_FAILURE_MESSAGES=[/Failed to fetch dynamically imported module: .*/];var INTEGRATIONS_LOAD_FAILURE_MESSAGES=[/Unable to load \(.*\) the script with the id .*/,/A timeout of \d+ ms occurred while trying to load the script with id .*/];var ERROR_MESSAGES_TO_BE_FILTERED=[new RegExp("".concat(FAILED_REQUEST_ERR_MSG_PREFIX,".*")),/A script with the id .* is already loaded\./];var SCRIPT_LOAD_FAILURE_MESSAGES=[].concat(PLUGINS_LOAD_FAILURE_MESSAGES,INTEGRATIONS_LOAD_FAILURE_MESSAGES);var INTEGRATIONS_ERROR_CATEGORY='integrations';var SDK_ERROR_CATEGORY='sdk';var DEFAULT_ERROR_CATEGORY=SDK_ERROR_CATEGORY;
1077
+
1078
+ var DEFAULT_XHR_REQUEST_OPTIONS={headers:{Accept:'application/json','Content-Type':'application/json;charset=UTF-8'},method:'GET'};/**
1079
+ * Utility to create request configuration based on default options
1080
+ */var createXhrRequestOptions=function createXhrRequestOptions(url,options,basicAuthHeader){var requestOptions=mergeDeepRight(DEFAULT_XHR_REQUEST_OPTIONS,options||{});if(basicAuthHeader){requestOptions.headers=mergeDeepRight(requestOptions.headers,{Authorization:basicAuthHeader});}requestOptions.url=url;return requestOptions;};/**
1081
+ * Utility implementation of XHR, fetch cannot be used as it requires explicit
1082
+ * origin allowed values and not wildcard for CORS requests with credentials and
1083
+ * this is not supported by our sourceConfig API
1084
+ */var xhrRequest=function xhrRequest(options){var timeout=arguments.length>1&&arguments[1]!==undefined?arguments[1]:DEFAULT_XHR_TIMEOUT_MS;var logger=arguments.length>2?arguments[2]:undefined;return new Promise(function(resolve,reject){var payload;if(options.sendRawData===true){payload=options.data;}else {payload=stringifyWithoutCircular(options.data,false,[],logger);if(isNull(payload)){reject({error:new Error(XHR_PAYLOAD_PREP_ERROR),undefined:undefined,options:options});// return and don't process further if the payload could not be stringified
1085
+ return;}}var xhr=new XMLHttpRequest();// eslint-disable-next-line @typescript-eslint/no-unused-vars
1086
+ var xhrReject=function xhrReject(e){reject({error:new Error(XHR_DELIVERY_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,xhr.status,xhr.statusText,options.url,xhr.responseText)),xhr:xhr,options:options});};var xhrError=function xhrError(e){reject(_objectSpread2({error:new Error(XHR_REQUEST_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,e,options.url)),xhr:xhr,options:options},(e===null||e===void 0?void 0:e.type)==='timeout'?{timedOut:true}:{}));};xhr.ontimeout=xhrError;xhr.onerror=xhrError;xhr.onload=function(){if(xhr.status>=200&&xhr.status<400){resolve({response:xhr.responseText,xhr:xhr,options:options});}else {xhrReject();}};xhr.open(options.method,options.url,true);if(options.withCredentials===true){xhr.withCredentials=true;}// The timeout property may be set only in the time interval between a call to the open method
1087
+ // and the first call to the send method in legacy browsers
1088
+ xhr.timeout=timeout;Object.keys(options.headers).forEach(function(headerName){if(options.headers[headerName]){xhr.setRequestHeader(headerName,options.headers[headerName]);}});try{xhr.send(payload);}catch(err){reject({error:getMutatedError(err,XHR_SEND_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,options.url)),xhr:xhr,options:options});}});};
1089
+
1090
+ /**
1091
+ * Service to handle data communication with APIs
1092
+ */var HttpClient=/*#__PURE__*/function(){function HttpClient(logger){_classCallCheck(this,HttpClient);this.logger=logger;this.onError=this.onError.bind(this);}return _createClass(HttpClient,[{key:"init",value:function init(errorHandler){this.errorHandler=errorHandler;}/**
1093
+ * Implement requests in a blocking way
1094
+ */},{key:"getData",value:(function(){var _getData=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(config){var url,options,timeout,isRawResponse,data,_t;return _regenerator().w(function(_context){while(1)switch(_context.p=_context.n){case 0:url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;_context.p=1;_context.n=2;return xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout,this.logger);case 2:data=_context.v;return _context.a(2,{data:isRawResponse?data.response:responseTextToJson(data.response,this.onError),details:data});case 3:_context.p=3;_t=_context.v;return _context.a(2,{data:undefined,details:_t});}},_callee,this,[[1,3]]);}));function getData(_x){return _getData.apply(this,arguments);}return getData;}()/**
1095
+ * Implement requests in a non-blocking way
1096
+ */)},{key:"getAsyncData",value:function getAsyncData(config){var _this=this;var callback=config.callback,url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;var isFireAndForget=!isFunction(callback);xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout,this.logger).then(function(data){if(!isFireAndForget){callback(isRawResponse?data.response:responseTextToJson(data.response,_this.onError),data);}}).catch(function(data){if(!isFireAndForget){callback(undefined,data);}});}/**
1097
+ * Handle errors
1098
+ */},{key:"onError",value:function onError(error,groupingHash){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError({error:error,context:HTTP_CLIENT,groupingHash:groupingHash});}/**
1099
+ * Set basic authentication header (eg writekey)
1100
+ */},{key:"setAuthHeader",value:function setAuthHeader(value){var noBtoa=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var authVal=noBtoa?value:toBase64("".concat(value,":"));this.basicAuthHeader="Basic ".concat(authVal);}/**
1101
+ * Clear basic authentication header
1102
+ */},{key:"resetAuthHeader",value:function resetAuthHeader(){this.basicAuthHeader=undefined;}}]);}();var defaultHttpClient=new HttpClient(defaultLogger);
1103
+
1104
+ var METRICS_PAYLOAD_VERSION='1';
1105
+
1106
+ // Errors from the below scripts are NOT allowed to reach Bugsnag
1107
+ var SDK_FILE_NAME_PREFIXES=function SDK_FILE_NAME_PREFIXES(){return ['rsa'// Prefix for all the SDK scripts including plugins and module federated chunks
1108
+ ];};var DEV_HOSTS=['www.test-host.com','localhost','127.0.0.1','[::1]'];// List of keys to exclude from the metadata
1109
+ // Potential PII or sensitive data
1110
+ var APP_STATE_EXCLUDE_KEYS=['userId','userTraits','groupId','groupTraits','anonymousId','config','integration',// integration instance objects
1111
+ 'eventBuffer',// pre-load event buffer (may contain PII)
1112
+ 'traits','authToken'];var NOTIFIER_NAME='RudderStack JavaScript SDK';var SDK_GITHUB_URL='git+https://github.com/rudderlabs/rudder-sdk-js.git';var SOURCE_NAME='js';
1113
+
1114
+ var detectAdBlockers=function detectAdBlockers(httpClient){state.capabilities.isAdBlockerDetectionInProgress.value=true;try{// Apparently, '?view=ad' is a query param that is blocked by majority of adblockers
1115
+ // Use source config URL here as it is very unlikely to be blocked by adblockers
1116
+ // Only the extra query param should make it vulnerable to adblockers
1117
+ // This will work even if the users proxies it.
1118
+ // The edge case where this doesn't work is when HEAD method is not allowed by the server (user's)
1119
+ var baseUrl=new URL(state.lifecycle.sourceConfigUrl.value);var url="".concat(baseUrl.origin).concat(baseUrl.pathname,"?view=ad");httpClient.getAsyncData({url:url,options:{// We actually don't need the response from the request, so we are using HEAD
1120
+ method:'HEAD',headers:{'Content-Type':undefined}},isRawResponse:true,callback:function callback(result,details){var _details$xhr;state.capabilities.isAdBlockerDetectionInProgress.value=false;// not ad blocked if the request is successful or it is not internally redirected on the client side
1121
+ // Often adblockers instead of blocking the request, they redirect it to an internal URL
1122
+ state.capabilities.isAdBlocked.value=(details===null||details===void 0?void 0:details.error)!==undefined||(details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.responseURL)!==url;}});}catch(err){// Reset the flag to prevent blocking future detection attempts
1123
+ state.capabilities.isAdBlockerDetectionInProgress.value=false;// Re-throw the error to be handled by the caller
1124
+ throw err;}};
1125
+
1126
+ var getErrInstance=function getErrInstance(err,errorType){switch(errorType){case ErrorType.UNHANDLEDEXCEPTION:{var _ref=err,error=_ref.error;return error||err;}case ErrorType.UNHANDLEDREJECTION:{return err.reason;}case ErrorType.HANDLEDEXCEPTION:default:return err;}};var createNewBreadcrumb=function createNewBreadcrumb(message){return {type:'manual',name:message,timestamp:new Date(),metaData:{}};};/**
1127
+ * A function to get the Bugsnag release stage for the current environment
1128
+ * @param getHostName Optional function to get the hostname (primarily for testing)
1129
+ * @returns 'development' if the host is empty (for file:// protocol etc.) or a dev host (localhost, 127.0.0.1, etc.), otherwise ''production'' (it'll be replaced with the actual release stage during the build)
1130
+ */var getReleaseStage=function getReleaseStage(){var getHostName=arguments.length>0&&arguments[0]!==undefined?arguments[0]:function(){return window.location.hostname;};var host=getHostName();return !host||host&&DEV_HOSTS.includes(host)?'development':'production';};var getAppStateForMetadata=function getAppStateForMetadata(state){var stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS);return stateStr!==null?JSON.parse(stateStr):{};};var getURLWithoutQueryString=function getURLWithoutQueryString(){var url=globalThis.location.href.split('?');return url[0];};var getUserDetails=function getUserDetails(source,session,lifecycle,autoTrack){var _source$value$id,_source$value,_session$sessionInfo$,_autoTrack$pageLifecy,_source$value$name,_source$value2;return {id:"".concat((_source$value$id=(_source$value=source.value)===null||_source$value===void 0?void 0:_source$value.id)!==null&&_source$value$id!==void 0?_source$value$id:lifecycle.writeKey.value,"..").concat((_session$sessionInfo$=session.sessionInfo.value.id)!==null&&_session$sessionInfo$!==void 0?_session$sessionInfo$:'NA',"..").concat((_autoTrack$pageLifecy=autoTrack.pageLifecycle.pageViewId.value)!==null&&_autoTrack$pageLifecy!==void 0?_autoTrack$pageLifecy:'NA'),name:(_source$value$name=(_source$value2=source.value)===null||_source$value2===void 0?void 0:_source$value2.name)!==null&&_source$value$name!==void 0?_source$value$name:'NA'};};var getDeviceDetails=function getDeviceDetails(locale,userAgent){var _locale$value,_userAgent$value;return {locale:(_locale$value=locale.value)!==null&&_locale$value!==void 0?_locale$value:'NA',userAgent:(_userAgent$value=userAgent.value)!==null&&_userAgent$value!==void 0?_userAgent$value:'NA',time:new Date()};};var getBugsnagErrorEvent=function getBugsnagErrorEvent(exception,errorState,state,groupingHash){var context=state.context,lifecycle=state.lifecycle,session=state.session,source=state.source,reporting=state.reporting,autoTrack=state.autoTrack;var app=context.app,locale=context.locale,userAgent=context.userAgent,timezone=context.timezone,screen=context.screen,library=context.library;return {payloadVersion:'5',notifier:{name:NOTIFIER_NAME,version:app.value.version,url:SDK_GITHUB_URL},events:[{exceptions:[clone(exception)],severity:errorState.severity,unhandled:errorState.unhandled,severityReason:errorState.severityReason,app:{version:app.value.version,releaseStage:getReleaseStage(),type:app.value.installType},device:getDeviceDetails(locale,userAgent),request:{url:getURLWithoutQueryString(),clientIp:'[NOT COLLECTED]'},breadcrumbs:clone(reporting.breadcrumbs.value),context:exception.message,groupingHash:groupingHash,metaData:_objectSpread2({app:{snippetVersion:library.value.snippetVersion},device:_objectSpread2(_objectSpread2({},screen.value),{},{timezone:timezone.value})},getAppStateForMetadata(state)),user:getUserDetails(source,session,lifecycle,autoTrack)}]};};/**
1131
+ * A function to check if adblockers are active. The promise's resolve function
1132
+ * is invoked with true if adblockers are not detected and false otherwise.
1133
+ * @param {ApplicationState} state The application state
1134
+ * @param {IHttpClient} httpClient The HTTP client instance
1135
+ * @param {Function} resolve The promise's resolve function
1136
+ */var checkIfAdBlockersAreActive=function checkIfAdBlockersAreActive(state,httpClient,resolve){// Initiate ad blocker detection if not done previously and not already in progress.
1137
+ if(isUndefined(state.capabilities.isAdBlocked.value)){if(state.capabilities.isAdBlockerDetectionInProgress.value===false){detectAdBlockers(httpClient);}// Wait for the detection to complete.
1138
+ var detectionDisposer=m(function(){if(isDefined(state.capabilities.isAdBlocked.value)){// If ad blocker is not detected, notify.
1139
+ resolve(state.capabilities.isAdBlocked.value===false);// Cleanup the effect.
1140
+ detectionDisposer();}});}else {// If ad blocker is not detected, notify.
1141
+ resolve(state.capabilities.isAdBlocked.value===false);}};/**
1142
+ * A function to determine whether the error should be promoted to notify or not.
1143
+ * For plugin and integration errors from RS CDN, if it is due to CSP blocked URLs or AdBlockers,
1144
+ * it will not be promoted to notify.
1145
+ * If it is due to other reasons, it will be promoted to notify.
1146
+ * @param {Error} exception The error object
1147
+ * @param {ApplicationState} state The application state
1148
+ * @param {IHttpClient} httpClient The HTTP client instance
1149
+ * @returns A promise that resolves to a boolean indicating whether the error should be promoted to notify or not
1150
+ */var checkIfAllowedToBeNotified=function checkIfAllowedToBeNotified(exception,state,httpClient){var errMsg=exception.message;return new Promise(function(resolve){// Filter out script load failures that are not from the RS CDN.
1151
+ if(SCRIPT_LOAD_FAILURE_MESSAGES.some(function(regex){return regex.test(errMsg);})){var _exec;var extractedURL=(_exec=/https?:\/\/[^\s"'(),;<>[\]{}]+/.exec(errMsg))===null||_exec===void 0?void 0:_exec[0];if(isString(extractedURL)){if(extractedURL.startsWith(SDK_CDN_BASE_URL)){// Filter out errors that are from CSP blocked URLs.
1152
+ if(state.capabilities.cspBlockedURLs.value.includes(extractedURL)){resolve(false);}else {// Filter out errors if adblockers are detected.
1153
+ checkIfAdBlockersAreActive(state,httpClient,resolve);}}else {// Filter out errors that are not from the RS CDN.
1154
+ resolve(false);}}else {// Allow the error to be notified if no URL could be extracted from the error message
1155
+ resolve(true);}}else {resolve(!ERROR_MESSAGES_TO_BE_FILTERED.some(function(e){return e.test(errMsg);}));}});};/**
1156
+ * A function to get the directory name from a file path.
1157
+ * @param {string} filePath The file path
1158
+ * @returns The directory name or undefined if the file path is invalid
1159
+ */var getDirectoryName=function getDirectoryName(filePath){if(!filePath){return undefined;}var paths=filePath.split('/');return paths.at(-2);};/**
1160
+ * A function to get the top stack path from the exception.
1161
+ * @param {Exception} exception The exception object
1162
+ * @returns The top stack path or undefined if the exception is invalid
1163
+ */var getTopStackPath=function getTopStackPath(exception){var _exception$stacktrace;var errorOrigin=(_exception$stacktrace=exception.stacktrace[0])===null||_exception$stacktrace===void 0?void 0:_exception$stacktrace.file;if(!errorOrigin||typeof errorOrigin!=='string'){return undefined;}return errorOrigin;};/**
1164
+ * A function to determine if the error is from Rudder SDK
1165
+ * @param {Error} exception
1166
+ * @returns
1167
+ */var isSDKError=function isSDKError(exception){var errorOrigin=getTopStackPath(exception);if(!errorOrigin){return false;}var srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);var parentFolderName=getDirectoryName(errorOrigin);return parentFolderName===CDN_INT_DIR||SDK_FILE_NAME_PREFIXES().some(function(prefix){return srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js');});};var getErrorCategory=function getErrorCategory(exception,category){if(category){return category;}var errorOrigin=getTopStackPath(exception);var directoryName=getDirectoryName(errorOrigin);if(directoryName===CDN_INT_DIR){return INTEGRATIONS_ERROR_CATEGORY;}return DEFAULT_ERROR_CATEGORY;};var getErrorDeliveryPayload=function getErrorDeliveryPayload(payload,state,category){var data={version:METRICS_PAYLOAD_VERSION,message_id:generateUUID(),source:{name:SOURCE_NAME,sdk_version:state.context.app.value.version,write_key:state.lifecycle.writeKey.value,install_type:state.context.app.value.installType,category:category},errors:payload};return stringifyWithoutCircular(data);};/**
1168
+ * A function to get the grouping hash value to be used for the error event.
1169
+ * If the grouping hash is an error instance, the normalized error message is used as the grouping hash.
1170
+ * If the grouping hash is an empty string or not specified, the default grouping hash is used.
1171
+ * If the grouping hash is a string, it is used as is.
1172
+ * @param curErrGroupingHash The grouping hash value part of the error event
1173
+ * @param defaultGroupingHash The default grouping hash value. It is the error message.
1174
+ * @param logger The logger instance
1175
+ * @returns The final grouping hash value to be used for the error event
1176
+ */var getErrorGroupingHash=function getErrorGroupingHash(curErrGroupingHash,defaultGroupingHash,logger){var normalizedGroupingHash;if(!isDefined(curErrGroupingHash)){normalizedGroupingHash=defaultGroupingHash;}else if(isString(curErrGroupingHash)){normalizedGroupingHash=curErrGroupingHash;}else {var normalizedErrorInstance=normalizeError(curErrGroupingHash,logger);if(isDefined(normalizedErrorInstance)){normalizedGroupingHash=normalizedErrorInstance.message;}else {normalizedGroupingHash=defaultGroupingHash;}}return normalizedGroupingHash;};
1177
+
1178
+ /**
1179
+ * A service to handle errors
1180
+ */var ErrorHandler=/*#__PURE__*/function(){// If no logger is passed errors will be thrown as unhandled error
1181
+ function ErrorHandler(httpClient,logger){_classCallCheck(this,ErrorHandler);_defineProperty(this,"initialized",false);this.httpClient=httpClient;this.logger=logger;}/**
1182
+ * Initializes the error handler by attaching global error listeners.
1183
+ * This method should be called once after construction.
1184
+ */return _createClass(ErrorHandler,[{key:"init",value:function init(){if(this.initialized){return;}this.attachErrorListeners();this.initialized=true;}/**
1185
+ * Attach error listeners to the global window object
1186
+ */},{key:"attachErrorListeners",value:function attachErrorListeners(){var _this=this;globalThis.addEventListener('error',function(event){_this.onError({error:event,context:ERROR_HANDLER,errorType:ErrorType.UNHANDLEDEXCEPTION});});globalThis.addEventListener('unhandledrejection',function(event){_this.onError({error:event,context:ERROR_HANDLER,errorType:ErrorType.UNHANDLEDREJECTION});});// Listen to CSP violations and add the blocked URL to the state
1187
+ // if those URLs are from RS CDN.
1188
+ document.addEventListener('securitypolicyviolation',function(event){var blockedURL=isString(event.blockedURI)?event.blockedURI:'';if(event.disposition==='enforce'&&blockedURL.startsWith(SDK_CDN_BASE_URL)&&!state.capabilities.cspBlockedURLs.value.includes(blockedURL)){state.capabilities.cspBlockedURLs.value=[].concat(_toConsumableArray(state.capabilities.cspBlockedURLs.value),[blockedURL]);}});}/**
1189
+ * Handle errors
1190
+ * @param errorInfo - The error information
1191
+ * @param errorInfo.error - The error to handle
1192
+ * @param errorInfo.context - The context of where the error occurred
1193
+ * @param errorInfo.customMessage - The custom message of the error
1194
+ * @param errorInfo.errorType - The type of the error (handled or unhandled)
1195
+ * @param errorInfo.groupingHash - The grouping hash of the error
1196
+ * @param errorInfo.category - The category of the error (sdk or integrations)
1197
+ */},{key:"onError",value:(function(){var _onError=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(errorInfo){var _errorInfo$errorType,error,context,customMessage,groupingHash,category,errorType,errInstance,normalizedError,customMsgVal,errorMsgPrefix,bsException,stacktrace,isSdkDispatched,isAllowed,errorState,normalizedGroupingHash,bugsnagPayload,errorCategory,_t;return _regenerator().w(function(_context){while(1)switch(_context.p=_context.n){case 0:_context.p=0;error=errorInfo.error,context=errorInfo.context,customMessage=errorInfo.customMessage,groupingHash=errorInfo.groupingHash,category=errorInfo.category;errorType=(_errorInfo$errorType=errorInfo.errorType)!==null&&_errorInfo$errorType!==void 0?_errorInfo$errorType:ErrorType.HANDLEDEXCEPTION;errInstance=getErrInstance(error,errorType);normalizedError=normalizeError(errInstance,this.logger);if(!isUndefined(normalizedError)){_context.n=1;break;}return _context.a(2);case 1:customMsgVal=customMessage?"".concat(customMessage," - "):'';errorMsgPrefix="".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(customMsgVal);bsException=createBugsnagException(normalizedError,errorMsgPrefix);stacktrace=getStacktrace(normalizedError);isSdkDispatched=stacktrace.includes(MANUAL_ERROR_IDENTIFIER);// Filter errors that are not originated in the SDK.
1198
+ // In case of NPM installations, the unhandled errors from the SDK cannot be identified
1199
+ // and will NOT be reported unless they occur in plugins or integrations.
1200
+ if(!(!isSdkDispatched&&!isSDKError(bsException)&&errorType!==ErrorType.HANDLEDEXCEPTION)){_context.n=2;break;}return _context.a(2);case 2:if(!state.reporting.isErrorReportingEnabled.value){_context.n=4;break;}_context.n=3;return checkIfAllowedToBeNotified(bsException,state,this.httpClient);case 3:isAllowed=_context.v;if(isAllowed){errorState={severity:'error',unhandled:errorType!==ErrorType.HANDLEDEXCEPTION,severityReason:{type:errorType}};// This will allow custom grouping of errors.
1201
+ // In case of NPM installations, the default grouping by surrounding code
1202
+ // does not make sense as each user application is different and will create a lot of noise in the alerts.
1203
+ // References:
1204
+ // https://docs.bugsnag.com/platforms/javascript/customizing-error-reports/#groupinghash
1205
+ // https://docs.bugsnag.com/product/error-grouping/#user_defined
1206
+ normalizedGroupingHash=getErrorGroupingHash(groupingHash,bsException.message,this.logger);// Get the final payload to be sent to the metrics service
1207
+ bugsnagPayload=getBugsnagErrorEvent(bsException,errorState,state,normalizedGroupingHash);errorCategory=getErrorCategory(bsException,category);// send it to metrics service
1208
+ this.httpClient.getAsyncData({url:state.metrics.metricsServiceUrl.value,options:{method:'POST',data:getErrorDeliveryPayload(bugsnagPayload,state,errorCategory),sendRawData:true},isRawResponse:true});}case 4:// Log handled errors and errors dispatched by the SDK
1209
+ if(errorType===ErrorType.HANDLEDEXCEPTION||isSdkDispatched){this.logger.error(bsException.message);}_context.n=6;break;case 5:_context.p=5;_t=_context.v;// If an error occurs while handling an error, log it
1210
+ this.logger.error(HANDLE_ERROR_FAILURE(ERROR_HANDLER),_t);case 6:return _context.a(2);}},_callee,this,[[0,5]]);}));function onError(_x){return _onError.apply(this,arguments);}return onError;}()/**
1211
+ * Add breadcrumbs to add insight of a user's journey before an error
1212
+ * occurred and send to external error monitoring service via a plugin
1213
+ *
1214
+ * @param {string} breadcrumb breadcrumbs message
1215
+ */)},{key:"leaveBreadcrumb",value:function leaveBreadcrumb(breadcrumb){try{state.reporting.breadcrumbs.value=[].concat(_toConsumableArray(state.reporting.breadcrumbs.value),[createNewBreadcrumb(breadcrumb)]);}catch(err){this.onError({error:err,context:ERROR_HANDLER,customMessage:BREADCRUMB_ERROR,groupingHash:BREADCRUMB_ERROR});}}}]);}();// Note: Remember to call defaultErrorHandler.init() before using it
1216
+ var defaultErrorHandler=new ErrorHandler(defaultHttpClient,defaultLogger);
1217
+
1218
+ // to next or return the value if it is the last one instead of an array per
1219
+ // plugin that is the normal invoke
1220
+ // TODO: add invoke method for extension point that we know only one plugin can be used. add invokeMultiple and invokeSingle methods
1221
+ var PluginEngine=/*#__PURE__*/function(){function PluginEngine(logger){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,PluginEngine);_defineProperty(this,"plugins",[]);_defineProperty(this,"byName",{});_defineProperty(this,"cache",{});_defineProperty(this,"config",{throws:true});this.config=_objectSpread2({throws:true},options);this.logger=logger;}return _createClass(PluginEngine,[{key:"register",value:function register(plugin,state){if(!plugin.name){var errorMessage=PLUGIN_NAME_MISSING_ERROR(PLUGIN_ENGINE);if(this.config.throws){throw new Error(errorMessage);}else {this.logger.error(errorMessage,plugin);return;}}if(this.byName[plugin.name]){var _errorMessage=PLUGIN_ALREADY_EXISTS_ERROR(PLUGIN_ENGINE,plugin.name);if(this.config.throws){throw new Error(_errorMessage);}else {this.logger.error(_errorMessage);return;}}this.cache={};this.plugins=this.plugins.slice();var pos=this.plugins.length;this.plugins.forEach(function(pluginItem,index){var _pluginItem$deps;if((_pluginItem$deps=pluginItem.deps)!==null&&_pluginItem$deps!==void 0&&_pluginItem$deps.includes(plugin.name)){pos=Math.min(pos,index);}});this.plugins.splice(pos,0,plugin);this.byName[plugin.name]=plugin;if(isFunction(plugin.initialize)){plugin.initialize(state);}}},{key:"unregister",value:function unregister(name){var plugin=this.byName[name];if(!plugin){var errorMessage=PLUGIN_NOT_FOUND_ERROR(PLUGIN_ENGINE,name);if(this.config.throws){throw new Error(errorMessage);}else {this.logger.error(errorMessage);return;}}var index=this.plugins.indexOf(plugin);if(index===-1){var _errorMessage2=PLUGIN_ENGINE_BUG_ERROR(PLUGIN_ENGINE,name);if(this.config.throws){throw new Error(_errorMessage2);}else {this.logger.error(_errorMessage2);return;}}this.cache={};delete this.byName[name];this.plugins=this.plugins.slice();this.plugins.splice(index,1);}},{key:"getPlugin",value:function getPlugin(name){return this.byName[name];}},{key:"getPlugins",value:function getPlugins(extPoint){var _this=this;var lifeCycleName=extPoint!==null&&extPoint!==void 0?extPoint:'.';if(!this.cache[lifeCycleName]){this.cache[lifeCycleName]=this.plugins.filter(function(plugin){var _plugin$deps;if((_plugin$deps=plugin.deps)!==null&&_plugin$deps!==void 0&&_plugin$deps.some(function(dependency){return !_this.byName[dependency];})){// If deps not exist, then not load it.
1222
+ var notExistDeps=plugin.deps.filter(function(dependency){return !_this.byName[dependency];});_this.logger.error(PLUGIN_DEPS_ERROR(PLUGIN_ENGINE,plugin.name,notExistDeps));return false;}return lifeCycleName==='.'?true:hasValueByPath(plugin,lifeCycleName);});}return this.cache[lifeCycleName];}// This method allows to process this.plugins so that it could
1223
+ // do some unified pre-process before application starts.
1224
+ },{key:"processRawPlugins",value:function processRawPlugins(callback){callback(this.plugins);this.cache={};}},{key:"invoke",value:function invoke(extPoint){var _this$config$throws,_this2=this;var allowMultiple=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;for(var _len=arguments.length,args=new Array(_len>2?_len-2:0),_key=2;_key<_len;_key++){args[_key-2]=arguments[_key];}var extensionPointName=extPoint;if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_MISSING_ERROR);}var noCall=extensionPointName.startsWith('!');var throws=(_this$config$throws=this.config.throws)!==null&&_this$config$throws!==void 0?_this$config$throws:extensionPointName.endsWith('!');// eslint-disable-next-line unicorn/better-regex
1225
+ extensionPointName=extensionPointName.replace(/(^!|!$)/g,'');if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_INVALID_ERROR);}var extensionPointNameParts=extensionPointName.split('.');extensionPointNameParts.pop();var pluginMethodPath=extensionPointNameParts.join('.');var pluginsToInvoke=allowMultiple?this.getPlugins(extensionPointName):[this.getPlugins(extensionPointName)[0]];return pluginsToInvoke.map(function(plugin){var method=getValueByPath(plugin,extensionPointName);if(!isFunction(method)||noCall){return method;}try{return method.apply(getValueByPath(plugin,pluginMethodPath),args);}catch(err){// When a plugin failed, doesn't break the app
1226
+ if(throws){throw err;}else {_this2.logger.error(PLUGIN_INVOCATION_ERROR(PLUGIN_ENGINE,extensionPointName,plugin.name),err);}}return null;});}},{key:"invokeSingle",value:function invokeSingle(extPoint){for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];}return this.invoke.apply(this,[extPoint,false].concat(args))[0];}},{key:"invokeMultiple",value:function invokeMultiple(extPoint){for(var _len3=arguments.length,args=new Array(_len3>1?_len3-1:0),_key3=1;_key3<_len3;_key3++){args[_key3-1]=arguments[_key3];}return this.invoke.apply(this,[extPoint,true].concat(args));}}]);}();var defaultPluginEngine=new PluginEngine(defaultLogger,{throws:true});
1227
+
1228
+ /**
1229
+ * A function to filter and return non cloud mode destinations
1230
+ * A destination is considered non cloud mode if it is not a cloud mode destination or if it is a hybrid mode destination
1231
+ * @param destination
1232
+ *
1233
+ * @returns boolean
1234
+ */var isNonCloudDestination=function isNonCloudDestination(destination){return Boolean(destination.config.connectionMode!=='cloud'||destination.config.useNativeSDKToSend===true||// this is the older flag for hybrid mode destinations
1235
+ destination.config.useNativeSDK===true);};var isHybridModeDestination=function isHybridModeDestination(destination){return Boolean(destination.config.connectionMode==='hybrid'||destination.config.useNativeSDKToSend===true);};/**
1236
+ * A function to filter and return non cloud mode destinations
1237
+ * @param destinations
1238
+ *
1239
+ * @returns destinations
1240
+ */var getNonCloudDestinations=function getNonCloudDestinations(destinations){return destinations.filter(isNonCloudDestination);};/**
1241
+ * A function to get the user friendly id for a destination
1242
+ * Replaces all spaces with hyphens and appends the id to the display name
1243
+ * @param displayName The display name of the destination
1244
+ * @param id The id of the destination
1245
+ *
1246
+ * @returns the user friendly id
1247
+ */var getDestinationUserFriendlyId=function getDestinationUserFriendlyId(displayName,id){return "".concat(displayName.replaceAll(' ','-'),"___").concat(id);};
1248
+
1249
+ /**
1250
+ * List of plugin names that are loaded as dynamic imports in modern builds
1251
+ */var pluginNamesList=['BeaconQueue','CustomConsentManager','DeviceModeDestinations','DeviceModeTransformation','ExternalAnonymousId','GoogleLinker','IubendaConsentManager','KetchConsentManager','NativeDestinationQueue','OneTrustConsentManager','StorageEncryption','StorageEncryptionLegacy','StorageMigrator','XhrQueue'];var deprecatedPluginsList=['Bugsnag','ErrorReporting'];
1252
+
1253
+ var CUSTOM_CONSENT_MANAGER_PLUGIN='CustomConsentManagerPlugin';
1254
+
1255
+ var DESTINATION_CONSENT_STATUS_ERROR$3="Failed to determine the consent status for the destination. Please check the destination configuration and try again.";
1256
+
1257
+ var pluginName$6='CustomConsentManager';var CustomConsentManager=function CustomConsentManager(){return {name:pluginName$6,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$6]);},consentManager:{init:function init(state,logger){// Nothing to initialize
1258
+ },updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){// Nothing to update. Already provided by the user
1259
+ },isDestinationConsented:function isDestinationConsented(state,destConfig,errorHandler,logger){if(!state.consents.initialized.value){return true;}var allowedConsentIds=state.consents.data.value.allowedConsentIds;try{var _cmpConfig$resolution;var consentManagement=destConfig.consentManagement;// If the destination does not have consent management config, events should be sent.
1260
+ if(!consentManagement){return true;}// Get the corresponding consents for the destination
1261
+ var cmpConfig=consentManagement.find(function(c){return c.provider===state.consents.provider.value;});// If there are no consents configured for the destination for the current provider, events should be sent.
1262
+ if(!(cmpConfig!==null&&cmpConfig!==void 0&&cmpConfig.consents)){return true;}var configuredConsents=cmpConfig.consents.map(function(c){return c.consent.trim();}).filter(function(n){return n;});var resolutionStrategy=(_cmpConfig$resolution=cmpConfig.resolutionStrategy)!==null&&_cmpConfig$resolution!==void 0?_cmpConfig$resolution:state.consents.resolutionStrategy.value;// match the configured consents with user provided consents as per
1263
+ // the configured resolution strategy
1264
+ var matchPredicate=function matchPredicate(consent){return allowedConsentIds.includes(consent);};switch(resolutionStrategy){case 'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case 'and':default:return configuredConsents.every(matchPredicate);}}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError({error:err,context:CUSTOM_CONSENT_MANAGER_PLUGIN,customMessage:DESTINATION_CONSENT_STATUS_ERROR$3});return true;}}}};};
1265
+
1266
+ var externallyLoadedSessionStorageKeys={segment:'ajs_anonymous_id'};
1267
+
1268
+ var COOKIE_STORAGE='cookieStorage';var LOCAL_STORAGE='localStorage';var SESSION_STORAGE='sessionStorage';var MEMORY_STORAGE='memoryStorage';var NO_STORAGE='none';var STORAGE_TEST_COOKIE='test_rudder_cookie';var STORAGE_TEST_LOCAL_STORAGE='test_rudder_ls';var STORAGE_TEST_SESSION_STORAGE='test_rudder_ss';
1269
+
1270
+ var removeDuplicateSlashes=function removeDuplicateSlashes(str){return str.replace(/\/{2,}/g,'/');};/**
1271
+ * Checks if provided url is valid or not
1272
+ * @param url
1273
+ * @returns true if `url` is valid and false otherwise
1274
+ */var isValidURL=function isValidURL(url){if(!isString(url)){return false;}try{// If URL is supported by the browser, we can use it to validate the URL
1275
+ // Otherwise, we can at least check if the URL matches the pattern
1276
+ if(isFunction(globalThis.URL)){// eslint-disable-next-line no-new
1277
+ new URL(url);}return URL_PATTERN.test(url);}catch(e){return false;}};
1278
+
1279
+ /**
1280
+ * This function is used to determine if the input status code is retryable.
1281
+ * @param status - The status code.
1282
+ * @returns True if the status code is not 4xx (except 429), false otherwise.
1283
+ */var isErrRetryable=function isErrRetryable(status){if(status===429){return true;}return !(status>=400&&status<500);};
1284
+
1285
+ /**
1286
+ * Encode.
1287
+ */var encode=function encode(value,logger){try{return encodeURIComponent(value);}catch(err){logger===null||logger===void 0||logger.error(COOKIE_DATA_ENCODING_ERROR,err);return undefined;}};/**
1288
+ * Decode
1289
+ */var decode=function decode(value){try{return decodeURIComponent(value);}catch(err){// Do nothing as non-RS SDK cookies may not be URI encoded
1290
+ return undefined;}};/**
1291
+ * Parse cookie `str`
1292
+ */var parse=function parse(str){var obj={};var pairs=str.split(/\s*;\s*/);var pair;if(!pairs[0]){return obj;}// TODO: Decode only the cookies that are needed by the SDK
1293
+ pairs.forEach(function(pairItem){pair=pairItem.split('=');var keyName=pair[0]?decode(pair[0]):undefined;if(keyName){obj[keyName]=pair[1]?decode(pair[1]):undefined;}});return obj;};/**
1294
+ * Set cookie `name` to `value`
1295
+ */var set=function set(name,value,optionsConfig,logger){var options=_objectSpread2({},optionsConfig||{});var cookieString="".concat(encode(name,logger),"=").concat(encode(value,logger));if(isNull(value)){options.maxage=-1;}if(options.maxage){options.expires=new Date(+new Date()+options.maxage);}if(options.path){cookieString+="; path=".concat(options.path);}if(options.domain){cookieString+="; domain=".concat(options.domain);}if(options.expires){cookieString+="; expires=".concat(options.expires.toUTCString());}if(options.samesite){cookieString+="; samesite=".concat(options.samesite);}if(options.secure){cookieString+="; secure";}globalThis.document.cookie=cookieString;};/**
1296
+ * Return all cookies
1297
+ */var all=function all(){var cookieStringValue=globalThis.document.cookie;return parse(cookieStringValue);};/**
1298
+ * Get cookie `name`
1299
+ */var get=function get(name){return all()[name];};/**
1300
+ * Set or get cookie `name` with `value` and `options` object
1301
+ */// eslint-disable-next-line func-names
1302
+ var cookie=function cookie(name,value,options,logger){switch(arguments.length){case 4:case 3:case 2:return set(name,value,options,logger);case 1:if(name){return get(name);}return all();default:return all();}};
1303
+
1304
+ var userIdKey='rl_user_id';var userTraitsKey='rl_trait';var anonymousUserIdKey='rl_anonymous_id';var groupIdKey='rl_group_id';var groupTraitsKey='rl_group_trait';var pageInitialReferrerKey='rl_page_init_referrer';var pageInitialReferringDomainKey='rl_page_init_referring_domain';var sessionInfoKey='rl_session';var authTokenKey='rl_auth_token';var COOKIE_KEYS={userId:userIdKey,userTraits:userTraitsKey,anonymousId:anonymousUserIdKey,groupId:groupIdKey,groupTraits:groupTraitsKey,initialReferrer:pageInitialReferrerKey,initialReferringDomain:pageInitialReferringDomainKey,sessionInfo:sessionInfoKey,authToken:authTokenKey};var ENCRYPTION_PREFIX_V3='RS_ENC_v3_';
1305
+
1306
+ var encryptBrowser=function encryptBrowser(value){return "".concat(ENCRYPTION_PREFIX_V3).concat(toBase64(value));};var decryptBrowser=function decryptBrowser(value){if(value!==null&&value!==void 0&&value.startsWith(ENCRYPTION_PREFIX_V3)){return fromBase64(value.substring(ENCRYPTION_PREFIX_V3.length));}return value;};
1307
+
1308
+ var EVENT_PAYLOAD_SIZE_BYTES_LIMIT=32*1024;// 32 KB
1309
+ var RETRY_REASON_CLIENT_NETWORK='client-network';var RETRY_REASON_CLIENT_TIMEOUT='client-timeout';var DEFAULT_RETRY_REASON=RETRY_REASON_CLIENT_NETWORK;
1310
+
1311
+ var isStorageQuotaExceeded=function isStorageQuotaExceeded(e){var matchingNames=['QuotaExceededError','NS_ERROR_DOM_QUOTA_REACHED'];// Everything except Firefox, Firefox
1312
+ var matchingCodes=[22,1014];if(e instanceof DOMException){return matchingNames.includes(e.name)||matchingCodes.includes(e.code);}return false;};// TODO: also check for SecurityErrors
1313
+ // https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage#exceptions
1314
+ var isStorageAvailable=function isStorageAvailable(){var type=arguments.length>0&&arguments[0]!==undefined?arguments[0]:LOCAL_STORAGE;var storageInstance=arguments.length>1?arguments[1]:undefined;var logger=arguments.length>2?arguments[2]:undefined;var storage;var testData;var msgPrefix=STORAGE_UNAVAILABILITY_ERROR_PREFIX(CAPABILITIES_MANAGER,type);var reason='unavailable';var isAccessible=true;var errObj;try{switch(type){case MEMORY_STORAGE:return true;case COOKIE_STORAGE:storage=storageInstance;testData=STORAGE_TEST_COOKIE;break;case LOCAL_STORAGE:storage=storageInstance!==null&&storageInstance!==void 0?storageInstance:globalThis.localStorage;testData=STORAGE_TEST_LOCAL_STORAGE;// was STORAGE_TEST_LOCAL_STORAGE in ours and generateUUID() in segment retry one
1315
+ break;case SESSION_STORAGE:storage=storageInstance!==null&&storageInstance!==void 0?storageInstance:globalThis.sessionStorage;testData=STORAGE_TEST_SESSION_STORAGE;break;default:return false;}if(storage){storage.setItem(testData,'true');if(storage.getItem(testData)){storage.removeItem(testData);return true;}}isAccessible=false;}catch(err){isAccessible=false;errObj=err;if(isStorageQuotaExceeded(err)){reason='full';}}if(!isAccessible){logger===null||logger===void 0||logger.warn("".concat(msgPrefix).concat(reason,"."),errObj);}// if we've have reached here, it means the storage is not available
1316
+ return false;};
1317
+
1318
+ var EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING=function EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING(context,payloadSize,sizeLimit){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The size of the event payload (").concat(payloadSize," bytes) exceeds the maximum limit of ").concat(sizeLimit," bytes. Events with large payloads may be dropped in the future. Please review your instrumentation to ensure that event payloads are within the size limit.");};var EVENT_PAYLOAD_SIZE_VALIDATION_WARNING=function EVENT_PAYLOAD_SIZE_VALIDATION_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to validate event payload size. Please make sure that the event payload is within the size limit and is a valid JSON object.");};var QUEUE_UTILITIES='QueueUtilities';/**
1319
+ * Utility to get the stringified event payload
1320
+ * @param event RudderEvent object
1321
+ * @param logger Logger instance
1322
+ * @returns stringified event payload. Empty string if error occurs.
1323
+ */var getDeliveryPayload=function getDeliveryPayload(event,logger){return stringifyWithoutCircular(event,true,undefined,logger);};/**
1324
+ * Utility to validate final payload size before sending to server
1325
+ * @param event RudderEvent object
1326
+ * @param logger Logger instance
1327
+ */var validateEventPayloadSize=function validateEventPayloadSize(event,logger){var payloadStr=getDeliveryPayload(event,logger);if(payloadStr){var payloadSize=payloadStr.length;if(payloadSize>EVENT_PAYLOAD_SIZE_BYTES_LIMIT){logger===null||logger===void 0||logger.warn(EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING(QUEUE_UTILITIES,payloadSize,EVENT_PAYLOAD_SIZE_BYTES_LIMIT));}}else {logger===null||logger===void 0||logger.warn(EVENT_PAYLOAD_SIZE_VALIDATION_WARNING(QUEUE_UTILITIES));}};/**
1328
+ * Mutates the event and return final event for delivery
1329
+ * Updates certain parameters like sentAt timestamp, integrations config etc.
1330
+ * @param event RudderEvent object
1331
+ * @returns Final event ready to be delivered
1332
+ */var getFinalEventForDeliveryMutator=function getFinalEventForDeliveryMutator(event,currentTime){var finalEvent=clone(event);// Update sentAt timestamp to the latest timestamp
1333
+ finalEvent.sentAt=currentTime;return finalEvent;};/**
1334
+ * Utility to get the storage type for events persistence
1335
+ * If local storage is available, use it; else, fall back to session storage; else, fall back to memory storage.
1336
+ * On some browsers, persistence storage is blocked for the JS SDK that is loaded from RS domains.
1337
+ * In such cases, we need to verify all the storage types and use the first one that is available.
1338
+ * @param logger Logger instance for logging storage availability warnings
1339
+ * @returns StorageType
1340
+ */var getStorageTypeForEventsPersistence=function getStorageTypeForEventsPersistence(logger){if(isStorageAvailable(LOCAL_STORAGE,undefined,logger)){return LOCAL_STORAGE;}if(isStorageAvailable(SESSION_STORAGE,undefined,logger)){return SESSION_STORAGE;}// Don't use cookie storage as it can potentially cause overhead with the network requests.
1341
+ // Note that events will not be persisted across page reloads in this case.
1342
+ return MEMORY_STORAGE;};
1343
+
1344
+ var QueueStatuses={IN_PROGRESS:'inProgress',QUEUE:'queue',RECLAIM_START:'reclaimStart',RECLAIM_END:'reclaimEnd',ACK:'ack',BATCH_QUEUE:'batchQueue'};
1345
+
1346
+ var getSegmentAnonymousId=function getSegmentAnonymousId(getStorageEngine){var anonymousId;/**
1347
+ * First check the local storage for anonymousId
1348
+ * Ref: https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/#identify
1349
+ */var lsEngine=getStorageEngine(LOCAL_STORAGE);if(lsEngine!==null&&lsEngine!==void 0&&lsEngine.isEnabled){anonymousId=lsEngine.getItem(externallyLoadedSessionStorageKeys.segment);}// If anonymousId is not present in local storage and find it in cookies
1350
+ var csEngine=getStorageEngine(COOKIE_STORAGE);if(!anonymousId&&csEngine!==null&&csEngine!==void 0&&csEngine.isEnabled){anonymousId=csEngine.getItem(externallyLoadedSessionStorageKeys.segment);}return anonymousId;};
1351
+
1352
+ var pluginName$5='ExternalAnonymousId';var ExternalAnonymousId=function ExternalAnonymousId(){return {name:pluginName$5,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$5]);},storage:{getAnonymousId:function getAnonymousId(getStorageEngine,options){var _options$autoCapture;var anonymousId;if(options!==null&&options!==void 0&&(_options$autoCapture=options.autoCapture)!==null&&_options$autoCapture!==void 0&&_options$autoCapture.enabled&&options.autoCapture.source){var source=options.autoCapture.source.toLowerCase();if(!Object.keys(externallyLoadedSessionStorageKeys).includes(source)){return anonymousId;}// eslint-disable-next-line sonarjs/no-small-switch
1353
+ switch(source){case 'segment':anonymousId=getSegmentAnonymousId(getStorageEngine);break;}}return anonymousId;}}};};
1354
+
1355
+ var IUBENDA_CONSENT_COOKIE_READ_ERROR=function IUBENDA_CONSENT_COOKIE_READ_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to read the consent cookie.");};var IUBENDA_CONSENT_COOKIE_PARSE_ERROR=function IUBENDA_CONSENT_COOKIE_PARSE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to parse the consent cookie.");};var DESTINATION_CONSENT_STATUS_ERROR$2="Failed to determine the consent status for the destination. Please check the destination configuration and try again.";
1356
+
1357
+ var IUBENDA_CONSENT_MANAGER_PLUGIN='IubendaConsentManagerPlugin';var IUBENDA_CONSENT_COOKIE_NAME_PATTERN=/^_iub_cs-\d+$/;
1358
+
1359
+ var getIubendaCookieName=function getIubendaCookieName(logger){try{// Retrieve cookies as a string and split them into an array
1360
+ var cookies=document.cookie.split('; ');// Find the cookie that matches the iubenda cookie pattern
1361
+ var matchedCookie=cookies.find(function(cookie){var _cookie$split=cookie.split('='),_cookie$split2=_slicedToArray(_cookie$split,1),name=_cookie$split2[0];return IUBENDA_CONSENT_COOKIE_NAME_PATTERN.test((name||'').trim());});if(!matchedCookie){throw new Error('Iubenda Cookie not found with the specified pattern.');}// Extract and return the cookie name
1362
+ var _matchedCookie$split=matchedCookie.split('='),_matchedCookie$split2=_slicedToArray(_matchedCookie$split,1),name=_matchedCookie$split2[0];return name||'';}catch(err){logger===null||logger===void 0||logger.error(IUBENDA_CONSENT_COOKIE_READ_ERROR(IUBENDA_CONSENT_MANAGER_PLUGIN),err);return '';}};/**
1363
+ * Gets the consent data from the Iubenda's consent cookie
1364
+ * @param storeManager Store manager instance
1365
+ * @param logger Logger instance
1366
+ * @returns Consent data from the consent cookie
1367
+ */var getIubendaConsentData=function getIubendaConsentData(storeManager,logger){var rawConsentCookieData=null;try{var dataStore=storeManager===null||storeManager===void 0?void 0:storeManager.setStore({id:IUBENDA_CONSENT_MANAGER_PLUGIN,name:IUBENDA_CONSENT_MANAGER_PLUGIN,type:COOKIE_STORAGE,errorHandler:storeManager===null||storeManager===void 0?void 0:storeManager.errorHandler,logger:storeManager===null||storeManager===void 0?void 0:storeManager.logger});rawConsentCookieData=dataStore===null||dataStore===void 0?void 0:dataStore.engine.getItem(getIubendaCookieName(logger));}catch(err){logger===null||logger===void 0||logger.error(IUBENDA_CONSENT_COOKIE_READ_ERROR(IUBENDA_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(isNullOrUndefined(rawConsentCookieData)){return undefined;}// Decode and parse the cookie data to JSON
1368
+ var consentCookieData;try{consentCookieData=JSON.parse(decodeURIComponent(rawConsentCookieData));}catch(err){logger===null||logger===void 0||logger.error(IUBENDA_CONSENT_COOKIE_PARSE_ERROR(IUBENDA_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(!consentCookieData){return undefined;}// Convert the cookie data to consent data
1369
+ var consentPurposes=consentCookieData.purposes;return consentPurposes;};/**
1370
+ * Gets the consent data in the format expected by the application state
1371
+ * @param iubendaConsentData Consent data derived from the consent cookie
1372
+ * @returns Consent data
1373
+ */var getConsentData$1=function getConsentData(iubendaConsentData){var allowedConsentIds=[];var deniedConsentIds=[];if(iubendaConsentData){Object.entries(iubendaConsentData).forEach(function(e){var purposeId=e[0];var isConsented=e[1];if(isConsented){allowedConsentIds.push(purposeId);}else {deniedConsentIds.push(purposeId);}});}return {allowedConsentIds:allowedConsentIds,deniedConsentIds:deniedConsentIds};};var updateConsentStateFromData$1=function updateConsentStateFromData(state,iubendaConsentData){var consentData=getConsentData$1(iubendaConsentData);state.consents.initialized.value=isDefined(iubendaConsentData);state.consents.data.value=consentData;};
1374
+
1375
+ var pluginName$4='IubendaConsentManager';var IubendaConsentManager=function IubendaConsentManager(){return {name:pluginName$4,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$4]);},consentManager:{init:function init(state,logger){// getIubendaUserConsentedPurposes returns current iubenda opted-in purposes
1376
+ // This will be helpful for debugging
1377
+ globalThis.getIubendaUserConsentedPurposes=function(){var _state$consents$data$;return (_state$consents$data$=state.consents.data.value.allowedConsentIds)===null||_state$consents$data$===void 0?void 0:_state$consents$data$.slice();};// getIubendaUserDeniedPurposes returns current Iubenda opted-out purposes
1378
+ // This will be helpful for debugging
1379
+ globalThis.getIubendaUserDeniedPurposes=function(){var _state$consents$data$2;return (_state$consents$data$2=state.consents.data.value.deniedConsentIds)===null||_state$consents$data$2===void 0?void 0:_state$consents$data$2.slice();};// updateIubendaConsent callback function to update current consent purpose state
1380
+ globalThis.updateIubendaConsent=function(iubendaConsentData){updateConsentStateFromData$1(state,iubendaConsentData);};},updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){// retrieve consent data and update the state
1381
+ var iubendaConsentData;// From window
1382
+ if(!isUndefined(globalThis._iub.cs.consent.purposes)){iubendaConsentData=globalThis._iub.cs.consent.purposes;// From cookie
1383
+ }else {iubendaConsentData=getIubendaConsentData(storeManager,logger);}updateConsentStateFromData$1(state,iubendaConsentData);},isDestinationConsented:function isDestinationConsented(state,destConfig,errorHandler,logger){if(!state.consents.initialized.value){return true;}var allowedConsentIds=state.consents.data.value.allowedConsentIds;var matchPredicate=function matchPredicate(consent){return allowedConsentIds.includes(consent);};try{var consentManagement=destConfig.consentManagement;// If the destination does not have consent management config, events should be sent.
1384
+ if(consentManagement){var _cmpConfig$resolution;// Get the corresponding consents for the destination
1385
+ var cmpConfig=consentManagement.find(function(c){return c.provider===state.consents.provider.value;});// If there are no consents configured for the destination for the current provider, events should be sent.
1386
+ if(!(cmpConfig!==null&&cmpConfig!==void 0&&cmpConfig.consents)){return true;}var configuredConsents=cmpConfig.consents.map(function(c){return c.consent.trim();}).filter(function(n){return n;});var resolutionStrategy=(_cmpConfig$resolution=cmpConfig.resolutionStrategy)!==null&&_cmpConfig$resolution!==void 0?_cmpConfig$resolution:state.consents.resolutionStrategy.value;// match the configured consents with user provided consents as per
1387
+ // the configured resolution strategy
1388
+ switch(resolutionStrategy){case 'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case 'and':default:return configuredConsents.every(matchPredicate);}}return true;}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError({error:err,context:IUBENDA_CONSENT_MANAGER_PLUGIN,customMessage:DESTINATION_CONSENT_STATUS_ERROR$2});return true;}}}};};
1389
+
1390
+ var KETCH_CONSENT_COOKIE_READ_ERROR=function KETCH_CONSENT_COOKIE_READ_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to read the consent cookie.");};var KETCH_CONSENT_COOKIE_PARSE_ERROR=function KETCH_CONSENT_COOKIE_PARSE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to parse the consent cookie.");};var DESTINATION_CONSENT_STATUS_ERROR$1="Failed to determine the consent status for the destination. Please check the destination configuration and try again.";
1391
+
1392
+ var KETCH_CONSENT_MANAGER_PLUGIN='KetchConsentManagerPlugin';var KETCH_CONSENT_COOKIE_NAME_V1='_ketch_consent_v1_';
1393
+
1394
+ /**
1395
+ * Gets the consent data from the Ketch's consent cookie
1396
+ * @param storeManager Store manager instance
1397
+ * @param logger Logger instance
1398
+ * @returns Consent data from the consent cookie
1399
+ */var getKetchConsentData=function getKetchConsentData(storeManager,logger){var rawConsentCookieData=null;try{// Create a data store instance to read the consent cookie
1400
+ var dataStore=storeManager===null||storeManager===void 0?void 0:storeManager.setStore({id:KETCH_CONSENT_MANAGER_PLUGIN,name:KETCH_CONSENT_MANAGER_PLUGIN,type:COOKIE_STORAGE,errorHandler:storeManager===null||storeManager===void 0?void 0:storeManager.errorHandler,logger:storeManager===null||storeManager===void 0?void 0:storeManager.logger});rawConsentCookieData=dataStore===null||dataStore===void 0?void 0:dataStore.engine.getItem(KETCH_CONSENT_COOKIE_NAME_V1);}catch(err){logger===null||logger===void 0||logger.error(KETCH_CONSENT_COOKIE_READ_ERROR(KETCH_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(isNullOrUndefined(rawConsentCookieData)){return undefined;}// Decode and parse the cookie data to JSON
1401
+ var consentCookieData;try{consentCookieData=JSON.parse(fromBase64(rawConsentCookieData));}catch(err){logger===null||logger===void 0||logger.error(KETCH_CONSENT_COOKIE_PARSE_ERROR(KETCH_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(!consentCookieData){return undefined;}// Convert the cookie data to consent data
1402
+ var consentPurposes={};Object.entries(consentCookieData).forEach(function(pEntry){var purposeCode=pEntry[0];var purposeValue=pEntry[1];consentPurposes[purposeCode]=(purposeValue===null||purposeValue===void 0?void 0:purposeValue.status)==='granted';});return consentPurposes;};/**
1403
+ * Gets the consent data in the format expected by the application state
1404
+ * @param ketchConsentData Consent data derived from the consent cookie
1405
+ * @returns Consent data
1406
+ */var getConsentData=function getConsentData(ketchConsentData){var allowedConsentIds=[];var deniedConsentIds=[];if(ketchConsentData){Object.entries(ketchConsentData).forEach(function(e){var purposeCode=e[0];var isConsented=e[1];if(isConsented){allowedConsentIds.push(purposeCode);}else {deniedConsentIds.push(purposeCode);}});}return {allowedConsentIds:allowedConsentIds,deniedConsentIds:deniedConsentIds};};var updateConsentStateFromData=function updateConsentStateFromData(state,ketchConsentData){var consentData=getConsentData(ketchConsentData);state.consents.initialized.value=isDefined(ketchConsentData);state.consents.data.value=consentData;};
1407
+
1408
+ var pluginName$3='KetchConsentManager';var KetchConsentManager=function KetchConsentManager(){return {name:pluginName$3,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$3]);},consentManager:{init:function init(state,logger){// getKetchUserConsentedPurposes returns current ketch opted-in purposes
1409
+ // This will be helpful for debugging
1410
+ globalThis.getKetchUserConsentedPurposes=function(){var _state$consents$data$;return (_state$consents$data$=state.consents.data.value.allowedConsentIds)===null||_state$consents$data$===void 0?void 0:_state$consents$data$.slice();};// getKetchUserDeniedPurposes returns current ketch opted-out purposes
1411
+ // This will be helpful for debugging
1412
+ globalThis.getKetchUserDeniedPurposes=function(){var _state$consents$data$2;return (_state$consents$data$2=state.consents.data.value.deniedConsentIds)===null||_state$consents$data$2===void 0?void 0:_state$consents$data$2.slice();};// updateKetchConsent callback function to update current consent purpose state
1413
+ // this will be called from ketch rudderstack plugin
1414
+ globalThis.updateKetchConsent=function(ketchConsentData){updateConsentStateFromData(state,ketchConsentData);};},updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){// retrieve consent data and update the state
1415
+ var ketchConsentData;if(!isUndefined(globalThis.ketchConsent)){ketchConsentData=globalThis.ketchConsent;}else {ketchConsentData=getKetchConsentData(storeManager,logger);}updateConsentStateFromData(state,ketchConsentData);},isDestinationConsented:function isDestinationConsented(state,destConfig,errorHandler,logger){if(!state.consents.initialized.value){return true;}var allowedConsentIds=state.consents.data.value.allowedConsentIds;try{var ketchConsentPurposes=destConfig.ketchConsentPurposes,consentManagement=destConfig.consentManagement;var matchPredicate=function matchPredicate(consent){return allowedConsentIds.includes(consent);};// Generic consent management
1416
+ if(consentManagement){var _consentManagement$fi;// Get the corresponding consents for the destination
1417
+ var cmpConsents=(_consentManagement$fi=consentManagement.find(function(c){return c.provider===state.consents.provider.value;}))===null||_consentManagement$fi===void 0?void 0:_consentManagement$fi.consents;// If there are no consents configured for the destination for the current provider, events should be sent.
1418
+ if(!cmpConsents){return true;}var configuredConsents=cmpConsents.map(function(c){return c.consent.trim();}).filter(function(n){return n;});// match the configured consents with user provided consents as per
1419
+ // the configured resolution strategy
1420
+ switch(state.consents.resolutionStrategy.value){case 'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case 'and':default:return configuredConsents.every(matchPredicate);}// Legacy cookie consent management
1421
+ // TODO: To be removed once the source config API is updated to support generic consent management
1422
+ }else if(ketchConsentPurposes){var _configuredConsents=ketchConsentPurposes.map(function(p){return p.purpose.trim();}).filter(function(n){return n;});// Check if any of the destination's mapped ketch purposes are consented by the user in the browser.
1423
+ return _configuredConsents.some(matchPredicate)||_configuredConsents.length===0;}// If there are no consents configured for the destination for the current provider, events should be sent.
1424
+ return true;}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError({error:err,context:KETCH_CONSENT_MANAGER_PLUGIN,customMessage:DESTINATION_CONSENT_STATUS_ERROR$1});return true;}}}};};
1425
+
1426
+ var ONETRUST_ACCESS_ERROR=function ONETRUST_ACCESS_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to access OneTrust SDK resources. Please ensure that the OneTrust SDK is loaded successfully before RudderStack SDK.");};var DESTINATION_CONSENT_STATUS_ERROR="Failed to determine the consent status for the destination. Please check the destination configuration and try again.";
1427
+
1428
+ var ONETRUST_CONSENT_MANAGER_PLUGIN='OneTrustConsentManagerPlugin';
1429
+
1430
+ var pluginName$2='OneTrustConsentManager';var OneTrustConsentManager=function OneTrustConsentManager(){return {name:pluginName$2,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$2]);},consentManager:{init:function init(state,logger){// Nothing to initialize
1431
+ },updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){if(!globalThis.OneTrust||!globalThis.OnetrustActiveGroups){logger===null||logger===void 0||logger.error(ONETRUST_ACCESS_ERROR(ONETRUST_CONSENT_MANAGER_PLUGIN));state.consents.initialized.value=false;return;}// Get the groups (cookie categorization), user has created in OneTrust account.
1432
+ var oneTrustAllGroupsInfo=globalThis.OneTrust.GetDomainData().Groups;// OneTrustConsentManager SDK populates a data layer object OnetrustActiveGroups with
1433
+ // the cookie categories Ids that the user has consented to.
1434
+ // Eg: ',C0001,C0003,'
1435
+ // We split it and save it as an array.
1436
+ var allowedConsentIds=globalThis.OnetrustActiveGroups.split(',').filter(function(n){return n;});var deniedConsentIds=[];oneTrustAllGroupsInfo.forEach(function(_ref){var CustomGroupId=_ref.CustomGroupId;if(!allowedConsentIds.includes(CustomGroupId)){deniedConsentIds.push(CustomGroupId);}});state.consents.initialized.value=true;state.consents.data.value={allowedConsentIds:allowedConsentIds,deniedConsentIds:deniedConsentIds};},isDestinationConsented:function isDestinationConsented(state,destConfig,errorHandler,logger){if(!state.consents.initialized.value){return true;}var allowedConsentIds=state.consents.data.value.allowedConsentIds;try{// mapping of the destination with the consent group name
1437
+ var oneTrustCookieCategories=destConfig.oneTrustCookieCategories,consentManagement=destConfig.consentManagement;var matchPredicate=function matchPredicate(consent){return allowedConsentIds.includes(consent);};// Generic consent management
1438
+ if(consentManagement){var _consentManagement$fi;// Get the corresponding consents for the destination
1439
+ var cmpConsents=(_consentManagement$fi=consentManagement.find(function(c){return c.provider===state.consents.provider.value;}))===null||_consentManagement$fi===void 0?void 0:_consentManagement$fi.consents;// If there are no consents configured for the destination for the current provider, events should be sent.
1440
+ if(!cmpConsents){return true;}var configuredConsents=cmpConsents.map(function(c){return c.consent.trim();}).filter(function(n){return n;});// match the configured consents with user provided consents as per
1441
+ // the configured resolution strategy
1442
+ switch(state.consents.resolutionStrategy.value){case 'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case 'and':default:return configuredConsents.every(matchPredicate);}// Legacy cookie consent management
1443
+ // TODO: To be removed once the source config API is updated to support generic consent management
1444
+ }else if(oneTrustCookieCategories){// Change the structure of oneTrustConsentGroup as an array and filter values if empty string
1445
+ // Eg:
1446
+ // ["Performance Cookies", "Functional Cookies"]
1447
+ var _configuredConsents=oneTrustCookieCategories.map(function(c){return c.oneTrustCookieCategory.trim();}).filter(function(n){return n;});// Check if all the destination's mapped cookie categories are consented by the user in the browser.
1448
+ return _configuredConsents.every(matchPredicate);}// If there are no consents configured for the destination for the current provider, events should be sent.
1449
+ return true;}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError({error:err,context:ONETRUST_CONSENT_MANAGER_PLUGIN,customMessage:DESTINATION_CONSENT_STATUS_ERROR});return true;}}}};};
1450
+
1451
+ var pluginName$1='StorageEncryption';var StorageEncryption=function StorageEncryption(){return {name:pluginName$1,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$1]);},storage:{encrypt:function encrypt(value){return encryptBrowser(value);},decrypt:function decrypt(value){return decryptBrowser(value);}}};};
1452
+
1453
+ var DEFAULT_RETRY_QUEUE_OPTIONS={maxRetryDelay:360000,minRetryDelay:1000,backoffFactor:2,maxAttempts:10,maxItems:100};var REQUEST_TIMEOUT_MS=30*1000;// 30 seconds
1454
+ var DATA_PLANE_API_VERSION='v1';var QUEUE_NAME='rudder';var XHR_QUEUE_PLUGIN='XhrQueuePlugin';
1455
+
1456
+ var EVENT_DELIVERY_FAILURE_ERROR_PREFIX=function EVENT_DELIVERY_FAILURE_ERROR_PREFIX(context,originalErrorMsg){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to deliver event(s). Cause: ").concat(originalErrorMsg,".");};
1457
+
1458
+ var getBatchDeliveryPayload=function getBatchDeliveryPayload(events,currentTime,logger){var batchPayload={batch:events,sentAt:currentTime};return stringifyWithoutCircular(batchPayload,true,undefined,logger);};var getNormalizedQueueOptions=function getNormalizedQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_RETRY_QUEUE_OPTIONS,queueOpts);};var getDeliveryUrl=function getDeliveryUrl(dataplaneUrl,endpoint){var dpUrl=new URL(dataplaneUrl);return new URL(removeDuplicateSlashes([dpUrl.pathname,'/',DATA_PLANE_API_VERSION,'/',endpoint].join('')),dpUrl).href;};var getBatchDeliveryUrl=function getBatchDeliveryUrl(dataplaneUrl){return getDeliveryUrl(dataplaneUrl,'batch');};var logMessageOnFailure=function logMessageOnFailure(details,isRetryable,qItemProcessInfo,logger){var _details$error$messag,_details$error;if(!logger){return;}var logMsg=EVENT_DELIVERY_FAILURE_ERROR_PREFIX(XHR_QUEUE_PLUGIN,(_details$error$messag=details===null||details===void 0||(_details$error=details.error)===null||_details$error===void 0?void 0:_details$error.message)!==null&&_details$error$messag!==void 0?_details$error$messag:'Unknown');var dropMsg="The event(s) will be dropped.";if(isRetryable){if(qItemProcessInfo.willBeRetried){logMsg="".concat(logMsg," The event(s) will be retried.");if(qItemProcessInfo.retryAttemptNumber>0){logMsg="".concat(logMsg," Retry attempt ").concat(qItemProcessInfo.retryAttemptNumber," of ").concat(qItemProcessInfo.maxRetryAttempts,".");}// Use warning for retryable failures that will be retried
1459
+ logger.warn(logMsg);}else {logger.error("".concat(logMsg," Retries exhausted (").concat(qItemProcessInfo.maxRetryAttempts,"). ").concat(dropMsg));}}else {// Use error for non-retryable failures
1460
+ logger.error("".concat(logMsg," ").concat(dropMsg));}};var getRequestInfo=function getRequestInfo(itemData,state,qItemProcessInfo,logger){var data;var headers;var url;var currentTime=getCurrentTimeFormatted();if(Array.isArray(itemData)){var finalEvents=itemData.map(function(queueItemData){return getFinalEventForDeliveryMutator(queueItemData.event,currentTime);});data=getBatchDeliveryPayload(finalEvents,currentTime,logger);headers=itemData[0]?clone(itemData[0].headers):{};url=getBatchDeliveryUrl(state.lifecycle.activeDataplaneUrl.value);}else {var eventUrl=itemData.url,event=itemData.event,eventHeaders=itemData.headers;var finalEvent=getFinalEventForDeliveryMutator(event,currentTime);data=getDeliveryPayload(finalEvent,logger);headers=clone(eventHeaders);url=eventUrl;}// Add current timestamp as sentAt header
1461
+ // The same value is added in the event payload as well
1462
+ headers.SentAt=currentTime;// Add a header to indicate if the item has been reclaimed from
1463
+ // local storage
1464
+ if(qItemProcessInfo.reclaimed){headers['Rsa-Recovered']='true';}// Add retry headers if the item is being retried for delivery
1465
+ if(qItemProcessInfo.retryAttemptNumber>0){// The number of times this item has been attempted to retry
1466
+ headers['Rsa-Retry-Attempt']=qItemProcessInfo.retryAttemptNumber.toString();// The number of milliseconds since the last attempt
1467
+ headers['Rsa-Since-Last-Attempt']=qItemProcessInfo.timeSinceLastAttempt.toString();// The number of milliseconds since the first attempt
1468
+ headers['Rsa-Since-First-Attempt']=qItemProcessInfo.timeSinceFirstAttempt.toString();// The reason for the retry
1469
+ headers['Rsa-Retry-Reason']=qItemProcessInfo.retryReason;}return {data:data,headers:headers,url:url};};
1470
+
1471
+ var ScheduleModes=/*#__PURE__*/function(ScheduleModes){ScheduleModes[ScheduleModes["ASAP"]=1]="ASAP";ScheduleModes[ScheduleModes["RESCHEDULE"]=2]="RESCHEDULE";ScheduleModes[ScheduleModes["ABANDON"]=3]="ABANDON";return ScheduleModes;}({});var DEFAULT_CLOCK_LATE_FACTOR=2;var DEFAULT_CLOCK={setTimeout:function setTimeout(fn,ms){return globalThis.setTimeout(fn,ms);},clearTimeout:function clearTimeout(id){return globalThis.clearTimeout(id);},Date:globalThis.Date,clockLateFactor:DEFAULT_CLOCK_LATE_FACTOR};var Schedule=/*#__PURE__*/function(){function Schedule(){_classCallCheck(this,Schedule);this.tasks={};this.nextId=1;this.clock=DEFAULT_CLOCK;}return _createClass(Schedule,[{key:"now",value:function now(){return +new this.clock.Date();}},{key:"run",value:function run(task,timeout,mode){if(this.nextId===Number.MAX_SAFE_INTEGER){this.nextId=1;}var id=(this.nextId++).toString();this.tasks[id]=this.clock.setTimeout(this.handle(id,task,timeout,mode||ScheduleModes.ASAP),timeout);return id;}},{key:"handle",value:function handle(id,callback,timeout,mode){var _this=this;var start=this.now();return function(){delete _this.tasks[id];var elapsedTimeoutTime=start+timeout*(_this.clock.clockLateFactor||DEFAULT_CLOCK_LATE_FACTOR);var currentTime=_this.now();var notCompletedOrTimedOut=mode>=ScheduleModes.RESCHEDULE&&elapsedTimeoutTime<currentTime;if(notCompletedOrTimedOut){if(mode===ScheduleModes.RESCHEDULE){_this.run(callback,timeout,mode);}return undefined;}return callback();};}},{key:"cancel",value:function cancel(id){if(this.tasks[id]){this.clock.clearTimeout(this.tasks[id]);delete this.tasks[id];}}},{key:"cancelAll",value:function cancelAll(){Object.values(this.tasks).forEach(this.clock.clearTimeout);this.tasks={};}}]);}();
1472
+
1473
+ var RETRY_QUEUE_PROCESS_ERROR=function RETRY_QUEUE_PROCESS_ERROR(context,errMsg){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"An unknown error occurred while processing the queue item. ").concat(errMsg);};var RETRY_QUEUE_ENTRY_REMOVE_ERROR=function RETRY_QUEUE_ENTRY_REMOVE_ERROR(context,entry,attempt){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to remove local storage entry \"").concat(entry,"\" (attempt: ").concat(attempt,".");};
1474
+
1475
+ var DEFAULT_MIN_RETRY_DELAY_MS=1000;var DEFAULT_MAX_RETRY_DELAY_MS=30000;var DEFAULT_BACKOFF_FACTOR=2;var DEFAULT_BACKOFF_JITTER=0;var DEFAULT_MAX_RETRY_ATTEMPTS=Infinity;var DEFAULT_MAX_ITEMS=Infinity;var DEFAULT_ACK_TIMER_MS=1000;var DEFAULT_RECLAIM_TIMER_MS=3000;var DEFAULT_RECLAIM_TIMEOUT_MS=10000;var DEFAULT_RECLAIM_WAIT_MS=500;var MIN_TIMER_SCALE_FACTOR=1;var MAX_TIMER_SCALE_FACTOR=10;var DEFAULT_MAX_BATCH_SIZE_BYTES=512*1024;// 512 KB; this is also the max size of a batch
1476
+ var DEFAULT_MAX_BATCH_ITEMS=100;var DEFAULT_BATCH_FLUSH_INTERVAL_MS=60*1000;// 1 minutes
1477
+ var BATCH_QUEUE_ITEM_TYPE='Batch';var SINGLE_QUEUE_ITEM_TYPE='Single';
1478
+
1479
+ var sortByTime=function sortByTime(a,b){return a.time-b.time;};var RETRY_QUEUE='RetryQueue';var RetryQueue=/*#__PURE__*/function(){/**
1480
+ * Constructs a RetryQueue backed by localStorage
1481
+ *
1482
+ * @param {String} name The name of the queue. Will be used to find abandoned queues and retry their items
1483
+ * @param {QueueOpts} [options] Optional argument to override `maxItems`, `maxAttempts`, `minRetryDelay, `maxRetryDelay`, `backoffFactor` and `backoffJitter`.
1484
+ * @param {QueueProcessCallback} queueProcessCb The function to call in order to process an item added to the queue
1485
+ * @param {IStoreManager} storeManager The store manager instance to use
1486
+ * @param {StorageType} [storageType] The storage type to use. Defaults to LOCAL_STORAGE
1487
+ * @param {ILogger} [logger] The logger to use
1488
+ * @param {QueueBatchItemsSizeCalculatorCallback} [queueBatchItemsSizeCalculatorCb] The callback to use to calculate the size of items in the batch queue
1489
+ */function RetryQueue(name,options,queueProcessCb,storeManager){var _options$timerScaleFa;var storageType=arguments.length>4&&arguments[4]!==undefined?arguments[4]:LOCAL_STORAGE;var logger=arguments.length>5?arguments[5]:undefined;var queueBatchItemsSizeCalculatorCb=arguments.length>6?arguments[6]:undefined;_classCallCheck(this,RetryQueue);this.storeManager=storeManager;this.logger=logger;this.name=name;this.id=generateUUID();this.processQueueCb=queueProcessCb;this.batchSizeCalcCb=queueBatchItemsSizeCalculatorCb;this.maxItems=options.maxItems||DEFAULT_MAX_ITEMS;this.maxAttempts=options.maxAttempts||DEFAULT_MAX_RETRY_ATTEMPTS;this.batch={enabled:false};this.configureBatchMode(options);this.backoff={minRetryDelay:options.minRetryDelay||DEFAULT_MIN_RETRY_DELAY_MS,maxRetryDelay:options.maxRetryDelay||DEFAULT_MAX_RETRY_DELAY_MS,factor:options.backoffFactor||DEFAULT_BACKOFF_FACTOR,jitter:options.backoffJitter||DEFAULT_BACKOFF_JITTER};// Limit the timer scale factor to the minimum value
1490
+ var timerScaleFactor=Math.max((_options$timerScaleFa=options.timerScaleFactor)!==null&&_options$timerScaleFa!==void 0?_options$timerScaleFa:MIN_TIMER_SCALE_FACTOR,MIN_TIMER_SCALE_FACTOR);// Limit the timer scale factor to the maximum value
1491
+ timerScaleFactor=Math.min(timerScaleFactor,MAX_TIMER_SCALE_FACTOR);// painstakingly tuned. that's why they're not "easily" configurable
1492
+ this.timeouts={ackTimer:Math.round(timerScaleFactor*DEFAULT_ACK_TIMER_MS),reclaimTimer:Math.round(timerScaleFactor*DEFAULT_RECLAIM_TIMER_MS),reclaimTimeout:Math.round(timerScaleFactor*DEFAULT_RECLAIM_TIMEOUT_MS),reclaimWait:Math.round(timerScaleFactor*DEFAULT_RECLAIM_WAIT_MS)};this.schedule=new Schedule();this.processId='0';// Set up our empty queues
1493
+ this.store=this.storeManager.setStore({id:this.id,name:this.name,validKeys:QueueStatuses,type:storageType,errorHandler:this.storeManager.errorHandler,logger:this.storeManager.logger});this.setDefaultQueueEntries();// bind recurring tasks for ease of use
1494
+ this.ack=this.ack.bind(this);this.checkReclaim=this.checkReclaim.bind(this);this.processHead=this.processHead.bind(this);this.flushBatch=this.flushBatch.bind(this);this.isPageAccessible=true;// Flush the queue on page leave
1495
+ this.flushBatchOnPageLeave();this.scheduleTimeoutActive=false;}return _createClass(RetryQueue,[{key:"setDefaultQueueEntries",value:function setDefaultQueueEntries(){this.setStorageEntry(QueueStatuses.IN_PROGRESS,{});this.setStorageEntry(QueueStatuses.QUEUE,[]);this.setStorageEntry(QueueStatuses.BATCH_QUEUE,[]);}},{key:"configureBatchMode",value:function configureBatchMode(options){this.batchingInProgress=false;if(!isObjectLiteralAndNotNull(options.batch)){return;}var batchOptions=options.batch;this.batch.enabled=batchOptions.enabled===true;if(this.batch.enabled){var _batchOptions$maxSize,_batchOptions$maxItem,_batchOptions$flushIn;// Set upper cap on the batch payload size
1496
+ this.batch.maxSize=Math.min((_batchOptions$maxSize=batchOptions.maxSize)!==null&&_batchOptions$maxSize!==void 0?_batchOptions$maxSize:DEFAULT_MAX_BATCH_SIZE_BYTES,DEFAULT_MAX_BATCH_SIZE_BYTES);this.batch.maxItems=(_batchOptions$maxItem=batchOptions.maxItems)!==null&&_batchOptions$maxItem!==void 0?_batchOptions$maxItem:DEFAULT_MAX_BATCH_ITEMS;this.batch.flushInterval=(_batchOptions$flushIn=batchOptions.flushInterval)!==null&&_batchOptions$flushIn!==void 0?_batchOptions$flushIn:DEFAULT_BATCH_FLUSH_INTERVAL_MS;}}},{key:"flushBatchOnPageLeave",value:function flushBatchOnPageLeave(){if(this.batch.enabled){onPageLeave(this.flushBatch);}}},{key:"getStorageEntry",value:function getStorageEntry(name){return this.store.get(name);}// TODO: fix the type of different queues to be the same if possible
1497
+ },{key:"setStorageEntry",value:function setStorageEntry(name,value){if(isNullOrUndefined(value)){this.store.remove(name);}else {this.store.set(name,value);}}/**
1498
+ * Stops processing the queue
1499
+ */},{key:"stop",value:function stop(){this.schedule.cancelAll();this.scheduleTimeoutActive=false;}/**
1500
+ * Starts processing the queue
1501
+ */},{key:"start",value:function start(){if(this.scheduleTimeoutActive){this.stop();}this.scheduleTimeoutActive=true;this.scheduleFlushBatch();this.ack();this.checkReclaim();this.processHead();}/**
1502
+ * Configures the timeout handler for flushing the batch queue
1503
+ */},{key:"scheduleFlushBatch",value:function scheduleFlushBatch(){var _this$batch;if(this.batch.enabled&&(_this$batch=this.batch)!==null&&_this$batch!==void 0&&_this$batch.flushInterval){if(this.flushBatchTaskId){this.schedule.cancel(this.flushBatchTaskId);}this.flushBatchTaskId=this.schedule.run(this.flushBatch,this.batch.flushInterval,ScheduleModes.ASAP);}}/**
1504
+ * Flushes the batch queue
1505
+ */},{key:"flushBatch",value:function flushBatch(){var isAccessible=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;if(!this.batchingInProgress){var _ref;this.isPageAccessible=isAccessible;this.batchingInProgress=true;var batchQueue=(_ref=this.getStorageEntry(QueueStatuses.BATCH_QUEUE))!==null&&_ref!==void 0?_ref:[];if(batchQueue.length>0){batchQueue=batchQueue.slice(-batchQueue.length);var batchEntry=this.genQueueItem(batchQueue.map(function(queueItem){return queueItem.item;}),BATCH_QUEUE_ITEM_TYPE);this.setStorageEntry(QueueStatuses.BATCH_QUEUE,[]);this.pushToMainQueue(batchEntry);}this.batchingInProgress=false;// Re-schedule the flush task
1506
+ this.scheduleFlushBatch();}}/**
1507
+ * Decides whether to retry. Overridable.
1508
+ *
1509
+ * @param {Object} item The item being processed
1510
+ * @param {Number} attemptNumber The attemptNumber (1 for first retry)
1511
+ * @return {Boolean} Whether to requeue the message
1512
+ */},{key:"shouldRetry",value:function shouldRetry(item,attemptNumber){return attemptNumber<=this.maxAttempts;}/**
1513
+ * Calculates the delay (in ms) for a retry attempt
1514
+ *
1515
+ * @param {Number} attemptNumber The attemptNumber (1 for first retry)
1516
+ * @return {Number} The delay in milliseconds to wait before attempting a retry
1517
+ */},{key:"getDelay",value:function getDelay(attemptNumber){var ms=this.backoff.minRetryDelay*Math.pow(this.backoff.factor,attemptNumber);if(this.backoff.jitter){var rand=Math.random();var deviation=Math.floor(rand*this.backoff.jitter*ms);if(Math.floor(rand*10)<5){ms-=deviation;}else {ms+=deviation;}}return Number(Math.min(ms,this.backoff.maxRetryDelay).toPrecision(1));}},{key:"enqueue",value:function enqueue(entry){var curEntry;if(this.batch.enabled&&entry.type===SINGLE_QUEUE_ITEM_TYPE){curEntry=this.handleNewItemForBatch(entry);}else {curEntry=entry;}// when batching is enabled, `curEntry` could be `undefined` if the batch criteria is not met
1518
+ if(curEntry){this.pushToMainQueue(curEntry);}}/**
1519
+ * Handles a new item added to the retry queue when batching is enabled
1520
+ * @param entry New item added to the retry queue
1521
+ * @returns Undefined or batch entry object
1522
+ */},{key:"handleNewItemForBatch",value:function handleNewItemForBatch(entry){var _ref2;var curEntry;var batchQueue=(_ref2=this.getStorageEntry(QueueStatuses.BATCH_QUEUE))!==null&&_ref2!==void 0?_ref2:[];if(!this.batchingInProgress){this.batchingInProgress=true;batchQueue=batchQueue.slice(-batchQueue.length);batchQueue.push(entry);var batchDispatchInfo=this.getBatchDispatchInfo(batchQueue);// if batch criteria is met, queue the batch events to the main queue and clear batch queue
1523
+ if(batchDispatchInfo.criteriaMet||batchDispatchInfo.criteriaExceeded){var batchEntries;if(batchDispatchInfo.criteriaExceeded){batchEntries=batchQueue.slice(0,batchQueue.length-1);batchQueue=[entry];}else {batchEntries=batchQueue;batchQueue=[];}// Don't make any batch request if there are no items
1524
+ if(batchEntries.length>0){var isReclaimed=batchEntries.every(function(queueItem){return queueItem.reclaimed;});var batchItems=batchEntries.map(function(queueItem){return queueItem.item;});if(isReclaimed){curEntry=this.genQueueItem(batchItems,BATCH_QUEUE_ITEM_TYPE,true);}else {curEntry=this.genQueueItem(batchItems,BATCH_QUEUE_ITEM_TYPE);}}// re-attach the timeout handler
1525
+ this.scheduleFlushBatch();}this.batchingInProgress=false;}else {batchQueue.push(entry);}// update the batch queue
1526
+ this.setStorageEntry(QueueStatuses.BATCH_QUEUE,batchQueue);return curEntry;}},{key:"pushToMainQueue",value:function pushToMainQueue(curEntry){var _ref3;var queue=(_ref3=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_ref3!==void 0?_ref3:[];if(this.maxItems>1){queue=queue.slice(-(this.maxItems-1));}else {queue=[];}queue.push(curEntry);queue=queue.sort(sortByTime);this.setStorageEntry(QueueStatuses.QUEUE,queue);if(this.scheduleTimeoutActive){this.processHead();}}/**
1527
+ * Adds an item to the queue
1528
+ *
1529
+ * @param {Object} itemData The item to process
1530
+ */},{key:"addItem",value:function addItem(itemData){this.enqueue(this.genQueueItem(itemData));}/**
1531
+ * Generates a queue item
1532
+ * @param itemData Queue item data
1533
+ * @returns Queue item
1534
+ */},{key:"genQueueItem",value:function genQueueItem(itemData){var type=arguments.length>1&&arguments[1]!==undefined?arguments[1]:SINGLE_QUEUE_ITEM_TYPE;var reclaimed=arguments.length>2?arguments[2]:undefined;return _objectSpread2({item:itemData,attemptNumber:0,time:this.schedule.now(),id:generateUUID(),type:type},isDefined(reclaimed)?{reclaimed:reclaimed}:{});}/**
1535
+ * Adds an item to the retry queue
1536
+ *
1537
+ * @param {Object} qItem The item to process
1538
+ */},{key:"requeue",value:function requeue(qItem){var attemptNumber=qItem.attemptNumber,item=qItem.item,type=qItem.type,id=qItem.id,firstAttemptedAt=qItem.firstAttemptedAt,lastAttemptedAt=qItem.lastAttemptedAt,reclaimed=qItem.reclaimed,retryReason=qItem.retryReason;// Increment the attempt number as we're about to retry
1539
+ var attemptNumberToUse=attemptNumber+1;if(this.shouldRetry(item,attemptNumberToUse)){this.enqueue({item:item,attemptNumber:attemptNumberToUse,time:this.schedule.now()+this.getDelay(attemptNumberToUse),id:id!==null&&id!==void 0?id:generateUUID(),type:type,firstAttemptedAt:firstAttemptedAt,lastAttemptedAt:lastAttemptedAt,reclaimed:reclaimed,retryReason:retryReason});}}/**
1540
+ * Returns the information about whether the batch criteria is met or exceeded
1541
+ * @param batchItems Prospective batch items
1542
+ * @returns Batch dispatch info
1543
+ */},{key:"getBatchDispatchInfo",value:function getBatchDispatchInfo(batchItems){var _this$batch2,_this$batch3;var lengthCriteriaMet=false;var lengthCriteriaExceeded=false;var configuredBatchMaxItems=(_this$batch2=this.batch)===null||_this$batch2===void 0?void 0:_this$batch2.maxItems;if(isDefined(configuredBatchMaxItems)){lengthCriteriaMet=batchItems.length===configuredBatchMaxItems;lengthCriteriaExceeded=batchItems.length>configuredBatchMaxItems;}if(lengthCriteriaMet||lengthCriteriaExceeded){return {criteriaMet:lengthCriteriaMet,criteriaExceeded:lengthCriteriaExceeded};}var sizeCriteriaMet=false;var sizeCriteriaExceeded=false;var configuredBatchMaxSize=(_this$batch3=this.batch)===null||_this$batch3===void 0?void 0:_this$batch3.maxSize;if(isDefined(configuredBatchMaxSize)&&isDefined(this.batchSizeCalcCb)){var curBatchSize=this.batchSizeCalcCb(batchItems.map(function(queueItem){return queueItem.item;}));sizeCriteriaMet=curBatchSize===configuredBatchMaxSize;sizeCriteriaExceeded=curBatchSize>configuredBatchMaxSize;}return {criteriaMet:sizeCriteriaMet,criteriaExceeded:sizeCriteriaExceeded};}},{key:"processHead",value:function processHead(){var _ref4,_this=this,_ref6,_ref8;// cancel the scheduled task if it exists
1544
+ this.schedule.cancel(this.processId);// Pop the head off the queue
1545
+ var queue=(_ref4=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_ref4!==void 0?_ref4:[];var now=this.schedule.now();var toRun=[];// eslint-disable-next-line @typescript-eslint/no-unused-vars
1546
+ var processItemCallback=function processItemCallback(el,id){return function(err,res){var _ref5;var inProgress=(_ref5=_this.getStorageEntry(QueueStatuses.IN_PROGRESS))!==null&&_ref5!==void 0?_ref5:{};var inProgressItem=inProgress[id];var firstAttemptedAt=inProgressItem===null||inProgressItem===void 0?void 0:inProgressItem.firstAttemptedAt;var lastAttemptedAt=inProgressItem===null||inProgressItem===void 0?void 0:inProgressItem.lastAttemptedAt;delete inProgress[id];_this.setStorageEntry(QueueStatuses.IN_PROGRESS,inProgress);if(err){var _res$retryReason;_this.requeue(_objectSpread2(_objectSpread2({},el),{},{firstAttemptedAt:firstAttemptedAt,lastAttemptedAt:lastAttemptedAt,retryReason:(_res$retryReason=res===null||res===void 0?void 0:res.retryReason)!==null&&_res$retryReason!==void 0?_res$retryReason:DEFAULT_RETRY_REASON}));}};};var enqueueItem=function enqueueItem(el,id){toRun.push({id:id,item:el.item,done:processItemCallback(el,id),attemptNumber:el.attemptNumber});};var inProgress=(_ref6=this.getStorageEntry(QueueStatuses.IN_PROGRESS))!==null&&_ref6!==void 0?_ref6:{};var inProgressSize=Object.keys(inProgress).length;// eslint-disable-next-line no-plusplus
1547
+ while(queue.length>0&&queue[0].time<=now&&inProgressSize++<this.maxItems){var el=queue.shift();if(el){var id=generateUUID();// Save this to the in progress map
1548
+ inProgress[id]={item:el.item,attemptNumber:el.attemptNumber,time:this.schedule.now(),type:el.type,firstAttemptedAt:el.firstAttemptedAt,lastAttemptedAt:el.lastAttemptedAt,reclaimed:el.reclaimed};enqueueItem(el,id);}}this.setStorageEntry(QueueStatuses.QUEUE,queue);this.setStorageEntry(QueueStatuses.IN_PROGRESS,inProgress);toRun.forEach(function(el){// TODO: handle processQueueCb timeout
1549
+ try{var _ref7;var _now=_this.schedule.now();var _inProgress=(_ref7=_this.getStorageEntry(QueueStatuses.IN_PROGRESS))!==null&&_ref7!==void 0?_ref7:{};var inProgressItem=_inProgress[el.id];var firstAttemptedAt=_now;var lastAttemptedAt=_now;var reclaimed=false;var retryReason=DEFAULT_RETRY_REASON;if(inProgressItem){var _inProgressItem$retry,_inProgressItem$first,_inProgressItem$lastA,_inProgressItem$recla;retryReason=(_inProgressItem$retry=inProgressItem.retryReason)!==null&&_inProgressItem$retry!==void 0?_inProgressItem$retry:retryReason;firstAttemptedAt=(_inProgressItem$first=inProgressItem.firstAttemptedAt)!==null&&_inProgressItem$first!==void 0?_inProgressItem$first:firstAttemptedAt;lastAttemptedAt=(_inProgressItem$lastA=inProgressItem.lastAttemptedAt)!==null&&_inProgressItem$lastA!==void 0?_inProgressItem$lastA:lastAttemptedAt;// Indicates if the item has been reclaimed from local storage
1550
+ reclaimed=(_inProgressItem$recla=inProgressItem.reclaimed)!==null&&_inProgressItem$recla!==void 0?_inProgressItem$recla:reclaimed;// Update the first attempted at timestamp for the in progress item
1551
+ inProgressItem.firstAttemptedAt=firstAttemptedAt;// Update the last attempted at to current timestamp for the in progress item
1552
+ inProgressItem.lastAttemptedAt=_now;_inProgress[el.id]=inProgressItem;_this.setStorageEntry(QueueStatuses.IN_PROGRESS,_inProgress);}// A decimal integer representing the milliseconds since the first attempt
1553
+ var timeSinceFirstAttempt=_now-firstAttemptedAt;// A decimal integer representing the milliseconds since the last attempt
1554
+ var timeSinceLastAttempt=_now-lastAttemptedAt;var willBeRetried=_this.shouldRetry(el.item,el.attemptNumber+1);_this.processQueueCb(el.item,el.done,{retryAttemptNumber:el.attemptNumber,maxRetryAttempts:_this.maxAttempts,willBeRetried:willBeRetried,timeSinceFirstAttempt:timeSinceFirstAttempt,timeSinceLastAttempt:timeSinceLastAttempt,reclaimed:reclaimed,isPageAccessible:_this.isPageAccessible,retryReason:retryReason});}catch(err){var _this$logger;var errMsg='';if(el.attemptNumber<_this.maxAttempts){errMsg='The item will be requeued.';if(el.attemptNumber>0){errMsg="".concat(errMsg," Retry attempt ").concat(el.attemptNumber," of ").concat(_this.maxAttempts,".");}// requeue the item to be retried
1555
+ el.done(err);}else {errMsg="Retries exhausted (".concat(_this.maxAttempts,"). The item will be dropped.");// drop the event as we're unable to process it
1556
+ // after the max attempts are exhausted
1557
+ el.done();}(_this$logger=_this.logger)===null||_this$logger===void 0||_this$logger.error(RETRY_QUEUE_PROCESS_ERROR(RETRY_QUEUE,errMsg),err);}});// re-read the queue in case the process function finished immediately or added another item
1558
+ queue=(_ref8=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_ref8!==void 0?_ref8:[];this.schedule.cancel(this.processId);if(queue.length>0){var nextProcessExecutionTime=queue[0].time-now;this.processId=this.schedule.run(this.processHead,nextProcessExecutionTime,ScheduleModes.ASAP);}}// Ack continuously to prevent other tabs from claiming our queue
1559
+ },{key:"ack",value:function ack(){this.setStorageEntry(QueueStatuses.ACK,this.schedule.now());if(this.reclaimStartVal!=null){this.reclaimStartVal=null;this.setStorageEntry(QueueStatuses.RECLAIM_START,null);}if(this.reclaimEndVal!=null){this.reclaimEndVal=null;this.setStorageEntry(QueueStatuses.RECLAIM_END,null);}this.schedule.run(this.ack,this.timeouts.ackTimer,ScheduleModes.ASAP);}},{key:"reclaim",value:function reclaim(id){var _this$getStorageEntry,_other$get,_other$get2,_other$get3,_this2=this;var other=this.storeManager.setStore({id:id,name:this.name,validKeys:QueueStatuses,type:LOCAL_STORAGE,errorHandler:this.storeManager.errorHandler,logger:this.storeManager.logger});var our={queue:(_this$getStorageEntry=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_this$getStorageEntry!==void 0?_this$getStorageEntry:[]};var their={inProgress:(_other$get=other.get(QueueStatuses.IN_PROGRESS))!==null&&_other$get!==void 0?_other$get:{},batchQueue:(_other$get2=other.get(QueueStatuses.BATCH_QUEUE))!==null&&_other$get2!==void 0?_other$get2:[],queue:(_other$get3=other.get(QueueStatuses.QUEUE))!==null&&_other$get3!==void 0?_other$get3:[]};var trackMessageIds=[];var addConcatQueue=function addConcatQueue(queue,incrementAttemptNumberBy){var concatIterator=function concatIterator(el){var _el$id;var id=(_el$id=el.id)!==null&&_el$id!==void 0?_el$id:generateUUID();if(trackMessageIds.includes(id));else {var _el$type;// Hack to determine the item type by the contents of the entry
1560
+ // After some point, we can remove this hack as most of the stale data will have been processed
1561
+ // and the new entries will have the type field set
1562
+ var type=Array.isArray(el.item)?BATCH_QUEUE_ITEM_TYPE:SINGLE_QUEUE_ITEM_TYPE;our.queue.push({item:el.item,attemptNumber:el.attemptNumber+incrementAttemptNumberBy,time:_this2.schedule.now(),id:id,type:(_el$type=el.type)!==null&&_el$type!==void 0?_el$type:type,firstAttemptedAt:el.firstAttemptedAt,lastAttemptedAt:el.lastAttemptedAt,retryReason:el.retryReason,// Mark the item as reclaimed from local storage
1563
+ reclaimed:true});trackMessageIds.push(id);}};if(Array.isArray(queue)){queue.forEach(concatIterator);}else if(queue){Object.values(queue).forEach(concatIterator);}};// add their queue to ours, resetting run-time to immediate and copying the attempt#
1564
+ addConcatQueue(their.queue,0);// Process batch queue items
1565
+ if(this.batch.enabled){their.batchQueue.forEach(function(el){var _el$id2;var id=(_el$id2=el.id)!==null&&_el$id2!==void 0?_el$id2:generateUUID();if(trackMessageIds.includes(id));else {var _el$type2;_this2.enqueue(_objectSpread2(_objectSpread2({},el),{},{id:id,retryReason:el.retryReason,// Mark the item as reclaimed from local storage
1566
+ reclaimed:true,type:(_el$type2=el.type)!==null&&_el$type2!==void 0?_el$type2:SINGLE_QUEUE_ITEM_TYPE,time:_this2.schedule.now()}));trackMessageIds.push(id);}});}else {// if batching is not enabled in the current instance, add those items to the main queue directly
1567
+ addConcatQueue(their.batchQueue,0);}// if the queue is abandoned, all the in-progress are failed. retry them immediately and increment the attempt#
1568
+ addConcatQueue(their.inProgress,1);our.queue.sort(sortByTime);this.setStorageEntry(QueueStatuses.QUEUE,our.queue);// remove all keys one by on next tick to avoid NS_ERROR_STORAGE_BUSY error
1569
+ this.clearQueueEntries(other,1);// process the new items we claimed
1570
+ this.processHead();}},{key:"clearQueueEntries",value:function clearQueueEntries(other,localStorageBackoff){this.removeStorageEntry(other,0,localStorageBackoff);}},{key:"removeStorageEntry",value:function removeStorageEntry(store,entryIdx,backoff){var _this3=this;var attempt=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;var maxAttempts=2;var queueEntryKeys=Object.keys(QueueStatuses);var entry=QueueStatuses[queueEntryKeys[entryIdx]];globalThis.setTimeout(function(){try{store.remove(entry);// clear the next entry
1571
+ if(entryIdx+1<queueEntryKeys.length){_this3.removeStorageEntry(store,entryIdx+1,backoff);}}catch(err){var storageBusyErr='NS_ERROR_STORAGE_BUSY';var isLocalStorageBusy=err.name===storageBusyErr||err.code===storageBusyErr||err.code===0x80630001;if(isLocalStorageBusy&&attempt<maxAttempts){// Try clearing the same entry again with some extra delay
1572
+ _this3.removeStorageEntry(store,entryIdx,backoff+40,attempt+1);}else {var _this3$logger;(_this3$logger=_this3.logger)===null||_this3$logger===void 0||_this3$logger.error(RETRY_QUEUE_ENTRY_REMOVE_ERROR(RETRY_QUEUE,entry,attempt),err);}// clear the next entry after we've exhausted our attempts
1573
+ if(attempt===maxAttempts&&entryIdx+1<queueEntryKeys.length){_this3.removeStorageEntry(store,entryIdx+1,backoff);}}},backoff);}},{key:"checkReclaim",value:function checkReclaim(){var _this4=this;var createReclaimStartTask=function createReclaimStartTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_END)!==_this4.id){return;}if(store.get(QueueStatuses.RECLAIM_START)!==_this4.id){return;}_this4.reclaim(store.id);};};var createReclaimEndTask=function createReclaimEndTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_START)!==_this4.id){return;}store.set(QueueStatuses.RECLAIM_END,_this4.id);_this4.schedule.run(createReclaimStartTask(store),_this4.timeouts.reclaimWait,ScheduleModes.ABANDON);};};var tryReclaim=function tryReclaim(store){store.set(QueueStatuses.RECLAIM_START,_this4.id);store.set(QueueStatuses.ACK,_this4.schedule.now());_this4.schedule.run(createReclaimEndTask(store),_this4.timeouts.reclaimWait,ScheduleModes.ABANDON);};var findOtherQueues=function findOtherQueues(name){var res=[];var storageEngine=_this4.store.getOriginalEngine();var storageKeys=[];// 'keys' API is not supported by all the core SDK versions
1574
+ // Hence, we need this backward compatibility check
1575
+ if(isFunction(storageEngine.keys)){storageKeys=storageEngine.keys();}else {for(var i=0;i<storageEngine.length;i++){var key=storageEngine.key(i);if(key){storageKeys.push(key);}}}storageKeys.forEach(function(k){var keyParts=k?k.split('.'):[];if(keyParts.length>=3&&keyParts[0]===name&&keyParts[1]!==_this4.id&&keyParts[2]===QueueStatuses.ACK){res.push(_this4.storeManager.setStore({id:keyParts[1],name:name,validKeys:QueueStatuses,type:LOCAL_STORAGE,errorHandler:_this4.storeManager.errorHandler,logger:_this4.storeManager.logger}));}});return res;};findOtherQueues(this.name).forEach(function(store){if(_this4.schedule.now()-store.get(QueueStatuses.ACK)<_this4.timeouts.reclaimTimeout){return;}tryReclaim(store);});this.schedule.run(this.checkReclaim,this.timeouts.reclaimTimer,ScheduleModes.RESCHEDULE);}},{key:"clear",value:function clear(){this.schedule.cancelAll();this.setDefaultQueueEntries();}}]);}();
1576
+
1577
+ var pluginName='XhrQueue';var XhrQueue=function XhrQueue(){return {name:pluginName,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName]);},dataplaneEventsQueue:{/**
1578
+ * Initialize the queue for delivery
1579
+ * @param state Application state
1580
+ * @param httpClient http client instance
1581
+ * @param storeManager Store Manager instance
1582
+ * @param errorHandler Error handler instance
1583
+ * @param logger Logger instance
1584
+ * @returns RetryQueue instance
1585
+ */init:function init(state,httpClient,storeManager,errorHandler,logger){var writeKey=state.lifecycle.writeKey.value;httpClient.setAuthHeader(writeKey);var finalQOpts=getNormalizedQueueOptions(state.loadOptions.value.queueOptions);var eventsQueue=new RetryQueue(// adding write key to the queue name to avoid conflicts
1586
+ "".concat(QUEUE_NAME,"_").concat(writeKey),finalQOpts,function(itemData,done,qItemProcessInfo){var _getRequestInfo=getRequestInfo(itemData,state,qItemProcessInfo,logger),data=_getRequestInfo.data,url=_getRequestInfo.url,headers=_getRequestInfo.headers;httpClient.getAsyncData({url:url,options:{method:'POST',headers:headers,data:data,sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS,callback:function callback(result,details){var _details$xhr$status,_details$xhr;// If there is no error, we can consider the item as delivered
1587
+ if(isUndefined(details===null||details===void 0?void 0:details.error)){// null means item will not be processed further and will be removed from the queue (even from the storage)
1588
+ done(null);return;}var isRetryable=isErrRetryable((_details$xhr$status=details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.status)!==null&&_details$xhr$status!==void 0?_details$xhr$status:0);logMessageOnFailure(details,isRetryable,qItemProcessInfo,logger);if(isRetryable){var _details$xhr2;var retryReason=DEFAULT_RETRY_REASON;if(details!==null&&details!==void 0&&details.timedOut){retryReason=RETRY_REASON_CLIENT_TIMEOUT;}else if(isDefined(details===null||details===void 0||(_details$xhr2=details.xhr)===null||_details$xhr2===void 0?void 0:_details$xhr2.status)){retryReason="server-".concat(details.xhr.status);}done(details,{retryReason:retryReason});}else {// null means item will not be processed further and will be removed from the queue (even from the storage)
1589
+ done(null);}}});},storeManager,getStorageTypeForEventsPersistence(logger),logger,function(itemData){var _getBatchDeliveryPayl;var currentTime=getCurrentTimeFormatted();var events=itemData.map(function(queueItemData){return queueItemData.event;});// type casting to string as we know that the event has already been validated prior to enqueue
1590
+ return (_getBatchDeliveryPayl=getBatchDeliveryPayload(events,currentTime,logger))===null||_getBatchDeliveryPayl===void 0?void 0:_getBatchDeliveryPayl.length;});return eventsQueue;},/**
1591
+ * Add event to the queue for delivery
1592
+ * @param state Application state
1593
+ * @param eventsQueue RetryQueue instance
1594
+ * @param event RudderEvent object
1595
+ * @param errorHandler Error handler instance
1596
+ * @param logger Logger instance
1597
+ * @returns none
1598
+ */enqueue:function enqueue(state,eventsQueue,event,errorHandler,logger){// sentAt is only added here for the validation step
1599
+ // It'll be updated to the latest timestamp during actual delivery
1600
+ event.sentAt=getCurrentTimeFormatted();validateEventPayloadSize(event,logger);var dataplaneUrl=state.lifecycle.activeDataplaneUrl.value;var url=getDeliveryUrl(dataplaneUrl,event.type);// Other default headers are added by the HttpClient
1601
+ // Auth header is added during initialization
1602
+ var headers={// To maintain event ordering while using the HTTP API as per is documentation,
1603
+ // make sure to include anonymousId as a header
1604
+ AnonymousId:toBase64(event.anonymousId)};eventsQueue.addItem({url:url,headers:headers,event:event});}}};};
1605
+
1606
+ /**
1607
+ * Map plugin names to direct code imports from plugins package
1608
+ */var getBundledBuildPluginImports=function getBundledBuildPluginImports(){return {BeaconQueue:{}.BeaconQueue,CustomConsentManager:CustomConsentManager,DeviceModeDestinations:{}.DeviceModeDestinations,DeviceModeTransformation:{}.DeviceModeTransformation,ExternalAnonymousId:ExternalAnonymousId,GoogleLinker:{}.GoogleLinker,IubendaConsentManager:IubendaConsentManager,KetchConsentManager:KetchConsentManager,NativeDestinationQueue:{}.NativeDestinationQueue,OneTrustConsentManager:OneTrustConsentManager,StorageEncryption:StorageEncryption,StorageEncryptionLegacy:{}.StorageEncryptionLegacy,StorageMigrator:{}.StorageMigrator,XhrQueue:XhrQueue};};
1609
+
1610
+ /**
1611
+ * Map of mandatory plugin names and direct imports
1612
+ */var getMandatoryPluginsMap=function getMandatoryPluginsMap(){return {};};/**
1613
+ * Map of optional plugin names and direct imports for legacy builds
1614
+ */var getOptionalPluginsMap=function getOptionalPluginsMap(){return getBundledBuildPluginImports();};/**
1615
+ * Map of optional plugin names and dynamic imports for modern builds
1616
+ */var getRemotePluginsMap=function getRemotePluginsMap(activePluginNames){{return {};}};var pluginsInventory=_objectSpread2(_objectSpread2({},getMandatoryPluginsMap()),getOptionalPluginsMap());var remotePluginsInventory=function remotePluginsInventory(activePluginNames){return _objectSpread2({},getRemotePluginsMap());};
1617
+
1618
+ // TODO: add retry mechanism for getting remote plugins
1619
+ // TODO: add timeout error mechanism for marking remote plugins that failed to load as failed in state
1620
+ var PluginsManager=/*#__PURE__*/function(){function PluginsManager(engine,errorHandler,logger){_classCallCheck(this,PluginsManager);this.engine=engine;this.errorHandler=errorHandler;this.logger=logger;this.onError=this.onError.bind(this);}/**
1621
+ * Orchestrate the plugin loading and registering
1622
+ */return _createClass(PluginsManager,[{key:"init",value:function init(){state.lifecycle.status.value='pluginsLoading';// Expose pluginsCDNPath to global object, so it can be used in the promise that determines
1623
+ this.setActivePlugins();this.registerLocalPlugins();this.registerRemotePlugins();this.attachEffects();}/**
1624
+ * Update state based on plugin loaded status
1625
+ */// eslint-disable-next-line class-methods-use-this
1626
+ },{key:"attachEffects",value:function attachEffects(){m(function(){var isAllPluginsReady=state.plugins.activePlugins.value.length===0||state.plugins.loadedPlugins.value.length+state.plugins.failedPlugins.value.length===state.plugins.totalPluginsToLoad.value;if(isAllPluginsReady){n(function(){state.plugins.ready.value=true;// TODO: decide what to do if a plugin fails to load for any reason.
1627
+ // Should we stop here or should we progress?
1628
+ state.lifecycle.status.value='pluginsReady';});}});}/**
1629
+ * Determine the list of plugins that should be loaded based on sourceConfig & load options
1630
+ */// eslint-disable-next-line class-methods-use-this
1631
+ },{key:"getPluginsToLoadBasedOnConfig",value:function getPluginsToLoadBasedOnConfig(){var _this=this;// This contains the default plugins if load option has been omitted by user
1632
+ var pluginsToLoadFromConfig=state.plugins.pluginsToLoadFromConfig.value;if(!pluginsToLoadFromConfig){return [];}// Filter deprecated plugins
1633
+ pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){if(deprecatedPluginsList.includes(pluginName)){_this.logger.warn(DEPRECATED_PLUGIN_WARNING(PLUGINS_MANAGER,pluginName));return false;}return true;});var pluginGroupsToProcess=[{configurationStatus:function configurationStatus(){return isDefined(state.dataPlaneEvents.eventsQueuePluginName.value);},configurationStatusStr:'Data plane events delivery is enabled',activePluginName:state.dataPlaneEvents.eventsQueuePluginName.value,supportedPlugins:Object.values(DataPlaneEventsTransportToPluginNameMap),shouldAddMissingPlugins:true},{configurationStatus:function configurationStatus(){return getNonCloudDestinations(state.nativeDestinations.configuredDestinations.value).length>0;},configurationStatusStr:'Device mode destinations are connected to the source',supportedPlugins:['DeviceModeDestinations','NativeDestinationQueue']},{configurationStatus:function configurationStatus(){return getNonCloudDestinations(state.nativeDestinations.configuredDestinations.value).some(function(destination){return destination.shouldApplyDeviceModeTransformation;});},configurationStatusStr:'Device mode transformations are enabled for at least one destination',supportedPlugins:['DeviceModeTransformation']},{configurationStatus:function configurationStatus(){return isDefined(state.consents.activeConsentManagerPluginName.value);},configurationStatusStr:'Consent management is enabled',activePluginName:state.consents.activeConsentManagerPluginName.value,supportedPlugins:Object.values(ConsentManagersToPluginNameMap)},{configurationStatus:function configurationStatus(){return isDefined(state.storage.encryptionPluginName.value);},configurationStatusStr:'Storage encryption is enabled',activePluginName:state.storage.encryptionPluginName.value,supportedPlugins:Object.values(StorageEncryptionVersionsToPluginNameMap)},{configurationStatus:function configurationStatus(){return state.storage.migrate.value;},configurationStatusStr:'Storage migration is enabled',supportedPlugins:['StorageMigrator']}];var addMissingPlugins=false;pluginGroupsToProcess.forEach(function(group){if(group.configurationStatus()){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(group.activePluginName?function(pluginName){return !(pluginName!==group.activePluginName&&group.supportedPlugins.includes(pluginName));}:function(pluginName){return isDefined(pluginName);}// pass through
1634
+ );_this.addMissingPlugins(group,addMissingPlugins,pluginsToLoadFromConfig);}else {pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(group.basePlugins!==undefined?function(pluginName){return !(group.basePlugins.includes(pluginName)||group.supportedPlugins.includes(pluginName));}:function(pluginName){return !group.supportedPlugins.includes(pluginName);});}});return [].concat(_toConsumableArray(Object.keys(getMandatoryPluginsMap())),_toConsumableArray(pluginsToLoadFromConfig));}},{key:"addMissingPlugins",value:function addMissingPlugins(group,_addMissingPlugins,pluginsToLoadFromConfig){var shouldAddMissingPlugins=group.shouldAddMissingPlugins||_addMissingPlugins;var pluginsToConfigure;if(group.activePluginName){pluginsToConfigure=[].concat(_toConsumableArray(group.basePlugins||[]),[group.activePluginName]);}else {pluginsToConfigure=_toConsumableArray(group.supportedPlugins);}var missingPlugins=pluginsToConfigure.filter(function(pluginName){return !pluginsToLoadFromConfig.includes(pluginName);});if(missingPlugins.length>0){if(shouldAddMissingPlugins){pluginsToLoadFromConfig.push.apply(pluginsToLoadFromConfig,_toConsumableArray(missingPlugins));}this.logger.warn(generateMisconfiguredPluginsWarning(PLUGINS_MANAGER,group.configurationStatusStr,missingPlugins,shouldAddMissingPlugins));}}/**
1635
+ * Determine the list of plugins that should be activated
1636
+ */},{key:"setActivePlugins",value:function setActivePlugins(){var pluginsToLoad=this.getPluginsToLoadBasedOnConfig();// Merging available mandatory and optional plugin name list
1637
+ var availablePlugins=[].concat(_toConsumableArray(Object.keys(pluginsInventory)),_toConsumableArray(pluginNamesList));var activePlugins=[];var failedPlugins=[];pluginsToLoad.forEach(function(pluginName){if(availablePlugins.includes(pluginName)){activePlugins.push(pluginName);}else {failedPlugins.push(pluginName);}});if(failedPlugins.length>0){this.logger.warn(UNKNOWN_PLUGINS_WARNING(PLUGINS_MANAGER,failedPlugins));}n(function(){state.plugins.totalPluginsToLoad.value=pluginsToLoad.length;state.plugins.activePlugins.value=activePlugins;state.plugins.failedPlugins.value=failedPlugins;});}/**
1638
+ * Register plugins that are direct imports to PluginEngine
1639
+ */},{key:"registerLocalPlugins",value:function registerLocalPlugins(){var _this2=this;var unavailablePlugins=[];Object.entries(pluginsInventory).forEach(function(_ref){var _ref2=_slicedToArray(_ref,2),pluginName=_ref2[0],localPlugin=_ref2[1];if(state.plugins.activePlugins.value.includes(pluginName)){if(isFunction(localPlugin)){_this2.register([localPlugin()]);}else {unavailablePlugins.push(pluginName);}}});if(unavailablePlugins.length>0){state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.failedPlugins.value),unavailablePlugins);this.logger.error(UNAVAILABLE_PLUGINS_ERROR(PLUGINS_MANAGER,unavailablePlugins));}}/**
1640
+ * Register plugins that are dynamic imports to PluginEngine
1641
+ */},{key:"registerRemotePlugins",value:function registerRemotePlugins(){var _this3=this;var remotePluginsList=remotePluginsInventory(state.plugins.activePlugins.value);Promise.all(Object.keys(remotePluginsList).map(/*#__PURE__*/function(){var _ref3=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(remotePluginKey){return _regenerator().w(function(_context){while(1)switch(_context.n){case 0:_context.n=1;return remotePluginsList[remotePluginKey]().then(function(remotePluginModule){return _this3.register([remotePluginModule.default()]);}).catch(function(err){// TODO: add retry here if dynamic import fails
1642
+ state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.failedPlugins.value),[remotePluginKey]);_this3.onError(err,"Failed to load plugin \"".concat(remotePluginKey,"\""),err);});case 1:return _context.a(2);}},_callee);}));return function(_x){return _ref3.apply(this,arguments);};}())).catch(function(err){_this3.onError(err);});}/**
1643
+ * Extension point invoke that allows multiple plugins to be registered to it with error handling
1644
+ */},{key:"invokeMultiple",value:function invokeMultiple(extPoint){try{var _this$engine;for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key];}return (_this$engine=this.engine).invokeMultiple.apply(_this$engine,[extPoint].concat(args));}catch(e){this.onError(e,extPoint);return [];}}/**
1645
+ * Extension point invoke that allows a single plugin to be registered to it with error handling
1646
+ */},{key:"invokeSingle",value:function invokeSingle(extPoint){try{var _this$engine2;for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];}return (_this$engine2=this.engine).invokeSingle.apply(_this$engine2,[extPoint].concat(args));}catch(e){this.onError(e,extPoint);return null;}}/**
1647
+ * Plugin engine register with error handling
1648
+ */},{key:"register",value:function register(plugins){var _this4=this;plugins.forEach(function(plugin){try{_this4.engine.register(plugin,state);}catch(e){state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.failedPlugins.value),[plugin.name]);_this4.onError(e,"Failed to register plugin \"".concat(plugin.name,"\""));}});}// TODO: Implement reset API instead
1649
+ },{key:"unregisterLocalPlugins",value:function unregisterLocalPlugins(){var _this5=this;Object.keys(pluginsInventory).forEach(function(pluginKey){try{_this5.engine.unregister(pluginKey);}catch(e){_this5.onError(e,"Failed to unregister plugin \"".concat(pluginKey,"\""));}});}/**
1650
+ * Handle errors
1651
+ */},{key:"onError",value:function onError(error,customMessage,groupingHash){this.errorHandler.onError({error:error,context:PLUGINS_MANAGER,customMessage:customMessage,groupingHash:groupingHash});}}]);}();
1652
+
1653
+ var STORAGE_TEST_TOP_LEVEL_DOMAIN='__tld__';var CLIENT_DATA_STORE_COOKIE='clientDataInCookie';var CLIENT_DATA_STORE_LS='clientDataInLocalStorage';var CLIENT_DATA_STORE_MEMORY='clientDataInMemory';var CLIENT_DATA_STORE_SESSION='clientDataInSessionStorage';var USER_SESSION_KEYS=['userId','userTraits','anonymousId','groupId','groupTraits','initialReferrer','initialReferringDomain','sessionInfo','authToken'];
1654
+
1655
+ var storageClientDataStoreNameMap=_defineProperty(_defineProperty(_defineProperty(_defineProperty({},COOKIE_STORAGE,CLIENT_DATA_STORE_COOKIE),LOCAL_STORAGE,CLIENT_DATA_STORE_LS),MEMORY_STORAGE,CLIENT_DATA_STORE_MEMORY),SESSION_STORAGE,CLIENT_DATA_STORE_SESSION);
1656
+
1657
+ var legacyGetHostname=function legacyGetHostname(href){var l=document.createElement('a');l.href=href;return l.hostname;};/**
1658
+ * Levels returns all levels of the given url
1659
+ *
1660
+ * The method returns an empty array when the hostname is an ip.
1661
+ */var levelsFunc=function levelsFunc(url){var _host$split;// This is called before the polyfills load thus new URL cannot be used
1662
+ var host=typeof globalThis.URL!=='function'?legacyGetHostname(url):new URL(url).hostname;var parts=(_host$split=host===null||host===void 0?void 0:host.split('.'))!==null&&_host$split!==void 0?_host$split:[];var last=parts[parts.length-1];var levels=[];// Ip address.
1663
+ if(parts.length===4&&last&&last===parseInt(last,10).toString()){return levels;}// Localhost.
1664
+ if(parts.length<=1){// Fix to support localhost
1665
+ if(parts[0]&&parts[0].indexOf('localhost')!==-1){return ['localhost'];}return levels;}// Create levels.
1666
+ for(var i=parts.length-2;i>=0;i-=1){levels.push(parts.slice(i).join('.'));}return levels;};/**
1667
+ * Get the top domain.
1668
+ *
1669
+ * The function constructs the levels of domain and attempts to set a global
1670
+ * cookie on each one when it succeeds it returns the top level domain.
1671
+ *
1672
+ * The method returns an empty string when the hostname is an ip.
1673
+ */var domain=function domain(url){var levels=levelsFunc(url);// Lookup the real top level one.
1674
+ // eslint-disable-next-line unicorn/no-for-loop
1675
+ for(var i=0;i<levels.length;i+=1){var _domain=levels[i];var cname=STORAGE_TEST_TOP_LEVEL_DOMAIN;var opts={domain:"".concat(_domain.indexOf('localhost')!==-1?'':'.').concat(_domain)};try{// Set cookie on domain
1676
+ cookie(cname,1,opts);// If successful
1677
+ if(cookie(cname)){// Remove cookie from domain
1678
+ cookie(cname,null,opts);return _domain;}}catch(_unused){// Silently continue to next domain level if cookie access is restricted or setting fails
1679
+ // Best-effort cleanup to avoid leaking the test cookie
1680
+ try{cookie(cname,null,opts);}catch(_unused2){// Ignore if we are unable to delete the cookie
1681
+ }}}return '';};
1682
+
1683
+ var getDefaultCookieOptions=function getDefaultCookieOptions(){var topDomain=".".concat(domain(globalThis.location.href));return {maxage:DEFAULT_COOKIE_MAX_AGE_MS,path:'/',domain:!topDomain||topDomain==='.'?undefined:topDomain,samesite:'Lax',enabled:true};};var getDefaultLocalStorageOptions=function getDefaultLocalStorageOptions(){return {enabled:true};};var getDefaultSessionStorageOptions=function getDefaultSessionStorageOptions(){return {enabled:true};};var getDefaultInMemoryStorageOptions=function getDefaultInMemoryStorageOptions(){return {enabled:true};};
1684
+
1685
+ /**
1686
+ * A storage utility to retain values in memory via Storage interface
1687
+ */var InMemoryStorage=/*#__PURE__*/function(){function InMemoryStorage(logger){_classCallCheck(this,InMemoryStorage);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);_defineProperty(this,"data",{});this.options=getDefaultInMemoryStorageOptions();this.logger=logger;}return _createClass(InMemoryStorage,[{key:"configure",value:function configure(options){this.options=mergeDeepRight(this.options,options!==null&&options!==void 0?options:{});this.isEnabled=Boolean(this.options.enabled);return this.options;}},{key:"setItem",value:function setItem(key,value){this.data[key]=value;this.length=Object.keys(this.data).length;return value;}},{key:"getItem",value:function getItem(key){if(key in this.data){return this.data[key];}return null;}},{key:"removeItem",value:function removeItem(key){if(key in this.data){delete this.data[key];}this.length=Object.keys(this.data).length;return null;}},{key:"clear",value:function clear(){this.data={};this.length=0;}},{key:"key",value:function key(index){var _curKeys$index;var curKeys=this.keys();return (_curKeys$index=curKeys[index])!==null&&_curKeys$index!==void 0?_curKeys$index:null;}},{key:"keys",value:function keys(){return Object.keys(this.data);}}]);}();var defaultInMemoryStorage=new InMemoryStorage(defaultLogger);
1688
+
1689
+ var store$2 = {exports: {}};
1690
+
1691
+ var store$1=store$2.exports;var hasRequiredStore;function requireStore(){if(hasRequiredStore)return store$2.exports;hasRequiredStore=1;(function(module,exports$1){(function(global,factory){module.exports=factory();})(store$1,function(){function isJSON(obj){obj=JSON.stringify(obj);if(!/^\{[\s\S]*\}$/.test(obj)){return false;}return true;}function stringify(val){return val===undefined||typeof val==="function"?val+'':JSON.stringify(val);}function deserialize(value){if(typeof value!=='string'){return undefined;}try{return JSON.parse(value);}catch(e){return value;}}function isFunction(value){return {}.toString.call(value)==="[object Function]";}function isArray(value){return Object.prototype.toString.call(value)==="[object Array]";}// https://github.com/jaywcjlove/store.js/pull/8
1692
+ // Error: QuotaExceededError
1693
+ function dealIncognito(storage){var _KEY='_Is_Incognit',_VALUE='yes';try{// NOTE: set default storage when not passed in
1694
+ 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
1695
+ 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
1696
+ 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;},len:function len(){return storage.length;}};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$2);return store$2.exports;}
1697
+
1698
+ var storeExports = requireStore();
1699
+ var store = /*@__PURE__*/getDefaultExportFromCjs(storeExports);
1700
+
1701
+ // check if the get, set overloads and search methods are used at all
1702
+ // if we do, ensure we provide types to support overloads as per storejs docs
1703
+ // https://www.npmjs.com/package/storejs
1704
+ /**
1705
+ * A storage utility to persist values in localstorage via Storage interface
1706
+ */var LocalStorage=/*#__PURE__*/function(){function LocalStorage(logger){_classCallCheck(this,LocalStorage);_defineProperty(this,"isSupportAvailable",true);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);this.options=getDefaultLocalStorageOptions();this.logger=logger;}return _createClass(LocalStorage,[{key:"configure",value:function configure(options){this.options=mergeDeepRight(this.options,options!==null&&options!==void 0?options:{});this.isSupportAvailable=isStorageAvailable(LOCAL_STORAGE);this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}},{key:"setItem",value:function setItem(key,value){store.set(key,value);this.length=store.len();}// eslint-disable-next-line class-methods-use-this
1707
+ },{key:"getItem",value:function getItem(key){var value=store.get(key);return isUndefined(value)?null:value;}},{key:"removeItem",value:function removeItem(key){store.remove(key);this.length=store.len();}},{key:"clear",value:function clear(){store.clear();this.length=0;}},{key:"key",value:function key(index){var _curKeys$index;var curKeys=this.keys();return (_curKeys$index=curKeys[index])!==null&&_curKeys$index!==void 0?_curKeys$index:null;}// eslint-disable-next-line class-methods-use-this
1708
+ },{key:"keys",value:function keys(){return store.keys();}}]);}();var defaultLocalStorage=new LocalStorage(defaultLogger);
1709
+
1710
+ /**
1711
+ * A storage utility to persist values in SessionStorage via Storage interface
1712
+ */var SessionStorage=/*#__PURE__*/function(){function SessionStorage(logger){_classCallCheck(this,SessionStorage);_defineProperty(this,"isSupportAvailable",true);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);this.options=getDefaultSessionStorageOptions();this.logger=logger;}return _createClass(SessionStorage,[{key:"configure",value:function configure(options){this.options=mergeDeepRight(this.options,options!==null&&options!==void 0?options:{});this.isSupportAvailable=isStorageAvailable(SESSION_STORAGE);// when storage is blocked by the user, even accessing the property throws an error
1713
+ if(this.isSupportAvailable){this.store=globalThis.sessionStorage;}this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}},{key:"setItem",value:function setItem(key,value){if(!this.store){return;}this.store.setItem(key,value);this.length=this.store.length;}},{key:"getItem",value:function getItem(key){if(!this.store){return null;}var value=this.store.getItem(key);return isUndefined(value)?null:value;}},{key:"removeItem",value:function removeItem(key){if(!this.store){return;}this.store.removeItem(key);this.length=this.store.length;}},{key:"clear",value:function clear(){var _this$store;(_this$store=this.store)===null||_this$store===void 0||_this$store.clear();this.length=0;}},{key:"key",value:function key(index){var _this$store$key,_this$store2;return (_this$store$key=(_this$store2=this.store)===null||_this$store2===void 0?void 0:_this$store2.key(index))!==null&&_this$store$key!==void 0?_this$store$key:null;}},{key:"keys",value:function keys(){var keys=[];if(!this.store){return keys;}for(var i=0;i<this.store.length;i+=1){var key=this.store.key(i);if(key!==null){keys.push(key);}}return keys;}}]);}();var defaultSessionStorage=new SessionStorage(defaultLogger);
1714
+
1715
+ /**
1716
+ * A storage utility to persist values in cookies via Storage interface
1717
+ */var CookieStorage=/*#__PURE__*/function(){function CookieStorage(logger){_classCallCheck(this,CookieStorage);_defineProperty(this,"isSupportAvailable",true);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);this.logger=logger;}return _createClass(CookieStorage,[{key:"configure",value:function configure(options){if(!this.options){this.options=getDefaultCookieOptions();}this.options=mergeDeepRight(this.options,options!==null&&options!==void 0?options:{});if(this.options.sameDomainCookiesOnly){delete this.options.domain;}this.isSupportAvailable=isStorageAvailable(COOKIE_STORAGE,this);this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}},{key:"setItem",value:function setItem(key,value){cookie(key,value,this.options,this.logger);this.length=Object.keys(cookie()).length;return true;}// eslint-disable-next-line class-methods-use-this
1718
+ },{key:"getItem",value:function getItem(key){var value=cookie(key);return isUndefined(value)?null:value;}},{key:"removeItem",value:function removeItem(key){var result=this.setItem(key,null);this.length=Object.keys(cookie()).length;return result;}// eslint-disable-next-line class-methods-use-this
1719
+ },{key:"clear",value:function clear(){// Not implemented
1720
+ // getting a list of all cookie storage keys and remove all values
1721
+ // sounds risky to do as it will take on all top domain cookies
1722
+ // better to explicitly clear specific ones if needed
1723
+ }},{key:"key",value:function key(index){var _curKeys$index;var curKeys=this.keys();return (_curKeys$index=curKeys[index])!==null&&_curKeys$index!==void 0?_curKeys$index:null;}// eslint-disable-next-line class-methods-use-this
1724
+ },{key:"keys",value:function keys(){return Object.keys(cookie());}}]);}();var defaultCookieStorage=new CookieStorage(defaultLogger);
1725
+
1726
+ /**
1727
+ * A utility to retrieve the storage singleton instance by type
1728
+ */var getStorageEngine=function getStorageEngine(type){switch(type){case LOCAL_STORAGE:return defaultLocalStorage;case SESSION_STORAGE:return defaultSessionStorage;case MEMORY_STORAGE:return defaultInMemoryStorage;case COOKIE_STORAGE:return defaultCookieStorage;default:return defaultInMemoryStorage;}};/**
1729
+ * Configure cookie storage singleton
1730
+ */var configureCookieStorageEngine=function configureCookieStorageEngine(options){var cookieStorageOptions=defaultCookieStorage.configure(options);// Update the state with the final cookie storage options
1731
+ state.storage.cookie.value={maxage:cookieStorageOptions.maxage,path:cookieStorageOptions.path,domain:cookieStorageOptions.domain,samesite:cookieStorageOptions.samesite,expires:cookieStorageOptions.expires,secure:cookieStorageOptions.secure};};/**
1732
+ * Configure local storage singleton
1733
+ */var configureLocalStorageEngine=function configureLocalStorageEngine(options){defaultLocalStorage.configure(options);};/**
1734
+ * Configure in memory storage singleton
1735
+ */var configureInMemoryStorageEngine=function configureInMemoryStorageEngine(options){defaultInMemoryStorage.configure(options);};/**
1736
+ * Configure session storage singleton
1737
+ */var configureSessionStorageEngine=function configureSessionStorageEngine(options){defaultSessionStorage.configure(options);};/**
1738
+ * Configure all storage singleton instances
1739
+ */var configureStorageEngines=function configureStorageEngines(){var cookieStorageOptions=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var localStorageOptions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var inMemoryStorageOptions=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var sessionStorageOptions=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};configureCookieStorageEngine(cookieStorageOptions);configureLocalStorageEngine(localStorageOptions);configureInMemoryStorageEngine(inMemoryStorageOptions);configureSessionStorageEngine(sessionStorageOptions);};
1740
+
1741
+ /**
1742
+ * Store Implementation with dedicated storage
1743
+ */var Store=/*#__PURE__*/function(){function Store(config,engine,pluginsManager){var _config$isEncrypted,_config$validKeys;_classCallCheck(this,Store);this.id=config.id;this.name=config.name;this.isEncrypted=(_config$isEncrypted=config.isEncrypted)!==null&&_config$isEncrypted!==void 0?_config$isEncrypted:false;this.validKeys=(_config$validKeys=config.validKeys)!==null&&_config$validKeys!==void 0?_config$validKeys:{};this.engine=engine;this.noKeyValidation=Object.keys(this.validKeys).length===0;this.noCompoundKey=config.noCompoundKey;this.originalEngine=this.engine;this.errorHandler=config.errorHandler;this.logger=config.logger;this.pluginsManager=pluginsManager;}/**
1744
+ * Ensure the key is valid and with correct format
1745
+ */return _createClass(Store,[{key:"createValidKey",value:function createValidKey(key){var name=this.name,id=this.id,validKeys=this.validKeys,noKeyValidation=this.noKeyValidation,noCompoundKey=this.noCompoundKey;if(noKeyValidation){return noCompoundKey?key:[name,id,key].join('.');}// validate and return undefined if invalid key
1746
+ var compoundKey;Object.values(validKeys).forEach(function(validKeyName){if(validKeyName===key){compoundKey=noCompoundKey?key:[name,id,key].join('.');}});return compoundKey;}/**
1747
+ * Switch to inMemoryEngine, bringing any existing data with.
1748
+ */},{key:"swapQueueStoreToInMemoryEngine",value:function swapQueueStoreToInMemoryEngine(){var _this=this;var name=this.name,id=this.id,validKeys=this.validKeys,noCompoundKey=this.noCompoundKey;var inMemoryStorage=getStorageEngine(MEMORY_STORAGE);// grab existing data, but only for this page's queue instance, not all
1749
+ // better to keep other queues in localstorage to be flushed later
1750
+ // than to pull them into memory and remove them from durable storage
1751
+ Object.keys(validKeys).forEach(function(key){var value=_this.get(validKeys[key]);var validKey=noCompoundKey?key:[name,id,key].join('.');inMemoryStorage.setItem(validKey,value);// TODO: are we sure we want to drop clientData
1752
+ // if cookies are not available and localstorage is full?
1753
+ _this.remove(key);});this.engine=inMemoryStorage;}/**
1754
+ * Set value by key.
1755
+ */},{key:"set",value:function set(key,value){var validKey=this.createValidKey(key);if(!validKey){return;}try{// storejs that is used in localstorage engine already stringifies json
1756
+ this.engine.setItem(validKey,this.encrypt(stringifyWithoutCircular(value,false,[],this.logger)));}catch(err){if(isStorageQuotaExceeded(err)){this.logger.warn(STORAGE_QUOTA_EXCEEDED_WARNING("Store ".concat(this.id)));// switch to inMemory engine
1757
+ this.swapQueueStoreToInMemoryEngine();// and save it there
1758
+ this.set(key,value);}else {var customMessage=STORE_DATA_SAVE_ERROR(key);this.onError(err,customMessage,customMessage);}}}/**
1759
+ * Get by Key.
1760
+ */},{key:"get",value:function get(key){var validKey=this.createValidKey(key);var decryptedValue;try{if(!validKey){return null;}decryptedValue=this.decrypt(this.engine.getItem(validKey));if(isNullOrUndefined(decryptedValue)||decryptedValue===''){return null;}// storejs that is used in localstorage engine already deserializes json strings but swallows errors
1761
+ return JSON.parse(decryptedValue);}catch(err){var encryptionPluginName=state.storage.encryptionPluginName.value;// Skip error reporting only when the encryption plugin is configured but failed to load
1762
+ var shouldReportError=!encryptionPluginName||!state.plugins.failedPlugins.value.includes(encryptionPluginName);if(shouldReportError){var customMessage=STORE_DATA_FETCH_ERROR(key);this.onError(err,customMessage,customMessage);}return null;}}/**
1763
+ * Remove by Key.
1764
+ */},{key:"remove",value:function remove(key){var validKey=this.createValidKey(key);if(validKey){this.engine.removeItem(validKey);}}/**
1765
+ * Get original engine
1766
+ */},{key:"getOriginalEngine",value:function getOriginalEngine(){return this.originalEngine;}/**
1767
+ * Decrypt values
1768
+ */},{key:"decrypt",value:function decrypt(value){if(isNullOrUndefined(value)){return null;}return this.crypto(value,'decrypt');}/**
1769
+ * Encrypt value
1770
+ */},{key:"encrypt",value:function encrypt(value){return this.crypto(value,'encrypt');}/**
1771
+ * Extension point to use with encryption plugins
1772
+ */},{key:"crypto",value:function crypto(value,mode){var noEncryption=!this.isEncrypted||!value||typeof value!=='string'||trim(value)==='';if(noEncryption){return value;}var extensionPointName="storage.".concat(mode);var formattedValue=this.pluginsManager?this.pluginsManager.invokeSingle(extensionPointName,value):value;return typeof formattedValue==='undefined'?value:formattedValue!==null&&formattedValue!==void 0?formattedValue:'';}/**
1773
+ * Handle errors
1774
+ */},{key:"onError",value:function onError(error,customMessage,groupingHash){this.errorHandler.onError({error:error,context:"Store ".concat(this.id),customMessage:customMessage,groupingHash:groupingHash});}}]);}();
1775
+
1776
+ var getStorageTypeFromPreConsentIfApplicable=function getStorageTypeFromPreConsentIfApplicable(state,sessionKey){var overriddenStorageType;if(state.consents.preConsent.value.enabled){var _state$consents$preCo;switch((_state$consents$preCo=state.consents.preConsent.value.storage)===null||_state$consents$preCo===void 0?void 0:_state$consents$preCo.strategy){case 'none':overriddenStorageType=NO_STORAGE;break;case 'session':if(sessionKey!=='sessionInfo'){overriddenStorageType=NO_STORAGE;}break;case 'anonymousId':if(sessionKey!=='anonymousId'){overriddenStorageType=NO_STORAGE;}break;}}return overriddenStorageType;};
1777
+
1778
+ /**
1779
+ * A service to manage stores & available storage client configurations
1780
+ */var StoreManager=/*#__PURE__*/function(){function StoreManager(pluginsManager,errorHandler,logger){_classCallCheck(this,StoreManager);_defineProperty(this,"stores",{});_defineProperty(this,"isInitialized",false);this.errorHandler=errorHandler;this.logger=logger;this.pluginsManager=pluginsManager;}/**
1781
+ * Configure available storage client instances
1782
+ */return _createClass(StoreManager,[{key:"init",value:function init(){var _config$cookieStorage,_state$storage$cookie,_state$storage$cookie2;if(this.isInitialized){return;}var loadOptions=state.loadOptions.value;var config={cookieStorageOptions:{samesite:loadOptions.sameSiteCookie,secure:loadOptions.secureCookie,domain:loadOptions.setCookieDomain,sameDomainCookiesOnly:loadOptions.sameDomainCookiesOnly},localStorageOptions:{},inMemoryStorageOptions:{},sessionStorageOptions:{}};configureStorageEngines(_removeUndefinedValues(mergeDeepRight((_config$cookieStorage=config.cookieStorageOptions)!==null&&_config$cookieStorage!==void 0?_config$cookieStorage:{},(_state$storage$cookie=(_state$storage$cookie2=state.storage.cookie)===null||_state$storage$cookie2===void 0?void 0:_state$storage$cookie2.value)!==null&&_state$storage$cookie!==void 0?_state$storage$cookie:{})),_removeUndefinedValues(config.localStorageOptions),_removeUndefinedValues(config.inMemoryStorageOptions),_removeUndefinedValues(config.sessionStorageOptions));this.initClientDataStores();this.isInitialized=true;}/**
1783
+ * Create store to persist data used by the SDK like session, used details etc
1784
+ */},{key:"initClientDataStores",value:function initClientDataStores(){var _this=this;this.initializeStorageState();// TODO: fill in extra config values and bring them in from StoreManagerOptions if needed
1785
+ // TODO: should we pass the keys for all in order to validate or leave free as v1.1?
1786
+ // Initializing all the enabled store because previous user data might be in different storage
1787
+ // that needs auto migration
1788
+ var storageTypes=[MEMORY_STORAGE,LOCAL_STORAGE,COOKIE_STORAGE,SESSION_STORAGE];storageTypes.forEach(function(storageType){var _getStorageEngine;if((_getStorageEngine=getStorageEngine(storageType))!==null&&_getStorageEngine!==void 0&&_getStorageEngine.isEnabled){_this.setStore({id:storageClientDataStoreNameMap[storageType],name:storageClientDataStoreNameMap[storageType],isEncrypted:true,noCompoundKey:true,type:storageType,errorHandler:_this.errorHandler,logger:_this.logger});}});}},{key:"initializeStorageState",value:function initializeStorageState(){var _state$loadOptions$va,_this2=this;var globalStorageType=state.storage.type.value;var entriesOptions=(_state$loadOptions$va=state.loadOptions.value.storage)===null||_state$loadOptions$va===void 0?void 0:_state$loadOptions$va.entries;// Use the storage options from post consent if anything is defined
1789
+ var postConsentStorageOpts=state.consents.postConsent.value.storage;if(isDefined(postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.type)||isDefined(postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.entries)){globalStorageType=postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.type;entriesOptions=postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.entries;}var trulyAnonymousTracking=true;var storageEntries={};USER_SESSION_KEYS.forEach(function(sessionKey){var _entriesOptions,_ref,_ref2;var key=sessionKey;var storageKey=sessionKey;var configuredStorageType=(_entriesOptions=entriesOptions)===null||_entriesOptions===void 0||(_entriesOptions=_entriesOptions[key])===null||_entriesOptions===void 0?void 0:_entriesOptions.type;var preConsentStorageType=getStorageTypeFromPreConsentIfApplicable(state,sessionKey);// Storage type precedence order: pre-consent strategy > entry type > global type > default
1790
+ var storageType=(_ref=(_ref2=preConsentStorageType!==null&&preConsentStorageType!==void 0?preConsentStorageType:configuredStorageType)!==null&&_ref2!==void 0?_ref2:globalStorageType)!==null&&_ref!==void 0?_ref:DEFAULT_STORAGE_TYPE;var finalStorageType=_this2.getResolvedStorageTypeForEntry(storageType,sessionKey);if(finalStorageType!==NO_STORAGE){trulyAnonymousTracking=false;}storageEntries=_objectSpread2(_objectSpread2({},storageEntries),{},_defineProperty({},sessionKey,{type:finalStorageType,key:COOKIE_KEYS[storageKey]}));});n(function(){state.storage.type.value=globalStorageType;state.storage.entries.value=storageEntries;state.storage.trulyAnonymousTracking.value=trulyAnonymousTracking;});}},{key:"getResolvedStorageTypeForEntry",value:function getResolvedStorageTypeForEntry(storageType,sessionKey){var _getStorageEngine2,_getStorageEngine3,_getStorageEngine4,_getStorageEngine5,_getStorageEngine6;var finalStorageType=storageType;switch(storageType){case LOCAL_STORAGE:if(!((_getStorageEngine2=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine2!==void 0&&_getStorageEngine2.isEnabled)){finalStorageType=MEMORY_STORAGE;}break;case SESSION_STORAGE:if(!((_getStorageEngine3=getStorageEngine(SESSION_STORAGE))!==null&&_getStorageEngine3!==void 0&&_getStorageEngine3.isEnabled)){finalStorageType=MEMORY_STORAGE;}break;case MEMORY_STORAGE:case NO_STORAGE:break;case COOKIE_STORAGE:default:// First try setting the storage to cookie else to local storage
1791
+ if((_getStorageEngine4=getStorageEngine(COOKIE_STORAGE))!==null&&_getStorageEngine4!==void 0&&_getStorageEngine4.isEnabled){finalStorageType=COOKIE_STORAGE;}else if((_getStorageEngine5=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine5!==void 0&&_getStorageEngine5.isEnabled){finalStorageType=LOCAL_STORAGE;}else if((_getStorageEngine6=getStorageEngine(SESSION_STORAGE))!==null&&_getStorageEngine6!==void 0&&_getStorageEngine6.isEnabled){finalStorageType=SESSION_STORAGE;}else {finalStorageType=MEMORY_STORAGE;}break;}if(finalStorageType!==storageType){this.logger.warn(STORAGE_UNAVAILABLE_WARNING(STORE_MANAGER,sessionKey,storageType,finalStorageType));}return finalStorageType;}/**
1792
+ * Create a new store
1793
+ */},{key:"setStore",value:function setStore(storeConfig){var storageEngine=getStorageEngine(storeConfig.type);this.stores[storeConfig.id]=new Store(storeConfig,storageEngine,this.pluginsManager);return this.stores[storeConfig.id];}/**
1794
+ * Retrieve a store
1795
+ */},{key:"getStore",value:function getStore(id){return this.stores[id];}}]);}();
1796
+
1797
+ var isValidSourceConfig=function isValidSourceConfig(res){return isObjectLiteralAndNotNull(res)&&isObjectLiteralAndNotNull(res.source)&&!isNullOrUndefined(res.source.id)&&isObjectLiteralAndNotNull(res.source.config)&&Array.isArray(res.source.destinations);};var isValidStorageType=function isValidStorageType(storageType){return typeof storageType==='string'&&SUPPORTED_STORAGE_TYPES.includes(storageType);};var getTopDomain=function getTopDomain(url){// Create a URL object
1798
+ var urlObj=new URL(url);// Extract the host and protocol
1799
+ var host=urlObj.host,protocol=urlObj.protocol;// Split the host into parts
1800
+ var parts=host.split('.');var topDomain;// Handle different cases, especially for co.uk or similar TLDs
1801
+ if(parts.length>2){// Join the last two parts for the top-level domain
1802
+ topDomain="".concat(parts[parts.length-2],".").concat(parts[parts.length-1]);}else {// If only two parts or less, return as it is
1803
+ topDomain=host;}return {topDomain:topDomain,protocol:protocol};};var getTopDomainUrl=function getTopDomainUrl(url){var _getTopDomain=getTopDomain(url),topDomain=_getTopDomain.topDomain,protocol=_getTopDomain.protocol;return "".concat(protocol,"//").concat(topDomain);};var getDataServiceUrl=function getDataServiceUrl(endpoint,useExactDomain){var url=useExactDomain?window.location.origin:getTopDomainUrl(window.location.href);var formattedEndpoint=endpoint.startsWith('/')?endpoint.substring(1):endpoint;return "".concat(url,"/").concat(formattedEndpoint);};var isWebpageTopLevelDomain=function isWebpageTopLevelDomain(providedDomain){var _getTopDomain2=getTopDomain(window.location.href),topDomain=_getTopDomain2.topDomain;return topDomain===providedDomain;};
1804
+
1805
+ /**
1806
+ * Removes trailing slash from url
1807
+ * @param url
1808
+ * @returns url
1809
+ */var _removeTrailingSlashes=function removeTrailingSlashes(url){return url!==null&&url!==void 0&&url.endsWith('/')?_removeTrailingSlashes(url.substring(0,url.length-1)):url;};var getDomain=function getDomain(url){try{var urlObj=new URL(url);return urlObj.host;}catch(error){return null;}};/**
1810
+ * Get the referring domain from the referrer URL
1811
+ * @param referrer Page referrer
1812
+ * @returns Page referring domain
1813
+ */var getReferringDomain=function getReferringDomain(referrer){var _getDomain;return (_getDomain=getDomain(referrer))!==null&&_getDomain!==void 0?_getDomain:'';};/**
1814
+ * Extracts UTM parameters from the URL
1815
+ * @param url Page URL
1816
+ * @returns UTM parameters
1817
+ */var extractUTMParameters=function extractUTMParameters(url){var result={};try{var urlObj=new URL(url);var UTM_PREFIX='utm_';urlObj.searchParams.forEach(function(value,sParam){if(sParam.startsWith(UTM_PREFIX)){var utmParam=sParam.substring(UTM_PREFIX.length);// Not sure why we're doing this
1818
+ if(utmParam==='campaign'){utmParam='name';}result[utmParam]=value;}});}catch(error){// Do nothing
1819
+ }return result;};/**
1820
+ * To get the URL until the hash
1821
+ * @param url The input URL
1822
+ * @returns URL until the hash
1823
+ */var getUrlWithoutHash=function getUrlWithoutHash(url){var urlWithoutHash=url;try{var urlObj=new URL(url);urlWithoutHash=urlObj.origin+urlObj.pathname+urlObj.search;}catch(error){// Do nothing
1824
+ }return urlWithoutHash;};
1825
+
1826
+ var DEFAULT_PRE_CONSENT_STORAGE_STRATEGY='none';var DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE='immediate';
1827
+
1828
+ var isErrorReportingEnabled=function isErrorReportingEnabled(sourceConfig){var _sourceConfig$statsCo;return (sourceConfig===null||sourceConfig===void 0||(_sourceConfig$statsCo=sourceConfig.statsCollection)===null||_sourceConfig$statsCo===void 0||(_sourceConfig$statsCo=_sourceConfig$statsCo.errors)===null||_sourceConfig$statsCo===void 0?void 0:_sourceConfig$statsCo.enabled)===true;};var isMetricsReportingEnabled=function isMetricsReportingEnabled(sourceConfig){var _sourceConfig$statsCo2;return (sourceConfig===null||sourceConfig===void 0||(_sourceConfig$statsCo2=sourceConfig.statsCollection)===null||_sourceConfig$statsCo2===void 0||(_sourceConfig$statsCo2=_sourceConfig$statsCo2.metrics)===null||_sourceConfig$statsCo2===void 0?void 0:_sourceConfig$statsCo2.enabled)===true;};
1829
+
1830
+ /**
1831
+ * Validates and normalizes the consent options provided by the user
1832
+ * @param options Consent options provided by the user
1833
+ * @returns Validated and normalized consent options
1834
+ */var getValidPostConsentOptions=function getValidPostConsentOptions(options){var validOptions={sendPageEvent:false,trackConsent:false,discardPreConsentEvents:false};if(isObjectLiteralAndNotNull(options)){var clonedOptions=clone(options);validOptions.storage=clonedOptions.storage;if(isNonEmptyObject(clonedOptions.integrations)){validOptions.integrations=clonedOptions.integrations;}validOptions.discardPreConsentEvents=clonedOptions.discardPreConsentEvents===true;validOptions.sendPageEvent=clonedOptions.sendPageEvent===true;validOptions.trackConsent=clonedOptions.trackConsent===true;if(isNonEmptyObject(clonedOptions.consentManagement)){// Override enabled value with the current state value
1835
+ validOptions.consentManagement=mergeDeepRight(clonedOptions.consentManagement,{enabled:state.consents.enabled.value});}}return validOptions;};/**
1836
+ * Validates if the input is a valid consents data
1837
+ * @param value Input consents data
1838
+ * @returns true if the input is a valid consents data else false
1839
+ */var isValidConsentsData=function isValidConsentsData(value){return isNonEmptyObject(value)||Array.isArray(value);};/**
1840
+ * Retrieves the corresponding provider and plugin name of the selected consent manager from the supported consent managers
1841
+ * @param consentManagementOpts consent management options
1842
+ * @param logger logger instance
1843
+ * @returns Corresponding provider and plugin name of the selected consent manager from the supported consent managers
1844
+ */var getConsentManagerInfo=function getConsentManagerInfo(consentManagementOpts,logger){var provider=consentManagementOpts.provider;var consentManagerPluginName=provider?ConsentManagersToPluginNameMap[provider]:undefined;if(provider&&!consentManagerPluginName){logger.error(UNSUPPORTED_CONSENT_MANAGER_ERROR(CONFIG_MANAGER,provider,ConsentManagersToPluginNameMap));// Reset the provider value
1845
+ provider=undefined;}return {provider:provider,consentManagerPluginName:consentManagerPluginName};};/**
1846
+ * Validates and converts the consent management options into a normalized format
1847
+ * @param consentManagementOpts Consent management options provided by the user
1848
+ * @param logger logger instance
1849
+ * @returns An object containing the consent manager plugin name, initialized, enabled and consents data
1850
+ */var getConsentManagementData=function getConsentManagementData(consentManagementOpts,logger){var consentManagerPluginName;var allowedConsentIds=[];var deniedConsentIds=[];var initialized=false;var provider;var enabled=(consentManagementOpts===null||consentManagementOpts===void 0?void 0:consentManagementOpts.enabled)===true;if(isNonEmptyObject(consentManagementOpts)&&enabled){// Get the corresponding plugin name of the selected consent manager from the supported consent managers
1851
+ var _getConsentManagerInf=getConsentManagerInfo(consentManagementOpts,logger);provider=_getConsentManagerInf.provider;consentManagerPluginName=_getConsentManagerInf.consentManagerPluginName;if(isValidConsentsData(consentManagementOpts.allowedConsentIds)){allowedConsentIds=consentManagementOpts.allowedConsentIds;initialized=true;}if(isValidConsentsData(consentManagementOpts.deniedConsentIds)){deniedConsentIds=consentManagementOpts.deniedConsentIds;initialized=true;}}var consentsData={allowedConsentIds:allowedConsentIds,deniedConsentIds:deniedConsentIds};// Enable consent management only if consent manager is supported
1852
+ enabled=enabled&&Boolean(consentManagerPluginName);return {provider:provider,consentManagerPluginName:consentManagerPluginName,initialized:initialized,enabled:enabled,consentsData:consentsData};};
1853
+
1854
+ /**
1855
+ * Determines the SDK URL
1856
+ * @returns sdkURL
1857
+ */var getSDKUrl=function getSDKUrl(){// First try the new method of getting the SDK URL
1858
+ // from the script tag
1859
+ var scriptTag=document.querySelector('script[data-rsa-write-key]');if(scriptTag&&scriptTag.dataset.rsaWriteKey===state.lifecycle.writeKey.value){return scriptTag.src;}// If the new method fails, try the old method
1860
+ // TODO: We need to remove this once all the customers upgrade to the
1861
+ // latest SDK loading snippet
1862
+ var scripts=document.getElementsByTagName('script');var sdkFileNameRegex=/(?:^|\/)rsa(\.min)?\.js$/;// eslint-disable-next-line no-restricted-syntax
1863
+ var _iterator=_createForOfIteratorHelper(scripts),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var script=_step.value;var src=script.getAttribute('src');if(src&&sdkFileNameRegex.test(src)){return src;}}}catch(err){_iterator.e(err);}finally{_iterator.f();}return undefined;};/**
1864
+ * Updates the reporting state variables from the source config data
1865
+ * @param res Source config
1866
+ * @param logger Logger instance
1867
+ */var updateReportingState=function updateReportingState(res){state.reporting.isErrorReportingEnabled.value=isErrorReportingEnabled(res.source.config)&&!isSDKRunningInChromeExtension();state.reporting.isMetricsReportingEnabled.value=isMetricsReportingEnabled(res.source.config);};var getServerSideCookiesStateData=function getServerSideCookiesStateData(logger){var _state$loadOptions$va=state.loadOptions.value,useServerSideCookies=_state$loadOptions$va.useServerSideCookies,dataServiceEndpoint=_state$loadOptions$va.dataServiceEndpoint,storageOptsFromLoad=_state$loadOptions$va.storage,setCookieDomain=_state$loadOptions$va.setCookieDomain,sameDomainCookiesOnly=_state$loadOptions$va.sameDomainCookiesOnly;var cookieOptions=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.cookie;var sscEnabled=false;var finalDataServiceUrl;if(useServerSideCookies){var _cookieOptions$domain;sscEnabled=useServerSideCookies;var providedCookieDomain=(_cookieOptions$domain=cookieOptions.domain)!==null&&_cookieOptions$domain!==void 0?_cookieOptions$domain:setCookieDomain;/**
1868
+ * Based on the following conditions, we decide whether to use the exact domain or not to determine the data service URL:
1869
+ * 1. If the cookie domain is provided and it is not a top-level domain, then use the exact domain
1870
+ * 2. If the sameDomainCookiesOnly flag is set to true, then use the exact domain
1871
+ */var useExactDomain=isDefined(providedCookieDomain)&&!isWebpageTopLevelDomain(removeLeadingPeriod(providedCookieDomain))||sameDomainCookiesOnly;var dataServiceUrl=getDataServiceUrl(dataServiceEndpoint!==null&&dataServiceEndpoint!==void 0?dataServiceEndpoint:DEFAULT_DATA_SERVICE_ENDPOINT,useExactDomain);if(isValidURL(dataServiceUrl)){finalDataServiceUrl=_removeTrailingSlashes(dataServiceUrl);var curHost=getDomain(window.location.href);var dataServiceHost=getDomain(dataServiceUrl);// If the current host is different from the data service host, then it is a cross-site request
1872
+ // For server-side cookies to work, we need to set the SameSite=None and Secure attributes
1873
+ // One round of cookie options manipulation is taking place here
1874
+ // Based on these(setCookieDomain/storage.cookie or sameDomainCookiesOnly) two load-options, final cookie options are set in the storage module
1875
+ // TODO: Refactor the cookie options manipulation logic in one place
1876
+ if(curHost!==dataServiceHost){cookieOptions=_objectSpread2(_objectSpread2({},cookieOptions),{},{samesite:'None',secure:true});}/**
1877
+ * If the sameDomainCookiesOnly flag is not set and the cookie domain is provided(not top level domain),
1878
+ * and the data service host is different from the provided cookie domain, then we disable server-side cookies
1879
+ * ex: provided cookie domain: 'random.com', data service host: 'sub.example.com'
1880
+ */if(!sameDomainCookiesOnly&&useExactDomain&&dataServiceHost!==removeLeadingPeriod(providedCookieDomain)){sscEnabled=false;logger.warn(SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING(CONFIG_MANAGER,providedCookieDomain,dataServiceHost));}}else {sscEnabled=false;}}return {sscEnabled:sscEnabled,cookieOptions:cookieOptions,finalDataServiceUrl:finalDataServiceUrl};};var updateStorageStateFromLoadOptions=function updateStorageStateFromLoadOptions(logger){var _storageOptsFromLoad$;var storageOptsFromLoad=state.loadOptions.value.storage;var storageType=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.type;if(isDefined(storageType)&&!isValidStorageType(storageType)){logger.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));storageType=DEFAULT_STORAGE_TYPE;}var storageEncryptionVersion=storageOptsFromLoad===null||storageOptsFromLoad===void 0||(_storageOptsFromLoad$=storageOptsFromLoad.encryption)===null||_storageOptsFromLoad$===void 0?void 0:_storageOptsFromLoad$.version;var encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
1881
+ 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
1882
+ var configuredMigrationValue=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.migrate;var finalMigrationVal=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&finalMigrationVal!==configuredMigrationValue){logger.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}var _getServerSideCookies=getServerSideCookiesStateData(logger),sscEnabled=_getServerSideCookies.sscEnabled,finalDataServiceUrl=_getServerSideCookies.finalDataServiceUrl,cookieOptions=_getServerSideCookies.cookieOptions;n(function(){state.storage.type.value=storageType;state.storage.cookie.value=cookieOptions;state.serverCookies.isEnabledServerSideCookies.value=sscEnabled;state.serverCookies.dataServiceUrl.value=finalDataServiceUrl;state.storage.encryptionPluginName.value=StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];state.storage.migrate.value=finalMigrationVal;});};var updateConsentsStateFromLoadOptions=function updateConsentsStateFromLoadOptions(logger){var _preConsentOpts$stora,_preConsentOpts$stora2,_preConsentOpts$event,_preConsentOpts$event2;var _getConsentManagement=getConsentManagementData(state.loadOptions.value.consentManagement,logger),provider=_getConsentManagement.provider,consentManagerPluginName=_getConsentManagement.consentManagerPluginName,initialized=_getConsentManagement.initialized,enabled=_getConsentManagement.enabled,consentsData=_getConsentManagement.consentsData;// Pre-consent
1883
+ var preConsentOpts=state.loadOptions.value.preConsent;var storageStrategy=(_preConsentOpts$stora=preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$stora2=preConsentOpts.storage)===null||_preConsentOpts$stora2===void 0?void 0:_preConsentOpts$stora2.strategy)!==null&&_preConsentOpts$stora!==void 0?_preConsentOpts$stora:DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;var StorageStrategies=['none','session','anonymousId'];if(isDefined(storageStrategy)&&!StorageStrategies.includes(storageStrategy)){var _preConsentOpts$stora3;storageStrategy=DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;logger.warn(UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(CONFIG_MANAGER,preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$stora3=preConsentOpts.storage)===null||_preConsentOpts$stora3===void 0?void 0:_preConsentOpts$stora3.strategy,DEFAULT_PRE_CONSENT_STORAGE_STRATEGY));}var eventsDeliveryType=(_preConsentOpts$event=preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$event2=preConsentOpts.events)===null||_preConsentOpts$event2===void 0?void 0:_preConsentOpts$event2.delivery)!==null&&_preConsentOpts$event!==void 0?_preConsentOpts$event:DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;var deliveryTypes=['immediate','buffer'];if(isDefined(eventsDeliveryType)&&!deliveryTypes.includes(eventsDeliveryType)){var _preConsentOpts$event3;eventsDeliveryType=DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;logger.warn(UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(CONFIG_MANAGER,preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$event3=preConsentOpts.events)===null||_preConsentOpts$event3===void 0?void 0:_preConsentOpts$event3.delivery,DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE));}n(function(){var _state$loadOptions$va2;state.consents.activeConsentManagerPluginName.value=consentManagerPluginName;state.consents.initialized.value=initialized;state.consents.enabled.value=enabled;state.consents.data.value=consentsData;state.consents.provider.value=provider;state.consents.preConsent.value={// Only enable pre-consent if it is explicitly enabled and
1884
+ // if it is not already initialized and
1885
+ // if consent management is enabled
1886
+ enabled:((_state$loadOptions$va2=state.loadOptions.value.preConsent)===null||_state$loadOptions$va2===void 0?void 0:_state$loadOptions$va2.enabled)===true&&initialized===false&&enabled===true,storage:{strategy:storageStrategy},events:{delivery:eventsDeliveryType}};});};/**
1887
+ * Determines the consent management state variables from the source config data
1888
+ * @param resp Source config response
1889
+ * @param logger Logger instance
1890
+ */var updateConsentsState=function updateConsentsState(resp){var resolutionStrategy=state.consents.resolutionStrategy.value;var cmpMetadata;if(isObjectLiteralAndNotNull(resp.consentManagementMetadata)){if(state.consents.provider.value){var _resp$consentManageme,_resp$consentManageme2;resolutionStrategy=(_resp$consentManageme=(_resp$consentManageme2=resp.consentManagementMetadata.providers.find(function(p){return p.provider===state.consents.provider.value;}))===null||_resp$consentManageme2===void 0?void 0:_resp$consentManageme2.resolutionStrategy)!==null&&_resp$consentManageme!==void 0?_resp$consentManageme:state.consents.resolutionStrategy.value;}cmpMetadata=resp.consentManagementMetadata;}// If the provider is custom, then the resolution strategy is not applicable
1891
+ if(state.consents.provider.value==='custom'){resolutionStrategy=undefined;}n(function(){state.consents.metadata.value=clone(cmpMetadata);state.consents.resolutionStrategy.value=resolutionStrategy;});};var updateDataPlaneEventsStateFromLoadOptions=function updateDataPlaneEventsStateFromLoadOptions(logger){if(state.dataPlaneEvents.deliveryEnabled.value){var defaultEventsQueuePluginName='XhrQueue';var eventsQueuePluginName=defaultEventsQueuePluginName;if(state.loadOptions.value.useBeacon){if(state.capabilities.isBeaconAvailable.value){eventsQueuePluginName='BeaconQueue';}else {eventsQueuePluginName=defaultEventsQueuePluginName;logger.warn(UNSUPPORTED_BEACON_API_WARNING(CONFIG_MANAGER));}}n(function(){state.dataPlaneEvents.eventsQueuePluginName.value=eventsQueuePluginName;});}};var getSourceConfigURL=function getSourceConfigURL(configUrl,writeKey,lockIntegrationsVersion,lockPluginsVersion,logger){var defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey:writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString(),lockPluginsVersion:lockPluginsVersion.toString()});var origin=DEFAULT_CONFIG_BE_URL;var searchParams=defSearchParams;var pathname='/sourceConfig/';var hash='';if(isValidURL(configUrl)){var configUrlInstance=new URL(configUrl);if(!_removeTrailingSlashes(configUrlInstance.pathname).endsWith('/sourceConfig')){configUrlInstance.pathname="".concat(_removeTrailingSlashes(configUrlInstance.pathname),"/sourceConfig/");}configUrlInstance.pathname=removeDuplicateSlashes(configUrlInstance.pathname);defSearchParams.forEach(function(value,key){if(configUrlInstance.searchParams.get(key)===null){configUrlInstance.searchParams.set(key,value);}});origin=configUrlInstance.origin;pathname=configUrlInstance.pathname;searchParams=configUrlInstance.searchParams;hash=configUrlInstance.hash;}else {logger.warn(INVALID_CONFIG_URL_WARNING(CONFIG_MANAGER,configUrl));}return "".concat(origin).concat(pathname,"?").concat(searchParams).concat(hash);};/**
1892
+ * Transforms destinations config from source config response to Destination format
1893
+ * @param destinations Array of destination items from config response
1894
+ * @returns Array of transformed Destination objects
1895
+ */var getDestinationsFromConfig=function getDestinationsFromConfig(destinations){return destinations.map(function(destination){var _destination$shouldAp,_destination$propagat;return {id:destination.id,displayName:destination.destinationDefinition.displayName,enabled:destination.enabled,config:destination.config,shouldApplyDeviceModeTransformation:(_destination$shouldAp=destination.shouldApplyDeviceModeTransformation)!==null&&_destination$shouldAp!==void 0?_destination$shouldAp:false,propagateEventsUntransformedOnError:(_destination$propagat=destination.propagateEventsUntransformedOnError)!==null&&_destination$propagat!==void 0?_destination$propagat:false,userFriendlyId:getDestinationUserFriendlyId(destination.destinationDefinition.displayName,destination.id),isCustomIntegration:destination.destinationDefinition.displayName===CUSTOM_DEVICE_MODE_DESTINATION_DISPLAY_NAME};});};
1896
+
1897
+ /**
1898
+ * A function that determines the base URL for the integrations or plugins SDK
1899
+ * @param componentType The type of the component (integrations or plugins)
1900
+ * @param pathSuffix The path suffix to be appended to the base URL (js-integrations or plugins)
1901
+ * @param defaultComponentUrl The default URL to be used if the user has not provided a custom URL
1902
+ * @param currentSdkVersion The current version of the SDK
1903
+ * @param lockVersion Flag to lock the version of the component
1904
+ * @param urlFromLoadOptions The URL provided by the user in the load options
1905
+ * @param logger Logger instance
1906
+ * @returns The base URL for the integrations or plugins SDK
1907
+ */var getSDKComponentBaseURL=function getSDKComponentBaseURL(componentType,pathSuffix,defaultComponentUrl,currentSdkVersion,lockVersion,urlFromLoadOptions,logger){var sdkComponentBaseURL;// If the user has provided a custom URL, then validate, clean up and use it
1908
+ if(urlFromLoadOptions){if(!isValidURL(urlFromLoadOptions)){logger.error(COMPONENT_BASE_URL_ERROR(CONFIG_MANAGER,componentType,urlFromLoadOptions));return null;}sdkComponentBaseURL=_removeTrailingSlashes(urlFromLoadOptions);}else {sdkComponentBaseURL=defaultComponentUrl;// We can automatically determine the base URL only for CDN installations
1909
+ if(state.context.app.value.installType==='cdn'){var sdkURL=getSDKUrl();if(sdkURL){// Extract the base URL from the core SDK file URL
1910
+ // and append the path suffix to it
1911
+ sdkComponentBaseURL=sdkURL.split('/').slice(0,-1).concat(pathSuffix).join('/');}}}// If the version needs to be locked, then replace the major version in the URL
1912
+ // with the current version of the SDK
1913
+ if(lockVersion){sdkComponentBaseURL=sdkComponentBaseURL.replace(new RegExp("/".concat(CDN_ARCH_VERSION_DIR,"/").concat(BUILD_TYPE,"/").concat(pathSuffix,"$")),"/".concat(currentSdkVersion,"/").concat(BUILD_TYPE,"/").concat(pathSuffix));}return sdkComponentBaseURL;};/**
1914
+ * A function that determines integration SDK loading path
1915
+ * @param currentSdkVersion Current SDK version
1916
+ * @param lockIntegrationsVersion Flag to lock the integrations version
1917
+ * @param integrationsUrlFromLoadOptions URL to load the integrations from as provided by the user
1918
+ * @param logger Logger instance
1919
+ * @returns
1920
+ */var getIntegrationsCDNPath=function getIntegrationsCDNPath(currentSdkVersion,lockIntegrationsVersion,integrationsUrlFromLoadOptions,logger){return getSDKComponentBaseURL('integrations',CDN_INT_DIR,DEFAULT_INTEGRATION_SDKS_URL,currentSdkVersion,lockIntegrationsVersion,integrationsUrlFromLoadOptions,logger);};
1921
+
1922
+ var ConfigManager=/*#__PURE__*/function(){function ConfigManager(httpClient,errorHandler,logger){_classCallCheck(this,ConfigManager);this.errorHandler=errorHandler;this.logger=logger;this.httpClient=httpClient;this.onError=this.onError.bind(this);this.processConfig=this.processConfig.bind(this);}return _createClass(ConfigManager,[{key:"attachEffects",value:function attachEffects(){var _this=this;m(function(){_this.logger.setMinLogLevel(state.lifecycle.logLevel.value);});}/**
1923
+ * A function to validate, construct and store loadOption, lifecycle, source and destination
1924
+ * config related information in global state
1925
+ */},{key:"init",value:function init(){var _this2=this;var _state$loadOptions$va=state.loadOptions.value,logLevel=_state$loadOptions$va.logLevel,configUrl=_state$loadOptions$va.configUrl,lockIntegrationsVersion=_state$loadOptions$va.lockIntegrationsVersion,lockPluginsVersion=_state$loadOptions$va.lockPluginsVersion,destSDKBaseURL=_state$loadOptions$va.destSDKBaseURL;_state$loadOptions$va.pluginsSDKBaseURL;var integrations=_state$loadOptions$va.integrations;// determine the path to fetch integration SDK from
1926
+ var intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,destSDKBaseURL,this.logger);if(isNull(intgCdnUrl)){return;}var pluginsCDNPath;this.attachEffects();state.lifecycle.activeDataplaneUrl.value=_removeTrailingSlashes(state.lifecycle.dataPlaneUrl.value);updateStorageStateFromLoadOptions(this.logger);updateConsentsStateFromLoadOptions(this.logger);updateDataPlaneEventsStateFromLoadOptions(this.logger);// set application lifecycle state in global state
1927
+ n(function(){state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycle.pluginsCDNPath.value=pluginsCDNPath;if(logLevel){state.lifecycle.logLevel.value=logLevel;}state.lifecycle.sourceConfigUrl.value=getSourceConfigURL(configUrl,state.lifecycle.writeKey.value,lockIntegrationsVersion,lockPluginsVersion,_this2.logger);state.metrics.metricsServiceUrl.value="".concat(state.lifecycle.activeDataplaneUrl.value,"/").concat(METRICS_SERVICE_ENDPOINT);// Data in the loadOptions state is already normalized
1928
+ state.nativeDestinations.loadOnlyIntegrations.value=integrations;});this.getConfig();}/**
1929
+ * Handle errors
1930
+ */},{key:"onError",value:function onError(error,customMessage,groupingHash){this.errorHandler.onError({error:error,context:CONFIG_MANAGER,customMessage:customMessage,groupingHash:groupingHash});}/**
1931
+ * A callback function that is executed once we fetch the source config response.
1932
+ * Use to construct and store information that are dependent on the sourceConfig.
1933
+ */},{key:"processConfig",value:function processConfig(response,details){// TODO: add retry logic with backoff based on rejectionDetails.xhr.status
1934
+ // We can use isErrRetryable utility method
1935
+ if(!isDefined(response)){if(isDefined(details)){this.onError(details.error,SOURCE_CONFIG_FETCH_ERROR);}else {this.onError(new Error(SOURCE_CONFIG_FETCH_ERROR));}return;}var res;try{if(isString(response)){res=JSON.parse(response);}else {res=response;}}catch(err){this.onError(err,SOURCE_CONFIG_RESOLUTION_ERROR);return;}if(!isValidSourceConfig(res)){this.onError(new Error(SOURCE_CONFIG_RESOLUTION_ERROR));return;}// Log error and abort if source is disabled
1936
+ if(res.source.enabled===false){this.logger.error(SOURCE_DISABLED_ERROR);return;}// set the values in state for reporting slice
1937
+ updateReportingState(res);var nativeDestinations=res.source.destinations.length>0?getDestinationsFromConfig(res.source.destinations):[];// set in the state --> source, destination, lifecycle, reporting
1938
+ n(function(){var _state$loadOptions$va2;// set source related information in state
1939
+ state.source.value={config:res.source.config,name:res.source.name,id:res.source.id,workspaceId:res.source.workspaceId};// set device mode destination related information in state
1940
+ state.nativeDestinations.configuredDestinations.value=nativeDestinations;// set the desired optional plugins
1941
+ state.plugins.pluginsToLoadFromConfig.value=(_state$loadOptions$va2=state.loadOptions.value.plugins)!==null&&_state$loadOptions$va2!==void 0?_state$loadOptions$va2:[];updateConsentsState(res);// set application lifecycle state
1942
+ state.lifecycle.status.value='configured';});}/**
1943
+ * A function to fetch source config either from /sourceConfig endpoint
1944
+ * or from getSourceConfig load option
1945
+ * @returns
1946
+ */},{key:"getConfig",value:function getConfig(){var _this3=this;var sourceConfigFunc=state.loadOptions.value.getSourceConfig;if(sourceConfigFunc){if(!isFunction(sourceConfigFunc)){this.logger.error(SOURCE_CONFIG_OPTION_ERROR(CONFIG_MANAGER));return;}// Fetch source config from the function
1947
+ var res=sourceConfigFunc();if(res instanceof Promise){res.then(function(pRes){return _this3.processConfig(pRes);}).catch(function(err){_this3.onError(err,'SourceConfig');});}else {this.processConfig(res);}}else {// Fetch source configuration from the configured URL
1948
+ this.httpClient.getAsyncData({url:state.lifecycle.sourceConfigUrl.value,options:{headers:{'Content-Type':undefined}},callback:this.processConfig});}}}]);}();
1949
+
1950
+ /**
1951
+ * To get the timezone of the user
1952
+ *
1953
+ * @returns string
1954
+ */var getTimezone=function getTimezone(){// Not susceptible to super-linear backtracking
1955
+ // eslint-disable-next-line sonarjs/slow-regex
1956
+ var timezone=/([A-Z]+[+-]\d+)/.exec(new Date().toString());return timezone!==null&&timezone!==void 0&&timezone[1]?timezone[1]:'NA';};
1957
+
1958
+ /**
1959
+ * Get the referrer URL
1960
+ * @returns The referrer URL
1961
+ */var getReferrer=function getReferrer(){var _getDocument;var getDocument=arguments.length>0&&arguments[0]!==undefined?arguments[0]:function(){return document;};return ((_getDocument=getDocument())===null||_getDocument===void 0?void 0:_getDocument.referrer)||'$direct';};/**
1962
+ * To get the canonical URL of the page
1963
+ * @returns canonical URL
1964
+ */var getCanonicalUrl=function getCanonicalUrl(){var getDocument=arguments.length>0&&arguments[0]!==undefined?arguments[0]:function(){return document;};var docInstance=getDocument();var tags=docInstance.getElementsByTagName('link');var canonicalUrl='';for(var i=0;tags[i];i+=1){var tag=tags[i];if(tag.getAttribute('rel')==='canonical'&&!canonicalUrl){var _tag$getAttribute;canonicalUrl=(_tag$getAttribute=tag.getAttribute('href'))!==null&&_tag$getAttribute!==void 0?_tag$getAttribute:'';break;}}return canonicalUrl;};var getUserAgent=function getUserAgent(){var getNavigator=arguments.length>0&&arguments[0]!==undefined?arguments[0]:function(){return globalThis.navigator;};var navigator=getNavigator();if(isUndefined(navigator)){return null;}var userAgent=navigator.userAgent;var _ref=navigator,brave=_ref.brave;// For supporting Brave browser detection,
1965
+ // add "Brave/<version>" to the user agent with the version value from the Chrome component
1966
+ if(brave&&Object.getPrototypeOf(brave).isBrave){// Example:
1967
+ // Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36
1968
+ var matchedArr=userAgent.match(/(chrome)\/([\w.]+)/i);if(matchedArr){userAgent="".concat(userAgent," Brave/").concat(matchedArr[2]);}}return userAgent;};var getLanguage=function getLanguage(){var _navigator$language;var getNavigator=arguments.length>0&&arguments[0]!==undefined?arguments[0]:function(){return globalThis.navigator;};var navigator=getNavigator();if(isUndefined(navigator)){return null;}return (_navigator$language=navigator.language)!==null&&_navigator$language!==void 0?_navigator$language:navigator.browserLanguage;};/**
1969
+ * Default page properties
1970
+ * @returns Default page properties
1971
+ */var getDefaultPageProperties=function getDefaultPageProperties(){var getLocation=arguments.length>0&&arguments[0]!==undefined?arguments[0]:function(){return globalThis.location;};var getDocument=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(){return document;};var location=getLocation();var canonicalUrl=getCanonicalUrl(getDocument);var path=location.pathname;var tabUrl=location.href;var pageUrl=tabUrl;var search=location.search;// If valid canonical URL is provided use this as page URL.
1972
+ if(canonicalUrl){try{var urlObj=new URL(canonicalUrl);// If existing, query params of canonical URL will be used instead of the location.search ones
1973
+ if(urlObj.search===''){pageUrl=canonicalUrl+search;}else {pageUrl=canonicalUrl;}path=urlObj.pathname;}catch(err){// Do nothing
1974
+ }}var url=getUrlWithoutHash(pageUrl);var _getDocument2=getDocument(),title=_getDocument2.title;var referrer=getReferrer(getDocument);return {path:path,referrer:referrer,referring_domain:getReferringDomain(referrer),search:search,title:title,url:url,tab_url:tabUrl};};
1975
+
1976
+ var getUserAgentClientHint=function getUserAgentClientHint(callback){var level=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'none';if(level==='none'){callback(undefined);}if(level==='default'){callback(navigator.userAgentData);}if(level==='full'){var _navigator$userAgentD;(_navigator$userAgentD=navigator.userAgentData)===null||_navigator$userAgentD===void 0||_navigator$userAgentD.getHighEntropyValues(['architecture','bitness','brands','mobile','model','platform','platformVersion','uaFullVersion','fullVersionList','wow64']).then(function(ua){callback(ua);}).catch(function(){callback();});}};
1977
+
1978
+ var isDatasetAvailable=function isDatasetAvailable(){var testElement=globalThis.document.createElement('div');testElement.setAttribute('data-a-b','c');return testElement.dataset?testElement.dataset.aB==='c':false;};var legacyJSEngineRequiredPolyfills={// Ideally, we should separate the checks for URL and URLSearchParams but
1979
+ // the polyfill service serves them under the same feature name, "URL".
1980
+ URL:function URL(){return !isFunction(globalThis.URL)||!isFunction(globalThis.URLSearchParams);},Promise:function Promise(){return !isFunction(globalThis.Promise);},'Number.isNaN':function NumberIsNaN(){return !isFunction(globalThis.Number.isNaN);},'Number.isInteger':function NumberIsInteger(){return !isFunction(globalThis.Number.isInteger);},'Array.from':function ArrayFrom(){return !isFunction(globalThis.Array.from);},'Array.prototype.find':function ArrayPrototypeFind(){return !isFunction(globalThis.Array.prototype.find);},'Array.prototype.includes':function ArrayPrototypeIncludes(){return !isFunction(globalThis.Array.prototype.includes);},'String.prototype.endsWith':function StringPrototypeEndsWith(){return !isFunction(globalThis.String.prototype.endsWith);},'String.prototype.startsWith':function StringPrototypeStartsWith(){return !isFunction(globalThis.String.prototype.startsWith);},'String.prototype.includes':function StringPrototypeIncludes(){return !isFunction(globalThis.String.prototype.includes);},'String.prototype.replaceAll':function StringPrototypeReplaceAll(){return !isFunction(globalThis.String.prototype.replaceAll);},'String.fromCodePoint':function StringFromCodePoint(){return !isFunction(globalThis.String.fromCodePoint);},'Object.entries':function ObjectEntries(){return !isFunction(globalThis.Object.entries);},'Object.values':function ObjectValues(){return !isFunction(globalThis.Object.values);},'Object.assign':function ObjectAssign(){return !isFunction(globalThis.Object.assign);},'Object.fromEntries':function ObjectFromEntries(){return !isFunction(globalThis.Object.fromEntries);},'Element.prototype.dataset':function ElementPrototypeDataset(){return !isDatasetAvailable();},// Ideally, we should separate the checks for TextEncoder and TextDecoder but
1981
+ // the polyfill service serves them under the same feature name, "TextEncoder".
1982
+ TextEncoder:function TextEncoder(){return !isFunction(globalThis.TextEncoder)||!isFunction(globalThis.TextDecoder);},requestAnimationFrame:function requestAnimationFrame(){return !isFunction(globalThis.requestAnimationFrame)||!isFunction(globalThis.cancelAnimationFrame);},CustomEvent:function CustomEvent(){return !isFunction(globalThis.CustomEvent);},'navigator.sendBeacon':function navigatorSendBeacon(){return !isFunction(globalThis.navigator.sendBeacon);},// Note, the polyfill service serves both ArrayBuffer and Uint8Array under the same feature name, "ArrayBuffer".
1983
+ ArrayBuffer:function ArrayBuffer(){return !isFunction(globalThis.Uint8Array);},Set:function Set(){return !isFunction(globalThis.Set);},atob:function atob(){return !isFunction(globalThis.atob);}};var isLegacyJSEngine=function isLegacyJSEngine(){var requiredCapabilitiesList=Object.keys(legacyJSEngineRequiredPolyfills);var needsPolyfill=false;/* eslint-disable-next-line unicorn/no-for-loop */for(var i=0;i<requiredCapabilitiesList.length;i++){var isCapabilityMissing=legacyJSEngineRequiredPolyfills[requiredCapabilitiesList[i]];if(isFunction(isCapabilityMissing)&&isCapabilityMissing()){needsPolyfill=true;break;}}return needsPolyfill;};
1984
+
1985
+ var polyfillIoSdkUrl='https://polyfill-fastly.io/v3/polyfill.min.js';var POLYFILL_URL="".concat(polyfillIoSdkUrl,"?version=3.111.0&features=").concat(Object.keys(legacyJSEngineRequiredPolyfills).join('%2C'));var POLYFILL_LOAD_TIMEOUT=10*1000;// 10 seconds
1986
+ var POLYFILL_SCRIPT_ID='rudderstackPolyfill';
1987
+
1988
+ var hasCrypto=function hasCrypto(){return !isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);};// eslint-disable-next-line compat/compat -- We are checking for the existence of navigator.userAgentData
1989
+ var hasUAClientHints=function hasUAClientHints(){return !isNullOrUndefined(globalThis.navigator.userAgentData);};var hasBeacon=function hasBeacon(){return !isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);};
1990
+
1991
+ var getScreenDetails=function getScreenDetails(){var screenDetails={density:0,width:0,height:0,innerWidth:0,innerHeight:0};screenDetails={width:globalThis.screen.width,height:globalThis.screen.height,density:globalThis.devicePixelRatio,innerWidth:globalThis.innerWidth,innerHeight:globalThis.innerHeight};return screenDetails;};
1992
+
1993
+ var CapabilitiesManager=/*#__PURE__*/function(){function CapabilitiesManager(httpClient,errorHandler,logger){_classCallCheck(this,CapabilitiesManager);this.httpClient=httpClient;this.errorHandler=errorHandler;this.logger=logger;this.externalSrcLoader=new ExternalSrcLoader(this.logger);this.onError=this.onError.bind(this);this.onReady=this.onReady.bind(this);}return _createClass(CapabilitiesManager,[{key:"init",value:function init(){this.prepareBrowserCapabilities();this.attachWindowListeners();}/**
1994
+ * Detect supported capabilities and set values in state
1995
+ */// eslint-disable-next-line class-methods-use-this
1996
+ },{key:"detectBrowserCapabilities",value:function detectBrowserCapabilities(){var _this=this;n(function(){// Storage related details
1997
+ 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
1998
+ 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
1999
+ state.context.userAgent.value=getUserAgent();state.context.locale.value=getLanguage();state.context.screen.value=getScreenDetails();state.context.timezone.value=getTimezone();if(hasUAClientHints()){getUserAgentClientHint(function(uach){state.context['ua-ch'].value=uach;},state.loadOptions.value.uaChTrackLevel);}});// Ad blocker detection
2000
+ m(function(){if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(_this.httpClient);}});}/**
2001
+ * Detect if polyfills are required and then load script from polyfill URL
2002
+ */},{key:"prepareBrowserCapabilities",value:function prepareBrowserCapabilities(){var _this2=this;state.capabilities.isLegacyDOM.value=isLegacyJSEngine();var customPolyfillUrl=state.loadOptions.value.polyfillURL;var polyfillUrl=POLYFILL_URL;if(isDefinedAndNotNull(customPolyfillUrl)){if(isValidURL(customPolyfillUrl)){polyfillUrl=customPolyfillUrl;}else {this.logger.warn(INVALID_POLYFILL_URL_WARNING(CAPABILITIES_MANAGER,customPolyfillUrl));}}var shouldLoadPolyfill=state.loadOptions.value.polyfillIfRequired&&state.capabilities.isLegacyDOM.value&&isValidURL(polyfillUrl);if(shouldLoadPolyfill){var isDefaultPolyfillService=polyfillUrl!==state.loadOptions.value.polyfillURL;if(isDefaultPolyfillService){// write key specific callback
2003
+ // NOTE: we're not putting this into RudderStackGlobals as providing the property path to the callback function in the polyfill URL is not possible
2004
+ var polyfillCallbackName="RS_polyfillCallback_".concat(state.lifecycle.writeKey.value);var polyfillCallback=function polyfillCallback(){_this2.onReady();// Remove the entry from window so we don't leave room for calling it again
2005
+ delete globalThis[polyfillCallbackName];};globalThis[polyfillCallbackName]=polyfillCallback;polyfillUrl="".concat(polyfillUrl,"&callback=").concat(polyfillCallbackName);}this.externalSrcLoader.loadJSFile({url:polyfillUrl,id:POLYFILL_SCRIPT_ID,async:true,timeout:POLYFILL_LOAD_TIMEOUT,callback:function callback(scriptId){if(!scriptId){_this2.onError(new Error(POLYFILL_SCRIPT_LOAD_ERROR(POLYFILL_SCRIPT_ID,polyfillUrl)));}else if(!isDefaultPolyfillService){_this2.onReady();}}});}else {this.onReady();}}/**
2006
+ * Attach listeners to window to observe event that update capabilities state values
2007
+ */},{key:"attachWindowListeners",value:function attachWindowListeners(){globalThis.addEventListener('offline',function(){state.capabilities.isOnline.value=false;});globalThis.addEventListener('online',function(){state.capabilities.isOnline.value=true;});globalThis.addEventListener('resize',debounce(function(){state.context.screen.value=getScreenDetails();},this));}/**
2008
+ * Set the lifecycle status to next phase
2009
+ */// eslint-disable-next-line class-methods-use-this
2010
+ },{key:"onReady",value:function onReady(){this.detectBrowserCapabilities();state.lifecycle.status.value='browserCapabilitiesReady';}/**
2011
+ * Handles error
2012
+ * @param error The error object
2013
+ */},{key:"onError",value:function onError(error,groupingHash){this.errorHandler.onError({error:error,context:CAPABILITIES_MANAGER,groupingHash:groupingHash});}}]);}();
2014
+
2015
+ var CHANNEL='web';// These are the top-level elements in the standard RudderStack event spec
2016
+ var TOP_LEVEL_ELEMENTS=['integrations','anonymousId','originalTimestamp'];// Reserved elements in the context of standard RudderStack event spec
2017
+ // Typically, these elements are not allowed to be overridden by the user
2018
+ var CONTEXT_RESERVED_ELEMENTS=['library','consentManagement','userAgent','ua-ch','screen'];// Reserved elements in the standard RudderStack event spec
2019
+ var RESERVED_ELEMENTS=['id','anonymous_id','user_id','sent_at','timestamp','received_at','original_timestamp','event','event_text','channel','context_ip','context_request_ip','context_passed_ip','group_id','previous_id'];
2020
+
2021
+ /**
2022
+ * A function to check given value is a number or not
2023
+ * @param num input value
2024
+ * @returns boolean
2025
+ */var isNumber=function isNumber(num){return typeof num==='number'&&!Number.isNaN(num);};/**
2026
+ * A function to check given number has minimum length or not
2027
+ * @param minimumLength minimum length
2028
+ * @param num input number
2029
+ * @returns boolean
2030
+ */var hasMinLength=function hasMinLength(minimumLength,num){return num.toString().length>=minimumLength;};/**
2031
+ * A function to check given value is a positive integer or not
2032
+ * @param num input value
2033
+ * @returns boolean
2034
+ */var isPositiveInteger=function isPositiveInteger(num){return isNumber(num)&&num>=0&&Number.isInteger(num);};
2035
+
2036
+ var _excluded=["entries"];var MIN_SESSION_ID_LENGTH=10;var isCutOffTimeExceeded=function isCutOffTimeExceeded(sessionInfo){var cutOff=sessionInfo.cutOff;var timestamp=Date.now();return Boolean((cutOff===null||cutOff===void 0?void 0:cutOff.enabled)&&cutOff.expiresAt&&timestamp>cutOff.expiresAt);};/**
2037
+ * A function to validate whether the current auto tracking session has expired or not.
2038
+ * It checks for the current session expiry and the cut off time expiry.
2039
+ * @param sessionInfo session info
2040
+ * @returns boolean
2041
+ */var hasSessionExpired=function hasSessionExpired(sessionInfo){var isCurrentSessionExpired=Boolean(!sessionInfo.expiresAt||Date.now()>sessionInfo.expiresAt);return isCurrentSessionExpired||isCutOffTimeExceeded(sessionInfo);};/**
2042
+ * A function to generate session id
2043
+ * @returns number
2044
+ */var generateSessionId=function generateSessionId(){return Date.now();};/**
2045
+ * Function to validate user provided sessionId
2046
+ * @param {number} sessionId
2047
+ * @param logger logger
2048
+ * @returns
2049
+ */var isManualSessionIdValid=function isManualSessionIdValid(sessionId,logger){if(!sessionId||!isPositiveInteger(sessionId)||!hasMinLength(MIN_SESSION_ID_LENGTH,sessionId)){logger.warn(INVALID_SESSION_ID_WARNING(USER_SESSION_MANAGER,sessionId,MIN_SESSION_ID_LENGTH));return false;}return true;};var getCutOffExpirationTimestamp=function getCutOffExpirationTimestamp(cutOff){var _cutOff$expiresAt;if(!(cutOff!==null&&cutOff!==void 0&&cutOff.enabled)){return undefined;}return (_cutOff$expiresAt=cutOff.expiresAt)!==null&&_cutOff$expiresAt!==void 0?_cutOff$expiresAt:isPositiveInteger(cutOff.duration)?Date.now()+cutOff.duration:undefined;};/**
2050
+ * A function to generate new auto tracking session
2051
+ * @param sessionInfo session info
2052
+ * @returns SessionInfo
2053
+ */var generateAutoTrackingSession=function generateAutoTrackingSession(sessionInfo){var timeout=sessionInfo.timeout,cutOff=sessionInfo.cutOff;var timestamp=Date.now();return _objectSpread2({id:timestamp,// set the current timestamp
2054
+ expiresAt:timestamp+timeout,// set the expiry time of the session
2055
+ timeout:timeout,autoTrack:true},cutOff&&{cutOff:cutOff});};/**
2056
+ * A function to generate new manual tracking session
2057
+ * @param id Provided sessionId
2058
+ * @param logger Logger module
2059
+ * @returns SessionInfo
2060
+ */var generateManualTrackingSession=function generateManualTrackingSession(id,logger){var sessionId=isManualSessionIdValid(id,logger)?id:generateSessionId();return {id:sessionId,sessionStart:undefined,manualTrack:true};};var isStorageTypeValidForStoringData=function isStorageTypeValidForStoringData(storageType){return Boolean(storageType===COOKIE_STORAGE||storageType===LOCAL_STORAGE||storageType===SESSION_STORAGE||storageType===MEMORY_STORAGE);};/**
2061
+ * Generate a new anonymousId
2062
+ * @returns string anonymousID
2063
+ */var generateAnonymousId=function generateAnonymousId(){return generateUUID();};var getFinalResetOptions=function getFinalResetOptions(options){// Legacy behavior: toggle only anonymousId without mutating defaults
2064
+ if(isBoolean(options)){var entries=DEFAULT_RESET_OPTIONS.entries,rest=_objectWithoutProperties(DEFAULT_RESET_OPTIONS,_excluded);return _objectSpread2(_objectSpread2({},rest),{},{entries:_objectSpread2(_objectSpread2({},entries),{},{anonymousId:options})});}// Override any defaults with the user provided options
2065
+ if(isObjectLiteralAndNotNull(options)&&isObjectLiteralAndNotNull(options.entries)){return mergeDeepRight(DEFAULT_RESET_OPTIONS,options);}return _objectSpread2({},DEFAULT_RESET_OPTIONS);};
2066
+
2067
+ /**
2068
+ * To get the page properties for context object
2069
+ * @param pageProps Page properties
2070
+ * @returns page properties object for context
2071
+ */var getContextPageProperties=function getContextPageProperties(pageProps){// Need to get updated page details on each event as an event to notify on SPA URL changes does not seem to exist
2072
+ var curPageProps=getDefaultPageProperties();var ctxPageProps={};Object.keys(curPageProps).forEach(function(key){ctxPageProps[key]=(pageProps===null||pageProps===void 0?void 0:pageProps[key])||curPageProps[key];});ctxPageProps.initial_referrer=(pageProps===null||pageProps===void 0?void 0:pageProps.initial_referrer)||state.session.initialReferrer.value;ctxPageProps.initial_referring_domain=(pageProps===null||pageProps===void 0?void 0:pageProps.initial_referring_domain)||state.session.initialReferringDomain.value;return ctxPageProps;};/**
2073
+ * Add any missing default page properties using values from options and defaults
2074
+ * @param properties Input page properties
2075
+ * @param options API options
2076
+ */var getUpdatedPageProperties=function getUpdatedPageProperties(properties,options){var optionsPageProps=(options===null||options===void 0?void 0:options.page)||{};var pageProps=properties;// Need to get updated page details on each event as an event to notify on SPA URL changes does not seem to exist
2077
+ var curPageProps=getDefaultPageProperties();Object.keys(curPageProps).forEach(function(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;};/**
2078
+ * Utility to check for reserved keys in the input object
2079
+ * @param obj Generic object
2080
+ * @param parentKeyPath Object's parent key path
2081
+ * @param logger Logger instance
2082
+ */var checkForReservedElementsInObject=function checkForReservedElementsInObject(obj,parentKeyPath,logger){if(isObjectLiteralAndNotNull(obj)){Object.keys(obj).forEach(function(property){if(RESERVED_ELEMENTS.includes(property)||RESERVED_ELEMENTS.includes(property.toLowerCase())){logger.warn(RESERVED_KEYWORD_WARNING(EVENT_MANAGER,property,parentKeyPath,RESERVED_ELEMENTS));}});}};/**
2083
+ * Checks for reserved keys in traits, properties, and contextual traits
2084
+ * @param rudderEvent Generated rudder event
2085
+ * @param logger Logger instance
2086
+ */var checkForReservedElements=function checkForReservedElements(rudderEvent,logger){// properties, traits, contextualTraits are either undefined or object
2087
+ var properties=rudderEvent.properties,traits=rudderEvent.traits,context=rudderEvent.context;var contextualTraits=context.traits;checkForReservedElementsInObject(properties,'properties',logger);checkForReservedElementsInObject(traits,'traits',logger);checkForReservedElementsInObject(contextualTraits,'context.traits',logger);};/**
2088
+ * Overrides the top-level event properties with data from API options
2089
+ * @param rudderEvent Generated rudder event
2090
+ * @param options API options
2091
+ */var updateTopLevelEventElements=function updateTopLevelEventElements(rudderEvent,options){if(options.anonymousId&&isString(options.anonymousId)){// eslint-disable-next-line no-param-reassign
2092
+ rudderEvent.anonymousId=options.anonymousId;}if(isNonEmptyObject(options.integrations)){// eslint-disable-next-line no-param-reassign
2093
+ rudderEvent.integrations=options.integrations;}if(options.originalTimestamp&&isString(options.originalTimestamp)){// eslint-disable-next-line no-param-reassign
2094
+ rudderEvent.originalTimestamp=options.originalTimestamp;}};/**
2095
+ * To merge the contextual information in API options with existing data
2096
+ * @param rudderContext Generated rudder event
2097
+ * @param options API options
2098
+ * @param logger Logger instance
2099
+ */var getMergedContext=function getMergedContext(rudderContext,options,logger){var context=rudderContext;Object.keys(options).forEach(function(key){if(!TOP_LEVEL_ELEMENTS.includes(key)&&!CONTEXT_RESERVED_ELEMENTS.includes(key)){if(key!=='context'){context=mergeDeepRight(context,_defineProperty({},key,options[key]));}else if(!isUndefined(options[key])&&isObjectLiteralAndNotNull(options[key])){var tempContext={};Object.keys(options[key]).forEach(function(e){if(!CONTEXT_RESERVED_ELEMENTS.includes(e)){tempContext[e]=options[key][e];}});context=mergeDeepRight(context,_objectSpread2({},tempContext));}else {logger.warn(INVALID_CONTEXT_OBJECT_WARNING(EVENT_MANAGER));}}});return context;};/**
2100
+ * Updates rudder event object with data from the API options
2101
+ * @param rudderEvent Generated rudder event
2102
+ * @param options API options
2103
+ */var processOptions=function processOptions(rudderEvent,options,logger){// Only allow object type for options
2104
+ if(isObjectLiteralAndNotNull(options)){updateTopLevelEventElements(rudderEvent,options);// eslint-disable-next-line no-param-reassign
2105
+ rudderEvent.context=getMergedContext(rudderEvent.context,options,logger);}};/**
2106
+ * Returns the final integrations config for the event based on the global config and event's config
2107
+ * @param integrationsConfig Event's integrations config
2108
+ * @returns Final integrations config
2109
+ */var getEventIntegrationsConfig=function getEventIntegrationsConfig(integrationsConfig){var finalIntgConfig;if(state.loadOptions.value.useGlobalIntegrationsConfigInEvents){var _state$consents$postC;// Prefer the integrations object from the consent API response over the load API integrations object
2110
+ finalIntgConfig=(_state$consents$postC=state.consents.postConsent.value.integrations)!==null&&_state$consents$postC!==void 0?_state$consents$postC:state.nativeDestinations.loadOnlyIntegrations.value;}else if(integrationsConfig){finalIntgConfig=integrationsConfig;}else {finalIntgConfig=DEFAULT_INTEGRATIONS_CONFIG;}return clone(finalIntgConfig);};/**
2111
+ * Enrich the base event object with data from state and the API options
2112
+ * @param rudderEvent RudderEvent object
2113
+ * @param options API options
2114
+ * @param pageProps Page properties
2115
+ * @param logger logger
2116
+ * @returns Enriched RudderEvent object
2117
+ */var getEnrichedEvent=function getEnrichedEvent(rudderEvent,options,pageProps,logger){var _state$storage$entrie;var commonEventData={channel:CHANNEL,context:_objectSpread2(_objectSpread2({traits:clone(state.session.userTraits.value),sessionId:state.session.sessionInfo.value.id||undefined,sessionStart:state.session.sessionInfo.value.sessionStart||undefined},state.consents.enabled.value&&{consentManagement:{deniedConsentIds:clone(state.consents.data.value.deniedConsentIds),allowedConsentIds:clone(state.consents.data.value.allowedConsentIds),provider:state.consents.provider.value,resolutionStrategy:state.consents.resolutionStrategy.value}}),{},{'ua-ch':state.context['ua-ch'].value,app:state.context.app.value,library:state.context.library.value,userAgent:state.context.userAgent.value,os:state.context.os.value,locale:state.context.locale.value,screen:state.context.screen.value,campaign:extractUTMParameters(globalThis.location.href),page:getContextPageProperties(pageProps),timezone:state.context.timezone.value},state.autoTrack.enabled.value&&{autoTrack:_objectSpread2({},state.autoTrack.pageLifecycle.enabled.value&&{page:{pageViewId:state.autoTrack.pageLifecycle.pageViewId.value}})}),originalTimestamp:getCurrentTimeFormatted(),messageId:generateUUID(),userId:rudderEvent.userId||state.session.userId.value};if(!isStorageTypeValidForStoringData((_state$storage$entrie=state.storage.entries.value.anonymousId)===null||_state$storage$entrie===void 0?void 0:_state$storage$entrie.type)){// Generate new anonymous id for each request
2118
+ commonEventData.anonymousId=generateAnonymousId();}else {// Type casting to string as the user session manager will take care of initializing the value
2119
+ commonEventData.anonymousId=state.session.anonymousId.value;}// set truly anonymous tracking flag
2120
+ if(state.storage.trulyAnonymousTracking.value){commonEventData.context.trulyAnonymousTracking=true;}if(rudderEvent.type==='identify'){var _state$storage$entrie2;commonEventData.context.traits=((_state$storage$entrie2=state.storage.entries.value.userTraits)===null||_state$storage$entrie2===void 0?void 0:_state$storage$entrie2.type)!==NO_STORAGE?clone(state.session.userTraits.value):rudderEvent.context.traits;}if(rudderEvent.type==='group'){if(rudderEvent.groupId||state.session.groupId.value){commonEventData.groupId=rudderEvent.groupId||state.session.groupId.value;}if(rudderEvent.traits||state.session.groupTraits.value){var _state$storage$entrie3;commonEventData.traits=((_state$storage$entrie3=state.storage.entries.value.groupTraits)===null||_state$storage$entrie3===void 0?void 0:_state$storage$entrie3.type)!==NO_STORAGE?clone(state.session.groupTraits.value):rudderEvent.traits;}}var processedEvent=mergeDeepRight(rudderEvent,commonEventData);// Set the default values for the event properties
2121
+ // matching with v1.1 payload
2122
+ if(processedEvent.event===undefined){processedEvent.event=null;}if(processedEvent.properties===undefined){processedEvent.properties=null;}processOptions(processedEvent,options,logger);checkForReservedElements(processedEvent,logger);// Update the integrations config for the event
2123
+ processedEvent.integrations=getEventIntegrationsConfig(processedEvent.integrations);return processedEvent;};
2124
+
2125
+ var RudderEventFactory=/*#__PURE__*/function(){function RudderEventFactory(logger){_classCallCheck(this,RudderEventFactory);this.logger=logger;}/**
2126
+ * Generate a 'page' event based on the user-input fields
2127
+ * @param category Page's category
2128
+ * @param name Page name
2129
+ * @param properties Page properties
2130
+ * @param options API options
2131
+ */return _createClass(RudderEventFactory,[{key:"generatePageEvent",value:function generatePageEvent(category,name,properties,options){var props=properties!==null&&properties!==void 0?properties:{};props=getUpdatedPageProperties(props,options);var pageEvent={properties:props,name:name,category:category,type:'page'};return getEnrichedEvent(pageEvent,options,props,this.logger);}/**
2132
+ * Generate a 'track' event based on the user-input fields
2133
+ * @param event The event name
2134
+ * @param properties Event properties
2135
+ * @param options API options
2136
+ */},{key:"generateTrackEvent",value:function generateTrackEvent(event,properties,options){var trackEvent={properties:properties,event:event,type:'track'};return getEnrichedEvent(trackEvent,options,undefined,this.logger);}/**
2137
+ * Generate an 'identify' event based on the user-input fields
2138
+ * @param userId New user ID
2139
+ * @param traits new traits
2140
+ * @param options API options
2141
+ */},{key:"generateIdentifyEvent",value:function generateIdentifyEvent(userId,traits,options){var identifyEvent={userId:userId,type:'identify',context:{traits:traits}};return getEnrichedEvent(identifyEvent,options,undefined,this.logger);}/**
2142
+ * Generate an 'alias' event based on the user-input fields
2143
+ * @param to New user ID
2144
+ * @param from Old user ID
2145
+ * @param options API options
2146
+ */},{key:"generateAliasEvent",value:function generateAliasEvent(to,from,options){var aliasEvent={previousId:from,type:'alias'};var enrichedEvent=getEnrichedEvent(aliasEvent,options,undefined,this.logger);// override the User ID from the API inputs
2147
+ enrichedEvent.userId=to!==null&&to!==void 0?to:enrichedEvent.userId;return enrichedEvent;}/**
2148
+ * Generate a 'group' event based on the user-input fields
2149
+ * @param groupId New group ID
2150
+ * @param traits new group traits
2151
+ * @param options API options
2152
+ */},{key:"generateGroupEvent",value:function generateGroupEvent(groupId,traits,options){var groupEvent={type:'group'};if(groupId){groupEvent.groupId=groupId;}if(traits){groupEvent.traits=traits;}return getEnrichedEvent(groupEvent,options,undefined,this.logger);}/**
2153
+ * Generates a new RudderEvent object based on the user-input fields
2154
+ * @param event API event parameters object
2155
+ * @returns A RudderEvent object
2156
+ */},{key:"create",value:function create(event){var eventObj;switch(event.type){case 'page':eventObj=this.generatePageEvent(event.category,event.name,event.properties,event.options);break;case 'track':eventObj=this.generateTrackEvent(event.name,event.properties,event.options);break;case 'identify':eventObj=this.generateIdentifyEvent(event.userId,event.traits,event.options);break;case 'alias':eventObj=this.generateAliasEvent(event.to,event.from,event.options);break;case 'group':default:eventObj=this.generateGroupEvent(event.groupId,event.traits,event.options);break;}return eventObj;}}]);}();
2157
+
2158
+ /**
2159
+ * A service to generate valid event payloads and queue them for processing
2160
+ */var EventManager=/*#__PURE__*/function(){/**
2161
+ *
2162
+ * @param eventRepository Event repository instance
2163
+ * @param userSessionManager UserSession Manager instance
2164
+ * @param errorHandler Error handler object
2165
+ * @param logger Logger object
2166
+ */function EventManager(eventRepository,userSessionManager,errorHandler,logger){_classCallCheck(this,EventManager);this.eventRepository=eventRepository;this.userSessionManager=userSessionManager;this.errorHandler=errorHandler;this.logger=logger;this.eventFactory=new RudderEventFactory(this.logger);}/**
2167
+ * Initializes the event manager
2168
+ */return _createClass(EventManager,[{key:"init",value:function init(){this.eventRepository.init();}},{key:"resume",value:function resume(){this.eventRepository.resume();}/**
2169
+ * Consumes a new incoming event
2170
+ * @param event Incoming event data
2171
+ */},{key:"addEvent",value:function addEvent(event){this.userSessionManager.refreshSession();var rudderEvent=this.eventFactory.create(event);this.eventRepository.enqueue(rudderEvent,event.callback);}}]);}();
2172
+
2173
+ var UserSessionManager=/*#__PURE__*/function(){/**
2174
+ * Tracks whether a server-side cookie setting request is in progress or not.
2175
+ */function UserSessionManager(pluginsManager,storeManager,httpClient,errorHandler,logger){_classCallCheck(this,UserSessionManager);this.storeManager=storeManager;this.pluginsManager=pluginsManager;this.logger=logger;this.errorHandler=errorHandler;this.httpClient=httpClient;this.onError=this.onError.bind(this);this.serverSideCookieDebounceFuncs={};this.serverSideCookiesRequestInProgress={};}/**
2176
+ * Initialize User session with values from storage
2177
+ */return _createClass(UserSessionManager,[{key:"init",value:function init(){this.syncStorageDataToState();// Register the effect to sync with storage
2178
+ this.registerEffects();}},{key:"syncStorageDataToState",value:function syncStorageDataToState(){this.migrateStorageIfNeeded();this.migrateDataFromPreviousStorage();// get the values from storage and set it again
2179
+ this.setUserId(this.getUserId());this.setUserTraits(this.getUserTraits());this.setGroupId(this.getGroupId());this.setGroupTraits(this.getGroupTraits());var _state$loadOptions$va=state.loadOptions.value,externalAnonymousIdCookieName=_state$loadOptions$va.externalAnonymousIdCookieName,anonymousIdOptions=_state$loadOptions$va.anonymousIdOptions;var externalAnonymousId;if(isDefinedAndNotNull(externalAnonymousIdCookieName)&&typeof externalAnonymousIdCookieName==='string'){externalAnonymousId=this.getExternalAnonymousIdByCookieName(externalAnonymousIdCookieName);}this.setAnonymousId(externalAnonymousId!==null&&externalAnonymousId!==void 0?externalAnonymousId:this.getAnonymousId(anonymousIdOptions));this.setAuthToken(this.getAuthToken());this.setInitialReferrerInfo();this.configureSessionTracking();}},{key:"configureSessionTracking",value:function configureSessionTracking(){var sessionInfo;if(this.isPersistenceEnabledForStorageEntry('sessionInfo')){var _this$getSessionInfo,_configuredSessionTra;var configuredSessionTrackingInfo=this.getConfiguredSessionTrackingInfo();var initialSessionInfo=(_this$getSessionInfo=this.getSessionInfo())!==null&&_this$getSessionInfo!==void 0?_this$getSessionInfo:DEFAULT_USER_SESSION_VALUES.sessionInfo;// Merge the session info from the storage and the configuration
2180
+ sessionInfo={// If manualTrack is set to true in the storage, then do not enable auto tracking even if configured.
2181
+ // Once manual tracking ends (endSession is called), auto tracking will be enabled in the next SDK run.
2182
+ autoTrack:configuredSessionTrackingInfo.autoTrack&&initialSessionInfo.manualTrack!==true,timeout:configuredSessionTrackingInfo.timeout,manualTrack:initialSessionInfo.manualTrack,expiresAt:initialSessionInfo.expiresAt,id:initialSessionInfo.id,sessionStart:initialSessionInfo.sessionStart};// If both autoTrack and manualTrack are disabled, reset the session info to default values
2183
+ if(!sessionInfo.autoTrack&&sessionInfo.manualTrack!==true){sessionInfo=DEFAULT_USER_SESSION_VALUES.sessionInfo;}else if(((_configuredSessionTra=configuredSessionTrackingInfo.cutOff)===null||_configuredSessionTra===void 0?void 0:_configuredSessionTra.enabled)===true){var _initialSessionInfo$c;sessionInfo.cutOff={enabled:true,duration:configuredSessionTrackingInfo.cutOff.duration,expiresAt:(_initialSessionInfo$c=initialSessionInfo.cutOff)===null||_initialSessionInfo$c===void 0?void 0:_initialSessionInfo$c.expiresAt};}}else {sessionInfo=DEFAULT_USER_SESSION_VALUES.sessionInfo;}state.session.sessionInfo.value=sessionInfo;// If auto session tracking is enabled start the session tracking
2184
+ if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking(state.session.sessionInfo.value);}}},{key:"setInitialReferrerInfo",value:function setInitialReferrerInfo(){var persistedInitialReferrer=this.getInitialReferrer();var persistedInitialReferringDomain=this.getInitialReferringDomain();if(persistedInitialReferrer&&persistedInitialReferringDomain){this.setInitialReferrer(persistedInitialReferrer);this.setInitialReferringDomain(persistedInitialReferringDomain);}else {var initialReferrer=persistedInitialReferrer||getReferrer();this.setInitialReferrer(initialReferrer);this.setInitialReferringDomain(getReferringDomain(initialReferrer));}}},{key:"isPersistenceEnabledForStorageEntry",value:function isPersistenceEnabledForStorageEntry(entryName){var _state$storage$entrie;return isStorageTypeValidForStoringData((_state$storage$entrie=state.storage.entries.value[entryName])===null||_state$storage$entrie===void 0?void 0:_state$storage$entrie.type);}},{key:"migrateDataFromPreviousStorage",value:function migrateDataFromPreviousStorage(){var _this=this;var entries=state.storage.entries.value;var storageTypesForMigration=[COOKIE_STORAGE,LOCAL_STORAGE,SESSION_STORAGE];Object.keys(entries).forEach(function(entry){var _entries$key,_this$storeManager;var key=entry;var currentStorage=(_entries$key=entries[key])===null||_entries$key===void 0?void 0:_entries$key.type;var curStore=(_this$storeManager=_this.storeManager)===null||_this$storeManager===void 0?void 0:_this$storeManager.getStore(storageClientDataStoreNameMap[currentStorage]);if(curStore){storageTypesForMigration.forEach(function(storage){var _this$storeManager2;var store=(_this$storeManager2=_this.storeManager)===null||_this$storeManager2===void 0?void 0:_this$storeManager2.getStore(storageClientDataStoreNameMap[storage]);if(store&&storage!==currentStorage){var value=store.get(COOKIE_KEYS[key]);if(isDefinedNotNullAndNotEmptyString(value)){curStore.set(COOKIE_KEYS[key],value);}store.remove(COOKIE_KEYS[key]);}});}});}},{key:"migrateStorageIfNeeded",value:function migrateStorageIfNeeded(stores,keys){var _this2=this;if(!state.storage.migrate.value){return;}var storesToMigrate=stores!==null&&stores!==void 0?stores:[];if(storesToMigrate.length===0){var persistentStoreNames=[CLIENT_DATA_STORE_COOKIE,CLIENT_DATA_STORE_LS,CLIENT_DATA_STORE_SESSION];persistentStoreNames.forEach(function(storeName){var _this2$storeManager;var store=(_this2$storeManager=_this2.storeManager)===null||_this2$storeManager===void 0?void 0:_this2$storeManager.getStore(storeName);if(store){storesToMigrate.push(store);}});}var keysToMigrate=keys!==null&&keys!==void 0?keys:Object.keys(COOKIE_KEYS);keysToMigrate.forEach(function(storageKey){var storageEntry=COOKIE_KEYS[storageKey];storesToMigrate.forEach(function(store){var _this2$pluginsManager;var migratedVal=(_this2$pluginsManager=_this2.pluginsManager)===null||_this2$pluginsManager===void 0?void 0:_this2$pluginsManager.invokeSingle('storage.migrate',storageEntry,store.engine,_this2.errorHandler,_this2.logger);// Skip setting the value if it is null or undefined
2185
+ // as those values indicate there is no need for migration or
2186
+ // migration failed
2187
+ if(!isNullOrUndefined(migratedVal)){store.set(storageEntry,migratedVal);}});});}},{key:"getConfiguredSessionTrackingInfo",value:function getConfiguredSessionTrackingInfo(){var _state$loadOptions$va2;var autoTrack=state.loadOptions.value.sessions.autoTrack!==false;// Do not validate any further if autoTrack is disabled
2188
+ if(!autoTrack){return {autoTrack:autoTrack};}var timeout;var configuredSessionTimeout=(_state$loadOptions$va2=state.loadOptions.value.sessions)===null||_state$loadOptions$va2===void 0?void 0:_state$loadOptions$va2.timeout;if(!isPositiveInteger(configuredSessionTimeout)){this.logger.warn(TIMEOUT_NOT_NUMBER_WARNING(USER_SESSION_MANAGER,configuredSessionTimeout,DEFAULT_SESSION_TIMEOUT_MS));timeout=DEFAULT_SESSION_TIMEOUT_MS;}else {timeout=configuredSessionTimeout;}if(timeout===0){this.logger.warn(TIMEOUT_ZERO_WARNING(USER_SESSION_MANAGER));autoTrack=false;}// In case user provides a timeout value greater than 0 but less than 10 seconds SDK will show a warning
2189
+ // and will proceed with it
2190
+ if(timeout>0&&timeout<MIN_SESSION_TIMEOUT_MS){this.logger.warn(TIMEOUT_NOT_RECOMMENDED_WARNING(USER_SESSION_MANAGER,timeout,MIN_SESSION_TIMEOUT_MS));}var cutOff=this.getCutOffInfo(timeout);return {timeout:timeout,autoTrack:autoTrack,cutOff:cutOff};}},{key:"getCutOffInfo",value:function getCutOffInfo(sessionTimeout){var cutOff=state.loadOptions.value.sessions.cutOff;var cutOffDuration;var cutOffEnabled=false;if(cutOff.enabled===true){cutOffDuration=cutOff.duration;cutOffEnabled=true;if(!isPositiveInteger(cutOffDuration)){this.logger.warn(CUT_OFF_DURATION_NOT_NUMBER_WARNING(USER_SESSION_MANAGER,cutOffDuration,DEFAULT_SESSION_CUT_OFF_DURATION_MS));// Use the default value for cut off duration
2191
+ cutOffDuration=DEFAULT_SESSION_CUT_OFF_DURATION_MS;}else if(cutOffDuration<sessionTimeout){this.logger.warn(CUT_OFF_DURATION_LESS_THAN_TIMEOUT_WARNING(USER_SESSION_MANAGER,cutOffDuration,sessionTimeout));cutOffEnabled=false;}}return {enabled:cutOffEnabled,duration:cutOffDuration};}/**
2192
+ * Handles error
2193
+ * @param error The error object
2194
+ */},{key:"onError",value:function onError(error,customMessage,groupingHash){this.errorHandler.onError({error:error,context:USER_SESSION_MANAGER,customMessage:customMessage,groupingHash:groupingHash});}/**
2195
+ * A function to encrypt the cookie value and return the encrypted data
2196
+ * @param cookiesData
2197
+ * @param store
2198
+ * @returns
2199
+ */},{key:"getEncryptedCookieData",value:function getEncryptedCookieData(cookiesData,store){var _this3=this;var encryptedCookieData=[];cookiesData.forEach(function(cData){var encryptedValue=store===null||store===void 0?void 0:store.encrypt(stringifyWithoutCircular(cData.value,false,[],_this3.logger));if(isDefinedAndNotNull(encryptedValue)){encryptedCookieData.push({name:cData.name,value:encryptedValue});}});return encryptedCookieData;}/**
2200
+ * A function that makes request to data service to set the cookie
2201
+ * @param encryptedCookieData
2202
+ * @param callback
2203
+ */},{key:"makeRequestToSetCookie",value:function makeRequestToSetCookie(encryptedCookieData,callback){var _this$httpClient,_state$source$value,_state$storage$cookie,_state$storage$cookie2,_state$storage$cookie3,_state$storage$cookie4,_state$storage$cookie5,_state$storage$cookie6;(_this$httpClient=this.httpClient)===null||_this$httpClient===void 0||_this$httpClient.getAsyncData({url:state.serverCookies.dataServiceUrl.value,options:{method:'POST',data:stringifyWithoutCircular({reqType:'setCookies',workspaceId:(_state$source$value=state.source.value)===null||_state$source$value===void 0?void 0:_state$source$value.workspaceId,data:{options:{maxAge:(_state$storage$cookie=state.storage.cookie.value)===null||_state$storage$cookie===void 0?void 0:_state$storage$cookie.maxage,path:(_state$storage$cookie2=state.storage.cookie.value)===null||_state$storage$cookie2===void 0?void 0:_state$storage$cookie2.path,domain:(_state$storage$cookie3=state.storage.cookie.value)===null||_state$storage$cookie3===void 0?void 0:_state$storage$cookie3.domain,sameSite:(_state$storage$cookie4=state.storage.cookie.value)===null||_state$storage$cookie4===void 0?void 0:_state$storage$cookie4.samesite,secure:(_state$storage$cookie5=state.storage.cookie.value)===null||_state$storage$cookie5===void 0?void 0:_state$storage$cookie5.secure,expires:(_state$storage$cookie6=state.storage.cookie.value)===null||_state$storage$cookie6===void 0?void 0:_state$storage$cookie6.expires},cookies:encryptedCookieData}}),sendRawData:true,withCredentials:true},isRawResponse:true,callback:callback});}/**
2204
+ * A function to make an external request to set the cookie from server side
2205
+ * @param sessionToCookiesMap map of session key to cookie name
2206
+ * @param cb callback function to be called when the cookie is set
2207
+ * @param store store to be used to get the cookie value
2208
+ */},{key:"setServerSideCookies",value:function setServerSideCookies(sessionToCookiesMap,cb,store){var _this4=this;// Retrieve the cookie value from the state
2209
+ var sessionKeys=Object.keys(sessionToCookiesMap);var getCurrentCookieValuesFromState=function getCurrentCookieValuesFromState(){return sessionKeys.map(function(sessionKey){return {name:sessionToCookiesMap[sessionKey].name,value:state.session[sessionKey].value};});};// Preserve the current cookie values
2210
+ var originalCookieValues={};sessionKeys.forEach(function(sessionKey){originalCookieValues[sessionToCookiesMap[sessionKey].name]=store===null||store===void 0?void 0:store.get(sessionToCookiesMap[sessionKey].name);});var clearInProgressFlags=function clearInProgressFlags(){sessionKeys.forEach(function(sessionKey){_this4.serverSideCookiesRequestInProgress[sessionKey]=false;});};var setCookiesClientSide=function setCookiesClientSide(){getCurrentCookieValuesFromState().forEach(function(each){if(cb){cb(each.name,each.value);}});};try{var expectedCookieValues={};sessionKeys.forEach(function(sessionKey){expectedCookieValues[sessionToCookiesMap[sessionKey].name]=state.session[sessionKey].value;});// encrypt cookies values
2211
+ var encryptedCookieData=this.getEncryptedCookieData(getCurrentCookieValuesFromState(),store);if(encryptedCookieData.length>0){// make request to data service to set the cookie from server side
2212
+ this.makeRequestToSetCookie(encryptedCookieData,function(res,details){var _details$xhr;// Mark the cookie req status as done
2213
+ clearInProgressFlags();if((details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.status)===200){getCurrentCookieValuesFromState().forEach(function(cData){var originalCookieVal=originalCookieValues[cData.name];var currentCookieVal=store===null||store===void 0?void 0:store.get(cData.name);// Check if the expected cookie values are set.
2214
+ if(stringifyWithoutCircular(expectedCookieValues[cData.name],false,[])!==stringifyWithoutCircular(currentCookieVal,false,[])){// It's fine if the values don't match as other active SDK sessions might have updated the cookie values
2215
+ // or other cookie requests might have updated the cookie value.
2216
+ // Log an error only when cookie didn't exist previously and currently also doesn't exist.
2217
+ if(isNull(originalCookieVal)&&isNull(currentCookieVal)){_this4.logger.error(FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(cData.name));}if(cb){cb(cData.name,cData.value);}}});}else {var _details$xhr2;_this4.logger.error(DATA_SERVER_REQUEST_FAIL_ERROR(details===null||details===void 0||(_details$xhr2=details.xhr)===null||_details$xhr2===void 0?void 0:_details$xhr2.status));setCookiesClientSide();}});}else {setCookiesClientSide();// Mark the cookie req status as done
2218
+ clearInProgressFlags();}}catch(e){this.onError(e,FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR,FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR);setCookiesClientSide();// Mark the cookie req status as done
2219
+ clearInProgressFlags();}}/**
2220
+ * A function to sync values in storage
2221
+ * @param sessionKey
2222
+ */},{key:"syncValueToStorage",value:function syncValueToStorage(sessionKey){var _entries$sessionKey,_this5=this;var entries=state.storage.entries.value;var storageType=(_entries$sessionKey=entries[sessionKey])===null||_entries$sessionKey===void 0?void 0:_entries$sessionKey.type;if(isStorageTypeValidForStoringData(storageType)){var _entries$sessionKey2;var curStore=this.storeManager.getStore(storageClientDataStoreNameMap[storageType]);var cookieName=(_entries$sessionKey2=entries[sessionKey])===null||_entries$sessionKey2===void 0?void 0:_entries$sessionKey2.key;var cookieValue=state.session[sessionKey].value;if(cookieValue&&(isString(cookieValue)||isNonEmptyObject(cookieValue))){// if useServerSideCookies load option is set to true
2223
+ // set the cookie from server side
2224
+ if(state.serverCookies.isEnabledServerSideCookies.value&&storageType===COOKIE_STORAGE){// Mark the requests as in progress.
2225
+ this.serverSideCookiesRequestInProgress[sessionKey]=true;if(this.serverSideCookieDebounceFuncs[sessionKey]){globalThis.clearTimeout(this.serverSideCookieDebounceFuncs[sessionKey]);}this.serverSideCookieDebounceFuncs[sessionKey]=globalThis.setTimeout(function(){// Create a map of session key to cookie name
2226
+ var sessionToCookiesMap=_defineProperty({},sessionKey,{name:cookieName});_this5.setServerSideCookies(sessionToCookiesMap,function(cookieName,cookieValue){curStore===null||curStore===void 0||curStore.set(cookieName,cookieValue);},curStore);},SERVER_SIDE_COOKIES_DEBOUNCE_TIME);}else {curStore===null||curStore===void 0||curStore.set(cookieName,cookieValue);}}else {curStore===null||curStore===void 0||curStore.remove(cookieName);}}}/**
2227
+ * Function to update storage whenever state value changes
2228
+ */},{key:"registerEffects",value:function registerEffects(){var _this6=this;// This will work as long as the user session entry key names are same as the state keys
2229
+ USER_SESSION_KEYS.forEach(function(sessionKey){m(function(){_this6.syncValueToStorage(sessionKey);});});}/**
2230
+ * Sets anonymous id in the following precedence:
2231
+ *
2232
+ * 1. anonymousId: Id directly provided to the function.
2233
+ * 2. rudderAmpLinkerParam: value generated from linker query parm (rudderstack)
2234
+ * using parseLinker util.
2235
+ * 3. generateUUID: A new unique id is generated and assigned.
2236
+ */},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){var finalAnonymousId=anonymousId;if(!isString(anonymousId)||!finalAnonymousId){finalAnonymousId=undefined;}if(this.isPersistenceEnabledForStorageEntry('anonymousId')){if(!finalAnonymousId&&rudderAmpLinkerParam){var _this$pluginsManager;var linkerPluginsResult=(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0?void 0:_this$pluginsManager.invokeSingle('userSession.anonymousIdGoogleLinker',rudderAmpLinkerParam);finalAnonymousId=linkerPluginsResult;}finalAnonymousId=finalAnonymousId||generateAnonymousId();}else {finalAnonymousId=DEFAULT_USER_SESSION_VALUES.anonymousId;}state.session.anonymousId.value=finalAnonymousId;}/**
2237
+ * Fetches anonymousId
2238
+ * @param options option to fetch it from external source
2239
+ * @returns anonymousId
2240
+ */},{key:"getAnonymousId",value:function getAnonymousId(options){var _state$storage$entrie2;var storage=(_state$storage$entrie2=state.storage.entries.value.anonymousId)===null||_state$storage$entrie2===void 0?void 0:_state$storage$entrie2.type;if(isStorageTypeValidForStoringData(storage)){var persistedAnonymousId=state.session.anonymousId.value;// If the anonymous ID is the default value, fetch it from storage
2241
+ if(!persistedAnonymousId||persistedAnonymousId===DEFAULT_USER_SESSION_VALUES.anonymousId){persistedAnonymousId=this.getEntryValue('anonymousId');}if(!persistedAnonymousId&&options){var _this$pluginsManager2;// fetch anonymousId from external source
2242
+ var autoCapturedAnonymousId=(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===void 0?void 0:_this$pluginsManager2.invokeSingle('storage.getAnonymousId',getStorageEngine,options);persistedAnonymousId=autoCapturedAnonymousId;}state.session.anonymousId.value=persistedAnonymousId||generateAnonymousId();}return state.session.anonymousId.value;}},{key:"getEntryValue",value:function getEntryValue(sessionKey){var _entries$sessionKey3;var entries=state.storage.entries.value;var storageType=(_entries$sessionKey3=entries[sessionKey])===null||_entries$sessionKey3===void 0?void 0:_entries$sessionKey3.type;if(isStorageTypeValidForStoringData(storageType)){var _this$storeManager3,_entries$sessionKey4,_store$get;var store=(_this$storeManager3=this.storeManager)===null||_this$storeManager3===void 0?void 0:_this$storeManager3.getStore(storageClientDataStoreNameMap[storageType]);// Migrate the storage data before fetching the value
2243
+ // This is needed for entries that are fetched from the storage
2244
+ // during the current session (for example, session info)
2245
+ this.migrateStorageIfNeeded([store],[sessionKey]);var storageKey=(_entries$sessionKey4=entries[sessionKey])===null||_entries$sessionKey4===void 0?void 0:_entries$sessionKey4.key;return (_store$get=store===null||store===void 0?void 0:store.get(storageKey))!==null&&_store$get!==void 0?_store$get:null;}return null;}},{key:"getExternalAnonymousIdByCookieName",value:function getExternalAnonymousIdByCookieName(key){var storageEngine=getStorageEngine(COOKIE_STORAGE);if(storageEngine!==null&&storageEngine!==void 0&&storageEngine.isEnabled){var _storageEngine$getIte;return (_storageEngine$getIte=storageEngine.getItem(key))!==null&&_storageEngine$getIte!==void 0?_storageEngine$getIte:null;}return null;}/**
2246
+ * Fetches the value for a session key. Preferably from storage, if the server-side
2247
+ * cookies request is not in progress. Otherwise, from the state.
2248
+ * @param sessionKey - The session key to fetch the value for
2249
+ * @returns - The value for the session key
2250
+ */},{key:"getUserSessionValue",value:function getUserSessionValue(sessionKey){// If the server-side cookies request is in progress, fetch the value from the state.
2251
+ if(this.serverSideCookiesRequestInProgress[sessionKey]){return state.session[sessionKey].value;}// Otherwise, fetch the value from storage.
2252
+ return this.getEntryValue(sessionKey);}/**
2253
+ * Fetches User Id
2254
+ * @returns
2255
+ */},{key:"getUserId",value:function getUserId(){return this.getUserSessionValue('userId');}/**
2256
+ * Fetches User Traits
2257
+ * @returns
2258
+ */},{key:"getUserTraits",value:function getUserTraits(){return this.getUserSessionValue('userTraits');}/**
2259
+ * Fetches Group Id
2260
+ * @returns
2261
+ */},{key:"getGroupId",value:function getGroupId(){return this.getUserSessionValue('groupId');}/**
2262
+ * Fetches Group Traits
2263
+ * @returns
2264
+ */},{key:"getGroupTraits",value:function getGroupTraits(){return this.getUserSessionValue('groupTraits');}/**
2265
+ * Fetches Initial Referrer
2266
+ * @returns
2267
+ */},{key:"getInitialReferrer",value:function getInitialReferrer(){return this.getUserSessionValue('initialReferrer');}/**
2268
+ * Fetches Initial Referring domain
2269
+ * @returns
2270
+ */},{key:"getInitialReferringDomain",value:function getInitialReferringDomain(){return this.getUserSessionValue('initialReferringDomain');}/**
2271
+ * Fetches session tracking information from storage
2272
+ * @returns
2273
+ */},{key:"getSessionInfo",value:function getSessionInfo(){return this.getUserSessionValue('sessionInfo');}/**
2274
+ * Fetches auth token from storage
2275
+ * @returns
2276
+ */},{key:"getAuthToken",value:function getAuthToken(){return this.getUserSessionValue('authToken');}/**
2277
+ * If session is active it returns the sessionId
2278
+ * @returns
2279
+ */},{key:"getSessionId",value:function getSessionId(){var _this$getSessionInfo2;var sessionInfo=(_this$getSessionInfo2=this.getSessionInfo())!==null&&_this$getSessionInfo2!==void 0?_this$getSessionInfo2:DEFAULT_USER_SESSION_VALUES.sessionInfo;if(sessionInfo.autoTrack&&!hasSessionExpired(sessionInfo)||sessionInfo.manualTrack){var _sessionInfo$id;return (_sessionInfo$id=sessionInfo.id)!==null&&_sessionInfo$id!==void 0?_sessionInfo$id:null;}return null;}/**
2280
+ * A function to keep the session information up to date in the state
2281
+ * before using it for building event payloads.
2282
+ */},{key:"refreshSession",value:function refreshSession(){var _this$getSessionInfo3;var sessionInfo=(_this$getSessionInfo3=this.getSessionInfo())!==null&&_this$getSessionInfo3!==void 0?_this$getSessionInfo3:DEFAULT_USER_SESSION_VALUES.sessionInfo;if(sessionInfo.autoTrack||sessionInfo.manualTrack){if(sessionInfo.autoTrack){this.startOrRenewAutoTracking(sessionInfo);sessionInfo=state.session.sessionInfo.value;}// Note that if sessionStart is false, then it's an active session.
2283
+ // So, we needn't update the session info.
2284
+ //
2285
+ // For other scenarios,
2286
+ // 1. If sessionStart is undefined, then it's a new session.
2287
+ // Mark it as sessionStart.
2288
+ // 2. If sessionStart is true, then need to flip it for the future events.
2289
+ if(sessionInfo.sessionStart===undefined){sessionInfo=_objectSpread2(_objectSpread2({},sessionInfo),{},{sessionStart:true});}else if(sessionInfo.sessionStart){sessionInfo=_objectSpread2(_objectSpread2({},sessionInfo),{},{sessionStart:false});}}// Always write to state (in-turn to storage) to keep the session info up to date.
2290
+ state.session.sessionInfo.value=sessionInfo;if(state.lifecycle.status.value!=='readyExecuted'){// Force update the storage as the 'effect' blocks are not getting triggered
2291
+ // when processing preload buffered requests
2292
+ this.syncValueToStorage('sessionInfo');}}},{key:"resetAndStartNewSession",value:function resetAndStartNewSession(){var session=state.session;var _session$sessionInfo$=session.sessionInfo.value,manualTrack=_session$sessionInfo$.manualTrack,autoTrack=_session$sessionInfo$.autoTrack,timeout=_session$sessionInfo$.timeout,cutOff=_session$sessionInfo$.cutOff;if(autoTrack){var sessionInfo=_objectSpread2(_objectSpread2({},DEFAULT_USER_SESSION_VALUES.sessionInfo),{},{timeout:timeout});if(cutOff){sessionInfo.cutOff={enabled:cutOff.enabled,duration:cutOff.duration};}session.sessionInfo.value=sessionInfo;this.startOrRenewAutoTracking(session.sessionInfo.value);}else if(manualTrack){this.startManualTrackingInternal();}}/**
2293
+ * Reset state values
2294
+ * @param options options for reset
2295
+ * @returns
2296
+ */},{key:"reset",value:function reset(options){var _this7=this;var session=state.session;var opts=getFinalResetOptions(options);n(function(){Object.keys(DEFAULT_USER_SESSION_VALUES).forEach(function(key){var userSessionKey=key;if(opts.entries[userSessionKey]!==true){return;}switch(key){case 'anonymousId':_this7.setAnonymousId();break;case 'sessionInfo':_this7.resetAndStartNewSession();break;default:session[userSessionKey].value=DEFAULT_USER_SESSION_VALUES[userSessionKey];break;}});});}/**
2297
+ * Set user Id
2298
+ * @param userId
2299
+ */},{key:"setUserId",value:function setUserId(userId){state.session.userId.value=this.isPersistenceEnabledForStorageEntry('userId')&&userId?userId:DEFAULT_USER_SESSION_VALUES.userId;}/**
2300
+ * Set user traits
2301
+ * @param traits
2302
+ */},{key:"setUserTraits",value:function setUserTraits(traits){var _state$session$userTr;state.session.userTraits.value=this.isPersistenceEnabledForStorageEntry('userTraits')&&isObjectLiteralAndNotNull(traits)?mergeDeepRight((_state$session$userTr=state.session.userTraits.value)!==null&&_state$session$userTr!==void 0?_state$session$userTr:DEFAULT_USER_SESSION_VALUES.userTraits,traits):DEFAULT_USER_SESSION_VALUES.userTraits;}/**
2303
+ * Set group Id
2304
+ * @param groupId
2305
+ */},{key:"setGroupId",value:function setGroupId(groupId){state.session.groupId.value=this.isPersistenceEnabledForStorageEntry('groupId')&&groupId?groupId:DEFAULT_USER_SESSION_VALUES.groupId;}/**
2306
+ * Set group traits
2307
+ * @param traits
2308
+ */},{key:"setGroupTraits",value:function setGroupTraits(traits){var _state$session$groupT;state.session.groupTraits.value=this.isPersistenceEnabledForStorageEntry('groupTraits')&&isObjectLiteralAndNotNull(traits)?mergeDeepRight((_state$session$groupT=state.session.groupTraits.value)!==null&&_state$session$groupT!==void 0?_state$session$groupT:DEFAULT_USER_SESSION_VALUES.groupTraits,traits):DEFAULT_USER_SESSION_VALUES.groupTraits;}/**
2309
+ * Set initial referrer
2310
+ * @param referrer
2311
+ */},{key:"setInitialReferrer",value:function setInitialReferrer(referrer){state.session.initialReferrer.value=this.isPersistenceEnabledForStorageEntry('initialReferrer')&&referrer?referrer:DEFAULT_USER_SESSION_VALUES.initialReferrer;}/**
2312
+ * Set initial referring domain
2313
+ * @param {String} referringDomain
2314
+ */},{key:"setInitialReferringDomain",value:function setInitialReferringDomain(referringDomain){state.session.initialReferringDomain.value=this.isPersistenceEnabledForStorageEntry('initialReferringDomain')&&referringDomain?referringDomain:DEFAULT_USER_SESSION_VALUES.initialReferringDomain;}/**
2315
+ * A function to check for existing session details and depending on that create a new session
2316
+ */},{key:"startOrRenewAutoTracking",value:function startOrRenewAutoTracking(sessionInfo){var finalSessionInfo=sessionInfo;if(hasSessionExpired(sessionInfo)){finalSessionInfo=generateAutoTrackingSession(sessionInfo);}else {var timestamp=Date.now();var timeout=sessionInfo.timeout;// Set the expiry time of the session
2317
+ finalSessionInfo.expiresAt=timestamp+timeout;}// Reset cut off expiry timestamp if it is exceeded
2318
+ if(isCutOffTimeExceeded(finalSessionInfo)){finalSessionInfo.cutOff.expiresAt=undefined;}// If cut off is active, set or retain the expiry time
2319
+ if(finalSessionInfo.cutOff){var cutOffExpiresAt=getCutOffExpirationTimestamp(finalSessionInfo.cutOff);finalSessionInfo.cutOff.expiresAt=cutOffExpiresAt;}// Update the session info in the state
2320
+ state.session.sessionInfo.value=finalSessionInfo;}/**
2321
+ * A function method to start a manual session
2322
+ * @param {number} id session identifier
2323
+ * @returns
2324
+ */},{key:"start",value:function start(id){state.session.sessionInfo.value=generateManualTrackingSession(id,this.logger);}/**
2325
+ * An internal function to start manual session
2326
+ */},{key:"startManualTrackingInternal",value:function startManualTrackingInternal(){this.start(Date.now());}/**
2327
+ * A public method to end an ongoing session.
2328
+ */},{key:"end",value:function end(){state.session.sessionInfo.value=DEFAULT_USER_SESSION_VALUES.sessionInfo;}/**
2329
+ * Set auth token
2330
+ * @param userId
2331
+ */},{key:"setAuthToken",value:function setAuthToken(token){state.session.authToken.value=this.isPersistenceEnabledForStorageEntry('authToken')&&token?token:DEFAULT_USER_SESSION_VALUES.authToken;}}]);}();
2332
+
2333
+ /**
2334
+ * Plugins to be loaded in the plugins loadOption is not defined
2335
+ */var allOptionalPlugins=['BeaconQueue','CustomConsentManager','DeviceModeDestinations','DeviceModeTransformation','ExternalAnonymousId','GoogleLinker','IubendaConsentManager','KetchConsentManager','NativeDestinationQueue','OneTrustConsentManager','StorageEncryption','StorageEncryptionLegacy','StorageMigrator','XhrQueue'];// Plugins excluded from lite builds which are also not connected to any SDK configuration options
2336
+ var liteExcludedPlugins=['GoogleLinker'];var defaultOptionalPluginsList=allOptionalPlugins.filter(function(plugin){return !liteExcludedPlugins.includes(plugin);});
2337
+
2338
+ var normalizeLoadOptions=function normalizeLoadOptions(loadOptionsFromState,loadOptions){// TODO: Maybe add warnings for invalid values
2339
+ var normalizedLoadOpts=clone(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){normalizedLoadOpts.setCookieDomain=undefined;}var cookieSameSiteValues=['Strict','Lax','None'];if(!cookieSameSiteValues.includes(normalizedLoadOpts.sameSiteCookie)){normalizedLoadOpts.sameSiteCookie=undefined;}normalizedLoadOpts.secureCookie=getNormalizedBooleanValue(normalizedLoadOpts.secureCookie,loadOptionsFromState.secureCookie);normalizedLoadOpts.sameDomainCookiesOnly=getNormalizedBooleanValue(normalizedLoadOpts.sameDomainCookiesOnly,loadOptionsFromState.sameDomainCookiesOnly);var uaChTrackLevels=['none','default','full'];if(!uaChTrackLevels.includes(normalizedLoadOpts.uaChTrackLevel)){normalizedLoadOpts.uaChTrackLevel=undefined;}normalizedLoadOpts.integrations=getNormalizedObjectValue(normalizedLoadOpts.integrations);if(!Array.isArray(normalizedLoadOpts.plugins)){normalizedLoadOpts.plugins=defaultOptionalPluginsList;}normalizedLoadOpts.useGlobalIntegrationsConfigInEvents=getNormalizedBooleanValue(normalizedLoadOpts.useGlobalIntegrationsConfigInEvents,loadOptionsFromState.useGlobalIntegrationsConfigInEvents);normalizedLoadOpts.bufferDataPlaneEventsUntilReady=getNormalizedBooleanValue(normalizedLoadOpts.bufferDataPlaneEventsUntilReady,loadOptionsFromState.bufferDataPlaneEventsUntilReady);normalizedLoadOpts.sendAdblockPage=getNormalizedBooleanValue(normalizedLoadOpts.sendAdblockPage,loadOptionsFromState.sendAdblockPage);normalizedLoadOpts.useServerSideCookies=getNormalizedBooleanValue(normalizedLoadOpts.useServerSideCookies,loadOptionsFromState.useServerSideCookies);if(!isString(normalizedLoadOpts.dataServiceEndpoint)){normalizedLoadOpts.dataServiceEndpoint=undefined;}normalizedLoadOpts.sendAdblockPageOptions=getNormalizedObjectValue(normalizedLoadOpts.sendAdblockPageOptions);normalizedLoadOpts.loadIntegration=getNormalizedBooleanValue(normalizedLoadOpts.loadIntegration,loadOptionsFromState.loadIntegration);if(!isNonEmptyObject(normalizedLoadOpts.storage)){normalizedLoadOpts.storage=undefined;}else {var _loadOptionsFromState;normalizedLoadOpts.storage.migrate=getNormalizedBooleanValue(normalizedLoadOpts.storage.migrate,(_loadOptionsFromState=loadOptionsFromState.storage)===null||_loadOptionsFromState===void 0?void 0:_loadOptionsFromState.migrate);normalizedLoadOpts.storage.cookie=getNormalizedObjectValue(normalizedLoadOpts.storage.cookie);normalizedLoadOpts.storage.encryption=getNormalizedObjectValue(normalizedLoadOpts.storage.encryption);normalizedLoadOpts.storage=_removeUndefinedAndNullValues(normalizedLoadOpts.storage);}normalizedLoadOpts.destinationsQueueOptions=getNormalizedObjectValue(normalizedLoadOpts.destinationsQueueOptions);normalizedLoadOpts.queueOptions=getNormalizedObjectValue(normalizedLoadOpts.queueOptions);normalizedLoadOpts.lockIntegrationsVersion=getNormalizedBooleanValue(normalizedLoadOpts.lockIntegrationsVersion,loadOptionsFromState.lockIntegrationsVersion);normalizedLoadOpts.lockPluginsVersion=getNormalizedBooleanValue(normalizedLoadOpts.lockPluginsVersion,loadOptionsFromState.lockPluginsVersion);if(!isNumber(normalizedLoadOpts.dataPlaneEventsBufferTimeout)){normalizedLoadOpts.dataPlaneEventsBufferTimeout=undefined;}normalizedLoadOpts.beaconQueueOptions=getNormalizedObjectValue(normalizedLoadOpts.beaconQueueOptions);normalizedLoadOpts.preConsent=getNormalizedObjectValue(normalizedLoadOpts.preConsent);normalizedLoadOpts.sourceConfigurationOverride=getNormalizedObjectValue(normalizedLoadOpts.sourceConfigurationOverride);var mergedLoadOptions=mergeDeepRight(loadOptionsFromState,_removeUndefinedAndNullValues(normalizedLoadOpts));return mergedLoadOptions;};
2340
+
2341
+ var DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';var DESTINATIONS_QUEUE_EXT_POINT_PREFIX='destinationsEventsQueue';var DMT_EXT_POINT_PREFIX='transformEvent';
2342
+
2343
+ /**
2344
+ * Filters and returns the user supplied integrations config that should take preference over the destination specific integrations config
2345
+ * @param eventIntgConfig User supplied integrations config at event level
2346
+ * @param destinationsIntgConfig Cumulative integrations config from all destinations
2347
+ * @returns Filtered user supplied integrations config
2348
+ */var getOverriddenIntegrationOptions=function getOverriddenIntegrationOptions(eventIntgConfig,destinationsIntgConfig){return Object.keys(eventIntgConfig).filter(function(intgName){return eventIntgConfig[intgName]!==true||!destinationsIntgConfig[intgName];}).reduce(function(obj,key){var retVal=clone(obj);retVal[key]=eventIntgConfig[key];return retVal;},{});};/**
2349
+ * Returns the event object with final integrations config
2350
+ * @param event RudderEvent object
2351
+ * @param state Application state
2352
+ * @returns Mutated event with final integrations config
2353
+ */var getFinalEvent=function getFinalEvent(event,state){var finalEvent=clone(event);// Merge the destination specific integrations config with the event's integrations config
2354
+ // In general, the preference is given to the event's integrations config
2355
+ var destinationsIntgConfig=state.nativeDestinations.integrationsConfig.value;var overriddenIntgOpts=getOverriddenIntegrationOptions(event.integrations,destinationsIntgConfig);finalEvent.integrations=mergeDeepRight(destinationsIntgConfig,overriddenIntgOpts);return finalEvent;};var shouldBufferEventsForPreConsent=function shouldBufferEventsForPreConsent(state){var _state$consents$preCo;return state.consents.preConsent.value.enabled&&((_state$consents$preCo=state.consents.preConsent.value.events)===null||_state$consents$preCo===void 0?void 0:_state$consents$preCo.delivery)==='buffer';};
2356
+
2357
+ var safelyInvokeCallback=function safelyInvokeCallback(callback,args,apiName,logger){if(!isDefined(callback)){return;}if(isFunction(callback)){try{callback.apply(void 0,_toConsumableArray(args));}catch(error){logger.error(CALLBACK_INVOKE_ERROR(apiName),error);}}else {logger.error(INVALID_CALLBACK_FN_ERROR(apiName));}};
2358
+
2359
+ /**
2360
+ * Event repository class responsible for queuing events for further processing and delivery
2361
+ */var EventRepository=/*#__PURE__*/function(){/**
2362
+ *
2363
+ * @param pluginsManager Plugins manager instance
2364
+ * @param storeManager Store Manager instance
2365
+ * @param errorHandler Error handler object
2366
+ * @param logger Logger object
2367
+ */function EventRepository(pluginsManager,storeManager,httpClient,errorHandler,logger){_classCallCheck(this,EventRepository);this.pluginsManager=pluginsManager;this.errorHandler=errorHandler;this.httpClient=httpClient;this.logger=logger;this.storeManager=storeManager;}/**
2368
+ * Initializes the event repository
2369
+ */return _createClass(EventRepository,[{key:"init",value:function init(){var _this=this;this.dataplaneEventsQueue=this.pluginsManager.invokeSingle("".concat(DATA_PLANE_QUEUE_EXT_POINT_PREFIX,".init"),state,this.httpClient,this.storeManager,this.errorHandler,this.logger);this.dmtEventsQueue=this.pluginsManager.invokeSingle("".concat(DMT_EXT_POINT_PREFIX,".init"),state,this.pluginsManager,this.httpClient,this.storeManager,this.errorHandler,this.logger);this.destinationsEventsQueue=this.pluginsManager.invokeSingle("".concat(DESTINATIONS_QUEUE_EXT_POINT_PREFIX,".init"),state,this.pluginsManager,this.storeManager,this.dmtEventsQueue,this.errorHandler,this.logger);// Start the queue once the client destinations are ready
2370
+ m(function(){if(state.nativeDestinations.clientDestinationsReady.value===true){var _this$destinationsEve,_this$dmtEventsQueue;(_this$destinationsEve=_this.destinationsEventsQueue)===null||_this$destinationsEve===void 0||_this$destinationsEve.start();(_this$dmtEventsQueue=_this.dmtEventsQueue)===null||_this$dmtEventsQueue===void 0||_this$dmtEventsQueue.start();}});var bufferEventsBeforeConsent=shouldBufferEventsForPreConsent(state);// Start the queue processing only when the destinations are ready or hybrid mode destinations exist
2371
+ // However, events will be enqueued for now.
2372
+ // At the time of processing the events, the integrations config data from destinations
2373
+ // is merged into the event object
2374
+ var timeoutId;m(function(){var _this$dataplaneEvents;var shouldBufferDpEvents=state.loadOptions.value.bufferDataPlaneEventsUntilReady===true&&state.nativeDestinations.clientDestinationsReady.value===false;var hybridDestExist=state.nativeDestinations.activeDestinations.value.some(function(dest){return isHybridModeDestination(dest);});if((hybridDestExist===false||shouldBufferDpEvents===false)&&!bufferEventsBeforeConsent&&((_this$dataplaneEvents=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents===void 0?void 0:_this$dataplaneEvents.scheduleTimeoutActive)!==true){var _this$dataplaneEvents2;globalThis.clearTimeout(timeoutId);(_this$dataplaneEvents2=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents2===void 0||_this$dataplaneEvents2.start();}});// Force start the data plane events queue processing after a timeout
2375
+ if(state.loadOptions.value.bufferDataPlaneEventsUntilReady===true){timeoutId=globalThis.setTimeout(function(){var _this$dataplaneEvents3;if(((_this$dataplaneEvents3=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents3===void 0?void 0:_this$dataplaneEvents3.scheduleTimeoutActive)!==true){var _this$dataplaneEvents4;(_this$dataplaneEvents4=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents4===void 0||_this$dataplaneEvents4.start();}},state.loadOptions.value.dataPlaneEventsBufferTimeout);}}},{key:"resume",value:function resume(){var _this$dataplaneEvents5;if(((_this$dataplaneEvents5=this.dataplaneEventsQueue)===null||_this$dataplaneEvents5===void 0?void 0:_this$dataplaneEvents5.scheduleTimeoutActive)!==true){var _this$dataplaneEvents7;if(state.consents.postConsent.value.discardPreConsentEvents){var _this$dataplaneEvents6,_this$destinationsEve2;(_this$dataplaneEvents6=this.dataplaneEventsQueue)===null||_this$dataplaneEvents6===void 0||_this$dataplaneEvents6.clear();(_this$destinationsEve2=this.destinationsEventsQueue)===null||_this$destinationsEve2===void 0||_this$destinationsEve2.clear();}(_this$dataplaneEvents7=this.dataplaneEventsQueue)===null||_this$dataplaneEvents7===void 0||_this$dataplaneEvents7.start();}}/**
2376
+ * Enqueues the event for processing
2377
+ * @param event RudderEvent object
2378
+ * @param callback API callback function
2379
+ */},{key:"enqueue",value:function enqueue(event,callback){var dpQEvent=getFinalEvent(event,state);this.pluginsManager.invokeSingle("".concat(DATA_PLANE_QUEUE_EXT_POINT_PREFIX,".enqueue"),state,this.dataplaneEventsQueue,dpQEvent,this.errorHandler,this.logger);var dQEvent=clone(event);this.pluginsManager.invokeSingle("".concat(DESTINATIONS_QUEUE_EXT_POINT_PREFIX,".enqueue"),state,this.destinationsEventsQueue,dQEvent,this.errorHandler,this.logger);// Invoke the callback if it exists
2380
+ var apiName="".concat(event.type.charAt(0).toUpperCase()).concat(event.type.slice(1)).concat(API_SUFFIX);safelyInvokeCallback(callback,[dpQEvent],apiName,this.logger);}}]);}();
2381
+
2382
+ var dispatchSDKEvent=function dispatchSDKEvent(event){var customEvent=new CustomEvent(event,{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:true,cancelable:true,composed:true});globalThis.document.dispatchEvent(customEvent);};var isWriteKeyValid=function isWriteKeyValid(writeKey){return isString(writeKey)&&writeKey.trim().length>0;};var isDataPlaneUrlValid=function isDataPlaneUrlValid(dataPlaneUrl){return isValidURL(dataPlaneUrl);};
2383
+
2384
+ /*
2385
+ * Analytics class with lifecycle based on state ad user triggered events
2386
+ */var Analytics=/*#__PURE__*/function(){/**
2387
+ * Initialize services and components or use default ones if singletons
2388
+ */function Analytics(){_classCallCheck(this,Analytics);this.preloadBuffer=new BufferQueue();this.initialized=false;this.errorHandler=defaultErrorHandler;this.logger=defaultLogger;this.externalSrcLoader=new ExternalSrcLoader(this.logger);this.httpClient=defaultHttpClient;this.httpClient.init(this.errorHandler);this.capabilitiesManager=new CapabilitiesManager(this.httpClient,this.errorHandler,this.logger);}/**
2389
+ * Start application lifecycle if not already started
2390
+ */return _createClass(Analytics,[{key:"load",value:function load(writeKey,dataPlaneUrl){var _state$loadOptions$va;var loadOptions=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};if(state.lifecycle.status.value){return;}if(!isWriteKeyValid(writeKey)){this.logger.error(WRITE_KEY_VALIDATION_ERROR(ANALYTICS_CORE,writeKey));return;}if(!isDataPlaneUrlValid(dataPlaneUrl)){this.logger.error(DATA_PLANE_URL_VALIDATION_ERROR(ANALYTICS_CORE,dataPlaneUrl));return;}// Set initial state values
2391
+ n(function(){state.lifecycle.writeKey.value=clone(writeKey);state.lifecycle.dataPlaneUrl.value=clone(dataPlaneUrl);state.loadOptions.value=normalizeLoadOptions(state.loadOptions.value,loadOptions);state.lifecycle.status.value='mounted';});// set log level as early as possible
2392
+ this.logger.setMinLogLevel((_state$loadOptions$va=state.loadOptions.value.logLevel)!==null&&_state$loadOptions$va!==void 0?_state$loadOptions$va:POST_LOAD_LOG_LEVEL);// Expose state to global objects
2393
+ setExposedGlobal('state',state,writeKey);// Configure initial config of any services or components here
2394
+ // State application lifecycle
2395
+ this.startLifecycle();}// Start lifecycle methods
2396
+ /**
2397
+ * Orchestrate the lifecycle of the application phases/status
2398
+ */},{key:"startLifecycle",value:function startLifecycle(){var _this=this;m(function(){try{switch(state.lifecycle.status.value){case 'mounted':_this.onMounted();break;case 'browserCapabilitiesReady':_this.onBrowserCapabilitiesReady();break;case 'configured':_this.onConfigured();break;case 'pluginsLoading':break;case 'pluginsReady':_this.onPluginsReady();break;case 'initialized':_this.onInitialized();break;case 'loaded':_this.onLoaded();break;case 'destinationsLoading':break;case 'destinationsReady':_this.onDestinationsReady();break;case 'ready':_this.onReady();break;case 'readyExecuted':default:break;}}catch(err){var issue='Failed to load the SDK';_this.errorHandler.onError({error:err,context:ANALYTICS_CORE,customMessage:issue,groupingHash:issue});}});}},{key:"onBrowserCapabilitiesReady",value:function onBrowserCapabilitiesReady(){// initialize the preloaded events enqueuing
2399
+ retrievePreloadBufferEvents(this);this.prepareInternalServices();this.loadConfig();}},{key:"onLoaded",value:function onLoaded(){this.processBufferedEvents();// Short-circuit the life cycle and move to the ready state if pre-consent behavior is enabled
2400
+ if(state.consents.preConsent.value.enabled===true){state.lifecycle.status.value='ready';}else {this.loadDestinations();}}/**
2401
+ * Load browser polyfill if required
2402
+ */},{key:"onMounted",value:function onMounted(){this.capabilitiesManager.init();}/**
2403
+ * Enqueue in SDK preload buffer events, used from preloadBuffer component
2404
+ */},{key:"enqueuePreloadBufferEvents",value:function enqueuePreloadBufferEvents(bufferedEvents){var _this2=this;if(Array.isArray(bufferedEvents)){bufferedEvents.forEach(function(bufferedEvent){return _this2.preloadBuffer.enqueue(clone(bufferedEvent));});}}/**
2405
+ * Process the buffer preloaded events by passing their arguments to the respective facade methods
2406
+ */},{key:"processDataInPreloadBuffer",value:function processDataInPreloadBuffer(){while(this.preloadBuffer.size()>0){var eventToProcess=this.preloadBuffer.dequeue();if(eventToProcess){consumePreloadBufferedEvent(_toConsumableArray(eventToProcess),this);}}}},{key:"prepareInternalServices",value:function prepareInternalServices(){this.pluginsManager=new PluginsManager(defaultPluginEngine,this.errorHandler,this.logger);this.storeManager=new StoreManager(this.pluginsManager,this.errorHandler,this.logger);this.configManager=new ConfigManager(this.httpClient,this.errorHandler,this.logger);this.userSessionManager=new UserSessionManager(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger);this.eventRepository=new EventRepository(this.pluginsManager,this.storeManager,this.httpClient,this.errorHandler,this.logger);this.eventManager=new EventManager(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger);}/**
2407
+ * Load configuration
2408
+ */},{key:"loadConfig",value:function loadConfig(){var _this$configManager;if(state.lifecycle.writeKey.value){this.httpClient.setAuthHeader(state.lifecycle.writeKey.value);}(_this$configManager=this.configManager)===null||_this$configManager===void 0||_this$configManager.init();}/**
2409
+ * Initialize the storage and event queue
2410
+ */},{key:"onPluginsReady",value:function onPluginsReady(){var _this$storeManager,_this$userSessionMana,_this$eventManager;// Initialize storage
2411
+ (_this$storeManager=this.storeManager)===null||_this$storeManager===void 0||_this$storeManager.init();(_this$userSessionMana=this.userSessionManager)===null||_this$userSessionMana===void 0||_this$userSessionMana.init();// Initialize the appropriate consent manager plugin
2412
+ if(state.consents.enabled.value&&!state.consents.initialized.value){var _this$pluginsManager;(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0||_this$pluginsManager.invokeSingle("consentManager.init",state,this.logger);if(state.consents.preConsent.value.enabled===false){var _this$pluginsManager2;(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===void 0||_this$pluginsManager2.invokeSingle("consentManager.updateConsentsInfo",state,this.storeManager,this.logger);}}// Initialize event manager
2413
+ (_this$eventManager=this.eventManager)===null||_this$eventManager===void 0||_this$eventManager.init();// Mark the SDK as initialized
2414
+ state.lifecycle.status.value='initialized';}/**
2415
+ * Load plugins
2416
+ */},{key:"onConfigured",value:function onConfigured(){var _this$pluginsManager3;(_this$pluginsManager3=this.pluginsManager)===null||_this$pluginsManager3===void 0||_this$pluginsManager3.init();// TODO: are we going to enable custom plugins to be passed as load options?
2417
+ // registerCustomPlugins(state.loadOptions.value.customPlugins);
2418
+ }/**
2419
+ * Trigger onLoaded callback if any is provided in config & emit initialised event
2420
+ */},{key:"onInitialized",value:function onInitialized(){// Process any preloaded events
2421
+ this.processDataInPreloadBuffer();// Set lifecycle state
2422
+ n(function(){state.lifecycle.loaded.value=true;state.lifecycle.status.value='loaded';});this.initialized=true;// Execute onLoaded callback if provided in load options
2423
+ var onLoadedCallbackFn=state.loadOptions.value.onLoaded;// TODO: we need to avoid passing the window object to the callback function
2424
+ // as this will prevent us from supporting multiple SDK instances in the same page
2425
+ safelyInvokeCallback(onLoadedCallbackFn,[globalThis.rudderanalytics],LOAD_API,this.logger);// Emit an event to use as substitute to the onLoaded callback
2426
+ dispatchSDKEvent('RSA_Initialised');}/**
2427
+ * Emit ready event
2428
+ */// eslint-disable-next-line class-methods-use-this
2429
+ },{key:"onReady",value:function onReady(){var _this3=this;state.lifecycle.status.value='readyExecuted';state.eventBuffer.readyCallbacksArray.value.forEach(function(callback){safelyInvokeCallback(callback,[],READY_API,_this3.logger);});// Emit an event to use as substitute to the ready callback
2430
+ dispatchSDKEvent('RSA_Ready');}/**
2431
+ * Consume preloaded events buffer
2432
+ */},{key:"processBufferedEvents",value:function processBufferedEvents(){// This logic has been intentionally implemented without a simple
2433
+ // for-loop as the individual events that are processed may
2434
+ // add more events to the buffer (this is needed for the consent API)
2435
+ var bufferedEvents=state.eventBuffer.toBeProcessedArray.value;while(bufferedEvents.length>0){var bufferedEvent=bufferedEvents.shift();state.eventBuffer.toBeProcessedArray.value=bufferedEvents;if(bufferedEvent){var methodName=bufferedEvent[0];if(isFunction(this[methodName])){var _ref;// Send additional arg 'true' to indicate that this is a buffered invocation
2436
+ (_ref=this)[methodName].apply(_ref,_toConsumableArray(bufferedEvent.slice(1)).concat([true]));}}bufferedEvents=state.eventBuffer.toBeProcessedArray.value;}}/**
2437
+ * Load device mode destinations
2438
+ */},{key:"loadDestinations",value:function loadDestinations(){var _this$pluginsManager4,_this$pluginsManager5;// If the integrations load is already triggered or completed, skip the rest of the logic
2439
+ if(state.lifecycle.status.value==='destinationsLoading'||state.lifecycle.status.value==='destinationsReady'){return;}// Set in state the desired activeDestinations to inject in DOM
2440
+ (_this$pluginsManager4=this.pluginsManager)===null||_this$pluginsManager4===void 0||_this$pluginsManager4.invokeSingle('nativeDestinations.setActiveDestinations',state,this.pluginsManager,this.errorHandler,this.logger);var totalDestinationsToLoad=state.nativeDestinations.activeDestinations.value.length;if(totalDestinationsToLoad===0){state.lifecycle.status.value='destinationsReady';return;}// Start loading native integration scripts and create instances
2441
+ state.lifecycle.status.value='destinationsLoading';(_this$pluginsManager5=this.pluginsManager)===null||_this$pluginsManager5===void 0||_this$pluginsManager5.invokeSingle('nativeDestinations.load',state,this.externalSrcLoader,this.errorHandler,this.logger);// Progress to next lifecycle phase if all native destinations are initialized or failed
2442
+ m(function(){var areAllDestinationsReady=totalDestinationsToLoad===0||state.nativeDestinations.initializedDestinations.value.length+state.nativeDestinations.failedDestinations.value.length===totalDestinationsToLoad;if(areAllDestinationsReady){n(function(){state.lifecycle.status.value='destinationsReady';state.nativeDestinations.clientDestinationsReady.value=true;});}});}/**
2443
+ * Move to the ready state
2444
+ */// eslint-disable-next-line class-methods-use-this
2445
+ },{key:"onDestinationsReady",value:function onDestinationsReady(){// May be do any destination specific actions here
2446
+ // Mark the ready status if not already done
2447
+ if(state.lifecycle.status.value!=='ready'){n(function(){state.lifecycle.status.value='ready';});}}// End lifecycle methods
2448
+ // Start consumer exposed methods
2449
+ },{key:"ready",value:function ready(callback){var type='ready';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,callback]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));if(!isFunction(callback)){this.logger.error(INVALID_CALLBACK_FN_ERROR(READY_API));return;}/**
2450
+ * If destinations are loaded or no integration is available for loading
2451
+ * execute the callback immediately else push the callbacks to a queue that
2452
+ * will be executed after loading completes
2453
+ */if(state.lifecycle.status.value==='readyExecuted'){safelyInvokeCallback(callback,[],READY_API,this.logger);}else {state.eventBuffer.readyCallbacksArray.value=[].concat(_toConsumableArray(state.eventBuffer.readyCallbacksArray.value),[callback]);}}},{key:"page",value:function page(payload){var _this$eventManager2;var type='page';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;(_this$eventManager2=this.eventManager)===null||_this$eventManager2===void 0||_this$eventManager2.addEvent({type:'page',category:payload.category,name:payload.name,properties:payload.properties,options:payload.options,callback:payload.callback});// TODO: Maybe we should alter the behavior to send the ad-block page event even if the SDK is still loaded. It'll be pushed into the to be processed queue.
2454
+ // Send automatic ad blocked page event if ad-blockers are detected on the page
2455
+ // Check page category to avoid infinite loop
2456
+ if(state.capabilities.isAdBlocked.value===true&&payload.category!==ADBLOCK_PAGE_CATEGORY){this.page(pageArgumentsToCallOptions(ADBLOCK_PAGE_CATEGORY,ADBLOCK_PAGE_NAME,{// 'title' is intentionally omitted as it does not make sense
2457
+ // in v3 implementation
2458
+ path:ADBLOCK_PAGE_PATH},state.loadOptions.value.sendAdblockPageOptions));}}},{key:"track",value:function track(payload){var _this$eventManager3;var type='track';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event - ").concat(payload.name));state.metrics.triggered.value+=1;(_this$eventManager3=this.eventManager)===null||_this$eventManager3===void 0||_this$eventManager3.addEvent({type:type,name:payload.name||undefined,properties:payload.properties,options:payload.options,callback:payload.callback});}},{key:"identify",value:function identify(payload){var _this$userSessionMana3,_this$eventManager4;var type='identify';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;var shouldResetSession=Boolean(payload.userId&&state.session.userId.value&&payload.userId!==state.session.userId.value);if(shouldResetSession){this.reset();}// `null` value indicates that previous user ID needs to be retained
2459
+ if(!isNull(payload.userId)){var _this$userSessionMana2;(_this$userSessionMana2=this.userSessionManager)===null||_this$userSessionMana2===void 0||_this$userSessionMana2.setUserId(payload.userId);}(_this$userSessionMana3=this.userSessionManager)===null||_this$userSessionMana3===void 0||_this$userSessionMana3.setUserTraits(payload.traits);(_this$eventManager4=this.eventManager)===null||_this$eventManager4===void 0||_this$eventManager4.addEvent({type:type,userId:payload.userId,traits:payload.traits,options:payload.options,callback:payload.callback});}},{key:"alias",value:function alias(payload){var _payload$from,_this$userSessionMana4,_this$eventManager5;var type='alias';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;var previousId=(_payload$from=payload.from)!==null&&_payload$from!==void 0?_payload$from:this.getUserId()||((_this$userSessionMana4=this.userSessionManager)===null||_this$userSessionMana4===void 0?void 0:_this$userSessionMana4.getAnonymousId());(_this$eventManager5=this.eventManager)===null||_this$eventManager5===void 0||_this$eventManager5.addEvent({type:type,to:payload.to,from:previousId,options:payload.options,callback:payload.callback});}},{key:"group",value:function group(payload){var _this$userSessionMana6,_this$eventManager6;var type='group';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;// `null` value indicates that previous group ID needs to be retained
2460
+ if(!isNull(payload.groupId)){var _this$userSessionMana5;(_this$userSessionMana5=this.userSessionManager)===null||_this$userSessionMana5===void 0||_this$userSessionMana5.setGroupId(payload.groupId);}(_this$userSessionMana6=this.userSessionManager)===null||_this$userSessionMana6===void 0||_this$userSessionMana6.setGroupTraits(payload.traits);(_this$eventManager6=this.eventManager)===null||_this$eventManager6===void 0||_this$eventManager6.addEvent({type:type,groupId:payload.groupId,traits:payload.traits,options:payload.options,callback:payload.callback});}},{key:"reset",value:function reset(options){var _this$userSessionMana7;var type='reset';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,options]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$userSessionMana7=this.userSessionManager)===null||_this$userSessionMana7===void 0||_this$userSessionMana7.reset(options);}},{key:"getAnonymousId",value:function getAnonymousId(options){var _this$userSessionMana8;return (_this$userSessionMana8=this.userSessionManager)===null||_this$userSessionMana8===void 0?void 0:_this$userSessionMana8.getAnonymousId(options);}},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){var _this$userSessionMana9;var type='setAnonymousId';// Buffering is needed as setting the anonymous ID may require invoking the GoogleLinker plugin
2461
+ if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,anonymousId,rudderAmpLinkerParam]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$userSessionMana9=this.userSessionManager)===null||_this$userSessionMana9===void 0||_this$userSessionMana9.setAnonymousId(anonymousId,rudderAmpLinkerParam);}// eslint-disable-next-line class-methods-use-this
2462
+ },{key:"getUserId",value:function getUserId(){return state.session.userId.value;}// eslint-disable-next-line class-methods-use-this
2463
+ },{key:"getUserTraits",value:function getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
2464
+ },{key:"getGroupId",value:function getGroupId(){return state.session.groupId.value;}// eslint-disable-next-line class-methods-use-this
2465
+ },{key:"getGroupTraits",value:function getGroupTraits(){return state.session.groupTraits.value;}},{key:"startSession",value:function startSession(sessionId){var _this$userSessionMana0;var type='startSession';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,sessionId]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$userSessionMana0=this.userSessionManager)===null||_this$userSessionMana0===void 0||_this$userSessionMana0.start(sessionId);}},{key:"endSession",value:function endSession(){var _this$userSessionMana1;var type='endSession';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$userSessionMana1=this.userSessionManager)===null||_this$userSessionMana1===void 0||_this$userSessionMana1.end();}// eslint-disable-next-line class-methods-use-this
2466
+ },{key:"getSessionId",value:function getSessionId(){var _this$userSessionMana10;var sessionId=(_this$userSessionMana10=this.userSessionManager)===null||_this$userSessionMana10===void 0?void 0:_this$userSessionMana10.getSessionId();return sessionId!==null&&sessionId!==void 0?sessionId:null;}},{key:"consent",value:function consent(options){var _this4=this,_this$storeManager2,_this$userSessionMana11,_this$eventManager7;var isBufferedInvocation=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var type='consent';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,options]]);return;}this.errorHandler.leaveBreadcrumb("New consent invocation");n(function(){state.consents.preConsent.value=_objectSpread2(_objectSpread2({},state.consents.preConsent.value),{},{enabled:false});state.consents.postConsent.value=getValidPostConsentOptions(options);var _getConsentManagement=getConsentManagementData(state.consents.postConsent.value.consentManagement,_this4.logger),initialized=_getConsentManagement.initialized,consentsData=_getConsentManagement.consentsData;state.consents.initialized.value=initialized;state.consents.data.value=consentsData;});// Update consents data in state
2467
+ if(state.consents.enabled.value&&!state.consents.initialized.value){var _this$pluginsManager6;(_this$pluginsManager6=this.pluginsManager)===null||_this$pluginsManager6===void 0||_this$pluginsManager6.invokeSingle("consentManager.updateConsentsInfo",state,this.storeManager,this.logger);}// Re-init store manager
2468
+ (_this$storeManager2=this.storeManager)===null||_this$storeManager2===void 0||_this$storeManager2.initializeStorageState();// Re-init user session manager
2469
+ (_this$userSessionMana11=this.userSessionManager)===null||_this$userSessionMana11===void 0||_this$userSessionMana11.syncStorageDataToState();// Resume event manager to process the events to destinations
2470
+ (_this$eventManager7=this.eventManager)===null||_this$eventManager7===void 0||_this$eventManager7.resume();this.loadDestinations();this.sendTrackingEvents(isBufferedInvocation);}},{key:"sendTrackingEvents",value:function sendTrackingEvents(isBufferedInvocation){// If isBufferedInvocation is true, then the tracking events will be added to the end of the
2471
+ // events buffer array so that any other preload events (mainly from query string API) will be processed first.
2472
+ if(state.consents.postConsent.value.trackConsent){var trackOptions=trackArgumentsToCallOptions(CONSENT_TRACK_EVENT_NAME);if(isBufferedInvocation){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[['track',trackOptions]]);}else {this.track(trackOptions);}}if(state.consents.postConsent.value.sendPageEvent){var pageOptions=pageArgumentsToCallOptions();if(isBufferedInvocation){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[['page',pageOptions]]);}else {this.page(pageOptions);}}}},{key:"setAuthToken",value:function setAuthToken(token){var _this$userSessionMana12;(_this$userSessionMana12=this.userSessionManager)===null||_this$userSessionMana12===void 0||_this$userSessionMana12.setAuthToken(token);}/**
2473
+ * Add a custom integration for a custom destination.
2474
+ * @param destinationId - The ID of the custom destination from the RudderStack dashboard.
2475
+ * @param integration - The custom integration object.
2476
+ * @param isBufferedInvocation - Whether the invocation is buffered.
2477
+ */},{key:"addCustomIntegration",value:function addCustomIntegration(destinationId,integration){var isBufferedInvocation=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var type='addCustomIntegration';if(isBufferedInvocation){var _this$pluginsManager7;this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$pluginsManager7=this.pluginsManager)===null||_this$pluginsManager7===void 0||_this$pluginsManager7.invokeSingle('nativeDestinations.addCustomIntegration',destinationId,integration,state,this.logger);}else {if(state.lifecycle.loaded.value){this.logger.error(CUSTOM_INTEGRATION_CANNOT_BE_ADDED_ERROR(ANALYTICS_CORE,destinationId));return;}state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,destinationId,integration]]);}}// End consumer exposed methods
2478
+ }]);}();
2479
+
2480
+ /*
2481
+ * RudderAnalytics facade singleton that is exposed as global object and will:
2482
+ * expose overloaded methods
2483
+ * handle multiple Analytics instances
2484
+ * consume SDK preload event buffer
2485
+ */var RudderAnalytics=/*#__PURE__*/function(){// Singleton with constructor bind methods
2486
+ function RudderAnalytics(){_classCallCheck(this,RudderAnalytics);// END-NO-SONAR-SCAN
2487
+ _defineProperty(this,"analyticsInstances",{});_defineProperty(this,"defaultAnalyticsKey",'');_defineProperty(this,"logger",defaultLogger);try{if(RudderAnalytics.globalSingleton){// START-NO-SONAR-SCAN
2488
+ // eslint-disable-next-line no-constructor-return
2489
+ return RudderAnalytics.globalSingleton;// END-NO-SONAR-SCAN
2490
+ }RudderAnalytics.initializeGlobalResources();this.setDefaultInstanceKey=this.setDefaultInstanceKey.bind(this);this.getAnalyticsInstance=this.getAnalyticsInstance.bind(this);this.load=this.load.bind(this);this.ready=this.ready.bind(this);this.triggerBufferedLoadEvent=this.triggerBufferedLoadEvent.bind(this);this.page=this.page.bind(this);this.track=this.track.bind(this);this.identify=this.identify.bind(this);this.alias=this.alias.bind(this);this.group=this.group.bind(this);this.reset=this.reset.bind(this);this.getAnonymousId=this.getAnonymousId.bind(this);this.setAnonymousId=this.setAnonymousId.bind(this);this.getUserId=this.getUserId.bind(this);this.getUserTraits=this.getUserTraits.bind(this);this.getGroupId=this.getGroupId.bind(this);this.getGroupTraits=this.getGroupTraits.bind(this);this.startSession=this.startSession.bind(this);this.endSession=this.endSession.bind(this);this.getSessionId=this.getSessionId.bind(this);this.setAuthToken=this.setAuthToken.bind(this);this.consent=this.consent.bind(this);this.addCustomIntegration=this.addCustomIntegration.bind(this);this.createSafeAnalyticsInstance();RudderAnalytics.globalSingleton=this;state.autoTrack.pageLifecycle.pageViewId.value=generateUUID();state.autoTrack.pageLifecycle.pageLoadedTimestamp.value=Date.now();// start loading if a load event was buffered or wait for explicit load call
2491
+ this.triggerBufferedLoadEvent();// Assign to global "rudderanalytics" object after processing the preload buffer (if any exists)
2492
+ // for CDN bundling IIFE exports covers this but for npm ESM and CJS bundling has to be done explicitly
2493
+ globalThis.rudderanalytics=this;}catch(error){dispatchErrorEvent(error);}}/**
2494
+ * Create an instance of the current instance that can be used
2495
+ * to call a subset of methods of the current instance.
2496
+ * It is typically used to expose the analytics instance to the integrations (standard and custom)
2497
+ */return _createClass(RudderAnalytics,[{key:"createSafeAnalyticsInstance",value:function createSafeAnalyticsInstance(){state.lifecycle.safeAnalyticsInstance.value={page:this.page.bind(this),track:this.track.bind(this),identify:this.identify.bind(this),alias:this.alias.bind(this),group:this.group.bind(this),getAnonymousId:this.getAnonymousId.bind(this),getUserId:this.getUserId.bind(this),getUserTraits:this.getUserTraits.bind(this),getGroupId:this.getGroupId.bind(this),getGroupTraits:this.getGroupTraits.bind(this),getSessionId:this.getSessionId.bind(this)};}},{key:"setDefaultInstanceKey",value:/**
2498
+ * Set instance to use if no specific writeKey is provided in methods
2499
+ * automatically for the first created instance
2500
+ * TODO: to support multiple analytics instances in the near future
2501
+ */function setDefaultInstanceKey(writeKey){// IMP: Add try-catch block to handle any unhandled errors
2502
+ // similar to other public methods
2503
+ // if the implementation of this method goes beyond
2504
+ // this simple implementation
2505
+ if(isString(writeKey)&&writeKey){this.defaultAnalyticsKey=writeKey;}}/**
2506
+ * Retrieve an existing analytics instance
2507
+ */},{key:"getAnalyticsInstance",value:function getAnalyticsInstance(writeKey){try{var instanceId=writeKey;if(!isString(instanceId)||!instanceId){instanceId=this.defaultAnalyticsKey;}var analyticsInstanceExists=Boolean(this.analyticsInstances[instanceId]);if(!analyticsInstanceExists){this.analyticsInstances[instanceId]=new Analytics();}return this.analyticsInstances[instanceId];}catch(error){dispatchErrorEvent(error);return undefined;}}/**
2508
+ * Loads the SDK
2509
+ * @param writeKey Source write key
2510
+ * @param dataPlaneUrl Data plane URL
2511
+ * @param loadOptions Additional options for loading the SDK
2512
+ * @returns none
2513
+ */},{key:"load",value:function load(writeKey,dataPlaneUrl,loadOptions){try{var _this$getAnalyticsIns;if(this.analyticsInstances[writeKey]){return;}this.setDefaultInstanceKey(writeKey);// Track page loaded lifecycle event if enabled
2514
+ this.trackPageLifecycleEvents(loadOptions);// Get the preloaded events array from global buffer instead of window.rudderanalytics
2515
+ // as the constructor must have already pushed the events to the global buffer
2516
+ var preloadedEventsArray=getExposedGlobal(GLOBAL_PRELOAD_BUFFER);// The array will be mutated in the below method
2517
+ promotePreloadedConsentEventsToTop(preloadedEventsArray);setExposedGlobal(GLOBAL_PRELOAD_BUFFER,clone(preloadedEventsArray));(_this$getAnalyticsIns=this.getAnalyticsInstance(writeKey))===null||_this$getAnalyticsIns===void 0||_this$getAnalyticsIns.load(writeKey,dataPlaneUrl,getSanitizedValue(loadOptions));}catch(error){dispatchErrorEvent(error);}}/**
2518
+ * A function to track page lifecycle events like page loaded and page unloaded
2519
+ * @param loadOptions
2520
+ * @returns
2521
+ */},{key:"trackPageLifecycleEvents",value:function trackPageLifecycleEvents(loadOptions){var _ref=loadOptions!==null&&loadOptions!==void 0?loadOptions:{},autoTrack=_ref.autoTrack,useBeacon=_ref.useBeacon;var _ref2=autoTrack!==null&&autoTrack!==void 0?autoTrack:{},_ref2$enabled=_ref2.enabled,autoTrackEnabled=_ref2$enabled===void 0?false:_ref2$enabled,_ref2$options=_ref2.options,autoTrackOptions=_ref2$options===void 0?{}:_ref2$options,pageLifecycle=_ref2.pageLifecycle;var _ref3=pageLifecycle!==null&&pageLifecycle!==void 0?pageLifecycle:{},_ref3$events=_ref3.events,events=_ref3$events===void 0?[PageLifecycleEvents.UNLOADED]:_ref3$events,_ref3$enabled=_ref3.enabled,pageLifecycleEnabled=_ref3$enabled===void 0?autoTrackEnabled:_ref3$enabled,_ref3$options=_ref3.options,options=_ref3$options===void 0?autoTrackOptions:_ref3$options;state.autoTrack.pageLifecycle.enabled.value=pageLifecycleEnabled;// Set the autoTrack enabled state
2522
+ // if at least one of the autoTrack options is enabled
2523
+ // IMPORTANT: make sure this is done at the end as it depends on the above states
2524
+ state.autoTrack.enabled.value=autoTrackEnabled||pageLifecycleEnabled;if(!pageLifecycleEnabled){return;}this.setupPageUnloadTracking(events,useBeacon,options);}/**
2525
+ * Setup page unload tracking if enabled
2526
+ * @param events
2527
+ * @param useBeacon
2528
+ * @param options
2529
+ */},{key:"setupPageUnloadTracking",value:function setupPageUnloadTracking(events,useBeacon,options){var _this=this;if(events.length===0||events.includes(PageLifecycleEvents.UNLOADED)){if(useBeacon===true){onPageLeave(function(isAccessible){if(isAccessible===false&&state.lifecycle.loaded.value){var pageUnloadedTimestamp=Date.now();var timeOnPage=pageUnloadedTimestamp-state.autoTrack.pageLifecycle.pageLoadedTimestamp.value;_this.track(PageLifecycleEvents.UNLOADED,{timeOnPage:timeOnPage},_objectSpread2(_objectSpread2({},options),{},{originalTimestamp:getFormattedTimestamp(new Date(pageUnloadedTimestamp))}));}},true);}else {// log warning if beacon is disabled
2530
+ this.logger.warn(PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(RSA));}}}/**
2531
+ * Trigger load event in buffer queue if exists and stores the
2532
+ * remaining preloaded events array in global object
2533
+ */},{key:"triggerBufferedLoadEvent",value:function triggerBufferedLoadEvent(){var preloadedEventsArray=Array.isArray(globalThis.rudderanalytics)?globalThis.rudderanalytics:[];// Get any load method call that is buffered if any
2534
+ // BTW, load method is also removed from the array
2535
+ // So, the Analytics object can directly consume the remaining events
2536
+ var loadEvent=getPreloadedLoadEvent(preloadedEventsArray);// Set the final preloaded events array in global object
2537
+ setExposedGlobal(GLOBAL_PRELOAD_BUFFER,clone(_toConsumableArray(preloadedEventsArray)));// Process load method if present in the buffered requests
2538
+ if(loadEvent.length>0){// Remove the event name from the Buffered Event array and keep only arguments
2539
+ loadEvent.shift();// eslint-disable-next-line @typescript-eslint/ban-ts-comment
2540
+ // @ts-ignore
2541
+ this.load.apply(null,loadEvent);}}/**
2542
+ * Get ready callback arguments and forward to ready call
2543
+ */},{key:"ready",value:function ready(callback){try{var _this$getAnalyticsIns2;(_this$getAnalyticsIns2=this.getAnalyticsInstance())===null||_this$getAnalyticsIns2===void 0||_this$getAnalyticsIns2.ready(getSanitizedValue(callback));}catch(error){dispatchErrorEvent(error);}}/**
2544
+ * Process page arguments and forward to page call
2545
+ */// These overloads should be same as AnalyticsPageMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
2546
+ },{key:"page",value:function page(category,name,properties,options,callback){try{var _this$getAnalyticsIns3;(_this$getAnalyticsIns3=this.getAnalyticsInstance())===null||_this$getAnalyticsIns3===void 0||_this$getAnalyticsIns3.page(pageArgumentsToCallOptions(getSanitizedValue(category),getSanitizedValue(name),getSanitizedValue(properties),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
2547
+ * Process track arguments and forward to page call
2548
+ */// These overloads should be same as AnalyticsTrackMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
2549
+ },{key:"track",value:function track(event,properties,options,callback){try{var _this$getAnalyticsIns4;(_this$getAnalyticsIns4=this.getAnalyticsInstance())===null||_this$getAnalyticsIns4===void 0||_this$getAnalyticsIns4.track(trackArgumentsToCallOptions(getSanitizedValue(event),getSanitizedValue(properties),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
2550
+ * Process identify arguments and forward to page call
2551
+ */// These overloads should be same as AnalyticsIdentifyMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
2552
+ },{key:"identify",value:function identify(userId,traits,options,callback){try{var _this$getAnalyticsIns5;(_this$getAnalyticsIns5=this.getAnalyticsInstance())===null||_this$getAnalyticsIns5===void 0||_this$getAnalyticsIns5.identify(identifyArgumentsToCallOptions(getSanitizedValue(userId),getSanitizedValue(traits),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
2553
+ * Process alias arguments and forward to page call
2554
+ */// These overloads should be same as AnalyticsAliasMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
2555
+ },{key:"alias",value:function alias(to,from,options,callback){try{var _this$getAnalyticsIns6;(_this$getAnalyticsIns6=this.getAnalyticsInstance())===null||_this$getAnalyticsIns6===void 0||_this$getAnalyticsIns6.alias(aliasArgumentsToCallOptions(getSanitizedValue(to),getSanitizedValue(from),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
2556
+ * Process group arguments and forward to page call
2557
+ */// These overloads should be same as AnalyticsGroupMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
2558
+ },{key:"group",value:function group(groupId,traits,options,callback){try{var _this$getAnalyticsIns7;(_this$getAnalyticsIns7=this.getAnalyticsInstance())===null||_this$getAnalyticsIns7===void 0||_this$getAnalyticsIns7.group(groupArgumentsToCallOptions(getSanitizedValue(groupId),getSanitizedValue(traits),getSanitizedValue(options),getSanitizedValue(callback)));}catch(error){dispatchErrorEvent(error);}}/**
2559
+ * Reset the analytics instance
2560
+ * @param options Reset options. Except for anonymousId, initialReferrer, and initialReferringDomain
2561
+ * all other values will be reset by default.
2562
+ * @example
2563
+ * ```ts
2564
+ * reset({
2565
+ * entries: {
2566
+ * anonymousId: true,
2567
+ * }
2568
+ * });
2569
+ * ```
2570
+ * @example
2571
+ * ```ts
2572
+ * reset({
2573
+ * entries: {
2574
+ * userId: false,
2575
+ * sessionInfo: false,
2576
+ * }
2577
+ * });
2578
+ * ```
2579
+ * @returns none
2580
+ */},{key:"reset",value:function reset(options){try{var _this$getAnalyticsIns8;(_this$getAnalyticsIns8=this.getAnalyticsInstance())===null||_this$getAnalyticsIns8===void 0||_this$getAnalyticsIns8.reset(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);}}},{key:"getAnonymousId",value:function getAnonymousId(options){try{var _this$getAnalyticsIns9;return (_this$getAnalyticsIns9=this.getAnalyticsInstance())===null||_this$getAnalyticsIns9===void 0?void 0:_this$getAnalyticsIns9.getAnonymousId(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);return undefined;}}},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){try{var _this$getAnalyticsIns0;(_this$getAnalyticsIns0=this.getAnalyticsInstance())===null||_this$getAnalyticsIns0===void 0||_this$getAnalyticsIns0.setAnonymousId(getSanitizedValue(anonymousId),getSanitizedValue(rudderAmpLinkerParam));}catch(error){dispatchErrorEvent(error);}}},{key:"getUserId",value:function getUserId(){try{var _this$getAnalyticsIns1;return (_this$getAnalyticsIns1=this.getAnalyticsInstance())===null||_this$getAnalyticsIns1===void 0?void 0:_this$getAnalyticsIns1.getUserId();}catch(error){dispatchErrorEvent(error);return undefined;}}},{key:"getUserTraits",value:function getUserTraits(){try{var _this$getAnalyticsIns10;return (_this$getAnalyticsIns10=this.getAnalyticsInstance())===null||_this$getAnalyticsIns10===void 0?void 0:_this$getAnalyticsIns10.getUserTraits();}catch(error){dispatchErrorEvent(error);return undefined;}}},{key:"getGroupId",value:function getGroupId(){try{var _this$getAnalyticsIns11;return (_this$getAnalyticsIns11=this.getAnalyticsInstance())===null||_this$getAnalyticsIns11===void 0?void 0:_this$getAnalyticsIns11.getGroupId();}catch(error){dispatchErrorEvent(error);return undefined;}}},{key:"getGroupTraits",value:function getGroupTraits(){try{var _this$getAnalyticsIns12;return (_this$getAnalyticsIns12=this.getAnalyticsInstance())===null||_this$getAnalyticsIns12===void 0?void 0:_this$getAnalyticsIns12.getGroupTraits();}catch(error){dispatchErrorEvent(error);return undefined;}}},{key:"startSession",value:function startSession(sessionId){try{var _this$getAnalyticsIns13;(_this$getAnalyticsIns13=this.getAnalyticsInstance())===null||_this$getAnalyticsIns13===void 0||_this$getAnalyticsIns13.startSession(getSanitizedValue(sessionId));}catch(error){dispatchErrorEvent(error);}}},{key:"endSession",value:function endSession(){try{var _this$getAnalyticsIns14;(_this$getAnalyticsIns14=this.getAnalyticsInstance())===null||_this$getAnalyticsIns14===void 0||_this$getAnalyticsIns14.endSession();}catch(error){dispatchErrorEvent(error);}}},{key:"getSessionId",value:function getSessionId(){try{var _this$getAnalyticsIns15;return (_this$getAnalyticsIns15=this.getAnalyticsInstance())===null||_this$getAnalyticsIns15===void 0?void 0:_this$getAnalyticsIns15.getSessionId();}catch(error){dispatchErrorEvent(error);return undefined;}}},{key:"setAuthToken",value:function setAuthToken(token){try{var _this$getAnalyticsIns16;(_this$getAnalyticsIns16=this.getAnalyticsInstance())===null||_this$getAnalyticsIns16===void 0||_this$getAnalyticsIns16.setAuthToken(getSanitizedValue(token));}catch(error){dispatchErrorEvent(error);}}},{key:"consent",value:function consent(options){try{var _this$getAnalyticsIns17;(_this$getAnalyticsIns17=this.getAnalyticsInstance())===null||_this$getAnalyticsIns17===void 0||_this$getAnalyticsIns17.consent(getSanitizedValue(options));}catch(error){dispatchErrorEvent(error);}}},{key:"addCustomIntegration",value:function addCustomIntegration(destinationId,integration){try{var _this$getAnalyticsIns18;(_this$getAnalyticsIns18=this.getAnalyticsInstance())===null||_this$getAnalyticsIns18===void 0||_this$getAnalyticsIns18.addCustomIntegration(getSanitizedValue(destinationId),getSanitizedValue(integration));}catch(error){dispatchErrorEvent(error);}}}],[{key:"initializeGlobalResources",value:function initializeGlobalResources(){// We need to initialize the error handler first to catch any unhandled errors occurring in this module as well
2581
+ defaultErrorHandler.init();// Initialize the storage engines with default options
2582
+ defaultCookieStorage.configure();defaultLocalStorage.configure();defaultSessionStorage.configure();defaultInMemoryStorage.configure();}}]);}();// START-NO-SONAR-SCAN
2583
+ // eslint-disable-next-line sonarjs/public-static-readonly
2584
+ _defineProperty(RudderAnalytics,"globalSingleton",null);
2585
+
2586
+ exports.RudderAnalytics = RudderAnalytics;
2587
+
2588
+ }));