@cookiemunch/react 0.7.0 → 0.8.0
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.
- package/CHANGELOG.md +4 -0
- package/dist/client.d.ts +8 -2
- package/dist/client.js +14 -4
- package/dist/client.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
Every published release, newest first. Dates are the day the version was cut.
|
|
4
4
|
|
|
5
|
+
## 0.8.0 (2026-11-25)
|
|
6
|
+
|
|
7
|
+
- Added: `<ConsentIdentity tokenUrl="/api/…">`: a same-origin route that mints the token server-side and answers `{ token }`, instead of a `getToken` in the browser. A 401 is retried once.
|
|
8
|
+
|
|
5
9
|
## 0.7.0 (2026-11-11)
|
|
6
10
|
|
|
7
11
|
- `onConsentCategory(category, fn)` and the hook `useConsentTransition(category, fn)` call `fn` only when that category changes, with `{ granted, previous, replay, cause }`. A visitor's stored decision is replayed once with `replay: true`.
|
package/dist/client.d.ts
CHANGED
|
@@ -145,14 +145,20 @@ interface ConsentIdentityProps {
|
|
|
145
145
|
* `() => getToken({ for: 'cookiemunch', cbid })`. Called on sign-in and every 12 hours while mounted,
|
|
146
146
|
* since a token is valid for 120 seconds only. Resolve null to skip a round.
|
|
147
147
|
*/
|
|
148
|
-
getToken
|
|
148
|
+
getToken?: () => Promise<string | null | undefined> | string | null | undefined;
|
|
149
|
+
/**
|
|
150
|
+
* Instead of `getToken`: a same-origin route of yours that mints the token server-side and answers
|
|
151
|
+
* `{ token }` to a GET, e.g. `/api/atlas/token/cookiemunch` (LinkHub CM-L14). Sent with the page's
|
|
152
|
+
* cookies; a 401 is retried once, then that round is skipped.
|
|
153
|
+
*/
|
|
154
|
+
tokenUrl?: string;
|
|
149
155
|
}
|
|
150
156
|
/**
|
|
151
157
|
* Links the visitor's consent decision to the signed-in person, so it follows them to their other
|
|
152
158
|
* devices (https://cookiemunch.net/docs/consent-api#linking-a-decision-to-a-signed-in-person).
|
|
153
159
|
* Put it once in the root layout, inside whatever provides the session. Renders nothing.
|
|
154
160
|
*/
|
|
155
|
-
declare function ConsentIdentity({ subject, getToken }: ConsentIdentityProps): null;
|
|
161
|
+
declare function ConsentIdentity({ subject, getToken, tokenUrl }: ConsentIdentityProps): null;
|
|
156
162
|
|
|
157
163
|
interface CookieSettingsLinkProps {
|
|
158
164
|
children?: ReactNode;
|
package/dist/client.js
CHANGED
|
@@ -230,6 +230,16 @@ function useConsentTransition(category, fn) {
|
|
|
230
230
|
// src/ConsentIdentity.tsx
|
|
231
231
|
import { useEffect as useEffect5, useRef as useRef4 } from "react";
|
|
232
232
|
var RELINK_MS = 12 * 60 * 60 * 1e3;
|
|
233
|
+
async function fromUrl(url) {
|
|
234
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
235
|
+
const res = await fetch(url, { credentials: "same-origin", headers: { Accept: "application/json" } });
|
|
236
|
+
if (res.status === 401 && attempt === 0) continue;
|
|
237
|
+
if (!res.ok) return null;
|
|
238
|
+
const t = (await res.json())?.token;
|
|
239
|
+
return typeof t === "string" && t ? t : null;
|
|
240
|
+
}
|
|
241
|
+
return null;
|
|
242
|
+
}
|
|
233
243
|
function identify(token) {
|
|
234
244
|
const w = window;
|
|
235
245
|
const fd = w.__consent = w.__consent || { q: [] };
|
|
@@ -239,9 +249,9 @@ function identify(token) {
|
|
|
239
249
|
function unlink() {
|
|
240
250
|
window.CookieMunch?.setSyncToken?.(null);
|
|
241
251
|
}
|
|
242
|
-
function ConsentIdentity({ subject, getToken }) {
|
|
243
|
-
const mint = useRef4(
|
|
244
|
-
mint.current = getToken;
|
|
252
|
+
function ConsentIdentity({ subject, getToken, tokenUrl }) {
|
|
253
|
+
const mint = useRef4(() => null);
|
|
254
|
+
mint.current = getToken ?? (tokenUrl ? () => fromUrl(tokenUrl) : () => null);
|
|
245
255
|
const linked = useRef4(false);
|
|
246
256
|
useEffect5(() => {
|
|
247
257
|
if (!subject) {
|
|
@@ -254,7 +264,7 @@ function ConsentIdentity({ subject, getToken }) {
|
|
|
254
264
|
const link = async () => {
|
|
255
265
|
try {
|
|
256
266
|
const token = await mint.current();
|
|
257
|
-
if (live && token) identify(token);
|
|
267
|
+
if (live && typeof token === "string" && token) identify(token);
|
|
258
268
|
} catch {
|
|
259
269
|
}
|
|
260
270
|
};
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ConsentProvider.tsx","../src/context.ts","../src/useConsent.ts","../src/ConsentGate.tsx","../src/useConsentValue.ts","../src/RightsLink.tsx","../src/CookieDeclaration.tsx","../src/useBannerInset.ts","../src/useConsentTransition.ts","../src/ConsentIdentity.tsx","../src/CookieSettingsLink.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type ReactNode } from 'react';\nimport { ConsentContext, EMPTY_CONSENT, type ConsentContextValue } from './context.js';\nimport type { CookieMunchGlobal, PublicConsent } from './helpers.js';\n\n/** Default CDN location of the base browser embed. */\nconst DEFAULT_SRC = 'https://cdn.cookiemunch.net/consent.js';\n/** The <script> id the embed's bootstrap reads via getElementById. */\nconst SCRIPT_ID = 'CookieMunch';\n\nexport interface ConsentProviderProps {\n /** The Cookie Munch site id (required). Injected as `data-cbid` on the embed. */\n cbid: string;\n /** Embed URL. Defaults to the public CDN. */\n src?: string;\n /** Override the API base the embed beacons to (injected as `data-api`). */\n apiBase?: string;\n children: ReactNode;\n}\n\ninterface Snapshot {\n ready: boolean;\n consent: PublicConsent;\n hasResponse: boolean;\n consented: boolean;\n}\n\nconst INITIAL_SNAPSHOT: Snapshot = {\n ready: false,\n consent: EMPTY_CONSENT,\n hasResponse: false,\n consented: false,\n};\n\n/**\n * Locate the embed's <script> tag, injecting it if it isn't already present.\n * The embed self-bootstraps from the tag's `data-*` attributes and, once ready,\n * assigns `window.CookieMunch`.\n */\nfunction ensureEmbedScript(cbid: string, src: string, apiBase: string | undefined): void {\n const existing = document.getElementById(SCRIPT_ID);\n if (existing) return;\n const script = document.createElement('script');\n script.id = SCRIPT_ID;\n script.async = true;\n script.src = src;\n script.setAttribute('data-cbid', cbid);\n if (apiBase) script.setAttribute('data-api', apiBase);\n (document.head || document.documentElement).appendChild(script);\n}\n\n/**\n * Loads the Cookie Munch browser embed from the CDN at runtime and exposes\n * reactive consent state to descendants — a standalone script-tag SDK wrapper\n * that does NOT bundle the proprietary engine.\n *\n * SSR-safe: no `window`/`document` access during render; the script is injected\n * and the global API resolved only inside an effect. Descendants see an\n * all-denied, not-ready snapshot until the embed reports in.\n */\nexport function ConsentProvider({ cbid, src = DEFAULT_SRC, apiBase, children }: ConsentProviderProps) {\n const apiRef = useRef<CookieMunchGlobal | null>(null);\n const [snap, setSnap] = useState<Snapshot>(INITIAL_SNAPSHOT);\n\n useEffect(() => {\n if (typeof window === 'undefined' || typeof document === 'undefined') return;\n\n let disposed = false;\n let offConsentChange: (() => void) | null = null;\n let pollTimer: ReturnType<typeof setInterval> | null = null;\n\n const sync = (api: CookieMunchGlobal) => {\n if (disposed) return;\n setSnap({\n ready: true,\n consent: api.consent,\n hasResponse: api.hasResponse,\n consented: api.consented,\n });\n };\n\n const bind = (api: CookieMunchGlobal) => {\n if (disposed) return;\n apiRef.current = api;\n sync(api);\n offConsentChange = api.onConsentChange(() => sync(api));\n };\n\n // If the embed is already on the page, reuse it immediately.\n if (window.CookieMunch) {\n bind(window.CookieMunch);\n } else {\n ensureEmbedScript(cbid, src, apiBase);\n // The embed sets window.CookieMunch asynchronously (after its remote-config\n // fetch), so poll until it appears, then bind once.\n pollTimer = setInterval(() => {\n if (window.CookieMunch) {\n if (pollTimer) clearInterval(pollTimer);\n pollTimer = null;\n bind(window.CookieMunch);\n }\n }, 50);\n }\n\n return () => {\n disposed = true;\n if (pollTimer) clearInterval(pollTimer);\n offConsentChange?.();\n apiRef.current = null;\n };\n // Re-bind if the site id / source changes.\n }, [cbid, src, apiBase]);\n\n const api = apiRef.current;\n const value: ConsentContextValue = {\n ready: snap.ready,\n consent: snap.consent,\n hasResponse: snap.hasResponse,\n consented: snap.consented,\n acceptAll: () => api?.submitCustomConsent(true, true, true),\n declineAll: () => api?.submitCustomConsent(false, false, false),\n submitCustomConsent: (p, s, m) => api?.submitCustomConsent(p, s, m),\n withdraw: () => api?.withdraw(),\n show: () => api?.show(),\n renew: () => api?.renew(),\n };\n\n return <ConsentContext.Provider value={value}>{children}</ConsentContext.Provider>;\n}\n","import { createContext } from 'react';\nimport type { PublicConsent } from './helpers.js';\n\nexport interface ConsentContextValue {\n ready: boolean;\n consent: PublicConsent;\n hasResponse: boolean;\n consented: boolean;\n acceptAll(): void;\n declineAll(): void;\n submitCustomConsent(preferences: boolean, statistics: boolean, marketing: boolean): void;\n withdraw(): void;\n show(): void;\n renew(): void;\n}\n\nexport const EMPTY_CONSENT: PublicConsent = {\n necessary: true,\n preferences: false,\n statistics: false,\n marketing: false,\n personalizedAds: false,\n basicAds: false,\n adProfiling: false,\n adMeasurement: false,\n stamp: '',\n};\n\n/** null sentinel => used to detect \"called outside a ConsentProvider\". */\nexport const ConsentContext = createContext<ConsentContextValue | null>(null);\n","import { useContext } from 'react';\nimport { ConsentContext, type ConsentContextValue } from './context.js';\n\nexport type { ConsentContextValue };\n\n/** Access reactive consent state + actions. Must be used within a ConsentProvider. */\nexport function useConsent(): ConsentContextValue {\n const ctx = useContext(ConsentContext);\n if (!ctx) {\n throw new Error('useConsent must be used within a <ConsentProvider>.');\n }\n return ctx;\n}\n","import type { ReactNode } from 'react';\nimport type { Category } from './helpers.js';\nimport { useConsent } from './useConsent.js';\n\nexport interface ConsentGateProps {\n category: Exclude<Category, 'necessary'>;\n children: ReactNode;\n fallback?: ReactNode;\n}\n\n/** Renders children only when the given category is granted (else `fallback`). */\nexport function ConsentGate({ category, children, fallback = null }: ConsentGateProps) {\n const { consent } = useConsent();\n return <>{consent[category] ? children : fallback}</>;\n}\n","import { useContext, useEffect, useSyncExternalStore } from 'react';\nimport { ConsentContext } from './context.js';\nimport { consentCookie, isGranted, type CategoryId, type ConsentCookieOptions } from './helpers.js';\n\n/** Window events after which the embed's consent may differ. */\nconst CHANGE_EVENTS = ['CookieMunchOnChange', 'CookieMunchOnAccept', 'CookieMunchOnDecline'];\n\nfunction subscribe(onStoreChange: () => void): () => void {\n if (typeof window === 'undefined') return () => {};\n for (const e of CHANGE_EVENTS) window.addEventListener(e, onStoreChange);\n return () => {\n for (const e of CHANGE_EVENTS) window.removeEventListener(e, onStoreChange);\n };\n}\n\n/**\n * Whether `category` is granted right now — `'preferences'`, `'statistics'`,\n * `'marketing'`, `'necessary'` (always true) or one of your custom category ids — and\n * re-renders when that changes, whatever changed it.\n *\n * `false` until the embed has reported (and during SSR), so gated content never renders\n * ahead of consent. Works inside `<ConsentProvider>` and, when the embed is on the page\n * some other way, without one.\n *\n * const analytics = useConsentValue('statistics');\n */\nexport function useConsentValue(category: CategoryId): boolean {\n const ctx = useContext(ConsentContext);\n const standalone = useSyncExternalStore(\n subscribe,\n () => (typeof window === 'undefined' ? false : isGranted(window.CookieMunch?.consent, category)),\n () => false,\n );\n if (ctx) return ctx.ready ? isGranted(ctx.consent, category) : category === 'necessary';\n return standalone;\n}\n\n/**\n * {@link consentCookie} for a component's lifetime: the cookie is written while `category`\n * is granted and removed when it is not. Pass a stable `value` (or a lazy function); the\n * subscription is re-created when `name`, `category`, `value` or an option changes.\n *\n * useConsentCookie('affiliate_id', 'marketing', ref, { maxAgeDays: 30 });\n */\nexport function useConsentCookie(\n name: string,\n category: CategoryId,\n value: string | (() => string),\n opts: ConsentCookieOptions = {},\n): void {\n const { maxAgeDays, path, domain, sameSite, secure } = opts;\n useEffect(\n () => consentCookie(name, category, value, { maxAgeDays, path, domain, sameSite, secure }),\n [name, category, value, maxAgeDays, path, domain, sameSite, secure],\n );\n}\n","import { useCallback, useState, type MouseEvent, type ReactNode } from 'react';\nimport { isRightsLinkUrl } from './helpers.js';\n\n/** What `mint` may resolve to: the mint response from `POST /v1/sites/{cbid}/rights-links`, or just its `url`. */\nexport type MintedRightsLink = string | { url: string; customDomain?: string | null };\n\nexport interface RightsLinkProps {\n /**\n * Mints a single-use account link for the signed-in person — a server action (or an endpoint\n * you call) that holds a `dsar:rights-links` key and calls `POST /v1/sites/{cbid}/rights-links`.\n * Never put the key in the browser. Called on click, not on render: links are single-use and\n * expire (15 minutes by default), so one minted per page view would mostly go to waste.\n */\n mint: () => Promise<MintedRightsLink>;\n /** Where the link goes before a mint, and when one fails: the plain hosted form (the email-code flow), e.g. `https://cookiemunch.net/r/<cbid>`. */\n fallbackHref?: string;\n children?: ReactNode;\n className?: string;\n /** Called when a mint fails or returns a URL that is not a rights link, before falling back. */\n onError?: (error: Error) => void;\n}\n\n/**\n * \"Your privacy rights\" for a signed-in person: on click it mints an account link (their email is\n * filled in and locked, the email-code step skipped) and opens it. Plain anchor markup, so it\n * renders the same on the server and the client.\n */\nexport function RightsLink({ mint, fallbackHref, children = 'Your privacy rights', className, onError }: RightsLinkProps) {\n const [busy, setBusy] = useState(false);\n const onClick = useCallback(\n async (e: MouseEvent<HTMLAnchorElement>) => {\n // A modified click (new tab, download) keeps the fallback: a minted link is for this tab.\n if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;\n e.preventDefault();\n if (busy) return;\n setBusy(true);\n try {\n const got = await mint();\n const url = typeof got === 'string' ? got : got.url;\n const customDomain = typeof got === 'string' ? undefined : got.customDomain;\n if (!isRightsLinkUrl(url, customDomain)) throw new Error(`not a rights link: ${url}`);\n window.location.assign(url);\n } catch (err) {\n onError?.(err instanceof Error ? err : new Error(String(err)));\n if (fallbackHref) window.location.assign(fallbackHref);\n } finally {\n setBusy(false);\n }\n },\n [busy, mint, fallbackHref, onError],\n );\n return (\n <a href={fallbackHref ?? '#'} className={className} onClick={onClick} aria-busy={busy || undefined}>\n {children}\n </a>\n );\n}\n","import { useEffect, useRef } from 'react';\n\nexport interface CookieDeclarationProps {\n /** Shown when the site has no cookies to list yet (the mount's `data-empty`). */\n emptyText?: string;\n className?: string;\n id?: string;\n}\n\n/**\n * Stable across renders: React rewrites `innerHTML` only when the `__html` string changes,\n * so an empty string that never changes means React never touches what the embed drew.\n */\nconst EMPTY = { __html: '' };\n\n/**\n * The live cookie declaration, for a privacy page in a React / Next.js app.\n *\n * Renders `<div data-cc=\"declaration\">` and lets the embed draw the table into it. The\n * embed fills the element whenever it appears — on first load, after a client-side\n * navigation, or before hydration on a server-rendered page — so the element's children\n * belong to the embed, not to React:\n * - `dangerouslySetInnerHTML` with a constant empty string tells React it does not own\n * the children, so it neither hydrates nor replaces them;\n * - `suppressHydrationWarning` covers the one difference React would otherwise report:\n * the server sent an empty element and the embed may already have filled it.\n * After mount it asks the embed to draw this element, in case it was added after load.\n */\nexport function CookieDeclaration({ emptyText, className, id }: CookieDeclarationProps) {\n const ref = useRef<HTMLDivElement>(null);\n useEffect(() => {\n const el = ref.current;\n const api = typeof window !== 'undefined' ? window.CookieMunch : undefined;\n if (el && !el.hasChildNodes()) void api?.renderDeclaration?.(el)?.catch?.(() => {});\n }, []);\n return (\n <div\n ref={ref}\n id={id}\n className={className}\n data-cc=\"declaration\"\n {...(emptyText !== undefined ? { 'data-empty': emptyText } : {})}\n suppressHydrationWarning\n dangerouslySetInnerHTML={EMPTY}\n />\n );\n}\n","import { useSyncExternalStore } from 'react';\n\nfunction subscribe(onStoreChange: () => void): () => void {\n if (typeof window === 'undefined') return () => {};\n window.addEventListener('fd:layout', onStoreChange);\n return () => window.removeEventListener('fd:layout', onStoreChange);\n}\n\nfunction read(edge: 'bottom' | 'top'): number {\n if (typeof document === 'undefined') return 0;\n const v = document.documentElement.style.getPropertyValue(`--cookiemunch-inset-${edge}`);\n const n = parseFloat(v);\n return Number.isFinite(n) ? n : 0;\n}\n\n/**\n * How many pixels of the viewport's bottom (or top) edge the consent bar covers right now — 0\n * when no bar shows — re-rendering on every change. For floating UI the CSS variable\n * `--cookiemunch-inset-bottom` (or the vendor-neutral `--fd-safe-bottom`) does the same job\n * without a render; use this when the offset is computed in JavaScript.\n *\n * const inset = useBannerInset();\n * <ChatButton style={{ bottom: 20 + inset }} />\n *\n * 0 during SSR. Works with or without `<ConsentProvider>`.\n */\nexport function useBannerInset(edge: 'bottom' | 'top' = 'bottom'): number {\n return useSyncExternalStore(subscribe, () => read(edge), () => 0);\n}\n","import { useEffect, useRef } from 'react';\nimport { onConsentCategory, type ConsentTransition } from './helpers.js';\n\n/**\n * `onConsentCategory` as a hook: `fn` runs only when `category` changes (and once as a replay when the\n * visitor had already decided). The latest `fn` is always the one called; resubscribes only when the category changes.\n */\nexport function useConsentTransition(category: string, fn: (t: ConsentTransition) => void): void {\n const ref = useRef(fn);\n ref.current = fn;\n useEffect(() => onConsentCategory(category, (t) => ref.current(t)), [category]);\n}\n","import { useEffect, useRef } from 'react';\n\n/** The sync token identify() earns lasts a day (server IDENTITY_TOKEN_TTL_MS); re-link well before it lapses. */\nconst RELINK_MS = 12 * 60 * 60 * 1000;\n\nexport interface ConsentIdentityProps {\n /**\n * The signed-in person's id in your app (any stable string), or null/undefined when nobody is signed in.\n * A change re-links; null unlinks this browser.\n */\n subject: string | null | undefined;\n /**\n * Mints a fresh subject token for `aud: cookiemunch:<cbid>` — with Atlas,\n * `() => getToken({ for: 'cookiemunch', cbid })`. Called on sign-in and every 12 hours while mounted,\n * since a token is valid for 120 seconds only. Resolve null to skip a round.\n */\n getToken: () => Promise<string | null | undefined> | string | null | undefined;\n}\n\ntype Queue = { q?: unknown[]; version?: unknown; identify?: (token: string) => unknown };\n\nfunction identify(token: string): void {\n const w = window as unknown as { __consent?: Queue };\n const fd = (w.__consent = w.__consent || { q: [] });\n // Before the embed loads, the call waits in the queue and is replayed in order.\n if (fd.version && typeof fd.identify === 'function') void fd.identify(token);\n else fd.q?.push(['identify', token]);\n}\n\nfunction unlink(): void {\n (window as unknown as { CookieMunch?: { setSyncToken?: (t: string | null) => void } }).CookieMunch?.setSyncToken?.(null);\n}\n\n/**\n * Links the visitor's consent decision to the signed-in person, so it follows them to their other\n * devices (https://cookiemunch.net/docs/consent-api#linking-a-decision-to-a-signed-in-person).\n * Put it once in the root layout, inside whatever provides the session. Renders nothing.\n */\nexport function ConsentIdentity({ subject, getToken }: ConsentIdentityProps): null {\n const mint = useRef(getToken);\n mint.current = getToken;\n const linked = useRef(false);\n useEffect(() => {\n // Unlink only on sign-out: an anonymous first render must not clear a sync token set another way.\n if (!subject) {\n if (linked.current) unlink();\n linked.current = false;\n return;\n }\n linked.current = true;\n let live = true;\n const link = async (): Promise<void> => {\n try {\n const token = await mint.current();\n if (live && token) identify(token);\n } catch {\n // A failed mint links nothing; the next round (or the next sign-in) tries again.\n }\n };\n void link();\n const timer = setInterval(() => void link(), RELINK_MS);\n return () => {\n live = false;\n clearInterval(timer);\n };\n }, [subject]);\n return null;\n}\n","import type { ReactNode } from 'react';\n\nexport interface CookieSettingsLinkProps {\n children?: ReactNode;\n className?: string;\n /** Where the link points before the embed has loaded (or with scripts off). Default `#cookie-settings`. */\n href?: string;\n}\n\n/**\n * \"Cookie settings\": reopens the visitor's consent choices. It is plain markup — an anchor with\n * `data-cc=\"show-settings\"`, which the embed's own click listener turns into\n * `CookieMunch.showSettings()` — so it renders identically on the server and the client, needs no\n * `<ConsentProvider>`, and opens the panel exactly once (no second handler of its own).\n */\nexport function CookieSettingsLink({ children = 'Cookie settings', className, href = '#cookie-settings' }: CookieSettingsLinkProps) {\n return (\n <a href={href} className={className} data-cc=\"show-settings\">\n {children}\n </a>\n );\n}\n"],"mappings":";;;AAAA,SAAS,WAAW,QAAQ,gBAAgC;;;ACA5D,SAAS,qBAAqB;AAgBvB,IAAM,gBAA+B;AAAA,EAC1C,WAAW;AAAA,EACX,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB,UAAU;AAAA,EACV,aAAa;AAAA,EACb,eAAe;AAAA,EACf,OAAO;AACT;AAGO,IAAM,iBAAiB,cAA0C,IAAI;;;ADiGnE;AAzHT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I,CAAC,SAAS;AACZ,UAAI,OAAO,QAAS,QAAO;AAC3B,aAAO,UAAU;AACjB;AAAA,IACF;AACA,WAAO,UAAU;AACjB,QAAI,OAAO;AACX,UAAM,OAAO,YAA2B;AACtC,UAAI;AACF,cAAM,QAAQ,MAAM,KAAK,QAAQ;AACjC,YAAI,QAAQ,MAAO,UAAS,KAAK;AAAA,MACnC,QAAQ;AAAA,MAER;AAAA,IACF;AACA,SAAK,KAAK;AACV,UAAM,QAAQ,YAAY,MAAM,KAAK,KAAK,GAAG,SAAS;AACtD,WAAO,MAAM;AACX,aAAO;AACP,oBAAc,KAAK;AAAA,IACrB;AAAA,EACF,GAAG,CAAC,OAAO,CAAC;AACZ,SAAO;AACT;;;AClDI,gBAAAE,YAAA;AAFG,SAAS,mBAAmB,EAAE,WAAW,mBAAmB,WAAW,OAAO,mBAAmB,GAA4B;AAClI,SACE,gBAAAA,KAAC,OAAE,MAAY,WAAsB,WAAQ,iBAC1C,UACH;AAEJ;","names":["api","jsx","useContext","useEffect","useContext","useEffect","useState","jsx","useEffect","useRef","jsx","useSyncExternalStore","subscribe","useEffect","useRef","useEffect","useRef","jsx"]}
|
|
1
|
+
{"version":3,"sources":["../src/ConsentProvider.tsx","../src/context.ts","../src/useConsent.ts","../src/ConsentGate.tsx","../src/useConsentValue.ts","../src/RightsLink.tsx","../src/CookieDeclaration.tsx","../src/useBannerInset.ts","../src/useConsentTransition.ts","../src/ConsentIdentity.tsx","../src/CookieSettingsLink.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type ReactNode } from 'react';\nimport { ConsentContext, EMPTY_CONSENT, type ConsentContextValue } from './context.js';\nimport type { CookieMunchGlobal, PublicConsent } from './helpers.js';\n\n/** Default CDN location of the base browser embed. */\nconst DEFAULT_SRC = 'https://cdn.cookiemunch.net/consent.js';\n/** The <script> id the embed's bootstrap reads via getElementById. */\nconst SCRIPT_ID = 'CookieMunch';\n\nexport interface ConsentProviderProps {\n /** The Cookie Munch site id (required). Injected as `data-cbid` on the embed. */\n cbid: string;\n /** Embed URL. Defaults to the public CDN. */\n src?: string;\n /** Override the API base the embed beacons to (injected as `data-api`). */\n apiBase?: string;\n children: ReactNode;\n}\n\ninterface Snapshot {\n ready: boolean;\n consent: PublicConsent;\n hasResponse: boolean;\n consented: boolean;\n}\n\nconst INITIAL_SNAPSHOT: Snapshot = {\n ready: false,\n consent: EMPTY_CONSENT,\n hasResponse: false,\n consented: false,\n};\n\n/**\n * Locate the embed's <script> tag, injecting it if it isn't already present.\n * The embed self-bootstraps from the tag's `data-*` attributes and, once ready,\n * assigns `window.CookieMunch`.\n */\nfunction ensureEmbedScript(cbid: string, src: string, apiBase: string | undefined): void {\n const existing = document.getElementById(SCRIPT_ID);\n if (existing) return;\n const script = document.createElement('script');\n script.id = SCRIPT_ID;\n script.async = true;\n script.src = src;\n script.setAttribute('data-cbid', cbid);\n if (apiBase) script.setAttribute('data-api', apiBase);\n (document.head || document.documentElement).appendChild(script);\n}\n\n/**\n * Loads the Cookie Munch browser embed from the CDN at runtime and exposes\n * reactive consent state to descendants — a standalone script-tag SDK wrapper\n * that does NOT bundle the proprietary engine.\n *\n * SSR-safe: no `window`/`document` access during render; the script is injected\n * and the global API resolved only inside an effect. Descendants see an\n * all-denied, not-ready snapshot until the embed reports in.\n */\nexport function ConsentProvider({ cbid, src = DEFAULT_SRC, apiBase, children }: ConsentProviderProps) {\n const apiRef = useRef<CookieMunchGlobal | null>(null);\n const [snap, setSnap] = useState<Snapshot>(INITIAL_SNAPSHOT);\n\n useEffect(() => {\n if (typeof window === 'undefined' || typeof document === 'undefined') return;\n\n let disposed = false;\n let offConsentChange: (() => void) | null = null;\n let pollTimer: ReturnType<typeof setInterval> | null = null;\n\n const sync = (api: CookieMunchGlobal) => {\n if (disposed) return;\n setSnap({\n ready: true,\n consent: api.consent,\n hasResponse: api.hasResponse,\n consented: api.consented,\n });\n };\n\n const bind = (api: CookieMunchGlobal) => {\n if (disposed) return;\n apiRef.current = api;\n sync(api);\n offConsentChange = api.onConsentChange(() => sync(api));\n };\n\n // If the embed is already on the page, reuse it immediately.\n if (window.CookieMunch) {\n bind(window.CookieMunch);\n } else {\n ensureEmbedScript(cbid, src, apiBase);\n // The embed sets window.CookieMunch asynchronously (after its remote-config\n // fetch), so poll until it appears, then bind once.\n pollTimer = setInterval(() => {\n if (window.CookieMunch) {\n if (pollTimer) clearInterval(pollTimer);\n pollTimer = null;\n bind(window.CookieMunch);\n }\n }, 50);\n }\n\n return () => {\n disposed = true;\n if (pollTimer) clearInterval(pollTimer);\n offConsentChange?.();\n apiRef.current = null;\n };\n // Re-bind if the site id / source changes.\n }, [cbid, src, apiBase]);\n\n const api = apiRef.current;\n const value: ConsentContextValue = {\n ready: snap.ready,\n consent: snap.consent,\n hasResponse: snap.hasResponse,\n consented: snap.consented,\n acceptAll: () => api?.submitCustomConsent(true, true, true),\n declineAll: () => api?.submitCustomConsent(false, false, false),\n submitCustomConsent: (p, s, m) => api?.submitCustomConsent(p, s, m),\n withdraw: () => api?.withdraw(),\n show: () => api?.show(),\n renew: () => api?.renew(),\n };\n\n return <ConsentContext.Provider value={value}>{children}</ConsentContext.Provider>;\n}\n","import { createContext } from 'react';\nimport type { PublicConsent } from './helpers.js';\n\nexport interface ConsentContextValue {\n ready: boolean;\n consent: PublicConsent;\n hasResponse: boolean;\n consented: boolean;\n acceptAll(): void;\n declineAll(): void;\n submitCustomConsent(preferences: boolean, statistics: boolean, marketing: boolean): void;\n withdraw(): void;\n show(): void;\n renew(): void;\n}\n\nexport const EMPTY_CONSENT: PublicConsent = {\n necessary: true,\n preferences: false,\n statistics: false,\n marketing: false,\n personalizedAds: false,\n basicAds: false,\n adProfiling: false,\n adMeasurement: false,\n stamp: '',\n};\n\n/** null sentinel => used to detect \"called outside a ConsentProvider\". */\nexport const ConsentContext = createContext<ConsentContextValue | null>(null);\n","import { useContext } from 'react';\nimport { ConsentContext, type ConsentContextValue } from './context.js';\n\nexport type { ConsentContextValue };\n\n/** Access reactive consent state + actions. Must be used within a ConsentProvider. */\nexport function useConsent(): ConsentContextValue {\n const ctx = useContext(ConsentContext);\n if (!ctx) {\n throw new Error('useConsent must be used within a <ConsentProvider>.');\n }\n return ctx;\n}\n","import type { ReactNode } from 'react';\nimport type { Category } from './helpers.js';\nimport { useConsent } from './useConsent.js';\n\nexport interface ConsentGateProps {\n category: Exclude<Category, 'necessary'>;\n children: ReactNode;\n fallback?: ReactNode;\n}\n\n/** Renders children only when the given category is granted (else `fallback`). */\nexport function ConsentGate({ category, children, fallback = null }: ConsentGateProps) {\n const { consent } = useConsent();\n return <>{consent[category] ? children : fallback}</>;\n}\n","import { useContext, useEffect, useSyncExternalStore } from 'react';\nimport { ConsentContext } from './context.js';\nimport { consentCookie, isGranted, type CategoryId, type ConsentCookieOptions } from './helpers.js';\n\n/** Window events after which the embed's consent may differ. */\nconst CHANGE_EVENTS = ['CookieMunchOnChange', 'CookieMunchOnAccept', 'CookieMunchOnDecline'];\n\nfunction subscribe(onStoreChange: () => void): () => void {\n if (typeof window === 'undefined') return () => {};\n for (const e of CHANGE_EVENTS) window.addEventListener(e, onStoreChange);\n return () => {\n for (const e of CHANGE_EVENTS) window.removeEventListener(e, onStoreChange);\n };\n}\n\n/**\n * Whether `category` is granted right now — `'preferences'`, `'statistics'`,\n * `'marketing'`, `'necessary'` (always true) or one of your custom category ids — and\n * re-renders when that changes, whatever changed it.\n *\n * `false` until the embed has reported (and during SSR), so gated content never renders\n * ahead of consent. Works inside `<ConsentProvider>` and, when the embed is on the page\n * some other way, without one.\n *\n * const analytics = useConsentValue('statistics');\n */\nexport function useConsentValue(category: CategoryId): boolean {\n const ctx = useContext(ConsentContext);\n const standalone = useSyncExternalStore(\n subscribe,\n () => (typeof window === 'undefined' ? false : isGranted(window.CookieMunch?.consent, category)),\n () => false,\n );\n if (ctx) return ctx.ready ? isGranted(ctx.consent, category) : category === 'necessary';\n return standalone;\n}\n\n/**\n * {@link consentCookie} for a component's lifetime: the cookie is written while `category`\n * is granted and removed when it is not. Pass a stable `value` (or a lazy function); the\n * subscription is re-created when `name`, `category`, `value` or an option changes.\n *\n * useConsentCookie('affiliate_id', 'marketing', ref, { maxAgeDays: 30 });\n */\nexport function useConsentCookie(\n name: string,\n category: CategoryId,\n value: string | (() => string),\n opts: ConsentCookieOptions = {},\n): void {\n const { maxAgeDays, path, domain, sameSite, secure } = opts;\n useEffect(\n () => consentCookie(name, category, value, { maxAgeDays, path, domain, sameSite, secure }),\n [name, category, value, maxAgeDays, path, domain, sameSite, secure],\n );\n}\n","import { useCallback, useState, type MouseEvent, type ReactNode } from 'react';\nimport { isRightsLinkUrl } from './helpers.js';\n\n/** What `mint` may resolve to: the mint response from `POST /v1/sites/{cbid}/rights-links`, or just its `url`. */\nexport type MintedRightsLink = string | { url: string; customDomain?: string | null };\n\nexport interface RightsLinkProps {\n /**\n * Mints a single-use account link for the signed-in person — a server action (or an endpoint\n * you call) that holds a `dsar:rights-links` key and calls `POST /v1/sites/{cbid}/rights-links`.\n * Never put the key in the browser. Called on click, not on render: links are single-use and\n * expire (15 minutes by default), so one minted per page view would mostly go to waste.\n */\n mint: () => Promise<MintedRightsLink>;\n /** Where the link goes before a mint, and when one fails: the plain hosted form (the email-code flow), e.g. `https://cookiemunch.net/r/<cbid>`. */\n fallbackHref?: string;\n children?: ReactNode;\n className?: string;\n /** Called when a mint fails or returns a URL that is not a rights link, before falling back. */\n onError?: (error: Error) => void;\n}\n\n/**\n * \"Your privacy rights\" for a signed-in person: on click it mints an account link (their email is\n * filled in and locked, the email-code step skipped) and opens it. Plain anchor markup, so it\n * renders the same on the server and the client.\n */\nexport function RightsLink({ mint, fallbackHref, children = 'Your privacy rights', className, onError }: RightsLinkProps) {\n const [busy, setBusy] = useState(false);\n const onClick = useCallback(\n async (e: MouseEvent<HTMLAnchorElement>) => {\n // A modified click (new tab, download) keeps the fallback: a minted link is for this tab.\n if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;\n e.preventDefault();\n if (busy) return;\n setBusy(true);\n try {\n const got = await mint();\n const url = typeof got === 'string' ? got : got.url;\n const customDomain = typeof got === 'string' ? undefined : got.customDomain;\n if (!isRightsLinkUrl(url, customDomain)) throw new Error(`not a rights link: ${url}`);\n window.location.assign(url);\n } catch (err) {\n onError?.(err instanceof Error ? err : new Error(String(err)));\n if (fallbackHref) window.location.assign(fallbackHref);\n } finally {\n setBusy(false);\n }\n },\n [busy, mint, fallbackHref, onError],\n );\n return (\n <a href={fallbackHref ?? '#'} className={className} onClick={onClick} aria-busy={busy || undefined}>\n {children}\n </a>\n );\n}\n","import { useEffect, useRef } from 'react';\n\nexport interface CookieDeclarationProps {\n /** Shown when the site has no cookies to list yet (the mount's `data-empty`). */\n emptyText?: string;\n className?: string;\n id?: string;\n}\n\n/**\n * Stable across renders: React rewrites `innerHTML` only when the `__html` string changes,\n * so an empty string that never changes means React never touches what the embed drew.\n */\nconst EMPTY = { __html: '' };\n\n/**\n * The live cookie declaration, for a privacy page in a React / Next.js app.\n *\n * Renders `<div data-cc=\"declaration\">` and lets the embed draw the table into it. The\n * embed fills the element whenever it appears — on first load, after a client-side\n * navigation, or before hydration on a server-rendered page — so the element's children\n * belong to the embed, not to React:\n * - `dangerouslySetInnerHTML` with a constant empty string tells React it does not own\n * the children, so it neither hydrates nor replaces them;\n * - `suppressHydrationWarning` covers the one difference React would otherwise report:\n * the server sent an empty element and the embed may already have filled it.\n * After mount it asks the embed to draw this element, in case it was added after load.\n */\nexport function CookieDeclaration({ emptyText, className, id }: CookieDeclarationProps) {\n const ref = useRef<HTMLDivElement>(null);\n useEffect(() => {\n const el = ref.current;\n const api = typeof window !== 'undefined' ? window.CookieMunch : undefined;\n if (el && !el.hasChildNodes()) void api?.renderDeclaration?.(el)?.catch?.(() => {});\n }, []);\n return (\n <div\n ref={ref}\n id={id}\n className={className}\n data-cc=\"declaration\"\n {...(emptyText !== undefined ? { 'data-empty': emptyText } : {})}\n suppressHydrationWarning\n dangerouslySetInnerHTML={EMPTY}\n />\n );\n}\n","import { useSyncExternalStore } from 'react';\n\nfunction subscribe(onStoreChange: () => void): () => void {\n if (typeof window === 'undefined') return () => {};\n window.addEventListener('fd:layout', onStoreChange);\n return () => window.removeEventListener('fd:layout', onStoreChange);\n}\n\nfunction read(edge: 'bottom' | 'top'): number {\n if (typeof document === 'undefined') return 0;\n const v = document.documentElement.style.getPropertyValue(`--cookiemunch-inset-${edge}`);\n const n = parseFloat(v);\n return Number.isFinite(n) ? n : 0;\n}\n\n/**\n * How many pixels of the viewport's bottom (or top) edge the consent bar covers right now — 0\n * when no bar shows — re-rendering on every change. For floating UI the CSS variable\n * `--cookiemunch-inset-bottom` (or the vendor-neutral `--fd-safe-bottom`) does the same job\n * without a render; use this when the offset is computed in JavaScript.\n *\n * const inset = useBannerInset();\n * <ChatButton style={{ bottom: 20 + inset }} />\n *\n * 0 during SSR. Works with or without `<ConsentProvider>`.\n */\nexport function useBannerInset(edge: 'bottom' | 'top' = 'bottom'): number {\n return useSyncExternalStore(subscribe, () => read(edge), () => 0);\n}\n","import { useEffect, useRef } from 'react';\nimport { onConsentCategory, type ConsentTransition } from './helpers.js';\n\n/**\n * `onConsentCategory` as a hook: `fn` runs only when `category` changes (and once as a replay when the\n * visitor had already decided). The latest `fn` is always the one called; resubscribes only when the category changes.\n */\nexport function useConsentTransition(category: string, fn: (t: ConsentTransition) => void): void {\n const ref = useRef(fn);\n ref.current = fn;\n useEffect(() => onConsentCategory(category, (t) => ref.current(t)), [category]);\n}\n","import { useEffect, useRef } from 'react';\n\n/** The sync token identify() earns lasts a day (server IDENTITY_TOKEN_TTL_MS); re-link well before it lapses. */\nconst RELINK_MS = 12 * 60 * 60 * 1000;\n\nexport interface ConsentIdentityProps {\n /**\n * The signed-in person's id in your app (any stable string), or null/undefined when nobody is signed in.\n * A change re-links; null unlinks this browser.\n */\n subject: string | null | undefined;\n /**\n * Mints a fresh subject token for `aud: cookiemunch:<cbid>` — with Atlas,\n * `() => getToken({ for: 'cookiemunch', cbid })`. Called on sign-in and every 12 hours while mounted,\n * since a token is valid for 120 seconds only. Resolve null to skip a round.\n */\n getToken?: () => Promise<string | null | undefined> | string | null | undefined;\n /**\n * Instead of `getToken`: a same-origin route of yours that mints the token server-side and answers\n * `{ token }` to a GET, e.g. `/api/atlas/token/cookiemunch` (LinkHub CM-L14). Sent with the page's\n * cookies; a 401 is retried once, then that round is skipped.\n */\n tokenUrl?: string;\n}\n\nasync function fromUrl(url: string): Promise<string | null> {\n for (let attempt = 0; attempt < 2; attempt++) {\n const res = await fetch(url, { credentials: 'same-origin', headers: { Accept: 'application/json' } });\n if (res.status === 401 && attempt === 0) continue;\n if (!res.ok) return null;\n const t = ((await res.json()) as { token?: unknown } | null)?.token;\n return typeof t === 'string' && t ? t : null;\n }\n return null;\n}\n\ntype Queue = { q?: unknown[]; version?: unknown; identify?: (token: string) => unknown };\n\nfunction identify(token: string): void {\n const w = window as unknown as { __consent?: Queue };\n const fd = (w.__consent = w.__consent || { q: [] });\n // Before the embed loads, the call waits in the queue and is replayed in order.\n if (fd.version && typeof fd.identify === 'function') void fd.identify(token);\n else fd.q?.push(['identify', token]);\n}\n\nfunction unlink(): void {\n (window as unknown as { CookieMunch?: { setSyncToken?: (t: string | null) => void } }).CookieMunch?.setSyncToken?.(null);\n}\n\n/**\n * Links the visitor's consent decision to the signed-in person, so it follows them to their other\n * devices (https://cookiemunch.net/docs/consent-api#linking-a-decision-to-a-signed-in-person).\n * Put it once in the root layout, inside whatever provides the session. Renders nothing.\n */\nexport function ConsentIdentity({ subject, getToken, tokenUrl }: ConsentIdentityProps): null {\n const mint = useRef<() => unknown>(() => null);\n mint.current = getToken ?? (tokenUrl ? () => fromUrl(tokenUrl) : () => null);\n const linked = useRef(false);\n useEffect(() => {\n // Unlink only on sign-out: an anonymous first render must not clear a sync token set another way.\n if (!subject) {\n if (linked.current) unlink();\n linked.current = false;\n return;\n }\n linked.current = true;\n let live = true;\n const link = async (): Promise<void> => {\n try {\n const token = await mint.current();\n if (live && typeof token === 'string' && token) identify(token);\n } catch {\n // A failed mint links nothing; the next round (or the next sign-in) tries again.\n }\n };\n void link();\n const timer = setInterval(() => void link(), RELINK_MS);\n return () => {\n live = false;\n clearInterval(timer);\n };\n }, [subject]);\n return null;\n}\n","import type { ReactNode } from 'react';\n\nexport interface CookieSettingsLinkProps {\n children?: ReactNode;\n className?: string;\n /** Where the link points before the embed has loaded (or with scripts off). Default `#cookie-settings`. */\n href?: string;\n}\n\n/**\n * \"Cookie settings\": reopens the visitor's consent choices. It is plain markup — an anchor with\n * `data-cc=\"show-settings\"`, which the embed's own click listener turns into\n * `CookieMunch.showSettings()` — so it renders identically on the server and the client, needs no\n * `<ConsentProvider>`, and opens the panel exactly once (no second handler of its own).\n */\nexport function CookieSettingsLink({ children = 'Cookie settings', className, href = '#cookie-settings' }: CookieSettingsLinkProps) {\n return (\n <a href={href} className={className} data-cc=\"show-settings\">\n {children}\n </a>\n );\n}\n"],"mappings":";;;AAAA,SAAS,WAAW,QAAQ,gBAAgC;;;ACA5D,SAAS,qBAAqB;AAgBvB,IAAM,gBAA+B;AAAA,EAC1C,WAAW;AAAA,EACX,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB,UAAU;AAAA,EACV,aAAa;AAAA,EACb,eAAe;AAAA,EACf,OAAO;AACT;AAGO,IAAM,iBAAiB,cAA0C,IAAI;;;ADiGnE;AAzHT,IAAM,cAAc;AAEpB,IAAM,YAAY;AAmBlB,IAAM,mBAA6B;AAAA,EACjC,OAAO;AAAA,EACP,SAAS;AAAA,EACT,aAAa;AAAA,EACb,WAAW;AACb;AAOA,SAAS,kBAAkB,MAAc,KAAa,SAAmC;AACvF,QAAM,WAAW,SAAS,eAAe,SAAS;AAClD,MAAI,SAAU;AACd,QAAM,SAAS,SAAS,cAAc,QAAQ;AAC9C,SAAO,KAAK;AACZ,SAAO,QAAQ;AACf,SAAO,MAAM;AACb,SAAO,aAAa,aAAa,IA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IAAI,MAAM;AACvE,QAAM,SAASA,QAAO,KAAK;AAC3B,EAAAD,WAAU,MAAM;AAEd,QAAI,CAAC,SAAS;AACZ,UAAI,OAAO,QAAS,QAAO;AAC3B,aAAO,UAAU;AACjB;AAAA,IACF;AACA,WAAO,UAAU;AACjB,QAAI,OAAO;AACX,UAAM,OAAO,YAA2B;AACtC,UAAI;AACF,cAAM,QAAQ,MAAM,KAAK,QAAQ;AACjC,YAAI,QAAQ,OAAO,UAAU,YAAY,MAAO,UAAS,KAAK;AAAA,MAChE,QAAQ;AAAA,MAER;AAAA,IACF;AACA,SAAK,KAAK;AACV,UAAM,QAAQ,YAAY,MAAM,KAAK,KAAK,GAAG,SAAS;AACtD,WAAO,MAAM;AACX,aAAO;AACP,oBAAc,KAAK;AAAA,IACrB;AAAA,EACF,GAAG,CAAC,OAAO,CAAC;AACZ,SAAO;AACT;;;ACnEI,gBAAAE,YAAA;AAFG,SAAS,mBAAmB,EAAE,WAAW,mBAAmB,WAAW,OAAO,mBAAmB,GAA4B;AAClI,SACE,gBAAAA,KAAC,OAAE,MAAY,WAAsB,WAAQ,iBAC1C,UACH;AAEJ;","names":["api","jsx","useContext","useEffect","useContext","useEffect","useState","jsx","useEffect","useRef","jsx","useSyncExternalStore","subscribe","useEffect","useRef","useEffect","useRef","jsx"]}
|