@codefast/tracking 0.7.0 → 0.7.2

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 (214) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +235 -105
  3. package/dist/adapters/tanstack-start.d.ts +12 -9
  4. package/dist/adapters/tanstack-start.js +5 -6
  5. package/dist/client/ad-framework-consent.d.ts +9 -8
  6. package/dist/client/ad-framework-consent.js +4 -5
  7. package/dist/client/browser-cookie.d.ts +2 -3
  8. package/dist/client/browser-cookie.js +2 -3
  9. package/dist/client/consent-runtime.d.ts +6 -5
  10. package/dist/client/consent-runtime.js +2 -3
  11. package/dist/client/consent-storage.d.ts +1 -2
  12. package/dist/client/consent-storage.js +1 -2
  13. package/dist/client/consent-withdrawal.d.ts +5 -4
  14. package/dist/client/consent-withdrawal.js +2 -3
  15. package/dist/client/cookie-anonymous-id.d.ts +8 -5
  16. package/dist/client/cookie-anonymous-id.js +2 -3
  17. package/dist/client/create-client-tracker.d.ts +8 -3
  18. package/dist/client/create-client-tracker.js +3 -2
  19. package/dist/client/gpc.d.ts +1 -2
  20. package/dist/client/gpc.js +1 -2
  21. package/dist/client/initial-consent-store.d.ts +7 -6
  22. package/dist/client/initial-consent-store.js +2 -3
  23. package/dist/client/is-analytics-allowed.d.ts +5 -4
  24. package/dist/client/is-analytics-allowed.js +2 -3
  25. package/dist/client/server-persisted-anonymous-id.d.ts +5 -4
  26. package/dist/client/server-persisted-anonymous-id.js +2 -3
  27. package/dist/core/consent-config.d.ts +3 -4
  28. package/dist/core/consent-config.js +2 -3
  29. package/dist/core/consent-receipt.d.ts +7 -8
  30. package/dist/core/consent-receipt.js +2 -3
  31. package/dist/core/consent.d.ts +24 -13
  32. package/dist/core/consent.js +13 -10
  33. package/dist/core/cookie.d.ts +3 -4
  34. package/dist/core/cookie.js +3 -4
  35. package/dist/core/destination.d.ts +1 -2
  36. package/dist/core/destination.js +1 -2
  37. package/dist/core/event-catalog.d.ts +2 -3
  38. package/dist/core/event-catalog.js +2 -3
  39. package/dist/core/event-id.d.ts +1 -2
  40. package/dist/core/event-id.js +1 -2
  41. package/dist/core/tracked-event.d.ts +1 -2
  42. package/dist/core/tracked-event.js +1 -2
  43. package/dist/destinations/ad-consent.d.ts +3 -4
  44. package/dist/destinations/ad-consent.js +2 -3
  45. package/dist/destinations/google-analytics.d.ts +17 -10
  46. package/dist/destinations/google-analytics.js +5 -6
  47. package/dist/destinations/google-consent.d.ts +10 -9
  48. package/dist/destinations/google-consent.js +6 -7
  49. package/dist/destinations/meta.d.ts +8 -7
  50. package/dist/destinations/meta.js +3 -4
  51. package/dist/destinations/microsoft-uet.d.ts +8 -7
  52. package/dist/destinations/microsoft-uet.js +3 -4
  53. package/dist/destinations/shared.d.ts +8 -5
  54. package/dist/destinations/shared.js +4 -3
  55. package/dist/destinations/tiktok.d.ts +8 -7
  56. package/dist/destinations/tiktok.js +3 -4
  57. package/dist/destinations/vercel-analytics.d.ts +4 -3
  58. package/dist/destinations/vercel-analytics.js +1 -2
  59. package/dist/index.d.ts +1 -2
  60. package/dist/index.js +1 -2
  61. package/dist/react/consent-banner.d.ts +29 -2
  62. package/dist/react/consent-banner.js +12 -9
  63. package/dist/react/gtag-consent-bootstrap.d.ts +5 -4
  64. package/dist/react/gtag-consent-bootstrap.js +2 -3
  65. package/dist/react/use-consent.d.ts +5 -2
  66. package/dist/react/use-consent.js +1 -2
  67. package/dist/react/use-google-consent-sync.d.ts +5 -4
  68. package/dist/react/use-google-consent-sync.js +2 -3
  69. package/dist/react/use-initial-consent.d.ts +2 -3
  70. package/dist/react/use-initial-consent.js +2 -3
  71. package/dist/server/anonymous-id-cookie.d.ts +8 -7
  72. package/dist/server/anonymous-id-cookie.js +5 -6
  73. package/dist/server/consent-receipt-store.d.ts +5 -6
  74. package/dist/server/consent-receipt-store.js +3 -4
  75. package/dist/server/consent-receipt.d.ts +5 -6
  76. package/dist/server/consent-receipt.js +4 -5
  77. package/dist/server/initial-consent.d.ts +5 -4
  78. package/dist/server/initial-consent.js +2 -3
  79. package/dist/server/measurement-protocol.d.ts +10 -9
  80. package/dist/server/measurement-protocol.js +4 -5
  81. package/dist/server/region.d.ts +3 -4
  82. package/dist/server/region.js +3 -4
  83. package/dist/server/user-deletion.d.ts +10 -7
  84. package/dist/server/user-deletion.js +3 -4
  85. package/dist/tooling/import-protection.d.ts +2 -3
  86. package/dist/tooling/import-protection.js +2 -3
  87. package/package.json +11 -62
  88. package/dist/adapters/tanstack-start.d.ts.map +0 -1
  89. package/dist/adapters/tanstack-start.js.map +0 -1
  90. package/dist/client/ad-framework-consent.d.ts.map +0 -1
  91. package/dist/client/ad-framework-consent.js.map +0 -1
  92. package/dist/client/browser-cookie.d.ts.map +0 -1
  93. package/dist/client/browser-cookie.js.map +0 -1
  94. package/dist/client/consent-runtime.d.ts.map +0 -1
  95. package/dist/client/consent-runtime.js.map +0 -1
  96. package/dist/client/consent-storage.d.ts.map +0 -1
  97. package/dist/client/consent-storage.js.map +0 -1
  98. package/dist/client/consent-withdrawal.d.ts.map +0 -1
  99. package/dist/client/consent-withdrawal.js.map +0 -1
  100. package/dist/client/cookie-anonymous-id.d.ts.map +0 -1
  101. package/dist/client/cookie-anonymous-id.js.map +0 -1
  102. package/dist/client/create-client-tracker.d.ts.map +0 -1
  103. package/dist/client/create-client-tracker.js.map +0 -1
  104. package/dist/client/gpc.d.ts.map +0 -1
  105. package/dist/client/gpc.js.map +0 -1
  106. package/dist/client/initial-consent-store.d.ts.map +0 -1
  107. package/dist/client/initial-consent-store.js.map +0 -1
  108. package/dist/client/is-analytics-allowed.d.ts.map +0 -1
  109. package/dist/client/is-analytics-allowed.js.map +0 -1
  110. package/dist/client/server-persisted-anonymous-id.d.ts.map +0 -1
  111. package/dist/client/server-persisted-anonymous-id.js.map +0 -1
  112. package/dist/core/consent-config.d.ts.map +0 -1
  113. package/dist/core/consent-config.js.map +0 -1
  114. package/dist/core/consent-receipt.d.ts.map +0 -1
  115. package/dist/core/consent-receipt.js.map +0 -1
  116. package/dist/core/consent.d.ts.map +0 -1
  117. package/dist/core/consent.js.map +0 -1
  118. package/dist/core/cookie.d.ts.map +0 -1
  119. package/dist/core/cookie.js.map +0 -1
  120. package/dist/core/destination.d.ts.map +0 -1
  121. package/dist/core/destination.js.map +0 -1
  122. package/dist/core/event-catalog.d.ts.map +0 -1
  123. package/dist/core/event-catalog.js.map +0 -1
  124. package/dist/core/event-id.d.ts.map +0 -1
  125. package/dist/core/event-id.js.map +0 -1
  126. package/dist/core/tracked-event.d.ts.map +0 -1
  127. package/dist/core/tracked-event.js.map +0 -1
  128. package/dist/destinations/ad-consent.d.ts.map +0 -1
  129. package/dist/destinations/ad-consent.js.map +0 -1
  130. package/dist/destinations/google-analytics.d.ts.map +0 -1
  131. package/dist/destinations/google-analytics.js.map +0 -1
  132. package/dist/destinations/google-consent.d.ts.map +0 -1
  133. package/dist/destinations/google-consent.js.map +0 -1
  134. package/dist/destinations/meta.d.ts.map +0 -1
  135. package/dist/destinations/meta.js.map +0 -1
  136. package/dist/destinations/microsoft-uet.d.ts.map +0 -1
  137. package/dist/destinations/microsoft-uet.js.map +0 -1
  138. package/dist/destinations/shared.d.ts.map +0 -1
  139. package/dist/destinations/shared.js.map +0 -1
  140. package/dist/destinations/tiktok.d.ts.map +0 -1
  141. package/dist/destinations/tiktok.js.map +0 -1
  142. package/dist/destinations/vercel-analytics.d.ts.map +0 -1
  143. package/dist/destinations/vercel-analytics.js.map +0 -1
  144. package/dist/index.d.ts.map +0 -1
  145. package/dist/index.js.map +0 -1
  146. package/dist/react/consent-banner.d.ts.map +0 -1
  147. package/dist/react/consent-banner.js.map +0 -1
  148. package/dist/react/gtag-consent-bootstrap.d.ts.map +0 -1
  149. package/dist/react/gtag-consent-bootstrap.js.map +0 -1
  150. package/dist/react/use-consent.d.ts.map +0 -1
  151. package/dist/react/use-consent.js.map +0 -1
  152. package/dist/react/use-google-consent-sync.d.ts.map +0 -1
  153. package/dist/react/use-google-consent-sync.js.map +0 -1
  154. package/dist/react/use-initial-consent.d.ts.map +0 -1
  155. package/dist/react/use-initial-consent.js.map +0 -1
  156. package/dist/server/anonymous-id-cookie.d.ts.map +0 -1
  157. package/dist/server/anonymous-id-cookie.js.map +0 -1
  158. package/dist/server/consent-receipt-store.d.ts.map +0 -1
  159. package/dist/server/consent-receipt-store.js.map +0 -1
  160. package/dist/server/consent-receipt.d.ts.map +0 -1
  161. package/dist/server/consent-receipt.js.map +0 -1
  162. package/dist/server/initial-consent.d.ts.map +0 -1
  163. package/dist/server/initial-consent.js.map +0 -1
  164. package/dist/server/measurement-protocol.d.ts.map +0 -1
  165. package/dist/server/measurement-protocol.js.map +0 -1
  166. package/dist/server/region.d.ts.map +0 -1
  167. package/dist/server/region.js.map +0 -1
  168. package/dist/server/user-deletion.d.ts.map +0 -1
  169. package/dist/server/user-deletion.js.map +0 -1
  170. package/dist/tooling/import-protection.d.ts.map +0 -1
  171. package/dist/tooling/import-protection.js.map +0 -1
  172. package/src/adapters/tanstack-start.ts +0 -135
  173. package/src/client/ad-framework-consent.ts +0 -86
  174. package/src/client/browser-cookie.ts +0 -16
  175. package/src/client/consent-runtime.ts +0 -80
  176. package/src/client/consent-storage.ts +0 -125
  177. package/src/client/consent-withdrawal.ts +0 -32
  178. package/src/client/cookie-anonymous-id.ts +0 -112
  179. package/src/client/create-client-tracker.ts +0 -168
  180. package/src/client/gpc.ts +0 -15
  181. package/src/client/initial-consent-store.ts +0 -218
  182. package/src/client/is-analytics-allowed.ts +0 -43
  183. package/src/client/server-persisted-anonymous-id.ts +0 -102
  184. package/src/core/consent-config.ts +0 -27
  185. package/src/core/consent-receipt.ts +0 -115
  186. package/src/core/consent.ts +0 -286
  187. package/src/core/cookie.ts +0 -29
  188. package/src/core/destination.ts +0 -29
  189. package/src/core/event-catalog.ts +0 -54
  190. package/src/core/event-id.ts +0 -8
  191. package/src/core/tracked-event.ts +0 -14
  192. package/src/css/consent.css +0 -119
  193. package/src/destinations/ad-consent.ts +0 -29
  194. package/src/destinations/google-analytics.ts +0 -296
  195. package/src/destinations/google-consent.ts +0 -164
  196. package/src/destinations/meta.ts +0 -96
  197. package/src/destinations/microsoft-uet.ts +0 -86
  198. package/src/destinations/shared.ts +0 -45
  199. package/src/destinations/tiktok.ts +0 -85
  200. package/src/destinations/vercel-analytics.ts +0 -39
  201. package/src/index.ts +0 -171
  202. package/src/react/consent-banner.tsx +0 -360
  203. package/src/react/gtag-consent-bootstrap.tsx +0 -48
  204. package/src/react/use-consent.ts +0 -119
  205. package/src/react/use-google-consent-sync.ts +0 -38
  206. package/src/react/use-initial-consent.ts +0 -22
  207. package/src/server/anonymous-id-cookie.ts +0 -103
  208. package/src/server/consent-receipt-store.ts +0 -79
  209. package/src/server/consent-receipt.ts +0 -89
  210. package/src/server/initial-consent.ts +0 -46
  211. package/src/server/measurement-protocol.ts +0 -114
  212. package/src/server/region.ts +0 -77
  213. package/src/server/user-deletion.ts +0 -93
  214. package/src/tooling/import-protection.ts +0 -22
@@ -1,48 +0,0 @@
1
- import type { ComponentProps, ReactNode } from "react";
2
-
3
- import type { GtagConsentBootstrapOptions } from "#/destinations/google-analytics";
4
- import { buildGtagConsentBootstrapScript } from "#/destinations/google-analytics";
5
-
6
- /**
7
- * @since 1.0.0-canary.6
8
- */
9
- export interface GtagConsentBootstrapProps
10
- extends
11
- Omit<ComponentProps<"script">, "children" | "dangerouslySetInnerHTML" | "nonce" | "src" | "type">,
12
- GtagConsentBootstrapOptions {}
13
-
14
- /**
15
- * Framework-agnostic inline `<script>` that runs `buildGtagConsentBootstrapScript` before
16
- * hydration. Pass the same `nonce` here and in `loadGtagScript` for CSP; this component
17
- * only sets the attribute on the host script — the generated source also stamps it onto
18
- * the injected gtag.js tag when `nonce` is provided.
19
- *
20
- * @since 1.0.0-canary.6
21
- */
22
- export function GtagConsentBootstrap({
23
- config,
24
- dataLayerName,
25
- defaultConsent,
26
- debugMode,
27
- gaMeasurementId,
28
- nonce,
29
- ...props
30
- }: GtagConsentBootstrapProps): ReactNode {
31
- const bootstrapOptions: GtagConsentBootstrapOptions = {
32
- config,
33
- defaultConsent,
34
- gaMeasurementId,
35
- ...(dataLayerName === undefined ? {} : { dataLayerName }),
36
- ...(debugMode === undefined ? {} : { debugMode }),
37
- ...(nonce === undefined ? {} : { nonce }),
38
- };
39
-
40
- return (
41
- <script
42
- {...props}
43
- dangerouslySetInnerHTML={{ __html: buildGtagConsentBootstrapScript(bootstrapOptions) }}
44
- {...(nonce === undefined ? {} : { nonce })}
45
- suppressHydrationWarning
46
- />
47
- );
48
- }
@@ -1,119 +0,0 @@
1
- "use client";
2
-
3
- import { useCallback, useMemo, useRef, useSyncExternalStore } from "react";
4
-
5
- import type { ConsentDecision, ConsentMode, ConsentStorage } from "#/core/consent";
6
- import { CONSENT_CATEGORIES, createConsentDecision, readStoredDecision, resolveDefaultConsent } from "#/core/consent";
7
- import type { ConsentConfig } from "#/core/consent-config";
8
-
9
- /**
10
- * @since 0.5.0-canary.4
11
- */
12
- export interface UseConsentOptions {
13
- /** Must be the same object the tracker gate and the tag bootstraps receive — one config, every surface. */
14
- config: ConsentConfig;
15
- hasGlobalPrivacyControlSignal?: boolean | undefined;
16
- mode: ConsentMode;
17
- onDecision?: ((decision: ConsentDecision) => void) | undefined;
18
- /** Must be a stable reference (module-level or memoized) — a new object per render resubscribes every render. */
19
- storage: ConsentStorage;
20
- }
21
-
22
- /**
23
- * @since 0.5.0-canary.4
24
- */
25
- export interface UseConsentResult {
26
- /** The stored decision under the current policy version — `undefined` until the visitor makes one. */
27
- decision: ConsentDecision | undefined;
28
- denyAll: () => void;
29
- /** What tags must obey right now — the stored decision, or the region default before one exists. */
30
- effectiveConsent: ConsentDecision;
31
- grantAll: () => void;
32
- /** Effective `analytics` consent — gates this package's own tracker pipeline. */
33
- isAnalyticsAllowed: boolean;
34
- /** True only for opt-in regions with no stored decision yet — drives whether to render the banner. */
35
- isPromptNeeded: boolean;
36
- /** Persist a granular per-category choice, e.g. from a preferences panel. */
37
- saveDecision: (decision: ConsentDecision) => void;
38
- }
39
-
40
- /**
41
- * Bridges `resolveConsentMode`/`resolveDefaultConsent` (core, region-aware) to React via
42
- * `useSyncExternalStore`: the stored record is the single source of truth, hydration is
43
- * safe by construction (the server snapshot is always "no decision yet", matching what
44
- * prerendered HTML could know), and a decision made in another tab syncs through the
45
- * storage subscription.
46
- *
47
- * @since 0.5.0-canary.4
48
- */
49
- export function useConsent(options: UseConsentOptions): UseConsentResult {
50
- const { mode, onDecision, storage } = options;
51
- const { policyVersion, requestedCategories } = options.config;
52
- const hasGlobalPrivacyControlSignal = options.hasGlobalPrivacyControlSignal ?? false;
53
-
54
- // useSyncExternalStore needs a referentially stable snapshot, but JSON-backed storages
55
- // parse a fresh record per load — so the last valid decision is cached by value.
56
- const cachedDecision = useRef<ConsentDecision | undefined>(undefined);
57
-
58
- const decision = useSyncExternalStore(
59
- storage.subscribe,
60
- (): ConsentDecision | undefined => {
61
- // Only a well-formed decision under the current policy version counts — the store
62
- // is tamperable plain JSON, and a garbage value must re-prompt, not silently deny.
63
- const stored = readStoredDecision(storage, policyVersion);
64
-
65
- if (stored === undefined) {
66
- cachedDecision.current = undefined;
67
-
68
- return undefined;
69
- }
70
-
71
- const cached = cachedDecision.current;
72
-
73
- if (cached !== undefined && CONSENT_CATEGORIES.every((category) => cached[category] === stored[category])) {
74
- return cached;
75
- }
76
-
77
- cachedDecision.current = stored;
78
-
79
- return cachedDecision.current;
80
- },
81
- () => undefined,
82
- );
83
-
84
- // Kept stable across renders (when their own inputs don't change) so a consumer that
85
- // passes this hook's result down as a prop/effect-dep doesn't get a fresh identity —
86
- // and therefore an unnecessary re-render/effect-rerun — every render.
87
- const saveDecision = useCallback(
88
- (next: ConsentDecision): void => {
89
- // No local state — the save notifies the subscription, which re-renders with the new snapshot.
90
- storage.save({ decision: next, policyVersion, timestamp: Date.now() });
91
- onDecision?.(next);
92
- },
93
- [onDecision, policyVersion, storage],
94
- );
95
-
96
- const denyAll = useCallback(() => {
97
- saveDecision(createConsentDecision([]));
98
- }, [saveDecision]);
99
-
100
- const grantAll = useCallback(() => {
101
- saveDecision(createConsentDecision(requestedCategories));
102
- }, [requestedCategories, saveDecision]);
103
-
104
- const effectiveConsent =
105
- decision ?? resolveDefaultConsent({ hasGlobalPrivacyControlSignal, mode, requestedCategories });
106
-
107
- return useMemo(
108
- () => ({
109
- decision,
110
- denyAll,
111
- effectiveConsent,
112
- grantAll,
113
- isAnalyticsAllowed: effectiveConsent.analytics,
114
- isPromptNeeded: mode === "opt-in" && decision === undefined,
115
- saveDecision,
116
- }),
117
- [decision, denyAll, effectiveConsent, grantAll, mode, saveDecision],
118
- );
119
- }
@@ -1,38 +0,0 @@
1
- "use client";
2
-
3
- import { useEffect } from "react";
4
-
5
- import { updateGoogleConsent } from "#/destinations/google-analytics";
6
- import type { UseConsentResult } from "#/react/use-consent";
7
-
8
- /**
9
- * @since 1.0.0-canary.6
10
- */
11
- export interface UseGoogleConsentSyncOptions {
12
- /**
13
- * Idempotent gtag.js load — advanced Consent Mode already injects the tag from a
14
- * bootstrap; pass a loader as a safety net after a runtime grant.
15
- */
16
- loadGtagScript?: (() => void) | undefined;
17
- }
18
-
19
- /**
20
- * Keeps Google Consent Mode v2 in sync with `useConsent`: emits `update` when a stored
21
- * decision exists (including cross-tab / privacy-page saves), and optionally loads gtag
22
- * when analytics is effective. Mount once on a page-wide surface (e.g. the footer gate).
23
- *
24
- * @since 1.0.0-canary.6
25
- */
26
- export function useGoogleConsentSync(consent: UseConsentResult, options: UseGoogleConsentSyncOptions = {}): void {
27
- const { loadGtagScript } = options;
28
-
29
- useEffect(() => {
30
- if (consent.decision !== undefined) {
31
- updateGoogleConsent(consent.decision);
32
- }
33
-
34
- if (consent.effectiveConsent.analytics) {
35
- loadGtagScript?.();
36
- }
37
- }, [consent.decision, consent.effectiveConsent.analytics, loadGtagScript]);
38
- }
@@ -1,22 +0,0 @@
1
- "use client";
2
-
3
- import { useEffect, useSyncExternalStore } from "react";
4
-
5
- import type { InitialConsentSnapshot, InitialConsentStore } from "#/client/initial-consent-store";
6
-
7
- /**
8
- * Reactive view of a `createInitialConsentStore` — kicks off resolution on mount (a no-op
9
- * when the app already did so at router creation) and re-renders once the server lane
10
- * answers. SSR and the first client render read the strictest snapshot, so hydration can
11
- * never mismatch on region.
12
- *
13
- * @since 1.0.0-canary.6
14
- */
15
- export function useInitialConsent(store: InitialConsentStore): InitialConsentSnapshot {
16
- // Post-hydration safety net — idempotent with an earlier, pre-hydration kick.
17
- useEffect(() => {
18
- store.ensureResolved();
19
- }, [store]);
20
-
21
- return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);
22
- }
@@ -1,103 +0,0 @@
1
- import { ONE_YEAR_IN_SECONDS } from "#/core/cookie";
2
-
3
- // The only shape the client ever mints (crypto.randomUUID) — anything else is rejected.
4
- const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
5
-
6
- // Conservative subset of the RFC 6265 cookie-name token.
7
- const COOKIE_NAME_PATTERN = /^[\w-]+$/;
8
-
9
- /**
10
- * Guards the cookie name against anything outside the RFC 6265 token set.
11
- *
12
- * @throws Error when `cookieName` is not a valid token.
13
- *
14
- * @since 1.0.0-canary.7
15
- */
16
- export function assertValidAnonymousIdCookieName(cookieName: string): void {
17
- if (!COOKIE_NAME_PATTERN.test(cookieName)) {
18
- throw new Error(`Invalid anonymous-id cookie name: ${JSON.stringify(cookieName)}`);
19
- }
20
- }
21
-
22
- /**
23
- * Whether a value is safe to persist as an anonymous id. The persist endpoint is public and
24
- * writes its input into a `Set-Cookie`, so only an exactly-UUID-shaped value may pass —
25
- * anything else is a header-injection attempt or corruption, never a valid id.
26
- *
27
- * @since 1.0.0-canary.6
28
- */
29
- export function isValidAnonymousId(value: string): boolean {
30
- return UUID_PATTERN.test(value);
31
- }
32
-
33
- /**
34
- * @since 1.0.0-canary.6
35
- */
36
- export interface AnonymousIdCookieOptions {
37
- /** Cookie name — must match what the client tracker reads. */
38
- cookieName: string;
39
- /** The client-minted id to persist — throws unless it is exactly UUID-shaped. */
40
- id: string;
41
- /** How long the id survives a return visit. Defaults to one year. */
42
- maxAgeSeconds?: number | undefined;
43
- }
44
-
45
- /**
46
- * The validated name/value plus cookie attributes for persisting a client-minted anonymous
47
- * id from the server — feed straight into the framework's cookie helper (`setCookie`).
48
- *
49
- * @remarks
50
- * Always `Secure` — on a plain-HTTP dev origin a browser may drop it, and the
51
- * client-written cookie (`createServerPersistedAnonymousId`'s optimistic write) still
52
- * covers that session. Not `httpOnly`: the client tracker must read the id to stamp it onto
53
- * events. A server-set cookie escapes Safari ITP's 7-day cap on `document.cookie` writes, so
54
- * the id actually lives its full max-age. The server only ever re-sets an id the client
55
- * hands it — minting stays client-side, after consent, by design.
56
- *
57
- * @throws Error when `id` is not UUID-shaped or `cookieName` is not a valid token.
58
- *
59
- * @since 1.0.0-canary.6
60
- */
61
- export function resolveAnonymousIdCookie(options: AnonymousIdCookieOptions): {
62
- maxAge: number;
63
- name: string;
64
- path: string;
65
- sameSite: "lax";
66
- secure: true;
67
- value: string;
68
- } {
69
- assertValidAnonymousIdCookieName(options.cookieName);
70
-
71
- if (!isValidAnonymousId(options.id)) {
72
- throw new Error("Invalid anonymous id: expected a UUID-shaped value");
73
- }
74
-
75
- return {
76
- maxAge: options.maxAgeSeconds ?? ONE_YEAR_IN_SECONDS,
77
- name: options.cookieName,
78
- path: "/",
79
- sameSite: "lax",
80
- secure: true,
81
- value: options.id,
82
- };
83
- }
84
-
85
- /**
86
- * Name plus attributes for expiring the anonymous-id cookie — the server half of a consent
87
- * withdrawal. Attributes must match {@link resolveAnonymousIdCookie} so the browser targets
88
- * the same cookie. Feed into the framework's `deleteCookie`.
89
- *
90
- * @throws Error when `cookieName` is not a valid token.
91
- *
92
- * @since 1.0.0-canary.6
93
- */
94
- export function resolveClearAnonymousIdCookie(cookieName: string): {
95
- name: string;
96
- path: string;
97
- sameSite: "lax";
98
- secure: true;
99
- } {
100
- assertValidAnonymousIdCookieName(cookieName);
101
-
102
- return { name: cookieName, path: "/", sameSite: "lax", secure: true };
103
- }
@@ -1,79 +0,0 @@
1
- import type { ConsentReceipt } from "#/core/consent-receipt";
2
-
3
- /**
4
- * Persistence backend for consent receipts — the durable store is the consumer's to supply
5
- * (a database, an append-only log). The store is **append-only**: `append` never overwrites,
6
- * and an update/withdrawal is a new receipt referencing the prior one (spec-consent-receipts §3).
7
- * May be async so a real backend can await its write.
8
- *
9
- * @since 1.0.0-canary.7
10
- */
11
- export interface ReceiptStore {
12
- append: (receipt: ConsentReceipt) => Promise<void> | void;
13
- get: (receiptId: string) => ConsentReceipt | undefined | Promise<ConsentReceipt | undefined>;
14
- }
15
-
16
- /**
17
- * An in-memory {@link ReceiptStore} for development and tests — **not** durable across a
18
- * process restart, and not a lawful production store on its own. A real deployment supplies
19
- * a database-backed implementation; this exists so the endpoint is runnable end-to-end
20
- * without standing up storage first.
21
- *
22
- * @remarks
23
- * Append is idempotent-by-id: re-appending the same `receiptId` is ignored, preserving the
24
- * append-only guarantee even if a client retries.
25
- *
26
- * @since 1.0.0-canary.7
27
- */
28
- export function createInMemoryReceiptStore(): ReceiptStore {
29
- const receipts = new Map<string, ConsentReceipt>();
30
-
31
- return {
32
- append(receipt: ConsentReceipt): void {
33
- if (!receipts.has(receipt.receiptId)) {
34
- receipts.set(receipt.receiptId, receipt);
35
- }
36
- },
37
- get(receiptId: string): ConsentReceipt | undefined {
38
- return receipts.get(receiptId);
39
- },
40
- };
41
- }
42
-
43
- /**
44
- * The minimal id-keyed primitive a durable backend must expose for {@link createDurableReceiptStore}.
45
- * Keeping it this small lets an integrator back receipts with any store (Vercel KV, Postgres,
46
- * an append-only log) by implementing two methods rather than the full {@link ReceiptStore}.
47
- *
48
- * @since 1.0.0-canary.7
49
- */
50
- export interface ReceiptStoreBackend {
51
- get: (receiptId: string) => Promise<ConsentReceipt | undefined>;
52
- /**
53
- * Persist one receipt under its id. MUST be idempotent-by-id and never overwrite — a
54
- * duplicate `receiptId` is a no-op — so the append-only guarantee holds atomically even
55
- * under a client retry or concurrent write (e.g. KV set-if-absent, Postgres
56
- * `INSERT … ON CONFLICT DO NOTHING`). The frame delegates rather than doing a racy
57
- * get-then-put itself.
58
- */
59
- put: (receiptId: string, receipt: ConsentReceipt) => Promise<void>;
60
- }
61
-
62
- /**
63
- * A durable {@link ReceiptStore} over an injected {@link ReceiptStoreBackend} — the package
64
- * supplies the append-only contract and adaptation, the deployment supplies the backend
65
- * client (no database dependency is baked in). Pair it with a real backend in production,
66
- * where {@link createInMemoryReceiptStore} is not a lawful store on its own.
67
- *
68
- * @since 1.0.0-canary.7
69
- */
70
- export function createDurableReceiptStore(options: { backend: ReceiptStoreBackend }): ReceiptStore {
71
- return {
72
- async append(receipt: ConsentReceipt): Promise<void> {
73
- await options.backend.put(receipt.receiptId, receipt);
74
- },
75
- async get(receiptId: string): Promise<ConsentReceipt | undefined> {
76
- return options.backend.get(receiptId);
77
- },
78
- };
79
- }
@@ -1,89 +0,0 @@
1
- import type { ConsentReceipt, ConsentReceiptInput } from "#/core/consent-receipt";
2
-
3
- /**
4
- * The receipt information-structure version this builder emits (ISO/IEC TS 27560-shaped).
5
- * Bump when the receipt field set changes; stored receipts carry it so a reader can migrate.
6
- *
7
- * @since 1.0.0-canary.7
8
- */
9
- export const RECEIPT_SCHEMA_VERSION = "1.0.0";
10
-
11
- const IPV4_PATTERN = /^(\d{1,3}\.){3}\d{1,3}$/;
12
-
13
- /**
14
- * Coarsens an IP for storage — a full address MUST never be persisted (spec-consent-receipts
15
- * §4, R5). IPv4 drops the last two octets; IPv6 keeps only the first two hextets. This mirrors
16
- * the Cookiebot-style anonymization cited in the spec and is the maximally-private default;
17
- * a controller may widen it under counsel, but the builder never returns a full address.
18
- * Returns `undefined` for a missing or malformed input rather than storing a bad value.
19
- *
20
- * @since 1.0.0-canary.7
21
- */
22
- export function coarsenIp(ip: string | null | undefined): string | undefined {
23
- if (!ip) {
24
- return undefined;
25
- }
26
-
27
- const trimmed = ip.trim();
28
-
29
- if (IPV4_PATTERN.test(trimmed)) {
30
- const octets = trimmed.split(".");
31
-
32
- // Reject out-of-range octets (e.g. "999.1.1.1") rather than storing a malformed coarse value.
33
- if (octets.some((octet) => Number(octet) > 255)) {
34
- return undefined;
35
- }
36
-
37
- return `${octets[0]}.${octets[1]}.0.0`;
38
- }
39
-
40
- if (trimmed.includes(":")) {
41
- const [first, second] = trimmed.split(":");
42
-
43
- // Require two explicit leading hextets — a compressed-leading address ("::1", "fe80::1")
44
- // can't be coarsened without full expansion, so degrade to no stored value.
45
- if (!first || !second) {
46
- return undefined;
47
- }
48
-
49
- return `${first}:${second}::`;
50
- }
51
-
52
- return undefined;
53
- }
54
-
55
- /**
56
- * @remarks
57
- * `sign` is optional so the package never bakes a crypto secret: supply an HMAC/signature
58
- * function to stamp an `integrityKey`, letting a client prove its state matches the stored
59
- * original (spec-consent-receipts §5). Omit it and receipts carry no integrity key.
60
- *
61
- * @since 1.0.0-canary.7
62
- */
63
- export interface BuildConsentReceiptOptions {
64
- input: ConsentReceiptInput;
65
- /** The connection IP, read server-side — never accepted from the request body. */
66
- rawIp?: string | null | undefined;
67
- sign?: ((receipt: Omit<ConsentReceipt, "integrityKey">) => string) | undefined;
68
- }
69
-
70
- /**
71
- * Builds a stored consent receipt from caller input plus server-derived fields
72
- * (`receiptId`, `timestamp`, coarsened IP, optional `integrityKey`). Pure except for the
73
- * id/clock it stamps — pass those in via a seam if a deterministic build is needed.
74
- *
75
- * @since 1.0.0-canary.7
76
- */
77
- export function buildConsentReceipt(options: BuildConsentReceiptOptions): ConsentReceipt {
78
- const base: Omit<ConsentReceipt, "integrityKey"> = {
79
- ...options.input,
80
- ipCoarse: coarsenIp(options.rawIp),
81
- receiptId: crypto.randomUUID(),
82
- schemaVersion: RECEIPT_SCHEMA_VERSION,
83
- timestamp: Date.now(),
84
- };
85
-
86
- const integrityKey = options.sign?.(base);
87
-
88
- return integrityKey === undefined ? base : { ...base, integrityKey };
89
- }
@@ -1,46 +0,0 @@
1
- import type { ConsentCategory, InitialConsent } from "#/core/consent";
2
- import { resolveConsentMode, resolveDefaultConsent, STRICTEST_INITIAL_CONSENT } from "#/core/consent";
3
- import { resolveRegionFromCountryCode } from "#/server/region";
4
-
5
- /**
6
- * @since 1.0.0-canary.6
7
- */
8
- export interface InitialConsentOptions {
9
- /** ISO 3166-1 alpha-2 from the geo header; missing → the strictest opt-in default. */
10
- countryCode: string | undefined;
11
- /** Honored as an ads-only opt-out on the default decision. */
12
- hasGlobalPrivacyControlSignal?: boolean | undefined;
13
- /** Categories the app's prompt asks about — opt-out regions grant exactly these by default. */
14
- requestedCategories: ReadonlyArray<ConsentCategory>;
15
- }
16
-
17
- /**
18
- * Pure region → mode → default-consent resolution for server functions (or a fail-closed
19
- * bake when country is unknown). Named with the `resolve*` family it composes.
20
- *
21
- * @remarks
22
- * A missing country code means an unknown visitor (a prerender crawl, a host without a
23
- * geo header) — not a known non-EU visitor — so it fails closed to
24
- * {@link STRICTEST_INITIAL_CONSENT} instead of `"other"`'s opt-out. Conflating the two
25
- * would grant analytics by default to every visitor, EU included, on a geo-less host.
26
- *
27
- * @since 1.0.0-canary.6
28
- */
29
- export function resolveInitialConsent(options: InitialConsentOptions): InitialConsent {
30
- if (!options.countryCode) {
31
- return STRICTEST_INITIAL_CONSENT;
32
- }
33
-
34
- const region = resolveRegionFromCountryCode(options.countryCode);
35
- const mode = resolveConsentMode(region);
36
-
37
- return {
38
- defaultConsent: resolveDefaultConsent({
39
- hasGlobalPrivacyControlSignal: options.hasGlobalPrivacyControlSignal ?? false,
40
- mode,
41
- requestedCategories: options.requestedCategories,
42
- }),
43
- mode,
44
- region,
45
- };
46
- }
@@ -1,114 +0,0 @@
1
- import type { ConsentDecision } from "#/core/consent";
2
-
3
- /**
4
- * A GA4 event for the Measurement Protocol. `params` are flat scalars — GA4 rejects nested values and booleans.
5
- *
6
- * @since 1.0.0-canary.7
7
- */
8
- export interface MeasurementProtocolEvent {
9
- name: string;
10
- params?: Record<string, number | string> | undefined;
11
- }
12
-
13
- /**
14
- * The GA4 MP `consent` object — the two ad-consent signals the payload accepts.
15
- *
16
- * @since 1.0.0-canary.7
17
- */
18
- export interface MeasurementProtocolConsent {
19
- ad_personalization: "DENIED" | "GRANTED";
20
- ad_user_data: "DENIED" | "GRANTED";
21
- }
22
-
23
- /**
24
- * Maps the package `ConsentDecision` to GA4 MP consent signals — `ads` drives both ad fields.
25
- *
26
- * @since 1.0.0-canary.7
27
- */
28
- export function toMeasurementProtocolConsent(decision: ConsentDecision): MeasurementProtocolConsent {
29
- const state = decision.ads ? "GRANTED" : "DENIED";
30
-
31
- return { ad_personalization: state, ad_user_data: state };
32
- }
33
-
34
- /**
35
- * Extracts the GA4 `client_id` from a `_ga` cookie value, e.g.
36
- * `GA1.1.1809596761.1693829043` → `1809596761.1693829043` (everything past the
37
- * `GA1.<version>.` prefix). The `_ga` layout is community-established, not part of the
38
- * Measurement Protocol reference, so anything that doesn't parse returns `undefined` rather
39
- * than sending a malformed id.
40
- *
41
- * @since 1.0.0-canary.7
42
- */
43
- export function extractGaClientId(gaCookieValue: string | undefined): string | undefined {
44
- if (!gaCookieValue) {
45
- return undefined;
46
- }
47
-
48
- const segments = gaCookieValue.split(".");
49
-
50
- if (segments.length < 4 || segments[0] !== "GA1") {
51
- return undefined;
52
- }
53
-
54
- return segments.slice(2).join(".");
55
- }
56
-
57
- /**
58
- * The one network primitive the sender needs — injected so the package ships no HTTP client.
59
- *
60
- * @since 1.0.0-canary.7
61
- */
62
- export type MeasurementProtocolTransport = (request: { body: string; url: string }) => Promise<void>;
63
-
64
- /** Default GA4 collection origin; use `https://region1.google-analytics.com` for EU data residency. */
65
- const DEFAULT_ENDPOINT_ORIGIN = "https://www.google-analytics.com";
66
-
67
- async function defaultTransport(request: { body: string; url: string }): Promise<void> {
68
- const response = await fetch(request.url, {
69
- body: request.body,
70
- headers: { "content-type": "application/json" },
71
- method: "POST",
72
- });
73
-
74
- // MP returns 2xx with no useful body; a non-2xx is a config error worth surfacing.
75
- if (!response.ok) {
76
- throw new Error(`Measurement Protocol responded ${String(response.status)}`);
77
- }
78
- }
79
-
80
- /**
81
- * @since 1.0.0-canary.7
82
- */
83
- export interface SendMeasurementProtocolEventsOptions {
84
- /** GA4 **API Secret** — read server-side from config, never a client-exposed var. */
85
- apiSecret: string;
86
- /** The visitor's GA4 client id (see {@link extractGaClientId}). */
87
- clientId: string;
88
- consent?: MeasurementProtocolConsent | undefined;
89
- endpointOrigin?: string | undefined;
90
- events: ReadonlyArray<MeasurementProtocolEvent>;
91
- measurementId: string;
92
- transport?: MeasurementProtocolTransport | undefined;
93
- }
94
-
95
- /**
96
- * POSTs one or more events to the GA4 Measurement Protocol for a known `client_id` — the
97
- * server-side counterpart to gtag.js. The caller owns credentials (never bake them) and the
98
- * consent gate: send only for a server-owned event the visitor's consent permits.
99
- *
100
- * @see https://developers.google.com/analytics/devguides/collection/protocol/ga4/sending-events
101
- *
102
- * @since 1.0.0-canary.7
103
- */
104
- export async function sendMeasurementProtocolEvents(options: SendMeasurementProtocolEventsOptions): Promise<void> {
105
- const origin = options.endpointOrigin ?? DEFAULT_ENDPOINT_ORIGIN;
106
- const url = `${origin}/mp/collect?measurement_id=${encodeURIComponent(options.measurementId)}&api_secret=${encodeURIComponent(options.apiSecret)}`;
107
- const body = JSON.stringify({
108
- client_id: options.clientId,
109
- events: options.events,
110
- ...(options.consent ? { consent: options.consent } : {}),
111
- });
112
-
113
- await (options.transport ?? defaultTransport)({ body, url });
114
- }