@vllnt/analytics 0.1.1 → 0.2.0-canary.13db137

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/src/analytics.ts DELETED
@@ -1,305 +0,0 @@
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 DELETED
@@ -1,175 +0,0 @@
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 DELETED
@@ -1,48 +0,0 @@
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/types.ts DELETED
@@ -1,102 +0,0 @@
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
- };