@usermaven/nextjs 1.4.0 → 1.4.1-rc.58

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