@usermaven/sdk-js 1.4.1-rc.62 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2682 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ /******************************************************************************
6
+ Copyright (c) Microsoft Corporation.
7
+
8
+ Permission to use, copy, modify, and/or distribute this software for any
9
+ purpose with or without fee is hereby granted.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
16
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17
+ PERFORMANCE OF THIS SOFTWARE.
18
+ ***************************************************************************** */
19
+
20
+ var __assign = function() {
21
+ __assign = Object.assign || function __assign(t) {
22
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
23
+ s = arguments[i];
24
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
25
+ }
26
+ return t;
27
+ };
28
+ return __assign.apply(this, arguments);
29
+ };
30
+
31
+ function __rest(s, e) {
32
+ var t = {};
33
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
34
+ t[p] = s[p];
35
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
36
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
37
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
38
+ t[p[i]] = s[p[i]];
39
+ }
40
+ return t;
41
+ }
42
+
43
+ function __awaiter(thisArg, _arguments, P, generator) {
44
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
45
+ return new (P || (P = Promise))(function (resolve, reject) {
46
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
47
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
48
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
49
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
50
+ });
51
+ }
52
+
53
+ function __generator(thisArg, body) {
54
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
55
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
56
+ function verb(n) { return function (v) { return step([n, v]); }; }
57
+ function step(op) {
58
+ if (f) throw new TypeError("Generator is already executing.");
59
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
60
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
61
+ if (y = 0, t) op = [op[0] & 2, t.value];
62
+ switch (op[0]) {
63
+ case 0: case 1: t = op; break;
64
+ case 4: _.label++; return { value: op[1], done: false };
65
+ case 5: _.label++; y = op[1]; op = [0]; continue;
66
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
67
+ default:
68
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
69
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
70
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
71
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
72
+ if (t[2]) _.ops.pop();
73
+ _.trys.pop(); continue;
74
+ }
75
+ op = body.call(thisArg, _);
76
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
77
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
78
+ }
79
+ }
80
+
81
+ function __spreadArray(to, from, pack) {
82
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
83
+ if (ar || !(i in from)) {
84
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
85
+ ar[i] = from[i];
86
+ }
87
+ }
88
+ return to.concat(ar || Array.prototype.slice.call(from));
89
+ }
90
+
91
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
92
+ var e = new Error(message);
93
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
94
+ };
95
+
96
+ var LogLevels = {
97
+ DEBUG: { name: "DEBUG", severity: 10 },
98
+ INFO: { name: "INFO", severity: 100 },
99
+ WARN: { name: "WARN", severity: 1000 },
100
+ ERROR: { name: "ERROR", severity: 10000 },
101
+ NONE: { name: "NONE", severity: 10000 }
102
+ };
103
+ var rootLogger = null;
104
+ /**
105
+ * Create logger or return cached instance
106
+ */
107
+ function getLogger() {
108
+ if (rootLogger) {
109
+ return rootLogger;
110
+ }
111
+ else {
112
+ return rootLogger = createLogger();
113
+ }
114
+ }
115
+ function setRootLogLevel(logLevelName) {
116
+ var logLevel = LogLevels[logLevelName.toLocaleUpperCase()];
117
+ if (!logLevel) {
118
+ console.warn("Can't find log level with name " + logLevelName.toLocaleUpperCase() + ", defaulting to INFO");
119
+ logLevel = LogLevels.INFO;
120
+ }
121
+ rootLogger = createLogger(logLevel);
122
+ return rootLogger;
123
+ }
124
+ function setDebugVar(name, val) {
125
+ if (!isWindowAvailable()) {
126
+ return;
127
+ }
128
+ var win = window;
129
+ if (!win.__usermavenDebug) {
130
+ win.__usermavenDebug = {};
131
+ }
132
+ win.__usermavenDebug[name] = val;
133
+ }
134
+ /**
135
+ * Creates a loggger with given log-level
136
+ * @param logLevel
137
+ */
138
+ function createLogger(logLevel) {
139
+ var globalLogLevel = isWindowAvailable() && window['__eventNLogLevel'];
140
+ var minLogLevel = LogLevels.WARN;
141
+ if (globalLogLevel) {
142
+ var level = LogLevels[globalLogLevel.toUpperCase()];
143
+ if (level && level > 0) {
144
+ minLogLevel = level;
145
+ }
146
+ }
147
+ else if (logLevel) {
148
+ minLogLevel = logLevel;
149
+ }
150
+ var logger = { minLogLevel: minLogLevel };
151
+ Object.values(LogLevels).forEach(function (_a) {
152
+ var name = _a.name, severity = _a.severity;
153
+ logger[name.toLowerCase()] = function () {
154
+ var args = [];
155
+ for (var _i = 0; _i < arguments.length; _i++) {
156
+ args[_i] = arguments[_i];
157
+ }
158
+ if (severity >= minLogLevel.severity && args.length > 0) {
159
+ var message = args[0];
160
+ var msgArgs = args.splice(1);
161
+ var msgFormatted = "[J-" + name + "] " + message;
162
+ if (name === 'DEBUG' || name === 'INFO') {
163
+ console.log.apply(console, __spreadArray([msgFormatted], msgArgs, false));
164
+ }
165
+ else if (name === 'WARN') {
166
+ console.warn.apply(console, __spreadArray([msgFormatted], msgArgs, false));
167
+ }
168
+ else {
169
+ console.error.apply(console, __spreadArray([msgFormatted], msgArgs, false));
170
+ }
171
+ }
172
+ };
173
+ });
174
+ setDebugVar("logger", logger);
175
+ return logger;
176
+ }
177
+
178
+ /**
179
+ * Checks if global variable 'window' is available. If it's available,
180
+ * code runs in browser environment
181
+ */
182
+
183
+ function isWindowAvailable(warnMsg = undefined) {
184
+ //here we check not only of window object is globally available, but also if it's not a fake one
185
+ //react-native do have a window object, but it's not a real one: https://stackoverflow.com/questions/49911424/what-does-the-variable-window-represent-in-react-native
186
+ const windowAvailable = !!globalThis.window && !!globalThis.window.document && !!globalThis.window.location;
187
+
188
+ if (!windowAvailable && warnMsg) {
189
+ getLogger().warn(warnMsg);
190
+ }
191
+ return windowAvailable;
192
+ }
193
+
194
+
195
+ /**
196
+ * @param msg
197
+ * @return {Window}
198
+ */
199
+ function requireWindow(msg = undefined) {
200
+ if (!isWindowAvailable()) {
201
+ throw new Error(msg || "window' is not available. Seems like this code runs outside browser environment. It shouldn't happen")
202
+ }
203
+ return window;
204
+ }
205
+
206
+ // Note: updated this method to test on staging (Ref:: https://github.com/PostHog/posthog-js/blob/master/src/storage.ts#L42)
207
+ // Commented out some jitsu cookies setters that are not bring used in posthog-js
208
+ function serializeCookie(name, val, opt) {
209
+ if (opt === void 0) { opt = {}; }
210
+ try {
211
+ var maxAge = opt.maxAge, domain = opt.domain, path = opt.path, expires = opt.expires, httpOnly = opt.httpOnly, secure = opt.secure, sameSite = opt.sameSite;
212
+ var new_cookie_val = name + "=" + encodeURIComponent(val);
213
+ if (domain) {
214
+ new_cookie_val += "; domain=" + domain;
215
+ }
216
+ if (path) {
217
+ new_cookie_val += "; path=" + path;
218
+ }
219
+ else {
220
+ new_cookie_val += "; path=/";
221
+ }
222
+ if (expires) {
223
+ new_cookie_val += "; expires=" + expires.toUTCString();
224
+ }
225
+ if (maxAge) {
226
+ new_cookie_val += "; max-age=" + maxAge;
227
+ }
228
+ if (httpOnly) {
229
+ new_cookie_val += "; httponly";
230
+ }
231
+ if (secure) {
232
+ new_cookie_val += "; secure";
233
+ }
234
+ if (sameSite) {
235
+ var sameSiteAttr = typeof sameSite === "string"
236
+ ? sameSite.toLowerCase()
237
+ : sameSite;
238
+ switch (sameSiteAttr) {
239
+ case true:
240
+ new_cookie_val += "; SameSite=Strict";
241
+ break;
242
+ case "lax":
243
+ new_cookie_val += "; SameSite=Lax";
244
+ break;
245
+ case "strict":
246
+ new_cookie_val += "; SameSite=Strict";
247
+ break;
248
+ case "none":
249
+ new_cookie_val += "; SameSite=None";
250
+ break;
251
+ }
252
+ }
253
+ else if (secure) {
254
+ /**
255
+ * SameSite=None - means that the browser sends the cookie with both cross-site and same-site requests.
256
+ * The Secure attribute must also be set when setting this value, like so SameSite=None; Secure.
257
+ * If Secure is missing an error will be logged.
258
+ *
259
+ * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
260
+ */
261
+ new_cookie_val += "; SameSite=None";
262
+ }
263
+ return new_cookie_val;
264
+ }
265
+ catch (e) {
266
+ getLogger().error("serializeCookie", e);
267
+ return '';
268
+ }
269
+ }
270
+
271
+ // Courtesy: https://stackoverflow.com/a/23945027
272
+ function extractHostname(url) {
273
+ var hostname;
274
+ //find & remove protocol (http, ftp, etc.) and get hostname
275
+ if (url.indexOf("//") > -1) {
276
+ hostname = url.split('/')[2];
277
+ }
278
+ else {
279
+ hostname = url.split('/')[0];
280
+ }
281
+ //find & remove port number
282
+ hostname = hostname.split(':')[0];
283
+ //find & remove "?"
284
+ hostname = hostname.split('?')[0];
285
+ return hostname;
286
+ }
287
+ // Warning: you can use this function to extract the "root" domain, but it will not be as accurate as using the psl package.
288
+ // https://www.npmjs.com/package/psl
289
+ var extractRootDomain = function (url) {
290
+ var domain = extractHostname(url), splitArr = domain.split('.'), arrLen = splitArr.length;
291
+ // extracting the root domain here
292
+ // if there is a subdomain
293
+ if (arrLen > 2) {
294
+ if (splitArr[arrLen - 1].length == 2) {
295
+ // likely a ccTLD
296
+ domain = splitArr[arrLen - 2] + '.' + splitArr[arrLen - 1];
297
+ // if the second level domain is also two letters (like co.uk), include the next part up
298
+ if (splitArr[arrLen - 2].length == 2) {
299
+ domain = splitArr[arrLen - 3] + '.' + domain;
300
+ }
301
+ }
302
+ else {
303
+ // likely a gTLD
304
+ domain = splitArr[arrLen - 2] + '.' + splitArr[arrLen - 1];
305
+ }
306
+ }
307
+ return domain;
308
+ };
309
+ var extractTopLevelDomain = function (url) {
310
+ var DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i;
311
+ var matches = url.match(DOMAIN_MATCH_REGEX), domain = matches ? matches[0] : '';
312
+ return domain;
313
+ };
314
+ var extractRoot = function (url) {
315
+ var domainParts = url.split(".");
316
+ var domainLength = domainParts.length;
317
+ // Check if it's an IP address
318
+ if (domainLength === 4 && domainParts.every(function (part) { return !isNaN(part); })) {
319
+ return url;
320
+ }
321
+ var rootDomain = extractTopLevelDomain(url);
322
+ if (!rootDomain) { // If it's not a top level domain, use a fallback method
323
+ rootDomain = extractRootDomain(url);
324
+ }
325
+ return rootDomain;
326
+ };
327
+ var getCookieDomain = function () {
328
+ if (isWindowAvailable()) {
329
+ // const domain = window.location.hostname.replace("www.", "")
330
+ //
331
+ // // Check if subdomain is set, if yes, we remove the subdomain from the cookie domain and return the root domain with a leading dot
332
+ // // This is to ensure that cookies are set correctly for cross domain tracking
333
+ // const subdomain = domain.split('.')[0]
334
+ // if (subdomain) {
335
+ // return '.' + extractRootDomain(domain)
336
+ // }
337
+ return extractRoot(window.location.hostname);
338
+ }
339
+ return undefined;
340
+ };
341
+ var cookieParsingCache;
342
+ function parseCookieString(cookieStr) {
343
+ if (!cookieStr) {
344
+ return {};
345
+ }
346
+ var res = {};
347
+ var cookies = cookieStr.split(";");
348
+ for (var i = 0; i < cookies.length; i++) {
349
+ var cookie = cookies[i];
350
+ var idx = cookie.indexOf("=");
351
+ if (idx > 0) {
352
+ res[cookie.substr(i > 0 ? 1 : 0, i > 0 ? idx - 1 : idx)] = cookie.substr(idx + 1);
353
+ }
354
+ }
355
+ return res;
356
+ }
357
+ function copyAttributes(source, target) {
358
+ return Array.from(source.attributes).forEach(function (attribute) {
359
+ target.setAttribute(attribute.nodeName, attribute.nodeValue);
360
+ });
361
+ }
362
+ function insertAndExecute(element, html) {
363
+ element.innerHTML = html;
364
+ var scripts = element.getElementsByTagName("script");
365
+ var index;
366
+ for (index = scripts.length - 1; index >= 0; index--) {
367
+ var script = scripts[index];
368
+ var tag = document.createElement("script");
369
+ copyAttributes(script, tag);
370
+ if (script.innerHTML) {
371
+ tag.innerHTML = script.innerHTML;
372
+ }
373
+ tag.setAttribute("data-usermaven-tag-id", element.id);
374
+ document.getElementsByTagName("head")[0].appendChild(tag);
375
+ scripts[index].parentNode.removeChild(scripts[index]);
376
+ }
377
+ }
378
+ var getCookies = function (useCache) {
379
+ if (useCache === void 0) { useCache = false; }
380
+ if (useCache && cookieParsingCache) {
381
+ return cookieParsingCache;
382
+ }
383
+ var res = parseCookieString(document.cookie);
384
+ cookieParsingCache = res;
385
+ return res;
386
+ };
387
+ // Methods partially borrowed from quirksmode.org/js/cookies.html
388
+ var getCookie = function (name) {
389
+ if (!name) {
390
+ return null;
391
+ }
392
+ try {
393
+ var nameEQ = name + '=';
394
+ var ca = requireWindow().document.cookie.split(';');
395
+ for (var i = 0; i < ca.length; i++) {
396
+ var c = ca[i];
397
+ while (c.charAt(0) == ' ') {
398
+ c = c.substring(1, c.length);
399
+ }
400
+ if (c.indexOf(nameEQ) === 0) {
401
+ return decodeURIComponent(c.substring(nameEQ.length, c.length));
402
+ }
403
+ }
404
+ }
405
+ catch (err) {
406
+ getLogger().error("getCookies", err);
407
+ }
408
+ return null;
409
+ };
410
+ var setCookie = function (name, value, opts) {
411
+ if (opts === void 0) { opts = {}; }
412
+ requireWindow().document.cookie = serializeCookie(name, value, opts);
413
+ };
414
+ var deleteCookie = function (name, path) {
415
+ if (path === void 0) { path = "/"; }
416
+ document.cookie = name + "= ; SameSite=Strict; expires = Thu, 01 Jan 1970 00:00:00 GMT" + (path ? ("; path = " + path) : "");
417
+ };
418
+ var generateId = function () { return Math.random().toString(36).substring(2, 12); };
419
+ var getUmExclusionState = function () {
420
+ var state = "false";
421
+ if (typeof window !== 'undefined' && window.localStorage) {
422
+ state = localStorage.getItem("um_exclusion");
423
+ }
424
+ return state === undefined || state === null || state === "false" ? false : true;
425
+ };
426
+ var generateRandom = function () { return Math.random().toString(36).substring(2, 7); };
427
+ var parseQuery = function (qs) {
428
+ if (!qs) {
429
+ return {};
430
+ }
431
+ var queryString = qs.length > 0 && qs.charAt(0) === "?" ? qs.substring(1) : qs;
432
+ var query = {};
433
+ var pairs = (queryString[0] === "?" ? queryString.substr(1) : queryString).split("&");
434
+ for (var i = 0; i < pairs.length; i++) {
435
+ var pair = pairs[i].split("=");
436
+ query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || "");
437
+ }
438
+ return query;
439
+ };
440
+ var UTM_TYPES = {
441
+ utm_source: "source",
442
+ utm_medium: "medium",
443
+ utm_campaign: "campaign",
444
+ utm_term: "term",
445
+ utm_content: "content"
446
+ };
447
+ var CLICK_IDS = {
448
+ gclid: true,
449
+ fbclid: true,
450
+ dclid: true
451
+ };
452
+ var getDataFromParams = function (params) {
453
+ var result = {
454
+ utm: {},
455
+ click_id: {},
456
+ };
457
+ for (var name in params) {
458
+ if (!params.hasOwnProperty(name)) {
459
+ continue;
460
+ }
461
+ var val = params[name];
462
+ var utm = UTM_TYPES[name];
463
+ if (utm) {
464
+ result.utm[utm] = val;
465
+ }
466
+ else if (CLICK_IDS[name]) {
467
+ result.click_id[name] = val;
468
+ }
469
+ }
470
+ return result;
471
+ };
472
+ //2020-08-24T13:42:16.439Z -> 2020-08-24T13:42:16.439123Z
473
+ var reformatDate = function (strDate) {
474
+ var end = strDate.split(".")[1];
475
+ if (!end) {
476
+ return strDate;
477
+ }
478
+ if (end.length >= 7) {
479
+ return strDate;
480
+ }
481
+ return strDate.slice(0, -1) + "0".repeat(7 - end.length) + "Z";
482
+ };
483
+ function endsWith(str, suffix) {
484
+ return str.indexOf(suffix, str.length - suffix.length) !== -1;
485
+ }
486
+ var getHostWithProtocol = function (host) {
487
+ while (endsWith(host, "/")) {
488
+ host = host.substr(0, host.length - 1);
489
+ }
490
+ if (host.indexOf("https://") === 0 || host.indexOf("http://") === 0) {
491
+ return host;
492
+ }
493
+ else {
494
+ return "https://" + host;
495
+ }
496
+ };
497
+
498
+ var MemoryQueue = /** @class */ (function () {
499
+ function MemoryQueue() {
500
+ this.queue = [];
501
+ }
502
+ MemoryQueue.prototype.flush = function () {
503
+ var queue = this.queue;
504
+ this.queue = [];
505
+ return queue;
506
+ };
507
+ MemoryQueue.prototype.push = function () {
508
+ var _a;
509
+ var values = [];
510
+ for (var _i = 0; _i < arguments.length; _i++) {
511
+ values[_i] = arguments[_i];
512
+ }
513
+ (_a = this.queue).push.apply(_a, values);
514
+ };
515
+ return MemoryQueue;
516
+ }());
517
+ var LocalStorageQueue = /** @class */ (function () {
518
+ function LocalStorageQueue(key) {
519
+ this.key = key;
520
+ }
521
+ LocalStorageQueue.prototype.flush = function () {
522
+ var queue = this.get();
523
+ if (queue.length) {
524
+ this.set([]);
525
+ }
526
+ return queue;
527
+ };
528
+ LocalStorageQueue.prototype.push = function () {
529
+ var values = [];
530
+ for (var _i = 0; _i < arguments.length; _i++) {
531
+ values[_i] = arguments[_i];
532
+ }
533
+ var queue = this.get();
534
+ queue.push.apply(queue, values);
535
+ this.set(queue);
536
+ };
537
+ LocalStorageQueue.prototype.set = function (queue) {
538
+ localStorage.setItem(this.key, JSON.stringify(queue));
539
+ };
540
+ LocalStorageQueue.prototype.get = function () {
541
+ var data = localStorage.getItem(this.key);
542
+ if (data !== null && data !== "") {
543
+ return JSON.parse(data);
544
+ }
545
+ return [];
546
+ };
547
+ return LocalStorageQueue;
548
+ }());
549
+
550
+ var ObjProto = Object.prototype;
551
+ var toString = ObjProto.toString;
552
+ var hasOwnProperty = ObjProto.hasOwnProperty;
553
+ var ArrayProto = Array.prototype;
554
+ var nativeForEach = ArrayProto.forEach, nativeIsArray = Array.isArray, breaker = {};
555
+ var _isArray = nativeIsArray ||
556
+ function (obj) {
557
+ return toString.call(obj) === '[object Array]';
558
+ };
559
+ function _eachArray(obj, iterator, thisArg) {
560
+ if (Array.isArray(obj)) {
561
+ if (nativeForEach && obj.forEach === nativeForEach) {
562
+ obj.forEach(iterator, thisArg);
563
+ }
564
+ else if ('length' in obj && obj.length === +obj.length) {
565
+ for (var i = 0, l = obj.length; i < l; i++) {
566
+ if (i in obj && iterator.call(thisArg, obj[i], i) === breaker) {
567
+ return;
568
+ }
569
+ }
570
+ }
571
+ }
572
+ }
573
+ // Embed part of the Underscore Library
574
+ var _trim = function (str) {
575
+ return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
576
+ };
577
+ var _bind_instance_methods = function (obj) {
578
+ for (var func in obj) {
579
+ if (typeof obj[func] === 'function') {
580
+ obj[func] = obj[func].bind(obj);
581
+ }
582
+ }
583
+ };
584
+ /**
585
+ * @param {*=} obj
586
+ * @param {function(...*)=} iterator
587
+ * @param {Object=} thisArg
588
+ */
589
+ function _each(obj, iterator, thisArg) {
590
+ if (obj === null || obj === undefined) {
591
+ return;
592
+ }
593
+ if (nativeForEach && Array.isArray(obj) && obj.forEach === nativeForEach) {
594
+ obj.forEach(iterator, thisArg);
595
+ }
596
+ else if ('length' in obj && obj.length === +obj.length) {
597
+ for (var i = 0, l = obj.length; i < l; i++) {
598
+ if (i in obj && iterator.call(thisArg, obj[i], i) === breaker) {
599
+ return;
600
+ }
601
+ }
602
+ }
603
+ else {
604
+ for (var key in obj) {
605
+ if (hasOwnProperty.call(obj, key)) {
606
+ if (iterator.call(thisArg, obj[key], key) === breaker) {
607
+ return;
608
+ }
609
+ }
610
+ }
611
+ }
612
+ }
613
+ var _extend = function (obj) {
614
+ var args = [];
615
+ for (var _i = 1; _i < arguments.length; _i++) {
616
+ args[_i - 1] = arguments[_i];
617
+ }
618
+ _eachArray(args, function (source) {
619
+ for (var prop in source) {
620
+ if (source[prop] !== void 0) {
621
+ obj[prop] = source[prop];
622
+ }
623
+ }
624
+ });
625
+ return obj;
626
+ };
627
+ function _includes(str, needle) {
628
+ return str.indexOf(needle) !== -1;
629
+ }
630
+ // from a comment on http://dbj.org/dbj/?p=286
631
+ // fails on only one very rare and deliberate custom object:
632
+ // let bomb = { toString : undefined, valueOf: function(o) { return "function BOMBA!"; }};
633
+ var _isFunction = function (f) {
634
+ try {
635
+ return /^\s*\bfunction\b/.test(f);
636
+ }
637
+ catch (x) {
638
+ return false;
639
+ }
640
+ };
641
+ var _isUndefined = function (obj) {
642
+ return obj === void 0;
643
+ };
644
+ var _register_event = (function () {
645
+ // written by Dean Edwards, 2005
646
+ // with input from Tino Zijdel - crisp@xs4all.nl
647
+ // with input from Carl Sverre - mail@carlsverre.com
648
+ // with input from PostHog
649
+ // http://dean.edwards.name/weblog/2005/10/add-event/
650
+ // https://gist.github.com/1930440
651
+ /**
652
+ * @param {Object} element
653
+ * @param {string} type
654
+ * @param {function(...*)} handler
655
+ * @param {boolean=} oldSchool
656
+ * @param {boolean=} useCapture
657
+ */
658
+ var register_event = function (element, type, handler, oldSchool, useCapture) {
659
+ if (!element) {
660
+ getLogger().error('No valid element provided to register_event');
661
+ return;
662
+ }
663
+ if (element.addEventListener && !oldSchool) {
664
+ element.addEventListener(type, handler, !!useCapture);
665
+ }
666
+ else {
667
+ var ontype = 'on' + type;
668
+ var old_handler = element[ontype] // can be undefined
669
+ ;
670
+ element[ontype] = makeHandler(element, handler, old_handler);
671
+ }
672
+ };
673
+ function makeHandler(element, new_handler, old_handlers) {
674
+ return function (event) {
675
+ event = event || fixEvent(window.event);
676
+ // this basically happens in firefox whenever another script
677
+ // overwrites the onload callback and doesn't pass the event
678
+ // object to previously defined callbacks. All the browsers
679
+ // that don't define window.event implement addEventListener
680
+ // so the dom_loaded handler will still be fired as usual.
681
+ if (!event) {
682
+ return undefined;
683
+ }
684
+ var ret = true;
685
+ var old_result;
686
+ if (_isFunction(old_handlers)) {
687
+ old_result = old_handlers(event);
688
+ }
689
+ var new_result = new_handler.call(element, event);
690
+ if (false === old_result || false === new_result) {
691
+ ret = false;
692
+ }
693
+ return ret;
694
+ };
695
+ }
696
+ function fixEvent(event) {
697
+ if (event) {
698
+ event.preventDefault = fixEvent.preventDefault;
699
+ event.stopPropagation = fixEvent.stopPropagation;
700
+ }
701
+ return event;
702
+ }
703
+ fixEvent.preventDefault = function () {
704
+ this.returnValue = false;
705
+ };
706
+ fixEvent.stopPropagation = function () {
707
+ this.cancelBubble = true;
708
+ };
709
+ return register_event;
710
+ })();
711
+ var _safewrap = function (f) {
712
+ return function () {
713
+ var args = [];
714
+ for (var _i = 0; _i < arguments.length; _i++) {
715
+ args[_i] = arguments[_i];
716
+ }
717
+ try {
718
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
719
+ // @ts-ignore
720
+ return f.apply(this, args);
721
+ }
722
+ catch (e) {
723
+ getLogger().error('Implementation error. Please turn on debug and contact support@usermaven.com.', e);
724
+ // if (Config.DEBUG) {
725
+ // getLogger.critical(e)
726
+ // }
727
+ }
728
+ };
729
+ };
730
+ var _safewrap_instance_methods = function (obj) {
731
+ for (var func in obj) {
732
+ if (typeof obj[func] === 'function') {
733
+ obj[func] = _safewrap(obj[func]);
734
+ }
735
+ }
736
+ };
737
+ var COPY_IN_PROGRESS_ATTRIBUTE = typeof Symbol !== 'undefined' ? Symbol('__deepCircularCopyInProgress__') : '__deepCircularCopyInProgress__';
738
+ /**
739
+ * Deep copies an object.
740
+ * It handles cycles by replacing all references to them with `undefined`
741
+ * Also supports customizing native values
742
+ *
743
+ * @param value
744
+ * @param customizer
745
+ * @param [key] if provided this is the object key associated with the value to be copied. It allows the customizer function to have context when it runs
746
+ * @returns {{}|undefined|*}
747
+ */
748
+ function deepCircularCopy(value, customizer, key) {
749
+ if (value !== Object(value))
750
+ return customizer ? customizer(value, key) : value; // primitive value
751
+ if (value[COPY_IN_PROGRESS_ATTRIBUTE])
752
+ return undefined;
753
+ value[COPY_IN_PROGRESS_ATTRIBUTE] = true;
754
+ var result;
755
+ if (_isArray(value)) {
756
+ result = [];
757
+ _eachArray(value, function (it) {
758
+ result.push(deepCircularCopy(it, customizer));
759
+ });
760
+ }
761
+ else {
762
+ result = {};
763
+ _each(value, function (val, key) {
764
+ if (key !== COPY_IN_PROGRESS_ATTRIBUTE) {
765
+ result[key] = deepCircularCopy(val, customizer, key);
766
+ }
767
+ });
768
+ }
769
+ delete value[COPY_IN_PROGRESS_ATTRIBUTE];
770
+ return result;
771
+ }
772
+ var LONG_STRINGS_ALLOW_LIST = ['$performance_raw'];
773
+ function _copyAndTruncateStrings(object, maxStringLength) {
774
+ return deepCircularCopy(object, function (value, key) {
775
+ if (key && LONG_STRINGS_ALLOW_LIST.indexOf(key) > -1) {
776
+ return value;
777
+ }
778
+ if (typeof value === 'string' && maxStringLength !== null) {
779
+ return value.slice(0, maxStringLength);
780
+ }
781
+ return value;
782
+ });
783
+ }
784
+ // Function to find the closest link element
785
+ function _findClosestLink(element) {
786
+ while (element && element.tagName) {
787
+ if (element.tagName.toLowerCase() == 'a') {
788
+ return element;
789
+ }
790
+ element = element.parentNode;
791
+ }
792
+ return null;
793
+ }
794
+ function _cleanObject(obj) {
795
+ for (var propName in obj) {
796
+ if (obj[propName] === '' || obj[propName] === null || obj[propName] === undefined || (typeof obj[propName] === 'object' && Object.keys(obj[propName]).length === 0)) {
797
+ delete obj[propName];
798
+ }
799
+ }
800
+ return obj;
801
+ }
802
+
803
+ /*
804
+ * Get the className of an element, accounting for edge cases where element.className is an object
805
+ * @param {Element} el - element to get the className of
806
+ * @returns {string} the element's class
807
+ */
808
+ function getClassName(el) {
809
+ switch (typeof el.className) {
810
+ case 'string':
811
+ return el.className;
812
+ // TODO: when is this ever used?
813
+ case 'object': // handle cases where className might be SVGAnimatedString or some other type
814
+ return ('baseVal' in el.className ? el.className.baseVal : null) || el.getAttribute('class') || '';
815
+ default:
816
+ // future proof
817
+ return '';
818
+ }
819
+ }
820
+ /*
821
+ * Get the direct text content of an element, protecting against sensitive data collection.
822
+ * Concats textContent of each of the element's text node children; this avoids potential
823
+ * collection of sensitive data that could happen if we used element.textContent and the
824
+ * element had sensitive child elements, since element.textContent includes child content.
825
+ * Scrubs values that look like they could be sensitive (i.e. cc or ssn number).
826
+ * @param {Element} el - element to get the text of
827
+ * @returns {string} the element's direct text content
828
+ */
829
+ function getSafeText(el) {
830
+ var elText = '';
831
+ if (shouldCaptureElement(el) && !isSensitiveElement(el) && el.childNodes && el.childNodes.length) {
832
+ _each(el.childNodes, function (child) {
833
+ if (isTextNode(child) && child.textContent) {
834
+ elText += _trim(child.textContent)
835
+ // scrub potentially sensitive values
836
+ .split(/(\s+)/)
837
+ .filter(shouldCaptureValue)
838
+ .join('')
839
+ // normalize whitespace
840
+ .replace(/[\r\n]/g, ' ')
841
+ .replace(/[ ]+/g, ' ')
842
+ // truncate
843
+ .substring(0, 255);
844
+ }
845
+ });
846
+ }
847
+ return _trim(elText);
848
+ }
849
+ /*
850
+ * Check whether an element has nodeType Node.ELEMENT_NODE
851
+ * @param {Element} el - element to check
852
+ * @returns {boolean} whether el is of the correct nodeType
853
+ */
854
+ function isElementNode(el) {
855
+ return !!el && el.nodeType === 1; // Node.ELEMENT_NODE - use integer constant for browser portability
856
+ }
857
+ /*
858
+ * Check whether an element is of a given tag type.
859
+ * Due to potential reference discrepancies (such as the webcomponents.js polyfill),
860
+ * we want to match tagNames instead of specific references because something like
861
+ * element === document.body won't always work because element might not be a native
862
+ * element.
863
+ * @param {Element} el - element to check
864
+ * @param {string} tag - tag name (e.g., "div")
865
+ * @returns {boolean} whether el is of the given tag type
866
+ */
867
+ function isTag(el, tag) {
868
+ return !!el && !!el.tagName && el.tagName.toLowerCase() === tag.toLowerCase();
869
+ }
870
+ /*
871
+ * Check whether an element has nodeType Node.TEXT_NODE
872
+ * @param {Element} el - element to check
873
+ * @returns {boolean} whether el is of the correct nodeType
874
+ */
875
+ function isTextNode(el) {
876
+ return !!el && el.nodeType === 3; // Node.TEXT_NODE - use integer constant for browser portability
877
+ }
878
+ /*
879
+ * Check whether an element has nodeType Node.DOCUMENT_FRAGMENT_NODE
880
+ * @param {Element} el - element to check
881
+ * @returns {boolean} whether el is of the correct nodeType
882
+ */
883
+ function isDocumentFragment(el) {
884
+ return !!el && el.nodeType === 11; // Node.DOCUMENT_FRAGMENT_NODE - use integer constant for browser portability
885
+ }
886
+ var usefulElements = ['a', 'button', 'form', 'input', 'select', 'textarea', 'label'];
887
+ /*
888
+ * Check whether a DOM event should be "captured" or if it may contain sentitive data
889
+ * using a variety of heuristics.
890
+ * @param {Element} el - element to check
891
+ * @param {Event} event - event to check
892
+ * @returns {boolean} whether the event should be captured
893
+ */
894
+ function shouldCaptureDomEvent(el, event) {
895
+ if (!el || isTag(el, 'html') || !isElementNode(el)) {
896
+ return false;
897
+ }
898
+ // Check if current element or any parent has um-no-capture class
899
+ var curEl = el;
900
+ while (curEl && !isTag(curEl, 'body')) {
901
+ if (curEl.classList && curEl.classList.contains('um-no-capture')) {
902
+ return false;
903
+ }
904
+ // Handle shadow DOM
905
+ if (curEl.parentNode && isDocumentFragment(curEl.parentNode)) {
906
+ curEl = curEl.parentNode.host;
907
+ }
908
+ else {
909
+ curEl = curEl.parentNode;
910
+ }
911
+ }
912
+ var parentIsUsefulElement = false;
913
+ curEl = el;
914
+ while (curEl && !isTag(curEl, 'body')) {
915
+ // Handle shadow DOM
916
+ if (curEl.parentNode && isDocumentFragment(curEl.parentNode)) {
917
+ curEl = curEl.parentNode.host;
918
+ if (curEl && usefulElements.indexOf(curEl.tagName.toLowerCase()) > -1) {
919
+ parentIsUsefulElement = true;
920
+ }
921
+ continue;
922
+ }
923
+ var parentNode = curEl.parentNode;
924
+ if (!parentNode)
925
+ break;
926
+ if (usefulElements.indexOf(parentNode.tagName.toLowerCase()) > -1) {
927
+ parentIsUsefulElement = true;
928
+ }
929
+ else {
930
+ var compStyles_1 = window.getComputedStyle(parentNode);
931
+ if (compStyles_1 && compStyles_1.getPropertyValue('cursor') === 'pointer') {
932
+ parentIsUsefulElement = true;
933
+ }
934
+ }
935
+ curEl = parentNode;
936
+ }
937
+ var compStyles = window.getComputedStyle(el);
938
+ if (compStyles && compStyles.getPropertyValue('cursor') === 'pointer' && event.type === 'click') {
939
+ return true;
940
+ }
941
+ var tag = el.tagName.toLowerCase();
942
+ switch (tag) {
943
+ case 'html':
944
+ return false;
945
+ case 'form':
946
+ return event.type === 'submit';
947
+ case 'input':
948
+ return event.type === 'change' || event.type === 'click';
949
+ case 'select':
950
+ case 'textarea':
951
+ return event.type === 'change' || event.type === 'click';
952
+ default:
953
+ if (parentIsUsefulElement)
954
+ return event.type === 'click';
955
+ return (event.type === 'click' &&
956
+ (usefulElements.indexOf(tag) > -1 || el.getAttribute('contenteditable') === 'true'));
957
+ }
958
+ }
959
+ /*
960
+ * Check whether a DOM element should be "captured" or if it may contain sentitive data
961
+ * using a variety of heuristics.
962
+ * @param {Element} el - element to check
963
+ * @returns {boolean} whether the element should be captured
964
+ */
965
+ function shouldCaptureElement(el) {
966
+ for (var curEl = el; curEl.parentNode && !isTag(curEl, 'body'); curEl = curEl.parentNode) {
967
+ var classes = getClassName(curEl).split(' ');
968
+ if (_includes(classes, 'ph-sensitive') || _includes(classes, 'ph-no-capture')) {
969
+ return false;
970
+ }
971
+ }
972
+ if (_includes(getClassName(el).split(' '), 'ph-include')) {
973
+ return true;
974
+ }
975
+ // don't include hidden or password fields
976
+ var type = el.type || '';
977
+ if (typeof type === 'string') {
978
+ // it's possible for el.type to be a DOM element if el is a form with a child input[name="type"]
979
+ switch (type.toLowerCase()) {
980
+ case 'hidden':
981
+ return false;
982
+ case 'password':
983
+ return false;
984
+ }
985
+ }
986
+ // filter out data from fields that look like sensitive fields
987
+ var name = el.name || el.id || '';
988
+ // See https://github.com/posthog/posthog-js/issues/165
989
+ // Under specific circumstances a bug caused .replace to be called on a DOM element
990
+ // instead of a string, removing the element from the page. Ensure this issue is mitigated.
991
+ if (typeof name === 'string') {
992
+ // it's possible for el.name or el.id to be a DOM element if el is a form with a child input[name="name"]
993
+ var sensitiveNameRegex = /^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i;
994
+ if (sensitiveNameRegex.test(name.replace(/[^a-zA-Z0-9]/g, ''))) {
995
+ return false;
996
+ }
997
+ }
998
+ return true;
999
+ }
1000
+ /*
1001
+ * Check whether a DOM element is 'sensitive' and we should only capture limited data
1002
+ * @param {Element} el - element to check
1003
+ * @returns {boolean} whether the element should be captured
1004
+ */
1005
+ function isSensitiveElement(el) {
1006
+ // don't send data from inputs or similar elements since there will always be
1007
+ // a risk of clientside javascript placing sensitive data in attributes
1008
+ var allowedInputTypes = ['button', 'checkbox', 'submit', 'reset'];
1009
+ if ((isTag(el, 'input') && !allowedInputTypes.includes(el.type)) ||
1010
+ isTag(el, 'select') ||
1011
+ isTag(el, 'textarea') ||
1012
+ el.getAttribute('contenteditable') === 'true') {
1013
+ return true;
1014
+ }
1015
+ return false;
1016
+ }
1017
+ /*
1018
+ * Check whether a string value should be "captured" or if it may contain sentitive data
1019
+ * using a variety of heuristics.
1020
+ * @param {string} value - string value to check
1021
+ * @returns {boolean} whether the element should be captured
1022
+ */
1023
+ function shouldCaptureValue(value) {
1024
+ if (value === null || _isUndefined(value)) {
1025
+ return false;
1026
+ }
1027
+ if (typeof value === 'string') {
1028
+ value = _trim(value);
1029
+ // check to see if input value looks like a credit card number
1030
+ // see: https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s20.html
1031
+ var ccRegex = /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/;
1032
+ if (ccRegex.test((value || '').replace(/[- ]/g, ''))) {
1033
+ return false;
1034
+ }
1035
+ // check to see if input value looks like a social security number
1036
+ var ssnRegex = /(^\d{3}-?\d{2}-?\d{4}$)/;
1037
+ if (ssnRegex.test(value)) {
1038
+ return false;
1039
+ }
1040
+ }
1041
+ return true;
1042
+ }
1043
+ /*
1044
+ * Check whether an attribute name is an Angular style attr (either _ngcontent or _nghost)
1045
+ * These update on each build and lead to noise in the element chain
1046
+ * More details on the attributes here: https://angular.io/guide/view-encapsulation
1047
+ * @param {string} attributeName - string value to check
1048
+ * @returns {boolean} whether the element is an angular tag
1049
+ */
1050
+ function isAngularStyleAttr(attributeName) {
1051
+ if (typeof attributeName === 'string') {
1052
+ return attributeName.substring(0, 10) === '_ngcontent' || attributeName.substring(0, 7) === '_nghost';
1053
+ }
1054
+ return false;
1055
+ }
1056
+
1057
+ // Naive rage click implementation: If mouse has not moved than RAGE_CLICK_THRESHOLD_PX
1058
+ // over RAGE_CLICK_CLICK_COUNT clicks with max RAGE_CLICK_TIMEOUT_MS between clicks, it's
1059
+ // counted as a rage click
1060
+ var RAGE_CLICK_THRESHOLD_PX = 30;
1061
+ var RAGE_CLICK_TIMEOUT_MS = 1000;
1062
+ var RAGE_CLICK_CLICK_COUNT = 3;
1063
+ var RageClick = /** @class */ (function () {
1064
+ function RageClick(instance, enabled) {
1065
+ if (enabled === void 0) { enabled = false; }
1066
+ this.clicks = [];
1067
+ this.instance = instance;
1068
+ this.enabled = enabled;
1069
+ }
1070
+ RageClick.prototype.click = function (x, y, timestamp) {
1071
+ if (!this.enabled) {
1072
+ return;
1073
+ }
1074
+ var lastClick = this.clicks[this.clicks.length - 1];
1075
+ if (lastClick &&
1076
+ Math.abs(x - lastClick.x) + Math.abs(y - lastClick.y) < RAGE_CLICK_THRESHOLD_PX &&
1077
+ timestamp - lastClick.timestamp < RAGE_CLICK_TIMEOUT_MS) {
1078
+ this.clicks.push({ x: x, y: y, timestamp: timestamp });
1079
+ if (this.clicks.length === RAGE_CLICK_CLICK_COUNT) {
1080
+ this.instance.capture('$rageclick');
1081
+ }
1082
+ }
1083
+ else {
1084
+ this.clicks = [{ x: x, y: y, timestamp: timestamp }];
1085
+ }
1086
+ };
1087
+ return RageClick;
1088
+ }());
1089
+
1090
+ /**
1091
+ * Scroll extension to add scroll get scroll depth in percentage
1092
+ */
1093
+ var ScrollDepth = /** @class */ (function () {
1094
+ function ScrollDepth(instance) {
1095
+ this.instance = instance;
1096
+ this.lastScrollDepth = 0;
1097
+ this.canSend = true;
1098
+ this.documentElement = document.documentElement;
1099
+ }
1100
+ /**
1101
+ * Track scroll depth
1102
+ * @description this function will be called on every scroll event to track scroll depth
1103
+ */
1104
+ ScrollDepth.prototype.track = function () {
1105
+ var scrollDepth = this.getScrollDepth();
1106
+ // If scroll depth is greater than last scroll depth, then update last scroll depth
1107
+ // We are doing this to only get the maximum scroll depth
1108
+ if (scrollDepth > this.lastScrollDepth) {
1109
+ this.lastScrollDepth = scrollDepth;
1110
+ this.canSend = true;
1111
+ }
1112
+ };
1113
+ /**
1114
+ * Send scroll depth event
1115
+ * @description this function will be when we want to send scroll depth event e.g. on page visibility change
1116
+ */
1117
+ ScrollDepth.prototype.send = function (eventType) {
1118
+ if (eventType === void 0) { eventType = "$scroll"; }
1119
+ if (!this.canSend) {
1120
+ return;
1121
+ }
1122
+ // Creating payload
1123
+ var props = {
1124
+ percent: this.lastScrollDepth,
1125
+ window_height: this.getWindowHeight(),
1126
+ document_height: this.getDocumentHeight(),
1127
+ scroll_distance: this.getScrollDistance()
1128
+ };
1129
+ // Sending event
1130
+ this.instance.capture(eventType, props);
1131
+ // Setting canSend to false, for avoiding sending multiple events
1132
+ this.canSend = false;
1133
+ };
1134
+ /**
1135
+ * Core method to get scroll depth
1136
+ */
1137
+ ScrollDepth.prototype.getScrollDepth = function () {
1138
+ try {
1139
+ // Get the height of the window and the document body
1140
+ var winHeight = this.getWindowHeight();
1141
+ var docHeight = this.getDocumentHeight();
1142
+ // Get the current scroll position and the length of the track
1143
+ var scrollTop = this.getScrollDistance();
1144
+ var trackLength = docHeight - winHeight;
1145
+ // Calculate the scroll depth as a percentage
1146
+ return Math.min(100, Math.floor(scrollTop / trackLength * 100));
1147
+ }
1148
+ catch (e) {
1149
+ return 0;
1150
+ }
1151
+ };
1152
+ /**
1153
+ * Core method to get window height
1154
+ */
1155
+ ScrollDepth.prototype.getWindowHeight = function () {
1156
+ try {
1157
+ return window.innerHeight || this.documentElement.clientHeight ||
1158
+ document.body.clientHeight || 0;
1159
+ }
1160
+ catch (e) {
1161
+ return 0;
1162
+ }
1163
+ };
1164
+ /**
1165
+ * Core method to get document height
1166
+ */
1167
+ ScrollDepth.prototype.getDocumentHeight = function () {
1168
+ try {
1169
+ return Math.max(document.body.scrollHeight || 0, this.documentElement.scrollHeight || 0, document.body.offsetHeight || 0, this.documentElement.offsetHeight || 0, document.body.clientHeight || 0, this.documentElement.clientHeight || 0);
1170
+ }
1171
+ catch (e) {
1172
+ return 0;
1173
+ }
1174
+ };
1175
+ /**
1176
+ * Core method to get scroll distance
1177
+ */
1178
+ ScrollDepth.prototype.getScrollDistance = function () {
1179
+ try {
1180
+ return window.scrollY || window.pageYOffset || document.body.scrollTop ||
1181
+ this.documentElement.scrollTop || 0;
1182
+ }
1183
+ catch (e) {
1184
+ return 0;
1185
+ }
1186
+ };
1187
+ return ScrollDepth;
1188
+ }());
1189
+
1190
+ var autocapture = {
1191
+ _initializedTokens: [],
1192
+ _previousElementSibling: function (el) {
1193
+ if (el.previousElementSibling) {
1194
+ return el.previousElementSibling;
1195
+ }
1196
+ else {
1197
+ var _el = el;
1198
+ do {
1199
+ _el = _el.previousSibling; // resolves to ChildNode->Node, which is Element's parent class
1200
+ } while (_el && !isElementNode(_el));
1201
+ return _el;
1202
+ }
1203
+ },
1204
+ _getPropertiesFromElement: function (elem, maskInputs, maskText) {
1205
+ var tag_name = elem.tagName.toLowerCase();
1206
+ var props = {
1207
+ tag_name: tag_name,
1208
+ };
1209
+ if (usefulElements.indexOf(tag_name) > -1 && !maskText) {
1210
+ props['$el_text'] = getSafeText(elem);
1211
+ }
1212
+ var classes = getClassName(elem);
1213
+ if (classes.length > 0)
1214
+ props['classes'] = classes.split(' ').filter(function (c) {
1215
+ return c !== '';
1216
+ });
1217
+ _each(elem.attributes, function (attr) {
1218
+ // Only capture attributes we know are safe
1219
+ if (isSensitiveElement(elem) && ['name', 'id', 'class'].indexOf(attr.name) === -1)
1220
+ return;
1221
+ if (!maskInputs && shouldCaptureValue(attr.value) && !isAngularStyleAttr(attr.name)) {
1222
+ props['attr__' + attr.name] = attr.value;
1223
+ }
1224
+ });
1225
+ var nthChild = 1;
1226
+ var nthOfType = 1;
1227
+ var currentElem = elem;
1228
+ while ((currentElem = this._previousElementSibling(currentElem))) {
1229
+ // eslint-disable-line no-cond-assign
1230
+ nthChild++;
1231
+ if (currentElem.tagName === elem.tagName) {
1232
+ nthOfType++;
1233
+ }
1234
+ }
1235
+ props['nth_child'] = nthChild;
1236
+ props['nth_of_type'] = nthOfType;
1237
+ return props;
1238
+ },
1239
+ _getDefaultProperties: function (eventType) {
1240
+ return {
1241
+ $event_type: eventType,
1242
+ $ce_version: 1,
1243
+ };
1244
+ },
1245
+ _extractCustomPropertyValue: function (customProperty) {
1246
+ var propValues = [];
1247
+ _each(document.querySelectorAll(customProperty['css_selector']), function (matchedElem) {
1248
+ var value;
1249
+ if (['input', 'select'].indexOf(matchedElem.tagName.toLowerCase()) > -1) {
1250
+ value = matchedElem['value'];
1251
+ }
1252
+ else if (matchedElem['textContent']) {
1253
+ value = matchedElem['textContent'];
1254
+ }
1255
+ if (shouldCaptureValue(value)) {
1256
+ propValues.push(value);
1257
+ }
1258
+ });
1259
+ return propValues.join(', ');
1260
+ },
1261
+ // TODO: delete custom_properties after changeless typescript refactor
1262
+ _getCustomProperties: function (targetElementList) {
1263
+ var _this = this;
1264
+ var props = {}; // will be deleted
1265
+ _each(this._customProperties, function (customProperty) {
1266
+ _each(customProperty['event_selectors'], function (eventSelector) {
1267
+ var eventElements = document.querySelectorAll(eventSelector);
1268
+ _each(eventElements, function (eventElement) {
1269
+ if (_includes(targetElementList, eventElement) && shouldCaptureElement(eventElement)) {
1270
+ props[customProperty['name']] = _this._extractCustomPropertyValue(customProperty);
1271
+ }
1272
+ });
1273
+ });
1274
+ });
1275
+ return props;
1276
+ },
1277
+ _getEventTarget: function (e) {
1278
+ var _a;
1279
+ // https://developer.mozilla.org/en-US/docs/Web/API/Event/target#Compatibility_notes
1280
+ if (typeof e.target === 'undefined') {
1281
+ return e.srcElement || null;
1282
+ }
1283
+ else {
1284
+ if ((_a = e.target) === null || _a === void 0 ? void 0 : _a.shadowRoot) {
1285
+ return e.composedPath()[0] || null;
1286
+ }
1287
+ return e.target || null;
1288
+ }
1289
+ },
1290
+ _captureEvent: function (e, instance, opts) {
1291
+ var _this = this;
1292
+ var _a;
1293
+ /*** Don't mess with this code without running IE8 tests on it ***/
1294
+ var target = this._getEventTarget(e);
1295
+ if (isTextNode(target)) {
1296
+ // defeat Safari bug (see: http://www.quirksmode.org/js/events_properties.html)
1297
+ target = (target.parentNode || null);
1298
+ }
1299
+ // If type is 'scroll', track the scroll depth
1300
+ if (e.type === 'scroll') {
1301
+ this.scrollDepth.track();
1302
+ return true;
1303
+ }
1304
+ // If type is visibilitychange and the page is about to be hidden, send a scroll depth event
1305
+ if ((e.type === 'visibilitychange' && document.visibilityState === 'hidden') || e.type === 'popstate') {
1306
+ this.scrollDepth.send();
1307
+ return true;
1308
+ }
1309
+ if (e.type === 'click' && e instanceof MouseEvent) {
1310
+ (_a = this.rageclicks) === null || _a === void 0 ? void 0 : _a.click(e.clientX, e.clientY, new Date().getTime());
1311
+ }
1312
+ if (target && shouldCaptureDomEvent(target, e)) {
1313
+ var targetElementList = [target];
1314
+ var curEl = target;
1315
+ while (curEl.parentNode && !isTag(curEl, 'body')) {
1316
+ if (isDocumentFragment(curEl.parentNode)) {
1317
+ targetElementList.push(curEl.parentNode.host);
1318
+ curEl = curEl.parentNode.host;
1319
+ continue;
1320
+ }
1321
+ targetElementList.push(curEl.parentNode);
1322
+ curEl = curEl.parentNode;
1323
+ }
1324
+ var elementsJson_1 = [];
1325
+ var href_1, explicitNoCapture_1 = false;
1326
+ _each(targetElementList, function (el) {
1327
+ var shouldCaptureEl = shouldCaptureElement(el);
1328
+ // if the element or a parent element is an anchor tag
1329
+ // include the href as a property
1330
+ if (el.tagName.toLowerCase() === 'a') {
1331
+ href_1 = el.getAttribute('href');
1332
+ href_1 = shouldCaptureEl && shouldCaptureValue(href_1) && href_1;
1333
+ }
1334
+ // allow users to programmatically prevent capturing of elements by adding class 'ph-no-capture'
1335
+ var classes = getClassName(el).split(' ');
1336
+ if (_includes(classes, 'ph-no-capture')) {
1337
+ explicitNoCapture_1 = true;
1338
+ }
1339
+ elementsJson_1.push(_this._getPropertiesFromElement(el, opts === null || opts === void 0 ? void 0 : opts.mask_all_element_attributes, opts === null || opts === void 0 ? void 0 : opts.mask_all_text));
1340
+ });
1341
+ if (!(opts === null || opts === void 0 ? void 0 : opts.mask_all_text)) {
1342
+ elementsJson_1[0]['$el_text'] = getSafeText(target);
1343
+ }
1344
+ if (href_1) {
1345
+ elementsJson_1[0]['attr__href'] = href_1;
1346
+ }
1347
+ if (explicitNoCapture_1) {
1348
+ return false;
1349
+ }
1350
+ var props = _extend(this._getDefaultProperties(e.type), {
1351
+ $elements: elementsJson_1,
1352
+ }, this._getCustomProperties(targetElementList));
1353
+ instance.capture('$autocapture', props);
1354
+ return true;
1355
+ }
1356
+ },
1357
+ // only reason is to stub for unit tests
1358
+ // since you can't override window.location props
1359
+ _navigate: function (href) {
1360
+ window.location.href = href;
1361
+ },
1362
+ _addDomEventHandlers: function (instance, opts) {
1363
+ var _this = this;
1364
+ var handler = function (e) {
1365
+ e = e || window.event;
1366
+ _this._captureEvent(e, instance, opts);
1367
+ };
1368
+ _register_event(document, 'submit', handler, false, true);
1369
+ _register_event(document, 'change', handler, false, true);
1370
+ _register_event(document, 'click', handler, false, true);
1371
+ _register_event(document, 'visibilitychange', handler, false, true);
1372
+ _register_event(document, 'scroll', handler, false, true);
1373
+ _register_event(window, 'popstate', handler, false, true);
1374
+ },
1375
+ _customProperties: [],
1376
+ rageclicks: null,
1377
+ scrollDepth: null,
1378
+ opts: {},
1379
+ init: function (instance, opts) {
1380
+ var _this = this;
1381
+ this.rageclicks = new RageClick(instance);
1382
+ this.scrollDepth = new ScrollDepth(instance);
1383
+ this.opts = opts;
1384
+ if (!(document && document.body)) {
1385
+ console.debug('document not ready yet, trying again in 500 milliseconds...');
1386
+ setTimeout(function () {
1387
+ _this.readyAutocapture(instance, opts);
1388
+ }, 500);
1389
+ return;
1390
+ }
1391
+ this.readyAutocapture(instance, opts);
1392
+ },
1393
+ readyAutocapture: function (instance, opts) {
1394
+ this._addDomEventHandlers(instance, opts);
1395
+ },
1396
+ // this is a mechanism to ramp up CE with no server-side interaction.
1397
+ // when CE is active, every page load results in a decide request. we
1398
+ // need to gently ramp this up so we don't overload decide. this decides
1399
+ // deterministically if CE is enabled for this project by modding the char
1400
+ // value of the project token.
1401
+ enabledForProject: function (token, numBuckets, numEnabledBuckets) {
1402
+ if (!token) {
1403
+ return true;
1404
+ }
1405
+ numBuckets = !_isUndefined(numBuckets) ? numBuckets : 10;
1406
+ numEnabledBuckets = !_isUndefined(numEnabledBuckets) ? numEnabledBuckets : 10;
1407
+ var charCodeSum = 0;
1408
+ for (var i = 0; i < token.length; i++) {
1409
+ charCodeSum += token.charCodeAt(i);
1410
+ }
1411
+ return charCodeSum % numBuckets < numEnabledBuckets;
1412
+ },
1413
+ isBrowserSupported: function () {
1414
+ return _isFunction(document.querySelectorAll);
1415
+ },
1416
+ };
1417
+ _bind_instance_methods(autocapture);
1418
+ _safewrap_instance_methods(autocapture);
1419
+
1420
+ var FormTracking = /** @class */ (function () {
1421
+ function FormTracking(instance, trackingType) {
1422
+ if (trackingType === void 0) { trackingType = 'all'; }
1423
+ this.instance = instance;
1424
+ this.trackingType = trackingType;
1425
+ // Wait for the DOM to be ready
1426
+ if (document.readyState === 'loading') {
1427
+ document.addEventListener('DOMContentLoaded', this.track.bind(this));
1428
+ }
1429
+ else {
1430
+ this.track();
1431
+ }
1432
+ }
1433
+ /**
1434
+ * Track form submit
1435
+ * @description this function will be called on every form submit event to track form submit
1436
+ */
1437
+ FormTracking.prototype.track = function () {
1438
+ var _this = this;
1439
+ this.formElements = document.querySelectorAll('form');
1440
+ if (this.trackingType === 'tagged') {
1441
+ this.formElements = document.querySelectorAll('form[data-um-form]');
1442
+ }
1443
+ this.formElements.forEach(function (form) {
1444
+ form.addEventListener('submit', function (event) {
1445
+ var form = event.target;
1446
+ var props = _this._getFormDetails(form);
1447
+ _this.instance.capture('$form', _cleanObject(props));
1448
+ });
1449
+ });
1450
+ };
1451
+ FormTracking.getInstance = function (instance, trackingType) {
1452
+ if (trackingType === void 0) { trackingType = 'all'; }
1453
+ if (!FormTracking.instance) {
1454
+ FormTracking.instance = new FormTracking(instance, trackingType);
1455
+ }
1456
+ return FormTracking.instance;
1457
+ };
1458
+ FormTracking.prototype._getFormDetails = function (form) {
1459
+ var _this = this;
1460
+ var formDetails = {
1461
+ form_id: form.id,
1462
+ form_name: form.name || '',
1463
+ form_action: form.action,
1464
+ form_method: form.method,
1465
+ };
1466
+ var formFields = form.querySelectorAll('input, select, textarea');
1467
+ // ignore form fields with class um-no-capture
1468
+ var filteredFormFields = Array.from(formFields).filter(function (field) { return !field.classList.contains('um-no-capture'); });
1469
+ filteredFormFields.forEach(function (field, index) {
1470
+ var fieldProps = _this._getFieldProps(field, index);
1471
+ Object.assign(formDetails, fieldProps);
1472
+ });
1473
+ return formDetails;
1474
+ };
1475
+ FormTracking.prototype._getFieldProps = function (field, index) {
1476
+ var _a;
1477
+ var fieldDataAttributes = Object.keys(field.dataset).length ? JSON.stringify(field.dataset) : undefined;
1478
+ var safeValue = this.getSafeText(field);
1479
+ return _a = {},
1480
+ _a["field_" + (index + 1) + "_tag"] = field.tagName.toLowerCase(),
1481
+ _a["field_" + (index + 1) + "_type"] = field instanceof HTMLInputElement ? field.type : undefined,
1482
+ _a["field_" + (index + 1) + "_data_attributes"] = fieldDataAttributes,
1483
+ _a["field_" + (index + 1) + "_id"] = field.id,
1484
+ _a["field_" + (index + 1) + "_value"] = safeValue,
1485
+ _a["field_" + (index + 1) + "_class"] = field.className,
1486
+ _a["field_" + (index + 1) + "_name"] = field.name,
1487
+ _a;
1488
+ };
1489
+ FormTracking.prototype.getSafeText = function (element) {
1490
+ var safeText = '';
1491
+ if ('value' in element && element.type !== "password") {
1492
+ safeText = element.value;
1493
+ }
1494
+ else if (element.hasChildNodes()) {
1495
+ var textNodes = Array.from(element.childNodes).filter(function (node) { return node.nodeType === Node.TEXT_NODE; });
1496
+ safeText = textNodes.map(function (node) { return node.textContent; }).join('');
1497
+ }
1498
+ else {
1499
+ safeText = element.textContent || '';
1500
+ }
1501
+ return this._scrubPotentiallySensitiveValues(safeText);
1502
+ };
1503
+ FormTracking.prototype._scrubPotentiallySensitiveValues = function (text) {
1504
+ if (!this._shouldCaptureValue(text)) {
1505
+ return '<redacted>';
1506
+ }
1507
+ return text;
1508
+ };
1509
+ FormTracking.prototype._shouldCaptureValue = function (value) {
1510
+ if (this._isNullish(value)) {
1511
+ return false;
1512
+ }
1513
+ if (this._isString(value)) {
1514
+ value = this._trim(value);
1515
+ // check to see if input value looks like a credit card number
1516
+ // see: https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s20.html
1517
+ var ccRegex = /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/;
1518
+ if (ccRegex.test((value || '').replace(/[- ]/g, ''))) {
1519
+ return false;
1520
+ }
1521
+ // check to see if input value looks like a social security number
1522
+ var ssnRegex = /(^\d{3}-?\d{2}-?\d{4}$)/;
1523
+ if (ssnRegex.test(value)) {
1524
+ return false;
1525
+ }
1526
+ }
1527
+ return true;
1528
+ };
1529
+ FormTracking.prototype._isNullish = function (value) {
1530
+ return value === null || value === undefined;
1531
+ };
1532
+ FormTracking.prototype._isString = function (value) {
1533
+ return typeof value === 'string' || value instanceof String;
1534
+ };
1535
+ FormTracking.prototype._trim = function (value) {
1536
+ return value.trim().replace(/^\s+|\s+$/g, '');
1537
+ };
1538
+ return FormTracking;
1539
+ }());
1540
+
1541
+ var VERSION_INFO = {
1542
+ env: 'production',
1543
+ date: '2024-11-15T06:39:44.205Z',
1544
+ version: '1.4.2'
1545
+ };
1546
+ var USERMAVEN_VERSION = VERSION_INFO.version + "/" + VERSION_INFO.env + "@" + VERSION_INFO.date;
1547
+ var MAX_AGE_TEN_YEARS = 31622400 * 10;
1548
+ var beaconTransport = function (url, json) {
1549
+ getLogger().debug("Sending beacon", json);
1550
+ var blob = new Blob([json], { type: "text/plain" });
1551
+ navigator.sendBeacon(url, blob);
1552
+ return Promise.resolve();
1553
+ };
1554
+ function tryFormat(string) {
1555
+ if (typeof string === "string") {
1556
+ try {
1557
+ return JSON.stringify(JSON.parse(string), null, 2);
1558
+ }
1559
+ catch (e) {
1560
+ return string;
1561
+ }
1562
+ }
1563
+ }
1564
+ var echoTransport = function (url, json) {
1565
+ console.debug("Jitsu client tried to send payload to " + url, tryFormat(json));
1566
+ return Promise.resolve();
1567
+ };
1568
+ // This is a hack to expire all cookies with non-root path left behind by invalid tracking.
1569
+ // TODO remove soon
1570
+ function expireNonRootCookies(name, path) {
1571
+ if (path === void 0) { path = undefined; }
1572
+ path = path !== null && path !== void 0 ? path : window.location.pathname;
1573
+ if (path == "" || path == "/") {
1574
+ return;
1575
+ }
1576
+ deleteCookie(name, path);
1577
+ expireNonRootCookies(name, path.slice(0, path.lastIndexOf("/")));
1578
+ }
1579
+ var CookiePersistence = /** @class */ (function () {
1580
+ function CookiePersistence(cookieDomain, cookieName) {
1581
+ this.cookieDomain = cookieDomain;
1582
+ this.cookieName = cookieName;
1583
+ }
1584
+ CookiePersistence.prototype.save = function (props) {
1585
+ setCookie(this.cookieName, JSON.stringify(props), {
1586
+ domain: this.cookieDomain,
1587
+ secure: document.location.protocol !== "http:",
1588
+ maxAge: MAX_AGE_TEN_YEARS,
1589
+ });
1590
+ };
1591
+ CookiePersistence.prototype.restore = function () {
1592
+ expireNonRootCookies(this.cookieName);
1593
+ var str = getCookie(this.cookieName);
1594
+ if (str) {
1595
+ try {
1596
+ var parsed = JSON.parse(decodeURIComponent(str));
1597
+ if (typeof parsed !== "object") {
1598
+ getLogger().warn("Can't restore value of " + this.cookieName + "@" + this.cookieDomain + ", expected to be object, but found " + (typeof parsed !== "object") + ": " + parsed + ". Ignoring");
1599
+ return undefined;
1600
+ }
1601
+ return parsed;
1602
+ }
1603
+ catch (e) {
1604
+ getLogger().error("Failed to decode JSON from " + str, e);
1605
+ return undefined;
1606
+ }
1607
+ }
1608
+ return undefined;
1609
+ };
1610
+ CookiePersistence.prototype.delete = function () {
1611
+ deleteCookie(this.cookieName);
1612
+ };
1613
+ return CookiePersistence;
1614
+ }());
1615
+ var NoPersistence = /** @class */ (function () {
1616
+ function NoPersistence() {
1617
+ }
1618
+ NoPersistence.prototype.save = function (props) {
1619
+ };
1620
+ NoPersistence.prototype.restore = function () {
1621
+ return undefined;
1622
+ };
1623
+ NoPersistence.prototype.delete = function () {
1624
+ };
1625
+ return NoPersistence;
1626
+ }());
1627
+ var defaultCompatMode = false;
1628
+ function usermavenClient(opts) {
1629
+ var client = new UsermavenClientImpl();
1630
+ client.init(opts);
1631
+ return client;
1632
+ }
1633
+ var browserEnv = {
1634
+ getSourceIp: function () { return undefined; },
1635
+ describeClient: function () { return ({
1636
+ referer: document.referrer,
1637
+ url: window.location.href,
1638
+ page_title: document.title,
1639
+ doc_path: document.location.pathname,
1640
+ doc_host: document.location.hostname,
1641
+ doc_search: window.location.search,
1642
+ screen_resolution: screen.width + "x" + screen.height,
1643
+ vp_size: Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0) +
1644
+ "x" +
1645
+ Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0),
1646
+ user_agent: navigator.userAgent,
1647
+ user_language: navigator.language,
1648
+ doc_encoding: document.characterSet,
1649
+ }); },
1650
+ getAnonymousId: function (_a) {
1651
+ var name = _a.name, domain = _a.domain, _b = _a.crossDomainLinking, crossDomainLinking = _b === void 0 ? true : _b;
1652
+ expireNonRootCookies(name);
1653
+ // Check if cross domain linking is enabled
1654
+ if (crossDomainLinking) {
1655
+ // Try to extract the '_um' parameter from query string and hash fragment (https://example.com#_um=1~abcde5~)
1656
+ var urlParams = new URLSearchParams(window.location.search);
1657
+ var queryId = urlParams.get('_um');
1658
+ var urlHash = window.location.hash.substring(1);
1659
+ var hashedValues = urlHash.split("~");
1660
+ var fragmentId = hashedValues.length > 1 ? hashedValues[1] : undefined;
1661
+ // If the '_um' parameter is set in both the query string and hash fragment,
1662
+ // prioritize the one in query string
1663
+ var crossDomainAnonymousId = queryId || fragmentId;
1664
+ // If coming from another domain, use the ID from URL parameter
1665
+ if (crossDomainAnonymousId) {
1666
+ getLogger().debug("Existing user id from other domain", crossDomainAnonymousId);
1667
+ // Check if the ID needs to be set as cookie
1668
+ var currentCookie = getCookie(name);
1669
+ if (!currentCookie || currentCookie !== crossDomainAnonymousId) {
1670
+ setCookie(name, crossDomainAnonymousId, {
1671
+ domain: domain,
1672
+ secure: document.location.protocol !== "http:",
1673
+ maxAge: MAX_AGE_TEN_YEARS,
1674
+ });
1675
+ }
1676
+ return crossDomainAnonymousId;
1677
+ }
1678
+ }
1679
+ var idCookie = getCookie(name);
1680
+ if (idCookie) {
1681
+ getLogger().debug("Existing user id", idCookie);
1682
+ return idCookie;
1683
+ }
1684
+ var newId = generateId();
1685
+ getLogger().debug("New user id", newId);
1686
+ setCookie(name, newId, {
1687
+ domain: domain,
1688
+ secure: document.location.protocol !== "http:",
1689
+ maxAge: MAX_AGE_TEN_YEARS,
1690
+ });
1691
+ return newId;
1692
+ },
1693
+ };
1694
+ function ensurePrefix(prefix, str) {
1695
+ if (!str) {
1696
+ return str;
1697
+ }
1698
+ return (str === null || str === void 0 ? void 0 : str.length) > 0 && str.indexOf(prefix) !== 0 ? prefix + str : str;
1699
+ }
1700
+ function cutPostfix(postfixes, str) {
1701
+ for (var _i = 0, _a = typeof postfixes === "string"
1702
+ ? [postfixes]
1703
+ : postfixes; _i < _a.length; _i++) {
1704
+ var postfix = _a[_i];
1705
+ while (str && str.length > 0 && str.charAt(str.length - 1) === postfix) {
1706
+ str = str.substring(0, str.length - 1);
1707
+ }
1708
+ }
1709
+ return str;
1710
+ }
1711
+ function fetchApi(req, res, opts) {
1712
+ if (opts === void 0) { opts = {}; }
1713
+ return {
1714
+ getAnonymousId: function (_a) {
1715
+ var name = _a.name, domain = _a.domain;
1716
+ if (opts === null || opts === void 0 ? void 0 : opts.disableCookies) {
1717
+ return "";
1718
+ }
1719
+ var cookie = parseCookieString(req.headers["cookie"])[name];
1720
+ if (!cookie) {
1721
+ var cookieOpts = {
1722
+ maxAge: 31622400 * 10,
1723
+ httpOnly: false,
1724
+ };
1725
+ if (domain) {
1726
+ cookieOpts.domain = domain;
1727
+ }
1728
+ var newId = generateId();
1729
+ res.headers.set("Set-Cookie", serializeCookie(name, newId, cookieOpts));
1730
+ return newId;
1731
+ }
1732
+ else {
1733
+ return cookie;
1734
+ }
1735
+ },
1736
+ getSourceIp: function () {
1737
+ var ip = req.headers["x-forwarded-for"] || req.headers["x-real-ip"] || req["ip"];
1738
+ return ip && ip.split(",")[0].trim();
1739
+ },
1740
+ describeClient: function () {
1741
+ var requestHost = req.headers.get("host") || req.headers.get("host");
1742
+ var proto = cutPostfix([":", "/"], req.headers["x-forwarded-proto"] || req["nextUrl"]["protocol"] || "http");
1743
+ while (proto && proto.length > 0 && proto.charAt(proto.length - 1)) {
1744
+ proto = proto.substring(0, proto.length - 1);
1745
+ }
1746
+ var reqUrl = req.url || "/";
1747
+ var queryPos = reqUrl.indexOf("?");
1748
+ var path, query;
1749
+ if (queryPos >= 0) {
1750
+ path = reqUrl.substring(0, queryPos);
1751
+ query = reqUrl.substring(queryPos + 1);
1752
+ }
1753
+ else {
1754
+ path = reqUrl;
1755
+ query = undefined;
1756
+ }
1757
+ query = ensurePrefix(query, "?");
1758
+ path = ensurePrefix(path, "/");
1759
+ return {
1760
+ doc_encoding: "",
1761
+ doc_host: requestHost,
1762
+ doc_path: reqUrl,
1763
+ doc_search: query,
1764
+ page_title: "",
1765
+ referer: req.headers["referrer"],
1766
+ screen_resolution: "",
1767
+ url: proto + "://" + requestHost + (path || "") + (query || ""),
1768
+ user_agent: req.headers["user-agent"],
1769
+ user_language: req.headers["accept-language"] &&
1770
+ req.headers["accept-language"].split(",")[0],
1771
+ vp_size: "",
1772
+ };
1773
+ },
1774
+ };
1775
+ }
1776
+ function httpApi(req, res, opts) {
1777
+ if (opts === void 0) { opts = {}; }
1778
+ var header = function (req, name) {
1779
+ var vals = req.headers[name.toLowerCase()];
1780
+ if (!vals) {
1781
+ return undefined;
1782
+ }
1783
+ if (typeof vals === "string") {
1784
+ return vals;
1785
+ }
1786
+ else if (vals.length > 0) {
1787
+ return vals.join(",");
1788
+ }
1789
+ };
1790
+ return {
1791
+ getAnonymousId: function (_a) {
1792
+ var name = _a.name, domain = _a.domain;
1793
+ if (opts === null || opts === void 0 ? void 0 : opts.disableCookies) {
1794
+ return "";
1795
+ }
1796
+ var cookie = parseCookieString(req.headers["cookie"])[name];
1797
+ if (!cookie) {
1798
+ var cookieOpts = {
1799
+ maxAge: 31622400 * 10,
1800
+ httpOnly: false,
1801
+ };
1802
+ if (domain) {
1803
+ cookieOpts.domain = domain;
1804
+ }
1805
+ var newId = generateId();
1806
+ res.setHeader("Set-Cookie", serializeCookie(name, newId, cookieOpts));
1807
+ return newId;
1808
+ }
1809
+ else {
1810
+ return cookie;
1811
+ }
1812
+ },
1813
+ getSourceIp: function () {
1814
+ var ip = header(req, "x-forwarded-for") ||
1815
+ header(req, "x-real-ip") ||
1816
+ req.socket.remoteAddress;
1817
+ return ip && ip.split(",")[0].trim();
1818
+ },
1819
+ describeClient: function () {
1820
+ var url = req.url
1821
+ ? new URL(req.url, req.url.startsWith("http") ? undefined : "http://localhost")
1822
+ : {};
1823
+ var requestHost = header(req, "x-forwarded-host") || header(req, "host") || url.hostname;
1824
+ var proto = cutPostfix([":", "/"], header(req, "x-forwarded-proto") || url.protocol);
1825
+ var query = ensurePrefix("?", url.search);
1826
+ var path = ensurePrefix("/", url.pathname);
1827
+ return {
1828
+ doc_encoding: "",
1829
+ doc_host: requestHost,
1830
+ doc_path: req.url,
1831
+ doc_search: query,
1832
+ page_title: "",
1833
+ referer: header(req, "referrer"),
1834
+ screen_resolution: "",
1835
+ url: proto + "://" + requestHost + (path || "") + (query || ""),
1836
+ user_agent: req.headers["user-agent"],
1837
+ user_language: req.headers["accept-language"] &&
1838
+ req.headers["accept-language"].split(",")[0],
1839
+ vp_size: "",
1840
+ };
1841
+ },
1842
+ };
1843
+ }
1844
+ var emptyEnv = {
1845
+ getSourceIp: function () { return undefined; },
1846
+ describeClient: function () { return ({}); },
1847
+ getAnonymousId: function () { return ""; },
1848
+ };
1849
+ /**
1850
+ * Dictionary of supported environments
1851
+ */
1852
+ var envs = {
1853
+ httpApi: httpApi,
1854
+ nextjsApi: httpApi,
1855
+ // fetchApi: fetchApi,
1856
+ // nextjsMiddleware: fetchApi,
1857
+ browser: function () { return browserEnv; },
1858
+ express: httpApi,
1859
+ empty: function () { return emptyEnv; },
1860
+ };
1861
+ var xmlHttpTransport = function (url, jsonPayload, additionalHeaders, handler) {
1862
+ if (handler === void 0) { handler = function (code, body) {
1863
+ }; }
1864
+ var req = new window.XMLHttpRequest();
1865
+ return new Promise(function (resolve, reject) {
1866
+ req.onerror = function (e) {
1867
+ getLogger().error("Failed to send payload to " + url + ": " + ((e === null || e === void 0 ? void 0 : e.message) || "unknown error"), jsonPayload, e);
1868
+ handler(-1, {});
1869
+ reject(new Error("Failed to send JSON. See console logs"));
1870
+ };
1871
+ req.onload = function () {
1872
+ if (req.status !== 200) {
1873
+ handler(req.status, {});
1874
+ getLogger().warn("Failed to send data to " + url + " (#" + req.status + " - " + req.statusText + ")", jsonPayload);
1875
+ reject(new Error("Failed to send JSON. Error code: " + req.status + ". See logs for details"));
1876
+ }
1877
+ else {
1878
+ handler(req.status, req.responseText);
1879
+ }
1880
+ resolve();
1881
+ };
1882
+ req.open("POST", url);
1883
+ req.setRequestHeader("Content-Type", "application/json");
1884
+ Object.entries(additionalHeaders || {}).forEach(function (_a) {
1885
+ var key = _a[0], val = _a[1];
1886
+ return req.setRequestHeader(key, val);
1887
+ });
1888
+ req.send(jsonPayload);
1889
+ getLogger().debug("sending json", jsonPayload);
1890
+ });
1891
+ };
1892
+ var fetchTransport = function (fetch) {
1893
+ return function (url, jsonPayload, additionalHeaders, handler) {
1894
+ if (handler === void 0) { handler = function (code, body) {
1895
+ }; }
1896
+ return __awaiter(void 0, void 0, void 0, function () {
1897
+ var res, e_1, resJson, text, contentType, e_2;
1898
+ var _a, _b;
1899
+ return __generator(this, function (_c) {
1900
+ switch (_c.label) {
1901
+ case 0:
1902
+ _c.trys.push([0, 2, , 3]);
1903
+ return [4 /*yield*/, fetch(url, {
1904
+ method: "POST",
1905
+ headers: __assign({ Accept: "application/json", "Content-Type": "application/json" }, (additionalHeaders || {})),
1906
+ body: jsonPayload,
1907
+ })];
1908
+ case 1:
1909
+ res = _c.sent();
1910
+ return [3 /*break*/, 3];
1911
+ case 2:
1912
+ e_1 = _c.sent();
1913
+ getLogger().error("Failed to send data to " + url + ": " + ((e_1 === null || e_1 === void 0 ? void 0 : e_1.message) || "unknown error"), jsonPayload, e_1);
1914
+ handler(-1, {});
1915
+ return [2 /*return*/];
1916
+ case 3:
1917
+ if (res.status !== 200) {
1918
+ getLogger().warn("Failed to send data to " + url + " (#" + res.status + " - " + res.statusText + ")", jsonPayload);
1919
+ handler(res.status, {});
1920
+ return [2 /*return*/];
1921
+ }
1922
+ resJson = {};
1923
+ text = "";
1924
+ contentType = (_b = (_a = res.headers) === null || _a === void 0 ? void 0 : _a.get('Content-Type')) !== null && _b !== void 0 ? _b : "";
1925
+ _c.label = 4;
1926
+ case 4:
1927
+ _c.trys.push([4, 6, , 7]);
1928
+ return [4 /*yield*/, res.text()];
1929
+ case 5:
1930
+ text = _c.sent();
1931
+ resJson = JSON.parse(text);
1932
+ return [3 /*break*/, 7];
1933
+ case 6:
1934
+ e_2 = _c.sent();
1935
+ getLogger().error("Failed to parse " + url + " response. Content-type: " + contentType + " text: " + text, e_2);
1936
+ return [3 /*break*/, 7];
1937
+ case 7:
1938
+ try {
1939
+ handler(res.status, resJson);
1940
+ }
1941
+ catch (e) {
1942
+ getLogger().error("Failed to handle " + url + " response. Content-type: " + contentType + " text: " + text, e);
1943
+ }
1944
+ return [2 /*return*/];
1945
+ }
1946
+ });
1947
+ });
1948
+ };
1949
+ };
1950
+ var UsermavenClientImpl = /** @class */ (function () {
1951
+ function UsermavenClientImpl() {
1952
+ this.userProperties = {};
1953
+ this.groupProperties = {};
1954
+ this.permanentProperties = {
1955
+ globalProps: {},
1956
+ propsPerEvent: {},
1957
+ };
1958
+ this.cookieDomain = "";
1959
+ this.trackingHost = "";
1960
+ this.idCookieName = "";
1961
+ this.randomizeUrl = false;
1962
+ this.namespace = "usermaven";
1963
+ this.crossDomainLinking = true;
1964
+ this.formTracking = false;
1965
+ this.domains = [];
1966
+ this.apiKey = "";
1967
+ this.initialized = false;
1968
+ this._3pCookies = {};
1969
+ this.cookiePolicy = "keep";
1970
+ this.ipPolicy = "keep";
1971
+ this.beaconApi = false;
1972
+ this.transport = xmlHttpTransport;
1973
+ this.customHeaders = function () { return ({}); };
1974
+ this.queue = new MemoryQueue();
1975
+ this.maxSendAttempts = 4;
1976
+ this.retryTimeout = [500, 1e12];
1977
+ this.flushing = false;
1978
+ this.attempt = 1;
1979
+ this.propertyBlacklist = [];
1980
+ // public persistence?: UserMavenPersistence;
1981
+ // public sessionManager?: SessionIdManager;
1982
+ this.__autocapture_enabled = false;
1983
+ this.__auto_pageview_enabled = false;
1984
+ // private anonymousId: string = '';
1985
+ // Fallback tracking host
1986
+ this.trackingHostFallback = "https://events.usermaven.com" ;
1987
+ }
1988
+ // Used for session + autocapture
1989
+ UsermavenClientImpl.prototype.get_config = function (prop_name) {
1990
+ return this.config ? this.config[prop_name] : null;
1991
+ };
1992
+ UsermavenClientImpl.prototype.id = function (props, doNotSendEvent) {
1993
+ this.userProperties = __assign(__assign({}, this.userProperties), props);
1994
+ getLogger().debug("Usermaven user identified", props);
1995
+ if (this.userIdPersistence) {
1996
+ this.userIdPersistence.save(props);
1997
+ }
1998
+ else {
1999
+ getLogger().warn("Id() is called before initialization");
2000
+ }
2001
+ if (!doNotSendEvent) {
2002
+ return this.track("user_identify", {});
2003
+ }
2004
+ else {
2005
+ return Promise.resolve();
2006
+ }
2007
+ };
2008
+ UsermavenClientImpl.prototype.group = function (props, doNotSendEvent) {
2009
+ this.groupProperties = __assign(__assign({}, this.groupProperties), props);
2010
+ getLogger().debug("Usermaven group identified", props);
2011
+ if (this.userIdPersistence) {
2012
+ // Update the 'company' property in the user persistence
2013
+ this.userIdPersistence.save({ company: props });
2014
+ }
2015
+ else {
2016
+ getLogger().warn("Group() is called before initialization");
2017
+ }
2018
+ if (!doNotSendEvent) {
2019
+ return this.track("group", {});
2020
+ }
2021
+ else {
2022
+ return Promise.resolve();
2023
+ }
2024
+ };
2025
+ UsermavenClientImpl.prototype.reset = function (resetAnonId) {
2026
+ if (this.userIdPersistence) {
2027
+ this.userIdPersistence.delete();
2028
+ }
2029
+ if (this.propsPersistance) {
2030
+ this.propsPersistance.delete();
2031
+ }
2032
+ if (resetAnonId) {
2033
+ var idCookie = getCookie(this.idCookieName);
2034
+ if (idCookie) {
2035
+ getLogger().debug("Removing id cookie", idCookie);
2036
+ setCookie(this.idCookieName, "", {
2037
+ domain: this.cookieDomain,
2038
+ expires: new Date(0),
2039
+ });
2040
+ }
2041
+ }
2042
+ return Promise.resolve();
2043
+ };
2044
+ UsermavenClientImpl.prototype.rawTrack = function (payload) {
2045
+ return this.sendJson(payload);
2046
+ };
2047
+ UsermavenClientImpl.prototype.makeEvent = function (event_type, src, payload) {
2048
+ var _a;
2049
+ var env = payload.env, payloadData = __rest(payload, ["env"]);
2050
+ if (!env) {
2051
+ env = isWindowAvailable() ? envs.browser() : envs.empty();
2052
+ }
2053
+ this.restoreId();
2054
+ var context = this.getCtx(env);
2055
+ var persistentProps = __assign(__assign({}, this.permanentProperties.globalProps), ((_a = this.permanentProperties.propsPerEvent[event_type]) !== null && _a !== void 0 ? _a : {}));
2056
+ var base = __assign({ api_key: this.apiKey, src: src, event_type: event_type }, payloadData);
2057
+ var sourceIp = env.getSourceIp();
2058
+ if (sourceIp) {
2059
+ base["source_ip"] = sourceIp;
2060
+ }
2061
+ return this.compatMode
2062
+ ? __assign(__assign(__assign({}, persistentProps), { eventn_ctx: context }), base) : __assign(__assign(__assign({}, persistentProps), context), base);
2063
+ };
2064
+ UsermavenClientImpl.prototype._send3p = function (sourceType, object, type) {
2065
+ var eventType = "3rdparty";
2066
+ if (type && type !== "") {
2067
+ eventType = type;
2068
+ }
2069
+ var e = this.makeEvent(eventType, sourceType, {
2070
+ src_payload: object,
2071
+ });
2072
+ return this.sendJson(e);
2073
+ };
2074
+ UsermavenClientImpl.prototype.sendJson = function (json) {
2075
+ return __awaiter(this, void 0, Promise, function () {
2076
+ var umExclusionState;
2077
+ return __generator(this, function (_a) {
2078
+ switch (_a.label) {
2079
+ case 0:
2080
+ umExclusionState = getUmExclusionState();
2081
+ if (!!umExclusionState) return [3 /*break*/, 3];
2082
+ if (!(this.maxSendAttempts > 1)) return [3 /*break*/, 1];
2083
+ this.queue.push([json, 0]);
2084
+ this.scheduleFlush(0);
2085
+ return [3 /*break*/, 3];
2086
+ case 1: return [4 /*yield*/, this.doSendJson(json)];
2087
+ case 2:
2088
+ _a.sent();
2089
+ _a.label = 3;
2090
+ case 3: return [2 /*return*/];
2091
+ }
2092
+ });
2093
+ });
2094
+ };
2095
+ UsermavenClientImpl.prototype.doSendJson = function (json) {
2096
+ var _this = this;
2097
+ var cookiePolicy = this.cookiePolicy !== "keep" ? "&cookie_policy=" + this.cookiePolicy : "";
2098
+ var ipPolicy = this.ipPolicy !== "keep" ? "&ip_policy=" + this.ipPolicy : "";
2099
+ var urlPrefix = isWindowAvailable() ? "/api/v1/event" : "/api/v1/s2s/event";
2100
+ var url = "" + this.trackingHost + urlPrefix + "?token=" + this.apiKey + cookiePolicy + ipPolicy;
2101
+ if (this.randomizeUrl) {
2102
+ url = this.trackingHost + "/api." + generateRandom() + "?p_" + generateRandom() + "=" + this.apiKey + cookiePolicy + ipPolicy;
2103
+ }
2104
+ var jsonString = JSON.stringify(json);
2105
+ getLogger().debug("Sending payload to " + url, json.length);
2106
+ return this.transport(url, jsonString, this.customHeaders(), function (code, body) {
2107
+ return _this.postHandle(code, body);
2108
+ });
2109
+ };
2110
+ UsermavenClientImpl.prototype.scheduleFlush = function (timeout) {
2111
+ var _this = this;
2112
+ if (this.flushing) {
2113
+ return;
2114
+ }
2115
+ this.flushing = true;
2116
+ if (typeof timeout === "undefined") {
2117
+ var random = Math.random() + 1;
2118
+ var factor = Math.pow(2, this.attempt++);
2119
+ timeout = Math.min(this.retryTimeout[0] * random * factor, this.retryTimeout[1]);
2120
+ }
2121
+ getLogger().debug("Scheduling event queue flush in " + timeout + " ms.");
2122
+ setTimeout(function () { return _this.flush(); }, timeout);
2123
+ };
2124
+ UsermavenClientImpl.prototype.flush = function () {
2125
+ return __awaiter(this, void 0, Promise, function () {
2126
+ var queue;
2127
+ var _a;
2128
+ var _this = this;
2129
+ return __generator(this, function (_b) {
2130
+ switch (_b.label) {
2131
+ case 0:
2132
+ if (isWindowAvailable() && !window.navigator.onLine) {
2133
+ this.flushing = false;
2134
+ this.scheduleFlush();
2135
+ }
2136
+ queue = this.queue.flush();
2137
+ this.flushing = false;
2138
+ if (queue.length === 0) {
2139
+ return [2 /*return*/];
2140
+ }
2141
+ _b.label = 1;
2142
+ case 1:
2143
+ _b.trys.push([1, 3, , 4]);
2144
+ return [4 /*yield*/, this.doSendJson(queue.map(function (el) { return el[0]; }))];
2145
+ case 2:
2146
+ _b.sent();
2147
+ this.attempt = 1;
2148
+ getLogger().debug("Successfully flushed " + queue.length + " events from queue");
2149
+ return [3 /*break*/, 4];
2150
+ case 3:
2151
+ _b.sent();
2152
+ // In case of failing custom domain (trackingHost), we will replace it with default domain (trackingHostFallback)
2153
+ if (this.trackingHost !== this.trackingHostFallback) {
2154
+ getLogger().debug("Using fallback tracking host " + this.trackingHostFallback + " instead of " + this.trackingHost + " on " + VERSION_INFO.env);
2155
+ this.trackingHost = this.trackingHostFallback;
2156
+ }
2157
+ queue = queue.map(function (el) { return [el[0], el[1] + 1]; }).filter(function (el) {
2158
+ if (el[1] >= _this.maxSendAttempts) {
2159
+ getLogger().error("Dropping queued event after " + el[1] + " attempts since max send attempts " + _this.maxSendAttempts + " reached. See logs for details");
2160
+ return false;
2161
+ }
2162
+ return true;
2163
+ });
2164
+ if (queue.length > 0) {
2165
+ (_a = this.queue).push.apply(_a, queue);
2166
+ this.scheduleFlush();
2167
+ }
2168
+ else {
2169
+ this.attempt = 1;
2170
+ }
2171
+ return [3 /*break*/, 4];
2172
+ case 4: return [2 /*return*/];
2173
+ }
2174
+ });
2175
+ });
2176
+ };
2177
+ UsermavenClientImpl.prototype.postHandle = function (status, response) {
2178
+ if (this.cookiePolicy === "strict" || this.cookiePolicy === "comply") {
2179
+ if (status === 200) {
2180
+ var data = response;
2181
+ if (typeof response === "string") {
2182
+ data = JSON.parse(response);
2183
+ }
2184
+ if (!data["delete_cookie"]) {
2185
+ return;
2186
+ }
2187
+ }
2188
+ this.userIdPersistence.delete();
2189
+ this.propsPersistance.delete();
2190
+ deleteCookie(this.idCookieName);
2191
+ }
2192
+ if (status === 200) {
2193
+ var data = response;
2194
+ if (typeof response === "string" && response.length > 0) {
2195
+ data = JSON.parse(response);
2196
+ var extras = data["jitsu_sdk_extras"];
2197
+ if (extras && extras.length > 0) {
2198
+ var isWindow = isWindowAvailable();
2199
+ if (!isWindow) {
2200
+ getLogger().error("Tags destination supported only in browser environment");
2201
+ }
2202
+ else {
2203
+ for (var _i = 0, extras_1 = extras; _i < extras_1.length; _i++) {
2204
+ var _a = extras_1[_i], type = _a.type, id = _a.id, value = _a.value;
2205
+ if (type === "tag") {
2206
+ var tag = document.createElement("div");
2207
+ tag.id = id;
2208
+ insertAndExecute(tag, value);
2209
+ if (tag.childElementCount > 0) {
2210
+ document.body.appendChild(tag);
2211
+ }
2212
+ }
2213
+ }
2214
+ }
2215
+ }
2216
+ }
2217
+ }
2218
+ };
2219
+ UsermavenClientImpl.prototype.getCtx = function (env) {
2220
+ var now = new Date();
2221
+ var props = env.describeClient() || {};
2222
+ var user = __assign({}, this.userProperties);
2223
+ var company = user['company'] || {};
2224
+ delete user['company'];
2225
+ var payload = __assign(__assign({ event_id: "", user: __assign(__assign({}, user), { anonymous_id: this.cookiePolicy !== "strict"
2226
+ ? env.getAnonymousId({
2227
+ name: this.idCookieName,
2228
+ domain: this.cookieDomain,
2229
+ crossDomainLinking: this.crossDomainLinking,
2230
+ })
2231
+ : "" }), ids: this._getIds(), utc_time: reformatDate(now.toISOString()), local_tz_offset: now.getTimezoneOffset() }, props), getDataFromParams(parseQuery(props.doc_search)));
2232
+ // id and name attributes will be checked on backend
2233
+ if (Object.keys(company).length) {
2234
+ payload['company'] = company;
2235
+ }
2236
+ return payload;
2237
+ };
2238
+ UsermavenClientImpl.prototype._getIds = function () {
2239
+ if (!isWindowAvailable()) {
2240
+ return {};
2241
+ }
2242
+ var cookies = getCookies(false);
2243
+ var res = {};
2244
+ for (var _i = 0, _a = Object.entries(cookies); _i < _a.length; _i++) {
2245
+ var _b = _a[_i], key = _b[0], value = _b[1];
2246
+ if (this._3pCookies[key]) {
2247
+ res[key.charAt(0) == "_" ? key.substr(1) : key] = value;
2248
+ }
2249
+ }
2250
+ return res;
2251
+ };
2252
+ UsermavenClientImpl.prototype.pathMatches = function (wildcardPath, docUrl) {
2253
+ var actualPath = new URL(docUrl).pathname;
2254
+ return actualPath.match(new RegExp('^' + wildcardPath.trim().replace(/\*\*/g, '.*').replace(/([^\.])\*/g, '$1[^\\s\/]*') + '\/?$'));
2255
+ };
2256
+ UsermavenClientImpl.prototype.track = function (type, payload) {
2257
+ var _this = this;
2258
+ var data = payload || {};
2259
+ getLogger().debug("track event of type", type, data);
2260
+ var env = isWindowAvailable() ? envs.browser() : envs.empty();
2261
+ var context = this.getCtx(env);
2262
+ // Check if the page is not excluded.
2263
+ if (this.config && this.config.exclude && this.config.exclude.length > 1 && (context === null || context === void 0 ? void 0 : context.url)) {
2264
+ var excludeList = this.config.exclude.split(',');
2265
+ // check if the current page is in the exclude list
2266
+ if (excludeList.some(function (excludePage) { return _this.pathMatches(excludePage.trim(), context === null || context === void 0 ? void 0 : context.url); })) {
2267
+ getLogger().debug("Page is excluded from tracking");
2268
+ return;
2269
+ }
2270
+ }
2271
+ var p = payload || {};
2272
+ // All custom events and scroll event will have event_attributes
2273
+ if (type !== "$autocapture" && type !== "user_identify" && type !== "pageview" && type !== "$pageleave") {
2274
+ p = {
2275
+ event_attributes: payload,
2276
+ };
2277
+ }
2278
+ var e = this.makeEvent(type, this.compatMode ? "eventn" : "usermaven", p);
2279
+ return this.sendJson(e);
2280
+ };
2281
+ UsermavenClientImpl.prototype.init = function (options) {
2282
+ var _this = this;
2283
+ var _a, _b, _c, _d, _e, _f;
2284
+ if (isWindowAvailable() && !options.force_use_fetch) {
2285
+ if (options.fetch) {
2286
+ getLogger().warn("Custom fetch implementation is provided to Usermaven. However, it will be ignored since Usermaven runs in browser");
2287
+ }
2288
+ this.transport = this.beaconApi ? beaconTransport : xmlHttpTransport;
2289
+ }
2290
+ else {
2291
+ if (!options.fetch && !globalThis.fetch) {
2292
+ throw new Error("Usermaven runs in Node environment. However, neither UsermavenOptions.fetch is provided, nor global fetch function is defined. \n" +
2293
+ "Please, provide custom fetch implementation. You can get it via node-fetch package");
2294
+ }
2295
+ this.transport = fetchTransport(options.fetch || globalThis.fetch);
2296
+ }
2297
+ if (options.custom_headers &&
2298
+ typeof options.custom_headers === "function") {
2299
+ this.customHeaders = options.custom_headers;
2300
+ }
2301
+ else if (options.custom_headers) {
2302
+ this.customHeaders = function () {
2303
+ return options.custom_headers;
2304
+ };
2305
+ }
2306
+ if (options.tracking_host === "echo") {
2307
+ getLogger().warn('jitsuClient is configured with "echo" transport. Outgoing requests will be written to console');
2308
+ this.transport = echoTransport;
2309
+ }
2310
+ if (options.ip_policy) {
2311
+ this.ipPolicy = options.ip_policy;
2312
+ }
2313
+ if (options.cookie_policy) {
2314
+ this.cookiePolicy = options.cookie_policy;
2315
+ }
2316
+ if (options.privacy_policy === "strict") {
2317
+ this.ipPolicy = "strict";
2318
+ this.cookiePolicy = "strict";
2319
+ }
2320
+ if (options.use_beacon_api && navigator.sendBeacon) {
2321
+ this.beaconApi = true;
2322
+ }
2323
+ //can't handle delete cookie response when beacon api
2324
+ if (this.cookiePolicy === "comply" && this.beaconApi) {
2325
+ this.cookiePolicy = "strict";
2326
+ }
2327
+ if (options.log_level) {
2328
+ setRootLogLevel(options.log_level);
2329
+ }
2330
+ this.initialOptions = options;
2331
+ getLogger().debug("Initializing Usemaven Tracker tracker", options, USERMAVEN_VERSION);
2332
+ if (!options.key) {
2333
+ getLogger().error("Can't initialize Usemaven, key property is not set");
2334
+ return;
2335
+ }
2336
+ this.compatMode =
2337
+ options.compat_mode === undefined
2338
+ ? defaultCompatMode
2339
+ : !!options.compat_mode;
2340
+ this.cookieDomain = options.cookie_domain || getCookieDomain();
2341
+ this.namespace = options.namespace || "usermaven";
2342
+ this.crossDomainLinking = (_a = options.cross_domain_linking) !== null && _a !== void 0 ? _a : true;
2343
+ this.formTracking = (_b = options.form_tracking) !== null && _b !== void 0 ? _b : false;
2344
+ this.domains = options.domains ? (options.domains).split(',').map(function (domain) { return domain.trim(); }) : [];
2345
+ this.trackingHost = getHostWithProtocol(options["tracking_host"] || "t.usermaven.com");
2346
+ this.randomizeUrl = options.randomize_url || false;
2347
+ this.apiKey = options.key;
2348
+ this.__auto_pageview_enabled = options.auto_pageview || false;
2349
+ this.idCookieName = options.cookie_name || "__eventn_id_" + options.key;
2350
+ if (this.cookiePolicy === "strict") {
2351
+ this.propsPersistance = new NoPersistence();
2352
+ }
2353
+ else {
2354
+ this.propsPersistance = isWindowAvailable()
2355
+ ? new CookiePersistence(this.cookieDomain, this.idCookieName + "_props")
2356
+ : new NoPersistence();
2357
+ }
2358
+ if (this.cookiePolicy === "strict") {
2359
+ this.userIdPersistence = new NoPersistence();
2360
+ }
2361
+ else {
2362
+ this.userIdPersistence = isWindowAvailable()
2363
+ ? new CookiePersistence(this.cookieDomain, this.idCookieName + "_usr")
2364
+ : new NoPersistence();
2365
+ }
2366
+ if (this.propsPersistance) {
2367
+ var restored = this.propsPersistance.restore();
2368
+ if (restored) {
2369
+ this.permanentProperties = restored;
2370
+ this.permanentProperties.globalProps = (_c = restored.globalProps) !== null && _c !== void 0 ? _c : {};
2371
+ this.permanentProperties.propsPerEvent = (_d = restored.propsPerEvent) !== null && _d !== void 0 ? _d : {};
2372
+ }
2373
+ getLogger().debug("Restored persistent properties", this.permanentProperties);
2374
+ }
2375
+ this.propertyBlacklist = options.property_blacklist && options.property_blacklist.length > 0 ? options.property_blacklist : [];
2376
+ // // Added these configuration for session management + autocapture
2377
+ var defaultConfig = {
2378
+ autocapture: false,
2379
+ properties_string_max_length: null,
2380
+ property_blacklist: [],
2381
+ sanitize_properties: null,
2382
+ auto_pageview: false
2383
+ };
2384
+ this.config = _extend({}, defaultConfig, options || {}, this.config || {}, { token: this.apiKey });
2385
+ getLogger().debug('Default Configuration', this.config);
2386
+ // this.manageSession(this.config);
2387
+ this.manageAutoCapture(this.config);
2388
+ this.manageFormTracking(this.config);
2389
+ this.manageCrossDomainLinking({
2390
+ cross_domain_linking: this.crossDomainLinking,
2391
+ domains: this.domains,
2392
+ cookiePolicy: this.cookiePolicy
2393
+ });
2394
+ if (options.capture_3rd_party_cookies === false) {
2395
+ this._3pCookies = {};
2396
+ }
2397
+ else {
2398
+ (options.capture_3rd_party_cookies || [
2399
+ "_ga",
2400
+ "_fbp",
2401
+ "_ym_uid",
2402
+ "ajs_user_id",
2403
+ "ajs_anonymous_id",
2404
+ ]).forEach(function (name) { return (_this._3pCookies[name] = true); });
2405
+ }
2406
+ if (options.ga_hook) {
2407
+ getLogger().warn("GA event interceptor isn't supported anymore");
2408
+ }
2409
+ if (options.segment_hook) {
2410
+ interceptSegmentCalls(this);
2411
+ }
2412
+ if (isWindowAvailable()) {
2413
+ if (!options.disable_event_persistence) {
2414
+ this.queue = new LocalStorageQueue(this.namespace + "-event-queue");
2415
+ this.scheduleFlush(0);
2416
+ }
2417
+ window.addEventListener("beforeunload", function () { return _this.flush(); });
2418
+ }
2419
+ if (this.__auto_pageview_enabled) {
2420
+ enableAutoPageviews(this);
2421
+ }
2422
+ this.retryTimeout = [
2423
+ (_e = options.min_send_timeout) !== null && _e !== void 0 ? _e : this.retryTimeout[0],
2424
+ (_f = options.max_send_timeout) !== null && _f !== void 0 ? _f : this.retryTimeout[1],
2425
+ ];
2426
+ if (!!options.max_send_attempts) {
2427
+ this.maxSendAttempts = options.max_send_attempts;
2428
+ }
2429
+ this.initialized = true;
2430
+ };
2431
+ UsermavenClientImpl.prototype.interceptAnalytics = function (analytics) {
2432
+ var _this = this;
2433
+ var interceptor = function (chain) {
2434
+ var _a;
2435
+ try {
2436
+ var payload = __assign({}, chain.payload);
2437
+ getLogger().debug("Intercepted segment payload", payload.obj);
2438
+ var integration = chain.integrations["Segment.io"];
2439
+ if (integration && integration.analytics) {
2440
+ var analyticsOriginal = integration.analytics;
2441
+ if (typeof analyticsOriginal.user === "function" &&
2442
+ analyticsOriginal.user() &&
2443
+ typeof analyticsOriginal.user().id === "function") {
2444
+ payload.obj.userId = analyticsOriginal.user().id();
2445
+ }
2446
+ }
2447
+ if ((_a = payload === null || payload === void 0 ? void 0 : payload.obj) === null || _a === void 0 ? void 0 : _a.timestamp) {
2448
+ payload.obj.sentAt = payload.obj.timestamp;
2449
+ }
2450
+ var type = chain.payload.type();
2451
+ if (type === "track") {
2452
+ type = chain.payload.event();
2453
+ }
2454
+ _this._send3p("ajs", payload, type);
2455
+ }
2456
+ catch (e) {
2457
+ getLogger().warn("Failed to send an event", e);
2458
+ }
2459
+ chain.next(chain.payload);
2460
+ };
2461
+ if (typeof analytics.addSourceMiddleware === "function") {
2462
+ //analytics is fully initialized
2463
+ getLogger().debug("Analytics.js is initialized, calling addSourceMiddleware");
2464
+ analytics.addSourceMiddleware(interceptor);
2465
+ }
2466
+ else {
2467
+ getLogger().debug("Analytics.js is not initialized, pushing addSourceMiddleware to callstack");
2468
+ analytics.push(["addSourceMiddleware", interceptor]);
2469
+ }
2470
+ analytics["__en_intercepted"] = true;
2471
+ };
2472
+ UsermavenClientImpl.prototype.restoreId = function () {
2473
+ if (this.userIdPersistence) {
2474
+ var props = this.userIdPersistence.restore();
2475
+ if (props) {
2476
+ this.userProperties = __assign(__assign({}, props), this.userProperties);
2477
+ }
2478
+ }
2479
+ };
2480
+ UsermavenClientImpl.prototype.set = function (properties, opts) {
2481
+ var _a;
2482
+ var eventType = opts === null || opts === void 0 ? void 0 : opts.eventType;
2483
+ var persist = (opts === null || opts === void 0 ? void 0 : opts.persist) === undefined || (opts === null || opts === void 0 ? void 0 : opts.persist);
2484
+ if (eventType !== undefined) {
2485
+ var current = (_a = this.permanentProperties.propsPerEvent[eventType]) !== null && _a !== void 0 ? _a : {};
2486
+ this.permanentProperties.propsPerEvent[eventType] = __assign(__assign({}, current), properties);
2487
+ }
2488
+ else {
2489
+ this.permanentProperties.globalProps = __assign(__assign({}, this.permanentProperties.globalProps), properties);
2490
+ }
2491
+ if (this.propsPersistance && persist) {
2492
+ this.propsPersistance.save(this.permanentProperties);
2493
+ }
2494
+ };
2495
+ UsermavenClientImpl.prototype.unset = function (propertyName, opts) {
2496
+ requireWindow();
2497
+ var eventType = opts === null || opts === void 0 ? void 0 : opts.eventType;
2498
+ var persist = (opts === null || opts === void 0 ? void 0 : opts.persist) === undefined || (opts === null || opts === void 0 ? void 0 : opts.persist);
2499
+ if (!eventType) {
2500
+ delete this.permanentProperties.globalProps[propertyName];
2501
+ }
2502
+ else if (this.permanentProperties.propsPerEvent[eventType]) {
2503
+ delete this.permanentProperties.propsPerEvent[eventType][propertyName];
2504
+ }
2505
+ if (this.propsPersistance && persist) {
2506
+ this.propsPersistance.save(this.permanentProperties);
2507
+ }
2508
+ };
2509
+ UsermavenClientImpl.prototype.manageCrossDomainLinking = function (options) {
2510
+ if (!isWindowAvailable() || !options.cross_domain_linking || options.domains.length === 0 || options.cookiePolicy === "strict") {
2511
+ return false;
2512
+ }
2513
+ var cookieName = this.idCookieName;
2514
+ var domains = options.domains || [];
2515
+ // Listen for all clicks on the page
2516
+ document.addEventListener('click', function (event) {
2517
+ // Find the closest link
2518
+ var target = _findClosestLink(event.target);
2519
+ if (target) {
2520
+ // Check if the link is pointing to a different domain
2521
+ var href = (target === null || target === void 0 ? void 0 : target.hasAttribute('href')) ? target === null || target === void 0 ? void 0 : target.getAttribute('href') : '';
2522
+ if (href && href.startsWith('http')) {
2523
+ var url = new URL(href);
2524
+ var cookie = getCookie(cookieName);
2525
+ // Skip the link if it's pointing to the current domain
2526
+ if (url.hostname === window.location.hostname) {
2527
+ return;
2528
+ }
2529
+ if (domains.includes(url.hostname) && cookie) {
2530
+ // Add the '_um' parameter to the URL
2531
+ url.searchParams.append('_um', cookie);
2532
+ target.setAttribute('href', url.toString());
2533
+ }
2534
+ }
2535
+ }
2536
+ }, false);
2537
+ };
2538
+ /**
2539
+ * Manage auto-capturing
2540
+ * @param options
2541
+ */
2542
+ UsermavenClientImpl.prototype.manageAutoCapture = function (options) {
2543
+ getLogger().debug("Auto Capture Status: ", this.config['autocapture']);
2544
+ this.__autocapture_enabled = this.config['autocapture'] && isWindowAvailable();
2545
+ if (!this.__autocapture_enabled) {
2546
+ return;
2547
+ }
2548
+ var num_buckets = 100;
2549
+ var num_enabled_buckets = 100;
2550
+ if (!autocapture.enabledForProject(this.apiKey, num_buckets, num_enabled_buckets)) {
2551
+ this.config['autocapture'] = false;
2552
+ this.__autocapture_enabled = false;
2553
+ getLogger().debug('Not in active bucket: disabling Automatic Event Collection.');
2554
+ }
2555
+ else if (!autocapture.isBrowserSupported()) {
2556
+ this.config['autocapture'] = false;
2557
+ this.__autocapture_enabled = false;
2558
+ getLogger().debug('Disabling Automatic Event Collection because this browser is not supported');
2559
+ }
2560
+ else {
2561
+ getLogger().debug('Autocapture enabled...');
2562
+ autocapture.init(this, options);
2563
+ }
2564
+ };
2565
+ /**
2566
+ * Manage form tracking
2567
+ */
2568
+ UsermavenClientImpl.prototype.manageFormTracking = function (options) {
2569
+ if (!isWindowAvailable() || !this.formTracking || this.formTracking === "none") {
2570
+ return;
2571
+ }
2572
+ getLogger().debug('Form tracking enabled...');
2573
+ // all and true are the same
2574
+ var trackingType = this.formTracking === true ? 'all' : this.formTracking;
2575
+ FormTracking.getInstance(this, trackingType).track();
2576
+ };
2577
+ /**
2578
+ * Capture an event. This is the most important and
2579
+ * frequently used usermaven function.
2580
+ *
2581
+ * ### Usage:
2582
+ * usermaven.capture('Registered', {'Gender': 'Male', 'Age': 21}, {});
2583
+ *
2584
+ * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.
2585
+ * @param {Object} [properties] A set of properties to include with the event you're sending. These describe the user who did the event or details about the event itself.
2586
+ * @param {Object} [options] Optional configuration for this capture request.
2587
+ * @param {String} [options.transport] Transport method for network request ('XHR' or 'sendBeacon').
2588
+ */
2589
+ UsermavenClientImpl.prototype.capture = function (event_name, properties) {
2590
+ var _a, _b;
2591
+ if (properties === void 0) { properties = {}; }
2592
+ if (!this.initialized) {
2593
+ console.error('Trying to capture event before initialization');
2594
+ return;
2595
+ }
2596
+ if (_isUndefined(event_name) || typeof event_name !== 'string') {
2597
+ console.error('No event name provided to usermaven.capture');
2598
+ return;
2599
+ }
2600
+ // if (_.isBlockedUA(userAgent)) {
2601
+ // return
2602
+ // }
2603
+ var data = {
2604
+ event: event_name + (properties['$event_type'] ? '_' + properties['$event_type'] : ''),
2605
+ properties: this._calculate_event_properties(event_name, properties),
2606
+ };
2607
+ data = _copyAndTruncateStrings(data, this.get_config('properties_string_max_length'));
2608
+ // send event if there is a tagname available
2609
+ if ((_b = (_a = data.properties) === null || _a === void 0 ? void 0 : _a.autocapture_attributes) === null || _b === void 0 ? void 0 : _b.tag_name) {
2610
+ this.track("$autocapture", data.properties);
2611
+ // this.track(data.event, data.properties)
2612
+ }
2613
+ // send event if the event is $scroll
2614
+ if (event_name === '$scroll') {
2615
+ this.track(event_name, data.properties);
2616
+ }
2617
+ // send event if the event is $form
2618
+ if (event_name === '$form') {
2619
+ this.track(event_name, data.properties);
2620
+ }
2621
+ };
2622
+ UsermavenClientImpl.prototype._calculate_event_properties = function (event_name, event_properties) {
2623
+ var _a, _b;
2624
+ // set defaults
2625
+ var properties = event_properties || {};
2626
+ if (event_name === '$snapshot' || event_name === '$scroll' || event_name === '$form') {
2627
+ return properties;
2628
+ }
2629
+ if (_isArray(this.propertyBlacklist)) {
2630
+ _each(this.propertyBlacklist, function (blacklisted_prop) {
2631
+ delete properties[blacklisted_prop];
2632
+ });
2633
+ }
2634
+ else {
2635
+ console.error('Invalid value for property_blacklist config: ' + this.propertyBlacklist);
2636
+ }
2637
+ // assign first element from $elements only
2638
+ var attributes = {};
2639
+ var elements = properties['$elements'] || [];
2640
+ if (elements.length) {
2641
+ attributes = elements[0];
2642
+ }
2643
+ properties['autocapture_attributes'] = attributes;
2644
+ properties['autocapture_attributes']["el_text"] = (_a = properties['autocapture_attributes']["$el_text"]) !== null && _a !== void 0 ? _a : "";
2645
+ properties['autocapture_attributes']["event_type"] = (_b = properties["$event_type"]) !== null && _b !== void 0 ? _b : "";
2646
+ ['$ce_version', "$event_type", "$initial_referrer", "$initial_referring_domain", "$referrer", "$referring_domain", "$elements"].forEach(function (key) {
2647
+ delete properties[key];
2648
+ });
2649
+ // TODO: later remove this from the autotrack code.
2650
+ delete properties['autocapture_attributes']["$el_text"];
2651
+ delete properties['autocapture_attributes']["nth_child"];
2652
+ delete properties['autocapture_attributes']["nth_of_type"];
2653
+ return properties;
2654
+ };
2655
+ return UsermavenClientImpl;
2656
+ }());
2657
+ function enableAutoPageviews(t) {
2658
+ var page = function () { return t.track("pageview"); };
2659
+ // Attach pushState and popState listeners
2660
+ var originalPushState = history.pushState;
2661
+ if (originalPushState) {
2662
+ // eslint-disable-next-line functional/immutable-data
2663
+ history.pushState = function (data, title, url) {
2664
+ originalPushState.apply(this, [data, title, url]);
2665
+ page();
2666
+ };
2667
+ addEventListener('popstate', page);
2668
+ }
2669
+ addEventListener('hashchange', page);
2670
+ }
2671
+ function interceptSegmentCalls(t) {
2672
+ var win = window;
2673
+ if (!win.analytics) {
2674
+ win.analytics = [];
2675
+ }
2676
+ t.interceptAnalytics(win.analytics);
2677
+ }
2678
+
2679
+ exports.envs = envs;
2680
+ exports.fetchApi = fetchApi;
2681
+ exports.httpApi = httpApi;
2682
+ exports.usermavenClient = usermavenClient;