@codefast/tracking 0.7.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +235 -105
  3. package/dist/adapters/tanstack-start.d.ts +1 -2
  4. package/dist/adapters/tanstack-start.js +1 -2
  5. package/dist/client/ad-framework-consent.d.ts +1 -2
  6. package/dist/client/ad-framework-consent.js +1 -2
  7. package/dist/client/browser-cookie.d.ts +1 -2
  8. package/dist/client/browser-cookie.js +1 -2
  9. package/dist/client/consent-runtime.d.ts +1 -2
  10. package/dist/client/consent-runtime.js +1 -2
  11. package/dist/client/consent-storage.d.ts +1 -2
  12. package/dist/client/consent-storage.js +1 -2
  13. package/dist/client/consent-withdrawal.d.ts +1 -2
  14. package/dist/client/consent-withdrawal.js +1 -2
  15. package/dist/client/cookie-anonymous-id.d.ts +1 -2
  16. package/dist/client/cookie-anonymous-id.js +1 -2
  17. package/dist/client/create-client-tracker.d.ts +1 -2
  18. package/dist/client/create-client-tracker.js +1 -2
  19. package/dist/client/gpc.d.ts +1 -2
  20. package/dist/client/gpc.js +1 -2
  21. package/dist/client/initial-consent-store.d.ts +1 -2
  22. package/dist/client/initial-consent-store.js +1 -2
  23. package/dist/client/is-analytics-allowed.d.ts +1 -2
  24. package/dist/client/is-analytics-allowed.js +1 -2
  25. package/dist/client/server-persisted-anonymous-id.d.ts +1 -2
  26. package/dist/client/server-persisted-anonymous-id.js +1 -2
  27. package/dist/core/consent-config.d.ts +1 -2
  28. package/dist/core/consent-config.js +1 -2
  29. package/dist/core/consent-receipt.d.ts +1 -2
  30. package/dist/core/consent-receipt.js +1 -2
  31. package/dist/core/consent.d.ts +1 -2
  32. package/dist/core/consent.js +1 -2
  33. package/dist/core/cookie.d.ts +1 -2
  34. package/dist/core/cookie.js +1 -2
  35. package/dist/core/destination.d.ts +1 -2
  36. package/dist/core/destination.js +1 -2
  37. package/dist/core/event-catalog.d.ts +1 -2
  38. package/dist/core/event-catalog.js +1 -2
  39. package/dist/core/event-id.d.ts +1 -2
  40. package/dist/core/event-id.js +1 -2
  41. package/dist/core/tracked-event.d.ts +1 -2
  42. package/dist/core/tracked-event.js +1 -2
  43. package/dist/destinations/ad-consent.d.ts +1 -2
  44. package/dist/destinations/ad-consent.js +1 -2
  45. package/dist/destinations/google-analytics.d.ts +1 -2
  46. package/dist/destinations/google-analytics.js +1 -2
  47. package/dist/destinations/google-consent.d.ts +1 -2
  48. package/dist/destinations/google-consent.js +1 -2
  49. package/dist/destinations/meta.d.ts +1 -2
  50. package/dist/destinations/meta.js +1 -2
  51. package/dist/destinations/microsoft-uet.d.ts +1 -2
  52. package/dist/destinations/microsoft-uet.js +1 -2
  53. package/dist/destinations/shared.d.ts +1 -2
  54. package/dist/destinations/shared.js +1 -2
  55. package/dist/destinations/tiktok.d.ts +1 -2
  56. package/dist/destinations/tiktok.js +1 -2
  57. package/dist/destinations/vercel-analytics.d.ts +1 -2
  58. package/dist/destinations/vercel-analytics.js +1 -2
  59. package/dist/index.d.ts +1 -2
  60. package/dist/index.js +1 -2
  61. package/dist/react/consent-banner.d.ts +1 -2
  62. package/dist/react/consent-banner.js +1 -2
  63. package/dist/react/gtag-consent-bootstrap.d.ts +1 -2
  64. package/dist/react/gtag-consent-bootstrap.js +1 -2
  65. package/dist/react/use-consent.d.ts +1 -2
  66. package/dist/react/use-consent.js +1 -2
  67. package/dist/react/use-google-consent-sync.d.ts +1 -2
  68. package/dist/react/use-google-consent-sync.js +1 -2
  69. package/dist/react/use-initial-consent.d.ts +1 -2
  70. package/dist/react/use-initial-consent.js +1 -2
  71. package/dist/server/anonymous-id-cookie.d.ts +1 -2
  72. package/dist/server/anonymous-id-cookie.js +1 -2
  73. package/dist/server/consent-receipt-store.d.ts +1 -2
  74. package/dist/server/consent-receipt-store.js +1 -2
  75. package/dist/server/consent-receipt.d.ts +1 -2
  76. package/dist/server/consent-receipt.js +1 -2
  77. package/dist/server/initial-consent.d.ts +1 -2
  78. package/dist/server/initial-consent.js +1 -2
  79. package/dist/server/measurement-protocol.d.ts +1 -2
  80. package/dist/server/measurement-protocol.js +1 -2
  81. package/dist/server/region.d.ts +1 -2
  82. package/dist/server/region.js +1 -2
  83. package/dist/server/user-deletion.d.ts +1 -2
  84. package/dist/server/user-deletion.js +1 -2
  85. package/dist/tooling/import-protection.d.ts +1 -2
  86. package/dist/tooling/import-protection.js +1 -2
  87. package/package.json +10 -61
  88. package/dist/adapters/tanstack-start.d.ts.map +0 -1
  89. package/dist/adapters/tanstack-start.js.map +0 -1
  90. package/dist/client/ad-framework-consent.d.ts.map +0 -1
  91. package/dist/client/ad-framework-consent.js.map +0 -1
  92. package/dist/client/browser-cookie.d.ts.map +0 -1
  93. package/dist/client/browser-cookie.js.map +0 -1
  94. package/dist/client/consent-runtime.d.ts.map +0 -1
  95. package/dist/client/consent-runtime.js.map +0 -1
  96. package/dist/client/consent-storage.d.ts.map +0 -1
  97. package/dist/client/consent-storage.js.map +0 -1
  98. package/dist/client/consent-withdrawal.d.ts.map +0 -1
  99. package/dist/client/consent-withdrawal.js.map +0 -1
  100. package/dist/client/cookie-anonymous-id.d.ts.map +0 -1
  101. package/dist/client/cookie-anonymous-id.js.map +0 -1
  102. package/dist/client/create-client-tracker.d.ts.map +0 -1
  103. package/dist/client/create-client-tracker.js.map +0 -1
  104. package/dist/client/gpc.d.ts.map +0 -1
  105. package/dist/client/gpc.js.map +0 -1
  106. package/dist/client/initial-consent-store.d.ts.map +0 -1
  107. package/dist/client/initial-consent-store.js.map +0 -1
  108. package/dist/client/is-analytics-allowed.d.ts.map +0 -1
  109. package/dist/client/is-analytics-allowed.js.map +0 -1
  110. package/dist/client/server-persisted-anonymous-id.d.ts.map +0 -1
  111. package/dist/client/server-persisted-anonymous-id.js.map +0 -1
  112. package/dist/core/consent-config.d.ts.map +0 -1
  113. package/dist/core/consent-config.js.map +0 -1
  114. package/dist/core/consent-receipt.d.ts.map +0 -1
  115. package/dist/core/consent-receipt.js.map +0 -1
  116. package/dist/core/consent.d.ts.map +0 -1
  117. package/dist/core/consent.js.map +0 -1
  118. package/dist/core/cookie.d.ts.map +0 -1
  119. package/dist/core/cookie.js.map +0 -1
  120. package/dist/core/destination.d.ts.map +0 -1
  121. package/dist/core/destination.js.map +0 -1
  122. package/dist/core/event-catalog.d.ts.map +0 -1
  123. package/dist/core/event-catalog.js.map +0 -1
  124. package/dist/core/event-id.d.ts.map +0 -1
  125. package/dist/core/event-id.js.map +0 -1
  126. package/dist/core/tracked-event.d.ts.map +0 -1
  127. package/dist/core/tracked-event.js.map +0 -1
  128. package/dist/destinations/ad-consent.d.ts.map +0 -1
  129. package/dist/destinations/ad-consent.js.map +0 -1
  130. package/dist/destinations/google-analytics.d.ts.map +0 -1
  131. package/dist/destinations/google-analytics.js.map +0 -1
  132. package/dist/destinations/google-consent.d.ts.map +0 -1
  133. package/dist/destinations/google-consent.js.map +0 -1
  134. package/dist/destinations/meta.d.ts.map +0 -1
  135. package/dist/destinations/meta.js.map +0 -1
  136. package/dist/destinations/microsoft-uet.d.ts.map +0 -1
  137. package/dist/destinations/microsoft-uet.js.map +0 -1
  138. package/dist/destinations/shared.d.ts.map +0 -1
  139. package/dist/destinations/shared.js.map +0 -1
  140. package/dist/destinations/tiktok.d.ts.map +0 -1
  141. package/dist/destinations/tiktok.js.map +0 -1
  142. package/dist/destinations/vercel-analytics.d.ts.map +0 -1
  143. package/dist/destinations/vercel-analytics.js.map +0 -1
  144. package/dist/index.d.ts.map +0 -1
  145. package/dist/index.js.map +0 -1
  146. package/dist/react/consent-banner.d.ts.map +0 -1
  147. package/dist/react/consent-banner.js.map +0 -1
  148. package/dist/react/gtag-consent-bootstrap.d.ts.map +0 -1
  149. package/dist/react/gtag-consent-bootstrap.js.map +0 -1
  150. package/dist/react/use-consent.d.ts.map +0 -1
  151. package/dist/react/use-consent.js.map +0 -1
  152. package/dist/react/use-google-consent-sync.d.ts.map +0 -1
  153. package/dist/react/use-google-consent-sync.js.map +0 -1
  154. package/dist/react/use-initial-consent.d.ts.map +0 -1
  155. package/dist/react/use-initial-consent.js.map +0 -1
  156. package/dist/server/anonymous-id-cookie.d.ts.map +0 -1
  157. package/dist/server/anonymous-id-cookie.js.map +0 -1
  158. package/dist/server/consent-receipt-store.d.ts.map +0 -1
  159. package/dist/server/consent-receipt-store.js.map +0 -1
  160. package/dist/server/consent-receipt.d.ts.map +0 -1
  161. package/dist/server/consent-receipt.js.map +0 -1
  162. package/dist/server/initial-consent.d.ts.map +0 -1
  163. package/dist/server/initial-consent.js.map +0 -1
  164. package/dist/server/measurement-protocol.d.ts.map +0 -1
  165. package/dist/server/measurement-protocol.js.map +0 -1
  166. package/dist/server/region.d.ts.map +0 -1
  167. package/dist/server/region.js.map +0 -1
  168. package/dist/server/user-deletion.d.ts.map +0 -1
  169. package/dist/server/user-deletion.js.map +0 -1
  170. package/dist/tooling/import-protection.d.ts.map +0 -1
  171. package/dist/tooling/import-protection.js.map +0 -1
  172. package/src/adapters/tanstack-start.ts +0 -139
  173. package/src/client/ad-framework-consent.ts +0 -88
  174. package/src/client/browser-cookie.ts +0 -16
  175. package/src/client/consent-runtime.ts +0 -82
  176. package/src/client/consent-storage.ts +0 -125
  177. package/src/client/consent-withdrawal.ts +0 -34
  178. package/src/client/cookie-anonymous-id.ts +0 -116
  179. package/src/client/create-client-tracker.ts +0 -174
  180. package/src/client/gpc.ts +0 -15
  181. package/src/client/initial-consent-store.ts +0 -220
  182. package/src/client/is-analytics-allowed.ts +0 -45
  183. package/src/client/server-persisted-anonymous-id.ts +0 -104
  184. package/src/core/consent-config.ts +0 -27
  185. package/src/core/consent-receipt.ts +0 -115
  186. package/src/core/consent.ts +0 -298
  187. package/src/core/cookie.ts +0 -29
  188. package/src/core/destination.ts +0 -29
  189. package/src/core/event-catalog.ts +0 -54
  190. package/src/core/event-id.ts +0 -8
  191. package/src/core/tracked-event.ts +0 -14
  192. package/src/css/consent.css +0 -119
  193. package/src/destinations/ad-consent.ts +0 -29
  194. package/src/destinations/google-analytics.ts +0 -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,116 +0,0 @@
1
- import { writeBrowserCookie } from "#/client/browser-cookie";
2
- import { ONE_YEAR_IN_SECONDS, readCookieValue } from "#/core/cookie";
3
-
4
- /**
5
- * Options for `createCookieAnonymousId`.
6
- *
7
- * @since 0.5.0-canary.6
8
- */
9
- export interface CookieAnonymousIdOptions {
10
- /** Cookie name — must not collide with another cookie on the domain. */
11
- cookieName: string;
12
- /** How long the id survives a return visit. Defaults to one year. */
13
- maxAgeSeconds?: number | undefined;
14
- }
15
-
16
- /**
17
- * A cookie-backed anonymous id handle: lazy minting, expiry refresh, and clearing on withdrawal.
18
- *
19
- * @since 0.5.0-canary.6
20
- */
21
- export interface CookieAnonymousId {
22
- /** Expires the cookie — call when the visitor withdraws tracking consent. */
23
- clear: () => void;
24
- /**
25
- * The existing id **without minting one** — `undefined` when the visitor has none yet.
26
- * Use this to stamp a receipt/decision with the id that already identifies the visitor,
27
- * rather than re-reading the cookie or minting a throwaway that never correlates.
28
- */
29
- current: () => string | undefined;
30
- /** The existing id, or a freshly minted and persisted one. */
31
- getOrCreate: () => string;
32
- /**
33
- * Rolls an *existing* id's expiry forward without ever minting one — safe to call on
34
- * page load for returning consented visitors (the ITP-refresh path), a no-op for
35
- * visitors who never got an id.
36
- */
37
- refresh: () => void;
38
- }
39
-
40
- /**
41
- * A `document.cookie`-backed anonymous id — not `localStorage`-only, so a server-owned
42
- * event can read the same id from the request and correlate to this visitor. Pass
43
- * `getOrCreate` (not the result of calling it) as `ClientTrackerOptions.anonymousId`:
44
- * it's invoked lazily, so the cookie is minted only once an event is actually allowed to
45
- * send, never as an import-time side effect.
46
- *
47
- * @since 0.5.0-canary.6
48
- */
49
- export function createCookieAnonymousId(options: CookieAnonymousIdOptions): CookieAnonymousId {
50
- const { cookieName, maxAgeSeconds = ONE_YEAR_IN_SECONDS } = options;
51
- // Cached after the first getOrCreate() so a callback invoked once per tracked event
52
- // doesn't re-parse the whole cookie header every time — cleared alongside the cookie.
53
- let cachedId: string | undefined;
54
-
55
- return {
56
- clear(): void {
57
- cachedId = undefined;
58
-
59
- if (typeof document === "undefined") {
60
- return;
61
- }
62
-
63
- writeBrowserCookie(cookieName, "", 0);
64
- },
65
- current(): string | undefined {
66
- // Prefer the live cookie — another tab may have minted or cleared it since this
67
- // instance last cached — falling back to the cache only when off the DOM (SSR).
68
- if (typeof document === "undefined") {
69
- return cachedId;
70
- }
71
-
72
- const existing = readCookieValue(document.cookie, cookieName);
73
-
74
- cachedId = existing;
75
-
76
- return existing;
77
- },
78
- getOrCreate(): string {
79
- if (typeof document === "undefined") {
80
- return cachedId ?? crypto.randomUUID();
81
- }
82
-
83
- const existing = readCookieValue(document.cookie, cookieName);
84
-
85
- // Prefer the live cookie over `cachedId` — another tab's withdrawal expires the
86
- // cookie without calling this instance's `clear()`, and a re-grant must not revive
87
- // the pre-withdrawal identity from memory.
88
- if (existing) {
89
- cachedId = existing;
90
-
91
- return existing;
92
- }
93
-
94
- cachedId = undefined;
95
-
96
- const id = crypto.randomUUID();
97
-
98
- writeBrowserCookie(cookieName, id, maxAgeSeconds);
99
- cachedId = id;
100
-
101
- return id;
102
- },
103
- refresh(): void {
104
- if (typeof document === "undefined") {
105
- return;
106
- }
107
-
108
- const existing = readCookieValue(document.cookie, cookieName);
109
-
110
- if (existing) {
111
- cachedId = existing;
112
- writeBrowserCookie(cookieName, existing, maxAgeSeconds);
113
- }
114
- },
115
- };
116
- }
@@ -1,174 +0,0 @@
1
- import type { StandardSchemaV1 } from "@standard-schema/spec";
2
-
3
- import type { Destination } from "#/core/destination";
4
- import type { EventCatalog } from "#/core/event-catalog";
5
- import { assertValidEventProperties } from "#/core/event-catalog";
6
- import { generateEventId } from "#/core/event-id";
7
- import type { TrackedEvent } from "#/core/tracked-event";
8
-
9
- /**
10
- * Context handed to {@link ClientTrackerOptions.onDeliveryError} for one failed delivery.
11
- *
12
- * @since 0.5.0-canary.6
13
- */
14
- export interface DeliveryErrorContext {
15
- destination: Destination;
16
- error: unknown;
17
- event: TrackedEvent;
18
- }
19
-
20
- /**
21
- * `Destination.send` is typed to always return a `Promise`, but that's unenforceable at
22
- * runtime for a third-party/plain-JS destination — one that ignores the contract and
23
- * throws synchronously (or returns a non-`Promise`) must still never break the tracked
24
- * interaction. `Promise.resolve(...)` normalizes a non-`Promise` return; the outer
25
- * try/catch is the only thing that can catch a throw that happens before `send` ever
26
- * gets to return anything. Both failure shapes surface through `onDeliveryError` (itself
27
- * guarded — an observer that throws must not break the interaction either).
28
- */
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 {
55
- try {
56
- void Promise.resolve(destination.onErasure?.(id)).catch(() => {
57
- /* an erasure failure must never break the withdrawal flow */
58
- });
59
- } catch {
60
- /* a sync throw must never break the withdrawal flow */
61
- }
62
- }
63
-
64
- /**
65
- * Options for `createClientTracker`.
66
- *
67
- * @since 0.5.0-canary.4
68
- */
69
- export interface ClientTrackerOptions<Catalog extends EventCatalog> {
70
- /** Invoked per allowed event — defer creating the id (e.g. minting a cookie) until an event is actually allowed to send, never as an import-time side effect. */
71
- anonymousId: () => string;
72
- catalog: Catalog;
73
- destinations: Array<Destination>;
74
- /**
75
- * Consulted before every event — while it returns `false`, only
76
- * `consentRequirement: "exempt"` destinations still receive events, stripped of
77
- * identifiers. Omit to always track.
78
- */
79
- isAnalyticsAllowed?: (() => boolean) | undefined;
80
- /**
81
- * Consulted before an `exempt` destination receives an event while the gate is closed.
82
- * ePrivacy audience-measurement exemption is jurisdiction-dependent (spec-destinations
83
- * §2), so it MUST be gateable per region rather than assumed global — return `false`
84
- * where exemption is not defensible and even exempt sinks are withheld. Omit to treat
85
- * exempt destinations as exempt everywhere.
86
- */
87
- isExemptionAllowed?: (() => boolean) | undefined;
88
- /**
89
- * Notified once per failed delivery (a destination throwing or rejecting) so a consumer
90
- * can meter the failure — the tracker still swallows it so tracking never breaks the
91
- * interaction. Wire it to a monitor in production.
92
- */
93
- onDeliveryError?: ((context: DeliveryErrorContext) => void) | undefined;
94
- }
95
-
96
- /**
97
- * A client-side tracker delivering catalog-validated events to destinations, plus erasure on withdrawal.
98
- *
99
- * @since 0.5.0-canary.4
100
- */
101
- export interface ClientTracker<Catalog extends EventCatalog> {
102
- /**
103
- * Runs each destination's {@link Destination.onErasure} once on withdrawal (spec-data-subject-rights
104
- * DSR-V2), passing the subject id to erase. Failures are swallowed so a destination that
105
- * throws never breaks the withdrawal flow.
106
- */
107
- erase: (id: string) => void;
108
- track: <Name extends keyof Catalog & string>(
109
- name: Name,
110
- properties: StandardSchemaV1.InferOutput<Catalog[Name]["schema"]>,
111
- ) => void;
112
- }
113
-
114
- /**
115
- * Creates a consent-gated tracker that validates each event against the catalog and fans it out to destinations.
116
- *
117
- * @since 0.5.0-canary.4
118
- */
119
- export function createClientTracker<Catalog extends EventCatalog>(
120
- options: ClientTrackerOptions<Catalog>,
121
- ): ClientTracker<Catalog> {
122
- // The exempt lane only carries what a cookieless sink may see — identifier-free counts.
123
- const exemptDestinations = options.destinations.filter((destination) => destination.consentRequirement === "exempt");
124
-
125
- return {
126
- erase(id) {
127
- for (const destination of options.destinations) {
128
- eraseInDestination(destination, id);
129
- }
130
- },
131
- track(name, properties) {
132
- // noUncheckedIndexedAccess types this as possibly undefined; the check also guards
133
- // callers who bypass the catalog key type with an `as` cast.
134
- const definition = options.catalog[name];
135
-
136
- if (!definition) {
137
- throw new Error(`Unknown event: ${String(name)}`);
138
- }
139
-
140
- // Forward the parsed output (not the raw input) so unknown keys cannot ride along.
141
- const validatedProperties = assertValidEventProperties(definition.schema, name, properties);
142
-
143
- // The gate runs per event (not at creation) so a consent change mid-session applies immediately.
144
- const isAllowed = options.isAnalyticsAllowed?.() !== false;
145
-
146
- // While gated, exempt sinks still receive identifier-free events — but only where
147
- // exemption is defensible (spec-destinations §2); a `false` here withholds them too.
148
- const activeDestinations = isAllowed
149
- ? options.destinations
150
- : options.isExemptionAllowed?.() === false
151
- ? []
152
- : exemptDestinations;
153
-
154
- if (activeDestinations.length === 0) {
155
- return;
156
- }
157
-
158
- const event: TrackedEvent = {
159
- // Gated events ship identifier-free: no anonymousId is resolved, so none is ever
160
- // minted as a side effect.
161
- anonymousId: isAllowed ? options.anonymousId() : "",
162
- eventId: generateEventId(),
163
- name,
164
- properties: validatedProperties as Record<string, unknown>,
165
- timestamp: Date.now(),
166
- type: "track",
167
- };
168
-
169
- for (const destination of activeDestinations) {
170
- sendToDestination(destination, event, options.onDeliveryError);
171
- }
172
- },
173
- };
174
- }
package/src/client/gpc.ts DELETED
@@ -1,15 +0,0 @@
1
- interface NavigatorWithGpc extends Navigator {
2
- globalPrivacyControl?: boolean | undefined;
3
- }
4
-
5
- /**
6
- * Global Privacy Control isn't in lib.dom yet, hence the local interface extension.
7
- * CCPA/CPRA requires honoring this as an opt-out signal even under the opt-out default.
8
- * Guarded so SSR renders (where the module is reachable) read `false`, not a crash on
9
- * runtimes without a global `navigator`.
10
- *
11
- * @since 0.5.0-canary.4
12
- */
13
- export function hasGlobalPrivacyControlSignal(): boolean {
14
- return typeof navigator !== "undefined" && (navigator as NavigatorWithGpc).globalPrivacyControl === true;
15
- }
@@ -1,220 +0,0 @@
1
- import type { InitialConsent } from "#/core/consent";
2
- import { isInitialConsent, STRICTEST_INITIAL_CONSENT } from "#/core/consent";
3
-
4
- /**
5
- * External-store view of the visitor's region default — the strictest value until the
6
- * server lane answers, then the resolved one.
7
- *
8
- * @since 0.5.0-canary.6
9
- */
10
- export interface InitialConsentSnapshot {
11
- /** The region-correct default once resolved; {@link STRICTEST_INITIAL_CONSENT} until then. */
12
- initialConsent: InitialConsent;
13
- /**
14
- * True once a usable default is published — either a successful server answer or a
15
- * fail-closed fallback. A failed fetch still sets this so consent UI can render, but
16
- * does not lock the session: resolution stays retryable.
17
- */
18
- isResolved: boolean;
19
- }
20
-
21
- /**
22
- * Options for `createInitialConsentStore`.
23
- *
24
- * @since 0.5.0-canary.6
25
- */
26
- export interface InitialConsentStoreOptions {
27
- /**
28
- * The per-visitor server lane — typically a server function wrapping
29
- * `resolveInitialConsentFromRequest`. Prerendered/CDN-cached HTML can carry nothing
30
- * region-specific, so this is the only place the region-correct default may come from.
31
- */
32
- resolve: () => Promise<InitialConsent>;
33
- /**
34
- * `sessionStorage` key caching the resolved value, so only the first page load of a
35
- * session pays the round trip — omit to resolve once per page load instead. Cached
36
- * values are re-validated with `isInitialConsent` before use.
37
- */
38
- sessionStorageKey?: string | undefined;
39
- }
40
-
41
- /**
42
- * `useSyncExternalStore`-shaped — pass `subscribe`/`getSnapshot`/`getServerSnapshot`
43
- * straight through, or use the `useInitialConsent` hook from `@codefast/tracking/react`.
44
- *
45
- * @since 0.5.0-canary.6
46
- */
47
- export interface InitialConsentStore {
48
- /**
49
- * Kicks off region resolution (at most one in-flight request; a success is sticky for
50
- * the store's lifetime). Call it early — e.g. at router creation, window-guarded — so
51
- * the round trip overlaps hydration instead of waiting for the first effect.
52
- */
53
- ensureResolved: () => void;
54
- getServerSnapshot: () => InitialConsentSnapshot;
55
- getSnapshot: () => InitialConsentSnapshot;
56
- /** Test seam — clears resolved state, retry listeners, and the session cache. */
57
- reset: () => void;
58
- subscribe: (listener: () => void) => () => void;
59
- }
60
-
61
- const SERVER_SNAPSHOT: InitialConsentSnapshot = {
62
- initialConsent: STRICTEST_INITIAL_CONSENT,
63
- isResolved: false,
64
- };
65
-
66
- /**
67
- * The client half of the server-resolved consent lane: single-flight resolution over the
68
- * given server function, an optional per-session cache, fail-closed publishing on error
69
- * (consent UI still renders, under the strictest default), and a retry the next time the
70
- * tab becomes visible — so one failed request never locks the whole SPA session.
71
- *
72
- * @since 0.5.0-canary.6
73
- */
74
- export function createInitialConsentStore(options: InitialConsentStoreOptions): InitialConsentStore {
75
- const listeners = new Set<() => void>();
76
-
77
- let snapshot: InitialConsentSnapshot = SERVER_SNAPSHOT;
78
- let isFetchInFlight = false;
79
- /** Sticky only after a successful resolve (or session-cache hit) — failures stay retryable. */
80
- let hasResolvedSuccessfully = false;
81
-
82
- function notify(): void {
83
- for (const listener of listeners) {
84
- listener();
85
- }
86
- }
87
-
88
- // add/removeEventListener dedupe an identical listener, so no armed-flag is needed.
89
- function stopResolveRetry(): void {
90
- if (typeof window === "undefined") {
91
- return;
92
- }
93
-
94
- document.removeEventListener("visibilitychange", onResolveRetryResume);
95
- window.removeEventListener("pageshow", onResolveRetryResume);
96
- window.removeEventListener("online", onResolveRetryResume);
97
- }
98
-
99
- function onResolveRetryResume(): void {
100
- if (hasResolvedSuccessfully) {
101
- stopResolveRetry();
102
-
103
- return;
104
- }
105
-
106
- if (document.visibilityState === "visible") {
107
- ensureResolved();
108
- }
109
- }
110
-
111
- /**
112
- * After a failed fetch, retry when the tab becomes visible again or connectivity
113
- * returns (coalesced by in-flight) — a visitor who never leaves the tab must not stay
114
- * fail-closed for the whole session over one network blip.
115
- */
116
- function scheduleResolveRetry(): void {
117
- if (typeof window === "undefined") {
118
- return;
119
- }
120
-
121
- document.addEventListener("visibilitychange", onResolveRetryResume);
122
- window.addEventListener("pageshow", onResolveRetryResume);
123
- window.addEventListener("online", onResolveRetryResume);
124
- }
125
-
126
- function publishResolved(initialConsent: InitialConsent): void {
127
- hasResolvedSuccessfully = true;
128
- snapshot = { initialConsent, isResolved: true };
129
- stopResolveRetry();
130
- notify();
131
- }
132
-
133
- /** Fail-closed UI without permanently locking the session against a later retry. */
134
- function publishFailClosed(): void {
135
- snapshot = { initialConsent: STRICTEST_INITIAL_CONSENT, isResolved: true };
136
- notify();
137
- }
138
-
139
- function readSessionCache(): InitialConsent | undefined {
140
- if (options.sessionStorageKey === undefined) {
141
- return undefined;
142
- }
143
-
144
- try {
145
- const raw = window.sessionStorage.getItem(options.sessionStorageKey);
146
- const parsed: unknown = raw === null ? undefined : JSON.parse(raw);
147
-
148
- return isInitialConsent(parsed) ? parsed : undefined;
149
- } catch {
150
- return undefined;
151
- }
152
- }
153
-
154
- function writeSessionCache(resolved: InitialConsent): void {
155
- if (options.sessionStorageKey === undefined) {
156
- return;
157
- }
158
-
159
- try {
160
- window.sessionStorage.setItem(options.sessionStorageKey, JSON.stringify(resolved));
161
- } catch {
162
- /* private mode / quota — resolve again next page load */
163
- }
164
- }
165
-
166
- function ensureResolved(): void {
167
- if (hasResolvedSuccessfully || isFetchInFlight || typeof window === "undefined") {
168
- return;
169
- }
170
-
171
- const cached = readSessionCache();
172
-
173
- if (cached) {
174
- publishResolved(cached);
175
-
176
- return;
177
- }
178
-
179
- isFetchInFlight = true;
180
-
181
- // Promise.resolve().then(...) folds a synchronously throwing resolver into the same
182
- // fail-closed path — tracking must never break the caller (a React mount effect).
183
- Promise.resolve()
184
- .then(() => options.resolve())
185
- .then((resolved) => {
186
- writeSessionCache(resolved);
187
- publishResolved(resolved);
188
- })
189
- .catch(() => {
190
- publishFailClosed();
191
- scheduleResolveRetry();
192
- })
193
- .finally(() => {
194
- isFetchInFlight = false;
195
- });
196
- }
197
-
198
- return {
199
- ensureResolved,
200
- getServerSnapshot: () => SERVER_SNAPSHOT,
201
- getSnapshot: () => snapshot,
202
- reset(): void {
203
- stopResolveRetry();
204
- snapshot = SERVER_SNAPSHOT;
205
- isFetchInFlight = false;
206
- hasResolvedSuccessfully = false;
207
-
208
- if (typeof window !== "undefined" && options.sessionStorageKey !== undefined) {
209
- window.sessionStorage.removeItem(options.sessionStorageKey);
210
- }
211
- },
212
- subscribe(listener: () => void): () => void {
213
- listeners.add(listener);
214
-
215
- return () => {
216
- listeners.delete(listener);
217
- };
218
- },
219
- };
220
- }
@@ -1,45 +0,0 @@
1
- import type { ConsentMode, ConsentStorage } from "#/core/consent";
2
- import { resolveEffectiveConsent } from "#/core/consent";
3
- import type { ConsentConfig } from "#/core/consent-config";
4
-
5
- /**
6
- * Options for `createIsAnalyticsAllowed`.
7
- *
8
- * @since 0.5.0-canary.6
9
- */
10
- export interface IsAnalyticsAllowedOptions {
11
- /** Must be the same object `useConsent` receives — one config, every surface. */
12
- config: ConsentConfig;
13
- /**
14
- * Re-read each call. Pass `hasGlobalPrivacyControlSignal` from `@codefast/tracking/client`
15
- * (or a wrapper) so GPC changes apply without recreating the gate.
16
- */
17
- hasGlobalPrivacyControlSignal?: (() => boolean) | undefined;
18
- /** Re-read each call so a post-hydration region resolve can win. */
19
- getMode: () => ConsentMode;
20
- /** Must be the same storage instance `useConsent` subscribes to. */
21
- storage: ConsentStorage;
22
- }
23
-
24
- /**
25
- * Non-React mirror of `useConsent`'s `isAnalyticsAllowed` — pass the returned function as
26
- * `createClientTracker({ isAnalyticsAllowed })` so the pipeline and the banner share one rule.
27
- *
28
- * @since 0.5.0-canary.6
29
- */
30
- export function createIsAnalyticsAllowed(options: IsAnalyticsAllowedOptions): () => boolean {
31
- const { config, getMode, storage } = options;
32
- const readGpc = options.hasGlobalPrivacyControlSignal ?? (() => false);
33
-
34
- return (): boolean => {
35
- const effectiveConsent = resolveEffectiveConsent({
36
- hasGlobalPrivacyControlSignal: readGpc(),
37
- mode: getMode(),
38
- policyVersion: config.policyVersion,
39
- requestedCategories: config.requestedCategories,
40
- storage,
41
- });
42
-
43
- return effectiveConsent.analytics;
44
- };
45
- }
@@ -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
- }