@codefast/tracking 1.0.0-canary.6 → 1.0.0-canary.7

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 (267) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +72 -17
  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.mts → browser-cookie.d.ts} +2 -4
  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} +3 -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.mts → gpc.d.ts} +2 -4
  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.mts → consent.d.ts} +49 -51
  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.mts → cookie.d.ts} +3 -5
  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.mts → event-id.d.ts} +2 -4
  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.mts → use-initial-consent.d.ts} +3 -6
  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.mts → region.d.ts} +5 -15
  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 +238 -59
  172. package/src/adapters/tanstack-start.ts +135 -0
  173. package/src/client/ad-framework-consent.ts +86 -0
  174. package/src/client/cookie-anonymous-id.ts +19 -0
  175. package/src/client/create-client-tracker.ts +81 -10
  176. package/src/client/server-persisted-anonymous-id.ts +4 -1
  177. package/src/core/consent-receipt.ts +115 -0
  178. package/src/core/consent.ts +2 -2
  179. package/src/core/destination.ts +7 -0
  180. package/src/core/event-catalog.ts +5 -4
  181. package/src/core/tracked-event.ts +5 -20
  182. package/src/destinations/ad-consent.ts +29 -0
  183. package/src/destinations/meta.ts +96 -0
  184. package/src/destinations/microsoft-uet.ts +86 -0
  185. package/src/destinations/tiktok.ts +85 -0
  186. package/src/index.ts +138 -19
  187. package/src/server/anonymous-id-cookie.ts +49 -22
  188. package/src/server/consent-receipt-store.ts +79 -0
  189. package/src/server/consent-receipt.ts +89 -0
  190. package/src/server/initial-consent.ts +0 -2
  191. package/src/server/measurement-protocol.ts +114 -0
  192. package/src/server/region.ts +0 -10
  193. package/src/server/user-deletion.ts +93 -0
  194. package/src/tooling/import-protection.ts +22 -0
  195. package/dist/client/browser-cookie.mjs +0 -15
  196. package/dist/client/consent-runtime.d.mts +0 -56
  197. package/dist/client/consent-runtime.mjs +0 -35
  198. package/dist/client/consent-storage.mjs +0 -82
  199. package/dist/client/consent-withdrawal.d.mts +0 -21
  200. package/dist/client/consent-withdrawal.mjs +0 -17
  201. package/dist/client/cookie-anonymous-id.d.mts +0 -37
  202. package/dist/client/cookie-anonymous-id.mjs +0 -46
  203. package/dist/client/create-client-tracker.d.mts +0 -32
  204. package/dist/client/create-client-tracker.mjs +0 -40
  205. package/dist/client/gpc.mjs +0 -14
  206. package/dist/client/index.d.mts +0 -10
  207. package/dist/client/index.mjs +0 -10
  208. package/dist/client/initial-consent-store.d.mts +0 -66
  209. package/dist/client/initial-consent-store.mjs +0 -119
  210. package/dist/client/is-analytics-allowed.d.mts +0 -29
  211. package/dist/client/is-analytics-allowed.mjs +0 -23
  212. package/dist/client/server-persisted-anonymous-id.d.mts +0 -33
  213. package/dist/client/server-persisted-anonymous-id.mjs +0 -50
  214. package/dist/core/consent-config.d.mts +0 -27
  215. package/dist/core/consent-config.mjs +0 -11
  216. package/dist/core/consent.mjs +0 -152
  217. package/dist/core/cookie.mjs +0 -23
  218. package/dist/core/destination.d.mts +0 -25
  219. package/dist/core/destination.mjs +0 -1
  220. package/dist/core/event-catalog.d.mts +0 -39
  221. package/dist/core/event-catalog.mjs +0 -30
  222. package/dist/core/event-id.mjs +0 -11
  223. package/dist/core/index.d.mts +0 -8
  224. package/dist/core/index.mjs +0 -6
  225. package/dist/core/tracked-event.d.mts +0 -30
  226. package/dist/core/tracked-event.mjs +0 -1
  227. package/dist/destinations/google-analytics.d.mts +0 -150
  228. package/dist/destinations/google-analytics.mjs +0 -130
  229. package/dist/destinations/google-consent.d.mts +0 -64
  230. package/dist/destinations/google-consent.mjs +0 -102
  231. package/dist/destinations/index.d.mts +0 -2
  232. package/dist/destinations/index.mjs +0 -2
  233. package/dist/destinations/shared.d.mts +0 -20
  234. package/dist/destinations/shared.mjs +0 -13
  235. package/dist/destinations/vercel-analytics.d.mts +0 -28
  236. package/dist/destinations/vercel-analytics.mjs +0 -23
  237. package/dist/import-protection.d.mts +0 -19
  238. package/dist/import-protection.mjs +0 -23
  239. package/dist/index.d.mts +0 -8
  240. package/dist/index.mjs +0 -6
  241. package/dist/react/consent-banner.d.mts +0 -180
  242. package/dist/react/consent-banner.mjs +0 -214
  243. package/dist/react/gtag-consent-bootstrap.d.mts +0 -27
  244. package/dist/react/gtag-consent-bootstrap.mjs +0 -29
  245. package/dist/react/index.d.mts +0 -6
  246. package/dist/react/index.mjs +0 -6
  247. package/dist/react/use-consent.d.mts +0 -45
  248. package/dist/react/use-consent.mjs +0 -71
  249. package/dist/react/use-google-consent-sync.d.mts +0 -23
  250. package/dist/react/use-google-consent-sync.mjs +0 -24
  251. package/dist/react/use-initial-consent.mjs +0 -19
  252. package/dist/server/anonymous-id-cookie.d.mts +0 -46
  253. package/dist/server/anonymous-id-cookie.mjs +0 -51
  254. package/dist/server/index.d.mts +0 -5
  255. package/dist/server/index.mjs +0 -4
  256. package/dist/server/initial-consent.d.mts +0 -29
  257. package/dist/server/initial-consent.mjs +0 -31
  258. package/dist/server/region.mjs +0 -77
  259. package/dist/tanstack-start/index.d.mts +0 -58
  260. package/dist/tanstack-start/index.mjs +0 -45
  261. package/src/client/index.ts +0 -28
  262. package/src/core/index.ts +0 -40
  263. package/src/destinations/index.ts +0 -19
  264. package/src/import-protection.ts +0 -20
  265. package/src/react/index.ts +0 -37
  266. package/src/server/index.ts +0 -16
  267. package/src/tanstack-start/index.ts +0 -83
@@ -0,0 +1,86 @@
1
+ import type { ConsentCategory, ConsentDecision } from "#/core/consent";
2
+
3
+ /**
4
+ * TCF/GPP interop reconciler (spec-ad-consent-frameworks): the system **reads** an external
5
+ * CMP and reconciles it with the native `{ ads, analytics }` decision — it never becomes a
6
+ * CMP, mints TC/GPP strings, or hard-codes TCF purpose ids or the Google vendor id (that
7
+ * mapping is ad-ops policy, so the caller derives `CmpConsentSignal` and passes it in).
8
+ */
9
+
10
+ /**
11
+ * Liveness of a detected CMP. `"out-of-scope"` is TCF `gdprApplies === false` / no applicable
12
+ * GPP section — the framework does not govern this user, so native consent stands.
13
+ *
14
+ * @since 1.0.0-canary.7
15
+ */
16
+ export type CmpStatus = "loading" | "out-of-scope" | "ready";
17
+
18
+ /**
19
+ * A CMP's governance over the native decision, already derived from TCData/GPP by ad-ops policy.
20
+ *
21
+ * @since 1.0.0-canary.7
22
+ */
23
+ export interface CmpConsentSignal {
24
+ /** Per-governed-category grant, read once `status` is `"ready"`. */
25
+ decision?: Partial<ConsentDecision> | undefined;
26
+ /** Categories this CMP governs in the current scope — the resolver overrides only these. */
27
+ governs: ReadonlyArray<ConsentCategory>;
28
+ status: CmpStatus;
29
+ }
30
+
31
+ /**
32
+ * @since 1.0.0-canary.7
33
+ */
34
+ export interface ReconcileAdFrameworkConsentOptions {
35
+ /** The live CMP signal, or omitted when no CMP is present (the resolver is then inert). */
36
+ cmp?: CmpConsentSignal | undefined;
37
+ /** Native GPC — can only tighten `ads`, never loosen a CMP grant. */
38
+ hasGlobalPrivacyControlSignal: boolean;
39
+ /** The stored/default decision that stands wherever no CMP governs. */
40
+ native: ConsentDecision;
41
+ }
42
+
43
+ /**
44
+ * Reconciles native consent with a CMP source of truth per spec-ad-consent-frameworks §3:
45
+ * a governing CMP overrides its categories (fail-closed to denied while loading); a missing
46
+ * or out-of-scope CMP leaves native standing; GPC always tightens `ads` last.
47
+ *
48
+ * @since 1.0.0-canary.7
49
+ */
50
+ export function reconcileAdFrameworkConsent(options: ReconcileAdFrameworkConsentOptions): ConsentDecision {
51
+ const result: ConsentDecision = { ...options.native };
52
+ const { cmp } = options;
53
+
54
+ // A governing CMP overrides only the categories it governs; no CMP / out-of-scope leaves native.
55
+ if (cmp && cmp.status !== "out-of-scope") {
56
+ for (const category of cmp.governs) {
57
+ // Fail closed until the CMP resolves; otherwise the CMP value wins for its categories.
58
+ result[category] = cmp.status === "loading" ? false : (cmp.decision?.[category] ?? false);
59
+ }
60
+ }
61
+
62
+ // GPC can only tighten `ads` — applied last so it wins over any CMP grant.
63
+ if (options.hasGlobalPrivacyControlSignal) {
64
+ result.ads = false;
65
+ }
66
+
67
+ return result;
68
+ }
69
+
70
+ /**
71
+ * Detects a TCF CMP without reading it — `typeof __tcfapi === "function"` (spec §3).
72
+ *
73
+ * @since 1.0.0-canary.7
74
+ */
75
+ export function hasTcfApi(scope: { __tcfapi?: unknown } = globalThis as { __tcfapi?: unknown }): boolean {
76
+ return typeof scope.__tcfapi === "function";
77
+ }
78
+
79
+ /**
80
+ * Detects a GPP CMP without reading it — `typeof __gpp === "function"` (spec §3).
81
+ *
82
+ * @since 1.0.0-canary.7
83
+ */
84
+ export function hasGppApi(scope: { __gpp?: unknown } = globalThis as { __gpp?: unknown }): boolean {
85
+ return typeof scope.__gpp === "function";
86
+ }
@@ -17,6 +17,12 @@ export interface CookieAnonymousIdOptions {
17
17
  export interface CookieAnonymousId {
18
18
  /** Expires the cookie — call when the visitor withdraws tracking consent. */
19
19
  clear: () => void;
20
+ /**
21
+ * The existing id **without minting one** — `undefined` when the visitor has none yet.
22
+ * Use this to stamp a receipt/decision with the id that already identifies the visitor,
23
+ * rather than re-reading the cookie or minting a throwaway that never correlates.
24
+ */
25
+ current: () => string | undefined;
20
26
  /** The existing id, or a freshly minted and persisted one. */
21
27
  getOrCreate: () => string;
22
28
  /**
@@ -52,6 +58,19 @@ export function createCookieAnonymousId(options: CookieAnonymousIdOptions): Cook
52
58
 
53
59
  writeBrowserCookie(cookieName, "", 0);
54
60
  },
61
+ current(): string | undefined {
62
+ // Prefer the live cookie — another tab may have minted or cleared it since this
63
+ // instance last cached — falling back to the cache only when off the DOM (SSR).
64
+ if (typeof document === "undefined") {
65
+ return cachedId;
66
+ }
67
+
68
+ const existing = readCookieValue(document.cookie, cookieName);
69
+
70
+ cachedId = existing;
71
+
72
+ return existing;
73
+ },
55
74
  getOrCreate(): string {
56
75
  if (typeof document === "undefined") {
57
76
  return cachedId ?? crypto.randomUUID();
@@ -6,21 +6,58 @@ import { assertValidEventProperties } from "#/core/event-catalog";
6
6
  import { generateEventId } from "#/core/event-id";
7
7
  import type { TrackedEvent } from "#/core/tracked-event";
8
8
 
9
+ /**
10
+ * Context handed to {@link ClientTrackerOptions.onDeliveryError} for one failed delivery.
11
+ *
12
+ * @since 1.0.0-canary.7
13
+ */
14
+ export interface DeliveryErrorContext {
15
+ destination: Destination;
16
+ error: unknown;
17
+ event: TrackedEvent;
18
+ }
19
+
9
20
  /**
10
21
  * `Destination.send` is typed to always return a `Promise`, but that's unenforceable at
11
22
  * runtime for a third-party/plain-JS destination — one that ignores the contract and
12
23
  * throws synchronously (or returns a non-`Promise`) must still never break the tracked
13
24
  * interaction. `Promise.resolve(...)` normalizes a non-`Promise` return; the outer
14
25
  * try/catch is the only thing that can catch a throw that happens before `send` ever
15
- * gets to return anything.
26
+ * gets to return anything. Both failure shapes surface through `onDeliveryError` (itself
27
+ * guarded — an observer that throws must not break the interaction either).
16
28
  */
17
- function sendToDestination(destination: Destination, event: TrackedEvent): void {
29
+ function sendToDestination(
30
+ destination: Destination,
31
+ event: TrackedEvent,
32
+ onDeliveryError?: (context: DeliveryErrorContext) => void,
33
+ ): void {
34
+ const report = (error: unknown): void => {
35
+ if (!onDeliveryError) {
36
+ return;
37
+ }
38
+
39
+ try {
40
+ onDeliveryError({ destination, error, event });
41
+ } catch {
42
+ /* an observer must never break the tracked interaction */
43
+ }
44
+ };
45
+
46
+ try {
47
+ void Promise.resolve(destination.send(event)).catch(report);
48
+ } catch (error) {
49
+ report(error);
50
+ }
51
+ }
52
+
53
+ /** Invokes a destination's erasure once, swallowing both failure shapes — DSR must never break the flow. */
54
+ function eraseInDestination(destination: Destination, id: string): void {
18
55
  try {
19
- void Promise.resolve(destination.send(event)).catch(() => {
20
- /* a destination owns its transport — tracking must never break the interaction */
56
+ void Promise.resolve(destination.onErasure?.(id)).catch(() => {
57
+ /* an erasure failure must never break the withdrawal flow */
21
58
  });
22
59
  } catch {
23
- /* a sync throw must never break the tracked interaction */
60
+ /* a sync throw must never break the withdrawal flow */
24
61
  }
25
62
  }
26
63
 
@@ -38,12 +75,32 @@ export interface ClientTrackerOptions<Catalog extends EventCatalog> {
38
75
  * identifiers. Omit to always track.
39
76
  */
40
77
  isAnalyticsAllowed?: (() => boolean) | undefined;
78
+ /**
79
+ * Consulted before an `exempt` destination receives an event while the gate is closed.
80
+ * ePrivacy audience-measurement exemption is jurisdiction-dependent (spec-destinations
81
+ * §2), so it MUST be gateable per region rather than assumed global — return `false`
82
+ * where exemption is not defensible and even exempt sinks are withheld. Omit to treat
83
+ * exempt destinations as exempt everywhere.
84
+ */
85
+ isExemptionAllowed?: (() => boolean) | undefined;
86
+ /**
87
+ * Notified once per failed delivery (a destination throwing or rejecting) so a consumer
88
+ * can meter the failure — the tracker still swallows it so tracking never breaks the
89
+ * interaction. Wire it to a monitor in production.
90
+ */
91
+ onDeliveryError?: ((context: DeliveryErrorContext) => void) | undefined;
41
92
  }
42
93
 
43
94
  /**
44
95
  * @since 0.5.0-canary.4
45
96
  */
46
97
  export interface ClientTracker<Catalog extends EventCatalog> {
98
+ /**
99
+ * Runs each destination's {@link Destination.onErasure} once on withdrawal (spec-data-subject-rights
100
+ * DSR-V2), passing the subject id to erase. Failures are swallowed so a destination that
101
+ * throws never breaks the withdrawal flow.
102
+ */
103
+ erase: (id: string) => void;
47
104
  track: <Name extends keyof Catalog & string>(
48
105
  name: Name,
49
106
  properties: StandardSchemaV1.InferOutput<Catalog[Name]["schema"]>,
@@ -60,6 +117,11 @@ export function createClientTracker<Catalog extends EventCatalog>(
60
117
  const exemptDestinations = options.destinations.filter((destination) => destination.consentRequirement === "exempt");
61
118
 
62
119
  return {
120
+ erase(id) {
121
+ for (const destination of options.destinations) {
122
+ eraseInDestination(destination, id);
123
+ }
124
+ },
63
125
  track(name, properties) {
64
126
  // noUncheckedIndexedAccess types this as possibly undefined; the check also guards
65
127
  // callers who bypass the catalog key type with an `as` cast.
@@ -69,12 +131,21 @@ export function createClientTracker<Catalog extends EventCatalog>(
69
131
  throw new Error(`Unknown event: ${String(name)}`);
70
132
  }
71
133
 
72
- assertValidEventProperties(definition.schema, name, properties);
134
+ // Forward the parsed output (not the raw input) so unknown keys cannot ride along.
135
+ const validatedProperties = assertValidEventProperties(definition.schema, name, properties);
73
136
 
74
137
  // The gate runs per event (not at creation) so a consent change mid-session applies immediately.
75
138
  const isAllowed = options.isAnalyticsAllowed?.() !== false;
76
139
 
77
- if (!isAllowed && exemptDestinations.length === 0) {
140
+ // While gated, exempt sinks still receive identifier-free events — but only where
141
+ // exemption is defensible (spec-destinations §2); a `false` here withholds them too.
142
+ const activeDestinations = isAllowed
143
+ ? options.destinations
144
+ : options.isExemptionAllowed?.() === false
145
+ ? []
146
+ : exemptDestinations;
147
+
148
+ if (activeDestinations.length === 0) {
78
149
  return;
79
150
  }
80
151
 
@@ -84,13 +155,13 @@ export function createClientTracker<Catalog extends EventCatalog>(
84
155
  anonymousId: isAllowed ? options.anonymousId() : "",
85
156
  eventId: generateEventId(),
86
157
  name,
87
- properties: properties as Record<string, unknown>,
158
+ properties: validatedProperties as Record<string, unknown>,
88
159
  timestamp: Date.now(),
89
160
  type: "track",
90
161
  };
91
162
 
92
- for (const destination of isAllowed ? options.destinations : exemptDestinations) {
93
- sendToDestination(destination, event);
163
+ for (const destination of activeDestinations) {
164
+ sendToDestination(destination, event, options.onDeliveryError);
94
165
  }
95
166
  },
96
167
  };
@@ -14,7 +14,7 @@ export interface ServerPersistedAnonymousIdOptions {
14
14
  maxAgeSeconds?: number | undefined;
15
15
  /**
16
16
  * Server round-trip that re-sets the cookie via `Set-Cookie` (e.g. a server function
17
- * calling `buildAnonymousIdSetCookie`). Fired at most once per page load, only after an
17
+ * calling `setAnonymousIdResponseCookie`). Fired at most once per page load, only after an
18
18
  * id exists client-side — the server persists and prolongs, it never mints.
19
19
  */
20
20
  persist: (id: string) => Promise<void>;
@@ -54,6 +54,9 @@ export function createServerPersistedAnonymousId(options: ServerPersistedAnonymo
54
54
  });
55
55
  }
56
56
  },
57
+ current(): string | undefined {
58
+ return local.current();
59
+ },
57
60
  getOrCreate(): string {
58
61
  // Cross-tab withdrawal expires the cookie without this instance's `clear()` — reset
59
62
  // so the next minted id is server-persisted (ITP re-issue) again.
@@ -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
+ }
@@ -89,8 +89,8 @@ export function isConsentDecision(value: unknown): value is ConsentDecision {
89
89
 
90
90
  /**
91
91
  * Re-derives a clean per-category decision from a tamperable record — extra keys are
92
- * dropped, every category becomes an explicit boolean. The one normalization rule shared
93
- * by the client (`readStoredDecision`) and server (`readConsentDecisionCookie`) mirrors.
92
+ * dropped, every category becomes an explicit boolean. The one normalization rule every
93
+ * reader of stored consent shares (e.g. `readStoredDecision`).
94
94
  *
95
95
  * @since 1.0.0-canary.6
96
96
  */
@@ -17,6 +17,13 @@ export interface Destination {
17
17
  */
18
18
  consentRequirement?: "exempt" | "required" | undefined;
19
19
  name: string;
20
+ /**
21
+ * Erase this destination's trace of the subject on withdrawal (spec-data-subject-rights
22
+ * §3): clear the destination's cookies and stop sending, and — where the platform offers
23
+ * one — request per-visitor deletion. Optional: a sink with nothing to erase omits it.
24
+ * Invoked at most once per withdrawal; the tracker swallows its failures.
25
+ */
26
+ onErasure?: ((id: string) => Promise<void> | void) | undefined;
20
27
  /** Must always return a `Promise` — mark `send` `async` even if the body has no `await`. */
21
28
  send: (event: TrackedEvent) => Promise<void>;
22
29
  }
@@ -29,16 +29,15 @@ export function defineEventCatalog<Catalog extends EventCatalog>(catalog: Catalo
29
29
  }
30
30
 
31
31
  /**
32
- * Validates event properties against the catalog schema and throws on mismatch. The
33
- * validated (possibly transformed) value is deliberately discarded — the tracker always
34
- * sends the caller's original properties, so a schema transform can never desync callers.
32
+ * Validates event properties against the catalog schema and returns the parsed output
33
+ * (unknown keys stripped / transforms applied) so destinations never see raw input.
35
34
  *
36
35
  * @throws Error when validation reports issues, or when the schema validates asynchronously —
37
36
  * tracking sits on synchronous call paths, so async schemas are unsupported by design.
38
37
  *
39
38
  * @since 1.0.0-canary.6
40
39
  */
41
- export function assertValidEventProperties(schema: StandardSchemaV1, eventName: string, properties: unknown): void {
40
+ export function assertValidEventProperties(schema: StandardSchemaV1, eventName: string, properties: unknown): unknown {
42
41
  const result = schema["~standard"].validate(properties);
43
42
 
44
43
  if (result instanceof Promise) {
@@ -50,4 +49,6 @@ export function assertValidEventProperties(schema: StandardSchemaV1, eventName:
50
49
 
51
50
  throw new Error(`Invalid properties for event "${eventName}": ${detail}`);
52
51
  }
52
+
53
+ return result.value;
53
54
  }
@@ -1,29 +1,14 @@
1
1
  /**
2
- * Fields shared by every envelope the tracker builds.
2
+ * The event envelope destinations receive. `type` stays a discriminant so a future envelope
3
+ * kind is an additive union member, not a wire-format break.
3
4
  *
4
- * @since 1.0.0-canary.6
5
+ * @since 0.5.0-canary.4
5
6
  */
6
- export interface TrackedEventBase {
7
+ export interface TrackedEvent {
7
8
  anonymousId: string;
8
9
  eventId: string;
9
- timestamp: number;
10
- }
11
-
12
- /**
13
- * A catalog-defined event envelope, as handed to destinations.
14
- *
15
- * @since 1.0.0-canary.6
16
- */
17
- export interface TrackEvent extends TrackedEventBase {
18
10
  name: string;
19
11
  properties: Record<string, unknown>;
12
+ timestamp: number;
20
13
  type: "track";
21
14
  }
22
-
23
- /**
24
- * The envelope destinations receive. `type` stays a discriminant so a future kind is an
25
- * additive union member, not a wire-format break.
26
- *
27
- * @since 0.5.0-canary.4
28
- */
29
- export type TrackedEvent = TrackEvent;
@@ -0,0 +1,29 @@
1
+ import type { ConsentDecision } from "#/core/consent";
2
+
3
+ /**
4
+ * The normalized two-lever ad-platform consent state derived from one `{ ads, analytics }`
5
+ * decision (spec-destinations §5): `analytics` drives whether events transmit at all, and
6
+ * `ads` drives Limited Data Use. The levers are independent — a US opt-out (`ads: false`)
7
+ * restricts to LDU but MUST NOT withhold first-party `analytics` (spec-consent §3). Every
8
+ * ad destination consumes this same shape so per-vendor mappings cannot drift.
9
+ *
10
+ * @since 1.0.0-canary.7
11
+ */
12
+ export interface AdConsentState {
13
+ /** `ads` denied → the platform must restrict to Limited Data Use (Meta/TikTok LDU, UET `ad_storage` denied). */
14
+ limitedDataUse: boolean;
15
+ /** `analytics` granted → events may transmit; denied → hold/revoke and send nothing. */
16
+ transmissionAllowed: boolean;
17
+ }
18
+
19
+ /**
20
+ * Normalizes a package `ConsentDecision` to the vendor-agnostic {@link AdConsentState}.
21
+ *
22
+ * @since 1.0.0-canary.7
23
+ */
24
+ export function toAdConsentState(decision: ConsentDecision): AdConsentState {
25
+ return {
26
+ limitedDataUse: !decision.ads,
27
+ transmissionAllowed: decision.analytics,
28
+ };
29
+ }
@@ -0,0 +1,96 @@
1
+ import type { ConsentDecision } from "#/core/consent";
2
+ import type { Destination } from "#/core/destination";
3
+ import { toAdConsentState } from "#/destinations/ad-consent";
4
+ import type { FlatPropertyValue } from "#/destinations/shared";
5
+ import { flattenEventProps } from "#/destinations/shared";
6
+
7
+ /**
8
+ * Meta's `dataProcessingOptions` restriction. `['LDU'], 0, 0` turns on Limited Data Use and
9
+ * lets Meta geolocate the user — the recommended default beyond California, where only
10
+ * country `1` (USA) / state `1000` (California) are documented codes (spec-destinations §5).
11
+ * `[]` applies no restriction.
12
+ *
13
+ * @since 1.0.0-canary.7
14
+ */
15
+ export interface MetaDataProcessingOptions {
16
+ country: number;
17
+ options: ReadonlyArray<string>;
18
+ state: number;
19
+ }
20
+
21
+ /**
22
+ * Maps a `ConsentDecision` to Meta's `dataProcessingOptions`: LDU when `ads` is denied.
23
+ *
24
+ * @since 1.0.0-canary.7
25
+ */
26
+ export function toMetaDataProcessingOptions(decision: ConsentDecision): MetaDataProcessingOptions {
27
+ return toAdConsentState(decision).limitedDataUse
28
+ ? { country: 0, options: ["LDU"], state: 0 }
29
+ : { country: 0, options: [], state: 0 };
30
+ }
31
+
32
+ /**
33
+ * The mapped per-event payload handed to a Meta transport (Pixel `fbq` or a CAPI request).
34
+ *
35
+ * @since 1.0.0-canary.7
36
+ */
37
+ export interface MetaEventPayload {
38
+ dataProcessingOptions: MetaDataProcessingOptions;
39
+ name: string;
40
+ properties: Record<string, FlatPropertyValue>;
41
+ }
42
+
43
+ /**
44
+ * @since 1.0.0-canary.7
45
+ */
46
+ export interface MetaDestinationOptions {
47
+ /**
48
+ * Erasure cookie-clear seam — invoked by `onErasure` to drop Meta's `_fbp`/`_fbc` cookies
49
+ * (spec-data-subject-rights DSR-V4). Meta exposes no per-visitor deletion API, so erasure
50
+ * is cookie-clear + stop-send only. Omit if the integrator clears cookies elsewhere.
51
+ */
52
+ clearCookies?: (() => void) | undefined;
53
+ /** Read per event so an `ads` change restricts data use without recreating the destination. */
54
+ getDecision: () => ConsentDecision;
55
+ name?: string | undefined;
56
+ /**
57
+ * Delivers one mapped event — the transport seam. Wire it to `fbq(...)` (Pixel) or a
58
+ * Conversions API request; this package ships the consent mapping, never the credentials
59
+ * or network client.
60
+ */
61
+ transport: (payload: MetaEventPayload) => Promise<void> | void;
62
+ }
63
+
64
+ /**
65
+ * Reference ad destination: maps each event to Meta's shape and applies Limited Data Use
66
+ * from the live `ads` decision (spec-destinations §5), then hands it to an injected
67
+ * transport. Consent-restriction mapping only — the Pixel/CAPI transport and credentials
68
+ * are the integrator's to supply. `consentRequirement` stays `"required"`: an ad sink is
69
+ * never exempt.
70
+ *
71
+ * @since 1.0.0-canary.7
72
+ */
73
+ export function createMetaDestination(options: MetaDestinationOptions): Destination {
74
+ // Erasure halts delivery for the rest of the session — Meta has no per-visitor deletion API.
75
+ let stopped = false;
76
+
77
+ return {
78
+ consentRequirement: "required",
79
+ name: options.name ?? "meta",
80
+ onErasure() {
81
+ stopped = true;
82
+ options.clearCookies?.();
83
+ },
84
+ async send(event) {
85
+ if (stopped) {
86
+ return;
87
+ }
88
+
89
+ await options.transport({
90
+ dataProcessingOptions: toMetaDataProcessingOptions(options.getDecision()),
91
+ name: event.name,
92
+ properties: flattenEventProps(event.properties),
93
+ });
94
+ },
95
+ };
96
+ }