@jini-ai/cookie-consent 0.7.2 → 0.7.3-next.2

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.
@@ -24,153 +24,154 @@ function assertLimits({ maximumRecords, retentionMs }) {
24
24
  if (!Number.isFinite(retentionMs) || retentionMs < 0)
25
25
  throw new Error('Consent receipt retention must be nonnegative.');
26
26
  }
27
- /** Publish a flushed staging file with an exclusive hard link, then flush the directory on non-Windows hosts.
28
- * Filesystem/link failures propagate. No reader ever sees a partially-written proof file.
29
- * @complexity Startup O(r log r) time/O(r) space; subsequent writes amortized O(1) plus bounded receipt I/O. */
30
- export function createNodeConsentFiles({ atomicWrite }, { filesystem = fs, uniqueId = randomUUID, maximumRecords = 10000, retentionMs = CONSENT_MAX_AGE_MS, nowMs = Date.now, platform = process.platform } = {}) {
31
- assertLimits({ maximumRecords, retentionMs });
32
- const writes = new Map();
33
- const inventories = new Map();
34
- /** Keep active-file removal and publication in the same directory queue so scans cannot race unlink.
35
- * Operation failures propagate and invalidate only that directory's inventory. @complexity O(1) queue overhead. */
36
- async function serialize({ directory, operation }, _options = {}) {
37
- const pending = (writes.get(directory) ?? Promise.resolve()).catch(() => undefined).then(operation);
38
- writes.set(directory, pending);
39
- try {
40
- await pending;
41
- }
42
- catch (error) {
43
- inventories.delete(directory);
27
+ function isErrorCode({ error, code }) {
28
+ return typeof error === 'object' && error !== null && 'code' in error && error.code === code;
29
+ }
30
+ /** Keep active-file removal and publication in the same directory queue so scans cannot race unlink.
31
+ * Operation failures propagate and invalidate only that directory's inventory. @complexity O(1) queue overhead. */
32
+ async function serializeConsentWrite(env, { directory, operation }) {
33
+ const { writes, inventories } = env;
34
+ const pending = (writes.get(directory) ?? Promise.resolve()).catch(() => undefined).then(operation);
35
+ writes.set(directory, pending);
36
+ try {
37
+ await pending;
38
+ }
39
+ catch (error) {
40
+ inventories.delete(directory);
41
+ throw error;
42
+ }
43
+ finally {
44
+ if (writes.get(directory) === pending)
45
+ writes.delete(directory);
46
+ }
47
+ }
48
+ /** Serialize capacity checks/publication in this adapter. The host selects proof retention;
49
+ * cookie expiry is not a legal proof-erasure policy. This bounded default is configurable,
50
+ * and capacity eviction may shorten it; hosts needing longer proof retention must size accordingly.
51
+ * Scan once at startup, then maintain an oldest-first inventory rather than stat every save.
52
+ * @complexity Initial O(r log r); cached lookup O(1), pruning amortized O(1) per receipt. */
53
+ async function consentInventory(env, { directory }) {
54
+ const cached = env.inventories.get(directory);
55
+ if (cached)
56
+ return cached;
57
+ let names;
58
+ try {
59
+ names = await env.filesystem.readdir(directory);
60
+ }
61
+ catch (error) {
62
+ if (isErrorCode({ error, code: 'ENOENT' }))
63
+ names = [];
64
+ else
44
65
  throw error;
45
- }
46
- finally {
47
- if (writes.get(directory) === pending)
48
- writes.delete(directory);
49
- }
50
66
  }
51
- /** Serialize capacity checks/publication in this adapter. The host selects proof retention;
52
- * cookie expiry is not a legal proof-erasure policy. This bounded default is configurable,
53
- * and capacity eviction may shorten it; hosts needing longer proof retention must size accordingly.
54
- * Scan once at startup, then maintain an oldest-first inventory rather than stat every save.
55
- * @complexity Initial O(r log r); cached lookup O(1), pruning amortized O(1) per receipt. */
56
- async function inventory({ directory }, _options = {}) {
57
- const cached = inventories.get(directory);
58
- if (cached)
59
- return cached;
60
- let names;
67
+ const entries = [];
68
+ for (const name of names) {
69
+ if (RECEIPT_FILENAME.test(name))
70
+ entries.push([name, (await env.filesystem.stat(path.join(directory, name))).mtimeMs]);
71
+ }
72
+ entries.sort((left, right) => left[1] - right[1]);
73
+ const retained = new Map(entries);
74
+ env.inventories.set(directory, retained);
75
+ return retained;
76
+ }
77
+ /** Expiry and capacity remove only owned receipts; unrelated files stay intact. */
78
+ async function enforceConsentCapacity(env, { directory, retained }) {
79
+ const cutoff = env.nowMs() - env.retentionMs;
80
+ for (const [name, timestamp] of retained) {
81
+ if (retained.size < env.maximumRecords && timestamp >= cutoff)
82
+ break;
61
83
  try {
62
- names = await filesystem.readdir(directory);
84
+ await env.filesystem.unlink(path.join(directory, name));
63
85
  }
64
86
  catch (error) {
65
- if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
66
- names = [];
67
- else
87
+ if (!isErrorCode({ error, code: 'ENOENT' }))
68
88
  throw error;
69
89
  }
70
- const entries = [];
71
- for (const name of names) {
72
- if (RECEIPT_FILENAME.test(name))
73
- entries.push([name, (await filesystem.stat(path.join(directory, name))).mtimeMs]);
90
+ retained.delete(name);
91
+ }
92
+ }
93
+ async function syncConsentDirectory({ env, directoryPath }) {
94
+ if (env.platform === 'win32')
95
+ return;
96
+ const directory = await env.filesystem.open(directoryPath, 'r');
97
+ try {
98
+ await directory.sync();
99
+ }
100
+ finally {
101
+ await directory.close();
102
+ }
103
+ }
104
+ async function readConsentText({ filesystem }, { filePath }) {
105
+ try {
106
+ const handle = await filesystem.open(filePath, 'r');
107
+ try {
108
+ if ((await handle.stat()).size > 4096)
109
+ throw new Error('Consent receipt exceeds 4096 bytes.');
110
+ return await handle.readFile('utf8');
111
+ }
112
+ finally {
113
+ await handle.close();
74
114
  }
75
- entries.sort((left, right) => left[1] - right[1]);
76
- const retained = new Map(entries);
77
- inventories.set(directory, retained);
78
- return retained;
79
115
  }
80
- /** Expiry and capacity remove only owned receipts; unrelated files stay intact. */
81
- async function capacity({ directory, retained }, _options = {}) {
82
- const cutoff = nowMs() - retentionMs;
83
- for (const [name, timestamp] of retained) {
84
- if (retained.size < maximumRecords && timestamp >= cutoff)
85
- break;
116
+ catch (error) {
117
+ if (isErrorCode({ error, code: 'ENOENT' }))
118
+ return null;
119
+ throw error;
120
+ }
121
+ }
122
+ async function writeConsentJson(env, { filePath, record }) {
123
+ const directoryPath = path.dirname(filePath);
124
+ await serializeConsentWrite(env, { directory: directoryPath, operation: async () => {
125
+ if (JSON.stringify(record).length > 4096)
126
+ throw new Error('Consent receipt exceeds 4096 bytes.');
127
+ const retained = await consentInventory(env, { directory: directoryPath });
128
+ if (retained.has(path.basename(filePath)))
129
+ throw new Error('Consent receipt ID already exists.');
130
+ const staging = path.join(path.dirname(filePath), `.${path.basename(filePath)}.${env.uniqueId()}.pending`);
131
+ await env.atomicWrite({ filePath: staging, data: record }, { createParent: true, mode: 0o600, refuseSymlink: true });
86
132
  try {
87
- await filesystem.unlink(path.join(directory, name));
133
+ await enforceConsentCapacity(env, { directory: directoryPath, retained });
134
+ await env.filesystem.link(staging, filePath);
135
+ retained.set(path.basename(filePath), env.nowMs());
136
+ await syncConsentDirectory({ env, directoryPath: path.dirname(filePath) });
88
137
  }
89
- catch (error) {
90
- if (!(error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT'))
91
- throw error;
138
+ finally {
139
+ await env.filesystem.unlink(staging);
92
140
  }
93
- retained.delete(name);
94
- }
95
- }
96
- return {
97
- async retire({ filePath }, _options = {}) {
98
- const directoryPath = path.dirname(filePath);
99
- await serialize({ directory: directoryPath, operation: async () => {
100
- const text = await this.readText({ filePath });
101
- if (text === null)
102
- return;
103
- // Publish the archive durably before unlinking the active receipt. A crash can only leave
104
- // the old choice active before the replacement save has been acknowledged to the visitor.
105
- const archived = path.join(directoryPath, 'retired', path.basename(filePath));
106
- if (await this.readText({ filePath: archived }) === null)
107
- await this.writeJson({ filePath: archived, record: JSON.parse(text) });
108
- try {
109
- await filesystem.unlink(filePath);
110
- }
111
- catch (error) {
112
- if (!(error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT'))
113
- throw error;
114
- }
115
- inventories.get(directoryPath)?.delete(path.basename(filePath));
116
- if (platform !== 'win32') {
117
- const directory = await filesystem.open(directoryPath, 'r');
118
- try {
119
- await directory.sync();
120
- }
121
- finally {
122
- await directory.close();
123
- }
124
- }
125
- } });
126
- },
127
- async readText({ filePath }) {
141
+ } });
142
+ }
143
+ async function retireConsentFile({ env, filePath }) {
144
+ const directoryPath = path.dirname(filePath);
145
+ await serializeConsentWrite(env, { directory: directoryPath, operation: async () => {
146
+ const text = await readConsentText(env, { filePath });
147
+ if (text === null)
148
+ return;
149
+ // Publish the archive durably before unlinking the active receipt. A crash can only leave
150
+ // the old choice active before the replacement save has been acknowledged to the visitor.
151
+ const archived = path.join(directoryPath, 'retired', path.basename(filePath));
152
+ if (await readConsentText(env, { filePath: archived }) === null)
153
+ await writeConsentJson(env, { filePath: archived, record: JSON.parse(text) });
128
154
  try {
129
- const handle = await filesystem.open(filePath, 'r');
130
- try {
131
- if ((await handle.stat()).size > 4096)
132
- throw new Error('Consent receipt exceeds 4096 bytes.');
133
- return await handle.readFile('utf8');
134
- }
135
- finally {
136
- await handle.close();
137
- }
155
+ await env.filesystem.unlink(filePath);
138
156
  }
139
157
  catch (error) {
140
- if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT')
141
- return null;
142
- throw error;
158
+ if (!isErrorCode({ error, code: 'ENOENT' }))
159
+ throw error;
143
160
  }
144
- },
145
- async writeJson({ filePath, record }, _options = {}) {
146
- const directoryPath = path.dirname(filePath);
147
- await serialize({ directory: directoryPath, operation: async () => {
148
- if (JSON.stringify(record).length > 4096)
149
- throw new Error('Consent receipt exceeds 4096 bytes.');
150
- const retained = await inventory({ directory: directoryPath });
151
- if (retained.has(path.basename(filePath)))
152
- throw new Error('Consent receipt ID already exists.');
153
- const staging = path.join(path.dirname(filePath), `.${path.basename(filePath)}.${uniqueId()}.pending`);
154
- await atomicWrite({ filePath: staging, data: record }, { createParent: true, mode: 0o600, refuseSymlink: true });
155
- try {
156
- await capacity({ directory: directoryPath, retained });
157
- await filesystem.link(staging, filePath);
158
- retained.set(path.basename(filePath), nowMs());
159
- if (platform !== 'win32') {
160
- const directory = await filesystem.open(path.dirname(filePath), 'r');
161
- try {
162
- await directory.sync();
163
- }
164
- finally {
165
- await directory.close();
166
- }
167
- }
168
- }
169
- finally {
170
- await filesystem.unlink(staging);
171
- }
172
- } });
173
- },
161
+ env.inventories.get(directoryPath)?.delete(path.basename(filePath));
162
+ await syncConsentDirectory({ env, directoryPath });
163
+ } });
164
+ }
165
+ /** Publish a flushed staging file with an exclusive hard link, then flush the directory on non-Windows hosts.
166
+ * Filesystem/link failures propagate. No reader ever sees a partially-written proof file.
167
+ * @complexity Startup O(r log r) time/O(r) space; subsequent writes amortized O(1) plus bounded receipt I/O. */
168
+ export function createNodeConsentFiles({ atomicWrite }, { filesystem = fs, uniqueId = randomUUID, maximumRecords = 10000, retentionMs = CONSENT_MAX_AGE_MS, nowMs = Date.now, platform = process.platform } = {}) {
169
+ assertLimits({ maximumRecords, retentionMs });
170
+ const env = { atomicWrite, filesystem, uniqueId, maximumRecords, retentionMs, nowMs, platform, writes: new Map(), inventories: new Map() };
171
+ return {
172
+ retire: ({ filePath }, _options = {}) => retireConsentFile({ env, filePath }),
173
+ readText: ({ filePath }) => readConsentText(env, { filePath }),
174
+ writeJson: (required, _options = {}) => writeConsentJson(env, required),
174
175
  };
175
176
  }
176
177
  /** Per-site opaque filenames; IDs cannot navigate out of the configured proof directory.
@@ -0,0 +1,56 @@
1
+ import type { ConsentFieldProblem, ConsentSettingsView } from './ConsentSettingsPanel.js';
2
+ import { useConsentSettingsPanel, usePolicyVersionInput } from './settings-panel.hooks.js';
3
+ /**
4
+ * @file The consent settings split into the three sections a host can place on its own tabs:
5
+ * Banner (copy and links), Look (placement and appearance) and Rules (on/off, region, version).
6
+ * `ConsentSettingsPanel` stacks all three for hosts that want one screen. Every section is
7
+ * controlled: it renders `value`, reports edits as patches and shows the host's `problems` next to
8
+ * the field each one names. Hosts style the plain `jini-` classes.
9
+ */
10
+ type TextKey = 'title' | 'message' | 'acceptLabel' | 'rejectLabel' | 'preferencesLabel' | 'privacyPolicyUrl' | 'secondaryLinkLabel' | 'secondaryLinkUrl';
11
+ export interface ConsentLightColors {
12
+ readonly bg: string;
13
+ readonly text: string;
14
+ readonly border: string;
15
+ }
16
+ export interface ConsentFieldsProps {
17
+ value: ConsentSettingsView;
18
+ onChange(required: {
19
+ patch: Partial<ConsentSettingsView>;
20
+ }, optional?: Record<string, never>): void;
21
+ disabled?: boolean | undefined;
22
+ /** Server/engine problems; each one with a matching `field` renders under that control. */
23
+ problems?: readonly ConsentFieldProblem[] | undefined;
24
+ /** Host translations keyed by the exact fallback copy; unspecified entries use English. */
25
+ dictionary?: Readonly<Record<string, string>> | undefined;
26
+ /** Host max lengths per text field; the defaults are the engine's loosest bounds. */
27
+ limits?: Readonly<Partial<Record<TextKey | 'policyVersion', number>>> | undefined;
28
+ /** Seam for tests: the handlers hook, defaulted to the real one. */
29
+ useConsentSettingsPanelHook?: typeof useConsentSettingsPanel | undefined;
30
+ }
31
+ /** Banner copy and its links. Optional host modes report only a mode patch; the host's independent
32
+ * enabled switch stays authoritative. Text is always plain text.
33
+ * @example <ConsentBannerFields value={value} onChange={onChange} bannerModes={['jini', 'headless', 'off']} /> */
34
+ export declare function ConsentBannerFields({ value, onChange, disabled, problems, dictionary, limits, bannerModes, useConsentSettingsPanelHook }: ConsentFieldsProps & {
35
+ bannerModes?: readonly NonNullable<ConsentSettingsView['bannerMode']>[] | undefined;
36
+ }): import("react").JSX.Element;
37
+ /** On/off, region behavior and the version that re-asks visitors when it changes. */
38
+ export declare function ConsentRulesFields({ value, onChange, disabled, problems, dictionary, limits, regionModes, useConsentSettingsPanelHook }: ConsentFieldsProps & {
39
+ regionModes?: readonly ConsentSettingsView['regionMode'][];
40
+ }): import("react").JSX.Element;
41
+ /** Placement, bounded appearance tokens and allowlisted custom CSS. The engine checks contrast and
42
+ * CSS safety; its problems arrive on the `appearance` field and show under the custom CSS. */
43
+ export declare function ConsentLookFields({ value, onChange, disabled, problems, dictionary, placements, useConsentSettingsPanelHook, lightColors }: ConsentFieldsProps & {
44
+ placements?: readonly string[];
45
+ lightColors: ConsentLightColors;
46
+ }): import("react").JSX.Element;
47
+ /** Keep transient empty edits local; only a valid policy version reaches autosave.
48
+ * Native validity gives keyboard users an actionable error. @complexity O(version length), <=128. */
49
+ export declare function PolicyVersionInput({ value, onChange, maxLength, aria, usePolicyVersionInputHook }: Pick<ConsentFieldsProps, 'onChange'> & {
50
+ value: string;
51
+ maxLength: number;
52
+ aria: object;
53
+ usePolicyVersionInputHook?: typeof usePolicyVersionInput;
54
+ }): import("react").JSX.Element;
55
+ export {};
56
+ //# sourceMappingURL=ConsentFields.d.ts.map
@@ -0,0 +1,86 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useId } from 'react';
3
+ import { createConsentTranslator, pixelInputValue, problemsFor, useConsentSettingsPanel, usePolicyVersionInput } from './settings-panel.hooks.js';
4
+ const BANNER_FIELDS = [
5
+ { key: 'title', label: 'Banner title' }, { key: 'message', label: 'Banner message', multiline: true },
6
+ { key: 'acceptLabel', label: 'Accept button text' }, { key: 'rejectLabel', label: 'Reject button text' },
7
+ { key: 'preferencesLabel', label: 'Preferences label' }, { key: 'privacyPolicyUrl', label: 'Privacy policy page URL' },
8
+ { key: 'secondaryLinkLabel', label: 'Second link text' }, { key: 'secondaryLinkUrl', label: 'Second link URL' },
9
+ ];
10
+ const BANNER_MODE_LABELS = { jini: 'Jini banner', headless: 'My own', off: 'None' };
11
+ const REGION_LABELS = {
12
+ auto: 'Automatic (unknown region: opt-in)', 'opt-in': 'Opt-in everywhere (EU / UK)', 'opt-out': 'Opt-out everywhere (California)',
13
+ };
14
+ const PLACEMENT_LABELS = { 'bottom-bar': 'Bottom bar', 'bottom-left': 'Bottom left', 'bottom-right': 'Bottom right', 'top-bar': 'Top bar' };
15
+ // Native color inputs need concrete colors rather than CSS variable expressions. The fallbacks come from the
16
+ // host kit's default theme, so they can only be read at render, never at import.
17
+ function consentColorFields({ lightColors }, _optional = {}) {
18
+ return [
19
+ { key: 'backgroundColor', label: 'Background', fallback: lightColors.bg }, { key: 'textColor', label: 'Text', fallback: lightColors.text }, { key: 'borderColor', label: 'Border', fallback: lightColors.border },
20
+ ];
21
+ }
22
+ /** The engine's own pixel bounds (`compileConsentCss`); out-of-range values come back as problems. */
23
+ const PIXEL_TOKENS = [
24
+ { key: 'borderRadius', label: 'Corner radius (px)', min: 0, max: 32 }, { key: 'padding', label: 'Padding (px)', min: 8, max: 32 },
25
+ { key: 'fontSize', label: 'Text size (px)', min: 16, max: 24 }, { key: 'maxWidth', label: 'Max width (px)', min: 256, max: 960 },
26
+ ];
27
+ /** One field's problems, linked to its control through `aria-describedby`. */
28
+ function FieldProblems({ id, problems }) {
29
+ if (!problems.length)
30
+ return null;
31
+ return _jsx("span", { id: id, className: "jini-consent-field-problems", children: problems.map(problem => _jsx("span", { className: "jini-hint jini-hint-error", children: problem.message }, `${problem.code ?? ''}${problem.message}`)) });
32
+ }
33
+ /** Label + control + problems. Problems sit outside the label so they never join the control's
34
+ * name; they are its description and mark it invalid instead. */
35
+ function Field({ label, field, problems, children }) {
36
+ const id = useId();
37
+ const own = problemsFor({ problems, field });
38
+ const attributes = own.length ? { id, 'aria-invalid': true, 'aria-describedby': `${id}-problems` } : { id };
39
+ return _jsxs("div", { className: "jini-consent-settings-field", children: [_jsx("label", { htmlFor: id, className: "jini-field-label", children: label }), children(attributes), _jsx(FieldProblems, { id: `${id}-problems`, problems: own })] });
40
+ }
41
+ /** Host-supplied banner modes. Native radios provide keyboard selection; the hint keeps its space
42
+ * while hidden, and the parent fieldset supplies the disabled state. */
43
+ function BannerModeFields({ value, onChange, dictionary, modes, useConsentSettingsPanelHook = useConsentSettingsPanel }) {
44
+ const id = useId();
45
+ const t = createConsentTranslator({ dictionary });
46
+ const handlers = useConsentSettingsPanelHook({ value, onChange });
47
+ return _jsxs("fieldset", { className: "jini-consent-banner-modes", "aria-describedby": value.bannerMode === 'headless' ? `${id}-mode-hint` : undefined, children: [_jsx("legend", { children: t('Banner mode') }), _jsx("div", { className: "jini-consent-banner-options", children: modes.map(mode => _jsxs("label", { children: [_jsx("input", { type: "radio", name: `${id}-banner-mode`, value: mode, checked: (value.bannerMode ?? 'jini') === mode, onChange: handlers.bannerMode({ mode }) }), _jsx("span", { children: t(BANNER_MODE_LABELS[mode]) })] }, mode)) }), _jsx("p", { id: `${id}-mode-hint`, className: "jini-hint jini-consent-banner-mode-hint", style: { visibility: value.bannerMode === 'headless' ? 'visible' : 'hidden' }, children: t('Your banner calls window.jiniConsent.set(...)') })] });
48
+ }
49
+ /** Banner copy and its links. Optional host modes report only a mode patch; the host's independent
50
+ * enabled switch stays authoritative. Text is always plain text.
51
+ * @example <ConsentBannerFields value={value} onChange={onChange} bannerModes={['jini', 'headless', 'off']} /> */
52
+ export function ConsentBannerFields({ value, onChange, disabled = false, problems, dictionary, limits = {}, bannerModes, useConsentSettingsPanelHook = useConsentSettingsPanel }) {
53
+ const t = createConsentTranslator({ dictionary });
54
+ const handlers = useConsentSettingsPanelHook({ value, onChange });
55
+ return _jsxs("fieldset", { disabled: disabled, className: "jini-consent-settings-fields", children: [_jsx("legend", { children: t('Banner text') }), bannerModes && _jsx(BannerModeFields, { value: value, onChange: onChange, dictionary: dictionary, modes: bannerModes, useConsentSettingsPanelHook: useConsentSettingsPanelHook }), BANNER_FIELDS.map(({ key, label, multiline }) => _jsx(Field, { label: t(label), field: key, problems: problems, children: aria => multiline
56
+ ? _jsx("textarea", { className: "jini-input", value: value[key] ?? '', maxLength: limits[key] ?? 2000, rows: 3, onChange: handlers.text(key), ...aria })
57
+ : _jsx("input", { className: "jini-input", type: "text", value: value[key] ?? '', maxLength: limits[key] ?? 2000, onChange: handlers.text(key), ...aria }) }, key)), _jsx("p", { className: "jini-hint", children: t('Link a published privacy page, such as /privacy. The second link is optional.') })] });
58
+ }
59
+ /** On/off, region behavior and the version that re-asks visitors when it changes. */
60
+ export function ConsentRulesFields({ value, onChange, disabled = false, problems, dictionary, limits = {}, regionModes = ['auto', 'opt-in', 'opt-out'], useConsentSettingsPanelHook = useConsentSettingsPanel }) {
61
+ const id = useId();
62
+ const t = createConsentTranslator({ dictionary });
63
+ const handlers = useConsentSettingsPanelHook({ value, onChange });
64
+ const modes = regionModes.includes(value.regionMode) ? regionModes : [value.regionMode, ...regionModes];
65
+ return _jsxs("fieldset", { disabled: disabled, className: "jini-consent-settings-fields", children: [_jsx("legend", { children: t('Rules') }), _jsxs("button", { type: "button", className: value.enabled ? 'jini-toggle-row on' : 'jini-toggle-row', role: "switch", "aria-checked": value.enabled, "aria-labelledby": `${id}-enabled`, "aria-describedby": `${id}-hint`, onClick: handlers.toggle, children: [_jsxs("span", { className: "jini-toggle-row-text", children: [_jsx("span", { id: `${id}-enabled`, className: "jini-toggle-row-label", children: t('Enable cookie consent on this site') }), _jsx("span", { id: `${id}-hint`, className: "jini-toggle-row-hint", children: t('Applies to published site pages.') })] }), _jsx("span", { className: "jini-toggle-row-switch", "aria-hidden": "true" })] }), _jsx(Field, { label: t('Region mode'), field: "regionMode", problems: problems, children: aria => _jsx("select", { className: "jini-input", value: value.regionMode, onChange: handlers.region, ...aria, children: modes.map(mode => _jsx("option", { value: mode, children: t(REGION_LABELS[mode]) }, mode)) }) }), _jsx("p", { className: "jini-hint", children: t('California permits optional categories until opt-out. Global Privacy Control always disables analytics and marketing.') }), _jsx(Field, { label: t('Policy version'), field: "policyVersion", problems: problems, children: aria => _jsx(PolicyVersionInput, { value: value.policyVersion, onChange: onChange, maxLength: limits.policyVersion ?? 128, aria: aria }) }), _jsx("p", { className: "jini-hint", children: t('Change the policy version to ask visitors to choose again.') })] });
66
+ }
67
+ /** Placement, bounded appearance tokens and allowlisted custom CSS. The engine checks contrast and
68
+ * CSS safety; its problems arrive on the `appearance` field and show under the custom CSS. */
69
+ export function ConsentLookFields({ value, onChange, disabled = false, problems, dictionary, placements = Object.keys(PLACEMENT_LABELS), useConsentSettingsPanelHook = useConsentSettingsPanel, lightColors }) {
70
+ const t = createConsentTranslator({ dictionary });
71
+ const handlers = useConsentSettingsPanelHook({ value, onChange });
72
+ const appearance = value.appearance ?? {};
73
+ return _jsxs("fieldset", { disabled: disabled, className: "jini-consent-settings-fields", children: [_jsx("legend", { children: t('Look & position') }), _jsx(Field, { label: t('Position'), field: "placement", problems: problems, children: aria => _jsx("select", { className: "jini-input", value: value.placement ?? placements[0], onChange: handlers.placement, ...aria, children: placements.map(placement => _jsx("option", { value: placement, children: t(PLACEMENT_LABELS[placement] ?? placement) }, placement)) }) }), _jsxs("div", { className: "jini-consent-token-grid", children: [consentColorFields({ lightColors }).map(token => _jsx(ColorToken, { label: t(token.label), value: appearance[token.key], fallback: token.fallback, resetLabel: t('Default'), onChange: handlers.token(token.key) }, token.key)), PIXEL_TOKENS.map(token => _jsx(Field, { label: t(token.label), field: token.key, children: attributes => _jsx("input", { className: "jini-input", type: "number", inputMode: "numeric", min: token.min, max: token.max, step: 1, placeholder: t('Default'), value: pixelInputValue({ value: appearance[token.key] }), onChange: event => handlers.token(token.key)(event.target.value === '' ? '' : `${event.target.value}px`), ...attributes }) }, token.key))] }), _jsx(Field, { label: t('Custom CSS'), field: "appearance", problems: problems, children: aria => _jsx("textarea", { className: "jini-input jini-consent-css", value: value.customCss ?? '', rows: 6, spellCheck: false, onChange: handlers.text('customCss'), ...aria }) }), _jsx("p", { className: "jini-hint", children: t('Only banner selectors and safe properties are allowed. Text needs 4.5:1 contrast.') })] });
74
+ }
75
+ /** A native color picker; unset shows the shared theme default and offers no reset. */
76
+ function ColorToken({ label, value, fallback, resetLabel, onChange }) {
77
+ const id = useId();
78
+ return _jsxs("div", { className: "jini-consent-settings-field", children: [_jsx("label", { htmlFor: id, className: "jini-field-label", children: label }), _jsxs("span", { className: "jini-consent-color-row", children: [_jsx("input", { id: id, className: "jini-consent-color", type: "color", value: value ?? fallback, onChange: event => onChange(event.target.value) }), _jsx("code", { className: "jini-hint", children: value ?? resetLabel }), value !== undefined && _jsx("button", { type: "button", className: "jini-btn-link", "aria-label": `${resetLabel}: ${label}`, onClick: () => onChange(''), children: resetLabel })] })] });
79
+ }
80
+ /** Keep transient empty edits local; only a valid policy version reaches autosave.
81
+ * Native validity gives keyboard users an actionable error. @complexity O(version length), <=128. */
82
+ export function PolicyVersionInput({ value, onChange, maxLength, aria, usePolicyVersionInputHook = usePolicyVersionInput }) {
83
+ const { draft, change, blur } = usePolicyVersionInputHook({ value, onChange });
84
+ return _jsx("input", { className: "jini-input", type: "text", value: draft, required: true, pattern: String.raw `.*\S.*`, maxLength: maxLength, onChange: change, onBlur: blur, ...aria });
85
+ }
86
+ //# sourceMappingURL=ConsentFields.js.map
@@ -0,0 +1,16 @@
1
+ import { useConsentPreviewWidth, type ConsentPreviewWidth } from './settings-panel.hooks.js';
2
+ export interface ConsentPreviewFrameProps {
3
+ /** The engine-gated page; `null` while it loads or when the host could not render it. */
4
+ html: string | null;
5
+ /** Shown in place of the frame while `html` is null. */
6
+ status?: string;
7
+ initialWidth?: ConsentPreviewWidth;
8
+ dictionary?: Readonly<Record<string, string>>;
9
+ /** Seam for tests: the width hook, defaulted to the real one. */
10
+ useConsentPreviewWidthHook?: typeof useConsentPreviewWidth;
11
+ }
12
+ /** The real rendered page with the banner, inert. The HTML is only ever the `srcdoc` of an iframe
13
+ * with an empty `sandbox`: no scripts, forms, popups or same-origin access, and it never enters the
14
+ * host DOM. Phone is 320px, the narrowest width the banner must still work at. */
15
+ export declare function ConsentPreviewFrame({ html, status, initialWidth, dictionary, useConsentPreviewWidthHook }: ConsentPreviewFrameProps): import("react").JSX.Element;
16
+ //# sourceMappingURL=ConsentPreviewFrame.d.ts.map
@@ -0,0 +1,14 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { createConsentTranslator, useConsentPreviewWidth } from './settings-panel.hooks.js';
3
+ const WIDTHS = [{ id: 'phone', label: 'Phone' }, { id: 'desktop', label: 'Desktop' }];
4
+ /** The real rendered page with the banner, inert. The HTML is only ever the `srcdoc` of an iframe
5
+ * with an empty `sandbox`: no scripts, forms, popups or same-origin access, and it never enters the
6
+ * host DOM. Phone is 320px, the narrowest width the banner must still work at. */
7
+ export function ConsentPreviewFrame({ html, status = '', initialWidth = 'desktop', dictionary = {}, useConsentPreviewWidthHook = useConsentPreviewWidth }) {
8
+ const t = createConsentTranslator({ dictionary });
9
+ const { width, setWidth } = useConsentPreviewWidthHook({ initial: initialWidth });
10
+ return _jsxs("section", { className: "jini-consent-preview", "aria-label": t('Banner preview'), children: [_jsx("div", { className: "jini-consent-preview-widths", role: "group", "aria-label": t('Preview width'), children: WIDTHS.map(option => _jsx("button", { type: "button", className: "jini-btn-secondary", "aria-pressed": width === option.id, onClick: () => setWidth(option.id), children: t(option.label) }, option.id)) }), html === null
11
+ ? _jsx("p", { className: "jini-hint jini-consent-preview-empty", children: status })
12
+ : _jsx("iframe", { className: `jini-consent-preview-frame is-${width}`, title: t('Banner preview'), sandbox: "", srcDoc: html, style: { width: width === 'phone' ? '320px' : '100%' } })] });
13
+ }
14
+ //# sourceMappingURL=ConsentPreviewFrame.js.map
@@ -0,0 +1,55 @@
1
+ import { type ConsentFieldsProps, type ConsentLightColors } from './ConsentFields.js';
2
+ /** Bounded appearance tokens, as the engine accepts them: opaque hex colors and `Npx` lengths. */
3
+ export interface ConsentAppearanceView {
4
+ backgroundColor?: string;
5
+ textColor?: string;
6
+ borderColor?: string;
7
+ borderRadius?: string;
8
+ padding?: string;
9
+ fontSize?: string;
10
+ maxWidth?: string;
11
+ }
12
+ /** The host's consent configuration. The look fields are optional so older hosts stay valid. */
13
+ export interface ConsentSettingsView {
14
+ enabled: boolean;
15
+ /** @deprecated Retained for saved-settings compatibility; declared-script consent does not use it. */
16
+ allowUnsafeEval?: boolean;
17
+ /** Optional for older hosts; omitted uses the Jini banner when consent is enabled. */
18
+ bannerMode?: 'jini' | 'headless' | 'off';
19
+ regionMode: 'auto' | 'opt-in' | 'opt-out';
20
+ policyVersion: string;
21
+ privacyPolicyUrl: string;
22
+ title: string;
23
+ message: string;
24
+ acceptLabel: string;
25
+ rejectLabel: string;
26
+ preferencesLabel: string;
27
+ placement?: string;
28
+ secondaryLinkLabel?: string;
29
+ secondaryLinkUrl?: string;
30
+ appearance?: ConsentAppearanceView;
31
+ customCss?: string;
32
+ }
33
+ /** One validation result. `field` names the setting it belongs to; field-less problems are the host's to show. */
34
+ export interface ConsentFieldProblem {
35
+ message: string;
36
+ field?: string;
37
+ code?: string;
38
+ }
39
+ export interface ConsentSettingsPanelProps extends Pick<ConsentFieldsProps, 'problems' | 'limits'> {
40
+ lightColors: ConsentLightColors;
41
+ value: ConsentSettingsView;
42
+ onChange(required: {
43
+ patch: Partial<ConsentSettingsView>;
44
+ }, optional?: Record<string, never>): void;
45
+ loading: boolean;
46
+ error: string | null;
47
+ status: string;
48
+ /** Host translations keyed by the exact fallback copy; unspecified entries use English. */
49
+ dictionary?: Readonly<Record<string, string>>;
50
+ }
51
+ /** The composed default for hosts that want one screen: Rules, Banner and Look stacked.
52
+ * Shared jini settings classes keep the panel in the host's design language.
53
+ * Native labels/selects/checkboxes support keyboard use at desktop and narrow widths. */
54
+ export declare function ConsentSettingsPanel({ value, onChange, loading, error, status, dictionary, problems, limits, lightColors }: ConsentSettingsPanelProps): import("react").JSX.Element;
55
+ //# sourceMappingURL=ConsentSettingsPanel.d.ts.map
@@ -0,0 +1,14 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useId } from 'react';
3
+ import { ConsentBannerFields, ConsentLookFields, ConsentRulesFields } from './ConsentFields.js';
4
+ import { createConsentTranslator } from './settings-panel.hooks.js';
5
+ /** The composed default for hosts that want one screen: Rules, Banner and Look stacked.
6
+ * Shared jini settings classes keep the panel in the host's design language.
7
+ * Native labels/selects/checkboxes support keyboard use at desktop and narrow widths. */
8
+ export function ConsentSettingsPanel({ value, onChange, loading, error, status, dictionary = {}, problems, limits, lightColors }) {
9
+ const id = useId();
10
+ const t = createConsentTranslator({ dictionary });
11
+ const fields = { value, onChange, disabled: loading, problems, dictionary, limits };
12
+ return _jsxs("section", { className: "jini-settings-section", "aria-labelledby": `${id}-heading`, children: [_jsx("div", { className: "jini-section-head", children: _jsxs("div", { children: [_jsx("h4", { id: `${id}-heading`, children: t('Site cookie consent') }), _jsx("p", { className: "jini-hint", children: t('Provides the consent mechanism, not legal advice. Review your texts, categories, and privacy policy for your site.') })] }) }), _jsx("p", { className: "jini-hint", children: t('Off by default. In opt-in regions, optional scripts stay paused until a visitor chooses. Unclassified third-party scripts use the marketing category. Global Privacy Control disables analytics and marketing.') }), _jsx(ConsentRulesFields, { ...fields }), _jsx(ConsentBannerFields, { ...fields }), _jsx(ConsentLookFields, { ...fields, lightColors: lightColors }), error && _jsx("p", { className: "jini-hint jini-hint-error", role: "alert", children: error }), _jsx("p", { className: "jini-hint", role: "status", children: status })] });
13
+ }
14
+ //# sourceMappingURL=ConsentSettingsPanel.js.map
@@ -0,0 +1,9 @@
1
+ export { ConsentSettingsPanel } from './ConsentSettingsPanel.js';
2
+ export type { ConsentAppearanceView, ConsentFieldProblem, ConsentSettingsPanelProps, ConsentSettingsView } from './ConsentSettingsPanel.js';
3
+ export { ConsentBannerFields, ConsentLookFields, ConsentRulesFields } from './ConsentFields.js';
4
+ export type { ConsentFieldsProps, ConsentLightColors } from './ConsentFields.js';
5
+ export { ConsentPreviewFrame } from './ConsentPreviewFrame.js';
6
+ export type { ConsentPreviewFrameProps } from './ConsentPreviewFrame.js';
7
+ export type { ConsentPreviewWidth } from './settings-panel.hooks.js';
8
+ export { CONSENT_PREVIEW_DESKTOP_WIDTH, consentPreviewScale } from './preview-scale.js';
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,5 @@
1
+ export { ConsentSettingsPanel } from './ConsentSettingsPanel.js';
2
+ export { ConsentBannerFields, ConsentLookFields, ConsentRulesFields } from './ConsentFields.js';
3
+ export { ConsentPreviewFrame } from './ConsentPreviewFrame.js';
4
+ export { CONSENT_PREVIEW_DESKTOP_WIDTH, consentPreviewScale } from './preview-scale.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,10 @@
1
+ /** The page width the Desktop preview lays out at. The consent banner switches to its phone layout
2
+ * (a full-width sheet) at 480px and below, so a preview drawn at a narrow pane's own width would show
3
+ * that phone sheet under a "Desktop" label instead of the corner card visitors see. */
4
+ export declare const CONSENT_PREVIEW_DESKTOP_WIDTH = 1024;
5
+ /** How far the desktop-width page is scaled down to fit the preview pane; never enlarged.
6
+ * An unmeasured (0) pane keeps 1. @complexity O(1). */
7
+ export declare function consentPreviewScale({ paneWidth }: {
8
+ paneWidth: number;
9
+ }, _optional?: Record<string, never>): number;
10
+ //# sourceMappingURL=preview-scale.d.ts.map
@@ -0,0 +1,10 @@
1
+ /** The page width the Desktop preview lays out at. The consent banner switches to its phone layout
2
+ * (a full-width sheet) at 480px and below, so a preview drawn at a narrow pane's own width would show
3
+ * that phone sheet under a "Desktop" label instead of the corner card visitors see. */
4
+ export const CONSENT_PREVIEW_DESKTOP_WIDTH = 1024;
5
+ /** How far the desktop-width page is scaled down to fit the preview pane; never enlarged.
6
+ * An unmeasured (0) pane keeps 1. @complexity O(1). */
7
+ export function consentPreviewScale({ paneWidth }, _optional = {}) {
8
+ return paneWidth > 0 ? Math.min(1, paneWidth / CONSENT_PREVIEW_DESKTOP_WIDTH) : 1;
9
+ }
10
+ //# sourceMappingURL=preview-scale.js.map