@usermaven/sdk-js 1.4.1-rc.58 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +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={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}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=void 0){const t=!!globalThis.window&&!!globalThis.window.document&&!!globalThis.window.location;return!t&&e&&c().warn(e),t}function o(e=void 0){if(!i())throw new Error(e||"window' is not available. Seems like this code runs outside browser environment. It shouldn't happen");return window}"function"==typeof SuppressedError&&SuppressedError;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-"+t+"] "+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=e+"="+encodeURIComponent(t);if(i&&(p+="; domain="+i),p+=o?"; path="+o:"; path=/",s&&(p+="; expires="+s.toUTCString()),r&&(p+="; max-age="+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"}else u&&(p+="; SameSite=None");return p}catch(e){return c().error("serializeCookie",e),""}}var p,d=function(){if(i())return function(e){var t=e.split(".");if(4===t.length&&t.every((function(e){return!isNaN(e)})))return e;var n=function(e){var t=e.match(/[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i);return t?t[0]:""}(e);return n||(n=function(e){var t=function(e){return(e.indexOf("//")>-1?e.split("/")[2]:e.split("/")[0]).split(":")[0].split("?")[0]}(e),n=t.split("."),r=n.length;return r>2&&(2==n[r-1].length?(t=n[r-2]+"."+n[r-1],2==n[r-2].length&&(t=n[r-3]+"."+t)):t=n[r-2]+"."+n[r-1]),t}(e)),n}(window.location.hostname)};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 g=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},v=function(e,t,n){void 0===n&&(n={}),o().document.cookie=l(e,t,n)},y=function(e,t){void 0===t&&(t="/"),document.cookie=e+"= ; SameSite=Strict; 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)},k={utm_source:"source",utm_medium:"medium",utm_campaign:"campaign",utm_term:"term",utm_content:"content"},w={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}(),S=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,N=x.toString,E=x.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 D=function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")};function L(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 j=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")}}(),M=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)}}},z="undefined"!=typeof Symbol?Symbol("__deepCircularCopyInProgress__"):"__deepCircularCopyInProgress__";function R(e,t,n){return e!==Object(e)?t?t(e,n):e:e[z]?void 0:(e[z]=!0,T(e)?(r=[],I(e,(function(e){r.push(R(e,t))}))):(r={},L(e,(function(e,n){n!==z&&(r[n]=R(e,t,n))}))),delete e[z],r);var r}var q=["$performance_raw"];function J(e,t){return R(e,(function(e,n){return n&&q.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&&L(e.childNodes,(function(e){K(e)&&e.textContent&&(t+=D(e.textContent).split(/(\s+)/).filter(ee).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))})),D(t)}function W(e){return!!e&&1===e.nodeType}function G(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function K(e){return!!e&&3===e.nodeType}function Q(e){return!!e&&11===e.nodeType}var Y=["a","button","form","input","select","textarea","label"];function X(e){for(var t=e;t.parentNode&&!G(t,"body");t=t.parentNode){var n=B(t).split(" ");if(H(n,"ph-sensitive")||H(n,"ph-no-capture"))return!1}if(H(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!!(G(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||G(e,"select")||G(e,"textarea")||"true"===e.getAttribute("contenteditable"))}function ee(e){if(null===e||$(e))return!1;if("string"==typeof e){e=D(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}))),L(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 L(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 L(this._customProperties,(function(r){L(r.event_selectors,(function(i){L(document.querySelectorAll(i),(function(i){H(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(K(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||G(e,"html")||!W(e))return!1;for(var n=e;n&&!G(n,"body");){if(n.classList&&n.classList.contains("um-no-capture"))return!1;n=n.parentNode&&Q(n.parentNode)?n.parentNode.host:n.parentNode}var r=!1;for(n=e;n&&!G(n,"body");)if(n.parentNode&&Q(n.parentNode))(n=n.parentNode.host)&&Y.indexOf(n.tagName.toLowerCase())>-1&&(r=!0);else{var i=n.parentNode;if(!i)break;if(Y.indexOf(i.tagName.toLowerCase())>-1)r=!0;else{var o=window.getComputedStyle(i);o&&"pointer"===o.getPropertyValue("cursor")&&(r=!0)}n=i}var s=window.getComputedStyle(e);if(s&&"pointer"===s.getPropertyValue("cursor")&&"click"===t.type)return!0;var a=e.tagName.toLowerCase();switch(a){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 r?"click"===t.type:"click"===t.type&&(Y.indexOf(a)>-1||"true"===e.getAttribute("contenteditable"))}}(o,e)){for(var s=[o],a=o;a.parentNode&&!G(a,"body");)Q(a.parentNode)?(s.push(a.parentNode.host),a=a.parentNode.host):(s.push(a.parentNode),a=a.parentNode);var c,u=[],l=!1;if(L(s,(function(e){var t=X(e);"a"===e.tagName.toLowerCase()&&(c=e.getAttribute("href"),c=t&&ee(c)&&c),H(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=j(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=$(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))}(re),function(e){for(var t in e)"function"==typeof e[t]&&(e[t]=M(e[t]))}(re);var ie=function(){function e(e,t){void 0===t&&(t="all"),this.instance=e,this.trackingType=t,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",this.track.bind(this)):this.track()}return e.prototype.track=function(){var e=this;this.formElements=document.querySelectorAll("form"),"tagged"===this.trackingType&&(this.formElements=document.querySelectorAll("form[data-um-form]")),this.formElements.forEach((function(t){t.addEventListener("submit",(function(t){var n=t.target,r=e._getFormDetails(n);e.instance.capture("$form",function(e){for(var t in e)(""===e[t]||null===e[t]||void 0===e[t]||"object"==typeof e[t]&&0===Object.keys(e[t]).length)&&delete e[t];return e}(r))}))}))},e.getInstance=function(t,n){return void 0===n&&(n="all"),e.instance||(e.instance=new e(t,n)),e.instance},e.prototype._getFormDetails=function(e){var t=this,n={form_id:e.id,form_name:e.name||"",form_action:e.action,form_method:e.method},r=e.querySelectorAll("input, select, textarea");return Array.from(r).filter((function(e){return!e.classList.contains("um-no-capture")})).forEach((function(e,r){var i=t._getFieldProps(e,r);Object.assign(n,i)})),n},e.prototype._getFieldProps=function(e,t){var n,r=Object.keys(e.dataset).length?JSON.stringify(e.dataset):void 0,i=this.getSafeText(e);return(n={})["field_"+(t+1)+"_tag"]=e.tagName.toLowerCase(),n["field_"+(t+1)+"_type"]=e instanceof HTMLInputElement?e.type:void 0,n["field_"+(t+1)+"_data_attributes"]=r,n["field_"+(t+1)+"_id"]=e.id,n["field_"+(t+1)+"_value"]=i,n["field_"+(t+1)+"_class"]=e.className,n["field_"+(t+1)+"_name"]=e.name,n},e.prototype.getSafeText=function(e){var t="";if("value"in e&&"password"!==e.type)t=e.value;else if(e.hasChildNodes()){t=Array.from(e.childNodes).filter((function(e){return e.nodeType===Node.TEXT_NODE})).map((function(e){return e.textContent})).join("")}else t=e.textContent||"";return this._scrubPotentiallySensitiveValues(t)},e.prototype._scrubPotentiallySensitiveValues=function(e){return this._shouldCaptureValue(e)?e:"<redacted>"},e.prototype._shouldCaptureValue=function(e){if(this._isNullish(e))return!1;if(this._isString(e)){e=this._trim(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},e.prototype._isNullish=function(e){return null==e},e.prototype._isString=function(e){return"string"==typeof e||e instanceof String},e.prototype._trim=function(e){return e.trim().replace(/^\s+|\s+$/g,"")},e}(),oe="production",se="1.4.1"+"/"+oe+"@"+"2024-11-12T08:10:12.027Z",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 "+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){v(this.cookieName,JSON.stringify(e),{domain:this.cookieDomain,secure:"http:"!==document.location.protocol,maxAge:ae})},e.prototype.restore=function(){le(this.cookieName);var e=g(this.cookieName);if(e)try{var t=JSON.parse(decodeURIComponent(e));return"object"!=typeof t?void c().warn("Can't restore value of "+this.cookieName+"@"+this.cookieDomain+", expected to be object, but found "+("object"!=typeof t)+": "+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,r=e.crossDomainLinking,i=void 0===r||r;if(le(t),i){var o=new URLSearchParams(window.location.search).get("_um"),s=window.location.hash.substring(1).split("~"),a=s.length>1?s[1]:void 0,u=o||a;if(u){c().debug("Existing user id from other domain",u);var l=g(t);return l&&l===u||v(t,u,{domain:n,secure:"http:"!==document.location.protocol,maxAge:ae}),u}}var p=g(t);if(p)return c().debug("Existing user id",p),p;var d=_();return c().debug("New user id",d),v(t,d,{domain:n,secure:"http:"!==document.location.protocol,maxAge:ae}),d}};var fe={getSourceIp:function(){},describeClient:function(){return{}},getAnonymousId:function(){return""}},me=function(){return he},ge=function(){return fe},ve=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 "+e+": "+((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 "+e+" (#"+i.status+" - "+i.statusText+")",t),s(new Error("Failed to send JSON. Error code: "+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.groupProperties={},this.permanentProperties={globalProps:{},propsPerEvent:{}},this.cookieDomain="",this.trackingHost="",this.idCookieName="",this.randomizeUrl=!1,this.namespace="usermaven",this.crossDomainLinking=!0,this.formTracking=!1,this.domains=[],this.apiKey="",this.initialized=!1,this._3pCookies={},this.cookiePolicy="keep",this.ipPolicy="keep",this.beaconApi=!1,this.transport=ve,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,this.__auto_pageview_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=g(this.idCookieName);t&&(c().debug("Removing id cookie",t),v(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()?me():ge()),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 n="false","undefined"!=typeof window&&window.localStorage&&(n=localStorage.getItem("um_exclusion")),null!=n&&"false"!==n?[3,3]: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]}var n}))}))},r.prototype.doSendJson=function(e){var t=this,n="keep"!==this.cookiePolicy?"&cookie_policy="+this.cookiePolicy:"",r="keep"!==this.ipPolicy?"&ip_policy="+this.ipPolicy:"",o=i()?"/api/v1/event":"/api/v1/s2s/event",s=""+this.trackingHost+o+"?token="+this.apiKey+n+r;this.randomizeUrl&&(s=this.trackingHost+"/api."+b()+"?p_"+b()+"="+this.apiKey+n+r);var a=JSON.stringify(e);return c().debug("Sending payload to "+s,e.length),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 "+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 "+e.length+" events from queue"),[3,4];case 3:return n.sent(),this.trackingHost!==this.trackingHostFallback&&(c().debug("Using fallback tracking host "+this.trackingHostFallback+" instead of "+this.trackingHost+" on "+oe),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 "+e[1]+" attempts since max send attempts "+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=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,crossDomainLinking:this.crossDomainLinking}):""},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=k[n];i?t.utm[i]=r:w[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=h(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()?me():ge(),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,h,f,m,g,v,y,_=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:ve;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=(g=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,h,f;return n(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,g(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 "+r+": "+((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 "+r+" (#"+t.status+" - "+t.statusText+")",i),s(t.status,{}),[2];u={},l="",p=null!==(f=null===(h=t.headers)||void 0===h?void 0:h.get("Content-Type"))&&void 0!==f?f:"",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 "+r+" response. Content-type: "+p+" text: "+l,d),[3,7];case 7:try{s(t.status,u)}catch(e){c().error("Failed to handle "+r+" response. Content-type: "+p+" text: "+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&&(v=r.log_level,(y=s[v.toLocaleUpperCase()])||(console.warn("Can't find log level with name "+v.toLocaleUpperCase()+", defaulting to INFO"),y=s.INFO),a=u(y)),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||d(),this.namespace=r.namespace||"usermaven",this.crossDomainLinking=null===(o=r.cross_domain_linking)||void 0===o||o,this.formTracking=null!==(l=r.form_tracking)&&void 0!==l&&l,this.domains=r.domains?r.domains.split(",").map((function(e){return e.trim()})):[],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.__auto_pageview_enabled=r.auto_pageview||!1,this.idCookieName=r.cookie_name||"__eventn_id_"+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 b=this.propsPersistance.restore();b&&(this.permanentProperties=b,this.permanentProperties.globalProps=null!==(p=b.globalProps)&&void 0!==p?p:{},this.permanentProperties.propsPerEvent=null!==(h=b.propsPerEvent)&&void 0!==h?h:{}),c().debug("Restored persistent properties",this.permanentProperties)}this.propertyBlacklist=r.property_blacklist&&r.property_blacklist.length>0?r.property_blacklist:[];this.config=j({},{autocapture:!1,properties_string_max_length:null,property_blacklist:[],sanitize_properties:null,auto_pageview:!1},r||{},this.config||{},{token:this.apiKey}),c().debug("Default Configuration",this.config),this.manageAutoCapture(this.config),this.manageFormTracking(this.config),this.manageCrossDomainLinking({cross_domain_linking:this.crossDomainLinking,domains:this.domains,cookiePolicy:this.cookiePolicy}),!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 _._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 S(this.namespace+"-event-queue"),this.scheduleFlush(0)),window.addEventListener("beforeunload",(function(){return _.flush()}))),this.__auto_pageview_enabled&&function(e){var t=function(){return e.track("pageview")},n=history.pushState;n&&(history.pushState=function(e,r,i){n.apply(this,[e,r,i]),t()},addEventListener("popstate",t));addEventListener("hashchange",t)}(this),this.retryTimeout=[null!==(f=r.min_send_timeout)&&void 0!==f?f:this.retryTimeout[0],null!==(m=r.max_send_timeout)&&void 0!==m?m: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.manageCrossDomainLinking=function(e){if(!i()||!e.cross_domain_linking||0===e.domains.length||"strict"===e.cookiePolicy)return!1;var t=this.idCookieName,n=e.domains||[];document.addEventListener("click",(function(e){var r=function(e){for(;e&&e.tagName;){if("a"==e.tagName.toLowerCase())return e;e=e.parentNode}return null}(e.target);if(r){var i=(null==r?void 0:r.hasAttribute("href"))?null==r?void 0:r.getAttribute("href"):"";if(i&&i.startsWith("http")){var o=new URL(i),s=g(t);if(o.hostname===window.location.hostname)return;n.includes(o.hostname)&&s&&(o.searchParams.append("_um",s),r.setAttribute("href",o.toString()))}}}),!1)},r.prototype.manageAutoCapture=function(e){if(c().debug("Auto Capture Status: ",this.config.autocapture),this.__autocapture_enabled=this.config.autocapture&&i(),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.manageFormTracking=function(e){if(i()&&this.formTracking&&"none"!==this.formTracking){c().debug("Form tracking enabled...");var t=!0===this.formTracking?"all":this.formTracking;ie.getInstance(this,t).track()}},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=J(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),"$form"===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||"$form"===e)return i;T(this.propertyBlacklist)?L(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="lib.js",be=["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","auto_pageview","namespace","cross_domain_linking","domains","form_tracking"];var ke="data-suppress-interception-warning";function we(e){return"\n ATTENTION! "+e+"-hook set to true along with defer/async attribute! If "+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 "+e+" before Usermaven is fully initialized, set "+ke+'="true"\n script attribute\n '}function Pe(e){var t=document.currentScript;if(t){var n,r={tracking_host:(n=t.getAttribute("src"),n.replace("/s/"+_e,"").replace("/"+_e,"")),key:null},i=t.getAttribute("data-namespace")||"usermaven";be.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}}));var o=i+"Client";e[o]=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(ke)||c().warn(we("segment")),!r.ga_hook||null===t.getAttribute("defer")&&null===t.getAttribute("async")||null!==t.getAttribute(ke)||c().warn(we("ga")),!function(t,n){e[t]=function(){var r=e[t+"Q"]=e[t+"Q"]||[];r.push(arguments),Se(r,e[n])}}(i,o),r.project_id&&e[i]("set",{project_id:r.project_id}),"true"!==t.getAttribute("data-init-only")&&"yes"!==t.getAttribute("data-init-only")&&e[i]("track","pageview");var s="beforeunload";return(navigator.userAgent.match(/iPad/i)||navigator.userAgent.match(/iPhone/i))&&(s="pagehide"),e.addEventListener(s,(function(){e[i]("track","$pageleave")})),e[o]}c().warn("Usermaven script is not properly initialized. The definition must contain data-usermaven-api-key as a parameter")}function Se(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}!function(e){if(window){var t=window,n=e,r=Pe(t);r?(c().debug("Usermaven in-browser tracker has been initialized",n),t[n]=function(){var e=t[n+"Q"]=t[n+"Q"]||[];e.push(arguments),Se(e,r)},t[n+"Q"]&&(c().debug("Initial queue size of "+t[n+"Q"].length+" will be processed"),Se(t[n+"Q"],r))):c().error("Usermaven tracker has not been initialized (reason unknown)")}else c().warn("Usermaven tracker called outside browser context. It will be ignored")}(document.currentScript.getAttribute("data-namespace")||"usermaven")}();
package/package.json CHANGED
@@ -1,56 +1,57 @@
1
1
  {
2
2
  "name": "@usermaven/sdk-js",
3
- "version": "1.4.1-rc.58",
4
- "description": "Usermaven JavaScript SDK",
5
- "main": "dist/lib.js",
6
- "module": "dist/usermaven.es.js",
7
- "types": "dist/index.d.ts",
3
+ "version": "1.4.1",
4
+ "description": "Usermaven JavaScript SDK.",
5
+ "main": "dist/npm/usermaven.cjs.js",
6
+ "module": "dist/npm/usermaven.es.js",
7
+ "types": "dist/npm/usermaven.d.ts",
8
8
  "files": [
9
- "dist"
10
- ],
11
- "keywords": [
12
- "usermaven",
13
- "analytics",
14
- "tracking"
9
+ "dist/npm/*",
10
+ "dist/web/*"
15
11
  ],
12
+ "author": "Usermaven <hello@usermaven.com>",
13
+ "scripts": {
14
+ "clean": "rm -rf ./dist",
15
+ "devserver": "PORT=8081 nodemon --watch '__tests__/common/*.ts' --exec 'ts-node' __tests__/common/devserver.ts",
16
+ "test": "rollup -c && jest --detectOpenHandles --verbose false",
17
+ "build": "rollup -c"
18
+ },
19
+ "jest": {
20
+ "testEnvironment": "node",
21
+ "testMatch": [
22
+ "**/__tests__/*.spec.{ts,js}"
23
+ ],
24
+ "automock": false,
25
+ "verbose": false
26
+ },
16
27
  "license": "MIT",
17
28
  "devDependencies": {
18
- "@testing-library/dom": "^10.4.0",
19
- "@testing-library/jest-dom": "^6.5.0",
20
- "@types/jest": "^29.5.13",
21
- "@types/node": "^18.15.11",
22
- "@typescript-eslint/eslint-plugin": "^5.57.1",
23
- "@typescript-eslint/parser": "^5.57.1",
24
- "@vitest/coverage-v8": "^2.1.2",
25
- "body-parser": "^1.20.3",
26
- "chalk": "^5.3.0",
27
- "colors": "^1.4.0",
28
- "concurrently": "^9.0.1",
29
- "cors": "^2.8.5",
30
- "eslint": "^8.37.0",
31
- "express": "^4.21.0",
32
- "jsdom": "^25.0.1",
33
- "morgan": "^1.10.0",
34
- "prettier": "^2.8.7",
35
- "typescript": "^5.0.3",
36
- "vite": "^5.4.8",
37
- "vite-plugin-dts": "^4.2.3",
38
- "vitest": "^2.1.2",
39
- "wait-on": "^8.0.1",
40
- "winston": "^3.14.2"
29
+ "@babel/preset-env": "^7.13.12",
30
+ "@babel/preset-typescript": "^7.13.0",
31
+ "@rollup/plugin-babel": "^5.3.0",
32
+ "@rollup/plugin-replace": "^2.4.2",
33
+ "@types/express": "^4.17.13",
34
+ "@types/jest": "^26.0.22",
35
+ "body-parser": "^1.19.0",
36
+ "express": "^4.17.1",
37
+ "fetch-cookie": "^1.0.0",
38
+ "jest": "^27.3.1",
39
+ "jest-fetch-mock": "^3.0.3",
40
+ "jest-playwright-preset": "^1.7.0",
41
+ "next": "^12.0.8",
42
+ "node-fetch": "^3.1.0",
43
+ "nodemon": "^2.0.15",
44
+ "playwright": "^1.19.2",
45
+ "rollup": "^2.70.1",
46
+ "rollup-plugin-copy": "^3.4.0",
47
+ "rollup-plugin-terser": "^7.0.2",
48
+ "rollup-plugin-typescript": "^1.0.1",
49
+ "ts-jest": "^27.1.2",
50
+ "ts-node": "9.1.1",
51
+ "tslib": "^2.3.1",
52
+ "typescript": "4.4.3"
41
53
  },
42
- "scripts": {
43
- "dev": "vite build --watch",
44
- "build": "tsc && vite build",
45
- "preview": "vite preview",
46
- "test": "vitest run",
47
- "test:watch": "vitest",
48
- "test:coverage": "vitest run --coverage",
49
- "lint": "eslint . --ext .ts",
50
- "format": "prettier --write \"src/**/*.ts\"",
51
- "mock": "wait-on dist/lib.js && node server/mockServer.js",
52
- "example:build": "tsc examples/test.ts --outDir examples",
53
- "example:serve": "wait-on dist/lib.js && vite --config vite.config.ts",
54
- "start": "concurrently \"npm run dev\" \"npm run example:serve\" \"npm run mock\" "
54
+ "resolutions": {
55
+
55
56
  }
56
- }
57
+ }
@@ -1,57 +0,0 @@
1
- import { Config } from './config';
2
- import { CompanyProps, EventPayload, UserProps } from './types';
3
- import { Logger } from '../utils/logger';
4
- export declare class UsermavenClient {
5
- private config;
6
- private logger;
7
- private cookieManager?;
8
- private transport;
9
- private persistence;
10
- private autoCapture?;
11
- private formTracking?;
12
- private pageviewTracking?;
13
- private retryQueue;
14
- private anonymousId;
15
- private namespace;
16
- private rageClick?;
17
- constructor(config: Config);
18
- private initializeBrowserFeatures;
19
- /**
20
- * Recursively merge the provided configuration with the existing defaultConfig
21
- * @param config
22
- * @param defaultConfig
23
- */
24
- mergeConfig(config: Partial<Config>, defaultConfig: Partial<Config>): Config;
25
- init(config: Config): void;
26
- private manageCrossDomainLinking;
27
- private findClosestLink;
28
- private initializeTransport;
29
- private initializePersistence;
30
- private getOrCreateAnonymousId;
31
- private generateFingerprint;
32
- private hashString;
33
- id(userData: UserProps, doNotSendEvent?: boolean): Promise<void>;
34
- track(typeName: string, payload?: EventPayload, directSend?: boolean): void;
35
- private trackInternal;
36
- rawTrack(payload: any): void;
37
- group(props: CompanyProps, doNotSendEvent?: boolean): Promise<void>;
38
- private createEventPayload;
39
- private processAutocaptureAttributes;
40
- getCookie(name: string): string | null;
41
- private getThirdPartyIds;
42
- private getUtmParams;
43
- pageview(): void;
44
- private setupPageLeaveTracking;
45
- getConfig(): Config;
46
- getLogger(): Logger;
47
- reset(resetAnonId?: boolean): Promise<void>;
48
- set(properties: Record<string, any>, opts?: {
49
- eventType?: string;
50
- persist?: boolean;
51
- }): void;
52
- setUserId(userId: string): void;
53
- unset(propertyName: string, options?: {
54
- eventType?: string;
55
- persist?: boolean;
56
- }): void;
57
- }
@@ -1,37 +0,0 @@
1
- import { LogLevel } from '../utils/logger';
2
- export type Policy = 'strict' | 'keep' | 'comply';
3
- export interface Config {
4
- key: string;
5
- trackingHost: string;
6
- cookieDomain?: string;
7
- cookieName?: string;
8
- logLevel?: LogLevel;
9
- useBeaconApi?: boolean;
10
- forceUseFetch?: boolean;
11
- autocapture?: boolean;
12
- rageClick?: boolean;
13
- formTracking?: boolean | 'all' | 'tagged' | 'none';
14
- autoPageview?: boolean;
15
- disableEventPersistence?: boolean;
16
- gaHook?: boolean;
17
- segmentHook?: boolean;
18
- randomizeUrl?: boolean;
19
- capture3rdPartyCookies?: string[] | false;
20
- idMethod?: 'cookie' | 'localStorage';
21
- privacyPolicy?: 'strict';
22
- ipPolicy?: Policy;
23
- cookiePolicy?: Policy;
24
- customHeaders?: Record<string, string> | (() => Record<string, string>);
25
- minSendTimeout?: number;
26
- maxSendTimeout?: number;
27
- maxSendAttempts?: number;
28
- propertiesStringMaxLength?: number | null;
29
- propertyBlacklist?: string[];
30
- exclude?: string;
31
- namespace?: string;
32
- crossDomainLinking?: boolean;
33
- domains?: string;
34
- maskAllText?: boolean;
35
- maskAllElementAttributes?: boolean;
36
- }
37
- export declare const defaultConfig: Partial<Config>;
@@ -1,38 +0,0 @@
1
- export interface EventPayload {
2
- [key: string]: any;
3
- }
4
- export interface UserProps extends EventPayload {
5
- id?: string;
6
- email?: string;
7
- }
8
- export interface Transport {
9
- send(payload: any): Promise<void>;
10
- }
11
- export interface UserProps {
12
- id?: string;
13
- email?: string;
14
- [key: string]: any;
15
- }
16
- export type Policy = 'strict' | 'keep' | 'comply';
17
- export interface CompanyProps {
18
- id: string;
19
- name: string;
20
- created_at: string;
21
- [key: string]: any;
22
- }
23
- /**
24
- * Environment where the event have happened.
25
- */
26
- export type ClientProperties = {
27
- screen_resolution: string;
28
- user_agent: string;
29
- referer: string;
30
- url: string;
31
- page_title: string;
32
- doc_path: string;
33
- doc_host: string;
34
- doc_search: string;
35
- vp_size: string;
36
- user_language: string;
37
- doc_encoding: string;
38
- };
@@ -1,15 +0,0 @@
1
- import { UsermavenClient } from '../core/client';
2
- export declare class RageClick {
3
- private client;
4
- private clicks;
5
- private threshold;
6
- private timeWindow;
7
- private distanceThreshold;
8
- constructor(client: UsermavenClient);
9
- private initializeEventListener;
10
- private handleClick;
11
- private shouldCaptureElement;
12
- click(x: number, y: number, timestamp: number): void;
13
- private checkRageClick;
14
- private sendRageClickEvent;
15
- }
@@ -1,19 +0,0 @@
1
- import { UsermavenClient } from '../core/client';
2
- export declare class ScrollDepth {
3
- private client;
4
- private maxScrollDepth;
5
- private milestones;
6
- private lastScrollDepth;
7
- private documentElement;
8
- private debouncedHandleScroll;
9
- constructor(client: UsermavenClient);
10
- private initializeEventListener;
11
- track(): void;
12
- send(eventType?: string): void;
13
- private handleScroll;
14
- private getScrollDepth;
15
- private getWindowHeight;
16
- private getDocumentHeight;
17
- private getScrollDistance;
18
- private checkMilestones;
19
- }
package/dist/index.d.ts DELETED
@@ -1,6 +0,0 @@
1
- import { UsermavenClient } from './core/client';
2
- import { Config } from './core/config';
3
- import { LogLevel } from './utils/logger';
4
- import { UserProps, EventPayload, ClientProperties } from './core/types';
5
- declare function usermavenClient(config: Partial<Config>): UsermavenClient;
6
- export { usermavenClient, UsermavenClient, Config as UsermavenOptions, UserProps, EventPayload, LogLevel, ClientProperties };
package/dist/lib.js DELETED
@@ -1,2 +0,0 @@
1
- (function(f,g){typeof exports=="object"&&typeof module<"u"?g(exports):typeof define=="function"&&define.amd?define(["exports"],g):(f=typeof globalThis<"u"?globalThis:f||self,g(f.Usermaven={}))})(this,function(f){"use strict";var g=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s))(g||{});class X{constructor(e){this.level=e}debug(e,...t){this.level<=0&&console.debug("[Usermaven Debug]:",e,...t)}info(e,...t){this.level<=1&&console.info("[Usermaven Info]:",e,...t)}warn(e,...t){this.level<=2&&console.warn("[Usermaven Warning]:",e,...t)}error(e,...t){this.level<=3&&console.error("[Usermaven Error]:",e,...t)}}function h(s=0){return new X(s)}const N={logLevel:g.ERROR,useBeaconApi:!1,forceUseFetch:!1,trackingHost:"t.usermaven.com",autocapture:!1,rageClick:!1,formTracking:!1,autoPageview:!1,disableEventPersistence:!1,gaHook:!1,segmentHook:!1,randomizeUrl:!1,capture3rdPartyCookies:["_ga","_fbp","_ym_uid","ajs_user_id","ajs_anonymous_id"],idMethod:"cookie",ipPolicy:"keep",cookiePolicy:"keep",minSendTimeout:0,maxSendTimeout:2e3,maxSendAttempts:4,propertiesStringMaxLength:null,propertyBlacklist:[],crossDomainLinking:!0,maskAllText:!1,maskAllElementAttributes:!1};class K{constructor(e){this.domain=e,this.cookieDomain=this.getCookieDomain(),console.log(this.cookieDomain)}set(e,t,i=365,n=!0,r=!1){console.log("Setting cookie",e,t,i,n,r);const o=new Date;o.setTime(o.getTime()+i*24*60*60*1e3);const c=`expires=${o.toUTCString()}`,l=n?"; Secure":"",a=r?"; HttpOnly":"";document.cookie=`${e}=${t};${c};path=/;domain=${this.cookieDomain}${l}${a}`}get(e){const t=e+"=",i=document.cookie.split(";");for(let n=0;n<i.length;n++){let r=i[n].trim();if(r.indexOf(t)===0)return decodeURIComponent(r.substring(t.length))}return null}delete(e,t="/"){document.cookie=`${e}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${t};domain=${this.cookieDomain}`}getCookieDomain(){return typeof window>"u"||this.domain?this.domain||"":this.extractRoot(window.location.hostname)}extractRoot(e){if(this.isIpAddress(e)||e==="localhost")return e;let t=this.extractTopLevelDomain(e);return t||(t=this.extractRootDomain(e)),"."+t}isIpAddress(e){const t=e.split(".");return t.length===4&&t.every(i=>!isNaN(Number(i)))}extractHostname(e){let t;return e.indexOf("//")>-1?t=e.split("/")[2]:t=e.split("/")[0],t=t.split(":")[0],t=t.split("?")[0],t}extractRootDomain(e){let t=this.extractHostname(e);const i=t.split("."),n=i.length;return n>2&&(i[n-1].length==2?(t=i[n-2]+"."+i[n-1],i[n-2].length==2&&(t=i[n-3]+"."+t)):t=i[n-2]+"."+i[n-1]),t}extractTopLevelDomain(e){const t=/[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i,i=e.match(t);return i?i[0]:""}}const Z=Object.prototype.hasOwnProperty,b=Array.prototype.forEach,$={};function G(s,e,t){if(Array.isArray(s)){if(b&&s.forEach===b)s.forEach(e,t);else if("length"in s&&s.length===+s.length){for(let i=0,n=s.length;i<n;i++)if(i in s&&e.call(t,s[i],i)===$)return}}}const T=function(s){return s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},Y=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=s[e].bind(s))};function A(s,e,t){if(s!=null){if(b&&Array.isArray(s)&&s.forEach===b)s.forEach(e,t);else if("length"in s&&s.length===+s.length){for(let i=0,n=s.length;i<n;i++)if(i in s&&e.call(t,s[i],i)===$)return}else for(const i in s)if(Z.call(s,i)&&e.call(t,s[i],i)===$)return}}const j=function(s,...e){return G(e,function(t){for(const i in t)t[i]!==void 0&&(s[i]=t[i])}),s};function E(s,e){return s.indexOf(e)!==-1}const O=function(s){try{return/^\s*\bfunction\b/.test(s)}catch{return!1}},ee=function(s){return s===void 0},y=function(){const s=function(i,n,r,o,c){if(!i){h().error("No valid element provided to register_event");return}if(i.addEventListener&&!o)i.addEventListener(n,r,!!c);else{const l="on"+n,a=i[l];i[l]=e(i,r,a)}};function e(i,n,r){return function(o){if(o=o||t(window.event),!o)return;let c=!0,l;O(r)&&(l=r(o));const a=n.call(i,o);return(l===!1||a===!1)&&(c=!1),c}}function t(i){return i&&(i.preventDefault=t.preventDefault,i.stopPropagation=t.stopPropagation),i}return t.preventDefault=function(){this.returnValue=!1},t.stopPropagation=function(){this.cancelBubble=!0},s}(),te=function(s){return function(...e){try{return s.apply(this,e)}catch(t){h().error("Implementation error. Please turn on debug and contact support@usermaven.com.",t)}}},L=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=te(s[e]))};function U(s){for(let e in s)(s[e]===""||s[e]===null||s[e]===void 0||typeof s[e]=="object"&&Object.keys(s[e]).length===0)&&delete s[e];return s}function u(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return h().warn("window is not available"),!1}}function m(s=5){const e=new Uint8Array(s);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").slice(0,s)}function ie(s){return s.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function S(s){return typeof s!="object"||s===null?s:Array.isArray(s)?s.map(S):Object.keys(s).reduce((e,t)=>{const i=ie(t);return e[i]=S(s[t]),e},{})}function P(s){switch(typeof s.className){case"string":return s.className;case"object":return("baseVal"in s.className?s.className.baseVal:null)||s.getAttribute("class")||"";default:return""}}function I(s){let e="";return z(s)&&!M(s)&&s.childNodes&&s.childNodes.length&&A(s.childNodes,function(t){D(t)&&t.textContent&&(e+=T(t.textContent).split(/(\s+)/).filter(H).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),T(e)}function C(s){return!!s&&s.nodeType===1}function p(s,e){return!!s&&!!s.tagName&&s.tagName.toLowerCase()===e.toLowerCase()}function D(s){return!!s&&s.nodeType===3}function F(s){return!!s&&s.nodeType===11}const x=["a","button","form","input","select","textarea","label"];function se(s,e){if(!s||p(s,"html")||!C(s)||s.classList&&s.classList.contains("um-no-capture"))return!1;let t=!1;const i=[s];let n=!0,r=s;for(;r.parentNode&&!p(r,"body");){if(F(r.parentNode)){i.push(r.parentNode.host),r=r.parentNode.host;continue}if(n=r.parentNode||!1,!n)break;if(x.indexOf(n.tagName.toLowerCase())>-1)t=!0;else{const l=window.getComputedStyle(n);l&&l.getPropertyValue("cursor")==="pointer"&&(t=!0)}i.push(n),r=n}const o=window.getComputedStyle(s);if(o&&o.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;const c=s.tagName.toLowerCase();switch(c){case"html":return!1;case"form":return e.type==="submit";case"input":return e.type==="change"||e.type==="click";case"select":case"textarea":return e.type==="change"||e.type==="click";default:return t?e.type==="click":e.type==="click"&&(x.indexOf(c)>-1||s.getAttribute("contenteditable")==="true")}}function z(s){if(!s||!C(s))return!1;if(typeof s.hasAttribute=="function"){if(s.hasAttribute(w.FORCE_CAPTURE_ATTR))return!0;if(s.hasAttribute(w.PREVENT_CAPTURE_ATTR))return!1}let e=s;for(;e&&e.parentElement&&!p(e,"body");){const n=P(e).split(" ");if(E(n,"ph-sensitive")||E(n,"ph-no-capture"))return!1;e=e.parentElement}if(E(P(s).split(" "),"ph-include"))return!0;const t=s.type;if(typeof t=="string")switch(t.toLowerCase()){case"hidden":case"password":return!1}const i=s.name||s.id||"";return!(typeof i=="string"&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,"")))}function M(s){const e=["button","checkbox","submit","reset"];return!!(p(s,"input")&&!e.includes(s.type)||p(s,"select")||p(s,"textarea")||s.getAttribute("contenteditable")==="true")}function H(s){return!(s===null||ee(s)||typeof s=="string"&&(s=T(s),/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((s||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(s)))}function ne(s){return typeof s=="string"?s.substring(0,10)==="_ngcontent"||s.substring(0,7)==="_nghost":!1}function R(){return m(10)}function re(s){return/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(s).toLowerCase())}function oe(s,e){let t;return function(...i){const n=()=>{clearTimeout(t),s(...i)};clearTimeout(t),t=setTimeout(n,e)}}function ae(s){const e={},t=s.replace(/^\?/,"").split("&");for(let i=0;i<t.length;i++){const n=t[i].split("=");n[0]!==""&&(e[decodeURIComponent(n[0])]=decodeURIComponent(n[1]||""))}return e}function B(s){return typeof s=="string"||s instanceof String}function _(s){return s!==null&&typeof s=="object"&&s.constructor===Object}function ce(s){if(s===null)return g.ERROR;const e=s.toUpperCase(),t=g[e];return t||t===0?t:g.ERROR}class le{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=oe(this.handleScroll.bind(this),250),this.initializeEventListener()}initializeEventListener(){window.addEventListener("scroll",this.debouncedHandleScroll)}track(){const e=this.getScrollDepth();e>this.lastScrollDepth&&(this.lastScrollDepth=e,this.checkMilestones(e))}send(e="$scroll"){const t={percent:this.lastScrollDepth,window_height:this.getWindowHeight(),document_height:this.getDocumentHeight(),scroll_distance:this.getScrollDistance()};this.client.track(e,t)}handleScroll(){this.track()}getScrollDepth(){const e=this.getWindowHeight(),t=this.getDocumentHeight(),i=this.getScrollDistance(),n=t-e;return Math.min(100,Math.floor(i/n*100))}getWindowHeight(){return window.innerHeight||this.documentElement.clientHeight||document.body.clientHeight||0}getDocumentHeight(){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)}getScrollDistance(){return window.pageYOffset||this.documentElement.scrollTop||document.body.scrollTop||0}checkMilestones(e){this.milestones.filter(i=>e>=i).forEach(i=>{this.send(),this.milestones=this.milestones.filter(n=>n!==i)})}}const v=class v{constructor(e,t,i=h()){this.logger=i,this.scrollDepth=null,this.client=e,this.options=t,this.scrollDepth=new le(e),Y(this),L(this)}init(){if(!(document&&document.body)){this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."),setTimeout(()=>this.init(),500);return}this.addDomEventHandlers()}addDomEventHandlers(){const e=t=>{t=t||window.event,this.captureEvent(t)};y(document,"submit",e,!1,!0),y(document,"change",e,!1,!0),y(document,"click",e,!1,!0),y(document,"visibilitychange",e,!1,!0),y(document,"scroll",e,!1,!0),y(window,"popstate",e,!1,!0)}isPageRefresh(){if("PerformanceNavigationTiming"in window){const e=performance.getEntriesByType("navigation");if(e.length>0)return e[0].type==="reload"}return performance.navigation&&performance.navigation.type===1}captureEvent(e){var i,n;let t=this.getEventTarget(e);if(D(t)&&(t=t.parentNode||null),e.type==="scroll")return(i=this.scrollDepth)==null||i.track(),!0;if(e.type==="visibilitychange"&&document.visibilityState==="hidden"||e.type==="popstate")return this.isPageRefresh()||(n=this.scrollDepth)==null||n.send(),!0;if(t&&this.shouldCaptureElement(t,e)){const r=this.getElementList(t),o=this.getElementsJson(r,e),c=j(this.getDefaultProperties(e.type),{$elements:o});return this.client.track("$autocapture",c),!0}}shouldCaptureElement(e,t){return!e||typeof e.hasAttribute!="function"?!1:e.hasAttribute(v.FORCE_CAPTURE_ATTR)?!0:e.hasAttribute(v.PREVENT_CAPTURE_ATTR)?!1:se(e,t)}getEventTarget(e){var t;return typeof e.target>"u"?e.srcElement||null:(t=e.target)!=null&&t.shadowRoot?e.composedPath()[0]||null:e.target||null}getElementList(e){const t=[e];let i=e;for(;i.parentNode&&!p(i,"body");)F(i.parentNode)?(t.push(i.parentNode.host),i=i.parentNode.host):(t.push(i.parentNode),i=i.parentNode);return t}getElementsJson(e,t){const i=[];let n=null,r=!1;return A(e,o=>{if(p(o,"a")){const l=o.getAttribute("href");l!==null&&z(o)&&H(l)&&(n=l)}const c=P(o).split(" ");E(c,"ph-no-capture")&&(r=!0),i.push(this.getPropertiesFromElement(o))}),this.options.maskAllText||(i[0].$el_text=this.sanitizeText(I(e[0]))),n!==null&&(i[0].attr__href=n),r?[]:i}getPropertiesFromElement(e){const t={tag_name:e.tagName.toLowerCase()};x.indexOf(t.tag_name)>-1&&!this.options.maskAllText&&(t.$el_text=this.sanitizeText(I(e)));const i=P(e);i.length>0&&(t.classes=i.split(" ").filter(c=>c!=="")),A(e.attributes,c=>{M(e)&&["name","id","class"].indexOf(c.name)===-1||!this.options.maskAllElementAttributes&&H(c.value)&&!ne(c.name)&&(t["attr__"+c.name]=this.sanitizeAttributeValue(c.name,c.value))});let n=1,r=1,o=e;for(;o=this.previousElementSibling(o);)n++,o.tagName===e.tagName&&r++;return t.nth_child=n,t.nth_of_type=r,t}previousElementSibling(e){if(e.previousElementSibling)return e.previousElementSibling;do e=e.previousSibling;while(e&&!C(e));return e}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}sanitizeText(e){e=e.replace(/<[^>]*?>/g,""),e=this.encodeHtml(e);const t=this.options.propertiesStringMaxLength||255;return e.length>t&&(e=e.substring(0,t)+"..."),e}sanitizeUrl(e){if(!e)return"";try{const t=new URL(e,window.location.href);return t.protocol!=="http:"&&t.protocol!=="https:"?"":encodeURI(t.toString())}catch{return this.encodeHtml(e)}}sanitizeAttributeValue(e,t){switch(e.toLowerCase()){case"href":case"src":return this.sanitizeUrl(t);default:return this.encodeHtml(t)}}encodeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}static enabledForProject(e,t=10,i=10){if(!e)return!1;let n=0;for(let r=0;r<e.length;r++)n+=e.charCodeAt(r);return n%t<i}static isBrowserSupported(){return O(document.querySelectorAll)}};v.FORCE_CAPTURE_ATTR="data-um-force-capture",v.PREVENT_CAPTURE_ATTR="data-um-no-capture";let w=v;class ue{constructor(e){this.client=e,this.lastPageUrl=window.location.href,this.trackInitialPageview(),this.initializePageviewTracking()}trackInitialPageview(){this.trackPageview()}initializePageviewTracking(){window.addEventListener("popstate",this.handlePageview.bind(this));const e=history.pushState;history.pushState=(...t)=>{e.apply(history,t),this.handlePageview()},window.addEventListener("hashchange",this.handlePageview.bind(this)),setInterval(this.checkForUrlChange.bind(this),1e3)}handlePageview(){this.trackPageview()}checkForUrlChange(){window.location.href!==this.lastPageUrl&&this.trackPageview()}trackPageview(){const e=window.location.href;e!==this.lastPageUrl&&(this.lastPageUrl=e,this.client.track("pageview",{url:e,referrer:document.referrer,title:document.title}))}}class he{constructor(e,t,i=h()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),n=new Blob([JSON.stringify(e)],{type:"application/json"});if(navigator.sendBeacon(i,n))this.logger.debug(`Successfully queued ${e.length} event(s) via Beacon API`);else throw new Error("Failed to queue events via Beacon API")}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}}class q{constructor(e,t,i=h()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),n=JSON.stringify(e),r={"Content-Type":"application/json",...this.getCustomHeaders()},o=await fetch(i,{method:"POST",headers:r,body:n});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);this.logger.debug(`Successfully sent ${e.length} event(s)`),this.postHandle(o.status,await o.text())}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}postHandle(e,t){this.logger.debug(`Response received. Status: ${e}, Body: ${t}`)}}class ge{constructor(e,t,i=h()){this.trackingHost=e,this.logger=i,this.config=t}send(e){return new Promise((t,i)=>{const n=new XMLHttpRequest,r=this.config.key,o=this.constructUrl(r);n.open("POST",o,!0),n.setRequestHeader("Content-Type","application/json");const c=this.getCustomHeaders();Object.keys(c).forEach(l=>{n.setRequestHeader(l,c[l])}),n.onload=()=>{n.status>=200&&n.status<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),t()):i(new Error(`HTTP error! status: ${n.status}`))},n.onerror=()=>{i(new Error("Network error"))},n.send(JSON.stringify(e))})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}postHandle(e,t){this.logger.debug(`Response received. Status: ${e}, Body: ${t}`)}}class V{constructor(e,t){this.storage={},this.prefix=`usermaven_${e}_`,this.load(),this.logger=t||h()}set(e,t){this.storage[e]=t,this.save()}get(e){return this.storage[e]}remove(e){delete this.storage[e],this.save()}clear(){this.storage={},this.save()}save(){if(!u()){this.logger.warn("localStorage is not available in this environment");return}try{localStorage.setItem(this.prefix+"data",JSON.stringify(this.storage))}catch(e){this.logger.error("Error saving to localStorage:",e)}}load(){if(!u()){this.logger.warn("localStorage is not available in this environment");return}try{const e=localStorage.getItem(this.prefix+"data");e&&(this.storage=JSON.parse(e))}catch(e){this.logger.error("Error loading from localStorage:",e)}}}class de{constructor(){this.storage={}}set(e,t){this.storage[e]=t}get(e){return this.storage[e]}remove(e){delete this.storage[e]}save(){}clear(){this.storage={}}}class J{constructor(e,t=3,i=1e3,n=10,r=1e3,o=h()){this.transport=e,this.maxRetries=t,this.retryInterval=i,this.batchSize=n,this.batchInterval=r,this.logger=o,this.queue=[],this.processing=!1,this.batchTimeoutId=null,this.isOnline=!0,this.persistence=new V("offline_queue"),u()&&(this.isOnline=navigator.onLine,this.loadQueueFromStorage(),this.initNetworkListeners(),this.scheduleBatch())}add(e){const t={payload:e,retries:0,timestamp:Date.now()};this.queue.push(t),u()?this.saveQueueToStorage():this.processBatch()}initNetworkListeners(){u()&&(window.addEventListener("online",()=>{this.isOnline=!0,this.processBatch()}),window.addEventListener("offline",()=>{this.isOnline=!1}))}scheduleBatch(){u()&&(this.batchTimeoutId!==null&&clearTimeout(this.batchTimeoutId),this.batchTimeoutId=window.setTimeout(()=>this.processBatch(),this.batchInterval))}async processBatch(){if((!u()||this.isOnline)&&!this.processing&&this.queue.length>0){this.processing=!0;const e=this.queue.splice(0,this.batchSize),t=e.map(i=>i.payload);try{await this.transport.send(t),this.logger.debug(`Successfully sent batch of ${e.length} payloads`),u()&&this.saveQueueToStorage()}catch(i){this.logger.error("Failed to send batch",i),await this.handleBatchFailure(e)}this.processing=!1}u()&&this.scheduleBatch()}async handleBatchFailure(e){for(const t of e)t.retries<this.maxRetries?(t.retries++,this.queue.unshift(t),this.logger.warn(`Retry attempt ${t.retries} for payload`)):this.logger.error("Max retries reached, discarding payload",t.payload);u()&&(this.saveQueueToStorage(),await new Promise(t=>setTimeout(t,this.retryInterval)))}loadQueueFromStorage(){if(u()){const e=this.persistence.get("queue");e&&(this.queue=JSON.parse(e))}}saveQueueToStorage(){u()&&this.persistence.set("queue",JSON.stringify(this.queue))}}class fe{constructor(e){this.clicks=[],this.threshold=3,this.timeWindow=2e3,this.distanceThreshold=30,this.client=e,this.initializeEventListener(),L(this)}initializeEventListener(){document.addEventListener("click",this.handleClick.bind(this))}handleClick(e){const t=e.target;this.shouldCaptureElement(t)&&this.click(e.clientX,e.clientY,Date.now())}shouldCaptureElement(e){return!e.closest(".um-no-capture")}click(e,t,i){const n={x:e,y:t,timestamp:i};this.clicks.push(n),this.clicks=this.clicks.filter(r=>i-r.timestamp<this.timeWindow),this.clicks.length>=this.threshold&&this.checkRageClick()}checkRageClick(){const e=this.clicks[0],i=(this.clicks[this.clicks.length-1].timestamp-e.timestamp)/1e3;this.clicks.every((r,o)=>{if(o===0)return!0;const c=this.clicks[o-1];return Math.sqrt(Math.pow(r.x-c.x,2)+Math.pow(r.y-c.y,2))<this.distanceThreshold})&&this.sendRageClickEvent(i)}sendRageClickEvent(e){const t=this.clicks[this.clicks.length-1];document.elementFromPoint(t.x,t.y)&&this.client.track("$rage_click",{no_of_clicks:this.clicks.length,time:e.toFixed(2)}),this.clicks=[]}}class pe{constructor(e,t,i=h()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=new(void 0)(this.constructUrl(t)),n={hostname:i.hostname,port:443,path:`${i.pathname}${i.search}`,method:"POST",headers:{"Content-Type":"application/json",...this.getCustomHeaders()}};return new Promise((r,o)=>{const c=(void 0)(n,l=>{l.on("data",a=>{}),l.on("end",()=>{const a=l.statusCode||0;a>=200&&a<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${a}`))})});c.on("error",l=>{o(l)}),c.write(JSON.stringify(e)),c.end()})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"";return`${this.trackingHost}/api/v1/s2s/event?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}}class k{constructor(e,t="all",i={}){this.instance=e,this.trackingType=t,this.options=i,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",this.initialize.bind(this)):this.initialize()}initialize(){this.trackingType!=="none"&&this.setupFormTracking()}setupFormTracking(){var e;this.formElements=this.trackingType==="tagged"?document.querySelectorAll("form[data-um-form]"):document.querySelectorAll("form"),(e=this.formElements)==null||e.forEach(t=>{t.addEventListener("submit",this.handleFormSubmit.bind(this))})}handleFormSubmit(e){const t=e.target,i=this._getFormDetails(t);this.instance.track("$form",U(i)),this.options.trackFieldChanges&&this.trackFieldChanges(t)}trackFieldChanges(e){e.querySelectorAll("input, select, textarea").forEach(i=>{i.addEventListener("change",n=>{const r=this._getFieldProps(n.target,0);this.instance.track("$form_field_change",U(r))})})}static getInstance(e,t="all",i={}){return k.instance||(k.instance=new k(e,t,i)),k.instance}_getFormDetails(e){const t={form_id:e.id,form_name:e.name||"",form_action:e.action,form_method:e.method,form_class:e.className,form_attributes:this._getElementAttributes(e)},i=e.querySelectorAll("input, select, textarea");return Array.from(i).filter(r=>!r.classList.contains("um-no-capture")).forEach((r,o)=>{const c=this._getFieldProps(r,o);Object.assign(t,c)}),t}_getFieldProps(e,t){const i=Object.keys(e.dataset).length?JSON.stringify(e.dataset):void 0,n=this.getSafeText(e);return{[`field_${t+1}_tag`]:e.tagName.toLowerCase(),[`field_${t+1}_type`]:e instanceof HTMLInputElement?e.type:void 0,[`field_${t+1}_data_attributes`]:i,[`field_${t+1}_id`]:e.id,[`field_${t+1}_value`]:n,[`field_${t+1}_class`]:e.className,[`field_${t+1}_name`]:e.name,[`field_${t+1}_attributes`]:this._getElementAttributes(e)}}_getElementAttributes(e){const t={};for(let i=0;i<e.attributes.length;i++){const n=e.attributes[i];n.name!=="value"&&!n.name.startsWith("data-")&&(t[n.name]=n.value)}return t}getSafeText(e){let t="";return"value"in e&&e.type!=="password"?t=e.value:e.hasChildNodes()?t=Array.from(e.childNodes).filter(n=>n.nodeType===Node.TEXT_NODE).map(n=>n.textContent).join(""):t=e.textContent||"",this._scrubPotentiallySensitiveValues(t)}_scrubPotentiallySensitiveValues(e){return this._shouldCaptureValue(e)?e:"<redacted>"}_shouldCaptureValue(e){return!(this._isNullish(e)||this._isString(e)&&(e=this._trim(e),/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((e||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(e)))}_isNullish(e){return e==null}_isString(e){return typeof e=="string"||e instanceof String}_trim(e){if(typeof String.prototype.trim=="function")return e.trim();let t=0,i=e.length-1;const n=[" ",`
2
- `,"\r"," ","\f","\v"," "," "," "," "," "," "," "," "," "," "," "," "," ","\u2028","\u2029"," "," "," "].join("");for(;t<=i&&n.indexOf(e[t])>-1;)t++;for(;i>=t&&n.indexOf(e[i])>-1;)i--;return e.slice(t,i+1)}}class Q{constructor(e){this.config=this.mergeConfig(e,N),this.logger=h(this.config.logLevel),this.namespace=e.namespace||"usermaven",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new J(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,200,this.logger),u()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new K(this.config.cookieDomain),this.config.autocapture&&w.enabledForProject(this.config.key)&&(this.autoCapture=new w(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=k.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new ue(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new fe(this)),this.setupPageLeaveTracking()}mergeConfig(e,t){const i=JSON.parse(JSON.stringify(e));let n={...t,...i};return Object.keys(t).forEach(r=>{_(t[r])&&(n[r]=this.mergeConfig(e[r],t[r]))}),n}init(e){this.config={...this.config,...e},this.logger=h(this.config.logLevel),this.namespace=e.namespace||this.namespace,this.transport=this.initializeTransport(e),this.persistence=this.initializePersistence(),this.retryQueue=new J(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,250,this.logger),u()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client reinitialized for namespace: ${this.namespace}`)}manageCrossDomainLinking(){if(!this.config.crossDomainLinking||!this.config.domains)return;const e=this.config.domains.split(",").map(i=>i.trim()),t=this.config.cookieName||`${this.namespace}_id_${this.config.key}`;document.addEventListener("click",i=>{var c;const n=this.findClosestLink(i.target);if(!n)return;const r=n.getAttribute("href");if(!r||!r.startsWith("http"))return;const o=new URL(r);if(o.hostname!==window.location.hostname&&e.includes(o.hostname)){const l=(c=this.cookieManager)==null?void 0:c.get(t);l&&(o.searchParams.append("_um",l),n.setAttribute("href",o.toString()))}}),this.logger.debug("Cross-domain linking initialized")}findClosestLink(e){for(;e&&e.tagName!=="A";)e=e.parentElement;return e}initializeTransport(e){if(!u())return new pe(e.trackingHost,e);const t="XMLHttpRequest"in window,i=typeof fetch<"u",n=typeof navigator<"u"&&"sendBeacon"in navigator;if(e.useBeaconApi&&n)return new he(e.trackingHost,e,this.logger);if(e.forceUseFetch&&i)return new q(e.trackingHost,e,this.logger);if(t)return new ge(e.trackingHost,e,this.logger);if(i)return new q(e.trackingHost,e,this.logger);throw new Error("No suitable transport method available")}initializePersistence(){return this.config.disableEventPersistence||!u()?new de:new V(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var i,n;if(!u())return R();if(this.config.privacyPolicy==="strict"||this.config.cookiePolicy==="strict")return this.generateFingerprint();const e=this.config.cookieName||`${this.namespace}_id_${this.config.key}`;let t=(i=this.cookieManager)==null?void 0:i.get(e);if(!t){if(this.config.crossDomainLinking){const c=new URLSearchParams(window.location.search).get("_um"),a=window.location.hash.substring(1).split("~"),d=a.length>1?a[1]:void 0;t=c||d||R()}t||(t=R());const r=365*10;(n=this.cookieManager)==null||n.set(e,t,r,document.location.protocol!=="http:",!1)}return t}generateFingerprint(){const e=navigator.userAgent,t=`${screen.width}x${screen.height}`,i=screen.colorDepth,n=Intl.DateTimeFormat().resolvedOptions().timeZone,r=`${e}|${t}|${i}|${n}`;return this.hashString(r)}hashString(e){let t=0;for(let i=0;i<e.length;i++){const n=e.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return t.toString(36)}async id(e,t=!1){if(!_(e))throw new Error("User data must be an object");if(e.email&&!re(e.email))throw new Error("Invalid email provided");if(!e.id||!B(e.id))throw new Error("User ID must be a string");const i=e.id;if(this.persistence.set("userId",i),this.persistence.set("userProps",e),!t){const n={...e,anonymous_id:this.anonymousId};await this.track("user_identify",n)}this.logger.info("User identified:",e)}track(e,t,i=!1){this.trackInternal(e,t,i)}trackInternal(e,t,i=!1){if(!B(e))throw new Error("Event name must be a string");if(t!==void 0&&(typeof t!="object"||t===null||Array.isArray(t)))throw new Error("Event payload must be a non-null object and not an array");const n=this.createEventPayload(e,t);try{if(i){this.transport.send(n),this.logger.debug(`Event sent: ${e}`,[n]);return}this.retryQueue.add(n),this.logger.debug(`Event tracked: ${e}`,[n])}catch(r){throw this.logger.error(`Failed to track event: ${e}`,r),new Error(`Failed to track event: ${e}`)}}rawTrack(e){if(!_(e))throw new Error("Event payload must be an object");this.track("raw",e)}async group(e,t=!1){if(!_(e))throw new Error("Company properties must be an object");if(!e.id||!e.name||!e.created_at)throw new Error("Company properties must include id, name, and created_at");this.persistence.set("companyProps",e),t||await this.track("group",e),this.logger.info("Company identified:",e)}createEventPayload(e,t){const i=this.persistence.get("userProps")||{},n=this.persistence.get("companyProps")||void 0,r=this.persistence.get("userId"),o=this.persistence.get("global_props")||{},c=this.persistence.get(`props_${e}`)||{};let l=t||{};const a={event_id:"",user:{anonymous_id:this.anonymousId,id:r,...i},...n&&{company:n},ids:this.getThirdPartyIds(),utc_time:new Date().toISOString(),local_tz_offset:new Date().getTimezoneOffset(),api_key:this.config.key,src:"usermaven",event_type:e,namespace:this.namespace,...o,...c};if(e==="$autocapture"){const d=this.processAutocaptureAttributes(t||{});a.autocapture_attributes=d}else Array.isArray(this.config.propertyBlacklist)&&this.config.propertyBlacklist.forEach(d=>{delete l[d]}),a.event_attributes=l;return u()&&(a.referer=document.referrer,a.url=window.location.href,a.page_title=document.title,a.doc_path=window.location.pathname,a.doc_host=window.location.hostname,a.doc_search=window.location.search,a.screen_resolution=`${window.screen.width}x${window.screen.height}`,a.vp_size=`${window.innerWidth}x${window.innerHeight}`,a.user_agent=navigator.userAgent,a.user_language=navigator.language,a.doc_encoding=document.characterSet,a.utm=this.getUtmParams()),a}processAutocaptureAttributes(e){let t={};const i=e.$elements||[];return i.length&&(t={...i[0]}),t.el_text=t.$el_text||"",t.event_type=e.$event_type||"",["$ce_version","$event_type","$initial_referrer","$initial_referring_domain","$referrer","$referring_domain","$elements"].forEach(n=>{delete t[n]}),delete t.$el_text,delete t.nth_child,delete t.nth_of_type,t}getCookie(e){var t;return((t=this.cookieManager)==null?void 0:t.get(e))||null}getThirdPartyIds(){const e={};if(u()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=ae(window.location.search);return["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(n=>{t[n]&&(e[n.replace("utm_","")]=t[n])}),e}pageview(){u()?this.track("pageview",{url:window.location.href,referrer:document.referrer,title:document.title},!0):this.logger.warn("Pageview tracking is not available in server-side environments")}setupPageLeaveTracking(){if(!u())return;let e=!1,t=!1;const i=()=>{!e&&!t&&(e=!0,this.track("$pageleave",{url:window.location.href,referrer:document.referrer,title:document.title}))};window.addEventListener("beforeunload",r=>{t=!0,setTimeout(()=>{t=!1},100)}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&!t&&i()});const n=history.pushState;history.pushState=function(){return i(),n.apply(this,arguments)},window.addEventListener("popstate",i)}getConfig(){return this.config}getLogger(){return this.logger}async reset(e=!1){if(this.persistence.clear(),e&&this.cookieManager){const t=this.config.cookieName||`${this.namespace}_id_${this.config.key}`;this.cookieManager.delete(t),this.anonymousId=this.getOrCreateAnonymousId()}this.logger.info("core state reset",{resetAnonId:e,namespace:this.namespace})}set(e,t){if(!_(e))throw new Error("Properties must be an object");const i=t==null?void 0:t.eventType,n=(t==null?void 0:t.persist)??!0;if(i){let r=this.persistence.get(`props_${i}`)||{};r={...r,...e},this.persistence.set(`props_${i}`,r)}else{let r=this.persistence.get("global_props")||{};r={...r,...e},this.persistence.set("global_props",r)}n&&this.persistence.save(),this.logger.debug("Properties set",{properties:e,eventType:i||"global",persist:n})}setUserId(e){this.persistence.set("userId",e);let t=this.persistence.get("userProps")||{};t.id=e,this.persistence.set("userProps",t),this.persistence.save()}unset(e,t){const i=t==null?void 0:t.eventType,n=(t==null?void 0:t.persist)??!0;if(i){let r=this.persistence.get(`props_${i}`)||{};delete r[e],this.persistence.set(`props_${i}`,r)}else{let r=this.persistence.get("global_props")||{};delete r[e],this.persistence.set("global_props",r)}n&&this.persistence.save(),this.logger.debug(`Property unset: ${e}`,`Event type: ${i||"global"}`)}}function W(s){const e=JSON.parse(JSON.stringify(s)),t=S(e),i={...N,...t};if(!i.key)throw new Error("API key is required!");if(!i.trackingHost)throw new Error("Tracking host is required!");return new Q(i)}function me(s){var n;const e={key:s.getAttribute("data-key")||void 0,trackingHost:s.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:ce(s.getAttribute("data-log-level")),autocapture:s.getAttribute("data-autocapture")==="true",formTracking:s.getAttribute("data-form-tracking")==="true"?"all":!1,autoPageview:s.getAttribute("data-auto-pageview")==="true",useBeaconApi:s.getAttribute("data-use-beacon-api")==="true",forceUseFetch:s.getAttribute("data-force-use-fetch")==="true",gaHook:s.getAttribute("data-ga-hook")==="true",segmentHook:s.getAttribute("data-segment-hook")==="true",randomizeUrl:s.getAttribute("data-randomize-url")==="true",capture3rdPartyCookies:s.getAttribute("data-capture-3rd-party-cookies")==="false"?!1:void 0,idMethod:s.getAttribute("data-id-method")||void 0,privacyPolicy:s.getAttribute("data-privacy-policy")==="strict"?"strict":void 0,ipPolicy:s.getAttribute("data-ip-policy")||void 0,cookiePolicy:s.getAttribute("data-cookie-policy")||void 0,minSendTimeout:parseInt(s.getAttribute("data-min-send-timeout")||"",10)||void 0,maxSendTimeout:parseInt(s.getAttribute("data-max-send-timeout")||"",10)||void 0,maxSendAttempts:parseInt(s.getAttribute("data-max-send-attempts")||"",10)||void 0,propertiesStringMaxLength:parseInt(s.getAttribute("data-properties-string-max-length")||"",10)||null,propertyBlacklist:((n=s.getAttribute("data-property-blacklist"))==null?void 0:n.split(","))||void 0,exclude:s.getAttribute("data-exclude")||void 0,namespace:s.getAttribute("data-namespace")||void 0,crossDomainLinking:s.getAttribute("data-cross-domain-linking")!=="false",domains:s.getAttribute("data-domains")||void 0,maskAllText:s.getAttribute("data-mask-all-text")==="true",maskAllElementAttributes:s.getAttribute("data-mask-all-element-attributes")==="true"},t=W(e),i=e.namespace||"usermaven";u()&&t.pageview(),ye(i,t)}function ye(s,e){let t=!1;const i=[],n=[];function r(){for(;i.length>0;){const a=i.shift();a&&window[s].apply(null,a)}}function o(){n.forEach(a=>a()),n.length=0}window[s]=function(...a){const d=a[0];if(d==="onLoad"){typeof a[1]=="function"&&(t?a[1]():n.push(a[1]));return}if(!t){i.push(a);return}if(typeof e[d]=="function")return e[d].apply(e,a.slice(1));console.error(`Method ${d} not found on UsermavenClient`)};const c=`${s}Q`,l=window[c]||[];for(window[c]=l,l.push=function(...a){return window[s].apply(null,a),Array.prototype.push.apply(this,a)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${s} is ready`)},0);l.length>0;){const a=l.shift();a&&i.push(a)}}u()&&function(s,e){const t=s.currentScript;function i(){t&&t.src.includes("lib.js")&&me(t)}typeof e<"u"&&(s.readyState==="loading"?s.addEventListener("DOMContentLoaded",i):i())}(document,window),f.LogLevel=g,f.UsermavenClient=Q,f.usermavenClient=W,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})});
@@ -1,13 +0,0 @@
1
- import { Logger } from '../utils/logger';
2
- export declare class LocalStoragePersistence {
3
- private storage;
4
- private prefix;
5
- private logger;
6
- constructor(apiKey: string, logger?: Logger);
7
- set(key: string, value: any): void;
8
- get(key: string): any;
9
- remove(key: string): void;
10
- clear(): void;
11
- save(): void;
12
- private load;
13
- }
@@ -1,8 +0,0 @@
1
- export declare class MemoryPersistence {
2
- private storage;
3
- set(key: string, value: any): void;
4
- get(key: string): any;
5
- remove(key: string): void;
6
- save(): void;
7
- clear(): void;
8
- }
@@ -1,29 +0,0 @@
1
- import { UsermavenClient } from '../core/client';
2
- import { Config } from '../core/config';
3
- declare class AutoCapture {
4
- private logger;
5
- private client;
6
- private options;
7
- private scrollDepth;
8
- static readonly FORCE_CAPTURE_ATTR = "data-um-force-capture";
9
- static readonly PREVENT_CAPTURE_ATTR = "data-um-no-capture";
10
- constructor(client: UsermavenClient, options: Config, logger?: import('../utils/logger').Logger);
11
- init(): void;
12
- private addDomEventHandlers;
13
- private isPageRefresh;
14
- private captureEvent;
15
- private shouldCaptureElement;
16
- private getEventTarget;
17
- private getElementList;
18
- private getElementsJson;
19
- private getPropertiesFromElement;
20
- private previousElementSibling;
21
- private getDefaultProperties;
22
- private sanitizeText;
23
- private sanitizeUrl;
24
- private sanitizeAttributeValue;
25
- private encodeHtml;
26
- static enabledForProject(token: string, numBuckets?: number, numEnabledBuckets?: number): boolean;
27
- static isBrowserSupported(): boolean;
28
- }
29
- export default AutoCapture;
@@ -1,27 +0,0 @@
1
- import { UsermavenClient } from '../core/client';
2
- export default class FormTracking {
3
- private instance;
4
- private formElements?;
5
- private trackingType;
6
- private options;
7
- private static instance;
8
- private constructor();
9
- private initialize;
10
- private setupFormTracking;
11
- private handleFormSubmit;
12
- private trackFieldChanges;
13
- static getInstance(instance: UsermavenClient, trackingType?: 'all' | 'tagged' | 'none', options?: FormTrackingOptions): FormTracking;
14
- private _getFormDetails;
15
- private _getFieldProps;
16
- private _getElementAttributes;
17
- private getSafeText;
18
- private _scrubPotentiallySensitiveValues;
19
- private _shouldCaptureValue;
20
- private _isNullish;
21
- private _isString;
22
- private _trim;
23
- }
24
- interface FormTrackingOptions {
25
- trackFieldChanges?: boolean;
26
- }
27
- export {};
@@ -1,11 +0,0 @@
1
- import { UsermavenClient } from '../core/client';
2
- export declare class PageviewTracking {
3
- private client;
4
- private lastPageUrl;
5
- constructor(client: UsermavenClient);
6
- private trackInitialPageview;
7
- private initializePageviewTracking;
8
- private handlePageview;
9
- private checkForUrlChange;
10
- private trackPageview;
11
- }
@@ -1,10 +0,0 @@
1
- import { Transport } from '../core/types';
2
- import { Config } from '../core/config';
3
- export declare class BeaconTransport implements Transport {
4
- private trackingHost;
5
- private logger;
6
- private config;
7
- constructor(trackingHost: string, config: Config, logger?: import('../utils/logger').Logger);
8
- send(payloads: any[]): Promise<void>;
9
- private constructUrl;
10
- }
@@ -1,13 +0,0 @@
1
- import { Transport } from '../core/types';
2
- import { Logger } from '../utils/logger';
3
- import { Config } from '../core/config';
4
- export declare class FetchTransport implements Transport {
5
- private trackingHost;
6
- private logger;
7
- private config;
8
- constructor(trackingHost: string, config: Config, logger?: Logger);
9
- send(payloads: any[]): Promise<void>;
10
- private constructUrl;
11
- private getCustomHeaders;
12
- private postHandle;
13
- }