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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 gonalc
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,139 @@
1
+ # analyzer-analytics
2
+
3
+ Lightweight analytics tracker for web applications. Under 3KB gzipped with support for older browsers and optimized for slow networks.
4
+
5
+ ## Features
6
+
7
+ - **Tiny footprint** - Core bundle <3KB gzipped
8
+ - **Auto pageview tracking** - Tracks pageviews on load
9
+ - **Custom events** - Track any event with properties
10
+ - **Offline support** - Events queued and sent when online
11
+ - **sendBeacon** - Reliable delivery on page unload
12
+ - **Bot filtering** - Automatically ignores known bots
13
+
14
+ ## Quick Start
15
+
16
+ ### Script Tag
17
+
18
+ ```html
19
+ <script
20
+ src="/analytics.min.js"
21
+ data-api-key="your_api_key"
22
+ data-endpoint="https://your-server.com"
23
+ ></script>
24
+ ```
25
+
26
+ ### Track Events
27
+
28
+ ```javascript
29
+ // Custom events
30
+ analytics.track('signup', { plan: 'pro' });
31
+ analytics.track('purchase', { product_id: 'abc', price: 99 });
32
+ ```
33
+
34
+ ## Installation
35
+
36
+ ### Option 1: Script Tag (recommended)
37
+
38
+ ```html
39
+ <script
40
+ src="/path/to/analytics.min.js"
41
+ data-api-key="pk_test_abc123"
42
+ data-endpoint="http://localhost:8080"
43
+ data-debug="true"
44
+ ></script>
45
+ ```
46
+
47
+ ### Option 2: ES Module
48
+
49
+ ```javascript
50
+ import analytics from 'analyzer-analytics';
51
+
52
+ analytics.init('pk_test_abc123', {
53
+ endpoint: 'http://localhost:8080'
54
+ });
55
+ ```
56
+
57
+ ## Configuration
58
+
59
+ | Attribute | Default | Description |
60
+ |-----------|---------|-------------|
61
+ | `data-api-key` | required | Your project API key |
62
+ | `data-endpoint` | `http://localhost:8080` | Analytics server URL |
63
+ | `data-debug` | `false` | Enable console logging |
64
+ | `data-auto-track` | `true` | Auto-track pageviews |
65
+
66
+ ## API
67
+
68
+ ```javascript
69
+ // Initialize
70
+ analytics.init(apiKey, { endpoint, debug, autoTrack });
71
+
72
+ // Track event
73
+ analytics.track('event_name', { key: 'value' });
74
+
75
+ // Force send queued events
76
+ await analytics.flush();
77
+
78
+ // Get visitor/session IDs
79
+ analytics.instance.getVisitorId();
80
+ analytics.instance.getSessionId();
81
+ ```
82
+
83
+ ## Documentation
84
+
85
+ See the complete **[SDK Usage Guide](../../docs/SDK_USAGE.md)** for:
86
+ - Framework integration (Astro, React, Vue, Next.js)
87
+ - SPA route tracking
88
+ - Event tracking examples
89
+ - Troubleshooting
90
+
91
+ ## Development
92
+
93
+ ### Prerequisites
94
+
95
+ - [Bun](https://bun.sh/) v1.0 or later
96
+
97
+ ### Setup
98
+
99
+ ```bash
100
+ bun install
101
+ ```
102
+
103
+ ### Build
104
+
105
+ ```bash
106
+ # Build all formats
107
+ bun run build
108
+
109
+ # Development mode (watch)
110
+ bun run dev
111
+ ```
112
+
113
+ ### Build Output
114
+
115
+ | File | Size | Description |
116
+ |------|------|-------------|
117
+ | `dist/analytics.min.js` | ~1.6KB gzip | Core build (recommended) |
118
+ | `dist/analytics.esm.js` | ~10KB gzip | ES Module |
119
+ | `dist/analytics.js` | ~10KB gzip | IIFE unminified |
120
+ | `dist/analytics.full.min.js` | ~8KB gzip | Full features |
121
+
122
+ ### Testing
123
+
124
+ ```bash
125
+ bun test
126
+ bun test:watch
127
+ ```
128
+
129
+ ### Size Check
130
+
131
+ ```bash
132
+ bun run size-check
133
+ ```
134
+
135
+ Target: Core bundle <3KB gzipped
136
+
137
+ ## License
138
+
139
+ MIT
@@ -0,0 +1,204 @@
1
+ /**
2
+ * @youranalytics/web-sdk Analytics Class
3
+ * Core SDK class that orchestrates storage, network, and event tracking
4
+ */
5
+ import type { AnalyticsConfig, ResolvedConfig, VisitorId, SessionId } from './types';
6
+ /**
7
+ * Main Analytics SDK class.
8
+ * Manages event tracking, queue, and communication with the analytics server.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * const analytics = new Analytics({ apiKey: 'pk_live_xxx' });
13
+ *
14
+ * // Track custom events
15
+ * analytics.track('signup', { plan: 'pro' });
16
+ *
17
+ * // Track page views (usually automatic)
18
+ * analytics.trackPageView();
19
+ *
20
+ * // Clean up when done
21
+ * analytics.destroy();
22
+ * ```
23
+ */
24
+ export declare class Analytics {
25
+ private config;
26
+ private queue;
27
+ private visitorId;
28
+ private sessionId;
29
+ private flushTimer;
30
+ private isInitialized;
31
+ private lastPageUrl;
32
+ private boundHandlePageUnload;
33
+ private boundHandleOnline;
34
+ private boundHandleOffline;
35
+ private boundHandlePopstate;
36
+ private debouncedTrackPageView;
37
+ private originalPushState;
38
+ private originalReplaceState;
39
+ private adapter;
40
+ private adapterCleanup;
41
+ private useAdaptiveNetwork;
42
+ /**
43
+ * Create a new Analytics instance.
44
+ *
45
+ * @param config - Analytics configuration
46
+ * @throws Error if API key is missing
47
+ */
48
+ constructor(config: AnalyticsConfig);
49
+ /**
50
+ * Set up auto-tracking, timers, and event listeners.
51
+ */
52
+ private init;
53
+ /**
54
+ * Initialize the network adapter for adaptive behavior.
55
+ */
56
+ private initNetworkAdapter;
57
+ /**
58
+ * Apply adaptive settings based on network conditions.
59
+ */
60
+ private applyAdaptiveSettings;
61
+ /**
62
+ * Track a custom event.
63
+ *
64
+ * @param eventName - Name of the event (will be sanitized)
65
+ * @param properties - Optional event properties
66
+ *
67
+ * @example
68
+ * ```typescript
69
+ * analytics.track('purchase', {
70
+ * product_id: '123',
71
+ * price: 99.99,
72
+ * currency: 'USD',
73
+ * });
74
+ * ```
75
+ */
76
+ track(eventName: string, properties?: Record<string, unknown>): void;
77
+ /**
78
+ * Track a page view event.
79
+ * Convenience method that calls track('pageview', {}).
80
+ */
81
+ trackPageView(): void;
82
+ /**
83
+ * Internal pageview tracking (not debounced).
84
+ */
85
+ private trackPageViewInternal;
86
+ /**
87
+ * Send all queued events to the server.
88
+ * Uses sendBeacon first, falls back to fetch.
89
+ *
90
+ * @returns Promise that resolves when flush is complete
91
+ */
92
+ flush(): Promise<void>;
93
+ /**
94
+ * Build RawEvents from QueuedEvents by adding context metadata.
95
+ */
96
+ private buildRawEvents;
97
+ /**
98
+ * Start periodic flush timer.
99
+ */
100
+ private startFlushTimer;
101
+ /**
102
+ * Stop flush timer.
103
+ */
104
+ private stopFlushTimer;
105
+ /**
106
+ * Set up automatic page view tracking for SPAs.
107
+ * Wraps history methods and listens to popstate.
108
+ */
109
+ private setupPageViewTracking;
110
+ /**
111
+ * Wrap history method to track navigation.
112
+ */
113
+ private wrapHistoryMethod;
114
+ /**
115
+ * Handle popstate event (back/forward navigation).
116
+ */
117
+ private handlePopstate;
118
+ /**
119
+ * Restore original history methods.
120
+ */
121
+ private restoreHistoryMethods;
122
+ /**
123
+ * Handle page unload - flush remaining events.
124
+ * Must use sendBeacon for reliability.
125
+ */
126
+ private handlePageUnload;
127
+ /**
128
+ * Handle coming back online.
129
+ * Send any queued offline events.
130
+ */
131
+ private handleOnline;
132
+ /**
133
+ * Handle going offline.
134
+ * Flush current queue to localStorage.
135
+ */
136
+ private handleOffline;
137
+ /**
138
+ * Send any queued offline events.
139
+ */
140
+ private sendOfflineEvents;
141
+ /**
142
+ * Update configuration at runtime.
143
+ *
144
+ * @param updates - Partial configuration to merge
145
+ */
146
+ setConfig(updates: Partial<AnalyticsConfig>): void;
147
+ /**
148
+ * Get current visitor ID.
149
+ * Useful for debugging or external tools.
150
+ *
151
+ * @returns Current visitor ID
152
+ */
153
+ getVisitorId(): VisitorId;
154
+ /**
155
+ * Get current session ID.
156
+ *
157
+ * @returns Current session ID
158
+ */
159
+ getSessionId(): SessionId;
160
+ /**
161
+ * Get current configuration.
162
+ *
163
+ * @returns Current resolved configuration
164
+ */
165
+ getConfig(): ResolvedConfig;
166
+ /**
167
+ * Get current queue length.
168
+ *
169
+ * @returns Number of events in queue
170
+ */
171
+ getQueueLength(): number;
172
+ /**
173
+ * Check if SDK is initialized.
174
+ *
175
+ * @returns true if initialized
176
+ */
177
+ isActive(): boolean;
178
+ /**
179
+ * Clean up SDK instance.
180
+ * Flushes remaining events and removes listeners.
181
+ */
182
+ destroy(): void;
183
+ /**
184
+ * Log to console if debug enabled.
185
+ */
186
+ private log;
187
+ /**
188
+ * Warn to console if debug enabled.
189
+ */
190
+ private warn;
191
+ /**
192
+ * Error to console if debug enabled.
193
+ */
194
+ private error;
195
+ }
196
+ /**
197
+ * Create a new Analytics instance.
198
+ * Convenience function that wraps the class constructor.
199
+ *
200
+ * @param config - Analytics configuration
201
+ * @returns New Analytics instance
202
+ */
203
+ export declare function createAnalytics(config: AnalyticsConfig): Analytics;
204
+ //# sourceMappingURL=analytics.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"analytics.d.ts","sourceRoot":"","sources":["../src/analytics.ts"],"names":[],"mappings":"AAAA;;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