@codefast/tracking 0.5.0-canary.4 → 0.5.0-canary.6

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 (277) hide show
  1. package/CHANGELOG.md +473 -0
  2. package/README.md +177 -95
  3. package/dist/adapters/tanstack-start.d.ts +80 -0
  4. package/dist/adapters/tanstack-start.d.ts.map +1 -0
  5. package/dist/adapters/tanstack-start.js +74 -0
  6. package/dist/adapters/tanstack-start.js.map +1 -0
  7. package/dist/client/ad-framework-consent.d.ts +62 -0
  8. package/dist/client/ad-framework-consent.d.ts.map +1 -0
  9. package/dist/client/ad-framework-consent.js +40 -0
  10. package/dist/client/ad-framework-consent.js.map +1 -0
  11. package/dist/client/browser-cookie.d.ts +9 -0
  12. package/dist/client/browser-cookie.d.ts.map +1 -0
  13. package/dist/client/browser-cookie.js +15 -0
  14. package/dist/client/browser-cookie.js.map +1 -0
  15. package/dist/client/consent-runtime.d.ts +53 -0
  16. package/dist/client/consent-runtime.d.ts.map +1 -0
  17. package/dist/client/consent-runtime.js +33 -0
  18. package/dist/client/consent-runtime.js.map +1 -0
  19. package/dist/client/{consent-storage.d.mts → consent-storage.d.ts} +8 -6
  20. package/dist/client/consent-storage.d.ts.map +1 -0
  21. package/dist/client/consent-storage.js +109 -0
  22. package/dist/client/consent-storage.js.map +1 -0
  23. package/dist/client/consent-withdrawal.d.ts +18 -0
  24. package/dist/client/consent-withdrawal.d.ts.map +1 -0
  25. package/dist/client/consent-withdrawal.js +17 -0
  26. package/dist/client/consent-withdrawal.js.map +1 -0
  27. package/dist/client/cookie-anonymous-id.d.ts +41 -0
  28. package/dist/client/cookie-anonymous-id.d.ts.map +1 -0
  29. package/dist/client/cookie-anonymous-id.js +65 -0
  30. package/dist/client/cookie-anonymous-id.js.map +1 -0
  31. package/dist/client/create-client-tracker.d.ts +60 -0
  32. package/dist/client/create-client-tracker.d.ts.map +1 -0
  33. package/dist/client/create-client-tracker.js +91 -0
  34. package/dist/client/create-client-tracker.js.map +1 -0
  35. package/dist/client/gpc.d.ts +10 -0
  36. package/dist/client/gpc.d.ts.map +1 -0
  37. package/dist/client/gpc.js +12 -0
  38. package/dist/client/gpc.js.map +1 -0
  39. package/dist/client/initial-consent-store.d.ts +63 -0
  40. package/dist/client/initial-consent-store.d.ts.map +1 -0
  41. package/dist/client/initial-consent-store.js +138 -0
  42. package/dist/client/initial-consent-store.js.map +1 -0
  43. package/dist/client/is-analytics-allowed.d.ts +26 -0
  44. package/dist/client/is-analytics-allowed.d.ts.map +1 -0
  45. package/dist/client/is-analytics-allowed.js +22 -0
  46. package/dist/client/is-analytics-allowed.js.map +1 -0
  47. package/dist/client/server-persisted-anonymous-id.d.ts +30 -0
  48. package/dist/client/server-persisted-anonymous-id.d.ts.map +1 -0
  49. package/dist/client/server-persisted-anonymous-id.js +72 -0
  50. package/dist/client/server-persisted-anonymous-id.js.map +1 -0
  51. package/dist/core/consent-config.d.ts +24 -0
  52. package/dist/core/consent-config.d.ts.map +1 -0
  53. package/dist/core/consent-config.js +9 -0
  54. package/dist/core/consent-config.js.map +1 -0
  55. package/dist/core/consent-receipt.d.ts +71 -0
  56. package/dist/core/consent-receipt.d.ts.map +1 -0
  57. package/dist/core/consent-receipt.js +39 -0
  58. package/dist/core/consent-receipt.js.map +1 -0
  59. package/dist/core/consent.d.ts +182 -0
  60. package/dist/core/consent.d.ts.map +1 -0
  61. package/dist/core/consent.js +159 -0
  62. package/dist/core/consent.js.map +1 -0
  63. package/dist/core/cookie.d.ts +15 -0
  64. package/dist/core/cookie.d.ts.map +1 -0
  65. package/dist/core/cookie.js +26 -0
  66. package/dist/core/cookie.js.map +1 -0
  67. package/dist/core/destination.d.ts +29 -0
  68. package/dist/core/destination.d.ts.map +1 -0
  69. package/dist/core/destination.js +2 -0
  70. package/dist/core/destination.js.map +1 -0
  71. package/dist/core/event-catalog.d.ts +35 -0
  72. package/dist/core/event-catalog.d.ts.map +1 -0
  73. package/dist/core/event-catalog.js +30 -0
  74. package/dist/core/event-catalog.js.map +1 -0
  75. package/dist/core/event-id.d.ts +7 -0
  76. package/dist/core/event-id.d.ts.map +1 -0
  77. package/dist/core/event-id.js +9 -0
  78. package/dist/core/event-id.js.map +1 -0
  79. package/dist/core/tracked-event.d.ts +15 -0
  80. package/dist/core/tracked-event.d.ts.map +1 -0
  81. package/dist/core/tracked-event.js +2 -0
  82. package/dist/core/tracked-event.js.map +1 -0
  83. package/dist/destinations/ad-consent.d.ts +23 -0
  84. package/dist/destinations/ad-consent.d.ts.map +1 -0
  85. package/dist/destinations/ad-consent.js +12 -0
  86. package/dist/destinations/ad-consent.js.map +1 -0
  87. package/dist/destinations/google-analytics.d.ts +148 -0
  88. package/dist/destinations/google-analytics.d.ts.map +1 -0
  89. package/dist/destinations/google-analytics.js +156 -0
  90. package/dist/destinations/google-analytics.js.map +1 -0
  91. package/dist/destinations/google-consent.d.ts +62 -0
  92. package/dist/destinations/google-consent.d.ts.map +1 -0
  93. package/dist/destinations/google-consent.js +109 -0
  94. package/dist/destinations/google-consent.js.map +1 -0
  95. package/dist/destinations/meta.d.ts +63 -0
  96. package/dist/destinations/meta.d.ts.map +1 -0
  97. package/dist/destinations/meta.js +44 -0
  98. package/dist/destinations/meta.js.map +1 -0
  99. package/dist/destinations/microsoft-uet.d.ts +56 -0
  100. package/dist/destinations/microsoft-uet.d.ts.map +1 -0
  101. package/dist/destinations/microsoft-uet.js +41 -0
  102. package/dist/destinations/microsoft-uet.js.map +1 -0
  103. package/dist/destinations/shared.d.ts +18 -0
  104. package/dist/destinations/shared.d.ts.map +1 -0
  105. package/dist/destinations/shared.js +19 -0
  106. package/dist/destinations/shared.js.map +1 -0
  107. package/dist/destinations/tiktok.d.ts +55 -0
  108. package/dist/destinations/tiktok.d.ts.map +1 -0
  109. package/dist/destinations/tiktok.js +40 -0
  110. package/dist/destinations/tiktok.js.map +1 -0
  111. package/dist/destinations/vercel-analytics.d.ts +25 -0
  112. package/dist/destinations/vercel-analytics.d.ts.map +1 -0
  113. package/dist/destinations/vercel-analytics.js +23 -0
  114. package/dist/destinations/vercel-analytics.js.map +1 -0
  115. package/dist/index.d.ts +64 -0
  116. package/dist/index.d.ts.map +1 -0
  117. package/dist/index.js +41 -0
  118. package/dist/index.js.map +1 -0
  119. package/dist/react/consent-banner.d.ts +155 -0
  120. package/dist/react/consent-banner.d.ts.map +1 -0
  121. package/dist/react/consent-banner.js +171 -0
  122. package/dist/react/consent-banner.js.map +1 -0
  123. package/dist/react/gtag-consent-bootstrap.d.ts +17 -0
  124. package/dist/react/gtag-consent-bootstrap.d.ts.map +1 -0
  125. package/dist/react/gtag-consent-bootstrap.js +22 -0
  126. package/dist/react/gtag-consent-bootstrap.js.map +1 -0
  127. package/dist/react/use-consent.d.ts +42 -0
  128. package/dist/react/use-consent.d.ts.map +1 -0
  129. package/dist/react/use-consent.js +60 -0
  130. package/dist/react/use-consent.js.map +1 -0
  131. package/dist/react/use-google-consent-sync.d.ts +20 -0
  132. package/dist/react/use-google-consent-sync.d.ts.map +1 -0
  133. package/dist/react/use-google-consent-sync.js +22 -0
  134. package/dist/react/use-google-consent-sync.js.map +1 -0
  135. package/dist/react/use-initial-consent.d.ts +11 -0
  136. package/dist/react/use-initial-consent.d.ts.map +1 -0
  137. package/dist/react/use-initial-consent.js +18 -0
  138. package/dist/react/use-initial-consent.js.map +1 -0
  139. package/dist/server/anonymous-id-cookie.d.ts +67 -0
  140. package/dist/server/anonymous-id-cookie.d.ts.map +1 -0
  141. package/dist/server/anonymous-id-cookie.js +71 -0
  142. package/dist/server/anonymous-id-cookie.js.map +1 -0
  143. package/dist/server/consent-receipt-store.d.ts +56 -0
  144. package/dist/server/consent-receipt-store.d.ts.map +1 -0
  145. package/dist/server/consent-receipt-store.js +44 -0
  146. package/dist/server/consent-receipt-store.js.map +1 -0
  147. package/dist/server/consent-receipt.d.ts +41 -0
  148. package/dist/server/consent-receipt.d.ts.map +1 -0
  149. package/dist/server/consent-receipt.js +60 -0
  150. package/dist/server/consent-receipt.js.map +1 -0
  151. package/dist/server/initial-consent.d.ts +26 -0
  152. package/dist/server/initial-consent.d.ts.map +1 -0
  153. package/dist/server/initial-consent.js +31 -0
  154. package/dist/server/initial-consent.js.map +1 -0
  155. package/dist/server/measurement-protocol.d.ts +69 -0
  156. package/dist/server/measurement-protocol.d.ts.map +1 -0
  157. package/dist/server/measurement-protocol.js +61 -0
  158. package/dist/server/measurement-protocol.js.map +1 -0
  159. package/dist/server/region.d.ts +27 -0
  160. package/dist/server/region.d.ts.map +1 -0
  161. package/dist/server/region.js +69 -0
  162. package/dist/server/region.js.map +1 -0
  163. package/dist/server/user-deletion.d.ts +64 -0
  164. package/dist/server/user-deletion.d.ts.map +1 -0
  165. package/dist/server/user-deletion.js +54 -0
  166. package/dist/server/user-deletion.js.map +1 -0
  167. package/dist/tooling/import-protection.d.ts +19 -0
  168. package/dist/tooling/import-protection.d.ts.map +1 -0
  169. package/dist/tooling/import-protection.js +23 -0
  170. package/dist/tooling/import-protection.js.map +1 -0
  171. package/package.json +202 -107
  172. package/src/adapters/tanstack-start.ts +135 -0
  173. package/src/client/ad-framework-consent.ts +86 -0
  174. package/src/client/browser-cookie.ts +16 -0
  175. package/src/client/consent-runtime.ts +80 -0
  176. package/src/client/consent-storage.ts +31 -1
  177. package/src/client/consent-withdrawal.ts +32 -0
  178. package/src/client/cookie-anonymous-id.ts +112 -0
  179. package/src/client/create-client-tracker.ts +128 -86
  180. package/src/client/gpc.ts +4 -2
  181. package/src/client/initial-consent-store.ts +218 -0
  182. package/src/client/is-analytics-allowed.ts +43 -0
  183. package/src/client/server-persisted-anonymous-id.ts +102 -0
  184. package/src/core/consent-config.ts +27 -0
  185. package/src/core/consent-receipt.ts +115 -0
  186. package/src/core/consent.ts +164 -10
  187. package/src/core/cookie.ts +29 -0
  188. package/src/core/destination.ts +17 -8
  189. package/src/core/event-catalog.ts +29 -15
  190. package/src/core/event-id.ts +1 -2
  191. package/src/core/tracked-event.ts +4 -4
  192. package/src/css/consent.css +119 -0
  193. package/src/destinations/ad-consent.ts +29 -0
  194. package/src/destinations/google-analytics.ts +196 -133
  195. package/src/destinations/google-consent.ts +164 -0
  196. package/src/destinations/meta.ts +96 -0
  197. package/src/destinations/microsoft-uet.ts +86 -0
  198. package/src/destinations/shared.ts +45 -0
  199. package/src/destinations/tiktok.ts +85 -0
  200. package/src/destinations/vercel-analytics.ts +23 -24
  201. package/src/index.ts +165 -8
  202. package/src/react/consent-banner.tsx +308 -111
  203. package/src/react/gtag-consent-bootstrap.tsx +48 -0
  204. package/src/react/use-consent.ts +53 -45
  205. package/src/react/use-google-consent-sync.ts +38 -0
  206. package/src/react/use-initial-consent.ts +22 -0
  207. package/src/server/anonymous-id-cookie.ts +103 -0
  208. package/src/server/consent-receipt-store.ts +79 -0
  209. package/src/server/consent-receipt.ts +89 -0
  210. package/src/server/initial-consent.ts +46 -0
  211. package/src/server/measurement-protocol.ts +114 -0
  212. package/src/server/region.ts +22 -15
  213. package/src/server/user-deletion.ts +93 -0
  214. package/src/tooling/import-protection.ts +22 -0
  215. package/dist/client/consent-storage.mjs +0 -63
  216. package/dist/client/create-client-tracker.d.mts +0 -37
  217. package/dist/client/create-client-tracker.mjs +0 -66
  218. package/dist/client/gpc.d.mts +0 -10
  219. package/dist/client/gpc.mjs +0 -12
  220. package/dist/client/index.d.mts +0 -8
  221. package/dist/client/index.mjs +0 -8
  222. package/dist/client/lifecycle.d.mts +0 -23
  223. package/dist/client/lifecycle.mjs +0 -30
  224. package/dist/client/local-storage.d.mts +0 -13
  225. package/dist/client/local-storage.mjs +0 -31
  226. package/dist/client/queue.d.mts +0 -49
  227. package/dist/client/queue.mjs +0 -71
  228. package/dist/client/router.d.mts +0 -30
  229. package/dist/client/router.mjs +0 -17
  230. package/dist/core/consent.d.mts +0 -89
  231. package/dist/core/consent.mjs +0 -57
  232. package/dist/core/destination.d.mts +0 -23
  233. package/dist/core/destination.mjs +0 -1
  234. package/dist/core/event-catalog.d.mts +0 -36
  235. package/dist/core/event-catalog.mjs +0 -12
  236. package/dist/core/event-id.d.mts +0 -10
  237. package/dist/core/event-id.mjs +0 -12
  238. package/dist/core/index.d.mts +0 -6
  239. package/dist/core/index.mjs +0 -4
  240. package/dist/core/tracked-event.d.mts +0 -17
  241. package/dist/core/tracked-event.mjs +0 -1
  242. package/dist/destinations/ga4-measurement-protocol.d.mts +0 -54
  243. package/dist/destinations/ga4-measurement-protocol.mjs +0 -89
  244. package/dist/destinations/google-analytics.d.mts +0 -98
  245. package/dist/destinations/google-analytics.mjs +0 -126
  246. package/dist/destinations/http-destination.d.mts +0 -20
  247. package/dist/destinations/http-destination.mjs +0 -25
  248. package/dist/destinations/index.d.mts +0 -5
  249. package/dist/destinations/index.mjs +0 -5
  250. package/dist/destinations/vercel-analytics.d.mts +0 -13
  251. package/dist/destinations/vercel-analytics.mjs +0 -30
  252. package/dist/index.d.mts +0 -6
  253. package/dist/index.mjs +0 -4
  254. package/dist/react/consent-banner.d.mts +0 -75
  255. package/dist/react/consent-banner.mjs +0 -114
  256. package/dist/react/index.d.mts +0 -3
  257. package/dist/react/index.mjs +0 -3
  258. package/dist/react/use-consent.d.mts +0 -49
  259. package/dist/react/use-consent.mjs +0 -54
  260. package/dist/server/create-server-tracker.d.mts +0 -42
  261. package/dist/server/create-server-tracker.mjs +0 -67
  262. package/dist/server/index.d.mts +0 -3
  263. package/dist/server/index.mjs +0 -3
  264. package/dist/server/region.d.mts +0 -20
  265. package/dist/server/region.mjs +0 -56
  266. package/src/client/index.ts +0 -17
  267. package/src/client/lifecycle.ts +0 -50
  268. package/src/client/local-storage.ts +0 -44
  269. package/src/client/queue.ts +0 -117
  270. package/src/client/router.ts +0 -37
  271. package/src/core/index.ts +0 -24
  272. package/src/destinations/ga4-measurement-protocol.ts +0 -166
  273. package/src/destinations/http-destination.ts +0 -33
  274. package/src/destinations/index.ts +0 -20
  275. package/src/react/index.ts +0 -5
  276. package/src/server/create-server-tracker.ts +0 -128
  277. package/src/server/index.ts +0 -4
@@ -0,0 +1,218 @@
1
+ import type { InitialConsent } from "#/core/consent";
2
+ import { isInitialConsent, STRICTEST_INITIAL_CONSENT } from "#/core/consent";
3
+
4
+ /**
5
+ * External-store view of the visitor's region default — the strictest value until the
6
+ * server lane answers, then the resolved one.
7
+ *
8
+ * @since 1.0.0-canary.6
9
+ */
10
+ export interface InitialConsentSnapshot {
11
+ /** The region-correct default once resolved; {@link STRICTEST_INITIAL_CONSENT} until then. */
12
+ initialConsent: InitialConsent;
13
+ /**
14
+ * True once a usable default is published — either a successful server answer or a
15
+ * fail-closed fallback. A failed fetch still sets this so consent UI can render, but
16
+ * does not lock the session: resolution stays retryable.
17
+ */
18
+ isResolved: boolean;
19
+ }
20
+
21
+ /**
22
+ * @since 1.0.0-canary.6
23
+ */
24
+ export interface InitialConsentStoreOptions {
25
+ /**
26
+ * The per-visitor server lane — typically a server function wrapping
27
+ * `resolveInitialConsentFromRequest`. Prerendered/CDN-cached HTML can carry nothing
28
+ * region-specific, so this is the only place the region-correct default may come from.
29
+ */
30
+ resolve: () => Promise<InitialConsent>;
31
+ /**
32
+ * `sessionStorage` key caching the resolved value, so only the first page load of a
33
+ * session pays the round trip — omit to resolve once per page load instead. Cached
34
+ * values are re-validated with `isInitialConsent` before use.
35
+ */
36
+ sessionStorageKey?: string | undefined;
37
+ }
38
+
39
+ /**
40
+ * `useSyncExternalStore`-shaped — pass `subscribe`/`getSnapshot`/`getServerSnapshot`
41
+ * straight through, or use the `useInitialConsent` hook from `@codefast/tracking/react`.
42
+ *
43
+ * @since 1.0.0-canary.6
44
+ */
45
+ export interface InitialConsentStore {
46
+ /**
47
+ * Kicks off region resolution (at most one in-flight request; a success is sticky for
48
+ * the store's lifetime). Call it early — e.g. at router creation, window-guarded — so
49
+ * the round trip overlaps hydration instead of waiting for the first effect.
50
+ */
51
+ ensureResolved: () => void;
52
+ getServerSnapshot: () => InitialConsentSnapshot;
53
+ getSnapshot: () => InitialConsentSnapshot;
54
+ /** Test seam — clears resolved state, retry listeners, and the session cache. */
55
+ reset: () => void;
56
+ subscribe: (listener: () => void) => () => void;
57
+ }
58
+
59
+ const SERVER_SNAPSHOT: InitialConsentSnapshot = {
60
+ initialConsent: STRICTEST_INITIAL_CONSENT,
61
+ isResolved: false,
62
+ };
63
+
64
+ /**
65
+ * The client half of the server-resolved consent lane: single-flight resolution over the
66
+ * given server function, an optional per-session cache, fail-closed publishing on error
67
+ * (consent UI still renders, under the strictest default), and a retry the next time the
68
+ * tab becomes visible — so one failed request never locks the whole SPA session.
69
+ *
70
+ * @since 1.0.0-canary.6
71
+ */
72
+ export function createInitialConsentStore(options: InitialConsentStoreOptions): InitialConsentStore {
73
+ const listeners = new Set<() => void>();
74
+
75
+ let snapshot: InitialConsentSnapshot = SERVER_SNAPSHOT;
76
+ let isFetchInFlight = false;
77
+ /** Sticky only after a successful resolve (or session-cache hit) — failures stay retryable. */
78
+ let hasResolvedSuccessfully = false;
79
+
80
+ function notify(): void {
81
+ for (const listener of listeners) {
82
+ listener();
83
+ }
84
+ }
85
+
86
+ // add/removeEventListener dedupe an identical listener, so no armed-flag is needed.
87
+ function stopResolveRetry(): void {
88
+ if (typeof window === "undefined") {
89
+ return;
90
+ }
91
+
92
+ document.removeEventListener("visibilitychange", onResolveRetryResume);
93
+ window.removeEventListener("pageshow", onResolveRetryResume);
94
+ window.removeEventListener("online", onResolveRetryResume);
95
+ }
96
+
97
+ function onResolveRetryResume(): void {
98
+ if (hasResolvedSuccessfully) {
99
+ stopResolveRetry();
100
+
101
+ return;
102
+ }
103
+
104
+ if (document.visibilityState === "visible") {
105
+ ensureResolved();
106
+ }
107
+ }
108
+
109
+ /**
110
+ * After a failed fetch, retry when the tab becomes visible again or connectivity
111
+ * returns (coalesced by in-flight) — a visitor who never leaves the tab must not stay
112
+ * fail-closed for the whole session over one network blip.
113
+ */
114
+ function scheduleResolveRetry(): void {
115
+ if (typeof window === "undefined") {
116
+ return;
117
+ }
118
+
119
+ document.addEventListener("visibilitychange", onResolveRetryResume);
120
+ window.addEventListener("pageshow", onResolveRetryResume);
121
+ window.addEventListener("online", onResolveRetryResume);
122
+ }
123
+
124
+ function publishResolved(initialConsent: InitialConsent): void {
125
+ hasResolvedSuccessfully = true;
126
+ snapshot = { initialConsent, isResolved: true };
127
+ stopResolveRetry();
128
+ notify();
129
+ }
130
+
131
+ /** Fail-closed UI without permanently locking the session against a later retry. */
132
+ function publishFailClosed(): void {
133
+ snapshot = { initialConsent: STRICTEST_INITIAL_CONSENT, isResolved: true };
134
+ notify();
135
+ }
136
+
137
+ function readSessionCache(): InitialConsent | undefined {
138
+ if (options.sessionStorageKey === undefined) {
139
+ return undefined;
140
+ }
141
+
142
+ try {
143
+ const raw = window.sessionStorage.getItem(options.sessionStorageKey);
144
+ const parsed: unknown = raw === null ? undefined : JSON.parse(raw);
145
+
146
+ return isInitialConsent(parsed) ? parsed : undefined;
147
+ } catch {
148
+ return undefined;
149
+ }
150
+ }
151
+
152
+ function writeSessionCache(resolved: InitialConsent): void {
153
+ if (options.sessionStorageKey === undefined) {
154
+ return;
155
+ }
156
+
157
+ try {
158
+ window.sessionStorage.setItem(options.sessionStorageKey, JSON.stringify(resolved));
159
+ } catch {
160
+ /* private mode / quota — resolve again next page load */
161
+ }
162
+ }
163
+
164
+ function ensureResolved(): void {
165
+ if (hasResolvedSuccessfully || isFetchInFlight || typeof window === "undefined") {
166
+ return;
167
+ }
168
+
169
+ const cached = readSessionCache();
170
+
171
+ if (cached) {
172
+ publishResolved(cached);
173
+
174
+ return;
175
+ }
176
+
177
+ isFetchInFlight = true;
178
+
179
+ // Promise.resolve().then(...) folds a synchronously throwing resolver into the same
180
+ // fail-closed path — tracking must never break the caller (a React mount effect).
181
+ Promise.resolve()
182
+ .then(() => options.resolve())
183
+ .then((resolved) => {
184
+ writeSessionCache(resolved);
185
+ publishResolved(resolved);
186
+ })
187
+ .catch(() => {
188
+ publishFailClosed();
189
+ scheduleResolveRetry();
190
+ })
191
+ .finally(() => {
192
+ isFetchInFlight = false;
193
+ });
194
+ }
195
+
196
+ return {
197
+ ensureResolved,
198
+ getServerSnapshot: () => SERVER_SNAPSHOT,
199
+ getSnapshot: () => snapshot,
200
+ reset(): void {
201
+ stopResolveRetry();
202
+ snapshot = SERVER_SNAPSHOT;
203
+ isFetchInFlight = false;
204
+ hasResolvedSuccessfully = false;
205
+
206
+ if (typeof window !== "undefined" && options.sessionStorageKey !== undefined) {
207
+ window.sessionStorage.removeItem(options.sessionStorageKey);
208
+ }
209
+ },
210
+ subscribe(listener: () => void): () => void {
211
+ listeners.add(listener);
212
+
213
+ return () => {
214
+ listeners.delete(listener);
215
+ };
216
+ },
217
+ };
218
+ }
@@ -0,0 +1,43 @@
1
+ import type { ConsentMode, ConsentStorage } from "#/core/consent";
2
+ import { resolveEffectiveConsent } from "#/core/consent";
3
+ import type { ConsentConfig } from "#/core/consent-config";
4
+
5
+ /**
6
+ * @since 1.0.0-canary.6
7
+ */
8
+ export interface IsAnalyticsAllowedOptions {
9
+ /** Must be the same object `useConsent` receives — one config, every surface. */
10
+ config: ConsentConfig;
11
+ /**
12
+ * Re-read each call. Pass `hasGlobalPrivacyControlSignal` from `@codefast/tracking/client`
13
+ * (or a wrapper) so GPC changes apply without recreating the gate.
14
+ */
15
+ hasGlobalPrivacyControlSignal?: (() => boolean) | undefined;
16
+ /** Re-read each call so a post-hydration region resolve can win. */
17
+ getMode: () => ConsentMode;
18
+ /** Must be the same storage instance `useConsent` subscribes to. */
19
+ storage: ConsentStorage;
20
+ }
21
+
22
+ /**
23
+ * Non-React mirror of `useConsent`'s `isAnalyticsAllowed` — pass the returned function as
24
+ * `createClientTracker({ isAnalyticsAllowed })` so the pipeline and the banner share one rule.
25
+ *
26
+ * @since 1.0.0-canary.6
27
+ */
28
+ export function createIsAnalyticsAllowed(options: IsAnalyticsAllowedOptions): () => boolean {
29
+ const { config, getMode, storage } = options;
30
+ const readGpc = options.hasGlobalPrivacyControlSignal ?? (() => false);
31
+
32
+ return (): boolean => {
33
+ const effectiveConsent = resolveEffectiveConsent({
34
+ hasGlobalPrivacyControlSignal: readGpc(),
35
+ mode: getMode(),
36
+ policyVersion: config.policyVersion,
37
+ requestedCategories: config.requestedCategories,
38
+ storage,
39
+ });
40
+
41
+ return effectiveConsent.analytics;
42
+ };
43
+ }
@@ -0,0 +1,102 @@
1
+ import type { CookieAnonymousId } from "#/client/cookie-anonymous-id";
2
+ import { createCookieAnonymousId } from "#/client/cookie-anonymous-id";
3
+ import { readCookieValue } from "#/core/cookie";
4
+
5
+ /**
6
+ * @since 1.0.0-canary.6
7
+ */
8
+ export interface ServerPersistedAnonymousIdOptions {
9
+ /** Server round-trip that expires the cookie via `Set-Cookie` — the server half of `clear()`. */
10
+ clearOnServer?: (() => Promise<void>) | undefined;
11
+ /** Cookie name — must not collide with another cookie on the domain. */
12
+ cookieName: string;
13
+ /** How long the id survives a return visit. Defaults to one year. */
14
+ maxAgeSeconds?: number | undefined;
15
+ /**
16
+ * Server round-trip that re-sets the cookie via `Set-Cookie` (e.g. a server function
17
+ * calling `setAnonymousIdResponseCookie`). Fired at most once per page load, only after an
18
+ * id exists client-side — the server persists and prolongs, it never mints.
19
+ */
20
+ persist: (id: string) => Promise<void>;
21
+ }
22
+
23
+ /**
24
+ * `createCookieAnonymousId` plus server persistence: the client still mints the id
25
+ * (lazily, only once an event is allowed to send — consent stays client-owned), then
26
+ * delegates the durable write to the server. A script-written cookie is capped at 7 days
27
+ * by Safari ITP; the server's `Set-Cookie` re-issue is what makes the id actually live
28
+ * its full max-age. Same optimistic `document.cookie` write first, so the current event
29
+ * never waits on the round-trip and a failed `persist` degrades to today's behavior.
30
+ *
31
+ * @since 1.0.0-canary.6
32
+ */
33
+ export function createServerPersistedAnonymousId(options: ServerPersistedAnonymousIdOptions): CookieAnonymousId {
34
+ const { clearOnServer, cookieName, maxAgeSeconds, persist } = options;
35
+ const local = createCookieAnonymousId({ cookieName, maxAgeSeconds });
36
+ // One attempt per page load — a failure is not retried until the next load, so a down
37
+ // endpoint costs one request, not one per event. Tracking must never break the app.
38
+ let hasRequestedPersist = false;
39
+
40
+ return {
41
+ clear(): void {
42
+ // Skip the server round-trip when the cookie is already gone (e.g. a second
43
+ // withdrawal clear from another mounted consent surface in the same tick).
44
+ const shouldClearServer =
45
+ typeof document !== "undefined" && Boolean(readCookieValue(document.cookie, cookieName));
46
+
47
+ local.clear();
48
+ // A fresh id after a re-grant must be persisted again.
49
+ hasRequestedPersist = false;
50
+
51
+ if (shouldClearServer) {
52
+ void clearOnServer?.().catch(() => {
53
+ /* the client-side expiry above already took effect */
54
+ });
55
+ }
56
+ },
57
+ current(): string | undefined {
58
+ return local.current();
59
+ },
60
+ getOrCreate(): string {
61
+ // Cross-tab withdrawal expires the cookie without this instance's `clear()` — reset
62
+ // so the next minted id is server-persisted (ITP re-issue) again.
63
+ if (typeof document !== "undefined" && !readCookieValue(document.cookie, cookieName)) {
64
+ hasRequestedPersist = false;
65
+ }
66
+
67
+ const id = local.getOrCreate();
68
+
69
+ // Also fires when the cookie already existed: the re-issue upgrades a script-written
70
+ // cookie to a server-set one and rolls its expiry forward on every visit.
71
+ if (!hasRequestedPersist && typeof document !== "undefined") {
72
+ hasRequestedPersist = true;
73
+ void persist(id).catch(() => {
74
+ /* optimistic client-side cookie still covers this session */
75
+ });
76
+ }
77
+
78
+ return id;
79
+ },
80
+ refresh(): void {
81
+ if (typeof document === "undefined") {
82
+ return;
83
+ }
84
+
85
+ const existing = readCookieValue(document.cookie, cookieName);
86
+
87
+ if (!existing) {
88
+ return;
89
+ }
90
+
91
+ local.refresh();
92
+
93
+ // Same once-per-load budget as getOrCreate — refresh must not add a second request.
94
+ if (!hasRequestedPersist) {
95
+ hasRequestedPersist = true;
96
+ void persist(existing).catch(() => {
97
+ /* optimistic client-side prolong above still covers this session */
98
+ });
99
+ }
100
+ },
101
+ };
102
+ }
@@ -0,0 +1,27 @@
1
+ import type { ConsentCategory } from "#/core/consent";
2
+
3
+ /**
4
+ * The consent constants every surface must agree on. The React hooks, the client
5
+ * tracker gate, and the pre-hydration tag bootstrap all accept this object, so the
6
+ * cross-surface "must match" contracts hold by construction instead of by hand-threading
7
+ * the same strings through every call site.
8
+ *
9
+ * @since 1.0.0-canary.6
10
+ */
11
+ export interface ConsentConfig {
12
+ /** Bumping re-prompts every visitor — a stored decision under any other version is ignored. */
13
+ policyVersion: string;
14
+ /** Purposes the app's prompt asks about — `grantAll` and opt-out defaults grant exactly these. */
15
+ requestedCategories: ReadonlyArray<ConsentCategory>;
16
+ /** `localStorage` key holding the visitor's `ConsentRecord`. */
17
+ storageKey: string;
18
+ }
19
+
20
+ /**
21
+ * Identity helper for declaring the config with inference — `defineEventCatalog`'s consent twin.
22
+ *
23
+ * @since 1.0.0-canary.6
24
+ */
25
+ export function defineConsentConfig<Config extends ConsentConfig>(config: Config): Config {
26
+ return config;
27
+ }
@@ -0,0 +1,115 @@
1
+ import type { ConsentDecision } from "#/core/consent";
2
+ import { isConsentDecision } from "#/core/consent";
3
+
4
+ /**
5
+ * Which consent event a receipt records. Receipts are append-only: an `update` or
6
+ * `withdraw` is a new receipt referencing the prior one, never a mutation.
7
+ *
8
+ * @since 1.0.0-canary.7
9
+ */
10
+ export type ConsentReceiptEventType = "give" | "update" | "withdraw";
11
+
12
+ /**
13
+ * How the decision was expressed — the "how" dimension a demonstrable-consent record must
14
+ * capture (GDPR Art. 7(1); EDPB 05/2020 §5.1). See spec/spec-consent-receipts.md.
15
+ *
16
+ * @since 1.0.0-canary.7
17
+ */
18
+ export type ConsentReceiptMethod = "banner-accept" | "banner-reject" | "granular" | "gpc-signal" | "withdrawal";
19
+
20
+ /**
21
+ * What kind of identifier links the receipt to a subject. A cookie-only visitor uses a
22
+ * pseudonymous `cookie` id — the receipt is still valid proof.
23
+ *
24
+ * @since 1.0.0-canary.7
25
+ */
26
+ export type ConsentReceiptSubjectIdType = "cookie" | "email-hash" | "userId";
27
+
28
+ /**
29
+ * The caller-supplied fields of a consent receipt. Deliberately carries **no IP** — the
30
+ * server derives a coarsened one from the connection so a full IP never transits the body.
31
+ *
32
+ * @since 1.0.0-canary.7
33
+ */
34
+ export interface ConsentReceiptInput {
35
+ decision: ConsentDecision;
36
+ eventType: ConsentReceiptEventType;
37
+ method: ConsentReceiptMethod;
38
+ /** BCP-47 language of the notice the subject was shown. */
39
+ noticeLanguage: string;
40
+ /** Version the stored notice snapshot resolves to — EDPB para 108's "copy of the information presented". */
41
+ noticeVersion: string;
42
+ policyVersion: string;
43
+ subjectId: string;
44
+ subjectIdType: ConsentReceiptSubjectIdType;
45
+ /** The prior receipt this update/withdrawal supersedes — the append-only chain link. */
46
+ supersedesReceiptId?: string | undefined;
47
+ }
48
+
49
+ /**
50
+ * A stored consent receipt: the caller input plus server-derived fields. This is the
51
+ * legally-authoritative record of proof — the client `ConsentRecord` is only a runtime
52
+ * cache (spec-consent-receipts §5).
53
+ *
54
+ * @remarks
55
+ * The record is append-only; never mutate a stored receipt. `ipCoarse` is truncated at
56
+ * write time and MUST NOT be a full IP.
57
+ *
58
+ * @since 1.0.0-canary.7
59
+ */
60
+ export interface ConsentReceipt extends ConsentReceiptInput {
61
+ /** Coarsened/pseudonymized IP, or absent — never a full address. */
62
+ ipCoarse?: string | undefined;
63
+ /** Optional tamper-evidence signature, present only when a signer was supplied. */
64
+ integrityKey?: string | undefined;
65
+ receiptId: string;
66
+ schemaVersion: string;
67
+ /** Milliseconds since the Unix epoch, from the server clock. */
68
+ timestamp: number;
69
+ }
70
+
71
+ function isString(value: unknown): value is string {
72
+ return typeof value === "string";
73
+ }
74
+
75
+ const RECEIPT_METHODS: ReadonlySet<ConsentReceiptMethod> = new Set([
76
+ "banner-accept",
77
+ "banner-reject",
78
+ "granular",
79
+ "gpc-signal",
80
+ "withdrawal",
81
+ ]);
82
+
83
+ const RECEIPT_SUBJECT_ID_TYPES: ReadonlySet<ConsentReceiptSubjectIdType> = new Set(["cookie", "email-hash", "userId"]);
84
+
85
+ /**
86
+ * Guards a receipt input received from an untrusted client. Rejects a body carrying an
87
+ * `ip`/`ipCoarse` field so a full address can never be persisted from caller input.
88
+ *
89
+ * @since 1.0.0-canary.7
90
+ */
91
+ export function isConsentReceiptInput(value: unknown): value is ConsentReceiptInput {
92
+ if (typeof value !== "object" || value === null) {
93
+ return false;
94
+ }
95
+
96
+ const input = value as Record<string, unknown>;
97
+
98
+ // A client MUST NOT supply IP — the server derives it. Presence is an integrity red flag.
99
+ if ("ip" in input || "ipCoarse" in input) {
100
+ return false;
101
+ }
102
+
103
+ return (
104
+ isConsentDecision(input.decision) &&
105
+ (input.eventType === "give" || input.eventType === "update" || input.eventType === "withdraw") &&
106
+ isString(input.method) &&
107
+ RECEIPT_METHODS.has(input.method as ConsentReceiptMethod) &&
108
+ isString(input.noticeLanguage) &&
109
+ isString(input.noticeVersion) &&
110
+ isString(input.policyVersion) &&
111
+ isString(input.subjectId) &&
112
+ isString(input.subjectIdType) &&
113
+ RECEIPT_SUBJECT_ID_TYPES.has(input.subjectIdType as ConsentReceiptSubjectIdType)
114
+ );
115
+ }