@codefast/tracking 0.7.1 → 0.7.3

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 +49 -0
  2. package/LICENSE +1 -1
  3. package/README.md +235 -105
  4. package/dist/adapters/tanstack-start.d.ts +5 -6
  5. package/dist/adapters/tanstack-start.js +5 -6
  6. package/dist/client/ad-framework-consent.d.ts +2 -3
  7. package/dist/client/ad-framework-consent.js +1 -2
  8. package/dist/client/browser-cookie.d.ts +1 -2
  9. package/dist/client/browser-cookie.js +1 -2
  10. package/dist/client/consent-runtime.d.ts +4 -5
  11. package/dist/client/consent-runtime.js +5 -6
  12. package/dist/client/consent-storage.d.ts +2 -3
  13. package/dist/client/consent-storage.js +2 -3
  14. package/dist/client/consent-withdrawal.d.ts +2 -3
  15. package/dist/client/consent-withdrawal.js +1 -2
  16. package/dist/client/cookie-anonymous-id.d.ts +1 -2
  17. package/dist/client/cookie-anonymous-id.js +3 -4
  18. package/dist/client/create-client-tracker.d.ts +4 -5
  19. package/dist/client/create-client-tracker.js +3 -4
  20. package/dist/client/gpc.d.ts +1 -2
  21. package/dist/client/gpc.js +1 -2
  22. package/dist/client/initial-consent-store.d.ts +2 -3
  23. package/dist/client/initial-consent-store.js +2 -3
  24. package/dist/client/is-analytics-allowed.d.ts +3 -4
  25. package/dist/client/is-analytics-allowed.js +2 -3
  26. package/dist/client/server-persisted-anonymous-id.d.ts +2 -3
  27. package/dist/client/server-persisted-anonymous-id.js +3 -4
  28. package/dist/core/consent-config.d.ts +2 -3
  29. package/dist/core/consent-config.js +1 -2
  30. package/dist/core/consent-receipt.d.ts +2 -3
  31. package/dist/core/consent-receipt.js +2 -3
  32. package/dist/core/consent.d.ts +1 -2
  33. package/dist/core/consent.js +1 -2
  34. package/dist/core/cookie.d.ts +1 -2
  35. package/dist/core/cookie.js +1 -2
  36. package/dist/core/destination.d.ts +2 -3
  37. package/dist/core/destination.js +1 -2
  38. package/dist/core/event-catalog.d.ts +1 -2
  39. package/dist/core/event-catalog.js +1 -2
  40. package/dist/core/event-id.d.ts +1 -2
  41. package/dist/core/event-id.js +1 -2
  42. package/dist/core/tracked-event.d.ts +1 -2
  43. package/dist/core/tracked-event.js +1 -2
  44. package/dist/destinations/ad-consent.d.ts +2 -3
  45. package/dist/destinations/ad-consent.js +1 -2
  46. package/dist/destinations/google-analytics.d.ts +6 -7
  47. package/dist/destinations/google-analytics.js +3 -4
  48. package/dist/destinations/google-consent.d.ts +2 -3
  49. package/dist/destinations/google-consent.js +2 -3
  50. package/dist/destinations/meta.d.ts +4 -5
  51. package/dist/destinations/meta.js +3 -4
  52. package/dist/destinations/microsoft-uet.d.ts +4 -5
  53. package/dist/destinations/microsoft-uet.js +3 -4
  54. package/dist/destinations/shared.d.ts +1 -2
  55. package/dist/destinations/shared.js +1 -2
  56. package/dist/destinations/tiktok.d.ts +4 -5
  57. package/dist/destinations/tiktok.js +3 -4
  58. package/dist/destinations/vercel-analytics.d.ts +2 -3
  59. package/dist/destinations/vercel-analytics.js +2 -3
  60. package/dist/index.d.ts +49 -50
  61. package/dist/index.js +26 -27
  62. package/dist/react/consent-banner.d.ts +3 -4
  63. package/dist/react/consent-banner.js +1 -2
  64. package/dist/react/gtag-consent-bootstrap.d.ts +2 -3
  65. package/dist/react/gtag-consent-bootstrap.js +2 -3
  66. package/dist/react/use-consent.d.ts +3 -4
  67. package/dist/react/use-consent.js +2 -3
  68. package/dist/react/use-google-consent-sync.d.ts +2 -3
  69. package/dist/react/use-google-consent-sync.js +2 -3
  70. package/dist/react/use-initial-consent.d.ts +2 -3
  71. package/dist/react/use-initial-consent.js +1 -2
  72. package/dist/server/anonymous-id-cookie.d.ts +1 -2
  73. package/dist/server/anonymous-id-cookie.js +2 -3
  74. package/dist/server/consent-receipt-store.d.ts +2 -3
  75. package/dist/server/consent-receipt-store.js +1 -2
  76. package/dist/server/consent-receipt.d.ts +2 -3
  77. package/dist/server/consent-receipt.js +1 -2
  78. package/dist/server/initial-consent.d.ts +2 -3
  79. package/dist/server/initial-consent.js +3 -4
  80. package/dist/server/measurement-protocol.d.ts +2 -3
  81. package/dist/server/measurement-protocol.js +1 -2
  82. package/dist/server/region.d.ts +2 -3
  83. package/dist/server/region.js +1 -2
  84. package/dist/server/user-deletion.d.ts +1 -2
  85. package/dist/server/user-deletion.js +1 -2
  86. package/dist/tooling/import-protection.d.ts +2 -3
  87. package/dist/tooling/import-protection.js +2 -3
  88. package/package.json +5 -94
  89. package/dist/adapters/tanstack-start.d.ts.map +0 -1
  90. package/dist/adapters/tanstack-start.js.map +0 -1
  91. package/dist/client/ad-framework-consent.d.ts.map +0 -1
  92. package/dist/client/ad-framework-consent.js.map +0 -1
  93. package/dist/client/browser-cookie.d.ts.map +0 -1
  94. package/dist/client/browser-cookie.js.map +0 -1
  95. package/dist/client/consent-runtime.d.ts.map +0 -1
  96. package/dist/client/consent-runtime.js.map +0 -1
  97. package/dist/client/consent-storage.d.ts.map +0 -1
  98. package/dist/client/consent-storage.js.map +0 -1
  99. package/dist/client/consent-withdrawal.d.ts.map +0 -1
  100. package/dist/client/consent-withdrawal.js.map +0 -1
  101. package/dist/client/cookie-anonymous-id.d.ts.map +0 -1
  102. package/dist/client/cookie-anonymous-id.js.map +0 -1
  103. package/dist/client/create-client-tracker.d.ts.map +0 -1
  104. package/dist/client/create-client-tracker.js.map +0 -1
  105. package/dist/client/gpc.d.ts.map +0 -1
  106. package/dist/client/gpc.js.map +0 -1
  107. package/dist/client/initial-consent-store.d.ts.map +0 -1
  108. package/dist/client/initial-consent-store.js.map +0 -1
  109. package/dist/client/is-analytics-allowed.d.ts.map +0 -1
  110. package/dist/client/is-analytics-allowed.js.map +0 -1
  111. package/dist/client/server-persisted-anonymous-id.d.ts.map +0 -1
  112. package/dist/client/server-persisted-anonymous-id.js.map +0 -1
  113. package/dist/core/consent-config.d.ts.map +0 -1
  114. package/dist/core/consent-config.js.map +0 -1
  115. package/dist/core/consent-receipt.d.ts.map +0 -1
  116. package/dist/core/consent-receipt.js.map +0 -1
  117. package/dist/core/consent.d.ts.map +0 -1
  118. package/dist/core/consent.js.map +0 -1
  119. package/dist/core/cookie.d.ts.map +0 -1
  120. package/dist/core/cookie.js.map +0 -1
  121. package/dist/core/destination.d.ts.map +0 -1
  122. package/dist/core/destination.js.map +0 -1
  123. package/dist/core/event-catalog.d.ts.map +0 -1
  124. package/dist/core/event-catalog.js.map +0 -1
  125. package/dist/core/event-id.d.ts.map +0 -1
  126. package/dist/core/event-id.js.map +0 -1
  127. package/dist/core/tracked-event.d.ts.map +0 -1
  128. package/dist/core/tracked-event.js.map +0 -1
  129. package/dist/destinations/ad-consent.d.ts.map +0 -1
  130. package/dist/destinations/ad-consent.js.map +0 -1
  131. package/dist/destinations/google-analytics.d.ts.map +0 -1
  132. package/dist/destinations/google-analytics.js.map +0 -1
  133. package/dist/destinations/google-consent.d.ts.map +0 -1
  134. package/dist/destinations/google-consent.js.map +0 -1
  135. package/dist/destinations/meta.d.ts.map +0 -1
  136. package/dist/destinations/meta.js.map +0 -1
  137. package/dist/destinations/microsoft-uet.d.ts.map +0 -1
  138. package/dist/destinations/microsoft-uet.js.map +0 -1
  139. package/dist/destinations/shared.d.ts.map +0 -1
  140. package/dist/destinations/shared.js.map +0 -1
  141. package/dist/destinations/tiktok.d.ts.map +0 -1
  142. package/dist/destinations/tiktok.js.map +0 -1
  143. package/dist/destinations/vercel-analytics.d.ts.map +0 -1
  144. package/dist/destinations/vercel-analytics.js.map +0 -1
  145. package/dist/index.d.ts.map +0 -1
  146. package/dist/index.js.map +0 -1
  147. package/dist/react/consent-banner.d.ts.map +0 -1
  148. package/dist/react/consent-banner.js.map +0 -1
  149. package/dist/react/gtag-consent-bootstrap.d.ts.map +0 -1
  150. package/dist/react/gtag-consent-bootstrap.js.map +0 -1
  151. package/dist/react/use-consent.d.ts.map +0 -1
  152. package/dist/react/use-consent.js.map +0 -1
  153. package/dist/react/use-google-consent-sync.d.ts.map +0 -1
  154. package/dist/react/use-google-consent-sync.js.map +0 -1
  155. package/dist/react/use-initial-consent.d.ts.map +0 -1
  156. package/dist/react/use-initial-consent.js.map +0 -1
  157. package/dist/server/anonymous-id-cookie.d.ts.map +0 -1
  158. package/dist/server/anonymous-id-cookie.js.map +0 -1
  159. package/dist/server/consent-receipt-store.d.ts.map +0 -1
  160. package/dist/server/consent-receipt-store.js.map +0 -1
  161. package/dist/server/consent-receipt.d.ts.map +0 -1
  162. package/dist/server/consent-receipt.js.map +0 -1
  163. package/dist/server/initial-consent.d.ts.map +0 -1
  164. package/dist/server/initial-consent.js.map +0 -1
  165. package/dist/server/measurement-protocol.d.ts.map +0 -1
  166. package/dist/server/measurement-protocol.js.map +0 -1
  167. package/dist/server/region.d.ts.map +0 -1
  168. package/dist/server/region.js.map +0 -1
  169. package/dist/server/user-deletion.d.ts.map +0 -1
  170. package/dist/server/user-deletion.js.map +0 -1
  171. package/dist/tooling/import-protection.d.ts.map +0 -1
  172. package/dist/tooling/import-protection.js.map +0 -1
  173. package/src/adapters/tanstack-start.ts +0 -139
  174. package/src/client/ad-framework-consent.ts +0 -88
  175. package/src/client/browser-cookie.ts +0 -16
  176. package/src/client/consent-runtime.ts +0 -82
  177. package/src/client/consent-storage.ts +0 -125
  178. package/src/client/consent-withdrawal.ts +0 -34
  179. package/src/client/cookie-anonymous-id.ts +0 -116
  180. package/src/client/create-client-tracker.ts +0 -174
  181. package/src/client/gpc.ts +0 -15
  182. package/src/client/initial-consent-store.ts +0 -220
  183. package/src/client/is-analytics-allowed.ts +0 -45
  184. package/src/client/server-persisted-anonymous-id.ts +0 -104
  185. package/src/core/consent-config.ts +0 -27
  186. package/src/core/consent-receipt.ts +0 -115
  187. package/src/core/consent.ts +0 -298
  188. package/src/core/cookie.ts +0 -29
  189. package/src/core/destination.ts +0 -29
  190. package/src/core/event-catalog.ts +0 -54
  191. package/src/core/event-id.ts +0 -8
  192. package/src/core/tracked-event.ts +0 -14
  193. package/src/destinations/ad-consent.ts +0 -29
  194. package/src/destinations/google-analytics.ts +0 -304
  195. package/src/destinations/google-consent.ts +0 -166
  196. package/src/destinations/meta.ts +0 -98
  197. package/src/destinations/microsoft-uet.ts +0 -88
  198. package/src/destinations/shared.ts +0 -51
  199. package/src/destinations/tiktok.ts +0 -87
  200. package/src/destinations/vercel-analytics.ts +0 -41
  201. package/src/index.ts +0 -171
  202. package/src/react/consent-banner.tsx +0 -386
  203. package/src/react/gtag-consent-bootstrap.tsx +0 -50
  204. package/src/react/use-consent.ts +0 -123
  205. package/src/react/use-google-consent-sync.ts +0 -40
  206. package/src/react/use-initial-consent.ts +0 -22
  207. package/src/server/anonymous-id-cookie.ts +0 -105
  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 -48
  211. package/src/server/measurement-protocol.ts +0 -116
  212. package/src/server/region.ts +0 -77
  213. package/src/server/user-deletion.ts +0 -97
  214. package/src/tooling/import-protection.ts +0 -22
@@ -1,104 +0,0 @@
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
- * Options for `createServerPersistedAnonymousId`.
7
- *
8
- * @since 0.5.0-canary.6
9
- */
10
- export interface ServerPersistedAnonymousIdOptions {
11
- /** Server round-trip that expires the cookie via `Set-Cookie` — the server half of `clear()`. */
12
- clearOnServer?: (() => Promise<void>) | undefined;
13
- /** Cookie name — must not collide with another cookie on the domain. */
14
- cookieName: string;
15
- /** How long the id survives a return visit. Defaults to one year. */
16
- maxAgeSeconds?: number | undefined;
17
- /**
18
- * Server round-trip that re-sets the cookie via `Set-Cookie` (e.g. a server function
19
- * calling `setAnonymousIdResponseCookie`). Fired at most once per page load, only after an
20
- * id exists client-side — the server persists and prolongs, it never mints.
21
- */
22
- persist: (id: string) => Promise<void>;
23
- }
24
-
25
- /**
26
- * `createCookieAnonymousId` plus server persistence: the client still mints the id
27
- * (lazily, only once an event is allowed to send — consent stays client-owned), then
28
- * delegates the durable write to the server. A script-written cookie is capped at 7 days
29
- * by Safari ITP; the server's `Set-Cookie` re-issue is what makes the id actually live
30
- * its full max-age. Same optimistic `document.cookie` write first, so the current event
31
- * never waits on the round-trip and a failed `persist` degrades to today's behavior.
32
- *
33
- * @since 0.5.0-canary.6
34
- */
35
- export function createServerPersistedAnonymousId(options: ServerPersistedAnonymousIdOptions): CookieAnonymousId {
36
- const { clearOnServer, cookieName, maxAgeSeconds, persist } = options;
37
- const local = createCookieAnonymousId({ cookieName, maxAgeSeconds });
38
- // One attempt per page load — a failure is not retried until the next load, so a down
39
- // endpoint costs one request, not one per event. Tracking must never break the app.
40
- let hasRequestedPersist = false;
41
-
42
- return {
43
- clear(): void {
44
- // Skip the server round-trip when the cookie is already gone (e.g. a second
45
- // withdrawal clear from another mounted consent surface in the same tick).
46
- const shouldClearServer =
47
- typeof document !== "undefined" && Boolean(readCookieValue(document.cookie, cookieName));
48
-
49
- local.clear();
50
- // A fresh id after a re-grant must be persisted again.
51
- hasRequestedPersist = false;
52
-
53
- if (shouldClearServer) {
54
- void clearOnServer?.().catch(() => {
55
- /* the client-side expiry above already took effect */
56
- });
57
- }
58
- },
59
- current(): string | undefined {
60
- return local.current();
61
- },
62
- getOrCreate(): string {
63
- // Cross-tab withdrawal expires the cookie without this instance's `clear()` — reset
64
- // so the next minted id is server-persisted (ITP re-issue) again.
65
- if (typeof document !== "undefined" && !readCookieValue(document.cookie, cookieName)) {
66
- hasRequestedPersist = false;
67
- }
68
-
69
- const id = local.getOrCreate();
70
-
71
- // Also fires when the cookie already existed: the re-issue upgrades a script-written
72
- // cookie to a server-set one and rolls its expiry forward on every visit.
73
- if (!hasRequestedPersist && typeof document !== "undefined") {
74
- hasRequestedPersist = true;
75
- void persist(id).catch(() => {
76
- /* optimistic client-side cookie still covers this session */
77
- });
78
- }
79
-
80
- return id;
81
- },
82
- refresh(): void {
83
- if (typeof document === "undefined") {
84
- return;
85
- }
86
-
87
- const existing = readCookieValue(document.cookie, cookieName);
88
-
89
- if (!existing) {
90
- return;
91
- }
92
-
93
- local.refresh();
94
-
95
- // Same once-per-load budget as getOrCreate — refresh must not add a second request.
96
- if (!hasRequestedPersist) {
97
- hasRequestedPersist = true;
98
- void persist(existing).catch(() => {
99
- /* optimistic client-side prolong above still covers this session */
100
- });
101
- }
102
- },
103
- };
104
- }
@@ -1,27 +0,0 @@
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 0.5.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 0.5.0-canary.6
24
- */
25
- export function defineConsentConfig<Config extends ConsentConfig>(config: Config): Config {
26
- return config;
27
- }
@@ -1,115 +0,0 @@
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 0.5.0-canary.6
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).
15
- *
16
- * @since 0.5.0-canary.6
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 0.5.0-canary.6
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 0.5.0-canary.6
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 0.5.0-canary.6
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 0.5.0-canary.6
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
- }
@@ -1,298 +0,0 @@
1
- /**
2
- * The privacy-law region a visitor's consent defaults are resolved for.
3
- *
4
- * @since 0.5.0-canary.4
5
- */
6
- export type ConsentRegion = "eu" | "other" | "us" | "vn";
7
-
8
- /**
9
- * Every consent region, in a stable order shared by guards and iteration.
10
- *
11
- * @since 0.5.0-canary.6
12
- */
13
- export const CONSENT_REGIONS: ReadonlyArray<ConsentRegion> = ["eu", "other", "us", "vn"];
14
-
15
- /**
16
- * Guards a region read from untrusted storage (a cached `InitialConsent`, a cookie).
17
- *
18
- * @since 0.5.0-canary.6
19
- */
20
- export function isConsentRegion(value: unknown): value is ConsentRegion {
21
- return CONSENT_REGIONS.includes(value as ConsentRegion);
22
- }
23
-
24
- /**
25
- * Whether a region requires explicit opt-in before tracking or defaults to opt-out.
26
- *
27
- * @since 0.5.0-canary.4
28
- */
29
- export type ConsentMode = "opt-in" | "opt-out";
30
-
31
- /**
32
- * GDPR (EU) and the PDPL — Luật 91/2025/QH15 (VN) — require explicit opt-in before any non-essential
33
- * tracking; CCPA/CPRA (US) defaults to opt-out instead. There is no single global default
34
- * that satisfies both, so the mode is resolved per region.
35
- *
36
- * @since 0.5.0-canary.4
37
- */
38
- export function resolveConsentMode(region: ConsentRegion): ConsentMode {
39
- switch (region) {
40
- case "eu":
41
- case "vn": {
42
- return "opt-in";
43
- }
44
-
45
- case "other":
46
- case "us": {
47
- return "opt-out";
48
- }
49
- }
50
- }
51
-
52
- /**
53
- * Consent purposes, mirroring Google Consent Mode v2's split: `analytics` gates
54
- * measurement (`analytics_storage`), `ads` gates advertising storage and data sharing
55
- * (`ad_storage`/`ad_user_data`/`ad_personalization`).
56
- *
57
- * @since 0.5.0-canary.4
58
- */
59
- export type ConsentCategory = "ads" | "analytics";
60
-
61
- /**
62
- * Every consent category, in a stable order shared by guards and iteration.
63
- *
64
- * @since 0.5.0-canary.4
65
- */
66
- export const CONSENT_CATEGORIES: ReadonlyArray<ConsentCategory> = ["ads", "analytics"];
67
-
68
- /**
69
- * Per-category consent — GDPR consent must be granular per purpose, so a single
70
- * granted/denied flag can't represent it. `true` means the visitor granted that purpose.
71
- *
72
- * @since 0.5.0-canary.4
73
- */
74
- export type ConsentDecision = Record<ConsentCategory, boolean>;
75
-
76
- /**
77
- * A decision granting exactly the given categories and denying every other one.
78
- *
79
- * @since 0.5.0-canary.4
80
- */
81
- export function createConsentDecision(grantedCategories: ReadonlyArray<ConsentCategory>): ConsentDecision {
82
- return { ads: grantedCategories.includes("ads"), analytics: grantedCategories.includes("analytics") };
83
- }
84
-
85
- function isPlainObject(value: unknown): value is Record<string, unknown> {
86
- return typeof value === "object" && value !== null && !Array.isArray(value);
87
- }
88
-
89
- /**
90
- * Guards stored JSON — the record is tamperable, so every category must be an explicit boolean.
91
- *
92
- * @since 0.5.0-canary.4
93
- */
94
- export function isConsentDecision(value: unknown): value is ConsentDecision {
95
- return isPlainObject(value) && CONSENT_CATEGORIES.every((category) => typeof value[category] === "boolean");
96
- }
97
-
98
- /**
99
- * Re-derives a clean per-category decision from a tamperable record — extra keys are
100
- * dropped, every category becomes an explicit boolean. The one normalization rule every
101
- * reader of stored consent shares (e.g. `readStoredDecision`).
102
- *
103
- * @since 0.5.0-canary.6
104
- */
105
- export function normalizeConsentDecision(decision: ConsentDecision): ConsentDecision {
106
- return createConsentDecision(CONSENT_CATEGORIES.filter((category) => decision[category]));
107
- }
108
-
109
- /**
110
- * Guards a persisted consent record read from untrusted storage (e.g. `localStorage`).
111
- *
112
- * @since 0.5.0-canary.6
113
- */
114
- export function isConsentRecord(value: unknown): value is ConsentRecord {
115
- return (
116
- isPlainObject(value) &&
117
- isConsentDecision(value.decision) &&
118
- typeof value.policyVersion === "string" &&
119
- typeof value.timestamp === "number"
120
- );
121
- }
122
-
123
- /**
124
- * Options for `resolveDefaultConsent`.
125
- *
126
- * @since 0.5.0-canary.6
127
- */
128
- export interface ResolveDefaultConsentOptions {
129
- /** A "do not sell or share" opt-out — forces `ads` denied under opt-out regions. */
130
- hasGlobalPrivacyControlSignal: boolean;
131
- mode: ConsentMode;
132
- requestedCategories: ReadonlyArray<ConsentCategory>;
133
- }
134
-
135
- /**
136
- * The effective consent before the visitor decides: opt-in regions start all-denied,
137
- * opt-out regions grant the categories the app asks for.
138
- *
139
- * @remarks
140
- * A Global Privacy Control signal is a "do not sell or share" opt-out (CCPA/CPRA), so it
141
- * forces `ads` denied — it does not withdraw first-party analytics measurement.
142
- *
143
- * @since 0.5.0-canary.4
144
- */
145
- export function resolveDefaultConsent(options: ResolveDefaultConsentOptions): ConsentDecision {
146
- const { hasGlobalPrivacyControlSignal, mode, requestedCategories } = options;
147
-
148
- if (mode === "opt-in") {
149
- return createConsentDecision([]);
150
- }
151
-
152
- const decision = createConsentDecision(requestedCategories);
153
-
154
- if (hasGlobalPrivacyControlSignal) {
155
- decision.ads = false;
156
- }
157
-
158
- return decision;
159
- }
160
-
161
- /**
162
- * Region-resolved consent defaults — typically from `resolveInitialConsent` on a
163
- * per-request server lane, then handed to the client so it never re-guesses the mode.
164
- *
165
- * @remarks
166
- * Drive UI and gates from `mode` (recompute `effectiveConsent` with live navigator GPC).
167
- * `defaultConsent` is the server snapshot — useful when you need request-time `sec-gpc`
168
- * as-is; analytics-only apps can ignore it because GPC only forces `ads` denied.
169
- *
170
- * @since 0.5.0-canary.6
171
- */
172
- export interface InitialConsent {
173
- defaultConsent: ConsentDecision;
174
- mode: ConsentMode;
175
- region: ConsentRegion;
176
- }
177
-
178
- /**
179
- * What shared HTML bakes and what an unknown-country request resolves to: all categories
180
- * denied under opt-in — the one default that is safe to show any visitor anywhere.
181
- * Prerendered/CDN-cached markup must carry nothing region-specific, and a missing geo
182
- * header means "unknown visitor", never "known non-EU visitor".
183
- *
184
- * @since 0.5.0-canary.6
185
- */
186
- export const STRICTEST_INITIAL_CONSENT: InitialConsent = Object.freeze({
187
- defaultConsent: Object.freeze(createConsentDecision([])),
188
- mode: "opt-in",
189
- region: "other",
190
- });
191
-
192
- /**
193
- * Guards an `InitialConsent` read from untrusted storage (a session cache, a cookie).
194
- * Enforces the mode/region pairing rule; the one deliberate exception is
195
- * {@link STRICTEST_INITIAL_CONSENT}'s own pairing — stricter than the region's usual
196
- * mode, never looser.
197
- *
198
- * @since 0.5.0-canary.6
199
- */
200
- export function isInitialConsent(value: unknown): value is InitialConsent {
201
- if (!isPlainObject(value)) {
202
- return false;
203
- }
204
-
205
- const mode = value.mode;
206
- const region = value.region;
207
-
208
- if (
209
- (mode !== "opt-in" && mode !== "opt-out") ||
210
- !isConsentRegion(region) ||
211
- !isConsentDecision(value.defaultConsent)
212
- ) {
213
- return false;
214
- }
215
-
216
- return (
217
- mode === resolveConsentMode(region) ||
218
- (mode === STRICTEST_INITIAL_CONSENT.mode && region === STRICTEST_INITIAL_CONSENT.region)
219
- );
220
- }
221
-
222
- /**
223
- * Vietnam's PDPL and GDPR both expect a record of *when* and *under what policy* consent
224
- * was given, not just per-category flags — `policyVersion` lets a later policy change
225
- * invalidate stale consent.
226
- *
227
- * @since 0.5.0-canary.4
228
- */
229
- export interface ConsentRecord {
230
- decision: ConsentDecision;
231
- policyVersion: string;
232
- timestamp: number;
233
- }
234
-
235
- /**
236
- * Persistence backend for the visitor's consent decision — swap in your own
237
- * implementation for non-browser environments or a different persistence layer.
238
- *
239
- * @since 0.5.0-canary.4
240
- */
241
- export interface ConsentStorage {
242
- clear: () => void;
243
- load: () => ConsentRecord | undefined;
244
- save: (record: ConsentRecord) => void;
245
- /**
246
- * Notify on any change to the stored record, including writes from other tabs — this
247
- * is what drives `useConsent`'s external-store subscription. Returns an unsubscribe.
248
- */
249
- subscribe: (listener: () => void) => () => void;
250
- }
251
-
252
- /**
253
- * The stored decision if one exists under the current `policyVersion`, normalized to drop
254
- * any tampered extra keys — `undefined` if there is none yet, the record is malformed, or
255
- * it was recorded under a superseded policy version.
256
- *
257
- * @since 0.5.0-canary.6
258
- */
259
- export function readStoredDecision(storage: ConsentStorage, policyVersion: string): ConsentDecision | undefined {
260
- const record = storage.load();
261
-
262
- if (record?.policyVersion !== policyVersion || !isConsentDecision(record.decision)) {
263
- return undefined;
264
- }
265
-
266
- return normalizeConsentDecision(record.decision);
267
- }
268
-
269
- /**
270
- * Options for `resolveEffectiveConsent`.
271
- *
272
- * @since 0.5.0-canary.6
273
- */
274
- export interface ResolveEffectiveConsentOptions {
275
- /** A "do not sell or share" opt-out — forces `ads` denied under opt-out regions. */
276
- hasGlobalPrivacyControlSignal: boolean;
277
- mode: ConsentMode;
278
- policyVersion: string;
279
- requestedCategories: ReadonlyArray<ConsentCategory>;
280
- storage: ConsentStorage;
281
- }
282
-
283
- /**
284
- * The consent a tracker should honor right now: the stored decision if one exists, else
285
- * the region default — the same rule `useConsent` applies to its `effectiveConsent`, so a
286
- * non-React gate (e.g. a tracker's `isAnalyticsAllowed` option) doesn't have to reimplement
287
- * "read storage, validate the policy version, fall back to `resolveDefaultConsent`" itself.
288
- *
289
- * @since 0.5.0-canary.6
290
- */
291
- export function resolveEffectiveConsent(options: ResolveEffectiveConsentOptions): ConsentDecision {
292
- const { hasGlobalPrivacyControlSignal, mode, policyVersion, requestedCategories, storage } = options;
293
-
294
- return (
295
- readStoredDecision(storage, policyVersion) ??
296
- resolveDefaultConsent({ hasGlobalPrivacyControlSignal, mode, requestedCategories })
297
- );
298
- }
@@ -1,29 +0,0 @@
1
- /**
2
- * Default lifetime shared by the anonymous-id and consent cookies — one year.
3
- *
4
- * @since 0.5.0-canary.6
5
- */
6
- export const ONE_YEAR_IN_SECONDS: number = 60 * 60 * 24 * 365;
7
-
8
- /**
9
- * The value of `cookieName` inside a cookie string — a request `Cookie` header or
10
- * `document.cookie`, which share the `name=value; name2=value2` wire format — or
11
- * `undefined` when absent. The name must match exactly; a longer prefix sibling is ignored.
12
- *
13
- * @since 0.5.0-canary.6
14
- */
15
- export function readCookieValue(cookieString: string | null | undefined, cookieName: string): string | undefined {
16
- if (!cookieString) {
17
- return undefined;
18
- }
19
-
20
- for (const part of cookieString.split(";")) {
21
- const separatorIndex = part.indexOf("=");
22
-
23
- if (separatorIndex !== -1 && part.slice(0, separatorIndex).trim() === cookieName) {
24
- return part.slice(separatorIndex + 1).trim();
25
- }
26
- }
27
-
28
- return undefined;
29
- }
@@ -1,29 +0,0 @@
1
- import type { TrackedEvent } from "#/core/tracked-event";
2
-
3
- /**
4
- * Fan-out target for tracked events. The tracker depends only on this interface, never
5
- * on a specific provider SDK — destinations own their transport (gtag.js and Vercel both
6
- * queue and batch in-page), so `send` is fire-and-forget at track time.
7
- *
8
- * @since 0.5.0-canary.4
9
- */
10
- export interface Destination {
11
- /**
12
- * "exempt" keeps this destination receiving events while the tracker's analytics gate
13
- * is closed — only for cookieless, identifier-free sinks: gated envelopes carry no
14
- * `anonymousId`, and nothing is persisted.
15
- *
16
- * @defaultValue "required"
17
- */
18
- consentRequirement?: "exempt" | "required" | undefined;
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;
27
- /** Must always return a `Promise` — mark `send` `async` even if the body has no `await`. */
28
- send: (event: TrackedEvent) => Promise<void>;
29
- }
@@ -1,54 +0,0 @@
1
- import type { StandardSchemaV1 } from "@standard-schema/spec";
2
-
3
- /**
4
- * One event's schema. Any Standard Schema library works (zod, zod/mini, valibot, ...) —
5
- * the client bundle only pays for the one the app already ships.
6
- *
7
- * @since 0.5.0-canary.4
8
- */
9
- export interface EventDefinition<Schema extends StandardSchemaV1 = StandardSchemaV1> {
10
- schema: Schema;
11
- }
12
-
13
- /**
14
- * An app-defined map of event name to its definition. `@codefast/tracking` ships no
15
- * events of its own — every consuming app builds and passes in its own catalog.
16
- *
17
- * @since 0.5.0-canary.4
18
- */
19
- export type EventCatalog = Record<string, EventDefinition>;
20
-
21
- /**
22
- * Identity helper for declaring a catalog with inference — nicer call-site than
23
- * `satisfies EventCatalog` when the catalog is assembled across multiple files.
24
- *
25
- * @since 0.5.0-canary.4
26
- */
27
- export function defineEventCatalog<Catalog extends EventCatalog>(catalog: Catalog): Catalog {
28
- return catalog;
29
- }
30
-
31
- /**
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.
34
- *
35
- * @throws Error when validation reports issues, or when the schema validates asynchronously —
36
- * tracking sits on synchronous call paths, so async schemas are unsupported by design.
37
- *
38
- * @since 0.5.0-canary.6
39
- */
40
- export function assertValidEventProperties(schema: StandardSchemaV1, eventName: string, properties: unknown): unknown {
41
- const result = schema["~standard"].validate(properties);
42
-
43
- if (result instanceof Promise) {
44
- throw new TypeError(`Event "${eventName}" uses an async schema — event properties must validate synchronously`);
45
- }
46
-
47
- if (result.issues) {
48
- const detail = result.issues.map((issue) => issue.message).join("; ");
49
-
50
- throw new Error(`Invalid properties for event "${eventName}": ${detail}`);
51
- }
52
-
53
- return result.value;
54
- }
@@ -1,8 +0,0 @@
1
- /**
2
- * Stamped on every envelope at track time — destinations that dedupe can key on it.
3
- *
4
- * @since 0.5.0-canary.4
5
- */
6
- export function generateEventId(): string {
7
- return crypto.randomUUID();
8
- }
@@ -1,14 +0,0 @@
1
- /**
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.
4
- *
5
- * @since 0.5.0-canary.4
6
- */
7
- export interface TrackedEvent {
8
- anonymousId: string;
9
- eventId: string;
10
- name: string;
11
- properties: Record<string, unknown>;
12
- timestamp: number;
13
- type: "track";
14
- }