@usermaven/nextjs 1.4.0 → 1.4.1-rc.59

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