@usermaven/sdk-js 1.1.8 → 1.2.0

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/README.md CHANGED
@@ -49,3 +49,4 @@ You will be able to access the domains at [localhost domain](http://localhost.co
49
49
 
50
50
  * Login with your *personal* credentials with `npm login`
51
51
  * Run `yarn install && yarn build && yarn test && npm publish --access public`
52
+ npm
@@ -176,7 +176,10 @@ function createLogger(logLevel) {
176
176
  */
177
177
 
178
178
  function isWindowAvailable(warnMsg = undefined) {
179
- let windowAvailable = !!globalThis.window;
179
+ //here we check not only of window object is globally available, but also if it's not a fake one
180
+ //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
181
+ const windowAvailable = !!globalThis.window && !!globalThis.window.document && !!globalThis.window.location;
182
+
180
183
  if (!windowAvailable && warnMsg) {
181
184
  getLogger().warn(warnMsg);
182
185
  }
@@ -195,25 +198,37 @@ function requireWindow(msg = undefined) {
195
198
  return window;
196
199
  }
197
200
 
198
- var DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i;
199
- var getCrossSubdomain = function () {
200
- var matches = document.location.hostname.match(DOMAIN_MATCH_REGEX);
201
- var domain = matches ? matches[0] : '';
202
- return domain ? ".".concat(domain) : '';
201
+ /**
202
+ * Checks if the domain is valid for setting cross domain cookies
203
+ * To check we will use Domain Matching technique as mentioned in RFC 6265 - https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3
204
+ * @param domain
205
+ */
206
+ var isValidCrossDomain = function (domain) {
207
+ var domain_parts = domain.split('.'); // .domain.com => ['', 'domain', 'com']
208
+ var host_parts = window.location.hostname.split('.'); // stage.domain.com => ['stage', 'domain', 'com']
209
+ // Check if the domain is a subdomain of the current host
210
+ // If yes, then it is a valid domain for setting cross domain cookies
211
+ var isValid = host_parts.length > domain_parts.length && host_parts.slice(-domain_parts.length).join('.') === domain_parts.filter(Boolean).join('.');
212
+ getLogger().debug("isValidCrossDomain", host_parts.slice(-domain_parts.length).join('.'), domain_parts.filter(Boolean).join('.'), isValid);
213
+ return isValid;
203
214
  };
204
215
  // Note: updated this method to test on staging (Ref:: https://github.com/PostHog/posthog-js/blob/master/src/storage.ts#L42)
205
216
  // Commented out some jitsu cookies setters that are not bring used in posthog-js
206
217
  function serializeCookie(name, val, opt) {
207
218
  if (opt === void 0) { opt = {}; }
208
219
  try {
209
- var maxAge = opt.maxAge, domain = opt.domain, path = opt.path, expires = opt.expires, httpOnly = opt.httpOnly, secure = opt.secure, sameSite = opt.sameSite, crossSubdomain = opt.crossSubdomain;
220
+ var maxAge = opt.maxAge, domain = opt.domain, path = opt.path, expires = opt.expires, httpOnly = opt.httpOnly, secure = opt.secure, sameSite = opt.sameSite;
210
221
  var new_cookie_val = "".concat(name, "=").concat(encodeURIComponent(val));
211
- if (crossSubdomain) {
212
- var cross_subdomain = getCrossSubdomain();
213
- new_cookie_val += "; domain=".concat(cross_subdomain);
214
- }
215
- else if (domain) {
216
- new_cookie_val += "; domain=".concat(domain);
222
+ if (domain) {
223
+ // https://stackoverflow.com/a/23086139/9783690
224
+ // We will be getting the domain in params as .domain.com, .localhost, etc in all cases,
225
+ // so we need to remove the leading dot before setting the cookie and also check if it is a valid domain
226
+ // for setting cross domain cookies
227
+ var isValid = isValidCrossDomain(domain);
228
+ if (isValid) {
229
+ // Remove the leading dot
230
+ new_cookie_val += "; domain=".concat(domain.replace(/^\./, ''));
231
+ }
217
232
  }
218
233
  if (path) {
219
234
  new_cookie_val += "; path=".concat(path);
@@ -224,21 +239,38 @@ function serializeCookie(name, val, opt) {
224
239
  if (expires) {
225
240
  new_cookie_val += "; expires=".concat(expires.toUTCString());
226
241
  }
227
- // if (maxAge) {
228
- // new_cookie_val += `; max-age=${maxAge}`
229
- // }
230
- // if (httpOnly) {
231
- // new_cookie_val += `; httponly`
232
- // }
242
+ if (maxAge) {
243
+ new_cookie_val += "; max-age=".concat(maxAge);
244
+ }
245
+ if (httpOnly) {
246
+ new_cookie_val += "; httponly";
247
+ }
233
248
  if (secure) {
234
249
  new_cookie_val += "; secure";
235
250
  }
236
- // if (sameSite) {
237
- // new_cookie_val += `; samesite=${sameSite}`
238
- // }
251
+ if (sameSite) {
252
+ var sameSiteAttr = typeof sameSite === "string"
253
+ ? sameSite.toLowerCase()
254
+ : sameSite;
255
+ switch (sameSiteAttr) {
256
+ case true:
257
+ new_cookie_val += "; SameSite=Strict";
258
+ break;
259
+ case "lax":
260
+ new_cookie_val += "; SameSite=Lax";
261
+ break;
262
+ case "strict":
263
+ new_cookie_val += "; SameSite=Strict";
264
+ break;
265
+ case "none":
266
+ new_cookie_val += "; SameSite=None";
267
+ break;
268
+ }
269
+ }
239
270
  return new_cookie_val;
240
271
  }
241
272
  catch (e) {
273
+ getLogger().error("serializeCookie", e);
242
274
  return '';
243
275
  }
244
276
  }
@@ -346,7 +378,9 @@ var getCookie = function (name) {
346
378
  }
347
379
  }
348
380
  }
349
- catch (err) { }
381
+ catch (err) {
382
+ getLogger().error("getCookies", err);
383
+ }
350
384
  return null;
351
385
  };
352
386
  var setCookie = function (name, value, opts) {
@@ -426,7 +460,7 @@ var getHostWithProtocol = function (host) {
426
460
  return host;
427
461
  }
428
462
  else {
429
- return "//" + host;
463
+ return "https://" + host;
430
464
  }
431
465
  };
432
466
 
@@ -812,6 +846,10 @@ function shouldCaptureDomEvent(el, event) {
812
846
  if (!el || isTag(el, 'html') || !isElementNode(el)) {
813
847
  return false;
814
848
  }
849
+ // allow users to programmatically prevent capturing of elements by adding class 'um-no-capture'
850
+ if (el.classList && el.classList.contains('um-no-capture')) {
851
+ return false;
852
+ }
815
853
  var parentIsUsefulElement = false;
816
854
  var targetElementList = [el]; // TODO: remove this var, it's never queried
817
855
  var parentNode = true;
@@ -1323,8 +1361,8 @@ _safewrap_instance_methods(autocapture);
1323
1361
 
1324
1362
  var VERSION_INFO = {
1325
1363
  env: 'production',
1326
- date: '2023-02-27T12:00:34.428Z',
1327
- version: '1.1.7'
1364
+ date: '2023-04-06T09:40:37.087Z',
1365
+ version: '1.2.0'
1328
1366
  };
1329
1367
  var USERMAVEN_VERSION = "".concat(VERSION_INFO.version, "/").concat(VERSION_INFO.env, "@").concat(VERSION_INFO.date);
1330
1368
  var MAX_AGE_TEN_YEARS = 31622400 * 10;
@@ -1621,7 +1659,7 @@ var xmlHttpTransport = function (url, jsonPayload, additionalHeaders, handler) {
1621
1659
  var req = new window.XMLHttpRequest();
1622
1660
  return new Promise(function (resolve, reject) {
1623
1661
  req.onerror = function (e) {
1624
- getLogger().error("Failed to send", jsonPayload, e);
1662
+ getLogger().error("Failed to send payload to ".concat(url, ": ").concat((e === null || e === void 0 ? void 0 : e.message) || "unknown error"), jsonPayload, e);
1625
1663
  handler(-1, {});
1626
1664
  reject(new Error("Failed to send JSON. See console logs"));
1627
1665
  };
@@ -1667,7 +1705,7 @@ var fetchTransport = function (fetch) {
1667
1705
  return [3 /*break*/, 3];
1668
1706
  case 2:
1669
1707
  e_1 = _c.sent();
1670
- getLogger().error("Failed to send", jsonPayload, e_1);
1708
+ getLogger().error("Failed to send data to ".concat(url, ": ").concat((e_1 === null || e_1 === void 0 ? void 0 : e_1.message) || "unknown error"), jsonPayload, e_1);
1671
1709
  handler(-1, {});
1672
1710
  return [2 /*return*/];
1673
1711
  case 3:
@@ -1707,6 +1745,7 @@ var fetchTransport = function (fetch) {
1707
1745
  var UsermavenClientImpl = /** @class */ (function () {
1708
1746
  function UsermavenClientImpl() {
1709
1747
  this.userProperties = {};
1748
+ this.groupProperties = {};
1710
1749
  this.permanentProperties = {
1711
1750
  globalProps: {},
1712
1751
  propsPerEvent: {},
@@ -1732,8 +1771,10 @@ var UsermavenClientImpl = /** @class */ (function () {
1732
1771
  // public persistence?: UserMavenPersistence;
1733
1772
  // public sessionManager?: SessionIdManager;
1734
1773
  this.__autocapture_enabled = false;
1774
+ // private anonymousId: string = '';
1775
+ // Fallback tracking host
1776
+ this.trackingHostFallback = "https://events.usermaven.com" ;
1735
1777
  }
1736
- // private anonymousId: string = '';
1737
1778
  // Used for session + autocapture
1738
1779
  UsermavenClientImpl.prototype.get_config = function (prop_name) {
1739
1780
  return this.config ? this.config[prop_name] : null;
@@ -1754,6 +1795,42 @@ var UsermavenClientImpl = /** @class */ (function () {
1754
1795
  return Promise.resolve();
1755
1796
  }
1756
1797
  };
1798
+ UsermavenClientImpl.prototype.group = function (props, doNotSendEvent) {
1799
+ this.groupProperties = __assign(__assign({}, this.groupProperties), props);
1800
+ getLogger().debug("Usermaven group identified", props);
1801
+ if (this.userIdPersistence) {
1802
+ // Update the 'company' property in the user persistence
1803
+ this.userIdPersistence.save({ company: props });
1804
+ }
1805
+ else {
1806
+ getLogger().warn("Group() is called before initialization");
1807
+ }
1808
+ if (!doNotSendEvent) {
1809
+ return this.track("group", {});
1810
+ }
1811
+ else {
1812
+ return Promise.resolve();
1813
+ }
1814
+ };
1815
+ UsermavenClientImpl.prototype.reset = function (resetAnonId) {
1816
+ if (this.userIdPersistence) {
1817
+ this.userIdPersistence.delete();
1818
+ }
1819
+ if (this.propsPersistance) {
1820
+ this.propsPersistance.delete();
1821
+ }
1822
+ if (resetAnonId) {
1823
+ var idCookie = getCookie(this.idCookieName);
1824
+ if (idCookie) {
1825
+ getLogger().debug("Removing id cookie", idCookie);
1826
+ setCookie(this.idCookieName, "", {
1827
+ domain: this.cookieDomain,
1828
+ expires: new Date(0),
1829
+ });
1830
+ }
1831
+ }
1832
+ return Promise.resolve();
1833
+ };
1757
1834
  UsermavenClientImpl.prototype.rawTrack = function (payload) {
1758
1835
  return this.sendJson(payload);
1759
1836
  };
@@ -1859,6 +1936,11 @@ var UsermavenClientImpl = /** @class */ (function () {
1859
1936
  return [3 /*break*/, 4];
1860
1937
  case 3:
1861
1938
  _b.sent();
1939
+ // In case of failing custom domain (trackingHost), we will replace it with default domain (trackingHostFallback)
1940
+ if (this.trackingHost !== this.trackingHostFallback) {
1941
+ getLogger().debug("Using fallback tracking host ".concat(this.trackingHostFallback, " instead of ").concat(this.trackingHost, " on ").concat(VERSION_INFO.env));
1942
+ this.trackingHost = this.trackingHostFallback;
1943
+ }
1862
1944
  queue = queue.map(function (el) { return [el[0], el[1] + 1]; }).filter(function (el) {
1863
1945
  if (el[1] >= _this.maxSendAttempts) {
1864
1946
  getLogger().error("Dropping queued event after ".concat(el[1], " attempts since max send attempts ").concat(_this.maxSendAttempts, " reached. See logs for details"));
@@ -1924,14 +2006,15 @@ var UsermavenClientImpl = /** @class */ (function () {
1924
2006
  UsermavenClientImpl.prototype.getCtx = function (env) {
1925
2007
  var now = new Date();
1926
2008
  var props = env.describeClient() || {};
1927
- var company = this.userProperties['company'] || {};
1928
- delete this.userProperties['company'];
2009
+ var user = __assign({}, this.userProperties);
2010
+ var company = user['company'] || {};
2011
+ delete user['company'];
1929
2012
  var payload = __assign(__assign({ event_id: "", user: __assign({ anonymous_id: this.cookiePolicy !== "strict"
1930
2013
  ? env.getAnonymousId({
1931
2014
  name: this.idCookieName,
1932
2015
  domain: this.cookieDomain,
1933
2016
  })
1934
- : "" }, this.userProperties), ids: this._getIds(), utc_time: reformatDate(now.toISOString()), local_tz_offset: now.getTimezoneOffset() }, props), getDataFromParams(parseQuery(props.doc_search)));
2017
+ : "" }, user), ids: this._getIds(), utc_time: reformatDate(now.toISOString()), local_tz_offset: now.getTimezoneOffset() }, props), getDataFromParams(parseQuery(props.doc_search)));
1935
2018
  // id and name attributes will be checked on backend
1936
2019
  if (Object.keys(company).length) {
1937
2020
  payload['company'] = company;
@@ -2043,8 +2126,8 @@ var UsermavenClientImpl = /** @class */ (function () {
2043
2126
  this.cookieDomain = options.cookie_domain || getCookieDomain();
2044
2127
  this.trackingHost = getHostWithProtocol(options["tracking_host"] || "t.usermaven.com");
2045
2128
  this.randomizeUrl = options.randomize_url || false;
2046
- this.idCookieName = options.cookie_name || "__eventn_id";
2047
2129
  this.apiKey = options.key;
2130
+ this.idCookieName = options.cookie_name || "__eventn_id_".concat(options.key);
2048
2131
  if (this.cookiePolicy === "strict") {
2049
2132
  this.propsPersistance = new NoPersistence();
2050
2133
  }
@@ -145,7 +145,7 @@ export type UsermavenOptions = {
145
145
  tracking_host?: string
146
146
 
147
147
  /**
148
- * Name of id cookie. __eventn_id by default
148
+ * Name of id cookie. __eventn_id_{data-key} by default
149
149
  */
150
150
  cookie_name?: string
151
151
  /**
@@ -306,6 +306,7 @@ export interface UserProps {
306
306
  company?: CompanyProps
307
307
  }
308
308
 
309
+
309
310
  /**
310
311
  * Ids for third-party tracking systems
311
312
  */
@@ -172,7 +172,10 @@ function createLogger(logLevel) {
172
172
  */
173
173
 
174
174
  function isWindowAvailable(warnMsg = undefined) {
175
- let windowAvailable = !!globalThis.window;
175
+ //here we check not only of window object is globally available, but also if it's not a fake one
176
+ //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
177
+ const windowAvailable = !!globalThis.window && !!globalThis.window.document && !!globalThis.window.location;
178
+
176
179
  if (!windowAvailable && warnMsg) {
177
180
  getLogger().warn(warnMsg);
178
181
  }
@@ -191,25 +194,37 @@ function requireWindow(msg = undefined) {
191
194
  return window;
192
195
  }
193
196
 
194
- var DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i;
195
- var getCrossSubdomain = function () {
196
- var matches = document.location.hostname.match(DOMAIN_MATCH_REGEX);
197
- var domain = matches ? matches[0] : '';
198
- return domain ? ".".concat(domain) : '';
197
+ /**
198
+ * Checks if the domain is valid for setting cross domain cookies
199
+ * To check we will use Domain Matching technique as mentioned in RFC 6265 - https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3
200
+ * @param domain
201
+ */
202
+ var isValidCrossDomain = function (domain) {
203
+ var domain_parts = domain.split('.'); // .domain.com => ['', 'domain', 'com']
204
+ var host_parts = window.location.hostname.split('.'); // stage.domain.com => ['stage', 'domain', 'com']
205
+ // Check if the domain is a subdomain of the current host
206
+ // If yes, then it is a valid domain for setting cross domain cookies
207
+ var isValid = host_parts.length > domain_parts.length && host_parts.slice(-domain_parts.length).join('.') === domain_parts.filter(Boolean).join('.');
208
+ getLogger().debug("isValidCrossDomain", host_parts.slice(-domain_parts.length).join('.'), domain_parts.filter(Boolean).join('.'), isValid);
209
+ return isValid;
199
210
  };
200
211
  // Note: updated this method to test on staging (Ref:: https://github.com/PostHog/posthog-js/blob/master/src/storage.ts#L42)
201
212
  // Commented out some jitsu cookies setters that are not bring used in posthog-js
202
213
  function serializeCookie(name, val, opt) {
203
214
  if (opt === void 0) { opt = {}; }
204
215
  try {
205
- var maxAge = opt.maxAge, domain = opt.domain, path = opt.path, expires = opt.expires, httpOnly = opt.httpOnly, secure = opt.secure, sameSite = opt.sameSite, crossSubdomain = opt.crossSubdomain;
216
+ var maxAge = opt.maxAge, domain = opt.domain, path = opt.path, expires = opt.expires, httpOnly = opt.httpOnly, secure = opt.secure, sameSite = opt.sameSite;
206
217
  var new_cookie_val = "".concat(name, "=").concat(encodeURIComponent(val));
207
- if (crossSubdomain) {
208
- var cross_subdomain = getCrossSubdomain();
209
- new_cookie_val += "; domain=".concat(cross_subdomain);
210
- }
211
- else if (domain) {
212
- new_cookie_val += "; domain=".concat(domain);
218
+ if (domain) {
219
+ // https://stackoverflow.com/a/23086139/9783690
220
+ // We will be getting the domain in params as .domain.com, .localhost, etc in all cases,
221
+ // so we need to remove the leading dot before setting the cookie and also check if it is a valid domain
222
+ // for setting cross domain cookies
223
+ var isValid = isValidCrossDomain(domain);
224
+ if (isValid) {
225
+ // Remove the leading dot
226
+ new_cookie_val += "; domain=".concat(domain.replace(/^\./, ''));
227
+ }
213
228
  }
214
229
  if (path) {
215
230
  new_cookie_val += "; path=".concat(path);
@@ -220,21 +235,38 @@ function serializeCookie(name, val, opt) {
220
235
  if (expires) {
221
236
  new_cookie_val += "; expires=".concat(expires.toUTCString());
222
237
  }
223
- // if (maxAge) {
224
- // new_cookie_val += `; max-age=${maxAge}`
225
- // }
226
- // if (httpOnly) {
227
- // new_cookie_val += `; httponly`
228
- // }
238
+ if (maxAge) {
239
+ new_cookie_val += "; max-age=".concat(maxAge);
240
+ }
241
+ if (httpOnly) {
242
+ new_cookie_val += "; httponly";
243
+ }
229
244
  if (secure) {
230
245
  new_cookie_val += "; secure";
231
246
  }
232
- // if (sameSite) {
233
- // new_cookie_val += `; samesite=${sameSite}`
234
- // }
247
+ if (sameSite) {
248
+ var sameSiteAttr = typeof sameSite === "string"
249
+ ? sameSite.toLowerCase()
250
+ : sameSite;
251
+ switch (sameSiteAttr) {
252
+ case true:
253
+ new_cookie_val += "; SameSite=Strict";
254
+ break;
255
+ case "lax":
256
+ new_cookie_val += "; SameSite=Lax";
257
+ break;
258
+ case "strict":
259
+ new_cookie_val += "; SameSite=Strict";
260
+ break;
261
+ case "none":
262
+ new_cookie_val += "; SameSite=None";
263
+ break;
264
+ }
265
+ }
235
266
  return new_cookie_val;
236
267
  }
237
268
  catch (e) {
269
+ getLogger().error("serializeCookie", e);
238
270
  return '';
239
271
  }
240
272
  }
@@ -342,7 +374,9 @@ var getCookie = function (name) {
342
374
  }
343
375
  }
344
376
  }
345
- catch (err) { }
377
+ catch (err) {
378
+ getLogger().error("getCookies", err);
379
+ }
346
380
  return null;
347
381
  };
348
382
  var setCookie = function (name, value, opts) {
@@ -422,7 +456,7 @@ var getHostWithProtocol = function (host) {
422
456
  return host;
423
457
  }
424
458
  else {
425
- return "//" + host;
459
+ return "https://" + host;
426
460
  }
427
461
  };
428
462
 
@@ -808,6 +842,10 @@ function shouldCaptureDomEvent(el, event) {
808
842
  if (!el || isTag(el, 'html') || !isElementNode(el)) {
809
843
  return false;
810
844
  }
845
+ // allow users to programmatically prevent capturing of elements by adding class 'um-no-capture'
846
+ if (el.classList && el.classList.contains('um-no-capture')) {
847
+ return false;
848
+ }
811
849
  var parentIsUsefulElement = false;
812
850
  var targetElementList = [el]; // TODO: remove this var, it's never queried
813
851
  var parentNode = true;
@@ -1319,8 +1357,8 @@ _safewrap_instance_methods(autocapture);
1319
1357
 
1320
1358
  var VERSION_INFO = {
1321
1359
  env: 'production',
1322
- date: '2023-02-27T12:00:34.428Z',
1323
- version: '1.1.7'
1360
+ date: '2023-04-06T09:40:37.087Z',
1361
+ version: '1.2.0'
1324
1362
  };
1325
1363
  var USERMAVEN_VERSION = "".concat(VERSION_INFO.version, "/").concat(VERSION_INFO.env, "@").concat(VERSION_INFO.date);
1326
1364
  var MAX_AGE_TEN_YEARS = 31622400 * 10;
@@ -1617,7 +1655,7 @@ var xmlHttpTransport = function (url, jsonPayload, additionalHeaders, handler) {
1617
1655
  var req = new window.XMLHttpRequest();
1618
1656
  return new Promise(function (resolve, reject) {
1619
1657
  req.onerror = function (e) {
1620
- getLogger().error("Failed to send", jsonPayload, e);
1658
+ getLogger().error("Failed to send payload to ".concat(url, ": ").concat((e === null || e === void 0 ? void 0 : e.message) || "unknown error"), jsonPayload, e);
1621
1659
  handler(-1, {});
1622
1660
  reject(new Error("Failed to send JSON. See console logs"));
1623
1661
  };
@@ -1663,7 +1701,7 @@ var fetchTransport = function (fetch) {
1663
1701
  return [3 /*break*/, 3];
1664
1702
  case 2:
1665
1703
  e_1 = _c.sent();
1666
- getLogger().error("Failed to send", jsonPayload, e_1);
1704
+ getLogger().error("Failed to send data to ".concat(url, ": ").concat((e_1 === null || e_1 === void 0 ? void 0 : e_1.message) || "unknown error"), jsonPayload, e_1);
1667
1705
  handler(-1, {});
1668
1706
  return [2 /*return*/];
1669
1707
  case 3:
@@ -1703,6 +1741,7 @@ var fetchTransport = function (fetch) {
1703
1741
  var UsermavenClientImpl = /** @class */ (function () {
1704
1742
  function UsermavenClientImpl() {
1705
1743
  this.userProperties = {};
1744
+ this.groupProperties = {};
1706
1745
  this.permanentProperties = {
1707
1746
  globalProps: {},
1708
1747
  propsPerEvent: {},
@@ -1728,8 +1767,10 @@ var UsermavenClientImpl = /** @class */ (function () {
1728
1767
  // public persistence?: UserMavenPersistence;
1729
1768
  // public sessionManager?: SessionIdManager;
1730
1769
  this.__autocapture_enabled = false;
1770
+ // private anonymousId: string = '';
1771
+ // Fallback tracking host
1772
+ this.trackingHostFallback = "https://events.usermaven.com" ;
1731
1773
  }
1732
- // private anonymousId: string = '';
1733
1774
  // Used for session + autocapture
1734
1775
  UsermavenClientImpl.prototype.get_config = function (prop_name) {
1735
1776
  return this.config ? this.config[prop_name] : null;
@@ -1750,6 +1791,42 @@ var UsermavenClientImpl = /** @class */ (function () {
1750
1791
  return Promise.resolve();
1751
1792
  }
1752
1793
  };
1794
+ UsermavenClientImpl.prototype.group = function (props, doNotSendEvent) {
1795
+ this.groupProperties = __assign(__assign({}, this.groupProperties), props);
1796
+ getLogger().debug("Usermaven group identified", props);
1797
+ if (this.userIdPersistence) {
1798
+ // Update the 'company' property in the user persistence
1799
+ this.userIdPersistence.save({ company: props });
1800
+ }
1801
+ else {
1802
+ getLogger().warn("Group() is called before initialization");
1803
+ }
1804
+ if (!doNotSendEvent) {
1805
+ return this.track("group", {});
1806
+ }
1807
+ else {
1808
+ return Promise.resolve();
1809
+ }
1810
+ };
1811
+ UsermavenClientImpl.prototype.reset = function (resetAnonId) {
1812
+ if (this.userIdPersistence) {
1813
+ this.userIdPersistence.delete();
1814
+ }
1815
+ if (this.propsPersistance) {
1816
+ this.propsPersistance.delete();
1817
+ }
1818
+ if (resetAnonId) {
1819
+ var idCookie = getCookie(this.idCookieName);
1820
+ if (idCookie) {
1821
+ getLogger().debug("Removing id cookie", idCookie);
1822
+ setCookie(this.idCookieName, "", {
1823
+ domain: this.cookieDomain,
1824
+ expires: new Date(0),
1825
+ });
1826
+ }
1827
+ }
1828
+ return Promise.resolve();
1829
+ };
1753
1830
  UsermavenClientImpl.prototype.rawTrack = function (payload) {
1754
1831
  return this.sendJson(payload);
1755
1832
  };
@@ -1855,6 +1932,11 @@ var UsermavenClientImpl = /** @class */ (function () {
1855
1932
  return [3 /*break*/, 4];
1856
1933
  case 3:
1857
1934
  _b.sent();
1935
+ // In case of failing custom domain (trackingHost), we will replace it with default domain (trackingHostFallback)
1936
+ if (this.trackingHost !== this.trackingHostFallback) {
1937
+ getLogger().debug("Using fallback tracking host ".concat(this.trackingHostFallback, " instead of ").concat(this.trackingHost, " on ").concat(VERSION_INFO.env));
1938
+ this.trackingHost = this.trackingHostFallback;
1939
+ }
1858
1940
  queue = queue.map(function (el) { return [el[0], el[1] + 1]; }).filter(function (el) {
1859
1941
  if (el[1] >= _this.maxSendAttempts) {
1860
1942
  getLogger().error("Dropping queued event after ".concat(el[1], " attempts since max send attempts ").concat(_this.maxSendAttempts, " reached. See logs for details"));
@@ -1920,14 +2002,15 @@ var UsermavenClientImpl = /** @class */ (function () {
1920
2002
  UsermavenClientImpl.prototype.getCtx = function (env) {
1921
2003
  var now = new Date();
1922
2004
  var props = env.describeClient() || {};
1923
- var company = this.userProperties['company'] || {};
1924
- delete this.userProperties['company'];
2005
+ var user = __assign({}, this.userProperties);
2006
+ var company = user['company'] || {};
2007
+ delete user['company'];
1925
2008
  var payload = __assign(__assign({ event_id: "", user: __assign({ anonymous_id: this.cookiePolicy !== "strict"
1926
2009
  ? env.getAnonymousId({
1927
2010
  name: this.idCookieName,
1928
2011
  domain: this.cookieDomain,
1929
2012
  })
1930
- : "" }, this.userProperties), ids: this._getIds(), utc_time: reformatDate(now.toISOString()), local_tz_offset: now.getTimezoneOffset() }, props), getDataFromParams(parseQuery(props.doc_search)));
2013
+ : "" }, user), ids: this._getIds(), utc_time: reformatDate(now.toISOString()), local_tz_offset: now.getTimezoneOffset() }, props), getDataFromParams(parseQuery(props.doc_search)));
1931
2014
  // id and name attributes will be checked on backend
1932
2015
  if (Object.keys(company).length) {
1933
2016
  payload['company'] = company;
@@ -2039,8 +2122,8 @@ var UsermavenClientImpl = /** @class */ (function () {
2039
2122
  this.cookieDomain = options.cookie_domain || getCookieDomain();
2040
2123
  this.trackingHost = getHostWithProtocol(options["tracking_host"] || "t.usermaven.com");
2041
2124
  this.randomizeUrl = options.randomize_url || false;
2042
- this.idCookieName = options.cookie_name || "__eventn_id";
2043
2125
  this.apiKey = options.key;
2126
+ this.idCookieName = options.cookie_name || "__eventn_id_".concat(options.key);
2044
2127
  if (this.cookiePolicy === "strict") {
2045
2128
  this.propsPersistance = new NoPersistence();
2046
2129
  }
package/dist/web/lib.js CHANGED
@@ -1 +1 @@
1
- !function(){"use strict";var e=function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},e.apply(this,arguments)};function t(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))}function n(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){s.label=o[1];break}if(6===o[0]&&s.label<i[1]){s.label=i[1],i=o;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(o);break}i[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,a])}}}function r(e,t,n){if(n||2===arguments.length)for(var r,i=0,o=t.length;i<o;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}function i(e){let t=!!globalThis.window;return!t&&e&&c().warn(e),t}function o(e){if(!i())throw new Error(e||"window' is not available. Seems like this code runs outside browser environment. It shouldn't happen");return window}var s={DEBUG:{name:"DEBUG",severity:10},INFO:{name:"INFO",severity:100},WARN:{name:"WARN",severity:1e3},ERROR:{name:"ERROR",severity:1e4},NONE:{name:"NONE",severity:1e4}},a=null;function c(){return a||(a=u())}function u(e){var t=i()&&window.__eventNLogLevel,n=s.WARN;if(t){var o=s[t.toUpperCase()];o&&o>0&&(n=o)}else e&&(n=e);var a={minLogLevel:n};return Object.values(s).forEach((function(e){var t=e.name,i=e.severity;a[t.toLowerCase()]=function(){for(var e=[],o=0;o<arguments.length;o++)e[o]=arguments[o];if(i>=n.severity&&e.length>0){var s=e[0],a=e.splice(1),c="[J-".concat(t,"] ").concat(s);"DEBUG"===t||"INFO"===t?console.log.apply(console,r([c],a,!1)):"WARN"===t?console.warn.apply(console,r([c],a,!1)):console.error.apply(console,r([c],a,!1))}}})),function(e,t){if(i()){var n=window;n.__usermavenDebug||(n.__usermavenDebug={}),n.__usermavenDebug[e]=t}}("logger",a),a}var l=/[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i;function p(e,t,n){void 0===n&&(n={});try{n.maxAge;var r=n.domain,i=n.path,o=n.expires,s=(n.httpOnly,n.secure),a=(n.sameSite,n.crossSubdomain),c="".concat(e,"=").concat(encodeURIComponent(t));if(a){var u=function(){var e=document.location.hostname.match(l),t=e?e[0]:"";return t?".".concat(t):""}();c+="; domain=".concat(u)}else r&&(c+="; domain=".concat(r));return c+=i?"; path=".concat(i):"; path=/",o&&(c+="; expires=".concat(o.toUTCString())),s&&(c+="; secure"),c}catch(e){return""}}var d;function h(e){if(!e)return{};for(var t={},n=e.split(";"),r=0;r<n.length;r++){var i=n[r],o=i.indexOf("=");o>0&&(t[i.substr(r>0?1:0,r>0?o-1:o)]=i.substr(o+1))}return t}function f(e,t){return Array.from(e.attributes).forEach((function(e){t.setAttribute(e.nodeName,e.nodeValue)}))}function m(e,t){e.innerHTML=t;var n,r=e.getElementsByTagName("script");for(n=r.length-1;n>=0;n--){var i=r[n],o=document.createElement("script");f(i,o),i.innerHTML&&(o.innerHTML=i.innerHTML),o.setAttribute("data-usermaven-tag-id",e.id),document.getElementsByTagName("head")[0].appendChild(o),r[n].parentNode.removeChild(r[n])}}var v=function(e){if(!e)return null;try{for(var t=e+"=",n=o().document.cookie.split(";"),r=0;r<n.length;r++){for(var i=n[r];" "==i.charAt(0);)i=i.substring(1,i.length);if(0===i.indexOf(t))return decodeURIComponent(i.substring(t.length,i.length))}}catch(e){}return null},g=function(e,t,n){void 0===n&&(n={}),o().document.cookie=p(e,t,n)},y=function(e,t){void 0===t&&(t="/"),document.cookie=e+"= ; expires = Thu, 01 Jan 1970 00:00:00 GMT"+(t?"; path = "+t:"")},_=function(){return Math.random().toString(36).substring(2,12)},b=function(){return Math.random().toString(36).substring(2,7)},w={utm_source:"source",utm_medium:"medium",utm_campaign:"campaign",utm_term:"term",utm_content:"content"},k={gclid:!0,fbclid:!0,dclid:!0};var P=function(){function e(){this.queue=[]}return e.prototype.flush=function(){var e=this.queue;return this.queue=[],e},e.prototype.push=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];(e=this.queue).push.apply(e,t)},e}(),x=function(){function e(e){this.key=e}return e.prototype.flush=function(){var e=this.get();return e.length&&this.set([]),e},e.prototype.push=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=this.get();n.push.apply(n,e),this.set(n)},e.prototype.set=function(e){localStorage.setItem(this.key,JSON.stringify(e))},e.prototype.get=function(){var e=localStorage.getItem(this.key);return null!==e&&""!==e?JSON.parse(e):[]},e}(),S=Object.prototype,N=S.toString,E=S.hasOwnProperty,A=Array.prototype.forEach,C=Array.isArray,O={},T=C||function(e){return"[object Array]"===N.call(e)};function I(e,t,n){if(Array.isArray(e))if(A&&e.forEach===A)e.forEach(t,n);else if("length"in e&&e.length===+e.length)for(var r=0,i=e.length;r<i;r++)if(r in e&&t.call(n,e[r],r)===O)return}var j=function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")};function D(e,t,n){if(null!=e)if(A&&Array.isArray(e)&&e.forEach===A)e.forEach(t,n);else if("length"in e&&e.length===+e.length){for(var r=0,i=e.length;r<i;r++)if(r in e&&t.call(n,e[r],r)===O)return}else for(var o in e)if(E.call(e,o)&&t.call(n,e[o],o)===O)return}var H=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];return I(t,(function(t){for(var n in t)void 0!==t[n]&&(e[n]=t[n])})),e};function $(e,t){return-1!==e.indexOf(t)}var F=function(e){try{return/^\s*\bfunction\b/.test(e)}catch(e){return!1}},M=function(e){return void 0===e},U=function(){function e(t){return t&&(t.preventDefault=e.preventDefault,t.stopPropagation=e.stopPropagation),t}return e.preventDefault=function(){this.returnValue=!1},e.stopPropagation=function(){this.cancelBubble=!0},function(t,n,r,i,o){if(t)if(t.addEventListener&&!i)t.addEventListener(n,r,!!o);else{var s="on"+n,a=t[s];t[s]=function(t,n,r){return function(i){if(i=i||e(window.event)){var o,s=!0;F(r)&&(o=r(i));var a=n.call(t,i);return!1!==o&&!1!==a||(s=!1),s}}}(t,r,a)}else c().error("No valid element provided to register_event")}}(),z=function(e){return function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];try{return e.apply(this,t)}catch(e){c().error("Implementation error. Please turn on debug and contact support@usermaven.com.",e)}}},L="undefined"!=typeof Symbol?Symbol("__deepCircularCopyInProgress__"):"__deepCircularCopyInProgress__";function q(e,t,n){return e!==Object(e)?t?t(e,n):e:e[L]?void 0:(e[L]=!0,T(e)?(r=[],I(e,(function(e){r.push(q(e,t))}))):(r={},D(e,(function(e,n){n!==L&&(r[n]=q(e,t,n))}))),delete e[L],r);var r}var J=["$performance_raw"];function R(e,t){return q(e,(function(e,n){return n&&J.indexOf(n)>-1?e:"string"==typeof e&&null!==t?e.slice(0,t):e}))}function B(e){switch(typeof e.className){case"string":return e.className;case"object":return("baseVal"in e.className?e.className.baseVal:null)||e.getAttribute("class")||"";default:return""}}function V(e){var t="";return X(e)&&!Z(e)&&e.childNodes&&e.childNodes.length&&D(e.childNodes,(function(e){Q(e)&&e.textContent&&(t+=j(e.textContent).split(/(\s+)/).filter(ee).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))})),j(t)}function W(e){return!!e&&1===e.nodeType}function K(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function Q(e){return!!e&&3===e.nodeType}function G(e){return!!e&&11===e.nodeType}var Y=["a","button","form","input","select","textarea","label"];function X(e){for(var t=e;t.parentNode&&!K(t,"body");t=t.parentNode){var n=B(t).split(" ");if($(n,"ph-sensitive")||$(n,"ph-no-capture"))return!1}if($(B(e).split(" "),"ph-include"))return!0;var r=e.type||"";if("string"==typeof r)switch(r.toLowerCase()){case"hidden":case"password":return!1}var i=e.name||e.id||"";if("string"==typeof i){if(/^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,"")))return!1}return!0}function Z(e){return!!(K(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||K(e,"select")||K(e,"textarea")||"true"===e.getAttribute("contenteditable"))}function ee(e){if(null===e||M(e))return!1;if("string"==typeof e){e=j(e);if(/^(?:(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,"")))return!1;if(/(^\d{3}-?\d{2}-?\d{4}$)/.test(e))return!1}return!0}var te=function(){function e(e,t){void 0===t&&(t=!1),this.clicks=[],this.instance=e,this.enabled=t}return e.prototype.click=function(e,t,n){if(this.enabled){var r=this.clicks[this.clicks.length-1];r&&Math.abs(e-r.x)+Math.abs(t-r.y)<30&&n-r.timestamp<1e3?(this.clicks.push({x:e,y:t,timestamp:n}),3===this.clicks.length&&this.instance.capture("$rageclick")):this.clicks=[{x:e,y:t,timestamp:n}]}},e}(),ne=function(){function e(e){this.instance=e,this.lastScrollDepth=0,this.canSend=!0,this.documentElement=document.documentElement}return e.prototype.track=function(){var e=this.getScrollDepth();e>this.lastScrollDepth&&(this.lastScrollDepth=e,this.canSend=!0)},e.prototype.send=function(e){if(void 0===e&&(e="$scroll"),this.canSend){var t={percent:this.lastScrollDepth,window_height:this.getWindowHeight(),document_height:this.getDocumentHeight(),scroll_distance:this.getScrollDistance()};this.instance.capture(e,t),this.canSend=!1}},e.prototype.getScrollDepth=function(){try{var e=this.getWindowHeight(),t=this.getDocumentHeight(),n=this.getScrollDistance(),r=t-e;return Math.min(100,Math.floor(n/r*100))}catch(e){return 0}},e.prototype.getWindowHeight=function(){try{return window.innerHeight||this.documentElement.clientHeight||document.body.clientHeight||0}catch(e){return 0}},e.prototype.getDocumentHeight=function(){try{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)}catch(e){return 0}},e.prototype.getScrollDistance=function(){try{return window.scrollY||window.pageYOffset||document.body.scrollTop||this.documentElement.scrollTop||0}catch(e){return 0}},e}(),re={_initializedTokens:[],_previousElementSibling:function(e){if(e.previousElementSibling)return e.previousElementSibling;var t=e;do{t=t.previousSibling}while(t&&!W(t));return t},_getPropertiesFromElement:function(e,t,n){var r=e.tagName.toLowerCase(),i={tag_name:r};Y.indexOf(r)>-1&&!n&&(i.$el_text=V(e));var o=B(e);o.length>0&&(i.classes=o.split(" ").filter((function(e){return""!==e}))),D(e.attributes,(function(n){var r;Z(e)&&-1===["name","id","class"].indexOf(n.name)||!t&&ee(n.value)&&("string"!=typeof(r=n.name)||"_ngcontent"!==r.substring(0,10)&&"_nghost"!==r.substring(0,7))&&(i["attr__"+n.name]=n.value)}));for(var s=1,a=1,c=e;c=this._previousElementSibling(c);)s++,c.tagName===e.tagName&&a++;return i.nth_child=s,i.nth_of_type=a,i},_getDefaultProperties:function(e){return{$event_type:e,$ce_version:1}},_extractCustomPropertyValue:function(e){var t=[];return D(document.querySelectorAll(e.css_selector),(function(e){var n;["input","select"].indexOf(e.tagName.toLowerCase())>-1?n=e.value:e.textContent&&(n=e.textContent),ee(n)&&t.push(n)})),t.join(", ")},_getCustomProperties:function(e){var t=this,n={};return D(this._customProperties,(function(r){D(r.event_selectors,(function(i){D(document.querySelectorAll(i),(function(i){$(e,i)&&X(i)&&(n[r.name]=t._extractCustomPropertyValue(r))}))}))})),n},_getEventTarget:function(e){var t;return void 0===e.target?e.srcElement||null:(null===(t=e.target)||void 0===t?void 0:t.shadowRoot)?e.composedPath()[0]||null:e.target||null},_captureEvent:function(e,t,n){var r,i=this,o=this._getEventTarget(e);if(Q(o)&&(o=o.parentNode||null),"scroll"===e.type)return this.scrollDepth.track(),!0;if("visibilitychange"===e.type&&"hidden"===document.visibilityState||"popstate"===e.type)return this.scrollDepth.send(),!0;if("click"===e.type&&e instanceof MouseEvent&&(null===(r=this.rageclicks)||void 0===r||r.click(e.clientX,e.clientY,(new Date).getTime())),o&&function(e,t){if(!e||K(e,"html")||!W(e))return!1;for(var n=!1,r=[e],i=!0,o=e;o.parentNode&&!K(o,"body");)if(G(o.parentNode))r.push(o.parentNode.host),o=o.parentNode.host;else{if(!(i=o.parentNode||!1))break;if(Y.indexOf(i.tagName.toLowerCase())>-1)n=!0;else{var s=window.getComputedStyle(i);s&&"pointer"===s.getPropertyValue("cursor")&&(n=!0)}r.push(i),o=i}var a=window.getComputedStyle(e);if(a&&"pointer"===a.getPropertyValue("cursor")&&"click"===t.type)return!0;var c=e.tagName.toLowerCase();switch(c){case"html":return!1;case"form":return"submit"===t.type;case"input":case"select":case"textarea":return"change"===t.type||"click"===t.type;default:return n?"click"===t.type:"click"===t.type&&(Y.indexOf(c)>-1||"true"===e.getAttribute("contenteditable"))}}(o,e)){for(var s=[o],a=o;a.parentNode&&!K(a,"body");)G(a.parentNode)?(s.push(a.parentNode.host),a=a.parentNode.host):(s.push(a.parentNode),a=a.parentNode);var c,u=[],l=!1;if(D(s,(function(e){var t=X(e);"a"===e.tagName.toLowerCase()&&(c=e.getAttribute("href"),c=t&&ee(c)&&c),$(B(e).split(" "),"ph-no-capture")&&(l=!0),u.push(i._getPropertiesFromElement(e,null==n?void 0:n.mask_all_element_attributes,null==n?void 0:n.mask_all_text))})),(null==n?void 0:n.mask_all_text)||(u[0].$el_text=V(o)),c&&(u[0].attr__href=c),l)return!1;var p=H(this._getDefaultProperties(e.type),{$elements:u},this._getCustomProperties(s));return t.capture("$autocapture",p),!0}},_navigate:function(e){window.location.href=e},_addDomEventHandlers:function(e,t){var n=this,r=function(r){r=r||window.event,n._captureEvent(r,e,t)};U(document,"submit",r,!1,!0),U(document,"change",r,!1,!0),U(document,"click",r,!1,!0),U(document,"visibilitychange",r,!1,!0),U(document,"scroll",r,!1,!0),U(window,"popstate",r,!1,!0)},_customProperties:[],rageclicks:null,scrollDepth:null,opts:{},init:function(e,t){var n=this;if(this.rageclicks=new te(e),this.scrollDepth=new ne(e),this.opts=t,!document||!document.body)return console.debug("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((function(){n.readyAutocapture(e,t)}),500);this.readyAutocapture(e,t)},readyAutocapture:function(e,t){this._addDomEventHandlers(e,t)},enabledForProject:function(e,t,n){if(!e)return!0;t=M(t)?10:t,n=M(n)?10:n;for(var r=0,i=0;i<e.length;i++)r+=e.charCodeAt(i);return r%t<n},isBrowserSupported:function(){return F(document.querySelectorAll)}};!function(e){for(var t in e)"function"==typeof e[t]&&(e[t]=e[t].bind(e))}(re),function(e){for(var t in e)"function"==typeof e[t]&&(e[t]=z(e[t]))}(re);var ie="__buildEnv__",oe="__buildDate__",se="".concat("__buildVersion__","/").concat(ie,"@").concat(oe),ae=316224e3,ce=function(e,t){c().debug("Sending beacon",t);var n=new Blob([t],{type:"text/plain"});return navigator.sendBeacon(e,n),Promise.resolve()};var ue=function(e,t){return console.debug("Jitsu client tried to send payload to ".concat(e),function(e){if("string"==typeof e)try{return JSON.stringify(JSON.parse(e),null,2)}catch(t){return e}}(t)),Promise.resolve()};function le(e,t){void 0===t&&(t=void 0),""!=(t=null!=t?t:window.location.pathname)&&"/"!=t&&(y(e,t),le(e,t.slice(0,t.lastIndexOf("/"))))}var pe=function(){function e(e,t){this.cookieDomain=e,this.cookieName=t}return e.prototype.save=function(e){g(this.cookieName,JSON.stringify(e),{domain:this.cookieDomain,secure:"http:"!==document.location.protocol,maxAge:ae})},e.prototype.restore=function(){le(this.cookieName);var e=v(this.cookieName);if(e)try{var t=JSON.parse(decodeURIComponent(e));return"object"!=typeof t?void c().warn("Can't restore value of ".concat(this.cookieName,"@").concat(this.cookieDomain,", expected to be object, but found ").concat("object"!=typeof t,": ").concat(t,". Ignoring")):t}catch(t){return void c().error("Failed to decode JSON from "+e,t)}},e.prototype.delete=function(){y(this.cookieName)},e}(),de=function(){function e(){}return e.prototype.save=function(e){},e.prototype.restore=function(){},e.prototype.delete=function(){},e}();var he={getSourceIp:function(){},describeClient:function(){return{referer:document.referrer,url:window.location.href,page_title:document.title,doc_path:document.location.pathname,doc_host:document.location.hostname,doc_search:window.location.search,screen_resolution:screen.width+"x"+screen.height,vp_size:Math.max(document.documentElement.clientWidth||0,window.innerWidth||0)+"x"+Math.max(document.documentElement.clientHeight||0,window.innerHeight||0),user_agent:navigator.userAgent,user_language:navigator.language,doc_encoding:document.characterSet}},getAnonymousId:function(e){var t=e.name,n=e.domain;le(t);var r=v(t);if(r)return c().debug("Existing user id",r),r;var i=_();return c().debug("New user id",i),g(t,i,{domain:n,secure:"http:"!==document.location.protocol,maxAge:ae}),i}};var fe={getSourceIp:function(){},describeClient:function(){return{}},getAnonymousId:function(){return""}},me=function(){return he},ve=function(){return fe},ge=function(e,t,n,r){void 0===r&&(r=function(e,t){});var i=new window.XMLHttpRequest;return new Promise((function(o,s){i.onerror=function(e){c().error("Failed to send",t,e),r(-1,{}),s(new Error("Failed to send JSON. See console logs"))},i.onload=function(){200!==i.status?(r(i.status,{}),c().warn("Failed to send data to ".concat(e," (#").concat(i.status," - ").concat(i.statusText,")"),t),s(new Error("Failed to send JSON. Error code: ".concat(i.status,". See logs for details")))):r(i.status,i.responseText),o()},i.open("POST",e),i.setRequestHeader("Content-Type","application/json"),Object.entries(n||{}).forEach((function(e){var t=e[0],n=e[1];return i.setRequestHeader(t,n)})),i.send(t),c().debug("sending json",t)}))},ye=function(){function r(){this.userProperties={},this.permanentProperties={globalProps:{},propsPerEvent:{}},this.cookieDomain="",this.trackingHost="",this.idCookieName="",this.randomizeUrl=!1,this.apiKey="",this.initialized=!1,this._3pCookies={},this.cookiePolicy="keep",this.ipPolicy="keep",this.beaconApi=!1,this.transport=ge,this.customHeaders=function(){return{}},this.queue=new P,this.maxSendAttempts=4,this.retryTimeout=[500,1e12],this.flushing=!1,this.attempt=1,this.propertyBlacklist=[],this.__autocapture_enabled=!1}return r.prototype.get_config=function(e){return this.config?this.config[e]:null},r.prototype.id=function(t,n){return this.userProperties=e(e({},this.userProperties),t),c().debug("Usermaven user identified",t),this.userIdPersistence?this.userIdPersistence.save(t):c().warn("Id() is called before initialization"),n?Promise.resolve():this.track("user_identify",{})},r.prototype.rawTrack=function(e){return this.sendJson(e)},r.prototype.makeEvent=function(t,n,r){var o,s=r.env,a=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}(r,["env"]);s||(s=i()?me():ve()),this.restoreId();var c=this.getCtx(s),u=e(e({},this.permanentProperties.globalProps),null!==(o=this.permanentProperties.propsPerEvent[t])&&void 0!==o?o:{}),l=e({api_key:this.apiKey,src:n,event_type:t},a),p=s.getSourceIp();return p&&(l.source_ip=p),this.compatMode?e(e(e({},u),{eventn_ctx:c}),l):e(e(e({},u),c),l)},r.prototype._send3p=function(e,t,n){var r="3rdparty";n&&""!==n&&(r=n);var i=this.makeEvent(r,e,{src_payload:t});return this.sendJson(i)},r.prototype.sendJson=function(e){return t(this,void 0,Promise,(function(){return n(this,(function(t){switch(t.label){case 0:return this.maxSendAttempts>1?(this.queue.push([e,0]),this.scheduleFlush(0),[3,3]):[3,1];case 1:return[4,this.doSendJson(e)];case 2:t.sent(),t.label=3;case 3:return[2]}}))}))},r.prototype.doSendJson=function(e){var t=this,n="keep"!==this.cookiePolicy?"&cookie_policy=".concat(this.cookiePolicy):"",r="keep"!==this.ipPolicy?"&ip_policy=".concat(this.ipPolicy):"",o=i()?"/api/v1/event":"/api/v1/s2s/event",s="".concat(this.trackingHost).concat(o,"?token=").concat(this.apiKey).concat(n).concat(r);this.randomizeUrl&&(s="".concat(this.trackingHost,"/api.").concat(b(),"?p_").concat(b(),"=").concat(this.apiKey).concat(n).concat(r));var a=JSON.stringify(e);return c().debug("Sending payload to ".concat(s),a),this.transport(s,a,this.customHeaders(),(function(e,n){return t.postHandle(e,n)}))},r.prototype.scheduleFlush=function(e){var t=this;if(!this.flushing){if(this.flushing=!0,void 0===e){var n=Math.random()+1,r=Math.pow(2,this.attempt++);e=Math.min(this.retryTimeout[0]*n*r,this.retryTimeout[1])}c().debug("Scheduling event queue flush in ".concat(e," ms.")),setTimeout((function(){return t.flush()}),e)}},r.prototype.flush=function(){return t(this,void 0,Promise,(function(){var e,t,r=this;return n(this,(function(n){switch(n.label){case 0:if(i()&&!window.navigator.onLine&&(this.flushing=!1,this.scheduleFlush()),e=this.queue.flush(),this.flushing=!1,0===e.length)return[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.doSendJson(e.map((function(e){return e[0]})))];case 2:return n.sent(),this.attempt=1,c().debug("Successfully flushed ".concat(e.length," events from queue")),[3,4];case 3:return n.sent(),(e=e.map((function(e){return[e[0],e[1]+1]})).filter((function(e){return!(e[1]>=r.maxSendAttempts)||(c().error("Dropping queued event after ".concat(e[1]," attempts since max send attempts ").concat(r.maxSendAttempts," reached. See logs for details")),!1)}))).length>0?((t=this.queue).push.apply(t,e),this.scheduleFlush()):this.attempt=1,[3,4];case 4:return[2]}}))}))},r.prototype.postHandle=function(e,t){if("strict"===this.cookiePolicy||"comply"===this.cookiePolicy){if(200===e){var n=t;if("string"==typeof t&&(n=JSON.parse(t)),!n.delete_cookie)return}this.userIdPersistence.delete(),this.propsPersistance.delete(),y(this.idCookieName)}if(200===e){n=t;if("string"==typeof t&&t.length>0){var r=(n=JSON.parse(t)).jitsu_sdk_extras;if(r&&r.length>0)if(i())for(var o=0,s=r;o<s.length;o++){var a=s[o],u=a.type,l=a.id,p=a.value;if("tag"===u){var d=document.createElement("div");d.id=l,m(d,p),d.childElementCount>0&&document.body.appendChild(d)}}else c().error("Tags destination supported only in browser environment")}}},r.prototype.getCtx=function(t){var n=new Date,r=t.describeClient()||{},i=this.userProperties.company||{};delete this.userProperties.company;var o,s,a=e(e({event_id:"",user:e({anonymous_id:"strict"!==this.cookiePolicy?t.getAnonymousId({name:this.idCookieName,domain:this.cookieDomain}):""},this.userProperties),ids:this._getIds(),utc_time:(o=n.toISOString(),s=o.split(".")[1],s?s.length>=7?o:o.slice(0,-1)+"0".repeat(7-s.length)+"Z":o),local_tz_offset:n.getTimezoneOffset()},r),function(e){var t={utm:{},click_id:{}};for(var n in e)if(e.hasOwnProperty(n)){var r=e[n],i=w[n];i?t.utm[i]=r:k[n]&&(t.click_id[n]=r)}return t}(function(e){if(!e)return{};for(var t=e.length>0&&"?"===e.charAt(0)?e.substring(1):e,n={},r=("?"===t[0]?t.substr(1):t).split("&"),i=0;i<r.length;i++){var o=r[i].split("=");n[decodeURIComponent(o[0])]=decodeURIComponent(o[1]||"")}return n}(r.doc_search)));return Object.keys(i).length&&(a.company=i),a},r.prototype._getIds=function(){if(!i())return{};for(var e=function(e){if(void 0===e&&(e=!1),e&&d)return d;var t=h(document.cookie);return d=t,t}(!1),t={},n=0,r=Object.entries(e);n<r.length;n++){var o=r[n],s=o[0],a=o[1];this._3pCookies[s]&&(t["_"==s.charAt(0)?s.substr(1):s]=a)}return t},r.prototype.pathMatches=function(e,t){return new URL(t).pathname.match(new RegExp("^"+e.trim().replace(/\*\*/g,".*").replace(/([^\.])\*/g,"$1[^\\s/]*")+"/?$"))},r.prototype.track=function(e,t){var n=this,r=t||{};c().debug("track event of type",e,r);var o=i()?me():ve(),s=this.getCtx(o);if(this.config&&this.config.exclude&&this.config.exclude.length>1&&(null==s?void 0:s.url)&&this.config.exclude.split(",").some((function(e){return n.pathMatches(e.trim(),null==s?void 0:s.url)})))return void c().debug("Page is excluded from tracking");var a=t||{};"$autocapture"!==e&&"user_identify"!==e&&"pageview"!==e&&"$pageleave"!==e&&(a={event_attributes:t});var u=this.makeEvent(e,this.compatMode?"eventn":"usermaven",a);return this.sendJson(u)},r.prototype.init=function(r){var o,l,p,d,h,f,m,v=this;if(i()&&!r.force_use_fetch)r.fetch&&c().warn("Custom fetch implementation is provided to Usermaven. However, it will be ignored since Usermaven runs in browser"),this.transport=this.beaconApi?ce:ge;else{if(!r.fetch&&!globalThis.fetch)throw new Error("Usermaven runs in Node environment. However, neither UsermavenOptions.fetch is provided, nor global fetch function is defined. \nPlease, provide custom fetch implementation. You can get it via node-fetch package");this.transport=(h=r.fetch||globalThis.fetch,function(r,i,o,s){return void 0===s&&(s=function(e,t){}),t(void 0,void 0,void 0,(function(){var t,a,u,l,p,d,f,m;return n(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,h(r,{method:"POST",headers:e({Accept:"application/json","Content-Type":"application/json"},o||{}),body:i})];case 1:return t=n.sent(),[3,3];case 2:return a=n.sent(),c().error("Failed to send",i,a),s(-1,{}),[2];case 3:if(200!==t.status)return c().warn("Failed to send data to ".concat(r," (#").concat(t.status," - ").concat(t.statusText,")"),i),s(t.status,{}),[2];u={},l="",p=null!==(m=null===(f=t.headers)||void 0===f?void 0:f.get("Content-Type"))&&void 0!==m?m:"",n.label=4;case 4:return n.trys.push([4,6,,7]),[4,t.text()];case 5:return l=n.sent(),u=JSON.parse(l),[3,7];case 6:return d=n.sent(),c().error("Failed to parse ".concat(r," response. Content-type: ").concat(p," text: ").concat(l),d),[3,7];case 7:try{s(t.status,u)}catch(e){c().error("Failed to handle ".concat(r," response. Content-type: ").concat(p," text: ").concat(l),e)}return[2]}}))}))})}if(r.custom_headers&&"function"==typeof r.custom_headers?this.customHeaders=r.custom_headers:r.custom_headers&&(this.customHeaders=function(){return r.custom_headers}),"echo"===r.tracking_host&&(c().warn('jitsuClient is configured with "echo" transport. Outgoing requests will be written to console'),this.transport=ue),r.ip_policy&&(this.ipPolicy=r.ip_policy),r.cookie_policy&&(this.cookiePolicy=r.cookie_policy),"strict"===r.privacy_policy&&(this.ipPolicy="strict",this.cookiePolicy="strict"),r.use_beacon_api&&navigator.sendBeacon&&(this.beaconApi=!0),"comply"===this.cookiePolicy&&this.beaconApi&&(this.cookiePolicy="strict"),r.log_level&&(f=r.log_level,(m=s[f.toLocaleUpperCase()])||(console.warn("Can't find log level with name ".concat(f.toLocaleUpperCase(),", defaulting to INFO")),m=s.INFO),a=u(m)),this.initialOptions=r,c().debug("Initializing Usemaven Tracker tracker",r,se),r.key){if(this.compatMode=void 0!==r.compat_mode&&!!r.compat_mode,this.cookieDomain=r.cookie_domain||function(){if(i())return".".concat((e=location.hostname,t=function(e){return(e.indexOf("//")>-1?e.split("/")[2]:e.split("/")[0]).split(":")[0].split("?")[0]}(e),n=t.split("."),(r=n.length)>2&&(t=n[r-2]+"."+n[r-1],2==n[r-2].length&&2==n[r-1].length&&(t=n[r-3]+"."+t)),t));var e,t,n,r}(),this.trackingHost=function(e){for(;n="/",-1!==(t=e).indexOf(n,t.length-n.length);)e=e.substr(0,e.length-1);var t,n;return 0===e.indexOf("https://")||0===e.indexOf("http://")?e:"//"+e}(r.tracking_host||"t.usermaven.com"),this.randomizeUrl=r.randomize_url||!1,this.idCookieName=r.cookie_name||"__eventn_id",this.apiKey=r.key,"strict"===this.cookiePolicy?this.propsPersistance=new de:this.propsPersistance=i()?new pe(this.cookieDomain,this.idCookieName+"_props"):new de,"strict"===this.cookiePolicy?this.userIdPersistence=new de:this.userIdPersistence=i()?new pe(this.cookieDomain,this.idCookieName+"_usr"):new de,this.propsPersistance){var g=this.propsPersistance.restore();g&&(this.permanentProperties=g,this.permanentProperties.globalProps=null!==(o=g.globalProps)&&void 0!==o?o:{},this.permanentProperties.propsPerEvent=null!==(l=g.propsPerEvent)&&void 0!==l?l:{}),c().debug("Restored persistent properties",this.permanentProperties)}this.propertyBlacklist=r.property_blacklist&&r.property_blacklist.length>0?r.property_blacklist:[];this.config=H({},{autocapture:!1,properties_string_max_length:null,property_blacklist:[],sanitize_properties:null},r||{},this.config||{},{token:this.apiKey}),c().debug("Default Configuration",this.config),this.manageAutoCapture(this.config),!1===r.capture_3rd_party_cookies?this._3pCookies={}:(r.capture_3rd_party_cookies||["_ga","_fbp","_ym_uid","ajs_user_id","ajs_anonymous_id"]).forEach((function(e){return v._3pCookies[e]=!0})),r.ga_hook&&c().warn("GA event interceptor isn't supported anymore"),r.segment_hook&&function(e){var t=window;t.analytics||(t.analytics=[]);e.interceptAnalytics(t.analytics)}(this),i()&&(r.disable_event_persistence||(this.queue=new x("jitsu-event-queue"),this.scheduleFlush(0)),window.addEventListener("beforeunload",(function(){return v.flush()}))),this.retryTimeout=[null!==(p=r.min_send_timeout)&&void 0!==p?p:this.retryTimeout[0],null!==(d=r.max_send_timeout)&&void 0!==d?d:this.retryTimeout[1]],r.max_send_attempts&&(this.maxSendAttempts=r.max_send_attempts),this.initialized=!0}else c().error("Can't initialize Usemaven, key property is not set")},r.prototype.interceptAnalytics=function(t){var n=this,r=function(t){var r;try{var i=e({},t.payload);c().debug("Intercepted segment payload",i.obj);var o=t.integrations["Segment.io"];if(o&&o.analytics){var s=o.analytics;"function"==typeof s.user&&s.user()&&"function"==typeof s.user().id&&(i.obj.userId=s.user().id())}(null===(r=null==i?void 0:i.obj)||void 0===r?void 0:r.timestamp)&&(i.obj.sentAt=i.obj.timestamp);var a=t.payload.type();"track"===a&&(a=t.payload.event()),n._send3p("ajs",i,a)}catch(e){c().warn("Failed to send an event",e)}t.next(t.payload)};"function"==typeof t.addSourceMiddleware?(c().debug("Analytics.js is initialized, calling addSourceMiddleware"),t.addSourceMiddleware(r)):(c().debug("Analytics.js is not initialized, pushing addSourceMiddleware to callstack"),t.push(["addSourceMiddleware",r])),t.__en_intercepted=!0},r.prototype.restoreId=function(){if(this.userIdPersistence){var t=this.userIdPersistence.restore();t&&(this.userProperties=e(e({},t),this.userProperties))}},r.prototype.set=function(t,n){var r,i=null==n?void 0:n.eventType,o=void 0===(null==n?void 0:n.persist)||(null==n?void 0:n.persist);if(void 0!==i){var s=null!==(r=this.permanentProperties.propsPerEvent[i])&&void 0!==r?r:{};this.permanentProperties.propsPerEvent[i]=e(e({},s),t)}else this.permanentProperties.globalProps=e(e({},this.permanentProperties.globalProps),t);this.propsPersistance&&o&&this.propsPersistance.save(this.permanentProperties)},r.prototype.unset=function(e,t){o();var n=null==t?void 0:t.eventType,r=void 0===(null==t?void 0:t.persist)||(null==t?void 0:t.persist);n?this.permanentProperties.propsPerEvent[n]&&delete this.permanentProperties.propsPerEvent[n][e]:delete this.permanentProperties.globalProps[e],this.propsPersistance&&r&&this.propsPersistance.save(this.permanentProperties)},r.prototype.manageAutoCapture=function(e){if(c().debug("Auto Capture Status: ",this.config.autocapture),this.__autocapture_enabled=this.config.autocapture,this.__autocapture_enabled){re.enabledForProject(this.apiKey,100,100)?re.isBrowserSupported()?(c().debug("Autocapture enabled..."),re.init(this,e)):(this.config.autocapture=!1,this.__autocapture_enabled=!1,c().debug("Disabling Automatic Event Collection because this browser is not supported")):(this.config.autocapture=!1,this.__autocapture_enabled=!1,c().debug("Not in active bucket: disabling Automatic Event Collection."))}},r.prototype.capture=function(e,t){var n,r;if(void 0===t&&(t={}),this.initialized)if(M(e)||"string"!=typeof e)console.error("No event name provided to usermaven.capture");else{var i={event:e+(t.$event_type?"_"+t.$event_type:""),properties:this._calculate_event_properties(e,t)};(null===(r=null===(n=(i=R(i,this.get_config("properties_string_max_length"))).properties)||void 0===n?void 0:n.autocapture_attributes)||void 0===r?void 0:r.tag_name)&&this.track("$autocapture",i.properties),"$scroll"===e&&this.track(e,i.properties)}else console.error("Trying to capture event before initialization")},r.prototype._calculate_event_properties=function(e,t){var n,r,i=t||{};if("$snapshot"===e||"$scroll"===e)return i;T(this.propertyBlacklist)?D(this.propertyBlacklist,(function(e){delete i[e]})):console.error("Invalid value for property_blacklist config: "+this.propertyBlacklist);var o={},s=i.$elements||[];return s.length&&(o=s[0]),i.autocapture_attributes=o,i.autocapture_attributes.el_text=null!==(n=i.autocapture_attributes.$el_text)&&void 0!==n?n:"",i.autocapture_attributes.event_type=null!==(r=i.$event_type)&&void 0!==r?r:"",["$ce_version","$event_type","$initial_referrer","$initial_referring_domain","$referrer","$referring_domain","$elements"].forEach((function(e){delete i[e]})),delete i.autocapture_attributes.$el_text,delete i.autocapture_attributes.nth_child,delete i.autocapture_attributes.nth_of_type,i},r}();var _e=["use_beacon_api","cookie_domain","tracking_host","cookie_name","key","ga_hook","segment_hook","randomize_url","capture_3rd_party_cookies","id_method","log_level","compat_mode","privacy_policy","cookie_policy","ip_policy","custom_headers","force_use_fetch","min_send_timeout","max_send_timeout","max_send_attempts","disable_event_persistence","project_id","autocapture","properties_string_max_length","property_blacklist","exclude"];var be="data-suppress-interception-warning";function we(e){return"\n ATTENTION! ".concat(e,"-hook set to true along with defer/async attribute! If ").concat(e," code is inserted right after Usermaven tag,\n first tracking call might not be intercepted! Consider one of the following:\n - Inject usermaven tracking code without defer/async attribute\n - If you're sure that events won't be sent to ").concat(e," before Usermaven is fully initialized, set ").concat(be,'="true"\n script attribute\n ')}function ke(e,t){c().debug("Processing queue",e);for(var n=0;n<e.length;n+=1){var i=r([],e[n],!0)||[],o=i[0],s=i.slice(1),a=t[o];"function"==typeof a&&a.apply(t,s)}e.length=0}if(window){var Pe=window,xe=function(e){var t=document.currentScript||document.querySelector("script[src*=jsFileName][data-usermaven-api-key]");if(t){var n,r={tracking_host:(n=t.getAttribute("src"),n.replace("/s/lib.js","").replace("/lib.js","")),key:null};_e.forEach((function(e){var n="data-"+e.replace(new RegExp("_","g"),"-");if(void 0!==t.getAttribute(n)&&null!==t.getAttribute(n)){var i=t.getAttribute(n);"true"===i?i=!0:"false"===i&&(i=!1),r[e]=i}})),e.usermavenClient=function(e){var t=new ye;return t.init(e),t}(r),!r.segment_hook||null===t.getAttribute("defer")&&null===t.getAttribute("async")||null!==t.getAttribute(be)||c().warn(we("segment")),!r.ga_hook||null===t.getAttribute("defer")&&null===t.getAttribute("async")||null!==t.getAttribute(be)||c().warn(we("ga"));var i=function(){var t=e.usermavenQ=e.usermavenQ||[];t.push(arguments),ke(t,e.usermavenClient)};return e.usermaven=i,r.project_id&&i("set",{project_id:r.project_id}),"true"!==t.getAttribute("data-init-only")&&"yes"!==t.getAttribute("data-init-only")&&i("track","pageview"),document.addEventListener("visibilitychange",(function(e){"visibilitychange"===e.type&&"hidden"===document.visibilityState&&i("track","$pageleave")}),!1),e.usermavenClient}c().warn("Usermaven script is not properly initialized. The definition must contain data-usermaven-api-key as a parameter")}(Pe);xe?(c().debug("Usermaven in-browser tracker has been initialized"),Pe.usermaven=function(){var e=Pe.usermavenQ=Pe.usermavenQ||[];e.push(arguments),ke(e,xe)},Pe.usermavenQ&&(c().debug("Initial queue size of ".concat(Pe.usermavenQ.length," will be processed")),ke(Pe.usermavenQ,xe))):c().error("Usermaven tracker has not been initialized (reason unknown)")}else c().warn("Usermaven tracker called outside browser context. It will be ignored")}();
1
+ !function(){"use strict";var e=function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},e.apply(this,arguments)};function t(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))}function n(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){s.label=o[1];break}if(6===o[0]&&s.label<i[1]){s.label=i[1],i=o;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(o);break}i[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,a])}}}function r(e,t,n){if(n||2===arguments.length)for(var r,i=0,o=t.length;i<o;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}function i(e){const t=!!globalThis.window&&!!globalThis.window.document&&!!globalThis.window.location;return!t&&e&&c().warn(e),t}function o(e){if(!i())throw new Error(e||"window' is not available. Seems like this code runs outside browser environment. It shouldn't happen");return window}var s={DEBUG:{name:"DEBUG",severity:10},INFO:{name:"INFO",severity:100},WARN:{name:"WARN",severity:1e3},ERROR:{name:"ERROR",severity:1e4},NONE:{name:"NONE",severity:1e4}},a=null;function c(){return a||(a=u())}function u(e){var t=i()&&window.__eventNLogLevel,n=s.WARN;if(t){var o=s[t.toUpperCase()];o&&o>0&&(n=o)}else e&&(n=e);var a={minLogLevel:n};return Object.values(s).forEach((function(e){var t=e.name,i=e.severity;a[t.toLowerCase()]=function(){for(var e=[],o=0;o<arguments.length;o++)e[o]=arguments[o];if(i>=n.severity&&e.length>0){var s=e[0],a=e.splice(1),c="[J-".concat(t,"] ").concat(s);"DEBUG"===t||"INFO"===t?console.log.apply(console,r([c],a,!1)):"WARN"===t?console.warn.apply(console,r([c],a,!1)):console.error.apply(console,r([c],a,!1))}}})),function(e,t){if(i()){var n=window;n.__usermavenDebug||(n.__usermavenDebug={}),n.__usermavenDebug[e]=t}}("logger",a),a}function l(e,t,n){void 0===n&&(n={});try{var r=n.maxAge,i=n.domain,o=n.path,s=n.expires,a=n.httpOnly,u=n.secure,l=n.sameSite,p="".concat(e,"=").concat(encodeURIComponent(t));if(i){var d=function(e){var t=e.split("."),n=window.location.hostname.split("."),r=n.length>t.length&&n.slice(-t.length).join(".")===t.filter(Boolean).join(".");return c().debug("isValidCrossDomain",n.slice(-t.length).join("."),t.filter(Boolean).join("."),r),r}(i);d&&(p+="; domain=".concat(i.replace(/^\./,"")))}if(p+=o?"; path=".concat(o):"; path=/",s&&(p+="; expires=".concat(s.toUTCString())),r&&(p+="; max-age=".concat(r)),a&&(p+="; httponly"),u&&(p+="; secure"),l)switch("string"==typeof l?l.toLowerCase():l){case!0:p+="; SameSite=Strict";break;case"lax":p+="; SameSite=Lax";break;case"strict":p+="; SameSite=Strict";break;case"none":p+="; SameSite=None"}return p}catch(e){return c().error("serializeCookie",e),""}}var p;function d(e){if(!e)return{};for(var t={},n=e.split(";"),r=0;r<n.length;r++){var i=n[r],o=i.indexOf("=");o>0&&(t[i.substr(r>0?1:0,r>0?o-1:o)]=i.substr(o+1))}return t}function h(e,t){return Array.from(e.attributes).forEach((function(e){t.setAttribute(e.nodeName,e.nodeValue)}))}function f(e,t){e.innerHTML=t;var n,r=e.getElementsByTagName("script");for(n=r.length-1;n>=0;n--){var i=r[n],o=document.createElement("script");h(i,o),i.innerHTML&&(o.innerHTML=i.innerHTML),o.setAttribute("data-usermaven-tag-id",e.id),document.getElementsByTagName("head")[0].appendChild(o),r[n].parentNode.removeChild(r[n])}}var m=function(e){if(!e)return null;try{for(var t=e+"=",n=o().document.cookie.split(";"),r=0;r<n.length;r++){for(var i=n[r];" "==i.charAt(0);)i=i.substring(1,i.length);if(0===i.indexOf(t))return decodeURIComponent(i.substring(t.length,i.length))}}catch(e){c().error("getCookies",e)}return null},g=function(e,t,n){void 0===n&&(n={}),o().document.cookie=l(e,t,n)},v=function(e,t){void 0===t&&(t="/"),document.cookie=e+"= ; expires = Thu, 01 Jan 1970 00:00:00 GMT"+(t?"; path = "+t:"")},y=function(){return Math.random().toString(36).substring(2,12)},_=function(){return Math.random().toString(36).substring(2,7)},b={utm_source:"source",utm_medium:"medium",utm_campaign:"campaign",utm_term:"term",utm_content:"content"},k={gclid:!0,fbclid:!0,dclid:!0};var w=function(){function e(){this.queue=[]}return e.prototype.flush=function(){var e=this.queue;return this.queue=[],e},e.prototype.push=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];(e=this.queue).push.apply(e,t)},e}(),P=function(){function e(e){this.key=e}return e.prototype.flush=function(){var e=this.get();return e.length&&this.set([]),e},e.prototype.push=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=this.get();n.push.apply(n,e),this.set(n)},e.prototype.set=function(e){localStorage.setItem(this.key,JSON.stringify(e))},e.prototype.get=function(){var e=localStorage.getItem(this.key);return null!==e&&""!==e?JSON.parse(e):[]},e}(),x=Object.prototype,S=x.toString,N=x.hasOwnProperty,C=Array.prototype.forEach,A=Array.isArray,E={},O=A||function(e){return"[object Array]"===S.call(e)};function I(e,t,n){if(Array.isArray(e))if(C&&e.forEach===C)e.forEach(t,n);else if("length"in e&&e.length===+e.length)for(var r=0,i=e.length;r<i;r++)if(r in e&&t.call(n,e[r],r)===E)return}var T=function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")};function j(e,t,n){if(null!=e)if(C&&Array.isArray(e)&&e.forEach===C)e.forEach(t,n);else if("length"in e&&e.length===+e.length){for(var r=0,i=e.length;r<i;r++)if(r in e&&t.call(n,e[r],r)===E)return}else for(var o in e)if(N.call(e,o)&&t.call(n,e[o],o)===E)return}var D=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];return I(t,(function(t){for(var n in t)void 0!==t[n]&&(e[n]=t[n])})),e};function H(e,t){return-1!==e.indexOf(t)}var F=function(e){try{return/^\s*\bfunction\b/.test(e)}catch(e){return!1}},$=function(e){return void 0===e},U=function(){function e(t){return t&&(t.preventDefault=e.preventDefault,t.stopPropagation=e.stopPropagation),t}return e.preventDefault=function(){this.returnValue=!1},e.stopPropagation=function(){this.cancelBubble=!0},function(t,n,r,i,o){if(t)if(t.addEventListener&&!i)t.addEventListener(n,r,!!o);else{var s="on"+n,a=t[s];t[s]=function(t,n,r){return function(i){if(i=i||e(window.event)){var o,s=!0;F(r)&&(o=r(i));var a=n.call(t,i);return!1!==o&&!1!==a||(s=!1),s}}}(t,r,a)}else c().error("No valid element provided to register_event")}}(),L=function(e){return function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];try{return e.apply(this,t)}catch(e){c().error("Implementation error. Please turn on debug and contact support@usermaven.com.",e)}}},M="undefined"!=typeof Symbol?Symbol("__deepCircularCopyInProgress__"):"__deepCircularCopyInProgress__";function z(e,t,n){return e!==Object(e)?t?t(e,n):e:e[M]?void 0:(e[M]=!0,O(e)?(r=[],I(e,(function(e){r.push(z(e,t))}))):(r={},j(e,(function(e,n){n!==M&&(r[n]=z(e,t,n))}))),delete e[M],r);var r}var R=["$performance_raw"];function q(e,t){return z(e,(function(e,n){return n&&R.indexOf(n)>-1?e:"string"==typeof e&&null!==t?e.slice(0,t):e}))}function J(e){switch(typeof e.className){case"string":return e.className;case"object":return("baseVal"in e.className?e.className.baseVal:null)||e.getAttribute("class")||"";default:return""}}function B(e){var t="";return Y(e)&&!Z(e)&&e.childNodes&&e.childNodes.length&&j(e.childNodes,(function(e){G(e)&&e.textContent&&(t+=T(e.textContent).split(/(\s+)/).filter(X).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))})),T(t)}function V(e){return!!e&&1===e.nodeType}function W(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function G(e){return!!e&&3===e.nodeType}function K(e){return!!e&&11===e.nodeType}var Q=["a","button","form","input","select","textarea","label"];function Y(e){for(var t=e;t.parentNode&&!W(t,"body");t=t.parentNode){var n=J(t).split(" ");if(H(n,"ph-sensitive")||H(n,"ph-no-capture"))return!1}if(H(J(e).split(" "),"ph-include"))return!0;var r=e.type||"";if("string"==typeof r)switch(r.toLowerCase()){case"hidden":case"password":return!1}var i=e.name||e.id||"";if("string"==typeof i){if(/^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,"")))return!1}return!0}function Z(e){return!!(W(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||W(e,"select")||W(e,"textarea")||"true"===e.getAttribute("contenteditable"))}function X(e){if(null===e||$(e))return!1;if("string"==typeof e){e=T(e);if(/^(?:(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,"")))return!1;if(/(^\d{3}-?\d{2}-?\d{4}$)/.test(e))return!1}return!0}var ee=function(){function e(e,t){void 0===t&&(t=!1),this.clicks=[],this.instance=e,this.enabled=t}return e.prototype.click=function(e,t,n){if(this.enabled){var r=this.clicks[this.clicks.length-1];r&&Math.abs(e-r.x)+Math.abs(t-r.y)<30&&n-r.timestamp<1e3?(this.clicks.push({x:e,y:t,timestamp:n}),3===this.clicks.length&&this.instance.capture("$rageclick")):this.clicks=[{x:e,y:t,timestamp:n}]}},e}(),te=function(){function e(e){this.instance=e,this.lastScrollDepth=0,this.canSend=!0,this.documentElement=document.documentElement}return e.prototype.track=function(){var e=this.getScrollDepth();e>this.lastScrollDepth&&(this.lastScrollDepth=e,this.canSend=!0)},e.prototype.send=function(e){if(void 0===e&&(e="$scroll"),this.canSend){var t={percent:this.lastScrollDepth,window_height:this.getWindowHeight(),document_height:this.getDocumentHeight(),scroll_distance:this.getScrollDistance()};this.instance.capture(e,t),this.canSend=!1}},e.prototype.getScrollDepth=function(){try{var e=this.getWindowHeight(),t=this.getDocumentHeight(),n=this.getScrollDistance(),r=t-e;return Math.min(100,Math.floor(n/r*100))}catch(e){return 0}},e.prototype.getWindowHeight=function(){try{return window.innerHeight||this.documentElement.clientHeight||document.body.clientHeight||0}catch(e){return 0}},e.prototype.getDocumentHeight=function(){try{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)}catch(e){return 0}},e.prototype.getScrollDistance=function(){try{return window.scrollY||window.pageYOffset||document.body.scrollTop||this.documentElement.scrollTop||0}catch(e){return 0}},e}(),ne={_initializedTokens:[],_previousElementSibling:function(e){if(e.previousElementSibling)return e.previousElementSibling;var t=e;do{t=t.previousSibling}while(t&&!V(t));return t},_getPropertiesFromElement:function(e,t,n){var r=e.tagName.toLowerCase(),i={tag_name:r};Q.indexOf(r)>-1&&!n&&(i.$el_text=B(e));var o=J(e);o.length>0&&(i.classes=o.split(" ").filter((function(e){return""!==e}))),j(e.attributes,(function(n){var r;Z(e)&&-1===["name","id","class"].indexOf(n.name)||!t&&X(n.value)&&("string"!=typeof(r=n.name)||"_ngcontent"!==r.substring(0,10)&&"_nghost"!==r.substring(0,7))&&(i["attr__"+n.name]=n.value)}));for(var s=1,a=1,c=e;c=this._previousElementSibling(c);)s++,c.tagName===e.tagName&&a++;return i.nth_child=s,i.nth_of_type=a,i},_getDefaultProperties:function(e){return{$event_type:e,$ce_version:1}},_extractCustomPropertyValue:function(e){var t=[];return j(document.querySelectorAll(e.css_selector),(function(e){var n;["input","select"].indexOf(e.tagName.toLowerCase())>-1?n=e.value:e.textContent&&(n=e.textContent),X(n)&&t.push(n)})),t.join(", ")},_getCustomProperties:function(e){var t=this,n={};return j(this._customProperties,(function(r){j(r.event_selectors,(function(i){j(document.querySelectorAll(i),(function(i){H(e,i)&&Y(i)&&(n[r.name]=t._extractCustomPropertyValue(r))}))}))})),n},_getEventTarget:function(e){var t;return void 0===e.target?e.srcElement||null:(null===(t=e.target)||void 0===t?void 0:t.shadowRoot)?e.composedPath()[0]||null:e.target||null},_captureEvent:function(e,t,n){var r,i=this,o=this._getEventTarget(e);if(G(o)&&(o=o.parentNode||null),"scroll"===e.type)return this.scrollDepth.track(),!0;if("visibilitychange"===e.type&&"hidden"===document.visibilityState||"popstate"===e.type)return this.scrollDepth.send(),!0;if("click"===e.type&&e instanceof MouseEvent&&(null===(r=this.rageclicks)||void 0===r||r.click(e.clientX,e.clientY,(new Date).getTime())),o&&function(e,t){if(!e||W(e,"html")||!V(e))return!1;if(e.classList&&e.classList.contains("um-no-capture"))return!1;for(var n=!1,r=[e],i=!0,o=e;o.parentNode&&!W(o,"body");)if(K(o.parentNode))r.push(o.parentNode.host),o=o.parentNode.host;else{if(!(i=o.parentNode||!1))break;if(Q.indexOf(i.tagName.toLowerCase())>-1)n=!0;else{var s=window.getComputedStyle(i);s&&"pointer"===s.getPropertyValue("cursor")&&(n=!0)}r.push(i),o=i}var a=window.getComputedStyle(e);if(a&&"pointer"===a.getPropertyValue("cursor")&&"click"===t.type)return!0;var c=e.tagName.toLowerCase();switch(c){case"html":return!1;case"form":return"submit"===t.type;case"input":case"select":case"textarea":return"change"===t.type||"click"===t.type;default:return n?"click"===t.type:"click"===t.type&&(Q.indexOf(c)>-1||"true"===e.getAttribute("contenteditable"))}}(o,e)){for(var s=[o],a=o;a.parentNode&&!W(a,"body");)K(a.parentNode)?(s.push(a.parentNode.host),a=a.parentNode.host):(s.push(a.parentNode),a=a.parentNode);var c,u=[],l=!1;if(j(s,(function(e){var t=Y(e);"a"===e.tagName.toLowerCase()&&(c=e.getAttribute("href"),c=t&&X(c)&&c),H(J(e).split(" "),"ph-no-capture")&&(l=!0),u.push(i._getPropertiesFromElement(e,null==n?void 0:n.mask_all_element_attributes,null==n?void 0:n.mask_all_text))})),(null==n?void 0:n.mask_all_text)||(u[0].$el_text=B(o)),c&&(u[0].attr__href=c),l)return!1;var p=D(this._getDefaultProperties(e.type),{$elements:u},this._getCustomProperties(s));return t.capture("$autocapture",p),!0}},_navigate:function(e){window.location.href=e},_addDomEventHandlers:function(e,t){var n=this,r=function(r){r=r||window.event,n._captureEvent(r,e,t)};U(document,"submit",r,!1,!0),U(document,"change",r,!1,!0),U(document,"click",r,!1,!0),U(document,"visibilitychange",r,!1,!0),U(document,"scroll",r,!1,!0),U(window,"popstate",r,!1,!0)},_customProperties:[],rageclicks:null,scrollDepth:null,opts:{},init:function(e,t){var n=this;if(this.rageclicks=new ee(e),this.scrollDepth=new te(e),this.opts=t,!document||!document.body)return console.debug("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((function(){n.readyAutocapture(e,t)}),500);this.readyAutocapture(e,t)},readyAutocapture:function(e,t){this._addDomEventHandlers(e,t)},enabledForProject:function(e,t,n){if(!e)return!0;t=$(t)?10:t,n=$(n)?10:n;for(var r=0,i=0;i<e.length;i++)r+=e.charCodeAt(i);return r%t<n},isBrowserSupported:function(){return F(document.querySelectorAll)}};!function(e){for(var t in e)"function"==typeof e[t]&&(e[t]=e[t].bind(e))}(ne),function(e){for(var t in e)"function"==typeof e[t]&&(e[t]=L(e[t]))}(ne);var re="production",ie="2023-04-06T09:40:36.263Z",oe="".concat("1.2.0","/").concat(re,"@").concat(ie),se=316224e3,ae=function(e,t){c().debug("Sending beacon",t);var n=new Blob([t],{type:"text/plain"});return navigator.sendBeacon(e,n),Promise.resolve()};var ce=function(e,t){return console.debug("Jitsu client tried to send payload to ".concat(e),function(e){if("string"==typeof e)try{return JSON.stringify(JSON.parse(e),null,2)}catch(t){return e}}(t)),Promise.resolve()};function ue(e,t){void 0===t&&(t=void 0),""!=(t=null!=t?t:window.location.pathname)&&"/"!=t&&(v(e,t),ue(e,t.slice(0,t.lastIndexOf("/"))))}var le=function(){function e(e,t){this.cookieDomain=e,this.cookieName=t}return e.prototype.save=function(e){g(this.cookieName,JSON.stringify(e),{domain:this.cookieDomain,secure:"http:"!==document.location.protocol,maxAge:se})},e.prototype.restore=function(){ue(this.cookieName);var e=m(this.cookieName);if(e)try{var t=JSON.parse(decodeURIComponent(e));return"object"!=typeof t?void c().warn("Can't restore value of ".concat(this.cookieName,"@").concat(this.cookieDomain,", expected to be object, but found ").concat("object"!=typeof t,": ").concat(t,". Ignoring")):t}catch(t){return void c().error("Failed to decode JSON from "+e,t)}},e.prototype.delete=function(){v(this.cookieName)},e}(),pe=function(){function e(){}return e.prototype.save=function(e){},e.prototype.restore=function(){},e.prototype.delete=function(){},e}();var de={getSourceIp:function(){},describeClient:function(){return{referer:document.referrer,url:window.location.href,page_title:document.title,doc_path:document.location.pathname,doc_host:document.location.hostname,doc_search:window.location.search,screen_resolution:screen.width+"x"+screen.height,vp_size:Math.max(document.documentElement.clientWidth||0,window.innerWidth||0)+"x"+Math.max(document.documentElement.clientHeight||0,window.innerHeight||0),user_agent:navigator.userAgent,user_language:navigator.language,doc_encoding:document.characterSet}},getAnonymousId:function(e){var t=e.name,n=e.domain;ue(t);var r=m(t);if(r)return c().debug("Existing user id",r),r;var i=y();return c().debug("New user id",i),g(t,i,{domain:n,secure:"http:"!==document.location.protocol,maxAge:se}),i}};var he={getSourceIp:function(){},describeClient:function(){return{}},getAnonymousId:function(){return""}},fe=function(){return de},me=function(){return he},ge=function(e,t,n,r){void 0===r&&(r=function(e,t){});var i=new window.XMLHttpRequest;return new Promise((function(o,s){i.onerror=function(n){c().error("Failed to send payload to ".concat(e,": ").concat((null==n?void 0:n.message)||"unknown error"),t,n),r(-1,{}),s(new Error("Failed to send JSON. See console logs"))},i.onload=function(){200!==i.status?(r(i.status,{}),c().warn("Failed to send data to ".concat(e," (#").concat(i.status," - ").concat(i.statusText,")"),t),s(new Error("Failed to send JSON. Error code: ".concat(i.status,". See logs for details")))):r(i.status,i.responseText),o()},i.open("POST",e),i.setRequestHeader("Content-Type","application/json"),Object.entries(n||{}).forEach((function(e){var t=e[0],n=e[1];return i.setRequestHeader(t,n)})),i.send(t),c().debug("sending json",t)}))},ve=function(){function r(){this.userProperties={},this.groupProperties={},this.permanentProperties={globalProps:{},propsPerEvent:{}},this.cookieDomain="",this.trackingHost="",this.idCookieName="",this.randomizeUrl=!1,this.apiKey="",this.initialized=!1,this._3pCookies={},this.cookiePolicy="keep",this.ipPolicy="keep",this.beaconApi=!1,this.transport=ge,this.customHeaders=function(){return{}},this.queue=new w,this.maxSendAttempts=4,this.retryTimeout=[500,1e12],this.flushing=!1,this.attempt=1,this.propertyBlacklist=[],this.__autocapture_enabled=!1,this.trackingHostFallback="https://events.usermaven.com"}return r.prototype.get_config=function(e){return this.config?this.config[e]:null},r.prototype.id=function(t,n){return this.userProperties=e(e({},this.userProperties),t),c().debug("Usermaven user identified",t),this.userIdPersistence?this.userIdPersistence.save(t):c().warn("Id() is called before initialization"),n?Promise.resolve():this.track("user_identify",{})},r.prototype.group=function(t,n){return this.groupProperties=e(e({},this.groupProperties),t),c().debug("Usermaven group identified",t),this.userIdPersistence?this.userIdPersistence.save({company:t}):c().warn("Group() is called before initialization"),n?Promise.resolve():this.track("group",{})},r.prototype.reset=function(e){if(this.userIdPersistence&&this.userIdPersistence.delete(),this.propsPersistance&&this.propsPersistance.delete(),e){var t=m(this.idCookieName);t&&(c().debug("Removing id cookie",t),g(this.idCookieName,"",{domain:this.cookieDomain,expires:new Date(0)}))}return Promise.resolve()},r.prototype.rawTrack=function(e){return this.sendJson(e)},r.prototype.makeEvent=function(t,n,r){var o,s=r.env,a=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}(r,["env"]);s||(s=i()?fe():me()),this.restoreId();var c=this.getCtx(s),u=e(e({},this.permanentProperties.globalProps),null!==(o=this.permanentProperties.propsPerEvent[t])&&void 0!==o?o:{}),l=e({api_key:this.apiKey,src:n,event_type:t},a),p=s.getSourceIp();return p&&(l.source_ip=p),this.compatMode?e(e(e({},u),{eventn_ctx:c}),l):e(e(e({},u),c),l)},r.prototype._send3p=function(e,t,n){var r="3rdparty";n&&""!==n&&(r=n);var i=this.makeEvent(r,e,{src_payload:t});return this.sendJson(i)},r.prototype.sendJson=function(e){return t(this,void 0,Promise,(function(){return n(this,(function(t){switch(t.label){case 0:return this.maxSendAttempts>1?(this.queue.push([e,0]),this.scheduleFlush(0),[3,3]):[3,1];case 1:return[4,this.doSendJson(e)];case 2:t.sent(),t.label=3;case 3:return[2]}}))}))},r.prototype.doSendJson=function(e){var t=this,n="keep"!==this.cookiePolicy?"&cookie_policy=".concat(this.cookiePolicy):"",r="keep"!==this.ipPolicy?"&ip_policy=".concat(this.ipPolicy):"",o=i()?"/api/v1/event":"/api/v1/s2s/event",s="".concat(this.trackingHost).concat(o,"?token=").concat(this.apiKey).concat(n).concat(r);this.randomizeUrl&&(s="".concat(this.trackingHost,"/api.").concat(_(),"?p_").concat(_(),"=").concat(this.apiKey).concat(n).concat(r));var a=JSON.stringify(e);return c().debug("Sending payload to ".concat(s),a),this.transport(s,a,this.customHeaders(),(function(e,n){return t.postHandle(e,n)}))},r.prototype.scheduleFlush=function(e){var t=this;if(!this.flushing){if(this.flushing=!0,void 0===e){var n=Math.random()+1,r=Math.pow(2,this.attempt++);e=Math.min(this.retryTimeout[0]*n*r,this.retryTimeout[1])}c().debug("Scheduling event queue flush in ".concat(e," ms.")),setTimeout((function(){return t.flush()}),e)}},r.prototype.flush=function(){return t(this,void 0,Promise,(function(){var e,t,r=this;return n(this,(function(n){switch(n.label){case 0:if(i()&&!window.navigator.onLine&&(this.flushing=!1,this.scheduleFlush()),e=this.queue.flush(),this.flushing=!1,0===e.length)return[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.doSendJson(e.map((function(e){return e[0]})))];case 2:return n.sent(),this.attempt=1,c().debug("Successfully flushed ".concat(e.length," events from queue")),[3,4];case 3:return n.sent(),this.trackingHost!==this.trackingHostFallback&&(c().debug("Using fallback tracking host ".concat(this.trackingHostFallback," instead of ").concat(this.trackingHost," on ").concat(re)),this.trackingHost=this.trackingHostFallback),(e=e.map((function(e){return[e[0],e[1]+1]})).filter((function(e){return!(e[1]>=r.maxSendAttempts)||(c().error("Dropping queued event after ".concat(e[1]," attempts since max send attempts ").concat(r.maxSendAttempts," reached. See logs for details")),!1)}))).length>0?((t=this.queue).push.apply(t,e),this.scheduleFlush()):this.attempt=1,[3,4];case 4:return[2]}}))}))},r.prototype.postHandle=function(e,t){if("strict"===this.cookiePolicy||"comply"===this.cookiePolicy){if(200===e){var n=t;if("string"==typeof t&&(n=JSON.parse(t)),!n.delete_cookie)return}this.userIdPersistence.delete(),this.propsPersistance.delete(),v(this.idCookieName)}if(200===e){n=t;if("string"==typeof t&&t.length>0){var r=(n=JSON.parse(t)).jitsu_sdk_extras;if(r&&r.length>0)if(i())for(var o=0,s=r;o<s.length;o++){var a=s[o],u=a.type,l=a.id,p=a.value;if("tag"===u){var d=document.createElement("div");d.id=l,f(d,p),d.childElementCount>0&&document.body.appendChild(d)}}else c().error("Tags destination supported only in browser environment")}}},r.prototype.getCtx=function(t){var n=new Date,r=t.describeClient()||{},i=e({},this.userProperties),o=i.company||{};delete i.company;var s,a,c=e(e({event_id:"",user:e({anonymous_id:"strict"!==this.cookiePolicy?t.getAnonymousId({name:this.idCookieName,domain:this.cookieDomain}):""},i),ids:this._getIds(),utc_time:(s=n.toISOString(),a=s.split(".")[1],a?a.length>=7?s:s.slice(0,-1)+"0".repeat(7-a.length)+"Z":s),local_tz_offset:n.getTimezoneOffset()},r),function(e){var t={utm:{},click_id:{}};for(var n in e)if(e.hasOwnProperty(n)){var r=e[n],i=b[n];i?t.utm[i]=r:k[n]&&(t.click_id[n]=r)}return t}(function(e){if(!e)return{};for(var t=e.length>0&&"?"===e.charAt(0)?e.substring(1):e,n={},r=("?"===t[0]?t.substr(1):t).split("&"),i=0;i<r.length;i++){var o=r[i].split("=");n[decodeURIComponent(o[0])]=decodeURIComponent(o[1]||"")}return n}(r.doc_search)));return Object.keys(o).length&&(c.company=o),c},r.prototype._getIds=function(){if(!i())return{};for(var e=function(e){if(void 0===e&&(e=!1),e&&p)return p;var t=d(document.cookie);return p=t,t}(!1),t={},n=0,r=Object.entries(e);n<r.length;n++){var o=r[n],s=o[0],a=o[1];this._3pCookies[s]&&(t["_"==s.charAt(0)?s.substr(1):s]=a)}return t},r.prototype.pathMatches=function(e,t){return new URL(t).pathname.match(new RegExp("^"+e.trim().replace(/\*\*/g,".*").replace(/([^\.])\*/g,"$1[^\\s/]*")+"/?$"))},r.prototype.track=function(e,t){var n=this,r=t||{};c().debug("track event of type",e,r);var o=i()?fe():me(),s=this.getCtx(o);if(this.config&&this.config.exclude&&this.config.exclude.length>1&&(null==s?void 0:s.url)&&this.config.exclude.split(",").some((function(e){return n.pathMatches(e.trim(),null==s?void 0:s.url)})))return void c().debug("Page is excluded from tracking");var a=t||{};"$autocapture"!==e&&"user_identify"!==e&&"pageview"!==e&&"$pageleave"!==e&&(a={event_attributes:t});var u=this.makeEvent(e,this.compatMode?"eventn":"usermaven",a);return this.sendJson(u)},r.prototype.init=function(r){var o,l,p,d,h,f,m,g=this;if(i()&&!r.force_use_fetch)r.fetch&&c().warn("Custom fetch implementation is provided to Usermaven. However, it will be ignored since Usermaven runs in browser"),this.transport=this.beaconApi?ae:ge;else{if(!r.fetch&&!globalThis.fetch)throw new Error("Usermaven runs in Node environment. However, neither UsermavenOptions.fetch is provided, nor global fetch function is defined. \nPlease, provide custom fetch implementation. You can get it via node-fetch package");this.transport=(h=r.fetch||globalThis.fetch,function(r,i,o,s){return void 0===s&&(s=function(e,t){}),t(void 0,void 0,void 0,(function(){var t,a,u,l,p,d,f,m;return n(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,h(r,{method:"POST",headers:e({Accept:"application/json","Content-Type":"application/json"},o||{}),body:i})];case 1:return t=n.sent(),[3,3];case 2:return a=n.sent(),c().error("Failed to send data to ".concat(r,": ").concat((null==a?void 0:a.message)||"unknown error"),i,a),s(-1,{}),[2];case 3:if(200!==t.status)return c().warn("Failed to send data to ".concat(r," (#").concat(t.status," - ").concat(t.statusText,")"),i),s(t.status,{}),[2];u={},l="",p=null!==(m=null===(f=t.headers)||void 0===f?void 0:f.get("Content-Type"))&&void 0!==m?m:"",n.label=4;case 4:return n.trys.push([4,6,,7]),[4,t.text()];case 5:return l=n.sent(),u=JSON.parse(l),[3,7];case 6:return d=n.sent(),c().error("Failed to parse ".concat(r," response. Content-type: ").concat(p," text: ").concat(l),d),[3,7];case 7:try{s(t.status,u)}catch(e){c().error("Failed to handle ".concat(r," response. Content-type: ").concat(p," text: ").concat(l),e)}return[2]}}))}))})}if(r.custom_headers&&"function"==typeof r.custom_headers?this.customHeaders=r.custom_headers:r.custom_headers&&(this.customHeaders=function(){return r.custom_headers}),"echo"===r.tracking_host&&(c().warn('jitsuClient is configured with "echo" transport. Outgoing requests will be written to console'),this.transport=ce),r.ip_policy&&(this.ipPolicy=r.ip_policy),r.cookie_policy&&(this.cookiePolicy=r.cookie_policy),"strict"===r.privacy_policy&&(this.ipPolicy="strict",this.cookiePolicy="strict"),r.use_beacon_api&&navigator.sendBeacon&&(this.beaconApi=!0),"comply"===this.cookiePolicy&&this.beaconApi&&(this.cookiePolicy="strict"),r.log_level&&(f=r.log_level,(m=s[f.toLocaleUpperCase()])||(console.warn("Can't find log level with name ".concat(f.toLocaleUpperCase(),", defaulting to INFO")),m=s.INFO),a=u(m)),this.initialOptions=r,c().debug("Initializing Usemaven Tracker tracker",r,oe),r.key){if(this.compatMode=void 0!==r.compat_mode&&!!r.compat_mode,this.cookieDomain=r.cookie_domain||function(){if(i())return".".concat((e=location.hostname,t=function(e){return(e.indexOf("//")>-1?e.split("/")[2]:e.split("/")[0]).split(":")[0].split("?")[0]}(e),n=t.split("."),(r=n.length)>2&&(t=n[r-2]+"."+n[r-1],2==n[r-2].length&&2==n[r-1].length&&(t=n[r-3]+"."+t)),t));var e,t,n,r}(),this.trackingHost=function(e){for(;n="/",-1!==(t=e).indexOf(n,t.length-n.length);)e=e.substr(0,e.length-1);var t,n;return 0===e.indexOf("https://")||0===e.indexOf("http://")?e:"https://"+e}(r.tracking_host||"t.usermaven.com"),this.randomizeUrl=r.randomize_url||!1,this.apiKey=r.key,this.idCookieName=r.cookie_name||"__eventn_id_".concat(r.key),"strict"===this.cookiePolicy?this.propsPersistance=new pe:this.propsPersistance=i()?new le(this.cookieDomain,this.idCookieName+"_props"):new pe,"strict"===this.cookiePolicy?this.userIdPersistence=new pe:this.userIdPersistence=i()?new le(this.cookieDomain,this.idCookieName+"_usr"):new pe,this.propsPersistance){var v=this.propsPersistance.restore();v&&(this.permanentProperties=v,this.permanentProperties.globalProps=null!==(o=v.globalProps)&&void 0!==o?o:{},this.permanentProperties.propsPerEvent=null!==(l=v.propsPerEvent)&&void 0!==l?l:{}),c().debug("Restored persistent properties",this.permanentProperties)}this.propertyBlacklist=r.property_blacklist&&r.property_blacklist.length>0?r.property_blacklist:[];this.config=D({},{autocapture:!1,properties_string_max_length:null,property_blacklist:[],sanitize_properties:null},r||{},this.config||{},{token:this.apiKey}),c().debug("Default Configuration",this.config),this.manageAutoCapture(this.config),!1===r.capture_3rd_party_cookies?this._3pCookies={}:(r.capture_3rd_party_cookies||["_ga","_fbp","_ym_uid","ajs_user_id","ajs_anonymous_id"]).forEach((function(e){return g._3pCookies[e]=!0})),r.ga_hook&&c().warn("GA event interceptor isn't supported anymore"),r.segment_hook&&function(e){var t=window;t.analytics||(t.analytics=[]);e.interceptAnalytics(t.analytics)}(this),i()&&(r.disable_event_persistence||(this.queue=new P("jitsu-event-queue"),this.scheduleFlush(0)),window.addEventListener("beforeunload",(function(){return g.flush()}))),this.retryTimeout=[null!==(p=r.min_send_timeout)&&void 0!==p?p:this.retryTimeout[0],null!==(d=r.max_send_timeout)&&void 0!==d?d:this.retryTimeout[1]],r.max_send_attempts&&(this.maxSendAttempts=r.max_send_attempts),this.initialized=!0}else c().error("Can't initialize Usemaven, key property is not set")},r.prototype.interceptAnalytics=function(t){var n=this,r=function(t){var r;try{var i=e({},t.payload);c().debug("Intercepted segment payload",i.obj);var o=t.integrations["Segment.io"];if(o&&o.analytics){var s=o.analytics;"function"==typeof s.user&&s.user()&&"function"==typeof s.user().id&&(i.obj.userId=s.user().id())}(null===(r=null==i?void 0:i.obj)||void 0===r?void 0:r.timestamp)&&(i.obj.sentAt=i.obj.timestamp);var a=t.payload.type();"track"===a&&(a=t.payload.event()),n._send3p("ajs",i,a)}catch(e){c().warn("Failed to send an event",e)}t.next(t.payload)};"function"==typeof t.addSourceMiddleware?(c().debug("Analytics.js is initialized, calling addSourceMiddleware"),t.addSourceMiddleware(r)):(c().debug("Analytics.js is not initialized, pushing addSourceMiddleware to callstack"),t.push(["addSourceMiddleware",r])),t.__en_intercepted=!0},r.prototype.restoreId=function(){if(this.userIdPersistence){var t=this.userIdPersistence.restore();t&&(this.userProperties=e(e({},t),this.userProperties))}},r.prototype.set=function(t,n){var r,i=null==n?void 0:n.eventType,o=void 0===(null==n?void 0:n.persist)||(null==n?void 0:n.persist);if(void 0!==i){var s=null!==(r=this.permanentProperties.propsPerEvent[i])&&void 0!==r?r:{};this.permanentProperties.propsPerEvent[i]=e(e({},s),t)}else this.permanentProperties.globalProps=e(e({},this.permanentProperties.globalProps),t);this.propsPersistance&&o&&this.propsPersistance.save(this.permanentProperties)},r.prototype.unset=function(e,t){o();var n=null==t?void 0:t.eventType,r=void 0===(null==t?void 0:t.persist)||(null==t?void 0:t.persist);n?this.permanentProperties.propsPerEvent[n]&&delete this.permanentProperties.propsPerEvent[n][e]:delete this.permanentProperties.globalProps[e],this.propsPersistance&&r&&this.propsPersistance.save(this.permanentProperties)},r.prototype.manageAutoCapture=function(e){if(c().debug("Auto Capture Status: ",this.config.autocapture),this.__autocapture_enabled=this.config.autocapture,this.__autocapture_enabled){ne.enabledForProject(this.apiKey,100,100)?ne.isBrowserSupported()?(c().debug("Autocapture enabled..."),ne.init(this,e)):(this.config.autocapture=!1,this.__autocapture_enabled=!1,c().debug("Disabling Automatic Event Collection because this browser is not supported")):(this.config.autocapture=!1,this.__autocapture_enabled=!1,c().debug("Not in active bucket: disabling Automatic Event Collection."))}},r.prototype.capture=function(e,t){var n,r;if(void 0===t&&(t={}),this.initialized)if($(e)||"string"!=typeof e)console.error("No event name provided to usermaven.capture");else{var i={event:e+(t.$event_type?"_"+t.$event_type:""),properties:this._calculate_event_properties(e,t)};(null===(r=null===(n=(i=q(i,this.get_config("properties_string_max_length"))).properties)||void 0===n?void 0:n.autocapture_attributes)||void 0===r?void 0:r.tag_name)&&this.track("$autocapture",i.properties),"$scroll"===e&&this.track(e,i.properties)}else console.error("Trying to capture event before initialization")},r.prototype._calculate_event_properties=function(e,t){var n,r,i=t||{};if("$snapshot"===e||"$scroll"===e)return i;O(this.propertyBlacklist)?j(this.propertyBlacklist,(function(e){delete i[e]})):console.error("Invalid value for property_blacklist config: "+this.propertyBlacklist);var o={},s=i.$elements||[];return s.length&&(o=s[0]),i.autocapture_attributes=o,i.autocapture_attributes.el_text=null!==(n=i.autocapture_attributes.$el_text)&&void 0!==n?n:"",i.autocapture_attributes.event_type=null!==(r=i.$event_type)&&void 0!==r?r:"",["$ce_version","$event_type","$initial_referrer","$initial_referring_domain","$referrer","$referring_domain","$elements"].forEach((function(e){delete i[e]})),delete i.autocapture_attributes.$el_text,delete i.autocapture_attributes.nth_child,delete i.autocapture_attributes.nth_of_type,i},r}();var ye=["use_beacon_api","cookie_domain","tracking_host","cookie_name","key","ga_hook","segment_hook","randomize_url","capture_3rd_party_cookies","id_method","log_level","compat_mode","privacy_policy","cookie_policy","ip_policy","custom_headers","force_use_fetch","min_send_timeout","max_send_timeout","max_send_attempts","disable_event_persistence","project_id","autocapture","properties_string_max_length","property_blacklist","exclude"];var _e="data-suppress-interception-warning";function be(e){return"\n ATTENTION! ".concat(e,"-hook set to true along with defer/async attribute! If ").concat(e," code is inserted right after Usermaven tag,\n first tracking call might not be intercepted! Consider one of the following:\n - Inject usermaven tracking code without defer/async attribute\n - If you're sure that events won't be sent to ").concat(e," before Usermaven is fully initialized, set ").concat(_e,'="true"\n script attribute\n ')}function ke(e,t){c().debug("Processing queue",e);for(var n=0;n<e.length;n+=1){var i=r([],e[n],!0)||[],o=i[0],s=i.slice(1),a=t[o];"function"==typeof a&&a.apply(t,s)}e.length=0}if(window){var we=window,Pe=function(e){var t=document.currentScript||document.querySelector("script[src*=jsFileName][data-usermaven-api-key]");if(t){var n,r={tracking_host:(n=t.getAttribute("src"),n.replace("/s/lib.js","").replace("/lib.js","")),key:null};ye.forEach((function(e){var n="data-"+e.replace(new RegExp("_","g"),"-");if(void 0!==t.getAttribute(n)&&null!==t.getAttribute(n)){var i=t.getAttribute(n);"true"===i?i=!0:"false"===i&&(i=!1),r[e]=i}})),e.usermavenClient=function(e){var t=new ve;return t.init(e),t}(r),!r.segment_hook||null===t.getAttribute("defer")&&null===t.getAttribute("async")||null!==t.getAttribute(_e)||c().warn(be("segment")),!r.ga_hook||null===t.getAttribute("defer")&&null===t.getAttribute("async")||null!==t.getAttribute(_e)||c().warn(be("ga"));var i=function(){var t=e.usermavenQ=e.usermavenQ||[];t.push(arguments),ke(t,e.usermavenClient)};return e.usermaven=i,r.project_id&&i("set",{project_id:r.project_id}),"true"!==t.getAttribute("data-init-only")&&"yes"!==t.getAttribute("data-init-only")&&i("track","pageview"),document.addEventListener("visibilitychange",(function(e){"visibilitychange"===e.type&&"hidden"===document.visibilityState&&i("track","$pageleave")}),!1),e.usermavenClient}c().warn("Usermaven script is not properly initialized. The definition must contain data-usermaven-api-key as a parameter")}(we);Pe?(c().debug("Usermaven in-browser tracker has been initialized"),we.usermaven=function(){var e=we.usermavenQ=we.usermavenQ||[];e.push(arguments),ke(e,Pe)},we.usermavenQ&&(c().debug("Initial queue size of ".concat(we.usermavenQ.length," will be processed")),ke(we.usermavenQ,Pe))):c().error("Usermaven tracker has not been initialized (reason unknown)")}else c().warn("Usermaven tracker called outside browser context. It will be ignored")}();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usermaven/sdk-js",
3
- "version": "1.1.8",
3
+ "version": "1.2.0",
4
4
  "description": "Usermaven JavaScript SDK.",
5
5
  "main": "dist/npm/usermaven.cjs.js",
6
6
  "module": "dist/npm/dist/usermaven.es.js",