analyzer-analytics 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ (()=>{var{defineProperty:x,getOwnPropertyNames:P,getOwnPropertyDescriptor:Q}=Object,T=Object.prototype.hasOwnProperty;var G=new WeakMap,U=(j)=>{var m=G.get(j),q;if(m)return m;if(m=x({},"__esModule",{value:!0}),j&&typeof j==="object"||typeof j==="function")P(j).map((w)=>!T.call(m,w)&&x(m,w,{get:()=>j[w],enumerable:!(q=Q(j,w))||q.enumerable}));return G.set(j,m),m};var W=(j,m)=>{for(var q in m)x(j,q,{get:m[q],enumerable:!0,configurable:!0,set:(w)=>m[q]=()=>w})};var $={};W($,{default:()=>z,VERSION:()=>M,Analytics:()=>F});function H(){return Date.now()+"_"+Math.random().toString(36).slice(2,10)}function J(j,m=!1){try{return(m?sessionStorage:localStorage).getItem(j)}catch{return null}}function L(j,m,q=!1){try{(q?sessionStorage:localStorage).setItem(j,m)}catch{}}function X(){let j=J("_a_vid");if(!j)j=H(),L("_a_vid",j);return j}function Y(){let j=J("_a_sid",!0);if(!j)j=H(),L("_a_sid",j,!0);return j}function Z(){let j=navigator.userAgent?.toLowerCase()||"";return/bot|crawler|spider|googlebot|bingbot|slurp|duckduckbot|baiduspider|yandex|headless|phantom|selenium|puppeteer/.test(j)}function _(j){return j.toLowerCase().replace(/\s+/g,"_").replace(/[^a-z0-9_]/g,"").slice(0,100)||"event"}class F{cfg;q=[];vid;sid;timer=null;ok=!1;constructor(j){if(!j.apiKey)throw new Error("API key required");if(this.cfg={apiKey:j.apiKey,endpoint:j.endpoint||"http://localhost:8080",debug:j.debug||!1,autoTrack:j.autoTrack!==!1,maxQueueSize:j.maxQueueSize||10,flushInterval:j.flushInterval||5000},this.vid=X(),this.sid=Y(),Z())return;if(this.ok=!0,this.cfg.autoTrack)this.trackPV();if(this.startTimer(),typeof window!=="undefined")window.addEventListener("beforeunload",()=>this.send())}track(j,m={}){if(!this.ok)return;if(this.q.push({e:_(j),p:m,t:Date.now()}),this.q.length>=this.cfg.maxQueueSize)this.flush()}trackPV(){this.track("pageview")}async flush(){if(!this.q.length)return;let j=this.q;this.q=[],await this.send(j)}async send(j=this.q){if(!j.length)return;let m={api_key:this.cfg.apiKey,events:j.map((w)=>this.build(w))},q=this.cfg.endpoint+"/events";try{if(navigator.sendBeacon?.(q,new Blob([JSON.stringify(m)],{type:"application/json"})))return;await fetch(q,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.cfg.apiKey}`},body:JSON.stringify(m),keepalive:!0})}catch(w){if(this.cfg.debug)console.error("[Analytics]",w)}}build(j){return{event:j.e,properties:j.p,timestamp:j.t,visitor_id:this.vid,session_id:this.sid,page_url:location.href,page_title:document.title,referrer:document.referrer,user_agent:navigator.userAgent,screen_width:screen.width,screen_height:screen.height}}startTimer(){if(this.cfg.flushInterval>0)this.timer=setInterval(()=>this.flush(),this.cfg.flushInterval)}destroy(){if(this.timer)clearInterval(this.timer);this.send(),this.ok=!1}getVisitorId(){return this.vid}getSessionId(){return this.sid}}var M="0.1.0",D={version:M,instance:null,init(j,m={}){if(this.instance)this.instance.destroy();return this.instance=new F({apiKey:j,...m}),this.instance},track(j,m={}){if(!this.instance){console.warn("[Analytics] Not initialized");return}this.instance.track(j,m)},async flush(){if(this.instance)await this.instance.flush()}};if(typeof window!=="undefined"){window.analytics=D;let j=document.currentScript,m=j?.getAttribute("data-api-key");if(m)D.init(m,{endpoint:j?.getAttribute("data-endpoint")||void 0,debug:j?.getAttribute("data-debug")==="true"})}var z=D;})();
package/dist/core.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * @youranalytics/web-sdk - Core Build
3
+ * Ultra-minimal analytics SDK (<3KB gzipped)
4
+ * Basic tracking without adaptive networking
5
+ * @version 0.1.0
6
+ */
7
+ interface Config {
8
+ apiKey: string;
9
+ endpoint: string;
10
+ debug: boolean;
11
+ autoTrack: boolean;
12
+ maxQueueSize: number;
13
+ flushInterval: number;
14
+ }
15
+ declare class Core {
16
+ private cfg;
17
+ private q;
18
+ private vid;
19
+ private sid;
20
+ private timer;
21
+ private ok;
22
+ constructor(config: Partial<Config> & {
23
+ apiKey: string;
24
+ });
25
+ track(event: string, props?: Record<string, unknown>): void;
26
+ trackPV(): void;
27
+ flush(): Promise<void>;
28
+ private send;
29
+ private build;
30
+ private startTimer;
31
+ destroy(): void;
32
+ getVisitorId(): string;
33
+ getSessionId(): string;
34
+ }
35
+ declare const VERSION = "0.1.0";
36
+ interface GA {
37
+ version: string;
38
+ instance: Core | null;
39
+ init(apiKey: string, cfg?: Partial<Config>): Core;
40
+ track(e: string, p?: Record<string, unknown>): void;
41
+ flush(): Promise<void>;
42
+ }
43
+ declare const ga: GA;
44
+ export { Core as Analytics, VERSION };
45
+ export default ga;
46
+ //# sourceMappingURL=core.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH,UAAU,MAAM;IACd,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,OAAO,CAAC;IACf,SAAS,EAAE,OAAO,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;CACvB;AAwED,cAAM,IAAI;IACR,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,CAAC,CAAmE;IAC5E,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,KAAK,CAA+C;IAC5D,OAAO,CAAC,EAAE,CAAS;gBAEP,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,GAAG;QAAE,MAAM,EAAE,MAAM,CAAA;KAAE;IA0BxD,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GAAG,IAAI;IAM/D,OAAO,IAAI,IAAI;IAIT,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;YAOd,IAAI;IA4BlB,OAAO,CAAC,KAAK;IAgBb,OAAO,CAAC,UAAU;IAMlB,OAAO,IAAI,IAAI;IAMf,YAAY,IAAI,MAAM;IACtB,YAAY,IAAI,MAAM;CACvB;AAMD,QAAA,MAAM,OAAO,UAAU,CAAC;AAExB,UAAU,EAAE;IACV,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,IAAI,GAAG,IAAI,CAAC;IACtB,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;IAClD,KAAK,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IACpD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED,QAAA,MAAM,EAAE,EAAE,EAaT,CAAC;AAaF,OAAO,EAAE,IAAI,IAAI,SAAS,EAAE,OAAO,EAAE,CAAC;AACtC,eAAe,EAAE,CAAC"}
@@ -0,0 +1,75 @@
1
+ /**
2
+ * @youranalytics/web-sdk
3
+ * Lightweight analytics SDK optimized for slow networks
4
+ * @version 0.1.0
5
+ * @license MIT
6
+ */
7
+ export { Analytics, createAnalytics } from './analytics';
8
+ export type { AnalyticsConfig, ResolvedConfig, RawEvent, QueuedEvent, UtmParams, ConnectionType, NetworkInfo, EventBatch, AdaptiveSettings as AdaptiveSettingsType, SdkState, VisitorId, SessionId, } from './types';
9
+ export { isValidEvent, isValidConfig, isValidQueuedEvent, isValidUtmParams, createVisitorId, createSessionId, DEFAULT_CONFIG, } from './types';
10
+ export { generateId, getVisitorId, getSessionId, getItem, setItem, getSessionItem, setSessionItem, isStorageAvailable, resetStorageCache, clearVisitorId, clearSessionId, STORAGE_KEYS, } from './storage';
11
+ export { parseQueryString, getUtmParams, getConnectionInfo, getConnectionType, isBot, debounce, throttle, supportsBeacon, supportsFetch, supportsCompression, resetCapabilityCache, sanitizeEventName, sanitizeProperties, getPageUrl, getPageTitle, getReferrer, getUserAgent, getScreenDimensions, } from './utils';
12
+ export { sendBeacon, sendFetch, sendWithRetry, send, queueOfflineEvents, getOfflineEvents, clearOfflineEvents, isOffline, onOnline, setDebugMode, NetworkError, } from './network';
13
+ export { NetworkAdapter, RetryStrategy, EventPriority, sortByPriority, assignPriority, isDataSaverEnabled, getRtt, getDownlink, sendAdaptive, getNetworkAdapter, resetNetworkAdapter, type AdaptiveSettings, type BatchingStrategy, type PrioritizedEvent, } from './network-adapter';
14
+ import { Analytics } from './analytics';
15
+ import type { AnalyticsConfig } from './types';
16
+ /**
17
+ * Version of the SDK
18
+ */
19
+ export declare const VERSION = "0.1.0";
20
+ /**
21
+ * Global analytics interface for script tag usage.
22
+ * Provides a simple API that can be accessed via window.analytics
23
+ */
24
+ export interface GlobalAnalytics {
25
+ /** SDK version */
26
+ readonly version: string;
27
+ /** Current analytics instance (null if not initialized) */
28
+ instance: Analytics | null;
29
+ /**
30
+ * Initialize the analytics SDK
31
+ * @param apiKey - Your API key from the analytics dashboard
32
+ * @param config - Optional configuration overrides
33
+ * @returns The Analytics instance
34
+ */
35
+ init(apiKey: string, config?: Partial<Omit<AnalyticsConfig, 'apiKey'>>): Analytics;
36
+ /**
37
+ * Track a custom event
38
+ * @param event - Event name
39
+ * @param properties - Optional event properties
40
+ */
41
+ track(event: string, properties?: Record<string, unknown>): void;
42
+ /**
43
+ * Track a page view
44
+ */
45
+ trackPageView(): void;
46
+ /**
47
+ * Get the current visitor ID
48
+ * @returns Visitor ID or null if not initialized
49
+ */
50
+ getVisitorId(): string | null;
51
+ /**
52
+ * Get the current session ID
53
+ * @returns Session ID or null if not initialized
54
+ */
55
+ getSessionId(): string | null;
56
+ /**
57
+ * Manually flush queued events
58
+ * @returns Promise that resolves when flush is complete
59
+ */
60
+ flush(): Promise<void>;
61
+ /**
62
+ * Destroy the analytics instance and clean up
63
+ */
64
+ destroy(): void;
65
+ }
66
+ /**
67
+ * Global analytics instance
68
+ */
69
+ declare const globalAnalytics: GlobalAnalytics;
70
+ /**
71
+ * Default export is the global analytics object.
72
+ * Can be used as: import analytics from '@youranalytics/web-sdk'
73
+ */
74
+ export default globalAnalytics;
75
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAOH,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAGzD,YAAY,EACV,eAAe,EACf,cAAc,EACd,QAAQ,EACR,WAAW,EACX,SAAS,EACT,cAAc,EACd,WAAW,EACX,UAAU,EACV,gBAAgB,IAAI,oBAAoB,EACxC,QAAQ,EACR,SAAS,EACT,SAAS,GACV,MAAM,SAAS,CAAC;AAGjB,OAAO,EACL,YAAY,EACZ,aAAa,EACb,kBAAkB,EAClB,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,cAAc,GACf,MAAM,SAAS,CAAC;AAGjB,OAAO,EACL,UAAU,EACV,YAAY,EACZ,YAAY,EACZ,OAAO,EACP,OAAO,EACP,cAAc,EACd,cAAc,EACd,kBAAkB,EAClB,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,YAAY,GACb,MAAM,WAAW,CAAC;AAGnB,OAAO,EAEL,gBAAgB,EAChB,YAAY,EAEZ,iBAAiB,EACjB,iBAAiB,EAEjB,KAAK,EAEL,QAAQ,EACR,QAAQ,EAER,cAAc,EACd,aAAa,EACb,mBAAmB,EACnB,oBAAoB,EAEpB,iBAAiB,EACjB,kBAAkB,EAElB,UAAU,EACV,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,mBAAmB,GACpB,MAAM,SAAS,CAAC;AAGjB,OAAO,EACL,UAAU,EACV,SAAS,EACT,aAAa,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,QAAA,MAAM,eAAe,EAAE,eAAyC,CAAC;AAgEjE;;;GAGG;AACH,eAAe,eAAe,CAAC"}
@@ -0,0 +1,243 @@
1
+ /**
2
+ * @youranalytics/web-sdk Network Adapter
3
+ * Adaptive behavior for different network conditions
4
+ * Optimized for 2G/3G networks with smart batching and compression
5
+ */
6
+ import type { ConnectionType, RawEvent, EventBatch } from './types';
7
+ /**
8
+ * Batching strategy based on network conditions.
9
+ * - aggressive: Large batches, less frequent sends (slow networks)
10
+ * - balanced: Medium batches, moderate frequency (3G)
11
+ * - conservative: Small batches, frequent sends (fast networks)
12
+ */
13
+ export type BatchingStrategy = 'aggressive' | 'balanced' | 'conservative';
14
+ /**
15
+ * Adaptive settings computed from network conditions.
16
+ */
17
+ export interface AdaptiveSettings {
18
+ /** Maximum events to queue before forcing a flush */
19
+ maxQueueSize: number;
20
+ /** Interval between automatic flushes in milliseconds */
21
+ flushInterval: number;
22
+ /** Whether to compress event payloads */
23
+ compressionEnabled: boolean;
24
+ /** Batching strategy name */
25
+ batchingStrategy: BatchingStrategy;
26
+ }
27
+ /**
28
+ * Event priority levels for request prioritization.
29
+ */
30
+ export declare enum EventPriority {
31
+ /** Low priority: page views, impressions */
32
+ LOW = 0,
33
+ /** Normal priority: custom events, interactions */
34
+ NORMAL = 1,
35
+ /** High priority: conversions, errors, critical events */
36
+ HIGH = 2
37
+ }
38
+ /**
39
+ * Event with priority information.
40
+ */
41
+ export interface PrioritizedEvent extends RawEvent {
42
+ priority: EventPriority;
43
+ }
44
+ /**
45
+ * Check if user has enabled data saver mode.
46
+ * Data saver mode indicates the user wants to minimize data usage.
47
+ *
48
+ * @returns true if data saver is enabled
49
+ */
50
+ export declare function isDataSaverEnabled(): boolean;
51
+ /**
52
+ * Get the round-trip time (RTT) in milliseconds.
53
+ * Returns a default value if not available.
54
+ *
55
+ * @returns RTT in milliseconds
56
+ */
57
+ export declare function getRtt(): number;
58
+ /**
59
+ * Get the downlink speed in Mbps.
60
+ * Returns a default value if not available.
61
+ *
62
+ * @returns Downlink speed in Mbps
63
+ */
64
+ export declare function getDownlink(): number;
65
+ /**
66
+ * Sort events by priority (high priority first).
67
+ * Useful for slow connections where high-priority events should be sent first.
68
+ *
69
+ * @param events - Array of prioritized events
70
+ * @returns Sorted array with high priority events first
71
+ */
72
+ export declare function sortByPriority(events: PrioritizedEvent[]): PrioritizedEvent[];
73
+ /**
74
+ * Assign priority to an event based on its type.
75
+ *
76
+ * @param event - Raw event to prioritize
77
+ * @returns Event with priority assigned
78
+ */
79
+ export declare function assignPriority(event: RawEvent): PrioritizedEvent;
80
+ /**
81
+ * Smart retry strategy with exponential backoff.
82
+ * Adapts max retries based on connection quality.
83
+ */
84
+ export declare class RetryStrategy {
85
+ private attempts;
86
+ private readonly maxRetries;
87
+ /**
88
+ * Create a new retry strategy.
89
+ *
90
+ * @param connectionType - Current connection type
91
+ */
92
+ constructor(connectionType?: ConnectionType);
93
+ /**
94
+ * Get the backoff delay for the current attempt.
95
+ * Uses exponential backoff with a maximum cap.
96
+ *
97
+ * Formula: min(1000 * 2^attempts, 30000)
98
+ * - Retry 1: 1s
99
+ * - Retry 2: 2s
100
+ * - Retry 3: 4s
101
+ * - Retry 4: 8s
102
+ * - Retry 5: 16s
103
+ * - Max: 30s
104
+ *
105
+ * @returns Delay in milliseconds
106
+ */
107
+ getBackoffDelay(): number;
108
+ /**
109
+ * Check if a retry should be attempted based on the error.
110
+ *
111
+ * Retry on:
112
+ * - Network errors (fetch failed)
113
+ * - 5xx server errors
114
+ * - Timeout errors
115
+ * - 429 rate limit errors
116
+ *
117
+ * Don't retry on:
118
+ * - 4xx client errors (except 429)
119
+ * - Max retries reached
120
+ *
121
+ * @param error - Error to evaluate
122
+ * @returns true if should retry
123
+ */
124
+ shouldRetry(error: Error): boolean;
125
+ /**
126
+ * Record an attempt.
127
+ */
128
+ recordAttempt(): void;
129
+ /**
130
+ * Reset the strategy.
131
+ */
132
+ reset(): void;
133
+ /**
134
+ * Get number of attempts made.
135
+ */
136
+ getAttempts(): number;
137
+ /**
138
+ * Get maximum retries allowed.
139
+ */
140
+ getMaxRetries(): number;
141
+ }
142
+ /**
143
+ * Network adapter that provides adaptive settings based on connection quality.
144
+ * Listens for connection changes and notifies subscribers.
145
+ */
146
+ export declare class NetworkAdapter {
147
+ private currentSettings;
148
+ private connection;
149
+ private changeCallbacks;
150
+ private boundHandleChange;
151
+ private cachedConnectionType;
152
+ private lastUpdateTime;
153
+ private readonly cacheTimeout;
154
+ /**
155
+ * Create a new network adapter.
156
+ * Automatically detects connection and sets up listeners.
157
+ */
158
+ constructor();
159
+ /**
160
+ * Compute settings based on current connection.
161
+ */
162
+ private computeSettings;
163
+ /**
164
+ * Handle connection change event.
165
+ */
166
+ private handleConnectionChange;
167
+ /**
168
+ * Get current connection type with caching.
169
+ */
170
+ private getConnectionType;
171
+ /**
172
+ * Get current adaptive settings.
173
+ *
174
+ * @returns Current settings based on connection quality
175
+ */
176
+ getSettings(): AdaptiveSettings;
177
+ /**
178
+ * Register a callback for connection changes.
179
+ * Callback is invoked when connection quality changes.
180
+ *
181
+ * @param callback - Function to call with new settings
182
+ * @returns Cleanup function to remove the callback
183
+ */
184
+ onConnectionChange(callback: (settings: AdaptiveSettings) => void): () => void;
185
+ /**
186
+ * Check if compression should be used.
187
+ * Based on connection type, CompressionStream availability, and data saver mode.
188
+ *
189
+ * @returns true if compression should be enabled
190
+ */
191
+ shouldCompress(): boolean;
192
+ /**
193
+ * Get the optimal batch size for current connection.
194
+ * Considers connection speed, RTT, and data saver mode.
195
+ *
196
+ * @returns Optimal batch size
197
+ */
198
+ getOptimalBatchSize(): number;
199
+ /**
200
+ * Get a retry strategy appropriate for current connection.
201
+ *
202
+ * @returns RetryStrategy configured for connection
203
+ */
204
+ getRetryStrategy(): RetryStrategy;
205
+ /**
206
+ * Check if network conditions are poor.
207
+ *
208
+ * @returns true if on slow connection
209
+ */
210
+ isSlowConnection(): boolean;
211
+ /**
212
+ * Get recommended timeout for requests.
213
+ * Based on RTT and connection type.
214
+ *
215
+ * @returns Timeout in milliseconds
216
+ */
217
+ getRecommendedTimeout(): number;
218
+ /**
219
+ * Clean up the adapter.
220
+ * Removes event listeners.
221
+ */
222
+ destroy(): void;
223
+ }
224
+ /**
225
+ * Send data with adaptive behavior based on network conditions.
226
+ * Chooses the best transport method and applies compression as needed.
227
+ *
228
+ * @param url - Endpoint URL
229
+ * @param data - Event batch to send
230
+ * @param adapter - Network adapter for connection info
231
+ */
232
+ export declare function sendAdaptive(url: string, data: EventBatch, adapter: NetworkAdapter): Promise<void>;
233
+ /**
234
+ * Get or create the global network adapter instance.
235
+ *
236
+ * @returns Global NetworkAdapter instance
237
+ */
238
+ export declare function getNetworkAdapter(): NetworkAdapter;
239
+ /**
240
+ * Reset the global adapter (for testing).
241
+ */
242
+ export declare function resetNetworkAdapter(): void;
243
+ //# sourceMappingURL=network-adapter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"network-adapter.d.ts","sourceRoot":"","sources":["../src/network-adapter.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAQpE;;;;;GAKG;AACH,MAAM,MAAM,gBAAgB,GAAG,YAAY,GAAG,UAAU,GAAG,cAAc,CAAC;AAE1E;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,qDAAqD;IACrD,YAAY,EAAE,MAAM,CAAC;IACrB,yDAAyD;IACzD,aAAa,EAAE,MAAM,CAAC;IACtB,yCAAyC;IACzC,kBAAkB,EAAE,OAAO,CAAC;IAC5B,6BAA6B;IAC7B,gBAAgB,EAAE,gBAAgB,CAAC;CACpC;AAED;;GAEG;AACH,oBAAY,aAAa;IACvB,4CAA4C;IAC5C,GAAG,IAAI;IACP,mDAAmD;IACnD,MAAM,IAAI;IACV,0DAA0D;IAC1D,IAAI,IAAI;CACT;AAED;;GAEG;AACH,MAAM,WAAW,gBAAi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iBAAiB;IAezB;;;;OAIG;IACH,WAAW,IAAI,gBAAgB;IAI/B;;;;;;OAMG;IACH,kBAAkB,CAChB,QAAQ,EAAE,CAAC,QAAQ,EAAE,gBAAgB,KAAK,IAAI,GAC7C,MAAM,IAAI;IAWb;;;;;OAKG;IACH,cAAc,IAAI,OAAO;IAezB;;;;;OAKG;IACH,mBAAmB,IAAI,MAAM;IAsB7B;;;;OAIG;IACH,gBAAgB,IAAI,aAAa;IAIjC;;;;OAIG;IACH,gBAAgB,IAAI,OAAO;IAK3B;;;;;OAKG;IACH,qBAAqB,IAAI,MAAM;IA0B/B;;;OAGG;IACH,OAAO,IAAI,IAAI;CAOhB;AAaD;;;;;;;GAOG;AACH,wBAAsB,YAAY,CAChC,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,UAAU,EAChB,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,IAAI,CAAC,CAiDf;AASD;;;;GAIG;AACH,wBAAgB,iBAAiB,IAAI,cAAc,CAKlD;AAED;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,IAAI,CAK1C"}
@@ -0,0 +1,175 @@
1
+ /**
2
+ * @youranalytics/web-sdk Network Communication Layer
3
+ * Handles sending events to the analytics server with fallbacks and offline support
4
+ */
5
+ import type { EventBatch, RawEvent } from './types';
6
+ /**
7
+ * Enable or disable debug logging.
8
+ * @param enabled - Whether to enable debug mode
9
+ */
10
+ export declare function setDebugMode(enabled: boolean): void;
11
+ /**
12
+ * Custom error class for network-related errors.
13
+ * Includes status code and retry information.
14
+ */
15
+ export declare class NetworkError extends Error {
16
+ readonly statusCode?: number | undefined;
17
+ readonly retry?: boolean | undefined;
18
+ constructor(message: string, statusCode?: number | undefined, retry?: boolean | undefined);
19
+ }
20
+ /**
21
+ * Send data using navigator.sendBeacon.
22
+ *
23
+ * Advantages:
24
+ * - Survives page navigation
25
+ * - Non-blocking
26
+ * - Browser queues the request
27
+ *
28
+ * Limits:
29
+ * - Max 64KB payload
30
+ * - No response handling
31
+ * - No retry on failure
32
+ *
33
+ * @param url - Endpoint URL
34
+ * @param data - Event batch to send
35
+ * @returns true if queued successfully, false otherwise
36
+ */
37
+ export declare function sendBeacon(url: string, data: EventBatch): boolean;
38
+ /**
39
+ * Send data using fetch API.
40
+ * Used when sendBeacon fails or isn't available.
41
+ *
42
+ * Features:
43
+ * - Handles responses
44
+ * - Can retry on failure
45
+ * - Works with larger payloads
46
+ * - Sends Authorization header with Bearer token
47
+ *
48
+ * @param url - Endpoint URL
49
+ * @param data - Event batch to send
50
+ * @param apiKey - Optional API key for Authorization header
51
+ * @throws NetworkError on failure
52
+ */
53
+ export declare function sendFetch(url: string, data: EventBatch, apiKey?: string): Promise<void>;
54
+ /**
55
+ * Send with retry on failure using exponential backoff.
56
+ *
57
+ * Backoff strategy:
58
+ * - Retry 1: wait 1s
59
+ * - Retry 2: wait 2s
60
+ * - Retry 3: wait 4s
61
+ * - Then give up
62
+ *
63
+ * Only retry on network errors, not 4xx errors.
64
+ *
65
+ * @param url - Endpoint URL
66
+ * @param data - Event batch to send
67
+ * @param maxRetries - Maximum number of retry attempts (default: 3)
68
+ * @param apiKey - Optional API key for Authorization header
69
+ * @throws NetworkError if all retries fail
70
+ */
71
+ export declare function sendWithRetry(url: string, data: EventBatch, maxRetries?: number, apiKey?: string): Promise<void>;
72
+ /**
73
+ * Compress JSON payload using GZIP.
74
+ * Only if CompressionStream is available.
75
+ *
76
+ * Savings: ~50-70% size reduction
77
+ *
78
+ * @param data - String data to compress
79
+ * @returns Compressed Blob or original string if compression not supported
80
+ */
81
+ export declare function compressData(data: string): Promise<Blob | string>;
82
+ /**
83
+ * Send compressed data using fetch.
84
+ * Falls back to uncompressed if compression fails.
85
+ *
86
+ * @param url - Endpoint URL
87
+ * @param data - Event batch to send
88
+ * @param apiKey - Optional API key for Authorization header
89
+ */
90
+ export declare function sendCompressed(url: string, data: EventBatch, apiKey?: string): Promise<void>;
91
+ /**
92
+ * Store events in localStorage when offline.
93
+ * Limits to MAX_OFFLINE_EVENTS to prevent quota issues.
94
+ *
95
+ * @param events - Events to queue for later sending
96
+ */
97
+ export declare function queueOfflineEvents(events: RawEvent[]): void;
98
+ /**
99
+ * Retrieve queued offline events.
100
+ * Parses from localStorage.
101
+ *
102
+ * @returns Array of queued events, or empty array if none or error
103
+ */
104
+ export declare function getOfflineEvents(): RawEvent[];
105
+ /**
106
+ * Clear offline queue after successful send.
107
+ */
108
+ export declare function clearOfflineEvents(): void;
109
+ /**
110
+ * Check if the browser is currently offline.
111
+ *
112
+ * @returns true if offline
113
+ */
114
+ export declare function isOffline(): boolean;
115
+ /**
116
+ * Register a callback to be called when the browser comes back online.
117
+ * Returns a cleanup function to remove the listener.
118
+ *
119
+ * @param callback - Function to call when online
120
+ * @returns Cleanup function
121
+ */
122
+ export declare function onOnline(callback: () => void): () => void;
123
+ /**
124
+ * Generate unique request ID.
125
+ * Format: timestamp_random
126
+ * Used to prevent duplicate sends.
127
+ *
128
+ * @returns Unique request ID
129
+ */
130
+ export declare function generateRequestId(): string;
131
+ /**
132
+ * Check if request was already sent.
133
+ * Checks sent IDs in sessionStorage.
134
+ *
135
+ * @param requestId - Request ID to check
136
+ * @returns true if request was already sent
137
+ */
138
+ export declare function wasRequestSent(requestId: string): boolean;
139
+ /**
140
+ * Mark request as sent.
141
+ * Stores in sessionStorage. Keeps last MAX_TRACKED_REQUESTS IDs.
142
+ *
143
+ * @param requestId - Request ID to mark as sent
144
+ */
145
+ export declare function markRequestSent(requestId: string): void;
146
+ /**
147
+ * Clear all tracked request IDs.
148
+ * Useful for testing.
149
+ */
150
+ export declare function clearSentRequests(): void;
151
+ /**
152
+ * Send events to the server using the best available method.
153
+ * Handles offline state, deduplication, and fallbacks.
154
+ *
155
+ * @param url - Endpoint URL
156
+ * @param data - Event batch to send
157
+ * @param options - Send options
158
+ * @returns Promise that resolves when sent (or queued if offline)
159
+ */
160
+ export declare function send(url: string, data: EventBatch, options?: {
161
+ useBeacon?: boolean;
162
+ compress?: boolean;
163
+ retry?: boolean;
164
+ requestId?: string;
165
+ apiKey?: string;
166
+ }): Promise<void>;
167
+ export declare const _testing: {
168
+ OFFLINE_QUEUE_KEY: string;
169
+ SENT_REQUESTS_KEY: string;
170
+ MAX_OFFLINE_EVENTS: number;
171
+ MAX_TRACKED_REQUESTS: number;
172
+ MAX_BEACON_PAYLOAD: number;
173
+ BASE_RETRY_DELAY: number;
174
+ };
175
+ //# sourceMappingURL=network.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"network.d.ts","sourceRoot":"","sources":["../src/network.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAgCpD;;;GAGG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAEnD;AAwBD;;;GAGG;AACH,qBAAa,YAAa,SAAQ,KAAK;aAGnB,UAAU,CAAC,EAAE,MAAM;aACnB,KAAK,CAAC,EAAE,OAAO;gBAF/B,OAAO,EAAE,MAAM,EACC,UAAU,CAAC,EAAE,MAAM,YAAA,EACnB,KAAK,CAAC,EAAE,OAAO,YAAA;CAUlC;AAMD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,GAAG,OAAO,CAkCjE;AAMD;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAkD7F;AAaD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,aAAa,CACjC,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,UAAU,EAChB,UAAU,SAAI,EACd,MAAM,CAAC,EAAE,MAAM,GACd,OAAO,CAAC,IAAI,CAAC,CAoCf;AAMD;;;;;;;;GAQG;AACH,wBAAs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C"}
package/dist/slim.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * @youranalytics/web-sdk - Slim Build
3
+ * Minimal analytics SDK (<3KB gzipped)
4
+ * Only includes core tracking functionality
5
+ * @version 0.1.0
6
+ */
7
+ import { Analytics } from './analytics';
8
+ import type { AnalyticsConfig } from './types';
9
+ export { Analytics };
10
+ export type { AnalyticsConfig };
11
+ export declare const VERSION = "0.1.0";
12
+ /**
13
+ * Global analytics interface for script tag usage.
14
+ */
15
+ interface GlobalAnalytics {
16
+ readonly version: string;
17
+ instance: Analytics | null;
18
+ init(apiKey: string, config?: Partial<Omit<AnalyticsConfig, 'apiKey'>>): Analytics;
19
+ track(event: string, properties?: Record<string, unknown>): void;
20
+ trackPageView(): void;
21
+ flush(): Promise<void>;
22
+ destroy(): void;
23
+ }
24
+ declare const globalAnalytics: GlobalAnalytics;
25
+ export default globalAnalytics;
26
+ //# sourceMappingURL=slim.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"slim.d.ts","sourceRoot":"","sources":["../src/slim.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAM/C,OAAO,EAAE,SAAS,EAAE,CAAC;AACrB,YAAY,EAAE,eAAe,EAAE,CAAC;AAMhC,eAAO,MAAM,OAAO,UAAU,CAAC;AAM/B;;GAEG;AACH,UAAU,eAAe;IACvB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,EAAE,SAAS,GAAG,IAAI,CAAC;IAC3B,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,eAAe,EAAE,QAAQ,CAAC,CAAC,GAAG,SAAS,CAAC;IACnF,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IACjE,aAAa,IAAI,IAAI,CAAC;IACtB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,OAAO,IAAI,IAAI,CAAC;CACjB;AAED,QAAA,MAAM,eAAe,EAAE,eAgCtB,CAAC;AAsBF,eAAe,eAAe,CAAC"}