@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
@@ -1,13 +1,28 @@
1
1
  import { Destination } from "../core/destination.mjs";
2
2
 
3
3
  //#region src/destinations/vercel-analytics.d.ts
4
+ /**
5
+ * @since 1.0.0-canary.6
6
+ */
7
+ interface VercelAnalyticsDestinationOptions {
8
+ /**
9
+ * Vercel Analytics is cookieless and its events carry no identifier from this
10
+ * package, so it qualifies for `"exempt"` — it then keeps receiving events while the
11
+ * tracker's analytics gate is closed. Defaults to `"required"` so pre-consent delivery
12
+ * stays an explicit opt-in.
13
+ */
14
+ consentRequirement?: "exempt" | "required" | undefined;
15
+ name?: string | undefined;
16
+ }
4
17
  /**
5
18
  * `track()` only pushes onto Vercel's own in-page queue (`window.va`/`window.vaq`), which
6
- * handles batching and unload delivery itself — hence `delivery: "immediate"`. Requires
7
- * `<Analytics />` from `@vercel/analytics/react` to be mounted once in the app.
19
+ * handles batching and unload delivery itself. Requires the Vercel Analytics script to be
20
+ * loaded once elsewhere in the app (`<Analytics />` from `@vercel/analytics/react`, or the
21
+ * framework-agnostic `inject()`) — this destination only queues events, so it imports the
22
+ * base `@vercel/analytics` package and has no React dependency of its own.
8
23
  *
9
24
  * @since 0.5.0-canary.4
10
25
  */
11
- declare function createVercelAnalyticsDestination(name?: string): Destination;
26
+ declare function createVercelAnalyticsDestination(options?: VercelAnalyticsDestinationOptions): Destination;
12
27
  //#endregion
13
- export { createVercelAnalyticsDestination };
28
+ export { VercelAnalyticsDestinationOptions, createVercelAnalyticsDestination };
@@ -1,28 +1,21 @@
1
- import { track } from "@vercel/analytics/react";
1
+ import { flattenEventProps } from "./shared.mjs";
2
+ import { track } from "@vercel/analytics";
2
3
  //#region src/destinations/vercel-analytics.ts
3
4
  /**
4
- * Vercel's `track()` rejects nested objects/arrays outright — flatten anything else
5
- * to a string instead of silently dropping it.
6
- */
7
- function toVercelAnalyticsProps(props) {
8
- const result = {};
9
- for (const [key, value] of Object.entries(props)) if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") result[key] = value;
10
- else if (value !== void 0) result[key] = JSON.stringify(value);
11
- return result;
12
- }
13
- /**
14
5
  * `track()` only pushes onto Vercel's own in-page queue (`window.va`/`window.vaq`), which
15
- * handles batching and unload delivery itself — hence `delivery: "immediate"`. Requires
16
- * `<Analytics />` from `@vercel/analytics/react` to be mounted once in the app.
6
+ * handles batching and unload delivery itself. Requires the Vercel Analytics script to be
7
+ * loaded once elsewhere in the app (`<Analytics />` from `@vercel/analytics/react`, or the
8
+ * framework-agnostic `inject()`) — this destination only queues events, so it imports the
9
+ * base `@vercel/analytics` package and has no React dependency of its own.
17
10
  *
18
11
  * @since 0.5.0-canary.4
19
12
  */
20
- function createVercelAnalyticsDestination(name = "vercel-analytics") {
13
+ function createVercelAnalyticsDestination(options = {}) {
21
14
  return {
22
- delivery: "immediate",
23
- name,
24
- send(event) {
25
- track(event.name, toVercelAnalyticsProps(event.props));
15
+ consentRequirement: options.consentRequirement ?? "required",
16
+ name: options.name ?? "vercel-analytics",
17
+ async send(event) {
18
+ track(event.name, flattenEventProps(event.properties, { allowNull: true }));
26
19
  }
27
20
  };
28
21
  }
@@ -0,0 +1,19 @@
1
+ //#region src/import-protection.d.ts
2
+ /**
3
+ * Import specifiers (picomatch patterns) every client bundle must deny — spread into
4
+ * TanStack Start's `importProtection.client.specifiers` so the deny-list ships and
5
+ * versions with the package instead of going stale in each consumer's config. Nothing in
6
+ * this package imports it — its consumers are app build configs (see apps/ui vite.config.ts).
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * tanstackStart({
11
+ * importProtection: { client: { specifiers: [...SERVER_ONLY_IMPORT_SPECIFIERS] } },
12
+ * });
13
+ * ```
14
+ *
15
+ * @since 1.0.0-canary.6
16
+ */
17
+ declare const SERVER_ONLY_IMPORT_SPECIFIERS: ReadonlyArray<string>;
18
+ //#endregion
19
+ export { SERVER_ONLY_IMPORT_SPECIFIERS };
@@ -0,0 +1,23 @@
1
+ //#region src/import-protection.ts
2
+ /**
3
+ * Import specifiers (picomatch patterns) every client bundle must deny — spread into
4
+ * TanStack Start's `importProtection.client.specifiers` so the deny-list ships and
5
+ * versions with the package instead of going stale in each consumer's config. Nothing in
6
+ * this package imports it — its consumers are app build configs (see apps/ui vite.config.ts).
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * tanstackStart({
11
+ * importProtection: { client: { specifiers: [...SERVER_ONLY_IMPORT_SPECIFIERS] } },
12
+ * });
13
+ * ```
14
+ *
15
+ * @since 1.0.0-canary.6
16
+ */
17
+ const SERVER_ONLY_IMPORT_SPECIFIERS = [
18
+ "@codefast/tracking/server",
19
+ "@codefast/tracking/server/**",
20
+ "@codefast/tracking/tanstack-start"
21
+ ];
22
+ //#endregion
23
+ export { SERVER_ONLY_IMPORT_SPECIFIERS };
package/dist/index.d.mts CHANGED
@@ -1,6 +1,8 @@
1
- import { CONSENT_CATEGORIES, ConsentCategory, ConsentDecision, ConsentMode, ConsentRecord, ConsentRegion, ConsentStorage, createConsentDecision, isConsentDecision, resolveConsentMode, resolveDefaultConsent } from "./core/consent.mjs";
2
- import { TrackedEvent } from "./core/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 "./core/consent.mjs";
2
+ import { ConsentConfig, defineConsentConfig } from "./core/consent-config.mjs";
3
+ import { TrackEvent, TrackedEvent, TrackedEventBase } from "./core/tracked-event.mjs";
3
4
  import { Destination } from "./core/destination.mjs";
4
- import { EventCatalog, EventDefinition, EventsOf, defineEventCatalog } from "./core/event-catalog.mjs";
5
+ import { EventCatalog, EventDefinition, assertValidEventProperties, defineEventCatalog } from "./core/event-catalog.mjs";
6
+ import { readCookieValue } from "./core/cookie.mjs";
5
7
  import { generateEventId } from "./core/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 };
package/dist/index.mjs CHANGED
@@ -1,4 +1,6 @@
1
- import { CONSENT_CATEGORIES, createConsentDecision, isConsentDecision, resolveConsentMode, resolveDefaultConsent } from "./core/consent.mjs";
2
- import { defineEventCatalog } from "./core/event-catalog.mjs";
1
+ import { CONSENT_CATEGORIES, CONSENT_REGIONS, STRICTEST_INITIAL_CONSENT, createConsentDecision, isConsentDecision, isConsentRecord, isConsentRegion, isInitialConsent, normalizeConsentDecision, readStoredDecision, resolveConsentMode, resolveDefaultConsent, resolveEffectiveConsent } from "./core/consent.mjs";
2
+ import { defineConsentConfig } from "./core/consent-config.mjs";
3
+ import { readCookieValue } from "./core/cookie.mjs";
4
+ import { assertValidEventProperties, defineEventCatalog } from "./core/event-catalog.mjs";
3
5
  import { generateEventId } from "./core/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 };
@@ -8,15 +8,15 @@ import { ComponentProps, ReactNode } from "react";
8
8
  */
9
9
  interface ConsentBannerProps extends ComponentProps<"section"> {
10
10
  consent: UseConsentResult;
11
- /** Overrides the default `needsPrompt` gating — e.g. to reopen the banner as a settings panel. */
11
+ /** Overrides the default `isPromptNeeded` gating — e.g. to reopen the banner as a settings panel. */
12
12
  open?: boolean | undefined;
13
13
  }
14
14
  /**
15
- * Non-blocking opt-in prompt for GDPR/NĐ 13 regions, as composable parts — the root owns
15
+ * Non-blocking opt-in prompt for GDPR/PDPL (VN) regions, as composable parts — the root owns
16
16
  * the visibility gating and the preferences-layer state; the `Accept`/`Reject`/`Customize`/
17
17
  * `Save` parts wire their own clicks to the consent hook, so any markup (including a
18
18
  * design system's button styles via `className`) slots in. Renders nothing once a decision
19
- * exists or the region defaults to opt-out (`consent.needsPrompt`), unless `open` says
19
+ * exists or the region defaults to opt-out (`consent.isPromptNeeded`), unless `open` says
20
20
  * otherwise. Rendered as a labeled region, not a `<dialog>`: an open non-modal dialog
21
21
  * neither traps focus nor blocks the page, so the dialog semantics would over-promise.
22
22
  * Unstyled by default — style via `className`/`data-slot` selectors, or import the
@@ -65,7 +65,7 @@ declare function ConsentBannerActions(props: ConsentBannerActionsProps): ReactNo
65
65
  */
66
66
  interface ConsentBannerAcceptProps extends Omit<ComponentProps<"button">, "type"> {}
67
67
  /**
68
- * Grants the categories the app requested (`useConsent`'s `categories`) — never more.
68
+ * Grants the categories the app requested (`useConsent`'s `requestedCategories`) — never more.
69
69
  *
70
70
  * @since 0.5.0-canary.5
71
71
  */
@@ -142,14 +142,30 @@ declare function ConsentBannerSave({
142
142
  * @since 0.5.0-canary.4
143
143
  */
144
144
  interface ConsentToggleProps extends Omit<ComponentProps<"button">, "children" | "onClick" | "type"> {
145
- allowLabel?: string;
145
+ /**
146
+ * Label shown while the scoped categories are denied — clicking grants them. Defaults
147
+ * to "Allow tracking".
148
+ */
149
+ allowLabel?: string | undefined;
146
150
  consent: UseConsentResult;
147
- denyLabel?: string;
151
+ /**
152
+ * Label shown while any scoped category is granted — clicking denies them. Defaults to
153
+ * CCPA/CPRA "Do Not Sell or Share My Personal Information".
154
+ */
155
+ denyLabel?: string | undefined;
156
+ /**
157
+ * Purposes this control flips. Defaults to `["ads"]` — CCPA/CPRA "Do Not Sell or Share"
158
+ * mirrors GPC (ads denied, first-party analytics left alone). Pass `["analytics"]` (or
159
+ * both) for a broader opt-out. Distinct from `useConsent`'s `requestedCategories` (what the
160
+ * prompt asks about / `grantAll` grants).
161
+ */
162
+ toggledCategories?: ReadonlyArray<ConsentCategory> | undefined;
148
163
  }
149
164
  /**
150
165
  * Always-visible control for opt-out regions — CCPA/CPRA requires a persistent
151
166
  * "Do Not Sell or Share My Personal Information" mechanism, not just a one-time prompt.
152
- * Flips between denying everything and re-granting the app's requested categories.
167
+ * By default it only flips `ads` (same scope as a GPC signal); pass `toggledCategories`
168
+ * to include analytics or both.
153
169
  *
154
170
  * @since 0.5.0-canary.4
155
171
  */
@@ -157,6 +173,7 @@ declare function ConsentToggle({
157
173
  allowLabel,
158
174
  consent,
159
175
  denyLabel,
176
+ toggledCategories,
160
177
  ...props
161
178
  }: ConsentToggleProps): ReactNode;
162
179
  //#endregion
@@ -1,4 +1,4 @@
1
- import { CONSENT_CATEGORIES } from "../core/consent.mjs";
1
+ "use client";
2
2
  import { createContext, useContext, useEffect, useState } from "react";
3
3
  import { jsx, jsxs } from "react/jsx-runtime";
4
4
  //#region src/react/consent-banner.tsx
@@ -9,11 +9,11 @@ function useConsentBannerContext(part) {
9
9
  return context;
10
10
  }
11
11
  /**
12
- * Non-blocking opt-in prompt for GDPR/NĐ 13 regions, as composable parts — the root owns
12
+ * Non-blocking opt-in prompt for GDPR/PDPL (VN) regions, as composable parts — the root owns
13
13
  * the visibility gating and the preferences-layer state; the `Accept`/`Reject`/`Customize`/
14
14
  * `Save` parts wire their own clicks to the consent hook, so any markup (including a
15
15
  * design system's button styles via `className`) slots in. Renders nothing once a decision
16
- * exists or the region defaults to opt-out (`consent.needsPrompt`), unless `open` says
16
+ * exists or the region defaults to opt-out (`consent.isPromptNeeded`), unless `open` says
17
17
  * otherwise. Rendered as a labeled region, not a `<dialog>`: an open non-modal dialog
18
18
  * neither traps focus nor blocks the page, so the dialog semantics would over-promise.
19
19
  * Unstyled by default — style via `className`/`data-slot` selectors, or import the
@@ -24,7 +24,7 @@ function useConsentBannerContext(part) {
24
24
  */
25
25
  function ConsentBanner({ children, consent, open, ...props }) {
26
26
  const [pending, setPending] = useState(void 0);
27
- const isVisible = open ?? consent.needsPrompt;
27
+ const isVisible = open ?? consent.isPromptNeeded;
28
28
  useEffect(() => {
29
29
  if (!isVisible) setPending(void 0);
30
30
  }, [isVisible]);
@@ -75,7 +75,7 @@ function ConsentBannerActions(props) {
75
75
  });
76
76
  }
77
77
  /**
78
- * Grants the categories the app requested (`useConsent`'s `categories`) — never more.
78
+ * Grants the categories the app requested (`useConsent`'s `requestedCategories`) — never more.
79
79
  *
80
80
  * @since 0.5.0-canary.5
81
81
  */
@@ -182,7 +182,7 @@ function ConsentBannerSave({ onClick, ...props }) {
182
182
  ...props,
183
183
  onClick: (event) => {
184
184
  onClick?.(event);
185
- consent.save(pending);
185
+ consent.saveDecision(pending);
186
186
  setPending(void 0);
187
187
  },
188
188
  type: "button"
@@ -191,18 +191,23 @@ function ConsentBannerSave({ onClick, ...props }) {
191
191
  /**
192
192
  * Always-visible control for opt-out regions — CCPA/CPRA requires a persistent
193
193
  * "Do Not Sell or Share My Personal Information" mechanism, not just a one-time prompt.
194
- * Flips between denying everything and re-granting the app's requested categories.
194
+ * By default it only flips `ads` (same scope as a GPC signal); pass `toggledCategories`
195
+ * to include analytics or both.
195
196
  *
196
197
  * @since 0.5.0-canary.4
197
198
  */
198
- function ConsentToggle({ allowLabel = "Allow tracking", consent, denyLabel = "Do Not Sell or Share My Personal Information", ...props }) {
199
- const anyAllowed = CONSENT_CATEGORIES.some((category) => consent.effectiveConsent[category]);
199
+ function ConsentToggle({ allowLabel = "Allow tracking", consent, denyLabel = "Do Not Sell or Share My Personal Information", toggledCategories = ["ads"], ...props }) {
200
+ const isAnyCategoryGranted = toggledCategories.some((category) => consent.effectiveConsent[category]);
200
201
  return /* @__PURE__ */ jsx("button", {
201
202
  "data-slot": "consent-toggle",
202
203
  ...props,
203
- onClick: anyAllowed ? consent.denyAll : consent.grantAll,
204
+ onClick: () => {
205
+ const next = { ...consent.effectiveConsent };
206
+ for (const category of toggledCategories) next[category] = !isAnyCategoryGranted;
207
+ consent.saveDecision(next);
208
+ },
204
209
  type: "button",
205
- children: anyAllowed ? denyLabel : allowLabel
210
+ children: isAnyCategoryGranted ? denyLabel : allowLabel
206
211
  });
207
212
  }
208
213
  //#endregion
@@ -0,0 +1,27 @@
1
+ import { GtagConsentBootstrapOptions } from "../destinations/google-analytics.mjs";
2
+ import { ComponentProps, ReactNode } from "react";
3
+
4
+ //#region src/react/gtag-consent-bootstrap.d.ts
5
+ /**
6
+ * @since 1.0.0-canary.6
7
+ */
8
+ interface GtagConsentBootstrapProps extends Omit<ComponentProps<"script">, "children" | "dangerouslySetInnerHTML" | "nonce" | "src" | "type">, GtagConsentBootstrapOptions {}
9
+ /**
10
+ * Framework-agnostic inline `<script>` that runs `buildGtagConsentBootstrapScript` before
11
+ * hydration. Pass the same `nonce` here and in `loadGtagScript` for CSP; this component
12
+ * only sets the attribute on the host script — the generated source also stamps it onto
13
+ * the injected gtag.js tag when `nonce` is provided.
14
+ *
15
+ * @since 1.0.0-canary.6
16
+ */
17
+ declare function GtagConsentBootstrap({
18
+ config,
19
+ dataLayerName,
20
+ defaultConsent,
21
+ debugMode,
22
+ gaMeasurementId,
23
+ nonce,
24
+ ...props
25
+ }: GtagConsentBootstrapProps): ReactNode;
26
+ //#endregion
27
+ export { GtagConsentBootstrap, GtagConsentBootstrapProps };
@@ -0,0 +1,29 @@
1
+ import { buildGtagConsentBootstrapScript } from "../destinations/google-analytics.mjs";
2
+ import { jsx } from "react/jsx-runtime";
3
+ //#region src/react/gtag-consent-bootstrap.tsx
4
+ /**
5
+ * Framework-agnostic inline `<script>` that runs `buildGtagConsentBootstrapScript` before
6
+ * hydration. Pass the same `nonce` here and in `loadGtagScript` for CSP; this component
7
+ * only sets the attribute on the host script — the generated source also stamps it onto
8
+ * the injected gtag.js tag when `nonce` is provided.
9
+ *
10
+ * @since 1.0.0-canary.6
11
+ */
12
+ function GtagConsentBootstrap({ config, dataLayerName, defaultConsent, debugMode, gaMeasurementId, nonce, ...props }) {
13
+ const bootstrapOptions = {
14
+ config,
15
+ defaultConsent,
16
+ gaMeasurementId,
17
+ ...dataLayerName === void 0 ? {} : { dataLayerName },
18
+ ...debugMode === void 0 ? {} : { debugMode },
19
+ ...nonce === void 0 ? {} : { nonce }
20
+ };
21
+ return /* @__PURE__ */ jsx("script", {
22
+ ...props,
23
+ dangerouslySetInnerHTML: { __html: buildGtagConsentBootstrapScript(bootstrapOptions) },
24
+ ...nonce === void 0 ? {} : { nonce },
25
+ suppressHydrationWarning: true
26
+ });
27
+ }
28
+ //#endregion
29
+ export { GtagConsentBootstrap };
@@ -1,3 +1,6 @@
1
1
  import { UseConsentOptions, UseConsentResult, useConsent } from "./use-consent.mjs";
2
2
  import { ConsentBanner, ConsentBannerAccept, ConsentBannerAcceptProps, ConsentBannerActions, ConsentBannerActionsProps, ConsentBannerCategory, ConsentBannerCategoryProps, ConsentBannerCustomize, ConsentBannerCustomizeProps, ConsentBannerDescription, ConsentBannerDescriptionProps, ConsentBannerPreferences, ConsentBannerPreferencesProps, ConsentBannerProps, ConsentBannerReject, ConsentBannerRejectProps, ConsentBannerSave, ConsentBannerSaveProps, ConsentBannerTitle, ConsentBannerTitleProps, ConsentToggle, ConsentToggleProps } from "./consent-banner.mjs";
3
- export { ConsentBanner, ConsentBannerAccept, type ConsentBannerAcceptProps, ConsentBannerActions, type ConsentBannerActionsProps, ConsentBannerCategory, type ConsentBannerCategoryProps, ConsentBannerCustomize, type ConsentBannerCustomizeProps, ConsentBannerDescription, type ConsentBannerDescriptionProps, ConsentBannerPreferences, type ConsentBannerPreferencesProps, type ConsentBannerProps, ConsentBannerReject, type ConsentBannerRejectProps, ConsentBannerSave, type ConsentBannerSaveProps, ConsentBannerTitle, type ConsentBannerTitleProps, ConsentToggle, type ConsentToggleProps, type UseConsentOptions, type UseConsentResult, useConsent };
3
+ import { GtagConsentBootstrap, GtagConsentBootstrapProps } from "./gtag-consent-bootstrap.mjs";
4
+ import { useInitialConsent } from "./use-initial-consent.mjs";
5
+ import { UseGoogleConsentSyncOptions, useGoogleConsentSync } from "./use-google-consent-sync.mjs";
6
+ export { ConsentBanner, ConsentBannerAccept, type ConsentBannerAcceptProps, ConsentBannerActions, type ConsentBannerActionsProps, ConsentBannerCategory, type ConsentBannerCategoryProps, ConsentBannerCustomize, type ConsentBannerCustomizeProps, ConsentBannerDescription, type ConsentBannerDescriptionProps, ConsentBannerPreferences, type ConsentBannerPreferencesProps, type ConsentBannerProps, ConsentBannerReject, type ConsentBannerRejectProps, ConsentBannerSave, type ConsentBannerSaveProps, ConsentBannerTitle, type ConsentBannerTitleProps, ConsentToggle, type ConsentToggleProps, GtagConsentBootstrap, type GtagConsentBootstrapProps, type UseConsentOptions, type UseConsentResult, type UseGoogleConsentSyncOptions, useConsent, useGoogleConsentSync, useInitialConsent };
@@ -1,3 +1,6 @@
1
1
  import { ConsentBanner, ConsentBannerAccept, ConsentBannerActions, ConsentBannerCategory, ConsentBannerCustomize, ConsentBannerDescription, ConsentBannerPreferences, ConsentBannerReject, ConsentBannerSave, ConsentBannerTitle, ConsentToggle } from "./consent-banner.mjs";
2
+ import { GtagConsentBootstrap } from "./gtag-consent-bootstrap.mjs";
2
3
  import { useConsent } from "./use-consent.mjs";
3
- export { ConsentBanner, ConsentBannerAccept, ConsentBannerActions, ConsentBannerCategory, ConsentBannerCustomize, ConsentBannerDescription, ConsentBannerPreferences, ConsentBannerReject, ConsentBannerSave, ConsentBannerTitle, ConsentToggle, useConsent };
4
+ import { useInitialConsent } from "./use-initial-consent.mjs";
5
+ import { useGoogleConsentSync } from "./use-google-consent-sync.mjs";
6
+ export { ConsentBanner, ConsentBannerAccept, ConsentBannerActions, ConsentBannerCategory, ConsentBannerCustomize, ConsentBannerDescription, ConsentBannerPreferences, ConsentBannerReject, ConsentBannerSave, ConsentBannerTitle, ConsentToggle, GtagConsentBootstrap, useConsent, useGoogleConsentSync, useInitialConsent };
@@ -1,20 +1,16 @@
1
- import { ConsentCategory, ConsentDecision, ConsentMode, ConsentStorage } from "../core/consent.mjs";
1
+ import { ConsentDecision, ConsentMode, ConsentStorage } from "../core/consent.mjs";
2
+ import { ConsentConfig } from "../core/consent-config.mjs";
2
3
 
3
4
  //#region src/react/use-consent.d.ts
4
5
  /**
5
6
  * @since 0.5.0-canary.4
6
7
  */
7
8
  interface UseConsentOptions {
8
- /**
9
- * Categories the app's prompt actually asks about — `grantAll` grants exactly these,
10
- * so an analytics-only banner can never grant ads consent it never asked for.
11
- * Defaults to `["analytics"]`.
12
- */
13
- categories?: ReadonlyArray<ConsentCategory>;
14
- hasGlobalPrivacyControlSignal?: boolean;
9
+ /** Must be the same object the tracker gate and the tag bootstraps receive — one config, every surface. */
10
+ config: ConsentConfig;
11
+ hasGlobalPrivacyControlSignal?: boolean | undefined;
15
12
  mode: ConsentMode;
16
- onDecision?: (decision: ConsentDecision) => void;
17
- policyVersion: string;
13
+ onDecision?: ((decision: ConsentDecision) => void) | undefined;
18
14
  /** Must be a stable reference (module-level or memoized) — a new object per render resubscribes every render. */
19
15
  storage: ConsentStorage;
20
16
  }
@@ -29,11 +25,11 @@ interface UseConsentResult {
29
25
  effectiveConsent: ConsentDecision;
30
26
  grantAll: () => void;
31
27
  /** Effective `analytics` consent — gates this package's own tracker pipeline. */
32
- isTrackingAllowed: boolean;
28
+ isAnalyticsAllowed: boolean;
33
29
  /** True only for opt-in regions with no stored decision yet — drives whether to render the banner. */
34
- needsPrompt: boolean;
30
+ isPromptNeeded: boolean;
35
31
  /** Persist a granular per-category choice, e.g. from a preferences panel. */
36
- save: (decision: ConsentDecision) => void;
32
+ saveDecision: (decision: ConsentDecision) => void;
37
33
  }
38
34
  /**
39
35
  * Bridges `resolveConsentMode`/`resolveDefaultConsent` (core, region-aware) to React via
@@ -1,7 +1,7 @@
1
- import { CONSENT_CATEGORIES, createConsentDecision, isConsentDecision, resolveDefaultConsent } from "../core/consent.mjs";
2
- import { useRef, useSyncExternalStore } from "react";
1
+ "use client";
2
+ import { CONSENT_CATEGORIES, createConsentDecision, readStoredDecision, resolveDefaultConsent } from "../core/consent.mjs";
3
+ import { useCallback, useMemo, useRef, useSyncExternalStore } from "react";
3
4
  //#region src/react/use-consent.ts
4
- const DEFAULT_CATEGORIES = ["analytics"];
5
5
  /**
6
6
  * Bridges `resolveConsentMode`/`resolveDefaultConsent` (core, region-aware) to React via
7
7
  * `useSyncExternalStore`: the stored record is the single source of truth, hydration is
@@ -12,43 +12,60 @@ const DEFAULT_CATEGORIES = ["analytics"];
12
12
  * @since 0.5.0-canary.4
13
13
  */
14
14
  function useConsent(options) {
15
- const { storage } = options;
16
- const categories = options.categories ?? DEFAULT_CATEGORIES;
15
+ const { mode, onDecision, storage } = options;
16
+ const { policyVersion, requestedCategories } = options.config;
17
+ const hasGlobalPrivacyControlSignal = options.hasGlobalPrivacyControlSignal ?? false;
17
18
  const cachedDecision = useRef(void 0);
18
19
  const decision = useSyncExternalStore(storage.subscribe, () => {
19
- const record = storage.load();
20
- if (record?.policyVersion !== options.policyVersion || !isConsentDecision(record.decision)) {
20
+ const stored = readStoredDecision(storage, policyVersion);
21
+ if (stored === void 0) {
21
22
  cachedDecision.current = void 0;
22
23
  return;
23
24
  }
24
- const stored = record.decision;
25
25
  const cached = cachedDecision.current;
26
26
  if (cached !== void 0 && CONSENT_CATEGORIES.every((category) => cached[category] === stored[category])) return cached;
27
- cachedDecision.current = createConsentDecision(CONSENT_CATEGORIES.filter((category) => stored[category]));
27
+ cachedDecision.current = stored;
28
28
  return cachedDecision.current;
29
29
  }, () => void 0);
30
- function save(next) {
30
+ const saveDecision = useCallback((next) => {
31
31
  storage.save({
32
32
  decision: next,
33
- policyVersion: options.policyVersion,
33
+ policyVersion,
34
34
  timestamp: Date.now()
35
35
  });
36
- options.onDecision?.(next);
37
- }
38
- const effectiveConsent = decision ?? resolveDefaultConsent(options.mode, categories, options.hasGlobalPrivacyControlSignal ?? false);
39
- return {
36
+ onDecision?.(next);
37
+ }, [
38
+ onDecision,
39
+ policyVersion,
40
+ storage
41
+ ]);
42
+ const denyAll = useCallback(() => {
43
+ saveDecision(createConsentDecision([]));
44
+ }, [saveDecision]);
45
+ const grantAll = useCallback(() => {
46
+ saveDecision(createConsentDecision(requestedCategories));
47
+ }, [requestedCategories, saveDecision]);
48
+ const effectiveConsent = decision ?? resolveDefaultConsent({
49
+ hasGlobalPrivacyControlSignal,
50
+ mode,
51
+ requestedCategories
52
+ });
53
+ return useMemo(() => ({
40
54
  decision,
41
- denyAll: () => {
42
- save(createConsentDecision([]));
43
- },
55
+ denyAll,
44
56
  effectiveConsent,
45
- grantAll: () => {
46
- save(createConsentDecision(categories));
47
- },
48
- isTrackingAllowed: effectiveConsent.analytics,
49
- needsPrompt: options.mode === "opt-in" && decision === void 0,
50
- save
51
- };
57
+ grantAll,
58
+ isAnalyticsAllowed: effectiveConsent.analytics,
59
+ isPromptNeeded: mode === "opt-in" && decision === void 0,
60
+ saveDecision
61
+ }), [
62
+ decision,
63
+ denyAll,
64
+ effectiveConsent,
65
+ grantAll,
66
+ mode,
67
+ saveDecision
68
+ ]);
52
69
  }
53
70
  //#endregion
54
71
  export { useConsent };
@@ -0,0 +1,23 @@
1
+ import { UseConsentResult } from "./use-consent.mjs";
2
+
3
+ //#region src/react/use-google-consent-sync.d.ts
4
+ /**
5
+ * @since 1.0.0-canary.6
6
+ */
7
+ interface UseGoogleConsentSyncOptions {
8
+ /**
9
+ * Idempotent gtag.js load — advanced Consent Mode already injects the tag from a
10
+ * bootstrap; pass a loader as a safety net after a runtime grant.
11
+ */
12
+ loadGtagScript?: (() => void) | undefined;
13
+ }
14
+ /**
15
+ * Keeps Google Consent Mode v2 in sync with `useConsent`: emits `update` when a stored
16
+ * decision exists (including cross-tab / privacy-page saves), and optionally loads gtag
17
+ * when analytics is effective. Mount once on a page-wide surface (e.g. the footer gate).
18
+ *
19
+ * @since 1.0.0-canary.6
20
+ */
21
+ declare function useGoogleConsentSync(consent: UseConsentResult, options?: UseGoogleConsentSyncOptions): void;
22
+ //#endregion
23
+ export { UseGoogleConsentSyncOptions, useGoogleConsentSync };
@@ -0,0 +1,24 @@
1
+ "use client";
2
+ import { updateGoogleConsent } from "../destinations/google-analytics.mjs";
3
+ import { useEffect } from "react";
4
+ //#region src/react/use-google-consent-sync.ts
5
+ /**
6
+ * Keeps Google Consent Mode v2 in sync with `useConsent`: emits `update` when a stored
7
+ * decision exists (including cross-tab / privacy-page saves), and optionally loads gtag
8
+ * when analytics is effective. Mount once on a page-wide surface (e.g. the footer gate).
9
+ *
10
+ * @since 1.0.0-canary.6
11
+ */
12
+ function useGoogleConsentSync(consent, options = {}) {
13
+ const { loadGtagScript } = options;
14
+ useEffect(() => {
15
+ if (consent.decision !== void 0) updateGoogleConsent(consent.decision);
16
+ if (consent.effectiveConsent.analytics) loadGtagScript?.();
17
+ }, [
18
+ consent.decision,
19
+ consent.effectiveConsent.analytics,
20
+ loadGtagScript
21
+ ]);
22
+ }
23
+ //#endregion
24
+ export { useGoogleConsentSync };
@@ -0,0 +1,14 @@
1
+ import { InitialConsentSnapshot, InitialConsentStore } from "../client/initial-consent-store.mjs";
2
+
3
+ //#region src/react/use-initial-consent.d.ts
4
+ /**
5
+ * Reactive view of a `createInitialConsentStore` — kicks off resolution on mount (a no-op
6
+ * when the app already did so at router creation) and re-renders once the server lane
7
+ * answers. SSR and the first client render read the strictest snapshot, so hydration can
8
+ * never mismatch on region.
9
+ *
10
+ * @since 1.0.0-canary.6
11
+ */
12
+ declare function useInitialConsent(store: InitialConsentStore): InitialConsentSnapshot;
13
+ //#endregion
14
+ export { useInitialConsent };
@@ -0,0 +1,19 @@
1
+ "use client";
2
+ import { useEffect, useSyncExternalStore } from "react";
3
+ //#region src/react/use-initial-consent.ts
4
+ /**
5
+ * Reactive view of a `createInitialConsentStore` — kicks off resolution on mount (a no-op
6
+ * when the app already did so at router creation) and re-renders once the server lane
7
+ * answers. SSR and the first client render read the strictest snapshot, so hydration can
8
+ * never mismatch on region.
9
+ *
10
+ * @since 1.0.0-canary.6
11
+ */
12
+ function useInitialConsent(store) {
13
+ useEffect(() => {
14
+ store.ensureResolved();
15
+ }, [store]);
16
+ return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);
17
+ }
18
+ //#endregion
19
+ export { useInitialConsent };
@@ -0,0 +1,46 @@
1
+ //#region src/server/anonymous-id-cookie.d.ts
2
+ /**
3
+ * Whether a value is safe to persist as an anonymous id. The persist endpoint is public
4
+ * and echoes its input into a response header, so only an exactly-UUID-shaped value may
5
+ * pass — anything else is a header-injection attempt or corruption, never a valid id.
6
+ *
7
+ * @since 1.0.0-canary.6
8
+ */
9
+ declare function isValidAnonymousId(value: string): boolean;
10
+ /**
11
+ * @since 1.0.0-canary.6
12
+ */
13
+ interface AnonymousIdSetCookieOptions {
14
+ /** Cookie name — must match what the client tracker reads. */
15
+ cookieName: string;
16
+ /** The client-minted id to persist — throws unless it is exactly UUID-shaped. */
17
+ id: string;
18
+ /** How long the id survives a return visit. Defaults to one year. */
19
+ maxAgeSeconds?: number | undefined;
20
+ }
21
+ /**
22
+ * `Set-Cookie` header value that persists (or prolongs) a client-minted anonymous id from
23
+ * the server. A server-set cookie escapes Safari ITP's 7-day cap on `document.cookie`
24
+ * writes, so the id actually lives its full max-age. The server only ever re-sets an id
25
+ * the client hands it — minting stays client-side, after consent, by design.
26
+ *
27
+ * @remarks
28
+ * Always `Secure` — on a plain-HTTP dev origin a browser may drop it, and the
29
+ * client-written cookie (`createServerPersistedAnonymousId`'s optimistic write) still
30
+ * covers that session. Not `HttpOnly`: the client tracker must read the id to stamp it
31
+ * onto events.
32
+ *
33
+ * @throws Error when `id` is not UUID-shaped or `cookieName` is not a valid token.
34
+ *
35
+ * @since 1.0.0-canary.6
36
+ */
37
+ declare function buildAnonymousIdSetCookie(options: AnonymousIdSetCookieOptions): string;
38
+ /**
39
+ * `Set-Cookie` header value that expires the anonymous-id cookie — the server half of a
40
+ * consent withdrawal, alongside the client's own `document.cookie` expiry.
41
+ *
42
+ * @since 1.0.0-canary.6
43
+ */
44
+ declare function buildClearAnonymousIdSetCookie(cookieName: string): string;
45
+ //#endregion
46
+ export { AnonymousIdSetCookieOptions, buildAnonymousIdSetCookie, buildClearAnonymousIdSetCookie, isValidAnonymousId };