@rudderstack/analytics-js 3.0.0-beta.5 → 3.0.0-beta.6
Sign up to get free protection for your applications and to get access to all the features.
- package/CHANGELOG.md +19 -0
- package/legacy/cjs/index.js +354 -338
- package/legacy/esm/index.js +354 -338
- package/legacy/umd/index.js +354 -338
- package/modern/cjs/index.js +37 -33
- package/modern/esm/index.js +37 -33
- package/modern/umd/index.js +37 -33
- package/package.json +5 -11
package/legacy/cjs/index.js
CHANGED
@@ -20,331 +20,336 @@ var LogLevel=/*#__PURE__*/function(LogLevel){LogLevel["Log"]="LOG";LogLevel["Inf
|
|
20
20
|
|
21
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
22
|
|
23
|
-
function ownKeys(
|
24
|
-
var
|
23
|
+
function ownKeys(e, r) {
|
24
|
+
var t = Object.keys(e);
|
25
25
|
if (Object.getOwnPropertySymbols) {
|
26
|
-
var
|
27
|
-
|
28
|
-
return Object.getOwnPropertyDescriptor(
|
29
|
-
})),
|
26
|
+
var o = Object.getOwnPropertySymbols(e);
|
27
|
+
r && (o = o.filter(function (r) {
|
28
|
+
return Object.getOwnPropertyDescriptor(e, r).enumerable;
|
29
|
+
})), t.push.apply(t, o);
|
30
30
|
}
|
31
|
-
return
|
31
|
+
return t;
|
32
32
|
}
|
33
|
-
function _objectSpread2(
|
34
|
-
for (var
|
35
|
-
var
|
36
|
-
|
37
|
-
_defineProperty(
|
38
|
-
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(
|
39
|
-
Object.defineProperty(
|
33
|
+
function _objectSpread2(e) {
|
34
|
+
for (var r = 1; r < arguments.length; r++) {
|
35
|
+
var t = null != arguments[r] ? arguments[r] : {};
|
36
|
+
r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
|
37
|
+
_defineProperty(e, r, t[r]);
|
38
|
+
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
|
39
|
+
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
|
40
40
|
});
|
41
41
|
}
|
42
|
-
return
|
42
|
+
return e;
|
43
43
|
}
|
44
44
|
function _regeneratorRuntime() {
|
45
45
|
_regeneratorRuntime = function () {
|
46
|
-
return
|
46
|
+
return e;
|
47
47
|
};
|
48
|
-
var
|
49
|
-
|
50
|
-
|
51
|
-
|
52
|
-
|
48
|
+
var t,
|
49
|
+
e = {},
|
50
|
+
r = Object.prototype,
|
51
|
+
n = r.hasOwnProperty,
|
52
|
+
o = Object.defineProperty || function (t, e, r) {
|
53
|
+
t[e] = r.value;
|
53
54
|
},
|
54
|
-
|
55
|
-
|
56
|
-
|
57
|
-
|
58
|
-
function define(
|
59
|
-
return Object.defineProperty(
|
60
|
-
value:
|
55
|
+
i = "function" == typeof Symbol ? Symbol : {},
|
56
|
+
a = i.iterator || "@@iterator",
|
57
|
+
c = i.asyncIterator || "@@asyncIterator",
|
58
|
+
u = i.toStringTag || "@@toStringTag";
|
59
|
+
function define(t, e, r) {
|
60
|
+
return Object.defineProperty(t, e, {
|
61
|
+
value: r,
|
61
62
|
enumerable: !0,
|
62
63
|
configurable: !0,
|
63
64
|
writable: !0
|
64
|
-
}),
|
65
|
+
}), t[e];
|
65
66
|
}
|
66
67
|
try {
|
67
68
|
define({}, "");
|
68
|
-
} catch (
|
69
|
-
define = function (
|
70
|
-
return
|
69
|
+
} catch (t) {
|
70
|
+
define = function (t, e, r) {
|
71
|
+
return t[e] = r;
|
71
72
|
};
|
72
73
|
}
|
73
|
-
function wrap(
|
74
|
-
var
|
75
|
-
|
76
|
-
|
77
|
-
return
|
78
|
-
value: makeInvokeMethod(
|
79
|
-
}),
|
74
|
+
function wrap(t, e, r, n) {
|
75
|
+
var i = e && e.prototype instanceof Generator ? e : Generator,
|
76
|
+
a = Object.create(i.prototype),
|
77
|
+
c = new Context(n || []);
|
78
|
+
return o(a, "_invoke", {
|
79
|
+
value: makeInvokeMethod(t, r, c)
|
80
|
+
}), a;
|
80
81
|
}
|
81
|
-
function tryCatch(
|
82
|
+
function tryCatch(t, e, r) {
|
82
83
|
try {
|
83
84
|
return {
|
84
85
|
type: "normal",
|
85
|
-
arg:
|
86
|
+
arg: t.call(e, r)
|
86
87
|
};
|
87
|
-
} catch (
|
88
|
+
} catch (t) {
|
88
89
|
return {
|
89
90
|
type: "throw",
|
90
|
-
arg:
|
91
|
+
arg: t
|
91
92
|
};
|
92
93
|
}
|
93
94
|
}
|
94
|
-
|
95
|
-
var
|
95
|
+
e.wrap = wrap;
|
96
|
+
var h = "suspendedStart",
|
97
|
+
l = "suspendedYield",
|
98
|
+
f = "executing",
|
99
|
+
s = "completed",
|
100
|
+
y = {};
|
96
101
|
function Generator() {}
|
97
102
|
function GeneratorFunction() {}
|
98
103
|
function GeneratorFunctionPrototype() {}
|
99
|
-
var
|
100
|
-
define(
|
104
|
+
var p = {};
|
105
|
+
define(p, a, function () {
|
101
106
|
return this;
|
102
107
|
});
|
103
|
-
var
|
104
|
-
|
105
|
-
|
106
|
-
var
|
107
|
-
function defineIteratorMethods(
|
108
|
-
["next", "throw", "return"].forEach(function (
|
109
|
-
define(
|
110
|
-
return this._invoke(
|
108
|
+
var d = Object.getPrototypeOf,
|
109
|
+
v = d && d(d(values([])));
|
110
|
+
v && v !== r && n.call(v, a) && (p = v);
|
111
|
+
var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
|
112
|
+
function defineIteratorMethods(t) {
|
113
|
+
["next", "throw", "return"].forEach(function (e) {
|
114
|
+
define(t, e, function (t) {
|
115
|
+
return this._invoke(e, t);
|
111
116
|
});
|
112
117
|
});
|
113
118
|
}
|
114
|
-
function AsyncIterator(
|
115
|
-
function invoke(
|
116
|
-
var
|
117
|
-
if ("throw" !==
|
118
|
-
var
|
119
|
-
|
120
|
-
return
|
121
|
-
invoke("next",
|
122
|
-
}, function (
|
123
|
-
invoke("throw",
|
124
|
-
}) :
|
125
|
-
|
126
|
-
}, function (
|
127
|
-
return invoke("throw",
|
119
|
+
function AsyncIterator(t, e) {
|
120
|
+
function invoke(r, o, i, a) {
|
121
|
+
var c = tryCatch(t[r], t, o);
|
122
|
+
if ("throw" !== c.type) {
|
123
|
+
var u = c.arg,
|
124
|
+
h = u.value;
|
125
|
+
return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
|
126
|
+
invoke("next", t, i, a);
|
127
|
+
}, function (t) {
|
128
|
+
invoke("throw", t, i, a);
|
129
|
+
}) : e.resolve(h).then(function (t) {
|
130
|
+
u.value = t, i(u);
|
131
|
+
}, function (t) {
|
132
|
+
return invoke("throw", t, i, a);
|
128
133
|
});
|
129
134
|
}
|
130
|
-
|
135
|
+
a(c.arg);
|
131
136
|
}
|
132
|
-
var
|
133
|
-
|
134
|
-
value: function (
|
137
|
+
var r;
|
138
|
+
o(this, "_invoke", {
|
139
|
+
value: function (t, n) {
|
135
140
|
function callInvokeWithMethodAndArg() {
|
136
|
-
return new
|
137
|
-
invoke(
|
141
|
+
return new e(function (e, r) {
|
142
|
+
invoke(t, n, e, r);
|
138
143
|
});
|
139
144
|
}
|
140
|
-
return
|
145
|
+
return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
|
141
146
|
}
|
142
147
|
});
|
143
148
|
}
|
144
|
-
function makeInvokeMethod(
|
145
|
-
var
|
146
|
-
return function (
|
147
|
-
if (
|
148
|
-
if (
|
149
|
-
if ("throw" ===
|
149
|
+
function makeInvokeMethod(e, r, n) {
|
150
|
+
var o = h;
|
151
|
+
return function (i, a) {
|
152
|
+
if (o === f) throw new Error("Generator is already running");
|
153
|
+
if (o === s) {
|
154
|
+
if ("throw" === i) throw a;
|
150
155
|
return {
|
151
|
-
value:
|
156
|
+
value: t,
|
152
157
|
done: !0
|
153
158
|
};
|
154
159
|
}
|
155
|
-
for (
|
156
|
-
var
|
157
|
-
if (
|
158
|
-
var
|
159
|
-
if (
|
160
|
-
if (
|
161
|
-
return
|
160
|
+
for (n.method = i, n.arg = a;;) {
|
161
|
+
var c = n.delegate;
|
162
|
+
if (c) {
|
163
|
+
var u = maybeInvokeDelegate(c, n);
|
164
|
+
if (u) {
|
165
|
+
if (u === y) continue;
|
166
|
+
return u;
|
162
167
|
}
|
163
168
|
}
|
164
|
-
if ("next" ===
|
165
|
-
if (
|
166
|
-
|
167
|
-
} else "return" ===
|
168
|
-
|
169
|
-
var
|
170
|
-
if ("normal" ===
|
171
|
-
if (
|
169
|
+
if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
|
170
|
+
if (o === h) throw o = s, n.arg;
|
171
|
+
n.dispatchException(n.arg);
|
172
|
+
} else "return" === n.method && n.abrupt("return", n.arg);
|
173
|
+
o = f;
|
174
|
+
var p = tryCatch(e, r, n);
|
175
|
+
if ("normal" === p.type) {
|
176
|
+
if (o = n.done ? s : l, p.arg === y) continue;
|
172
177
|
return {
|
173
|
-
value:
|
174
|
-
done:
|
178
|
+
value: p.arg,
|
179
|
+
done: n.done
|
175
180
|
};
|
176
181
|
}
|
177
|
-
"throw" ===
|
182
|
+
"throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
|
178
183
|
}
|
179
184
|
};
|
180
185
|
}
|
181
|
-
function maybeInvokeDelegate(
|
182
|
-
var
|
183
|
-
|
184
|
-
if (
|
185
|
-
var
|
186
|
-
if ("throw" ===
|
187
|
-
var
|
188
|
-
return
|
186
|
+
function maybeInvokeDelegate(e, r) {
|
187
|
+
var n = r.method,
|
188
|
+
o = e.iterator[n];
|
189
|
+
if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
|
190
|
+
var i = tryCatch(o, e.iterator, r.arg);
|
191
|
+
if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
|
192
|
+
var a = i.arg;
|
193
|
+
return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
|
189
194
|
}
|
190
|
-
function pushTryEntry(
|
191
|
-
var
|
192
|
-
tryLoc:
|
195
|
+
function pushTryEntry(t) {
|
196
|
+
var e = {
|
197
|
+
tryLoc: t[0]
|
193
198
|
};
|
194
|
-
1 in
|
199
|
+
1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
|
195
200
|
}
|
196
|
-
function resetTryEntry(
|
197
|
-
var
|
198
|
-
|
201
|
+
function resetTryEntry(t) {
|
202
|
+
var e = t.completion || {};
|
203
|
+
e.type = "normal", delete e.arg, t.completion = e;
|
199
204
|
}
|
200
|
-
function Context(
|
205
|
+
function Context(t) {
|
201
206
|
this.tryEntries = [{
|
202
207
|
tryLoc: "root"
|
203
|
-
}],
|
208
|
+
}], t.forEach(pushTryEntry, this), this.reset(!0);
|
204
209
|
}
|
205
|
-
function values(
|
206
|
-
if (
|
207
|
-
var
|
208
|
-
if (
|
209
|
-
if ("function" == typeof
|
210
|
-
if (!isNaN(
|
211
|
-
var
|
212
|
-
|
213
|
-
for (; ++
|
214
|
-
return next.value =
|
210
|
+
function values(e) {
|
211
|
+
if (e || "" === e) {
|
212
|
+
var r = e[a];
|
213
|
+
if (r) return r.call(e);
|
214
|
+
if ("function" == typeof e.next) return e;
|
215
|
+
if (!isNaN(e.length)) {
|
216
|
+
var o = -1,
|
217
|
+
i = function next() {
|
218
|
+
for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
|
219
|
+
return next.value = t, next.done = !0, next;
|
215
220
|
};
|
216
|
-
return
|
221
|
+
return i.next = i;
|
217
222
|
}
|
218
223
|
}
|
219
|
-
throw new TypeError(typeof
|
224
|
+
throw new TypeError(typeof e + " is not iterable");
|
220
225
|
}
|
221
|
-
return GeneratorFunction.prototype = GeneratorFunctionPrototype,
|
226
|
+
return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
|
222
227
|
value: GeneratorFunctionPrototype,
|
223
228
|
configurable: !0
|
224
|
-
}),
|
229
|
+
}), o(GeneratorFunctionPrototype, "constructor", {
|
225
230
|
value: GeneratorFunction,
|
226
231
|
configurable: !0
|
227
|
-
}), GeneratorFunction.displayName = define(GeneratorFunctionPrototype,
|
228
|
-
var
|
229
|
-
return !!
|
230
|
-
},
|
231
|
-
return Object.setPrototypeOf ? Object.setPrototypeOf(
|
232
|
-
},
|
232
|
+
}), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
|
233
|
+
var e = "function" == typeof t && t.constructor;
|
234
|
+
return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
|
235
|
+
}, e.mark = function (t) {
|
236
|
+
return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
|
237
|
+
}, e.awrap = function (t) {
|
233
238
|
return {
|
234
|
-
__await:
|
239
|
+
__await: t
|
235
240
|
};
|
236
|
-
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype,
|
241
|
+
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
|
237
242
|
return this;
|
238
|
-
}),
|
239
|
-
void 0 ===
|
240
|
-
var
|
241
|
-
return
|
242
|
-
return
|
243
|
+
}), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
|
244
|
+
void 0 === i && (i = Promise);
|
245
|
+
var a = new AsyncIterator(wrap(t, r, n, o), i);
|
246
|
+
return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
|
247
|
+
return t.done ? t.value : a.next();
|
243
248
|
});
|
244
|
-
}, defineIteratorMethods(
|
249
|
+
}, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
|
245
250
|
return this;
|
246
|
-
}), define(
|
251
|
+
}), define(g, "toString", function () {
|
247
252
|
return "[object Generator]";
|
248
|
-
}),
|
249
|
-
var
|
250
|
-
|
251
|
-
for (var
|
252
|
-
return
|
253
|
-
for (;
|
254
|
-
var
|
255
|
-
if (
|
253
|
+
}), e.keys = function (t) {
|
254
|
+
var e = Object(t),
|
255
|
+
r = [];
|
256
|
+
for (var n in e) r.push(n);
|
257
|
+
return r.reverse(), function next() {
|
258
|
+
for (; r.length;) {
|
259
|
+
var t = r.pop();
|
260
|
+
if (t in e) return next.value = t, next.done = !1, next;
|
256
261
|
}
|
257
262
|
return next.done = !0, next;
|
258
263
|
};
|
259
|
-
},
|
264
|
+
}, e.values = values, Context.prototype = {
|
260
265
|
constructor: Context,
|
261
|
-
reset: function (
|
262
|
-
if (this.prev = 0, this.next = 0, this.sent = this._sent =
|
266
|
+
reset: function (e) {
|
267
|
+
if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
|
263
268
|
},
|
264
269
|
stop: function () {
|
265
270
|
this.done = !0;
|
266
|
-
var
|
267
|
-
if ("throw" ===
|
271
|
+
var t = this.tryEntries[0].completion;
|
272
|
+
if ("throw" === t.type) throw t.arg;
|
268
273
|
return this.rval;
|
269
274
|
},
|
270
|
-
dispatchException: function (
|
271
|
-
if (this.done) throw
|
272
|
-
var
|
273
|
-
function handle(
|
274
|
-
return
|
275
|
+
dispatchException: function (e) {
|
276
|
+
if (this.done) throw e;
|
277
|
+
var r = this;
|
278
|
+
function handle(n, o) {
|
279
|
+
return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
|
275
280
|
}
|
276
|
-
for (var
|
277
|
-
var
|
278
|
-
|
279
|
-
if ("root" ===
|
280
|
-
if (
|
281
|
-
var
|
282
|
-
|
283
|
-
if (
|
284
|
-
if (this.prev <
|
285
|
-
if (this.prev <
|
286
|
-
} else if (
|
287
|
-
if (this.prev <
|
281
|
+
for (var o = this.tryEntries.length - 1; o >= 0; --o) {
|
282
|
+
var i = this.tryEntries[o],
|
283
|
+
a = i.completion;
|
284
|
+
if ("root" === i.tryLoc) return handle("end");
|
285
|
+
if (i.tryLoc <= this.prev) {
|
286
|
+
var c = n.call(i, "catchLoc"),
|
287
|
+
u = n.call(i, "finallyLoc");
|
288
|
+
if (c && u) {
|
289
|
+
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
|
290
|
+
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
|
291
|
+
} else if (c) {
|
292
|
+
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
|
288
293
|
} else {
|
289
|
-
if (!
|
290
|
-
if (this.prev <
|
294
|
+
if (!u) throw new Error("try statement without catch or finally");
|
295
|
+
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
|
291
296
|
}
|
292
297
|
}
|
293
298
|
}
|
294
299
|
},
|
295
|
-
abrupt: function (
|
296
|
-
for (var
|
297
|
-
var
|
298
|
-
if (
|
299
|
-
var
|
300
|
+
abrupt: function (t, e) {
|
301
|
+
for (var r = this.tryEntries.length - 1; r >= 0; --r) {
|
302
|
+
var o = this.tryEntries[r];
|
303
|
+
if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
|
304
|
+
var i = o;
|
300
305
|
break;
|
301
306
|
}
|
302
307
|
}
|
303
|
-
|
304
|
-
var
|
305
|
-
return
|
308
|
+
i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
|
309
|
+
var a = i ? i.completion : {};
|
310
|
+
return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
|
306
311
|
},
|
307
|
-
complete: function (
|
308
|
-
if ("throw" ===
|
309
|
-
return "break" ===
|
312
|
+
complete: function (t, e) {
|
313
|
+
if ("throw" === t.type) throw t.arg;
|
314
|
+
return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
|
310
315
|
},
|
311
|
-
finish: function (
|
312
|
-
for (var
|
313
|
-
var
|
314
|
-
if (
|
316
|
+
finish: function (t) {
|
317
|
+
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
|
318
|
+
var r = this.tryEntries[e];
|
319
|
+
if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
|
315
320
|
}
|
316
321
|
},
|
317
|
-
catch: function (
|
318
|
-
for (var
|
319
|
-
var
|
320
|
-
if (
|
321
|
-
var
|
322
|
-
if ("throw" ===
|
323
|
-
var
|
324
|
-
resetTryEntry(
|
322
|
+
catch: function (t) {
|
323
|
+
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
|
324
|
+
var r = this.tryEntries[e];
|
325
|
+
if (r.tryLoc === t) {
|
326
|
+
var n = r.completion;
|
327
|
+
if ("throw" === n.type) {
|
328
|
+
var o = n.arg;
|
329
|
+
resetTryEntry(r);
|
325
330
|
}
|
326
|
-
return
|
331
|
+
return o;
|
327
332
|
}
|
328
333
|
}
|
329
334
|
throw new Error("illegal catch attempt");
|
330
335
|
},
|
331
|
-
delegateYield: function (
|
336
|
+
delegateYield: function (e, r, n) {
|
332
337
|
return this.delegate = {
|
333
|
-
iterator: values(
|
334
|
-
resultName:
|
335
|
-
nextLoc:
|
336
|
-
}, "next" === this.method && (this.arg =
|
338
|
+
iterator: values(e),
|
339
|
+
resultName: r,
|
340
|
+
nextLoc: n
|
341
|
+
}, "next" === this.method && (this.arg = t), y;
|
337
342
|
}
|
338
|
-
},
|
343
|
+
}, e;
|
339
344
|
}
|
340
|
-
function _typeof(
|
345
|
+
function _typeof(o) {
|
341
346
|
"@babel/helpers - typeof";
|
342
347
|
|
343
|
-
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (
|
344
|
-
return typeof
|
345
|
-
} : function (
|
346
|
-
return
|
347
|
-
}, _typeof(
|
348
|
+
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
|
349
|
+
return typeof o;
|
350
|
+
} : function (o) {
|
351
|
+
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
|
352
|
+
}, _typeof(o);
|
348
353
|
}
|
349
354
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
350
355
|
try {
|
@@ -1018,17 +1023,24 @@ if(isDefined(payload.groupId)){payload.groupId=tryStringify(payload.groupId);}el
|
|
1018
1023
|
|
1019
1024
|
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';var RS_APP='RudderStackApplication';var ANALYTICS_CORE='AnalyticsCore';
|
1020
1025
|
|
1021
|
-
var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.0.0-beta.
|
1026
|
+
var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.0.0-beta.6';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';
|
1022
1027
|
|
1023
1028
|
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';
|
1024
1029
|
|
1030
|
+
var DEFAULT_XHR_TIMEOUT_MS=10*1000;// 10 seconds
|
1031
|
+
var DEFAULT_COOKIE_MAX_AGE_MS=31536000*1000;// 1 year
|
1032
|
+
var DEFAULT_SESSION_TIMEOUT_MS=30*60*1000;// 30 minutes
|
1033
|
+
var MIN_SESSION_TIMEOUT_MS=10*1000;// 10 seconds
|
1034
|
+
var DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS=10*1000;// 10 seconds
|
1035
|
+
var DEBOUNCED_TIMEOUT_MS=250;// 250 milliseconds
|
1036
|
+
|
1025
1037
|
/**
|
1026
1038
|
* Create globally accessible RudderStackGlobals object
|
1027
1039
|
*/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]={};}};/**
|
1028
1040
|
* Add move values to globally accessible RudderStackGlobals object per analytics instance
|
1029
1041
|
*/var setExposedGlobal=function setExposedGlobal(keyName,value){var analyticsInstanceId=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'app';createExposedGlobals(analyticsInstanceId);globalThis.RudderStackGlobals[analyticsInstanceId][keyName]=value;};/**
|
1030
1042
|
* Get values from globally accessible RudderStackGlobals object by analytics instance
|
1031
|
-
*/var getExposedGlobal=function getExposedGlobal(keyName){var analyticsInstanceId=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'app';createExposedGlobals(analyticsInstanceId);return globalThis.RudderStackGlobals[analyticsInstanceId][keyName];};
|
1043
|
+
*/var getExposedGlobal=function getExposedGlobal(keyName){var analyticsInstanceId=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'app';createExposedGlobals(analyticsInstanceId);return globalThis.RudderStackGlobals[analyticsInstanceId][keyName];};function debounce(func,thisArg){var delay=arguments.length>2&&arguments[2]!==undefined?arguments[2]:DEBOUNCED_TIMEOUT_MS;var timeoutId;return function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}globalThis.clearTimeout(timeoutId);timeoutId=globalThis.setTimeout(function(){func.apply(thisArg,args);},delay);};}
|
1032
1044
|
|
1033
1045
|
/**
|
1034
1046
|
* Parse query string params into object values for keys that start with a defined prefix
|
@@ -1059,14 +1071,14 @@ var JSON_STRINGIFY='JSONStringify';var getCircularReplacer=function getCircularR
|
|
1059
1071
|
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.
|
1060
1072
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
1061
1073
|
// @ts-ignore-next-line
|
1062
|
-
while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();}if(ancestors.includes(value)){logger===null||logger===void 0
|
1074
|
+
while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();}if(ancestors.includes(value)){logger===null||logger===void 0||logger.warn(CIRCULAR_REFERENCE_WARNING(JSON_STRINGIFY,key));return '[Circular Reference]';}ancestors.push(value);return value;};};/**
|
1063
1075
|
* Utility method for JSON stringify object excluding null values & circular references
|
1064
1076
|
*
|
1065
1077
|
* @param {*} value input
|
1066
1078
|
* @param {boolean} excludeNull if it should exclude nul or not
|
1067
1079
|
* @param {function} logger optional logger methods for warning
|
1068
1080
|
* @returns string
|
1069
|
-
*/var stringifyWithoutCircular=function stringifyWithoutCircular(value,excludeNull,excludeKeys,logger){try{return JSON.stringify(value,getCircularReplacer(excludeNull,excludeKeys,logger));}catch(err){logger===null||logger===void 0
|
1081
|
+
*/var stringifyWithoutCircular=function stringifyWithoutCircular(value,excludeNull,excludeKeys,logger){try{return JSON.stringify(value,getCircularReplacer(excludeNull,excludeKeys,logger));}catch(err){logger===null||logger===void 0||logger.warn(JSON_STRINGIFY_WARNING,err);return null;}};
|
1070
1082
|
|
1071
1083
|
/**
|
1072
1084
|
* Get mutated error with issue prepended to error message
|
@@ -1117,7 +1129,7 @@ timeoutID=globalThis.setTimeout(function(){reject(new Error(SCRIPT_LOAD_TIMEOUT_
|
|
1117
1129
|
* Load external resource of type javascript
|
1118
1130
|
*/_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();}});}/**
|
1119
1131
|
* Handle errors
|
1120
|
-
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0
|
1132
|
+
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,EXTERNAL_SRC_LOADER);}else {throw error;}}}]);return ExternalSrcLoader;}();
|
1121
1133
|
|
1122
1134
|
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);}
|
1123
1135
|
|
@@ -1131,7 +1143,7 @@ var LifecycleStatus=/*#__PURE__*/function(LifecycleStatus){LifecycleStatus["Moun
|
|
1131
1143
|
|
1132
1144
|
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;';/**
|
1133
1145
|
* Service to log messages/data to output provider, default is console
|
1134
|
-
*/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
|
1146
|
+
*/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$logProvider2;(_this$logProvider=(_this$logProvider2=this.logProvider)[logMethod.toLowerCase()])===null||_this$logProvider===void 0||_this$logProvider.call.apply(_this$logProvider,[_this$logProvider2].concat(_toConsumableArray(this.formatLogData(data))));}}},{key:"setScope",value:function setScope(scopeVal){this.scope=scopeVal||this.scope;}// TODO: should we allow to change the level via global variable on run time
|
1135
1147
|
// to assist on the fly debugging?
|
1136
1148
|
},{key:"setMinLogLevel",value:function setMinLogLevel(logLevel){this.minLogLevel=LOG_LEVEL_MAP[logLevel];if(isUndefined(this.minLogLevel)){this.minLogLevel=LOG_LEVEL_MAP[DEFAULT_LOG_LEVEL];}}/**
|
1137
1149
|
* Formats the console message using `scope` and styles
|
@@ -1150,13 +1162,7 @@ var SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','ses
|
|
1150
1162
|
|
1151
1163
|
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
|
1152
1164
|
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
|
1153
|
-
var STORAGE_TYPE_VALIDATION_WARNING=function STORAGE_TYPE_VALIDATION_WARNING(context,storageType,defaultStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(storageType,"\" is not supported. Please choose one of the following supported storage types: \"").concat(SUPPORTED_STORAGE_TYPES,"\". The default storage \"").concat(defaultStorageType,"\" will be used instead.");};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_WARNING=function STORAGE_UNAVAILABLE_WARNING(context,selectedStorageType,finalStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(selectedStorageType,"\" is not available. The SDK will be initialized with \"").concat(finalStorageType,"\" instead.");};var WRITE_KEY_NOT_A_STRING_ERROR=function WRITE_KEY_NOT_A_STRING_ERROR(context,writeKey){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The write key \"").concat(writeKey,"\" is not a string. Please check that the write key is correct and try again.");};var EMPTY_GROUP_CALL_ERROR=function EMPTY_GROUP_CALL_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The group() method must be called with at least one argument.");};var READY_CALLBACK_INVOKE_ERROR="Failed to invoke the ready callback";var API_CALLBACK_INVOKE_ERROR="API Callback Invocation Failed";var INVALID_CONFIG_URL_WARNING=function INVALID_CONFIG_URL_WARNING(context,configUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided config URL \"").concat(configUrl,"\" is invalid. Using the default value instead.");};// DEBUG
|
1154
|
-
|
1155
|
-
var DEFAULT_XHR_TIMEOUT_MS=10*1000;// 10 seconds
|
1156
|
-
var DEFAULT_COOKIE_MAX_AGE_MS=31536000*1000;// 1 year
|
1157
|
-
var DEFAULT_SESSION_TIMEOUT_MS=30*60*1000;// 30 minutes
|
1158
|
-
var MIN_SESSION_TIMEOUT_MS=10*1000;// 10 seconds
|
1159
|
-
var DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS=10*1000;// 10 seconds
|
1165
|
+
var STORAGE_TYPE_VALIDATION_WARNING=function STORAGE_TYPE_VALIDATION_WARNING(context,storageType,defaultStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(storageType,"\" is not supported. Please choose one of the following supported storage types: \"").concat(SUPPORTED_STORAGE_TYPES,"\". The default storage \"").concat(defaultStorageType,"\" will be used instead.");};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_WARNING=function STORAGE_UNAVAILABLE_WARNING(context,selectedStorageType,finalStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(selectedStorageType,"\" is not available. The SDK will be initialized with \"").concat(finalStorageType,"\" instead.");};var WRITE_KEY_NOT_A_STRING_ERROR=function WRITE_KEY_NOT_A_STRING_ERROR(context,writeKey){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The write key \"").concat(writeKey,"\" is not a string. Please check that the write key is correct and try again.");};var EMPTY_GROUP_CALL_ERROR=function EMPTY_GROUP_CALL_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The group() method must be called with at least one argument.");};var READY_CALLBACK_INVOKE_ERROR="Failed to invoke the ready callback";var API_CALLBACK_INVOKE_ERROR="API Callback Invocation Failed";var INVALID_CONFIG_URL_WARNING=function INVALID_CONFIG_URL_WARNING(context,configUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided config URL \"").concat(configUrl,"\" is invalid. Using the default value instead.");};var POLYFILL_SCRIPT_LOAD_ERROR=function POLYFILL_SCRIPT_LOAD_ERROR(scriptId,url){return "Failed to load the polyfill script with ID \"".concat(scriptId,"\" from URL ").concat(url,".");};var COOKIE_DATA_ENCODING_ERROR="Failed to encode the cookie data.";// DEBUG
|
1160
1166
|
|
1161
1167
|
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,"/beta/3.0.0-beta/").concat(BUILD_TYPE,"/").concat(CDN_INT_DIR);var PLUGINS_BASE_URL="".concat(SDK_CDN_BASE_URL,"/beta/3.0.0-beta/").concat(BUILD_TYPE,"/").concat(CDN_PLUGINS_DIR);// TODO: change the above to production URLs when beta phase is done
|
1162
1168
|
// const DEST_SDK_BASE_URL = `${SDK_CDN_BASE_URL}/latest/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${CDN_INT_DIR}`;
|
@@ -1196,12 +1202,12 @@ var defaultStateValues={capabilities:capabilitiesState,consents:consentsState,co
|
|
1196
1202
|
// to next or return the value if it is the last one instead of an array per
|
1197
1203
|
// plugin that is the normal invoke
|
1198
1204
|
// TODO: add invoke method for extension point that we know only one plugin can be used. add invokeMultiple and invokeSingle methods
|
1199
|
-
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
|
1200
|
-
var notExistDeps=plugin.deps.filter(function(dependency){return !_this.byName[dependency];});(_this$logger5=_this.logger)===null||_this$logger5===void 0
|
1205
|
+
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||_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||_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||_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||_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.
|
1206
|
+
var notExistDeps=plugin.deps.filter(function(dependency){return !_this.byName[dependency];});(_this$logger5=_this.logger)===null||_this$logger5===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
|
1201
1207
|
// do some unified pre-process before application starts.
|
1202
1208
|
},{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
|
1203
1209
|
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
|
1204
|
-
if(throws){throw err;}else {var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0
|
1210
|
+
if(throws){throw err;}else {var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===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);
|
1205
1211
|
|
1206
1212
|
var FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';var ERROR_MESSAGES_TO_BE_FILTERED=[FAILED_REQUEST_ERR_MSG_PREFIX];
|
1207
1213
|
|
@@ -1216,7 +1222,7 @@ var FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';var ERROR_MESSAGES_TO_BE_
|
|
1216
1222
|
/**
|
1217
1223
|
* A service to handle errors
|
1218
1224
|
*/var ErrorHandler=/*#__PURE__*/function(){// If no logger is passed errors will be thrown as unhandled error
|
1219
|
-
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
|
1225
|
+
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||_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
|
1220
1226
|
var errorMessage=processError(error);// If no error message after we normalize, then we swallow/ignore the errors
|
1221
1227
|
if(!errorMessage){return;}errorMessage=removeDoubleSpaces("".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(customMessage," ").concat(errorMessage));var normalizedError=error;// Enhance error message
|
1222
1228
|
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;}}/**
|
@@ -1229,7 +1235,7 @@ if(isTypeOfError(error)){normalizedError.message=errorMessage;}else {normalizedE
|
|
1229
1235
|
*
|
1230
1236
|
* @param {Error} error Error instance from handled error
|
1231
1237
|
*/},{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
|
1232
|
-
(_this$logger2=this.logger)===null||_this$logger2===void 0
|
1238
|
+
(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),err);}}}}]);return ErrorHandler;}();var defaultErrorHandler=new ErrorHandler(defaultLogger,defaultPluginEngine);
|
1233
1239
|
|
1234
1240
|
var DestinationConnectionMode=/*#__PURE__*/function(DestinationConnectionMode){DestinationConnectionMode["Hybrid"]="hybrid";DestinationConnectionMode["Cloud"]="cloud";DestinationConnectionMode["Device"]="device";return DestinationConnectionMode;}({});
|
1235
1241
|
|
@@ -1265,7 +1271,7 @@ var hasCrypto$1=function hasCrypto(){return !isNullOrUndefined(globalThis.crypto
|
|
1265
1271
|
|
1266
1272
|
var generateUUID=function generateUUID(){if(hasCrypto$1()){return v4$1();}return v4();};
|
1267
1273
|
|
1268
|
-
var QueueStatuses={IN_PROGRESS:'inProgress',QUEUE:'queue',RECLAIM_START:'reclaimStart',RECLAIM_END:'reclaimEnd',ACK:'ack'};
|
1274
|
+
var QueueStatuses={IN_PROGRESS:'inProgress',QUEUE:'queue',RECLAIM_START:'reclaimStart',RECLAIM_END:'reclaimEnd',ACK:'ack',BATCH_QUEUE:'batchQueue'};
|
1269
1275
|
|
1270
1276
|
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);
|
1271
1277
|
|
@@ -1425,7 +1431,7 @@ var destCNamesToDisplayNamesMap=_objectSpread2(_objectSpread2(_objectSpread2(_ob
|
|
1425
1431
|
var EVENT_PAYLOAD_SIZE_BYTES_LIMIT=32*1024;// 32 KB
|
1426
1432
|
|
1427
1433
|
var INVALID_SOURCE_CONFIG_ERROR="Invalid source configuration or source id.";// ERROR
|
1428
|
-
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_DELIVERY_ERROR=function BEACON_QUEUE_DELIVERY_ERROR(url){return "Failed to send events batch data to the browser's beacon queue for URL ".concat(url,".");};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(destUserFriendlyId){return "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(destUserFriendlyId){return "Failed to initialize destination ".concat(destUserFriendlyId,".");};var DESTINATION_INTEGRATIONS_DATA_ERROR=function DESTINATION_INTEGRATIONS_DATA_ERROR(destUserFriendlyId){return "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="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(key){return "Failed to retrieve or parse data for ".concat(key," from storage.");};var
|
1434
|
+
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_DELIVERY_ERROR=function BEACON_QUEUE_DELIVERY_ERROR(url){return "Failed to send events batch data to the browser's beacon queue for URL ".concat(url,".");};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(destUserFriendlyId){return "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(destUserFriendlyId){return "Failed to initialize destination ".concat(destUserFriendlyId,".");};var DESTINATION_INTEGRATIONS_DATA_ERROR=function DESTINATION_INTEGRATIONS_DATA_ERROR(destUserFriendlyId){return "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="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(key){return "Failed to retrieve or parse data for ".concat(key," from storage.");};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_DELIVERY_FAILURE_ERROR_PREFIX=function EVENT_DELIVERY_FAILURE_ERROR_PREFIX(context,url){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to deliver event(s) 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
|
1429
1435
|
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
|
1430
1436
|
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.");};
|
1431
1437
|
|
@@ -1434,11 +1440,11 @@ var QUEUE_UTILITIES='QueueUtilities';/**
|
|
1434
1440
|
* @param event RudderEvent object
|
1435
1441
|
* @param logger Logger instance
|
1436
1442
|
* @returns stringified event payload. Empty string if error occurs.
|
1437
|
-
*/var getDeliveryPayload$1=function getDeliveryPayload(event,logger){
|
1443
|
+
*/var getDeliveryPayload$1=function getDeliveryPayload(event,logger){return stringifyWithoutCircular(event,true,undefined,logger);};var getBatchDeliveryPayload=function getBatchDeliveryPayload(events,logger){return stringifyWithoutCircular({batch:events},true,undefined,logger);};/**
|
1438
1444
|
* Utility to validate final payload size before sending to server
|
1439
1445
|
* @param event RudderEvent object
|
1440
1446
|
* @param logger Logger instance
|
1441
|
-
*/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
|
1447
|
+
*/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||logger.warn(EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING(QUEUE_UTILITIES,payloadSize,EVENT_PAYLOAD_SIZE_BYTES_LIMIT));}}else {logger===null||logger===void 0||logger.warn(EVENT_PAYLOAD_SIZE_VALIDATION_WARNING(QUEUE_UTILITIES));}};/**
|
1442
1448
|
* Filters and returns the user supplied integrations config that should take preference over the destination specific integrations config
|
1443
1449
|
* @param eventIntgConfig User supplied integrations config at event level
|
1444
1450
|
* @param destinationsIntgConfig Cumulative integrations config from all destinations
|
@@ -1466,7 +1472,7 @@ var DEFAULT_BEACON_QUEUE_OPTIONS={maxItems:DEFAULT_BEACON_QUEUE_MAX_SIZE,flushQu
|
|
1466
1472
|
* @param events RudderEvent object array
|
1467
1473
|
* @param logger Logger instance
|
1468
1474
|
* @returns stringified events payload as Blob, undefined if error occurs.
|
1469
|
-
*/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
|
1475
|
+
*/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||logger.error(BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR(BEACON_QUEUE_PLUGIN));}catch(err){logger===null||logger===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;};
|
1470
1476
|
|
1471
1477
|
var COOKIE_STORAGE='cookieStorage';var LOCAL_STORAGE='localStorage';var SESSION_STORAGE='sessionStorage';var MEMORY_STORAGE='memoryStorage';var NO_STORAGE='none';
|
1472
1478
|
|
@@ -1477,7 +1483,7 @@ var eventsToSend=queue.slice(0);var batchData=getDeliveryPayload(eventsToSend.ma
|
|
1477
1483
|
var isExceededMaxPayloadSize=Boolean(batchData&&batchData.length>MAX_BATCH_PAYLOAD_SIZE_BYTES);if(isExceededMaxPayloadSize){// Flush all previous items
|
1478
1484
|
eventsToSend=queue.slice(0,queue.length-1);this.flushQueue(eventsToSend);// Add only latest item in the remaining queue that is cleared appropriately in flushQueue
|
1479
1485
|
queue=this.getQueue();queue.push(entry);}this.setQueue(this.name,queue);// If queue has total of max items then flush
|
1480
|
-
if(queue.length===this.maxItems){this.flushQueue();}this.start();}},{key:"addItem",value:function addItem(
|
1486
|
+
if(queue.length===this.maxItems){this.flushQueue();}this.start();}},{key:"addItem",value:function addItem(itemData){this.enqueue({item:itemData,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
|
1481
1487
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
1482
1488
|
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
|
1483
1489
|
beaconSendCallback(null);}else {this.nextFlushPending=true;}}}]);return BeaconItemsQueue;}();
|
@@ -1490,7 +1496,7 @@ var pluginName$d='BeaconQueue';var BeaconQueue=function BeaconQueue(){return {na
|
|
1490
1496
|
* @param errorHandler Error handler instance
|
1491
1497
|
* @param logger Logger instance
|
1492
1498
|
* @returns BeaconItemsQueue instance
|
1493
|
-
*/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
|
1499
|
+
*/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||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||logger.error(BEACON_QUEUE_SEND_ERROR(BEACON_QUEUE_PLUGIN));}done(null,isEnqueuedInBeacon);}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,BEACON_QUEUE_PLUGIN,BEACON_QUEUE_DELIVERY_ERROR(url));done(err);}}else {// Mark the item as done so that it can be removed from the queue
|
1494
1500
|
done(null);}};var eventsQueue=new BeaconItemsQueue("".concat(QUEUE_NAME$2,"_").concat(writeKey,"}"),finalQOpts,queueProcessCallback,storeManager);return eventsQueue;},/**
|
1495
1501
|
* Add event to the queue for delivery
|
1496
1502
|
* @param state Application state
|
@@ -1528,15 +1534,15 @@ event.context='Script load failures';}// eslint-disable-next-line no-param-reass
|
|
1528
1534
|
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
|
1529
1535
|
if(!isRudderSDKError(event)){return false;}enhanceErrorEventMutator(event,metadataSource);return true;}catch(_unused){// Drop the error event if it couldn't be filtered as
|
1530
1536
|
// it is most likely a non-SDK error
|
1531
|
-
return false;}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};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.
|
1537
|
+
return false;}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};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.6',// Set SDK version as the app version from build config
|
1532
1538
|
metaData:{SDK:{name:'JS',installType:'npm'}},beforeSend:onError(state),autoCaptureSessions:false,// auto capture sessions is disabled
|
1533
1539
|
collectUserIp:false,// collecting user's IP is disabled
|
1534
1540
|
// enabledBreadcrumbTypes: ['error', 'log', 'user'], // for v7 and above
|
1535
|
-
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
|
1541
|
+
maxEvents:100,maxBreadcrumbs:40,releaseStage:getReleaseStage(),user:{id:state.lifecycle.writeKey.value},logger:logger,networkBreadcrumbsEnabled:false};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||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
|
1536
1542
|
globalThis.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;};
|
1537
1543
|
|
1538
1544
|
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
|
1539
|
-
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
|
1545
|
+
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||client.notify(error,{metaData:{state:getAppStateForMetadata(state)}});},breadcrumb:function breadcrumb(client,message,logger){client===null||client===void 0||client.leaveBreadcrumb(message);}}};};
|
1540
1546
|
|
1541
1547
|
var READY_CHECK_TIMEOUT_MS=11*1000;// 11 seconds
|
1542
1548
|
var SCRIPT_LOAD_TIMEOUT_MS=10*1000;// 10 seconds
|
@@ -1562,16 +1568,16 @@ var isDestIntgConfigTruthy=function isDestIntgConfigTruthy(destIntgConfig){retur
|
|
1562
1568
|
* @param curDestIntgConfig Current destinations integration config
|
1563
1569
|
* @param logger Logger object
|
1564
1570
|
* @returns Combined destinations integrations config
|
1565
|
-
*/var getCumulativeIntegrationsConfig=function getCumulativeIntegrationsConfig(dest,curDestIntgConfig,errorHandler){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,normalizeIntegrationOptions((_dest$instance2=dest.instance)===null||_dest$instance2===void 0?void 0:_dest$instance2.getDataForIntegrationsObject()));}catch(err){errorHandler===null||errorHandler===void 0
|
1566
|
-
if(isHybridModeDestination(initializedDestination)){state.nativeDestinations.integrationsConfig.value=getCumulativeIntegrationsConfig(initializedDestination,state.nativeDestinations.integrationsConfig.value,errorHandler);}state.nativeDestinations.initializedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.initializedDestinations.value),[initializedDestination]);}).catch(function(err){
|
1567
|
-
logger===null||logger===void 0
|
1571
|
+
*/var getCumulativeIntegrationsConfig=function getCumulativeIntegrationsConfig(dest,curDestIntgConfig,errorHandler){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,normalizeIntegrationOptions((_dest$instance2=dest.instance)===null||_dest$instance2===void 0?void 0:_dest$instance2.getDataForIntegrationsObject()));}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,DEVICE_MODE_DESTINATIONS_PLUGIN,DESTINATION_INTEGRATIONS_DATA_ERROR(dest.userFriendlyId));}}return integrationsConfig;};var initializeDestination=function initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger){try{var initializedDestination=clone$1(dest);var destInstance=createDestinationInstance(destSDKIdentifier,sdkTypeName,dest,state);initializedDestination.instance=destInstance;destInstance.init();isDestinationReady(initializedDestination).then(function(){// Collect the integrations data for the hybrid mode destinations
|
1572
|
+
if(isHybridModeDestination(initializedDestination)){state.nativeDestinations.integrationsConfig.value=getCumulativeIntegrationsConfig(initializedDestination,state.nativeDestinations.integrationsConfig.value,errorHandler);}state.nativeDestinations.initializedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.initializedDestinations.value),[initializedDestination]);}).catch(function(err){state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);// The error message is already formatted in the isDestinationReady function
|
1573
|
+
logger===null||logger===void 0||logger.error(err);});}catch(err){state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);errorHandler===null||errorHandler===void 0||errorHandler.onError(err,DEVICE_MODE_DESTINATIONS_PLUGIN,DESTINATION_INIT_ERROR(dest.userFriendlyId));}};
|
1568
1574
|
|
1569
1575
|
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,errorHandler,logger){// Normalize the integration options from the load API call
|
1570
1576
|
state.nativeDestinations.loadOnlyIntegrations.value=normalizeIntegrationOptions(state.loadOptions.value.integrations);state.nativeDestinations.loadIntegration.value=state.loadOptions.value.loadIntegration;// Filter destination that doesn't have mapping config-->Integration names
|
1571
|
-
var configSupportedDestinations=state.nativeDestinations.configuredDestinations.value.filter(function(configDest){if(destDisplayNamesToFileNamesMap[configDest.displayName]){return true;}errorHandler===null||errorHandler===void 0
|
1577
|
+
var configSupportedDestinations=state.nativeDestinations.configuredDestinations.value.filter(function(configDest){if(destDisplayNamesToFileNamesMap[configDest.displayName]){return true;}errorHandler===null||errorHandler===void 0||errorHandler.onError(new Error(DESTINATION_NOT_SUPPORTED_ERROR(configDest.userFriendlyId)),DEVICE_MODE_DESTINATIONS_PLUGIN);return false;});// Filter destinations that are disabled through load options
|
1572
1578
|
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
|
1573
1579
|
(_pluginsManager$invok=pluginsManager.invokeSingle("consentManager.isDestinationConsented",state,dest.config,errorHandler,logger))!==null&&_pluginsManager$invok!==void 0?_pluginsManager$invok:true);});state.nativeDestinations.activeDestinations.value=consentedDestinations;},load:function load(state,externalSrcLoader,errorHandler,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
|
1574
|
-
var sdkTypeName=sdkName;if(!isDestinationSDKMounted(destSDKIdentifier,sdkTypeName)){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){logger===null||logger===void 0
|
1580
|
+
var sdkTypeName=sdkName;if(!isDestinationSDKMounted(destSDKIdentifier,sdkTypeName)){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){logger===null||logger===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]);}else {initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger);}},timeout:SCRIPT_LOAD_TIMEOUT_MS});}else {initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger);}});}}};};
|
1575
1581
|
|
1576
1582
|
/* 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
|
1577
1583
|
// TODO: for now this is a pass through
|
@@ -1681,6 +1687,9 @@ var GoogleLinker=function GoogleLinker(){return {name:pluginName$7,initialize:fu
|
|
1681
1687
|
|
1682
1688
|
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;}();
|
1683
1689
|
|
1690
|
+
var DEFAULT_MIN_RETRY_DELAY_MS=1000;var DEFAULT_MAX_RETRY_DELAY_MS=30000;var DEFAULT_BACKOFF_FACTOR=2;var DEFAULT_BACKOFF_JITTER=0;var DEFAULT_MAX_RETRY_ATTEMPTS=Infinity;var DEFAULT_MAX_ITEMS=Infinity;var DEFAULT_ACK_TIMER_MS=1000;var DEFAULT_RECLAIM_TIMER_MS=3000;var DEFAULT_RECLAIM_TIMEOUT_MS=10000;var DEFAULT_RECLAIM_WAIT_MS=500;var DEFAULT_MAX_BATCH_SIZE_BYTES=1024*1024;// 1MB
|
1691
|
+
var DEFAULT_MAX_BATCH_ITEMS=100;
|
1692
|
+
|
1684
1693
|
var sortByTime=function sortByTime(a,b){return a.time-b.time;};var RETRY_QUEUE='RetryQueue';/**
|
1685
1694
|
* Constructs a RetryQueue backed by localStorage
|
1686
1695
|
*
|
@@ -1688,10 +1697,11 @@ var sortByTime=function sortByTime(a,b){return a.time-b.time;};var RETRY_QUEUE='
|
|
1688
1697
|
* @param {String} name The name of the queue. Will be used to find abandoned queues and retry their items
|
1689
1698
|
* @param {Object} [opts] Optional argument to override `maxItems`, `maxAttempts`, `minRetryDelay, `maxRetryDelay`, `backoffFactor` and `backoffJitter`.
|
1690
1699
|
* @param {QueueProcessCallback} fn The function to call in order to process an item added to the queue
|
1691
|
-
*/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||
|
1692
|
-
this.timeouts={
|
1693
|
-
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
|
1694
|
-
this.ack=this.ack.bind(this);this.checkReclaim=this.checkReclaim.bind(this);this.processHead=this.processHead.bind(this);this.scheduleTimeoutActive=false;}_createClass(RetryQueue,[{key:"
|
1700
|
+
*/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;var queueBatchItemsSizeCalculatorCb=arguments.length>6?arguments[6]:undefined;_classCallCheck(this,RetryQueue);this.storeManager=storeManager;this.name=name;this.id=generateUUID();this.processQueueCb=queueProcessCb;this.maxItems=options.maxItems||DEFAULT_MAX_ITEMS;this.maxAttempts=options.maxAttempts||DEFAULT_MAX_RETRY_ATTEMPTS;this.enableBatching=isObjectLiteralAndNotNull(options.batch);this.queueBatchItemsSizeCalculatorCb=queueBatchItemsSizeCalculatorCb;this.configureBatchingOptions(options);this.logger=logger;this.backoff={minRetryDelay:options.minRetryDelay||DEFAULT_MIN_RETRY_DELAY_MS,maxRetryDelay:options.maxRetryDelay||DEFAULT_MAX_RETRY_DELAY_MS,factor:options.backoffFactor||DEFAULT_BACKOFF_FACTOR,jitter:options.backoffJitter||DEFAULT_BACKOFF_JITTER};// painstakingly tuned. that's why they're not "easily" configurable
|
1701
|
+
this.timeouts={ackTimer:DEFAULT_ACK_TIMER_MS,reclaimTimer:DEFAULT_RECLAIM_TIMER_MS,reclaimTimeout:DEFAULT_RECLAIM_TIMEOUT_MS,reclaimWait:DEFAULT_RECLAIM_WAIT_MS};this.schedule=new Schedule();this.processId='0';// Set up our empty queues
|
1702
|
+
this.store=this.storeManager.setStore({id:this.id,name:this.name,validKeys:QueueStatuses,type:storageType});this.setQueue(QueueStatuses.IN_PROGRESS,{});this.setQueue(QueueStatuses.QUEUE,[]);this.setQueue(QueueStatuses.BATCH_QUEUE,[]);// bind recurring tasks for ease of use
|
1703
|
+
this.ack=this.ack.bind(this);this.checkReclaim=this.checkReclaim.bind(this);this.processHead=this.processHead.bind(this);this.scheduleTimeoutActive=false;}_createClass(RetryQueue,[{key:"configureBatchingOptions",value:function configureBatchingOptions(options){if(this.enableBatching){this.batch=options.batch;if(isDefined(this.batch.maxSize)){this.batch.maxSize=+this.batch.maxSize||DEFAULT_MAX_BATCH_SIZE_BYTES;}if(isDefined(this.batch.maxItems)){this.batch.maxItems=+this.batch.maxItems||DEFAULT_MAX_BATCH_ITEMS;}// if both maxSize and maxItems are undefined, disable batching
|
1704
|
+
if(isUndefined(this.batch.maxSize)&&isUndefined(this.batch.maxItems)){this.enableBatching=false;}}}},{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
|
1695
1705
|
},{key:"setQueue",value:function setQueue(name,value){this.store.set(name!==null&&name!==void 0?name:this.name,value!==null&&value!==void 0?value:[]);}/**
|
1696
1706
|
* Stops processing the queue
|
1697
1707
|
*/},{key:"stop",value:function stop(){this.schedule.cancelAll();this.scheduleTimeoutActive=false;}/**
|
@@ -1707,34 +1717,38 @@ this.ack=this.ack.bind(this);this.checkReclaim=this.checkReclaim.bind(this);this
|
|
1707
1717
|
*
|
1708
1718
|
* @param {Number} attemptNumber The attemptNumber (1 for first retry)
|
1709
1719
|
* @return {Number} The delay in milliseconds to wait before attempting a retry
|
1710
|
-
*/},{key:"getDelay",value:function getDelay(attemptNumber){var ms=this.backoff.
|
1720
|
+
*/},{key:"getDelay",value:function getDelay(attemptNumber){var ms=this.backoff.minRetryDelay*Math.pow(this.backoff.factor,attemptNumber);if(this.backoff.jitter){var rand=Math.random();var deviation=Math.floor(rand*this.backoff.jitter*ms);if(Math.floor(rand*10)<5){ms-=deviation;}else {ms+=deviation;}}return Number(Math.min(ms,this.backoff.maxRetryDelay).toPrecision(1));}},{key:"enqueue",value:function enqueue(entry){var curEntry;if(this.enableBatching){var _ref;var batchQueue=(_ref=this.getQueue(QueueStatuses.BATCH_QUEUE))!==null&&_ref!==void 0?_ref:[];batchQueue=batchQueue.slice(-batchQueue.length);batchQueue.push(entry);// if batch criteria is met, queue the batch events to the main queue and clear batch queue
|
1721
|
+
if(this.isBatchReadyToDispatch(batchQueue)){var batchItems=batchQueue.map(function(queueItem){return queueItem.item;});curEntry=this.generateQueueItem(batchItems);batchQueue=[];}this.setQueue(QueueStatuses.BATCH_QUEUE,batchQueue);}else {curEntry=entry;}// when batching is enabled, `curEntry` could be `undefined` if the batch criteria is not met
|
1722
|
+
if(curEntry){var _ref2;var queue=(_ref2=this.getQueue(QueueStatuses.QUEUE))!==null&&_ref2!==void 0?_ref2:[];queue=queue.slice(-(this.maxItems-1));queue.push(curEntry);queue=queue.sort(sortByTime);this.setQueue(QueueStatuses.QUEUE,queue);if(this.scheduleTimeoutActive){this.processHead();}}}/**
|
1711
1723
|
* Adds an item to the queue
|
1712
1724
|
*
|
1713
|
-
* @param {Object}
|
1714
|
-
*/},{key:"addItem",value:function addItem(
|
1725
|
+
* @param {Object} itemData The item to process
|
1726
|
+
*/},{key:"addItem",value:function addItem(itemData){this.enqueue(this.generateQueueItem(itemData));}},{key:"generateQueueItem",value:function generateQueueItem(itemData){return {item:itemData,attemptNumber:0,time:this.schedule.now(),id:generateUUID()};}/**
|
1715
1727
|
* Adds an item to the retry queue
|
1716
1728
|
*
|
1717
|
-
* @param {Object}
|
1729
|
+
* @param {Object} itemData The item to retry
|
1718
1730
|
* @param {Number} attemptNumber The attempt number (1 for first retry)
|
1719
1731
|
* @param {Error} [error] The error from previous attempt, if there was one
|
1720
1732
|
* @param {String} [id] The id of the queued message used for tracking duplicate entries
|
1721
|
-
*/},{key:"requeue",value:function requeue(
|
1733
|
+
*/},{key:"requeue",value:function requeue(itemData,attemptNumber,error,id){if(this.shouldRetry(itemData,attemptNumber)){this.enqueue({item:itemData,attemptNumber:attemptNumber,time:this.schedule.now()+this.getDelay(attemptNumber),id:id||generateUUID()});}}},{key:"isBatchReadyToDispatch",value:function isBatchReadyToDispatch(batchItems){var _this$batch,_this$batch3;var lengthCriteriaMet=false;if(isDefined((_this$batch=this.batch)===null||_this$batch===void 0?void 0:_this$batch.maxItems)){var _this$batch2;lengthCriteriaMet=batchItems.length>=((_this$batch2=this.batch)===null||_this$batch2===void 0?void 0:_this$batch2.maxItems);}if(lengthCriteriaMet){return true;}var sizeCriteriaMet=false;if(isDefined((_this$batch3=this.batch)===null||_this$batch3===void 0?void 0:_this$batch3.maxSize)&&isDefined(this.queueBatchItemsSizeCalculatorCb)){var _this$batch4;var curBatchSize=this.queueBatchItemsSizeCalculatorCb(batchItems.map(function(queueItem){return queueItem.item;}));sizeCriteriaMet=curBatchSize>=((_this$batch4=this.batch)===null||_this$batch4===void 0?void 0:_this$batch4.maxSize);}return sizeCriteriaMet;}},{key:"processHead",value:function processHead(){var _ref3,_ref4,_this=this,_ref6;// cancel the scheduled task if it exists
|
1722
1734
|
this.schedule.cancel(this.processId);// Pop the head off the queue
|
1723
|
-
var queue=(
|
1724
|
-
var processItemCallback=function processItemCallback(el,id){return function(err,res){var
|
1735
|
+
var queue=(_ref3=this.getQueue(QueueStatuses.QUEUE))!==null&&_ref3!==void 0?_ref3:[];var inProgress=(_ref4=this.getQueue(QueueStatuses.IN_PROGRESS))!==null&&_ref4!==void 0?_ref4:{};var now=this.schedule.now();var toRun=[];// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
1736
|
+
var processItemCallback=function processItemCallback(el,id){return function(err,res){var _ref5;var inProgress=(_ref5=_this.getQueue(QueueStatuses.IN_PROGRESS))!==null&&_ref5!==void 0?_ref5:{};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
|
1725
1737
|
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
|
1726
1738
|
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
|
1727
|
-
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
|
1728
|
-
queue=(
|
1729
|
-
},{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.
|
1730
|
-
addConcatQueue(their.queue,0);//
|
1739
|
+
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||_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
|
1740
|
+
queue=(_ref6=this.getQueue(QueueStatuses.QUEUE))!==null&&_ref6!==void 0?_ref6:[];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
|
1741
|
+
},{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.ackTimer,ScheduleModes.ASAP);}},{key:"reclaim",value:function reclaim(id){var _this$getQueue,_other$get,_other$get2,_other$get3,_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:{},batchQueue:(_other$get2=other.get(QueueStatuses.BATCH_QUEUE))!==null&&_other$get2!==void 0?_other$get2:[],queue:(_other$get3=other.get(QueueStatuses.QUEUE))!==null&&_other$get3!==void 0?_other$get3:[]};var trackMessageIds=[];var addConcatQueue=function addConcatQueue(queue,incrementAttemptNumberBy){var concatIterator=function concatIterator(el){var 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#
|
1742
|
+
addConcatQueue(their.queue,0);// Process batch queue items
|
1743
|
+
if(this.enableBatching){their.batchQueue.forEach(function(el){var id=el.id||generateUUID();if(trackMessageIds.includes(id));else {_this2.enqueue(el);trackMessageIds.push(id);}});}else {// if batching is not enabled in the current instance, add those items to the main queue directly
|
1744
|
+
addConcatQueue(their.batchQueue,0);}// if the queue is abandoned, all the in-progress are failed. retry them immediately and increment the attempt#
|
1731
1745
|
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
|
1732
|
-
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){
|
1746
|
+
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){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(retryError);}}else {var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===void 0||_this$logger3.error(e);}}// process the new items we claimed
|
1733
1747
|
this.processHead();}// eslint-disable-next-line class-methods-use-this
|
1734
|
-
},{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.
|
1748
|
+
},{key:"clearOtherQueue",value:function clearOtherQueue(other,localStorageBackoff){globalThis.setTimeout(function(){other.remove(QueueStatuses.BATCH_QUEUE);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);},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.reclaimWait,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.reclaimWait,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
|
1735
1749
|
continue;}if(parts[0]!==name){// eslint-disable-next-line no-continue
|
1736
1750
|
continue;}if(parts[2]!==QueueStatuses.ACK){// eslint-disable-next-line no-continue
|
1737
|
-
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.
|
1751
|
+
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.reclaimTimeout){return;}tryReclaim(store);});this.schedule.run(this.checkReclaim,this.timeouts.reclaimTimer,ScheduleModes.RESCHEDULE);}}]);return RetryQueue;}();
|
1738
1752
|
|
1739
1753
|
var DEFAULT_QUEUE_OPTIONS={maxItems:100};var QUEUE_NAME$1='rudder_destinations_events';var NATIVE_DESTINATION_QUEUE_PLUGIN='NativeDestinationQueuePlugin';
|
1740
1754
|
|
@@ -1742,7 +1756,7 @@ var getNormalizedQueueOptions$1=function getNormalizedQueueOptions(queueOpts){re
|
|
1742
1756
|
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
|
1743
1757
|
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
|
1744
1758
|
// This will remain until we update the destinations to accept the event directly
|
1745
|
-
(_dest$instance=dest.instance)===null||_dest$instance===void 0||(_dest$instance$method=_dest$instance[methodName])===null||_dest$instance$method===void 0
|
1759
|
+
(_dest$instance=dest.instance)===null||_dest$instance===void 0||(_dest$instance$method=_dest$instance[methodName])===null||_dest$instance$method===void 0||_dest$instance$method.call(_dest$instance,{message:item});}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,NATIVE_DESTINATION_QUEUE_PLUGIN,DESTINATION_EVENT_FORWARDING_ERROR(dest.userFriendlyId));}};
|
1746
1760
|
|
1747
1761
|
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:{/**
|
1748
1762
|
* Initialize the queue for delivery to destinations
|
@@ -1753,7 +1767,7 @@ var pluginName$6='NativeDestinationQueue';var NativeDestinationQueue=function Na
|
|
1753
1767
|
* @param logger Logger instance
|
1754
1768
|
* @returns IQueue instance
|
1755
1769
|
*/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
|
1756
|
-
"".concat(QUEUE_NAME$1,"_").concat(writeKey),finalQOpts,function(rudderEvent,done){var destinationsToSend=filterDestinations(rudderEvent.integrations,state.nativeDestinations.initializedDestinations.value);destinationsToSend.forEach(function(dest){var clonedRudderEvent=clone$1(rudderEvent);var sendEvent=!isEventDenyListed(clonedRudderEvent.type,clonedRudderEvent.event,dest);if(!sendEvent){logger===null||logger===void 0
|
1770
|
+
"".concat(QUEUE_NAME$1,"_").concat(writeKey),finalQOpts,function(rudderEvent,done){var destinationsToSend=filterDestinations(rudderEvent.integrations,state.nativeDestinations.initializedDestinations.value);destinationsToSend.forEach(function(dest){var clonedRudderEvent=clone$1(rudderEvent);var sendEvent=!isEventDenyListed(clonedRudderEvent.type,clonedRudderEvent.event,dest);if(!sendEvent){logger===null||logger===void 0||logger.warn(DESTINATION_EVENT_FILTERING_WARNING(NATIVE_DESTINATION_QUEUE_PLUGIN,clonedRudderEvent.event,dest.userFriendlyId));return;}if(dest.shouldApplyDeviceModeTransformation){pluginsManager.invokeSingle('transformEvent.enqueue',state,clonedRudderEvent,dest,logger);}else {sendEventToDestination(clonedRudderEvent,dest,errorHandler);}});// Mark success always
|
1757
1771
|
done(null);},storeManager,MEMORY_STORAGE);// TODO: This seems to not work as expected. Need to investigate
|
1758
1772
|
// effect(() => {
|
1759
1773
|
// if (state.nativeDestinations.clientDestinationsReady.value === true) {
|
@@ -1779,7 +1793,7 @@ return eventsQueue;},/**
|
|
1779
1793
|
|
1780
1794
|
var ONETRUST_CONSENT_MANAGER_PLUGIN='OneTrustConsentManagerPlugin';
|
1781
1795
|
|
1782
|
-
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
|
1796
|
+
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||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
|
1783
1797
|
// the cookie categories Ids that the user has consented to.
|
1784
1798
|
// Eg: ',C0001,C0003,'
|
1785
1799
|
// We split it and save it as an array.
|
@@ -1790,7 +1804,7 @@ if(!oneTrustCookieCategories){return true;}// Change the structure of oneTrustCo
|
|
1790
1804
|
// Eg:
|
1791
1805
|
// ["Performance Cookies", "Functional Cookies"]
|
1792
1806
|
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.
|
1793
|
-
containsAllConsent=validOneTrustCookieCategories.every(function(element){return Object.keys(allowedConsents).includes(element.trim())||Object.values(allowedConsents).includes(element.trim());});return containsAllConsent;}catch(err){errorHandler===null||errorHandler===void 0
|
1807
|
+
containsAllConsent=validOneTrustCookieCategories.every(function(element){return Object.keys(allowedConsents).includes(element.trim())||Object.values(allowedConsents).includes(element.trim());});return containsAllConsent;}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,ONETRUST_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR);return true;}}}};};
|
1794
1808
|
|
1795
1809
|
var KETCH_CONSENT_MANAGER_PLUGIN='KetchConsentManagerPlugin';var KETCH_CONSENT_COOKIE_NAME_V1='_ketch_consent_v1_';
|
1796
1810
|
|
@@ -1800,8 +1814,8 @@ var KETCH_CONSENT_MANAGER_PLUGIN='KetchConsentManagerPlugin';var KETCH_CONSENT_C
|
|
1800
1814
|
* @param logger Logger instance
|
1801
1815
|
* @returns Consent data from the consent cookie
|
1802
1816
|
*/var getKetchConsentData=function getKetchConsentData(storeManager,logger){var rawConsentCookieData=null;try{// Create a data store instance to read the consent cookie
|
1803
|
-
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
|
1804
|
-
var consentCookieData;try{consentCookieData=JSON.parse(fromBase64(rawConsentCookieData));}catch(err){logger===null||logger===void 0
|
1817
|
+
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||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
|
1818
|
+
var consentCookieData;try{consentCookieData=JSON.parse(fromBase64(rawConsentCookieData));}catch(err){logger===null||logger===void 0||logger.error(KETCH_CONSENT_COOKIE_PARSE_ERROR(KETCH_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(!consentCookieData){return undefined;}// Convert the cookie data to consent data
|
1805
1819
|
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;};/**
|
1806
1820
|
* Gets the consent data in the format expected by the application state
|
1807
1821
|
* @param ketchConsentData Consent data derived from the consent cookie
|
@@ -1817,7 +1831,7 @@ globalThis.getKetchUserDeniedPurposes=function(){var _state$consents$data$2;retu
|
|
1817
1831
|
globalThis.updateKetchConsent=function(ketchConsentData){updateConsentStateFromData(state,ketchConsentData);};// retrieve consent data and update the state
|
1818
1832
|
var ketchConsentData;if(!isUndefined(globalThis.ketchConsent)){ketchConsentData=globalThis.ketchConsent;}else {ketchConsentData=getKetchConsentData(storeManager,logger);}updateConsentStateFromData(state,ketchConsentData);},isDestinationConsented:function isDestinationConsented(state,destConfig,errorHandler,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.
|
1819
1833
|
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.
|
1820
|
-
var containsAnyOfConsent=purposes.some(function(element){return allowedConsents.includes(element.trim());});return containsAnyOfConsent;}catch(err){errorHandler===null||errorHandler===void 0
|
1834
|
+
var containsAnyOfConsent=purposes.some(function(element){return allowedConsents.includes(element.trim());});return containsAnyOfConsent;}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,KETCH_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR);return true;}}}};};
|
1821
1835
|
|
1822
1836
|
var ENCRYPTION_PREFIX_V3='RS_ENC_v3_';
|
1823
1837
|
|
@@ -2991,7 +3005,7 @@ var STORAGE_MIGRATOR_PLUGIN='StorageMigratorPlugin';
|
|
2991
3005
|
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,errorHandler,logger){try{var storedVal=storageEngine.getItem(key);if(isNullOrUndefined(storedVal)){return null;}var decryptedVal=decrypt(storedVal);// The value is not encrypted using legacy encryption
|
2992
3006
|
// Try latest
|
2993
3007
|
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
|
2994
|
-
return JSON.parse(decryptedVal);}catch(err){errorHandler===null||errorHandler===void 0
|
3008
|
+
return JSON.parse(decryptedVal);}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,STORAGE_MIGRATOR_PLUGIN,STORAGE_MIGRATION_ERROR(key));return null;}}}};};
|
2995
3009
|
|
2996
3010
|
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
|
2997
3011
|
isRetryableNWFailure=xhrStatus===429||xhrStatus>=500&&xhrStatus<600;}return isRetryableNWFailure;};
|
@@ -2999,7 +3013,7 @@ isRetryableNWFailure=xhrStatus===429||xhrStatus>=500&&xhrStatus<600;}return isRe
|
|
2999
3013
|
var DEFAULT_RETRY_QUEUE_OPTIONS={maxRetryDelay:360000,minRetryDelay:1000,backoffFactor:2,maxAttempts:10,maxItems:100};var REQUEST_TIMEOUT_MS=10*1000;// 10 seconds
|
3000
3014
|
var DATA_PLANE_API_VERSION='v1';var QUEUE_NAME='rudder';var XHR_QUEUE_PLUGIN='XhrQueuePlugin';
|
3001
3015
|
|
3002
|
-
var getNormalizedQueueOptions=function getNormalizedQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_RETRY_QUEUE_OPTIONS,queueOpts);};var getDeliveryUrl=function getDeliveryUrl(dataplaneUrl,
|
3016
|
+
var getNormalizedQueueOptions=function getNormalizedQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_RETRY_QUEUE_OPTIONS,queueOpts);};var getDeliveryUrl=function getDeliveryUrl(dataplaneUrl,endpoint){var dpUrl=new URL(dataplaneUrl);return new URL(removeDuplicateSlashes([dpUrl.pathname,'/',DATA_PLANE_API_VERSION,'/',endpoint].join('')),dpUrl).href;};var getBatchDeliveryUrl=function getBatchDeliveryUrl(dataplaneUrl){return getDeliveryUrl(dataplaneUrl,'batch');};var logErrorOnFailure=function logErrorOnFailure(details,url,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,url);var dropMsg="The event(s) will be dropped.";if(isRetryableFailure){if(willBeRetried){errMsg="".concat(errMsg," It/they will be retried.");if(attemptNumber>0){errMsg="".concat(errMsg," Retry attempt ").concat(attemptNumber," of ").concat(maxRetryAttempts,".");}}else {errMsg="".concat(errMsg," Retries exhausted (").concat(maxRetryAttempts,"). ").concat(dropMsg);}}else {errMsg="".concat(errMsg," ").concat(dropMsg);}logger===null||logger===void 0||logger.error(errMsg);};var getRequestInfo=function getRequestInfo(itemData,state,logger){var data;var headers;var url;if(Array.isArray(itemData)){var finalEvents=itemData.map(function(queueItemData){return getFinalEventForDeliveryMutator(queueItemData.event,state);});data=getBatchDeliveryPayload(finalEvents,logger);headers=_objectSpread2({},itemData[0].headers);url=getBatchDeliveryUrl(state.lifecycle.activeDataplaneUrl.value);}else {var eventUrl=itemData.url,event=itemData.event,eventHeaders=itemData.headers;var finalEvent=getFinalEventForDeliveryMutator(event,state);data=getDeliveryPayload$1(finalEvent,logger);headers=_objectSpread2({},eventHeaders);url=eventUrl;}return {data:data,headers:headers,url:url};};
|
3003
3017
|
|
3004
3018
|
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:{/**
|
3005
3019
|
* Initialize the queue for delivery
|
@@ -3010,9 +3024,8 @@ var pluginName='XhrQueue';var XhrQueue=function XhrQueue(){return {name:pluginNa
|
|
3010
3024
|
* @param logger Logger instance
|
3011
3025
|
* @returns RetryQueue instance
|
3012
3026
|
*/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
|
3013
|
-
"".concat(QUEUE_NAME,"_").concat(writeKey),finalQOpts,function(
|
3014
|
-
var queueErrResp=isErrRetryable(details)?details:null;logErrorOnFailure(details,
|
3015
|
-
done(null);}},storeManager);return eventsQueue;},/**
|
3027
|
+
"".concat(QUEUE_NAME,"_").concat(writeKey),finalQOpts,function(itemData,done,attemptNumber,maxRetryAttempts,willBeRetried){var _getRequestInfo=getRequestInfo(itemData,state,logger),data=_getRequestInfo.data,url=_getRequestInfo.url,headers=_getRequestInfo.headers;httpClient.getAsyncData({url:url,options:{method:'POST',headers:headers,data:data,sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS,callback:function callback(result,details){// null means item will not be requeued
|
3028
|
+
var queueErrResp=isErrRetryable(details)?details:null;logErrorOnFailure(details,url,willBeRetried,attemptNumber,maxRetryAttempts,logger);done(queueErrResp,result);}});},storeManager,LOCAL_STORAGE,logger,function(itemData){var _getBatchDeliveryPayl;var events=itemData.map(function(queueItemData){return queueItemData.event;});return (_getBatchDeliveryPayl=getBatchDeliveryPayload(events,logger))===null||_getBatchDeliveryPayl===void 0?void 0:_getBatchDeliveryPayl.length;});return eventsQueue;},/**
|
3016
3029
|
* Add event to the queue for delivery
|
3017
3030
|
* @param state Application state
|
3018
3031
|
* @param eventsQueue RetryQueue instance
|
@@ -3056,7 +3069,7 @@ state.lifecycle.status.value=LifecycleStatus.PluginsReady;});}});}/**
|
|
3056
3069
|
},{key:"getPluginsToLoadBasedOnConfig",value:function getPluginsToLoadBasedOnConfig(){var _state$nativeDestinat;// This contains the default plugins if load option has been omitted by user
|
3057
3070
|
var pluginsToLoadFromConfig=state.plugins.pluginsToLoadFromConfig.value;if(!pluginsToLoadFromConfig){return [];}// Error reporting related plugins
|
3058
3071
|
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
|
3059
|
-
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
|
3072
|
+
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||_this$logger.warn(UNSUPPORTED_BEACON_API_WARNING(PLUGINS_MANAGER));}pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return pluginName!==PluginName.BeaconQueue;});}// Device mode destinations related plugins
|
3060
3073
|
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
|
3061
3074
|
var supportedConsentManagerPlugins=Object.values(ConsentManagersToPluginNameMap);pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return !(pluginName!==state.consents.activeConsentManagerPluginName.value&&supportedConsentManagerPlugins.includes(pluginName));});// Storage encryption related plugins
|
3062
3075
|
var supportedStorageEncryptionPlugins=Object.values(StorageEncryptionVersionsToPluginNameMap);pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return !(pluginName!==state.storage.encryptionPluginName.value&&supportedStorageEncryptionPlugins.includes(pluginName));});// Storage migrator related plugins
|
@@ -3103,7 +3116,7 @@ xhr.timeout=timeout;Object.keys(options.headers).forEach(function(headerName){if
|
|
3103
3116
|
* Implement requests in a non-blocking way
|
3104
3117
|
*/},{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);}});}/**
|
3105
3118
|
* Handle errors
|
3106
|
-
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0
|
3119
|
+
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,HTTP_CLIENT);}else {throw error;}}/**
|
3107
3120
|
* Set basic authentication header (eg writekey)
|
3108
3121
|
*/},{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);}/**
|
3109
3122
|
* Clear basic authentication header
|
@@ -3123,7 +3136,7 @@ state.capabilities.isAdBlocked.value=(details===null||details===void 0?void 0:de
|
|
3123
3136
|
|
3124
3137
|
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\./));};
|
3125
3138
|
|
3126
|
-
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
|
3139
|
+
var getUserAgentClientHint=function getUserAgentClientHint(callback){var level=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'none';if(level==='none'){callback(undefined);}if(level==='default'){callback(navigator.userAgentData);}if(level==='full'){var _navigator$userAgentD;(_navigator$userAgentD=navigator.userAgentData)===null||_navigator$userAgentD===void 0||_navigator$userAgentD.getHighEntropyValues(['architecture','bitness','brands','mobile','model','platform','platformVersion','uaFullVersion','fullVersionList','wow64']).then(function(ua){callback(ua);}).catch(function(){callback();});}};
|
3127
3140
|
|
3128
3141
|
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;},requestAnimationFrame:function requestAnimationFrame(){return !isFunction(globalThis.requestAnimationFrame);},cancelAnimationFrame:function cancelAnimationFrame(){return !isFunction(globalThis.cancelAnimationFrame);},CustomEvent:function CustomEvent(){return !isFunction(globalThis.CustomEvent);}};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;break;}}return needsPolyfill;};
|
3129
3142
|
|
@@ -3134,24 +3147,26 @@ var matchingCodes=[22,1014];// [everything except Firefox, Firefox]
|
|
3134
3147
|
var isQuotaExceededError=matchingNames.includes(e.name)||matchingCodes.includes(e.code);return e instanceof DOMException&&isQuotaExceededError;};// TODO: also check for SecurityErrors
|
3135
3148
|
// https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage#exceptions
|
3136
3149
|
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
|
3137
|
-
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
|
3150
|
+
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||logger.error("".concat(msgPrefix).concat(reason,"."),err);return false;}};
|
3138
3151
|
|
3139
3152
|
/**
|
3140
3153
|
* Encode.
|
3141
|
-
*/var encode=function encode(value){return encodeURIComponent(value);};/**
|
3154
|
+
*/var encode=function encode(value,logger){try{return encodeURIComponent(value);}catch(err){logger===null||logger===void 0||logger.error(COOKIE_DATA_ENCODING_ERROR,err);return undefined;}};/**
|
3142
3155
|
* Decode
|
3143
|
-
*/var decode=function decode(value){return decodeURIComponent(value);}
|
3156
|
+
*/var decode=function decode(value){try{return decodeURIComponent(value);}catch(err){// Do nothing as non-RS SDK cookies may not be URI encoded
|
3157
|
+
return undefined;}};/**
|
3144
3158
|
* Parse cookie `str`
|
3145
|
-
*/var parse=function parse(str){var obj={};var pairs=str.split(/\s*;\s*/);var pair;if(!pairs[0]){return obj;}
|
3159
|
+
*/var parse=function parse(str){var obj={};var pairs=str.split(/\s*;\s*/);var pair;if(!pairs[0]){return obj;}// TODO: Decode only the cookies that are needed by the SDK
|
3160
|
+
pairs.forEach(function(pairItem){pair=pairItem.split('=');var keyName=decode(pair[0]);if(keyName){obj[keyName]=decode(pair[1]);}});return obj;};/**
|
3146
3161
|
* Set cookie `name` to `value`
|
3147
|
-
*/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;};/**
|
3162
|
+
*/var set=function set(name,value,optionsConfig,logger){var options=_objectSpread2({},optionsConfig)||{};var cookieString="".concat(encode(name,logger),"=").concat(encode(value,logger));if(isNull(value)){options.maxage=-1;}if(options.maxage){options.expires=new Date(+new Date()+options.maxage);}if(options.path){cookieString+="; path=".concat(options.path);}if(options.domain){cookieString+="; domain=".concat(options.domain);}if(options.expires){cookieString+="; expires=".concat(options.expires.toUTCString());}if(options.samesite){cookieString+="; samesite=".concat(options.samesite);}if(options.secure){cookieString+="; secure";}globalThis.document.cookie=cookieString;};/**
|
3148
3163
|
* Return all cookies
|
3149
3164
|
*/var all=function all(){var cookieStringValue=globalThis.document.cookie;return parse(cookieStringValue);};/**
|
3150
3165
|
* Get cookie `name`
|
3151
3166
|
*/var get=function get(name){return all()[name];};/**
|
3152
3167
|
* Set or get cookie `name` with `value` and `options` object
|
3153
3168
|
*/ // eslint-disable-next-line func-names
|
3154
|
-
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();}};
|
3169
|
+
var cookie=function cookie(name,value,options,logger){switch(arguments.length){case 4:case 3:case 2:return set(name,value,options,logger);case 1:if(name){return get(name);}return all();default:return all();}};
|
3155
3170
|
|
3156
3171
|
var legacyGetHostname=function legacyGetHostname(href){var l=document.createElement('a');l.href=href;return l.hostname;};/**
|
3157
3172
|
* Levels returns all levels of the given url
|
@@ -3181,7 +3196,7 @@ var getDefaultCookieOptions=function getDefaultCookieOptions(){var topDomain=dom
|
|
3181
3196
|
/**
|
3182
3197
|
* A storage utility to persist values in cookies via Storage interface
|
3183
3198
|
*/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
|
3184
|
-
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
|
3199
|
+
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.logger);this.length=Object.keys(cookie()).length;return true;}// eslint-disable-next-line class-methods-use-this
|
3185
3200
|
},{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
|
3186
3201
|
},{key:"clear",value:function clear(){// Not implemented
|
3187
3202
|
// getting a list of all cookie storage keys and remove all values
|
@@ -3239,7 +3254,7 @@ Object.keys(validKeys).forEach(function(key){var value=_this.get(validKeys[key])
|
|
3239
3254
|
_this.remove(key);});this.engine=inMemoryStorage;}/**
|
3240
3255
|
* Set value by key.
|
3241
3256
|
*/},{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
|
3242
|
-
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
|
3257
|
+
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||_this$logger.warn(STORAGE_QUOTA_EXCEEDED_WARNING("Store ".concat(this.id)));// switch to inMemory engine
|
3243
3258
|
this.swapQueueStoreToInMemoryEngine();// and save it there
|
3244
3259
|
this.set(key,value);}else {this.onError(getMutatedError(err,STORE_DATA_SAVE_ERROR(key)));}}}/**
|
3245
3260
|
* Get by Key.
|
@@ -3256,7 +3271,7 @@ return JSON.parse(str);}catch(err){this.onError(new Error("".concat(STORE_DATA_F
|
|
3256
3271
|
* Extension point to use with encryption plugins
|
3257
3272
|
*/},{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:'';}/**
|
3258
3273
|
* Handle errors
|
3259
|
-
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0
|
3274
|
+
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,"Store ".concat(this.id));}else {throw error;}}}]);return Store;}();
|
3260
3275
|
|
3261
3276
|
/**
|
3262
3277
|
* A service to manage stores & available storage client configurations
|
@@ -3265,7 +3280,7 @@ return JSON.parse(str);}catch(err){this.onError(new Error("".concat(STORE_DATA_F
|
|
3265
3280
|
*/_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;}/**
|
3266
3281
|
* Create store to persist data used by the SDK like session, used details etc
|
3267
3282
|
*/},{key:"initClientDataStore",value:function initClientDataStore(){var _getStorageEngine,_getStorageEngine2,_getStorageEngine3;var storageType=state.storage.type.value||COOKIE_STORAGE;var finalStorageType=storageType;switch(storageType){case LOCAL_STORAGE:if(!((_getStorageEngine=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine!==void 0&&_getStorageEngine.isEnabled)){finalStorageType=MEMORY_STORAGE;}break;case MEMORY_STORAGE:finalStorageType=MEMORY_STORAGE;break;case NO_STORAGE:finalStorageType=NO_STORAGE;break;case COOKIE_STORAGE:default:// First try setting the storage to cookie else to local storage
|
3268
|
-
if((_getStorageEngine2=getStorageEngine(COOKIE_STORAGE))!==null&&_getStorageEngine2!==void 0&&_getStorageEngine2.isEnabled){finalStorageType=COOKIE_STORAGE;}else if((_getStorageEngine3=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine3!==void 0&&_getStorageEngine3.isEnabled){finalStorageType=LOCAL_STORAGE;}else {finalStorageType=MEMORY_STORAGE;}break;}if(finalStorageType!==storageType){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0
|
3283
|
+
if((_getStorageEngine2=getStorageEngine(COOKIE_STORAGE))!==null&&_getStorageEngine2!==void 0&&_getStorageEngine2.isEnabled){finalStorageType=COOKIE_STORAGE;}else if((_getStorageEngine3=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine3!==void 0&&_getStorageEngine3.isEnabled){finalStorageType=LOCAL_STORAGE;}else {finalStorageType=MEMORY_STORAGE;}break;}if(finalStorageType!==storageType){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(STORAGE_UNAVAILABLE_WARNING(STORE_MANAGER,storageType,finalStorageType));}// TODO: fill in extra config values and bring them in from StoreManagerOptions if needed
|
3269
3284
|
// TODO: should we pass the keys for all in order to validate or leave free as v1.1?
|
3270
3285
|
if(finalStorageType!==NO_STORAGE){this.setStore({id:CLIENT_DATA_STORE_NAME,name:CLIENT_DATA_STORE_NAME,isEncrypted:true,noCompoundKey:true,type:finalStorageType});}}/**
|
3271
3286
|
* Create a new store
|
@@ -3273,7 +3288,7 @@ if(finalStorageType!==NO_STORAGE){this.setStore({id:CLIENT_DATA_STORE_NAME,name:
|
|
3273
3288
|
* Retrieve a store
|
3274
3289
|
*/},{key:"getStore",value:function getStore(id){return this.stores[id];}/**
|
3275
3290
|
* Handle errors
|
3276
|
-
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0
|
3291
|
+
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,STORE_MANAGER);}else {throw error;}}}]);return StoreManager;}();
|
3277
3292
|
|
3278
3293
|
/**
|
3279
3294
|
* Removes trailing slash from url
|
@@ -3321,7 +3336,10 @@ var defaultOptionalPluginsList=[PluginName.Bugsnag,PluginName.DeviceModeDestinat
|
|
3321
3336
|
*/var isPositiveInteger=function isPositiveInteger(num){return isNumber(num)&&num>=0&&Number.isInteger(num);};
|
3322
3337
|
|
3323
3338
|
var normalizeLoadOptions=function normalizeLoadOptions(loadOptionsFromState,loadOptions){var _normalizedLoadOpts$p;// TODO: Maybe add warnings for invalid values
|
3324
|
-
var normalizedLoadOpts=clone$1(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){delete normalizedLoadOpts.setCookieDomain;}if(!getObjectValues(CookieSameSite).includes(normalizedLoadOpts.sameSiteCookie)){delete normalizedLoadOpts.sameSiteCookie;}normalizedLoadOpts.secureCookie=normalizedLoadOpts.secureCookie===true;if(!getObjectValues(UaChTrackLevel).includes(normalizedLoadOpts.uaChTrackLevel)){delete normalizedLoadOpts.uaChTrackLevel;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.integrations)){delete normalizedLoadOpts.integrations;}normalizedLoadOpts.plugins=(_normalizedLoadOpts$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;if(!isObjectLiteralAndNotNull(normalizedLoadOpts.sendAdblockPageOptions)){delete normalizedLoadOpts.sendAdblockPageOptions;}if(!isDefined(normalizedLoadOpts.loadIntegration)){delete normalizedLoadOpts.loadIntegration;}else {normalizedLoadOpts.loadIntegration=normalizedLoadOpts.loadIntegration===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.storage)){delete normalizedLoadOpts.storage;}else {var _normalizedLoadOpts$s;normalizedLoadOpts.storage=removeUndefinedAndNullValues(normalizedLoadOpts.storage);normalizedLoadOpts.storage.migrate=((_normalizedLoadOpts$s=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s===void 0?void 0:_normalizedLoadOpts$s.migrate)===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.beaconQueueOptions)){delete normalizedLoadOpts.beaconQueueOptions;}else {normalizedLoadOpts.beaconQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.beaconQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.destinationsQueueOptions)){delete normalizedLoadOpts.destinationsQueueOptions;}else {normalizedLoadOpts.destinationsQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.destinationsQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.queueOptions)){delete normalizedLoadOpts.queueOptions;}else {normalizedLoadOpts.queueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.queueOptions);}normalizedLoadOpts.lockIntegrationsVersion=normalizedLoadOpts.lockIntegrationsVersion===true;if(!isNumber(normalizedLoadOpts.dataPlaneEventsBufferTimeout)){delete normalizedLoadOpts.dataPlaneEventsBufferTimeout;}var mergedLoadOptions=mergeDeepRight(loadOptionsFromState,normalizedLoadOpts);return mergedLoadOptions;};var getSourceConfigURL=function getSourceConfigURL(configUrl,writeKey,lockIntegrationsVersion,logger){var defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey:writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString()});var origin=DEFAULT_CONFIG_BE_URL;var searchParams=defSearchParams;var pathname='/sourceConfig/';var hash=''
|
3339
|
+
var normalizedLoadOpts=clone$1(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){delete normalizedLoadOpts.setCookieDomain;}if(!getObjectValues(CookieSameSite).includes(normalizedLoadOpts.sameSiteCookie)){delete normalizedLoadOpts.sameSiteCookie;}normalizedLoadOpts.secureCookie=normalizedLoadOpts.secureCookie===true;if(!getObjectValues(UaChTrackLevel).includes(normalizedLoadOpts.uaChTrackLevel)){delete normalizedLoadOpts.uaChTrackLevel;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.integrations)){delete normalizedLoadOpts.integrations;}normalizedLoadOpts.plugins=(_normalizedLoadOpts$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;if(!isObjectLiteralAndNotNull(normalizedLoadOpts.sendAdblockPageOptions)){delete normalizedLoadOpts.sendAdblockPageOptions;}if(!isDefined(normalizedLoadOpts.loadIntegration)){delete normalizedLoadOpts.loadIntegration;}else {normalizedLoadOpts.loadIntegration=normalizedLoadOpts.loadIntegration===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.storage)){delete normalizedLoadOpts.storage;}else {var _normalizedLoadOpts$s;normalizedLoadOpts.storage=removeUndefinedAndNullValues(normalizedLoadOpts.storage);normalizedLoadOpts.storage.migrate=((_normalizedLoadOpts$s=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s===void 0?void 0:_normalizedLoadOpts$s.migrate)===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.beaconQueueOptions)){delete normalizedLoadOpts.beaconQueueOptions;}else {normalizedLoadOpts.beaconQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.beaconQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.destinationsQueueOptions)){delete normalizedLoadOpts.destinationsQueueOptions;}else {normalizedLoadOpts.destinationsQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.destinationsQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.queueOptions)){delete normalizedLoadOpts.queueOptions;}else {normalizedLoadOpts.queueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.queueOptions);}normalizedLoadOpts.lockIntegrationsVersion=normalizedLoadOpts.lockIntegrationsVersion===true;if(!isNumber(normalizedLoadOpts.dataPlaneEventsBufferTimeout)){delete normalizedLoadOpts.dataPlaneEventsBufferTimeout;}var mergedLoadOptions=mergeDeepRight(loadOptionsFromState,normalizedLoadOpts);return mergedLoadOptions;};var getSourceConfigURL=function getSourceConfigURL(configUrl,writeKey,lockIntegrationsVersion,logger){var defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey:writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString()});var origin=DEFAULT_CONFIG_BE_URL;var searchParams=defSearchParams;var pathname='/sourceConfig/';var hash='';// Ideally, this check is not required but URL polyfill
|
3340
|
+
// doesn't seem to throw errors for empty URLs
|
3341
|
+
// TODO: Need to improve this check to find out if the URL is valid or not
|
3342
|
+
if(configUrl){try{var configUrlInstance=new URL(configUrl);if(!removeTrailingSlashes(configUrlInstance.pathname).endsWith('/sourceConfig')){configUrlInstance.pathname="".concat(removeTrailingSlashes(configUrlInstance.pathname),"/sourceConfig/");}configUrlInstance.pathname=removeDuplicateSlashes(configUrlInstance.pathname);defSearchParams.forEach(function(value,key){if(configUrlInstance.searchParams.get(key)===null){configUrlInstance.searchParams.set(key,value);}});origin=configUrlInstance.origin;pathname=configUrlInstance.pathname;searchParams=configUrlInstance.searchParams;hash=configUrlInstance.hash;}catch(err){logger===null||logger===void 0||logger.warn(INVALID_CONFIG_URL_WARNING(CONFIG_MANAGER,configUrl));}}return "".concat(origin).concat(pathname,"?").concat(searchParams).concat(hash);};
|
3325
3343
|
|
3326
3344
|
/**
|
3327
3345
|
* A function to filter enabled destinations and map to required properties only
|
@@ -3334,7 +3352,7 @@ var DEFAULT_REGION='US';/**
|
|
3334
3352
|
* A function to get url from source config response
|
3335
3353
|
* @param {array} urls An array of objects containing urls
|
3336
3354
|
* @returns
|
3337
|
-
*/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
|
3355
|
+
*/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||logger.warn(UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING(CONFIG_MANAGER,residencyServerRegion,DEFAULT_REGION));return undefined;}return residencyServerRegion;};/**
|
3338
3356
|
* A function to determine the dataPlaneUrl
|
3339
3357
|
* @param {Object} dataplanes An object containing dataPlaneUrl for different region
|
3340
3358
|
* @param {String} serverUrl dataPlaneUrl provided in the load call
|
@@ -3358,9 +3376,9 @@ return sdkURL;};/**
|
|
3358
3376
|
* @param logger Logger instance
|
3359
3377
|
*/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
|
3360
3378
|
var errReportingProviderPlugin=errReportingProvider?ErrorReportingProvidersToPluginNameMap[errReportingProvider]:undefined;if(!isUndefined(errReportingProvider)&&!errReportingProviderPlugin){// set the default error reporting provider
|
3361
|
-
logger===null||logger===void 0
|
3362
|
-
logger===null||logger===void 0
|
3363
|
-
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
|
3379
|
+
logger===null||logger===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
|
3380
|
+
logger===null||logger===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
|
3381
|
+
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||logger.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}});};
|
3364
3382
|
|
3365
3383
|
/**
|
3366
3384
|
* A function that determines integration SDK loading path
|
@@ -3393,19 +3411,19 @@ var sdkURL=getSDKUrl();pluginsCDNPath=sdkURL&&isString(sdkURL)?sdkURL.split('/')
|
|
3393
3411
|
* Output: 'oneTrust'
|
3394
3412
|
*/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;});};
|
3395
3413
|
|
3396
|
-
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
|
3414
|
+
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||_this$logger.setMinLogLevel(state.lifecycle.logLevel.value);});}/**
|
3397
3415
|
* A function to validate, construct and store loadOption, lifecycle, source and destination
|
3398
3416
|
* config related information in global state
|
3399
3417
|
*/},{key:"init",value:function init(){var _this2=this;var consentManagerPluginName;this.attachEffects();var lockIntegrationsVersion=state.loadOptions.value.lockIntegrationsVersion;validateLoadArgs(state.lifecycle.writeKey.value,state.lifecycle.dataPlaneUrl.value);// determine the path to fetch integration SDK from
|
3400
3418
|
var intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,state.loadOptions.value.destSDKBaseURL);// determine the path to fetch remote plugins from
|
3401
3419
|
var pluginsCDNPath=getPluginsCDNPath(state.loadOptions.value.pluginsSDKBaseURL);// Get the consent manager if provided as load option
|
3402
3420
|
var selectedConsentManager=getUserSelectedConsentManager(state.loadOptions.value.cookieConsentManager);if(selectedConsentManager){// Get the corresponding plugin name of the selected consent manager from the supported consent managers
|
3403
|
-
consentManagerPluginName=ConsentManagersToPluginNameMap[selectedConsentManager];if(!consentManagerPluginName){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0
|
3404
|
-
o(function(){var _state$loadOptions$va;state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycle.pluginsCDNPath.value=pluginsCDNPath;if(state.loadOptions.value.logLevel){state.lifecycle.logLevel.value=state.loadOptions.value.logLevel;}
|
3421
|
+
consentManagerPluginName=ConsentManagersToPluginNameMap[selectedConsentManager];if(!consentManagerPluginName){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(UNSUPPORTED_CONSENT_MANAGER_ERROR(CONFIG_MANAGER,selectedConsentManager,ConsentManagersToPluginNameMap));}}updateStorageState(this.logger);// set application lifecycle state in global state
|
3422
|
+
o(function(){var _state$loadOptions$va;state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycle.pluginsCDNPath.value=pluginsCDNPath;if(state.loadOptions.value.logLevel){state.lifecycle.logLevel.value=state.loadOptions.value.logLevel;}state.lifecycle.sourceConfigUrl.value=getSourceConfigURL(state.loadOptions.value.configUrl,state.lifecycle.writeKey.value,lockIntegrationsVersion,_this2.logger);// Set consent manager plugin name in state
|
3405
3423
|
state.consents.activeConsentManagerPluginName.value=consentManagerPluginName;// set storage type in state
|
3406
|
-
var storageType=(_state$loadOptions$va=state.loadOptions.value.storage)===null||_state$loadOptions$va===void 0?void 0:_state$loadOptions$va.type;if(!isValidStorageType(storageType)){var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0
|
3424
|
+
var storageType=(_state$loadOptions$va=state.loadOptions.value.storage)===null||_state$loadOptions$va===void 0?void 0:_state$loadOptions$va.type;if(!isValidStorageType(storageType)){var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0||_this2$logger.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));state.storage.type.value=DEFAULT_STORAGE_TYPE;}else {state.storage.type.value=storageType;}});this.getConfig();}/**
|
3407
3425
|
* Handle errors
|
3408
|
-
*/},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0
|
3426
|
+
*/},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,CONFIG_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}/**
|
3409
3427
|
* A callback function that is executed once we fetch the source config response.
|
3410
3428
|
* Use to construct and store information that are dependent on the sourceConfig.
|
3411
3429
|
*/},{key:"processConfig",value:function processConfig(response,details){var _this3=this;// TODO: add retry logic with backoff based on rejectionDetails.xhr.status
|
@@ -3456,13 +3474,12 @@ state.capabilities.isBeaconAvailable.value=hasBeacon();state.capabilities.isUaCH
|
|
3456
3474
|
state.context.userAgent.value=getUserAgent();state.context.locale.value=getLanguage();state.context.screen.value=getScreenDetails();if(hasUAClientHints()){getUserAgentClientHint(function(uach){state.context['ua-ch'].value=uach;},state.loadOptions.value.uaChTrackLevel);}});// Ad blocker detection
|
3457
3475
|
b(function(){if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(_this.errorHandler,_this.logger);}});}/**
|
3458
3476
|
* Detect if polyfills are required and then load script from polyfill URL
|
3459
|
-
*/},{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
|
3460
|
-
//
|
3461
|
-
var
|
3477
|
+
*/},{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;var isDefaultPolyfillService=polyfillUrl!==state.loadOptions.value.polyfillURL;if(isDefaultPolyfillService){var polyfillCallback=function polyfillCallback(){return _this2.onReady();};// write key specific callback
|
3478
|
+
// NOTE: we're not putting this into RudderStackGlobals as providing the property path to the callback function in the polyfill URL is not possible
|
3479
|
+
var polyfillCallbackName="RS_polyfillCallback_".concat(state.lifecycle.writeKey.value);globalThis[polyfillCallbackName]=polyfillCallback;polyfillUrl="".concat(polyfillUrl,"&callback=").concat(polyfillCallbackName);}(_this$externalSrcLoad=this.externalSrcLoader)===null||_this$externalSrcLoad===void 0||_this$externalSrcLoad.loadJSFile({url:polyfillUrl,id:POLYFILL_SCRIPT_ID,async:true,timeout:POLYFILL_LOAD_TIMEOUT,callback:function callback(scriptId){if(!scriptId){_this2.onError(new Error(POLYFILL_SCRIPT_LOAD_ERROR(POLYFILL_SCRIPT_ID,polyfillUrl)));}else if(!isDefaultPolyfillService){_this2.onReady();}}});}else {this.onReady();}}/**
|
3462
3480
|
* Attach listeners to window to observe event that update capabilities state values
|
3463
3481
|
*/ // eslint-disable-next-line class-methods-use-this
|
3464
|
-
},{key:"attachWindowListeners",value:function attachWindowListeners(){globalThis.addEventListener('offline',function(){state.capabilities.isOnline.value=false;});globalThis.addEventListener('online',function(){state.capabilities.isOnline.value=true;})
|
3465
|
-
}/**
|
3482
|
+
},{key:"attachWindowListeners",value:function attachWindowListeners(){globalThis.addEventListener('offline',function(){state.capabilities.isOnline.value=false;});globalThis.addEventListener('online',function(){state.capabilities.isOnline.value=true;});globalThis.addEventListener('resize',debounce(function(){state.context.screen.value=getScreenDetails();},this));}/**
|
3466
3483
|
* Set the lifecycle status to next phase
|
3467
3484
|
*/ // eslint-disable-next-line class-methods-use-this
|
3468
3485
|
},{key:"onReady",value:function onReady(){this.detectBrowserCapabilities();state.lifecycle.status.value=LifecycleStatus.BrowserCapabilitiesReady;}/**
|
@@ -3492,7 +3509,7 @@ var curPageProps=getDefaultPageProperties();Object.keys(curPageProps).forEach(fu
|
|
3492
3509
|
* @param eventType Rudder event type
|
3493
3510
|
* @param parentKeyPath Object's parent key path
|
3494
3511
|
* @param logger Logger instance
|
3495
|
-
*/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
|
3512
|
+
*/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||logger.warn(RESERVED_KEYWORD_WARNING(EVENT_MANAGER,property,parentKeyPath,RESERVED_ELEMENTS));}});}};/**
|
3496
3513
|
* Checks for reserved keys in traits, properties, and contextual traits
|
3497
3514
|
* @param rudderEvent Generated rudder event
|
3498
3515
|
* @param logger Logger instance
|
@@ -3509,7 +3526,7 @@ rudderEvent.originalTimestamp=options.originalTimestamp;}};/**
|
|
3509
3526
|
* @param rudderContext Generated rudder event
|
3510
3527
|
* @param options API options
|
3511
3528
|
* @param logger Logger instance
|
3512
|
-
*/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
|
3529
|
+
*/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||logger.warn(INVALID_CONTEXT_OBJECT_WARNING(EVENT_MANAGER));}}});return context;};/**
|
3513
3530
|
* A function to determine whether SDK should use the integration option provided in load call
|
3514
3531
|
* @returns boolean
|
3515
3532
|
*/var shouldUseGlobalIntegrationsConfigInEvents=function shouldUseGlobalIntegrationsConfigInEvents(){return state.loadOptions.value.useGlobalIntegrationsConfigInEvents&&isObjectLiteralAndNotNull(state.nativeDestinations.loadOnlyIntegrations.value);};/**
|
@@ -3529,8 +3546,7 @@ rudderEvent.context=getMergedContext(rudderEvent.context,options);}};/**
|
|
3529
3546
|
* @param pageProps Page properties
|
3530
3547
|
* @param logger logger
|
3531
3548
|
* @returns Enriched RudderEvent object
|
3532
|
-
*/var getEnrichedEvent=function getEnrichedEvent(rudderEvent,options,pageProps,logger){var commonEventData={channel:CHANNEL,context:{traits:clone$1(state.session.userTraits.value),sessionId:state.session.sessionInfo.value.id||undefined,sessionStart:state.session.sessionInfo.value.sessionStart||undefined,consentManagement:{deniedConsentIds:clone$1(state.consents.data.value.deniedConsentIds)},'ua-ch':state.context['ua-ch'].value,app:state.context.app.value,library:state.context.library.value,userAgent:state.context.userAgent.value,os:state.context.os.value,locale:state.context.locale.value
|
3533
|
-
screen:getScreenDetails(),campaign:extractUTMParameters(globalThis.location.href),page:getContextPageProperties(pageProps)},originalTimestamp:getCurrentTimeFormatted(),integrations:DEFAULT_INTEGRATIONS_CONFIG,messageId:generateUUID(),userId:rudderEvent.userId||state.session.userId.value};if(state.storage.type.value===NO_STORAGE){// Generate new anonymous id for each request
|
3549
|
+
*/var getEnrichedEvent=function getEnrichedEvent(rudderEvent,options,pageProps,logger){var commonEventData={channel:CHANNEL,context:{traits:clone$1(state.session.userTraits.value),sessionId:state.session.sessionInfo.value.id||undefined,sessionStart:state.session.sessionInfo.value.sessionStart||undefined,consentManagement:{deniedConsentIds:clone$1(state.consents.data.value.deniedConsentIds)},'ua-ch':state.context['ua-ch'].value,app:state.context.app.value,library:state.context.library.value,userAgent:state.context.userAgent.value,os:state.context.os.value,locale:state.context.locale.value,screen:state.context.screen.value,campaign:extractUTMParameters(globalThis.location.href),page:getContextPageProperties(pageProps)},originalTimestamp:getCurrentTimeFormatted(),integrations:DEFAULT_INTEGRATIONS_CONFIG,messageId:generateUUID(),userId:rudderEvent.userId||state.session.userId.value};if(state.storage.type.value===NO_STORAGE){// Generate new anonymous id for each request
|
3534
3550
|
commonEventData.anonymousId=generateUUID();commonEventData.context.anonymousTracking=true;}else {// Type casting to string as the user session manager will take care of initializing the value
|
3535
3551
|
commonEventData.anonymousId=state.session.anonymousUserId.value;}if(rudderEvent.type===RudderEventType.Identify){commonEventData.context.traits=state.storage.type.value!==NO_STORAGE?clone$1(state.session.userTraits.value):rudderEvent.context.traits;}if(rudderEvent.type===RudderEventType.Group){if(rudderEvent.groupId||state.session.groupId.value){commonEventData.groupId=rudderEvent.groupId||state.session.groupId.value;}if(rudderEvent.traits||state.session.groupTraits.value){commonEventData.traits=state.storage.type.value!==NO_STORAGE?clone$1(state.session.groupTraits.value):rudderEvent.traits;}}var processedEvent=mergeDeepRight(rudderEvent,commonEventData);// Set the default values for the event properties
|
3536
3552
|
// matching with v1.1 payload
|
@@ -3595,7 +3611,7 @@ var MIN_SESSION_ID_LENGTH=10;/**
|
|
3595
3611
|
* Function to validate user provided sessionId
|
3596
3612
|
* @param {number} sessionId
|
3597
3613
|
* @returns
|
3598
|
-
*/var isManualSessionIdValid=function isManualSessionIdValid(sessionId,logger){if(!sessionId||!isPositiveInteger(sessionId)||!hasMinLength(MIN_SESSION_ID_LENGTH,sessionId)){logger===null||logger===void 0
|
3614
|
+
*/var isManualSessionIdValid=function isManualSessionIdValid(sessionId,logger){if(!sessionId||!isPositiveInteger(sessionId)||!hasMinLength(MIN_SESSION_ID_LENGTH,sessionId)){logger===null||logger===void 0||logger.warn(INVALID_SESSION_ID_WARNING(USER_SESSION_MANAGER,sessionId,MIN_SESSION_ID_LENGTH));return false;}return true;};/**
|
3599
3615
|
* A function to generate new auto tracking session
|
3600
3616
|
* @param sessionTimeout current timestamp
|
3601
3617
|
* @returns SessionInfo
|
@@ -3618,9 +3634,9 @@ this.setUserId((_this$getUserId=this.getUserId())!==null&&_this$getUserId!==void
|
|
3618
3634
|
this.initializeSessionTracking();// Register the effect to sync with storage
|
3619
3635
|
this.registerEffects();}}},{key:"setDefaultValues",value:function setDefaultValues(){o(function(){state.session.userId.value=defaultUserSessionValues.userId;state.session.userTraits.value=defaultUserSessionValues.userTraits;state.session.groupId.value=defaultUserSessionValues.groupId;state.session.groupTraits.value=defaultUserSessionValues.groupTraits;state.session.anonymousUserId.value=defaultUserSessionValues.anonymousUserId;state.session.initialReferrer.value=defaultUserSessionValues.initialReferrer;state.session.initialReferringDomain.value=defaultUserSessionValues.initialReferringDomain;state.session.sessionInfo.value=defaultUserSessionValues.sessionInfo;});}},{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.errorHandler,_this.logger);_this.syncValueToStorage(storageEntry,migratedVal);});}/**
|
3620
3636
|
* A function to initialize sessionTracking
|
3621
|
-
*/},{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
|
3637
|
+
*/},{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||_this$logger.warn(TIMEOUT_NOT_NUMBER_WARNING(USER_SESSION_MANAGER,configuredSessionTimeout,DEFAULT_SESSION_TIMEOUT_MS));sessionTimeout=DEFAULT_SESSION_TIMEOUT_MS;}else {sessionTimeout=configuredSessionTimeout;}if(sessionTimeout===0){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===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
|
3622
3638
|
// and will proceed with it
|
3623
|
-
if(sessionTimeout>0&&sessionTimeout<MIN_SESSION_TIMEOUT_MS){var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===void 0
|
3639
|
+
if(sessionTimeout>0&&sessionTimeout<MIN_SESSION_TIMEOUT_MS){var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===void 0||_this$logger3.warn(TIMEOUT_NOT_RECOMMENDED_WARNING(USER_SESSION_MANAGER,sessionTimeout,MIN_SESSION_TIMEOUT_MS));}state.session.sessionInfo.value=_objectSpread2(_objectSpread2({},sessionInfo),{},{timeout:sessionTimeout,autoTrack:finalAutoTrackingStatus});// If auto session tracking is enabled start the session tracking
|
3624
3640
|
if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}}/**
|
3625
3641
|
* Handles error
|
3626
3642
|
* @param error The error object
|
@@ -3628,7 +3644,7 @@ if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}}
|
|
3628
3644
|
* A function to sync values in storage
|
3629
3645
|
* @param key
|
3630
3646
|
* @param value
|
3631
|
-
*/},{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
|
3647
|
+
*/},{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||_this$store2.set(key,value);}else {var _this$store3;(_this$store3=this.store)===null||_this$store3===void 0||_this$store3.remove(key);}}/**
|
3632
3648
|
* Function to update storage whenever state value changes
|
3633
3649
|
*/},{key:"registerEffects",value:function registerEffects(){var _this2=this;/**
|
3634
3650
|
* Update userId in storage automatically when userId is updated in state
|
@@ -3722,7 +3738,7 @@ var autoCapturedAnonymousId=(_this$pluginsManager3=this.pluginsManager)===null||
|
|
3722
3738
|
*/},{key:"end",value:function end(){state.session.sessionInfo.value={};}/**
|
3723
3739
|
* Clear storage
|
3724
3740
|
* @param resetAnonymousId
|
3725
|
-
*/},{key:"clearUserSessionStorage",value:function clearUserSessionStorage(resetAnonymousId){var _this$store12,_this$store13,_this$store14,_this$store15;(_this$store12=this.store)===null||_this$store12===void 0
|
3741
|
+
*/},{key:"clearUserSessionStorage",value:function clearUserSessionStorage(resetAnonymousId){var _this$store12,_this$store13,_this$store14,_this$store15;(_this$store12=this.store)===null||_this$store12===void 0||_this$store12.remove(userSessionStorageKeys.userId);(_this$store13=this.store)===null||_this$store13===void 0||_this$store13.remove(userSessionStorageKeys.userTraits);(_this$store14=this.store)===null||_this$store14===void 0||_this$store14.remove(userSessionStorageKeys.groupId);(_this$store15=this.store)===null||_this$store15===void 0||_this$store15.remove(userSessionStorageKeys.groupTraits);if(resetAnonymousId){var _this$store16;(_this$store16=this.store)===null||_this$store16===void 0||_this$store16.remove(userSessionStorageKeys.anonymousUserId);}}}]);return UserSessionManager;}();
|
3726
3742
|
|
3727
3743
|
/**
|
3728
3744
|
* A buffer queue to serve as a store for any type of data
|
@@ -3741,19 +3757,19 @@ var DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';var DESTINATIONS_QU
|
|
3741
3757
|
*/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);}/**
|
3742
3758
|
* Initializes the event repository
|
3743
3759
|
*/_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
|
3744
|
-
b(function(){if(state.nativeDestinations.clientDestinationsReady.value===true){_this.destinationsEventsQueue.start();}})
|
3745
|
-
* Enqueues the event for processing
|
3746
|
-
* @param event RudderEvent object
|
3747
|
-
* @param callback API callback function
|
3748
|
-
*/},{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
|
3760
|
+
b(function(){if(state.nativeDestinations.clientDestinationsReady.value===true){var _this$destinationsEve;(_this$destinationsEve=_this.destinationsEventsQueue)===null||_this$destinationsEve===void 0||_this$destinationsEve.start();}});// Start the queue processing only when the destinations are ready or hybrid mode destinations exist
|
3749
3761
|
// However, events will be enqueued for now.
|
3750
3762
|
// At the time of processing the events, the integrations config data from destinations
|
3751
3763
|
// is merged into the event object
|
3752
|
-
b(function(){var
|
3753
|
-
if(state.loadOptions.value.bufferDataPlaneEventsUntilReady===true){globalThis.setTimeout(function(){var
|
3764
|
+
var timeoutId;b(function(){var _this$dataplaneEvents;var shouldBufferDpEvents=state.loadOptions.value.bufferDataPlaneEventsUntilReady===true&&state.nativeDestinations.clientDestinationsReady.value===false;var hybridDestExist=state.nativeDestinations.activeDestinations.value.some(function(dest){return isHybridModeDestination(dest);});if((hybridDestExist===false||shouldBufferDpEvents===false)&&((_this$dataplaneEvents=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents===void 0?void 0:_this$dataplaneEvents.scheduleTimeoutActive)!==true){var _this$dataplaneEvents2;globalThis.clearTimeout(timeoutId);(_this$dataplaneEvents2=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents2===void 0||_this$dataplaneEvents2.start();}});// Force start the data plane events queue processing after a timeout
|
3765
|
+
if(state.loadOptions.value.bufferDataPlaneEventsUntilReady===true){timeoutId=globalThis.setTimeout(function(){var _this$dataplaneEvents3;if(((_this$dataplaneEvents3=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents3===void 0?void 0:_this$dataplaneEvents3.scheduleTimeoutActive)!==true){var _this$dataplaneEvents4;(_this$dataplaneEvents4=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents4===void 0||_this$dataplaneEvents4.start();}},state.loadOptions.value.dataPlaneEventsBufferTimeout);}}/**
|
3766
|
+
* Enqueues the event for processing
|
3767
|
+
* @param event RudderEvent object
|
3768
|
+
* @param callback API callback function
|
3769
|
+
*/},{key:"enqueue",value:function enqueue(event,callback){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
|
3754
3770
|
try{// Using the event sent to the data plane queue here
|
3755
3771
|
// to ensure the mutated (if any) event is sent to the callback
|
3756
|
-
callback===null||callback===void 0
|
3772
|
+
callback===null||callback===void 0||callback(dpQEvent);}catch(error){this.onError(error,API_CALLBACK_INVOKE_ERROR);}}/**
|
3757
3773
|
* Handles error
|
3758
3774
|
* @param error The error object
|
3759
3775
|
* @param customMessage a message
|
@@ -3783,15 +3799,15 @@ retrievePreloadBufferEvents(_this);_this.prepareInternalServices();_this.loadCon
|
|
3783
3799
|
* Process the buffer preloaded events by passing their arguments to the respective facade methods
|
3784
3800
|
*/},{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);}/**
|
3785
3801
|
* Load configuration
|
3786
|
-
*/},{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
|
3802
|
+
*/},{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||_this$configManager.init();}/**
|
3787
3803
|
* Initialize the storage and event queue
|
3788
3804
|
*/},{key:"init",value:function init(){var _this$storeManager,_this$storeManager2,_this$userSessionMana,_this$eventManager;this.errorHandler.init(this.externalSrcLoader);// Initialize storage
|
3789
|
-
(_this$storeManager=this.storeManager)===null||_this$storeManager===void 0
|
3790
|
-
if(state.consents.activeConsentManagerPluginName.value){var _this$pluginsManager;(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0
|
3791
|
-
(_this$eventManager=this.eventManager)===null||_this$eventManager===void 0
|
3805
|
+
(_this$storeManager=this.storeManager)===null||_this$storeManager===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||_this$userSessionMana.init(this.clientDataStore);// Initialize consent manager
|
3806
|
+
if(state.consents.activeConsentManagerPluginName.value){var _this$pluginsManager;(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0||_this$pluginsManager.invokeSingle("consentManager.init",state,this.storeManager,this.logger);}// Initialize event manager
|
3807
|
+
(_this$eventManager=this.eventManager)===null||_this$eventManager===void 0||_this$eventManager.init();// Mark the SDK as initialized
|
3792
3808
|
state.lifecycle.status.value=LifecycleStatus.Initialized;}/**
|
3793
3809
|
* Load plugins
|
3794
|
-
*/},{key:"loadPlugins",value:function loadPlugins(){var _this$pluginsManager2;(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===void 0
|
3810
|
+
*/},{key:"loadPlugins",value:function loadPlugins(){var _this$pluginsManager2;(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===void 0||_this$pluginsManager2.init();// TODO: are we going to enable custom plugins to be passed as load options?
|
3795
3811
|
// registerCustomPlugins(state.loadOptions.value.customPlugins);
|
3796
3812
|
}/**
|
3797
3813
|
* Trigger onLoaded callback if any is provided in config & emit initialised event
|
@@ -3811,8 +3827,8 @@ var readyEvent=new CustomEvent('RSA_Ready',{detail:{analyticsInstance:globalThis
|
|
3811
3827
|
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=[];}/**
|
3812
3828
|
* Load device mode destinations
|
3813
3829
|
*/},{key:"loadDestinations",value:function loadDestinations(){var _this$pluginsManager3,_this$pluginsManager4;// Set in state the desired activeDestinations to inject in DOM
|
3814
|
-
(_this$pluginsManager3=this.pluginsManager)===null||_this$pluginsManager3===void 0
|
3815
|
-
state.lifecycle.status.value=LifecycleStatus.DestinationsLoading;(_this$pluginsManager4=this.pluginsManager)===null||_this$pluginsManager4===void 0
|
3830
|
+
(_this$pluginsManager3=this.pluginsManager)===null||_this$pluginsManager3===void 0||_this$pluginsManager3.invokeSingle('nativeDestinations.setActiveDestinations',state,this.pluginsManager,this.errorHandler,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
|
3831
|
+
state.lifecycle.status.value=LifecycleStatus.DestinationsLoading;(_this$pluginsManager4=this.pluginsManager)===null||_this$pluginsManager4===void 0||_this$pluginsManager4.invokeSingle('nativeDestinations.load',state,this.externalSrcLoader,this.errorHandler,this.logger);// Progress to next lifecycle phase if all native destinations are initialized or failed
|
3816
3832
|
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;});}});}/**
|
3817
3833
|
* Invoke the ready callbacks if any exist
|
3818
3834
|
*/ // eslint-disable-next-line class-methods-use-this
|
@@ -3822,20 +3838,20 @@ b(function(){var areAllDestinationsReady=totalDestinationsToLoad===0||state.nati
|
|
3822
3838
|
* If destinations are loaded or no integration is available for loading
|
3823
3839
|
* execute the callback immediately else push the callbacks to a queue that
|
3824
3840
|
* will be executed after loading completes
|
3825
|
-
*/if(state.lifecycle.status.value===LifecycleStatus.Ready){try{callback();}catch(err){this.errorHandler.onError(err,ANALYTICS_CORE,READY_CALLBACK_INVOKE_ERROR);}}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
|
3841
|
+
*/if(state.lifecycle.status.value===LifecycleStatus.Ready){try{callback();}catch(err){this.errorHandler.onError(err,ANALYTICS_CORE,READY_CALLBACK_INVOKE_ERROR);}}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||_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.
|
3826
3842
|
// Send automatic ad blocked page event if adblockers are detected on the page
|
3827
3843
|
// Check page category to avoid infinite loop
|
3828
3844
|
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
|
3829
3845
|
// in v3 implementation
|
3830
|
-
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
|
3831
|
-
if(!isNull(payload.userId)){var _this$userSessionMana2;(_this$userSessionMana2=this.userSessionManager)===null||_this$userSessionMana2===void 0
|
3832
|
-
if(!isNull(payload.groupId)){var _this$userSessionMana6;(_this$userSessionMana6=this.userSessionManager)===null||_this$userSessionMana6===void 0
|
3833
|
-
if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,anonymousId,rudderAmpLinkerParam]);return;}(_this$userSessionMana10=this.userSessionManager)===null||_this$userSessionMana10===void 0
|
3846
|
+
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||_this$eventManager3.addEvent({type:RudderEventType.Track,name:payload.name||undefined,properties:payload.properties,options:payload.options,callback:payload.callback});}},{key:"identify",value:function identify(payload){var _this$userSessionMana3,_this$eventManager4;var type='identify';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();}// `null` value indicates that previous user ID needs to be retained
|
3847
|
+
if(!isNull(payload.userId)){var _this$userSessionMana2;(_this$userSessionMana2=this.userSessionManager)===null||_this$userSessionMana2===void 0||_this$userSessionMana2.setUserId(payload.userId);}(_this$userSessionMana3=this.userSessionManager)===null||_this$userSessionMana3===void 0||_this$userSessionMana3.setUserTraits(payload.traits);(_this$eventManager4=this.eventManager)===null||_this$eventManager4===void 0||_this$eventManager4.addEvent({type: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||_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$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;}// `null` value indicates that previous group ID needs to be retained
|
3848
|
+
if(!isNull(payload.groupId)){var _this$userSessionMana6;(_this$userSessionMana6=this.userSessionManager)===null||_this$userSessionMana6===void 0||_this$userSessionMana6.setGroupId(payload.groupId);}(_this$userSessionMana7=this.userSessionManager)===null||_this$userSessionMana7===void 0||_this$userSessionMana7.setGroupTraits(payload.traits);(_this$eventManager6=this.eventManager)===null||_this$eventManager6===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||_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;var type='setAnonymousId';// Buffering is needed as setting the anonymous ID may require invoking the GoogleLinker plugin
|
3849
|
+
if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,anonymousId,rudderAmpLinkerParam]);return;}(_this$userSessionMana10=this.userSessionManager)===null||_this$userSessionMana10===void 0||_this$userSessionMana10.setAnonymousId(anonymousId,rudderAmpLinkerParam);}// eslint-disable-next-line class-methods-use-this
|
3834
3850
|
},{key:"getUserId",value:function getUserId(){return state.session.userId.value;}// eslint-disable-next-line class-methods-use-this
|
3835
3851
|
},{key:"getUserTraits",value:function getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
|
3836
3852
|
},{key:"getGroupId",value:function getGroupId(){return state.session.groupId.value;}// eslint-disable-next-line class-methods-use-this
|
3837
|
-
},{key:"getGroupTraits",value:function getGroupTraits(){return state.session.groupTraits.value;}},{key:"startSession",value:function startSession(sessionId){var _this$userSessionMana11;var type='startSession';this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,sessionId]);return;}(_this$userSessionMana11=this.userSessionManager)===null||_this$userSessionMana11===void 0
|
3838
|
-
},{key:"getSessionId",value:function getSessionId(){var _this$userSessionMana13,_state$session$sessio,_state$session$sessio2;(_this$userSessionMana13=this.userSessionManager)===null||_this$userSessionMana13===void 0
|
3853
|
+
},{key:"getGroupTraits",value:function getGroupTraits(){return state.session.groupTraits.value;}},{key:"startSession",value:function startSession(sessionId){var _this$userSessionMana11;var type='startSession';this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,sessionId]);return;}(_this$userSessionMana11=this.userSessionManager)===null||_this$userSessionMana11===void 0||_this$userSessionMana11.start(sessionId);}},{key:"endSession",value:function endSession(){var _this$userSessionMana12;var type='endSession';this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type]);return;}(_this$userSessionMana12=this.userSessionManager)===null||_this$userSessionMana12===void 0||_this$userSessionMana12.end();}// eslint-disable-next-line class-methods-use-this
|
3854
|
+
},{key:"getSessionId",value:function getSessionId(){var _this$userSessionMana13,_state$session$sessio,_state$session$sessio2;(_this$userSessionMana13=this.userSessionManager)===null||_this$userSessionMana13===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
|
3839
3855
|
}]);return Analytics;}();
|
3840
3856
|
|
3841
3857
|
/*
|