@codefast/tracking 0.0.0 → 0.5.0-canary.4

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.
Files changed (71) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +46 -8
  3. package/dist/client/consent-storage.d.mts +11 -3
  4. package/dist/client/consent-storage.mjs +45 -9
  5. package/dist/client/create-client-tracker.d.mts +10 -0
  6. package/dist/client/create-client-tracker.mjs +14 -1
  7. package/dist/client/gpc.d.mts +2 -0
  8. package/dist/client/gpc.mjs +2 -0
  9. package/dist/client/lifecycle.d.mts +5 -0
  10. package/dist/client/lifecycle.mjs +2 -0
  11. package/dist/client/local-storage.d.mts +5 -2
  12. package/dist/client/local-storage.mjs +12 -5
  13. package/dist/client/queue.d.mts +7 -0
  14. package/dist/client/queue.mjs +2 -0
  15. package/dist/client/router.d.mts +4 -0
  16. package/dist/client/router.mjs +2 -0
  17. package/dist/core/consent.d.mts +61 -9
  18. package/dist/core/consent.mjs +39 -7
  19. package/dist/core/destination.d.mts +10 -0
  20. package/dist/core/event-catalog.d.mts +8 -0
  21. package/dist/core/event-catalog.mjs +2 -0
  22. package/dist/core/event-id.d.mts +2 -0
  23. package/dist/core/event-id.mjs +2 -0
  24. package/dist/core/index.d.mts +2 -2
  25. package/dist/core/index.mjs +2 -2
  26. package/dist/core/tracked-event.d.mts +2 -0
  27. package/dist/destinations/ga4-measurement-protocol.d.mts +54 -0
  28. package/dist/destinations/ga4-measurement-protocol.mjs +89 -0
  29. package/dist/destinations/google-analytics.d.mts +98 -0
  30. package/dist/destinations/google-analytics.mjs +126 -0
  31. package/dist/destinations/http-destination.d.mts +5 -0
  32. package/dist/destinations/http-destination.mjs +2 -0
  33. package/dist/destinations/index.d.mts +3 -1
  34. package/dist/destinations/index.mjs +3 -1
  35. package/dist/destinations/vercel-analytics.d.mts +4 -2
  36. package/dist/destinations/vercel-analytics.mjs +5 -2
  37. package/dist/index.d.mts +2 -2
  38. package/dist/index.mjs +2 -2
  39. package/dist/react/consent-banner.d.mts +48 -14
  40. package/dist/react/consent-banner.mjs +94 -22
  41. package/dist/react/index.d.mts +2 -2
  42. package/dist/react/use-consent.d.mts +30 -5
  43. package/dist/react/use-consent.mjs +38 -15
  44. package/dist/server/create-server-tracker.d.mts +14 -0
  45. package/dist/server/create-server-tracker.mjs +24 -5
  46. package/dist/server/region.d.mts +4 -0
  47. package/dist/server/region.mjs +4 -0
  48. package/package.json +12 -2
  49. package/src/client/consent-storage.ts +75 -10
  50. package/src/client/create-client-tracker.ts +30 -1
  51. package/src/client/gpc.ts +2 -0
  52. package/src/client/lifecycle.ts +5 -0
  53. package/src/client/local-storage.ts +21 -6
  54. package/src/client/queue.ts +7 -0
  55. package/src/client/router.ts +4 -0
  56. package/src/core/consent.ts +85 -11
  57. package/src/core/destination.ts +10 -0
  58. package/src/core/event-catalog.ts +8 -0
  59. package/src/core/event-id.ts +2 -0
  60. package/src/core/index.ts +15 -2
  61. package/src/core/tracked-event.ts +2 -0
  62. package/src/destinations/ga4-measurement-protocol.ts +166 -0
  63. package/src/destinations/google-analytics.ts +233 -0
  64. package/src/destinations/http-destination.ts +5 -0
  65. package/src/destinations/index.ts +16 -0
  66. package/src/destinations/vercel-analytics.ts +5 -2
  67. package/src/react/consent-banner.tsx +121 -22
  68. package/src/react/index.ts +1 -1
  69. package/src/react/use-consent.ts +81 -23
  70. package/src/server/create-server-tracker.ts +39 -16
  71. package/src/server/region.ts +4 -0
@@ -0,0 +1,233 @@
1
+ import type { ConsentDecision } from "#/core/consent";
2
+ import type { Destination } from "#/core/destination";
3
+
4
+ type GtagPropertyValue = boolean | number | string;
5
+
6
+ type GoogleConsentState = "denied" | "granted";
7
+
8
+ interface GoogleConsentParams {
9
+ ad_personalization: GoogleConsentState;
10
+ ad_storage: GoogleConsentState;
11
+ ad_user_data: GoogleConsentState;
12
+ analytics_storage: GoogleConsentState;
13
+ region?: ReadonlyArray<string>;
14
+ wait_for_update?: number;
15
+ }
16
+
17
+ /**
18
+ * All signatures share one `gtag` global, so they must live in a single overloaded type —
19
+ * two separate `declare global` augmentations with different signatures for the same
20
+ * property is a TS error, not a merge.
21
+ */
22
+ type GtagFunction = {
23
+ (command: "consent", action: "default" | "update", params: GoogleConsentParams): void;
24
+ (command: "event", eventName: string, params?: Record<string, GtagPropertyValue>): void;
25
+ (command: "set", params: Record<string, GtagPropertyValue>): void;
26
+ (command: "set", key: string, value: boolean): void;
27
+ };
28
+
29
+ declare global {
30
+ interface Window {
31
+ dataLayer?: Array<unknown>;
32
+ gtag?: GtagFunction;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * The visitor's per-category decision maps onto Consent Mode v2's signals: `analytics`
38
+ * drives `analytics_storage`; `ads` drives all three ads signals together — a banner
39
+ * that got ads consent got it for storage, sharing, and personalization alike.
40
+ */
41
+ function toGoogleConsentParams(decision: ConsentDecision): GoogleConsentParams {
42
+ const ads: GoogleConsentState = decision.ads ? "granted" : "denied";
43
+
44
+ return {
45
+ ad_personalization: ads,
46
+ ad_storage: ads,
47
+ ad_user_data: ads,
48
+ analytics_storage: decision.analytics ? "granted" : "denied",
49
+ };
50
+ }
51
+
52
+ /**
53
+ * Ensures the standard gtag.js queueing stub exists so consent commands can be issued
54
+ * before the tag itself loads — gtag.js replays the queue in order once it boots.
55
+ */
56
+ function ensureGtag(): GtagFunction | undefined {
57
+ if (typeof window === "undefined") {
58
+ return undefined;
59
+ }
60
+
61
+ window.dataLayer ??= [];
62
+
63
+ // gtag.js requires the live Arguments object on the dataLayer — pushing an array is
64
+ // treated as a GTM message, not a gtag command.
65
+ window.gtag ??= function gtag() {
66
+ window.dataLayer?.push(arguments);
67
+ } as GtagFunction;
68
+
69
+ return window.gtag;
70
+ }
71
+
72
+ /**
73
+ * @since 0.5.0-canary.4
74
+ */
75
+ export interface GoogleConsentDefaultOptions {
76
+ /** Restrict the default to these ISO 3166-2 codes (gtag's `region` param); omit for a global default. */
77
+ region?: ReadonlyArray<string>;
78
+ /** Consent Mode's `wait_for_update` — how long tags hold hits so a stored decision can arrive as an update first. */
79
+ waitForUpdateMs?: number;
80
+ }
81
+
82
+ /**
83
+ * Google Consent Mode v2's "default" signal — call before the gtag.js script tag loads
84
+ * (this defines the queueing stub itself, so no snippet has to run first) with the
85
+ * region-resolved default, so GA4/Ads never fire a hit ahead of it.
86
+ *
87
+ * @since 0.5.0-canary.4
88
+ */
89
+ export function setGoogleConsentDefault(decision: ConsentDecision, options: GoogleConsentDefaultOptions = {}): void {
90
+ const params = toGoogleConsentParams(decision);
91
+
92
+ if (options.region !== undefined) {
93
+ params.region = options.region;
94
+ }
95
+
96
+ if (options.waitForUpdateMs !== undefined) {
97
+ params.wait_for_update = options.waitForUpdateMs;
98
+ }
99
+
100
+ ensureGtag()?.("consent", "default", params);
101
+ }
102
+
103
+ /**
104
+ * Google Consent Mode v2's "update" signal — call whenever the visitor's effective
105
+ * consent changes (a banner decision, or one synced from another tab), so already-loaded
106
+ * GA4/Ads tags pick up the change without a page reload.
107
+ *
108
+ * @since 0.5.0-canary.4
109
+ */
110
+ export function updateGoogleConsent(decision: ConsentDecision): void {
111
+ ensureGtag()?.("consent", "update", toGoogleConsentParams(decision));
112
+ }
113
+
114
+ /**
115
+ * Consent Mode's `ads_data_redaction` flag — with `ad_storage` denied, gtag further
116
+ * redacts ad click identifiers (gclid/dclid) from its cookieless pings. Set alongside
117
+ * the consent default.
118
+ *
119
+ * @since 0.5.0-canary.4
120
+ */
121
+ export function setGoogleAdsDataRedaction(enabled: boolean): void {
122
+ ensureGtag()?.("set", "ads_data_redaction", enabled);
123
+ }
124
+
125
+ /**
126
+ * Consent Mode's `url_passthrough` flag — carries ad click info through page URLs while
127
+ * storage is denied, preserving conversion attribution without cookies.
128
+ *
129
+ * @since 0.5.0-canary.4
130
+ */
131
+ export function setGoogleUrlPassthrough(enabled: boolean): void {
132
+ ensureGtag()?.("set", "url_passthrough", enabled);
133
+ }
134
+
135
+ /**
136
+ * gtag.js event params must be flat string/number/boolean — stringify anything else
137
+ * instead of letting GA4 silently drop it.
138
+ */
139
+ function toGtagParams(props: Record<string, unknown>): Record<string, GtagPropertyValue> {
140
+ const result: Record<string, GtagPropertyValue> = {};
141
+
142
+ for (const [key, value] of Object.entries(props)) {
143
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
144
+ result[key] = value;
145
+ } else if (value !== undefined && value !== null) {
146
+ result[key] = JSON.stringify(value);
147
+ }
148
+ }
149
+
150
+ return result;
151
+ }
152
+
153
+ // GA4 rejects event names that don't start with a letter or exceed 40 chars — a `$`-prefixed
154
+ // or otherwise invalid name would be dropped at processing without any signal to the dev.
155
+ const GA4_EVENT_NAME_PATTERN = /^[A-Za-z][\w]{0,39}$/;
156
+
157
+ /**
158
+ * @since 0.5.0-canary.4
159
+ */
160
+ export interface GoogleAnalyticsDestinationOptions {
161
+ name?: string;
162
+ /**
163
+ * Forward `$page_viewed` as GA4's `page_view`. Off by default: `gtag('config', ...)`
164
+ * sends the initial page_view and GA4's Enhanced Measurement (on by default in admin)
165
+ * tracks SPA history changes, so forwarding here would double-count. Enable only after
166
+ * setting `send_page_view: false` on config and disabling Enhanced Measurement's
167
+ * history-based page views.
168
+ */
169
+ trackPageViews?: boolean;
170
+ }
171
+
172
+ /**
173
+ * Forwards events to `window.gtag`, translating this package's `$`-prefixed built-ins to
174
+ * GA4's vocabulary — `$identify` sets `user_id`, `$group` becomes the recommended
175
+ * `join_group` event, `$page_viewed` maps to `page_view` (opt-in, see `trackPageViews`).
176
+ * Requires the gtag.js snippet plus `gtag('config', measurementId)` mounted once by the
177
+ * app. Marked `delivery: "immediate"` — gtag.js has its own batching and unload delivery,
178
+ * so queueing in front of it only delays events and replays stale ones next session.
179
+ *
180
+ * @since 0.5.0-canary.4
181
+ */
182
+ export function createGoogleAnalyticsDestination(options: GoogleAnalyticsDestinationOptions = {}): Destination {
183
+ const name = options.name ?? "google-analytics";
184
+
185
+ return {
186
+ delivery: "immediate",
187
+ name,
188
+ send(event) {
189
+ if (typeof window === "undefined" || typeof window.gtag !== "function") {
190
+ return;
191
+ }
192
+
193
+ if (event.name === "$identify") {
194
+ // GA4 has no identify event — user_id is set once and rides along on later hits.
195
+ if (event.userId !== undefined) {
196
+ window.gtag("set", { user_id: event.userId });
197
+ }
198
+
199
+ return;
200
+ }
201
+
202
+ if (event.name === "$page_viewed") {
203
+ if (options.trackPageViews === true) {
204
+ // gtag.js attaches page_location/page_title from the live document itself, so
205
+ // only the caller's extra props are forwarded.
206
+ const { href: _href, name: _name, ...extras } = event.props;
207
+
208
+ window.gtag("event", "page_view", toGtagParams(extras));
209
+ }
210
+
211
+ return;
212
+ }
213
+
214
+ if (event.name === "$group") {
215
+ const { groupId, ...traits } = event.props;
216
+
217
+ window.gtag("event", "join_group", toGtagParams({ group_id: groupId, ...traits }));
218
+
219
+ return;
220
+ }
221
+
222
+ if (!GA4_EVENT_NAME_PATTERN.test(event.name)) {
223
+ console.warn(
224
+ `[tracking] "${name}" dropped event "${event.name}" — GA4 event names must start with a letter and contain only letters, digits, or underscores (max 40 chars)`,
225
+ );
226
+
227
+ return;
228
+ }
229
+
230
+ window.gtag("event", event.name, toGtagParams(event.props));
231
+ },
232
+ };
233
+ }
@@ -1,5 +1,8 @@
1
1
  import type { Destination } from "#/core/destination";
2
2
 
3
+ /**
4
+ * @since 0.5.0-canary.4
5
+ */
3
6
  export interface HttpDestinationOptions {
4
7
  endpoint: string;
5
8
  headers?: Record<string, string>;
@@ -9,6 +12,8 @@ export interface HttpDestinationOptions {
9
12
  /**
10
13
  * Generic fetch-based `Destination` — the building block for a real provider adapter
11
14
  * (PostHog, GA4, ...); those ship their own payload shape and aren't implemented here.
15
+ *
16
+ * @since 0.5.0-canary.4
12
17
  */
13
18
  export function createHttpDestination(options: HttpDestinationOptions): Destination {
14
19
  return {
@@ -1,3 +1,19 @@
1
+ export type { Ga4MeasurementProtocolDestinationOptions } from "#/destinations/ga4-measurement-protocol";
2
+ export {
3
+ createGa4MeasurementProtocolDestination,
4
+ extractGa4ClientId,
5
+ extractGa4SessionId,
6
+ } from "#/destinations/ga4-measurement-protocol";
7
+
8
+ export type { GoogleAnalyticsDestinationOptions, GoogleConsentDefaultOptions } from "#/destinations/google-analytics";
9
+ export {
10
+ createGoogleAnalyticsDestination,
11
+ setGoogleAdsDataRedaction,
12
+ setGoogleConsentDefault,
13
+ setGoogleUrlPassthrough,
14
+ updateGoogleConsent,
15
+ } from "#/destinations/google-analytics";
16
+
1
17
  export type { HttpDestinationOptions } from "#/destinations/http-destination";
2
18
  export { createHttpDestination } from "#/destinations/http-destination";
3
19
 
@@ -23,12 +23,15 @@ function toVercelAnalyticsProps(props: Record<string, unknown>): Record<string,
23
23
  }
24
24
 
25
25
  /**
26
- * `track()` only pushes onto Vercel's own in-page queue (`window.va`/`window.vaq`) — it
27
- * never rejects, so this destination never triggers `EventQueue`'s retry path. Requires
26
+ * `track()` only pushes onto Vercel's own in-page queue (`window.va`/`window.vaq`), which
27
+ * handles batching and unload delivery itself — hence `delivery: "immediate"`. Requires
28
28
  * `<Analytics />` from `@vercel/analytics/react` to be mounted once in the app.
29
+ *
30
+ * @since 0.5.0-canary.4
29
31
  */
30
32
  export function createVercelAnalyticsDestination(name = "vercel-analytics"): Destination {
31
33
  return {
34
+ delivery: "immediate",
32
35
  name,
33
36
  send(event) {
34
37
  track(event.name, toVercelAnalyticsProps(event.props));
@@ -1,47 +1,135 @@
1
- import type { ReactNode } from "react";
1
+ import type { ComponentProps, ReactNode } from "react";
2
+ import { useState } from "react";
2
3
 
4
+ import type { ConsentCategory, ConsentDecision } from "#/core/consent";
5
+ import { CONSENT_CATEGORIES } from "#/core/consent";
3
6
  import type { UseConsentResult } from "#/react/use-consent";
4
7
 
5
- export interface ConsentBannerProps {
8
+ /**
9
+ * One row of the preferences layer — the visitor-facing wording for a consent category.
10
+ *
11
+ * @since 0.5.0-canary.4
12
+ */
13
+ export interface ConsentCategoryOption {
14
+ category: ConsentCategory;
15
+ description?: string;
16
+ label: string;
17
+ }
18
+
19
+ /**
20
+ * @since 0.5.0-canary.4
21
+ */
22
+ export interface ConsentBannerProps extends Omit<ComponentProps<"section">, "children"> {
6
23
  acceptLabel?: string;
7
- className?: string;
24
+ /** Enables the per-category preferences layer; omit to keep the two-button banner. */
25
+ categories?: ReadonlyArray<ConsentCategoryOption>;
8
26
  consent: UseConsentResult;
9
- message?: string;
27
+ customizeLabel?: string;
28
+ /** A node, not just a string — informed consent needs the privacy-policy link inside the message. */
29
+ message?: ReactNode;
10
30
  rejectLabel?: string;
31
+ saveLabel?: string;
11
32
  }
12
33
 
13
34
  /**
14
- * Blocking opt-in prompt for GDPR/NĐ 13 regions — renders nothing once a decision
15
- * exists or the region defaults to opt-out (`consent.needsPrompt` covers both). No
16
- * styling is baked in; pass `className` to match the host app's design system.
35
+ * Non-blocking opt-in prompt for GDPR/NĐ 13 regions — renders nothing once a decision
36
+ * exists or the region defaults to opt-out (`consent.needsPrompt` covers both). Accept
37
+ * grants only the categories the app requested (`useConsent`'s `categories`), and the
38
+ * optional `categories` prop adds a second layer of per-category checkboxes — GDPR
39
+ * consent must be granular per purpose, not a single yes/no. Rendered as a labeled
40
+ * region, not a `<dialog>`: an open non-modal dialog neither traps focus nor blocks the
41
+ * page, so the dialog semantics would over-promise. No styling is baked in — target the
42
+ * root via `className` and the parts via their `data-slot` attributes (`consent-message`,
43
+ * `consent-actions`, `consent-action`, `consent-preferences`, `consent-category`).
44
+ *
45
+ * @since 0.5.0-canary.4
17
46
  */
18
47
  export function ConsentBanner({
19
48
  acceptLabel = "Accept",
20
- className,
49
+ categories,
21
50
  consent,
51
+ customizeLabel = "Customize",
22
52
  message = "We use cookies to understand how you use this site.",
23
53
  rejectLabel = "Reject",
54
+ saveLabel = "Save preferences",
55
+ ...props
24
56
  }: ConsentBannerProps): ReactNode {
57
+ // The pending per-category selection — `undefined` while the preferences layer is closed.
58
+ const [pending, setPending] = useState<ConsentDecision | undefined>(undefined);
59
+
25
60
  if (!consent.needsPrompt) {
26
61
  return null;
27
62
  }
28
63
 
29
64
  return (
30
- <dialog aria-live="polite" className={className} open>
31
- <p>{message}</p>
32
- <button onClick={consent.grant} type="button">
33
- {acceptLabel}
34
- </button>
35
- <button onClick={consent.deny} type="button">
36
- {rejectLabel}
37
- </button>
38
- </dialog>
65
+ <section aria-label="Cookie consent" data-slot="consent-banner" {...props}>
66
+ <p data-slot="consent-message">{message}</p>
67
+ {pending !== undefined && categories !== undefined ? (
68
+ <div data-slot="consent-preferences">
69
+ {categories.map((option) => (
70
+ <label data-slot="consent-category" key={option.category}>
71
+ <input
72
+ checked={pending[option.category]}
73
+ data-slot="consent-category-checkbox"
74
+ onChange={(event) => {
75
+ setPending({ ...pending, [option.category]: event.target.checked });
76
+ }}
77
+ type="checkbox"
78
+ />
79
+ <span data-slot="consent-category-label">{option.label}</span>
80
+ {option.description === undefined ? null : (
81
+ <span data-slot="consent-category-description">{option.description}</span>
82
+ )}
83
+ </label>
84
+ ))}
85
+ </div>
86
+ ) : null}
87
+ <div data-slot="consent-actions">
88
+ {pending === undefined ? (
89
+ <>
90
+ <button data-action="accept" data-slot="consent-action" onClick={consent.grantAll} type="button">
91
+ {acceptLabel}
92
+ </button>
93
+ <button data-action="reject" data-slot="consent-action" onClick={consent.denyAll} type="button">
94
+ {rejectLabel}
95
+ </button>
96
+ {categories !== undefined && categories.length > 0 ? (
97
+ <button
98
+ data-action="customize"
99
+ data-slot="consent-action"
100
+ onClick={() => {
101
+ // Starts from the current effective state — all-denied in opt-in regions,
102
+ // so no box arrives pre-ticked (pre-ticked consent is invalid under GDPR).
103
+ setPending(consent.effectiveConsent);
104
+ }}
105
+ type="button"
106
+ >
107
+ {customizeLabel}
108
+ </button>
109
+ ) : null}
110
+ </>
111
+ ) : (
112
+ <button
113
+ data-action="save"
114
+ data-slot="consent-action"
115
+ onClick={() => {
116
+ consent.save(pending);
117
+ }}
118
+ type="button"
119
+ >
120
+ {saveLabel}
121
+ </button>
122
+ )}
123
+ </div>
124
+ </section>
39
125
  );
40
126
  }
41
127
 
42
- export interface ConsentToggleProps {
128
+ /**
129
+ * @since 0.5.0-canary.4
130
+ */
131
+ export interface ConsentToggleProps extends Omit<ComponentProps<"button">, "children" | "onClick" | "type"> {
43
132
  allowLabel?: string;
44
- className?: string;
45
133
  consent: UseConsentResult;
46
134
  denyLabel?: string;
47
135
  }
@@ -49,16 +137,27 @@ export interface ConsentToggleProps {
49
137
  /**
50
138
  * Always-visible control for opt-out regions — CCPA/CPRA requires a persistent
51
139
  * "Do Not Sell or Share My Personal Information" mechanism, not just a one-time prompt.
140
+ * Flips between denying everything and re-granting the app's requested categories.
141
+ *
142
+ * @since 0.5.0-canary.4
52
143
  */
53
144
  export function ConsentToggle({
54
145
  allowLabel = "Allow tracking",
55
- className,
56
146
  consent,
57
147
  denyLabel = "Do Not Sell or Share My Personal Information",
148
+ ...props
58
149
  }: ConsentToggleProps): ReactNode {
150
+ const anyAllowed = CONSENT_CATEGORIES.some((category) => consent.effectiveConsent[category]);
151
+
59
152
  return (
60
- <button className={className} onClick={consent.isTrackingAllowed ? consent.deny : consent.grant} type="button">
61
- {consent.isTrackingAllowed ? denyLabel : allowLabel}
153
+ <button
154
+ data-slot="consent-toggle"
155
+ {...props}
156
+ // the toggle owns its click — flipping the stored decision is its whole purpose
157
+ onClick={anyAllowed ? consent.denyAll : consent.grantAll}
158
+ type="button"
159
+ >
160
+ {anyAllowed ? denyLabel : allowLabel}
62
161
  </button>
63
162
  );
64
163
  }
@@ -1,4 +1,4 @@
1
- export type { ConsentBannerProps, ConsentToggleProps } from "#/react/consent-banner";
1
+ export type { ConsentBannerProps, ConsentCategoryOption, ConsentToggleProps } from "#/react/consent-banner";
2
2
  export { ConsentBanner, ConsentToggle } from "#/react/consent-banner";
3
3
 
4
4
  export type { UseConsentOptions, UseConsentResult } from "#/react/use-consent";
@@ -1,53 +1,111 @@
1
- import { useCallback, useState } from "react";
1
+ import { useRef, useSyncExternalStore } from "react";
2
2
 
3
- import type { ConsentDecision, ConsentMode, ConsentStorage } from "#/core/consent";
4
- import { shouldTrackByDefault } from "#/core/consent";
3
+ import type { ConsentCategory, ConsentDecision, ConsentMode, ConsentStorage } from "#/core/consent";
4
+ import { CONSENT_CATEGORIES, createConsentDecision, isConsentDecision, resolveDefaultConsent } from "#/core/consent";
5
5
 
6
+ /**
7
+ * @since 0.5.0-canary.4
8
+ */
6
9
  export interface UseConsentOptions {
10
+ /**
11
+ * Categories the app's prompt actually asks about — `grantAll` grants exactly these,
12
+ * so an analytics-only banner can never grant ads consent it never asked for.
13
+ * Defaults to `["analytics"]`.
14
+ */
15
+ categories?: ReadonlyArray<ConsentCategory>;
7
16
  hasGlobalPrivacyControlSignal?: boolean;
8
17
  mode: ConsentMode;
9
18
  onDecision?: (decision: ConsentDecision) => void;
10
19
  policyVersion: string;
20
+ /** Must be a stable reference (module-level or memoized) — a new object per render resubscribes every render. */
11
21
  storage: ConsentStorage;
12
22
  }
13
23
 
24
+ /**
25
+ * @since 0.5.0-canary.4
26
+ */
14
27
  export interface UseConsentResult {
15
- deny: () => void;
16
- grant: () => void;
28
+ /** The stored decision under the current policy version — `undefined` until the visitor makes one. */
29
+ decision: ConsentDecision | undefined;
30
+ denyAll: () => void;
31
+ /** What tags must obey right now — the stored decision, or the region default before one exists. */
32
+ effectiveConsent: ConsentDecision;
33
+ grantAll: () => void;
34
+ /** Effective `analytics` consent — gates this package's own tracker pipeline. */
17
35
  isTrackingAllowed: boolean;
18
36
  /** True only for opt-in regions with no stored decision yet — drives whether to render the banner. */
19
37
  needsPrompt: boolean;
38
+ /** Persist a granular per-category choice, e.g. from a preferences panel. */
39
+ save: (decision: ConsentDecision) => void;
20
40
  }
21
41
 
42
+ const DEFAULT_CATEGORIES: ReadonlyArray<ConsentCategory> = ["analytics"];
43
+
22
44
  /**
23
- * Bridges `resolveConsentMode`/`shouldTrackByDefault` (core, region-aware) to React state,
24
- * persisting the visitor's decision via the given `ConsentStorage`.
45
+ * Bridges `resolveConsentMode`/`resolveDefaultConsent` (core, region-aware) to React via
46
+ * `useSyncExternalStore`: the stored record is the single source of truth, hydration is
47
+ * safe by construction (the server snapshot is always "no decision yet", matching what
48
+ * prerendered HTML could know), and a decision made in another tab syncs through the
49
+ * storage subscription.
50
+ *
51
+ * @since 0.5.0-canary.4
25
52
  */
26
53
  export function useConsent(options: UseConsentOptions): UseConsentResult {
27
- const [decision, setDecision] = useState<ConsentDecision | undefined>(() => options.storage.load()?.decision);
54
+ const { storage } = options;
55
+ const categories = options.categories ?? DEFAULT_CATEGORIES;
56
+
57
+ // useSyncExternalStore needs a referentially stable snapshot, but JSON-backed storages
58
+ // parse a fresh record per load — so the last valid decision is cached by value.
59
+ const cachedDecision = useRef<ConsentDecision | undefined>(undefined);
60
+
61
+ const decision = useSyncExternalStore(
62
+ storage.subscribe,
63
+ (): ConsentDecision | undefined => {
64
+ const record = storage.load();
28
65
 
29
- const decide = useCallback(
30
- (next: ConsentDecision): void => {
31
- options.storage.save({ decision: next, policyVersion: options.policyVersion, timestamp: Date.now() });
32
- setDecision(next);
33
- options.onDecision?.(next);
66
+ // Only a well-formed decision under the current policy version counts — the store
67
+ // is tamperable plain JSON, and a garbage value must re-prompt, not silently deny.
68
+ if (record?.policyVersion !== options.policyVersion || !isConsentDecision(record.decision)) {
69
+ cachedDecision.current = undefined;
70
+
71
+ return undefined;
72
+ }
73
+
74
+ const stored = record.decision;
75
+ const cached = cachedDecision.current;
76
+
77
+ if (cached !== undefined && CONSENT_CATEGORIES.every((category) => cached[category] === stored[category])) {
78
+ return cached;
79
+ }
80
+
81
+ // A normalized copy, so tampered extra keys never leak past the hook.
82
+ cachedDecision.current = createConsentDecision(CONSENT_CATEGORIES.filter((category) => stored[category]));
83
+
84
+ return cachedDecision.current;
34
85
  },
35
- [options],
86
+ () => undefined,
36
87
  );
37
88
 
38
- const isTrackingAllowed =
39
- decision === undefined
40
- ? shouldTrackByDefault(options.mode, options.hasGlobalPrivacyControlSignal ?? false)
41
- : decision === "granted";
89
+ function save(next: ConsentDecision): void {
90
+ // No local state — the save notifies the subscription, which re-renders with the new snapshot.
91
+ storage.save({ decision: next, policyVersion: options.policyVersion, timestamp: Date.now() });
92
+ options.onDecision?.(next);
93
+ }
94
+
95
+ const effectiveConsent =
96
+ decision ?? resolveDefaultConsent(options.mode, categories, options.hasGlobalPrivacyControlSignal ?? false);
42
97
 
43
98
  return {
44
- deny: () => {
45
- decide("denied");
99
+ decision,
100
+ denyAll: () => {
101
+ save(createConsentDecision([]));
46
102
  },
47
- grant: () => {
48
- decide("granted");
103
+ effectiveConsent,
104
+ grantAll: () => {
105
+ save(createConsentDecision(categories));
49
106
  },
50
- isTrackingAllowed,
107
+ isTrackingAllowed: effectiveConsent.analytics,
51
108
  needsPrompt: options.mode === "opt-in" && decision === undefined,
109
+ save,
52
110
  };
53
111
  }