@vllnt/analytics 0.1.0-canary.a05802e

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 vllnt
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,203 @@
1
+ # @vllnt/analytics
2
+
3
+ Lightweight, privacy-first analytics library with consent management and React integration.
4
+
5
+ ## Features
6
+
7
+ - **Event tracking** with pre-init queuing (no lost events during hydration)
8
+ - **Consent management** — two categories (analytics + functional), localStorage + SSR cookie
9
+ - **Versioned consent** — bump version to re-prompt users
10
+ - **Do Not Track** — respects browser DNT setting
11
+ - **SSR-safe** — all browser APIs guarded
12
+ - **Zero external analytics dependencies** — bring your own backend (Vercel Analytics, GA, custom)
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pnpm add @vllnt/analytics
18
+ ```
19
+
20
+ Peer dependency: `react ^18.0.0 || ^19.0.0`
21
+
22
+ ## Usage
23
+
24
+ ### React Provider
25
+
26
+ ```tsx
27
+ import { AnalyticsProvider } from '@vllnt/analytics/react'
28
+
29
+ function App() {
30
+ return (
31
+ <AnalyticsProvider config={{ app: 'my-app', version: 1, debug: true }}>
32
+ {children}
33
+ </AnalyticsProvider>
34
+ )
35
+ }
36
+ ```
37
+
38
+ ### Consent Banner
39
+
40
+ ```tsx
41
+ import { useConsent } from '@vllnt/analytics/react'
42
+
43
+ function CookieBanner() {
44
+ const { hasResponded, isLoading, acceptAll, declineAnalytics } = useConsent()
45
+
46
+ if (isLoading || hasResponded) return null
47
+
48
+ return (
49
+ <div>
50
+ <p>We use cookies for analytics.</p>
51
+ <button onClick={acceptAll}>Accept</button>
52
+ <button onClick={declineAnalytics}>Decline</button>
53
+ </div>
54
+ )
55
+ }
56
+ ```
57
+
58
+ ### Track Events
59
+
60
+ ```tsx
61
+ import { track, trackPage } from '@vllnt/analytics'
62
+
63
+ // Generic event
64
+ track('button_click', { id: 'cta-hero' })
65
+
66
+ // Page view
67
+ trackPage({ path: '/about' })
68
+ ```
69
+
70
+ ### Tutorial Tracking
71
+
72
+ Typed helpers for tutorial/content flows:
73
+
74
+ ```tsx
75
+ import {
76
+ trackTutorialStart,
77
+ trackSectionView,
78
+ trackSectionComplete,
79
+ trackTutorialComplete,
80
+ trackTutorialNavigation,
81
+ trackTimeSpent,
82
+ } from '@vllnt/analytics'
83
+
84
+ trackTutorialStart({
85
+ tutorial_id: 'getting-started',
86
+ tutorial_title: 'Getting Started',
87
+ locale: 'en',
88
+ total_sections: 5,
89
+ })
90
+
91
+ trackSectionView({
92
+ tutorial_id: 'getting-started',
93
+ tutorial_title: 'Getting Started',
94
+ locale: 'en',
95
+ section_id: 'intro',
96
+ section_index: 0,
97
+ total_sections: 5,
98
+ })
99
+ ```
100
+
101
+ ### Identify Users
102
+
103
+ ```tsx
104
+ import { identify, resetAnalytics } from '@vllnt/analytics'
105
+
106
+ // After login
107
+ identify('user-123', { plan: 'pro' })
108
+
109
+ // After logout
110
+ resetAnalytics()
111
+ ```
112
+
113
+ ### Consent Utilities (non-React)
114
+
115
+ ```ts
116
+ import {
117
+ loadConsent,
118
+ saveConsent,
119
+ clearConsent,
120
+ createAcceptAllConsent,
121
+ createDeclineAnalyticsConsent,
122
+ getConsentFromCookie,
123
+ isDoNotTrackEnabled,
124
+ needsRePrompt,
125
+ } from '@vllnt/analytics'
126
+
127
+ // SSR: read consent from cookie header
128
+ const analyticsAllowed = getConsentFromCookie(request.headers.cookie)
129
+
130
+ // Check if re-prompt needed after version bump
131
+ const consent = loadConsent()
132
+ if (consent && needsRePrompt(consent, 2)) {
133
+ clearConsent()
134
+ }
135
+ ```
136
+
137
+ ## API
138
+
139
+ ### Core
140
+
141
+ | Function | Description |
142
+ |---|---|
143
+ | `initAnalytics(config)` | Initialize analytics singleton |
144
+ | `track(name, properties?)` | Track a custom event |
145
+ | `trackPage(properties?)` | Track a page view |
146
+ | `identify(userId, traits?)` | Identify a user |
147
+ | `resetAnalytics()` | Clear user identity (logout) |
148
+ | `enableAnalytics(config)` | Re-enable after consent granted |
149
+ | `disableAnalytics()` | Disable after consent revoked |
150
+ | `isAnalyticsEnabled()` | Check if tracking is active |
151
+
152
+ ### Consent
153
+
154
+ | Function | Description |
155
+ |---|---|
156
+ | `loadConsent()` | Load consent from localStorage |
157
+ | `saveConsent(state)` | Persist consent to localStorage + cookie |
158
+ | `clearConsent()` | Remove consent (triggers re-prompt) |
159
+ | `createAcceptAllConsent()` | Create accept-all consent state |
160
+ | `createDeclineAnalyticsConsent()` | Create analytics-declined state |
161
+ | `updateConsentCategory(state, category, value)` | Update a single category |
162
+ | `needsRePrompt(consent, version)` | Check if version requires re-prompt |
163
+ | `getConsentFromCookie(cookieString)` | Parse consent from cookie (SSR) |
164
+ | `isDoNotTrackEnabled()` | Check browser DNT setting |
165
+
166
+ ### React (`@vllnt/analytics/react`)
167
+
168
+ | Export | Description |
169
+ |---|---|
170
+ | `AnalyticsProvider` | Context provider — wires consent + analytics init |
171
+ | `useAnalytics()` | Access full analytics context |
172
+ | `useConsent(options?)` | Standalone consent hook for banner UIs |
173
+
174
+ ## How It Works
175
+
176
+ ```
177
+ User visits site
178
+ │
179
+ ├─ DNT enabled? ──▶ Block all tracking
180
+ │
181
+ ├─ Consent exists?
182
+ │ ├─ Version outdated? ──▶ Clear & re-prompt
183
+ │ ├─ Analytics declined? ──▶ Block tracking
184
+ │ └─ Analytics accepted ──▶ Initialize & flush queue
185
+ │
186
+ └─ No consent ──▶ Queue events until user responds
187
+ ```
188
+
189
+ Events fired before initialization are queued and flushed once consent is granted and analytics initializes.
190
+
191
+ ## Scripts
192
+
193
+ ```bash
194
+ pnpm test # Run tests (watch mode)
195
+ pnpm test:once # Run tests once
196
+ pnpm test:coverage # Run with coverage
197
+ pnpm lint # Lint
198
+ pnpm lint:fix # Lint + autofix
199
+ ```
200
+
201
+ ## License
202
+
203
+ [MIT](LICENSE)
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "@vllnt/analytics",
3
+ "version": "0.1.0-canary.a05802e",
4
+ "description": "Lightweight, privacy-first analytics with consent management and React integration",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/vllnt/analytics.git"
10
+ },
11
+ "keywords": [
12
+ "analytics",
13
+ "consent",
14
+ "privacy",
15
+ "gdpr",
16
+ "react",
17
+ "do-not-track"
18
+ ],
19
+ "sideEffects": false,
20
+ "files": [
21
+ "src",
22
+ "!src/__tests__",
23
+ "README.md",
24
+ "LICENSE"
25
+ ],
26
+ "main": "./src/index.ts",
27
+ "module": "./src/index.ts",
28
+ "types": "./src/index.ts",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./src/index.ts",
32
+ "import": "./src/index.ts",
33
+ "require": "./src/index.ts"
34
+ },
35
+ "./react": {
36
+ "types": "./src/react.tsx",
37
+ "import": "./src/react.tsx",
38
+ "require": "./src/react.tsx"
39
+ }
40
+ },
41
+ "peerDependencies": {
42
+ "react": "^18.0.0 || ^19.0.0"
43
+ },
44
+ "devDependencies": {
45
+ "eslint": "^9.39.1",
46
+ "@testing-library/jest-dom": "^6.9.1",
47
+ "@testing-library/react": "^16.3.0",
48
+ "@types/node": "^22",
49
+ "@types/react": "^19.1.6",
50
+ "@vitest/coverage-v8": "^4.0.16",
51
+ "@vllnt/eslint-config": "^1.0.0",
52
+ "@vllnt/typescript": "^1.0.0",
53
+ "jsdom": "^26.1.0",
54
+ "react": "^19.2.0",
55
+ "typescript": "^5.9.3",
56
+ "vitest": "^4.0.16"
57
+ },
58
+ "scripts": {
59
+ "clean": "rm -rf node_modules",
60
+ "lint": "eslint .",
61
+ "lint:fix": "eslint . --fix",
62
+ "test": "vitest",
63
+ "test:once": "vitest run",
64
+ "test:coverage": "vitest run --coverage"
65
+ }
66
+ }
@@ -0,0 +1,305 @@
1
+ // Lightweight custom analytics implementation
2
+ // Replaces external 'analytics' package with minimal implementation
3
+
4
+ import { isDoNotTrackEnabled, loadConsent } from "./consent";
5
+ import type {
6
+ AnalyticsConfig,
7
+ AnalyticsEvent,
8
+ TutorialEventName,
9
+ TutorialEventProperties,
10
+ } from "./types";
11
+
12
+ // Analytics state (singleton)
13
+ type AnalyticsState = {
14
+ app: string;
15
+ debug?: boolean;
16
+ traits?: Record<string, unknown>;
17
+ userId?: string;
18
+ version?: number;
19
+ };
20
+
21
+ let analyticsState: AnalyticsState | undefined;
22
+
23
+ // Queue for events before initialization
24
+ let eventQueue: AnalyticsEvent[] = [];
25
+
26
+ // Track initialization state
27
+ let isInitialized = false;
28
+ let isBlocked = false;
29
+
30
+ /**
31
+ * Reset analytics state (for testing only)
32
+ * @internal
33
+ */
34
+ export function _resetAnalyticsState(): void {
35
+ analyticsState = undefined;
36
+ eventQueue = [];
37
+ isInitialized = false;
38
+ isBlocked = false;
39
+ }
40
+
41
+ /**
42
+ * Log event in debug mode
43
+ */
44
+ function debugLog(type: string, data: unknown): void {
45
+ if (analyticsState?.debug) {
46
+ // eslint-disable-next-line no-console -- Debug logging is intentional
47
+ console.log(`[analytics:${type}]`, data);
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Send event to analytics endpoint or external service
53
+ * This is where you'd integrate with Vercel Analytics, GA, etc.
54
+ */
55
+ function sendEvent(name: string, properties?: Record<string, unknown>): void {
56
+ debugLog("track", { name, properties });
57
+
58
+ // Integration point: Forward to Vercel Analytics or other services
59
+ // Vercel Analytics integration is handled by the React provider
60
+ // This function serves as the central tracking point
61
+
62
+ // For custom backends, you could send to an API endpoint:
63
+ // fetch('/api/analytics', { method: 'POST', body: JSON.stringify({ name, properties }) })
64
+ }
65
+
66
+ /**
67
+ * Initialize analytics with configuration
68
+ */
69
+ export function initAnalytics(config: AnalyticsConfig): void {
70
+ if (analyticsState) return;
71
+
72
+ // Check Do Not Track
73
+ if (isDoNotTrackEnabled()) {
74
+ isBlocked = true;
75
+ debugLog("init", "Do Not Track enabled, analytics blocked");
76
+ return;
77
+ }
78
+
79
+ // Check consent
80
+ const consent = loadConsent();
81
+ if (consent && !consent.analytics) {
82
+ isBlocked = true;
83
+ debugLog("init", "Analytics consent declined");
84
+ return;
85
+ }
86
+
87
+ analyticsState = {
88
+ app: config.app,
89
+ debug: config.debug,
90
+ version: config.version,
91
+ };
92
+
93
+ isInitialized = true;
94
+
95
+ debugLog("init", { app: config.app, version: config.version });
96
+
97
+ // Process queued events
98
+ processQueue();
99
+ }
100
+
101
+ /**
102
+ * Process queued events after initialization
103
+ */
104
+ function processQueue(): void {
105
+ if (!analyticsState || isBlocked) return;
106
+
107
+ // Process and clear the queue
108
+ const queue = [...eventQueue];
109
+ eventQueue = [];
110
+
111
+ for (const event of queue) {
112
+ if (event.name === "__page__") {
113
+ debugLog("page", event.properties);
114
+ } else {
115
+ sendEvent(event.name, event.properties);
116
+ }
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Track a custom event
122
+ */
123
+ export function track(
124
+ name: string,
125
+ properties?: Record<string, unknown>,
126
+ ): void {
127
+ if (typeof window === "undefined") return;
128
+
129
+ if (isBlocked) return;
130
+
131
+ const event: AnalyticsEvent = {
132
+ name,
133
+ properties,
134
+ timestamp: new Date().toISOString(),
135
+ };
136
+
137
+ if (!isInitialized) {
138
+ eventQueue.push(event);
139
+ return;
140
+ }
141
+
142
+ sendEvent(name, properties);
143
+ }
144
+
145
+ /**
146
+ * Track a page view
147
+ */
148
+ export function trackPage(properties?: Record<string, unknown>): void {
149
+ if (typeof window === "undefined") return;
150
+ if (isBlocked) return;
151
+
152
+ if (!isInitialized) {
153
+ eventQueue.push({
154
+ name: "__page__",
155
+ properties,
156
+ timestamp: new Date().toISOString(),
157
+ });
158
+ return;
159
+ }
160
+
161
+ debugLog("page", properties);
162
+ }
163
+
164
+ /**
165
+ * Identify a user
166
+ */
167
+ export function identify(
168
+ userId: string,
169
+ traits?: Record<string, unknown>,
170
+ ): void {
171
+ if (typeof window === "undefined") return;
172
+ if (isBlocked) return;
173
+
174
+ if (!isInitialized || !analyticsState) {
175
+ return;
176
+ }
177
+
178
+ analyticsState.userId = userId;
179
+ analyticsState.traits = traits;
180
+
181
+ debugLog("identify", { traits, userId });
182
+ }
183
+
184
+ /**
185
+ * Reset analytics state (on logout)
186
+ */
187
+ export function resetAnalytics(): void {
188
+ if (typeof window === "undefined") return;
189
+
190
+ if (analyticsState) {
191
+ analyticsState.userId = undefined;
192
+ analyticsState.traits = undefined;
193
+ }
194
+
195
+ debugLog("reset", undefined);
196
+ }
197
+
198
+ /**
199
+ * Enable analytics after consent is given
200
+ */
201
+ export function enableAnalytics(config: AnalyticsConfig): void {
202
+ if (isBlocked && !isDoNotTrackEnabled()) {
203
+ isBlocked = false;
204
+ analyticsState = undefined;
205
+ initAnalytics(config);
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Disable analytics after consent is revoked.
211
+ * NOTE: Does not clear in-memory userId/traits (GDPR Art. 17 limitation).
212
+ * Callers should trigger a page reload or call resetAnalytics() to purge PII.
213
+ */
214
+ export function disableAnalytics(): void {
215
+ isBlocked = true;
216
+ eventQueue.length = 0; // Clear queue
217
+ }
218
+
219
+ /**
220
+ * Check if analytics is currently enabled
221
+ */
222
+ export function isAnalyticsEnabled(): boolean {
223
+ return isInitialized && !isBlocked;
224
+ }
225
+
226
+ /**
227
+ * Get current analytics state (for advanced usage/debugging)
228
+ */
229
+ export function getAnalyticsState(): AnalyticsState | undefined {
230
+ return analyticsState;
231
+ }
232
+
233
+ // Tutorial-specific tracking helpers
234
+
235
+ /**
236
+ * Track tutorial start
237
+ */
238
+ export function trackTutorialStart(
239
+ properties: Omit<TutorialEventProperties, "section_id">,
240
+ ): void {
241
+ track(
242
+ "tutorial_start" satisfies TutorialEventName,
243
+ properties as Record<string, unknown>,
244
+ );
245
+ }
246
+
247
+ /**
248
+ * Track section view
249
+ */
250
+ export function trackSectionView(properties: TutorialEventProperties): void {
251
+ track(
252
+ "tutorial_section_view" satisfies TutorialEventName,
253
+ properties as Record<string, unknown>,
254
+ );
255
+ }
256
+
257
+ /**
258
+ * Track section completion
259
+ */
260
+ export function trackSectionComplete(
261
+ properties: TutorialEventProperties,
262
+ ): void {
263
+ track(
264
+ "tutorial_section_complete" satisfies TutorialEventName,
265
+ properties as Record<string, unknown>,
266
+ );
267
+ }
268
+
269
+ /**
270
+ * Track tutorial completion
271
+ */
272
+ export function trackTutorialComplete(
273
+ properties: Omit<TutorialEventProperties, "section_id">,
274
+ ): void {
275
+ track(
276
+ "tutorial_complete" satisfies TutorialEventName,
277
+ properties as Record<string, unknown>,
278
+ );
279
+ }
280
+
281
+ /**
282
+ * Track navigation between sections
283
+ */
284
+ export function trackTutorialNavigation(
285
+ properties: TutorialEventProperties & {
286
+ navigation_type: "keyboard" | "next" | "prev" | "toc";
287
+ },
288
+ ): void {
289
+ track(
290
+ "tutorial_navigation" satisfies TutorialEventName,
291
+ properties as Record<string, unknown>,
292
+ );
293
+ }
294
+
295
+ /**
296
+ * Track time spent on a section
297
+ */
298
+ export function trackTimeSpent(
299
+ properties: TutorialEventProperties & { time_spent_seconds: number },
300
+ ): void {
301
+ track(
302
+ "tutorial_time_spent" satisfies TutorialEventName,
303
+ properties as Record<string, unknown>,
304
+ );
305
+ }
package/src/consent.ts ADDED
@@ -0,0 +1,175 @@
1
+ import type { ConsentCategory, ConsentState } from "./types";
2
+
3
+ /** Current consent schema version - bump to re-prompt users */
4
+ export const CONSENT_VERSION = 1;
5
+
6
+ /** localStorage key for consent state */
7
+ export const CONSENT_STORAGE_KEY = "vllnt:analytics-consent";
8
+
9
+ /** Cookie name for SSR consent detection */
10
+ export const CONSENT_COOKIE_NAME = "vllnt-consent";
11
+
12
+ /**
13
+ * Type guard to validate consent state from storage
14
+ */
15
+ export function isValidConsentState(value: unknown): value is ConsentState {
16
+ if (typeof value !== "object" || value === null) return false;
17
+
18
+ const state = value as Record<string, unknown>;
19
+
20
+ return (
21
+ typeof state.analytics === "boolean" &&
22
+ typeof state.functional === "boolean" &&
23
+ typeof state.timestamp === "string" &&
24
+ typeof state.version === "number"
25
+ );
26
+ }
27
+
28
+ /**
29
+ * Check if localStorage is available
30
+ */
31
+ export function isStorageAvailable(): boolean {
32
+ if (typeof window === "undefined") return false;
33
+
34
+ try {
35
+ const testKey = "__storage_test__";
36
+ localStorage.setItem(testKey, testKey);
37
+ localStorage.removeItem(testKey);
38
+ return true;
39
+ } catch {
40
+ return false;
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Load consent state from localStorage
46
+ */
47
+ export function loadConsent(): ConsentState | null {
48
+ if (!isStorageAvailable()) return null;
49
+
50
+ try {
51
+ const raw = localStorage.getItem(CONSENT_STORAGE_KEY);
52
+ if (!raw) return null;
53
+
54
+ const parsed: unknown = JSON.parse(raw);
55
+ if (!isValidConsentState(parsed)) return null;
56
+
57
+ return parsed;
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Save consent state to localStorage and cookie
65
+ */
66
+ export function saveConsent(state: ConsentState): void {
67
+ if (!isStorageAvailable()) return;
68
+
69
+ try {
70
+ localStorage.setItem(CONSENT_STORAGE_KEY, JSON.stringify(state));
71
+
72
+ // Also set a cookie for SSR detection (1 year expiry)
73
+ const expires = new Date();
74
+ expires.setFullYear(expires.getFullYear() + 1);
75
+
76
+ // Cookie value: "1" for analytics allowed, "0" for declined
77
+ const cookieValue = state.analytics ? "1" : "0";
78
+ document.cookie = `${CONSENT_COOKIE_NAME}=${cookieValue}; expires=${expires.toUTCString()}; path=/; SameSite=Lax`;
79
+ } catch (error) {
80
+ console.warn("Failed to save consent:", error);
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Clear consent state (for re-prompting)
86
+ */
87
+ export function clearConsent(): void {
88
+ if (!isStorageAvailable()) return;
89
+
90
+ try {
91
+ localStorage.removeItem(CONSENT_STORAGE_KEY);
92
+
93
+ // Clear cookie
94
+ document.cookie = `${CONSENT_COOKIE_NAME}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Lax`;
95
+ } catch {
96
+ // Ignore errors during cleanup
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Create a new consent state with all categories accepted
102
+ */
103
+ export function createAcceptAllConsent(): ConsentState {
104
+ return {
105
+ analytics: true,
106
+ functional: true,
107
+ timestamp: new Date().toISOString(),
108
+ version: CONSENT_VERSION,
109
+ };
110
+ }
111
+
112
+ /**
113
+ * Create a consent state with analytics declined
114
+ */
115
+ export function createDeclineAnalyticsConsent(): ConsentState {
116
+ return {
117
+ analytics: false,
118
+ functional: true, // Functional always enabled
119
+ timestamp: new Date().toISOString(),
120
+ version: CONSENT_VERSION,
121
+ };
122
+ }
123
+
124
+ /**
125
+ * Update a specific consent category
126
+ */
127
+ export function updateConsentCategory(
128
+ current: ConsentState,
129
+ category: ConsentCategory,
130
+ value: boolean,
131
+ ): ConsentState {
132
+ // Functional cookies cannot be disabled
133
+ if (category === "functional" && !value) {
134
+ return current;
135
+ }
136
+
137
+ return {
138
+ ...current,
139
+ [category]: value,
140
+ timestamp: new Date().toISOString(),
141
+ };
142
+ }
143
+
144
+ /**
145
+ * Check if consent needs to be re-prompted (version mismatch)
146
+ */
147
+ export function needsRePrompt(
148
+ consent: ConsentState,
149
+ currentVersion: number,
150
+ ): boolean {
151
+ return consent.version < currentVersion;
152
+ }
153
+
154
+ /**
155
+ * Check Do Not Track browser setting
156
+ */
157
+ export function isDoNotTrackEnabled(): boolean {
158
+ if (typeof window === "undefined") return false;
159
+
160
+ const dnt =
161
+ navigator.doNotTrack ||
162
+ (window as unknown as { doNotTrack?: string }).doNotTrack ||
163
+ (navigator as unknown as { msDoNotTrack?: string }).msDoNotTrack;
164
+
165
+ return dnt === "1" || dnt === "yes";
166
+ }
167
+
168
+ /**
169
+ * Get consent from cookie (for SSR)
170
+ */
171
+ export function getConsentFromCookie(cookieString: string): boolean | null {
172
+ const match = new RegExp(`${CONSENT_COOKIE_NAME}=([^;]+)`).exec(cookieString);
173
+ if (!match) return null;
174
+ return match[1] === "1";
175
+ }
package/src/index.ts ADDED
@@ -0,0 +1,48 @@
1
+ // Core analytics
2
+ export {
3
+ disableAnalytics,
4
+ enableAnalytics,
5
+ getAnalyticsState,
6
+ identify,
7
+ initAnalytics,
8
+ isAnalyticsEnabled,
9
+ resetAnalytics,
10
+ track,
11
+ trackPage,
12
+ trackSectionComplete,
13
+ trackSectionView,
14
+ trackTimeSpent,
15
+ trackTutorialComplete,
16
+ trackTutorialNavigation,
17
+ trackTutorialStart,
18
+ } from "./analytics";
19
+
20
+ // Consent management
21
+ export {
22
+ clearConsent,
23
+ CONSENT_COOKIE_NAME,
24
+ CONSENT_STORAGE_KEY,
25
+ CONSENT_VERSION,
26
+ createAcceptAllConsent,
27
+ createDeclineAnalyticsConsent,
28
+ getConsentFromCookie,
29
+ isDoNotTrackEnabled,
30
+ isStorageAvailable,
31
+ isValidConsentState,
32
+ loadConsent,
33
+ needsRePrompt,
34
+ saveConsent,
35
+ updateConsentCategory,
36
+ } from "./consent";
37
+
38
+ // Types
39
+ export type {
40
+ AnalyticsConfig,
41
+ AnalyticsEvent,
42
+ ConsentCategory,
43
+ ConsentState,
44
+ TutorialEventName,
45
+ TutorialEventProperties,
46
+ UseConsentOptions,
47
+ UseConsentReturn,
48
+ } from "./types";
package/src/react.tsx ADDED
@@ -0,0 +1,221 @@
1
+ "use client";
2
+
3
+ import {
4
+ createContext,
5
+ type ReactNode,
6
+ useCallback,
7
+ useContext,
8
+ useEffect,
9
+ useMemo,
10
+ useState,
11
+ } from "react";
12
+
13
+ import { disableAnalytics, enableAnalytics, initAnalytics } from "./analytics";
14
+ import {
15
+ clearConsent,
16
+ CONSENT_VERSION,
17
+ createAcceptAllConsent,
18
+ createDeclineAnalyticsConsent,
19
+ loadConsent,
20
+ needsRePrompt,
21
+ saveConsent,
22
+ updateConsentCategory,
23
+ } from "./consent";
24
+ import type {
25
+ AnalyticsConfig,
26
+ ConsentCategory,
27
+ ConsentState,
28
+ UseConsentOptions,
29
+ UseConsentReturn,
30
+ } from "./types";
31
+
32
+ // Context for analytics configuration
33
+ type AnalyticsContextValue = {
34
+ acceptAll: () => void;
35
+ config: AnalyticsConfig;
36
+ consent: ConsentState | null;
37
+ declineAnalytics: () => void;
38
+ hasResponded: boolean;
39
+ isLoading: boolean;
40
+ resetConsent: () => void;
41
+ updateConsent: (category: ConsentCategory, value: boolean) => void;
42
+ };
43
+
44
+ const AnalyticsContext = createContext<AnalyticsContextValue | null>(null);
45
+
46
+ /**
47
+ * Analytics provider component
48
+ */
49
+ export function AnalyticsProvider({
50
+ children,
51
+ config,
52
+ consentVersion = CONSENT_VERSION,
53
+ }: {
54
+ children: ReactNode;
55
+ config: AnalyticsConfig;
56
+ consentVersion?: number;
57
+ }) {
58
+ const [consent, setConsent] = useState<ConsentState | null>(() => {
59
+ const stored = loadConsent();
60
+ if (!stored) return null;
61
+ if (needsRePrompt(stored, consentVersion)) {
62
+ clearConsent();
63
+ return null;
64
+ }
65
+ return stored;
66
+ });
67
+
68
+ const [hasResponded, setHasResponded] = useState(() => consent !== null);
69
+
70
+ // Initialize analytics if stored consent allows
71
+ useEffect(() => {
72
+ if (consent?.analytics) {
73
+ initAnalytics(config);
74
+ }
75
+ }, [consent, config]);
76
+
77
+ const acceptAll = useCallback(() => {
78
+ const newConsent = createAcceptAllConsent();
79
+ saveConsent(newConsent);
80
+ setConsent(newConsent);
81
+ setHasResponded(true);
82
+ enableAnalytics(config);
83
+ }, [config]);
84
+
85
+ const declineAnalytics = useCallback(() => {
86
+ const newConsent = createDeclineAnalyticsConsent();
87
+ saveConsent(newConsent);
88
+ setConsent(newConsent);
89
+ setHasResponded(true);
90
+ disableAnalytics();
91
+ }, []);
92
+
93
+ const updateConsentHandler = useCallback(
94
+ (category: ConsentCategory, value: boolean) => {
95
+ if (!consent) return;
96
+
97
+ const newConsent = updateConsentCategory(consent, category, value);
98
+ saveConsent(newConsent);
99
+ setConsent(newConsent);
100
+
101
+ // Update analytics state
102
+ if (category === "analytics") {
103
+ if (value) {
104
+ enableAnalytics(config);
105
+ } else {
106
+ disableAnalytics();
107
+ }
108
+ }
109
+ },
110
+ [consent, config],
111
+ );
112
+
113
+ const resetConsentHandler = useCallback(() => {
114
+ clearConsent();
115
+ setConsent(null);
116
+ setHasResponded(false);
117
+ disableAnalytics();
118
+ }, []);
119
+
120
+ const value = useMemo<AnalyticsContextValue>(
121
+ () => ({
122
+ acceptAll,
123
+ config,
124
+ consent,
125
+ declineAnalytics,
126
+ hasResponded,
127
+ isLoading: false,
128
+ resetConsent: resetConsentHandler,
129
+ updateConsent: updateConsentHandler,
130
+ }),
131
+ [
132
+ config,
133
+ consent,
134
+ hasResponded,
135
+ acceptAll,
136
+ declineAnalytics,
137
+ updateConsentHandler,
138
+ resetConsentHandler,
139
+ ],
140
+ );
141
+
142
+ return (
143
+ <AnalyticsContext.Provider value={value}>
144
+ {children}
145
+ </AnalyticsContext.Provider>
146
+ );
147
+ }
148
+
149
+ /**
150
+ * Hook to access analytics context
151
+ */
152
+ export function useAnalytics() {
153
+ const context = useContext(AnalyticsContext);
154
+ if (!context) {
155
+ throw new Error("useAnalytics must be used within an AnalyticsProvider");
156
+ }
157
+ return context;
158
+ }
159
+
160
+ /**
161
+ * Hook to manage consent state
162
+ */
163
+ export function useConsent(options: UseConsentOptions = {}): UseConsentReturn {
164
+ const { consentVersion = CONSENT_VERSION } = options;
165
+
166
+ const [consent, setConsent] = useState<ConsentState | null>(() => {
167
+ const stored = loadConsent();
168
+ if (!stored) return null;
169
+ if (needsRePrompt(stored, consentVersion)) {
170
+ clearConsent();
171
+ return null;
172
+ }
173
+ return stored;
174
+ });
175
+
176
+ const [hasResponded, setHasResponded] = useState(() => consent !== null);
177
+
178
+ const acceptAll = useCallback(() => {
179
+ const newConsent = createAcceptAllConsent();
180
+ saveConsent(newConsent);
181
+ setConsent(newConsent);
182
+ setHasResponded(true);
183
+ }, []);
184
+
185
+ const declineAnalytics = useCallback(() => {
186
+ const newConsent = createDeclineAnalyticsConsent();
187
+ saveConsent(newConsent);
188
+ setConsent(newConsent);
189
+ setHasResponded(true);
190
+ }, []);
191
+
192
+ const updateConsentHandler = useCallback(
193
+ (category: ConsentCategory, value: boolean) => {
194
+ if (!consent) return;
195
+
196
+ const newConsent = updateConsentCategory(consent, category, value);
197
+ saveConsent(newConsent);
198
+ setConsent(newConsent);
199
+ },
200
+ [consent],
201
+ );
202
+
203
+ const resetConsentHandler = useCallback(() => {
204
+ clearConsent();
205
+ setConsent(null);
206
+ setHasResponded(false);
207
+ }, []);
208
+
209
+ return {
210
+ acceptAll,
211
+ consent,
212
+ declineAnalytics,
213
+ hasResponded,
214
+ isLoading: false,
215
+ resetConsent: resetConsentHandler,
216
+ updateConsent: updateConsentHandler,
217
+ };
218
+ }
219
+
220
+ // Re-export core analytics functions for convenience
221
+ export { initAnalytics } from "./analytics";
package/src/types.ts ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Analytics consent state stored in localStorage
3
+ */
4
+ export type ConsentState = {
5
+ /** Whether analytics tracking is allowed */
6
+ analytics: boolean;
7
+ /** Whether functional cookies are allowed (always true for site operation) */
8
+ functional: boolean;
9
+ /** ISO timestamp when consent was given */
10
+ timestamp: string;
11
+ /** Version of consent prompt (bump to re-prompt users) */
12
+ version: number;
13
+ };
14
+
15
+ /**
16
+ * Consent categories that can be toggled
17
+ */
18
+ export type ConsentCategory = "analytics" | "functional";
19
+
20
+ /**
21
+ * Tutorial-specific event names
22
+ */
23
+ export type TutorialEventName =
24
+ | "tutorial_complete"
25
+ | "tutorial_navigation"
26
+ | "tutorial_section_complete"
27
+ | "tutorial_section_view"
28
+ | "tutorial_start"
29
+ | "tutorial_time_spent";
30
+
31
+ /**
32
+ * Tutorial event properties
33
+ */
34
+ export type TutorialEventProperties = {
35
+ /** Completion percentage (0-100) */
36
+ completion_percent?: number;
37
+ /** User's locale */
38
+ locale: string;
39
+ /** Navigation method used */
40
+ navigation_type?: "keyboard" | "next" | "prev" | "toc";
41
+ /** Section identifier */
42
+ section_id?: string;
43
+ /** Section position (0-indexed) */
44
+ section_index?: number;
45
+ /** Time spent in seconds */
46
+ time_spent_seconds?: number;
47
+ /** Total number of sections */
48
+ total_sections?: number;
49
+ /** Unique tutorial identifier (contentId) */
50
+ tutorial_id: string;
51
+ /** Human-readable tutorial title */
52
+ tutorial_title: string;
53
+ };
54
+
55
+ /**
56
+ * Generic analytics event
57
+ */
58
+ export type AnalyticsEvent = {
59
+ name: string;
60
+ properties?: Record<string, unknown>;
61
+ timestamp?: string;
62
+ };
63
+
64
+ /**
65
+ * Analytics instance configuration
66
+ */
67
+ export type AnalyticsConfig = {
68
+ /** Application name for analytics */
69
+ app: string;
70
+ /** Enable debug mode */
71
+ debug?: boolean;
72
+ /** Application version */
73
+ version?: number;
74
+ };
75
+
76
+ /**
77
+ * Hook options for useConsent
78
+ */
79
+ export type UseConsentOptions = {
80
+ /** Current consent version (bump to re-prompt) */
81
+ consentVersion?: number;
82
+ };
83
+
84
+ /**
85
+ * Return type for useConsent hook
86
+ */
87
+ export type UseConsentReturn = {
88
+ /** Accept all tracking */
89
+ acceptAll: () => void;
90
+ /** Current consent state (null if not yet determined) */
91
+ consent: ConsentState | null;
92
+ /** Decline analytics tracking (functional always on) */
93
+ declineAnalytics: () => void;
94
+ /** Whether consent has been given (any response) */
95
+ hasResponded: boolean;
96
+ /** Whether currently loading from storage */
97
+ isLoading: boolean;
98
+ /** Reset consent (will re-show banner) */
99
+ resetConsent: () => void;
100
+ /** Update specific consent category */
101
+ updateConsent: (category: ConsentCategory, value: boolean) => void;
102
+ };