@codefast/tracking 0.0.0 → 0.5.0-canary.5
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/CHANGELOG.md +44 -0
- package/README.md +79 -9
- package/dist/client/consent-storage.d.mts +11 -3
- package/dist/client/consent-storage.mjs +45 -9
- package/dist/client/create-client-tracker.d.mts +10 -0
- package/dist/client/create-client-tracker.mjs +14 -1
- package/dist/client/gpc.d.mts +2 -0
- package/dist/client/gpc.mjs +2 -0
- package/dist/client/lifecycle.d.mts +5 -0
- package/dist/client/lifecycle.mjs +2 -0
- package/dist/client/local-storage.d.mts +5 -2
- package/dist/client/local-storage.mjs +12 -5
- package/dist/client/queue.d.mts +7 -0
- package/dist/client/queue.mjs +2 -0
- package/dist/client/router.d.mts +4 -0
- package/dist/client/router.mjs +2 -0
- package/dist/core/consent.d.mts +61 -9
- package/dist/core/consent.mjs +39 -7
- package/dist/core/destination.d.mts +10 -0
- package/dist/core/event-catalog.d.mts +8 -0
- package/dist/core/event-catalog.mjs +2 -0
- package/dist/core/event-id.d.mts +2 -0
- package/dist/core/event-id.mjs +2 -0
- package/dist/core/index.d.mts +2 -2
- package/dist/core/index.mjs +2 -2
- package/dist/core/tracked-event.d.mts +2 -0
- package/dist/destinations/ga4-measurement-protocol.d.mts +54 -0
- package/dist/destinations/ga4-measurement-protocol.mjs +89 -0
- package/dist/destinations/google-analytics.d.mts +98 -0
- package/dist/destinations/google-analytics.mjs +126 -0
- package/dist/destinations/http-destination.d.mts +5 -0
- package/dist/destinations/http-destination.mjs +2 -0
- package/dist/destinations/index.d.mts +3 -1
- package/dist/destinations/index.mjs +3 -1
- package/dist/destinations/vercel-analytics.d.mts +4 -2
- package/dist/destinations/vercel-analytics.mjs +5 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/react/consent-banner.d.mts +140 -18
- package/dist/react/consent-banner.mjs +195 -28
- package/dist/react/index.d.mts +2 -2
- package/dist/react/index.mjs +2 -2
- package/dist/react/use-consent.d.mts +30 -5
- package/dist/react/use-consent.mjs +38 -15
- package/dist/server/create-server-tracker.d.mts +14 -0
- package/dist/server/create-server-tracker.mjs +24 -5
- package/dist/server/region.d.mts +4 -0
- package/dist/server/region.mjs +4 -0
- package/package.json +13 -2
- package/src/client/consent-storage.ts +75 -10
- package/src/client/create-client-tracker.ts +30 -1
- package/src/client/gpc.ts +2 -0
- package/src/client/lifecycle.ts +5 -0
- package/src/client/local-storage.ts +21 -6
- package/src/client/queue.ts +7 -0
- package/src/client/router.ts +4 -0
- package/src/core/consent.ts +85 -11
- package/src/core/destination.ts +10 -0
- package/src/core/event-catalog.ts +8 -0
- package/src/core/event-id.ts +2 -0
- package/src/core/index.ts +15 -2
- package/src/core/tracked-event.ts +2 -0
- package/src/css/consent.css +119 -0
- package/src/destinations/ga4-measurement-protocol.ts +166 -0
- package/src/destinations/google-analytics.ts +233 -0
- package/src/destinations/http-destination.ts +5 -0
- package/src/destinations/index.ts +16 -0
- package/src/destinations/vercel-analytics.ts +5 -2
- package/src/react/consent-banner.tsx +301 -31
- package/src/react/index.ts +26 -2
- package/src/react/use-consent.ts +81 -23
- package/src/server/create-server-tracker.ts +39 -16
- package/src/server/region.ts +4 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# @codefast/tracking
|
|
2
|
+
|
|
3
|
+
## 0.5.0-canary.5
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [`08f10fb`](https://github.com/codefastlabs/codefast/commit/08f10fb6f4f16e175557fac1adeb5b480dc691db) Thanks [@thevuong](https://github.com/thevuong)! - Rebuild `ConsentBanner` as composable compound parts (`ConsentBannerTitle`/`Description`/`Actions`/`Accept`/`Reject`/`Customize`/`Preferences`/`Category`/`Save`) — the root owns visibility (`needsPrompt`, overridable via `open` for a "Cookie settings" reopen) and the preferences-layer state, action parts wire their own clicks and compose the consumer's `onClick`, so any markup including a design system's button styles slots in via `className`. The monolithic `message`/`acceptLabel`/`categories` props are gone. An optional plain-CSS default theme ships at `@codefast/tracking/css/consent.css` — data-slot selectors, `--consent-*` custom properties with `light-dark()` fallbacks, zero Tailwind dependency.
|
|
8
|
+
|
|
9
|
+
## 0.5.0-canary.4
|
|
10
|
+
|
|
11
|
+
### Minor Changes
|
|
12
|
+
|
|
13
|
+
- [`079b8df`](https://github.com/codefastlabs/codefast/commit/079b8dfad7bd58d1d1f0d9a8ef376383544a37c2) Thanks [@thevuong](https://github.com/thevuong)! - Rebuild the consent layer on `useSyncExternalStore` and expose `data-slot` styling hooks on the consent UI.
|
|
14
|
+
|
|
15
|
+
- `useConsent` treats the stored `ConsentRecord` as the single source of truth: the server snapshot is always "no decision yet" (hydration-safe by construction on prerendered pages), a decision made in one tab syncs to every other tab, and a record saved under an older `policyVersion` is ignored so bumping the version re-prompts as documented.
|
|
16
|
+
- **Breaking:** `ConsentStorage` gains a required `subscribe(listener)` method — custom implementations must notify on changes. `createLocalStorageConsentStorage` implements it (same-tab saves plus the cross-tab `storage` event) and now degrades a blocked `localStorage` (private mode/quota) to a session-scoped in-memory record instead of re-prompting in a loop.
|
|
17
|
+
- **Breaking:** `ConsentBanner` renders a labeled region instead of a non-modal `<dialog>` (which neither traps focus nor blocks, so the dialog semantics over-promised). Both components extend their host element's `ComponentProps` and expose `data-slot` attributes (`consent-message`, `consent-actions`, `consent-action`, `consent-toggle`) for Tailwind `**:data-[slot=...]` styling.
|
|
18
|
+
|
|
19
|
+
- [`41951df`](https://github.com/codefastlabs/codefast/commit/41951dfe97776bb0147e4ce766c9162327ef53b4) Thanks [@thevuong](https://github.com/thevuong)! - Expose the stored decision from `useConsent` and ignore tampered consent records.
|
|
20
|
+
|
|
21
|
+
- `UseConsentResult` gains `decision` — the stored decision under the current policy version, `undefined` until the visitor makes one. Consumers need it to replay a returning visitor's decision into Google Consent Mode (e.g. from an effect) without conflating "denied" with "no decision yet", which the boolean `isTrackingAllowed` cannot distinguish.
|
|
22
|
+
- `useConsent` now counts only a well-formed `decision` (`"granted"`/`"denied"`): the record is tamperable plain JSON, and a garbage value re-prompts instead of silently denying. This matches how a pre-hydration Consent Mode bootstrap reading the same record should treat it.
|
|
23
|
+
- Documented that `createLocalStorageConsentStorage` persists the record as plain `JSON.stringify(ConsentRecord)` — a stable contract, so inline scripts can read the decision synchronously before any tag fires.
|
|
24
|
+
|
|
25
|
+
- [`079b8df`](https://github.com/codefastlabs/codefast/commit/079b8dfad7bd58d1d1f0d9a8ef376383544a37c2) Thanks [@thevuong](https://github.com/thevuong)! - Align the Google Analytics (gtag) destination with GA4's event and consent semantics.
|
|
26
|
+
|
|
27
|
+
- GA4 rejects `$`-prefixed event names, so the tracker's built-ins are now translated instead of forwarded verbatim: `$identify` → `gtag('set', { user_id })`, `$group` → the recommended `join_group` event (`group_id` param), and other invalid names are warned about and dropped instead of being sent to nowhere.
|
|
28
|
+
- `$page_viewed` is dropped by default — `gtag('config')` plus Enhanced Measurement (on by default in GA4 admin) already report page views, so forwarding it double-counted. Opt in with `trackPageViews: true` after disabling both.
|
|
29
|
+
- **`setGoogleConsentDefault`/`updateGoogleConsent` now grant `analytics_storage` only**; the `ad_*` Consent Mode v2 categories stay denied unless the new `includeAds` option is set, since an analytics-only banner never asked the visitor about ads data sharing.
|
|
30
|
+
- Both consent functions define the standard gtag.js queueing stub themselves, so the default signal can be issued before the tag loads — as their docs always promised.
|
|
31
|
+
|
|
32
|
+
- [`079b8df`](https://github.com/codefastlabs/codefast/commit/079b8dfad7bd58d1d1f0d9a8ef376383544a37c2) Thanks [@thevuong](https://github.com/thevuong)! - Correlate GA4 Measurement Protocol hits with gtag.js's own identifiers.
|
|
33
|
+
|
|
34
|
+
GA4 joins hits on gtag's client ID (the `_ga` cookie), not on an app-generated anonymous ID — MP events sent with our ID landed on a different GA4 user than the visitor's client-side hits. New `extractGa4ClientId`/`extractGa4SessionId` helpers read gtag's `_ga`/`_ga_<stream>` request cookies (both GS1 and GS2 formats) so the destination can echo them via the new `clientId`/`sessionId` options. Events now also carry `engagement_time_msec`, `session_id`, and `timestamp_micros` — without them GA4 accepts the hit but leaves it out of realtime and session-scoped reports, and retried events drift to receipt time. `$group` maps to `join_group`; `$alias` is dropped (GA4 merges identities via `user_id`).
|
|
35
|
+
|
|
36
|
+
- [`079b8df`](https://github.com/codefastlabs/codefast/commit/079b8dfad7bd58d1d1f0d9a8ef376383544a37c2) Thanks [@thevuong](https://github.com/thevuong)! - Deliver events to SDK-backed destinations at track time instead of through the batching queue.
|
|
37
|
+
|
|
38
|
+
`Destination` gains an optional `delivery: "immediate" | "queued"` field. The Google Analytics and Vercel destinations are marked `"immediate"` — their SDKs own batching and unload delivery, so routing them through the queue only delayed events and replayed stale ones next session with wrong timestamps. The queue keeps serving HTTP destinations and the `flushWithBeacon` path unchanged.
|
|
39
|
+
|
|
40
|
+
- [`2ebb0c0`](https://github.com/codefastlabs/codefast/commit/2ebb0c0202891297f75525156b57ed9b2040ab82) Thanks [@thevuong](https://github.com/thevuong)! - Make consent per-category, mirroring Google Consent Mode v2. `ConsentDecision` is now `{ ads: boolean, analytics: boolean }` instead of a single `"granted" | "denied"` flag, `useConsent` takes the `categories` the app's prompt asks about (`grantAll`/`denyAll`/`save` replace `grant`/`deny`), and `ConsentBanner` gains a per-category preferences layer plus a `ReactNode` message for the privacy-policy link. The GA4 helpers map the decision onto the v2 signals (`ads` drives `ad_storage`/`ad_user_data`/`ad_personalization`), take `wait_for_update`/`region`, and gain `setGoogleAdsDataRedaction`/`setGoogleUrlPassthrough`; the destination-side `includeAds` override is gone — the visitor's decision carries ads consent. `resolveDefaultConsent` replaces `shouldTrackByDefault` and honors GPC as an ads-only opt-out. Previously stored string decisions fail shape validation and re-prompt, no policy-version bump needed.
|
|
41
|
+
|
|
42
|
+
### Patch Changes
|
|
43
|
+
|
|
44
|
+
- [`46c32d6`](https://github.com/codefastlabs/codefast/commit/46c32d6a5dfcfbccd5e1b3dd6a5488cb84b31b6a) Thanks [@thevuong](https://github.com/thevuong)! - Default `engagement_time_msec` on Measurement Protocol events to 100ms — the fallback Google's own MP documentation prescribes when the elapsed time since the previous event is unknown — instead of 1ms.
|
package/README.md
CHANGED
|
@@ -10,8 +10,10 @@ multi-destination fan-out, region-based consent).
|
|
|
10
10
|
## Status
|
|
11
11
|
|
|
12
12
|
Early scaffold. `core`, `client`, `server`, and `react` (headless consent) implement the
|
|
13
|
-
shapes described in the spec.
|
|
14
|
-
|
|
13
|
+
shapes described in the spec. `createVercelAnalyticsDestination`,
|
|
14
|
+
`createGoogleAnalyticsDestination`, and `createGa4MeasurementProtocolDestination` are
|
|
15
|
+
implemented; PostHog is not built yet — use `createHttpDestination` or implement the
|
|
16
|
+
`Destination` interface directly.
|
|
15
17
|
|
|
16
18
|
## Quick start
|
|
17
19
|
|
|
@@ -64,27 +66,95 @@ attachRouterPageTracking(tracker, router); // router: your app's TanStack Router
|
|
|
64
66
|
attachClientLifecycle(tracker, { beaconEndpoint: "/api/events", flushIntervalMs: 10_000 });
|
|
65
67
|
```
|
|
66
68
|
|
|
67
|
-
## Consent (region-based)
|
|
69
|
+
## Consent (region-based, per-category)
|
|
70
|
+
|
|
71
|
+
Consent is granular per purpose, mirroring Google Consent Mode v2's split: a
|
|
72
|
+
`ConsentDecision` is `{ ads: boolean, analytics: boolean }`, never a single yes/no —
|
|
73
|
+
GDPR requires purpose-level consent, and the ads signals (`ad_storage`/`ad_user_data`/
|
|
74
|
+
`ad_personalization`) must be able to differ from `analytics_storage`.
|
|
68
75
|
|
|
69
76
|
Resolve the region/mode server-side (`resolveRegion` + `resolveConsentMode` from
|
|
70
77
|
`@codefast/tracking/server` and `@codefast/tracking`) and pass `mode` down to the client.
|
|
71
|
-
|
|
72
|
-
|
|
78
|
+
The banner ships as composable, headless parts — no `@codefast/ui` dependency, any
|
|
79
|
+
markup (including a design system's button styles via `className`) slots in. For a
|
|
80
|
+
default look without writing CSS, import the optional plain-CSS theme:
|
|
81
|
+
|
|
82
|
+
```css
|
|
83
|
+
@import "@codefast/tracking/css/consent.css";
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Or style the parts yourself via `className`/`data-slot` attributes (`consent-banner`,
|
|
87
|
+
`consent-title`, `consent-description`, `consent-actions`, `consent-action`,
|
|
88
|
+
`consent-preferences`, `consent-category`, `consent-toggle`), e.g. Tailwind's
|
|
89
|
+
`**:data-[slot=consent-action]:rounded-md`. `data-state` on the root flips between
|
|
90
|
+
`prompt` and `preferences`.
|
|
73
91
|
|
|
74
92
|
```tsx
|
|
75
93
|
import { createLocalStorageConsentStorage } from "@codefast/tracking/client";
|
|
76
|
-
import {
|
|
94
|
+
import { updateGoogleConsent } from "@codefast/tracking/destinations";
|
|
95
|
+
import {
|
|
96
|
+
ConsentBanner,
|
|
97
|
+
ConsentBannerAccept,
|
|
98
|
+
ConsentBannerActions,
|
|
99
|
+
ConsentBannerCategory,
|
|
100
|
+
ConsentBannerCustomize,
|
|
101
|
+
ConsentBannerDescription,
|
|
102
|
+
ConsentBannerPreferences,
|
|
103
|
+
ConsentBannerReject,
|
|
104
|
+
ConsentBannerSave,
|
|
105
|
+
ConsentBannerTitle,
|
|
106
|
+
ConsentToggle,
|
|
107
|
+
useConsent,
|
|
108
|
+
} from "@codefast/tracking/react";
|
|
109
|
+
|
|
110
|
+
// Module scope — useConsent subscribes to the storage, so it must be a stable reference.
|
|
111
|
+
const consentStorage = createLocalStorageConsentStorage("tracking-consent");
|
|
77
112
|
|
|
78
113
|
function ConsentGate({ mode }: { mode: "opt-in" | "opt-out" }) {
|
|
79
114
|
const consent = useConsent({
|
|
115
|
+
categories: ["analytics"], // the purposes your prompt asks about — Accept grants exactly these
|
|
80
116
|
mode,
|
|
81
117
|
onDecision: (decision) => {
|
|
82
|
-
|
|
118
|
+
updateGoogleConsent(decision); // per-category Consent Mode v2 update
|
|
119
|
+
if (!decision.analytics) tracker.clear(); // stop tracking + drop the pending queue
|
|
83
120
|
},
|
|
84
121
|
policyVersion: "2026-01",
|
|
85
|
-
storage:
|
|
122
|
+
storage: consentStorage,
|
|
86
123
|
});
|
|
87
124
|
|
|
88
|
-
return mode === "opt-in" ?
|
|
125
|
+
return mode === "opt-in" ? (
|
|
126
|
+
<ConsentBanner consent={consent}>
|
|
127
|
+
<ConsentBannerTitle>Cookies & analytics</ConsentBannerTitle>
|
|
128
|
+
<ConsentBannerDescription>
|
|
129
|
+
We use cookies to understand how you use this site. <a href="/privacy">Privacy policy</a>
|
|
130
|
+
</ConsentBannerDescription>
|
|
131
|
+
{/* optional second layer: per-category checkboxes ("Customize" → "Save preferences") */}
|
|
132
|
+
<ConsentBannerPreferences>
|
|
133
|
+
<ConsentBannerCategory category="analytics">Analytics</ConsentBannerCategory>
|
|
134
|
+
<ConsentBannerSave>Save preferences</ConsentBannerSave>
|
|
135
|
+
</ConsentBannerPreferences>
|
|
136
|
+
<ConsentBannerActions>
|
|
137
|
+
<ConsentBannerAccept>Accept</ConsentBannerAccept>
|
|
138
|
+
<ConsentBannerReject>Reject</ConsentBannerReject>
|
|
139
|
+
<ConsentBannerCustomize>Customize</ConsentBannerCustomize>
|
|
140
|
+
</ConsentBannerActions>
|
|
141
|
+
</ConsentBanner>
|
|
142
|
+
) : (
|
|
143
|
+
<ConsentToggle consent={consent} />
|
|
144
|
+
);
|
|
89
145
|
}
|
|
90
146
|
```
|
|
147
|
+
|
|
148
|
+
The root gates itself on `consent.needsPrompt`; pass `open` to override — e.g. reopening
|
|
149
|
+
the banner as a "Cookie settings" panel after a decision (GDPR expects withdrawing
|
|
150
|
+
consent to be as easy as giving it).
|
|
151
|
+
|
|
152
|
+
The stored decision is the single source of truth (`useSyncExternalStore` under the
|
|
153
|
+
hood): hydration-safe on prerendered pages, and a decision made in one tab dismisses the
|
|
154
|
+
banner in every other tab via the `storage` event.
|
|
155
|
+
|
|
156
|
+
For Consent Mode v2, `setGoogleConsentDefault(decision, { waitForUpdateMs, region })`
|
|
157
|
+
issues the pre-tag default (it defines the gtag queueing stub itself), and
|
|
158
|
+
`setGoogleAdsDataRedaction`/`setGoogleUrlPassthrough` cover the denied-ads flags. A GPC
|
|
159
|
+
signal is honored as a do-not-sell-or-share opt-out: it forces `ads` denied without
|
|
160
|
+
withdrawing first-party `analytics`.
|
|
@@ -2,9 +2,17 @@ import { ConsentStorage } from "../core/consent.mjs";
|
|
|
2
2
|
|
|
3
3
|
//#region src/client/consent-storage.d.ts
|
|
4
4
|
/**
|
|
5
|
-
* `localStorage`-backed consent storage
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* `localStorage`-backed consent storage. Corrupt state, a private-mode/quota error, or no
|
|
6
|
+
* `window` (SSR) degrades to an in-memory record — the visitor's decision still applies
|
|
7
|
+
* for the session instead of re-prompting in a loop. `subscribe` fires for same-tab
|
|
8
|
+
* writes and, via the `storage` event, for decisions made in other tabs.
|
|
9
|
+
*
|
|
10
|
+
* @remarks
|
|
11
|
+
* The record persists as plain `JSON.stringify(ConsentRecord)` — a stable contract, so
|
|
12
|
+
* pre-hydration inline scripts (e.g. a Consent Mode default bootstrap) can read the
|
|
13
|
+
* decision synchronously before any tag fires.
|
|
14
|
+
*
|
|
15
|
+
* @since 0.5.0-canary.4
|
|
8
16
|
*/
|
|
9
17
|
declare function createLocalStorageConsentStorage(storageKey: string): ConsentStorage;
|
|
10
18
|
//#endregion
|
|
@@ -1,25 +1,61 @@
|
|
|
1
1
|
//#region src/client/consent-storage.ts
|
|
2
2
|
/**
|
|
3
|
-
* `localStorage`-backed consent storage
|
|
4
|
-
*
|
|
5
|
-
*
|
|
3
|
+
* `localStorage`-backed consent storage. Corrupt state, a private-mode/quota error, or no
|
|
4
|
+
* `window` (SSR) degrades to an in-memory record — the visitor's decision still applies
|
|
5
|
+
* for the session instead of re-prompting in a loop. `subscribe` fires for same-tab
|
|
6
|
+
* writes and, via the `storage` event, for decisions made in other tabs.
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* The record persists as plain `JSON.stringify(ConsentRecord)` — a stable contract, so
|
|
10
|
+
* pre-hydration inline scripts (e.g. a Consent Mode default bootstrap) can read the
|
|
11
|
+
* decision synchronously before any tag fires.
|
|
12
|
+
*
|
|
13
|
+
* @since 0.5.0-canary.4
|
|
6
14
|
*/
|
|
7
15
|
function createLocalStorageConsentStorage(storageKey) {
|
|
16
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
17
|
+
let memoryRecord;
|
|
18
|
+
function notify() {
|
|
19
|
+
for (const listener of listeners) listener();
|
|
20
|
+
}
|
|
8
21
|
return {
|
|
9
22
|
clear() {
|
|
10
|
-
|
|
23
|
+
if (typeof globalThis.window === "undefined") return;
|
|
24
|
+
memoryRecord = void 0;
|
|
25
|
+
try {
|
|
26
|
+
globalThis.window.localStorage.removeItem(storageKey);
|
|
27
|
+
} catch {}
|
|
28
|
+
notify();
|
|
11
29
|
},
|
|
12
30
|
load() {
|
|
13
|
-
|
|
14
|
-
if (!raw) return;
|
|
31
|
+
if (typeof globalThis.window === "undefined") return;
|
|
15
32
|
try {
|
|
16
|
-
|
|
33
|
+
const raw = globalThis.window.localStorage.getItem(storageKey);
|
|
34
|
+
return raw ? JSON.parse(raw) : memoryRecord;
|
|
17
35
|
} catch {
|
|
18
|
-
return;
|
|
36
|
+
return memoryRecord;
|
|
19
37
|
}
|
|
20
38
|
},
|
|
21
39
|
save(record) {
|
|
22
|
-
|
|
40
|
+
if (typeof globalThis.window === "undefined") return;
|
|
41
|
+
try {
|
|
42
|
+
globalThis.window.localStorage.setItem(storageKey, JSON.stringify(record));
|
|
43
|
+
memoryRecord = void 0;
|
|
44
|
+
} catch {
|
|
45
|
+
memoryRecord = record;
|
|
46
|
+
}
|
|
47
|
+
notify();
|
|
48
|
+
},
|
|
49
|
+
subscribe(listener) {
|
|
50
|
+
listeners.add(listener);
|
|
51
|
+
function handleStorageEvent(event) {
|
|
52
|
+
if (event.key === null || event.key === storageKey) listener();
|
|
53
|
+
}
|
|
54
|
+
if (typeof globalThis.window !== "undefined") globalThis.window.addEventListener("storage", handleStorageEvent);
|
|
55
|
+
return () => {
|
|
56
|
+
listeners.delete(listener);
|
|
57
|
+
if (typeof globalThis.window !== "undefined") globalThis.window.removeEventListener("storage", handleStorageEvent);
|
|
58
|
+
};
|
|
23
59
|
}
|
|
24
60
|
};
|
|
25
61
|
}
|
|
@@ -4,6 +4,9 @@ import { EventCatalog, EventsOf } from "../core/event-catalog.mjs";
|
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
|
|
6
6
|
//#region src/client/create-client-tracker.d.ts
|
|
7
|
+
/**
|
|
8
|
+
* @since 0.5.0-canary.4
|
|
9
|
+
*/
|
|
7
10
|
interface ClientTrackerOptions<Catalog extends EventCatalog> {
|
|
8
11
|
anonymousId: string;
|
|
9
12
|
catalog: Catalog;
|
|
@@ -12,16 +15,23 @@ interface ClientTrackerOptions<Catalog extends EventCatalog> {
|
|
|
12
15
|
maxRetries?: number;
|
|
13
16
|
storage: EventQueueStorage;
|
|
14
17
|
}
|
|
18
|
+
/**
|
|
19
|
+
* @since 0.5.0-canary.4
|
|
20
|
+
*/
|
|
15
21
|
interface ClientTracker<Catalog extends EventCatalog> {
|
|
16
22
|
/** Drops every pending event without sending it — call this when consent is revoked. */
|
|
17
23
|
clear: () => void;
|
|
18
24
|
flush: () => Promise<void>;
|
|
19
25
|
/** Synchronous, best-effort flush via `navigator.sendBeacon` — for page unload only. */
|
|
20
26
|
flushWithBeacon: (endpoint: string) => void;
|
|
27
|
+
group: (groupId: string, traits?: Record<string, unknown>) => void;
|
|
21
28
|
identify: (userId: string, traits?: Record<string, unknown>) => void;
|
|
22
29
|
page: (name?: string, props?: Record<string, unknown>) => void;
|
|
23
30
|
track: <Name extends keyof EventsOf<Catalog, "client">>(name: Name, props: z.infer<EventsOf<Catalog, "client">[Name]["schema"]>) => void;
|
|
24
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* @since 0.5.0-canary.4
|
|
34
|
+
*/
|
|
25
35
|
declare function createClientTracker<Catalog extends EventCatalog>(options: ClientTrackerOptions<Catalog>): ClientTracker<Catalog>;
|
|
26
36
|
//#endregion
|
|
27
37
|
export { ClientTracker, ClientTrackerOptions, createClientTracker };
|
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
import { generateEventId } from "../core/event-id.mjs";
|
|
2
2
|
import { EventQueue } from "./queue.mjs";
|
|
3
3
|
//#region src/client/create-client-tracker.ts
|
|
4
|
+
/**
|
|
5
|
+
* @since 0.5.0-canary.4
|
|
6
|
+
*/
|
|
4
7
|
function createClientTracker(options) {
|
|
8
|
+
const immediateDestinations = options.destinations.filter((destination) => destination.delivery === "immediate");
|
|
5
9
|
const queue = new EventQueue({
|
|
6
|
-
destinations: options.destinations,
|
|
10
|
+
destinations: options.destinations.filter((destination) => destination.delivery !== "immediate"),
|
|
7
11
|
maxQueueSize: options.maxQueueSize,
|
|
8
12
|
maxRetries: options.maxRetries,
|
|
9
13
|
storage: options.storage
|
|
@@ -19,6 +23,9 @@ function createClientTracker(options) {
|
|
|
19
23
|
timestamp: Date.now(),
|
|
20
24
|
...userId === void 0 ? {} : { userId }
|
|
21
25
|
};
|
|
26
|
+
for (const destination of immediateDestinations) try {
|
|
27
|
+
Promise.resolve(destination.send(envelope)).catch(() => {});
|
|
28
|
+
} catch {}
|
|
22
29
|
queue.enqueue(envelope);
|
|
23
30
|
}
|
|
24
31
|
return {
|
|
@@ -31,6 +38,12 @@ function createClientTracker(options) {
|
|
|
31
38
|
if (events.length === 0) return;
|
|
32
39
|
if (!navigator.sendBeacon(endpoint, JSON.stringify(events))) for (const event of events) queue.enqueue(event);
|
|
33
40
|
},
|
|
41
|
+
group(groupId, traits = {}) {
|
|
42
|
+
enqueue("$group", {
|
|
43
|
+
groupId,
|
|
44
|
+
...traits
|
|
45
|
+
});
|
|
46
|
+
},
|
|
34
47
|
identify(id, traits = {}) {
|
|
35
48
|
userId = id;
|
|
36
49
|
enqueue("$identify", traits);
|
package/dist/client/gpc.d.mts
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* Global Privacy Control isn't in lib.dom yet, hence the local interface extension.
|
|
4
4
|
* CCPA/CPRA requires honoring this as an opt-out signal even under the opt-out default.
|
|
5
|
+
*
|
|
6
|
+
* @since 0.5.0-canary.4
|
|
5
7
|
*/
|
|
6
8
|
declare function hasGlobalPrivacyControlSignal(): boolean;
|
|
7
9
|
//#endregion
|
package/dist/client/gpc.mjs
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* Global Privacy Control isn't in lib.dom yet, hence the local interface extension.
|
|
4
4
|
* CCPA/CPRA requires honoring this as an opt-out signal even under the opt-out default.
|
|
5
|
+
*
|
|
6
|
+
* @since 0.5.0-canary.4
|
|
5
7
|
*/
|
|
6
8
|
function hasGlobalPrivacyControlSignal() {
|
|
7
9
|
return navigator.globalPrivacyControl === true;
|
|
@@ -2,6 +2,9 @@ import { EventCatalog } from "../core/event-catalog.mjs";
|
|
|
2
2
|
import { ClientTracker } from "./create-client-tracker.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/client/lifecycle.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* @since 0.5.0-canary.4
|
|
7
|
+
*/
|
|
5
8
|
interface ClientLifecycleOptions {
|
|
6
9
|
/** `sendBeacon` target used on unload — omit to skip the unload flush entirely. */
|
|
7
10
|
beaconEndpoint?: string;
|
|
@@ -12,6 +15,8 @@ interface ClientLifecycleOptions {
|
|
|
12
15
|
* `EventQueue`): a periodic interval flush, and a best-effort `sendBeacon` flush on
|
|
13
16
|
* unload — `fetch` isn't reliable once the page starts unloading, `sendBeacon` is.
|
|
14
17
|
* Returns a cleanup function to remove all listeners/timers.
|
|
18
|
+
*
|
|
19
|
+
* @since 0.5.0-canary.4
|
|
15
20
|
*/
|
|
16
21
|
declare function attachClientLifecycle<Catalog extends EventCatalog>(tracker: Pick<ClientTracker<Catalog>, "flush" | "flushWithBeacon">, options?: ClientLifecycleOptions): () => void;
|
|
17
22
|
//#endregion
|
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
* `EventQueue`): a periodic interval flush, and a best-effort `sendBeacon` flush on
|
|
5
5
|
* unload — `fetch` isn't reliable once the page starts unloading, `sendBeacon` is.
|
|
6
6
|
* Returns a cleanup function to remove all listeners/timers.
|
|
7
|
+
*
|
|
8
|
+
* @since 0.5.0-canary.4
|
|
7
9
|
*/
|
|
8
10
|
function attachClientLifecycle(tracker, options = {}) {
|
|
9
11
|
const flushIntervalMs = options.flushIntervalMs ?? 1e4;
|
|
@@ -2,8 +2,11 @@ import { EventQueueStorage } from "./queue.mjs";
|
|
|
2
2
|
|
|
3
3
|
//#region src/client/local-storage.d.ts
|
|
4
4
|
/**
|
|
5
|
-
* `localStorage`-backed queue storage — corrupt/missing state
|
|
6
|
-
*
|
|
5
|
+
* `localStorage`-backed queue storage — corrupt/missing state, a private-mode/quota
|
|
6
|
+
* error, or no `window` (SSR) are all treated as empty rather than thrown, since a lost
|
|
7
|
+
* offline queue is preferable to a crashing app.
|
|
8
|
+
*
|
|
9
|
+
* @since 0.5.0-canary.4
|
|
7
10
|
*/
|
|
8
11
|
declare function createLocalStorageQueueStorage(storageKey: string): EventQueueStorage;
|
|
9
12
|
//#endregion
|
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
//#region src/client/local-storage.ts
|
|
2
2
|
/**
|
|
3
|
-
* `localStorage`-backed queue storage — corrupt/missing state
|
|
4
|
-
*
|
|
3
|
+
* `localStorage`-backed queue storage — corrupt/missing state, a private-mode/quota
|
|
4
|
+
* error, or no `window` (SSR) are all treated as empty rather than thrown, since a lost
|
|
5
|
+
* offline queue is preferable to a crashing app.
|
|
6
|
+
*
|
|
7
|
+
* @since 0.5.0-canary.4
|
|
5
8
|
*/
|
|
6
9
|
function createLocalStorageQueueStorage(storageKey) {
|
|
7
10
|
return {
|
|
8
11
|
load() {
|
|
9
|
-
|
|
10
|
-
if (!raw) return [];
|
|
12
|
+
if (typeof globalThis.window === "undefined") return [];
|
|
11
13
|
try {
|
|
14
|
+
const raw = globalThis.window.localStorage.getItem(storageKey);
|
|
15
|
+
if (!raw) return [];
|
|
12
16
|
const parsed = JSON.parse(raw);
|
|
13
17
|
return Array.isArray(parsed) ? parsed : [];
|
|
14
18
|
} catch {
|
|
@@ -16,7 +20,10 @@ function createLocalStorageQueueStorage(storageKey) {
|
|
|
16
20
|
}
|
|
17
21
|
},
|
|
18
22
|
save(events) {
|
|
19
|
-
|
|
23
|
+
if (typeof globalThis.window === "undefined") return;
|
|
24
|
+
try {
|
|
25
|
+
globalThis.window.localStorage.setItem(storageKey, JSON.stringify(events));
|
|
26
|
+
} catch {}
|
|
20
27
|
}
|
|
21
28
|
};
|
|
22
29
|
}
|
package/dist/client/queue.d.mts
CHANGED
|
@@ -5,11 +5,16 @@ import { Destination } from "../core/destination.mjs";
|
|
|
5
5
|
/**
|
|
6
6
|
* Persistence backend for the offline queue — a thin wrapper so tests and non-browser
|
|
7
7
|
* environments can swap in an in-memory implementation instead of real `localStorage`.
|
|
8
|
+
*
|
|
9
|
+
* @since 0.5.0-canary.4
|
|
8
10
|
*/
|
|
9
11
|
interface EventQueueStorage {
|
|
10
12
|
load: () => Array<TrackedEvent>;
|
|
11
13
|
save: (events: Array<TrackedEvent>) => void;
|
|
12
14
|
}
|
|
15
|
+
/**
|
|
16
|
+
* @since 0.5.0-canary.4
|
|
17
|
+
*/
|
|
13
18
|
interface EventQueueOptions {
|
|
14
19
|
destinations: Array<Destination>;
|
|
15
20
|
flushBatchSize?: number | undefined;
|
|
@@ -20,6 +25,8 @@ interface EventQueueOptions {
|
|
|
20
25
|
/**
|
|
21
26
|
* Client-side batching/offline queue: persists across reloads, caps its size
|
|
22
27
|
* (drop-oldest), and retries a failed batch up to `maxRetries` times.
|
|
28
|
+
*
|
|
29
|
+
* @since 0.5.0-canary.4
|
|
23
30
|
*/
|
|
24
31
|
declare class EventQueue {
|
|
25
32
|
private readonly destinations;
|
package/dist/client/queue.mjs
CHANGED
package/dist/client/router.d.mts
CHANGED
|
@@ -11,6 +11,8 @@ interface ResolvedNavigation {
|
|
|
11
11
|
/**
|
|
12
12
|
* Structurally matches `Router["subscribe"]` from `@tanstack/router-core` for the
|
|
13
13
|
* `"onResolved"` event — duck-typed so this package doesn't depend on TanStack Router.
|
|
14
|
+
*
|
|
15
|
+
* @since 0.5.0-canary.4
|
|
14
16
|
*/
|
|
15
17
|
interface RouterLike {
|
|
16
18
|
subscribe: (eventType: "onResolved", fn: (event: ResolvedNavigation) => void) => () => void;
|
|
@@ -20,6 +22,8 @@ interface RouterLike {
|
|
|
20
22
|
* `popstate` only fires for browser back/forward. Page views are low-frequency, so this
|
|
21
23
|
* flushes right away instead of waiting on the batch queue's interval/size threshold —
|
|
22
24
|
* a slow navigation shouldn't leave a pageview stranded if the tab closes right after.
|
|
25
|
+
*
|
|
26
|
+
* @since 0.5.0-canary.4
|
|
23
27
|
*/
|
|
24
28
|
declare function attachRouterPageTracking<Catalog extends EventCatalog>(tracker: Pick<ClientTracker<Catalog>, "flush" | "page">, router: RouterLike): () => void;
|
|
25
29
|
//#endregion
|
package/dist/client/router.mjs
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
* `popstate` only fires for browser back/forward. Page views are low-frequency, so this
|
|
5
5
|
* flushes right away instead of waiting on the batch queue's interval/size threshold —
|
|
6
6
|
* a slow navigation shouldn't leave a pageview stranded if the tab closes right after.
|
|
7
|
+
*
|
|
8
|
+
* @since 0.5.0-canary.4
|
|
7
9
|
*/
|
|
8
10
|
function attachRouterPageTracking(tracker, router) {
|
|
9
11
|
return router.subscribe("onResolved", (event) => {
|
package/dist/core/consent.d.mts
CHANGED
|
@@ -1,23 +1,68 @@
|
|
|
1
1
|
//#region src/core/consent.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* @since 0.5.0-canary.4
|
|
4
|
+
*/
|
|
2
5
|
type ConsentRegion = "eu" | "other" | "us" | "vn";
|
|
6
|
+
/**
|
|
7
|
+
* @since 0.5.0-canary.4
|
|
8
|
+
*/
|
|
3
9
|
type ConsentMode = "opt-in" | "opt-out";
|
|
4
10
|
/**
|
|
5
11
|
* GDPR (EU) and Nghị định 13/2023 (VN) require explicit opt-in before any non-essential
|
|
6
12
|
* tracking; CCPA/CPRA (US) defaults to opt-out instead. There is no single global default
|
|
7
13
|
* that satisfies both, so the mode is resolved per region.
|
|
14
|
+
*
|
|
15
|
+
* @since 0.5.0-canary.4
|
|
8
16
|
*/
|
|
9
17
|
declare function resolveConsentMode(region: ConsentRegion): ConsentMode;
|
|
10
18
|
/**
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
19
|
+
* Consent purposes, mirroring Google Consent Mode v2's split: `analytics` gates
|
|
20
|
+
* measurement (`analytics_storage`), `ads` gates advertising storage and data sharing
|
|
21
|
+
* (`ad_storage`/`ad_user_data`/`ad_personalization`).
|
|
22
|
+
*
|
|
23
|
+
* @since 0.5.0-canary.4
|
|
24
|
+
*/
|
|
25
|
+
type ConsentCategory = "ads" | "analytics";
|
|
26
|
+
/**
|
|
27
|
+
* @since 0.5.0-canary.4
|
|
28
|
+
*/
|
|
29
|
+
declare const CONSENT_CATEGORIES: ReadonlyArray<ConsentCategory>;
|
|
30
|
+
/**
|
|
31
|
+
* Per-category consent — GDPR consent must be granular per purpose, so a single
|
|
32
|
+
* granted/denied flag can't represent it. `true` means the visitor granted that purpose.
|
|
33
|
+
*
|
|
34
|
+
* @since 0.5.0-canary.4
|
|
35
|
+
*/
|
|
36
|
+
type ConsentDecision = Record<ConsentCategory, boolean>;
|
|
37
|
+
/**
|
|
38
|
+
* A decision granting exactly the given categories and denying every other one.
|
|
39
|
+
*
|
|
40
|
+
* @since 0.5.0-canary.4
|
|
41
|
+
*/
|
|
42
|
+
declare function createConsentDecision(grantedCategories: ReadonlyArray<ConsentCategory>): ConsentDecision;
|
|
43
|
+
/**
|
|
44
|
+
* Guards stored JSON — the record is tamperable, so every category must be an explicit boolean.
|
|
45
|
+
*
|
|
46
|
+
* @since 0.5.0-canary.4
|
|
47
|
+
*/
|
|
48
|
+
declare function isConsentDecision(value: unknown): value is ConsentDecision;
|
|
49
|
+
/**
|
|
50
|
+
* The effective consent before the visitor decides: opt-in regions start all-denied,
|
|
51
|
+
* opt-out regions grant the categories the app asks for.
|
|
52
|
+
*
|
|
53
|
+
* @remarks
|
|
54
|
+
* A Global Privacy Control signal is a "do not sell or share" opt-out (CCPA/CPRA), so it
|
|
55
|
+
* forces `ads` denied — it does not withdraw first-party analytics measurement.
|
|
56
|
+
*
|
|
57
|
+
* @since 0.5.0-canary.4
|
|
14
58
|
*/
|
|
15
|
-
declare function
|
|
16
|
-
type ConsentDecision = "denied" | "granted";
|
|
59
|
+
declare function resolveDefaultConsent(mode: ConsentMode, requestedCategories: ReadonlyArray<ConsentCategory>, hasGlobalPrivacyControlSignal: boolean): ConsentDecision;
|
|
17
60
|
/**
|
|
18
61
|
* NĐ 13/2023 and GDPR both expect a record of *when* and *under what policy* consent
|
|
19
|
-
* was given, not just
|
|
62
|
+
* was given, not just per-category flags — `policyVersion` lets a later policy change
|
|
20
63
|
* invalidate stale consent.
|
|
64
|
+
*
|
|
65
|
+
* @since 0.5.0-canary.4
|
|
21
66
|
*/
|
|
22
67
|
interface ConsentRecord {
|
|
23
68
|
decision: ConsentDecision;
|
|
@@ -25,13 +70,20 @@ interface ConsentRecord {
|
|
|
25
70
|
timestamp: number;
|
|
26
71
|
}
|
|
27
72
|
/**
|
|
28
|
-
* Persistence backend for the visitor's consent decision —
|
|
29
|
-
*
|
|
73
|
+
* Persistence backend for the visitor's consent decision — swap in your own
|
|
74
|
+
* implementation for non-browser environments or a different persistence layer.
|
|
75
|
+
*
|
|
76
|
+
* @since 0.5.0-canary.4
|
|
30
77
|
*/
|
|
31
78
|
interface ConsentStorage {
|
|
32
79
|
clear: () => void;
|
|
33
80
|
load: () => ConsentRecord | undefined;
|
|
34
81
|
save: (record: ConsentRecord) => void;
|
|
82
|
+
/**
|
|
83
|
+
* Notify on any change to the stored record, including writes from other tabs — this
|
|
84
|
+
* is what drives `useConsent`'s external-store subscription. Returns an unsubscribe.
|
|
85
|
+
*/
|
|
86
|
+
subscribe: (listener: () => void) => () => void;
|
|
35
87
|
}
|
|
36
88
|
//#endregion
|
|
37
|
-
export { ConsentDecision, ConsentMode, ConsentRecord, ConsentRegion, ConsentStorage, resolveConsentMode,
|
|
89
|
+
export { CONSENT_CATEGORIES, ConsentCategory, ConsentDecision, ConsentMode, ConsentRecord, ConsentRegion, ConsentStorage, createConsentDecision, isConsentDecision, resolveConsentMode, resolveDefaultConsent };
|