@usermaven/sdk-js 1.5.4-rc.96 → 1.5.5-rc.97
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -0
- package/dist/lib.js +2 -2
- package/dist/usermaven.cjs.js +2 -2
- package/dist/usermaven.es.js +181 -151
- package/dist/utils/amd-detector.d.ts +2 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -159,6 +159,38 @@ To set up the project for development:
|
|
|
159
159
|
3. Run tests: `npm test`
|
|
160
160
|
4. Build the project: `npm run build`
|
|
161
161
|
|
|
162
|
+
## Testing
|
|
163
|
+
|
|
164
|
+
### Unit Tests
|
|
165
|
+
|
|
166
|
+
To run unit tests:
|
|
167
|
+
|
|
168
|
+
```bash
|
|
169
|
+
pnpm --filter @usermaven/sdk-js test
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
### E2E Tests
|
|
173
|
+
|
|
174
|
+
To run end-to-end tests with a specific browser (e.g., Chrome):
|
|
175
|
+
|
|
176
|
+
```bash
|
|
177
|
+
pnpm --filter @usermaven/sdk-js test:e2e --project=chromium
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
You can replace `chromium` with other browsers like `firefox` or `webkit` to test on different browsers.
|
|
181
|
+
|
|
182
|
+
To run E2E tests with a UI for debugging:
|
|
183
|
+
|
|
184
|
+
```bash
|
|
185
|
+
pnpm --filter @usermaven/sdk-js test:e2e:ui
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
To view the Playwright report after running tests:
|
|
189
|
+
|
|
190
|
+
```bash
|
|
191
|
+
pnpm exec playwright show-report
|
|
192
|
+
```
|
|
193
|
+
|
|
162
194
|
## Contributing
|
|
163
195
|
|
|
164
196
|
Contributions are welcome! Please read our contributing guidelines and code of conduct before submitting pull requests.
|
package/dist/lib.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(f,g){typeof exports=="object"&&typeof module<"u"?g(exports):typeof define=="function"&&define.amd?define(["exports"],g):(f=typeof globalThis<"u"?globalThis:f||self,g(f.Usermaven={}))})(this,function(f){"use strict";var g=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i))(g||{});class X{constructor(e){this.level=e}debug(e,...t){this.level<=0&&console.debug("[Usermaven Debug]:",e,...t)}info(e,...t){this.level<=1&&console.info("[Usermaven Info]:",e,...t)}warn(e,...t){this.level<=2&&console.warn("[Usermaven Warning]:",e,...t)}error(e,...t){this.level<=3&&console.error("[Usermaven Error]:",e,...t)}}function d(i=0){return new X(i)}const L={logLevel:g.ERROR,useBeaconApi:!1,forceUseFetch:!1,trackingHost:"t.usermaven.com",autocapture:!1,rageClick:!1,formTracking:!1,autoPageview:!1,disableEventPersistence:!1,gaHook:!1,segmentHook:!1,randomizeUrl:!1,capture3rdPartyCookies:["_ga","_fbp","_ym_uid","ajs_user_id","ajs_anonymous_id"],idMethod:"cookie",ipPolicy:"keep",cookiePolicy:"keep",minSendTimeout:0,maxSendTimeout:2e3,maxSendAttempts:4,propertiesStringMaxLength:null,propertyBlacklist:[],crossDomainLinking:!0,maskAllText:!1,maskAllElementAttributes:!1};class K{constructor(e){this.domain=e,this.cookieDomain=this.getCookieDomain()}set(e,t,s=365,n=!0,r=!1){const o=new Date;o.setTime(o.getTime()+s*24*60*60*1e3);const c=`expires=${o.toUTCString()}`,l=n?"; Secure":"",a=r?"; HttpOnly":"";document.cookie=`${e}=${t};${c};path=/;domain=${this.cookieDomain}${l}${a}`}get(e){const t=e+"=",s=document.cookie.split(";");for(let n=0;n<s.length;n++){let r=s[n].trim();if(r.indexOf(t)===0)return decodeURIComponent(r.substring(t.length))}return null}delete(e,t="/"){document.cookie=`${e}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${t};domain=${this.cookieDomain}`}getCookieDomain(){return typeof window>"u"||this.domain?this.domain||"":this.extractRoot(window.location.hostname)}extractRoot(e){if(this.isIpAddress(e)||e==="localhost")return e;let t=this.extractTopLevelDomain(e);return t||(t=this.extractRootDomain(e)),"."+t}isIpAddress(e){const t=e.split(".");return t.length===4&&t.every(s=>!isNaN(Number(s)))}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 s=t.split("."),n=s.length;return n>2&&(s[n-1].length==2?(t=s[n-2]+"."+s[n-1],s[n-2].length==2&&(t=s[n-3]+"."+t)):t=s[n-2]+"."+s[n-1]),t}extractTopLevelDomain(e){const t=/[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i,s=e.match(t);return s?s[0]:""}}const G=Object.prototype.hasOwnProperty,P=Array.prototype.forEach,A={};function Y(i,e,t){if(Array.isArray(i)){if(P&&i.forEach===P)i.forEach(e,t);else if("length"in i&&i.length===+i.length){for(let s=0,n=i.length;s<n;s++)if(s in i&&e.call(t,i[s],s)===A)return}}}const x=function(i){return i.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},Z=function(i){for(const e in i)typeof i[e]=="function"&&(i[e]=i[e].bind(i))};function m(i,e,t){if(i!=null){if(P&&Array.isArray(i)&&i.forEach===P)i.forEach(e,t);else if("length"in i&&i.length===+i.length){for(let s=0,n=i.length;s<n;s++)if(s in i&&e.call(t,i[s],s)===A)return}else for(const s in i)if(G.call(i,s)&&e.call(t,i[s],s)===A)return}}const j=function(i,...e){return Y(e,function(t){for(const s in t)t[s]!==void 0&&(i[s]=t[s])}),i};function v(i,e){return i.indexOf(e)!==-1}const ee=function(i){try{return/^\s*\bfunction\b/.test(i)}catch{return!1}},te=function(i){return i===void 0},w=function(){const i=function(s,n,r,o,c){if(!s){d().error("No valid element provided to register_event");return}if(s.addEventListener&&!o)s.addEventListener(n,r,!!c);else{const l="on"+n,a=s[l];s[l]=e(s,r,a)}};function e(s,n,r){return function(o){if(o=o||t(window.event),!o)return;let c=!0,l;ee(r)&&(l=r(o));const a=n.call(s,o);return(l===!1||a===!1)&&(c=!1),c}}function t(s){return s&&(s.preventDefault=t.preventDefault,s.stopPropagation=t.stopPropagation),s}return t.preventDefault=function(){this.returnValue=!1},t.stopPropagation=function(){this.cancelBubble=!0},i}(),ie=function(i){return function(...e){try{return i.apply(this,e)}catch(t){d().error("Implementation error. Please turn on debug and contact support@usermaven.com.",t)}}},I=function(i){for(const e in i)typeof i[e]=="function"&&(i[e]=ie(i[e]))};function D(i){for(let e in i)(i[e]===""||i[e]===null||i[e]===void 0||typeof i[e]=="object"&&Object.keys(i[e]).length===0)&&delete i[e];return i}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 y(i=5){const e=new Uint8Array(i);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").slice(0,i)}function se(i){return i.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function H(i){return typeof i!="object"||i===null?i:Array.isArray(i)?i.map(H):Object.keys(i).reduce((e,t)=>{const s=se(t);return e[s]=H(i[t]),e},{})}function E(i){switch(typeof i.className){case"string":return i.className;case"object":return("baseVal"in i.className?i.className.baseVal:null)||i.getAttribute("class")||"";default:return""}}function U(i){let e="";return O(i)&&!B(i)&&i.childNodes&&i.childNodes.length&&m(i.childNodes,function(t){z(t)&&t.textContent&&(e+=x(t.textContent).split(/(\s+)/).filter(S).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),x(e)}function F(i){return!!i&&i.nodeType===1}function p(i,e){return!!i&&!!i.tagName&&i.tagName.toLowerCase()===e.toLowerCase()}function z(i){return!!i&&i.nodeType===3}function N(i){return!!i&&i.nodeType===11}const $=["a","button","form","input","select","textarea","label"];function ne(i,e){if(!i||p(i,"html")||!F(i))return!1;let t=i;for(;t&&!p(t,"body");){if(t.classList&&t.classList.contains("um-no-capture"))return!1;t.parentNode&&N(t.parentNode)?t=t.parentNode.host:t=t.parentNode}let s=!1;for(t=i;t&&!p(t,"body");){if(t.parentNode&&N(t.parentNode)){t=t.parentNode.host,t&&$.indexOf(t.tagName.toLowerCase())>-1&&(s=!0);continue}const o=t.parentNode;if(!o)break;if($.indexOf(o.tagName.toLowerCase())>-1)s=!0;else{const c=window.getComputedStyle(o);c&&c.getPropertyValue("cursor")==="pointer"&&(s=!0)}t=o}const n=window.getComputedStyle(i);if(n&&n.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;const r=i.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 s?e.type==="click":e.type==="click"&&($.indexOf(r)>-1||i.getAttribute("contenteditable")==="true")}}function O(i){for(let s=i;s.parentNode&&!p(s,"body");s=s.parentNode){const n=E(s).split(" ");if(v(n,"ph-sensitive")||v(n,"ph-no-capture"))return!1}if(v(E(i).split(" "),"ph-include"))return!0;const e=i.type||"";if(typeof e=="string")switch(e.toLowerCase()){case"hidden":return!1;case"password":return!1}const t=i.name||i.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 B(i){const e=["button","checkbox","submit","reset"];return!!(p(i,"input")&&!e.includes(i.type)||p(i,"select")||p(i,"textarea")||i.getAttribute("contenteditable")==="true")}function S(i){return!(i===null||te(i)||typeof i=="string"&&(i=x(i),/^(?:(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((i||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(i)))}function re(i){return typeof i=="string"?i.substring(0,10)==="_ngcontent"||i.substring(0,7)==="_nghost":!1}function R(){return y(10)}function oe(i){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(i).toLowerCase())}function ae(i,e){let t;return function(...s){const n=()=>{clearTimeout(t),i(...s)};clearTimeout(t),t=setTimeout(n,e)}}function ce(i){const e={},t=i.replace(/^\?/,"").split("&");for(let s=0;s<t.length;s++){const n=t[s].split("=");n[0]!==""&&(e[decodeURIComponent(n[0])]=decodeURIComponent(n[1]||""))}return e}function M(i){return typeof i=="string"||i instanceof String}function _(i){return i!==null&&typeof i=="object"&&i.constructor===Object}function le(i){if(i===null)return g.ERROR;const e=i.toUpperCase(),t=g[e];return t||t===0?t:g.ERROR}const ue=()=>{let i="false";return typeof window<"u"&&window.localStorage&&(i=localStorage.getItem("um_exclusion")),!(i==null||i==="false")};class he{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=ae(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(),s=this.getScrollDistance(),n=t-e;return Math.min(100,Math.floor(s/n*100))}getWindowHeight(){return window.innerHeight||this.documentElement.clientHeight||document.body.clientHeight||0}getDocumentHeight(){return Math.max(document.body.scrollHeight||0,this.documentElement.scrollHeight||0,document.body.offsetHeight||0,this.documentElement.offsetHeight||0,document.body.clientHeight||0,this.documentElement.clientHeight||0)}getScrollDistance(){return window.pageYOffset||this.documentElement.scrollTop||document.body.scrollTop||0}checkMilestones(e){this.milestones.filter(s=>e>=s).forEach(s=>{this.send(),this.milestones=this.milestones.filter(n=>n!==s)})}}const T=class T{constructor(e,t,s=d()){this.logger=s,this.scrollDepth=null,this.customProperties=[],this.client=e,this.options=t,this.scrollDepth=new he(e),Z(this),I(this)}init(){if(!(document&&document.body)){this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."),setTimeout(()=>this.init(),500);return}this.addDomEventHandlers()}addDomEventHandlers(){const e=t=>{t=t||window.event,this.captureEvent(t)};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 s,n;let t=this.getEventTarget(e);if(z(t)&&(t=t.parentNode||null),e.type==="scroll")return(s=this.scrollDepth)==null||s.track(),!0;if(e.type==="visibilitychange"&&document.visibilityState==="hidden"||e.type==="popstate")return this.isPageRefresh()||(n=this.scrollDepth)==null||n.send(),!0;if(t&&ne(t,e)){const r=[t];let o=t;for(;o.parentNode&&!p(o,"body");){if(N(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,b=>{const ve=O(b);b.tagName.toLowerCase()==="a"&&(l=b.getAttribute("href"),l=ve&&S(l)&&l);const _e=E(b).split(" ");v(_e,"ph-no-capture")&&(a=!0),c.push(this.getPropertiesFromElement(b,this.options.maskAllElementAttributes??!1,this.options.maskAllText??!1))}),this.options.maskAllText||(c[0].$el_text=U(t)),l&&(c[0].attr__href=l),a)return!1;const h=j(this.getDefaultProperties(e.type),{$elements:c},this.getCustomProperties(r));return this.client.track("$autocapture",h),!0}}getCustomProperties(e){const t={};return m(this.customProperties,s=>{m(s.event_selectors,n=>{const r=document.querySelectorAll(n);m(r,o=>{v(e,o)&&O(o)&&(t[s.name]=this.extractCustomPropertyValue(s))})})}),t}extractCustomPropertyValue(e){const t=[];return m(document.querySelectorAll(e.css_selector),function(s){let n;["input","select"].indexOf(s.tagName.toLowerCase())>-1?n=s.value:s.textContent&&(n=s.textContent),S(n)&&t.push(n)}),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,s){const n=e.tagName.toLowerCase(),r={tag_name:n};$.indexOf(n)>-1&&!s&&(r.$el_text=U(e));const o=E(e);o.length>0&&(r.classes=o.split(" ").filter(function(h){return h!==""})),m(e.attributes,function(h){B(e)&&["name","id","class"].indexOf(h.name)===-1||!t&&S(h.value)&&!re(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&&!F(t));return t}}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}encodeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}static enabledForProject(e,t=10,s=10){if(!e)return!1;let n=0;for(let r=0;r<e.length;r++)n+=e.charCodeAt(r);return n%t<s}};T.FORCE_CAPTURE_ATTR="data-um-force-capture",T.PREVENT_CAPTURE_ATTR="data-um-no-capture";let C=T;class de{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 ge{constructor(e,t,s=d()){this.trackingHost=e,this.logger=s,this.config=t}async send(e){const t=this.config.key,s=this.constructUrl(t),n=new Blob([JSON.stringify(e)],{type:"application/json"});if(navigator.sendBeacon(s,n))this.logger.debug(`Successfully queued ${e.length} event(s) via Beacon API`);else throw new Error("Failed to queue events via Beacon API")}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",s=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${y()}?p_${y()}=${e}${t}${s}`:`${this.trackingHost}${n}?token=${e}${t}${s}`}}class q{constructor(e,t,s=d()){this.trackingHost=e,this.logger=s,this.config=t}async send(e){const t=this.config.key,s=this.constructUrl(t),n=JSON.stringify(e),r={"Content-Type":"application/json",...this.getCustomHeaders()},o=await fetch(s,{method:"POST",headers:r,body:n});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);this.logger.debug(`Successfully sent ${e.length} event(s)`),this.postHandle(o.status,await o.text())}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",s=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${y()}?p_${y()}=${e}${t}${s}`:`${this.trackingHost}${n}?token=${e}${t}${s}`}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 fe{constructor(e,t,s=d()){this.trackingHost=e,this.logger=s,this.config=t}send(e){return new Promise((t,s)=>{const n=new XMLHttpRequest,r=this.config.key,o=this.constructUrl(r);n.open("POST",o,!0),n.setRequestHeader("Content-Type","application/json");const c=this.getCustomHeaders();Object.keys(c).forEach(l=>{n.setRequestHeader(l,c[l])}),n.onload=()=>{n.status>=200&&n.status<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),t()):s(new Error(`HTTP error! status: ${n.status}`))},n.onerror=()=>{s(new Error("Network error"))},n.send(JSON.stringify(e))})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",s=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${y()}?p_${y()}=${e}${t}${s}`:`${this.trackingHost}${n}?token=${e}${t}${s}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}postHandle(e,t){this.logger.debug(`Response received. Status: ${e}, Body: ${t}`)}}class V{constructor(e,t){this.storage={},this.prefix=`usermaven_${e}_`,this.load(),this.logger=t||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 pe{constructor(){this.storage={}}set(e,t){this.storage[e]=t}get(e){return this.storage[e]}remove(e){delete this.storage[e]}save(){}clear(){this.storage={}}}class J{constructor(e,t=3,s=1e3,n=10,r=1e3,o=d(),c="default"){this.transport=e,this.maxRetries=t,this.retryInterval=s,this.batchSize=n,this.batchInterval=r,this.logger=o,this.queue=[],this.processing=!1,this.batchTimeoutId=null,this.isOnline=!0,this.persistence=new V(`offline_queue_${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(s=>s.payload);try{await this.transport.send(t),this.logger.debug(`Successfully sent batch of ${e.length} payloads`),u()&&this.saveQueueToStorage()}catch(s){this.logger.error("Failed to send batch",s),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 me{constructor(e){this.clicks=[],this.threshold=3,this.timeWindow=2e3,this.distanceThreshold=30,this.client=e,this.initializeEventListener(),I(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,s){const n={x:e,y:t,timestamp:s};this.clicks.push(n),this.clicks=this.clicks.filter(r=>s-r.timestamp<this.timeWindow),this.clicks.length>=this.threshold&&this.checkRageClick()}checkRageClick(){const e=this.clicks[0],s=(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(s)}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 ye{constructor(e,t,s=d()){this.trackingHost=e,this.logger=s,this.config=t}async send(e){const t=this.config.key,s=new(void 0)(this.constructUrl(t)),n={hostname:s.hostname,port:443,path:`${s.pathname}${s.search}`,method:"POST",headers:{"Content-Type":"application/json",...this.getCustomHeaders()}};return new Promise((r,o)=>{const c=(void 0)(n,l=>{l.on("data",a=>{}),l.on("end",()=>{const a=l.statusCode||0;a>=200&&a<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${a}`))})});c.on("error",l=>{o(l)}),c.write(JSON.stringify(e)),c.end()})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",s=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"";return`${this.trackingHost}/api/v1/s2s/event?token=${e}${t}${s}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}}class k{constructor(e,t="all",s={}){this.instance=e,this.trackingType=t,this.options=s,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,s=this._getFormDetails(t);this.instance.track("$form",D(s)),this.options.trackFieldChanges&&this.trackFieldChanges(t)}trackFieldChanges(e){e.querySelectorAll("input, select, textarea").forEach(s=>{s.addEventListener("change",n=>{const r=this._getFieldProps(n.target,0);this.instance.track("$form_field_change",D(r))})})}static getInstance(e,t="all",s={}){return k.instance||(k.instance=new k(e,t,s)),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)},s=e.querySelectorAll("input, select, textarea");return Array.from(s).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 s=Object.keys(e.dataset).length?JSON.stringify(e.dataset):void 0,n=this.getSafeText(e);return{[`field_${t+1}_tag`]:e.tagName.toLowerCase(),[`field_${t+1}_type`]:e instanceof HTMLInputElement?e.type:void 0,[`field_${t+1}_data_attributes`]:s,[`field_${t+1}_id`]:e.id,[`field_${t+1}_value`]:n,[`field_${t+1}_class`]:e.className,[`field_${t+1}_name`]:e.name,[`field_${t+1}_attributes`]:this._getElementAttributes(e)}}_getElementAttributes(e){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(n=>n.nodeType===Node.TEXT_NODE).map(n=>n.textContent).join(""):t=e.textContent||"",this._scrubPotentiallySensitiveValues(t)}_scrubPotentiallySensitiveValues(e){return this._shouldCaptureValue(e)?e:"<redacted>"}_shouldCaptureValue(e){return!(this._isNullish(e)||this._isString(e)&&(e=this._trim(e),/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((e||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(e)))}_isNullish(e){return e==null}_isString(e){return typeof e=="string"||e instanceof String}_trim(e){if(typeof String.prototype.trim=="function")return e.trim();let t=0,s=e.length-1;const n=[" ",`
|
|
2
|
-
`,"\r"," ","\f","\v"," "," "," "," "," "," "," "," "," "," "," "," "," ","\u2028","\u2029"," "," "," "].join("");for(;t<=s&&n.indexOf(e[t])>-1;)t++;for(;s>=t&&n.indexOf(e[s])>-1;)s--;return e.slice(t,s+1)}}class Q{constructor(e){this.config=this.mergeConfig(e,L),this.logger=d(this.config.logLevel),this.namespace=e.namespace||"default",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new J(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,200,this.logger,this.namespace),u()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new K(this.config.cookieDomain),this.config.autocapture&&C.enabledForProject(this.config.key)&&(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=k.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new de(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new me(this)),this.setupPageLeaveTracking()}mergeConfig(e,t){const s=JSON.parse(JSON.stringify(e));let n={...t,...s};return Object.keys(t).forEach(r=>{_(t[r])&&(n[r]=this.mergeConfig(e[r],t[r]))}),n}init(e){this.config={...this.config,...e},this.logger=d(this.config.logLevel),this.namespace=e.namespace||this.namespace,this.transport=this.initializeTransport(e),this.persistence=this.initializePersistence(),this.retryQueue=new J(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,250,this.logger,this.namespace),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(s=>s.trim()),t=this.config.cookieName||`__eventn_id_${this.config.key}`;document.addEventListener("click",s=>{var c;const n=this.findClosestLink(s.target);if(!n)return;const r=n.getAttribute("href");if(!r||!r.startsWith("http"))return;const o=new URL(r);if(o.hostname!==window.location.hostname&&e.includes(o.hostname)){const l=(c=this.cookieManager)==null?void 0:c.get(t);l&&(o.searchParams.append("_um",l),n.setAttribute("href",o.toString()))}}),this.logger.debug("Cross-domain linking initialized")}findClosestLink(e){for(;e&&e.tagName!=="A";)e=e.parentElement;return e}initializeTransport(e){const t="https://events.usermaven.com";if(!u())return new ye(e.trackingHost||t,e);const s="XMLHttpRequest"in window,n=typeof fetch<"u",r=typeof navigator<"u"&&"sendBeacon"in navigator;if(e.useBeaconApi&&r)return new ge(e.trackingHost||t,e,this.logger);if(e.forceUseFetch&&n)return new q(e.trackingHost||t,e,this.logger);if(s)return new fe(e.trackingHost||t,e,this.logger);if(n)return new q(e.trackingHost||t,e,this.logger);throw new Error("No suitable transport method available")}initializePersistence(){return this.config.disableEventPersistence||!u()?new pe:new V(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var s,n;if(!u())return R();if(this.config.privacyPolicy==="strict"||this.config.cookiePolicy==="strict")return"";const e=this.config.cookieName||`__eventn_id_${this.config.key}`;let t=(s=this.cookieManager)==null?void 0:s.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||R()}t||(t=R());const r=365*10;(n=this.cookieManager)==null||n.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&&!oe(e.email))throw new Error("Invalid email provided");if(!e.id||!M(e.id))throw new Error("User ID must be a string");const s=e.id;if(this.persistence.set("userId",s),this.persistence.set("userProps",e),!t){const n={...e,anonymous_id:this.anonymousId};await this.track("user_identify",n)}this.logger.info("User identified:",e)}track(e,t,s=!1){this.trackInternal(e,t,s)}trackInternal(e,t,s=!1){if(ue()){this.logger.debug("Tracking disabled due to um_exclusion setting");return}if(!M(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(s){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 s=this.persistence.get("userProps")||{},n=this.persistence.get("companyProps")||(s==null?void 0:s.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,...s},...n&&{company:n},ids:this.getThirdPartyIds(),utc_time:new Date().toISOString(),local_tz_offset:new Date().getTimezoneOffset(),api_key:this.config.key,src:"usermaven",event_type:e,namespace:this.namespace,...o,...c};if(e==="$autocapture"){const 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 s=e.$elements||[];return s.length&&(t={...s[0]}),t.el_text=t.$el_text||"",t.event_type=e.$event_type||"",["$ce_version","$event_type","$initial_referrer","$initial_referring_domain","$referrer","$referring_domain","$elements"].forEach(n=>{delete t[n]}),delete t.$el_text,delete t.nth_child,delete t.nth_of_type,t}getCookie(e){var t;return((t=this.cookieManager)==null?void 0:t.get(e))||null}getThirdPartyIds(){const e={};if(u()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=ce(window.location.search);return["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(n=>{t[n]&&(e[n.replace("utm_","")]=t[n])}),e}pageview(){u()?this.track("pageview",{url:window.location.href,referrer:document.referrer,title:document.title},!0):this.logger.warn("Pageview tracking is not available in server-side environments")}setupPageLeaveTracking(){if(!u())return;let e=!1,t=!1;const s=()=>{!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&&s()});const n=history.pushState;history.pushState=function(){return s(),n.apply(this,arguments)},window.addEventListener("popstate",s)}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 s=t==null?void 0:t.eventType,n=(t==null?void 0:t.persist)??!0;if(s){let r=this.persistence.get(`props_${s}`)||{};r={...r,...e},this.persistence.set(`props_${s}`,r)}else{let r=this.persistence.get("global_props")||{};r={...r,...e},this.persistence.set("global_props",r)}n&&this.persistence.save(),this.logger.debug("Properties set",{properties:e,eventType:s||"global",persist:n})}setUserId(e){this.persistence.set("userId",e);let t=this.persistence.get("userProps")||{};t.id=e,this.persistence.set("userProps",t),this.persistence.save()}unset(e,t){const s=t==null?void 0:t.eventType,n=(t==null?void 0:t.persist)??!0;if(s){let r=this.persistence.get(`props_${s}`)||{};delete r[e],this.persistence.set(`props_${s}`,r)}else{let r=this.persistence.get("global_props")||{};delete r[e],this.persistence.set("global_props",r)}n&&this.persistence.save(),this.logger.debug(`Property unset: ${e}`,`Event type: ${s||"global"}`)}}function W(i){const e=JSON.parse(JSON.stringify(i)),t=H(e),s={...L,...t};if(!s.key)throw new Error("API key is required!");if(!s.trackingHost)throw new Error("Tracking host is required!");return new Q(s)}function we(i){var n;const e={key:i.getAttribute("data-key")||void 0,trackingHost:i.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:le(i.getAttribute("data-log-level")),autocapture:i.getAttribute("data-autocapture")==="true",formTracking:i.getAttribute("data-form-tracking")==="false"?!1:i.getAttribute("data-form-tracking")==="true"?"all":i.getAttribute("data-form-tracking"),autoPageview:i.getAttribute("data-auto-pageview")==="true",useBeaconApi:i.getAttribute("data-use-beacon-api")==="true",forceUseFetch:i.getAttribute("data-force-use-fetch")==="true",gaHook:i.getAttribute("data-ga-hook")==="true",segmentHook:i.getAttribute("data-segment-hook")==="true",randomizeUrl:i.getAttribute("data-randomize-url")==="true",capture3rdPartyCookies:i.getAttribute("data-capture-3rd-party-cookies")==="false"?!1:void 0,idMethod:i.getAttribute("data-id-method")||void 0,privacyPolicy:i.getAttribute("data-privacy-policy")==="strict"?"strict":void 0,ipPolicy:i.getAttribute("data-ip-policy")||void 0,cookiePolicy:i.getAttribute("data-cookie-policy")||void 0,minSendTimeout:parseInt(i.getAttribute("data-min-send-timeout")||"",10)||void 0,maxSendTimeout:parseInt(i.getAttribute("data-max-send-timeout")||"",10)||void 0,maxSendAttempts:parseInt(i.getAttribute("data-max-send-attempts")||"",10)||void 0,propertiesStringMaxLength:parseInt(i.getAttribute("data-properties-string-max-length")||"",10)||null,propertyBlacklist:((n=i.getAttribute("data-property-blacklist"))==null?void 0:n.split(","))||void 0,exclude:i.getAttribute("data-exclude")||void 0,namespace:i.getAttribute("data-namespace")||void 0,crossDomainLinking:i.getAttribute("data-cross-domain-linking")!=="false",domains:i.getAttribute("data-domains")||void 0,maskAllText:i.getAttribute("data-mask-all-text")==="true",maskAllElementAttributes:i.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=W(e),s=e.namespace||"usermaven";u()&&t.pageview(),ke(s,t)}function ke(i,e){let t=!1;const s=[],n=[];function r(){for(;s.length>0;){const a=s.shift();a&&window[i].apply(null,a)}}function o(){n.forEach(a=>a()),n.length=0}window[i]=function(...a){const h=a[0];if(h==="onLoad"){typeof a[1]=="function"&&(t?a[1]():n.push(a[1]));return}if(!t){s.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=`${i}Q`,l=window[c]||[];for(window[c]=l,l.push=function(...a){return window[i].apply(null,a),Array.prototype.push.apply(this,a)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${i} is ready`)},0);l.length>0;){const a=l.shift();a&&s.push(a)}}u()&&function(i,e){const t=i.currentScript;function s(){t&&t.src.includes("lib.js")&&we(t)}typeof e<"u"&&(i.readyState==="loading"?i.addEventListener("DOMContentLoaded",s):s())}(document,window),f.LogLevel=g,f.UsermavenClient=Q,f.usermavenClient=W,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(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=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i))(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(i=0){return new Y(i)}const U={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 Z{constructor(e){this.domain=e,this.cookieDomain=this.getCookieDomain()}set(e,t,n=365,s=!0,r=!1){const o=new Date;o.setTime(o.getTime()+n*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+"=",n=document.cookie.split(";");for(let s=0;s<n.length;s++){let r=n[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(n=>!isNaN(Number(n)))}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 n=t.split("."),s=n.length;return s>2&&(n[s-1].length==2?(t=n[s-2]+"."+n[s-1],n[s-2].length==2&&(t=n[s-3]+"."+t)):t=n[s-2]+"."+n[s-1]),t}extractTopLevelDomain(e){const t=/[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i,n=e.match(t);return n?n[0]:""}}const j=Object.prototype.hasOwnProperty,$=Array.prototype.forEach,H={};function ee(i,e,t){if(Array.isArray(i)){if($&&i.forEach===$)i.forEach(e,t);else if("length"in i&&i.length===+i.length){for(let n=0,s=i.length;n<s;n++)if(n in i&&e.call(t,i[n],n)===H)return}}}const N=function(i){return i.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},te=function(i){for(const e in i)typeof i[e]=="function"&&(i[e]=i[e].bind(i))};function m(i,e,t){if(i!=null){if($&&Array.isArray(i)&&i.forEach===$)i.forEach(e,t);else if("length"in i&&i.length===+i.length){for(let n=0,s=i.length;n<s;n++)if(n in i&&e.call(t,i[n],n)===H)return}else for(const n in i)if(j.call(i,n)&&e.call(t,i[n],n)===H)return}}const ie=function(i,...e){return ee(e,function(t){for(const n in t)t[n]!==void 0&&(i[n]=t[n])}),i};function v(i,e){return i.indexOf(e)!==-1}const ne=function(i){try{return/^\s*\bfunction\b/.test(i)}catch{return!1}},se=function(i){return i===void 0},w=function(){const i=function(n,s,r,o,c){if(!n){f().error("No valid element provided to register_event");return}if(n.addEventListener&&!o)n.addEventListener(s,r,!!c);else{const l="on"+s,a=n[l];n[l]=e(n,r,a)}};function e(n,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(n,o);return(l===!1||a===!1)&&(c=!1),c}}function t(n){return n&&(n.preventDefault=t.preventDefault,n.stopPropagation=t.stopPropagation),n}return t.preventDefault=function(){this.returnValue=!1},t.stopPropagation=function(){this.cancelBubble=!0},i}(),re=function(i){return function(...e){try{return i.apply(this,e)}catch(t){f().error("Implementation error. Please turn on debug and contact support@usermaven.com.",t)}}},F=function(i){for(const e in i)typeof i[e]=="function"&&(i[e]=re(i[e]))};function z(i){for(let e in i)(i[e]===""||i[e]===null||i[e]===void 0||typeof i[e]=="object"&&Object.keys(i[e]).length===0)&&delete i[e];return i}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(i=5){const e=new Uint8Array(i);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").slice(0,i)}function oe(i){return i.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function O(i){return typeof i!="object"||i===null?i:Array.isArray(i)?i.map(O):Object.keys(i).reduce((e,t)=>{const n=oe(t);return e[n]=O(i[t]),e},{})}function S(i){switch(typeof i.className){case"string":return i.className;case"object":return("baseVal"in i.className?i.className.baseVal:null)||i.getAttribute("class")||"";default:return""}}function M(i){let e="";return L(i)&&!V(i)&&i.childNodes&&i.childNodes.length&&m(i.childNodes,function(t){q(t)&&t.textContent&&(e+=N(t.textContent).split(/(\s+)/).filter(T).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),N(e)}function B(i){return!!i&&i.nodeType===1}function p(i,e){return!!i&&!!i.tagName&&i.tagName.toLowerCase()===e.toLowerCase()}function q(i){return!!i&&i.nodeType===3}function R(i){return!!i&&i.nodeType===11}const C=["a","button","form","input","select","textarea","label"];function ae(i,e){if(!i||p(i,"html")||!B(i))return!1;let t=i;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 n=!1;for(t=i;t&&!p(t,"body");){if(t.parentNode&&R(t.parentNode)){t=t.parentNode.host,t&&C.indexOf(t.tagName.toLowerCase())>-1&&(n=!0);continue}const o=t.parentNode;if(!o)break;if(C.indexOf(o.tagName.toLowerCase())>-1)n=!0;else{const c=window.getComputedStyle(o);c&&c.getPropertyValue("cursor")==="pointer"&&(n=!0)}t=o}const s=window.getComputedStyle(i);if(s&&s.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;const r=i.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 n?e.type==="click":e.type==="click"&&(C.indexOf(r)>-1||i.getAttribute("contenteditable")==="true")}}function L(i){for(let n=i;n.parentNode&&!p(n,"body");n=n.parentNode){const s=S(n).split(" ");if(v(s,"ph-sensitive")||v(s,"ph-no-capture"))return!1}if(v(S(i).split(" "),"ph-include"))return!0;const e=i.type||"";if(typeof e=="string")switch(e.toLowerCase()){case"hidden":return!1;case"password":return!1}const t=i.name||i.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(i){const e=["button","checkbox","submit","reset"];return!!(p(i,"input")&&!e.includes(i.type)||p(i,"select")||p(i,"textarea")||i.getAttribute("contenteditable")==="true")}function T(i){return!(i===null||se(i)||typeof i=="string"&&(i=N(i),/^(?:(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((i||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(i)))}function ce(i){return typeof i=="string"?i.substring(0,10)==="_ngcontent"||i.substring(0,7)==="_nghost":!1}function I(){return y(10)}function le(i){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(i).toLowerCase())}function ue(i,e){let t;return function(...n){const s=()=>{clearTimeout(t),i(...n)};clearTimeout(t),t=setTimeout(s,e)}}function he(i){const e={},t=i.replace(/^\?/,"").split("&");for(let n=0;n<t.length;n++){const s=t[n].split("=");s[0]!==""&&(e[decodeURIComponent(s[0])]=decodeURIComponent(s[1]||""))}return e}function J(i){return typeof i=="string"||i instanceof String}function _(i){return i!==null&&typeof i=="object"&&i.constructor===Object}function de(i){if(i===null)return d.ERROR;const e=i.toUpperCase(),t=d[e];return t||t===0?t:d.ERROR}const fe=()=>{let i="false";return typeof window<"u"&&window.localStorage&&(i=localStorage.getItem("um_exclusion")),!(i==null||i==="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(),n=this.getScrollDistance(),s=t-e;return Math.min(100,Math.floor(n/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(n=>e>=n).forEach(n=>{this.send(),this.milestones=this.milestones.filter(s=>s!==n)})}}const x=class x{constructor(e,t,n=f()){this.logger=n,this.scrollDepth=null,this.customProperties=[],this.client=e,this.options=t,this.scrollDepth=new ge(e),te(this),F(this)}init(){if(!(document&&document.body)){this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."),setTimeout(()=>this.init(),500);return}this.addDomEventHandlers()}addDomEventHandlers(){const e=t=>{t=t||window.event,this.captureEvent(t)};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 n,s;let t=this.getEventTarget(e);if(q(t)&&(t=t.parentNode||null),e.type==="scroll")return(n=this.scrollDepth)==null||n.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 Ee=L(E);E.tagName.toLowerCase()==="a"&&(l=E.getAttribute("href"),l=Ee&&T(l)&&l);const $e=S(E).split(" ");v($e,"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,n=>{m(n.event_selectors,s=>{const r=document.querySelectorAll(s);m(r,o=>{v(e,o)&&L(o)&&(t[n.name]=this.extractCustomPropertyValue(n))})})}),t}extractCustomPropertyValue(e){const t=[];return m(document.querySelectorAll(e.css_selector),function(n){let s;["input","select"].indexOf(n.tagName.toLowerCase())>-1?s=n.value:n.textContent&&(s=n.textContent),T(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,n){const s=e.tagName.toLowerCase(),r={tag_name:s};C.indexOf(s)>-1&&!n&&(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&&T(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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}static enabledForProject(e,t=10,n=10){if(!e)return!1;let s=0;for(let r=0;r<e.length;r++)s+=e.charCodeAt(r);return s%t<n}};x.FORCE_CAPTURE_ATTR="data-um-force-capture",x.PREVENT_CAPTURE_ATTR="data-um-no-capture";let A=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,n=f()){this.trackingHost=e,this.logger=n,this.config=t}async send(e){const t=this.config.key,n=this.constructUrl(t),s=new Blob([JSON.stringify(e)],{type:"application/json"});if(navigator.sendBeacon(n,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}`:"",n=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}${n}`:`${this.trackingHost}${s}?token=${e}${t}${n}`}}class Q{constructor(e,t,n=f()){this.trackingHost=e,this.logger=n,this.config=t}async send(e){const t=this.config.key,n=this.constructUrl(t),s=JSON.stringify(e),r={"Content-Type":"application/json",...this.getCustomHeaders()},o=await fetch(n,{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}`:"",n=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}${n}`:`${this.trackingHost}${s}?token=${e}${t}${n}`}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,n=f()){this.trackingHost=e,this.logger=n,this.config=t}send(e){return new Promise((t,n)=>{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()):n(new Error(`HTTP error! status: ${s.status}`))},s.onerror=()=>{n(new Error("Network error"))},s.send(JSON.stringify(e))})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",n=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}${n}`:`${this.trackingHost}${s}?token=${e}${t}${n}`}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 X{constructor(e,t=3,n=1e3,s=10,r=1e3,o=f(),c="default"){this.transport=e,this.maxRetries=t,this.retryInterval=n,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(n=>n.payload);try{await this.transport.send(t),this.logger.debug(`Successfully sent batch of ${e.length} payloads`),u()&&this.saveQueueToStorage()}catch(n){this.logger.error("Failed to send batch",n),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,n){const s={x:e,y:t,timestamp:n};this.clicks.push(s),this.clicks=this.clicks.filter(r=>n-r.timestamp<this.timeWindow),this.clicks.length>=this.threshold&&this.checkRageClick()}checkRageClick(){const e=this.clicks[0],n=(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(n)}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,n=f()){this.trackingHost=e,this.logger=n,this.config=t}async send(e){const t=this.config.key,n=new(void 0)(this.constructUrl(t)),s={hostname:n.hostname,port:443,path:`${n.pathname}${n.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}`:"",n=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"";return`${this.trackingHost}/api/v1/s2s/event?token=${e}${t}${n}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}}class k{constructor(e,t="all",n={}){this.instance=e,this.trackingType=t,this.options=n,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,n=this._getFormDetails(t);this.instance.track("$form",z(n)),this.options.trackFieldChanges&&this.trackFieldChanges(t)}trackFieldChanges(e){e.querySelectorAll("input, select, textarea").forEach(n=>{n.addEventListener("change",s=>{const r=this._getFieldProps(s.target,0);this.instance.track("$form_field_change",z(r))})})}static getInstance(e,t="all",n={}){return k.instance||(k.instance=new k(e,t,n)),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)},n=e.querySelectorAll("input, select, textarea");return Array.from(n).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 n=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`]:n,[`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,n=e.length-1;const s=[" ",`
|
|
2
|
+
`,"\r"," ","\f","\v"," "," "," "," "," "," "," "," "," "," "," "," "," ","\u2028","\u2029"," "," "," "].join("");for(;t<=n&&s.indexOf(e[t])>-1;)t++;for(;n>=t&&s.indexOf(e[n])>-1;)n--;return e.slice(t,n+1)}}class b{constructor(e){this.config=this.mergeConfig(e,U),this.logger=f(this.config.logLevel),this.namespace=e.namespace||"default",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new X(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 Z(this.config.cookieDomain),this.config.autocapture&&A.enabledForProject(this.config.key)&&(this.autoCapture=new A(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 n=JSON.parse(JSON.stringify(e));let s={...t,...n};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 X(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(n=>n.trim()),t=this.config.cookieName||`__eventn_id_${this.config.key}`;document.addEventListener("click",n=>{var c;const s=this.findClosestLink(n.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 n="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(n)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 n,s;if(!u())return I();if(this.config.privacyPolicy==="strict"||this.config.cookiePolicy==="strict")return"";const e=this.config.cookieName||`__eventn_id_${this.config.key}`;let t=(n=this.cookieManager)==null?void 0:n.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||I()}t||(t=I());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 n=e.id;if(this.persistence.set("userId",n),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,n=!1){this.trackInternal(e,t,n)}trackInternal(e,t,n=!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(n){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 n=this.persistence.get("userProps")||{},s=this.persistence.get("companyProps")||(n==null?void 0:n.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,...n},...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 n=e.$elements||[];return n.length&&(t={...n[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 n=()=>{!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&&n()});const s=history.pushState;history.pushState=function(){return n(),s.apply(this,arguments)},window.addEventListener("popstate",n)}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 n=t==null?void 0:t.eventType,s=(t==null?void 0:t.persist)??!0;if(n){let r=this.persistence.get(`props_${n}`)||{};r={...r,...e},this.persistence.set(`props_${n}`,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:n||"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 n=t==null?void 0:t.eventType,s=(t==null?void 0:t.persist)??!0;if(n){let r=this.persistence.get(`props_${n}`)||{};delete r[e],this.persistence.set(`props_${n}`,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: ${n||"global"}`)}}function K(){return typeof window<"u"&&typeof window.define=="function"&&window.define.amd}function _e(){return K()?window.define:void 0}function P(i){const e=JSON.parse(JSON.stringify(i)),t=O(e),n={...U,...t};if(!n.key)throw new Error("API key is required!");if(!n.trackingHost)throw new Error("Tracking host is required!");return new b(n)}function be(i){var s;const e={key:i.getAttribute("data-key")||void 0,trackingHost:i.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:de(i.getAttribute("data-log-level")),autocapture:i.getAttribute("data-autocapture")==="true",formTracking:i.getAttribute("data-form-tracking")==="false"?!1:i.getAttribute("data-form-tracking")==="true"?"all":i.getAttribute("data-form-tracking"),autoPageview:i.getAttribute("data-auto-pageview")==="true",useBeaconApi:i.getAttribute("data-use-beacon-api")==="true",forceUseFetch:i.getAttribute("data-force-use-fetch")==="true",gaHook:i.getAttribute("data-ga-hook")==="true",segmentHook:i.getAttribute("data-segment-hook")==="true",randomizeUrl:i.getAttribute("data-randomize-url")==="true",capture3rdPartyCookies:i.getAttribute("data-capture-3rd-party-cookies")==="false"?!1:void 0,idMethod:i.getAttribute("data-id-method")||void 0,privacyPolicy:i.getAttribute("data-privacy-policy")==="strict"?"strict":void 0,ipPolicy:i.getAttribute("data-ip-policy")||void 0,cookiePolicy:i.getAttribute("data-cookie-policy")||void 0,minSendTimeout:parseInt(i.getAttribute("data-min-send-timeout")||"",10)||void 0,maxSendTimeout:parseInt(i.getAttribute("data-max-send-timeout")||"",10)||void 0,maxSendAttempts:parseInt(i.getAttribute("data-max-send-attempts")||"",10)||void 0,propertiesStringMaxLength:parseInt(i.getAttribute("data-properties-string-max-length")||"",10)||null,propertyBlacklist:((s=i.getAttribute("data-property-blacklist"))==null?void 0:s.split(","))||void 0,exclude:i.getAttribute("data-exclude")||void 0,namespace:i.getAttribute("data-namespace")||void 0,crossDomainLinking:i.getAttribute("data-cross-domain-linking")!=="false",domains:i.getAttribute("data-domains")||void 0,maskAllText:i.getAttribute("data-mask-all-text")==="true",maskAllElementAttributes:i.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),n=e.namespace||"usermaven";return u()&&e.autoPageview!==!1&&t.pageview(),Pe(n,t),t}function Pe(i,e){let t=!1;const n=[],s=[];function r(){for(;n.length>0;){const a=n.shift();a&&window[i].apply(null,a)}}function o(){s.forEach(a=>a()),s.length=0}window[i]=function(...a){const h=a[0];if(h==="onLoad"){typeof a[1]=="function"&&(t?a[1]():s.push(a[1]));return}if(!t){n.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=`${i}Q`,l=window[c]||[];for(window[c]=l,l.push=function(...a){return window[i].apply(null,a),Array.prototype.push.apply(this,a)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${i} is ready`)},0);l.length>0;){const a=l.shift();a&&n.push(a)}}let G=!1,D=null;if(u()){const i=_e();i&&i("usermaven",[],function(){return{usermavenClient:P,UsermavenClient:b,LogLevel:d,getScriptTagClient:()=>D}}),typeof window<"u"&&(window.usermavenClient=P,window.UsermavenClient=b,window.usermavenScriptTagClient=()=>D),function(e,t){const n=e.currentScript;function s(){return G||!n||!n.hasAttribute("data-key")||n.getAttribute("data-no-auto-init")==="true"?!1:n.src.includes("lib.js")}function r(){s()&&(console.log("[Usermaven] Auto-initializing from script tag"),D=be(n),G=!0)}typeof t<"u"&&n&&(e.readyState==="loading"?e.addEventListener("DOMContentLoaded",r):r())}(document,window)}typeof module<"u"&&module.exports&&!K()&&(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"})});
|
package/dist/usermaven.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var w=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i))(w||{});class K{constructor(e){this.level=e}debug(e,...t){this.level<=0&&console.debug("[Usermaven Debug]:",e,...t)}info(e,...t){this.level<=1&&console.info("[Usermaven Info]:",e,...t)}warn(e,...t){this.level<=2&&console.warn("[Usermaven Warning]:",e,...t)}error(e,...t){this.level<=3&&console.error("[Usermaven Error]:",e,...t)}}function g(i=0){return new K(i)}const F={logLevel:w.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,s=365,n=!0,r=!1){const o=new Date;o.setTime(o.getTime()+s*24*60*60*1e3);const c=`expires=${o.toUTCString()}`,l=n?"; Secure":"",a=r?"; HttpOnly":"";document.cookie=`${e}=${t};${c};path=/;domain=${this.cookieDomain}${l}${a}`}get(e){const t=e+"=",s=document.cookie.split(";");for(let n=0;n<s.length;n++){let r=s[n].trim();if(r.indexOf(t)===0)return decodeURIComponent(r.substring(t.length))}return null}delete(e,t="/"){document.cookie=`${e}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${t};domain=${this.cookieDomain}`}getCookieDomain(){return typeof window>"u"||this.domain?this.domain||"":this.extractRoot(window.location.hostname)}extractRoot(e){if(this.isIpAddress(e)||e==="localhost")return e;let t=this.extractTopLevelDomain(e);return t||(t=this.extractRootDomain(e)),"."+t}isIpAddress(e){const t=e.split(".");return t.length===4&&t.every(s=>!isNaN(Number(s)))}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 s=t.split("."),n=s.length;return n>2&&(s[n-1].length==2?(t=s[n-2]+"."+s[n-1],s[n-2].length==2&&(t=s[n-3]+"."+t)):t=s[n-2]+"."+s[n-1]),t}extractTopLevelDomain(e){const t=/[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i,s=e.match(t);return s?s[0]:""}}const Y=Object.prototype,Z=Y.hasOwnProperty,j=Array.prototype,E=j.forEach,A={};function ee(i,e,t){if(Array.isArray(i)){if(E&&i.forEach===E)i.forEach(e,t);else if("length"in i&&i.length===+i.length){for(let s=0,n=i.length;s<n;s++)if(s in i&&e.call(t,i[s],s)===A)return}}}const x=function(i){return i.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},te=function(i){for(const e in i)typeof i[e]=="function"&&(i[e]=i[e].bind(i))};function f(i,e,t){if(i!=null){if(E&&Array.isArray(i)&&i.forEach===E)i.forEach(e,t);else if("length"in i&&i.length===+i.length){for(let s=0,n=i.length;s<n;s++)if(s in i&&e.call(t,i[s],s)===A)return}else for(const s in i)if(Z.call(i,s)&&e.call(t,i[s],s)===A)return}}const ie=function(i,...e){return ee(e,function(t){for(const s in t)t[s]!==void 0&&(i[s]=t[s])}),i};function _(i,e){return i.indexOf(e)!==-1}const se=function(i){try{return/^\s*\bfunction\b/.test(i)}catch{return!1}},ne=function(i){return i===void 0},m=function(){const i=function(s,n,r,o,c){if(!s){g().error("No valid element provided to register_event");return}if(s.addEventListener&&!o)s.addEventListener(n,r,!!c);else{const l="on"+n,a=s[l];s[l]=e(s,r,a)}};function e(s,n,r){return function(o){if(o=o||t(window.event),!o)return;let c=!0,l;se(r)&&(l=r(o));const a=n.call(s,o);return(l===!1||a===!1)&&(c=!1),c}}function t(s){return s&&(s.preventDefault=t.preventDefault,s.stopPropagation=t.stopPropagation),s}return t.preventDefault=function(){this.returnValue=!1},t.stopPropagation=function(){this.cancelBubble=!0},i}(),re=function(i){return function(...e){try{return i.apply(this,e)}catch(t){g().error("Implementation error. Please turn on debug and contact support@usermaven.com.",t)}}},z=function(i){for(const e in i)typeof i[e]=="function"&&(i[e]=re(i[e]))};function R(i){for(let e in i)(i[e]===""||i[e]===null||i[e]===void 0||typeof i[e]=="object"&&Object.keys(i[e]).length===0)&&delete i[e];return i}function u(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return g().warn("window is not available"),!1}}function p(i=5){const e=new Uint8Array(i);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").slice(0,i)}function oe(i){return i.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function H(i){return typeof i!="object"||i===null?i:Array.isArray(i)?i.map(H):Object.keys(i).reduce((e,t)=>{const s=oe(t);return e[s]=H(i[t]),e},{})}function $(i){switch(typeof i.className){case"string":return i.className;case"object":return("baseVal"in i.className?i.className.baseVal:null)||i.getAttribute("class")||"";default:return""}}function L(i){let e="";return O(i)&&!q(i)&&i.childNodes&&i.childNodes.length&&f(i.childNodes,function(t){M(t)&&t.textContent&&(e+=x(t.textContent).split(/(\s+)/).filter(P).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),x(e)}function B(i){return!!i&&i.nodeType===1}function d(i,e){return!!i&&!!i.tagName&&i.tagName.toLowerCase()===e.toLowerCase()}function M(i){return!!i&&i.nodeType===3}function N(i){return!!i&&i.nodeType===11}const b=["a","button","form","input","select","textarea","label"];function ae(i,e){if(!i||d(i,"html")||!B(i))return!1;let t=i;for(;t&&!d(t,"body");){if(t.classList&&t.classList.contains("um-no-capture"))return!1;t.parentNode&&N(t.parentNode)?t=t.parentNode.host:t=t.parentNode}let s=!1;for(t=i;t&&!d(t,"body");){if(t.parentNode&&N(t.parentNode)){t=t.parentNode.host,t&&b.indexOf(t.tagName.toLowerCase())>-1&&(s=!0);continue}const o=t.parentNode;if(!o)break;if(b.indexOf(o.tagName.toLowerCase())>-1)s=!0;else{const c=window.getComputedStyle(o);c&&c.getPropertyValue("cursor")==="pointer"&&(s=!0)}t=o}const n=window.getComputedStyle(i);if(n&&n.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;const r=i.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 s?e.type==="click":e.type==="click"&&(b.indexOf(r)>-1||i.getAttribute("contenteditable")==="true")}}function O(i){for(let s=i;s.parentNode&&!d(s,"body");s=s.parentNode){const n=$(s).split(" ");if(_(n,"ph-sensitive")||_(n,"ph-no-capture"))return!1}if(_($(i).split(" "),"ph-include"))return!0;const e=i.type||"";if(typeof e=="string")switch(e.toLowerCase()){case"hidden":return!1;case"password":return!1}const t=i.name||i.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 q(i){const e=["button","checkbox","submit","reset"];return!!(d(i,"input")&&!e.includes(i.type)||d(i,"select")||d(i,"textarea")||i.getAttribute("contenteditable")==="true")}function P(i){return!(i===null||ne(i)||typeof i=="string"&&(i=x(i),/^(?:(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((i||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(i)))}function ce(i){return typeof i=="string"?i.substring(0,10)==="_ngcontent"||i.substring(0,7)==="_nghost":!1}function T(){return p(10)}function le(i){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(i).toLowerCase())}function ue(i,e){let t;return function(...s){const n=()=>{clearTimeout(t),i(...s)};clearTimeout(t),t=setTimeout(n,e)}}function he(i){const e={},t=i.replace(/^\?/,"").split("&");for(let s=0;s<t.length;s++){const n=t[s].split("=");n[0]!==""&&(e[decodeURIComponent(n[0])]=decodeURIComponent(n[1]||""))}return e}function I(i){return typeof i=="string"||i instanceof String}function v(i){return i!==null&&typeof i=="object"&&i.constructor===Object}function ge(i){if(i===null)return w.ERROR;const e=i.toUpperCase(),t=w[e];return t||t===0?t:w.ERROR}const de=()=>{let i="false";return typeof window<"u"&&window.localStorage&&(i=localStorage.getItem("um_exclusion")),!(i==null||i==="false")};class fe{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(),s=this.getScrollDistance(),n=t-e;return Math.min(100,Math.floor(s/n*100))}getWindowHeight(){return window.innerHeight||this.documentElement.clientHeight||document.body.clientHeight||0}getDocumentHeight(){return Math.max(document.body.scrollHeight||0,this.documentElement.scrollHeight||0,document.body.offsetHeight||0,this.documentElement.offsetHeight||0,document.body.clientHeight||0,this.documentElement.clientHeight||0)}getScrollDistance(){return window.pageYOffset||this.documentElement.scrollTop||document.body.scrollTop||0}checkMilestones(e){this.milestones.filter(s=>e>=s).forEach(s=>{this.send(),this.milestones=this.milestones.filter(n=>n!==s)})}}const C=class C{constructor(e,t,s=g()){this.logger=s,this.scrollDepth=null,this.customProperties=[],this.client=e,this.options=t,this.scrollDepth=new fe(e),te(this),z(this)}init(){if(!(document&&document.body)){this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."),setTimeout(()=>this.init(),500);return}this.addDomEventHandlers()}addDomEventHandlers(){const e=t=>{t=t||window.event,this.captureEvent(t)};m(document,"submit",e,!1,!0),m(document,"change",e,!1,!0),m(document,"click",e,!1,!0),m(document,"visibilitychange",e,!1,!0),m(document,"scroll",e,!1,!0),m(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 s,n;let t=this.getEventTarget(e);if(M(t)&&(t=t.parentNode||null),e.type==="scroll")return(s=this.scrollDepth)==null||s.track(),!0;if(e.type==="visibilitychange"&&document.visibilityState==="hidden"||e.type==="popstate")return this.isPageRefresh()||(n=this.scrollDepth)==null||n.send(),!0;if(t&&ae(t,e)){const r=[t];let o=t;for(;o.parentNode&&!d(o,"body");){if(N(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(f(r,k=>{const W=O(k);k.tagName.toLowerCase()==="a"&&(l=k.getAttribute("href"),l=W&&P(l)&&l);const X=$(k).split(" ");_(X,"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=L(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 f(this.customProperties,s=>{f(s.event_selectors,n=>{const r=document.querySelectorAll(n);f(r,o=>{_(e,o)&&O(o)&&(t[s.name]=this.extractCustomPropertyValue(s))})})}),t}extractCustomPropertyValue(e){const t=[];return f(document.querySelectorAll(e.css_selector),function(s){let n;["input","select"].indexOf(s.tagName.toLowerCase())>-1?n=s.value:s.textContent&&(n=s.textContent),P(n)&&t.push(n)}),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,s){const n=e.tagName.toLowerCase(),r={tag_name:n};b.indexOf(n)>-1&&!s&&(r.$el_text=L(e));const o=$(e);o.length>0&&(r.classes=o.split(" ").filter(function(h){return h!==""})),f(e.attributes,function(h){q(e)&&["name","id","class"].indexOf(h.name)===-1||!t&&P(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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}static enabledForProject(e,t=10,s=10){if(!e)return!1;let n=0;for(let r=0;r<e.length;r++)n+=e.charCodeAt(r);return n%t<s}};C.FORCE_CAPTURE_ATTR="data-um-force-capture",C.PREVENT_CAPTURE_ATTR="data-um-no-capture";let S=C;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,s=g()){this.trackingHost=e,this.logger=s,this.config=t}async send(e){const t=this.config.key,s=this.constructUrl(t),n=new Blob([JSON.stringify(e)],{type:"application/json"});if(navigator.sendBeacon(s,n))this.logger.debug(`Successfully queued ${e.length} event(s) via Beacon API`);else throw new Error("Failed to queue events via Beacon API")}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",s=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${p()}?p_${p()}=${e}${t}${s}`:`${this.trackingHost}${n}?token=${e}${t}${s}`}}class D{constructor(e,t,s=g()){this.trackingHost=e,this.logger=s,this.config=t}async send(e){const t=this.config.key,s=this.constructUrl(t),n=JSON.stringify(e),r={"Content-Type":"application/json",...this.getCustomHeaders()},o=await fetch(s,{method:"POST",headers:r,body:n});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);this.logger.debug(`Successfully sent ${e.length} event(s)`),this.postHandle(o.status,await o.text())}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",s=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${p()}?p_${p()}=${e}${t}${s}`:`${this.trackingHost}${n}?token=${e}${t}${s}`}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,s=g()){this.trackingHost=e,this.logger=s,this.config=t}send(e){return new Promise((t,s)=>{const n=new XMLHttpRequest,r=this.config.key,o=this.constructUrl(r);n.open("POST",o,!0),n.setRequestHeader("Content-Type","application/json");const c=this.getCustomHeaders();Object.keys(c).forEach(l=>{n.setRequestHeader(l,c[l])}),n.onload=()=>{n.status>=200&&n.status<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),t()):s(new Error(`HTTP error! status: ${n.status}`))},n.onerror=()=>{s(new Error("Network error"))},n.send(JSON.stringify(e))})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",s=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${p()}?p_${p()}=${e}${t}${s}`:`${this.trackingHost}${n}?token=${e}${t}${s}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}postHandle(e,t){this.logger.debug(`Response received. Status: ${e}, Body: ${t}`)}}class V{constructor(e,t){this.storage={},this.prefix=`usermaven_${e}_`,this.load(),this.logger=t||g()}set(e,t){this.storage[e]=t,this.save()}get(e){return this.storage[e]}remove(e){delete this.storage[e],this.save()}clear(){this.storage={},this.save()}save(){if(!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 U{constructor(e,t=3,s=1e3,n=10,r=1e3,o=g(),c="default"){this.transport=e,this.maxRetries=t,this.retryInterval=s,this.batchSize=n,this.batchInterval=r,this.logger=o,this.queue=[],this.processing=!1,this.batchTimeoutId=null,this.isOnline=!0,this.persistence=new V(`offline_queue_${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(s=>s.payload);try{await this.transport.send(t),this.logger.debug(`Successfully sent batch of ${e.length} payloads`),u()&&this.saveQueueToStorage()}catch(s){this.logger.error("Failed to send batch",s),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(),z(this)}initializeEventListener(){document.addEventListener("click",this.handleClick.bind(this))}handleClick(e){const t=e.target;this.shouldCaptureElement(t)&&this.click(e.clientX,e.clientY,Date.now())}shouldCaptureElement(e){return!e.closest(".um-no-capture")}click(e,t,s){const n={x:e,y:t,timestamp:s};this.clicks.push(n),this.clicks=this.clicks.filter(r=>s-r.timestamp<this.timeWindow),this.clicks.length>=this.threshold&&this.checkRageClick()}checkRageClick(){const e=this.clicks[0],s=(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(s)}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,s=g()){this.trackingHost=e,this.logger=s,this.config=t}async send(e){const t=this.config.key,s=new(void 0)(this.constructUrl(t)),n={hostname:s.hostname,port:443,path:`${s.pathname}${s.search}`,method:"POST",headers:{"Content-Type":"application/json",...this.getCustomHeaders()}};return new Promise((r,o)=>{const c=(void 0)(n,l=>{l.on("data",a=>{}),l.on("end",()=>{const a=l.statusCode||0;a>=200&&a<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${a}`))})});c.on("error",l=>{o(l)}),c.write(JSON.stringify(e)),c.end()})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",s=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"";return`${this.trackingHost}/api/v1/s2s/event?token=${e}${t}${s}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}}class y{constructor(e,t="all",s={}){this.instance=e,this.trackingType=t,this.options=s,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,s=this._getFormDetails(t);this.instance.track("$form",R(s)),this.options.trackFieldChanges&&this.trackFieldChanges(t)}trackFieldChanges(e){e.querySelectorAll("input, select, textarea").forEach(s=>{s.addEventListener("change",n=>{const r=this._getFieldProps(n.target,0);this.instance.track("$form_field_change",R(r))})})}static getInstance(e,t="all",s={}){return y.instance||(y.instance=new y(e,t,s)),y.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)},s=e.querySelectorAll("input, select, textarea");return Array.from(s).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 s=Object.keys(e.dataset).length?JSON.stringify(e.dataset):void 0,n=this.getSafeText(e);return{[`field_${t+1}_tag`]:e.tagName.toLowerCase(),[`field_${t+1}_type`]:e instanceof HTMLInputElement?e.type:void 0,[`field_${t+1}_data_attributes`]:s,[`field_${t+1}_id`]:e.id,[`field_${t+1}_value`]:n,[`field_${t+1}_class`]:e.className,[`field_${t+1}_name`]:e.name,[`field_${t+1}_attributes`]:this._getElementAttributes(e)}}_getElementAttributes(e){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(n=>n.nodeType===Node.TEXT_NODE).map(n=>n.textContent).join(""):t=e.textContent||"",this._scrubPotentiallySensitiveValues(t)}_scrubPotentiallySensitiveValues(e){return this._shouldCaptureValue(e)?e:"<redacted>"}_shouldCaptureValue(e){return!(this._isNullish(e)||this._isString(e)&&(e=this._trim(e),/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((e||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(e)))}_isNullish(e){return e==null}_isString(e){return typeof e=="string"||e instanceof String}_trim(e){if(typeof String.prototype.trim=="function")return e.trim();let t=0,s=e.length-1;const n=[" ",`
|
|
2
|
-
`,"\r"," ","\f","\v"," "," "," "," "," "," "," "," "," "," "," "," "," ","\u2028","\u2029"," "," "," "].join("");for(;t<=s&&n.indexOf(e[t])>-1;)t++;for(;s>=t&&n.indexOf(e[s])>-1;)s--;return e.slice(t,s+1)}}class J{constructor(e){this.config=this.mergeConfig(e,F),this.logger=g(this.config.logLevel),this.namespace=e.namespace||"default",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new U(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&&S.enabledForProject(this.config.key)&&(this.autoCapture=new S(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=y.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 s=JSON.parse(JSON.stringify(e));let n={...t,...s};return Object.keys(t).forEach(r=>{v(t[r])&&(n[r]=this.mergeConfig(e[r],t[r]))}),n}init(e){this.config={...this.config,...e},this.logger=g(this.config.logLevel),this.namespace=e.namespace||this.namespace,this.transport=this.initializeTransport(e),this.persistence=this.initializePersistence(),this.retryQueue=new U(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(s=>s.trim()),t=this.config.cookieName||`__eventn_id_${this.config.key}`;document.addEventListener("click",s=>{var c;const n=this.findClosestLink(s.target);if(!n)return;const r=n.getAttribute("href");if(!r||!r.startsWith("http"))return;const o=new URL(r);if(o.hostname!==window.location.hostname&&e.includes(o.hostname)){const l=(c=this.cookieManager)==null?void 0:c.get(t);l&&(o.searchParams.append("_um",l),n.setAttribute("href",o.toString()))}}),this.logger.debug("Cross-domain linking initialized")}findClosestLink(e){for(;e&&e.tagName!=="A";)e=e.parentElement;return e}initializeTransport(e){const t="https://events.usermaven.com";if(!u())return new ve(e.trackingHost||t,e);const s="XMLHttpRequest"in window,n=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&&n)return new D(e.trackingHost||t,e,this.logger);if(s)return new ye(e.trackingHost||t,e,this.logger);if(n)return new D(e.trackingHost||t,e,this.logger);throw new Error("No suitable transport method available")}initializePersistence(){return this.config.disableEventPersistence||!u()?new we:new V(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var s,n;if(!u())return T();if(this.config.privacyPolicy==="strict"||this.config.cookiePolicy==="strict")return"";const e=this.config.cookieName||`__eventn_id_${this.config.key}`;let t=(s=this.cookieManager)==null?void 0:s.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||T()}t||(t=T());const r=365*10;(n=this.cookieManager)==null||n.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&&!le(e.email))throw new Error("Invalid email provided");if(!e.id||!I(e.id))throw new Error("User ID must be a string");const s=e.id;if(this.persistence.set("userId",s),this.persistence.set("userProps",e),!t){const n={...e,anonymous_id:this.anonymousId};await this.track("user_identify",n)}this.logger.info("User identified:",e)}track(e,t,s=!1){this.trackInternal(e,t,s)}trackInternal(e,t,s=!1){if(de()){this.logger.debug("Tracking disabled due to um_exclusion setting");return}if(!I(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(s){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 s=this.persistence.get("userProps")||{},n=this.persistence.get("companyProps")||(s==null?void 0:s.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,...s},...n&&{company:n},ids:this.getThirdPartyIds(),utc_time:new Date().toISOString(),local_tz_offset:new Date().getTimezoneOffset(),api_key:this.config.key,src:"usermaven",event_type:e,namespace:this.namespace,...o,...c};if(e==="$autocapture"){const 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 s=e.$elements||[];return s.length&&(t={...s[0]}),t.el_text=t.$el_text||"",t.event_type=e.$event_type||"",["$ce_version","$event_type","$initial_referrer","$initial_referring_domain","$referrer","$referring_domain","$elements"].forEach(n=>{delete t[n]}),delete t.$el_text,delete t.nth_child,delete t.nth_of_type,t}getCookie(e){var t;return((t=this.cookieManager)==null?void 0:t.get(e))||null}getThirdPartyIds(){const e={};if(u()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=he(window.location.search);return["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(n=>{t[n]&&(e[n.replace("utm_","")]=t[n])}),e}pageview(){u()?this.track("pageview",{url:window.location.href,referrer:document.referrer,title:document.title},!0):this.logger.warn("Pageview tracking is not available in server-side environments")}setupPageLeaveTracking(){if(!u())return;let e=!1,t=!1;const s=()=>{!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&&s()});const n=history.pushState;history.pushState=function(){return s(),n.apply(this,arguments)},window.addEventListener("popstate",s)}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 s=t==null?void 0:t.eventType,n=(t==null?void 0:t.persist)??!0;if(s){let r=this.persistence.get(`props_${s}`)||{};r={...r,...e},this.persistence.set(`props_${s}`,r)}else{let r=this.persistence.get("global_props")||{};r={...r,...e},this.persistence.set("global_props",r)}n&&this.persistence.save(),this.logger.debug("Properties set",{properties:e,eventType:s||"global",persist:n})}setUserId(e){this.persistence.set("userId",e);let t=this.persistence.get("userProps")||{};t.id=e,this.persistence.set("userProps",t),this.persistence.save()}unset(e,t){const s=t==null?void 0:t.eventType,n=(t==null?void 0:t.persist)??!0;if(s){let r=this.persistence.get(`props_${s}`)||{};delete r[e],this.persistence.set(`props_${s}`,r)}else{let r=this.persistence.get("global_props")||{};delete r[e],this.persistence.set("global_props",r)}n&&this.persistence.save(),this.logger.debug(`Property unset: ${e}`,`Event type: ${s||"global"}`)}}function Q(i){const e=JSON.parse(JSON.stringify(i)),t=H(e),s={...F,...t};if(!s.key)throw new Error("API key is required!");if(!s.trackingHost)throw new Error("Tracking host is required!");return new J(s)}function _e(i){var n;const e={key:i.getAttribute("data-key")||void 0,trackingHost:i.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:ge(i.getAttribute("data-log-level")),autocapture:i.getAttribute("data-autocapture")==="true",formTracking:i.getAttribute("data-form-tracking")==="false"?!1:i.getAttribute("data-form-tracking")==="true"?"all":i.getAttribute("data-form-tracking"),autoPageview:i.getAttribute("data-auto-pageview")==="true",useBeaconApi:i.getAttribute("data-use-beacon-api")==="true",forceUseFetch:i.getAttribute("data-force-use-fetch")==="true",gaHook:i.getAttribute("data-ga-hook")==="true",segmentHook:i.getAttribute("data-segment-hook")==="true",randomizeUrl:i.getAttribute("data-randomize-url")==="true",capture3rdPartyCookies:i.getAttribute("data-capture-3rd-party-cookies")==="false"?!1:void 0,idMethod:i.getAttribute("data-id-method")||void 0,privacyPolicy:i.getAttribute("data-privacy-policy")==="strict"?"strict":void 0,ipPolicy:i.getAttribute("data-ip-policy")||void 0,cookiePolicy:i.getAttribute("data-cookie-policy")||void 0,minSendTimeout:parseInt(i.getAttribute("data-min-send-timeout")||"",10)||void 0,maxSendTimeout:parseInt(i.getAttribute("data-max-send-timeout")||"",10)||void 0,maxSendAttempts:parseInt(i.getAttribute("data-max-send-attempts")||"",10)||void 0,propertiesStringMaxLength:parseInt(i.getAttribute("data-properties-string-max-length")||"",10)||null,propertyBlacklist:((n=i.getAttribute("data-property-blacklist"))==null?void 0:n.split(","))||void 0,exclude:i.getAttribute("data-exclude")||void 0,namespace:i.getAttribute("data-namespace")||void 0,crossDomainLinking:i.getAttribute("data-cross-domain-linking")!=="false",domains:i.getAttribute("data-domains")||void 0,maskAllText:i.getAttribute("data-mask-all-text")==="true",maskAllElementAttributes:i.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=Q(e),s=e.namespace||"usermaven";u()&&t.pageview(),be(s,t)}function be(i,e){let t=!1;const s=[],n=[];function r(){for(;s.length>0;){const a=s.shift();a&&window[i].apply(null,a)}}function o(){n.forEach(a=>a()),n.length=0}window[i]=function(...a){const h=a[0];if(h==="onLoad"){typeof a[1]=="function"&&(t?a[1]():n.push(a[1]));return}if(!t){s.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=`${i}Q`,l=window[c]||[];for(window[c]=l,l.push=function(...a){return window[i].apply(null,a),Array.prototype.push.apply(this,a)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${i} is ready`)},0);l.length>0;){const a=l.shift();a&&s.push(a)}}u()&&function(i,e){const t=i.currentScript;function s(){t&&t.src.includes("lib.js")&&_e(t)}typeof e<"u"&&(i.readyState==="loading"?i.addEventListener("DOMContentLoaded",s):s())}(document,window);exports.LogLevel=w;exports.UsermavenClient=J;exports.usermavenClient=Q;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var f=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i))(f||{});class Z{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(i=0){return new Z(i)}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,s=365,n=!0,r=!1){const o=new Date;o.setTime(o.getTime()+s*24*60*60*1e3);const c=`expires=${o.toUTCString()}`,l=n?"; Secure":"",a=r?"; HttpOnly":"";document.cookie=`${e}=${t};${c};path=/;domain=${this.cookieDomain}${l}${a}`}get(e){const t=e+"=",s=document.cookie.split(";");for(let n=0;n<s.length;n++){let r=s[n].trim();if(r.indexOf(t)===0)return decodeURIComponent(r.substring(t.length))}return null}delete(e,t="/"){document.cookie=`${e}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${t};domain=${this.cookieDomain}`}getCookieDomain(){return typeof window>"u"||this.domain?this.domain||"":this.extractRoot(window.location.hostname)}extractRoot(e){if(this.isIpAddress(e)||e==="localhost")return e;let t=this.extractTopLevelDomain(e);return t||(t=this.extractRootDomain(e)),"."+t}isIpAddress(e){const t=e.split(".");return t.length===4&&t.every(s=>!isNaN(Number(s)))}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 s=t.split("."),n=s.length;return n>2&&(s[n-1].length==2?(t=s[n-2]+"."+s[n-1],s[n-2].length==2&&(t=s[n-3]+"."+t)):t=s[n-2]+"."+s[n-1]),t}extractTopLevelDomain(e){const t=/[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i,s=e.match(t);return s?s[0]:""}}const ee=Object.prototype,te=ee.hasOwnProperty,ie=Array.prototype,S=ie.forEach,N={};function se(i,e,t){if(Array.isArray(i)){if(S&&i.forEach===S)i.forEach(e,t);else if("length"in i&&i.length===+i.length){for(let s=0,n=i.length;s<n;s++)if(s in i&&e.call(t,i[s],s)===N)return}}}const O=function(i){return i.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},ne=function(i){for(const e in i)typeof i[e]=="function"&&(i[e]=i[e].bind(i))};function p(i,e,t){if(i!=null){if(S&&Array.isArray(i)&&i.forEach===S)i.forEach(e,t);else if("length"in i&&i.length===+i.length){for(let s=0,n=i.length;s<n;s++)if(s in i&&e.call(t,i[s],s)===N)return}else for(const s in i)if(te.call(i,s)&&e.call(t,i[s],s)===N)return}}const re=function(i,...e){return se(e,function(t){for(const s in t)t[s]!==void 0&&(i[s]=t[s])}),i};function _(i,e){return i.indexOf(e)!==-1}const oe=function(i){try{return/^\s*\bfunction\b/.test(i)}catch{return!1}},ae=function(i){return i===void 0},y=function(){const i=function(s,n,r,o,c){if(!s){d().error("No valid element provided to register_event");return}if(s.addEventListener&&!o)s.addEventListener(n,r,!!c);else{const l="on"+n,a=s[l];s[l]=e(s,r,a)}};function e(s,n,r){return function(o){if(o=o||t(window.event),!o)return;let c=!0,l;oe(r)&&(l=r(o));const a=n.call(s,o);return(l===!1||a===!1)&&(c=!1),c}}function t(s){return s&&(s.preventDefault=t.preventDefault,s.stopPropagation=t.stopPropagation),s}return t.preventDefault=function(){this.returnValue=!1},t.stopPropagation=function(){this.cancelBubble=!0},i}(),ce=function(i){return function(...e){try{return i.apply(this,e)}catch(t){d().error("Implementation error. Please turn on debug and contact support@usermaven.com.",t)}}},V=function(i){for(const e in i)typeof i[e]=="function"&&(i[e]=ce(i[e]))};function D(i){for(let e in i)(i[e]===""||i[e]===null||i[e]===void 0||typeof i[e]=="object"&&Object.keys(i[e]).length===0)&&delete i[e];return i}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(i=5){const e=new Uint8Array(i);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").slice(0,i)}function le(i){return i.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function R(i){return typeof i!="object"||i===null?i:Array.isArray(i)?i.map(R):Object.keys(i).reduce((e,t)=>{const s=le(t);return e[s]=R(i[t]),e},{})}function C(i){switch(typeof i.className){case"string":return i.className;case"object":return("baseVal"in i.className?i.className.baseVal:null)||i.getAttribute("class")||"";default:return""}}function U(i){let e="";return I(i)&&!W(i)&&i.childNodes&&i.childNodes.length&&p(i.childNodes,function(t){Q(t)&&t.textContent&&(e+=O(t.textContent).split(/(\s+)/).filter($).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),O(e)}function J(i){return!!i&&i.nodeType===1}function g(i,e){return!!i&&!!i.tagName&&i.tagName.toLowerCase()===e.toLowerCase()}function Q(i){return!!i&&i.nodeType===3}function L(i){return!!i&&i.nodeType===11}const E=["a","button","form","input","select","textarea","label"];function ue(i,e){if(!i||g(i,"html")||!J(i))return!1;let t=i;for(;t&&!g(t,"body");){if(t.classList&&t.classList.contains("um-no-capture"))return!1;t.parentNode&&L(t.parentNode)?t=t.parentNode.host:t=t.parentNode}let s=!1;for(t=i;t&&!g(t,"body");){if(t.parentNode&&L(t.parentNode)){t=t.parentNode.host,t&&E.indexOf(t.tagName.toLowerCase())>-1&&(s=!0);continue}const o=t.parentNode;if(!o)break;if(E.indexOf(o.tagName.toLowerCase())>-1)s=!0;else{const c=window.getComputedStyle(o);c&&c.getPropertyValue("cursor")==="pointer"&&(s=!0)}t=o}const n=window.getComputedStyle(i);if(n&&n.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;const r=i.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 s?e.type==="click":e.type==="click"&&(E.indexOf(r)>-1||i.getAttribute("contenteditable")==="true")}}function I(i){for(let s=i;s.parentNode&&!g(s,"body");s=s.parentNode){const n=C(s).split(" ");if(_(n,"ph-sensitive")||_(n,"ph-no-capture"))return!1}if(_(C(i).split(" "),"ph-include"))return!0;const e=i.type||"";if(typeof e=="string")switch(e.toLowerCase()){case"hidden":return!1;case"password":return!1}const t=i.name||i.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(i){const e=["button","checkbox","submit","reset"];return!!(g(i,"input")&&!e.includes(i.type)||g(i,"select")||g(i,"textarea")||i.getAttribute("contenteditable")==="true")}function $(i){return!(i===null||ae(i)||typeof i=="string"&&(i=O(i),/^(?:(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((i||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(i)))}function he(i){return typeof i=="string"?i.substring(0,10)==="_ngcontent"||i.substring(0,7)==="_nghost":!1}function x(){return m(10)}function de(i){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(i).toLowerCase())}function fe(i,e){let t;return function(...s){const n=()=>{clearTimeout(t),i(...s)};clearTimeout(t),t=setTimeout(n,e)}}function ge(i){const e={},t=i.replace(/^\?/,"").split("&");for(let s=0;s<t.length;s++){const n=t[s].split("=");n[0]!==""&&(e[decodeURIComponent(n[0])]=decodeURIComponent(n[1]||""))}return e}function F(i){return typeof i=="string"||i instanceof String}function v(i){return i!==null&&typeof i=="object"&&i.constructor===Object}function pe(i){if(i===null)return f.ERROR;const e=i.toUpperCase(),t=f[e];return t||t===0?t:f.ERROR}const me=()=>{let i="false";return typeof window<"u"&&window.localStorage&&(i=localStorage.getItem("um_exclusion")),!(i==null||i==="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(),s=this.getScrollDistance(),n=t-e;return Math.min(100,Math.floor(s/n*100))}getWindowHeight(){return window.innerHeight||this.documentElement.clientHeight||document.body.clientHeight||0}getDocumentHeight(){return Math.max(document.body.scrollHeight||0,this.documentElement.scrollHeight||0,document.body.offsetHeight||0,this.documentElement.offsetHeight||0,document.body.clientHeight||0,this.documentElement.clientHeight||0)}getScrollDistance(){return window.pageYOffset||this.documentElement.scrollTop||document.body.scrollTop||0}checkMilestones(e){this.milestones.filter(s=>e>=s).forEach(s=>{this.send(),this.milestones=this.milestones.filter(n=>n!==s)})}}const A=class A{constructor(e,t,s=d()){this.logger=s,this.scrollDepth=null,this.customProperties=[],this.client=e,this.options=t,this.scrollDepth=new ye(e),ne(this),V(this)}init(){if(!(document&&document.body)){this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."),setTimeout(()=>this.init(),500);return}this.addDomEventHandlers()}addDomEventHandlers(){const e=t=>{t=t||window.event,this.captureEvent(t)};y(document,"submit",e,!1,!0),y(document,"change",e,!1,!0),y(document,"click",e,!1,!0),y(document,"visibilitychange",e,!1,!0),y(document,"scroll",e,!1,!0),y(window,"popstate",e,!1,!0)}isPageRefresh(){if("PerformanceNavigationTiming"in window){const e=performance.getEntriesByType("navigation");if(e.length>0)return e[0].type==="reload"}return performance.navigation&&performance.navigation.type===1}captureEvent(e){var s,n;let t=this.getEventTarget(e);if(Q(t)&&(t=t.parentNode||null),e.type==="scroll")return(s=this.scrollDepth)==null||s.track(),!0;if(e.type==="visibilitychange"&&document.visibilityState==="hidden"||e.type==="popstate")return this.isPageRefresh()||(n=this.scrollDepth)==null||n.send(),!0;if(t&&ue(t,e)){const r=[t];let o=t;for(;o.parentNode&&!g(o,"body");){if(L(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 G=I(k);k.tagName.toLowerCase()==="a"&&(l=k.getAttribute("href"),l=G&&$(l)&&l);const Y=C(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=U(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,s=>{p(s.event_selectors,n=>{const r=document.querySelectorAll(n);p(r,o=>{_(e,o)&&I(o)&&(t[s.name]=this.extractCustomPropertyValue(s))})})}),t}extractCustomPropertyValue(e){const t=[];return p(document.querySelectorAll(e.css_selector),function(s){let n;["input","select"].indexOf(s.tagName.toLowerCase())>-1?n=s.value:s.textContent&&(n=s.textContent),$(n)&&t.push(n)}),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,s){const n=e.tagName.toLowerCase(),r={tag_name:n};E.indexOf(n)>-1&&!s&&(r.$el_text=U(e));const o=C(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&&$(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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}static enabledForProject(e,t=10,s=10){if(!e)return!1;let n=0;for(let r=0;r<e.length;r++)n+=e.charCodeAt(r);return n%t<s}};A.FORCE_CAPTURE_ATTR="data-um-force-capture",A.PREVENT_CAPTURE_ATTR="data-um-no-capture";let T=A;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,s=d()){this.trackingHost=e,this.logger=s,this.config=t}async send(e){const t=this.config.key,s=this.constructUrl(t),n=new Blob([JSON.stringify(e)],{type:"application/json"});if(navigator.sendBeacon(s,n))this.logger.debug(`Successfully queued ${e.length} event(s) via Beacon API`);else throw new Error("Failed to queue events via Beacon API")}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",s=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${e}${t}${s}`:`${this.trackingHost}${n}?token=${e}${t}${s}`}}class z{constructor(e,t,s=d()){this.trackingHost=e,this.logger=s,this.config=t}async send(e){const t=this.config.key,s=this.constructUrl(t),n=JSON.stringify(e),r={"Content-Type":"application/json",...this.getCustomHeaders()},o=await fetch(s,{method:"POST",headers:r,body:n});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);this.logger.debug(`Successfully sent ${e.length} event(s)`),this.postHandle(o.status,await o.text())}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",s=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${e}${t}${s}`:`${this.trackingHost}${n}?token=${e}${t}${s}`}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,s=d()){this.trackingHost=e,this.logger=s,this.config=t}send(e){return new Promise((t,s)=>{const n=new XMLHttpRequest,r=this.config.key,o=this.constructUrl(r);n.open("POST",o,!0),n.setRequestHeader("Content-Type","application/json");const c=this.getCustomHeaders();Object.keys(c).forEach(l=>{n.setRequestHeader(l,c[l])}),n.onload=()=>{n.status>=200&&n.status<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),t()):s(new Error(`HTTP error! status: ${n.status}`))},n.onerror=()=>{s(new Error("Network error"))},n.send(JSON.stringify(e))})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",s=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${e}${t}${s}`:`${this.trackingHost}${n}?token=${e}${t}${s}`}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 X{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,s=1e3,n=10,r=1e3,o=d(),c="default"){this.transport=e,this.maxRetries=t,this.retryInterval=s,this.batchSize=n,this.batchInterval=r,this.logger=o,this.queue=[],this.processing=!1,this.batchTimeoutId=null,this.isOnline=!0,this.persistence=new X(`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(s=>s.payload);try{await this.transport.send(t),this.logger.debug(`Successfully sent batch of ${e.length} payloads`),u()&&this.saveQueueToStorage()}catch(s){this.logger.error("Failed to send batch",s),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,s){const n={x:e,y:t,timestamp:s};this.clicks.push(n),this.clicks=this.clicks.filter(r=>s-r.timestamp<this.timeWindow),this.clicks.length>=this.threshold&&this.checkRageClick()}checkRageClick(){const e=this.clicks[0],s=(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(s)}sendRageClickEvent(e){const t=this.clicks[this.clicks.length-1];document.elementFromPoint(t.x,t.y)&&this.client.track("$rage_click",{no_of_clicks:this.clicks.length,time:e.toFixed(2)}),this.clicks=[]}}class Pe{constructor(e,t,s=d()){this.trackingHost=e,this.logger=s,this.config=t}async send(e){const t=this.config.key,s=new(void 0)(this.constructUrl(t)),n={hostname:s.hostname,port:443,path:`${s.pathname}${s.search}`,method:"POST",headers:{"Content-Type":"application/json",...this.getCustomHeaders()}};return new Promise((r,o)=>{const c=(void 0)(n,l=>{l.on("data",a=>{}),l.on("end",()=>{const a=l.statusCode||0;a>=200&&a<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${a}`))})});c.on("error",l=>{o(l)}),c.write(JSON.stringify(e)),c.end()})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",s=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"";return`${this.trackingHost}/api/v1/s2s/event?token=${e}${t}${s}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}}class w{constructor(e,t="all",s={}){this.instance=e,this.trackingType=t,this.options=s,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,s=this._getFormDetails(t);this.instance.track("$form",D(s)),this.options.trackFieldChanges&&this.trackFieldChanges(t)}trackFieldChanges(e){e.querySelectorAll("input, select, textarea").forEach(s=>{s.addEventListener("change",n=>{const r=this._getFieldProps(n.target,0);this.instance.track("$form_field_change",D(r))})})}static getInstance(e,t="all",s={}){return w.instance||(w.instance=new w(e,t,s)),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)},s=e.querySelectorAll("input, select, textarea");return Array.from(s).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 s=Object.keys(e.dataset).length?JSON.stringify(e.dataset):void 0,n=this.getSafeText(e);return{[`field_${t+1}_tag`]:e.tagName.toLowerCase(),[`field_${t+1}_type`]:e instanceof HTMLInputElement?e.type:void 0,[`field_${t+1}_data_attributes`]:s,[`field_${t+1}_id`]:e.id,[`field_${t+1}_value`]:n,[`field_${t+1}_class`]:e.className,[`field_${t+1}_name`]:e.name,[`field_${t+1}_attributes`]:this._getElementAttributes(e)}}_getElementAttributes(e){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(n=>n.nodeType===Node.TEXT_NODE).map(n=>n.textContent).join(""):t=e.textContent||"",this._scrubPotentiallySensitiveValues(t)}_scrubPotentiallySensitiveValues(e){return this._shouldCaptureValue(e)?e:"<redacted>"}_shouldCaptureValue(e){return!(this._isNullish(e)||this._isString(e)&&(e=this._trim(e),/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((e||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(e)))}_isNullish(e){return e==null}_isString(e){return typeof e=="string"||e instanceof String}_trim(e){if(typeof String.prototype.trim=="function")return e.trim();let t=0,s=e.length-1;const n=[" ",`
|
|
2
|
+
`,"\r"," ","\f","\v"," "," "," "," "," "," "," "," "," "," "," "," "," ","\u2028","\u2029"," "," "," "].join("");for(;t<=s&&n.indexOf(e[t])>-1;)t++;for(;s>=t&&n.indexOf(e[s])>-1;)s--;return e.slice(t,s+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&&T.enabledForProject(this.config.key)&&(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=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 s=JSON.parse(JSON.stringify(e));let n={...t,...s};return Object.keys(t).forEach(r=>{v(t[r])&&(n[r]=this.mergeConfig(e[r],t[r]))}),n}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(s=>s.trim()),t=this.config.cookieName||`__eventn_id_${this.config.key}`;document.addEventListener("click",s=>{var c;const n=this.findClosestLink(s.target);if(!n)return;const r=n.getAttribute("href");if(!r||!r.startsWith("http"))return;const o=new URL(r);if(o.hostname!==window.location.hostname&&e.includes(o.hostname)){const l=(c=this.cookieManager)==null?void 0:c.get(t);l&&(o.searchParams.append("_um",l),n.setAttribute("href",o.toString()))}}),this.logger.debug("Cross-domain linking initialized")}findClosestLink(e){for(;e&&e.tagName!=="A";)e=e.parentElement;return e}initializeTransport(e){const t="https://events.usermaven.com";if(!u())return new Pe(e.trackingHost||t,e);const s="XMLHttpRequest"in window,n=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&&n)return new z(e.trackingHost||t,e,this.logger);if(s)return new ve(e.trackingHost||t,e,this.logger);if(n)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 X(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var s,n;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=(s=this.cookieManager)==null?void 0:s.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;(n=this.cookieManager)==null||n.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 s=e.id;if(this.persistence.set("userId",s),this.persistence.set("userProps",e),!t){const n={...e,anonymous_id:this.anonymousId};await this.track("user_identify",n)}this.logger.info("User identified:",e)}track(e,t,s=!1){this.trackInternal(e,t,s)}trackInternal(e,t,s=!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(s){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 s=this.persistence.get("userProps")||{},n=this.persistence.get("companyProps")||(s==null?void 0:s.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,...s},...n&&{company:n},ids:this.getThirdPartyIds(),utc_time:new Date().toISOString(),local_tz_offset:new Date().getTimezoneOffset(),api_key:this.config.key,src:"usermaven",event_type:e,namespace:this.namespace,...o,...c};if(e==="$autocapture"){const 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 s=e.$elements||[];return s.length&&(t={...s[0]}),t.el_text=t.$el_text||"",t.event_type=e.$event_type||"",["$ce_version","$event_type","$initial_referrer","$initial_referring_domain","$referrer","$referring_domain","$elements"].forEach(n=>{delete t[n]}),delete t.$el_text,delete t.nth_child,delete t.nth_of_type,t}getCookie(e){var t;return((t=this.cookieManager)==null?void 0:t.get(e))||null}getThirdPartyIds(){const e={};if(u()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=ge(window.location.search);return["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(n=>{t[n]&&(e[n.replace("utm_","")]=t[n])}),e}pageview(){u()?this.track("pageview",{url:window.location.href,referrer:document.referrer,title:document.title},!0):this.logger.warn("Pageview tracking is not available in server-side environments")}setupPageLeaveTracking(){if(!u())return;let e=!1,t=!1;const s=()=>{!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&&s()});const n=history.pushState;history.pushState=function(){return s(),n.apply(this,arguments)},window.addEventListener("popstate",s)}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 s=t==null?void 0:t.eventType,n=(t==null?void 0:t.persist)??!0;if(s){let r=this.persistence.get(`props_${s}`)||{};r={...r,...e},this.persistence.set(`props_${s}`,r)}else{let r=this.persistence.get("global_props")||{};r={...r,...e},this.persistence.set("global_props",r)}n&&this.persistence.save(),this.logger.debug("Properties set",{properties:e,eventType:s||"global",persist:n})}setUserId(e){this.persistence.set("userId",e);let t=this.persistence.get("userProps")||{};t.id=e,this.persistence.set("userProps",t),this.persistence.save()}unset(e,t){const s=t==null?void 0:t.eventType,n=(t==null?void 0:t.persist)??!0;if(s){let r=this.persistence.get(`props_${s}`)||{};delete r[e],this.persistence.set(`props_${s}`,r)}else{let r=this.persistence.get("global_props")||{};delete r[e],this.persistence.set("global_props",r)}n&&this.persistence.save(),this.logger.debug(`Property unset: ${e}`,`Event type: ${s||"global"}`)}}function K(){return typeof window<"u"&&typeof window.define=="function"&&window.define.amd}function Ee(){return K()?window.define:void 0}function P(i){const e=JSON.parse(JSON.stringify(i)),t=R(e),s={...q,...t};if(!s.key)throw new Error("API key is required!");if(!s.trackingHost)throw new Error("Tracking host is required!");return new b(s)}function $e(i){var n;const e={key:i.getAttribute("data-key")||void 0,trackingHost:i.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:pe(i.getAttribute("data-log-level")),autocapture:i.getAttribute("data-autocapture")==="true",formTracking:i.getAttribute("data-form-tracking")==="false"?!1:i.getAttribute("data-form-tracking")==="true"?"all":i.getAttribute("data-form-tracking"),autoPageview:i.getAttribute("data-auto-pageview")==="true",useBeaconApi:i.getAttribute("data-use-beacon-api")==="true",forceUseFetch:i.getAttribute("data-force-use-fetch")==="true",gaHook:i.getAttribute("data-ga-hook")==="true",segmentHook:i.getAttribute("data-segment-hook")==="true",randomizeUrl:i.getAttribute("data-randomize-url")==="true",capture3rdPartyCookies:i.getAttribute("data-capture-3rd-party-cookies")==="false"?!1:void 0,idMethod:i.getAttribute("data-id-method")||void 0,privacyPolicy:i.getAttribute("data-privacy-policy")==="strict"?"strict":void 0,ipPolicy:i.getAttribute("data-ip-policy")||void 0,cookiePolicy:i.getAttribute("data-cookie-policy")||void 0,minSendTimeout:parseInt(i.getAttribute("data-min-send-timeout")||"",10)||void 0,maxSendTimeout:parseInt(i.getAttribute("data-max-send-timeout")||"",10)||void 0,maxSendAttempts:parseInt(i.getAttribute("data-max-send-attempts")||"",10)||void 0,propertiesStringMaxLength:parseInt(i.getAttribute("data-properties-string-max-length")||"",10)||null,propertyBlacklist:((n=i.getAttribute("data-property-blacklist"))==null?void 0:n.split(","))||void 0,exclude:i.getAttribute("data-exclude")||void 0,namespace:i.getAttribute("data-namespace")||void 0,crossDomainLinking:i.getAttribute("data-cross-domain-linking")!=="false",domains:i.getAttribute("data-domains")||void 0,maskAllText:i.getAttribute("data-mask-all-text")==="true",maskAllElementAttributes:i.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),s=e.namespace||"usermaven";return u()&&e.autoPageview!==!1&&t.pageview(),Se(s,t),t}function Se(i,e){let t=!1;const s=[],n=[];function r(){for(;s.length>0;){const a=s.shift();a&&window[i].apply(null,a)}}function o(){n.forEach(a=>a()),n.length=0}window[i]=function(...a){const h=a[0];if(h==="onLoad"){typeof a[1]=="function"&&(t?a[1]():n.push(a[1]));return}if(!t){s.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=`${i}Q`,l=window[c]||[];for(window[c]=l,l.push=function(...a){return window[i].apply(null,a),Array.prototype.push.apply(this,a)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${i} is ready`)},0);l.length>0;){const a=l.shift();a&&s.push(a)}}let B=!1,H=null;if(u()){const i=Ee();i&&i("usermaven",[],function(){return{usermavenClient:P,UsermavenClient:b,LogLevel:f,getScriptTagClient:()=>H}}),typeof window<"u"&&(window.usermavenClient=P,window.UsermavenClient=b,window.usermavenScriptTagClient=()=>H),function(e,t){const s=e.currentScript;function n(){return B||!s||!s.hasAttribute("data-key")||s.getAttribute("data-no-auto-init")==="true"?!1:s.src.includes("lib.js")}function r(){n()&&(console.log("[Usermaven] Auto-initializing from script tag"),H=$e(s),B=!0)}typeof t<"u"&&s&&(e.readyState==="loading"?e.addEventListener("DOMContentLoaded",r):r())}(document,window)}typeof module<"u"&&module.exports&&!K()&&(module.exports={usermavenClient:P,UsermavenClient:b,Config:void 0,UserProps:void 0,EventPayload:void 0,LogLevel:f,ClientProperties:void 0});exports.LogLevel=f;exports.UsermavenClient=b;exports.usermavenClient=P;
|
package/dist/usermaven.es.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
2
|
-
class
|
|
1
|
+
var p = /* @__PURE__ */ ((i) => (i[i.DEBUG = 0] = "DEBUG", i[i.INFO = 1] = "INFO", i[i.WARN = 2] = "WARN", i[i.ERROR = 3] = "ERROR", i))(p || {});
|
|
2
|
+
class Z {
|
|
3
3
|
constructor(e) {
|
|
4
4
|
this.level = e;
|
|
5
5
|
}
|
|
@@ -17,10 +17,10 @@ class W {
|
|
|
17
17
|
}
|
|
18
18
|
}
|
|
19
19
|
function d(i = 0) {
|
|
20
|
-
return new
|
|
20
|
+
return new Z(i);
|
|
21
21
|
}
|
|
22
|
-
const
|
|
23
|
-
logLevel:
|
|
22
|
+
const q = {
|
|
23
|
+
logLevel: p.ERROR,
|
|
24
24
|
useBeaconApi: !1,
|
|
25
25
|
forceUseFetch: !1,
|
|
26
26
|
trackingHost: "t.usermaven.com",
|
|
@@ -45,7 +45,7 @@ const F = {
|
|
|
45
45
|
maskAllText: !1,
|
|
46
46
|
maskAllElementAttributes: !1
|
|
47
47
|
};
|
|
48
|
-
class
|
|
48
|
+
class j {
|
|
49
49
|
constructor(e) {
|
|
50
50
|
this.domain = e, this.cookieDomain = this.getCookieDomain();
|
|
51
51
|
}
|
|
@@ -94,40 +94,40 @@ class X {
|
|
|
94
94
|
return s ? s[0] : "";
|
|
95
95
|
}
|
|
96
96
|
}
|
|
97
|
-
const
|
|
98
|
-
function
|
|
97
|
+
const ee = Object.prototype, te = ee.hasOwnProperty, ie = Array.prototype, E = ie.forEach, N = {};
|
|
98
|
+
function se(i, e, t) {
|
|
99
99
|
if (Array.isArray(i)) {
|
|
100
100
|
if (E && i.forEach === E)
|
|
101
101
|
i.forEach(e, t);
|
|
102
102
|
else if ("length" in i && i.length === +i.length) {
|
|
103
103
|
for (let s = 0, n = i.length; s < n; s++)
|
|
104
|
-
if (s in i && e.call(t, i[s], s) ===
|
|
104
|
+
if (s in i && e.call(t, i[s], s) === N)
|
|
105
105
|
return;
|
|
106
106
|
}
|
|
107
107
|
}
|
|
108
108
|
}
|
|
109
|
-
const
|
|
109
|
+
const O = function(i) {
|
|
110
110
|
return i.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
|
|
111
|
-
},
|
|
111
|
+
}, ne = function(i) {
|
|
112
112
|
for (const e in i)
|
|
113
113
|
typeof i[e] == "function" && (i[e] = i[e].bind(i));
|
|
114
114
|
};
|
|
115
|
-
function
|
|
115
|
+
function g(i, e, t) {
|
|
116
116
|
if (i != null) {
|
|
117
117
|
if (E && Array.isArray(i) && i.forEach === E)
|
|
118
118
|
i.forEach(e, t);
|
|
119
119
|
else if ("length" in i && i.length === +i.length) {
|
|
120
120
|
for (let s = 0, n = i.length; s < n; s++)
|
|
121
|
-
if (s in i && e.call(t, i[s], s) ===
|
|
121
|
+
if (s in i && e.call(t, i[s], s) === N)
|
|
122
122
|
return;
|
|
123
123
|
} else
|
|
124
124
|
for (const s in i)
|
|
125
|
-
if (
|
|
125
|
+
if (te.call(i, s) && e.call(t, i[s], s) === N)
|
|
126
126
|
return;
|
|
127
127
|
}
|
|
128
128
|
}
|
|
129
|
-
const
|
|
130
|
-
return
|
|
129
|
+
const re = function(i, ...e) {
|
|
130
|
+
return se(e, function(t) {
|
|
131
131
|
for (const s in t)
|
|
132
132
|
t[s] !== void 0 && (i[s] = t[s]);
|
|
133
133
|
}), i;
|
|
@@ -135,15 +135,15 @@ const ee = function(i, ...e) {
|
|
|
135
135
|
function _(i, e) {
|
|
136
136
|
return i.indexOf(e) !== -1;
|
|
137
137
|
}
|
|
138
|
-
const
|
|
138
|
+
const oe = function(i) {
|
|
139
139
|
try {
|
|
140
140
|
return /^\s*\bfunction\b/.test(i);
|
|
141
141
|
} catch {
|
|
142
142
|
return !1;
|
|
143
143
|
}
|
|
144
|
-
},
|
|
144
|
+
}, ae = function(i) {
|
|
145
145
|
return i === void 0;
|
|
146
|
-
},
|
|
146
|
+
}, y = function() {
|
|
147
147
|
const i = function(s, n, r, o, c) {
|
|
148
148
|
if (!s) {
|
|
149
149
|
d().error("No valid element provided to register_event");
|
|
@@ -161,7 +161,7 @@ const te = function(i) {
|
|
|
161
161
|
if (o = o || t(window.event), !o)
|
|
162
162
|
return;
|
|
163
163
|
let c = !0, l;
|
|
164
|
-
|
|
164
|
+
oe(r) && (l = r(o));
|
|
165
165
|
const a = n.call(s, o);
|
|
166
166
|
return (l === !1 || a === !1) && (c = !1), c;
|
|
167
167
|
};
|
|
@@ -174,7 +174,7 @@ const te = function(i) {
|
|
|
174
174
|
}, t.stopPropagation = function() {
|
|
175
175
|
this.cancelBubble = !0;
|
|
176
176
|
}, i;
|
|
177
|
-
}(),
|
|
177
|
+
}(), ce = function(i) {
|
|
178
178
|
return function(...e) {
|
|
179
179
|
try {
|
|
180
180
|
return i.apply(this, e);
|
|
@@ -182,11 +182,11 @@ const te = function(i) {
|
|
|
182
182
|
d().error("Implementation error. Please turn on debug and contact support@usermaven.com.", t);
|
|
183
183
|
}
|
|
184
184
|
};
|
|
185
|
-
},
|
|
185
|
+
}, V = function(i) {
|
|
186
186
|
for (const e in i)
|
|
187
|
-
typeof i[e] == "function" && (i[e] =
|
|
187
|
+
typeof i[e] == "function" && (i[e] = ce(i[e]));
|
|
188
188
|
};
|
|
189
|
-
function
|
|
189
|
+
function D(i) {
|
|
190
190
|
for (let e in i)
|
|
191
191
|
(i[e] === "" || i[e] === null || i[e] === void 0 || typeof i[e] == "object" && Object.keys(i[e]).length === 0) && delete i[e];
|
|
192
192
|
return i;
|
|
@@ -198,20 +198,20 @@ function u() {
|
|
|
198
198
|
return d().warn("window is not available"), !1;
|
|
199
199
|
}
|
|
200
200
|
}
|
|
201
|
-
function
|
|
201
|
+
function m(i = 5) {
|
|
202
202
|
const e = new Uint8Array(i);
|
|
203
203
|
return crypto.getRandomValues(e), Array.from(e, (t) => t.toString(36).padStart(2, "0")).join("").slice(0, i);
|
|
204
204
|
}
|
|
205
|
-
function
|
|
205
|
+
function le(i) {
|
|
206
206
|
return i.replace(
|
|
207
207
|
/([-_][a-z])/g,
|
|
208
208
|
(e) => e.toUpperCase().replace("-", "").replace("_", "")
|
|
209
209
|
);
|
|
210
210
|
}
|
|
211
|
-
function
|
|
212
|
-
return typeof i != "object" || i === null ? i : Array.isArray(i) ? i.map(
|
|
213
|
-
const s =
|
|
214
|
-
return e[s] =
|
|
211
|
+
function R(i) {
|
|
212
|
+
return typeof i != "object" || i === null ? i : Array.isArray(i) ? i.map(R) : Object.keys(i).reduce((e, t) => {
|
|
213
|
+
const s = le(t);
|
|
214
|
+
return e[s] = R(i[t]), e;
|
|
215
215
|
}, {});
|
|
216
216
|
}
|
|
217
217
|
function $(i) {
|
|
@@ -224,37 +224,37 @@ function $(i) {
|
|
|
224
224
|
return "";
|
|
225
225
|
}
|
|
226
226
|
}
|
|
227
|
-
function
|
|
227
|
+
function U(i) {
|
|
228
228
|
let e = "";
|
|
229
|
-
return
|
|
230
|
-
|
|
231
|
-
}),
|
|
229
|
+
return L(i) && !W(i) && i.childNodes && i.childNodes.length && g(i.childNodes, function(t) {
|
|
230
|
+
Q(t) && t.textContent && (e += O(t.textContent).split(/(\s+)/).filter(P).join("").replace(/[\r\n]/g, " ").replace(/[ ]+/g, " ").substring(0, 255));
|
|
231
|
+
}), O(e);
|
|
232
232
|
}
|
|
233
|
-
function
|
|
233
|
+
function J(i) {
|
|
234
234
|
return !!i && i.nodeType === 1;
|
|
235
235
|
}
|
|
236
|
-
function
|
|
236
|
+
function f(i, e) {
|
|
237
237
|
return !!i && !!i.tagName && i.tagName.toLowerCase() === e.toLowerCase();
|
|
238
238
|
}
|
|
239
|
-
function
|
|
239
|
+
function Q(i) {
|
|
240
240
|
return !!i && i.nodeType === 3;
|
|
241
241
|
}
|
|
242
|
-
function
|
|
242
|
+
function I(i) {
|
|
243
243
|
return !!i && i.nodeType === 11;
|
|
244
244
|
}
|
|
245
245
|
const b = ["a", "button", "form", "input", "select", "textarea", "label"];
|
|
246
|
-
function
|
|
247
|
-
if (!i ||
|
|
246
|
+
function ue(i, e) {
|
|
247
|
+
if (!i || f(i, "html") || !J(i))
|
|
248
248
|
return !1;
|
|
249
249
|
let t = i;
|
|
250
|
-
for (; t && !
|
|
250
|
+
for (; t && !f(t, "body"); ) {
|
|
251
251
|
if (t.classList && t.classList.contains("um-no-capture"))
|
|
252
252
|
return !1;
|
|
253
|
-
t.parentNode &&
|
|
253
|
+
t.parentNode && I(t.parentNode) ? t = t.parentNode.host : t = t.parentNode;
|
|
254
254
|
}
|
|
255
255
|
let s = !1;
|
|
256
|
-
for (t = i; t && !
|
|
257
|
-
if (t.parentNode &&
|
|
256
|
+
for (t = i; t && !f(t, "body"); ) {
|
|
257
|
+
if (t.parentNode && I(t.parentNode)) {
|
|
258
258
|
t = t.parentNode.host, t && b.indexOf(t.tagName.toLowerCase()) > -1 && (s = !0);
|
|
259
259
|
continue;
|
|
260
260
|
}
|
|
@@ -286,8 +286,8 @@ function re(i, e) {
|
|
|
286
286
|
return s ? e.type === "click" : e.type === "click" && (b.indexOf(r) > -1 || i.getAttribute("contenteditable") === "true");
|
|
287
287
|
}
|
|
288
288
|
}
|
|
289
|
-
function
|
|
290
|
-
for (let s = i; s.parentNode && !
|
|
289
|
+
function L(i) {
|
|
290
|
+
for (let s = i; s.parentNode && !f(s, "body"); s = s.parentNode) {
|
|
291
291
|
const n = $(s).split(" ");
|
|
292
292
|
if (_(n, "ph-sensitive") || _(n, "ph-no-capture"))
|
|
293
293
|
return !1;
|
|
@@ -305,23 +305,23 @@ function O(i) {
|
|
|
305
305
|
const t = i.name || i.id || "";
|
|
306
306
|
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, "")));
|
|
307
307
|
}
|
|
308
|
-
function
|
|
308
|
+
function W(i) {
|
|
309
309
|
const e = ["button", "checkbox", "submit", "reset"];
|
|
310
|
-
return !!(
|
|
310
|
+
return !!(f(i, "input") && !e.includes(i.type) || f(i, "select") || f(i, "textarea") || i.getAttribute("contenteditable") === "true");
|
|
311
311
|
}
|
|
312
312
|
function P(i) {
|
|
313
|
-
return !(i === null ||
|
|
313
|
+
return !(i === null || ae(i) || typeof i == "string" && (i = O(i), /^(?:(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((i || "").replace(/[- ]/g, "")) || /(^\d{3}-?\d{2}-?\d{4}$)/.test(i)));
|
|
314
314
|
}
|
|
315
|
-
function
|
|
315
|
+
function he(i) {
|
|
316
316
|
return typeof i == "string" ? i.substring(0, 10) === "_ngcontent" || i.substring(0, 7) === "_nghost" : !1;
|
|
317
317
|
}
|
|
318
|
-
function
|
|
319
|
-
return
|
|
318
|
+
function x() {
|
|
319
|
+
return m(10);
|
|
320
320
|
}
|
|
321
|
-
function
|
|
321
|
+
function de(i) {
|
|
322
322
|
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(i).toLowerCase());
|
|
323
323
|
}
|
|
324
|
-
function
|
|
324
|
+
function fe(i, e) {
|
|
325
325
|
let t;
|
|
326
326
|
return function(...s) {
|
|
327
327
|
const n = () => {
|
|
@@ -330,7 +330,7 @@ function ce(i, e) {
|
|
|
330
330
|
clearTimeout(t), t = setTimeout(n, e);
|
|
331
331
|
};
|
|
332
332
|
}
|
|
333
|
-
function
|
|
333
|
+
function ge(i) {
|
|
334
334
|
const e = {}, t = i.replace(/^\?/, "").split("&");
|
|
335
335
|
for (let s = 0; s < t.length; s++) {
|
|
336
336
|
const n = t[s].split("=");
|
|
@@ -338,25 +338,25 @@ function le(i) {
|
|
|
338
338
|
}
|
|
339
339
|
return e;
|
|
340
340
|
}
|
|
341
|
-
function
|
|
341
|
+
function F(i) {
|
|
342
342
|
return typeof i == "string" || i instanceof String;
|
|
343
343
|
}
|
|
344
|
-
function
|
|
344
|
+
function v(i) {
|
|
345
345
|
return i !== null && typeof i == "object" && i.constructor === Object;
|
|
346
346
|
}
|
|
347
|
-
function
|
|
347
|
+
function pe(i) {
|
|
348
348
|
if (i === null)
|
|
349
|
-
return
|
|
350
|
-
const e = i.toUpperCase(), t =
|
|
351
|
-
return t || t === 0 ? t :
|
|
349
|
+
return p.ERROR;
|
|
350
|
+
const e = i.toUpperCase(), t = p[e];
|
|
351
|
+
return t || t === 0 ? t : p.ERROR;
|
|
352
352
|
}
|
|
353
|
-
const
|
|
353
|
+
const me = () => {
|
|
354
354
|
let i = "false";
|
|
355
355
|
return typeof window < "u" && window.localStorage && (i = localStorage.getItem("um_exclusion")), !(i == null || i === "false");
|
|
356
356
|
};
|
|
357
|
-
class
|
|
357
|
+
class ye {
|
|
358
358
|
constructor(e) {
|
|
359
|
-
this.maxScrollDepth = 0, this.milestones = [25, 50, 75, 90], this.lastScrollDepth = 0, this.client = e, this.documentElement = document.documentElement, this.debouncedHandleScroll =
|
|
359
|
+
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();
|
|
360
360
|
}
|
|
361
361
|
initializeEventListener() {
|
|
362
362
|
window.addEventListener("scroll", this.debouncedHandleScroll);
|
|
@@ -405,9 +405,9 @@ class de {
|
|
|
405
405
|
});
|
|
406
406
|
}
|
|
407
407
|
}
|
|
408
|
-
const
|
|
408
|
+
const A = class A {
|
|
409
409
|
constructor(e, t, s = d()) {
|
|
410
|
-
this.logger = s, this.scrollDepth = null, this.customProperties = [], this.client = e, this.options = t, this.scrollDepth = new
|
|
410
|
+
this.logger = s, this.scrollDepth = null, this.customProperties = [], this.client = e, this.options = t, this.scrollDepth = new ye(e), ne(this), V(this);
|
|
411
411
|
}
|
|
412
412
|
init() {
|
|
413
413
|
if (!(document && document.body)) {
|
|
@@ -420,7 +420,7 @@ const C = class C {
|
|
|
420
420
|
const e = (t) => {
|
|
421
421
|
t = t || window.event, this.captureEvent(t);
|
|
422
422
|
};
|
|
423
|
-
|
|
423
|
+
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);
|
|
424
424
|
}
|
|
425
425
|
isPageRefresh() {
|
|
426
426
|
if ("PerformanceNavigationTiming" in window) {
|
|
@@ -433,15 +433,15 @@ const C = class C {
|
|
|
433
433
|
captureEvent(e) {
|
|
434
434
|
var s, n;
|
|
435
435
|
let t = this.getEventTarget(e);
|
|
436
|
-
if (
|
|
436
|
+
if (Q(t) && (t = t.parentNode || null), e.type === "scroll")
|
|
437
437
|
return (s = this.scrollDepth) == null || s.track(), !0;
|
|
438
438
|
if (e.type === "visibilitychange" && document.visibilityState === "hidden" || e.type === "popstate")
|
|
439
439
|
return this.isPageRefresh() || (n = this.scrollDepth) == null || n.send(), !0;
|
|
440
|
-
if (t &&
|
|
440
|
+
if (t && ue(t, e)) {
|
|
441
441
|
const r = [t];
|
|
442
442
|
let o = t;
|
|
443
|
-
for (; o.parentNode && !
|
|
444
|
-
if (
|
|
443
|
+
for (; o.parentNode && !f(o, "body"); ) {
|
|
444
|
+
if (I(o.parentNode)) {
|
|
445
445
|
r.push(o.parentNode.host), o = o.parentNode.host;
|
|
446
446
|
continue;
|
|
447
447
|
}
|
|
@@ -449,20 +449,20 @@ const C = class C {
|
|
|
449
449
|
}
|
|
450
450
|
const c = [];
|
|
451
451
|
let l, a = !1;
|
|
452
|
-
if (
|
|
453
|
-
const
|
|
454
|
-
|
|
455
|
-
const
|
|
456
|
-
_(
|
|
452
|
+
if (g(r, (k) => {
|
|
453
|
+
const G = L(k);
|
|
454
|
+
k.tagName.toLowerCase() === "a" && (l = k.getAttribute("href"), l = G && P(l) && l);
|
|
455
|
+
const Y = $(k).split(" ");
|
|
456
|
+
_(Y, "ph-no-capture") && (a = !0), c.push(
|
|
457
457
|
this.getPropertiesFromElement(
|
|
458
|
-
|
|
458
|
+
k,
|
|
459
459
|
this.options.maskAllElementAttributes ?? !1,
|
|
460
460
|
this.options.maskAllText ?? !1
|
|
461
461
|
)
|
|
462
462
|
);
|
|
463
|
-
}), this.options.maskAllText || (c[0].$el_text =
|
|
463
|
+
}), this.options.maskAllText || (c[0].$el_text = U(t)), l && (c[0].attr__href = l), a)
|
|
464
464
|
return !1;
|
|
465
|
-
const h =
|
|
465
|
+
const h = re(
|
|
466
466
|
this.getDefaultProperties(e.type),
|
|
467
467
|
{
|
|
468
468
|
$elements: c
|
|
@@ -474,18 +474,18 @@ const C = class C {
|
|
|
474
474
|
}
|
|
475
475
|
getCustomProperties(e) {
|
|
476
476
|
const t = {};
|
|
477
|
-
return
|
|
478
|
-
|
|
477
|
+
return g(this.customProperties, (s) => {
|
|
478
|
+
g(s.event_selectors, (n) => {
|
|
479
479
|
const r = document.querySelectorAll(n);
|
|
480
|
-
|
|
481
|
-
_(e, o) &&
|
|
480
|
+
g(r, (o) => {
|
|
481
|
+
_(e, o) && L(o) && (t[s.name] = this.extractCustomPropertyValue(s));
|
|
482
482
|
});
|
|
483
483
|
});
|
|
484
484
|
}), t;
|
|
485
485
|
}
|
|
486
486
|
extractCustomPropertyValue(e) {
|
|
487
487
|
const t = [];
|
|
488
|
-
return
|
|
488
|
+
return g(document.querySelectorAll(e.css_selector), function(s) {
|
|
489
489
|
let n;
|
|
490
490
|
["input", "select"].indexOf(s.tagName.toLowerCase()) > -1 ? n = s.value : s.textContent && (n = s.textContent), P(n) && t.push(n);
|
|
491
491
|
}), t.join(", ");
|
|
@@ -498,12 +498,12 @@ const C = class C {
|
|
|
498
498
|
const n = e.tagName.toLowerCase(), r = {
|
|
499
499
|
tag_name: n
|
|
500
500
|
};
|
|
501
|
-
b.indexOf(n) > -1 && !s && (r.$el_text =
|
|
501
|
+
b.indexOf(n) > -1 && !s && (r.$el_text = U(e));
|
|
502
502
|
const o = $(e);
|
|
503
503
|
o.length > 0 && (r.classes = o.split(" ").filter(function(h) {
|
|
504
504
|
return h !== "";
|
|
505
|
-
})),
|
|
506
|
-
|
|
505
|
+
})), g(e.attributes, function(h) {
|
|
506
|
+
W(e) && ["name", "id", "class"].indexOf(h.name) === -1 || !t && P(h.value) && !he(h.name) && (r["attr__" + h.name] = h.value);
|
|
507
507
|
});
|
|
508
508
|
let c = 1, l = 1, a = e;
|
|
509
509
|
for (; a = this.previousElementSibling(a); )
|
|
@@ -517,7 +517,7 @@ const C = class C {
|
|
|
517
517
|
let t = e;
|
|
518
518
|
do
|
|
519
519
|
t = t.previousSibling;
|
|
520
|
-
while (t && !
|
|
520
|
+
while (t && !J(t));
|
|
521
521
|
return t;
|
|
522
522
|
}
|
|
523
523
|
}
|
|
@@ -539,9 +539,9 @@ const C = class C {
|
|
|
539
539
|
return n % t < s;
|
|
540
540
|
}
|
|
541
541
|
};
|
|
542
|
-
|
|
543
|
-
let S =
|
|
544
|
-
class
|
|
542
|
+
A.FORCE_CAPTURE_ATTR = "data-um-force-capture", A.PREVENT_CAPTURE_ATTR = "data-um-no-capture";
|
|
543
|
+
let S = A;
|
|
544
|
+
class we {
|
|
545
545
|
constructor(e) {
|
|
546
546
|
this.client = e, this.lastPageUrl = window.location.href, this.trackInitialPageview(), this.initializePageviewTracking();
|
|
547
547
|
}
|
|
@@ -570,7 +570,7 @@ class ge {
|
|
|
570
570
|
}));
|
|
571
571
|
}
|
|
572
572
|
}
|
|
573
|
-
class
|
|
573
|
+
class ke {
|
|
574
574
|
constructor(e, t, s = d()) {
|
|
575
575
|
this.trackingHost = e, this.logger = s, this.config = t;
|
|
576
576
|
}
|
|
@@ -583,12 +583,12 @@ class fe {
|
|
|
583
583
|
}
|
|
584
584
|
constructUrl(e) {
|
|
585
585
|
const t = this.config.cookiePolicy !== "keep" ? `&cookie_policy=${this.config.cookiePolicy}` : "", s = this.config.ipPolicy !== "keep" ? `&ip_policy=${this.config.ipPolicy}` : "", n = u() ? "/api/v1/event" : "/api/v1/s2s/event";
|
|
586
|
-
return this.config.randomizeUrl ? `${this.trackingHost}/api.${
|
|
586
|
+
return this.config.randomizeUrl ? `${this.trackingHost}/api.${m()}?p_${m()}=${e}${t}${s}` : `${this.trackingHost}${n}?token=${e}${t}${s}`;
|
|
587
587
|
}
|
|
588
588
|
// Note: Beacon API doesn't support custom headers, so we can't use them here.
|
|
589
589
|
// If custom headers are crucial, you might want to fall back to XHR or Fetch in those cases.
|
|
590
590
|
}
|
|
591
|
-
class
|
|
591
|
+
class z {
|
|
592
592
|
constructor(e, t, s = d()) {
|
|
593
593
|
this.trackingHost = e, this.logger = s, this.config = t;
|
|
594
594
|
}
|
|
@@ -607,7 +607,7 @@ class D {
|
|
|
607
607
|
}
|
|
608
608
|
constructUrl(e) {
|
|
609
609
|
const t = this.config.cookiePolicy !== "keep" ? `&cookie_policy=${this.config.cookiePolicy}` : "", s = this.config.ipPolicy !== "keep" ? `&ip_policy=${this.config.ipPolicy}` : "", n = u() ? "/api/v1/event" : "/api/v1/s2s/event";
|
|
610
|
-
return this.config.randomizeUrl ? `${this.trackingHost}/api.${
|
|
610
|
+
return this.config.randomizeUrl ? `${this.trackingHost}/api.${m()}?p_${m()}=${e}${t}${s}` : `${this.trackingHost}${n}?token=${e}${t}${s}`;
|
|
611
611
|
}
|
|
612
612
|
getCustomHeaders() {
|
|
613
613
|
return typeof this.config.customHeaders == "function" ? this.config.customHeaders() : this.config.customHeaders ? this.config.customHeaders : {};
|
|
@@ -616,7 +616,7 @@ class D {
|
|
|
616
616
|
this.logger.debug(`Response received. Status: ${e}, Body: ${t}`);
|
|
617
617
|
}
|
|
618
618
|
}
|
|
619
|
-
class
|
|
619
|
+
class ve {
|
|
620
620
|
constructor(e, t, s = d()) {
|
|
621
621
|
this.trackingHost = e, this.logger = s, this.config = t;
|
|
622
622
|
}
|
|
@@ -636,7 +636,7 @@ class pe {
|
|
|
636
636
|
}
|
|
637
637
|
constructUrl(e) {
|
|
638
638
|
const t = this.config.cookiePolicy !== "keep" ? `&cookie_policy=${this.config.cookiePolicy}` : "", s = this.config.ipPolicy !== "keep" ? `&ip_policy=${this.config.ipPolicy}` : "", n = u() ? "/api/v1/event" : "/api/v1/s2s/event";
|
|
639
|
-
return this.config.randomizeUrl ? `${this.trackingHost}/api.${
|
|
639
|
+
return this.config.randomizeUrl ? `${this.trackingHost}/api.${m()}?p_${m()}=${e}${t}${s}` : `${this.trackingHost}${n}?token=${e}${t}${s}`;
|
|
640
640
|
}
|
|
641
641
|
getCustomHeaders() {
|
|
642
642
|
return typeof this.config.customHeaders == "function" ? this.config.customHeaders() : this.config.customHeaders ? this.config.customHeaders : {};
|
|
@@ -645,7 +645,7 @@ class pe {
|
|
|
645
645
|
this.logger.debug(`Response received. Status: ${e}, Body: ${t}`);
|
|
646
646
|
}
|
|
647
647
|
}
|
|
648
|
-
class
|
|
648
|
+
class X {
|
|
649
649
|
constructor(e, t) {
|
|
650
650
|
this.storage = {}, this.prefix = `usermaven_${e}_`, this.load(), this.logger = t || d();
|
|
651
651
|
}
|
|
@@ -685,7 +685,7 @@ class V {
|
|
|
685
685
|
}
|
|
686
686
|
}
|
|
687
687
|
}
|
|
688
|
-
class
|
|
688
|
+
class _e {
|
|
689
689
|
constructor() {
|
|
690
690
|
this.storage = {};
|
|
691
691
|
}
|
|
@@ -704,10 +704,10 @@ class me {
|
|
|
704
704
|
this.storage = {};
|
|
705
705
|
}
|
|
706
706
|
}
|
|
707
|
-
class
|
|
707
|
+
class M {
|
|
708
708
|
// Default to true for server-side
|
|
709
709
|
constructor(e, t = 3, s = 1e3, n = 10, r = 1e3, o = d(), c = "default") {
|
|
710
|
-
this.transport = e, this.maxRetries = t, this.retryInterval = s, this.batchSize = n, this.batchInterval = r, this.logger = o, this.queue = [], this.processing = !1, this.batchTimeoutId = null, this.isOnline = !0, this.persistence = new
|
|
710
|
+
this.transport = e, this.maxRetries = t, this.retryInterval = s, this.batchSize = n, this.batchInterval = r, this.logger = o, this.queue = [], this.processing = !1, this.batchTimeoutId = null, this.isOnline = !0, this.persistence = new X(`offline_queue_${c}`), u() && (this.isOnline = navigator.onLine, this.loadQueueFromStorage(), this.initNetworkListeners(), this.scheduleBatch());
|
|
711
711
|
}
|
|
712
712
|
add(e) {
|
|
713
713
|
const t = { payload: e, retries: 0, timestamp: Date.now() };
|
|
@@ -751,9 +751,9 @@ class U {
|
|
|
751
751
|
u() && this.persistence.set("queue", JSON.stringify(this.queue));
|
|
752
752
|
}
|
|
753
753
|
}
|
|
754
|
-
class
|
|
754
|
+
class be {
|
|
755
755
|
constructor(e) {
|
|
756
|
-
this.clicks = [], this.threshold = 3, this.timeWindow = 2e3, this.distanceThreshold = 30, this.client = e, this.initializeEventListener(),
|
|
756
|
+
this.clicks = [], this.threshold = 3, this.timeWindow = 2e3, this.distanceThreshold = 30, this.client = e, this.initializeEventListener(), V(this);
|
|
757
757
|
}
|
|
758
758
|
initializeEventListener() {
|
|
759
759
|
document.addEventListener("click", this.handleClick.bind(this));
|
|
@@ -785,7 +785,7 @@ class ye {
|
|
|
785
785
|
}), this.clicks = [];
|
|
786
786
|
}
|
|
787
787
|
}
|
|
788
|
-
class
|
|
788
|
+
class Pe {
|
|
789
789
|
constructor(e, t, s = d()) {
|
|
790
790
|
this.trackingHost = e, this.logger = s, this.config = t;
|
|
791
791
|
}
|
|
@@ -821,7 +821,7 @@ class we {
|
|
|
821
821
|
return typeof this.config.customHeaders == "function" ? this.config.customHeaders() : this.config.customHeaders ? this.config.customHeaders : {};
|
|
822
822
|
}
|
|
823
823
|
}
|
|
824
|
-
class
|
|
824
|
+
class w {
|
|
825
825
|
constructor(e, t = "all", s = {}) {
|
|
826
826
|
this.instance = e, this.trackingType = t, this.options = s, document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", this.initialize.bind(this)) : this.initialize();
|
|
827
827
|
}
|
|
@@ -836,18 +836,18 @@ class y {
|
|
|
836
836
|
}
|
|
837
837
|
handleFormSubmit(e) {
|
|
838
838
|
const t = e.target, s = this._getFormDetails(t);
|
|
839
|
-
this.instance.track("$form",
|
|
839
|
+
this.instance.track("$form", D(s)), this.options.trackFieldChanges && this.trackFieldChanges(t);
|
|
840
840
|
}
|
|
841
841
|
trackFieldChanges(e) {
|
|
842
842
|
e.querySelectorAll("input, select, textarea").forEach((s) => {
|
|
843
843
|
s.addEventListener("change", (n) => {
|
|
844
844
|
const r = this._getFieldProps(n.target, 0);
|
|
845
|
-
this.instance.track("$form_field_change",
|
|
845
|
+
this.instance.track("$form_field_change", D(r));
|
|
846
846
|
});
|
|
847
847
|
});
|
|
848
848
|
}
|
|
849
849
|
static getInstance(e, t = "all", s = {}) {
|
|
850
|
-
return
|
|
850
|
+
return w.instance || (w.instance = new w(e, t, s)), w.instance;
|
|
851
851
|
}
|
|
852
852
|
_getFormDetails(e) {
|
|
853
853
|
const t = {
|
|
@@ -935,9 +935,9 @@ class y {
|
|
|
935
935
|
return e.slice(t, s + 1);
|
|
936
936
|
}
|
|
937
937
|
}
|
|
938
|
-
class
|
|
938
|
+
class C {
|
|
939
939
|
constructor(e) {
|
|
940
|
-
this.config = this.mergeConfig(e,
|
|
940
|
+
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(
|
|
941
941
|
this.transport,
|
|
942
942
|
this.config.maxSendAttempts || 3,
|
|
943
943
|
this.config.minSendTimeout || 1e3,
|
|
@@ -949,13 +949,13 @@ class ke {
|
|
|
949
949
|
), u() && this.initializeBrowserFeatures(), this.anonymousId = this.getOrCreateAnonymousId(), this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`);
|
|
950
950
|
}
|
|
951
951
|
initializeBrowserFeatures() {
|
|
952
|
-
if (this.cookieManager = new
|
|
952
|
+
if (this.cookieManager = new j(this.config.cookieDomain), this.config.autocapture && S.enabledForProject(this.config.key) && (this.autoCapture = new S(this, this.config, this.logger), this.autoCapture.init()), this.config.formTracking) {
|
|
953
953
|
const e = this.config.formTracking === !0 ? "all" : this.config.formTracking;
|
|
954
|
-
this.formTracking =
|
|
954
|
+
this.formTracking = w.getInstance(this, e || "none", {
|
|
955
955
|
trackFieldChanges: !1
|
|
956
956
|
});
|
|
957
957
|
}
|
|
958
|
-
this.config.autoPageview && (this.pageviewTracking = new
|
|
958
|
+
this.config.autoPageview && (this.pageviewTracking = new we(this)), this.config.crossDomainLinking && this.manageCrossDomainLinking(), this.config.rageClick && (this.rageClick = new be(this)), this.setupPageLeaveTracking();
|
|
959
959
|
}
|
|
960
960
|
/**
|
|
961
961
|
* Recursively merge the provided configuration with the existing defaultConfig
|
|
@@ -966,11 +966,11 @@ class ke {
|
|
|
966
966
|
const s = JSON.parse(JSON.stringify(e));
|
|
967
967
|
let n = { ...t, ...s };
|
|
968
968
|
return Object.keys(t).forEach((r) => {
|
|
969
|
-
|
|
969
|
+
v(t[r]) && (n[r] = this.mergeConfig(e[r], t[r]));
|
|
970
970
|
}), n;
|
|
971
971
|
}
|
|
972
972
|
init(e) {
|
|
973
|
-
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
|
|
973
|
+
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(
|
|
974
974
|
this.transport,
|
|
975
975
|
this.config.maxSendAttempts || 3,
|
|
976
976
|
this.config.minSendTimeout || 1e3,
|
|
@@ -1006,25 +1006,25 @@ class ke {
|
|
|
1006
1006
|
initializeTransport(e) {
|
|
1007
1007
|
const t = "https://events.usermaven.com";
|
|
1008
1008
|
if (!u())
|
|
1009
|
-
return new
|
|
1009
|
+
return new Pe(e.trackingHost || t, e);
|
|
1010
1010
|
const s = "XMLHttpRequest" in window, n = typeof fetch < "u", r = typeof navigator < "u" && "sendBeacon" in navigator;
|
|
1011
1011
|
if (e.useBeaconApi && r)
|
|
1012
|
-
return new
|
|
1012
|
+
return new ke(e.trackingHost || t, e, this.logger);
|
|
1013
1013
|
if (e.forceUseFetch && n)
|
|
1014
|
-
return new
|
|
1014
|
+
return new z(e.trackingHost || t, e, this.logger);
|
|
1015
1015
|
if (s)
|
|
1016
|
-
return new
|
|
1016
|
+
return new ve(e.trackingHost || t, e, this.logger);
|
|
1017
1017
|
if (n)
|
|
1018
|
-
return new
|
|
1018
|
+
return new z(e.trackingHost || t, e, this.logger);
|
|
1019
1019
|
throw new Error("No suitable transport method available");
|
|
1020
1020
|
}
|
|
1021
1021
|
initializePersistence() {
|
|
1022
|
-
return this.config.disableEventPersistence || !u() ? new
|
|
1022
|
+
return this.config.disableEventPersistence || !u() ? new _e() : new X(`${this.namespace}_${this.config.key}`, this.logger);
|
|
1023
1023
|
}
|
|
1024
1024
|
getOrCreateAnonymousId() {
|
|
1025
1025
|
var s, n;
|
|
1026
1026
|
if (!u())
|
|
1027
|
-
return
|
|
1027
|
+
return x();
|
|
1028
1028
|
if (this.config.privacyPolicy === "strict" || this.config.cookiePolicy === "strict")
|
|
1029
1029
|
return "";
|
|
1030
1030
|
const e = this.config.cookieName || `__eventn_id_${this.config.key}`;
|
|
@@ -1032,20 +1032,20 @@ class ke {
|
|
|
1032
1032
|
if (!t) {
|
|
1033
1033
|
if (this.config.crossDomainLinking) {
|
|
1034
1034
|
const c = new URLSearchParams(window.location.search).get("_um"), a = window.location.hash.substring(1).split("~"), h = a.length > 1 ? a[1] : void 0;
|
|
1035
|
-
t = c || h ||
|
|
1035
|
+
t = c || h || x();
|
|
1036
1036
|
}
|
|
1037
|
-
t || (t =
|
|
1037
|
+
t || (t = x());
|
|
1038
1038
|
const r = 365 * 10;
|
|
1039
1039
|
(n = this.cookieManager) == null || n.set(e, t, r, document.location.protocol !== "http:", !1);
|
|
1040
1040
|
}
|
|
1041
1041
|
return t;
|
|
1042
1042
|
}
|
|
1043
1043
|
async id(e, t = !1) {
|
|
1044
|
-
if (!
|
|
1044
|
+
if (!v(e))
|
|
1045
1045
|
throw new Error("User data must be an object");
|
|
1046
|
-
if (e.email && !
|
|
1046
|
+
if (e.email && !de(e.email))
|
|
1047
1047
|
throw new Error("Invalid email provided");
|
|
1048
|
-
if (!e.id || !
|
|
1048
|
+
if (!e.id || !F(e.id))
|
|
1049
1049
|
throw new Error("User ID must be a string");
|
|
1050
1050
|
const s = e.id;
|
|
1051
1051
|
if (this.persistence.set("userId", s), this.persistence.set("userProps", e), !t) {
|
|
@@ -1061,11 +1061,11 @@ class ke {
|
|
|
1061
1061
|
this.trackInternal(e, t, s);
|
|
1062
1062
|
}
|
|
1063
1063
|
trackInternal(e, t, s = !1) {
|
|
1064
|
-
if (
|
|
1064
|
+
if (me()) {
|
|
1065
1065
|
this.logger.debug("Tracking disabled due to um_exclusion setting");
|
|
1066
1066
|
return;
|
|
1067
1067
|
}
|
|
1068
|
-
if (!
|
|
1068
|
+
if (!F(e))
|
|
1069
1069
|
throw new Error("Event name must be a string");
|
|
1070
1070
|
if (t !== void 0 && (typeof t != "object" || t === null || Array.isArray(t)))
|
|
1071
1071
|
throw new Error("Event payload must be a non-null object and not an array");
|
|
@@ -1081,12 +1081,12 @@ class ke {
|
|
|
1081
1081
|
}
|
|
1082
1082
|
}
|
|
1083
1083
|
rawTrack(e) {
|
|
1084
|
-
if (!
|
|
1084
|
+
if (!v(e))
|
|
1085
1085
|
throw new Error("Event payload must be an object");
|
|
1086
1086
|
this.track("raw", e);
|
|
1087
1087
|
}
|
|
1088
1088
|
async group(e, t = !1) {
|
|
1089
|
-
if (!
|
|
1089
|
+
if (!v(e))
|
|
1090
1090
|
throw new Error("Company properties must be an object");
|
|
1091
1091
|
if (!e.id || !e.name || !e.created_at)
|
|
1092
1092
|
throw new Error("Company properties must include id, name, and created_at");
|
|
@@ -1141,7 +1141,7 @@ class ke {
|
|
|
1141
1141
|
return e;
|
|
1142
1142
|
}
|
|
1143
1143
|
getUtmParams() {
|
|
1144
|
-
const e = {}, t =
|
|
1144
|
+
const e = {}, t = ge(window.location.search);
|
|
1145
1145
|
return ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"].forEach((n) => {
|
|
1146
1146
|
t[n] && (e[n.replace("utm_", "")] = t[n]);
|
|
1147
1147
|
}), e;
|
|
@@ -1189,7 +1189,7 @@ class ke {
|
|
|
1189
1189
|
this.logger.info("core state reset", { resetAnonId: e, namespace: this.namespace });
|
|
1190
1190
|
}
|
|
1191
1191
|
set(e, t) {
|
|
1192
|
-
if (!
|
|
1192
|
+
if (!v(e))
|
|
1193
1193
|
throw new Error("Properties must be an object");
|
|
1194
1194
|
const s = t == null ? void 0 : t.eventType, n = (t == null ? void 0 : t.persist) ?? !0;
|
|
1195
1195
|
if (s) {
|
|
@@ -1222,20 +1222,26 @@ class ke {
|
|
|
1222
1222
|
n && this.persistence.save(), this.logger.debug(`Property unset: ${e}`, `Event type: ${s || "global"}`);
|
|
1223
1223
|
}
|
|
1224
1224
|
}
|
|
1225
|
-
function
|
|
1226
|
-
|
|
1225
|
+
function K() {
|
|
1226
|
+
return typeof window < "u" && typeof window.define == "function" && window.define.amd;
|
|
1227
|
+
}
|
|
1228
|
+
function Ee() {
|
|
1229
|
+
return K() ? window.define : void 0;
|
|
1230
|
+
}
|
|
1231
|
+
function T(i) {
|
|
1232
|
+
const e = JSON.parse(JSON.stringify(i)), t = R(e), s = { ...q, ...t };
|
|
1227
1233
|
if (!s.key)
|
|
1228
1234
|
throw new Error("API key is required!");
|
|
1229
1235
|
if (!s.trackingHost)
|
|
1230
1236
|
throw new Error("Tracking host is required!");
|
|
1231
|
-
return new
|
|
1237
|
+
return new C(s);
|
|
1232
1238
|
}
|
|
1233
|
-
function
|
|
1239
|
+
function $e(i) {
|
|
1234
1240
|
var n;
|
|
1235
1241
|
const e = {
|
|
1236
1242
|
key: i.getAttribute("data-key") || void 0,
|
|
1237
1243
|
trackingHost: i.getAttribute("data-tracking-host") || "https://events.usermaven.com",
|
|
1238
|
-
logLevel:
|
|
1244
|
+
logLevel: pe(i.getAttribute("data-log-level")),
|
|
1239
1245
|
autocapture: i.getAttribute("data-autocapture") === "true",
|
|
1240
1246
|
formTracking: i.getAttribute("data-form-tracking") === "false" ? !1 : i.getAttribute("data-form-tracking") === "true" ? "all" : i.getAttribute("data-form-tracking"),
|
|
1241
1247
|
autoPageview: i.getAttribute("data-auto-pageview") === "true",
|
|
@@ -1262,10 +1268,10 @@ function _e(i) {
|
|
|
1262
1268
|
maskAllElementAttributes: i.getAttribute("data-mask-all-element-attributes") === "true"
|
|
1263
1269
|
};
|
|
1264
1270
|
e.privacyPolicy === "strict" && (e.cookiePolicy = "strict", e.ipPolicy = "strict"), e.cookiePolicy === "comply" && e.useBeaconApi && (e.cookiePolicy = "strict");
|
|
1265
|
-
const t =
|
|
1266
|
-
u() && t.pageview(),
|
|
1271
|
+
const t = T(e), s = e.namespace || "usermaven";
|
|
1272
|
+
return u() && e.autoPageview !== !1 && t.pageview(), Se(s, t), t;
|
|
1267
1273
|
}
|
|
1268
|
-
function
|
|
1274
|
+
function Se(i, e) {
|
|
1269
1275
|
let t = !1;
|
|
1270
1276
|
const s = [], n = [];
|
|
1271
1277
|
function r() {
|
|
@@ -1301,15 +1307,39 @@ function be(i, e) {
|
|
|
1301
1307
|
a && s.push(a);
|
|
1302
1308
|
}
|
|
1303
1309
|
}
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1310
|
+
let B = !1, H = null;
|
|
1311
|
+
if (u()) {
|
|
1312
|
+
const i = Ee();
|
|
1313
|
+
i && i("usermaven", [], function() {
|
|
1314
|
+
return {
|
|
1315
|
+
usermavenClient: T,
|
|
1316
|
+
UsermavenClient: C,
|
|
1317
|
+
LogLevel: p,
|
|
1318
|
+
// Expose the script tag client if it exists
|
|
1319
|
+
getScriptTagClient: () => H
|
|
1320
|
+
};
|
|
1321
|
+
}), typeof window < "u" && (window.usermavenClient = T, window.UsermavenClient = C, window.usermavenScriptTagClient = () => H), function(e, t) {
|
|
1322
|
+
const s = e.currentScript;
|
|
1323
|
+
function n() {
|
|
1324
|
+
return B || !s || !s.hasAttribute("data-key") || s.getAttribute("data-no-auto-init") === "true" ? !1 : s.src.includes("lib.js");
|
|
1325
|
+
}
|
|
1326
|
+
function r() {
|
|
1327
|
+
n() && (console.log("[Usermaven] Auto-initializing from script tag"), H = $e(s), B = !0);
|
|
1328
|
+
}
|
|
1329
|
+
typeof t < "u" && s && (e.readyState === "loading" ? e.addEventListener("DOMContentLoaded", r) : r());
|
|
1330
|
+
}(document, window);
|
|
1331
|
+
}
|
|
1332
|
+
typeof module < "u" && module.exports && !K() && (module.exports = {
|
|
1333
|
+
usermavenClient: T,
|
|
1334
|
+
UsermavenClient: C,
|
|
1335
|
+
Config: void 0,
|
|
1336
|
+
UserProps: void 0,
|
|
1337
|
+
EventPayload: void 0,
|
|
1338
|
+
LogLevel: p,
|
|
1339
|
+
ClientProperties: void 0
|
|
1340
|
+
});
|
|
1311
1341
|
export {
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1342
|
+
p as LogLevel,
|
|
1343
|
+
C as UsermavenClient,
|
|
1344
|
+
T as usermavenClient
|
|
1315
1345
|
};
|