@codefast/tracking 0.5.0-canary.5 → 1.0.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 (133) hide show
  1. package/CHANGELOG.md +165 -0
  2. package/README.md +122 -127
  3. package/dist/client/browser-cookie.d.mts +11 -0
  4. package/dist/client/browser-cookie.mjs +15 -0
  5. package/dist/client/consent-runtime.d.mts +56 -0
  6. package/dist/client/consent-runtime.mjs +35 -0
  7. package/dist/client/consent-storage.d.mts +5 -0
  8. package/dist/client/consent-storage.mjs +20 -1
  9. package/dist/client/consent-withdrawal.d.mts +21 -0
  10. package/dist/client/consent-withdrawal.mjs +17 -0
  11. package/dist/client/cookie-anonymous-id.d.mts +37 -0
  12. package/dist/client/cookie-anonymous-id.mjs +46 -0
  13. package/dist/client/create-client-tracker.d.mts +11 -16
  14. package/dist/client/create-client-tracker.mjs +27 -53
  15. package/dist/client/gpc.d.mts +2 -0
  16. package/dist/client/gpc.mjs +3 -1
  17. package/dist/client/index.d.mts +7 -5
  18. package/dist/client/index.mjs +8 -6
  19. package/dist/client/initial-consent-store.d.mts +66 -0
  20. package/dist/client/initial-consent-store.mjs +119 -0
  21. package/dist/client/is-analytics-allowed.d.mts +29 -0
  22. package/dist/client/is-analytics-allowed.mjs +23 -0
  23. package/dist/client/server-persisted-anonymous-id.d.mts +33 -0
  24. package/dist/client/server-persisted-anonymous-id.mjs +50 -0
  25. package/dist/core/consent-config.d.mts +27 -0
  26. package/dist/core/consent-config.mjs +11 -0
  27. package/dist/core/consent.d.mts +99 -4
  28. package/dist/core/consent.mjs +99 -4
  29. package/dist/core/cookie.d.mts +17 -0
  30. package/dist/core/cookie.mjs +23 -0
  31. package/dist/core/destination.d.mts +10 -8
  32. package/dist/core/event-catalog.d.mts +16 -13
  33. package/dist/core/event-catalog.mjs +19 -1
  34. package/dist/core/event-id.d.mts +1 -2
  35. package/dist/core/event-id.mjs +1 -2
  36. package/dist/core/index.d.mts +6 -4
  37. package/dist/core/index.mjs +5 -3
  38. package/dist/core/tracked-event.d.mts +21 -8
  39. package/dist/destinations/google-analytics.d.mts +100 -48
  40. package/dist/destinations/google-analytics.mjs +89 -85
  41. package/dist/destinations/google-consent.d.mts +64 -0
  42. package/dist/destinations/google-consent.mjs +102 -0
  43. package/dist/destinations/index.d.mts +2 -5
  44. package/dist/destinations/index.mjs +2 -5
  45. package/dist/destinations/shared.d.mts +20 -0
  46. package/dist/destinations/shared.mjs +13 -0
  47. package/dist/destinations/vercel-analytics.d.mts +19 -4
  48. package/dist/destinations/vercel-analytics.mjs +11 -18
  49. package/dist/import-protection.d.mts +19 -0
  50. package/dist/import-protection.mjs +23 -0
  51. package/dist/index.d.mts +6 -4
  52. package/dist/index.mjs +5 -3
  53. package/dist/react/consent-banner.d.mts +24 -7
  54. package/dist/react/consent-banner.mjs +16 -11
  55. package/dist/react/gtag-consent-bootstrap.d.mts +27 -0
  56. package/dist/react/gtag-consent-bootstrap.mjs +29 -0
  57. package/dist/react/index.d.mts +4 -1
  58. package/dist/react/index.mjs +4 -1
  59. package/dist/react/use-consent.d.mts +9 -13
  60. package/dist/react/use-consent.mjs +42 -25
  61. package/dist/react/use-google-consent-sync.d.mts +23 -0
  62. package/dist/react/use-google-consent-sync.mjs +24 -0
  63. package/dist/react/use-initial-consent.d.mts +14 -0
  64. package/dist/react/use-initial-consent.mjs +19 -0
  65. package/dist/server/anonymous-id-cookie.d.mts +46 -0
  66. package/dist/server/anonymous-id-cookie.mjs +51 -0
  67. package/dist/server/index.d.mts +5 -3
  68. package/dist/server/index.mjs +4 -3
  69. package/dist/server/initial-consent.d.mts +29 -0
  70. package/dist/server/initial-consent.mjs +31 -0
  71. package/dist/server/region.d.mts +21 -4
  72. package/dist/server/region.mjs +26 -5
  73. package/dist/tanstack-start/index.d.mts +58 -0
  74. package/dist/tanstack-start/index.mjs +45 -0
  75. package/package.json +26 -110
  76. package/src/client/browser-cookie.ts +16 -0
  77. package/src/client/consent-runtime.ts +80 -0
  78. package/src/client/consent-storage.ts +31 -1
  79. package/src/client/consent-withdrawal.ts +32 -0
  80. package/src/client/cookie-anonymous-id.ts +93 -0
  81. package/src/client/create-client-tracker.ts +56 -85
  82. package/src/client/gpc.ts +4 -2
  83. package/src/client/index.ts +19 -8
  84. package/src/client/initial-consent-store.ts +218 -0
  85. package/src/client/is-analytics-allowed.ts +43 -0
  86. package/src/client/server-persisted-anonymous-id.ts +99 -0
  87. package/src/core/consent-config.ts +27 -0
  88. package/src/core/consent.ts +164 -10
  89. package/src/core/cookie.ts +29 -0
  90. package/src/core/destination.ts +10 -8
  91. package/src/core/event-catalog.ts +28 -15
  92. package/src/core/event-id.ts +1 -2
  93. package/src/core/index.ts +19 -3
  94. package/src/core/tracked-event.ts +22 -7
  95. package/src/destinations/google-analytics.ts +196 -133
  96. package/src/destinations/google-consent.ts +164 -0
  97. package/src/destinations/index.ts +14 -15
  98. package/src/destinations/shared.ts +45 -0
  99. package/src/destinations/vercel-analytics.ts +23 -24
  100. package/src/import-protection.ts +20 -0
  101. package/src/index.ts +46 -8
  102. package/src/react/consent-banner.tsx +40 -14
  103. package/src/react/gtag-consent-bootstrap.tsx +48 -0
  104. package/src/react/index.ts +8 -0
  105. package/src/react/use-consent.ts +53 -45
  106. package/src/react/use-google-consent-sync.ts +38 -0
  107. package/src/react/use-initial-consent.ts +22 -0
  108. package/src/server/anonymous-id-cookie.ts +76 -0
  109. package/src/server/index.ts +15 -3
  110. package/src/server/initial-consent.ts +48 -0
  111. package/src/server/region.ts +22 -5
  112. package/src/tanstack-start/index.ts +83 -0
  113. package/dist/client/lifecycle.d.mts +0 -23
  114. package/dist/client/lifecycle.mjs +0 -30
  115. package/dist/client/local-storage.d.mts +0 -13
  116. package/dist/client/local-storage.mjs +0 -31
  117. package/dist/client/queue.d.mts +0 -49
  118. package/dist/client/queue.mjs +0 -71
  119. package/dist/client/router.d.mts +0 -30
  120. package/dist/client/router.mjs +0 -17
  121. package/dist/destinations/ga4-measurement-protocol.d.mts +0 -54
  122. package/dist/destinations/ga4-measurement-protocol.mjs +0 -89
  123. package/dist/destinations/http-destination.d.mts +0 -20
  124. package/dist/destinations/http-destination.mjs +0 -25
  125. package/dist/server/create-server-tracker.d.mts +0 -42
  126. package/dist/server/create-server-tracker.mjs +0 -67
  127. package/src/client/lifecycle.ts +0 -50
  128. package/src/client/local-storage.ts +0 -44
  129. package/src/client/queue.ts +0 -117
  130. package/src/client/router.ts +0 -37
  131. package/src/destinations/ga4-measurement-protocol.ts +0 -166
  132. package/src/destinations/http-destination.ts +0 -33
  133. package/src/server/create-server-tracker.ts +0 -128
@@ -0,0 +1,50 @@
1
+ import { readCookieValue } from "../core/cookie.mjs";
2
+ import { createCookieAnonymousId } from "./cookie-anonymous-id.mjs";
3
+ //#region src/client/server-persisted-anonymous-id.ts
4
+ /**
5
+ * `createCookieAnonymousId` plus server persistence: the client still mints the id
6
+ * (lazily, only once an event is allowed to send — consent stays client-owned), then
7
+ * delegates the durable write to the server. A script-written cookie is capped at 7 days
8
+ * by Safari ITP; the server's `Set-Cookie` re-issue is what makes the id actually live
9
+ * its full max-age. Same optimistic `document.cookie` write first, so the current event
10
+ * never waits on the round-trip and a failed `persist` degrades to today's behavior.
11
+ *
12
+ * @since 1.0.0-canary.6
13
+ */
14
+ function createServerPersistedAnonymousId(options) {
15
+ const { clearOnServer, cookieName, maxAgeSeconds, persist } = options;
16
+ const local = createCookieAnonymousId({
17
+ cookieName,
18
+ maxAgeSeconds
19
+ });
20
+ let hasRequestedPersist = false;
21
+ return {
22
+ clear() {
23
+ const shouldClearServer = typeof document !== "undefined" && Boolean(readCookieValue(document.cookie, cookieName));
24
+ local.clear();
25
+ hasRequestedPersist = false;
26
+ if (shouldClearServer) clearOnServer?.().catch(() => {});
27
+ },
28
+ getOrCreate() {
29
+ if (typeof document !== "undefined" && !readCookieValue(document.cookie, cookieName)) hasRequestedPersist = false;
30
+ const id = local.getOrCreate();
31
+ if (!hasRequestedPersist && typeof document !== "undefined") {
32
+ hasRequestedPersist = true;
33
+ persist(id).catch(() => {});
34
+ }
35
+ return id;
36
+ },
37
+ refresh() {
38
+ if (typeof document === "undefined") return;
39
+ const existing = readCookieValue(document.cookie, cookieName);
40
+ if (!existing) return;
41
+ local.refresh();
42
+ if (!hasRequestedPersist) {
43
+ hasRequestedPersist = true;
44
+ persist(existing).catch(() => {});
45
+ }
46
+ }
47
+ };
48
+ }
49
+ //#endregion
50
+ export { createServerPersistedAnonymousId };
@@ -0,0 +1,27 @@
1
+ import { ConsentCategory } from "./consent.mjs";
2
+
3
+ //#region src/core/consent-config.d.ts
4
+ /**
5
+ * The consent constants every surface must agree on. The React hooks, the client
6
+ * tracker gate, and the pre-hydration tag bootstrap all accept this object, so the
7
+ * cross-surface "must match" contracts hold by construction instead of by hand-threading
8
+ * the same strings through every call site.
9
+ *
10
+ * @since 1.0.0-canary.6
11
+ */
12
+ interface ConsentConfig {
13
+ /** Bumping re-prompts every visitor — a stored decision under any other version is ignored. */
14
+ policyVersion: string;
15
+ /** Purposes the app's prompt asks about — `grantAll` and opt-out defaults grant exactly these. */
16
+ requestedCategories: ReadonlyArray<ConsentCategory>;
17
+ /** `localStorage` key holding the visitor's `ConsentRecord`. */
18
+ storageKey: string;
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
+ declare function defineConsentConfig<Config extends ConsentConfig>(config: Config): Config;
26
+ //#endregion
27
+ export { ConsentConfig, defineConsentConfig };
@@ -0,0 +1,11 @@
1
+ //#region src/core/consent-config.ts
2
+ /**
3
+ * Identity helper for declaring the config with inference — `defineEventCatalog`'s consent twin.
4
+ *
5
+ * @since 1.0.0-canary.6
6
+ */
7
+ function defineConsentConfig(config) {
8
+ return config;
9
+ }
10
+ //#endregion
11
+ export { defineConsentConfig };
@@ -3,12 +3,22 @@
3
3
  * @since 0.5.0-canary.4
4
4
  */
5
5
  type ConsentRegion = "eu" | "other" | "us" | "vn";
6
+ /**
7
+ * @since 1.0.0-canary.6
8
+ */
9
+ declare const CONSENT_REGIONS: ReadonlyArray<ConsentRegion>;
10
+ /**
11
+ * Guards a region read from untrusted storage (a cached `InitialConsent`, a cookie).
12
+ *
13
+ * @since 1.0.0-canary.6
14
+ */
15
+ declare function isConsentRegion(value: unknown): value is ConsentRegion;
6
16
  /**
7
17
  * @since 0.5.0-canary.4
8
18
  */
9
19
  type ConsentMode = "opt-in" | "opt-out";
10
20
  /**
11
- * GDPR (EU) and Nghị định 13/2023 (VN) require explicit opt-in before any non-essential
21
+ * GDPR (EU) and the PDPL — Luật 91/2025/QH15 (VN) — require explicit opt-in before any non-essential
12
22
  * tracking; CCPA/CPRA (US) defaults to opt-out instead. There is no single global default
13
23
  * that satisfies both, so the mode is resolved per region.
14
24
  *
@@ -46,6 +56,29 @@ declare function createConsentDecision(grantedCategories: ReadonlyArray<ConsentC
46
56
  * @since 0.5.0-canary.4
47
57
  */
48
58
  declare function isConsentDecision(value: unknown): value is ConsentDecision;
59
+ /**
60
+ * Re-derives a clean per-category decision from a tamperable record — extra keys are
61
+ * dropped, every category becomes an explicit boolean. The one normalization rule shared
62
+ * by the client (`readStoredDecision`) and server (`readConsentDecisionCookie`) mirrors.
63
+ *
64
+ * @since 1.0.0-canary.6
65
+ */
66
+ declare function normalizeConsentDecision(decision: ConsentDecision): ConsentDecision;
67
+ /**
68
+ * Guards a persisted consent record read from untrusted storage (e.g. `localStorage`).
69
+ *
70
+ * @since 1.0.0-canary.6
71
+ */
72
+ declare function isConsentRecord(value: unknown): value is ConsentRecord;
73
+ /**
74
+ * @since 1.0.0-canary.6
75
+ */
76
+ interface ResolveDefaultConsentOptions {
77
+ /** A "do not sell or share" opt-out — forces `ads` denied under opt-out regions. */
78
+ hasGlobalPrivacyControlSignal: boolean;
79
+ mode: ConsentMode;
80
+ requestedCategories: ReadonlyArray<ConsentCategory>;
81
+ }
49
82
  /**
50
83
  * The effective consent before the visitor decides: opt-in regions start all-denied,
51
84
  * opt-out regions grant the categories the app asks for.
@@ -56,9 +89,43 @@ declare function isConsentDecision(value: unknown): value is ConsentDecision;
56
89
  *
57
90
  * @since 0.5.0-canary.4
58
91
  */
59
- declare function resolveDefaultConsent(mode: ConsentMode, requestedCategories: ReadonlyArray<ConsentCategory>, hasGlobalPrivacyControlSignal: boolean): ConsentDecision;
92
+ declare function resolveDefaultConsent(options: ResolveDefaultConsentOptions): ConsentDecision;
93
+ /**
94
+ * Region-resolved consent defaults — typically from `resolveInitialConsent` on a
95
+ * per-request server lane, then handed to the client so it never re-guesses the mode.
96
+ *
97
+ * @remarks
98
+ * Drive UI and gates from `mode` (recompute `effectiveConsent` with live navigator GPC).
99
+ * `defaultConsent` is the server snapshot — useful when you need request-time `sec-gpc`
100
+ * as-is; analytics-only apps can ignore it because GPC only forces `ads` denied.
101
+ *
102
+ * @since 1.0.0-canary.6
103
+ */
104
+ interface InitialConsent {
105
+ defaultConsent: ConsentDecision;
106
+ mode: ConsentMode;
107
+ region: ConsentRegion;
108
+ }
109
+ /**
110
+ * What shared HTML bakes and what an unknown-country request resolves to: all categories
111
+ * denied under opt-in — the one default that is safe to show any visitor anywhere.
112
+ * Prerendered/CDN-cached markup must carry nothing region-specific, and a missing geo
113
+ * header means "unknown visitor", never "known non-EU visitor".
114
+ *
115
+ * @since 1.0.0-canary.6
116
+ */
117
+ declare const STRICTEST_INITIAL_CONSENT: InitialConsent;
60
118
  /**
61
- * NĐ 13/2023 and GDPR both expect a record of *when* and *under what policy* consent
119
+ * Guards an `InitialConsent` read from untrusted storage (a session cache, a cookie).
120
+ * Enforces the mode/region pairing rule; the one deliberate exception is
121
+ * {@link STRICTEST_INITIAL_CONSENT}'s own pairing — stricter than the region's usual
122
+ * mode, never looser.
123
+ *
124
+ * @since 1.0.0-canary.6
125
+ */
126
+ declare function isInitialConsent(value: unknown): value is InitialConsent;
127
+ /**
128
+ * Vietnam's PDPL and GDPR both expect a record of *when* and *under what policy* consent
62
129
  * was given, not just per-category flags — `policyVersion` lets a later policy change
63
130
  * invalidate stale consent.
64
131
  *
@@ -85,5 +152,33 @@ interface ConsentStorage {
85
152
  */
86
153
  subscribe: (listener: () => void) => () => void;
87
154
  }
155
+ /**
156
+ * The stored decision if one exists under the current `policyVersion`, normalized to drop
157
+ * any tampered extra keys — `undefined` if there is none yet, the record is malformed, or
158
+ * it was recorded under a superseded policy version.
159
+ *
160
+ * @since 1.0.0-canary.6
161
+ */
162
+ declare function readStoredDecision(storage: ConsentStorage, policyVersion: string): ConsentDecision | undefined;
163
+ /**
164
+ * @since 1.0.0-canary.6
165
+ */
166
+ interface ResolveEffectiveConsentOptions {
167
+ /** A "do not sell or share" opt-out — forces `ads` denied under opt-out regions. */
168
+ hasGlobalPrivacyControlSignal: boolean;
169
+ mode: ConsentMode;
170
+ policyVersion: string;
171
+ requestedCategories: ReadonlyArray<ConsentCategory>;
172
+ storage: ConsentStorage;
173
+ }
174
+ /**
175
+ * The consent a tracker should honor right now: the stored decision if one exists, else
176
+ * the region default — the same rule `useConsent` applies to its `effectiveConsent`, so a
177
+ * non-React gate (e.g. a tracker's `isAnalyticsAllowed` option) doesn't have to reimplement
178
+ * "read storage, validate the policy version, fall back to `resolveDefaultConsent`" itself.
179
+ *
180
+ * @since 1.0.0-canary.6
181
+ */
182
+ declare function resolveEffectiveConsent(options: ResolveEffectiveConsentOptions): ConsentDecision;
88
183
  //#endregion
89
- export { CONSENT_CATEGORIES, ConsentCategory, ConsentDecision, ConsentMode, ConsentRecord, ConsentRegion, ConsentStorage, createConsentDecision, isConsentDecision, resolveConsentMode, resolveDefaultConsent };
184
+ export { CONSENT_CATEGORIES, CONSENT_REGIONS, ConsentCategory, ConsentDecision, ConsentMode, ConsentRecord, ConsentRegion, ConsentStorage, InitialConsent, ResolveDefaultConsentOptions, ResolveEffectiveConsentOptions, STRICTEST_INITIAL_CONSENT, createConsentDecision, isConsentDecision, isConsentRecord, isConsentRegion, isInitialConsent, normalizeConsentDecision, readStoredDecision, resolveConsentMode, resolveDefaultConsent, resolveEffectiveConsent };
@@ -1,6 +1,23 @@
1
1
  //#region src/core/consent.ts
2
2
  /**
3
- * GDPR (EU) and Nghị định 13/2023 (VN) require explicit opt-in before any non-essential
3
+ * @since 1.0.0-canary.6
4
+ */
5
+ const CONSENT_REGIONS = [
6
+ "eu",
7
+ "other",
8
+ "us",
9
+ "vn"
10
+ ];
11
+ /**
12
+ * Guards a region read from untrusted storage (a cached `InitialConsent`, a cookie).
13
+ *
14
+ * @since 1.0.0-canary.6
15
+ */
16
+ function isConsentRegion(value) {
17
+ return CONSENT_REGIONS.includes(value);
18
+ }
19
+ /**
20
+ * GDPR (EU) and the PDPL — Luật 91/2025/QH15 (VN) — require explicit opt-in before any non-essential
4
21
  * tracking; CCPA/CPRA (US) defaults to opt-out instead. There is no single global default
5
22
  * that satisfies both, so the mode is resolved per region.
6
23
  *
@@ -29,13 +46,34 @@ function createConsentDecision(grantedCategories) {
29
46
  analytics: grantedCategories.includes("analytics")
30
47
  };
31
48
  }
49
+ function isPlainObject(value) {
50
+ return typeof value === "object" && value !== null && !Array.isArray(value);
51
+ }
32
52
  /**
33
53
  * Guards stored JSON — the record is tamperable, so every category must be an explicit boolean.
34
54
  *
35
55
  * @since 0.5.0-canary.4
36
56
  */
37
57
  function isConsentDecision(value) {
38
- return typeof value === "object" && value !== null && CONSENT_CATEGORIES.every((category) => typeof value[category] === "boolean");
58
+ return isPlainObject(value) && CONSENT_CATEGORIES.every((category) => typeof value[category] === "boolean");
59
+ }
60
+ /**
61
+ * Re-derives a clean per-category decision from a tamperable record — extra keys are
62
+ * dropped, every category becomes an explicit boolean. The one normalization rule shared
63
+ * by the client (`readStoredDecision`) and server (`readConsentDecisionCookie`) mirrors.
64
+ *
65
+ * @since 1.0.0-canary.6
66
+ */
67
+ function normalizeConsentDecision(decision) {
68
+ return createConsentDecision(CONSENT_CATEGORIES.filter((category) => decision[category]));
69
+ }
70
+ /**
71
+ * Guards a persisted consent record read from untrusted storage (e.g. `localStorage`).
72
+ *
73
+ * @since 1.0.0-canary.6
74
+ */
75
+ function isConsentRecord(value) {
76
+ return isPlainObject(value) && isConsentDecision(value.decision) && typeof value.policyVersion === "string" && typeof value.timestamp === "number";
39
77
  }
40
78
  /**
41
79
  * The effective consent before the visitor decides: opt-in regions start all-denied,
@@ -47,11 +85,68 @@ function isConsentDecision(value) {
47
85
  *
48
86
  * @since 0.5.0-canary.4
49
87
  */
50
- function resolveDefaultConsent(mode, requestedCategories, hasGlobalPrivacyControlSignal) {
88
+ function resolveDefaultConsent(options) {
89
+ const { hasGlobalPrivacyControlSignal, mode, requestedCategories } = options;
51
90
  if (mode === "opt-in") return createConsentDecision([]);
52
91
  const decision = createConsentDecision(requestedCategories);
53
92
  if (hasGlobalPrivacyControlSignal) decision.ads = false;
54
93
  return decision;
55
94
  }
95
+ /**
96
+ * What shared HTML bakes and what an unknown-country request resolves to: all categories
97
+ * denied under opt-in — the one default that is safe to show any visitor anywhere.
98
+ * Prerendered/CDN-cached markup must carry nothing region-specific, and a missing geo
99
+ * header means "unknown visitor", never "known non-EU visitor".
100
+ *
101
+ * @since 1.0.0-canary.6
102
+ */
103
+ const STRICTEST_INITIAL_CONSENT = Object.freeze({
104
+ defaultConsent: Object.freeze(createConsentDecision([])),
105
+ mode: "opt-in",
106
+ region: "other"
107
+ });
108
+ /**
109
+ * Guards an `InitialConsent` read from untrusted storage (a session cache, a cookie).
110
+ * Enforces the mode/region pairing rule; the one deliberate exception is
111
+ * {@link STRICTEST_INITIAL_CONSENT}'s own pairing — stricter than the region's usual
112
+ * mode, never looser.
113
+ *
114
+ * @since 1.0.0-canary.6
115
+ */
116
+ function isInitialConsent(value) {
117
+ if (!isPlainObject(value)) return false;
118
+ const mode = value.mode;
119
+ const region = value.region;
120
+ if (mode !== "opt-in" && mode !== "opt-out" || !isConsentRegion(region) || !isConsentDecision(value.defaultConsent)) return false;
121
+ return mode === resolveConsentMode(region) || mode === STRICTEST_INITIAL_CONSENT.mode && region === STRICTEST_INITIAL_CONSENT.region;
122
+ }
123
+ /**
124
+ * The stored decision if one exists under the current `policyVersion`, normalized to drop
125
+ * any tampered extra keys — `undefined` if there is none yet, the record is malformed, or
126
+ * it was recorded under a superseded policy version.
127
+ *
128
+ * @since 1.0.0-canary.6
129
+ */
130
+ function readStoredDecision(storage, policyVersion) {
131
+ const record = storage.load();
132
+ if (record?.policyVersion !== policyVersion || !isConsentDecision(record.decision)) return;
133
+ return normalizeConsentDecision(record.decision);
134
+ }
135
+ /**
136
+ * The consent a tracker should honor right now: the stored decision if one exists, else
137
+ * the region default — the same rule `useConsent` applies to its `effectiveConsent`, so a
138
+ * non-React gate (e.g. a tracker's `isAnalyticsAllowed` option) doesn't have to reimplement
139
+ * "read storage, validate the policy version, fall back to `resolveDefaultConsent`" itself.
140
+ *
141
+ * @since 1.0.0-canary.6
142
+ */
143
+ function resolveEffectiveConsent(options) {
144
+ const { hasGlobalPrivacyControlSignal, mode, policyVersion, requestedCategories, storage } = options;
145
+ return readStoredDecision(storage, policyVersion) ?? resolveDefaultConsent({
146
+ hasGlobalPrivacyControlSignal,
147
+ mode,
148
+ requestedCategories
149
+ });
150
+ }
56
151
  //#endregion
57
- export { CONSENT_CATEGORIES, createConsentDecision, isConsentDecision, resolveConsentMode, resolveDefaultConsent };
152
+ export { CONSENT_CATEGORIES, CONSENT_REGIONS, STRICTEST_INITIAL_CONSENT, createConsentDecision, isConsentDecision, isConsentRecord, isConsentRegion, isInitialConsent, normalizeConsentDecision, readStoredDecision, resolveConsentMode, resolveDefaultConsent, resolveEffectiveConsent };
@@ -0,0 +1,17 @@
1
+ //#region src/core/cookie.d.ts
2
+ /**
3
+ * Default lifetime shared by the anonymous-id and consent cookies — one year.
4
+ *
5
+ * @since 1.0.0-canary.6
6
+ */
7
+ declare const ONE_YEAR_IN_SECONDS: number;
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 1.0.0-canary.6
14
+ */
15
+ declare function readCookieValue(cookieString: string | null | undefined, cookieName: string): string | undefined;
16
+ //#endregion
17
+ export { ONE_YEAR_IN_SECONDS, readCookieValue };
@@ -0,0 +1,23 @@
1
+ //#region src/core/cookie.ts
2
+ /**
3
+ * Default lifetime shared by the anonymous-id and consent cookies — one year.
4
+ *
5
+ * @since 1.0.0-canary.6
6
+ */
7
+ const ONE_YEAR_IN_SECONDS = 3600 * 24 * 365;
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 1.0.0-canary.6
14
+ */
15
+ function readCookieValue(cookieString, cookieName) {
16
+ if (!cookieString) return;
17
+ for (const part of cookieString.split(";")) {
18
+ const separatorIndex = part.indexOf("=");
19
+ if (separatorIndex !== -1 && part.slice(0, separatorIndex).trim() === cookieName) return part.slice(separatorIndex + 1).trim();
20
+ }
21
+ }
22
+ //#endregion
23
+ export { ONE_YEAR_IN_SECONDS, readCookieValue };
@@ -2,22 +2,24 @@ import { TrackedEvent } from "./tracked-event.mjs";
2
2
 
3
3
  //#region src/core/destination.d.ts
4
4
  /**
5
- * Fan-out target for tracked events (PostHog, GA4, a self-hosted store, ...).
6
- * Trackers depend only on this interface, never on a specific provider SDK.
5
+ * Fan-out target for tracked events. The tracker depends only on this interface, never
6
+ * on a specific provider SDK — destinations own their transport (gtag.js and Vercel both
7
+ * queue and batch in-page), so `send` is fire-and-forget at track time.
7
8
  *
8
9
  * @since 0.5.0-canary.4
9
10
  */
10
11
  interface Destination {
11
12
  /**
12
- * "immediate" for SDK-backed destinations that own their transport (gtag.js, Vercel's
13
- * in-page queue) — the client tracker calls `send` at track time and never queues,
14
- * persists, or retries for them.
13
+ * "exempt" keeps this destination receiving events while the tracker's analytics gate
14
+ * is closed — only for cookieless, identifier-free sinks: gated envelopes carry no
15
+ * `anonymousId`, and nothing is persisted.
15
16
  *
16
- * @defaultValue "queued"
17
+ * @defaultValue "required"
17
18
  */
18
- delivery?: "immediate" | "queued";
19
+ consentRequirement?: "exempt" | "required" | undefined;
19
20
  name: string;
20
- send: (event: TrackedEvent) => Promise<void> | void;
21
+ /** Must always return a `Promise` — mark `send` `async` even if the body has no `await`. */
22
+ send: (event: TrackedEvent) => Promise<void>;
21
23
  }
22
24
  //#endregion
23
25
  export { Destination };
@@ -1,13 +1,13 @@
1
- import { z } from "zod";
1
+ import { StandardSchemaV1 } from "@standard-schema/spec";
2
2
 
3
3
  //#region src/core/event-catalog.d.ts
4
4
  /**
5
- * One event's Zod schema plus which side of the app is allowed to fire it.
5
+ * One event's schema. Any Standard Schema library works (zod, zod/mini, valibot, ...) —
6
+ * the client bundle only pays for the one the app already ships.
6
7
  *
7
8
  * @since 0.5.0-canary.4
8
9
  */
9
- interface EventDefinition<Schema extends z.ZodType = z.ZodType> {
10
- owner: "client" | "server";
10
+ interface EventDefinition<Schema extends StandardSchemaV1 = StandardSchemaV1> {
11
11
  schema: Schema;
12
12
  }
13
13
  /**
@@ -17,14 +17,6 @@ interface EventDefinition<Schema extends z.ZodType = z.ZodType> {
17
17
  * @since 0.5.0-canary.4
18
18
  */
19
19
  type EventCatalog = Record<string, EventDefinition>;
20
- /**
21
- * Filters a catalog down to the events a given owner may fire. Client and server
22
- * trackers are built from this, so calling a server-owned event from client code
23
- * (or vice versa) is a compile-time error, not a runtime surprise.
24
- *
25
- * @since 0.5.0-canary.4
26
- */
27
- type EventsOf<Catalog extends EventCatalog, Owner extends "client" | "server"> = { [Key in keyof Catalog as Catalog[Key]["owner"] extends Owner ? Key : never]: Catalog[Key] };
28
20
  /**
29
21
  * Identity helper for declaring a catalog with inference — nicer call-site than
30
22
  * `satisfies EventCatalog` when the catalog is assembled across multiple files.
@@ -32,5 +24,16 @@ type EventsOf<Catalog extends EventCatalog, Owner extends "client" | "server"> =
32
24
  * @since 0.5.0-canary.4
33
25
  */
34
26
  declare function defineEventCatalog<Catalog extends EventCatalog>(catalog: Catalog): Catalog;
27
+ /**
28
+ * Validates event properties against the catalog schema and throws on mismatch. The
29
+ * validated (possibly transformed) value is deliberately discarded — the tracker always
30
+ * sends the caller's original properties, so a schema transform can never desync callers.
31
+ *
32
+ * @throws Error when validation reports issues, or when the schema validates asynchronously —
33
+ * tracking sits on synchronous call paths, so async schemas are unsupported by design.
34
+ *
35
+ * @since 1.0.0-canary.6
36
+ */
37
+ declare function assertValidEventProperties(schema: StandardSchemaV1, eventName: string, properties: unknown): void;
35
38
  //#endregion
36
- export { EventCatalog, EventDefinition, EventsOf, defineEventCatalog };
39
+ export { EventCatalog, EventDefinition, assertValidEventProperties, defineEventCatalog };
@@ -8,5 +8,23 @@
8
8
  function defineEventCatalog(catalog) {
9
9
  return catalog;
10
10
  }
11
+ /**
12
+ * Validates event properties against the catalog schema and throws on mismatch. The
13
+ * validated (possibly transformed) value is deliberately discarded — the tracker always
14
+ * sends the caller's original properties, so a schema transform can never desync callers.
15
+ *
16
+ * @throws Error when validation reports issues, or when the schema validates asynchronously —
17
+ * tracking sits on synchronous call paths, so async schemas are unsupported by design.
18
+ *
19
+ * @since 1.0.0-canary.6
20
+ */
21
+ function assertValidEventProperties(schema, eventName, properties) {
22
+ const result = schema["~standard"].validate(properties);
23
+ if (result instanceof Promise) throw new TypeError(`Event "${eventName}" uses an async schema — event properties must validate synchronously`);
24
+ if (result.issues) {
25
+ const detail = result.issues.map((issue) => issue.message).join("; ");
26
+ throw new Error(`Invalid properties for event "${eventName}": ${detail}`);
27
+ }
28
+ }
11
29
  //#endregion
12
- export { defineEventCatalog };
30
+ export { assertValidEventProperties, defineEventCatalog };
@@ -1,7 +1,6 @@
1
1
  //#region src/core/event-id.d.ts
2
2
  /**
3
- * Client-owned events use this at enqueue time; server-owned events derive an ID
4
- * from the request instead so retries of the same request don't double-count.
3
+ * Stamped on every envelope at track time — destinations that dedupe can key on it.
5
4
  *
6
5
  * @since 0.5.0-canary.4
7
6
  */
@@ -1,7 +1,6 @@
1
1
  //#region src/core/event-id.ts
2
2
  /**
3
- * Client-owned events use this at enqueue time; server-owned events derive an ID
4
- * from the request instead so retries of the same request don't double-count.
3
+ * Stamped on every envelope at track time — destinations that dedupe can key on it.
5
4
  *
6
5
  * @since 0.5.0-canary.4
7
6
  */
@@ -1,6 +1,8 @@
1
- import { CONSENT_CATEGORIES, ConsentCategory, ConsentDecision, ConsentMode, ConsentRecord, ConsentRegion, ConsentStorage, createConsentDecision, isConsentDecision, resolveConsentMode, resolveDefaultConsent } from "./consent.mjs";
2
- import { TrackedEvent } from "./tracked-event.mjs";
1
+ import { CONSENT_CATEGORIES, CONSENT_REGIONS, ConsentCategory, ConsentDecision, ConsentMode, ConsentRecord, ConsentRegion, ConsentStorage, InitialConsent, ResolveDefaultConsentOptions, ResolveEffectiveConsentOptions, STRICTEST_INITIAL_CONSENT, createConsentDecision, isConsentDecision, isConsentRecord, isConsentRegion, isInitialConsent, normalizeConsentDecision, readStoredDecision, resolveConsentMode, resolveDefaultConsent, resolveEffectiveConsent } from "./consent.mjs";
2
+ import { ConsentConfig, defineConsentConfig } from "./consent-config.mjs";
3
+ import { TrackEvent, TrackedEvent, TrackedEventBase } from "./tracked-event.mjs";
3
4
  import { Destination } from "./destination.mjs";
4
- import { EventCatalog, EventDefinition, EventsOf, defineEventCatalog } from "./event-catalog.mjs";
5
+ import { EventCatalog, EventDefinition, assertValidEventProperties, defineEventCatalog } from "./event-catalog.mjs";
6
+ import { readCookieValue } from "./cookie.mjs";
5
7
  import { generateEventId } from "./event-id.mjs";
6
- export { CONSENT_CATEGORIES, type ConsentCategory, type ConsentDecision, type ConsentMode, type ConsentRecord, type ConsentRegion, type ConsentStorage, type Destination, type EventCatalog, type EventDefinition, type EventsOf, type TrackedEvent, createConsentDecision, defineEventCatalog, generateEventId, isConsentDecision, resolveConsentMode, resolveDefaultConsent };
8
+ export { CONSENT_CATEGORIES, CONSENT_REGIONS, type ConsentCategory, type ConsentConfig, type ConsentDecision, type ConsentMode, type ConsentRecord, type ConsentRegion, type ConsentStorage, type Destination, type EventCatalog, type EventDefinition, type InitialConsent, type ResolveDefaultConsentOptions, type ResolveEffectiveConsentOptions, STRICTEST_INITIAL_CONSENT, type TrackEvent, type TrackedEvent, type TrackedEventBase, assertValidEventProperties, createConsentDecision, defineConsentConfig, defineEventCatalog, generateEventId, isConsentDecision, isConsentRecord, isConsentRegion, isInitialConsent, normalizeConsentDecision, readCookieValue, readStoredDecision, resolveConsentMode, resolveDefaultConsent, resolveEffectiveConsent };
@@ -1,4 +1,6 @@
1
- import { CONSENT_CATEGORIES, createConsentDecision, isConsentDecision, resolveConsentMode, resolveDefaultConsent } from "./consent.mjs";
2
- import { defineEventCatalog } from "./event-catalog.mjs";
1
+ import { CONSENT_CATEGORIES, CONSENT_REGIONS, STRICTEST_INITIAL_CONSENT, createConsentDecision, isConsentDecision, isConsentRecord, isConsentRegion, isInitialConsent, normalizeConsentDecision, readStoredDecision, resolveConsentMode, resolveDefaultConsent, resolveEffectiveConsent } from "./consent.mjs";
2
+ import { defineConsentConfig } from "./consent-config.mjs";
3
+ import { readCookieValue } from "./cookie.mjs";
4
+ import { assertValidEventProperties, defineEventCatalog } from "./event-catalog.mjs";
3
5
  import { generateEventId } from "./event-id.mjs";
4
- export { CONSENT_CATEGORIES, createConsentDecision, defineEventCatalog, generateEventId, isConsentDecision, resolveConsentMode, resolveDefaultConsent };
6
+ export { CONSENT_CATEGORIES, CONSENT_REGIONS, STRICTEST_INITIAL_CONSENT, assertValidEventProperties, createConsentDecision, defineConsentConfig, defineEventCatalog, generateEventId, isConsentDecision, isConsentRecord, isConsentRegion, isInitialConsent, normalizeConsentDecision, readCookieValue, readStoredDecision, resolveConsentMode, resolveDefaultConsent, resolveEffectiveConsent };
@@ -1,17 +1,30 @@
1
1
  //#region src/core/tracked-event.d.ts
2
2
  /**
3
- * Envelope every tracker (client/server) builds before handing an event to a destination.
3
+ * Fields shared by every envelope the tracker builds.
4
4
  *
5
- * @since 0.5.0-canary.4
5
+ * @since 1.0.0-canary.6
6
6
  */
7
- interface TrackedEvent {
7
+ interface TrackedEventBase {
8
8
  anonymousId: string;
9
9
  eventId: string;
10
- name: string;
11
- owner: "client" | "server";
12
- props: Record<string, unknown>;
13
10
  timestamp: number;
14
- userId?: string | undefined;
15
11
  }
12
+ /**
13
+ * A catalog-defined event envelope, as handed to destinations.
14
+ *
15
+ * @since 1.0.0-canary.6
16
+ */
17
+ interface TrackEvent extends TrackedEventBase {
18
+ name: string;
19
+ properties: Record<string, unknown>;
20
+ type: "track";
21
+ }
22
+ /**
23
+ * The envelope destinations receive. `type` stays a discriminant so a future kind is an
24
+ * additive union member, not a wire-format break.
25
+ *
26
+ * @since 0.5.0-canary.4
27
+ */
28
+ type TrackedEvent = TrackEvent;
16
29
  //#endregion
17
- export { TrackedEvent };
30
+ export { TrackEvent, TrackedEvent, TrackedEventBase };