You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

@usermaven/sdk-js

Package Overview
Dependencies
Maintainers
1
Versions
73
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@usermaven/sdk-js - npm Package Compare versions

Comparing version

to
1.5.7-rc.102

4

dist/lib.js

@@ -1,2 +0,2 @@

(function(g,d){typeof exports=="object"&&typeof module<"u"?d(exports):typeof define=="function"&&define.amd?define(["exports"],d):(g=typeof globalThis<"u"?globalThis:g||self,d(g.Usermaven={}))})(this,function(g){"use strict";var d=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n))(d||{});class Y{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 Y(n)}const D={logLevel:d.ERROR,useBeaconApi:!1,forceUseFetch:!1,trackingHost:"t.usermaven.com",autocapture:!1,rageClick:!1,formTracking:!1,autoPageview:!1,disableEventPersistence:!1,gaHook:!1,segmentHook:!1,randomizeUrl:!1,capture3rdPartyCookies:["_ga","_fbp","_ym_uid","ajs_user_id","ajs_anonymous_id"],idMethod:"cookie",ipPolicy:"keep",cookiePolicy:"keep",minSendTimeout:0,maxSendTimeout:2e3,maxSendAttempts:4,propertiesStringMaxLength:null,propertyBlacklist:[],crossDomainLinking:!0,maskAllText:!1,maskAllElementAttributes:!1};class G{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 c=`expires=${o.toUTCString()}`,l=s?"; Secure":"",a=r?"; HttpOnly":"";document.cookie=`${e}=${t};${c};path=/;domain=${this.cookieDomain}${l}${a}`}get(e){const t=e+"=",i=document.cookie.split(";");for(let 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 j=Object.prototype.hasOwnProperty,A=Array.prototype.forEach,H={};function ee(n,e,t){if(Array.isArray(n)){if(A&&n.forEach===A)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)===H)return}}}const N=function(n){return n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},te=function(n){for(const e in n)typeof n[e]=="function"&&(n[e]=n[e].bind(n))};function m(n,e,t){if(n!=null){if(A&&Array.isArray(n)&&n.forEach===A)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)===H)return}else for(const i in n)if(j.call(n,i)&&e.call(t,n[i],i)===H)return}}const ie=function(n,...e){return ee(e,function(t){for(const i in t)t[i]!==void 0&&(n[i]=t[i])}),n};function v(n,e){return n.indexOf(e)!==-1}const ne=function(n){try{return/^\s*\bfunction\b/.test(n)}catch{return!1}},se=function(n){return n===void 0},w=function(){const n=function(i,s,r,o,c){if(!i){f().error("No valid element provided to register_event");return}if(i.addEventListener&&!o)i.addEventListener(s,r,!!c);else{const l="on"+s,a=i[l];i[l]=e(i,r,a)}};function e(i,s,r){return function(o){if(o=o||t(window.event),!o)return;let c=!0,l;ne(r)&&(l=r(o));const a=s.call(i,o);return(l===!1||a===!1)&&(c=!1),c}}function t(i){return i&&(i.preventDefault=t.preventDefault,i.stopPropagation=t.stopPropagation),i}return t.preventDefault=function(){this.returnValue=!1},t.stopPropagation=function(){this.cancelBubble=!0},n}(),re=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)}}},F=function(n){for(const e in n)typeof n[e]=="function"&&(n[e]=re(n[e]))};function z(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 u(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return f().warn("window is not available"),!1}}function y(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 oe(n){return n.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function O(n){return typeof n!="object"||n===null?n:Array.isArray(n)?n.map(O):Object.keys(n).reduce((e,t)=>{const i=oe(t);return e[i]=O(n[t]),e},{})}function S(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 M(n){let e="";return I(n)&&!V(n)&&n.childNodes&&n.childNodes.length&&m(n.childNodes,function(t){q(t)&&t.textContent&&(e+=N(t.textContent).split(/(\s+)/).filter(C).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),N(e)}function B(n){return!!n&&n.nodeType===1}function p(n,e){return!!n&&!!n.tagName&&n.tagName.toLowerCase()===e.toLowerCase()}function q(n){return!!n&&n.nodeType===3}function R(n){return!!n&&n.nodeType===11}const $=["a","button","form","input","select","textarea","label"];function ae(n,e){if(!n||p(n,"html")||!B(n))return!1;let t=n;for(;t&&!p(t,"body");){if(t.classList&&t.classList.contains("um-no-capture"))return!1;t.parentNode&&R(t.parentNode)?t=t.parentNode.host:t=t.parentNode}let i=!1;for(t=n;t&&!p(t,"body");){if(t.parentNode&&R(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 c=window.getComputedStyle(o);c&&c.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 I(n){for(let i=n;i.parentNode&&!p(i,"body");i=i.parentNode){const s=S(i).split(" ");if(v(s,"ph-sensitive")||v(s,"ph-no-capture"))return!1}if(v(S(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 V(n){const e=["button","checkbox","submit","reset"];return!!(p(n,"input")&&!e.includes(n.type)||p(n,"select")||p(n,"textarea")||n.getAttribute("contenteditable")==="true")}function C(n){return!(n===null||se(n)||typeof n=="string"&&(n=N(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 ce(n){return typeof n=="string"?n.substring(0,10)==="_ngcontent"||n.substring(0,7)==="_nghost":!1}function L(){return y(10)}function le(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 ue(n,e){let t;return function(...i){const s=()=>{clearTimeout(t),n(...i)};clearTimeout(t),t=setTimeout(s,e)}}function he(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 _(n){return n!==null&&typeof n=="object"&&n.constructor===Object}function de(n){if(n===null)return d.ERROR;const e=n.toUpperCase(),t=d[e];return t||t===0?t:d.ERROR}const fe=()=>{let n="false";return typeof window<"u"&&window.localStorage&&(n=localStorage.getItem("um_exclusion")),!(n==null||n==="false")};class ge{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=ue(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 x=class x{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 ge(e),te(this),F(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)};w(document,"submit",e,!1,!0),w(document,"change",e,!1,!0),w(document,"click",e,!1,!0),w(document,"visibilitychange",e,!1,!0),w(document,"scroll",e,!1,!0),w(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(q(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&&ae(t,e)){const r=[t];let o=t;for(;o.parentNode&&!p(o,"body");){if(R(o.parentNode)){r.push(o.parentNode.host),o=o.parentNode.host;continue}r.push(o.parentNode),o=o.parentNode}const c=[];let l,a=!1;if(m(r,E=>{const Ae=I(E);E.tagName.toLowerCase()==="a"&&(l=E.getAttribute("href"),l=Ae&&C(l)&&l);const Se=S(E).split(" ");v(Se,"ph-no-capture")&&(a=!0),c.push(this.getPropertiesFromElement(E,this.options.maskAllElementAttributes??!1,this.options.maskAllText??!1))}),this.options.maskAllText||(c[0].$el_text=M(t)),l&&(c[0].attr__href=l),a)return!1;const h=ie(this.getDefaultProperties(e.type),{$elements:c},this.getCustomProperties(r));return this.client.track("$autocapture",h),!0}}getCustomProperties(e){const t={};return m(this.customProperties,i=>{m(i.event_selectors,s=>{const r=document.querySelectorAll(s);m(r,o=>{v(e,o)&&I(o)&&(t[i.name]=this.extractCustomPropertyValue(i))})})}),t}extractCustomPropertyValue(e){const t=[];return m(document.querySelectorAll(e.css_selector),function(i){let s;["input","select"].indexOf(i.tagName.toLowerCase())>-1?s=i.value:i.textContent&&(s=i.textContent),C(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=M(e));const o=S(e);o.length>0&&(r.classes=o.split(" ").filter(function(h){return h!==""})),m(e.attributes,function(h){V(e)&&["name","id","class"].indexOf(h.name)===-1||!t&&C(h.value)&&!ce(h.name)&&(r["attr__"+h.name]=h.value)});let c=1,l=1,a=e;for(;a=this.previousElementSibling(a);)c++,a.tagName===e.tagName&&l++;return r.nth_child=c,r.nth_of_type=l,r}previousElementSibling(e){if(e.previousElementSibling)return e.previousElementSibling;{let t=e;do t=t.previousSibling;while(t&&!B(t));return t}}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}encodeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}static enabledForProject(e,t=10,i=10){if(!e)return!1;let s=0;for(let r=0;r<e.length;r++)s+=e.charCodeAt(r);return s%t<i}};x.FORCE_CAPTURE_ATTR="data-um-force-capture",x.PREVENT_CAPTURE_ATTR="data-um-no-capture";let T=x;class pe{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 me{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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${y()}?p_${y()}=${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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${y()}?p_${y()}=${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 ye{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 c=this.getCustomHeaders();Object.keys(c).forEach(l=>{s.setRequestHeader(l,c[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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${y()}?p_${y()}=${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 W{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(!u()){this.logger.warn("localStorage is not available in this environment");return}try{localStorage.setItem(this.prefix+"data",JSON.stringify(this.storage))}catch(e){this.logger.error("Error saving to localStorage:",e)}}load(){if(!u()){this.logger.warn("localStorage is not available in this environment");return}try{const e=localStorage.getItem(this.prefix+"data");e&&(this.storage=JSON.parse(e))}catch(e){this.logger.error("Error loading from localStorage:",e)}}}class we{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 K{constructor(e,t=3,i=1e3,s=10,r=1e3,o=f(),c="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 W(`offline_queue_${c}`),u()&&(this.isOnline=navigator.onLine,this.loadQueueFromStorage(),this.initNetworkListeners(),this.scheduleBatch())}add(e){const t={payload:e,retries:0,timestamp:Date.now()};this.queue.push(t),u()?this.saveQueueToStorage():this.processBatch()}initNetworkListeners(){u()&&(window.addEventListener("online",()=>{this.isOnline=!0,this.processBatch()}),window.addEventListener("offline",()=>{this.isOnline=!1}))}scheduleBatch(){u()&&(this.batchTimeoutId!==null&&clearTimeout(this.batchTimeoutId),this.batchTimeoutId=window.setTimeout(()=>this.processBatch(),this.batchInterval))}async processBatch(){if((!u()||this.isOnline)&&!this.processing&&this.queue.length>0){this.processing=!0;const e=this.queue.splice(0,this.batchSize),t=e.map(i=>i.payload);try{await this.transport.send(t),this.logger.debug(`Successfully sent batch of ${e.length} payloads`),u()&&this.saveQueueToStorage()}catch(i){this.logger.error("Failed to send batch",i),await this.handleBatchFailure(e)}this.processing=!1}u()&&this.scheduleBatch()}async handleBatchFailure(e){for(const t of e)t.retries<this.maxRetries?(t.retries++,this.queue.unshift(t),this.logger.warn(`Retry attempt ${t.retries} for payload`)):this.logger.error("Max retries reached, discarding payload",t.payload);u()&&(this.saveQueueToStorage(),await new Promise(t=>setTimeout(t,this.retryInterval)))}loadQueueFromStorage(){if(u()){const e=this.persistence.get("queue");e&&(this.queue=JSON.parse(e))}}saveQueueToStorage(){u()&&this.persistence.set("queue",JSON.stringify(this.queue))}}class ke{constructor(e){this.clicks=[],this.threshold=3,this.timeWindow=2e3,this.distanceThreshold=30,this.client=e,this.initializeEventListener(),F(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 c=this.clicks[o-1];return Math.sqrt(Math.pow(r.x-c.x,2)+Math.pow(r.y-c.y,2))<this.distanceThreshold})&&this.sendRageClickEvent(i)}sendRageClickEvent(e){const t=this.clicks[this.clicks.length-1];document.elementFromPoint(t.x,t.y)&&this.client.track("$rage_click",{no_of_clicks:this.clicks.length,time:e.toFixed(2)}),this.clicks=[]}}class ve{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 c=(void 0)(s,l=>{l.on("data",a=>{}),l.on("end",()=>{const a=l.statusCode||0;a>=200&&a<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${a}`))})});c.on("error",l=>{o(l)}),c.write(JSON.stringify(e)),c.end()})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"";return`${this.trackingHost}/api/v1/s2s/event?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}}class k{constructor(e,t="all",i={}){this.instance=e,this.trackingType=t,this.options=i,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",this.initialize.bind(this)):this.initialize()}initialize(){this.trackingType!=="none"&&this.setupFormTracking()}setupFormTracking(){var e;this.formElements=this.trackingType==="tagged"?document.querySelectorAll("form[data-um-form]"):document.querySelectorAll("form"),(e=this.formElements)==null||e.forEach(t=>{t.addEventListener("submit",this.handleFormSubmit.bind(this))})}handleFormSubmit(e){const t=e.target,i=this._getFormDetails(t);this.instance.track("$form",z(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",z(r))})})}static getInstance(e,t="all",i={}){return k.instance||(k.instance=new k(e,t,i)),k.instance}_getFormDetails(e){const t={form_id:e.id,form_name:e.name||"",form_action:e.action,form_method:e.method,form_class:e.className,form_attributes:this._getElementAttributes(e)},i=e.querySelectorAll("input, select, textarea");return Array.from(i).filter(r=>!r.classList.contains("um-no-capture")).forEach((r,o)=>{const c=this._getFieldProps(r,o);Object.assign(t,c)}),t}_getFieldProps(e,t){const i=Object.keys(e.dataset).length?JSON.stringify(e.dataset):void 0,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=[" ",`
`,"\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 b{constructor(e){this.config=this.mergeConfig(e,D),this.logger=f(this.config.logLevel),this.namespace=e.namespace||"default",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new K(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,200,this.logger,this.namespace),u()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new G(this.config.cookieDomain),this.config.autocapture&&T.enabledForProject(this.config.key)&&!this.config.disableAutocaptureListenerRegistration&&(this.autoCapture=new T(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=k.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new pe(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new ke(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=f(this.config.logLevel),this.namespace=e.namespace||this.namespace,this.transport=this.initializeTransport(e),this.persistence=this.initializePersistence(),this.retryQueue=new K(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,250,this.logger,this.namespace),u()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client reinitialized for namespace: ${this.namespace}`)}manageCrossDomainLinking(){if(!this.config.crossDomainLinking||!this.config.domains)return;const e=this.config.domains.split(",").map(i=>i.trim()),t=this.config.cookieName||`__eventn_id_${this.config.key}`;document.addEventListener("click",i=>{var c;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=(c=this.cookieManager)==null?void 0:c.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(!u())return new ve(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 me(e.trackingHost||t,e,this.logger);if(e.forceUseFetch&&s)return new Q(e.trackingHost||t,e,this.logger);if(i)return new ye(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||!u()?new we:new W(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var i,s;if(!u())return L();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 c=new URLSearchParams(window.location.search).get("_um"),a=window.location.hash.substring(1).split("~"),h=a.length>1?a[1]:void 0;t=c||h||L()}t||(t=L());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&&!le(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(fe()){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(!_(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")||{},c=this.persistence.get(`props_${e}`)||{};let l=t||{};const a={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,...c};if(e==="$autocapture"){const h=this.processAutocaptureAttributes(t||{});a.autocapture_attributes=h}else e!=="user_identify"&&e!=="group"&&(Array.isArray(this.config.propertyBlacklist)&&this.config.propertyBlacklist.forEach(h=>{delete l[h]}),a.event_attributes=l);return u()&&(a.referer=document.referrer,a.url=window.location.href,a.page_title=document.title,a.doc_path=window.location.pathname,a.doc_host=window.location.hostname,a.doc_search=window.location.search,a.screen_resolution=`${window.screen.width}x${window.screen.height}`,a.vp_size=`${window.innerWidth}x${window.innerHeight}`,a.user_agent=navigator.userAgent,a.user_language=navigator.language,a.doc_encoding=document.characterSet,a.utm=this.getUtmParams()),a}processAutocaptureAttributes(e){let t={};const i=e.$elements||[];return i.length&&(t={...i[0]}),t.el_text=t.$el_text||"",t.event_type=e.$event_type||"",["$ce_version","$event_type","$initial_referrer","$initial_referring_domain","$referrer","$referring_domain","$elements"].forEach(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(u()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=he(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(){u()?this.track("pageview",{url:window.location.href,referrer:document.referrer,title:document.title},!0):this.logger.warn("Pageview tracking is not available in server-side environments")}setupPageLeaveTracking(){if(!u())return;let e=!1,t=!1;const i=()=>{!e&&!t&&(e=!0,this.track("$pageleave",{url:window.location.href,referrer:document.referrer,title:document.title}))};window.addEventListener("beforeunload",r=>{t=!0,setTimeout(()=>{t=!1},100)}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&!t&&i()});const 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 X(){return typeof window<"u"&&typeof window.define=="function"&&window.define.amd}function _e(){return X()?window.define:void 0}const be="__USERMAVEN_AUTOCAPTURE_INITIALIZED__";function P(n){const e=JSON.parse(JSON.stringify(n)),t=O(e),i={...D,...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=`${be}${s}`;return u()&&i.autocapture&&window[r]&&(console.warn("Usermaven: Autocapture already initialized in another instance, skipping duplicate initialization."),i.disableAutocaptureListenerRegistration=!0),u()&&i.autocapture&&!i.disableAutocaptureListenerRegistration&&(window[r]=!0),new b(i)}function Pe(n){var s;const e={key:n.getAttribute("data-key")||void 0,trackingHost:n.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:de(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=P(e),i=e.namespace||"usermaven";return u()&&e.autoPageview!==!1&&t.pageview(),Ee(i,t),t}function Ee(n,e){let t=!1;const i=[],s=[];function r(){for(;i.length>0;){const a=i.shift();a&&window[n].apply(null,a)}}function o(){s.forEach(a=>a()),s.length=0}window[n]=function(...a){const h=a[0];if(h==="onLoad"){typeof a[1]=="function"&&(t?a[1]():s.push(a[1]));return}if(!t){i.push(a);return}if(typeof e[h]=="function")return e[h].apply(e,a.slice(1));console.error(`Method ${h} not found on UsermavenClient`)};const c=`${n}Q`,l=window[c]||[];for(window[c]=l,l.push=function(...a){return window[n].apply(null,a),Array.prototype.push.apply(this,a)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${n} is ready`)},0);l.length>0;){const a=l.shift();a&&i.push(a)}}let Z=!1,U=null;if(u()){const n=_e();n&&n("usermaven",[],function(){return{usermavenClient:P,UsermavenClient:b,LogLevel:d,getScriptTagClient:()=>U}}),typeof window<"u"&&(window.usermavenClient=P,window.UsermavenClient=b,window.usermavenScriptTagClient=()=>U),function(e,t){const i=e.currentScript;function s(){return Z||!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"),U=Pe(i),Z=!0)}typeof t<"u"&&i&&(e.readyState==="loading"?e.addEventListener("DOMContentLoaded",r):r())}(document,window)}typeof module<"u"&&module.exports&&!X()&&(module.exports={usermavenClient:P,UsermavenClient:b,Config:void 0,UserProps:void 0,EventPayload:void 0,LogLevel:d,ClientProperties:void 0}),g.LogLevel=d,g.UsermavenClient=b,g.usermavenClient=P,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})});
(function(g,d){typeof exports=="object"&&typeof module<"u"?d(exports):typeof define=="function"&&define.amd?define(["exports"],d):(g=typeof globalThis<"u"?globalThis:g||self,d(g.Usermaven={}))})(this,function(g){"use strict";var d=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n))(d||{});class Y{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 Y(n)}const D={logLevel:d.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 G{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 c=`expires=${o.toUTCString()}`,l=s?"; Secure":"",a=r?"; HttpOnly":"";document.cookie=`${e}=${t};${c};path=/;domain=${this.cookieDomain}${l}${a}`}get(e){const t=e+"=",i=document.cookie.split(";");for(let 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 j=Object.prototype.hasOwnProperty,A=Array.prototype.forEach,H={};function ee(n,e,t){if(Array.isArray(n)){if(A&&n.forEach===A)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)===H)return}}}const N=function(n){return n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},te=function(n){for(const e in n)typeof n[e]=="function"&&(n[e]=n[e].bind(n))};function m(n,e,t){if(n!=null){if(A&&Array.isArray(n)&&n.forEach===A)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)===H)return}else for(const i in n)if(j.call(n,i)&&e.call(t,n[i],i)===H)return}}const ie=function(n,...e){return ee(e,function(t){for(const i in t)t[i]!==void 0&&(n[i]=t[i])}),n};function v(n,e){return n.indexOf(e)!==-1}const ne=function(n){try{return/^\s*\bfunction\b/.test(n)}catch{return!1}},se=function(n){return n===void 0},w=function(){const n=function(i,s,r,o,c){if(!i){f().error("No valid element provided to register_event");return}if(i.addEventListener&&!o)i.addEventListener(s,r,!!c);else{const l="on"+s,a=i[l];i[l]=e(i,r,a)}};function e(i,s,r){return function(o){if(o=o||t(window.event),!o)return;let c=!0,l;ne(r)&&(l=r(o));const a=s.call(i,o);return(l===!1||a===!1)&&(c=!1),c}}function t(i){return i&&(i.preventDefault=t.preventDefault,i.stopPropagation=t.stopPropagation),i}return t.preventDefault=function(){this.returnValue=!1},t.stopPropagation=function(){this.cancelBubble=!0},n}(),re=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)}}},F=function(n){for(const e in n)typeof n[e]=="function"&&(n[e]=re(n[e]))};function z(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 u(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return f().warn("window is not available"),!1}}function y(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 oe(n){return n.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function O(n){return typeof n!="object"||n===null?n:Array.isArray(n)?n.map(O):Object.keys(n).reduce((e,t)=>{const i=oe(t);return e[i]=O(n[t]),e},{})}function S(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 M(n){let e="";return I(n)&&!V(n)&&n.childNodes&&n.childNodes.length&&m(n.childNodes,function(t){q(t)&&t.textContent&&(e+=N(t.textContent).split(/(\s+)/).filter(C).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),N(e)}function B(n){return!!n&&n.nodeType===1}function p(n,e){return!!n&&!!n.tagName&&n.tagName.toLowerCase()===e.toLowerCase()}function q(n){return!!n&&n.nodeType===3}function R(n){return!!n&&n.nodeType===11}const $=["a","button","form","input","select","textarea","label"];function ae(n,e){if(!n||p(n,"html")||!B(n))return!1;let t=n;for(;t&&!p(t,"body");){if(t.classList&&t.classList.contains("um-no-capture"))return!1;t.parentNode&&R(t.parentNode)?t=t.parentNode.host:t=t.parentNode}let i=!1;for(t=n;t&&!p(t,"body");){if(t.parentNode&&R(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 c=window.getComputedStyle(o);c&&c.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 I(n){for(let i=n;i.parentNode&&!p(i,"body");i=i.parentNode){const s=S(i).split(" ");if(v(s,"ph-sensitive")||v(s,"ph-no-capture"))return!1}if(v(S(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 V(n){const e=["button","checkbox","submit","reset"];return!!(p(n,"input")&&!e.includes(n.type)||p(n,"select")||p(n,"textarea")||n.getAttribute("contenteditable")==="true")}function C(n){return!(n===null||se(n)||typeof n=="string"&&(n=N(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 ce(n){return typeof n=="string"?n.substring(0,10)==="_ngcontent"||n.substring(0,7)==="_nghost":!1}function L(){return y(10)}function le(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 ue(n,e){let t;return function(...i){const s=()=>{clearTimeout(t),n(...i)};clearTimeout(t),t=setTimeout(s,e)}}function he(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 _(n){return n!==null&&typeof n=="object"&&n.constructor===Object}function de(n){if(n===null)return d.ERROR;const e=n.toUpperCase(),t=d[e];return t||t===0?t:d.ERROR}const fe=()=>{let n="false";return typeof window<"u"&&window.localStorage&&(n=localStorage.getItem("um_exclusion")),!(n==null||n==="false")};class ge{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=ue(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 x=class x{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 ge(e),te(this),F(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)};w(document,"submit",e,!1,!0),w(document,"change",e,!1,!0),w(document,"click",e,!1,!0),w(document,"visibilitychange",e,!1,!0),w(document,"scroll",e,!1,!0),w(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(q(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&&ae(t,e)){const r=[t];let o=t;for(;o.parentNode&&!p(o,"body");){if(R(o.parentNode)){r.push(o.parentNode.host),o=o.parentNode.host;continue}r.push(o.parentNode),o=o.parentNode}const c=[];let l,a=!1;if(m(r,E=>{const Ae=I(E);E.tagName.toLowerCase()==="a"&&(l=E.getAttribute("href"),l=Ae&&C(l)&&l);const Se=S(E).split(" ");v(Se,"ph-no-capture")&&(a=!0),c.push(this.getPropertiesFromElement(E,this.options.maskAllElementAttributes??!1,this.options.maskAllText??!1))}),this.options.maskAllText||(c[0].$el_text=M(t)),l&&(c[0].attr__href=l),a)return!1;const h=ie(this.getDefaultProperties(e.type),{$elements:c},this.getCustomProperties(r));return this.client.track("$autocapture",h),!0}}getCustomProperties(e){const t={};return m(this.customProperties,i=>{m(i.event_selectors,s=>{const r=document.querySelectorAll(s);m(r,o=>{v(e,o)&&I(o)&&(t[i.name]=this.extractCustomPropertyValue(i))})})}),t}extractCustomPropertyValue(e){const t=[];return m(document.querySelectorAll(e.css_selector),function(i){let s;["input","select"].indexOf(i.tagName.toLowerCase())>-1?s=i.value:i.textContent&&(s=i.textContent),C(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=M(e));const o=S(e);o.length>0&&(r.classes=o.split(" ").filter(function(h){return h!==""})),m(e.attributes,function(h){V(e)&&["name","id","class"].indexOf(h.name)===-1||!t&&C(h.value)&&!ce(h.name)&&(r["attr__"+h.name]=h.value)});let c=1,l=1,a=e;for(;a=this.previousElementSibling(a);)c++,a.tagName===e.tagName&&l++;return r.nth_child=c,r.nth_of_type=l,r}previousElementSibling(e){if(e.previousElementSibling)return e.previousElementSibling;{let t=e;do t=t.previousSibling;while(t&&!B(t));return t}}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}encodeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}static enabledForProject(e,t=10,i=10){if(!e)return!1;let s=0;for(let r=0;r<e.length;r++)s+=e.charCodeAt(r);return s%t<i}};x.FORCE_CAPTURE_ATTR="data-um-force-capture",x.PREVENT_CAPTURE_ATTR="data-um-no-capture";let T=x;class pe{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 me{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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${y()}?p_${y()}=${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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${y()}?p_${y()}=${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 ye{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 c=this.getCustomHeaders();Object.keys(c).forEach(l=>{s.setRequestHeader(l,c[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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${y()}?p_${y()}=${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 W{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(!u()){this.logger.warn("localStorage is not available in this environment");return}try{localStorage.setItem(this.prefix+"data",JSON.stringify(this.storage))}catch(e){this.logger.error("Error saving to localStorage:",e)}}load(){if(!u()){this.logger.warn("localStorage is not available in this environment");return}try{const e=localStorage.getItem(this.prefix+"data");e&&(this.storage=JSON.parse(e))}catch(e){this.logger.error("Error loading from localStorage:",e)}}}class we{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 K{constructor(e,t=3,i=1e3,s=10,r=1e3,o=f(),c="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 W(`offline_queue_${c}`),u()&&(this.isOnline=navigator.onLine,this.loadQueueFromStorage(),this.initNetworkListeners(),this.scheduleBatch())}add(e){const t={payload:e,retries:0,timestamp:Date.now()};this.queue.push(t),u()?this.saveQueueToStorage():this.processBatch()}initNetworkListeners(){u()&&(window.addEventListener("online",()=>{this.isOnline=!0,this.processBatch()}),window.addEventListener("offline",()=>{this.isOnline=!1}))}scheduleBatch(){u()&&(this.batchTimeoutId!==null&&clearTimeout(this.batchTimeoutId),this.batchTimeoutId=window.setTimeout(()=>this.processBatch(),this.batchInterval))}async processBatch(){if((!u()||this.isOnline)&&!this.processing&&this.queue.length>0){this.processing=!0;const e=this.queue.splice(0,this.batchSize),t=e.map(i=>i.payload);try{await this.transport.send(t),this.logger.debug(`Successfully sent batch of ${e.length} payloads`),u()&&this.saveQueueToStorage()}catch(i){this.logger.error("Failed to send batch",i),await this.handleBatchFailure(e)}this.processing=!1}u()&&this.scheduleBatch()}async handleBatchFailure(e){for(const t of e)t.retries<this.maxRetries?(t.retries++,this.queue.unshift(t),this.logger.warn(`Retry attempt ${t.retries} for payload`)):this.logger.error("Max retries reached, discarding payload",t.payload);u()&&(this.saveQueueToStorage(),await new Promise(t=>setTimeout(t,this.retryInterval)))}loadQueueFromStorage(){if(u()){const e=this.persistence.get("queue");e&&(this.queue=JSON.parse(e))}}saveQueueToStorage(){u()&&this.persistence.set("queue",JSON.stringify(this.queue))}}class ke{constructor(e){this.clicks=[],this.threshold=3,this.timeWindow=2e3,this.distanceThreshold=30,this.client=e,this.initializeEventListener(),F(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 c=this.clicks[o-1];return Math.sqrt(Math.pow(r.x-c.x,2)+Math.pow(r.y-c.y,2))<this.distanceThreshold})&&this.sendRageClickEvent(i)}sendRageClickEvent(e){const t=this.clicks[this.clicks.length-1];document.elementFromPoint(t.x,t.y)&&this.client.track("$rage_click",{no_of_clicks:this.clicks.length,time:e.toFixed(2)}),this.clicks=[]}}class ve{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 c=(void 0)(s,l=>{l.on("data",a=>{}),l.on("end",()=>{const a=l.statusCode||0;a>=200&&a<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${a}`))})});c.on("error",l=>{o(l)}),c.write(JSON.stringify(e)),c.end()})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"";return`${this.trackingHost}/api/v1/s2s/event?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}}class k{constructor(e,t="all",i={}){this.instance=e,this.trackingType=t,this.options=i,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",this.initialize.bind(this)):this.initialize()}initialize(){this.trackingType!=="none"&&this.setupFormTracking()}setupFormTracking(){var e;this.formElements=this.trackingType==="tagged"?document.querySelectorAll("form[data-um-form]"):document.querySelectorAll("form"),(e=this.formElements)==null||e.forEach(t=>{t.addEventListener("submit",this.handleFormSubmit.bind(this))})}handleFormSubmit(e){const t=e.target,i=this._getFormDetails(t);this.instance.track("$form",z(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",z(r))})})}static getInstance(e,t="all",i={}){return k.instance||(k.instance=new k(e,t,i)),k.instance}_getFormDetails(e){const t={form_id:e.id,form_name:e.name||"",form_action:e.action,form_method:e.method,form_class:e.className,form_attributes:this._getElementAttributes(e)},i=e.querySelectorAll("input, select, textarea");return Array.from(i).filter(r=>!r.classList.contains("um-no-capture")).forEach((r,o)=>{const c=this._getFieldProps(r,o);Object.assign(t,c)}),t}_getFieldProps(e,t){const i=Object.keys(e.dataset).length?JSON.stringify(e.dataset):void 0,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=[" ",`
`,"\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 b{constructor(e){this.config=this.mergeConfig(e,D),this.logger=f(this.config.logLevel),this.namespace=e.namespace||"default",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new K(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,200,this.logger,this.namespace),u()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new G(this.config.cookieDomain),this.config.autocapture&&T.enabledForProject(this.config.key)&&!this.config.disableAutocaptureListenerRegistration&&(this.autoCapture=new T(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=k.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new pe(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new ke(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=f(this.config.logLevel),this.namespace=e.namespace||this.namespace,this.transport=this.initializeTransport(e),this.persistence=this.initializePersistence(),this.retryQueue=new K(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,250,this.logger,this.namespace),u()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client reinitialized for namespace: ${this.namespace}`)}manageCrossDomainLinking(){if(!this.config.crossDomainLinking||!this.config.domains)return;const e=this.config.domains.split(",").map(i=>i.trim()),t=this.config.cookieName||`__eventn_id_${this.config.key}`;document.addEventListener("click",i=>{var c;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=(c=this.cookieManager)==null?void 0:c.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(!u())return new ve(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 me(e.trackingHost||t,e,this.logger);if(e.forceUseFetch&&s)return new Q(e.trackingHost||t,e,this.logger);if(i)return new ye(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||!u()?new we:new W(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var i,s;if(!u())return L();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 c=new URLSearchParams(window.location.search).get("_um"),a=window.location.hash.substring(1).split("~"),h=a.length>1?a[1]:void 0;t=c||h||L()}t||(t=L());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&&!le(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(fe()){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(!_(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")||{},c=this.persistence.get(`props_${e}`)||{};let l=t||{};const a={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,...c};if(e==="$autocapture"){const h=this.processAutocaptureAttributes(t||{});a.autocapture_attributes=h}else e!=="user_identify"&&e!=="group"&&(Array.isArray(this.config.propertyBlacklist)&&this.config.propertyBlacklist.forEach(h=>{delete l[h]}),a.event_attributes=l);return u()&&(a.referer=document.referrer,a.url=window.location.href,a.page_title=document.title,a.doc_path=window.location.pathname,a.doc_host=window.location.hostname,a.doc_search=window.location.search,a.screen_resolution=`${window.screen.width}x${window.screen.height}`,a.vp_size=`${window.innerWidth}x${window.innerHeight}`,a.user_agent=navigator.userAgent,a.user_language=navigator.language,a.doc_encoding=document.characterSet,a.utm=this.getUtmParams()),a}processAutocaptureAttributes(e){let t={};const i=e.$elements||[];return i.length&&(t={...i[0]}),t.el_text=t.$el_text||"",t.event_type=e.$event_type||"",["$ce_version","$event_type","$initial_referrer","$initial_referring_domain","$referrer","$referring_domain","$elements"].forEach(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(u()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=he(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(){u()?this.track("pageview",{url:window.location.href,referrer:document.referrer,title:document.title},!0):this.logger.warn("Pageview tracking is not available in server-side environments")}setupPageLeaveTracking(){if(!u())return;let e=!1,t=!1;const i=()=>{!e&&!t&&(e=!0,this.track("$pageleave",{url:window.location.href,referrer:document.referrer,title:document.title}))};window.addEventListener("beforeunload",r=>{t=!0,setTimeout(()=>{t=!1},100)}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&!t&&i()});const 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 X(){return typeof window<"u"&&typeof window.define=="function"&&window.define.amd}function _e(){return X()?window.define:void 0}const be="__USERMAVEN_AUTOCAPTURE_INITIALIZED__";function P(n){const e=JSON.parse(JSON.stringify(n)),t=O(e),i={...D,...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=`${be}${s}`;return u()&&i.autocapture&&window[r]&&(console.warn("Usermaven: Autocapture already initialized in another instance, skipping duplicate initialization."),i.disableAutocaptureListenerRegistration=!0),u()&&i.autocapture&&!i.disableAutocaptureListenerRegistration&&(window[r]=!0),new b(i)}function Pe(n){var s;const e={key:n.getAttribute("data-key")||void 0,trackingHost:n.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:de(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=P(e),i=e.namespace||"usermaven";return u()&&t.pageview(),Ee(i,t),t}function Ee(n,e){let t=!1;const i=[],s=[];function r(){for(;i.length>0;){const a=i.shift();a&&window[n].apply(null,a)}}function o(){s.forEach(a=>a()),s.length=0}window[n]=function(...a){const h=a[0];if(h==="onLoad"){typeof a[1]=="function"&&(t?a[1]():s.push(a[1]));return}if(!t){i.push(a);return}if(typeof e[h]=="function")return e[h].apply(e,a.slice(1));console.error(`Method ${h} not found on UsermavenClient`)};const c=`${n}Q`,l=window[c]||[];for(window[c]=l,l.push=function(...a){return window[n].apply(null,a),Array.prototype.push.apply(this,a)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${n} is ready`)},0);l.length>0;){const a=l.shift();a&&i.push(a)}}let Z=!1,U=null;if(u()){const n=_e();n&&n("usermaven",[],function(){return{usermavenClient:P,UsermavenClient:b,LogLevel:d,getScriptTagClient:()=>U}}),typeof window<"u"&&(window.usermavenClient=P,window.UsermavenClient=b,window.usermavenScriptTagClient=()=>U),function(e,t){const i=e.currentScript;function s(){return Z||!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"),U=Pe(i),Z=!0)}typeof t<"u"&&i&&(e.readyState==="loading"?e.addEventListener("DOMContentLoaded",r):r())}(document,window)}typeof module<"u"&&module.exports&&!X()&&(module.exports={usermavenClient:P,UsermavenClient:b,Config:void 0,UserProps:void 0,EventPayload:void 0,LogLevel:d,ClientProperties:void 0}),g.LogLevel=d,g.UsermavenClient=b,g.usermavenClient=P,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})});

@@ -1,2 +0,2 @@

"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});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 G{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 d(n=0){return new G(n)}const q={logLevel:f.ERROR,useBeaconApi:!1,forceUseFetch:!1,trackingHost:"t.usermaven.com",autocapture:!1,rageClick:!1,formTracking:!1,autoPageview:!1,disableEventPersistence:!1,gaHook:!1,segmentHook:!1,randomizeUrl:!1,capture3rdPartyCookies:["_ga","_fbp","_ym_uid","ajs_user_id","ajs_anonymous_id"],idMethod:"cookie",ipPolicy:"keep",cookiePolicy:"keep",minSendTimeout:0,maxSendTimeout:2e3,maxSendAttempts:4,propertiesStringMaxLength:null,propertyBlacklist:[],crossDomainLinking:!0,maskAllText:!1,maskAllElementAttributes:!1};class j{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 c=`expires=${o.toUTCString()}`,l=s?"; Secure":"",a=r?"; HttpOnly":"";document.cookie=`${e}=${t};${c};path=/;domain=${this.cookieDomain}${l}${a}`}get(e){const t=e+"=",i=document.cookie.split(";");for(let 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 ee=Object.prototype,te=ee.hasOwnProperty,ie=Array.prototype,S=ie.forEach,N={};function ne(n,e,t){if(Array.isArray(n)){if(S&&n.forEach===S)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)===N)return}}}const O=function(n){return n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},se=function(n){for(const e in n)typeof n[e]=="function"&&(n[e]=n[e].bind(n))};function p(n,e,t){if(n!=null){if(S&&Array.isArray(n)&&n.forEach===S)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)===N)return}else for(const i in n)if(te.call(n,i)&&e.call(t,n[i],i)===N)return}}const re=function(n,...e){return ne(e,function(t){for(const i in t)t[i]!==void 0&&(n[i]=t[i])}),n};function _(n,e){return n.indexOf(e)!==-1}const oe=function(n){try{return/^\s*\bfunction\b/.test(n)}catch{return!1}},ae=function(n){return n===void 0},y=function(){const n=function(i,s,r,o,c){if(!i){d().error("No valid element provided to register_event");return}if(i.addEventListener&&!o)i.addEventListener(s,r,!!c);else{const l="on"+s,a=i[l];i[l]=e(i,r,a)}};function e(i,s,r){return function(o){if(o=o||t(window.event),!o)return;let c=!0,l;oe(r)&&(l=r(o));const a=s.call(i,o);return(l===!1||a===!1)&&(c=!1),c}}function t(i){return i&&(i.preventDefault=t.preventDefault,i.stopPropagation=t.stopPropagation),i}return t.preventDefault=function(){this.returnValue=!1},t.stopPropagation=function(){this.cancelBubble=!0},n}(),ce=function(n){return function(...e){try{return n.apply(this,e)}catch(t){d().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]=ce(n[e]))};function U(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 u(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return d().warn("window is not available"),!1}}function m(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 le(n){return n.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function R(n){return typeof n!="object"||n===null?n:Array.isArray(n)?n.map(R):Object.keys(n).reduce((e,t)=>{const i=le(t);return e[i]=R(n[t]),e},{})}function $(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 D(n){let e="";return L(n)&&!W(n)&&n.childNodes&&n.childNodes.length&&p(n.childNodes,function(t){Q(t)&&t.textContent&&(e+=O(t.textContent).split(/(\s+)/).filter(A).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),O(e)}function J(n){return!!n&&n.nodeType===1}function g(n,e){return!!n&&!!n.tagName&&n.tagName.toLowerCase()===e.toLowerCase()}function Q(n){return!!n&&n.nodeType===3}function I(n){return!!n&&n.nodeType===11}const P=["a","button","form","input","select","textarea","label"];function ue(n,e){if(!n||g(n,"html")||!J(n))return!1;let t=n;for(;t&&!g(t,"body");){if(t.classList&&t.classList.contains("um-no-capture"))return!1;t.parentNode&&I(t.parentNode)?t=t.parentNode.host:t=t.parentNode}let i=!1;for(t=n;t&&!g(t,"body");){if(t.parentNode&&I(t.parentNode)){t=t.parentNode.host,t&&P.indexOf(t.tagName.toLowerCase())>-1&&(i=!0);continue}const o=t.parentNode;if(!o)break;if(P.indexOf(o.tagName.toLowerCase())>-1)i=!0;else{const c=window.getComputedStyle(o);c&&c.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"&&(P.indexOf(r)>-1||n.getAttribute("contenteditable")==="true")}}function L(n){for(let i=n;i.parentNode&&!g(i,"body");i=i.parentNode){const s=$(i).split(" ");if(_(s,"ph-sensitive")||_(s,"ph-no-capture"))return!1}if(_($(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 W(n){const e=["button","checkbox","submit","reset"];return!!(g(n,"input")&&!e.includes(n.type)||g(n,"select")||g(n,"textarea")||n.getAttribute("contenteditable")==="true")}function A(n){return!(n===null||ae(n)||typeof n=="string"&&(n=O(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 he(n){return typeof n=="string"?n.substring(0,10)==="_ngcontent"||n.substring(0,7)==="_nghost":!1}function x(){return m(10)}function de(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 fe(n,e){let t;return function(...i){const s=()=>{clearTimeout(t),n(...i)};clearTimeout(t),t=setTimeout(s,e)}}function ge(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 F(n){return typeof n=="string"||n instanceof String}function v(n){return n!==null&&typeof n=="object"&&n.constructor===Object}function pe(n){if(n===null)return f.ERROR;const e=n.toUpperCase(),t=f[e];return t||t===0?t:f.ERROR}const me=()=>{let n="false";return typeof window<"u"&&window.localStorage&&(n=localStorage.getItem("um_exclusion")),!(n==null||n==="false")};class ye{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=fe(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 T=class T{constructor(e,t,i=d()){this.logger=i,this.scrollDepth=null,this.customProperties=[],this.domHandlersAttached=!1,this.client=e,this.options=t,this.scrollDepth=new ye(e),se(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)};y(document,"submit",e,!1,!0),y(document,"change",e,!1,!0),y(document,"click",e,!1,!0),y(document,"visibilitychange",e,!1,!0),y(document,"scroll",e,!1,!0),y(window,"popstate",e,!1,!0)}isPageRefresh(){if("PerformanceNavigationTiming"in window){const e=performance.getEntriesByType("navigation");if(e.length>0)return e[0].type==="reload"}return performance.navigation&&performance.navigation.type===1}captureEvent(e){var i,s;let t=this.getEventTarget(e);if(Q(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&&ue(t,e)){const r=[t];let o=t;for(;o.parentNode&&!g(o,"body");){if(I(o.parentNode)){r.push(o.parentNode.host),o=o.parentNode.host;continue}r.push(o.parentNode),o=o.parentNode}const c=[];let l,a=!1;if(p(r,k=>{const Z=L(k);k.tagName.toLowerCase()==="a"&&(l=k.getAttribute("href"),l=Z&&A(l)&&l);const Y=$(k).split(" ");_(Y,"ph-no-capture")&&(a=!0),c.push(this.getPropertiesFromElement(k,this.options.maskAllElementAttributes??!1,this.options.maskAllText??!1))}),this.options.maskAllText||(c[0].$el_text=D(t)),l&&(c[0].attr__href=l),a)return!1;const h=re(this.getDefaultProperties(e.type),{$elements:c},this.getCustomProperties(r));return this.client.track("$autocapture",h),!0}}getCustomProperties(e){const t={};return p(this.customProperties,i=>{p(i.event_selectors,s=>{const r=document.querySelectorAll(s);p(r,o=>{_(e,o)&&L(o)&&(t[i.name]=this.extractCustomPropertyValue(i))})})}),t}extractCustomPropertyValue(e){const t=[];return p(document.querySelectorAll(e.css_selector),function(i){let s;["input","select"].indexOf(i.tagName.toLowerCase())>-1?s=i.value:i.textContent&&(s=i.textContent),A(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};P.indexOf(s)>-1&&!i&&(r.$el_text=D(e));const o=$(e);o.length>0&&(r.classes=o.split(" ").filter(function(h){return h!==""})),p(e.attributes,function(h){W(e)&&["name","id","class"].indexOf(h.name)===-1||!t&&A(h.value)&&!he(h.name)&&(r["attr__"+h.name]=h.value)});let c=1,l=1,a=e;for(;a=this.previousElementSibling(a);)c++,a.tagName===e.tagName&&l++;return r.nth_child=c,r.nth_of_type=l,r}previousElementSibling(e){if(e.previousElementSibling)return e.previousElementSibling;{let t=e;do t=t.previousSibling;while(t&&!J(t));return t}}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}encodeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}static enabledForProject(e,t=10,i=10){if(!e)return!1;let s=0;for(let r=0;r<e.length;r++)s+=e.charCodeAt(r);return s%t<i}};T.FORCE_CAPTURE_ATTR="data-um-force-capture",T.PREVENT_CAPTURE_ATTR="data-um-no-capture";let C=T;class we{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 ke{constructor(e,t,i=d()){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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${e}${t}${i}`:`${this.trackingHost}${s}?token=${e}${t}${i}`}}class z{constructor(e,t,i=d()){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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${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 ve{constructor(e,t,i=d()){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 c=this.getCustomHeaders();Object.keys(c).forEach(l=>{s.setRequestHeader(l,c[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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${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 K{constructor(e,t){this.storage={},this.prefix=`usermaven_${e}_`,this.load(),this.logger=t||d()}set(e,t){this.storage[e]=t,this.save()}get(e){return this.storage[e]}remove(e){delete this.storage[e],this.save()}clear(){this.storage={},this.save()}save(){if(!u()){this.logger.warn("localStorage is not available in this environment");return}try{localStorage.setItem(this.prefix+"data",JSON.stringify(this.storage))}catch(e){this.logger.error("Error saving to localStorage:",e)}}load(){if(!u()){this.logger.warn("localStorage is not available in this environment");return}try{const e=localStorage.getItem(this.prefix+"data");e&&(this.storage=JSON.parse(e))}catch(e){this.logger.error("Error loading from localStorage:",e)}}}class _e{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 M{constructor(e,t=3,i=1e3,s=10,r=1e3,o=d(),c="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 K(`offline_queue_${c}`),u()&&(this.isOnline=navigator.onLine,this.loadQueueFromStorage(),this.initNetworkListeners(),this.scheduleBatch())}add(e){const t={payload:e,retries:0,timestamp:Date.now()};this.queue.push(t),u()?this.saveQueueToStorage():this.processBatch()}initNetworkListeners(){u()&&(window.addEventListener("online",()=>{this.isOnline=!0,this.processBatch()}),window.addEventListener("offline",()=>{this.isOnline=!1}))}scheduleBatch(){u()&&(this.batchTimeoutId!==null&&clearTimeout(this.batchTimeoutId),this.batchTimeoutId=window.setTimeout(()=>this.processBatch(),this.batchInterval))}async processBatch(){if((!u()||this.isOnline)&&!this.processing&&this.queue.length>0){this.processing=!0;const e=this.queue.splice(0,this.batchSize),t=e.map(i=>i.payload);try{await this.transport.send(t),this.logger.debug(`Successfully sent batch of ${e.length} payloads`),u()&&this.saveQueueToStorage()}catch(i){this.logger.error("Failed to send batch",i),await this.handleBatchFailure(e)}this.processing=!1}u()&&this.scheduleBatch()}async handleBatchFailure(e){for(const t of e)t.retries<this.maxRetries?(t.retries++,this.queue.unshift(t),this.logger.warn(`Retry attempt ${t.retries} for payload`)):this.logger.error("Max retries reached, discarding payload",t.payload);u()&&(this.saveQueueToStorage(),await new Promise(t=>setTimeout(t,this.retryInterval)))}loadQueueFromStorage(){if(u()){const e=this.persistence.get("queue");e&&(this.queue=JSON.parse(e))}}saveQueueToStorage(){u()&&this.persistence.set("queue",JSON.stringify(this.queue))}}class be{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 c=this.clicks[o-1];return Math.sqrt(Math.pow(r.x-c.x,2)+Math.pow(r.y-c.y,2))<this.distanceThreshold})&&this.sendRageClickEvent(i)}sendRageClickEvent(e){const t=this.clicks[this.clicks.length-1];document.elementFromPoint(t.x,t.y)&&this.client.track("$rage_click",{no_of_clicks:this.clicks.length,time:e.toFixed(2)}),this.clicks=[]}}class Ee{constructor(e,t,i=d()){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 c=(void 0)(s,l=>{l.on("data",a=>{}),l.on("end",()=>{const a=l.statusCode||0;a>=200&&a<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${a}`))})});c.on("error",l=>{o(l)}),c.write(JSON.stringify(e)),c.end()})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"";return`${this.trackingHost}/api/v1/s2s/event?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}}class w{constructor(e,t="all",i={}){this.instance=e,this.trackingType=t,this.options=i,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",this.initialize.bind(this)):this.initialize()}initialize(){this.trackingType!=="none"&&this.setupFormTracking()}setupFormTracking(){var e;this.formElements=this.trackingType==="tagged"?document.querySelectorAll("form[data-um-form]"):document.querySelectorAll("form"),(e=this.formElements)==null||e.forEach(t=>{t.addEventListener("submit",this.handleFormSubmit.bind(this))})}handleFormSubmit(e){const t=e.target,i=this._getFormDetails(t);this.instance.track("$form",U(i)),this.options.trackFieldChanges&&this.trackFieldChanges(t)}trackFieldChanges(e){e.querySelectorAll("input, select, textarea").forEach(i=>{i.addEventListener("change",s=>{const r=this._getFieldProps(s.target,0);this.instance.track("$form_field_change",U(r))})})}static getInstance(e,t="all",i={}){return w.instance||(w.instance=new w(e,t,i)),w.instance}_getFormDetails(e){const t={form_id:e.id,form_name:e.name||"",form_action:e.action,form_method:e.method,form_class:e.className,form_attributes:this._getElementAttributes(e)},i=e.querySelectorAll("input, select, textarea");return Array.from(i).filter(r=>!r.classList.contains("um-no-capture")).forEach((r,o)=>{const c=this._getFieldProps(r,o);Object.assign(t,c)}),t}_getFieldProps(e,t){const i=Object.keys(e.dataset).length?JSON.stringify(e.dataset):void 0,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=[" ",`
`,"\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 b{constructor(e){this.config=this.mergeConfig(e,q),this.logger=d(this.config.logLevel),this.namespace=e.namespace||"default",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new M(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,200,this.logger,this.namespace),u()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new j(this.config.cookieDomain),this.config.autocapture&&C.enabledForProject(this.config.key)&&!this.config.disableAutocaptureListenerRegistration&&(this.autoCapture=new C(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=w.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new we(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new be(this)),this.setupPageLeaveTracking()}mergeConfig(e,t){const i=JSON.parse(JSON.stringify(e));let s={...t,...i};return Object.keys(t).forEach(r=>{v(t[r])&&(s[r]=this.mergeConfig(e[r],t[r]))}),s}init(e){this.config={...this.config,...e},this.logger=d(this.config.logLevel),this.namespace=e.namespace||this.namespace,this.transport=this.initializeTransport(e),this.persistence=this.initializePersistence(),this.retryQueue=new M(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,250,this.logger,this.namespace),u()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client reinitialized for namespace: ${this.namespace}`)}manageCrossDomainLinking(){if(!this.config.crossDomainLinking||!this.config.domains)return;const e=this.config.domains.split(",").map(i=>i.trim()),t=this.config.cookieName||`__eventn_id_${this.config.key}`;document.addEventListener("click",i=>{var c;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=(c=this.cookieManager)==null?void 0:c.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(!u())return new Ee(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 ke(e.trackingHost||t,e,this.logger);if(e.forceUseFetch&&s)return new z(e.trackingHost||t,e,this.logger);if(i)return new ve(e.trackingHost||t,e,this.logger);if(s)return new z(e.trackingHost||t,e,this.logger);throw new Error("No suitable transport method available")}initializePersistence(){return this.config.disableEventPersistence||!u()?new _e:new K(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var i,s;if(!u())return x();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 c=new URLSearchParams(window.location.search).get("_um"),a=window.location.hash.substring(1).split("~"),h=a.length>1?a[1]:void 0;t=c||h||x()}t||(t=x());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(!v(e))throw new Error("User data must be an object");if(e.email&&!de(e.email))throw new Error("Invalid email provided");if(!e.id||!F(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(me()){this.logger.debug("Tracking disabled due to um_exclusion setting");return}if(!F(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(!v(e))throw new Error("Event payload must be an object");this.track("raw",e)}async group(e,t=!1){if(!v(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")||{},c=this.persistence.get(`props_${e}`)||{};let l=t||{};const a={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,...c};if(e==="$autocapture"){const h=this.processAutocaptureAttributes(t||{});a.autocapture_attributes=h}else e!=="user_identify"&&e!=="group"&&(Array.isArray(this.config.propertyBlacklist)&&this.config.propertyBlacklist.forEach(h=>{delete l[h]}),a.event_attributes=l);return u()&&(a.referer=document.referrer,a.url=window.location.href,a.page_title=document.title,a.doc_path=window.location.pathname,a.doc_host=window.location.hostname,a.doc_search=window.location.search,a.screen_resolution=`${window.screen.width}x${window.screen.height}`,a.vp_size=`${window.innerWidth}x${window.innerHeight}`,a.user_agent=navigator.userAgent,a.user_language=navigator.language,a.doc_encoding=document.characterSet,a.utm=this.getUtmParams()),a}processAutocaptureAttributes(e){let t={};const i=e.$elements||[];return i.length&&(t={...i[0]}),t.el_text=t.$el_text||"",t.event_type=e.$event_type||"",["$ce_version","$event_type","$initial_referrer","$initial_referring_domain","$referrer","$referring_domain","$elements"].forEach(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(u()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=ge(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(){u()?this.track("pageview",{url:window.location.href,referrer:document.referrer,title:document.title},!0):this.logger.warn("Pageview tracking is not available in server-side environments")}setupPageLeaveTracking(){if(!u())return;let e=!1,t=!1;const i=()=>{!e&&!t&&(e=!0,this.track("$pageleave",{url:window.location.href,referrer:document.referrer,title:document.title}))};window.addEventListener("beforeunload",r=>{t=!0,setTimeout(()=>{t=!1},100)}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&!t&&i()});const 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(!v(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 X(){return typeof window<"u"&&typeof window.define=="function"&&window.define.amd}function Pe(){return X()?window.define:void 0}const Ae="__USERMAVEN_AUTOCAPTURE_INITIALIZED__";function E(n){const e=JSON.parse(JSON.stringify(n)),t=R(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=`${Ae}${s}`;return u()&&i.autocapture&&window[r]&&(console.warn("Usermaven: Autocapture already initialized in another instance, skipping duplicate initialization."),i.disableAutocaptureListenerRegistration=!0),u()&&i.autocapture&&!i.disableAutocaptureListenerRegistration&&(window[r]=!0),new b(i)}function Se(n){var s;const e={key:n.getAttribute("data-key")||void 0,trackingHost:n.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:pe(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(e),i=e.namespace||"usermaven";return u()&&e.autoPageview!==!1&&t.pageview(),$e(i,t),t}function $e(n,e){let t=!1;const i=[],s=[];function r(){for(;i.length>0;){const a=i.shift();a&&window[n].apply(null,a)}}function o(){s.forEach(a=>a()),s.length=0}window[n]=function(...a){const h=a[0];if(h==="onLoad"){typeof a[1]=="function"&&(t?a[1]():s.push(a[1]));return}if(!t){i.push(a);return}if(typeof e[h]=="function")return e[h].apply(e,a.slice(1));console.error(`Method ${h} not found on UsermavenClient`)};const c=`${n}Q`,l=window[c]||[];for(window[c]=l,l.push=function(...a){return window[n].apply(null,a),Array.prototype.push.apply(this,a)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${n} is ready`)},0);l.length>0;){const a=l.shift();a&&i.push(a)}}let B=!1,H=null;if(u()){const n=Pe();n&&n("usermaven",[],function(){return{usermavenClient:E,UsermavenClient:b,LogLevel:f,getScriptTagClient:()=>H}}),typeof window<"u"&&(window.usermavenClient=E,window.UsermavenClient=b,window.usermavenScriptTagClient=()=>H),function(e,t){const i=e.currentScript;function s(){return B||!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"),H=Se(i),B=!0)}typeof t<"u"&&i&&(e.readyState==="loading"?e.addEventListener("DOMContentLoaded",r):r())}(document,window)}typeof module<"u"&&module.exports&&!X()&&(module.exports={usermavenClient:E,UsermavenClient:b,Config:void 0,UserProps:void 0,EventPayload:void 0,LogLevel:f,ClientProperties:void 0});exports.LogLevel=f;exports.UsermavenClient=b;exports.usermavenClient=E;
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});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 G{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 d(n=0){return new G(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 j{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 c=`expires=${o.toUTCString()}`,l=s?"; Secure":"",a=r?"; HttpOnly":"";document.cookie=`${e}=${t};${c};path=/;domain=${this.cookieDomain}${l}${a}`}get(e){const t=e+"=",i=document.cookie.split(";");for(let 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 ee=Object.prototype,te=ee.hasOwnProperty,ie=Array.prototype,S=ie.forEach,N={};function ne(n,e,t){if(Array.isArray(n)){if(S&&n.forEach===S)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)===N)return}}}const O=function(n){return n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},se=function(n){for(const e in n)typeof n[e]=="function"&&(n[e]=n[e].bind(n))};function p(n,e,t){if(n!=null){if(S&&Array.isArray(n)&&n.forEach===S)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)===N)return}else for(const i in n)if(te.call(n,i)&&e.call(t,n[i],i)===N)return}}const re=function(n,...e){return ne(e,function(t){for(const i in t)t[i]!==void 0&&(n[i]=t[i])}),n};function _(n,e){return n.indexOf(e)!==-1}const oe=function(n){try{return/^\s*\bfunction\b/.test(n)}catch{return!1}},ae=function(n){return n===void 0},y=function(){const n=function(i,s,r,o,c){if(!i){d().error("No valid element provided to register_event");return}if(i.addEventListener&&!o)i.addEventListener(s,r,!!c);else{const l="on"+s,a=i[l];i[l]=e(i,r,a)}};function e(i,s,r){return function(o){if(o=o||t(window.event),!o)return;let c=!0,l;oe(r)&&(l=r(o));const a=s.call(i,o);return(l===!1||a===!1)&&(c=!1),c}}function t(i){return i&&(i.preventDefault=t.preventDefault,i.stopPropagation=t.stopPropagation),i}return t.preventDefault=function(){this.returnValue=!1},t.stopPropagation=function(){this.cancelBubble=!0},n}(),ce=function(n){return function(...e){try{return n.apply(this,e)}catch(t){d().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]=ce(n[e]))};function U(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 u(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return d().warn("window is not available"),!1}}function m(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 le(n){return n.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function R(n){return typeof n!="object"||n===null?n:Array.isArray(n)?n.map(R):Object.keys(n).reduce((e,t)=>{const i=le(t);return e[i]=R(n[t]),e},{})}function $(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 D(n){let e="";return L(n)&&!W(n)&&n.childNodes&&n.childNodes.length&&p(n.childNodes,function(t){Q(t)&&t.textContent&&(e+=O(t.textContent).split(/(\s+)/).filter(A).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),O(e)}function J(n){return!!n&&n.nodeType===1}function g(n,e){return!!n&&!!n.tagName&&n.tagName.toLowerCase()===e.toLowerCase()}function Q(n){return!!n&&n.nodeType===3}function I(n){return!!n&&n.nodeType===11}const P=["a","button","form","input","select","textarea","label"];function ue(n,e){if(!n||g(n,"html")||!J(n))return!1;let t=n;for(;t&&!g(t,"body");){if(t.classList&&t.classList.contains("um-no-capture"))return!1;t.parentNode&&I(t.parentNode)?t=t.parentNode.host:t=t.parentNode}let i=!1;for(t=n;t&&!g(t,"body");){if(t.parentNode&&I(t.parentNode)){t=t.parentNode.host,t&&P.indexOf(t.tagName.toLowerCase())>-1&&(i=!0);continue}const o=t.parentNode;if(!o)break;if(P.indexOf(o.tagName.toLowerCase())>-1)i=!0;else{const c=window.getComputedStyle(o);c&&c.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"&&(P.indexOf(r)>-1||n.getAttribute("contenteditable")==="true")}}function L(n){for(let i=n;i.parentNode&&!g(i,"body");i=i.parentNode){const s=$(i).split(" ");if(_(s,"ph-sensitive")||_(s,"ph-no-capture"))return!1}if(_($(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 W(n){const e=["button","checkbox","submit","reset"];return!!(g(n,"input")&&!e.includes(n.type)||g(n,"select")||g(n,"textarea")||n.getAttribute("contenteditable")==="true")}function A(n){return!(n===null||ae(n)||typeof n=="string"&&(n=O(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 he(n){return typeof n=="string"?n.substring(0,10)==="_ngcontent"||n.substring(0,7)==="_nghost":!1}function x(){return m(10)}function de(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 fe(n,e){let t;return function(...i){const s=()=>{clearTimeout(t),n(...i)};clearTimeout(t),t=setTimeout(s,e)}}function ge(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 F(n){return typeof n=="string"||n instanceof String}function v(n){return n!==null&&typeof n=="object"&&n.constructor===Object}function pe(n){if(n===null)return f.ERROR;const e=n.toUpperCase(),t=f[e];return t||t===0?t:f.ERROR}const me=()=>{let n="false";return typeof window<"u"&&window.localStorage&&(n=localStorage.getItem("um_exclusion")),!(n==null||n==="false")};class ye{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=fe(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 T=class T{constructor(e,t,i=d()){this.logger=i,this.scrollDepth=null,this.customProperties=[],this.domHandlersAttached=!1,this.client=e,this.options=t,this.scrollDepth=new ye(e),se(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)};y(document,"submit",e,!1,!0),y(document,"change",e,!1,!0),y(document,"click",e,!1,!0),y(document,"visibilitychange",e,!1,!0),y(document,"scroll",e,!1,!0),y(window,"popstate",e,!1,!0)}isPageRefresh(){if("PerformanceNavigationTiming"in window){const e=performance.getEntriesByType("navigation");if(e.length>0)return e[0].type==="reload"}return performance.navigation&&performance.navigation.type===1}captureEvent(e){var i,s;let t=this.getEventTarget(e);if(Q(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&&ue(t,e)){const r=[t];let o=t;for(;o.parentNode&&!g(o,"body");){if(I(o.parentNode)){r.push(o.parentNode.host),o=o.parentNode.host;continue}r.push(o.parentNode),o=o.parentNode}const c=[];let l,a=!1;if(p(r,k=>{const Z=L(k);k.tagName.toLowerCase()==="a"&&(l=k.getAttribute("href"),l=Z&&A(l)&&l);const Y=$(k).split(" ");_(Y,"ph-no-capture")&&(a=!0),c.push(this.getPropertiesFromElement(k,this.options.maskAllElementAttributes??!1,this.options.maskAllText??!1))}),this.options.maskAllText||(c[0].$el_text=D(t)),l&&(c[0].attr__href=l),a)return!1;const h=re(this.getDefaultProperties(e.type),{$elements:c},this.getCustomProperties(r));return this.client.track("$autocapture",h),!0}}getCustomProperties(e){const t={};return p(this.customProperties,i=>{p(i.event_selectors,s=>{const r=document.querySelectorAll(s);p(r,o=>{_(e,o)&&L(o)&&(t[i.name]=this.extractCustomPropertyValue(i))})})}),t}extractCustomPropertyValue(e){const t=[];return p(document.querySelectorAll(e.css_selector),function(i){let s;["input","select"].indexOf(i.tagName.toLowerCase())>-1?s=i.value:i.textContent&&(s=i.textContent),A(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};P.indexOf(s)>-1&&!i&&(r.$el_text=D(e));const o=$(e);o.length>0&&(r.classes=o.split(" ").filter(function(h){return h!==""})),p(e.attributes,function(h){W(e)&&["name","id","class"].indexOf(h.name)===-1||!t&&A(h.value)&&!he(h.name)&&(r["attr__"+h.name]=h.value)});let c=1,l=1,a=e;for(;a=this.previousElementSibling(a);)c++,a.tagName===e.tagName&&l++;return r.nth_child=c,r.nth_of_type=l,r}previousElementSibling(e){if(e.previousElementSibling)return e.previousElementSibling;{let t=e;do t=t.previousSibling;while(t&&!J(t));return t}}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}encodeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}static enabledForProject(e,t=10,i=10){if(!e)return!1;let s=0;for(let r=0;r<e.length;r++)s+=e.charCodeAt(r);return s%t<i}};T.FORCE_CAPTURE_ATTR="data-um-force-capture",T.PREVENT_CAPTURE_ATTR="data-um-no-capture";let C=T;class we{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 ke{constructor(e,t,i=d()){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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${e}${t}${i}`:`${this.trackingHost}${s}?token=${e}${t}${i}`}}class z{constructor(e,t,i=d()){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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${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 ve{constructor(e,t,i=d()){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 c=this.getCustomHeaders();Object.keys(c).forEach(l=>{s.setRequestHeader(l,c[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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${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 K{constructor(e,t){this.storage={},this.prefix=`usermaven_${e}_`,this.load(),this.logger=t||d()}set(e,t){this.storage[e]=t,this.save()}get(e){return this.storage[e]}remove(e){delete this.storage[e],this.save()}clear(){this.storage={},this.save()}save(){if(!u()){this.logger.warn("localStorage is not available in this environment");return}try{localStorage.setItem(this.prefix+"data",JSON.stringify(this.storage))}catch(e){this.logger.error("Error saving to localStorage:",e)}}load(){if(!u()){this.logger.warn("localStorage is not available in this environment");return}try{const e=localStorage.getItem(this.prefix+"data");e&&(this.storage=JSON.parse(e))}catch(e){this.logger.error("Error loading from localStorage:",e)}}}class _e{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 M{constructor(e,t=3,i=1e3,s=10,r=1e3,o=d(),c="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 K(`offline_queue_${c}`),u()&&(this.isOnline=navigator.onLine,this.loadQueueFromStorage(),this.initNetworkListeners(),this.scheduleBatch())}add(e){const t={payload:e,retries:0,timestamp:Date.now()};this.queue.push(t),u()?this.saveQueueToStorage():this.processBatch()}initNetworkListeners(){u()&&(window.addEventListener("online",()=>{this.isOnline=!0,this.processBatch()}),window.addEventListener("offline",()=>{this.isOnline=!1}))}scheduleBatch(){u()&&(this.batchTimeoutId!==null&&clearTimeout(this.batchTimeoutId),this.batchTimeoutId=window.setTimeout(()=>this.processBatch(),this.batchInterval))}async processBatch(){if((!u()||this.isOnline)&&!this.processing&&this.queue.length>0){this.processing=!0;const e=this.queue.splice(0,this.batchSize),t=e.map(i=>i.payload);try{await this.transport.send(t),this.logger.debug(`Successfully sent batch of ${e.length} payloads`),u()&&this.saveQueueToStorage()}catch(i){this.logger.error("Failed to send batch",i),await this.handleBatchFailure(e)}this.processing=!1}u()&&this.scheduleBatch()}async handleBatchFailure(e){for(const t of e)t.retries<this.maxRetries?(t.retries++,this.queue.unshift(t),this.logger.warn(`Retry attempt ${t.retries} for payload`)):this.logger.error("Max retries reached, discarding payload",t.payload);u()&&(this.saveQueueToStorage(),await new Promise(t=>setTimeout(t,this.retryInterval)))}loadQueueFromStorage(){if(u()){const e=this.persistence.get("queue");e&&(this.queue=JSON.parse(e))}}saveQueueToStorage(){u()&&this.persistence.set("queue",JSON.stringify(this.queue))}}class be{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 c=this.clicks[o-1];return Math.sqrt(Math.pow(r.x-c.x,2)+Math.pow(r.y-c.y,2))<this.distanceThreshold})&&this.sendRageClickEvent(i)}sendRageClickEvent(e){const t=this.clicks[this.clicks.length-1];document.elementFromPoint(t.x,t.y)&&this.client.track("$rage_click",{no_of_clicks:this.clicks.length,time:e.toFixed(2)}),this.clicks=[]}}class Ee{constructor(e,t,i=d()){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 c=(void 0)(s,l=>{l.on("data",a=>{}),l.on("end",()=>{const a=l.statusCode||0;a>=200&&a<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${a}`))})});c.on("error",l=>{o(l)}),c.write(JSON.stringify(e)),c.end()})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"";return`${this.trackingHost}/api/v1/s2s/event?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}}class w{constructor(e,t="all",i={}){this.instance=e,this.trackingType=t,this.options=i,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",this.initialize.bind(this)):this.initialize()}initialize(){this.trackingType!=="none"&&this.setupFormTracking()}setupFormTracking(){var e;this.formElements=this.trackingType==="tagged"?document.querySelectorAll("form[data-um-form]"):document.querySelectorAll("form"),(e=this.formElements)==null||e.forEach(t=>{t.addEventListener("submit",this.handleFormSubmit.bind(this))})}handleFormSubmit(e){const t=e.target,i=this._getFormDetails(t);this.instance.track("$form",U(i)),this.options.trackFieldChanges&&this.trackFieldChanges(t)}trackFieldChanges(e){e.querySelectorAll("input, select, textarea").forEach(i=>{i.addEventListener("change",s=>{const r=this._getFieldProps(s.target,0);this.instance.track("$form_field_change",U(r))})})}static getInstance(e,t="all",i={}){return w.instance||(w.instance=new w(e,t,i)),w.instance}_getFormDetails(e){const t={form_id:e.id,form_name:e.name||"",form_action:e.action,form_method:e.method,form_class:e.className,form_attributes:this._getElementAttributes(e)},i=e.querySelectorAll("input, select, textarea");return Array.from(i).filter(r=>!r.classList.contains("um-no-capture")).forEach((r,o)=>{const c=this._getFieldProps(r,o);Object.assign(t,c)}),t}_getFieldProps(e,t){const i=Object.keys(e.dataset).length?JSON.stringify(e.dataset):void 0,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=[" ",`
`,"\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 b{constructor(e){this.config=this.mergeConfig(e,q),this.logger=d(this.config.logLevel),this.namespace=e.namespace||"default",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new M(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,200,this.logger,this.namespace),u()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new j(this.config.cookieDomain),this.config.autocapture&&C.enabledForProject(this.config.key)&&!this.config.disableAutocaptureListenerRegistration&&(this.autoCapture=new C(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=w.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new we(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new be(this)),this.setupPageLeaveTracking()}mergeConfig(e,t){const i=JSON.parse(JSON.stringify(e));let s={...t,...i};return Object.keys(t).forEach(r=>{v(t[r])&&(s[r]=this.mergeConfig(e[r],t[r]))}),s}init(e){this.config={...this.config,...e},this.logger=d(this.config.logLevel),this.namespace=e.namespace||this.namespace,this.transport=this.initializeTransport(e),this.persistence=this.initializePersistence(),this.retryQueue=new M(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,250,this.logger,this.namespace),u()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client reinitialized for namespace: ${this.namespace}`)}manageCrossDomainLinking(){if(!this.config.crossDomainLinking||!this.config.domains)return;const e=this.config.domains.split(",").map(i=>i.trim()),t=this.config.cookieName||`__eventn_id_${this.config.key}`;document.addEventListener("click",i=>{var c;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=(c=this.cookieManager)==null?void 0:c.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(!u())return new Ee(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 ke(e.trackingHost||t,e,this.logger);if(e.forceUseFetch&&s)return new z(e.trackingHost||t,e,this.logger);if(i)return new ve(e.trackingHost||t,e,this.logger);if(s)return new z(e.trackingHost||t,e,this.logger);throw new Error("No suitable transport method available")}initializePersistence(){return this.config.disableEventPersistence||!u()?new _e:new K(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var i,s;if(!u())return x();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 c=new URLSearchParams(window.location.search).get("_um"),a=window.location.hash.substring(1).split("~"),h=a.length>1?a[1]:void 0;t=c||h||x()}t||(t=x());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(!v(e))throw new Error("User data must be an object");if(e.email&&!de(e.email))throw new Error("Invalid email provided");if(!e.id||!F(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(me()){this.logger.debug("Tracking disabled due to um_exclusion setting");return}if(!F(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(!v(e))throw new Error("Event payload must be an object");this.track("raw",e)}async group(e,t=!1){if(!v(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")||{},c=this.persistence.get(`props_${e}`)||{};let l=t||{};const a={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,...c};if(e==="$autocapture"){const h=this.processAutocaptureAttributes(t||{});a.autocapture_attributes=h}else e!=="user_identify"&&e!=="group"&&(Array.isArray(this.config.propertyBlacklist)&&this.config.propertyBlacklist.forEach(h=>{delete l[h]}),a.event_attributes=l);return u()&&(a.referer=document.referrer,a.url=window.location.href,a.page_title=document.title,a.doc_path=window.location.pathname,a.doc_host=window.location.hostname,a.doc_search=window.location.search,a.screen_resolution=`${window.screen.width}x${window.screen.height}`,a.vp_size=`${window.innerWidth}x${window.innerHeight}`,a.user_agent=navigator.userAgent,a.user_language=navigator.language,a.doc_encoding=document.characterSet,a.utm=this.getUtmParams()),a}processAutocaptureAttributes(e){let t={};const i=e.$elements||[];return i.length&&(t={...i[0]}),t.el_text=t.$el_text||"",t.event_type=e.$event_type||"",["$ce_version","$event_type","$initial_referrer","$initial_referring_domain","$referrer","$referring_domain","$elements"].forEach(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(u()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=ge(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(){u()?this.track("pageview",{url:window.location.href,referrer:document.referrer,title:document.title},!0):this.logger.warn("Pageview tracking is not available in server-side environments")}setupPageLeaveTracking(){if(!u())return;let e=!1,t=!1;const i=()=>{!e&&!t&&(e=!0,this.track("$pageleave",{url:window.location.href,referrer:document.referrer,title:document.title}))};window.addEventListener("beforeunload",r=>{t=!0,setTimeout(()=>{t=!1},100)}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&!t&&i()});const 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(!v(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 X(){return typeof window<"u"&&typeof window.define=="function"&&window.define.amd}function Pe(){return X()?window.define:void 0}const Ae="__USERMAVEN_AUTOCAPTURE_INITIALIZED__";function E(n){const e=JSON.parse(JSON.stringify(n)),t=R(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=`${Ae}${s}`;return u()&&i.autocapture&&window[r]&&(console.warn("Usermaven: Autocapture already initialized in another instance, skipping duplicate initialization."),i.disableAutocaptureListenerRegistration=!0),u()&&i.autocapture&&!i.disableAutocaptureListenerRegistration&&(window[r]=!0),new b(i)}function Se(n){var s;const e={key:n.getAttribute("data-key")||void 0,trackingHost:n.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:pe(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(e),i=e.namespace||"usermaven";return u()&&t.pageview(),$e(i,t),t}function $e(n,e){let t=!1;const i=[],s=[];function r(){for(;i.length>0;){const a=i.shift();a&&window[n].apply(null,a)}}function o(){s.forEach(a=>a()),s.length=0}window[n]=function(...a){const h=a[0];if(h==="onLoad"){typeof a[1]=="function"&&(t?a[1]():s.push(a[1]));return}if(!t){i.push(a);return}if(typeof e[h]=="function")return e[h].apply(e,a.slice(1));console.error(`Method ${h} not found on UsermavenClient`)};const c=`${n}Q`,l=window[c]||[];for(window[c]=l,l.push=function(...a){return window[n].apply(null,a),Array.prototype.push.apply(this,a)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${n} is ready`)},0);l.length>0;){const a=l.shift();a&&i.push(a)}}let B=!1,H=null;if(u()){const n=Pe();n&&n("usermaven",[],function(){return{usermavenClient:E,UsermavenClient:b,LogLevel:f,getScriptTagClient:()=>H}}),typeof window<"u"&&(window.usermavenClient=E,window.UsermavenClient=b,window.usermavenScriptTagClient=()=>H),function(e,t){const i=e.currentScript;function s(){return B||!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"),H=Se(i),B=!0)}typeof t<"u"&&i&&(e.readyState==="loading"?e.addEventListener("DOMContentLoaded",r):r())}(document,window)}typeof module<"u"&&module.exports&&!X()&&(module.exports={usermavenClient:E,UsermavenClient:b,Config:void 0,UserProps:void 0,EventPayload:void 0,LogLevel:f,ClientProperties:void 0});exports.LogLevel=f;exports.UsermavenClient=b;exports.usermavenClient=E;

@@ -30,3 +30,3 @@ var p = /* @__PURE__ */ ((n) => (n[n.DEBUG = 0] = "DEBUG", n[n.INFO = 1] = "INFO", n[n.WARN = 2] = "WARN", n[n.ERROR = 3] = "ERROR", n))(p || {});

formTracking: !1,
autoPageview: !1,
autoPageview: !0,
disableEventPersistence: !1,

@@ -1286,3 +1286,3 @@ gaHook: !1,

const t = C(e), i = e.namespace || "usermaven";
return u() && e.autoPageview !== !1 && t.pageview(), Se(i, t), t;
return u() && t.pageview(), Se(i, t), t;
}

@@ -1289,0 +1289,0 @@ function Se(n, e) {

{
"name": "@usermaven/sdk-js",
"version": "1.5.6",
"version": "1.5.7-rc.102",
"description": "Usermaven JavaScript SDK",

@@ -5,0 +5,0 @@ "main": "dist/lib.js",