@entrolytics/svelte-sdk 2.2.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) 2025 Entrolytics <hey@entrolytics.click>
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,284 @@
1
+ <div align="center">
2
+ <img src="https://raw.githubusercontent.com/entrolytics/.github/main/media/entrov2.png" alt="Entrolytics" width="64" height="64">
3
+
4
+ [![npm](https://img.shields.io/npm/v/@entrolytics/svelte-sdk.svg?logo=npm)](https://www.npmjs.com/package/@entrolytics/svelte-sdk)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
6
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.0-3178C6.svg?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
7
+ [![Svelte](https://img.shields.io/badge/Svelte-5+-FF3E00.svg?logo=svelte&logoColor=white)](https://svelte.dev/)
8
+
9
+ </div>
10
+
11
+ ---
12
+
13
+ ## Overview
14
+
15
+ **@entrolytics/svelte-sdk** is the official SvelteKit SDK for Entrolytics - first-party growth analytics for the edge. Add powerful analytics to your Svelte 5 and SvelteKit applications with minimal configuration.
16
+
17
+ **Why use this SDK?**
18
+ - Zero-config setup with automatic environment detection
19
+ - Svelte actions for declarative click tracking
20
+ - Svelte stores for reactive state management
21
+ - Edge-optimized with sub-50ms response times globally
22
+
23
+ ## Key Features
24
+
25
+ <table>
26
+ <tr>
27
+ <td width="50%">
28
+
29
+ ### Analytics
30
+ - Automatic page view tracking
31
+ - Custom event tracking
32
+ - User identification
33
+ - SvelteKit navigation support
34
+
35
+ </td>
36
+ <td width="50%">
37
+
38
+ ### Developer Experience
39
+ - `use:trackClick` Svelte action
40
+ - `$isLoaded` reactive store
41
+ - SvelteKit `$page` store integration
42
+ - Full TypeScript support
43
+
44
+ </td>
45
+ </tr>
46
+ </table>
47
+
48
+ ## Quick Start
49
+
50
+ <table>
51
+ <tr>
52
+ <td align="center" width="25%">
53
+ <img src="https://api.iconify.design/lucide:download.svg?color=%236366f1" width="48"><br>
54
+ <strong>1. Install</strong><br>
55
+ <code>npm i @entrolytics/svelte-sdk</code>
56
+ </td>
57
+ <td align="center" width="25%">
58
+ <img src="https://api.iconify.design/lucide:code.svg?color=%236366f1" width="48"><br>
59
+ <strong>2. Initialize</strong><br>
60
+ <code>initEntrolytics()</code>
61
+ </td>
62
+ <td align="center" width="25%">
63
+ <img src="https://api.iconify.design/lucide:settings.svg?color=%236366f1" width="48"><br>
64
+ <strong>3. Configure</strong><br>
65
+ Set Website ID in <code>.env</code>
66
+ </td>
67
+ <td align="center" width="25%">
68
+ <img src="https://api.iconify.design/lucide:bar-chart-3.svg?color=%236366f1" width="48"><br>
69
+ <strong>4. Track</strong><br>
70
+ View analytics in dashboard
71
+ </td>
72
+ </tr>
73
+ </table>
74
+
75
+ ## Installation
76
+
77
+ ```bash
78
+ npm install @entrolytics/svelte-sdk
79
+ # or
80
+ pnpm add @entrolytics/svelte-sdk
81
+ ```
82
+
83
+ ```svelte
84
+ <!-- +layout.svelte -->
85
+ <script>
86
+ import { initEntrolytics } from '@entrolytics/svelte-sdk';
87
+
88
+ // Zero-config: automatically reads from .env
89
+ initEntrolytics();
90
+ </script>
91
+
92
+ <slot />
93
+ ```
94
+
95
+ Add to your `.env` file:
96
+
97
+ ```bash
98
+ VITE_ENTROLYTICS_WEBSITE_ID=your-website-id
99
+ VITE_ENTROLYTICS_HOST=https://entrolytics.click
100
+
101
+ # Or for SvelteKit static
102
+ PUBLIC_ENTROLYTICS_WEBSITE_ID=your-website-id
103
+ PUBLIC_ENTROLYTICS_HOST=https://entrolytics.click
104
+ ```
105
+
106
+ ## Configuration Options
107
+
108
+ ### Zero-Config (Recommended)
109
+
110
+ ```svelte
111
+ <script>
112
+ initEntrolytics(); // Reads from env
113
+ </script>
114
+ ```
115
+
116
+ ### Explicit Configuration
117
+
118
+ ```ts
119
+ initEntrolytics({
120
+ // Required: Your Entrolytics website ID
121
+ websiteId: 'your-website-id',
122
+
123
+ // Optional: Custom host (for self-hosted)
124
+ host: 'https://entrolytics.click',
125
+
126
+ // Optional: Auto-track page views (default: true)
127
+ autoTrack: true,
128
+
129
+ // Optional: Use edge-optimized endpoints (default: true)
130
+ useEdgeRuntime: true,
131
+
132
+ // Optional: Respect Do Not Track (default: false)
133
+ respectDnt: false,
134
+
135
+ // Optional: Cross-domain tracking
136
+ domains: ['example.com', 'blog.example.com'],
137
+ });
138
+ ```
139
+
140
+ ### Runtime Configuration
141
+
142
+ The `useEdgeRuntime` option controls which collection endpoint is used:
143
+
144
+ **Edge Runtime (default)** - Optimized for speed and global distribution:
145
+
146
+ ```ts
147
+ initEntrolytics({
148
+ websiteId: 'your-website-id',
149
+ useEdgeRuntime: true // or omit (default)
150
+ });
151
+ ```
152
+
153
+ - **Latency**: Sub-50ms response times globally
154
+ - **Best for**: Production Svelte/SvelteKit apps, globally distributed users
155
+ - **Endpoint**: Uses `/api/send-native` for edge-to-edge communication
156
+ - **Limitations**: No ClickHouse export, basic geo data
157
+
158
+ **Node.js Runtime** - Full-featured with advanced capabilities:
159
+
160
+ ```ts
161
+ initEntrolytics({
162
+ websiteId: 'your-website-id',
163
+ useEdgeRuntime: false
164
+ });
165
+ ```
166
+
167
+ - **Features**: ClickHouse export, MaxMind GeoIP (city-level accuracy)
168
+ - **Best for**: Self-hosted deployments, advanced analytics requirements
169
+ - **Endpoint**: Uses `/api/send` for Node.js runtime
170
+ - **Latency**: 50-150ms (regional)
171
+
172
+ **When to use Node.js runtime**:
173
+ - Self-hosted Svelte/SvelteKit deployments without edge runtime support
174
+ - Applications requiring ClickHouse data export
175
+ - Need for advanced geo-targeting with MaxMind
176
+ - Custom server-side analytics workflows
177
+
178
+ ## Tracking Events
179
+
180
+ ### trackEvent
181
+
182
+ ```svelte
183
+ <script>
184
+ import { trackEvent } from '@entrolytics/svelte';
185
+
186
+ function handlePurchase() {
187
+ trackEvent('purchase', {
188
+ revenue: 99.99,
189
+ currency: 'USD'
190
+ });
191
+ }
192
+ </script>
193
+
194
+ <button on:click={handlePurchase}>Buy Now</button>
195
+ ```
196
+
197
+ ### trackClick Action
198
+
199
+ Use the Svelte action for declarative click tracking:
200
+
201
+ ```svelte
202
+ <script>
203
+ import { trackClick } from '@entrolytics/svelte';
204
+ </script>
205
+
206
+ <button use:trackClick={{ event: 'cta_click', data: { variant: 'hero' } }}>
207
+ Get Started
208
+ </button>
209
+ ```
210
+
211
+ ## Page View Tracking
212
+
213
+ ### Automatic (with SvelteKit)
214
+
215
+ ```svelte
216
+ <!-- +layout.svelte -->
217
+ <script>
218
+ import { page } from '$app/stores';
219
+ import { initEntrolytics, usePageView } from '@entrolytics/svelte';
220
+
221
+ initEntrolytics({ websiteId: 'your-website-id' });
222
+ usePageView(page);
223
+ </script>
224
+
225
+ <slot />
226
+ ```
227
+
228
+ ### Manual
229
+
230
+ ```svelte
231
+ <script>
232
+ import { trackPageView } from '@entrolytics/svelte';
233
+
234
+ // Track current page
235
+ trackPageView();
236
+
237
+ // Track specific URL
238
+ trackPageView('/custom-path', 'https://referrer.com');
239
+ </script>
240
+ ```
241
+
242
+ ## User Identification
243
+
244
+ ```svelte
245
+ <script>
246
+ import { identify } from '@entrolytics/svelte';
247
+
248
+ // When user logs in
249
+ function handleLogin(user) {
250
+ identify(user.id, {
251
+ email: user.email,
252
+ plan: user.subscription
253
+ });
254
+ }
255
+ </script>
256
+ ```
257
+
258
+ ## Stores
259
+
260
+ ### isLoaded
261
+
262
+ Check if the tracking script is loaded:
263
+
264
+ ```svelte
265
+ <script>
266
+ import { isLoaded } from '@entrolytics/svelte';
267
+ </script>
268
+
269
+ {#if $isLoaded}
270
+ <p>Analytics loaded!</p>
271
+ {/if}
272
+ ```
273
+
274
+ ## TypeScript
275
+
276
+ Full TypeScript support with exported types:
277
+
278
+ ```ts
279
+ import type { EntrolyticsOptions } from '@entrolytics/svelte';
280
+ ```
281
+
282
+ ## License
283
+
284
+ MIT License - see [LICENSE](LICENSE) file for details.
@@ -0,0 +1,370 @@
1
+ import { Writable } from 'svelte/store';
2
+
3
+ /**
4
+ * Event payload type - mirrors @entrolytics/shared EventPayload
5
+ * TODO: Import from @entrolytics/shared once published with EventPayload export
6
+ */
7
+ interface EventPayload {
8
+ websiteId: string;
9
+ sessionId: string;
10
+ visitorId: string;
11
+ url: string;
12
+ referrer?: string;
13
+ eventType: string;
14
+ eventName?: string;
15
+ properties?: Record<string, unknown>;
16
+ screenWidth?: number;
17
+ screenHeight?: number;
18
+ loadTime?: number;
19
+ domInteractive?: number;
20
+ domComplete?: number;
21
+ utmSource?: string;
22
+ utmMedium?: string;
23
+ utmCampaign?: string;
24
+ utmTerm?: string;
25
+ utmContent?: string;
26
+ }
27
+ type EventData = NonNullable<EventPayload['properties']>;
28
+ interface EntrolyticsOptions {
29
+ websiteId: string;
30
+ host?: string;
31
+ autoTrack?: boolean;
32
+ respectDnt?: boolean;
33
+ domains?: string[];
34
+ /** Use edge runtime endpoints for faster response times (default: true) */
35
+ useEdgeRuntime?: boolean;
36
+ /** Custom tag for A/B testing */
37
+ tag?: string;
38
+ /** Strip query parameters from URLs */
39
+ excludeSearch?: boolean;
40
+ /** Strip hash from URLs */
41
+ excludeHash?: boolean;
42
+ /** Callback before sending data */
43
+ beforeSend?: (type: string, payload: unknown) => unknown | null;
44
+ }
45
+ declare global {
46
+ interface Window {
47
+ entrolytics?: {
48
+ track: (eventName?: string | object, eventData?: Record<string, unknown>) => void;
49
+ identify: (data: Record<string, unknown>) => void;
50
+ };
51
+ }
52
+ }
53
+ declare const isLoaded: Writable<boolean>;
54
+ declare const isReady: Writable<boolean>;
55
+ /**
56
+ * Initialize Entrolytics tracking
57
+ *
58
+ * Call this in your root +layout.svelte
59
+ *
60
+ * @example
61
+ * Zero-config (reads from env):
62
+ * ```svelte
63
+ * <script>
64
+ * import { initEntrolytics } from '@entrolytics/svelte';
65
+ * initEntrolytics();
66
+ * </script>
67
+ * ```
68
+ *
69
+ * @example
70
+ * Explicit config:
71
+ * ```svelte
72
+ * <script>
73
+ * import { initEntrolytics } from '@entrolytics/svelte';
74
+ * initEntrolytics({ websiteId: 'your-website-id' });
75
+ * </script>
76
+ * ```
77
+ */
78
+ declare function initEntrolytics(options?: Partial<EntrolyticsOptions>): void;
79
+ /**
80
+ * Track a custom event
81
+ *
82
+ * @example
83
+ * ```svelte
84
+ * <script>
85
+ * import { trackEvent } from '@entrolytics/svelte';
86
+ *
87
+ * function handleClick() {
88
+ * trackEvent('button_click', { variant: 'primary' });
89
+ * }
90
+ * </script>
91
+ *
92
+ * <button on:click={handleClick}>Click me</button>
93
+ * ```
94
+ */
95
+ declare function trackEvent(eventName: string, eventData?: EventData): void;
96
+ /**
97
+ * Track revenue event
98
+ *
99
+ * @example
100
+ * ```svelte
101
+ * <script>
102
+ * import { trackRevenue } from '@entrolytics/svelte';
103
+ *
104
+ * async function handlePurchase(product) {
105
+ * await processPayment();
106
+ * trackRevenue('purchase', product.price, 'USD', {
107
+ * productId: product.id,
108
+ * productName: product.name
109
+ * });
110
+ * }
111
+ * </script>
112
+ * ```
113
+ */
114
+ declare function trackRevenue(eventName: string, revenue: number, currency?: string, data?: EventData): void;
115
+ /**
116
+ * Track outbound link click
117
+ *
118
+ * @example
119
+ * ```svelte
120
+ * <script>
121
+ * import { trackOutboundLink } from '@entrolytics/svelte';
122
+ *
123
+ * function handleExternalClick(url: string) {
124
+ * trackOutboundLink(url, { placement: 'sidebar' });
125
+ * }
126
+ * </script>
127
+ * ```
128
+ */
129
+ declare function trackOutboundLink(url: string, data?: EventData): void;
130
+ /**
131
+ * Identify with custom data
132
+ *
133
+ * @example
134
+ * ```svelte
135
+ * <script>
136
+ * import { identify } from '@entrolytics/svelte';
137
+ *
138
+ * identify({ company: 'Acme Corp', plan: 'enterprise' });
139
+ * </script>
140
+ * ```
141
+ */
142
+ declare function identify(data: EventData): void;
143
+ /**
144
+ * Identify a user by ID
145
+ *
146
+ * @example
147
+ * ```svelte
148
+ * <script>
149
+ * import { identifyUser } from '@entrolytics/svelte';
150
+ *
151
+ * // When user logs in
152
+ * identifyUser(user.id, { email: user.email, plan: user.plan });
153
+ * </script>
154
+ * ```
155
+ */
156
+ declare function identifyUser(userId: string, traits?: EventData): void;
157
+ /**
158
+ * Set tag for A/B testing
159
+ */
160
+ declare function setTag(tag: string): void;
161
+ /**
162
+ * Track page view manually
163
+ * Useful for SPA navigation
164
+ */
165
+ declare function trackPageView(url?: string, referrer?: string): void;
166
+ /**
167
+ * Svelte action for tracking clicks
168
+ *
169
+ * @example
170
+ * ```svelte
171
+ * <script>
172
+ * import { trackClick } from '@entrolytics/svelte';
173
+ * </script>
174
+ *
175
+ * <button use:trackClick={{ event: 'cta_click', data: { variant: 'hero' } }}>
176
+ * Click me
177
+ * </button>
178
+ * ```
179
+ */
180
+ declare function trackClick(node: HTMLElement, params: {
181
+ event: string;
182
+ data?: EventData;
183
+ }): {
184
+ update(newParams: {
185
+ event: string;
186
+ data?: EventData;
187
+ }): void;
188
+ destroy(): void;
189
+ };
190
+ /**
191
+ * Svelte action for tracking outbound links
192
+ *
193
+ * @example
194
+ * ```svelte
195
+ * <a href="https://example.com" use:outboundLink={{ data: { placement: 'footer' } }}>
196
+ * Visit Example
197
+ * </a>
198
+ * ```
199
+ */
200
+ declare function outboundLink(node: HTMLAnchorElement, params?: {
201
+ data?: EventData;
202
+ }): {
203
+ update(newParams?: {
204
+ data?: EventData;
205
+ }): void;
206
+ destroy(): void;
207
+ };
208
+ /**
209
+ * Hook for tracking page views in SvelteKit
210
+ *
211
+ * Use in +layout.svelte to auto-track navigation
212
+ *
213
+ * @example
214
+ * ```svelte
215
+ * <script>
216
+ * import { page } from '$app/stores';
217
+ * import { usePageView } from '@entrolytics/svelte';
218
+ *
219
+ * usePageView(page);
220
+ * </script>
221
+ * ```
222
+ */
223
+ declare function usePageView(pageStore: {
224
+ subscribe: (fn: (value: {
225
+ url: URL;
226
+ }) => void) => () => void;
227
+ }): void;
228
+ type WebVitalMetric = 'LCP' | 'INP' | 'CLS' | 'TTFB' | 'FCP';
229
+ type WebVitalRating = 'good' | 'needs-improvement' | 'poor';
230
+ type NavigationType = 'navigate' | 'reload' | 'back-forward' | 'back-forward-cache' | 'prerender' | 'restore';
231
+ interface WebVitalData {
232
+ metric: WebVitalMetric;
233
+ value: number;
234
+ rating: WebVitalRating;
235
+ delta?: number;
236
+ id?: string;
237
+ navigationType?: NavigationType;
238
+ attribution?: Record<string, unknown>;
239
+ }
240
+ /**
241
+ * Track a Web Vital metric
242
+ *
243
+ * @example
244
+ * ```svelte
245
+ * <script>
246
+ * import { onLCP, onINP, onCLS } from 'web-vitals';
247
+ * import { trackVital } from '@entrolytics/svelte';
248
+ *
249
+ * onMount(() => {
250
+ * onLCP((metric) => trackVital({
251
+ * metric: 'LCP',
252
+ * value: metric.value,
253
+ * rating: metric.rating
254
+ * }));
255
+ * });
256
+ * </script>
257
+ * ```
258
+ */
259
+ declare function trackVital(data: WebVitalData): Promise<void>;
260
+ /**
261
+ * Initialize automatic Web Vitals tracking
262
+ * Call this in your root +layout.svelte
263
+ *
264
+ * @example
265
+ * ```svelte
266
+ * <script>
267
+ * import { initWebVitals } from '@entrolytics/svelte';
268
+ * import { onMount } from 'svelte';
269
+ *
270
+ * onMount(() => {
271
+ * initWebVitals();
272
+ * });
273
+ * </script>
274
+ * ```
275
+ */
276
+ declare function initWebVitals(): Promise<void>;
277
+ type FormEventType = 'start' | 'field_focus' | 'field_blur' | 'field_error' | 'submit' | 'abandon';
278
+ interface FormEventData {
279
+ eventType: FormEventType;
280
+ formId: string;
281
+ formName?: string;
282
+ urlPath?: string;
283
+ fieldName?: string;
284
+ fieldType?: string;
285
+ fieldIndex?: number;
286
+ timeOnField?: number;
287
+ timeSinceStart?: number;
288
+ errorMessage?: string;
289
+ success?: boolean;
290
+ }
291
+ /**
292
+ * Track a form event
293
+ *
294
+ * @example
295
+ * ```svelte
296
+ * <script>
297
+ * import { trackFormEvent } from '@entrolytics/svelte';
298
+ *
299
+ * async function handleSubmit() {
300
+ * const success = await submitForm();
301
+ * trackFormEvent({
302
+ * eventType: 'submit',
303
+ * formId: 'contact-form',
304
+ * success
305
+ * });
306
+ * }
307
+ * </script>
308
+ * ```
309
+ */
310
+ declare function trackFormEvent(data: FormEventData): Promise<void>;
311
+ /**
312
+ * Create a form tracker for a specific form
313
+ *
314
+ * @example
315
+ * ```svelte
316
+ * <script>
317
+ * import { createFormTracker } from '@entrolytics/svelte';
318
+ *
319
+ * const tracker = createFormTracker('signup-form', 'Signup Form');
320
+ *
321
+ * function handleSubmit() {
322
+ * const success = await submit();
323
+ * tracker.trackSubmit(success);
324
+ * }
325
+ * </script>
326
+ *
327
+ * <form on:submit|preventDefault={handleSubmit}>
328
+ * <input
329
+ * name="email"
330
+ * on:focus={() => tracker.trackFieldFocus('email', 'email', 0)}
331
+ * on:blur={() => tracker.trackFieldBlur('email', 'email', 0)}
332
+ * />
333
+ * </form>
334
+ * ```
335
+ */
336
+ declare function createFormTracker(formId: string, formName?: string): {
337
+ trackStart: () => void;
338
+ trackFieldFocus: (fieldName: string, fieldType?: string, fieldIndex?: number) => void;
339
+ trackFieldBlur: (fieldName: string, fieldType?: string, fieldIndex?: number) => void;
340
+ trackFieldError: (fieldName: string, errorMessage: string, fieldType?: string, fieldIndex?: number) => void;
341
+ trackSubmit: (success: boolean) => void;
342
+ trackAbandon: () => void;
343
+ };
344
+ /**
345
+ * Svelte action for automatic form tracking
346
+ *
347
+ * @example
348
+ * ```svelte
349
+ * <script>
350
+ * import { trackForm } from '@entrolytics/svelte';
351
+ * </script>
352
+ *
353
+ * <form use:trackForm={{ formId: 'contact', formName: 'Contact Form' }}>
354
+ * <input name="email" type="email" />
355
+ * <button type="submit">Send</button>
356
+ * </form>
357
+ * ```
358
+ */
359
+ declare function trackForm(node: HTMLFormElement, params: {
360
+ formId: string;
361
+ formName?: string;
362
+ }): {
363
+ update(newParams: {
364
+ formId: string;
365
+ formName?: string;
366
+ }): void;
367
+ destroy(): void;
368
+ };
369
+
370
+ export { type EntrolyticsOptions, type EventData, type FormEventData, type FormEventType, type NavigationType, type WebVitalData, type WebVitalMetric, type WebVitalRating, createFormTracker, identify, identifyUser, initEntrolytics, initWebVitals, isLoaded, isReady, outboundLink, setTag, trackClick, trackEvent, trackForm, trackFormEvent, trackOutboundLink, trackPageView, trackRevenue, trackVital, usePageView };