@cookiemunch/react 0.1.0 → 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
@@ -46,7 +46,44 @@ That's it — the banner itself is rendered by the embed script, not by React. T
46
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
47
  | `children` | `ReactNode` | yes | Your app tree. |
48
48
 
49
- `ConsentProvider` is SSR-safe: it never touches `window` or `document` during render, only inside an effect, so it's safe to mount in a Next.js Server Component boundary (the provider itself must be a Client Component, but its children don't have to be). Until the embed reports in, descendants see a not-ready, all-denied snapshot (`necessary: true`, everything else `false`) rather than throwing or blocking render.
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.
50
87
 
51
88
  If `cbid`, `src`, or `apiBase` change on a re-render, the provider re-binds to the (possibly new) embed instance.
52
89
 
@@ -205,5 +242,5 @@ To read the same decision on your server, see [the consent cookie](https://cooki
205
242
  ## Notes
206
243
 
207
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.
208
- - Everything exported (`ConsentProvider`, `useConsent`, `ConsentGate`, `useConsentValue`, `useConsentCookie`, `consentCookie`, `isGranted`, and the `Category` / `PublicConsent` / `CookieMunchGlobal` types) is available from the package root: `import { ... } from '@cookiemunch/react'`.
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.
209
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;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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O,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;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,CAA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G,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":[]}
package/dist/index.d.ts CHANGED
@@ -1,174 +1,2 @@
1
- import * as react from 'react';
2
- import { ReactNode } from 'react';
3
-
4
- interface ConsentProviderProps {
5
- /** The Cookie Munch site id (required). Injected as `data-cbid` on the embed. */
6
- cbid: string;
7
- /** Embed URL. Defaults to the public CDN. */
8
- src?: string;
9
- /** Override the API base the embed beacons to (injected as `data-api`). */
10
- apiBase?: string;
11
- children: ReactNode;
12
- }
13
- /**
14
- * Loads the Cookie Munch browser embed from the CDN at runtime and exposes
15
- * reactive consent state to descendants — a standalone script-tag SDK wrapper
16
- * that does NOT bundle the proprietary engine.
17
- *
18
- * SSR-safe: no `window`/`document` access during render; the script is injected
19
- * and the global API resolved only inside an effect. Descendants see an
20
- * all-denied, not-ready snapshot until the embed reports in.
21
- */
22
- declare function ConsentProvider({ cbid, src, apiBase, children }: ConsentProviderProps): react.JSX.Element;
23
-
24
- /**
25
- * Local, standalone type definitions for the Cookie Munch browser embed's public
26
- * surface. These are copied from the public shapes exposed on the global
27
- * `window.CookieMunch` object so this package can be published WITHOUT depending
28
- * on (or bundling) the proprietary `@cookiemunch/core` engine.
29
- *
30
- * Keep these in sync with the embed's public API by shape only — never import
31
- * from `@cookiemunch/core`.
32
- */
33
- /** The four base consent categories. */
34
- type Category = 'necessary' | 'preferences' | 'statistics' | 'marketing';
35
- /**
36
- * The visitor's consent snapshot, mirroring what the embed exposes at
37
- * `window.CookieMunch.consent`. Includes the four base categories, the granular
38
- * advertising signals, and a receipt `stamp`. Custom category keys may also be
39
- * present, hence the index signature.
40
- */
41
- interface PublicConsent {
42
- necessary: boolean;
43
- preferences: boolean;
44
- statistics: boolean;
45
- marketing: boolean;
46
- /** Granular advertising signals (IAB TCF purposes), else fall back to `marketing`. */
47
- personalizedAds: boolean;
48
- basicAds: boolean;
49
- adProfiling: boolean;
50
- adMeasurement: boolean;
51
- /** The current consent-receipt stamp. */
52
- stamp: string;
53
- /** Custom category keys are included when the site defines them. */
54
- [key: string]: boolean | string;
55
- }
56
- /**
57
- * The minimal shape of the global `window.CookieMunch` API this wrapper relies
58
- * on. The real embed exposes a superset of this (Cookiebot-compatible facade);
59
- * we only type the members we call.
60
- */
61
- interface CookieMunchGlobal {
62
- readonly consent: PublicConsent;
63
- readonly consented: boolean;
64
- readonly hasResponse: boolean;
65
- show(): void;
66
- renew(): void;
67
- /** Open the preference center / second layer. */
68
- showSettings(): void;
69
- withdraw(): void;
70
- submitCustomConsent(preferences: boolean, statistics: boolean, marketing: boolean): void;
71
- /** Subscribe to consent changes (accept/decline). Returns an unsubscribe fn. */
72
- onConsentChange(callback: (state: unknown) => void): () => void;
73
- }
74
- /** Augment the browser `Window` with the embed's globals. */
75
- declare global {
76
- interface Window {
77
- CookieMunch?: CookieMunchGlobal;
78
- }
79
- }
80
-
81
- interface ConsentContextValue {
82
- ready: boolean;
83
- consent: PublicConsent;
84
- hasResponse: boolean;
85
- consented: boolean;
86
- acceptAll(): void;
87
- declineAll(): void;
88
- submitCustomConsent(preferences: boolean, statistics: boolean, marketing: boolean): void;
89
- withdraw(): void;
90
- show(): void;
91
- renew(): void;
92
- }
93
-
94
- /** Access reactive consent state + actions. Must be used within a ConsentProvider. */
95
- declare function useConsent(): ConsentContextValue;
96
-
97
- interface ConsentGateProps {
98
- category: Exclude<Category, 'necessary'>;
99
- children: ReactNode;
100
- fallback?: ReactNode;
101
- }
102
- /** Renders children only when the given category is granted (else `fallback`). */
103
- declare function ConsentGate({ category, children, fallback }: ConsentGateProps): react.JSX.Element;
104
-
105
- /**
106
- * "Store this only with consent" — the helper every integrator ends up writing.
107
- *
108
- * A first-party cookie of your own (an A/B bucket, an affiliate id, a chat session) is
109
- * only lawful while the visitor consents to the category it belongs to. `consentCookie`
110
- * writes it the moment that consent holds and removes it the moment it stops — a
111
- * withdrawal from a footer link, a "Deny all", a selection that unticks the category —
112
- * and does nothing at all until the embed has said what the visitor decided.
113
- *
114
- * Framework-free: it listens to the embed's `CookieMunchOnChange` window event, so it
115
- * works with or without `<ConsentProvider>`, and with custom categories.
116
- */
117
- /** Anything carrying a category decision: the public `consent` snapshot or a `ConsentState`. */
118
- type ConsentLike = Record<string, unknown> & {
119
- custom?: Record<string, unknown>;
120
- };
121
- /**
122
- * Whether `category` is granted in a consent snapshot. `necessary` is always granted. A
123
- * custom category is read from the top level (the public `CookieMunch.consent` snapshot)
124
- * or from `custom` (the `ConsentState` that events carry). Anything else: not granted.
125
- */
126
- declare function isGranted(consent: ConsentLike | null | undefined, category: string): boolean;
127
- interface ConsentCookieOptions {
128
- /** Lifetime in days. Default: a session cookie (no max-age). */
129
- maxAgeDays?: number;
130
- /** Default `/`. */
131
- path?: string;
132
- /** Domain attribute, e.g. `example.com` to share across subdomains. Default: host-only. */
133
- domain?: string;
134
- /** Default `Lax`. */
135
- sameSite?: 'Lax' | 'Strict' | 'None';
136
- /** Default: true on an https page. Forced on with `sameSite: 'None'`, as browsers require. */
137
- secure?: boolean;
138
- }
139
- /**
140
- * Keep the cookie `name` in step with consent for `category`: written (with `value`) while
141
- * it is granted, removed when it is not. `value` may be a function, called only when the
142
- * cookie is about to be written and is not already there — so an id is never even
143
- * generated without consent, and a stored one survives page loads.
144
- *
145
- * Applies the current decision immediately when the embed has already loaded, then follows
146
- * every change. Until the embed reports a decision, nothing is written or removed. Returns
147
- * a function that stops following (the cookie is left as it is).
148
- *
149
- * const stop = consentCookie('ab_bucket', 'statistics', () => pickBucket(), { maxAgeDays: 30 });
150
- */
151
- declare function consentCookie(name: string, category: string, value: string | (() => string), opts?: ConsentCookieOptions): () => void;
152
-
153
- /**
154
- * Whether `category` is granted right now — `'preferences'`, `'statistics'`,
155
- * `'marketing'`, `'necessary'` (always true) or one of your custom category ids — and
156
- * re-renders when that changes, whatever changed it.
157
- *
158
- * `false` until the embed has reported (and during SSR), so gated content never renders
159
- * ahead of consent. Works inside `<ConsentProvider>` and, when the embed is on the page
160
- * some other way, without one.
161
- *
162
- * const analytics = useConsentValue('statistics');
163
- */
164
- declare function useConsentValue(category: string): boolean;
165
- /**
166
- * {@link consentCookie} for a component's lifetime: the cookie is written while `category`
167
- * is granted and removed when it is not. Pass a stable `value` (or a lazy function); the
168
- * subscription is re-created when `name`, `category`, `value` or an option changes.
169
- *
170
- * useConsentCookie('affiliate_id', 'marketing', ref, { maxAgeDays: 30 });
171
- */
172
- declare function useConsentCookie(name: string, category: string, value: string | (() => string), opts?: ConsentCookieOptions): void;
173
-
174
- export { type Category, type ConsentContextValue, type ConsentCookieOptions, ConsentGate, type ConsentGateProps, ConsentProvider, type ConsentProviderProps, type CookieMunchGlobal, type PublicConsent, consentCookie, isGranted, useConsent, useConsentCookie, useConsentValue };
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 CHANGED
@@ -1,209 +1,24 @@
1
- // src/ConsentProvider.tsx
2
- import { useEffect, useRef, useState } from "react";
3
-
4
- // src/context.ts
5
- import { createContext } from "react";
6
- var EMPTY_CONSENT = {
7
- necessary: true,
8
- preferences: false,
9
- statistics: false,
10
- marketing: false,
11
- personalizedAds: false,
12
- basicAds: false,
13
- adProfiling: false,
14
- adMeasurement: false,
15
- stamp: ""
16
- };
17
- var ConsentContext = createContext(null);
18
-
19
- // src/ConsentProvider.tsx
20
- import { jsx } from "react/jsx-runtime";
21
- var DEFAULT_SRC = "https://cdn.cookiemunch.net/consent.js";
22
- var SCRIPT_ID = "CookieMunch";
23
- var INITIAL_SNAPSHOT = {
24
- ready: false,
25
- consent: EMPTY_CONSENT,
26
- hasResponse: false,
27
- consented: false
28
- };
29
- function ensureEmbedScript(cbid, src, apiBase) {
30
- const existing = document.getElementById(SCRIPT_ID);
31
- if (existing) return;
32
- const script = document.createElement("script");
33
- script.id = SCRIPT_ID;
34
- script.async = true;
35
- script.src = src;
36
- script.setAttribute("data-cbid", cbid);
37
- if (apiBase) script.setAttribute("data-api", apiBase);
38
- (document.head || document.documentElement).appendChild(script);
39
- }
40
- function ConsentProvider({ cbid, src = DEFAULT_SRC, apiBase, children }) {
41
- const apiRef = useRef(null);
42
- const [snap, setSnap] = useState(INITIAL_SNAPSHOT);
43
- useEffect(() => {
44
- if (typeof window === "undefined" || typeof document === "undefined") return;
45
- let disposed = false;
46
- let offConsentChange = null;
47
- let pollTimer = null;
48
- const sync = (api2) => {
49
- if (disposed) return;
50
- setSnap({
51
- ready: true,
52
- consent: api2.consent,
53
- hasResponse: api2.hasResponse,
54
- consented: api2.consented
55
- });
56
- };
57
- const bind = (api2) => {
58
- if (disposed) return;
59
- apiRef.current = api2;
60
- sync(api2);
61
- offConsentChange = api2.onConsentChange(() => sync(api2));
62
- };
63
- if (window.CookieMunch) {
64
- bind(window.CookieMunch);
65
- } else {
66
- ensureEmbedScript(cbid, src, apiBase);
67
- pollTimer = setInterval(() => {
68
- if (window.CookieMunch) {
69
- if (pollTimer) clearInterval(pollTimer);
70
- pollTimer = null;
71
- bind(window.CookieMunch);
72
- }
73
- }, 50);
74
- }
75
- return () => {
76
- disposed = true;
77
- if (pollTimer) clearInterval(pollTimer);
78
- offConsentChange?.();
79
- apiRef.current = null;
80
- };
81
- }, [cbid, src, apiBase]);
82
- const api = apiRef.current;
83
- const value = {
84
- ready: snap.ready,
85
- consent: snap.consent,
86
- hasResponse: snap.hasResponse,
87
- consented: snap.consented,
88
- acceptAll: () => api?.submitCustomConsent(true, true, true),
89
- declineAll: () => api?.submitCustomConsent(false, false, false),
90
- submitCustomConsent: (p, s, m) => api?.submitCustomConsent(p, s, m),
91
- withdraw: () => api?.withdraw(),
92
- show: () => api?.show(),
93
- renew: () => api?.renew()
94
- };
95
- return /* @__PURE__ */ jsx(ConsentContext.Provider, { value, children });
96
- }
97
-
98
- // src/useConsent.ts
99
- import { useContext } from "react";
100
- function useConsent() {
101
- const ctx = useContext(ConsentContext);
102
- if (!ctx) {
103
- throw new Error("useConsent must be used within a <ConsentProvider>.");
104
- }
105
- return ctx;
106
- }
107
-
108
- // src/ConsentGate.tsx
109
- import { Fragment, jsx as jsx2 } from "react/jsx-runtime";
110
- function ConsentGate({ category, children, fallback = null }) {
111
- const { consent } = useConsent();
112
- return /* @__PURE__ */ jsx2(Fragment, { children: consent[category] ? children : fallback });
113
- }
114
-
115
- // src/useConsentValue.ts
116
- import { useContext as useContext2, useEffect as useEffect2, useSyncExternalStore } from "react";
117
-
118
- // src/consent-cookie.ts
119
- function isGranted(consent, category) {
120
- if (category === "necessary") return true;
121
- if (!consent) return false;
122
- const top = consent[category];
123
- if (typeof top === "boolean") return top;
124
- return consent.custom?.[category] === true;
125
- }
126
- function hasDom() {
127
- return typeof window !== "undefined" && typeof document !== "undefined";
128
- }
129
- function attributes(opts) {
130
- const parts = [`path=${opts.path ?? "/"}`];
131
- if (opts.domain) parts.push(`domain=${opts.domain}`);
132
- const sameSite = opts.sameSite ?? "Lax";
133
- parts.push(`SameSite=${sameSite}`);
134
- const secure = opts.secure ?? (sameSite === "None" || window.location?.protocol === "https:");
135
- if (secure || sameSite === "None") parts.push("Secure");
136
- return parts;
137
- }
138
- function setCookie(name, value, opts) {
139
- const parts = [`${name}=${encodeURIComponent(value)}`, ...attributes(opts)];
140
- if (typeof opts.maxAgeDays === "number" && opts.maxAgeDays > 0) {
141
- parts.push(`max-age=${Math.round(opts.maxAgeDays * 86400)}`);
142
- }
143
- document.cookie = parts.join("; ");
144
- }
145
- function hasCookie(name) {
146
- return document.cookie.split(";").some((c) => c.trim().startsWith(`${name}=`));
147
- }
148
- function removeCookie(name, opts) {
149
- document.cookie = [`${name}=`, ...attributes(opts), "max-age=0", "expires=Thu, 01 Jan 1970 00:00:00 GMT"].join("; ");
150
- }
151
- function consentCookie(name, category, value, opts = {}) {
152
- if (!hasDom()) return () => {
153
- };
154
- let written = null;
155
- const apply = (consent) => {
156
- if (!consent) return;
157
- const granted = isGranted(consent, category);
158
- if (granted) {
159
- if (written !== true) {
160
- if (typeof value !== "function") setCookie(name, value, opts);
161
- else if (!hasCookie(name)) setCookie(name, value(), opts);
162
- }
163
- } else {
164
- removeCookie(name, opts);
165
- }
166
- written = granted;
167
- };
168
- const onChange = (e) => apply(e.detail?.consent);
169
- window.addEventListener("CookieMunchOnChange", onChange);
170
- const api = window.CookieMunch;
171
- if (api?.consent) apply(api.consent);
172
- return () => window.removeEventListener("CookieMunchOnChange", onChange);
173
- }
174
-
175
- // src/useConsentValue.ts
176
- var CHANGE_EVENTS = ["CookieMunchOnChange", "CookieMunchOnAccept", "CookieMunchOnDecline"];
177
- function subscribe(onStoreChange) {
178
- if (typeof window === "undefined") return () => {
179
- };
180
- for (const e of CHANGE_EVENTS) window.addEventListener(e, onStoreChange);
181
- return () => {
182
- for (const e of CHANGE_EVENTS) window.removeEventListener(e, onStoreChange);
183
- };
184
- }
185
- function useConsentValue(category) {
186
- const ctx = useContext2(ConsentContext);
187
- const standalone = useSyncExternalStore(
188
- subscribe,
189
- () => typeof window === "undefined" ? false : isGranted(window.CookieMunch?.consent, category),
190
- () => false
191
- );
192
- if (ctx) return ctx.ready ? isGranted(ctx.consent, category) : category === "necessary";
193
- return standalone;
194
- }
195
- function useConsentCookie(name, category, value, opts = {}) {
196
- const { maxAgeDays, path, domain, sameSite, secure } = opts;
197
- useEffect2(
198
- () => consentCookie(name, category, value, { maxAgeDays, path, domain, sameSite, secure }),
199
- [name, category, value, maxAgeDays, path, domain, sameSite, secure]
200
- );
201
- }
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";
202
15
  export {
16
+ CONSENT_COOKIE_NAME,
203
17
  ConsentGate,
204
18
  ConsentProvider,
205
19
  consentCookie,
206
20
  isGranted,
21
+ parseConsentCookie,
207
22
  useConsent,
208
23
  useConsentCookie,
209
24
  useConsentValue
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ConsentProvider.tsx","../src/context.ts","../src/useConsent.ts","../src/ConsentGate.tsx","../src/useConsentValue.ts","../src/consent-cookie.ts"],"sourcesContent":["import { useEffect, useRef, useState, type ReactNode } from 'react';\nimport { ConsentContext, EMPTY_CONSENT, type ConsentContextValue } from './context.js';\nimport type { CookieMunchGlobal, PublicConsent } from './types.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 './types.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 './types.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 './consent-cookie.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","/**\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"],"mappings":";AAAA,SAAS,WAAW,QAAQ,gBAAgC;;;ACA5D,SAAS,qBAAqB;AAgBvB,IAAM,gBAA+B;AAAA,EAC1C,WAAW;AAAA,EACX,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB,UAAU;AAAA,EACV,aAAa;AAAA,EACb,eAAe;AAAA,EACf,OAAO;AACT;AAGO,IAAM,iBAAiB,cAA0C,IAAI;;;ADiGnE;AAzHT,IAAM,cAAc;AAEpB,IAAM,YAAY;AAmBlB,IAAM,mBAA6B;AAAA,EACjC,OAAO;AAAA,EACP,SAAS;AAAA,EACT,aAAa;AAAA,EACb,WAAW;AACb;AAOA,SAAS,kBAAkB,MAAc,KAAa,SAAmC;AACvF,QAAM,WAAW,SAAS,eAAe,SAAS;AAClD,MAAI,SAAU;AACd,QAAM,SAAS,SAAS,cAAc,QAAQ;AAC9C,SAAO,KAAK;AACZ,SAAO,QAAQ;AACf,SAAO,MAAM;AACb,SAAO,aAAa,aAAa,IAAI;AACrC,MAAI,QAAS,QAAO,aAAa,YAAY,OAAO;AACpD,GAAC,SAAS,QAAQ,SAAS,iBAAiB,YAAY,MAAM;AAChE;AAWO,SAAS,gBAAgB,EAAE,MAAM,MAAM,aAAa,SAAS,SAAS,GAAyB;AACpG,QAAM,SAAS,OAAiC,IAAI;AACpD,QAAM,CAAC,MAAM,OAAO,IAAI,SAAmB,gBAAgB;AAE3D,YAAU,MAAM;AACd,QAAI,OAAO,WAAW,eAAe,OAAO,aAAa,YAAa;AAEtE,QAAI,WAAW;AACf,QAAI,mBAAwC;AAC5C,QAAI,YAA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D,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"]}
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,6 @@
1
1
  {
2
2
  "name": "@cookiemunch/react",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "React/Next wrapper for Cookie Munch",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -29,7 +29,7 @@
29
29
  },
30
30
  "license": "MIT",
31
31
  "scripts": {
32
- "build": "tsup",
32
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup",
33
33
  "test": "vitest run"
34
34
  }
35
35
  }