@clianta/sdk 1.3.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/clianta.cjs.js +759 -631
- package/dist/clianta.cjs.js.map +1 -1
- package/dist/clianta.esm.js +759 -631
- package/dist/clianta.esm.js.map +1 -1
- package/dist/clianta.umd.js +759 -631
- package/dist/clianta.umd.js.map +1 -1
- package/dist/clianta.umd.min.js +2 -2
- package/dist/clianta.umd.min.js.map +1 -1
- package/dist/index.d.ts +863 -803
- package/dist/react.cjs.js +759 -631
- package/dist/react.cjs.js.map +1 -1
- package/dist/react.d.ts +37 -3
- package/dist/react.esm.js +759 -631
- package/dist/react.esm.js.map +1 -1
- package/dist/vue.cjs.js +759 -631
- package/dist/vue.cjs.js.map +1 -1
- package/dist/vue.d.ts +37 -3
- package/dist/vue.esm.js +759 -631
- package/dist/vue.esm.js.map +1 -1
- package/package.json +1 -1
package/dist/clianta.umd.min.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* Clianta SDK v1.
|
|
2
|
+
* Clianta SDK v1.4.0
|
|
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";const t="1.3.0",i={projectId:"",apiEndpoint:(()=>{if("undefined"==typeof window)return"https://api.clianta.online";const e=window.location.hostname;return e.includes("localhost")||e.includes("127.0.0.1")?"http://localhost:5000":"https://api.clianta.online"})(),authToken:"",debug:!1,autoPageView:!0,plugins:["pageView","forms","scroll","clicks","engagement","downloads","exitIntent"],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},n="mb_vid",s="mb_sid",r="mb_st",o="mb_consent",a="mb_queue",c=[25,50,75,100],d=[".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".rar",".tar",".gz",".7z",".csv",".txt",".json",".xml",".mp3",".mp4",".wav",".avi",".mov"];const l="[Clianta]",u={debug:"color: #6b7280; font-weight: normal;",info:"color: #3b82f6; font-weight: normal;",warn:"color: #f59e0b; font-weight: bold;",error:"color: #ef4444; font-weight: bold;"},h={debug:0,info:1,warn:2,error:3};const p=function(e=!1){let t="debug",i=e;const n=e=>!!i&&h[e]>=h[t],s=(e,t)=>"undefined"!=typeof console&&"undefined"!=typeof window?[`%c${l}`,u[e],...t]:[`${l} [${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});return this.send(t,i)}async sendIdentify(e){const t=`${this.config.apiEndpoint}/api/public/track/identify`,i=JSON.stringify(e);return this.send(t,i)}sendBeacon(e){if("undefined"==typeof navigator||!navigator.sendBeacon)return p.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?p.debug(`Beacon sent ${e.length} events`):p.warn("sendBeacon returned false"),i}catch(e){return p.error("sendBeacon error:",e),!1}}async send(e,t,i=1){try{const n=await this.fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:!0});return n.ok?(p.debug("Request successful:",e),{success:!0,status:n.status}):n.status>=500&&i<this.config.maxRetries?(p.warn(`Server error (${n.status}), retrying...`),await this.delay(this.config.retryDelay*i),this.send(e,t,i+1)):(p.error(`Request failed with status ${n.status}`),{success:!1,status:n.status})}catch(n){return i<this.config.maxRetries?(p.warn(`Network error, retrying (${i}/${this.config.maxRetries})...`),await this.delay(this.config.retryDelay*i),this.send(e,t,i+1)):(p.error("Request failed after retries:",n),{success:!1,error:n})}}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 m(){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 f(e){try{if("undefined"!=typeof localStorage)return localStorage.getItem(e)}catch{}return null}function y(e,t){try{if("undefined"!=typeof localStorage)return localStorage.setItem(e,t),!0}catch{}return!1}function w(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 v(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()}return document.cookie=e+"="+t+n+"; path=/; SameSite=Lax",t}function k(e=!1){const t=n;let i=null;return i=e?v(t):f(t),i||(i=m(),e?v(t,i,365):y(t,i)),i}function S(e=!1){const t=n;if(e)v(t,"",-1);else try{localStorage.removeItem(t)}catch{}try{sessionStorage.removeItem(s),sessionStorage.removeItem(r)}catch{}}function T(){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 E(e){try{return e.split("/").pop()?.split("?")[0]||"unknown"}catch{return"unknown"}}function I(e){const t=E(e).split(".");return t.length>1&&t.pop()||"unknown"}function x(e,t=100){return(e.innerText||e.textContent||e.value||"").trim().substring(0,t)}class C{constructor(e,t={}){this.queue=[],this.flushTimer=null,this.isFlushing=!1,this.eventTimestamps=[],this.boundBeforeUnload=null,this.boundVisibilityChange=null,this.boundPageHide=null,this.transport=e,this.config={batchSize:t.batchSize??10,flushInterval:t.flushInterval??5e3,maxQueueSize:t.maxQueueSize??1e3,storageKey:t.storageKey??a},this.restoreQueue(),this.startFlushTimer(),this.setupUnloadHandlers()}push(e){this.checkRateLimit()?(this.queue.length>=this.config.maxQueueSize&&(p.warn("Queue full, dropping oldest event"),this.queue.shift()),this.queue.push(e),p.debug("Event queued:",e.eventName,`(${this.queue.length} in queue)`),this.queue.length>=this.config.batchSize&&this.flush()):p.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)return;this.isFlushing=!0;const e=this.queue.length,t=this.queue.splice(0,e);try{p.debug(`Flushing ${t.length} events`),this.persistQueue([]);(await this.transport.sendEvents(t)).success?p.debug("Flush successful"):(p.warn("Flush failed, re-queuing events"),this.queue.unshift(...t),this.persistQueue(this.queue))}catch(e){p.error("Flush error:",e)}finally{this.isFlushing=!1}}flushSync(){if(0===this.queue.length)return;const e=this.queue.splice(0,this.queue.length);p.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(){this.queue=[],this.persistQueue([])}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))}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()},window.addEventListener("visibilitychange",this.boundVisibilityChange),this.boundPageHide=()=>this.flushSync(),window.addEventListener("pagehide",this.boundPageHide))}persistQueue(e){try{y(this.config.storageKey,JSON.stringify(e))}catch{}}restoreQueue(){try{const e=f(this.config.storageKey);if(e){const t=JSON.parse(e);Array.isArray(t)&&t.length>0&&(this.queue=t,p.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)}}class q extends ${constructor(){super(...arguments),this.name="pageView",this.originalPushState=null,this.originalReplaceState=null,this.popstateHandler=null}init(e){if(super.init(e),this.trackPageView(),"undefined"!=typeof window){this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;const e=this;history.pushState=function(...t){e.originalPushState.apply(history,t),e.trackPageView()},history.replaceState=function(...t){e.originalReplaceState.apply(history,t),e.trackPageView()},this.popstateHandler=()=>this.trackPageView(),window.addEventListener("popstate",this.popstateHandler)}}destroy(){this.originalPushState&&(history.pushState=this.originalPushState,this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,this.originalReplaceState=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=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 L extends ${constructor(){super(...arguments),this.name="scroll",this.milestonesReached=new Set,this.maxScrollDepth=0,this.pageLoadTime=0,this.scrollTimeout=null,this.boundHandler=null,this.originalPushState=null,this.originalReplaceState=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.setupNavigationReset())}destroy(){this.boundHandler&&"undefined"!=typeof window&&window.removeEventListener("scroll",this.boundHandler),this.scrollTimeout&&clearTimeout(this.scrollTimeout),this.originalPushState&&(history.pushState=this.originalPushState,this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,this.originalReplaceState=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()}setupNavigationReset(){if("undefined"==typeof window)return;this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;const e=this;history.pushState=function(...t){e.originalPushState.apply(history,t),e.resetForNavigation()},history.replaceState=function(...t){e.originalReplaceState.apply(history,t),e.resetForNavigation()},this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler)}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 c)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 P extends ${constructor(){super(...arguments),this.name="forms",this.trackedForms=new WeakSet,this.formInteractions=new Set,this.observer=null,this.listeners=[]}init(e){super.init(e),"undefined"!=typeof document&&(this.trackAllForms(),"undefined"!=typeof MutationObserver&&(this.observer=new MutationObserver(()=>this.trackAllForms()),this.observer.observe(document.body,{childList:!0,subtree:!0})))}destroy(){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).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(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 H 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){const t=e.target;if(!(t&&(i=t,["BUTTON","A","INPUT"].includes(i.tagName)||i.hasAttribute("data-track-click")||i.classList.contains("track-click"))))return;var i;const n=x(t,100),s=function(e){return{tag:e.tagName?.toLowerCase()||"unknown",id:e.id||"",className:e.className||"",text:x(e,50)}}(t);this.track("button_click","Button Clicked",{buttonText:n,elementType:t.tagName.toLowerCase(),elementId:s.id,elementClass:s.className,href:t.href||void 0})}}class F extends ${constructor(){super(...arguments),this.name="engagement",this.pageLoadTime=0,this.engagementStartTime=0,this.isEngaged=!1,this.engagementTimeout=null,this.boundMarkEngaged=null,this.boundTrackTimeOnPage=null,this.boundVisibilityHandler=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()},["mousemove","keydown","touchstart","scroll"].forEach(e=>{document.addEventListener(e,this.boundMarkEngaged,{passive:!0})}),window.addEventListener("beforeunload",this.boundTrackTimeOnPage),document.addEventListener("visibilitychange",this.boundVisibilityHandler))}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.engagementTimeout&&clearTimeout(this.engagementTimeout),super.destroy()}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(){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.originalPushState=null,this.originalReplaceState=null,this.popstateHandler=null}init(e){super.init(e),"undefined"!=typeof document&&(this.boundHandler=this.handleClick.bind(this),document.addEventListener("click",this.boundHandler,!0),this.setupNavigationReset())}destroy(){this.boundHandler&&"undefined"!=typeof document&&document.removeEventListener("click",this.boundHandler,!0),this.originalPushState&&(history.pushState=this.originalPushState,this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,this.originalReplaceState=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),super.destroy()}resetForNavigation(){this.trackedDownloads.clear()}setupNavigationReset(){if("undefined"==typeof window)return;this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;const e=this;history.pushState=function(...t){e.originalPushState.apply(history,t),e.resetForNavigation()},history.replaceState=function(...t){e.originalReplaceState.apply(history,t),e.resetForNavigation()},this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler)}handleClick(e){const t=e.target.closest("a");if(!t||!t.href)return;const i=t.href;(function(e){const t=e.toLowerCase();return d.some(e=>t.includes(e))})(i)&&(this.trackedDownloads.has(i)||(this.trackedDownloads.add(i),this.track("download","File Download",{url:i,filename:E(i),fileType:I(i),linkText:x(t,100)})))}}class N extends ${constructor(){super(...arguments),this.name="exitIntent",this.exitIntentShown=!1,this.pageLoadTime=0,this.boundHandler=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))}destroy(){this.boundHandler&&"undefined"!=typeof document&&document.removeEventListener("mouseleave",this.boundHandler),super.destroy()}handleMouseLeave(e){e.clientY>0||this.exitIntentShown||(this.exitIntentShown=!0,this.track("exit_intent","Exit Intent Detected",{timeOnPage:Date.now()-this.pageLoadTime}))}}class R extends ${constructor(){super(...arguments),this.name="errors",this.boundErrorHandler=null,this.boundRejectionHandler=null}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){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){this.track("error","Unhandled Promise Rejection",{reason:String(e.reason).substring(0,200)})}}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],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 _ extends ${constructor(){super(...arguments),this.name="popupForms",this.forms=[],this.shownForms=new Set,this.scrollHandler=null,this.exitHandler=null}async init(e){super.init(e),"undefined"!=typeof window&&(this.loadShownForms(),await this.fetchForms(),this.setupTriggers())}destroy(){this.removeTriggers(),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(),i=e.apiEndpoint||"https://api.clianta.online";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){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":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=>{t.addEventListener("click",()=>this.showForm(e))})}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||"https://api.clianta.online";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||"https://api.clianta.online",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.innerHTML="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");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&&setTimeout(()=>{window.location.href=e.redirectUrl},1500),setTimeout(()=>{const t=document.getElementById(`clianta-form-overlay-${e._id}`);t&&this.closeForm(e._id,t,i)},2e3)}}catch(t){console.error("[Clianta] Form submit error:",t),a&&(a.disabled=!1,a.innerHTML=e.submitButtonText||"Subscribe")}}}function M(e){switch(e){case"pageView":return new q;case"scroll":return new L;case"forms":return new P;case"clicks":return new H;case"engagement":return new F;case"downloads":return new O;case"exitIntent":return new N;case"errors":return new R;case"performance":return new D;case"popupForms":return new _;default:throw new Error(`Unknown plugin: ${e}`)}}function A(e){try{if("undefined"==typeof localStorage)return!1;const t={state:e,timestamp:Date.now(),version:1};return localStorage.setItem(o,JSON.stringify(t)),!0}catch{return!1}}function V(){try{if("undefined"==typeof localStorage)return null;const e=localStorage.getItem(o);if(!e)return null;const t=JSON.parse(e);return 1!==t.version?(U(),null):t}catch{return null}}function U(){try{return"undefined"!=typeof localStorage&&(localStorage.removeItem(o),!0)}catch{return!1}}class z{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=V();t?(this.state=t.state,this.hasExplicitConsent=!0,p.debug("Loaded stored consent:",this.state)):(this.state=this.config.defaultConsent||{analytics:!0},this.hasExplicitConsent=!1,p.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,A(this.state),p.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,A(this.state),p.info("Consent revoked:",e),this.notifyChange(t)}update(e){const t={...this.state};this.state={...e},this.hasExplicitConsent=!0,A(this.state),p.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=[],U(),p.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!==V()}bufferEvent(e){this.eventBuffer.length>=100&&(p.warn("Consent event buffer full, dropping oldest event"),this.eventBuffer.shift()),this.eventBuffer.push(e),p.debug("Event buffered (waiting for consent):",e.eventName)}flushBuffer(){const e=[...this.eventBuffer];return this.eventBuffer=[],e.length>0&&p.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){p.error("Consent change callback error:",e)}}}class B{constructor(e,n={}){if(this.plugins=[],this.isInitialized=!1,this.pendingIdentify=null,!e)throw new Error("[Clianta] Workspace ID is required");this.workspaceId=e,this.config=function(e={}){return{...i,...e,consent:{...i.consent,...e.consent}}}(n),p.enabled=this.config.debug,p.info(`Initializing SDK v${t}`,{workspaceId:e}),this.consentManager=new z({...this.config.consent,onConsentChange:(e,t)=>{this.onConsentChange(e,t)}}),this.transport=new g({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(),p.debug("IDs created",{visitorId:this.visitorId,sessionId:this.sessionId}),this.initPlugins(),this.isInitialized=!0,p.info("SDK initialized successfully")}createVisitorId(){if(this.config.consent.anonymousMode&&!this.consentManager.hasExplicit()){const e=n+"_anon";let t=w(e);return t||(t="anon_"+m(),b(e,t)),t}if(this.config.cookielessMode){let e=w(n);return e||(e=m(),b(n,e)),e}return k(this.config.useCookies)}createSessionId(){return function(e){const t=s,i=r;let n=w(t);const o=parseInt(w(i)||"0",10),a=Date.now();return(!n||a-o>e)&&(n=m(),b(t,n)),b(i,a.toString()),n}(this.config.sessionTimeout)}onConsentChange(e,t){if(p.debug("Consent changed:",{from:t,to:e}),e.analytics&&!t.analytics){this.config.consent.anonymousMode&&(this.visitorId=k(this.config.useCookies),p.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=M(e),i=t.init(this);i instanceof Promise&&i.catch(t=>{p.error(`Async plugin init failed: ${e}`,t)}),this.plugins.push(t),p.debug(`Plugin loaded: ${e}`)}catch(t){p.error(`Failed to load plugin: ${e}`,t)}}track(e,i,n={}){if(!this.isInitialized)return void p.warn("SDK not initialized, event dropped");const s={workspaceId:this.workspaceId,visitorId:this.visitorId,sessionId:this.sessionId,eventType:e,eventName:i,url:"undefined"!=typeof window?window.location.href:"",referrer:"undefined"!=typeof document&&document.referrer||void 0,properties:n,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"},...T(),timestamp:(new Date).toISOString(),sdkVersion:t};if(!this.consentManager.canTrack())return this.config.consent.waitForConsent?void this.consentManager.bufferEvent(s):void p.debug("Event dropped (no consent):",i);this.queue.push(s),p.debug("Event tracked:",i,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 void p.warn("Email is required for identification");p.info("Identifying visitor:",e);const i=await this.transport.sendIdentify({workspaceId:this.workspaceId,visitorId:this.visitorId,email:e,properties:t});i.success?(p.info("Visitor identified successfully"),this.pendingIdentify=null):(p.error("Failed to identify visitor:",i.error),this.pendingIdentify={email:e,traits:t})}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){p.enabled=e,p.info("Debug mode "+(e?"enabled":"disabled"))}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(){p.info("Resetting visitor data"),S(this.config.useCookies),this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),this.queue.clear()}deleteData(){if(p.info("Deleting all user data (GDPR request)"),this.queue.clear(),this.consentManager.reset(),S(this.config.useCookies),"undefined"!=typeof sessionStorage)try{sessionStorage.removeItem(n),sessionStorage.removeItem(n+"_anon"),sessionStorage.removeItem(s),sessionStorage.removeItem(r)}catch{}if("undefined"!=typeof localStorage)try{localStorage.removeItem(n),localStorage.removeItem(o),localStorage.removeItem(a)}catch{}this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),p.info("All user data deleted")}async destroy(){p.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 j{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),p.debug(`Event listener registered: ${e}`)}off(e,t){const i=this.listeners.get(e);i&&i.delete(t)}emit(e,t){p.debug(`Event emitted: ${e}`,t);const i=this.listeners.get(e);i&&i.forEach(i=>{try{i(t)}catch(t){p.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){p.info(`Executing actions for trigger: ${e.name}`);for(const i of e.actions)try{await this.executeAction(i,t)}catch(e){p.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:p.warn("Unknown action type:",e)}}async executeSendEmail(e,t){p.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){p.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){p.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?(p.debug("Updating contact:",i),await this.request(`/api/workspaces/${this.workspaceId}/contacts/${i}`,{method:"PUT",body:JSON.stringify(e.updates)})):p.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})}}class J{constructor(e,t,i){this.apiEndpoint=e,this.workspaceId=t,this.authToken=i,this.triggers=new j(e,t,i)}setAuthToken(e){this.authToken=e,this.triggers.setAuthToken(e)}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.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 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 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)}}let W=null;function Q(e,t){return W&&W.getWorkspaceId()===e||(W&&W.destroy(),W=new B(e,t)),W}"undefined"!=typeof window&&(window.clianta=Q,window.Clianta={clianta:Q,Tracker:B,CRMClient:J,ConsentManager:z,EventTriggersManager:j}),e.CRMClient=J,e.ConsentManager=z,e.EventTriggersManager=j,e.SDK_VERSION=t,e.Tracker=B,e.clianta=Q,e.default=Q,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";const t="1.4.0",i={projectId:"",apiEndpoint:(()=>{if("undefined"==typeof window)return"https://api.clianta.online";const e=window.location.hostname;return e.includes("localhost")||e.includes("127.0.0.1")?"http://localhost:5000":"https://api.clianta.online"})(),authToken:"",apiKey:"",debug:!1,autoPageView:!0,plugins:["pageView","forms","scroll","clicks","engagement","downloads","exitIntent"],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},n="mb_vid",s="mb_sid",r="mb_st",o="mb_consent",a="mb_queue",c=[25,50,75,100],d=[".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".rar",".tar",".gz",".7z",".csv",".txt",".json",".xml",".mp3",".mp4",".wav",".avi",".mov"];const u="[Clianta]",l={debug:"color: #6b7280; font-weight: normal;",info:"color: #3b82f6; font-weight: normal;",warn:"color: #f59e0b; font-weight: bold;",error:"color: #ef4444; font-weight: bold;"},h={debug:0,info:1,warn:2,error:3};const p=function(e=!1){let t="debug",i=e;const n=e=>!!i&&h[e]>=h[t],s=(e,t)=>"undefined"!=typeof console&&"undefined"!=typeof window?[`%c${u}`,l[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});return this.send(t,i)}async sendIdentify(e){const t=`${this.config.apiEndpoint}/api/public/track/identify`;try{const i=await this.fetchWithTimeout(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0}),n=await i.json().catch(()=>({}));return i.ok?(p.debug("Identify successful, contactId:",n.contactId),{success:!0,status:i.status,contactId:n.contactId??void 0}):(i.status>=500?p.warn(`Identify server error (${i.status})`):p.error(`Identify failed with status ${i.status}:`,n.message),{success:!1,status:i.status})}catch(e){return p.error("Identify request failed:",e),{success:!1,error:e}}}sendBeacon(e){if("undefined"==typeof navigator||!navigator.sendBeacon)return p.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?p.debug(`Beacon sent ${e.length} events`):p.warn("sendBeacon returned false"),i}catch(e){return p.error("sendBeacon error:",e),!1}}async send(e,t,i=1){try{const n=await this.fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:!0});return n.ok?(p.debug("Request successful:",e),{success:!0,status:n.status}):n.status>=500&&i<this.config.maxRetries?(p.warn(`Server error (${n.status}), retrying...`),await this.delay(this.config.retryDelay*i),this.send(e,t,i+1)):(p.error(`Request failed with status ${n.status}`),{success:!1,status:n.status})}catch(n){return i<this.config.maxRetries?(p.warn(`Network error, retrying (${i}/${this.config.maxRetries})...`),await this.delay(this.config.retryDelay*i),this.send(e,t,i+1)):(p.error("Request failed after retries:",n),{success:!1,error:n})}}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 m(){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 f(e){try{if("undefined"!=typeof localStorage)return localStorage.getItem(e)}catch{}return null}function y(e,t){try{if("undefined"!=typeof localStorage)return localStorage.setItem(e,t),!0}catch{}return!1}function w(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 v(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()}return document.cookie=e+"="+t+n+"; path=/; SameSite=Lax",t}function k(e=!1){const t=n;let i=null;return i=e?v(t):f(t),i||(i=m(),e?v(t,i,365):y(t,i)),i}function S(e=!1){const t=n;if(e)v(t,"",-1);else try{localStorage.removeItem(t)}catch{}try{sessionStorage.removeItem(s),sessionStorage.removeItem(r)}catch{}}function T(){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 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 x(e,t=100){return(e.innerText||e.textContent||e.value||"").trim().substring(0,t)}class C{constructor(e,t={}){this.queue=[],this.flushTimer=null,this.isFlushing=!1,this.eventTimestamps=[],this.boundBeforeUnload=null,this.boundVisibilityChange=null,this.boundPageHide=null,this.transport=e,this.config={batchSize:t.batchSize??10,flushInterval:t.flushInterval??5e3,maxQueueSize:t.maxQueueSize??1e3,storageKey:t.storageKey??a},this.restoreQueue(),this.startFlushTimer(),this.setupUnloadHandlers()}push(e){this.checkRateLimit()?(this.queue.length>=this.config.maxQueueSize&&(p.warn("Queue full, dropping oldest event"),this.queue.shift()),this.queue.push(e),p.debug("Event queued:",e.eventName,`(${this.queue.length} in queue)`),this.queue.length>=this.config.batchSize&&this.flush()):p.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)return;this.isFlushing=!0;const e=this.queue.length,t=this.queue.splice(0,e);try{p.debug(`Flushing ${t.length} events`),this.persistQueue([]);(await this.transport.sendEvents(t)).success?p.debug("Flush successful"):(p.warn("Flush failed, re-queuing events"),this.queue.unshift(...t),this.persistQueue(this.queue))}catch(e){p.error("Flush error:",e)}finally{this.isFlushing=!1}}flushSync(){if(0===this.queue.length)return;const e=this.queue.splice(0,this.queue.length);p.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(){this.queue=[],this.persistQueue([])}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))}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()},window.addEventListener("visibilitychange",this.boundVisibilityChange),this.boundPageHide=()=>this.flushSync(),window.addEventListener("pagehide",this.boundPageHide))}persistQueue(e){try{y(this.config.storageKey,JSON.stringify(e))}catch{}}restoreQueue(){try{const e=f(this.config.storageKey);if(e){const t=JSON.parse(e);Array.isArray(t)&&t.length>0&&(this.queue=t,p.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)}}class q extends ${constructor(){super(...arguments),this.name="pageView",this.originalPushState=null,this.originalReplaceState=null,this.popstateHandler=null}init(e){if(super.init(e),this.trackPageView(),"undefined"!=typeof window){this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;const e=this;history.pushState=function(...t){e.originalPushState.apply(history,t),e.trackPageView()},history.replaceState=function(...t){e.originalReplaceState.apply(history,t),e.trackPageView()},this.popstateHandler=()=>this.trackPageView(),window.addEventListener("popstate",this.popstateHandler)}}destroy(){this.originalPushState&&(history.pushState=this.originalPushState,this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,this.originalReplaceState=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=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 L extends ${constructor(){super(...arguments),this.name="scroll",this.milestonesReached=new Set,this.maxScrollDepth=0,this.pageLoadTime=0,this.scrollTimeout=null,this.boundHandler=null,this.originalPushState=null,this.originalReplaceState=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.setupNavigationReset())}destroy(){this.boundHandler&&"undefined"!=typeof window&&window.removeEventListener("scroll",this.boundHandler),this.scrollTimeout&&clearTimeout(this.scrollTimeout),this.originalPushState&&(history.pushState=this.originalPushState,this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,this.originalReplaceState=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()}setupNavigationReset(){if("undefined"==typeof window)return;this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;const e=this;history.pushState=function(...t){e.originalPushState.apply(history,t),e.resetForNavigation()},history.replaceState=function(...t){e.originalReplaceState.apply(history,t),e.resetForNavigation()},this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler)}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 c)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 P extends ${constructor(){super(...arguments),this.name="forms",this.trackedForms=new WeakSet,this.formInteractions=new Set,this.observer=null,this.listeners=[]}init(e){super.init(e),"undefined"!=typeof document&&(this.trackAllForms(),"undefined"!=typeof MutationObserver&&(this.observer=new MutationObserver(()=>this.trackAllForms()),this.observer.observe(document.body,{childList:!0,subtree:!0})))}destroy(){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).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(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 H 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){const t=e.target;if(!(t&&(i=t,["BUTTON","A","INPUT"].includes(i.tagName)||i.hasAttribute("data-track-click")||i.classList.contains("track-click"))))return;var i;const n=x(t,100),s=function(e){return{tag:e.tagName?.toLowerCase()||"unknown",id:e.id||"",className:e.className||"",text:x(e,50)}}(t);this.track("button_click","Button Clicked",{buttonText:n,elementType:t.tagName.toLowerCase(),elementId:s.id,elementClass:s.className,href:t.href||void 0})}}class F extends ${constructor(){super(...arguments),this.name="engagement",this.pageLoadTime=0,this.engagementStartTime=0,this.isEngaged=!1,this.engagementTimeout=null,this.boundMarkEngaged=null,this.boundTrackTimeOnPage=null,this.boundVisibilityHandler=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()},["mousemove","keydown","touchstart","scroll"].forEach(e=>{document.addEventListener(e,this.boundMarkEngaged,{passive:!0})}),window.addEventListener("beforeunload",this.boundTrackTimeOnPage),document.addEventListener("visibilitychange",this.boundVisibilityHandler))}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.engagementTimeout&&clearTimeout(this.engagementTimeout),super.destroy()}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(){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.originalPushState=null,this.originalReplaceState=null,this.popstateHandler=null}init(e){super.init(e),"undefined"!=typeof document&&(this.boundHandler=this.handleClick.bind(this),document.addEventListener("click",this.boundHandler,!0),this.setupNavigationReset())}destroy(){this.boundHandler&&"undefined"!=typeof document&&document.removeEventListener("click",this.boundHandler,!0),this.originalPushState&&(history.pushState=this.originalPushState,this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,this.originalReplaceState=null),this.popstateHandler&&"undefined"!=typeof window&&(window.removeEventListener("popstate",this.popstateHandler),this.popstateHandler=null),super.destroy()}resetForNavigation(){this.trackedDownloads.clear()}setupNavigationReset(){if("undefined"==typeof window)return;this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState;const e=this;history.pushState=function(...t){e.originalPushState.apply(history,t),e.resetForNavigation()},history.replaceState=function(...t){e.originalReplaceState.apply(history,t),e.resetForNavigation()},this.popstateHandler=()=>this.resetForNavigation(),window.addEventListener("popstate",this.popstateHandler)}handleClick(e){const t=e.target.closest("a");if(!t||!t.href)return;const i=t.href;(function(e){const t=e.toLowerCase();return d.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:x(t,100)})))}}class N extends ${constructor(){super(...arguments),this.name="exitIntent",this.exitIntentShown=!1,this.pageLoadTime=0,this.boundHandler=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))}destroy(){this.boundHandler&&"undefined"!=typeof document&&document.removeEventListener("mouseleave",this.boundHandler),super.destroy()}handleMouseLeave(e){e.clientY>0||this.exitIntentShown||(this.exitIntentShown=!0,this.track("exit_intent","Exit Intent Detected",{timeOnPage:Date.now()-this.pageLoadTime}))}}class R extends ${constructor(){super(...arguments),this.name="errors",this.boundErrorHandler=null,this.boundRejectionHandler=null}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){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){this.track("error","Unhandled Promise Rejection",{reason:String(e.reason).substring(0,200)})}}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],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 A extends ${constructor(){super(...arguments),this.name="popupForms",this.forms=[],this.shownForms=new Set,this.scrollHandler=null,this.exitHandler=null}async init(e){super.init(e),"undefined"!=typeof window&&(this.loadShownForms(),await this.fetchForms(),this.setupTriggers())}destroy(){this.removeTriggers(),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(),i=e.apiEndpoint||"https://api.clianta.online";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){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":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=>{t.addEventListener("click",()=>this.showForm(e))})}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||"https://api.clianta.online";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||"https://api.clianta.online",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.innerHTML="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");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&&setTimeout(()=>{window.location.href=e.redirectUrl},1500),setTimeout(()=>{const t=document.getElementById(`clianta-form-overlay-${e._id}`);t&&this.closeForm(e._id,t,i)},2e3)}}catch(t){console.error("[Clianta] Form submit error:",t),a&&(a.disabled=!1,a.innerHTML=e.submitButtonText||"Subscribe")}}}function _(e){switch(e){case"pageView":return new q;case"scroll":return new L;case"forms":return new P;case"clicks":return new H;case"engagement":return new F;case"downloads":return new O;case"exitIntent":return new N;case"errors":return new R;case"performance":return new D;case"popupForms":return new A;default:throw new Error(`Unknown plugin: ${e}`)}}function M(e){try{if("undefined"==typeof localStorage)return!1;const t={state:e,timestamp:Date.now(),version:1};return localStorage.setItem(o,JSON.stringify(t)),!0}catch{return!1}}function V(){try{if("undefined"==typeof localStorage)return null;const e=localStorage.getItem(o);if(!e)return null;const t=JSON.parse(e);return 1!==t.version?(U(),null):t}catch{return null}}function U(){try{return"undefined"!=typeof localStorage&&(localStorage.removeItem(o),!0)}catch{return!1}}class z{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=V();t?(this.state=t.state,this.hasExplicitConsent=!0,p.debug("Loaded stored consent:",this.state)):(this.state=this.config.defaultConsent||{analytics:!0},this.hasExplicitConsent=!1,p.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,M(this.state),p.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,M(this.state),p.info("Consent revoked:",e),this.notifyChange(t)}update(e){const t={...this.state};this.state={...e},this.hasExplicitConsent=!0,M(this.state),p.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=[],U(),p.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!==V()}bufferEvent(e){this.eventBuffer.length>=100&&(p.warn("Consent event buffer full, dropping oldest event"),this.eventBuffer.shift()),this.eventBuffer.push(e),p.debug("Event buffered (waiting for consent):",e.eventName)}flushBuffer(){const e=[...this.eventBuffer];return this.eventBuffer=[],e.length>0&&p.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){p.error("Consent change callback error:",e)}}}class B{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),p.debug(`Event listener registered: ${e}`)}off(e,t){const i=this.listeners.get(e);i&&i.delete(t)}emit(e,t){p.debug(`Event emitted: ${e}`,t);const i=this.listeners.get(e);i&&i.forEach(i=>{try{i(t)}catch(t){p.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){p.info(`Executing actions for trigger: ${e.name}`);for(const i of e.actions)try{await this.executeAction(i,t)}catch(e){p.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:p.warn("Unknown action type:",e)}}async executeSendEmail(e,t){p.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){p.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){p.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?(p.debug("Updating contact:",i),await this.request(`/api/workspaces/${this.workspaceId}/contacts/${i}`,{method:"PUT",body:JSON.stringify(e.updates)})):p.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})}}class j{constructor(e,t,i,n){this.apiEndpoint=e,this.workspaceId=t,this.authToken=i,this.apiKey=n,this.triggers=new B(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 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)}}class J{constructor(e,n={}){if(this.plugins=[],this.isInitialized=!1,this.contactId=null,this.pendingIdentify=null,!e)throw new Error("[Clianta] Workspace ID is required");this.workspaceId=e,this.config=function(e={}){return{...i,...e,consent:{...i.consent,...e.consent}}}(n),p.enabled=this.config.debug,p.info(`Initializing SDK v${t}`,{workspaceId:e}),this.consentManager=new z({...this.config.consent,onConsentChange:(e,t)=>{this.onConsentChange(e,t)}}),this.transport=new g({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(),p.debug("IDs created",{visitorId:this.visitorId,sessionId:this.sessionId}),this.initPlugins(),this.isInitialized=!0,p.info("SDK initialized successfully")}createVisitorId(){if(this.config.consent.anonymousMode&&!this.consentManager.hasExplicit()){const e=n+"_anon";let t=w(e);return t||(t="anon_"+m(),b(e,t)),t}if(this.config.cookielessMode){let e=w(n);return e||(e=m(),b(n,e)),e}return k(this.config.useCookies)}createSessionId(){return function(e){const t=s,i=r;let n=w(t);const o=parseInt(w(i)||"0",10),a=Date.now();return(!n||a-o>e)&&(n=m(),b(t,n)),b(i,a.toString()),n}(this.config.sessionTimeout)}onConsentChange(e,t){if(p.debug("Consent changed:",{from:t,to:e}),e.analytics&&!t.analytics){this.config.consent.anonymousMode&&(this.visitorId=k(this.config.useCookies),p.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=_(e),i=t.init(this);i instanceof Promise&&i.catch(t=>{p.error(`Async plugin init failed: ${e}`,t)}),this.plugins.push(t),p.debug(`Plugin loaded: ${e}`)}catch(t){p.error(`Failed to load plugin: ${e}`,t)}}track(e,i,n={}){if(!this.isInitialized)return void p.warn("SDK not initialized, event dropped");const s={workspaceId:this.workspaceId,visitorId:this.visitorId,sessionId:this.sessionId,eventType:e,eventName:i,url:"undefined"!=typeof window?window.location.href:"",referrer:"undefined"!=typeof document&&document.referrer||void 0,properties:{...n,eventId:m()},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"},...T(),timestamp:(new Date).toISOString(),sdkVersion:t};if(this.contactId&&(s.contactId=this.contactId),!this.consentManager.canTrack())return this.config.consent.waitForConsent?void this.consentManager.bufferEvent(s):void p.debug("Event dropped (no consent):",i);this.queue.push(s),p.debug("Event tracked:",i,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 p.warn("Email is required for identification"),null;p.info("Identifying visitor:",e);const i=await this.transport.sendIdentify({workspaceId:this.workspaceId,visitorId:this.visitorId,email:e,properties:t});return i.success?(p.info("Visitor identified successfully, contactId:",i.contactId),this.contactId=i.contactId??null,this.pendingIdentify=null,this.contactId):(p.error("Failed to identify visitor:",i.error),this.pendingIdentify={email:e,traits:t},null)}async sendEvent(e){const t=this.config.apiKey;if(!t)return p.error("sendEvent() requires an apiKey in the SDK config"),{success:!1,contactCreated:!1,event:e.event,error:"No API key configured"};return new j(this.config.apiEndpoint,this.workspaceId,void 0,t).sendEvent(e)}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){p.enabled=e,p.info("Debug mode "+(e?"enabled":"disabled"))}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(){p.info("Resetting visitor data"),S(this.config.useCookies),this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),this.queue.clear()}deleteData(){if(p.info("Deleting all user data (GDPR request)"),this.queue.clear(),this.consentManager.reset(),S(this.config.useCookies),"undefined"!=typeof sessionStorage)try{sessionStorage.removeItem(n),sessionStorage.removeItem(n+"_anon"),sessionStorage.removeItem(s),sessionStorage.removeItem(r)}catch{}if("undefined"!=typeof localStorage)try{localStorage.removeItem(n),localStorage.removeItem(o),localStorage.removeItem(a)}catch{}this.visitorId=this.createVisitorId(),this.sessionId=this.createSessionId(),p.info("All user data deleted")}async destroy(){p.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 K=null;function W(e,t){return K&&K.getWorkspaceId()===e||(K&&K.destroy(),K=new J(e,t)),K}"undefined"!=typeof window&&(window.clianta=W,window.Clianta={clianta:W,Tracker:J,CRMClient:j,ConsentManager:z,EventTriggersManager:B}),e.CRMClient=j,e.ConsentManager=z,e.EventTriggersManager=B,e.SDK_VERSION=t,e.Tracker=J,e.clianta=W,e.default=W,Object.defineProperty(e,"__esModule",{value:!0})});
|
|
7
7
|
//# sourceMappingURL=clianta.umd.min.js.map
|