@cookieyes/core 0.4.0 → 0.6.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.d.ts CHANGED
@@ -1,710 +1,5 @@
1
- /**
2
- * The integration format — the shared contract between the consent engine and
3
- * every vendor preset (Google, Segment, Meta, …). It carries no vendor
4
- * knowledge; a preset in `@cookieyes/scripts` fills it in.
5
- *
6
- * Two plain axes describe every vendor:
7
- * - `load`: when the vendor starts — right away, or only after consent.
8
- * - `onRevoke`: what happens when consent is withdrawn — one of three modes.
9
- *
10
- * `onRevoke` is declarative (readable without running `setup`, so a debug view
11
- * or a version check can inspect it), and it's a discriminated union so the
12
- * compiler forces the matching handler — you can't declare `"silence"` with no
13
- * way to actually silence.
14
- */
15
- type Cleanup = () => void;
16
- type SilenceControl = {
17
- silence: () => void;
18
- resume: () => void;
19
- };
20
- /** What a vendor's `setup` receives from the engine. */
21
- type SetupCtx = {
22
- /** Is this integration's category currently committed-granted? */
23
- granted: () => boolean;
24
- /**
25
- * Subscribe to committed-consent changes; returns an unsubscribe function.
26
- * `keep` vendors (e.g. Google Consent Mode) use this to emit their own
27
- * updates on every change. The engine also releases these automatically when
28
- * the integration is torn down, so a vendor listener never outlives it.
29
- */
30
- onConsentChange: (fn: () => void) => () => void;
31
- /** Resolved region/regulation — for a vendor's US-state privacy switch. */
32
- region: RegionDecision;
33
- };
34
- type Base = {
35
- id: string;
36
- /**
37
- * The consent category (or categories) that gate this integration. Pass an
38
- * array to require more than one — combined with {@link Base.match}.
39
- */
40
- category: ConsentCategory | ConsentCategory[];
41
- /**
42
- * How to combine multiple categories: `"all"` (default) needs every one
43
- * granted; `"any"` needs at least one. Ignored for a single category.
44
- */
45
- match?: "all" | "any";
46
- /** Format version; an unknown version is refused (see {@link runIntegrations}). */
47
- version: number;
48
- /**
49
- * When to start. Note: `setup` always runs on a microtask, so `immediately`
50
- * is *very early* but not synchronous / same-tick. The truly-first-thing case
51
- * (Consent Mode's deny-default before any tag fires) is the server `<head>`
52
- * snippet's job, not the engine's.
53
- */
54
- load: "immediately" | "afterConsent";
55
- };
56
- type Integration = Base & ({
57
- onRevoke: "keep";
58
- setup: (ctx: SetupCtx) => void | Promise<void>;
59
- } | {
60
- onRevoke: "remove";
61
- setup: (ctx: SetupCtx) => Cleanup | Promise<Cleanup>;
62
- } | {
63
- onRevoke: "silence";
64
- setup: (ctx: SetupCtx) => SilenceControl | Promise<SilenceControl>;
65
- });
66
- /** The format version this engine understands. Bump on a breaking format change. */
67
- declare const INTEGRATION_FORMAT_VERSION = 1;
68
- /**
69
- * Warn when a vendor is configured on both sides — a new `integrations` preset
70
- * whose id matches a deprecated `builtInIntegrations` vendor. Both would run,
71
- * which for a tracker means double-counted events (the DEVP-38 double-pixel).
72
- * Preset ids are the vendor's canonical name (`"segment"`, `"meta"`, …), which
73
- * is exactly the built-in vendor name, so the match is a plain id === vendor.
74
- */
75
- declare function warnOverlappingVendors(integrationIds: string[], builtInVendors: string[]): void;
76
- /**
77
- * Warn when an `afterConsent` integration is gated on a category that isn't in
78
- * the configured taxonomy — otherwise it waits for consent that can never be
79
- * granted and silently never loads. A common trap with a custom `categories`
80
- * list plus a preset left on its default category (e.g. `segment()` → "analytics").
81
- * `immediately` integrations aren't gated by category, so they're not checked.
82
- */
83
- declare function warnUnknownCategories(integrations: Integration[], knownCategoryIds: string[]): void;
84
- /** Live status of one integration — read by the debug/self-check view. */
85
- type IntegrationStatus = "idle" | "loading" | "active" | "silenced" | "removed" | "error";
86
- /** What the engine needs from the consent runtime — framework-agnostic. */
87
- type IntegrationHost = {
88
- /** Committed-granted state for a category (never the unsaved toggle). */
89
- granted: (category: ConsentCategory) => boolean;
90
- /** Subscribe to committed-consent changes; returns unsubscribe. */
91
- subscribe: (fn: () => void) => () => void;
92
- region: RegionDecision;
93
- };
94
- /** One row for a debug view: an integration's config plus its live status. */
95
- type IntegrationDebugInfo = {
96
- id: string;
97
- category: ConsentCategory | ConsentCategory[];
98
- load: "immediately" | "afterConsent";
99
- onRevoke: "keep" | "remove" | "silence";
100
- status: IntegrationStatus;
101
- };
102
- type IntegrationRunner = {
103
- /** Current status per integration id — the debug/self-check view reads this. */
104
- status: () => Record<string, IntegrationStatus>;
105
- /**
106
- * Config + live status for every registered integration, in order — the data
107
- * for a debug view (e.g. `console.table(runner.list())`).
108
- */
109
- list: () => IntegrationDebugInfo[];
110
- /**
111
- * Tear the runner down: stop reconciling, release every vendor's
112
- * consent-change listener, and undo each loaded vendor — `remove` runs its
113
- * cleanup, `silence` is silenced. `keep` vendors' scripts stay (that's the
114
- * mode), but their listeners are still released. Safe to call more than once.
115
- */
116
- stop: () => void;
117
- };
118
- /**
119
- * Run a set of integrations against the consent runtime. Reconciles each one on
120
- * load and on every committed-consent change:
121
- * - not loaded → load it (immediately, or once its category is granted)
122
- * - `keep` → nothing on revoke (the vendor manages its own update)
123
- * - `remove` → run cleanup on revoke; re-load on re-grant
124
- * - `silence` → call `silence()` on revoke; `resume()` on re-grant
125
- *
126
- * `setup` may be async and may fail; a failure marks the integration `error`
127
- * and is retried on the next trigger (never loops on its own). Nothing here
128
- * throws into the host.
129
- */
130
- declare function runIntegrations(integrations: Integration[], host: IntegrationHost): IntegrationRunner;
131
-
132
- type NetworkBlockerRule = {
133
- id: string;
134
- domain: string;
135
- pathIncludes?: string | undefined;
136
- methods?: string[] | undefined;
137
- category: ConsentCategory;
138
- };
139
- type BlockedRequestInfo = {
140
- rule: NetworkBlockerRule;
141
- url: string;
142
- method: string;
143
- };
144
- type NetworkBlockerConfig = {
145
- rules: NetworkBlockerRule[];
146
- onRequestBlocked?: ((info: BlockedRequestInfo) => void) | undefined;
147
- logBlockedRequests?: boolean | undefined;
148
- };
149
- type ConsentChecker = (category: ConsentCategory) => boolean;
150
- declare function installNetworkBlocker(config: NetworkBlockerConfig, hasConsent: ConsentChecker): () => void;
151
- declare function uninstallNetworkBlocker(): void;
152
-
153
- /**
154
- * A tool that can be stopped (and optionally resumed) at runtime when consent
155
- * for its category changes — no page reload needed. `stop()` is called when the
156
- * category is revoked; `resume()` (if provided) when it's re-granted.
157
- *
158
- * If `stop()` throws, that tool is treated as "couldn't be stopped cleanly" and
159
- * falls back to the reload notice for that one tool — it never breaks the page.
160
- */
161
- type StopHandler = {
162
- id: string;
163
- category: ConsentCategory;
164
- stop: () => void;
165
- resume?: (() => void) | undefined;
166
- };
167
- /**
168
- * A tool with no known clean runtime stop — revoking its category can only be
169
- * fully applied by reloading the page. Registering one means "if this category
170
- * is revoked, show the visitor the reload notice."
171
- */
172
- type ReloadOnlyHandler = {
173
- id: string;
174
- category: ConsentCategory;
175
- needsReload: true;
176
- };
177
- type AnyStopHandler = StopHandler | ReloadOnlyHandler;
178
- /**
179
- * Built-in, first-party integrations. Each maps to either a clean stop-handler
180
- * or a reload-only marker (see the audit in the README).
181
- *
182
- * Note: Google Analytics 4 and Google Tag Manager are **not** listed here.
183
- * They're governed by Google Consent Mode v2, which the SDK broadcasts
184
- * automatically whenever a `dataLayer` is present (see google-consent-mode.ts)
185
- * — on load and on every consent change, derived from each category's `gcm`
186
- * mapping. So you don't register them as integrations; just add the standard
187
- * Consent Mode default snippet and the SDK owns the updates.
188
- *
189
- * VERIFIED clean-stop vendors (documented, stable runtime opt-out):
190
- * - `meta` — `fbq('consent','revoke'|'grant')`, Meta's official consent API.
191
- *
192
- * The rest have no confident, documented runtime stop, so they're modelled as
193
- * reload-only (Story 1's honest answer). Upgrading any of them to a clean-stop
194
- * later is a one-line change here once a real API is confirmed.
195
- */
196
- type BuiltInIntegration = {
197
- vendor: "meta";
198
- category?: ConsentCategory | undefined;
199
- } | {
200
- vendor: "tiktok";
201
- category?: ConsentCategory | undefined;
202
- } | {
203
- vendor: "linkedin";
204
- category?: ConsentCategory | undefined;
205
- } | {
206
- vendor: "hotjar";
207
- category?: ConsentCategory | undefined;
208
- } | {
209
- vendor: "segment";
210
- category?: ConsentCategory | undefined;
211
- };
212
- declare function resolveBuiltInIntegration(cfg: BuiltInIntegration): AnyStopHandler;
213
- declare function registerStopHandler(handler: AnyStopHandler): void;
214
- /** Test-only: reset registry + transition state between cases. */
215
- declare function _clearStopHandlers(): void;
216
-
217
- /**
218
- * A consent category id. The five built-in ids are offered for autocomplete,
219
- * but any string is valid — customers can define their own taxonomy via
220
- * `categories` (see {@link CategoryDef}).
221
- */
222
- type ConsentCategory = "necessary" | "functional" | "analytics" | "performance" | "advertisement" | (string & {});
223
- type Regulation = "GDPR" | "CCPA" | "DEFAULT";
224
- /** Display text for one consent category. */
225
- type CategoryText = {
226
- label: string;
227
- description: string;
228
- };
229
- type TranslationMap = {
230
- bannerTitle: string;
231
- bannerDescription: string;
232
- acceptAll: string;
233
- rejectAll: string;
234
- managePreferences: string;
235
- savePreferences: string;
236
- doNotSell: string;
237
- ccpaDescription: string;
238
- accept: string;
239
- poweredBy: string;
240
- preferencesTitle: string;
241
- preferencesIntro: string;
242
- categories: {
243
- necessary: CategoryText;
244
- functional: CategoryText;
245
- analytics: CategoryText;
246
- performance: CategoryText;
247
- advertisement: CategoryText;
248
- } & Record<string, CategoryText>;
249
- optOut: {
250
- title: string;
251
- description: string;
252
- cancel: string;
253
- successText: string;
254
- successCountdown: string;
255
- };
256
- reloadNotice: {
257
- message: string;
258
- reloadButton: string;
259
- dismissButton: string;
260
- };
261
- };
262
- /** A subset of TranslationMap — lets a customer override just a few strings. */
263
- type DeepPartial<T> = T extends object ? {
264
- [K in keyof T]?: DeepPartial<T[K]>;
265
- } : T;
266
- type PartialTranslations = DeepPartial<TranslationMap>;
267
- /** Reading direction of a language. */
268
- type TextDirection = "ltr" | "rtl";
269
- /** The active language, its reading direction, and the languages currently loaded. */
270
- type LanguageInfo = {
271
- language: string;
272
- direction: TextDirection;
273
- languages: string[];
274
- };
275
- /** Returns the visitor's region synchronously, e.g. "DE" or "US-CA" (or undefined). */
276
- type RegionDetector = () => string | undefined;
277
- /** Optional geo-detection: pick the banner's regulation from the visitor's region. */
278
- type RegionConfig = {
279
- /** Return the visitor's region synchronously — e.g. from a hosting header you read. */
280
- detect?: RegionDetector | undefined;
281
- /** Which regulation each region maps to (you own this). Matched most-specific first: "US-CA" then "US". */
282
- map?: Record<string, Regulation> | undefined;
283
- /** Honour the browser's GPC "do not sell/share" signal (a CCPA opt-out). Default `true`. */
284
- honorGpc?: boolean | undefined;
285
- /** Regulation to apply when the region is unknown or detection fails. Default `"GDPR"`. */
286
- strictest?: Regulation | undefined;
287
- /** Log the region decision to the console at setup (for local debugging). Default `false`. */
288
- debug?: boolean | undefined;
289
- };
290
- /** How the active regulation was decided. */
291
- type RegionSource = "manual" | "detected" | "strictest";
292
- /** The outcome of geo-detection — the region seen and the regulation chosen. */
293
- type RegionDecision = {
294
- region: string | undefined;
295
- regulation: Regulation;
296
- source: RegionSource;
297
- confidence: "high" | "low";
298
- };
299
- type ThemeConfig = {
300
- primaryColor?: string | undefined;
301
- backgroundColor?: string | undefined;
302
- textColor?: string | undefined;
303
- mutedTextColor?: string | undefined;
304
- borderColor?: string | undefined;
305
- borderRadius?: string | undefined;
306
- fontFamily?: string | undefined;
307
- buttonVariant?: "filled" | "outlined" | undefined;
308
- widgetPosition?: "bottom-right" | "bottom-left" | undefined;
309
- };
310
- type ScriptEntry = {
311
- id: string;
312
- src: string;
313
- category: ConsentCategory;
314
- strategy?: "afterConsent" | "lazyOnce" | undefined;
315
- onLoad?: (() => void) | undefined;
316
- };
317
- type I18nConfig = {
318
- /** Translations per language. Each may be partial — missing text falls back to English. */
319
- messages?: Record<string, PartialTranslations> | undefined;
320
- locale?: string | undefined;
321
- detectBrowserLanguage?: boolean | undefined;
322
- /**
323
- * Called when a language is switched to that isn't already in `messages` —
324
- * return its translations (fetch them from your own URL, import them, etc.).
325
- * Lets you load languages on demand instead of bundling them all upfront.
326
- */
327
- loadLanguage?: ((tag: string) => PartialTranslations | Promise<PartialTranslations>) | undefined;
328
- };
329
- type ConsentConfig = {
330
- apiUrl?: string | undefined;
331
- apiKey?: string | undefined;
332
- backend?: ConsentBackend | undefined;
333
- regulation?: Regulation | undefined;
334
- /**
335
- * Define your own category taxonomy. Omit to get the built-in five
336
- * (necessary, functional, analytics, performance, advertisement) unchanged.
337
- * At least one category must be `{ required: true }`. Invalid configs fall
338
- * back to the built-in five with a console warning. See {@link CategoryDef}.
339
- */
340
- categories?: CategoryDef[] | undefined;
341
- theme?: ThemeConfig | undefined;
342
- colorScheme?: ColorScheme | undefined;
343
- reloadOnRevoke?: boolean | undefined;
344
- /**
345
- * How to combine multiple categories that map to the same Google Consent Mode
346
- * signal: `"any"` (default) grants the signal if any maps-and-granted; `"all"`
347
- * requires every mapping category. Only affects custom overlapping mappings.
348
- */
349
- googleConsentMatch?: "all" | "any" | undefined;
350
- /**
351
- * Built-in, first-party integrations to stop cleanly (no reload) when their
352
- * category is revoked — e.g. `{ vendor: "meta" }`. (Google Analytics/Tag
353
- * Manager are handled automatically via the Consent Mode broadcast — no entry
354
- * needed.) Integrations with no clean runtime stop fall back to the reload notice.
355
- */
356
- integrations?: BuiltInIntegration[] | undefined;
357
- /**
358
- * Your own scripts' stop instructions, for anything without a built-in
359
- * integration. A handler that can stop cleanly provides `stop()`; one that
360
- * can't should be registered as a reload-only handler instead so revoking it
361
- * shows the reload notice rather than silently continuing to track.
362
- */
363
- customStopHandlers?: StopHandler[] | undefined;
364
- /** Detected region (e.g. "US-CA"), recorded on the consent-log payload. */
365
- region?: string | undefined;
366
- /**
367
- * Internal — set by the runtime when a CCPA visitor arrives with the browser's
368
- * GPC "do not sell" signal on. Starts them opted out (non-required categories
369
- * off) until they explicitly choose otherwise, so nothing is shared first.
370
- */
371
- gpcOptOut?: boolean | undefined;
372
- onConsentReady?: ((state: ConsentSnapshot) => void) | undefined;
373
- onConsentUpdate?: ((state: ConsentSnapshot) => void) | undefined;
374
- };
375
- /**
376
- * Surfaced when a revoked tool has no clean runtime stop and can only be fully
377
- * applied by reloading. `required` is false once dismissed; `reasons` lists the
378
- * handler ids that triggered it (e.g. `["hotjar"]`).
379
- */
380
- type ReloadNoticeState = {
381
- required: boolean;
382
- reasons: string[];
383
- };
384
- type ConsentSnapshot = {
385
- consentId: string;
386
- hasActed: boolean;
387
- /** Category id → granted. Keys are the configured taxonomy's ids. */
388
- categories: Record<string, boolean>;
389
- regulation: Regulation;
390
- lastRenewed?: number | undefined;
391
- /**
392
- * Signature of the category taxonomy in effect when this consent was
393
- * recorded. Lets us (and the customer) tell what a returning visitor
394
- * actually agreed to, and drives re-request when the taxonomy changes.
395
- */
396
- taxonomyHash?: string | undefined;
397
- };
398
- type ConsentManager = ConsentSnapshot & {
399
- /**
400
- * Consent in effect — changes only on a real decision (accept / reject / save
401
- * / reset), never on a dialog toggle. Gate scripts/embeds on this. (`categories`
402
- * is the live value that drives the dialog checkboxes.)
403
- */
404
- committedCategories: Record<string, boolean>;
405
- acceptAll: () => void;
406
- rejectAll: () => void;
407
- acceptSelected: (categories: ConsentCategory[]) => void;
408
- updateCategory: (category: ConsentCategory, value: boolean) => void;
409
- savePreferences: () => void;
410
- resetConsent: () => void;
411
- showPreferences: () => void;
412
- hidePreferences: () => void;
413
- isPreferencesOpen: boolean;
414
- subscribe: (listener: (state: ConsentSnapshot) => void) => () => void;
415
- registerScript: (entry: ScriptEntry) => void;
416
- /** Current reload-notice state (see {@link ReloadNoticeState}). */
417
- reloadNotice: ReloadNoticeState;
418
- /** Dismiss the reload notice; it won't reappear until a new revoke needs one. */
419
- dismissReloadNotice: () => void;
420
- };
421
- /**
422
- * Shape of the JSON body POSTed to the customer's `apiUrl`
423
- * on every consent decision (Accept All / Reject All / Save Preferences).
424
- *
425
- * Customers building a TypeScript backend can import this type to get
426
- * full type safety on their request handler.
427
- */
428
- type ConsentPayload = {
429
- consentId: string;
430
- categories: Record<string, boolean>;
431
- regulation: Regulation;
432
- domain: string;
433
- /** Detected region when geo-detection is on (e.g. "US-CA"); omitted otherwise. */
434
- region?: string | undefined;
435
- };
436
- /**
437
- * Customer-implemented adapter that decides how a consent decision
438
- * reaches their backend. Provide this when `mode: "self-hosted"` and you
439
- * need full control over the request shape, headers, auth, transport,
440
- * batching, retries, etc. — anything you can't express with `apiUrl`.
441
- *
442
- * The SDK hands you a standardised `ConsentPayload`; you transform and
443
- * dispatch it however your backend expects.
444
- */
445
- interface ConsentBackend {
446
- persist(payload: ConsentPayload): Promise<void> | void;
447
- }
448
- /**
449
- * @deprecated Use `"cookie-only"` instead — identical behavior, clearer name.
450
- * `"offline"` still works but will be removed in a future release.
451
- */
452
- type DeprecatedOfflineMode = "offline";
453
- type ConsentRuntimeMode = "self-hosted" | "cookie-only" | DeprecatedOfflineMode;
454
- type ColorScheme = "light" | "dark" | "system";
455
- /**
456
- * Fields shared by every {@link CookieYesConfig} regardless of `mode`.
457
- * This is the one canonical config surface — both `@cookieyes/core` and
458
- * `@cookieyes/react` consume the exact same object, so a config is
459
- * copy-pasteable between them with zero edits.
460
- */
461
- type CookieYesConfigCommon = {
462
- /**
463
- * Which privacy regulation applies. Top-level and identical across every
464
- * package (replaces the builder's `.regulation()` and core's former
465
- * nested `overrides.regulation`).
466
- */
467
- regulation?: Regulation | undefined;
468
- /**
469
- * Optional geo-detection: choose the regulation from the visitor's region.
470
- * Fully optional — omit it and nothing changes. A manual `regulation` (above)
471
- * always wins over detection. See {@link RegionConfig}.
472
- */
473
- region?: RegionConfig | undefined;
474
- colorScheme?: ColorScheme | undefined;
475
- theme?: ThemeConfig | undefined;
476
- i18n?: I18nConfig | undefined;
477
- consentCategories?: ConsentCategory[] | undefined;
478
- /**
479
- * Define your own category taxonomy. Omit to get the built-in five
480
- * (necessary, functional, analytics, performance, advertisement) unchanged.
481
- * At least one category must be `{ required: true }`. Invalid configs fall
482
- * back to the built-in five with a console warning. See {@link CategoryDef}.
483
- */
484
- categories?: CategoryDef[] | undefined;
485
- networkBlocker?: NetworkBlockerConfig | undefined;
486
- reloadOnRevoke?: boolean | undefined;
487
- /**
488
- * How to combine multiple categories that map to the same Google Consent Mode
489
- * signal: `"any"` (default) or `"all"`. Only matters for a custom taxonomy
490
- * where more than one category maps to the same signal.
491
- */
492
- googleConsentMatch?: "all" | "any" | undefined;
493
- /**
494
- * Ready-made third-party integrations to gate behind consent — Segment, Meta,
495
- * Google, and more — using a preset from `@cookieyes/scripts`. Each preset
496
- * returns an {@link Integration}: it loads only once its category is granted
497
- * (or, for Google Consent Mode, loads immediately and denies by default), and
498
- * is removed or silenced on withdrawal.
499
- *
500
- * @example integrations: [segment({ writeKey: "..." })]
501
- */
502
- integrations?: Integration[] | undefined;
503
- /**
504
- * @deprecated Renamed from `integrations`. Built-in stop-handlers for a few
505
- * first-party vendors — e.g. `{ vendor: "meta" }` — stopped cleanly (no
506
- * reload) when their category is revoked. Prefer the new `integrations` field
507
- * with a preset from `@cookieyes/scripts`; this will be removed in a future
508
- * release.
509
- */
510
- builtInIntegrations?: BuiltInIntegration[] | undefined;
511
- /**
512
- * Your own scripts' stop instructions, for anything without a built-in
513
- * integration. A handler that can stop cleanly provides `stop()`; one that
514
- * can't should be registered as a reload-only handler instead so revoking it
515
- * shows the reload notice rather than silently continuing to track.
516
- */
517
- customStopHandlers?: StopHandler[] | undefined;
518
- /** Low-level: fires once, after the runtime's initial state is known (e.g. to conditionally load analytics on first load). For ongoing updates, use `consentStore.subscribeToConsentChanges` instead. */
519
- onConsentReady?: ((state: ConsentSnapshot) => void) | undefined;
520
- /** Low-level: fires on every saved consent change, for the lifetime of this config. If you need to subscribe/unsubscribe dynamically after mount, use `consentStore.getState().subscribeToConsentChanges` instead. */
521
- onConsentUpdate?: ((state: ConsentSnapshot) => void) | undefined;
522
- /**
523
- * @deprecated Set `regulation` at the top level instead. This nested form
524
- * still works and maps to the top-level field; if both are given, the
525
- * top-level `regulation` wins. Retained for back-compat and removed after
526
- * three release cycles, per the SDK deprecation policy.
527
- */
528
- overrides?: {
529
- regulation?: Regulation | undefined;
530
- } | undefined;
531
- };
532
- /**
533
- * Cookie-only mode — consent is stored client-side only; no backend keys are
534
- * permitted (they fail at the type level). `mode: "cookie-only"` is the
535
- * canonical value; `mode: "offline"` is a deprecated alias with identical
536
- * behavior that emits a one-time-per-page-load deprecation warning.
537
- */
538
- type CookieYesOfflineConfig = CookieYesConfigCommon & {
539
- mode: "cookie-only" | DeprecatedOfflineMode;
540
- };
541
- /** Self-hosted mode — consent decisions are persisted to your own backend. */
542
- type CookieYesSelfHostedConfig = CookieYesConfigCommon & {
543
- mode: "self-hosted";
544
- /** Endpoint the {@link ConsentPayload} is POSTed to. Canonical key. */
545
- apiUrl?: string | undefined;
546
- apiKey?: string | undefined;
547
- /** Custom persistence adapter — full control over transport/headers/retries. */
548
- backend?: ConsentBackend | undefined;
549
- /**
550
- * @deprecated Renamed to `apiUrl`. This alias still works and maps to
551
- * `apiUrl`; if both are given, `apiUrl` wins. Retained for back-compat and
552
- * removed after three release cycles, per the SDK deprecation policy.
553
- */
554
- backendURL?: string | undefined;
555
- };
556
- /**
557
- * The canonical configuration object for the CookieYes SDK, discriminated on
558
- * `mode`. Passed identically to `initCookieYes()` /
559
- * `getOrCreateConsentRuntime()` in `@cookieyes/core` and `initCookieYes()` in
560
- * `@cookieyes/react`.
561
- *
562
- * The discriminated union guarantees invalid combinations fail at compile time
563
- * — e.g. supplying `apiUrl`/`backend` under `mode: "cookie-only"` is a type error.
564
- */
565
- type CookieYesConfig = CookieYesOfflineConfig | CookieYesSelfHostedConfig;
566
- /**
567
- * @deprecated Renamed to {@link CookieYesConfig}. Retained as a type alias for
568
- * back-compat and removed after three release cycles, per the SDK deprecation
569
- * policy.
570
- */
571
- type ConsentRuntimeOptions = CookieYesConfig;
572
- type ConsentChangePayload = {
573
- allowedCategories: ConsentCategory[];
574
- deniedCategories: ConsentCategory[];
575
- };
576
- /** Which consent event to listen for. See {@link ConsentStore.on}. */
577
- type ConsentEventType = "save" | "change";
578
- type ConsentEventPayload = {
579
- /** The full committed consent map in effect when the event fired. */
580
- categories: Record<string, boolean>;
581
- /** Categories whose value differed from before. Empty on the initial replay. */
582
- changedCategories: ConsentCategory[];
583
- /**
584
- * `true` when this is the one-off replay a listener gets on attach (here's
585
- * the current state), `false` when the visitor actually just acted.
586
- */
587
- isInitial: boolean;
588
- };
589
- type ConsentEventListener = (payload: ConsentEventPayload) => void;
590
- /** Restrict a listener to a single category (fires only when it changes). */
591
- type ConsentEventOptions = {
592
- category?: ConsentCategory;
593
- };
594
- type ActiveUI = "banner" | "dialog" | null;
595
- type ConsentStoreState = ConsentSnapshot & {
596
- activeUI: ActiveUI;
597
- /** Live/working values — reflect in-progress dialog toggles. Drive checkboxes. */
598
- consents: Record<string, boolean>;
599
- /**
600
- * Consent in effect — changes only on a saved decision, not a toggle. Gate
601
- * scripts/embeds on this (or {@link ConsentStoreState.has}).
602
- */
603
- committedConsents: Record<string, boolean>;
604
- /** True when `category` is committed-granted (a saved decision), not just toggled. */
605
- has: (category: ConsentCategory) => boolean;
606
- saveConsents: (target: "all" | "necessary" | ConsentCategory[]) => Promise<void>;
607
- setConsent: (category: ConsentCategory, value: boolean) => void;
608
- /** Low-level: fires only on *saved* preference changes, not transient UI toggles — see `ConsentStore.subscribe` for the recommended, general-purpose subscription. */
609
- subscribeToConsentChanges: (listener: (payload: ConsentChangePayload) => void) => () => void;
610
- };
611
- /**
612
- * The recommended way to read consent state outside React. `subscribe` fires
613
- * on every state change (including transient UI toggles, e.g. a checkbox
614
- * flip before saving); for saved-changes-only, see
615
- * `ConsentStoreState.subscribeToConsentChanges`.
616
- */
617
- type ConsentStore = {
618
- subscribe: (listener: (state: ConsentStoreState) => void) => () => void;
619
- getState: () => ConsentStoreState;
620
- /** Text for the active language (English fills gaps). Swaps on `setLanguage`. */
621
- translations: TranslationMap;
622
- /** The active language, its reading direction, and the languages loaded. */
623
- getLanguageInfo: () => LanguageInfo;
624
- /**
625
- * Switch language live (no reload) — `subscribe` listeners fire so a custom UI
626
- * can re-render. Loads the language via `i18n.loadLanguage` if not bundled.
627
- */
628
- setLanguage: (tag: string) => Promise<void>;
629
- /** Customer-provided text for a category in the active language, if any. */
630
- getCategoryText: (id: string) => Partial<CategoryText> | undefined;
631
- /**
632
- * The category taxonomy in effect (custom list or the built-in five) — its
633
- * ids, which are `required`, etc. Use it to render categories in a custom UI
634
- * so it follows whatever taxonomy is configured.
635
- */
636
- categories: ResolvedCategories;
637
- /** How the active regulation was decided (region, source, confidence). */
638
- getRegion: () => RegionDecision;
639
- /**
640
- * React to consent decisions. `"save"` fires on every save (even an
641
- * unchanged re-confirm); `"change"` fires only when a category actually
642
- * differs — use it to (re)load a script without re-running on a re-confirm.
643
- * The listener fires once immediately with the current state
644
- * (`isInitial: true`). Pass `{ category }` to only hear about one category.
645
- * Returns an unsubscribe function.
646
- */
647
- on: (type: ConsentEventType, listener: ConsentEventListener, options?: ConsentEventOptions) => () => void;
648
- };
649
- type ConsentRuntime = {
650
- consentManager: ConsentManager;
651
- consentStore: ConsentStore;
652
- /** Config + live status for each script integration — data for a debug view. */
653
- getIntegrations: () => IntegrationDebugInfo[];
654
- };
655
-
656
- /**
657
- * Google Consent Mode v2 storage/signal types. A category can declare which of
658
- * these it represents via {@link CategoryDef.gcm}; the SDK then broadcasts them
659
- * (see google-consent-mode.ts). `security_storage` is always granted and is
660
- * handled by the broadcast itself, so it never needs to be mapped.
661
- */
662
- type GoogleConsentSignal = "ad_storage" | "ad_user_data" | "ad_personalization" | "analytics_storage" | "functionality_storage" | "personalization_storage" | "security_storage";
663
- /**
664
- * A single consent category. `id` is the stable key stored in the cookie and
665
- * used everywhere (banner, preferences, read APIs, integrations). Exactly one
666
- * category should be marked `required` — the always-on, non-optional one (like
667
- * the default "necessary") — flagged explicitly here, never inferred from a
668
- * name, so it survives full renaming.
669
- */
670
- type CategoryDef = {
671
- id: ConsentCategory;
672
- /** The always-on, non-optional category. At least one is required. */
673
- required?: boolean | undefined;
674
- /** Display label. Falls back to the translation for built-in ids. */
675
- label?: string | undefined;
676
- /** Display description. Falls back to the translation for built-in ids. */
677
- description?: string | undefined;
678
- /** Google Consent Mode signals this category governs (see {@link GoogleConsentSignal}). */
679
- gcm?: GoogleConsentSignal[] | undefined;
680
- };
681
- /**
682
- * The built-in five, used verbatim when a customer configures nothing. GCM
683
- * mapping mirrors production's `_ckySetGoogleConsentMode` (analytics →
684
- * analytics_storage, advertisement → the ad_* signals, functional →
685
- * functionality/personalization; performance maps to nothing; security_storage
686
- * is always granted by the broadcast).
687
- */
688
- declare const DEFAULT_CATEGORIES: CategoryDef[];
689
- type ResolvedCategories = {
690
- /** Ordered category definitions actually in effect. */
691
- list: CategoryDef[];
692
- /** Ordered ids (fast access). */
693
- ids: ConsentCategory[];
694
- /** Ids marked `required` (always granted, never toggleable). */
695
- requiredIds: Set<ConsentCategory>;
696
- /** Stable signature of this taxonomy; a change here re-requests consent. */
697
- taxonomyHash: string;
698
- /** True when the built-in five are in effect (configured or fallback). */
699
- isDefault: boolean;
700
- };
701
- /**
702
- * Resolve the category list from config. Returns the built-in five when nothing
703
- * is configured. On an invalid custom config (empty, duplicate/reserved ids, or
704
- * no `required` category) it warns and falls back to the built-in five, rather
705
- * than leaving the visitor a broken/empty or unprotected setup.
706
- */
707
- declare function resolveCategories(defs?: CategoryDef[]): ResolvedCategories;
1
+ import { C as ConsentRuntimeMode, R as Regulation, a as RegionConfig, b as ColorScheme, T as ThemeConfig, I as I18nConfig, c as CategoryDef, N as NetworkBlockerConfig, d as Integration, B as BuiltInIntegration, S as StopHandler, e as ConsentSnapshot, f as ConsentBackend, g as CookieYesConfig, h as ConsentEventType, i as ConsentEventListener, j as ConsentEventOptions, k as ResolvedCategories, G as GoogleConsentSignal, l as TranslationMap, m as TextDirection, P as PartialTranslations, n as IntegrationHost, o as IntegrationRunner, L as LanguageInfo, p as CategoryText, q as ConsentConfig, r as ConsentManager, s as ConsentCategory, t as RegionDecision, u as ConsentRuntime } from './categories-D1vlERV6.js';
2
+ export { A as ActiveUI, v as AnyStopHandler, w as BlockedRequestInfo, x as Cleanup, y as ConsentChangePayload, z as ConsentEventPayload, D as ConsentPayload, E as ConsentRuntimeOptions, F as ConsentStore, H as ConsentStoreState, J as CookieYesOfflineConfig, K as CookieYesSelfHostedConfig, M as DEFAULT_CATEGORIES, O as INTEGRATION_FORMAT_VERSION, Q as IntegrationDebugInfo, U as IntegrationStatus, V as NetworkBlockerRule, W as RegionDetector, X as RegionSource, Y as ReloadNoticeState, Z as ReloadOnlyHandler, _ as ScriptEntry, $ as SetupCtx, a0 as SilenceControl, a1 as _clearStopHandlers, a2 as installNetworkBlocker, a3 as registerNetworkBlocker, a4 as registerStopHandler, a5 as resolveBuiltInIntegration, a6 as resolveCategories, a7 as runIntegrations, a8 as uninstallNetworkBlocker, a9 as warnOverlappingVendors, aa as warnUnknownCategories } from './categories-D1vlERV6.js';
708
3
 
709
4
  /**
710
5
  * The canonical config with every deprecated alias already collapsed into its
@@ -721,7 +16,6 @@ type _NormalizedConfig = {
721
16
  colorScheme?: ColorScheme | undefined;
722
17
  theme?: ThemeConfig | undefined;
723
18
  i18n?: I18nConfig | undefined;
724
- consentCategories?: ConsentCategory[] | undefined;
725
19
  categories?: CategoryDef[] | undefined;
726
20
  networkBlocker?: NetworkBlockerConfig | undefined;
727
21
  reloadOnRevoke?: boolean | undefined;
@@ -777,6 +71,8 @@ declare function generateConsentId(): string;
777
71
  * One-time-per-page-load console warning for `mode: "offline"`.
778
72
  * Both @cookieyes/core and @cookieyes/react call this so the wording and the
779
73
  * "once" behavior stay identical no matter which package reads the setting.
74
+ *
75
+ * No-op in a production bundle; see the note at the top of this file.
780
76
  */
781
77
  declare function _warnOfflineModeDeprecated(): void;
782
78
  /** @internal test-only — resets the one-time warning guard between test cases. */
@@ -785,6 +81,8 @@ declare function _resetOfflineModeWarning(): void;
785
81
  * One-time-per-page-load console warning for the deprecated `builtInIntegrations`
786
82
  * config field (formerly `integrations`). Both packages call this so the wording
787
83
  * and the "once" behavior stay identical.
84
+ *
85
+ * No-op in a production bundle; see the note at the top of this file.
788
86
  */
789
87
  declare function _warnBuiltInIntegrationsDeprecated(): void;
790
88
  /** @internal test-only — resets the one-time warning guard between test cases. */
@@ -851,6 +149,30 @@ declare function pickLanguage(i18n?: I18nConfig): string;
851
149
  /** Full translations for the resolved starting language, English filling any gaps. */
852
150
  declare function resolveTranslations(i18n?: I18nConfig): TranslationMap;
853
151
 
152
+ /**
153
+ * Load the integration runner on demand.
154
+ *
155
+ * The runner is the largest single subsystem in `@cookieyes/core` — 1.2 KB of
156
+ * gzip, measured — and it does nothing at all unless `integrations` is
157
+ * configured, which most consumers never do. `integrations.ts` is a separate
158
+ * build entry (see `sdk/core/rollup.config.mjs`) so that this stays a real
159
+ * `import()` in the published output rather than being flattened back into the
160
+ * main chunk, and a bundler can therefore keep it out of the initial download.
161
+ *
162
+ * This indirection exists so that `@cookieyes/react` does not need a static
163
+ * import of `runIntegrations` to do the same thing. A dynamic
164
+ * `import("@cookieyes/core")` from the adapter would pull the whole barrel and
165
+ * defeat the split; a static import of *this* function costs a few bytes and
166
+ * leaves the heavy module behind one `import()` that only core knows about.
167
+ *
168
+ * @internal — consumed by framework adapters, not part of the public API.
169
+ */
170
+ declare function _loadIntegrations(): Promise<{
171
+ runIntegrations: (list: Integration[], host: IntegrationHost) => IntegrationRunner;
172
+ warnOverlappingVendors: (ids: string[], vendors: string[]) => void;
173
+ warnUnknownCategories: (list: Integration[], known: string[]) => void;
174
+ }>;
175
+
854
176
  type LanguageController = {
855
177
  /** Text for the active language (English fills any gaps). */
856
178
  getTranslations: () => TranslationMap;
@@ -876,6 +198,34 @@ declare function createLanguageController(i18n: I18nConfig | undefined, onChange
876
198
 
877
199
  declare function createConsentManager(config: ConsentConfig): ConsentManager;
878
200
 
201
+ /** @internal Test-only — empties the slot so one test cannot leak into the next. */
202
+ declare function _clearNetworkBlockerInstaller(): void;
203
+ /** True when a customer has registered the blocker. @internal */
204
+ declare function _hasNetworkBlockerInstaller(): boolean;
205
+ /**
206
+ * Install the registered blocker, or complain loudly that there isn't one.
207
+ *
208
+ * The failure mode this guards against is the dangerous one: a customer who
209
+ * configured `networkBlocker` before this change and upgrades would otherwise
210
+ * find their requests silently no longer blocked, which on a consent product is
211
+ * worse than a crash. `console.error` rather than `throw` because taking the
212
+ * page down is not proportionate, and the message names the exact two lines
213
+ * needed to fix it.
214
+ *
215
+ * @internal — consumed by core's runtime and by framework adapters.
216
+ */
217
+ declare function _installRegisteredNetworkBlocker(config: NetworkBlockerConfig, hasConsent: (category: ConsentCategory) => boolean): void;
218
+ /**
219
+ * Restore the browser's networking functions, if the blocker was installed.
220
+ *
221
+ * Idempotent, and a no-op when nothing was installed — which is why the runtime
222
+ * can call it unconditionally on reset without dragging the blocker back into
223
+ * the bundle.
224
+ *
225
+ * @internal
226
+ */
227
+ declare function _uninstallRegisteredNetworkBlocker(): void;
228
+
879
229
  /** Anything with a header getter — a `Headers` object, Next's `headers()`, etc. */
880
230
  type HeaderSource = {
881
231
  get(name: string): string | null | undefined;
@@ -990,5 +340,5 @@ declare function readServerConsent(cookieHeader: string, options?: ServerConsent
990
340
  */
991
341
  declare const CORE_VERSION = "0.0.0-dev";
992
342
 
993
- export { CORE_VERSION, DEFAULT_CATEGORIES, INTEGRATION_FORMAT_VERSION, _clearScriptRegistry, _clearStopHandlers, _logRegionDecision, _normalizeConfig, _resetBuiltInIntegrationsWarning, _resetOfflineModeWarning, _warnBuiltInIntegrationsDeprecated, _warnOfflineModeDeprecated, broadcastGoogleConsent, computeGoogleConsent, createConsentEmitter, createConsentManager, createLanguageController, en as defaultTranslations, generateConsentId, getOrCreateConsentRuntime, getTextDirection, initCookieYes, installNetworkBlocker, mergeTranslations, parseCookie, parseCookieHeader, pickLanguage, primaryOf, readGpc, readServerConsent, regionFromHeaders, registerStopHandler, resetConsentRuntime, resolveBuiltInIntegration, resolveCategories, resolveRegion, resolveTranslations, runIntegrations, serializeCookie, uninstallNetworkBlocker, warnOverlappingVendors, warnUnknownCategories };
994
- export type { ActiveUI, AnyStopHandler, BlockedRequestInfo, BuiltInIntegration, CategoryDef, CategoryText, Cleanup, ColorScheme, ConsentBackend, ConsentCategory, ConsentChangePayload, ConsentConfig, ConsentEmitter, ConsentEventListener, ConsentEventOptions, ConsentEventPayload, ConsentEventType, ConsentManager, ConsentPayload, ConsentRuntime, ConsentRuntimeMode, ConsentRuntimeOptions, ConsentSnapshot, ConsentStore, ConsentStoreState, CookieYesConfig, CookieYesOfflineConfig, CookieYesSelfHostedConfig, GoogleConsentSignal, HeaderSource, I18nConfig, Integration, IntegrationDebugInfo, IntegrationHost, IntegrationRunner, IntegrationStatus, LanguageController, LanguageInfo, NetworkBlockerConfig, NetworkBlockerRule, PartialTranslations, RegionConfig, RegionDecision, RegionDetector, RegionSource, Regulation, ReloadNoticeState, ReloadOnlyHandler, ResolvedCategories, ScriptEntry, ServerConsentOptions, SetupCtx, SilenceControl, StopHandler, TextDirection, ThemeConfig, TranslationMap, _NormalizedConfig };
343
+ export { BuiltInIntegration, CORE_VERSION, CategoryDef, CategoryText, ColorScheme, ConsentBackend, ConsentCategory, ConsentConfig, ConsentEventListener, ConsentEventOptions, ConsentEventType, ConsentManager, ConsentRuntime, ConsentRuntimeMode, ConsentSnapshot, CookieYesConfig, GoogleConsentSignal, I18nConfig, Integration, IntegrationHost, IntegrationRunner, LanguageInfo, NetworkBlockerConfig, PartialTranslations, RegionConfig, RegionDecision, Regulation, ResolvedCategories, StopHandler, TextDirection, ThemeConfig, TranslationMap, _clearNetworkBlockerInstaller, _clearScriptRegistry, _hasNetworkBlockerInstaller, _installRegisteredNetworkBlocker, _loadIntegrations, _logRegionDecision, _normalizeConfig, _resetBuiltInIntegrationsWarning, _resetOfflineModeWarning, _uninstallRegisteredNetworkBlocker, _warnBuiltInIntegrationsDeprecated, _warnOfflineModeDeprecated, broadcastGoogleConsent, computeGoogleConsent, createConsentEmitter, createConsentManager, createLanguageController, en as defaultTranslations, generateConsentId, getOrCreateConsentRuntime, getTextDirection, initCookieYes, mergeTranslations, parseCookie, parseCookieHeader, pickLanguage, primaryOf, readGpc, readServerConsent, regionFromHeaders, resetConsentRuntime, resolveRegion, resolveTranslations, serializeCookie };
344
+ export type { ConsentEmitter, HeaderSource, LanguageController, ServerConsentOptions, _NormalizedConfig };