@zaplier/sdk 1.9.0 → 1.9.1

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.
@@ -0,0 +1,6 @@
1
+ /*!
2
+ * Zaplier SDK v3.0.0 - Unified SDK
3
+ * Advanced privacy-first tracking with code splitting
4
+ * (c) 2026 Zaplier Team
5
+ */
6
+ const t=new Set(["token","replay","heatmap","debug","allow_localhost","gdprMode","replaySampleRate"]);function i(t){return function(t){const i=new Date||new Date;return`${t}_${i.getFullYear()}${(i.getMonth()+1).toString().padStart(2,"0")}${i.getDate().toString().padStart(2,"0")}_${i.getHours().toString().padStart(2,"0")}`}(t)}const e={apiEndpoint:"https://api.zaplier.com",retryEnabled:!0,maxRetries:3,retryDelays:[1e3,2e3,4e3],autoTrack:!0,dedupeEnabled:!0,fingerprintEnabled:!0,presenceTracking:!1,heartbeatInterval:3e4,scrollTracking:!0,scrollDepthTracking:!0,gdprCompliant:!0,enhancedTracking:"ask",replaySampling:.1,replayMaskInputs:!0};class n{constructor(i){var n;if(this.version="1.9.1",this.isInitialized=!1,this.eventQueue=[],this.t=!1,!i.token)throw console.error('[Zaplier] Missing required "token" option. Get your token at https://app.zaplier.com/dashboard/keys'),new Error("Zaplier: token is required");if("string"!=typeof i.token||i.token.trim().length<5)throw console.error('[Zaplier] Invalid token format. Token should be a workspace API key (e.g., "ws_abc123...")'),new Error("Zaplier: invalid token format");for(const e of Object.keys(i))t.has(e)||console.warn(`[Zaplier] Unknown config option "${e}". Valid options: ${[...t].join(", ")}`);const s=["replay","heatmap","debug","allow_localhost","gdprMode"];for(const t of s){const e=i[t];void 0!==e&&"boolean"!=typeof e&&console.warn(`[Zaplier] "${t}" should be true or false, got: ${typeof e}`)}let o=i;if(void 0!==i.replaySampleRate){const t=i.replaySampleRate;("number"!=typeof t||t<0||t>1)&&(console.warn(`[Zaplier] "replaySampleRate" must be a number between 0 and 1, got: ${t}. Defaulting to 1.0.`),o={...i,replaySampleRate:1})}this.config={...e,...o,gdprMode:null!==(n=o.gdprMode)&&void 0!==n&&n},this.t=this.isDevEnvironment(),this.heatmap=this.createHeatmapProxy(),this.replay=this.createReplayProxy(),this.autoTrack=this.createAutoTrackProxy(),this.initializeCore()}initializeCore(){try{if(this.config.debug&&this.version,!this.config.allow_localhost&&this.isLocalhost())return void this.config.debug;this.sessionId=this.generateTempSessionId(),this.visitorId=this.generateTempVisitorId(),this.isInitialized=!0,this.processEventQueue(),this.config.debug,"undefined"!=typeof window&&this.scheduleModuleLoading()}catch(t){console.error("[Zaplier] Initialization failed:",t)}}scheduleModuleLoading(){const t=(t,i)=>{"undefined"!=typeof requestIdleCallback?requestIdleCallback(t,{timeout:i}):setTimeout(t,Math.min(i/10,200))};t(async()=>{try{await this.loadFingerprint(),this.config.debug}catch(t){this.config.debug&&console.error("[Zaplier] Deferred fingerprinting failed:",t)}},3e3),t(()=>{this.loadAntiAdblock(),this.config.debug},1e3),this.config.autoTrack&&t(()=>{this.loadAutoTracker(),this.config.debug},1500),this.config.replay&&t(async()=>{await this.loadReplayEngine(),this.config.debug},2e3),this.config.heatmap&&t(()=>{this.loadHeatmapEngine(),this.config.debug},2500)}async loadFingerprint(){if(!this.fingerprint)try{const{getCompleteFingerprint:t,getLightweightFingerprint:i}=await import("./fingerprint-C1MH_xUr.min.js").then(function(t){return t.f}),e=this.config.gdprMode?await i():await t();if(e.success&&e.data){this.fingerprint=e.data,e.data.incognitoDetection&&(this.fingerprint.incognitoDetection={...e.data.incognitoDetection,detectionTimestamp:Date.now(),sdkVersion:this.version});try{const{VisitorIdentityManager:t}=await import("./visitor-persistence-nXdSbDzp.min.js");this.visitorIdentityManager=new t;const i=await this.visitorIdentityManager.getOrCreateVisitorIdentity({fingerprintHash:e.data.hash,stableCoreHash:e.data.stableCoreHash,deviceFingerprint:e.data.stableCoreHash||e.data.hash,sessionId:this.sessionId,userAgent:navigator.userAgent,ipAddress:void 0});i.visitorId&&!i.pendingBackendResponse&&(this.visitorId=i.visitorId,this.backendVisitorId=i.visitorId),this.config.debug&&(this.visitorId,i.persistenceMethod,i.confidence,i.reused)}catch(t){this.config.debug&&console.error("[Zaplier] Visitor persistence loading failed:",t)}this.config.debug&&(e.collectedComponents,e.data.hash,e.data.stableCoreHash,this.config.gdprMode)}}catch(t){this.config.debug&&console.error("[Zaplier] Fingerprinting failed:",t),this.collectFallbackEntropy()}}collectFallbackEntropy(){try{const t=[navigator.userAgent||"",navigator.language||"",navigator.platform||"",screen.width||0,screen.height||0,screen.colorDepth||0,new Date(2024,0,1).getTimezoneOffset(),navigator.hardwareConcurrency||0,navigator.deviceMemory||0,navigator.maxTouchPoints||0,performance.timeOrigin||0,navigator.plugins?navigator.plugins.length:0].join("|");let i=0;for(let e=0;e<t.length;e++)i=(i<<5)-i+t.charCodeAt(e)&4294967295,i^=i>>>16;this.fingerprint||(this.fingerprint={}),this.fingerprint.fallbackEntropy=Math.abs(i).toString(36)}catch{}}async loadAntiAdblock(){if(!this.antiAdblockManager)try{const{AntiAdblockManager:t}=await import("./anti-adblock-B_7p9rSc.min.js");this.antiAdblockManager=new t(this.config.apiEndpoint,this.config.token,{enabled:!0,methods:["elysia-websocket","fetch"],fallbackDelay:100,maxRetries:2,debug:this.config.debug})}catch(t){this.config.debug&&console.error("[Zaplier] Anti-adblock loading failed:",t)}}async loadAutoTracker(){if(!this.i)try{const{AutoTracker:t}=await import("./auto-tracker-5ij0Y4C-.min.js");this.i=new t(this,{enabled:!0,trackClicks:!0,trackScrolls:!0,trackViews:!0,trackHovers:!0,trackForms:!0,debug:this.config.debug}),this.i.start()}catch(t){this.config.debug&&console.error("[Zaplier] Auto tracker loading failed:",t)}}shouldRecord(){var t,i;const e="__zp_rs";try{if("undefined"!=typeof window&&window.sessionStorage){const i=sessionStorage.getItem(e);if(null!==i)return"1"===i;const n=null!==(t=this.config.replaySampleRate)&&void 0!==t?t:1,s=Math.random()<n;return sessionStorage.setItem(e,s?"1":"0"),s}}catch{}const n=null!==(i=this.config.replaySampleRate)&&void 0!==i?i:1;return Math.random()<n}async fetchFeatureFlags(){try{const t=await this.makeRequest(`/sdk/features?token=${encodeURIComponent(this.config.token)}`,null,"GET");return{hasSessionReplay:!0===(null==t?void 0:t.hasSessionReplay),hasHeatmap:!0===(null==t?void 0:t.hasHeatmap)}}catch{return this.config.debug&&console.warn("[Zaplier] Feature flag fetch failed, assuming features enabled"),{hasSessionReplay:!0,hasHeatmap:!0}}}async loadReplayEngine(){if(!this.o)try{if(!(await this.fetchFeatureFlags()).hasSessionReplay)return;if(!this.shouldRecord())return void this.config.debug;this.sessionId||(this.sessionId=this.generateSessionId());const{SessionReplayEngine:t}=await import("./session-replay-DsIhuKDJ.min.js");this.o=new t(this.sessionId,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),this.o.start()}catch(t){this.config.debug&&console.error("[Zaplier] Replay loading failed:",t)}}async loadHeatmapEngine(){if(!this.h)try{if(!(await this.fetchFeatureFlags()).hasHeatmap)return void this.config.debug;this.sessionId||(this.sessionId=this.generateSessionId());const{HeatmapEngine:t}=await import("./heatmap-FZpkJ8Pr.min.js");this.h=new t(this.sessionId,{trackClicks:!0,trackScrollDepth:!0,trackRageClicks:!0,trackMouseMoves:!1,apiEndpoint:this.config.apiEndpoint,token:this.config.token}),this.antiAdblockManager&&this.h.setAntiAdblockManager(this.antiAdblockManager),this.h.start()}catch(t){this.config.debug&&console.error("[Zaplier] Heatmap loading failed:",t)}}createHeatmapProxy(){const t=this;return{enable(){t.config.heatmap=!0,!t.h&&t.isInitialized&&t.loadHeatmapEngine(),t.config.debug},disable(){t.config.heatmap=!1,t.h&&(t.h.stop(),t.h=void 0),t.config.debug},enableMouseTracking(){t.h?t.h.enableMouseTracking():t.loadHeatmapEngine().then(()=>{var i;null===(i=t.h)||void 0===i||i.enableMouseTracking()})},disableMouseTracking(){t.h&&t.h.disableMouseTracking()},getStats:()=>t.h?t.h.getStats():null,isRecording:()=>!!t.h&&t.h.isRecording()}}createReplayProxy(){const t=this;return{enable(){t.config.replay=!0,(!t.o&&t.isInitialized||t.o&&!t.o.isRecording())&&t.loadReplayEngineForced(),t.config.debug},disable(){t.config.replay=!1,t.o&&(t.o.stop(),t.o=void 0),t.config.debug},start:async()=>(!t.o&&t.isInitialized&&await t.loadReplayEngineForced(),!!t.o&&t.o.start()),stop(){t.o&&t.o.stop()},isRecording:()=>!!t.o&&t.o.isRecording(),getEventCount:()=>t.o?t.o.getEventCount():0,addFunnelStep(i){t.sendEvent({eventType:"funnel_step",eventName:"funnel_step",customData:i})},markConversion(i){t.trackConversion("funnel_conversion",i.value,i.currency,i)}}}createAutoTrackProxy(){const t=this;return{enable(){t.i?t.i.configure({enabled:!0}):t.loadAutoTracker(),t.config.debug},disable(){t.i&&(t.i.stop(),t.i=void 0),t.config.debug},configure(i){t.i&&t.i.configure(i),t.config.debug},refreshTracking(){t.i&&t.i.refreshTracking(),t.config.debug},getDiagnostics:()=>t.i?t.i.getDiagnostics():null,getStats:()=>t.i?t.i.getStats():null,isEnabled:()=>!!t.i}}async loadReplayEngineForced(){try{this.o&&(this.o.stop(),this.o=void 0),this.sessionId||(this.sessionId=this.generateSessionId());const{SessionReplayEngine:t}=await import("./session-replay-DsIhuKDJ.min.js");this.o=new t(this.sessionId,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),this.o.start()}catch(t){this.config.debug&&console.error("[Zaplier] Replay engine loading failed:",t)}}extractUTMParameters(){const t={};if("undefined"==typeof window||!window.location)return t;try{const i=new URLSearchParams(window.location.search),e=i.get("utm_source"),n=i.get("utm_medium"),s=i.get("utm_campaign"),o=i.get("utm_content"),a=i.get("utm_term"),r=i.get("fbclid"),h=i.get("gclid"),l=i.get("ttclid"),c=i.get("creative_id"),d=i.get("ad_id"),u=i.get("adset_id"),p=i.get("campaign_id"),v=i.get("platform");e&&(t.utmSource=e),n&&(t.utmMedium=n),s&&(t.utmCampaign=s),o&&(t.utmContent=o),a&&(t.utmTerm=a),r&&(t.fbclid=r),h&&(t.gclid=h),l&&(t.ttclid=l),c&&(t.creativeId=c),d&&(t.adId=d),u&&(t.adsetId=u),p&&(t.campaignId=p),v&&(t.platform=v),this.config.debug&&Object.keys(t).length}catch(t){this.config.debug&&console.warn("[Zaplier] Failed to extract UTM parameters:",t)}return t}async sendEvent(t){var e,n,s,o,a,r,h,l,c,d,u,p,v,f,g,w,m,y,k;if(!this.isInitialized)return this.eventQueue.length>=100&&this.eventQueue.shift(),void this.eventQueue.push(t);try{const k={visitorId:this.backendVisitorId||null,sessionId:this.sessionId,fingerprintHash:null===(e=this.fingerprint)||void 0===e?void 0:e.hash,stableCoreHash:null===(n=this.fingerprint)||void 0===n?void 0:n.stableCoreHash,stableCoreVector:null===(s=this.fingerprint)||void 0===s?void 0:s.stableCoreVector,fingerprintVector:this.fingerprint||void 0,incognitoDetection:(null===(o=this.fingerprint)||void 0===o?void 0:o.incognitoDetection)&&(void 0!==this.fingerprint.incognitoDetection.likelihood||this.fingerprint.incognitoDetection.methods&&this.fingerprint.incognitoDetection.methods.length>0)?this.fingerprint.incognitoDetection:void 0,fingerprintComponents:(null===(a=this.fingerprint)||void 0===a?void 0:a.components)||{},isSafari:"undefined"!=typeof navigator&&/safari/i.test(navigator.userAgent)&&!/chrome|chromium|opr|edg|edge/i.test(navigator.userAgent),ch:navigator.userAgentData?{brands:navigator.userAgentData.brands||[],platform:navigator.userAgentData.platform||void 0,mobile:navigator.userAgentData.mobile||void 0,model:navigator.userAgentData.model||void 0}:void 0,...this.extractUTMParameters(),...t,timestamp:(new Date).toISOString(),url:"undefined"!=typeof window&&window.location?window.location.href:"",referrer:"undefined"!=typeof document?document.referrer:"",pageTitle:"undefined"!=typeof document?document.title:"",userAgent:"undefined"!=typeof navigator?navigator.userAgent:"",screenWidth:(null===(l=null===(h=null===(r=this.fingerprint)||void 0===r?void 0:r.screen)||void 0===h?void 0:h.value)||void 0===l?void 0:l.width)||("undefined"!=typeof window&&window.screen?window.screen.width:0),screenHeight:(null===(u=null===(d=null===(c=this.fingerprint)||void 0===c?void 0:c.screen)||void 0===d?void 0:d.value)||void 0===u?void 0:u.height)||("undefined"!=typeof window&&window.screen?window.screen.height:0),viewportWidth:(null===(f=null===(v=null===(p=this.fingerprint)||void 0===p?void 0:p.screen)||void 0===v?void 0:v.value)||void 0===f?void 0:f.viewportWidth)||("undefined"!=typeof window?window.innerWidth:0),viewportHeight:(null===(m=null===(w=null===(g=this.fingerprint)||void 0===g?void 0:g.screen)||void 0===w?void 0:w.value)||void 0===m?void 0:m.viewportHeight)||("undefined"!=typeof window?window.innerHeight:0),gdprMode:this.config.gdprMode,isDev:this.t},b=await this.makeRequest(`/tracking/event?token=${encodeURIComponent(this.config.token)}`,k);if(b.visitorId){if(this.backendVisitorId=b.visitorId,this.visitorIdentityManager&&(null===(y=this.fingerprint)||void 0===y?void 0:y.stableCoreHash))try{await this.visitorIdentityManager.updateVisitorIdFromBackend(b.visitorId,this.fingerprint.stableCoreHash,this.sessionId)}catch(t){this.config.debug&&console.error("[Zaplier] Failed to save backend visitor ID to storage:",t)}this.config.debug&&b.visitorId}if(!b.sessionId||this.sessionId&&!this.sessionId.includes("temp_")){if(this.backendVisitorId&&(!this.sessionId||this.sessionId.includes("temp_"))){const t=this.sessionId;this.sessionId=i(this.backendVisitorId),t!==this.sessionId&&this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}}else{const t=this.sessionId;this.sessionId=b.sessionId,t!==this.sessionId&&this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}return b}catch(i){if(this.config.debug&&console.error("[Zaplier] Event sending failed:",i),this.config.retryEnabled){const i=t.l||0;if(i<this.config.maxRetries){const e=null!==(k=this.config.retryDelays[i])&&void 0!==k?k:5e3;setTimeout(()=>{this.sendEvent({...t,l:i+1})},e)}else this.config.debug&&console.warn("[Zaplier] Event dropped after max retries:",t.eventType)}}}async sendReplayBatch(t){var i;if(!this.isInitialized)return{success:!1,error:"SDK not initialized"};try{const e={sessionId:t.sessionId,userId:this.backendVisitorId,events:t.events,metadata:{...t.metadata,visitorId:this.backendVisitorId,fingerprintHash:null===(i=this.fingerprint)||void 0===i?void 0:i.hash}};this.config.debug&&(e.sessionId,e.events.length);const n=await this.makeRequest(`/replays/record?token=${encodeURIComponent(this.config.token)}`,e,"POST");if(n.sessionId&&n.sessionId!==this.sessionId){const t=this.sessionId;this.sessionId=n.sessionId,t!==this.sessionId&&this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}return n}catch(t){return this.config.debug&&console.error("[Zaplier] Replay batch sending failed:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async makeRequest(t,i,e="POST"){const n=`${this.config.apiEndpoint}${t}`,s={method:e,headers:{"Content-Type":"application/json"}};"POST"===e&&i&&(s.body=JSON.stringify(i),s.keepalive=!0);try{const t=Promise.race([fetch(n,s),new Promise((t,i)=>setTimeout(()=>i(new Error("Fetch timeout - possibly blocked")),5e3))]),i=await t;if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);return await i.json()}catch(n){if(this.antiAdblockManager&&"POST"===e){this.config.debug&&console.warn(`[Zaplier] Standard fetch failed (${n instanceof Error?n.message:String(n)}), trying anti-adblock fallback`);try{const e=await this.antiAdblockManager.send(i,t);if(e.success)return this.config.debug&&(e.method,e.latency),{success:!0,method:e.method}}catch(t){this.config.debug&&console.warn("[Zaplier] Both standard fetch and anti-adblock failed:",t)}}throw n}}updateTrackingEnginesSessionId(t){try{if(this.o){const i=this.o.isRecording();this.o.stop(),import("./session-replay-DsIhuKDJ.min.js").then(({SessionReplayEngine:e})=>{this.o=new e(t,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),i&&this.o.start()})}if(this.h){const i=this.h.isRecording();this.h.stop(),import("./heatmap-FZpkJ8Pr.min.js").then(({HeatmapEngine:e})=>{this.h=new e(t,{trackClicks:!0,trackScrollDepth:!0,trackRageClicks:!0,trackMouseMoves:!1,apiEndpoint:this.config.apiEndpoint,token:this.config.token}),this.antiAdblockManager&&this.h.setAntiAdblockManager(this.antiAdblockManager),i&&this.h.start()})}this.config.debug}catch(t){console.error("[Zaplier] Failed to update tracking engines session ID:",t)}}processEventQueue(){if(0===this.eventQueue.length)return;const t=[...this.eventQueue];this.eventQueue=[],t.forEach(t=>this.sendEvent(t))}isLocalhost(){return!("undefined"==typeof window||!window.location)&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname||window.location.hostname.startsWith("192.168.")||window.location.hostname.startsWith("10.")||window.location.hostname.includes("local"))}isDevEnvironment(){if("undefined"==typeof window)return!1;const t=window.location.hostname;return"localhost"===t||"127.0.0.1"===t||"[::1]"===t||t.endsWith(".local")||t.endsWith(".test")||!0===this.config.debug}generateTempSessionId(){const t=new Date,i=t.getFullYear()+(t.getMonth()+1).toString().padStart(2,"0")+t.getDate().toString().padStart(2,"0"),e=t.getHours().toString().padStart(2,"0");return`temp_${Date.now()}_${i}_${e}`}generateTempVisitorId(){return`temp_visitor_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}generateSessionId(){return this.backendVisitorId?i(this.backendVisitorId):i(this.visitorId||"temp-"+Date.now().toString(36))}track(t,i){this.sendEvent({eventType:t,eventName:t,customData:i})}trackCustomEvent(t,i){return this.sendEvent({eventType:"custom",eventName:t,customData:i}),!0}trackConversion(t,i,e,n){return this.sendEvent({eventType:"conversion",eventName:t,revenue:i,currency:e||"USD",customData:n}),!0}trackPageView(t){this.sendEvent({eventType:"page_view",eventName:"page_view",...t})}trackSPANavigation(t,i){this.trackPageView({url:t||("undefined"!=typeof window&&window.location?window.location.href:""),pageTitle:i||("undefined"!=typeof document?document.title:"")})}trackPurchase(t){this.sendEvent({eventType:"purchase",eventName:"purchase",revenue:t.value||t.revenue,currency:t.currency||"USD",quantity:t.quantity||1,productId:t.productId,customData:{productName:t.productName,orderId:t.orderId,...t.customData}})}trackAddToCart(t){this.sendEvent({eventType:"add_to_cart",eventName:"add_to_cart",revenue:null==t?void 0:t.price,quantity:(null==t?void 0:t.quantity)||1,productId:null==t?void 0:t.productId,customData:{productName:null==t?void 0:t.productName,...null==t?void 0:t.customData}})}trackViewContent(t){this.sendEvent({eventType:"view_content",eventName:"view_content",productId:null==t?void 0:t.productId,customData:{productName:null==t?void 0:t.productName,category:null==t?void 0:t.category,...null==t?void 0:t.customData}})}trackInitiateCheckout(t){this.sendEvent({eventType:"initiate_checkout",eventName:"initiate_checkout",revenue:null==t?void 0:t.value,currency:(null==t?void 0:t.currency)||"USD",quantity:null==t?void 0:t.numItems,customData:null==t?void 0:t.customData})}trackLead(t){this.sendEvent({eventType:"lead",eventName:"lead",customData:t})}identify(t){this.sendEvent({eventType:"identify",eventName:"identify",email:t.email,phone:t.phone,customData:t})}startPresenceTracking(){this.config.presenceTracking=!0,this.config.debug}stopPresenceTracking(){this.config.presenceTracking=!1,this.config.debug}enableAdvancedFeatures(){return this.loadFingerprint()}enableEnhancedTracking(){return this.config.enhancedTracking="true",this.config.gdprMode=!1,this.loadFingerprint(),this.config.debug,!0}disableEnhancedTracking(){this.config.enhancedTracking="false",this.config.gdprMode=!0,this.config.debug}isEnhancedMode(){return"true"===this.config.enhancedTracking&&!this.config.gdprMode}resetScrollTracking(){this.config.debug}getVisitorId(){if(this.backendVisitorId)return this.backendVisitorId;if(this.visitorId)return this.visitorId;if(this.visitorIdentityManager){const t=this.visitorIdentityManager.getCurrentVisitorId();if(t)return this.backendVisitorId=t,this.visitorId=t,t}return null}getUserData(){var t,i,e,n,s,o,a;const r="undefined"!=typeof navigator?{userAgent:navigator.userAgent,language:navigator.language,screen:{width:null!==(i=null===(t=window.screen)||void 0===t?void 0:t.width)&&void 0!==i?i:0,height:null!==(n=null===(e=window.screen)||void 0===e?void 0:e.height)&&void 0!==n?n:0}}:{userAgent:"",language:"",screen:{width:0,height:0}};return{sessionId:null!==(s=this.sessionId)&&void 0!==s?s:"",visitorId:null!==(o=this.getVisitorId())&&void 0!==o?o:void 0,location:{},device:r,journey:[],fingerprint:null===(a=this.fingerprint)||void 0===a?void 0:a.hash}}async getVisitorInfo(){const t=this.backendVisitorId;if(!t)return this.config.debug&&console.warn("[Zaplier] No backend visitor ID yet. Track an event first."),null;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return null;if(this.cachedVisitorInfo)return this.cachedVisitorInfo;try{const i=await this.makeRequest(`/tracking/visitor/${t}?token=${encodeURIComponent(this.config.token)}`,null,"GET");return this.cachedVisitorInfo=i,i}catch{return null}}async getVisitorHistory(){const t=this.backendVisitorId;if(!t)return this.config.debug&&console.warn("[Zaplier] No backend visitor ID available. Track an event first."),null;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return null;try{return await this.makeRequest(`/tracking/visitor/${t}/history?token=${encodeURIComponent(this.config.token)}`,null,"GET")}catch(t){return this.config.debug&&console.error("[Zaplier] Failed to get visitor history:",t),null}}getConversionLikelihood(){return{score:0,level:"unknown",factors:[]}}getUserSegment(){return{segment:"unknown",confidence:0,traits:[]}}}function s(t){return new n(t)}const o=s;if("undefined"!=typeof window){window.Zaplier={init:s,version:"1.9.1"};const t=()=>{const t=document.getElementsByTagName("script");for(const i of Array.from(t))if(i.src&&(i.src.includes("zaplier")||i.src.includes("core.min.js")||i.src.includes("sdk.min.js"))&&i.dataset.token){const t=s({token:i.dataset.token,debug:"true"===i.dataset.debug,replay:"true"===i.dataset.replay,heatmap:"true"===i.dataset.heatmap,gdprMode:"true"===i.dataset.gdprMode,allow_localhost:"true"===i.dataset.allowLocalhost});return window.Zaplier.instance=t,void t.trackPageView()}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}export{n as Z,o as a,i as g,s as i};
@@ -0,0 +1,6 @@
1
+ /*!
2
+ * Zaplier SDK v3.0.0 - Unified SDK
3
+ * Advanced privacy-first tracking with code splitting
4
+ * (c) 2026 Zaplier Team
5
+ */
6
+ const t=new Set(["token","replay","heatmap","debug","allow_localhost","gdprMode","replaySampleRate"]);function i(t){return function(t){const i=new Date||new Date;return`${t}_${i.getFullYear()}${(i.getMonth()+1).toString().padStart(2,"0")}${i.getDate().toString().padStart(2,"0")}_${i.getHours().toString().padStart(2,"0")}`}(t)}const e={apiEndpoint:"https://api.zaplier.com",retryEnabled:!0,maxRetries:3,retryDelays:[1e3,2e3,4e3],autoTrack:!0,dedupeEnabled:!0,fingerprintEnabled:!0,presenceTracking:!1,heartbeatInterval:3e4,scrollTracking:!0,scrollDepthTracking:!0,gdprCompliant:!0,enhancedTracking:"ask",replaySampling:.1,replayMaskInputs:!0};class n{constructor(i){var n;if(this.version="1.9.0",this.isInitialized=!1,this.eventQueue=[],this.t=!1,!i.token)throw console.error('[Zaplier] Missing required "token" option. Get your token at https://app.zaplier.com/dashboard/keys'),new Error("Zaplier: token is required");if("string"!=typeof i.token||i.token.trim().length<5)throw console.error('[Zaplier] Invalid token format. Token should be a workspace API key (e.g., "ws_abc123...")'),new Error("Zaplier: invalid token format");for(const e of Object.keys(i))t.has(e)||console.warn(`[Zaplier] Unknown config option "${e}". Valid options: ${[...t].join(", ")}`);const s=["replay","heatmap","debug","allow_localhost","gdprMode"];for(const t of s){const e=i[t];void 0!==e&&"boolean"!=typeof e&&console.warn(`[Zaplier] "${t}" should be true or false, got: ${typeof e}`)}let o=i;if(void 0!==i.replaySampleRate){const t=i.replaySampleRate;("number"!=typeof t||t<0||t>1)&&(console.warn(`[Zaplier] "replaySampleRate" must be a number between 0 and 1, got: ${t}. Defaulting to 1.0.`),o={...i,replaySampleRate:1})}this.config={...e,...o,gdprMode:null!==(n=o.gdprMode)&&void 0!==n&&n},this.t=this.isDevEnvironment(),this.heatmap=this.createHeatmapProxy(),this.replay=this.createReplayProxy(),this.autoTrack=this.createAutoTrackProxy(),this.initializeCore()}initializeCore(){try{if(this.config.debug&&this.version,!this.config.allow_localhost&&this.isLocalhost())return void this.config.debug;this.sessionId=this.generateTempSessionId(),this.visitorId=this.generateTempVisitorId(),this.isInitialized=!0,this.processEventQueue(),this.config.debug,"undefined"!=typeof window&&this.scheduleModuleLoading()}catch(t){console.error("[Zaplier] Initialization failed:",t)}}scheduleModuleLoading(){const t=(t,i)=>{"undefined"!=typeof requestIdleCallback?requestIdleCallback(t,{timeout:i}):setTimeout(t,Math.min(i/10,200))};t(async()=>{try{await this.loadFingerprint(),this.config.debug}catch(t){this.config.debug&&console.error("[Zaplier] Deferred fingerprinting failed:",t)}},3e3),t(()=>{this.loadAntiAdblock(),this.config.debug},1e3),this.config.autoTrack&&t(()=>{this.loadAutoTracker(),this.config.debug},1500),this.config.replay&&t(async()=>{await this.loadReplayEngine(),this.config.debug},2e3),this.config.heatmap&&t(()=>{this.loadHeatmapEngine(),this.config.debug},2500)}async loadFingerprint(){if(!this.fingerprint)try{const{getCompleteFingerprint:t,getLightweightFingerprint:i}=await import("./fingerprint-C1MH_xUr.min.js").then(function(t){return t.f}),e=this.config.gdprMode?await i():await t();if(e.success&&e.data){this.fingerprint=e.data,e.data.incognitoDetection&&(this.fingerprint.incognitoDetection={...e.data.incognitoDetection,detectionTimestamp:Date.now(),sdkVersion:this.version});try{const{VisitorIdentityManager:t}=await import("./visitor-persistence-FU8S1BmX.min.js");this.visitorIdentityManager=new t;const i=await this.visitorIdentityManager.getOrCreateVisitorIdentity({fingerprintHash:e.data.hash,stableCoreHash:e.data.stableCoreHash,deviceFingerprint:e.data.stableCoreHash||e.data.hash,sessionId:this.sessionId,userAgent:navigator.userAgent,ipAddress:void 0});i.visitorId&&!i.pendingBackendResponse&&(this.visitorId=i.visitorId,this.backendVisitorId=i.visitorId),this.config.debug&&(this.visitorId,i.persistenceMethod,i.confidence,i.reused)}catch(t){this.config.debug&&console.error("[Zaplier] Visitor persistence loading failed:",t)}this.config.debug&&(e.collectedComponents,e.data.hash,e.data.stableCoreHash,this.config.gdprMode)}}catch(t){this.config.debug&&console.error("[Zaplier] Fingerprinting failed:",t),this.collectFallbackEntropy()}}collectFallbackEntropy(){try{const t=[navigator.userAgent||"",navigator.language||"",navigator.platform||"",screen.width||0,screen.height||0,screen.colorDepth||0,new Date(2024,0,1).getTimezoneOffset(),navigator.hardwareConcurrency||0,navigator.deviceMemory||0,navigator.maxTouchPoints||0,performance.timeOrigin||0,navigator.plugins?navigator.plugins.length:0].join("|");let i=0;for(let e=0;e<t.length;e++)i=(i<<5)-i+t.charCodeAt(e)&4294967295,i^=i>>>16;this.fingerprint||(this.fingerprint={}),this.fingerprint.fallbackEntropy=Math.abs(i).toString(36)}catch{}}async loadAntiAdblock(){if(!this.antiAdblockManager)try{const{AntiAdblockManager:t}=await import("./anti-adblock-B_7p9rSc.min.js");this.antiAdblockManager=new t(this.config.apiEndpoint,this.config.token,{enabled:!0,methods:["elysia-websocket","fetch"],fallbackDelay:100,maxRetries:2,debug:this.config.debug})}catch(t){this.config.debug&&console.error("[Zaplier] Anti-adblock loading failed:",t)}}async loadAutoTracker(){if(!this.i)try{const{AutoTracker:t}=await import("./auto-tracker-5ij0Y4C-.min.js");this.i=new t(this,{enabled:!0,trackClicks:!0,trackScrolls:!0,trackViews:!0,trackHovers:!0,trackForms:!0,debug:this.config.debug}),this.i.start()}catch(t){this.config.debug&&console.error("[Zaplier] Auto tracker loading failed:",t)}}shouldRecord(){var t,i;const e="__zp_rs";try{if("undefined"!=typeof window&&window.sessionStorage){const i=sessionStorage.getItem(e);if(null!==i)return"1"===i;const n=null!==(t=this.config.replaySampleRate)&&void 0!==t?t:1,s=Math.random()<n;return sessionStorage.setItem(e,s?"1":"0"),s}}catch{}const n=null!==(i=this.config.replaySampleRate)&&void 0!==i?i:1;return Math.random()<n}async fetchFeatureFlags(){try{const t=await this.makeRequest(`/sdk/features?token=${encodeURIComponent(this.config.token)}`,null,"GET");return{hasSessionReplay:!0===(null==t?void 0:t.hasSessionReplay),hasHeatmap:!0===(null==t?void 0:t.hasHeatmap)}}catch{return this.config.debug&&console.warn("[Zaplier] Feature flag fetch failed, assuming features enabled"),{hasSessionReplay:!0,hasHeatmap:!0}}}async loadReplayEngine(){if(!this.o)try{if(!(await this.fetchFeatureFlags()).hasSessionReplay)return;if(!this.shouldRecord())return void this.config.debug;this.sessionId||(this.sessionId=this.generateSessionId());const{SessionReplayEngine:t}=await import("./session-replay-DsIhuKDJ.min.js");this.o=new t(this.sessionId,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),this.o.start()}catch(t){this.config.debug&&console.error("[Zaplier] Replay loading failed:",t)}}async loadHeatmapEngine(){if(!this.h)try{if(!(await this.fetchFeatureFlags()).hasHeatmap)return void this.config.debug;this.sessionId||(this.sessionId=this.generateSessionId());const{HeatmapEngine:t}=await import("./heatmap-FZpkJ8Pr.min.js");this.h=new t(this.sessionId,{trackClicks:!0,trackScrollDepth:!0,trackRageClicks:!0,trackMouseMoves:!1,apiEndpoint:this.config.apiEndpoint,token:this.config.token}),this.antiAdblockManager&&this.h.setAntiAdblockManager(this.antiAdblockManager),this.h.start()}catch(t){this.config.debug&&console.error("[Zaplier] Heatmap loading failed:",t)}}createHeatmapProxy(){const t=this;return{enable(){t.config.heatmap=!0,!t.h&&t.isInitialized&&t.loadHeatmapEngine(),t.config.debug},disable(){t.config.heatmap=!1,t.h&&(t.h.stop(),t.h=void 0),t.config.debug},enableMouseTracking(){t.h?t.h.enableMouseTracking():t.loadHeatmapEngine().then(()=>{var i;null===(i=t.h)||void 0===i||i.enableMouseTracking()})},disableMouseTracking(){t.h&&t.h.disableMouseTracking()},getStats:()=>t.h?t.h.getStats():null,isRecording:()=>!!t.h&&t.h.isRecording()}}createReplayProxy(){const t=this;return{enable(){t.config.replay=!0,(!t.o&&t.isInitialized||t.o&&!t.o.isRecording())&&t.loadReplayEngineForced(),t.config.debug},disable(){t.config.replay=!1,t.o&&(t.o.stop(),t.o=void 0),t.config.debug},start:async()=>(!t.o&&t.isInitialized&&await t.loadReplayEngineForced(),!!t.o&&t.o.start()),stop(){t.o&&t.o.stop()},isRecording:()=>!!t.o&&t.o.isRecording(),getEventCount:()=>t.o?t.o.getEventCount():0,addFunnelStep(i){t.sendEvent({eventType:"funnel_step",eventName:"funnel_step",customData:i})},markConversion(i){t.trackConversion("funnel_conversion",i.value,i.currency,i)}}}createAutoTrackProxy(){const t=this;return{enable(){t.i?t.i.configure({enabled:!0}):t.loadAutoTracker(),t.config.debug},disable(){t.i&&(t.i.stop(),t.i=void 0),t.config.debug},configure(i){t.i&&t.i.configure(i),t.config.debug},refreshTracking(){t.i&&t.i.refreshTracking(),t.config.debug},getDiagnostics:()=>t.i?t.i.getDiagnostics():null,getStats:()=>t.i?t.i.getStats():null,isEnabled:()=>!!t.i}}async loadReplayEngineForced(){try{this.o&&(this.o.stop(),this.o=void 0),this.sessionId||(this.sessionId=this.generateSessionId());const{SessionReplayEngine:t}=await import("./session-replay-DsIhuKDJ.min.js");this.o=new t(this.sessionId,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),this.o.start()}catch(t){this.config.debug&&console.error("[Zaplier] Replay engine loading failed:",t)}}extractUTMParameters(){const t={};if("undefined"==typeof window||!window.location)return t;try{const i=new URLSearchParams(window.location.search),e=i.get("utm_source"),n=i.get("utm_medium"),s=i.get("utm_campaign"),o=i.get("utm_content"),a=i.get("utm_term"),r=i.get("fbclid"),h=i.get("gclid"),l=i.get("ttclid"),c=i.get("creative_id"),d=i.get("ad_id"),u=i.get("adset_id"),p=i.get("campaign_id"),v=i.get("platform");e&&(t.utmSource=e),n&&(t.utmMedium=n),s&&(t.utmCampaign=s),o&&(t.utmContent=o),a&&(t.utmTerm=a),r&&(t.fbclid=r),h&&(t.gclid=h),l&&(t.ttclid=l),c&&(t.creativeId=c),d&&(t.adId=d),u&&(t.adsetId=u),p&&(t.campaignId=p),v&&(t.platform=v),this.config.debug&&Object.keys(t).length}catch(t){this.config.debug&&console.warn("[Zaplier] Failed to extract UTM parameters:",t)}return t}async sendEvent(t){var e,n,s,o,a,r,h,l,c,d,u,p,v,f,g,w,m,y,k;if(!this.isInitialized)return this.eventQueue.length>=100&&this.eventQueue.shift(),void this.eventQueue.push(t);try{const k={visitorId:this.backendVisitorId||null,sessionId:this.sessionId,fingerprintHash:null===(e=this.fingerprint)||void 0===e?void 0:e.hash,stableCoreHash:null===(n=this.fingerprint)||void 0===n?void 0:n.stableCoreHash,stableCoreVector:null===(s=this.fingerprint)||void 0===s?void 0:s.stableCoreVector,fingerprintVector:this.fingerprint||void 0,incognitoDetection:(null===(o=this.fingerprint)||void 0===o?void 0:o.incognitoDetection)&&(void 0!==this.fingerprint.incognitoDetection.likelihood||this.fingerprint.incognitoDetection.methods&&this.fingerprint.incognitoDetection.methods.length>0)?this.fingerprint.incognitoDetection:void 0,fingerprintComponents:(null===(a=this.fingerprint)||void 0===a?void 0:a.components)||{},isSafari:"undefined"!=typeof navigator&&/safari/i.test(navigator.userAgent)&&!/chrome|chromium|opr|edg|edge/i.test(navigator.userAgent),ch:navigator.userAgentData?{brands:navigator.userAgentData.brands||[],platform:navigator.userAgentData.platform||void 0,mobile:navigator.userAgentData.mobile||void 0,model:navigator.userAgentData.model||void 0}:void 0,...this.extractUTMParameters(),...t,timestamp:(new Date).toISOString(),url:"undefined"!=typeof window&&window.location?window.location.href:"",referrer:"undefined"!=typeof document?document.referrer:"",pageTitle:"undefined"!=typeof document?document.title:"",userAgent:"undefined"!=typeof navigator?navigator.userAgent:"",screenWidth:(null===(l=null===(h=null===(r=this.fingerprint)||void 0===r?void 0:r.screen)||void 0===h?void 0:h.value)||void 0===l?void 0:l.width)||("undefined"!=typeof window&&window.screen?window.screen.width:0),screenHeight:(null===(u=null===(d=null===(c=this.fingerprint)||void 0===c?void 0:c.screen)||void 0===d?void 0:d.value)||void 0===u?void 0:u.height)||("undefined"!=typeof window&&window.screen?window.screen.height:0),viewportWidth:(null===(f=null===(v=null===(p=this.fingerprint)||void 0===p?void 0:p.screen)||void 0===v?void 0:v.value)||void 0===f?void 0:f.viewportWidth)||("undefined"!=typeof window?window.innerWidth:0),viewportHeight:(null===(m=null===(w=null===(g=this.fingerprint)||void 0===g?void 0:g.screen)||void 0===w?void 0:w.value)||void 0===m?void 0:m.viewportHeight)||("undefined"!=typeof window?window.innerHeight:0),gdprMode:this.config.gdprMode,isDev:this.t},b=await this.makeRequest(`/tracking/event?token=${encodeURIComponent(this.config.token)}`,k);if(b.visitorId){if(this.backendVisitorId=b.visitorId,this.visitorIdentityManager&&(null===(y=this.fingerprint)||void 0===y?void 0:y.stableCoreHash))try{await this.visitorIdentityManager.updateVisitorIdFromBackend(b.visitorId,this.fingerprint.stableCoreHash,this.sessionId)}catch(t){this.config.debug&&console.error("[Zaplier] Failed to save backend visitor ID to storage:",t)}this.config.debug&&b.visitorId}if(!b.sessionId||this.sessionId&&!this.sessionId.includes("temp_")){if(this.backendVisitorId&&(!this.sessionId||this.sessionId.includes("temp_"))){const t=this.sessionId;this.sessionId=i(this.backendVisitorId),t!==this.sessionId&&this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}}else{const t=this.sessionId;this.sessionId=b.sessionId,t!==this.sessionId&&this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}return b}catch(i){if(this.config.debug&&console.error("[Zaplier] Event sending failed:",i),this.config.retryEnabled){const i=t.l||0;if(i<this.config.maxRetries){const e=null!==(k=this.config.retryDelays[i])&&void 0!==k?k:5e3;setTimeout(()=>{this.sendEvent({...t,l:i+1})},e)}else this.config.debug&&console.warn("[Zaplier] Event dropped after max retries:",t.eventType)}}}async sendReplayBatch(t){var i;if(!this.isInitialized)return{success:!1,error:"SDK not initialized"};try{const e={sessionId:t.sessionId,userId:this.backendVisitorId,events:t.events,metadata:{...t.metadata,visitorId:this.backendVisitorId,fingerprintHash:null===(i=this.fingerprint)||void 0===i?void 0:i.hash}};this.config.debug&&(e.sessionId,e.events.length);const n=await this.makeRequest(`/replays/record?token=${encodeURIComponent(this.config.token)}`,e,"POST");if(n.sessionId&&n.sessionId!==this.sessionId){const t=this.sessionId;this.sessionId=n.sessionId,t!==this.sessionId&&this.sessionId&&this.updateTrackingEnginesSessionId(this.sessionId)}return n}catch(t){return this.config.debug&&console.error("[Zaplier] Replay batch sending failed:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async makeRequest(t,i,e="POST"){const n=`${this.config.apiEndpoint}${t}`,s={method:e,headers:{"Content-Type":"application/json"}};"POST"===e&&i&&(s.body=JSON.stringify(i),s.keepalive=!0);try{const t=Promise.race([fetch(n,s),new Promise((t,i)=>setTimeout(()=>i(new Error("Fetch timeout - possibly blocked")),5e3))]),i=await t;if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);return await i.json()}catch(n){if(this.antiAdblockManager&&"POST"===e){this.config.debug&&console.warn(`[Zaplier] Standard fetch failed (${n instanceof Error?n.message:String(n)}), trying anti-adblock fallback`);try{const e=await this.antiAdblockManager.send(i,t);if(e.success)return this.config.debug&&(e.method,e.latency),{success:!0,method:e.method}}catch(t){this.config.debug&&console.warn("[Zaplier] Both standard fetch and anti-adblock failed:",t)}}throw n}}updateTrackingEnginesSessionId(t){try{if(this.o){const i=this.o.isRecording();this.o.stop(),import("./session-replay-DsIhuKDJ.min.js").then(({SessionReplayEngine:e})=>{this.o=new e(t,this.backendVisitorId||"unknown",{sampleRate:1,inactivityTimeout:3e4,pauseOnInactive:!0}),this.o.setSDKInstance(this),i&&this.o.start()})}if(this.h){const i=this.h.isRecording();this.h.stop(),import("./heatmap-FZpkJ8Pr.min.js").then(({HeatmapEngine:e})=>{this.h=new e(t,{trackClicks:!0,trackScrollDepth:!0,trackRageClicks:!0,trackMouseMoves:!1,apiEndpoint:this.config.apiEndpoint,token:this.config.token}),this.antiAdblockManager&&this.h.setAntiAdblockManager(this.antiAdblockManager),i&&this.h.start()})}this.config.debug}catch(t){console.error("[Zaplier] Failed to update tracking engines session ID:",t)}}processEventQueue(){if(0===this.eventQueue.length)return;const t=[...this.eventQueue];this.eventQueue=[],t.forEach(t=>this.sendEvent(t))}isLocalhost(){return!("undefined"==typeof window||!window.location)&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname||window.location.hostname.startsWith("192.168.")||window.location.hostname.startsWith("10.")||window.location.hostname.includes("local"))}isDevEnvironment(){if("undefined"==typeof window)return!1;const t=window.location.hostname;return"localhost"===t||"127.0.0.1"===t||"[::1]"===t||t.endsWith(".local")||t.endsWith(".test")||!0===this.config.debug}generateTempSessionId(){const t=new Date,i=t.getFullYear()+(t.getMonth()+1).toString().padStart(2,"0")+t.getDate().toString().padStart(2,"0"),e=t.getHours().toString().padStart(2,"0");return`temp_${Date.now()}_${i}_${e}`}generateTempVisitorId(){return`temp_visitor_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}generateSessionId(){return this.backendVisitorId?i(this.backendVisitorId):i(this.visitorId||"temp-"+Date.now().toString(36))}track(t,i){this.sendEvent({eventType:t,eventName:t,customData:i})}trackCustomEvent(t,i){return this.sendEvent({eventType:"custom",eventName:t,customData:i}),!0}trackConversion(t,i,e,n){return this.sendEvent({eventType:"conversion",eventName:t,revenue:i,currency:e||"USD",customData:n}),!0}trackPageView(t){this.sendEvent({eventType:"page_view",eventName:"page_view",...t})}trackSPANavigation(t,i){this.trackPageView({url:t||("undefined"!=typeof window&&window.location?window.location.href:""),pageTitle:i||("undefined"!=typeof document?document.title:"")})}trackPurchase(t){this.sendEvent({eventType:"purchase",eventName:"purchase",revenue:t.value||t.revenue,currency:t.currency||"USD",quantity:t.quantity||1,productId:t.productId,customData:{productName:t.productName,orderId:t.orderId,...t.customData}})}trackAddToCart(t){this.sendEvent({eventType:"add_to_cart",eventName:"add_to_cart",revenue:null==t?void 0:t.price,quantity:(null==t?void 0:t.quantity)||1,productId:null==t?void 0:t.productId,customData:{productName:null==t?void 0:t.productName,...null==t?void 0:t.customData}})}trackViewContent(t){this.sendEvent({eventType:"view_content",eventName:"view_content",productId:null==t?void 0:t.productId,customData:{productName:null==t?void 0:t.productName,category:null==t?void 0:t.category,...null==t?void 0:t.customData}})}trackInitiateCheckout(t){this.sendEvent({eventType:"initiate_checkout",eventName:"initiate_checkout",revenue:null==t?void 0:t.value,currency:(null==t?void 0:t.currency)||"USD",quantity:null==t?void 0:t.numItems,customData:null==t?void 0:t.customData})}trackLead(t){this.sendEvent({eventType:"lead",eventName:"lead",customData:t})}identify(t){this.sendEvent({eventType:"identify",eventName:"identify",email:t.email,phone:t.phone,customData:t})}startPresenceTracking(){this.config.presenceTracking=!0,this.config.debug}stopPresenceTracking(){this.config.presenceTracking=!1,this.config.debug}enableAdvancedFeatures(){return this.loadFingerprint()}enableEnhancedTracking(){return this.config.enhancedTracking="true",this.config.gdprMode=!1,this.loadFingerprint(),this.config.debug,!0}disableEnhancedTracking(){this.config.enhancedTracking="false",this.config.gdprMode=!0,this.config.debug}isEnhancedMode(){return"true"===this.config.enhancedTracking&&!this.config.gdprMode}resetScrollTracking(){this.config.debug}getVisitorId(){if(this.backendVisitorId)return this.backendVisitorId;if(this.visitorId)return this.visitorId;if(this.visitorIdentityManager){const t=this.visitorIdentityManager.getCurrentVisitorId();if(t)return this.backendVisitorId=t,this.visitorId=t,t}return null}getUserData(){var t,i,e,n,s,o,a;const r="undefined"!=typeof navigator?{userAgent:navigator.userAgent,language:navigator.language,screen:{width:null!==(i=null===(t=window.screen)||void 0===t?void 0:t.width)&&void 0!==i?i:0,height:null!==(n=null===(e=window.screen)||void 0===e?void 0:e.height)&&void 0!==n?n:0}}:{userAgent:"",language:"",screen:{width:0,height:0}};return{sessionId:null!==(s=this.sessionId)&&void 0!==s?s:"",visitorId:null!==(o=this.getVisitorId())&&void 0!==o?o:void 0,location:{},device:r,journey:[],fingerprint:null===(a=this.fingerprint)||void 0===a?void 0:a.hash}}async getVisitorInfo(){const t=this.backendVisitorId;if(!t)return this.config.debug&&console.warn("[Zaplier] No backend visitor ID yet. Track an event first."),null;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return null;if(this.cachedVisitorInfo)return this.cachedVisitorInfo;try{const i=await this.makeRequest(`/tracking/visitor/${t}?token=${encodeURIComponent(this.config.token)}`,null,"GET");return this.cachedVisitorInfo=i,i}catch{return null}}async getVisitorHistory(){const t=this.backendVisitorId;if(!t)return this.config.debug&&console.warn("[Zaplier] No backend visitor ID available. Track an event first."),null;if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))return null;try{return await this.makeRequest(`/tracking/visitor/${t}/history?token=${encodeURIComponent(this.config.token)}`,null,"GET")}catch(t){return this.config.debug&&console.error("[Zaplier] Failed to get visitor history:",t),null}}getConversionLikelihood(){return{score:0,level:"unknown",factors:[]}}getUserSegment(){return{segment:"unknown",confidence:0,traits:[]}}}function s(t){return new n(t)}const o=s;if("undefined"!=typeof window){window.Zaplier={init:s,version:"1.9.0"};const t=()=>{const t=document.getElementsByTagName("script");for(const i of Array.from(t))if(i.src&&(i.src.includes("zaplier")||i.src.includes("core.min.js")||i.src.includes("sdk.min.js"))&&i.dataset.token){const t=s({token:i.dataset.token,debug:"true"===i.dataset.debug,replay:"true"===i.dataset.replay,heatmap:"true"===i.dataset.heatmap,gdprMode:"true"===i.dataset.gdprMode,allow_localhost:"true"===i.dataset.allowLocalhost});return window.Zaplier.instance=t,void t.trackPageView()}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}export{n as Z,o as a,i as g,s as i};
@@ -0,0 +1,6 @@
1
+ /*!
2
+ * Zaplier SDK v3.0.0 - Unified SDK
3
+ * Advanced privacy-first tracking with code splitting
4
+ * (c) 2026 Zaplier Team
5
+ */
6
+ class t{constructor(t,i={}){this.clicks=[],this.scrollData=[],this.mouseMoves=[],this.lastMouseMove=0,this.maxScrollDepth=0,this.isActive=!1,this.recentClicks=[],this.handleClick=t=>{if(!this.config.trackClicks)return;const i=t.target;i.getBoundingClientRect();const s=window.pageXOffset||document.documentElement.scrollLeft,e=window.pageYOffset||document.documentElement.scrollTop,h={x:t.clientX,y:t.clientY,absoluteX:t.clientX+s,absoluteY:t.clientY+e,element:this.getElementSelector(i),timestamp:Date.now(),button:t.button};this.config.trackRageClicks&&this.detectRageClick(h.x,h.y,h.timestamp)&&(h.rageClick=!0),this.clicks.push(h),this.clicks.length>this.config.maxClickBuffer&&(this.clicks=this.clicks.slice(-this.config.maxClickBuffer))},this.handleScroll=()=>{if(!this.config.trackScrollDepth)return;const t=this.calculateScrollDepth();this.maxScrollDepth=Math.max(this.maxScrollDepth,t),this.scrollData.push({depth:t,maxDepth:this.maxScrollDepth,timestamp:Date.now(),viewport:{width:window.innerWidth,height:window.innerHeight}}),this.scrollData.length>100&&(this.scrollData=this.scrollData.slice(-50))},this.handleMouseMove=t=>{if(!this.config.trackMouseMoves)return;const i=Date.now();i-this.lastMouseMove<this.config.mouseMoveThrottle||(this.lastMouseMove=i,this.mouseMoves.push({x:t.clientX,y:t.clientY,timestamp:i}),this.mouseMoves.length>200&&(this.mouseMoves=this.mouseMoves.slice(-100)))},this.handleResize=()=>{const t=this.calculateScrollDepth();this.scrollData.push({depth:t,maxDepth:this.maxScrollDepth,timestamp:Date.now(),viewport:{width:window.innerWidth,height:window.innerHeight}})},this.sessionId=t,this.config={enabled:!0,trackClicks:!0,trackScrollDepth:!0,trackMouseMoves:!1,trackRageClicks:!0,mouseMoveThrottle:200,batchInterval:1e4,maxClickBuffer:500,rageClickThreshold:3,rageClickTimeWindow:1e3,...i}}start(){return!(!this.config.enabled||this.isActive||(this.isActive=!0,this.setupEventListeners(),this.startBatchTimer(),this.trackInitialViewport(),0))}stop(){if(this.isActive&&(this.isActive=!1,this.removeEventListeners(),this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0),this.clicks.length>0||this.scrollData.length>0||this.mouseMoves.length>0)){try{if("undefined"!=typeof navigator&&navigator.sendBeacon&&this.config.apiEndpoint&&this.config.token){const t=`${this.config.apiEndpoint}/heatmap/track?token=${encodeURIComponent(this.config.token)}`;let i;try{const t=new URL(window.location.href);i=t.origin+t.pathname}catch{i=window.location.href}const s=Math.max(document.body.scrollWidth,document.body.offsetWidth,document.documentElement.clientWidth,document.documentElement.scrollWidth,document.documentElement.offsetWidth),e=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight),h={sessionId:this.sessionId,pageMetadata:{url:window.location.href,normalizedUrl:i,width:s,height:e,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},documentSize:{width:s,height:e}},clicks:[...this.clicks],scrollData:[...this.scrollData],mouseMoves:this.config.trackMouseMoves?[...this.mouseMoves]:[],maxScrollDepth:this.maxScrollDepth,timestamp:Date.now()},o=new Blob([JSON.stringify(h)],{type:"application/json"});if(navigator.sendBeacon(t,o))return this.clicks=[],this.scrollData=[],void(this.mouseMoves=[])}}catch{}this.sendBatch()}}setupEventListeners(){this.config.trackClicks&&document.addEventListener("click",this.handleClick,!0),this.config.trackScrollDepth&&(window.addEventListener("scroll",this.handleScroll,{passive:!0}),document.addEventListener("scroll",this.handleScroll,{passive:!0})),this.config.trackMouseMoves&&document.addEventListener("mousemove",this.handleMouseMove,{passive:!0}),window.addEventListener("resize",this.handleResize),window.addEventListener("orientationchange",this.handleResize)}removeEventListeners(){document.removeEventListener("click",this.handleClick,!0),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("scroll",this.handleScroll),document.removeEventListener("mousemove",this.handleMouseMove),window.removeEventListener("resize",this.handleResize),window.removeEventListener("orientationchange",this.handleResize)}trackInitialViewport(){const t=this.calculateScrollDepth();this.scrollData.push({depth:t,maxDepth:t,timestamp:Date.now(),viewport:{width:window.innerWidth,height:window.innerHeight}})}calculateScrollDepth(){const t=window.pageYOffset||document.documentElement.scrollTop,i=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight),s=window.innerHeight;return i<=s?100:Math.min(100,Math.round((t+s)/i*100))}detectRageClick(t,i,s){const e=this.config.rageClickTimeWindow;this.recentClicks=this.recentClicks.filter(t=>s-t.timestamp<=e);const h=this.recentClicks.filter(s=>Math.sqrt(Math.pow(s.x-t,2)+Math.pow(s.y-i,2))<=50);return this.recentClicks.push({x:t,y:i,timestamp:s}),h.length>=this.config.rageClickThreshold-1}getElementSelector(t){if(t.id)return`#${t.id}`;if(t.className&&"string"==typeof t.className){const i=t.className.split(" ").filter(t=>t.length>0);if(i.length>0)return`.${i.slice(0,2).join(".")}`}const i=t.tagName.toLowerCase();return t.parentElement?`${i}:nth-child(${Array.from(t.parentElement.children).indexOf(t)+1})`:i}startBatchTimer(){this.batchTimer=window.setInterval(()=>{this.sendBatch()},this.config.batchInterval)}sendBatch(){if(0===this.clicks.length&&0===this.scrollData.length&&0===this.mouseMoves.length)return;const t=Math.max(document.body.scrollWidth,document.body.offsetWidth,document.documentElement.clientWidth,document.documentElement.scrollWidth,document.documentElement.offsetWidth),i=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight);let s;try{const t=new URL(window.location.href);s=t.origin+t.pathname}catch{s=window.location.href}const e={sessionId:this.sessionId,pageMetadata:{url:window.location.href,normalizedUrl:s,width:t,height:i,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},documentSize:{width:t,height:i}},clicks:[...this.clicks],scrollData:[...this.scrollData],mouseMoves:this.config.trackMouseMoves?[...this.mouseMoves]:[],maxScrollDepth:this.maxScrollDepth,timestamp:Date.now()};this.clicks=[],this.scrollData=[],this.mouseMoves=[],this.sendToBackend(e)}setAntiAdblockManager(t){this.antiAdblockManager=t}async sendToBackend(t){try{if(this.antiAdblockManager&&(await this.antiAdblockManager.send(t,"/heatmap/track")).success)return;const i=this.config.apiEndpoint?`${this.config.apiEndpoint}/heatmap/track?token=${encodeURIComponent(this.config.token||"")}`:"/api/heatmap/track";(await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok||console.warn("[Zaplier] Heatmap batch failed to send")}catch(t){console.warn("[Zaplier] Heatmap error:",t)}}getStats(){const t=this.clicks.filter(t=>t.rageClick).length;return{clickCount:this.clicks.length,maxScrollDepth:this.maxScrollDepth,isRecording:this.isActive,mouseMovements:this.mouseMoves.length,rageClicks:t}}enableMouseTracking(){this.config.trackMouseMoves||(this.config.trackMouseMoves=!0,this.isActive&&document.addEventListener("mousemove",this.handleMouseMove,{passive:!0}))}disableMouseTracking(){this.config.trackMouseMoves&&(this.config.trackMouseMoves=!1,document.removeEventListener("mousemove",this.handleMouseMove),this.mouseMoves=[])}isRecording(){return this.isActive}}export{t as HeatmapEngine};
@@ -0,0 +1,6 @@
1
+ /*!
2
+ * Zaplier SDK v3.0.0 - Unified SDK
3
+ * Advanced privacy-first tracking with code splitting
4
+ * (c) 2026 Zaplier Team
5
+ */
6
+ import{g as e}from"./core-hqxwsWnO.min.js";const t={session:"__zp_s",visitor:"__zp_v",device:"__zp_d",prefs:"__zp_p",analytics:"__zp_a"};class n{static setLocal(e,t){try{if("undefined"!=typeof window&&window.localStorage)return localStorage.setItem(e,t),!0}catch(e){}return!1}static getLocal(e){try{if("undefined"!=typeof window&&window.localStorage)return localStorage.getItem(e)}catch(e){}return null}static setSession(e,t){try{if("undefined"!=typeof window&&window.sessionStorage)return sessionStorage.setItem(e,t),!0}catch(e){}return!1}static getSession(e){try{if("undefined"!=typeof window&&window.sessionStorage)return sessionStorage.getItem(e)}catch(e){}return null}static setCookie(e,t,n=365){try{if("undefined"!=typeof document){const s=new Date(Date.now()+24*n*60*60*1e3).toUTCString();return document.cookie=`${e}=${t}; expires=${s}; path=/; SameSite=Lax`,!0}}catch(e){}return!1}static getCookie(e){try{if("undefined"!=typeof document){const t=e+"=",n=decodeURIComponent(document.cookie).split(";");for(let e=0;e<n.length;e++){let s=n[e];if(s){for(;" "===s.charAt(0);)s=s.substring(1);if(0===s.indexOf(t))return s.substring(t.length,s.length)}}}}catch(e){}return null}static setMemory(e,t){return this.memoryStore.set(e,t),!0}static getMemory(e){return this.memoryStore.get(e)||null}static get(e){let t=this.getLocal(e);return t?{value:t,method:"localStorage"}:(t=this.getSession(e),t?{value:t,method:"sessionStorage"}:(t=this.getCookie(e),t?{value:t,method:"cookie"}:(t=this.getMemory(e),t?{value:t,method:"memory"}:{value:null,method:"none"})))}static set(e,t){return this.setLocal(e,t)?{success:!0,method:"localStorage"}:this.setSession(e,t)?{success:!0,method:"sessionStorage"}:this.setCookie(e,t)?{success:!0,method:"cookie"}:(this.setMemory(e,t),{success:!0,method:"memory"})}}n.memoryStore=new Map;class s{generateSessionId(){const{value:s}=n.get(t.prefs);if(s)try{const t=JSON.parse(s);if(t.t&&!0===t.o)return e(t.t)}catch(e){}const o="temp-"+Date.now().toString(36);return e(o)}createCamouflageData(e,t,n,s=!1){return{theme:"auto",lang:(navigator.language||"en-US").substring(0,2),tz:Intl.DateTimeFormat().resolvedOptions().timeZone,analytics:!0,cookies:!0,t:e,i:t,u:n,o:!!s||void 0,ts:Date.now()}}extractFromCamouflage(e){try{const t=JSON.parse(e);if(t.t&&t.i&&t.u&&!0===t.o)return{visitorId:t.t,sessionId:t.i,stableCoreHash:t.u,persistenceMethod:"localStorage",confidence:.95,createdAt:t.ts||Date.now(),lastSeen:Date.now(),reused:!0};if(t.t&&!t.o)return null}catch(e){}return null}async getOrCreateVisitorIdentity(e){const{stableCoreHash:s}=e,{value:o,method:r}=n.get(t.prefs);if(o){const e=this.extractFromCamouflage(o);if(e&&e.stableCoreHash===s&&e.visitorId){const o=this.createCamouflageData(e.visitorId,e.sessionId,s);return n.set(t.prefs,JSON.stringify(o)),{...e,persistenceMethod:r,lastSeen:Date.now(),reused:!0}}}return{sessionId:e.sessionId||this.generateSessionId(),stableCoreHash:s,deviceFingerprint:e.deviceFingerprint,persistenceMethod:"memory",confidence:.9,createdAt:Date.now(),lastSeen:Date.now(),reused:!1,pendingBackendResponse:!0}}async updateVisitorIdFromBackend(s,o,r){try{let i=r||this.getCurrentSessionId();i&&!i.includes("temp-")||(i=e(s));const a=this.createCamouflageData(s,i,o,!0),{success:c,method:u}=n.set(t.prefs,JSON.stringify(a));return!!c&&(n.set(t.device,o),!0)}catch(e){return console.error("[VisitorIdentityManager] Failed to update visitor ID from backend:",e),!1}}getCurrentSessionId(){const{value:e}=n.get(t.prefs);if(e){const t=this.extractFromCamouflage(e);return(null==t?void 0:t.sessionId)||null}return null}getCurrentVisitorId(){const{value:e}=n.get(t.prefs);if(e){const t=this.extractFromCamouflage(e);return(null==t?void 0:t.visitorId)||null}return null}clearIdentity(){try{for(const e of Object.values(t)){try{"undefined"!=typeof window&&window.localStorage&&localStorage.removeItem(e)}catch{}try{"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.removeItem(e)}catch{}}n.setCookie(t.prefs,"",-1),n.setCookie(t.device,"",-1)}catch(e){}}}export{s as VisitorIdentityManager};
@@ -0,0 +1,6 @@
1
+ /*!
2
+ * Zaplier SDK v3.0.0 - Unified SDK
3
+ * Advanced privacy-first tracking with code splitting
4
+ * (c) 2026 Zaplier Team
5
+ */
6
+ import{g as e}from"./core-BTl6GQvU.min.js";const t={session:"__zp_s",visitor:"__zp_v",device:"__zp_d",prefs:"__zp_p",analytics:"__zp_a"};class n{static setLocal(e,t){try{if("undefined"!=typeof window&&window.localStorage)return localStorage.setItem(e,t),!0}catch(e){}return!1}static getLocal(e){try{if("undefined"!=typeof window&&window.localStorage)return localStorage.getItem(e)}catch(e){}return null}static setSession(e,t){try{if("undefined"!=typeof window&&window.sessionStorage)return sessionStorage.setItem(e,t),!0}catch(e){}return!1}static getSession(e){try{if("undefined"!=typeof window&&window.sessionStorage)return sessionStorage.getItem(e)}catch(e){}return null}static setCookie(e,t,n=365){try{if("undefined"!=typeof document){const s=new Date(Date.now()+24*n*60*60*1e3).toUTCString();return document.cookie=`${e}=${t}; expires=${s}; path=/; SameSite=Lax`,!0}}catch(e){}return!1}static getCookie(e){try{if("undefined"!=typeof document){const t=e+"=",n=decodeURIComponent(document.cookie).split(";");for(let e=0;e<n.length;e++){let s=n[e];if(s){for(;" "===s.charAt(0);)s=s.substring(1);if(0===s.indexOf(t))return s.substring(t.length,s.length)}}}}catch(e){}return null}static setMemory(e,t){return this.memoryStore.set(e,t),!0}static getMemory(e){return this.memoryStore.get(e)||null}static get(e){let t=this.getLocal(e);return t?{value:t,method:"localStorage"}:(t=this.getSession(e),t?{value:t,method:"sessionStorage"}:(t=this.getCookie(e),t?{value:t,method:"cookie"}:(t=this.getMemory(e),t?{value:t,method:"memory"}:{value:null,method:"none"})))}static set(e,t){return this.setLocal(e,t)?{success:!0,method:"localStorage"}:this.setSession(e,t)?{success:!0,method:"sessionStorage"}:this.setCookie(e,t)?{success:!0,method:"cookie"}:(this.setMemory(e,t),{success:!0,method:"memory"})}}n.memoryStore=new Map;class s{generateSessionId(){const{value:s}=n.get(t.prefs);if(s)try{const t=JSON.parse(s);if(t.t&&!0===t.o)return e(t.t)}catch(e){}const o="temp-"+Date.now().toString(36);return e(o)}createCamouflageData(e,t,n,s=!1){return{theme:"auto",lang:(navigator.language||"en-US").substring(0,2),tz:Intl.DateTimeFormat().resolvedOptions().timeZone,analytics:!0,cookies:!0,t:e,i:t,u:n,o:!!s||void 0,ts:Date.now()}}extractFromCamouflage(e){try{const t=JSON.parse(e);if(t.t&&t.i&&t.u&&!0===t.o)return{visitorId:t.t,sessionId:t.i,stableCoreHash:t.u,persistenceMethod:"localStorage",confidence:.95,createdAt:t.ts||Date.now(),lastSeen:Date.now(),reused:!0};if(t.t&&!t.o)return null}catch(e){}return null}async getOrCreateVisitorIdentity(e){const{stableCoreHash:s}=e,{value:o,method:r}=n.get(t.prefs);if(o){const e=this.extractFromCamouflage(o);if(e&&e.stableCoreHash===s&&e.visitorId){const o=this.createCamouflageData(e.visitorId,e.sessionId,s);return n.set(t.prefs,JSON.stringify(o)),{...e,persistenceMethod:r,lastSeen:Date.now(),reused:!0}}}return{sessionId:e.sessionId||this.generateSessionId(),stableCoreHash:s,deviceFingerprint:e.deviceFingerprint,persistenceMethod:"memory",confidence:.9,createdAt:Date.now(),lastSeen:Date.now(),reused:!1,pendingBackendResponse:!0}}async updateVisitorIdFromBackend(s,o,r){try{let i=r||this.getCurrentSessionId();i&&!i.includes("temp-")||(i=e(s));const a=this.createCamouflageData(s,i,o,!0),{success:c,method:u}=n.set(t.prefs,JSON.stringify(a));return!!c&&(n.set(t.device,o),!0)}catch(e){return console.error("[VisitorIdentityManager] Failed to update visitor ID from backend:",e),!1}}getCurrentSessionId(){const{value:e}=n.get(t.prefs);if(e){const t=this.extractFromCamouflage(e);return(null==t?void 0:t.sessionId)||null}return null}getCurrentVisitorId(){const{value:e}=n.get(t.prefs);if(e){const t=this.extractFromCamouflage(e);return(null==t?void 0:t.visitorId)||null}return null}clearIdentity(){try{for(const e of Object.values(t)){try{"undefined"!=typeof window&&window.localStorage&&localStorage.removeItem(e)}catch{}try{"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.removeItem(e)}catch{}}n.setCookie(t.prefs,"",-1),n.setCookie(t.device,"",-1)}catch(e){}}}export{s as VisitorIdentityManager};
package/dist/v2/core.d.ts CHANGED
@@ -297,7 +297,7 @@ declare global {
297
297
 
298
298
  declare class ZaplierCore {
299
299
  config: InternalConfig;
300
- readonly version = "1.9.0";
300
+ readonly version = "1.9.1";
301
301
  private isInitialized;
302
302
  private eventQueue;
303
303
  private sessionId?;
@@ -3,4 +3,4 @@
3
3
  * Advanced privacy-first tracking with code splitting
4
4
  * (c) 2026 Zaplier Team
5
5
  */
6
- export{Z as ZaplierCore,Z as default,i as initZaplier,a as initZaplierCore}from"./chunks/core-zJiDcx4q.min.js";
6
+ export{Z as ZaplierCore,Z as default,i as initZaplier,a as initZaplierCore}from"./chunks/core-BTl6GQvU.min.js";
@@ -3,4 +3,4 @@
3
3
  * Advanced privacy-first tracking with code splitting
4
4
  * (c) 2026 Zaplier Team
5
5
  */
6
- class e{constructor(e,t={}){this.clicks=[],this.scrollData=[],this.mouseMoves=[],this.lastMouseMove=0,this.maxScrollDepth=0,this.isActive=!1,this.recentClicks=[],this.handleClick=e=>{if(!this.config.trackClicks)return;const t=e.target;t.getBoundingClientRect();const i=window.pageXOffset||document.documentElement.scrollLeft,s=window.pageYOffset||document.documentElement.scrollTop,o={x:e.clientX,y:e.clientY,absoluteX:e.clientX+i,absoluteY:e.clientY+s,element:this.getElementSelector(t),timestamp:Date.now(),button:e.button};this.config.trackRageClicks&&this.detectRageClick(o.x,o.y,o.timestamp)&&(o.rageClick=!0),this.clicks.push(o),this.clicks.length>this.config.maxClickBuffer&&(this.clicks=this.clicks.slice(-this.config.maxClickBuffer))},this.handleScroll=()=>{if(!this.config.trackScrollDepth)return;const e=this.calculateScrollDepth();this.maxScrollDepth=Math.max(this.maxScrollDepth,e),this.scrollData.push({depth:e,maxDepth:this.maxScrollDepth,timestamp:Date.now(),viewport:{width:window.innerWidth,height:window.innerHeight}}),this.scrollData.length>100&&(this.scrollData=this.scrollData.slice(-50))},this.handleMouseMove=e=>{if(!this.config.trackMouseMoves)return;const t=Date.now();t-this.lastMouseMove<this.config.mouseMoveThrottle||(this.lastMouseMove=t,this.mouseMoves.push({x:e.clientX,y:e.clientY,timestamp:t}),this.mouseMoves.length>200&&(this.mouseMoves=this.mouseMoves.slice(-100)))},this.handleResize=()=>{const e=this.calculateScrollDepth();this.scrollData.push({depth:e,maxDepth:this.maxScrollDepth,timestamp:Date.now(),viewport:{width:window.innerWidth,height:window.innerHeight}})},this.sessionId=e,this.config={enabled:!0,trackClicks:!0,trackScrollDepth:!0,trackMouseMoves:!1,trackRageClicks:!0,mouseMoveThrottle:200,batchInterval:1e4,maxClickBuffer:500,rageClickThreshold:3,rageClickTimeWindow:1e3,...t}}start(){return!(!this.config.enabled||this.isActive||(this.isActive=!0,this.setupEventListeners(),this.startBatchTimer(),this.trackInitialViewport(),0))}stop(){this.isActive&&(this.isActive=!1,this.removeEventListeners(),this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0),this.sendBatch())}setupEventListeners(){this.config.trackClicks&&document.addEventListener("click",this.handleClick,!0),this.config.trackScrollDepth&&(window.addEventListener("scroll",this.handleScroll,{passive:!0}),document.addEventListener("scroll",this.handleScroll,{passive:!0})),this.config.trackMouseMoves&&document.addEventListener("mousemove",this.handleMouseMove,{passive:!0}),window.addEventListener("resize",this.handleResize),window.addEventListener("orientationchange",this.handleResize)}removeEventListeners(){document.removeEventListener("click",this.handleClick,!0),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("scroll",this.handleScroll),document.removeEventListener("mousemove",this.handleMouseMove),window.removeEventListener("resize",this.handleResize),window.removeEventListener("orientationchange",this.handleResize)}trackInitialViewport(){const e=this.calculateScrollDepth();this.scrollData.push({depth:e,maxDepth:e,timestamp:Date.now(),viewport:{width:window.innerWidth,height:window.innerHeight}})}calculateScrollDepth(){const e=window.pageYOffset||document.documentElement.scrollTop,t=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight),i=window.innerHeight;return t<=i?100:Math.min(100,Math.round((e+i)/t*100))}detectRageClick(e,t,i){const s=this.config.rageClickTimeWindow;this.recentClicks=this.recentClicks.filter(e=>i-e.timestamp<=s);const o=this.recentClicks.filter(i=>Math.sqrt(Math.pow(i.x-e,2)+Math.pow(i.y-t,2))<=50);return this.recentClicks.push({x:e,y:t,timestamp:i}),o.length>=this.config.rageClickThreshold-1}getElementSelector(e){if(e.id)return`#${e.id}`;if(e.className&&"string"==typeof e.className){const t=e.className.split(" ").filter(e=>e.length>0);if(t.length>0)return`.${t.slice(0,2).join(".")}`}const t=e.tagName.toLowerCase();return e.parentElement?`${t}:nth-child(${Array.from(e.parentElement.children).indexOf(e)+1})`:t}startBatchTimer(){this.batchTimer=window.setInterval(()=>{this.sendBatch()},this.config.batchInterval)}sendBatch(){if(0===this.clicks.length&&0===this.scrollData.length&&0===this.mouseMoves.length)return;const e={sessionId:this.sessionId,pageMetadata:{url:window.location.href,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},documentSize:{width:Math.max(document.body.scrollWidth,document.body.offsetWidth,document.documentElement.clientWidth,document.documentElement.scrollWidth,document.documentElement.offsetWidth),height:Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight)}},clicks:[...this.clicks],scrollData:[...this.scrollData],mouseMoves:this.config.trackMouseMoves?[...this.mouseMoves]:[],maxScrollDepth:this.maxScrollDepth,timestamp:Date.now()};this.clicks=[],this.scrollData=[],this.mouseMoves=[],this.sendToBackend(e)}setAntiAdblockManager(e){this.antiAdblockManager=e}async sendToBackend(e){try{if(this.antiAdblockManager&&(await this.antiAdblockManager.send(e,"/api/heatmap/record")).success)return;(await fetch("/api/heatmap/track",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).ok}catch(e){}}getStats(){const e=this.clicks.filter(e=>e.rageClick).length;return{clickCount:this.clicks.length,maxScrollDepth:this.maxScrollDepth,isRecording:this.isActive,mouseMovements:this.mouseMoves.length,rageClicks:e}}enableMouseTracking(){this.config.trackMouseMoves||(this.config.trackMouseMoves=!0,this.isActive&&document.addEventListener("mousemove",this.handleMouseMove,{passive:!0}))}disableMouseTracking(){this.config.trackMouseMoves&&(this.config.trackMouseMoves=!1,document.removeEventListener("mousemove",this.handleMouseMove),this.mouseMoves=[])}isRecording(){return this.isActive}}export{e as HeatmapEngine};
6
+ class t{constructor(t,e={}){this.clicks=[],this.scrollData=[],this.mouseMoves=[],this.lastMouseMove=0,this.maxScrollDepth=0,this.isActive=!1,this.recentClicks=[],this.handleClick=t=>{if(!this.config.trackClicks)return;const e=t.target;e.getBoundingClientRect();const i=window.pageXOffset||document.documentElement.scrollLeft,s=window.pageYOffset||document.documentElement.scrollTop,o={x:t.clientX,y:t.clientY,absoluteX:t.clientX+i,absoluteY:t.clientY+s,element:this.getElementSelector(e),timestamp:Date.now(),button:t.button};this.config.trackRageClicks&&this.detectRageClick(o.x,o.y,o.timestamp)&&(o.rageClick=!0),this.clicks.push(o),this.clicks.length>this.config.maxClickBuffer&&(this.clicks=this.clicks.slice(-this.config.maxClickBuffer))},this.handleScroll=()=>{if(!this.config.trackScrollDepth)return;const t=this.calculateScrollDepth();this.maxScrollDepth=Math.max(this.maxScrollDepth,t),this.scrollData.push({depth:t,maxDepth:this.maxScrollDepth,timestamp:Date.now(),viewport:{width:window.innerWidth,height:window.innerHeight}}),this.scrollData.length>100&&(this.scrollData=this.scrollData.slice(-50))},this.handleMouseMove=t=>{if(!this.config.trackMouseMoves)return;const e=Date.now();e-this.lastMouseMove<this.config.mouseMoveThrottle||(this.lastMouseMove=e,this.mouseMoves.push({x:t.clientX,y:t.clientY,timestamp:e}),this.mouseMoves.length>200&&(this.mouseMoves=this.mouseMoves.slice(-100)))},this.handleResize=()=>{const t=this.calculateScrollDepth();this.scrollData.push({depth:t,maxDepth:this.maxScrollDepth,timestamp:Date.now(),viewport:{width:window.innerWidth,height:window.innerHeight}})},this.sessionId=t,this.config={enabled:!0,trackClicks:!0,trackScrollDepth:!0,trackMouseMoves:!1,trackRageClicks:!0,mouseMoveThrottle:200,batchInterval:1e4,maxClickBuffer:500,rageClickThreshold:3,rageClickTimeWindow:1e3,...e}}start(){return!(!this.config.enabled||this.isActive||(this.isActive=!0,this.setupEventListeners(),this.startBatchTimer(),this.trackInitialViewport(),0))}stop(){if(this.isActive&&(this.isActive=!1,this.removeEventListeners(),this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0),this.clicks.length>0||this.scrollData.length>0||this.mouseMoves.length>0)){try{if("undefined"!=typeof navigator&&navigator.sendBeacon&&this.config.apiEndpoint&&this.config.token){const t=`${this.config.apiEndpoint}/heatmap/track?token=${encodeURIComponent(this.config.token)}`;let e;try{const t=new URL(window.location.href);e=t.origin+t.pathname}catch{e=window.location.href}const i=Math.max(document.body.scrollWidth,document.body.offsetWidth,document.documentElement.clientWidth,document.documentElement.scrollWidth,document.documentElement.offsetWidth),s=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight),o={sessionId:this.sessionId,pageMetadata:{url:window.location.href,normalizedUrl:e,width:i,height:s,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},documentSize:{width:i,height:s}},clicks:[...this.clicks],scrollData:[...this.scrollData],mouseMoves:this.config.trackMouseMoves?[...this.mouseMoves]:[],maxScrollDepth:this.maxScrollDepth,timestamp:Date.now()},n=new Blob([JSON.stringify(o)],{type:"application/json"});if(navigator.sendBeacon(t,n))return this.clicks=[],this.scrollData=[],void(this.mouseMoves=[])}}catch{}this.sendBatch()}}setupEventListeners(){this.config.trackClicks&&document.addEventListener("click",this.handleClick,!0),this.config.trackScrollDepth&&(window.addEventListener("scroll",this.handleScroll,{passive:!0}),document.addEventListener("scroll",this.handleScroll,{passive:!0})),this.config.trackMouseMoves&&document.addEventListener("mousemove",this.handleMouseMove,{passive:!0}),window.addEventListener("resize",this.handleResize),window.addEventListener("orientationchange",this.handleResize)}removeEventListeners(){document.removeEventListener("click",this.handleClick,!0),window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("scroll",this.handleScroll),document.removeEventListener("mousemove",this.handleMouseMove),window.removeEventListener("resize",this.handleResize),window.removeEventListener("orientationchange",this.handleResize)}trackInitialViewport(){const t=this.calculateScrollDepth();this.scrollData.push({depth:t,maxDepth:t,timestamp:Date.now(),viewport:{width:window.innerWidth,height:window.innerHeight}})}calculateScrollDepth(){const t=window.pageYOffset||document.documentElement.scrollTop,e=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight),i=window.innerHeight;return e<=i?100:Math.min(100,Math.round((t+i)/e*100))}detectRageClick(t,e,i){const s=this.config.rageClickTimeWindow;this.recentClicks=this.recentClicks.filter(t=>i-t.timestamp<=s);const o=this.recentClicks.filter(i=>Math.sqrt(Math.pow(i.x-t,2)+Math.pow(i.y-e,2))<=50);return this.recentClicks.push({x:t,y:e,timestamp:i}),o.length>=this.config.rageClickThreshold-1}getElementSelector(t){if(t.id)return`#${t.id}`;if(t.className&&"string"==typeof t.className){const e=t.className.split(" ").filter(t=>t.length>0);if(e.length>0)return`.${e.slice(0,2).join(".")}`}const e=t.tagName.toLowerCase();return t.parentElement?`${e}:nth-child(${Array.from(t.parentElement.children).indexOf(t)+1})`:e}startBatchTimer(){this.batchTimer=window.setInterval(()=>{this.sendBatch()},this.config.batchInterval)}sendBatch(){if(0===this.clicks.length&&0===this.scrollData.length&&0===this.mouseMoves.length)return;const t=Math.max(document.body.scrollWidth,document.body.offsetWidth,document.documentElement.clientWidth,document.documentElement.scrollWidth,document.documentElement.offsetWidth),e=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight);let i;try{const t=new URL(window.location.href);i=t.origin+t.pathname}catch{i=window.location.href}const s={sessionId:this.sessionId,pageMetadata:{url:window.location.href,normalizedUrl:i,width:t,height:e,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},documentSize:{width:t,height:e}},clicks:[...this.clicks],scrollData:[...this.scrollData],mouseMoves:this.config.trackMouseMoves?[...this.mouseMoves]:[],maxScrollDepth:this.maxScrollDepth,timestamp:Date.now()};this.clicks=[],this.scrollData=[],this.mouseMoves=[],this.sendToBackend(s)}setAntiAdblockManager(t){this.antiAdblockManager=t}async sendToBackend(t){try{if(this.antiAdblockManager&&(await this.antiAdblockManager.send(t,"/heatmap/track")).success)return;const e=this.config.apiEndpoint?`${this.config.apiEndpoint}/heatmap/track?token=${encodeURIComponent(this.config.token||"")}`:"/api/heatmap/track";(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok}catch(t){}}getStats(){const t=this.clicks.filter(t=>t.rageClick).length;return{clickCount:this.clicks.length,maxScrollDepth:this.maxScrollDepth,isRecording:this.isActive,mouseMovements:this.mouseMoves.length,rageClicks:t}}enableMouseTracking(){this.config.trackMouseMoves||(this.config.trackMouseMoves=!0,this.isActive&&document.addEventListener("mousemove",this.handleMouseMove,{passive:!0}))}disableMouseTracking(){this.config.trackMouseMoves&&(this.config.trackMouseMoves=!1,document.removeEventListener("mousemove",this.handleMouseMove),this.mouseMoves=[])}isRecording(){return this.isActive}}export{t as HeatmapEngine};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaplier/sdk",
3
- "version": "1.9.0",
3
+ "version": "1.9.1",
4
4
  "description": "Advanced privacy-first tracking SDK with session replay, heatmaps, and anti-adblock technology",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",