@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,2582 @@
1
+ 'use strict';
2
+
3
+ function _arrayLikeToArray(r, a) {
4
+ (null == a || a > r.length) && (a = r.length);
5
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
6
+ return n;
7
+ }
8
+ function _arrayWithHoles(r) {
9
+ if (Array.isArray(r)) return r;
10
+ }
11
+ function _arrayWithoutHoles(r) {
12
+ if (Array.isArray(r)) return _arrayLikeToArray(r);
13
+ }
14
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
15
+ try {
16
+ var i = n[a](c),
17
+ u = i.value;
18
+ } catch (n) {
19
+ return void e(n);
20
+ }
21
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
22
+ }
23
+ function _asyncToGenerator(n) {
24
+ return function () {
25
+ var t = this,
26
+ e = arguments;
27
+ return new Promise(function (r, o) {
28
+ var a = n.apply(t, e);
29
+ function _next(n) {
30
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
31
+ }
32
+ function _throw(n) {
33
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
34
+ }
35
+ _next(void 0);
36
+ });
37
+ };
38
+ }
39
+ function _classCallCheck(a, n) {
40
+ if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
41
+ }
42
+ function _defineProperties(e, r) {
43
+ for (var t = 0; t < r.length; t++) {
44
+ var o = r[t];
45
+ o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
46
+ }
47
+ }
48
+ function _createClass(e, r, t) {
49
+ return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
50
+ writable: false
51
+ }), e;
52
+ }
53
+ function _createForOfIteratorHelper(r, e) {
54
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
55
+ if (!t) {
56
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
57
+ t && (r = t);
58
+ var n = 0,
59
+ F = function () {};
60
+ return {
61
+ s: F,
62
+ n: function () {
63
+ return n >= r.length ? {
64
+ done: true
65
+ } : {
66
+ done: false,
67
+ value: r[n++]
68
+ };
69
+ },
70
+ e: function (r) {
71
+ throw r;
72
+ },
73
+ f: F
74
+ };
75
+ }
76
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
77
+ }
78
+ var o,
79
+ a = true,
80
+ u = false;
81
+ return {
82
+ s: function () {
83
+ t = t.call(r);
84
+ },
85
+ n: function () {
86
+ var r = t.next();
87
+ return a = r.done, r;
88
+ },
89
+ e: function (r) {
90
+ u = true, o = r;
91
+ },
92
+ f: function () {
93
+ try {
94
+ a || null == t.return || t.return();
95
+ } finally {
96
+ if (u) throw o;
97
+ }
98
+ }
99
+ };
100
+ }
101
+ function _defineProperty(e, r, t) {
102
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
103
+ value: t,
104
+ enumerable: true,
105
+ configurable: true,
106
+ writable: true
107
+ }) : e[r] = t, e;
108
+ }
109
+ function _iterableToArray(r) {
110
+ if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
111
+ }
112
+ function _iterableToArrayLimit(r, l) {
113
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
114
+ if (null != t) {
115
+ var e,
116
+ n,
117
+ i,
118
+ u,
119
+ a = [],
120
+ f = true,
121
+ o = false;
122
+ try {
123
+ if (i = (t = t.call(r)).next, 0 === l) {
124
+ if (Object(t) !== t) return;
125
+ f = !1;
126
+ } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
127
+ } catch (r) {
128
+ o = true, n = r;
129
+ } finally {
130
+ try {
131
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
132
+ } finally {
133
+ if (o) throw n;
134
+ }
135
+ }
136
+ return a;
137
+ }
138
+ }
139
+ function _nonIterableRest() {
140
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
141
+ }
142
+ function _nonIterableSpread() {
143
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
144
+ }
145
+ function ownKeys(e, r) {
146
+ var t = Object.keys(e);
147
+ if (Object.getOwnPropertySymbols) {
148
+ var o = Object.getOwnPropertySymbols(e);
149
+ r && (o = o.filter(function (r) {
150
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
151
+ })), t.push.apply(t, o);
152
+ }
153
+ return t;
154
+ }
155
+ function _objectSpread2(e) {
156
+ for (var r = 1; r < arguments.length; r++) {
157
+ var t = null != arguments[r] ? arguments[r] : {};
158
+ r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
159
+ _defineProperty(e, r, t[r]);
160
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
161
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
162
+ });
163
+ }
164
+ return e;
165
+ }
166
+ function _objectWithoutProperties(e, t) {
167
+ if (null == e) return {};
168
+ var o,
169
+ r,
170
+ i = _objectWithoutPropertiesLoose(e, t);
171
+ if (Object.getOwnPropertySymbols) {
172
+ var n = Object.getOwnPropertySymbols(e);
173
+ for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
174
+ }
175
+ return i;
176
+ }
177
+ function _objectWithoutPropertiesLoose(r, e) {
178
+ if (null == r) return {};
179
+ var t = {};
180
+ for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
181
+ if (-1 !== e.indexOf(n)) continue;
182
+ t[n] = r[n];
183
+ }
184
+ return t;
185
+ }
186
+ function _regenerator() {
187
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
188
+ var e,
189
+ t,
190
+ r = "function" == typeof Symbol ? Symbol : {},
191
+ n = r.iterator || "@@iterator",
192
+ o = r.toStringTag || "@@toStringTag";
193
+ function i(r, n, o, i) {
194
+ var c = n && n.prototype instanceof Generator ? n : Generator,
195
+ u = Object.create(c.prototype);
196
+ return _regeneratorDefine(u, "_invoke", function (r, n, o) {
197
+ var i,
198
+ c,
199
+ u,
200
+ f = 0,
201
+ p = o || [],
202
+ y = false,
203
+ G = {
204
+ p: 0,
205
+ n: 0,
206
+ v: e,
207
+ a: d,
208
+ f: d.bind(e, 4),
209
+ d: function (t, r) {
210
+ return i = t, c = 0, u = e, G.n = r, a;
211
+ }
212
+ };
213
+ function d(r, n) {
214
+ for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
215
+ var o,
216
+ i = p[t],
217
+ d = G.p,
218
+ l = i[2];
219
+ 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));
220
+ }
221
+ if (o || r > 1) return a;
222
+ throw y = true, n;
223
+ }
224
+ return function (o, p, l) {
225
+ if (f > 1) throw TypeError("Generator is already running");
226
+ for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
227
+ i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
228
+ try {
229
+ if (f = 2, i) {
230
+ if (c || (o = "next"), t = i[o]) {
231
+ if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
232
+ if (!t.done) return t;
233
+ u = t.value, c < 2 && (c = 0);
234
+ } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
235
+ i = e;
236
+ } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
237
+ } catch (t) {
238
+ i = e, c = 1, u = t;
239
+ } finally {
240
+ f = 1;
241
+ }
242
+ }
243
+ return {
244
+ value: t,
245
+ done: y
246
+ };
247
+ };
248
+ }(r, o, i), true), u;
249
+ }
250
+ var a = {};
251
+ function Generator() {}
252
+ function GeneratorFunction() {}
253
+ function GeneratorFunctionPrototype() {}
254
+ t = Object.getPrototypeOf;
255
+ var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
256
+ return this;
257
+ }), t),
258
+ u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
259
+ function f(e) {
260
+ return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
261
+ }
262
+ 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 () {
263
+ return this;
264
+ }), _regeneratorDefine(u, "toString", function () {
265
+ return "[object Generator]";
266
+ }), (_regenerator = function () {
267
+ return {
268
+ w: i,
269
+ m: f
270
+ };
271
+ })();
272
+ }
273
+ function _regeneratorDefine(e, r, n, t) {
274
+ var i = Object.defineProperty;
275
+ try {
276
+ i({}, "", {});
277
+ } catch (e) {
278
+ i = 0;
279
+ }
280
+ _regeneratorDefine = function (e, r, n, t) {
281
+ function o(r, n) {
282
+ _regeneratorDefine(e, r, function (e) {
283
+ return this._invoke(r, n, e);
284
+ });
285
+ }
286
+ r ? i ? i(e, r, {
287
+ value: n,
288
+ enumerable: !t,
289
+ configurable: !t,
290
+ writable: !t
291
+ }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
292
+ }, _regeneratorDefine(e, r, n, t);
293
+ }
294
+ function _slicedToArray(r, e) {
295
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
296
+ }
297
+ function _toConsumableArray(r) {
298
+ return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
299
+ }
300
+ function _toPrimitive(t, r) {
301
+ if ("object" != typeof t || !t) return t;
302
+ var e = t[Symbol.toPrimitive];
303
+ if (void 0 !== e) {
304
+ var i = e.call(t, r);
305
+ if ("object" != typeof i) return i;
306
+ throw new TypeError("@@toPrimitive must return a primitive value.");
307
+ }
308
+ return (String )(t);
309
+ }
310
+ function _toPropertyKey(t) {
311
+ var i = _toPrimitive(t, "string");
312
+ return "symbol" == typeof i ? i : i + "";
313
+ }
314
+ function _typeof(o) {
315
+ "@babel/helpers - typeof";
316
+
317
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
318
+ return typeof o;
319
+ } : function (o) {
320
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
321
+ }, _typeof(o);
322
+ }
323
+ function _unsupportedIterableToArray(r, a) {
324
+ if (r) {
325
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
326
+ var t = {}.toString.call(r).slice(8, -1);
327
+ 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;
328
+ }
329
+ }
330
+
331
+ function _isPlaceholder(a){return a!=null&&_typeof(a)==='object'&&a['@@functional/placeholder']===true;}
332
+
333
+ /**
334
+ * Optimized internal one-arity curry function.
335
+ *
336
+ * @private
337
+ * @category Function
338
+ * @param {Function} fn The function to curry.
339
+ * @return {Function} The curried function.
340
+ */function _curry1(fn){return function f1(a){if(arguments.length===0||_isPlaceholder(a)){return f1;}else {return fn.apply(this,arguments);}};}
341
+
342
+ /**
343
+ * Optimized internal two-arity curry function.
344
+ *
345
+ * @private
346
+ * @category Function
347
+ * @param {Function} fn The function to curry.
348
+ * @return {Function} The curried function.
349
+ */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);}};}
350
+
351
+ /**
352
+ * Optimized internal three-arity curry function.
353
+ *
354
+ * @private
355
+ * @category Function
356
+ * @param {Function} fn The function to curry.
357
+ * @return {Function} The curried function.
358
+ */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);}};}
359
+
360
+ function _has(prop,obj){return Object.prototype.hasOwnProperty.call(obj,prop);}
361
+
362
+ /**
363
+ * Gives a single-word string description of the (native) type of a value,
364
+ * returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not
365
+ * attempt to distinguish user Object types any further, reporting them all as
366
+ * 'Object'.
367
+ *
368
+ * @func
369
+ * @memberOf R
370
+ * @since v0.8.0
371
+ * @category Type
372
+ * @sig * -> String
373
+ * @param {*} val The value to test
374
+ * @return {String}
375
+ * @example
376
+ *
377
+ * R.type({}); //=> "Object"
378
+ * R.type(new Map); //=> "Map"
379
+ * R.type(new Set); //=> "Set"
380
+ * R.type(1); //=> "Number"
381
+ * R.type(false); //=> "Boolean"
382
+ * R.type('s'); //=> "String"
383
+ * R.type(null); //=> "Null"
384
+ * R.type([]); //=> "Array"
385
+ * R.type(/[A-z]/); //=> "RegExp"
386
+ * R.type(() => {}); //=> "Function"
387
+ * R.type(async () => {}); //=> "AsyncFunction"
388
+ * R.type(undefined); //=> "Undefined"
389
+ * R.type(BigInt(123)); //=> "BigInt"
390
+ */var type=/*#__PURE__*/_curry1(function type(val){return val===null?'Null':val===undefined?'Undefined':Object.prototype.toString.call(val).slice(8,-1);});
391
+
392
+ function _isObject(x){return Object.prototype.toString.call(x)==='[object Object]';}
393
+
394
+ /**
395
+ * Determine if the passed argument is an integer.
396
+ *
397
+ * @private
398
+ * @param {*} n
399
+ * @category Type
400
+ * @return {Boolean}
401
+ */var _isInteger = Number.isInteger||function _isInteger(n){return n<<0===n;};
402
+
403
+ function _nth(offset,list){var idx=offset<0?list.length+offset:offset;return list[idx];}
404
+
405
+ 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':''));}
406
+
407
+ /**
408
+ * Copies an object.
409
+ *
410
+ * @private
411
+ * @param {*} value The value to be copied
412
+ * @param {Boolean} deep Whether or not to perform deep cloning.
413
+ * @return {*} The copied value.
414
+ */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.
415
+ 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.
416
+ 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){/**
417
+ * 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,
418
+ * on my tests this number is 180, anything above that using the hash function is faster.
419
+ */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;}();
420
+
421
+ /**
422
+ * Creates a deep copy of the source that can be used in place of the source
423
+ * object without retaining any references to it.
424
+ * The source object may contain (nested) `Array`s and `Object`s,
425
+ * `Number`s, `String`s, `Boolean`s and `Date`s.
426
+ * `Function`s are assigned by reference rather than copied.
427
+ *
428
+ * Dispatches to a `clone` method if present.
429
+ *
430
+ * Note that if the source object has multiple nodes that share a reference,
431
+ * the returned object will have the same structure, but the references will
432
+ * be pointed to the location within the cloned value.
433
+ *
434
+ * @func
435
+ * @memberOf R
436
+ * @since v0.1.0
437
+ * @category Object
438
+ * @sig {*} -> {*}
439
+ * @param {*} value The object or array to clone
440
+ * @return {*} A deeply cloned copy of `val`
441
+ * @example
442
+ *
443
+ * const objects = [{}, {}, {}];
444
+ * const objectsClone = R.clone(objects);
445
+ * objects === objectsClone; //=> false
446
+ * objects[0] === objectsClone[0]; //=> false
447
+ */var clone=/*#__PURE__*/_curry1(function clone(value){return value!=null&&typeof value.clone==='function'?value.clone():_clone(value);});
448
+
449
+ 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;}
450
+
451
+ /**
452
+ * Creates a new object with the own properties of the two provided objects. If
453
+ * a key exists in both objects, the provided function is applied to the key
454
+ * and the values associated with the key in each object, with the result being
455
+ * used as the value associated with the key in the returned object.
456
+ *
457
+ * @func
458
+ * @memberOf R
459
+ * @since v0.19.0
460
+ * @category Object
461
+ * @sig ((String, a, a) -> a) -> {a} -> {a} -> {a}
462
+ * @param {Function} fn
463
+ * @param {Object} l
464
+ * @param {Object} r
465
+ * @return {Object}
466
+ * @see R.mergeDeepWithKey, R.mergeWith
467
+ * @example
468
+ *
469
+ * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r
470
+ * R.mergeWithKey(concatValues,
471
+ * { a: true, thing: 'foo', values: [10, 20] },
472
+ * { b: true, thing: 'bar', values: [15, 35] });
473
+ * //=> { a: true, b: true, thing: 'bar', values: [10, 20, 15, 35] }
474
+ * @symb R.mergeWithKey(f, { x: 1, y: 2 }, { y: 5, z: 3 }) = { x: 1, y: f('y', 2, 5), z: 3 }
475
+ */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;});
476
+
477
+ /**
478
+ * Creates a new object with the own properties of the two provided objects.
479
+ * If a key exists in both objects:
480
+ * - and both associated values are also objects then the values will be
481
+ * recursively merged.
482
+ * - otherwise the provided function is applied to the key and associated values
483
+ * using the resulting value as the new value associated with the key.
484
+ * If a key only exists in one object, the value will be associated with the key
485
+ * of the resulting object.
486
+ *
487
+ * @func
488
+ * @memberOf R
489
+ * @since v0.24.0
490
+ * @category Object
491
+ * @sig ((String, a, a) -> a) -> {a} -> {a} -> {a}
492
+ * @param {Function} fn
493
+ * @param {Object} lObj
494
+ * @param {Object} rObj
495
+ * @return {Object}
496
+ * @see R.mergeWithKey, R.mergeDeepWith
497
+ * @example
498
+ *
499
+ * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r
500
+ * R.mergeDeepWithKey(concatValues,
501
+ * { a: true, c: { thing: 'foo', values: [10, 20] }},
502
+ * { b: true, c: { thing: 'bar', values: [15, 35] }});
503
+ * //=> { a: true, b: true, c: { thing: 'bar', values: [10, 20, 15, 35] }}
504
+ */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);});
505
+
506
+ /**
507
+ * Creates a new object with the own properties of the two provided objects.
508
+ * If a key exists in both objects:
509
+ * - and both associated values are also objects then the values will be
510
+ * recursively merged.
511
+ * - otherwise the provided function is applied to associated values using the
512
+ * resulting value as the new value associated with the key.
513
+ * If a key only exists in one object, the value will be associated with the key
514
+ * of the resulting object.
515
+ *
516
+ * @func
517
+ * @memberOf R
518
+ * @since v0.24.0
519
+ * @category Object
520
+ * @sig ((a, a) -> a) -> {a} -> {a} -> {a}
521
+ * @param {Function} fn
522
+ * @param {Object} lObj
523
+ * @param {Object} rObj
524
+ * @return {Object}
525
+ * @see R.mergeWith, R.mergeDeepWithKey
526
+ * @example
527
+ *
528
+ * R.mergeDeepWith(R.concat,
529
+ * { a: true, c: { values: [10, 20] }},
530
+ * { b: true, c: { values: [15, 35] }});
531
+ * //=> { a: true, b: true, c: { values: [10, 20, 15, 35] }}
532
+ */var mergeDeepWith=/*#__PURE__*/_curry3(function mergeDeepWith(fn,lObj,rObj){return mergeDeepWithKey(function(k,lVal,rVal){return fn(lVal,rVal);},lObj,rObj);});
533
+
534
+ /**
535
+ * Retrieves the value at a given path. The nodes of the path can be arbitrary strings or non-negative integers.
536
+ * For anything else, the value is unspecified. Integer paths are meant to index arrays, strings are meant for objects.
537
+ *
538
+ * @func
539
+ * @memberOf R
540
+ * @since v0.2.0
541
+ * @category Object
542
+ * @typedefn Idx = String | Int | Symbol
543
+ * @sig [Idx] -> {a} -> a | Undefined
544
+ * @sig Idx = String | NonNegativeInt
545
+ * @param {Array} path The path to use.
546
+ * @param {Object} obj The object or array to retrieve the nested property from.
547
+ * @return {*} The data at `path`.
548
+ * @see R.prop, R.nth, R.assocPath, R.dissocPath
549
+ * @example
550
+ *
551
+ * R.path(['a', 'b'], {a: {b: 2}}); //=> 2
552
+ * R.path(['a', 'b'], {c: {b: 2}}); //=> undefined
553
+ * R.path(['a', 'b', 0], {a: {b: [1, 2, 3]}}); //=> 1
554
+ * R.path(['a', 'b', -2], {a: {b: [1, 2, 3]}}); //=> 2
555
+ * R.path([2], {'2': 2}); //=> 2
556
+ * R.path([-2], {'-2': 'a'}); //=> undefined
557
+ */var path=/*#__PURE__*/_curry2(_path);
558
+
559
+ /**
560
+ * Returns a partial copy of an object containing only the keys that satisfy
561
+ * the supplied predicate.
562
+ *
563
+ * @func
564
+ * @memberOf R
565
+ * @since v0.8.0
566
+ * @category Object
567
+ * @sig ((v, k) -> Boolean) -> {k: v} -> {k: v}
568
+ * @param {Function} pred A predicate to determine whether or not a key
569
+ * should be included on the output object.
570
+ * @param {Object} obj The object to copy from
571
+ * @return {Object} A new object with only properties that satisfy `pred`
572
+ * on it.
573
+ * @see R.pick, R.filter
574
+ * @example
575
+ *
576
+ * const isUpperCase = (val, key) => key.toUpperCase() === key;
577
+ * R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4}
578
+ */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;});
579
+
580
+ /**
581
+ * A function to check given value is a function
582
+ * @param value input value
583
+ * @returns boolean
584
+ */var isFunction=function isFunction(value){return typeof value==='function'&&Boolean(value.constructor&&value.call&&value.apply);};/**
585
+ * A function to check given value is a string
586
+ * @param value input value
587
+ * @returns boolean
588
+ */var isString=function isString(value){return typeof value==='string';};/**
589
+ * A function to check given value is null or not
590
+ * @param value input value
591
+ * @returns boolean
592
+ */var isNull=function isNull(value){return value===null;};/**
593
+ * A function to check given value is undefined
594
+ * @param value input value
595
+ * @returns boolean
596
+ */var isUndefined=function isUndefined(value){return typeof value==='undefined';};/**
597
+ * A function to check given value is null or undefined
598
+ * @param value input value
599
+ * @returns boolean
600
+ */var isNullOrUndefined=function isNullOrUndefined(value){return isNull(value)||isUndefined(value);};/**
601
+ * Checks if the input is a BigInt
602
+ * @param value input value
603
+ * @returns True if the input is a BigInt
604
+ */var isBigInt=function isBigInt(value){return typeof value==='bigint';};/**
605
+ * A function to check given value is defined
606
+ * @param value input value
607
+ * @returns boolean
608
+ */var isDefined=function isDefined(value){return !isUndefined(value);};/**
609
+ * A function to check given value is defined and not null
610
+ * @param value input value
611
+ * @returns boolean
612
+ */var isDefinedAndNotNull=function isDefinedAndNotNull(value){return !isNullOrUndefined(value);};/**
613
+ * A function to check given value is defined and not null
614
+ * @param value input value
615
+ * @returns boolean
616
+ */var isDefinedNotNullAndNotEmptyString=function isDefinedNotNullAndNotEmptyString(value){return isDefinedAndNotNull(value)&&value!=='';};/**
617
+ * Determines if the input is of type error
618
+ * @param value input value
619
+ * @returns true if the input is of type error else false
620
+ */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;}};/**
621
+ * A function to check given value is a boolean
622
+ * @param value input value
623
+ * @returns boolean
624
+ */var isBoolean=function isBoolean(value){return typeof value==='boolean';};
625
+
626
+ 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';};/**
627
+ * Checks if the input is an object literal or built-in object type and not null
628
+ * @param value Input value
629
+ * @returns true if the input is an object and not null
630
+ */var isObjectAndNotNull=function isObjectAndNotNull(value){return !isNull(value)&&isObject(value)&&!Array.isArray(value);};/**
631
+ * Checks if the input is an object literal and not null
632
+ * @param value Input value
633
+ * @returns true if the input is an object and not null
634
+ */var isObjectLiteralAndNotNull=function isObjectLiteralAndNotNull(value){return !isNull(value)&&Object.prototype.toString.call(value)==='[object Object]';};/**
635
+ * Merges two arrays deeply, right-to-left
636
+ * In the case of conflicts, the right array's values replace the left array's values in the
637
+ * same index position
638
+ * @param leftValue - The left array
639
+ * @param rightValue - The right array
640
+ * @returns The merged array
641
+ */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
642
+ mergeDeepRight(mergedArray[index],value):value;});return mergedArray;};/**
643
+ * Merges two objects deeply, right-to-left.
644
+ * In the case of conflicts, the right object's values take precedence.
645
+ * For arrays, the right array's values replace the left array's values in the
646
+ * same index position keeping the remaining left array's values in the resultant array.
647
+ * @param leftObject - The left object
648
+ * @param rightObject - The right object
649
+ * @returns The merged object
650
+ */var mergeDeepRight=function mergeDeepRight(leftObject,rightObject){return mergeDeepWith(mergeDeepRightObjectArrays,leftObject,rightObject);};/**
651
+ Checks if the input is a non-empty object literal type and not undefined or null
652
+ * @param value input any
653
+ * @returns boolean
654
+ */var isNonEmptyObject=function isNonEmptyObject(value){return isObjectLiteralAndNotNull(value)&&Object.keys(value).length>0;};/**
655
+ * A utility to recursively remove undefined values from an object
656
+ * @param obj input object
657
+ * @returns a new object
658
+ */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;};/**
659
+ * A utility to recursively remove undefined and null values from an object
660
+ * @param obj input object
661
+ * @returns a new object
662
+ */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;};/**
663
+ * Normalizes an object by removing undefined and null values.
664
+ * @param val - The value to normalize
665
+ * @returns The normalized object, or undefined if input is not a non-empty object
666
+ * @example
667
+ * getNormalizedObjectValue({ a: 1, b: null, c: undefined }) // returns { a: 1 }
668
+ * getNormalizedObjectValue({}) // returns undefined
669
+ * getNormalizedObjectValue(null) // returns undefined
670
+ */var getNormalizedObjectValue=function getNormalizedObjectValue(val){if(!isNonEmptyObject(val)){return undefined;}return _removeUndefinedAndNullValues(val);};/**
671
+ * Normalizes a value to a boolean, with support for a default value
672
+ * @param val Input value
673
+ * @param defVal Default value
674
+ * @returns Returns the input value if it is a boolean, otherwise returns the default value
675
+ * @example
676
+ * getNormalizedBooleanValue(true, false) // returns true
677
+ */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);};
678
+
679
+ var trim=function trim(value){return value.replace(/^\s+|\s+$/gm,'');};var removeLeadingPeriod=function removeLeadingPeriod(value){return value.replace(/^\.+/,'');};/**
680
+ * A function to convert values to string
681
+ * @param val input value
682
+ * @returns stringified value
683
+ */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
684
+ // https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem
685
+ /**
686
+ * Converts a base64 encoded string to bytes array
687
+ * @param base64Str base64 encoded string
688
+ * @returns bytes array
689
+ */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);};/**
690
+ * Converts a bytes array to base64 encoded string
691
+ * @param bytes bytes array to be converted to base64
692
+ * @returns base64 encoded string
693
+ */var bytesToBase64=function bytesToBase64(bytes){var binString=Array.from(bytes,function(x){return String.fromCodePoint(x);}).join('');return globalThis.btoa(binString);};/**
694
+ * Encodes a string to base64 even with unicode characters
695
+ * @param value input string
696
+ * @returns base64 encoded string
697
+ */var toBase64=function toBase64(value){return bytesToBase64(new TextEncoder().encode(value));};/**
698
+ * Decodes a base64 encoded string
699
+ * @param value base64 encoded string
700
+ * @returns decoded string
701
+ */var fromBase64=function fromBase64(value){return new TextDecoder().decode(base64ToBytes(value));};
702
+
703
+ // if yes make them null instead of omitting in overloaded cases
704
+ /*
705
+ * Normalise the overloaded arguments of the page call facade
706
+ */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,
707
+ // use it as name and set category to undefined
708
+ if(isString(category)&&!isString(name)){payload.category=undefined;payload.name=category;}// Rest of the code is just to clean up undefined values
709
+ // and set some proper defaults
710
+ // Also, to clone the incoming object type arguments
711
+ 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
712
+ payload.properties=mergeDeepRight(isObjectLiteralAndNotNull(payload.properties)?payload.properties:{},_objectSpread2(_objectSpread2({},nameForProperties&&{name:nameForProperties}),categoryForProperties&&{category:categoryForProperties}));return payload;};/*
713
+ * Normalise the overloaded arguments of the track call facade
714
+ */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
715
+ // and set some proper defaults
716
+ // Also, to clone the incoming object type arguments
717
+ payload.properties=isDefinedAndNotNull(payload.properties)?clone(payload.properties):{};if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}return payload;};/*
718
+ * Normalise the overloaded arguments of the identify call facade
719
+ */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
720
+ // in the Analytics class
721
+ 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
722
+ // and set some proper defaults
723
+ // Also, to clone the incoming object type arguments
724
+ 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;};/*
725
+ * Normalise the overloaded arguments of the alias call facade
726
+ */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
727
+ // and set some proper defaults
728
+ // Also, to clone the incoming object type arguments
729
+ 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;};/*
730
+ * Normalise the overloaded arguments of the group call facade
731
+ */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
732
+ // in the Analytics class
733
+ 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
734
+ // and set some proper defaults
735
+ // Also, to clone the incoming object type arguments
736
+ 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;};
737
+
738
+ /**
739
+ * Represents the options parameter for anonymousId
740
+ *//**
741
+ * Represents the beacon queue options parameter in loadOptions type
742
+ *//**
743
+ * Represents the queue options parameter in loadOptions type
744
+ *//**
745
+ * Represents the destinations queue options parameter in loadOptions type
746
+ */var PageLifecycleEvents=/*#__PURE__*/function(PageLifecycleEvents){PageLifecycleEvents["UNLOADED"]="Page Unloaded";return PageLifecycleEvents;}({});/**
747
+ * Represents the source configuration override options for destinations
748
+ *//**
749
+ * Represents the options parameter in the load API
750
+ */
751
+
752
+ 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';
753
+
754
+ function random(len){return crypto.getRandomValues(new Uint8Array(len));}
755
+
756
+ 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;}
757
+
758
+ 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;}
759
+
760
+ var hasCrypto$1=function hasCrypto(){return !isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);};
761
+
762
+ var generateUUID=function generateUUID(){if(hasCrypto$1()){return v4$1();}return v4();};
763
+
764
+ /**
765
+ * Determines if the SDK is running inside a chrome extension
766
+ * @returns boolean
767
+ */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);};
768
+
769
+ /**
770
+ * Registers events to detect page leave scenarios
771
+ * @param callback Callback function
772
+ * @param avoidBfCacheOptimization When `true`, forcefully subscribes to beforeunload event, compromising on the bfcache optimization
773
+ */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
774
+ // are fired at once.
775
+ var pageLeft=false;var isAccessible=false;function handleOnLeave(){if(pageLeft){return;}pageLeft=true;callback(isAccessible);// Reset pageLeft on the next tick
776
+ // to ensure callback executes for other listeners
777
+ // when closing an inactive browser tab.
778
+ setTimeout(function(){pageLeft=false;},0);}// Catches the unloading of the page (e.g., closing the tab or navigating away).
779
+ // Includes user actions like clicking a link, entering a new URL,
780
+ // refreshing the page, or closing the browser tab
781
+ // Note that 'pagehide' is not supported in IE.
782
+ // Registering this event conditionally for IE11 also because
783
+ // it affects bfcache optimization on modern browsers otherwise.
784
+ // However, if optimization is disabled, force subscribe the event
785
+ if(avoidBfCacheOptimization||isIE11()){globalThis.addEventListener('beforeunload',function(){isAccessible=false;handleOnLeave();});}// This is important for iOS Safari browser as it does not
786
+ // fire the regular pagehide and visibilitychange events
787
+ // when user goes to tablist view and closes the tab.
788
+ globalThis.addEventListener('blur',function(){isAccessible=true;handleOnLeave();});globalThis.addEventListener('focus',function(){pageLeft=false;});// Catches the page being hidden, including scenarios like closing the tab.
789
+ document.addEventListener('pagehide',function(){isAccessible=document.visibilityState==='hidden';handleOnLeave();});// Catches visibility changes, such as switching tabs or minimizing the browser.
790
+ document.addEventListener('visibilitychange',function(){isAccessible=true;if(document.visibilityState==='hidden'){handleOnLeave();}else {pageLeft=false;}});};
791
+
792
+ var getFormattedTimestamp=function getFormattedTimestamp(date){return date.toISOString();};/**
793
+ * To get the current timestamp in ISO string format
794
+ * @returns ISO formatted timestamp string
795
+ */var getCurrentTimeFormatted=function getCurrentTimeFormatted(){return getFormattedTimestamp(new Date());};
796
+
797
+ 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 ");};
798
+
799
+ 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
800
+ // eslint-disable-next-line func-names
801
+ 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.
802
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
803
+ // @ts-ignore-next-line
804
+ 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;};};/**
805
+ * Utility method for JSON stringify object excluding null values & circular references
806
+ *
807
+ * @param {*} value input
808
+ * @param {boolean} excludeNull if it should exclude nul or not
809
+ * @param {function} logger optional logger methods for warning
810
+ * @returns string
811
+ */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
812
+ // Using a regular function to use `this` for the parent context
813
+ return function replacer(key,value){if(isBigInt(value)){return BIG_INT_PLACEHOLDER;// Replace BigInt values
814
+ }// `this` is the object that value is contained in, i.e., its direct parent.
815
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
816
+ // @ts-ignore-next-line
817
+ while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();// Remove ancestors that are no longer part of the chain
818
+ }// Check for circular references (if the value is already in the ancestors)
819
+ if(ancestors.includes(value)){return CIRCULAR_REFERENCE_PLACEHOLDER;}// Add current value to ancestors
820
+ ancestors.push(value);return value;};};var _traverseWithThis=function traverseWithThis(obj,replacer){// Create a new result object or array
821
+ var result=Array.isArray(obj)?[]:{};// Traverse object properties or array elements
822
+ // eslint-disable-next-line no-restricted-syntax
823
+ for(var key in obj){if(Object.hasOwnProperty.call(obj,key)){var value=obj[key];// Recursively apply the replacer and traversal
824
+ var sanitizedValue=replacer.call(obj,key,value);// If the value is an object or array, continue traversal
825
+ if(isObjectLiteralAndNotNull(sanitizedValue)||Array.isArray(sanitizedValue)){result[key]=_traverseWithThis(sanitizedValue,replacer);}else {result[key]=sanitizedValue;}}}return result;};/**
826
+ * Recursively traverses an object similar to JSON.stringify,
827
+ * sanitizing BigInts and circular references
828
+ * @param value Input object
829
+ * @param logger Logger instance
830
+ * @returns Sanitized value
831
+ */var getSanitizedValue=function getSanitizedValue(value,logger){var replacer=getReplacer();// This is needed for registering the first ancestor
832
+ var newValue=replacer.call(value,'',value);if(isObjectLiteralAndNotNull(value)||Array.isArray(value)){return _traverseWithThis(value,replacer);}return newValue;};
833
+
834
+ 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;};/**
835
+ * Get mutated error with issue prepended to error message
836
+ * @param err Original error
837
+ * @param issue Issue to prepend to error message
838
+ * @returns Instance of Error with message prepended with issue
839
+ */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.)
840
+ var ErrorConstructor=err.constructor;var newError=new ErrorConstructor("".concat(issue,": ").concat(err.message));// Preserve stack trace
841
+ var stack=getStacktrace(err);if(stack){newError.stack=stack;}// Preserve any other enumerable properties
842
+ 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
843
+ }}});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
844
+ error.stack="".concat(stack,"\n").concat(MANUAL_ERROR_IDENTIFIER);break;case stacktrace:// eslint-disable-next-line no-param-reassign
845
+ error.stacktrace="".concat(stacktrace,"\n").concat(MANUAL_ERROR_IDENTIFIER);break;case operaSourceloc:default:// eslint-disable-next-line no-param-reassign
846
+ error['opera#sourceloc']="".concat(operaSourceloc,"\n").concat(MANUAL_ERROR_IDENTIFIER);break;}}}globalThis.dispatchEvent(new ErrorEvent('error',{error:error,bubbles:true,cancelable:true,composed:true}));};
847
+
848
+ 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';
849
+
850
+ 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';
851
+
852
+ var DEFAULT_XHR_TIMEOUT_MS=10*1000;// 10 seconds
853
+ var DEFAULT_COOKIE_MAX_AGE_MS=31536000*1000;// 1 year
854
+ var DEFAULT_SESSION_CUT_OFF_DURATION_MS=12*60*60*1000;// 12 hours
855
+ var DEFAULT_SESSION_TIMEOUT_MS=30*60*1000;// 30 minutes
856
+ var MIN_SESSION_TIMEOUT_MS=10*1000;// 10 seconds
857
+ var DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS=10*1000;// 10 seconds
858
+ var DEBOUNCED_TIMEOUT_MS=250;// 250 milliseconds
859
+
860
+ /**
861
+ * Create globally accessible RudderStackGlobals object
862
+ */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]={};}};/**
863
+ * Add move values to globally accessible RudderStackGlobals object per analytics instance
864
+ */var setExposedGlobal=function setExposedGlobal(keyName,value){var analyticsInstanceId=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'app';createExposedGlobals(analyticsInstanceId);globalThis.RudderStackGlobals[analyticsInstanceId][keyName]=value;};/**
865
+ * Get values from globally accessible RudderStackGlobals object by analytics instance
866
+ */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);};}
867
+
868
+ /**
869
+ * Parse query string params into object values for keys that start with a defined prefix
870
+ */var getEventDataFromQueryString=function getEventDataFromQueryString(params,dataTypeNamePrefix){var data={};params.forEach(function(value,key){if(key.startsWith(dataTypeNamePrefix)){// remove prefix from key name
871
+ var dataKey=key.substring(dataTypeNamePrefix.length);// add new key value pair in generated object
872
+ data[dataKey]=params.get(key);}});return data;};/**
873
+ * Parse query string into preload buffer events & push into existing array before any other events
874
+ */var retrieveEventsFromQueryString=function retrieveEventsFromQueryString(){var argumentsArray=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];// Mapping for trait and properties values based on key prefix
875
+ 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
876
+ 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
877
+ 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
878
+ var identifyApiArgs=[].concat(_toConsumableArray(userId?[userId]:[]),[userTraits]);argumentsArray.unshift(['identify'].concat(_toConsumableArray(identifyApiArgs)));}// Set anonymousID
879
+ if(queryObject.get(QUERY_PARAM_ANONYMOUS_ID_KEY)){argumentsArray.unshift(['setAnonymousId',queryObject.get(QUERY_PARAM_ANONYMOUS_ID_KEY)]);}};/**
880
+ * Retrieve an existing buffered load method call and remove from the existing array
881
+ */var getPreloadedLoadEvent=function getPreloadedLoadEvent(preloadedEventsArray){var loadMethodName='load';var loadEvent=[];/**
882
+ * Iterate the buffered API calls until we find load call and process it separately
883
+ */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;};/**
884
+ * Promote consent events to the top of the preloaded events array
885
+ * @param preloadedEventsArray Preloaded events array
886
+ * @returns None
887
+ */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
888
+ // eslint-disable-next-line unicorn/no-useless-spread
889
+ preloadedEventsArray.splice.apply(preloadedEventsArray,[0,preloadedEventsArray.length].concat(_toConsumableArray(consentEvents),_toConsumableArray(nonConsentEvents)));};/**
890
+ * Retrieve any existing events that were triggered before SDK load and enqueue in buffer
891
+ */var retrievePreloadBufferEvents=function retrievePreloadBufferEvents(instance){var preloadedEventsArray=getExposedGlobal(GLOBAL_PRELOAD_BUFFER)||[];// Get events that are pre-populated via query string params
892
+ retrieveEventsFromQueryString(preloadedEventsArray);// Enqueue the non load events in the buffer of the global rudder analytics singleton
893
+ 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);}}};
894
+
895
+ var DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS=10*1000;// 10 seconds
896
+
897
+ var EXTERNAL_SOURCE_LOAD_ORIGIN='RS_JS_SDK';
898
+
899
+ /**
900
+ * Create the DOM element to load a script marked as RS SDK originated
901
+ *
902
+ * @param {*} url The URL of the script to be loaded
903
+ * @param {*} id ID for the script tag
904
+ * @param {*} async Whether to load the script in async mode. Defaults to `true` [optional]
905
+ * @param {*} onload callback to invoke onload [optional]
906
+ * @param {*} onerror callback to invoke onerror [optional]
907
+ * @param {*} extraAttributes key/value pair with html attributes to add in html tag [optional]
908
+ *
909
+ * @returns HTMLScriptElement
910
+ */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;};/**
911
+ * Add script DOM element to DOM
912
+ *
913
+ * @param {*} newScriptElement the script element to add
914
+ *
915
+ * @returns
916
+ */var insertScript=function insertScript(newScriptElement){var _scriptElements$;// First try to add it to the head
917
+ 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
918
+ 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
919
+ var headElement=document.createElement('head');headElement.appendChild(newScriptElement);var htmlElement=document.getElementsByTagName('html')[0];htmlElement===null||htmlElement===void 0||htmlElement.insertBefore(headElement,htmlElement.firstChild);};/**
920
+ * Loads external js file as a script html tag
921
+ *
922
+ * @param {*} url The URL of the script to be loaded
923
+ * @param {*} id ID for the script tag
924
+ * @param {*} timeout loading timeout
925
+ * @param {*} async Whether to load the script in async mode. Defaults to `true` [optional]
926
+ * @param {*} extraAttributes key/value pair with html attributes to add in html tag [optional]
927
+ *
928
+ * @returns
929
+ */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
930
+ insertScript(createScriptElement(url,id,async,onload,onerror,extraAttributes));// Reject on timeout
931
+ 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')));}});};
932
+
933
+ /**
934
+ * Service to load external resources/files
935
+ */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;}/**
936
+ * Load external resource of type javascript
937
+ */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);}});}}]);}();
938
+
939
+ 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;}
940
+
941
+ /**
942
+ * A buffer queue to serve as a store for any type of data
943
+ */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=[];}}]);}();
944
+
945
+ 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;';/**
946
+ * Service to log messages/data to output provider, default is console
947
+ */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
948
+ // to assist on the fly debugging?
949
+ },{key:"setMinLogLevel",value:function setMinLogLevel(logLevel){this.minLogLevel=LOG_LEVEL_MAP[logLevel];if(isUndefined(this.minLogLevel)){this.minLogLevel=LOG_LEVEL_MAP[DEFAULT_LOG_LEVEL];}}/**
950
+ * Formats the console message using `scope` and styles
951
+ */},{key:"formatLogData",value:function formatLogData(data){if(Array.isArray(data)&&data.length>0){// prefix SDK identifier
952
+ var msg="%c ".concat(LOG_MSG_PREFIX);// format the log message using `scope`
953
+ if(this.scope){msg="".concat(msg," - ").concat(this.scope);}// trim whitespaces for original message
954
+ var originalMsg=isString(data[0])?data[0].trim():'';// prepare the final message
955
+ msg="".concat(msg," %c ").concat(originalMsg);var styledLogArgs=[msg,LOG_MSG_PREFIX_STYLE,// add style for the prefix
956
+ LOG_MSG_STYLE// reset the style for the actual message
957
+ ];// add first it if it was not a string msg
958
+ if(!isString(data[0])){styledLogArgs.push(data[0]);}// append rest of the original arguments
959
+ styledLogArgs.push.apply(styledLogArgs,_toConsumableArray(data.slice(1)));return styledLogArgs;}return data;}}]);}();var defaultLogger=new Logger();
960
+
961
+ var ErrorType=/*#__PURE__*/function(ErrorType){ErrorType["HANDLEDEXCEPTION"]="handledException";ErrorType["UNHANDLEDEXCEPTION"]="unhandledException";ErrorType["UNHANDLEDREJECTION"]="unhandledPromiseRejection";return ErrorType;}({});
962
+
963
+ // default is v3
964
+ var SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','sessionStorage','none'];var DEFAULT_STORAGE_TYPE='cookieStorage';
965
+
966
+ 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
967
+ 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
968
+ 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.");};
969
+
970
+ var DEFAULT_INTEGRATIONS_CONFIG={All:true};
971
+
972
+ var CDN_INT_DIR='js-integrations';var CDN_PLUGINS_DIR='plugins';var URL_PATTERN=new RegExp('^(https?:\\/\\/)'+// protocol
973
+ '('+'((([a-zA-Z\\d]([a-zA-Z\\d-]*[a-zA-Z\\d])*)\\.)+[a-zA-Z]{2,}|'+// domain name
974
+ 'localhost|'+// localhost
975
+ '((25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9]?)\\.){3}'+// OR IP (v4) address first 3 octets
976
+ '(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9]?))'+// last octet of IP address
977
+ ')'+'(\\:\\d+)?'+// port
978
+ '(\\/[-a-zA-Z\\d%_.~+]*)*'+// path
979
+ '(\\?[;&a-zA-Z\\d%_.~+=-]*)?'+// query string
980
+ '(\\#[-a-zA-Z\\d_]*)?$')// fragment locator
981
+ ;
982
+
983
+ 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';
984
+
985
+ 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';
986
+
987
+ 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));
988
+
989
+ 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
990
+ anonymousId:false,initialReferrer:false,initialReferringDomain:false}});var SERVER_SIDE_COOKIES_DEBOUNCE_TIME=10;// milliseconds
991
+
992
+ 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)};
993
+
994
+ 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([])};
995
+
996
+ var reportingState={isErrorReportingEnabled:c(false),isMetricsReportingEnabled:c(false),breadcrumbs:c([])};
997
+
998
+ var sourceConfigState=c(undefined);
999
+
1000
+ 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)};
1001
+
1002
+ 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)};
1003
+
1004
+ var metricsState={retries:c(0),dropped:c(0),sent:c(0),queued:c(0),triggered:c(0),metricsServiceUrl:c(undefined)};
1005
+
1006
+ var getVariantValue=function getVariantValue(){// For CDN builds, use runtime window.rudderAnalyticsBuildType
1007
+ 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)};
1008
+
1009
+ var nativeDestinationsState={configuredDestinations:c([]),activeDestinations:c([]),loadOnlyIntegrations:c({}),failedDestinations:c([]),loadIntegration:c(true),initializedDestinations:c([]),clientDestinationsReady:c(false),integrationsConfig:c({})};
1010
+
1011
+ var eventBufferState={toBeProcessedArray:c([]),readyCallbacksArray:c([])};
1012
+
1013
+ var pluginsState={ready:c(false),loadedPlugins:c([]),failedPlugins:c([]),pluginsToLoadFromConfig:c([]),activePlugins:c([]),totalPluginsToLoad:c(0)};
1014
+
1015
+ var storageState={encryptionPluginName:c(undefined),migrate:c(false),type:c(undefined),cookie:c(undefined),entries:c({}),trulyAnonymousTracking:c(false)};
1016
+
1017
+ var serverSideCookiesState={isEnabledServerSideCookies:c(false),dataServiceUrl:c(undefined)};
1018
+
1019
+ var dataPlaneEventsState={eventsQueuePluginName:c(undefined),deliveryEnabled:c(true)// Delivery should always happen
1020
+ };
1021
+
1022
+ var autoTrackState={enabled:c(false),pageLifecycle:{enabled:c(false),pageViewId:c(undefined),pageLoadedTimestamp:c(undefined)}};
1023
+
1024
+ 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));
1025
+
1026
+ function getDefaultExportFromCjs (x) {
1027
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
1028
+ }
1029
+
1030
+ var errorStackParser$1 = {exports: {}};
1031
+
1032
+ var stackframe$1 = {exports: {}};
1033
+
1034
+ 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;}
1035
+
1036
+ 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 {/**
1037
+ * Given an Error object, extract the most information from it.
1038
+ *
1039
+ * @param {Error} error object
1040
+ * @return {Array} of StackFrames
1041
+ */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)
1042
+ extractLocation:function ErrorStackParser$$extractLocation(urlLike){// Fail-fast but return locations like "(native)"
1043
+ 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
1044
+ 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
1045
+ // case it has spaces in it, as the string is split on \s+ later on
1046
+ var location=sanitizedLine.match(/ (\(.+\)$)/);// remove the parenthesized location from the line, if it was matched
1047
+ sanitizedLine=location?sanitizedLine.replace(location[0],''):sanitizedLine;// if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine
1048
+ // because this line doesn't have function name
1049
+ 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
1050
+ 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
1051
+ 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
1052
+ 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;}
1053
+
1054
+ var errorStackParserExports = requireErrorStackParser();
1055
+ var ErrorStackParser = /*@__PURE__*/getDefaultExportFromCjs(errorStackParserExports);
1056
+
1057
+ var GLOBAL_CODE='global code';var normalizeFunctionName=function normalizeFunctionName(name){if(isDefined(name)){return /^global code$/i.test(name)?GLOBAL_CODE:name;}return name;};/**
1058
+ * Takes a stacktrace.js style stackframe (https://github.com/stacktracejs/stackframe)
1059
+ * and returns a Bugsnag compatible stackframe (https://docs.bugsnag.com/api/error-reporting/#json-payload)
1060
+ * @param frame
1061
+ * @returns
1062
+ */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:
1063
+ // - non-error exception thrown from global code in FF
1064
+ // This adds one.
1065
+ 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
1066
+ 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,[]);}};
1067
+
1068
+ /**
1069
+ * Utility to parse XHR JSON response
1070
+ */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;};
1071
+
1072
+ 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;
1073
+
1074
+ var DEFAULT_XHR_REQUEST_OPTIONS={headers:{Accept:'application/json','Content-Type':'application/json;charset=UTF-8'},method:'GET'};/**
1075
+ * Utility to create request configuration based on default options
1076
+ */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;};/**
1077
+ * Utility implementation of XHR, fetch cannot be used as it requires explicit
1078
+ * origin allowed values and not wildcard for CORS requests with credentials and
1079
+ * this is not supported by our sourceConfig API
1080
+ */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
1081
+ return;}}var xhr=new XMLHttpRequest();// eslint-disable-next-line @typescript-eslint/no-unused-vars
1082
+ 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
1083
+ // and the first call to the send method in legacy browsers
1084
+ 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});}});};
1085
+
1086
+ /**
1087
+ * Service to handle data communication with APIs
1088
+ */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;}/**
1089
+ * Implement requests in a blocking way
1090
+ */},{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;}()/**
1091
+ * Implement requests in a non-blocking way
1092
+ */)},{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);}});}/**
1093
+ * Handle errors
1094
+ */},{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});}/**
1095
+ * Set basic authentication header (eg writekey)
1096
+ */},{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);}/**
1097
+ * Clear basic authentication header
1098
+ */},{key:"resetAuthHeader",value:function resetAuthHeader(){this.basicAuthHeader=undefined;}}]);}();var defaultHttpClient=new HttpClient(defaultLogger);
1099
+
1100
+ var METRICS_PAYLOAD_VERSION='1';
1101
+
1102
+ // Errors from the below scripts are NOT allowed to reach Bugsnag
1103
+ var SDK_FILE_NAME_PREFIXES=function SDK_FILE_NAME_PREFIXES(){return ['rsa'// Prefix for all the SDK scripts including plugins and module federated chunks
1104
+ ];};var DEV_HOSTS=['www.test-host.com','localhost','127.0.0.1','[::1]'];// List of keys to exclude from the metadata
1105
+ // Potential PII or sensitive data
1106
+ var APP_STATE_EXCLUDE_KEYS=['userId','userTraits','groupId','groupTraits','anonymousId','config','integration',// integration instance objects
1107
+ 'eventBuffer',// pre-load event buffer (may contain PII)
1108
+ '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';
1109
+
1110
+ 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
1111
+ // Use source config URL here as it is very unlikely to be blocked by adblockers
1112
+ // Only the extra query param should make it vulnerable to adblockers
1113
+ // This will work even if the users proxies it.
1114
+ // The edge case where this doesn't work is when HEAD method is not allowed by the server (user's)
1115
+ 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
1116
+ 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
1117
+ // Often adblockers instead of blocking the request, they redirect it to an internal URL
1118
+ 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
1119
+ state.capabilities.isAdBlockerDetectionInProgress.value=false;// Re-throw the error to be handled by the caller
1120
+ throw err;}};
1121
+
1122
+ 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:{}};};/**
1123
+ * A function to get the Bugsnag release stage for the current environment
1124
+ * @param getHostName Optional function to get the hostname (primarily for testing)
1125
+ * @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)
1126
+ */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)}]};};/**
1127
+ * A function to check if adblockers are active. The promise's resolve function
1128
+ * is invoked with true if adblockers are not detected and false otherwise.
1129
+ * @param {ApplicationState} state The application state
1130
+ * @param {IHttpClient} httpClient The HTTP client instance
1131
+ * @param {Function} resolve The promise's resolve function
1132
+ */var checkIfAdBlockersAreActive=function checkIfAdBlockersAreActive(state,httpClient,resolve){// Initiate ad blocker detection if not done previously and not already in progress.
1133
+ if(isUndefined(state.capabilities.isAdBlocked.value)){if(state.capabilities.isAdBlockerDetectionInProgress.value===false){detectAdBlockers(httpClient);}// Wait for the detection to complete.
1134
+ var detectionDisposer=m(function(){if(isDefined(state.capabilities.isAdBlocked.value)){// If ad blocker is not detected, notify.
1135
+ resolve(state.capabilities.isAdBlocked.value===false);// Cleanup the effect.
1136
+ detectionDisposer();}});}else {// If ad blocker is not detected, notify.
1137
+ resolve(state.capabilities.isAdBlocked.value===false);}};/**
1138
+ * A function to determine whether the error should be promoted to notify or not.
1139
+ * For plugin and integration errors from RS CDN, if it is due to CSP blocked URLs or AdBlockers,
1140
+ * it will not be promoted to notify.
1141
+ * If it is due to other reasons, it will be promoted to notify.
1142
+ * @param {Error} exception The error object
1143
+ * @param {ApplicationState} state The application state
1144
+ * @param {IHttpClient} httpClient The HTTP client instance
1145
+ * @returns A promise that resolves to a boolean indicating whether the error should be promoted to notify or not
1146
+ */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.
1147
+ 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.
1148
+ if(state.capabilities.cspBlockedURLs.value.includes(extractedURL)){resolve(false);}else {// Filter out errors if adblockers are detected.
1149
+ checkIfAdBlockersAreActive(state,httpClient,resolve);}}else {// Filter out errors that are not from the RS CDN.
1150
+ resolve(false);}}else {// Allow the error to be notified if no URL could be extracted from the error message
1151
+ resolve(true);}}else {resolve(!ERROR_MESSAGES_TO_BE_FILTERED.some(function(e){return e.test(errMsg);}));}});};/**
1152
+ * A function to get the directory name from a file path.
1153
+ * @param {string} filePath The file path
1154
+ * @returns The directory name or undefined if the file path is invalid
1155
+ */var getDirectoryName=function getDirectoryName(filePath){if(!filePath){return undefined;}var paths=filePath.split('/');return paths.at(-2);};/**
1156
+ * A function to get the top stack path from the exception.
1157
+ * @param {Exception} exception The exception object
1158
+ * @returns The top stack path or undefined if the exception is invalid
1159
+ */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;};/**
1160
+ * A function to determine if the error is from Rudder SDK
1161
+ * @param {Error} exception
1162
+ * @returns
1163
+ */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);};/**
1164
+ * A function to get the grouping hash value to be used for the error event.
1165
+ * If the grouping hash is an error instance, the normalized error message is used as the grouping hash.
1166
+ * If the grouping hash is an empty string or not specified, the default grouping hash is used.
1167
+ * If the grouping hash is a string, it is used as is.
1168
+ * @param curErrGroupingHash The grouping hash value part of the error event
1169
+ * @param defaultGroupingHash The default grouping hash value. It is the error message.
1170
+ * @param logger The logger instance
1171
+ * @returns The final grouping hash value to be used for the error event
1172
+ */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;};
1173
+
1174
+ /**
1175
+ * A service to handle errors
1176
+ */var ErrorHandler=/*#__PURE__*/function(){// If no logger is passed errors will be thrown as unhandled error
1177
+ function ErrorHandler(httpClient,logger){_classCallCheck(this,ErrorHandler);_defineProperty(this,"initialized",false);this.httpClient=httpClient;this.logger=logger;}/**
1178
+ * Initializes the error handler by attaching global error listeners.
1179
+ * This method should be called once after construction.
1180
+ */return _createClass(ErrorHandler,[{key:"init",value:function init(){if(this.initialized){return;}this.attachErrorListeners();this.initialized=true;}/**
1181
+ * Attach error listeners to the global window object
1182
+ */},{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
1183
+ // if those URLs are from RS CDN.
1184
+ 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]);}});}/**
1185
+ * Handle errors
1186
+ * @param errorInfo - The error information
1187
+ * @param errorInfo.error - The error to handle
1188
+ * @param errorInfo.context - The context of where the error occurred
1189
+ * @param errorInfo.customMessage - The custom message of the error
1190
+ * @param errorInfo.errorType - The type of the error (handled or unhandled)
1191
+ * @param errorInfo.groupingHash - The grouping hash of the error
1192
+ * @param errorInfo.category - The category of the error (sdk or integrations)
1193
+ */},{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.
1194
+ // In case of NPM installations, the unhandled errors from the SDK cannot be identified
1195
+ // and will NOT be reported unless they occur in plugins or integrations.
1196
+ 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.
1197
+ // In case of NPM installations, the default grouping by surrounding code
1198
+ // does not make sense as each user application is different and will create a lot of noise in the alerts.
1199
+ // References:
1200
+ // https://docs.bugsnag.com/platforms/javascript/customizing-error-reports/#groupinghash
1201
+ // https://docs.bugsnag.com/product/error-grouping/#user_defined
1202
+ normalizedGroupingHash=getErrorGroupingHash(groupingHash,bsException.message,this.logger);// Get the final payload to be sent to the metrics service
1203
+ bugsnagPayload=getBugsnagErrorEvent(bsException,errorState,state,normalizedGroupingHash);errorCategory=getErrorCategory(bsException,category);// send it to metrics service
1204
+ 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
1205
+ 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
1206
+ 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;}()/**
1207
+ * Add breadcrumbs to add insight of a user's journey before an error
1208
+ * occurred and send to external error monitoring service via a plugin
1209
+ *
1210
+ * @param {string} breadcrumb breadcrumbs message
1211
+ */)},{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
1212
+ var defaultErrorHandler=new ErrorHandler(defaultHttpClient,defaultLogger);
1213
+
1214
+ // to next or return the value if it is the last one instead of an array per
1215
+ // plugin that is the normal invoke
1216
+ // TODO: add invoke method for extension point that we know only one plugin can be used. add invokeMultiple and invokeSingle methods
1217
+ 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.
1218
+ 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
1219
+ // do some unified pre-process before application starts.
1220
+ },{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
1221
+ 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
1222
+ 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});
1223
+
1224
+ /**
1225
+ * A function to filter and return non cloud mode destinations
1226
+ * A destination is considered non cloud mode if it is not a cloud mode destination or if it is a hybrid mode destination
1227
+ * @param destination
1228
+ *
1229
+ * @returns boolean
1230
+ */var isNonCloudDestination=function isNonCloudDestination(destination){return Boolean(destination.config.connectionMode!=='cloud'||destination.config.useNativeSDKToSend===true||// this is the older flag for hybrid mode destinations
1231
+ destination.config.useNativeSDK===true);};var isHybridModeDestination=function isHybridModeDestination(destination){return Boolean(destination.config.connectionMode==='hybrid'||destination.config.useNativeSDKToSend===true);};/**
1232
+ * A function to filter and return non cloud mode destinations
1233
+ * @param destinations
1234
+ *
1235
+ * @returns destinations
1236
+ */var getNonCloudDestinations=function getNonCloudDestinations(destinations){return destinations.filter(isNonCloudDestination);};/**
1237
+ * A function to get the user friendly id for a destination
1238
+ * Replaces all spaces with hyphens and appends the id to the display name
1239
+ * @param displayName The display name of the destination
1240
+ * @param id The id of the destination
1241
+ *
1242
+ * @returns the user friendly id
1243
+ */var getDestinationUserFriendlyId=function getDestinationUserFriendlyId(displayName,id){return "".concat(displayName.replaceAll(' ','-'),"___").concat(id);};
1244
+
1245
+ /**
1246
+ * List of plugin names that are loaded as dynamic imports in modern builds
1247
+ */var pluginNamesList=['BeaconQueue','CustomConsentManager','DeviceModeDestinations','DeviceModeTransformation','ExternalAnonymousId','GoogleLinker','IubendaConsentManager','KetchConsentManager','NativeDestinationQueue','OneTrustConsentManager','StorageEncryption','StorageEncryptionLegacy','StorageMigrator','XhrQueue'];var deprecatedPluginsList=['Bugsnag','ErrorReporting'];
1248
+
1249
+ var CUSTOM_CONSENT_MANAGER_PLUGIN='CustomConsentManagerPlugin';
1250
+
1251
+ var DESTINATION_CONSENT_STATUS_ERROR$3="Failed to determine the consent status for the destination. Please check the destination configuration and try again.";
1252
+
1253
+ 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
1254
+ },updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){// Nothing to update. Already provided by the user
1255
+ },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.
1256
+ if(!consentManagement){return true;}// Get the corresponding consents for the destination
1257
+ 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.
1258
+ 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
1259
+ // the configured resolution strategy
1260
+ 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;}}}};};
1261
+
1262
+ var externallyLoadedSessionStorageKeys={segment:'ajs_anonymous_id'};
1263
+
1264
+ 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';
1265
+
1266
+ var removeDuplicateSlashes=function removeDuplicateSlashes(str){return str.replace(/\/{2,}/g,'/');};/**
1267
+ * Checks if provided url is valid or not
1268
+ * @param url
1269
+ * @returns true if `url` is valid and false otherwise
1270
+ */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
1271
+ // Otherwise, we can at least check if the URL matches the pattern
1272
+ if(isFunction(globalThis.URL)){// eslint-disable-next-line no-new
1273
+ new URL(url);}return URL_PATTERN.test(url);}catch(e){return false;}};
1274
+
1275
+ /**
1276
+ * This function is used to determine if the input status code is retryable.
1277
+ * @param status - The status code.
1278
+ * @returns True if the status code is not 4xx (except 429), false otherwise.
1279
+ */var isErrRetryable=function isErrRetryable(status){if(status===429){return true;}return !(status>=400&&status<500);};
1280
+
1281
+ /**
1282
+ * Encode.
1283
+ */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;}};/**
1284
+ * Decode
1285
+ */var decode=function decode(value){try{return decodeURIComponent(value);}catch(err){// Do nothing as non-RS SDK cookies may not be URI encoded
1286
+ return undefined;}};/**
1287
+ * Parse cookie `str`
1288
+ */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
1289
+ 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;};/**
1290
+ * Set cookie `name` to `value`
1291
+ */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;};/**
1292
+ * Return all cookies
1293
+ */var all=function all(){var cookieStringValue=globalThis.document.cookie;return parse(cookieStringValue);};/**
1294
+ * Get cookie `name`
1295
+ */var get=function get(name){return all()[name];};/**
1296
+ * Set or get cookie `name` with `value` and `options` object
1297
+ */// eslint-disable-next-line func-names
1298
+ 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();}};
1299
+
1300
+ 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_';
1301
+
1302
+ 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;};
1303
+
1304
+ var EVENT_PAYLOAD_SIZE_BYTES_LIMIT=32*1024;// 32 KB
1305
+ var RETRY_REASON_CLIENT_NETWORK='client-network';var RETRY_REASON_CLIENT_TIMEOUT='client-timeout';var DEFAULT_RETRY_REASON=RETRY_REASON_CLIENT_NETWORK;
1306
+
1307
+ var isStorageQuotaExceeded=function isStorageQuotaExceeded(e){var matchingNames=['QuotaExceededError','NS_ERROR_DOM_QUOTA_REACHED'];// Everything except Firefox, Firefox
1308
+ var matchingCodes=[22,1014];if(e instanceof DOMException){return matchingNames.includes(e.name)||matchingCodes.includes(e.code);}return false;};// TODO: also check for SecurityErrors
1309
+ // https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage#exceptions
1310
+ 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
1311
+ 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
1312
+ return false;};
1313
+
1314
+ 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';/**
1315
+ * Utility to get the stringified event payload
1316
+ * @param event RudderEvent object
1317
+ * @param logger Logger instance
1318
+ * @returns stringified event payload. Empty string if error occurs.
1319
+ */var getDeliveryPayload=function getDeliveryPayload(event,logger){return stringifyWithoutCircular(event,true,undefined,logger);};/**
1320
+ * Utility to validate final payload size before sending to server
1321
+ * @param event RudderEvent object
1322
+ * @param logger Logger instance
1323
+ */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));}};/**
1324
+ * Mutates the event and return final event for delivery
1325
+ * Updates certain parameters like sentAt timestamp, integrations config etc.
1326
+ * @param event RudderEvent object
1327
+ * @returns Final event ready to be delivered
1328
+ */var getFinalEventForDeliveryMutator=function getFinalEventForDeliveryMutator(event,currentTime){var finalEvent=clone(event);// Update sentAt timestamp to the latest timestamp
1329
+ finalEvent.sentAt=currentTime;return finalEvent;};/**
1330
+ * Utility to get the storage type for events persistence
1331
+ * If local storage is available, use it; else, fall back to session storage; else, fall back to memory storage.
1332
+ * On some browsers, persistence storage is blocked for the JS SDK that is loaded from RS domains.
1333
+ * In such cases, we need to verify all the storage types and use the first one that is available.
1334
+ * @param logger Logger instance for logging storage availability warnings
1335
+ * @returns StorageType
1336
+ */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.
1337
+ // Note that events will not be persisted across page reloads in this case.
1338
+ return MEMORY_STORAGE;};
1339
+
1340
+ var QueueStatuses={IN_PROGRESS:'inProgress',QUEUE:'queue',RECLAIM_START:'reclaimStart',RECLAIM_END:'reclaimEnd',ACK:'ack',BATCH_QUEUE:'batchQueue'};
1341
+
1342
+ var getSegmentAnonymousId=function getSegmentAnonymousId(getStorageEngine){var anonymousId;/**
1343
+ * First check the local storage for anonymousId
1344
+ * Ref: https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/#identify
1345
+ */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
1346
+ var csEngine=getStorageEngine(COOKIE_STORAGE);if(!anonymousId&&csEngine!==null&&csEngine!==void 0&&csEngine.isEnabled){anonymousId=csEngine.getItem(externallyLoadedSessionStorageKeys.segment);}return anonymousId;};
1347
+
1348
+ 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
1349
+ switch(source){case 'segment':anonymousId=getSegmentAnonymousId(getStorageEngine);break;}}return anonymousId;}}};};
1350
+
1351
+ 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.";
1352
+
1353
+ var IUBENDA_CONSENT_MANAGER_PLUGIN='IubendaConsentManagerPlugin';var IUBENDA_CONSENT_COOKIE_NAME_PATTERN=/^_iub_cs-\d+$/;
1354
+
1355
+ var getIubendaCookieName=function getIubendaCookieName(logger){try{// Retrieve cookies as a string and split them into an array
1356
+ var cookies=document.cookie.split('; ');// Find the cookie that matches the iubenda cookie pattern
1357
+ 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
1358
+ 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 '';}};/**
1359
+ * Gets the consent data from the Iubenda's consent cookie
1360
+ * @param storeManager Store manager instance
1361
+ * @param logger Logger instance
1362
+ * @returns Consent data from the consent cookie
1363
+ */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
1364
+ 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
1365
+ var consentPurposes=consentCookieData.purposes;return consentPurposes;};/**
1366
+ * Gets the consent data in the format expected by the application state
1367
+ * @param iubendaConsentData Consent data derived from the consent cookie
1368
+ * @returns Consent data
1369
+ */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;};
1370
+
1371
+ 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
1372
+ // This will be helpful for debugging
1373
+ 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
1374
+ // This will be helpful for debugging
1375
+ 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
1376
+ globalThis.updateIubendaConsent=function(iubendaConsentData){updateConsentStateFromData$1(state,iubendaConsentData);};},updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){// retrieve consent data and update the state
1377
+ var iubendaConsentData;// From window
1378
+ if(!isUndefined(globalThis._iub.cs.consent.purposes)){iubendaConsentData=globalThis._iub.cs.consent.purposes;// From cookie
1379
+ }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.
1380
+ if(consentManagement){var _cmpConfig$resolution;// Get the corresponding consents for the destination
1381
+ 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.
1382
+ 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
1383
+ // the configured resolution strategy
1384
+ 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;}}}};};
1385
+
1386
+ 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.";
1387
+
1388
+ var KETCH_CONSENT_MANAGER_PLUGIN='KetchConsentManagerPlugin';var KETCH_CONSENT_COOKIE_NAME_V1='_ketch_consent_v1_';
1389
+
1390
+ /**
1391
+ * Gets the consent data from the Ketch's consent cookie
1392
+ * @param storeManager Store manager instance
1393
+ * @param logger Logger instance
1394
+ * @returns Consent data from the consent cookie
1395
+ */var getKetchConsentData=function getKetchConsentData(storeManager,logger){var rawConsentCookieData=null;try{// Create a data store instance to read the consent cookie
1396
+ 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
1397
+ 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
1398
+ 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;};/**
1399
+ * Gets the consent data in the format expected by the application state
1400
+ * @param ketchConsentData Consent data derived from the consent cookie
1401
+ * @returns Consent data
1402
+ */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;};
1403
+
1404
+ 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
1405
+ // This will be helpful for debugging
1406
+ 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
1407
+ // This will be helpful for debugging
1408
+ 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
1409
+ // this will be called from ketch rudderstack plugin
1410
+ globalThis.updateKetchConsent=function(ketchConsentData){updateConsentStateFromData(state,ketchConsentData);};},updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){// retrieve consent data and update the state
1411
+ 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
1412
+ if(consentManagement){var _consentManagement$fi;// Get the corresponding consents for the destination
1413
+ 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.
1414
+ 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
1415
+ // the configured resolution strategy
1416
+ 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
1417
+ // TODO: To be removed once the source config API is updated to support generic consent management
1418
+ }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.
1419
+ return _configuredConsents.some(matchPredicate)||_configuredConsents.length===0;}// If there are no consents configured for the destination for the current provider, events should be sent.
1420
+ 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;}}}};};
1421
+
1422
+ 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.";
1423
+
1424
+ var ONETRUST_CONSENT_MANAGER_PLUGIN='OneTrustConsentManagerPlugin';
1425
+
1426
+ 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
1427
+ },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.
1428
+ var oneTrustAllGroupsInfo=globalThis.OneTrust.GetDomainData().Groups;// OneTrustConsentManager SDK populates a data layer object OnetrustActiveGroups with
1429
+ // the cookie categories Ids that the user has consented to.
1430
+ // Eg: ',C0001,C0003,'
1431
+ // We split it and save it as an array.
1432
+ 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
1433
+ var oneTrustCookieCategories=destConfig.oneTrustCookieCategories,consentManagement=destConfig.consentManagement;var matchPredicate=function matchPredicate(consent){return allowedConsentIds.includes(consent);};// Generic consent management
1434
+ if(consentManagement){var _consentManagement$fi;// Get the corresponding consents for the destination
1435
+ 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.
1436
+ 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
1437
+ // the configured resolution strategy
1438
+ 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
1439
+ // TODO: To be removed once the source config API is updated to support generic consent management
1440
+ }else if(oneTrustCookieCategories){// Change the structure of oneTrustConsentGroup as an array and filter values if empty string
1441
+ // Eg:
1442
+ // ["Performance Cookies", "Functional Cookies"]
1443
+ 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.
1444
+ return _configuredConsents.every(matchPredicate);}// If there are no consents configured for the destination for the current provider, events should be sent.
1445
+ 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;}}}};};
1446
+
1447
+ 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);}}};};
1448
+
1449
+ var DEFAULT_RETRY_QUEUE_OPTIONS={maxRetryDelay:360000,minRetryDelay:1000,backoffFactor:2,maxAttempts:10,maxItems:100};var REQUEST_TIMEOUT_MS=30*1000;// 30 seconds
1450
+ var DATA_PLANE_API_VERSION='v1';var QUEUE_NAME='rudder';var XHR_QUEUE_PLUGIN='XhrQueuePlugin';
1451
+
1452
+ 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,".");};
1453
+
1454
+ 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
1455
+ logger.warn(logMsg);}else {logger.error("".concat(logMsg," Retries exhausted (").concat(qItemProcessInfo.maxRetryAttempts,"). ").concat(dropMsg));}}else {// Use error for non-retryable failures
1456
+ 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
1457
+ // The same value is added in the event payload as well
1458
+ headers.SentAt=currentTime;// Add a header to indicate if the item has been reclaimed from
1459
+ // local storage
1460
+ if(qItemProcessInfo.reclaimed){headers['Rsa-Recovered']='true';}// Add retry headers if the item is being retried for delivery
1461
+ if(qItemProcessInfo.retryAttemptNumber>0){// The number of times this item has been attempted to retry
1462
+ headers['Rsa-Retry-Attempt']=qItemProcessInfo.retryAttemptNumber.toString();// The number of milliseconds since the last attempt
1463
+ headers['Rsa-Since-Last-Attempt']=qItemProcessInfo.timeSinceLastAttempt.toString();// The number of milliseconds since the first attempt
1464
+ headers['Rsa-Since-First-Attempt']=qItemProcessInfo.timeSinceFirstAttempt.toString();// The reason for the retry
1465
+ headers['Rsa-Retry-Reason']=qItemProcessInfo.retryReason;}return {data:data,headers:headers,url:url};};
1466
+
1467
+ 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={};}}]);}();
1468
+
1469
+ 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,".");};
1470
+
1471
+ 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
1472
+ var DEFAULT_MAX_BATCH_ITEMS=100;var DEFAULT_BATCH_FLUSH_INTERVAL_MS=60*1000;// 1 minutes
1473
+ var BATCH_QUEUE_ITEM_TYPE='Batch';var SINGLE_QUEUE_ITEM_TYPE='Single';
1474
+
1475
+ var sortByTime=function sortByTime(a,b){return a.time-b.time;};var RETRY_QUEUE='RetryQueue';var RetryQueue=/*#__PURE__*/function(){/**
1476
+ * Constructs a RetryQueue backed by localStorage
1477
+ *
1478
+ * @param {String} name The name of the queue. Will be used to find abandoned queues and retry their items
1479
+ * @param {QueueOpts} [options] Optional argument to override `maxItems`, `maxAttempts`, `minRetryDelay, `maxRetryDelay`, `backoffFactor` and `backoffJitter`.
1480
+ * @param {QueueProcessCallback} queueProcessCb The function to call in order to process an item added to the queue
1481
+ * @param {IStoreManager} storeManager The store manager instance to use
1482
+ * @param {StorageType} [storageType] The storage type to use. Defaults to LOCAL_STORAGE
1483
+ * @param {ILogger} [logger] The logger to use
1484
+ * @param {QueueBatchItemsSizeCalculatorCallback} [queueBatchItemsSizeCalculatorCb] The callback to use to calculate the size of items in the batch queue
1485
+ */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
1486
+ 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
1487
+ timerScaleFactor=Math.min(timerScaleFactor,MAX_TIMER_SCALE_FACTOR);// painstakingly tuned. that's why they're not "easily" configurable
1488
+ 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
1489
+ 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
1490
+ 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
1491
+ 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
1492
+ 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
1493
+ },{key:"setStorageEntry",value:function setStorageEntry(name,value){if(isNullOrUndefined(value)){this.store.remove(name);}else {this.store.set(name,value);}}/**
1494
+ * Stops processing the queue
1495
+ */},{key:"stop",value:function stop(){this.schedule.cancelAll();this.scheduleTimeoutActive=false;}/**
1496
+ * Starts processing the queue
1497
+ */},{key:"start",value:function start(){if(this.scheduleTimeoutActive){this.stop();}this.scheduleTimeoutActive=true;this.scheduleFlushBatch();this.ack();this.checkReclaim();this.processHead();}/**
1498
+ * Configures the timeout handler for flushing the batch queue
1499
+ */},{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);}}/**
1500
+ * Flushes the batch queue
1501
+ */},{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
1502
+ this.scheduleFlushBatch();}}/**
1503
+ * Decides whether to retry. Overridable.
1504
+ *
1505
+ * @param {Object} item The item being processed
1506
+ * @param {Number} attemptNumber The attemptNumber (1 for first retry)
1507
+ * @return {Boolean} Whether to requeue the message
1508
+ */},{key:"shouldRetry",value:function shouldRetry(item,attemptNumber){return attemptNumber<=this.maxAttempts;}/**
1509
+ * Calculates the delay (in ms) for a retry attempt
1510
+ *
1511
+ * @param {Number} attemptNumber The attemptNumber (1 for first retry)
1512
+ * @return {Number} The delay in milliseconds to wait before attempting a retry
1513
+ */},{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
1514
+ if(curEntry){this.pushToMainQueue(curEntry);}}/**
1515
+ * Handles a new item added to the retry queue when batching is enabled
1516
+ * @param entry New item added to the retry queue
1517
+ * @returns Undefined or batch entry object
1518
+ */},{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
1519
+ 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
1520
+ 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
1521
+ this.scheduleFlushBatch();}this.batchingInProgress=false;}else {batchQueue.push(entry);}// update the batch queue
1522
+ 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();}}/**
1523
+ * Adds an item to the queue
1524
+ *
1525
+ * @param {Object} itemData The item to process
1526
+ */},{key:"addItem",value:function addItem(itemData){this.enqueue(this.genQueueItem(itemData));}/**
1527
+ * Generates a queue item
1528
+ * @param itemData Queue item data
1529
+ * @returns Queue item
1530
+ */},{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}:{});}/**
1531
+ * Adds an item to the retry queue
1532
+ *
1533
+ * @param {Object} qItem The item to process
1534
+ */},{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
1535
+ 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});}}/**
1536
+ * Returns the information about whether the batch criteria is met or exceeded
1537
+ * @param batchItems Prospective batch items
1538
+ * @returns Batch dispatch info
1539
+ */},{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
1540
+ this.schedule.cancel(this.processId);// Pop the head off the queue
1541
+ 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
1542
+ 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
1543
+ 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
1544
+ 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
1545
+ 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
1546
+ reclaimed=(_inProgressItem$recla=inProgressItem.reclaimed)!==null&&_inProgressItem$recla!==void 0?_inProgressItem$recla:reclaimed;// Update the first attempted at timestamp for the in progress item
1547
+ inProgressItem.firstAttemptedAt=firstAttemptedAt;// Update the last attempted at to current timestamp for the in progress item
1548
+ inProgressItem.lastAttemptedAt=_now;_inProgress[el.id]=inProgressItem;_this.setStorageEntry(QueueStatuses.IN_PROGRESS,_inProgress);}// A decimal integer representing the milliseconds since the first attempt
1549
+ var timeSinceFirstAttempt=_now-firstAttemptedAt;// A decimal integer representing the milliseconds since the last attempt
1550
+ 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
1551
+ 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
1552
+ // after the max attempts are exhausted
1553
+ 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
1554
+ 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
1555
+ },{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
1556
+ // After some point, we can remove this hack as most of the stale data will have been processed
1557
+ // and the new entries will have the type field set
1558
+ 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
1559
+ 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#
1560
+ addConcatQueue(their.queue,0);// Process batch queue items
1561
+ 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
1562
+ 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
1563
+ addConcatQueue(their.batchQueue,0);}// if the queue is abandoned, all the in-progress are failed. retry them immediately and increment the attempt#
1564
+ 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
1565
+ this.clearQueueEntries(other,1);// process the new items we claimed
1566
+ 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
1567
+ 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
1568
+ _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
1569
+ 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
1570
+ // Hence, we need this backward compatibility check
1571
+ 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();}}]);}();
1572
+
1573
+ 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:{/**
1574
+ * Initialize the queue for delivery
1575
+ * @param state Application state
1576
+ * @param httpClient http client instance
1577
+ * @param storeManager Store Manager instance
1578
+ * @param errorHandler Error handler instance
1579
+ * @param logger Logger instance
1580
+ * @returns RetryQueue instance
1581
+ */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
1582
+ "".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
1583
+ 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)
1584
+ 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)
1585
+ 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
1586
+ return (_getBatchDeliveryPayl=getBatchDeliveryPayload(events,currentTime,logger))===null||_getBatchDeliveryPayl===void 0?void 0:_getBatchDeliveryPayl.length;});return eventsQueue;},/**
1587
+ * Add event to the queue for delivery
1588
+ * @param state Application state
1589
+ * @param eventsQueue RetryQueue instance
1590
+ * @param event RudderEvent object
1591
+ * @param errorHandler Error handler instance
1592
+ * @param logger Logger instance
1593
+ * @returns none
1594
+ */enqueue:function enqueue(state,eventsQueue,event,errorHandler,logger){// sentAt is only added here for the validation step
1595
+ // It'll be updated to the latest timestamp during actual delivery
1596
+ 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
1597
+ // Auth header is added during initialization
1598
+ var headers={// To maintain event ordering while using the HTTP API as per is documentation,
1599
+ // make sure to include anonymousId as a header
1600
+ AnonymousId:toBase64(event.anonymousId)};eventsQueue.addItem({url:url,headers:headers,event:event});}}};};
1601
+
1602
+ /**
1603
+ * Map plugin names to direct code imports from plugins package
1604
+ */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};};
1605
+
1606
+ /**
1607
+ * Map of mandatory plugin names and direct imports
1608
+ */var getMandatoryPluginsMap=function getMandatoryPluginsMap(){return {};};/**
1609
+ * Map of optional plugin names and direct imports for legacy builds
1610
+ */var getOptionalPluginsMap=function getOptionalPluginsMap(){return getBundledBuildPluginImports();};/**
1611
+ * Map of optional plugin names and dynamic imports for modern builds
1612
+ */var getRemotePluginsMap=function getRemotePluginsMap(activePluginNames){{return {};}};var pluginsInventory=_objectSpread2(_objectSpread2({},getMandatoryPluginsMap()),getOptionalPluginsMap());var remotePluginsInventory=function remotePluginsInventory(activePluginNames){return _objectSpread2({},getRemotePluginsMap());};
1613
+
1614
+ // TODO: add retry mechanism for getting remote plugins
1615
+ // TODO: add timeout error mechanism for marking remote plugins that failed to load as failed in state
1616
+ 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);}/**
1617
+ * Orchestrate the plugin loading and registering
1618
+ */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
1619
+ this.setActivePlugins();this.registerLocalPlugins();this.registerRemotePlugins();this.attachEffects();}/**
1620
+ * Update state based on plugin loaded status
1621
+ */// eslint-disable-next-line class-methods-use-this
1622
+ },{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.
1623
+ // Should we stop here or should we progress?
1624
+ state.lifecycle.status.value='pluginsReady';});}});}/**
1625
+ * Determine the list of plugins that should be loaded based on sourceConfig & load options
1626
+ */// eslint-disable-next-line class-methods-use-this
1627
+ },{key:"getPluginsToLoadBasedOnConfig",value:function getPluginsToLoadBasedOnConfig(){var _this=this;// This contains the default plugins if load option has been omitted by user
1628
+ var pluginsToLoadFromConfig=state.plugins.pluginsToLoadFromConfig.value;if(!pluginsToLoadFromConfig){return [];}// Filter deprecated plugins
1629
+ 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
1630
+ );_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));}}/**
1631
+ * Determine the list of plugins that should be activated
1632
+ */},{key:"setActivePlugins",value:function setActivePlugins(){var pluginsToLoad=this.getPluginsToLoadBasedOnConfig();// Merging available mandatory and optional plugin name list
1633
+ 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;});}/**
1634
+ * Register plugins that are direct imports to PluginEngine
1635
+ */},{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));}}/**
1636
+ * Register plugins that are dynamic imports to PluginEngine
1637
+ */},{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
1638
+ 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);});}/**
1639
+ * Extension point invoke that allows multiple plugins to be registered to it with error handling
1640
+ */},{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 [];}}/**
1641
+ * Extension point invoke that allows a single plugin to be registered to it with error handling
1642
+ */},{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;}}/**
1643
+ * Plugin engine register with error handling
1644
+ */},{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
1645
+ },{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,"\""));}});}/**
1646
+ * Handle errors
1647
+ */},{key:"onError",value:function onError(error,customMessage,groupingHash){this.errorHandler.onError({error:error,context:PLUGINS_MANAGER,customMessage:customMessage,groupingHash:groupingHash});}}]);}();
1648
+
1649
+ 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'];
1650
+
1651
+ 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);
1652
+
1653
+ var legacyGetHostname=function legacyGetHostname(href){var l=document.createElement('a');l.href=href;return l.hostname;};/**
1654
+ * Levels returns all levels of the given url
1655
+ *
1656
+ * The method returns an empty array when the hostname is an ip.
1657
+ */var levelsFunc=function levelsFunc(url){var _host$split;// This is called before the polyfills load thus new URL cannot be used
1658
+ 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.
1659
+ if(parts.length===4&&last&&last===parseInt(last,10).toString()){return levels;}// Localhost.
1660
+ if(parts.length<=1){// Fix to support localhost
1661
+ if(parts[0]&&parts[0].indexOf('localhost')!==-1){return ['localhost'];}return levels;}// Create levels.
1662
+ for(var i=parts.length-2;i>=0;i-=1){levels.push(parts.slice(i).join('.'));}return levels;};/**
1663
+ * Get the top domain.
1664
+ *
1665
+ * The function constructs the levels of domain and attempts to set a global
1666
+ * cookie on each one when it succeeds it returns the top level domain.
1667
+ *
1668
+ * The method returns an empty string when the hostname is an ip.
1669
+ */var domain=function domain(url){var levels=levelsFunc(url);// Lookup the real top level one.
1670
+ // eslint-disable-next-line unicorn/no-for-loop
1671
+ 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
1672
+ cookie(cname,1,opts);// If successful
1673
+ if(cookie(cname)){// Remove cookie from domain
1674
+ cookie(cname,null,opts);return _domain;}}catch(_unused){// Silently continue to next domain level if cookie access is restricted or setting fails
1675
+ // Best-effort cleanup to avoid leaking the test cookie
1676
+ try{cookie(cname,null,opts);}catch(_unused2){// Ignore if we are unable to delete the cookie
1677
+ }}}return '';};
1678
+
1679
+ 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};};
1680
+
1681
+ /**
1682
+ * A storage utility to retain values in memory via Storage interface
1683
+ */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);
1684
+
1685
+ var store$2 = {exports: {}};
1686
+
1687
+ 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
1688
+ // Error: QuotaExceededError
1689
+ function dealIncognito(storage){var _KEY='_Is_Incognit',_VALUE='yes';try{// NOTE: set default storage when not passed in
1690
+ 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
1691
+ 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
1692
+ 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;}
1693
+
1694
+ var storeExports = requireStore();
1695
+ var store = /*@__PURE__*/getDefaultExportFromCjs(storeExports);
1696
+
1697
+ // check if the get, set overloads and search methods are used at all
1698
+ // if we do, ensure we provide types to support overloads as per storejs docs
1699
+ // https://www.npmjs.com/package/storejs
1700
+ /**
1701
+ * A storage utility to persist values in localstorage via Storage interface
1702
+ */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
1703
+ },{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
1704
+ },{key:"keys",value:function keys(){return store.keys();}}]);}();var defaultLocalStorage=new LocalStorage(defaultLogger);
1705
+
1706
+ /**
1707
+ * A storage utility to persist values in SessionStorage via Storage interface
1708
+ */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
1709
+ 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);
1710
+
1711
+ /**
1712
+ * A storage utility to persist values in cookies via Storage interface
1713
+ */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
1714
+ },{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
1715
+ },{key:"clear",value:function clear(){// Not implemented
1716
+ // getting a list of all cookie storage keys and remove all values
1717
+ // sounds risky to do as it will take on all top domain cookies
1718
+ // better to explicitly clear specific ones if needed
1719
+ }},{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
1720
+ },{key:"keys",value:function keys(){return Object.keys(cookie());}}]);}();var defaultCookieStorage=new CookieStorage(defaultLogger);
1721
+
1722
+ /**
1723
+ * A utility to retrieve the storage singleton instance by type
1724
+ */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;}};/**
1725
+ * Configure cookie storage singleton
1726
+ */var configureCookieStorageEngine=function configureCookieStorageEngine(options){var cookieStorageOptions=defaultCookieStorage.configure(options);// Update the state with the final cookie storage options
1727
+ state.storage.cookie.value={maxage:cookieStorageOptions.maxage,path:cookieStorageOptions.path,domain:cookieStorageOptions.domain,samesite:cookieStorageOptions.samesite,expires:cookieStorageOptions.expires,secure:cookieStorageOptions.secure};};/**
1728
+ * Configure local storage singleton
1729
+ */var configureLocalStorageEngine=function configureLocalStorageEngine(options){defaultLocalStorage.configure(options);};/**
1730
+ * Configure in memory storage singleton
1731
+ */var configureInMemoryStorageEngine=function configureInMemoryStorageEngine(options){defaultInMemoryStorage.configure(options);};/**
1732
+ * Configure session storage singleton
1733
+ */var configureSessionStorageEngine=function configureSessionStorageEngine(options){defaultSessionStorage.configure(options);};/**
1734
+ * Configure all storage singleton instances
1735
+ */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);};
1736
+
1737
+ /**
1738
+ * Store Implementation with dedicated storage
1739
+ */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;}/**
1740
+ * Ensure the key is valid and with correct format
1741
+ */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
1742
+ var compoundKey;Object.values(validKeys).forEach(function(validKeyName){if(validKeyName===key){compoundKey=noCompoundKey?key:[name,id,key].join('.');}});return compoundKey;}/**
1743
+ * Switch to inMemoryEngine, bringing any existing data with.
1744
+ */},{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
1745
+ // better to keep other queues in localstorage to be flushed later
1746
+ // than to pull them into memory and remove them from durable storage
1747
+ 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
1748
+ // if cookies are not available and localstorage is full?
1749
+ _this.remove(key);});this.engine=inMemoryStorage;}/**
1750
+ * Set value by key.
1751
+ */},{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
1752
+ 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
1753
+ this.swapQueueStoreToInMemoryEngine();// and save it there
1754
+ this.set(key,value);}else {var customMessage=STORE_DATA_SAVE_ERROR(key);this.onError(err,customMessage,customMessage);}}}/**
1755
+ * Get by Key.
1756
+ */},{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
1757
+ 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
1758
+ 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;}}/**
1759
+ * Remove by Key.
1760
+ */},{key:"remove",value:function remove(key){var validKey=this.createValidKey(key);if(validKey){this.engine.removeItem(validKey);}}/**
1761
+ * Get original engine
1762
+ */},{key:"getOriginalEngine",value:function getOriginalEngine(){return this.originalEngine;}/**
1763
+ * Decrypt values
1764
+ */},{key:"decrypt",value:function decrypt(value){if(isNullOrUndefined(value)){return null;}return this.crypto(value,'decrypt');}/**
1765
+ * Encrypt value
1766
+ */},{key:"encrypt",value:function encrypt(value){return this.crypto(value,'encrypt');}/**
1767
+ * Extension point to use with encryption plugins
1768
+ */},{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:'';}/**
1769
+ * Handle errors
1770
+ */},{key:"onError",value:function onError(error,customMessage,groupingHash){this.errorHandler.onError({error:error,context:"Store ".concat(this.id),customMessage:customMessage,groupingHash:groupingHash});}}]);}();
1771
+
1772
+ 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;};
1773
+
1774
+ /**
1775
+ * A service to manage stores & available storage client configurations
1776
+ */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;}/**
1777
+ * Configure available storage client instances
1778
+ */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;}/**
1779
+ * Create store to persist data used by the SDK like session, used details etc
1780
+ */},{key:"initClientDataStores",value:function initClientDataStores(){var _this=this;this.initializeStorageState();// TODO: fill in extra config values and bring them in from StoreManagerOptions if needed
1781
+ // TODO: should we pass the keys for all in order to validate or leave free as v1.1?
1782
+ // Initializing all the enabled store because previous user data might be in different storage
1783
+ // that needs auto migration
1784
+ 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
1785
+ 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
1786
+ 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
1787
+ 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;}/**
1788
+ * Create a new store
1789
+ */},{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];}/**
1790
+ * Retrieve a store
1791
+ */},{key:"getStore",value:function getStore(id){return this.stores[id];}}]);}();
1792
+
1793
+ 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
1794
+ var urlObj=new URL(url);// Extract the host and protocol
1795
+ var host=urlObj.host,protocol=urlObj.protocol;// Split the host into parts
1796
+ var parts=host.split('.');var topDomain;// Handle different cases, especially for co.uk or similar TLDs
1797
+ if(parts.length>2){// Join the last two parts for the top-level domain
1798
+ topDomain="".concat(parts[parts.length-2],".").concat(parts[parts.length-1]);}else {// If only two parts or less, return as it is
1799
+ 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;};
1800
+
1801
+ /**
1802
+ * Removes trailing slash from url
1803
+ * @param url
1804
+ * @returns url
1805
+ */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;}};/**
1806
+ * Get the referring domain from the referrer URL
1807
+ * @param referrer Page referrer
1808
+ * @returns Page referring domain
1809
+ */var getReferringDomain=function getReferringDomain(referrer){var _getDomain;return (_getDomain=getDomain(referrer))!==null&&_getDomain!==void 0?_getDomain:'';};/**
1810
+ * Extracts UTM parameters from the URL
1811
+ * @param url Page URL
1812
+ * @returns UTM parameters
1813
+ */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
1814
+ if(utmParam==='campaign'){utmParam='name';}result[utmParam]=value;}});}catch(error){// Do nothing
1815
+ }return result;};/**
1816
+ * To get the URL until the hash
1817
+ * @param url The input URL
1818
+ * @returns URL until the hash
1819
+ */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
1820
+ }return urlWithoutHash;};
1821
+
1822
+ var DEFAULT_PRE_CONSENT_STORAGE_STRATEGY='none';var DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE='immediate';
1823
+
1824
+ 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;};
1825
+
1826
+ /**
1827
+ * Validates and normalizes the consent options provided by the user
1828
+ * @param options Consent options provided by the user
1829
+ * @returns Validated and normalized consent options
1830
+ */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
1831
+ validOptions.consentManagement=mergeDeepRight(clonedOptions.consentManagement,{enabled:state.consents.enabled.value});}}return validOptions;};/**
1832
+ * Validates if the input is a valid consents data
1833
+ * @param value Input consents data
1834
+ * @returns true if the input is a valid consents data else false
1835
+ */var isValidConsentsData=function isValidConsentsData(value){return isNonEmptyObject(value)||Array.isArray(value);};/**
1836
+ * Retrieves the corresponding provider and plugin name of the selected consent manager from the supported consent managers
1837
+ * @param consentManagementOpts consent management options
1838
+ * @param logger logger instance
1839
+ * @returns Corresponding provider and plugin name of the selected consent manager from the supported consent managers
1840
+ */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
1841
+ provider=undefined;}return {provider:provider,consentManagerPluginName:consentManagerPluginName};};/**
1842
+ * Validates and converts the consent management options into a normalized format
1843
+ * @param consentManagementOpts Consent management options provided by the user
1844
+ * @param logger logger instance
1845
+ * @returns An object containing the consent manager plugin name, initialized, enabled and consents data
1846
+ */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
1847
+ 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
1848
+ enabled=enabled&&Boolean(consentManagerPluginName);return {provider:provider,consentManagerPluginName:consentManagerPluginName,initialized:initialized,enabled:enabled,consentsData:consentsData};};
1849
+
1850
+ /**
1851
+ * Determines the SDK URL
1852
+ * @returns sdkURL
1853
+ */var getSDKUrl=function getSDKUrl(){// First try the new method of getting the SDK URL
1854
+ // from the script tag
1855
+ 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
1856
+ // TODO: We need to remove this once all the customers upgrade to the
1857
+ // latest SDK loading snippet
1858
+ var scripts=document.getElementsByTagName('script');var sdkFileNameRegex=/(?:^|\/)rsa(\.min)?\.js$/;// eslint-disable-next-line no-restricted-syntax
1859
+ 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;};/**
1860
+ * Updates the reporting state variables from the source config data
1861
+ * @param res Source config
1862
+ * @param logger Logger instance
1863
+ */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;/**
1864
+ * Based on the following conditions, we decide whether to use the exact domain or not to determine the data service URL:
1865
+ * 1. If the cookie domain is provided and it is not a top-level domain, then use the exact domain
1866
+ * 2. If the sameDomainCookiesOnly flag is set to true, then use the exact domain
1867
+ */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
1868
+ // For server-side cookies to work, we need to set the SameSite=None and Secure attributes
1869
+ // One round of cookie options manipulation is taking place here
1870
+ // Based on these(setCookieDomain/storage.cookie or sameDomainCookiesOnly) two load-options, final cookie options are set in the storage module
1871
+ // TODO: Refactor the cookie options manipulation logic in one place
1872
+ if(curHost!==dataServiceHost){cookieOptions=_objectSpread2(_objectSpread2({},cookieOptions),{},{samesite:'None',secure:true});}/**
1873
+ * If the sameDomainCookiesOnly flag is not set and the cookie domain is provided(not top level domain),
1874
+ * and the data service host is different from the provided cookie domain, then we disable server-side cookies
1875
+ * ex: provided cookie domain: 'random.com', data service host: 'sub.example.com'
1876
+ */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
1877
+ 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
1878
+ 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
1879
+ 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
1880
+ // if it is not already initialized and
1881
+ // if consent management is enabled
1882
+ 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}};});};/**
1883
+ * Determines the consent management state variables from the source config data
1884
+ * @param resp Source config response
1885
+ * @param logger Logger instance
1886
+ */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
1887
+ 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);};/**
1888
+ * Transforms destinations config from source config response to Destination format
1889
+ * @param destinations Array of destination items from config response
1890
+ * @returns Array of transformed Destination objects
1891
+ */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};});};
1892
+
1893
+ /**
1894
+ * A function that determines the base URL for the integrations or plugins SDK
1895
+ * @param componentType The type of the component (integrations or plugins)
1896
+ * @param pathSuffix The path suffix to be appended to the base URL (js-integrations or plugins)
1897
+ * @param defaultComponentUrl The default URL to be used if the user has not provided a custom URL
1898
+ * @param currentSdkVersion The current version of the SDK
1899
+ * @param lockVersion Flag to lock the version of the component
1900
+ * @param urlFromLoadOptions The URL provided by the user in the load options
1901
+ * @param logger Logger instance
1902
+ * @returns The base URL for the integrations or plugins SDK
1903
+ */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
1904
+ 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
1905
+ if(state.context.app.value.installType==='cdn'){var sdkURL=getSDKUrl();if(sdkURL){// Extract the base URL from the core SDK file URL
1906
+ // and append the path suffix to it
1907
+ sdkComponentBaseURL=sdkURL.split('/').slice(0,-1).concat(pathSuffix).join('/');}}}// If the version needs to be locked, then replace the major version in the URL
1908
+ // with the current version of the SDK
1909
+ 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;};/**
1910
+ * A function that determines integration SDK loading path
1911
+ * @param currentSdkVersion Current SDK version
1912
+ * @param lockIntegrationsVersion Flag to lock the integrations version
1913
+ * @param integrationsUrlFromLoadOptions URL to load the integrations from as provided by the user
1914
+ * @param logger Logger instance
1915
+ * @returns
1916
+ */var getIntegrationsCDNPath=function getIntegrationsCDNPath(currentSdkVersion,lockIntegrationsVersion,integrationsUrlFromLoadOptions,logger){return getSDKComponentBaseURL('integrations',CDN_INT_DIR,DEFAULT_INTEGRATION_SDKS_URL,currentSdkVersion,lockIntegrationsVersion,integrationsUrlFromLoadOptions,logger);};
1917
+
1918
+ 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);});}/**
1919
+ * A function to validate, construct and store loadOption, lifecycle, source and destination
1920
+ * config related information in global state
1921
+ */},{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
1922
+ 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
1923
+ 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
1924
+ state.nativeDestinations.loadOnlyIntegrations.value=integrations;});this.getConfig();}/**
1925
+ * Handle errors
1926
+ */},{key:"onError",value:function onError(error,customMessage,groupingHash){this.errorHandler.onError({error:error,context:CONFIG_MANAGER,customMessage:customMessage,groupingHash:groupingHash});}/**
1927
+ * A callback function that is executed once we fetch the source config response.
1928
+ * Use to construct and store information that are dependent on the sourceConfig.
1929
+ */},{key:"processConfig",value:function processConfig(response,details){// TODO: add retry logic with backoff based on rejectionDetails.xhr.status
1930
+ // We can use isErrRetryable utility method
1931
+ 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
1932
+ if(res.source.enabled===false){this.logger.error(SOURCE_DISABLED_ERROR);return;}// set the values in state for reporting slice
1933
+ updateReportingState(res);var nativeDestinations=res.source.destinations.length>0?getDestinationsFromConfig(res.source.destinations):[];// set in the state --> source, destination, lifecycle, reporting
1934
+ n(function(){var _state$loadOptions$va2;// set source related information in state
1935
+ 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
1936
+ state.nativeDestinations.configuredDestinations.value=nativeDestinations;// set the desired optional plugins
1937
+ 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
1938
+ state.lifecycle.status.value='configured';});}/**
1939
+ * A function to fetch source config either from /sourceConfig endpoint
1940
+ * or from getSourceConfig load option
1941
+ * @returns
1942
+ */},{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
1943
+ 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
1944
+ this.httpClient.getAsyncData({url:state.lifecycle.sourceConfigUrl.value,options:{headers:{'Content-Type':undefined}},callback:this.processConfig});}}}]);}();
1945
+
1946
+ /**
1947
+ * To get the timezone of the user
1948
+ *
1949
+ * @returns string
1950
+ */var getTimezone=function getTimezone(){// Not susceptible to super-linear backtracking
1951
+ // eslint-disable-next-line sonarjs/slow-regex
1952
+ var timezone=/([A-Z]+[+-]\d+)/.exec(new Date().toString());return timezone!==null&&timezone!==void 0&&timezone[1]?timezone[1]:'NA';};
1953
+
1954
+ /**
1955
+ * Get the referrer URL
1956
+ * @returns The referrer URL
1957
+ */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';};/**
1958
+ * To get the canonical URL of the page
1959
+ * @returns canonical URL
1960
+ */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,
1961
+ // add "Brave/<version>" to the user agent with the version value from the Chrome component
1962
+ if(brave&&Object.getPrototypeOf(brave).isBrave){// Example:
1963
+ // 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
1964
+ 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;};/**
1965
+ * Default page properties
1966
+ * @returns Default page properties
1967
+ */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.
1968
+ if(canonicalUrl){try{var urlObj=new URL(canonicalUrl);// If existing, query params of canonical URL will be used instead of the location.search ones
1969
+ if(urlObj.search===''){pageUrl=canonicalUrl+search;}else {pageUrl=canonicalUrl;}path=urlObj.pathname;}catch(err){// Do nothing
1970
+ }}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};};
1971
+
1972
+ 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();});}};
1973
+
1974
+ 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
1975
+ // the polyfill service serves them under the same feature name, "URL".
1976
+ 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
1977
+ // the polyfill service serves them under the same feature name, "TextEncoder".
1978
+ 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".
1979
+ 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;};
1980
+
1981
+ 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
1982
+ var POLYFILL_SCRIPT_ID='rudderstackPolyfill';
1983
+
1984
+ 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
1985
+ var hasUAClientHints=function hasUAClientHints(){return !isNullOrUndefined(globalThis.navigator.userAgentData);};var hasBeacon=function hasBeacon(){return !isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);};
1986
+
1987
+ 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;};
1988
+
1989
+ 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();}/**
1990
+ * Detect supported capabilities and set values in state
1991
+ */// eslint-disable-next-line class-methods-use-this
1992
+ },{key:"detectBrowserCapabilities",value:function detectBrowserCapabilities(){var _this=this;n(function(){// Storage related details
1993
+ 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
1994
+ 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
1995
+ 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
1996
+ m(function(){if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(_this.httpClient);}});}/**
1997
+ * Detect if polyfills are required and then load script from polyfill URL
1998
+ */},{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
1999
+ // NOTE: we're not putting this into RudderStackGlobals as providing the property path to the callback function in the polyfill URL is not possible
2000
+ 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
2001
+ 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();}}/**
2002
+ * Attach listeners to window to observe event that update capabilities state values
2003
+ */},{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));}/**
2004
+ * Set the lifecycle status to next phase
2005
+ */// eslint-disable-next-line class-methods-use-this
2006
+ },{key:"onReady",value:function onReady(){this.detectBrowserCapabilities();state.lifecycle.status.value='browserCapabilitiesReady';}/**
2007
+ * Handles error
2008
+ * @param error The error object
2009
+ */},{key:"onError",value:function onError(error,groupingHash){this.errorHandler.onError({error:error,context:CAPABILITIES_MANAGER,groupingHash:groupingHash});}}]);}();
2010
+
2011
+ var CHANNEL='web';// These are the top-level elements in the standard RudderStack event spec
2012
+ var TOP_LEVEL_ELEMENTS=['integrations','anonymousId','originalTimestamp'];// Reserved elements in the context of standard RudderStack event spec
2013
+ // Typically, these elements are not allowed to be overridden by the user
2014
+ var CONTEXT_RESERVED_ELEMENTS=['library','consentManagement','userAgent','ua-ch','screen'];// Reserved elements in the standard RudderStack event spec
2015
+ 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'];
2016
+
2017
+ /**
2018
+ * A function to check given value is a number or not
2019
+ * @param num input value
2020
+ * @returns boolean
2021
+ */var isNumber=function isNumber(num){return typeof num==='number'&&!Number.isNaN(num);};/**
2022
+ * A function to check given number has minimum length or not
2023
+ * @param minimumLength minimum length
2024
+ * @param num input number
2025
+ * @returns boolean
2026
+ */var hasMinLength=function hasMinLength(minimumLength,num){return num.toString().length>=minimumLength;};/**
2027
+ * A function to check given value is a positive integer or not
2028
+ * @param num input value
2029
+ * @returns boolean
2030
+ */var isPositiveInteger=function isPositiveInteger(num){return isNumber(num)&&num>=0&&Number.isInteger(num);};
2031
+
2032
+ 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);};/**
2033
+ * A function to validate whether the current auto tracking session has expired or not.
2034
+ * It checks for the current session expiry and the cut off time expiry.
2035
+ * @param sessionInfo session info
2036
+ * @returns boolean
2037
+ */var hasSessionExpired=function hasSessionExpired(sessionInfo){var isCurrentSessionExpired=Boolean(!sessionInfo.expiresAt||Date.now()>sessionInfo.expiresAt);return isCurrentSessionExpired||isCutOffTimeExceeded(sessionInfo);};/**
2038
+ * A function to generate session id
2039
+ * @returns number
2040
+ */var generateSessionId=function generateSessionId(){return Date.now();};/**
2041
+ * Function to validate user provided sessionId
2042
+ * @param {number} sessionId
2043
+ * @param logger logger
2044
+ * @returns
2045
+ */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;};/**
2046
+ * A function to generate new auto tracking session
2047
+ * @param sessionInfo session info
2048
+ * @returns SessionInfo
2049
+ */var generateAutoTrackingSession=function generateAutoTrackingSession(sessionInfo){var timeout=sessionInfo.timeout,cutOff=sessionInfo.cutOff;var timestamp=Date.now();return _objectSpread2({id:timestamp,// set the current timestamp
2050
+ expiresAt:timestamp+timeout,// set the expiry time of the session
2051
+ timeout:timeout,autoTrack:true},cutOff&&{cutOff:cutOff});};/**
2052
+ * A function to generate new manual tracking session
2053
+ * @param id Provided sessionId
2054
+ * @param logger Logger module
2055
+ * @returns SessionInfo
2056
+ */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);};/**
2057
+ * Generate a new anonymousId
2058
+ * @returns string anonymousID
2059
+ */var generateAnonymousId=function generateAnonymousId(){return generateUUID();};var getFinalResetOptions=function getFinalResetOptions(options){// Legacy behavior: toggle only anonymousId without mutating defaults
2060
+ 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
2061
+ if(isObjectLiteralAndNotNull(options)&&isObjectLiteralAndNotNull(options.entries)){return mergeDeepRight(DEFAULT_RESET_OPTIONS,options);}return _objectSpread2({},DEFAULT_RESET_OPTIONS);};
2062
+
2063
+ /**
2064
+ * To get the page properties for context object
2065
+ * @param pageProps Page properties
2066
+ * @returns page properties object for context
2067
+ */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
2068
+ 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;};/**
2069
+ * Add any missing default page properties using values from options and defaults
2070
+ * @param properties Input page properties
2071
+ * @param options API options
2072
+ */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
2073
+ 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;};/**
2074
+ * Utility to check for reserved keys in the input object
2075
+ * @param obj Generic object
2076
+ * @param parentKeyPath Object's parent key path
2077
+ * @param logger Logger instance
2078
+ */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));}});}};/**
2079
+ * Checks for reserved keys in traits, properties, and contextual traits
2080
+ * @param rudderEvent Generated rudder event
2081
+ * @param logger Logger instance
2082
+ */var checkForReservedElements=function checkForReservedElements(rudderEvent,logger){// properties, traits, contextualTraits are either undefined or object
2083
+ 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);};/**
2084
+ * Overrides the top-level event properties with data from API options
2085
+ * @param rudderEvent Generated rudder event
2086
+ * @param options API options
2087
+ */var updateTopLevelEventElements=function updateTopLevelEventElements(rudderEvent,options){if(options.anonymousId&&isString(options.anonymousId)){// eslint-disable-next-line no-param-reassign
2088
+ rudderEvent.anonymousId=options.anonymousId;}if(isNonEmptyObject(options.integrations)){// eslint-disable-next-line no-param-reassign
2089
+ rudderEvent.integrations=options.integrations;}if(options.originalTimestamp&&isString(options.originalTimestamp)){// eslint-disable-next-line no-param-reassign
2090
+ rudderEvent.originalTimestamp=options.originalTimestamp;}};/**
2091
+ * To merge the contextual information in API options with existing data
2092
+ * @param rudderContext Generated rudder event
2093
+ * @param options API options
2094
+ * @param logger Logger instance
2095
+ */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;};/**
2096
+ * Updates rudder event object with data from the API options
2097
+ * @param rudderEvent Generated rudder event
2098
+ * @param options API options
2099
+ */var processOptions=function processOptions(rudderEvent,options,logger){// Only allow object type for options
2100
+ if(isObjectLiteralAndNotNull(options)){updateTopLevelEventElements(rudderEvent,options);// eslint-disable-next-line no-param-reassign
2101
+ rudderEvent.context=getMergedContext(rudderEvent.context,options,logger);}};/**
2102
+ * Returns the final integrations config for the event based on the global config and event's config
2103
+ * @param integrationsConfig Event's integrations config
2104
+ * @returns Final integrations config
2105
+ */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
2106
+ 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);};/**
2107
+ * Enrich the base event object with data from state and the API options
2108
+ * @param rudderEvent RudderEvent object
2109
+ * @param options API options
2110
+ * @param pageProps Page properties
2111
+ * @param logger logger
2112
+ * @returns Enriched RudderEvent object
2113
+ */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
2114
+ commonEventData.anonymousId=generateAnonymousId();}else {// Type casting to string as the user session manager will take care of initializing the value
2115
+ commonEventData.anonymousId=state.session.anonymousId.value;}// set truly anonymous tracking flag
2116
+ 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
2117
+ // matching with v1.1 payload
2118
+ 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
2119
+ processedEvent.integrations=getEventIntegrationsConfig(processedEvent.integrations);return processedEvent;};
2120
+
2121
+ var RudderEventFactory=/*#__PURE__*/function(){function RudderEventFactory(logger){_classCallCheck(this,RudderEventFactory);this.logger=logger;}/**
2122
+ * Generate a 'page' event based on the user-input fields
2123
+ * @param category Page's category
2124
+ * @param name Page name
2125
+ * @param properties Page properties
2126
+ * @param options API options
2127
+ */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);}/**
2128
+ * Generate a 'track' event based on the user-input fields
2129
+ * @param event The event name
2130
+ * @param properties Event properties
2131
+ * @param options API options
2132
+ */},{key:"generateTrackEvent",value:function generateTrackEvent(event,properties,options){var trackEvent={properties:properties,event:event,type:'track'};return getEnrichedEvent(trackEvent,options,undefined,this.logger);}/**
2133
+ * Generate an 'identify' event based on the user-input fields
2134
+ * @param userId New user ID
2135
+ * @param traits new traits
2136
+ * @param options API options
2137
+ */},{key:"generateIdentifyEvent",value:function generateIdentifyEvent(userId,traits,options){var identifyEvent={userId:userId,type:'identify',context:{traits:traits}};return getEnrichedEvent(identifyEvent,options,undefined,this.logger);}/**
2138
+ * Generate an 'alias' event based on the user-input fields
2139
+ * @param to New user ID
2140
+ * @param from Old user ID
2141
+ * @param options API options
2142
+ */},{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
2143
+ enrichedEvent.userId=to!==null&&to!==void 0?to:enrichedEvent.userId;return enrichedEvent;}/**
2144
+ * Generate a 'group' event based on the user-input fields
2145
+ * @param groupId New group ID
2146
+ * @param traits new group traits
2147
+ * @param options API options
2148
+ */},{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);}/**
2149
+ * Generates a new RudderEvent object based on the user-input fields
2150
+ * @param event API event parameters object
2151
+ * @returns A RudderEvent object
2152
+ */},{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;}}]);}();
2153
+
2154
+ /**
2155
+ * A service to generate valid event payloads and queue them for processing
2156
+ */var EventManager=/*#__PURE__*/function(){/**
2157
+ *
2158
+ * @param eventRepository Event repository instance
2159
+ * @param userSessionManager UserSession Manager instance
2160
+ * @param errorHandler Error handler object
2161
+ * @param logger Logger object
2162
+ */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);}/**
2163
+ * Initializes the event manager
2164
+ */return _createClass(EventManager,[{key:"init",value:function init(){this.eventRepository.init();}},{key:"resume",value:function resume(){this.eventRepository.resume();}/**
2165
+ * Consumes a new incoming event
2166
+ * @param event Incoming event data
2167
+ */},{key:"addEvent",value:function addEvent(event){this.userSessionManager.refreshSession();var rudderEvent=this.eventFactory.create(event);this.eventRepository.enqueue(rudderEvent,event.callback);}}]);}();
2168
+
2169
+ var UserSessionManager=/*#__PURE__*/function(){/**
2170
+ * Tracks whether a server-side cookie setting request is in progress or not.
2171
+ */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={};}/**
2172
+ * Initialize User session with values from storage
2173
+ */return _createClass(UserSessionManager,[{key:"init",value:function init(){this.syncStorageDataToState();// Register the effect to sync with storage
2174
+ this.registerEffects();}},{key:"syncStorageDataToState",value:function syncStorageDataToState(){this.migrateStorageIfNeeded();this.migrateDataFromPreviousStorage();// get the values from storage and set it again
2175
+ 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
2176
+ sessionInfo={// If manualTrack is set to true in the storage, then do not enable auto tracking even if configured.
2177
+ // Once manual tracking ends (endSession is called), auto tracking will be enabled in the next SDK run.
2178
+ 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
2179
+ 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
2180
+ 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
2181
+ // as those values indicate there is no need for migration or
2182
+ // migration failed
2183
+ 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
2184
+ 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
2185
+ // and will proceed with it
2186
+ 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
2187
+ 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};}/**
2188
+ * Handles error
2189
+ * @param error The error object
2190
+ */},{key:"onError",value:function onError(error,customMessage,groupingHash){this.errorHandler.onError({error:error,context:USER_SESSION_MANAGER,customMessage:customMessage,groupingHash:groupingHash});}/**
2191
+ * A function to encrypt the cookie value and return the encrypted data
2192
+ * @param cookiesData
2193
+ * @param store
2194
+ * @returns
2195
+ */},{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;}/**
2196
+ * A function that makes request to data service to set the cookie
2197
+ * @param encryptedCookieData
2198
+ * @param callback
2199
+ */},{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});}/**
2200
+ * A function to make an external request to set the cookie from server side
2201
+ * @param sessionToCookiesMap map of session key to cookie name
2202
+ * @param cb callback function to be called when the cookie is set
2203
+ * @param store store to be used to get the cookie value
2204
+ */},{key:"setServerSideCookies",value:function setServerSideCookies(sessionToCookiesMap,cb,store){var _this4=this;// Retrieve the cookie value from the state
2205
+ 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
2206
+ 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
2207
+ var encryptedCookieData=this.getEncryptedCookieData(getCurrentCookieValuesFromState(),store);if(encryptedCookieData.length>0){// make request to data service to set the cookie from server side
2208
+ this.makeRequestToSetCookie(encryptedCookieData,function(res,details){var _details$xhr;// Mark the cookie req status as done
2209
+ 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.
2210
+ 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
2211
+ // or other cookie requests might have updated the cookie value.
2212
+ // Log an error only when cookie didn't exist previously and currently also doesn't exist.
2213
+ 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
2214
+ 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
2215
+ clearInProgressFlags();}}/**
2216
+ * A function to sync values in storage
2217
+ * @param sessionKey
2218
+ */},{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
2219
+ // set the cookie from server side
2220
+ if(state.serverCookies.isEnabledServerSideCookies.value&&storageType===COOKIE_STORAGE){// Mark the requests as in progress.
2221
+ 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
2222
+ 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);}}}/**
2223
+ * Function to update storage whenever state value changes
2224
+ */},{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
2225
+ USER_SESSION_KEYS.forEach(function(sessionKey){m(function(){_this6.syncValueToStorage(sessionKey);});});}/**
2226
+ * Sets anonymous id in the following precedence:
2227
+ *
2228
+ * 1. anonymousId: Id directly provided to the function.
2229
+ * 2. rudderAmpLinkerParam: value generated from linker query parm (rudderstack)
2230
+ * using parseLinker util.
2231
+ * 3. generateUUID: A new unique id is generated and assigned.
2232
+ */},{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;}/**
2233
+ * Fetches anonymousId
2234
+ * @param options option to fetch it from external source
2235
+ * @returns anonymousId
2236
+ */},{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
2237
+ if(!persistedAnonymousId||persistedAnonymousId===DEFAULT_USER_SESSION_VALUES.anonymousId){persistedAnonymousId=this.getEntryValue('anonymousId');}if(!persistedAnonymousId&&options){var _this$pluginsManager2;// fetch anonymousId from external source
2238
+ 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
2239
+ // This is needed for entries that are fetched from the storage
2240
+ // during the current session (for example, session info)
2241
+ 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;}/**
2242
+ * Fetches the value for a session key. Preferably from storage, if the server-side
2243
+ * cookies request is not in progress. Otherwise, from the state.
2244
+ * @param sessionKey - The session key to fetch the value for
2245
+ * @returns - The value for the session key
2246
+ */},{key:"getUserSessionValue",value:function getUserSessionValue(sessionKey){// If the server-side cookies request is in progress, fetch the value from the state.
2247
+ if(this.serverSideCookiesRequestInProgress[sessionKey]){return state.session[sessionKey].value;}// Otherwise, fetch the value from storage.
2248
+ return this.getEntryValue(sessionKey);}/**
2249
+ * Fetches User Id
2250
+ * @returns
2251
+ */},{key:"getUserId",value:function getUserId(){return this.getUserSessionValue('userId');}/**
2252
+ * Fetches User Traits
2253
+ * @returns
2254
+ */},{key:"getUserTraits",value:function getUserTraits(){return this.getUserSessionValue('userTraits');}/**
2255
+ * Fetches Group Id
2256
+ * @returns
2257
+ */},{key:"getGroupId",value:function getGroupId(){return this.getUserSessionValue('groupId');}/**
2258
+ * Fetches Group Traits
2259
+ * @returns
2260
+ */},{key:"getGroupTraits",value:function getGroupTraits(){return this.getUserSessionValue('groupTraits');}/**
2261
+ * Fetches Initial Referrer
2262
+ * @returns
2263
+ */},{key:"getInitialReferrer",value:function getInitialReferrer(){return this.getUserSessionValue('initialReferrer');}/**
2264
+ * Fetches Initial Referring domain
2265
+ * @returns
2266
+ */},{key:"getInitialReferringDomain",value:function getInitialReferringDomain(){return this.getUserSessionValue('initialReferringDomain');}/**
2267
+ * Fetches session tracking information from storage
2268
+ * @returns
2269
+ */},{key:"getSessionInfo",value:function getSessionInfo(){return this.getUserSessionValue('sessionInfo');}/**
2270
+ * Fetches auth token from storage
2271
+ * @returns
2272
+ */},{key:"getAuthToken",value:function getAuthToken(){return this.getUserSessionValue('authToken');}/**
2273
+ * If session is active it returns the sessionId
2274
+ * @returns
2275
+ */},{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;}/**
2276
+ * A function to keep the session information up to date in the state
2277
+ * before using it for building event payloads.
2278
+ */},{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.
2279
+ // So, we needn't update the session info.
2280
+ //
2281
+ // For other scenarios,
2282
+ // 1. If sessionStart is undefined, then it's a new session.
2283
+ // Mark it as sessionStart.
2284
+ // 2. If sessionStart is true, then need to flip it for the future events.
2285
+ 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.
2286
+ state.session.sessionInfo.value=sessionInfo;if(state.lifecycle.status.value!=='readyExecuted'){// Force update the storage as the 'effect' blocks are not getting triggered
2287
+ // when processing preload buffered requests
2288
+ 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();}}/**
2289
+ * Reset state values
2290
+ * @param options options for reset
2291
+ * @returns
2292
+ */},{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;}});});}/**
2293
+ * Set user Id
2294
+ * @param userId
2295
+ */},{key:"setUserId",value:function setUserId(userId){state.session.userId.value=this.isPersistenceEnabledForStorageEntry('userId')&&userId?userId:DEFAULT_USER_SESSION_VALUES.userId;}/**
2296
+ * Set user traits
2297
+ * @param traits
2298
+ */},{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;}/**
2299
+ * Set group Id
2300
+ * @param groupId
2301
+ */},{key:"setGroupId",value:function setGroupId(groupId){state.session.groupId.value=this.isPersistenceEnabledForStorageEntry('groupId')&&groupId?groupId:DEFAULT_USER_SESSION_VALUES.groupId;}/**
2302
+ * Set group traits
2303
+ * @param traits
2304
+ */},{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;}/**
2305
+ * Set initial referrer
2306
+ * @param referrer
2307
+ */},{key:"setInitialReferrer",value:function setInitialReferrer(referrer){state.session.initialReferrer.value=this.isPersistenceEnabledForStorageEntry('initialReferrer')&&referrer?referrer:DEFAULT_USER_SESSION_VALUES.initialReferrer;}/**
2308
+ * Set initial referring domain
2309
+ * @param {String} referringDomain
2310
+ */},{key:"setInitialReferringDomain",value:function setInitialReferringDomain(referringDomain){state.session.initialReferringDomain.value=this.isPersistenceEnabledForStorageEntry('initialReferringDomain')&&referringDomain?referringDomain:DEFAULT_USER_SESSION_VALUES.initialReferringDomain;}/**
2311
+ * A function to check for existing session details and depending on that create a new session
2312
+ */},{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
2313
+ finalSessionInfo.expiresAt=timestamp+timeout;}// Reset cut off expiry timestamp if it is exceeded
2314
+ if(isCutOffTimeExceeded(finalSessionInfo)){finalSessionInfo.cutOff.expiresAt=undefined;}// If cut off is active, set or retain the expiry time
2315
+ if(finalSessionInfo.cutOff){var cutOffExpiresAt=getCutOffExpirationTimestamp(finalSessionInfo.cutOff);finalSessionInfo.cutOff.expiresAt=cutOffExpiresAt;}// Update the session info in the state
2316
+ state.session.sessionInfo.value=finalSessionInfo;}/**
2317
+ * A function method to start a manual session
2318
+ * @param {number} id session identifier
2319
+ * @returns
2320
+ */},{key:"start",value:function start(id){state.session.sessionInfo.value=generateManualTrackingSession(id,this.logger);}/**
2321
+ * An internal function to start manual session
2322
+ */},{key:"startManualTrackingInternal",value:function startManualTrackingInternal(){this.start(Date.now());}/**
2323
+ * A public method to end an ongoing session.
2324
+ */},{key:"end",value:function end(){state.session.sessionInfo.value=DEFAULT_USER_SESSION_VALUES.sessionInfo;}/**
2325
+ * Set auth token
2326
+ * @param userId
2327
+ */},{key:"setAuthToken",value:function setAuthToken(token){state.session.authToken.value=this.isPersistenceEnabledForStorageEntry('authToken')&&token?token:DEFAULT_USER_SESSION_VALUES.authToken;}}]);}();
2328
+
2329
+ /**
2330
+ * Plugins to be loaded in the plugins loadOption is not defined
2331
+ */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
2332
+ var liteExcludedPlugins=['GoogleLinker'];var defaultOptionalPluginsList=allOptionalPlugins.filter(function(plugin){return !liteExcludedPlugins.includes(plugin);});
2333
+
2334
+ var normalizeLoadOptions=function normalizeLoadOptions(loadOptionsFromState,loadOptions){// TODO: Maybe add warnings for invalid values
2335
+ 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;};
2336
+
2337
+ var DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';var DESTINATIONS_QUEUE_EXT_POINT_PREFIX='destinationsEventsQueue';var DMT_EXT_POINT_PREFIX='transformEvent';
2338
+
2339
+ /**
2340
+ * Filters and returns the user supplied integrations config that should take preference over the destination specific integrations config
2341
+ * @param eventIntgConfig User supplied integrations config at event level
2342
+ * @param destinationsIntgConfig Cumulative integrations config from all destinations
2343
+ * @returns Filtered user supplied integrations config
2344
+ */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;},{});};/**
2345
+ * Returns the event object with final integrations config
2346
+ * @param event RudderEvent object
2347
+ * @param state Application state
2348
+ * @returns Mutated event with final integrations config
2349
+ */var getFinalEvent=function getFinalEvent(event,state){var finalEvent=clone(event);// Merge the destination specific integrations config with the event's integrations config
2350
+ // In general, the preference is given to the event's integrations config
2351
+ 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';};
2352
+
2353
+ 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));}};
2354
+
2355
+ /**
2356
+ * Event repository class responsible for queuing events for further processing and delivery
2357
+ */var EventRepository=/*#__PURE__*/function(){/**
2358
+ *
2359
+ * @param pluginsManager Plugins manager instance
2360
+ * @param storeManager Store Manager instance
2361
+ * @param errorHandler Error handler object
2362
+ * @param logger Logger object
2363
+ */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;}/**
2364
+ * Initializes the event repository
2365
+ */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
2366
+ 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
2367
+ // However, events will be enqueued for now.
2368
+ // At the time of processing the events, the integrations config data from destinations
2369
+ // is merged into the event object
2370
+ 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
2371
+ 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();}}/**
2372
+ * Enqueues the event for processing
2373
+ * @param event RudderEvent object
2374
+ * @param callback API callback function
2375
+ */},{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
2376
+ var apiName="".concat(event.type.charAt(0).toUpperCase()).concat(event.type.slice(1)).concat(API_SUFFIX);safelyInvokeCallback(callback,[dpQEvent],apiName,this.logger);}}]);}();
2377
+
2378
+ 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);};
2379
+
2380
+ /*
2381
+ * Analytics class with lifecycle based on state ad user triggered events
2382
+ */var Analytics=/*#__PURE__*/function(){/**
2383
+ * Initialize services and components or use default ones if singletons
2384
+ */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);}/**
2385
+ * Start application lifecycle if not already started
2386
+ */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
2387
+ 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
2388
+ 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
2389
+ setExposedGlobal('state',state,writeKey);// Configure initial config of any services or components here
2390
+ // State application lifecycle
2391
+ this.startLifecycle();}// Start lifecycle methods
2392
+ /**
2393
+ * Orchestrate the lifecycle of the application phases/status
2394
+ */},{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
2395
+ 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
2396
+ if(state.consents.preConsent.value.enabled===true){state.lifecycle.status.value='ready';}else {this.loadDestinations();}}/**
2397
+ * Load browser polyfill if required
2398
+ */},{key:"onMounted",value:function onMounted(){this.capabilitiesManager.init();}/**
2399
+ * Enqueue in SDK preload buffer events, used from preloadBuffer component
2400
+ */},{key:"enqueuePreloadBufferEvents",value:function enqueuePreloadBufferEvents(bufferedEvents){var _this2=this;if(Array.isArray(bufferedEvents)){bufferedEvents.forEach(function(bufferedEvent){return _this2.preloadBuffer.enqueue(clone(bufferedEvent));});}}/**
2401
+ * Process the buffer preloaded events by passing their arguments to the respective facade methods
2402
+ */},{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);}/**
2403
+ * Load configuration
2404
+ */},{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();}/**
2405
+ * Initialize the storage and event queue
2406
+ */},{key:"onPluginsReady",value:function onPluginsReady(){var _this$storeManager,_this$userSessionMana,_this$eventManager;// Initialize storage
2407
+ (_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
2408
+ 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
2409
+ (_this$eventManager=this.eventManager)===null||_this$eventManager===void 0||_this$eventManager.init();// Mark the SDK as initialized
2410
+ state.lifecycle.status.value='initialized';}/**
2411
+ * Load plugins
2412
+ */},{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?
2413
+ // registerCustomPlugins(state.loadOptions.value.customPlugins);
2414
+ }/**
2415
+ * Trigger onLoaded callback if any is provided in config & emit initialised event
2416
+ */},{key:"onInitialized",value:function onInitialized(){// Process any preloaded events
2417
+ this.processDataInPreloadBuffer();// Set lifecycle state
2418
+ n(function(){state.lifecycle.loaded.value=true;state.lifecycle.status.value='loaded';});this.initialized=true;// Execute onLoaded callback if provided in load options
2419
+ var onLoadedCallbackFn=state.loadOptions.value.onLoaded;// TODO: we need to avoid passing the window object to the callback function
2420
+ // as this will prevent us from supporting multiple SDK instances in the same page
2421
+ safelyInvokeCallback(onLoadedCallbackFn,[globalThis.rudderanalytics],LOAD_API,this.logger);// Emit an event to use as substitute to the onLoaded callback
2422
+ dispatchSDKEvent('RSA_Initialised');}/**
2423
+ * Emit ready event
2424
+ */// eslint-disable-next-line class-methods-use-this
2425
+ },{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
2426
+ dispatchSDKEvent('RSA_Ready');}/**
2427
+ * Consume preloaded events buffer
2428
+ */},{key:"processBufferedEvents",value:function processBufferedEvents(){// This logic has been intentionally implemented without a simple
2429
+ // for-loop as the individual events that are processed may
2430
+ // add more events to the buffer (this is needed for the consent API)
2431
+ 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
2432
+ (_ref=this)[methodName].apply(_ref,_toConsumableArray(bufferedEvent.slice(1)).concat([true]));}}bufferedEvents=state.eventBuffer.toBeProcessedArray.value;}}/**
2433
+ * Load device mode destinations
2434
+ */},{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
2435
+ if(state.lifecycle.status.value==='destinationsLoading'||state.lifecycle.status.value==='destinationsReady'){return;}// Set in state the desired activeDestinations to inject in DOM
2436
+ (_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
2437
+ 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
2438
+ 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;});}});}/**
2439
+ * Move to the ready state
2440
+ */// eslint-disable-next-line class-methods-use-this
2441
+ },{key:"onDestinationsReady",value:function onDestinationsReady(){// May be do any destination specific actions here
2442
+ // Mark the ready status if not already done
2443
+ if(state.lifecycle.status.value!=='ready'){n(function(){state.lifecycle.status.value='ready';});}}// End lifecycle methods
2444
+ // Start consumer exposed methods
2445
+ },{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;}/**
2446
+ * If destinations are loaded or no integration is available for loading
2447
+ * execute the callback immediately else push the callbacks to a queue that
2448
+ * will be executed after loading completes
2449
+ */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.
2450
+ // Send automatic ad blocked page event if ad-blockers are detected on the page
2451
+ // Check page category to avoid infinite loop
2452
+ 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
2453
+ // in v3 implementation
2454
+ 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
2455
+ 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
2456
+ 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
2457
+ 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
2458
+ },{key:"getUserId",value:function getUserId(){return state.session.userId.value;}// eslint-disable-next-line class-methods-use-this
2459
+ },{key:"getUserTraits",value:function getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
2460
+ },{key:"getGroupId",value:function getGroupId(){return state.session.groupId.value;}// eslint-disable-next-line class-methods-use-this
2461
+ },{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
2462
+ },{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
2463
+ 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
2464
+ (_this$storeManager2=this.storeManager)===null||_this$storeManager2===void 0||_this$storeManager2.initializeStorageState();// Re-init user session manager
2465
+ (_this$userSessionMana11=this.userSessionManager)===null||_this$userSessionMana11===void 0||_this$userSessionMana11.syncStorageDataToState();// Resume event manager to process the events to destinations
2466
+ (_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
2467
+ // events buffer array so that any other preload events (mainly from query string API) will be processed first.
2468
+ 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);}/**
2469
+ * Add a custom integration for a custom destination.
2470
+ * @param destinationId - The ID of the custom destination from the RudderStack dashboard.
2471
+ * @param integration - The custom integration object.
2472
+ * @param isBufferedInvocation - Whether the invocation is buffered.
2473
+ */},{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
2474
+ }]);}();
2475
+
2476
+ /*
2477
+ * RudderAnalytics facade singleton that is exposed as global object and will:
2478
+ * expose overloaded methods
2479
+ * handle multiple Analytics instances
2480
+ * consume SDK preload event buffer
2481
+ */var RudderAnalytics=/*#__PURE__*/function(){// Singleton with constructor bind methods
2482
+ function RudderAnalytics(){_classCallCheck(this,RudderAnalytics);// END-NO-SONAR-SCAN
2483
+ _defineProperty(this,"analyticsInstances",{});_defineProperty(this,"defaultAnalyticsKey",'');_defineProperty(this,"logger",defaultLogger);try{if(RudderAnalytics.globalSingleton){// START-NO-SONAR-SCAN
2484
+ // eslint-disable-next-line no-constructor-return
2485
+ return RudderAnalytics.globalSingleton;// END-NO-SONAR-SCAN
2486
+ }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
2487
+ this.triggerBufferedLoadEvent();// Assign to global "rudderanalytics" object after processing the preload buffer (if any exists)
2488
+ // for CDN bundling IIFE exports covers this but for npm ESM and CJS bundling has to be done explicitly
2489
+ globalThis.rudderanalytics=this;}catch(error){dispatchErrorEvent(error);}}/**
2490
+ * Create an instance of the current instance that can be used
2491
+ * to call a subset of methods of the current instance.
2492
+ * It is typically used to expose the analytics instance to the integrations (standard and custom)
2493
+ */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:/**
2494
+ * Set instance to use if no specific writeKey is provided in methods
2495
+ * automatically for the first created instance
2496
+ * TODO: to support multiple analytics instances in the near future
2497
+ */function setDefaultInstanceKey(writeKey){// IMP: Add try-catch block to handle any unhandled errors
2498
+ // similar to other public methods
2499
+ // if the implementation of this method goes beyond
2500
+ // this simple implementation
2501
+ if(isString(writeKey)&&writeKey){this.defaultAnalyticsKey=writeKey;}}/**
2502
+ * Retrieve an existing analytics instance
2503
+ */},{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;}}/**
2504
+ * Loads the SDK
2505
+ * @param writeKey Source write key
2506
+ * @param dataPlaneUrl Data plane URL
2507
+ * @param loadOptions Additional options for loading the SDK
2508
+ * @returns none
2509
+ */},{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
2510
+ this.trackPageLifecycleEvents(loadOptions);// Get the preloaded events array from global buffer instead of window.rudderanalytics
2511
+ // as the constructor must have already pushed the events to the global buffer
2512
+ var preloadedEventsArray=getExposedGlobal(GLOBAL_PRELOAD_BUFFER);// The array will be mutated in the below method
2513
+ 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);}}/**
2514
+ * A function to track page lifecycle events like page loaded and page unloaded
2515
+ * @param loadOptions
2516
+ * @returns
2517
+ */},{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
2518
+ // if at least one of the autoTrack options is enabled
2519
+ // IMPORTANT: make sure this is done at the end as it depends on the above states
2520
+ state.autoTrack.enabled.value=autoTrackEnabled||pageLifecycleEnabled;if(!pageLifecycleEnabled){return;}this.setupPageUnloadTracking(events,useBeacon,options);}/**
2521
+ * Setup page unload tracking if enabled
2522
+ * @param events
2523
+ * @param useBeacon
2524
+ * @param options
2525
+ */},{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
2526
+ this.logger.warn(PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(RSA));}}}/**
2527
+ * Trigger load event in buffer queue if exists and stores the
2528
+ * remaining preloaded events array in global object
2529
+ */},{key:"triggerBufferedLoadEvent",value:function triggerBufferedLoadEvent(){var preloadedEventsArray=Array.isArray(globalThis.rudderanalytics)?globalThis.rudderanalytics:[];// Get any load method call that is buffered if any
2530
+ // BTW, load method is also removed from the array
2531
+ // So, the Analytics object can directly consume the remaining events
2532
+ var loadEvent=getPreloadedLoadEvent(preloadedEventsArray);// Set the final preloaded events array in global object
2533
+ setExposedGlobal(GLOBAL_PRELOAD_BUFFER,clone(_toConsumableArray(preloadedEventsArray)));// Process load method if present in the buffered requests
2534
+ if(loadEvent.length>0){// Remove the event name from the Buffered Event array and keep only arguments
2535
+ loadEvent.shift();// eslint-disable-next-line @typescript-eslint/ban-ts-comment
2536
+ // @ts-ignore
2537
+ this.load.apply(null,loadEvent);}}/**
2538
+ * Get ready callback arguments and forward to ready call
2539
+ */},{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);}}/**
2540
+ * Process page arguments and forward to page call
2541
+ */// These overloads should be same as AnalyticsPageMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
2542
+ },{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);}}/**
2543
+ * Process track arguments and forward to page call
2544
+ */// These overloads should be same as AnalyticsTrackMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
2545
+ },{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);}}/**
2546
+ * Process identify arguments and forward to page call
2547
+ */// These overloads should be same as AnalyticsIdentifyMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
2548
+ },{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);}}/**
2549
+ * Process alias arguments and forward to page call
2550
+ */// These overloads should be same as AnalyticsAliasMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
2551
+ },{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);}}/**
2552
+ * Process group arguments and forward to page call
2553
+ */// These overloads should be same as AnalyticsGroupMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
2554
+ },{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);}}/**
2555
+ * Reset the analytics instance
2556
+ * @param options Reset options. Except for anonymousId, initialReferrer, and initialReferringDomain
2557
+ * all other values will be reset by default.
2558
+ * @example
2559
+ * ```ts
2560
+ * reset({
2561
+ * entries: {
2562
+ * anonymousId: true,
2563
+ * }
2564
+ * });
2565
+ * ```
2566
+ * @example
2567
+ * ```ts
2568
+ * reset({
2569
+ * entries: {
2570
+ * userId: false,
2571
+ * sessionInfo: false,
2572
+ * }
2573
+ * });
2574
+ * ```
2575
+ * @returns none
2576
+ */},{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
2577
+ defaultErrorHandler.init();// Initialize the storage engines with default options
2578
+ defaultCookieStorage.configure();defaultLocalStorage.configure();defaultSessionStorage.configure();defaultInMemoryStorage.configure();}}]);}();// START-NO-SONAR-SCAN
2579
+ // eslint-disable-next-line sonarjs/public-static-readonly
2580
+ _defineProperty(RudderAnalytics,"globalSingleton",null);
2581
+
2582
+ exports.RudderAnalytics = RudderAnalytics;