@rudderstack/analytics-js 3.0.0-beta.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,3881 @@
1
+ 'use strict';
2
+
3
+ var UaChTrackLevel=/*#__PURE__*/function(UaChTrackLevel){UaChTrackLevel["None"]="none";UaChTrackLevel["Default"]="default";UaChTrackLevel["Full"]="full";return UaChTrackLevel;}({});/**
4
+ * Represents the options parameter for anonymousId
5
+ */ /**
6
+ * Represents the beacon queue options parameter in loadOptions type
7
+ */var CookieSameSite=/*#__PURE__*/function(CookieSameSite){CookieSameSite["Strict"]="Strict";CookieSameSite["Lax"]="Lax";CookieSameSite["None"]="None";return CookieSameSite;}({});/**
8
+ * Represents the queue options parameter in loadOptions type
9
+ */ /**
10
+ * Represents the destinations queue options parameter in loadOptions type
11
+ */ /**
12
+ * Represents the options parameter in the load API
13
+ */
14
+
15
+ /**
16
+ * Represents residency server input the options
17
+ */var ResidencyServerRegion=/*#__PURE__*/function(ResidencyServerRegion){ResidencyServerRegion["US"]="US";ResidencyServerRegion["EU"]="EU";return ResidencyServerRegion;}({});
18
+
19
+ var LogLevel=/*#__PURE__*/function(LogLevel){LogLevel["Log"]="LOG";LogLevel["Info"]="INFO";LogLevel["Debug"]="DEBUG";LogLevel["Warn"]="WARN";LogLevel["Error"]="ERROR";LogLevel["None"]="NONE";return LogLevel;}({});
20
+
21
+ var PluginName=/*#__PURE__*/function(PluginName){PluginName["BeaconQueue"]="BeaconQueue";PluginName["DeviceModeDestinations"]="DeviceModeDestinations";PluginName["DeviceModeTransformation"]="DeviceModeTransformation";PluginName["ErrorReporting"]="ErrorReporting";PluginName["ExternalAnonymousId"]="ExternalAnonymousId";PluginName["GoogleLinker"]="GoogleLinker";PluginName["NativeDestinationQueue"]="NativeDestinationQueue";PluginName["StorageEncryption"]="StorageEncryption";PluginName["StorageEncryptionLegacy"]="StorageEncryptionLegacy";PluginName["StorageMigrator"]="StorageMigrator";PluginName["XhrQueue"]="XhrQueue";PluginName["OneTrustConsentManager"]="OneTrustConsentManager";PluginName["KetchConsentManager"]="KetchConsentManager";PluginName["Bugsnag"]="Bugsnag";return PluginName;}({});
22
+
23
+ function _iterableToArrayLimit(arr, i) {
24
+ var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
25
+ if (null != _i) {
26
+ var _s,
27
+ _e,
28
+ _x,
29
+ _r,
30
+ _arr = [],
31
+ _n = !0,
32
+ _d = !1;
33
+ try {
34
+ if (_x = (_i = _i.call(arr)).next, 0 === i) {
35
+ if (Object(_i) !== _i) return;
36
+ _n = !1;
37
+ } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
38
+ } catch (err) {
39
+ _d = !0, _e = err;
40
+ } finally {
41
+ try {
42
+ if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
43
+ } finally {
44
+ if (_d) throw _e;
45
+ }
46
+ }
47
+ return _arr;
48
+ }
49
+ }
50
+ function ownKeys(object, enumerableOnly) {
51
+ var keys = Object.keys(object);
52
+ if (Object.getOwnPropertySymbols) {
53
+ var symbols = Object.getOwnPropertySymbols(object);
54
+ enumerableOnly && (symbols = symbols.filter(function (sym) {
55
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
56
+ })), keys.push.apply(keys, symbols);
57
+ }
58
+ return keys;
59
+ }
60
+ function _objectSpread2(target) {
61
+ for (var i = 1; i < arguments.length; i++) {
62
+ var source = null != arguments[i] ? arguments[i] : {};
63
+ i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
64
+ _defineProperty(target, key, source[key]);
65
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
66
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
67
+ });
68
+ }
69
+ return target;
70
+ }
71
+ function _regeneratorRuntime() {
72
+ _regeneratorRuntime = function () {
73
+ return exports;
74
+ };
75
+ var exports = {},
76
+ Op = Object.prototype,
77
+ hasOwn = Op.hasOwnProperty,
78
+ defineProperty = Object.defineProperty || function (obj, key, desc) {
79
+ obj[key] = desc.value;
80
+ },
81
+ $Symbol = "function" == typeof Symbol ? Symbol : {},
82
+ iteratorSymbol = $Symbol.iterator || "@@iterator",
83
+ asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
84
+ toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
85
+ function define(obj, key, value) {
86
+ return Object.defineProperty(obj, key, {
87
+ value: value,
88
+ enumerable: !0,
89
+ configurable: !0,
90
+ writable: !0
91
+ }), obj[key];
92
+ }
93
+ try {
94
+ define({}, "");
95
+ } catch (err) {
96
+ define = function (obj, key, value) {
97
+ return obj[key] = value;
98
+ };
99
+ }
100
+ function wrap(innerFn, outerFn, self, tryLocsList) {
101
+ var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
102
+ generator = Object.create(protoGenerator.prototype),
103
+ context = new Context(tryLocsList || []);
104
+ return defineProperty(generator, "_invoke", {
105
+ value: makeInvokeMethod(innerFn, self, context)
106
+ }), generator;
107
+ }
108
+ function tryCatch(fn, obj, arg) {
109
+ try {
110
+ return {
111
+ type: "normal",
112
+ arg: fn.call(obj, arg)
113
+ };
114
+ } catch (err) {
115
+ return {
116
+ type: "throw",
117
+ arg: err
118
+ };
119
+ }
120
+ }
121
+ exports.wrap = wrap;
122
+ var ContinueSentinel = {};
123
+ function Generator() {}
124
+ function GeneratorFunction() {}
125
+ function GeneratorFunctionPrototype() {}
126
+ var IteratorPrototype = {};
127
+ define(IteratorPrototype, iteratorSymbol, function () {
128
+ return this;
129
+ });
130
+ var getProto = Object.getPrototypeOf,
131
+ NativeIteratorPrototype = getProto && getProto(getProto(values([])));
132
+ NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
133
+ var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
134
+ function defineIteratorMethods(prototype) {
135
+ ["next", "throw", "return"].forEach(function (method) {
136
+ define(prototype, method, function (arg) {
137
+ return this._invoke(method, arg);
138
+ });
139
+ });
140
+ }
141
+ function AsyncIterator(generator, PromiseImpl) {
142
+ function invoke(method, arg, resolve, reject) {
143
+ var record = tryCatch(generator[method], generator, arg);
144
+ if ("throw" !== record.type) {
145
+ var result = record.arg,
146
+ value = result.value;
147
+ return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
148
+ invoke("next", value, resolve, reject);
149
+ }, function (err) {
150
+ invoke("throw", err, resolve, reject);
151
+ }) : PromiseImpl.resolve(value).then(function (unwrapped) {
152
+ result.value = unwrapped, resolve(result);
153
+ }, function (error) {
154
+ return invoke("throw", error, resolve, reject);
155
+ });
156
+ }
157
+ reject(record.arg);
158
+ }
159
+ var previousPromise;
160
+ defineProperty(this, "_invoke", {
161
+ value: function (method, arg) {
162
+ function callInvokeWithMethodAndArg() {
163
+ return new PromiseImpl(function (resolve, reject) {
164
+ invoke(method, arg, resolve, reject);
165
+ });
166
+ }
167
+ return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
168
+ }
169
+ });
170
+ }
171
+ function makeInvokeMethod(innerFn, self, context) {
172
+ var state = "suspendedStart";
173
+ return function (method, arg) {
174
+ if ("executing" === state) throw new Error("Generator is already running");
175
+ if ("completed" === state) {
176
+ if ("throw" === method) throw arg;
177
+ return doneResult();
178
+ }
179
+ for (context.method = method, context.arg = arg;;) {
180
+ var delegate = context.delegate;
181
+ if (delegate) {
182
+ var delegateResult = maybeInvokeDelegate(delegate, context);
183
+ if (delegateResult) {
184
+ if (delegateResult === ContinueSentinel) continue;
185
+ return delegateResult;
186
+ }
187
+ }
188
+ if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
189
+ if ("suspendedStart" === state) throw state = "completed", context.arg;
190
+ context.dispatchException(context.arg);
191
+ } else "return" === context.method && context.abrupt("return", context.arg);
192
+ state = "executing";
193
+ var record = tryCatch(innerFn, self, context);
194
+ if ("normal" === record.type) {
195
+ if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
196
+ return {
197
+ value: record.arg,
198
+ done: context.done
199
+ };
200
+ }
201
+ "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
202
+ }
203
+ };
204
+ }
205
+ function maybeInvokeDelegate(delegate, context) {
206
+ var methodName = context.method,
207
+ method = delegate.iterator[methodName];
208
+ if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel;
209
+ var record = tryCatch(method, delegate.iterator, context.arg);
210
+ if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
211
+ var info = record.arg;
212
+ return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
213
+ }
214
+ function pushTryEntry(locs) {
215
+ var entry = {
216
+ tryLoc: locs[0]
217
+ };
218
+ 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
219
+ }
220
+ function resetTryEntry(entry) {
221
+ var record = entry.completion || {};
222
+ record.type = "normal", delete record.arg, entry.completion = record;
223
+ }
224
+ function Context(tryLocsList) {
225
+ this.tryEntries = [{
226
+ tryLoc: "root"
227
+ }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
228
+ }
229
+ function values(iterable) {
230
+ if (iterable) {
231
+ var iteratorMethod = iterable[iteratorSymbol];
232
+ if (iteratorMethod) return iteratorMethod.call(iterable);
233
+ if ("function" == typeof iterable.next) return iterable;
234
+ if (!isNaN(iterable.length)) {
235
+ var i = -1,
236
+ next = function next() {
237
+ for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
238
+ return next.value = undefined, next.done = !0, next;
239
+ };
240
+ return next.next = next;
241
+ }
242
+ }
243
+ return {
244
+ next: doneResult
245
+ };
246
+ }
247
+ function doneResult() {
248
+ return {
249
+ value: undefined,
250
+ done: !0
251
+ };
252
+ }
253
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
254
+ value: GeneratorFunctionPrototype,
255
+ configurable: !0
256
+ }), defineProperty(GeneratorFunctionPrototype, "constructor", {
257
+ value: GeneratorFunction,
258
+ configurable: !0
259
+ }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
260
+ var ctor = "function" == typeof genFun && genFun.constructor;
261
+ return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
262
+ }, exports.mark = function (genFun) {
263
+ return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
264
+ }, exports.awrap = function (arg) {
265
+ return {
266
+ __await: arg
267
+ };
268
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
269
+ return this;
270
+ }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
271
+ void 0 === PromiseImpl && (PromiseImpl = Promise);
272
+ var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
273
+ return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
274
+ return result.done ? result.value : iter.next();
275
+ });
276
+ }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
277
+ return this;
278
+ }), define(Gp, "toString", function () {
279
+ return "[object Generator]";
280
+ }), exports.keys = function (val) {
281
+ var object = Object(val),
282
+ keys = [];
283
+ for (var key in object) keys.push(key);
284
+ return keys.reverse(), function next() {
285
+ for (; keys.length;) {
286
+ var key = keys.pop();
287
+ if (key in object) return next.value = key, next.done = !1, next;
288
+ }
289
+ return next.done = !0, next;
290
+ };
291
+ }, exports.values = values, Context.prototype = {
292
+ constructor: Context,
293
+ reset: function (skipTempReset) {
294
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
295
+ },
296
+ stop: function () {
297
+ this.done = !0;
298
+ var rootRecord = this.tryEntries[0].completion;
299
+ if ("throw" === rootRecord.type) throw rootRecord.arg;
300
+ return this.rval;
301
+ },
302
+ dispatchException: function (exception) {
303
+ if (this.done) throw exception;
304
+ var context = this;
305
+ function handle(loc, caught) {
306
+ return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
307
+ }
308
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
309
+ var entry = this.tryEntries[i],
310
+ record = entry.completion;
311
+ if ("root" === entry.tryLoc) return handle("end");
312
+ if (entry.tryLoc <= this.prev) {
313
+ var hasCatch = hasOwn.call(entry, "catchLoc"),
314
+ hasFinally = hasOwn.call(entry, "finallyLoc");
315
+ if (hasCatch && hasFinally) {
316
+ if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
317
+ if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
318
+ } else if (hasCatch) {
319
+ if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
320
+ } else {
321
+ if (!hasFinally) throw new Error("try statement without catch or finally");
322
+ if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
323
+ }
324
+ }
325
+ }
326
+ },
327
+ abrupt: function (type, arg) {
328
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
329
+ var entry = this.tryEntries[i];
330
+ if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
331
+ var finallyEntry = entry;
332
+ break;
333
+ }
334
+ }
335
+ finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
336
+ var record = finallyEntry ? finallyEntry.completion : {};
337
+ return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
338
+ },
339
+ complete: function (record, afterLoc) {
340
+ if ("throw" === record.type) throw record.arg;
341
+ return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
342
+ },
343
+ finish: function (finallyLoc) {
344
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
345
+ var entry = this.tryEntries[i];
346
+ if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
347
+ }
348
+ },
349
+ catch: function (tryLoc) {
350
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
351
+ var entry = this.tryEntries[i];
352
+ if (entry.tryLoc === tryLoc) {
353
+ var record = entry.completion;
354
+ if ("throw" === record.type) {
355
+ var thrown = record.arg;
356
+ resetTryEntry(entry);
357
+ }
358
+ return thrown;
359
+ }
360
+ }
361
+ throw new Error("illegal catch attempt");
362
+ },
363
+ delegateYield: function (iterable, resultName, nextLoc) {
364
+ return this.delegate = {
365
+ iterator: values(iterable),
366
+ resultName: resultName,
367
+ nextLoc: nextLoc
368
+ }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
369
+ }
370
+ }, exports;
371
+ }
372
+ function _typeof(obj) {
373
+ "@babel/helpers - typeof";
374
+
375
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
376
+ return typeof obj;
377
+ } : function (obj) {
378
+ return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
379
+ }, _typeof(obj);
380
+ }
381
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
382
+ try {
383
+ var info = gen[key](arg);
384
+ var value = info.value;
385
+ } catch (error) {
386
+ reject(error);
387
+ return;
388
+ }
389
+ if (info.done) {
390
+ resolve(value);
391
+ } else {
392
+ Promise.resolve(value).then(_next, _throw);
393
+ }
394
+ }
395
+ function _asyncToGenerator(fn) {
396
+ return function () {
397
+ var self = this,
398
+ args = arguments;
399
+ return new Promise(function (resolve, reject) {
400
+ var gen = fn.apply(self, args);
401
+ function _next(value) {
402
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
403
+ }
404
+ function _throw(err) {
405
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
406
+ }
407
+ _next(undefined);
408
+ });
409
+ };
410
+ }
411
+ function _classCallCheck(instance, Constructor) {
412
+ if (!(instance instanceof Constructor)) {
413
+ throw new TypeError("Cannot call a class as a function");
414
+ }
415
+ }
416
+ function _defineProperties(target, props) {
417
+ for (var i = 0; i < props.length; i++) {
418
+ var descriptor = props[i];
419
+ descriptor.enumerable = descriptor.enumerable || false;
420
+ descriptor.configurable = true;
421
+ if ("value" in descriptor) descriptor.writable = true;
422
+ Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
423
+ }
424
+ }
425
+ function _createClass(Constructor, protoProps, staticProps) {
426
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
427
+ if (staticProps) _defineProperties(Constructor, staticProps);
428
+ Object.defineProperty(Constructor, "prototype", {
429
+ writable: false
430
+ });
431
+ return Constructor;
432
+ }
433
+ function _defineProperty(obj, key, value) {
434
+ key = _toPropertyKey(key);
435
+ if (key in obj) {
436
+ Object.defineProperty(obj, key, {
437
+ value: value,
438
+ enumerable: true,
439
+ configurable: true,
440
+ writable: true
441
+ });
442
+ } else {
443
+ obj[key] = value;
444
+ }
445
+ return obj;
446
+ }
447
+ function _slicedToArray(arr, i) {
448
+ return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
449
+ }
450
+ function _toConsumableArray(arr) {
451
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
452
+ }
453
+ function _arrayWithoutHoles(arr) {
454
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
455
+ }
456
+ function _arrayWithHoles(arr) {
457
+ if (Array.isArray(arr)) return arr;
458
+ }
459
+ function _iterableToArray(iter) {
460
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
461
+ }
462
+ function _unsupportedIterableToArray(o, minLen) {
463
+ if (!o) return;
464
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
465
+ var n = Object.prototype.toString.call(o).slice(8, -1);
466
+ if (n === "Object" && o.constructor) n = o.constructor.name;
467
+ if (n === "Map" || n === "Set") return Array.from(o);
468
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
469
+ }
470
+ function _arrayLikeToArray(arr, len) {
471
+ if (len == null || len > arr.length) len = arr.length;
472
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
473
+ return arr2;
474
+ }
475
+ function _nonIterableSpread() {
476
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
477
+ }
478
+ function _nonIterableRest() {
479
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
480
+ }
481
+ function _toPrimitive(input, hint) {
482
+ if (typeof input !== "object" || input === null) return input;
483
+ var prim = input[Symbol.toPrimitive];
484
+ if (prim !== undefined) {
485
+ var res = prim.call(input, hint || "default");
486
+ if (typeof res !== "object") return res;
487
+ throw new TypeError("@@toPrimitive must return a primitive value.");
488
+ }
489
+ return (hint === "string" ? String : Number)(input);
490
+ }
491
+ function _toPropertyKey(arg) {
492
+ var key = _toPrimitive(arg, "string");
493
+ return typeof key === "symbol" ? key : String(key);
494
+ }
495
+
496
+ function _isPlaceholder(a){return a!=null&&_typeof(a)==='object'&&a['@@functional/placeholder']===true;}
497
+
498
+ /**
499
+ * Optimized internal one-arity curry function.
500
+ *
501
+ * @private
502
+ * @category Function
503
+ * @param {Function} fn The function to curry.
504
+ * @return {Function} The curried function.
505
+ */function _curry1(fn){return function f1(a){if(arguments.length===0||_isPlaceholder(a)){return f1;}else {return fn.apply(this,arguments);}};}
506
+
507
+ /**
508
+ * Optimized internal two-arity curry function.
509
+ *
510
+ * @private
511
+ * @category Function
512
+ * @param {Function} fn The function to curry.
513
+ * @return {Function} The curried function.
514
+ */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);}};}
515
+
516
+ /**
517
+ * Optimized internal three-arity curry function.
518
+ *
519
+ * @private
520
+ * @category Function
521
+ * @param {Function} fn The function to curry.
522
+ * @return {Function} The curried function.
523
+ */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);}};}
524
+
525
+ /**
526
+ * Tests whether or not an object is an array.
527
+ *
528
+ * @private
529
+ * @param {*} val The object to test.
530
+ * @return {Boolean} `true` if `val` is an array, `false` otherwise.
531
+ * @example
532
+ *
533
+ * _isArray([]); //=> true
534
+ * _isArray(null); //=> false
535
+ * _isArray({}); //=> false
536
+ */var _isArray = Array.isArray||function _isArray(val){return val!=null&&val.length>=0&&Object.prototype.toString.call(val)==='[object Array]';};
537
+
538
+ function _arrayFromIterator(iter){var list=[];var next;while(!(next=iter.next()).done){list.push(next.value);}return list;}
539
+
540
+ function _includesWith(pred,x,list){var idx=0;var len=list.length;while(idx<len){if(pred(x,list[idx])){return true;}idx+=1;}return false;}
541
+
542
+ function _functionName(f){// String(x => x) evaluates to "x => x", so the pattern may not match.
543
+ var match=String(f).match(/^function (\w*)/);return match==null?'':match[1];}
544
+
545
+ function _has(prop,obj){return Object.prototype.hasOwnProperty.call(obj,prop);}
546
+
547
+ // Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
548
+ function _objectIs(a,b){// SameValue algorithm
549
+ if(a===b){// Steps 1-5, 7-10
550
+ // Steps 6.b-6.e: +0 != -0
551
+ return a!==0||1/a===1/b;}else {// Step 6.a: NaN == NaN
552
+ return a!==a&&b!==b;}}var _objectIs$1 = typeof Object.is==='function'?Object.is:_objectIs;
553
+
554
+ var toString=Object.prototype.toString;var _isArguments=/*#__PURE__*/function(){return toString.call(arguments)==='[object Arguments]'?function _isArguments(x){return toString.call(x)==='[object Arguments]';}:function _isArguments(x){return _has('callee',x);};}();
555
+
556
+ var hasEnumBug=!/*#__PURE__*/{toString:null}.propertyIsEnumerable('toString');var nonEnumerableProps=['constructor','valueOf','isPrototypeOf','toString','propertyIsEnumerable','hasOwnProperty','toLocaleString'];// Safari bug
557
+ var hasArgsEnumBug=/*#__PURE__*/function(){return arguments.propertyIsEnumerable('length');}();var contains=function contains(list,item){var idx=0;while(idx<list.length){if(list[idx]===item){return true;}idx+=1;}return false;};/**
558
+ * Returns a list containing the names of all the enumerable own properties of
559
+ * the supplied object.
560
+ * Note that the order of the output array is not guaranteed to be consistent
561
+ * across different JS platforms.
562
+ *
563
+ * @func
564
+ * @memberOf R
565
+ * @since v0.1.0
566
+ * @category Object
567
+ * @sig {k: v} -> [k]
568
+ * @param {Object} obj The object to extract properties from
569
+ * @return {Array} An array of the object's own properties.
570
+ * @see R.keysIn, R.values, R.toPairs
571
+ * @example
572
+ *
573
+ * R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c']
574
+ */var keys=typeof Object.keys==='function'&&!hasArgsEnumBug?/*#__PURE__*/_curry1(function keys(obj){return Object(obj)!==obj?[]:Object.keys(obj);}):/*#__PURE__*/_curry1(function keys(obj){if(Object(obj)!==obj){return [];}var prop,nIdx;var ks=[];var checkArgsLength=hasArgsEnumBug&&_isArguments(obj);for(prop in obj){if(_has(prop,obj)&&(!checkArgsLength||prop!=='length')){ks[ks.length]=prop;}}if(hasEnumBug){nIdx=nonEnumerableProps.length-1;while(nIdx>=0){prop=nonEnumerableProps[nIdx];if(_has(prop,obj)&&!contains(ks,prop)){ks[ks.length]=prop;}nIdx-=1;}}return ks;});
575
+
576
+ /**
577
+ * Gives a single-word string description of the (native) type of a value,
578
+ * returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not
579
+ * attempt to distinguish user Object types any further, reporting them all as
580
+ * 'Object'.
581
+ *
582
+ * @func
583
+ * @memberOf R
584
+ * @since v0.8.0
585
+ * @category Type
586
+ * @sig * -> String
587
+ * @param {*} val The value to test
588
+ * @return {String}
589
+ * @example
590
+ *
591
+ * R.type({}); //=> "Object"
592
+ * R.type(1); //=> "Number"
593
+ * R.type(false); //=> "Boolean"
594
+ * R.type('s'); //=> "String"
595
+ * R.type(null); //=> "Null"
596
+ * R.type([]); //=> "Array"
597
+ * R.type(/[A-z]/); //=> "RegExp"
598
+ * R.type(() => {}); //=> "Function"
599
+ * R.type(undefined); //=> "Undefined"
600
+ */var type=/*#__PURE__*/_curry1(function type(val){return val===null?'Null':val===undefined?'Undefined':Object.prototype.toString.call(val).slice(8,-1);});
601
+
602
+ /**
603
+ * private _uniqContentEquals function.
604
+ * That function is checking equality of 2 iterator contents with 2 assumptions
605
+ * - iterators lengths are the same
606
+ * - iterators values are unique
607
+ *
608
+ * false-positive result will be returned for comparison of, e.g.
609
+ * - [1,2,3] and [1,2,3,4]
610
+ * - [1,1,1] and [1,2,3]
611
+ * */function _uniqContentEquals(aIterator,bIterator,stackA,stackB){var a=_arrayFromIterator(aIterator);var b=_arrayFromIterator(bIterator);function eq(_a,_b){return _equals(_a,_b,stackA.slice(),stackB.slice());}// if *a* array contains any element that is not included in *b*
612
+ return !_includesWith(function(b,aItem){return !_includesWith(eq,aItem,b);},b,a);}function _equals(a,b,stackA,stackB){if(_objectIs$1(a,b)){return true;}var typeA=type(a);if(typeA!==type(b)){return false;}if(typeof a['fantasy-land/equals']==='function'||typeof b['fantasy-land/equals']==='function'){return typeof a['fantasy-land/equals']==='function'&&a['fantasy-land/equals'](b)&&typeof b['fantasy-land/equals']==='function'&&b['fantasy-land/equals'](a);}if(typeof a.equals==='function'||typeof b.equals==='function'){return typeof a.equals==='function'&&a.equals(b)&&typeof b.equals==='function'&&b.equals(a);}switch(typeA){case'Arguments':case'Array':case'Object':if(typeof a.constructor==='function'&&_functionName(a.constructor)==='Promise'){return a===b;}break;case'Boolean':case'Number':case'String':if(!(_typeof(a)===_typeof(b)&&_objectIs$1(a.valueOf(),b.valueOf()))){return false;}break;case'Date':if(!_objectIs$1(a.valueOf(),b.valueOf())){return false;}break;case'Error':return a.name===b.name&&a.message===b.message;case'RegExp':if(!(a.source===b.source&&a.global===b.global&&a.ignoreCase===b.ignoreCase&&a.multiline===b.multiline&&a.sticky===b.sticky&&a.unicode===b.unicode)){return false;}break;}var idx=stackA.length-1;while(idx>=0){if(stackA[idx]===a){return stackB[idx]===b;}idx-=1;}switch(typeA){case'Map':if(a.size!==b.size){return false;}return _uniqContentEquals(a.entries(),b.entries(),stackA.concat([a]),stackB.concat([b]));case'Set':if(a.size!==b.size){return false;}return _uniqContentEquals(a.values(),b.values(),stackA.concat([a]),stackB.concat([b]));case'Arguments':case'Array':case'Object':case'Boolean':case'Number':case'String':case'Date':case'Error':case'RegExp':case'Int8Array':case'Uint8Array':case'Uint8ClampedArray':case'Int16Array':case'Uint16Array':case'Int32Array':case'Uint32Array':case'Float32Array':case'Float64Array':case'ArrayBuffer':break;default:// Values of other types are only equal if identical.
613
+ return false;}var keysA=keys(a);if(keysA.length!==keys(b).length){return false;}var extendedStackA=stackA.concat([a]);var extendedStackB=stackB.concat([b]);idx=keysA.length-1;while(idx>=0){var key=keysA[idx];if(!(_has(key,b)&&_equals(b[key],a[key],extendedStackA,extendedStackB))){return false;}idx-=1;}return true;}
614
+
615
+ /**
616
+ * Returns `true` if its arguments are equivalent, `false` otherwise. Handles
617
+ * cyclical data structures.
618
+ *
619
+ * Dispatches symmetrically to the `equals` methods of both arguments, if
620
+ * present.
621
+ *
622
+ * @func
623
+ * @memberOf R
624
+ * @since v0.15.0
625
+ * @category Relation
626
+ * @sig a -> b -> Boolean
627
+ * @param {*} a
628
+ * @param {*} b
629
+ * @return {Boolean}
630
+ * @example
631
+ *
632
+ * R.equals(1, 1); //=> true
633
+ * R.equals(1, '1'); //=> false
634
+ * R.equals([1, 2, 3], [1, 2, 3]); //=> true
635
+ *
636
+ * const a = {}; a.v = a;
637
+ * const b = {}; b.v = b;
638
+ * R.equals(a, b); //=> true
639
+ */var equals=/*#__PURE__*/_curry2(function equals(a,b){return _equals(a,b,[],[]);});
640
+
641
+ function _isObject(x){return Object.prototype.toString.call(x)==='[object Object]';}
642
+
643
+ /**
644
+ * Determine if the passed argument is an integer.
645
+ *
646
+ * @private
647
+ * @param {*} n
648
+ * @category Type
649
+ * @return {Boolean}
650
+ */var _isInteger = Number.isInteger||function _isInteger(n){return n<<0===n;};
651
+
652
+ function _isString(x){return Object.prototype.toString.call(x)==='[object String]';}
653
+
654
+ /**
655
+ * Returns the nth element of the given list or string. If n is negative the
656
+ * element at index length + n is returned.
657
+ *
658
+ * @func
659
+ * @memberOf R
660
+ * @since v0.1.0
661
+ * @category List
662
+ * @sig Number -> [a] -> a | Undefined
663
+ * @sig Number -> String -> String
664
+ * @param {Number} offset
665
+ * @param {*} list
666
+ * @return {*}
667
+ * @example
668
+ *
669
+ * const list = ['foo', 'bar', 'baz', 'quux'];
670
+ * R.nth(1, list); //=> 'bar'
671
+ * R.nth(-1, list); //=> 'quux'
672
+ * R.nth(-99, list); //=> undefined
673
+ *
674
+ * R.nth(2, 'abc'); //=> 'c'
675
+ * R.nth(3, 'abc'); //=> ''
676
+ * @symb R.nth(-1, [a, b, c]) = c
677
+ * @symb R.nth(0, [a, b, c]) = a
678
+ * @symb R.nth(1, [a, b, c]) = b
679
+ */var nth=/*#__PURE__*/_curry2(function nth(offset,list){var idx=offset<0?list.length+offset:offset;return _isString(list)?list.charAt(idx):list[idx];});
680
+
681
+ 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':''));}
682
+
683
+ /**
684
+ * Copies an object.
685
+ *
686
+ * @private
687
+ * @param {*} value The value to be copied
688
+ * @param {Boolean} deep Whether or not to perform deep cloning.
689
+ * @return {*} The copied value.
690
+ */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.
691
+ 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.
692
+ 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]=deep?_clone(value[key],true,map):value[key];}}return copiedValue;};switch(type(value)){case'Object':return copy(Object.create(Object.getPrototypeOf(value)));case'Array':return copy([]);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){/**
693
+ * 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,
694
+ * on my tests this number is 180, anything above that using the hash function is faster.
695
+ */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;}();
696
+
697
+ /**
698
+ * Creates a deep copy of the source that can be used in place of the source
699
+ * object without retaining any references to it.
700
+ * The source object may contain (nested) `Array`s and `Object`s,
701
+ * `Number`s, `String`s, `Boolean`s and `Date`s.
702
+ * `Function`s are assigned by reference rather than copied.
703
+ *
704
+ * Dispatches to a `clone` method if present.
705
+ *
706
+ * Note that if the source object has multiple nodes that share a reference,
707
+ * the returned object will have the same structure, but the references will
708
+ * be pointed to the location within the cloned value.
709
+ *
710
+ * @func
711
+ * @memberOf R
712
+ * @since v0.1.0
713
+ * @category Object
714
+ * @sig {*} -> {*}
715
+ * @param {*} value The object or array to clone
716
+ * @return {*} A deeply cloned copy of `val`
717
+ * @example
718
+ *
719
+ * const objects = [{}, {}, {}];
720
+ * const objectsClone = R.clone(objects);
721
+ * objects === objectsClone; //=> false
722
+ * objects[0] === objectsClone[0]; //=> false
723
+ */var clone=/*#__PURE__*/_curry1(function clone(value){return value!=null&&typeof value.clone==='function'?value.clone():_clone(value,true);});var clone$1 = clone;
724
+
725
+ /**
726
+ * Tests whether or not an object is a typed array.
727
+ *
728
+ * @private
729
+ * @param {*} val The object to test.
730
+ * @return {Boolean} `true` if `val` is a typed array, `false` otherwise.
731
+ * @example
732
+ *
733
+ * _isTypedArray(new Uint8Array([])); //=> true
734
+ * _isTypedArray(new Float32Array([])); //=> true
735
+ * _isTypedArray([]); //=> false
736
+ * _isTypedArray(null); //=> false
737
+ * _isTypedArray({}); //=> false
738
+ */function _isTypedArray(val){var type=Object.prototype.toString.call(val);return type==='[object Uint8ClampedArray]'||type==='[object Int8Array]'||type==='[object Uint8Array]'||type==='[object Int16Array]'||type==='[object Uint16Array]'||type==='[object Int32Array]'||type==='[object Uint32Array]'||type==='[object Float32Array]'||type==='[object Float64Array]'||type==='[object BigInt64Array]'||type==='[object BigUint64Array]';}
739
+
740
+ /**
741
+ * Returns the empty value of its argument's type. Ramda defines the empty
742
+ * value of Array (`[]`), Object (`{}`), String (`''`),
743
+ * TypedArray (`Uint8Array []`, `Float32Array []`, etc), and Arguments. Other
744
+ * types are supported if they define `<Type>.empty`,
745
+ * `<Type>.prototype.empty` or implement the
746
+ * [FantasyLand Monoid spec](https://github.com/fantasyland/fantasy-land#monoid).
747
+ *
748
+ * Dispatches to the `empty` method of the first argument, if present.
749
+ *
750
+ * @func
751
+ * @memberOf R
752
+ * @since v0.3.0
753
+ * @category Function
754
+ * @sig a -> a
755
+ * @param {*} x
756
+ * @return {*}
757
+ * @example
758
+ *
759
+ * R.empty(Just(42)); //=> Nothing()
760
+ * R.empty([1, 2, 3]); //=> []
761
+ * R.empty('unicorns'); //=> ''
762
+ * R.empty({x: 1, y: 2}); //=> {}
763
+ * R.empty(Uint8Array.from('123')); //=> Uint8Array []
764
+ */var empty=/*#__PURE__*/_curry1(function empty(x){return x!=null&&typeof x['fantasy-land/empty']==='function'?x['fantasy-land/empty']():x!=null&&x.constructor!=null&&typeof x.constructor['fantasy-land/empty']==='function'?x.constructor['fantasy-land/empty']():x!=null&&typeof x.empty==='function'?x.empty():x!=null&&x.constructor!=null&&typeof x.constructor.empty==='function'?x.constructor.empty():_isArray(x)?[]:_isString(x)?'':_isObject(x)?{}:_isArguments(x)?function(){return arguments;}():_isTypedArray(x)?x.constructor.from(''):void 0// else
765
+ ;});
766
+
767
+ /**
768
+ * Returns `true` if the given value is its type's empty value; `false`
769
+ * otherwise.
770
+ *
771
+ * @func
772
+ * @memberOf R
773
+ * @since v0.1.0
774
+ * @category Logic
775
+ * @sig a -> Boolean
776
+ * @param {*} x
777
+ * @return {Boolean}
778
+ * @see R.empty
779
+ * @example
780
+ *
781
+ * R.isEmpty([1, 2, 3]); //=> false
782
+ * R.isEmpty([]); //=> true
783
+ * R.isEmpty(''); //=> true
784
+ * R.isEmpty(null); //=> false
785
+ * R.isEmpty({}); //=> true
786
+ * R.isEmpty({length: 0}); //=> false
787
+ * R.isEmpty(Uint8Array.from('')); //=> true
788
+ */var isEmpty=/*#__PURE__*/_curry1(function isEmpty(x){return x!=null&&equals(x,empty(x));});var isEmpty$1 = isEmpty;
789
+
790
+ /**
791
+ * Retrieves the values at given paths of an object.
792
+ *
793
+ * @func
794
+ * @memberOf R
795
+ * @since v0.27.1
796
+ * @category Object
797
+ * @typedefn Idx = [String | Int | Symbol]
798
+ * @sig [Idx] -> {a} -> [a | Undefined]
799
+ * @param {Array} pathsArray The array of paths to be fetched.
800
+ * @param {Object} obj The object to retrieve the nested properties from.
801
+ * @return {Array} A list consisting of values at paths specified by "pathsArray".
802
+ * @see R.path
803
+ * @example
804
+ *
805
+ * R.paths([['a', 'b'], ['p', 0, 'q']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, 3]
806
+ * R.paths([['a', 'b'], ['p', 'r']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, undefined]
807
+ */var paths=/*#__PURE__*/_curry2(function paths(pathsArray,obj){return pathsArray.map(function(paths){var val=obj;var idx=0;var p;while(idx<paths.length){if(val==null){return;}p=paths[idx];val=_isInteger(p)?nth(p,val):val[p];idx+=1;}return val;});});
808
+
809
+ /**
810
+ * Retrieves the value at a given path. The nodes of the path can be arbitrary strings or non-negative integers.
811
+ * For anything else, the value is unspecified. Integer paths are meant to index arrays, strings are meant for objects.
812
+ *
813
+ * @func
814
+ * @memberOf R
815
+ * @since v0.2.0
816
+ * @category Object
817
+ * @typedefn Idx = String | Int | Symbol
818
+ * @sig [Idx] -> {a} -> a | Undefined
819
+ * @sig Idx = String | NonNegativeInt
820
+ * @param {Array} path The path to use.
821
+ * @param {Object} obj The object or array to retrieve the nested property from.
822
+ * @return {*} The data at `path`.
823
+ * @see R.prop, R.nth, R.assocPath, R.dissocPath
824
+ * @example
825
+ *
826
+ * R.path(['a', 'b'], {a: {b: 2}}); //=> 2
827
+ * R.path(['a', 'b'], {c: {b: 2}}); //=> undefined
828
+ * R.path(['a', 'b', 0], {a: {b: [1, 2, 3]}}); //=> 1
829
+ * R.path(['a', 'b', -2], {a: {b: [1, 2, 3]}}); //=> 2
830
+ * R.path([2], {'2': 2}); //=> 2
831
+ * R.path([-2], {'-2': 'a'}); //=> undefined
832
+ */var path=/*#__PURE__*/_curry2(function path(pathAr,obj){return paths([pathAr],obj)[0];});var path$1 = path;
833
+
834
+ /**
835
+ * Creates a new object with the own properties of the two provided objects. If
836
+ * a key exists in both objects, the provided function is applied to the key
837
+ * and the values associated with the key in each object, with the result being
838
+ * used as the value associated with the key in the returned object.
839
+ *
840
+ * @func
841
+ * @memberOf R
842
+ * @since v0.19.0
843
+ * @category Object
844
+ * @sig ((String, a, a) -> a) -> {a} -> {a} -> {a}
845
+ * @param {Function} fn
846
+ * @param {Object} l
847
+ * @param {Object} r
848
+ * @return {Object}
849
+ * @see R.mergeDeepWithKey, R.merge, R.mergeWith
850
+ * @example
851
+ *
852
+ * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r
853
+ * R.mergeWithKey(concatValues,
854
+ * { a: true, thing: 'foo', values: [10, 20] },
855
+ * { b: true, thing: 'bar', values: [15, 35] });
856
+ * //=> { a: true, b: true, thing: 'bar', values: [10, 20, 15, 35] }
857
+ * @symb R.mergeWithKey(f, { x: 1, y: 2 }, { y: 5, z: 3 }) = { x: 1, y: f('y', 2, 5), z: 3 }
858
+ */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;});
859
+
860
+ /**
861
+ * Creates a new object with the own properties of the two provided objects.
862
+ * If a key exists in both objects:
863
+ * - and both associated values are also objects then the values will be
864
+ * recursively merged.
865
+ * - otherwise the provided function is applied to the key and associated values
866
+ * using the resulting value as the new value associated with the key.
867
+ * If a key only exists in one object, the value will be associated with the key
868
+ * of the resulting object.
869
+ *
870
+ * @func
871
+ * @memberOf R
872
+ * @since v0.24.0
873
+ * @category Object
874
+ * @sig ((String, a, a) -> a) -> {a} -> {a} -> {a}
875
+ * @param {Function} fn
876
+ * @param {Object} lObj
877
+ * @param {Object} rObj
878
+ * @return {Object}
879
+ * @see R.mergeWithKey, R.mergeDeepWith
880
+ * @example
881
+ *
882
+ * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r
883
+ * R.mergeDeepWithKey(concatValues,
884
+ * { a: true, c: { thing: 'foo', values: [10, 20] }},
885
+ * { b: true, c: { thing: 'bar', values: [15, 35] }});
886
+ * //=> { a: true, b: true, c: { thing: 'bar', values: [10, 20, 15, 35] }}
887
+ */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);});
888
+
889
+ /**
890
+ * Creates a new object with the own properties of the two provided objects.
891
+ * If a key exists in both objects:
892
+ * - and both associated values are also objects then the values will be
893
+ * recursively merged.
894
+ * - otherwise the provided function is applied to associated values using the
895
+ * resulting value as the new value associated with the key.
896
+ * If a key only exists in one object, the value will be associated with the key
897
+ * of the resulting object.
898
+ *
899
+ * @func
900
+ * @memberOf R
901
+ * @since v0.24.0
902
+ * @category Object
903
+ * @sig ((a, a) -> a) -> {a} -> {a} -> {a}
904
+ * @param {Function} fn
905
+ * @param {Object} lObj
906
+ * @param {Object} rObj
907
+ * @return {Object}
908
+ * @see R.mergeWith, R.mergeDeepWithKey
909
+ * @example
910
+ *
911
+ * R.mergeDeepWith(R.concat,
912
+ * { a: true, c: { values: [10, 20] }},
913
+ * { b: true, c: { values: [15, 35] }});
914
+ * //=> { a: true, b: true, c: { values: [10, 20, 15, 35] }}
915
+ */var mergeDeepWith=/*#__PURE__*/_curry3(function mergeDeepWith(fn,lObj,rObj){return mergeDeepWithKey(function(k,lVal,rVal){return fn(lVal,rVal);},lObj,rObj);});var mergeDeepWith$1 = mergeDeepWith;
916
+
917
+ /**
918
+ * Returns a partial copy of an object containing only the keys that satisfy
919
+ * the supplied predicate.
920
+ *
921
+ * @func
922
+ * @memberOf R
923
+ * @since v0.8.0
924
+ * @category Object
925
+ * @sig ((v, k) -> Boolean) -> {k: v} -> {k: v}
926
+ * @param {Function} pred A predicate to determine whether or not a key
927
+ * should be included on the output object.
928
+ * @param {Object} obj The object to copy from
929
+ * @return {Object} A new object with only properties that satisfy `pred`
930
+ * on it.
931
+ * @see R.pick, R.filter
932
+ * @example
933
+ *
934
+ * const isUpperCase = (val, key) => key.toUpperCase() === key;
935
+ * R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4}
936
+ */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;});var pickBy$1 = pickBy;
937
+
938
+ /**
939
+ * A function to check given value is a function
940
+ * @param value input value
941
+ * @returns boolean
942
+ */var isFunction=function isFunction(value){return typeof value==='function'&&Boolean(value.constructor&&value.call&&value.apply);};/**
943
+ * A function to check given value is a string
944
+ * @param value input value
945
+ * @returns boolean
946
+ */var isString=function isString(value){return typeof value==='string';};/**
947
+ * A function to check given value is null or not
948
+ * @param value input value
949
+ * @returns boolean
950
+ */var isNull=function isNull(value){return value===null;};/**
951
+ * A function to check given value is undefined
952
+ * @param value input value
953
+ * @returns boolean
954
+ */var isUndefined=function isUndefined(value){return typeof value==='undefined';};/**
955
+ * A function to check given value is null or undefined
956
+ * @param value input value
957
+ * @returns boolean
958
+ */var isNullOrUndefined=function isNullOrUndefined(value){return isNull(value)||isUndefined(value);};/**
959
+ * A function to check given value is defined
960
+ * @param value input value
961
+ * @returns boolean
962
+ */var isDefined=function isDefined(value){return !isUndefined(value);};/**
963
+ * A function to check given value is defined and not null
964
+ * @param value input value
965
+ * @returns boolean
966
+ */var isDefinedAndNotNull=function isDefinedAndNotNull(value){return !isNullOrUndefined(value);};/**
967
+ * Determines if the input is an instance of Error
968
+ * @param obj input value
969
+ * @returns true if the input is an instance of Error and false otherwise
970
+ */var isTypeOfError=function isTypeOfError(obj){return obj instanceof Error;};
971
+
972
+ var getValueByPath=function getValueByPath(obj,keyPath){var pathParts=keyPath.split('.');return path$1(pathParts,obj);};var hasValueByPath=function hasValueByPath(obj,path){return Boolean(getValueByPath(obj,path));};/**
973
+ * Checks if the input is an object literal or built-in object type and not null
974
+ * @param value Input value
975
+ * @returns true if the input is an object and not null
976
+ */var isObjectAndNotNull=function isObjectAndNotNull(value){return !isNull(value)&&_typeof(value)==='object'&&!Array.isArray(value);};/**
977
+ * Checks if the input is an object literal and not null
978
+ * @param value Input value
979
+ * @returns true if the input is an object and not null
980
+ */var isObjectLiteralAndNotNull=function isObjectLiteralAndNotNull(value){return !isNull(value)&&Object.prototype.toString.call(value)==='[object Object]';};var mergeDeepRightObjectArrays=function mergeDeepRightObjectArrays(leftValue,rightValue){if(!Array.isArray(leftValue)||!Array.isArray(rightValue)){return clone$1(rightValue);}var mergedArray=clone$1(leftValue);rightValue.forEach(function(value,index){mergedArray[index]=Array.isArray(value)||isObjectAndNotNull(value)?// eslint-disable-next-line @typescript-eslint/no-use-before-define
981
+ mergeDeepRight(mergedArray[index],value):value;});return mergedArray;};var mergeDeepRight=function mergeDeepRight(leftObject,rightObject){return mergeDeepWith$1(mergeDeepRightObjectArrays,leftObject,rightObject);};/**
982
+ Checks if the input is a non-empty object literal type and not undefined or null
983
+ * @param value input any
984
+ * @returns boolean
985
+ */var isNonEmptyObject=function isNonEmptyObject(value){return isObjectLiteralAndNotNull(value)&&Object.keys(value).length>0;};/**
986
+ * A utility to recursively remove undefined values from an object
987
+ * @param obj input object
988
+ * @returns a new object
989
+ */var removeUndefinedValues=function removeUndefinedValues(obj){var result=pickBy$1(isDefined,obj);Object.entries(result).forEach(function(_ref){var _ref2=_slicedToArray(_ref,2),key=_ref2[0],value=_ref2[1];if(isObjectLiteralAndNotNull(value)){result[key]=removeUndefinedValues(value);}});return result;};/**
990
+ * A utility to recursively remove undefined and null values from an object
991
+ * @param obj input object
992
+ * @returns a new object
993
+ */var removeUndefinedAndNullValues=function removeUndefinedAndNullValues(obj){var result=pickBy$1(isDefinedAndNotNull,obj);Object.entries(result).forEach(function(_ref3){var _ref4=_slicedToArray(_ref3,2),key=_ref4[0],value=_ref4[1];if(isObjectLiteralAndNotNull(value)){result[key]=removeUndefinedAndNullValues(value);}});return result;};
994
+
995
+ var trim=function trim(value){return value.replace(/^\s+|\s+$/gm,'');};var removeDoubleSpaces=function removeDoubleSpaces(value){return value.replace(/ {2,}/g,' ');};/**
996
+ * A function to convert values to string
997
+ * @param val input value
998
+ * @returns stringified value
999
+ */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
1000
+ // https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem
1001
+ /**
1002
+ * Converts a base64 encoded string to bytes array
1003
+ * @param base64Str base64 encoded string
1004
+ * @returns bytes array
1005
+ */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);};/**
1006
+ * Converts a bytes array to base64 encoded string
1007
+ * @param bytes bytes array to be converted to base64
1008
+ * @returns base64 encoded string
1009
+ */var bytesToBase64=function bytesToBase64(bytes){var binString=Array.from(bytes,function(x){return String.fromCodePoint(x);}).join('');return globalThis.btoa(binString);};/**
1010
+ * Encodes a string to base64 even with unicode characters
1011
+ * @param value input string
1012
+ * @returns base64 encoded string
1013
+ */var toBase64=function toBase64(value){return bytesToBase64(new TextEncoder().encode(value));};/**
1014
+ * Decodes a base64 encoded string
1015
+ * @param value base64 encoded string
1016
+ * @returns decoded string
1017
+ */var fromBase64=function fromBase64(value){return new TextDecoder().decode(base64ToBytes(value));};
1018
+
1019
+ // if yes make them null instead of omitting in overloaded cases
1020
+ /*
1021
+ * Normalise the overloaded arguments of the page call facade
1022
+ */var pageArgumentsToCallOptions=function pageArgumentsToCallOptions(category,name,properties,options,callback){var payload={};if(isFunction(callback)){payload.category=category;payload.name=name;payload.properties=clone$1(properties);payload.options=clone$1(options);payload.callback=callback;}if(isFunction(options)){payload.category=category;payload.name=name;payload.properties=clone$1(properties);payload.callback=options;}if(isFunction(properties)){payload.category=category;payload.name=name;payload.callback=properties;}if(isFunction(name)){payload.category=category;payload.callback=name;}if(isFunction(category)){payload.callback=category;}if(isObjectLiteralAndNotNull(category)){payload.options=clone$1(name);payload.properties=clone$1(category);delete payload.name;delete payload.category;}else if(isObjectLiteralAndNotNull(name)){payload.options=clone$1(properties);payload.properties=clone$1(name);delete payload.name;}if(isObjectLiteralAndNotNull(options)&&!isString(payload.options)){payload.options=options;}if(isObjectLiteralAndNotNull(properties)&&!isString(payload.properties)&&!isObjectLiteralAndNotNull(name)){payload.properties=properties;}if(isString(category)&&!isString(payload.category)){payload.category=category;}if(isString(name)&&!isString(payload.name)){payload.name=name;}if(isString(payload.category)&&!isString(payload.name)){payload.name=payload.category;delete payload.category;}if(isUndefined(payload.category)){delete payload.category;}payload.properties=mergeDeepRight(payload.properties&&isObjectLiteralAndNotNull(payload.properties)?payload.properties:{},{name:isString(payload.name)?payload.name:null,category:isString(payload.category)?payload.category:null});return payload;};/*
1023
+ * Normalise the overloaded arguments of the track call facade
1024
+ */var trackArgumentsToCallOptions=function trackArgumentsToCallOptions(event,properties,options,callback){var payload={name:event};if(isFunction(callback)){payload.properties=clone$1(properties);payload.options=clone$1(options);payload.callback=callback;}if(isFunction(options)){payload.properties=clone$1(properties);payload.callback=options;}if(isFunction(properties)){payload.callback=properties;}if(isObjectLiteralAndNotNull(options)||isNull(options)){payload.options=options;}if(isObjectLiteralAndNotNull(properties)||isNull(properties)){payload.properties=properties;}// To match v1.1 generated payload
1025
+ if(isUndefined(payload.properties)||isNull(payload.properties)){payload.properties={};}return payload;};/*
1026
+ * Normalise the overloaded arguments of the identify call facade
1027
+ */var identifyArgumentsToCallOptions=function identifyArgumentsToCallOptions(userId,traits,options,callback){var payload={};if(isFunction(callback)){payload.traits=clone$1(traits);payload.options=clone$1(options);payload.callback=callback;}if(isFunction(options)){payload.traits=clone$1(traits);payload.callback=options;}if(isFunction(traits)){payload.callback=traits;}if(isObjectLiteralAndNotNull(userId)||isNull(userId)){delete payload.userId;payload.traits=clone$1(userId);payload.options=clone$1(traits);}else {payload.userId=tryStringify(userId);if(!isUndefined(traits)&&!isFunction(traits)){payload.traits=clone$1(traits);}if(!isUndefined(options)&&!isFunction(options)){payload.options=clone$1(options);}}return payload;};/*
1028
+ * Normalise the overloaded arguments of the alias call facade
1029
+ */var aliasArgumentsToCallOptions=function aliasArgumentsToCallOptions(to,from,options,callback){var payload={};if(isFunction(callback)){var _tryStringify;payload.to=(_tryStringify=tryStringify(to))!==null&&_tryStringify!==void 0?_tryStringify:null;payload.from=from;payload.options=clone$1(options);payload.callback=callback;}if(isFunction(options)){var _tryStringify2;payload.to=(_tryStringify2=tryStringify(to))!==null&&_tryStringify2!==void 0?_tryStringify2:null;payload.from=from;payload.callback=options;}if(isFunction(from)){var _tryStringify3;payload.to=(_tryStringify3=tryStringify(to))!==null&&_tryStringify3!==void 0?_tryStringify3:null;payload.callback=from;}else if(isObjectLiteralAndNotNull(from)||isNull(from)){var _tryStringify4;payload.to=(_tryStringify4=tryStringify(to))!==null&&_tryStringify4!==void 0?_tryStringify4:null;payload.options=isNull(from)?null:clone$1(from);delete payload.from;}else {var _tryStringify5;payload.to=(_tryStringify5=tryStringify(to))!==null&&_tryStringify5!==void 0?_tryStringify5:null;payload.from=tryStringify(from);}if(isFunction(to)){payload.to=null;payload.callback=to;}if(isObjectLiteralAndNotNull(to)){payload.to=null;payload.options=clone$1(to);}return payload;};/*
1030
+ * Normalise the overloaded arguments of the group call facade
1031
+ */var groupArgumentsToCallOptions=function groupArgumentsToCallOptions(groupId,traits,options,callback){var payload={};if(isFunction(callback)){payload.traits=clone$1(traits);payload.options=clone$1(options);payload.callback=callback;}if(isFunction(options)){payload.traits=clone$1(traits);payload.callback=options;}if(isFunction(traits)){payload.callback=traits;}// TODO: why do we enable overload for group that only passes callback? is there any use case?
1032
+ if(isFunction(groupId)){payload.callback=groupId;}else if(isObjectLiteralAndNotNull(groupId)||isNull(groupId)){payload.traits=isNull(groupId)?undefined:clone$1(groupId);if(isFunction(traits)){payload.callback=traits;}else {payload.options=clone$1(traits);}}else {payload.groupId=tryStringify(groupId);payload.traits=!isObjectLiteralAndNotNull(traits)?undefined:clone$1(traits);payload.options=!isObjectLiteralAndNotNull(options)?undefined:clone$1(options);}return payload;};
1033
+
1034
+ 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';
1035
+
1036
+ /**
1037
+ * Create globally accessible RudderStackGlobals object
1038
+ */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]={};}};/**
1039
+ * Add move values to globally accessible RudderStackGlobals object per analytics instance
1040
+ */var setExposedGlobal=function setExposedGlobal(keyName,value){var analyticsInstanceId=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'app';createExposedGlobals(analyticsInstanceId);globalThis.RudderStackGlobals[analyticsInstanceId][keyName]=value;};/**
1041
+ * Get values from globally accessible RudderStackGlobals object by analytics instance
1042
+ */var getExposedGlobal=function getExposedGlobal(keyName){var analyticsInstanceId=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'app';createExposedGlobals(analyticsInstanceId);return globalThis.RudderStackGlobals[analyticsInstanceId][keyName];};
1043
+
1044
+ var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.0.0-beta.1';var APP_NAMESPACE='com.rudderlabs.javascript';var MODULE_TYPE='npm';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';
1045
+
1046
+ /**
1047
+ * Parse query string params into object values for keys that start with a defined prefix
1048
+ */var getEventDataFromQueryString=function getEventDataFromQueryString(params,dataTypeNamePrefix){var data={};params.forEach(function(value,key){if(key.startsWith(dataTypeNamePrefix)){// remove prefix from key name
1049
+ var dataKey=key.substring(dataTypeNamePrefix.length);// add new key value pair in generated object
1050
+ data[dataKey]=params.get(key);}});return data;};/**
1051
+ * Parse query string into preload buffer events & push into existing array before any other events
1052
+ */var retrieveEventsFromQueryString=function retrieveEventsFromQueryString(){var argumentsArray=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];// Mapping for trait and properties values based on key prefix
1053
+ 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
1054
+ if(queryObject.get(QUERY_PARAM_TRACK_EVENT_NAME_KEY)){argumentsArray.unshift(['track',queryObject.get(QUERY_PARAM_TRACK_EVENT_NAME_KEY),getEventDataFromQueryString(queryObject,eventArgumentToQueryParamMap.properties)]);}// Set userId and user traits
1055
+ if(queryObject.get(QUERY_PARAM_USER_ID_KEY)){argumentsArray.unshift(['identify',queryObject.get(QUERY_PARAM_USER_ID_KEY),getEventDataFromQueryString(queryObject,eventArgumentToQueryParamMap.trait)]);}// Set anonymousID
1056
+ if(queryObject.get(QUERY_PARAM_ANONYMOUS_ID_KEY)){argumentsArray.unshift(['setAnonymousId',queryObject.get(QUERY_PARAM_ANONYMOUS_ID_KEY)]);}};/**
1057
+ * Retrieve an existing buffered load method call and remove from the existing array
1058
+ */var getPreloadedLoadEvent=function getPreloadedLoadEvent(preloadedEventsArray){var loadMethodName='load';var loadEvent=[];/**
1059
+ * Iterate the buffered API calls until we find load call and process it separately
1060
+ */var i=0;while(i<preloadedEventsArray.length){if(preloadedEventsArray[i]&&preloadedEventsArray[i][0]===loadMethodName){loadEvent=preloadedEventsArray[i];preloadedEventsArray.splice(i,1);break;}i+=1;}return loadEvent;};/**
1061
+ * Retrieve any existing events that were triggered before SDK load and enqueue in buffer
1062
+ */var retrievePreloadBufferEvents=function retrievePreloadBufferEvents(instance){var preloadedEventsArray=getExposedGlobal(GLOBAL_PRELOAD_BUFFER)||[];// Get events that are pre-populated via query string params
1063
+ retrieveEventsFromQueryString(preloadedEventsArray);var sanitizedPreloadedEventsArray=preloadedEventsArray.filter(function(bufferedEvent){return bufferedEvent[0]!=='load';});// Enqueue the non load events in the buffer of the global rudder analytics singleton
1064
+ if(sanitizedPreloadedEventsArray.length>0){instance.enqueuePreloadBufferEvents(sanitizedPreloadedEventsArray);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);}}};
1065
+
1066
+ var _LOG_LEVEL_MAP;var LOG_LEVEL_MAP=(_LOG_LEVEL_MAP={},_defineProperty(_LOG_LEVEL_MAP,LogLevel.Log,0),_defineProperty(_LOG_LEVEL_MAP,LogLevel.Info,1),_defineProperty(_LOG_LEVEL_MAP,LogLevel.Debug,2),_defineProperty(_LOG_LEVEL_MAP,LogLevel.Warn,3),_defineProperty(_LOG_LEVEL_MAP,LogLevel.Error,4),_defineProperty(_LOG_LEVEL_MAP,LogLevel.None,5),_LOG_LEVEL_MAP);var DEFAULT_LOG_LEVEL=LogLevel.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;';/**
1067
+ * Service to log messages/data to output provider, default is console
1068
+ */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;}_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(LogLevel.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(LogLevel.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(LogLevel.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(LogLevel.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(LogLevel.Error,data);}},{key:"outputLog",value:function outputLog(logMethod,data){if(this.minLogLevel<=LOG_LEVEL_MAP[logMethod]){var _this$logProvider;(_this$logProvider=this.logProvider)[logMethod.toLowerCase()].apply(_this$logProvider,_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
1069
+ // to assist on the fly debugging?
1070
+ },{key:"setMinLogLevel",value:function setMinLogLevel(logLevel){this.minLogLevel=LOG_LEVEL_MAP[logLevel];if(isUndefined(this.minLogLevel)){this.minLogLevel=LOG_LEVEL_MAP[DEFAULT_LOG_LEVEL];}}/**
1071
+ * Formats the console message using `scope` and styles
1072
+ */},{key:"formatLogData",value:function formatLogData(data){if(Array.isArray(data)&&data.length>0){// prefix SDK identifier
1073
+ var msg="%c ".concat(LOG_MSG_PREFIX);// format the log message using `scope`
1074
+ if(this.scope){msg="".concat(msg," - ").concat(this.scope);}// trim whitespaces for original message
1075
+ var originalMsg=isString(data[0])?data[0].trim():'';// prepare the final message
1076
+ msg="".concat(msg," %c ").concat(originalMsg);var styledLogArgs=[msg,LOG_MSG_PREFIX_STYLE,// add style for the prefix
1077
+ LOG_MSG_STYLE// reset the style for the actual message
1078
+ ];// add first it if it was not a string msg
1079
+ if(!isString(data[0])){styledLogArgs.push(data[0]);}// append rest of the original arguments
1080
+ styledLogArgs.push.apply(styledLogArgs,_toConsumableArray(data.slice(1)));return styledLogArgs;}return data;}}]);return Logger;}();var defaultLogger=new Logger();
1081
+
1082
+ 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='readyApi';var LOAD_CONFIGURATION='LoadConfiguration';var EVENT_REPOSITORY='EventRepository';var EXTERNAL_SRC_LOADER='ExternalSrcLoader';var HTTP_CLIENT='HttpClient';
1083
+
1084
+ 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){return "Failed to load 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.";
1085
+
1086
+ var SOURCE_CONFIG_OPTION_ERROR="\"getSourceConfig\" must be a function. Please make sure that it is defined and returns a valid source configuration object.";var INTG_CDN_BASE_URL_ERROR="Failed to load the SDK as the CDN base URL for integrations is not valid.";var PLUGINS_CDN_BASE_URL_ERROR="Failed to load the SDK as the CDN base URL for plugins is not valid.";var DATA_PLANE_URL_ERROR="Failed to load the SDK as the data plane URL could not be determined. Please check that the data plane URL is set correctly and try again.";var XHR_PAYLOAD_PREP_ERROR="Failed to prepare data for the request.";var EVENT_OBJECT_GENERATION_ERROR="Failed to generate the event object.";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.";// ERROR
1087
+ 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 REPORTING_PLUGIN_INIT_FAILURE_ERROR=function REPORTING_PLUGIN_INIT_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to initialize the error reporting plugin.");};var NOTIFY_FAILURE_ERROR=function NOTIFY_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to notify 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 STORAGE_UNAVAILABILITY_ERROR_PREFIX=function STORAGE_UNAVAILABILITY_ERROR_PREFIX(context,storageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(storageType,"\" storage type is ");};var SOURCE_CONFIG_FETCH_ERROR=function SOURCE_CONFIG_FETCH_ERROR(reason){return "Failed to fetch the source config. Reason: ".concat(reason);};var WRITE_KEY_VALIDATION_ERROR=function WRITE_KEY_VALIDATION_ERROR(writeKey){return "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(dataPlaneUrl){return "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 READY_API_CALLBACK_ERROR=function READY_API_CALLBACK_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The callback is not a function.");};var XHR_DELIVERY_ERROR=function XHR_DELIVERY_ERROR(prefix,status,statusText,url){return "".concat(prefix," with status: ").concat(status,", ").concat(statusText," for URL: ").concat(url,".");};var XHR_REQUEST_ERROR=function XHR_REQUEST_ERROR(prefix,e,url){return "".concat(prefix," due to timeout or no connection (").concat(e?e.type:'',") 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");};// WARNING
1088
+ var UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING=function UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(context,selectedErrorReportingProvider,errorReportingProvidersToPluginNameMap,defaultProvider){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The error reporting provider \"").concat(selectedErrorReportingProvider,"\" is not supported. Please choose one of the following supported providers: \"").concat(Object.keys(errorReportingProvidersToPluginNameMap),"\". The default provider \"").concat(defaultProvider,"\" 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 UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING=function UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING(context,selectedResidencyServerRegion,defaultRegion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The residency server region \"").concat(selectedResidencyServerRegion,"\" is not supported. Please choose one of the following supported regions: \"").concat(Object.values(ResidencyServerRegion),"\". The default region \"").concat(defaultRegion,"\" will be used instead.");};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 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_ERROR=function STORAGE_UNAVAILABLE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"No storage is available. The SDK will be initialized without storage.");};// DEBUG
1089
+
1090
+ // to next or return the value if it is the last one instead of an array per
1091
+ // plugin that is the normal invoke
1092
+ // TODO: add invoke method for extension point that we know only one plugin can be used. add invokeMultiple and invokeSingle methods
1093
+ var PluginEngine=/*#__PURE__*/function(){function PluginEngine(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var logger=arguments.length>1?arguments[1]:undefined;_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;}_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 {var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0?void 0:_this$logger.error(errorMessage,plugin);}}if(this.byName[plugin.name]){var _errorMessage=PLUGIN_ALREADY_EXISTS_ERROR(PLUGIN_ENGINE,plugin.name);if(this.config.throws){throw new Error(_errorMessage);}else {var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0?void 0:_this$logger2.error(_errorMessage);}}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(plugin.initialize&&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 {var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===void 0?void 0:_this$logger3.error(errorMessage);}}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 {var _this$logger4;(_this$logger4=this.logger)===null||_this$logger4===void 0?void 0:_this$logger4.error(_errorMessage2);}}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];})){var _this$logger5;// If deps not exist, then not load it.
1094
+ var notExistDeps=plugin.deps.filter(function(dependency){return !_this.byName[dependency];});(_this$logger5=_this.logger)===null||_this$logger5===void 0?void 0:_this$logger5.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
1095
+ // do some unified pre-process before application starts.
1096
+ },{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
1097
+ 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
1098
+ if(throws){throw err;}else {var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0?void 0:_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));}}]);return PluginEngine;}();var defaultPluginEngine=new PluginEngine({throws:true},defaultLogger);
1099
+
1100
+ function i(){throw new Error("Cycle detected");}function t(){if(!(h>1)){var i,t=!1;while(void 0!==n){var o=n;n=void 0;s++;while(void 0!==o){var r=o.o;o.o=void 0;o.f&=-3;if(!(8&o.f)&&c(o))try{o.c();}catch(o){if(!t){i=o;t=!0;}}o=r;}}s=0;h--;if(t)throw i;}else h--;}function o(i){if(h>0)return i();h++;try{return i();}finally{t();}}var r=void 0,n=void 0,h=0,s=0,f=0;function v(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 e(i){this.v=i;this.i=0;this.n=void 0;this.t=void 0;}e.prototype.h=function(){return !0;};e.prototype.S=function(i){if(this.t!==i&&void 0===i.e){i.x=this.t;if(void 0!==this.t)this.t.e=i;this.t=i;}};e.prototype.U=function(i){if(void 0!==this.t){var t=i.e,o=i.x;if(void 0!==t){t.x=o;i.e=void 0;}if(void 0!==o){o.e=t;i.x=void 0;}if(i===this.t)this.t=o;}};e.prototype.subscribe=function(i){var t=this;return b(function(){var o=t.value,r=32&this.f;this.f&=-33;try{i(o);}finally{this.f|=r;}});};e.prototype.valueOf=function(){return this.value;};e.prototype.toString=function(){return this.value+"";};e.prototype.toJSON=function(){return this.value;};e.prototype.peek=function(){return this.v;};Object.defineProperty(e.prototype,"value",{get:function get(){var i=v(this);if(void 0!==i)i.i=this.i;return this.v;},set:function set(o){if(r instanceof l)!function(){throw new Error("Computed cannot have side-effects");}();if(o!==this.v){if(s>100)i();this.v=o;this.i++;f++;h++;try{for(var n=this.t;void 0!==n;n=n.x)n.t.N();}finally{t();}}}});function u(i){return new e(i);}function c(i){for(var t=i.s;void 0!==t;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return !0;return !1;}function d(i){for(var t=i.s;void 0!==t;t=t.n){var o=t.S.n;if(void 0!==o)t.r=o;t.S.n=t;t.i=-1;if(void 0===t.n){i.s=t;break;}}}function a(i){var t=i.s,o=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 o=t;t.S.n=t.r;if(void 0!==t.r)t.r=void 0;t=r;}i.s=o;}function l(i){e.call(this,void 0);this.x=i;this.s=void 0;this.g=f-1;this.f=4;}(l.prototype=new e()).h=function(){this.f&=-3;if(1&this.f)return !1;if(32==(36&this.f))return !0;this.f&=-5;if(this.g===f)return !0;this.g=f;this.f|=1;if(this.i>0&&!c(this)){this.f&=-2;return !0;}var i=r;try{d(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;a(this);this.f&=-2;return !0;};l.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);}e.prototype.S.call(this,i);};l.prototype.U=function(i){if(void 0!==this.t){e.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);}}};l.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var i=this.t;void 0!==i;i=i.x)i.t.N();}};l.prototype.peek=function(){if(!this.h())i();if(16&this.f)throw this.v;return this.v;};Object.defineProperty(l.prototype,"value",{get:function get(){if(1&this.f)i();var t=v(this);this.h();if(void 0!==t)t.i=this.i;if(16&this.f)throw this.v;return this.v;}});function y(i){var o=i.u;i.u=void 0;if("function"==typeof o){h++;var n=r;r=void 0;try{o();}catch(t){i.f&=-2;i.f|=8;_(i);throw t;}finally{r=n;t();}}}function _(i){for(var t=i.s;void 0!==t;t=t.n)t.S.U(t);i.x=void 0;i.s=void 0;y(i);}function p(i){if(r!==this)throw new Error("Out-of-order effect");a(this);r=i;this.f&=-2;if(8&this.f)_(this);t();}function g(i){this.x=i;this.u=void 0;this.s=void 0;this.o=void 0;this.f=32;}g.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();}};g.prototype.S=function(){if(1&this.f)i();this.f|=1;this.f&=-9;y(this);d(this);h++;var t=r;r=this;return p.bind(this,t);};g.prototype.N=function(){if(!(2&this.f)){this.f|=2;this.o=n;n=this;}};g.prototype.d=function(){this.f|=8;if(!(1&this.f))_(this);};function b(i){var t=new g(i);try{t.c();}catch(i){t.d();throw i;}return t.d.bind(t);}
1101
+
1102
+ var BUILD_TYPE='legacy';var SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';var CDN_ARCH_VERSION_DIR='v3';var CDN_INT_DIR='js-integrations';var CDN_PLUGINS_DIR='plugins';var DEST_SDK_BASE_URL="".concat(SDK_CDN_BASE_URL,"/").concat(CDN_ARCH_VERSION_DIR,"/latest/").concat(BUILD_TYPE,"/").concat(CDN_INT_DIR);var PLUGINS_BASE_URL="".concat(SDK_CDN_BASE_URL,"/").concat(CDN_ARCH_VERSION_DIR,"/latest/").concat(BUILD_TYPE,"/").concat(CDN_PLUGINS_DIR);var DEFAULT_CONFIG_BE_URL='https://api.rudderstack.com';
1103
+
1104
+ var DEFAULT_XHR_TIMEOUT=10*1000;// 10 seconds
1105
+ var DEFAULT_COOKIE_MAX_AGE=31536000*1000;// 1 year
1106
+ var DEFAULT_SESSION_TIMEOUT=30*60*1000;// 30 minutes
1107
+ var MIN_SESSION_TIMEOUT=10*1000;// 10 seconds
1108
+
1109
+ var StorageEncryptionVersion=/*#__PURE__*/function(StorageEncryptionVersion){StorageEncryptionVersion["Legacy"]="legacy";StorageEncryptionVersion["V3"]="v3";return StorageEncryptionVersion;}({});// default
1110
+
1111
+ var _StorageEncryptionVer;var DEFAULT_ERROR_REPORTING_PROVIDER='bugsnag';var DEFAULT_STORAGE_ENCRYPTION_VERSION=StorageEncryptionVersion.V3;var ConsentManagersToPluginNameMap={oneTrust:PluginName.OneTrustConsentManager,ketch:PluginName.KetchConsentManager};var ErrorReportingProvidersToPluginNameMap=_defineProperty({},DEFAULT_ERROR_REPORTING_PROVIDER,PluginName.Bugsnag);var StorageEncryptionVersionsToPluginNameMap=(_StorageEncryptionVer={},_defineProperty(_StorageEncryptionVer,DEFAULT_STORAGE_ENCRYPTION_VERSION,PluginName.StorageEncryption),_defineProperty(_StorageEncryptionVer,StorageEncryptionVersion.Legacy,PluginName.StorageEncryptionLegacy),_StorageEncryptionVer);
1112
+
1113
+ var defaultLoadOptions={logLevel:LogLevel.Error,configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT},sameSiteCookie:CookieSameSite.Lax,polyfillIfRequired:true,integrations:{All:true},useBeacon:false,lockIntegrationsVersion:false,uaChTrackLevel:UaChTrackLevel.None,plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:false}};var loadOptionsState=u(clone$1(defaultLoadOptions));
1114
+
1115
+ var defaultSessionInfo={autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT};var sessionState={userId:u(undefined),userTraits:u(undefined),anonymousUserId:u(undefined),groupId:u(undefined),groupTraits:u(undefined),initialReferrer:u(undefined),initialReferringDomain:u(undefined),sessionInfo:u(_objectSpread2({},defaultSessionInfo))};
1116
+
1117
+ var capabilitiesState={isOnline:u(true),storage:{isLocalStorageAvailable:u(false),isCookieStorageAvailable:u(false),isSessionStorageAvailable:u(false)},isBeaconAvailable:u(false),isLegacyDOM:u(false),isUaCHAvailable:u(false),isCryptoAvailable:u(false),isIE11:u(false),isAdBlocked:u(false)};
1118
+
1119
+ var reportingState={isErrorReportingEnabled:u(false),isMetricsReportingEnabled:u(false),errorReportingProviderPluginName:u(undefined)};
1120
+
1121
+ var sourceConfigState=u(undefined);
1122
+
1123
+ var lifecycleState={activeDataplaneUrl:u(undefined),integrationsCDNPath:u(DEST_SDK_BASE_URL),pluginsCDNPath:u(PLUGINS_BASE_URL),sourceConfigUrl:u(undefined),status:u(undefined),initialized:u(false),logLevel:u(LogLevel.Error),loaded:u(false),readyCallbacks:u([]),writeKey:u(undefined),dataPlaneUrl:u(undefined)};
1124
+
1125
+ var consentsState={data:u({initialized:false}),activeConsentManagerPluginName:u(undefined)};
1126
+
1127
+ var metricsState={retries:u(0),dropped:u(0),sent:u(0),queued:u(0),triggered:u(0)};
1128
+
1129
+ var contextState={app:u({name:APP_NAME,namespace:APP_NAMESPACE,version:APP_VERSION}),traits:u(null),library:u({name:APP_NAME,version:APP_VERSION}),userAgent:u(''),device:u(null),network:u(null),os:u({name:'',version:''}),locale:u(null),screen:u({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),'ua-ch':u(undefined),campaign:u({})};
1130
+
1131
+ var nativeDestinationsState={configuredDestinations:u([]),activeDestinations:u([]),loadOnlyIntegrations:u({}),failedDestinations:u([]),loadIntegration:u(true),initializedDestinations:u([]),clientDestinationsReady:u(false),integrationsConfig:u({})};
1132
+
1133
+ var eventBufferState={toBeProcessedArray:u([]),readyCallbacksArray:u([])};
1134
+
1135
+ var pluginsState={ready:u(false),loadedPlugins:u([]),failedPlugins:u([]),pluginsToLoadFromConfig:u([]),activePlugins:u([]),totalPluginsToLoad:u(0)};
1136
+
1137
+ var pagePropertiesState={path:u(''),referrer:u(''),referring_domain:u(''),search:u(''),title:u(''),url:u(''),tab_url:u('')};
1138
+
1139
+ var storageState={encryptionPluginName:u(undefined),migrate:u(false)};
1140
+
1141
+ 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,page:pagePropertiesState,storage:storageState};var state=_objectSpread2({},clone$1(defaultStateValues));
1142
+
1143
+ var JSON_STRINGIFY='JSONStringify';var getCircularReplacer=function getCircularReplacer(excludeNull,excludeKeys,logger){var ancestors=[];// Here we do not want to use arrow function to use "this" in function context
1144
+ // eslint-disable-next-line func-names
1145
+ 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.
1146
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1147
+ // @ts-ignore-next-line
1148
+ while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();}if(ancestors.includes(value)){logger===null||logger===void 0?void 0:logger.warn(CIRCULAR_REFERENCE_WARNING(JSON_STRINGIFY,key));return '[Circular Reference]';}ancestors.push(value);return value;};};/**
1149
+ * Utility method for JSON stringify object excluding null values & circular references
1150
+ *
1151
+ * @param {*} value input
1152
+ * @param {boolean} excludeNull if it should exclude nul or not
1153
+ * @param {function} logger optional logger methods for warning
1154
+ * @returns string
1155
+ */var stringifyWithoutCircular=function stringifyWithoutCircular(value,excludeNull,excludeKeys,logger){try{return JSON.stringify(value,getCircularReplacer(excludeNull,excludeKeys,logger));}catch(err){logger===null||logger===void 0?void 0:logger.warn(JSON_STRINGIFY_WARNING,err);return null;}};
1156
+
1157
+ var FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';var ERROR_MESSAGES_TO_BE_FILTERED=[FAILED_REQUEST_ERR_MSG_PREFIX];
1158
+
1159
+ /**
1160
+ * Utility method to normalise errors
1161
+ */var processError=function processError(error){var errorMessage;try{if(isString(error)){errorMessage=error;}else if(error instanceof Error){errorMessage=error.message;}else {errorMessage=error.message?error.message:stringifyWithoutCircular(error);}}catch(e){errorMessage="Unknown error: ".concat(e.message);}return errorMessage;};/**
1162
+ * A function to determine whether the error should be promoted to notify or not
1163
+ * @param {Error} error
1164
+ * @returns
1165
+ */var isAllowedToBeNotified=function isAllowedToBeNotified(error){if(error.message){return !ERROR_MESSAGES_TO_BE_FILTERED.some(function(e){return error.message.includes(e);});}return true;};
1166
+
1167
+ /**
1168
+ * A service to handle errors
1169
+ */var ErrorHandler=/*#__PURE__*/function(){// If no logger is passed errors will be thrown as unhandled error
1170
+ function ErrorHandler(logger,pluginEngine){_classCallCheck(this,ErrorHandler);this.logger=logger;this.pluginEngine=pluginEngine;}_createClass(ErrorHandler,[{key:"init",value:function init(externalSrcLoader){var _this=this;if(!this.pluginEngine){return;}try{var extPoint='errorReporting.init';var errReportingInitVal=this.pluginEngine.invokeSingle(extPoint,state,this.pluginEngine,externalSrcLoader,this.logger);if(errReportingInitVal instanceof Promise){errReportingInitVal.then(function(client){_this.errReportingClient=client;}).catch(function(err){var _this$logger;(_this$logger=_this.logger)===null||_this$logger===void 0?void 0:_this$logger.error(REPORTING_PLUGIN_INIT_FAILURE_ERROR(ERROR_HANDLER),err);});}}catch(err){this.onError(err,ERROR_HANDLER);}}},{key:"onError",value:function onError(error){var context=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var customMessage=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'';var shouldAlwaysThrow=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;// Error handling is already implemented in processError method
1171
+ var errorMessage=processError(error);// If no error message after we normalize, then we swallow/ignore the errors
1172
+ if(!errorMessage){return;}errorMessage=removeDoubleSpaces("".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(customMessage," ").concat(errorMessage));var normalizedError=error;// Enhance error message
1173
+ if(isTypeOfError(error)){normalizedError.message=errorMessage;}else {normalizedError=new Error(errorMessage);}this.notifyError(normalizedError);if(this.logger){this.logger.error(errorMessage);if(shouldAlwaysThrow){throw normalizedError;}}else {throw normalizedError;}}/**
1174
+ * Add breadcrumbs to add insight of a user's journey before an error
1175
+ * occurred and send to external error monitoring service via a plugin
1176
+ *
1177
+ * @param {string} breadcrumb breadcrumbs message
1178
+ */},{key:"leaveBreadcrumb",value:function leaveBreadcrumb(breadcrumb){if(this.pluginEngine){try{this.pluginEngine.invokeSingle('errorReporting.breadcrumb',this.pluginEngine,this.errReportingClient,breadcrumb,this.logger);}catch(err){this.onError(err,'errorReporting.breadcrumb');}}}/**
1179
+ * Send handled errors to external error monitoring service via a plugin
1180
+ *
1181
+ * @param {Error} error Error instance from handled error
1182
+ */},{key:"notifyError",value:function notifyError(error){if(this.pluginEngine&&isAllowedToBeNotified(error)){try{this.pluginEngine.invokeSingle('errorReporting.notify',this.pluginEngine,this.errReportingClient,error,state,this.logger);}catch(err){var _this$logger2;// Not calling onError here as we don't want to go into infinite loop
1183
+ (_this$logger2=this.logger)===null||_this$logger2===void 0?void 0:_this$logger2.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),err);}}}}]);return ErrorHandler;}();var defaultErrorHandler=new ErrorHandler(defaultLogger,defaultPluginEngine);
1184
+
1185
+ var DestinationConnectionMode=/*#__PURE__*/function(DestinationConnectionMode){DestinationConnectionMode["Hybrid"]="hybrid";DestinationConnectionMode["Cloud"]="cloud";DestinationConnectionMode["Device"]="device";return DestinationConnectionMode;}({});
1186
+
1187
+ /**
1188
+ * A function to filter and return non cloud mode destinations
1189
+ * @param destination
1190
+ *
1191
+ * @returns boolean
1192
+ */var isNonCloudDestination=function isNonCloudDestination(destination){return Boolean(destination.config.connectionMode!==DestinationConnectionMode.Cloud||destination.config.useNativeSDKToSend===true||// this is the older flag for hybrid mode destinations
1193
+ destination.config.useNativeSDK===true);};var isHybridModeDestination=function isHybridModeDestination(destination){return Boolean(destination.config.connectionMode===DestinationConnectionMode.Hybrid||destination.config.useNativeSDKToSend===true);};/**
1194
+ * A function to filter and return non cloud mode destinations
1195
+ * @param destinations
1196
+ *
1197
+ * @returns destinations
1198
+ */var getNonCloudDestinations=function getNonCloudDestinations(destinations){return destinations.filter(isNonCloudDestination);};
1199
+
1200
+ var LifecycleStatus=/*#__PURE__*/function(LifecycleStatus){LifecycleStatus["Mounted"]="mounted";LifecycleStatus["BrowserCapabilitiesReady"]="browserCapabilitiesReady";LifecycleStatus["Configured"]="configured";LifecycleStatus["PluginsLoading"]="pluginsLoading";LifecycleStatus["PluginsReady"]="pluginsReady";LifecycleStatus["Initialized"]="initialized";LifecycleStatus["Loaded"]="loaded";LifecycleStatus["DestinationsLoading"]="destinationsLoading";LifecycleStatus["DestinationsReady"]="destinationsReady";LifecycleStatus["Ready"]="ready";return LifecycleStatus;}({});
1201
+
1202
+ /**
1203
+ * List of plugin names that are loaded as dynamic imports in modern builds
1204
+ */var remotePluginNames=[PluginName.BeaconQueue,PluginName.DeviceModeTransformation,PluginName.DeviceModeDestinations,PluginName.ErrorReporting,PluginName.ExternalAnonymousId,PluginName.GoogleLinker,PluginName.NativeDestinationQueue,PluginName.StorageEncryption,PluginName.StorageEncryptionLegacy,PluginName.StorageMigrator,PluginName.XhrQueue,PluginName.OneTrustConsentManager,PluginName.KetchConsentManager,PluginName.Bugsnag];
1205
+
1206
+ /**
1207
+ * To get the current timestamp in ISO string format
1208
+ * @returns ISO formatted timestamp string
1209
+ */var getCurrentTimeFormatted=function getCurrentTimeFormatted(){var curDateTime=new Date().toISOString();return curDateTime;};
1210
+
1211
+ function random(len){return crypto.getRandomValues(new Uint8Array(len));}
1212
+
1213
+ 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;}
1214
+
1215
+ 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;}
1216
+
1217
+ var hasCrypto$1=function hasCrypto(){return !isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);};
1218
+
1219
+ var generateUUID=function generateUUID(){if(hasCrypto$1()){return v4$1();}return v4();};
1220
+
1221
+ var DEFAULT_EXT_SRC_LOAD_TIMEOUT=10*1000;// 10 seconds
1222
+
1223
+ /**
1224
+ * Get mutated error with issue prepended to error message
1225
+ * @param err Original error
1226
+ * @param issue Issue to prepend to error message
1227
+ * @returns Instance of Error with message prepended with issue
1228
+ */var getMutatedError=function getMutatedError(err,issue){var finalError=err;if(!isTypeOfError(err)){finalError=new Error("".concat(issue,": ").concat(stringifyWithoutCircular(err)));}else {finalError.message="".concat(issue,": ").concat(err.message);}return finalError;};
1229
+
1230
+ var EXTERNAL_SOURCE_LOAD_ORIGIN='RS_JS_SDK';
1231
+
1232
+ /**
1233
+ * Create the DOM element to load a script marked as RS SDK originated
1234
+ *
1235
+ * @param {*} url The URL of the script to be loaded
1236
+ * @param {*} id ID for the script tag
1237
+ * @param {*} async Whether to load the script in async mode. Defaults to `true` [optional]
1238
+ * @param {*} onload callback to invoke onload [optional]
1239
+ * @param {*} onerror callback to invoke onerror [optional]
1240
+ * @param {*} extraAttributes key/value pair with html attributes to add in html tag [optional]
1241
+ *
1242
+ * @returns HTMLScriptElement
1243
+ */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;scriptElement.setAttribute('data-append-origin',EXTERNAL_SOURCE_LOAD_ORIGIN);Object.keys(extraAttributes).forEach(function(attributeName){scriptElement.setAttribute(attributeName,extraAttributes[attributeName]);});return scriptElement;};/**
1244
+ * Add script DOM element to DOM
1245
+ *
1246
+ * @param {*} newScriptElement the script element to add
1247
+ *
1248
+ * @returns
1249
+ */var insertScript=function insertScript(newScriptElement){// First try to add it to the head
1250
+ var headElements=document.getElementsByTagName('head');if(headElements.length>0){headElements[0].insertBefore(newScriptElement,headElements[0].firstChild);return;}// Else wise add it before the first script tag
1251
+ var scriptElements=document.getElementsByTagName('script');if(scriptElements.length>0&&scriptElements[0].parentNode){scriptElements[0].parentNode.insertBefore(newScriptElement,scriptElements[0]);return;}// Create a new head element and add the script as fallback
1252
+ var headElement=document.createElement('head');headElement.appendChild(newScriptElement);var htmlElement=document.getElementsByTagName('html')[0];htmlElement.insertBefore(headElement,htmlElement.firstChild);};/**
1253
+ * Loads external js file as a script html tag
1254
+ *
1255
+ * @param {*} url The URL of the script to be loaded
1256
+ * @param {*} id ID for the script tag
1257
+ * @param {*} timeout loading timeout
1258
+ * @param {*} async Whether to load the script in async mode. Defaults to `true` [optional]
1259
+ * @param {*} extraAttributes key/value pair with html attributes to add in html tag [optional]
1260
+ *
1261
+ * @returns
1262
+ */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(){globalThis.clearTimeout(timeoutID);reject(new Error(SCRIPT_LOAD_ERROR(id,url)));};// Create the DOM element to load the script and add it to the DOM
1263
+ insertScript(createScriptElement(url,id,async,onload,onerror,extraAttributes));// Reject on timeout
1264
+ 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)));}});};
1265
+
1266
+ /**
1267
+ * Service to load external resources/files
1268
+ */var ExternalSrcLoader=/*#__PURE__*/function(){function ExternalSrcLoader(errorHandler,logger){var timeout=arguments.length>2&&arguments[2]!==undefined?arguments[2]:DEFAULT_EXT_SRC_LOAD_TIMEOUT;_classCallCheck(this,ExternalSrcLoader);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.timeout=timeout;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);}/**
1269
+ * Load external resource of type javascript
1270
+ */_createClass(ExternalSrcLoader,[{key:"loadJSFile",value:function loadJSFile(config){var _this=this;var url=config.url,id=config.id,timeout=config.timeout,async=config.async,callback=config.callback,extraAttributes=config.extraAttributes;var isFireAndForget=!(callback&&isFunction(callback));jsFileLoader(url,id,timeout||this.timeout,async,extraAttributes).then(function(id){if(!isFireAndForget){callback(id);}}).catch(function(err){_this.onError(err);if(!isFireAndForget){callback();}});}/**
1271
+ * Handle errors
1272
+ */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0?void 0:_this$errorHandler.onError(error,EXTERNAL_SRC_LOADER);}else {throw error;}}}]);return ExternalSrcLoader;}();
1273
+
1274
+ var QueueStatuses={IN_PROGRESS:'inProgress',QUEUE:'queue',RECLAIM_START:'reclaimStart',RECLAIM_END:'reclaimEnd',ACK:'ack'};
1275
+
1276
+ var isDestIntgConfigTruthy=function isDestIntgConfigTruthy(destIntgConfig){return !isUndefined(destIntgConfig)&&Boolean(destIntgConfig)===true;};var isDestIntgConfigFalsy=function isDestIntgConfigFalsy(destIntgConfig){return !isUndefined(destIntgConfig)&&Boolean(destIntgConfig)===false;};
1277
+
1278
+ var EVENT_PAYLOAD_SIZE_BYTES_LIMIT=32*1024;// 32 KB
1279
+
1280
+ var INVALID_SOURCE_CONFIG_ERROR="Invalid source configuration or source id.";// ERROR
1281
+ var BEACON_QUEUE_SEND_ERROR=function BEACON_QUEUE_SEND_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to send events batch data to the browser's beacon queue. The events will be dropped.");};var BEACON_QUEUE_PAYLOAD_PREPARATION_ERROR=function BEACON_QUEUE_PAYLOAD_PREPARATION_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to prepare the events batch payload for delivery. The events will be dropped.");};var BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR=function BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to convert events batch object to string.");};var BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR=function BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to convert events batch object to Blob.");};var BUGSNAG_SDK_LOAD_ERROR=function BUGSNAG_SDK_LOAD_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to load the Bugsnag SDK.");};var DESTINATION_NOT_SUPPORTED_ERROR=function DESTINATION_NOT_SUPPORTED_ERROR(context,destUserFriendlyId){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Destination ").concat(destUserFriendlyId," is not supported.");};var DESTINATION_SDK_LOAD_ERROR=function DESTINATION_SDK_LOAD_ERROR(context,destUserFriendlyId){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to load script for destination ").concat(destUserFriendlyId,".");};var DESTINATION_INIT_ERROR=function DESTINATION_INIT_ERROR(context,destUserFriendlyId){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to initialize destination ").concat(destUserFriendlyId,".");};var DESTINATION_SDK_EVALUATION_TIMEOUT_ERROR=function DESTINATION_SDK_EVALUATION_TIMEOUT_ERROR(context,destUserFriendlyId){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"SDK script evaluation timed out for destination ").concat(destUserFriendlyId,".");};var DESTINATION_INTEGRATIONS_DATA_ERROR=function DESTINATION_INTEGRATIONS_DATA_ERROR(context,destUserFriendlyId){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to get integrations data for destination ").concat(destUserFriendlyId,".");};var DESTINATION_EVENT_FILTERING_WARNING=function DESTINATION_EVENT_FILTERING_WARNING(context,eventName,destUserFriendlyId){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(eventName,"\" track event has been filtered for the \"").concat(destUserFriendlyId,"\" destination.");};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 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=function DESTINATION_CONSENT_STATUS_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to determine the consent status for the destination. Please check the destination configuration and try again.");};var STORAGE_MIGRATION_ERROR=function STORAGE_MIGRATION_ERROR(context,key){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to retrieve or parse data for ").concat(key," from storage.");};var EVENT_STRINGIFY_ERROR=function EVENT_STRINGIFY_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to convert event object to string.");};var RETRY_QUEUE_PROCESS_ERROR=function RETRY_QUEUE_PROCESS_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Process function threw an error.");};var EVENT_PAYLOAD_PREPARATION_ERROR=function EVENT_PAYLOAD_PREPARATION_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to prepare the event payload for delivery. The event will be dropped.");};var EVENT_DELIVERY_FAILURE_ERROR_PREFIX=function EVENT_DELIVERY_FAILURE_ERROR_PREFIX(context,url){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to deliver event to ").concat(url,".");};var BUGSNAG_API_KEY_VALIDATION_ERROR=function BUGSNAG_API_KEY_VALIDATION_ERROR(apiKey){return "The Bugsnag API key (".concat(apiKey,") is invalid or not provided.");};var DESTINATION_READY_TIMEOUT_ERROR=function DESTINATION_READY_TIMEOUT_ERROR(timeout,destUserFriendlyId){return "A timeout of ".concat(timeout," ms occurred while trying to check the ready status for \"").concat(destUserFriendlyId,"\" destination.");};var DESTINATION_EVENT_FORWARDING_ERROR=function DESTINATION_EVENT_FORWARDING_ERROR(destUserFriendlyId){return "Failed to forward event to destination \"".concat(destUserFriendlyId,"\".");};var BUGSNAG_SDK_LOAD_TIMEOUT_ERROR=function BUGSNAG_SDK_LOAD_TIMEOUT_ERROR(timeout){return "A timeout ".concat(timeout," ms occurred while trying to load the Bugsnag SDK.");};// WARN
1282
+ 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.");};// DEBUG
1283
+ var BEACON_PLUGIN_EVENTS_QUEUE_DEBUG=function BEACON_PLUGIN_EVENTS_QUEUE_DEBUG(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Sending events to data plane.");};
1284
+
1285
+ var QUEUE_UTILITIES='QueueUtilities';/**
1286
+ * Utility to get the stringified event payload
1287
+ * @param event RudderEvent object
1288
+ * @param logger Logger instance
1289
+ * @returns stringified event payload. Empty string if error occurs.
1290
+ */var getDeliveryPayload$1=function getDeliveryPayload(event,logger){var deliveryPayloadStr='';try{deliveryPayloadStr=stringifyWithoutCircular(event,true);}catch(err){logger===null||logger===void 0?void 0:logger.error(EVENT_STRINGIFY_ERROR(QUEUE_UTILITIES),err);}return deliveryPayloadStr;};/**
1291
+ * Utility to validate final payload size before sending to server
1292
+ * @param event RudderEvent object
1293
+ * @param logger Logger instance
1294
+ */var validateEventPayloadSize=function validateEventPayloadSize(event,logger){var payloadStr=getDeliveryPayload$1(event,logger);if(payloadStr){var payloadSize=payloadStr.length;if(payloadSize>EVENT_PAYLOAD_SIZE_BYTES_LIMIT){logger===null||logger===void 0?void 0:logger.warn(EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING(QUEUE_UTILITIES,payloadSize,EVENT_PAYLOAD_SIZE_BYTES_LIMIT));}}else {logger===null||logger===void 0?void 0:logger.warn(EVENT_PAYLOAD_SIZE_VALIDATION_WARNING(QUEUE_UTILITIES));}};var getOverriddenIntegrationOptions=function getOverriddenIntegrationOptions(finalIntgConfig,destinationsIntgConfig){return Object.keys(finalIntgConfig).filter(function(intgName){var eventDestConfig=finalIntgConfig[intgName];var globalDestConfig=destinationsIntgConfig[intgName];// unless the event dest config is undefined, use it (falsy or truthy)
1295
+ if(typeof eventDestConfig!=='boolean'){return !isUndefined(eventDestConfig);}if(eventDestConfig===false||isUndefined(globalDestConfig)){return true;}return isDestIntgConfigFalsy(globalDestConfig);}).reduce(function(obj,key){var retVal=clone$1(obj);retVal[key]=finalIntgConfig[key];return retVal;},{});};/**
1296
+ * Mutates the event and return final event for delivery
1297
+ * Updates certain parameters like sentAt timestamp, integrations config etc.
1298
+ * @param event RudderEvent object
1299
+ * @param state Application state
1300
+ * @returns Final event ready to be delivered
1301
+ */var getFinalEventForDeliveryMutator=function getFinalEventForDeliveryMutator(event,state){var finalEvent=clone$1(event);// Update sentAt timestamp to the latest timestamp
1302
+ finalEvent.sentAt=getCurrentTimeFormatted();// IMPORTANT: This logic has been improved over the v1.1 to handle other generic cases as well
1303
+ // Merge the destination specific integrations config with the event's integrations config
1304
+ // In general, the preference is given to the event's integrations config
1305
+ var finalIntgConfig=event.integrations;var destinationsIntgConfig=state.nativeDestinations.integrationsConfig.value;var overriddenIntgOpts=getOverriddenIntegrationOptions(finalIntgConfig,destinationsIntgConfig);finalIntgConfig=mergeDeepRight(destinationsIntgConfig,overriddenIntgOpts);finalEvent.integrations=finalIntgConfig;return finalEvent;};var removeDuplicateSlashes=function removeDuplicateSlashes(str){return str.replace(/\/{2,}/g,'/');};
1306
+
1307
+ var DEFAULT_BEACON_QUEUE_MAX_SIZE=10;var DEFAULT_BEACON_QUEUE_FLUSH_INTERVAL_MS=10*60*1000;// 10 minutes
1308
+ // Limit of the Beacon transfer mechanism on the browsers
1309
+ var MAX_BATCH_PAYLOAD_SIZE_BYTES=64*1024;// 64 KB
1310
+ var DEFAULT_BEACON_QUEUE_OPTIONS={maxItems:DEFAULT_BEACON_QUEUE_MAX_SIZE,flushQueueInterval:DEFAULT_BEACON_QUEUE_FLUSH_INTERVAL_MS};var DATA_PLANE_API_VERSION$1='v1';var QUEUE_NAME$2='rudder_beacon';var BEACON_QUEUE_PLUGIN='BeaconQueuePlugin';
1311
+
1312
+ /**
1313
+ * Utility to get the stringified event payload as Blob
1314
+ * @param events RudderEvent object array
1315
+ * @param logger Logger instance
1316
+ * @returns stringified events payload as Blob, undefined if error occurs.
1317
+ */var getDeliveryPayload=function getDeliveryPayload(events,logger){var data={batch:events};try{var blobPayload=stringifyWithoutCircular(data,true);var blobOptions={type:'text/plain'};if(blobPayload){return new Blob([blobPayload],blobOptions);}logger===null||logger===void 0?void 0:logger.error(BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR(BEACON_QUEUE_PLUGIN));}catch(err){logger===null||logger===void 0?void 0:logger.error(BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR(BEACON_QUEUE_PLUGIN),err);}return undefined;};var getNormalizedBeaconQueueOptions=function getNormalizedBeaconQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_BEACON_QUEUE_OPTIONS,queueOpts);};var getDeliveryUrl$1=function getDeliveryUrl(dataplaneUrl,writeKey){var dpUrl=new URL(dataplaneUrl);return new URL(removeDuplicateSlashes([dpUrl.pathname,'beacon','/',DATA_PLANE_API_VERSION$1,'/',"batch?writeKey=".concat(writeKey)].join('')),dpUrl).href;};
1318
+
1319
+ var COOKIE_STORAGE='cookieStorage';var LOCAL_STORAGE='localStorage';var SESSION_STORAGE='sessionStorage';var MEMORY_STORAGE='memoryStorage';
1320
+
1321
+ var sortByTime$1=function sortByTime(a,b){return a.time-b.time;};var BeaconItemsQueue=/*#__PURE__*/function(){function BeaconItemsQueue(name,options,queueProcessCb,storeManager){var _options$maxItems,_options$flushQueueIn;var storageType=arguments.length>4&&arguments[4]!==undefined?arguments[4]:MEMORY_STORAGE;_classCallCheck(this,BeaconItemsQueue);this.storeManager=storeManager;this.name=name;this.id=generateUUID();this.processQueueCb=queueProcessCb;this.maxItems=(_options$maxItems=options.maxItems)!==null&&_options$maxItems!==void 0?_options$maxItems:DEFAULT_BEACON_QUEUE_OPTIONS.maxItems;this.timeouts={flushQueueTimeOutInterval:(_options$flushQueueIn=options.flushQueueInterval)!==null&&_options$flushQueueIn!==void 0?_options$flushQueueIn:DEFAULT_BEACON_QUEUE_OPTIONS.flushQueueInterval};this.flushInProgress=false;this.nextFlushPending=false;// Set up our empty queues
1322
+ this.store=this.storeManager.setStore({id:this.id,name:this.name,type:storageType});this.flushQueue=this.flushQueue.bind(this);this.attachListeners();this.flushQueueTimeOut=undefined;this.scheduleTimeoutActive=false;}_createClass(BeaconItemsQueue,[{key:"attachListeners",value:function attachListeners(){var _this=this;globalThis.addEventListener('visibilitychange',function(){if(document.visibilityState==='hidden'){_this.flushQueue();}});}},{key:"getQueue",value:function getQueue(name){var _this$store$get;return (_this$store$get=this.store.get(name!==null&&name!==void 0?name:this.name))!==null&&_this$store$get!==void 0?_this$store$get:[];}},{key:"setQueue",value:function setQueue(name,value){this.store.set(name!==null&&name!==void 0?name:this.name,value!==null&&value!==void 0?value:[]);}},{key:"start",value:function start(){if(!this.scheduleTimeoutActive){this.flushQueueTimeOut=globalThis.setTimeout(this.flushQueue,this.timeouts.flushQueueTimeOutInterval);this.scheduleTimeoutActive=true;}}},{key:"stop",value:function stop(){if(this.scheduleTimeoutActive){clearTimeout(this.flushQueueTimeOut);this.scheduleTimeoutActive=false;}}},{key:"enqueue",value:function enqueue(entry){var queue=this.getQueue();// Get max items from the queue minus one
1323
+ queue=queue.slice(-(this.maxItems-1));queue.push(entry);queue=queue.sort(sortByTime$1);// Calculate response payload size after the addition of new event
1324
+ var eventsToSend=queue.slice(0);var batchData=getDeliveryPayload(eventsToSend.map(function(queueItem){return queueItem.item.event;}));// Send events that existed in the queue if totaling more max payload size
1325
+ var isExceededMaxPayloadSize=Boolean(batchData&&batchData.length>MAX_BATCH_PAYLOAD_SIZE_BYTES);if(isExceededMaxPayloadSize){// Flush all previous items
1326
+ eventsToSend=queue.slice(0,queue.length-1);this.flushQueue(eventsToSend);// Add only latest item in the remaining queue that is cleared appropriately in flushQueue
1327
+ queue=this.getQueue();queue.push(entry);}this.setQueue(this.name,queue);// If queue has total of max items then flush
1328
+ if(queue.length===this.maxItems){this.flushQueue();}this.start();}},{key:"addItem",value:function addItem(item){this.enqueue({item:item,attemptNumber:0,time:Date.now(),id:generateUUID()});}},{key:"flushQueue",value:function flushQueue(queueItems){var _this2=this;if(!this.flushInProgress){this.flushInProgress=true;var batchItems=queueItems!==null&&queueItems!==void 0?queueItems:this.getQueue();var batchData=batchItems&&batchItems.length>0?batchItems.slice(0,batchItems.length):[];// TODO: add retry mechanism here
1329
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1330
+ var beaconSendCallback=function beaconSendCallback(error,response){_this2.setQueue(_this2.name,[]);_this2.stop();_this2.flushInProgress=false;if(_this2.nextFlushPending){_this2.nextFlushPending=false;_this2.flushQueue();}};if(batchData.length>0){this.processQueueCb(batchData,beaconSendCallback);return;}// If no items to send just clear timer
1331
+ beaconSendCallback(null);}else {this.nextFlushPending=true;}}}]);return BeaconItemsQueue;}();
1332
+
1333
+ var pluginName$d='BeaconQueue';var BeaconQueue=function BeaconQueue(){return {name:pluginName$d,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$d]);},dataplaneEventsQueue:{/**
1334
+ * Initialize the queue for delivery
1335
+ * @param state Application state
1336
+ * @param httpClient http client instance
1337
+ * @param storeManager Store Manager instance
1338
+ * @param errorHandler Error handler instance
1339
+ * @param logger Logger instance
1340
+ * @returns BeaconItemsQueue instance
1341
+ */init:function init(state,httpClient,storeManager,errorHandler,logger){var _state$loadOptions$va;var writeKey=state.lifecycle.writeKey.value;var dataplaneUrl=state.lifecycle.activeDataplaneUrl.value;var url=getDeliveryUrl$1(dataplaneUrl,writeKey);var finalQOpts=getNormalizedBeaconQueueOptions((_state$loadOptions$va=state.loadOptions.value.beaconQueueOptions)!==null&&_state$loadOptions$va!==void 0?_state$loadOptions$va:{});var queueProcessCallback=function queueProcessCallback(queueItems,done){logger===null||logger===void 0?void 0:logger.debug(BEACON_PLUGIN_EVENTS_QUEUE_DEBUG(BEACON_QUEUE_PLUGIN));var finalEvents=queueItems.map(function(queueItem){return getFinalEventForDeliveryMutator(queueItem.item.event,state);});var data=getDeliveryPayload(finalEvents);if(data){try{var isEnqueuedInBeacon=navigator.sendBeacon(url,data);if(!isEnqueuedInBeacon){logger===null||logger===void 0?void 0:logger.error(BEACON_QUEUE_SEND_ERROR(BEACON_QUEUE_PLUGIN));}done(null,isEnqueuedInBeacon);}catch(e){e.message="An error occurred while sending events batch data to beacon queue for ".concat(url,": ").concat(e.message);done(e);}}else {logger===null||logger===void 0?void 0:logger.error(BEACON_QUEUE_PAYLOAD_PREPARATION_ERROR(BEACON_QUEUE_PLUGIN));// Mark the item as done so that it can be removed from the queue
1342
+ done(null);}};var eventsQueue=new BeaconItemsQueue("".concat(QUEUE_NAME$2,"_").concat(writeKey,"}"),finalQOpts,queueProcessCallback,storeManager);return eventsQueue;},/**
1343
+ * Add event to the queue for delivery
1344
+ * @param state Application state
1345
+ * @param eventsQueue IQueue instance
1346
+ * @param event RudderEvent object
1347
+ * @param errorHandler Error handler instance
1348
+ * @param logger Logger instance
1349
+ * @returns none
1350
+ */enqueue:function enqueue(state,eventsQueue,event,errorHandler,logger){// sentAt is only added here for the validation step
1351
+ // It'll be updated to the latest timestamp during actual delivery
1352
+ event.sentAt=getCurrentTimeFormatted();validateEventPayloadSize(event,logger);eventsQueue.addItem({event:event});}}};};
1353
+
1354
+ var _CNameMapping$18;var DIR_NAME$18='AdobeAnalytics';var NAME$18='ADOBE_ANALYTICS';var DISPLAY_NAME$18='Adobe Analytics';var DISPLAY_NAME_TO_DIR_NAME_MAP$18=_defineProperty({},DISPLAY_NAME$18,DIR_NAME$18);var CNameMapping$18=(_CNameMapping$18={'Adobe Analytics':NAME$18,ADOBEANALYTICS:NAME$18,'ADOBE ANALYTICS':NAME$18},_defineProperty(_CNameMapping$18,NAME$18,NAME$18),_defineProperty(_CNameMapping$18,"AdobeAnalytics",NAME$18),_defineProperty(_CNameMapping$18,"adobeanalytics",NAME$18),_defineProperty(_CNameMapping$18,'adobe analytics',NAME$18),_defineProperty(_CNameMapping$18,'Adobe analytics',NAME$18),_defineProperty(_CNameMapping$18,'adobe Analytics',NAME$18),_CNameMapping$18);
1355
+
1356
+ var _CNameMapping$17;var DIR_NAME$17='Amplitude';var NAME$17='AM';var DISPLAY_NAME$17='Amplitude';var DISPLAY_NAME_TO_DIR_NAME_MAP$17=_defineProperty({},DISPLAY_NAME$17,DIR_NAME$17);var CNameMapping$17=(_CNameMapping$17={},_defineProperty(_CNameMapping$17,NAME$17,NAME$17),_defineProperty(_CNameMapping$17,"AMPLITUDE",NAME$17),_defineProperty(_CNameMapping$17,"Amplitude",NAME$17),_defineProperty(_CNameMapping$17,"am",NAME$17),_CNameMapping$17);
1357
+
1358
+ var _CNameMapping$16;var DIR_NAME$16='Appcues';var NAME$16='APPCUES';var DISPLAY_NAME$16='Appcues';var DISPLAY_NAME_TO_DIR_NAME_MAP$16=_defineProperty({},DISPLAY_NAME$16,DIR_NAME$16);var CNameMapping$16=(_CNameMapping$16={},_defineProperty(_CNameMapping$16,NAME$16,NAME$16),_defineProperty(_CNameMapping$16,"Appcues",NAME$16),_defineProperty(_CNameMapping$16,'App Cues',NAME$16),_defineProperty(_CNameMapping$16,"appcues",NAME$16),_CNameMapping$16);
1359
+
1360
+ var _CNameMapping$15;var DIR_NAME$15='BingAds';var NAME$15='BINGADS';var DISPLAY_NAME$15='Bing Ads';var DISPLAY_NAME_TO_DIR_NAME_MAP$15=_defineProperty({},DISPLAY_NAME$15,DIR_NAME$15);var CNameMapping$15=(_CNameMapping$15={},_defineProperty(_CNameMapping$15,NAME$15,NAME$15),_defineProperty(_CNameMapping$15,"BingAds",NAME$15),_defineProperty(_CNameMapping$15,"bingads",NAME$15),_defineProperty(_CNameMapping$15,'Bing Ads',NAME$15),_defineProperty(_CNameMapping$15,'Bing ads',NAME$15),_defineProperty(_CNameMapping$15,'bing Ads',NAME$15),_defineProperty(_CNameMapping$15,'bing ads',NAME$15),_CNameMapping$15);
1361
+
1362
+ var _CNameMapping$14;var DIR_NAME$14='Braze';var NAME$14='BRAZE';var DISPLAY_NAME$14='Braze';var DISPLAY_NAME_TO_DIR_NAME_MAP$14=_defineProperty({},DISPLAY_NAME$14,DIR_NAME$14);var CNameMapping$14=(_CNameMapping$14={},_defineProperty(_CNameMapping$14,NAME$14,NAME$14),_defineProperty(_CNameMapping$14,"Braze",NAME$14),_defineProperty(_CNameMapping$14,"braze",NAME$14),_CNameMapping$14);
1363
+
1364
+ var _CNameMapping$13;var DIR_NAME$13='Bugsnag';var NAME$13='BUGSNAG';var DISPLAY_NAME$13='Bugsnag';var DISPLAY_NAME_TO_DIR_NAME_MAP$13=_defineProperty({},DISPLAY_NAME$13,DIR_NAME$13);var CNameMapping$13=(_CNameMapping$13={},_defineProperty(_CNameMapping$13,NAME$13,NAME$13),_defineProperty(_CNameMapping$13,"bugsnag",NAME$13),_defineProperty(_CNameMapping$13,"Bugsnag",NAME$13),_CNameMapping$13);
1365
+
1366
+ var _CNameMapping$12;var DIR_NAME$12='Chartbeat';var NAME$12='CHARTBEAT';var DISPLAY_NAME$12='Chartbeat';var DISPLAY_NAME_TO_DIR_NAME_MAP$12=_defineProperty({},DISPLAY_NAME$12,DIR_NAME$12);var CNameMapping$12=(_CNameMapping$12={},_defineProperty(_CNameMapping$12,NAME$12,NAME$12),_defineProperty(_CNameMapping$12,"Chartbeat",NAME$12),_defineProperty(_CNameMapping$12,"chartbeat",NAME$12),_defineProperty(_CNameMapping$12,'Chart Beat',NAME$12),_defineProperty(_CNameMapping$12,'chart beat',NAME$12),_CNameMapping$12);
1367
+
1368
+ var _CNameMapping$11;var DIR_NAME$11='Clevertap';var NAME$11='CLEVERTAP';var DISPLAY_NAME$11='CleverTap';var DISPLAY_NAME_TO_DIR_NAME_MAP$11=_defineProperty({},DISPLAY_NAME$11,DIR_NAME$11);var CNameMapping$11=(_CNameMapping$11={},_defineProperty(_CNameMapping$11,NAME$11,NAME$11),_defineProperty(_CNameMapping$11,"Clevertap",NAME$11),_defineProperty(_CNameMapping$11,"clevertap",NAME$11),_CNameMapping$11);
1369
+
1370
+ var _CNameMapping$10;var DIR_NAME$10='Comscore';var NAME$10='COMSCORE';var DISPLAY_NAME$10='Comscore';var DISPLAY_NAME_TO_DIR_NAME_MAP$10=_defineProperty({},DISPLAY_NAME$10,DIR_NAME$10);var CNameMapping$10=(_CNameMapping$10={},_defineProperty(_CNameMapping$10,NAME$10,NAME$10),_defineProperty(_CNameMapping$10,"Comscore",NAME$10),_defineProperty(_CNameMapping$10,'Com Score',NAME$10),_defineProperty(_CNameMapping$10,'com Score',NAME$10),_defineProperty(_CNameMapping$10,'com score',NAME$10),_defineProperty(_CNameMapping$10,'Com score',NAME$10),_CNameMapping$10);
1371
+
1372
+ var _CNameMapping$$;var DIR_NAME$$='Criteo';var NAME$$='CRITEO';var DISPLAY_NAME$$='Criteo';var DISPLAY_NAME_TO_DIR_NAME_MAP$$=_defineProperty({},DISPLAY_NAME$$,DIR_NAME$$);var CNameMapping$$=(_CNameMapping$$={},_defineProperty(_CNameMapping$$,NAME$$,NAME$$),_defineProperty(_CNameMapping$$,"Criteo",NAME$$),_defineProperty(_CNameMapping$$,"criteo",NAME$$),_CNameMapping$$);
1373
+
1374
+ var _CNameMapping$_;var DIR_NAME$_='CustomerIO';var NAME$_='CUSTOMERIO';var DISPLAY_NAME$_='Customer IO';var DISPLAY_NAME_TO_DIR_NAME_MAP$_=_defineProperty({},DISPLAY_NAME$_,DIR_NAME$_);var CNameMapping$_=(_CNameMapping$_={},_defineProperty(_CNameMapping$_,NAME$_,NAME$_),_defineProperty(_CNameMapping$_,"Customerio",NAME$_),_defineProperty(_CNameMapping$_,'Customer.io',NAME$_),_defineProperty(_CNameMapping$_,'CUSTOMER.IO',NAME$_),_defineProperty(_CNameMapping$_,'customer.io',NAME$_),_CNameMapping$_);
1375
+
1376
+ var _CNameMapping$Z;var DIR_NAME$Z='Drip';var NAME$Z='DRIP';var DISPLAY_NAME$Z='Drip';var DISPLAY_NAME_TO_DIR_NAME_MAP$Z=_defineProperty({},DISPLAY_NAME$Z,DIR_NAME$Z);var CNameMapping$Z=(_CNameMapping$Z={},_defineProperty(_CNameMapping$Z,NAME$Z,NAME$Z),_defineProperty(_CNameMapping$Z,"Drip",NAME$Z),_defineProperty(_CNameMapping$Z,"drip",NAME$Z),_CNameMapping$Z);
1377
+
1378
+ var _CNameMapping$Y;var DIR_NAME$Y='FacebookPixel';var NAME$Y='FACEBOOK_PIXEL';var DISPLAY_NAME$Y='Facebook Pixel';var DISPLAY_NAME_TO_DIR_NAME_MAP$Y=_defineProperty({},DISPLAY_NAME$Y,DIR_NAME$Y);var CNameMapping$Y=(_CNameMapping$Y={},_defineProperty(_CNameMapping$Y,NAME$Y,NAME$Y),_defineProperty(_CNameMapping$Y,'FB Pixel',NAME$Y),_defineProperty(_CNameMapping$Y,'Facebook Pixel',NAME$Y),_defineProperty(_CNameMapping$Y,'facebook pixel',NAME$Y),_defineProperty(_CNameMapping$Y,"fbpixel",NAME$Y),_defineProperty(_CNameMapping$Y,"FBPIXEL",NAME$Y),_defineProperty(_CNameMapping$Y,"FB_PIXEL",NAME$Y),_CNameMapping$Y);
1379
+
1380
+ var _CNameMapping$X;var DIR_NAME$X='Fullstory';var NAME$X='FULLSTORY';var DISPLAY_NAME$X='Fullstory';var DISPLAY_NAME_TO_DIR_NAME_MAP$X=_defineProperty({},DISPLAY_NAME$X,DIR_NAME$X);var CNameMapping$X=(_CNameMapping$X={},_defineProperty(_CNameMapping$X,NAME$X,NAME$X),_defineProperty(_CNameMapping$X,"Fullstory",NAME$X),_defineProperty(_CNameMapping$X,"FullStory",NAME$X),_defineProperty(_CNameMapping$X,'full Story',NAME$X),_defineProperty(_CNameMapping$X,'Full Story',NAME$X),_defineProperty(_CNameMapping$X,'Full story',NAME$X),_defineProperty(_CNameMapping$X,'full story',NAME$X),_defineProperty(_CNameMapping$X,"fullstory",NAME$X),_CNameMapping$X);
1381
+
1382
+ var _CNameMapping$W;var DIR_NAME$W='GA';var NAME$W='GA';var DISPLAY_NAME$W='Google Analytics';var DISPLAY_NAME_TO_DIR_NAME_MAP$W=_defineProperty({},DISPLAY_NAME$W,DIR_NAME$W);var CNameMapping$W=(_CNameMapping$W={},_defineProperty(_CNameMapping$W,NAME$W,NAME$W),_defineProperty(_CNameMapping$W,'Google Analytics',NAME$W),_defineProperty(_CNameMapping$W,"GoogleAnalytics",NAME$W),_defineProperty(_CNameMapping$W,'GOOGLE ANALYTICS',NAME$W),_defineProperty(_CNameMapping$W,'google analytics',NAME$W),_CNameMapping$W);
1383
+
1384
+ var _CNameMapping$V;var DIR_NAME$V='GA4';var NAME$V='GA4';var DISPLAY_NAME$V='Google Analytics 4 (GA4)';var DISPLAY_NAME_TO_DIR_NAME_MAP$V=_defineProperty({},DISPLAY_NAME$V,DIR_NAME$V);var CNameMapping$V=(_CNameMapping$V={},_defineProperty(_CNameMapping$V,NAME$V,NAME$V),_defineProperty(_CNameMapping$V,'Google Analytics 4',NAME$V),_defineProperty(_CNameMapping$V,'Google analytics 4',NAME$V),_defineProperty(_CNameMapping$V,'google analytics 4',NAME$V),_defineProperty(_CNameMapping$V,'Google Analytics4',NAME$V),_defineProperty(_CNameMapping$V,'Google analytics4',NAME$V),_defineProperty(_CNameMapping$V,'google analytics4',NAME$V),_defineProperty(_CNameMapping$V,"GoogleAnalytics4",NAME$V),_CNameMapping$V);
1385
+
1386
+ var _CNameMapping$U;var DIR_NAME$U='GoogleAds';var NAME$U='GOOGLEADS';var DISPLAY_NAME$U='Google Ads';var DISPLAY_NAME_TO_DIR_NAME_MAP$U=_defineProperty({},DISPLAY_NAME$U,DIR_NAME$U);var CNameMapping$U=(_CNameMapping$U={},_defineProperty(_CNameMapping$U,NAME$U,NAME$U),_defineProperty(_CNameMapping$U,'Google Ads',NAME$U),_defineProperty(_CNameMapping$U,"GoogleAds",NAME$U),_defineProperty(_CNameMapping$U,'GOOGLE ADS',NAME$U),_defineProperty(_CNameMapping$U,'google ads',NAME$U),_defineProperty(_CNameMapping$U,"googleads",NAME$U),_CNameMapping$U);
1387
+
1388
+ var _CNameMapping$T;var DIR_NAME$T='GoogleOptimize';var NAME$T='GOOGLE_OPTIMIZE';var DISPLAY_NAME$T='Google Optimize';var DISPLAY_NAME_TO_DIR_NAME_MAP$T=_defineProperty({},DISPLAY_NAME$T,DIR_NAME$T);var CNameMapping$T=(_CNameMapping$T={},_defineProperty(_CNameMapping$T,NAME$T,NAME$T),_defineProperty(_CNameMapping$T,'Google Optimize',NAME$T),_defineProperty(_CNameMapping$T,"GoogleOptimize",NAME$T),_defineProperty(_CNameMapping$T,"Googleoptimize",NAME$T),_defineProperty(_CNameMapping$T,"GOOGLEOPTIMIZE",NAME$T),_defineProperty(_CNameMapping$T,'google optimize',NAME$T),_defineProperty(_CNameMapping$T,'Google optimize',NAME$T),_defineProperty(_CNameMapping$T,'GOOGLE OPTIMIZE',NAME$T),_CNameMapping$T);
1389
+
1390
+ var _CNameMapping$S;var DIR_NAME$S='GoogleTagManager';var NAME$S='GTM';var DISPLAY_NAME$S='Google Tag Manager';var DISPLAY_NAME_TO_DIR_NAME_MAP$S=_defineProperty({},DISPLAY_NAME$S,DIR_NAME$S);var CNameMapping$S=(_CNameMapping$S={},_defineProperty(_CNameMapping$S,NAME$S,NAME$S),_defineProperty(_CNameMapping$S,'Google Tag Manager',NAME$S),_defineProperty(_CNameMapping$S,'google tag manager',NAME$S),_defineProperty(_CNameMapping$S,'googletag manager',NAME$S),_defineProperty(_CNameMapping$S,"googletagmanager",NAME$S),_CNameMapping$S);
1391
+
1392
+ var _CNameMapping$R;var DIR_NAME$R='Heap';var NAME$R='HEAP';var DISPLAY_NAME$R='Heap.io';var DISPLAY_NAME_TO_DIR_NAME_MAP$R=_defineProperty({},DISPLAY_NAME$R,DIR_NAME$R);var CNameMapping$R=(_CNameMapping$R={},_defineProperty(_CNameMapping$R,NAME$R,NAME$R),_defineProperty(_CNameMapping$R,"Heap",NAME$R),_defineProperty(_CNameMapping$R,"heap",NAME$R),_defineProperty(_CNameMapping$R,'Heap.io',NAME$R),_CNameMapping$R);
1393
+
1394
+ var _CNameMapping$Q;var DIR_NAME$Q='Hotjar';var NAME$Q='HOTJAR';var DISPLAY_NAME$Q='Hotjar';var DISPLAY_NAME_TO_DIR_NAME_MAP$Q=_defineProperty({},DISPLAY_NAME$Q,DIR_NAME$Q);var CNameMapping$Q=(_CNameMapping$Q={},_defineProperty(_CNameMapping$Q,NAME$Q,NAME$Q),_defineProperty(_CNameMapping$Q,"Hotjar",NAME$Q),_defineProperty(_CNameMapping$Q,"hotjar",NAME$Q),_defineProperty(_CNameMapping$Q,'Hot Jar',NAME$Q),_defineProperty(_CNameMapping$Q,'hot jar',NAME$Q),_CNameMapping$Q);
1395
+
1396
+ var _CNameMapping$P;var DIR_NAME$P='HubSpot';var NAME$P='HS';var DISPLAY_NAME$P='HubSpot';var DISPLAY_NAME_TO_DIR_NAME_MAP$P=_defineProperty({},DISPLAY_NAME$P,DIR_NAME$P);var CNameMapping$P=(_CNameMapping$P={},_defineProperty(_CNameMapping$P,NAME$P,NAME$P),_defineProperty(_CNameMapping$P,"Hubspot",NAME$P),_defineProperty(_CNameMapping$P,"HUBSPOT",NAME$P),_defineProperty(_CNameMapping$P,'hub spot',NAME$P),_defineProperty(_CNameMapping$P,'Hub Spot',NAME$P),_defineProperty(_CNameMapping$P,'Hub spot',NAME$P),_CNameMapping$P);
1397
+
1398
+ var _CNameMapping$O;var DIR_NAME$O='INTERCOM';var NAME$O='INTERCOM';var DISPLAY_NAME$O='Intercom';var DISPLAY_NAME_TO_DIR_NAME_MAP$O=_defineProperty({},DISPLAY_NAME$O,DIR_NAME$O);var CNameMapping$O=(_CNameMapping$O={},_defineProperty(_CNameMapping$O,NAME$O,NAME$O),_defineProperty(_CNameMapping$O,"Intercom",NAME$O),_defineProperty(_CNameMapping$O,"intercom",NAME$O),_CNameMapping$O);
1399
+
1400
+ var _CNameMapping$N;var DIR_NAME$N='Keen';var NAME$N='KEEN';var DISPLAY_NAME$N='Keen';var DISPLAY_NAME_TO_DIR_NAME_MAP$N=_defineProperty({},DISPLAY_NAME$N,DIR_NAME$N);var CNameMapping$N=(_CNameMapping$N={},_defineProperty(_CNameMapping$N,NAME$N,NAME$N),_defineProperty(_CNameMapping$N,"Keen",NAME$N),_defineProperty(_CNameMapping$N,'Keen.io',NAME$N),_defineProperty(_CNameMapping$N,"keen",NAME$N),_defineProperty(_CNameMapping$N,'keen.io',NAME$N),_CNameMapping$N);
1401
+
1402
+ var _CNameMapping$M;var DIR_NAME$M='Kissmetrics';var NAME$M='KISSMETRICS';var DISPLAY_NAME$M='Kiss Metrics';var DISPLAY_NAME_TO_DIR_NAME_MAP$M=_defineProperty({},DISPLAY_NAME$M,DIR_NAME$M);var CNameMapping$M=(_CNameMapping$M={},_defineProperty(_CNameMapping$M,NAME$M,NAME$M),_defineProperty(_CNameMapping$M,"Kissmetrics",NAME$M),_defineProperty(_CNameMapping$M,"kissmetrics",NAME$M),_CNameMapping$M);
1403
+
1404
+ var _CNameMapping$L;var DIR_NAME$L='Klaviyo';var NAME$L='KLAVIYO';var DISPLAY_NAME$L='Klaviyo';var DISPLAY_NAME_TO_DIR_NAME_MAP$L=_defineProperty({},DISPLAY_NAME$L,DIR_NAME$L);var CNameMapping$L=(_CNameMapping$L={},_defineProperty(_CNameMapping$L,NAME$L,NAME$L),_defineProperty(_CNameMapping$L,"Klaviyo",NAME$L),_defineProperty(_CNameMapping$L,"klaviyo",NAME$L),_CNameMapping$L);
1405
+
1406
+ var _CNameMapping$K;var DIR_NAME$K='LaunchDarkly';var NAME$K='LAUNCHDARKLY';var DISPLAY_NAME$K='LaunchDarkly';var DISPLAY_NAME_TO_DIR_NAME_MAP$K=_defineProperty({},DISPLAY_NAME$K,DIR_NAME$K);var CNameMapping$K=(_CNameMapping$K={},_defineProperty(_CNameMapping$K,NAME$K,NAME$K),_defineProperty(_CNameMapping$K,"LaunchDarkly",NAME$K),_defineProperty(_CNameMapping$K,"Launch_Darkly",NAME$K),_defineProperty(_CNameMapping$K,'Launch Darkly',NAME$K),_defineProperty(_CNameMapping$K,"launchDarkly",NAME$K),_defineProperty(_CNameMapping$K,'launch darkly',NAME$K),_CNameMapping$K);
1407
+
1408
+ var _CNameMapping$J;var DIR_NAME$J='LinkedInInsightTag';var NAME$J='LINKEDIN_INSIGHT_TAG';var DISPLAY_NAME$J='Linkedin Insight Tag';var DISPLAY_NAME_TO_DIR_NAME_MAP$J=_defineProperty({},DISPLAY_NAME$J,DIR_NAME$J);var CNameMapping$J=(_CNameMapping$J={},_defineProperty(_CNameMapping$J,NAME$J,NAME$J),_defineProperty(_CNameMapping$J,'LinkedIn Insight Tag',NAME$J),_defineProperty(_CNameMapping$J,'LinkedIn insight tag',NAME$J),_defineProperty(_CNameMapping$J,'linkedIn insight tag',NAME$J),_defineProperty(_CNameMapping$J,"Linkedin_insight_tag",NAME$J),_defineProperty(_CNameMapping$J,"LinkedinInsighttag",NAME$J),_defineProperty(_CNameMapping$J,"LinkedinInsightTag",NAME$J),_defineProperty(_CNameMapping$J,"LinkedInInsightTag",NAME$J),_defineProperty(_CNameMapping$J,"Linkedininsighttag",NAME$J),_defineProperty(_CNameMapping$J,"LINKEDININSIGHTTAG",NAME$J),_defineProperty(_CNameMapping$J,"linkedininsighttag",NAME$J),_CNameMapping$J);
1409
+
1410
+ var _CNameMapping$I;var DIR_NAME$I='Lotame';var NAME$I='LOTAME';var DISPLAY_NAME$I='Lotame';var DISPLAY_NAME_TO_DIR_NAME_MAP$I=_defineProperty({},DISPLAY_NAME$I,DIR_NAME$I);var CNameMapping$I=(_CNameMapping$I={},_defineProperty(_CNameMapping$I,NAME$I,NAME$I),_defineProperty(_CNameMapping$I,"Lotame",NAME$I),_defineProperty(_CNameMapping$I,"lotame",NAME$I),_CNameMapping$I);
1411
+
1412
+ var _CNameMapping$H;var DIR_NAME$H='Lytics';var NAME$H='LYTICS';var DISPLAY_NAME$H='Lytics';var DISPLAY_NAME_TO_DIR_NAME_MAP$H=_defineProperty({},DISPLAY_NAME$H,DIR_NAME$H);var CNameMapping$H=(_CNameMapping$H={},_defineProperty(_CNameMapping$H,NAME$H,NAME$H),_defineProperty(_CNameMapping$H,"Lytics",NAME$H),_defineProperty(_CNameMapping$H,"lytics",NAME$H),_CNameMapping$H);
1413
+
1414
+ var _CNameMapping$G;var DIR_NAME$G='Mixpanel';var NAME$G='MP';var DISPLAY_NAME$G='Mixpanel';var DISPLAY_NAME_TO_DIR_NAME_MAP$G=_defineProperty({},DISPLAY_NAME$G,DIR_NAME$G);var CNameMapping$G=(_CNameMapping$G={},_defineProperty(_CNameMapping$G,NAME$G,NAME$G),_defineProperty(_CNameMapping$G,"MIXPANEL",NAME$G),_defineProperty(_CNameMapping$G,"Mixpanel",NAME$G),_defineProperty(_CNameMapping$G,'MIX PANEL',NAME$G),_defineProperty(_CNameMapping$G,'Mix panel',NAME$G),_defineProperty(_CNameMapping$G,'Mix Panel',NAME$G),_CNameMapping$G);
1415
+
1416
+ var _CNameMapping$F;var DIR_NAME$F='MoEngage';var NAME$F='MOENGAGE';var DISPLAY_NAME$F='MoEngage';var DISPLAY_NAME_TO_DIR_NAME_MAP$F=_defineProperty({},DISPLAY_NAME$F,DIR_NAME$F);var CNameMapping$F=(_CNameMapping$F={},_defineProperty(_CNameMapping$F,NAME$F,NAME$F),_defineProperty(_CNameMapping$F,"MoEngage",NAME$F),_defineProperty(_CNameMapping$F,"moengage",NAME$F),_defineProperty(_CNameMapping$F,"Moengage",NAME$F),_defineProperty(_CNameMapping$F,'Mo Engage',NAME$F),_defineProperty(_CNameMapping$F,'mo engage',NAME$F),_defineProperty(_CNameMapping$F,'Mo engage',NAME$F),_CNameMapping$F);
1417
+
1418
+ var _CNameMapping$E;var DIR_NAME$E='Optimizely';var NAME$E='OPTIMIZELY';var DISPLAY_NAME$E='Optimizely Web';var DISPLAY_NAME_TO_DIR_NAME_MAP$E=_defineProperty({},DISPLAY_NAME$E,DIR_NAME$E);var CNameMapping$E=(_CNameMapping$E={},_defineProperty(_CNameMapping$E,NAME$E,NAME$E),_defineProperty(_CNameMapping$E,"Optimizely",NAME$E),_defineProperty(_CNameMapping$E,"optimizely",NAME$E),_CNameMapping$E);
1419
+
1420
+ var _CNameMapping$D;var DIR_NAME$D='Pendo';var NAME$D='PENDO';var DISPLAY_NAME$D='Pendo';var DISPLAY_NAME_TO_DIR_NAME_MAP$D=_defineProperty({},DISPLAY_NAME$D,DIR_NAME$D);var CNameMapping$D=(_CNameMapping$D={},_defineProperty(_CNameMapping$D,NAME$D,NAME$D),_defineProperty(_CNameMapping$D,"Pendo",NAME$D),_defineProperty(_CNameMapping$D,"pendo",NAME$D),_CNameMapping$D);
1421
+
1422
+ var _CNameMapping$C;var DIR_NAME$C='PinterestTag';var NAME$C='PINTEREST_TAG';var DISPLAY_NAME$C='Pinterest Tag';var DISPLAY_NAME_TO_DIR_NAME_MAP$C=_defineProperty({},DISPLAY_NAME$C,DIR_NAME$C);var CNameMapping$C=(_CNameMapping$C={},_defineProperty(_CNameMapping$C,NAME$C,NAME$C),_defineProperty(_CNameMapping$C,"PinterestTag",NAME$C),_defineProperty(_CNameMapping$C,"Pinterest_Tag",NAME$C),_defineProperty(_CNameMapping$C,"PINTERESTTAG",NAME$C),_defineProperty(_CNameMapping$C,"pinterest",NAME$C),_defineProperty(_CNameMapping$C,"PinterestAds",NAME$C),_defineProperty(_CNameMapping$C,"Pinterest_Ads",NAME$C),_defineProperty(_CNameMapping$C,"Pinterest",NAME$C),_defineProperty(_CNameMapping$C,'Pinterest Tag',NAME$C),_defineProperty(_CNameMapping$C,'Pinterest tag',NAME$C),_defineProperty(_CNameMapping$C,'PINTEREST TAG',NAME$C),_defineProperty(_CNameMapping$C,'pinterest tag',NAME$C),_defineProperty(_CNameMapping$C,'Pinterest Ads',NAME$C),_defineProperty(_CNameMapping$C,'Pinterest ads',NAME$C),_CNameMapping$C);
1423
+
1424
+ var _CNameMapping$B;var DIR_NAME$B='PostAffiliatePro';var NAME$B='POST_AFFILIATE_PRO';var DISPLAY_NAME$B='Post Affiliate Pro';var DISPLAY_NAME_TO_DIR_NAME_MAP$B=_defineProperty({},DISPLAY_NAME$B,DIR_NAME$B);var CNameMapping$B=(_CNameMapping$B={},_defineProperty(_CNameMapping$B,NAME$B,NAME$B),_defineProperty(_CNameMapping$B,"PostAffiliatePro",NAME$B),_defineProperty(_CNameMapping$B,"Post_affiliate_pro",NAME$B),_defineProperty(_CNameMapping$B,'Post Affiliate Pro',NAME$B),_defineProperty(_CNameMapping$B,'Post affiliate pro',NAME$B),_defineProperty(_CNameMapping$B,'post affiliate pro',NAME$B),_defineProperty(_CNameMapping$B,"postaffiliatepro",NAME$B),_defineProperty(_CNameMapping$B,"POSTAFFILIATEPRO",NAME$B),_CNameMapping$B);
1425
+
1426
+ var _CNameMapping$A;var DIR_NAME$A='Posthog';var NAME$A='POSTHOG';var DISPLAY_NAME$A='PostHog';var DISPLAY_NAME_TO_DIR_NAME_MAP$A=_defineProperty({},DISPLAY_NAME$A,DIR_NAME$A);var CNameMapping$A=(_CNameMapping$A={},_defineProperty(_CNameMapping$A,NAME$A,NAME$A),_defineProperty(_CNameMapping$A,"PostHog",NAME$A),_defineProperty(_CNameMapping$A,"Posthog",NAME$A),_defineProperty(_CNameMapping$A,"posthog",NAME$A),_defineProperty(_CNameMapping$A,'Post Hog',NAME$A),_defineProperty(_CNameMapping$A,'Post hog',NAME$A),_defineProperty(_CNameMapping$A,'post hog',NAME$A),_CNameMapping$A);
1427
+
1428
+ var _CNameMapping$z;var DIR_NAME$z='ProfitWell';var NAME$z='PROFITWELL';var DISPLAY_NAME$z='ProfitWell';var DISPLAY_NAME_TO_DIR_NAME_MAP$z=_defineProperty({},DISPLAY_NAME$z,DIR_NAME$z);var CNameMapping$z=(_CNameMapping$z={},_defineProperty(_CNameMapping$z,NAME$z,NAME$z),_defineProperty(_CNameMapping$z,"ProfitWell",NAME$z),_defineProperty(_CNameMapping$z,"profitwell",NAME$z),_defineProperty(_CNameMapping$z,"Profitwell",NAME$z),_defineProperty(_CNameMapping$z,'Profit Well',NAME$z),_defineProperty(_CNameMapping$z,'profit well',NAME$z),_defineProperty(_CNameMapping$z,'Profit well',NAME$z),_CNameMapping$z);
1429
+
1430
+ var _CNameMapping$y;var DIR_NAME$y='Qualtrics';var NAME$y='QUALTRICS';var DISPLAY_NAME$y='Qualtrics';var DISPLAY_NAME_TO_DIR_NAME_MAP$y=_defineProperty({},DISPLAY_NAME$y,DIR_NAME$y);var CNameMapping$y=(_CNameMapping$y={},_defineProperty(_CNameMapping$y,NAME$y,NAME$y),_defineProperty(_CNameMapping$y,"Qualtrics",NAME$y),_defineProperty(_CNameMapping$y,"qualtrics",NAME$y),_CNameMapping$y);
1431
+
1432
+ var _CNameMapping$x;var DIR_NAME$x='QuantumMetric';var NAME$x='QUANTUMMETRIC';var DISPLAY_NAME$x='Quantum Metric';var DISPLAY_NAME_TO_DIR_NAME_MAP$x=_defineProperty({},DISPLAY_NAME$x,DIR_NAME$x);var CNameMapping$x=(_CNameMapping$x={},_defineProperty(_CNameMapping$x,NAME$x,NAME$x),_defineProperty(_CNameMapping$x,'Quantum Metric',NAME$x),_defineProperty(_CNameMapping$x,'quantum Metric',NAME$x),_defineProperty(_CNameMapping$x,'quantum metric',NAME$x),_defineProperty(_CNameMapping$x,"QuantumMetric",NAME$x),_defineProperty(_CNameMapping$x,"quantumMetric",NAME$x),_defineProperty(_CNameMapping$x,"quantummetric",NAME$x),_defineProperty(_CNameMapping$x,"Quantum_Metric",NAME$x),_CNameMapping$x);
1433
+
1434
+ var _CNameMapping$w;var DIR_NAME$w='RedditPixel';var NAME$w='REDDIT_PIXEL';var DISPLAY_NAME$w='Reddit Pixel';var DISPLAY_NAME_TO_DIR_NAME_MAP$w=_defineProperty({},DISPLAY_NAME$w,DIR_NAME$w);var CNameMapping$w=(_CNameMapping$w={},_defineProperty(_CNameMapping$w,NAME$w,NAME$w),_defineProperty(_CNameMapping$w,"Reddit_Pixel",NAME$w),_defineProperty(_CNameMapping$w,"RedditPixel",NAME$w),_defineProperty(_CNameMapping$w,"REDDITPIXEL",NAME$w),_defineProperty(_CNameMapping$w,"redditpixel",NAME$w),_defineProperty(_CNameMapping$w,'Reddit Pixel',NAME$w),_defineProperty(_CNameMapping$w,'REDDIT PIXEL',NAME$w),_defineProperty(_CNameMapping$w,'reddit pixel',NAME$w),_CNameMapping$w);
1435
+
1436
+ var _CNameMapping$v;var DIR_NAME$v='Sentry';var NAME$v='SENTRY';var DISPLAY_NAME$v='Sentry';var DISPLAY_NAME_TO_DIR_NAME_MAP$v=_defineProperty({},DISPLAY_NAME$v,DIR_NAME$v);var CNameMapping$v=(_CNameMapping$v={},_defineProperty(_CNameMapping$v,NAME$v,NAME$v),_defineProperty(_CNameMapping$v,"sentry",NAME$v),_defineProperty(_CNameMapping$v,"Sentry",NAME$v),_CNameMapping$v);
1437
+
1438
+ var _CNameMapping$u;var DIR_NAME$u='SnapPixel';var NAME$u='SNAP_PIXEL';var DISPLAY_NAME$u='Snap Pixel';var DISPLAY_NAME_TO_DIR_NAME_MAP$u=_defineProperty({},DISPLAY_NAME$u,DIR_NAME$u);var CNameMapping$u=(_CNameMapping$u={},_defineProperty(_CNameMapping$u,NAME$u,NAME$u),_defineProperty(_CNameMapping$u,"Snap_Pixel",NAME$u),_defineProperty(_CNameMapping$u,"SnapPixel",NAME$u),_defineProperty(_CNameMapping$u,"SNAPPIXEL",NAME$u),_defineProperty(_CNameMapping$u,"snappixel",NAME$u),_defineProperty(_CNameMapping$u,'Snap Pixel',NAME$u),_defineProperty(_CNameMapping$u,'SNAP PIXEL',NAME$u),_defineProperty(_CNameMapping$u,'snap pixel',NAME$u),_CNameMapping$u);
1439
+
1440
+ var _CNameMapping$t;var DIR_NAME$t='TVSquared';var NAME$t='TVSQUARED';var DISPLAY_NAME$t='TVSquared';var DISPLAY_NAME_TO_DIR_NAME_MAP$t=_defineProperty({},DISPLAY_NAME$t,DIR_NAME$t);var CNameMapping$t=(_CNameMapping$t={},_defineProperty(_CNameMapping$t,NAME$t,NAME$t),_defineProperty(_CNameMapping$t,"TVSquared",NAME$t),_defineProperty(_CNameMapping$t,"tvsquared",NAME$t),_defineProperty(_CNameMapping$t,"tvSquared",NAME$t),_defineProperty(_CNameMapping$t,"TvSquared",NAME$t),_defineProperty(_CNameMapping$t,"Tvsquared",NAME$t),_defineProperty(_CNameMapping$t,'TV Squared',NAME$t),_defineProperty(_CNameMapping$t,'tv squared',NAME$t),_defineProperty(_CNameMapping$t,'tv Squared',NAME$t),_CNameMapping$t);
1441
+
1442
+ var _CNameMapping$s;var DIR_NAME$s='VWO';var NAME$s='VWO';var DISPLAY_NAME$s='VWO';var DISPLAY_NAME_TO_DIR_NAME_MAP$s=_defineProperty({},DISPLAY_NAME$s,DIR_NAME$s);var CNameMapping$s=(_CNameMapping$s={},_defineProperty(_CNameMapping$s,NAME$s,NAME$s),_defineProperty(_CNameMapping$s,"VisualWebsiteOptimizer",NAME$s),_defineProperty(_CNameMapping$s,"Visualwebsiteoptimizer",NAME$s),_defineProperty(_CNameMapping$s,"visualwebsiteoptimizer",NAME$s),_defineProperty(_CNameMapping$s,"vwo",NAME$s),_defineProperty(_CNameMapping$s,'Visual Website Optimizer',NAME$s),_defineProperty(_CNameMapping$s,'Visual website optimizer',NAME$s),_defineProperty(_CNameMapping$s,'visual website optimizer',NAME$s),_CNameMapping$s);
1443
+
1444
+ var _CNameMapping$r;var DIR_NAME$r='GA360';var NAME$r='GA360';var DISPLAY_NAME$r='Google Analytics 360';var DISPLAY_NAME_TO_DIR_NAME_MAP$r=_defineProperty({},DISPLAY_NAME$r,DIR_NAME$r);var CNameMapping$r=(_CNameMapping$r={},_defineProperty(_CNameMapping$r,NAME$r,NAME$r),_defineProperty(_CNameMapping$r,'Google Analytics 360',NAME$r),_defineProperty(_CNameMapping$r,'Google analytics 360',NAME$r),_defineProperty(_CNameMapping$r,'google analytics 360',NAME$r),_defineProperty(_CNameMapping$r,'Google Analytics360',NAME$r),_defineProperty(_CNameMapping$r,'Google analytics360',NAME$r),_defineProperty(_CNameMapping$r,'google analytics360',NAME$r),_defineProperty(_CNameMapping$r,"GoogleAnalytics360",NAME$r),_defineProperty(_CNameMapping$r,'GA 360',NAME$r),_CNameMapping$r);
1445
+
1446
+ var _CNameMapping$q;var DIR_NAME$q='Adroll';var NAME$q='ADROLL';var DISPLAY_NAME$q='Adroll';var DISPLAY_NAME_TO_DIR_NAME_MAP$q=_defineProperty({},DISPLAY_NAME$q,DIR_NAME$q);var CNameMapping$q=(_CNameMapping$q={},_defineProperty(_CNameMapping$q,NAME$q,NAME$q),_defineProperty(_CNameMapping$q,"Adroll",NAME$q),_defineProperty(_CNameMapping$q,'Ad roll',NAME$q),_defineProperty(_CNameMapping$q,'ad roll',NAME$q),_defineProperty(_CNameMapping$q,"adroll",NAME$q),_CNameMapping$q);
1447
+
1448
+ var _CNameMapping$p;var DIR_NAME$p='DCMFloodlight';var NAME$p='DCM_FLOODLIGHT';var DISPLAY_NAME$p='DCM Floodlight';var DISPLAY_NAME_TO_DIR_NAME_MAP$p=_defineProperty({},DISPLAY_NAME$p,DIR_NAME$p);var CNameMapping$p=(_CNameMapping$p={},_defineProperty(_CNameMapping$p,NAME$p,NAME$p),_defineProperty(_CNameMapping$p,'DCM Floodlight',NAME$p),_defineProperty(_CNameMapping$p,'dcm floodlight',NAME$p),_defineProperty(_CNameMapping$p,'Dcm Floodlight',NAME$p),_defineProperty(_CNameMapping$p,"DCMFloodlight",NAME$p),_defineProperty(_CNameMapping$p,"dcmfloodlight",NAME$p),_defineProperty(_CNameMapping$p,"DcmFloodlight",NAME$p),_defineProperty(_CNameMapping$p,"dcm_floodlight",NAME$p),_defineProperty(_CNameMapping$p,"DCM_Floodlight",NAME$p),_CNameMapping$p);
1449
+
1450
+ var _CNameMapping$o;var DIR_NAME$o='Matomo';var NAME$o='MATOMO';var DISPLAY_NAME$o='Matomo';var DISPLAY_NAME_TO_DIR_NAME_MAP$o=_defineProperty({},DISPLAY_NAME$o,DIR_NAME$o);var CNameMapping$o=(_CNameMapping$o={},_defineProperty(_CNameMapping$o,NAME$o,NAME$o),_defineProperty(_CNameMapping$o,"Matomo",NAME$o),_defineProperty(_CNameMapping$o,"matomo",NAME$o),_CNameMapping$o);
1451
+
1452
+ var _CNameMapping$n;var DIR_NAME$n='Vero';var NAME$n='VERO';var DISPLAY_NAME$n='Vero';var DISPLAY_NAME_TO_DIR_NAME_MAP$n=_defineProperty({},DISPLAY_NAME$n,DIR_NAME$n);var CNameMapping$n=(_CNameMapping$n={},_defineProperty(_CNameMapping$n,NAME$n,NAME$n),_defineProperty(_CNameMapping$n,"Vero",NAME$n),_defineProperty(_CNameMapping$n,"vero",NAME$n),_CNameMapping$n);
1453
+
1454
+ var _CNameMapping$m;var DIR_NAME$m='Mouseflow';var NAME$m='MOUSEFLOW';var DISPLAY_NAME$m='Mouseflow';var DISPLAY_NAME_TO_DIR_NAME_MAP$m=_defineProperty({},DISPLAY_NAME$m,DIR_NAME$m);var CNameMapping$m=(_CNameMapping$m={},_defineProperty(_CNameMapping$m,NAME$m,NAME$m),_defineProperty(_CNameMapping$m,"Mouseflow",NAME$m),_defineProperty(_CNameMapping$m,"mouseflow",NAME$m),_defineProperty(_CNameMapping$m,"mouseFlow",NAME$m),_defineProperty(_CNameMapping$m,"MouseFlow",NAME$m),_defineProperty(_CNameMapping$m,'Mouse flow',NAME$m),_defineProperty(_CNameMapping$m,'mouse flow',NAME$m),_defineProperty(_CNameMapping$m,'mouse Flow',NAME$m),_defineProperty(_CNameMapping$m,'Mouse Flow',NAME$m),_CNameMapping$m);
1455
+
1456
+ var _CNameMapping$l;var DIR_NAME$l='Rockerbox';var NAME$l='ROCKERBOX';var DISPLAY_NAME$l='Rockerbox';var DISPLAY_NAME_TO_DIR_NAME_MAP$l=_defineProperty({},DISPLAY_NAME$l,DIR_NAME$l);var CNameMapping$l=(_CNameMapping$l={},_defineProperty(_CNameMapping$l,NAME$l,NAME$l),_defineProperty(_CNameMapping$l,"Rockerbox",NAME$l),_defineProperty(_CNameMapping$l,"rockerbox",NAME$l),_defineProperty(_CNameMapping$l,"RockerBox",NAME$l),_defineProperty(_CNameMapping$l,'Rocker box',NAME$l),_defineProperty(_CNameMapping$l,'rocker box',NAME$l),_defineProperty(_CNameMapping$l,'Rocker Box',NAME$l),_CNameMapping$l);
1457
+
1458
+ var _CNameMapping$k;var DIR_NAME$k='ConvertFlow';var NAME$k='CONVERTFLOW';var DISPLAY_NAME$k='ConvertFlow';var DISPLAY_NAME_TO_DIR_NAME_MAP$k=_defineProperty({},DISPLAY_NAME$k,DIR_NAME$k);var CNameMapping$k=(_CNameMapping$k={},_defineProperty(_CNameMapping$k,NAME$k,NAME$k),_defineProperty(_CNameMapping$k,"Convertflow",NAME$k),_defineProperty(_CNameMapping$k,"convertflow",NAME$k),_defineProperty(_CNameMapping$k,"convertFlow",NAME$k),_defineProperty(_CNameMapping$k,"ConvertFlow",NAME$k),_defineProperty(_CNameMapping$k,'Convert flow',NAME$k),_defineProperty(_CNameMapping$k,'convert flow',NAME$k),_defineProperty(_CNameMapping$k,'convert Flow',NAME$k),_defineProperty(_CNameMapping$k,'Convert Flow',NAME$k),_defineProperty(_CNameMapping$k,'CONVERT FLOW',NAME$k),_CNameMapping$k);
1459
+
1460
+ var _CNameMapping$j;var DIR_NAME$j='SnapEngage';var NAME$j='SNAPENGAGE';var DISPLAY_NAME$j='SnapEngage';var DISPLAY_NAME_TO_DIR_NAME_MAP$j=_defineProperty({},DISPLAY_NAME$j,DIR_NAME$j);var CNameMapping$j=(_CNameMapping$j={},_defineProperty(_CNameMapping$j,NAME$j,NAME$j),_defineProperty(_CNameMapping$j,"SnapEngage",NAME$j),_defineProperty(_CNameMapping$j,"Snap_Engage",NAME$j),_defineProperty(_CNameMapping$j,"snapengage",NAME$j),_defineProperty(_CNameMapping$j,'SNAP ENGAGE',NAME$j),_defineProperty(_CNameMapping$j,'Snap Engage',NAME$j),_defineProperty(_CNameMapping$j,'snap engage',NAME$j),_CNameMapping$j);
1461
+
1462
+ var _CNameMapping$i;var DIR_NAME$i='LiveChat';var NAME$i='LIVECHAT';var DISPLAY_NAME$i='LiveChat';var DISPLAY_NAME_TO_DIR_NAME_MAP$i=_defineProperty({},DISPLAY_NAME$i,DIR_NAME$i);var CNameMapping$i=(_CNameMapping$i={},_defineProperty(_CNameMapping$i,NAME$i,NAME$i),_defineProperty(_CNameMapping$i,"LiveChat",NAME$i),_defineProperty(_CNameMapping$i,"Live_Chat",NAME$i),_defineProperty(_CNameMapping$i,"livechat",NAME$i),_defineProperty(_CNameMapping$i,'LIVE CHAT',NAME$i),_defineProperty(_CNameMapping$i,'Live Chat',NAME$i),_defineProperty(_CNameMapping$i,'live chat',NAME$i),_CNameMapping$i);
1463
+
1464
+ var _CNameMapping$h;var DIR_NAME$h='Shynet';var NAME$h='SHYNET';var DISPLAY_NAME$h='Shynet';var DISPLAY_NAME_TO_DIR_NAME_MAP$h=_defineProperty({},DISPLAY_NAME$h,DIR_NAME$h);var CNameMapping$h=(_CNameMapping$h={},_defineProperty(_CNameMapping$h,NAME$h,NAME$h),_defineProperty(_CNameMapping$h,"shynet",NAME$h),_defineProperty(_CNameMapping$h,"ShyNet",NAME$h),_defineProperty(_CNameMapping$h,"shyNet",NAME$h),_defineProperty(_CNameMapping$h,"Shynet",NAME$h),_defineProperty(_CNameMapping$h,'shy net',NAME$h),_defineProperty(_CNameMapping$h,'Shy Net',NAME$h),_defineProperty(_CNameMapping$h,'shy Net',NAME$h),_defineProperty(_CNameMapping$h,'Shy net',NAME$h),_CNameMapping$h);
1465
+
1466
+ var _CNameMapping$g;var DIR_NAME$g='Woopra';var NAME$g='WOOPRA';var DISPLAY_NAME$g='Woopra';var DISPLAY_NAME_TO_DIR_NAME_MAP$g=_defineProperty({},DISPLAY_NAME$g,DIR_NAME$g);var CNameMapping$g=(_CNameMapping$g={},_defineProperty(_CNameMapping$g,NAME$g,NAME$g),_defineProperty(_CNameMapping$g,"Woopra",NAME$g),_defineProperty(_CNameMapping$g,"woopra",NAME$g),_CNameMapping$g);
1467
+
1468
+ var _CNameMapping$f;var DIR_NAME$f='RollBar';var NAME$f='ROLLBAR';var DISPLAY_NAME$f='RollBar';var DISPLAY_NAME_TO_DIR_NAME_MAP$f=_defineProperty({},DISPLAY_NAME$f,DIR_NAME$f);var CNameMapping$f=(_CNameMapping$f={},_defineProperty(_CNameMapping$f,NAME$f,NAME$f),_defineProperty(_CNameMapping$f,"RollBar",NAME$f),_defineProperty(_CNameMapping$f,"Roll_Bar",NAME$f),_defineProperty(_CNameMapping$f,"rollbar",NAME$f),_defineProperty(_CNameMapping$f,"Rollbar",NAME$f),_defineProperty(_CNameMapping$f,'ROLL BAR',NAME$f),_defineProperty(_CNameMapping$f,'Roll Bar',NAME$f),_defineProperty(_CNameMapping$f,'roll bar',NAME$f),_CNameMapping$f);
1469
+
1470
+ var _CNameMapping$e;var DIR_NAME$e='QuoraPixel';var NAME$e='QUORA_PIXEL';var DISPLAY_NAME$e='Quora Pixel';var DISPLAY_NAME_TO_DIR_NAME_MAP$e=_defineProperty({},DISPLAY_NAME$e,DIR_NAME$e);var CNameMapping$e=(_CNameMapping$e={},_defineProperty(_CNameMapping$e,NAME$e,NAME$e),_defineProperty(_CNameMapping$e,'Quora Pixel',NAME$e),_defineProperty(_CNameMapping$e,'Quora pixel',NAME$e),_defineProperty(_CNameMapping$e,'QUORA PIXEL',NAME$e),_defineProperty(_CNameMapping$e,"QuoraPixel",NAME$e),_defineProperty(_CNameMapping$e,"Quorapixel",NAME$e),_defineProperty(_CNameMapping$e,"QUORAPIXEL",NAME$e),_defineProperty(_CNameMapping$e,"Quora_Pixel",NAME$e),_defineProperty(_CNameMapping$e,"quora_pixel",NAME$e),_defineProperty(_CNameMapping$e,"Quora",NAME$e),_CNameMapping$e);
1471
+
1472
+ var _CNameMapping$d;var DIR_NAME$d='June';var NAME$d='JUNE';var DISPLAY_NAME$d='June';var DISPLAY_NAME_TO_DIR_NAME_MAP$d=_defineProperty({},DISPLAY_NAME$d,DIR_NAME$d);var CNameMapping$d=(_CNameMapping$d={},_defineProperty(_CNameMapping$d,NAME$d,NAME$d),_defineProperty(_CNameMapping$d,"June",NAME$d),_defineProperty(_CNameMapping$d,"june",NAME$d),_CNameMapping$d);
1473
+
1474
+ var _CNameMapping$c;var DIR_NAME$c='Engage';var NAME$c='ENGAGE';var DISPLAY_NAME$c='Engage';var DISPLAY_NAME_TO_DIR_NAME_MAP$c=_defineProperty({},DISPLAY_NAME$c,DIR_NAME$c);var CNameMapping$c=(_CNameMapping$c={},_defineProperty(_CNameMapping$c,NAME$c,NAME$c),_defineProperty(_CNameMapping$c,"Engage",NAME$c),_defineProperty(_CNameMapping$c,"engage",NAME$c),_CNameMapping$c);
1475
+
1476
+ var _CNameMapping$b;var DIR_NAME$b='Iterable';var NAME$b='ITERABLE';var DISPLAY_NAME$b='Iterable';var DISPLAY_NAME_TO_DIR_NAME_MAP$b=_defineProperty({},DISPLAY_NAME$b,DIR_NAME$b);var CNameMapping$b=(_CNameMapping$b={},_defineProperty(_CNameMapping$b,NAME$b,NAME$b),_defineProperty(_CNameMapping$b,"Iterable",NAME$b),_defineProperty(_CNameMapping$b,"iterable",NAME$b),_CNameMapping$b);
1477
+
1478
+ var _CNameMapping$a;var DIR_NAME$a='YandexMetrica';var NAME$a='YANDEX_METRICA';var DISPLAY_NAME$a='Yandex.Metrica';var DISPLAY_NAME_TO_DIR_NAME_MAP$a=_defineProperty({},DISPLAY_NAME$a,DIR_NAME$a);var CNameMapping$a=(_CNameMapping$a={},_defineProperty(_CNameMapping$a,NAME$a,NAME$a),_defineProperty(_CNameMapping$a,"Yandexmetrica",NAME$a),_defineProperty(_CNameMapping$a,"yandexmetrica",NAME$a),_defineProperty(_CNameMapping$a,"yandexMetrica",NAME$a),_defineProperty(_CNameMapping$a,"YandexMetrica",NAME$a),_CNameMapping$a);
1479
+
1480
+ var _CNameMapping$9;var DIR_NAME$9='Refiner';var NAME$9='REFINER';var DISPLAY_NAME$9='Refiner';var DISPLAY_NAME_TO_DIR_NAME_MAP$9=_defineProperty({},DISPLAY_NAME$9,DIR_NAME$9);var CNameMapping$9=(_CNameMapping$9={},_defineProperty(_CNameMapping$9,NAME$9,NAME$9),_defineProperty(_CNameMapping$9,"Refiner",NAME$9),_defineProperty(_CNameMapping$9,"refiner",NAME$9),_CNameMapping$9);
1481
+
1482
+ var _CNameMapping$8;var DIR_NAME$8='Qualaroo';var NAME$8='QUALAROO';var DISPLAY_NAME$8='Qualaroo';var DISPLAY_NAME_TO_DIR_NAME_MAP$8=_defineProperty({},DISPLAY_NAME$8,DIR_NAME$8);var CNameMapping$8=(_CNameMapping$8={},_defineProperty(_CNameMapping$8,NAME$8,NAME$8),_defineProperty(_CNameMapping$8,"Qualaroo",NAME$8),_defineProperty(_CNameMapping$8,"qualaroo",NAME$8),_CNameMapping$8);
1483
+
1484
+ var _CNameMapping$7;var DIR_NAME$7='Podsights';var NAME$7='PODSIGHTS';var DISPLAY_NAME$7='Podsights';var DISPLAY_NAME_TO_DIR_NAME_MAP$7=_defineProperty({},DISPLAY_NAME$7,DIR_NAME$7);var CNameMapping$7=(_CNameMapping$7={},_defineProperty(_CNameMapping$7,NAME$7,NAME$7),_defineProperty(_CNameMapping$7,"Podsights",NAME$7),_defineProperty(_CNameMapping$7,"PodSights",NAME$7),_defineProperty(_CNameMapping$7,'pod Sights',NAME$7),_defineProperty(_CNameMapping$7,'Pod Sights',NAME$7),_defineProperty(_CNameMapping$7,'pod sights',NAME$7),_defineProperty(_CNameMapping$7,'POD SIGHTS',NAME$7),_defineProperty(_CNameMapping$7,'Pod sights',NAME$7),_CNameMapping$7);// default mapping for the events
1485
+
1486
+ var _CNameMapping$6;var DIR_NAME$6='Axeptio';var NAME$6='AXEPTIO';var DISPLAY_NAME$6='Axeptio';var DISPLAY_NAME_TO_DIR_NAME_MAP$6=_defineProperty({},DISPLAY_NAME$6,DIR_NAME$6);var CNameMapping$6=(_CNameMapping$6={},_defineProperty(_CNameMapping$6,NAME$6,NAME$6),_defineProperty(_CNameMapping$6,"Axeptio",NAME$6),_defineProperty(_CNameMapping$6,"axeptio",NAME$6),_CNameMapping$6);
1487
+
1488
+ var _CNameMapping$5;var DIR_NAME$5='Satismeter';var NAME$5='SATISMETER';var DISPLAY_NAME$5='Satismeter';var DISPLAY_NAME_TO_DIR_NAME_MAP$5=_defineProperty({},DISPLAY_NAME$5,DIR_NAME$5);var CNameMapping$5=(_CNameMapping$5={},_defineProperty(_CNameMapping$5,NAME$5,NAME$5),_defineProperty(_CNameMapping$5,"Satismeter",NAME$5),_defineProperty(_CNameMapping$5,"SatisMeter",NAME$5),_CNameMapping$5);
1489
+
1490
+ var _CNameMapping$4;var DIR_NAME$4='MicrosoftClarity';var NAME$4='MICROSOFT_CLARITY';var DISPLAY_NAME$4='Microsoft Clarity';var DISPLAY_NAME_TO_DIR_NAME_MAP$4=_defineProperty({},DISPLAY_NAME$4,DIR_NAME$4);var CNameMapping$4=(_CNameMapping$4={},_defineProperty(_CNameMapping$4,NAME$4,NAME$4),_defineProperty(_CNameMapping$4,'Microsoft Clarity',NAME$4),_defineProperty(_CNameMapping$4,'Microsoft clarity',NAME$4),_defineProperty(_CNameMapping$4,'microsoft clarity',NAME$4),_defineProperty(_CNameMapping$4,"Microsoft_clarity",NAME$4),_defineProperty(_CNameMapping$4,"MicrosoftClarity",NAME$4),_defineProperty(_CNameMapping$4,"MICROSOFTCLARITY",NAME$4),_defineProperty(_CNameMapping$4,"microsoftclarity",NAME$4),_defineProperty(_CNameMapping$4,"microsoftClarity",NAME$4),_CNameMapping$4);
1491
+
1492
+ var _CNameMapping$3;var DIR_NAME$3='Sendinblue';var NAME$3='SENDINBLUE';var DISPLAY_NAME$3='Sendinblue';var DISPLAY_NAME_TO_DIR_NAME_MAP$3=_defineProperty({},DISPLAY_NAME$3,DIR_NAME$3);var CNameMapping$3=(_CNameMapping$3={},_defineProperty(_CNameMapping$3,NAME$3,NAME$3),_defineProperty(_CNameMapping$3,"Sendinblue",NAME$3),_defineProperty(_CNameMapping$3,"sendinblue",NAME$3),_defineProperty(_CNameMapping$3,"SendinBlue",NAME$3),_CNameMapping$3);
1493
+
1494
+ var _CNameMapping$2;var DIR_NAME$2='Olark';var NAME$2='OLARK';var DISPLAY_NAME$2='Olark';var DISPLAY_NAME_TO_DIR_NAME_MAP$2=_defineProperty({},DISPLAY_NAME$2,DIR_NAME$2);var CNameMapping$2=(_CNameMapping$2={},_defineProperty(_CNameMapping$2,NAME$2,NAME$2),_defineProperty(_CNameMapping$2,"Olark",NAME$2),_defineProperty(_CNameMapping$2,"olark",NAME$2),_CNameMapping$2);
1495
+
1496
+ var _CNameMapping$1;var DIR_NAME$1='Lemnisk';var NAME$1='LEMNISK';var DISPLAY_NAME$1='Lemnisk';var DISPLAY_NAME_TO_DIR_NAME_MAP$1=_defineProperty({},DISPLAY_NAME$1,DIR_NAME$1);var CNameMapping$1=(_CNameMapping$1={},_defineProperty(_CNameMapping$1,NAME$1,NAME$1),_defineProperty(_CNameMapping$1,"LEMNISK_MARKETING_AUTOMATION",NAME$1),_defineProperty(_CNameMapping$1,'Lemnisk Marketing Automation',NAME$1),_defineProperty(_CNameMapping$1,"LemniskMarketingAutomation",NAME$1),_defineProperty(_CNameMapping$1,"lemniskmarketingautomation",NAME$1),_defineProperty(_CNameMapping$1,"lemniskMarketingAutomation",NAME$1),_defineProperty(_CNameMapping$1,"lemnisk",NAME$1),_defineProperty(_CNameMapping$1,"Lemnisk",NAME$1),_CNameMapping$1);
1497
+
1498
+ var _CNameMapping;var DIR_NAME='TiktokAds';var NAME='TIKTOK_ADS';var DISPLAY_NAME='TikTok Ads';var DISPLAY_NAME_TO_DIR_NAME_MAP=_defineProperty({},DISPLAY_NAME,DIR_NAME);var CNameMapping=(_CNameMapping={},_defineProperty(_CNameMapping,NAME,NAME),_defineProperty(_CNameMapping,"TiktokAds",NAME),_defineProperty(_CNameMapping,'Tiktok ads',NAME),_defineProperty(_CNameMapping,'Tiktok Ads',NAME),_defineProperty(_CNameMapping,'Tik Tok Ads',NAME),_defineProperty(_CNameMapping,'tik tok ads',NAME),_defineProperty(_CNameMapping,"tiktokads",NAME),_CNameMapping);
1499
+
1500
+ var destDisplayNamesToFileNamesMap=_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({},DISPLAY_NAME_TO_DIR_NAME_MAP$P),DISPLAY_NAME_TO_DIR_NAME_MAP$W),DISPLAY_NAME_TO_DIR_NAME_MAP$Q),DISPLAY_NAME_TO_DIR_NAME_MAP$U),DISPLAY_NAME_TO_DIR_NAME_MAP$s),DISPLAY_NAME_TO_DIR_NAME_MAP$S),DISPLAY_NAME_TO_DIR_NAME_MAP$14),DISPLAY_NAME_TO_DIR_NAME_MAP$O),DISPLAY_NAME_TO_DIR_NAME_MAP$N),DISPLAY_NAME_TO_DIR_NAME_MAP$M),DISPLAY_NAME_TO_DIR_NAME_MAP$_),DISPLAY_NAME_TO_DIR_NAME_MAP$12),DISPLAY_NAME_TO_DIR_NAME_MAP$10),DISPLAY_NAME_TO_DIR_NAME_MAP$Y),DISPLAY_NAME_TO_DIR_NAME_MAP$I),DISPLAY_NAME_TO_DIR_NAME_MAP$E),DISPLAY_NAME_TO_DIR_NAME_MAP$13),DISPLAY_NAME_TO_DIR_NAME_MAP$X),DISPLAY_NAME_TO_DIR_NAME_MAP$t),DISPLAY_NAME_TO_DIR_NAME_MAP$V),DISPLAY_NAME_TO_DIR_NAME_MAP$F),DISPLAY_NAME_TO_DIR_NAME_MAP$17),DISPLAY_NAME_TO_DIR_NAME_MAP$D),DISPLAY_NAME_TO_DIR_NAME_MAP$H),DISPLAY_NAME_TO_DIR_NAME_MAP$16),DISPLAY_NAME_TO_DIR_NAME_MAP$A),DISPLAY_NAME_TO_DIR_NAME_MAP$L),DISPLAY_NAME_TO_DIR_NAME_MAP$11),DISPLAY_NAME_TO_DIR_NAME_MAP$15),DISPLAY_NAME_TO_DIR_NAME_MAP$C),DISPLAY_NAME_TO_DIR_NAME_MAP$18),DISPLAY_NAME_TO_DIR_NAME_MAP$J),DISPLAY_NAME_TO_DIR_NAME_MAP$w),DISPLAY_NAME_TO_DIR_NAME_MAP$Z),DISPLAY_NAME_TO_DIR_NAME_MAP$R),DISPLAY_NAME_TO_DIR_NAME_MAP$$),DISPLAY_NAME_TO_DIR_NAME_MAP$G),DISPLAY_NAME_TO_DIR_NAME_MAP$y),DISPLAY_NAME_TO_DIR_NAME_MAP$z),DISPLAY_NAME_TO_DIR_NAME_MAP$v),DISPLAY_NAME_TO_DIR_NAME_MAP$x),DISPLAY_NAME_TO_DIR_NAME_MAP$u),DISPLAY_NAME_TO_DIR_NAME_MAP$B),DISPLAY_NAME_TO_DIR_NAME_MAP$T),DISPLAY_NAME_TO_DIR_NAME_MAP$K),DISPLAY_NAME_TO_DIR_NAME_MAP$r),DISPLAY_NAME_TO_DIR_NAME_MAP$q),DISPLAY_NAME_TO_DIR_NAME_MAP$p),DISPLAY_NAME_TO_DIR_NAME_MAP$o),DISPLAY_NAME_TO_DIR_NAME_MAP$n),DISPLAY_NAME_TO_DIR_NAME_MAP$m),DISPLAY_NAME_TO_DIR_NAME_MAP$l),DISPLAY_NAME_TO_DIR_NAME_MAP$k),DISPLAY_NAME_TO_DIR_NAME_MAP$j),DISPLAY_NAME_TO_DIR_NAME_MAP$i),DISPLAY_NAME_TO_DIR_NAME_MAP$h),DISPLAY_NAME_TO_DIR_NAME_MAP$g),DISPLAY_NAME_TO_DIR_NAME_MAP$f),DISPLAY_NAME_TO_DIR_NAME_MAP$e),DISPLAY_NAME_TO_DIR_NAME_MAP$d),DISPLAY_NAME_TO_DIR_NAME_MAP$c),DISPLAY_NAME_TO_DIR_NAME_MAP$b),DISPLAY_NAME_TO_DIR_NAME_MAP$a),DISPLAY_NAME_TO_DIR_NAME_MAP$9),DISPLAY_NAME_TO_DIR_NAME_MAP$8),DISPLAY_NAME_TO_DIR_NAME_MAP$7),DISPLAY_NAME_TO_DIR_NAME_MAP$6),DISPLAY_NAME_TO_DIR_NAME_MAP$5),DISPLAY_NAME_TO_DIR_NAME_MAP$4),DISPLAY_NAME_TO_DIR_NAME_MAP$3),DISPLAY_NAME_TO_DIR_NAME_MAP$2),DISPLAY_NAME_TO_DIR_NAME_MAP$1),DISPLAY_NAME_TO_DIR_NAME_MAP);
1501
+
1502
+ var BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME='bugsnag';// For version 6 and below
1503
+ var BUGSNAG_LIB_V7_INSTANCE_GLOBAL_KEY_NAME='Bugsnag';var GLOBAL_LIBRARY_OBJECT_NAMES=[BUGSNAG_LIB_V7_INSTANCE_GLOBAL_KEY_NAME,BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME];var BUGSNAG_CDN_URL='https://d2wy8f7a9ursnm.cloudfront.net/v6/bugsnag.min.js';var ERROR_REPORT_PROVIDER_NAME_BUGSNAG='rs-bugsnag';// This API key token is parsed in the CI pipeline
1504
+ var API_KEY='0d96a60df267f4a13f808bbaa54e535c';var BUGSNAG_VALID_MAJOR_VERSION='6';var SDK_LOAD_POLL_INTERVAL_MS=100;// ms
1505
+ var MAX_WAIT_FOR_SDK_LOAD_MS=100*SDK_LOAD_POLL_INTERVAL_MS;// ms
1506
+ // Errors from the below scripts are NOT allowed to reach Bugsnag
1507
+ var SDK_FILE_NAME_PREFIXES=function SDK_FILE_NAME_PREFIXES(){return ['rsa'].concat(_toConsumableArray(Object.values(destDisplayNamesToFileNamesMap)));};var DEV_HOSTS=['www.test-host.com','localhost','127.0.0.1','[::1]'];// List of keys to exclude from the metadata
1508
+ // Potential PII or sensitive data
1509
+ var APP_STATE_EXCLUDE_KEYS=['userId','userTraits','groupId','groupTraits','anonymousId','config','instance',// destination instance objects
1510
+ 'anonymousUserId','eventBuffer',// pre-load event buffer (may contain PII)
1511
+ 'traits'];var BUGSNAG_PLUGIN='BugsnagPlugin';
1512
+
1513
+ var isValidVersion=function isValidVersion(globalLibInstance){var _globalLibInstance$_c;// For version 7
1514
+ // eslint-disable-next-line no-underscore-dangle
1515
+ var version=globalLibInstance===null||globalLibInstance===void 0||(_globalLibInstance$_c=globalLibInstance._client)===null||_globalLibInstance$_c===void 0||(_globalLibInstance$_c=_globalLibInstance$_c._notifier)===null||_globalLibInstance$_c===void 0?void 0:_globalLibInstance$_c.version;// For versions older than 7
1516
+ if(!version){var _tempInstance$notifie;var tempInstance=globalLibInstance({apiKey:API_KEY,releaseStage:'version-test',// eslint-disable-next-line func-names, object-shorthand
1517
+ beforeSend:function beforeSend(){return false;}});version=(_tempInstance$notifie=tempInstance.notifier)===null||_tempInstance$notifie===void 0?void 0:_tempInstance$notifie.version;}return version&&version.charAt(0)===BUGSNAG_VALID_MAJOR_VERSION;};var isRudderSDKError=function isRudderSDKError(event){var _event$stacktrace;var errorOrigin=(_event$stacktrace=event.stacktrace)===null||_event$stacktrace===void 0||(_event$stacktrace=_event$stacktrace[0])===null||_event$stacktrace===void 0?void 0:_event$stacktrace.file;if(!errorOrigin||typeof errorOrigin!=='string'){return false;}var srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);return SDK_FILE_NAME_PREFIXES().some(function(prefix){return srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js');});};var enhanceErrorEventMutator=function enhanceErrorEventMutator(event,metadataSource){event.updateMetaData('source',{metadataSource:metadataSource});var errorMessage=event.errorMessage;// eslint-disable-next-line no-param-reassign
1518
+ event.context=errorMessage;// Hack for easily grouping the script load errors
1519
+ // on the dashboard
1520
+ if(errorMessage.includes('error in script loading')){// eslint-disable-next-line no-param-reassign
1521
+ event.context='Script load failures';}// eslint-disable-next-line no-param-reassign
1522
+ event.severity='error';};var onError=function onError(state){var _state$source$value;var metadataSource=(_state$source$value=state.source.value)===null||_state$source$value===void 0?void 0:_state$source$value.id;return function(event){try{// Discard the event if it's not originated at the SDK
1523
+ if(!isRudderSDKError(event)){return false;}enhanceErrorEventMutator(event,metadataSource);return true;}catch(_unused){// Drop the error event if it couldn't be filtered as
1524
+ // it is most likely a non-SDK error
1525
+ return false;}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'development';};var getGlobalBugsnagLibInstance=function getGlobalBugsnagLibInstance(){return globalThis[BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME];};var getNewClient=function getNewClient(state,logger){var globalBugsnagLibInstance=getGlobalBugsnagLibInstance();var clientConfig={apiKey:API_KEY,appVersion:'3.0.0-beta.1',// Set SDK version as the app version from build config
1526
+ metaData:{SDK:{name:'JS',installType:'npm'}},beforeSend:onError(state),autoCaptureSessions:false,// auto capture sessions is disabled
1527
+ collectUserIp:false,// collecting user's IP is disabled
1528
+ // enabledBreadcrumbTypes: ['error', 'log', 'user'], // for v7 and above
1529
+ maxEvents:100,maxBreadcrumbs:40,releaseStage:getReleaseStage(),user:{id:state.lifecycle.writeKey.value},logger:logger};var client=globalBugsnagLibInstance(clientConfig);return client;};var isApiKeyValid=function isApiKeyValid(apiKey){var isAPIKeyValid=!(apiKey.startsWith('{{')||apiKey.endsWith('}}')||apiKey.length===0);return isAPIKeyValid;};var loadBugsnagSDK=function loadBugsnagSDK(externalSrcLoader,logger){var isNotLoaded=GLOBAL_LIBRARY_OBJECT_NAMES.every(function(globalKeyName){return !globalThis[globalKeyName];});if(!isNotLoaded){return;}externalSrcLoader.loadJSFile({url:BUGSNAG_CDN_URL,id:ERROR_REPORT_PROVIDER_NAME_BUGSNAG,callback:function callback(id){if(!id){logger===null||logger===void 0?void 0:logger.error(BUGSNAG_SDK_LOAD_ERROR(BUGSNAG_PLUGIN));}}});};var initBugsnagClient=function initBugsnagClient(state,promiseResolve,promiseReject,logger){var time=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0;var globalBugsnagLibInstance=getGlobalBugsnagLibInstance();if(typeof globalBugsnagLibInstance==='function'){if(isValidVersion(globalBugsnagLibInstance)){var client=getNewClient(state,logger);promiseResolve(client);}}else if(time>=MAX_WAIT_FOR_SDK_LOAD_MS){promiseReject(new Error(BUGSNAG_SDK_LOAD_TIMEOUT_ERROR(MAX_WAIT_FOR_SDK_LOAD_MS)));}else {// Try to initialize the client after a delay
1530
+ setTimeout(initBugsnagClient,SDK_LOAD_POLL_INTERVAL_MS,state,promiseResolve,promiseReject,logger,time+SDK_LOAD_POLL_INTERVAL_MS);}};var getAppStateForMetadata=function getAppStateForMetadata(state){var stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS);return stateStr!==null?JSON.parse(stateStr):undefined;};
1531
+
1532
+ var pluginName$c='Bugsnag';var Bugsnag=function Bugsnag(){return {name:pluginName$c,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$c]);},errorReportingProvider:{init:function init(state,externalSrcLoader,logger){return new Promise(function(resolve,reject){// If API key token is not parsed or invalid, don't proceed to initialize the client
1533
+ if(!isApiKeyValid(API_KEY)){reject(new Error(BUGSNAG_API_KEY_VALIDATION_ERROR(API_KEY)));return;}loadBugsnagSDK(externalSrcLoader,logger);initBugsnagClient(state,resolve,reject,logger);});},notify:function notify(client,error,state,logger){client===null||client===void 0?void 0:client.notify(error,{metaData:{state:getAppStateForMetadata(state)}});},breadcrumb:function breadcrumb(client,message,logger){client===null||client===void 0?void 0:client.leaveBreadcrumb(message);}}};};
1534
+
1535
+ var replaceValuesWithDisplayName=function replaceValuesWithDisplayName(CNameMapping,displayName){var updatedCNameMapping={};Object.keys(CNameMapping).forEach(function(key){updatedCNameMapping[key]=displayName;});return updatedCNameMapping;};// As the common names mapping in v1.1 is mapped to the definition name
1536
+ // we're converting the definition name to display names temporarily
1537
+ var destCNamesToDisplayNamesMap=_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({},replaceValuesWithDisplayName(CNameMapping$18,DISPLAY_NAME$18)),replaceValuesWithDisplayName(CNameMapping$17,DISPLAY_NAME$17)),replaceValuesWithDisplayName(CNameMapping$16,DISPLAY_NAME$16)),replaceValuesWithDisplayName(CNameMapping$15,DISPLAY_NAME$15)),replaceValuesWithDisplayName(CNameMapping$14,DISPLAY_NAME$14)),replaceValuesWithDisplayName(CNameMapping$13,DISPLAY_NAME$13)),replaceValuesWithDisplayName(CNameMapping$12,DISPLAY_NAME$12)),replaceValuesWithDisplayName(CNameMapping$11,DISPLAY_NAME$11)),replaceValuesWithDisplayName(CNameMapping$10,DISPLAY_NAME$10)),replaceValuesWithDisplayName(CNameMapping$$,DISPLAY_NAME$$)),replaceValuesWithDisplayName(CNameMapping$_,DISPLAY_NAME$_)),replaceValuesWithDisplayName(CNameMapping$Z,DISPLAY_NAME$Z)),replaceValuesWithDisplayName(CNameMapping$Y,DISPLAY_NAME$Y)),replaceValuesWithDisplayName(CNameMapping$X,DISPLAY_NAME$X)),replaceValuesWithDisplayName(CNameMapping$W,DISPLAY_NAME$W)),replaceValuesWithDisplayName(CNameMapping$V,DISPLAY_NAME$V)),replaceValuesWithDisplayName(CNameMapping$r,DISPLAY_NAME$r)),replaceValuesWithDisplayName(CNameMapping$U,DISPLAY_NAME$U)),replaceValuesWithDisplayName(CNameMapping$T,DISPLAY_NAME$T)),replaceValuesWithDisplayName(CNameMapping$S,DISPLAY_NAME$S)),replaceValuesWithDisplayName(CNameMapping$R,DISPLAY_NAME$R)),replaceValuesWithDisplayName(CNameMapping$Q,DISPLAY_NAME$Q)),replaceValuesWithDisplayName(CNameMapping$P,DISPLAY_NAME$P)),replaceValuesWithDisplayName(CNameMapping$O,DISPLAY_NAME$O)),replaceValuesWithDisplayName(CNameMapping$N,DISPLAY_NAME$N)),replaceValuesWithDisplayName(CNameMapping$M,DISPLAY_NAME$M)),replaceValuesWithDisplayName(CNameMapping$L,DISPLAY_NAME$L)),replaceValuesWithDisplayName(CNameMapping$K,DISPLAY_NAME$K)),replaceValuesWithDisplayName(CNameMapping$J,DISPLAY_NAME$J)),replaceValuesWithDisplayName(CNameMapping$I,DISPLAY_NAME$I)),replaceValuesWithDisplayName(CNameMapping$H,DISPLAY_NAME$H)),replaceValuesWithDisplayName(CNameMapping$G,DISPLAY_NAME$G)),replaceValuesWithDisplayName(CNameMapping$F,DISPLAY_NAME$F)),replaceValuesWithDisplayName(CNameMapping$E,DISPLAY_NAME$E)),replaceValuesWithDisplayName(CNameMapping$D,DISPLAY_NAME$D)),replaceValuesWithDisplayName(CNameMapping$C,DISPLAY_NAME$C)),replaceValuesWithDisplayName(CNameMapping$B,DISPLAY_NAME$B)),replaceValuesWithDisplayName(CNameMapping$A,DISPLAY_NAME$A)),replaceValuesWithDisplayName(CNameMapping$z,DISPLAY_NAME$z)),replaceValuesWithDisplayName(CNameMapping$y,DISPLAY_NAME$y)),replaceValuesWithDisplayName(CNameMapping$x,DISPLAY_NAME$x)),replaceValuesWithDisplayName(CNameMapping$w,DISPLAY_NAME$w)),replaceValuesWithDisplayName(CNameMapping$v,DISPLAY_NAME$v)),replaceValuesWithDisplayName(CNameMapping$u,DISPLAY_NAME$u)),replaceValuesWithDisplayName(CNameMapping$t,DISPLAY_NAME$t)),replaceValuesWithDisplayName(CNameMapping$s,DISPLAY_NAME$s)),replaceValuesWithDisplayName(CNameMapping$q,DISPLAY_NAME$q)),replaceValuesWithDisplayName(CNameMapping$p,DISPLAY_NAME$p)),replaceValuesWithDisplayName(CNameMapping$o,DISPLAY_NAME$o)),replaceValuesWithDisplayName(CNameMapping$n,DISPLAY_NAME$n)),replaceValuesWithDisplayName(CNameMapping$m,DISPLAY_NAME$m)),replaceValuesWithDisplayName(CNameMapping$k,DISPLAY_NAME$k)),replaceValuesWithDisplayName(CNameMapping$j,DISPLAY_NAME$j)),replaceValuesWithDisplayName(CNameMapping$i,DISPLAY_NAME$i)),replaceValuesWithDisplayName(CNameMapping$h,DISPLAY_NAME$h)),replaceValuesWithDisplayName(CNameMapping$g,DISPLAY_NAME$g)),replaceValuesWithDisplayName(CNameMapping$f,DISPLAY_NAME$f)),replaceValuesWithDisplayName(CNameMapping$e,DISPLAY_NAME$e)),replaceValuesWithDisplayName(CNameMapping$d,DISPLAY_NAME$d)),replaceValuesWithDisplayName(CNameMapping$c,DISPLAY_NAME$c)),replaceValuesWithDisplayName(CNameMapping$b,DISPLAY_NAME$b)),replaceValuesWithDisplayName(CNameMapping$l,DISPLAY_NAME$l)),replaceValuesWithDisplayName(CNameMapping$a,DISPLAY_NAME$a)),replaceValuesWithDisplayName(CNameMapping$9,DISPLAY_NAME$9)),replaceValuesWithDisplayName(CNameMapping$8,DISPLAY_NAME$8)),replaceValuesWithDisplayName(CNameMapping$7,DISPLAY_NAME$7)),replaceValuesWithDisplayName(CNameMapping$6,DISPLAY_NAME$6)),replaceValuesWithDisplayName(CNameMapping$5,DISPLAY_NAME$5)),replaceValuesWithDisplayName(CNameMapping$4,DISPLAY_NAME$4)),replaceValuesWithDisplayName(CNameMapping$3,DISPLAY_NAME$3)),replaceValuesWithDisplayName(CNameMapping$2,DISPLAY_NAME$2)),replaceValuesWithDisplayName(CNameMapping$1,DISPLAY_NAME$1)),replaceValuesWithDisplayName(CNameMapping,DISPLAY_NAME));
1538
+
1539
+ var LOAD_CHECK_POLL_INTERVAL=1000;var LOAD_CHECK_TIMEOUT=10*LOAD_CHECK_POLL_INTERVAL;var INITIALIZED_CHECK_POLL_INTERVAL=100;var INITIALIZED_CHECK_TIMEOUT=11*10*INITIALIZED_CHECK_POLL_INTERVAL;var DEVICE_MODE_DESTINATIONS_PLUGIN='DeviceModeDestinationsPlugin';
1540
+
1541
+ /**
1542
+ * Determines if the destination SDK code is evaluated
1543
+ * @param destSDKIdentifier The name of the global globalThis object that contains the destination SDK
1544
+ * @param sdkTypeName The name of the destination SDK type
1545
+ * @param logger Logger instance
1546
+ * @returns true if the destination SDK code is evaluated, false otherwise
1547
+ */var isDestinationSDKEvaluated=function isDestinationSDKEvaluated(destSDKIdentifier,sdkTypeName,logger){return Boolean(globalThis[destSDKIdentifier]&&globalThis[destSDKIdentifier][sdkTypeName]&&globalThis[destSDKIdentifier][sdkTypeName].prototype&&typeof globalThis[destSDKIdentifier][sdkTypeName].prototype.constructor!=='undefined');};var wait=function wait(time){return new Promise(function(resolve){globalThis.setTimeout(resolve,time);});};var createDestinationInstance=function createDestinationInstance(destSDKIdentifier,sdkTypeName,dest,state,logger){var rAnalytics=globalThis.rudderanalytics;var analytics=rAnalytics.getAnalyticsInstance(state.lifecycle.writeKey.value);return new globalThis[destSDKIdentifier][sdkTypeName](clone$1(dest.config),{loadIntegration:state.nativeDestinations.loadIntegration.value,logLevel:state.lifecycle.logLevel.value,loadOnlyIntegrations:state.nativeDestinations.loadOnlyIntegrations.value,page:function page(category,name,properties,options,callback){return analytics.page(pageArgumentsToCallOptions(category,name,properties,options,callback));},track:function track(event,properties,options,callback){return analytics.track(trackArgumentsToCallOptions(event,properties,options,callback));},identify:function identify(userId,traits,options,callback){return analytics.identify(identifyArgumentsToCallOptions(userId,traits,options,callback));},alias:function alias(to,from,options,callback){return analytics.alias(aliasArgumentsToCallOptions(to,from,options,callback));},group:function group(groupId,traits,options,callback){return analytics.group(groupArgumentsToCallOptions(groupId,traits,options,callback));},getAnonymousId:function getAnonymousId(){return analytics.getAnonymousId();},getUserId:function getUserId(){return analytics.getUserId();},getUserTraits:function getUserTraits(){return analytics.getUserTraits();},getGroupId:function getGroupId(){return analytics.getGroupId();},getGroupTraits:function getGroupTraits(){return analytics.getGroupTraits();},getSessionId:function getSessionId(){return analytics.getSessionId();}},{shouldApplyDeviceModeTransformation:dest.shouldApplyDeviceModeTransformation,propagateEventsUntransformedOnError:dest.propagateEventsUntransformedOnError,destinationId:dest.id});};var isDestinationReady=function isDestinationReady(dest,logger){var time=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;return new Promise(function(resolve,reject){var instance=dest.instance;if(instance.isLoaded()&&(!instance.isReady||instance.isReady())){resolve(true);}else if(time>=INITIALIZED_CHECK_TIMEOUT){reject(new Error(DESTINATION_READY_TIMEOUT_ERROR(INITIALIZED_CHECK_TIMEOUT,dest.userFriendlyId)));}else {wait(LOAD_CHECK_POLL_INTERVAL).then(function(){return isDestinationReady(dest,logger,time+LOAD_CHECK_POLL_INTERVAL).then(resolve).catch(function(err){return reject(err);});}).catch(function(err){return reject(err);});}});};/**
1548
+ * Converts the common names of the destinations to their display names
1549
+ * @param intgOptions Load or API integration options
1550
+ */var normalizeIntegrationOptions=function normalizeIntegrationOptions(intgOptions){var normalizedIntegrationOptions={};if(intgOptions){Object.keys(intgOptions).forEach(function(key){var destOpts=clone$1(intgOptions[key]);if(key==='All'){normalizedIntegrationOptions[key]=Boolean(destOpts);}else {var displayName=destCNamesToDisplayNamesMap[key];if(displayName){normalizedIntegrationOptions[displayName]=destOpts;}else {normalizedIntegrationOptions[key]=destOpts;}}});}if(isUndefined(normalizedIntegrationOptions.All)){normalizedIntegrationOptions.All=true;}return normalizedIntegrationOptions;};/**
1551
+ * Filters the destinations that should not be loaded or forwarded events to based on the integration options (load or events API)
1552
+ * @param intgOpts Integration options object
1553
+ * @param destinations Destinations array
1554
+ * @returns Destinations array filtered based on the integration options
1555
+ */var filterDestinations=function filterDestinations(intgOpts,destinations){var allOptVal=intgOpts.All;return destinations.filter(function(dest){var dispName=dest.displayName;var isDestEnabled;if(allOptVal){isDestEnabled=true;if(isDestIntgConfigFalsy(intgOpts[dispName])){isDestEnabled=false;}}else {isDestEnabled=false;if(isDestIntgConfigTruthy(intgOpts[dispName])){isDestEnabled=true;}}return isDestEnabled;});};/**
1556
+ * Extracts the integration config, if any, from the given destination
1557
+ * and merges it with the current integrations config
1558
+ * @param dest Destination object
1559
+ * @param curDestIntgConfig Current destinations integration config
1560
+ * @param logger Logger object
1561
+ * @returns Combined destinations integrations config
1562
+ */var getCumulativeIntegrationsConfig=function getCumulativeIntegrationsConfig(dest,curDestIntgConfig,logger){var _dest$instance;var integrationsConfig=curDestIntgConfig;if(isFunction((_dest$instance=dest.instance)===null||_dest$instance===void 0?void 0:_dest$instance.getDataForIntegrationsObject)){try{var _dest$instance2;integrationsConfig=mergeDeepRight(curDestIntgConfig,(_dest$instance2=dest.instance)===null||_dest$instance2===void 0?void 0:_dest$instance2.getDataForIntegrationsObject());}catch(err){logger===null||logger===void 0?void 0:logger.error(DESTINATION_INTEGRATIONS_DATA_ERROR(DEVICE_MODE_DESTINATIONS_PLUGIN,dest.userFriendlyId),err);}}return integrationsConfig;};
1563
+
1564
+ var pluginName$b='DeviceModeDestinations';var DeviceModeDestinations=function DeviceModeDestinations(){return {name:pluginName$b,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$b]);},nativeDestinations:{setActiveDestinations:function setActiveDestinations(state,pluginsManager,logger){// Normalize the integration options from the load API call
1565
+ state.nativeDestinations.loadOnlyIntegrations.value=normalizeIntegrationOptions(state.loadOptions.value.integrations);// Filter destination that doesn't have mapping config-->Integration names
1566
+ var configSupportedDestinations=state.nativeDestinations.configuredDestinations.value.filter(function(configDest){if(destDisplayNamesToFileNamesMap[configDest.displayName]){return true;}logger===null||logger===void 0?void 0:logger.error(DESTINATION_NOT_SUPPORTED_ERROR(DEVICE_MODE_DESTINATIONS_PLUGIN,configDest.userFriendlyId));return false;});// Filter destinations that are disabled through load options
1567
+ var destinationsToLoad=filterDestinations(state.nativeDestinations.loadOnlyIntegrations.value,configSupportedDestinations);var consentedDestinations=destinationsToLoad.filter(function(dest){var _pluginsManager$invok;return(// if consent manager is not configured, then default to load the destination
1568
+ (_pluginsManager$invok=pluginsManager.invokeSingle("consentManager.isDestinationConsented",state,dest.config,logger))!==null&&_pluginsManager$invok!==void 0?_pluginsManager$invok:true);});state.nativeDestinations.activeDestinations.value=consentedDestinations;},load:function load(state,externalSrcLoader,logger,externalScriptOnLoad){var integrationsCDNPath=state.lifecycle.integrationsCDNPath.value;var activeDestinations=state.nativeDestinations.activeDestinations.value;activeDestinations.forEach(function(dest){var sdkName=destDisplayNamesToFileNamesMap[dest.displayName];var destSDKIdentifier="".concat(sdkName,"_RS");// this is the name of the object loaded on the window
1569
+ var timeoutId;var intervalId;if(!isDestinationSDKEvaluated(destSDKIdentifier,sdkName)){var destSdkURL="".concat(integrationsCDNPath,"/").concat(sdkName,".min.js");externalSrcLoader.loadJSFile({url:destSdkURL,id:dest.userFriendlyId,callback:externalScriptOnLoad!==null&&externalScriptOnLoad!==void 0?externalScriptOnLoad:function(id){if(!id){// Stop wasting time to check whether SDK is loaded
1570
+ globalThis.clearInterval(intervalId);globalThis.clearTimeout(timeoutId);logger===null||logger===void 0?void 0:logger.error(DESTINATION_SDK_LOAD_ERROR(DEVICE_MODE_DESTINATIONS_PLUGIN,dest.userFriendlyId));state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);}}});}intervalId=globalThis.setInterval(function(){var sdkTypeName=sdkName;if(isDestinationSDKEvaluated(destSDKIdentifier,sdkTypeName)){globalThis.clearInterval(intervalId);globalThis.clearTimeout(timeoutId);try{var destInstance=createDestinationInstance(destSDKIdentifier,sdkTypeName,dest,state,logger);destInstance.init();var initializedDestination=clone$1(dest);initializedDestination.instance=destInstance;isDestinationReady(initializedDestination,logger).then(function(){// Collect the integrations data for the hybrid mode destinations
1571
+ if(isHybridModeDestination(initializedDestination)){state.nativeDestinations.integrationsConfig.value=getCumulativeIntegrationsConfig(initializedDestination,state.nativeDestinations.integrationsConfig.value,logger);}state.nativeDestinations.initializedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.initializedDestinations.value),[initializedDestination]);}).catch(function(err){// The error message is already formatted in the isDestinationReady function
1572
+ logger===null||logger===void 0?void 0:logger.error(err);state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);});}catch(err){logger===null||logger===void 0?void 0:logger.error(DESTINATION_INIT_ERROR(DEVICE_MODE_DESTINATIONS_PLUGIN,dest.userFriendlyId),err);state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);}}},INITIALIZED_CHECK_POLL_INTERVAL);timeoutId=globalThis.setTimeout(function(){globalThis.clearInterval(intervalId);logger===null||logger===void 0?void 0:logger.error(DESTINATION_SDK_EVALUATION_TIMEOUT_ERROR(DEVICE_MODE_DESTINATIONS_PLUGIN,dest.userFriendlyId));state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);},LOAD_CHECK_TIMEOUT);});}}};};
1573
+
1574
+ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable no-param-reassign */var pluginName$a='DeviceModeTransformation';var DeviceModeTransformation=function DeviceModeTransformation(){return {name:pluginName$a,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$a]);},transformEvent:{enqueue:function enqueue(state,pluginsManager,event,destination,errorHandler,logger){// TODO: Implement DMT logic here
1575
+ // TODO: for now this is a pass through
1576
+ pluginsManager.invokeSingle('destinationsEventsQueue.enqueueEventToDestination',state,event,destination,errorHandler,logger);}}};};
1577
+
1578
+ var pluginName$9='ErrorReporting';var ErrorReporting=function ErrorReporting(){return {name:pluginName$9,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$9]);},errorReporting:{init:function init(state,pluginEngine,externalSrcLoader,logger){var _state$source$value,_state$source$value2;if(!((_state$source$value=state.source.value)!==null&&_state$source$value!==void 0&&_state$source$value.config)||!((_state$source$value2=state.source.value)!==null&&_state$source$value2!==void 0&&_state$source$value2.id)){return Promise.reject(new Error(INVALID_SOURCE_CONFIG_ERROR));}return pluginEngine.invokeSingle('errorReportingProvider.init',state,externalSrcLoader,logger);},notify:function notify(pluginEngine,client,error,state,logger){pluginEngine.invokeSingle('errorReportingProvider.notify',client,error,state,logger);},breadcrumb:function breadcrumb(pluginEngine,client,message,logger){pluginEngine.invokeSingle('errorReportingProvider.breadcrumb',client,message,logger);}}};};
1579
+
1580
+ var externallyLoadedSessionStorageKeys={segment:'ajs_anonymous_id'};
1581
+
1582
+ var getSegmentAnonymousId=function getSegmentAnonymousId(getStorageEngine){var anonymousId;/**
1583
+ * First check the local storage for anonymousId
1584
+ * Ref: https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/#identify
1585
+ */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
1586
+ var csEngine=getStorageEngine(COOKIE_STORAGE);if(!anonymousId&&csEngine!==null&&csEngine!==void 0&&csEngine.isEnabled){anonymousId=csEngine.getItem(externallyLoadedSessionStorageKeys.segment);}return anonymousId;};
1587
+
1588
+ var pluginName$8='ExternalAnonymousId';var ExternalAnonymousId=function ExternalAnonymousId(){return {name:pluginName$8,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$8]);},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
1589
+ switch(source){case'segment':anonymousId=getSegmentAnonymousId(getStorageEngine);break;}}return anonymousId;}}};};
1590
+
1591
+ var AMP_LINKER_ANONYMOUS_ID_KEY='rs_amp_id';
1592
+
1593
+ /* eslint-disable no-bitwise */ /**
1594
+ * generate crc table
1595
+ *
1596
+ * @params none
1597
+ * @returns array of CRC table
1598
+ */var makeCRCTable=function makeCRCTable(){var crcTable=[];var c;for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++){c=c&1?0xedb88320^c>>>1:c>>>1;}crcTable[n]=c;}return crcTable;};/**
1599
+ * This is utility function for crc32 algorithm
1600
+ *
1601
+ * @param {string} str
1602
+ * @returns {number} crc32
1603
+ */var crc32=function crc32(str){var crcTable=makeCRCTable();var crc=0^-1;for(var i=0;i<str.length;i++){crc=crc>>>8^crcTable[(crc^str.charCodeAt(i))&0xff];}return (crc^-1)>>>0;};
1604
+
1605
+ /**
1606
+ * An interface to fetch user device details.
1607
+ */var USER_INTERFACE={/**
1608
+ * @returns {string} user language
1609
+ */getUserLanguage:function getUserLanguage(){var _navigator;return (_navigator=navigator)===null||_navigator===void 0?void 0:_navigator.language;},/**
1610
+ * @returns {string} userAgent
1611
+ */getUserAgent:function getUserAgent(){var _navigator2;return (_navigator2=navigator)===null||_navigator2===void 0?void 0:_navigator2.userAgent;}};
1612
+
1613
+ /**
1614
+ * This is utility function for decoding from base 64 to utf8
1615
+ *
1616
+ * @param {string} str base64
1617
+ *
1618
+ * @returns {string} utf8
1619
+ */var b64DecodeUnicode=function b64DecodeUnicode(str){return(// Going backwards: from bytestream, to percent-encoding, to original string.
1620
+ decodeURIComponent(globalThis.atob(str).split('').map(function(c){var percentEncodingChar="00".concat(c.charCodeAt(0).toString(16));return "%".concat(percentEncodingChar.slice(-2));}).join('')));};/**
1621
+ * This is utility function for decoding from base 64 to utf8
1622
+ *
1623
+ * @param {string} data
1624
+ *
1625
+ * @return {string}
1626
+ */var decode$1=function decode(){var data=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';var decodedData=data.endsWith('..')?data.substring(0,data.length-2):data;return b64DecodeUnicode(decodedData);};
1627
+
1628
+ var KEY_VALIDATOR=/^[\w.-]+$/;var CHECKSUM_OFFSET_MAX_MIN=1;var VALID_VERSION=1;var DELIMITER='*';/**
1629
+ * Parse the linker param value to version checksum and serializedParams
1630
+ *
1631
+ * @param {string} value
1632
+ *
1633
+ * @return {?Object}
1634
+ */var parseLinkerParamValue=function parseLinkerParamValue(value){var parts=value.split(DELIMITER);var isEven=parts.length%2===0;if(parts.length<4||!isEven){// Format <version>*<checksum>*<key1>*<value1>
1635
+ // Note: linker makes sure there's at least one pair of non empty key value
1636
+ // Make sure there is at least three delimiters.
1637
+ return null;}var version=Number(parts.shift());if(version!==VALID_VERSION){return null;}var checksum=parts.shift();var serializedIds=parts.join(DELIMITER);return {checksum:checksum!==null&&checksum!==void 0?checksum:'',serializedIds:serializedIds};};/**
1638
+ * Deserialize the serializedIds and return keyValue pairs.
1639
+ *
1640
+ * @param {string} serializedIds
1641
+ *
1642
+ * @return {!Object<string, string>}
1643
+ */var deserialize=function deserialize(serializedIds){var keyValuePairs={};var params=serializedIds.split(DELIMITER);for(var i=0;i<params.length;i+=2){var key=params[i];var valid=KEY_VALIDATOR.test(key);if(valid){keyValuePairs[key]=decode$1(params[i+1]);}}return keyValuePairs;};/**
1644
+ * Generates a semi-unique value for page visitor.
1645
+ *
1646
+ * @return {string}
1647
+ */var getFingerprint=function getFingerprint(userAgent,language){var date=new Date();var timezone=date.getTimezoneOffset();return [userAgent,timezone,language].join(DELIMITER);};/**
1648
+ * Rounded time used to check if t2 - t1 is within our time tolerance.
1649
+ * Timestamp in minutes, floored.
1650
+ *
1651
+ * @return {number}
1652
+ */var getMinSinceEpoch=function getMinSinceEpoch(){return Math.floor(Date.now()/60000);};/**
1653
+ * Create a unique checksum hashing the fingerprint and a few other values.
1654
+ *
1655
+ * @param {string} serializedIds
1656
+ * @param {number=} optOffsetMin
1657
+ * @param {string} userAgent
1658
+ * @param {string} language
1659
+ *
1660
+ * @return {string}
1661
+ */var getCheckSum=function getCheckSum(serializedIds,optOffsetMin,userAgent,language){var fingerprint=getFingerprint(userAgent,language);var offset=optOffsetMin||0;var timestamp=getMinSinceEpoch()-offset;var crc=crc32([fingerprint,timestamp,serializedIds].join(DELIMITER));// Encoded to base36 for fewer bytes.
1662
+ return crc.toString(36);};/**
1663
+ * Check if the checksum is valid with time offset tolerance.
1664
+ *
1665
+ * @param {string} serializedIds
1666
+ * @param {string} checksum
1667
+ *
1668
+ * @return {boolean}
1669
+ */var isCheckSumValid=function isCheckSumValid(serializedIds,checksum){var userAgent=USER_INTERFACE.getUserAgent();var language=USER_INTERFACE.getUserLanguage();for(var i=0;i<=CHECKSUM_OFFSET_MAX_MIN;i+=1){var calculateCheckSum=getCheckSum(serializedIds,i,userAgent,language);if(calculateCheckSum===checksum){return true;}}return false;};/**
1670
+ * AMP Linker Parser (works for Rudder, GA or any other linker created by following Google's linker standard.)
1671
+ *
1672
+ * @param {string} value
1673
+ *
1674
+ * @return {?Object<string, string>}
1675
+ */var parseLinker=function parseLinker(value){var linkerObj=parseLinkerParamValue(value);if(!linkerObj){return null;}var checksum=linkerObj.checksum,serializedIds=linkerObj.serializedIds;if(!isCheckSumValid(serializedIds,checksum)){return null;}return deserialize(serializedIds);};
1676
+
1677
+ var pluginName$7='GoogleLinker';// TODO: refactor this plugin and all related sourcecode to be typesafe
1678
+ var GoogleLinker=function GoogleLinker(){return {name:pluginName$7,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$7]);},userSession:{anonymousIdGoogleLinker:function anonymousIdGoogleLinker(rudderAmpLinkerParam){if(!rudderAmpLinkerParam){return null;}var parsedAnonymousIdObj=rudderAmpLinkerParam?parseLinker(rudderAmpLinkerParam):null;return parsedAnonymousIdObj?parsedAnonymousIdObj[AMP_LINKER_ANONYMOUS_ID_KEY]:null;}}};};
1679
+
1680
+ 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);_defineProperty(this,"tasks",{});_defineProperty(this,"nextId",1);_defineProperty(this,"clock",DEFAULT_CLOCK);}_createClass(Schedule,[{key:"now",value:function now(){return +new this.clock.Date();}},{key:"run",value:function run(task,timeout,mode){var id=(this.nextId+1).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={};}},{key:"setClock",value:function setClock(newClock){this.clock=newClock;}},{key:"resetClock",value:function resetClock(){this.clock=DEFAULT_CLOCK;}}]);return Schedule;}();
1681
+
1682
+ var sortByTime=function sortByTime(a,b){return a.time-b.time;};var RETRY_QUEUE='RetryQueue';/**
1683
+ * Constructs a RetryQueue backed by localStorage
1684
+ *
1685
+ * @constructor
1686
+ * @param {String} name The name of the queue. Will be used to find abandoned queues and retry their items
1687
+ * @param {Object} [opts] Optional argument to override `maxItems`, `maxAttempts`, `minRetryDelay, `maxRetryDelay`, `backoffFactor` and `backoffJitter`.
1688
+ * @param {QueueProcessCallback} fn The function to call in order to process an item added to the queue
1689
+ */var RetryQueue=/*#__PURE__*/function(){function RetryQueue(name,options,queueProcessCb,storeManager){var storageType=arguments.length>4&&arguments[4]!==undefined?arguments[4]:LOCAL_STORAGE;var logger=arguments.length>5?arguments[5]:undefined;_classCallCheck(this,RetryQueue);this.storeManager=storeManager;this.name=name;this.id=generateUUID();this.processQueueCb=queueProcessCb;this.maxItems=options.maxItems||Infinity;this.maxAttempts=options.maxAttempts||Infinity;this.logger=logger;this.backoff={MIN_RETRY_DELAY:options.minRetryDelay||1000,MAX_RETRY_DELAY:options.maxRetryDelay||30000,FACTOR:options.backoffFactor||2,JITTER:options.backoffJitter||0};// painstakingly tuned. that's why they're not "easily" configurable
1690
+ this.timeouts={ACK_TIMER:1000,RECLAIM_TIMER:3000,RECLAIM_TIMEOUT:10000,RECLAIM_WAIT:500};this.schedule=new Schedule();this.processId='0';// Set up our empty queues
1691
+ this.store=this.storeManager.setStore({id:this.id,name:this.name,validKeys:QueueStatuses,type:storageType});this.setQueue(QueueStatuses.IN_PROGRESS,{});this.setQueue(QueueStatuses.QUEUE,[]);// bind recurring tasks for ease of use
1692
+ this.ack=this.ack.bind(this);this.checkReclaim=this.checkReclaim.bind(this);this.processHead=this.processHead.bind(this);this.scheduleTimeoutActive=false;}_createClass(RetryQueue,[{key:"getQueue",value:function getQueue(name){return this.store.get(name!==null&&name!==void 0?name:this.name);}// TODO: fix the type of different queues to be the same if possible
1693
+ },{key:"setQueue",value:function setQueue(name,value){this.store.set(name!==null&&name!==void 0?name:this.name,value!==null&&value!==void 0?value:[]);}/**
1694
+ * Stops processing the queue
1695
+ */},{key:"stop",value:function stop(){this.schedule.cancelAll();this.scheduleTimeoutActive=false;}/**
1696
+ * Starts processing the queue
1697
+ */},{key:"start",value:function start(){if(this.scheduleTimeoutActive){this.stop();}this.scheduleTimeoutActive=true;this.ack();this.checkReclaim();this.processHead();}/**
1698
+ * Decides whether to retry. Overridable.
1699
+ *
1700
+ * @param {Object} item The item being processed
1701
+ * @param {Number} attemptNumber The attemptNumber (1 for first retry)
1702
+ * @return {Boolean} Whether to requeue the message
1703
+ */},{key:"shouldRetry",value:function shouldRetry(item,attemptNumber){return attemptNumber<=this.maxAttempts;}/**
1704
+ * Calculates the delay (in ms) for a retry attempt
1705
+ *
1706
+ * @param {Number} attemptNumber The attemptNumber (1 for first retry)
1707
+ * @return {Number} The delay in milliseconds to wait before attempting a retry
1708
+ */},{key:"getDelay",value:function getDelay(attemptNumber){var ms=this.backoff.MIN_RETRY_DELAY*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.MAX_RETRY_DELAY).toPrecision(1));}},{key:"enqueue",value:function enqueue(entry){var _ref;var queue=(_ref=this.getQueue(QueueStatuses.QUEUE))!==null&&_ref!==void 0?_ref:[];queue=queue.slice(-(this.maxItems-1));queue.push(entry);queue=queue.sort(sortByTime);this.setQueue(QueueStatuses.QUEUE,queue);if(this.scheduleTimeoutActive){this.processHead();}}/**
1709
+ * Adds an item to the queue
1710
+ *
1711
+ * @param {Object} item The item to process
1712
+ */},{key:"addItem",value:function addItem(item){this.enqueue({item:item,attemptNumber:0,time:this.schedule.now(),id:generateUUID()});}/**
1713
+ * Adds an item to the retry queue
1714
+ *
1715
+ * @param {Object} item The item to retry
1716
+ * @param {Number} attemptNumber The attempt number (1 for first retry)
1717
+ * @param {Error} [error] The error from previous attempt, if there was one
1718
+ * @param {String} [id] The id of the queued message used for tracking duplicate entries
1719
+ */},{key:"requeue",value:function requeue(item,attemptNumber,error,id){if(this.shouldRetry(item,attemptNumber)){this.enqueue({item:item,attemptNumber:attemptNumber,time:this.schedule.now()+this.getDelay(attemptNumber),id:id||generateUUID()});}}},{key:"processHead",value:function processHead(){var _ref2,_ref3,_this=this,_ref5;// cancel the scheduled task if it exists
1720
+ this.schedule.cancel(this.processId);// Pop the head off the queue
1721
+ var queue=(_ref2=this.getQueue(QueueStatuses.QUEUE))!==null&&_ref2!==void 0?_ref2:[];var inProgress=(_ref3=this.getQueue(QueueStatuses.IN_PROGRESS))!==null&&_ref3!==void 0?_ref3:{};var now=this.schedule.now();var toRun=[];// eslint-disable-next-line @typescript-eslint/no-unused-vars
1722
+ var processItemCallback=function processItemCallback(el,id){return function(err,res){var _ref4;var inProgress=(_ref4=_this.getQueue(QueueStatuses.IN_PROGRESS))!==null&&_ref4!==void 0?_ref4:{};delete inProgress[id];_this.setQueue(QueueStatuses.IN_PROGRESS,inProgress);if(err){_this.requeue(el.item,el.attemptNumber+1,err,el.id);}};};var enqueueItem=function enqueueItem(el,id){toRun.push({item:el.item,done:processItemCallback(el,id),attemptNumber:el.attemptNumber});};var inProgressSize=Object.keys(inProgress).length;// eslint-disable-next-line no-plusplus
1723
+ 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
1724
+ inProgress[id]={item:el.item,attemptNumber:el.attemptNumber,time:this.schedule.now()};enqueueItem(el,id);}}this.setQueue(QueueStatuses.QUEUE,queue);this.setQueue(QueueStatuses.IN_PROGRESS,inProgress);toRun.forEach(function(el){// TODO: handle processQueueCb timeout
1725
+ try{var willBeRetried=_this.shouldRetry(el.item,el.attemptNumber+1);_this.processQueueCb(el.item,el.done,el.attemptNumber,_this.maxAttempts,willBeRetried);}catch(err){var _this$logger;(_this$logger=_this.logger)===null||_this$logger===void 0?void 0:_this$logger.error(RETRY_QUEUE_PROCESS_ERROR(RETRY_QUEUE),err);}});// re-read the queue in case the process function finished immediately or added another item
1726
+ queue=(_ref5=this.getQueue(QueueStatuses.QUEUE))!==null&&_ref5!==void 0?_ref5:[];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
1727
+ },{key:"ack",value:function ack(){this.setQueue(QueueStatuses.ACK,this.schedule.now());this.setQueue(QueueStatuses.RECLAIM_START,null);this.setQueue(QueueStatuses.RECLAIM_END,null);this.schedule.run(this.ack,this.timeouts.ACK_TIMER,ScheduleModes.ASAP);}},{key:"reclaim",value:function reclaim(id){var _this$getQueue,_other$get,_other$get2,_this2=this;var other=this.storeManager.setStore({id:id,name:this.name,validKeys:QueueStatuses,type:LOCAL_STORAGE});var our={queue:(_this$getQueue=this.getQueue(QueueStatuses.QUEUE))!==null&&_this$getQueue!==void 0?_this$getQueue:[]};var their={inProgress:(_other$get=other.get(QueueStatuses.IN_PROGRESS))!==null&&_other$get!==void 0?_other$get:{},queue:(_other$get2=other.get(QueueStatuses.QUEUE))!==null&&_other$get2!==void 0?_other$get2:[]};var trackMessageIds=[];var addConcatQueue=function addConcatQueue(queue,incrementAttemptNumberBy){var concatIterator=function concatIterator(el){var id=el.id||generateUUID();if(trackMessageIds.includes(id));else {our.queue.push({item:el.item,attemptNumber:el.attemptNumber+incrementAttemptNumberBy,time:_this2.schedule.now(),id:id});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#
1728
+ addConcatQueue(their.queue,0);// if the queue is abandoned, all the in-progress are failed. retry them immediately and increment the attempt#
1729
+ addConcatQueue(their.inProgress,1);our.queue=our.queue.sort(sortByTime);this.setQueue(QueueStatuses.QUEUE,our.queue);// remove all keys one by on next tick to avoid NS_ERROR_STORAGE_BUSY error
1730
+ try{this.clearOtherQueue(other,1);}catch(e){var isLocalStorageBusy=e.name==='NS_ERROR_STORAGE_BUSY'||e.code==='NS_ERROR_STORAGE_BUSY'||e.code===0x80630001;if(isLocalStorageBusy){try{this.clearOtherQueue(other,40);}catch(retryError){console.error(retryError);}}else {console.error(e);}}// process the new items we claimed
1731
+ this.processHead();}// eslint-disable-next-line class-methods-use-this
1732
+ },{key:"clearOtherQueue",value:function clearOtherQueue(other,localStorageBackoff){globalThis.setTimeout(function(){other.remove(QueueStatuses.IN_PROGRESS);globalThis.setTimeout(function(){other.remove(QueueStatuses.QUEUE);globalThis.setTimeout(function(){other.remove(QueueStatuses.RECLAIM_START);globalThis.setTimeout(function(){other.remove(QueueStatuses.RECLAIM_END);globalThis.setTimeout(function(){other.remove(QueueStatuses.ACK);},localStorageBackoff);},localStorageBackoff);},localStorageBackoff);},localStorageBackoff);},localStorageBackoff);}},{key:"checkReclaim",value:function checkReclaim(){var _this3=this;var createReclaimStartTask=function createReclaimStartTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_END)!==_this3.id){return;}if(store.get(QueueStatuses.RECLAIM_START)!==_this3.id){return;}_this3.reclaim(store.id);};};var createReclaimEndTask=function createReclaimEndTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_START)!==_this3.id){return;}store.set(QueueStatuses.RECLAIM_END,_this3.id);_this3.schedule.run(createReclaimStartTask(store),_this3.timeouts.RECLAIM_WAIT,ScheduleModes.ABANDON);};};var tryReclaim=function tryReclaim(store){store.set(QueueStatuses.RECLAIM_START,_this3.id);store.set(QueueStatuses.ACK,_this3.schedule.now());_this3.schedule.run(createReclaimEndTask(store),_this3.timeouts.RECLAIM_WAIT,ScheduleModes.ABANDON);};var findOtherQueues=function findOtherQueues(name){var res=[];var storage=_this3.store.getOriginalEngine();for(var i=0;i<storage.length;i++){var k=storage.key(i);var parts=k?k.split('.'):[];if(parts.length!==3){// eslint-disable-next-line no-continue
1733
+ continue;}if(parts[0]!==name){// eslint-disable-next-line no-continue
1734
+ continue;}if(parts[2]!==QueueStatuses.ACK){// eslint-disable-next-line no-continue
1735
+ continue;}res.push(_this3.storeManager.setStore({id:parts[1],name:name,validKeys:QueueStatuses,type:LOCAL_STORAGE}));}return res;};findOtherQueues(this.name).forEach(function(store){if(store.id===_this3.id){return;}if(_this3.schedule.now()-store.get(QueueStatuses.ACK)<_this3.timeouts.RECLAIM_TIMEOUT){return;}tryReclaim(store);});this.schedule.run(this.checkReclaim,this.timeouts.RECLAIM_TIMER,ScheduleModes.RESCHEDULE);}}]);return RetryQueue;}();
1736
+
1737
+ var DEFAULT_QUEUE_OPTIONS={maxItems:100};var QUEUE_NAME$1='rudder_destinations_events';var NATIVE_DESTINATION_QUEUE_PLUGIN='NativeDestinationQueuePlugin';
1738
+
1739
+ var getNormalizedQueueOptions$1=function getNormalizedQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_QUEUE_OPTIONS,queueOpts);};var isValidEventName=function isValidEventName(eventName){return eventName&&typeof eventName==='string';};var isEventDenyListed=function isEventDenyListed(eventType,eventName,dest){if(eventType!=='track'){return false;}var _dest$config=dest.config,blacklistedEvents=_dest$config.blacklistedEvents,whitelistedEvents=_dest$config.whitelistedEvents,eventFilteringOption=_dest$config.eventFilteringOption;switch(eventFilteringOption){// Blacklist is chosen for filtering events
1740
+ case'blacklistedEvents':{if(!isValidEventName(eventName)){return false;}var trimmedEventName=eventName.trim();if(Array.isArray(blacklistedEvents)){return blacklistedEvents.some(function(eventObj){return eventObj.eventName.trim()===trimmedEventName;});}return false;}// Whitelist is chosen for filtering events
1741
+ case'whitelistedEvents':{if(!isValidEventName(eventName)){return true;}var _trimmedEventName=eventName.trim();if(Array.isArray(whitelistedEvents)){return !whitelistedEvents.some(function(eventObj){return eventObj.eventName.trim()===_trimmedEventName;});}return true;}case'disable':default:return false;}};var sendEventToDestination=function sendEventToDestination(item,dest,errorHandler,logger){var methodName=item.type.toString();try{var _dest$instance,_dest$instance$method;// Destinations expect the event to be wrapped under the `message` key
1742
+ // This will remain until we update the destinations to accept the event directly
1743
+ (_dest$instance=dest.instance)===null||_dest$instance===void 0||(_dest$instance$method=_dest$instance[methodName])===null||_dest$instance$method===void 0?void 0:_dest$instance$method.call(_dest$instance,{message:item});}catch(err){errorHandler===null||errorHandler===void 0?void 0:errorHandler.onError(err,'NativeDestinationQueue',DESTINATION_EVENT_FORWARDING_ERROR(dest.userFriendlyId));}};
1744
+
1745
+ var pluginName$6='NativeDestinationQueue';var NativeDestinationQueue=function NativeDestinationQueue(){return {name:pluginName$6,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$6]);},destinationsEventsQueue:{/**
1746
+ * Initialize the queue for delivery to destinations
1747
+ * @param state Application state
1748
+ * @param pluginsManager PluginsManager instance
1749
+ * @param storeManager StoreManager instance
1750
+ * @param errorHandler Error handler instance
1751
+ * @param logger Logger instance
1752
+ * @returns IQueue instance
1753
+ */init:function init(state,pluginsManager,storeManager,errorHandler,logger){var finalQOpts=getNormalizedQueueOptions$1(state.loadOptions.value.destinationsQueueOptions);var writeKey=state.lifecycle.writeKey.value;var eventsQueue=new RetryQueue(// adding write key to the queue name to avoid conflicts
1754
+ "".concat(QUEUE_NAME$1,"_").concat(writeKey),finalQOpts,function(item,done){var destinationsToSend=filterDestinations(item.integrations,state.nativeDestinations.initializedDestinations.value);destinationsToSend.forEach(function(dest){var sendEvent=!isEventDenyListed(item.type,item.event,dest);if(!sendEvent){logger===null||logger===void 0?void 0:logger.warn(DESTINATION_EVENT_FILTERING_WARNING(NATIVE_DESTINATION_QUEUE_PLUGIN,item.event,dest.userFriendlyId));return;}if(dest.shouldApplyDeviceModeTransformation){pluginsManager.invokeSingle('transformEvent.enqueue',state,item,dest,logger);}else {sendEventToDestination(item,dest,errorHandler);}});// Mark success always
1755
+ done(null);},storeManager,MEMORY_STORAGE);// TODO: This seems to not work as expected. Need to investigate
1756
+ // effect(() => {
1757
+ // if (state.nativeDestinations.clientDestinationsReady.value === true) {
1758
+ // eventsQueue.start();
1759
+ // }
1760
+ // });
1761
+ return eventsQueue;},/**
1762
+ * Add event to the queue for delivery to destinations
1763
+ * @param state Application state
1764
+ * @param eventsQueue IQueue instance
1765
+ * @param event RudderEvent object
1766
+ * @param errorHandler Error handler instance
1767
+ * @param logger Logger instance
1768
+ * @returns none
1769
+ */enqueue:function enqueue(state,eventsQueue,event,errorHandler,logger){event.integrations=normalizeIntegrationOptions(event.integrations);eventsQueue.addItem(event);},/**
1770
+ * This extension point is used to directly send the transformed event to the destination
1771
+ * @param state Application state
1772
+ * @param event RudderEvent Object
1773
+ * @param destination Destination Object
1774
+ * @param errorHandler Error handler instance
1775
+ * @param logger Logger instance
1776
+ */enqueueEventToDestination:function enqueueEventToDestination(state,event,destination,errorHandler,logger){sendEventToDestination(event,destination,errorHandler);}}};};
1777
+
1778
+ var ONETRUST_CONSENT_MANAGER_PLUGIN='OneTrustConsentManagerPlugin';
1779
+
1780
+ var pluginName$5='OneTrustConsentManager';var OneTrustConsentManager=function OneTrustConsentManager(){return {name:pluginName$5,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$5]);},consentManager:{init:function init(state,storeManager,logger){if(!globalThis.OneTrust||!globalThis.OnetrustActiveGroups){logger===null||logger===void 0?void 0:logger.error(ONETRUST_ACCESS_ERROR(ONETRUST_CONSENT_MANAGER_PLUGIN));state.consents.data.value={initialized:false};return;}// OneTrustConsentManager SDK populates a data layer object OnetrustActiveGroups with
1781
+ // the cookie categories Ids that the user has consented to.
1782
+ // Eg: ',C0001,C0003,'
1783
+ // We split it and save it as an array.
1784
+ var allowedConsentIds=globalThis.OnetrustActiveGroups.split(',').filter(function(n){return n;});var allowedConsents={};var deniedConsentIds=[];// Get the groups(cookie categorization), user has created in one trust account.
1785
+ var oneTrustAllGroupsInfo=globalThis.OneTrust.GetDomainData().Groups;oneTrustAllGroupsInfo.forEach(function(group){var CustomGroupId=group.CustomGroupId,GroupName=group.GroupName;if(allowedConsentIds.includes(CustomGroupId)){allowedConsents[CustomGroupId]=GroupName;}else {deniedConsentIds.push(CustomGroupId);}});state.consents.data.value={initialized:true,allowedConsents:allowedConsents,deniedConsentIds:deniedConsentIds};},isDestinationConsented:function isDestinationConsented(state,destConfig,logger){var consentData=state.consents.data.value;if(!consentData.initialized){return true;}var allowedConsents=consentData.allowedConsents;try{// mapping of the destination with the consent group name
1786
+ var oneTrustCookieCategories=destConfig.oneTrustCookieCategories;// If the destination do not have this mapping events will be sent.
1787
+ if(!oneTrustCookieCategories){return true;}// Change the structure of oneTrustConsentGroup as an array and filter values if empty string
1788
+ // Eg:
1789
+ // ["Performance Cookies", "Functional Cookies"]
1790
+ var validOneTrustCookieCategories=oneTrustCookieCategories.map(function(c){return c.oneTrustCookieCategory;}).filter(function(n){return n;});var containsAllConsent=true;// Check if all the destination's mapped cookie categories are consented by the user in the browser.
1791
+ containsAllConsent=validOneTrustCookieCategories.every(function(element){return Object.keys(allowedConsents).includes(element.trim())||Object.values(allowedConsents).includes(element.trim());});return containsAllConsent;}catch(err){logger===null||logger===void 0?void 0:logger.error(DESTINATION_CONSENT_STATUS_ERROR(ONETRUST_CONSENT_MANAGER_PLUGIN),err);return true;}}}};};
1792
+
1793
+ var KETCH_CONSENT_MANAGER_PLUGIN='KetchConsentManagerPlugin';var KETCH_CONSENT_COOKIE_NAME_V1='_ketch_consent_v1_';
1794
+
1795
+ /**
1796
+ * Gets the consent data from the Ketch's consent cookie
1797
+ * @param storeManager Store manager instance
1798
+ * @param logger Logger instance
1799
+ * @returns Consent data from the consent cookie
1800
+ */var getKetchConsentData=function getKetchConsentData(storeManager,logger){var rawConsentCookieData=null;try{// Create a data store instance to read the consent cookie
1801
+ var dataStore=storeManager===null||storeManager===void 0?void 0:storeManager.setStore({id:KETCH_CONSENT_MANAGER_PLUGIN,name:KETCH_CONSENT_MANAGER_PLUGIN,type:COOKIE_STORAGE});rawConsentCookieData=dataStore===null||dataStore===void 0?void 0:dataStore.engine.getItem(KETCH_CONSENT_COOKIE_NAME_V1);}catch(err){logger===null||logger===void 0?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
1802
+ var consentCookieData;try{consentCookieData=JSON.parse(fromBase64(rawConsentCookieData));}catch(err){logger===null||logger===void 0?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
1803
+ 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;};/**
1804
+ * Gets the consent data in the format expected by the application state
1805
+ * @param ketchConsentData Consent data derived from the consent cookie
1806
+ * @returns Consent data
1807
+ */var getConsentData=function getConsentData(ketchConsentData){var allowedConsents=[];var deniedConsentIds=[];var initialized=false;if(ketchConsentData){Object.entries(ketchConsentData).forEach(function(e){var purposeCode=e[0];var isConsented=e[1];if(isConsented){allowedConsents.push(purposeCode);}else {deniedConsentIds.push(purposeCode);}});initialized=true;}return {initialized:initialized,allowedConsents:allowedConsents,deniedConsentIds:deniedConsentIds};};var updateConsentStateFromData=function updateConsentStateFromData(state,ketchConsentData){var consentData=getConsentData(ketchConsentData);state.consents.data.value=consentData;};
1808
+
1809
+ var pluginName$4='KetchConsentManager';var KetchConsentManager=function KetchConsentManager(){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,storeManager,logger){// getKetchUserConsentedPurposes returns current ketch opted-in purposes
1810
+ // This will be helpful for debugging
1811
+ globalThis.getKetchUserConsentedPurposes=function(){var _state$consents$data$;return (_state$consents$data$=state.consents.data.value.allowedConsents)===null||_state$consents$data$===void 0?void 0:_state$consents$data$.slice();};// getKetchUserDeniedPurposes returns current ketch opted-out purposes
1812
+ // This will be helpful for debugging
1813
+ 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
1814
+ // this will be called from ketch rudderstack plugin
1815
+ globalThis.updateKetchConsent=function(ketchConsentData){updateConsentStateFromData(state,ketchConsentData);};// retrieve consent data and update the state
1816
+ var ketchConsentData;if(!isUndefined(globalThis.ketchConsent)){ketchConsentData=globalThis.ketchConsent;}else {ketchConsentData=getKetchConsentData(storeManager,logger);}updateConsentStateFromData(state,ketchConsentData);},isDestinationConsented:function isDestinationConsented(state,destConfig,logger){var consentData=state.consents.data.value;if(!consentData.initialized){return true;}var allowedConsents=consentData.allowedConsents;try{var ketchConsentPurposes=destConfig.ketchConsentPurposes;// If the destination do not have this mapping events will be sent.
1817
+ if(!ketchConsentPurposes||ketchConsentPurposes.length===0){return true;}var purposes=ketchConsentPurposes.map(function(p){return p.purpose;}).filter(function(n){return n;});// Check if any of the destination's mapped ketch purposes are consented by the user in the browser.
1818
+ var containsAnyOfConsent=purposes.some(function(element){return allowedConsents.includes(element.trim());});return containsAnyOfConsent;}catch(err){logger===null||logger===void 0?void 0:logger.error(DESTINATION_CONSENT_STATUS_ERROR(KETCH_CONSENT_MANAGER_PLUGIN),err);return true;}}}};};
1819
+
1820
+ var ENCRYPTION_PREFIX_V3='RS_ENC_v3_';
1821
+
1822
+ var encrypt$1=function encrypt(value){return "".concat(ENCRYPTION_PREFIX_V3).concat(toBase64(value));};var decrypt$1=function decrypt(value){if(value.startsWith(ENCRYPTION_PREFIX_V3)){return fromBase64(value.substring(ENCRYPTION_PREFIX_V3.length));}return value;};
1823
+
1824
+ var pluginName$3='StorageEncryption';var StorageEncryption=function StorageEncryption(){return {name:pluginName$3,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$3]);},storage:{encrypt:function encrypt(value){return encrypt$1(value);},decrypt:function decrypt(value){return decrypt$1(value);}}};};
1825
+
1826
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
1827
+
1828
+ function getDefaultExportFromCjs (x) {
1829
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
1830
+ }
1831
+
1832
+ function getDefaultExportFromNamespaceIfNotNamed (n) {
1833
+ return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
1834
+ }
1835
+
1836
+ var aes = {exports: {}};
1837
+
1838
+ function commonjsRequire(path) {
1839
+ throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
1840
+ }
1841
+
1842
+ var core = {exports: {}};
1843
+
1844
+ var _polyfillNode_crypto = {};
1845
+
1846
+ var _polyfillNode_crypto$1 = /*#__PURE__*/Object.freeze({
1847
+ __proto__: null,
1848
+ default: _polyfillNode_crypto
1849
+ });
1850
+
1851
+ var require$$0 = /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(_polyfillNode_crypto$1);
1852
+
1853
+ var hasRequiredCore;function requireCore(){if(hasRequiredCore)return core.exports;hasRequiredCore=1;(function(module,exports){(function(root,factory){{// CommonJS
1854
+ module.exports=factory();}})(commonjsGlobal,function(){/*globals window, global, require*/ /**
1855
+ * CryptoJS core components.
1856
+ */var CryptoJS=CryptoJS||function(Math,undefined$1){var crypto;// Native crypto from window (Browser)
1857
+ if(typeof window!=='undefined'&&window.crypto){crypto=window.crypto;}// Native crypto in web worker (Browser)
1858
+ if(typeof self!=='undefined'&&self.crypto){crypto=self.crypto;}// Native crypto from worker
1859
+ if(typeof globalThis!=='undefined'&&globalThis.crypto){crypto=globalThis.crypto;}// Native (experimental IE 11) crypto from window (Browser)
1860
+ if(!crypto&&typeof window!=='undefined'&&window.msCrypto){crypto=window.msCrypto;}// Native crypto from global (NodeJS)
1861
+ if(!crypto&&typeof commonjsGlobal!=='undefined'&&commonjsGlobal.crypto){crypto=commonjsGlobal.crypto;}// Native crypto import via require (NodeJS)
1862
+ if(!crypto&&typeof commonjsRequire==='function'){try{crypto=require$$0;}catch(err){}}/*
1863
+ * Cryptographically secure pseudorandom number generator
1864
+ *
1865
+ * As Math.random() is cryptographically not safe to use
1866
+ */var cryptoSecureRandomInt=function cryptoSecureRandomInt(){if(crypto){// Use getRandomValues method (Browser)
1867
+ if(typeof crypto.getRandomValues==='function'){try{return crypto.getRandomValues(new Uint32Array(1))[0];}catch(err){}}// Use randomBytes method (NodeJS)
1868
+ if(typeof crypto.randomBytes==='function'){try{return crypto.randomBytes(4).readInt32LE();}catch(err){}}}throw new Error('Native crypto module could not be used to get secure random number.');};/*
1869
+ * Local polyfill of Object.create
1870
+
1871
+ */var create=Object.create||function(){function F(){}return function(obj){var subtype;F.prototype=obj;subtype=new F();F.prototype=null;return subtype;};}();/**
1872
+ * CryptoJS namespace.
1873
+ */var C={};/**
1874
+ * Library namespace.
1875
+ */var C_lib=C.lib={};/**
1876
+ * Base object for prototypal inheritance.
1877
+ */var Base=C_lib.Base=function(){return {/**
1878
+ * Creates a new object that inherits from this object.
1879
+ *
1880
+ * @param {Object} overrides Properties to copy into the new object.
1881
+ *
1882
+ * @return {Object} The new object.
1883
+ *
1884
+ * @static
1885
+ *
1886
+ * @example
1887
+ *
1888
+ * var MyType = CryptoJS.lib.Base.extend({
1889
+ * field: 'value',
1890
+ *
1891
+ * method: function () {
1892
+ * }
1893
+ * });
1894
+ */extend:function extend(overrides){// Spawn
1895
+ var subtype=create(this);// Augment
1896
+ if(overrides){subtype.mixIn(overrides);}// Create default initializer
1897
+ if(!subtype.hasOwnProperty('init')||this.init===subtype.init){subtype.init=function(){subtype.$super.init.apply(this,arguments);};}// Initializer's prototype is the subtype object
1898
+ subtype.init.prototype=subtype;// Reference supertype
1899
+ subtype.$super=this;return subtype;},/**
1900
+ * Extends this object and runs the init method.
1901
+ * Arguments to create() will be passed to init().
1902
+ *
1903
+ * @return {Object} The new object.
1904
+ *
1905
+ * @static
1906
+ *
1907
+ * @example
1908
+ *
1909
+ * var instance = MyType.create();
1910
+ */create:function create(){var instance=this.extend();instance.init.apply(instance,arguments);return instance;},/**
1911
+ * Initializes a newly created object.
1912
+ * Override this method to add some logic when your objects are created.
1913
+ *
1914
+ * @example
1915
+ *
1916
+ * var MyType = CryptoJS.lib.Base.extend({
1917
+ * init: function () {
1918
+ * // ...
1919
+ * }
1920
+ * });
1921
+ */init:function init(){},/**
1922
+ * Copies properties into this object.
1923
+ *
1924
+ * @param {Object} properties The properties to mix in.
1925
+ *
1926
+ * @example
1927
+ *
1928
+ * MyType.mixIn({
1929
+ * field: 'value'
1930
+ * });
1931
+ */mixIn:function mixIn(properties){for(var propertyName in properties){if(properties.hasOwnProperty(propertyName)){this[propertyName]=properties[propertyName];}}// IE won't copy toString using the loop above
1932
+ if(properties.hasOwnProperty('toString')){this.toString=properties.toString;}},/**
1933
+ * Creates a copy of this object.
1934
+ *
1935
+ * @return {Object} The clone.
1936
+ *
1937
+ * @example
1938
+ *
1939
+ * var clone = instance.clone();
1940
+ */clone:function clone(){return this.init.prototype.extend(this);}};}();/**
1941
+ * An array of 32-bit words.
1942
+ *
1943
+ * @property {Array} words The array of 32-bit words.
1944
+ * @property {number} sigBytes The number of significant bytes in this word array.
1945
+ */var WordArray=C_lib.WordArray=Base.extend({/**
1946
+ * Initializes a newly created word array.
1947
+ *
1948
+ * @param {Array} words (Optional) An array of 32-bit words.
1949
+ * @param {number} sigBytes (Optional) The number of significant bytes in the words.
1950
+ *
1951
+ * @example
1952
+ *
1953
+ * var wordArray = CryptoJS.lib.WordArray.create();
1954
+ * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
1955
+ * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
1956
+ */init:function init(words,sigBytes){words=this.words=words||[];if(sigBytes!=undefined$1){this.sigBytes=sigBytes;}else {this.sigBytes=words.length*4;}},/**
1957
+ * Converts this word array to a string.
1958
+ *
1959
+ * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
1960
+ *
1961
+ * @return {string} The stringified word array.
1962
+ *
1963
+ * @example
1964
+ *
1965
+ * var string = wordArray + '';
1966
+ * var string = wordArray.toString();
1967
+ * var string = wordArray.toString(CryptoJS.enc.Utf8);
1968
+ */toString:function toString(encoder){return (encoder||Hex).stringify(this);},/**
1969
+ * Concatenates a word array to this word array.
1970
+ *
1971
+ * @param {WordArray} wordArray The word array to append.
1972
+ *
1973
+ * @return {WordArray} This word array.
1974
+ *
1975
+ * @example
1976
+ *
1977
+ * wordArray1.concat(wordArray2);
1978
+ */concat:function concat(wordArray){// Shortcuts
1979
+ var thisWords=this.words;var thatWords=wordArray.words;var thisSigBytes=this.sigBytes;var thatSigBytes=wordArray.sigBytes;// Clamp excess bits
1980
+ this.clamp();// Concat
1981
+ if(thisSigBytes%4){// Copy one byte at a time
1982
+ for(var i=0;i<thatSigBytes;i++){var thatByte=thatWords[i>>>2]>>>24-i%4*8&0xff;thisWords[thisSigBytes+i>>>2]|=thatByte<<24-(thisSigBytes+i)%4*8;}}else {// Copy one word at a time
1983
+ for(var j=0;j<thatSigBytes;j+=4){thisWords[thisSigBytes+j>>>2]=thatWords[j>>>2];}}this.sigBytes+=thatSigBytes;// Chainable
1984
+ return this;},/**
1985
+ * Removes insignificant bits.
1986
+ *
1987
+ * @example
1988
+ *
1989
+ * wordArray.clamp();
1990
+ */clamp:function clamp(){// Shortcuts
1991
+ var words=this.words;var sigBytes=this.sigBytes;// Clamp
1992
+ words[sigBytes>>>2]&=0xffffffff<<32-sigBytes%4*8;words.length=Math.ceil(sigBytes/4);},/**
1993
+ * Creates a copy of this word array.
1994
+ *
1995
+ * @return {WordArray} The clone.
1996
+ *
1997
+ * @example
1998
+ *
1999
+ * var clone = wordArray.clone();
2000
+ */clone:function clone(){var clone=Base.clone.call(this);clone.words=this.words.slice(0);return clone;},/**
2001
+ * Creates a word array filled with random bytes.
2002
+ *
2003
+ * @param {number} nBytes The number of random bytes to generate.
2004
+ *
2005
+ * @return {WordArray} The random word array.
2006
+ *
2007
+ * @static
2008
+ *
2009
+ * @example
2010
+ *
2011
+ * var wordArray = CryptoJS.lib.WordArray.random(16);
2012
+ */random:function random(nBytes){var words=[];for(var i=0;i<nBytes;i+=4){words.push(cryptoSecureRandomInt());}return new WordArray.init(words,nBytes);}});/**
2013
+ * Encoder namespace.
2014
+ */var C_enc=C.enc={};/**
2015
+ * Hex encoding strategy.
2016
+ */var Hex=C_enc.Hex={/**
2017
+ * Converts a word array to a hex string.
2018
+ *
2019
+ * @param {WordArray} wordArray The word array.
2020
+ *
2021
+ * @return {string} The hex string.
2022
+ *
2023
+ * @static
2024
+ *
2025
+ * @example
2026
+ *
2027
+ * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
2028
+ */stringify:function stringify(wordArray){// Shortcuts
2029
+ var words=wordArray.words;var sigBytes=wordArray.sigBytes;// Convert
2030
+ var hexChars=[];for(var i=0;i<sigBytes;i++){var bite=words[i>>>2]>>>24-i%4*8&0xff;hexChars.push((bite>>>4).toString(16));hexChars.push((bite&0x0f).toString(16));}return hexChars.join('');},/**
2031
+ * Converts a hex string to a word array.
2032
+ *
2033
+ * @param {string} hexStr The hex string.
2034
+ *
2035
+ * @return {WordArray} The word array.
2036
+ *
2037
+ * @static
2038
+ *
2039
+ * @example
2040
+ *
2041
+ * var wordArray = CryptoJS.enc.Hex.parse(hexString);
2042
+ */parse:function parse(hexStr){// Shortcut
2043
+ var hexStrLength=hexStr.length;// Convert
2044
+ var words=[];for(var i=0;i<hexStrLength;i+=2){words[i>>>3]|=parseInt(hexStr.substr(i,2),16)<<24-i%8*4;}return new WordArray.init(words,hexStrLength/2);}};/**
2045
+ * Latin1 encoding strategy.
2046
+ */var Latin1=C_enc.Latin1={/**
2047
+ * Converts a word array to a Latin1 string.
2048
+ *
2049
+ * @param {WordArray} wordArray The word array.
2050
+ *
2051
+ * @return {string} The Latin1 string.
2052
+ *
2053
+ * @static
2054
+ *
2055
+ * @example
2056
+ *
2057
+ * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
2058
+ */stringify:function stringify(wordArray){// Shortcuts
2059
+ var words=wordArray.words;var sigBytes=wordArray.sigBytes;// Convert
2060
+ var latin1Chars=[];for(var i=0;i<sigBytes;i++){var bite=words[i>>>2]>>>24-i%4*8&0xff;latin1Chars.push(String.fromCharCode(bite));}return latin1Chars.join('');},/**
2061
+ * Converts a Latin1 string to a word array.
2062
+ *
2063
+ * @param {string} latin1Str The Latin1 string.
2064
+ *
2065
+ * @return {WordArray} The word array.
2066
+ *
2067
+ * @static
2068
+ *
2069
+ * @example
2070
+ *
2071
+ * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
2072
+ */parse:function parse(latin1Str){// Shortcut
2073
+ var latin1StrLength=latin1Str.length;// Convert
2074
+ var words=[];for(var i=0;i<latin1StrLength;i++){words[i>>>2]|=(latin1Str.charCodeAt(i)&0xff)<<24-i%4*8;}return new WordArray.init(words,latin1StrLength);}};/**
2075
+ * UTF-8 encoding strategy.
2076
+ */var Utf8=C_enc.Utf8={/**
2077
+ * Converts a word array to a UTF-8 string.
2078
+ *
2079
+ * @param {WordArray} wordArray The word array.
2080
+ *
2081
+ * @return {string} The UTF-8 string.
2082
+ *
2083
+ * @static
2084
+ *
2085
+ * @example
2086
+ *
2087
+ * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
2088
+ */stringify:function stringify(wordArray){try{return decodeURIComponent(escape(Latin1.stringify(wordArray)));}catch(e){throw new Error('Malformed UTF-8 data');}},/**
2089
+ * Converts a UTF-8 string to a word array.
2090
+ *
2091
+ * @param {string} utf8Str The UTF-8 string.
2092
+ *
2093
+ * @return {WordArray} The word array.
2094
+ *
2095
+ * @static
2096
+ *
2097
+ * @example
2098
+ *
2099
+ * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
2100
+ */parse:function parse(utf8Str){return Latin1.parse(unescape(encodeURIComponent(utf8Str)));}};/**
2101
+ * Abstract buffered block algorithm template.
2102
+ *
2103
+ * The property blockSize must be implemented in a concrete subtype.
2104
+ *
2105
+ * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
2106
+ */var BufferedBlockAlgorithm=C_lib.BufferedBlockAlgorithm=Base.extend({/**
2107
+ * Resets this block algorithm's data buffer to its initial state.
2108
+ *
2109
+ * @example
2110
+ *
2111
+ * bufferedBlockAlgorithm.reset();
2112
+ */reset:function reset(){// Initial values
2113
+ this._data=new WordArray.init();this._nDataBytes=0;},/**
2114
+ * Adds new data to this block algorithm's buffer.
2115
+ *
2116
+ * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
2117
+ *
2118
+ * @example
2119
+ *
2120
+ * bufferedBlockAlgorithm._append('data');
2121
+ * bufferedBlockAlgorithm._append(wordArray);
2122
+ */_append:function _append(data){// Convert string to WordArray, else assume WordArray already
2123
+ if(typeof data=='string'){data=Utf8.parse(data);}// Append
2124
+ this._data.concat(data);this._nDataBytes+=data.sigBytes;},/**
2125
+ * Processes available data blocks.
2126
+ *
2127
+ * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
2128
+ *
2129
+ * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
2130
+ *
2131
+ * @return {WordArray} The processed data.
2132
+ *
2133
+ * @example
2134
+ *
2135
+ * var processedData = bufferedBlockAlgorithm._process();
2136
+ * var processedData = bufferedBlockAlgorithm._process(!!'flush');
2137
+ */_process:function _process(doFlush){var processedWords;// Shortcuts
2138
+ var data=this._data;var dataWords=data.words;var dataSigBytes=data.sigBytes;var blockSize=this.blockSize;var blockSizeBytes=blockSize*4;// Count blocks ready
2139
+ var nBlocksReady=dataSigBytes/blockSizeBytes;if(doFlush){// Round up to include partial blocks
2140
+ nBlocksReady=Math.ceil(nBlocksReady);}else {// Round down to include only full blocks,
2141
+ // less the number of blocks that must remain in the buffer
2142
+ nBlocksReady=Math.max((nBlocksReady|0)-this._minBufferSize,0);}// Count words ready
2143
+ var nWordsReady=nBlocksReady*blockSize;// Count bytes ready
2144
+ var nBytesReady=Math.min(nWordsReady*4,dataSigBytes);// Process blocks
2145
+ if(nWordsReady){for(var offset=0;offset<nWordsReady;offset+=blockSize){// Perform concrete-algorithm logic
2146
+ this._doProcessBlock(dataWords,offset);}// Remove processed words
2147
+ processedWords=dataWords.splice(0,nWordsReady);data.sigBytes-=nBytesReady;}// Return processed words
2148
+ return new WordArray.init(processedWords,nBytesReady);},/**
2149
+ * Creates a copy of this object.
2150
+ *
2151
+ * @return {Object} The clone.
2152
+ *
2153
+ * @example
2154
+ *
2155
+ * var clone = bufferedBlockAlgorithm.clone();
2156
+ */clone:function clone(){var clone=Base.clone.call(this);clone._data=this._data.clone();return clone;},_minBufferSize:0});/**
2157
+ * Abstract hasher template.
2158
+ *
2159
+ * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
2160
+ */C_lib.Hasher=BufferedBlockAlgorithm.extend({/**
2161
+ * Configuration options.
2162
+ */cfg:Base.extend(),/**
2163
+ * Initializes a newly created hasher.
2164
+ *
2165
+ * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
2166
+ *
2167
+ * @example
2168
+ *
2169
+ * var hasher = CryptoJS.algo.SHA256.create();
2170
+ */init:function init(cfg){// Apply config defaults
2171
+ this.cfg=this.cfg.extend(cfg);// Set initial values
2172
+ this.reset();},/**
2173
+ * Resets this hasher to its initial state.
2174
+ *
2175
+ * @example
2176
+ *
2177
+ * hasher.reset();
2178
+ */reset:function reset(){// Reset data buffer
2179
+ BufferedBlockAlgorithm.reset.call(this);// Perform concrete-hasher logic
2180
+ this._doReset();},/**
2181
+ * Updates this hasher with a message.
2182
+ *
2183
+ * @param {WordArray|string} messageUpdate The message to append.
2184
+ *
2185
+ * @return {Hasher} This hasher.
2186
+ *
2187
+ * @example
2188
+ *
2189
+ * hasher.update('message');
2190
+ * hasher.update(wordArray);
2191
+ */update:function update(messageUpdate){// Append
2192
+ this._append(messageUpdate);// Update the hash
2193
+ this._process();// Chainable
2194
+ return this;},/**
2195
+ * Finalizes the hash computation.
2196
+ * Note that the finalize operation is effectively a destructive, read-once operation.
2197
+ *
2198
+ * @param {WordArray|string} messageUpdate (Optional) A final message update.
2199
+ *
2200
+ * @return {WordArray} The hash.
2201
+ *
2202
+ * @example
2203
+ *
2204
+ * var hash = hasher.finalize();
2205
+ * var hash = hasher.finalize('message');
2206
+ * var hash = hasher.finalize(wordArray);
2207
+ */finalize:function finalize(messageUpdate){// Final message update
2208
+ if(messageUpdate){this._append(messageUpdate);}// Perform concrete-hasher logic
2209
+ var hash=this._doFinalize();return hash;},blockSize:512/32,/**
2210
+ * Creates a shortcut function to a hasher's object interface.
2211
+ *
2212
+ * @param {Hasher} hasher The hasher to create a helper for.
2213
+ *
2214
+ * @return {Function} The shortcut function.
2215
+ *
2216
+ * @static
2217
+ *
2218
+ * @example
2219
+ *
2220
+ * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
2221
+ */_createHelper:function _createHelper(hasher){return function(message,cfg){return new hasher.init(cfg).finalize(message);};},/**
2222
+ * Creates a shortcut function to the HMAC's object interface.
2223
+ *
2224
+ * @param {Hasher} hasher The hasher to use in this HMAC helper.
2225
+ *
2226
+ * @return {Function} The shortcut function.
2227
+ *
2228
+ * @static
2229
+ *
2230
+ * @example
2231
+ *
2232
+ * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
2233
+ */_createHmacHelper:function _createHmacHelper(hasher){return function(message,key){return new C_algo.HMAC.init(hasher,key).finalize(message);};}});/**
2234
+ * Algorithm namespace.
2235
+ */var C_algo=C.algo={};return C;}(Math);return CryptoJS;});})(core);return core.exports;}
2236
+
2237
+ var encBase64 = {exports: {}};
2238
+
2239
+ var hasRequiredEncBase64;function requireEncBase64(){if(hasRequiredEncBase64)return encBase64.exports;hasRequiredEncBase64=1;(function(module,exports){(function(root,factory){{// CommonJS
2240
+ module.exports=factory(requireCore());}})(commonjsGlobal,function(CryptoJS){(function(){// Shortcuts
2241
+ var C=CryptoJS;var C_lib=C.lib;var WordArray=C_lib.WordArray;var C_enc=C.enc;/**
2242
+ * Base64 encoding strategy.
2243
+ */C_enc.Base64={/**
2244
+ * Converts a word array to a Base64 string.
2245
+ *
2246
+ * @param {WordArray} wordArray The word array.
2247
+ *
2248
+ * @return {string} The Base64 string.
2249
+ *
2250
+ * @static
2251
+ *
2252
+ * @example
2253
+ *
2254
+ * var base64String = CryptoJS.enc.Base64.stringify(wordArray);
2255
+ */stringify:function stringify(wordArray){// Shortcuts
2256
+ var words=wordArray.words;var sigBytes=wordArray.sigBytes;var map=this._map;// Clamp excess bits
2257
+ wordArray.clamp();// Convert
2258
+ var base64Chars=[];for(var i=0;i<sigBytes;i+=3){var byte1=words[i>>>2]>>>24-i%4*8&0xff;var byte2=words[i+1>>>2]>>>24-(i+1)%4*8&0xff;var byte3=words[i+2>>>2]>>>24-(i+2)%4*8&0xff;var triplet=byte1<<16|byte2<<8|byte3;for(var j=0;j<4&&i+j*0.75<sigBytes;j++){base64Chars.push(map.charAt(triplet>>>6*(3-j)&0x3f));}}// Add padding
2259
+ var paddingChar=map.charAt(64);if(paddingChar){while(base64Chars.length%4){base64Chars.push(paddingChar);}}return base64Chars.join('');},/**
2260
+ * Converts a Base64 string to a word array.
2261
+ *
2262
+ * @param {string} base64Str The Base64 string.
2263
+ *
2264
+ * @return {WordArray} The word array.
2265
+ *
2266
+ * @static
2267
+ *
2268
+ * @example
2269
+ *
2270
+ * var wordArray = CryptoJS.enc.Base64.parse(base64String);
2271
+ */parse:function parse(base64Str){// Shortcuts
2272
+ var base64StrLength=base64Str.length;var map=this._map;var reverseMap=this._reverseMap;if(!reverseMap){reverseMap=this._reverseMap=[];for(var j=0;j<map.length;j++){reverseMap[map.charCodeAt(j)]=j;}}// Ignore padding
2273
+ var paddingChar=map.charAt(64);if(paddingChar){var paddingIndex=base64Str.indexOf(paddingChar);if(paddingIndex!==-1){base64StrLength=paddingIndex;}}// Convert
2274
+ return parseLoop(base64Str,base64StrLength,reverseMap);},_map:'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='};function parseLoop(base64Str,base64StrLength,reverseMap){var words=[];var nBytes=0;for(var i=0;i<base64StrLength;i++){if(i%4){var bits1=reverseMap[base64Str.charCodeAt(i-1)]<<i%4*2;var bits2=reverseMap[base64Str.charCodeAt(i)]>>>6-i%4*2;var bitsCombined=bits1|bits2;words[nBytes>>>2]|=bitsCombined<<24-nBytes%4*8;nBytes++;}}return WordArray.create(words,nBytes);}})();return CryptoJS.enc.Base64;});})(encBase64);return encBase64.exports;}
2275
+
2276
+ var md5 = {exports: {}};
2277
+
2278
+ var hasRequiredMd5;function requireMd5(){if(hasRequiredMd5)return md5.exports;hasRequiredMd5=1;(function(module,exports){(function(root,factory){{// CommonJS
2279
+ module.exports=factory(requireCore());}})(commonjsGlobal,function(CryptoJS){(function(Math){// Shortcuts
2280
+ var C=CryptoJS;var C_lib=C.lib;var WordArray=C_lib.WordArray;var Hasher=C_lib.Hasher;var C_algo=C.algo;// Constants table
2281
+ var T=[];// Compute constants
2282
+ (function(){for(var i=0;i<64;i++){T[i]=Math.abs(Math.sin(i+1))*0x100000000|0;}})();/**
2283
+ * MD5 hash algorithm.
2284
+ */var MD5=C_algo.MD5=Hasher.extend({_doReset:function _doReset(){this._hash=new WordArray.init([0x67452301,0xefcdab89,0x98badcfe,0x10325476]);},_doProcessBlock:function _doProcessBlock(M,offset){// Swap endian
2285
+ for(var i=0;i<16;i++){// Shortcuts
2286
+ var offset_i=offset+i;var M_offset_i=M[offset_i];M[offset_i]=(M_offset_i<<8|M_offset_i>>>24)&0x00ff00ff|(M_offset_i<<24|M_offset_i>>>8)&0xff00ff00;}// Shortcuts
2287
+ var H=this._hash.words;var M_offset_0=M[offset+0];var M_offset_1=M[offset+1];var M_offset_2=M[offset+2];var M_offset_3=M[offset+3];var M_offset_4=M[offset+4];var M_offset_5=M[offset+5];var M_offset_6=M[offset+6];var M_offset_7=M[offset+7];var M_offset_8=M[offset+8];var M_offset_9=M[offset+9];var M_offset_10=M[offset+10];var M_offset_11=M[offset+11];var M_offset_12=M[offset+12];var M_offset_13=M[offset+13];var M_offset_14=M[offset+14];var M_offset_15=M[offset+15];// Working varialbes
2288
+ var a=H[0];var b=H[1];var c=H[2];var d=H[3];// Computation
2289
+ a=FF(a,b,c,d,M_offset_0,7,T[0]);d=FF(d,a,b,c,M_offset_1,12,T[1]);c=FF(c,d,a,b,M_offset_2,17,T[2]);b=FF(b,c,d,a,M_offset_3,22,T[3]);a=FF(a,b,c,d,M_offset_4,7,T[4]);d=FF(d,a,b,c,M_offset_5,12,T[5]);c=FF(c,d,a,b,M_offset_6,17,T[6]);b=FF(b,c,d,a,M_offset_7,22,T[7]);a=FF(a,b,c,d,M_offset_8,7,T[8]);d=FF(d,a,b,c,M_offset_9,12,T[9]);c=FF(c,d,a,b,M_offset_10,17,T[10]);b=FF(b,c,d,a,M_offset_11,22,T[11]);a=FF(a,b,c,d,M_offset_12,7,T[12]);d=FF(d,a,b,c,M_offset_13,12,T[13]);c=FF(c,d,a,b,M_offset_14,17,T[14]);b=FF(b,c,d,a,M_offset_15,22,T[15]);a=GG(a,b,c,d,M_offset_1,5,T[16]);d=GG(d,a,b,c,M_offset_6,9,T[17]);c=GG(c,d,a,b,M_offset_11,14,T[18]);b=GG(b,c,d,a,M_offset_0,20,T[19]);a=GG(a,b,c,d,M_offset_5,5,T[20]);d=GG(d,a,b,c,M_offset_10,9,T[21]);c=GG(c,d,a,b,M_offset_15,14,T[22]);b=GG(b,c,d,a,M_offset_4,20,T[23]);a=GG(a,b,c,d,M_offset_9,5,T[24]);d=GG(d,a,b,c,M_offset_14,9,T[25]);c=GG(c,d,a,b,M_offset_3,14,T[26]);b=GG(b,c,d,a,M_offset_8,20,T[27]);a=GG(a,b,c,d,M_offset_13,5,T[28]);d=GG(d,a,b,c,M_offset_2,9,T[29]);c=GG(c,d,a,b,M_offset_7,14,T[30]);b=GG(b,c,d,a,M_offset_12,20,T[31]);a=HH(a,b,c,d,M_offset_5,4,T[32]);d=HH(d,a,b,c,M_offset_8,11,T[33]);c=HH(c,d,a,b,M_offset_11,16,T[34]);b=HH(b,c,d,a,M_offset_14,23,T[35]);a=HH(a,b,c,d,M_offset_1,4,T[36]);d=HH(d,a,b,c,M_offset_4,11,T[37]);c=HH(c,d,a,b,M_offset_7,16,T[38]);b=HH(b,c,d,a,M_offset_10,23,T[39]);a=HH(a,b,c,d,M_offset_13,4,T[40]);d=HH(d,a,b,c,M_offset_0,11,T[41]);c=HH(c,d,a,b,M_offset_3,16,T[42]);b=HH(b,c,d,a,M_offset_6,23,T[43]);a=HH(a,b,c,d,M_offset_9,4,T[44]);d=HH(d,a,b,c,M_offset_12,11,T[45]);c=HH(c,d,a,b,M_offset_15,16,T[46]);b=HH(b,c,d,a,M_offset_2,23,T[47]);a=II(a,b,c,d,M_offset_0,6,T[48]);d=II(d,a,b,c,M_offset_7,10,T[49]);c=II(c,d,a,b,M_offset_14,15,T[50]);b=II(b,c,d,a,M_offset_5,21,T[51]);a=II(a,b,c,d,M_offset_12,6,T[52]);d=II(d,a,b,c,M_offset_3,10,T[53]);c=II(c,d,a,b,M_offset_10,15,T[54]);b=II(b,c,d,a,M_offset_1,21,T[55]);a=II(a,b,c,d,M_offset_8,6,T[56]);d=II(d,a,b,c,M_offset_15,10,T[57]);c=II(c,d,a,b,M_offset_6,15,T[58]);b=II(b,c,d,a,M_offset_13,21,T[59]);a=II(a,b,c,d,M_offset_4,6,T[60]);d=II(d,a,b,c,M_offset_11,10,T[61]);c=II(c,d,a,b,M_offset_2,15,T[62]);b=II(b,c,d,a,M_offset_9,21,T[63]);// Intermediate hash value
2290
+ H[0]=H[0]+a|0;H[1]=H[1]+b|0;H[2]=H[2]+c|0;H[3]=H[3]+d|0;},_doFinalize:function _doFinalize(){// Shortcuts
2291
+ var data=this._data;var dataWords=data.words;var nBitsTotal=this._nDataBytes*8;var nBitsLeft=data.sigBytes*8;// Add padding
2292
+ dataWords[nBitsLeft>>>5]|=0x80<<24-nBitsLeft%32;var nBitsTotalH=Math.floor(nBitsTotal/0x100000000);var nBitsTotalL=nBitsTotal;dataWords[(nBitsLeft+64>>>9<<4)+15]=(nBitsTotalH<<8|nBitsTotalH>>>24)&0x00ff00ff|(nBitsTotalH<<24|nBitsTotalH>>>8)&0xff00ff00;dataWords[(nBitsLeft+64>>>9<<4)+14]=(nBitsTotalL<<8|nBitsTotalL>>>24)&0x00ff00ff|(nBitsTotalL<<24|nBitsTotalL>>>8)&0xff00ff00;data.sigBytes=(dataWords.length+1)*4;// Hash final blocks
2293
+ this._process();// Shortcuts
2294
+ var hash=this._hash;var H=hash.words;// Swap endian
2295
+ for(var i=0;i<4;i++){// Shortcut
2296
+ var H_i=H[i];H[i]=(H_i<<8|H_i>>>24)&0x00ff00ff|(H_i<<24|H_i>>>8)&0xff00ff00;}// Return final computed hash
2297
+ return hash;},clone:function clone(){var clone=Hasher.clone.call(this);clone._hash=this._hash.clone();return clone;}});function FF(a,b,c,d,x,s,t){var n=a+(b&c|~b&d)+x+t;return (n<<s|n>>>32-s)+b;}function GG(a,b,c,d,x,s,t){var n=a+(b&d|c&~d)+x+t;return (n<<s|n>>>32-s)+b;}function HH(a,b,c,d,x,s,t){var n=a+(b^c^d)+x+t;return (n<<s|n>>>32-s)+b;}function II(a,b,c,d,x,s,t){var n=a+(c^(b|~d))+x+t;return (n<<s|n>>>32-s)+b;}/**
2298
+ * Shortcut function to the hasher's object interface.
2299
+ *
2300
+ * @param {WordArray|string} message The message to hash.
2301
+ *
2302
+ * @return {WordArray} The hash.
2303
+ *
2304
+ * @static
2305
+ *
2306
+ * @example
2307
+ *
2308
+ * var hash = CryptoJS.MD5('message');
2309
+ * var hash = CryptoJS.MD5(wordArray);
2310
+ */C.MD5=Hasher._createHelper(MD5);/**
2311
+ * Shortcut function to the HMAC's object interface.
2312
+ *
2313
+ * @param {WordArray|string} message The message to hash.
2314
+ * @param {WordArray|string} key The secret key.
2315
+ *
2316
+ * @return {WordArray} The HMAC.
2317
+ *
2318
+ * @static
2319
+ *
2320
+ * @example
2321
+ *
2322
+ * var hmac = CryptoJS.HmacMD5(message, key);
2323
+ */C.HmacMD5=Hasher._createHmacHelper(MD5);})(Math);return CryptoJS.MD5;});})(md5);return md5.exports;}
2324
+
2325
+ var evpkdf = {exports: {}};
2326
+
2327
+ var sha1 = {exports: {}};
2328
+
2329
+ var hasRequiredSha1;function requireSha1(){if(hasRequiredSha1)return sha1.exports;hasRequiredSha1=1;(function(module,exports){(function(root,factory){{// CommonJS
2330
+ module.exports=factory(requireCore());}})(commonjsGlobal,function(CryptoJS){(function(){// Shortcuts
2331
+ var C=CryptoJS;var C_lib=C.lib;var WordArray=C_lib.WordArray;var Hasher=C_lib.Hasher;var C_algo=C.algo;// Reusable object
2332
+ var W=[];/**
2333
+ * SHA-1 hash algorithm.
2334
+ */var SHA1=C_algo.SHA1=Hasher.extend({_doReset:function _doReset(){this._hash=new WordArray.init([0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0]);},_doProcessBlock:function _doProcessBlock(M,offset){// Shortcut
2335
+ var H=this._hash.words;// Working variables
2336
+ var a=H[0];var b=H[1];var c=H[2];var d=H[3];var e=H[4];// Computation
2337
+ for(var i=0;i<80;i++){if(i<16){W[i]=M[offset+i]|0;}else {var n=W[i-3]^W[i-8]^W[i-14]^W[i-16];W[i]=n<<1|n>>>31;}var t=(a<<5|a>>>27)+e+W[i];if(i<20){t+=(b&c|~b&d)+0x5a827999;}else if(i<40){t+=(b^c^d)+0x6ed9eba1;}else if(i<60){t+=(b&c|b&d|c&d)-0x70e44324;}else/* if (i < 80) */{t+=(b^c^d)-0x359d3e2a;}e=d;d=c;c=b<<30|b>>>2;b=a;a=t;}// Intermediate hash value
2338
+ H[0]=H[0]+a|0;H[1]=H[1]+b|0;H[2]=H[2]+c|0;H[3]=H[3]+d|0;H[4]=H[4]+e|0;},_doFinalize:function _doFinalize(){// Shortcuts
2339
+ var data=this._data;var dataWords=data.words;var nBitsTotal=this._nDataBytes*8;var nBitsLeft=data.sigBytes*8;// Add padding
2340
+ dataWords[nBitsLeft>>>5]|=0x80<<24-nBitsLeft%32;dataWords[(nBitsLeft+64>>>9<<4)+14]=Math.floor(nBitsTotal/0x100000000);dataWords[(nBitsLeft+64>>>9<<4)+15]=nBitsTotal;data.sigBytes=dataWords.length*4;// Hash final blocks
2341
+ this._process();// Return final computed hash
2342
+ return this._hash;},clone:function clone(){var clone=Hasher.clone.call(this);clone._hash=this._hash.clone();return clone;}});/**
2343
+ * Shortcut function to the hasher's object interface.
2344
+ *
2345
+ * @param {WordArray|string} message The message to hash.
2346
+ *
2347
+ * @return {WordArray} The hash.
2348
+ *
2349
+ * @static
2350
+ *
2351
+ * @example
2352
+ *
2353
+ * var hash = CryptoJS.SHA1('message');
2354
+ * var hash = CryptoJS.SHA1(wordArray);
2355
+ */C.SHA1=Hasher._createHelper(SHA1);/**
2356
+ * Shortcut function to the HMAC's object interface.
2357
+ *
2358
+ * @param {WordArray|string} message The message to hash.
2359
+ * @param {WordArray|string} key The secret key.
2360
+ *
2361
+ * @return {WordArray} The HMAC.
2362
+ *
2363
+ * @static
2364
+ *
2365
+ * @example
2366
+ *
2367
+ * var hmac = CryptoJS.HmacSHA1(message, key);
2368
+ */C.HmacSHA1=Hasher._createHmacHelper(SHA1);})();return CryptoJS.SHA1;});})(sha1);return sha1.exports;}
2369
+
2370
+ var hmac = {exports: {}};
2371
+
2372
+ var hasRequiredHmac;function requireHmac(){if(hasRequiredHmac)return hmac.exports;hasRequiredHmac=1;(function(module,exports){(function(root,factory){{// CommonJS
2373
+ module.exports=factory(requireCore());}})(commonjsGlobal,function(CryptoJS){(function(){// Shortcuts
2374
+ var C=CryptoJS;var C_lib=C.lib;var Base=C_lib.Base;var C_enc=C.enc;var Utf8=C_enc.Utf8;var C_algo=C.algo;/**
2375
+ * HMAC algorithm.
2376
+ */C_algo.HMAC=Base.extend({/**
2377
+ * Initializes a newly created HMAC.
2378
+ *
2379
+ * @param {Hasher} hasher The hash algorithm to use.
2380
+ * @param {WordArray|string} key The secret key.
2381
+ *
2382
+ * @example
2383
+ *
2384
+ * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
2385
+ */init:function init(hasher,key){// Init hasher
2386
+ hasher=this._hasher=new hasher.init();// Convert string to WordArray, else assume WordArray already
2387
+ if(typeof key=='string'){key=Utf8.parse(key);}// Shortcuts
2388
+ var hasherBlockSize=hasher.blockSize;var hasherBlockSizeBytes=hasherBlockSize*4;// Allow arbitrary length keys
2389
+ if(key.sigBytes>hasherBlockSizeBytes){key=hasher.finalize(key);}// Clamp excess bits
2390
+ key.clamp();// Clone key for inner and outer pads
2391
+ var oKey=this._oKey=key.clone();var iKey=this._iKey=key.clone();// Shortcuts
2392
+ var oKeyWords=oKey.words;var iKeyWords=iKey.words;// XOR keys with pad constants
2393
+ for(var i=0;i<hasherBlockSize;i++){oKeyWords[i]^=0x5c5c5c5c;iKeyWords[i]^=0x36363636;}oKey.sigBytes=iKey.sigBytes=hasherBlockSizeBytes;// Set initial values
2394
+ this.reset();},/**
2395
+ * Resets this HMAC to its initial state.
2396
+ *
2397
+ * @example
2398
+ *
2399
+ * hmacHasher.reset();
2400
+ */reset:function reset(){// Shortcut
2401
+ var hasher=this._hasher;// Reset
2402
+ hasher.reset();hasher.update(this._iKey);},/**
2403
+ * Updates this HMAC with a message.
2404
+ *
2405
+ * @param {WordArray|string} messageUpdate The message to append.
2406
+ *
2407
+ * @return {HMAC} This HMAC instance.
2408
+ *
2409
+ * @example
2410
+ *
2411
+ * hmacHasher.update('message');
2412
+ * hmacHasher.update(wordArray);
2413
+ */update:function update(messageUpdate){this._hasher.update(messageUpdate);// Chainable
2414
+ return this;},/**
2415
+ * Finalizes the HMAC computation.
2416
+ * Note that the finalize operation is effectively a destructive, read-once operation.
2417
+ *
2418
+ * @param {WordArray|string} messageUpdate (Optional) A final message update.
2419
+ *
2420
+ * @return {WordArray} The HMAC.
2421
+ *
2422
+ * @example
2423
+ *
2424
+ * var hmac = hmacHasher.finalize();
2425
+ * var hmac = hmacHasher.finalize('message');
2426
+ * var hmac = hmacHasher.finalize(wordArray);
2427
+ */finalize:function finalize(messageUpdate){// Shortcut
2428
+ var hasher=this._hasher;// Compute HMAC
2429
+ var innerHash=hasher.finalize(messageUpdate);hasher.reset();var hmac=hasher.finalize(this._oKey.clone().concat(innerHash));return hmac;}});})();});})(hmac);return hmac.exports;}
2430
+
2431
+ var hasRequiredEvpkdf;function requireEvpkdf(){if(hasRequiredEvpkdf)return evpkdf.exports;hasRequiredEvpkdf=1;(function(module,exports){(function(root,factory,undef){{// CommonJS
2432
+ module.exports=factory(requireCore(),requireSha1(),requireHmac());}})(commonjsGlobal,function(CryptoJS){(function(){// Shortcuts
2433
+ var C=CryptoJS;var C_lib=C.lib;var Base=C_lib.Base;var WordArray=C_lib.WordArray;var C_algo=C.algo;var MD5=C_algo.MD5;/**
2434
+ * This key derivation function is meant to conform with EVP_BytesToKey.
2435
+ * www.openssl.org/docs/crypto/EVP_BytesToKey.html
2436
+ */var EvpKDF=C_algo.EvpKDF=Base.extend({/**
2437
+ * Configuration options.
2438
+ *
2439
+ * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
2440
+ * @property {Hasher} hasher The hash algorithm to use. Default: MD5
2441
+ * @property {number} iterations The number of iterations to perform. Default: 1
2442
+ */cfg:Base.extend({keySize:128/32,hasher:MD5,iterations:1}),/**
2443
+ * Initializes a newly created key derivation function.
2444
+ *
2445
+ * @param {Object} cfg (Optional) The configuration options to use for the derivation.
2446
+ *
2447
+ * @example
2448
+ *
2449
+ * var kdf = CryptoJS.algo.EvpKDF.create();
2450
+ * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
2451
+ * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
2452
+ */init:function init(cfg){this.cfg=this.cfg.extend(cfg);},/**
2453
+ * Derives a key from a password.
2454
+ *
2455
+ * @param {WordArray|string} password The password.
2456
+ * @param {WordArray|string} salt A salt.
2457
+ *
2458
+ * @return {WordArray} The derived key.
2459
+ *
2460
+ * @example
2461
+ *
2462
+ * var key = kdf.compute(password, salt);
2463
+ */compute:function compute(password,salt){var block;// Shortcut
2464
+ var cfg=this.cfg;// Init hasher
2465
+ var hasher=cfg.hasher.create();// Initial values
2466
+ var derivedKey=WordArray.create();// Shortcuts
2467
+ var derivedKeyWords=derivedKey.words;var keySize=cfg.keySize;var iterations=cfg.iterations;// Generate key
2468
+ while(derivedKeyWords.length<keySize){if(block){hasher.update(block);}block=hasher.update(password).finalize(salt);hasher.reset();// Iterations
2469
+ for(var i=1;i<iterations;i++){block=hasher.finalize(block);hasher.reset();}derivedKey.concat(block);}derivedKey.sigBytes=keySize*4;return derivedKey;}});/**
2470
+ * Derives a key from a password.
2471
+ *
2472
+ * @param {WordArray|string} password The password.
2473
+ * @param {WordArray|string} salt A salt.
2474
+ * @param {Object} cfg (Optional) The configuration options to use for this computation.
2475
+ *
2476
+ * @return {WordArray} The derived key.
2477
+ *
2478
+ * @static
2479
+ *
2480
+ * @example
2481
+ *
2482
+ * var key = CryptoJS.EvpKDF(password, salt);
2483
+ * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
2484
+ * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
2485
+ */C.EvpKDF=function(password,salt,cfg){return EvpKDF.create(cfg).compute(password,salt);};})();return CryptoJS.EvpKDF;});})(evpkdf);return evpkdf.exports;}
2486
+
2487
+ var cipherCore = {exports: {}};
2488
+
2489
+ var hasRequiredCipherCore;function requireCipherCore(){if(hasRequiredCipherCore)return cipherCore.exports;hasRequiredCipherCore=1;(function(module,exports){(function(root,factory,undef){{// CommonJS
2490
+ module.exports=factory(requireCore(),requireEvpkdf());}})(commonjsGlobal,function(CryptoJS){/**
2491
+ * Cipher core components.
2492
+ */CryptoJS.lib.Cipher||function(undefined$1){// Shortcuts
2493
+ var C=CryptoJS;var C_lib=C.lib;var Base=C_lib.Base;var WordArray=C_lib.WordArray;var BufferedBlockAlgorithm=C_lib.BufferedBlockAlgorithm;var C_enc=C.enc;C_enc.Utf8;var Base64=C_enc.Base64;var C_algo=C.algo;var EvpKDF=C_algo.EvpKDF;/**
2494
+ * Abstract base cipher template.
2495
+ *
2496
+ * @property {number} keySize This cipher's key size. Default: 4 (128 bits)
2497
+ * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
2498
+ * @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
2499
+ * @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
2500
+ */var Cipher=C_lib.Cipher=BufferedBlockAlgorithm.extend({/**
2501
+ * Configuration options.
2502
+ *
2503
+ * @property {WordArray} iv The IV to use for this operation.
2504
+ */cfg:Base.extend(),/**
2505
+ * Creates this cipher in encryption mode.
2506
+ *
2507
+ * @param {WordArray} key The key.
2508
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2509
+ *
2510
+ * @return {Cipher} A cipher instance.
2511
+ *
2512
+ * @static
2513
+ *
2514
+ * @example
2515
+ *
2516
+ * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
2517
+ */createEncryptor:function createEncryptor(key,cfg){return this.create(this._ENC_XFORM_MODE,key,cfg);},/**
2518
+ * Creates this cipher in decryption mode.
2519
+ *
2520
+ * @param {WordArray} key The key.
2521
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2522
+ *
2523
+ * @return {Cipher} A cipher instance.
2524
+ *
2525
+ * @static
2526
+ *
2527
+ * @example
2528
+ *
2529
+ * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
2530
+ */createDecryptor:function createDecryptor(key,cfg){return this.create(this._DEC_XFORM_MODE,key,cfg);},/**
2531
+ * Initializes a newly created cipher.
2532
+ *
2533
+ * @param {number} xformMode Either the encryption or decryption transormation mode constant.
2534
+ * @param {WordArray} key The key.
2535
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2536
+ *
2537
+ * @example
2538
+ *
2539
+ * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
2540
+ */init:function init(xformMode,key,cfg){// Apply config defaults
2541
+ this.cfg=this.cfg.extend(cfg);// Store transform mode and key
2542
+ this._xformMode=xformMode;this._key=key;// Set initial values
2543
+ this.reset();},/**
2544
+ * Resets this cipher to its initial state.
2545
+ *
2546
+ * @example
2547
+ *
2548
+ * cipher.reset();
2549
+ */reset:function reset(){// Reset data buffer
2550
+ BufferedBlockAlgorithm.reset.call(this);// Perform concrete-cipher logic
2551
+ this._doReset();},/**
2552
+ * Adds data to be encrypted or decrypted.
2553
+ *
2554
+ * @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
2555
+ *
2556
+ * @return {WordArray} The data after processing.
2557
+ *
2558
+ * @example
2559
+ *
2560
+ * var encrypted = cipher.process('data');
2561
+ * var encrypted = cipher.process(wordArray);
2562
+ */process:function process(dataUpdate){// Append
2563
+ this._append(dataUpdate);// Process available blocks
2564
+ return this._process();},/**
2565
+ * Finalizes the encryption or decryption process.
2566
+ * Note that the finalize operation is effectively a destructive, read-once operation.
2567
+ *
2568
+ * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
2569
+ *
2570
+ * @return {WordArray} The data after final processing.
2571
+ *
2572
+ * @example
2573
+ *
2574
+ * var encrypted = cipher.finalize();
2575
+ * var encrypted = cipher.finalize('data');
2576
+ * var encrypted = cipher.finalize(wordArray);
2577
+ */finalize:function finalize(dataUpdate){// Final data update
2578
+ if(dataUpdate){this._append(dataUpdate);}// Perform concrete-cipher logic
2579
+ var finalProcessedData=this._doFinalize();return finalProcessedData;},keySize:128/32,ivSize:128/32,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,/**
2580
+ * Creates shortcut functions to a cipher's object interface.
2581
+ *
2582
+ * @param {Cipher} cipher The cipher to create a helper for.
2583
+ *
2584
+ * @return {Object} An object with encrypt and decrypt shortcut functions.
2585
+ *
2586
+ * @static
2587
+ *
2588
+ * @example
2589
+ *
2590
+ * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
2591
+ */_createHelper:function(){function selectCipherStrategy(key){if(typeof key=='string'){return PasswordBasedCipher;}else {return SerializableCipher;}}return function(cipher){return {encrypt:function encrypt(message,key,cfg){return selectCipherStrategy(key).encrypt(cipher,message,key,cfg);},decrypt:function decrypt(ciphertext,key,cfg){return selectCipherStrategy(key).decrypt(cipher,ciphertext,key,cfg);}};};}()});/**
2592
+ * Abstract base stream cipher template.
2593
+ *
2594
+ * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
2595
+ */C_lib.StreamCipher=Cipher.extend({_doFinalize:function _doFinalize(){// Process partial blocks
2596
+ var finalProcessedBlocks=this._process(!!'flush');return finalProcessedBlocks;},blockSize:1});/**
2597
+ * Mode namespace.
2598
+ */var C_mode=C.mode={};/**
2599
+ * Abstract base block cipher mode template.
2600
+ */var BlockCipherMode=C_lib.BlockCipherMode=Base.extend({/**
2601
+ * Creates this mode for encryption.
2602
+ *
2603
+ * @param {Cipher} cipher A block cipher instance.
2604
+ * @param {Array} iv The IV words.
2605
+ *
2606
+ * @static
2607
+ *
2608
+ * @example
2609
+ *
2610
+ * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
2611
+ */createEncryptor:function createEncryptor(cipher,iv){return this.Encryptor.create(cipher,iv);},/**
2612
+ * Creates this mode for decryption.
2613
+ *
2614
+ * @param {Cipher} cipher A block cipher instance.
2615
+ * @param {Array} iv The IV words.
2616
+ *
2617
+ * @static
2618
+ *
2619
+ * @example
2620
+ *
2621
+ * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
2622
+ */createDecryptor:function createDecryptor(cipher,iv){return this.Decryptor.create(cipher,iv);},/**
2623
+ * Initializes a newly created mode.
2624
+ *
2625
+ * @param {Cipher} cipher A block cipher instance.
2626
+ * @param {Array} iv The IV words.
2627
+ *
2628
+ * @example
2629
+ *
2630
+ * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
2631
+ */init:function init(cipher,iv){this._cipher=cipher;this._iv=iv;}});/**
2632
+ * Cipher Block Chaining mode.
2633
+ */var CBC=C_mode.CBC=function(){/**
2634
+ * Abstract base CBC mode.
2635
+ */var CBC=BlockCipherMode.extend();/**
2636
+ * CBC encryptor.
2637
+ */CBC.Encryptor=CBC.extend({/**
2638
+ * Processes the data block at offset.
2639
+ *
2640
+ * @param {Array} words The data words to operate on.
2641
+ * @param {number} offset The offset where the block starts.
2642
+ *
2643
+ * @example
2644
+ *
2645
+ * mode.processBlock(data.words, offset);
2646
+ */processBlock:function processBlock(words,offset){// Shortcuts
2647
+ var cipher=this._cipher;var blockSize=cipher.blockSize;// XOR and encrypt
2648
+ xorBlock.call(this,words,offset,blockSize);cipher.encryptBlock(words,offset);// Remember this block to use with next block
2649
+ this._prevBlock=words.slice(offset,offset+blockSize);}});/**
2650
+ * CBC decryptor.
2651
+ */CBC.Decryptor=CBC.extend({/**
2652
+ * Processes the data block at offset.
2653
+ *
2654
+ * @param {Array} words The data words to operate on.
2655
+ * @param {number} offset The offset where the block starts.
2656
+ *
2657
+ * @example
2658
+ *
2659
+ * mode.processBlock(data.words, offset);
2660
+ */processBlock:function processBlock(words,offset){// Shortcuts
2661
+ var cipher=this._cipher;var blockSize=cipher.blockSize;// Remember this block to use with next block
2662
+ var thisBlock=words.slice(offset,offset+blockSize);// Decrypt and XOR
2663
+ cipher.decryptBlock(words,offset);xorBlock.call(this,words,offset,blockSize);// This block becomes the previous block
2664
+ this._prevBlock=thisBlock;}});function xorBlock(words,offset,blockSize){var block;// Shortcut
2665
+ var iv=this._iv;// Choose mixing block
2666
+ if(iv){block=iv;// Remove IV for subsequent blocks
2667
+ this._iv=undefined$1;}else {block=this._prevBlock;}// XOR blocks
2668
+ for(var i=0;i<blockSize;i++){words[offset+i]^=block[i];}}return CBC;}();/**
2669
+ * Padding namespace.
2670
+ */var C_pad=C.pad={};/**
2671
+ * PKCS #5/7 padding strategy.
2672
+ */var Pkcs7=C_pad.Pkcs7={/**
2673
+ * Pads data using the algorithm defined in PKCS #5/7.
2674
+ *
2675
+ * @param {WordArray} data The data to pad.
2676
+ * @param {number} blockSize The multiple that the data should be padded to.
2677
+ *
2678
+ * @static
2679
+ *
2680
+ * @example
2681
+ *
2682
+ * CryptoJS.pad.Pkcs7.pad(wordArray, 4);
2683
+ */pad:function pad(data,blockSize){// Shortcut
2684
+ var blockSizeBytes=blockSize*4;// Count padding bytes
2685
+ var nPaddingBytes=blockSizeBytes-data.sigBytes%blockSizeBytes;// Create padding word
2686
+ var paddingWord=nPaddingBytes<<24|nPaddingBytes<<16|nPaddingBytes<<8|nPaddingBytes;// Create padding
2687
+ var paddingWords=[];for(var i=0;i<nPaddingBytes;i+=4){paddingWords.push(paddingWord);}var padding=WordArray.create(paddingWords,nPaddingBytes);// Add padding
2688
+ data.concat(padding);},/**
2689
+ * Unpads data that had been padded using the algorithm defined in PKCS #5/7.
2690
+ *
2691
+ * @param {WordArray} data The data to unpad.
2692
+ *
2693
+ * @static
2694
+ *
2695
+ * @example
2696
+ *
2697
+ * CryptoJS.pad.Pkcs7.unpad(wordArray);
2698
+ */unpad:function unpad(data){// Get number of padding bytes from last byte
2699
+ var nPaddingBytes=data.words[data.sigBytes-1>>>2]&0xff;// Remove padding
2700
+ data.sigBytes-=nPaddingBytes;}};/**
2701
+ * Abstract base block cipher template.
2702
+ *
2703
+ * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
2704
+ */C_lib.BlockCipher=Cipher.extend({/**
2705
+ * Configuration options.
2706
+ *
2707
+ * @property {Mode} mode The block mode to use. Default: CBC
2708
+ * @property {Padding} padding The padding strategy to use. Default: Pkcs7
2709
+ */cfg:Cipher.cfg.extend({mode:CBC,padding:Pkcs7}),reset:function reset(){var modeCreator;// Reset cipher
2710
+ Cipher.reset.call(this);// Shortcuts
2711
+ var cfg=this.cfg;var iv=cfg.iv;var mode=cfg.mode;// Reset block mode
2712
+ if(this._xformMode==this._ENC_XFORM_MODE){modeCreator=mode.createEncryptor;}else/* if (this._xformMode == this._DEC_XFORM_MODE) */{modeCreator=mode.createDecryptor;// Keep at least one block in the buffer for unpadding
2713
+ this._minBufferSize=1;}if(this._mode&&this._mode.__creator==modeCreator){this._mode.init(this,iv&&iv.words);}else {this._mode=modeCreator.call(mode,this,iv&&iv.words);this._mode.__creator=modeCreator;}},_doProcessBlock:function _doProcessBlock(words,offset){this._mode.processBlock(words,offset);},_doFinalize:function _doFinalize(){var finalProcessedBlocks;// Shortcut
2714
+ var padding=this.cfg.padding;// Finalize
2715
+ if(this._xformMode==this._ENC_XFORM_MODE){// Pad data
2716
+ padding.pad(this._data,this.blockSize);// Process final blocks
2717
+ finalProcessedBlocks=this._process(!!'flush');}else/* if (this._xformMode == this._DEC_XFORM_MODE) */{// Process final blocks
2718
+ finalProcessedBlocks=this._process(!!'flush');// Unpad data
2719
+ padding.unpad(finalProcessedBlocks);}return finalProcessedBlocks;},blockSize:128/32});/**
2720
+ * A collection of cipher parameters.
2721
+ *
2722
+ * @property {WordArray} ciphertext The raw ciphertext.
2723
+ * @property {WordArray} key The key to this ciphertext.
2724
+ * @property {WordArray} iv The IV used in the ciphering operation.
2725
+ * @property {WordArray} salt The salt used with a key derivation function.
2726
+ * @property {Cipher} algorithm The cipher algorithm.
2727
+ * @property {Mode} mode The block mode used in the ciphering operation.
2728
+ * @property {Padding} padding The padding scheme used in the ciphering operation.
2729
+ * @property {number} blockSize The block size of the cipher.
2730
+ * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
2731
+ */var CipherParams=C_lib.CipherParams=Base.extend({/**
2732
+ * Initializes a newly created cipher params object.
2733
+ *
2734
+ * @param {Object} cipherParams An object with any of the possible cipher parameters.
2735
+ *
2736
+ * @example
2737
+ *
2738
+ * var cipherParams = CryptoJS.lib.CipherParams.create({
2739
+ * ciphertext: ciphertextWordArray,
2740
+ * key: keyWordArray,
2741
+ * iv: ivWordArray,
2742
+ * salt: saltWordArray,
2743
+ * algorithm: CryptoJS.algo.AES,
2744
+ * mode: CryptoJS.mode.CBC,
2745
+ * padding: CryptoJS.pad.PKCS7,
2746
+ * blockSize: 4,
2747
+ * formatter: CryptoJS.format.OpenSSL
2748
+ * });
2749
+ */init:function init(cipherParams){this.mixIn(cipherParams);},/**
2750
+ * Converts this cipher params object to a string.
2751
+ *
2752
+ * @param {Format} formatter (Optional) The formatting strategy to use.
2753
+ *
2754
+ * @return {string} The stringified cipher params.
2755
+ *
2756
+ * @throws Error If neither the formatter nor the default formatter is set.
2757
+ *
2758
+ * @example
2759
+ *
2760
+ * var string = cipherParams + '';
2761
+ * var string = cipherParams.toString();
2762
+ * var string = cipherParams.toString(CryptoJS.format.OpenSSL);
2763
+ */toString:function toString(formatter){return (formatter||this.formatter).stringify(this);}});/**
2764
+ * Format namespace.
2765
+ */var C_format=C.format={};/**
2766
+ * OpenSSL formatting strategy.
2767
+ */var OpenSSLFormatter=C_format.OpenSSL={/**
2768
+ * Converts a cipher params object to an OpenSSL-compatible string.
2769
+ *
2770
+ * @param {CipherParams} cipherParams The cipher params object.
2771
+ *
2772
+ * @return {string} The OpenSSL-compatible string.
2773
+ *
2774
+ * @static
2775
+ *
2776
+ * @example
2777
+ *
2778
+ * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
2779
+ */stringify:function stringify(cipherParams){var wordArray;// Shortcuts
2780
+ var ciphertext=cipherParams.ciphertext;var salt=cipherParams.salt;// Format
2781
+ if(salt){wordArray=WordArray.create([0x53616c74,0x65645f5f]).concat(salt).concat(ciphertext);}else {wordArray=ciphertext;}return wordArray.toString(Base64);},/**
2782
+ * Converts an OpenSSL-compatible string to a cipher params object.
2783
+ *
2784
+ * @param {string} openSSLStr The OpenSSL-compatible string.
2785
+ *
2786
+ * @return {CipherParams} The cipher params object.
2787
+ *
2788
+ * @static
2789
+ *
2790
+ * @example
2791
+ *
2792
+ * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
2793
+ */parse:function parse(openSSLStr){var salt;// Parse base64
2794
+ var ciphertext=Base64.parse(openSSLStr);// Shortcut
2795
+ var ciphertextWords=ciphertext.words;// Test for salt
2796
+ if(ciphertextWords[0]==0x53616c74&&ciphertextWords[1]==0x65645f5f){// Extract salt
2797
+ salt=WordArray.create(ciphertextWords.slice(2,4));// Remove salt from ciphertext
2798
+ ciphertextWords.splice(0,4);ciphertext.sigBytes-=16;}return CipherParams.create({ciphertext:ciphertext,salt:salt});}};/**
2799
+ * A cipher wrapper that returns ciphertext as a serializable cipher params object.
2800
+ */var SerializableCipher=C_lib.SerializableCipher=Base.extend({/**
2801
+ * Configuration options.
2802
+ *
2803
+ * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
2804
+ */cfg:Base.extend({format:OpenSSLFormatter}),/**
2805
+ * Encrypts a message.
2806
+ *
2807
+ * @param {Cipher} cipher The cipher algorithm to use.
2808
+ * @param {WordArray|string} message The message to encrypt.
2809
+ * @param {WordArray} key The key.
2810
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2811
+ *
2812
+ * @return {CipherParams} A cipher params object.
2813
+ *
2814
+ * @static
2815
+ *
2816
+ * @example
2817
+ *
2818
+ * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
2819
+ * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
2820
+ * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
2821
+ */encrypt:function encrypt(cipher,message,key,cfg){// Apply config defaults
2822
+ cfg=this.cfg.extend(cfg);// Encrypt
2823
+ var encryptor=cipher.createEncryptor(key,cfg);var ciphertext=encryptor.finalize(message);// Shortcut
2824
+ var cipherCfg=encryptor.cfg;// Create and return serializable cipher params
2825
+ return CipherParams.create({ciphertext:ciphertext,key:key,iv:cipherCfg.iv,algorithm:cipher,mode:cipherCfg.mode,padding:cipherCfg.padding,blockSize:cipher.blockSize,formatter:cfg.format});},/**
2826
+ * Decrypts serialized ciphertext.
2827
+ *
2828
+ * @param {Cipher} cipher The cipher algorithm to use.
2829
+ * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
2830
+ * @param {WordArray} key The key.
2831
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2832
+ *
2833
+ * @return {WordArray} The plaintext.
2834
+ *
2835
+ * @static
2836
+ *
2837
+ * @example
2838
+ *
2839
+ * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
2840
+ * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
2841
+ */decrypt:function decrypt(cipher,ciphertext,key,cfg){// Apply config defaults
2842
+ cfg=this.cfg.extend(cfg);// Convert string to CipherParams
2843
+ ciphertext=this._parse(ciphertext,cfg.format);// Decrypt
2844
+ var plaintext=cipher.createDecryptor(key,cfg).finalize(ciphertext.ciphertext);return plaintext;},/**
2845
+ * Converts serialized ciphertext to CipherParams,
2846
+ * else assumed CipherParams already and returns ciphertext unchanged.
2847
+ *
2848
+ * @param {CipherParams|string} ciphertext The ciphertext.
2849
+ * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
2850
+ *
2851
+ * @return {CipherParams} The unserialized ciphertext.
2852
+ *
2853
+ * @static
2854
+ *
2855
+ * @example
2856
+ *
2857
+ * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
2858
+ */_parse:function _parse(ciphertext,format){if(typeof ciphertext=='string'){return format.parse(ciphertext,this);}else {return ciphertext;}}});/**
2859
+ * Key derivation function namespace.
2860
+ */var C_kdf=C.kdf={};/**
2861
+ * OpenSSL key derivation function.
2862
+ */var OpenSSLKdf=C_kdf.OpenSSL={/**
2863
+ * Derives a key and IV from a password.
2864
+ *
2865
+ * @param {string} password The password to derive from.
2866
+ * @param {number} keySize The size in words of the key to generate.
2867
+ * @param {number} ivSize The size in words of the IV to generate.
2868
+ * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
2869
+ *
2870
+ * @return {CipherParams} A cipher params object with the key, IV, and salt.
2871
+ *
2872
+ * @static
2873
+ *
2874
+ * @example
2875
+ *
2876
+ * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
2877
+ * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
2878
+ */execute:function execute(password,keySize,ivSize,salt){// Generate random salt
2879
+ if(!salt){salt=WordArray.random(64/8);}// Derive key and IV
2880
+ var key=EvpKDF.create({keySize:keySize+ivSize}).compute(password,salt);// Separate key and IV
2881
+ var iv=WordArray.create(key.words.slice(keySize),ivSize*4);key.sigBytes=keySize*4;// Return params
2882
+ return CipherParams.create({key:key,iv:iv,salt:salt});}};/**
2883
+ * A serializable cipher wrapper that derives the key from a password,
2884
+ * and returns ciphertext as a serializable cipher params object.
2885
+ */var PasswordBasedCipher=C_lib.PasswordBasedCipher=SerializableCipher.extend({/**
2886
+ * Configuration options.
2887
+ *
2888
+ * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
2889
+ */cfg:SerializableCipher.cfg.extend({kdf:OpenSSLKdf}),/**
2890
+ * Encrypts a message using a password.
2891
+ *
2892
+ * @param {Cipher} cipher The cipher algorithm to use.
2893
+ * @param {WordArray|string} message The message to encrypt.
2894
+ * @param {string} password The password.
2895
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2896
+ *
2897
+ * @return {CipherParams} A cipher params object.
2898
+ *
2899
+ * @static
2900
+ *
2901
+ * @example
2902
+ *
2903
+ * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
2904
+ * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
2905
+ */encrypt:function encrypt(cipher,message,password,cfg){// Apply config defaults
2906
+ cfg=this.cfg.extend(cfg);// Derive key and other params
2907
+ var derivedParams=cfg.kdf.execute(password,cipher.keySize,cipher.ivSize);// Add IV to config
2908
+ cfg.iv=derivedParams.iv;// Encrypt
2909
+ var ciphertext=SerializableCipher.encrypt.call(this,cipher,message,derivedParams.key,cfg);// Mix in derived params
2910
+ ciphertext.mixIn(derivedParams);return ciphertext;},/**
2911
+ * Decrypts serialized ciphertext using a password.
2912
+ *
2913
+ * @param {Cipher} cipher The cipher algorithm to use.
2914
+ * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
2915
+ * @param {string} password The password.
2916
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2917
+ *
2918
+ * @return {WordArray} The plaintext.
2919
+ *
2920
+ * @static
2921
+ *
2922
+ * @example
2923
+ *
2924
+ * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
2925
+ * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
2926
+ */decrypt:function decrypt(cipher,ciphertext,password,cfg){// Apply config defaults
2927
+ cfg=this.cfg.extend(cfg);// Convert string to CipherParams
2928
+ ciphertext=this._parse(ciphertext,cfg.format);// Derive key and other params
2929
+ var derivedParams=cfg.kdf.execute(password,cipher.keySize,cipher.ivSize,ciphertext.salt);// Add IV to config
2930
+ cfg.iv=derivedParams.iv;// Decrypt
2931
+ var plaintext=SerializableCipher.decrypt.call(this,cipher,ciphertext,derivedParams.key,cfg);return plaintext;}});}();});})(cipherCore);return cipherCore.exports;}
2932
+
2933
+ (function(module,exports){(function(root,factory,undef){{// CommonJS
2934
+ module.exports=factory(requireCore(),requireEncBase64(),requireMd5(),requireEvpkdf(),requireCipherCore());}})(commonjsGlobal,function(CryptoJS){(function(){// Shortcuts
2935
+ var C=CryptoJS;var C_lib=C.lib;var BlockCipher=C_lib.BlockCipher;var C_algo=C.algo;// Lookup tables
2936
+ var SBOX=[];var INV_SBOX=[];var SUB_MIX_0=[];var SUB_MIX_1=[];var SUB_MIX_2=[];var SUB_MIX_3=[];var INV_SUB_MIX_0=[];var INV_SUB_MIX_1=[];var INV_SUB_MIX_2=[];var INV_SUB_MIX_3=[];// Compute lookup tables
2937
+ (function(){// Compute double table
2938
+ var d=[];for(var i=0;i<256;i++){if(i<128){d[i]=i<<1;}else {d[i]=i<<1^0x11b;}}// Walk GF(2^8)
2939
+ var x=0;var xi=0;for(var i=0;i<256;i++){// Compute sbox
2940
+ var sx=xi^xi<<1^xi<<2^xi<<3^xi<<4;sx=sx>>>8^sx&0xff^0x63;SBOX[x]=sx;INV_SBOX[sx]=x;// Compute multiplication
2941
+ var x2=d[x];var x4=d[x2];var x8=d[x4];// Compute sub bytes, mix columns tables
2942
+ var t=d[sx]*0x101^sx*0x1010100;SUB_MIX_0[x]=t<<24|t>>>8;SUB_MIX_1[x]=t<<16|t>>>16;SUB_MIX_2[x]=t<<8|t>>>24;SUB_MIX_3[x]=t;// Compute inv sub bytes, inv mix columns tables
2943
+ var t=x8*0x1010101^x4*0x10001^x2*0x101^x*0x1010100;INV_SUB_MIX_0[sx]=t<<24|t>>>8;INV_SUB_MIX_1[sx]=t<<16|t>>>16;INV_SUB_MIX_2[sx]=t<<8|t>>>24;INV_SUB_MIX_3[sx]=t;// Compute next counter
2944
+ if(!x){x=xi=1;}else {x=x2^d[d[d[x8^x2]]];xi^=d[d[xi]];}}})();// Precomputed Rcon lookup
2945
+ var RCON=[0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36];/**
2946
+ * AES block cipher algorithm.
2947
+ */var AES=C_algo.AES=BlockCipher.extend({_doReset:function _doReset(){var t;// Skip reset of nRounds has been set before and key did not change
2948
+ if(this._nRounds&&this._keyPriorReset===this._key){return;}// Shortcuts
2949
+ var key=this._keyPriorReset=this._key;var keyWords=key.words;var keySize=key.sigBytes/4;// Compute number of rounds
2950
+ var nRounds=this._nRounds=keySize+6;// Compute number of key schedule rows
2951
+ var ksRows=(nRounds+1)*4;// Compute key schedule
2952
+ var keySchedule=this._keySchedule=[];for(var ksRow=0;ksRow<ksRows;ksRow++){if(ksRow<keySize){keySchedule[ksRow]=keyWords[ksRow];}else {t=keySchedule[ksRow-1];if(!(ksRow%keySize)){// Rot word
2953
+ t=t<<8|t>>>24;// Sub word
2954
+ t=SBOX[t>>>24]<<24|SBOX[t>>>16&0xff]<<16|SBOX[t>>>8&0xff]<<8|SBOX[t&0xff];// Mix Rcon
2955
+ t^=RCON[ksRow/keySize|0]<<24;}else if(keySize>6&&ksRow%keySize==4){// Sub word
2956
+ t=SBOX[t>>>24]<<24|SBOX[t>>>16&0xff]<<16|SBOX[t>>>8&0xff]<<8|SBOX[t&0xff];}keySchedule[ksRow]=keySchedule[ksRow-keySize]^t;}}// Compute inv key schedule
2957
+ var invKeySchedule=this._invKeySchedule=[];for(var invKsRow=0;invKsRow<ksRows;invKsRow++){var ksRow=ksRows-invKsRow;if(invKsRow%4){var t=keySchedule[ksRow];}else {var t=keySchedule[ksRow-4];}if(invKsRow<4||ksRow<=4){invKeySchedule[invKsRow]=t;}else {invKeySchedule[invKsRow]=INV_SUB_MIX_0[SBOX[t>>>24]]^INV_SUB_MIX_1[SBOX[t>>>16&0xff]]^INV_SUB_MIX_2[SBOX[t>>>8&0xff]]^INV_SUB_MIX_3[SBOX[t&0xff]];}}},encryptBlock:function encryptBlock(M,offset){this._doCryptBlock(M,offset,this._keySchedule,SUB_MIX_0,SUB_MIX_1,SUB_MIX_2,SUB_MIX_3,SBOX);},decryptBlock:function decryptBlock(M,offset){// Swap 2nd and 4th rows
2958
+ var t=M[offset+1];M[offset+1]=M[offset+3];M[offset+3]=t;this._doCryptBlock(M,offset,this._invKeySchedule,INV_SUB_MIX_0,INV_SUB_MIX_1,INV_SUB_MIX_2,INV_SUB_MIX_3,INV_SBOX);// Inv swap 2nd and 4th rows
2959
+ var t=M[offset+1];M[offset+1]=M[offset+3];M[offset+3]=t;},_doCryptBlock:function _doCryptBlock(M,offset,keySchedule,SUB_MIX_0,SUB_MIX_1,SUB_MIX_2,SUB_MIX_3,SBOX){// Shortcut
2960
+ var nRounds=this._nRounds;// Get input, add round key
2961
+ var s0=M[offset]^keySchedule[0];var s1=M[offset+1]^keySchedule[1];var s2=M[offset+2]^keySchedule[2];var s3=M[offset+3]^keySchedule[3];// Key schedule row counter
2962
+ var ksRow=4;// Rounds
2963
+ for(var round=1;round<nRounds;round++){// Shift rows, sub bytes, mix columns, add round key
2964
+ var t0=SUB_MIX_0[s0>>>24]^SUB_MIX_1[s1>>>16&0xff]^SUB_MIX_2[s2>>>8&0xff]^SUB_MIX_3[s3&0xff]^keySchedule[ksRow++];var t1=SUB_MIX_0[s1>>>24]^SUB_MIX_1[s2>>>16&0xff]^SUB_MIX_2[s3>>>8&0xff]^SUB_MIX_3[s0&0xff]^keySchedule[ksRow++];var t2=SUB_MIX_0[s2>>>24]^SUB_MIX_1[s3>>>16&0xff]^SUB_MIX_2[s0>>>8&0xff]^SUB_MIX_3[s1&0xff]^keySchedule[ksRow++];var t3=SUB_MIX_0[s3>>>24]^SUB_MIX_1[s0>>>16&0xff]^SUB_MIX_2[s1>>>8&0xff]^SUB_MIX_3[s2&0xff]^keySchedule[ksRow++];// Update state
2965
+ s0=t0;s1=t1;s2=t2;s3=t3;}// Shift rows, sub bytes, add round key
2966
+ var t0=(SBOX[s0>>>24]<<24|SBOX[s1>>>16&0xff]<<16|SBOX[s2>>>8&0xff]<<8|SBOX[s3&0xff])^keySchedule[ksRow++];var t1=(SBOX[s1>>>24]<<24|SBOX[s2>>>16&0xff]<<16|SBOX[s3>>>8&0xff]<<8|SBOX[s0&0xff])^keySchedule[ksRow++];var t2=(SBOX[s2>>>24]<<24|SBOX[s3>>>16&0xff]<<16|SBOX[s0>>>8&0xff]<<8|SBOX[s1&0xff])^keySchedule[ksRow++];var t3=(SBOX[s3>>>24]<<24|SBOX[s0>>>16&0xff]<<16|SBOX[s1>>>8&0xff]<<8|SBOX[s2&0xff])^keySchedule[ksRow++];// Set output
2967
+ M[offset]=t0;M[offset+1]=t1;M[offset+2]=t2;M[offset+3]=t3;},keySize:256/32});/**
2968
+ * Shortcut functions to the cipher's object interface.
2969
+ *
2970
+ * @example
2971
+ *
2972
+ * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
2973
+ * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
2974
+ */C.AES=BlockCipher._createHelper(AES);})();return CryptoJS.AES;});})(aes);var aesExports=aes.exports;var AES = /*@__PURE__*/getDefaultExportFromCjs(aesExports);
2975
+
2976
+ var encUtf8 = {exports: {}};
2977
+
2978
+ (function(module,exports){(function(root,factory){{// CommonJS
2979
+ module.exports=factory(requireCore());}})(commonjsGlobal,function(CryptoJS){return CryptoJS.enc.Utf8;});})(encUtf8);var encUtf8Exports=encUtf8.exports;var Utf8 = /*@__PURE__*/getDefaultExportFromCjs(encUtf8Exports);
2980
+
2981
+ var ENCRYPTION_PREFIX_V1='RudderEncrypt:';var ENCRYPTION_KEY_V1='Rudder';
2982
+
2983
+ var encrypt=function encrypt(value){return "".concat(ENCRYPTION_PREFIX_V1).concat(AES.encrypt(value,ENCRYPTION_KEY_V1).toString());};var decrypt=function decrypt(value){if(value.startsWith(ENCRYPTION_PREFIX_V1)){return AES.decrypt(value.substring(ENCRYPTION_PREFIX_V1.length),ENCRYPTION_KEY_V1).toString(Utf8);}return value;};
2984
+
2985
+ var pluginName$2='StorageEncryptionLegacy';var StorageEncryptionLegacy=function StorageEncryptionLegacy(){return {name:pluginName$2,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$2]);},storage:{encrypt:function encrypt$1(value){return encrypt(value);},decrypt:function decrypt$1(value){return decrypt(value);}}};};
2986
+
2987
+ var STORAGE_MIGRATOR_PLUGIN='StorageMigrator';
2988
+
2989
+ var pluginName$1='StorageMigrator';var StorageMigrator=function StorageMigrator(){return {name:pluginName$1,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$1]);},storage:{migrate:function migrate(key,storageEngine,logger){try{var storedVal=storageEngine.getItem(key);if(isNullOrUndefined(storedVal)){return null;}var decryptedVal=decrypt(storedVal);// The value is not encrypted using legacy encryption
2990
+ // Try latest
2991
+ if(decryptedVal===storedVal){decryptedVal=decrypt$1(storedVal);}if(isNullOrUndefined(decryptedVal)){return null;}// storejs that is used in localstorage engine already deserializes json strings but swallows errors
2992
+ return JSON.parse(decryptedVal);}catch(err){logger===null||logger===void 0?void 0:logger.error(STORAGE_MIGRATION_ERROR(STORAGE_MIGRATOR_PLUGIN,key),err);return null;}}}};};
2993
+
2994
+ var isErrRetryable=function isErrRetryable(details){var isRetryableNWFailure=false;if(details!==null&&details!==void 0&&details.error&&details!==null&&details!==void 0&&details.xhr){var xhrStatus=details.xhr.status;// same as in v1.1
2995
+ isRetryableNWFailure=xhrStatus===429||xhrStatus>=500&&xhrStatus<600;}return isRetryableNWFailure;};
2996
+
2997
+ var DEFAULT_RETRY_QUEUE_OPTIONS={maxRetryDelay:360000,minRetryDelay:1000,backoffFactor:2,maxAttempts:10,maxItems:100};var REQUEST_TIMEOUT_MS=10*1000;// 10 seconds
2998
+ var DATA_PLANE_API_VERSION='v1';var QUEUE_NAME='rudder';var XHR_QUEUE_PLUGIN='XhrQueuePlugin';
2999
+
3000
+ var getNormalizedQueueOptions=function getNormalizedQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_RETRY_QUEUE_OPTIONS,queueOpts);};var getDeliveryUrl=function getDeliveryUrl(dataplaneUrl,eventType){var dpUrl=new URL(dataplaneUrl);return new URL(removeDuplicateSlashes([dpUrl.pathname,DATA_PLANE_API_VERSION,'/',eventType].join('')),dpUrl).href;};var logErrorOnFailure=function logErrorOnFailure(details,item,willBeRetried,attemptNumber,maxRetryAttempts,logger){if(isUndefined(details===null||details===void 0?void 0:details.error)||isUndefined(logger)){return;}var isRetryableFailure=isErrRetryable(details);var errMsg=EVENT_DELIVERY_FAILURE_ERROR_PREFIX(XHR_QUEUE_PLUGIN,item.url);var eventDropMsg="The event will be dropped.";if(isRetryableFailure){if(willBeRetried){errMsg="".concat(errMsg," It'll be retried.");if(attemptNumber>0){errMsg="".concat(errMsg," Retry attempt ").concat(attemptNumber," of ").concat(maxRetryAttempts,".");}}else {errMsg="".concat(errMsg," Retries exhausted (").concat(maxRetryAttempts,"). ").concat(eventDropMsg);}}else {errMsg="".concat(errMsg," ").concat(eventDropMsg);}logger===null||logger===void 0?void 0:logger.error(errMsg);};
3001
+
3002
+ 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:{/**
3003
+ * Initialize the queue for delivery
3004
+ * @param state Application state
3005
+ * @param httpClient http client instance
3006
+ * @param storeManager Store Manager instance
3007
+ * @param errorHandler Error handler instance
3008
+ * @param logger Logger instance
3009
+ * @returns RetryQueue instance
3010
+ */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
3011
+ "".concat(QUEUE_NAME,"_").concat(writeKey),finalQOpts,function(item,done,attemptNumber,maxRetryAttempts,willBeRetried){var url=item.url,event=item.event,headers=item.headers;var finalEvent=getFinalEventForDeliveryMutator(event,state);var data=getDeliveryPayload$1(finalEvent);if(data){httpClient.getAsyncData({url:url,options:{method:'POST',headers:headers,data:data,sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS,callback:function callback(result,details){// null means item will not be requeued
3012
+ var queueErrResp=isErrRetryable(details)?details:null;logErrorOnFailure(details,item,willBeRetried,attemptNumber,maxRetryAttempts,logger);done(queueErrResp,result);}});}else {logger===null||logger===void 0?void 0:logger.error(EVENT_PAYLOAD_PREPARATION_ERROR(XHR_QUEUE_PLUGIN));// Mark the item as done so that it can be removed from the queue
3013
+ done(null);}},storeManager);return eventsQueue;},/**
3014
+ * Add event to the queue for delivery
3015
+ * @param state Application state
3016
+ * @param eventsQueue RetryQueue instance
3017
+ * @param event RudderEvent object
3018
+ * @param errorHandler Error handler instance
3019
+ * @param logger Logger instance
3020
+ * @returns none
3021
+ */enqueue:function enqueue(state,eventsQueue,event,errorHandler,logger){// sentAt is only added here for the validation step
3022
+ // It'll be updated to the latest timestamp during actual delivery
3023
+ 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
3024
+ // Auth header is added during initialization
3025
+ var headers={// TODO: why do we need this header value?
3026
+ AnonymousId:toBase64(event.anonymousId)};eventsQueue.addItem({url:url,headers:headers,event:event});}}};};
3027
+
3028
+ // eslint-disable-next-line import/no-extraneous-dependencies
3029
+ /**
3030
+ * Map plugin names to direct code imports from plugins package
3031
+ */var legacyBuildPluginImports=function legacyBuildPluginImports(){return {Bugsnag:Bugsnag,BeaconQueue:BeaconQueue,DeviceModeTransformation:DeviceModeTransformation,DeviceModeDestinations:DeviceModeDestinations,ErrorReporting:ErrorReporting,ExternalAnonymousId:ExternalAnonymousId,GoogleLinker:GoogleLinker,NativeDestinationQueue:NativeDestinationQueue,StorageEncryption:StorageEncryption,StorageEncryptionLegacy:StorageEncryptionLegacy,StorageMigrator:StorageMigrator,XhrQueue:XhrQueue,OneTrustConsentManager:OneTrustConsentManager,KetchConsentManager:KetchConsentManager};};
3032
+
3033
+ /**
3034
+ * Map of mandatory plugin names and direct imports
3035
+ */var getMandatoryPluginsMap=function getMandatoryPluginsMap(){return {};};/**
3036
+ * Map of optional plugin names and direct imports for legacy builds
3037
+ */var getOptionalPluginsMap=function getOptionalPluginsMap(){return _objectSpread2({},(legacyBuildPluginImports===null||legacyBuildPluginImports===void 0?void 0:legacyBuildPluginImports())||{});};/**
3038
+ * Map of optional plugin names and dynamic imports for modern builds
3039
+ */var getRemotePluginsMap=function getRemotePluginsMap(activePluginNames){{return {};}};var pluginsInventory=_objectSpread2(_objectSpread2({},getMandatoryPluginsMap()),getOptionalPluginsMap());var remotePluginsInventory=function remotePluginsInventory(activePluginNames){return _objectSpread2({},getRemotePluginsMap());};
3040
+
3041
+ // TODO: add retry mechanism for getting remote plugins
3042
+ // TODO: add timeout error mechanism for marking remote plugins that failed to load as failed in state
3043
+ 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);}/**
3044
+ * Orchestrate the plugin loading and registering
3045
+ */_createClass(PluginsManager,[{key:"init",value:function init(){state.lifecycle.status.value=LifecycleStatus.PluginsLoading;// Expose pluginsCDNPath to global object, so it can be used in the promise that determines
3046
+ this.setActivePlugins();this.registerLocalPlugins();this.registerRemotePlugins();this.attachEffects();}/**
3047
+ * Update state based on plugin loaded status
3048
+ */ // eslint-disable-next-line class-methods-use-this
3049
+ },{key:"attachEffects",value:function attachEffects(){b(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){o(function(){state.plugins.ready.value=true;// TODO: decide what to do if a plugin fails to load for any reason.
3050
+ // Should we stop here or should we progress?
3051
+ state.lifecycle.status.value=LifecycleStatus.PluginsReady;});}});}/**
3052
+ * Determine the list of plugins that should be loaded based on sourceConfig & load options
3053
+ */ // eslint-disable-next-line class-methods-use-this
3054
+ },{key:"getPluginsToLoadBasedOnConfig",value:function getPluginsToLoadBasedOnConfig(){var _state$nativeDestinat;// This contains the default plugins if load option has been omitted by user
3055
+ var pluginsToLoadFromConfig=state.plugins.pluginsToLoadFromConfig.value;if(!pluginsToLoadFromConfig){return [];}// Error reporting related plugins
3056
+ var supportedErrReportingProviderPluginNames=Object.values(ErrorReportingProvidersToPluginNameMap);if(state.reporting.errorReportingProviderPluginName.value){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return !(pluginName!==state.reporting.errorReportingProviderPluginName.value&&supportedErrReportingProviderPluginNames.includes(pluginName));});}else {pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return !(pluginName===PluginName.ErrorReporting||supportedErrReportingProviderPluginNames.includes(pluginName));});}// dataplane events delivery plugins
3057
+ if(state.loadOptions.value.useBeacon===true&&state.capabilities.isBeaconAvailable.value){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return pluginName!==PluginName.XhrQueue;});}else {if(state.loadOptions.value.useBeacon===true){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0?void 0:_this$logger.warn(UNSUPPORTED_BEACON_API_WARNING(PLUGINS_MANAGER));}pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return pluginName!==PluginName.BeaconQueue;});}// Device mode destinations related plugins
3058
+ if(getNonCloudDestinations((_state$nativeDestinat=state.nativeDestinations.configuredDestinations.value)!==null&&_state$nativeDestinat!==void 0?_state$nativeDestinat:[]).length===0){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return ![PluginName.DeviceModeDestinations,PluginName.DeviceModeTransformation,PluginName.NativeDestinationQueue].includes(pluginName);});}// Consent Management related plugins
3059
+ var supportedConsentManagerPlugins=Object.values(ConsentManagersToPluginNameMap);pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return !(pluginName!==state.consents.activeConsentManagerPluginName.value&&supportedConsentManagerPlugins.includes(pluginName));});// Storage encryption related plugins
3060
+ var supportedStorageEncryptionPlugins=Object.values(StorageEncryptionVersionsToPluginNameMap);pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return !(pluginName!==state.storage.encryptionPluginName.value&&supportedStorageEncryptionPlugins.includes(pluginName));});// Storage migrator related plugins
3061
+ if(!state.storage.migrate.value){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return pluginName!==PluginName.StorageMigrator;});}return [].concat(_toConsumableArray(Object.keys(getMandatoryPluginsMap())),_toConsumableArray(pluginsToLoadFromConfig));}/**
3062
+ * Determine the list of plugins that should be activated
3063
+ */},{key:"setActivePlugins",value:function setActivePlugins(){var pluginsToLoad=this.getPluginsToLoadBasedOnConfig();// Merging available mandatory and optional plugin name list
3064
+ var availablePlugins=[].concat(_toConsumableArray(Object.keys(pluginsInventory)),_toConsumableArray(remotePluginNames));var activePlugins=[];var failedPlugins=[];pluginsToLoad.forEach(function(pluginName){if(availablePlugins.includes(pluginName)){activePlugins.push(pluginName);}else {failedPlugins.push(pluginName);}});if(failedPlugins.length>0){this.onError(new Error("Ignoring loading of unknown plugins: ".concat(failedPlugins.join(','),". Mandatory plugins: ").concat(Object.keys(getMandatoryPluginsMap()).join(','),". Load option plugins: ").concat(state.plugins.pluginsToLoadFromConfig.value.join(','))));}o(function(){state.plugins.totalPluginsToLoad.value=pluginsToLoad.length;state.plugins.activePlugins.value=activePlugins;state.plugins.failedPlugins.value=failedPlugins;});}/**
3065
+ * Register plugins that are direct imports to PluginEngine
3066
+ */},{key:"registerLocalPlugins",value:function registerLocalPlugins(){var _this=this;Object.values(pluginsInventory).forEach(function(localPlugin){if(state.plugins.activePlugins.value.includes(localPlugin().name)){_this.register([localPlugin()]);}});}/**
3067
+ * Register plugins that are dynamic imports to PluginEngine
3068
+ */},{key:"registerRemotePlugins",value:function registerRemotePlugins(){var _this2=this;var remotePluginsList=remotePluginsInventory(state.plugins.activePlugins.value);Promise.all(Object.keys(remotePluginsList).map(/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(remotePluginKey){return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:_context.next=2;return remotePluginsList[remotePluginKey]().then(function(remotePluginModule){return _this2.register([remotePluginModule.default()]);}).catch(function(err){// TODO: add retry here if dynamic import fails
3069
+ state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.failedPlugins.value),[remotePluginKey]);_this2.onError(err,remotePluginKey);});case 2:case"end":return _context.stop();}},_callee);}));return function(_x){return _ref.apply(this,arguments);};}())).catch(function(err){_this2.onError(err);});}/**
3070
+ * Extension point invoke that allows multiple plugins to be registered to it with error handling
3071
+ */},{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 [];}}/**
3072
+ * Extension point invoke that allows a single plugin to be registered to it with error handling
3073
+ */},{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;}}/**
3074
+ * Plugin engine register with error handling
3075
+ */},{key:"register",value:function register(plugins){var _this3=this;plugins.forEach(function(plugin){try{_this3.engine.register(plugin,state);}catch(e){state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.failedPlugins.value),[plugin.name]);_this3.onError(e);}});}// TODO: Implement reset API instead
3076
+ },{key:"unregisterLocalPlugins",value:function unregisterLocalPlugins(){var _this4=this;Object.values(pluginsInventory).forEach(function(localPlugin){try{_this4.engine.unregister(localPlugin().name);}catch(e){_this4.onError(e);}});}/**
3077
+ * Handle errors
3078
+ */},{key:"onError",value:function onError(error,customMessage){if(this.errorHandler){this.errorHandler.onError(error,PLUGINS_MANAGER,customMessage);}else {throw error;}}}]);return PluginsManager;}();
3079
+
3080
+ /**
3081
+ * Utility to parse XHR JSON response
3082
+ */var responseTextToJson=function responseTextToJson(responseText,onError){try{return JSON.parse(responseText||'');}catch(err){var error=getMutatedError(err,'Failed to parse response data');if(onError&&isFunction(onError)){onError(error);}else {throw error;}}return undefined;};
3083
+
3084
+ var DEFAULT_XHR_REQUEST_OPTIONS={headers:{Accept:'application/json','Content-Type':'application/json;charset=UTF-8'},method:'GET'};/**
3085
+ * Utility to create request configuration based on default options
3086
+ */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;};/**
3087
+ * Utility implementation of XHR, fetch cannot be used as it requires explicit
3088
+ * origin allowed values and not wildcard for CORS requests with credentials and
3089
+ * this is not supported by our sourceConfig API
3090
+ */var xhrRequest=function xhrRequest(options){var timeout=arguments.length>1&&arguments[1]!==undefined?arguments[1]:DEFAULT_XHR_TIMEOUT;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
3091
+ return;}}var xhr=new XMLHttpRequest();// eslint-disable-next-line @typescript-eslint/no-unused-vars
3092
+ var xhrReject=function xhrReject(e){reject({error:new Error(XHR_DELIVERY_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,xhr.status,xhr.statusText,options.url)),xhr:xhr,options:options});};var xhrError=function xhrError(e){reject({error:new Error(XHR_REQUEST_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,e,options.url)),xhr:xhr,options:options});};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);// The timeout property may be set only in the time interval between a call to the open method
3093
+ // and the first call to the send method in legacy browsers
3094
+ 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});}});};
3095
+
3096
+ /**
3097
+ * Service to handle data communication with APIs
3098
+ */var HttpClient=/*#__PURE__*/function(){function HttpClient(errorHandler,logger){_classCallCheck(this,HttpClient);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);}/**
3099
+ * Implement requests in a blocking way
3100
+ */_createClass(HttpClient,[{key:"getData",value:function(){var _getData=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(config){var url,options,timeout,isRawResponse,data,_error;return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;_context.prev=1;_context.next=4;return xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout,this.logger);case 4:data=_context.sent;return _context.abrupt("return",{data:isRawResponse?data.response:responseTextToJson(data.response,this.onError),details:data});case 8:_context.prev=8;_context.t0=_context["catch"](1);this.onError((_error=_context.t0.error)!==null&&_error!==void 0?_error:_context.t0);return _context.abrupt("return",{data:undefined,details:_context.t0});case 12:case"end":return _context.stop();}},_callee,this,[[1,8]]);}));function getData(_x){return _getData.apply(this,arguments);}return getData;}()/**
3101
+ * Implement requests in a non-blocking way
3102
+ */},{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=!(callback&&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){var _data$error;_this.onError((_data$error=data.error)!==null&&_data$error!==void 0?_data$error:data);if(!isFireAndForget){callback(undefined,data);}});}/**
3103
+ * Handle errors
3104
+ */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0?void 0:_this$errorHandler.onError(error,HTTP_CLIENT);}else {throw error;}}/**
3105
+ * Set basic authentication header (eg writekey)
3106
+ */},{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);}/**
3107
+ * Clear basic authentication header
3108
+ */},{key:"resetAuthHeader",value:function resetAuthHeader(){this.basicAuthHeader=undefined;}}]);return HttpClient;}();var defaultHttpClient=new HttpClient(defaultErrorHandler,defaultLogger);
3109
+
3110
+ var STORAGE_TEST_COOKIE='test_rudder_cookie';var STORAGE_TEST_LOCAL_STORAGE='test_rudder_ls';var STORAGE_TEST_SESSION_STORAGE='test_rudder_ss';var STORAGE_TEST_TOP_LEVEL_DOMAIN='__tld__';var CLIENT_DATA_STORE_NAME='clientData';
3111
+
3112
+ var detectAdBlockers=function detectAdBlockers(errorHandler,logger){// Apparently, '?view=ad' is a query param that is blocked by majority of adblockers
3113
+ // Use source config URL here as it is very unlikely to be blocked by adblockers
3114
+ // Only the extra query param should make it vulnerable to adblockers
3115
+ // This will work even if the users proxies it.
3116
+ // The edge case where this doesn't work is when HEAD method is not allowed by the server (user's)
3117
+ var baseUrl=new URL(state.lifecycle.sourceConfigUrl.value);var url="".concat(baseUrl.origin).concat(baseUrl.pathname,"?view=ad");var httpClient=new HttpClient(errorHandler,logger);httpClient.setAuthHeader(state.lifecycle.writeKey.value);httpClient.getAsyncData({url:url,options:{// We actually don't need the response from the request, so we are using HEAD
3118
+ method:'HEAD',headers:{'Content-Type':undefined}},isRawResponse:true,callback:function callback(result,details){var _details$xhr;// not ad blocked if the request is successful or it is not internally redirected on the client side
3119
+ // Often adblockers instead of blocking the request, they redirect it to an internal URL
3120
+ 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;}});};
3121
+
3122
+ var hasCrypto=function hasCrypto(){return !isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);};var hasUAClientHints=function hasUAClientHints(){return !isNullOrUndefined(globalThis.navigator.userAgentData);};var hasBeacon=function hasBeacon(){return !isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);};var isIE11=function isIE11(){return Boolean(globalThis.navigator.userAgent.match(/Trident.*rv:11\./));};
3123
+
3124
+ 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?void 0:_navigator$userAgentD.getHighEntropyValues(['architecture','bitness','brands','mobile','model','platform','platformVersion','uaFullVersion','fullVersionList','wow64']).then(function(ua){callback(ua);}).catch(function(){callback();});}};
3125
+
3126
+ var isDatasetAvailable=function isDatasetAvailable(){var testElement=document.createElement('div');testElement.setAttribute('data-a-b','c');return testElement.dataset?testElement.dataset.aB==='c':false;};var legacyJSEngineRequiredPolyfills={URLSearchParams:function URLSearchParams(){return !globalThis.URLSearchParams;},URL:function URL(){return !isFunction(globalThis.URL);},MutationObserver:function(_MutationObserver){function MutationObserver(){return _MutationObserver.apply(this,arguments);}MutationObserver.toString=function(){return _MutationObserver.toString();};return MutationObserver;}(function(){return isUndefined(MutationObserver);}),Promise:function(_Promise){function Promise(){return _Promise.apply(this,arguments);}Promise.toString=function(){return _Promise.toString();};return Promise;}(function(){return isUndefined(Promise);}),'Number.isNaN':function NumberIsNaN(){return !Number.isNaN;},'Number.isInteger':function NumberIsInteger(){return !Number.isInteger;},'Array.from':function ArrayFrom(){return !Array.from;},'Array.prototype.find':function ArrayPrototypeFind(){return !Array.prototype.find;},'Array.prototype.includes':function ArrayPrototypeIncludes(){return !Array.prototype.includes;},'String.prototype.endsWith':function StringPrototypeEndsWith(){return !String.prototype.endsWith;},'String.prototype.startsWith':function StringPrototypeStartsWith(){return !String.prototype.startsWith;},'String.prototype.includes':function StringPrototypeIncludes(){return !String.prototype.includes;},'Object.entries':function ObjectEntries(){return !Object.entries;},'Object.values':function ObjectValues(){return !Object.values;},'Element.prototype.dataset':function ElementPrototypeDataset(){return !isDatasetAvailable();},'String.prototype.replaceAll':function StringPrototypeReplaceAll(){return !String.prototype.replaceAll;},TextEncoder:function(_TextEncoder){function TextEncoder(){return _TextEncoder.apply(this,arguments);}TextEncoder.toString=function(){return _TextEncoder.toString();};return TextEncoder;}(function(){return isUndefined(TextEncoder);}),TextDecoder:function(_TextDecoder){function TextDecoder(){return _TextDecoder.apply(this,arguments);}TextDecoder.toString=function(){return _TextDecoder.toString();};return TextDecoder;}(function(){return isUndefined(TextDecoder);}),'String.fromCodePoint':function StringFromCodePoint(){return !String.fromCodePoint;}};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(isCapabilityMissing()){needsPolyfill=true;}}return needsPolyfill;};
3127
+
3128
+ 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;};
3129
+
3130
+ var isStorageQuotaExceeded=function isStorageQuotaExceeded(e){var matchingNames=['QuotaExceededError','NS_ERROR_DOM_QUOTA_REACHED'];// [everything except Firefox, Firefox]
3131
+ var matchingCodes=[22,1014];// [everything except Firefox, Firefox]
3132
+ var isQuotaExceededError=matchingNames.includes(e.name)||matchingCodes.includes(e.code);return e instanceof DOMException&&isQuotaExceededError;};// TODO: also check for SecurityErrors
3133
+ // https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage#exceptions
3134
+ 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;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
3135
+ break;case SESSION_STORAGE:storage=storageInstance!==null&&storageInstance!==void 0?storageInstance:globalThis.sessionStorage;testData=STORAGE_TEST_SESSION_STORAGE;break;default:return false;}if(!storage){return false;}storage.setItem(testData,'true');if(storage.getItem(testData)){storage.removeItem(testData);return true;}return false;}catch(err){var msgPrefix=STORAGE_UNAVAILABILITY_ERROR_PREFIX(CAPABILITIES_MANAGER,type);var reason='unavailable';if(isStorageQuotaExceeded(err)){reason='full';}logger===null||logger===void 0?void 0:logger.error("".concat(msgPrefix).concat(reason,"."),err);return false;}};
3136
+
3137
+ /**
3138
+ * Encode.
3139
+ */var encode=function encode(value){return encodeURIComponent(value);};/**
3140
+ * Decode
3141
+ */var decode=function decode(value){return decodeURIComponent(value);};/**
3142
+ * Parse cookie `str`
3143
+ */var parse=function parse(str){var obj={};var pairs=str.split(/\s*;\s*/);var pair;if(!pairs[0]){return obj;}pairs.forEach(function(pairItem){pair=pairItem.split('=');obj[decode(pair[0])]=decode(pair[1]);});return obj;};/**
3144
+ * Set cookie `name` to `value`
3145
+ */var set=function set(name,value,optionsConfig){var options=_objectSpread2({},optionsConfig)||{};var cookieString="".concat(encode(name),"=").concat(encode(value));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;};/**
3146
+ * Return all cookies
3147
+ */var all=function all(){var cookieStringValue=globalThis.document.cookie;return parse(cookieStringValue);};/**
3148
+ * Get cookie `name`
3149
+ */var get=function get(name){return all()[name];};/**
3150
+ * Set or get cookie `name` with `value` and `options` object
3151
+ */ // eslint-disable-next-line func-names
3152
+ var cookie=function cookie(name,value,options){switch(arguments.length){case 3:case 2:return set(name,value,options);case 1:if(name){return get(name);}return all();default:return all();}};
3153
+
3154
+ var legacyGetHostname=function legacyGetHostname(href){var l=document.createElement('a');l.href=href;return l.hostname;};/**
3155
+ * Levels returns all levels of the given url
3156
+ *
3157
+ * The method returns an empty array when the hostname is an ip.
3158
+ */var levelsFunc=function levelsFunc(url){var _host$split;// This is called before the polyfills load thus new URL cannot be used
3159
+ 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.
3160
+ if(parts.length===4&&last===parseInt(last,10).toString()){return levels;}// Localhost.
3161
+ if(parts.length<=1){// Fix to support localhost
3162
+ if(parts[0].indexOf('localhost')!==-1){return ['localhost'];}return levels;}// Create levels.
3163
+ for(var i=parts.length-2;i>=0;i-=1){levels.push(parts.slice(i).join('.'));}return levels;};/**
3164
+ * Get the top domain.
3165
+ *
3166
+ * The function constructs the levels of domain and attempts to set a global
3167
+ * cookie on each one when it succeeds it returns the top level domain.
3168
+ *
3169
+ * The method returns an empty string when the hostname is an ip.
3170
+ */var domain=function domain(url){var levels=levelsFunc(url);// Lookup the real top level one.
3171
+ // eslint-disable-next-line unicorn/no-for-loop
3172
+ 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)};// Set cookie on domain
3173
+ cookie(cname,1,opts);// If successful
3174
+ if(cookie(cname)){// Remove cookie from domain
3175
+ cookie(cname,null,opts);return _domain;}}return '';};
3176
+
3177
+ var getDefaultCookieOptions=function getDefaultCookieOptions(){var topDomain=domain(globalThis.location.href);return {maxage:DEFAULT_COOKIE_MAX_AGE,path:'/',domain:!topDomain||topDomain==='.'?undefined:topDomain,samesite:CookieSameSite.Lax,enabled:true};};var getDefaultLocalStorageOptions=function getDefaultLocalStorageOptions(){return {enabled:true};};var getDefaultInMemoryStorageOptions=function getDefaultInMemoryStorageOptions(){return {enabled:true};};
3178
+
3179
+ /**
3180
+ * A storage utility to persist values in cookies via Storage interface
3181
+ */var CookieStorage=/*#__PURE__*/function(){function CookieStorage(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var logger=arguments.length>1?arguments[1]:undefined;_classCallCheck(this,CookieStorage);_defineProperty(this,"isSupportAvailable",true);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);if(CookieStorage.globalSingleton){// eslint-disable-next-line no-constructor-return
3182
+ return CookieStorage.globalSingleton;}this.options=getDefaultCookieOptions();this.logger=logger;this.configure(options);CookieStorage.globalSingleton=this;}_createClass(CookieStorage,[{key:"configure",value:function configure(options){var _this$options;this.options=mergeDeepRight((_this$options=this.options)!==null&&_this$options!==void 0?_this$options:{},options);this.isSupportAvailable=isStorageAvailable(COOKIE_STORAGE,this,this.logger);this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}},{key:"setItem",value:function setItem(key,value){cookie(key,value,this.options);this.length=Object.keys(cookie()).length;return true;}// eslint-disable-next-line class-methods-use-this
3183
+ },{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
3184
+ },{key:"clear",value:function clear(){// Not implemented
3185
+ // getting a list of all cookie storage keys and remove all values
3186
+ // sounds risky to do as it will take on all top domain cookies
3187
+ // better to explicitly clear specific ones if needed
3188
+ }// This cannot be implemented for cookies
3189
+ // eslint-disable-next-line class-methods-use-this
3190
+ },{key:"key",value:function key(index){var cookies=cookie();var cookieNames=Object.keys(cookies);return isUndefined(cookieNames[index])?null:cookieNames[index];}}]);return CookieStorage;}();_defineProperty(CookieStorage,"globalSingleton",null);
3191
+
3192
+ /**
3193
+ * A storage utility to retain values in memory via Storage interface
3194
+ */var InMemoryStorage=/*#__PURE__*/function(){function InMemoryStorage(options,logger){_classCallCheck(this,InMemoryStorage);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);_defineProperty(this,"data",{});this.options=getDefaultInMemoryStorageOptions();this.logger=logger;this.configure(options!==null&&options!==void 0?options:{});}_createClass(InMemoryStorage,[{key:"configure",value:function configure(options){this.options=mergeDeepRight(this.options,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){return Object.keys(this.data)[index];}}]);return InMemoryStorage;}();var defaultInMemoryStorage=new InMemoryStorage({},defaultLogger);
3195
+
3196
+ var store$1 = {exports: {}};
3197
+
3198
+ (function(module,exports){(function(global,factory){module.exports=factory();})(commonjsGlobal,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
3199
+ // Error: QuotaExceededError
3200
+ function dealIncognito(storage){var _KEY='_Is_Incognit',_VALUE='yes';try{// NOTE: set default storage when not passed in
3201
+ 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
3202
+ 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){if(!key){var ret={};this.forEach(function(key,val){return ret[key]=val;});return ret;}if(key.charAt(0)==='?'){return this.has(key.substr(1));}var args=arguments;if(args.length>1){var dt={};for(var i=0,len=args.length;i<len;i++){var value=deserialize(storage.getItem(args[i]));if(this.has(args[i])){dt[args[i]]=value;}}return dt;}return deserialize(storage.getItem(key));},clear:function clear(){storage.clear();return this;},remove:function remove(key){var val=this.get(key);storage.removeItem(key);return val;},has:function has(key){return {}.hasOwnProperty.call(this.get(),key);},keys:function keys(){var d=[];this.forEach(function(k){d.push(k);});return d;},forEach:function forEach(callback){for(var i=0,len=storage.length;i<len;i++){var key=storage.key(i);callback(key,this.get(key));}return this;},search:function search(str){var arr=this.keys(),dt={};for(var i=0,len=arr.length;i<len;i++){if(arr[i].indexOf(str)>-1)dt[arr[i]]=this.get(arr[i]);}return dt;}};var _Store=null;function store(key,data){var argm=arguments;var dt=null;if(!_Store)_Store=Store();if(argm.length===0)return _Store.get();if(argm.length===1){if(typeof key==="string")return _Store.get(key);if(isJSON(key))return _Store.set(key);}if(argm.length===2&&typeof key==="string"){if(!data)return _Store.remove(key);if(data&&typeof data==="string")return _Store.set(key,data);if(data&&isFunction(data)){dt=null;dt=data(key,_Store.get(key));store.set(key,dt);}}if(argm.length===2&&isArray(key)&&isFunction(data)){for(var i=0,len=key.length;i<len;i++){dt=data(key[i],_Store.get(key[i]));store.set(key[i],dt);}}return store;}for(var a in Store.prototype)store[a]=Store.prototype[a];return store;});})(store$1);var storeExports=store$1.exports;var store = /*@__PURE__*/getDefaultExportFromCjs(storeExports);
3203
+
3204
+ // check if the get, set overloads and search methods are used at all
3205
+ // if we do, ensure we provide types to support overloads as per storejs docs
3206
+ // https://www.npmjs.com/package/storejs
3207
+ /**
3208
+ * A storage utility to persist values in localstorage via Storage interface
3209
+ */var LocalStorage=/*#__PURE__*/function(){function LocalStorage(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var logger=arguments.length>1?arguments[1]:undefined;_classCallCheck(this,LocalStorage);_defineProperty(this,"isSupportAvailable",true);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);this.options=getDefaultLocalStorageOptions();this.logger=logger;this.configure(options);}_createClass(LocalStorage,[{key:"configure",value:function configure(options){this.options=mergeDeepRight(this.options,options);this.isSupportAvailable=isStorageAvailable(LOCAL_STORAGE,this,this.logger);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.keys().length;}// eslint-disable-next-line class-methods-use-this
3210
+ },{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.keys().length;}},{key:"clear",value:function clear(){store.clear();this.length=0;}// eslint-disable-next-line class-methods-use-this
3211
+ },{key:"key",value:function key(index){return store.keys()[index];}}]);return LocalStorage;}();var defaultLocalStorage=new LocalStorage({},defaultLogger);
3212
+
3213
+ /**
3214
+ * A utility to retrieve the storage singleton instance by type
3215
+ */var getStorageEngine=function getStorageEngine(type){switch(type){case LOCAL_STORAGE:return defaultLocalStorage;case SESSION_STORAGE:return globalThis.sessionStorage;case MEMORY_STORAGE:return defaultInMemoryStorage;case COOKIE_STORAGE:return new CookieStorage({},defaultLogger);default:return defaultInMemoryStorage;}};/**
3216
+ * Configure cookie storage singleton
3217
+ */var configureCookieStorageEngine=function configureCookieStorageEngine(options){new CookieStorage({},defaultLogger).configure(options);};/**
3218
+ * Configure local storage singleton
3219
+ */var configureLocalStorageEngine=function configureLocalStorageEngine(options){defaultLocalStorage.configure(options);};/**
3220
+ * Configure in memory storage singleton
3221
+ */var configureInMemoryStorageEngine=function configureInMemoryStorageEngine(options){defaultInMemoryStorage.configure(options);};/**
3222
+ * Configure all storage singleton instances
3223
+ */var configureStorageEngines=function configureStorageEngines(){var cookieOptions=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]:{};configureCookieStorageEngine(cookieOptions);configureLocalStorageEngine(localStorageOptions);configureInMemoryStorageEngine(inMemoryStorageOptions);};
3224
+
3225
+ /**
3226
+ * Store Implementation with dedicated storage
3227
+ */var Store=/*#__PURE__*/function(){function Store(config,engine,pluginsManager){var _config$isEncrypted,_config$validKeys,_config$errorHandler,_config$logger;_classCallCheck(this,Store);_defineProperty(this,"hasErrorHandler",false);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!==null&&engine!==void 0?engine:getStorageEngine(LOCAL_STORAGE);this.noKeyValidation=Object.keys(this.validKeys).length===0;this.noCompoundKey=config.noCompoundKey;this.originalEngine=this.engine;this.errorHandler=(_config$errorHandler=config.errorHandler)!==null&&_config$errorHandler!==void 0?_config$errorHandler:defaultErrorHandler;this.hasErrorHandler=Boolean(this.errorHandler);this.logger=(_config$logger=config.logger)!==null&&_config$logger!==void 0?_config$logger:defaultLogger;this.pluginsManager=pluginsManager;}/**
3228
+ * Ensure the key is valid and with correct format
3229
+ */_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
3230
+ var compoundKey;Object.values(validKeys).forEach(function(validKeyName){if(validKeyName===key){compoundKey=noCompoundKey?key:[name,id,key].join('.');}});return compoundKey;}/**
3231
+ * Switch to inMemoryEngine, bringing any existing data with.
3232
+ */},{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
3233
+ // better to keep other queues in localstorage to be flushed later
3234
+ // than to pull them into memory and remove them from durable storage
3235
+ 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
3236
+ // if cookies are not available and localstorage is full?
3237
+ _this.remove(key);});this.engine=inMemoryStorage;}/**
3238
+ * Set value by key.
3239
+ */},{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
3240
+ this.engine.setItem(validKey,this.encrypt(stringifyWithoutCircular(value,false,[],this.logger)));}catch(err){if(isStorageQuotaExceeded(err)){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0?void 0:_this$logger.warn(STORAGE_QUOTA_EXCEEDED_WARNING(STORE_MANAGER));// switch to inMemory engine
3241
+ this.swapQueueStoreToInMemoryEngine();// and save it there
3242
+ this.set(key,value);}else {this.onError(getMutatedError(err,STORE_DATA_SAVE_ERROR(key)));}}}/**
3243
+ * Get by Key.
3244
+ */},{key:"get",value:function get(key){var validKey=this.createValidKey(key);try{if(!validKey){return null;}var str=this.decrypt(this.engine.getItem(validKey));if(isNullOrUndefined(str)){return null;}// storejs that is used in localstorage engine already deserializes json strings but swallows errors
3245
+ return JSON.parse(str);}catch(err){this.onError(new Error("".concat(STORE_DATA_FETCH_ERROR(key),": ").concat(err.message)));return null;}}/**
3246
+ * Remove by Key.
3247
+ */},{key:"remove",value:function remove(key){var validKey=this.createValidKey(key);if(validKey){this.engine.removeItem(validKey);}}/**
3248
+ * Get original engine
3249
+ */},{key:"getOriginalEngine",value:function getOriginalEngine(){return this.originalEngine;}/**
3250
+ * Decrypt values
3251
+ */},{key:"decrypt",value:function decrypt(value){if(isNullOrUndefined(value)){return null;}return this.crypto(value,'decrypt');}/**
3252
+ * Encrypt value
3253
+ */},{key:"encrypt",value:function encrypt(value){return this.crypto(value,'encrypt');}/**
3254
+ * Extension point to use with encryption plugins
3255
+ */},{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:'';}/**
3256
+ * Handle errors
3257
+ */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0?void 0:_this$errorHandler.onError(error,"Store ".concat(this.id));}else {throw error;}}}]);return Store;}();
3258
+
3259
+ /**
3260
+ * A service to manage stores & available storage client configurations
3261
+ */var StoreManager=/*#__PURE__*/function(){function StoreManager(pluginsManager,errorHandler,logger){_classCallCheck(this,StoreManager);_defineProperty(this,"stores",{});_defineProperty(this,"isInitialized",false);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.hasErrorHandler=Boolean(this.errorHandler);this.pluginsManager=pluginsManager;this.onError=this.onError.bind(this);}/**
3262
+ * Configure available storage client instances
3263
+ */_createClass(StoreManager,[{key:"init",value:function init(){if(this.isInitialized){return;}var config={cookieOptions:{samesite:state.loadOptions.value.sameSiteCookie,secure:state.loadOptions.value.secureCookie,domain:state.loadOptions.value.setCookieDomain,enabled:true},localStorageOptions:{enabled:true},inMemoryStorageOptions:{enabled:true}};configureStorageEngines(removeUndefinedValues(config.cookieOptions),removeUndefinedValues(config.localStorageOptions),removeUndefinedValues(config.inMemoryStorageOptions));this.initClientDataStore();this.isInitialized=true;}/**
3264
+ * Create store to persist data used by the SDK like session, used details etc
3265
+ */},{key:"initClientDataStore",value:function initClientDataStore(){var _getStorageEngine,_getStorageEngine2;var storageType='';// First try setting the storage to cookie else to localstorage
3266
+ if((_getStorageEngine=getStorageEngine(COOKIE_STORAGE))!==null&&_getStorageEngine!==void 0&&_getStorageEngine.isEnabled){storageType=COOKIE_STORAGE;}else if((_getStorageEngine2=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine2!==void 0&&_getStorageEngine2.isEnabled){storageType=LOCAL_STORAGE;}// TODO: fallback to in-memory storage if not other storage is available
3267
+ // TODO: should we fallback to session storage instead so we retain values on page refresh, navigation etc?
3268
+ if(!storageType){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0?void 0:_this$logger.error(STORAGE_UNAVAILABLE_ERROR(STORE_MANAGER));return;}// TODO: fill in extra config values and bring them in from StoreManagerOptions if needed
3269
+ // TODO: should we pass the keys for all in order to validate or leave free as v1.1?
3270
+ this.setStore({id:CLIENT_DATA_STORE_NAME,name:CLIENT_DATA_STORE_NAME,isEncrypted:true,noCompoundKey:true,type:storageType});}/**
3271
+ * Create a new store
3272
+ */},{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];}/**
3273
+ * Retrieve a store
3274
+ */},{key:"getStore",value:function getStore(id){return this.stores[id];}/**
3275
+ * Handle errors
3276
+ */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0?void 0:_this$errorHandler.onError(error,STORE_MANAGER);}else {throw error;}}}]);return StoreManager;}();
3277
+
3278
+ /**
3279
+ * Removes trailing slash from url
3280
+ * @param url
3281
+ * @returns url
3282
+ */var removeTrailingSlashes=function removeTrailingSlashes(url){return url&&url.endsWith('/')?removeTrailingSlashes(url.substring(0,url.length-1)):url;};/**
3283
+ * Checks if provided url is valid or not
3284
+ * @param url
3285
+ * @returns true if `url` is valid and false otherwise
3286
+ */var isValidUrl=function isValidUrl(url){try{var validUrl=new URL(url);return Boolean(validUrl);}catch(err){return false;}};/**
3287
+ * Get the referring domain from the referrer URL
3288
+ * @param referrer Page referrer
3289
+ * @returns Page referring domain
3290
+ */var getReferringDomain=function getReferringDomain(referrer){var referringDomain='';try{var url=new URL(referrer);referringDomain=url.host;}catch(error){// Do nothing
3291
+ }return referringDomain;};/**
3292
+ * Extracts UTM parameters from the URL
3293
+ * @param url Page URL
3294
+ * @returns UTM parameters
3295
+ */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
3296
+ if(utmParam==='campaign'){utmParam='name';}result[utmParam]=value;}});}catch(error){// Do nothing
3297
+ }return result;};/**
3298
+ * To get the URL until the hash
3299
+ * @param url The input URL
3300
+ * @returns URL until the hash
3301
+ */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
3302
+ }return urlWithoutHash;};
3303
+
3304
+ var validateWriteKey=function validateWriteKey(writeKey){if(!writeKey||writeKey.trim().length===0){throw new Error(WRITE_KEY_VALIDATION_ERROR(writeKey));}};var validateDataPlaneUrl=function validateDataPlaneUrl(dataPlaneUrl){if(dataPlaneUrl&&!isValidUrl(dataPlaneUrl)){throw new Error(DATA_PLANE_URL_VALIDATION_ERROR(dataPlaneUrl));}};var validateLoadArgs=function validateLoadArgs(writeKey,dataPlaneUrl){validateWriteKey(writeKey);validateDataPlaneUrl(dataPlaneUrl);};var isValidSourceConfig=function isValidSourceConfig(res){return isObjectLiteralAndNotNull(res)&&isObjectLiteralAndNotNull(res.source)&&!isNullOrUndefined(res.source.id)&&isObjectLiteralAndNotNull(res.source.config)&&Array.isArray(res.source.destinations);};
3305
+
3306
+ /**
3307
+ * A function to filter enabled destinations and map to required properties only
3308
+ * @param destinations
3309
+ *
3310
+ * @returns Destination[]
3311
+ */var filterEnabledDestination=function filterEnabledDestination(destinations){var nativeDestinations=[];destinations.forEach(function(destination){if(destination.enabled&&!destination.deleted){nativeDestinations.push({id:destination.id,displayName:destination.destinationDefinition.displayName,config:destination.config,shouldApplyDeviceModeTransformation:destination.shouldApplyDeviceModeTransformation||false,propagateEventsUntransformedOnError:destination.propagateEventsUntransformedOnError||false,userFriendlyId:"".concat(destination.destinationDefinition.displayName.replaceAll(' ','-'),"___").concat(destination.id)});}});return nativeDestinations;};
3312
+
3313
+ var defaultOptionalPluginsList=[PluginName.Bugsnag,PluginName.DeviceModeDestinations,PluginName.ErrorReporting,PluginName.ExternalAnonymousId,PluginName.GoogleLinker,PluginName.NativeDestinationQueue,PluginName.StorageEncryption,PluginName.StorageEncryptionLegacy,PluginName.StorageMigrator,PluginName.XhrQueue,PluginName.OneTrustConsentManager,PluginName.KetchConsentManager,PluginName.BeaconQueue];
3314
+
3315
+ var normalizeLoadOptions=function normalizeLoadOptions(loadOptionsFromState,loadOptions){var _normalizedLoadOpts$p,_normalizedLoadOpts$s;// TODO: add all the validations as per
3316
+ // https://github.com/rudderlabs/rudder-sdk-js/blob/a620e11f98e1438be34114ad40b325201b1d7a6e/src/core/analytics.js#L1156
3317
+ // TODO: Maybe add warnings for invalid values
3318
+ var normalizedLoadOpts=clone$1(loadOptions);normalizedLoadOpts.setCookieDomain=isDefined(normalizedLoadOpts.setCookieDomain)&&isString(normalizedLoadOpts.setCookieDomain)?normalizedLoadOpts.setCookieDomain:undefined;normalizedLoadOpts.secureCookie=normalizedLoadOpts.secureCookie===true;normalizedLoadOpts.sameSiteCookie=isDefined(normalizedLoadOpts.sameSiteCookie)&&Object.values(CookieSameSite).includes(normalizedLoadOpts.sameSiteCookie)?normalizedLoadOpts.sameSiteCookie:undefined;normalizedLoadOpts.plugins=(_normalizedLoadOpts$p=normalizedLoadOpts.plugins)!==null&&_normalizedLoadOpts$p!==void 0?_normalizedLoadOpts$p:defaultOptionalPluginsList;normalizedLoadOpts.useGlobalIntegrationsConfigInEvents=normalizedLoadOpts.useGlobalIntegrationsConfigInEvents===true;normalizedLoadOpts.bufferDataPlaneEventsUntilReady=normalizedLoadOpts.bufferDataPlaneEventsUntilReady===true;normalizedLoadOpts.sendAdblockPage=normalizedLoadOpts.sendAdblockPage===true;normalizedLoadOpts.sendAdblockPageOptions=isObjectLiteralAndNotNull(normalizedLoadOpts.sendAdblockPageOptions)?normalizedLoadOpts.sendAdblockPageOptions:{};normalizedLoadOpts.storage=isObjectLiteralAndNotNull(normalizedLoadOpts.storage)?removeUndefinedAndNullValues(normalizedLoadOpts.storage):{};normalizedLoadOpts.storage.migrate=((_normalizedLoadOpts$s=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s===void 0?void 0:_normalizedLoadOpts$s.migrate)===true;normalizedLoadOpts.beaconQueueOptions=isObjectLiteralAndNotNull(normalizedLoadOpts.beaconQueueOptions)?removeUndefinedAndNullValues(normalizedLoadOpts.beaconQueueOptions):{};normalizedLoadOpts.destinationsQueueOptions=isObjectLiteralAndNotNull(normalizedLoadOpts.destinationsQueueOptions)?removeUndefinedAndNullValues(normalizedLoadOpts.destinationsQueueOptions):{};normalizedLoadOpts.queueOptions=isObjectLiteralAndNotNull(normalizedLoadOpts.queueOptions)?removeUndefinedAndNullValues(normalizedLoadOpts.queueOptions):{};var mergedLoadOptions=mergeDeepRight(loadOptionsFromState,normalizedLoadOpts);return mergedLoadOptions;};var getSourceConfigURL=function getSourceConfigURL(){var configUrlHost=arguments.length>0&&arguments[0]!==undefined?arguments[0]:DEFAULT_CONFIG_BE_URL;return "".concat(configUrlHost,"/sourceConfig/?p=").concat(MODULE_TYPE,"&v=").concat(APP_VERSION,"&build=").concat(BUILD_TYPE);};
3319
+
3320
+ var DEFAULT_REGION='US';/**
3321
+ * A function to get url from source config response
3322
+ * @param {array} urls An array of objects containing urls
3323
+ * @returns
3324
+ */var getDefaultUrlOfRegion=function getDefaultUrlOfRegion(urls){var url;if(Array.isArray(urls)&&urls.length>0){var obj=urls.find(function(elem){return elem.default===true;});if(obj&&isValidUrl(obj.url)){return obj.url;}}return url;};var validateResidencyServerRegion=function validateResidencyServerRegion(residencyServerRegion,logger){if(residencyServerRegion&&!Object.values(ResidencyServerRegion).includes(residencyServerRegion)){logger===null||logger===void 0?void 0:logger.warn(UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING(CONFIG_MANAGER,residencyServerRegion,DEFAULT_REGION));return undefined;}return residencyServerRegion;};/**
3325
+ * A function to determine the dataPlaneUrl
3326
+ * @param {Object} dataplanes An object containing dataPlaneUrl for different region
3327
+ * @param {String} serverUrl dataPlaneUrl provided in the load call
3328
+ * @param {String} residencyServerRegion User provided residency server region
3329
+ * @param {Logger} logger logger instance
3330
+ * @returns The data plane URL string to use
3331
+ */var resolveDataPlaneUrl=function resolveDataPlaneUrl(dataplanes,serverUrl,residencyServerRegion,logger){// Check if dataPlanes object is present in source config
3332
+ if(dataplanes&&Object.keys(dataplanes).length>0){var _validateResidencySer;var region=(_validateResidencySer=validateResidencyServerRegion(residencyServerRegion,logger))!==null&&_validateResidencySer!==void 0?_validateResidencySer:DEFAULT_REGION;var regionUrlArr=dataplanes[region]||dataplanes[DEFAULT_REGION];var defaultUrl=getDefaultUrlOfRegion(regionUrlArr);if(defaultUrl){return defaultUrl;}}// return the dataPlaneUrl provided in load API(if available)
3333
+ if(serverUrl){return serverUrl;}// return undefined if data plane url can not be determined
3334
+ return undefined;};
3335
+
3336
+ 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 getErrorReportingProviderNameFromConfig=function getErrorReportingProviderNameFromConfig(sourceConfig){var _sourceConfig$statsCo2;return sourceConfig===null||sourceConfig===void 0||(_sourceConfig$statsCo2=sourceConfig.statsCollection)===null||_sourceConfig$statsCo2===void 0||(_sourceConfig$statsCo2=_sourceConfig$statsCo2.errors)===null||_sourceConfig$statsCo2===void 0?void 0:_sourceConfig$statsCo2.provider;};var isMetricsReportingEnabled=function isMetricsReportingEnabled(sourceConfig){var _sourceConfig$statsCo3;return (sourceConfig===null||sourceConfig===void 0||(_sourceConfig$statsCo3=sourceConfig.statsCollection)===null||_sourceConfig$statsCo3===void 0||(_sourceConfig$statsCo3=_sourceConfig$statsCo3.metrics)===null||_sourceConfig$statsCo3===void 0?void 0:_sourceConfig$statsCo3.enabled)===true;};
3337
+
3338
+ /**
3339
+ * Determines the SDK url
3340
+ * @returns sdkURL
3341
+ */var getSDKUrl=function getSDKUrl(){var scripts=document.getElementsByTagName('script');var sdkURL;var scriptList=Array.prototype.slice.call(scripts);scriptList.some(function(script){var curScriptSrc=removeTrailingSlashes(script.getAttribute('src'));if(curScriptSrc){var urlMatches=curScriptSrc.match(/^.*rsa?(\.min)?\.js$/);if(urlMatches){sdkURL=curScriptSrc;return true;}}return false;});// TODO: Return the URL object instead of the plain URL string
3342
+ return sdkURL;};/**
3343
+ * Updates the reporting state variables from the source config data
3344
+ * @param res Source config
3345
+ * @param logger Logger instance
3346
+ */var updateReportingState=function updateReportingState(res,logger){state.reporting.isErrorReportingEnabled.value=isErrorReportingEnabled(res.source.config);state.reporting.isMetricsReportingEnabled.value=isMetricsReportingEnabled(res.source.config);if(state.reporting.isErrorReportingEnabled.value){var errReportingProvider=getErrorReportingProviderNameFromConfig(res.source.config);// Get the corresponding plugin name of the selected error reporting provider from the supported error reporting providers
3347
+ var errReportingProviderPlugin=errReportingProvider?ErrorReportingProvidersToPluginNameMap[errReportingProvider]:undefined;if(!isUndefined(errReportingProvider)&&!errReportingProviderPlugin){// set the default error reporting provider
3348
+ logger===null||logger===void 0?void 0:logger.warn(UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(CONFIG_MANAGER,errReportingProvider,ErrorReportingProvidersToPluginNameMap,DEFAULT_ERROR_REPORTING_PROVIDER));}state.reporting.errorReportingProviderPluginName.value=errReportingProviderPlugin!==null&&errReportingProviderPlugin!==void 0?errReportingProviderPlugin:ErrorReportingProvidersToPluginNameMap[DEFAULT_ERROR_REPORTING_PROVIDER];}};var updateStorageState=function updateStorageState(logger){var _state$loadOptions$va;var storageEncryptionVersion=(_state$loadOptions$va=state.loadOptions.value.storage)===null||_state$loadOptions$va===void 0||(_state$loadOptions$va=_state$loadOptions$va.encryption)===null||_state$loadOptions$va===void 0?void 0:_state$loadOptions$va.version;var encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
3349
+ logger===null||logger===void 0?void 0: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;}o(function(){var _state$loadOptions$va2;state.storage.encryptionPluginName.value=StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];// Allow migration only if the configured encryption version is the default encryption version
3350
+ var configuredMigrationValue=(_state$loadOptions$va2=state.loadOptions.value.storage)===null||_state$loadOptions$va2===void 0?void 0:_state$loadOptions$va2.migrate;state.storage.migrate.value=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&state.storage.migrate.value!==configuredMigrationValue){logger===null||logger===void 0?void 0:logger.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}});};
3351
+
3352
+ /**
3353
+ * A function that determines integration SDK loading path
3354
+ * @param requiredVersion
3355
+ * @param lockIntegrationsVersion
3356
+ * @param customIntegrationsCDNPath
3357
+ * @returns
3358
+ */var getIntegrationsCDNPath=function getIntegrationsCDNPath(requiredVersion,lockIntegrationsVersion,customIntegrationsCDNPath){var integrationsCDNPath='';// Get the CDN base URL from the user provided URL if any
3359
+ if(customIntegrationsCDNPath){integrationsCDNPath=removeTrailingSlashes(customIntegrationsCDNPath);if(!integrationsCDNPath||integrationsCDNPath&&!isValidUrl(integrationsCDNPath)){throw new Error(INTG_CDN_BASE_URL_ERROR);}return integrationsCDNPath;}// Get the base path from the SDK script tag src attribute or use the default path
3360
+ var sdkURL=getSDKUrl();integrationsCDNPath=sdkURL&&isString(sdkURL)?sdkURL.split('/').slice(0,-1).concat(CDN_INT_DIR).join('/'):DEST_SDK_BASE_URL;// If version is not locked it will always get the latest version of the integrations
3361
+ if(lockIntegrationsVersion){integrationsCDNPath=integrationsCDNPath.replace(CDN_ARCH_VERSION_DIR,requiredVersion);}return integrationsCDNPath;};/**
3362
+ * A function that determines plugins SDK loading path
3363
+ * @param customPluginsCDNPath
3364
+ * @returns
3365
+ */var getPluginsCDNPath=function getPluginsCDNPath(customPluginsCDNPath){var pluginsCDNPath='';// Get the CDN base URL from the user provided URL if any
3366
+ if(customPluginsCDNPath){pluginsCDNPath=removeTrailingSlashes(customPluginsCDNPath);if(!pluginsCDNPath||pluginsCDNPath&&!isValidUrl(pluginsCDNPath)){throw new Error(PLUGINS_CDN_BASE_URL_ERROR);}return pluginsCDNPath;}// Get the base path from the SDK script tag src attribute or use the default path
3367
+ var sdkURL=getSDKUrl();pluginsCDNPath=sdkURL&&isString(sdkURL)?sdkURL.split('/').slice(0,-1).concat(CDN_PLUGINS_DIR).join('/'):PLUGINS_BASE_URL;return pluginsCDNPath;};
3368
+
3369
+ /**
3370
+ * A function to get the name of the consent manager with enabled true set in the load options
3371
+ * @param cookieConsentOptions Input provided as load option
3372
+ * @returns string|undefined
3373
+ *
3374
+ * Example input: {
3375
+ * oneTrust:{
3376
+ * enabled: true
3377
+ * }
3378
+ * }
3379
+ *
3380
+ * Output: 'oneTrust'
3381
+ */var getUserSelectedConsentManager=function getUserSelectedConsentManager(cookieConsentOptions){if(!isNonEmptyObject(cookieConsentOptions)){return undefined;}var validCookieConsentOptions=cookieConsentOptions;return Object.keys(validCookieConsentOptions).find(function(e){return e&&validCookieConsentOptions[e].enabled===true;});};
3382
+
3383
+ var ConfigManager=/*#__PURE__*/function(){function ConfigManager(httpClient,errorHandler,logger){_classCallCheck(this,ConfigManager);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.httpClient=httpClient;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);this.processConfig=this.processConfig.bind(this);}_createClass(ConfigManager,[{key:"attachEffects",value:function attachEffects(){var _this=this;b(function(){var _this$logger;(_this$logger=_this.logger)===null||_this$logger===void 0?void 0:_this$logger.setMinLogLevel(state.lifecycle.logLevel.value);});}/**
3384
+ * A function to validate, construct and store loadOption, lifecycle, source and destination
3385
+ * config related information in global state
3386
+ */},{key:"init",value:function init(){var consentManagerPluginName;this.attachEffects();validateLoadArgs(state.lifecycle.writeKey.value,state.lifecycle.dataPlaneUrl.value);var lockIntegrationsVersion=state.loadOptions.value.lockIntegrationsVersion===true;try{// determine the path to fetch integration SDK from
3387
+ var intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,state.loadOptions.value.destSDKBaseURL);// determine the path to fetch remote plugins from
3388
+ var pluginsCDNPath=getPluginsCDNPath(state.loadOptions.value.pluginsSDKBaseURL);// Get the consent manager if provided as load option
3389
+ var selectedConsentManager=getUserSelectedConsentManager(state.loadOptions.value.cookieConsentManager);if(selectedConsentManager){// Get the corresponding plugin name of the selected consent manager from the supported consent managers
3390
+ consentManagerPluginName=ConsentManagersToPluginNameMap[selectedConsentManager];if(!consentManagerPluginName){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0?void 0:_this$logger2.error(UNSUPPORTED_CONSENT_MANAGER_ERROR(CONFIG_MANAGER,selectedConsentManager,ConsentManagersToPluginNameMap));}}updateStorageState(this.logger);// set application lifecycle state in global state
3391
+ o(function(){state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycle.pluginsCDNPath.value=pluginsCDNPath;if(state.loadOptions.value.logLevel){state.lifecycle.logLevel.value=state.loadOptions.value.logLevel;}if(state.loadOptions.value.configUrl){state.lifecycle.sourceConfigUrl.value=new URL("".concat(getSourceConfigURL(state.loadOptions.value.configUrl),"&writeKey=").concat(state.lifecycle.writeKey.value,"&lockIntegrationsVersion=").concat(lockIntegrationsVersion)).toString();}// Set consent manager plugin name in state
3392
+ state.consents.activeConsentManagerPluginName.value=consentManagerPluginName;});}catch(err){var issue='Failed to load the SDK';this.onError(getMutatedError(err,issue));return;}this.getConfig();}/**
3393
+ * Handle errors
3394
+ */},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0?void 0:_this$errorHandler.onError(error,CONFIG_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}/**
3395
+ * A callback function that is executed once we fetch the source config response.
3396
+ * Use to construct and store information that are dependent on the sourceConfig.
3397
+ */},{key:"processConfig",value:function processConfig(response,details){var _this2=this;// TODO: add retry logic with backoff based on rejectionDetails.xhr.status
3398
+ // We can use isErrRetryable utility method
3399
+ if(!response){this.onError(SOURCE_CONFIG_FETCH_ERROR(details===null||details===void 0?void 0:details.error));return;}var res;var errMessage='Unable to process/parse source config';try{if(isString(response)){res=JSON.parse(response);}else {res=response;}}catch(e){this.onError(e,errMessage,true);return;}if(!isValidSourceConfig(res)){this.onError(new Error(errMessage),undefined,true);return;}// determine the dataPlane url
3400
+ var dataPlaneUrl=resolveDataPlaneUrl(res.source.dataplanes,state.lifecycle.dataPlaneUrl.value,state.loadOptions.value.residencyServer,this.logger);if(!dataPlaneUrl){this.onError(new Error(DATA_PLANE_URL_ERROR),undefined,true);return;}var nativeDestinations=res.source.destinations.length>0?filterEnabledDestination(res.source.destinations):[];// set in the state --> source, destination, lifecycle, reporting
3401
+ o(function(){var _state$loadOptions$va;// set source related information in state
3402
+ state.source.value={config:res.source.config,id:res.source.id};// set device mode destination related information in state
3403
+ state.nativeDestinations.configuredDestinations.value=nativeDestinations;// set application lifecycle state
3404
+ // Cast to string as we are sure that the value is not undefined
3405
+ state.lifecycle.activeDataplaneUrl.value=removeTrailingSlashes(dataPlaneUrl);state.lifecycle.status.value=LifecycleStatus.Configured;// set the values in state for reporting slice
3406
+ updateReportingState(res,_this2.logger);// set the desired optional plugins
3407
+ state.plugins.pluginsToLoadFromConfig.value=(_state$loadOptions$va=state.loadOptions.value.plugins)!==null&&_state$loadOptions$va!==void 0?_state$loadOptions$va:[];// set application lifecycle state
3408
+ state.lifecycle.activeDataplaneUrl.value=dataPlaneUrl;state.lifecycle.status.value=LifecycleStatus.Configured;});}/**
3409
+ * A function to fetch source config either from /sourceConfig endpoint
3410
+ * or from getSourceConfig load option
3411
+ * @returns
3412
+ */},{key:"getConfig",value:function getConfig(){var _this3=this;var sourceConfigFunc=state.loadOptions.value.getSourceConfig;if(sourceConfigFunc){if(!isFunction(sourceConfigFunc)){throw new Error(SOURCE_CONFIG_OPTION_ERROR);}// fetch source config from the function
3413
+ 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);}return;}// fetch source config from config url API
3414
+ this.httpClient.getAsyncData({url:state.lifecycle.sourceConfigUrl.value,options:{headers:{'Content-Type':undefined}},callback:this.processConfig});}}]);return ConfigManager;}();
3415
+
3416
+ /**
3417
+ * Get the referrer URL
3418
+ * @returns The referrer URL
3419
+ */var getReferrer=function getReferrer(){return document.referrer||'$direct';};/**
3420
+ * To get the canonical URL of the page
3421
+ * @returns canonical URL
3422
+ */var getCanonicalUrl=function getCanonicalUrl(){var tags=document.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(){if(isUndefined(globalThis.navigator)){return null;}var userAgent=globalThis.navigator.userAgent;var _ref=globalThis.navigator,brave=_ref.brave;// For supporting Brave browser detection,
3423
+ // add "Brave/<version>" to the user agent with the version value from the Chrome component
3424
+ if(brave&&Object.getPrototypeOf(brave).isBrave){// Example:
3425
+ // 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
3426
+ var matchedArr=userAgent.match(/(chrome)\/([\w.]+)/i);if(matchedArr){userAgent="".concat(userAgent," Brave/").concat(matchedArr[2]);}}return userAgent;};var getLanguage=function getLanguage(){var _globalThis$navigator;if(isUndefined(globalThis.navigator)){return null;}return (_globalThis$navigator=globalThis.navigator.language)!==null&&_globalThis$navigator!==void 0?_globalThis$navigator:globalThis.navigator.browserLanguage;};/**
3427
+ * Default page properties
3428
+ * @returns Default page properties
3429
+ */var getDefaultPageProperties=function getDefaultPageProperties(){var canonicalUrl=getCanonicalUrl();var path=globalThis.location.pathname;var tabUrl=globalThis.location.href;var pageUrl=tabUrl;var search=globalThis.location.search;// If valid canonical url is provided use this as page url.
3430
+ if(canonicalUrl){try{var urlObj=new URL(canonicalUrl);// If existing, query params of canonical url will be used instead of the location.search ones
3431
+ if(urlObj.search===''){pageUrl=canonicalUrl+search;}else {pageUrl=canonicalUrl;}path=urlObj.pathname;}catch(err){// Do nothing
3432
+ }}var url=getUrlWithoutHash(pageUrl);var _document=document,title=_document.title;var referrer=getReferrer();return {path:path,referrer:referrer,referring_domain:getReferringDomain(referrer),search:search,title:title,url:url,tab_url:tabUrl};};
3433
+
3434
+ var POLYFILL_URL="https://polyfill.io/v3/polyfill.min.js?features=".concat(Object.keys(legacyJSEngineRequiredPolyfills).join('%2C'));var POLYFILL_LOAD_TIMEOUT=10*1000;// 10 seconds
3435
+ var POLYFILL_SCRIPT_ID='rudderstackPolyfill';
3436
+
3437
+ var CapabilitiesManager=/*#__PURE__*/function(){function CapabilitiesManager(errorHandler,logger){_classCallCheck(this,CapabilitiesManager);this.logger=logger;this.errorHandler=errorHandler;this.externalSrcLoader=new ExternalSrcLoader(this.errorHandler,this.logger);this.onError=this.onError.bind(this);this.onReady=this.onReady.bind(this);}_createClass(CapabilitiesManager,[{key:"init",value:function init(){try{this.prepareBrowserCapabilities();this.attachWindowListeners();}catch(e){this.onError(e);}}/**
3438
+ * Detect supported capabilities and set values in state
3439
+ */ // eslint-disable-next-line class-methods-use-this
3440
+ },{key:"detectBrowserCapabilities",value:function detectBrowserCapabilities(){var _this=this;o(function(){// Storage related details
3441
+ 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
3442
+ 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
3443
+ state.context.userAgent.value=getUserAgent();state.context.locale.value=getLanguage();state.context.screen.value=getScreenDetails();state.context.campaign.value=extractUTMParameters(globalThis.location.href);if(hasUAClientHints()){getUserAgentClientHint(function(uach){state.context['ua-ch'].value=uach;},state.loadOptions.value.uaChTrackLevel);}// Get page properties details
3444
+ var pageProperties=getDefaultPageProperties();state.page.path.value=pageProperties.path;state.page.referrer.value=pageProperties.referrer;state.page.referring_domain.value=pageProperties.referring_domain;state.page.search.value=pageProperties.search;state.page.title.value=pageProperties.title;state.page.url.value=pageProperties.url;state.page.tab_url.value=pageProperties.tab_url;});// Ad blocker detection
3445
+ b(function(){if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(_this.errorHandler,_this.logger);}});}/**
3446
+ * Detect if polyfills are required and then load script from polyfill URL
3447
+ */},{key:"prepareBrowserCapabilities",value:function prepareBrowserCapabilities(){var _state$loadOptions$va,_this2=this;state.capabilities.isLegacyDOM.value=isLegacyJSEngine();var polyfillUrl=(_state$loadOptions$va=state.loadOptions.value.polyfillURL)!==null&&_state$loadOptions$va!==void 0?_state$loadOptions$va:POLYFILL_URL;var shouldLoadPolyfill=state.loadOptions.value.polyfillIfRequired&&state.capabilities.isLegacyDOM.value&&Boolean(polyfillUrl);if(shouldLoadPolyfill){var _this$externalSrcLoad,_state$loadOptions$va2;// TODO: check if polyfill has been evaluated via polling or
3448
+ // with the callback param in its url and an exposed function
3449
+ var onPolyfillLoad=function onPolyfillLoad(scriptId){return Boolean(scriptId)&&_this2.onReady();};(_this$externalSrcLoad=this.externalSrcLoader)===null||_this$externalSrcLoad===void 0?void 0:_this$externalSrcLoad.loadJSFile({url:(_state$loadOptions$va2=state.loadOptions.value.polyfillURL)!==null&&_state$loadOptions$va2!==void 0?_state$loadOptions$va2:POLYFILL_URL,id:POLYFILL_SCRIPT_ID,async:true,timeout:POLYFILL_LOAD_TIMEOUT,callback:onPolyfillLoad});}else {this.onReady();}}/**
3450
+ * Attach listeners to window to observe event that update capabilities state values
3451
+ */ // eslint-disable-next-line class-methods-use-this
3452
+ },{key:"attachWindowListeners",value:function attachWindowListeners(){globalThis.addEventListener('offline',function(){state.capabilities.isOnline.value=false;});globalThis.addEventListener('online',function(){state.capabilities.isOnline.value=true;});// TODO: add debounched listener for globalThis.onResize event and update state.context.screen.value
3453
+ }/**
3454
+ * Set the lifecycle status to next phase
3455
+ */ // eslint-disable-next-line class-methods-use-this
3456
+ },{key:"onReady",value:function onReady(){this.detectBrowserCapabilities();state.lifecycle.status.value=LifecycleStatus.BrowserCapabilitiesReady;}/**
3457
+ * Handles error
3458
+ * @param error The error object
3459
+ */},{key:"onError",value:function onError(error){if(this.errorHandler){this.errorHandler.onError(error,CAPABILITIES_MANAGER);}else {throw error;}}}]);return CapabilitiesManager;}();
3460
+
3461
+ // TODO: should we take the types from IdentifyTrait instead of any string key?
3462
+ // https://www.rudderstack.com/docs/event-spec/standard-events/identify/#identify-traits
3463
+ /**
3464
+ * Represents the options parameter in the APIs
3465
+ */var RudderEventType=/*#__PURE__*/function(RudderEventType){RudderEventType["Page"]="page";RudderEventType["Track"]="track";RudderEventType["Identify"]="identify";RudderEventType["Alias"]="alias";RudderEventType["Group"]="group";return RudderEventType;}({});
3466
+
3467
+ var CHANNEL='web';// These are the top-level elements in the standard RudderStack event spec
3468
+ var TOP_LEVEL_ELEMENTS=['integrations','anonymousId','originalTimestamp'];// Reserved elements in the context of standard RudderStack event spec
3469
+ // Typically, these elements are not allowed to be overridden by the user
3470
+ var CONTEXT_RESERVED_ELEMENTS=['library','consentManagement','userAgent','ua-ch','screen'];// Reserved elements in the standard RudderStack event spec
3471
+ var RESERVED_ELEMENTS=['anonymousId','sentAt','receivedAt','timestamp','originalTimestamp','event','messageId','channel'];var DEFAULT_INTEGRATIONS_CONFIG={All:true};
3472
+
3473
+ /**
3474
+ * To get the page properties for context object
3475
+ * @param pageProps Page properties
3476
+ * @returns page properties object for context
3477
+ */var getContextPageProperties=function getContextPageProperties(pageProps){var ctxPageProps={};Object.keys(state.page).forEach(function(key){ctxPageProps[key]=(pageProps===null||pageProps===void 0?void 0:pageProps[key])||state.page[key].value;});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;};/**
3478
+ * Add any missing default page properties using values from options and defaults
3479
+ * @param properties Input page properties
3480
+ * @param options API options
3481
+ */var getUpdatedPageProperties=function getUpdatedPageProperties(properties,options){var optionsPageProps=(options===null||options===void 0?void 0:options.page)||{};var pageProps=properties;Object.keys(state.page).forEach(function(key){if(isUndefined(pageProps[key])){pageProps[key]=optionsPageProps[key]||state.page[key].value;}});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;};/**
3482
+ * Utility to check for reserved keys in the input object
3483
+ * @param obj Generic object
3484
+ * @param eventType Rudder event type
3485
+ * @param parentKeyPath Object's parent key path
3486
+ * @param logger Logger instance
3487
+ */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===null||logger===void 0?void 0:logger.warn(RESERVED_KEYWORD_WARNING(EVENT_MANAGER,property,parentKeyPath,RESERVED_ELEMENTS));}});}};/**
3488
+ * Checks for reserved keys in traits, properties, and contextual traits
3489
+ * @param rudderEvent Generated rudder event
3490
+ * @param logger Logger instance
3491
+ */var checkForReservedElements=function checkForReservedElements(rudderEvent,logger){// properties, traits, contextualTraits are either undefined or object
3492
+ 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);};/**
3493
+ * Overrides the top-level event properties with data from API options
3494
+ * @param rudderEvent Generated rudder event
3495
+ * @param options API options
3496
+ */var updateTopLevelEventElements=function updateTopLevelEventElements(rudderEvent,options){if(options.anonymousId&&isString(options.anonymousId)){// eslint-disable-next-line no-param-reassign
3497
+ rudderEvent.anonymousId=options.anonymousId;}if(options.integrations&&isObjectLiteralAndNotNull(options.integrations)){// eslint-disable-next-line no-param-reassign
3498
+ rudderEvent.integrations=options.integrations;}if(options.originalTimestamp&&isString(options.originalTimestamp)){// eslint-disable-next-line no-param-reassign
3499
+ rudderEvent.originalTimestamp=options.originalTimestamp;}};/**
3500
+ * To merge the contextual information in API options with existing data
3501
+ * @param rudderContext Generated rudder event
3502
+ * @param options API options
3503
+ * @param logger Logger instance
3504
+ */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===null||logger===void 0?void 0:logger.warn(INVALID_CONTEXT_OBJECT_WARNING(EVENT_MANAGER));}}});return context;};/**
3505
+ * A function to determine whether SDK should use the integration option provided in load call
3506
+ * @returns boolean
3507
+ */var shouldUseGlobalIntegrationsConfigInEvents=function shouldUseGlobalIntegrationsConfigInEvents(){return state.loadOptions.value.useGlobalIntegrationsConfigInEvents&&isObjectLiteralAndNotNull(state.nativeDestinations.loadOnlyIntegrations.value);};/**
3508
+ * Updates rudder event object with data from the API options
3509
+ * @param rudderEvent Generated rudder event
3510
+ * @param options API options
3511
+ */var processOptions=function processOptions(rudderEvent,options){// Only allow object type for options
3512
+ if(!isNullOrUndefined(options)&&isObjectLiteralAndNotNull(options)){updateTopLevelEventElements(rudderEvent,options);// eslint-disable-next-line no-param-reassign
3513
+ rudderEvent.context=getMergedContext(rudderEvent.context,options);}};/**
3514
+ * Returns the final integrations config for the event based on the global config and event's config
3515
+ * @param integrationsConfig Event's integrations config
3516
+ * @returns Final integrations config
3517
+ */var getEventIntegrationsConfig=function getEventIntegrationsConfig(integrationsConfig){var finalIntgConfig;if(shouldUseGlobalIntegrationsConfigInEvents()){finalIntgConfig=state.nativeDestinations.loadOnlyIntegrations.value;}else if(isObjectLiteralAndNotNull(integrationsConfig)){finalIntgConfig=integrationsConfig;}else {finalIntgConfig=DEFAULT_INTEGRATIONS_CONFIG;}return finalIntgConfig;};/**
3518
+ * Enrich the base event object with data from state and the API options
3519
+ * @param rudderEvent RudderEvent object
3520
+ * @param options API options
3521
+ * @param pageProps Page properties
3522
+ * @param logger logger
3523
+ * @returns Enriched RudderEvent object
3524
+ */var getEnrichedEvent=function getEnrichedEvent(rudderEvent,options,pageProps,logger){var commonEventData={// Type casting to string as the user session manager will take care of initializing the value
3525
+ anonymousId:state.session.anonymousUserId.value,channel:CHANNEL,context:{traits:clone$1(state.session.userTraits.value),sessionId:state.session.sessionInfo.value.id,sessionStart:state.session.sessionInfo.value.sessionStart||undefined,consentManagement:{deniedConsentIds:clone$1(state.consents.data.value.deniedConsentIds)},'ua-ch':state.context['ua-ch'].value,app:state.context.app.value,library:state.context.library.value,userAgent:state.context.userAgent.value,os:state.context.os.value,locale:state.context.locale.value,screen:state.context.screen.value,campaign:clone$1(state.context.campaign.value),page:getContextPageProperties(pageProps)},originalTimestamp:getCurrentTimeFormatted(),integrations:DEFAULT_INTEGRATIONS_CONFIG,messageId:generateUUID(),userId:state.session.userId.value};if(rudderEvent.type===RudderEventType.Group){commonEventData.groupId=state.session.groupId.value;commonEventData.traits=clone$1(state.session.groupTraits.value);}var processedEvent=mergeDeepRight(rudderEvent,commonEventData);// Set the default values for the event properties
3526
+ // matching with v1.1 payload
3527
+ if(processedEvent.event===undefined){processedEvent.event=null;}if(processedEvent.properties===undefined){processedEvent.properties=null;}processOptions(processedEvent,options);// TODO: We might not need this check altogether
3528
+ checkForReservedElements(processedEvent,logger);// Update the integrations config for the event
3529
+ processedEvent.integrations=getEventIntegrationsConfig(processedEvent.integrations);return processedEvent;};
3530
+
3531
+ var RudderEventFactory=/*#__PURE__*/function(){function RudderEventFactory(logger){_classCallCheck(this,RudderEventFactory);this.logger=logger;}/**
3532
+ * Generate a 'page' event based on the user-input fields
3533
+ * @param category Page's category
3534
+ * @param name Page name
3535
+ * @param properties Page properties
3536
+ * @param options API options
3537
+ */_createClass(RudderEventFactory,[{key:"generatePageEvent",value:function generatePageEvent(category,name,properties,options){var props=properties!==null&&properties!==void 0?properties:{};props.name=name;props.category=category;props=getUpdatedPageProperties(props,options);var pageEvent={properties:props,name:name,category:category,type:RudderEventType.Page};return getEnrichedEvent(pageEvent,options,props,this.logger);}/**
3538
+ * Generate a 'track' event based on the user-input fields
3539
+ * @param event The event name
3540
+ * @param properties Event properties
3541
+ * @param options API options
3542
+ */},{key:"generateTrackEvent",value:function generateTrackEvent(event,properties,options){var trackEvent={properties:properties,event:event,type:RudderEventType.Track};return getEnrichedEvent(trackEvent,options,undefined,this.logger);}/**
3543
+ * Generate an 'identify' event based on the user-input fields
3544
+ * @param options API options
3545
+ */},{key:"generateIdentifyEvent",value:function generateIdentifyEvent(options){var identifyEvent={type:RudderEventType.Identify};return getEnrichedEvent(identifyEvent,options,undefined,this.logger);}/**
3546
+ * Generate an 'alias' event based on the user-input fields
3547
+ * @param to New user ID
3548
+ * @param from Old user ID
3549
+ * @param options API options
3550
+ */},{key:"generateAliasEvent",value:function generateAliasEvent(to,from,options){var aliasEvent={previousId:from,type:RudderEventType.Alias};var enrichedEvent=getEnrichedEvent(aliasEvent,options,undefined,this.logger);// override the User ID from the API inputs
3551
+ enrichedEvent.userId=to!==null&&to!==void 0?to:enrichedEvent.userId;return enrichedEvent;}/**
3552
+ * Generate a 'group' event based on the user-input fields
3553
+ * @param options API options
3554
+ */},{key:"generateGroupEvent",value:function generateGroupEvent(options){var groupEvent={type:RudderEventType.Group};return getEnrichedEvent(groupEvent,options,undefined,this.logger);}/**
3555
+ * Generates a new RudderEvent object based on the user-input fields
3556
+ * @param event API event parameters object
3557
+ * @returns A RudderEvent object
3558
+ */},{key:"create",value:function create(event){var eventObj;switch(event.type){case RudderEventType.Page:eventObj=this.generatePageEvent(event.category,event.name,event.properties,event.options);break;case RudderEventType.Track:eventObj=this.generateTrackEvent(event.name,event.properties,event.options);break;case RudderEventType.Identify:eventObj=this.generateIdentifyEvent(event.options);break;case RudderEventType.Alias:eventObj=this.generateAliasEvent(event.to,event.from,event.options);break;case RudderEventType.Group:eventObj=this.generateGroupEvent(event.options);break;}return eventObj;}}]);return RudderEventFactory;}();
3559
+
3560
+ /**
3561
+ * A service to generate valid event payloads and queue them for processing
3562
+ */var EventManager=/*#__PURE__*/function(){/**
3563
+ *
3564
+ * @param eventRepository Event repository instance
3565
+ * @param userSessionManager UserSession Manager instance
3566
+ * @param errorHandler Error handler object
3567
+ * @param logger Logger object
3568
+ */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);this.onError=this.onError.bind(this);}/**
3569
+ * Initializes the event manager
3570
+ */_createClass(EventManager,[{key:"init",value:function init(){this.eventRepository.init();state.lifecycle.status.value=LifecycleStatus.Initialized;}/**
3571
+ * Consumes a new incoming event
3572
+ * @param event Incoming event data
3573
+ */},{key:"addEvent",value:function addEvent(event){this.userSessionManager.refreshSession();var rudderEvent=this.eventFactory.create(event);if(rudderEvent){this.eventRepository.enqueue(rudderEvent,event.callback);}else {this.onError(new Error(EVENT_OBJECT_GENERATION_ERROR));}}/**
3574
+ * Handles error
3575
+ * @param error The error object
3576
+ */},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);return EventManager;}();
3577
+
3578
+ /**
3579
+ * A function to check given value is a number or not
3580
+ * @param num input value
3581
+ * @returns boolean
3582
+ */var isNumber=function isNumber(num){return typeof num==='number'&&!Number.isNaN(num);};/**
3583
+ * A function to check given number has minimum length or not
3584
+ * @param minimumLength minimum length
3585
+ * @param num input number
3586
+ * @returns boolean
3587
+ */var hasMinLength=function hasMinLength(minimumLength,num){return num.toString().length>=minimumLength;};/**
3588
+ * A function to check given value is a positive integer or not
3589
+ * @param num input value
3590
+ * @returns boolean
3591
+ */var isPositiveInteger=function isPositiveInteger(num){return isNumber(num)&&num>=0&&Number.isInteger(num);};
3592
+
3593
+ var MIN_SESSION_ID_LENGTH=10;/**
3594
+ * A function to validate current session and return true/false depending on that
3595
+ * @returns boolean
3596
+ */var hasSessionExpired=function hasSessionExpired(expiresAt){var timestamp=Date.now();return Boolean(!expiresAt||timestamp>expiresAt);};/**
3597
+ * A function to generate session id
3598
+ * @returns number
3599
+ */var generateSessionId=function generateSessionId(){return Date.now();};/**
3600
+ * Function to validate user provided sessionId
3601
+ * @param {number} sessionId
3602
+ * @returns
3603
+ */var isManualSessionIdValid=function isManualSessionIdValid(sessionId,logger){if(!sessionId||!isPositiveInteger(sessionId)||!hasMinLength(MIN_SESSION_ID_LENGTH,sessionId)){logger===null||logger===void 0?void 0:logger.warn(INVALID_SESSION_ID_WARNING(USER_SESSION_MANAGER,sessionId,MIN_SESSION_ID_LENGTH));return false;}return true;};/**
3604
+ * A function to generate new auto tracking session
3605
+ * @param sessionTimeout current timestamp
3606
+ * @returns SessionInfo
3607
+ */var generateAutoTrackingSession=function generateAutoTrackingSession(sessionTimeout){var timestamp=Date.now();var timeout=sessionTimeout||DEFAULT_SESSION_TIMEOUT;return {id:timestamp,// set the current timestamp
3608
+ expiresAt:timestamp+timeout,// set the expiry time of the session
3609
+ timeout:timeout,sessionStart:undefined,autoTrack:true};};/**
3610
+ * A function to generate new manual tracking session
3611
+ * @param id Provided sessionId
3612
+ * @param logger Logger module
3613
+ * @returns SessionInfo
3614
+ */var generateManualTrackingSession=function generateManualTrackingSession(id,logger){var sessionId=isManualSessionIdValid(id,logger)?id:generateSessionId();return {id:sessionId,sessionStart:undefined,manualTrack:true};};
3615
+
3616
+ var userSessionStorageKeys={userId:'rl_user_id',userTraits:'rl_trait',anonymousUserId:'rl_anonymous_id',groupId:'rl_group_id',groupTraits:'rl_group_trait',initialReferrer:'rl_page_init_referrer',initialReferringDomain:'rl_page_init_referring_domain',sessionInfo:'rl_session'};
3617
+
3618
+ var UserSessionManager=/*#__PURE__*/function(){function UserSessionManager(errorHandler,logger,pluginsManager,store){_classCallCheck(this,UserSessionManager);this.store=store;this.pluginsManager=pluginsManager;this.logger=logger;this.errorHandler=errorHandler;this.onError=this.onError.bind(this);}/**
3619
+ * Initialize User session with values from storage
3620
+ * @param store Selected store
3621
+ */_createClass(UserSessionManager,[{key:"init",value:function init(store){var _this$getUserId,_this$getUserTraits,_this$getGroupId,_this$getGroupTraits;this.store=store;this.migrateStorageIfNeeded();// get the values from storage and set it again
3622
+ this.setUserId((_this$getUserId=this.getUserId())!==null&&_this$getUserId!==void 0?_this$getUserId:'');this.setUserTraits((_this$getUserTraits=this.getUserTraits())!==null&&_this$getUserTraits!==void 0?_this$getUserTraits:{});this.setGroupId((_this$getGroupId=this.getGroupId())!==null&&_this$getGroupId!==void 0?_this$getGroupId:'');this.setGroupTraits((_this$getGroupTraits=this.getGroupTraits())!==null&&_this$getGroupTraits!==void 0?_this$getGroupTraits:{});this.setAnonymousId(this.getAnonymousId(state.loadOptions.value.anonymousIdOptions));var initialReferrer=this.getInitialReferrer();var initialReferringDomain=this.getInitialReferringDomain();if(initialReferrer&&initialReferringDomain){this.setInitialReferrer(initialReferrer);this.setInitialReferringDomain(initialReferringDomain);}else {if(initialReferrer){this.setInitialReferrer(initialReferrer);this.setInitialReferringDomain(getReferringDomain(initialReferrer));}var referrer=getReferrer();this.setInitialReferrer(referrer);this.setInitialReferringDomain(getReferringDomain(referrer));}// Initialize session tracking
3623
+ this.initializeSessionTracking();// Register the effect to sync with storage
3624
+ this.registerEffects();}},{key:"migrateStorageIfNeeded",value:function migrateStorageIfNeeded(){var _this=this;if(!state.storage.migrate.value){return;}Object.values(userSessionStorageKeys).forEach(function(storageEntry){var _this$pluginsManager,_this$store;var migratedVal=(_this$pluginsManager=_this.pluginsManager)===null||_this$pluginsManager===void 0?void 0:_this$pluginsManager.invokeSingle('storage.migrate',storageEntry,(_this$store=_this.store)===null||_this$store===void 0?void 0:_this$store.engine,_this.logger);_this.syncValueToStorage(storageEntry,migratedVal);});}/**
3625
+ * A function to initialize sessionTracking
3626
+ */},{key:"initializeSessionTracking",value:function initializeSessionTracking(){var _this$getSessionFromS;var sessionInfo=(_this$getSessionFromS=this.getSessionFromStorage())!==null&&_this$getSessionFromS!==void 0?_this$getSessionFromS:defaultSessionInfo;var finalAutoTrackingStatus=!(state.loadOptions.value.sessions.autoTrack===false||sessionInfo.manualTrack===true);var sessionTimeout;var configuredSessionTimeout=state.loadOptions.value.sessions.timeout;if(!isPositiveInteger(configuredSessionTimeout)){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0?void 0:_this$logger.warn(TIMEOUT_NOT_NUMBER_WARNING(USER_SESSION_MANAGER,configuredSessionTimeout,DEFAULT_SESSION_TIMEOUT));sessionTimeout=DEFAULT_SESSION_TIMEOUT;}else {sessionTimeout=configuredSessionTimeout;}if(sessionTimeout===0){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0?void 0:_this$logger2.warn(TIMEOUT_ZERO_WARNING(USER_SESSION_MANAGER));finalAutoTrackingStatus=false;}// In case user provides a timeout value greater than 0 but less than 10 seconds SDK will show a warning
3627
+ // and will proceed with it
3628
+ if(sessionTimeout>0&&sessionTimeout<MIN_SESSION_TIMEOUT){var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===void 0?void 0:_this$logger3.warn(TIMEOUT_NOT_RECOMMENDED_WARNING(USER_SESSION_MANAGER,sessionTimeout,MIN_SESSION_TIMEOUT));}state.session.sessionInfo.value=_objectSpread2(_objectSpread2({},sessionInfo),{},{timeout:sessionTimeout,autoTrack:finalAutoTrackingStatus});// If auto session tracking is enabled start the session tracking
3629
+ if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}}/**
3630
+ * Handles error
3631
+ * @param error The error object
3632
+ */},{key:"onError",value:function onError(error){if(this.errorHandler){this.errorHandler.onError(error,USER_SESSION_MANAGER);}else {throw error;}}/**
3633
+ * A function to sync values in storage
3634
+ * @param key
3635
+ * @param value
3636
+ */},{key:"syncValueToStorage",value:function syncValueToStorage(key,value){if(value&&isString(value)||isNonEmptyObject(value)){var _this$store2;(_this$store2=this.store)===null||_this$store2===void 0?void 0:_this$store2.set(key,value);}else {var _this$store3;(_this$store3=this.store)===null||_this$store3===void 0?void 0:_this$store3.remove(key);}}/**
3637
+ * Function to update storage whenever state value changes
3638
+ */},{key:"registerEffects",value:function registerEffects(){var _this2=this;/**
3639
+ * Update userId in storage automatically when userId is updated in state
3640
+ */b(function(){_this2.syncValueToStorage(userSessionStorageKeys.userId,state.session.userId.value);});/**
3641
+ * Update user traits in storage automatically when it is updated in state
3642
+ */b(function(){_this2.syncValueToStorage(userSessionStorageKeys.userTraits,state.session.userTraits.value);});/**
3643
+ * Update group id in storage automatically when it is updated in state
3644
+ */b(function(){_this2.syncValueToStorage(userSessionStorageKeys.groupId,state.session.groupId.value);});/**
3645
+ * Update group traits in storage automatically when it is updated in state
3646
+ */b(function(){_this2.syncValueToStorage(userSessionStorageKeys.groupTraits,state.session.groupTraits.value);});/**
3647
+ * Update anonymous user id in storage automatically when it is updated in state
3648
+ */b(function(){_this2.syncValueToStorage(userSessionStorageKeys.anonymousUserId,state.session.anonymousUserId.value);});/**
3649
+ * Update initial referrer in storage automatically when it is updated in state
3650
+ */b(function(){_this2.syncValueToStorage(userSessionStorageKeys.initialReferrer,state.session.initialReferrer.value);});/**
3651
+ * Update initial referring domain in storage automatically when it is updated in state
3652
+ */b(function(){_this2.syncValueToStorage(userSessionStorageKeys.initialReferringDomain,state.session.initialReferringDomain.value);});/**
3653
+ * Update session tracking info in storage automatically when it is updated in state
3654
+ */b(function(){_this2.syncValueToStorage(userSessionStorageKeys.sessionInfo,state.session.sessionInfo.value);});}/**
3655
+ * Sets anonymous id in the following precedence:
3656
+ *
3657
+ * 1. anonymousId: Id directly provided to the function.
3658
+ * 2. rudderAmpLinkerParam: value generated from linker query parm (rudderstack)
3659
+ * using parseLinker util.
3660
+ * 3. generateUUID: A new unique id is generated and assigned.
3661
+ */},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){var finalAnonymousId=anonymousId;if(!finalAnonymousId&&rudderAmpLinkerParam){var _this$pluginsManager2;var linkerPluginsResult=(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===void 0?void 0:_this$pluginsManager2.invokeMultiple('userSession.anonymousIdGoogleLinker',rudderAmpLinkerParam);finalAnonymousId=linkerPluginsResult===null||linkerPluginsResult===void 0?void 0:linkerPluginsResult[0];}state.session.anonymousUserId.value=finalAnonymousId||this.generateAnonymousId();}/**
3662
+ * Generate a new anonymousId
3663
+ * @returns string anonymousID
3664
+ */},{key:"generateAnonymousId",value:function generateAnonymousId(){return generateUUID();}/**
3665
+ * Fetches anonymousId
3666
+ * @param options option to fetch it from external source
3667
+ * @returns anonymousId
3668
+ */},{key:"getAnonymousId",value:function getAnonymousId(options){var _this$store4;// fetch the anonymousUserId from storage
3669
+ var persistedAnonymousId=(_this$store4=this.store)===null||_this$store4===void 0?void 0:_this$store4.get(userSessionStorageKeys.anonymousUserId);if(!persistedAnonymousId&&options){var _this$pluginsManager3;// fetch anonymousId from external source
3670
+ var autoCapturedAnonymousId=(_this$pluginsManager3=this.pluginsManager)===null||_this$pluginsManager3===void 0?void 0:_this$pluginsManager3.invokeSingle('storage.getAnonymousId',getStorageEngine,options);persistedAnonymousId=autoCapturedAnonymousId;}state.session.anonymousUserId.value=persistedAnonymousId||this.generateAnonymousId();return state.session.anonymousUserId.value;}/**
3671
+ * Fetches User Id
3672
+ * @returns
3673
+ */},{key:"getUserId",value:function getUserId(){var _this$store$get,_this$store5;return (_this$store$get=(_this$store5=this.store)===null||_this$store5===void 0?void 0:_this$store5.get(userSessionStorageKeys.userId))!==null&&_this$store$get!==void 0?_this$store$get:null;}/**
3674
+ * Fetches User Traits
3675
+ * @returns
3676
+ */},{key:"getUserTraits",value:function getUserTraits(){var _this$store$get2,_this$store6;return (_this$store$get2=(_this$store6=this.store)===null||_this$store6===void 0?void 0:_this$store6.get(userSessionStorageKeys.userTraits))!==null&&_this$store$get2!==void 0?_this$store$get2:null;}/**
3677
+ * Fetches Group Id
3678
+ * @returns
3679
+ */},{key:"getGroupId",value:function getGroupId(){var _this$store$get3,_this$store7;return (_this$store$get3=(_this$store7=this.store)===null||_this$store7===void 0?void 0:_this$store7.get(userSessionStorageKeys.groupId))!==null&&_this$store$get3!==void 0?_this$store$get3:null;}/**
3680
+ * Fetches Group Traits
3681
+ * @returns
3682
+ */},{key:"getGroupTraits",value:function getGroupTraits(){var _this$store$get4,_this$store8;return (_this$store$get4=(_this$store8=this.store)===null||_this$store8===void 0?void 0:_this$store8.get(userSessionStorageKeys.groupTraits))!==null&&_this$store$get4!==void 0?_this$store$get4:null;}/**
3683
+ * Fetches Initial Referrer
3684
+ * @returns
3685
+ */},{key:"getInitialReferrer",value:function getInitialReferrer(){var _this$store$get5,_this$store9;return (_this$store$get5=(_this$store9=this.store)===null||_this$store9===void 0?void 0:_this$store9.get(userSessionStorageKeys.initialReferrer))!==null&&_this$store$get5!==void 0?_this$store$get5:null;}/**
3686
+ * Fetches Initial Referring domain
3687
+ * @returns
3688
+ */},{key:"getInitialReferringDomain",value:function getInitialReferringDomain(){var _this$store$get6,_this$store10;return (_this$store$get6=(_this$store10=this.store)===null||_this$store10===void 0?void 0:_this$store10.get(userSessionStorageKeys.initialReferringDomain))!==null&&_this$store$get6!==void 0?_this$store$get6:null;}/**
3689
+ * Fetches session tracking information from storage
3690
+ * @returns
3691
+ */},{key:"getSessionFromStorage",value:function getSessionFromStorage(){var _this$store$get7,_this$store11;return (_this$store$get7=(_this$store11=this.store)===null||_this$store11===void 0?void 0:_this$store11.get(userSessionStorageKeys.sessionInfo))!==null&&_this$store$get7!==void 0?_this$store$get7:null;}/**
3692
+ * A function to update current session info after each event call
3693
+ */},{key:"refreshSession",value:function refreshSession(){if(state.session.sessionInfo.value.autoTrack||state.session.sessionInfo.value.manualTrack){if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}if(state.session.sessionInfo.value.sessionStart===undefined){state.session.sessionInfo.value=_objectSpread2(_objectSpread2({},state.session.sessionInfo.value),{},{sessionStart:true});}else if(state.session.sessionInfo.value.sessionStart){state.session.sessionInfo.value=_objectSpread2(_objectSpread2({},state.session.sessionInfo.value),{},{sessionStart:false});}}}/**
3694
+ * Reset state values
3695
+ * @param resetAnonymousId
3696
+ * @param noNewSessionStart
3697
+ * @returns
3698
+ */},{key:"reset",value:function reset(resetAnonymousId,noNewSessionStart){var _this3=this;var _state$session$sessio=state.session.sessionInfo.value,manualTrack=_state$session$sessio.manualTrack,autoTrack=_state$session$sessio.autoTrack;o(function(){state.session.userId.value='';state.session.userTraits.value={};state.session.groupId.value='';state.session.groupTraits.value={};if(resetAnonymousId){state.session.anonymousUserId.value='';}if(noNewSessionStart){return;}if(autoTrack){state.session.sessionInfo.value={};_this3.startOrRenewAutoTracking();}else if(manualTrack){_this3.startManualTrackingInternal();}});}/**
3699
+ * Set user Id
3700
+ * @param userId
3701
+ */},{key:"setUserId",value:function setUserId(userId){state.session.userId.value=userId;}/**
3702
+ * Set user traits
3703
+ * @param traits
3704
+ */},{key:"setUserTraits",value:function setUserTraits(traits){if(traits){var _state$session$userTr;state.session.userTraits.value=mergeDeepRight((_state$session$userTr=state.session.userTraits.value)!==null&&_state$session$userTr!==void 0?_state$session$userTr:{},traits);}}/**
3705
+ * Set group Id
3706
+ * @param groupId
3707
+ */},{key:"setGroupId",value:function setGroupId(groupId){state.session.groupId.value=groupId;}/**
3708
+ * Set group traits
3709
+ * @param traits
3710
+ */},{key:"setGroupTraits",value:function setGroupTraits(traits){if(traits){var _state$session$groupT;state.session.groupTraits.value=mergeDeepRight((_state$session$groupT=state.session.groupTraits.value)!==null&&_state$session$groupT!==void 0?_state$session$groupT:{},traits);}}/**
3711
+ * Set initial referrer
3712
+ * @param referrer
3713
+ */},{key:"setInitialReferrer",value:function setInitialReferrer(referrer){state.session.initialReferrer.value=referrer;}/**
3714
+ * Set initial referring domain
3715
+ * @param referrer
3716
+ */},{key:"setInitialReferringDomain",value:function setInitialReferringDomain(referrer){state.session.initialReferringDomain.value=referrer;}/**
3717
+ * A function to check for existing session details and depending on that create a new session.
3718
+ */},{key:"startOrRenewAutoTracking",value:function startOrRenewAutoTracking(){if(hasSessionExpired(state.session.sessionInfo.value.expiresAt)){state.session.sessionInfo.value=generateAutoTrackingSession(state.session.sessionInfo.value.timeout);}else {var timestamp=Date.now();var timeout=state.session.sessionInfo.value.timeout;state.session.sessionInfo.value=mergeDeepRight(state.session.sessionInfo.value,{expiresAt:timestamp+timeout// set the expiry time of the session
3719
+ });}}/**
3720
+ * A function method to start a manual session
3721
+ * @param {number} id session identifier
3722
+ * @returns
3723
+ */},{key:"start",value:function start(id){state.session.sessionInfo.value=generateManualTrackingSession(id,this.logger);}/**
3724
+ * An internal function to start manual session
3725
+ */},{key:"startManualTrackingInternal",value:function startManualTrackingInternal(){this.start(Date.now());}/**
3726
+ * A public method to end an ongoing session.
3727
+ */},{key:"end",value:function end(){state.session.sessionInfo.value={};}/**
3728
+ * Clear storage
3729
+ * @param resetAnonymousId
3730
+ */},{key:"clearUserSessionStorage",value:function clearUserSessionStorage(resetAnonymousId){var _this$store12,_this$store13,_this$store14,_this$store15;(_this$store12=this.store)===null||_this$store12===void 0?void 0:_this$store12.remove(userSessionStorageKeys.userId);(_this$store13=this.store)===null||_this$store13===void 0?void 0:_this$store13.remove(userSessionStorageKeys.userTraits);(_this$store14=this.store)===null||_this$store14===void 0?void 0:_this$store14.remove(userSessionStorageKeys.groupId);(_this$store15=this.store)===null||_this$store15===void 0?void 0:_this$store15.remove(userSessionStorageKeys.groupTraits);if(resetAnonymousId){var _this$store16;(_this$store16=this.store)===null||_this$store16===void 0?void 0:_this$store16.remove(userSessionStorageKeys.anonymousUserId);}}}]);return UserSessionManager;}();
3731
+
3732
+ /**
3733
+ * A buffer queue to serve as a store for any type of data
3734
+ */var BufferQueue=/*#__PURE__*/function(){function BufferQueue(){_classCallCheck(this,BufferQueue);this.items=[];}_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=[];}}]);return BufferQueue;}();
3735
+
3736
+ var DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';var DESTINATIONS_QUEUE_EXT_POINT_PREFIX='destinationsEventsQueue';
3737
+
3738
+ /**
3739
+ * Event repository class responsible for queuing events for further processing and delivery
3740
+ */var EventRepository=/*#__PURE__*/function(){/**
3741
+ *
3742
+ * @param pluginsManager Plugins manager instance
3743
+ * @param storeManager Store Manager instance
3744
+ * @param errorHandler Error handler object
3745
+ * @param logger Logger object
3746
+ */function EventRepository(pluginsManager,storeManager,errorHandler,logger){_classCallCheck(this,EventRepository);this.pluginsManager=pluginsManager;this.errorHandler=errorHandler;this.logger=logger;this.httpClient=new HttpClient(errorHandler,logger);this.storeManager=storeManager;this.onError=this.onError.bind(this);}/**
3747
+ * Initializes the event repository
3748
+ */_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.destinationsEventsQueue=this.pluginsManager.invokeSingle("".concat(DESTINATIONS_QUEUE_EXT_POINT_PREFIX,".init"),state,this.pluginsManager,this.storeManager,this.errorHandler,this.logger);// Start the queue once the client destinations are ready
3749
+ b(function(){if(state.nativeDestinations.clientDestinationsReady.value===true){_this.destinationsEventsQueue.start();}});}/**
3750
+ * Enqueues the event for processing
3751
+ * @param event RudderEvent object
3752
+ * @param callback API callback function
3753
+ */},{key:"enqueue",value:function enqueue(event,callback){var _this2=this;// Start the queue processing only when the destinations are ready or hybrid mode destinations exist
3754
+ // However, events will be enqueued for now.
3755
+ // At the time of processing the events, the integrations config data from destinations
3756
+ // is merged into the event object
3757
+ b(function(){var _this2$dataplaneEvent;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&&((_this2$dataplaneEvent=_this2.dataplaneEventsQueue)===null||_this2$dataplaneEvent===void 0?void 0:_this2$dataplaneEvent.running)!==true){var _this2$dataplaneEvent2;(_this2$dataplaneEvent2=_this2.dataplaneEventsQueue)===null||_this2$dataplaneEvent2===void 0?void 0:_this2$dataplaneEvent2.start();}});var dpQEvent=clone$1(event);this.pluginsManager.invokeSingle("".concat(DATA_PLANE_QUEUE_EXT_POINT_PREFIX,".enqueue"),state,this.dataplaneEventsQueue,dpQEvent,this.errorHandler,this.logger);var dQEvent=clone$1(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
3758
+ try{// Using the event sent to the data plane queue here
3759
+ // to ensure the mutated (if any) event is sent to the callback
3760
+ callback===null||callback===void 0?void 0:callback(dpQEvent);}catch(error){this.onError(error,'API Callback Invocation Failed');}}/**
3761
+ * Handles error
3762
+ * @param error The error object
3763
+ * @param customMessage a message
3764
+ * @param shouldAlwaysThrow if it should throw or use logger
3765
+ */},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_REPOSITORY,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);return EventRepository;}();
3766
+
3767
+ /*
3768
+ * Analytics class with lifecycle based on state ad user triggered events
3769
+ */var Analytics=/*#__PURE__*/function(){/**
3770
+ * Initialize services and components or use default ones if singletons
3771
+ */function Analytics(){_classCallCheck(this,Analytics);_defineProperty(this,"preloadBuffer",new BufferQueue());this.initialized=false;this.errorHandler=defaultErrorHandler;this.logger=defaultLogger;this.externalSrcLoader=new ExternalSrcLoader(this.errorHandler,this.logger);this.capabilitiesManager=new CapabilitiesManager(this.errorHandler,this.logger);this.httpClient=defaultHttpClient;this.load=this.load.bind(this);this.startLifecycle=this.startLifecycle.bind(this);this.prepareBrowserCapabilities=this.prepareBrowserCapabilities.bind(this);this.enqueuePreloadBufferEvents=this.enqueuePreloadBufferEvents.bind(this);this.processDataInPreloadBuffer=this.processDataInPreloadBuffer.bind(this);this.prepareInternalServices=this.prepareInternalServices.bind(this);this.loadConfig=this.loadConfig.bind(this);this.init=this.init.bind(this);this.loadPlugins=this.loadPlugins.bind(this);this.onLoaded=this.onLoaded.bind(this);this.processBufferedEvents=this.processBufferedEvents.bind(this);this.loadIntegrations=this.loadIntegrations.bind(this);this.onReady=this.onReady.bind(this);this.ready=this.ready.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);}/**
3772
+ * Start application lifecycle if not already started
3773
+ */_createClass(Analytics,[{key:"load",value:function load(writeKey,dataPlaneUrl){var loadOptions=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};if(state.lifecycle.status.value){return;}var clonedDataPlaneUrl=clone$1(dataPlaneUrl);var clonedLoadOptions=clone$1(loadOptions);// dataPlaneUrl is not provided
3774
+ if(isObjectAndNotNull(dataPlaneUrl)){clonedLoadOptions=dataPlaneUrl;clonedDataPlaneUrl=undefined;}// Set initial state values
3775
+ o(function(){state.lifecycle.writeKey.value=writeKey;state.lifecycle.dataPlaneUrl.value=clonedDataPlaneUrl;state.loadOptions.value=normalizeLoadOptions(state.loadOptions.value,clonedLoadOptions);state.lifecycle.status.value=LifecycleStatus.Mounted;});// Expose state to global objects
3776
+ setExposedGlobal('state',state,writeKey);// Configure initial config of any services or components here
3777
+ // State application lifecycle
3778
+ this.startLifecycle();}// Start lifecycle methods
3779
+ /**
3780
+ * Orchestrate the lifecycle of the application phases/status
3781
+ */},{key:"startLifecycle",value:function startLifecycle(){var _this=this;b(function(){switch(state.lifecycle.status.value){case LifecycleStatus.Mounted:_this.prepareBrowserCapabilities();break;case LifecycleStatus.BrowserCapabilitiesReady:// initialize the preloaded events enqueuing
3782
+ retrievePreloadBufferEvents(_this);_this.prepareInternalServices();_this.loadConfig();break;case LifecycleStatus.Configured:_this.loadPlugins();break;case LifecycleStatus.PluginsLoading:break;case LifecycleStatus.PluginsReady:_this.init();break;case LifecycleStatus.Initialized:_this.onLoaded();break;case LifecycleStatus.Loaded:_this.loadIntegrations();_this.processBufferedEvents();break;case LifecycleStatus.DestinationsLoading:break;case LifecycleStatus.DestinationsReady:_this.onReady();break;case LifecycleStatus.Ready:break;}});}/**
3783
+ * Load browser polyfill if required
3784
+ */},{key:"prepareBrowserCapabilities",value:function prepareBrowserCapabilities(){this.capabilitiesManager.init();}/**
3785
+ * Enqueue in SDK preload buffer events, used from preloadBuffer component
3786
+ */},{key:"enqueuePreloadBufferEvents",value:function enqueuePreloadBufferEvents(bufferedEvents){var _this2=this;if(Array.isArray(bufferedEvents)){bufferedEvents.forEach(function(bufferedEvent){return _this2.preloadBuffer.enqueue(clone$1(bufferedEvent));});}}/**
3787
+ * Process the buffer preloaded events by passing their arguments to the respective facade methods
3788
+ */},{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.errorHandler,this.logger,this.pluginsManager);this.eventRepository=new EventRepository(this.pluginsManager,this.storeManager,this.errorHandler,this.logger);this.eventManager=new EventManager(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger);}/**
3789
+ * Load configuration
3790
+ */},{key:"loadConfig",value:function loadConfig(){var _this$configManager;if(!state.lifecycle.writeKey.value){this.errorHandler.onError(new Error('A write key is required to load the SDK. Please provide a valid write key.'),LOAD_CONFIGURATION);return;}this.httpClient.setAuthHeader(state.lifecycle.writeKey.value);(_this$configManager=this.configManager)===null||_this$configManager===void 0?void 0:_this$configManager.init();}/**
3791
+ * Initialize the storage and event queue
3792
+ */},{key:"init",value:function init(){var _this$storeManager,_this$storeManager2,_this$userSessionMana,_this$eventManager;this.errorHandler.init(this.externalSrcLoader);// Initialize storage
3793
+ (_this$storeManager=this.storeManager)===null||_this$storeManager===void 0?void 0:_this$storeManager.init();this.clientDataStore=(_this$storeManager2=this.storeManager)===null||_this$storeManager2===void 0?void 0:_this$storeManager2.getStore(CLIENT_DATA_STORE_NAME);(_this$userSessionMana=this.userSessionManager)===null||_this$userSessionMana===void 0?void 0:_this$userSessionMana.init(this.clientDataStore);// Initialize consent manager
3794
+ if(state.consents.activeConsentManagerPluginName.value){var _this$pluginsManager;(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0?void 0:_this$pluginsManager.invokeSingle("consentManager.init",state,this.storeManager,this.logger);}// Initialize event manager
3795
+ (_this$eventManager=this.eventManager)===null||_this$eventManager===void 0?void 0:_this$eventManager.init();}/**
3796
+ * Load plugins
3797
+ */},{key:"loadPlugins",value:function loadPlugins(){var _this$pluginsManager2;(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===void 0?void 0:_this$pluginsManager2.init();// TODO: are we going to enable custom plugins to be passed as load options?
3798
+ // registerCustomPlugins(state.loadOptions.value.customPlugins);
3799
+ }/**
3800
+ * Trigger onLoaded callback if any is provided in config
3801
+ */},{key:"onLoaded",value:function onLoaded(){// Process any preloaded events
3802
+ this.processDataInPreloadBuffer();// Set lifecycle state
3803
+ o(function(){state.lifecycle.loaded.value=true;state.lifecycle.status.value=LifecycleStatus.Loaded;});// Execute onLoaded callback if provided in load options
3804
+ if(state.loadOptions.value.onLoaded&&isFunction(state.loadOptions.value.onLoaded)){state.loadOptions.value.onLoaded(this);}}/**
3805
+ * Consume preloaded events buffer
3806
+ */},{key:"processBufferedEvents",value:function processBufferedEvents(){var _this3=this;// Process buffered events
3807
+ state.eventBuffer.toBeProcessedArray.value.forEach(function(bufferedItem){var methodName=bufferedItem[0];if(isFunction(_this3[methodName])){var _ref;(_ref=_this3)[methodName].apply(_ref,_toConsumableArray(bufferedItem.slice(1)));}});state.eventBuffer.toBeProcessedArray.value=[];}/**
3808
+ * Load device mode integrations
3809
+ */},{key:"loadIntegrations",value:function loadIntegrations(){var _this$pluginsManager3,_this$pluginsManager4;// Set in state the desired activeIntegrations to inject in DOM
3810
+ (_this$pluginsManager3=this.pluginsManager)===null||_this$pluginsManager3===void 0?void 0:_this$pluginsManager3.invokeSingle('nativeDestinations.setActiveDestinations',state,this.pluginsManager,this.logger);var totalDestinationsToLoad=state.nativeDestinations.activeDestinations.value.length;if(totalDestinationsToLoad===0){state.lifecycle.status.value=LifecycleStatus.DestinationsReady;return;}// Start loading native integration scripts and create instances
3811
+ state.lifecycle.status.value=LifecycleStatus.DestinationsLoading;(_this$pluginsManager4=this.pluginsManager)===null||_this$pluginsManager4===void 0?void 0:_this$pluginsManager4.invokeSingle('nativeDestinations.load',state,this.externalSrcLoader,this.logger);// Progress to next lifecycle phase if all native integrations are initialized or failed
3812
+ b(function(){var areAllDestinationsReady=totalDestinationsToLoad===0||state.nativeDestinations.initializedDestinations.value.length+state.nativeDestinations.failedDestinations.value.length===totalDestinationsToLoad;if(areAllDestinationsReady){o(function(){state.lifecycle.status.value=LifecycleStatus.DestinationsReady;state.nativeDestinations.clientDestinationsReady.value=true;});}});}/**
3813
+ * Invoke the ready callbacks if any exist
3814
+ */ // eslint-disable-next-line class-methods-use-this
3815
+ },{key:"onReady",value:function onReady(){state.eventBuffer.readyCallbacksArray.value.forEach(function(callback){return callback();});state.lifecycle.status.value=LifecycleStatus.Ready;}// End lifecycle methods
3816
+ // Start consumer exposed methods
3817
+ },{key:"ready",value:function ready(callback){var type='ready';this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));if(!isFunction(callback)){this.logger.error(READY_API_CALLBACK_ERROR(READY_API));return;}if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,callback]);return;}/**
3818
+ * If integrations are loaded or no integration is available for loading
3819
+ * execute the callback immediately else push the callbacks to a queue that
3820
+ * will be executed after loading completes
3821
+ */if(state.lifecycle.status.value===LifecycleStatus.Ready){callback();}else {state.eventBuffer.readyCallbacksArray.value.push(callback);}}},{key:"page",value:function page(payload){var _this$eventManager2;var type='page';this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,payload]);return;}(_this$eventManager2=this.eventManager)===null||_this$eventManager2===void 0?void 0:_this$eventManager2.addEvent({type:RudderEventType.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.
3822
+ // Send automatic ad blocked page event if adblockers are detected on the page
3823
+ if(state.capabilities.isAdBlocked.value===true&&payload.category!==ADBLOCK_PAGE_CATEGORY){var pageCallArgs={category:ADBLOCK_PAGE_CATEGORY,name:ADBLOCK_PAGE_NAME,properties:{// 'title' is intentionally omitted as it does not make sense
3824
+ // in v3 implementation
3825
+ path:ADBLOCK_PAGE_PATH},options:state.loadOptions.value.sendAdblockPageOptions};this.page(pageCallArgs);}}},{key:"track",value:function track(payload){var _this$eventManager3;var type='track';this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,payload]);return;}(_this$eventManager3=this.eventManager)===null||_this$eventManager3===void 0?void 0:_this$eventManager3.addEvent({type:RudderEventType.Track,name:payload.name,properties:payload.properties,options:payload.options,callback:payload.callback});}},{key:"identify",value:function identify(payload){var _this$userSessionMana2,_this$userSessionMana3,_this$eventManager4;var type='identify';this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,payload]);return;}var shouldResetSession=Boolean(payload.userId&&state.session.userId.value&&payload.userId!==state.session.userId.value);if(shouldResetSession){this.reset();}(_this$userSessionMana2=this.userSessionManager)===null||_this$userSessionMana2===void 0?void 0:_this$userSessionMana2.setUserId(payload.userId);(_this$userSessionMana3=this.userSessionManager)===null||_this$userSessionMana3===void 0?void 0:_this$userSessionMana3.setUserTraits(payload.traits);(_this$eventManager4=this.eventManager)===null||_this$eventManager4===void 0?void 0:_this$eventManager4.addEvent({type:RudderEventType.Identify,userId:payload.userId,traits:payload.traits,options:payload.options,callback:payload.callback});}},{key:"alias",value:function alias(payload){var _ref2,_payload$from,_this$userSessionMana4,_this$userSessionMana5,_this$eventManager5;var type='alias';this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,payload]);return;}var previousId=(_ref2=(_payload$from=payload.from)!==null&&_payload$from!==void 0?_payload$from:(_this$userSessionMana4=this.userSessionManager)===null||_this$userSessionMana4===void 0?void 0:_this$userSessionMana4.getUserId())!==null&&_ref2!==void 0?_ref2:(_this$userSessionMana5=this.userSessionManager)===null||_this$userSessionMana5===void 0?void 0:_this$userSessionMana5.getAnonymousId();(_this$eventManager5=this.eventManager)===null||_this$eventManager5===void 0?void 0:_this$eventManager5.addEvent({type:RudderEventType.Alias,to:payload.to,from:previousId,options:payload.options,callback:payload.callback});}},{key:"group",value:function group(payload){var _this$userSessionMana6,_this$userSessionMana7,_this$eventManager6;var type='group';this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,payload]);return;}(_this$userSessionMana6=this.userSessionManager)===null||_this$userSessionMana6===void 0?void 0:_this$userSessionMana6.setGroupId(payload.groupId);(_this$userSessionMana7=this.userSessionManager)===null||_this$userSessionMana7===void 0?void 0:_this$userSessionMana7.setGroupTraits(payload.traits);(_this$eventManager6=this.eventManager)===null||_this$eventManager6===void 0?void 0:_this$eventManager6.addEvent({type:RudderEventType.Group,groupId:payload.groupId,traits:payload.traits,options:payload.options,callback:payload.callback});}},{key:"reset",value:function reset(resetAnonymousId){var _this$userSessionMana8;var type='reset';this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation, resetAnonymousId: ").concat(resetAnonymousId));if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,resetAnonymousId]);return;}(_this$userSessionMana8=this.userSessionManager)===null||_this$userSessionMana8===void 0?void 0:_this$userSessionMana8.reset(resetAnonymousId);}},{key:"getAnonymousId",value:function getAnonymousId(options){var _this$userSessionMana9;return (_this$userSessionMana9=this.userSessionManager)===null||_this$userSessionMana9===void 0?void 0:_this$userSessionMana9.getAnonymousId(options);}},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){var _this$userSessionMana10;(_this$userSessionMana10=this.userSessionManager)===null||_this$userSessionMana10===void 0?void 0:_this$userSessionMana10.setAnonymousId(anonymousId,rudderAmpLinkerParam);}// eslint-disable-next-line class-methods-use-this
3826
+ },{key:"getUserId",value:function getUserId(){return state.session.userId.value;}// eslint-disable-next-line class-methods-use-this
3827
+ },{key:"getUserTraits",value:function getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
3828
+ },{key:"getGroupId",value:function getGroupId(){return state.session.groupId.value;}// eslint-disable-next-line class-methods-use-this
3829
+ },{key:"getGroupTraits",value:function getGroupTraits(){return state.session.groupTraits.value;}},{key:"startSession",value:function startSession(sessionId){var _this$userSessionMana11;(_this$userSessionMana11=this.userSessionManager)===null||_this$userSessionMana11===void 0?void 0:_this$userSessionMana11.start(sessionId);}},{key:"endSession",value:function endSession(){var _this$userSessionMana12;(_this$userSessionMana12=this.userSessionManager)===null||_this$userSessionMana12===void 0?void 0:_this$userSessionMana12.end();}// eslint-disable-next-line class-methods-use-this
3830
+ },{key:"getSessionId",value:function getSessionId(){var _this$userSessionMana13,_state$session$sessio,_state$session$sessio2;(_this$userSessionMana13=this.userSessionManager)===null||_this$userSessionMana13===void 0?void 0:_this$userSessionMana13.refreshSession();return (_state$session$sessio=(_state$session$sessio2=state.session.sessionInfo.value)===null||_state$session$sessio2===void 0?void 0:_state$session$sessio2.id)!==null&&_state$session$sessio!==void 0?_state$session$sessio:null;}// End consumer exposed methods
3831
+ }]);return Analytics;}();
3832
+
3833
+ /*
3834
+ * RudderAnalytics facade singleton that is exposed as global object and will:
3835
+ * expose overloaded methods
3836
+ * handle multiple Analytics instances
3837
+ * consume SDK preload event buffer
3838
+ */var RudderAnalytics=/*#__PURE__*/function(){// Singleton with constructor bind methods
3839
+ function RudderAnalytics(){_classCallCheck(this,RudderAnalytics);_defineProperty(this,"analyticsInstances",{});_defineProperty(this,"defaultAnalyticsKey",'');if(RudderAnalytics.globalSingleton){// eslint-disable-next-line no-constructor-return
3840
+ return RudderAnalytics.globalSingleton;}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.getPreloadBuffer=this.getPreloadBuffer.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);RudderAnalytics.globalSingleton=this;// get the preloaded events before replacing global object
3841
+ this.getPreloadBuffer();// start loading if a load event was buffered or wait for explicit load call
3842
+ this.triggerBufferedLoadEvent();// eslint-disable-next-line no-constructor-return
3843
+ return this;}/**
3844
+ * Set instance to use if no specific writeKey is provided in methods
3845
+ * automatically for the first created instance
3846
+ * TODO: to support multiple analytics instances in the near future
3847
+ */_createClass(RudderAnalytics,[{key:"setDefaultInstanceKey",value:function setDefaultInstanceKey(writeKey){if(isEmpty$1(this.analyticsInstances)){this.defaultAnalyticsKey=writeKey;}}/**
3848
+ * Retrieve an existing analytics instance
3849
+ */},{key:"getAnalyticsInstance",value:function getAnalyticsInstance(writeKey){var instanceId=writeKey||this.defaultAnalyticsKey;var analyticsInstanceExists=Boolean(this.analyticsInstances[instanceId]);if(!analyticsInstanceExists){this.analyticsInstances[instanceId]=new Analytics();}return this.analyticsInstances[instanceId];}/**
3850
+ * Create new analytics instance and trigger application lifecycle start
3851
+ */},{key:"load",value:function load(writeKey,dataPlaneUrl,loadOptions){var shouldSkipLoad=!isString(writeKey)||Boolean(this.analyticsInstances[writeKey]);if(shouldSkipLoad){return;}this.setDefaultInstanceKey(writeKey);this.analyticsInstances[writeKey]=new Analytics();this.getAnalyticsInstance(writeKey).load(writeKey,dataPlaneUrl,loadOptions);}/**
3852
+ * Get preloaded events in buffer queue if exists
3853
+ */ // eslint-disable-next-line class-methods-use-this
3854
+ },{key:"getPreloadBuffer",value:function getPreloadBuffer(){var preloadedEventsArray=Array.isArray(globalThis.rudderanalytics)?globalThis.rudderanalytics:[];// Expose buffer to global objects
3855
+ setExposedGlobal(GLOBAL_PRELOAD_BUFFER,clone$1(preloadedEventsArray));}/**
3856
+ * Trigger load event in buffer queue if exists
3857
+ */},{key:"triggerBufferedLoadEvent",value:function triggerBufferedLoadEvent(){var preloadedEventsArray=Array.isArray(globalThis.rudderanalytics)?globalThis.rudderanalytics:[];// Get any load method call that is buffered if any
3858
+ var loadEvent=getPreloadedLoadEvent(preloadedEventsArray);// Process load method if present in the buffered requests
3859
+ if(loadEvent.length>0){// Remove the event name from the Buffered Event array and keep only arguments
3860
+ loadEvent.shift();// eslint-disable-next-line @typescript-eslint/ban-ts-comment
3861
+ // @ts-ignore
3862
+ this.load.apply(null,loadEvent);}}/**
3863
+ * Get ready callback arguments and forward to ready call
3864
+ */},{key:"ready",value:function ready(callback){this.getAnalyticsInstance().ready(callback);}/**
3865
+ * Process page arguments and forward to page call
3866
+ */},{key:"page",value:function page(category,name,properties,options,callback){this.getAnalyticsInstance().page(pageArgumentsToCallOptions(category,name,properties,options,callback));}/**
3867
+ * Process track arguments and forward to page call
3868
+ */},{key:"track",value:function track(event,properties,options,callback){this.getAnalyticsInstance().track(trackArgumentsToCallOptions(event,properties,options,callback));}/**
3869
+ * Process identify arguments and forward to page call
3870
+ */},{key:"identify",value:function identify(userId,traits,options,callback){this.getAnalyticsInstance().identify(identifyArgumentsToCallOptions(userId,traits,options,callback));}/**
3871
+ * Process alias arguments and forward to page call
3872
+ */},{key:"alias",value:function alias(to,from,options,callback){this.getAnalyticsInstance().alias(aliasArgumentsToCallOptions(to,from,options,callback));}/**
3873
+ * Process group arguments and forward to page call
3874
+ */},{key:"group",value:function group(groupId,traits,options,callback){this.getAnalyticsInstance().group(groupArgumentsToCallOptions(groupId,traits,options,callback));}},{key:"reset",value:function reset(resetAnonymousId){this.getAnalyticsInstance().reset(resetAnonymousId);}},{key:"getAnonymousId",value:function getAnonymousId(options){return this.getAnalyticsInstance().getAnonymousId(options);}},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){this.getAnalyticsInstance().setAnonymousId(anonymousId,rudderAmpLinkerParam);}},{key:"getUserId",value:function getUserId(){return this.getAnalyticsInstance().getUserId();}},{key:"getUserTraits",value:function getUserTraits(){return this.getAnalyticsInstance().getUserTraits();}},{key:"getGroupId",value:function getGroupId(){return this.getAnalyticsInstance().getGroupId();}},{key:"getGroupTraits",value:function getGroupTraits(){return this.getAnalyticsInstance().getGroupTraits();}},{key:"startSession",value:function startSession(sessionId){return this.getAnalyticsInstance().startSession(sessionId);}},{key:"endSession",value:function endSession(){return this.getAnalyticsInstance().endSession();}},{key:"getSessionId",value:function getSessionId(){return this.getAnalyticsInstance().getSessionId();}}]);return RudderAnalytics;}();_defineProperty(RudderAnalytics,"globalSingleton",null);
3875
+
3876
+ exports.CookieSameSite = CookieSameSite;
3877
+ exports.LogLevel = LogLevel;
3878
+ exports.PluginName = PluginName;
3879
+ exports.ResidencyServerRegion = ResidencyServerRegion;
3880
+ exports.RudderAnalytics = RudderAnalytics;
3881
+ exports.UaChTrackLevel = UaChTrackLevel;