@luwiostack/cookie-consent 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/dist/index.cjs ADDED
@@ -0,0 +1,571 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_errors = require("./errors-BqpghFQf.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_errors.ConsentError("A consent decision needs a non-empty consent_id.");
28
+ if (typeof input.policy_version !== "string" || input.policy_version === "") throw new require_errors.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_errors.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_errors.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_errors.ConsentError(`${where}: cookies must be an array.`);
86
+ const names = /* @__PURE__ */ new Set();
87
+ for (const cookie of vendor.cookies) {
88
+ if (typeof cookie.name !== "string" || cookie.name === "") throw new require_errors.ConsentError(`${where}: a cookie name must be non-empty.`);
89
+ if (names.has(cookie.name)) throw new require_errors.ConsentError(`${where}: duplicate cookie "${cookie.name}".`);
90
+ names.add(cookie.name);
91
+ if (!require_errors.isConsentCategoryId(cookie.category)) throw new require_errors.ConsentError(`${where}: cookie "${cookie.name}" needs a category (${require_errors.CONSENT_CATEGORIES.join(", ")}).`);
92
+ if (cookie.type !== void 0 && !COOKIE_TYPES.has(cookie.type)) throw new require_errors.ConsentError(`${where}: cookie "${cookie.name}" has an unknown type "${cookie.type}".`);
93
+ const { max_age } = cookie;
94
+ if (!(max_age === "session" || max_age === "persistent" || typeof max_age === "number" && Number.isFinite(max_age) && max_age > 0)) throw new require_errors.ConsentError(`${where}: cookie "${cookie.name}" needs max_age as positive milliseconds, 'session' or 'persistent'.`);
95
+ }
96
+ }
97
+ /**
98
+ * Resolves the per-category config into the vendors the app actually uses: a vendor listed under a
99
+ * category brings its cookies of that category, plus its necessary cookies (always allowed, and part
100
+ * of any use of the service). A vendor listed under several categories is merged into one.
101
+ */
102
+ function resolveVendors(config) {
103
+ if (typeof config !== "object" || config === null || Array.isArray(config)) throw new require_errors.ConsentError("categories must be an object of category id → vendors.");
104
+ for (const key of Object.keys(config)) if (!require_errors.isConsentCategoryId(key)) throw new require_errors.ConsentError(`Unknown consent category "${key}" — use ${require_errors.CONSENT_CATEGORIES.join(", ")}.`);
105
+ const merged = /* @__PURE__ */ new Map();
106
+ const listed = Object.fromEntries(require_errors.CONSENT_CATEGORIES.map((id) => [id, []]));
107
+ for (const category of require_errors.CONSENT_CATEGORIES) {
108
+ const inCategory = config[category];
109
+ if (inCategory === void 0) continue;
110
+ if (!Array.isArray(inCategory)) throw new require_errors.ConsentError(`Category "${category}": vendors must be an array.`);
111
+ const seen = /* @__PURE__ */ new Set();
112
+ for (const vendor of inCategory) {
113
+ validateVendor(vendor, category);
114
+ const where = `Category "${category}", vendor "${vendor.id}"`;
115
+ if (seen.has(vendor.id)) throw new require_errors.ConsentError(`${where}: duplicate vendor.`);
116
+ seen.add(vendor.id);
117
+ listed[category].push(vendor.id);
118
+ if (vendor.cookies.filter((c) => c.category === category).length === 0) throw new require_errors.ConsentError(`${where}: the vendor has no ${category} cookies.`);
119
+ const entry = merged.get(vendor.id) ?? {
120
+ vendor,
121
+ cookies: /* @__PURE__ */ new Map()
122
+ };
123
+ for (const cookie of vendor.cookies) if (cookie.category === category || cookie.category === "necessary") entry.cookies.set(cookie.name, cookie);
124
+ merged.set(vendor.id, entry);
125
+ }
126
+ }
127
+ return {
128
+ vendors: [...merged.values()].map(({ vendor, cookies }) => ({
129
+ ...vendor,
130
+ cookies: vendor.cookies.filter((c) => cookies.has(c.name))
131
+ })),
132
+ listed
133
+ };
134
+ }
135
+ function reusableId(record) {
136
+ const id = record?.consent_id;
137
+ return typeof id === "string" && id !== "" ? id : null;
138
+ }
139
+ function randomId() {
140
+ const c = globalThis.crypto;
141
+ if (c && typeof c.randomUUID === "function") return c.randomUUID();
142
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
143
+ }
144
+ /**
145
+ * Create a consent instance: per category, the vendors the app uses there (a vendor brings only its
146
+ * cookies of that category, plus its necessary ones), where the decision is kept, and when it must
147
+ * be asked again. Create it once (module
148
+ * scope is fine — storage is only touched on access, so it's SSR-safe) and hand it to
149
+ * `<Consent consent={…}>` in React, or use it directly.
150
+ *
151
+ * ```ts
152
+ * import { googleAnalytics, youtube } from '@luwiostack/cookie-consent/vendors'
153
+ *
154
+ * const consent = createConsent({
155
+ * categories: {
156
+ * statistics: [googleAnalytics()],
157
+ * preferences: [youtube()], // the embed only — no YouTube tracking cookies
158
+ * },
159
+ * policyVersion: 2,
160
+ * })
161
+ * consent.isGranted('preferences', 'youtube') // the embed may load
162
+ * consent.isGranted('marketing', 'youtube') // false — not used there
163
+ * ```
164
+ *
165
+ * @throws {ConsentError} for an invalid `maxAge`, an unknown category, or an invalid vendor (listed
166
+ * twice in a category, no cookies of the category it's listed in, duplicate cookie, empty name,
167
+ * missing cookie category, bad `max_age` / `type`).
168
+ */
169
+ function createConsent(config = {}) {
170
+ const { vendors, listed } = resolveVendors(config.categories ?? {});
171
+ const byId = new Map(vendors.map((v) => [v.id, v]));
172
+ const categories = require_errors.CONSENT_CATEGORIES.map((id) => {
173
+ const ids = [.../* @__PURE__ */ new Set([...listed[id], ...vendors.map((v) => v.id)])];
174
+ return {
175
+ id,
176
+ required: id === require_errors.REQUIRED_CATEGORY,
177
+ vendors: ids.flatMap((vendorId) => {
178
+ const vendor = byId.get(vendorId);
179
+ const cookies = vendor.cookies.filter((c) => c.category === id);
180
+ return cookies.length > 0 ? [{
181
+ ...vendor,
182
+ cookies
183
+ }] : [];
184
+ })
185
+ };
186
+ });
187
+ const usedIn = require_used_vendors.usedVendors(categories);
188
+ const maxAge = config.maxAge ?? 31536e6;
189
+ if (typeof maxAge !== "number" || Number.isNaN(maxAge) || maxAge <= 0) throw new require_errors.ConsentError("maxAge must be a positive number of milliseconds.");
190
+ const policyVersion = String(config.policyVersion ?? 1);
191
+ const store = config.store ?? (0, _luwiostack_storage.localStore)("luwio.consent", { onError: "ignore" });
192
+ const now = config.now ?? Date.now;
193
+ let unsaved;
194
+ const listeners = /* @__PURE__ */ new Set();
195
+ const notify = () => {
196
+ for (const fn of [...listeners]) fn();
197
+ };
198
+ const read = () => unsaved !== void 0 ? unsaved : store.read();
199
+ let lastRecord;
200
+ let lastExpired = false;
201
+ let lastSnapshot = PENDING;
202
+ function toDecision(record) {
203
+ if (record.policy_version !== policyVersion) return null;
204
+ if (!Array.isArray(record.granted)) return null;
205
+ const granted = /* @__PURE__ */ new Set([require_errors.REQUIRED_CATEGORY]);
206
+ for (const id of record.granted) if (require_errors.isConsentCategoryId(id)) granted.add(id);
207
+ return ConsentDecision.tryNew({
208
+ ...record,
209
+ granted
210
+ });
211
+ }
212
+ function getSnapshot() {
213
+ const record = read();
214
+ const age = record === null ? 0 : now() - record.decided_at;
215
+ const expired = record !== null && (age > maxAge || age < -3e5);
216
+ if (record === lastRecord && expired === lastExpired) return lastSnapshot;
217
+ lastRecord = record;
218
+ lastExpired = expired;
219
+ const decision = record && !expired ? toDecision(record) : null;
220
+ lastSnapshot = decision ? Object.freeze({
221
+ status: "decided",
222
+ decision
223
+ }) : PENDING;
224
+ return lastSnapshot;
225
+ }
226
+ function current() {
227
+ return getSnapshot().decision;
228
+ }
229
+ function commit(granted) {
230
+ const previous = current();
231
+ const set = /* @__PURE__ */ new Set([require_errors.REQUIRED_CATEGORY]);
232
+ for (const id of granted) if (require_errors.isConsentCategoryId(id)) set.add(id);
233
+ const next = ConsentDecision.new({
234
+ consent_id: previous?.consent_id ?? reusableId(read()) ?? randomId(),
235
+ policy_version: policyVersion,
236
+ granted: require_errors.CONSENT_CATEGORIES.filter((id) => set.has(id)),
237
+ decided_at: now()
238
+ });
239
+ const record = next.toJSON();
240
+ store.write(record);
241
+ const kept = store.read();
242
+ const landed = kept?.consent_id === record.consent_id && kept?.decided_at === record.decided_at;
243
+ unsaved = landed ? void 0 : record;
244
+ if (!landed) notify();
245
+ config.onChange?.(next, previous);
246
+ return next;
247
+ }
248
+ const isRequired = (id) => id === require_errors.REQUIRED_CATEGORY;
249
+ const isGranted = (id, vendorId) => (vendorId === void 0 || usedIn[id].has(vendorId)) && (isRequired(id) || (current()?.isGranted(id) ?? false));
250
+ return {
251
+ categories,
252
+ vendors,
253
+ policyVersion,
254
+ getSnapshot,
255
+ subscribe: (onChange) => {
256
+ listeners.add(onChange);
257
+ const unsubscribe = store.subscribe(onChange);
258
+ return () => {
259
+ listeners.delete(onChange);
260
+ unsubscribe();
261
+ };
262
+ },
263
+ isGranted,
264
+ isRequired,
265
+ acceptAll: () => commit(require_errors.CONSENT_CATEGORIES),
266
+ rejectAll: () => commit([]),
267
+ save: (granted) => commit(granted),
268
+ grant: (...grant) => commit([...current()?.granted() ?? [], ...grant]),
269
+ revoke: (...revoke) => {
270
+ const drop = new Set(revoke);
271
+ return commit((current()?.granted() ?? []).filter((id) => !drop.has(id)));
272
+ },
273
+ reset: () => {
274
+ const previous = current();
275
+ store.clear();
276
+ if (unsaved !== void 0) {
277
+ unsaved = void 0;
278
+ notify();
279
+ }
280
+ config.onChange?.(null, previous);
281
+ }
282
+ };
283
+ }
284
+ //#endregion
285
+ //#region src/formatters/consent-cookie-formatter.ts
286
+ const SECOND = 1e3;
287
+ const MINUTE = 60 * SECOND;
288
+ const HOUR = 60 * MINUTE;
289
+ const DAY = 24 * HOUR;
290
+ const UNITS = [
291
+ ["year", 365 * DAY],
292
+ ["month", 30 * DAY],
293
+ ["day", DAY],
294
+ ["hour", HOUR],
295
+ ["minute", MINUTE],
296
+ ["second", SECOND]
297
+ ];
298
+ /** Renders a cookie declaration's values for people. */
299
+ var ConsentCookieFormatter = class {
300
+ /**
301
+ * A cookie's lifetime in `locale`, in the largest unit that divides it evenly: 2 years, 3 months,
302
+ * 400 days, 30 minutes — falling back to whole days (or the largest unit that fits) when nothing
303
+ * divides evenly. Returns `null` for `'session'` and `'persistent'`: those are words, so render
304
+ * them through your own translations.
305
+ */
306
+ static formatLocale(cookie, locale, options = {}) {
307
+ const { max_age } = cookie;
308
+ if (typeof max_age !== "number") return null;
309
+ const unitDisplay = options.unitDisplay ?? "long";
310
+ 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]);
311
+ const value = Math.max(1, Math.round(max_age / ms));
312
+ return new Intl.NumberFormat(locale.toString(), {
313
+ style: "unit",
314
+ unit,
315
+ unitDisplay
316
+ }).format(value);
317
+ }
318
+ };
319
+ //#endregion
320
+ //#region src/integrations/clear-revoked-cookies.ts
321
+ /** A declared name as a matcher: `*` matches any run of characters (`_ga_*`, `ttcsid*`). */
322
+ function matcher(name) {
323
+ if (!name.includes("*")) return (actual) => actual === name;
324
+ const pattern = name.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"));
325
+ const re = new RegExp(`^${pattern.join(".*")}$`);
326
+ return (actual) => re.test(actual);
327
+ }
328
+ /**
329
+ * The domains a first-party cookie may have been set for: none (host-only), the host itself, and
330
+ * each parent domain (`www.shop.example.com` → `shop.example.com`, `example.com`). Analytics tags
331
+ * usually set theirs on the registrable domain, so deleting needs the same `Domain` attribute.
332
+ * A bare top-level domain (`com`) is never a valid cookie domain, so it's left out.
333
+ * @internal
334
+ */
335
+ function domainCandidates(hostname) {
336
+ const parts = hostname.split(".");
337
+ const parents = [];
338
+ for (let i = 0; i < parts.length - 1; i++) parents.push(parts.slice(i).join("."));
339
+ return [void 0, ...parents];
340
+ }
341
+ /** The paths a cookie may have been set for, from this page up to the root: `/a/b` → `/a/b`, `/a`, `/`. @internal */
342
+ function pathCandidates(pathname) {
343
+ const segments = pathname.split("/").filter(Boolean);
344
+ const paths = ["/"];
345
+ for (let i = 1; i <= segments.length; i++) paths.push(`/${segments.slice(0, i).join("/")}`);
346
+ return paths;
347
+ }
348
+ function cookieNames(doc) {
349
+ return doc.cookie.split(";").map((pair) => pair.slice(0, pair.indexOf("=") === -1 ? void 0 : pair.indexOf("=")).trim()).filter(Boolean);
350
+ }
351
+ function expireCookie(doc, name) {
352
+ const { hostname, pathname } = doc.location;
353
+ 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`;
354
+ }
355
+ function storageKeys(storage) {
356
+ const keys = [];
357
+ for (let i = 0; i < storage.length; i++) {
358
+ const key = storage.key(i);
359
+ if (key !== null) keys.push(key);
360
+ }
361
+ return keys;
362
+ }
363
+ /**
364
+ * Remove what a withdrawn category left behind. At start and on every change, the declared cookies
365
+ * and storage items of every category that isn't granted are deleted — after "withdraw statistics",
366
+ * `_ga` and `_ga_*` are gone, not just unused. `necessary` is never touched, and a name a granted
367
+ * category also declares is kept.
368
+ *
369
+ * Only **first-party** storage can be reached: cookies on your own domain (tried with every parent
370
+ * domain and path, since tags set them broadly), `localStorage` / `sessionStorage` items and
371
+ * IndexedDB databases. A third-party cookie (`IDE` on doubleclick.net) lives on another site and
372
+ * can't be removed from yours; `HttpOnly` cookies only by your server. Scripts already running keep
373
+ * running — reload the page (e.g. from `onClear`) to stop them.
374
+ *
375
+ * Returns a stop function. A no-op on the server.
376
+ */
377
+ function clearRevokedCookies(consent, options = {}) {
378
+ if (typeof document === "undefined") return () => {};
379
+ const clear = () => {
380
+ const kept = [];
381
+ const revoked = [];
382
+ for (const category of consent.categories) {
383
+ const granted = category.id === "necessary" || consent.isGranted(category.id);
384
+ for (const vendor of category.vendors) for (const cookie of vendor.cookies) if (granted) kept.push(matcher(cookie.name));
385
+ else revoked.push(cookie);
386
+ }
387
+ if (revoked.length === 0) return;
388
+ const isKept = (actual) => kept.some((matches) => matches(actual));
389
+ const cleared = (cookie, actual) => options.onClear?.(cookie, actual);
390
+ for (const cookie of revoked) {
391
+ const matches = matcher(cookie.name);
392
+ const type = cookie.type ?? "http";
393
+ if (type === "http") for (const actual of cookieNames(document)) {
394
+ if (!matches(actual) || isKept(actual)) continue;
395
+ expireCookie(document, actual);
396
+ if (!cookieNames(document).includes(actual)) cleared(cookie, actual);
397
+ }
398
+ else if (type === "local_storage" || type === "session_storage") {
399
+ let storage;
400
+ try {
401
+ storage = type === "local_storage" ? window.localStorage : window.sessionStorage;
402
+ } catch {
403
+ continue;
404
+ }
405
+ for (const actual of storageKeys(storage)) {
406
+ if (!matches(actual) || isKept(actual)) continue;
407
+ storage.removeItem(actual);
408
+ cleared(cookie, actual);
409
+ }
410
+ } else if (type === "indexed_db" && typeof indexedDB !== "undefined") {
411
+ if (typeof indexedDB.databases === "function") indexedDB.databases().then((databases) => {
412
+ for (const { name } of databases) {
413
+ if (!name || !matches(name) || isKept(name)) continue;
414
+ indexedDB.deleteDatabase(name);
415
+ cleared(cookie, name);
416
+ }
417
+ });
418
+ else if (!cookie.name.includes("*") && !isKept(cookie.name)) indexedDB.deleteDatabase(cookie.name);
419
+ }
420
+ }
421
+ };
422
+ clear();
423
+ return consent.subscribe(clear);
424
+ }
425
+ //#endregion
426
+ //#region src/integrations/google-consent-mode.ts
427
+ /** The standard mapping of Google's signals onto the fixed categories — the default. */
428
+ const DEFAULT_GOOGLE_CONSENT_MAPPING = {
429
+ ad_storage: "marketing",
430
+ ad_user_data: "marketing",
431
+ ad_personalization: "marketing",
432
+ analytics_storage: "statistics",
433
+ functionality_storage: "preferences",
434
+ personalization_storage: "preferences",
435
+ security_storage: "necessary"
436
+ };
437
+ function resolveGtag() {
438
+ if (typeof window === "undefined") return void 0;
439
+ const w = window;
440
+ if (typeof w.gtag === "function") return w.gtag;
441
+ w.dataLayer = w.dataLayer ?? [];
442
+ const dataLayer = w.dataLayer;
443
+ w.gtag = function gtag() {
444
+ dataLayer.push(arguments);
445
+ };
446
+ return w.gtag;
447
+ }
448
+ /**
449
+ * Wire a consent instance to Google Consent Mode v2: sends `gtag('consent', 'default', …)` with every
450
+ * mapped signal denied (signals mapped to required categories granted), then an `update` with the
451
+ * visitor's decision — immediately when one is stored, and again on every change.
452
+ *
453
+ * Call it **before** the Google tag (gtag.js / GTM) loads, so the default is in place for its first
454
+ * hit. Returns an unsubscribe. A no-op on the server.
455
+ */
456
+ function googleConsentMode(consent, options = {}) {
457
+ const gtag = options.gtag ?? resolveGtag();
458
+ if (!gtag) return () => {};
459
+ const entries = Object.entries(options.mapping ?? DEFAULT_GOOGLE_CONSENT_MAPPING);
460
+ const signals = (isGranted) => {
461
+ const out = {};
462
+ for (const [signal, cat] of entries) out[signal] = (typeof cat === "string" ? [cat] : cat).every(isGranted) ? "granted" : "denied";
463
+ return out;
464
+ };
465
+ if (options.adsDataRedaction) gtag("set", "ads_data_redaction", true);
466
+ if (options.urlPassthrough) gtag("set", "url_passthrough", true);
467
+ gtag("consent", "default", {
468
+ ...signals((id) => consent.isRequired(id)),
469
+ wait_for_update: options.waitForUpdate ?? 500,
470
+ ...options.region ? { region: [...options.region] } : {}
471
+ });
472
+ let last = "";
473
+ const sync = () => {
474
+ if (consent.getSnapshot().status !== "decided" && last === "") return;
475
+ const next = signals((id) => consent.isGranted(id));
476
+ const key = JSON.stringify(next);
477
+ if (key === last) return;
478
+ last = key;
479
+ gtag("consent", "update", next);
480
+ };
481
+ sync();
482
+ return consent.subscribe(sync);
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_errors.CONSENT_CATEGORIES;
558
+ exports.ConsentCookieFormatter = ConsentCookieFormatter;
559
+ exports.ConsentDecision = ConsentDecision;
560
+ exports.ConsentError = require_errors.ConsentError;
561
+ exports.DEFAULT_GOOGLE_CONSENT_MAPPING = DEFAULT_GOOGLE_CONSENT_MAPPING;
562
+ exports.DEFAULT_MAX_AGE = DEFAULT_MAX_AGE;
563
+ exports.DEFAULT_STORAGE_KEY = DEFAULT_STORAGE_KEY;
564
+ exports.REQUIRED_CATEGORY = require_errors.REQUIRED_CATEGORY;
565
+ exports.clearRevokedCookies = clearRevokedCookies;
566
+ exports.createConsent = createConsent;
567
+ exports.googleConsentMode = googleConsentMode;
568
+ exports.isConsentCategoryId = require_errors.isConsentCategoryId;
569
+ exports.unblockScripts = unblockScripts;
570
+
571
+ //# sourceMappingURL=index.cjs.map