@cookiemunch/react 0.4.0 → 0.5.1

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 CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  Every published release, newest first. Dates are the day the version was cut.
4
4
 
5
+ ## 0.5.1 (2026-11-04)
6
+
7
+ - Changed: published from CI with an npm provenance attestation; no code change.
8
+
9
+ ## 0.5.0 (2026-11-03)
10
+
11
+ - Added: `CookieMunchCategories`, an augmentable interface: `cookiemunch types` writes it so category arguments accept only your site's categories. Empty, any string still works.
12
+
5
13
  ## 0.4.0 (2026-11-02)
6
14
 
7
15
  - Added: types for `CookieMunch.consentState(category)` and `CookieMunch.onConsent(category, cb)` on the embed global.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Cookie Munch
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/client.d.ts CHANGED
@@ -1,8 +1,145 @@
1
- export { ConsentProvider, type ConsentProviderProps } from './ConsentProvider.js';
2
- export { useConsent, type ConsentContextValue } from './useConsent.js';
3
- export { ConsentGate, type ConsentGateProps } from './ConsentGate.js';
4
- export { useConsentValue, useConsentCookie } from './useConsentValue.js';
5
- export { RightsLink, type RightsLinkProps, type MintedRightsLink } from './RightsLink.js';
6
- export { CookieDeclaration, type CookieDeclarationProps } from './CookieDeclaration.js';
7
- export { useBannerInset } from './useBannerInset.js';
8
- export { CookieSettingsLink, type CookieSettingsLinkProps } from './CookieSettingsLink.js';
1
+ import * as react from 'react';
2
+ import { ReactNode } from 'react';
3
+ import { PublicConsent, Category, CategoryId, ConsentCookieOptions } from './helpers.js';
4
+
5
+ interface ConsentProviderProps {
6
+ /** The Cookie Munch site id (required). Injected as `data-cbid` on the embed. */
7
+ cbid: string;
8
+ /** Embed URL. Defaults to the public CDN. */
9
+ src?: string;
10
+ /** Override the API base the embed beacons to (injected as `data-api`). */
11
+ apiBase?: string;
12
+ children: ReactNode;
13
+ }
14
+ /**
15
+ * Loads the Cookie Munch browser embed from the CDN at runtime and exposes
16
+ * reactive consent state to descendants — a standalone script-tag SDK wrapper
17
+ * that does NOT bundle the proprietary engine.
18
+ *
19
+ * SSR-safe: no `window`/`document` access during render; the script is injected
20
+ * and the global API resolved only inside an effect. Descendants see an
21
+ * all-denied, not-ready snapshot until the embed reports in.
22
+ */
23
+ declare function ConsentProvider({ cbid, src, apiBase, children }: ConsentProviderProps): react.JSX.Element;
24
+
25
+ interface ConsentContextValue {
26
+ ready: boolean;
27
+ consent: PublicConsent;
28
+ hasResponse: boolean;
29
+ consented: boolean;
30
+ acceptAll(): void;
31
+ declineAll(): void;
32
+ submitCustomConsent(preferences: boolean, statistics: boolean, marketing: boolean): void;
33
+ withdraw(): void;
34
+ show(): void;
35
+ renew(): void;
36
+ }
37
+
38
+ /** Access reactive consent state + actions. Must be used within a ConsentProvider. */
39
+ declare function useConsent(): ConsentContextValue;
40
+
41
+ interface ConsentGateProps {
42
+ category: Exclude<Category, 'necessary'>;
43
+ children: ReactNode;
44
+ fallback?: ReactNode;
45
+ }
46
+ /** Renders children only when the given category is granted (else `fallback`). */
47
+ declare function ConsentGate({ category, children, fallback }: ConsentGateProps): react.JSX.Element;
48
+
49
+ /**
50
+ * Whether `category` is granted right now — `'preferences'`, `'statistics'`,
51
+ * `'marketing'`, `'necessary'` (always true) or one of your custom category ids — and
52
+ * re-renders when that changes, whatever changed it.
53
+ *
54
+ * `false` until the embed has reported (and during SSR), so gated content never renders
55
+ * ahead of consent. Works inside `<ConsentProvider>` and, when the embed is on the page
56
+ * some other way, without one.
57
+ *
58
+ * const analytics = useConsentValue('statistics');
59
+ */
60
+ declare function useConsentValue(category: CategoryId): boolean;
61
+ /**
62
+ * {@link consentCookie} for a component's lifetime: the cookie is written while `category`
63
+ * is granted and removed when it is not. Pass a stable `value` (or a lazy function); the
64
+ * subscription is re-created when `name`, `category`, `value` or an option changes.
65
+ *
66
+ * useConsentCookie('affiliate_id', 'marketing', ref, { maxAgeDays: 30 });
67
+ */
68
+ declare function useConsentCookie(name: string, category: CategoryId, value: string | (() => string), opts?: ConsentCookieOptions): void;
69
+
70
+ /** What `mint` may resolve to: the mint response from `POST /v1/sites/{cbid}/rights-links`, or just its `url`. */
71
+ type MintedRightsLink = string | {
72
+ url: string;
73
+ customDomain?: string | null;
74
+ };
75
+ interface RightsLinkProps {
76
+ /**
77
+ * Mints a single-use account link for the signed-in person — a server action (or an endpoint
78
+ * you call) that holds a `dsar:rights-links` key and calls `POST /v1/sites/{cbid}/rights-links`.
79
+ * Never put the key in the browser. Called on click, not on render: links are single-use and
80
+ * expire (15 minutes by default), so one minted per page view would mostly go to waste.
81
+ */
82
+ mint: () => Promise<MintedRightsLink>;
83
+ /** 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>`. */
84
+ fallbackHref?: string;
85
+ children?: ReactNode;
86
+ className?: string;
87
+ /** Called when a mint fails or returns a URL that is not a rights link, before falling back. */
88
+ onError?: (error: Error) => void;
89
+ }
90
+ /**
91
+ * "Your privacy rights" for a signed-in person: on click it mints an account link (their email is
92
+ * filled in and locked, the email-code step skipped) and opens it. Plain anchor markup, so it
93
+ * renders the same on the server and the client.
94
+ */
95
+ declare function RightsLink({ mint, fallbackHref, children, className, onError }: RightsLinkProps): react.JSX.Element;
96
+
97
+ interface CookieDeclarationProps {
98
+ /** Shown when the site has no cookies to list yet (the mount's `data-empty`). */
99
+ emptyText?: string;
100
+ className?: string;
101
+ id?: string;
102
+ }
103
+ /**
104
+ * The live cookie declaration, for a privacy page in a React / Next.js app (CKM-S-10).
105
+ *
106
+ * Renders `<div data-cc="declaration">` and lets the embed draw the table into it. The
107
+ * embed fills the element whenever it appears — on first load, after a client-side
108
+ * navigation, or before hydration on a server-rendered page — so the element's children
109
+ * belong to the embed, not to React:
110
+ * - `dangerouslySetInnerHTML` with a constant empty string tells React it does not own
111
+ * the children, so it neither hydrates nor replaces them;
112
+ * - `suppressHydrationWarning` covers the one difference React would otherwise report:
113
+ * the server sent an empty element and the embed may already have filled it.
114
+ * After mount it asks the embed to draw this element, in case it was added after load.
115
+ */
116
+ declare function CookieDeclaration({ emptyText, className, id }: CookieDeclarationProps): react.JSX.Element;
117
+
118
+ /**
119
+ * How many pixels of the viewport's bottom (or top) edge the consent bar covers right now — 0
120
+ * when no bar shows — re-rendering on every change. For floating UI the CSS variable
121
+ * `--cookiemunch-inset-bottom` (or the vendor-neutral `--fd-safe-bottom`) does the same job
122
+ * without a render; use this when the offset is computed in JavaScript.
123
+ *
124
+ * const inset = useBannerInset();
125
+ * <ChatButton style={{ bottom: 20 + inset }} />
126
+ *
127
+ * 0 during SSR. Works with or without `<ConsentProvider>`.
128
+ */
129
+ declare function useBannerInset(edge?: 'bottom' | 'top'): number;
130
+
131
+ interface CookieSettingsLinkProps {
132
+ children?: ReactNode;
133
+ className?: string;
134
+ /** Where the link points before the embed has loaded (or with scripts off). Default `#cookie-settings`. */
135
+ href?: string;
136
+ }
137
+ /**
138
+ * "Cookie settings": reopens the visitor's consent choices. It is plain markup — an anchor with
139
+ * `data-cc="show-settings"`, which the embed's own click listener turns into
140
+ * `CookieMunch.showSettings()` — so it renders identically on the server and the client, needs no
141
+ * `<ConsentProvider>`, and opens the panel exactly once (no second handler of its own).
142
+ */
143
+ declare function CookieSettingsLink({ children, className, href }: CookieSettingsLinkProps): react.JSX.Element;
144
+
145
+ export { type ConsentContextValue, ConsentGate, type ConsentGateProps, ConsentProvider, type ConsentProviderProps, CookieDeclaration, type CookieDeclarationProps, CookieSettingsLink, type CookieSettingsLinkProps, type MintedRightsLink, RightsLink, type RightsLinkProps, useBannerInset, useConsent, useConsentCookie, useConsentValue };
@@ -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/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 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: string): 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: string,\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 (CKM-S-10).\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 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,WA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,SAAS,KAAK,MAAgC;AAC5C,MAAI,OAAO,aAAa,YAAa,QAAO;AAC5C,QAAM,IAAI,SAAS,gBAAgB,MAAM,iBAAiB,uBAAuB,IAAI,EAAE;AACvF,QAAM,IAAI,WAAW,CAAC;AACtB,SAAO,OAAO,SAAS,CAAC,IAAI,IAAI;AAClC;AAaO,SAAS,eAAe,OAAyB,UAAkB;AACxE,SAAOD,sBAAqBC,YAAW,MAAM,KAAK,IAAI,GAAG,MAAM,CAAC;AAClE;;;ACXI,gBAAAC,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","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/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 (CKM-S-10).\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 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,mBA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iB,aAAa,aAAa;AAClD,SAAO,MAAM,OAAO,oBAAoB,aAAa,aAAa;AACpE;AAEA,SAAS,KAAK,MAAgC;AAC5C,MAAI,OAAO,aAAa,YAAa,QAAO;AAC5C,QAAM,IAAI,SAAS,gBAAgB,MAAM,iBAAiB,uBAAuB,IAAI,EAAE;AACvF,QAAM,IAAI,WAAW,CAAC;AACtB,SAAO,OAAO,SAAS,CAAC,IAAI,IAAI;AAClC;AAaO,SAAS,eAAe,OAAyB,UAAkB;AACxE,SAAOD,sBAAqBC,YAAW,MAAM,KAAK,IAAI,GAAG,MAAM,CAAC;AAClE;;;ACXI,gBAAAC,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","jsx"]}
package/dist/helpers.d.ts CHANGED
@@ -1,9 +1,167 @@
1
- export { consentCookie, isGranted, type ConsentCookieOptions } from './consent-cookie.js';
2
- export { CONSENT_COOKIE_NAME, parseConsentCookie, type ConsentCookieState } from './consent-parse.js';
3
- export type { Category, PublicConsent, CookieMunchGlobal } from './types.js';
1
+ /**
2
+ * "Store this only with consent" — the helper every integrator ends up writing.
3
+ *
4
+ * A first-party cookie of your own (an A/B bucket, an affiliate id, a chat session) is
5
+ * only lawful while the visitor consents to the category it belongs to. `consentCookie`
6
+ * writes it the moment that consent holds and removes it the moment it stops — a
7
+ * withdrawal from a footer link, a "Deny all", a selection that unticks the category —
8
+ * and does nothing at all until the embed has said what the visitor decided.
9
+ *
10
+ * Framework-free: it listens to the embed's `CookieMunchOnChange` window event, so it
11
+ * works with or without `<ConsentProvider>`, and with custom categories.
12
+ */
13
+ /** Anything carrying a category decision: the public `consent` snapshot or a `ConsentState`. */
14
+ type ConsentLike = Record<string, unknown> & {
15
+ custom?: Record<string, unknown>;
16
+ };
17
+ /**
18
+ * Whether `category` is granted in a consent snapshot. `necessary` is always granted. A
19
+ * custom category is read from the top level (the public `CookieMunch.consent` snapshot)
20
+ * or from `custom` (the `ConsentState` that events carry). Anything else: not granted.
21
+ */
22
+ declare function isGranted(consent: ConsentLike | null | undefined, category: string): boolean;
23
+ interface ConsentCookieOptions {
24
+ /** Lifetime in days. Default: a session cookie (no max-age). */
25
+ maxAgeDays?: number;
26
+ /** Default `/`. */
27
+ path?: string;
28
+ /** Domain attribute, e.g. `example.com` to share across subdomains. Default: host-only. */
29
+ domain?: string;
30
+ /** Default `Lax`. */
31
+ sameSite?: 'Lax' | 'Strict' | 'None';
32
+ /** Default: true on an https page. Forced on with `sameSite: 'None'`, as browsers require. */
33
+ secure?: boolean;
34
+ }
35
+ /**
36
+ * Keep the cookie `name` in step with consent for `category`: written (with `value`) while
37
+ * it is granted, removed when it is not. `value` may be a function, called only when the
38
+ * cookie is about to be written and is not already there — so an id is never even
39
+ * generated without consent, and a stored one survives page loads.
40
+ *
41
+ * Applies the current decision immediately when the embed has already loaded, then follows
42
+ * every change. Until the embed reports a decision, nothing is written or removed. Returns
43
+ * a function that stops following (the cookie is left as it is).
44
+ *
45
+ * const stop = consentCookie('ab_bucket', 'statistics', () => pickBucket(), { maxAgeDays: 30 });
46
+ */
47
+ declare function consentCookie(name: string, category: string, value: string | (() => string), opts?: ConsentCookieOptions): () => void;
48
+
49
+ /**
50
+ * Read the embed's consent cookie on the server, where `document` does not exist — a Server
51
+ * Component, a route handler, middleware:
52
+ *
53
+ * const consent = parseConsentCookie((await cookies()).get(CONSENT_COOKIE_NAME)?.value);
54
+ * if (isGranted(consent, 'statistics')) { ... }
55
+ *
56
+ * The wire format is the embed's: URL-encoded JSON of its consent state. A legacy Cookiebot
57
+ * `CookieConsent` value (a relaxed JS object literal) is read too. Standalone on purpose — this
58
+ * package never imports `@cookiemunch/core`.
59
+ */
60
+ /** The first-party cookie the embed stores the visitor's decision in. */
61
+ declare const CONSENT_COOKIE_NAME = "CookieMunch";
62
+ /** The category decisions a consent cookie carries. Pass it to `isGranted`. */
63
+ interface ConsentCookieState {
64
+ necessary: true;
65
+ preferences: boolean;
66
+ statistics: boolean;
67
+ marketing: boolean;
68
+ /** Custom categories the site defines, by id. */
69
+ custom?: Record<string, boolean>;
70
+ [key: string]: unknown;
71
+ }
72
+ /**
73
+ * The decisions in a consent cookie value, or `null` when there is none the embed would honour
74
+ * (not its format, or a required field missing or mistyped). `necessary` is always
75
+ * true, whatever the cookie says. `null` passed to `isGranted` grants only `necessary`.
76
+ */
77
+ declare function parseConsentCookie(raw: string | null | undefined): ConsentCookieState | null;
78
+
79
+ /**
80
+ * Local, standalone type definitions for the Cookie Munch browser embed's public
81
+ * surface. These are copied from the public shapes exposed on the global
82
+ * `window.CookieMunch` object so this package can be published WITHOUT depending
83
+ * on (or bundling) the proprietary `@cookiemunch/core` engine.
84
+ *
85
+ * Keep these in sync with the embed's public API by shape only — never import
86
+ * from `@cookiemunch/core`.
87
+ */
88
+ /** The four base consent categories. */
89
+ type Category = 'necessary' | 'preferences' | 'statistics' | 'marketing';
90
+ /**
91
+ * Empty until you augment it with your site's category ids (`cookiemunch types` writes the augmentation):
92
+ *
93
+ * declare module '@cookiemunch/react' { interface CookieMunchCategories { necessary: true; statistics: true } }
94
+ *
95
+ * Then every category argument (useConsentValue, useConsentCookie, consentState, onConsent, hasConsent) accepts only those.
96
+ */
97
+ interface CookieMunchCategories {
98
+ }
99
+ /** A category id: one of CookieMunchCategories' keys once augmented, any string until then. */
100
+ type CategoryId = [keyof CookieMunchCategories] extends [never] ? string : Extract<keyof CookieMunchCategories, string>;
101
+ /**
102
+ * The visitor's consent snapshot, mirroring what the embed exposes at
103
+ * `window.CookieMunch.consent`. Includes the four base categories, the granular
104
+ * advertising signals, and a receipt `stamp`. Custom category keys may also be
105
+ * present, hence the index signature.
106
+ */
107
+ interface PublicConsent {
108
+ necessary: boolean;
109
+ preferences: boolean;
110
+ statistics: boolean;
111
+ marketing: boolean;
112
+ /** Granular advertising signals (IAB TCF purposes), else fall back to `marketing`. */
113
+ personalizedAds: boolean;
114
+ basicAds: boolean;
115
+ adProfiling: boolean;
116
+ adMeasurement: boolean;
117
+ /** The current consent-receipt stamp. */
118
+ stamp: string;
119
+ /** Custom category keys are included when the site defines them. */
120
+ [key: string]: boolean | string;
121
+ }
122
+ /**
123
+ * The minimal shape of the global `window.CookieMunch` API this wrapper relies
124
+ * on. The real embed exposes a superset of this (Cookiebot-compatible facade);
125
+ * we only type the members we call.
126
+ */
127
+ interface CookieMunchGlobal {
128
+ readonly consent: PublicConsent;
129
+ readonly consented: boolean;
130
+ readonly hasResponse: boolean;
131
+ /** The site id, including one resolved from the page host (`data-cbid="auto"`); undefined until known. */
132
+ cbid?: string;
133
+ show(): void;
134
+ renew(): void;
135
+ /** Open the preference center / second layer. */
136
+ showSettings(): void;
137
+ withdraw(): void;
138
+ submitCustomConsent(preferences: boolean, statistics: boolean, marketing: boolean): void;
139
+ /** Subscribe to consent changes (accept/decline). Returns an unsubscribe fn. */
140
+ onConsentChange(callback: (state: unknown) => void): () => void;
141
+ /**
142
+ * Whether `category` (a site category id or an alias such as `functional`) is consented.
143
+ * An unknown category answers false. Optional: older embeds lack it.
144
+ */
145
+ hasConsent?(category: CategoryId): boolean;
146
+ /** `true` granted, `false` refused (or unknown name), `null` not decided yet. Optional: older embeds lack it. */
147
+ consentState?(category: CategoryId): boolean | null;
148
+ /** Call `callback` once when `category` is granted (a microtask later if it already is). Returns an unsubscribe. Optional: older embeds lack it. */
149
+ onConsent?(category: CategoryId, callback: () => void): () => void;
150
+ /** Draw the cookie declaration into `el` (all mounts when omitted). Optional: older embeds lack it. */
151
+ renderDeclaration?(el?: Element | null): Promise<void>;
152
+ }
153
+ /** Augment the browser `Window` with the embed's globals. */
154
+ declare global {
155
+ interface Window {
156
+ CookieMunch?: CookieMunchGlobal;
157
+ }
158
+ }
159
+
4
160
  /**
5
161
  * The URL shapes a minted link can have (docs: account-linked-rights): `https://<customDomain>/?t=…`
6
162
  * when the site has an active custom rights domain, else `https://<app>/r/<cbid>?t=…`. Anything
7
163
  * else — another scheme, no token — is refused rather than followed.
8
164
  */
9
- export declare function isRightsLinkUrl(url: string, customDomain?: string | null): boolean;
165
+ declare function isRightsLinkUrl(url: string, customDomain?: string | null): boolean;
166
+
167
+ export { CONSENT_COOKIE_NAME, type Category, type CategoryId, type ConsentCookieOptions, type ConsentCookieState, type CookieMunchCategories, type CookieMunchGlobal, type PublicConsent, consentCookie, isGranted, isRightsLinkUrl, parseConsentCookie };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/consent-cookie.ts","../src/consent-parse.ts","../src/helpers.ts"],"sourcesContent":["/**\n * \"Store this only with consent\" — the helper every integrator ends up writing.\n *\n * A first-party cookie of your own (an A/B bucket, an affiliate id, a chat session) is\n * only lawful while the visitor consents to the category it belongs to. `consentCookie`\n * writes it the moment that consent holds and removes it the moment it stops — a\n * withdrawal from a footer link, a \"Deny all\", a selection that unticks the category —\n * and does nothing at all until the embed has said what the visitor decided.\n *\n * Framework-free: it listens to the embed's `CookieMunchOnChange` window event, so it\n * works with or without `<ConsentProvider>`, and with custom categories.\n */\n\n/** Anything carrying a category decision: the public `consent` snapshot or a `ConsentState`. */\ntype ConsentLike = Record<string, unknown> & { custom?: Record<string, unknown> };\n\n/**\n * Whether `category` is granted in a consent snapshot. `necessary` is always granted. A\n * custom category is read from the top level (the public `CookieMunch.consent` snapshot)\n * or from `custom` (the `ConsentState` that events carry). Anything else: not granted.\n */\nexport function isGranted(consent: ConsentLike | null | undefined, category: string): boolean {\n if (category === 'necessary') return true;\n if (!consent) return false;\n const top = consent[category];\n if (typeof top === 'boolean') return top;\n return consent.custom?.[category] === true;\n}\n\nexport interface ConsentCookieOptions {\n /** Lifetime in days. Default: a session cookie (no max-age). */\n maxAgeDays?: number;\n /** Default `/`. */\n path?: string;\n /** Domain attribute, e.g. `example.com` to share across subdomains. Default: host-only. */\n domain?: string;\n /** Default `Lax`. */\n sameSite?: 'Lax' | 'Strict' | 'None';\n /** Default: true on an https page. Forced on with `sameSite: 'None'`, as browsers require. */\n secure?: boolean;\n}\n\n/** The detail of `CookieMunchOnChange` — only the part this helper reads. */\ninterface ChangeDetail {\n consent?: ConsentLike;\n}\n\nfunction hasDom(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\nfunction attributes(opts: ConsentCookieOptions): string[] {\n const parts = [`path=${opts.path ?? '/'}`];\n if (opts.domain) parts.push(`domain=${opts.domain}`);\n const sameSite = opts.sameSite ?? 'Lax';\n parts.push(`SameSite=${sameSite}`);\n const secure = opts.secure ?? (sameSite === 'None' || window.location?.protocol === 'https:');\n if (secure || sameSite === 'None') parts.push('Secure');\n return parts;\n}\n\nfunction setCookie(name: string, value: string, opts: ConsentCookieOptions): void {\n const parts = [`${name}=${encodeURIComponent(value)}`, ...attributes(opts)];\n if (typeof opts.maxAgeDays === 'number' && opts.maxAgeDays > 0) {\n parts.push(`max-age=${Math.round(opts.maxAgeDays * 86400)}`);\n }\n document.cookie = parts.join('; ');\n}\n\nfunction hasCookie(name: string): boolean {\n return document.cookie.split(';').some((c) => c.trim().startsWith(`${name}=`));\n}\n\n/** Delete with the same path and domain it was written with — a browser matches on all three. */\nfunction removeCookie(name: string, opts: ConsentCookieOptions): void {\n document.cookie = [`${name}=`, ...attributes(opts), 'max-age=0', 'expires=Thu, 01 Jan 1970 00:00:00 GMT'].join('; ');\n}\n\n/**\n * Keep the cookie `name` in step with consent for `category`: written (with `value`) while\n * it is granted, removed when it is not. `value` may be a function, called only when the\n * cookie is about to be written and is not already there — so an id is never even\n * generated without consent, and a stored one survives page loads.\n *\n * Applies the current decision immediately when the embed has already loaded, then follows\n * every change. Until the embed reports a decision, nothing is written or removed. Returns\n * a function that stops following (the cookie is left as it is).\n *\n * const stop = consentCookie('ab_bucket', 'statistics', () => pickBucket(), { maxAgeDays: 30 });\n */\nexport function consentCookie(\n name: string,\n category: string,\n value: string | (() => string),\n opts: ConsentCookieOptions = {},\n): () => void {\n if (!hasDom()) return () => {};\n\n let written: boolean | null = null;\n const apply = (consent: ConsentLike | null | undefined) => {\n if (!consent) return;\n const granted = isGranted(consent, category);\n if (granted) {\n // Once per grant, not on every repeated announcement. A lazy value that is already\n // stored (from an earlier page) is kept: regenerating it would, say, move a visitor\n // to a new A/B bucket on every page load.\n if (written !== true) {\n if (typeof value !== 'function') setCookie(name, value, opts);\n else if (!hasCookie(name)) setCookie(name, value(), opts);\n }\n } else {\n removeCookie(name, opts);\n }\n written = granted;\n };\n\n const onChange = (e: Event) => apply((e as CustomEvent<ChangeDetail>).detail?.consent);\n window.addEventListener('CookieMunchOnChange', onChange);\n\n // Already loaded: apply what is in force now. (A later load announces itself, including\n // a returning visitor's stored decision, through the same event.)\n const api = (window as { CookieMunch?: { consent?: unknown } }).CookieMunch;\n if (api?.consent) apply(api.consent as ConsentLike);\n\n return () => window.removeEventListener('CookieMunchOnChange', onChange);\n}\n","/**\n * Read the embed's consent cookie on the server, where `document` does not exist — a Server\n * Component, a route handler, middleware:\n *\n * const consent = parseConsentCookie((await cookies()).get(CONSENT_COOKIE_NAME)?.value);\n * if (isGranted(consent, 'statistics')) { ... }\n *\n * The wire format is the embed's: URL-encoded JSON of its consent state. A legacy Cookiebot\n * `CookieConsent` value (a relaxed JS object literal) is read too. Standalone on purpose — this\n * package never imports `@cookiemunch/core`.\n */\n\n/** The first-party cookie the embed stores the visitor's decision in. */\nexport const CONSENT_COOKIE_NAME = 'CookieMunch';\n\n/** The category decisions a consent cookie carries. Pass it to `isGranted`. */\nexport interface ConsentCookieState {\n necessary: true;\n preferences: boolean;\n statistics: boolean;\n marketing: boolean;\n /** Custom categories the site defines, by id. */\n custom?: Record<string, boolean>;\n [key: string]: unknown;\n}\n\nfunction decode(raw: string): string {\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n}\n\nfunction json(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\n/** `{stamp:'abc==',necessary:true,...}` → strict JSON: single quotes doubled, bare keys quoted. */\nfunction legacy(text: string): unknown {\n if (!text.includes('necessary')) return undefined;\n return json(text.replace(/'/g, '\"').replace(/([{,]\\s*)([A-Za-z_]\\w*)\\s*:/g, '$1\"$2\":'));\n}\n\n/**\n * The decisions in a consent cookie value, or `null` when there is none the embed would honour\n * (not its format, or a required field missing or mistyped). `necessary` is always\n * true, whatever the cookie says. `null` passed to `isGranted` grants only `necessary`.\n */\nexport function parseConsentCookie(raw: string | null | undefined): ConsentCookieState | null {\n if (!raw) return null;\n const text = decode(raw);\n const o = json(text) ?? legacy(text);\n if (o === null || typeof o !== 'object' || Array.isArray(o)) return null;\n const r = o as Record<string, unknown>;\n const { preferences, statistics, marketing } = r;\n if (typeof preferences !== 'boolean' || typeof statistics !== 'boolean' || typeof marketing !== 'boolean') return null;\n // The rest of what the embed requires before it honours a value (see /docs/consent-cookie).\n if (r.method !== 'explicit' && r.method !== 'implied') return null;\n if (typeof r.ver !== 'number' || typeof r.utc !== 'number' || typeof r.region !== 'string') return null;\n if (typeof r.stamp !== 'string' && typeof r.stamp !== 'number') return null;\n const state: ConsentCookieState = { necessary: true, preferences, statistics, marketing };\n if (r.custom !== null && typeof r.custom === 'object' && !Array.isArray(r.custom)) {\n const custom: Record<string, boolean> = {};\n for (const [k, v] of Object.entries(r.custom as Record<string, unknown>)) if (typeof v === 'boolean') custom[k] = v;\n if (Object.keys(custom).length > 0) state.custom = custom;\n }\n return state;\n}\n","// The server-safe half: no directive, nothing from React. Callable from a Server Component —\n// read the consent cookie from `cookies()` and decide what to render before any client code runs.\nexport { consentCookie, isGranted, type ConsentCookieOptions } from './consent-cookie.js';\nexport { CONSENT_COOKIE_NAME, parseConsentCookie, type ConsentCookieState } from './consent-parse.js';\nexport type { Category, PublicConsent, CookieMunchGlobal } from './types.js';\n\n/**\n * The URL shapes a minted link can have (docs: account-linked-rights): `https://<customDomain>/?t=…`\n * when the site has an active custom rights domain, else `https://<app>/r/<cbid>?t=…`. Anything\n * else — another scheme, no token — is refused rather than followed.\n */\nexport function isRightsLinkUrl(url: string, customDomain?: string | null): boolean {\n let u: URL;\n try {\n u = new URL(url);\n } catch {\n return false;\n }\n if (u.protocol !== 'https:' || !u.searchParams.get('t')) return false;\n if (customDomain) return u.host === customDomain && u.pathname === '/';\n return /^\\/r\\/[^/]+$/.test(u.pathname);\n}\n"],"mappings":";AAqBO,SAAS,UAAU,SAAyC,UAA2B;AAC5F,MAAI,aAAa,YAAa,QAAO;AACrC,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,MAAM,QAAQ,QAAQ;AAC5B,MAAI,OAAO,QAAQ,UAAW,QAAO;AACrC,SAAO,QAAQ,SAAS,QAAQ,MAAM;AACxC;AAoBA,SAAS,SAAkB;AACzB,SAAO,OAAO,WAAW,eAAe,OAAO,aAAa;AAC9D;AAEA,SAAS,WAAW,MAAsC;AACxD,QAAM,QAAQ,CAAC,QAAQ,KAAK,QAAQ,GAAG,EAAE;AACzC,MAAI,KAAK,OAAQ,OAAM,KAAK,UAAU,KAAK,MAAM,EAAE;AACnD,QAAM,WAAW,KAAK,YAAY;AAClC,QAAM,KAAK,YAAY,QAAQ,EAAE;AACjC,QAAM,SAAS,KAAK,WAAW,aAAa,UAAU,OAAO,UAAU,aAAa;AACpF,MAAI,UAAU,aAAa,OAAQ,OAAM,KAAK,QAAQ;AACtD,SAAO;AACT;AAEA,SAAS,UAAU,MAAc,OAAe,MAAkC;AAChF,QAAM,QAAQ,CAAC,GAAG,IAAI,IAAI,mBAAmB,KAAK,CAAC,IAAI,GAAG,WAAW,IAAI,CAAC;AAC1E,MAAI,OAAO,KAAK,eAAe,YAAY,KAAK,aAAa,GAAG;AAC9D,UAAM,KAAK,WAAW,KAAK,MAAM,KAAK,aAAa,KAAK,CAAC,EAAE;AAAA,EAC7D;AACA,WAAS,SAAS,MAAM,KAAK,IAAI;AACnC;AAEA,SAAS,U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IAAI,GAAG,EAAG,QAAO;AAChE,MAAI,aAAc,QAAO,EAAE,SAAS,gBAAgB,EAAE,aAAa;AACnE,SAAO,eAAe,KAAK,EAAE,QAAQ;AACvC;","names":[]}
1
+ {"version":3,"sources":["../src/consent-cookie.ts","../src/consent-parse.ts","../src/helpers.ts"],"sourcesContent":["/**\n * \"Store this only with consent\" — the helper every integrator ends up writing.\n *\n * A first-party cookie of your own (an A/B bucket, an affiliate id, a chat session) is\n * only lawful while the visitor consents to the category it belongs to. `consentCookie`\n * writes it the moment that consent holds and removes it the moment it stops — a\n * withdrawal from a footer link, a \"Deny all\", a selection that unticks the category —\n * and does nothing at all until the embed has said what the visitor decided.\n *\n * Framework-free: it listens to the embed's `CookieMunchOnChange` window event, so it\n * works with or without `<ConsentProvider>`, and with custom categories.\n */\n\n/** Anything carrying a category decision: the public `consent` snapshot or a `ConsentState`. */\ntype ConsentLike = Record<string, unknown> & { custom?: Record<string, unknown> };\n\n/**\n * Whether `category` is granted in a consent snapshot. `necessary` is always granted. A\n * custom category is read from the top level (the public `CookieMunch.consent` snapshot)\n * or from `custom` (the `ConsentState` that events carry). Anything else: not granted.\n */\nexport function isGranted(consent: ConsentLike | null | undefined, category: string): boolean {\n if (category === 'necessary') return true;\n if (!consent) return false;\n const top = consent[category];\n if (typeof top === 'boolean') return top;\n return consent.custom?.[category] === true;\n}\n\nexport interface ConsentCookieOptions {\n /** Lifetime in days. Default: a session cookie (no max-age). */\n maxAgeDays?: number;\n /** Default `/`. */\n path?: string;\n /** Domain attribute, e.g. `example.com` to share across subdomains. Default: host-only. */\n domain?: string;\n /** Default `Lax`. */\n sameSite?: 'Lax' | 'Strict' | 'None';\n /** Default: true on an https page. Forced on with `sameSite: 'None'`, as browsers require. */\n secure?: boolean;\n}\n\n/** The detail of `CookieMunchOnChange` — only the part this helper reads. */\ninterface ChangeDetail {\n consent?: ConsentLike;\n}\n\nfunction hasDom(): boolean {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\nfunction attributes(opts: ConsentCookieOptions): string[] {\n const parts = [`path=${opts.path ?? '/'}`];\n if (opts.domain) parts.push(`domain=${opts.domain}`);\n const sameSite = opts.sameSite ?? 'Lax';\n parts.push(`SameSite=${sameSite}`);\n const secure = opts.secure ?? (sameSite === 'None' || window.location?.protocol === 'https:');\n if (secure || sameSite === 'None') parts.push('Secure');\n return parts;\n}\n\nfunction setCookie(name: string, value: string, opts: ConsentCookieOptions): void {\n const parts = [`${name}=${encodeURIComponent(value)}`, ...attributes(opts)];\n if (typeof opts.maxAgeDays === 'number' && opts.maxAgeDays > 0) {\n parts.push(`max-age=${Math.round(opts.maxAgeDays * 86400)}`);\n }\n document.cookie = parts.join('; ');\n}\n\nfunction hasCookie(name: string): boolean {\n return document.cookie.split(';').some((c) => c.trim().startsWith(`${name}=`));\n}\n\n/** Delete with the same path and domain it was written with — a browser matches on all three. */\nfunction removeCookie(name: string, opts: ConsentCookieOptions): void {\n document.cookie = [`${name}=`, ...attributes(opts), 'max-age=0', 'expires=Thu, 01 Jan 1970 00:00:00 GMT'].join('; ');\n}\n\n/**\n * Keep the cookie `name` in step with consent for `category`: written (with `value`) while\n * it is granted, removed when it is not. `value` may be a function, called only when the\n * cookie is about to be written and is not already there — so an id is never even\n * generated without consent, and a stored one survives page loads.\n *\n * Applies the current decision immediately when the embed has already loaded, then follows\n * every change. Until the embed reports a decision, nothing is written or removed. Returns\n * a function that stops following (the cookie is left as it is).\n *\n * const stop = consentCookie('ab_bucket', 'statistics', () => pickBucket(), { maxAgeDays: 30 });\n */\nexport function consentCookie(\n name: string,\n category: string,\n value: string | (() => string),\n opts: ConsentCookieOptions = {},\n): () => void {\n if (!hasDom()) return () => {};\n\n let written: boolean | null = null;\n const apply = (consent: ConsentLike | null | undefined) => {\n if (!consent) return;\n const granted = isGranted(consent, category);\n if (granted) {\n // Once per grant, not on every repeated announcement. A lazy value that is already\n // stored (from an earlier page) is kept: regenerating it would, say, move a visitor\n // to a new A/B bucket on every page load.\n if (written !== true) {\n if (typeof value !== 'function') setCookie(name, value, opts);\n else if (!hasCookie(name)) setCookie(name, value(), opts);\n }\n } else {\n removeCookie(name, opts);\n }\n written = granted;\n };\n\n const onChange = (e: Event) => apply((e as CustomEvent<ChangeDetail>).detail?.consent);\n window.addEventListener('CookieMunchOnChange', onChange);\n\n // Already loaded: apply what is in force now. (A later load announces itself, including\n // a returning visitor's stored decision, through the same event.)\n const api = (window as { CookieMunch?: { consent?: unknown } }).CookieMunch;\n if (api?.consent) apply(api.consent as ConsentLike);\n\n return () => window.removeEventListener('CookieMunchOnChange', onChange);\n}\n","/**\n * Read the embed's consent cookie on the server, where `document` does not exist — a Server\n * Component, a route handler, middleware:\n *\n * const consent = parseConsentCookie((await cookies()).get(CONSENT_COOKIE_NAME)?.value);\n * if (isGranted(consent, 'statistics')) { ... }\n *\n * The wire format is the embed's: URL-encoded JSON of its consent state. A legacy Cookiebot\n * `CookieConsent` value (a relaxed JS object literal) is read too. Standalone on purpose — this\n * package never imports `@cookiemunch/core`.\n */\n\n/** The first-party cookie the embed stores the visitor's decision in. */\nexport const CONSENT_COOKIE_NAME = 'CookieMunch';\n\n/** The category decisions a consent cookie carries. Pass it to `isGranted`. */\nexport interface ConsentCookieState {\n necessary: true;\n preferences: boolean;\n statistics: boolean;\n marketing: boolean;\n /** Custom categories the site defines, by id. */\n custom?: Record<string, boolean>;\n [key: string]: unknown;\n}\n\nfunction decode(raw: string): string {\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n}\n\nfunction json(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\n/** `{stamp:'abc==',necessary:true,...}` → strict JSON: single quotes doubled, bare keys quoted. */\nfunction legacy(text: string): unknown {\n if (!text.includes('necessary')) return undefined;\n return json(text.replace(/'/g, '\"').replace(/([{,]\\s*)([A-Za-z_]\\w*)\\s*:/g, '$1\"$2\":'));\n}\n\n/**\n * The decisions in a consent cookie value, or `null` when there is none the embed would honour\n * (not its format, or a required field missing or mistyped). `necessary` is always\n * true, whatever the cookie says. `null` passed to `isGranted` grants only `necessary`.\n */\nexport function parseConsentCookie(raw: string | null | undefined): ConsentCookieState | null {\n if (!raw) return null;\n const text = decode(raw);\n const o = json(text) ?? legacy(text);\n if (o === null || typeof o !== 'object' || Array.isArray(o)) return null;\n const r = o as Record<string, unknown>;\n const { preferences, statistics, marketing } = r;\n if (typeof preferences !== 'boolean' || typeof statistics !== 'boolean' || typeof marketing !== 'boolean') return null;\n // The rest of what the embed requires before it honours a value (see /docs/consent-cookie).\n if (r.method !== 'explicit' && r.method !== 'implied') return null;\n if (typeof r.ver !== 'number' || typeof r.utc !== 'number' || typeof r.region !== 'string') return null;\n if (typeof r.stamp !== 'string' && typeof r.stamp !== 'number') return null;\n const state: ConsentCookieState = { necessary: true, preferences, statistics, marketing };\n if (r.custom !== null && typeof r.custom === 'object' && !Array.isArray(r.custom)) {\n const custom: Record<string, boolean> = {};\n for (const [k, v] of Object.entries(r.custom as Record<string, unknown>)) if (typeof v === 'boolean') custom[k] = v;\n if (Object.keys(custom).length > 0) state.custom = custom;\n }\n return state;\n}\n","// The server-safe half: no directive, nothing from React. Callable from a Server Component —\n// read the consent cookie from `cookies()` and decide what to render before any client code runs.\nexport { consentCookie, isGranted, type ConsentCookieOptions } from './consent-cookie.js';\nexport { CONSENT_COOKIE_NAME, parseConsentCookie, type ConsentCookieState } from './consent-parse.js';\nexport type { Category, CategoryId, CookieMunchCategories, PublicConsent, CookieMunchGlobal } from './types.js';\n\n/**\n * The URL shapes a minted link can have (docs: account-linked-rights): `https://<customDomain>/?t=…`\n * when the site has an active custom rights domain, else `https://<app>/r/<cbid>?t=…`. Anything\n * else — another scheme, no token — is refused rather than followed.\n */\nexport function isRightsLinkUrl(url: string, customDomain?: string | null): boolean {\n let u: URL;\n try {\n u = new URL(url);\n } catch {\n return false;\n }\n if (u.protocol !== 'https:' || !u.searchParams.get('t')) return false;\n if (customDomain) return u.host === customDomain && u.pathname === '/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KAAK,OAAO,IAAI;AACnC,MAAI,MAAM,QAAQ,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,EAAG,QAAO;AACpE,QAAM,IAAI;AACV,QAAM,EAAE,aAAa,YAAY,UAAU,IAAI;AAC/C,MAAI,OAAO,gBAAgB,aAAa,OAAO,eAAe,aAAa,OAAO,cAAc,UAAW,QAAO;AAElH,MAAI,EAAE,WAAW,cAAc,EAAE,WAAW,UAAW,QAAO;AAC9D,MAAI,OAAO,EAAE,QAAQ,YAAY,OAAO,EAAE,QAAQ,YAAY,OAAO,EAAE,WAAW,SAAU,QAAO;AACnG,MAAI,OAAO,EAAE,UAAU,YAAY,OAAO,EAAE,UAAU,SAAU,QAAO;AACvE,QAAM,QAA4B,EAAE,WAAW,MAAM,aAAa,YAAY,UAAU;AACxF,MAAI,EAAE,WAAW,QAAQ,OAAO,EAAE,WAAW,YAAY,CAAC,MAAM,QAAQ,EAAE,MAAM,GAAG;AACjF,UAAM,SAAkC,CAAC;AACzC,eAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,EAAE,MAAiC,EAAG,KAAI,OAAO,MAAM,UAAW,QAAO,CAAC,IAAI;AAClH,QAAI,OAAO,KAAK,MAAM,EAAE,SAAS,EAAG,OAAM,SAAS;AAAA,EACrD;AACA,SAAO;AACT;;;AC7DO,SAAS,gBAAgB,KAAa,cAAuC;AAClF,MAAI;AACJ,MAAI;AACF,QAAI,IAAI,IAAI,GAAG;AAAA,EACjB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,EAAE,aAAa,YAAY,CAAC,EAAE,aAAa,IAAI,GAAG,EAAG,QAAO;AAChE,MAAI,aAAc,QAAO,EAAE,SAAS,gBAAgB,EAAE,aAAa;AACnE,SAAO,eAAe,KAAK,EAAE,QAAQ;AACvC;","names":[]}
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { ConsentProvider, type ConsentProviderProps, useConsent, type ConsentContextValue, ConsentGate, type ConsentGateProps, useConsentValue, useConsentCookie, useBannerInset, RightsLink, type RightsLinkProps, type MintedRightsLink, CookieDeclaration, type CookieDeclarationProps, CookieSettingsLink, type CookieSettingsLinkProps, } from './client.js';
2
- export { consentCookie, isGranted, type ConsentCookieOptions, CONSENT_COOKIE_NAME, parseConsentCookie, isRightsLinkUrl, type ConsentCookieState, type Category, type PublicConsent, type CookieMunchGlobal, } from './helpers.js';
1
+ export { ConsentContextValue, ConsentGate, ConsentGateProps, ConsentProvider, ConsentProviderProps, CookieDeclaration, CookieDeclarationProps, CookieSettingsLink, CookieSettingsLinkProps, MintedRightsLink, RightsLink, RightsLinkProps, useBannerInset, useConsent, useConsentCookie, useConsentValue } from './client.js';
2
+ export { CONSENT_COOKIE_NAME, Category, CategoryId, ConsentCookieOptions, ConsentCookieState, CookieMunchCategories, CookieMunchGlobal, PublicConsent, consentCookie, isGranted, isRightsLinkUrl, parseConsentCookie } from './helpers.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["// No directive here, only re-exports. On the React Server layer Next turns the client.js names\n// into client references and leaves the helpers as plain functions, so one root import —\n// `import { ConsentProvider, isGranted } from '@cookiemunch/react'` — works in a Server Component.\nexport {\n ConsentProvider,\n type ConsentProviderProps,\n useConsent,\n type ConsentContextValue,\n ConsentGate,\n type ConsentGateProps,\n useConsentValue,\n useConsentCookie,\n useBannerInset,\n RightsLink,\n type RightsLinkProps,\n type MintedRightsLink,\n CookieDeclaration,\n type CookieDeclarationProps,\n CookieSettingsLink,\n type CookieSettingsLinkProps,\n} from './client.js';\nexport {\n consentCookie,\n isGranted,\n type ConsentCookieOptions,\n CONSENT_COOKIE_NAME,\n parseConsentCookie,\n isRightsLinkUrl,\n type ConsentCookieState,\n type Category,\n type PublicConsent,\n type CookieMunchGlobal,\n} from './helpers.js';\n"],"mappings":";AAGA;AAAA,EACE;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;AAAA,EAEA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OAKK;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["// No directive here, only re-exports. On the React Server layer Next turns the client.js names\n// into client references and leaves the helpers as plain functions, so one root import —\n// `import { ConsentProvider, isGranted } from '@cookiemunch/react'` — works in a Server Component.\nexport {\n ConsentProvider,\n type ConsentProviderProps,\n useConsent,\n type ConsentContextValue,\n ConsentGate,\n type ConsentGateProps,\n useConsentValue,\n useConsentCookie,\n useBannerInset,\n RightsLink,\n type RightsLinkProps,\n type MintedRightsLink,\n CookieDeclaration,\n type CookieDeclarationProps,\n CookieSettingsLink,\n type CookieSettingsLinkProps,\n} from './client.js';\nexport {\n consentCookie,\n isGranted,\n type ConsentCookieOptions,\n CONSENT_COOKIE_NAME,\n parseConsentCookie,\n isRightsLinkUrl,\n type ConsentCookieState,\n type Category,\n type CategoryId,\n type CookieMunchCategories,\n type PublicConsent,\n type CookieMunchGlobal,\n} from './helpers.js';\n"],"mappings":";AAGA;AAAA,EACE;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;AAAA,EAEA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OAOK;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cookiemunch/react",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "React/Next wrapper for Cookie Munch",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -17,6 +17,10 @@
17
17
  "README.md",
18
18
  "CHANGELOG.md"
19
19
  ],
20
+ "scripts": {
21
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup",
22
+ "test": "vitest run"
23
+ },
20
24
  "peerDependencies": {
21
25
  "react": ">=18"
22
26
  },
@@ -29,8 +33,17 @@
29
33
  "url": "https://github.com/Cookie-Munch/react/issues"
30
34
  },
31
35
  "license": "MIT",
32
- "scripts": {
33
- "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup",
34
- "test": "vitest run"
36
+ "devDependencies": {
37
+ "@testing-library/dom": "10.4.1",
38
+ "@testing-library/react": "16.3.2",
39
+ "@types/node": "22.20.0",
40
+ "@types/react": "19.2.17",
41
+ "@types/react-dom": "19.2.3",
42
+ "happy-dom": "21.0.4",
43
+ "react": "19.2.7",
44
+ "react-dom": "19.2.7",
45
+ "tsup": "8.5.1",
46
+ "typescript": "5.9.3",
47
+ "vitest": "2.1.9"
35
48
  }
36
- }
49
+ }
@@ -1,9 +0,0 @@
1
- import type { ReactNode } from 'react';
2
- import type { Category } from './helpers.js';
3
- export interface ConsentGateProps {
4
- category: Exclude<Category, 'necessary'>;
5
- children: ReactNode;
6
- fallback?: ReactNode;
7
- }
8
- /** Renders children only when the given category is granted (else `fallback`). */
9
- export declare function ConsentGate({ category, children, fallback }: ConsentGateProps): import("react").JSX.Element;
@@ -1,20 +0,0 @@
1
- import { type ReactNode } from 'react';
2
- export interface ConsentProviderProps {
3
- /** The Cookie Munch site id (required). Injected as `data-cbid` on the embed. */
4
- cbid: string;
5
- /** Embed URL. Defaults to the public CDN. */
6
- src?: string;
7
- /** Override the API base the embed beacons to (injected as `data-api`). */
8
- apiBase?: string;
9
- children: ReactNode;
10
- }
11
- /**
12
- * Loads the Cookie Munch browser embed from the CDN at runtime and exposes
13
- * reactive consent state to descendants — a standalone script-tag SDK wrapper
14
- * that does NOT bundle the proprietary engine.
15
- *
16
- * SSR-safe: no `window`/`document` access during render; the script is injected
17
- * and the global API resolved only inside an effect. Descendants see an
18
- * all-denied, not-ready snapshot until the embed reports in.
19
- */
20
- export declare function ConsentProvider({ cbid, src, apiBase, children }: ConsentProviderProps): import("react").JSX.Element;
@@ -1,20 +0,0 @@
1
- export interface CookieDeclarationProps {
2
- /** Shown when the site has no cookies to list yet (the mount's `data-empty`). */
3
- emptyText?: string;
4
- className?: string;
5
- id?: string;
6
- }
7
- /**
8
- * The live cookie declaration, for a privacy page in a React / Next.js app (CKM-S-10).
9
- *
10
- * Renders `<div data-cc="declaration">` and lets the embed draw the table into it. The
11
- * embed fills the element whenever it appears — on first load, after a client-side
12
- * navigation, or before hydration on a server-rendered page — so the element's children
13
- * belong to the embed, not to React:
14
- * - `dangerouslySetInnerHTML` with a constant empty string tells React it does not own
15
- * the children, so it neither hydrates nor replaces them;
16
- * - `suppressHydrationWarning` covers the one difference React would otherwise report:
17
- * the server sent an empty element and the embed may already have filled it.
18
- * After mount it asks the embed to draw this element, in case it was added after load.
19
- */
20
- export declare function CookieDeclaration({ emptyText, className, id }: CookieDeclarationProps): import("react").JSX.Element;
@@ -1,14 +0,0 @@
1
- import type { ReactNode } from 'react';
2
- export interface CookieSettingsLinkProps {
3
- children?: ReactNode;
4
- className?: string;
5
- /** Where the link points before the embed has loaded (or with scripts off). Default `#cookie-settings`. */
6
- href?: string;
7
- }
8
- /**
9
- * "Cookie settings": reopens the visitor's consent choices. It is plain markup — an anchor with
10
- * `data-cc="show-settings"`, which the embed's own click listener turns into
11
- * `CookieMunch.showSettings()` — so it renders identically on the server and the client, needs no
12
- * `<ConsentProvider>`, and opens the panel exactly once (no second handler of its own).
13
- */
14
- export declare function CookieSettingsLink({ children, className, href }: CookieSettingsLinkProps): import("react").JSX.Element;
@@ -1,27 +0,0 @@
1
- import { type ReactNode } from 'react';
2
- /** What `mint` may resolve to: the mint response from `POST /v1/sites/{cbid}/rights-links`, or just its `url`. */
3
- export type MintedRightsLink = string | {
4
- url: string;
5
- customDomain?: string | null;
6
- };
7
- export interface RightsLinkProps {
8
- /**
9
- * Mints a single-use account link for the signed-in person — a server action (or an endpoint
10
- * you call) that holds a `dsar:rights-links` key and calls `POST /v1/sites/{cbid}/rights-links`.
11
- * Never put the key in the browser. Called on click, not on render: links are single-use and
12
- * expire (15 minutes by default), so one minted per page view would mostly go to waste.
13
- */
14
- mint: () => Promise<MintedRightsLink>;
15
- /** 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>`. */
16
- fallbackHref?: string;
17
- children?: ReactNode;
18
- className?: string;
19
- /** Called when a mint fails or returns a URL that is not a rights link, before falling back. */
20
- onError?: (error: Error) => void;
21
- }
22
- /**
23
- * "Your privacy rights" for a signed-in person: on click it mints an account link (their email is
24
- * filled in and locked, the email-code step skipped) and opens it. Plain anchor markup, so it
25
- * renders the same on the server and the client.
26
- */
27
- export declare function RightsLink({ mint, fallbackHref, children, className, onError }: RightsLinkProps): import("react").JSX.Element;
@@ -1,48 +0,0 @@
1
- /**
2
- * "Store this only with consent" — the helper every integrator ends up writing.
3
- *
4
- * A first-party cookie of your own (an A/B bucket, an affiliate id, a chat session) is
5
- * only lawful while the visitor consents to the category it belongs to. `consentCookie`
6
- * writes it the moment that consent holds and removes it the moment it stops — a
7
- * withdrawal from a footer link, a "Deny all", a selection that unticks the category —
8
- * and does nothing at all until the embed has said what the visitor decided.
9
- *
10
- * Framework-free: it listens to the embed's `CookieMunchOnChange` window event, so it
11
- * works with or without `<ConsentProvider>`, and with custom categories.
12
- */
13
- /** Anything carrying a category decision: the public `consent` snapshot or a `ConsentState`. */
14
- type ConsentLike = Record<string, unknown> & {
15
- custom?: Record<string, unknown>;
16
- };
17
- /**
18
- * Whether `category` is granted in a consent snapshot. `necessary` is always granted. A
19
- * custom category is read from the top level (the public `CookieMunch.consent` snapshot)
20
- * or from `custom` (the `ConsentState` that events carry). Anything else: not granted.
21
- */
22
- export declare function isGranted(consent: ConsentLike | null | undefined, category: string): boolean;
23
- export interface ConsentCookieOptions {
24
- /** Lifetime in days. Default: a session cookie (no max-age). */
25
- maxAgeDays?: number;
26
- /** Default `/`. */
27
- path?: string;
28
- /** Domain attribute, e.g. `example.com` to share across subdomains. Default: host-only. */
29
- domain?: string;
30
- /** Default `Lax`. */
31
- sameSite?: 'Lax' | 'Strict' | 'None';
32
- /** Default: true on an https page. Forced on with `sameSite: 'None'`, as browsers require. */
33
- secure?: boolean;
34
- }
35
- /**
36
- * Keep the cookie `name` in step with consent for `category`: written (with `value`) while
37
- * it is granted, removed when it is not. `value` may be a function, called only when the
38
- * cookie is about to be written and is not already there — so an id is never even
39
- * generated without consent, and a stored one survives page loads.
40
- *
41
- * Applies the current decision immediately when the embed has already loaded, then follows
42
- * every change. Until the embed reports a decision, nothing is written or removed. Returns
43
- * a function that stops following (the cookie is left as it is).
44
- *
45
- * const stop = consentCookie('ab_bucket', 'statistics', () => pickBucket(), { maxAgeDays: 30 });
46
- */
47
- export declare function consentCookie(name: string, category: string, value: string | (() => string), opts?: ConsentCookieOptions): () => void;
48
- export {};
@@ -1,29 +0,0 @@
1
- /**
2
- * Read the embed's consent cookie on the server, where `document` does not exist — a Server
3
- * Component, a route handler, middleware:
4
- *
5
- * const consent = parseConsentCookie((await cookies()).get(CONSENT_COOKIE_NAME)?.value);
6
- * if (isGranted(consent, 'statistics')) { ... }
7
- *
8
- * The wire format is the embed's: URL-encoded JSON of its consent state. A legacy Cookiebot
9
- * `CookieConsent` value (a relaxed JS object literal) is read too. Standalone on purpose — this
10
- * package never imports `@cookiemunch/core`.
11
- */
12
- /** The first-party cookie the embed stores the visitor's decision in. */
13
- export declare const CONSENT_COOKIE_NAME = "CookieMunch";
14
- /** The category decisions a consent cookie carries. Pass it to `isGranted`. */
15
- export interface ConsentCookieState {
16
- necessary: true;
17
- preferences: boolean;
18
- statistics: boolean;
19
- marketing: boolean;
20
- /** Custom categories the site defines, by id. */
21
- custom?: Record<string, boolean>;
22
- [key: string]: unknown;
23
- }
24
- /**
25
- * The decisions in a consent cookie value, or `null` when there is none the embed would honour
26
- * (not its format, or a required field missing or mistyped). `necessary` is always
27
- * true, whatever the cookie says. `null` passed to `isGranted` grants only `necessary`.
28
- */
29
- export declare function parseConsentCookie(raw: string | null | undefined): ConsentCookieState | null;
package/dist/context.d.ts DELETED
@@ -1,16 +0,0 @@
1
- import type { PublicConsent } from './helpers.js';
2
- export interface ConsentContextValue {
3
- ready: boolean;
4
- consent: PublicConsent;
5
- hasResponse: boolean;
6
- consented: boolean;
7
- acceptAll(): void;
8
- declineAll(): void;
9
- submitCustomConsent(preferences: boolean, statistics: boolean, marketing: boolean): void;
10
- withdraw(): void;
11
- show(): void;
12
- renew(): void;
13
- }
14
- export declare const EMPTY_CONSENT: PublicConsent;
15
- /** null sentinel => used to detect "called outside a ConsentProvider". */
16
- export declare const ConsentContext: import("react").Context<ConsentContextValue | null>;
package/dist/types.d.ts DELETED
@@ -1,69 +0,0 @@
1
- /**
2
- * Local, standalone type definitions for the Cookie Munch browser embed's public
3
- * surface. These are copied from the public shapes exposed on the global
4
- * `window.CookieMunch` object so this package can be published WITHOUT depending
5
- * on (or bundling) the proprietary `@cookiemunch/core` engine.
6
- *
7
- * Keep these in sync with the embed's public API by shape only — never import
8
- * from `@cookiemunch/core`.
9
- */
10
- /** The four base consent categories. */
11
- export type Category = 'necessary' | 'preferences' | 'statistics' | 'marketing';
12
- /**
13
- * The visitor's consent snapshot, mirroring what the embed exposes at
14
- * `window.CookieMunch.consent`. Includes the four base categories, the granular
15
- * advertising signals, and a receipt `stamp`. Custom category keys may also be
16
- * present, hence the index signature.
17
- */
18
- export interface PublicConsent {
19
- necessary: boolean;
20
- preferences: boolean;
21
- statistics: boolean;
22
- marketing: boolean;
23
- /** Granular advertising signals (IAB TCF purposes), else fall back to `marketing`. */
24
- personalizedAds: boolean;
25
- basicAds: boolean;
26
- adProfiling: boolean;
27
- adMeasurement: boolean;
28
- /** The current consent-receipt stamp. */
29
- stamp: string;
30
- /** Custom category keys are included when the site defines them. */
31
- [key: string]: boolean | string;
32
- }
33
- /**
34
- * The minimal shape of the global `window.CookieMunch` API this wrapper relies
35
- * on. The real embed exposes a superset of this (Cookiebot-compatible facade);
36
- * we only type the members we call.
37
- */
38
- export interface CookieMunchGlobal {
39
- readonly consent: PublicConsent;
40
- readonly consented: boolean;
41
- readonly hasResponse: boolean;
42
- /** The site id, including one resolved from the page host (`data-cbid="auto"`); undefined until known. */
43
- cbid?: string;
44
- show(): void;
45
- renew(): void;
46
- /** Open the preference center / second layer. */
47
- showSettings(): void;
48
- withdraw(): void;
49
- submitCustomConsent(preferences: boolean, statistics: boolean, marketing: boolean): void;
50
- /** Subscribe to consent changes (accept/decline). Returns an unsubscribe fn. */
51
- onConsentChange(callback: (state: unknown) => void): () => void;
52
- /**
53
- * Whether `category` (a site category id or an alias such as `functional`) is consented.
54
- * An unknown category answers false. Optional: older embeds lack it.
55
- */
56
- hasConsent?(category: string): boolean;
57
- /** `true` granted, `false` refused (or unknown name), `null` not decided yet. Optional: older embeds lack it. */
58
- consentState?(category: string): boolean | null;
59
- /** Call `callback` once when `category` is granted (a microtask later if it already is). Returns an unsubscribe. Optional: older embeds lack it. */
60
- onConsent?(category: string, callback: () => void): () => void;
61
- /** Draw the cookie declaration into `el` (all mounts when omitted). Optional: older embeds lack it. */
62
- renderDeclaration?(el?: Element | null): Promise<void>;
63
- }
64
- /** Augment the browser `Window` with the embed's globals. */
65
- declare global {
66
- interface Window {
67
- CookieMunch?: CookieMunchGlobal;
68
- }
69
- }
@@ -1,12 +0,0 @@
1
- /**
2
- * How many pixels of the viewport's bottom (or top) edge the consent bar covers right now — 0
3
- * when no bar shows — re-rendering on every change. For floating UI the CSS variable
4
- * `--cookiemunch-inset-bottom` (or the vendor-neutral `--fd-safe-bottom`) does the same job
5
- * without a render; use this when the offset is computed in JavaScript.
6
- *
7
- * const inset = useBannerInset();
8
- * <ChatButton style={{ bottom: 20 + inset }} />
9
- *
10
- * 0 during SSR. Works with or without `<ConsentProvider>`.
11
- */
12
- export declare function useBannerInset(edge?: 'bottom' | 'top'): number;
@@ -1,4 +0,0 @@
1
- import { type ConsentContextValue } from './context.js';
2
- export type { ConsentContextValue };
3
- /** Access reactive consent state + actions. Must be used within a ConsentProvider. */
4
- export declare function useConsent(): ConsentContextValue;
@@ -1,21 +0,0 @@
1
- import { type ConsentCookieOptions } from './helpers.js';
2
- /**
3
- * Whether `category` is granted right now — `'preferences'`, `'statistics'`,
4
- * `'marketing'`, `'necessary'` (always true) or one of your custom category ids — and
5
- * re-renders when that changes, whatever changed it.
6
- *
7
- * `false` until the embed has reported (and during SSR), so gated content never renders
8
- * ahead of consent. Works inside `<ConsentProvider>` and, when the embed is on the page
9
- * some other way, without one.
10
- *
11
- * const analytics = useConsentValue('statistics');
12
- */
13
- export declare function useConsentValue(category: string): boolean;
14
- /**
15
- * {@link consentCookie} for a component's lifetime: the cookie is written while `category`
16
- * is granted and removed when it is not. Pass a stable `value` (or a lazy function); the
17
- * subscription is re-created when `name`, `category`, `value` or an option changes.
18
- *
19
- * useConsentCookie('affiliate_id', 'marketing', ref, { maxAgeDays: 30 });
20
- */
21
- export declare function useConsentCookie(name: string, category: string, value: string | (() => string), opts?: ConsentCookieOptions): void;