@jini-ai/cookie-consent 0.6.19 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  Cookie consent with no dependencies and no vendor code. It has five parts:
4
4
 
5
5
  - a consent-state contract that any banner can drive,
6
- - a small browser client (`dist/client.min.js`),
6
+ - a state/context browser client (`dist/client.min.js`) and optional features asset (`dist/extensions.min.js`),
7
7
  - a banner renderer that returns plain strings, with owner CSS,
8
8
  - web-standard receipts (`Request` → `Response`),
9
9
  - open plugin slots.
@@ -18,17 +18,17 @@ npm install @jini-ai/cookie-consent
18
18
 
19
19
  ## Standalone use
20
20
 
21
- Render on the server (or at build time), serve the client and mount the receipt endpoint.
21
+ Render on the server (or at build time), serve both browser assets and mount the receipt endpoint.
22
22
 
23
23
  ```ts
24
24
  import { renderBanner } from '@jini-ai/cookie-consent/render';
25
25
 
26
26
  const { head, body, problems } = renderBanner(
27
27
  { mode: 'jini', client: { contract: 1, policy: '2026-10-26', regionMode: 'auto' }, copy: { privacyPolicyUrl: '/privacy' } },
28
- { clientSrc: '/consent/client.min.js', evidence: { mode: 'durable', endpoint: '/_consent' } },
28
+ { clientSrc: '/consent/client.min.js', extensionSrc: '/consent/extensions.min.js', evidence: { mode: 'durable', endpoint: '/_consent' } },
29
29
  );
30
30
  // Put `head` in <head> and `body` at the end of <body>. Serve
31
- // node_modules/@jini-ai/cookie-consent/dist/client.min.js at /consent/client.min.js.
31
+ // Serve the package assets client.min.js and extensions.min.js at those two URLs.
32
32
  ```
33
33
 
34
34
  ```ts
@@ -42,20 +42,40 @@ const response = await handleReceipt({ request, ports: { store, policy: () => '2
42
42
 
43
43
  - **Modes:**
44
44
  - `jini` is the built-in banner.
45
- - `headless` is your own banner. It drives `window.jiniConsent` (`get`, `set`, `subscribe`, `open`, `setOpen`).
46
- - `off` renders the client config without banner UI and permits anonymous analytics only. It writes no consent cookie or receipt and ignores earlier choices. Raw inert tags stay blocked.
45
+ - `headless` is your own banner. It drives `window.jiniConsent` (`get`, `allows`, `set`, `subscribe`, `open`, `setOpen`).
46
+ - A host with consent off omits config and both assets, with no consent requests, cookie reads or policy reads per page. `renderScriptAssets({ scripts })` supplies ordinary script tags. The direct `createCookieConsent` API retains its older `banner: 'off'` anonymous mode for explicit library consumers; hosts need not boot that mode.
47
47
  - **Evidence:**
48
48
  - `durable`: a grant only takes effect once the server has stored its receipt.
49
49
  - `local`: the record stays in the browser (static export, Electron, `file:`) and is labelled as browser-only.
50
50
  - Denial applies before any network call. Global Privacy Control or DNT turns off analytics and marketing (including anonymous analytics), and nothing can turn them back on. The receipt response never sets a cookie.
51
51
  - Choices use `jini_choices`, separate from the older CMS engine's HttpOnly `jini_consent`. Old cookies are never imported as consent; returning visitors choose once under this engine. Hosts may expire the old host-only cookie when switching engines.
52
- - **Server-side gate:** `readConsent({ cookieHeader, policy, regionMode }, { secGpc, dnt, anonymous })` from `./server`. Bind `anonymous: true` when the banner is off. The historical `gpc` state/receipt field records the effective GPC-or-DNT opt-out.
52
+ - **Server-side gate:** `readConsent({ cookieHeader, policy, regionMode }, { secGpc, dnt, anonymous })` from `./server`. Hosts bypass consent reads when disabled; explicit anonymous consumers may pass `anonymous: true`. The historical `gpc` state/receipt field records the effective GPC-or-DNT opt-out.
53
53
  - **Inert tags:**
54
54
  - `<script type="text/plain" data-consent-category="analytics">` runs only once its category is allowed.
55
55
  - `<iframe data-consent-category data-src>` loads only once its category is allowed.
56
56
 
57
57
  A runnable example is in `examples/cookie-consent-standalone` (it includes a slow fake vendor that shows queueing).
58
58
 
59
+ ## Declared scripts and document slots
60
+
61
+ Declarations carry URLs, never script bodies:
62
+
63
+ ```ts
64
+ import type { DeclaredScript } from '@jini-ai/cookie-consent';
65
+
66
+ const scripts = [
67
+ { src: '/scripts/menu.js' },
68
+ { src: '/scripts/stats.js', consent: ['analytics'] },
69
+ { src: 'https://example.com/pixel.js', consent: ['analytics', 'marketing'] },
70
+ ] satisfies readonly DeclaredScript[];
71
+ ```
72
+
73
+ Pass them as `client.scripts`. Omitted `consent` runs automatically, including external URLs, with no warning. Several categories mean all must be effectively allowed: `api.allows({ consent: ['analytics', 'marketing'] })`. Grants wait for durable receipts; scripts start in eligible array order once. Withdrawal cancels pending starts and reloads when arbitrary executed code cannot be stopped.
74
+
75
+ A document renderer emits `head` and `body` during construction. No consent code scans or rewrites finished pages or stored HTML. Existing unmanaged executable content remains unmanaged and must be disclosed in admin; full-document themes need an authored runtime slot before adoption. Provider-authored inert frames/templates remain supported.
76
+
77
+ Shared cached documents contain declarations and policy snapshots, never visitor choices or region. A live host can include `context: '/_consent/context'` in its page config. Before reading cookies, the core requests that URL once with `no-store`; the host reads published settings only and responds with `{ enabled, policy, regionMode }`, resolving trusted region and setting the region cookie there. A changed policy reloads the document before installing consent. Static exports omit `context`, use `evidence: { mode: 'local' }`, and explicitly copy local declared URLs and both runtime assets; JSON URLs are invisible to an HTML asset crawl.
78
+
59
79
  ## Plugin slots
60
80
 
61
81
  The slot set is open. Each kind is a string. A contribution for a kind that no slot defines yet waits until `defineSlot` arrives. Every register or inject call takes `(required, optional)` objects.
@@ -72,6 +92,7 @@ The slot set is open. Each kind is a string. A contribution for a kind that no s
72
92
  In off mode `allowed.analytics` is always `false`; `state.analyticsLevel` is `anonymous` (or `none` under GPC/DNT). Adapters must read `state.analyticsLevel` (`none` | `anonymous` | `full`). Only adapters declaring `supportsAnonymous: true` can run in off mode. Anonymous means no cookies/localStorage/sessionStorage created, no cross-page identifier, person profiles, IP geolocation, replay or form-input capture. Adapters remove their own leftover identity at anonymous/none levels; off-mode adapters may be imported for this cleanup without a grant. Hosts must pass the server decision to collectors; a browser payload never sets its own level.
73
93
 
74
94
  If `revoke()` returns false (or is missing), the page reloads so that it ends up clean.
95
+ - **Banner/CMP bridges** (`kind: 'consent-bridge'`) provide `mount({ api, doc })`, optionally returning a disposer, or a `src` module. The built-in banner uses this same lifecycle. An outside CMP maps its events into `api.set`; receipt and privacy-signal restrictions still apply.
75
96
  - **Server region resolvers** (`kind: 'region-resolver'`). There are two forms:
76
97
  - Live: `resolve({ request })`.
77
98
  - Data only: `{ header, usValues }`. `REGION_SLOT` turns this into a header resolver.
@@ -98,4 +119,4 @@ An engine parity block is always added after the owner's CSS. `compileConsentCss
98
119
 
99
120
  ## Size
100
121
 
101
- `dist/client.min.js` is about 4.4 KB gzipped, and that includes the built-in banner binding. The build fails above 4,608 bytes (`npm run build` prints the size). The design target was about 3 KB. The gate is set to stop further growth, not to bless the current size.
122
+ `dist/client.min.js` owns state and the live context request; `dist/extensions.min.js` owns the banner binding, declared-script loading and bridges. Each asset retains the 4,608-byte gzip ceiling, and the build prints both measured sizes. At this revision they are approximately 4.5 KB and 1.8 KB gzipped. Serve both for the built-in banner or declarations; a headless ESM host may import only the pieces it uses.
package/dist/banner.css CHANGED
@@ -23,6 +23,7 @@
23
23
  #jini-consent:where([data-placement="top-bar"]){inset:1rem 1rem auto}
24
24
  .jini-consent-reopen{display:none;position:fixed;left:1rem;bottom:1rem;z-index:2147483646;padding:.5rem 1rem;border:1px solid var(--jini-border,#0002);border-radius:999px;background:var(--jini-surface,Canvas);color:var(--jini-text,CanvasText);font-size:12.5px;box-shadow:0 1px 2px #0000000f,0 8px 20px #0000001f}
25
25
  html[data-consent="set"]:not([data-consent-open]) .jini-consent-reopen{display:inline-flex}
26
+ .jini-consent-settings{display:inline-block;margin:1rem;padding:.5rem .75rem;color:var(--jini-text,var(--fg,CanvasText));background:var(--jini-surface,var(--bg,Canvas));border:1px solid var(--jini-border,var(--border,currentColor));border-radius:var(--jini-radius,.5rem);font:inherit;text-decoration:underline}.jini-consent-settings:focus-visible{outline:2px solid currentColor;outline-offset:2px}
26
27
  @media(max-width:640px){.jini-consent{inset:auto 0 0;padding:12px 16px calc(12px + env(safe-area-inset-bottom,0px));border-radius:var(--consent-radius) var(--consent-radius) 0 0}}
27
28
  @media(prefers-reduced-motion:reduce){.jini-consent,.jini-consent *{transition:none!important;animation:none!important}}
28
29
 
@@ -0,0 +1,8 @@
1
+ /** UI and outside CMP bridges use the same state and receipt-enforcing API as the built-in banner. */
2
+ import { type ConsentBridge, type JiniConsentApi, type SlotKind } from '../contract.js';
3
+ export declare const BRIDGE_SLOT: SlotKind<ConsentBridge>;
4
+ export declare function bindBridges({ api, doc }: {
5
+ api: JiniConsentApi;
6
+ doc: Document;
7
+ }, _optional?: {}): void;
8
+ //# sourceMappingURL=bridges.d.ts.map
@@ -0,0 +1,49 @@
1
+ /** UI and outside CMP bridges use the same state and receipt-enforcing API as the built-in banner. */
2
+ import { BRIDGE_KIND } from '../contract.js';
3
+ export const BRIDGE_SLOT = {
4
+ kind: BRIDGE_KIND,
5
+ accept: ({ contribution }) => typeof contribution.mount === 'function' || typeof contribution.src === 'string'
6
+ ? contribution : 'mount() or module src needed',
7
+ };
8
+ function disposeBridge(entry) {
9
+ entry.disposed = true;
10
+ try {
11
+ entry.dispose?.();
12
+ }
13
+ catch { /* A broken bridge cannot block other mounts or consent. */ }
14
+ }
15
+ export function bindBridges({ api, doc }, _optional = {}) {
16
+ const active = new Map();
17
+ function sync(items) {
18
+ for (const [id, entry] of active) {
19
+ if (items.some(item => item.id === id))
20
+ continue;
21
+ disposeBridge(entry);
22
+ active.delete(id);
23
+ }
24
+ for (const bridge of items) {
25
+ if (active.has(bridge.id))
26
+ continue;
27
+ const held = { disposed: false, dispose: undefined };
28
+ active.set(bridge.id, held);
29
+ const mount = (loaded) => {
30
+ if (held.disposed)
31
+ return;
32
+ try {
33
+ const dispose = loaded.mount?.({ api, doc });
34
+ if (typeof dispose === 'function')
35
+ held.dispose = dispose;
36
+ }
37
+ catch { /* Isolate this contribution; the shared consent state stays authoritative. */ }
38
+ };
39
+ if (bridge.mount)
40
+ mount(bridge);
41
+ else
42
+ void import(/* @vite-ignore */ bridge.src).then(module => mount(module.default)).catch(() => undefined);
43
+ }
44
+ }
45
+ api.plugins.defineSlot({ slot: BRIDGE_SLOT });
46
+ api.plugins.subscribe({ kind: BRIDGE_KIND, listener: items => sync(items) });
47
+ sync(api.plugins.list({ kind: BRIDGE_KIND }));
48
+ }
49
+ //# sourceMappingURL=bridges.js.map
@@ -1,5 +1,3 @@
1
- /** @file DOM helpers for the browser client: cookies, storage purge, inert tags and the Jini banner binding.
2
- * The Jini banner is a client of the public API, exactly like an owner's own ("My own") banner. */
3
1
  import { type Choices, type ConsentState, type JiniConsentApi, type Optional, type StoragePrefixes } from '../contract.js';
4
2
  /** @complexity O(cookie header). Malformed escapes read as "no value", never throw. */
5
3
  export declare function readCookie(doc: Document, name: string): string | null;
@@ -30,4 +28,11 @@ export declare function bindBanner({ api, doc }: {
30
28
  api: JiniConsentApi;
31
29
  doc: Document;
32
30
  }): void;
31
+ /** Declared frame purposes share the script permission check. Withdrawal unloads first, then reloads.
32
+ * Only renderer-owned declarations are consumed; arbitrary authored frames are untouched.
33
+ * @complexity O(frames × declared purposes) per consent update; no polling or server reads. */
34
+ export declare function declaredFrames({ doc, reload }: {
35
+ doc: Document;
36
+ reload: () => void;
37
+ }, _optional?: {}): (state: ConsentState) => void;
33
38
  //# sourceMappingURL=dom.d.ts.map
@@ -1,5 +1,6 @@
1
1
  /** @file DOM helpers for the browser client: cookies, storage purge, inert tags and the Jini banner binding.
2
2
  * The Jini banner is a client of the public API, exactly like an owner's own ("My own") banner. */
3
+ import { allows } from '../contracts/scripts.js';
3
4
  import { OPEN_EVENT, OPTIONAL } from '../contract.js';
4
5
  const SKIP = ['type', 'data-src', 'data-type', 'data-consent-category'];
5
6
  // Not <html>: the client sets html[data-consent-open] while the banner shows, and every click's closest() would hit it.
@@ -138,4 +139,40 @@ export function bindBanner({ api, doc }) {
138
139
  syncInputs(root, api.get());
139
140
  show(api.get().status === 'pending');
140
141
  }
142
+ /** Declared frame purposes share the script permission check. Withdrawal unloads first, then reloads.
143
+ * Only renderer-owned declarations are consumed; arbitrary authored frames are untouched.
144
+ * @complexity O(frames × declared purposes) per consent update; no polling or server reads. */
145
+ export function declaredFrames({ doc, reload }, _optional = {}) {
146
+ const entries = [...doc.querySelectorAll('iframe[data-src][data-jini-consent]')]
147
+ .map(node => ({ node, consent: frameConsent(node), started: false }));
148
+ let withdrawn = false;
149
+ return state => {
150
+ if (withdrawn)
151
+ return;
152
+ const revoked = entries.filter(entry => entry.started && !allows({ state, consent: entry.consent }));
153
+ if (revoked.length) {
154
+ withdrawn = true;
155
+ revoked.forEach(entry => entry.node.removeAttribute('src'));
156
+ // The remote document may already have executed scripts; removing the frame is not full cleanup.
157
+ reload();
158
+ return;
159
+ }
160
+ entries.forEach(entry => {
161
+ if (entry.started || !allows({ state, consent: entry.consent }))
162
+ return;
163
+ entry.started = true;
164
+ entry.node.setAttribute('src', entry.node.dataset.src);
165
+ });
166
+ };
167
+ }
168
+ /** Malformed purpose data fails closed through the same unknown-purpose check. */
169
+ function frameConsent(node) {
170
+ try {
171
+ const consent = JSON.parse(node.dataset.jiniConsent);
172
+ if (Array.isArray(consent))
173
+ return consent;
174
+ }
175
+ catch { /* Invalid declarations stay inert. */ }
176
+ return ['invalid'];
177
+ }
141
178
  //# sourceMappingURL=dom.js.map
@@ -0,0 +1,14 @@
1
+ /** Optional declared assets and UI bridges install once, before or after the core READY event. */
2
+ import { type ClientConfig, type JiniConsentApi } from '../contract.js';
3
+ export declare function installFeatures({ api, doc, config, reload }: {
4
+ api: JiniConsentApi;
5
+ doc: Document;
6
+ config: ClientConfig;
7
+ reload: () => void;
8
+ }, { bindBanner }?: {
9
+ bindBanner?: ((required: {
10
+ api: JiniConsentApi;
11
+ doc: Document;
12
+ }) => void) | undefined;
13
+ }): void;
14
+ //# sourceMappingURL=features.d.ts.map
@@ -0,0 +1,34 @@
1
+ /** Optional declared assets and UI bridges install once, before or after the core READY event. */
2
+ import { BRIDGE_KIND } from '../contract.js';
3
+ import { bindBridges } from './bridges.js';
4
+ import { declaredScripts } from './scripts.js';
5
+ import { declaredFrames } from './dom.js';
6
+ const installed = Symbol.for('jini-consent:features');
7
+ export function installFeatures({ api, doc, config, reload }, { bindBanner } = {}) {
8
+ if (Object.prototype.hasOwnProperty.call(api, installed))
9
+ return;
10
+ Object.defineProperty(api, installed, { value: true });
11
+ const reconcile = declaredAssets({ doc, config, reload });
12
+ api.subscribe({ listener: reconcile });
13
+ reconcile(api.get());
14
+ bindBridges({ api, doc });
15
+ if (config.banner === 'jini' && bindBanner)
16
+ api.plugins.registerPlugin({ id: 'jini-banner', kind: BRIDGE_KIND, mount: bindBanner });
17
+ }
18
+ /** Both declaration owners finish their withdrawal cleanup before the shared document reload. */
19
+ function declaredAssets({ doc, config, reload }) {
20
+ let requested = false;
21
+ let reloaded = false;
22
+ const requestReload = () => { requested = true; };
23
+ const scripts = declaredScripts({ doc, scripts: config.scripts ?? [], reload: requestReload });
24
+ const frames = declaredFrames({ doc, reload: requestReload });
25
+ return state => {
26
+ frames(state);
27
+ scripts(state);
28
+ if (!requested || reloaded)
29
+ return;
30
+ reloaded = true;
31
+ reload();
32
+ };
33
+ }
34
+ //# sourceMappingURL=features.js.map
@@ -1,45 +1,11 @@
1
- /** @file Browser runtime (dist/client.min.js). It owns the cookie, the adapter lifecycle, inert tags and
2
- * receipts. Denial is applied before any network; a durable grant runs only once its receipt exists; a
3
- * response never sets a cookie, so a slow Accept can't overwrite a newer Reject. No polling, and no reload
4
- * unless something already ran that cannot be stopped (a raw inert script, or an adapter that can't revoke). */
5
- import { type ClientConfig, type ConsentAdapter, type Evidence, type JiniConsentApi, type PluginRegistry, type StoragePrefixes } from '../contract.js';
6
- export interface ClientPorts {
7
- doc: Document;
8
- fetch: typeof fetch;
9
- now: () => number;
10
- gpc: () => boolean;
11
- reload: () => void;
12
- importModule: (src: string) => Promise<{
13
- default: ConsentAdapter;
14
- }>;
15
- }
16
- export interface ClientOptions {
17
- plugins?: PluginRegistry;
18
- evidence?: Evidence | undefined;
19
- }
20
- /** @example createCookieConsent({ config, ports: browserPorts(window) }, { evidence: { mode: 'local' } }) */
21
- export declare function createCookieConsent({ config, ports }: {
22
- config: ClientConfig;
23
- ports: ClientPorts;
24
- }, options?: ClientOptions): JiniConsentApi;
25
- export declare function browserPorts(win: Window & typeof globalThis): ClientPorts;
26
- export interface BootOptions {
27
- ports?: ClientPorts;
28
- /** The Jini banner binding; only the client-jini.min.js build passes it, so headless pages never download it. */
29
- bindBanner?: (required: {
30
- api: JiniConsentApi;
31
- doc: Document;
32
- }) => void;
33
- }
34
- /** Reads #jini-consent-config, installs window.jiniConsent, drains and replaces the pre-boot queue.
35
- * A missing or broken config installs nothing, so nothing optional can run (fail closed). */
36
- export declare function boot(win?: Window & typeof globalThis, { ports, bindBanner }?: BootOptions): JiniConsentApi | undefined;
37
- /** Delete only the caller's storage prefixes; blocked localStorage is tolerated.
38
- * @example purgeStorage({ doc: document, storage: { cookies: ['vendor_'], local: ['vendor_'] } })
39
- * @complexity O(cookies + local keys), O(keys) temporary space; no new identity or network. */
40
- export declare function purgeStorage({ doc, storage }: {
41
- doc: Document;
42
- storage: StoragePrefixes;
43
- }, _optional?: {}): void;
44
- export { bindBanner, installOpeners } from './dom.js';
1
+ /** Full ESM client surface. The browser assets split optional feature delivery from core state. */
2
+ import type { JiniConsentApi } from '../contract.js';
3
+ import { createCookieConsent as createCore, type BootOptions } from './runtime.js';
4
+ export { browserPorts, purgeStorage, installOpeners, bindBanner } from './runtime.js';
5
+ export type { ClientPorts, ClientOptions, BootOptions } from './runtime.js';
6
+ export declare const createCookieConsent: typeof createCore;
7
+ export declare function boot(win?: Window & typeof globalThis, options?: BootOptions): JiniConsentApi | undefined;
8
+ export declare function bootWithContext({ win }: {
9
+ win: Window & typeof globalThis;
10
+ }, options?: BootOptions): Promise<JiniConsentApi | undefined>;
45
11
  //# sourceMappingURL=index.d.ts.map
@@ -1,225 +1,20 @@
1
- /** @file Browser runtime (dist/client.min.js). It owns the cookie, the adapter lifecycle, inert tags and
2
- * receipts. Denial is applied before any network; a durable grant runs only once its receipt exists; a
3
- * response never sets a cookie, so a slow Accept can't overwrite a newer Reject. No polling, and no reload
4
- * unless something already ran that cannot be stopped (a raw inert script, or an adapter that can't revoke). */
5
- import { ADAPTER_KIND, CONFIG_ID, CONSENT_COOKIE, OPEN_EVENT, OPTIONAL, READY_EVENT, REGION_COOKIE, STATE_EVENT } from '../contract.js';
6
- import { choicesFor, DAY_MS, effective, parseStored, RECEIPT_ID, regionFrom } from '../contracts/policy.js';
7
- import { ADAPTER_SLOT, createPluginRegistry } from '../contracts/plugins.js';
8
- import { activateInert, installOpeners, purge, readCookie, waiting, writeCookie } from './dom.js';
9
- const within = (p, ms) => Promise.race([p, new Promise(r => setTimeout(r, ms))]);
10
- const quiet = (fn) => { try {
11
- fn();
12
- }
13
- catch { /* a broken plugin or listener never blocks consent */ } };
14
- /** @example createCookieConsent({ config, ports: browserPorts(window) }, { evidence: { mode: 'local' } }) */
15
- export function createCookieConsent({ config, ports }, options = {}) {
16
- const { doc } = ports;
17
- const plugins = options.plugins ?? createPluginRegistry({}, { slots: [ADAPTER_SLOT] });
18
- const durable = options.evidence?.mode === 'durable' ? options.evidence : null;
19
- const slots = new Map();
20
- const listeners = new Set();
21
- const ran = new Set(); // categories whose raw inert tags executed
22
- const anonymous = config.banner === 'off';
23
- const maxAgeMs = (config.maxAgeDays ?? 180) * DAY_MS;
24
- const region = regionFrom({ configured: config.regionMode, hint: anonymous ? null : readCookie(doc, REGION_COOKIE) });
25
- const fromCookie = () => anonymous ? null : parseStored({ raw: readCookie(doc, CONSENT_COOKIE) });
26
- let stored = fromCookie();
27
- let cookiePersisted = true;
28
- let state = compute();
29
- function compute() {
30
- return effective({ stored, policy: config.policy, region, gpc: ports.gpc(), nowMs: ports.now() }, { maxAgeMs, durable: !!durable, anonymous });
31
- }
32
- function persist() {
33
- const value = JSON.stringify(stored);
34
- writeCookie(doc, { name: CONSENT_COOKIE, value, maxAgeS: maxAgeMs / 1000 }, { domain: config.cookieDomain });
35
- cookiePersisted = readCookie(doc, CONSENT_COOKIE) === value;
36
- }
37
- /** Off-mode adapters load for identity cleanup even at none; only permitted levels grant.
38
- * Abort is checked after the import and handed to grant(), so a withdrawal during either wait wins. */
39
- function start(slot) {
40
- slot.generation++;
41
- const ctl = new AbortController();
42
- const load = Promise.resolve(slot.adapter ?? ports.importModule(slot.entry.src).then(m => (slot.adapter = m.default)));
43
- const result = load.then(adapter => {
44
- quiet(() => adapter.onState?.({ state }));
45
- if (ctl.signal.aborted || anonymous && state.analyticsLevel === 'none')
46
- return null; // withdrawn first: nothing ran
47
- return Promise.resolve().then(() => adapter.grant({ config: slot.entry.config ?? adapter.config, state, signal: ctl.signal }))
48
- .then((r = {}) => r, () => ({})); // a grant that threw may have run code
49
- }, () => null); // import failed: nothing ran
50
- slot.run = { ctl, result };
51
- }
52
- /** Detached from set(): a hung import can never delay a withdrawal. Resolves true when a reload is needed.
53
- * A newer grant owns its storage even if this revoke finishes after another withdrawal. */
54
- async function stop(slot) {
55
- const run = slot.run;
56
- const generation = slot.generation;
57
- slot.run = undefined;
58
- run.ctl.abort();
59
- const revoker = await run.result;
60
- if (!revoker)
61
- return false;
62
- const clean = await Promise.resolve().then(() => revoker.revoke?.()).catch(() => false);
63
- if (!anonymous && slot.generation === generation)
64
- purge(doc, slot.adapter?.storage ?? slot.entry.storage);
65
- return !clean;
66
- }
67
- function reconcile(next) {
68
- const stops = [];
69
- for (const slot of slots.values()) {
70
- const allowed = anonymous ? next.analyticsLevel === 'anonymous' : next.allowed[slot.entry.category];
71
- if (allowed && !slot.run)
72
- start(slot);
73
- if (!allowed && slot.run)
74
- stops.push(stop(slot));
75
- quiet(() => slot.adapter?.onState?.({ state: next }));
76
- }
77
- // Raw tags cannot promise anonymous behavior; only declared adapters can.
78
- if (!anonymous)
79
- activateInert(doc, { allowed: next.allowed, ran });
80
- const rawRevoked = OPTIONAL.some(c => ran.has(c) && !next.allowed[c]);
81
- void Promise.all(stops).then(dirty => { if (rawRevoked || dirty.includes(true))
82
- ports.reload(); });
83
- }
84
- function apply() {
85
- const next = (state = compute());
86
- const html = doc.documentElement;
87
- html.dataset.consent = next.status;
88
- html.dataset.consentRegion = next.region;
89
- html.toggleAttribute('data-consent-gpc', next.gpc);
90
- reconcile(next); // stops start before any listener runs
91
- listeners.forEach(fn => quiet(() => fn(next)));
92
- doc.dispatchEvent(new CustomEvent(STATE_EVENT, { detail: next }));
93
- return next;
94
- }
95
- async function confirm(choice, previousId) {
96
- if (!durable)
97
- return;
98
- const body = JSON.stringify({ policy: choice.p, choices: choice.c, action: choice.a, gpc: ports.gpc(), previousId });
99
- const res = await ports.fetch(durable.endpoint, { method: 'POST', credentials: 'same-origin', keepalive: true,
100
- headers: { 'content-type': 'application/json' }, body }).catch(() => null);
101
- const out = res?.ok ? (await res.json().catch(() => null)) : null;
102
- // Superseded in this tab, or another tab wrote a newer choice (adopt it): the late receipt is ignored.
103
- if (stored !== choice || adopt())
104
- return;
105
- if (typeof out?.id !== 'string' || !RECEIPT_ID.test(out.id))
106
- return; // failed: q stays, retried at the next boot
107
- // Keep the choice intact, replacing its pending marker with the confirmed receipt.
108
- stored = { ...choice, r: out.id };
109
- delete stored.q;
110
- persist();
111
- apply(); // the receipt is what lets durable grants run
112
- }
113
- async function set({ action }, { choices: picked = {} } = {}) {
114
- if (anonymous)
115
- return apply();
116
- const previousId = stored?.r;
117
- stored = { v: 1, p: config.policy, c: choicesFor({ action, picked }), t: ports.now(), a: action, ...(durable ? { q: 1 } : {}) };
118
- persist();
119
- const now = apply(); // denial is live here, before any network
120
- const sent = confirm(stored, previousId);
121
- if (durable && waiting(now))
122
- await within(sent, durable.waitMs ?? 1500);
123
- return state;
124
- }
125
- function addSlot(entry) {
126
- if (anonymous && (!entry.supportsAnonymous || entry.category !== 'analytics'))
127
- return;
128
- const slot = { entry, generation: 0, adapter: typeof entry.grant === 'function' ? entry : undefined };
129
- slots.set(entry.id, slot);
130
- if (anonymous || state.allowed[entry.category])
131
- start(slot);
132
- else
133
- purge(doc, entry.storage); // leftovers of an expired or withdrawn choice
134
- quiet(() => slot.adapter?.onState?.({ state })); // lazy adapters get state once loaded
135
- }
136
- function syncSlots(items) {
137
- const ids = new Set(items.map(i => i.id));
138
- for (const [id, slot] of slots) {
139
- if (ids.has(id))
140
- continue;
141
- slots.delete(id);
142
- if (slot.run)
143
- void stop(slot).then(dirty => { if (dirty)
144
- ports.reload(); });
145
- }
146
- for (const item of items)
147
- if (!slots.has(item.id))
148
- addSlot(item);
149
- }
150
- /** Another tab chose: adopt its cookie exactly as a page load would. Page-visible events only, no polling.
151
- * Returns true when the cookie held a different choice. */
152
- function adopt() {
153
- const latest = fromCookie();
154
- // A refused cookie write leaves only this tab's choice; absence cannot supersede it.
155
- if (!latest && !cookiePersisted)
156
- return false;
157
- if (latest?.t === stored?.t && latest?.a === stored?.a && latest?.r === stored?.r)
158
- return false;
159
- stored = latest;
160
- apply();
161
- return true;
162
- }
163
- const api = {
164
- contract: 1, plugins, set,
165
- get: () => state,
166
- subscribe: ({ listener }) => { listeners.add(listener); return () => { listeners.delete(listener); }; },
167
- open: () => { doc.dispatchEvent(new CustomEvent(OPEN_EVENT)); },
168
- setOpen: ({ open }) => { doc.documentElement.toggleAttribute('data-consent-open', open); },
169
- };
170
- plugins.subscribe({ kind: ADAPTER_KIND, listener: syncSlots });
171
- syncSlots(plugins.list({ kind: ADAPTER_KIND })); // registered before this client existed
172
- config.plugins?.forEach(item => plugins.registerPlugin(item, { source: 'page' }));
173
- apply();
174
- doc.addEventListener('visibilitychange', () => { if (doc.visibilityState === 'visible')
175
- adopt(); });
176
- doc.defaultView?.addEventListener('pageshow', adopt);
177
- if (stored?.q && stored.p === config.policy)
178
- void confirm(stored); // durable retry of an earlier failed receipt
1
+ import { createCookieConsent as createCore, boot as bootCore, bootWithContext as bootCoreWithContext, readPage } from './runtime.js';
2
+ import { installFeatures } from './features.js';
3
+ export { browserPorts, purgeStorage, installOpeners, bindBanner } from './runtime.js';
4
+ export const createCookieConsent = (required, options) => {
5
+ const api = createCore(required, options);
6
+ installFeatures({ api, doc: required.ports.doc, config: required.config, reload: required.ports.reload });
179
7
  return api;
180
- }
181
- export function browserPorts(win) {
182
- return {
183
- doc: win.document, fetch: win.fetch.bind(win), now: Date.now, reload: () => win.location.reload(),
184
- gpc: () => win.navigator.globalPrivacyControl === true || win.navigator.doNotTrack === '1',
185
- importModule: src => import(/* @vite-ignore */ src),
186
- };
187
- }
188
- function readPage(doc) {
189
- try {
190
- return JSON.parse(doc.getElementById(CONFIG_ID)?.textContent ?? '');
191
- }
192
- catch {
193
- return null;
194
- }
195
- }
196
- /** Reads #jini-consent-config, installs window.jiniConsent, drains and replaces the pre-boot queue.
197
- * A missing or broken config installs nothing, so nothing optional can run (fail closed). */
198
- export function boot(win = window, { ports = browserPorts(win), bindBanner } = {}) {
199
- if (win.jiniConsent)
200
- return win.jiniConsent;
201
- const doc = win.document;
202
- const page = readPage(doc);
203
- if (!page)
204
- return undefined;
205
- // The parsed page already satisfies ClientConfig; avoid copying it just to omit evidence.
206
- const api = createCookieConsent({ config: page, ports }, { evidence: page.evidence });
207
- // Before boot the queue is a plain array; an already-replaced queue object has nothing left to drain.
208
- const queued = Array.isArray(win.jiniConsentQueue) ? win.jiniConsentQueue : [];
209
- win.jiniConsent = api;
210
- win.jiniConsentQueue = { push: (...items) => items.forEach(item => api.plugins.registerPlugin(item, { source: 'queue' })) };
211
- win.jiniConsentQueue.push(...queued);
212
- installOpeners({ api, doc });
213
- if (page.banner === 'jini')
214
- bindBanner?.({ api, doc });
215
- doc.dispatchEvent(new CustomEvent(READY_EVENT, { detail: api }));
8
+ };
9
+ function features(win, api, options) {
10
+ if (api)
11
+ installFeatures({ api, doc: win.document, config: readPage(win.document), reload: options.ports?.reload ?? (() => win.location.reload()) }, { bindBanner: options.bindBanner });
216
12
  return api;
217
13
  }
218
- /** Delete only the caller's storage prefixes; blocked localStorage is tolerated.
219
- * @example purgeStorage({ doc: document, storage: { cookies: ['vendor_'], local: ['vendor_'] } })
220
- * @complexity O(cookies + local keys), O(keys) temporary space; no new identity or network. */
221
- export function purgeStorage({ doc, storage }, _optional = {}) {
222
- purge(doc, storage);
14
+ export function boot(win = window, options = {}) {
15
+ return features(win, bootCore(win, { ...options, bindBanner: undefined }), options);
16
+ }
17
+ export async function bootWithContext({ win }, options = {}) {
18
+ return features(win, await bootCoreWithContext({ win }, { ...options, bindBanner: undefined }), options);
223
19
  }
224
- export { bindBanner, installOpeners } from './dom.js';
225
20
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,51 @@
1
+ /** @file Browser runtime (dist/client.min.js). It owns the cookie, the adapter lifecycle, inert tags and
2
+ * receipts. Denial is applied before any network; a durable grant runs only once its receipt exists; a
3
+ * response never sets a cookie, so a slow Accept can't overwrite a newer Reject. No polling, and no reload
4
+ * unless something already ran that cannot be stopped (a raw inert script, or an adapter that can't revoke). */
5
+ import { type ClientConfig, type ConsentAdapter, type Evidence, type JiniConsentApi, type PageConfig, type PluginRegistry, type StoragePrefixes } from '../contract.js';
6
+ export interface ClientPorts {
7
+ doc: Document;
8
+ fetch: typeof fetch;
9
+ now: () => number;
10
+ gpc: () => boolean;
11
+ reload: () => void;
12
+ importModule: (src: string) => Promise<{
13
+ default: ConsentAdapter;
14
+ }>;
15
+ }
16
+ export interface ClientOptions {
17
+ plugins?: PluginRegistry;
18
+ evidence?: Evidence | undefined;
19
+ }
20
+ /** @example createCookieConsent({ config, ports: browserPorts(window) }, { evidence: { mode: 'local' } }) */
21
+ export declare function createCookieConsent({ config, ports }: {
22
+ config: ClientConfig;
23
+ ports: ClientPorts;
24
+ }, options?: ClientOptions): JiniConsentApi;
25
+ export declare function browserPorts(win: Window & typeof globalThis): ClientPorts;
26
+ export interface BootOptions {
27
+ ports?: ClientPorts;
28
+ /** Optional ESM-host banner binding; the shipped browser core leaves UI bindings to extensions.min.js. */
29
+ bindBanner?: ((required: {
30
+ api: JiniConsentApi;
31
+ doc: Document;
32
+ }) => void) | undefined;
33
+ }
34
+ export declare function readPage(doc: Document): PageConfig | null;
35
+ /** Reads #jini-consent-config, installs window.jiniConsent, drains and replaces the pre-boot queue.
36
+ * A missing or broken config installs nothing, so nothing optional can run (fail closed). */
37
+ export declare function boot(win?: Window & typeof globalThis, { ports, bindBanner }?: BootOptions): JiniConsentApi | undefined;
38
+ /** One fresh published-context read before cookie access. Shared cached HTML contains no visitor state.
39
+ * Missing/disabled config and failed context install nothing; no polling or storage reads. */
40
+ export declare function bootWithContext({ win }: {
41
+ win: Window & typeof globalThis;
42
+ }, options?: BootOptions): Promise<JiniConsentApi | undefined>;
43
+ /** Delete only the caller's storage prefixes; blocked localStorage is tolerated.
44
+ * @example purgeStorage({ doc: document, storage: { cookies: ['vendor_'], local: ['vendor_'] } })
45
+ * @complexity O(cookies + local keys), O(keys) temporary space; no new identity or network. */
46
+ export declare function purgeStorage({ doc, storage }: {
47
+ doc: Document;
48
+ storage: StoragePrefixes;
49
+ }, _optional?: {}): void;
50
+ export { bindBanner, installOpeners } from './dom.js';
51
+ //# sourceMappingURL=runtime.d.ts.map