@vllnt/analytics 0.2.0-canary.8bb6613 → 0.2.0-canary.9bbc838

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/docs/API.md ADDED
@@ -0,0 +1,384 @@
1
+ # @vllnt/analytics API
2
+
3
+ Reference for every public export of this package version, written from `src/index.ts` and
4
+ `src/react.tsx`. Those sources ship in this package under `src/`.
5
+
6
+ The library has no transport. Events are queued and gated by consent, then dropped; with
7
+ `debug: true` they are written to `console.log`. Send them to your own backend yourself.
8
+
9
+ ## Entry points
10
+
11
+ Only these subpaths are exported (`package.json` `exports`). Each has ESM, CommonJS and type
12
+ declarations in `dist/`.
13
+
14
+ | Import | Contents |
15
+ | ---------------------------- | ------------------------------------------------------------ |
16
+ | `@vllnt/analytics` | Tracking functions, consent functions and constants, types |
17
+ | `@vllnt/analytics/react` | `AnalyticsProvider`, `useAnalytics`, `useConsent`, `initAnalytics` |
18
+ | `@vllnt/analytics/package.json` | Package metadata |
19
+
20
+ Types are exported from `@vllnt/analytics` only. Both entry points share one analytics state, so
21
+ `initAnalytics` from `./react` and `track` from `.` act on the same instance.
22
+
23
+ Peer dependency: `react` `^18.0.0 || ^19.0.0` (used by `./react` only).
24
+
25
+ All browser APIs are guarded, so importing on the server is safe. On the server `track`,
26
+ `trackPage`, `identify` and `resetAnalytics` return early, `loadConsent` returns `null`, and
27
+ `isStorageAvailable` and `isDoNotTrackEnabled` return `false`. `getConsentFromCookie` only parses
28
+ the string it is given, so it is the consent reader to use on the server. `initAnalytics`,
29
+ `enableAnalytics` and `disableAnalytics` have no server guard: `initAnalytics` on the server
30
+ starts the process-wide instance, so call it only in the browser.
31
+
32
+ ## Tracking (`@vllnt/analytics`)
33
+
34
+ ### `initAnalytics(config: AnalyticsConfig): void`
35
+
36
+ Starts the shared analytics instance and flushes queued events. Later calls do nothing while an
37
+ instance exists. It does not start, and blocks tracking, when Do Not Track is on (`"1"` or
38
+ `"yes"`) or stored consent has `analytics: false`; already queued events are then dropped, so
39
+ they are never sent later.
40
+ With no stored consent it starts, so call it only after the user accepts if you need opt-in
41
+ (`AnalyticsProvider` does this for you). Once tracking is blocked (by a blocked init or by
42
+ `disableAnalytics`), calling `initAnalytics` again does not unblock it; only `enableAnalytics`
43
+ does.
44
+
45
+ ```ts
46
+ import { initAnalytics } from "@vllnt/analytics";
47
+
48
+ initAnalytics({ app: "my-app", version: 1, debug: true });
49
+ ```
50
+
51
+ ### `track(name: string, properties?: Record<string, unknown>): void`
52
+
53
+ Records a custom event. Before `initAnalytics` the event is queued; while blocked it is dropped.
54
+ An empty or non-string `name` is ignored.
55
+
56
+ ```ts
57
+ track("button_click", { id: "cta-hero" });
58
+ ```
59
+
60
+ ### `trackPage(properties?: Record<string, unknown>): void`
61
+
62
+ Records a page view, queued before init like `track`.
63
+
64
+ ```ts
65
+ trackPage({ path: "/about" });
66
+ ```
67
+
68
+ ### `identify(userId: string, traits?: Record<string, unknown>): void`
69
+
70
+ Stores a user id and traits on the started instance. Ignored before init, while blocked, or
71
+ when `userId` is empty or not a string. Not queued.
72
+
73
+ ```ts
74
+ identify("user-123", { plan: "pro" });
75
+ ```
76
+
77
+ ### `resetAnalytics(): void`
78
+
79
+ Clears the stored user id and traits (for logout). The instance stays started.
80
+
81
+ ```ts
82
+ resetAnalytics();
83
+ ```
84
+
85
+ ### `enableAnalytics(config: AnalyticsConfig): void`
86
+
87
+ Unblocks, discards the current instance and runs `initAnalytics(config)` again. Does nothing
88
+ unless tracking is currently blocked, and does nothing while Do Not Track is on. Because it
89
+ re-reads stored consent, save the accepted consent first: a stored `analytics: false` blocks it
90
+ again. The new instance has no `userId` or `traits`.
91
+
92
+ ```ts
93
+ saveConsent(createAcceptAllConsent());
94
+ enableAnalytics({ app: "my-app" });
95
+ ```
96
+
97
+ ### `disableAnalytics(): void`
98
+
99
+ Blocks tracking and empties the queue after consent is revoked. It keeps the in-memory user id
100
+ and traits; call `resetAnalytics()` or reload the page to clear them.
101
+
102
+ ```ts
103
+ disableAnalytics();
104
+ resetAnalytics();
105
+ ```
106
+
107
+ ### `isAnalyticsEnabled(): boolean`
108
+
109
+ `true` when the instance has started and is not blocked.
110
+
111
+ ```ts
112
+ if (isAnalyticsEnabled()) track("export_clicked");
113
+ ```
114
+
115
+ ### `getAnalyticsState()`
116
+
117
+ Returns the current instance state for debugging, or `undefined` before init. Shape:
118
+ `{ app: string; debug?: boolean; version?: number; userId?: string; traits?: Record<string, unknown> }`.
119
+ The state type is not exported.
120
+
121
+ ```ts
122
+ console.log(getAnalyticsState()?.userId);
123
+ ```
124
+
125
+ ### Tutorial helpers
126
+
127
+ Typed wrappers around `track` that send fixed event names (`TutorialEventName`). Every helper
128
+ needs `tutorial_id`, `tutorial_title` and `locale`.
129
+
130
+ | Function | Event name | Extra required fields |
131
+ | ------------------------------------- | --------------------------- | ---------------------------------- |
132
+ | `trackTutorialStart(properties)` | `tutorial_start` | none (`section_id` not allowed) |
133
+ | `trackSectionView(properties)` | `tutorial_section_view` | none |
134
+ | `trackSectionComplete(properties)` | `tutorial_section_complete` | none |
135
+ | `trackTutorialComplete(properties)` | `tutorial_complete` | none (`section_id` not allowed) |
136
+ | `trackTutorialNavigation(properties)` | `tutorial_navigation` | `navigation_type` |
137
+ | `trackTimeSpent(properties)` | `tutorial_time_spent` | `time_spent_seconds` |
138
+
139
+ ```ts
140
+ import { trackSectionView, trackTutorialNavigation } from "@vllnt/analytics";
141
+
142
+ const base = { tutorial_id: "intro", tutorial_title: "Intro", locale: "en" };
143
+ trackSectionView({ ...base, section_id: "setup", section_index: 0, total_sections: 5 });
144
+ trackTutorialNavigation({ ...base, section_id: "setup", navigation_type: "next" });
145
+ ```
146
+
147
+ ## Consent (`@vllnt/analytics`)
148
+
149
+ Consent is stored as JSON in `localStorage` under `CONSENT_STORAGE_KEY` and mirrored to the
150
+ `CONSENT_COOKIE_NAME` cookie (`1` allowed, `0` declined; one-year expiry, `path=/`,
151
+ `SameSite=Lax`) so the server can read it.
152
+
153
+ ### Constants
154
+
155
+ | Name | Value |
156
+ | --------------------- | ---------------------------- |
157
+ | `CONSENT_VERSION` | `1` |
158
+ | `CONSENT_STORAGE_KEY` | `"vllnt:analytics-consent"` |
159
+ | `CONSENT_COOKIE_NAME` | `"vllnt-consent"` |
160
+
161
+ ### `loadConsent(): ConsentState | null`
162
+
163
+ Reads and validates stored consent. `null` when none, invalid, or storage is unavailable.
164
+
165
+ ```ts
166
+ const consent = loadConsent();
167
+ ```
168
+
169
+ ### `saveConsent(state: ConsentState): void`
170
+
171
+ Writes consent to `localStorage` and the cookie. Does nothing when storage is unavailable.
172
+
173
+ ```ts
174
+ saveConsent(createAcceptAllConsent());
175
+ ```
176
+
177
+ ### `clearConsent(): void`
178
+
179
+ Removes stored consent and expires the cookie.
180
+
181
+ ```ts
182
+ clearConsent();
183
+ ```
184
+
185
+ ### `createAcceptAllConsent(): ConsentState`
186
+
187
+ New state with `analytics: true`, `functional: true`, the current time and `CONSENT_VERSION`. To
188
+ record another version, override it: `{ ...createAcceptAllConsent(), version: 2 }`.
189
+
190
+ ```ts
191
+ const accepted = createAcceptAllConsent();
192
+ ```
193
+
194
+ ### `createDeclineAnalyticsConsent(): ConsentState`
195
+
196
+ New state with `analytics: false`, `functional: true`, the current time and `CONSENT_VERSION`.
197
+
198
+ ```ts
199
+ const declined = createDeclineAnalyticsConsent();
200
+ ```
201
+
202
+ ### `updateConsentCategory(current: ConsentState, category: ConsentCategory, value: boolean): ConsentState`
203
+
204
+ Returns a copy with one category changed and a new timestamp. Setting `functional` to `false`
205
+ returns `current` unchanged.
206
+
207
+ ```ts
208
+ const stored = loadConsent();
209
+ if (stored) saveConsent(updateConsentCategory(stored, "analytics", false));
210
+ ```
211
+
212
+ ### `needsRePrompt(consent: ConsentState, currentVersion: number): boolean`
213
+
214
+ `true` when `consent.version < currentVersion`.
215
+
216
+ ```ts
217
+ if (consent && needsRePrompt(consent, 2)) clearConsent();
218
+ ```
219
+
220
+ ### `getConsentFromCookie(cookieString: string): boolean | null`
221
+
222
+ Parses a `Cookie` header: `true` for `1`, `false` for any other value, `null` when the cookie is
223
+ absent. The name must start the string or follow `;`, so `evil-vllnt-consent=1` does not match.
224
+
225
+ ```ts
226
+ const allowed = getConsentFromCookie(request.headers.get("cookie") ?? "");
227
+ ```
228
+
229
+ ### `isDoNotTrackEnabled(): boolean`
230
+
231
+ Reads `navigator.doNotTrack`, then `window.doNotTrack`, then `navigator.msDoNotTrack`, and
232
+ returns `true` when the first one that is set equals `"1"` or `"yes"`. `false` on the server.
233
+
234
+ ```ts
235
+ if (isDoNotTrackEnabled()) hideBanner();
236
+ ```
237
+
238
+ ### `isStorageAvailable(): boolean`
239
+
240
+ `true` when `localStorage` can be written. `false` on the server or when storage throws.
241
+
242
+ ```ts
243
+ if (!isStorageAvailable()) console.warn("consent will not persist");
244
+ ```
245
+
246
+ ### `isValidConsentState(value: unknown): value is ConsentState`
247
+
248
+ Type guard: checks the four fields and their types.
249
+
250
+ ```ts
251
+ const parsed: unknown = JSON.parse(raw);
252
+ if (isValidConsentState(parsed)) saveConsent(parsed);
253
+ ```
254
+
255
+ ## React (`@vllnt/analytics/react`)
256
+
257
+ Both builds of this entry (`dist/react.js` and `dist/react.cjs`) start with `"use client"`; the
258
+ core entry does not.
259
+
260
+ Both `AnalyticsProvider` and `useConsent` read stored consent during the first render. On the
261
+ server that read returns `null`, so `consent` is `null` and `hasResponded` is `false` there, while
262
+ the first browser render may already see stored consent. If you render a banner from
263
+ `hasResponded`, render it only after the component has mounted to avoid a hydration mismatch.
264
+
265
+ ### `AnalyticsProvider`
266
+
267
+ ```ts
268
+ function AnalyticsProvider(props: {
269
+ children: ReactNode;
270
+ config: AnalyticsConfig;
271
+ consentVersion?: number; // default CONSENT_VERSION
272
+ }): React.JSX.Element;
273
+ ```
274
+
275
+ Reads stored consent, clears it when `needsRePrompt(stored, consentVersion)`, calls
276
+ `initAnalytics(config)` while consent has `analytics: true`, and calls `disableAnalytics()` while
277
+ it has `analytics: false`, so after a stored decline `track()` calls are dropped, not queued. Its
278
+ context actions save consent with `consentVersion` and call `enableAnalytics` or
279
+ `disableAnalytics`. Before the user responds (no stored consent), events are queued in memory and
280
+ flushed if the user accepts. Pass a stable `config` (for example a module constant), because the
281
+ init effect depends on it.
282
+
283
+ ```tsx
284
+ const config = { app: "my-app", version: 1 };
285
+
286
+ export function Root({ children }: { children: React.ReactNode }) {
287
+ return <AnalyticsProvider config={config}>{children}</AnalyticsProvider>;
288
+ }
289
+ ```
290
+
291
+ ### `useAnalytics()`
292
+
293
+ Returns the provider context; throws `useAnalytics must be used within an AnalyticsProvider`
294
+ outside one. Fields: `config`, `consent`, `hasResponded`, `isLoading` (always `false`),
295
+ `acceptAll()`, `declineAnalytics()`, `updateConsent(category, value)`, `resetConsent()`.
296
+ `updateConsent` does nothing while `consent` is `null` (before the user has responded).
297
+
298
+ ```tsx
299
+ function CookieBanner() {
300
+ const { hasResponded, acceptAll, declineAnalytics } = useAnalytics();
301
+ const [mounted, setMounted] = useState(false);
302
+ useEffect(() => setMounted(true), []);
303
+ if (!mounted || hasResponded) return null;
304
+ return (
305
+ <div>
306
+ <button onClick={acceptAll}>Accept</button>
307
+ <button onClick={declineAnalytics}>Decline</button>
308
+ </div>
309
+ );
310
+ }
311
+ ```
312
+
313
+ ### `useConsent(options?: UseConsentOptions): UseConsentReturn`
314
+
315
+ Standalone consent state with the same fields as `useAnalytics()` except `config`. It reads and
316
+ writes stored consent only: it does not start or stop analytics and does not share state with
317
+ `AnalyticsProvider`. Inside a provider, use `useAnalytics()` for a banner so accepting starts
318
+ tracking.
319
+
320
+ ```tsx
321
+ const { consent, updateConsent } = useConsent({ consentVersion: 1 });
322
+ ```
323
+
324
+ ### `initAnalytics`
325
+
326
+ Re-export of the core `initAnalytics`, for apps that only import from `./react`.
327
+
328
+ ### Consent versions
329
+
330
+ `AnalyticsProvider` and `useConsent` save each choice with their `consentVersion`. Raising
331
+ `consentVersion` asks every visitor once more; the new choice is then kept on later visits.
332
+
333
+ ## Types (`@vllnt/analytics`)
334
+
335
+ ```ts
336
+ type AnalyticsConfig = { app: string; debug?: boolean; version?: number };
337
+
338
+ type AnalyticsEvent = {
339
+ name: string;
340
+ properties?: Record<string, unknown>;
341
+ timestamp?: string;
342
+ };
343
+
344
+ type ConsentCategory = "analytics" | "functional";
345
+
346
+ type ConsentState = {
347
+ analytics: boolean;
348
+ functional: boolean;
349
+ timestamp: string; // ISO time of the choice
350
+ version: number;
351
+ };
352
+
353
+ type TutorialEventName =
354
+ | "tutorial_complete"
355
+ | "tutorial_navigation"
356
+ | "tutorial_section_complete"
357
+ | "tutorial_section_view"
358
+ | "tutorial_start"
359
+ | "tutorial_time_spent";
360
+
361
+ type TutorialEventProperties = {
362
+ tutorial_id: string;
363
+ tutorial_title: string;
364
+ locale: string;
365
+ completion_percent?: number; // 0-100
366
+ navigation_type?: "keyboard" | "next" | "prev" | "toc";
367
+ section_id?: string;
368
+ section_index?: number; // 0-based
369
+ time_spent_seconds?: number;
370
+ total_sections?: number;
371
+ };
372
+
373
+ type UseConsentOptions = { consentVersion?: number };
374
+
375
+ type UseConsentReturn = {
376
+ acceptAll: () => void;
377
+ consent: ConsentState | null;
378
+ declineAnalytics: () => void;
379
+ hasResponded: boolean;
380
+ isLoading: boolean;
381
+ resetConsent: () => void;
382
+ updateConsent: (category: ConsentCategory, value: boolean) => void;
383
+ };
384
+ ```
package/llms.txt ADDED
@@ -0,0 +1,56 @@
1
+ # @vllnt/analytics
2
+
3
+ > Lightweight, privacy-first analytics with consent management and React integration.
4
+
5
+ Facts for AI tools. The library has no transport: it queues and gates events, and only
6
+ `console.log`s them when `debug: true`. Bring your own backend.
7
+
8
+ ## For coding agents
9
+
10
+ The docs are bundled in the package at `node_modules/@vllnt/analytics/docs/`, with this file,
11
+ `CHANGELOG.md` and the TypeScript sources in `src/`. They match the installed version. Read them
12
+ before writing code.
13
+
14
+ ## Package
15
+
16
+ - npm: `@vllnt/analytics` (MIT), repo: https://github.com/vllnt/analytics
17
+ - Unreleased builds from `main` use the `canary` dist-tag
18
+ - Ships ESM, CommonJS and type declarations from `dist` (built with tsup); both builds of
19
+ `./react` start with `"use client"`
20
+ - Entry points: `@vllnt/analytics` (core + consent + types), `@vllnt/analytics/react` (`AnalyticsProvider`, `useAnalytics`, `useConsent`, `initAnalytics`)
21
+ - Peer dependency: React `^18.0.0 || ^19.0.0`
22
+ - Install: `pnpm add @vllnt/analytics`
23
+
24
+ ## Behaviour
25
+
26
+ - Events tracked before `initAnalytics()` are queued and flushed on the first unblocked init;
27
+ a blocked init drops them.
28
+ - `initAnalytics()` blocks tracking when Do Not Track is on (`"1"` or `"yes"`) or stored consent
29
+ has `analytics: false`. With no stored consent it starts tracking. `AnalyticsProvider` calls it
30
+ while consent has `analytics: true` and calls `disableAnalytics()` after a stored decline, so a
31
+ declined visitor's events are dropped. Before the user responds, events are queued in memory.
32
+ - Once blocked, only `enableAnalytics(config)` unblocks; it re-reads stored consent.
33
+ - Consent is stored in `localStorage` (`vllnt:analytics-consent`) and a `vllnt-consent` cookie
34
+ (`1` or `0`) for SSR; `getConsentFromCookie(cookieString)` reads it with an anchored match.
35
+ - Consent is versioned; a stored version below the hook's `consentVersion` (default
36
+ `CONSENT_VERSION`) re-prompts once, and the hooks save the new choice with that version.
37
+ - `track()` ignores empty or non-string names; `identify()` ignores empty or non-string ids.
38
+ - Browser APIs are guarded, so server-side import is safe. `initAnalytics()` has no server
39
+ guard and starts the process-wide instance there, so call it only in the browser.
40
+
41
+ ## Docs
42
+
43
+ - [API reference](./docs/API.md): every public export, signatures, examples, entry points
44
+ - [README](./README.md): usage and API summary
45
+ - [Changelog](./CHANGELOG.md): release history
46
+ - [Core exports](./src/index.ts) and [React exports](./src/react.tsx): source of the public API
47
+
48
+ ## Optional
49
+
50
+ - [Contributing](https://github.com/vllnt/analytics/blob/main/CONTRIBUTING.md): setup, checks, release flow
51
+ - [Security policy](https://github.com/vllnt/analytics/blob/main/SECURITY.md): private vulnerability reporting
52
+ - [AGENTS.md](https://github.com/vllnt/analytics/blob/main/AGENTS.md): instructions for contributing agents
53
+
54
+ ## Ecosystem
55
+
56
+ - [vllnt oss](https://oss.vllnt.com/llms.txt): index of all vllnt open-source packages
package/package.json CHANGED
@@ -1,25 +1,33 @@
1
1
  {
2
2
  "name": "@vllnt/analytics",
3
- "version": "0.2.0-canary.8bb6613",
3
+ "version": "0.2.0-canary.9bbc838",
4
4
  "description": "Lightweight, privacy-first analytics with consent management and React integration",
5
5
  "type": "module",
6
- "packageManager": "pnpm@10.34.8",
6
+ "packageManager": "pnpm@12.22.0",
7
7
  "license": "MIT",
8
8
  "repository": {
9
9
  "type": "git",
10
10
  "url": "git+https://github.com/vllnt/analytics.git"
11
11
  },
12
+ "homepage": "https://oss.vllnt.com/packages/analytics",
12
13
  "keywords": [
13
14
  "analytics",
14
15
  "consent",
15
16
  "privacy",
16
17
  "gdpr",
17
18
  "react",
18
- "do-not-track"
19
+ "do-not-track",
20
+ "cookie-consent",
21
+ "ssr"
19
22
  ],
20
23
  "sideEffects": false,
21
24
  "files": [
22
- "dist"
25
+ "dist",
26
+ "src",
27
+ "!src/__tests__",
28
+ "docs/API.md",
29
+ "CHANGELOG.md",
30
+ "llms.txt"
23
31
  ],
24
32
  "main": "./dist/index.cjs",
25
33
  "module": "./dist/index.js",
@@ -62,32 +70,18 @@
62
70
  "react": "^18.0.0 || ^19.0.0"
63
71
  },
64
72
  "devDependencies": {
65
- "@testing-library/jest-dom": "^7.0.1",
73
+ "@testing-library/jest-dom": "^8.0.0",
66
74
  "@testing-library/react": "^16.3.3",
67
75
  "@types/node": "^24.19.2",
68
76
  "@types/react": "^19.3.0",
69
- "@vitest/coverage-v8": "^5.1.0",
77
+ "@vitest/coverage-v8": "^5.1.1",
70
78
  "@vllnt/eslint-config": "^2.1.0",
71
- "@vllnt/typescript": "^2.0.0",
79
+ "@vllnt/typescript": "^3.0.0",
72
80
  "eslint": "^9.39.5",
73
- "jsdom": "^30.1.3",
81
+ "jsdom": "^31.0.1",
74
82
  "react": "^19.3.1",
75
83
  "tsup": "^9.0.0",
76
84
  "typescript": "^6.0.3",
77
- "vitest": "^5.1.0"
78
- },
79
- "pnpm": {
80
- "minimumReleaseAge": 10080,
81
- "minimumReleaseAgeExclude": [
82
- "@vllnt/*"
83
- ],
84
- "overrides": {
85
- "minimatch@>=7.0.0 <11.0.1": "11.0.5",
86
- "deepmerge-ts@<8.0.0": "8.0.0",
87
- "handlebars@<4.7.10": "4.7.10"
88
- },
89
- "ignoredBuiltDependencies": [
90
- "esbuild"
91
- ]
85
+ "vitest": "^5.1.1"
92
86
  }
93
87
  }