@venturetime/consent 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/README.md +75 -4
- package/dist/index.d.ts +135 -21
- package/dist/index.js +158 -44
- package/dist/react.d.ts +34 -3
- package/dist/react.js +8 -12
- package/package.json +6 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
Hardening after an outside review. Sites should call `consent.start(model)`
|
|
6
|
+
at page start (it replaces `ensureDefault()`, which still works) and wire
|
|
7
|
+
`onError`.
|
|
8
|
+
|
|
9
|
+
- **An older answer cannot come back.** A late server response used to be
|
|
10
|
+
able to put an earlier "yes" back over a "no". The latest answer is now
|
|
11
|
+
also kept in `localStorage`, and corrects the cookie as the response lands
|
|
12
|
+
or on the next page load, before any tag runs. `consent.reconcile()` is
|
|
13
|
+
public for sites that record outside the `record` hook.
|
|
14
|
+
- **A failing hook no longer stops a decision.** `onApply`, subscribers and
|
|
15
|
+
`record` are isolated; failures go to the new `onError(error, step)`.
|
|
16
|
+
- **`consent.start(model)`** runs `onApply` with what applies at page start,
|
|
17
|
+
answered or not. `onApply` now gets a second argument: `'answer'`,
|
|
18
|
+
`'start'` or `'other-tab'`.
|
|
19
|
+
- **Answers from other tabs** are applied at once; `useConsentBanner` closes
|
|
20
|
+
the question when an answer is given elsewhere.
|
|
21
|
+
- **Global Privacy Control wins over a stored yes** in an `opt-out` model.
|
|
22
|
+
New config field `globalPrivacyControl: 'signal-wins' | 'answer-wins'`.
|
|
23
|
+
New `effectiveConsent()` and `consent.effective(model)`.
|
|
24
|
+
- **A record that is refused is reported:** a rejected promise, a thrown
|
|
25
|
+
hook or a response with `ok: false`.
|
|
26
|
+
- **Config is validated** at every entry point (`assertConsentConfig`):
|
|
27
|
+
cookie name, version, lifetime, cookie patterns (no `g` or `y` flag),
|
|
28
|
+
paths.
|
|
29
|
+
- **Cookie cleanup takes paths:** `paths` on an optional cookie.
|
|
30
|
+
- `consentDefaultScript` now needs `maxAgeSeconds` in its config (pass the
|
|
31
|
+
whole config).
|
|
32
|
+
- Real-browser tests (Chromium, WebKit) of the built package.
|
|
33
|
+
|
|
34
|
+
## 0.1.0
|
|
35
|
+
|
|
36
|
+
First release.
|
package/README.md
CHANGED
|
@@ -24,9 +24,9 @@ code that reads it.
|
|
|
24
24
|
|
|
25
25
|
| Module | What it does |
|
|
26
26
|
| --- | --- |
|
|
27
|
-
| `state` | The answer `{ analytics, marketing }`, its cookie value (`a1m0v1`), the version rule, Google Consent Mode v2 signals, what applies to a visitor
|
|
27
|
+
| `state` | The answer `{ analytics, marketing }`, its cookie value (`a1m0v1`), the version rule, Google Consent Mode v2 signals, `effectiveConsent` (what applies to a visitor now: the answer, else the model's rule, with Global Privacy Control), the cookie as a server sets it, `assertConsentConfig` |
|
|
28
28
|
| `inline-script` | The `<head>` script: Consent Mode default, then the stored answer, before the tag manager loads |
|
|
29
|
-
| `controller` | `createConsent(config, hooks)`: the one place an answer is applied — Consent Mode update → the site's hooks → cookies of a refused purpose removed → cookie written → subscribers |
|
|
29
|
+
| `controller` | `createConsent(config, hooks)`: the one place an answer is applied — Consent Mode update → the site's hooks → cookies of a refused purpose removed → cookie and memory written → subscribers. `start(model)` at page start; answers from other tabs; a failing hook never stops a decision |
|
|
30
30
|
| `cookies` | Which cookies to expire for a refused purpose, on the host and its parent domains |
|
|
31
31
|
| `react` | `useConsentBanner(consent, model)`: when the banner shows, what the switches start as, focus and Escape. No markup |
|
|
32
32
|
|
|
@@ -47,6 +47,9 @@ export const CONSENT: ConsentConfig = {
|
|
|
47
47
|
};
|
|
48
48
|
|
|
49
49
|
export const consent = createConsent(CONSENT, {
|
|
50
|
+
// Other tools that follow consent. Runs on every decision and at page start.
|
|
51
|
+
onApply: (state) => (state.analytics ? analytics.optIn() : analytics.optOut()),
|
|
52
|
+
// Return the fetch promise: a network failure or a response that is not ok goes to onError.
|
|
50
53
|
record: (state, source) =>
|
|
51
54
|
fetch('/api/consent', {
|
|
52
55
|
method: 'POST',
|
|
@@ -54,6 +57,8 @@ export const consent = createConsent(CONSENT, {
|
|
|
54
57
|
body: JSON.stringify({ ...state, source }),
|
|
55
58
|
keepalive: true,
|
|
56
59
|
}),
|
|
60
|
+
// A hook threw, the record was not taken, storage was refused. The answer was applied all the same.
|
|
61
|
+
onError: (error, step) => reportError(error, { step }),
|
|
57
62
|
});
|
|
58
63
|
```
|
|
59
64
|
|
|
@@ -69,7 +74,10 @@ import { consentDefaultScript } from '@venturetime/consent';
|
|
|
69
74
|
'use client';
|
|
70
75
|
import { useConsentBanner } from '@venturetime/consent/react';
|
|
71
76
|
|
|
72
|
-
|
|
77
|
+
// Once, before optional SDKs initialise: a Consent Mode default exists, a
|
|
78
|
+
// cookie a late server response got wrong is put right, and onApply runs
|
|
79
|
+
// with what applies to this visitor — answered or not.
|
|
80
|
+
consent.start('opt-in');
|
|
73
81
|
|
|
74
82
|
export function Banner() {
|
|
75
83
|
const b = useConsentBanner(consent, 'opt-in');
|
|
@@ -114,7 +122,11 @@ const cookie = consentCookie(state, CONSENT, { secure: true });
|
|
|
114
122
|
refuse a request from another origin — its response sets the cookie that
|
|
115
123
|
says what the visitor agreed to.
|
|
116
124
|
7. **Hooks** for anything else that follows the answer (`onApply`: product
|
|
117
|
-
analytics opt-in and opt-out)
|
|
125
|
+
analytics opt-in and opt-out), and `onError` wired to the site's
|
|
126
|
+
monitoring.
|
|
127
|
+
8. **One call at page start**, `consent.start(model)`, before optional SDKs
|
|
128
|
+
initialise. On the server, read the cookie with
|
|
129
|
+
`effectiveConsent(readConsent(cookie, CONFIG), model, request has Sec-GPC: 1, CONFIG)`.
|
|
118
130
|
|
|
119
131
|
## Moving a site onto it
|
|
120
132
|
|
|
@@ -136,6 +148,65 @@ const cookie = consentCookie(state, CONSENT, { secure: true });
|
|
|
136
148
|
export the vendor's consent log, update the privacy policy so it lists the
|
|
137
149
|
cookies itself, cancel the vendor.
|
|
138
150
|
|
|
151
|
+
## What it guarantees, and what it does not
|
|
152
|
+
|
|
153
|
+
**An older answer cannot come back.** The server sets the cookie when it has
|
|
154
|
+
recorded an answer, and responses can arrive out of order: a slow "yes"
|
|
155
|
+
landing after a quick "no", in this tab or another. Every answer is also kept
|
|
156
|
+
in `localStorage` under the cookie's name, which no response can write. When
|
|
157
|
+
the two disagree, that memory wins: as the late response lands if the page is
|
|
158
|
+
still open, otherwise in the inline script of the next page load, before any
|
|
159
|
+
tag runs, and the cookie is rewritten so the server reads the right answer
|
|
160
|
+
too. The memory only corrects a cookie that exists — when the cookie ends
|
|
161
|
+
(expired, cleared), so does the answer.
|
|
162
|
+
|
|
163
|
+
**A failing hook cannot stop a decision.** If `onApply`, a subscriber or
|
|
164
|
+
`record` throws, the answer is still stored, cleaned up after, announced and
|
|
165
|
+
recorded. The failure goes to `onError`.
|
|
166
|
+
|
|
167
|
+
**Tabs agree.** An answer in one tab reaches the tags, `onApply` and the
|
|
168
|
+
banner in every other tab of the site at once.
|
|
169
|
+
|
|
170
|
+
**Global Privacy Control**, in an `opt-out` model: marketing is off for as
|
|
171
|
+
long as the browser sends the signal, also over a stored yes
|
|
172
|
+
(`globalPrivacyControl: 'answer-wins'` in the config reverses that; decide it
|
|
173
|
+
per market with whoever owns its privacy policy). In an `opt-in` model the
|
|
174
|
+
signal changes nothing: nothing runs without a yes, and a yes was asked for.
|
|
175
|
+
|
|
176
|
+
**What an answer is valid for:** this browser, this host, this cookie name,
|
|
177
|
+
until the cookie's lifetime ends or `version` is raised. It carries no market
|
|
178
|
+
and no model: a site that serves markets with different rules from one host
|
|
179
|
+
should give each its own `cookieName`. An answer to a higher version than the
|
|
180
|
+
site now runs still counts (a rollback), which assumes a version only adds to
|
|
181
|
+
what was asked.
|
|
182
|
+
|
|
183
|
+
What it does **not** guarantee:
|
|
184
|
+
|
|
185
|
+
- **That a tag has stopped by the time the cleanup runs.** The Consent Mode
|
|
186
|
+
update is a command on the data layer; a tag manager normally acts on it at
|
|
187
|
+
once, but a tag in mid-flight can still write a cookie afterwards. The
|
|
188
|
+
stored answer is the durable part: from the next page load every tag starts
|
|
189
|
+
denied. Check what you rely on against your own container, with nothing
|
|
190
|
+
blocked.
|
|
191
|
+
- **That every trace of a refused purpose is gone.** Cleanup removes cookies
|
|
192
|
+
a script can see, on the host and its parent domains, on the paths you list
|
|
193
|
+
(`/` by default). It cannot reach `HttpOnly` or server-set cookies, cookies
|
|
194
|
+
of another site in an iframe, or what a tag keeps in `localStorage` or
|
|
195
|
+
IndexedDB. Those are the site's to clean up where they exist.
|
|
196
|
+
- **That a tag waits for consent at all.** A tag that does not check its
|
|
197
|
+
Consent Mode signal is not stopped by any banner.
|
|
198
|
+
- **That the record was written.** The answer never waits for the server.
|
|
199
|
+
Wire `onError` to your monitoring, or a failing route goes unseen.
|
|
200
|
+
|
|
201
|
+
## Tests
|
|
202
|
+
|
|
203
|
+
`pnpm test` runs the unit tests. `pnpm test:browser` builds the package and
|
|
204
|
+
runs it in Chromium and WebKit against a small test server
|
|
205
|
+
(`test/browser`): real cookies with real paths and lifetimes, a server
|
|
206
|
+
response that really arrives late, leaving the page before it lands, two
|
|
207
|
+
tabs, Global Privacy Control. They do not run a real tag container; that
|
|
208
|
+
check belongs in each site.
|
|
209
|
+
|
|
139
210
|
## Changing this package
|
|
140
211
|
|
|
141
212
|
- Nothing that only one site needs goes in here: no markup, no text, no
|
package/dist/index.d.ts
CHANGED
|
@@ -17,8 +17,12 @@ interface ConsentState {
|
|
|
17
17
|
type ConsentModel = 'opt-in' | 'opt-out';
|
|
18
18
|
/** One optional cookie a tag sets: how to recognise its name, and who sets it. */
|
|
19
19
|
interface OptionalCookie {
|
|
20
|
+
/** Matches the cookie's name. No `g` or `y` flag: those make a pattern remember where it last matched. */
|
|
20
21
|
pattern: RegExp;
|
|
21
22
|
setBy: string;
|
|
23
|
+
/** The paths the cookie may have been set on. A cookie can only be removed
|
|
24
|
+
* by naming its path. Default: `['/']`, where tags set theirs. */
|
|
25
|
+
paths?: readonly string[];
|
|
22
26
|
}
|
|
23
27
|
/** What a site decides about its own consent; everything else here is the same for every site. */
|
|
24
28
|
interface ConsentConfig {
|
|
@@ -40,7 +44,24 @@ interface ConsentConfig {
|
|
|
40
44
|
* withdrawn, and what the site's privacy policy has to name.
|
|
41
45
|
*/
|
|
42
46
|
optionalCookies: Record<Purpose, readonly OptionalCookie[]>;
|
|
47
|
+
/**
|
|
48
|
+
* In an opt-out model, what decides when the browser sends Global Privacy
|
|
49
|
+
* Control and the visitor has also stored a yes to marketing:
|
|
50
|
+
* - 'signal-wins' (default): the signal. Marketing stays off for as long
|
|
51
|
+
* as the browser sends it, whatever was answered before.
|
|
52
|
+
* - 'answer-wins': the stored answer.
|
|
53
|
+
* Has no effect in an opt-in model, where nothing runs without a yes.
|
|
54
|
+
*/
|
|
55
|
+
globalPrivacyControl?: 'signal-wins' | 'answer-wins';
|
|
43
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* Refuses a config that would misbehave somewhere else later: a cookie name
|
|
59
|
+
* that is not a plain name (it is written into cookies, a regular expression
|
|
60
|
+
* and an inline script), a version or lifetime that is not a positive whole
|
|
61
|
+
* number, a cookie pattern that remembers state, a path that is not a path.
|
|
62
|
+
* Checks the fields it is given; every entry point of the package calls it.
|
|
63
|
+
*/
|
|
64
|
+
declare function assertConsentConfig(config: Partial<ConsentConfig>): void;
|
|
44
65
|
type Signal = 'granted' | 'denied';
|
|
45
66
|
interface ConsentModeParams {
|
|
46
67
|
analytics_storage: Signal;
|
|
@@ -54,13 +75,33 @@ interface ConsentModeParams {
|
|
|
54
75
|
* answered under version 1. Short so the inline restore script's parser
|
|
55
76
|
* stays a one-liner. */
|
|
56
77
|
declare function serializeConsent(state: ConsentState, config: Pick<ConsentConfig, 'version'>): string;
|
|
57
|
-
/**
|
|
58
|
-
*
|
|
78
|
+
/**
|
|
79
|
+
* The answer in a cookie value, or null when there is none that still counts
|
|
80
|
+
* (no cookie, junk, or an answer to an older version).
|
|
81
|
+
*
|
|
82
|
+
* What an answer is valid for: this browser, on this host, under this cookie
|
|
83
|
+
* name, for six months or whatever the site set, until the version is
|
|
84
|
+
* raised. It carries no market and no model. Sites that serve markets with
|
|
85
|
+
* different rules from one host should give each its own cookie name, or an
|
|
86
|
+
* answer given under one market's wording counts in the other. An answer to
|
|
87
|
+
* a HIGHER version than the site now runs also counts: that is what a
|
|
88
|
+
* rollback looks like, and it assumes a version only ever adds to what was
|
|
89
|
+
* asked. If a version can also take something away, raise it again instead
|
|
90
|
+
* of rolling back.
|
|
91
|
+
*/
|
|
59
92
|
declare function readConsent(value: string | undefined | null, config: Pick<ConsentConfig, 'version'>): ConsentState | null;
|
|
60
93
|
/** What applies to a visitor who has not answered. `gpc` is the browser's
|
|
61
94
|
* Global Privacy Control signal (navigator.globalPrivacyControl, or the
|
|
62
95
|
* `Sec-GPC: 1` request header). */
|
|
63
96
|
declare function unansweredConsent(model: ConsentModel, gpc: boolean): ConsentState;
|
|
97
|
+
/**
|
|
98
|
+
* What applies to a visitor right now: their stored answer, or the model's
|
|
99
|
+
* rule when there is none — and, in an opt-out model, Global Privacy Control
|
|
100
|
+
* on top of either unless the site chose 'answer-wins'. Use this wherever
|
|
101
|
+
* something has to follow consent: an SDK starting up, a server reading the
|
|
102
|
+
* cookie off a request (`gpc` = the `Sec-GPC: 1` header).
|
|
103
|
+
*/
|
|
104
|
+
declare function effectiveConsent(stored: ConsentState | null, model: ConsentModel, gpc: boolean, config?: Pick<ConsentConfig, 'globalPrivacyControl'>): ConsentState;
|
|
64
105
|
/** The Consent Mode signal every optional storage type starts in. */
|
|
65
106
|
declare function defaultSignal(model: ConsentModel): Signal;
|
|
66
107
|
/** A decision as Consent Mode signals. Functionality is always granted (the
|
|
@@ -69,6 +110,19 @@ declare function defaultSignal(model: ConsentModel): Signal;
|
|
|
69
110
|
declare function consentModeParams(state: ConsentState): ConsentModeParams;
|
|
70
111
|
/** Global Privacy Control as this browser reports it. */
|
|
71
112
|
declare function browserGpc(): boolean;
|
|
113
|
+
/**
|
|
114
|
+
* The stored value in this browser, or undefined: the cookie, corrected by
|
|
115
|
+
* the browser's own memory of the latest answer when the two disagree.
|
|
116
|
+
*
|
|
117
|
+
* Why there is a second memory: the server sets the cookie again when it has
|
|
118
|
+
* recorded an answer, and its responses can arrive out of order — a slow
|
|
119
|
+
* "yes" landing after a quick "no" would put the yes back. Every answer is
|
|
120
|
+
* therefore also kept in localStorage under the cookie's name, which no
|
|
121
|
+
* response can write. It only ever corrects a cookie that exists: with no
|
|
122
|
+
* cookie (expired, cleared) it counts for nothing, so an answer still ends
|
|
123
|
+
* when its cookie does.
|
|
124
|
+
*/
|
|
125
|
+
declare function storedConsentValue(config: Pick<ConsentConfig, 'cookieName' | 'version'>): string | undefined;
|
|
72
126
|
/** The visitor's stored decision in this browser, or null when undecided. */
|
|
73
127
|
declare function getStoredConsent(config: Pick<ConsentConfig, 'cookieName' | 'version'>): ConsentState | null;
|
|
74
128
|
/**
|
|
@@ -95,50 +149,103 @@ declare function consentCookie(state: ConsentState, config: ConsentConfig, opts:
|
|
|
95
149
|
* The `document.cookie` writes that remove every cookie of a refused purpose
|
|
96
150
|
* from this browser. Pure: given the current cookie string and the host. A
|
|
97
151
|
* tag may have set its cookie on the host or on any parent domain, and a
|
|
98
|
-
* cookie can only be removed by naming the domain it was set on, so
|
|
99
|
-
* expired on all of
|
|
152
|
+
* cookie can only be removed by naming the domain and path it was set on, so
|
|
153
|
+
* each is expired on all of the domains, on each of its paths (`/` unless
|
|
154
|
+
* the config lists others).
|
|
155
|
+
*
|
|
156
|
+
* What this cannot reach, and a site must handle itself where it applies:
|
|
157
|
+
* cookies a script cannot see (HttpOnly, set by a server), cookies on a path
|
|
158
|
+
* the config does not list, cookies of another site (a third-party iframe),
|
|
159
|
+
* and anything a tag keeps outside cookies (localStorage, IndexedDB).
|
|
100
160
|
*/
|
|
101
161
|
declare function refusedCookieExpiries(cookieString: string, state: ConsentState, hostname: string, optionalCookies: ConsentConfig['optionalCookies']): string[];
|
|
102
162
|
|
|
103
163
|
/**
|
|
104
164
|
* The Consent Mode DEFAULT plus the visitor's stored decision, as the body
|
|
105
165
|
* of an inline <script> for the page's <head>, BEFORE the tag manager's
|
|
106
|
-
* loader. It cannot import anything, so it re-implements the cookie
|
|
107
|
-
* (the tests assert
|
|
108
|
-
* applied synchronously after the default, so tags never
|
|
109
|
-
* denied→granted flip on a returning visit.
|
|
166
|
+
* loader. It cannot import anything, so it re-implements the cookie reader
|
|
167
|
+
* (the tests assert the two agree, value by value). When a stored decision
|
|
168
|
+
* exists it is applied synchronously after the default, so tags never
|
|
169
|
+
* observe a denied→granted flip on a returning visit.
|
|
170
|
+
*
|
|
171
|
+
* It reads what `getStoredConsent` reads: the cookie, corrected by the
|
|
172
|
+
* browser's own memory of the latest answer when a late server response has
|
|
173
|
+
* put an older one back (state.ts: storedConsentValue). When it corrects, it
|
|
174
|
+
* also rewrites the cookie, so the server reads the right answer on the next
|
|
175
|
+
* request.
|
|
110
176
|
*
|
|
111
|
-
* The default follows the model: denied for opt-in, granted for opt-out.
|
|
112
|
-
*
|
|
113
|
-
*
|
|
177
|
+
* The default follows the model: denied for opt-in, granted for opt-out. In
|
|
178
|
+
* an opt-out model a browser sending Global Privacy Control has refused
|
|
179
|
+
* marketing — also over a stored yes, unless the config says 'answer-wins'.
|
|
180
|
+
* security_storage is always granted.
|
|
114
181
|
*
|
|
115
182
|
* `firstPush` is put on the data layer before anything else — what the
|
|
116
183
|
* site's container needs to know from the first event (a market, a currency).
|
|
117
184
|
*/
|
|
118
|
-
declare function consentDefaultScript(config: Pick<ConsentConfig, 'cookieName' | 'version'>, model: ConsentModel, firstPush?: Record<string, unknown>): string;
|
|
185
|
+
declare function consentDefaultScript(config: Pick<ConsentConfig, 'cookieName' | 'version' | 'maxAgeSeconds' | 'globalPrivacyControl'>, model: ConsentModel, firstPush?: Record<string, unknown>): string;
|
|
119
186
|
|
|
120
187
|
/** Where the visitor gave the answer: the first-visit banner, or "Cookie settings" later. */
|
|
121
188
|
type ConsentSource = 'banner' | 'settings';
|
|
189
|
+
/**
|
|
190
|
+
* Why `onApply` is running:
|
|
191
|
+
* - 'answer': the visitor just answered here.
|
|
192
|
+
* - 'start': the page is starting up (`start(model)`): what applies to this
|
|
193
|
+
* visitor, whether or not they ever answered.
|
|
194
|
+
* - 'other-tab': the visitor answered in another tab of this site.
|
|
195
|
+
*/
|
|
196
|
+
type ConsentCause = 'answer' | 'start' | 'other-tab';
|
|
197
|
+
/** Which step failed, for `onError`. Nothing here ever stops an answer from being applied. */
|
|
198
|
+
type ConsentErrorStep = 'onApply' | 'subscriber' | 'record' | 'storage';
|
|
122
199
|
/** What a site hangs on an answer, beyond what every site does. */
|
|
123
200
|
interface ConsentHooks {
|
|
124
|
-
/**
|
|
125
|
-
*
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
*
|
|
201
|
+
/**
|
|
202
|
+
* Other tools that follow consent (product analytics opt-in and opt-out).
|
|
203
|
+
* Runs right after the Consent Mode update on every decision, and once
|
|
204
|
+
* from `start(model)` with what applies at page start. If it throws, the
|
|
205
|
+
* error goes to `onError` and the rest of the decision still happens.
|
|
206
|
+
*/
|
|
207
|
+
onApply?: (state: ConsentState, cause: ConsentCause) => void;
|
|
208
|
+
/**
|
|
209
|
+
* Tell the server a visitor answered, so it can keep the record and set
|
|
210
|
+
* the cookie from its response. Never awaited. Return the `fetch` promise:
|
|
211
|
+
* a rejection, or a response that is not `ok`, goes to `onError`.
|
|
212
|
+
*/
|
|
129
213
|
record?: (state: ConsentState, source: ConsentSource) => void | Promise<unknown>;
|
|
214
|
+
/**
|
|
215
|
+
* Something around a decision failed: a hook threw, the record was not
|
|
216
|
+
* taken, storage was refused. Report it to your monitoring. The decision
|
|
217
|
+
* itself was applied all the same.
|
|
218
|
+
*/
|
|
219
|
+
onError?: (error: unknown, step: ConsentErrorStep) => void;
|
|
130
220
|
}
|
|
131
221
|
interface ConsentController {
|
|
132
222
|
readonly config: ConsentConfig;
|
|
133
223
|
/** The visitor's stored answer in this browser, or null. */
|
|
134
224
|
stored(): ConsentState | null;
|
|
135
|
-
/**
|
|
225
|
+
/** What applies to this visitor now: the stored answer, else the model's rule, with Global Privacy Control (state.ts: effectiveConsent). */
|
|
226
|
+
effective(model: ConsentModel): ConsentState;
|
|
227
|
+
/** Apply a decision everywhere: Consent Mode update → onApply → refused cookies removed → cookie and memory written → subscribers. */
|
|
136
228
|
apply(state: ConsentState): void;
|
|
137
229
|
/** The visitor answered: apply it now, then tell the server (hooks.record). */
|
|
138
230
|
answer(state: ConsentState, source: ConsentSource): void;
|
|
139
|
-
/**
|
|
231
|
+
/**
|
|
232
|
+
* Call once when the page starts, before optional SDKs initialise (module
|
|
233
|
+
* evaluation of the banner component is the place): makes sure a Consent
|
|
234
|
+
* Mode default exists, puts right a cookie a late server response got
|
|
235
|
+
* wrong, and runs `onApply` with what applies to this visitor, so every
|
|
236
|
+
* tool starts from the same decision the tags did. Returns that decision.
|
|
237
|
+
*/
|
|
238
|
+
start(model: ConsentModel): ConsentState;
|
|
239
|
+
/** Push an all-denied default (and the stored answer) if the data layer holds none yet. `start` does this too. */
|
|
140
240
|
ensureDefault(): void;
|
|
141
|
-
/**
|
|
241
|
+
/**
|
|
242
|
+
* Put the cookie back in line with the latest answer this browser
|
|
243
|
+
* remembers, if a late server response replaced it. True when it had to.
|
|
244
|
+
* Runs by itself at start and after every record; call it yourself after
|
|
245
|
+
* any other request whose response may set the consent cookie.
|
|
246
|
+
*/
|
|
247
|
+
reconcile(): boolean;
|
|
248
|
+
/** Hear every applied decision, from this tab or another. Returns the unsubscribe. */
|
|
142
249
|
subscribe(listener: (state: ConsentState) => void): () => void;
|
|
143
250
|
/** "Cookie settings" was pressed: ask the banner to open its choices. */
|
|
144
251
|
openSettings(): void;
|
|
@@ -151,7 +258,14 @@ declare function pushGtagCommand(...args: unknown[]): void;
|
|
|
151
258
|
* signals have one author: the Consent Mode update, the site's own hooks,
|
|
152
259
|
* removing the cookies of a refused purpose, and the first-party cookie the
|
|
153
260
|
* inline script reads on the next page load — in this order.
|
|
261
|
+
*
|
|
262
|
+
* About that order: the update is a command on the data layer, and a tag
|
|
263
|
+
* manager acts on it when it processes that command — normally at once, but
|
|
264
|
+
* not provably before the next line here runs. A tag that was mid-flight may
|
|
265
|
+
* still write a cookie after the cleanup. The cookie is the durable part:
|
|
266
|
+
* from the next page load every tag starts denied. Check the behaviour you
|
|
267
|
+
* rely on against your own container.
|
|
154
268
|
*/
|
|
155
269
|
declare function createConsent(config: ConsentConfig, hooks?: ConsentHooks): ConsentController;
|
|
156
270
|
|
|
157
|
-
export { type ConsentConfig, type ConsentController, type ConsentHooks, type ConsentModeParams, type ConsentModel, type ConsentSource, type ConsentState, type OptionalCookie, type Purpose, type Signal, browserGpc, consentCookie, consentDefaultScript, consentModeParams, createConsent, defaultSignal, getStoredConsent, pushGtagCommand, readConsent, refusedCookieExpiries, serializeConsent, unansweredConsent };
|
|
271
|
+
export { type ConsentCause, type ConsentConfig, type ConsentController, type ConsentErrorStep, type ConsentHooks, type ConsentModeParams, type ConsentModel, type ConsentSource, type ConsentState, type OptionalCookie, type Purpose, type Signal, assertConsentConfig, browserGpc, consentCookie, consentDefaultScript, consentModeParams, createConsent, defaultSignal, effectiveConsent, getStoredConsent, pushGtagCommand, readConsent, refusedCookieExpiries, serializeConsent, storedConsentValue, unansweredConsent };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,20 @@
|
|
|
1
1
|
// src/state.ts
|
|
2
|
+
function assertConsentConfig(config) {
|
|
3
|
+
const fail = (what) => {
|
|
4
|
+
throw new Error(`consent config: ${what}`);
|
|
5
|
+
};
|
|
6
|
+
if ("cookieName" in config && !/^[A-Za-z0-9_-]+$/.test(String(config.cookieName))) fail(`cookie name ${JSON.stringify(config.cookieName)} is not a plain name`);
|
|
7
|
+
if ("version" in config && !(Number.isInteger(config.version) && config.version >= 1)) fail(`version ${config.version} is not a whole number from 1 up`);
|
|
8
|
+
if ("maxAgeSeconds" in config && !(Number.isInteger(config.maxAgeSeconds) && config.maxAgeSeconds > 0)) fail(`maxAgeSeconds ${config.maxAgeSeconds} is not a positive whole number`);
|
|
9
|
+
if (config.globalPrivacyControl !== void 0 && config.globalPrivacyControl !== "signal-wins" && config.globalPrivacyControl !== "answer-wins") fail(`globalPrivacyControl ${JSON.stringify(config.globalPrivacyControl)} is not a known policy`);
|
|
10
|
+
for (const [purpose, cookies] of Object.entries(config.optionalCookies ?? {})) {
|
|
11
|
+
for (const { pattern, paths } of cookies) {
|
|
12
|
+
if (!(pattern instanceof RegExp)) fail(`${purpose}: a cookie pattern is not a RegExp`);
|
|
13
|
+
if (pattern.global || pattern.sticky) fail(`${purpose}: ${pattern} has a g or y flag, which makes it match differently from one call to the next`);
|
|
14
|
+
for (const path of paths ?? []) if (!path.startsWith("/")) fail(`${purpose}: path ${JSON.stringify(path)} does not start with /`);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
2
18
|
function serializeConsent(state, config) {
|
|
3
19
|
return `a${state.analytics ? 1 : 0}m${state.marketing ? 1 : 0}v${config.version}`;
|
|
4
20
|
}
|
|
@@ -12,6 +28,11 @@ function unansweredConsent(model, gpc) {
|
|
|
12
28
|
if (model === "opt-in") return { analytics: false, marketing: false };
|
|
13
29
|
return { analytics: true, marketing: !gpc };
|
|
14
30
|
}
|
|
31
|
+
function effectiveConsent(stored, model, gpc, config = {}) {
|
|
32
|
+
const state = stored ?? unansweredConsent(model, gpc);
|
|
33
|
+
if (model === "opt-out" && gpc && config.globalPrivacyControl !== "answer-wins") return { ...state, marketing: false };
|
|
34
|
+
return state;
|
|
35
|
+
}
|
|
15
36
|
function defaultSignal(model) {
|
|
16
37
|
return model === "opt-in" ? "denied" : "granted";
|
|
17
38
|
}
|
|
@@ -30,12 +51,26 @@ function consentModeParams(state) {
|
|
|
30
51
|
function browserGpc() {
|
|
31
52
|
return typeof navigator !== "undefined" && navigator.globalPrivacyControl === true;
|
|
32
53
|
}
|
|
54
|
+
function cookieValue(cookieName) {
|
|
55
|
+
return document.cookie.match(new RegExp(`(?:^|; )${cookieName}=([^;]*)`))?.[1];
|
|
56
|
+
}
|
|
57
|
+
function storedConsentValue(config) {
|
|
58
|
+
if (typeof document === "undefined") return void 0;
|
|
59
|
+
assertConsentConfig({ cookieName: config.cookieName });
|
|
60
|
+
const cookie = cookieValue(config.cookieName);
|
|
61
|
+
if (cookie === void 0) return void 0;
|
|
62
|
+
try {
|
|
63
|
+
const latest = localStorage.getItem(config.cookieName);
|
|
64
|
+
if (latest && latest !== cookie && readConsent(latest, config)) return latest;
|
|
65
|
+
} catch {
|
|
66
|
+
}
|
|
67
|
+
return cookie;
|
|
68
|
+
}
|
|
33
69
|
function getStoredConsent(config) {
|
|
34
|
-
|
|
35
|
-
const m = document.cookie.match(new RegExp(`(?:^|; )${config.cookieName}=([^;]+)`));
|
|
36
|
-
return readConsent(m?.[1], config);
|
|
70
|
+
return readConsent(storedConsentValue(config), config);
|
|
37
71
|
}
|
|
38
72
|
function consentCookie(state, config, opts) {
|
|
73
|
+
assertConsentConfig(config);
|
|
39
74
|
return {
|
|
40
75
|
name: config.cookieName,
|
|
41
76
|
value: serializeConsent(state, config),
|
|
@@ -50,22 +85,33 @@ function refusedCookieExpiries(cookieString, state, hostname, optionalCookies) {
|
|
|
50
85
|
const labels = hostname.split(".");
|
|
51
86
|
const domains = ["", ...labels.slice(0, -1).map((_, i) => `.${labels.slice(i).join(".")}`)];
|
|
52
87
|
const names = cookieString.split("; ").map((part) => part.split("=")[0]).filter(Boolean);
|
|
53
|
-
return names.
|
|
88
|
+
return names.flatMap((name) => {
|
|
89
|
+
const paths = new Set(refused.filter(({ pattern }) => pattern.test(name)).flatMap(({ paths: paths2 }) => paths2 ?? ["/"]));
|
|
90
|
+
return [...paths].flatMap((path) => domains.map((domain) => `${name}=; path=${path}; max-age=0${domain ? `; domain=${domain}` : ""}`));
|
|
91
|
+
});
|
|
54
92
|
}
|
|
55
93
|
|
|
56
94
|
// src/inline-script.ts
|
|
57
95
|
function consentDefaultScript(config, model, firstPush) {
|
|
58
|
-
|
|
96
|
+
assertConsentConfig(config);
|
|
97
|
+
const name = config.cookieName;
|
|
59
98
|
const d = JSON.stringify(defaultSignal(model));
|
|
99
|
+
const value = "a([01])m([01])(?:v(\\d+))?";
|
|
60
100
|
const update = (a, m) => `gtag("consent","update",{analytics_storage:${a},ad_storage:${m},ad_user_data:${m},ad_personalization:${m},functionality_storage:"granted",personalization_storage:${a}});`;
|
|
101
|
+
const signalWins = config.globalPrivacyControl !== "answer-wins";
|
|
61
102
|
return [
|
|
62
103
|
"window.dataLayer=window.dataLayer||[];",
|
|
63
104
|
...firstPush ? [`window.dataLayer.push(${JSON.stringify(firstPush).replace(/</g, "\\u003c")});`] : [],
|
|
64
105
|
"function gtag(){dataLayer.push(arguments)}",
|
|
65
106
|
`gtag("consent","default",{ad_personalization:${d},ad_storage:${d},ad_user_data:${d},analytics_storage:${d},functionality_storage:${d},personalization_storage:${d},security_storage:"granted",wait_for_update:500});`,
|
|
66
|
-
`var
|
|
67
|
-
`if(
|
|
68
|
-
|
|
107
|
+
`var c=(document.cookie.match(/(?:^|; )${name}=([^;]*)/)||[])[1],r=/^${value}$/;`,
|
|
108
|
+
`try{var l=localStorage.getItem("${name}"),k=l&&l.match(r);if(c!==undefined&&k&&l!==c&&+(k[3]||1)>=${config.version}){c=l;document.cookie="${name}="+l+"; path=/; max-age=${config.maxAgeSeconds}; samesite=lax"}}catch(e){}`,
|
|
109
|
+
`var m=c&&c.match(r);if(m&&+(m[3]||1)<${config.version})m=null;`,
|
|
110
|
+
...model === "opt-out" ? [
|
|
111
|
+
"var g=navigator.globalPrivacyControl===true;",
|
|
112
|
+
`if(m){var a=m[1]==="1"?"granted":"denied",d=m[2]==="1"${signalWins ? "&&!g" : ""}?"granted":"denied";${update("a", "d")}}`,
|
|
113
|
+
`else if(g){${update('"granted"', '"denied"')}}`
|
|
114
|
+
] : [`if(m){var a=m[1]==="1"?"granted":"denied",d=m[2]==="1"?"granted":"denied";${update("a", "d")}}`],
|
|
69
115
|
'gtag("set","ads_data_redaction",true);',
|
|
70
116
|
'gtag("set","url_passthrough",false);'
|
|
71
117
|
].join("");
|
|
@@ -82,55 +128,120 @@ function pushGtagCommand(...args) {
|
|
|
82
128
|
w.dataLayer.push(asArguments(...args));
|
|
83
129
|
}
|
|
84
130
|
function createConsent(config, hooks = {}) {
|
|
131
|
+
assertConsentConfig(config);
|
|
85
132
|
const listeners = /* @__PURE__ */ new Set();
|
|
86
133
|
const settingsListeners = /* @__PURE__ */ new Set();
|
|
87
|
-
|
|
134
|
+
const report = (error, step) => {
|
|
135
|
+
try {
|
|
136
|
+
hooks.onError?.(error, step);
|
|
137
|
+
} catch {
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
const guarded = (step, run) => {
|
|
141
|
+
try {
|
|
142
|
+
run();
|
|
143
|
+
} catch (error) {
|
|
144
|
+
report(error, step);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
const cookieLine = (value) => `${config.cookieName}=${value}; path=/; max-age=${config.maxAgeSeconds}; samesite=lax`;
|
|
148
|
+
const rawCookie = () => document.cookie.match(new RegExp(`(?:^|; )${config.cookieName}=([^;]*)`))?.[1];
|
|
149
|
+
function remember(value) {
|
|
150
|
+
try {
|
|
151
|
+
localStorage.setItem(config.cookieName, value);
|
|
152
|
+
} catch (error) {
|
|
153
|
+
try {
|
|
154
|
+
localStorage.removeItem(config.cookieName);
|
|
155
|
+
} catch {
|
|
156
|
+
}
|
|
157
|
+
report(error, "storage");
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
function reconcile() {
|
|
161
|
+
if (typeof document === "undefined") return false;
|
|
162
|
+
try {
|
|
163
|
+
const cookie = rawCookie();
|
|
164
|
+
const latest = localStorage.getItem(config.cookieName);
|
|
165
|
+
if (!latest) return false;
|
|
166
|
+
if (cookie === void 0) {
|
|
167
|
+
localStorage.removeItem(config.cookieName);
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
if (latest === cookie || !readConsent(latest, config)) return false;
|
|
171
|
+
document.cookie = cookieLine(latest);
|
|
172
|
+
return true;
|
|
173
|
+
} catch {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
function decide(state, cause, persist) {
|
|
88
178
|
if (typeof window === "undefined") return;
|
|
89
179
|
pushGtagCommand("consent", "update", consentModeParams(state));
|
|
90
|
-
hooks.onApply?.(state);
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
180
|
+
guarded("onApply", () => hooks.onApply?.(state, cause));
|
|
181
|
+
if (persist) {
|
|
182
|
+
const hostname = window.location?.hostname ?? "";
|
|
183
|
+
for (const expiry of refusedCookieExpiries(document.cookie, state, hostname, config.optionalCookies)) document.cookie = expiry;
|
|
184
|
+
const value = serializeConsent(state, config);
|
|
185
|
+
document.cookie = cookieLine(value);
|
|
186
|
+
remember(value);
|
|
187
|
+
}
|
|
188
|
+
listeners.forEach((listener) => guarded("subscriber", () => listener(state)));
|
|
95
189
|
}
|
|
190
|
+
if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
|
|
191
|
+
window.addEventListener("storage", (event) => {
|
|
192
|
+
if (event.key !== config.cookieName || !event.newValue) return;
|
|
193
|
+
const state = readConsent(event.newValue, config);
|
|
194
|
+
if (state) decide(state, "other-tab", false);
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
function ensureDefault() {
|
|
198
|
+
if (typeof window === "undefined") return;
|
|
199
|
+
reconcile();
|
|
200
|
+
const dl = window.dataLayer ?? [];
|
|
201
|
+
const has = Array.from(dl).some((c) => c != null && typeof c === "object" && c[0] === "consent" && c[1] === "default");
|
|
202
|
+
if (has) return;
|
|
203
|
+
pushGtagCommand("consent", "default", {
|
|
204
|
+
ad_personalization: "denied",
|
|
205
|
+
ad_storage: "denied",
|
|
206
|
+
ad_user_data: "denied",
|
|
207
|
+
analytics_storage: "denied",
|
|
208
|
+
functionality_storage: "denied",
|
|
209
|
+
personalization_storage: "denied",
|
|
210
|
+
security_storage: "granted",
|
|
211
|
+
wait_for_update: 500
|
|
212
|
+
});
|
|
213
|
+
const stored = getStoredConsent(config);
|
|
214
|
+
if (stored) pushGtagCommand("consent", "update", consentModeParams(stored));
|
|
215
|
+
}
|
|
216
|
+
const effective = (model) => effectiveConsent(getStoredConsent(config), model, browserGpc(), config);
|
|
96
217
|
return {
|
|
97
218
|
config,
|
|
98
219
|
stored: () => getStoredConsent(config),
|
|
99
|
-
|
|
220
|
+
effective,
|
|
221
|
+
apply: (state) => decide(state, "answer", true),
|
|
100
222
|
answer(state, source) {
|
|
101
|
-
|
|
223
|
+
decide(state, "answer", true);
|
|
224
|
+
let sent = void 0;
|
|
102
225
|
try {
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
226
|
+
sent = hooks.record?.(state, source);
|
|
227
|
+
} catch (error) {
|
|
228
|
+
report(error, "record");
|
|
106
229
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
* strictest, whatever the model — and the stored answer now. Call it at
|
|
113
|
-
* module evaluation of a client component, before the tag manager's
|
|
114
|
-
* loader runs. Without a default, Google treats consent as granted.
|
|
115
|
-
*/
|
|
116
|
-
ensureDefault() {
|
|
117
|
-
if (typeof window === "undefined") return;
|
|
118
|
-
const dl = window.dataLayer ?? [];
|
|
119
|
-
const has = Array.from(dl).some((c) => c != null && typeof c === "object" && c[0] === "consent" && c[1] === "default");
|
|
120
|
-
if (has) return;
|
|
121
|
-
pushGtagCommand("consent", "default", {
|
|
122
|
-
ad_personalization: "denied",
|
|
123
|
-
ad_storage: "denied",
|
|
124
|
-
ad_user_data: "denied",
|
|
125
|
-
analytics_storage: "denied",
|
|
126
|
-
functionality_storage: "denied",
|
|
127
|
-
personalization_storage: "denied",
|
|
128
|
-
security_storage: "granted",
|
|
129
|
-
wait_for_update: 500
|
|
230
|
+
void Promise.resolve(sent).then((response) => {
|
|
231
|
+
const r = response;
|
|
232
|
+
if (r && typeof r === "object" && r.ok === false) throw new Error(`consent record was refused${typeof r.status === "number" ? ` (${r.status})` : ""}`);
|
|
233
|
+
}).catch((error) => report(error, "record")).then(() => {
|
|
234
|
+
reconcile();
|
|
130
235
|
});
|
|
131
|
-
const stored = getStoredConsent(config);
|
|
132
|
-
if (stored) pushGtagCommand("consent", "update", consentModeParams(stored));
|
|
133
236
|
},
|
|
237
|
+
start(model) {
|
|
238
|
+
ensureDefault();
|
|
239
|
+
const state = effective(model);
|
|
240
|
+
if (typeof window !== "undefined") guarded("onApply", () => hooks.onApply?.(state, "start"));
|
|
241
|
+
return state;
|
|
242
|
+
},
|
|
243
|
+
ensureDefault,
|
|
244
|
+
reconcile,
|
|
134
245
|
subscribe(listener) {
|
|
135
246
|
listeners.add(listener);
|
|
136
247
|
return () => listeners.delete(listener);
|
|
@@ -145,16 +256,19 @@ function createConsent(config, hooks = {}) {
|
|
|
145
256
|
};
|
|
146
257
|
}
|
|
147
258
|
export {
|
|
259
|
+
assertConsentConfig,
|
|
148
260
|
browserGpc,
|
|
149
261
|
consentCookie,
|
|
150
262
|
consentDefaultScript,
|
|
151
263
|
consentModeParams,
|
|
152
264
|
createConsent,
|
|
153
265
|
defaultSignal,
|
|
266
|
+
effectiveConsent,
|
|
154
267
|
getStoredConsent,
|
|
155
268
|
pushGtagCommand,
|
|
156
269
|
readConsent,
|
|
157
270
|
refusedCookieExpiries,
|
|
158
271
|
serializeConsent,
|
|
272
|
+
storedConsentValue,
|
|
159
273
|
unansweredConsent
|
|
160
274
|
};
|
package/dist/react.d.ts
CHANGED
|
@@ -19,8 +19,12 @@ interface ConsentState {
|
|
|
19
19
|
type ConsentModel = 'opt-in' | 'opt-out';
|
|
20
20
|
/** One optional cookie a tag sets: how to recognise its name, and who sets it. */
|
|
21
21
|
interface OptionalCookie {
|
|
22
|
+
/** Matches the cookie's name. No `g` or `y` flag: those make a pattern remember where it last matched. */
|
|
22
23
|
pattern: RegExp;
|
|
23
24
|
setBy: string;
|
|
25
|
+
/** The paths the cookie may have been set on. A cookie can only be removed
|
|
26
|
+
* by naming its path. Default: `['/']`, where tags set theirs. */
|
|
27
|
+
paths?: readonly string[];
|
|
24
28
|
}
|
|
25
29
|
/** What a site decides about its own consent; everything else here is the same for every site. */
|
|
26
30
|
interface ConsentConfig {
|
|
@@ -42,6 +46,15 @@ interface ConsentConfig {
|
|
|
42
46
|
* withdrawn, and what the site's privacy policy has to name.
|
|
43
47
|
*/
|
|
44
48
|
optionalCookies: Record<Purpose, readonly OptionalCookie[]>;
|
|
49
|
+
/**
|
|
50
|
+
* In an opt-out model, what decides when the browser sends Global Privacy
|
|
51
|
+
* Control and the visitor has also stored a yes to marketing:
|
|
52
|
+
* - 'signal-wins' (default): the signal. Marketing stays off for as long
|
|
53
|
+
* as the browser sends it, whatever was answered before.
|
|
54
|
+
* - 'answer-wins': the stored answer.
|
|
55
|
+
* Has no effect in an opt-in model, where nothing runs without a yes.
|
|
56
|
+
*/
|
|
57
|
+
globalPrivacyControl?: 'signal-wins' | 'answer-wins';
|
|
45
58
|
}
|
|
46
59
|
|
|
47
60
|
/** Where the visitor gave the answer: the first-visit banner, or "Cookie settings" later. */
|
|
@@ -50,13 +63,30 @@ interface ConsentController {
|
|
|
50
63
|
readonly config: ConsentConfig;
|
|
51
64
|
/** The visitor's stored answer in this browser, or null. */
|
|
52
65
|
stored(): ConsentState | null;
|
|
53
|
-
/**
|
|
66
|
+
/** What applies to this visitor now: the stored answer, else the model's rule, with Global Privacy Control (state.ts: effectiveConsent). */
|
|
67
|
+
effective(model: ConsentModel): ConsentState;
|
|
68
|
+
/** Apply a decision everywhere: Consent Mode update → onApply → refused cookies removed → cookie and memory written → subscribers. */
|
|
54
69
|
apply(state: ConsentState): void;
|
|
55
70
|
/** The visitor answered: apply it now, then tell the server (hooks.record). */
|
|
56
71
|
answer(state: ConsentState, source: ConsentSource): void;
|
|
57
|
-
/**
|
|
72
|
+
/**
|
|
73
|
+
* Call once when the page starts, before optional SDKs initialise (module
|
|
74
|
+
* evaluation of the banner component is the place): makes sure a Consent
|
|
75
|
+
* Mode default exists, puts right a cookie a late server response got
|
|
76
|
+
* wrong, and runs `onApply` with what applies to this visitor, so every
|
|
77
|
+
* tool starts from the same decision the tags did. Returns that decision.
|
|
78
|
+
*/
|
|
79
|
+
start(model: ConsentModel): ConsentState;
|
|
80
|
+
/** Push an all-denied default (and the stored answer) if the data layer holds none yet. `start` does this too. */
|
|
58
81
|
ensureDefault(): void;
|
|
59
|
-
/**
|
|
82
|
+
/**
|
|
83
|
+
* Put the cookie back in line with the latest answer this browser
|
|
84
|
+
* remembers, if a late server response replaced it. True when it had to.
|
|
85
|
+
* Runs by itself at start and after every record; call it yourself after
|
|
86
|
+
* any other request whose response may set the consent cookie.
|
|
87
|
+
*/
|
|
88
|
+
reconcile(): boolean;
|
|
89
|
+
/** Hear every applied decision, from this tab or another. Returns the unsubscribe. */
|
|
60
90
|
subscribe(listener: (state: ConsentState) => void): () => void;
|
|
61
91
|
/** "Cookie settings" was pressed: ask the banner to open its choices. */
|
|
62
92
|
openSettings(): void;
|
|
@@ -95,6 +125,7 @@ interface ConsentBanner<T extends HTMLElement> {
|
|
|
95
125
|
* moves into the banner, Escape closes it and focus goes back to the link.
|
|
96
126
|
* - The banner appears only after hydration (the cookie is read in the
|
|
97
127
|
* browser), and never for a visitor whose answer still counts.
|
|
128
|
+
* - An answer given in another tab closes the question here too.
|
|
98
129
|
*
|
|
99
130
|
* What the markup must do: draw "reject all" and "accept all" as the same
|
|
100
131
|
* control side by side, so no is exactly as easy as yes, and never block the
|
package/dist/react.js
CHANGED
|
@@ -2,17 +2,6 @@
|
|
|
2
2
|
|
|
3
3
|
// src/react.ts
|
|
4
4
|
import { useEffect, useRef, useState } from "react";
|
|
5
|
-
|
|
6
|
-
// src/state.ts
|
|
7
|
-
function unansweredConsent(model, gpc) {
|
|
8
|
-
if (model === "opt-in") return { analytics: false, marketing: false };
|
|
9
|
-
return { analytics: true, marketing: !gpc };
|
|
10
|
-
}
|
|
11
|
-
function browserGpc() {
|
|
12
|
-
return typeof navigator !== "undefined" && navigator.globalPrivacyControl === true;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
// src/react.ts
|
|
16
5
|
function useConsentBanner(consent, model) {
|
|
17
6
|
const cardRef = useRef(null);
|
|
18
7
|
const opener = useRef(null);
|
|
@@ -25,12 +14,19 @@ function useConsentBanner(consent, model) {
|
|
|
25
14
|
useEffect(
|
|
26
15
|
() => consent.subscribeSettings(() => {
|
|
27
16
|
opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
|
28
|
-
setChoiceState(consent.
|
|
17
|
+
setChoiceState(consent.effective(model));
|
|
29
18
|
setFromSettings(true);
|
|
30
19
|
setView("choose");
|
|
31
20
|
}),
|
|
32
21
|
[consent, model]
|
|
33
22
|
);
|
|
23
|
+
useEffect(
|
|
24
|
+
() => consent.subscribe((state) => {
|
|
25
|
+
setChoiceState(state);
|
|
26
|
+
setView((current) => current === "ask" ? "hidden" : current);
|
|
27
|
+
}),
|
|
28
|
+
[consent]
|
|
29
|
+
);
|
|
34
30
|
function dismiss(next) {
|
|
35
31
|
setView(next);
|
|
36
32
|
setFromSettings(false);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@venturetime/consent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Cookie consent without a banner vendor: the answer, its cookie, Google Consent Mode v2 signals and the banner's behaviour. No markup, no text, no database.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -23,13 +23,15 @@
|
|
|
23
23
|
"main": "./dist/index.js",
|
|
24
24
|
"types": "./dist/index.d.ts",
|
|
25
25
|
"files": [
|
|
26
|
-
"dist"
|
|
26
|
+
"dist",
|
|
27
|
+
"CHANGELOG.md"
|
|
27
28
|
],
|
|
28
29
|
"scripts": {
|
|
29
30
|
"build": "tsup",
|
|
30
31
|
"typecheck": "tsc --noEmit",
|
|
31
32
|
"test": "vitest run",
|
|
32
|
-
"prepublishOnly": "pnpm typecheck && pnpm test && pnpm build"
|
|
33
|
+
"prepublishOnly": "pnpm typecheck && pnpm test && pnpm build",
|
|
34
|
+
"test:browser": "pnpm build && playwright test"
|
|
33
35
|
},
|
|
34
36
|
"peerDependencies": {
|
|
35
37
|
"react": ">=18"
|
|
@@ -40,6 +42,7 @@
|
|
|
40
42
|
}
|
|
41
43
|
},
|
|
42
44
|
"devDependencies": {
|
|
45
|
+
"@playwright/test": "1.59.1",
|
|
43
46
|
"@types/react": "^19",
|
|
44
47
|
"@types/react-dom": "^19",
|
|
45
48
|
"jsdom": "^26",
|