@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
|
@@ -1,47 +1,306 @@
|
|
|
1
|
-
import type { ReactNode } from "react";
|
|
1
|
+
import type { ComponentProps, Dispatch, ReactNode, SetStateAction } from "react";
|
|
2
|
+
import { createContext, useContext, useEffect, 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
|
-
|
|
6
|
-
acceptLabel?: string;
|
|
7
|
-
className?: string;
|
|
8
|
+
interface ConsentBannerContextValue {
|
|
8
9
|
consent: UseConsentResult;
|
|
9
|
-
|
|
10
|
-
|
|
10
|
+
/** The in-progress per-category selection — `undefined` while the preferences layer is closed. */
|
|
11
|
+
pending: ConsentDecision | undefined;
|
|
12
|
+
setPending: Dispatch<SetStateAction<ConsentDecision | undefined>>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const ConsentBannerContext = createContext<ConsentBannerContextValue | null>(null);
|
|
16
|
+
|
|
17
|
+
function useConsentBannerContext(part: string): ConsentBannerContextValue {
|
|
18
|
+
const context = useContext(ConsentBannerContext);
|
|
19
|
+
|
|
20
|
+
if (context === null) {
|
|
21
|
+
throw new Error(`\`${part}\` must be rendered inside \`ConsentBanner\``);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
return context;
|
|
11
25
|
}
|
|
12
26
|
|
|
13
27
|
/**
|
|
14
|
-
*
|
|
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.
|
|
28
|
+
* @since 0.5.0-canary.4
|
|
17
29
|
*/
|
|
18
|
-
export
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
30
|
+
export interface ConsentBannerProps extends ComponentProps<"section"> {
|
|
31
|
+
consent: UseConsentResult;
|
|
32
|
+
/** Overrides the default `needsPrompt` gating — e.g. to reopen the banner as a settings panel. */
|
|
33
|
+
open?: boolean | undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Non-blocking opt-in prompt for GDPR/NĐ 13 regions, as composable parts — the root owns
|
|
38
|
+
* the visibility gating and the preferences-layer state; the `Accept`/`Reject`/`Customize`/
|
|
39
|
+
* `Save` parts wire their own clicks to the consent hook, so any markup (including a
|
|
40
|
+
* design system's button styles via `className`) slots in. Renders nothing once a decision
|
|
41
|
+
* exists or the region defaults to opt-out (`consent.needsPrompt`), unless `open` says
|
|
42
|
+
* otherwise. Rendered as a labeled region, not a `<dialog>`: an open non-modal dialog
|
|
43
|
+
* neither traps focus nor blocks the page, so the dialog semantics would over-promise.
|
|
44
|
+
* Unstyled by default — style via `className`/`data-slot` selectors, or import the
|
|
45
|
+
* optional `@codefast/tracking/css/consent.css` theme. `data-state` on the root flips
|
|
46
|
+
* between `prompt` and `preferences` for state-dependent styling.
|
|
47
|
+
*
|
|
48
|
+
* @since 0.5.0-canary.4
|
|
49
|
+
*/
|
|
50
|
+
export function ConsentBanner({ children, consent, open, ...props }: ConsentBannerProps): ReactNode {
|
|
51
|
+
const [pending, setPending] = useState<ConsentDecision | undefined>(undefined);
|
|
52
|
+
|
|
53
|
+
const isVisible = open ?? consent.needsPrompt;
|
|
54
|
+
|
|
55
|
+
// Closing must reset the layer — a reopened banner starts at the prompt, not mid-preferences.
|
|
56
|
+
useEffect(() => {
|
|
57
|
+
if (!isVisible) {
|
|
58
|
+
setPending(undefined);
|
|
59
|
+
}
|
|
60
|
+
}, [isVisible]);
|
|
61
|
+
|
|
62
|
+
if (!isVisible) {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return (
|
|
67
|
+
<ConsentBannerContext.Provider value={{ consent, pending, setPending }}>
|
|
68
|
+
<section
|
|
69
|
+
aria-label="Cookie consent"
|
|
70
|
+
data-slot="consent-banner"
|
|
71
|
+
data-state={pending === undefined ? "prompt" : "preferences"}
|
|
72
|
+
{...props}
|
|
73
|
+
>
|
|
74
|
+
{children}
|
|
75
|
+
</section>
|
|
76
|
+
</ConsentBannerContext.Provider>
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* @since 0.5.0-canary.5
|
|
82
|
+
*/
|
|
83
|
+
export interface ConsentBannerTitleProps extends ComponentProps<"h2"> {}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* @since 0.5.0-canary.5
|
|
87
|
+
*/
|
|
88
|
+
export function ConsentBannerTitle({ children, ...props }: ConsentBannerTitleProps): ReactNode {
|
|
89
|
+
return (
|
|
90
|
+
<h2 data-slot="consent-title" {...props}>
|
|
91
|
+
{children}
|
|
92
|
+
</h2>
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* @since 0.5.0-canary.5
|
|
98
|
+
*/
|
|
99
|
+
export interface ConsentBannerDescriptionProps extends ComponentProps<"p"> {}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Hosts the message and the privacy-policy link informed consent requires.
|
|
103
|
+
*
|
|
104
|
+
* @since 0.5.0-canary.5
|
|
105
|
+
*/
|
|
106
|
+
export function ConsentBannerDescription(props: ConsentBannerDescriptionProps): ReactNode {
|
|
107
|
+
return <p data-slot="consent-description" {...props} />;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* @since 0.5.0-canary.5
|
|
112
|
+
*/
|
|
113
|
+
export interface ConsentBannerActionsProps extends ComponentProps<"div"> {}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* @since 0.5.0-canary.5
|
|
117
|
+
*/
|
|
118
|
+
export function ConsentBannerActions(props: ConsentBannerActionsProps): ReactNode {
|
|
119
|
+
return <div data-slot="consent-actions" {...props} />;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* @since 0.5.0-canary.5
|
|
124
|
+
*/
|
|
125
|
+
export interface ConsentBannerAcceptProps extends Omit<ComponentProps<"button">, "type"> {}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Grants the categories the app requested (`useConsent`'s `categories`) — never more.
|
|
129
|
+
*
|
|
130
|
+
* @since 0.5.0-canary.5
|
|
131
|
+
*/
|
|
132
|
+
export function ConsentBannerAccept({ onClick, ...props }: ConsentBannerAcceptProps): ReactNode {
|
|
133
|
+
const { consent, setPending } = useConsentBannerContext("ConsentBannerAccept");
|
|
134
|
+
|
|
135
|
+
return (
|
|
136
|
+
<button
|
|
137
|
+
data-action="accept"
|
|
138
|
+
data-slot="consent-action"
|
|
139
|
+
{...props}
|
|
140
|
+
// the part owns the decision — composed so a consumer onClick (e.g. closing a settings view) still runs
|
|
141
|
+
onClick={(event) => {
|
|
142
|
+
onClick?.(event);
|
|
143
|
+
consent.grantAll();
|
|
144
|
+
setPending(undefined);
|
|
145
|
+
}}
|
|
146
|
+
type="button"
|
|
147
|
+
/>
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* @since 0.5.0-canary.5
|
|
153
|
+
*/
|
|
154
|
+
export interface ConsentBannerRejectProps extends Omit<ComponentProps<"button">, "type"> {}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* @since 0.5.0-canary.5
|
|
158
|
+
*/
|
|
159
|
+
export function ConsentBannerReject({ onClick, ...props }: ConsentBannerRejectProps): ReactNode {
|
|
160
|
+
const { consent, setPending } = useConsentBannerContext("ConsentBannerReject");
|
|
161
|
+
|
|
162
|
+
return (
|
|
163
|
+
<button
|
|
164
|
+
data-action="reject"
|
|
165
|
+
data-slot="consent-action"
|
|
166
|
+
{...props}
|
|
167
|
+
// the part owns the decision — composed so a consumer onClick (e.g. closing a settings view) still runs
|
|
168
|
+
onClick={(event) => {
|
|
169
|
+
onClick?.(event);
|
|
170
|
+
consent.denyAll();
|
|
171
|
+
setPending(undefined);
|
|
172
|
+
}}
|
|
173
|
+
type="button"
|
|
174
|
+
/>
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* @since 0.5.0-canary.5
|
|
180
|
+
*/
|
|
181
|
+
export interface ConsentBannerCustomizeProps extends Omit<ComponentProps<"button">, "type"> {}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Opens the per-category preferences layer, starting from the current effective state so
|
|
185
|
+
* nothing arrives pre-ticked in an opt-in region (pre-ticked consent is invalid under
|
|
186
|
+
* GDPR). Hidden while the layer is open — `ConsentBannerSave` takes over.
|
|
187
|
+
*
|
|
188
|
+
* @since 0.5.0-canary.5
|
|
189
|
+
*/
|
|
190
|
+
export function ConsentBannerCustomize({ onClick, ...props }: ConsentBannerCustomizeProps): ReactNode {
|
|
191
|
+
const { consent, pending, setPending } = useConsentBannerContext("ConsentBannerCustomize");
|
|
192
|
+
|
|
193
|
+
if (pending !== undefined) {
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return (
|
|
198
|
+
<button
|
|
199
|
+
data-action="customize"
|
|
200
|
+
data-slot="consent-action"
|
|
201
|
+
{...props}
|
|
202
|
+
// the part owns the layer toggle — composed so a consumer onClick still runs
|
|
203
|
+
onClick={(event) => {
|
|
204
|
+
onClick?.(event);
|
|
205
|
+
setPending(consent.effectiveConsent);
|
|
206
|
+
}}
|
|
207
|
+
type="button"
|
|
208
|
+
/>
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* @since 0.5.0-canary.5
|
|
214
|
+
*/
|
|
215
|
+
export interface ConsentBannerPreferencesProps extends ComponentProps<"div"> {}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Container for the per-category rows — renders only while the preferences layer is open.
|
|
219
|
+
*
|
|
220
|
+
* @since 0.5.0-canary.5
|
|
221
|
+
*/
|
|
222
|
+
export function ConsentBannerPreferences(props: ConsentBannerPreferencesProps): ReactNode {
|
|
223
|
+
const { pending } = useConsentBannerContext("ConsentBannerPreferences");
|
|
224
|
+
|
|
225
|
+
if (pending === undefined) {
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
return <div data-slot="consent-preferences" {...props} />;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* @since 0.5.0-canary.5
|
|
234
|
+
*/
|
|
235
|
+
export interface ConsentBannerCategoryProps extends ComponentProps<"label"> {
|
|
236
|
+
category: ConsentCategory;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* One checkbox row of the preferences layer — `children` is the visitor-facing wording.
|
|
241
|
+
*
|
|
242
|
+
* @since 0.5.0-canary.5
|
|
243
|
+
*/
|
|
244
|
+
export function ConsentBannerCategory({ category, children, ...props }: ConsentBannerCategoryProps): ReactNode {
|
|
245
|
+
const { pending, setPending } = useConsentBannerContext("ConsentBannerCategory");
|
|
246
|
+
|
|
247
|
+
if (pending === undefined) {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
return (
|
|
252
|
+
<label data-slot="consent-category" {...props}>
|
|
253
|
+
<input
|
|
254
|
+
checked={pending[category]}
|
|
255
|
+
data-slot="consent-category-checkbox"
|
|
256
|
+
onChange={(event) => {
|
|
257
|
+
setPending({ ...pending, [category]: event.target.checked });
|
|
258
|
+
}}
|
|
259
|
+
type="checkbox"
|
|
260
|
+
/>
|
|
261
|
+
{children}
|
|
262
|
+
</label>
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* @since 0.5.0-canary.5
|
|
268
|
+
*/
|
|
269
|
+
export interface ConsentBannerSaveProps extends Omit<ComponentProps<"button">, "type"> {}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Persists the pending per-category selection — renders only while the preferences layer is open.
|
|
273
|
+
*
|
|
274
|
+
* @since 0.5.0-canary.5
|
|
275
|
+
*/
|
|
276
|
+
export function ConsentBannerSave({ onClick, ...props }: ConsentBannerSaveProps): ReactNode {
|
|
277
|
+
const { consent, pending, setPending } = useConsentBannerContext("ConsentBannerSave");
|
|
278
|
+
|
|
279
|
+
if (pending === undefined) {
|
|
26
280
|
return null;
|
|
27
281
|
}
|
|
28
282
|
|
|
29
283
|
return (
|
|
30
|
-
<
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
284
|
+
<button
|
|
285
|
+
data-action="save"
|
|
286
|
+
data-slot="consent-action"
|
|
287
|
+
{...props}
|
|
288
|
+
// the part owns the decision — composed so a consumer onClick still runs
|
|
289
|
+
onClick={(event) => {
|
|
290
|
+
onClick?.(event);
|
|
291
|
+
consent.save(pending);
|
|
292
|
+
setPending(undefined);
|
|
293
|
+
}}
|
|
294
|
+
type="button"
|
|
295
|
+
/>
|
|
39
296
|
);
|
|
40
297
|
}
|
|
41
298
|
|
|
42
|
-
|
|
299
|
+
/**
|
|
300
|
+
* @since 0.5.0-canary.4
|
|
301
|
+
*/
|
|
302
|
+
export interface ConsentToggleProps extends Omit<ComponentProps<"button">, "children" | "onClick" | "type"> {
|
|
43
303
|
allowLabel?: string;
|
|
44
|
-
className?: string;
|
|
45
304
|
consent: UseConsentResult;
|
|
46
305
|
denyLabel?: string;
|
|
47
306
|
}
|
|
@@ -49,16 +308,27 @@ export interface ConsentToggleProps {
|
|
|
49
308
|
/**
|
|
50
309
|
* Always-visible control for opt-out regions — CCPA/CPRA requires a persistent
|
|
51
310
|
* "Do Not Sell or Share My Personal Information" mechanism, not just a one-time prompt.
|
|
311
|
+
* Flips between denying everything and re-granting the app's requested categories.
|
|
312
|
+
*
|
|
313
|
+
* @since 0.5.0-canary.4
|
|
52
314
|
*/
|
|
53
315
|
export function ConsentToggle({
|
|
54
316
|
allowLabel = "Allow tracking",
|
|
55
|
-
className,
|
|
56
317
|
consent,
|
|
57
318
|
denyLabel = "Do Not Sell or Share My Personal Information",
|
|
319
|
+
...props
|
|
58
320
|
}: ConsentToggleProps): ReactNode {
|
|
321
|
+
const anyAllowed = CONSENT_CATEGORIES.some((category) => consent.effectiveConsent[category]);
|
|
322
|
+
|
|
59
323
|
return (
|
|
60
|
-
<button
|
|
61
|
-
|
|
324
|
+
<button
|
|
325
|
+
data-slot="consent-toggle"
|
|
326
|
+
{...props}
|
|
327
|
+
// the toggle owns its click — flipping the stored decision is its whole purpose
|
|
328
|
+
onClick={anyAllowed ? consent.denyAll : consent.grantAll}
|
|
329
|
+
type="button"
|
|
330
|
+
>
|
|
331
|
+
{anyAllowed ? denyLabel : allowLabel}
|
|
62
332
|
</button>
|
|
63
333
|
);
|
|
64
334
|
}
|
package/src/react/index.ts
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
|
-
export type {
|
|
2
|
-
|
|
1
|
+
export type {
|
|
2
|
+
ConsentBannerAcceptProps,
|
|
3
|
+
ConsentBannerActionsProps,
|
|
4
|
+
ConsentBannerCategoryProps,
|
|
5
|
+
ConsentBannerCustomizeProps,
|
|
6
|
+
ConsentBannerDescriptionProps,
|
|
7
|
+
ConsentBannerPreferencesProps,
|
|
8
|
+
ConsentBannerProps,
|
|
9
|
+
ConsentBannerRejectProps,
|
|
10
|
+
ConsentBannerSaveProps,
|
|
11
|
+
ConsentBannerTitleProps,
|
|
12
|
+
ConsentToggleProps,
|
|
13
|
+
} from "#/react/consent-banner";
|
|
14
|
+
export {
|
|
15
|
+
ConsentBanner,
|
|
16
|
+
ConsentBannerAccept,
|
|
17
|
+
ConsentBannerActions,
|
|
18
|
+
ConsentBannerCategory,
|
|
19
|
+
ConsentBannerCustomize,
|
|
20
|
+
ConsentBannerDescription,
|
|
21
|
+
ConsentBannerPreferences,
|
|
22
|
+
ConsentBannerReject,
|
|
23
|
+
ConsentBannerSave,
|
|
24
|
+
ConsentBannerTitle,
|
|
25
|
+
ConsentToggle,
|
|
26
|
+
} from "#/react/consent-banner";
|
|
3
27
|
|
|
4
28
|
export type { UseConsentOptions, UseConsentResult } from "#/react/use-consent";
|
|
5
29
|
export { useConsent } from "#/react/use-consent";
|
package/src/react/use-consent.ts
CHANGED
|
@@ -1,53 +1,111 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { useRef, useSyncExternalStore } from "react";
|
|
2
2
|
|
|
3
|
-
import type { ConsentDecision, ConsentMode, ConsentStorage } from "#/core/consent";
|
|
4
|
-
import {
|
|
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
|
-
|
|
16
|
-
|
|
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`/`
|
|
24
|
-
*
|
|
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
|
|
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
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
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
|
-
|
|
86
|
+
() => undefined,
|
|
36
87
|
);
|
|
37
88
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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
|
-
|
|
45
|
-
|
|
99
|
+
decision,
|
|
100
|
+
denyAll: () => {
|
|
101
|
+
save(createConsentDecision([]));
|
|
46
102
|
},
|
|
47
|
-
|
|
48
|
-
|
|
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
|
}
|
|
@@ -5,11 +5,17 @@ import type { EventCatalog, EventsOf } from "#/core/event-catalog";
|
|
|
5
5
|
import { generateEventId } from "#/core/event-id";
|
|
6
6
|
import type { TrackedEvent } from "#/core/tracked-event";
|
|
7
7
|
|
|
8
|
+
/**
|
|
9
|
+
* @since 0.5.0-canary.4
|
|
10
|
+
*/
|
|
8
11
|
export interface ServerTrackContext {
|
|
9
12
|
anonymousId: string;
|
|
10
13
|
userId?: string | undefined;
|
|
11
14
|
}
|
|
12
15
|
|
|
16
|
+
/**
|
|
17
|
+
* @since 0.5.0-canary.4
|
|
18
|
+
*/
|
|
13
19
|
export interface ServerTrackerOptions<Catalog extends EventCatalog> {
|
|
14
20
|
catalog: Catalog;
|
|
15
21
|
destinations: Array<Destination>;
|
|
@@ -19,7 +25,13 @@ export interface ServerTrackerOptions<Catalog extends EventCatalog> {
|
|
|
19
25
|
retryDelayMs?: number;
|
|
20
26
|
}
|
|
21
27
|
|
|
28
|
+
/**
|
|
29
|
+
* @since 0.5.0-canary.4
|
|
30
|
+
*/
|
|
22
31
|
export interface ServerTracker<Catalog extends EventCatalog> {
|
|
32
|
+
/** Explicit anonymous → known-user merge, for when `identify` timing can't do it. */
|
|
33
|
+
alias: (previousId: string, userId: string, context: ServerTrackContext) => Promise<void>;
|
|
34
|
+
group: (groupId: string, traits: Record<string, unknown> | undefined, context: ServerTrackContext) => Promise<void>;
|
|
23
35
|
track: <Name extends keyof EventsOf<Catalog, "server">>(
|
|
24
36
|
name: Name,
|
|
25
37
|
props: z.infer<EventsOf<Catalog, "server">[Name]["schema"]>,
|
|
@@ -60,6 +72,8 @@ async function sendWithRetry(
|
|
|
60
72
|
/**
|
|
61
73
|
* No dead-letter queue yet (self-host storage is Phase 2) — a destination that keeps
|
|
62
74
|
* failing after retries is only logged via `onDestinationError`, never re-queued.
|
|
75
|
+
*
|
|
76
|
+
* @since 0.5.0-canary.4
|
|
63
77
|
*/
|
|
64
78
|
export function createServerTracker<Catalog extends EventCatalog>(
|
|
65
79
|
options: ServerTrackerOptions<Catalog>,
|
|
@@ -73,7 +87,31 @@ export function createServerTracker<Catalog extends EventCatalog>(
|
|
|
73
87
|
console.error(`[tracking] destination "${destination.name}" failed for event "${event.name}"`, error);
|
|
74
88
|
});
|
|
75
89
|
|
|
90
|
+
async function sendEvent(name: string, props: Record<string, unknown>, context: ServerTrackContext): Promise<void> {
|
|
91
|
+
const event: TrackedEvent = {
|
|
92
|
+
anonymousId: context.anonymousId,
|
|
93
|
+
eventId: createId(),
|
|
94
|
+
name,
|
|
95
|
+
owner: "server",
|
|
96
|
+
props,
|
|
97
|
+
timestamp: Date.now(),
|
|
98
|
+
...(context.userId === undefined ? {} : { userId: context.userId }),
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
await Promise.all(
|
|
102
|
+
options.destinations.map(async (destination) =>
|
|
103
|
+
sendWithRetry(destination, event, maxRetries, retryDelayMs, onError),
|
|
104
|
+
),
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
|
|
76
108
|
return {
|
|
109
|
+
async alias(previousId, userId, context) {
|
|
110
|
+
await sendEvent("$alias", { previousId, userId }, context);
|
|
111
|
+
},
|
|
112
|
+
async group(groupId, traits, context) {
|
|
113
|
+
await sendEvent("$group", { groupId, ...traits }, context);
|
|
114
|
+
},
|
|
77
115
|
async track(name, props, context) {
|
|
78
116
|
// noUncheckedIndexedAccess types this as possibly undefined; the owner check also
|
|
79
117
|
// guards callers who bypass the EventsOf filter with an `as` cast.
|
|
@@ -84,22 +122,7 @@ export function createServerTracker<Catalog extends EventCatalog>(
|
|
|
84
122
|
}
|
|
85
123
|
|
|
86
124
|
definition.schema.parse(props);
|
|
87
|
-
|
|
88
|
-
const event: TrackedEvent = {
|
|
89
|
-
anonymousId: context.anonymousId,
|
|
90
|
-
eventId: createId(),
|
|
91
|
-
name: name as string,
|
|
92
|
-
owner: "server",
|
|
93
|
-
props: props as Record<string, unknown>,
|
|
94
|
-
timestamp: Date.now(),
|
|
95
|
-
...(context.userId === undefined ? {} : { userId: context.userId }),
|
|
96
|
-
};
|
|
97
|
-
|
|
98
|
-
await Promise.all(
|
|
99
|
-
options.destinations.map(async (destination) =>
|
|
100
|
-
sendWithRetry(destination, event, maxRetries, retryDelayMs, onError),
|
|
101
|
-
),
|
|
102
|
-
);
|
|
125
|
+
await sendEvent(name as string, props as Record<string, unknown>, context);
|
|
103
126
|
},
|
|
104
127
|
};
|
|
105
128
|
}
|
package/src/server/region.ts
CHANGED
|
@@ -34,6 +34,8 @@ const EU_COUNTRY_CODES = new Set([
|
|
|
34
34
|
* Missing/unrecognized codes fall back to "other", which `resolveConsentMode` treats
|
|
35
35
|
* as opt-out — the least restrictive default, safe only because opt-in regions (EU/VN)
|
|
36
36
|
* are matched explicitly above it.
|
|
37
|
+
*
|
|
38
|
+
* @since 0.5.0-canary.4
|
|
37
39
|
*/
|
|
38
40
|
export function resolveRegionFromCountryCode(countryCode: string | undefined): ConsentRegion {
|
|
39
41
|
if (!countryCode) {
|
|
@@ -60,6 +62,8 @@ export function resolveRegionFromCountryCode(countryCode: string | undefined): C
|
|
|
60
62
|
/**
|
|
61
63
|
* Reads the hosting platform's geo header (e.g. Vercel's `x-vercel-ip-country`) — pass
|
|
62
64
|
* the incoming request's `Headers` from server-function/middleware context.
|
|
65
|
+
*
|
|
66
|
+
* @since 0.5.0-canary.4
|
|
63
67
|
*/
|
|
64
68
|
export function resolveRegion(headers: Headers, headerName = "x-vercel-ip-country"): ConsentRegion {
|
|
65
69
|
return resolveRegionFromCountryCode(headers.get(headerName) ?? undefined);
|