datafast 1.0.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,432 @@
1
+ /**
2
+ * Storage adapter interface - implement this for your platform
3
+ */
4
+ interface StorageAdapter {
5
+ getItem(key: string): Promise<string | null>;
6
+ setItem(key: string, value: string): Promise<void>;
7
+ removeItem(key: string): Promise<void>;
8
+ }
9
+ /**
10
+ * Network status adapter interface - implement this for your platform
11
+ */
12
+ interface NetworkAdapter {
13
+ isConnected(): Promise<boolean>;
14
+ onConnectionChange?(callback: (isConnected: boolean) => void): () => void;
15
+ }
16
+ /**
17
+ * Platform information
18
+ */
19
+ type Platform = 'ios' | 'android' | 'web';
20
+ /**
21
+ * Configuration options for initializing the SDK
22
+ */
23
+ interface DataFastConfig {
24
+ /** Your DataFast app/website ID (required) */
25
+ appId: string;
26
+ /** App bundle identifier, e.g., "com.example.myapp" (required for mobile) */
27
+ domain: string;
28
+ /** Storage adapter for persisting visitor/session IDs */
29
+ storage: StorageAdapter;
30
+ /** Network adapter for checking connectivity */
31
+ network?: NetworkAdapter;
32
+ /** Platform: 'ios' | 'android' | 'web' */
33
+ platform: Platform;
34
+ /** App version string, e.g., "1.0.0" */
35
+ appVersion?: string;
36
+ /** Custom API endpoint (defaults to https://datafa.st/api/events) */
37
+ apiUrl?: string;
38
+ /** Enable debug logging */
39
+ debug?: boolean;
40
+ /** Flush interval in milliseconds for queued events (default: 30000) */
41
+ flushInterval?: number;
42
+ /** Maximum events to queue before forcing flush (default: 20) */
43
+ maxQueueSize?: number;
44
+ }
45
+ /**
46
+ * Viewport dimensions
47
+ */
48
+ interface Viewport {
49
+ width: number;
50
+ height: number;
51
+ }
52
+ /**
53
+ * Device information collected by the SDK
54
+ */
55
+ interface DeviceInfo {
56
+ platform: Platform;
57
+ osVersion: string;
58
+ deviceModel: string;
59
+ appVersion: string;
60
+ screenWidth: number;
61
+ screenHeight: number;
62
+ viewport: Viewport;
63
+ language: string;
64
+ timezone: string;
65
+ }
66
+ /**
67
+ * Base event payload sent to the API
68
+ */
69
+ interface BaseEventPayload {
70
+ websiteId: string;
71
+ domain: string;
72
+ visitorId: string;
73
+ sessionId: string;
74
+ href: string;
75
+ referrer: string | null;
76
+ type: EventType;
77
+ viewport: Viewport;
78
+ language: string;
79
+ timezone: string;
80
+ screenWidth: number;
81
+ screenHeight: number;
82
+ extraData?: Record<string, unknown>;
83
+ }
84
+ /**
85
+ * Event types supported by the API
86
+ */
87
+ type EventType = 'pageview' | 'custom' | 'identify' | 'payment' | 'external_link';
88
+ /**
89
+ * Custom event properties - max 10, keys max 64 chars, values max 255 chars
90
+ */
91
+ type CustomProperties = Record<string, string | number | boolean>;
92
+ /**
93
+ * User properties for identify calls
94
+ */
95
+ interface UserProperties {
96
+ user_id: string;
97
+ name?: string;
98
+ email?: string;
99
+ image?: string;
100
+ [key: string]: unknown;
101
+ }
102
+ /**
103
+ * Payment event data
104
+ */
105
+ interface PaymentData {
106
+ email: string;
107
+ amount?: number;
108
+ currency?: string;
109
+ }
110
+ /**
111
+ * Queued event with metadata
112
+ */
113
+ interface QueuedEvent {
114
+ id: string;
115
+ payload: BaseEventPayload;
116
+ timestamp: number;
117
+ retries: number;
118
+ }
119
+ /**
120
+ * Internal state of the SDK
121
+ */
122
+ interface SDKState {
123
+ initialized: boolean;
124
+ visitorId: string | null;
125
+ sessionId: string | null;
126
+ sessionStartTime: number | null;
127
+ lastScreenName: string | null;
128
+ config: DataFastConfig | null;
129
+ deviceInfo: DeviceInfo | null;
130
+ }
131
+
132
+ declare class DataFastClient {
133
+ private state;
134
+ private queue;
135
+ private logger;
136
+ /**
137
+ * Initialize the SDK with configuration
138
+ */
139
+ init(config: DataFastConfig): Promise<void>;
140
+ /**
141
+ * Track a screen view (equivalent to pageview)
142
+ */
143
+ trackScreen(screenName: string): Promise<void>;
144
+ /**
145
+ * Track a custom event
146
+ */
147
+ track(eventName: string, properties?: CustomProperties): Promise<void>;
148
+ /**
149
+ * Identify a user
150
+ */
151
+ identify(userId: string, properties?: Omit<UserProperties, 'user_id'>): Promise<void>;
152
+ /**
153
+ * Track a payment event
154
+ */
155
+ trackPayment(data: PaymentData): Promise<void>;
156
+ /**
157
+ * Track an external link click
158
+ */
159
+ trackExternalLink(url: string, text?: string): Promise<void>;
160
+ /**
161
+ * Flush all queued events immediately
162
+ */
163
+ flush(): Promise<void>;
164
+ /**
165
+ * Reset the session (start a new session)
166
+ */
167
+ resetSession(): Promise<void>;
168
+ /**
169
+ * Reset the visitor (new anonymous user)
170
+ */
171
+ reset(): Promise<void>;
172
+ /**
173
+ * Opt out of tracking
174
+ */
175
+ optOut(): Promise<void>;
176
+ /**
177
+ * Opt back into tracking
178
+ */
179
+ optIn(): Promise<void>;
180
+ /**
181
+ * Set device info (call this when device info becomes available)
182
+ */
183
+ setDeviceInfo(info: Partial<DeviceInfo>): void;
184
+ /**
185
+ * Get current visitor ID
186
+ */
187
+ getVisitorId(): string | null;
188
+ /**
189
+ * Get current session ID
190
+ */
191
+ getSessionId(): string | null;
192
+ /**
193
+ * Check if SDK is initialized and ready
194
+ */
195
+ isInitialized(): boolean;
196
+ /**
197
+ * Shutdown the SDK
198
+ */
199
+ shutdown(): Promise<void>;
200
+ private isReady;
201
+ private initVisitorId;
202
+ private initSessionId;
203
+ private buildBasePayload;
204
+ }
205
+ /**
206
+ * Get the singleton DataFast client instance
207
+ */
208
+ declare function getDataFastClient(): DataFastClient;
209
+ /**
210
+ * Create a new DataFast client (for cases where you need multiple instances)
211
+ */
212
+ declare function createDataFastClient(): DataFastClient;
213
+
214
+ declare class EventQueue {
215
+ private queue;
216
+ private storage;
217
+ private network?;
218
+ private apiUrl;
219
+ private userAgent;
220
+ private flushInterval;
221
+ private maxQueueSize;
222
+ private flushTimer;
223
+ private isFlushing;
224
+ private onFlushError?;
225
+ constructor(options: {
226
+ storage: StorageAdapter;
227
+ network?: NetworkAdapter;
228
+ apiUrl: string;
229
+ userAgent: string;
230
+ flushInterval?: number;
231
+ maxQueueSize?: number;
232
+ onFlushError?: (error: Error, event: QueuedEvent) => void;
233
+ });
234
+ /**
235
+ * Initialize the queue - load persisted events from storage
236
+ */
237
+ init(): Promise<void>;
238
+ /**
239
+ * Add an event to the queue
240
+ */
241
+ enqueue(payload: BaseEventPayload): Promise<void>;
242
+ /**
243
+ * Flush all queued events to the server
244
+ */
245
+ flush(): Promise<void>;
246
+ /**
247
+ * Send a single event to the API
248
+ */
249
+ private sendEvent;
250
+ /**
251
+ * Persist queue to storage
252
+ */
253
+ private persistQueue;
254
+ /**
255
+ * Start the periodic flush timer
256
+ */
257
+ private startFlushTimer;
258
+ /**
259
+ * Stop the flush timer and flush remaining events
260
+ */
261
+ shutdown(): Promise<void>;
262
+ /**
263
+ * Get current queue size
264
+ */
265
+ get size(): number;
266
+ /**
267
+ * Clear all queued events
268
+ */
269
+ clear(): Promise<void>;
270
+ }
271
+
272
+ /**
273
+ * Generate a UUID v4 for visitor ID
274
+ * Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx (36 chars)
275
+ */
276
+ declare function generateVisitorId(): string;
277
+ /**
278
+ * Generate a session ID
279
+ * Format: sxxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx (37 chars, starts with 's')
280
+ */
281
+ declare function generateSessionId(): string;
282
+ /**
283
+ * Validate visitor ID format (UUID v4)
284
+ */
285
+ declare function isValidVisitorId(id: string): boolean;
286
+ /**
287
+ * Validate session ID format (s + UUID v4)
288
+ */
289
+ declare function isValidSessionId(id: string): boolean;
290
+ /**
291
+ * Build the href for a screen view
292
+ * Format: datafast://platform/ScreenName
293
+ */
294
+ declare function buildScreenHref(platform: Platform, screenName: string): string;
295
+ /**
296
+ * Build User-Agent header for mobile SDK
297
+ * Format: DataFast/version (OS version; Device)
298
+ */
299
+ declare function buildUserAgent(sdkVersion: string, platform: Platform, osVersion: string, deviceModel: string): string;
300
+ /**
301
+ * Validate custom event name
302
+ * - Lowercase alphanumeric + underscore/hyphen
303
+ * - Max 64 characters
304
+ */
305
+ declare function isValidEventName(name: string): boolean;
306
+ /**
307
+ * Validate and sanitize custom properties
308
+ * - Max 10 properties
309
+ * - Property names: lowercase alphanumeric + underscore/hyphen, max 64 chars
310
+ * - Property values: max 255 chars
311
+ */
312
+ declare function sanitizeCustomProperties(properties: Record<string, unknown>): Record<string, string> | null;
313
+ /**
314
+ * Generate a unique event ID for queue management
315
+ */
316
+ declare function generateEventId(): string;
317
+ /**
318
+ * Check if session has expired (24 hours)
319
+ */
320
+ declare function isSessionExpired(sessionStartTime: number): boolean;
321
+ /**
322
+ * Simple logger that respects debug mode
323
+ */
324
+ declare function createLogger(debug: boolean): {
325
+ log: (...args: unknown[]) => void;
326
+ warn: (...args: unknown[]) => void;
327
+ error: (...args: unknown[]) => void;
328
+ };
329
+
330
+ /**
331
+ * Browser localStorage adapter for DataFast
332
+ */
333
+ declare function createLocalStorageAdapter(): StorageAdapter;
334
+ /**
335
+ * In-memory storage adapter (fallback when localStorage is not available)
336
+ */
337
+ declare function createMemoryStorageAdapter(): StorageAdapter;
338
+
339
+ /**
340
+ * Browser fetch-based network adapter for DataFast
341
+ */
342
+ declare function createFetchNetworkAdapter(): NetworkAdapter;
343
+
344
+ /**
345
+ * Get device info for web browsers
346
+ */
347
+ declare function getDeviceInfo(): Partial<DeviceInfo>;
348
+ /**
349
+ * Listen for viewport changes (resize events)
350
+ */
351
+ declare function onViewportChange(callback: (viewport: {
352
+ width: number;
353
+ height: number;
354
+ }) => void): () => void;
355
+
356
+ /**
357
+ * Simplified configuration for web apps
358
+ */
359
+ interface DataFastWebConfig {
360
+ /** Your DataFast website ID */
361
+ websiteId: string;
362
+ /** Domain (defaults to current hostname) */
363
+ domain?: string;
364
+ /** Custom API endpoint */
365
+ apiUrl?: string;
366
+ /** Enable debug logging */
367
+ debug?: boolean;
368
+ /** Flush interval in ms (default: 5000) */
369
+ flushInterval?: number;
370
+ /** Max queue size before flush (default: 10) */
371
+ maxQueueSize?: number;
372
+ }
373
+ /**
374
+ * Initialize DataFast for web apps
375
+ *
376
+ * This is the recommended way to use DataFast in browser environments.
377
+ * It automatically configures localStorage and fetch adapters and returns
378
+ * a client with trackPageview(), track(), identify(), trackPayment(), reset().
379
+ *
380
+ * Usage (matches docs):
381
+ * ```ts
382
+ * import { initDataFast } from 'datafast';
383
+ *
384
+ * const datafast = await initDataFast({
385
+ * websiteId: 'your-website-id',
386
+ * });
387
+ *
388
+ * datafast.trackPageview();
389
+ * datafast.track('button_click', { button: 'signup' });
390
+ * datafast.identify('user_123', { name: 'John' });
391
+ * ```
392
+ */
393
+ declare function initDataFast(config: DataFastWebConfig): Promise<DataFastWeb>;
394
+ /**
395
+ * Create a DataFast client with manual configuration
396
+ *
397
+ * Use this for more control over adapters or for non-standard setups.
398
+ *
399
+ * Usage:
400
+ * ```ts
401
+ * import {
402
+ * createDataFastWithAdapters,
403
+ * createLocalStorageAdapter,
404
+ * createFetchNetworkAdapter,
405
+ * } from 'datafast/web';
406
+ *
407
+ * const datafast = await createDataFastWithAdapters({
408
+ * appId: 'your-website-id',
409
+ * domain: 'example.com',
410
+ * storage: createLocalStorageAdapter(),
411
+ * network: createFetchNetworkAdapter(),
412
+ * platform: 'web',
413
+ * });
414
+ * ```
415
+ */
416
+ declare function createDataFastWithAdapters(config: DataFastConfig): Promise<DataFastClient>;
417
+ interface DataFastWeb extends DataFastClient {
418
+ /** Track a page view (alias for trackScreen). Optional path defaults to current location. */
419
+ trackPageview(path?: string): Promise<void>;
420
+ }
421
+ /**
422
+ * Create a web-optimized DataFast client. Same as initDataFast (alias).
423
+ */
424
+ declare function createDataFastWeb(config: DataFastWebConfig): Promise<DataFastWeb>;
425
+ declare const dataFastWeb: {
426
+ init: typeof initDataFast;
427
+ createWeb: typeof createDataFastWeb;
428
+ getClient: typeof getDataFastClient;
429
+ createClient: typeof createDataFastClient;
430
+ };
431
+
432
+ export { type BaseEventPayload, type CustomProperties, DataFastClient, type DataFastConfig, type DataFastWeb, type DataFastWebConfig, type DeviceInfo, EventQueue, type EventType, type NetworkAdapter, type PaymentData, type Platform, type QueuedEvent, type SDKState, type StorageAdapter, type UserProperties, type Viewport, buildScreenHref, buildUserAgent, createDataFastClient, createDataFastWeb, createDataFastWithAdapters, createFetchNetworkAdapter, createLocalStorageAdapter, createLogger, createMemoryStorageAdapter, dataFastWeb as default, generateEventId, generateSessionId, generateVisitorId, getDataFastClient, getDeviceInfo, initDataFast, isSessionExpired, isValidEventName, isValidSessionId, isValidVisitorId, onViewportChange, sanitizeCustomProperties };