@cookiemunch/react 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,246 @@
1
- # Temporary Holding Version
1
+ # React SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Full documentation: https://cookiemunch.net/docs/sdk-react
4
+
5
+ `@cookiemunch/react` is a thin React/Next.js wrapper around the Cookie Munch browser embed (`consent.js`). It does not bundle the consent engine itself — at runtime it injects the same `<script data-cbid="...">` tag you'd otherwise hand-write, waits for the embed to assign `window.CookieMunch`, and exposes that object's state and actions through a context, a hook, and a gating component. Because the engine stays out of your bundle, this package has no dependency on `@cookiemunch/core` — it only depends on `react` (`>=18`) as a peer dependency, and ships pre-built (no separate build step in your app).
6
+
7
+ If you already have `consent.js` on the page some other way (Google Tag Manager, a `<script>` tag in your HTML template, a previous SSR render), `ConsentProvider` detects the existing `window.CookieMunch` and reuses it instead of injecting a second copy.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install @cookiemunch/react
13
+ # or
14
+ pnpm add @cookiemunch/react
15
+ # or
16
+ yarn add @cookiemunch/react
17
+ ```
18
+
19
+ ## Quick start
20
+
21
+ Wrap your app (or just the part of the tree that needs consent state) in `<ConsentProvider>`, giving it your site id (`cbid`):
22
+
23
+ ```tsx
24
+ // app/layout.tsx (Next.js App Router) or your root component
25
+ import { ConsentProvider } from '@cookiemunch/react';
26
+
27
+ export default function RootLayout({ children }: { children: React.ReactNode }) {
28
+ return (
29
+ <html lang="en">
30
+ <body>
31
+ <ConsentProvider cbid="your-site-id">{children}</ConsentProvider>
32
+ </body>
33
+ </html>
34
+ );
35
+ }
36
+ ```
37
+
38
+ That's it — the banner itself is rendered by the embed script, not by React. The provider's job is purely to load `consent.js` and mirror its state into React so the rest of your component tree can read it and react to it.
39
+
40
+ ### `ConsentProviderProps`
41
+
42
+ | Prop | Type | Required | Description |
43
+ | --- | --- | --- | --- |
44
+ | `cbid` | `string` | yes | Your Cookie Munch site id. Injected as `data-cbid` on the embed `<script>` tag. |
45
+ | `src` | `string` | no | URL of the embed script. Defaults to `https://cdn.cookiemunch.net/consent.js` — override only to serve it from your own static origin. |
46
+ | `apiBase` | `string` | no | Overrides the API origin the embed beacons consent decisions to. Injected as `data-api`. Omit it to use the default (same origin as the CDN). |
47
+ | `children` | `ReactNode` | yes | Your app tree. |
48
+
49
+ `ConsentProvider` is SSR-safe: it never touches `window` or `document` during render, only inside an effect. Until the embed reports in, descendants see a not-ready, all-denied snapshot (`necessary: true`, everything else `false`) rather than throwing or blocking render.
50
+
51
+ ### Next.js App Router
52
+
53
+ From 0.1.1 a Server Component can import from the package root directly. The `app/layout.tsx` above works as written: no wrapper file, and no `"use client"` in your layout. Your layout and the pages under it stay Server Components; only the provider and the hooks run in the browser.
54
+
55
+ The package is built as two modules behind the root:
56
+
57
+ | Module | Directive | Exports |
58
+ | --- | --- | --- |
59
+ | client | `"use client"` | `ConsentProvider`, `useConsent`, `useConsentValue`, `useConsentCookie`, `ConsentGate` |
60
+ | helpers | none | `isGranted`, `parseConsentCookie`, `CONSENT_COOKIE_NAME`, `consentCookie`, the types |
61
+
62
+ The root entry has no directive and only re-exports the two. In a Server Component, Next.js turns the client names into client references, and the helpers stay plain functions you can call there. So a single import serves both:
63
+
64
+ ```tsx
65
+ // app/layout.tsx — a Server Component
66
+ import { cookies } from 'next/headers';
67
+ import { ConsentProvider, CONSENT_COOKIE_NAME, isGranted, parseConsentCookie } from '@cookiemunch/react';
68
+
69
+ export default async function RootLayout({ children }: { children: React.ReactNode }) {
70
+ const consent = parseConsentCookie((await cookies()).get(CONSENT_COOKIE_NAME)?.value);
71
+ return (
72
+ <html lang="en">
73
+ <body>
74
+ <ConsentProvider cbid="your-site-id">{children}</ConsentProvider>
75
+ {isGranted(consent, 'statistics') && <script src="/analytics.js" async />}
76
+ </body>
77
+ </html>
78
+ );
79
+ }
80
+ ```
81
+
82
+ `parseConsentCookie(value)` reads the embed's `CookieMunch` cookie: the URL-encoded JSON the embed writes, plain JSON, or a legacy Cookiebot value. It returns the decision, or `null` when there is none the embed would honour. `isGranted(null, category)` is `true` only for `necessary`. It does not apply `minVersion` or `expiryDays`. For those, use `readConsent` from `@cookiemunch/sdk/consent` (see [the consent cookie](/docs/consent-cookie)).
83
+
84
+ Hooks and components still only work in Client Components. `consentCookie` can be imported anywhere, but it does nothing on the server, because there is no `document` there.
85
+
86
+ On 0.1.0, importing `ConsentProvider` in a Server Component failed `next build` with *"You're importing a component that needs `useEffect`"*. If you added a wrapper for that (a `providers.tsx` with `"use client"` that re-exports `ConsentProvider`), it still works, and you can delete it after upgrading.
87
+
88
+ If `cbid`, `src`, or `apiBase` change on a re-render, the provider re-binds to the (possibly new) embed instance.
89
+
90
+ ## Reading consent with `useConsent()`
91
+
92
+ Call `useConsent()` from any descendant of `ConsentProvider`. It throws if called outside one, so you'll find out immediately if the provider is missing higher up the tree.
93
+
94
+ ```tsx
95
+ import { useConsent } from '@cookiemunch/react';
96
+
97
+ function CookieSettingsLink() {
98
+ const { show, ready } = useConsent();
99
+ if (!ready) return null;
100
+ return <button onClick={show}>Cookie settings</button>;
101
+ }
102
+ ```
103
+
104
+ `useConsent()` returns a `ConsentContextValue`:
105
+
106
+ | Field | Type | Description |
107
+ | --- | --- | --- |
108
+ | `ready` | `boolean` | `true` once the embed has loaded and reported its first state. |
109
+ | `consent` | `PublicConsent` | The current per-category snapshot (see below). |
110
+ | `hasResponse` | `boolean` | `true` once the visitor has any recorded decision, explicit or implied. |
111
+ | `consented` | `boolean` | `true` once the visitor has an active, valid consent decision. |
112
+ | `acceptAll()` | `() => void` | Grants every category. |
113
+ | `declineAll()` | `() => void` | Denies every non-necessary category. |
114
+ | `submitCustomConsent(preferences, statistics, marketing)` | `(boolean, boolean, boolean) => void` | Records a specific per-category decision, bypassing the banner UI — e.g. for a custom preferences form you build in React. |
115
+ | `withdraw()` | `() => void` | Revokes all non-necessary consent and re-blocks previously activated scripts. |
116
+ | `show()` | `() => void` | Opens the phase-1 banner. |
117
+ | `renew()` | `() => void` | Re-prompts on the site's configured surface (banner, or straight to preferences if configured that way). |
118
+
119
+ `consent` is a `PublicConsent` object:
120
+
121
+ ```ts
122
+ interface PublicConsent {
123
+ necessary: boolean;
124
+ preferences: boolean;
125
+ statistics: boolean;
126
+ marketing: boolean;
127
+ personalizedAds: boolean; // granular IAB TCF signal, falls back to `marketing`
128
+ basicAds: boolean;
129
+ adProfiling: boolean;
130
+ adMeasurement: boolean;
131
+ stamp: string; // the consent-receipt id
132
+ [key: string]: boolean | string; // custom categories, if your config defines any
133
+ }
134
+ ```
135
+
136
+ Before the embed has reported in (`ready === false`), `consent` reads as `{ necessary: true, preferences: false, statistics: false, marketing: false, ... , stamp: '' }` — treat that as "no decision yet," not as an explicit decline.
137
+
138
+ Because `submitCustomConsent` bypasses the embed's own UI, you can also build a fully custom preferences screen in React — a form that toggles checkboxes and calls `submitCustomConsent(preferences, statistics, marketing)` on submit — and it still writes through the same engine, ledger, and receipt stamp as the stock banner.
139
+
140
+ ## Gating components with `<ConsentGate>`
141
+
142
+ `<ConsentGate>` renders its children only when a given category is granted, and a `fallback` (default `null`) otherwise. It's a thin wrapper over `useConsent()` — use it when you want to keep a component tree declarative rather than branching on `consent[category]` yourself:
143
+
144
+ ```tsx
145
+ import { ConsentGate } from '@cookiemunch/react';
146
+
147
+ function Page() {
148
+ return (
149
+ <ConsentGate category="marketing" fallback={<p>Enable marketing cookies to see this widget.</p>}>
150
+ <RetargetingPixel />
151
+ </ConsentGate>
152
+ );
153
+ }
154
+ ```
155
+
156
+ ### `ConsentGateProps`
157
+
158
+ | Prop | Type | Required | Description |
159
+ | --- | --- | --- | --- |
160
+ | `category` | `'preferences' \| 'statistics' \| 'marketing'` | yes | The category to gate on. `'necessary'` is intentionally excluded — it's always granted, so gating on it would be a no-op. |
161
+ | `children` | `ReactNode` | yes | Rendered when `category` is granted. |
162
+ | `fallback` | `ReactNode` | no | Rendered when it isn't. Defaults to `null`. |
163
+
164
+ `ConsentGate` re-renders automatically whenever consent changes, because it reads from the same context `ConsentProvider` updates. There's no polling or manual refresh needed.
165
+
166
+ ## Reacting to consent changes
167
+
168
+ `useConsent()`'s returned values already update on every accept/decline, so the most common pattern is simply reading `consent` inside a component and letting React re-render it. To run an imperative side effect (e.g. lazily initializing a third-party SDK) when a category newly becomes granted, combine it with `useEffect`:
169
+
170
+ ```tsx
171
+ import { useConsent } from '@cookiemunch/react';
172
+ import { useEffect } from 'react';
173
+
174
+ function AnalyticsBootstrap() {
175
+ const { consent, ready } = useConsent();
176
+
177
+ useEffect(() => {
178
+ if (ready && consent.statistics) {
179
+ initAnalytics();
180
+ }
181
+ }, [ready, consent.statistics]);
182
+
183
+ return null;
184
+ }
185
+ ```
186
+
187
+ This mirrors what `window.CookieMunch.onConsentChange()` does at the embed level (see the [JavaScript API](https://cookiemunch.net/docs/js-api) docs) — `ConsentProvider` already subscribes to that event and flows updates through React state, so you never call `onConsentChange` yourself from React code.
188
+
189
+ ## One category: `useConsentValue(category)`
190
+
191
+ When a component cares about one category, read just that:
192
+
193
+ ```tsx
194
+ import { useConsentValue } from '@cookiemunch/react';
195
+
196
+ function ChatWidget() {
197
+ const allowed = useConsentValue('chat'); // a custom category id works the same way
198
+ return allowed ? <LiveChat /> : <ChatPlaceholder />;
199
+ }
200
+ ```
201
+
202
+ It returns `true` while `category` is granted and re-renders when that changes, whatever changed it — a click, a withdrawal from a footer link, a returning visitor's stored decision. `'necessary'` is always `true`; everything else is `false` until the embed has reported, and during server rendering, so gated content never appears ahead of consent. It works inside `<ConsentProvider>` and also without one, when `consent.js` is on the page some other way: it then follows the embed's [`CookieMunchOnChange`](https://cookiemunch.net/docs/js-api) event directly.
203
+
204
+ ## Store this only with consent: `consentCookie` and `useConsentCookie`
205
+
206
+ A first-party cookie of your own — an A/B bucket, an affiliate reference, a chat session — is only lawful while the visitor consents to its category. `consentCookie` keeps one in step: written while the category is granted, removed the moment it is not.
207
+
208
+ ```tsx
209
+ import { useConsentCookie, consentCookie } from '@cookiemunch/react';
210
+
211
+ // In a component: follows consent for as long as the component is mounted.
212
+ function Affiliate({ ref }: { ref: string }) {
213
+ useConsentCookie('aff_ref', 'marketing', ref, { maxAgeDays: 30 });
214
+ return null;
215
+ }
216
+
217
+ // Anywhere else (no React needed): returns a function that stops following.
218
+ const stop = consentCookie('ab_bucket', 'statistics', () => pickBucket(), { maxAgeDays: 90 });
219
+ ```
220
+
221
+ `consentCookie(name, category, value, options?)`:
222
+
223
+ - writes `name=value` (URL-encoded) when `category` is granted, and deletes it — with the same path and domain, which a browser requires to match — when it is not: a "Deny all", a selection that unticks the category, or `CookieMunch.withdraw()`
224
+ - does nothing until the embed has reported a decision; if the embed is already loaded it applies the current decision at once, and a returning visitor's stored decision is applied when the embed starts
225
+ - takes `value` as a string or a function. A function is called only when the cookie is about to be written and is not already there, so an id is never generated without consent, and one stored on an earlier page is kept rather than regenerated
226
+ - works with custom categories
227
+
228
+ | Option | Meaning |
229
+ | --- | --- |
230
+ | `maxAgeDays` | Lifetime in days. Default: a session cookie. |
231
+ | `path` | Default `/`. |
232
+ | `domain` | Share across subdomains, e.g. `example.com`. Default: host-only. |
233
+ | `sameSite` | `Lax` (default), `Strict` or `None`. |
234
+ | `secure` | Default: on for an HTTPS page; always on with `sameSite: 'None'`. |
235
+
236
+ `useConsentCookie(name, category, value, options?)` is the same thing tied to a component's lifetime. Pass a stable `value` (or a function defined outside render), since a change re-creates the subscription. Unmounting stops following but leaves the cookie as it is.
237
+
238
+ `isGranted(consent, category)` is the predicate both use, exported for your own code: it reads a category from `CookieMunch.consent` or from an event's `ConsentState`, custom categories included.
239
+
240
+ To read the same decision on your server, see [the consent cookie](https://cookiemunch.net/docs/consent-cookie).
241
+
242
+ ## Notes
243
+
244
+ - There is no `<ConsentBanner>` export in `@cookiemunch/react` — banner UI is rendered by the embed script itself (configured from your Cookie Munch dashboard), not by React. `ConsentProvider` only bridges its state into your component tree. If you want a fully custom banner, hide the stock one in your config and drive `submitCustomConsent`/`acceptAll`/`declineAll` from your own UI as shown above.
245
+ - Everything exported (`ConsentProvider`, `useConsent`, `ConsentGate`, `useConsentValue`, `useConsentCookie`, `consentCookie`, `isGranted`, `parseConsentCookie`, `CONSENT_COOKIE_NAME`, and the `Category` / `PublicConsent` / `CookieMunchGlobal` / `ConsentCookieState` types) is available from the package root: `import { ... } from '@cookiemunch/react'`, in Client and Server Components alike.
246
+ - Types for `window.CookieMunch` are declared locally in this package (not imported from `@cookiemunch/core`), so installing `@cookiemunch/react` alone is enough to get full typing in a project that never installs the core engine directly.
@@ -0,0 +1,70 @@
1
+ import * as react from 'react';
2
+ import { ReactNode } from 'react';
3
+ import { PublicConsent, Category, 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: string): 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: string, value: string | (() => string), opts?: ConsentCookieOptions): void;
69
+
70
+ export { type ConsentContextValue, ConsentGate, type ConsentGateProps, ConsentProvider, type ConsentProviderProps, useConsent, useConsentCookie, useConsentValue };
package/dist/client.js ADDED
@@ -0,0 +1,153 @@
1
+ "use client";
2
+
3
+ // src/ConsentProvider.tsx
4
+ import { useEffect, useRef, useState } from "react";
5
+
6
+ // src/context.ts
7
+ import { createContext } from "react";
8
+ var EMPTY_CONSENT = {
9
+ necessary: true,
10
+ preferences: false,
11
+ statistics: false,
12
+ marketing: false,
13
+ personalizedAds: false,
14
+ basicAds: false,
15
+ adProfiling: false,
16
+ adMeasurement: false,
17
+ stamp: ""
18
+ };
19
+ var ConsentContext = createContext(null);
20
+
21
+ // src/ConsentProvider.tsx
22
+ import { jsx } from "react/jsx-runtime";
23
+ var DEFAULT_SRC = "https://cdn.cookiemunch.net/consent.js";
24
+ var SCRIPT_ID = "CookieMunch";
25
+ var INITIAL_SNAPSHOT = {
26
+ ready: false,
27
+ consent: EMPTY_CONSENT,
28
+ hasResponse: false,
29
+ consented: false
30
+ };
31
+ function ensureEmbedScript(cbid, src, apiBase) {
32
+ const existing = document.getElementById(SCRIPT_ID);
33
+ if (existing) return;
34
+ const script = document.createElement("script");
35
+ script.id = SCRIPT_ID;
36
+ script.async = true;
37
+ script.src = src;
38
+ script.setAttribute("data-cbid", cbid);
39
+ if (apiBase) script.setAttribute("data-api", apiBase);
40
+ (document.head || document.documentElement).appendChild(script);
41
+ }
42
+ function ConsentProvider({ cbid, src = DEFAULT_SRC, apiBase, children }) {
43
+ const apiRef = useRef(null);
44
+ const [snap, setSnap] = useState(INITIAL_SNAPSHOT);
45
+ useEffect(() => {
46
+ if (typeof window === "undefined" || typeof document === "undefined") return;
47
+ let disposed = false;
48
+ let offConsentChange = null;
49
+ let pollTimer = null;
50
+ const sync = (api2) => {
51
+ if (disposed) return;
52
+ setSnap({
53
+ ready: true,
54
+ consent: api2.consent,
55
+ hasResponse: api2.hasResponse,
56
+ consented: api2.consented
57
+ });
58
+ };
59
+ const bind = (api2) => {
60
+ if (disposed) return;
61
+ apiRef.current = api2;
62
+ sync(api2);
63
+ offConsentChange = api2.onConsentChange(() => sync(api2));
64
+ };
65
+ if (window.CookieMunch) {
66
+ bind(window.CookieMunch);
67
+ } else {
68
+ ensureEmbedScript(cbid, src, apiBase);
69
+ pollTimer = setInterval(() => {
70
+ if (window.CookieMunch) {
71
+ if (pollTimer) clearInterval(pollTimer);
72
+ pollTimer = null;
73
+ bind(window.CookieMunch);
74
+ }
75
+ }, 50);
76
+ }
77
+ return () => {
78
+ disposed = true;
79
+ if (pollTimer) clearInterval(pollTimer);
80
+ offConsentChange?.();
81
+ apiRef.current = null;
82
+ };
83
+ }, [cbid, src, apiBase]);
84
+ const api = apiRef.current;
85
+ const value = {
86
+ ready: snap.ready,
87
+ consent: snap.consent,
88
+ hasResponse: snap.hasResponse,
89
+ consented: snap.consented,
90
+ acceptAll: () => api?.submitCustomConsent(true, true, true),
91
+ declineAll: () => api?.submitCustomConsent(false, false, false),
92
+ submitCustomConsent: (p, s, m) => api?.submitCustomConsent(p, s, m),
93
+ withdraw: () => api?.withdraw(),
94
+ show: () => api?.show(),
95
+ renew: () => api?.renew()
96
+ };
97
+ return /* @__PURE__ */ jsx(ConsentContext.Provider, { value, children });
98
+ }
99
+
100
+ // src/useConsent.ts
101
+ import { useContext } from "react";
102
+ function useConsent() {
103
+ const ctx = useContext(ConsentContext);
104
+ if (!ctx) {
105
+ throw new Error("useConsent must be used within a <ConsentProvider>.");
106
+ }
107
+ return ctx;
108
+ }
109
+
110
+ // src/ConsentGate.tsx
111
+ import { Fragment, jsx as jsx2 } from "react/jsx-runtime";
112
+ function ConsentGate({ category, children, fallback = null }) {
113
+ const { consent } = useConsent();
114
+ return /* @__PURE__ */ jsx2(Fragment, { children: consent[category] ? children : fallback });
115
+ }
116
+
117
+ // src/useConsentValue.ts
118
+ import { useContext as useContext2, useEffect as useEffect2, useSyncExternalStore } from "react";
119
+ import { consentCookie, isGranted } from "./helpers.js";
120
+ var CHANGE_EVENTS = ["CookieMunchOnChange", "CookieMunchOnAccept", "CookieMunchOnDecline"];
121
+ function subscribe(onStoreChange) {
122
+ if (typeof window === "undefined") return () => {
123
+ };
124
+ for (const e of CHANGE_EVENTS) window.addEventListener(e, onStoreChange);
125
+ return () => {
126
+ for (const e of CHANGE_EVENTS) window.removeEventListener(e, onStoreChange);
127
+ };
128
+ }
129
+ function useConsentValue(category) {
130
+ const ctx = useContext2(ConsentContext);
131
+ const standalone = useSyncExternalStore(
132
+ subscribe,
133
+ () => typeof window === "undefined" ? false : isGranted(window.CookieMunch?.consent, category),
134
+ () => false
135
+ );
136
+ if (ctx) return ctx.ready ? isGranted(ctx.consent, category) : category === "necessary";
137
+ return standalone;
138
+ }
139
+ function useConsentCookie(name, category, value, opts = {}) {
140
+ const { maxAgeDays, path, domain, sameSite, secure } = opts;
141
+ useEffect2(
142
+ () => consentCookie(name, category, value, { maxAgeDays, path, domain, sameSite, secure }),
143
+ [name, category, value, maxAgeDays, path, domain, sameSite, secure]
144
+ );
145
+ }
146
+ export {
147
+ ConsentGate,
148
+ ConsentProvider,
149
+ useConsent,
150
+ useConsentCookie,
151
+ useConsentValue
152
+ };
153
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ConsentProvider.tsx","../src/context.ts","../src/useConsent.ts","../src/ConsentGate.tsx","../src/useConsentValue.ts"],"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"],"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;AAA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ACdA,SAAS,cAAAC,aAAY,aAAAC,YAAW,4BAA4B;AAE5D,SAAS,eAAe,iBAA4C;AAGpE,IAAM,gBAAgB,CAAC,uBAAuB,uBAAuB,sBAAsB;AAE3F,SAAS,UAAU,eAAuC;AACxD,MAAI,OAAO,WAAW,YAAa,QAAO,MAAM;AAAA,EAAC;AACjD,aAAW,KAAK,cAAe,QAAO,iBAAiB,GAAG,aAAa;AACvE,SAAO,MAAM;AACX,eAAW,KAAK,cAAe,QAAO,oBAAoB,GAAG,aAAa;AAAA,EAC5E;AACF;AAaO,SAAS,gBAAgB,UAA2B;AACzD,QAAM,MAAMC,YAAW,cAAc;AACrC,QAAM,aAAa;AAAA,IACjB;AAAA,IACA,MAAO,OAAO,WAAW,cAAc,QAAQ,UAAU,OAAO,aAAa,SAAS,QAAQ;AAAA,IAC9F,MAAM;AAAA,EACR;AACA,MAAI,IAAK,QAAO,IAAI,QAAQ,UAAU,IAAI,SAAS,QAAQ,IAAI,aAAa;AAC5E,SAAO;AACT;AASO,SAAS,iBACd,MACA,UACA,OACA,OAA6B,CAAC,GACxB;AACN,QAAM,EAAE,YAAY,MAAM,QAAQ,UAAU,OAAO,IAAI;AACvD,EAAAC;AAAA,IACE,MAAM,cAAc,MAAM,UAAU,OAAO,EAAE,YAAY,MAAM,QAAQ,UAAU,OAAO,CAAC;AAAA,IACzF,CAAC,MAAM,UAAU,OAAO,YAAY,MAAM,QAAQ,UAAU,MAAM;AAAA,EACpE;AACF;","names":["api","jsx","useContext","useEffect","useContext","useEffect"]}
@@ -0,0 +1,136 @@
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
+ * The visitor's consent snapshot, mirroring what the embed exposes at
92
+ * `window.CookieMunch.consent`. Includes the four base categories, the granular
93
+ * advertising signals, and a receipt `stamp`. Custom category keys may also be
94
+ * present, hence the index signature.
95
+ */
96
+ interface PublicConsent {
97
+ necessary: boolean;
98
+ preferences: boolean;
99
+ statistics: boolean;
100
+ marketing: boolean;
101
+ /** Granular advertising signals (IAB TCF purposes), else fall back to `marketing`. */
102
+ personalizedAds: boolean;
103
+ basicAds: boolean;
104
+ adProfiling: boolean;
105
+ adMeasurement: boolean;
106
+ /** The current consent-receipt stamp. */
107
+ stamp: string;
108
+ /** Custom category keys are included when the site defines them. */
109
+ [key: string]: boolean | string;
110
+ }
111
+ /**
112
+ * The minimal shape of the global `window.CookieMunch` API this wrapper relies
113
+ * on. The real embed exposes a superset of this (Cookiebot-compatible facade);
114
+ * we only type the members we call.
115
+ */
116
+ interface CookieMunchGlobal {
117
+ readonly consent: PublicConsent;
118
+ readonly consented: boolean;
119
+ readonly hasResponse: boolean;
120
+ show(): void;
121
+ renew(): void;
122
+ /** Open the preference center / second layer. */
123
+ showSettings(): void;
124
+ withdraw(): void;
125
+ submitCustomConsent(preferences: boolean, statistics: boolean, marketing: boolean): void;
126
+ /** Subscribe to consent changes (accept/decline). Returns an unsubscribe fn. */
127
+ onConsentChange(callback: (state: unknown) => void): () => void;
128
+ }
129
+ /** Augment the browser `Window` with the embed's globals. */
130
+ declare global {
131
+ interface Window {
132
+ CookieMunch?: CookieMunchGlobal;
133
+ }
134
+ }
135
+
136
+ export { CONSENT_COOKIE_NAME, type Category, type ConsentCookieOptions, type ConsentCookieState, type CookieMunchGlobal, type PublicConsent, consentCookie, isGranted, parseConsentCookie };
@@ -0,0 +1,103 @@
1
+ // src/consent-cookie.ts
2
+ function isGranted(consent, category) {
3
+ if (category === "necessary") return true;
4
+ if (!consent) return false;
5
+ const top = consent[category];
6
+ if (typeof top === "boolean") return top;
7
+ return consent.custom?.[category] === true;
8
+ }
9
+ function hasDom() {
10
+ return typeof window !== "undefined" && typeof document !== "undefined";
11
+ }
12
+ function attributes(opts) {
13
+ const parts = [`path=${opts.path ?? "/"}`];
14
+ if (opts.domain) parts.push(`domain=${opts.domain}`);
15
+ const sameSite = opts.sameSite ?? "Lax";
16
+ parts.push(`SameSite=${sameSite}`);
17
+ const secure = opts.secure ?? (sameSite === "None" || window.location?.protocol === "https:");
18
+ if (secure || sameSite === "None") parts.push("Secure");
19
+ return parts;
20
+ }
21
+ function setCookie(name, value, opts) {
22
+ const parts = [`${name}=${encodeURIComponent(value)}`, ...attributes(opts)];
23
+ if (typeof opts.maxAgeDays === "number" && opts.maxAgeDays > 0) {
24
+ parts.push(`max-age=${Math.round(opts.maxAgeDays * 86400)}`);
25
+ }
26
+ document.cookie = parts.join("; ");
27
+ }
28
+ function hasCookie(name) {
29
+ return document.cookie.split(";").some((c) => c.trim().startsWith(`${name}=`));
30
+ }
31
+ function removeCookie(name, opts) {
32
+ document.cookie = [`${name}=`, ...attributes(opts), "max-age=0", "expires=Thu, 01 Jan 1970 00:00:00 GMT"].join("; ");
33
+ }
34
+ function consentCookie(name, category, value, opts = {}) {
35
+ if (!hasDom()) return () => {
36
+ };
37
+ let written = null;
38
+ const apply = (consent) => {
39
+ if (!consent) return;
40
+ const granted = isGranted(consent, category);
41
+ if (granted) {
42
+ if (written !== true) {
43
+ if (typeof value !== "function") setCookie(name, value, opts);
44
+ else if (!hasCookie(name)) setCookie(name, value(), opts);
45
+ }
46
+ } else {
47
+ removeCookie(name, opts);
48
+ }
49
+ written = granted;
50
+ };
51
+ const onChange = (e) => apply(e.detail?.consent);
52
+ window.addEventListener("CookieMunchOnChange", onChange);
53
+ const api = window.CookieMunch;
54
+ if (api?.consent) apply(api.consent);
55
+ return () => window.removeEventListener("CookieMunchOnChange", onChange);
56
+ }
57
+
58
+ // src/consent-parse.ts
59
+ var CONSENT_COOKIE_NAME = "CookieMunch";
60
+ function decode(raw) {
61
+ try {
62
+ return decodeURIComponent(raw);
63
+ } catch {
64
+ return raw;
65
+ }
66
+ }
67
+ function json(text) {
68
+ try {
69
+ return JSON.parse(text);
70
+ } catch {
71
+ return void 0;
72
+ }
73
+ }
74
+ function legacy(text) {
75
+ if (!text.includes("necessary")) return void 0;
76
+ return json(text.replace(/'/g, '"').replace(/([{,]\s*)([A-Za-z_]\w*)\s*:/g, '$1"$2":'));
77
+ }
78
+ function parseConsentCookie(raw) {
79
+ if (!raw) return null;
80
+ const text = decode(raw);
81
+ const o = json(text) ?? legacy(text);
82
+ if (o === null || typeof o !== "object" || Array.isArray(o)) return null;
83
+ const r = o;
84
+ const { preferences, statistics, marketing } = r;
85
+ if (typeof preferences !== "boolean" || typeof statistics !== "boolean" || typeof marketing !== "boolean") return null;
86
+ if (r.method !== "explicit" && r.method !== "implied") return null;
87
+ if (typeof r.ver !== "number" || typeof r.utc !== "number" || typeof r.region !== "string") return null;
88
+ if (typeof r.stamp !== "string" && typeof r.stamp !== "number") return null;
89
+ const state = { necessary: true, preferences, statistics, marketing };
90
+ if (r.custom !== null && typeof r.custom === "object" && !Array.isArray(r.custom)) {
91
+ const custom = {};
92
+ for (const [k, v] of Object.entries(r.custom)) if (typeof v === "boolean") custom[k] = v;
93
+ if (Object.keys(custom).length > 0) state.custom = custom;
94
+ }
95
+ return state;
96
+ }
97
+ export {
98
+ CONSENT_COOKIE_NAME,
99
+ consentCookie,
100
+ isGranted,
101
+ parseConsentCookie
102
+ };
103
+ //# sourceMappingURL=helpers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/consent-cookie.ts","../src/consent-parse.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"],"mappings":";AAqBO,SAAS,UAAU,SAAyC,UAA2B;AAC5F,MAAI,aAAa,YAAa,QAAO;AACrC,MAAI,CAAC,QAAS,QAAO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,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;","names":[]}
@@ -0,0 +1,2 @@
1
+ export { ConsentContextValue, ConsentGate, ConsentGateProps, ConsentProvider, ConsentProviderProps, useConsent, useConsentCookie, useConsentValue } from './client.js';
2
+ export { CONSENT_COOKIE_NAME, Category, ConsentCookieOptions, ConsentCookieState, CookieMunchGlobal, PublicConsent, consentCookie, isGranted, parseConsentCookie } from './helpers.js';
package/dist/index.js ADDED
@@ -0,0 +1,26 @@
1
+ // src/index.ts
2
+ import {
3
+ ConsentProvider,
4
+ useConsent,
5
+ ConsentGate,
6
+ useConsentValue,
7
+ useConsentCookie
8
+ } from "./client.js";
9
+ import {
10
+ consentCookie,
11
+ isGranted,
12
+ CONSENT_COOKIE_NAME,
13
+ parseConsentCookie
14
+ } from "./helpers.js";
15
+ export {
16
+ CONSENT_COOKIE_NAME,
17
+ ConsentGate,
18
+ ConsentProvider,
19
+ consentCookie,
20
+ isGranted,
21
+ parseConsentCookie,
22
+ useConsent,
23
+ useConsentCookie,
24
+ useConsentValue
25
+ };
26
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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} from './client.js';\nexport {\n consentCookie,\n isGranted,\n type ConsentCookieOptions,\n CONSENT_COOKIE_NAME,\n parseConsentCookie,\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,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,OAKK;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@cookiemunch/react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "React/Next wrapper for Cookie Munch",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "peerDependencies": {
20
+ "react": ">=18"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/Cookie-Munch/react.git"
25
+ },
26
+ "homepage": "https://cookiemunch.net/docs",
27
+ "bugs": {
28
+ "url": "https://github.com/Cookie-Munch/react/issues"
29
+ },
30
+ "license": "MIT",
31
+ "scripts": {
32
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup",
33
+ "test": "vitest run"
34
+ }
6
35
  }