@jini-ai/cookie-consent 0.7.2 → 0.7.3-next.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,53 @@
1
+ import { type ChangeEvent, type FocusEvent } from 'react';
2
+ import type { ConsentAppearanceView, ConsentFieldProblem, ConsentSettingsPanelProps, ConsentSettingsView } from './ConsentSettingsPanel.js';
3
+ /** Resolve host-supplied copy, falling back to the original text. */
4
+ export declare function createConsentTranslator({ dictionary }: {
5
+ dictionary?: Readonly<Record<string, string>> | undefined;
6
+ }, _options?: {}): (text: string) => string;
7
+ /** Keep value conversions and toggle behavior out of the view. React owns event signatures. */
8
+ export declare function useConsentSettingsPanel({ value, onChange }: Pick<ConsentSettingsPanelProps, 'value' | 'onChange'>, _options?: {}): {
9
+ toggle: () => void;
10
+ bannerMode: ({ mode }: {
11
+ mode: NonNullable<ConsentSettingsView["bannerMode"]>;
12
+ }, _optional?: {}) => () => void;
13
+ region: (event: ChangeEvent<HTMLSelectElement>) => void;
14
+ placement: (event: ChangeEvent<HTMLSelectElement>) => void;
15
+ text: (key: keyof ConsentSettingsView) => (event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
16
+ /** Empty input unsets the token so the engine default applies again. */
17
+ token: (key: keyof ConsentAppearanceView) => (next: string) => void;
18
+ };
19
+ /** A new token object with `key` set, or removed when `value` is empty. Never mutates the input.
20
+ * @complexity O(t), t <= 7 tokens. */
21
+ export declare function withAppearanceToken({ appearance, key, value }: {
22
+ appearance?: ConsentAppearanceView | undefined;
23
+ key: keyof ConsentAppearanceView;
24
+ value: string;
25
+ }, _options?: {}): ConsentAppearanceView;
26
+ /** `"12px"` → `"12"` for a number input; unset or hand-written values read empty. */
27
+ export declare function pixelInputValue({ value }: {
28
+ value: string | undefined;
29
+ }, _options?: {}): string;
30
+ /** The problems a host attached to one field, in their original order. O(p). */
31
+ export declare function problemsFor({ problems, field }: {
32
+ problems?: readonly ConsentFieldProblem[] | undefined;
33
+ field: string;
34
+ }, _options?: {}): ConsentFieldProblem[];
35
+ /** Keep transient empty edits local; only a valid policy version reaches autosave.
36
+ * Native validity gives keyboard users an actionable error. Valid edits save before navigation.
37
+ * @complexity O(version length), <=128. */
38
+ export declare function usePolicyVersionInput({ value, onChange }: Pick<ConsentSettingsPanelProps, 'onChange'> & {
39
+ value: string;
40
+ }, _options?: {}): {
41
+ draft: string;
42
+ change: (event: ChangeEvent<HTMLInputElement>) => void;
43
+ blur: (event: FocusEvent<HTMLInputElement>) => void;
44
+ };
45
+ export type ConsentPreviewWidth = 'phone' | 'desktop';
46
+ /** The preview's own phone/desktop switch; the host never needs to own it. */
47
+ export declare function useConsentPreviewWidth({ initial }?: {
48
+ initial?: ConsentPreviewWidth;
49
+ }, _options?: {}): {
50
+ width: ConsentPreviewWidth;
51
+ setWidth: import("react").Dispatch<import("react").SetStateAction<ConsentPreviewWidth>>;
52
+ };
53
+ //# sourceMappingURL=settings-panel.hooks.d.ts.map
@@ -0,0 +1,61 @@
1
+ import { useEffect, useState } from 'react';
2
+ /** Resolve host-supplied copy, falling back to the original text. */
3
+ export function createConsentTranslator({ dictionary = {} }, _options = {}) {
4
+ return (text) => dictionary[text] ?? text;
5
+ }
6
+ /** Keep value conversions and toggle behavior out of the view. React owns event signatures. */
7
+ export function useConsentSettingsPanel({ value, onChange }, _options = {}) {
8
+ return {
9
+ toggle: () => onChange({ patch: { enabled: !value.enabled } }),
10
+ bannerMode: ({ mode }, _optional = {}) => () => onChange({ patch: { bannerMode: mode } }),
11
+ region: (event) => onChange({ patch: { regionMode: event.target.value } }),
12
+ placement: (event) => onChange({ patch: { placement: event.target.value } }),
13
+ text: (key) => (event) => onChange({ patch: { [key]: event.target.value } }),
14
+ /** Empty input unsets the token so the engine default applies again. */
15
+ token: (key) => (next) => onChange({ patch: { appearance: withAppearanceToken({ appearance: value.appearance, key, value: next }) } }),
16
+ };
17
+ }
18
+ /** A new token object with `key` set, or removed when `value` is empty. Never mutates the input.
19
+ * @complexity O(t), t <= 7 tokens. */
20
+ export function withAppearanceToken({ appearance = {}, key, value }, _options = {}) {
21
+ const next = { ...appearance };
22
+ if (value === '')
23
+ delete next[key];
24
+ else
25
+ next[key] = value;
26
+ return next;
27
+ }
28
+ /** `"12px"` → `"12"` for a number input; unset or hand-written values read empty. */
29
+ export function pixelInputValue({ value }, _options = {}) {
30
+ return /^(\d+(?:\.\d+)?)px$/.exec(value ?? '')?.[1] ?? '';
31
+ }
32
+ /** The problems a host attached to one field, in their original order. O(p). */
33
+ export function problemsFor({ problems = [], field }, _options = {}) {
34
+ return problems.filter(problem => problem.field === field);
35
+ }
36
+ /** Keep transient empty edits local; only a valid policy version reaches autosave.
37
+ * Native validity gives keyboard users an actionable error. Valid edits save before navigation.
38
+ * @complexity O(version length), <=128. */
39
+ export function usePolicyVersionInput({ value, onChange }, _options = {}) {
40
+ const [draft, setDraft] = useState(value);
41
+ useEffect(() => setDraft(value), [value]);
42
+ return {
43
+ draft,
44
+ change: (event) => {
45
+ const next = event.currentTarget.value;
46
+ setDraft(next);
47
+ if (event.currentTarget.checkValidity())
48
+ onChange({ patch: { policyVersion: next } });
49
+ },
50
+ blur: (event) => {
51
+ if (!event.currentTarget.checkValidity())
52
+ event.currentTarget.reportValidity();
53
+ },
54
+ };
55
+ }
56
+ /** The preview's own phone/desktop switch; the host never needs to own it. */
57
+ export function useConsentPreviewWidth({ initial = 'desktop' } = {}, _options = {}) {
58
+ const [width, setWidth] = useState(initial);
59
+ return { width, setWidth };
60
+ }
61
+ //# sourceMappingURL=settings-panel.hooks.js.map
@@ -56,9 +56,11 @@ export interface RenderedBanner {
56
56
  problems: ConsentCssProblem[];
57
57
  }
58
58
  /** Refuse executable/data/protocol-relative links; local pages are the common case. @complexity O(url length). */
59
- export declare function safeHref(url: string | undefined): string | null;
59
+ export declare function safeHref({ url }: {
60
+ url: string | undefined;
61
+ }, _optional?: Record<string, never>): string | null;
60
62
  /** Owner copy over the defaults; a non-string field falls back instead of rendering "undefined". */
61
- export declare function resolveCopy(input?: BannerCopyInput): BannerCopy;
63
+ export declare function resolveCopy(input?: BannerCopyInput, _optional?: Record<string, never>): BannerCopy;
62
64
  /** @example renderBanner({ mode: 'jini', client: { contract: 1, policy: '2026-10-26', regionMode: 'auto' }, copy: {} }, { clientSrc: '/consent/client.min.js', evidence: { mode: 'local' } })
63
65
  * @complexity O(copy + CSS length). */
64
66
  export declare function renderBanner({ mode, client, copy }: RenderBannerConfig, options?: RenderBannerOptions): RenderedBanner;
@@ -21,7 +21,7 @@ const json = (v) => JSON.stringify(v).replace(/</g, '\\u003c');
21
21
  const EMPTY = Object.freeze({ head: '', body: '', htmlAttrs: '', problems: [] });
22
22
  // MOVED-FROM: @jini-ai/cms consent/html/render.ts consentPolicyHref. Follow-up (P4): delete the cms copy.
23
23
  /** Refuse executable/data/protocol-relative links; local pages are the common case. @complexity O(url length). */
24
- export function safeHref(url) {
24
+ export function safeHref({ url }, _optional = {}) {
25
25
  if (!url)
26
26
  return null;
27
27
  if (/^\/(?!\/)/.test(url) && !/[\\\x00-\x20]/.test(url))
@@ -35,7 +35,7 @@ export function safeHref(url) {
35
35
  }
36
36
  }
37
37
  /** Owner copy over the defaults; a non-string field falls back instead of rendering "undefined". */
38
- export function resolveCopy(input = {}) {
38
+ export function resolveCopy(input = {}, _optional = {}) {
39
39
  const pick = (base, over) => Object.fromEntries(Object.entries(base).map(([k, v]) => [k, typeof over?.[k] === 'string' ? over[k] : v]));
40
40
  const { categoryLabels, ...rest } = DEFAULT_COPY;
41
41
  const merged = pick(rest, input);
@@ -75,8 +75,8 @@ function previewAttrs(preview) {
75
75
  return `data-consent="pending" data-consent-region="${preview.region === 'opt-out' ? 'opt-out' : 'opt-in'}" data-consent-open`;
76
76
  }
77
77
  function links(copy) {
78
- const privacy = safeHref(copy.privacyPolicyUrl);
79
- const second = safeHref(copy.secondaryLinkUrl);
78
+ const privacy = safeHref({ url: copy.privacyPolicyUrl });
79
+ const second = safeHref({ url: copy.secondaryLinkUrl });
80
80
  const items = [privacy ? `<a href="${esc(privacy)}">${esc(copy.privacyLabel)}</a>` : '',
81
81
  second && copy.secondaryLinkLabel ? `<a href="${esc(second)}">${esc(copy.secondaryLinkLabel)}</a>` : ''].filter(Boolean);
82
82
  return items.length ? `<p class="jini-consent-links">${items.join(' · ')}</p>` : '';
@@ -30,14 +30,16 @@ declare const DEFAULT_COLORS: {
30
30
  };
31
31
  type Colors = typeof DEFAULT_COLORS;
32
32
  /** Normalized selector, or null when it leaves the banner scope or could break Reject parity. @complexity O(selector length). */
33
- export declare function scopedSelector(selector: string): string | null;
33
+ export declare function scopedSelector({ selector }: {
34
+ selector: string;
35
+ }, _optional?: Record<string, never>): string | null;
34
36
  /** Engine-owned lock after all customization: the banner stays visible and on top, Reject and Accept share
35
37
  * one fill and border, controls inherit the root's validated colors, and the region/GPC variants are
36
38
  * CSS-toggled from <html> attributes so the markup is the same for every visitor. Unknown region = strict:
37
39
  * the opt-in variant (with Reject) shows unless the client has positively set opt-out. @complexity O(1). */
38
40
  export declare function parityCss({ colors }: {
39
41
  colors: Colors | null;
40
- }): string;
42
+ }, _optional?: Record<string, never>): string;
41
43
  /** Validate/compile the banner appearance for both the admin preview and delivery. Tokens render first, then
42
44
  * owner CSS, then the engine parity block. Each bad rule is dropped and reported; the rest applies.
43
45
  * @example compileConsentCss({ css: '#jini-consent button{font-weight:700}', tokens: { backgroundColor: '#101820', textColor: '#ffffff' } })
@@ -105,7 +105,7 @@ function hasContrast({ background, text }) {
105
105
  const COMPOUND = /^(?:[a-z][a-z0-9-]*|\*)?(?:[.#][a-z][\w-]*)*(?::(?:hover|focus|focus-visible|focus-within|active))?$/i;
106
106
  const ROOTS = /^(?:#jini-consent|\.jini-consent|\.jini-consent-reopen)(?=$|[\s>:])/;
107
107
  /** Normalized selector, or null when it leaves the banner scope or could break Reject parity. @complexity O(selector length). */
108
- export function scopedSelector(selector) {
108
+ export function scopedSelector({ selector }, _optional = {}) {
109
109
  const normalized = selector.trim().split('>').map(part => part.trim()).join(' > ').replace(/\s+/g, ' ');
110
110
  if (!ROOTS.test(normalized))
111
111
  return null;
@@ -133,7 +133,7 @@ function declarationProblem({ declaration, selector, media }) {
133
133
  function ruleProblems(rule) {
134
134
  const problems = [];
135
135
  for (const raw of rule.selector.split(',')) {
136
- const selector = scopedSelector(raw);
136
+ const selector = scopedSelector({ selector: raw });
137
137
  if (!selector) {
138
138
  problems.push({ code: 'selector', message: `"${raw.trim()}" must start with #jini-consent and may not use attribute, structural or sibling selectors (Accept and Reject must look alike).`, offset: rule.offset, selector: raw.trim() });
139
139
  continue;
@@ -154,7 +154,7 @@ function tokenRule(tokens) {
154
154
  }));
155
155
  return { selector: CONSENT_CSS_SCOPE, declarations, offset: 0 };
156
156
  }
157
- const isRoot = (rule) => rule.media === undefined && rule.selector.split(',').some(s => scopedSelector(s) === CONSENT_CSS_SCOPE);
157
+ const isRoot = (rule) => rule.media === undefined && rule.selector.split(',').some(s => scopedSelector({ selector: s }) === CONSENT_CSS_SCOPE);
158
158
  /** Last root color declaration wins, matching the emitted cascade. Null = no customized color, so the theme
159
159
  * colors of the base styles stay in charge; one customized side is checked against the default other side.
160
160
  * @complexity O(declarations). */
@@ -172,7 +172,7 @@ function finalColors(rules) {
172
172
  * one fill and border, controls inherit the root's validated colors, and the region/GPC variants are
173
173
  * CSS-toggled from <html> attributes so the markup is the same for every visitor. Unknown region = strict:
174
174
  * the opt-in variant (with Reject) shows unless the client has positively set opt-out. @complexity O(1). */
175
- export function parityCss({ colors }) {
175
+ export function parityCss({ colors }, _optional = {}) {
176
176
  const root = CONSENT_CSS_SCOPE;
177
177
  // Derived text and button fills must use the same validated palette as the root.
178
178
  const rootColors = colors ? `--consent-bg:${colors.background}!important;--consent-fg:${colors.text}!important;background:${colors.background}!important;color:${colors.text}!important;` : '';
@@ -231,7 +231,7 @@ function withoutRootColors(rules) {
231
231
  }
232
232
  /** Emit only validated selectors/declarations, retaining their optional width condition. @complexity O(rule bytes). */
233
233
  function emitRule(rule) {
234
- const selectors = rule.selector.split(',').map(s => scopedSelector(s)).join(',');
234
+ const selectors = rule.selector.split(',').map(s => scopedSelector({ selector: s })).join(',');
235
235
  const declarations = rule.declarations.map(({ property, value }) => `${property}:${value}`).join(';');
236
236
  const css = `${selectors}{${declarations}}`;
237
237
  return rule.media === undefined ? css : `@media ${rule.media}{${css}}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/cookie-consent",
3
- "version": "0.7.2",
3
+ "version": "0.7.3-next.1",
4
4
  "description": "Standalone, vendor-free cookie consent: a consent-state contract any banner can drive, a ~3 KB browser client, a pure-string banner renderer with owner CSS, web-standard receipts and open plugin slots.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -23,12 +23,16 @@
23
23
  "./policy": "universal",
24
24
  "./plugins": "universal",
25
25
  "./render": "universal",
26
+ "./react": "browser",
26
27
  "./client": "browser",
27
28
  "./client.min.js": "browser",
28
29
  "./banner.css": "browser",
29
30
  "./server": "universal",
30
31
  "./node": "node",
31
32
  "./extensions.min.js": "browser"
33
+ },
34
+ "optionalPeers": {
35
+ "react": "opt-in: react consent settings; import @jini-ai/cookie-consent/react — React consent settings could not load react. Install react to enable this feature, or check its installed version."
32
36
  }
33
37
  },
34
38
  "type": "module",
@@ -59,6 +63,11 @@
59
63
  "import": "./dist/render/index.js",
60
64
  "default": "./dist/render/index.js"
61
65
  },
66
+ "./react": {
67
+ "types": "./dist/react/index.d.ts",
68
+ "import": "./dist/react/index.js",
69
+ "default": "./dist/react/index.js"
70
+ },
62
71
  "./client": {
63
72
  "types": "./dist/client/index.d.ts",
64
73
  "import": "./dist/client/index.js",
@@ -91,13 +100,27 @@
91
100
  },
92
101
  "dependencies": {},
93
102
  "devDependencies": {
103
+ "@testing-library/jest-dom": "^6.6.3",
104
+ "@testing-library/react": "^16.3.0",
105
+ "@testing-library/user-event": "^14.6.1",
94
106
  "@types/node": "^24.0.0",
107
+ "@types/react": "^19.2.0",
95
108
  "@vitest/coverage-v8": "^2.1.9",
96
109
  "esbuild": "^0.28.1",
97
110
  "jsdom": "^25.0.1",
111
+ "react": "^19.2.0",
112
+ "react-dom": "^19.2.0",
98
113
  "typescript": "^5.6.0",
99
114
  "vitest": "^2.1.0"
100
115
  },
116
+ "peerDependencies": {
117
+ "react": "^18.3.0 || ^19.0.0"
118
+ },
119
+ "peerDependenciesMeta": {
120
+ "react": {
121
+ "optional": true
122
+ }
123
+ },
101
124
  "scripts": {
102
125
  "build": "tsc -p tsconfig.json && node scripts/build-client.mjs",
103
126
  "typecheck": "tsc -p tsconfig.json --noEmit",