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

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/package.json CHANGED
@@ -1,25 +1,47 @@
1
1
  {
2
2
  "name": "@vllnt/analytics",
3
- "version": "0.2.0-canary.13db137",
4
- "description": "Lightweight, privacy-first analytics with consent management and React integration",
3
+ "version": "0.2.0-canary.2103207",
4
+ "description": "Cookie consent state and consent-gated event tracking for React and TypeScript, with Do Not Track and an SSR consent cookie.",
5
5
  "type": "module",
6
- "packageManager": "pnpm@10.34.8",
6
+ "packageManager": "pnpm@12.22.0",
7
7
  "license": "MIT",
8
+ "author": {
9
+ "name": "bntvllnt",
10
+ "url": "https://bntvllnt.com"
11
+ },
12
+ "funding": {
13
+ "type": "github",
14
+ "url": "https://github.com/sponsors/bntvllnt"
15
+ },
8
16
  "repository": {
9
17
  "type": "git",
10
18
  "url": "git+https://github.com/vllnt/analytics.git"
11
19
  },
20
+ "homepage": "https://oss.vllnt.com/packages/analytics",
21
+ "bugs": {
22
+ "url": "https://github.com/vllnt/analytics/issues"
23
+ },
12
24
  "keywords": [
13
25
  "analytics",
14
- "consent",
15
- "privacy",
26
+ "event-tracking",
27
+ "cookie-consent",
28
+ "consent-management",
16
29
  "gdpr",
30
+ "do-not-track",
31
+ "privacy",
17
32
  "react",
18
- "do-not-track"
33
+ "react-hooks",
34
+ "ssr",
35
+ "typescript"
19
36
  ],
20
37
  "sideEffects": false,
21
38
  "files": [
22
- "dist"
39
+ "dist",
40
+ "src",
41
+ "!src/__tests__",
42
+ "docs/API.md",
43
+ "CHANGELOG.md",
44
+ "llms.txt"
23
45
  ],
24
46
  "main": "./dist/index.cjs",
25
47
  "module": "./dist/index.js",
@@ -55,6 +77,7 @@
55
77
  "test": "vitest",
56
78
  "test:once": "vitest run",
57
79
  "test:coverage": "vitest run --coverage",
80
+ "test:package": "bash scripts/test-package.sh",
58
81
  "typecheck": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/typecheck.tsbuildinfo",
59
82
  "typecheck:ci": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/typecheck-ci.tsbuildinfo"
60
83
  },
@@ -62,31 +85,17 @@
62
85
  "react": "^18.0.0 || ^19.0.0"
63
86
  },
64
87
  "devDependencies": {
65
- "@testing-library/jest-dom": "^7.0.1",
66
88
  "@testing-library/react": "^16.3.3",
67
89
  "@types/node": "^24.19.2",
68
90
  "@types/react": "^19.3.0",
69
- "@vitest/coverage-v8": "^5.0.5",
70
- "@vllnt/eslint-config": "^2.0.0",
71
- "@vllnt/typescript": "^2.0.0",
91
+ "@vitest/coverage-v8": "^5.1.1",
92
+ "@vllnt/eslint-config": "^2.1.0",
93
+ "@vllnt/typescript": "^3.0.0",
72
94
  "eslint": "^9.39.5",
73
- "jsdom": "^30.1.3",
95
+ "jsdom": "^31.0.1",
74
96
  "react": "^19.3.1",
75
97
  "tsup": "^9.0.0",
76
98
  "typescript": "^6.0.3",
77
- "vitest": "^5.0.5"
78
- },
79
- "pnpm": {
80
- "minimumReleaseAge": 10080,
81
- "minimumReleaseAgeExclude": [
82
- "@vllnt/*"
83
- ],
84
- "overrides": {
85
- "deepmerge-ts@<8.0.0": "8.0.0",
86
- "handlebars@<4.7.10": "4.7.10"
87
- },
88
- "ignoredBuiltDependencies": [
89
- "esbuild"
90
- ]
99
+ "vitest": "^5.1.1"
91
100
  }
92
101
  }
@@ -0,0 +1,322 @@
1
+ import { isDoNotTrackEnabled, loadConsent } from "./consent";
2
+ import type {
3
+ AnalyticsConfig,
4
+ AnalyticsEvent,
5
+ TutorialEventName,
6
+ TutorialEventProperties,
7
+ } from "./types";
8
+
9
+ // Analytics state (singleton)
10
+ type AnalyticsState = {
11
+ app: string;
12
+ debug?: boolean;
13
+ traits?: Record<string, unknown>;
14
+ userId?: string;
15
+ version?: number;
16
+ };
17
+
18
+ let analyticsState: AnalyticsState | undefined;
19
+
20
+ /**
21
+ * Default `maxQueuedEvents`: how many `track` and `trackPage` calls are kept
22
+ * in memory before `initAnalytics` runs.
23
+ */
24
+ export const DEFAULT_MAX_QUEUED_EVENTS = 100;
25
+
26
+ // Queue for events before initialization
27
+ let eventQueue: AnalyticsEvent[] = [];
28
+ let maxQueuedEvents = DEFAULT_MAX_QUEUED_EVENTS;
29
+
30
+ // Track initialization state
31
+ let isInitialized = false;
32
+ let isBlocked = false;
33
+
34
+ /**
35
+ * Reset analytics state (for testing only)
36
+ * @internal
37
+ */
38
+ export function _resetAnalyticsState(): void {
39
+ analyticsState = undefined;
40
+ eventQueue = [];
41
+ maxQueuedEvents = DEFAULT_MAX_QUEUED_EVENTS;
42
+ isInitialized = false;
43
+ isBlocked = false;
44
+ }
45
+
46
+ /**
47
+ * Set the pre-init queue limit and keep only the first `limit` queued events.
48
+ * A value that is not a non-negative safe integer means the default.
49
+ * @internal
50
+ */
51
+ export function setMaxQueuedEvents(limit: number | undefined): void {
52
+ maxQueuedEvents =
53
+ typeof limit === "number" && Number.isSafeInteger(limit) && limit >= 0
54
+ ? limit
55
+ : DEFAULT_MAX_QUEUED_EVENTS;
56
+ eventQueue = eventQueue.slice(0, maxQueuedEvents);
57
+ }
58
+
59
+ /**
60
+ * Queue an event before init; calls past the limit are dropped.
61
+ */
62
+ function enqueue(event: AnalyticsEvent): void {
63
+ if (eventQueue.length < maxQueuedEvents) eventQueue.push(event);
64
+ }
65
+
66
+ /**
67
+ * Block tracking and drop queued events, so nothing recorded before the
68
+ * decision is flushed later.
69
+ */
70
+ function block(): void {
71
+ isBlocked = true;
72
+ eventQueue = [];
73
+ }
74
+
75
+ /**
76
+ * Log event in debug mode
77
+ */
78
+ function debugLog(type: string, data: unknown): void {
79
+ if (analyticsState?.debug) {
80
+ // eslint-disable-next-line no-console -- Debug logging is intentional
81
+ console.log(`[analytics:${type}]`, data);
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Central tracking point. The library has no transport: events are only
87
+ * logged in debug mode and are not sent anywhere.
88
+ */
89
+ function sendEvent(name: string, properties?: Record<string, unknown>): void {
90
+ debugLog("track", { name, properties });
91
+ }
92
+
93
+ /**
94
+ * Start the shared analytics instance and flush queued events. Blocks tracking,
95
+ * and drops the queue, when Do Not Track is on or stored consent declines it.
96
+ * @see https://oss.vllnt.com/packages/analytics
97
+ */
98
+ export function initAnalytics(config: AnalyticsConfig): void {
99
+ if (analyticsState) return;
100
+
101
+ setMaxQueuedEvents(config.maxQueuedEvents);
102
+
103
+ // Check Do Not Track
104
+ if (isDoNotTrackEnabled()) {
105
+ block();
106
+ debugLog("init", "Do Not Track enabled, analytics blocked");
107
+ return;
108
+ }
109
+
110
+ // Check consent
111
+ const consent = loadConsent();
112
+ if (consent && !consent.analytics) {
113
+ block();
114
+ debugLog("init", "Analytics consent declined");
115
+ return;
116
+ }
117
+
118
+ analyticsState = {
119
+ app: config.app,
120
+ debug: config.debug,
121
+ version: config.version,
122
+ };
123
+
124
+ isInitialized = true;
125
+
126
+ debugLog("init", { app: config.app, version: config.version });
127
+
128
+ // Process queued events
129
+ processQueue();
130
+ }
131
+
132
+ /**
133
+ * Process queued events after initialization
134
+ */
135
+ function processQueue(): void {
136
+ if (!analyticsState || isBlocked) return;
137
+
138
+ // Process and clear the queue
139
+ const queue = [...eventQueue];
140
+ eventQueue = [];
141
+
142
+ for (const event of queue) {
143
+ if (event.name === "__page__") {
144
+ debugLog("page", event.properties);
145
+ } else {
146
+ sendEvent(event.name, event.properties);
147
+ }
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Track a custom event. Events with an empty or non-string name are ignored.
153
+ * Before init, only the first `maxQueuedEvents` calls (shared with
154
+ * `trackPage`) are queued.
155
+ */
156
+ export function track(
157
+ name: string,
158
+ properties?: Record<string, unknown>,
159
+ ): void {
160
+ if (typeof window === "undefined") return;
161
+ if (typeof name !== "string" || name === "") return;
162
+
163
+ if (isBlocked) return;
164
+
165
+ const event: AnalyticsEvent = {
166
+ name,
167
+ properties,
168
+ timestamp: new Date().toISOString(),
169
+ };
170
+
171
+ if (!isInitialized) {
172
+ enqueue(event);
173
+ return;
174
+ }
175
+
176
+ sendEvent(name, properties);
177
+ }
178
+
179
+ /**
180
+ * Track a page view. Before init, it shares the `maxQueuedEvents` limit with
181
+ * `track`.
182
+ */
183
+ export function trackPage(properties?: Record<string, unknown>): void {
184
+ if (typeof window === "undefined") return;
185
+ if (isBlocked) return;
186
+
187
+ if (!isInitialized) {
188
+ enqueue({
189
+ name: "__page__",
190
+ properties,
191
+ timestamp: new Date().toISOString(),
192
+ });
193
+ return;
194
+ }
195
+
196
+ debugLog("page", properties);
197
+ }
198
+
199
+ /**
200
+ * Identify a user. An empty or non-string user id is ignored.
201
+ */
202
+ export function identify(
203
+ userId: string,
204
+ traits?: Record<string, unknown>,
205
+ ): void {
206
+ if (typeof window === "undefined") return;
207
+ if (typeof userId !== "string" || userId === "") return;
208
+ if (isBlocked) return;
209
+
210
+ if (!isInitialized || !analyticsState) {
211
+ return;
212
+ }
213
+
214
+ analyticsState.userId = userId;
215
+ analyticsState.traits = traits;
216
+
217
+ debugLog("identify", { traits, userId });
218
+ }
219
+
220
+ /**
221
+ * Reset analytics state (on logout)
222
+ */
223
+ export function resetAnalytics(): void {
224
+ if (typeof window === "undefined") return;
225
+
226
+ if (analyticsState) {
227
+ analyticsState.userId = undefined;
228
+ analyticsState.traits = undefined;
229
+ }
230
+
231
+ debugLog("reset", undefined);
232
+ }
233
+
234
+ /**
235
+ * Enable analytics after consent is given
236
+ */
237
+ export function enableAnalytics(config: AnalyticsConfig): void {
238
+ if (isBlocked && !isDoNotTrackEnabled()) {
239
+ isBlocked = false;
240
+ analyticsState = undefined;
241
+ initAnalytics(config);
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Disable analytics after consent is revoked.
247
+ * NOTE: Does not clear in-memory userId/traits (GDPR Art. 17 limitation).
248
+ * Callers should trigger a page reload or call resetAnalytics() to purge PII.
249
+ */
250
+ export function disableAnalytics(): void {
251
+ block();
252
+ }
253
+
254
+ /**
255
+ * Check if analytics is currently enabled
256
+ */
257
+ export function isAnalyticsEnabled(): boolean {
258
+ return isInitialized && !isBlocked;
259
+ }
260
+
261
+ /**
262
+ * Get current analytics state (for advanced usage/debugging)
263
+ */
264
+ export function getAnalyticsState(): AnalyticsState | undefined {
265
+ return analyticsState;
266
+ }
267
+
268
+ // Tutorial-specific tracking helpers
269
+
270
+ /**
271
+ * Track tutorial start
272
+ */
273
+ export function trackTutorialStart(
274
+ properties: Omit<TutorialEventProperties, "section_id">,
275
+ ): void {
276
+ track("tutorial_start" satisfies TutorialEventName, properties);
277
+ }
278
+
279
+ /**
280
+ * Track section view
281
+ */
282
+ export function trackSectionView(properties: TutorialEventProperties): void {
283
+ track("tutorial_section_view" satisfies TutorialEventName, properties);
284
+ }
285
+
286
+ /**
287
+ * Track section completion
288
+ */
289
+ export function trackSectionComplete(
290
+ properties: TutorialEventProperties,
291
+ ): void {
292
+ track("tutorial_section_complete" satisfies TutorialEventName, properties);
293
+ }
294
+
295
+ /**
296
+ * Track tutorial completion
297
+ */
298
+ export function trackTutorialComplete(
299
+ properties: Omit<TutorialEventProperties, "section_id">,
300
+ ): void {
301
+ track("tutorial_complete" satisfies TutorialEventName, properties);
302
+ }
303
+
304
+ /**
305
+ * Track navigation between sections
306
+ */
307
+ export function trackTutorialNavigation(
308
+ properties: TutorialEventProperties & {
309
+ navigation_type: "keyboard" | "next" | "prev" | "toc";
310
+ },
311
+ ): void {
312
+ track("tutorial_navigation" satisfies TutorialEventName, properties);
313
+ }
314
+
315
+ /**
316
+ * Track time spent on a section
317
+ */
318
+ export function trackTimeSpent(
319
+ properties: TutorialEventProperties & { time_spent_seconds: number },
320
+ ): void {
321
+ track("tutorial_time_spent" satisfies TutorialEventName, properties);
322
+ }
package/src/consent.ts ADDED
@@ -0,0 +1,181 @@
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
+ * Reads directly (no write probe), so a stored choice is still found when the
47
+ * storage quota is full.
48
+ */
49
+ export function loadConsent(): ConsentState | null {
50
+ if (typeof window === "undefined") return null;
51
+
52
+ try {
53
+ const raw = localStorage.getItem(CONSENT_STORAGE_KEY);
54
+ if (!raw) return null;
55
+
56
+ const parsed: unknown = JSON.parse(raw);
57
+ if (!isValidConsentState(parsed)) return null;
58
+
59
+ return parsed;
60
+ } catch {
61
+ return null;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Save consent state to localStorage and cookie
67
+ */
68
+ export function saveConsent(state: ConsentState): void {
69
+ if (!isStorageAvailable()) return;
70
+
71
+ try {
72
+ localStorage.setItem(CONSENT_STORAGE_KEY, JSON.stringify(state));
73
+
74
+ // Also set a cookie for SSR detection (1 year expiry)
75
+ const expires = new Date();
76
+ expires.setFullYear(expires.getFullYear() + 1);
77
+
78
+ // Cookie value: "1" for analytics allowed, "0" for declined
79
+ const cookieValue = state.analytics ? "1" : "0";
80
+ document.cookie = `${CONSENT_COOKIE_NAME}=${cookieValue}; expires=${expires.toUTCString()}; path=/; SameSite=Lax`;
81
+ } catch (error) {
82
+ console.warn("Failed to save consent:", error);
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Clear consent state (for re-prompting)
88
+ */
89
+ export function clearConsent(): void {
90
+ if (!isStorageAvailable()) return;
91
+
92
+ try {
93
+ localStorage.removeItem(CONSENT_STORAGE_KEY);
94
+
95
+ // Clear cookie
96
+ document.cookie = `${CONSENT_COOKIE_NAME}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Lax`;
97
+ } catch {
98
+ // Ignore errors during cleanup
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Create a new consent state with all categories accepted
104
+ */
105
+ export function createAcceptAllConsent(): ConsentState {
106
+ return {
107
+ analytics: true,
108
+ functional: true,
109
+ timestamp: new Date().toISOString(),
110
+ version: CONSENT_VERSION,
111
+ };
112
+ }
113
+
114
+ /**
115
+ * Create a consent state with analytics declined
116
+ */
117
+ export function createDeclineAnalyticsConsent(): ConsentState {
118
+ return {
119
+ analytics: false,
120
+ functional: true, // Functional always enabled
121
+ timestamp: new Date().toISOString(),
122
+ version: CONSENT_VERSION,
123
+ };
124
+ }
125
+
126
+ /**
127
+ * Update a specific consent category
128
+ */
129
+ export function updateConsentCategory(
130
+ current: ConsentState,
131
+ category: ConsentCategory,
132
+ value: boolean,
133
+ ): ConsentState {
134
+ // Functional cookies cannot be disabled
135
+ if (category === "functional" && !value) {
136
+ return current;
137
+ }
138
+
139
+ return {
140
+ ...current,
141
+ [category]: value,
142
+ timestamp: new Date().toISOString(),
143
+ };
144
+ }
145
+
146
+ /**
147
+ * Check if consent needs to be re-prompted (version mismatch)
148
+ */
149
+ export function needsRePrompt(
150
+ consent: ConsentState,
151
+ currentVersion: number,
152
+ ): boolean {
153
+ return consent.version < currentVersion;
154
+ }
155
+
156
+ /**
157
+ * Check Do Not Track browser setting
158
+ */
159
+ export function isDoNotTrackEnabled(): boolean {
160
+ if (typeof window === "undefined") return false;
161
+
162
+ const dnt =
163
+ navigator.doNotTrack ||
164
+ (window as unknown as { doNotTrack?: string }).doNotTrack ||
165
+ (navigator as unknown as { msDoNotTrack?: string }).msDoNotTrack;
166
+
167
+ return dnt === "1" || dnt === "yes";
168
+ }
169
+
170
+ /**
171
+ * Get consent from cookie (for SSR)
172
+ */
173
+ export function getConsentFromCookie(cookieString: string): boolean | null {
174
+ // Anchor to the start of the string or a cookie separator so that
175
+ // look-alike names such as "evil-vllnt-consent" are not matched.
176
+ const match = new RegExp(`(?:^|;\\s*)${CONSENT_COOKIE_NAME}=([^;]+)`).exec(
177
+ cookieString,
178
+ );
179
+ if (!match) return null;
180
+ return match[1] === "1";
181
+ }
package/src/index.ts ADDED
@@ -0,0 +1,49 @@
1
+ // Core analytics
2
+ export {
3
+ DEFAULT_MAX_QUEUED_EVENTS,
4
+ disableAnalytics,
5
+ enableAnalytics,
6
+ getAnalyticsState,
7
+ identify,
8
+ initAnalytics,
9
+ isAnalyticsEnabled,
10
+ resetAnalytics,
11
+ track,
12
+ trackPage,
13
+ trackSectionComplete,
14
+ trackSectionView,
15
+ trackTimeSpent,
16
+ trackTutorialComplete,
17
+ trackTutorialNavigation,
18
+ trackTutorialStart,
19
+ } from "./analytics";
20
+
21
+ // Consent management
22
+ export {
23
+ clearConsent,
24
+ CONSENT_COOKIE_NAME,
25
+ CONSENT_STORAGE_KEY,
26
+ CONSENT_VERSION,
27
+ createAcceptAllConsent,
28
+ createDeclineAnalyticsConsent,
29
+ getConsentFromCookie,
30
+ isDoNotTrackEnabled,
31
+ isStorageAvailable,
32
+ isValidConsentState,
33
+ loadConsent,
34
+ needsRePrompt,
35
+ saveConsent,
36
+ updateConsentCategory,
37
+ } from "./consent";
38
+
39
+ // Types
40
+ export type {
41
+ AnalyticsConfig,
42
+ AnalyticsEvent,
43
+ ConsentCategory,
44
+ ConsentState,
45
+ TutorialEventName,
46
+ TutorialEventProperties,
47
+ UseConsentOptions,
48
+ UseConsentReturn,
49
+ } from "./types";