@luwiostack/cookie-consent 0.0.0-stage → 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/README.md +415 -2
- package/dist/index.cjs +569 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +118 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +118 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +558 -0
- package/dist/index.mjs.map +1 -0
- package/dist/machine-names-DAJioLt5.mjs +102 -0
- package/dist/machine-names-DAJioLt5.mjs.map +1 -0
- package/dist/machine-names-DCujHBVM.cjs +137 -0
- package/dist/machine-names-DCujHBVM.cjs.map +1 -0
- package/dist/react.cjs +124 -0
- package/dist/react.cjs.map +1 -0
- package/dist/react.d.cts +109 -0
- package/dist/react.d.cts.map +1 -0
- package/dist/react.d.mts +109 -0
- package/dist/react.d.mts.map +1 -0
- package/dist/react.mjs +120 -0
- package/dist/react.mjs.map +1 -0
- package/dist/types-ByyibBUg.d.cts +272 -0
- package/dist/types-ByyibBUg.d.cts.map +1 -0
- package/dist/types-ByyibBUg.d.mts +272 -0
- package/dist/types-ByyibBUg.d.mts.map +1 -0
- package/dist/used-vendors-C8uSNIkd.cjs +14 -0
- package/dist/used-vendors-C8uSNIkd.cjs.map +1 -0
- package/dist/used-vendors-Dxk4PZtY.mjs +9 -0
- package/dist/used-vendors-Dxk4PZtY.mjs.map +1 -0
- package/dist/vendors.cjs +619 -0
- package/dist/vendors.cjs.map +1 -0
- package/dist/vendors.d.cts +171 -0
- package/dist/vendors.d.cts.map +1 -0
- package/dist/vendors.d.mts +171 -0
- package/dist/vendors.d.mts.map +1 -0
- package/dist/vendors.mjs +606 -0
- package/dist/vendors.mjs.map +1 -0
- package/package.json +89 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,569 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_machine_names = require("./machine-names-DCujHBVM.cjs");
|
|
3
|
+
const require_used_vendors = require("./used-vendors-C8uSNIkd.cjs");
|
|
4
|
+
let _luwiostack_storage = require("@luwiostack/storage");
|
|
5
|
+
//#region src/domain/consent-decision.ts
|
|
6
|
+
/**
|
|
7
|
+
* One visitor's answer to the consent question: which categories they granted, under which policy
|
|
8
|
+
* version, and when. Immutable and always valid — the factory throws on a malformed input.
|
|
9
|
+
*
|
|
10
|
+
* Validity over time (policy version, expiry) is not the decision's concern: the consent instance
|
|
11
|
+
* decides whether a stored decision still counts.
|
|
12
|
+
*/
|
|
13
|
+
var ConsentDecision = class ConsentDecision {
|
|
14
|
+
consent_id;
|
|
15
|
+
policy_version;
|
|
16
|
+
/** When the decision was made, in epoch milliseconds. */
|
|
17
|
+
decided_at;
|
|
18
|
+
#granted;
|
|
19
|
+
constructor(input) {
|
|
20
|
+
this.consent_id = input.consent_id;
|
|
21
|
+
this.policy_version = input.policy_version;
|
|
22
|
+
this.decided_at = input.decided_at;
|
|
23
|
+
this.#granted = new Set(input.granted);
|
|
24
|
+
}
|
|
25
|
+
/** @throws {ConsentError} on an empty `consent_id` / `policy_version` or a non-finite `decided_at`. */
|
|
26
|
+
static new(input) {
|
|
27
|
+
if (typeof input.consent_id !== "string" || input.consent_id === "") throw new require_machine_names.ConsentError("A consent decision needs a non-empty consent_id.");
|
|
28
|
+
if (typeof input.policy_version !== "string" || input.policy_version === "") throw new require_machine_names.ConsentError("A consent decision needs a non-empty policy_version.");
|
|
29
|
+
if (typeof input.decided_at !== "number" || !Number.isFinite(input.decided_at)) throw new require_machine_names.ConsentError("A consent decision needs decided_at as finite epoch milliseconds.");
|
|
30
|
+
return new ConsentDecision(input);
|
|
31
|
+
}
|
|
32
|
+
/** Like {@link ConsentDecision.new}, but returns `null` instead of throwing. */
|
|
33
|
+
static tryNew(input) {
|
|
34
|
+
try {
|
|
35
|
+
return ConsentDecision.new(input);
|
|
36
|
+
} catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Whether this decision grants the category. */
|
|
41
|
+
isGranted(id) {
|
|
42
|
+
return this.#granted.has(id);
|
|
43
|
+
}
|
|
44
|
+
/** Every granted category id. */
|
|
45
|
+
granted() {
|
|
46
|
+
return [...this.#granted];
|
|
47
|
+
}
|
|
48
|
+
/** Same id, version, time and granted set. */
|
|
49
|
+
equals(other) {
|
|
50
|
+
if (this.consent_id !== other.consent_id || this.policy_version !== other.policy_version || this.decided_at !== other.decided_at || this.#granted.size !== other.#granted.size) return false;
|
|
51
|
+
for (const id of this.#granted) if (!other.#granted.has(id)) return false;
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
/** The serialized form kept in the store. */
|
|
55
|
+
toJSON() {
|
|
56
|
+
return {
|
|
57
|
+
consent_id: this.consent_id,
|
|
58
|
+
policy_version: this.policy_version,
|
|
59
|
+
granted: this.granted(),
|
|
60
|
+
decided_at: this.decided_at
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
//#endregion
|
|
65
|
+
//#region src/consent.ts
|
|
66
|
+
/** The key the default `localStorage` store keeps the decision behind. */
|
|
67
|
+
const DEFAULT_STORAGE_KEY = "luwio.consent";
|
|
68
|
+
/** The default decision lifetime: 365 days. */
|
|
69
|
+
const DEFAULT_MAX_AGE = 31536e6;
|
|
70
|
+
const PENDING = Object.freeze({
|
|
71
|
+
status: "pending",
|
|
72
|
+
decision: null
|
|
73
|
+
});
|
|
74
|
+
const COOKIE_TYPES = /* @__PURE__ */ new Set([
|
|
75
|
+
"http",
|
|
76
|
+
"local_storage",
|
|
77
|
+
"session_storage",
|
|
78
|
+
"indexed_db",
|
|
79
|
+
"pixel"
|
|
80
|
+
]);
|
|
81
|
+
/** Checks one vendor declaration: an id, unique cookie names, valid categories and lifetimes. */
|
|
82
|
+
function validateVendor(vendor, listedIn) {
|
|
83
|
+
if (typeof vendor?.id !== "string" || vendor.id === "") throw new require_machine_names.ConsentError(`Category "${listedIn}": a vendor id must be non-empty.`);
|
|
84
|
+
const where = `Vendor "${vendor.id}"`;
|
|
85
|
+
if (!Array.isArray(vendor.cookies)) throw new require_machine_names.ConsentError(`${where}: cookies must be an array.`);
|
|
86
|
+
validateTransfers(vendor.transfers, where);
|
|
87
|
+
const names = /* @__PURE__ */ new Set();
|
|
88
|
+
for (const cookie of vendor.cookies) {
|
|
89
|
+
if (typeof cookie !== "object" || cookie === null) throw new require_machine_names.ConsentError(`${where}: every cookie must be an object.`);
|
|
90
|
+
if (typeof cookie.name !== "string" || cookie.name === "") throw new require_machine_names.ConsentError(`${where}: a cookie name must be non-empty.`);
|
|
91
|
+
if (names.has(cookie.name)) throw new require_machine_names.ConsentError(`${where}: duplicate cookie "${cookie.name}".`);
|
|
92
|
+
names.add(cookie.name);
|
|
93
|
+
if (!require_machine_names.isConsentCategoryId(cookie.category)) throw new require_machine_names.ConsentError(`${where}: cookie "${cookie.name}" needs a category (${require_machine_names.CONSENT_CATEGORIES.join(", ")}).`);
|
|
94
|
+
if (cookie.type !== void 0 && !COOKIE_TYPES.has(cookie.type)) throw new require_machine_names.ConsentError(`${where}: cookie "${cookie.name}" has an unknown type "${cookie.type}".`);
|
|
95
|
+
const { max_age } = cookie;
|
|
96
|
+
if (!(max_age === "session" || max_age === "persistent" || typeof max_age === "number" && Number.isFinite(max_age) && max_age > 0)) throw new require_machine_names.ConsentError(`${where}: cookie "${cookie.name}" needs max_age as positive milliseconds, 'session' or 'persistent'.`);
|
|
97
|
+
if (cookie.domain !== void 0 && (typeof cookie.domain !== "string" || !DOMAIN.test(cookie.domain))) throw new require_machine_names.ConsentError(`${where}: cookie "${cookie.name}" needs domain as a host name like ".youtube.com", or none for the site's own domain.`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/** A cookie domain: a host name, optionally with a leading dot, no scheme, port or path. */
|
|
101
|
+
const DOMAIN = /^\.?[a-z0-9-]+(\.[a-z0-9-]+)+$/i;
|
|
102
|
+
const SAFEGUARDS = /* @__PURE__ */ new Set([
|
|
103
|
+
"adequacy",
|
|
104
|
+
"dpf",
|
|
105
|
+
"scc",
|
|
106
|
+
"bcr"
|
|
107
|
+
]);
|
|
108
|
+
/** Transfers: absent, or per unique ISO alpha-2 country at least one known safeguard. */
|
|
109
|
+
function validateTransfers(transfers, where) {
|
|
110
|
+
if (transfers === void 0) return;
|
|
111
|
+
if (!Array.isArray(transfers)) throw new require_machine_names.ConsentError(`${where}: transfers must be an array.`);
|
|
112
|
+
const countries = /* @__PURE__ */ new Set();
|
|
113
|
+
for (const transfer of transfers) {
|
|
114
|
+
const country = transfer?.country;
|
|
115
|
+
if (typeof country !== "string" || !/^[A-Z]{2}$/.test(country)) throw new require_machine_names.ConsentError(`${where}: a transfer needs country as ISO alpha-2, e.g. "US".`);
|
|
116
|
+
if (countries.has(country)) throw new require_machine_names.ConsentError(`${where}: duplicate transfer "${country}".`);
|
|
117
|
+
countries.add(country);
|
|
118
|
+
const { safeguards } = transfer;
|
|
119
|
+
if (!Array.isArray(safeguards) || safeguards.length === 0 || !safeguards.every((s) => SAFEGUARDS.has(s))) throw new require_machine_names.ConsentError(`${where}: transfer "${country}" needs safeguards from ${[...SAFEGUARDS].join(", ")}.`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Resolves the per-category config into the vendors the app actually uses: a vendor listed under a
|
|
124
|
+
* category brings its cookies of that category, plus its necessary cookies (always allowed, and part
|
|
125
|
+
* of any use of the service). A vendor listed under several categories is merged into one.
|
|
126
|
+
*/
|
|
127
|
+
function resolveVendors(config) {
|
|
128
|
+
if (typeof config !== "object" || config === null || Array.isArray(config)) throw new require_machine_names.ConsentError("categories must be an object of category id → vendors.");
|
|
129
|
+
for (const key of Object.keys(config)) if (!require_machine_names.isConsentCategoryId(key)) throw new require_machine_names.ConsentError(`Unknown consent category "${key}" — use ${require_machine_names.CONSENT_CATEGORIES.join(", ")}.`);
|
|
130
|
+
const merged = /* @__PURE__ */ new Map();
|
|
131
|
+
const idByMachineName = /* @__PURE__ */ new Map();
|
|
132
|
+
const listed = Object.fromEntries(require_machine_names.CONSENT_CATEGORIES.map((id) => [id, []]));
|
|
133
|
+
for (const category of require_machine_names.CONSENT_CATEGORIES) {
|
|
134
|
+
const inCategory = config[category];
|
|
135
|
+
if (inCategory === void 0) continue;
|
|
136
|
+
if (!Array.isArray(inCategory)) throw new require_machine_names.ConsentError(`Category "${category}": vendors must be an array.`);
|
|
137
|
+
const seen = /* @__PURE__ */ new Set();
|
|
138
|
+
for (const declaration of inCategory) {
|
|
139
|
+
validateVendor(declaration, category);
|
|
140
|
+
const vendor = require_machine_names.toConsentVendor(declaration);
|
|
141
|
+
const other = idByMachineName.get(vendor.machine_name);
|
|
142
|
+
if (other !== void 0 && other !== vendor.id) throw new require_machine_names.ConsentError(`Vendors "${other}" and "${vendor.id}" have the same machine name "${vendor.machine_name}".`);
|
|
143
|
+
idByMachineName.set(vendor.machine_name, vendor.id);
|
|
144
|
+
const where = `Category "${category}", vendor "${vendor.id}"`;
|
|
145
|
+
if (seen.has(vendor.id)) throw new require_machine_names.ConsentError(`${where}: duplicate vendor.`);
|
|
146
|
+
seen.add(vendor.id);
|
|
147
|
+
listed[category].push(vendor.id);
|
|
148
|
+
if (vendor.cookies.filter((c) => c.category === category).length === 0) throw new require_machine_names.ConsentError(`${where}: the vendor has no ${category} cookies.`);
|
|
149
|
+
const entry = merged.get(vendor.id) ?? {
|
|
150
|
+
vendor,
|
|
151
|
+
cookies: /* @__PURE__ */ new Map()
|
|
152
|
+
};
|
|
153
|
+
if (entry.vendor !== vendor && !sameVendorInfo(entry.vendor, vendor)) throw new require_machine_names.ConsentError(`Vendor "${vendor.id}" is declared differently in two categories (privacy_policy_url or transfers).`);
|
|
154
|
+
for (const cookie of vendor.cookies) {
|
|
155
|
+
if (cookie.category !== category && cookie.category !== "necessary") continue;
|
|
156
|
+
const known = entry.cookies.get(cookie.name);
|
|
157
|
+
if (known !== void 0 && !sameCookie(known, cookie)) throw new require_machine_names.ConsentError(`Vendor "${vendor.id}": cookie "${cookie.name}" is declared differently in two categories.`);
|
|
158
|
+
const clash = [...entry.cookies.values()].find((c) => c.name !== cookie.name && c.machine_name === cookie.machine_name);
|
|
159
|
+
if (clash) throw new require_machine_names.ConsentError(`Vendor "${vendor.id}": cookies "${clash.name}" and "${cookie.name}" have the same machine name "${cookie.machine_name}".`);
|
|
160
|
+
entry.cookies.set(cookie.name, cookie);
|
|
161
|
+
}
|
|
162
|
+
merged.set(vendor.id, entry);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return {
|
|
166
|
+
vendors: [...merged.values()].map(({ vendor, cookies }) => {
|
|
167
|
+
const order = vendor.cookies.map((c) => c.name).filter((name) => cookies.has(name));
|
|
168
|
+
const ordered = new Set(order);
|
|
169
|
+
for (const name of cookies.keys()) if (!ordered.has(name)) order.push(name);
|
|
170
|
+
return {
|
|
171
|
+
...vendor,
|
|
172
|
+
cookies: order.flatMap((name) => cookies.get(name) ?? [])
|
|
173
|
+
};
|
|
174
|
+
}),
|
|
175
|
+
listed
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
function sameVendorInfo(a, b) {
|
|
179
|
+
return a.privacy_policy_url === b.privacy_policy_url && transfersKey(a.transfers) === transfersKey(b.transfers);
|
|
180
|
+
}
|
|
181
|
+
/** Transfers in a canonical form: the same countries and safeguards in any order compare equal. */
|
|
182
|
+
function transfersKey(transfers) {
|
|
183
|
+
if (transfers === void 0) return "none";
|
|
184
|
+
return transfers.map((t) => `${t.country}:${[...t.safeguards].sort().join(",")}`).sort().join(";");
|
|
185
|
+
}
|
|
186
|
+
function sameCookie(a, b) {
|
|
187
|
+
return a.category === b.category && (a.type ?? "http") === (b.type ?? "http") && a.max_age === b.max_age && a.domain === b.domain;
|
|
188
|
+
}
|
|
189
|
+
function reusableId(record) {
|
|
190
|
+
const id = record?.consent_id;
|
|
191
|
+
return typeof id === "string" && id !== "" ? id : null;
|
|
192
|
+
}
|
|
193
|
+
function randomId() {
|
|
194
|
+
const c = globalThis.crypto;
|
|
195
|
+
if (c && typeof c.randomUUID === "function") return c.randomUUID();
|
|
196
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Create a consent instance: per category, the vendors the app uses there (a vendor brings only its
|
|
200
|
+
* cookies of that category, plus its necessary ones), where the decision is kept, and when it must
|
|
201
|
+
* be asked again. Create it once (module
|
|
202
|
+
* scope is fine — storage is only touched on access, so it's SSR-safe) and hand it to
|
|
203
|
+
* `<Consent consent={…}>` in React, or use it directly.
|
|
204
|
+
*
|
|
205
|
+
* ```ts
|
|
206
|
+
* import { googleAnalytics, youtube } from '@luwiostack/cookie-consent/vendors'
|
|
207
|
+
*
|
|
208
|
+
* const consent = createConsent({
|
|
209
|
+
* categories: {
|
|
210
|
+
* statistics: [googleAnalytics()],
|
|
211
|
+
* preferences: [youtube()], // the embed only — no YouTube tracking cookies
|
|
212
|
+
* },
|
|
213
|
+
* policyVersion: 2,
|
|
214
|
+
* })
|
|
215
|
+
* consent.isGranted('preferences', 'youtube') // the embed may load
|
|
216
|
+
* consent.isGranted('marketing', 'youtube') // false — not used there
|
|
217
|
+
* ```
|
|
218
|
+
*
|
|
219
|
+
* @throws {ConsentError} for an invalid `maxAge`, an unknown category, or an invalid vendor (listed
|
|
220
|
+
* twice in a category, no cookies of the category it's listed in, duplicate cookie, empty name,
|
|
221
|
+
* missing cookie category, bad `max_age` / `type`).
|
|
222
|
+
*/
|
|
223
|
+
function createConsent(config = {}) {
|
|
224
|
+
const { vendors, listed } = resolveVendors(config.categories ?? {});
|
|
225
|
+
const byId = new Map(vendors.map((v) => [v.id, v]));
|
|
226
|
+
const categories = require_machine_names.CONSENT_CATEGORIES.map((id) => {
|
|
227
|
+
const ids = [.../* @__PURE__ */ new Set([...listed[id], ...vendors.map((v) => v.id)])];
|
|
228
|
+
return {
|
|
229
|
+
id,
|
|
230
|
+
machine_name: require_machine_names.categoryMachineName(id),
|
|
231
|
+
description_machine_name: `${require_machine_names.categoryMachineName(id)}_description`,
|
|
232
|
+
required: id === require_machine_names.REQUIRED_CATEGORY,
|
|
233
|
+
vendors: ids.flatMap((vendorId) => {
|
|
234
|
+
const vendor = byId.get(vendorId);
|
|
235
|
+
const cookies = vendor.cookies.filter((c) => c.category === id);
|
|
236
|
+
return cookies.length > 0 ? [{
|
|
237
|
+
...vendor,
|
|
238
|
+
cookies
|
|
239
|
+
}] : [];
|
|
240
|
+
})
|
|
241
|
+
};
|
|
242
|
+
});
|
|
243
|
+
const usedIn = require_used_vendors.usedVendors(categories);
|
|
244
|
+
const maxAge = config.maxAge ?? 31536e6;
|
|
245
|
+
if (typeof maxAge !== "number" || Number.isNaN(maxAge) || maxAge <= 0) throw new require_machine_names.ConsentError("maxAge must be a positive number of milliseconds.");
|
|
246
|
+
const rawVersion = config.policyVersion ?? 1;
|
|
247
|
+
if (!(typeof rawVersion === "string" && rawVersion !== "" || typeof rawVersion === "number" && Number.isFinite(rawVersion))) throw new require_machine_names.ConsentError("policyVersion must be a non-empty string or a finite number.");
|
|
248
|
+
const policyVersion = String(rawVersion);
|
|
249
|
+
const store = config.store ?? (0, _luwiostack_storage.localStore)("luwio.consent", { onError: "ignore" });
|
|
250
|
+
const now = config.now ?? Date.now;
|
|
251
|
+
let unsaved;
|
|
252
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
253
|
+
const notify = () => {
|
|
254
|
+
for (const fn of [...listeners]) fn();
|
|
255
|
+
};
|
|
256
|
+
const read = () => unsaved !== void 0 ? unsaved : store.read();
|
|
257
|
+
let lastRecord;
|
|
258
|
+
let lastExpired = false;
|
|
259
|
+
let lastSnapshot = PENDING;
|
|
260
|
+
function toDecision(record) {
|
|
261
|
+
if (record.policy_version !== policyVersion) return null;
|
|
262
|
+
if (!Array.isArray(record.granted)) return null;
|
|
263
|
+
const granted = /* @__PURE__ */ new Set([require_machine_names.REQUIRED_CATEGORY]);
|
|
264
|
+
for (const id of record.granted) if (require_machine_names.isConsentCategoryId(id)) granted.add(id);
|
|
265
|
+
return ConsentDecision.tryNew({
|
|
266
|
+
...record,
|
|
267
|
+
granted
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
function getSnapshot() {
|
|
271
|
+
const record = read();
|
|
272
|
+
const age = record === null ? 0 : now() - record.decided_at;
|
|
273
|
+
const expired = record !== null && (age > maxAge || age < -3e5);
|
|
274
|
+
if (record === lastRecord && expired === lastExpired) return lastSnapshot;
|
|
275
|
+
lastRecord = record;
|
|
276
|
+
lastExpired = expired;
|
|
277
|
+
const decision = record && !expired ? toDecision(record) : null;
|
|
278
|
+
lastSnapshot = decision ? Object.freeze({
|
|
279
|
+
status: "decided",
|
|
280
|
+
decision
|
|
281
|
+
}) : PENDING;
|
|
282
|
+
return lastSnapshot;
|
|
283
|
+
}
|
|
284
|
+
function current() {
|
|
285
|
+
return getSnapshot().decision;
|
|
286
|
+
}
|
|
287
|
+
function commit(granted) {
|
|
288
|
+
const previous = current();
|
|
289
|
+
const set = /* @__PURE__ */ new Set([require_machine_names.REQUIRED_CATEGORY]);
|
|
290
|
+
for (const id of granted) if (require_machine_names.isConsentCategoryId(id)) set.add(id);
|
|
291
|
+
const next = ConsentDecision.new({
|
|
292
|
+
consent_id: previous?.consent_id ?? reusableId(read()) ?? randomId(),
|
|
293
|
+
policy_version: policyVersion,
|
|
294
|
+
granted: require_machine_names.CONSENT_CATEGORIES.filter((id) => set.has(id)),
|
|
295
|
+
decided_at: now()
|
|
296
|
+
});
|
|
297
|
+
const record = next.toJSON();
|
|
298
|
+
store.write(record);
|
|
299
|
+
const kept = store.read();
|
|
300
|
+
const landed = kept?.consent_id === record.consent_id && kept?.decided_at === record.decided_at;
|
|
301
|
+
unsaved = landed ? void 0 : record;
|
|
302
|
+
if (!landed) notify();
|
|
303
|
+
config.onChange?.(next, previous);
|
|
304
|
+
return next;
|
|
305
|
+
}
|
|
306
|
+
const isRequired = (id) => id === require_machine_names.REQUIRED_CATEGORY;
|
|
307
|
+
const isGranted = (id, vendorId) => (vendorId === void 0 || usedIn[id]?.has(vendorId) === true) && (isRequired(id) || (current()?.isGranted(id) ?? false));
|
|
308
|
+
return {
|
|
309
|
+
categories,
|
|
310
|
+
vendors,
|
|
311
|
+
policyVersion,
|
|
312
|
+
getSnapshot,
|
|
313
|
+
subscribe: (onChange) => {
|
|
314
|
+
listeners.add(onChange);
|
|
315
|
+
const unsubscribe = store.subscribe(onChange);
|
|
316
|
+
return () => {
|
|
317
|
+
listeners.delete(onChange);
|
|
318
|
+
unsubscribe();
|
|
319
|
+
};
|
|
320
|
+
},
|
|
321
|
+
isGranted,
|
|
322
|
+
isRequired,
|
|
323
|
+
acceptAll: () => commit(require_machine_names.CONSENT_CATEGORIES),
|
|
324
|
+
rejectAll: () => commit([]),
|
|
325
|
+
save: (granted) => commit(granted),
|
|
326
|
+
grant: (...grant) => commit([...current()?.granted() ?? [], ...grant]),
|
|
327
|
+
revoke: (...revoke) => {
|
|
328
|
+
const drop = new Set(revoke);
|
|
329
|
+
return commit((current()?.granted() ?? []).filter((id) => !drop.has(id)));
|
|
330
|
+
},
|
|
331
|
+
reset: () => {
|
|
332
|
+
const previous = current();
|
|
333
|
+
store.clear();
|
|
334
|
+
if (unsaved !== void 0) {
|
|
335
|
+
unsaved = void 0;
|
|
336
|
+
notify();
|
|
337
|
+
}
|
|
338
|
+
config.onChange?.(null, previous);
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
//#endregion
|
|
343
|
+
//#region src/formatters/consent-cookie-formatter.ts
|
|
344
|
+
const SECOND = 1e3;
|
|
345
|
+
const MINUTE = 60 * SECOND;
|
|
346
|
+
const HOUR = 60 * MINUTE;
|
|
347
|
+
const DAY = 24 * HOUR;
|
|
348
|
+
const UNITS = [
|
|
349
|
+
["year", 365 * DAY],
|
|
350
|
+
["month", 30 * DAY],
|
|
351
|
+
["day", DAY],
|
|
352
|
+
["hour", HOUR],
|
|
353
|
+
["minute", MINUTE],
|
|
354
|
+
["second", SECOND]
|
|
355
|
+
];
|
|
356
|
+
/** Renders a cookie declaration's values for people. */
|
|
357
|
+
var ConsentCookieFormatter = class {
|
|
358
|
+
/**
|
|
359
|
+
* A cookie's lifetime in `locale`, in the largest unit that divides it evenly: 2 years, 3 months,
|
|
360
|
+
* 400 days, 30 minutes — falling back to whole days (or the largest unit that fits) when nothing
|
|
361
|
+
* divides evenly. Returns `null` for `'session'` and `'persistent'`: those are words, so translate
|
|
362
|
+
* them — `formatLocale(cookie, locale) ?? t(cookie.max_age_machine_name)`.
|
|
363
|
+
*/
|
|
364
|
+
static formatLocale(cookie, locale, options = {}) {
|
|
365
|
+
const { max_age } = cookie;
|
|
366
|
+
if (typeof max_age !== "number") return null;
|
|
367
|
+
const unitDisplay = options.unitDisplay ?? "long";
|
|
368
|
+
const [unit, ms] = UNITS.find(([, ms]) => max_age >= ms && max_age % ms === 0) ?? (max_age >= DAY ? UNITS[2] : UNITS.find(([, u]) => max_age >= u) ?? UNITS[5]);
|
|
369
|
+
const value = Math.max(1, Math.round(max_age / ms));
|
|
370
|
+
return new Intl.NumberFormat(locale.toString(), {
|
|
371
|
+
style: "unit",
|
|
372
|
+
unit,
|
|
373
|
+
unitDisplay
|
|
374
|
+
}).format(value);
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
//#endregion
|
|
378
|
+
//#region src/integrations/clear-revoked-cookies.ts
|
|
379
|
+
/** A declared name as a matcher: `*` matches any run of characters (`_ga_*`, `ttcsid*`). */
|
|
380
|
+
function matcher(name) {
|
|
381
|
+
if (!name.includes("*")) return (actual) => actual === name;
|
|
382
|
+
const pattern = name.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"));
|
|
383
|
+
const re = new RegExp(`^${pattern.join(".*")}$`);
|
|
384
|
+
return (actual) => re.test(actual);
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* The domains a first-party cookie may have been set for: none (host-only), the host itself, and
|
|
388
|
+
* each parent domain (`www.shop.example.com` → `shop.example.com`, `example.com`). Analytics tags
|
|
389
|
+
* usually set theirs on the registrable domain, so deleting needs the same `Domain` attribute.
|
|
390
|
+
* A bare top-level domain (`com`) is never a valid cookie domain, so it's left out.
|
|
391
|
+
* @internal
|
|
392
|
+
*/
|
|
393
|
+
function domainCandidates(hostname) {
|
|
394
|
+
const parts = hostname.split(".");
|
|
395
|
+
const parents = [];
|
|
396
|
+
for (let i = 0; i < parts.length - 1; i++) parents.push(parts.slice(i).join("."));
|
|
397
|
+
return [void 0, ...parents];
|
|
398
|
+
}
|
|
399
|
+
/** The paths a cookie may have been set for, from this page up to the root: `/a/b` → `/a/b`, `/a`, `/`. @internal */
|
|
400
|
+
function pathCandidates(pathname) {
|
|
401
|
+
const segments = pathname.split("/").filter(Boolean);
|
|
402
|
+
const paths = ["/"];
|
|
403
|
+
for (let i = 1; i <= segments.length; i++) paths.push(`/${segments.slice(0, i).join("/")}`);
|
|
404
|
+
return paths;
|
|
405
|
+
}
|
|
406
|
+
function cookieNames(doc) {
|
|
407
|
+
return doc.cookie.split(";").map((pair) => pair.slice(0, pair.indexOf("=") === -1 ? void 0 : pair.indexOf("=")).trim()).filter(Boolean);
|
|
408
|
+
}
|
|
409
|
+
function expireCookie(doc, name) {
|
|
410
|
+
const { hostname, pathname } = doc.location;
|
|
411
|
+
for (const domain of domainCandidates(hostname)) for (const path of pathCandidates(pathname)) doc.cookie = `${name}=; Path=${path}${domain ? `; Domain=${domain}` : ""}; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT`;
|
|
412
|
+
}
|
|
413
|
+
function storageKeys(storage) {
|
|
414
|
+
const keys = [];
|
|
415
|
+
for (let i = 0; i < storage.length; i++) {
|
|
416
|
+
const key = storage.key(i);
|
|
417
|
+
if (key !== null) keys.push(key);
|
|
418
|
+
}
|
|
419
|
+
return keys;
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Remove what a withdrawn category left behind. At start and on every change, the declared cookies
|
|
423
|
+
* and storage items of every category that isn't granted are deleted — after "withdraw statistics",
|
|
424
|
+
* `_ga` and `_ga_*` are gone, not just unused. `necessary` is never touched, and a name a granted
|
|
425
|
+
* category also declares is kept.
|
|
426
|
+
*
|
|
427
|
+
* Only **first-party** storage can be reached: cookies on your own domain (tried with every parent
|
|
428
|
+
* domain and path, since tags set them broadly), `localStorage` / `sessionStorage` items and
|
|
429
|
+
* IndexedDB databases. A third-party cookie (declared with a `domain`, like `IDE` on
|
|
430
|
+
* doubleclick.net) lives on another site: it's skipped, so a first-party item that shares its name
|
|
431
|
+
* is never removed. `HttpOnly` cookies can only be removed by your server. Scripts already running keep
|
|
432
|
+
* running — reload the page (e.g. from `onClear`) to stop them.
|
|
433
|
+
*
|
|
434
|
+
* Returns a stop function. A no-op on the server.
|
|
435
|
+
*/
|
|
436
|
+
function clearRevokedCookies(consent, options = {}) {
|
|
437
|
+
if (typeof document === "undefined") return () => {};
|
|
438
|
+
const clear = () => {
|
|
439
|
+
const kept = [];
|
|
440
|
+
const revoked = [];
|
|
441
|
+
for (const category of consent.categories) {
|
|
442
|
+
const granted = category.id === "necessary" || consent.isGranted(category.id);
|
|
443
|
+
for (const vendor of category.vendors) for (const cookie of vendor.cookies) if (granted) kept.push(matcher(cookie.name));
|
|
444
|
+
else if (cookie.domain === void 0) revoked.push(cookie);
|
|
445
|
+
}
|
|
446
|
+
if (revoked.length === 0) return;
|
|
447
|
+
const isKept = (actual) => kept.some((matches) => matches(actual));
|
|
448
|
+
const cleared = (cookie, actual) => options.onClear?.(cookie, actual);
|
|
449
|
+
for (const cookie of revoked) {
|
|
450
|
+
const matches = matcher(cookie.name);
|
|
451
|
+
const type = cookie.type ?? "http";
|
|
452
|
+
if (type === "http") for (const actual of cookieNames(document)) {
|
|
453
|
+
if (!matches(actual) || isKept(actual)) continue;
|
|
454
|
+
expireCookie(document, actual);
|
|
455
|
+
if (!cookieNames(document).includes(actual)) cleared(cookie, actual);
|
|
456
|
+
}
|
|
457
|
+
else if (type === "local_storage" || type === "session_storage") {
|
|
458
|
+
let storage;
|
|
459
|
+
try {
|
|
460
|
+
storage = type === "local_storage" ? window.localStorage : window.sessionStorage;
|
|
461
|
+
} catch {
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
for (const actual of storageKeys(storage)) {
|
|
465
|
+
if (!matches(actual) || isKept(actual)) continue;
|
|
466
|
+
storage.removeItem(actual);
|
|
467
|
+
cleared(cookie, actual);
|
|
468
|
+
}
|
|
469
|
+
} else if (type === "indexed_db" && typeof indexedDB !== "undefined") {
|
|
470
|
+
if (typeof indexedDB.databases === "function") indexedDB.databases().then((databases) => {
|
|
471
|
+
for (const { name } of databases) {
|
|
472
|
+
if (!name || !matches(name) || isKept(name)) continue;
|
|
473
|
+
indexedDB.deleteDatabase(name);
|
|
474
|
+
cleared(cookie, name);
|
|
475
|
+
}
|
|
476
|
+
}).catch(() => {});
|
|
477
|
+
else if (!cookie.name.includes("*") && !isKept(cookie.name)) indexedDB.deleteDatabase(cookie.name);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
};
|
|
481
|
+
clear();
|
|
482
|
+
return consent.subscribe(clear);
|
|
483
|
+
}
|
|
484
|
+
//#endregion
|
|
485
|
+
//#region src/integrations/unblock-scripts.ts
|
|
486
|
+
/**
|
|
487
|
+
* Hold third-party scripts and embeds back until their category is granted — mark them up blocked and
|
|
488
|
+
* this activates them the moment consent allows (on load, and on every later change):
|
|
489
|
+
*
|
|
490
|
+
* ```html
|
|
491
|
+
* <!-- a script: type="text/plain" so the browser doesn't run it; data-type restores a module type -->
|
|
492
|
+
* <script type="text/plain" data-consent="statistics" src="https://example.com/analytics.js"><\/script>
|
|
493
|
+
* <script type="text/plain" data-consent="marketing">trackPageView()<\/script>
|
|
494
|
+
*
|
|
495
|
+
* <!-- with a vendor: also only while that vendor is used in the category -->
|
|
496
|
+
* <script type="text/plain" data-consent="marketing" data-consent-vendor="meta_pixel">fbq(…)<\/script>
|
|
497
|
+
*
|
|
498
|
+
* <!-- an iframe / img: data-src instead of src -->
|
|
499
|
+
* <iframe data-consent="marketing" data-src="https://www.youtube-nocookie.com/embed/…"></iframe>
|
|
500
|
+
* ```
|
|
501
|
+
*
|
|
502
|
+
* A script is replaced by a fresh `<script>` copy (the only way to make the browser run it), its
|
|
503
|
+
* CSP `nonce` included; an embed gets its `src` from `data-src`. Activation is one-way: a revoked category can't un-run a
|
|
504
|
+
* script — reload the page from `onChange` when something is withdrawn. Returns a stop function.
|
|
505
|
+
*/
|
|
506
|
+
function unblockScripts(consent, options = {}) {
|
|
507
|
+
if (typeof document === "undefined") return () => {};
|
|
508
|
+
const root = options.root ?? document;
|
|
509
|
+
const attr = options.attribute ?? "data-consent";
|
|
510
|
+
const vendorAttr = options.vendorAttribute ?? "data-consent-vendor";
|
|
511
|
+
const allowed = (el) => {
|
|
512
|
+
const ids = (el.getAttribute(attr) ?? "").split(/\s+/).filter(Boolean);
|
|
513
|
+
const vendor = el.getAttribute(vendorAttr) ?? void 0;
|
|
514
|
+
return ids.length > 0 && ids.every((id) => consent.isGranted(id, vendor));
|
|
515
|
+
};
|
|
516
|
+
const activate = () => {
|
|
517
|
+
for (const el of Array.from(root.querySelectorAll(`script[type="text/plain"][${attr}]`))) {
|
|
518
|
+
if (!allowed(el)) continue;
|
|
519
|
+
const script = document.createElement("script");
|
|
520
|
+
for (const { name, value } of Array.from(el.attributes)) {
|
|
521
|
+
if (name === "type" || name === "data-type") continue;
|
|
522
|
+
script.setAttribute(name, value);
|
|
523
|
+
}
|
|
524
|
+
const type = el.getAttribute("data-type");
|
|
525
|
+
if (type) script.setAttribute("type", type);
|
|
526
|
+
const { nonce } = el;
|
|
527
|
+
if (nonce) script.nonce = nonce;
|
|
528
|
+
if (!el.hasAttribute("src")) script.text = el.textContent ?? "";
|
|
529
|
+
el.replaceWith(script);
|
|
530
|
+
}
|
|
531
|
+
for (const el of Array.from(root.querySelectorAll(`[${attr}][data-src]:not(script)`))) {
|
|
532
|
+
if (!allowed(el)) continue;
|
|
533
|
+
const src = el.getAttribute("data-src");
|
|
534
|
+
el.removeAttribute("data-src");
|
|
535
|
+
if (src) el.setAttribute("src", src);
|
|
536
|
+
}
|
|
537
|
+
};
|
|
538
|
+
activate();
|
|
539
|
+
const unsubscribe = consent.subscribe(activate);
|
|
540
|
+
let observer;
|
|
541
|
+
if ((options.observe ?? true) && typeof MutationObserver !== "undefined") {
|
|
542
|
+
observer = new MutationObserver((records) => {
|
|
543
|
+
if (records.some((r) => r.addedNodes.length > 0)) activate();
|
|
544
|
+
});
|
|
545
|
+
const target = root instanceof Document ? root.documentElement : root;
|
|
546
|
+
observer.observe(target, {
|
|
547
|
+
childList: true,
|
|
548
|
+
subtree: true
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
return () => {
|
|
552
|
+
unsubscribe();
|
|
553
|
+
observer?.disconnect();
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
//#endregion
|
|
557
|
+
exports.CONSENT_CATEGORIES = require_machine_names.CONSENT_CATEGORIES;
|
|
558
|
+
exports.ConsentCookieFormatter = ConsentCookieFormatter;
|
|
559
|
+
exports.ConsentDecision = ConsentDecision;
|
|
560
|
+
exports.ConsentError = require_machine_names.ConsentError;
|
|
561
|
+
exports.DEFAULT_MAX_AGE = DEFAULT_MAX_AGE;
|
|
562
|
+
exports.DEFAULT_STORAGE_KEY = DEFAULT_STORAGE_KEY;
|
|
563
|
+
exports.REQUIRED_CATEGORY = require_machine_names.REQUIRED_CATEGORY;
|
|
564
|
+
exports.clearRevokedCookies = clearRevokedCookies;
|
|
565
|
+
exports.createConsent = createConsent;
|
|
566
|
+
exports.isConsentCategoryId = require_machine_names.isConsentCategoryId;
|
|
567
|
+
exports.unblockScripts = unblockScripts;
|
|
568
|
+
|
|
569
|
+
//# sourceMappingURL=index.cjs.map
|