@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.
@@ -0,0 +1,275 @@
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 { allows } from '../contracts/scripts.js';
8
+ import { ADAPTER_SLOT, createPluginRegistry } from '../contracts/plugins.js';
9
+ import { activateInert, installOpeners, purge, readCookie, waiting, writeCookie } from './dom.js';
10
+ const within = (p, ms) => Promise.race([p, new Promise(r => setTimeout(r, ms))]);
11
+ const quiet = (fn) => { try {
12
+ fn();
13
+ }
14
+ catch { /* a broken plugin or listener never blocks consent */ } };
15
+ const durableEvidence = (evidence) => evidence?.mode === 'durable' ? evidence : null;
16
+ /** @example createCookieConsent({ config, ports: browserPorts(window) }, { evidence: { mode: 'local' } }) */
17
+ export function createCookieConsent({ config, ports }, options = {}) {
18
+ const { doc } = ports;
19
+ const plugins = options.plugins ?? createPluginRegistry({}, { slots: [ADAPTER_SLOT] });
20
+ const durable = durableEvidence(options.evidence);
21
+ const slots = new Map();
22
+ const listeners = new Set();
23
+ const ran = new Set(); // categories whose raw inert tags executed
24
+ const anonymous = config.banner === 'off';
25
+ const maxAgeMs = (config.maxAgeDays ?? 180) * DAY_MS;
26
+ const region = regionFrom({ configured: config.regionMode, hint: anonymous ? null : readCookie(doc, REGION_COOKIE) });
27
+ const fromCookie = () => anonymous ? null : parseStored({ raw: readCookie(doc, CONSENT_COOKIE) });
28
+ let stored = fromCookie();
29
+ let cookiePersisted = true;
30
+ let state = compute();
31
+ function compute() {
32
+ return effective({ stored, policy: config.policy, region, gpc: ports.gpc(), nowMs: ports.now() }, { maxAgeMs, durable: !!durable, anonymous });
33
+ }
34
+ function persist() {
35
+ const value = JSON.stringify(stored);
36
+ writeCookie(doc, { name: CONSENT_COOKIE, value, maxAgeS: maxAgeMs / 1000 }, { domain: config.cookieDomain });
37
+ cookiePersisted = readCookie(doc, CONSENT_COOKIE) === value;
38
+ }
39
+ /** Off-mode adapters load for identity cleanup even at none; only permitted levels grant.
40
+ * Abort is checked after the import and handed to grant(), so a withdrawal during either wait wins. */
41
+ function start(slot) {
42
+ slot.generation++;
43
+ const ctl = new AbortController();
44
+ const load = Promise.resolve(slot.adapter ?? ports.importModule(slot.entry.src).then(m => (slot.adapter = m.default)));
45
+ const result = load.then(adapter => {
46
+ quiet(() => adapter.onState?.({ state }));
47
+ if (ctl.signal.aborted || anonymous && state.analyticsLevel === 'none')
48
+ return null; // withdrawn first: nothing ran
49
+ return Promise.resolve().then(() => adapter.grant({ config: slot.entry.config ?? adapter.config, state, signal: ctl.signal }))
50
+ .then((r = {}) => r, () => ({})); // a grant that threw may have run code
51
+ }, () => null); // import failed: nothing ran
52
+ slot.run = { ctl, result };
53
+ }
54
+ /** Detached from set(): a hung import can never delay a withdrawal. Resolves true when a reload is needed.
55
+ * A newer grant owns its storage even if this revoke finishes after another withdrawal. */
56
+ async function stop(slot) {
57
+ const run = slot.run;
58
+ const generation = slot.generation;
59
+ slot.run = undefined;
60
+ run.ctl.abort();
61
+ const revoker = await run.result;
62
+ if (!revoker)
63
+ return false;
64
+ const clean = await Promise.resolve().then(() => revoker.revoke?.()).catch(() => false);
65
+ if (!anonymous && slot.generation === generation)
66
+ purge(doc, slot.adapter?.storage ?? slot.entry.storage);
67
+ return !clean;
68
+ }
69
+ function reconcile(next) {
70
+ const stops = [];
71
+ for (const slot of slots.values()) {
72
+ const allowed = anonymous ? next.analyticsLevel === 'anonymous' : next.allowed[slot.entry.category];
73
+ if (allowed && !slot.run)
74
+ start(slot);
75
+ if (!allowed && slot.run)
76
+ stops.push(stop(slot));
77
+ quiet(() => slot.adapter?.onState?.({ state: next }));
78
+ }
79
+ // Raw tags cannot promise anonymous behavior; only declared adapters can.
80
+ if (!anonymous)
81
+ activateInert(doc, { allowed: next.allowed, ran });
82
+ const rawRevoked = OPTIONAL.some(c => ran.has(c) && !next.allowed[c]);
83
+ void Promise.all(stops).then(dirty => { if (rawRevoked || dirty.includes(true))
84
+ ports.reload(); });
85
+ }
86
+ function apply() {
87
+ const next = (state = compute());
88
+ const html = doc.documentElement;
89
+ html.dataset.consent = next.status;
90
+ html.dataset.consentRegion = next.region;
91
+ html.toggleAttribute('data-consent-gpc', next.gpc);
92
+ reconcile(next); // stops start before any listener runs
93
+ listeners.forEach(fn => quiet(() => fn(next)));
94
+ doc.dispatchEvent(new CustomEvent(STATE_EVENT, { detail: next }));
95
+ return next;
96
+ }
97
+ async function confirm(choice, previousId) {
98
+ if (!durable)
99
+ return;
100
+ const body = JSON.stringify({ policy: choice.p, choices: choice.c, action: choice.a, gpc: ports.gpc(), previousId });
101
+ const res = await ports.fetch(durable.endpoint, { method: 'POST', credentials: 'same-origin', keepalive: true,
102
+ headers: { 'content-type': 'application/json' }, body }).catch(() => null);
103
+ const out = res?.ok ? (await res.json().catch(() => null)) : null;
104
+ // Superseded in this tab, or another tab wrote a newer choice (adopt it): the late receipt is ignored.
105
+ if (stored !== choice || adopt())
106
+ return;
107
+ if (typeof out?.id !== 'string' || !RECEIPT_ID.test(out.id))
108
+ return; // failed: q stays, retried at the next boot
109
+ // Keep the choice intact, replacing its pending marker with the confirmed receipt.
110
+ stored = { ...choice, r: out.id };
111
+ delete stored.q;
112
+ persist();
113
+ apply(); // the receipt is what lets durable grants run
114
+ }
115
+ async function set({ action }, { choices: picked = {} } = {}) {
116
+ if (anonymous)
117
+ return apply();
118
+ const previousId = stored?.r;
119
+ stored = { v: 1, p: config.policy, c: choicesFor({ action, picked }), t: ports.now(), a: action, ...(durable ? { q: 1 } : {}) };
120
+ persist();
121
+ const now = apply(); // denial is live here, before any network
122
+ const sent = confirm(stored, previousId);
123
+ if (durable && waiting(now))
124
+ await within(sent, durable.waitMs ?? 1500);
125
+ return state;
126
+ }
127
+ function addSlot(entry) {
128
+ if (anonymous && (!entry.supportsAnonymous || entry.category !== 'analytics'))
129
+ return;
130
+ const slot = { entry, generation: 0, adapter: typeof entry.grant === 'function' ? entry : undefined };
131
+ slots.set(entry.id, slot);
132
+ if (anonymous || state.allowed[entry.category])
133
+ start(slot);
134
+ else
135
+ purge(doc, entry.storage); // leftovers of an expired or withdrawn choice
136
+ quiet(() => slot.adapter?.onState?.({ state })); // lazy adapters get state once loaded
137
+ }
138
+ function syncSlots(items) {
139
+ const ids = new Set(items.map(i => i.id));
140
+ for (const [id, slot] of slots) {
141
+ if (ids.has(id))
142
+ continue;
143
+ slots.delete(id);
144
+ if (slot.run)
145
+ void stop(slot).then(dirty => { if (dirty)
146
+ ports.reload(); });
147
+ }
148
+ for (const item of items)
149
+ if (!slots.has(item.id))
150
+ addSlot(item);
151
+ }
152
+ /** Another tab chose: adopt its cookie exactly as a page load would. Page-visible events only, no polling.
153
+ * Returns true when the cookie held a different choice. */
154
+ function adopt() {
155
+ const latest = fromCookie();
156
+ // A refused cookie write leaves only this tab's choice; absence cannot supersede it.
157
+ if (!latest && !cookiePersisted)
158
+ return false;
159
+ if (['t', 'a', 'r'].every(key => latest?.[key] === stored?.[key]))
160
+ return false;
161
+ stored = latest;
162
+ apply();
163
+ return true;
164
+ }
165
+ const api = {
166
+ contract: 1, plugins, set,
167
+ get: () => state,
168
+ allows: ({ consent }) => allows({ state, consent }),
169
+ subscribe: ({ listener }) => { listeners.add(listener); return () => { listeners.delete(listener); }; },
170
+ open: () => { doc.dispatchEvent(new CustomEvent(OPEN_EVENT)); },
171
+ setOpen: ({ open }) => { doc.documentElement.toggleAttribute('data-consent-open', open); },
172
+ };
173
+ plugins.subscribe({ kind: ADAPTER_KIND, listener: syncSlots });
174
+ syncSlots(plugins.list({ kind: ADAPTER_KIND })); // registered before this client existed
175
+ config.plugins?.forEach(item => plugins.registerPlugin(item, { source: 'page' }));
176
+ apply();
177
+ doc.addEventListener('visibilitychange', () => { if (doc.visibilityState === 'visible')
178
+ adopt(); });
179
+ doc.defaultView?.addEventListener('pageshow', adopt);
180
+ if (stored?.q && stored.p === config.policy)
181
+ void confirm(stored); // durable retry of an earlier failed receipt
182
+ return api;
183
+ }
184
+ export function browserPorts(win) {
185
+ return {
186
+ doc: win.document, fetch: win.fetch.bind(win), now: Date.now, reload: () => win.location.reload(),
187
+ gpc: () => win.navigator.globalPrivacyControl === true || win.navigator.doNotTrack === '1',
188
+ importModule: src => import(/* @vite-ignore */ src),
189
+ };
190
+ }
191
+ export function readPage(doc) {
192
+ try {
193
+ return JSON.parse(doc.getElementById(CONFIG_ID)?.textContent ?? '');
194
+ }
195
+ catch {
196
+ return null;
197
+ }
198
+ }
199
+ /** Reads #jini-consent-config, installs window.jiniConsent, drains and replaces the pre-boot queue.
200
+ * A missing or broken config installs nothing, so nothing optional can run (fail closed). */
201
+ export function boot(win = window, { ports = browserPorts(win), bindBanner } = {}) {
202
+ if (win.jiniConsent)
203
+ return win.jiniConsent;
204
+ const doc = win.document;
205
+ const page = readPage(doc);
206
+ if (!page)
207
+ return undefined;
208
+ return installPage(win, page, { ports, bindBanner });
209
+ }
210
+ function installPage(win, page, { ports = browserPorts(win), bindBanner }) {
211
+ // The parsed page already satisfies ClientConfig; avoid copying it just to omit evidence.
212
+ const doc = win.document;
213
+ const api = createCookieConsent({ config: page, ports }, { evidence: page.evidence });
214
+ // Before boot the queue is a plain array; an already-replaced queue object has nothing left to drain.
215
+ const queued = Array.isArray(win.jiniConsentQueue) ? win.jiniConsentQueue : [];
216
+ win.jiniConsent = api;
217
+ win.jiniConsentQueue = { push: (...items) => items.forEach(item => api.plugins.registerPlugin(item, { source: 'queue' })) };
218
+ win.jiniConsentQueue.push(...queued);
219
+ installOpeners({ api, doc });
220
+ if (page.banner === 'jini')
221
+ bindBanner?.({ api, doc });
222
+ doc.dispatchEvent(new CustomEvent(READY_EVENT, { detail: api }));
223
+ return api;
224
+ }
225
+ /** One fresh published-context read before cookie access. Shared cached HTML contains no visitor state.
226
+ * Missing/disabled config and failed context install nothing; no polling or storage reads. */
227
+ export async function bootWithContext({ win }, options = {}) {
228
+ if (win.jiniConsent)
229
+ return win.jiniConsent;
230
+ const page = readPage(win.document);
231
+ if (!page || page.banner === 'off')
232
+ return undefined;
233
+ if (!page.context)
234
+ return boot(win, options);
235
+ const ports = options.ports ?? browserPorts(win);
236
+ try {
237
+ const context = await ports.fetch(page.context, { credentials: 'same-origin', cache: 'no-store' })
238
+ .then(response => response.ok ? response.json() : null);
239
+ if (!validContext(context))
240
+ return undefined;
241
+ // Cached copy/CSS must describe the policy being accepted; revalidation fetches the current document.
242
+ if (context.policy !== page.policy) {
243
+ reloadStalePage({ win, policy: page.policy, reload: ports.reload });
244
+ return undefined;
245
+ }
246
+ return installPage(win, { ...page, regionMode: context.regionMode }, { ...options, ports });
247
+ }
248
+ catch {
249
+ return undefined;
250
+ }
251
+ }
252
+ /** A shared cache can return the same stale page after reload. Persist the guard before navigating;
253
+ * blocked session storage leaves optional code withheld instead of risking a reload loop. O(1). */
254
+ function reloadStalePage({ win, policy, reload }) {
255
+ try {
256
+ const key = `jini-consent-reload:${policy}`;
257
+ if (win.sessionStorage.getItem(key))
258
+ return;
259
+ win.sessionStorage.setItem(key, '1');
260
+ reload();
261
+ }
262
+ catch { /* Storage unavailable: keep this stale policy inert. */ }
263
+ }
264
+ function validContext(value) {
265
+ const context = value;
266
+ return context?.enabled === true && typeof context.policy === 'string' && ['auto', 'opt-in', 'opt-out'].includes(String(context.regionMode));
267
+ }
268
+ /** Delete only the caller's storage prefixes; blocked localStorage is tolerated.
269
+ * @example purgeStorage({ doc: document, storage: { cookies: ['vendor_'], local: ['vendor_'] } })
270
+ * @complexity O(cookies + local keys), O(keys) temporary space; no new identity or network. */
271
+ export function purgeStorage({ doc, storage }, _optional = {}) {
272
+ purge(doc, storage);
273
+ }
274
+ export { bindBanner, installOpeners } from './dom.js';
275
+ //# sourceMappingURL=runtime.js.map
@@ -0,0 +1,8 @@
1
+ /** Ordered, once-only declared scripts. Arbitrary executed code needs a reload on withdrawal. */
2
+ import type { ConsentState, DeclaredScript } from '../contract.js';
3
+ export declare function declaredScripts({ doc, scripts, reload }: {
4
+ doc: Document;
5
+ scripts: readonly DeclaredScript[];
6
+ reload: () => void;
7
+ }, _optional?: {}): (state: ConsentState) => void;
8
+ //# sourceMappingURL=scripts.d.ts.map
@@ -0,0 +1,39 @@
1
+ import { allows, validateScripts } from '../contracts/scripts.js';
2
+ export function declaredScripts({ doc, scripts, reload }, _optional = {}) {
3
+ const entries = validateScripts({ scripts }).scripts.map(script => ({ script, started: false, node: null }));
4
+ let loading = null;
5
+ let latest;
6
+ let withdrawn = false;
7
+ function advance() {
8
+ if (loading || withdrawn)
9
+ return;
10
+ const entry = entries.find(item => !item.started && allows({ state: latest, consent: item.script.consent }));
11
+ if (!entry)
12
+ return;
13
+ entry.started = true;
14
+ const node = doc.createElement('script');
15
+ entry.node = loading = node;
16
+ node.async = false;
17
+ node.src = entry.script.src;
18
+ const complete = () => {
19
+ if (loading === node)
20
+ loading = null;
21
+ advance();
22
+ };
23
+ node.onload = complete;
24
+ node.onerror = complete;
25
+ doc.head.append(node);
26
+ }
27
+ return state => {
28
+ latest = state;
29
+ const revoked = entries.filter(entry => entry.started && !allows({ state, consent: entry.script.consent }));
30
+ if (revoked.length && !withdrawn) {
31
+ withdrawn = true;
32
+ revoked.forEach(entry => entry.node?.remove());
33
+ // Removing a pending node cannot prove it never executed. Denial was persisted before reconciliation.
34
+ reload();
35
+ }
36
+ advance();
37
+ };
38
+ }
39
+ //# sourceMappingURL=scripts.js.map
@@ -1 +1 @@
1
- "use strict";(()=>{var R="jini_choices",B="jini_region",G="jini:consent",V="jini:consent-ready",O="jini:consent-open",$="jini-consent-config",v=["functional","analytics","marketing"],ke=["necessary",...v],W=["accept","reject","save","do-not-sell","withdraw"];var P="consent-adapter";var N=864e5,le=180*N,ue=6e4,D=/^[\w-]{16,128}$/,z=Object.freeze({necessary:!0,functional:!1,analytics:!1,marketing:!1});function Q({configured:e,hint:n},t={}){return e!=="auto"?e:n==="us"?"opt-out":"opt-in"}var x=(e,n=e,t=n)=>({functional:e,analytics:n,marketing:t});function Y({action:e,picked:n={}},t={}){return e==="accept"?x(!0):e==="save"?x(n.functional===!0,n.analytics===!0,n.marketing===!0):e==="do-not-sell"?x(n.functional!==!1,!1):x(!1)}function de({flags:e,gpc:n},t={}){return{necessary:!0,functional:e.functional,analytics:e.analytics&&!n,marketing:e.marketing&&!n}}function U({stored:e,policy:n,region:t,gpc:o,nowMs:r},{maxAgeMs:a=le,durable:c=!1,anonymous:f=!1}={}){let m=!f&&e&&e.p===n&&e.t<=r+ue&&r-e.t<=a?e:null,C=de({flags:f?z:m?.c??x(t==="opt-out"),gpc:o}),h={contract:1,policy:n,region:t,gpc:o,choices:C,...pe({choices:C,live:m,durable:c,anonymous:f,gpc:o})};return m?{...h,status:"set",action:m.a,at:m.t,receipt:fe(m)}:{...h,status:"pending",action:null,at:null,receipt:"none"}}function pe({choices:e,live:n,durable:t,anonymous:o,gpc:r},a={}){let c=n&&t&&!n.r,f=o||c?z:e,m=f.analytics?"full":"none";return{allowed:f,analyticsLevel:o&&!r?"anonymous":m}}function fe(e){return e.r?"stored":e.q?"pending":"local"}function X({raw:e},n={}){if(!e||e.length>1024)return null;let t;try{t=JSON.parse(e)}catch{return null}if(!ge(t))return null;let o={v:1,p:t.p,c:x(t.c.functional,t.c.analytics,t.c.marketing),t:t.t,a:t.a};return typeof t.r=="string"&&D.test(t.r)&&(o.r=t.r),t.q===1&&(o.q=1),o}function ge(e){return!e||e.v!==1||typeof e.p!="string"||!Number.isFinite(e.t)?!1:W.includes(e.a)&&ye(e.c)}function ye(e){let n=e;return!n||typeof n!="object"?!1:["functional","analytics","marketing"].every(t=>Object.hasOwn(n,t)&&typeof n[t]=="boolean")}var me=/^[a-z0-9][a-z0-9._:-]{0,63}$/;function Z(e={},{slots:n=[],onProblem:t=()=>{}}={}){let o=new Map,r=[],a=new Set,c=new Set,f=s=>r.filter(u=>u.kind===s).sort((u,l)=>l.priority-u.priority).map(u=>u.value),m=s=>c.forEach(u=>{if(u.kind===s)try{u.fn(f(s))}catch{}});function C(s,u){let l=S=>(t({id:String(s.id),kind:s.kind,reason:S,...u.source?{source:u.source}:{}}),()=>{});if(!me.test(String(s.id)))return l("short lowercase id");let E=o.get(s.kind).accept({contribution:s});if(typeof E=="string")return l(E);if(r.some(S=>S.kind===s.kind&&S.id===s.id))return l("duplicate id");let b={kind:s.kind,id:s.id,value:E,priority:u.priority??0};return r.push(b),m(s.kind),()=>{let S=r.indexOf(b);S>=0&&(r.splice(S,1),m(s.kind))}}let h={defineSlot({slot:s}){if(!o.has(s.kind)){o.set(s.kind,s);for(let u of a)u.raw.kind===s.kind&&(a.delete(u),u.dispose=C(u.raw,u.options))}},registerPlugin(s,u={}){if(o.has(s.kind))return C(s,u);let l={raw:s,options:u,dispose:()=>{a.delete(l)}};return a.add(l),()=>l.dispose()},list:({kind:s})=>f(s),subscribe({kind:s,listener:u}){let l={kind:s,fn:u};return c.add(l),()=>{c.delete(l)}}};for(let s of n)h.defineSlot({slot:s});return h}var ee={kind:P,accept({contribution:e}){return v.includes(e.category)?typeof e.grant=="function"||typeof e.src=="string"?e:"grant() or src needed":"category must be functional, analytics or marketing"}};var Ce=["type","data-src","data-type","data-consent-category"],be=':not(html)[data-consent-open],a[href="#privacy-choices"]';function T(e,n){let t=e.cookie.split(/;\s*/).find(o=>o.startsWith(n+"="));try{return t?decodeURIComponent(t.slice(n.length+1)):null}catch{return null}}function te(e,{name:n,value:t,maxAgeS:o},{domain:r}={}){let a=e.defaultView?.location.protocol==="https:"?"; Secure":"";e.cookie=`${n}=${encodeURIComponent(t)}; Path=/; Max-Age=${Math.floor(o)}; SameSite=Lax${a}`+(r?"; Domain="+r:"")}function Se(e,n){let t=(e.defaultView?.location.hostname??"").split("."),o=`${n}=; Path=/; Max-Age=0`;e.cookie=o;for(let r=0;r<t.length-1;r++)e.cookie=`${o}; Domain=.${t.slice(r).join(".")}`}function M(e,n){if(n){for(let t of e.cookie.split(/;\s*/)){let o=t.split("=")[0];n.cookies?.some(r=>o.startsWith(r))&&Se(e,o)}try{let t=e.defaultView.localStorage;for(let o of Object.keys(t))n.local?.some(r=>o.startsWith(r))&&t.removeItem(o)}catch{}}}function ne(e,{allowed:n,ran:t}){e.querySelectorAll('script[type="text/plain"],iframe[data-src],template[data-jini-consent-resource]').forEach(o=>{let r=o.content,a=r?o.dataset.category:o.dataset.consentCategory;!v.includes(a)||!n[a]||(t.add(a),o.tagName==="IFRAME"?(o.src=o.dataset.src,o.removeAttribute("data-src")):o.replaceWith(r??ve(e,o)))})}function ve(e,n){let t=e.createElement("script");for(let{name:o,value:r}of n.attributes)Ce.includes(o)||t.setAttribute(o,r);return n.nonce&&(t.nonce=n.nonce),n.dataset.type&&(t.type=n.dataset.type),n.dataset.src?t.src=n.dataset.src:t.text=n.text,t.async=!1,t}function L({api:e,doc:n}){n.addEventListener("click",t=>{t.target.closest?.(be)&&(t.preventDefault(),e.open())})}function he(e){let n={};for(let t of v){let o=e.querySelector(`input[name="${t}"]`);o&&(n[t]=o.checked)}return n}function _(e,n){for(let t of v){let o=e.querySelector(`input[name="${t}"]`);o&&(o.checked=n.choices[t],o.disabled=n.gpc&&t!=="functional")}}var k=e=>v.some(n=>e.choices[n]&&!e.allowed[n]);function j({api:e,doc:n}){let t=n.getElementById("jini-consent");if(!t)return;let o=t.querySelector("[data-consent-error]"),r=c=>{t.hidden=!c,e.setOpen({open:c})},a=c=>{o&&(o.hidden=!k(c)),k(c)||r(!1)};t.addEventListener("click",c=>{let f=c.target.closest?.("[data-consent-action]")?.dataset.consentAction;f&&(c.preventDefault(),e.set({action:f},{choices:he(t)}).then(a))}),t.addEventListener("keydown",c=>{c.key==="Escape"&&e.get().status==="set"&&r(!1)}),n.addEventListener(O,()=>{_(t,e.get()),r(!0),t.querySelector("button")?.focus()}),e.subscribe({listener:c=>{_(t,c),o&&!o.hidden&&!k(c)&&a(c)}}),_(t,e.get()),r(e.get().status==="pending")}var Ee=(e,n)=>Promise.race([e,new Promise(t=>setTimeout(t,n))]),w=e=>{try{e()}catch{}};function xe({config:e,ports:n},t={}){let{doc:o}=n,r=t.plugins??Z({},{slots:[ee]}),a=t.evidence?.mode==="durable"?t.evidence:null,c=new Map,f=new Set,m=new Set,C=e.banner==="off",h=(e.maxAgeDays??180)*N,s=Q({configured:e.regionMode,hint:C?null:T(o,B)}),u=()=>C?null:X({raw:T(o,R)}),l=u(),E=!0,b=S();function S(){return U({stored:l,policy:e.policy,region:s,gpc:n.gpc(),nowMs:n.now()},{maxAgeMs:h,durable:!!a,anonymous:C})}function q(){let i=JSON.stringify(l);te(o,{name:R,value:i,maxAgeS:h/1e3},{domain:e.cookieDomain}),E=T(o,R)===i}function F(i){i.generation++;let p=new AbortController,d=Promise.resolve(i.adapter??n.importModule(i.entry.src).then(y=>i.adapter=y.default)).then(y=>(w(()=>y.onState?.({state:b})),p.signal.aborted||C&&b.analyticsLevel==="none"?null:Promise.resolve().then(()=>y.grant({config:i.entry.config??y.config,state:b,signal:p.signal})).then((ce={})=>ce,()=>({}))),()=>null);i.run={ctl:p,result:d}}async function K(i){let p=i.run,g=i.generation;i.run=void 0,p.ctl.abort();let d=await p.result;if(!d)return!1;let y=await Promise.resolve().then(()=>d.revoke?.()).catch(()=>!1);return!C&&i.generation===g&&M(o,i.adapter?.storage??i.entry.storage),!y}function ie(i){let p=[];for(let d of c.values()){let y=C?i.analyticsLevel==="anonymous":i.allowed[d.entry.category];y&&!d.run&&F(d),!y&&d.run&&p.push(K(d)),w(()=>d.adapter?.onState?.({state:i}))}C||ne(o,{allowed:i.allowed,ran:m});let g=v.some(d=>m.has(d)&&!i.allowed[d]);Promise.all(p).then(d=>{(g||d.includes(!0))&&n.reload()})}function A(){let i=b=S(),p=o.documentElement;return p.dataset.consent=i.status,p.dataset.consentRegion=i.region,p.toggleAttribute("data-consent-gpc",i.gpc),ie(i),f.forEach(g=>w(()=>g(i))),o.dispatchEvent(new CustomEvent(G,{detail:i})),i}async function H(i,p){if(!a)return;let g=JSON.stringify({policy:i.p,choices:i.c,action:i.a,gpc:n.gpc(),previousId:p}),d=await n.fetch(a.endpoint,{method:"POST",credentials:"same-origin",keepalive:!0,headers:{"content-type":"application/json"},body:g}).catch(()=>null),y=d?.ok?await d.json().catch(()=>null):null;l!==i||I()||typeof y?.id!="string"||!D.test(y.id)||(l={...i,r:y.id},delete l.q,q(),A())}async function re({action:i},{choices:p={}}={}){if(C)return A();let g=l?.r;l={v:1,p:e.policy,c:Y({action:i,picked:p}),t:n.now(),a:i,...a?{q:1}:{}},q();let d=A(),y=H(l,g);return a&&k(d)&&await Ee(y,a.waitMs??1500),b}function se(i){if(C&&(!i.supportsAnonymous||i.category!=="analytics"))return;let p={entry:i,generation:0,adapter:typeof i.grant=="function"?i:void 0};c.set(i.id,p),C||b.allowed[i.category]?F(p):M(o,i.storage),w(()=>p.adapter?.onState?.({state:b}))}function J(i){let p=new Set(i.map(g=>g.id));for(let[g,d]of c)p.has(g)||(c.delete(g),d.run&&K(d).then(y=>{y&&n.reload()}));for(let g of i)c.has(g.id)||se(g)}function I(){let i=u();return!i&&!E||i?.t===l?.t&&i?.a===l?.a&&i?.r===l?.r?!1:(l=i,A(),!0)}let ae={contract:1,plugins:r,set:re,get:()=>b,subscribe:({listener:i})=>(f.add(i),()=>{f.delete(i)}),open:()=>{o.dispatchEvent(new CustomEvent(O))},setOpen:({open:i})=>{o.documentElement.toggleAttribute("data-consent-open",i)}};return r.subscribe({kind:P,listener:J}),J(r.list({kind:P})),e.plugins?.forEach(i=>r.registerPlugin(i,{source:"page"})),A(),o.addEventListener("visibilitychange",()=>{o.visibilityState==="visible"&&I()}),o.defaultView?.addEventListener("pageshow",I),l?.q&&l.p===e.policy&&H(l),ae}function Ae(e){return{doc:e.document,fetch:e.fetch.bind(e),now:Date.now,reload:()=>e.location.reload(),gpc:()=>e.navigator.globalPrivacyControl===!0||e.navigator.doNotTrack==="1",importModule:n=>import(n)}}function Pe(e){try{return JSON.parse(e.getElementById($)?.textContent??"")}catch{return null}}function oe(e=window,{ports:n=Ae(e),bindBanner:t}={}){if(e.jiniConsent)return e.jiniConsent;let o=e.document,r=Pe(o);if(!r)return;let a=xe({config:r,ports:n},{evidence:r.evidence}),c=Array.isArray(e.jiniConsentQueue)?e.jiniConsentQueue:[];return e.jiniConsent=a,e.jiniConsentQueue={push:(...f)=>f.forEach(m=>a.plugins.registerPlugin(m,{source:"queue"}))},e.jiniConsentQueue.push(...c),L({api:a,doc:o}),r.banner==="jini"&&t?.({api:a,doc:o}),o.dispatchEvent(new CustomEvent(V,{detail:a})),a}oe(window,{bindBanner:j});})();
1
+ "use strict";(()=>{var P="jini_choices",K="jini_region",H="jini:consent",J="jini:consent-ready",T="jini:consent-open",B="jini-consent-config",h=["functional","analytics","marketing"],G=["necessary",...h],V=["accept","reject","save","do-not-sell","withdraw"];var k="consent-adapter";var D=864e5,pe=180*D,fe=6e4,I=/^[\w-]{16,128}$/,W=Object.freeze({necessary:!0,functional:!1,analytics:!1,marketing:!1});function $({configured:e,hint:t},n={}){return e!=="auto"?e:t==="us"?"opt-out":"opt-in"}var A=(e,t=e,n=t)=>({functional:e,analytics:t,marketing:n});function z({action:e,picked:t={}},n={}){return e==="accept"?A(!0):e==="save"?A(t.functional===!0,t.analytics===!0,t.marketing===!0):e==="do-not-sell"?A(t.functional!==!1,!1):A(!1)}function ge({flags:e,gpc:t},n={}){return{necessary:!0,functional:e.functional,analytics:e.analytics&&!t,marketing:e.marketing&&!t}}function U({stored:e,policy:t,region:n,gpc:o,nowMs:r},{maxAgeMs:a=pe,durable:m=!1,anonymous:C=!1}={}){let g=!C&&e&&e.p===t&&e.t<=r+fe&&r-e.t<=a?e:null,y=ge({flags:C?W:g?.c??A(n==="opt-out"),gpc:o}),v={contract:1,policy:t,region:n,gpc:o,choices:y,...ye({choices:y,live:g,durable:m,anonymous:C,gpc:o})};return g?{...v,status:"set",action:g.a,at:g.t,receipt:me(g)}:{...v,status:"pending",action:null,at:null,receipt:"none"}}function ye({choices:e,live:t,durable:n,anonymous:o,gpc:r},a={}){let m=t&&n&&!t.r,C=o||m?W:e,g=C.analytics?"full":"none";return{allowed:C,analyticsLevel:o&&!r?"anonymous":g}}function me(e){return e.r?"stored":e.q?"pending":"local"}function Q({raw:e},t={}){if(!e||e.length>1024)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!Ce(n))return null;let o={v:1,p:n.p,c:A(n.c.functional,n.c.analytics,n.c.marketing),t:n.t,a:n.a};return typeof n.r=="string"&&I.test(n.r)&&(o.r=n.r),n.q===1&&(o.q=1),o}function Ce(e){return!e||e.v!==1||typeof e.p!="string"||!Number.isFinite(e.t)?!1:V.includes(e.a)&&be(e.c)}function be(e){let t=e;return!t||typeof t!="object"?!1:["functional","analytics","marketing"].every(n=>Object.hasOwn(t,n)&&typeof t[n]=="boolean")}function Y({state:e,consent:t=[]},n={}){return t.every(o=>G.includes(o)&&e.allowed[o]===!0)}var Se=/^[a-z0-9][a-z0-9._:-]{0,63}$/;function X(e={},{slots:t=[],onProblem:n=()=>{}}={}){let o=new Map,r=[],a=new Set,m=new Set,C=s=>r.filter(c=>c.kind===s).sort((c,l)=>l.priority-c.priority).map(c=>c.value),g=s=>m.forEach(c=>{if(c.kind===s)try{c.fn(C(s))}catch{}});function y(s,c){let l=S=>(n({id:String(s.id),kind:s.kind,reason:S,...c.source?{source:c.source}:{}}),()=>{});if(!Se.test(String(s.id)))return l("short lowercase id");let x=o.get(s.kind).accept({contribution:s});if(typeof x=="string")return l(x);if(r.some(S=>S.kind===s.kind&&S.id===s.id))return l("duplicate id");let b={kind:s.kind,id:s.id,value:x,priority:c.priority??0};return r.push(b),g(s.kind),()=>{let S=r.indexOf(b);S>=0&&(r.splice(S,1),g(s.kind))}}let v={defineSlot({slot:s}){if(!o.has(s.kind)){o.set(s.kind,s);for(let c of a)c.raw.kind===s.kind&&(a.delete(c),c.dispose=y(c.raw,c.options))}},registerPlugin(s,c={}){if(o.has(s.kind))return y(s,c);let l={raw:s,options:c,dispose:()=>{a.delete(l)}};return a.add(l),()=>l.dispose()},list:({kind:s})=>C(s),subscribe({kind:s,listener:c}){let l={kind:s,fn:c};return m.add(l),()=>{m.delete(l)}}};for(let s of t)v.defineSlot({slot:s});return v}var Z={kind:k,accept({contribution:e}){return h.includes(e.category)?typeof e.grant=="function"||typeof e.src=="string"?e:"grant() or src needed":"category must be functional, analytics or marketing"}};var ve=["type","data-src","data-type","data-consent-category"],he=':not(html)[data-consent-open],a[href="#privacy-choices"]';function R(e,t){let n=e.cookie.split(/;\s*/).find(o=>o.startsWith(t+"="));try{return n?decodeURIComponent(n.slice(t.length+1)):null}catch{return null}}function ee(e,{name:t,value:n,maxAgeS:o},{domain:r}={}){let a=e.defaultView?.location.protocol==="https:"?"; Secure":"";e.cookie=`${t}=${encodeURIComponent(n)}; Path=/; Max-Age=${Math.floor(o)}; SameSite=Lax${a}`+(r?"; Domain="+r:"")}function xe(e,t){let n=(e.defaultView?.location.hostname??"").split("."),o=`${t}=; Path=/; Max-Age=0`;e.cookie=o;for(let r=0;r<n.length-1;r++)e.cookie=`${o}; Domain=.${n.slice(r).join(".")}`}function M(e,t){if(t){for(let n of e.cookie.split(/;\s*/)){let o=n.split("=")[0];t.cookies?.some(r=>o.startsWith(r))&&xe(e,o)}try{let n=e.defaultView.localStorage;for(let o of Object.keys(n))t.local?.some(r=>o.startsWith(r))&&n.removeItem(o)}catch{}}}function te(e,{allowed:t,ran:n}){e.querySelectorAll('script[type="text/plain"],iframe[data-src],template[data-jini-consent-resource]').forEach(o=>{let r=o.content,a=r?o.dataset.category:o.dataset.consentCategory;!h.includes(a)||!t[a]||(n.add(a),o.tagName==="IFRAME"?(o.src=o.dataset.src,o.removeAttribute("data-src")):o.replaceWith(r??Ae(e,o)))})}function Ae(e,t){let n=e.createElement("script");for(let{name:o,value:r}of t.attributes)ve.includes(o)||n.setAttribute(o,r);return t.nonce&&(n.nonce=t.nonce),t.dataset.type&&(n.type=t.dataset.type),t.dataset.src?n.src=t.dataset.src:n.text=t.text,n.async=!1,n}function ne({api:e,doc:t}){t.addEventListener("click",n=>{n.target.closest?.(he)&&(n.preventDefault(),e.open())})}var oe=e=>h.some(t=>e.choices[t]&&!e.allowed[t]);var Ee=(e,t)=>Promise.race([e,new Promise(n=>setTimeout(n,t))]),O=e=>{try{e()}catch{}},ke=e=>e?.mode==="durable"?e:null;function Pe({config:e,ports:t},n={}){let{doc:o}=t,r=n.plugins??X({},{slots:[Z]}),a=ke(n.evidence),m=new Map,C=new Set,g=new Set,y=e.banner==="off",v=(e.maxAgeDays??180)*D,s=$({configured:e.regionMode,hint:y?null:R(o,K)}),c=()=>y?null:Q({raw:R(o,P)}),l=c(),x=!0,b=S();function S(){return U({stored:l,policy:e.policy,region:s,gpc:t.gpc(),nowMs:t.now()},{maxAgeMs:v,durable:!!a,anonymous:y})}function _(){let i=JSON.stringify(l);ee(o,{name:P,value:i,maxAgeS:v/1e3},{domain:e.cookieDomain}),x=R(o,P)===i}function j(i){i.generation++;let u=new AbortController,d=Promise.resolve(i.adapter??t.importModule(i.entry.src).then(f=>i.adapter=f.default)).then(f=>(O(()=>f.onState?.({state:b})),u.signal.aborted||y&&b.analyticsLevel==="none"?null:Promise.resolve().then(()=>f.grant({config:i.entry.config??f.config,state:b,signal:u.signal})).then((de={})=>de,()=>({}))),()=>null);i.run={ctl:u,result:d}}async function L(i){let u=i.run,p=i.generation;i.run=void 0,u.ctl.abort();let d=await u.result;if(!d)return!1;let f=await Promise.resolve().then(()=>d.revoke?.()).catch(()=>!1);return!y&&i.generation===p&&M(o,i.adapter?.storage??i.entry.storage),!f}function ae(i){let u=[];for(let d of m.values()){let f=y?i.analyticsLevel==="anonymous":i.allowed[d.entry.category];f&&!d.run&&j(d),!f&&d.run&&u.push(L(d)),O(()=>d.adapter?.onState?.({state:i}))}y||te(o,{allowed:i.allowed,ran:g});let p=h.some(d=>g.has(d)&&!i.allowed[d]);Promise.all(u).then(d=>{(p||d.includes(!0))&&t.reload()})}function E(){let i=b=S(),u=o.documentElement;return u.dataset.consent=i.status,u.dataset.consentRegion=i.region,u.toggleAttribute("data-consent-gpc",i.gpc),ae(i),C.forEach(p=>O(()=>p(i))),o.dispatchEvent(new CustomEvent(H,{detail:i})),i}async function q(i,u){if(!a)return;let p=JSON.stringify({policy:i.p,choices:i.c,action:i.a,gpc:t.gpc(),previousId:u}),d=await t.fetch(a.endpoint,{method:"POST",credentials:"same-origin",keepalive:!0,headers:{"content-type":"application/json"},body:p}).catch(()=>null),f=d?.ok?await d.json().catch(()=>null):null;l!==i||w()||typeof f?.id!="string"||!I.test(f.id)||(l={...i,r:f.id},delete l.q,_(),E())}async function ce({action:i},{choices:u={}}={}){if(y)return E();let p=l?.r;l={v:1,p:e.policy,c:z({action:i,picked:u}),t:t.now(),a:i,...a?{q:1}:{}},_();let d=E(),f=q(l,p);return a&&oe(d)&&await Ee(f,a.waitMs??1500),b}function le(i){if(y&&(!i.supportsAnonymous||i.category!=="analytics"))return;let u={entry:i,generation:0,adapter:typeof i.grant=="function"?i:void 0};m.set(i.id,u),y||b.allowed[i.category]?j(u):M(o,i.storage),O(()=>u.adapter?.onState?.({state:b}))}function F(i){let u=new Set(i.map(p=>p.id));for(let[p,d]of m)u.has(p)||(m.delete(p),d.run&&L(d).then(f=>{f&&t.reload()}));for(let p of i)m.has(p.id)||le(p)}function w(){let i=c();return!i&&!x||["t","a","r"].every(u=>i?.[u]===l?.[u])?!1:(l=i,E(),!0)}let ue={contract:1,plugins:r,set:ce,get:()=>b,allows:({consent:i})=>Y({state:b,consent:i}),subscribe:({listener:i})=>(C.add(i),()=>{C.delete(i)}),open:()=>{o.dispatchEvent(new CustomEvent(T))},setOpen:({open:i})=>{o.documentElement.toggleAttribute("data-consent-open",i)}};return r.subscribe({kind:k,listener:F}),F(r.list({kind:k})),e.plugins?.forEach(i=>r.registerPlugin(i,{source:"page"})),E(),o.addEventListener("visibilitychange",()=>{o.visibilityState==="visible"&&w()}),o.defaultView?.addEventListener("pageshow",w),l?.q&&l.p===e.policy&&q(l),ue}function N(e){return{doc:e.document,fetch:e.fetch.bind(e),now:Date.now,reload:()=>e.location.reload(),gpc:()=>e.navigator.globalPrivacyControl===!0||e.navigator.doNotTrack==="1",importModule:t=>import(t)}}function ie(e){try{return JSON.parse(e.getElementById(B)?.textContent??"")}catch{return null}}function Re(e=window,{ports:t=N(e),bindBanner:n}={}){if(e.jiniConsent)return e.jiniConsent;let o=e.document,r=ie(o);if(r)return re(e,r,{ports:t,bindBanner:n})}function re(e,t,{ports:n=N(e),bindBanner:o}){let r=e.document,a=Pe({config:t,ports:n},{evidence:t.evidence}),m=Array.isArray(e.jiniConsentQueue)?e.jiniConsentQueue:[];return e.jiniConsent=a,e.jiniConsentQueue={push:(...C)=>C.forEach(g=>a.plugins.registerPlugin(g,{source:"queue"}))},e.jiniConsentQueue.push(...m),ne({api:a,doc:r}),t.banner==="jini"&&o?.({api:a,doc:r}),r.dispatchEvent(new CustomEvent(J,{detail:a})),a}async function se({win:e},t={}){if(e.jiniConsent)return e.jiniConsent;let n=ie(e.document);if(!n||n.banner==="off")return;if(!n.context)return Re(e,t);let o=t.ports??N(e);try{let r=await o.fetch(n.context,{credentials:"same-origin",cache:"no-store"}).then(a=>a.ok?a.json():null);if(!we(r))return;if(r.policy!==n.policy){Oe({win:e,policy:n.policy,reload:o.reload});return}return re(e,{...n,regionMode:r.regionMode},{...t,ports:o})}catch{return}}function Oe({win:e,policy:t,reload:n}){try{let o=`jini-consent-reload:${t}`;if(e.sessionStorage.getItem(o))return;e.sessionStorage.setItem(o,"1"),n()}catch{}}function we(e){let t=e;return t?.enabled===!0&&typeof t.policy=="string"&&["auto","opt-in","opt-out"].includes(String(t.regionMode))}se({win:window});})();
@@ -1,6 +1,7 @@
1
1
  /** @file @jini-ai/cookie-consent contract: the only module a banner, plugin or host feature needs to import.
2
2
  * Types and constants only. Every call that injects something takes (required, optional): the first
3
3
  * argument is an object of required fields/ports, the second an object of optional ones. */
4
+ import type { ConsentAppearanceTokens } from './render/css.js';
4
5
  export declare const CONTRACT: 1;
5
6
  /** Separate from the CMS engine's HttpOnly jini_consent: browsers cannot overwrite that cookie. */
6
7
  export declare const CONSENT_COOKIE = "jini_choices";
@@ -70,6 +71,32 @@ export interface ConsentState {
70
71
  at: number | null;
71
72
  receipt: ReceiptStatus;
72
73
  }
74
+ /** Saved host policy. Existing revisions keep their field names when execution moves to declarations. */
75
+ export interface ConsentConfig {
76
+ enabled: boolean;
77
+ /** @deprecated Retained for saved-setting compatibility; declared scripts do not evaluate this flag. */
78
+ allowUnsafeEval?: boolean;
79
+ regionMode: 'auto' | RegionMode;
80
+ policyVersion: string;
81
+ privacyPolicyUrl: string;
82
+ title: string;
83
+ message: string;
84
+ acceptLabel: string;
85
+ rejectLabel: string;
86
+ preferencesLabel: string;
87
+ placement?: 'bottom-bar' | 'bottom-left' | 'bottom-right' | 'top-bar';
88
+ reopen?: 'corner' | 'link';
89
+ secondaryLinkLabel?: string;
90
+ secondaryLinkUrl?: string;
91
+ appearance?: ConsentAppearanceTokens;
92
+ customCss?: string;
93
+ bannerMode?: BannerMode;
94
+ }
95
+ /** Internal delivery evidence; never an analytics property or visitor identity. */
96
+ export interface ConsentAnalyticsProof {
97
+ receiptId: string;
98
+ policyVersion: string;
99
+ }
73
100
  export interface Contribution<K extends string = string> {
74
101
  readonly id: string;
75
102
  readonly kind: K;
@@ -161,6 +188,18 @@ export interface HeaderRegion extends Contribution<typeof REGION_KIND> {
161
188
  header: string;
162
189
  usValues?: readonly string[];
163
190
  }
191
+ export declare const BRIDGE_KIND = "consent-bridge";
192
+ export interface ConsentBridge extends Contribution<typeof BRIDGE_KIND> {
193
+ src?: string;
194
+ mount?(required: {
195
+ api: JiniConsentApi;
196
+ doc: Document;
197
+ }, optional?: object): void | (() => void);
198
+ }
199
+ export interface DeclaredScript {
200
+ src: string;
201
+ consent?: readonly Category[];
202
+ }
164
203
  export interface ClientConfig {
165
204
  contract: 1;
166
205
  policy: string;
@@ -168,17 +207,22 @@ export interface ClientConfig {
168
207
  banner: BannerMode;
169
208
  /** LazyAdapter entries and any future browser kinds; unknown kinds wait for their slot. */
170
209
  plugins?: readonly RawContribution[];
210
+ scripts?: readonly DeclaredScript[];
171
211
  maxAgeDays?: number;
172
212
  cookieDomain?: string;
173
213
  }
174
214
  /** What #jini-consent-config holds: the config plus the evidence mode the host chose. */
175
215
  export type PageConfig = ClientConfig & {
176
216
  evidence?: Evidence;
217
+ context?: string;
177
218
  };
178
219
  export interface JiniConsentApi {
179
220
  readonly contract: 1;
180
221
  readonly plugins: PluginRegistry;
181
222
  get(): ConsentState;
223
+ allows(required: {
224
+ consent?: readonly Category[];
225
+ }, optional?: object): boolean;
182
226
  subscribe(required: {
183
227
  listener: (state: ConsentState) => void;
184
228
  }, optional?: object): () => void;
package/dist/contract.js CHANGED
@@ -1,6 +1,3 @@
1
- /** @file @jini-ai/cookie-consent contract: the only module a banner, plugin or host feature needs to import.
2
- * Types and constants only. Every call that injects something takes (required, optional): the first
3
- * argument is an object of required fields/ports, the second an object of optional ones. */
4
1
  export const CONTRACT = 1;
5
2
  /** Separate from the CMS engine's HttpOnly jini_consent: browsers cannot overwrite that cookie. */
6
3
  export const CONSENT_COOKIE = 'jini_choices';
@@ -23,4 +20,5 @@ export const BANNER_MODES = ['jini', 'headless', 'off'];
23
20
  export const ADAPTER_KIND = 'consent-adapter';
24
21
  // ---- Slot kind: server region resolver ----
25
22
  export const REGION_KIND = 'region-resolver';
23
+ export const BRIDGE_KIND = 'consent-bridge';
26
24
  //# sourceMappingURL=contract.js.map
@@ -0,0 +1,29 @@
1
+ /** @file Pure rules for a plugin's cookie-consent contribution file (schema 2: one open
2
+ * `contributions` list of `{ kind, id, … }`): region readers, browser bridges and declared scripts.
3
+ * Data only; no plugin code runs. Kinds this file doesn't know are skipped, not refused. Loading,
4
+ * activation and which plugin may supply trusted region readers stay with the host. */
5
+ import type { RawContribution } from '../contract.js';
6
+ /** Parse one schema-2 file into region readers and browser bridge declarations. Pure. @complexity O(entries). */
7
+ export declare function parseConsentContributions({ raw }: {
8
+ raw: string;
9
+ }, _optional?: {}): {
10
+ ok: true;
11
+ descriptors: RawContribution[];
12
+ } | {
13
+ ok: false;
14
+ reason: string;
15
+ };
16
+ /** Accept only data and a served HTTP(S) or site-relative module URL; no inline code or URL schemes.
17
+ * O(URL bytes); this never resolves or reads the module on the server. */
18
+ export declare function consentBridgeContribution({ entry }: {
19
+ entry: RawContribution;
20
+ }, _optional?: {}): RawContribution | undefined;
21
+ /** Validate one recognized contribution so the lifecycle returns an explicit refusal, not a silent drop. */
22
+ export declare function declaredScriptsContribution({ pluginId, entry }: {
23
+ pluginId: string;
24
+ entry: RawContribution;
25
+ }, _optional?: {}): {
26
+ pluginId: string;
27
+ entry: RawContribution;
28
+ } | string;
29
+ //# sourceMappingURL=consent-file.d.ts.map
@@ -0,0 +1,62 @@
1
+ import { validateScripts } from './scripts.js';
2
+ /** Parse one schema-2 file into region readers and browser bridge declarations. Pure. @complexity O(entries). */
3
+ export function parseConsentContributions({ raw }, _optional = {}) {
4
+ let file;
5
+ try {
6
+ file = JSON.parse(raw);
7
+ }
8
+ catch {
9
+ return { ok: false, reason: 'not JSON' };
10
+ }
11
+ const { schemaVersion, contributions } = (file ?? {});
12
+ if (schemaVersion !== 2 || !Array.isArray(contributions))
13
+ return { ok: false, reason: 'expected { "schemaVersion": 2, "contributions": [...] }' };
14
+ const descriptors = contributions.filter(isConsentContribution);
15
+ return { ok: true, descriptors };
16
+ }
17
+ function isConsentContribution(item) {
18
+ if (!item || typeof item !== 'object')
19
+ return false;
20
+ const entry = item;
21
+ if (entry.kind === 'declared-scripts')
22
+ return true;
23
+ if (typeof entry.id !== 'string')
24
+ return false;
25
+ return entry.kind === 'region-resolver' || consentBridgeContribution({ entry }) !== undefined;
26
+ }
27
+ /** Accept only data and a served HTTP(S) or site-relative module URL; no inline code or URL schemes.
28
+ * O(URL bytes); this never resolves or reads the module on the server. */
29
+ export function consentBridgeContribution({ entry }, _optional = {}) {
30
+ if (entry.kind !== 'consent-bridge' || !servedUrl(entry.src))
31
+ return undefined;
32
+ return { id: entry.id, kind: 'consent-bridge', src: entry.src };
33
+ }
34
+ function servedUrl(src) {
35
+ if (typeof src !== 'string' || /[\\\s]/.test(src))
36
+ return false;
37
+ const relative = src.startsWith('/') && !src.startsWith('//');
38
+ if (!relative && !/^https?:\/\//i.test(src))
39
+ return false;
40
+ try {
41
+ const url = new URL(src, 'https://site.invalid');
42
+ return !url.username && !url.password;
43
+ }
44
+ catch {
45
+ return false;
46
+ }
47
+ }
48
+ /** Validate one recognized contribution so the lifecycle returns an explicit refusal, not a silent drop. */
49
+ export function declaredScriptsContribution({ pluginId, entry }, _optional = {}) {
50
+ if (typeof entry.id !== 'string' || !/^[a-z0-9][a-z0-9._:-]{0,63}$/.test(entry.id))
51
+ return `Script declarations from '${pluginId}' have an invalid contribution id.`;
52
+ const checked = validateScripts({ scripts: entry.scripts });
53
+ const label = `Script declarations '${entry.id}' from '${pluginId}'`;
54
+ if (entry.scripts === undefined)
55
+ return `${label} need a scripts array.`;
56
+ if (checked.problems.length)
57
+ return `${label} were refused: ${checked.problems.join('; ')}.`;
58
+ if (checked.scripts.some(script => !servedUrl(script.src)))
59
+ return `${label} need already-served HTTP(S) or site-relative URLs; unresolved relative paths are not supported.`;
60
+ return { pluginId, entry: { id: entry.id, kind: entry.kind, scripts: checked.scripts } };
61
+ }
62
+ //# sourceMappingURL=consent-file.js.map
@@ -0,0 +1,15 @@
1
+ /** Declared assets are data; no HTML or script body is inspected. */
2
+ import { type Category, type ConsentState, type DeclaredScript } from '../contract.js';
3
+ /** All purposes must be effectively allowed, including receipt and privacy-signal restrictions. */
4
+ export declare function allows({ state, consent }: {
5
+ state: Pick<ConsentState, 'allowed'>;
6
+ consent?: readonly Category[] | undefined;
7
+ }, _optional?: {}): boolean;
8
+ /** Malformed declarations never become executable assets; diagnostics identify their array position. */
9
+ export declare function validateScripts({ scripts }: {
10
+ scripts: unknown;
11
+ }, _optional?: {}): {
12
+ scripts: DeclaredScript[];
13
+ problems: string[];
14
+ };
15
+ //# sourceMappingURL=scripts.d.ts.map
@@ -0,0 +1,43 @@
1
+ /** Declared assets are data; no HTML or script body is inspected. */
2
+ import { CATEGORIES } from '../contract.js';
3
+ /** All purposes must be effectively allowed, including receipt and privacy-signal restrictions. */
4
+ export function allows({ state, consent = [] }, _optional = {}) {
5
+ return consent.every(category => CATEGORIES.includes(category) && state.allowed[category] === true);
6
+ }
7
+ function validSrc(src) {
8
+ if (!/^(?:https?:\/\/|\/(?!\/)|\.\.?\/)/.test(src))
9
+ return false;
10
+ try {
11
+ return ['http:', 'https:'].includes(new URL(src, 'https://declared.invalid').protocol);
12
+ }
13
+ catch {
14
+ return false;
15
+ }
16
+ }
17
+ function validScript(value) {
18
+ if (!value || typeof value !== 'object')
19
+ return false;
20
+ const { src, consent } = value;
21
+ if (typeof src !== 'string' || !src.trim() || /[\s\\]/.test(src))
22
+ return false;
23
+ if (!validSrc(src))
24
+ return false;
25
+ return consent === undefined || Array.isArray(consent) && consent.every(c => CATEGORIES.includes(c));
26
+ }
27
+ /** Malformed declarations never become executable assets; diagnostics identify their array position. */
28
+ export function validateScripts({ scripts }, _optional = {}) {
29
+ if (scripts === undefined)
30
+ return { scripts: [], problems: [] };
31
+ if (!Array.isArray(scripts))
32
+ return { scripts: [], problems: ['scripts must be an array'] };
33
+ const accepted = [];
34
+ const problems = [];
35
+ scripts.forEach((entry, index) => {
36
+ if (validScript(entry))
37
+ accepted.push({ src: entry.src, ...(entry.consent && { consent: [...entry.consent] }) });
38
+ else
39
+ problems.push(`scripts[${index}] needs an HTTP(S) or relative src and known consent categories`);
40
+ });
41
+ return { scripts: accepted, problems };
42
+ }
43
+ //# sourceMappingURL=scripts.js.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=extensions.min.d.ts.map
@@ -0,0 +1 @@
1
+ "use strict";(()=>{var x="jini:consent-ready",S="jini:consent-open",v="jini-consent-config",g=["functional","analytics","marketing"],m=["necessary",...g];var u="consent-bridge";function f({state:e,consent:t=[]},n={}){return t.every(o=>m.includes(o)&&e.allowed[o]===!0)}function O(e){if(!/^(?:https?:\/\/|\/(?!\/)|\.\.?\/)/.test(e))return!1;try{return["http:","https:"].includes(new URL(e,"https://declared.invalid").protocol)}catch{return!1}}function w(e){if(!e||typeof e!="object")return!1;let{src:t,consent:n}=e;return typeof t!="string"||!t.trim()||/[\s\\]/.test(t)||!O(t)?!1:n===void 0||Array.isArray(n)&&n.every(o=>m.includes(o))}function E({scripts:e},t={}){if(e===void 0)return{scripts:[],problems:[]};if(!Array.isArray(e))return{scripts:[],problems:["scripts must be an array"]};let n=[],o=[];return e.forEach((a,i)=>{w(a)?n.push({src:a.src,...a.consent&&{consent:[...a.consent]}}):o.push(`scripts[${i}] needs an HTTP(S) or relative src and known consent categories`)}),{scripts:n,problems:o}}function N(e){let t={};for(let n of g){let o=e.querySelector(`input[name="${n}"]`);o&&(t[n]=o.checked)}return t}function y(e,t){for(let n of g){let o=e.querySelector(`input[name="${n}"]`);o&&(o.checked=t.choices[n],o.disabled=t.gpc&&n!=="functional")}}var C=e=>g.some(t=>e.choices[t]&&!e.allowed[t]);function h({api:e,doc:t}){let n=t.getElementById("jini-consent");if(!n)return;let o=n.querySelector("[data-consent-error]"),a=r=>{n.hidden=!r,e.setOpen({open:r})},i=r=>{o&&(o.hidden=!C(r)),C(r)||a(!1)};n.addEventListener("click",r=>{let s=r.target.closest?.("[data-consent-action]")?.dataset.consentAction;s&&(r.preventDefault(),e.set({action:s},{choices:N(n)}).then(i))}),n.addEventListener("keydown",r=>{r.key==="Escape"&&e.get().status==="set"&&a(!1)}),t.addEventListener(S,()=>{y(n,e.get()),a(!0),n.querySelector("button")?.focus()}),e.subscribe({listener:r=>{y(n,r),o&&!o.hidden&&!C(r)&&i(r)}}),y(n,e.get()),a(e.get().status==="pending")}function A({doc:e,reload:t},n={}){let o=[...e.querySelectorAll("iframe[data-src][data-jini-consent]")].map(i=>({node:i,consent:P(i),started:!1})),a=!1;return i=>{if(a)return;let r=o.filter(s=>s.started&&!f({state:i,consent:s.consent}));if(r.length){a=!0,r.forEach(s=>s.node.removeAttribute("src")),t();return}o.forEach(s=>{s.started||!f({state:i,consent:s.consent})||(s.started=!0,s.node.setAttribute("src",s.node.dataset.src))})}}function P(e){try{let t=JSON.parse(e.dataset.jiniConsent);if(Array.isArray(t))return t}catch{}return["invalid"]}var j={kind:u,accept:({contribution:e})=>typeof e.mount=="function"||typeof e.src=="string"?e:"mount() or module src needed"};function L(e){e.disposed=!0;try{e.dispose?.()}catch{}}function R({api:e,doc:t},n={}){let o=new Map;function a(i){for(let[r,s]of o)i.some(d=>d.id===r)||(L(s),o.delete(r));for(let r of i){if(o.has(r.id))continue;let s={disposed:!1,dispose:void 0};o.set(r.id,s);let d=c=>{if(!s.disposed)try{let l=c.mount?.({api:e,doc:t});typeof l=="function"&&(s.dispose=l)}catch{}};r.mount?d(r):import(r.src).then(c=>d(c.default)).catch(()=>{})}}e.plugins.defineSlot({slot:j}),e.plugins.subscribe({kind:u,listener:i=>a(i)}),a(e.plugins.list({kind:u}))}function D({doc:e,scripts:t,reload:n},o={}){let a=E({scripts:t}).scripts.map(c=>({script:c,started:!1,node:null})),i=null,r,s=!1;function d(){if(i||s)return;let c=a.find(b=>!b.started&&f({state:r,consent:b.script.consent}));if(!c)return;c.started=!0;let l=e.createElement("script");c.node=i=l,l.async=!1,l.src=c.script.src;let p=()=>{i===l&&(i=null),d()};l.onload=p,l.onerror=p,e.head.append(l)}return c=>{r=c;let l=a.filter(p=>p.started&&!f({state:c,consent:p.script.consent}));l.length&&!s&&(s=!0,l.forEach(p=>p.node?.remove()),n()),d()}}var k=Symbol.for("jini-consent:features");function I({api:e,doc:t,config:n,reload:o},{bindBanner:a}={}){if(Object.prototype.hasOwnProperty.call(e,k))return;Object.defineProperty(e,k,{value:!0});let i=M({doc:t,config:n,reload:o});e.subscribe({listener:i}),i(e.get()),R({api:e,doc:t}),n.banner==="jini"&&a&&e.plugins.registerPlugin({id:"jini-banner",kind:u,mount:a})}function M({doc:e,config:t,reload:n}){let o=!1,a=!1,i=()=>{o=!0},r=D({doc:e,scripts:t.scripts??[],reload:i}),s=A({doc:e,reload:i});return d=>{s(d),r(d),!(!o||a)&&(a=!0,n())}}function T(){let e=window.jiniConsent;if(e)try{let t=JSON.parse(document.getElementById(v)?.textContent??"");I({api:e,doc:document,config:t,reload:()=>location.reload()},{bindBanner:h})}catch{}}document.addEventListener(x,T);T();})();
package/dist/plugins.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  /** Compatibility entry; the shared implementation serves browser and server consumers. */
2
2
  export * from './contracts/plugins.js';
3
+ export { consentBridgeContribution, declaredScriptsContribution, parseConsentContributions } from './contracts/consent-file.js';
3
4
  //# sourceMappingURL=plugins.d.ts.map