@zaplier/sdk 1.8.2 → 1.8.4

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/dist/v2/core.d.ts CHANGED
@@ -1,7 +1,278 @@
1
+ /**
2
+ * Visitor-related types for SDK responses
3
+ */
4
+ /**
5
+ * Visitor information returned by getVisitorInfo()
6
+ */
7
+ interface VisitorInfo {
8
+ visitorId: string;
9
+ workspaceId: string;
10
+ location: {
11
+ country?: string;
12
+ countryCode?: string;
13
+ city?: string;
14
+ };
15
+ device: {
16
+ browser?: string;
17
+ os?: string;
18
+ deviceType?: string;
19
+ userAgent?: string;
20
+ };
21
+ stats: {
22
+ visitCount: number;
23
+ firstSeenAt: string;
24
+ lastSeenAt: string;
25
+ identificationScore?: number;
26
+ };
27
+ signals?: {
28
+ smartSignals?: any;
29
+ tlsFingerprint?: string | null;
30
+ cookieFingerprint?: string | null;
31
+ };
32
+ }
33
+ /**
34
+ * Visit history entry
35
+ */
36
+ interface VisitHistoryEntry {
37
+ id: string;
38
+ timestamp: string;
39
+ location: string | null;
40
+ country?: string | null;
41
+ countryCode?: string | null;
42
+ city?: string | null;
43
+ ip: string | null;
44
+ browser: string | null;
45
+ os: string | null;
46
+ deviceType: string | null;
47
+ isIncognito: boolean;
48
+ vpnDetected: boolean;
49
+ suspectScore: number;
50
+ }
51
+ /**
52
+ * Visitor history response
53
+ */
54
+ interface VisitorHistory {
55
+ visitorId: string;
56
+ visits: VisitHistoryEntry[];
57
+ summary: {
58
+ totalVisits: number;
59
+ uniqueIPs: number;
60
+ uniqueLocations: number;
61
+ incognitoSessions: number;
62
+ };
63
+ }
64
+ /**
65
+ * User data returned by getUserData()
66
+ */
67
+ interface UserData {
68
+ sessionId: string;
69
+ visitorId?: string;
70
+ userId?: string;
71
+ location: {
72
+ city?: string;
73
+ country?: string;
74
+ coordinates?: {
75
+ lat: number;
76
+ lng: number;
77
+ };
78
+ };
79
+ device: {
80
+ userAgent: string;
81
+ language: string;
82
+ screen: {
83
+ width: number;
84
+ height: number;
85
+ };
86
+ };
87
+ journey: any[];
88
+ fingerprint?: string;
89
+ }
90
+
91
+ /**
92
+ * SDK Configuration Types
93
+ *
94
+ * 100% Cookieless tracking using fingerprinting only.
95
+ * No storage dependencies - fully GDPR/LGPD compliant.
96
+ */
97
+ interface SDKConfig {
98
+ /** Workspace token (required) */
99
+ token: string;
100
+ /** Enable session replay recording (default: false) */
101
+ replay?: boolean;
102
+ /** Enable heatmap tracking (default: false) */
103
+ heatmap?: boolean;
104
+ /** Enable debug mode for development (default: false) */
105
+ debug?: boolean;
106
+ /** Allow tracking on localhost (default: false) */
107
+ allow_localhost?: boolean;
108
+ /** GDPR mode - limits invasive fingerprinting (default: false) */
109
+ gdprMode?: boolean;
110
+ }
111
+ /**
112
+ * Internal configuration with optimized defaults
113
+ * These settings are not exposed to the user but can be referenced internally
114
+ */
115
+ interface InternalConfig extends SDKConfig {
116
+ apiEndpoint: string;
117
+ retryEnabled: boolean;
118
+ maxRetries: number;
119
+ retryDelays: number[];
120
+ autoTrack: boolean;
121
+ dedupeEnabled: boolean;
122
+ fingerprintEnabled: boolean;
123
+ presenceTracking: boolean;
124
+ heartbeatInterval: number;
125
+ scrollTracking: boolean;
126
+ scrollDepthTracking: boolean;
127
+ gdprCompliant: boolean;
128
+ enhancedTracking: 'ask' | 'true' | 'false';
129
+ replaySampling: number;
130
+ replayMaskInputs: boolean;
131
+ }
132
+
133
+ /**
134
+ * Event and Tracking Types
135
+ */
136
+ interface BaseEventData {
137
+ eventType: string;
138
+ eventName?: string;
139
+ customData?: Record<string, any>;
140
+ }
141
+ interface PageViewEvent extends BaseEventData {
142
+ eventType: 'page_view';
143
+ url?: string;
144
+ pageTitle?: string;
145
+ referrer?: string;
146
+ spaNavigation?: boolean;
147
+ navigationType?: 'manual' | 'spa' | 'direct';
148
+ }
149
+
150
+ /**
151
+ * Method parameter types for SDK calls
152
+ */
153
+ /**
154
+ * Parameters for trackPurchase()
155
+ */
156
+ interface TrackPurchaseParams {
157
+ value?: number;
158
+ revenue?: number;
159
+ currency?: string;
160
+ quantity?: number;
161
+ productId?: string;
162
+ productName?: string;
163
+ orderId?: string;
164
+ customData?: Record<string, any>;
165
+ }
166
+ /**
167
+ * Parameters for trackAddToCart()
168
+ */
169
+ interface TrackAddToCartParams {
170
+ productId?: string;
171
+ productName?: string;
172
+ price?: number;
173
+ quantity?: number;
174
+ customData?: Record<string, any>;
175
+ }
176
+ /**
177
+ * Parameters for trackViewContent()
178
+ */
179
+ interface TrackViewContentParams {
180
+ productId?: string;
181
+ productName?: string;
182
+ category?: string;
183
+ customData?: Record<string, any>;
184
+ }
185
+ /**
186
+ * Parameters for trackInitiateCheckout()
187
+ */
188
+ interface TrackInitiateCheckoutParams {
189
+ value?: number;
190
+ currency?: string;
191
+ numItems?: number;
192
+ customData?: Record<string, any>;
193
+ }
194
+ /**
195
+ * Parameters for identify()
196
+ */
197
+ interface IdentifyParams {
198
+ email?: string;
199
+ phone?: string;
200
+ [key: string]: any;
201
+ }
202
+ /**
203
+ * Response from trackConversion()
204
+ */
205
+ interface ConversionLikelihoodResponse {
206
+ score: number;
207
+ factors: string[];
208
+ }
209
+ /**
210
+ * Response from getUserSegment()
211
+ */
212
+ interface UserSegmentResponse {
213
+ type: "high_intent" | "medium_intent" | "exploring";
214
+ confidence: number;
215
+ }
216
+
217
+ /**
218
+ * Main SDK interface
219
+ */
220
+ interface ZaplierSDK {
221
+ track(eventType: string, eventData?: Record<string, any>): void;
222
+ trackCustomEvent(eventName: string, metadata?: Record<string, any>): boolean;
223
+ trackConversion(eventName: string, value?: number, currency?: string, metadata?: Record<string, any>): boolean;
224
+ trackPageView(data?: Partial<PageViewEvent>): void;
225
+ trackPurchase(data: TrackPurchaseParams): void;
226
+ trackAddToCart(data?: TrackAddToCartParams): void;
227
+ trackViewContent(data?: TrackViewContentParams): void;
228
+ trackInitiateCheckout(data?: TrackInitiateCheckoutParams): void;
229
+ trackLead(data?: Record<string, any>): void;
230
+ identify(userData: IdentifyParams): void;
231
+ trackSPANavigation(url?: string, title?: string): void;
232
+ resetScrollTracking(): void;
233
+ startPresenceTracking(): void;
234
+ stopPresenceTracking(): void;
235
+ heatmap: {
236
+ enable(): void;
237
+ disable(): void;
238
+ };
239
+ replay: {
240
+ enable(): void;
241
+ disable(): void;
242
+ addFunnelStep(stepData: Record<string, any>): void;
243
+ markConversion(data: Record<string, any>): void;
244
+ };
245
+ enableEnhancedTracking(): boolean;
246
+ disableEnhancedTracking(): void;
247
+ isEnhancedMode(): boolean;
248
+ getVisitorId(): string | null;
249
+ getVisitorInfo(): Promise<VisitorInfo | null>;
250
+ getVisitorHistory(): Promise<VisitorHistory | null>;
251
+ getUserData(): UserData;
252
+ getConversionLikelihood(): ConversionLikelihoodResponse;
253
+ getUserSegment(): UserSegmentResponse;
254
+ config: InternalConfig;
255
+ version: string;
256
+ }
257
+ /**
258
+ * Global window interface extension
259
+ */
260
+ declare global {
261
+ interface Window {
262
+ Zaplier?: ZaplierSDK;
263
+ zaplier?: ZaplierSDK;
264
+ stalker?: {
265
+ config?: Partial<SDKConfig>;
266
+ q?: any[][];
267
+ } & ZaplierSDK;
268
+ }
269
+ }
270
+
1
271
  /**
2
272
  * Zaplier SDK Core v2.0.0 - Performance Optimized
3
273
  * Minimal core for instant initialization with lazy loading
4
274
  */
275
+
5
276
  interface CoreConfig {
6
277
  token: string;
7
278
  debug?: boolean;
@@ -23,6 +294,8 @@ declare class ZaplierCore {
23
294
  private sessionId?;
24
295
  private visitorId?;
25
296
  private modules;
297
+ private backendVisitorId?;
298
+ private cachedVisitorInfo?;
26
299
  private readonly version;
27
300
  /** Cached dev environment flag, computed once at init time */
28
301
  private _isDev;
@@ -77,14 +350,17 @@ declare class ZaplierCore {
77
350
  */
78
351
  private generateTempVisitorId;
79
352
  /**
80
- * Get visitor info (for compatibility)
353
+ * Get the visitor ID (backend UUID if available, otherwise temp ID)
81
354
  */
82
- getVisitorInfo(): {
83
- visitorId: string | undefined;
84
- sessionId: string | undefined;
85
- isReady: boolean;
86
- hasFingerprint: boolean;
87
- };
355
+ getVisitorId(): string | null;
356
+ /**
357
+ * Get client-side user data synchronously (SSR-safe)
358
+ */
359
+ getUserData(): UserData;
360
+ /**
361
+ * Get full visitor info from backend (async, only fetches when backend UUID is available)
362
+ */
363
+ getVisitorInfo(): Promise<VisitorInfo | null>;
88
364
  }
89
365
  /**
90
366
  * Factory function for easy initialization
@@ -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){if(this.eventQueue=[],this.isInitialized=!1,this.modules=new Map,this.version="2.0.0",this.t=!1,!e.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 e.token||e.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");this.config={deferAdvanced:!0,loadTimeout:5e3,debug:!1,...e},this.t=this.isDevEnvironment(),this.initializeCore()}isDevEnvironment(){if("undefined"==typeof window)return!1;const e=window.location.hostname;return"localhost"===e||"127.0.0.1"===e||"[::1]"===e||e.endsWith(".local")||e.endsWith(".test")||!0===this.config.debug}initializeCore(){try{this.config.debug&&this.version,this.sessionId=this.generateTempSessionId(),this.visitorId=this.generateTempVisitorId(),this.isInitialized=!0,this.processEventQueue(),this.config.debug,this.config.deferAdvanced||this.scheduleAdvancedLoading()}catch(e){console.error("[Zaplier Core] Initialization failed:",e)}}trackPageView(e={}){this.config.debug;const t={eventType:"page_view",eventName:"page_view",sessionId:this.sessionId,visitorId:this.visitorId,url:window.location.href,referrer:document.referrer,timestamp:(new Date).toISOString(),...e};this.sendEvent(t)}track(e,t={}){this.config.debug;const i={eventType:"custom",eventName:e,sessionId:this.sessionId,visitorId:this.visitorId,timestamp:(new Date).toISOString(),...t};this.sendEvent(i)}async enableAdvancedFeatures(){this.config.debug;try{await this.loadFingerprinting(),this.config.replay&&await this.loadReplayModule(),this.config.debug}catch(e){console.error("[Zaplier Core] Failed to load advanced features:",e)}}async loadFingerprinting(){if(!this.modules.has("fingerprint"))try{const{getCompleteFingerprint:e}=await import("./chunks/fingerprint-FfUEEIAd.min.js").then(function(e){return e.f}),t=await e();t.success&&t.data&&(this.visitorId=t.data.hash||this.visitorId,this.modules.set("fingerprint",t.data),this.config.debug)}catch(e){console.error("[Zaplier Core] Fingerprinting failed:",e)}}async loadReplayModule(){if(!this.modules.has("replay"))try{const{SessionReplayEngine:e}=await import("./chunks/session-replay-C5Tp0d16.min.js"),t=new e(this.sessionId,this.visitorId,{sampleRate:this.config.replaySampling||.1});t.start()&&(this.modules.set("replay",t),this.config.debug)}catch(e){console.error("[Zaplier Core] Replay loading failed:",e)}}scheduleAdvancedLoading(){((e,t=100)=>{"undefined"!=typeof requestIdleCallback?requestIdleCallback(e,{timeout:this.config.loadTimeout}):setTimeout(e,t)})(()=>this.enableAdvancedFeatures())}async sendEvent(e){try{const t={...e,isDev:this.t},i=await fetch(`${this.config.apiEndpoint||"https://api.zaplier.com"}/events?token=${encodeURIComponent(this.config.token)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0});this.config.debug&&!i.ok&&console.warn(`[Zaplier Core] Event sending failed: ${i.status}`)}catch(t){this.eventQueue.push(e),this.config.debug&&console.warn("[Zaplier Core] Event queued for retry:",t)}}processEventQueue(){if(0===this.eventQueue.length)return;const e=[...this.eventQueue];this.eventQueue=[],e.forEach(e=>this.sendEvent(e))}generateTempSessionId(){const e=new Date,t=e.getFullYear()+(e.getMonth()+1).toString().padStart(2,"0")+e.getDate().toString().padStart(2,"0"),i=e.getHours().toString().padStart(2,"0");return`temp_${Date.now()}_${t}_${i}`}generateTempVisitorId(){return`temp_visitor_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}getVisitorInfo(){return{visitorId:this.visitorId,sessionId:this.sessionId,isReady:this.isInitialized,hasFingerprint:this.modules.has("fingerprint")}}}function t(t){return new e(t)}if("undefined"!=typeof window){window.Zaplier={init:t,version:"2.0.0"};const e=()=>{const e=document.getElementsByTagName("script");for(const i of Array.from(e))if(i.src&&(i.src.includes("zaplier")||i.src.includes("core.min.js"))&&i.dataset.token){const e=t({token:i.dataset.token,debug:"true"===i.dataset.debug,replay:"true"===i.dataset.replay,deferAdvanced:"false"!==i.dataset.deferAdvanced});return window.Zaplier.instance=e,e.trackPageView(),void(e.config.deferAdvanced&&e.enableAdvancedFeatures())}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}export{e as ZaplierCore,e as default,t as initZaplierCore};
6
+ class e{constructor(e){if(this.eventQueue=[],this.isInitialized=!1,this.modules=new Map,this.version="2.0.0",this.t=!1,!e.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 e.token||e.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");this.config={deferAdvanced:!0,loadTimeout:5e3,debug:!1,...e},this.t=this.isDevEnvironment(),this.initializeCore()}isDevEnvironment(){if("undefined"==typeof window)return!1;const e=window.location.hostname;return"localhost"===e||"127.0.0.1"===e||"[::1]"===e||e.endsWith(".local")||e.endsWith(".test")||!0===this.config.debug}initializeCore(){try{this.config.debug&&this.version,this.sessionId=this.generateTempSessionId(),this.visitorId=this.generateTempVisitorId(),this.isInitialized=!0,this.processEventQueue(),this.config.debug,this.config.deferAdvanced||this.scheduleAdvancedLoading()}catch(e){console.error("[Zaplier Core] Initialization failed:",e)}}trackPageView(e={}){this.config.debug;const t={eventType:"page_view",eventName:"page_view",sessionId:this.sessionId,visitorId:this.visitorId,url:window.location.href,referrer:document.referrer,timestamp:(new Date).toISOString(),...e};this.sendEvent(t)}track(e,t={}){this.config.debug;const i={eventType:"custom",eventName:e,sessionId:this.sessionId,visitorId:this.visitorId,timestamp:(new Date).toISOString(),...t};this.sendEvent(i)}async enableAdvancedFeatures(){this.config.debug;try{await this.loadFingerprinting(),this.config.replay&&await this.loadReplayModule(),this.config.debug}catch(e){console.error("[Zaplier Core] Failed to load advanced features:",e)}}async loadFingerprinting(){if(!this.modules.has("fingerprint"))try{const{getCompleteFingerprint:e}=await import("./chunks/fingerprint-FfUEEIAd.min.js").then(function(e){return e.f}),t=await e();t.success&&t.data&&(this.visitorId=t.data.hash||this.visitorId,this.modules.set("fingerprint",t.data),this.config.debug)}catch(e){console.error("[Zaplier Core] Fingerprinting failed:",e)}}async loadReplayModule(){if(!this.modules.has("replay"))try{const{SessionReplayEngine:e}=await import("./chunks/session-replay-C5Tp0d16.min.js"),t=new e(this.sessionId,this.visitorId,{sampleRate:this.config.replaySampling||.1});t.start()&&(this.modules.set("replay",t),this.config.debug)}catch(e){console.error("[Zaplier Core] Replay loading failed:",e)}}scheduleAdvancedLoading(){((e,t=100)=>{"undefined"!=typeof requestIdleCallback?requestIdleCallback(e,{timeout:this.config.loadTimeout}):setTimeout(e,t)})(()=>this.enableAdvancedFeatures())}async sendEvent(e){try{const t={...e,isDev:this.t},i=await fetch(`${this.config.apiEndpoint||"https://api.zaplier.com"}/events?token=${encodeURIComponent(this.config.token)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0});if(this.config.debug&&!i.ok&&console.warn(`[Zaplier Core] Event sending failed: ${i.status}`),i.ok){const e=await i.json().catch(()=>null);(null==e?void 0:e.visitorId)&&(this.backendVisitorId=e.visitorId)}}catch(t){this.eventQueue.push(e),this.config.debug&&console.warn("[Zaplier Core] Event queued for retry:",t)}}processEventQueue(){if(0===this.eventQueue.length)return;const e=[...this.eventQueue];this.eventQueue=[],e.forEach(e=>this.sendEvent(e))}generateTempSessionId(){const e=new Date,t=e.getFullYear()+(e.getMonth()+1).toString().padStart(2,"0")+e.getDate().toString().padStart(2,"0"),i=e.getHours().toString().padStart(2,"0");return`temp_${Date.now()}_${t}_${i}`}generateTempVisitorId(){return`temp_visitor_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}getVisitorId(){var e,t;return null!==(t=null!==(e=this.backendVisitorId)&&void 0!==e?e:this.visitorId)&&void 0!==t?t:null}getUserData(){var e,t,i,n,s,o,r;const a="undefined"!=typeof navigator?{userAgent:navigator.userAgent,language:navigator.language,screen:{width:null!==(t=null===(e=window.screen)||void 0===e?void 0:e.width)&&void 0!==t?t:0,height:null!==(n=null===(i=window.screen)||void 0===i?void 0:i.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:a,journey:[],fingerprint:null===(r=this.modules.get("fingerprint"))||void 0===r?void 0:r.hash}}async getVisitorInfo(){var e;const t=this.backendVisitorId;if(!t)return this.config.debug&&console.warn("[Zaplier Core] 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=null!==(e=this.config.apiEndpoint)&&void 0!==e?e:"https://api.zaplier.com",n=await fetch(`${i}/tracking/visitor/${t}?token=${encodeURIComponent(this.config.token)}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!n.ok)return null;const s=await n.json();return this.cachedVisitorInfo=s,s}catch{return null}}}function t(t){return new e(t)}if("undefined"!=typeof window){window.Zaplier={init:t,version:"2.0.0"};const e=()=>{const e=document.getElementsByTagName("script");for(const i of Array.from(e))if(i.src&&(i.src.includes("zaplier")||i.src.includes("core.min.js"))&&i.dataset.token){const e=t({token:i.dataset.token,debug:"true"===i.dataset.debug,replay:"true"===i.dataset.replay,deferAdvanced:"false"!==i.dataset.deferAdvanced});return window.Zaplier.instance=e,e.trackPageView(),void(e.config.deferAdvanced&&e.enableAdvancedFeatures())}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}export{e as ZaplierCore,e as default,t as initZaplierCore};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaplier/sdk",
3
- "version": "1.8.2",
3
+ "version": "1.8.4",
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",