@usermaven/react 1.4.1-rc.59 → 1.4.1

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