@usermaven/sdk-js 1.5.9 → 1.5.10-rc.109
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lib.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(m,f){typeof exports=="object"&&typeof module<"u"?f(exports):typeof define=="function"&&define.amd?define(["exports"],f):(m=typeof globalThis<"u"?globalThis:m||self,f(m.Usermaven={}))})(this,function(m){"use strict";var f=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n))(f||{});class ne{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 g(n=0){return new ne(n)}const q={logLevel:f.ERROR,useBeaconApi:!1,forceUseFetch:!1,trackingHost:"t.usermaven.com",autocapture:!1,rageClick:!1,formTracking:!1,autoPageview:!0,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 se{constructor(e){this.domain=e,this.cookieDomain=this.getCookieDomain()}set(e,t,i=365,s=!0,r=!1){const o=new Date;o.setTime(o.getTime()+i*24*60*60*1e3);const a=`expires=${o.toUTCString()}`,l=s?"; Secure":"",c=r?"; HttpOnly":"";document.cookie=`${e}=${t};${a};path=/;domain=${this.cookieDomain}${l}${c}`}get(e){const t=e+"=",i=document.cookie.split(";");for(let s=0;s<i.length;s++){let r=i[s].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("."),s=i.length;return s>2&&(i[s-1].length==2?(t=i[s-2]+"."+i[s-1],i[s-2].length==2&&(t=i[s-3]+"."+t)):t=i[s-2]+"."+i[s-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 re=Object.prototype.hasOwnProperty,x=Array.prototype.forEach,U={};function oe(n,e,t){if(Array.isArray(n)){if(x&&n.forEach===x)n.forEach(e,t);else if("length"in n&&n.length===+n.length){for(let i=0,s=n.length;i<s;i++)if(i in n&&e.call(t,n[i],i)===U)return}}}const L=function(n){return n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},ae=function(n){for(const e in n)typeof n[e]=="function"&&(n[e]=n[e].bind(n))};function v(n,e,t){if(n!=null){if(x&&Array.isArray(n)&&n.forEach===x)n.forEach(e,t);else if("length"in n&&n.length===+n.length){for(let i=0,s=n.length;i<s;i++)if(i in n&&e.call(t,n[i],i)===U)return}else for(const i in n)if(re.call(n,i)&&e.call(t,n[i],i)===U)return}}const ce=function(n,...e){return oe(e,function(t){for(const i in t)t[i]!==void 0&&(n[i]=t[i])}),n};function S(n,e){return n.indexOf(e)!==-1}const le=function(n){try{return/^\s*\bfunction\b/.test(n)}catch{return!1}},ue=function(n){return n===void 0},b=function(){const n=function(i,s,r,o,a){if(!i){g().error("No valid element provided to register_event");return}if(i.addEventListener&&!o)i.addEventListener(s,r,!!a);else{const l="on"+s,c=i[l];i[l]=e(i,r,c)}};function e(i,s,r){return function(o){if(o=o||t(window.event),!o)return;let a=!0,l;le(r)&&(l=r(o));const c=s.call(i,o);return(l===!1||c===!1)&&(a=!1),a}}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},n}(),he=function(n){return function(...e){try{return n.apply(this,e)}catch(t){g().error("Implementation error. Please turn on debug and contact support@usermaven.com.",t)}}},V=function(n){for(const e in n)typeof n[e]=="function"&&(n[e]=he(n[e]))};function J(n){for(let e in n)(n[e]===""||n[e]===null||n[e]===void 0||typeof n[e]=="object"&&Object.keys(n[e]).length===0)&&delete n[e];return n}function h(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return g().warn("window is not available"),!1}}function _(n=5){const e=new Uint8Array(n);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").slice(0,n)}function de(n){return n.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function D(n){return typeof n!="object"||n===null?n:Array.isArray(n)?n.map(D):Object.keys(n).reduce((e,t)=>{const i=de(t);return e[i]=D(n[t]),e},{})}function H(n){switch(typeof n.className){case"string":return n.className;case"object":return("baseVal"in n.className?n.className.baseVal:null)||n.getAttribute("class")||"";default:return""}}function Q(n){let e="";return z(n)&&!X(n)&&n.childNodes&&n.childNodes.length&&v(n.childNodes,function(t){K(t)&&t.textContent&&(e+=L(t.textContent).split(/(\s+)/).filter(I).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),L(e)}function W(n){return!!n&&n.nodeType===1}function y(n,e){return!!n&&!!n.tagName&&n.tagName.toLowerCase()===e.toLowerCase()}function K(n){return!!n&&n.nodeType===3}function F(n){return!!n&&n.nodeType===11}const N=["a","button","form","input","select","textarea","label"];function fe(n,e){if(!n||y(n,"html")||!W(n))return!1;let t=n;for(;t&&!y(t,"body");){if(t.classList&&t.classList.contains("um-no-capture"))return!1;t.parentNode&&F(t.parentNode)?t=t.parentNode.host:t=t.parentNode}let i=!1;for(t=n;t&&!y(t,"body");){if(t.parentNode&&F(t.parentNode)){t=t.parentNode.host,t&&N.indexOf(t.tagName.toLowerCase())>-1&&(i=!0);continue}const o=t.parentNode;if(!o)break;if(N.indexOf(o.tagName.toLowerCase())>-1)i=!0;else{const a=window.getComputedStyle(o);a&&a.getPropertyValue("cursor")==="pointer"&&(i=!0)}t=o}const s=window.getComputedStyle(n);if(s&&s.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;const r=n.tagName.toLowerCase();switch(r){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 i?e.type==="click":e.type==="click"&&(N.indexOf(r)>-1||n.getAttribute("contenteditable")==="true")}}function z(n){for(let i=n;i.parentNode&&!y(i,"body");i=i.parentNode){const s=H(i).split(" ");if(S(s,"ph-sensitive")||S(s,"ph-no-capture"))return!1}if(S(H(n).split(" "),"ph-include"))return!0;const e=n.type||"";if(typeof e=="string")switch(e.toLowerCase()){case"hidden":return!1;case"password":return!1}const t=n.name||n.id||"";return!(typeof t=="string"&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(t.replace(/[^a-zA-Z0-9]/g,"")))}function X(n){const e=["button","checkbox","submit","reset"];return!!(y(n,"input")&&!e.includes(n.type)||y(n,"select")||y(n,"textarea")||n.getAttribute("contenteditable")==="true")}function I(n){return!(n===null||ue(n)||typeof n=="string"&&(n=L(n),/^(?:(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((n||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(n)))}function ge(n){return typeof n=="string"?n.substring(0,10)==="_ngcontent"||n.substring(0,7)==="_nghost":!1}function M(){return _(10)}function pe(n){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(n).toLowerCase())}function me(n,e){let t;return function(...i){const s=()=>{clearTimeout(t),n(...i)};clearTimeout(t),t=setTimeout(s,e)}}function ye(n){const e={},t=n.replace(/^\?/,"").split("&");for(let i=0;i<t.length;i++){const s=t[i].split("=");s[0]!==""&&(e[decodeURIComponent(s[0])]=decodeURIComponent(s[1]||""))}return e}function Z(n){return typeof n=="string"||n instanceof String}function $(n){return n!==null&&typeof n=="object"&&n.constructor===Object}function we(n){if(n===null)return f.ERROR;const e=n.toUpperCase(),t=f[e];return t||t===0?t:f.ERROR}const ke=()=>{let n="false";return typeof window<"u"&&window.localStorage&&(n=localStorage.getItem("um_exclusion")),!(n==null||n==="false")};class ve{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=me(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"){if(!this.lastScrollDepth)return;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(),s=t-e;return Math.min(100,Math.floor(i/s*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(s=>s!==i)})}}const R=class R{constructor(e,t,i=g()){this.logger=i,this.scrollDepth=null,this.customProperties=[],this.domHandlersAttached=!1,this.client=e,this.options=t,this.scrollDepth=new ve(e),ae(this),V(this)}isBrowserSupported(){return typeof document<"u"&&typeof document.addEventListener=="function"}init(){if(!this.isBrowserSupported()){this.logger.debug("Browser not supported for autocapture");return}if(this.domHandlersAttached){this.logger.debug("Autocapture already initialized.");return}if(!(document&&document.body)){this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."),setTimeout(()=>this.init(),500);return}this.addDomEventHandlers(),this.domHandlersAttached=!0}addDomEventHandlers(){const e=t=>{t=t||window.event,this.captureEvent(t)};b(document,"submit",e,!1,!0),b(document,"change",e,!1,!0),b(document,"click",e,!1,!0),b(document,"visibilitychange",e,!1,!0),b(document,"scroll",e,!1,!0),b(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,s;let t=this.getEventTarget(e);if(K(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()||(s=this.scrollDepth)==null||s.send(),!0;if(t&&fe(t,e)){const r=[t];let o=t;for(;o.parentNode&&!y(o,"body");){if(F(o.parentNode)){r.push(o.parentNode.host),o=o.parentNode.host;continue}r.push(o.parentNode),o=o.parentNode}const a=[];let l,c=!1;if(v(r,w=>{const E=z(w);w.tagName.toLowerCase()==="a"&&(l=w.getAttribute("href"),l=E&&I(l)&&l);const u=H(w).split(" ");S(u,"ph-no-capture")&&(c=!0),a.push(this.getPropertiesFromElement(w,this.options.maskAllElementAttributes??!1,this.options.maskAllText??!1))}),this.options.maskAllText||(a[0].$el_text=Q(t)),l&&(a[0].attr__href=l),c)return!1;const d=ce(this.getDefaultProperties(e.type),{$elements:a},this.getCustomProperties(r));return this.client.track("$autocapture",d),!0}}getCustomProperties(e){const t={};return v(this.customProperties,i=>{v(i.event_selectors,s=>{const r=document.querySelectorAll(s);v(r,o=>{S(e,o)&&z(o)&&(t[i.name]=this.extractCustomPropertyValue(i))})})}),t}extractCustomPropertyValue(e){const t=[];return v(document.querySelectorAll(e.css_selector),function(i){let s;["input","select"].indexOf(i.tagName.toLowerCase())>-1?s=i.value:i.textContent&&(s=i.textContent),I(s)&&t.push(s)}),t.join(", ")}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}getPropertiesFromElement(e,t,i){const s=e.tagName.toLowerCase(),r={tag_name:s};N.indexOf(s)>-1&&!i&&(r.$el_text=Q(e));const o=H(e);o.length>0&&(r.classes=o.split(" ").filter(function(d){return d!==""})),v(e.attributes,function(d){X(e)&&["name","id","class"].indexOf(d.name)===-1||!t&&I(d.value)&&!ge(d.name)&&(r["attr__"+d.name]=d.value)});let a=1,l=1,c=e;for(;c=this.previousElementSibling(c);)a++,c.tagName===e.tagName&&l++;return r.nth_child=a,r.nth_of_type=l,r}previousElementSibling(e){if(e.previousElementSibling)return e.previousElementSibling;{let t=e;do t=t.previousSibling;while(t&&!W(t));return t}}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}encodeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}static enabledForProject(e,t=10,i=10){if(!e)return!1;let s=0;for(let r=0;r<e.length;r++)s+=e.charCodeAt(r);return s%t<i}};R.FORCE_CAPTURE_ATTR="data-um-force-capture",R.PREVENT_CAPTURE_ATTR="data-um-no-capture";let O=R;class _e{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 be{constructor(e,t,i=g()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),s=new Blob([JSON.stringify(e)],{type:"application/json"});if(navigator.sendBeacon(i,s))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}`:"",s=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${_()}?p_${_()}=${e}${t}${i}`:`${this.trackingHost}${s}?token=${e}${t}${i}`}}class Y{constructor(e,t,i=g()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),s=JSON.stringify(e),r={"Content-Type":"application/json",...this.getCustomHeaders()},o=await fetch(i,{method:"POST",headers:r,body:s});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}`:"",s=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${_()}?p_${_()}=${e}${t}${i}`:`${this.trackingHost}${s}?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 Pe{constructor(e,t,i=g()){this.trackingHost=e,this.logger=i,this.config=t}send(e){return new Promise((t,i)=>{const s=new XMLHttpRequest,r=this.config.key,o=this.constructUrl(r);s.open("POST",o,!0),s.setRequestHeader("Content-Type","application/json");const a=this.getCustomHeaders();Object.keys(a).forEach(l=>{s.setRequestHeader(l,a[l])}),s.onload=()=>{s.status>=200&&s.status<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),t()):i(new Error(`HTTP error! status: ${s.status}`))},s.onerror=()=>{i(new Error("Network error"))},s.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}`:"",s=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${_()}?p_${_()}=${e}${t}${i}`:`${this.trackingHost}${s}?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 G{constructor(e,t){this.storage={},this.prefix=`usermaven_${e}_`,this.load(),this.logger=t||g()}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(!h()){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(!h()){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 Ee{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,s=10,r=1e3,o=g(),a="default"){this.transport=e,this.maxRetries=t,this.retryInterval=i,this.batchSize=s,this.batchInterval=r,this.logger=o,this.queue=[],this.processing=!1,this.batchTimeoutId=null,this.isOnline=!0,this.persistence=new G(`offline_queue_${a}`),h()&&(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),h()?this.saveQueueToStorage():this.processBatch()}initNetworkListeners(){h()&&(window.addEventListener("online",()=>{this.isOnline=!0,this.processBatch()}),window.addEventListener("offline",()=>{this.isOnline=!1}))}scheduleBatch(){h()&&(this.batchTimeoutId!==null&&clearTimeout(this.batchTimeoutId),this.batchTimeoutId=window.setTimeout(()=>this.processBatch(),this.batchInterval))}async processBatch(){if((!h()||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`),h()&&this.saveQueueToStorage()}catch(i){this.logger.error("Failed to send batch",i),await this.handleBatchFailure(e)}this.processing=!1}h()&&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);h()&&(this.saveQueueToStorage(),await new Promise(t=>setTimeout(t,this.retryInterval)))}loadQueueFromStorage(){if(h()){const e=this.persistence.get("queue");e&&(this.queue=JSON.parse(e))}}saveQueueToStorage(){h()&&this.persistence.set("queue",JSON.stringify(this.queue))}}class Ae{constructor(e){this.clicks=[],this.threshold=3,this.timeWindow=2e3,this.distanceThreshold=30,this.client=e,this.initializeEventListener(),V(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 s={x:e,y:t,timestamp:i};this.clicks.push(s),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 a=this.clicks[o-1];return Math.sqrt(Math.pow(r.x-a.x,2)+Math.pow(r.y-a.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 Se{constructor(e,t,i=g()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=new(void 0)(this.constructUrl(t)),s={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 a=(void 0)(s,l=>{l.on("data",c=>{}),l.on("end",()=>{const c=l.statusCode||0;c>=200&&c<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${c}`))})});a.on("error",l=>{o(l)}),a.write(JSON.stringify(e)),a.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 P{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",J(i)),this.options.trackFieldChanges&&this.trackFieldChanges(t)}trackFieldChanges(e){e.querySelectorAll("input, select, textarea").forEach(i=>{i.addEventListener("change",s=>{const r=this._getFieldProps(s.target,0);this.instance.track("$form_field_change",J(r))})})}static getInstance(e,t="all",i={}){return P.instance||(P.instance=new P(e,t,i)),P.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 a=this._getFieldProps(r,o);Object.assign(t,a)}),t}_getFieldProps(e,t){const i=Object.keys(e.dataset).length?JSON.stringify(e.dataset):void 0,s=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`]:s,[`field_${t+1}_class`]:e.className,[`field_${t+1}_name`]:e.name,[`field_${t+1}_attributes`]:this._getElementAttributes(e)}}_getElementAttributes(e){return Object.keys(e.dataset).length?JSON.parse(JSON.stringify(e.dataset)):{}}getSafeText(e){let t="";return"value"in e&&e.type!=="password"?t=e.value:e.hasChildNodes()?t=Array.from(e.childNodes).filter(s=>s.nodeType===Node.TEXT_NODE).map(s=>s.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 s=[" ",`
|
|
2
|
-
`,"\r"," ","\f","\v"," "," "," "," "," "," "," "," "," "," "," "," "," ","\u2028","\u2029"," "," "," "].join("");for(;t<=i&&s.indexOf(e[t])>-1;)t++;for(;i>=t&&s.indexOf(e[i])>-1;)i--;return e.slice(t,i+1)}}class C{constructor(e){this.config=this.mergeConfig(e,q),this.logger=g(this.config.logLevel),this.namespace=e.namespace||"default",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,this.namespace),h()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new se(this.config.cookieDomain),this.config.autocapture&&O.enabledForProject(this.config.key)&&!this.config.disableAutocaptureListenerRegistration&&(this.autoCapture=new O(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=P.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new _e(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new Ae(this)),this.setupPageLeaveTracking()}mergeConfig(e,t){const i=JSON.parse(JSON.stringify(e));let s={...t,...i};return Object.keys(t).forEach(r=>{$(t[r])&&(s[r]=this.mergeConfig(e[r],t[r]))}),s}init(e){this.config={...this.config,...e},this.logger=g(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,this.namespace),h()&&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||`__eventn_id_${this.config.key}`;document.addEventListener("click",i=>{var a;const s=this.findClosestLink(i.target);if(!s)return;const r=s.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=(a=this.cookieManager)==null?void 0:a.get(t);l&&(o.searchParams.append("_um",l),s.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){const t="https://events.usermaven.com";if(!h())return new Se(e.trackingHost||t,e);const i="XMLHttpRequest"in window,s=typeof fetch<"u",r=typeof navigator<"u"&&"sendBeacon"in navigator;if(e.useBeaconApi&&r)return new be(e.trackingHost||t,e,this.logger);if(e.forceUseFetch&&s)return new Y(e.trackingHost||t,e,this.logger);if(i)return new Pe(e.trackingHost||t,e,this.logger);if(s)return new Y(e.trackingHost||t,e,this.logger);throw new Error("No suitable transport method available")}initializePersistence(){return this.config.disableEventPersistence||!h()?new Ee:new G(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var i,s;if(!h())return M();if(this.config.privacyPolicy==="strict"||this.config.cookiePolicy==="strict")return"";const e=this.config.cookieName||`__eventn_id_${this.config.key}`;let t=(i=this.cookieManager)==null?void 0:i.get(e);if(!t){if(this.config.crossDomainLinking){const a=new URLSearchParams(window.location.search).get("_um"),c=window.location.hash.substring(1).split("~"),d=c.length>1?c[1]:void 0;t=a||d||M()}t||(t=M());const r=365*10;(s=this.cookieManager)==null||s.set(e,t,r,document.location.protocol!=="http:",!1)}return t}async id(e,t=!1){if(!$(e))throw new Error("User data must be an object");if(e.email&&!pe(e.email))throw new Error("Invalid email provided");if(!e.id||!Z(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 s={...e,anonymous_id:this.anonymousId};await this.track("user_identify",s)}this.logger.info("User identified:",e)}track(e,t,i=!1){this.trackInternal(e,t,i)}trackInternal(e,t,i=!1){if(ke()){this.logger.debug("Tracking disabled due to um_exclusion setting");return}if(!Z(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 r=this.createEventPayload(e,t);try{if(i){this.transport.send(r),this.logger.debug(`Event sent: ${e}`,[r]);return}this.retryQueue.add(r),this.logger.debug(`Event tracked: ${e}`,[r])}catch(o){throw this.logger.error(`Failed to track event: ${e}`,o),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")||{},s=this.persistence.get("companyProps")||(i==null?void 0:i.company)||{},r=this.persistence.get("userId"),o=this.persistence.get("global_props")||{},a=this.persistence.get(`props_${e}`)||{};let l=t||{};const c={event_id:"",user:{anonymous_id:this.anonymousId,id:r,...i},...s&&{company:s},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,...a};if(e==="$autocapture"){const d=this.processAutocaptureAttributes(t||{});c.autocapture_attributes=d}else e!=="user_identify"&&e!=="group"&&(Array.isArray(this.config.propertyBlacklist)&&this.config.propertyBlacklist.forEach(d=>{delete l[d]}),c.event_attributes=l);return h()&&(c.referer=document.referrer,c.url=window.location.href,c.page_title=document.title,c.doc_path=window.location.pathname,c.doc_host=window.location.hostname,c.doc_search=window.location.search,c.screen_resolution=`${window.screen.width}x${window.screen.height}`,c.vp_size=`${window.innerWidth}x${window.innerHeight}`,c.user_agent=navigator.userAgent,c.user_language=navigator.language,c.doc_encoding=document.characterSet,c.utm=this.getUtmParams()),c}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(s=>{delete t[s]}),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(h()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=ye(window.location.search);return["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(s=>{t[s]&&(e[s.replace("utm_","")]=t[s])}),e}pageview(){h()?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(!h())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 s=history.pushState;history.pushState=function(){return i(),s.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||`__eventn_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,s=(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)}s&&this.persistence.save(),this.logger.debug("Properties set",{properties:e,eventType:i||"global",persist:s})}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,s=(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)}s&&this.persistence.save(),this.logger.debug(`Property unset: ${e}`,`Event type: ${i||"global"}`)}}function ee(){return typeof window<"u"&&typeof window.define=="function"&&window.define.amd}function $e(){return ee()?window.define:void 0}const Ce="__USERMAVEN_AUTOCAPTURE_INITIALIZED__";function T(n){const e=JSON.parse(JSON.stringify(n)),t=D(e),i={...q,...t};if(!i.key)throw new Error("API key is required!");if(!i.trackingHost)throw new Error("Tracking host is required!");const s=i.key||"",r=`${Ce}${s}`;return h()&&i.autocapture&&window[r]&&(console.warn("Usermaven: Autocapture already initialized in another instance, skipping duplicate initialization."),i.disableAutocaptureListenerRegistration=!0),h()&&i.autocapture&&!i.disableAutocaptureListenerRegistration&&(window[r]=!0),new C(i)}function Te(n){var s;const e={key:n.getAttribute("data-key")||void 0,trackingHost:n.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:we(n.getAttribute("data-log-level")),autocapture:n.getAttribute("data-autocapture")==="true",formTracking:n.getAttribute("data-form-tracking")==="false"?!1:n.getAttribute("data-form-tracking")==="true"?"all":n.getAttribute("data-form-tracking"),autoPageview:n.getAttribute("data-auto-pageview")==="true",useBeaconApi:n.getAttribute("data-use-beacon-api")==="true",forceUseFetch:n.getAttribute("data-force-use-fetch")==="true",gaHook:n.getAttribute("data-ga-hook")==="true",segmentHook:n.getAttribute("data-segment-hook")==="true",randomizeUrl:n.getAttribute("data-randomize-url")==="true",capture3rdPartyCookies:n.getAttribute("data-capture-3rd-party-cookies")==="false"?!1:void 0,idMethod:n.getAttribute("data-id-method")||void 0,privacyPolicy:n.getAttribute("data-privacy-policy")==="strict"?"strict":void 0,ipPolicy:n.getAttribute("data-ip-policy")||void 0,cookiePolicy:n.getAttribute("data-cookie-policy")||void 0,minSendTimeout:parseInt(n.getAttribute("data-min-send-timeout")||"",10)||void 0,maxSendTimeout:parseInt(n.getAttribute("data-max-send-timeout")||"",10)||void 0,maxSendAttempts:parseInt(n.getAttribute("data-max-send-attempts")||"",10)||void 0,propertiesStringMaxLength:parseInt(n.getAttribute("data-properties-string-max-length")||"",10)||null,propertyBlacklist:((s=n.getAttribute("data-property-blacklist"))==null?void 0:s.split(","))||void 0,exclude:n.getAttribute("data-exclude")||void 0,namespace:n.getAttribute("data-namespace")||void 0,crossDomainLinking:n.getAttribute("data-cross-domain-linking")!=="false",domains:n.getAttribute("data-domains")||void 0,maskAllText:n.getAttribute("data-mask-all-text")==="true",maskAllElementAttributes:n.getAttribute("data-mask-all-element-attributes")==="true"};e.privacyPolicy==="strict"&&(e.cookiePolicy="strict",e.ipPolicy="strict"),e.cookiePolicy==="comply"&&e.useBeaconApi&&(e.cookiePolicy="strict");const t=T(e),i=e.namespace||"usermaven";return h()&&t.pageview(),xe(i,t),t}function xe(n,e){let t=!1;const i=[],s=[];function r(){for(;i.length>0;){const u=i.shift();if(u){const p=u[u.length-1];if(p&&typeof p.resolve=="function"){const k=u.pop();try{const A=a.apply(null,u);A&&typeof A.then=="function"?A.then(k.resolve).catch(k.reject):k.resolve(A)}catch(A){k.reject(A)}}else try{a.apply(null,u)}catch(k){console.error("Usermaven: Error processing queued command:",k)}}}}function o(){s.forEach(u=>u()),s.length=0}function a(...u){const p=u[0];if(p==="onLoad"){typeof u[1]=="function"&&(t?u[1]():s.push(u[1]));return}if(!t){i.push(u);return}if(typeof e[p]=="function")return e[p].apply(e,u.slice(1));console.error(`Method ${p} not found on UsermavenClient`)}const l=["id","group","reset"],c=["track","pageview","set","unset","rawTrack","setUserId"];[...l,...c].forEach(u=>{a[u]=function(...p){if(!t){if(l.includes(u))return new Promise((ie,k)=>{i.push([u,...p,{resolve:ie,reject:k}])});i.push([u,...p]);return}if(typeof e[u]=="function")return e[u].apply(e,p)}}),a.getConfig=function(){return t?e.getConfig():(console.warn("Usermaven client not ready yet"),null)},window[n]=a;const w=`${n}Q`,E=window[w]||[];for(window[w]=E,E.push=function(...u){return a.apply(null,u),Array.prototype.push.apply(this,u)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${n} is ready`)},0);E.length>0;){const u=E.shift();u&&i.push(u)}}let te=!1,B=null;if(h()){const n=$e();n&&n("usermaven",[],function(){return{usermavenClient:T,UsermavenClient:C,LogLevel:f,getScriptTagClient:()=>B}}),typeof window<"u"&&(window.usermavenClient=T,window.UsermavenClient=C,window.usermavenScriptTagClient=()=>B),function(e,t){const i=e.currentScript;function s(){return te||!i||!i.hasAttribute("data-key")||i.getAttribute("data-no-auto-init")==="true"?!1:i.src.includes("lib.js")}function r(){s()&&(console.log("[Usermaven] Auto-initializing from script tag"),B=Te(i),te=!0)}typeof t<"u"&&i&&(e.readyState==="loading"?e.addEventListener("DOMContentLoaded",r):r())}(document,window)}typeof module<"u"&&module.exports&&!ee()&&(module.exports={usermavenClient:T,UsermavenClient:C,Config:void 0,UserProps:void 0,EventPayload:void 0,LogLevel:f,ClientProperties:void 0}),m.LogLevel=f,m.UsermavenClient=C,m.usermavenClient=T,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(m,f){typeof exports=="object"&&typeof module<"u"?f(exports):typeof define=="function"&&define.amd?define(["exports"],f):(m=typeof globalThis<"u"?globalThis:m||self,f(m.Usermaven={}))})(this,function(m){"use strict";var f=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n))(f||{});class ne{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 g(n=0){return new ne(n)}const q={logLevel:f.ERROR,useBeaconApi:!1,forceUseFetch:!1,trackingHost:"t.usermaven.com",autocapture:!1,rageClick:!1,formTracking:!1,autoPageview:!0,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 se{constructor(e){this.domain=e,this.cookieDomain=this.getCookieDomain()}set(e,t,i=365,s=!0,r=!1){const o=new Date;o.setTime(o.getTime()+i*24*60*60*1e3);const a=`expires=${o.toUTCString()}`,l=s?"; Secure":"",c=r?"; HttpOnly":"";document.cookie=`${e}=${t};${a};path=/;domain=${this.cookieDomain}${l}${c}`}get(e){const t=e+"=",i=document.cookie.split(";");for(let s=0;s<i.length;s++){let r=i[s].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("."),s=i.length;return s>2&&(i[s-1].length==2?(t=i[s-2]+"."+i[s-1],i[s-2].length==2&&(t=i[s-3]+"."+t)):t=i[s-2]+"."+i[s-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 re=Object.prototype.hasOwnProperty,x=Array.prototype.forEach,L={};function oe(n,e,t){if(Array.isArray(n)){if(x&&n.forEach===x)n.forEach(e,t);else if("length"in n&&n.length===+n.length){for(let i=0,s=n.length;i<s;i++)if(i in n&&e.call(t,n[i],i)===L)return}}}const U=function(n){return n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},ae=function(n){for(const e in n)typeof n[e]=="function"&&(n[e]=n[e].bind(n))};function v(n,e,t){if(n!=null){if(x&&Array.isArray(n)&&n.forEach===x)n.forEach(e,t);else if("length"in n&&n.length===+n.length){for(let i=0,s=n.length;i<s;i++)if(i in n&&e.call(t,n[i],i)===L)return}else for(const i in n)if(re.call(n,i)&&e.call(t,n[i],i)===L)return}}const ce=function(n,...e){return oe(e,function(t){for(const i in t)t[i]!==void 0&&(n[i]=t[i])}),n};function S(n,e){return n.indexOf(e)!==-1}const le=function(n){try{return/^\s*\bfunction\b/.test(n)}catch{return!1}},ue=function(n){return n===void 0},b=function(){const n=function(i,s,r,o,a){if(!i){g().error("No valid element provided to register_event");return}if(i.addEventListener&&!o)i.addEventListener(s,r,!!a);else{const l="on"+s,c=i[l];i[l]=e(i,r,c)}};function e(i,s,r){return function(o){if(o=o||t(window.event),!o)return;let a=!0,l;le(r)&&(l=r(o));const c=s.call(i,o);return(l===!1||c===!1)&&(a=!1),a}}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},n}(),he=function(n){return function(...e){try{return n.apply(this,e)}catch(t){g().error("Implementation error. Please turn on debug and contact support@usermaven.com.",t)}}},V=function(n){for(const e in n)typeof n[e]=="function"&&(n[e]=he(n[e]))};function Q(n){for(let e in n)(n[e]===""||n[e]===null||n[e]===void 0||typeof n[e]=="object"&&Object.keys(n[e]).length===0)&&delete n[e];return n}function h(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return g().warn("window is not available"),!1}}function _(n=5){const e=new Uint8Array(n);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").slice(0,n)}function de(n){return n.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function D(n){return typeof n!="object"||n===null?n:Array.isArray(n)?n.map(D):Object.keys(n).reduce((e,t)=>{const i=de(t);return e[i]=D(n[t]),e},{})}function H(n){switch(typeof n.className){case"string":return n.className;case"object":return("baseVal"in n.className?n.className.baseVal:null)||n.getAttribute("class")||"";default:return""}}function J(n){let e="";return z(n)&&!X(n)&&n.childNodes&&n.childNodes.length&&v(n.childNodes,function(t){K(t)&&t.textContent&&(e+=U(t.textContent).split(/(\s+)/).filter(O).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),U(e)}function W(n){return!!n&&n.nodeType===1}function y(n,e){return!!n&&!!n.tagName&&n.tagName.toLowerCase()===e.toLowerCase()}function K(n){return!!n&&n.nodeType===3}function F(n){return!!n&&n.nodeType===11}const N=["a","button","form","input","select","textarea","label"];function fe(n,e){if(!n||y(n,"html")||!W(n))return!1;let t=n;for(;t&&!y(t,"body");){if(t.classList&&t.classList.contains("um-no-capture"))return!1;t.parentNode&&F(t.parentNode)?t=t.parentNode.host:t=t.parentNode}let i=!1;for(t=n;t&&!y(t,"body");){if(t.parentNode&&F(t.parentNode)){t=t.parentNode.host,t&&N.indexOf(t.tagName.toLowerCase())>-1&&(i=!0);continue}const o=t.parentNode;if(!o)break;if(N.indexOf(o.tagName.toLowerCase())>-1)i=!0;else{const a=window.getComputedStyle(o);a&&a.getPropertyValue("cursor")==="pointer"&&(i=!0)}t=o}const s=window.getComputedStyle(n);if(s&&s.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;const r=n.tagName.toLowerCase();switch(r){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 i?e.type==="click":e.type==="click"&&(N.indexOf(r)>-1||n.getAttribute("contenteditable")==="true")}}function z(n){for(let i=n;i.parentNode&&!y(i,"body");i=i.parentNode){const s=H(i).split(" ");if(S(s,"ph-sensitive")||S(s,"ph-no-capture"))return!1}if(S(H(n).split(" "),"ph-include"))return!0;const e=n.type||"";if(typeof e=="string")switch(e.toLowerCase()){case"hidden":return!1;case"password":return!1}const t=n.name||n.id||"";return!(typeof t=="string"&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(t.replace(/[^a-zA-Z0-9]/g,"")))}function X(n){const e=["button","checkbox","submit","reset"];return!!(y(n,"input")&&!e.includes(n.type)||y(n,"select")||y(n,"textarea")||n.getAttribute("contenteditable")==="true")}function O(n){return!(n===null||ue(n)||typeof n=="string"&&(n=U(n),/^(?:(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((n||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(n)))}function ge(n){return typeof n=="string"?n.substring(0,10)==="_ngcontent"||n.substring(0,7)==="_nghost":!1}function M(){return _(10)}function pe(n){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(n).toLowerCase())}function me(n,e){let t;return function(...i){const s=()=>{clearTimeout(t),n(...i)};clearTimeout(t),t=setTimeout(s,e)}}function ye(n){const e={},t=n.replace(/^\?/,"").split("&");for(let i=0;i<t.length;i++){const s=t[i].split("=");s[0]!==""&&(e[decodeURIComponent(s[0])]=decodeURIComponent(s[1]||""))}return e}function Z(n){return typeof n=="string"||n instanceof String}function C(n){return n!==null&&typeof n=="object"&&n.constructor===Object}function we(n){if(n===null)return f.ERROR;const e=n.toUpperCase(),t=f[e];return t||t===0?t:f.ERROR}const ke=()=>{let n="false";return typeof window<"u"&&window.localStorage&&(n=localStorage.getItem("um_exclusion")),!(n==null||n==="false")};class ve{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=me(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"){if(!this.lastScrollDepth)return;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(),s=t-e;return Math.min(100,Math.floor(i/s*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(s=>s!==i)})}destroy(){window.removeEventListener("scroll",this.debouncedHandleScroll)}}const R=class R{constructor(e,t,i=g()){this.logger=i,this.scrollDepth=null,this.customProperties=[],this.domHandlersAttached=!1,this.client=e,this.options=t,this.scrollDepth=new ve(e),ae(this),V(this)}isBrowserSupported(){return typeof document<"u"&&typeof document.addEventListener=="function"}init(){if(!this.isBrowserSupported()){this.logger.debug("Browser not supported for autocapture");return}if(this.domHandlersAttached){this.logger.debug("Autocapture already initialized.");return}if(!(document&&document.body)){this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."),setTimeout(()=>this.init(),500);return}this.addDomEventHandlers(),this.domHandlersAttached=!0}addDomEventHandlers(){const e=t=>{t=t||window.event,this.captureEvent(t)};b(document,"submit",e,!1,!0),b(document,"change",e,!1,!0),b(document,"click",e,!1,!0),b(document,"visibilitychange",e,!1,!0),b(document,"scroll",e,!1,!0),b(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,s;let t=this.getEventTarget(e);if(K(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()||(s=this.scrollDepth)==null||s.send(),!0;if(t&&fe(t,e)){const r=[t];let o=t;for(;o.parentNode&&!y(o,"body");){if(F(o.parentNode)){r.push(o.parentNode.host),o=o.parentNode.host;continue}r.push(o.parentNode),o=o.parentNode}const a=[];let l,c=!1;if(v(r,w=>{const E=z(w);w.tagName.toLowerCase()==="a"&&(l=w.getAttribute("href"),l=E&&O(l)&&l);const u=H(w).split(" ");S(u,"ph-no-capture")&&(c=!0),a.push(this.getPropertiesFromElement(w,this.options.maskAllElementAttributes??!1,this.options.maskAllText??!1))}),this.options.maskAllText||(a[0].$el_text=J(t)),l&&(a[0].attr__href=l),c)return!1;const d=ce(this.getDefaultProperties(e.type),{$elements:a},this.getCustomProperties(r));return this.client.track("$autocapture",d),!0}}getCustomProperties(e){const t={};return v(this.customProperties,i=>{v(i.event_selectors,s=>{const r=document.querySelectorAll(s);v(r,o=>{S(e,o)&&z(o)&&(t[i.name]=this.extractCustomPropertyValue(i))})})}),t}extractCustomPropertyValue(e){const t=[];return v(document.querySelectorAll(e.css_selector),function(i){let s;["input","select"].indexOf(i.tagName.toLowerCase())>-1?s=i.value:i.textContent&&(s=i.textContent),O(s)&&t.push(s)}),t.join(", ")}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}getPropertiesFromElement(e,t,i){const s=e.tagName.toLowerCase(),r={tag_name:s};N.indexOf(s)>-1&&!i&&(r.$el_text=J(e));const o=H(e);o.length>0&&(r.classes=o.split(" ").filter(function(d){return d!==""})),v(e.attributes,function(d){X(e)&&["name","id","class"].indexOf(d.name)===-1||!t&&O(d.value)&&!ge(d.name)&&(r["attr__"+d.name]=d.value)});let a=1,l=1,c=e;for(;c=this.previousElementSibling(c);)a++,c.tagName===e.tagName&&l++;return r.nth_child=a,r.nth_of_type=l,r}previousElementSibling(e){if(e.previousElementSibling)return e.previousElementSibling;{let t=e;do t=t.previousSibling;while(t&&!W(t));return t}}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}encodeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}static enabledForProject(e,t=10,i=10){if(!e)return!1;let s=0;for(let r=0;r<e.length;r++)s+=e.charCodeAt(r);return s%t<i}};R.FORCE_CAPTURE_ATTR="data-um-force-capture",R.PREVENT_CAPTURE_ATTR="data-um-no-capture";let I=R;class _e{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 be{constructor(e,t,i=g()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),s=new Blob([JSON.stringify(e)],{type:"application/json"});if(navigator.sendBeacon(i,s))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}`:"",s=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${_()}?p_${_()}=${e}${t}${i}`:`${this.trackingHost}${s}?token=${e}${t}${i}`}}class Y{constructor(e,t,i=g()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),s=JSON.stringify(e),r={"Content-Type":"application/json",...this.getCustomHeaders()},o=await fetch(i,{method:"POST",headers:r,body:s});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}`:"",s=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${_()}?p_${_()}=${e}${t}${i}`:`${this.trackingHost}${s}?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 Pe{constructor(e,t,i=g()){this.trackingHost=e,this.logger=i,this.config=t}send(e){return new Promise((t,i)=>{const s=new XMLHttpRequest,r=this.config.key,o=this.constructUrl(r);s.open("POST",o,!0),s.setRequestHeader("Content-Type","application/json");const a=this.getCustomHeaders();Object.keys(a).forEach(l=>{s.setRequestHeader(l,a[l])}),s.onload=()=>{s.status>=200&&s.status<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),t()):i(new Error(`HTTP error! status: ${s.status}`))},s.onerror=()=>{i(new Error("Network error"))},s.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}`:"",s=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${_()}?p_${_()}=${e}${t}${i}`:`${this.trackingHost}${s}?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 G{constructor(e,t){this.storage={},this.prefix=`usermaven_${e}_`,this.load(),this.logger=t||g()}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(!h()){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(!h()){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 Ee{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,s=10,r=1e3,o=g(),a="default"){this.transport=e,this.maxRetries=t,this.retryInterval=i,this.batchSize=s,this.batchInterval=r,this.logger=o,this.queue=[],this.processing=!1,this.batchTimeoutId=null,this.isOnline=!0,this.persistence=new G(`offline_queue_${a}`),h()&&(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),h()?this.saveQueueToStorage():this.processBatch()}initNetworkListeners(){h()&&(window.addEventListener("online",()=>{this.isOnline=!0,this.processBatch()}),window.addEventListener("offline",()=>{this.isOnline=!1}))}scheduleBatch(){h()&&(this.batchTimeoutId!==null&&clearTimeout(this.batchTimeoutId),this.batchTimeoutId=window.setTimeout(()=>this.processBatch(),this.batchInterval))}async processBatch(){if((!h()||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`),h()&&this.saveQueueToStorage()}catch(i){this.logger.error("Failed to send batch",i),await this.handleBatchFailure(e)}this.processing=!1}h()&&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);h()&&(this.saveQueueToStorage(),await new Promise(t=>setTimeout(t,this.retryInterval)))}loadQueueFromStorage(){if(h()){const e=this.persistence.get("queue");e&&(this.queue=JSON.parse(e))}}saveQueueToStorage(){h()&&this.persistence.set("queue",JSON.stringify(this.queue))}}class Ae{constructor(e){this.clicks=[],this.threshold=3,this.timeWindow=2e3,this.distanceThreshold=30,this.client=e,this.initializeEventListener(),V(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 s={x:e,y:t,timestamp:i};this.clicks.push(s),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 a=this.clicks[o-1];return Math.sqrt(Math.pow(r.x-a.x,2)+Math.pow(r.y-a.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 Se{constructor(e,t,i=g()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=new(void 0)(this.constructUrl(t)),s={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 a=(void 0)(s,l=>{l.on("data",c=>{}),l.on("end",()=>{const c=l.statusCode||0;c>=200&&c<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${c}`))})});a.on("error",l=>{o(l)}),a.write(JSON.stringify(e)),a.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 P{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",Q(i)),this.options.trackFieldChanges&&this.trackFieldChanges(t)}trackFieldChanges(e){e.querySelectorAll("input, select, textarea").forEach(i=>{i.addEventListener("change",s=>{const r=this._getFieldProps(s.target);this.instance.track("$form_field_change",Q({form_id:e.id,form_name:e.name||"",field:r}))})})}static getInstance(e,t="all",i={}){return P.instance||(P.instance=new P(e,t,i)),P.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),fields:[]},i=e.querySelectorAll("input, select, textarea");return Array.from(i).filter(r=>!r.classList.contains("um-no-capture")).forEach(r=>{const o=this._getFieldProps(r);t.fields.push(o)}),t}_getFieldProps(e){const t=Object.keys(e.dataset).length?this._convertDOMStringMapToObject(e.dataset):void 0,i=this.getSafeText(e);return{tag:e.tagName.toLowerCase(),type:e instanceof HTMLInputElement?e.type:void 0,data_attributes:t,id:e.id,value:i,class:e.className,name:e.name,attributes:this._getElementAttributes(e)}}_getElementAttributes(e){return Object.keys(e.dataset).length?this._convertDOMStringMapToObject(e.dataset):{}}_convertDOMStringMapToObject(e){const t={};for(const i in e)e.hasOwnProperty(i)&&e[i]!==void 0&&(t[i]=e[i]);return t}getSafeText(e){let t="";return"value"in e&&e.type!=="password"?t=e.value:e.hasChildNodes()?t=Array.from(e.childNodes).filter(s=>s.nodeType===Node.TEXT_NODE).map(s=>s.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 s=[" ",`
|
|
2
|
+
`,"\r"," ","\f","\v"," "," "," "," "," "," "," "," "," "," "," "," "," ","\u2028","\u2029"," "," "," "].join("");for(;t<=i&&s.indexOf(e[t])>-1;)t++;for(;i>=t&&s.indexOf(e[i])>-1;)i--;return e.slice(t,i+1)}}class T{constructor(e){this.config=this.mergeConfig(e,q),this.logger=g(this.config.logLevel),this.namespace=e.namespace||"default",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,this.namespace),h()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new se(this.config.cookieDomain),this.config.autocapture&&I.enabledForProject(this.config.key)&&!this.config.disableAutocaptureListenerRegistration&&(this.autoCapture=new I(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=P.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new _e(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new Ae(this)),this.setupPageLeaveTracking()}mergeConfig(e,t){const i=JSON.parse(JSON.stringify(e));let s={...t,...i};return Object.keys(t).forEach(r=>{C(t[r])&&(s[r]=this.mergeConfig(e[r],t[r]))}),s}init(e){this.config={...this.config,...e},this.logger=g(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,this.namespace),h()&&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||`__eventn_id_${this.config.key}`;document.addEventListener("click",i=>{var a;const s=this.findClosestLink(i.target);if(!s)return;const r=s.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=(a=this.cookieManager)==null?void 0:a.get(t);l&&(o.searchParams.append("_um",l),s.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){const t="https://events.usermaven.com";if(!h())return new Se(e.trackingHost||t,e);const i="XMLHttpRequest"in window,s=typeof fetch<"u",r=typeof navigator<"u"&&"sendBeacon"in navigator;if(e.useBeaconApi&&r)return new be(e.trackingHost||t,e,this.logger);if(e.forceUseFetch&&s)return new Y(e.trackingHost||t,e,this.logger);if(i)return new Pe(e.trackingHost||t,e,this.logger);if(s)return new Y(e.trackingHost||t,e,this.logger);throw new Error("No suitable transport method available")}initializePersistence(){return this.config.disableEventPersistence||!h()?new Ee:new G(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var i,s;if(!h())return M();if(this.config.privacyPolicy==="strict"||this.config.cookiePolicy==="strict")return"";const e=this.config.cookieName||`__eventn_id_${this.config.key}`;let t=(i=this.cookieManager)==null?void 0:i.get(e);if(!t){if(this.config.crossDomainLinking){const a=new URLSearchParams(window.location.search).get("_um"),c=window.location.hash.substring(1).split("~"),d=c.length>1?c[1]:void 0;t=a||d||M()}t||(t=M());const r=365*10;(s=this.cookieManager)==null||s.set(e,t,r,document.location.protocol!=="http:",!1)}return t}async id(e,t=!1){if(!C(e))throw new Error("User data must be an object");if(e.email&&!pe(e.email))throw new Error("Invalid email provided");if(!e.id||!Z(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 s={...e,anonymous_id:this.anonymousId};await this.track("user_identify",s)}this.logger.info("User identified:",e)}track(e,t,i=!1){this.trackInternal(e,t,i)}trackInternal(e,t,i=!1){if(ke()){this.logger.debug("Tracking disabled due to um_exclusion setting");return}if(!Z(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 r=this.createEventPayload(e,t);try{if(i){this.transport.send(r),this.logger.debug(`Event sent: ${e}`,[r]);return}this.retryQueue.add(r),this.logger.debug(`Event tracked: ${e}`,[r])}catch(o){throw this.logger.error(`Failed to track event: ${e}`,o),new Error(`Failed to track event: ${e}`)}}rawTrack(e){if(!C(e))throw new Error("Event payload must be an object");this.track("raw",e)}async group(e,t=!1){if(!C(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")||{},s=this.persistence.get("companyProps")||(i==null?void 0:i.company)||{},r=this.persistence.get("userId"),o=this.persistence.get("global_props")||{},a=this.persistence.get(`props_${e}`)||{};let l=t||{};const c={event_id:"",user:{anonymous_id:this.anonymousId,id:r,...i},...s&&{company:s},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,...a};if(e==="$autocapture"){const d=this.processAutocaptureAttributes(t||{});c.autocapture_attributes=d}else e!=="user_identify"&&e!=="group"&&(Array.isArray(this.config.propertyBlacklist)&&this.config.propertyBlacklist.forEach(d=>{delete l[d]}),c.event_attributes=l);return h()&&(c.referer=document.referrer,c.url=window.location.href,c.page_title=document.title,c.doc_path=window.location.pathname,c.doc_host=window.location.hostname,c.doc_search=window.location.search,c.screen_resolution=`${window.screen.width}x${window.screen.height}`,c.vp_size=`${window.innerWidth}x${window.innerHeight}`,c.user_agent=navigator.userAgent,c.user_language=navigator.language,c.doc_encoding=document.characterSet,c.utm=this.getUtmParams()),c}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(s=>{delete t[s]}),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(h()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=ye(window.location.search);return["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(s=>{t[s]&&(e[s.replace("utm_","")]=t[s])}),e}pageview(){h()?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(!h())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 s=history.pushState;history.pushState=function(){return i(),s.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||`__eventn_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(!C(e))throw new Error("Properties must be an object");const i=t==null?void 0:t.eventType,s=(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)}s&&this.persistence.save(),this.logger.debug("Properties set",{properties:e,eventType:i||"global",persist:s})}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,s=(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)}s&&this.persistence.save(),this.logger.debug(`Property unset: ${e}`,`Event type: ${i||"global"}`)}}function ee(){return typeof window<"u"&&typeof window.define=="function"&&window.define.amd}function Ce(){return ee()?window.define:void 0}const Te="__USERMAVEN_AUTOCAPTURE_INITIALIZED__";function $(n){const e=JSON.parse(JSON.stringify(n)),t=D(e),i={...q,...t};if(!i.key)throw new Error("API key is required!");if(!i.trackingHost)throw new Error("Tracking host is required!");const s=i.key||"",r=`${Te}${s}`;return h()&&i.autocapture&&window[r]&&(console.warn("Usermaven: Autocapture already initialized in another instance, skipping duplicate initialization."),i.disableAutocaptureListenerRegistration=!0),h()&&i.autocapture&&!i.disableAutocaptureListenerRegistration&&(window[r]=!0),new T(i)}function $e(n){var s;const e={key:n.getAttribute("data-key")||void 0,trackingHost:n.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:we(n.getAttribute("data-log-level")),autocapture:n.getAttribute("data-autocapture")==="true",formTracking:n.getAttribute("data-form-tracking")==="false"?!1:n.getAttribute("data-form-tracking")==="true"?"all":n.getAttribute("data-form-tracking"),autoPageview:n.getAttribute("data-auto-pageview")==="true",useBeaconApi:n.getAttribute("data-use-beacon-api")==="true",forceUseFetch:n.getAttribute("data-force-use-fetch")==="true",gaHook:n.getAttribute("data-ga-hook")==="true",segmentHook:n.getAttribute("data-segment-hook")==="true",randomizeUrl:n.getAttribute("data-randomize-url")==="true",capture3rdPartyCookies:n.getAttribute("data-capture-3rd-party-cookies")==="false"?!1:void 0,idMethod:n.getAttribute("data-id-method")||void 0,privacyPolicy:n.getAttribute("data-privacy-policy")==="strict"?"strict":void 0,ipPolicy:n.getAttribute("data-ip-policy")||void 0,cookiePolicy:n.getAttribute("data-cookie-policy")||void 0,minSendTimeout:parseInt(n.getAttribute("data-min-send-timeout")||"",10)||void 0,maxSendTimeout:parseInt(n.getAttribute("data-max-send-timeout")||"",10)||void 0,maxSendAttempts:parseInt(n.getAttribute("data-max-send-attempts")||"",10)||void 0,propertiesStringMaxLength:parseInt(n.getAttribute("data-properties-string-max-length")||"",10)||null,propertyBlacklist:((s=n.getAttribute("data-property-blacklist"))==null?void 0:s.split(","))||void 0,exclude:n.getAttribute("data-exclude")||void 0,namespace:n.getAttribute("data-namespace")||void 0,crossDomainLinking:n.getAttribute("data-cross-domain-linking")!=="false",domains:n.getAttribute("data-domains")||void 0,maskAllText:n.getAttribute("data-mask-all-text")==="true",maskAllElementAttributes:n.getAttribute("data-mask-all-element-attributes")==="true"};e.privacyPolicy==="strict"&&(e.cookiePolicy="strict",e.ipPolicy="strict"),e.cookiePolicy==="comply"&&e.useBeaconApi&&(e.cookiePolicy="strict");const t=$(e),i=e.namespace||"usermaven";return h()&&t.pageview(),xe(i,t),t}function xe(n,e){let t=!1;const i=[],s=[];function r(){for(;i.length>0;){const u=i.shift();if(u){const p=u[u.length-1];if(p&&typeof p.resolve=="function"){const k=u.pop();try{const A=a.apply(null,u);A&&typeof A.then=="function"?A.then(k.resolve).catch(k.reject):k.resolve(A)}catch(A){k.reject(A)}}else try{a.apply(null,u)}catch(k){console.error("Usermaven: Error processing queued command:",k)}}}}function o(){s.forEach(u=>u()),s.length=0}function a(...u){const p=u[0];if(p==="onLoad"){typeof u[1]=="function"&&(t?u[1]():s.push(u[1]));return}if(!t){i.push(u);return}if(typeof e[p]=="function")return e[p].apply(e,u.slice(1));console.error(`Method ${p} not found on UsermavenClient`)}const l=["id","group","reset"],c=["track","pageview","set","unset","rawTrack","setUserId"];[...l,...c].forEach(u=>{a[u]=function(...p){if(!t){if(l.includes(u))return new Promise((ie,k)=>{i.push([u,...p,{resolve:ie,reject:k}])});i.push([u,...p]);return}if(typeof e[u]=="function")return e[u].apply(e,p)}}),a.getConfig=function(){return t?e.getConfig():(console.warn("Usermaven client not ready yet"),null)},window[n]=a;const w=`${n}Q`,E=window[w]||[];for(window[w]=E,E.push=function(...u){return a.apply(null,u),Array.prototype.push.apply(this,u)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${n} is ready`)},0);E.length>0;){const u=E.shift();u&&i.push(u)}}let te=!1,B=null;if(h()){const n=Ce();n&&n("usermaven",[],function(){return{usermavenClient:$,UsermavenClient:T,LogLevel:f,getScriptTagClient:()=>B}}),typeof window<"u"&&(window.usermavenClient=$,window.UsermavenClient=T,window.usermavenScriptTagClient=()=>B),function(e,t){const i=e.currentScript;function s(){return te||!i||!i.hasAttribute("data-key")||i.getAttribute("data-no-auto-init")==="true"?!1:i.src.includes("lib.js")}function r(){s()&&(console.log("[Usermaven] Auto-initializing from script tag"),B=$e(i),te=!0)}typeof t<"u"&&i&&(e.readyState==="loading"?e.addEventListener("DOMContentLoaded",r):r())}(document,window)}typeof module<"u"&&module.exports&&!ee()&&(module.exports={usermavenClient:$,UsermavenClient:T,Config:void 0,UserProps:void 0,EventPayload:void 0,LogLevel:f,ClientProperties:void 0}),m.LogLevel=f,m.UsermavenClient=T,m.usermavenClient=$,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
|
|
@@ -14,6 +14,7 @@ export default class FormTracking {
|
|
|
14
14
|
private _getFormDetails;
|
|
15
15
|
private _getFieldProps;
|
|
16
16
|
private _getElementAttributes;
|
|
17
|
+
private _convertDOMStringMapToObject;
|
|
17
18
|
private getSafeText;
|
|
18
19
|
private _scrubPotentiallySensitiveValues;
|
|
19
20
|
private _shouldCaptureValue;
|
package/dist/usermaven.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var y=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n))(y||{});class ie{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 f(n=0){return new ie(n)}const X={logLevel:y.ERROR,useBeaconApi:!1,forceUseFetch:!1,trackingHost:"t.usermaven.com",autocapture:!1,rageClick:!1,formTracking:!1,autoPageview:!0,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 ne{constructor(e){this.domain=e,this.cookieDomain=this.getCookieDomain()}set(e,t,i=365,s=!0,r=!1){const o=new Date;o.setTime(o.getTime()+i*24*60*60*1e3);const a=`expires=${o.toUTCString()}`,l=s?"; Secure":"",c=r?"; HttpOnly":"";document.cookie=`${e}=${t};${a};path=/;domain=${this.cookieDomain}${l}${c}`}get(e){const t=e+"=",i=document.cookie.split(";");for(let s=0;s<i.length;s++){let r=i[s].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("."),s=i.length;return s>2&&(i[s-1].length==2?(t=i[s-2]+"."+i[s-1],i[s-2].length==2&&(t=i[s-3]+"."+t)):t=i[s-2]+"."+i[s-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 se=Object.prototype,re=se.hasOwnProperty,oe=Array.prototype,H=oe.forEach,U={};function ae(n,e,t){if(Array.isArray(n)){if(H&&n.forEach===H)n.forEach(e,t);else if("length"in n&&n.length===+n.length){for(let i=0,s=n.length;i<s;i++)if(i in n&&e.call(t,n[i],i)===U)return}}}const D=function(n){return n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},ce=function(n){for(const e in n)typeof n[e]=="function"&&(n[e]=n[e].bind(n))};function k(n,e,t){if(n!=null){if(H&&Array.isArray(n)&&n.forEach===H)n.forEach(e,t);else if("length"in n&&n.length===+n.length){for(let i=0,s=n.length;i<s;i++)if(i in n&&e.call(t,n[i],i)===U)return}else for(const i in n)if(re.call(n,i)&&e.call(t,n[i],i)===U)return}}const le=function(n,...e){return ae(e,function(t){for(const i in t)t[i]!==void 0&&(n[i]=t[i])}),n};function S(n,e){return n.indexOf(e)!==-1}const ue=function(n){try{return/^\s*\bfunction\b/.test(n)}catch{return!1}},he=function(n){return n===void 0},E=function(){const n=function(i,s,r,o,a){if(!i){f().error("No valid element provided to register_event");return}if(i.addEventListener&&!o)i.addEventListener(s,r,!!a);else{const l="on"+s,c=i[l];i[l]=e(i,r,c)}};function e(i,s,r){return function(o){if(o=o||t(window.event),!o)return;let a=!0,l;ue(r)&&(l=r(o));const c=s.call(i,o);return(l===!1||c===!1)&&(a=!1),a}}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},n}(),de=function(n){return function(...e){try{return n.apply(this,e)}catch(t){f().error("Implementation error. Please turn on debug and contact support@usermaven.com.",t)}}},Z=function(n){for(const e in n)typeof n[e]=="function"&&(n[e]=de(n[e]))};function q(n){for(let e in n)(n[e]===""||n[e]===null||n[e]===void 0||typeof n[e]=="object"&&Object.keys(n[e]).length===0)&&delete n[e];return n}function h(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return f().warn("window is not available"),!1}}function v(n=5){const e=new Uint8Array(n);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").slice(0,n)}function fe(n){return n.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function F(n){return typeof n!="object"||n===null?n:Array.isArray(n)?n.map(F):Object.keys(n).reduce((e,t)=>{const i=fe(t);return e[i]=F(n[t]),e},{})}function N(n){switch(typeof n.className){case"string":return n.className;case"object":return("baseVal"in n.className?n.className.baseVal:null)||n.getAttribute("class")||"";default:return""}}function V(n){let e="";return M(n)&&!j(n)&&n.childNodes&&n.childNodes.length&&k(n.childNodes,function(t){G(t)&&t.textContent&&(e+=D(t.textContent).split(/(\s+)/).filter(x).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),D(e)}function Y(n){return!!n&&n.nodeType===1}function w(n,e){return!!n&&!!n.tagName&&n.tagName.toLowerCase()===e.toLowerCase()}function G(n){return!!n&&n.nodeType===3}function z(n){return!!n&&n.nodeType===11}const T=["a","button","form","input","select","textarea","label"];function ge(n,e){if(!n||w(n,"html")||!Y(n))return!1;let t=n;for(;t&&!w(t,"body");){if(t.classList&&t.classList.contains("um-no-capture"))return!1;t.parentNode&&z(t.parentNode)?t=t.parentNode.host:t=t.parentNode}let i=!1;for(t=n;t&&!w(t,"body");){if(t.parentNode&&z(t.parentNode)){t=t.parentNode.host,t&&T.indexOf(t.tagName.toLowerCase())>-1&&(i=!0);continue}const o=t.parentNode;if(!o)break;if(T.indexOf(o.tagName.toLowerCase())>-1)i=!0;else{const a=window.getComputedStyle(o);a&&a.getPropertyValue("cursor")==="pointer"&&(i=!0)}t=o}const s=window.getComputedStyle(n);if(s&&s.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;const r=n.tagName.toLowerCase();switch(r){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 i?e.type==="click":e.type==="click"&&(T.indexOf(r)>-1||n.getAttribute("contenteditable")==="true")}}function M(n){for(let i=n;i.parentNode&&!w(i,"body");i=i.parentNode){const s=N(i).split(" ");if(S(s,"ph-sensitive")||S(s,"ph-no-capture"))return!1}if(S(N(n).split(" "),"ph-include"))return!0;const e=n.type||"";if(typeof e=="string")switch(e.toLowerCase()){case"hidden":return!1;case"password":return!1}const t=n.name||n.id||"";return!(typeof t=="string"&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(t.replace(/[^a-zA-Z0-9]/g,"")))}function j(n){const e=["button","checkbox","submit","reset"];return!!(w(n,"input")&&!e.includes(n.type)||w(n,"select")||w(n,"textarea")||n.getAttribute("contenteditable")==="true")}function x(n){return!(n===null||he(n)||typeof n=="string"&&(n=D(n),/^(?:(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((n||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(n)))}function pe(n){return typeof n=="string"?n.substring(0,10)==="_ngcontent"||n.substring(0,7)==="_nghost":!1}function R(){return v(10)}function me(n){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(n).toLowerCase())}function ye(n,e){let t;return function(...i){const s=()=>{clearTimeout(t),n(...i)};clearTimeout(t),t=setTimeout(s,e)}}function we(n){const e={},t=n.replace(/^\?/,"").split("&");for(let i=0;i<t.length;i++){const s=t[i].split("=");s[0]!==""&&(e[decodeURIComponent(s[0])]=decodeURIComponent(s[1]||""))}return e}function J(n){return typeof n=="string"||n instanceof String}function A(n){return n!==null&&typeof n=="object"&&n.constructor===Object}function ke(n){if(n===null)return y.ERROR;const e=n.toUpperCase(),t=y[e];return t||t===0?t:y.ERROR}const ve=()=>{let n="false";return typeof window<"u"&&window.localStorage&&(n=localStorage.getItem("um_exclusion")),!(n==null||n==="false")};class _e{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=ye(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"){if(!this.lastScrollDepth)return;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(),s=t-e;return Math.min(100,Math.floor(i/s*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(s=>s!==i)})}}const O=class O{constructor(e,t,i=f()){this.logger=i,this.scrollDepth=null,this.customProperties=[],this.domHandlersAttached=!1,this.client=e,this.options=t,this.scrollDepth=new _e(e),ce(this),Z(this)}isBrowserSupported(){return typeof document<"u"&&typeof document.addEventListener=="function"}init(){if(!this.isBrowserSupported()){this.logger.debug("Browser not supported for autocapture");return}if(this.domHandlersAttached){this.logger.debug("Autocapture already initialized.");return}if(!(document&&document.body)){this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."),setTimeout(()=>this.init(),500);return}this.addDomEventHandlers(),this.domHandlersAttached=!0}addDomEventHandlers(){const e=t=>{t=t||window.event,this.captureEvent(t)};E(document,"submit",e,!1,!0),E(document,"change",e,!1,!0),E(document,"click",e,!1,!0),E(document,"visibilitychange",e,!1,!0),E(document,"scroll",e,!1,!0),E(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,s;let t=this.getEventTarget(e);if(G(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()||(s=this.scrollDepth)==null||s.send(),!0;if(t&&ge(t,e)){const r=[t];let o=t;for(;o.parentNode&&!w(o,"body");){if(z(o.parentNode)){r.push(o.parentNode.host),o=o.parentNode.host;continue}r.push(o.parentNode),o=o.parentNode}const a=[];let l,c=!1;if(k(r,p=>{const _=M(p);p.tagName.toLowerCase()==="a"&&(l=p.getAttribute("href"),l=_&&x(l)&&l);const u=N(p).split(" ");S(u,"ph-no-capture")&&(c=!0),a.push(this.getPropertiesFromElement(p,this.options.maskAllElementAttributes??!1,this.options.maskAllText??!1))}),this.options.maskAllText||(a[0].$el_text=V(t)),l&&(a[0].attr__href=l),c)return!1;const d=le(this.getDefaultProperties(e.type),{$elements:a},this.getCustomProperties(r));return this.client.track("$autocapture",d),!0}}getCustomProperties(e){const t={};return k(this.customProperties,i=>{k(i.event_selectors,s=>{const r=document.querySelectorAll(s);k(r,o=>{S(e,o)&&M(o)&&(t[i.name]=this.extractCustomPropertyValue(i))})})}),t}extractCustomPropertyValue(e){const t=[];return k(document.querySelectorAll(e.css_selector),function(i){let s;["input","select"].indexOf(i.tagName.toLowerCase())>-1?s=i.value:i.textContent&&(s=i.textContent),x(s)&&t.push(s)}),t.join(", ")}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}getPropertiesFromElement(e,t,i){const s=e.tagName.toLowerCase(),r={tag_name:s};T.indexOf(s)>-1&&!i&&(r.$el_text=V(e));const o=N(e);o.length>0&&(r.classes=o.split(" ").filter(function(d){return d!==""})),k(e.attributes,function(d){j(e)&&["name","id","class"].indexOf(d.name)===-1||!t&&x(d.value)&&!pe(d.name)&&(r["attr__"+d.name]=d.value)});let a=1,l=1,c=e;for(;c=this.previousElementSibling(c);)a++,c.tagName===e.tagName&&l++;return r.nth_child=a,r.nth_of_type=l,r}previousElementSibling(e){if(e.previousElementSibling)return e.previousElementSibling;{let t=e;do t=t.previousSibling;while(t&&!Y(t));return t}}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}encodeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}static enabledForProject(e,t=10,i=10){if(!e)return!1;let s=0;for(let r=0;r<e.length;r++)s+=e.charCodeAt(r);return s%t<i}};O.FORCE_CAPTURE_ATTR="data-um-force-capture",O.PREVENT_CAPTURE_ATTR="data-um-no-capture";let I=O;class be{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 Ee{constructor(e,t,i=f()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),s=new Blob([JSON.stringify(e)],{type:"application/json"});if(navigator.sendBeacon(i,s))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}`:"",s=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${v()}?p_${v()}=${e}${t}${i}`:`${this.trackingHost}${s}?token=${e}${t}${i}`}}class Q{constructor(e,t,i=f()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),s=JSON.stringify(e),r={"Content-Type":"application/json",...this.getCustomHeaders()},o=await fetch(i,{method:"POST",headers:r,body:s});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}`:"",s=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${v()}?p_${v()}=${e}${t}${i}`:`${this.trackingHost}${s}?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 Pe{constructor(e,t,i=f()){this.trackingHost=e,this.logger=i,this.config=t}send(e){return new Promise((t,i)=>{const s=new XMLHttpRequest,r=this.config.key,o=this.constructUrl(r);s.open("POST",o,!0),s.setRequestHeader("Content-Type","application/json");const a=this.getCustomHeaders();Object.keys(a).forEach(l=>{s.setRequestHeader(l,a[l])}),s.onload=()=>{s.status>=200&&s.status<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),t()):i(new Error(`HTTP error! status: ${s.status}`))},s.onerror=()=>{i(new Error("Network error"))},s.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}`:"",s=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${v()}?p_${v()}=${e}${t}${i}`:`${this.trackingHost}${s}?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 ee{constructor(e,t){this.storage={},this.prefix=`usermaven_${e}_`,this.load(),this.logger=t||f()}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(!h()){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(!h()){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 Ae{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 W{constructor(e,t=3,i=1e3,s=10,r=1e3,o=f(),a="default"){this.transport=e,this.maxRetries=t,this.retryInterval=i,this.batchSize=s,this.batchInterval=r,this.logger=o,this.queue=[],this.processing=!1,this.batchTimeoutId=null,this.isOnline=!0,this.persistence=new ee(`offline_queue_${a}`),h()&&(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),h()?this.saveQueueToStorage():this.processBatch()}initNetworkListeners(){h()&&(window.addEventListener("online",()=>{this.isOnline=!0,this.processBatch()}),window.addEventListener("offline",()=>{this.isOnline=!1}))}scheduleBatch(){h()&&(this.batchTimeoutId!==null&&clearTimeout(this.batchTimeoutId),this.batchTimeoutId=window.setTimeout(()=>this.processBatch(),this.batchInterval))}async processBatch(){if((!h()||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`),h()&&this.saveQueueToStorage()}catch(i){this.logger.error("Failed to send batch",i),await this.handleBatchFailure(e)}this.processing=!1}h()&&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);h()&&(this.saveQueueToStorage(),await new Promise(t=>setTimeout(t,this.retryInterval)))}loadQueueFromStorage(){if(h()){const e=this.persistence.get("queue");e&&(this.queue=JSON.parse(e))}}saveQueueToStorage(){h()&&this.persistence.set("queue",JSON.stringify(this.queue))}}class Se{constructor(e){this.clicks=[],this.threshold=3,this.timeWindow=2e3,this.distanceThreshold=30,this.client=e,this.initializeEventListener(),Z(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 s={x:e,y:t,timestamp:i};this.clicks.push(s),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 a=this.clicks[o-1];return Math.sqrt(Math.pow(r.x-a.x,2)+Math.pow(r.y-a.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 $e{constructor(e,t,i=f()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=new(void 0)(this.constructUrl(t)),s={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 a=(void 0)(s,l=>{l.on("data",c=>{}),l.on("end",()=>{const c=l.statusCode||0;c>=200&&c<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${c}`))})});a.on("error",l=>{o(l)}),a.write(JSON.stringify(e)),a.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 P{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",q(i)),this.options.trackFieldChanges&&this.trackFieldChanges(t)}trackFieldChanges(e){e.querySelectorAll("input, select, textarea").forEach(i=>{i.addEventListener("change",s=>{const r=this._getFieldProps(s.target,0);this.instance.track("$form_field_change",q(r))})})}static getInstance(e,t="all",i={}){return P.instance||(P.instance=new P(e,t,i)),P.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 a=this._getFieldProps(r,o);Object.assign(t,a)}),t}_getFieldProps(e,t){const i=Object.keys(e.dataset).length?JSON.stringify(e.dataset):void 0,s=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`]:s,[`field_${t+1}_class`]:e.className,[`field_${t+1}_name`]:e.name,[`field_${t+1}_attributes`]:this._getElementAttributes(e)}}_getElementAttributes(e){return Object.keys(e.dataset).length?JSON.parse(JSON.stringify(e.dataset)):{}}getSafeText(e){let t="";return"value"in e&&e.type!=="password"?t=e.value:e.hasChildNodes()?t=Array.from(e.childNodes).filter(s=>s.nodeType===Node.TEXT_NODE).map(s=>s.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 s=[" ",`
|
|
2
|
-
`,"\r"," ","\f","\v"," "," "," "," "," "," "," "," "," "," "," "," "," ","\u2028","\u2029"," "," "," "].join("");for(;t<=i&&s.indexOf(e[t])>-1;)t++;for(;i>=t&&s.indexOf(e[i])>-1;)i--;return e.slice(t,i+1)}}class ${constructor(e){this.config=this.mergeConfig(e,X),this.logger=f(this.config.logLevel),this.namespace=e.namespace||"default",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new W(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,200,this.logger,this.namespace),h()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new ne(this.config.cookieDomain),this.config.autocapture&&I.enabledForProject(this.config.key)&&!this.config.disableAutocaptureListenerRegistration&&(this.autoCapture=new I(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=P.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new be(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new Se(this)),this.setupPageLeaveTracking()}mergeConfig(e,t){const i=JSON.parse(JSON.stringify(e));let s={...t,...i};return Object.keys(t).forEach(r=>{A(t[r])&&(s[r]=this.mergeConfig(e[r],t[r]))}),s}init(e){this.config={...this.config,...e},this.logger=f(this.config.logLevel),this.namespace=e.namespace||this.namespace,this.transport=this.initializeTransport(e),this.persistence=this.initializePersistence(),this.retryQueue=new W(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,250,this.logger,this.namespace),h()&&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||`__eventn_id_${this.config.key}`;document.addEventListener("click",i=>{var a;const s=this.findClosestLink(i.target);if(!s)return;const r=s.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=(a=this.cookieManager)==null?void 0:a.get(t);l&&(o.searchParams.append("_um",l),s.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){const t="https://events.usermaven.com";if(!h())return new $e(e.trackingHost||t,e);const i="XMLHttpRequest"in window,s=typeof fetch<"u",r=typeof navigator<"u"&&"sendBeacon"in navigator;if(e.useBeaconApi&&r)return new Ee(e.trackingHost||t,e,this.logger);if(e.forceUseFetch&&s)return new Q(e.trackingHost||t,e,this.logger);if(i)return new Pe(e.trackingHost||t,e,this.logger);if(s)return new Q(e.trackingHost||t,e,this.logger);throw new Error("No suitable transport method available")}initializePersistence(){return this.config.disableEventPersistence||!h()?new Ae:new ee(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var i,s;if(!h())return R();if(this.config.privacyPolicy==="strict"||this.config.cookiePolicy==="strict")return"";const e=this.config.cookieName||`__eventn_id_${this.config.key}`;let t=(i=this.cookieManager)==null?void 0:i.get(e);if(!t){if(this.config.crossDomainLinking){const a=new URLSearchParams(window.location.search).get("_um"),c=window.location.hash.substring(1).split("~"),d=c.length>1?c[1]:void 0;t=a||d||R()}t||(t=R());const r=365*10;(s=this.cookieManager)==null||s.set(e,t,r,document.location.protocol!=="http:",!1)}return t}async id(e,t=!1){if(!A(e))throw new Error("User data must be an object");if(e.email&&!me(e.email))throw new Error("Invalid email provided");if(!e.id||!J(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 s={...e,anonymous_id:this.anonymousId};await this.track("user_identify",s)}this.logger.info("User identified:",e)}track(e,t,i=!1){this.trackInternal(e,t,i)}trackInternal(e,t,i=!1){if(ve()){this.logger.debug("Tracking disabled due to um_exclusion setting");return}if(!J(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 r=this.createEventPayload(e,t);try{if(i){this.transport.send(r),this.logger.debug(`Event sent: ${e}`,[r]);return}this.retryQueue.add(r),this.logger.debug(`Event tracked: ${e}`,[r])}catch(o){throw this.logger.error(`Failed to track event: ${e}`,o),new Error(`Failed to track event: ${e}`)}}rawTrack(e){if(!A(e))throw new Error("Event payload must be an object");this.track("raw",e)}async group(e,t=!1){if(!A(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")||{},s=this.persistence.get("companyProps")||(i==null?void 0:i.company)||{},r=this.persistence.get("userId"),o=this.persistence.get("global_props")||{},a=this.persistence.get(`props_${e}`)||{};let l=t||{};const c={event_id:"",user:{anonymous_id:this.anonymousId,id:r,...i},...s&&{company:s},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,...a};if(e==="$autocapture"){const d=this.processAutocaptureAttributes(t||{});c.autocapture_attributes=d}else e!=="user_identify"&&e!=="group"&&(Array.isArray(this.config.propertyBlacklist)&&this.config.propertyBlacklist.forEach(d=>{delete l[d]}),c.event_attributes=l);return h()&&(c.referer=document.referrer,c.url=window.location.href,c.page_title=document.title,c.doc_path=window.location.pathname,c.doc_host=window.location.hostname,c.doc_search=window.location.search,c.screen_resolution=`${window.screen.width}x${window.screen.height}`,c.vp_size=`${window.innerWidth}x${window.innerHeight}`,c.user_agent=navigator.userAgent,c.user_language=navigator.language,c.doc_encoding=document.characterSet,c.utm=this.getUtmParams()),c}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(s=>{delete t[s]}),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(h()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=we(window.location.search);return["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(s=>{t[s]&&(e[s.replace("utm_","")]=t[s])}),e}pageview(){h()?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(!h())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 s=history.pushState;history.pushState=function(){return i(),s.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||`__eventn_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(!A(e))throw new Error("Properties must be an object");const i=t==null?void 0:t.eventType,s=(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)}s&&this.persistence.save(),this.logger.debug("Properties set",{properties:e,eventType:i||"global",persist:s})}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,s=(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)}s&&this.persistence.save(),this.logger.debug(`Property unset: ${e}`,`Event type: ${i||"global"}`)}}function te(){return typeof window<"u"&&typeof window.define=="function"&&window.define.amd}function Ce(){return te()?window.define:void 0}const Te="__USERMAVEN_AUTOCAPTURE_INITIALIZED__";function C(n){const e=JSON.parse(JSON.stringify(n)),t=F(e),i={...X,...t};if(!i.key)throw new Error("API key is required!");if(!i.trackingHost)throw new Error("Tracking host is required!");const s=i.key||"",r=`${Te}${s}`;return h()&&i.autocapture&&window[r]&&(console.warn("Usermaven: Autocapture already initialized in another instance, skipping duplicate initialization."),i.disableAutocaptureListenerRegistration=!0),h()&&i.autocapture&&!i.disableAutocaptureListenerRegistration&&(window[r]=!0),new $(i)}function xe(n){var s;const e={key:n.getAttribute("data-key")||void 0,trackingHost:n.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:ke(n.getAttribute("data-log-level")),autocapture:n.getAttribute("data-autocapture")==="true",formTracking:n.getAttribute("data-form-tracking")==="false"?!1:n.getAttribute("data-form-tracking")==="true"?"all":n.getAttribute("data-form-tracking"),autoPageview:n.getAttribute("data-auto-pageview")==="true",useBeaconApi:n.getAttribute("data-use-beacon-api")==="true",forceUseFetch:n.getAttribute("data-force-use-fetch")==="true",gaHook:n.getAttribute("data-ga-hook")==="true",segmentHook:n.getAttribute("data-segment-hook")==="true",randomizeUrl:n.getAttribute("data-randomize-url")==="true",capture3rdPartyCookies:n.getAttribute("data-capture-3rd-party-cookies")==="false"?!1:void 0,idMethod:n.getAttribute("data-id-method")||void 0,privacyPolicy:n.getAttribute("data-privacy-policy")==="strict"?"strict":void 0,ipPolicy:n.getAttribute("data-ip-policy")||void 0,cookiePolicy:n.getAttribute("data-cookie-policy")||void 0,minSendTimeout:parseInt(n.getAttribute("data-min-send-timeout")||"",10)||void 0,maxSendTimeout:parseInt(n.getAttribute("data-max-send-timeout")||"",10)||void 0,maxSendAttempts:parseInt(n.getAttribute("data-max-send-attempts")||"",10)||void 0,propertiesStringMaxLength:parseInt(n.getAttribute("data-properties-string-max-length")||"",10)||null,propertyBlacklist:((s=n.getAttribute("data-property-blacklist"))==null?void 0:s.split(","))||void 0,exclude:n.getAttribute("data-exclude")||void 0,namespace:n.getAttribute("data-namespace")||void 0,crossDomainLinking:n.getAttribute("data-cross-domain-linking")!=="false",domains:n.getAttribute("data-domains")||void 0,maskAllText:n.getAttribute("data-mask-all-text")==="true",maskAllElementAttributes:n.getAttribute("data-mask-all-element-attributes")==="true"};e.privacyPolicy==="strict"&&(e.cookiePolicy="strict",e.ipPolicy="strict"),e.cookiePolicy==="comply"&&e.useBeaconApi&&(e.cookiePolicy="strict");const t=C(e),i=e.namespace||"usermaven";return h()&&t.pageview(),He(i,t),t}function He(n,e){let t=!1;const i=[],s=[];function r(){for(;i.length>0;){const u=i.shift();if(u){const g=u[u.length-1];if(g&&typeof g.resolve=="function"){const m=u.pop();try{const b=a.apply(null,u);b&&typeof b.then=="function"?b.then(m.resolve).catch(m.reject):m.resolve(b)}catch(b){m.reject(b)}}else try{a.apply(null,u)}catch(m){console.error("Usermaven: Error processing queued command:",m)}}}}function o(){s.forEach(u=>u()),s.length=0}function a(...u){const g=u[0];if(g==="onLoad"){typeof u[1]=="function"&&(t?u[1]():s.push(u[1]));return}if(!t){i.push(u);return}if(typeof e[g]=="function")return e[g].apply(e,u.slice(1));console.error(`Method ${g} not found on UsermavenClient`)}const l=["id","group","reset"],c=["track","pageview","set","unset","rawTrack","setUserId"];[...l,...c].forEach(u=>{a[u]=function(...g){if(!t){if(l.includes(u))return new Promise((B,m)=>{i.push([u,...g,{resolve:B,reject:m}])});i.push([u,...g]);return}if(typeof e[u]=="function")return e[u].apply(e,g)}}),a.getConfig=function(){return t?e.getConfig():(console.warn("Usermaven client not ready yet"),null)},window[n]=a;const p=`${n}Q`,_=window[p]||[];for(window[p]=_,_.push=function(...u){return a.apply(null,u),Array.prototype.push.apply(this,u)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${n} is ready`)},0);_.length>0;){const u=_.shift();u&&i.push(u)}}let K=!1,L=null;if(h()){const n=Ce();n&&n("usermaven",[],function(){return{usermavenClient:C,UsermavenClient:$,LogLevel:y,getScriptTagClient:()=>L}}),typeof window<"u"&&(window.usermavenClient=C,window.UsermavenClient=$,window.usermavenScriptTagClient=()=>L),function(e,t){const i=e.currentScript;function s(){return K||!i||!i.hasAttribute("data-key")||i.getAttribute("data-no-auto-init")==="true"?!1:i.src.includes("lib.js")}function r(){s()&&(console.log("[Usermaven] Auto-initializing from script tag"),L=xe(i),K=!0)}typeof t<"u"&&i&&(e.readyState==="loading"?e.addEventListener("DOMContentLoaded",r):r())}(document,window)}typeof module<"u"&&module.exports&&!te()&&(module.exports={usermavenClient:C,UsermavenClient:$,Config:void 0,UserProps:void 0,EventPayload:void 0,LogLevel:y,ClientProperties:void 0});exports.LogLevel=y;exports.UsermavenClient=$;exports.usermavenClient=C;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var y=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n))(y||{});class ie{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 f(n=0){return new ie(n)}const X={logLevel:y.ERROR,useBeaconApi:!1,forceUseFetch:!1,trackingHost:"t.usermaven.com",autocapture:!1,rageClick:!1,formTracking:!1,autoPageview:!0,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 ne{constructor(e){this.domain=e,this.cookieDomain=this.getCookieDomain()}set(e,t,i=365,s=!0,r=!1){const o=new Date;o.setTime(o.getTime()+i*24*60*60*1e3);const a=`expires=${o.toUTCString()}`,l=s?"; Secure":"",c=r?"; HttpOnly":"";document.cookie=`${e}=${t};${a};path=/;domain=${this.cookieDomain}${l}${c}`}get(e){const t=e+"=",i=document.cookie.split(";");for(let s=0;s<i.length;s++){let r=i[s].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("."),s=i.length;return s>2&&(i[s-1].length==2?(t=i[s-2]+"."+i[s-1],i[s-2].length==2&&(t=i[s-3]+"."+t)):t=i[s-2]+"."+i[s-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 se=Object.prototype,re=se.hasOwnProperty,oe=Array.prototype,H=oe.forEach,U={};function ae(n,e,t){if(Array.isArray(n)){if(H&&n.forEach===H)n.forEach(e,t);else if("length"in n&&n.length===+n.length){for(let i=0,s=n.length;i<s;i++)if(i in n&&e.call(t,n[i],i)===U)return}}}const D=function(n){return n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},ce=function(n){for(const e in n)typeof n[e]=="function"&&(n[e]=n[e].bind(n))};function k(n,e,t){if(n!=null){if(H&&Array.isArray(n)&&n.forEach===H)n.forEach(e,t);else if("length"in n&&n.length===+n.length){for(let i=0,s=n.length;i<s;i++)if(i in n&&e.call(t,n[i],i)===U)return}else for(const i in n)if(re.call(n,i)&&e.call(t,n[i],i)===U)return}}const le=function(n,...e){return ae(e,function(t){for(const i in t)t[i]!==void 0&&(n[i]=t[i])}),n};function A(n,e){return n.indexOf(e)!==-1}const ue=function(n){try{return/^\s*\bfunction\b/.test(n)}catch{return!1}},he=function(n){return n===void 0},E=function(){const n=function(i,s,r,o,a){if(!i){f().error("No valid element provided to register_event");return}if(i.addEventListener&&!o)i.addEventListener(s,r,!!a);else{const l="on"+s,c=i[l];i[l]=e(i,r,c)}};function e(i,s,r){return function(o){if(o=o||t(window.event),!o)return;let a=!0,l;ue(r)&&(l=r(o));const c=s.call(i,o);return(l===!1||c===!1)&&(a=!1),a}}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},n}(),de=function(n){return function(...e){try{return n.apply(this,e)}catch(t){f().error("Implementation error. Please turn on debug and contact support@usermaven.com.",t)}}},Z=function(n){for(const e in n)typeof n[e]=="function"&&(n[e]=de(n[e]))};function q(n){for(let e in n)(n[e]===""||n[e]===null||n[e]===void 0||typeof n[e]=="object"&&Object.keys(n[e]).length===0)&&delete n[e];return n}function h(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return f().warn("window is not available"),!1}}function v(n=5){const e=new Uint8Array(n);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").slice(0,n)}function fe(n){return n.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function F(n){return typeof n!="object"||n===null?n:Array.isArray(n)?n.map(F):Object.keys(n).reduce((e,t)=>{const i=fe(t);return e[i]=F(n[t]),e},{})}function N(n){switch(typeof n.className){case"string":return n.className;case"object":return("baseVal"in n.className?n.className.baseVal:null)||n.getAttribute("class")||"";default:return""}}function V(n){let e="";return M(n)&&!j(n)&&n.childNodes&&n.childNodes.length&&k(n.childNodes,function(t){G(t)&&t.textContent&&(e+=D(t.textContent).split(/(\s+)/).filter(x).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),D(e)}function Y(n){return!!n&&n.nodeType===1}function w(n,e){return!!n&&!!n.tagName&&n.tagName.toLowerCase()===e.toLowerCase()}function G(n){return!!n&&n.nodeType===3}function z(n){return!!n&&n.nodeType===11}const $=["a","button","form","input","select","textarea","label"];function ge(n,e){if(!n||w(n,"html")||!Y(n))return!1;let t=n;for(;t&&!w(t,"body");){if(t.classList&&t.classList.contains("um-no-capture"))return!1;t.parentNode&&z(t.parentNode)?t=t.parentNode.host:t=t.parentNode}let i=!1;for(t=n;t&&!w(t,"body");){if(t.parentNode&&z(t.parentNode)){t=t.parentNode.host,t&&$.indexOf(t.tagName.toLowerCase())>-1&&(i=!0);continue}const o=t.parentNode;if(!o)break;if($.indexOf(o.tagName.toLowerCase())>-1)i=!0;else{const a=window.getComputedStyle(o);a&&a.getPropertyValue("cursor")==="pointer"&&(i=!0)}t=o}const s=window.getComputedStyle(n);if(s&&s.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;const r=n.tagName.toLowerCase();switch(r){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 i?e.type==="click":e.type==="click"&&($.indexOf(r)>-1||n.getAttribute("contenteditable")==="true")}}function M(n){for(let i=n;i.parentNode&&!w(i,"body");i=i.parentNode){const s=N(i).split(" ");if(A(s,"ph-sensitive")||A(s,"ph-no-capture"))return!1}if(A(N(n).split(" "),"ph-include"))return!0;const e=n.type||"";if(typeof e=="string")switch(e.toLowerCase()){case"hidden":return!1;case"password":return!1}const t=n.name||n.id||"";return!(typeof t=="string"&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(t.replace(/[^a-zA-Z0-9]/g,"")))}function j(n){const e=["button","checkbox","submit","reset"];return!!(w(n,"input")&&!e.includes(n.type)||w(n,"select")||w(n,"textarea")||n.getAttribute("contenteditable")==="true")}function x(n){return!(n===null||he(n)||typeof n=="string"&&(n=D(n),/^(?:(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((n||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(n)))}function pe(n){return typeof n=="string"?n.substring(0,10)==="_ngcontent"||n.substring(0,7)==="_nghost":!1}function R(){return v(10)}function me(n){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(n).toLowerCase())}function ye(n,e){let t;return function(...i){const s=()=>{clearTimeout(t),n(...i)};clearTimeout(t),t=setTimeout(s,e)}}function we(n){const e={},t=n.replace(/^\?/,"").split("&");for(let i=0;i<t.length;i++){const s=t[i].split("=");s[0]!==""&&(e[decodeURIComponent(s[0])]=decodeURIComponent(s[1]||""))}return e}function Q(n){return typeof n=="string"||n instanceof String}function S(n){return n!==null&&typeof n=="object"&&n.constructor===Object}function ke(n){if(n===null)return y.ERROR;const e=n.toUpperCase(),t=y[e];return t||t===0?t:y.ERROR}const ve=()=>{let n="false";return typeof window<"u"&&window.localStorage&&(n=localStorage.getItem("um_exclusion")),!(n==null||n==="false")};class _e{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=ye(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"){if(!this.lastScrollDepth)return;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(),s=t-e;return Math.min(100,Math.floor(i/s*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(s=>s!==i)})}destroy(){window.removeEventListener("scroll",this.debouncedHandleScroll)}}const I=class I{constructor(e,t,i=f()){this.logger=i,this.scrollDepth=null,this.customProperties=[],this.domHandlersAttached=!1,this.client=e,this.options=t,this.scrollDepth=new _e(e),ce(this),Z(this)}isBrowserSupported(){return typeof document<"u"&&typeof document.addEventListener=="function"}init(){if(!this.isBrowserSupported()){this.logger.debug("Browser not supported for autocapture");return}if(this.domHandlersAttached){this.logger.debug("Autocapture already initialized.");return}if(!(document&&document.body)){this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."),setTimeout(()=>this.init(),500);return}this.addDomEventHandlers(),this.domHandlersAttached=!0}addDomEventHandlers(){const e=t=>{t=t||window.event,this.captureEvent(t)};E(document,"submit",e,!1,!0),E(document,"change",e,!1,!0),E(document,"click",e,!1,!0),E(document,"visibilitychange",e,!1,!0),E(document,"scroll",e,!1,!0),E(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,s;let t=this.getEventTarget(e);if(G(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()||(s=this.scrollDepth)==null||s.send(),!0;if(t&&ge(t,e)){const r=[t];let o=t;for(;o.parentNode&&!w(o,"body");){if(z(o.parentNode)){r.push(o.parentNode.host),o=o.parentNode.host;continue}r.push(o.parentNode),o=o.parentNode}const a=[];let l,c=!1;if(k(r,p=>{const _=M(p);p.tagName.toLowerCase()==="a"&&(l=p.getAttribute("href"),l=_&&x(l)&&l);const u=N(p).split(" ");A(u,"ph-no-capture")&&(c=!0),a.push(this.getPropertiesFromElement(p,this.options.maskAllElementAttributes??!1,this.options.maskAllText??!1))}),this.options.maskAllText||(a[0].$el_text=V(t)),l&&(a[0].attr__href=l),c)return!1;const d=le(this.getDefaultProperties(e.type),{$elements:a},this.getCustomProperties(r));return this.client.track("$autocapture",d),!0}}getCustomProperties(e){const t={};return k(this.customProperties,i=>{k(i.event_selectors,s=>{const r=document.querySelectorAll(s);k(r,o=>{A(e,o)&&M(o)&&(t[i.name]=this.extractCustomPropertyValue(i))})})}),t}extractCustomPropertyValue(e){const t=[];return k(document.querySelectorAll(e.css_selector),function(i){let s;["input","select"].indexOf(i.tagName.toLowerCase())>-1?s=i.value:i.textContent&&(s=i.textContent),x(s)&&t.push(s)}),t.join(", ")}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}getPropertiesFromElement(e,t,i){const s=e.tagName.toLowerCase(),r={tag_name:s};$.indexOf(s)>-1&&!i&&(r.$el_text=V(e));const o=N(e);o.length>0&&(r.classes=o.split(" ").filter(function(d){return d!==""})),k(e.attributes,function(d){j(e)&&["name","id","class"].indexOf(d.name)===-1||!t&&x(d.value)&&!pe(d.name)&&(r["attr__"+d.name]=d.value)});let a=1,l=1,c=e;for(;c=this.previousElementSibling(c);)a++,c.tagName===e.tagName&&l++;return r.nth_child=a,r.nth_of_type=l,r}previousElementSibling(e){if(e.previousElementSibling)return e.previousElementSibling;{let t=e;do t=t.previousSibling;while(t&&!Y(t));return t}}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}encodeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}static enabledForProject(e,t=10,i=10){if(!e)return!1;let s=0;for(let r=0;r<e.length;r++)s+=e.charCodeAt(r);return s%t<i}};I.FORCE_CAPTURE_ATTR="data-um-force-capture",I.PREVENT_CAPTURE_ATTR="data-um-no-capture";let O=I;class be{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 Ee{constructor(e,t,i=f()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),s=new Blob([JSON.stringify(e)],{type:"application/json"});if(navigator.sendBeacon(i,s))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}`:"",s=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${v()}?p_${v()}=${e}${t}${i}`:`${this.trackingHost}${s}?token=${e}${t}${i}`}}class J{constructor(e,t,i=f()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),s=JSON.stringify(e),r={"Content-Type":"application/json",...this.getCustomHeaders()},o=await fetch(i,{method:"POST",headers:r,body:s});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}`:"",s=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${v()}?p_${v()}=${e}${t}${i}`:`${this.trackingHost}${s}?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 Pe{constructor(e,t,i=f()){this.trackingHost=e,this.logger=i,this.config=t}send(e){return new Promise((t,i)=>{const s=new XMLHttpRequest,r=this.config.key,o=this.constructUrl(r);s.open("POST",o,!0),s.setRequestHeader("Content-Type","application/json");const a=this.getCustomHeaders();Object.keys(a).forEach(l=>{s.setRequestHeader(l,a[l])}),s.onload=()=>{s.status>=200&&s.status<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),t()):i(new Error(`HTTP error! status: ${s.status}`))},s.onerror=()=>{i(new Error("Network error"))},s.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}`:"",s=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${v()}?p_${v()}=${e}${t}${i}`:`${this.trackingHost}${s}?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 ee{constructor(e,t){this.storage={},this.prefix=`usermaven_${e}_`,this.load(),this.logger=t||f()}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(!h()){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(!h()){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 Se{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 W{constructor(e,t=3,i=1e3,s=10,r=1e3,o=f(),a="default"){this.transport=e,this.maxRetries=t,this.retryInterval=i,this.batchSize=s,this.batchInterval=r,this.logger=o,this.queue=[],this.processing=!1,this.batchTimeoutId=null,this.isOnline=!0,this.persistence=new ee(`offline_queue_${a}`),h()&&(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),h()?this.saveQueueToStorage():this.processBatch()}initNetworkListeners(){h()&&(window.addEventListener("online",()=>{this.isOnline=!0,this.processBatch()}),window.addEventListener("offline",()=>{this.isOnline=!1}))}scheduleBatch(){h()&&(this.batchTimeoutId!==null&&clearTimeout(this.batchTimeoutId),this.batchTimeoutId=window.setTimeout(()=>this.processBatch(),this.batchInterval))}async processBatch(){if((!h()||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`),h()&&this.saveQueueToStorage()}catch(i){this.logger.error("Failed to send batch",i),await this.handleBatchFailure(e)}this.processing=!1}h()&&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);h()&&(this.saveQueueToStorage(),await new Promise(t=>setTimeout(t,this.retryInterval)))}loadQueueFromStorage(){if(h()){const e=this.persistence.get("queue");e&&(this.queue=JSON.parse(e))}}saveQueueToStorage(){h()&&this.persistence.set("queue",JSON.stringify(this.queue))}}class Ae{constructor(e){this.clicks=[],this.threshold=3,this.timeWindow=2e3,this.distanceThreshold=30,this.client=e,this.initializeEventListener(),Z(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 s={x:e,y:t,timestamp:i};this.clicks.push(s),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 a=this.clicks[o-1];return Math.sqrt(Math.pow(r.x-a.x,2)+Math.pow(r.y-a.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 Ce{constructor(e,t,i=f()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=new(void 0)(this.constructUrl(t)),s={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 a=(void 0)(s,l=>{l.on("data",c=>{}),l.on("end",()=>{const c=l.statusCode||0;c>=200&&c<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${c}`))})});a.on("error",l=>{o(l)}),a.write(JSON.stringify(e)),a.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 P{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",q(i)),this.options.trackFieldChanges&&this.trackFieldChanges(t)}trackFieldChanges(e){e.querySelectorAll("input, select, textarea").forEach(i=>{i.addEventListener("change",s=>{const r=this._getFieldProps(s.target);this.instance.track("$form_field_change",q({form_id:e.id,form_name:e.name||"",field:r}))})})}static getInstance(e,t="all",i={}){return P.instance||(P.instance=new P(e,t,i)),P.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),fields:[]},i=e.querySelectorAll("input, select, textarea");return Array.from(i).filter(r=>!r.classList.contains("um-no-capture")).forEach(r=>{const o=this._getFieldProps(r);t.fields.push(o)}),t}_getFieldProps(e){const t=Object.keys(e.dataset).length?this._convertDOMStringMapToObject(e.dataset):void 0,i=this.getSafeText(e);return{tag:e.tagName.toLowerCase(),type:e instanceof HTMLInputElement?e.type:void 0,data_attributes:t,id:e.id,value:i,class:e.className,name:e.name,attributes:this._getElementAttributes(e)}}_getElementAttributes(e){return Object.keys(e.dataset).length?this._convertDOMStringMapToObject(e.dataset):{}}_convertDOMStringMapToObject(e){const t={};for(const i in e)e.hasOwnProperty(i)&&e[i]!==void 0&&(t[i]=e[i]);return t}getSafeText(e){let t="";return"value"in e&&e.type!=="password"?t=e.value:e.hasChildNodes()?t=Array.from(e.childNodes).filter(s=>s.nodeType===Node.TEXT_NODE).map(s=>s.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 s=[" ",`
|
|
2
|
+
`,"\r"," ","\f","\v"," "," "," "," "," "," "," "," "," "," "," "," "," ","\u2028","\u2029"," "," "," "].join("");for(;t<=i&&s.indexOf(e[t])>-1;)t++;for(;i>=t&&s.indexOf(e[i])>-1;)i--;return e.slice(t,i+1)}}class C{constructor(e){this.config=this.mergeConfig(e,X),this.logger=f(this.config.logLevel),this.namespace=e.namespace||"default",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new W(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,200,this.logger,this.namespace),h()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new ne(this.config.cookieDomain),this.config.autocapture&&O.enabledForProject(this.config.key)&&!this.config.disableAutocaptureListenerRegistration&&(this.autoCapture=new O(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=P.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new be(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new Ae(this)),this.setupPageLeaveTracking()}mergeConfig(e,t){const i=JSON.parse(JSON.stringify(e));let s={...t,...i};return Object.keys(t).forEach(r=>{S(t[r])&&(s[r]=this.mergeConfig(e[r],t[r]))}),s}init(e){this.config={...this.config,...e},this.logger=f(this.config.logLevel),this.namespace=e.namespace||this.namespace,this.transport=this.initializeTransport(e),this.persistence=this.initializePersistence(),this.retryQueue=new W(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,250,this.logger,this.namespace),h()&&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||`__eventn_id_${this.config.key}`;document.addEventListener("click",i=>{var a;const s=this.findClosestLink(i.target);if(!s)return;const r=s.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=(a=this.cookieManager)==null?void 0:a.get(t);l&&(o.searchParams.append("_um",l),s.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){const t="https://events.usermaven.com";if(!h())return new Ce(e.trackingHost||t,e);const i="XMLHttpRequest"in window,s=typeof fetch<"u",r=typeof navigator<"u"&&"sendBeacon"in navigator;if(e.useBeaconApi&&r)return new Ee(e.trackingHost||t,e,this.logger);if(e.forceUseFetch&&s)return new J(e.trackingHost||t,e,this.logger);if(i)return new Pe(e.trackingHost||t,e,this.logger);if(s)return new J(e.trackingHost||t,e,this.logger);throw new Error("No suitable transport method available")}initializePersistence(){return this.config.disableEventPersistence||!h()?new Se:new ee(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var i,s;if(!h())return R();if(this.config.privacyPolicy==="strict"||this.config.cookiePolicy==="strict")return"";const e=this.config.cookieName||`__eventn_id_${this.config.key}`;let t=(i=this.cookieManager)==null?void 0:i.get(e);if(!t){if(this.config.crossDomainLinking){const a=new URLSearchParams(window.location.search).get("_um"),c=window.location.hash.substring(1).split("~"),d=c.length>1?c[1]:void 0;t=a||d||R()}t||(t=R());const r=365*10;(s=this.cookieManager)==null||s.set(e,t,r,document.location.protocol!=="http:",!1)}return t}async id(e,t=!1){if(!S(e))throw new Error("User data must be an object");if(e.email&&!me(e.email))throw new Error("Invalid email provided");if(!e.id||!Q(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 s={...e,anonymous_id:this.anonymousId};await this.track("user_identify",s)}this.logger.info("User identified:",e)}track(e,t,i=!1){this.trackInternal(e,t,i)}trackInternal(e,t,i=!1){if(ve()){this.logger.debug("Tracking disabled due to um_exclusion setting");return}if(!Q(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 r=this.createEventPayload(e,t);try{if(i){this.transport.send(r),this.logger.debug(`Event sent: ${e}`,[r]);return}this.retryQueue.add(r),this.logger.debug(`Event tracked: ${e}`,[r])}catch(o){throw this.logger.error(`Failed to track event: ${e}`,o),new Error(`Failed to track event: ${e}`)}}rawTrack(e){if(!S(e))throw new Error("Event payload must be an object");this.track("raw",e)}async group(e,t=!1){if(!S(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")||{},s=this.persistence.get("companyProps")||(i==null?void 0:i.company)||{},r=this.persistence.get("userId"),o=this.persistence.get("global_props")||{},a=this.persistence.get(`props_${e}`)||{};let l=t||{};const c={event_id:"",user:{anonymous_id:this.anonymousId,id:r,...i},...s&&{company:s},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,...a};if(e==="$autocapture"){const d=this.processAutocaptureAttributes(t||{});c.autocapture_attributes=d}else e!=="user_identify"&&e!=="group"&&(Array.isArray(this.config.propertyBlacklist)&&this.config.propertyBlacklist.forEach(d=>{delete l[d]}),c.event_attributes=l);return h()&&(c.referer=document.referrer,c.url=window.location.href,c.page_title=document.title,c.doc_path=window.location.pathname,c.doc_host=window.location.hostname,c.doc_search=window.location.search,c.screen_resolution=`${window.screen.width}x${window.screen.height}`,c.vp_size=`${window.innerWidth}x${window.innerHeight}`,c.user_agent=navigator.userAgent,c.user_language=navigator.language,c.doc_encoding=document.characterSet,c.utm=this.getUtmParams()),c}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(s=>{delete t[s]}),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(h()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=we(window.location.search);return["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(s=>{t[s]&&(e[s.replace("utm_","")]=t[s])}),e}pageview(){h()?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(!h())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 s=history.pushState;history.pushState=function(){return i(),s.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||`__eventn_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(!S(e))throw new Error("Properties must be an object");const i=t==null?void 0:t.eventType,s=(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)}s&&this.persistence.save(),this.logger.debug("Properties set",{properties:e,eventType:i||"global",persist:s})}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,s=(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)}s&&this.persistence.save(),this.logger.debug(`Property unset: ${e}`,`Event type: ${i||"global"}`)}}function te(){return typeof window<"u"&&typeof window.define=="function"&&window.define.amd}function Te(){return te()?window.define:void 0}const $e="__USERMAVEN_AUTOCAPTURE_INITIALIZED__";function T(n){const e=JSON.parse(JSON.stringify(n)),t=F(e),i={...X,...t};if(!i.key)throw new Error("API key is required!");if(!i.trackingHost)throw new Error("Tracking host is required!");const s=i.key||"",r=`${$e}${s}`;return h()&&i.autocapture&&window[r]&&(console.warn("Usermaven: Autocapture already initialized in another instance, skipping duplicate initialization."),i.disableAutocaptureListenerRegistration=!0),h()&&i.autocapture&&!i.disableAutocaptureListenerRegistration&&(window[r]=!0),new C(i)}function xe(n){var s;const e={key:n.getAttribute("data-key")||void 0,trackingHost:n.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:ke(n.getAttribute("data-log-level")),autocapture:n.getAttribute("data-autocapture")==="true",formTracking:n.getAttribute("data-form-tracking")==="false"?!1:n.getAttribute("data-form-tracking")==="true"?"all":n.getAttribute("data-form-tracking"),autoPageview:n.getAttribute("data-auto-pageview")==="true",useBeaconApi:n.getAttribute("data-use-beacon-api")==="true",forceUseFetch:n.getAttribute("data-force-use-fetch")==="true",gaHook:n.getAttribute("data-ga-hook")==="true",segmentHook:n.getAttribute("data-segment-hook")==="true",randomizeUrl:n.getAttribute("data-randomize-url")==="true",capture3rdPartyCookies:n.getAttribute("data-capture-3rd-party-cookies")==="false"?!1:void 0,idMethod:n.getAttribute("data-id-method")||void 0,privacyPolicy:n.getAttribute("data-privacy-policy")==="strict"?"strict":void 0,ipPolicy:n.getAttribute("data-ip-policy")||void 0,cookiePolicy:n.getAttribute("data-cookie-policy")||void 0,minSendTimeout:parseInt(n.getAttribute("data-min-send-timeout")||"",10)||void 0,maxSendTimeout:parseInt(n.getAttribute("data-max-send-timeout")||"",10)||void 0,maxSendAttempts:parseInt(n.getAttribute("data-max-send-attempts")||"",10)||void 0,propertiesStringMaxLength:parseInt(n.getAttribute("data-properties-string-max-length")||"",10)||null,propertyBlacklist:((s=n.getAttribute("data-property-blacklist"))==null?void 0:s.split(","))||void 0,exclude:n.getAttribute("data-exclude")||void 0,namespace:n.getAttribute("data-namespace")||void 0,crossDomainLinking:n.getAttribute("data-cross-domain-linking")!=="false",domains:n.getAttribute("data-domains")||void 0,maskAllText:n.getAttribute("data-mask-all-text")==="true",maskAllElementAttributes:n.getAttribute("data-mask-all-element-attributes")==="true"};e.privacyPolicy==="strict"&&(e.cookiePolicy="strict",e.ipPolicy="strict"),e.cookiePolicy==="comply"&&e.useBeaconApi&&(e.cookiePolicy="strict");const t=T(e),i=e.namespace||"usermaven";return h()&&t.pageview(),He(i,t),t}function He(n,e){let t=!1;const i=[],s=[];function r(){for(;i.length>0;){const u=i.shift();if(u){const g=u[u.length-1];if(g&&typeof g.resolve=="function"){const m=u.pop();try{const b=a.apply(null,u);b&&typeof b.then=="function"?b.then(m.resolve).catch(m.reject):m.resolve(b)}catch(b){m.reject(b)}}else try{a.apply(null,u)}catch(m){console.error("Usermaven: Error processing queued command:",m)}}}}function o(){s.forEach(u=>u()),s.length=0}function a(...u){const g=u[0];if(g==="onLoad"){typeof u[1]=="function"&&(t?u[1]():s.push(u[1]));return}if(!t){i.push(u);return}if(typeof e[g]=="function")return e[g].apply(e,u.slice(1));console.error(`Method ${g} not found on UsermavenClient`)}const l=["id","group","reset"],c=["track","pageview","set","unset","rawTrack","setUserId"];[...l,...c].forEach(u=>{a[u]=function(...g){if(!t){if(l.includes(u))return new Promise((B,m)=>{i.push([u,...g,{resolve:B,reject:m}])});i.push([u,...g]);return}if(typeof e[u]=="function")return e[u].apply(e,g)}}),a.getConfig=function(){return t?e.getConfig():(console.warn("Usermaven client not ready yet"),null)},window[n]=a;const p=`${n}Q`,_=window[p]||[];for(window[p]=_,_.push=function(...u){return a.apply(null,u),Array.prototype.push.apply(this,u)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${n} is ready`)},0);_.length>0;){const u=_.shift();u&&i.push(u)}}let K=!1,L=null;if(h()){const n=Te();n&&n("usermaven",[],function(){return{usermavenClient:T,UsermavenClient:C,LogLevel:y,getScriptTagClient:()=>L}}),typeof window<"u"&&(window.usermavenClient=T,window.UsermavenClient=C,window.usermavenScriptTagClient=()=>L),function(e,t){const i=e.currentScript;function s(){return K||!i||!i.hasAttribute("data-key")||i.getAttribute("data-no-auto-init")==="true"?!1:i.src.includes("lib.js")}function r(){s()&&(console.log("[Usermaven] Auto-initializing from script tag"),L=xe(i),K=!0)}typeof t<"u"&&i&&(e.readyState==="loading"?e.addEventListener("DOMContentLoaded",r):r())}(document,window)}typeof module<"u"&&module.exports&&!te()&&(module.exports={usermavenClient:T,UsermavenClient:C,Config:void 0,UserProps:void 0,EventPayload:void 0,LogLevel:y,ClientProperties:void 0});exports.LogLevel=y;exports.UsermavenClient=C;exports.usermavenClient=T;
|
package/dist/usermaven.es.js
CHANGED
|
@@ -94,14 +94,14 @@ class ne {
|
|
|
94
94
|
return i ? i[0] : "";
|
|
95
95
|
}
|
|
96
96
|
}
|
|
97
|
-
const se = Object.prototype, re = se.hasOwnProperty, oe = Array.prototype,
|
|
97
|
+
const se = Object.prototype, re = se.hasOwnProperty, oe = Array.prototype, $ = oe.forEach, U = {};
|
|
98
98
|
function ae(n, e, t) {
|
|
99
99
|
if (Array.isArray(n)) {
|
|
100
|
-
if (
|
|
100
|
+
if ($ && n.forEach === $)
|
|
101
101
|
n.forEach(e, t);
|
|
102
102
|
else if ("length" in n && n.length === +n.length) {
|
|
103
103
|
for (let i = 0, s = n.length; i < s; i++)
|
|
104
|
-
if (i in n && e.call(t, n[i], i) ===
|
|
104
|
+
if (i in n && e.call(t, n[i], i) === U)
|
|
105
105
|
return;
|
|
106
106
|
}
|
|
107
107
|
}
|
|
@@ -114,15 +114,15 @@ const D = function(n) {
|
|
|
114
114
|
};
|
|
115
115
|
function w(n, e, t) {
|
|
116
116
|
if (n != null) {
|
|
117
|
-
if (
|
|
117
|
+
if ($ && Array.isArray(n) && n.forEach === $)
|
|
118
118
|
n.forEach(e, t);
|
|
119
119
|
else if ("length" in n && n.length === +n.length) {
|
|
120
120
|
for (let i = 0, s = n.length; i < s; i++)
|
|
121
|
-
if (i in n && e.call(t, n[i], i) ===
|
|
121
|
+
if (i in n && e.call(t, n[i], i) === U)
|
|
122
122
|
return;
|
|
123
123
|
} else
|
|
124
124
|
for (const i in n)
|
|
125
|
-
if (re.call(n, i) && e.call(t, n[i], i) ===
|
|
125
|
+
if (re.call(n, i) && e.call(t, n[i], i) === U)
|
|
126
126
|
return;
|
|
127
127
|
}
|
|
128
128
|
}
|
|
@@ -132,7 +132,7 @@ const le = function(n, ...e) {
|
|
|
132
132
|
t[i] !== void 0 && (n[i] = t[i]);
|
|
133
133
|
}), n;
|
|
134
134
|
};
|
|
135
|
-
function
|
|
135
|
+
function S(n, e) {
|
|
136
136
|
return n.indexOf(e) !== -1;
|
|
137
137
|
}
|
|
138
138
|
const ue = function(n) {
|
|
@@ -227,7 +227,7 @@ function x(n) {
|
|
|
227
227
|
function V(n) {
|
|
228
228
|
let e = "";
|
|
229
229
|
return M(n) && !j(n) && n.childNodes && n.childNodes.length && w(n.childNodes, function(t) {
|
|
230
|
-
G(t) && t.textContent && (e += D(t.textContent).split(/(\s+)/).filter(
|
|
230
|
+
G(t) && t.textContent && (e += D(t.textContent).split(/(\s+)/).filter(T).join("").replace(/[\r\n]/g, " ").replace(/[ ]+/g, " ").substring(0, 255));
|
|
231
231
|
}), D(e);
|
|
232
232
|
}
|
|
233
233
|
function Y(n) {
|
|
@@ -242,7 +242,7 @@ function G(n) {
|
|
|
242
242
|
function z(n) {
|
|
243
243
|
return !!n && n.nodeType === 11;
|
|
244
244
|
}
|
|
245
|
-
const
|
|
245
|
+
const C = ["a", "button", "form", "input", "select", "textarea", "label"];
|
|
246
246
|
function ge(n, e) {
|
|
247
247
|
if (!n || y(n, "html") || !Y(n))
|
|
248
248
|
return !1;
|
|
@@ -255,12 +255,12 @@ function ge(n, e) {
|
|
|
255
255
|
let i = !1;
|
|
256
256
|
for (t = n; t && !y(t, "body"); ) {
|
|
257
257
|
if (t.parentNode && z(t.parentNode)) {
|
|
258
|
-
t = t.parentNode.host, t &&
|
|
258
|
+
t = t.parentNode.host, t && C.indexOf(t.tagName.toLowerCase()) > -1 && (i = !0);
|
|
259
259
|
continue;
|
|
260
260
|
}
|
|
261
261
|
const o = t.parentNode;
|
|
262
262
|
if (!o) break;
|
|
263
|
-
if (
|
|
263
|
+
if (C.indexOf(o.tagName.toLowerCase()) > -1)
|
|
264
264
|
i = !0;
|
|
265
265
|
else {
|
|
266
266
|
const a = window.getComputedStyle(o);
|
|
@@ -283,16 +283,16 @@ function ge(n, e) {
|
|
|
283
283
|
case "textarea":
|
|
284
284
|
return e.type === "change" || e.type === "click";
|
|
285
285
|
default:
|
|
286
|
-
return i ? e.type === "click" : e.type === "click" && (
|
|
286
|
+
return i ? e.type === "click" : e.type === "click" && (C.indexOf(r) > -1 || n.getAttribute("contenteditable") === "true");
|
|
287
287
|
}
|
|
288
288
|
}
|
|
289
289
|
function M(n) {
|
|
290
290
|
for (let i = n; i.parentNode && !y(i, "body"); i = i.parentNode) {
|
|
291
291
|
const s = x(i).split(" ");
|
|
292
|
-
if (
|
|
292
|
+
if (S(s, "ph-sensitive") || S(s, "ph-no-capture"))
|
|
293
293
|
return !1;
|
|
294
294
|
}
|
|
295
|
-
if (
|
|
295
|
+
if (S(x(n).split(" "), "ph-include"))
|
|
296
296
|
return !0;
|
|
297
297
|
const e = n.type || "";
|
|
298
298
|
if (typeof e == "string")
|
|
@@ -309,13 +309,13 @@ function j(n) {
|
|
|
309
309
|
const e = ["button", "checkbox", "submit", "reset"];
|
|
310
310
|
return !!(y(n, "input") && !e.includes(n.type) || y(n, "select") || y(n, "textarea") || n.getAttribute("contenteditable") === "true");
|
|
311
311
|
}
|
|
312
|
-
function
|
|
312
|
+
function T(n) {
|
|
313
313
|
return !(n === null || he(n) || typeof n == "string" && (n = D(n), /^(?:(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((n || "").replace(/[- ]/g, "")) || /(^\d{3}-?\d{2}-?\d{4}$)/.test(n)));
|
|
314
314
|
}
|
|
315
315
|
function pe(n) {
|
|
316
316
|
return typeof n == "string" ? n.substring(0, 10) === "_ngcontent" || n.substring(0, 7) === "_nghost" : !1;
|
|
317
317
|
}
|
|
318
|
-
function
|
|
318
|
+
function R() {
|
|
319
319
|
return v(10);
|
|
320
320
|
}
|
|
321
321
|
function me(n) {
|
|
@@ -338,7 +338,7 @@ function we(n) {
|
|
|
338
338
|
}
|
|
339
339
|
return e;
|
|
340
340
|
}
|
|
341
|
-
function
|
|
341
|
+
function Q(n) {
|
|
342
342
|
return typeof n == "string" || n instanceof String;
|
|
343
343
|
}
|
|
344
344
|
function A(n) {
|
|
@@ -404,8 +404,11 @@ class _e {
|
|
|
404
404
|
this.send(), this.milestones = this.milestones.filter((s) => s !== i);
|
|
405
405
|
});
|
|
406
406
|
}
|
|
407
|
+
destroy() {
|
|
408
|
+
window.removeEventListener("scroll", this.debouncedHandleScroll);
|
|
409
|
+
}
|
|
407
410
|
}
|
|
408
|
-
const
|
|
411
|
+
const I = class I {
|
|
409
412
|
constructor(e, t, i = f()) {
|
|
410
413
|
this.logger = i, this.scrollDepth = null, this.customProperties = [], this.domHandlersAttached = !1, this.client = e, this.options = t, this.scrollDepth = new _e(e), ce(this), Z(this);
|
|
411
414
|
}
|
|
@@ -462,9 +465,9 @@ const R = class R {
|
|
|
462
465
|
let l, c = !1;
|
|
463
466
|
if (w(r, (p) => {
|
|
464
467
|
const _ = M(p);
|
|
465
|
-
p.tagName.toLowerCase() === "a" && (l = p.getAttribute("href"), l = _ &&
|
|
468
|
+
p.tagName.toLowerCase() === "a" && (l = p.getAttribute("href"), l = _ && T(l) && l);
|
|
466
469
|
const u = x(p).split(" ");
|
|
467
|
-
|
|
470
|
+
S(u, "ph-no-capture") && (c = !0), a.push(
|
|
468
471
|
this.getPropertiesFromElement(
|
|
469
472
|
p,
|
|
470
473
|
this.options.maskAllElementAttributes ?? !1,
|
|
@@ -489,7 +492,7 @@ const R = class R {
|
|
|
489
492
|
w(i.event_selectors, (s) => {
|
|
490
493
|
const r = document.querySelectorAll(s);
|
|
491
494
|
w(r, (o) => {
|
|
492
|
-
|
|
495
|
+
S(e, o) && M(o) && (t[i.name] = this.extractCustomPropertyValue(i));
|
|
493
496
|
});
|
|
494
497
|
});
|
|
495
498
|
}), t;
|
|
@@ -498,7 +501,7 @@ const R = class R {
|
|
|
498
501
|
const t = [];
|
|
499
502
|
return w(document.querySelectorAll(e.css_selector), function(i) {
|
|
500
503
|
let s;
|
|
501
|
-
["input", "select"].indexOf(i.tagName.toLowerCase()) > -1 ? s = i.value : i.textContent && (s = i.textContent),
|
|
504
|
+
["input", "select"].indexOf(i.tagName.toLowerCase()) > -1 ? s = i.value : i.textContent && (s = i.textContent), T(s) && t.push(s);
|
|
502
505
|
}), t.join(", ");
|
|
503
506
|
}
|
|
504
507
|
getEventTarget(e) {
|
|
@@ -509,12 +512,12 @@ const R = class R {
|
|
|
509
512
|
const s = e.tagName.toLowerCase(), r = {
|
|
510
513
|
tag_name: s
|
|
511
514
|
};
|
|
512
|
-
|
|
515
|
+
C.indexOf(s) > -1 && !i && (r.$el_text = V(e));
|
|
513
516
|
const o = x(e);
|
|
514
517
|
o.length > 0 && (r.classes = o.split(" ").filter(function(d) {
|
|
515
518
|
return d !== "";
|
|
516
519
|
})), w(e.attributes, function(d) {
|
|
517
|
-
j(e) && ["name", "id", "class"].indexOf(d.name) === -1 || !t &&
|
|
520
|
+
j(e) && ["name", "id", "class"].indexOf(d.name) === -1 || !t && T(d.value) && !pe(d.name) && (r["attr__" + d.name] = d.value);
|
|
518
521
|
});
|
|
519
522
|
let a = 1, l = 1, c = e;
|
|
520
523
|
for (; c = this.previousElementSibling(c); )
|
|
@@ -550,8 +553,8 @@ const R = class R {
|
|
|
550
553
|
return s % t < i;
|
|
551
554
|
}
|
|
552
555
|
};
|
|
553
|
-
|
|
554
|
-
let H =
|
|
556
|
+
I.FORCE_CAPTURE_ATTR = "data-um-force-capture", I.PREVENT_CAPTURE_ATTR = "data-um-no-capture";
|
|
557
|
+
let H = I;
|
|
555
558
|
class be {
|
|
556
559
|
constructor(e) {
|
|
557
560
|
this.client = e, this.lastPageUrl = window.location.href, this.trackInitialPageview(), this.initializePageviewTracking();
|
|
@@ -599,7 +602,7 @@ class Ee {
|
|
|
599
602
|
// Note: Beacon API doesn't support custom headers, so we can't use them here.
|
|
600
603
|
// If custom headers are crucial, you might want to fall back to XHR or Fetch in those cases.
|
|
601
604
|
}
|
|
602
|
-
class
|
|
605
|
+
class J {
|
|
603
606
|
constructor(e, t, i = f()) {
|
|
604
607
|
this.trackingHost = e, this.logger = i, this.config = t;
|
|
605
608
|
}
|
|
@@ -762,7 +765,7 @@ class W {
|
|
|
762
765
|
h() && this.persistence.set("queue", JSON.stringify(this.queue));
|
|
763
766
|
}
|
|
764
767
|
}
|
|
765
|
-
class
|
|
768
|
+
class Se {
|
|
766
769
|
constructor(e) {
|
|
767
770
|
this.clicks = [], this.threshold = 3, this.timeWindow = 2e3, this.distanceThreshold = 30, this.client = e, this.initializeEventListener(), Z(this);
|
|
768
771
|
}
|
|
@@ -796,7 +799,7 @@ class $e {
|
|
|
796
799
|
}), this.clicks = [];
|
|
797
800
|
}
|
|
798
801
|
}
|
|
799
|
-
class
|
|
802
|
+
class Ce {
|
|
800
803
|
constructor(e, t, i = f()) {
|
|
801
804
|
this.trackingHost = e, this.logger = i, this.config = t;
|
|
802
805
|
}
|
|
@@ -852,8 +855,12 @@ class P {
|
|
|
852
855
|
trackFieldChanges(e) {
|
|
853
856
|
e.querySelectorAll("input, select, textarea").forEach((i) => {
|
|
854
857
|
i.addEventListener("change", (s) => {
|
|
855
|
-
const r = this._getFieldProps(s.target
|
|
856
|
-
this.instance.track("$form_field_change", q(
|
|
858
|
+
const r = this._getFieldProps(s.target);
|
|
859
|
+
this.instance.track("$form_field_change", q({
|
|
860
|
+
form_id: e.id,
|
|
861
|
+
form_name: e.name || "",
|
|
862
|
+
field: r
|
|
863
|
+
}));
|
|
857
864
|
});
|
|
858
865
|
});
|
|
859
866
|
}
|
|
@@ -867,28 +874,35 @@ class P {
|
|
|
867
874
|
form_action: e.action,
|
|
868
875
|
form_method: e.method,
|
|
869
876
|
form_class: e.className,
|
|
870
|
-
form_attributes: this._getElementAttributes(e)
|
|
877
|
+
form_attributes: this._getElementAttributes(e),
|
|
878
|
+
fields: []
|
|
871
879
|
}, i = e.querySelectorAll("input, select, textarea");
|
|
872
|
-
return Array.from(i).filter((r) => !r.classList.contains("um-no-capture")).forEach((r
|
|
873
|
-
const
|
|
874
|
-
|
|
880
|
+
return Array.from(i).filter((r) => !r.classList.contains("um-no-capture")).forEach((r) => {
|
|
881
|
+
const o = this._getFieldProps(r);
|
|
882
|
+
t.fields.push(o);
|
|
875
883
|
}), t;
|
|
876
884
|
}
|
|
877
|
-
_getFieldProps(e
|
|
878
|
-
const
|
|
885
|
+
_getFieldProps(e) {
|
|
886
|
+
const t = Object.keys(e.dataset).length ? this._convertDOMStringMapToObject(e.dataset) : void 0, i = this.getSafeText(e);
|
|
879
887
|
return {
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
+
tag: e.tagName.toLowerCase(),
|
|
889
|
+
type: e instanceof HTMLInputElement ? e.type : void 0,
|
|
890
|
+
data_attributes: t,
|
|
891
|
+
id: e.id,
|
|
892
|
+
value: i,
|
|
893
|
+
class: e.className,
|
|
894
|
+
name: e.name,
|
|
895
|
+
attributes: this._getElementAttributes(e)
|
|
888
896
|
};
|
|
889
897
|
}
|
|
890
898
|
_getElementAttributes(e) {
|
|
891
|
-
return Object.keys(e.dataset).length ?
|
|
899
|
+
return Object.keys(e.dataset).length ? this._convertDOMStringMapToObject(e.dataset) : {};
|
|
900
|
+
}
|
|
901
|
+
_convertDOMStringMapToObject(e) {
|
|
902
|
+
const t = {};
|
|
903
|
+
for (const i in e)
|
|
904
|
+
e.hasOwnProperty(i) && e[i] !== void 0 && (t[i] = e[i]);
|
|
905
|
+
return t;
|
|
892
906
|
}
|
|
893
907
|
getSafeText(e) {
|
|
894
908
|
let t = "";
|
|
@@ -966,7 +980,7 @@ class N {
|
|
|
966
980
|
trackFieldChanges: !1
|
|
967
981
|
});
|
|
968
982
|
}
|
|
969
|
-
this.config.autoPageview && (this.pageviewTracking = new be(this)), this.config.crossDomainLinking && this.manageCrossDomainLinking(), this.config.rageClick && (this.rageClick = new
|
|
983
|
+
this.config.autoPageview && (this.pageviewTracking = new be(this)), this.config.crossDomainLinking && this.manageCrossDomainLinking(), this.config.rageClick && (this.rageClick = new Se(this)), this.setupPageLeaveTracking();
|
|
970
984
|
}
|
|
971
985
|
/**
|
|
972
986
|
* Recursively merge the provided configuration with the existing defaultConfig
|
|
@@ -1017,16 +1031,16 @@ class N {
|
|
|
1017
1031
|
initializeTransport(e) {
|
|
1018
1032
|
const t = "https://events.usermaven.com";
|
|
1019
1033
|
if (!h())
|
|
1020
|
-
return new
|
|
1034
|
+
return new Ce(e.trackingHost || t, e);
|
|
1021
1035
|
const i = "XMLHttpRequest" in window, s = typeof fetch < "u", r = typeof navigator < "u" && "sendBeacon" in navigator;
|
|
1022
1036
|
if (e.useBeaconApi && r)
|
|
1023
1037
|
return new Ee(e.trackingHost || t, e, this.logger);
|
|
1024
1038
|
if (e.forceUseFetch && s)
|
|
1025
|
-
return new
|
|
1039
|
+
return new J(e.trackingHost || t, e, this.logger);
|
|
1026
1040
|
if (i)
|
|
1027
1041
|
return new Pe(e.trackingHost || t, e, this.logger);
|
|
1028
1042
|
if (s)
|
|
1029
|
-
return new
|
|
1043
|
+
return new J(e.trackingHost || t, e, this.logger);
|
|
1030
1044
|
throw new Error("No suitable transport method available");
|
|
1031
1045
|
}
|
|
1032
1046
|
initializePersistence() {
|
|
@@ -1035,7 +1049,7 @@ class N {
|
|
|
1035
1049
|
getOrCreateAnonymousId() {
|
|
1036
1050
|
var i, s;
|
|
1037
1051
|
if (!h())
|
|
1038
|
-
return
|
|
1052
|
+
return R();
|
|
1039
1053
|
if (this.config.privacyPolicy === "strict" || this.config.cookiePolicy === "strict")
|
|
1040
1054
|
return "";
|
|
1041
1055
|
const e = this.config.cookieName || `__eventn_id_${this.config.key}`;
|
|
@@ -1043,9 +1057,9 @@ class N {
|
|
|
1043
1057
|
if (!t) {
|
|
1044
1058
|
if (this.config.crossDomainLinking) {
|
|
1045
1059
|
const a = new URLSearchParams(window.location.search).get("_um"), c = window.location.hash.substring(1).split("~"), d = c.length > 1 ? c[1] : void 0;
|
|
1046
|
-
t = a || d ||
|
|
1060
|
+
t = a || d || R();
|
|
1047
1061
|
}
|
|
1048
|
-
t || (t =
|
|
1062
|
+
t || (t = R());
|
|
1049
1063
|
const r = 365 * 10;
|
|
1050
1064
|
(s = this.cookieManager) == null || s.set(e, t, r, document.location.protocol !== "http:", !1);
|
|
1051
1065
|
}
|
|
@@ -1056,7 +1070,7 @@ class N {
|
|
|
1056
1070
|
throw new Error("User data must be an object");
|
|
1057
1071
|
if (e.email && !me(e.email))
|
|
1058
1072
|
throw new Error("Invalid email provided");
|
|
1059
|
-
if (!e.id || !
|
|
1073
|
+
if (!e.id || !Q(e.id))
|
|
1060
1074
|
throw new Error("User ID must be a string");
|
|
1061
1075
|
const i = e.id;
|
|
1062
1076
|
if (this.persistence.set("userId", i), this.persistence.set("userProps", e), !t) {
|
|
@@ -1076,7 +1090,7 @@ class N {
|
|
|
1076
1090
|
this.logger.debug("Tracking disabled due to um_exclusion setting");
|
|
1077
1091
|
return;
|
|
1078
1092
|
}
|
|
1079
|
-
if (!
|
|
1093
|
+
if (!Q(e))
|
|
1080
1094
|
throw new Error("Event name must be a string");
|
|
1081
1095
|
if (t !== void 0 && (typeof t != "object" || t === null || Array.isArray(t)))
|
|
1082
1096
|
throw new Error("Event payload must be a non-null object and not an array");
|
|
@@ -1236,17 +1250,17 @@ class N {
|
|
|
1236
1250
|
function te() {
|
|
1237
1251
|
return typeof window < "u" && typeof window.define == "function" && window.define.amd;
|
|
1238
1252
|
}
|
|
1239
|
-
function
|
|
1253
|
+
function Te() {
|
|
1240
1254
|
return te() ? window.define : void 0;
|
|
1241
1255
|
}
|
|
1242
|
-
const
|
|
1243
|
-
function
|
|
1256
|
+
const $e = "__USERMAVEN_AUTOCAPTURE_INITIALIZED__";
|
|
1257
|
+
function O(n) {
|
|
1244
1258
|
const e = JSON.parse(JSON.stringify(n)), t = F(e), i = { ...X, ...t };
|
|
1245
1259
|
if (!i.key)
|
|
1246
1260
|
throw new Error("API key is required!");
|
|
1247
1261
|
if (!i.trackingHost)
|
|
1248
1262
|
throw new Error("Tracking host is required!");
|
|
1249
|
-
const s = i.key || "", r = `${
|
|
1263
|
+
const s = i.key || "", r = `${$e}${s}`;
|
|
1250
1264
|
return h() && i.autocapture && window[r] && (console.warn("Usermaven: Autocapture already initialized in another instance, skipping duplicate initialization."), i.disableAutocaptureListenerRegistration = !0), h() && i.autocapture && !i.disableAutocaptureListenerRegistration && (window[r] = !0), new N(i);
|
|
1251
1265
|
}
|
|
1252
1266
|
function xe(n) {
|
|
@@ -1281,7 +1295,7 @@ function xe(n) {
|
|
|
1281
1295
|
maskAllElementAttributes: n.getAttribute("data-mask-all-element-attributes") === "true"
|
|
1282
1296
|
};
|
|
1283
1297
|
e.privacyPolicy === "strict" && (e.cookiePolicy = "strict", e.ipPolicy = "strict"), e.cookiePolicy === "comply" && e.useBeaconApi && (e.cookiePolicy = "strict");
|
|
1284
|
-
const t =
|
|
1298
|
+
const t = O(e), i = e.namespace || "usermaven";
|
|
1285
1299
|
return h() && t.pageview(), He(i, t), t;
|
|
1286
1300
|
}
|
|
1287
1301
|
function He(n, e) {
|
|
@@ -1353,30 +1367,30 @@ function He(n, e) {
|
|
|
1353
1367
|
u && i.push(u);
|
|
1354
1368
|
}
|
|
1355
1369
|
}
|
|
1356
|
-
let K = !1,
|
|
1370
|
+
let K = !1, L = null;
|
|
1357
1371
|
if (h()) {
|
|
1358
|
-
const n =
|
|
1372
|
+
const n = Te();
|
|
1359
1373
|
n && n("usermaven", [], function() {
|
|
1360
1374
|
return {
|
|
1361
|
-
usermavenClient:
|
|
1375
|
+
usermavenClient: O,
|
|
1362
1376
|
UsermavenClient: N,
|
|
1363
1377
|
LogLevel: k,
|
|
1364
1378
|
// Expose the script tag client if it exists
|
|
1365
|
-
getScriptTagClient: () =>
|
|
1379
|
+
getScriptTagClient: () => L
|
|
1366
1380
|
};
|
|
1367
|
-
}), typeof window < "u" && (window.usermavenClient =
|
|
1381
|
+
}), typeof window < "u" && (window.usermavenClient = O, window.UsermavenClient = N, window.usermavenScriptTagClient = () => L), function(e, t) {
|
|
1368
1382
|
const i = e.currentScript;
|
|
1369
1383
|
function s() {
|
|
1370
1384
|
return K || !i || !i.hasAttribute("data-key") || i.getAttribute("data-no-auto-init") === "true" ? !1 : i.src.includes("lib.js");
|
|
1371
1385
|
}
|
|
1372
1386
|
function r() {
|
|
1373
|
-
s() && (console.log("[Usermaven] Auto-initializing from script tag"),
|
|
1387
|
+
s() && (console.log("[Usermaven] Auto-initializing from script tag"), L = xe(i), K = !0);
|
|
1374
1388
|
}
|
|
1375
1389
|
typeof t < "u" && i && (e.readyState === "loading" ? e.addEventListener("DOMContentLoaded", r) : r());
|
|
1376
1390
|
}(document, window);
|
|
1377
1391
|
}
|
|
1378
1392
|
typeof module < "u" && module.exports && !te() && (module.exports = {
|
|
1379
|
-
usermavenClient:
|
|
1393
|
+
usermavenClient: O,
|
|
1380
1394
|
UsermavenClient: N,
|
|
1381
1395
|
Config: void 0,
|
|
1382
1396
|
UserProps: void 0,
|
|
@@ -1387,5 +1401,5 @@ typeof module < "u" && module.exports && !te() && (module.exports = {
|
|
|
1387
1401
|
export {
|
|
1388
1402
|
k as LogLevel,
|
|
1389
1403
|
N as UsermavenClient,
|
|
1390
|
-
|
|
1404
|
+
O as usermavenClient
|
|
1391
1405
|
};
|