@cookiemunch/react 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +208 -2
- package/dist/index.d.ts +174 -0
- package/dist/index.js +211 -0
- package/dist/index.js.map +1 -0
- package/package.json +32 -3
package/README.md
CHANGED
|
@@ -1,3 +1,209 @@
|
|
|
1
|
-
#
|
|
1
|
+
# React SDK
|
|
2
2
|
|
|
3
|
-
|
|
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, 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.
|
|
50
|
+
|
|
51
|
+
If `cbid`, `src`, or `apiBase` change on a re-render, the provider re-binds to the (possibly new) embed instance.
|
|
52
|
+
|
|
53
|
+
## Reading consent with `useConsent()`
|
|
54
|
+
|
|
55
|
+
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.
|
|
56
|
+
|
|
57
|
+
```tsx
|
|
58
|
+
import { useConsent } from '@cookiemunch/react';
|
|
59
|
+
|
|
60
|
+
function CookieSettingsLink() {
|
|
61
|
+
const { show, ready } = useConsent();
|
|
62
|
+
if (!ready) return null;
|
|
63
|
+
return <button onClick={show}>Cookie settings</button>;
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`useConsent()` returns a `ConsentContextValue`:
|
|
68
|
+
|
|
69
|
+
| Field | Type | Description |
|
|
70
|
+
| --- | --- | --- |
|
|
71
|
+
| `ready` | `boolean` | `true` once the embed has loaded and reported its first state. |
|
|
72
|
+
| `consent` | `PublicConsent` | The current per-category snapshot (see below). |
|
|
73
|
+
| `hasResponse` | `boolean` | `true` once the visitor has any recorded decision, explicit or implied. |
|
|
74
|
+
| `consented` | `boolean` | `true` once the visitor has an active, valid consent decision. |
|
|
75
|
+
| `acceptAll()` | `() => void` | Grants every category. |
|
|
76
|
+
| `declineAll()` | `() => void` | Denies every non-necessary category. |
|
|
77
|
+
| `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. |
|
|
78
|
+
| `withdraw()` | `() => void` | Revokes all non-necessary consent and re-blocks previously activated scripts. |
|
|
79
|
+
| `show()` | `() => void` | Opens the phase-1 banner. |
|
|
80
|
+
| `renew()` | `() => void` | Re-prompts on the site's configured surface (banner, or straight to preferences if configured that way). |
|
|
81
|
+
|
|
82
|
+
`consent` is a `PublicConsent` object:
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
interface PublicConsent {
|
|
86
|
+
necessary: boolean;
|
|
87
|
+
preferences: boolean;
|
|
88
|
+
statistics: boolean;
|
|
89
|
+
marketing: boolean;
|
|
90
|
+
personalizedAds: boolean; // granular IAB TCF signal, falls back to `marketing`
|
|
91
|
+
basicAds: boolean;
|
|
92
|
+
adProfiling: boolean;
|
|
93
|
+
adMeasurement: boolean;
|
|
94
|
+
stamp: string; // the consent-receipt id
|
|
95
|
+
[key: string]: boolean | string; // custom categories, if your config defines any
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
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.
|
|
100
|
+
|
|
101
|
+
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.
|
|
102
|
+
|
|
103
|
+
## Gating components with `<ConsentGate>`
|
|
104
|
+
|
|
105
|
+
`<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:
|
|
106
|
+
|
|
107
|
+
```tsx
|
|
108
|
+
import { ConsentGate } from '@cookiemunch/react';
|
|
109
|
+
|
|
110
|
+
function Page() {
|
|
111
|
+
return (
|
|
112
|
+
<ConsentGate category="marketing" fallback={<p>Enable marketing cookies to see this widget.</p>}>
|
|
113
|
+
<RetargetingPixel />
|
|
114
|
+
</ConsentGate>
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### `ConsentGateProps`
|
|
120
|
+
|
|
121
|
+
| Prop | Type | Required | Description |
|
|
122
|
+
| --- | --- | --- | --- |
|
|
123
|
+
| `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. |
|
|
124
|
+
| `children` | `ReactNode` | yes | Rendered when `category` is granted. |
|
|
125
|
+
| `fallback` | `ReactNode` | no | Rendered when it isn't. Defaults to `null`. |
|
|
126
|
+
|
|
127
|
+
`ConsentGate` re-renders automatically whenever consent changes, because it reads from the same context `ConsentProvider` updates. There's no polling or manual refresh needed.
|
|
128
|
+
|
|
129
|
+
## Reacting to consent changes
|
|
130
|
+
|
|
131
|
+
`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`:
|
|
132
|
+
|
|
133
|
+
```tsx
|
|
134
|
+
import { useConsent } from '@cookiemunch/react';
|
|
135
|
+
import { useEffect } from 'react';
|
|
136
|
+
|
|
137
|
+
function AnalyticsBootstrap() {
|
|
138
|
+
const { consent, ready } = useConsent();
|
|
139
|
+
|
|
140
|
+
useEffect(() => {
|
|
141
|
+
if (ready && consent.statistics) {
|
|
142
|
+
initAnalytics();
|
|
143
|
+
}
|
|
144
|
+
}, [ready, consent.statistics]);
|
|
145
|
+
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
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.
|
|
151
|
+
|
|
152
|
+
## One category: `useConsentValue(category)`
|
|
153
|
+
|
|
154
|
+
When a component cares about one category, read just that:
|
|
155
|
+
|
|
156
|
+
```tsx
|
|
157
|
+
import { useConsentValue } from '@cookiemunch/react';
|
|
158
|
+
|
|
159
|
+
function ChatWidget() {
|
|
160
|
+
const allowed = useConsentValue('chat'); // a custom category id works the same way
|
|
161
|
+
return allowed ? <LiveChat /> : <ChatPlaceholder />;
|
|
162
|
+
}
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
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.
|
|
166
|
+
|
|
167
|
+
## Store this only with consent: `consentCookie` and `useConsentCookie`
|
|
168
|
+
|
|
169
|
+
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.
|
|
170
|
+
|
|
171
|
+
```tsx
|
|
172
|
+
import { useConsentCookie, consentCookie } from '@cookiemunch/react';
|
|
173
|
+
|
|
174
|
+
// In a component: follows consent for as long as the component is mounted.
|
|
175
|
+
function Affiliate({ ref }: { ref: string }) {
|
|
176
|
+
useConsentCookie('aff_ref', 'marketing', ref, { maxAgeDays: 30 });
|
|
177
|
+
return null;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Anywhere else (no React needed): returns a function that stops following.
|
|
181
|
+
const stop = consentCookie('ab_bucket', 'statistics', () => pickBucket(), { maxAgeDays: 90 });
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
`consentCookie(name, category, value, options?)`:
|
|
185
|
+
|
|
186
|
+
- 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()`
|
|
187
|
+
- 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
|
|
188
|
+
- 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
|
|
189
|
+
- works with custom categories
|
|
190
|
+
|
|
191
|
+
| Option | Meaning |
|
|
192
|
+
| --- | --- |
|
|
193
|
+
| `maxAgeDays` | Lifetime in days. Default: a session cookie. |
|
|
194
|
+
| `path` | Default `/`. |
|
|
195
|
+
| `domain` | Share across subdomains, e.g. `example.com`. Default: host-only. |
|
|
196
|
+
| `sameSite` | `Lax` (default), `Strict` or `None`. |
|
|
197
|
+
| `secure` | Default: on for an HTTPS page; always on with `sameSite: 'None'`. |
|
|
198
|
+
|
|
199
|
+
`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.
|
|
200
|
+
|
|
201
|
+
`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.
|
|
202
|
+
|
|
203
|
+
To read the same decision on your server, see [the consent cookie](https://cookiemunch.net/docs/consent-cookie).
|
|
204
|
+
|
|
205
|
+
## Notes
|
|
206
|
+
|
|
207
|
+
- 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'`.
|
|
209
|
+
- 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.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
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 };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
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
|
+
}
|
|
202
|
+
export {
|
|
203
|
+
ConsentGate,
|
|
204
|
+
ConsentProvider,
|
|
205
|
+
consentCookie,
|
|
206
|
+
isGranted,
|
|
207
|
+
useConsent,
|
|
208
|
+
useConsentCookie,
|
|
209
|
+
useConsentValue
|
|
210
|
+
};
|
|
211
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +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;AAO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,YAAY,MAAM,QAAQ,UAAU,MAAM;AAAA,EACpE;AACF;","names":["api","jsx","useContext","useEffect","useContext","useEffect"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cookiemunch/react",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
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": "tsup",
|
|
33
|
+
"test": "vitest run"
|
|
34
|
+
}
|
|
6
35
|
}
|