@clianta/sdk 1.7.2 → 1.7.3

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.
@@ -1,7 +1,7 @@
1
1
  /*!
2
- * Clianta SDK v1.7.2
2
+ * Clianta SDK v1.7.3
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
6
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Clianta={})}(this,function(e){"use strict";var t="undefined"!=typeof document?document.currentScript:null;const n="1.7.2",i={projectId:"",apiEndpoint:(()=>{if("undefined"!=typeof process&&process.env?.NEXT_PUBLIC_CLIANTA_API_ENDPOINT)return process.env.NEXT_PUBLIC_CLIANTA_API_ENDPOINT;try{"undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(__filename).href:"undefined"==typeof document?location.href:t&&"SCRIPT"===t.tagName.toUpperCase()&&t.src||new URL("clianta.umd.min.js",document.baseURI).href,0}catch{}if("undefined"!=typeof process&&process.env?.REACT_APP_CLIANTA_API_ENDPOINT)return process.env.REACT_APP_CLIANTA_API_ENDPOINT;if("undefined"!=typeof process&&process.env?.CLIANTA_API_ENDPOINT)return process.env.CLIANTA_API_ENDPOINT;return"undefined"!=typeof window&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname)||"undefined"==typeof console||console.warn("[Clianta] No API endpoint configured. Set NEXT_PUBLIC_CLIANTA_API_ENDPOINT (Next.js), VITE_CLIANTA_API_ENDPOINT (Vite), or pass apiEndpoint directly to clianta(). Falling back to localhost — tracking will not work in production."),"http://localhost:5000"})(),debug:!1,autoPageView:!0,plugins:["pageView","forms","scroll","clicks","engagement","downloads","exitIntent","errors","performance","autoIdentify"],sessionTimeout:18e5,batchSize:10,flushInterval:5e3,consent:{defaultConsent:{analytics:!0,marketing:!1,personalization:!1},waitForConsent:!1,storageKey:"mb_consent",anonymousMode:!1},cookieDomain:"",useCookies:!1,cookielessMode:!1,persistMode:"session"},s="mb_vid",o="mb_sid",r="mb_st",a="mb_consent",d="mb_queue",l=[25,50,75,100],c=[".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".rar",".tar",".gz",".7z",".csv",".txt",".json",".xml",".mp3",".mp4",".wav",".avi",".mov"];const u="[Clianta]",h={debug:"color: #6b7280; font-weight: normal;",info:"color: #3b82f6; font-weight: normal;",warn:"color: #f59e0b; font-weight: bold;",error:"color: #ef4444; font-weight: bold;"},f={debug:0,info:1,warn:2,error:3};const m=function(e=!1){let t="debug",n=e;const i=e=>!!n&&f[e]>=f[t],s=(e,t)=>"undefined"!=typeof console&&"undefined"!=typeof window?[`%c${u}`,h[e],...t]:[`${u} [${e.toUpperCase()}]`,...t];return{get enabled(){return n},set enabled(e){n=e},debug(...e){i("debug")&&"undefined"!=typeof console&&console.log(...s("debug",e))},info(...e){i("info")&&"undefined"!=typeof console&&console.info(...s("info",e))},warn(...e){i("warn")&&"undefined"!=typeof console&&console.warn(...s("warn",e))},error(...e){i("error")&&"undefined"!=typeof console&&console.error(...s("error",e))},setLevel(e){t=e}}}(!1);class p{constructor(e){this.config={apiEndpoint:e.apiEndpoint,maxRetries:e.maxRetries??3,retryDelay:e.retryDelay??1e3,timeout:e.timeout??1e4}}async sendEvents(e){const t=`${this.config.apiEndpoint}/api/public/track/event`,n=JSON.stringify({events:e});if(n.length>6e4){return this.sendBeacon(e)?{success:!0}:this.send(t,n,1,!1)}return this.send(t,n)}async sendIdentify(e){const t=`${this.config.apiEndpoint}/api/public/track/identify`;try{const n=await this.fetchWithTimeout(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0}),i=await n.json().catch(()=>({}));return n.ok?(m.debug("Identify successful, contactId:",i.contactId),{success:!0,status:n.status,contactId:i.contactId??void 0}):(n.status>=500?m.warn(`Identify server error (${n.status})`):m.error(`Identify failed with status ${n.status}:`,i.message),{success:!1,status:n.status})}catch(e){return m.error("Identify request failed:",e),{success:!1,error:e}}}sendBeacon(e){if("undefined"==typeof navigator||!navigator.sendBeacon)return m.warn("sendBeacon not available, events may be lost"),!1;const t=`${this.config.apiEndpoint}/api/public/track/event`,n=JSON.stringify({events:e}),i=new Blob([n],{type:"application/json"});try{const n=navigator.sendBeacon(t,i);return n?m.debug(`Beacon sent ${e.length} events`):m.warn("sendBeacon returned false"),n}catch(e){return m.error("sendBeacon error:",e),!1}}async sendPost(e,t){const n=`${this.config.apiEndpoint}${e}`,i=JSON.stringify(t);return this.send(n,i)}async fetchData(e,t){const n=new URL(`${this.config.apiEndpoint}${e}`);t&&Object.entries(t).forEach(([e,t])=>{null!=t&&n.searchParams.set(e,t)});try{const t=await this.fetchWithTimeout(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(t.ok){const n=await t.json();return m.debug("Fetch successful:",e),{success:!0,data:n.data??n,status:t.status}}return m.error(`Fetch failed with status ${t.status}`),{success:!1,status:t.status}}catch(e){return m.error("Fetch request failed:",e),{success:!1,error:e}}}async send(e,t,n=1,i=!0){if("undefined"!=typeof navigator&&!navigator.onLine)return m.warn("Device offline, skipping send"),{success:!1,error:new Error("offline")};try{const s=await this.fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:i});if(s.ok)return m.debug("Request successful:",e),{success:!0,status:s.status};if(s.status>=500&&n<this.config.maxRetries){const o=this.config.retryDelay*Math.pow(2,n-1);return m.warn(`Server error (${s.status}), retrying in ${o}ms...`),await this.delay(o),this.send(e,t,n+1,i)}return m.error(`Request failed with status ${s.status}`),{success:!1,status:s.status}}catch(s){if(("undefined"==typeof navigator||navigator.onLine)&&n<this.config.maxRetries){const s=this.config.retryDelay*Math.pow(2,n-1);return m.warn(`Network error, retrying in ${s}ms (${n}/${this.config.maxRetries})...`),await this.delay(s),this.send(e,t,n+1,i)}return m.error("Request failed after retries:",s),{success:!1,error:s}}}async fetchWithTimeout(e,t){const n=new AbortController,i=setTimeout(()=>n.abort(),this.config.timeout);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(i)}}delay(e){return new Promise(t=>setTimeout(t,e))}}function g(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function y(e){try{if("undefined"!=typeof sessionStorage)return sessionStorage.getItem(e)}catch{}return null}function w(e,t){try{if("undefined"!=typeof sessionStorage)return sessionStorage.setItem(e,t),!0}catch{}return!1}function v(e,t,n){if("undefined"==typeof document)return null;if(void 0===t){const t=document.cookie.match(new RegExp("(^| )"+e+"=([^;]+)"));return t?t[2]:null}let i="";if(n){const e=new Date;e.setTime(e.getTime()+24*n*60*60*1e3),i="; expires="+e.toUTCString()}const s="undefined"!=typeof location&&"https:"===location.protocol?"; Secure":"";return document.cookie=e+"="+t+i+"; path=/; SameSite=Lax"+s,t}function b(e=!1){const t=s;let n=null;return n=e?v(t):function(e){try{if("undefined"!=typeof localStorage)return localStorage.getItem(e)}catch{}return null}(t),n||(n=g(),e?v(t,n,365):function(e,t){try{if("undefined"!=typeof localStorage)return localStorage.setItem(e,t),!0}catch{}}(t,n)),n}function k(e=!1){const t=s;if(e)v(t,"",-1);else try{localStorage.removeItem(t)}catch{}try{sessionStorage.removeItem(o),sessionStorage.removeItem(r)}catch{}}function E(){if("undefined"==typeof window)return{};try{const e=new URLSearchParams(window.location.search);return{utmSource:e.get("utm_source")||void 0,utmMedium:e.get("utm_medium")||void 0,utmCampaign:e.get("utm_campaign")||void 0,utmTerm:e.get("utm_term")||void 0,utmContent:e.get("utm_content")||void 0}}catch{return{}}}function S(e){try{return e.split("/").pop()?.split("?")[0]||"unknown"}catch{return"unknown"}}function T(e){const t=S(e).split(".");return t.length>1&&t.pop()||"unknown"}function I(e,t=100){return(e.innerText||e.textContent||e.value||"").trim().substring(0,t)}function x(e){return["BUTTON","A","INPUT"].includes(e.tagName)||e.hasAttribute("data-track-click")||e.classList.contains("track-click")}class C{constructor(e,t={}){this.queue=[],this.flushTimer=null,this.isFlushing=!1,this.isOnline=!0,this.eventTimestamps=[],this.boundBeforeUnload=null,this.boundVisibilityChange=null,this.boundPageHide=null,this.boundOnline=null,this.boundOffline=null,this.unloadFlushed=!1,this.transport=e,this.config={batchSize:t.batchSize??10,flushInterval:t.flushInterval??5e3,maxQueueSize:t.maxQueueSize??1e3,storageKey:t.storageKey??d},this.persistMode=t.persistMode||"session",this.isOnline="undefined"==typeof navigator||navigator.onLine,this.restoreQueue(),this.startFlushTimer(),this.setupUnloadHandlers()}push(e){this.checkRateLimit()?(this.queue.length>=this.config.maxQueueSize&&(m.warn("Queue full, dropping oldest event"),this.queue.shift()),this.queue.push(e),m.debug("Event queued:",e.eventName,`(${this.queue.length} in queue)`),this.queue.length>=this.config.batchSize&&this.flush()):m.warn("Rate limit exceeded, event dropped:",e.eventName)}checkRateLimit(){const e=Date.now();return this.eventTimestamps=this.eventTimestamps.filter(t=>e-t<6e4),!(this.eventTimestamps.length>=100)&&(this.eventTimestamps.push(e),!0)}async flush(){if(this.isFlushing||0===this.queue.length||!this.isOnline)return;this.isFlushing=!0;const e=this.queue.length,t=this.queue.splice(0,e);try{m.debug(`Flushing ${t.length} events`),this.persistQueue([]);(await this.transport.sendEvents(t)).success?m.debug("Flush successful"):(m.warn("Flush failed, re-queuing events"),this.queue.unshift(...t),this.persistQueue(this.queue))}catch(e){m.error("Flush error:",e)}finally{this.isFlushing=!1}}flushSync(){if(this.unloadFlushed||0===this.queue.length)return;this.unloadFlushed=!0;const e=this.queue.splice(0,this.queue.length);m.debug(`Sync flushing ${e.length} events via beacon`);this.transport.sendBeacon(e)||(this.queue.unshift(...e),this.persistQueue(this.queue))}get length(){return this.queue.length}clear(){if(this.queue=[],this.persistQueue([]),"local"===this.persistMode&&"undefined"!=typeof localStorage)try{localStorage.removeItem(this.config.storageKey)}catch{}}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),"undefined"!=typeof window&&(this.boundBeforeUnload&&window.removeEventListener("beforeunload",this.boundBeforeUnload),this.boundVisibilityChange&&window.removeEventListener("visibilitychange",this.boundVisibilityChange),this.boundPageHide&&window.removeEventListener("pagehide",this.boundPageHide),this.boundOnline&&window.removeEventListener("online",this.boundOnline),this.boundOffline&&window.removeEventListener("offline",this.boundOffline))}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush()},this.config.flushInterval)}setupUnloadHandlers(){"undefined"!=typeof window&&(this.boundBeforeUnload=()=>this.flushSync(),window.addEventListener("beforeunload",this.boundBeforeUnload),this.boundVisibilityChange=()=>{"hidden"===document.visibilityState?this.flushSync():this.unloadFlushed=!1},window.addEventListener("visibilitychange",this.boundVisibilityChange),this.boundPageHide=()=>this.flushSync(),window.addEventListener("pagehide",this.boundPageHide),this.boundOnline=()=>{m.info("Connection restored — flushing queued events"),this.isOnline=!0,this.flush()},this.boundOffline=()=>{m.warn("Connection lost — pausing event queue"),this.isOnline=!1},window.addEventListener("online",this.boundOnline),window.addEventListener("offline",this.boundOffline))}persistQueue(e){if("none"!==this.persistMode)try{const t=JSON.stringify(e);if("local"===this.persistMode&&"undefined"!=typeof localStorage)try{localStorage.setItem(this.config.storageKey,t)}catch{w(this.config.storageKey,t)}else w(this.config.storageKey,t)}catch{}}restoreQueue(){try{let e=null;if("local"===this.persistMode&&"undefined"!=typeof localStorage&&(e=localStorage.getItem(this.config.storageKey)),e||(e=y(this.config.storageKey)),e){const t=JSON.parse(e);Array.isArray(t)&&t.length>0&&(this.queue=t,m.debug(`Restored ${t.length} events from storage`))}}catch{}}}class _{constructor(){this.tracker=null}init(e){this.tracker=e}destroy(){this.tracker=null}track(e,t,n){this.tracker&&this.tracker.track(e,t,n)}}const H="__clianta_pv_wrapped__";class L extends _{constructor(){super(...arguments),this.name="pageView",this.originalPushState=null,this.originalReplaceState=null,this.navHandler=null,this.popstateHandler=null}init(e){if(super.init(e),this.trackPageView(),"undefined"!=typeof window){if(!history.pushState[H]){this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;const e=this.originalPushState,t=this.originalReplaceState;history.pushState=function(...t){e.apply(history,t),window.dispatchEvent(new Event("clianta:navigation"))},history.pushState[H]=!0,history.replaceState=function(...e){t.apply(history,e),window.dispatchEvent(new Event("clianta:navigation"))},history.replaceState[H]=!0}this.navHandler=()=>this.trackPageView(),window.addEventListener("clianta:navigation",this.navHandler),this.popstateHandler=()=>this.trackPageView(),window.addEventListener("popstate",this.popstateHandler)}}destroy(){"undefined"!=typeof window&&(this.navHandler&&(window.removeEventListener("clianta:navigation",this.navHandler),this.navHandler=null),this.popstateHandler&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null)),this.originalPushState&&(history.pushState=this.originalPushState,delete history.pushState[H],this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,delete history.replaceState[H],this.originalReplaceState=null),super.destroy()}trackPageView(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.track("page_view","Page Viewed",{title:document.title,path:window.location.pathname,search:window.location.search,hash:window.location.hash,referrer:document.referrer||"direct",viewport:`${window.innerWidth}x${window.innerHeight}`})}}class N extends _{constructor(){super(...arguments),this.name="scroll",this.milestonesReached=new Set,this.maxScrollDepth=0,this.pageLoadTime=0,this.scrollTimeout=null,this.boundHandler=null,this.navigationHandler=null,this.popstateHandler=null}init(e){super.init(e),this.pageLoadTime=Date.now(),"undefined"!=typeof window&&(this.boundHandler=this.handleScroll.bind(this),window.addEventListener("scroll",this.boundHandler,{passive:!0}),this.navigationHandler=()=>this.resetForNavigation(),window.addEventListener("clianta:navigation",this.navigationHandler),this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler))}destroy(){this.boundHandler&&"undefined"!=typeof window&&window.removeEventListener("scroll",this.boundHandler),this.scrollTimeout&&clearTimeout(this.scrollTimeout),this.navigationHandler&&"undefined"!=typeof window&&(window.removeEventListener("clianta:navigation",this.navigationHandler),this.navigationHandler=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),super.destroy()}resetForNavigation(){this.milestonesReached.clear(),this.maxScrollDepth=0,this.pageLoadTime=Date.now()}handleScroll(){this.scrollTimeout&&clearTimeout(this.scrollTimeout),this.scrollTimeout=setTimeout(()=>this.trackScrollDepth(),150)}trackScrollDepth(){if("undefined"==typeof window||"undefined"==typeof document)return;const e=window.innerHeight,t=document.documentElement.scrollHeight,n=window.pageYOffset||document.documentElement.scrollTop,i=t-e;if(i<=0)return;const s=Math.floor(n/i*100),o=Math.max(0,Math.min(100,s));o>this.maxScrollDepth&&(this.maxScrollDepth=o);for(const e of l)o>=e&&!this.milestonesReached.has(e)&&(this.milestonesReached.add(e),this.track("scroll_depth",`Scrolled ${e}%`,{depth:e,maxDepth:this.maxScrollDepth,timeToReach:Date.now()-this.pageLoadTime}))}}class F extends _{constructor(){super(...arguments),this.name="forms",this.trackedForms=new WeakSet,this.formInteractions=new Set,this.observer=null,this.observerTimer=null,this.listeners=[]}init(e){super.init(e),"undefined"!=typeof document&&(this.trackAllForms(),"undefined"!=typeof MutationObserver&&(this.observer=new MutationObserver(()=>{this.observerTimer&&clearTimeout(this.observerTimer),this.observerTimer=setTimeout(()=>this.trackAllForms(),100)}),this.observer.observe(document.body,{childList:!0,subtree:!0})))}destroy(){this.observerTimer&&(clearTimeout(this.observerTimer),this.observerTimer=null),this.observer&&(this.observer.disconnect(),this.observer=null);for(const{element:e,event:t,handler:n}of this.listeners)e.removeEventListener(t,n);this.listeners=[],super.destroy()}addListener(e,t,n){e.addEventListener(t,n),this.listeners.push({element:e,event:t,handler:n})}trackAllForms(){document.querySelectorAll("form").forEach(e=>{this.setupFormTracking(e)})}setupFormTracking(e){if(this.trackedForms.has(e))return;this.trackedForms.add(e);const t=e.id||e.name||`form-${Math.random().toString(36).substr(2,9)}`;this.track("form_view","Form Viewed",{formId:t,action:e.action,method:e.method,fieldCount:e.elements.length}),Array.from(e.elements).forEach(e=>{if(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement){if(!e.name||"submit"===e.type||"button"===e.type)return;["focus","blur","change"].forEach(n=>{this.addListener(e,n,()=>{const i=`${t}-${e.name}-${n}`;this.formInteractions.has(i)||(this.formInteractions.add(i),this.track("form_interaction","Form Field Interaction",{formId:t,fieldName:e.name,fieldType:e.type,interactionType:n}))})})}});this.addListener(e,"submit",()=>{this.track("form_submit","Form Submitted",{formId:t,action:e.action,method:e.method}),this.autoIdentify(e)})}autoIdentify(e){const t=e.querySelector('input[type="email"], input[name*="email"]');if(!t?.value||!this.tracker)return;const n=t.value,i={},s=e.querySelector('[name*="first"], [name*="fname"]'),o=e.querySelector('[name*="last"], [name*="lname"]'),r=e.querySelector('[name*="company"], [name*="organization"]'),a=e.querySelector('[type="tel"], [name*="phone"]');s?.value&&(i.firstName=s.value),o?.value&&(i.lastName=o.value),r?.value&&(i.company=r.value),a?.value&&(i.phone=a.value),this.tracker.identify(n,i)}}class P extends _{constructor(){super(...arguments),this.name="clicks",this.boundHandler=null}init(e){super.init(e),"undefined"!=typeof document&&(this.boundHandler=this.handleClick.bind(this),document.addEventListener("click",this.boundHandler,!0))}destroy(){this.boundHandler&&"undefined"!=typeof document&&document.removeEventListener("click",this.boundHandler,!0),super.destroy()}handleClick(e){let t=e.target;for(;t&&!x(t);)t=t.parentElement;if(!t)return;const n=I(t,100),i=(s=t,{tag:s.tagName?.toLowerCase()||"unknown",id:s.id||"",className:s.className||"",text:I(s,50)});var s;this.track("button_click","Button Clicked",{buttonText:n,elementType:t.tagName.toLowerCase(),elementId:i.id,elementClass:i.className,href:t.href||void 0,x:Math.round(e.clientX/window.innerWidth*100),y:Math.round(e.clientY/window.innerHeight*100),viewportWidth:window.innerWidth,viewportHeight:window.innerHeight})}}class A extends _{constructor(){super(...arguments),this.name="engagement",this.pageLoadTime=0,this.engagementStartTime=0,this.isEngaged=!1,this.engagementTimeout=null,this.unloadReported=!1,this.boundMarkEngaged=null,this.boundTrackTimeOnPage=null,this.boundVisibilityHandler=null,this.navigationHandler=null,this.popstateHandler=null}init(e){super.init(e),this.pageLoadTime=Date.now(),this.engagementStartTime=Date.now(),"undefined"!=typeof document&&"undefined"!=typeof window&&(this.boundMarkEngaged=this.markEngaged.bind(this),this.boundTrackTimeOnPage=this.trackTimeOnPage.bind(this),this.boundVisibilityHandler=()=>{"hidden"===document.visibilityState?this.trackTimeOnPage():(this.engagementStartTime=Date.now(),this.unloadReported=!1)},["mousemove","keydown","touchstart","scroll"].forEach(e=>{document.addEventListener(e,this.boundMarkEngaged,{passive:!0})}),window.addEventListener("beforeunload",this.boundTrackTimeOnPage),document.addEventListener("visibilitychange",this.boundVisibilityHandler),this.navigationHandler=()=>this.resetForNavigation(),window.addEventListener("clianta:navigation",this.navigationHandler),this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler))}destroy(){this.boundMarkEngaged&&"undefined"!=typeof document&&["mousemove","keydown","touchstart","scroll"].forEach(e=>{document.removeEventListener(e,this.boundMarkEngaged)}),this.boundTrackTimeOnPage&&"undefined"!=typeof window&&window.removeEventListener("beforeunload",this.boundTrackTimeOnPage),this.boundVisibilityHandler&&"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.boundVisibilityHandler),this.navigationHandler&&"undefined"!=typeof window&&(window.removeEventListener("clianta:navigation",this.navigationHandler),this.navigationHandler=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),this.engagementTimeout&&clearTimeout(this.engagementTimeout),super.destroy()}resetForNavigation(){this.pageLoadTime=Date.now(),this.engagementStartTime=Date.now(),this.isEngaged=!1,this.unloadReported=!1,this.engagementTimeout&&(clearTimeout(this.engagementTimeout),this.engagementTimeout=null)}markEngaged(){this.isEngaged||(this.isEngaged=!0,this.track("engagement","User Engaged",{timeToEngage:Date.now()-this.pageLoadTime})),this.engagementTimeout&&clearTimeout(this.engagementTimeout),this.engagementTimeout=setTimeout(()=>{this.isEngaged=!1},3e4)}trackTimeOnPage(){if(this.unloadReported)return;this.unloadReported=!0;const e=Math.floor((Date.now()-this.engagementStartTime)/1e3);e>0&&this.track("time_on_page","Time Spent",{seconds:e,engaged:this.isEngaged})}}class O extends _{constructor(){super(...arguments),this.name="downloads",this.trackedDownloads=new Set,this.boundHandler=null,this.navigationHandler=null,this.popstateHandler=null}init(e){super.init(e),"undefined"!=typeof document&&(this.boundHandler=this.handleClick.bind(this),document.addEventListener("click",this.boundHandler,!0)),"undefined"!=typeof window&&(this.navigationHandler=()=>this.resetForNavigation(),window.addEventListener("clianta:navigation",this.navigationHandler),this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler))}destroy(){this.boundHandler&&"undefined"!=typeof document&&document.removeEventListener("click",this.boundHandler,!0),this.navigationHandler&&"undefined"!=typeof window&&(window.removeEventListener("clianta:navigation",this.navigationHandler),this.navigationHandler=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),super.destroy()}resetForNavigation(){this.trackedDownloads.clear()}handleClick(e){const t=e.target.closest("a");if(!t||!t.href)return;const n=t.href;(function(e){const t=e.toLowerCase();return c.some(e=>t.includes(e))})(n)&&(this.trackedDownloads.has(n)||(this.trackedDownloads.add(n),this.track("download","File Download",{url:n,filename:S(n),fileType:T(n),linkText:I(t,100)})))}}class M extends _{constructor(){super(...arguments),this.name="exitIntent",this.exitIntentShown=!1,this.pageLoadTime=0,this.boundHandler=null,this.navigationHandler=null,this.popstateHandler=null}init(e){super.init(e),this.pageLoadTime=Date.now(),"undefined"!=typeof navigator&&/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)||("undefined"!=typeof document&&(this.boundHandler=this.handleMouseLeave.bind(this),document.addEventListener("mouseleave",this.boundHandler)),"undefined"!=typeof window&&(this.navigationHandler=()=>this.resetForNavigation(),window.addEventListener("clianta:navigation",this.navigationHandler),this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler)))}destroy(){this.boundHandler&&"undefined"!=typeof document&&document.removeEventListener("mouseleave",this.boundHandler),this.navigationHandler&&"undefined"!=typeof window&&(window.removeEventListener("clianta:navigation",this.navigationHandler),this.navigationHandler=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),super.destroy()}resetForNavigation(){this.exitIntentShown=!1,this.pageLoadTime=Date.now()}handleMouseLeave(e){e.clientY>0||this.exitIntentShown||(this.exitIntentShown=!0,this.track("exit_intent","Exit Intent Detected",{timeOnPage:Date.now()-this.pageLoadTime}))}}class $ extends _{constructor(){super(...arguments),this.name="errors",this.boundErrorHandler=null,this.boundRejectionHandler=null,this.seenErrors=new Set}init(e){super.init(e),"undefined"!=typeof window&&(this.boundErrorHandler=this.handleError.bind(this),this.boundRejectionHandler=this.handleRejection.bind(this),window.addEventListener("error",this.boundErrorHandler),window.addEventListener("unhandledrejection",this.boundRejectionHandler))}destroy(){"undefined"!=typeof window&&(this.boundErrorHandler&&window.removeEventListener("error",this.boundErrorHandler),this.boundRejectionHandler&&window.removeEventListener("unhandledrejection",this.boundRejectionHandler)),super.destroy()}handleError(e){const t=`${e.message}:${e.filename}:${e.lineno}`;this.dedup(t)&&this.track("error","JavaScript Error",{message:e.message,filename:e.filename,line:e.lineno,column:e.colno,stack:e.error?.stack?.substring(0,500)})}handleRejection(e){const t=String(e.reason).substring(0,200);this.dedup(t)&&this.track("error","Unhandled Promise Rejection",{reason:t})}dedup(e){return!this.seenErrors.has(e)&&(!(this.seenErrors.size>=20)&&(this.seenErrors.add(e),!0))}}class D extends _{constructor(){super(...arguments),this.name="performance",this.boundLoadHandler=null,this.observers=[],this.boundClsVisibilityHandler=null}init(e){super.init(e),"undefined"!=typeof window&&(this.boundLoadHandler=()=>{setTimeout(()=>this.trackPerformance(),100)},window.addEventListener("load",this.boundLoadHandler))}destroy(){this.boundLoadHandler&&"undefined"!=typeof window&&window.removeEventListener("load",this.boundLoadHandler);for(const e of this.observers)e.disconnect();this.observers=[],this.boundClsVisibilityHandler&&"undefined"!=typeof window&&window.removeEventListener("visibilitychange",this.boundClsVisibilityHandler),super.destroy()}trackPerformance(){if("undefined"==typeof performance)return;const e=performance.getEntriesByType("navigation");if(e.length>0){const t=e[0],n=Math.round(t.loadEventEnd-t.startTime),i=Math.round(t.domContentLoadedEventEnd-t.startTime),s=Math.round(t.responseStart-t.requestStart),o=Math.round(t.domInteractive-t.startTime);this.track("performance","Page Performance",{loadTime:n,domReady:i,ttfb:s,domInteractive:o,dns:Math.round(t.domainLookupEnd-t.domainLookupStart),connection:Math.round(t.connectEnd-t.connectStart),transferSize:t.transferSize})}else{const e=performance.timing;if(!e)return;const t=e.loadEventEnd-e.navigationStart,n=e.domContentLoadedEventEnd-e.navigationStart,i=e.responseStart-e.navigationStart,s=e.domInteractive-e.navigationStart;this.track("performance","Page Performance",{loadTime:t,domReady:n,ttfb:i,domInteractive:s})}this.trackWebVitals()}trackWebVitals(){if("PerformanceObserver"in window){try{const e=new PerformanceObserver(e=>{const t=e.getEntries(),n=t[t.length-1];n&&this.track("performance","Web Vital - LCP",{metric:"LCP",value:Math.round(n.startTime)})});e.observe({type:"largest-contentful-paint",buffered:!0}),this.observers.push(e)}catch{}try{const e=new PerformanceObserver(e=>{const t=e.getEntries()[0];t&&this.track("performance","Web Vital - FID",{metric:"FID",value:Math.round(t.processingStart-t.startTime)})});e.observe({type:"first-input",buffered:!0}),this.observers.push(e)}catch{}try{let e=0;const t=new PerformanceObserver(t=>{t.getEntries().forEach(t=>{t.hadRecentInput||(e+=t.value||0)})});t.observe({type:"layout-shift",buffered:!0}),this.observers.push(t),this.boundClsVisibilityHandler=()=>{"hidden"===document.visibilityState&&e>0&&this.track("performance","Web Vital - CLS",{metric:"CLS",value:Math.round(1e3*e)/1e3})},window.addEventListener("visibilitychange",this.boundClsVisibilityHandler,{once:!0})}catch{}}}}class q extends _{constructor(){super(...arguments),this.name="popupForms",this.forms=[],this.shownForms=new Set,this.scrollHandler=null,this.exitHandler=null,this.delayTimers=[],this.clickTriggerListeners=[]}async init(e){super.init(e),"undefined"!=typeof window&&(this.loadShownForms(),await this.fetchForms(),this.setupTriggers())}destroy(){this.removeTriggers();for(const e of this.delayTimers)clearTimeout(e);this.delayTimers=[];for(const{element:e,handler:t}of this.clickTriggerListeners)e.removeEventListener("click",t);this.clickTriggerListeners=[],super.destroy()}loadShownForms(){try{const e=localStorage.getItem("clianta_shown_forms");if(e){const t=JSON.parse(e);this.shownForms=new Set(t.forms||[])}}catch(e){}}saveShownForms(){try{localStorage.setItem("clianta_shown_forms",JSON.stringify({forms:Array.from(this.shownForms),timestamp:Date.now()}))}catch(e){}}async fetchForms(){if(!this.tracker)return;const e=this.tracker.getConfig(),t=this.tracker.getWorkspaceId(),n=e.apiEndpoint||"http://localhost:5000";try{const e=encodeURIComponent(window.location.href),i=await fetch(`${n}/api/public/lead-forms/${t}?url=${e}`);if(!i.ok)return;const s=await i.json();s.success&&Array.isArray(s.data)&&(this.forms=s.data.filter(e=>this.shouldShowForm(e)))}catch(e){console.error("[Clianta] Failed to fetch forms:",e)}}shouldShowForm(e){if("once_per_visitor"===e.showFrequency){if(this.shownForms.has(e._id))return!1}else if("once_per_session"===e.showFrequency){const t=`clianta_form_${e._id}_shown`;if(sessionStorage.getItem(t))return!1}return!0}setupTriggers(){this.forms.forEach(e=>{switch(e.trigger.type){case"delay":this.delayTimers.push(setTimeout(()=>this.showForm(e),1e3*(e.trigger.value||5)));break;case"scroll":this.setupScrollTrigger(e);break;case"exit_intent":this.setupExitIntentTrigger(e);break;case"click":this.setupClickTrigger(e)}})}setupScrollTrigger(e){const t=e.trigger.value||50;this.scrollHandler=()=>{window.scrollY/(document.documentElement.scrollHeight-window.innerHeight)*100>=t&&(this.showForm(e),this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler))},window.addEventListener("scroll",this.scrollHandler,{passive:!0})}setupExitIntentTrigger(e){this.exitHandler=t=>{t.clientY<=0&&(this.showForm(e),this.exitHandler&&document.removeEventListener("mouseout",this.exitHandler))},document.addEventListener("mouseout",this.exitHandler)}setupClickTrigger(e){if(!e.trigger.selector)return;document.querySelectorAll(e.trigger.selector).forEach(t=>{const n=()=>this.showForm(e);t.addEventListener("click",n),this.clickTriggerListeners.push({element:t,handler:n})})}removeTriggers(){this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler),this.exitHandler&&document.removeEventListener("mouseout",this.exitHandler)}async showForm(e){this.shouldShowForm(e)&&(this.shownForms.add(e._id),this.saveShownForms(),sessionStorage.setItem(`clianta_form_${e._id}_shown`,"true"),await this.trackFormView(e._id),this.renderForm(e))}async trackFormView(e){if(!this.tracker)return;const t=this.tracker.getConfig().apiEndpoint||"http://localhost:5000";try{await fetch(`${t}/api/public/lead-forms/${e}/view`,{method:"POST",headers:{"Content-Type":"application/json"}})}catch(e){}}renderForm(e){const t=document.createElement("div");t.id=`clianta-form-overlay-${e._id}`,t.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.5);\n z-index: 999998;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0;\n transition: opacity 0.3s ease;\n ";const n=document.createElement("div");n.id=`clianta-form-${e._id}`;const i=e.style||{};n.style.cssText=`\n background: ${i.backgroundColor||"#FFFFFF"};\n border-radius: ${i.borderRadius||12}px;\n padding: 24px;\n max-width: 400px;\n width: 90%;\n box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);\n transform: translateY(20px);\n opacity: 0;\n transition: all 0.3s ease;\n `,this.buildFormDOM(e,n),t.appendChild(n),document.body.appendChild(t),requestAnimationFrame(()=>{t.style.opacity="1",n.style.transform="translateY(0)",n.style.opacity="1"}),this.setupFormEvents(e,t,n)}escapeHTML(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}buildFormDOM(e,t){const n=e.style||{},i=n.primaryColor||"#10B981",s=n.textColor||"#18181B",o=document.createElement("button");o.id="clianta-form-close",o.style.cssText="\n position: absolute;\n top: 12px;\n right: 12px;\n background: none;\n border: none;\n font-size: 20px;\n cursor: pointer;\n color: #71717A;\n padding: 4px;\n ",o.textContent="×",t.appendChild(o);const r=document.createElement("h2");r.style.cssText=`font-size: 20px; font-weight: 700; margin-bottom: 8px; color: ${this.escapeHTML(s)};`,r.textContent=e.headline||"Stay in touch",t.appendChild(r);const a=document.createElement("p");a.style.cssText="font-size: 14px; color: #71717A; margin-bottom: 16px;",a.textContent=e.subheadline||"Get the latest updates",t.appendChild(a);const d=document.createElement("form");d.id="clianta-form-element",e.fields.forEach(e=>{const t=document.createElement("div");if(t.style.marginBottom="12px","checkbox"===e.type){const n=document.createElement("label");n.style.cssText=`display: flex; align-items: center; gap: 8px; font-size: 14px; color: ${this.escapeHTML(s)}; cursor: pointer;`;const i=document.createElement("input");i.type="checkbox",i.name=e.name,e.required&&(i.required=!0),i.style.cssText="width: 16px; height: 16px;",n.appendChild(i);const o=document.createTextNode(e.label+" ");if(n.appendChild(o),e.required){const e=document.createElement("span");e.style.color="#EF4444",e.textContent="*",n.appendChild(e)}t.appendChild(n)}else{const n=document.createElement("label");if(n.style.cssText=`display: block; font-size: 14px; font-weight: 500; margin-bottom: 4px; color: ${this.escapeHTML(s)};`,n.textContent=e.label+" ",e.required){const e=document.createElement("span");e.style.color="#EF4444",e.textContent="*",n.appendChild(e)}if(t.appendChild(n),"textarea"===e.type){const n=document.createElement("textarea");n.name=e.name,e.placeholder&&(n.placeholder=e.placeholder),e.required&&(n.required=!0),n.style.cssText="width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; resize: vertical; min-height: 80px; box-sizing: border-box;",t.appendChild(n)}else if("select"===e.type){const n=document.createElement("select");if(n.name=e.name,e.required&&(n.required=!0),n.style.cssText="width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; box-sizing: border-box; background: white; cursor: pointer;",e.placeholder){const t=document.createElement("option");t.value="",t.textContent=e.placeholder,t.disabled=!0,t.selected=!0,n.appendChild(t)}e.options&&Array.isArray(e.options)&&e.options.forEach(e=>{const t=document.createElement("option");"string"==typeof e?(t.value=e,t.textContent=e):(t.value=e.value,t.textContent=e.label),n.appendChild(t)}),t.appendChild(n)}else{const n=document.createElement("input");n.type=e.type,n.name=e.name,e.placeholder&&(n.placeholder=e.placeholder),e.required&&(n.required=!0),n.style.cssText="width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; box-sizing: border-box;",t.appendChild(n)}}d.appendChild(t)});const l=document.createElement("button");l.type="submit",l.style.cssText=`\n width: 100%;\n padding: 10px 16px;\n background: ${this.escapeHTML(i)};\n color: white;\n border: none;\n border-radius: 6px;\n font-size: 14px;\n font-weight: 500;\n cursor: pointer;\n margin-top: 8px;\n `,l.textContent=e.submitButtonText||"Subscribe",d.appendChild(l),t.appendChild(d)}setupFormEvents(e,t,n){const i=n.querySelector("#clianta-form-close");i&&i.addEventListener("click",()=>this.closeForm(e._id,t,n)),t.addEventListener("click",i=>{i.target===t&&this.closeForm(e._id,t,n)});const s=n.querySelector("#clianta-form-element");s&&s.addEventListener("submit",async t=>{t.preventDefault(),await this.handleSubmit(e,s,n)})}closeForm(e,t,n){n.style.transform="translateY(20px)",n.style.opacity="0",t.style.opacity="0",setTimeout(()=>{t.remove()},300)}async handleSubmit(e,t,n){if(!this.tracker)return;const i=this.tracker.getConfig().apiEndpoint||"http://localhost:5000",s=this.tracker.getVisitorId(),o=new FormData(t),r={};o.forEach((e,t)=>{r[t]=e});const a=t.querySelector('button[type="submit"]');a&&(a.disabled=!0,a.textContent="Submitting...");try{const t=await fetch(`${i}/api/public/lead-forms/${e._id}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({visitorId:s,data:r,url:window.location.href})});if((await t.json()).success){n.innerHTML="";const t=document.createElement("div");t.style.cssText="text-align: center; padding: 20px;";const i=document.createElement("div");i.style.cssText="width: 48px; height: 48px; background: #10B981; border-radius: 50%; margin: 0 auto 16px; display: flex; align-items: center; justify-content: center;";const s=document.createElementNS("http://www.w3.org/2000/svg","svg");s.setAttribute("width","24"),s.setAttribute("height","24"),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke","white"),s.setAttribute("stroke-width","2");const o=document.createElementNS("http://www.w3.org/2000/svg","polyline");o.setAttribute("points","20 6 9 17 4 12"),s.appendChild(o),i.appendChild(s);const a=document.createElement("p");if(a.style.cssText="font-size: 16px; font-weight: 500; color: #18181B;",a.textContent=e.successMessage||"Thank you!",t.appendChild(i),t.appendChild(a),n.appendChild(t),r.email&&this.tracker?.identify(r.email,r),e.redirectUrl)try{const t=new URL(e.redirectUrl,window.location.origin),n=t.origin===window.location.origin,i="https:"===t.protocol||"http:"===t.protocol;n||i?setTimeout(()=>{window.location.href=t.href},1500):console.warn("[Clianta] Blocked unsafe redirect URL:",e.redirectUrl)}catch{console.warn("[Clianta] Invalid redirect URL:",e.redirectUrl)}setTimeout(()=>{const t=document.getElementById(`clianta-form-overlay-${e._id}`);t&&this.closeForm(e._id,t,n)},2e3)}}catch(t){console.error("[Clianta] Form submit error:",t),a&&(a.disabled=!1,a.textContent=e.submitButtonText||"Subscribe")}}}const R=5e4,U=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/,V=["__session","__clerk_db_jwt","next-auth.session-token","__Secure-next-auth.session-token","sb-access-token","auth0.is.authenticated","KEYCLOAK_SESSION","KEYCLOAK_IDENTITY","KC_RESTART","token","jwt","access_token","session_token","auth_token","id_token"],j=["sb-","supabase.auth.","firebase:authUser:","auth0spajs","@@auth0spajs@@","msal.","msal.account","CognitoIdentityServiceProvider","amplify-signin-with-hostedUI","kc-callback-","persist:","-storage","token","jwt","auth","user","session","credential","account"],z=["email","sub","preferred_username","user_email","mail","emailAddress","e_mail"],B=["name","full_name","display_name","displayName"],W=["given_name","first_name","firstName","fname"],K=["family_name","last_name","lastName","lname"],J=[2e3,5e3,1e4,1e4,3e4,3e4,3e4,6e4,6e4,6e4];class Q extends _{constructor(){super(...arguments),this.name="autoIdentify",this.pollTimeouts=[],this.identifiedEmail=null,this.storageHandler=null,this.sessionProbed=!1}init(e){super.init(e),"undefined"!=typeof window&&(this.schedulePollChecks(),this.listenForStorageChanges())}destroy(){for(const e of this.pollTimeouts)clearTimeout(e);this.pollTimeouts=[],this.storageHandler&&"undefined"!=typeof window&&(window.removeEventListener("storage",this.storageHandler),this.storageHandler=null),super.destroy()}schedulePollChecks(){let e=0;for(let t=0;t<J.length;t++){e+=J[t];const n=setTimeout(()=>{if(!this.identifiedEmail){try{this.checkForAuthUser()}catch{}3!==t||this.sessionProbed||(this.sessionProbed=!0,this.guardedSessionProbe())}},e);this.pollTimeouts.push(n)}}listenForStorageChanges(){this.storageHandler=e=>{if(this.identifiedEmail)return;if(!e.key||!e.newValue)return;const t=e.key.toLowerCase();if(j.some(e=>t.includes(e.toLowerCase())))try{this.checkForAuthUser()}catch{}},window.addEventListener("storage",this.storageHandler)}checkForAuthUser(){if(this.tracker&&!this.identifiedEmail){try{const e=this.checkAuthProviders();if(e)return void this.identifyUser(e)}catch{}try{const e=this.checkCookies();if(e)return void this.identifyUser(e)}catch{}try{if("undefined"!=typeof localStorage){const e=this.checkStorage(localStorage);if(e)return void this.identifyUser(e)}}catch{}try{if("undefined"!=typeof sessionStorage){const e=this.checkStorage(sessionStorage);if(e)return void this.identifyUser(e)}}catch{}}}checkAuthProviders(){const e=window;try{const t=e.Clerk?.user;if(t){const e=t.primaryEmailAddress?.emailAddress||t.emailAddresses?.[0]?.emailAddress;if(e&&this.isValidEmail(e))return{email:e,firstName:t.firstName||void 0,lastName:t.lastName||void 0}}}catch{}try{const t=e.firebase?.auth?.(),n=t?.currentUser;if(n?.email&&this.isValidEmail(n.email)){const e=(n.displayName||"").split(" ");return{email:n.email,firstName:e[0]||void 0,lastName:e.slice(1).join(" ")||void 0}}}catch{}try{const t=e.__SUPABASE_CLIENT__||e.supabase;if(t?.auth){const e=t.auth.session?.()||t.auth.getSession?.(),n=e?.data?.session?.user||e?.user;if(n?.email&&this.isValidEmail(n.email)){const e=n.user_metadata||{};return{email:n.email,firstName:e.first_name||e.full_name?.split(" ")[0]||void 0,lastName:e.last_name||e.full_name?.split(" ").slice(1).join(" ")||void 0}}}}catch{}try{const t=e.__auth0Client||e.auth0Client;if(t?.isAuthenticated?.()){const e=t.getUser?.();if(e?.email&&this.isValidEmail(e.email))return{email:e.email,firstName:e.given_name||e.name?.split(" ")[0]||void 0,lastName:e.family_name||e.name?.split(" ").slice(1).join(" ")||void 0}}}catch{}try{const t=e.__google_credential_response?.credential;if(t&&"string"==typeof t){const e=this.extractUserFromToken(t);if(e)return e}const n=e.gapi?.auth2?.getAuthInstance?.()?.currentUser?.get?.(),i=n?.getBasicProfile?.();if(i){const e=i.getEmail?.();if(e&&this.isValidEmail(e))return{email:e,firstName:i.getGivenName?.()||void 0,lastName:i.getFamilyName?.()||void 0}}}catch{}try{const t=e.msalInstance||e.__msalInstance;if(t){const e=(t.getAllAccounts?.()||[])[0];if(e?.username&&this.isValidEmail(e.username)){const t=(e.name||"").split(" ");return{email:e.username,firstName:t[0]||void 0,lastName:t.slice(1).join(" ")||void 0}}}}catch{}try{const t=e.aws_amplify_currentUser||e.__amplify_user;if(t?.signInDetails?.loginId&&this.isValidEmail(t.signInDetails.loginId))return{email:t.signInDetails.loginId,firstName:t.attributes?.given_name||void 0,lastName:t.attributes?.family_name||void 0};if("undefined"!=typeof localStorage){const e=this.checkCognitoStorage();if(e)return e}}catch{}try{const t=e.keycloak||e.Keycloak;if(t?.authenticated&&t.tokenParsed){const e=t.tokenParsed,n=e.email||e.preferred_username;if(n&&this.isValidEmail(n))return{email:n,firstName:e.given_name||void 0,lastName:e.family_name||void 0}}}catch{}try{const t=e.__clianta_user;if(t?.email&&"string"==typeof t.email&&this.isValidEmail(t.email))return{email:t.email,firstName:t.firstName||void 0,lastName:t.lastName||void 0}}catch{}return null}identifyUser(e){if(this.tracker&&this.identifiedEmail!==e.email){this.identifiedEmail=e.email,this.tracker.identify(e.email,{firstName:e.firstName,lastName:e.lastName});for(const e of this.pollTimeouts)clearTimeout(e);this.pollTimeouts=[]}}checkCookies(){if("undefined"==typeof document)return null;try{const e=document.cookie.split(";").map(e=>e.trim());for(const t of e){const[e,...n]=t.split("="),i=n.join("="),s=e.trim().toLowerCase();if(V.some(e=>s.includes(e.toLowerCase()))&&i){const e=this.extractUserFromToken(decodeURIComponent(i));if(e)return e}}}catch{}return null}checkStorage(e){try{for(let t=0;t<e.length;t++){const n=e.key(t);if(!n)continue;const i=n.toLowerCase();if(j.some(e=>i.includes(e.toLowerCase()))){const t=e.getItem(n);if(!t)continue;if(t.length>R)continue;const i=this.extractUserFromToken(t);if(i)return i;try{const e=JSON.parse(t),n=this.deepScanForUser(e,0);if(n)return n}catch{}}}}catch{}return null}deepScanForUser(e,t){if(t>4||!e||"object"!=typeof e||Array.isArray(e))return null;const n=e,i=Object.keys(n),s=this.extractUserFromClaims(n);if(s)return s;const o=i.slice(0,20);for(const e of o){const t=n[e];if("string"==typeof t&&t.length>30&&t.length<4e3){if(2===(t.match(/\./g)||[]).length){const e=this.extractUserFromToken(t);if(e)return e}}}for(const e of o){const i=n[e];if(i&&"object"==typeof i&&!Array.isArray(i)){const e=this.deepScanForUser(i,t+1);if(e)return e}}return null}extractUserFromToken(e){const t=e.split(".");if(3!==t.length)return null;try{const e=JSON.parse(atob(t[1].replace(/-/g,"+").replace(/_/g,"/")));return this.extractUserFromClaims(e)}catch{return null}}extractUserFromClaims(e){if(!e||"object"!=typeof e)return null;let t,n,i=null;for(const t of z){const n=e[t];if(n&&"string"==typeof n&&this.isValidEmail(n)){i=n;break}}if(!i){const t=e.primaryEmailAddress?.emailAddress||e.emailAddresses?.[0]?.emailAddress;t&&"string"==typeof t&&this.isValidEmail(t)&&(i=t)}if(!i)return null;for(const n of W)if(e[n]&&"string"==typeof e[n]){t=e[n];break}for(const t of K)if(e[t]&&"string"==typeof e[t]){n=e[t];break}if(!t)for(const i of B)if(e[i]&&"string"==typeof e[i]){const s=e[i].split(" ");t=s[0],n=n||s.slice(1).join(" ")||void 0;break}return{email:i,firstName:t,lastName:n}}async guardedSessionProbe(){if(this.identifiedEmail)return;const e="undefined"!=typeof document&&(document.cookie.includes("next-auth.session-token")||document.cookie.includes("__Secure-next-auth.session-token")),t="undefined"!=typeof window&&(null!=window.__NEXTAUTH||null!=window.__NEXT_DATA__);if(e||t)try{const e=await fetch("/api/auth/session",{method:"GET",credentials:"include",headers:{Accept:"application/json"}});if(e.ok){const t=await e.json();if(t&&"object"==typeof t&&Object.keys(t).length>0){const e=this.deepScanForUser(t,0);e&&this.identifyUser(e)}}}catch{}}checkCognitoStorage(){try{for(let e=0;e<localStorage.length;e++){const t=localStorage.key(e);if(t){if(t.startsWith("CognitoIdentityServiceProvider.")&&t.endsWith(".idToken")){const e=localStorage.getItem(t);if(e&&e.length<R){const t=this.extractUserFromToken(e);if(t)return t}}if(t.startsWith("CognitoIdentityServiceProvider.")&&t.endsWith(".userData")){const e=localStorage.getItem(t);if(e&&e.length<R)try{const t=JSON.parse(e),n=t.UserAttributes||t.attributes||[],i=n.find?.(e=>"email"===e.Name||"email"===e.name);if(i?.Value&&this.isValidEmail(i.Value)){const e=n.find?.(e=>"name"===e.Name||"name"===e.name),t=n.find?.(e=>"given_name"===e.Name||"given_name"===e.name),s=n.find?.(e=>"family_name"===e.Name||"family_name"===e.name);let o=t?.Value,r=s?.Value;if(!o&&e?.Value){const t=e.Value.split(" ");o=t[0],r=r||t.slice(1).join(" ")||void 0}return{email:i.Value,firstName:o||void 0,lastName:r||void 0}}}catch{}}}}}catch{}return null}isValidEmail(e){return U.test(e)}}function Y(e){switch(e){case"pageView":return new L;case"scroll":return new N;case"forms":return new F;case"clicks":return new P;case"engagement":return new A;case"downloads":return new O;case"exitIntent":return new M;case"errors":return new $;case"performance":return new D;case"popupForms":return new q;case"autoIdentify":return new Q;default:throw new Error(`Unknown plugin: ${e}`)}}function G(e){try{if("undefined"==typeof localStorage)return!1;const t={state:e,timestamp:Date.now(),version:1};return localStorage.setItem(a,JSON.stringify(t)),!0}catch{return!1}}function X(){try{if("undefined"==typeof localStorage)return null;const e=localStorage.getItem(a);if(!e)return null;const t=JSON.parse(e);return 1!==t.version?(Z(),null):t}catch{return null}}function Z(){try{return"undefined"!=typeof localStorage&&(localStorage.removeItem(a),!0)}catch{return!1}}class ee{constructor(e={}){this.eventBuffer=[],this.callbacks=[],this.hasExplicitConsent=!1,this.config={defaultConsent:{analytics:!0,marketing:!1,personalization:!1},waitForConsent:!1,storageKey:"mb_consent",...e};const t=X();t?(this.state=t.state,this.hasExplicitConsent=!0,m.debug("Loaded stored consent:",this.state)):(this.state=this.config.defaultConsent||{analytics:!0},this.hasExplicitConsent=!1,m.debug("Using default consent:",this.state)),e.onConsentChange&&this.callbacks.push(e.onConsentChange)}grant(e){const t={...this.state};this.state={...this.state,...e},this.hasExplicitConsent=!0,G(this.state),m.info("Consent granted:",e),this.notifyChange(t)}revoke(e){const t={...this.state};for(const t of e)this.state[t]=!1;this.hasExplicitConsent=!0,G(this.state),m.info("Consent revoked:",e),this.notifyChange(t)}update(e){const t={...this.state};this.state={...e},this.hasExplicitConsent=!0,G(this.state),m.info("Consent updated:",this.state),this.notifyChange(t)}reset(){const e={...this.state};this.state=this.config.defaultConsent||{analytics:!0},this.hasExplicitConsent=!1,this.eventBuffer=[],Z(),m.info("Consent reset to defaults"),this.notifyChange(e)}getState(){return{...this.state}}hasConsent(e){return!0===this.state[e]}canTrack(){return!(this.config.waitForConsent&&!this.hasExplicitConsent)&&!0===this.state.analytics}hasExplicit(){return this.hasExplicitConsent}hasStored(){return null!==X()}bufferEvent(e){this.eventBuffer.length>=100&&(m.warn("Consent event buffer full, dropping oldest event"),this.eventBuffer.shift()),this.eventBuffer.push(e),m.debug("Event buffered (waiting for consent):",e.eventName)}flushBuffer(){const e=[...this.eventBuffer];return this.eventBuffer=[],e.length>0&&m.debug(`Flushing ${e.length} buffered events`),e}getBufferSize(){return this.eventBuffer.length}onChange(e){return this.callbacks.push(e),()=>{const t=this.callbacks.indexOf(e);t>-1&&this.callbacks.splice(t,1)}}notifyChange(e){for(const t of this.callbacks)try{t(this.state,e)}catch(e){m.error("Consent change callback error:",e)}}}class te{constructor(e,t={}){if(this.plugins=[],this.isInitialized=!1,this.contactId=null,this.groupId=null,this.pendingIdentify=null,this.eventSchemas=new Map,this.middlewares=[],this.readyCallbacks=[],!e)throw new Error("[Clianta] Workspace ID is required");this.workspaceId=e,this.config=function(e={}){return{...i,...e,consent:{...i.consent,...e.consent}}}(t),m.enabled=this.config.debug,m.info(`Initializing SDK v${n}`,{workspaceId:e}),this.consentManager=new ee({...this.config.consent,onConsentChange:(e,t)=>{this.onConsentChange(e,t)}}),this.transport=new p({apiEndpoint:this.config.apiEndpoint}),this.queue=new C(this.transport,{batchSize:this.config.batchSize,flushInterval:this.config.flushInterval}),this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),m.debug("IDs created",{visitorId:this.visitorId,sessionId:this.sessionId}),!this.config.apiEndpoint.startsWith("http://")||"undefined"==typeof window||window.location.hostname.includes("localhost")||window.location.hostname.includes("127.0.0.1")||m.warn("apiEndpoint uses HTTP — events will be sent unencrypted. Use HTTPS in production."),this.initPlugins(),this.isInitialized=!0,m.info("SDK initialized successfully");for(const e of this.readyCallbacks)try{e()}catch(e){m.error("onReady callback error:",e)}this.readyCallbacks=[]}createVisitorId(){if(this.config.consent.anonymousMode&&!this.consentManager.hasExplicit()){const e=s+"_anon";let t=y(e);return t||(t="anon_"+g(),w(e,t)),t}if(this.config.cookielessMode){let e=y(s);return e||(e=g(),w(s,e)),e}return b(this.config.useCookies)}createSessionId(){return function(e){const t=o,n=r;let i=y(t);const s=parseInt(y(n)||"0",10),a=Date.now();return(!i||a-s>e)&&(i=g(),w(t,i)),w(n,a.toString()),i}(this.config.sessionTimeout)}onConsentChange(e,t){if(m.debug("Consent changed:",{from:t,to:e}),e.analytics&&!t.analytics){this.config.consent.anonymousMode&&(this.visitorId=b(this.config.useCookies),m.info("Upgraded from anonymous to persistent visitor ID"));const e=this.consentManager.flushBuffer();for(const t of e)t.visitorId=this.visitorId,this.queue.push(t)}}initPlugins(){const e=this.config.plugins,t=this.config.autoPageView?e:e.filter(e=>"pageView"!==e);for(const e of t)try{const t=Y(e),n=t.init(this);n instanceof Promise&&n.catch(t=>{m.error(`Async plugin init failed: ${e}`,t)}),this.plugins.push(t),m.debug(`Plugin loaded: ${e}`)}catch(t){m.error(`Failed to load plugin: ${e}`,t)}}track(e,t,i={}){if(!this.isInitialized)return void m.warn("SDK not initialized, event dropped");const s={workspaceId:this.workspaceId,visitorId:this.visitorId,sessionId:this.sessionId,eventType:e,eventName:t,url:"undefined"!=typeof window?window.location.href:"",referrer:"undefined"!=typeof document&&document.referrer||void 0,properties:{...i,eventId:g(),websiteDomain:"undefined"!=typeof window?window.location.hostname:void 0},device:"undefined"==typeof window||"undefined"==typeof navigator?{userAgent:"unknown",screen:"unknown",language:"unknown",timezone:"unknown"}:{userAgent:navigator.userAgent,screen:`${screen.width}x${screen.height}`,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||"unknown"},...E(),timestamp:(new Date).toISOString(),sdkVersion:n};if(this.contactId&&(s.contactId=this.contactId),this.groupId&&(s.groupId=this.groupId),this.validateEventSchema(e,i),!this.consentManager.canTrack())return this.config.consent.waitForConsent?void this.consentManager.bufferEvent(s):void m.debug("Event dropped (no consent):",t);this.runMiddleware(s,()=>{this.queue.push(s),m.debug("Event tracked:",t,i)})}page(e,t={}){const n=e||("undefined"!=typeof document?document.title:"Page View");this.track("page_view",n,{...t,path:"undefined"!=typeof window?window.location.pathname:""})}async identify(e,t={}){if(!e)return m.warn("Email is required for identification"),null;if(!function(e){return!("string"!=typeof e||!e)&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}(e))return m.warn("Invalid email format, identification skipped:",e),null;m.info("Identifying visitor:",e);const n=await this.transport.sendIdentify({workspaceId:this.workspaceId,visitorId:this.visitorId,email:e,properties:t});return n.success?(m.info("Visitor identified successfully, contactId:",n.contactId),this.contactId=n.contactId??null,this.pendingIdentify=null,this.contactId):(m.error("Failed to identify visitor:",n.error),this.pendingIdentify={email:e,traits:t},null)}async retryPendingIdentify(){if(!this.pendingIdentify)return;const{email:e,traits:t}=this.pendingIdentify;this.pendingIdentify=null,await this.identify(e,t)}consent(e){this.consentManager.update(e)}getConsentState(){return this.consentManager.getState()}debug(e){m.enabled=e,m.info("Debug mode "+(e?"enabled":"disabled"))}group(e,t={}){e?(this.groupId=e,m.info("Visitor grouped:",e),this.track("group","Group Identified",{groupId:e,...t})):m.warn("groupId is required for group()")}async alias(e,t){if(!e)return m.warn("newId is required for alias()"),!1;const n=t||this.visitorId;m.info("Aliasing visitor:",{from:n,to:e});const i=await this.transport.sendPost("/api/public/track/alias",{workspaceId:this.workspaceId,previousId:n,newId:e});return i.success?(m.info("Alias successful"),!0):(m.error("Alias failed:",i.error??i.status),!1)}screen(e,t={}){this.track("screen_view",e,{...t,screenName:e})}use(e){this.middlewares.push(e),m.debug("Middleware registered")}runMiddleware(e,t){if(0===this.middlewares.length)return void t();let n=0;const i=this.middlewares,s=()=>{if(n++,n<i.length)try{i[n](e,s)}catch(e){m.error("Middleware error:",e),t()}else t()};try{i[0](e,s)}catch(e){m.error("Middleware error:",e),t()}}onReady(e){if(this.isInitialized)try{e()}catch(e){m.error("onReady callback error:",e)}else this.readyCallbacks.push(e)}isReady(){return this.isInitialized}registerEventSchema(e,t){this.eventSchemas.set(e,t),m.debug("Event schema registered:",e)}validateEventSchema(e,t){if(!this.config.debug)return;const n=this.eventSchemas.get(e);if(n)for(const[i,s]of Object.entries(n)){const n=t[i];if(void 0===n){m.warn(`[Schema] Missing property "${i}" for event type "${e}"`);continue}let o=!1;switch(s){case"string":o="string"==typeof n;break;case"number":o="number"==typeof n;break;case"boolean":o="boolean"==typeof n;break;case"object":o="object"==typeof n&&!Array.isArray(n);break;case"array":o=Array.isArray(n)}o||m.warn(`[Schema] Property "${i}" for event "${e}" expected ${s}, got ${typeof n}`)}}getVisitorId(){return this.visitorId}getSessionId(){return this.sessionId}getWorkspaceId(){return this.workspaceId}getConfig(){return{...this.config}}async flush(){await this.retryPendingIdentify(),await this.queue.flush()}reset(){m.info("Resetting visitor data"),k(this.config.useCookies),this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),this.contactId=null,this.pendingIdentify=null,this.queue.clear()}deleteData(){if(m.info("Deleting all user data (GDPR request)"),this.queue.clear(),this.consentManager.reset(),k(this.config.useCookies),"undefined"!=typeof sessionStorage)try{sessionStorage.removeItem(s),sessionStorage.removeItem(s+"_anon"),sessionStorage.removeItem(o),sessionStorage.removeItem(r)}catch{}if("undefined"!=typeof localStorage)try{localStorage.removeItem(s),localStorage.removeItem(a),localStorage.removeItem(d)}catch{}this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),m.info("All user data deleted")}async createContact(e){return this.publicCrmRequest("/api/public/crm/contacts","POST",{workspaceId:this.workspaceId,...e})}async updateContact(e,t){return this.publicCrmRequest(`/api/public/crm/contacts/${e}`,"PUT",{workspaceId:this.workspaceId,...t})}async submitForm(e,t){const n={...t,metadata:{...t.metadata,visitorId:this.visitorId,sessionId:this.sessionId,pageUrl:"undefined"!=typeof window?window.location.href:void 0,referrer:"undefined"!=typeof document&&document.referrer||void 0}};return this.publicCrmRequest(`/api/public/crm/forms/${e}/submit`,"POST",n)}async logActivity(e){return this.publicCrmRequest("/api/public/crm/activities","POST",{workspaceId:this.workspaceId,...e})}async createOpportunity(e){return this.publicCrmRequest("/api/public/crm/opportunities","POST",{workspaceId:this.workspaceId,...e})}async publicCrmRequest(e,t,n){const i=`${this.config.apiEndpoint}${e}`;try{const s=await fetch(i,{method:t,headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),o=await s.json().catch(()=>({}));return s.ok?(m.debug(`Public CRM ${t} ${e} succeeded`),{success:!0,data:o.data??o,status:s.status}):(m.error(`Public CRM ${t} ${e} failed (${s.status}):`,o.message),{success:!1,error:o.message,status:s.status})}catch(n){return m.error(`Public CRM ${t} ${e} error:`,n),{success:!1,error:n.message}}}async destroy(){m.info("Destroying tracker"),await this.queue.flush();for(const e of this.plugins)e.destroy&&e.destroy();this.plugins=[],this.queue.destroy(),this.isInitialized=!1}}let ne=null;function ie(e,t){return ne&&ne.getWorkspaceId()===e?(t&&Object.keys(t).length>0&&"undefined"!=typeof console&&console.warn('[Clianta] clianta() called with config on an already-initialized instance for workspace "'+e+'". The new config was ignored. Call tracker.destroy() first if you need to reconfigure.'),ne):(ne&&ne.destroy(),ne=new te(e,t),ne)}if("undefined"!=typeof window){window.clianta=ie,window.Clianta={clianta:ie,Tracker:te,ConsentManager:ee};const e=()=>{const e=document.querySelectorAll("script[data-project-id]"),t=e[e.length-1];if(!t)return;const n=t.getAttribute("data-project-id");if(!n)return;const i={debug:t.hasAttribute("data-debug")},s=t.getAttribute("data-api-endpoint");s&&(i.apiEndpoint=s),t.hasAttribute("data-cookieless")&&(i.cookielessMode=!0),t.hasAttribute("data-use-cookies")&&(i.useCookies=!0);const o=ie(n,i);window.__clianta=o};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}e.ConsentManager=ee,e.SDK_VERSION=n,e.Tracker=te,e.clianta=ie,e.default=ie,Object.defineProperty(e,"__esModule",{value:!0})});
6
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Clianta={})}(this,function(e){"use strict";var t="undefined"!=typeof document?document.currentScript:null;const i="1.7.2",n={projectId:"",apiEndpoint:(()=>{if("undefined"!=typeof process&&process.env?.NEXT_PUBLIC_CLIANTA_API_ENDPOINT)return process.env.NEXT_PUBLIC_CLIANTA_API_ENDPOINT;try{"undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(__filename).href:"undefined"==typeof document?location.href:t&&"SCRIPT"===t.tagName.toUpperCase()&&t.src||new URL("clianta.umd.min.js",document.baseURI).href,0}catch{}if("undefined"!=typeof process&&process.env?.REACT_APP_CLIANTA_API_ENDPOINT)return process.env.REACT_APP_CLIANTA_API_ENDPOINT;if("undefined"!=typeof process&&process.env?.CLIANTA_API_ENDPOINT)return process.env.CLIANTA_API_ENDPOINT;return"undefined"!=typeof window&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname)||"undefined"==typeof console||console.warn("[Clianta] No API endpoint configured. Set NEXT_PUBLIC_CLIANTA_API_ENDPOINT (Next.js), VITE_CLIANTA_API_ENDPOINT (Vite), or pass apiEndpoint directly to clianta(). Falling back to localhost — tracking will not work in production."),"http://localhost:5000"})(),debug:!1,autoPageView:!0,plugins:["pageView","forms","scroll","clicks","engagement","downloads","exitIntent","errors","performance","autoIdentify"],sessionTimeout:18e5,batchSize:10,flushInterval:5e3,consent:{defaultConsent:{analytics:!0,marketing:!1,personalization:!1},waitForConsent:!1,storageKey:"mb_consent",anonymousMode:!1},cookieDomain:"",useCookies:!1,cookielessMode:!1,persistMode:"session"},s="mb_vid",r="mb_sid",o="mb_st",a="mb_consent",c="mb_queue",d=[25,50,75,100],l=[".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".rar",".tar",".gz",".7z",".csv",".txt",".json",".xml",".mp3",".mp4",".wav",".avi",".mov"];const u="[Clianta]",h={debug:"color: #6b7280; font-weight: normal;",info:"color: #3b82f6; font-weight: normal;",warn:"color: #f59e0b; font-weight: bold;",error:"color: #ef4444; font-weight: bold;"},p={debug:0,info:1,warn:2,error:3};const m=function(e=!1){let t="debug",i=e;const n=e=>!!i&&p[e]>=p[t],s=(e,t)=>"undefined"!=typeof console&&"undefined"!=typeof window?[`%c${u}`,h[e],...t]:[`${u} [${e.toUpperCase()}]`,...t];return{get enabled(){return i},set enabled(e){i=e},debug(...e){n("debug")&&"undefined"!=typeof console&&console.log(...s("debug",e))},info(...e){n("info")&&"undefined"!=typeof console&&console.info(...s("info",e))},warn(...e){n("warn")&&"undefined"!=typeof console&&console.warn(...s("warn",e))},error(...e){n("error")&&"undefined"!=typeof console&&console.error(...s("error",e))},setLevel(e){t=e}}}(!1);class g{constructor(e){this.config={apiEndpoint:e.apiEndpoint,maxRetries:e.maxRetries??3,retryDelay:e.retryDelay??1e3,timeout:e.timeout??1e4}}async sendEvents(e){const t=`${this.config.apiEndpoint}/api/public/track/event`,i=JSON.stringify({events:e});if(i.length>6e4){return this.sendBeacon(e)?{success:!0}:this.send(t,i,1,!1)}return this.send(t,i)}async sendIdentify(e,t=1){const i=`${this.config.apiEndpoint}/api/public/track/identify`;try{const n=await this.fetchWithTimeout(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0}),s=await n.json().catch(()=>({}));if(n.ok)return m.debug("Identify successful, contactId:",s.contactId),{success:!0,status:n.status,contactId:s.contactId??void 0};if(n.status>=500&&t<this.config.maxRetries){const i=this.config.retryDelay*Math.pow(2,t-1);return m.warn(`Identify server error (${n.status}), retrying in ${i}ms...`),await this.delay(i),this.sendIdentify(e,t+1)}return m.error(`Identify failed with status ${n.status}:`,s.message),{success:!1,status:n.status}}catch(i){if(("undefined"==typeof navigator||navigator.onLine)&&t<this.config.maxRetries){const i=this.config.retryDelay*Math.pow(2,t-1);return m.warn(`Identify network error, retrying in ${i}ms (${t}/${this.config.maxRetries})...`),await this.delay(i),this.sendIdentify(e,t+1)}return m.error("Identify request failed after retries:",i),{success:!1,error:i}}}sendBeacon(e){if("undefined"==typeof navigator||!navigator.sendBeacon)return m.warn("sendBeacon not available, events may be lost"),!1;const t=`${this.config.apiEndpoint}/api/public/track/event`,i=JSON.stringify({events:e}),n=new Blob([i],{type:"application/json"});try{const i=navigator.sendBeacon(t,n);return i?m.debug(`Beacon sent ${e.length} events`):m.warn("sendBeacon returned false"),i}catch(e){return m.error("sendBeacon error:",e),!1}}async sendPost(e,t){const i=`${this.config.apiEndpoint}${e}`,n=JSON.stringify(t);return this.send(i,n)}async fetchData(e,t){const i=new URL(`${this.config.apiEndpoint}${e}`);t&&Object.entries(t).forEach(([e,t])=>{null!=t&&i.searchParams.set(e,t)});try{const t=await this.fetchWithTimeout(i.toString(),{method:"GET",headers:{Accept:"application/json"}});if(t.ok){const i=await t.json();return m.debug("Fetch successful:",e),{success:!0,data:i.data??i,status:t.status}}return m.error(`Fetch failed with status ${t.status}`),{success:!1,status:t.status}}catch(e){return m.error("Fetch request failed:",e),{success:!1,error:e}}}async send(e,t,i=1,n=!0){if("undefined"!=typeof navigator&&!navigator.onLine)return m.warn("Device offline, skipping send"),{success:!1,error:new Error("offline")};try{const s=await this.fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:n});if(s.ok)return m.debug("Request successful:",e),{success:!0,status:s.status};if(s.status>=500&&i<this.config.maxRetries){const r=this.config.retryDelay*Math.pow(2,i-1);return m.warn(`Server error (${s.status}), retrying in ${r}ms...`),await this.delay(r),this.send(e,t,i+1,n)}return m.error(`Request failed with status ${s.status}`),{success:!1,status:s.status}}catch(s){if(("undefined"==typeof navigator||navigator.onLine)&&i<this.config.maxRetries){const s=this.config.retryDelay*Math.pow(2,i-1);return m.warn(`Network error, retrying in ${s}ms (${i}/${this.config.maxRetries})...`),await this.delay(s),this.send(e,t,i+1,n)}return m.error("Request failed after retries:",s),{success:!1,error:s}}}async fetchWithTimeout(e,t){const i=new AbortController,n=setTimeout(()=>i.abort(),this.config.timeout);try{return await fetch(e,{...t,signal:i.signal})}finally{clearTimeout(n)}}delay(e){return new Promise(t=>setTimeout(t,e))}}function f(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function y(e){try{if("undefined"!=typeof localStorage)return localStorage.getItem(e)}catch{}return null}function w(e,t){try{if("undefined"!=typeof localStorage)return localStorage.setItem(e,t),!0}catch{}return!1}function v(e){try{if("undefined"!=typeof sessionStorage)return sessionStorage.getItem(e)}catch{}return null}function b(e,t){try{if("undefined"!=typeof sessionStorage)return sessionStorage.setItem(e,t),!0}catch{}return!1}function k(e,t,i){if("undefined"==typeof document)return null;if(void 0===t){const t=document.cookie.match(new RegExp("(^| )"+e+"=([^;]+)"));return t?t[2]:null}let n="";if(i){const e=new Date;e.setTime(e.getTime()+24*i*60*60*1e3),n="; expires="+e.toUTCString()}const s="undefined"!=typeof location&&"https:"===location.protocol?"; Secure":"";return document.cookie=e+"="+t+n+"; path=/; SameSite=Lax"+s,t}function S(e=!1){const t=s;let i=null;return i=e?k(t):y(t),i||(i=f(),e?k(t,i,365):w(t,i)),i}function T(e=!1){const t=s;if(e)k(t,"",-1);else try{localStorage.removeItem(t)}catch{}try{sessionStorage.removeItem(r),sessionStorage.removeItem(o)}catch{}}function I(e){try{return e.split("/").pop()?.split("?")[0]||"unknown"}catch{return"unknown"}}function E(e){const t=I(e).split(".");return t.length>1&&t.pop()||"unknown"}function C(e,t=100){return(e.innerText||e.textContent||e.value||"").trim().substring(0,t)}function x(e){return["BUTTON","A","INPUT"].includes(e.tagName)||e.hasAttribute("data-track-click")||e.classList.contains("track-click")}class ${constructor(e,t={}){this.queue=[],this.flushTimer=null,this.isFlushing=!1,this.isOnline=!0,this.eventTimestamps=[],this.boundBeforeUnload=null,this.boundVisibilityChange=null,this.boundPageHide=null,this.boundOnline=null,this.boundOffline=null,this.unloadFlushed=!1,this.transport=e,this.config={batchSize:t.batchSize??10,flushInterval:t.flushInterval??5e3,maxQueueSize:t.maxQueueSize??1e3,storageKey:t.storageKey??c,persistMode:t.persistMode??"session"},this.persistMode=this.config.persistMode,this.isOnline="undefined"==typeof navigator||navigator.onLine,this.restoreQueue(),this.startFlushTimer(),this.setupUnloadHandlers()}push(e){this.checkRateLimit()?(this.queue.length>=this.config.maxQueueSize&&(m.warn("Queue full, dropping oldest event"),this.queue.shift()),this.queue.push(e),m.debug("Event queued:",e.eventName,`(${this.queue.length} in queue)`),this.queue.length>=this.config.batchSize&&this.flush()):m.warn("Rate limit exceeded, event dropped:",e.eventName)}checkRateLimit(){const e=Date.now();return this.eventTimestamps=this.eventTimestamps.filter(t=>e-t<6e4),!(this.eventTimestamps.length>=100)&&(this.eventTimestamps.push(e),!0)}async flush(){if(this.isFlushing||0===this.queue.length||!this.isOnline)return;this.isFlushing=!0;const e=this.queue.length,t=this.queue.splice(0,e);try{m.debug(`Flushing ${t.length} events`),this.persistQueue([]);if((await this.transport.sendEvents(t)).success)m.debug("Flush successful");else{m.warn("Flush failed, re-queuing events");const e=this.config.maxQueueSize-this.queue.length,i=t.slice(0,Math.max(0,e));this.queue.unshift(...i),this.persistQueue(this.queue)}}catch(e){m.error("Flush error:",e)}finally{this.isFlushing=!1}}flushSync(){if(this.unloadFlushed||0===this.queue.length)return;this.unloadFlushed=!0;const e=this.queue.splice(0,this.queue.length);m.debug(`Sync flushing ${e.length} events via beacon`);this.transport.sendBeacon(e)||(this.queue.unshift(...e),this.persistQueue(this.queue))}get length(){return this.queue.length}clear(){if(this.queue=[],this.persistQueue([]),"local"===this.persistMode&&"undefined"!=typeof localStorage)try{localStorage.removeItem(this.config.storageKey)}catch{}}destroy(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),"undefined"!=typeof window&&(this.boundBeforeUnload&&window.removeEventListener("beforeunload",this.boundBeforeUnload),this.boundVisibilityChange&&window.removeEventListener("visibilitychange",this.boundVisibilityChange),this.boundPageHide&&window.removeEventListener("pagehide",this.boundPageHide),this.boundOnline&&window.removeEventListener("online",this.boundOnline),this.boundOffline&&window.removeEventListener("offline",this.boundOffline))}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=setInterval(()=>{this.flush()},this.config.flushInterval)}setupUnloadHandlers(){"undefined"!=typeof window&&(this.boundBeforeUnload=()=>this.flushSync(),window.addEventListener("beforeunload",this.boundBeforeUnload),this.boundVisibilityChange=()=>{"hidden"===document.visibilityState?this.flushSync():this.unloadFlushed=!1},window.addEventListener("visibilitychange",this.boundVisibilityChange),this.boundPageHide=()=>this.flushSync(),window.addEventListener("pagehide",this.boundPageHide),this.boundOnline=()=>{m.info("Connection restored — flushing queued events"),this.isOnline=!0,this.flush()},this.boundOffline=()=>{m.warn("Connection lost — pausing event queue"),this.isOnline=!1},window.addEventListener("online",this.boundOnline),window.addEventListener("offline",this.boundOffline))}persistQueue(e){if("none"!==this.persistMode)try{const t=JSON.stringify(e);if("local"===this.persistMode&&"undefined"!=typeof localStorage)try{localStorage.setItem(this.config.storageKey,t)}catch{b(this.config.storageKey,t)}else b(this.config.storageKey,t)}catch{}}restoreQueue(){try{let e=null;if("local"===this.persistMode&&"undefined"!=typeof localStorage&&(e=localStorage.getItem(this.config.storageKey)),e||(e=v(this.config.storageKey)),e){const t=JSON.parse(e);Array.isArray(t)&&t.length>0&&(this.queue=t,m.debug(`Restored ${t.length} events from storage`))}}catch{}}}class _{constructor(){this.tracker=null}init(e){this.tracker=e}destroy(){this.tracker=null}track(e,t,i){this.tracker&&this.tracker.track(e,t,i)}}const L="__clianta_pv_wrapped__";class N extends _{constructor(){super(...arguments),this.name="pageView",this.originalPushState=null,this.originalReplaceState=null,this.navHandler=null,this.popstateHandler=null}init(e){if(super.init(e),this.trackPageView(),"undefined"!=typeof window){if(!history.pushState[L]){this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;const e=this.originalPushState,t=this.originalReplaceState;history.pushState=function(...t){e.apply(history,t),window.dispatchEvent(new Event("clianta:navigation"))},history.pushState[L]=!0,history.replaceState=function(...e){t.apply(history,e),window.dispatchEvent(new Event("clianta:navigation"))},history.replaceState[L]=!0}this.navHandler=()=>this.trackPageView(),window.addEventListener("clianta:navigation",this.navHandler),this.popstateHandler=()=>this.trackPageView(),window.addEventListener("popstate",this.popstateHandler)}}destroy(){"undefined"!=typeof window&&(this.navHandler&&(window.removeEventListener("clianta:navigation",this.navHandler),this.navHandler=null),this.popstateHandler&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null)),this.originalPushState&&(history.pushState=this.originalPushState,delete history.pushState[L],this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,delete history.replaceState[L],this.originalReplaceState=null),super.destroy()}trackPageView(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.track("page_view","Page Viewed",{title:document.title,path:window.location.pathname,search:window.location.search,hash:window.location.hash,referrer:document.referrer||"direct",viewport:`${window.innerWidth}x${window.innerHeight}`})}}class P extends _{constructor(){super(...arguments),this.name="scroll",this.milestonesReached=new Set,this.maxScrollDepth=0,this.pageLoadTime=0,this.scrollTimeout=null,this.boundHandler=null,this.navigationHandler=null,this.popstateHandler=null}init(e){super.init(e),this.pageLoadTime=Date.now(),"undefined"!=typeof window&&(this.boundHandler=this.handleScroll.bind(this),window.addEventListener("scroll",this.boundHandler,{passive:!0}),this.navigationHandler=()=>this.resetForNavigation(),window.addEventListener("clianta:navigation",this.navigationHandler),this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler))}destroy(){this.boundHandler&&"undefined"!=typeof window&&window.removeEventListener("scroll",this.boundHandler),this.scrollTimeout&&clearTimeout(this.scrollTimeout),this.navigationHandler&&"undefined"!=typeof window&&(window.removeEventListener("clianta:navigation",this.navigationHandler),this.navigationHandler=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),super.destroy()}resetForNavigation(){this.milestonesReached.clear(),this.maxScrollDepth=0,this.pageLoadTime=Date.now()}handleScroll(){this.scrollTimeout&&clearTimeout(this.scrollTimeout),this.scrollTimeout=setTimeout(()=>this.trackScrollDepth(),150)}trackScrollDepth(){if("undefined"==typeof window||"undefined"==typeof document)return;const e=window.innerHeight,t=document.documentElement.scrollHeight,i=window.pageYOffset||document.documentElement.scrollTop,n=t-e;if(n<=0)return;const s=Math.floor(i/n*100),r=Math.max(0,Math.min(100,s));r>this.maxScrollDepth&&(this.maxScrollDepth=r);for(const e of d)r>=e&&!this.milestonesReached.has(e)&&(this.milestonesReached.add(e),this.track("scroll_depth",`Scrolled ${e}%`,{depth:e,maxDepth:this.maxScrollDepth,timeToReach:Date.now()-this.pageLoadTime}))}}class H extends _{constructor(){super(...arguments),this.name="forms",this.trackedForms=new WeakSet,this.formInteractions=new Set,this.observer=null,this.observerTimer=null,this.listeners=[]}init(e){super.init(e),"undefined"!=typeof document&&(this.trackAllForms(),"undefined"!=typeof MutationObserver&&(this.observer=new MutationObserver(()=>{this.observerTimer&&clearTimeout(this.observerTimer),this.observerTimer=setTimeout(()=>this.trackAllForms(),100)}),this.observer.observe(document.body,{childList:!0,subtree:!0})))}destroy(){this.observerTimer&&(clearTimeout(this.observerTimer),this.observerTimer=null),this.observer&&(this.observer.disconnect(),this.observer=null);for(const{element:e,event:t,handler:i}of this.listeners)e.removeEventListener(t,i);this.listeners=[],super.destroy()}addListener(e,t,i){e.addEventListener(t,i),this.listeners.push({element:e,event:t,handler:i})}trackAllForms(){document.querySelectorAll("form").forEach(e=>{this.setupFormTracking(e)})}setupFormTracking(e){if(this.trackedForms.has(e))return;this.trackedForms.add(e);const t=e.id||e.name||`form-${Math.random().toString(36).substring(2,11)}`;this.track("form_view","Form Viewed",{formId:t,action:e.action,method:e.method,fieldCount:e.elements.length}),Array.from(e.elements).forEach(e=>{if(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement){if(!e.name||"submit"===e.type||"button"===e.type)return;["focus","blur","change"].forEach(i=>{this.addListener(e,i,()=>{const n=`${t}-${e.name}-${i}`;this.formInteractions.has(n)||(this.formInteractions.add(n),this.track("form_interaction","Form Field Interaction",{formId:t,fieldName:e.name,fieldType:e.type,interactionType:i}))})})}});this.addListener(e,"submit",()=>{this.track("form_submit","Form Submitted",{formId:t,action:e.action,method:e.method}),this.autoIdentify(e)})}autoIdentify(e){const t=e.querySelector('input[type="email"], input[name*="email"]');if(!t?.value||!this.tracker)return;const i=t.value,n={},s=e.querySelector('[name*="first"], [name*="fname"]'),r=e.querySelector('[name*="last"], [name*="lname"]'),o=e.querySelector('[name*="company"], [name*="organization"]'),a=e.querySelector('[type="tel"], [name*="phone"]');s?.value&&(n.firstName=s.value),r?.value&&(n.lastName=r.value),o?.value&&(n.company=o.value),a?.value&&(n.phone=a.value),this.tracker.identify(i,n)}}class q extends _{constructor(){super(...arguments),this.name="clicks",this.boundHandler=null}init(e){super.init(e),"undefined"!=typeof document&&(this.boundHandler=this.handleClick.bind(this),document.addEventListener("click",this.boundHandler,!0))}destroy(){this.boundHandler&&"undefined"!=typeof document&&document.removeEventListener("click",this.boundHandler,!0),super.destroy()}handleClick(e){let t=e.target;for(;t&&!x(t);)t=t.parentElement;if(!t)return;const i=C(t,100),n=(s=t,{tag:s.tagName?.toLowerCase()||"unknown",id:s.id||"",className:s.className||"",text:C(s,50)});var s;this.track("button_click","Button Clicked",{buttonText:i,elementType:t.tagName.toLowerCase(),elementId:n.id,elementClass:n.className,href:t.href||void 0,x:Math.round(e.clientX/window.innerWidth*100),y:Math.round(e.clientY/window.innerHeight*100),viewportWidth:window.innerWidth,viewportHeight:window.innerHeight})}}class A extends _{constructor(){super(...arguments),this.name="engagement",this.pageLoadTime=0,this.engagementStartTime=0,this.isEngaged=!1,this.engagementTimeout=null,this.unloadReported=!1,this.boundMarkEngaged=null,this.boundTrackTimeOnPage=null,this.boundVisibilityHandler=null,this.navigationHandler=null,this.popstateHandler=null}init(e){super.init(e),this.pageLoadTime=Date.now(),this.engagementStartTime=Date.now(),"undefined"!=typeof document&&"undefined"!=typeof window&&(this.boundMarkEngaged=this.markEngaged.bind(this),this.boundTrackTimeOnPage=this.trackTimeOnPage.bind(this),this.boundVisibilityHandler=()=>{"hidden"===document.visibilityState?this.trackTimeOnPage():(this.engagementStartTime=Date.now(),this.unloadReported=!1)},["mousemove","keydown","touchstart","scroll"].forEach(e=>{document.addEventListener(e,this.boundMarkEngaged,{passive:!0})}),window.addEventListener("beforeunload",this.boundTrackTimeOnPage),document.addEventListener("visibilitychange",this.boundVisibilityHandler),this.navigationHandler=()=>this.resetForNavigation(),window.addEventListener("clianta:navigation",this.navigationHandler),this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler))}destroy(){this.boundMarkEngaged&&"undefined"!=typeof document&&["mousemove","keydown","touchstart","scroll"].forEach(e=>{document.removeEventListener(e,this.boundMarkEngaged)}),this.boundTrackTimeOnPage&&"undefined"!=typeof window&&window.removeEventListener("beforeunload",this.boundTrackTimeOnPage),this.boundVisibilityHandler&&"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.boundVisibilityHandler),this.navigationHandler&&"undefined"!=typeof window&&(window.removeEventListener("clianta:navigation",this.navigationHandler),this.navigationHandler=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),this.engagementTimeout&&clearTimeout(this.engagementTimeout),super.destroy()}resetForNavigation(){this.pageLoadTime=Date.now(),this.engagementStartTime=Date.now(),this.isEngaged=!1,this.unloadReported=!1,this.engagementTimeout&&(clearTimeout(this.engagementTimeout),this.engagementTimeout=null)}markEngaged(){this.isEngaged||(this.isEngaged=!0,this.track("engagement","User Engaged",{timeToEngage:Date.now()-this.pageLoadTime})),this.engagementTimeout&&clearTimeout(this.engagementTimeout),this.engagementTimeout=setTimeout(()=>{this.isEngaged=!1},3e4)}trackTimeOnPage(){if(this.unloadReported)return;this.unloadReported=!0;const e=Math.floor((Date.now()-this.engagementStartTime)/1e3);e>0&&this.track("time_on_page","Time Spent",{seconds:e,engaged:this.isEngaged})}}class O extends _{constructor(){super(...arguments),this.name="downloads",this.trackedDownloads=new Set,this.boundHandler=null,this.navigationHandler=null,this.popstateHandler=null}init(e){super.init(e),"undefined"!=typeof document&&(this.boundHandler=this.handleClick.bind(this),document.addEventListener("click",this.boundHandler,!0)),"undefined"!=typeof window&&(this.navigationHandler=()=>this.resetForNavigation(),window.addEventListener("clianta:navigation",this.navigationHandler),this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler))}destroy(){this.boundHandler&&"undefined"!=typeof document&&document.removeEventListener("click",this.boundHandler,!0),this.navigationHandler&&"undefined"!=typeof window&&(window.removeEventListener("clianta:navigation",this.navigationHandler),this.navigationHandler=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),super.destroy()}resetForNavigation(){this.trackedDownloads.clear()}handleClick(e){const t=e.target.closest("a");if(!t||!t.href)return;const i=t.href;(function(e){const t=e.toLowerCase();return l.some(e=>t.includes(e))})(i)&&(this.trackedDownloads.has(i)||(this.trackedDownloads.add(i),this.track("download","File Download",{url:i,filename:I(i),fileType:E(i),linkText:C(t,100)})))}}class F extends _{constructor(){super(...arguments),this.name="exitIntent",this.exitIntentShown=!1,this.pageLoadTime=0,this.boundHandler=null,this.navigationHandler=null,this.popstateHandler=null}init(e){super.init(e),this.pageLoadTime=Date.now(),"undefined"!=typeof navigator&&/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)||("undefined"!=typeof document&&(this.boundHandler=this.handleMouseLeave.bind(this),document.addEventListener("mouseleave",this.boundHandler)),"undefined"!=typeof window&&(this.navigationHandler=()=>this.resetForNavigation(),window.addEventListener("clianta:navigation",this.navigationHandler),this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler)))}destroy(){this.boundHandler&&"undefined"!=typeof document&&document.removeEventListener("mouseleave",this.boundHandler),this.navigationHandler&&"undefined"!=typeof window&&(window.removeEventListener("clianta:navigation",this.navigationHandler),this.navigationHandler=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),super.destroy()}resetForNavigation(){this.exitIntentShown=!1,this.pageLoadTime=Date.now()}handleMouseLeave(e){e.clientY>0||this.exitIntentShown||(this.exitIntentShown=!0,this.track("exit_intent","Exit Intent Detected",{timeOnPage:Date.now()-this.pageLoadTime}))}}class D extends _{constructor(){super(...arguments),this.name="errors",this.boundErrorHandler=null,this.boundRejectionHandler=null,this.seenErrors=new Set}init(e){super.init(e),"undefined"!=typeof window&&(this.boundErrorHandler=this.handleError.bind(this),this.boundRejectionHandler=this.handleRejection.bind(this),window.addEventListener("error",this.boundErrorHandler),window.addEventListener("unhandledrejection",this.boundRejectionHandler))}destroy(){"undefined"!=typeof window&&(this.boundErrorHandler&&window.removeEventListener("error",this.boundErrorHandler),this.boundRejectionHandler&&window.removeEventListener("unhandledrejection",this.boundRejectionHandler)),super.destroy()}handleError(e){const t=`${e.message}:${e.filename}:${e.lineno}`;this.dedup(t)&&this.track("error","JavaScript Error",{message:e.message,filename:e.filename,line:e.lineno,column:e.colno,stack:e.error?.stack?.substring(0,500)})}handleRejection(e){const t=String(e.reason).substring(0,200);this.dedup(t)&&this.track("error","Unhandled Promise Rejection",{reason:t})}dedup(e){return!this.seenErrors.has(e)&&(!(this.seenErrors.size>=20)&&(this.seenErrors.add(e),!0))}}class R extends _{constructor(){super(...arguments),this.name="performance",this.boundLoadHandler=null,this.observers=[],this.boundClsVisibilityHandler=null}init(e){super.init(e),"undefined"!=typeof window&&(this.boundLoadHandler=()=>{setTimeout(()=>this.trackPerformance(),100)},window.addEventListener("load",this.boundLoadHandler))}destroy(){this.boundLoadHandler&&"undefined"!=typeof window&&window.removeEventListener("load",this.boundLoadHandler);for(const e of this.observers)e.disconnect();this.observers=[],this.boundClsVisibilityHandler&&"undefined"!=typeof window&&window.removeEventListener("visibilitychange",this.boundClsVisibilityHandler),super.destroy()}trackPerformance(){if("undefined"==typeof performance)return;const e=performance.getEntriesByType("navigation");if(e.length>0){const t=e[0],i=Math.round(t.loadEventEnd-t.startTime),n=Math.round(t.domContentLoadedEventEnd-t.startTime),s=Math.round(t.responseStart-t.requestStart),r=Math.round(t.domInteractive-t.startTime);this.track("performance","Page Performance",{loadTime:i,domReady:n,ttfb:s,domInteractive:r,dns:Math.round(t.domainLookupEnd-t.domainLookupStart),connection:Math.round(t.connectEnd-t.connectStart),transferSize:t.transferSize})}else{const e=performance.timing;if(!e)return;const t=e.loadEventEnd-e.navigationStart,i=e.domContentLoadedEventEnd-e.navigationStart,n=e.responseStart-e.navigationStart,s=e.domInteractive-e.navigationStart;this.track("performance","Page Performance",{loadTime:t,domReady:i,ttfb:n,domInteractive:s})}this.trackWebVitals()}trackWebVitals(){if("PerformanceObserver"in window){try{const e=new PerformanceObserver(e=>{const t=e.getEntries(),i=t[t.length-1];i&&this.track("performance","Web Vital - LCP",{metric:"LCP",value:Math.round(i.startTime)})});e.observe({type:"largest-contentful-paint",buffered:!0}),this.observers.push(e)}catch{}try{const e=new PerformanceObserver(e=>{const t=e.getEntries()[0];t&&this.track("performance","Web Vital - FID",{metric:"FID",value:Math.round(t.processingStart-t.startTime)})});e.observe({type:"first-input",buffered:!0}),this.observers.push(e)}catch{}try{let e=0;const t=new PerformanceObserver(t=>{t.getEntries().forEach(t=>{t.hadRecentInput||(e+=t.value||0)})});t.observe({type:"layout-shift",buffered:!0}),this.observers.push(t),this.boundClsVisibilityHandler=()=>{"hidden"===document.visibilityState&&e>0&&this.track("performance","Web Vital - CLS",{metric:"CLS",value:Math.round(1e3*e)/1e3})},window.addEventListener("visibilitychange",this.boundClsVisibilityHandler,{once:!0})}catch{}}}}class U extends _{constructor(){super(...arguments),this.name="popupForms",this.forms=[],this.shownForms=new Set,this.scrollHandler=null,this.exitHandler=null,this.delayTimers=[],this.clickTriggerListeners=[]}async init(e){super.init(e),"undefined"!=typeof window&&(this.loadShownForms(),await this.fetchForms(),this.setupTriggers())}destroy(){this.removeTriggers();for(const e of this.delayTimers)clearTimeout(e);this.delayTimers=[];for(const{element:e,handler:t}of this.clickTriggerListeners)e.removeEventListener("click",t);this.clickTriggerListeners=[],super.destroy()}loadShownForms(){const e=y("clianta_shown_forms");if(e)try{const t=JSON.parse(e);this.shownForms=new Set(t.forms||[])}catch{}}saveShownForms(){w("clianta_shown_forms",JSON.stringify({forms:Array.from(this.shownForms),timestamp:Date.now()}))}async fetchForms(){if(!this.tracker)return;const e=this.tracker.getConfig(),t=this.tracker.getWorkspaceId(),i=e.apiEndpoint||"http://localhost:5000";try{const e=encodeURIComponent(window.location.href),n=await fetch(`${i}/api/public/lead-forms/${t}?url=${e}`);if(!n.ok)return;const s=await n.json();s.success&&Array.isArray(s.data)&&(this.forms=s.data.filter(e=>this.shouldShowForm(e)))}catch(e){m.error("Failed to fetch popup forms:",e)}}shouldShowForm(e){if("once_per_visitor"===e.showFrequency){if(this.shownForms.has(e._id))return!1}else if("once_per_session"===e.showFrequency){if(v(`clianta_form_${e._id}_shown`))return!1}return!0}setupTriggers(){this.forms.forEach(e=>{switch(e.trigger.type){case"delay":this.delayTimers.push(setTimeout(()=>this.showForm(e),1e3*(e.trigger.value||5)));break;case"scroll":this.setupScrollTrigger(e);break;case"exit_intent":this.setupExitIntentTrigger(e);break;case"click":this.setupClickTrigger(e)}})}setupScrollTrigger(e){const t=e.trigger.value||50;this.scrollHandler=()=>{window.scrollY/(document.documentElement.scrollHeight-window.innerHeight)*100>=t&&(this.showForm(e),this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler))},window.addEventListener("scroll",this.scrollHandler,{passive:!0})}setupExitIntentTrigger(e){this.exitHandler=t=>{t.clientY<=0&&(this.showForm(e),this.exitHandler&&document.removeEventListener("mouseout",this.exitHandler))},document.addEventListener("mouseout",this.exitHandler)}setupClickTrigger(e){if(!e.trigger.selector)return;document.querySelectorAll(e.trigger.selector).forEach(t=>{const i=()=>this.showForm(e);t.addEventListener("click",i),this.clickTriggerListeners.push({element:t,handler:i})})}removeTriggers(){this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler),this.exitHandler&&document.removeEventListener("mouseout",this.exitHandler)}async showForm(e){this.shouldShowForm(e)&&(this.shownForms.add(e._id),this.saveShownForms(),b(`clianta_form_${e._id}_shown`,"true"),await this.trackFormView(e._id),this.renderForm(e))}async trackFormView(e){if(!this.tracker)return;const t=this.tracker.getConfig().apiEndpoint||"http://localhost:5000";try{await fetch(`${t}/api/public/lead-forms/${e}/view`,{method:"POST",headers:{"Content-Type":"application/json"}})}catch(e){}}renderForm(e){const t=document.createElement("div");t.id=`clianta-form-overlay-${e._id}`,t.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.5);\n z-index: 999998;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0;\n transition: opacity 0.3s ease;\n ";const i=document.createElement("div");i.id=`clianta-form-${e._id}`;const n=e.style||{};i.style.cssText=`\n background: ${n.backgroundColor||"#FFFFFF"};\n border-radius: ${n.borderRadius||12}px;\n padding: 24px;\n max-width: 400px;\n width: 90%;\n box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);\n transform: translateY(20px);\n opacity: 0;\n transition: all 0.3s ease;\n `,this.buildFormDOM(e,i),t.appendChild(i),document.body.appendChild(t),requestAnimationFrame(()=>{t.style.opacity="1",i.style.transform="translateY(0)",i.style.opacity="1"}),this.setupFormEvents(e,t,i)}escapeHTML(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}buildFormDOM(e,t){const i=e.style||{},n=i.primaryColor||"#10B981",s=i.textColor||"#18181B",r=document.createElement("button");r.id="clianta-form-close",r.style.cssText="\n position: absolute;\n top: 12px;\n right: 12px;\n background: none;\n border: none;\n font-size: 20px;\n cursor: pointer;\n color: #71717A;\n padding: 4px;\n ",r.textContent="×",t.appendChild(r);const o=document.createElement("h2");o.style.cssText=`font-size: 20px; font-weight: 700; margin-bottom: 8px; color: ${this.escapeHTML(s)};`,o.textContent=e.headline||"Stay in touch",t.appendChild(o);const a=document.createElement("p");a.style.cssText="font-size: 14px; color: #71717A; margin-bottom: 16px;",a.textContent=e.subheadline||"Get the latest updates",t.appendChild(a);const c=document.createElement("form");c.id="clianta-form-element",e.fields.forEach(e=>{const t=document.createElement("div");if(t.style.marginBottom="12px","checkbox"===e.type){const i=document.createElement("label");i.style.cssText=`display: flex; align-items: center; gap: 8px; font-size: 14px; color: ${this.escapeHTML(s)}; cursor: pointer;`;const n=document.createElement("input");n.type="checkbox",n.name=e.name,e.required&&(n.required=!0),n.style.cssText="width: 16px; height: 16px;",i.appendChild(n);const r=document.createTextNode(e.label+" ");if(i.appendChild(r),e.required){const e=document.createElement("span");e.style.color="#EF4444",e.textContent="*",i.appendChild(e)}t.appendChild(i)}else{const i=document.createElement("label");if(i.style.cssText=`display: block; font-size: 14px; font-weight: 500; margin-bottom: 4px; color: ${this.escapeHTML(s)};`,i.textContent=e.label+" ",e.required){const e=document.createElement("span");e.style.color="#EF4444",e.textContent="*",i.appendChild(e)}if(t.appendChild(i),"textarea"===e.type){const i=document.createElement("textarea");i.name=e.name,e.placeholder&&(i.placeholder=e.placeholder),e.required&&(i.required=!0),i.style.cssText="width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; resize: vertical; min-height: 80px; box-sizing: border-box;",t.appendChild(i)}else if("select"===e.type){const i=document.createElement("select");if(i.name=e.name,e.required&&(i.required=!0),i.style.cssText="width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; box-sizing: border-box; background: white; cursor: pointer;",e.placeholder){const t=document.createElement("option");t.value="",t.textContent=e.placeholder,t.disabled=!0,t.selected=!0,i.appendChild(t)}e.options&&Array.isArray(e.options)&&e.options.forEach(e=>{const t=document.createElement("option");"string"==typeof e?(t.value=e,t.textContent=e):(t.value=e.value,t.textContent=e.label),i.appendChild(t)}),t.appendChild(i)}else{const i=document.createElement("input");i.type=e.type,i.name=e.name,e.placeholder&&(i.placeholder=e.placeholder),e.required&&(i.required=!0),i.style.cssText="width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; box-sizing: border-box;",t.appendChild(i)}}c.appendChild(t)});const d=document.createElement("button");d.type="submit",d.style.cssText=`\n width: 100%;\n padding: 10px 16px;\n background: ${this.escapeHTML(n)};\n color: white;\n border: none;\n border-radius: 6px;\n font-size: 14px;\n font-weight: 500;\n cursor: pointer;\n margin-top: 8px;\n `,d.textContent=e.submitButtonText||"Subscribe",c.appendChild(d),t.appendChild(c)}setupFormEvents(e,t,i){const n=i.querySelector("#clianta-form-close");n&&n.addEventListener("click",()=>this.closeForm(e._id,t,i)),t.addEventListener("click",n=>{n.target===t&&this.closeForm(e._id,t,i)});const s=i.querySelector("#clianta-form-element");s&&s.addEventListener("submit",async t=>{t.preventDefault(),await this.handleSubmit(e,s,i)})}closeForm(e,t,i){i.style.transform="translateY(20px)",i.style.opacity="0",t.style.opacity="0",setTimeout(()=>{t.remove()},300)}async handleSubmit(e,t,i){if(!this.tracker)return;const n=this.tracker.getConfig().apiEndpoint||"http://localhost:5000",s=this.tracker.getVisitorId(),r=new FormData(t),o={};r.forEach((e,t)=>{o[t]=e});const a=t.querySelector('button[type="submit"]');a&&(a.disabled=!0,a.textContent="Submitting...");try{const t=await fetch(`${n}/api/public/lead-forms/${e._id}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({visitorId:s,data:o,url:window.location.href})});if((await t.json()).success){i.innerHTML="";const t=document.createElement("div");t.style.cssText="text-align: center; padding: 20px;";const n=document.createElement("div");n.style.cssText="width: 48px; height: 48px; background: #10B981; border-radius: 50%; margin: 0 auto 16px; display: flex; align-items: center; justify-content: center;";const s=document.createElementNS("http://www.w3.org/2000/svg","svg");s.setAttribute("width","24"),s.setAttribute("height","24"),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke","white"),s.setAttribute("stroke-width","2");const r=document.createElementNS("http://www.w3.org/2000/svg","polyline");r.setAttribute("points","20 6 9 17 4 12"),s.appendChild(r),n.appendChild(s);const a=document.createElement("p");if(a.style.cssText="font-size: 16px; font-weight: 500; color: #18181B;",a.textContent=e.successMessage||"Thank you!",t.appendChild(n),t.appendChild(a),i.appendChild(t),o.email&&this.tracker?.identify(o.email,o),e.redirectUrl)try{const t=new URL(e.redirectUrl,window.location.origin),i=t.origin===window.location.origin,n="https:"===t.protocol||"http:"===t.protocol;i&&n?setTimeout(()=>{window.location.href=t.href},1500):m.warn("Blocked unsafe redirect URL:",e.redirectUrl)}catch{m.warn("Invalid redirect URL:",e.redirectUrl)}setTimeout(()=>{const t=document.getElementById(`clianta-form-overlay-${e._id}`);t&&this.closeForm(e._id,t,i)},2e3)}}catch(t){m.error("Form submit error:",t),a&&(a.disabled=!1,a.textContent=e.submitButtonText||"Subscribe")}}}const M=5e4,V=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/,j=["__session","__clerk_db_jwt","next-auth.session-token","__Secure-next-auth.session-token","sb-access-token","auth0.is.authenticated","KEYCLOAK_SESSION","KEYCLOAK_IDENTITY","KC_RESTART","token","jwt","access_token","session_token","auth_token","id_token"],B=["sb-","supabase.auth.","firebase:authUser:","auth0spajs","@@auth0spajs@@","msal.","msal.account","CognitoIdentityServiceProvider","amplify-signin-with-hostedUI","kc-callback-","persist:","-storage","token","jwt","auth","user","session","credential","account"],z=["email","preferred_username","user_email","mail","emailAddress","e_mail"],J=["name","full_name","display_name","displayName"],K=["given_name","first_name","firstName","fname"],W=["family_name","last_name","lastName","lname"],Q=[2e3,5e3,1e4,1e4,3e4,3e4,3e4,6e4,6e4,6e4];class Y extends _{constructor(){super(...arguments),this.name="autoIdentify",this.pollTimeouts=[],this.identifiedEmail=null,this.storageHandler=null,this.sessionProbed=!1}init(e){super.init(e),"undefined"!=typeof window&&(this.schedulePollChecks(),this.listenForStorageChanges())}destroy(){for(const e of this.pollTimeouts)clearTimeout(e);this.pollTimeouts=[],this.storageHandler&&"undefined"!=typeof window&&(window.removeEventListener("storage",this.storageHandler),this.storageHandler=null),super.destroy()}schedulePollChecks(){let e=0;for(let t=0;t<Q.length;t++){e+=Q[t];const i=setTimeout(()=>{if(!this.identifiedEmail){try{this.checkForAuthUser()}catch{}3!==t||this.sessionProbed||(this.sessionProbed=!0,this.guardedSessionProbe())}},e);this.pollTimeouts.push(i)}}listenForStorageChanges(){this.storageHandler=e=>{if(this.identifiedEmail)return;if(!e.key||!e.newValue)return;const t=e.key.toLowerCase();if(B.some(e=>t.includes(e.toLowerCase())))try{this.checkForAuthUser()}catch{}},window.addEventListener("storage",this.storageHandler)}checkForAuthUser(){if(this.tracker&&!this.identifiedEmail){try{const e=this.checkAuthProviders();if(e)return void this.identifyUser(e)}catch{}try{const e=this.checkCookies();if(e)return void this.identifyUser(e)}catch{}try{if("undefined"!=typeof localStorage){const e=this.checkStorage(localStorage);if(e)return void this.identifyUser(e)}}catch{}try{if("undefined"!=typeof sessionStorage){const e=this.checkStorage(sessionStorage);if(e)return void this.identifyUser(e)}}catch{}}}checkAuthProviders(){const e=window;try{const t=e.Clerk?.user;if(t){const e=t.primaryEmailAddress?.emailAddress||t.emailAddresses?.[0]?.emailAddress;if(e&&this.isValidEmail(e))return{email:e,firstName:t.firstName||void 0,lastName:t.lastName||void 0}}}catch{}try{const t=e.firebase?.auth?.(),i=t?.currentUser;if(i?.email&&this.isValidEmail(i.email)){const e=(i.displayName||"").split(" ");return{email:i.email,firstName:e[0]||void 0,lastName:e.slice(1).join(" ")||void 0}}}catch{}try{const t=e.__SUPABASE_CLIENT__||e.supabase;if(t?.auth){const e=t.auth.session?.()||t.auth.getSession?.(),i=e?.data?.session?.user||e?.user;if(i?.email&&this.isValidEmail(i.email)){const e=i.user_metadata||{};return{email:i.email,firstName:e.first_name||e.full_name?.split(" ")[0]||void 0,lastName:e.last_name||e.full_name?.split(" ").slice(1).join(" ")||void 0}}}}catch{}try{const t=e.__auth0Client||e.auth0Client;if(t?.isAuthenticated?.()){const e=t.getUser?.();if(e?.email&&this.isValidEmail(e.email))return{email:e.email,firstName:e.given_name||e.name?.split(" ")[0]||void 0,lastName:e.family_name||e.name?.split(" ").slice(1).join(" ")||void 0}}}catch{}try{const t=e.__google_credential_response?.credential;if(t&&"string"==typeof t){const e=this.extractUserFromToken(t);if(e)return e}const i=e.gapi?.auth2?.getAuthInstance?.()?.currentUser?.get?.(),n=i?.getBasicProfile?.();if(n){const e=n.getEmail?.();if(e&&this.isValidEmail(e))return{email:e,firstName:n.getGivenName?.()||void 0,lastName:n.getFamilyName?.()||void 0}}}catch{}try{const t=e.msalInstance||e.__msalInstance;if(t){const e=(t.getAllAccounts?.()||[])[0];if(e?.username&&this.isValidEmail(e.username)){const t=(e.name||"").split(" ");return{email:e.username,firstName:t[0]||void 0,lastName:t.slice(1).join(" ")||void 0}}}}catch{}try{const t=e.aws_amplify_currentUser||e.__amplify_user;if(t?.signInDetails?.loginId&&this.isValidEmail(t.signInDetails.loginId))return{email:t.signInDetails.loginId,firstName:t.attributes?.given_name||void 0,lastName:t.attributes?.family_name||void 0};if("undefined"!=typeof localStorage){const e=this.checkCognitoStorage();if(e)return e}}catch{}try{const t=e.keycloak||e.Keycloak;if(t?.authenticated&&t.tokenParsed){const e=t.tokenParsed,i=e.email||e.preferred_username;if(i&&this.isValidEmail(i))return{email:i,firstName:e.given_name||void 0,lastName:e.family_name||void 0}}}catch{}try{const t=e.__clianta_user;if(t?.email&&"string"==typeof t.email&&this.isValidEmail(t.email))return{email:t.email,firstName:t.firstName||void 0,lastName:t.lastName||void 0}}catch{}return null}identifyUser(e){if(this.tracker&&this.identifiedEmail!==e.email){this.identifiedEmail=e.email,this.tracker.identify(e.email,{firstName:e.firstName,lastName:e.lastName});for(const e of this.pollTimeouts)clearTimeout(e);this.pollTimeouts=[]}}checkCookies(){if("undefined"==typeof document)return null;try{const e=document.cookie.split(";").map(e=>e.trim());for(const t of e){const[e,...i]=t.split("="),n=i.join("="),s=e.trim().toLowerCase();if(j.some(e=>s.includes(e.toLowerCase()))&&n){const e=this.extractUserFromToken(decodeURIComponent(n));if(e)return e}}}catch{}return null}checkStorage(e){try{for(let t=0;t<e.length;t++){const i=e.key(t);if(!i)continue;const n=i.toLowerCase();if(B.some(e=>n.includes(e.toLowerCase()))){const t=e.getItem(i);if(!t)continue;if(t.length>M)continue;const n=this.extractUserFromToken(t);if(n)return n;try{const e=JSON.parse(t),i=this.deepScanForUser(e,0);if(i)return i}catch{}}}}catch{}return null}deepScanForUser(e,t){if(t>4||!e||"object"!=typeof e||Array.isArray(e))return null;const i=e,n=Object.keys(i),s=this.extractUserFromClaims(i);if(s)return s;const r=n.slice(0,20);for(const e of r){const t=i[e];if("string"==typeof t&&t.length>30&&t.length<4e3){if(2===(t.match(/\./g)||[]).length){const e=this.extractUserFromToken(t);if(e)return e}}}for(const e of r){const n=i[e];if(n&&"object"==typeof n&&!Array.isArray(n)){const e=this.deepScanForUser(n,t+1);if(e)return e}}return null}extractUserFromToken(e){const t=e.split(".");if(3!==t.length)return null;try{const e=JSON.parse(atob(t[1].replace(/-/g,"+").replace(/_/g,"/")));return this.extractUserFromClaims(e)}catch{return null}}extractUserFromClaims(e){if(!e||"object"!=typeof e)return null;let t,i,n=null;for(const t of z){const i=e[t];if(i&&"string"==typeof i&&this.isValidEmail(i)){n=i;break}}if(!n){const t=e.primaryEmailAddress?.emailAddress||e.emailAddresses?.[0]?.emailAddress;t&&"string"==typeof t&&this.isValidEmail(t)&&(n=t)}if(!n)return null;for(const i of K)if(e[i]&&"string"==typeof e[i]){t=e[i];break}for(const t of W)if(e[t]&&"string"==typeof e[t]){i=e[t];break}if(!t)for(const n of J)if(e[n]&&"string"==typeof e[n]){const s=e[n].split(" ");t=s[0],i=i||s.slice(1).join(" ")||void 0;break}return{email:n,firstName:t,lastName:i}}async guardedSessionProbe(){if(this.identifiedEmail)return;const e="undefined"!=typeof document&&(document.cookie.includes("next-auth.session-token")||document.cookie.includes("__Secure-next-auth.session-token")),t="undefined"!=typeof window&&(null!=window.__NEXTAUTH||null!=window.__NEXT_DATA__);if(e||t)try{const e=await fetch("/api/auth/session",{method:"GET",credentials:"include",headers:{Accept:"application/json"}});if(e.ok){const t=await e.json();if(t&&"object"==typeof t&&Object.keys(t).length>0){const e=this.deepScanForUser(t,0);e&&this.identifyUser(e)}}}catch{}}checkCognitoStorage(){try{for(let e=0;e<localStorage.length;e++){const t=localStorage.key(e);if(t){if(t.startsWith("CognitoIdentityServiceProvider.")&&t.endsWith(".idToken")){const e=localStorage.getItem(t);if(e&&e.length<M){const t=this.extractUserFromToken(e);if(t)return t}}if(t.startsWith("CognitoIdentityServiceProvider.")&&t.endsWith(".userData")){const e=localStorage.getItem(t);if(e&&e.length<M)try{const t=JSON.parse(e),i=t.UserAttributes||t.attributes||[],n=i.find?.(e=>"email"===e.Name||"email"===e.name);if(n?.Value&&this.isValidEmail(n.Value)){const e=i.find?.(e=>"name"===e.Name||"name"===e.name),t=i.find?.(e=>"given_name"===e.Name||"given_name"===e.name),s=i.find?.(e=>"family_name"===e.Name||"family_name"===e.name);let r=t?.Value,o=s?.Value;if(!r&&e?.Value){const t=e.Value.split(" ");r=t[0],o=o||t.slice(1).join(" ")||void 0}return{email:n.Value,firstName:r||void 0,lastName:o||void 0}}}catch{}}}}}catch{}return null}isValidEmail(e){return V.test(e)}}function X(e){switch(e){case"pageView":return new N;case"scroll":return new P;case"forms":return new H;case"clicks":return new q;case"engagement":return new A;case"downloads":return new O;case"exitIntent":return new F;case"errors":return new D;case"performance":return new R;case"popupForms":return new U;case"autoIdentify":return new Y;default:throw new Error(`Unknown plugin: ${e}`)}}function G(e){try{if("undefined"==typeof localStorage)return!1;const t={state:e,timestamp:Date.now(),version:1};return localStorage.setItem(a,JSON.stringify(t)),!0}catch{return!1}}function Z(){try{if("undefined"==typeof localStorage)return null;const e=localStorage.getItem(a);if(!e)return null;const t=JSON.parse(e);return 1!==t.version?(ee(),null):t}catch{return null}}function ee(){try{return"undefined"!=typeof localStorage&&(localStorage.removeItem(a),!0)}catch{return!1}}class te{constructor(e={}){this.eventBuffer=[],this.callbacks=[],this.hasExplicitConsent=!1,this.config={defaultConsent:{analytics:!0,marketing:!1,personalization:!1},waitForConsent:!1,storageKey:"mb_consent",...e};const t=Z();t?(this.state=t.state,this.hasExplicitConsent=!0,m.debug("Loaded stored consent:",this.state)):(this.state=this.config.defaultConsent||{analytics:!0},this.hasExplicitConsent=!1,m.debug("Using default consent:",this.state)),e.onConsentChange&&this.callbacks.push(e.onConsentChange)}grant(e){const t={...this.state};this.state={...this.state,...e},this.hasExplicitConsent=!0,G(this.state),m.info("Consent granted:",e),this.notifyChange(t)}revoke(e){const t={...this.state};for(const t of e)this.state[t]=!1;this.hasExplicitConsent=!0,G(this.state),m.info("Consent revoked:",e),this.notifyChange(t)}update(e){const t={...this.state};this.state={...e},this.hasExplicitConsent=!0,G(this.state),m.info("Consent updated:",this.state),this.notifyChange(t)}reset(){const e={...this.state};this.state=this.config.defaultConsent||{analytics:!0},this.hasExplicitConsent=!1,this.eventBuffer=[],ee(),m.info("Consent reset to defaults"),this.notifyChange(e)}getState(){return{...this.state}}hasConsent(e){return!0===this.state[e]}canTrack(){return!(this.config.waitForConsent&&!this.hasExplicitConsent)&&!0===this.state.analytics}hasExplicit(){return this.hasExplicitConsent}hasStored(){return null!==Z()}bufferEvent(e){this.eventBuffer.length>=100&&(m.warn("Consent event buffer full, dropping oldest event"),this.eventBuffer.shift()),this.eventBuffer.push(e),m.debug("Event buffered (waiting for consent):",e.eventName)}flushBuffer(){const e=[...this.eventBuffer];return this.eventBuffer=[],e.length>0&&m.debug(`Flushing ${e.length} buffered events`),e}getBufferSize(){return this.eventBuffer.length}onChange(e){return this.callbacks.push(e),()=>{const t=this.callbacks.indexOf(e);t>-1&&this.callbacks.splice(t,1)}}notifyChange(e){for(const t of this.callbacks)try{t(this.state,e)}catch(e){m.error("Consent change callback error:",e)}}}class ie{constructor(e,t={}){if(this.plugins=[],this.isInitialized=!1,this.contactId=null,this.groupId=null,this.pendingIdentify=null,this.eventSchemas=new Map,this.middlewares=[],this.readyCallbacks=[],!e)throw new Error("[Clianta] Workspace ID is required");this.workspaceId=e,this.config=function(e={}){return{...n,...e,consent:{...n.consent,...e.consent}}}(t),m.enabled=this.config.debug,m.info(`Initializing SDK v${i}`,{workspaceId:e}),this.consentManager=new te({...this.config.consent,onConsentChange:(e,t)=>{this.onConsentChange(e,t)}}),this.transport=new g({apiEndpoint:this.config.apiEndpoint}),this.queue=new $(this.transport,{batchSize:this.config.batchSize,flushInterval:this.config.flushInterval,persistMode:this.config.persistMode}),this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),m.debug("IDs created",{visitorId:this.visitorId,sessionId:this.sessionId}),!this.config.apiEndpoint.startsWith("http://")||"undefined"==typeof window||window.location.hostname.includes("localhost")||window.location.hostname.includes("127.0.0.1")||m.warn("apiEndpoint uses HTTP — events will be sent unencrypted. Use HTTPS in production."),this.initPlugins(),this.isInitialized=!0,m.info("SDK initialized successfully");for(const e of this.readyCallbacks)try{e()}catch(e){m.error("onReady callback error:",e)}this.readyCallbacks=[]}createVisitorId(){if(this.config.consent.anonymousMode&&!this.consentManager.hasExplicit()){const e=s+"_anon";let t=v(e);return t||(t="anon_"+f(),b(e,t)),t}if(this.config.cookielessMode){let e=v(s);return e||(e=f(),b(s,e)),e}return S(this.config.useCookies)}createSessionId(){return function(e){const t=r,i=o;let n=v(t);const s=parseInt(v(i)||"0",10),a=Date.now();return(!n||a-s>e)&&(n=f(),b(t,n)),b(i,a.toString()),n}(this.config.sessionTimeout)}onConsentChange(e,t){if(m.debug("Consent changed:",{from:t,to:e}),e.analytics&&!t.analytics){this.config.consent.anonymousMode&&(this.visitorId=S(this.config.useCookies),m.info("Upgraded from anonymous to persistent visitor ID"));const e=this.consentManager.flushBuffer();for(const t of e)t.visitorId=this.visitorId,this.queue.push(t)}}initPlugins(){const e=this.config.plugins,t=this.config.autoPageView?e:e.filter(e=>"pageView"!==e);for(const e of t)try{const t=X(e),i=t.init(this);i instanceof Promise&&i.catch(t=>{m.error(`Async plugin init failed: ${e}`,t)}),this.plugins.push(t),m.debug(`Plugin loaded: ${e}`)}catch(t){m.error(`Failed to load plugin: ${e}`,t)}}track(e,t,n={}){if(!this.isInitialized)return void m.warn("SDK not initialized, event dropped");const s=function(){if("undefined"==typeof window)return{};try{const e=new URLSearchParams(window.location.search);return{utmSource:e.get("utm_source")||void 0,utmMedium:e.get("utm_medium")||void 0,utmCampaign:e.get("utm_campaign")||void 0,utmTerm:e.get("utm_term")||void 0,utmContent:e.get("utm_content")||void 0}}catch{return{}}}(),r={workspaceId:this.workspaceId,visitorId:this.visitorId,sessionId:this.sessionId,contactId:this.contactId??void 0,groupId:this.groupId??void 0,eventType:e,eventName:t,url:"undefined"!=typeof window?window.location.href:"",referrer:"undefined"!=typeof document&&document.referrer||void 0,properties:{...n,eventId:f(),websiteDomain:"undefined"!=typeof window?window.location.hostname:void 0},device:"undefined"==typeof window||"undefined"==typeof navigator?{userAgent:"unknown",screen:"unknown",language:"unknown",timezone:"unknown"}:{userAgent:navigator.userAgent,screen:`${screen.width}x${screen.height}`,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||"unknown"},utmSource:s.utmSource,utmMedium:s.utmMedium,utmCampaign:s.utmCampaign,utmTerm:s.utmTerm,utmContent:s.utmContent,timestamp:(new Date).toISOString(),sdkVersion:i};if(this.validateEventSchema(e,n),!this.consentManager.canTrack())return this.config.consent.waitForConsent?void this.consentManager.bufferEvent(r):void m.debug("Event dropped (no consent):",t);this.runMiddleware(r,()=>{this.queue.push(r),m.debug("Event tracked:",t,n)})}page(e,t={}){const i=e||("undefined"!=typeof document?document.title:"Page View");this.track("page_view",i,{...t,path:"undefined"!=typeof window?window.location.pathname:""})}async identify(e,t={}){if(!e)return m.warn("Email is required for identification"),null;if(!function(e){return!("string"!=typeof e||!e)&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}(e))return m.warn("Invalid email format, identification skipped:",e),null;m.info("Identifying visitor:",e);const i=await this.transport.sendIdentify({workspaceId:this.workspaceId,visitorId:this.visitorId,email:e,properties:t});return i.success?(m.info("Visitor identified successfully, contactId:",i.contactId),this.contactId=i.contactId??null,this.pendingIdentify=null,this.contactId):(m.error("Failed to identify visitor:",i.error),this.pendingIdentify={email:e,traits:t},null)}async retryPendingIdentify(){if(!this.pendingIdentify)return;const{email:e,traits:t}=this.pendingIdentify;this.pendingIdentify=null,await this.identify(e,t)}consent(e){this.consentManager.update(e)}getConsentState(){return this.consentManager.getState()}debug(e){m.enabled=e,m.info("Debug mode "+(e?"enabled":"disabled"))}group(e,t={}){e?(this.groupId=e,m.info("Visitor grouped:",e),this.track("group","Group Identified",{groupId:e,...t})):m.warn("groupId is required for group()")}async alias(e,t){if(!e)return m.warn("newId is required for alias()"),!1;const i=t||this.visitorId;m.info("Aliasing visitor:",{from:i,to:e});const n=await this.transport.sendPost("/api/public/track/alias",{workspaceId:this.workspaceId,previousId:i,newId:e});return n.success?(m.info("Alias successful"),!0):(m.error("Alias failed:",n.error??n.status),!1)}screen(e,t={}){this.track("screen_view",e,{...t,screenName:e})}use(e){this.middlewares.push(e),m.debug("Middleware registered")}runMiddleware(e,t){if(0===this.middlewares.length)return void t();let i=0;const n=this.middlewares,s=()=>{if(i++,i<n.length)try{n[i](e,s)}catch(e){m.error("Middleware error:",e),t()}else t()};try{n[0](e,s)}catch(e){m.error("Middleware error:",e),t()}}onReady(e){if(this.isInitialized)try{e()}catch(e){m.error("onReady callback error:",e)}else this.readyCallbacks.push(e)}isReady(){return this.isInitialized}registerEventSchema(e,t){this.eventSchemas.set(e,t),m.debug("Event schema registered:",e)}validateEventSchema(e,t){if(!this.config.debug)return;const i=this.eventSchemas.get(e);if(i)for(const[n,s]of Object.entries(i)){const i=t[n];if(void 0===i){m.warn(`[Schema] Missing property "${n}" for event type "${e}"`);continue}let r=!1;switch(s){case"string":r="string"==typeof i;break;case"number":r="number"==typeof i;break;case"boolean":r="boolean"==typeof i;break;case"object":r="object"==typeof i&&!Array.isArray(i);break;case"array":r=Array.isArray(i)}r||m.warn(`[Schema] Property "${n}" for event "${e}" expected ${s}, got ${typeof i}`)}}getVisitorId(){return this.visitorId}getSessionId(){return this.sessionId}getWorkspaceId(){return this.workspaceId}getConfig(){return{...this.config}}async flush(){await this.retryPendingIdentify(),await this.queue.flush()}reset(){m.info("Resetting visitor data"),T(this.config.useCookies),this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),this.contactId=null,this.pendingIdentify=null,this.queue.clear()}deleteData(){if(m.info("Deleting all user data (GDPR request)"),this.queue.clear(),this.consentManager.reset(),T(this.config.useCookies),"undefined"!=typeof sessionStorage)try{sessionStorage.removeItem(s),sessionStorage.removeItem(s+"_anon"),sessionStorage.removeItem(r),sessionStorage.removeItem(o)}catch{}if("undefined"!=typeof localStorage)try{localStorage.removeItem(s),localStorage.removeItem(a),localStorage.removeItem(c)}catch{}this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),m.info("All user data deleted")}async createContact(e){return this.publicCrmRequest("/api/public/crm/contacts","POST",{workspaceId:this.workspaceId,...e})}async updateContact(e,t){return this.publicCrmRequest(`/api/public/crm/contacts/${e}`,"PUT",{workspaceId:this.workspaceId,...t})}async submitForm(e,t){const i={...t,metadata:{...t.metadata,visitorId:this.visitorId,sessionId:this.sessionId,pageUrl:"undefined"!=typeof window?window.location.href:void 0,referrer:"undefined"!=typeof document&&document.referrer||void 0}};return this.publicCrmRequest(`/api/public/crm/forms/${e}/submit`,"POST",i)}async logActivity(e){return this.publicCrmRequest("/api/public/crm/activities","POST",{workspaceId:this.workspaceId,...e})}async createOpportunity(e){return this.publicCrmRequest("/api/public/crm/opportunities","POST",{workspaceId:this.workspaceId,...e})}async publicCrmRequest(e,t,i){const n=`${this.config.apiEndpoint}${e}`;try{const s=await fetch(n,{method:t,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),r=await s.json().catch(()=>({}));return s.ok?(m.debug(`Public CRM ${t} ${e} succeeded`),{success:!0,data:r.data??r,status:s.status}):(m.error(`Public CRM ${t} ${e} failed (${s.status}):`,r.message),{success:!1,error:r.message,status:s.status})}catch(i){return m.error(`Public CRM ${t} ${e} error:`,i),{success:!1,error:i.message}}}async destroy(){m.info("Destroying tracker"),await this.queue.flush();for(const e of this.plugins)e.destroy&&e.destroy();this.plugins=[],this.queue.destroy(),this.isInitialized=!1}}class ne{constructor(e,t,i){this.triggers=new Map,this.listeners=new Map,this.apiEndpoint=e,this.workspaceId=t,this.authToken=i}setAuthToken(e){this.authToken=e}async request(e,t={}){const i=`${this.apiEndpoint}${e}`,n={"Content-Type":"application/json",...t.headers||{}};this.authToken&&(n.Authorization=`Bearer ${this.authToken}`);try{const e=await fetch(i,{...t,headers:n}),s=await e.json();return e.ok?{success:!0,data:s.data||s,status:e.status}:{success:!1,error:s.message||"Request failed",status:e.status}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Network error",status:0}}}async getTriggers(){return this.request(`/api/workspaces/${this.workspaceId}/triggers`)}async getTrigger(e){return this.request(`/api/workspaces/${this.workspaceId}/triggers/${e}`)}async createTrigger(e){const t=await this.request(`/api/workspaces/${this.workspaceId}/triggers`,{method:"POST",body:JSON.stringify(e)});return t.success&&t.data?._id&&this.triggers.set(t.data._id,t.data),t}async updateTrigger(e,t){const i=await this.request(`/api/workspaces/${this.workspaceId}/triggers/${e}`,{method:"PUT",body:JSON.stringify(t)});return i.success&&i.data?._id&&this.triggers.set(i.data._id,i.data),i}async deleteTrigger(e){const t=await this.request(`/api/workspaces/${this.workspaceId}/triggers/${e}`,{method:"DELETE"});return t.success&&this.triggers.delete(e),t}async activateTrigger(e){return this.updateTrigger(e,{isActive:!0})}async deactivateTrigger(e){return this.updateTrigger(e,{isActive:!1})}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),m.debug(`Event listener registered: ${e}`)}off(e,t){const i=this.listeners.get(e);i&&i.delete(t)}emit(e,t){m.debug(`Event emitted: ${e}`,t);const i=this.listeners.get(e);i&&i.forEach(i=>{try{i(t)}catch(t){m.error(`Error in event listener for ${e}:`,t)}})}evaluateConditions(e,t){return!e||0===e.length||e.every(e=>{const i=e.field.includes(".")?this.getNestedValue(t,e.field):t[e.field],n=e.value;switch(e.operator){case"equals":return i===n;case"not_equals":return i!==n;case"contains":return String(i).includes(String(n));case"greater_than":return Number(i)>Number(n);case"less_than":return Number(i)<Number(n);case"in":return Array.isArray(n)&&n.includes(i);case"not_in":return Array.isArray(n)&&!n.includes(i);default:return!1}})}async executeActions(e,t){m.info(`Executing actions for trigger: ${e.name}`);for(const i of e.actions)try{await this.executeAction(i,t)}catch(e){m.error("Failed to execute action:",e)}}async executeAction(e,t){switch(e.type){case"send_email":await this.executeSendEmail(e,t);break;case"webhook":await this.executeWebhook(e,t);break;case"create_task":await this.executeCreateTask(e,t);break;case"update_contact":await this.executeUpdateContact(e,t);break;default:m.warn("Unknown action type:",e)}}async executeSendEmail(e,t){m.debug("Sending email:",e);const i={to:this.replaceVariables(e.to,t),subject:e.subject?this.replaceVariables(e.subject,t):void 0,body:e.body?this.replaceVariables(e.body,t):void 0,templateId:e.templateId,cc:e.cc,bcc:e.bcc,from:e.from,delayMinutes:e.delayMinutes};await this.request(`/api/workspaces/${this.workspaceId}/emails/send`,{method:"POST",body:JSON.stringify(i)})}async executeWebhook(e,t){m.debug("Calling webhook:",e.url);const i=e.body?this.replaceVariables(e.body,t):JSON.stringify(t);await fetch(e.url,{method:e.method,headers:{"Content-Type":"application/json",...e.headers},body:i})}async executeCreateTask(e,t){m.debug("Creating task:",e.title);const i=e.dueDays?new Date(Date.now()+24*e.dueDays*60*60*1e3).toISOString():void 0;await this.request(`/api/workspaces/${this.workspaceId}/tasks`,{method:"POST",body:JSON.stringify({title:this.replaceVariables(e.title,t),description:e.description?this.replaceVariables(e.description,t):void 0,priority:e.priority,dueDate:i,assignedTo:e.assignedTo,relatedContactId:"string"==typeof t.contactId?t.contactId:void 0})})}async executeUpdateContact(e,t){const i=t.contactId||t._id;i?(m.debug("Updating contact:",i),await this.request(`/api/workspaces/${this.workspaceId}/contacts/${i}`,{method:"PUT",body:JSON.stringify(e.updates)})):m.warn("Cannot update contact: no contactId in data")}replaceVariables(e,t){return e.replace(/\{\{([^}]+)\}\}/g,(e,i)=>{const n=this.getNestedValue(t,i.trim());return void 0!==n?String(n):e})}getNestedValue(e,t){return t.split(".").reduce((e,t)=>null!=e&&"object"==typeof e?e[t]:void 0,e)}extractAvailableFields(e,t="",i=3){if(i<=0)return[];const n=[];for(const s in e){if(!e.hasOwnProperty(s))continue;const r=e[s],o=t?`${t}.${s}`:s;if(n.push(o),null!==r&&"object"==typeof r&&!Array.isArray(r)){const e=this.extractAvailableFields(r,o,i-1);n.push(...e)}}return n}getAvailableFields(e){return this.extractAvailableFields(e)}async createEmailTrigger(e){return this.createTrigger({name:e.name,eventType:e.eventType,conditions:e.conditions,actions:[{type:"send_email",to:e.to,subject:e.subject,body:e.body}],isActive:!0})}async createTaskTrigger(e){return this.createTrigger({name:e.name,eventType:e.eventType,conditions:e.conditions,actions:[{type:"create_task",title:e.taskTitle,description:e.taskDescription,priority:e.priority,dueDays:e.dueDays}],isActive:!0})}async createWebhookTrigger(e){return this.createTrigger({name:e.name,eventType:e.eventType,conditions:e.conditions,actions:[{type:"webhook",url:e.webhookUrl,method:e.method||"POST"}],isActive:!0})}}let se=null;function re(e,t){return se&&se.getWorkspaceId()===e?(t&&Object.keys(t).length>0&&"undefined"!=typeof console&&console.warn('[Clianta] clianta() called with config on an already-initialized instance for workspace "'+e+'". The new config was ignored. Call tracker.destroy() first if you need to reconfigure.'),se):(se&&se.destroy(),se=new ie(e,t),se)}if("undefined"!=typeof window){window.clianta=re,window.Clianta={clianta:re,Tracker:ie,ConsentManager:te};const e=()=>{const e=document.querySelectorAll("script[data-project-id]"),t=e[e.length-1];if(!t)return;const i=t.getAttribute("data-project-id");if(!i)return;const n={debug:t.hasAttribute("data-debug")},s=t.getAttribute("data-api-endpoint");s&&(n.apiEndpoint=s),t.hasAttribute("data-cookieless")&&(n.cookielessMode=!0),t.hasAttribute("data-use-cookies")&&(n.useCookies=!0);const r=re(i,n);window.__clianta=r};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}e.CRMClient=class{constructor(e,t,i,n){this.apiEndpoint=e,this.workspaceId=t,this.authToken=i,this.apiKey=n,this.triggers=new ne(e,t,i)}setAuthToken(e){this.authToken=e,this.apiKey=void 0,this.triggers.setAuthToken(e)}setApiKey(e){this.apiKey=e,this.authToken=void 0}validateRequired(e,t,i){if(null==t||""===t)throw new Error(`[CRMClient.${i}] ${e} is required`)}async request(e,t={}){const i=`${this.apiEndpoint}${e}`,n={"Content-Type":"application/json",...t.headers||{}};this.apiKey?n["X-Api-Key"]=this.apiKey:this.authToken&&(n.Authorization=`Bearer ${this.authToken}`);try{const e=await fetch(i,{...t,headers:n}),s=await e.json();return e.ok?{success:!0,data:s.data||s,status:e.status}:{success:!1,error:s.message||"Request failed",status:e.status}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Network error",status:0}}}async sendEvent(e){const t=`${this.apiEndpoint}/api/public/events`,i={"Content-Type":"application/json"};this.apiKey?i["X-Api-Key"]=this.apiKey:this.authToken&&(i.Authorization=`Bearer ${this.authToken}`);try{const n=await fetch(t,{method:"POST",headers:i,body:JSON.stringify(e)}),s=await n.json();return n.ok?{success:s.success,contactCreated:s.contactCreated,contactId:s.contactId,event:s.event}:{success:!1,contactCreated:!1,event:e.event,error:s.error||"Request failed"}}catch(t){return{success:!1,contactCreated:!1,event:e.event,error:t instanceof Error?t.message:"Network error"}}}async getContacts(e){const t=new URLSearchParams;e?.page&&t.set("page",e.page.toString()),e?.limit&&t.set("limit",e.limit.toString()),e?.search&&t.set("search",e.search),e?.status&&t.set("status",e.status);const i=t.toString(),n=`/api/workspaces/${this.workspaceId}/contacts${i?`?${i}`:""}`;return this.request(n)}async getContact(e){return this.validateRequired("contactId",e,"getContact"),this.request(`/api/workspaces/${this.workspaceId}/contacts/${e}`)}async createContact(e){return this.request(`/api/workspaces/${this.workspaceId}/contacts`,{method:"POST",body:JSON.stringify(e)})}async updateContact(e,t){return this.validateRequired("contactId",e,"updateContact"),this.request(`/api/workspaces/${this.workspaceId}/contacts/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteContact(e){return this.validateRequired("contactId",e,"deleteContact"),this.request(`/api/workspaces/${this.workspaceId}/contacts/${e}`,{method:"DELETE"})}async getOpportunities(e){const t=new URLSearchParams;e?.page&&t.set("page",e.page.toString()),e?.limit&&t.set("limit",e.limit.toString()),e?.pipelineId&&t.set("pipelineId",e.pipelineId),e?.stageId&&t.set("stageId",e.stageId);const i=t.toString(),n=`/api/workspaces/${this.workspaceId}/opportunities${i?`?${i}`:""}`;return this.request(n)}async getOpportunity(e){return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${e}`)}async createOpportunity(e){return this.request(`/api/workspaces/${this.workspaceId}/opportunities`,{method:"POST",body:JSON.stringify(e)})}async updateOpportunity(e,t){return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteOpportunity(e){return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${e}`,{method:"DELETE"})}async moveOpportunity(e,t){return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${e}/move`,{method:"POST",body:JSON.stringify({stageId:t})})}async getCompanies(e){const t=new URLSearchParams;e?.page&&t.set("page",e.page.toString()),e?.limit&&t.set("limit",e.limit.toString()),e?.search&&t.set("search",e.search),e?.status&&t.set("status",e.status),e?.industry&&t.set("industry",e.industry);const i=t.toString(),n=`/api/workspaces/${this.workspaceId}/companies${i?`?${i}`:""}`;return this.request(n)}async getCompany(e){return this.request(`/api/workspaces/${this.workspaceId}/companies/${e}`)}async createCompany(e){return this.request(`/api/workspaces/${this.workspaceId}/companies`,{method:"POST",body:JSON.stringify(e)})}async updateCompany(e,t){return this.request(`/api/workspaces/${this.workspaceId}/companies/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteCompany(e){return this.request(`/api/workspaces/${this.workspaceId}/companies/${e}`,{method:"DELETE"})}async getCompanyContacts(e,t){const i=new URLSearchParams;t?.page&&i.set("page",t.page.toString()),t?.limit&&i.set("limit",t.limit.toString());const n=i.toString(),s=`/api/workspaces/${this.workspaceId}/companies/${e}/contacts${n?`?${n}`:""}`;return this.request(s)}async getCompanyDeals(e,t){const i=new URLSearchParams;t?.page&&i.set("page",t.page.toString()),t?.limit&&i.set("limit",t.limit.toString());const n=i.toString(),s=`/api/workspaces/${this.workspaceId}/companies/${e}/deals${n?`?${n}`:""}`;return this.request(s)}async getPipelines(){return this.request(`/api/workspaces/${this.workspaceId}/pipelines`)}async getPipeline(e){return this.request(`/api/workspaces/${this.workspaceId}/pipelines/${e}`)}async createPipeline(e){return this.request(`/api/workspaces/${this.workspaceId}/pipelines`,{method:"POST",body:JSON.stringify(e)})}async updatePipeline(e,t){return this.request(`/api/workspaces/${this.workspaceId}/pipelines/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deletePipeline(e){return this.request(`/api/workspaces/${this.workspaceId}/pipelines/${e}`,{method:"DELETE"})}async getTasks(e){const t=new URLSearchParams;e?.page&&t.set("page",e.page.toString()),e?.limit&&t.set("limit",e.limit.toString()),e?.status&&t.set("status",e.status),e?.priority&&t.set("priority",e.priority),e?.contactId&&t.set("contactId",e.contactId),e?.companyId&&t.set("companyId",e.companyId),e?.opportunityId&&t.set("opportunityId",e.opportunityId);const i=t.toString(),n=`/api/workspaces/${this.workspaceId}/tasks${i?`?${i}`:""}`;return this.request(n)}async getTask(e){return this.request(`/api/workspaces/${this.workspaceId}/tasks/${e}`)}async createTask(e){return this.request(`/api/workspaces/${this.workspaceId}/tasks`,{method:"POST",body:JSON.stringify(e)})}async updateTask(e,t){return this.request(`/api/workspaces/${this.workspaceId}/tasks/${e}`,{method:"PUT",body:JSON.stringify(t)})}async completeTask(e){return this.request(`/api/workspaces/${this.workspaceId}/tasks/${e}/complete`,{method:"PATCH"})}async deleteTask(e){return this.request(`/api/workspaces/${this.workspaceId}/tasks/${e}`,{method:"DELETE"})}async getContactActivities(e,t){const i=new URLSearchParams;t?.page&&i.set("page",t.page.toString()),t?.limit&&i.set("limit",t.limit.toString()),t?.type&&i.set("type",t.type);const n=i.toString(),s=`/api/workspaces/${this.workspaceId}/contacts/${e}/activities${n?`?${n}`:""}`;return this.request(s)}async getOpportunityActivities(e,t){const i=new URLSearchParams;t?.page&&i.set("page",t.page.toString()),t?.limit&&i.set("limit",t.limit.toString()),t?.type&&i.set("type",t.type);const n=i.toString(),s=`/api/workspaces/${this.workspaceId}/opportunities/${e}/activities${n?`?${n}`:""}`;return this.request(s)}async createActivity(e){let t;return t=e.opportunityId?`/api/workspaces/${this.workspaceId}/opportunities/${e.opportunityId}/activities`:e.contactId?`/api/workspaces/${this.workspaceId}/contacts/${e.contactId}/activities`:`/api/workspaces/${this.workspaceId}/activities`,this.request(t,{method:"POST",body:JSON.stringify(e)})}async updateActivity(e,t){return this.request(`/api/workspaces/${this.workspaceId}/activities/${e}`,{method:"PATCH",body:JSON.stringify(t)})}async deleteActivity(e){return this.request(`/api/workspaces/${this.workspaceId}/activities/${e}`,{method:"DELETE"})}async logCall(e){return this.createActivity({type:"call",title:("inbound"===e.direction?"Inbound":"Outbound")+" Call",direction:e.direction,duration:e.duration,outcome:e.outcome,description:e.notes,contactId:e.contactId,opportunityId:e.opportunityId})}async logMeeting(e){return this.createActivity({type:"meeting",title:e.title,duration:e.duration,outcome:e.outcome,description:e.notes,contactId:e.contactId,opportunityId:e.opportunityId})}async addNote(e){return this.createActivity({type:"note",title:"Note",description:e.content,contactId:e.contactId,opportunityId:e.opportunityId})}async getEmailTemplates(e){const t=new URLSearchParams;e?.page&&t.set("page",e.page.toString()),e?.limit&&t.set("limit",e.limit.toString());const i=t.toString(),n=`/api/workspaces/${this.workspaceId}/email-templates${i?`?${i}`:""}`;return this.request(n)}async getEmailTemplate(e){return this.request(`/api/workspaces/${this.workspaceId}/email-templates/${e}`)}async createEmailTemplate(e){return this.request(`/api/workspaces/${this.workspaceId}/email-templates`,{method:"POST",body:JSON.stringify(e)})}async updateEmailTemplate(e,t){return this.request(`/api/workspaces/${this.workspaceId}/email-templates/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteEmailTemplate(e){return this.request(`/api/workspaces/${this.workspaceId}/email-templates/${e}`,{method:"DELETE"})}async sendEmail(e){return this.request(`/api/workspaces/${this.workspaceId}/emails/send`,{method:"POST",body:JSON.stringify(e)})}async getContactByEmail(e){this.validateRequired("email",e,"getContactByEmail");const t=new URLSearchParams({search:e,limit:"1"});return this.request(`/api/workspaces/${this.workspaceId}/contacts?${t.toString()}`)}async getContactActivity(e,t){this.validateRequired("contactId",e,"getContactActivity");const i=new URLSearchParams;t?.page&&i.set("page",t.page.toString()),t?.limit&&i.set("limit",t.limit.toString()),t?.type&&i.set("type",t.type),t?.startDate&&i.set("startDate",t.startDate),t?.endDate&&i.set("endDate",t.endDate);const n=i.toString(),s=`/api/workspaces/${this.workspaceId}/contacts/${e}/activities${n?`?${n}`:""}`;return this.request(s)}async getContactEngagement(e){return this.validateRequired("contactId",e,"getContactEngagement"),this.request(`/api/workspaces/${this.workspaceId}/contacts/${e}/engagement`)}async getContactTimeline(e,t){this.validateRequired("contactId",e,"getContactTimeline");const i=new URLSearchParams;t?.page&&i.set("page",t.page.toString()),t?.limit&&i.set("limit",t.limit.toString());const n=i.toString(),s=`/api/workspaces/${this.workspaceId}/contacts/${e}/timeline${n?`?${n}`:""}`;return this.request(s)}async searchContacts(e,t){const i=new URLSearchParams;i.set("search",e),t?.status&&i.set("status",t.status),t?.lifecycleStage&&i.set("lifecycleStage",t.lifecycleStage),t?.source&&i.set("source",t.source),t?.tags&&i.set("tags",t.tags.join(",")),t?.page&&i.set("page",t.page.toString()),t?.limit&&i.set("limit",t.limit.toString());const n=i.toString(),s=`/api/workspaces/${this.workspaceId}/contacts${n?`?${n}`:""}`;return this.request(s)}async listWebhooks(e){const t=new URLSearchParams;e?.page&&t.set("page",e.page.toString()),e?.limit&&t.set("limit",e.limit.toString());const i=t.toString();return this.request(`/api/workspaces/${this.workspaceId}/webhooks${i?`?${i}`:""}`)}async createWebhook(e){return this.request(`/api/workspaces/${this.workspaceId}/webhooks`,{method:"POST",body:JSON.stringify(e)})}async deleteWebhook(e){return this.validateRequired("webhookId",e,"deleteWebhook"),this.request(`/api/workspaces/${this.workspaceId}/webhooks/${e}`,{method:"DELETE"})}async getEventTriggers(){return this.triggers.getTriggers()}async createEventTrigger(e){return this.triggers.createTrigger(e)}async updateEventTrigger(e,t){return this.triggers.updateTrigger(e,t)}async deleteEventTrigger(e){return this.triggers.deleteTrigger(e)}},e.ConsentManager=te,e.SDK_VERSION=i,e.Tracker=ie,e.clianta=re,e.default=re,Object.defineProperty(e,"__esModule",{value:!0})});
7
7
  //# sourceMappingURL=clianta.umd.min.js.map