@rcooler/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.
@@ -0,0 +1,687 @@
1
+ import { fetchJSON, sameOriginURL } from "./network.js";
2
+ import { deniedChoices, noRestrictions } from "./types.js";
3
+ import { regionalNotices, restrictionNames, serviceRestricted, validRestrictions, } from "./regional.js";
4
+ import { resolveNoticeLocale, validateConfig, validChoices } from "./validation.js";
5
+ const hasGrant = (choices) => Object.values(choices).some(Boolean);
6
+ const clone = (value) => JSON.parse(JSON.stringify(value));
7
+ /** No optional resource is created by this state machine without an explicit adapter. */
8
+ export function createConsent(options) {
9
+ if (!validateConfig(options.config))
10
+ throw new Error("Invalid consent configuration");
11
+ let config = clone(options.config);
12
+ const now = options.now ?? Date.now;
13
+ const origin = options.origin ?? location.origin;
14
+ const reload = options.reload ?? (() => location.reload());
15
+ const events = options.events ?? window;
16
+ const fetcher = options.fetcher ?? fetch;
17
+ const locale = options.locale ??
18
+ (typeof document !== "undefined" ? document.documentElement.lang || "en" : "en");
19
+ const configURL = options.configURL ? sameOriginURL(options.configURL, origin) : undefined;
20
+ if (config.receipt_url)
21
+ sameOriginURL(config.receipt_url, origin);
22
+ let storage;
23
+ try {
24
+ storage = options.storage ?? localStorage;
25
+ }
26
+ catch {
27
+ /* Storage denial is handled by save/read. */
28
+ }
29
+ const key = `rcooler.consent.v1.${config.policy.site}`;
30
+ const privacyKey = `rcooler.consent.privacy.v1.${config.policy.site}`;
31
+ const listeners = new Set();
32
+ const registrations = new Map();
33
+ const retries = new Set();
34
+ let generation = 0;
35
+ let destroyed = false;
36
+ let healthy = config.enabled && !configURL;
37
+ let checking;
38
+ let pending = false;
39
+ let error = null;
40
+ let decision = null;
41
+ let choices = deniedChoices();
42
+ let lastCheck = now();
43
+ let reloadRequested = false;
44
+ let restrictions = readRestrictions();
45
+ let lastSignal = gpc();
46
+ function gpc() {
47
+ try {
48
+ return (config.privacy_signals?.gpc === true ||
49
+ (options.privacySignal
50
+ ? options.privacySignal()
51
+ : typeof navigator !== "undefined" &&
52
+ navigator.globalPrivacyControl ===
53
+ true));
54
+ }
55
+ catch {
56
+ // A failing injected signal provider cannot restore an optional permission.
57
+ return true;
58
+ }
59
+ }
60
+ function effectiveRestrictions() {
61
+ return gpc()
62
+ ? { ...restrictions, sale: true, sharing: true, targeted_advertising: true }
63
+ : { ...restrictions };
64
+ }
65
+ function readRestrictions() {
66
+ try {
67
+ const raw = storage?.getItem(privacyKey);
68
+ if (!raw)
69
+ return noRestrictions();
70
+ if (raw.length > 1024)
71
+ throw new Error("Invalid privacy preferences");
72
+ const value = JSON.parse(raw);
73
+ if (!validRestrictions(value))
74
+ throw new Error("Invalid privacy preferences");
75
+ return value;
76
+ }
77
+ catch {
78
+ return { sale: true, sharing: true, targeted_advertising: true, sensitive_data: true };
79
+ }
80
+ }
81
+ function saveRestrictions(value) {
82
+ try {
83
+ if (!storage)
84
+ return false;
85
+ const encoded = JSON.stringify(value);
86
+ if (storage.getItem(privacyKey) !== encoded)
87
+ storage.setItem(privacyKey, encoded);
88
+ return storage.getItem(privacyKey) === encoded;
89
+ }
90
+ catch {
91
+ return false;
92
+ }
93
+ }
94
+ function read() {
95
+ try {
96
+ const raw = storage?.getItem(key) ?? "null";
97
+ if (raw.length > 16384)
98
+ return null;
99
+ const value = JSON.parse(raw);
100
+ if (!value ||
101
+ value.site !== config.policy.site ||
102
+ value.epoch !== config.policy.epoch ||
103
+ value.policy_version !== config.policy.version ||
104
+ (value.region?.selection_id ?? "") !== (config.region?.selection_id ?? "") ||
105
+ (value.restrictions !== undefined && !validRestrictions(value.restrictions)) ||
106
+ (config.region &&
107
+ (!validRestrictions(value.restrictions) ||
108
+ !value.privacy_signals ||
109
+ typeof value.privacy_signals.gpc !== "boolean")) ||
110
+ !validChoices(value.choices) ||
111
+ typeof value.event_id !== "string" ||
112
+ !/^[A-Za-z0-9_-]{1,128}$/.test(value.event_id) ||
113
+ typeof value.locale !== "string" ||
114
+ !/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/.test(value.locale) ||
115
+ typeof value.decided_at !== "string" ||
116
+ (value.receipt_id !== undefined &&
117
+ (typeof value.receipt_id !== "string" ||
118
+ !/^[A-Za-z0-9_-]{1,128}$/.test(value.receipt_id))) ||
119
+ !Number.isSafeInteger(value.sequence) ||
120
+ value.sequence <= 0 ||
121
+ !Number.isFinite(value.expires_at) ||
122
+ value.expires_at <= now() ||
123
+ value.expires_at >
124
+ Date.parse(value.decided_at) + config.policy.expires_after_days * 86400000 ||
125
+ !Number.isFinite(Date.parse(value.decided_at)) ||
126
+ Date.parse(value.decided_at) > now() + 60000 ||
127
+ typeof value.acknowledged !== "boolean" ||
128
+ (hasGrant(value.choices) &&
129
+ (!value.acknowledged || (config.receipt_url && !value.receipt_id))))
130
+ return null;
131
+ // A persisted receipt can retain a denial even if the separate privacy write failed.
132
+ if (value.restrictions)
133
+ for (const name of restrictionNames)
134
+ restrictions[name] ||= value.restrictions[name];
135
+ return value;
136
+ }
137
+ catch {
138
+ return null;
139
+ }
140
+ }
141
+ function save(value) {
142
+ try {
143
+ if (!storage)
144
+ return false;
145
+ storage.setItem(key, JSON.stringify(value));
146
+ return storage.getItem(key) === JSON.stringify(value);
147
+ }
148
+ catch {
149
+ return false;
150
+ }
151
+ }
152
+ function clearStored() {
153
+ try {
154
+ storage?.removeItem(key);
155
+ }
156
+ catch {
157
+ /* Denial remains in memory. */
158
+ }
159
+ }
160
+ function state() {
161
+ return {
162
+ config: clone(config),
163
+ choices: { ...choices },
164
+ decided: decision !== null && decision.source !== "privacy_signal",
165
+ pending,
166
+ error,
167
+ restrictions: effectiveRestrictions(),
168
+ privacy_signals: { gpc: gpc() },
169
+ };
170
+ }
171
+ function emit() {
172
+ for (const listener of listeners)
173
+ listener(state());
174
+ }
175
+ function allowed(serviceID) {
176
+ if (destroyed || !healthy || !config.enabled || (decision && decision.expires_at <= now()))
177
+ return false;
178
+ const service = config.policy.services.find((item) => item.id === serviceID);
179
+ return Boolean(service &&
180
+ (service.category === "necessary" || !(lastSignal && !gpc())) &&
181
+ !serviceRestricted(service, effectiveRestrictions(), gpc()) &&
182
+ config.allowed_services.includes(serviceID) &&
183
+ (service.category === "necessary" || choices[service.category]));
184
+ }
185
+ function cleanStorage(service) {
186
+ for (const entry of service.storage) {
187
+ try {
188
+ if (entry.type === "localStorage") {
189
+ if (entry.name !== key && entry.name !== privacyKey)
190
+ storage?.removeItem(entry.name);
191
+ }
192
+ else if (typeof document !== "undefined") {
193
+ // Only exact, declared cookie names are removed. HttpOnly and third-party storage require host cleanup.
194
+ if (!/^[!#$%&'*+.^_`|~A-Za-z0-9-]+$/.test(entry.name))
195
+ continue;
196
+ const domain = entry.domain ? `; Domain=${entry.domain}` : "";
197
+ document.cookie = `${entry.name}=; Max-Age=0; Path=${entry.path ?? "/"}${domain}; SameSite=Lax`;
198
+ }
199
+ }
200
+ catch {
201
+ /* Cleanup must never prevent denial. */
202
+ }
203
+ }
204
+ }
205
+ function stop(id, registration) {
206
+ if (!registration.abort)
207
+ return;
208
+ registration.abort.abort();
209
+ delete registration.abort;
210
+ try {
211
+ registration.cleanup?.();
212
+ }
213
+ catch {
214
+ /* A host cleanup failure cannot restore consent. */
215
+ }
216
+ delete registration.cleanup;
217
+ const service = config.policy.services.find((item) => item.id === id);
218
+ if (service)
219
+ cleanStorage(service);
220
+ if (registration.started && registration.adapter.reloadOnRevoke && !reloadRequested) {
221
+ reloadRequested = true;
222
+ reload();
223
+ }
224
+ registration.started = false;
225
+ }
226
+ function cleanDenied(requested) {
227
+ for (const service of config.policy.services) {
228
+ if ((service.category !== "necessary" && !requested[service.category]) ||
229
+ serviceRestricted(service, effectiveRestrictions(), gpc()))
230
+ cleanStorage(service);
231
+ }
232
+ }
233
+ function reconcile() {
234
+ for (const [id, registration] of registrations) {
235
+ if (!allowed(id)) {
236
+ stop(id, registration);
237
+ continue;
238
+ }
239
+ if (registration.abort)
240
+ continue;
241
+ const service = config.policy.services.find((item) => item.id === id);
242
+ if (!service)
243
+ continue;
244
+ const abort = new AbortController();
245
+ registration.abort = abort;
246
+ // Mark before invoking: a synchronous provider load also requires reload on withdrawal.
247
+ registration.started = true;
248
+ try {
249
+ const result = registration.adapter.activate({
250
+ service: clone(service),
251
+ signal: abort.signal,
252
+ isAllowed: () => !abort.signal.aborted && allowed(id),
253
+ });
254
+ void Promise.resolve(result)
255
+ .then((cleanup) => {
256
+ if (!cleanup)
257
+ return;
258
+ if (abort.signal.aborted || !allowed(id))
259
+ cleanup();
260
+ else
261
+ registration.cleanup = cleanup;
262
+ })
263
+ .catch(() => {
264
+ if (registration.abort !== abort)
265
+ return;
266
+ if (!abort.signal.aborted) {
267
+ error = "service_failed";
268
+ emit();
269
+ }
270
+ stop(id, registration);
271
+ });
272
+ }
273
+ catch {
274
+ if (registration.abort !== abort)
275
+ continue;
276
+ stop(id, registration);
277
+ error = "service_failed";
278
+ }
279
+ }
280
+ }
281
+ function deny(reason, clear = true) {
282
+ generation++;
283
+ choices = deniedChoices();
284
+ pending = false;
285
+ error = reason;
286
+ decision = null;
287
+ if (clear)
288
+ clearStored();
289
+ cleanDenied(choices);
290
+ reconcile();
291
+ emit();
292
+ }
293
+ function validAck(value, eventID) {
294
+ if (!value || typeof value !== "object")
295
+ return false;
296
+ const ack = value;
297
+ return (ack.event_id === eventID &&
298
+ typeof ack.receipt_id === "string" &&
299
+ /^[A-Za-z0-9_-]{1,128}$/.test(ack.receipt_id) &&
300
+ typeof ack.received_at === "string" &&
301
+ typeof ack.expires_at === "string" &&
302
+ Number.isFinite(Date.parse(ack.received_at)) &&
303
+ Number.isFinite(Date.parse(ack.expires_at)) &&
304
+ Date.parse(ack.expires_at) > now());
305
+ }
306
+ async function post(value) {
307
+ if (!config.receipt_url)
308
+ return undefined;
309
+ const submission = {
310
+ event_id: value.event_id,
311
+ site: value.site,
312
+ epoch: value.epoch,
313
+ policy_version: value.policy_version,
314
+ locale: value.locale,
315
+ choices: value.choices,
316
+ decided_at: value.decided_at,
317
+ sequence: value.sequence,
318
+ ...(value.previous_receipt_id ? { previous_receipt_id: value.previous_receipt_id } : {}),
319
+ ...(value.region ? { region: value.region } : {}),
320
+ privacy_signals: value.privacy_signals ?? { gpc: false },
321
+ restrictions: value.restrictions ?? noRestrictions(),
322
+ };
323
+ const response = await fetchJSON(sameOriginURL(config.receipt_url, origin), {
324
+ method: "POST",
325
+ headers: { "Content-Type": "application/json" },
326
+ body: JSON.stringify(submission),
327
+ }, fetcher);
328
+ if (!validAck(response, value.event_id))
329
+ throw new Error("Invalid consent receipt");
330
+ return response;
331
+ }
332
+ function recordDenial(value, attempt = 0) {
333
+ void post(value)
334
+ .then((ack) => {
335
+ if (destroyed ||
336
+ decision?.event_id !== value.event_id ||
337
+ read()?.event_id !== value.event_id)
338
+ return;
339
+ if (ack) {
340
+ value.receipt_id = ack.receipt_id;
341
+ value.acknowledged = true;
342
+ save(value);
343
+ decision = value;
344
+ }
345
+ })
346
+ .catch(() => {
347
+ if (destroyed || decision?.event_id !== value.event_id || attempt >= 2)
348
+ return;
349
+ const timer = setTimeout(() => {
350
+ retries.delete(timer);
351
+ recordDenial(value, attempt + 1);
352
+ }, 1000 * (attempt + 1));
353
+ retries.add(timer);
354
+ });
355
+ }
356
+ const controller = {
357
+ get state() {
358
+ return state();
359
+ },
360
+ subscribe(listener) {
361
+ listeners.add(listener);
362
+ listener(state());
363
+ return () => listeners.delete(listener);
364
+ },
365
+ isAllowed: allowed,
366
+ async decide(requested, requestedLocale, requestedRestrictions) {
367
+ if (destroyed ||
368
+ !validChoices(requested) ||
369
+ (requestedRestrictions !== undefined && !validRestrictions(requestedRestrictions)))
370
+ return false;
371
+ const priorRestrictions = restrictions;
372
+ // Accept-all only affects service categories. It never cancels a privacy opt-out.
373
+ restrictions = requestedRestrictions ? { ...requestedRestrictions } : effectiveRestrictions();
374
+ restrictions = effectiveRestrictions();
375
+ const relaxing = restrictionNames.some((name) => priorRestrictions[name] && !restrictions[name]);
376
+ // Lifting an opt-out cannot activate an earlier category grant before a new receipt.
377
+ if (relaxing) {
378
+ choices = deniedChoices();
379
+ clearStored();
380
+ reconcile();
381
+ }
382
+ const privacySaved = saveRestrictions(restrictions);
383
+ if (!privacySaved && relaxing) {
384
+ restrictions = priorRestrictions;
385
+ deny("storage_unavailable");
386
+ return false;
387
+ }
388
+ const previous = decision;
389
+ const token = ++generation;
390
+ const sequence = Math.max(previous?.sequence ?? 0, now()) + 1;
391
+ const value = {
392
+ event_id: crypto.randomUUID(),
393
+ site: config.policy.site,
394
+ epoch: config.policy.epoch,
395
+ policy_version: config.policy.version,
396
+ locale: regionalNotices(config, requestedLocale ?? locale)[0]?.locale ??
397
+ resolveNoticeLocale(config.policy, requestedLocale ?? locale),
398
+ choices: { ...requested },
399
+ decided_at: new Date(now()).toISOString(),
400
+ sequence,
401
+ expires_at: now() + config.policy.expires_after_days * 86400000,
402
+ acknowledged: !config.receipt_url,
403
+ ...(config.region ? { region: clone(config.region) } : {}),
404
+ privacy_signals: { gpc: gpc() },
405
+ restrictions: { ...restrictions },
406
+ };
407
+ if (previous?.receipt_id)
408
+ value.previous_receipt_id = previous.receipt_id;
409
+ // Apply every withdrawal before any storage or network operation.
410
+ choices = {
411
+ preferences: choices.preferences && requested.preferences,
412
+ analytics: choices.analytics && requested.analytics,
413
+ marketing: choices.marketing && requested.marketing,
414
+ };
415
+ pending = hasGrant(requested);
416
+ error = null;
417
+ cleanDenied(requested);
418
+ reconcile();
419
+ const saved = save(value);
420
+ decision = value;
421
+ emit();
422
+ if (!hasGrant(requested)) {
423
+ pending = false;
424
+ emit();
425
+ if (config.receipt_url)
426
+ recordDenial(value);
427
+ return true;
428
+ }
429
+ if (!saved) {
430
+ deny("storage_unavailable");
431
+ return false;
432
+ }
433
+ try {
434
+ if (configURL && !healthy)
435
+ await controller.recheck();
436
+ if (token !== generation || destroyed)
437
+ return false;
438
+ if (!healthy || !config.enabled)
439
+ throw new Error("Configuration unavailable");
440
+ const ack = await post(value);
441
+ // Storage must still contain this exact pending choice; another tab may already have denied it.
442
+ const stored = JSON.parse(storage?.getItem(key) ?? "null");
443
+ if (destroyed || token !== generation || stored?.event_id !== value.event_id)
444
+ return false;
445
+ if (gpc() && !value.privacy_signals?.gpc) {
446
+ synchronizePrivacy();
447
+ return false;
448
+ }
449
+ value.acknowledged = true;
450
+ if (ack) {
451
+ value.receipt_id = ack.receipt_id;
452
+ value.expires_at = Math.min(value.expires_at, Date.parse(ack.expires_at));
453
+ }
454
+ if (!save(value))
455
+ throw new Error("Storage unavailable");
456
+ decision = value;
457
+ choices = { ...value.choices };
458
+ pending = false;
459
+ reconcile();
460
+ emit();
461
+ return true;
462
+ }
463
+ catch {
464
+ if (token === generation && !destroyed)
465
+ deny("save_failed");
466
+ return false;
467
+ }
468
+ },
469
+ restrict(requested, requestedLocale) {
470
+ if (!validRestrictions(requested))
471
+ return Promise.resolve(false);
472
+ const merged = effectiveRestrictions();
473
+ for (const name of restrictionNames)
474
+ merged[name] ||= requested[name];
475
+ // An opt-out action never renews or reauthorizes an earlier category grant.
476
+ return controller.decide(deniedChoices(), requestedLocale, merged);
477
+ },
478
+ register(serviceID, adapter) {
479
+ if (destroyed ||
480
+ registrations.has(serviceID) ||
481
+ !config.policy.services.some((service) => service.id === serviceID)) {
482
+ throw new Error("Unknown or duplicate consent service");
483
+ }
484
+ const registration = { adapter, started: false };
485
+ registrations.set(serviceID, registration);
486
+ reconcile();
487
+ return () => {
488
+ stop(serviceID, registration);
489
+ registrations.delete(serviceID);
490
+ };
491
+ },
492
+ async recheck() {
493
+ if (destroyed)
494
+ return false;
495
+ if (checking)
496
+ return checking;
497
+ checking = (async () => {
498
+ if (decision && decision.expires_at <= now())
499
+ deny(null);
500
+ if (!configURL)
501
+ return healthy;
502
+ const token = generation;
503
+ try {
504
+ const fresh = await fetchJSON(configURL, {}, fetcher);
505
+ if (destroyed)
506
+ return false;
507
+ if (!validateConfig(fresh))
508
+ throw new Error("Invalid consent configuration");
509
+ if (fresh.receipt_url)
510
+ sameOriginURL(fresh.receipt_url, origin);
511
+ if (fresh.policy.site !== config.policy.site)
512
+ throw new Error("Consent site changed");
513
+ const changed = JSON.stringify(fresh.policy) !== JSON.stringify(config.policy) ||
514
+ fresh.receipt_url !== config.receipt_url ||
515
+ fresh.region?.selection_id !== config.region?.selection_id;
516
+ if (changed || !fresh.enabled)
517
+ deny(null);
518
+ config = clone(fresh);
519
+ synchronizePrivacy();
520
+ healthy = fresh.enabled;
521
+ // Rechecks never replace an in-flight local decision with a stale storage snapshot.
522
+ if (!changed && token === generation && !pending) {
523
+ decision = read();
524
+ choices = decision ? { ...decision.choices } : deniedChoices();
525
+ }
526
+ lastCheck = now();
527
+ reconcile();
528
+ emit();
529
+ return healthy;
530
+ }
531
+ catch {
532
+ healthy = false;
533
+ deny("config_unavailable");
534
+ return false;
535
+ }
536
+ })();
537
+ try {
538
+ return await checking;
539
+ }
540
+ finally {
541
+ checking = undefined;
542
+ }
543
+ },
544
+ destroy() {
545
+ destroyed = true;
546
+ generation++;
547
+ clearInterval(interval);
548
+ for (const timer of retries)
549
+ clearTimeout(timer);
550
+ for (const [id, registration] of registrations)
551
+ stop(id, registration);
552
+ registrations.clear();
553
+ listeners.clear();
554
+ events.removeEventListener("storage", onStorage);
555
+ events.removeEventListener("pageshow", onPageShow);
556
+ events.removeEventListener("focus", onFocus);
557
+ },
558
+ };
559
+ const onStorage = (event) => {
560
+ const storageEvent = event;
561
+ if (storageEvent.key === privacyKey || storageEvent.key === null) {
562
+ // A remote preference update can restrict this tab, but cannot silently lift its opt-outs.
563
+ const remote = readRestrictions();
564
+ for (const name of restrictionNames)
565
+ restrictions[name] ||= remote[name];
566
+ restrictions = effectiveRestrictions();
567
+ cleanDenied(choices);
568
+ reconcile();
569
+ emit();
570
+ if (storageEvent.key === privacyKey)
571
+ return;
572
+ }
573
+ if (storageEvent.key !== key && storageEvent.key !== null)
574
+ return;
575
+ // Storage events can arrive after a newer local decision. Their payload must still be current.
576
+ if (storage && (typeof storageEvent.newValue === "string" || storageEvent.newValue === null)) {
577
+ try {
578
+ if (storage.getItem(key) !== storageEvent.newValue)
579
+ return;
580
+ }
581
+ catch {
582
+ /* Unavailable storage is handled below as a denial. */
583
+ }
584
+ }
585
+ generation++;
586
+ pending = false;
587
+ decision = read();
588
+ cleanDenied(decision?.choices ?? deniedChoices());
589
+ // A cross-tab grant requires fresh eligibility before any activation.
590
+ choices = deniedChoices();
591
+ reconcile();
592
+ emit();
593
+ if (configURL)
594
+ void controller.recheck();
595
+ else {
596
+ choices = decision ? { ...decision.choices } : deniedChoices();
597
+ reconcile();
598
+ emit();
599
+ }
600
+ };
601
+ const onPageShow = (event) => {
602
+ synchronizePrivacy();
603
+ if (!event.persisted)
604
+ return;
605
+ deny(null, false);
606
+ if (configURL)
607
+ void controller.recheck();
608
+ };
609
+ function synchronizePrivacy() {
610
+ const signal = gpc();
611
+ if (signal === lastSignal)
612
+ return;
613
+ lastSignal = signal;
614
+ if (signal) {
615
+ restrictions = effectiveRestrictions();
616
+ saveRestrictions(restrictions);
617
+ generation++;
618
+ pending = false;
619
+ decision = null;
620
+ choices = deniedChoices();
621
+ clearStored();
622
+ cleanDenied(choices);
623
+ reconcile();
624
+ recordSignal();
625
+ }
626
+ else
627
+ deny(null);
628
+ emit();
629
+ }
630
+ function recordSignal() {
631
+ if (destroyed || !gpc())
632
+ return;
633
+ // Record the signal as a denial, never as a refreshed affirmative decision.
634
+ void controller.decide(deniedChoices(), locale, effectiveRestrictions());
635
+ if (decision) {
636
+ decision.source = "privacy_signal";
637
+ save(decision);
638
+ emit();
639
+ }
640
+ }
641
+ function recordInitialSignal() {
642
+ if (gpc() && !decision?.privacy_signals?.gpc)
643
+ recordSignal();
644
+ }
645
+ const onFocus = () => synchronizePrivacy();
646
+ events.addEventListener("storage", onStorage);
647
+ events.addEventListener("pageshow", onPageShow);
648
+ events.addEventListener("focus", onFocus);
649
+ restrictions = effectiveRestrictions();
650
+ if (gpc())
651
+ saveRestrictions(restrictions);
652
+ decision = read();
653
+ choices = decision ? { ...decision.choices } : deniedChoices();
654
+ cleanDenied(choices);
655
+ const interval = setInterval(() => {
656
+ synchronizePrivacy();
657
+ if (decision && decision.expires_at <= now())
658
+ deny(null);
659
+ if (configURL && now() - lastCheck >= config.recheck_after_seconds * 1000)
660
+ void controller.recheck();
661
+ }, 1000);
662
+ if (configURL)
663
+ void Promise.resolve().then(async () => {
664
+ if (await controller.recheck())
665
+ recordInitialSignal();
666
+ });
667
+ else
668
+ void Promise.resolve().then(recordInitialSignal);
669
+ // Import only a verifiable refusal from the former Kit GA4 runtime. Acceptance never migrates.
670
+ if (!decision) {
671
+ try {
672
+ const raw = storage?.getItem(`rcooler.measurement-consent.v1.${config.policy.site}`) ?? "null";
673
+ const legacy = raw.length <= 16384 ? JSON.parse(raw) : null;
674
+ if (legacy?.allow === false &&
675
+ legacy.epoch === config.policy.epoch &&
676
+ Number.isSafeInteger(legacy.policy) &&
677
+ Number(legacy.policy) > 0 &&
678
+ config.policy.services.some((service) => service.kind === "ga4" && service.measurement_id === legacy.id)) {
679
+ void controller.decide(deniedChoices());
680
+ }
681
+ }
682
+ catch {
683
+ /* Invalid legacy storage grants nothing and does not suppress a fresh notice. */
684
+ }
685
+ }
686
+ return controller;
687
+ }
@@ -0,0 +1,7 @@
1
+ export * from "./types.js";
2
+ export * from "./regional.js";
3
+ export * from "./validation.js";
4
+ export * from "./headless.js";
5
+ export * from "./ui.js";
6
+ export * from "./integrations.js";
7
+ export * from "./initialize.js";