@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,29 +0,0 @@
1
- import type { ConsentDecision } from "#/core/consent";
2
-
3
- /**
4
- * The normalized two-lever ad-platform consent state derived from one `{ ads, analytics }`
5
- * decision (spec-destinations §5): `analytics` drives whether events transmit at all, and
6
- * `ads` drives Limited Data Use. The levers are independent — a US opt-out (`ads: false`)
7
- * restricts to LDU but MUST NOT withhold first-party `analytics` (spec-consent §3). Every
8
- * ad destination consumes this same shape so per-vendor mappings cannot drift.
9
- *
10
- * @since 0.5.0-canary.6
11
- */
12
- export interface AdConsentState {
13
- /** `ads` denied → the platform must restrict to Limited Data Use (Meta/TikTok LDU, UET `ad_storage` denied). */
14
- limitedDataUse: boolean;
15
- /** `analytics` granted → events may transmit; denied → hold/revoke and send nothing. */
16
- transmissionAllowed: boolean;
17
- }
18
-
19
- /**
20
- * Normalizes a package `ConsentDecision` to the vendor-agnostic {@link AdConsentState}.
21
- *
22
- * @since 0.5.0-canary.6
23
- */
24
- export function toAdConsentState(decision: ConsentDecision): AdConsentState {
25
- return {
26
- limitedDataUse: !decision.ads,
27
- transmissionAllowed: decision.analytics,
28
- };
29
- }
@@ -1,304 +0,0 @@
1
- import type { ConsentDecision } from "#/core/consent";
2
- import type { ConsentConfig } from "#/core/consent-config";
3
- import type { Destination } from "#/core/destination";
4
- import type { GoogleConsentParams } from "#/destinations/google-consent";
5
- import {
6
- buildGoogleConsentBootstrapPreamble,
7
- DEFAULT_DATA_LAYER_NAME,
8
- ensureDataLayer,
9
- toGoogleConsentParams,
10
- warnUnlessGa4EventName,
11
- } from "#/destinations/google-consent";
12
- import type { FlatPropertyValue } from "#/destinations/shared";
13
- import { flattenEventProps } from "#/destinations/shared";
14
-
15
- const GTAG_SCRIPT_BASE_URL = "https://www.googletagmanager.com/gtag/js";
16
-
17
- type GtagPropertyValue = FlatPropertyValue;
18
-
19
- /**
20
- * All signatures share one `gtag` global, so they must live in a single overloaded type —
21
- * two separate `declare global` augmentations with different signatures for the same
22
- * property is a TS error, not a merge.
23
- *
24
- * @since 0.5.0-canary.6
25
- */
26
- export type GtagFunction = {
27
- (command: "config", targetId: string, params?: Record<string, GtagPropertyValue>): void;
28
- (command: "consent", action: "default" | "update", params: GoogleConsentParams): void;
29
- (command: "event", eventName: string, params?: Record<string, GtagPropertyValue>): void;
30
- (command: "js", startDate: Date): void;
31
- (command: "set", params: Record<string, GtagPropertyValue>): void;
32
- (command: "set", key: string, value: boolean): void;
33
- };
34
-
35
- declare global {
36
- interface Window {
37
- dataLayer?: Array<unknown>;
38
- gtag?: GtagFunction;
39
- }
40
- }
41
-
42
- function gtagScriptSrc(gaMeasurementId: string, dataLayerName: string): string {
43
- const url = new URL(GTAG_SCRIPT_BASE_URL);
44
-
45
- url.searchParams.set("id", gaMeasurementId);
46
-
47
- if (dataLayerName !== DEFAULT_DATA_LAYER_NAME) {
48
- // gtag.js's `l` param names the queue array — must match the stub that pushes into it.
49
- url.searchParams.set("l", dataLayerName);
50
- }
51
-
52
- return url.toString();
53
- }
54
-
55
- /**
56
- * Options for `ensureGtag`.
57
- *
58
- * @since 0.5.0-canary.6
59
- */
60
- export interface EnsureGtagOptions {
61
- /**
62
- * Name of the queue array on `window`. Defaults to `"dataLayer"`. Must match across
63
- * `ensureGtag` / `loadGtagScript` / `buildGtagConsentBootstrapScript` for one page.
64
- */
65
- dataLayerName?: string | undefined;
66
- }
67
-
68
- /**
69
- * Ensures the standard gtag.js queueing stub exists so consent commands can be issued
70
- * before the tag itself loads — gtag.js replays the queue in order once it boots.
71
- *
72
- * @since 0.5.0-canary.6
73
- */
74
- export function ensureGtag(options: EnsureGtagOptions = {}): GtagFunction | undefined {
75
- if (typeof window === "undefined") {
76
- return undefined;
77
- }
78
-
79
- const dataLayerName = options.dataLayerName ?? DEFAULT_DATA_LAYER_NAME;
80
-
81
- ensureDataLayer(dataLayerName);
82
-
83
- // First stub wins — recreating would orphan commands already queued on another layer.
84
- // Callers must pass the same dataLayerName for every helper on the page.
85
- window.gtag ??= function gtag() {
86
- ensureDataLayer(dataLayerName)?.push(arguments);
87
- } as GtagFunction;
88
-
89
- return window.gtag;
90
- }
91
-
92
- /**
93
- * Options for `loadGtagScript`.
94
- *
95
- * @since 0.5.0-canary.6
96
- */
97
- export interface LoadGtagScriptOptions {
98
- /**
99
- * Name of the queue array on `window`. Defaults to `"dataLayer"` — must match the
100
- * bootstrap / `ensureGtag` call that already applied Consent Mode.
101
- */
102
- dataLayerName?: string | undefined;
103
- /** Forwarded as `gtag('config', id, { debug_mode: true })` for GA4 DebugView. */
104
- debugMode?: boolean | undefined;
105
- /** Google Analytics 4 Measurement ID (e.g. `"G-XXXXXXX"`). */
106
- gaMeasurementId: string;
107
- /**
108
- * CSP nonce applied to the injected gtag.js `<script>` element. The app must also put
109
- * the same nonce on any inline bootstrap `<script>` that runs `buildGtagConsentBootstrapScript`.
110
- */
111
- nonce?: string | undefined;
112
- }
113
-
114
- /**
115
- * Loads gtag.js on demand — idempotent (a second call is a no-op) and reuses any
116
- * existing `dataLayer`/`gtag` stub instead of clobbering it. Queues `js`/`config` before
117
- * appending the script tag, so gtag.js replays them under the caller's already-applied
118
- * consent state once it boots. Prefer `buildGtagConsentBootstrapScript` for page load
119
- * (advanced Consent Mode always injects the tag after the default); use this when the
120
- * bootstrap did not run, or as an idempotent safety net after a runtime grant.
121
- *
122
- * @since 0.5.0-canary.6
123
- */
124
- export function loadGtagScript(options: LoadGtagScriptOptions): void {
125
- if (typeof document === "undefined" || document.querySelector(`script[src^="${GTAG_SCRIPT_BASE_URL}"]`) !== null) {
126
- return;
127
- }
128
-
129
- const dataLayerName = options.dataLayerName ?? DEFAULT_DATA_LAYER_NAME;
130
- const gtag = ensureGtag({ dataLayerName });
131
-
132
- if (!gtag) {
133
- return;
134
- }
135
-
136
- gtag("js", new Date());
137
-
138
- if (options.debugMode === true) {
139
- gtag("config", options.gaMeasurementId, { debug_mode: true });
140
- } else {
141
- gtag("config", options.gaMeasurementId);
142
- }
143
-
144
- const script = document.createElement("script");
145
-
146
- script.async = true;
147
- script.src = gtagScriptSrc(options.gaMeasurementId, dataLayerName);
148
-
149
- if (options.nonce !== undefined) {
150
- script.nonce = options.nonce;
151
- }
152
-
153
- document.head.append(script);
154
- }
155
-
156
- /**
157
- * Expires Google's `_ga` / `_ga_*` cookies on `path=/` and the current host's parent
158
- * domain. Consent Mode stops using them once denied but never removes them — call from
159
- * a consent-withdrawal handler so a revoke does not leave identifier cookies behind.
160
- *
161
- * @since 0.5.0-canary.6
162
- */
163
- export function clearGoogleAnalyticsCookies(): void {
164
- if (typeof document === "undefined") {
165
- return;
166
- }
167
-
168
- const { hostname } = globalThis.location;
169
-
170
- for (const cookie of document.cookie.split("; ")) {
171
- const name = cookie.split("=")[0];
172
-
173
- if (name !== undefined && (name === "_ga" || name.startsWith("_ga_"))) {
174
- // GA sets its cookies on the broadest domain it can reach — expire both variants.
175
- document.cookie = `${name}=; path=/; max-age=0`;
176
- document.cookie = `${name}=; path=/; max-age=0; domain=.${hostname}`;
177
- }
178
- }
179
- }
180
-
181
- /**
182
- * Google Consent Mode v2's "update" signal — call whenever the visitor's effective
183
- * consent changes (a banner decision, or one synced from another tab), so already-loaded
184
- * GA4/Ads tags pick up the change without a page reload.
185
- *
186
- * @since 0.5.0-canary.4
187
- */
188
- export function updateGoogleConsent(decision: ConsentDecision, options: EnsureGtagOptions = {}): void {
189
- ensureGtag(options)?.("consent", "update", toGoogleConsentParams(decision));
190
- }
191
-
192
- /**
193
- * Options for `buildGtagConsentBootstrapScript`.
194
- *
195
- * @since 0.5.0-canary.6
196
- */
197
- export interface GtagConsentBootstrapOptions {
198
- /** The same object `useConsent` receives — the bootstrap reads its `storageKey` and `policyVersion`. */
199
- config: ConsentConfig;
200
- /**
201
- * Name of the queue array on `window`. Defaults to `"dataLayer"`. Must match
202
- * `loadGtagScript` / `ensureGtag` if those run later on the same page.
203
- */
204
- dataLayerName?: string | undefined;
205
- /**
206
- * Consent to apply when nothing valid is stored yet. Embedded as a literal — bake the
207
- * strictest default on cached/shared HTML; upgrade after hydration via the private
208
- * server-fn lane + `updateGoogleConsent`.
209
- */
210
- defaultConsent: ConsentDecision;
211
- /** Forwarded as `gtag('config', id, { debug_mode: true })` after the consent default. */
212
- debugMode?: boolean | undefined;
213
- /** Google Analytics 4 Measurement ID (e.g. `"G-XXXXXXX"`). */
214
- gaMeasurementId: string;
215
- /**
216
- * CSP nonce written onto the *injected* gtag.js `<script>` element inside the generated
217
- * source. The host `<script dangerouslySetInnerHTML={…}>` that embeds this string must
218
- * receive the same nonce from the app (this helper only returns JS text, not a React node).
219
- */
220
- nonce?: string | undefined;
221
- }
222
-
223
- /**
224
- * Builds the literal JS source for a `<script dangerouslySetInnerHTML>` mounted in
225
- * `<head>`, before hydration: applies Consent Mode v2's default signal from the visitor's
226
- * stored decision (falling back to literal `defaultConsent` when none is stored yet),
227
- * then always loads gtag.js (advanced Consent Mode) so cookieless pings / modeling can
228
- * run even when storage is denied. A runtime decision change needs `updateGoogleConsent`
229
- * so the already-loaded tag picks up the grant/deny — this only covers the page-load
230
- * default + script injection.
231
- *
232
- * @since 0.5.0-canary.6
233
- */
234
- export function buildGtagConsentBootstrapScript(options: GtagConsentBootstrapOptions): string {
235
- const {
236
- config,
237
- dataLayerName = DEFAULT_DATA_LAYER_NAME,
238
- defaultConsent,
239
- debugMode,
240
- gaMeasurementId,
241
- nonce,
242
- } = options;
243
-
244
- const gtagScriptUrl = gtagScriptSrc(gaMeasurementId, dataLayerName);
245
- const configArgs =
246
- debugMode === true ? `${JSON.stringify(gaMeasurementId)}, { debug_mode: true }` : JSON.stringify(gaMeasurementId);
247
- const nonceAssignment = nonce === undefined ? "" : `gtagScript.nonce = ${JSON.stringify(nonce)};`;
248
- const preamble = buildGoogleConsentBootstrapPreamble({
249
- consentStorageKey: config.storageKey,
250
- dataLayerName,
251
- defaultConsent,
252
- policyVersion: config.policyVersion,
253
- });
254
-
255
- // Advanced Consent Mode: consent default first, then always load the tag (even when denied).
256
- return `${preamble}
257
- gtag("js", new Date());
258
- gtag("config", ${configArgs});
259
- var gtagScript = document.createElement("script");
260
- gtagScript.async = true;
261
- gtagScript.src = ${JSON.stringify(gtagScriptUrl)};
262
- ${nonceAssignment}
263
- document.head.appendChild(gtagScript);
264
- `;
265
- }
266
-
267
- /**
268
- * Options for `createGoogleAnalyticsDestination`.
269
- *
270
- * @since 0.5.0-canary.4
271
- */
272
- export interface GoogleAnalyticsDestinationOptions {
273
- name?: string | undefined;
274
- }
275
-
276
- /**
277
- * Forwards catalog events to `window.gtag` as GA4 custom events. Page views are not this
278
- * destination's job: `gtag('config', ...)` sends the initial page_view and GA4's Enhanced
279
- * Measurement tracks SPA history changes. Requires the gtag.js snippet plus
280
- * `gtag('config', measurementId)` mounted once by the app (see the consent bootstrap) —
281
- * gtag.js owns its own batching and unload delivery.
282
- *
283
- * @since 0.5.0-canary.4
284
- */
285
- export function createGoogleAnalyticsDestination(options: GoogleAnalyticsDestinationOptions = {}): Destination {
286
- const name = options.name ?? "google-analytics";
287
-
288
- return {
289
- name,
290
- // Synchronous today, but declared async so a throw here rejects the returned Promise
291
- // instead of escaping as a synchronous throw — matches Destination.send's contract.
292
- async send(event) {
293
- if (typeof window === "undefined" || typeof window.gtag !== "function") {
294
- return;
295
- }
296
-
297
- if (!warnUnlessGa4EventName(name, event.name)) {
298
- return;
299
- }
300
-
301
- window.gtag("event", event.name, flattenEventProps(event.properties));
302
- },
303
- };
304
- }
@@ -1,166 +0,0 @@
1
- import type { ConsentCategory, ConsentDecision } from "#/core/consent";
2
- import { CONSENT_CATEGORIES } from "#/core/consent";
3
-
4
- /**
5
- * gtag.js/gtm.js's default queue-array name — shared so the gtag and GTM helpers cannot disagree.
6
- *
7
- * @since 0.5.0-canary.6
8
- */
9
- export const DEFAULT_DATA_LAYER_NAME = "dataLayer";
10
-
11
- type GoogleConsentState = "denied" | "granted";
12
-
13
- /**
14
- * Consent Mode v2 params issued via `gtag('consent', …)` — shared by the gtag and GTM
15
- * bootstraps so signal mapping cannot drift between them.
16
- *
17
- * @since 0.5.0-canary.6
18
- */
19
- export interface GoogleConsentParams {
20
- ad_personalization: GoogleConsentState;
21
- ad_storage: GoogleConsentState;
22
- ad_user_data: GoogleConsentState;
23
- analytics_storage: GoogleConsentState;
24
- region?: ReadonlyArray<string> | undefined;
25
- wait_for_update?: number | undefined;
26
- }
27
-
28
- /**
29
- * Which per-category decision each Consent Mode v2 signal follows: `analytics` drives
30
- * `analytics_storage`; `ads` drives all three ads signals together.
31
- */
32
- const GOOGLE_CONSENT_SIGNAL_CATEGORIES = {
33
- ad_personalization: "ads",
34
- ad_storage: "ads",
35
- ad_user_data: "ads",
36
- analytics_storage: "analytics",
37
- } as const satisfies Record<
38
- "ad_personalization" | "ad_storage" | "ad_user_data" | "analytics_storage",
39
- ConsentCategory
40
- >;
41
-
42
- type GoogleConsentSignal = keyof typeof GOOGLE_CONSENT_SIGNAL_CATEGORIES;
43
-
44
- /**
45
- * Maps a package `ConsentDecision` onto Consent Mode v2's four storage signals.
46
- *
47
- * @since 0.5.0-canary.6
48
- */
49
- export function toGoogleConsentParams(decision: ConsentDecision): GoogleConsentParams {
50
- // Derived from the signal map (not hand-written per signal) so the runtime params and
51
- // the bootstrap fragment below can never disagree.
52
- return {
53
- ad_personalization: decision[GOOGLE_CONSENT_SIGNAL_CATEGORIES.ad_personalization] ? "granted" : "denied",
54
- ad_storage: decision[GOOGLE_CONSENT_SIGNAL_CATEGORIES.ad_storage] ? "granted" : "denied",
55
- ad_user_data: decision[GOOGLE_CONSENT_SIGNAL_CATEGORIES.ad_user_data] ? "granted" : "denied",
56
- analytics_storage: decision[GOOGLE_CONSENT_SIGNAL_CATEGORIES.analytics_storage] ? "granted" : "denied",
57
- };
58
- }
59
-
60
- /** JS fragment that validates a stored `ConsentRecord.decision` shape inside a bootstrap. */
61
- function consentDecisionShapeCheckExpression(): string {
62
- return CONSENT_CATEGORIES.map((category) => `typeof record.decision[${JSON.stringify(category)}] === "boolean"`).join(
63
- " && ",
64
- );
65
- }
66
-
67
- /**
68
- * JS object-literal fragment for `gtag("consent", "default", { … })` — generated from
69
- * {@link GOOGLE_CONSENT_SIGNAL_CATEGORIES} so runtime and bootstrap stay aligned.
70
- */
71
- function consentSignalAssignmentsExpression(): string {
72
- return (Object.keys(GOOGLE_CONSENT_SIGNAL_CATEGORIES) as Array<GoogleConsentSignal>)
73
- .map((signal) => {
74
- const category = GOOGLE_CONSENT_SIGNAL_CATEGORIES[signal];
75
-
76
- return `${signal}: consent.${category} ? "granted" : "denied"`;
77
- })
78
- .join(",\n ");
79
- }
80
-
81
- /**
82
- * Options for `buildGoogleConsentBootstrapPreamble`.
83
- *
84
- * @since 0.5.0-canary.6
85
- */
86
- export interface GoogleConsentBootstrapPreambleOptions {
87
- /** localStorage key holding the package's `ConsentRecord`. */
88
- consentStorageKey: string;
89
- dataLayerName: string;
90
- /** Literal fallback when nothing valid is stored — baked into the script as JSON. */
91
- defaultConsent: ConsentDecision;
92
- policyVersion: string;
93
- }
94
-
95
- /**
96
- * Shared head of the gtag and GTM consent bootstraps: dataLayer init, `gtag()` stub,
97
- * stored-decision read (policy-version + shape checked), and the Consent Mode v2
98
- * "default" signal. The builders append only their tag-specific tail, so the consent
99
- * logic cannot drift between them.
100
- *
101
- * @since 0.5.0-canary.6
102
- */
103
- export function buildGoogleConsentBootstrapPreamble(options: GoogleConsentBootstrapPreambleOptions): string {
104
- const dataLayerAccess = `window[${JSON.stringify(options.dataLayerName)}]`;
105
-
106
- return `
107
- ${dataLayerAccess} = ${dataLayerAccess} || [];
108
- function gtag(){${dataLayerAccess}.push(arguments);}
109
- var storedConsent = null;
110
- try {
111
- var record = JSON.parse(window.localStorage.getItem(${JSON.stringify(options.consentStorageKey)}));
112
- if (record && record.policyVersion === ${JSON.stringify(options.policyVersion)} && record.decision && ${consentDecisionShapeCheckExpression()}) {
113
- storedConsent = record.decision;
114
- }
115
- } catch (e) {}
116
- var consent = storedConsent || (${JSON.stringify(options.defaultConsent)});
117
- gtag("consent", "default", {
118
- ${consentSignalAssignmentsExpression()}
119
- });`;
120
- }
121
-
122
- /**
123
- * Reads or creates a named `window[dataLayerName]` queue array.
124
- *
125
- * @since 0.5.0-canary.6
126
- */
127
- export function ensureDataLayer(dataLayerName: string): Array<unknown> | undefined {
128
- if (typeof window === "undefined") {
129
- return undefined;
130
- }
131
-
132
- const existing = Reflect.get(window, dataLayerName);
133
- const layer: Array<unknown> = Array.isArray(existing) ? existing : [];
134
-
135
- Reflect.set(window, dataLayerName, layer);
136
-
137
- return layer;
138
- }
139
-
140
- /**
141
- * GA4's event-name rules (letter start, letters/digits/underscores only, ≤40 chars).
142
- * Catalog `track` names that fail this are accepted by gtag/MP HTTP but dropped at GA4
143
- * processing with no client error — destinations warn and skip instead of sending nowhere.
144
- */
145
- const GA4_EVENT_NAME_PATTERN = /^[A-Za-z][\w]{0,39}$/;
146
-
147
- function isGa4EventName(name: string): boolean {
148
- return GA4_EVENT_NAME_PATTERN.test(name);
149
- }
150
-
151
- /**
152
- * Warns and returns `false` when `eventName` would be rejected by GA4.
153
- *
154
- * @since 0.5.0-canary.6
155
- */
156
- export function warnUnlessGa4EventName(destinationName: string, eventName: string): boolean {
157
- if (isGa4EventName(eventName)) {
158
- return true;
159
- }
160
-
161
- console.warn(
162
- `[tracking] "${destinationName}" dropped event "${eventName}" — GA4 event names must start with a letter and contain only letters, digits, or underscores (max 40 chars)`,
163
- );
164
-
165
- return false;
166
- }
@@ -1,98 +0,0 @@
1
- import type { ConsentDecision } from "#/core/consent";
2
- import type { Destination } from "#/core/destination";
3
- import { toAdConsentState } from "#/destinations/ad-consent";
4
- import type { FlatPropertyValue } from "#/destinations/shared";
5
- import { flattenEventProps } from "#/destinations/shared";
6
-
7
- /**
8
- * Meta's `dataProcessingOptions` restriction. `['LDU'], 0, 0` turns on Limited Data Use and
9
- * lets Meta geolocate the user — the recommended default beyond California, where only
10
- * country `1` (USA) / state `1000` (California) are documented codes (spec-destinations §5).
11
- * `[]` applies no restriction.
12
- *
13
- * @since 0.5.0-canary.6
14
- */
15
- export interface MetaDataProcessingOptions {
16
- country: number;
17
- options: ReadonlyArray<string>;
18
- state: number;
19
- }
20
-
21
- /**
22
- * Maps a `ConsentDecision` to Meta's `dataProcessingOptions`: LDU when `ads` is denied.
23
- *
24
- * @since 0.5.0-canary.6
25
- */
26
- export function toMetaDataProcessingOptions(decision: ConsentDecision): MetaDataProcessingOptions {
27
- return toAdConsentState(decision).limitedDataUse
28
- ? { country: 0, options: ["LDU"], state: 0 }
29
- : { country: 0, options: [], state: 0 };
30
- }
31
-
32
- /**
33
- * The mapped per-event payload handed to a Meta transport (Pixel `fbq` or a CAPI request).
34
- *
35
- * @since 0.5.0-canary.6
36
- */
37
- export interface MetaEventPayload {
38
- dataProcessingOptions: MetaDataProcessingOptions;
39
- name: string;
40
- properties: Record<string, FlatPropertyValue>;
41
- }
42
-
43
- /**
44
- * Options for `createMetaDestination`.
45
- *
46
- * @since 0.5.0-canary.6
47
- */
48
- export interface MetaDestinationOptions {
49
- /**
50
- * Erasure cookie-clear seam — invoked by `onErasure` to drop Meta's `_fbp`/`_fbc` cookies
51
- * (spec-data-subject-rights DSR-V4). Meta exposes no per-visitor deletion API, so erasure
52
- * is cookie-clear + stop-send only. Omit if the integrator clears cookies elsewhere.
53
- */
54
- clearCookies?: (() => void) | undefined;
55
- /** Read per event so an `ads` change restricts data use without recreating the destination. */
56
- getDecision: () => ConsentDecision;
57
- name?: string | undefined;
58
- /**
59
- * Delivers one mapped event — the transport seam. Wire it to `fbq(...)` (Pixel) or a
60
- * Conversions API request; this package ships the consent mapping, never the credentials
61
- * or network client.
62
- */
63
- transport: (payload: MetaEventPayload) => Promise<void> | void;
64
- }
65
-
66
- /**
67
- * Reference ad destination: maps each event to Meta's shape and applies Limited Data Use
68
- * from the live `ads` decision (spec-destinations §5), then hands it to an injected
69
- * transport. Consent-restriction mapping only — the Pixel/CAPI transport and credentials
70
- * are the integrator's to supply. `consentRequirement` stays `"required"`: an ad sink is
71
- * never exempt.
72
- *
73
- * @since 0.5.0-canary.6
74
- */
75
- export function createMetaDestination(options: MetaDestinationOptions): Destination {
76
- // Erasure halts delivery for the rest of the session — Meta has no per-visitor deletion API.
77
- let stopped = false;
78
-
79
- return {
80
- consentRequirement: "required",
81
- name: options.name ?? "meta",
82
- onErasure() {
83
- stopped = true;
84
- options.clearCookies?.();
85
- },
86
- async send(event) {
87
- if (stopped) {
88
- return;
89
- }
90
-
91
- await options.transport({
92
- dataProcessingOptions: toMetaDataProcessingOptions(options.getDecision()),
93
- name: event.name,
94
- properties: flattenEventProps(event.properties),
95
- });
96
- },
97
- };
98
- }
@@ -1,88 +0,0 @@
1
- import type { ConsentDecision } from "#/core/consent";
2
- import type { Destination } from "#/core/destination";
3
- import { toAdConsentState } from "#/destinations/ad-consent";
4
- import type { FlatPropertyValue } from "#/destinations/shared";
5
- import { flattenEventProps } from "#/destinations/shared";
6
-
7
- /**
8
- * Microsoft UET consent. UET enforces **only** `ad_storage` — it has no `analytics_storage`,
9
- * and its `ad_user_data`/`ad_personalization` fields have no documented behavior, so this
10
- * models the one enforced signal (spec-destinations §5). Pushed via
11
- * `uetq.push('consent','update', …)`.
12
- *
13
- * @since 0.5.0-canary.6
14
- */
15
- export interface MicrosoftUetConsent {
16
- ad_storage: "denied" | "granted";
17
- }
18
-
19
- /**
20
- * Maps a `ConsentDecision` to UET's enforced `ad_storage` signal via the shared ad lever, so
21
- * it can't drift from Meta/TikTok — `ad_storage` is the inverse of Limited Data Use.
22
- *
23
- * @since 0.5.0-canary.6
24
- */
25
- export function toMicrosoftUetConsent(decision: ConsentDecision): MicrosoftUetConsent {
26
- return { ad_storage: toAdConsentState(decision).limitedDataUse ? "denied" : "granted" };
27
- }
28
-
29
- /**
30
- * The mapped per-event payload handed to a UET transport (`uetq.push`).
31
- *
32
- * @since 0.5.0-canary.6
33
- */
34
- export interface MicrosoftUetEventPayload {
35
- consent: MicrosoftUetConsent;
36
- name: string;
37
- properties: Record<string, FlatPropertyValue>;
38
- }
39
-
40
- /**
41
- * Options for `createMicrosoftUetDestination`.
42
- *
43
- * @since 0.5.0-canary.6
44
- */
45
- export interface MicrosoftUetDestinationOptions {
46
- /** Erasure cookie-clear seam — UET exposes no per-visitor deletion API, so erasure is cookie-clear + stop-send (DSR-V4). */
47
- clearCookies?: (() => void) | undefined;
48
- /** Read per event so an `ads` change updates `ad_storage` without recreating the destination. */
49
- getDecision: () => ConsentDecision;
50
- name?: string | undefined;
51
- /**
52
- * Delivers one mapped event — the transport seam. Wire it to `uetq.push(...)`; this package
53
- * ships the consent mapping, never the tag id or network client.
54
- */
55
- transport: (payload: MicrosoftUetEventPayload) => Promise<void> | void;
56
- }
57
-
58
- /**
59
- * Reference ad destination for Microsoft UET: maps each event and the live `ads` decision to
60
- * UET's `ad_storage` signal, then hands it to an injected transport. Consent-restriction
61
- * mapping only — the tag id and `uetq` transport are the integrator's. `consentRequirement`
62
- * stays `"required"`.
63
- *
64
- * @since 0.5.0-canary.6
65
- */
66
- export function createMicrosoftUetDestination(options: MicrosoftUetDestinationOptions): Destination {
67
- let stopped = false;
68
-
69
- return {
70
- consentRequirement: "required",
71
- name: options.name ?? "microsoft-uet",
72
- onErasure() {
73
- stopped = true;
74
- options.clearCookies?.();
75
- },
76
- async send(event) {
77
- if (stopped) {
78
- return;
79
- }
80
-
81
- await options.transport({
82
- consent: toMicrosoftUetConsent(options.getDecision()),
83
- name: event.name,
84
- properties: flattenEventProps(event.properties),
85
- });
86
- },
87
- };
88
- }