cookie-prefs 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,228 @@
1
+ // src/core/cookie.ts
2
+ var rawOf = (source, name) => {
3
+ if (typeof source == "string") {
4
+ for (const part of source.split(";")) {
5
+ const i = part.indexOf("=");
6
+ if (i > 0 && part.slice(0, i).trim() == name)
7
+ return decodeURIComponent(
8
+ part.slice(i + 1).trim().replace(/^"(.*)"$/, "$1")
9
+ );
10
+ }
11
+ return;
12
+ }
13
+ return typeof source?.get == "function" ? source.get(name)?.value : source?.[name];
14
+ };
15
+ var merge = (...sources) => Object.fromEntries(sources.flatMap((s) => Object.entries({ ...s }).filter((e) => e[1] != null)));
16
+ var defaults = { path: "/", maxAge: 3456e4, sameSite: "lax" };
17
+ var serialize = (c, value) => c.name + "=" + (value == null ? "" : encodeURIComponent(value.toWellFormed?.() ?? value)) + "; Path=" + c.path + (c.domain ? "; Domain=" + c.domain : "") + "; Max-Age=" + (value == null ? 0 : c.maxAge) + "; SameSite=" + c.sameSite + (c.secure ?? location.protocol == "https:" ? "; Secure" : "") + (c.partitioned ? "; Partitioned" : "");
18
+
19
+ // src/core/builder.ts
20
+ var builder = (def) => ({
21
+ ...def,
22
+ default: (d) => builder({ ...def, d }),
23
+ options: (o) => builder({ ...def, o: merge(def.o, o) }),
24
+ reflect: (r, m) => builder({ ...def, r: [].concat(r), m })
25
+ });
26
+
27
+ // src/core/reflect.ts
28
+ var domOf = (kind, value) => value == null ? null : typeof kind == "object" ? kind[value] ?? null : String(value);
29
+ var apply = (targets, kind, s) => {
30
+ const h = document.documentElement;
31
+ try {
32
+ for (const t of targets)
33
+ if (t == "class") {
34
+ for (const k in kind) h.classList.remove(kind[k]);
35
+ if (s != null) h.classList.add(s);
36
+ } else if (t[0] == "-") {
37
+ if (s == null) h.style.removeProperty(t);
38
+ else h.style.setProperty(t, s);
39
+ } else if (s == null) h.removeAttribute(t);
40
+ else h.setAttribute(t, s);
41
+ } catch {
42
+ }
43
+ };
44
+ var SOURCE = '(function(P){var h=document.documentElement,C="; "+document.cookie,i=0,j,p,m,v,n,t,k;for(P=JSON.parse(P);p=P[i++];)try{m=p[2];v=C.split("; "+p[0]+"=")[1];if(v!=null)try{v=decodeURIComponent(v.split(";")[0].replace(/^"(.*)"$/,"$1"));if(m===1){n=parseFloat(v);v=n===+v&&isFinite(n)?""+n:null}else if(m)v={}.hasOwnProperty.call(m,v)?m[v]:null}catch(e){v=null}if(v==null)v=p[3];for(j=0;t=p[1][j++];)if(t=="class"){for(k in m)h.classList.remove(m[k]);if(v!=null)h.classList.add(v)}else if(t[0]=="-"){if(v==null)h.style.removeProperty(t);else h.style.setProperty(t,v)}else if(v==null)h.removeAttribute(t);else h.setAttribute(t,v)}catch(e){}})(';
45
+ var script = (config) => config.length ? SOURCE + JSON.stringify(JSON.stringify(config)).replace(
46
+ /[<>&\u2028\u2029]/g,
47
+ (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
48
+ ) + ")" : "";
49
+
50
+ // src/core/sync.ts
51
+ var CHANNEL = "cookie-prefs";
52
+ var subs = /* @__PURE__ */ new Set();
53
+ var off;
54
+ var changed = () => subs.forEach((check) => check());
55
+ var hub = (check, on) => {
56
+ if (on) subs.add(check);
57
+ else subs.delete(check);
58
+ if (!subs.size) {
59
+ off?.();
60
+ off = void 0;
61
+ } else if (!off) {
62
+ const store = globalThis.cookieStore;
63
+ if (store) {
64
+ store.addEventListener("change", changed);
65
+ off = () => store.removeEventListener("change", changed);
66
+ } else if (typeof BroadcastChannel == "function") {
67
+ const channel = new BroadcastChannel(CHANNEL);
68
+ channel.onmessage = changed;
69
+ off = () => channel.close();
70
+ } else off = () => {
71
+ };
72
+ }
73
+ };
74
+ var post = () => {
75
+ if (!globalThis.cookieStore && typeof BroadcastChannel == "function") {
76
+ const channel = new BroadcastChannel(CHANNEL);
77
+ channel.postMessage(0);
78
+ channel.close();
79
+ }
80
+ };
81
+
82
+ // src/core/store.ts
83
+ var REFLECTION = /* @__PURE__ */ Symbol.for("cookie-prefs.reflection.1");
84
+ var hasDom = () => typeof document != "undefined";
85
+ var bind = (key, def, prefix, options) => {
86
+ const name = encodeURIComponent(def.o?.name ?? prefix + key);
87
+ const attrs = merge(defaults, options, def.o, { name });
88
+ const fallback = def.d;
89
+ const targets = def.r;
90
+ const kind = def.values ? Object.fromEntries(def.values.map((v) => [v, merge({ [v]: v }, def.m)[v]])) : def.k;
91
+ if (typeof process == "object" && process.env.NODE_ENV != "production" && targets?.includes("class") && Object.values({ ...kind }).some((c) => !/^[^\t\n\f\r ]+$/.test(c)))
92
+ throw TypeError(`cookie-prefs: ${key}.reflect('class') needs non-empty classes without whitespace`);
93
+ const cache = /* @__PURE__ */ new Map();
94
+ const listeners = /* @__PURE__ */ new Set();
95
+ let last;
96
+ const read = (source) => {
97
+ try {
98
+ const raw = rawOf(source, name);
99
+ if (typeof raw == "string" && raw.length <= 4096) {
100
+ if (!cache.has(raw)) {
101
+ if (cache.size > 9) cache.clear();
102
+ cache.set(raw, def.p(raw));
103
+ }
104
+ const value = cache.get(raw);
105
+ if (value !== void 0) return value;
106
+ }
107
+ } catch {
108
+ }
109
+ return fallback;
110
+ };
111
+ let warned = false;
112
+ const get = () => {
113
+ try {
114
+ return read(document.cookie);
115
+ } catch {
116
+ }
117
+ if (typeof process == "object" && process.env.NODE_ENV != "production" && !warned) {
118
+ warned = true;
119
+ console.warn(
120
+ `cookie-prefs: ${key}.get() cannot read document.cookie here and returns the default. On the server use read() or getPrefs().`
121
+ );
122
+ }
123
+ return fallback;
124
+ };
125
+ const check = () => {
126
+ const value = get();
127
+ if (targets) apply(targets, kind, domOf(kind, value));
128
+ if (!Object.is(value, last)) {
129
+ last = value;
130
+ listeners.forEach((listener) => listener(value));
131
+ }
132
+ };
133
+ const write = (value) => {
134
+ try {
135
+ document.cookie = serialize(attrs, value);
136
+ post();
137
+ } catch {
138
+ }
139
+ check();
140
+ };
141
+ const handle = {
142
+ key,
143
+ name,
144
+ defaultValue: fallback,
145
+ get,
146
+ set: (value) => {
147
+ if (hasDom()) write(def.s(typeof value == "function" ? value(get()) : value));
148
+ },
149
+ reset: () => {
150
+ if (hasDom()) write();
151
+ },
152
+ subscribe: (listener) => {
153
+ if (!hasDom()) return () => {
154
+ };
155
+ if (!listeners.size) {
156
+ hub(check, true);
157
+ check();
158
+ }
159
+ listeners.add(listener);
160
+ return () => {
161
+ listeners.delete(listener);
162
+ if (!listeners.size) hub(check, false);
163
+ };
164
+ },
165
+ read,
166
+ toCookie: (value) => ({ ...attrs, value: def.s(value) })
167
+ };
168
+ if (targets)
169
+ Object.defineProperty(handle, REFLECTION, {
170
+ value: [name, targets, kind, domOf(kind, fallback)]
171
+ });
172
+ return handle;
173
+ };
174
+
175
+ // src/index.ts
176
+ var pref = {
177
+ enum: (values) => builder({ values, p: (raw) => values.includes(raw) ? raw : void 0, s: String }),
178
+ boolean: () => builder({
179
+ k: { true: "true", false: "false" },
180
+ p: (raw) => raw == "true" || (raw == "false" ? false : void 0),
181
+ s: String
182
+ }),
183
+ number: () => builder({
184
+ k: 1,
185
+ p: (raw) => {
186
+ const n = parseFloat(raw);
187
+ return n === +raw && isFinite(n) ? n : void 0;
188
+ },
189
+ s: String
190
+ }),
191
+ string: () => builder({ k: 0, p: (raw) => raw, s: String }),
192
+ json: (schema) => builder({
193
+ p: (raw) => {
194
+ const result = schema["~standard"].validate(JSON.parse(raw));
195
+ return "then" in result || result.issues ? void 0 : result.value;
196
+ },
197
+ s: JSON.stringify
198
+ }),
199
+ custom: (codec) => builder({ p: (raw) => codec.parse(raw), s: (value) => codec.serialize(value) })
200
+ };
201
+ function definePrefs(shape, { prefix, ...options } = {}) {
202
+ const prefs = {};
203
+ for (const key in shape) prefs[key] = bind(key, shape[key], prefix ?? "", options);
204
+ return prefs;
205
+ }
206
+ function readPrefs(prefs, source) {
207
+ const values = {};
208
+ for (const key in prefs) values[key] = prefs[key].read(source);
209
+ return values;
210
+ }
211
+ function snapshotPrefs(prefs, source) {
212
+ const snapshot = {};
213
+ for (const { name } of Object.values(prefs)) {
214
+ try {
215
+ const raw = rawOf(source, name);
216
+ if (typeof raw == "string") snapshot[name] = raw;
217
+ } catch {
218
+ }
219
+ }
220
+ return snapshot;
221
+ }
222
+ function prefsScript(prefs) {
223
+ return script(
224
+ Object.values(prefs).map((handle) => handle[REFLECTION]).filter((r) => !!r)
225
+ );
226
+ }
227
+
228
+ export { definePrefs, pref, prefsScript, readPrefs, snapshotPrefs };
@@ -0,0 +1,43 @@
1
+ 'use strict';
2
+
3
+ var headers_js = require('next/headers.js');
4
+ var cookiePrefs = require('cookie-prefs');
5
+ var react = require('cookie-prefs/react');
6
+ var jsxRuntime = require('react/jsx-runtime');
7
+
8
+ // src/next/index.tsx
9
+ var requestSnapshot = async (prefs) => {
10
+ const header = (await headers_js.headers()).get("cookie") ?? "";
11
+ const store = await headers_js.cookies();
12
+ const snapshot = cookiePrefs.snapshotPrefs(prefs, header);
13
+ for (const { name } of Object.values(prefs)) {
14
+ const value = store.get(name)?.value;
15
+ const key = name + "=";
16
+ if (value != null && !header.split(/; */).some((part) => {
17
+ part = part == name ? key + "true" : part;
18
+ try {
19
+ return part.startsWith(key) && decodeURIComponent(part.slice(key.length)) == value;
20
+ } catch {
21
+ }
22
+ })) {
23
+ if (value) snapshot[name] = value;
24
+ else delete snapshot[name];
25
+ }
26
+ }
27
+ return snapshot;
28
+ };
29
+ async function getPrefs(prefs) {
30
+ return cookiePrefs.readPrefs(prefs, await requestSnapshot(prefs));
31
+ }
32
+ async function PrefsProvider({
33
+ prefs,
34
+ mode = "script",
35
+ nonce,
36
+ children
37
+ }) {
38
+ const snapshot = mode == "server" ? await requestSnapshot(prefs) : void 0;
39
+ return /* @__PURE__ */ jsxRuntime.jsx(react.PrefsProvider, { snapshot, script: cookiePrefs.prefsScript(prefs), nonce, children });
40
+ }
41
+
42
+ exports.PrefsProvider = PrefsProvider;
43
+ exports.getPrefs = getPrefs;
@@ -0,0 +1,48 @@
1
+ import { ReactNode, ReactElement } from 'react';
2
+ import { PrefsRecord, PrefValues } from '../index.cjs';
3
+
4
+ /**
5
+ * Typed values of all prefs for the current request, read from the `Cookie` header
6
+ * like the browser does, plus cookies set or deleted earlier in the same request
7
+ * (`(await cookies()).set(prefs.x.toCookie(v))` in a Server Function, middleware).
8
+ * Server-only (Server Components, Server Functions, Route Handlers). Reading request
9
+ * cookies makes the route dynamic; with Cache Components, call it inside
10
+ * `<Suspense>`. Server Components are not refreshed by client writes: when output
11
+ * depends on a pref, call `router.refresh()` after `set()`.
12
+ * @example
13
+ * const { sidebar } = await getPrefs(prefs)
14
+ * return <Shell collapsed={!sidebar} />
15
+ */
16
+ declare function getPrefs<P extends PrefsRecord>(prefs: P): Promise<PrefValues<P>>;
17
+ interface NextPrefsProviderProps<P extends PrefsRecord> {
18
+ /** The handles from `definePrefs()`. Stays on the server; only cookie strings reach the client. */
19
+ prefs: P;
20
+ /**
21
+ * `'script'`: no request API is touched, the route stays static; the inline script
22
+ * reflects prefs on `<html>` before paint and hooks render defaults until hydration,
23
+ * so anything visible before hydration must come from reflected attributes plus CSS.
24
+ * `'server'`: reads request cookies (like `getPrefs`) so hooks render exact
25
+ * values during SSR; makes the route dynamic (with Cache Components, the layout
26
+ * needs `export const instant = false`).
27
+ * @default 'script'
28
+ */
29
+ mode?: 'script' | 'server' | undefined;
30
+ /** CSP nonce for the inline script, e.g. from `(await headers()).get('x-nonce') ?? undefined`. */
31
+ nonce?: string | undefined;
32
+ children?: ReactNode;
33
+ }
34
+ /**
35
+ * Server Component that wires prefs into the App Router: renders the pre-paint
36
+ * script and the client `PrefsProvider` with the request snapshot. Put it at the top
37
+ * of `<body>` in the root layout and add `suppressHydrationWarning` to `<html>`.
38
+ * @example
39
+ * <html lang="en" suppressHydrationWarning>
40
+ * <body>
41
+ * <PrefsProvider prefs={prefs}>{children}</PrefsProvider>
42
+ * </body>
43
+ * </html>
44
+ */
45
+ declare function PrefsProvider<P extends PrefsRecord>({ prefs, mode, nonce, children, }: NextPrefsProviderProps<P>): Promise<ReactElement>;
46
+
47
+ export { PrefsProvider, getPrefs };
48
+ export type { NextPrefsProviderProps };
@@ -0,0 +1,48 @@
1
+ import { ReactNode, ReactElement } from 'react';
2
+ import { PrefsRecord, PrefValues } from '../index.js';
3
+
4
+ /**
5
+ * Typed values of all prefs for the current request, read from the `Cookie` header
6
+ * like the browser does, plus cookies set or deleted earlier in the same request
7
+ * (`(await cookies()).set(prefs.x.toCookie(v))` in a Server Function, middleware).
8
+ * Server-only (Server Components, Server Functions, Route Handlers). Reading request
9
+ * cookies makes the route dynamic; with Cache Components, call it inside
10
+ * `<Suspense>`. Server Components are not refreshed by client writes: when output
11
+ * depends on a pref, call `router.refresh()` after `set()`.
12
+ * @example
13
+ * const { sidebar } = await getPrefs(prefs)
14
+ * return <Shell collapsed={!sidebar} />
15
+ */
16
+ declare function getPrefs<P extends PrefsRecord>(prefs: P): Promise<PrefValues<P>>;
17
+ interface NextPrefsProviderProps<P extends PrefsRecord> {
18
+ /** The handles from `definePrefs()`. Stays on the server; only cookie strings reach the client. */
19
+ prefs: P;
20
+ /**
21
+ * `'script'`: no request API is touched, the route stays static; the inline script
22
+ * reflects prefs on `<html>` before paint and hooks render defaults until hydration,
23
+ * so anything visible before hydration must come from reflected attributes plus CSS.
24
+ * `'server'`: reads request cookies (like `getPrefs`) so hooks render exact
25
+ * values during SSR; makes the route dynamic (with Cache Components, the layout
26
+ * needs `export const instant = false`).
27
+ * @default 'script'
28
+ */
29
+ mode?: 'script' | 'server' | undefined;
30
+ /** CSP nonce for the inline script, e.g. from `(await headers()).get('x-nonce') ?? undefined`. */
31
+ nonce?: string | undefined;
32
+ children?: ReactNode;
33
+ }
34
+ /**
35
+ * Server Component that wires prefs into the App Router: renders the pre-paint
36
+ * script and the client `PrefsProvider` with the request snapshot. Put it at the top
37
+ * of `<body>` in the root layout and add `suppressHydrationWarning` to `<html>`.
38
+ * @example
39
+ * <html lang="en" suppressHydrationWarning>
40
+ * <body>
41
+ * <PrefsProvider prefs={prefs}>{children}</PrefsProvider>
42
+ * </body>
43
+ * </html>
44
+ */
45
+ declare function PrefsProvider<P extends PrefsRecord>({ prefs, mode, nonce, children, }: NextPrefsProviderProps<P>): Promise<ReactElement>;
46
+
47
+ export { PrefsProvider, getPrefs };
48
+ export type { NextPrefsProviderProps };
@@ -0,0 +1,40 @@
1
+ import { headers, cookies } from 'next/headers.js';
2
+ import { readPrefs, prefsScript, snapshotPrefs } from 'cookie-prefs';
3
+ import { PrefsProvider as PrefsProvider$1 } from 'cookie-prefs/react';
4
+ import { jsx } from 'react/jsx-runtime';
5
+
6
+ // src/next/index.tsx
7
+ var requestSnapshot = async (prefs) => {
8
+ const header = (await headers()).get("cookie") ?? "";
9
+ const store = await cookies();
10
+ const snapshot = snapshotPrefs(prefs, header);
11
+ for (const { name } of Object.values(prefs)) {
12
+ const value = store.get(name)?.value;
13
+ const key = name + "=";
14
+ if (value != null && !header.split(/; */).some((part) => {
15
+ part = part == name ? key + "true" : part;
16
+ try {
17
+ return part.startsWith(key) && decodeURIComponent(part.slice(key.length)) == value;
18
+ } catch {
19
+ }
20
+ })) {
21
+ if (value) snapshot[name] = value;
22
+ else delete snapshot[name];
23
+ }
24
+ }
25
+ return snapshot;
26
+ };
27
+ async function getPrefs(prefs) {
28
+ return readPrefs(prefs, await requestSnapshot(prefs));
29
+ }
30
+ async function PrefsProvider({
31
+ prefs,
32
+ mode = "script",
33
+ nonce,
34
+ children
35
+ }) {
36
+ const snapshot = mode == "server" ? await requestSnapshot(prefs) : void 0;
37
+ return /* @__PURE__ */ jsx(PrefsProvider$1, { snapshot, script: prefsScript(prefs), nonce, children });
38
+ }
39
+
40
+ export { PrefsProvider, getPrefs };
@@ -0,0 +1,98 @@
1
+ 'use client';
2
+ 'use strict';
3
+
4
+ var react = require('react');
5
+ var jsxRuntime = require('react/jsx-runtime');
6
+
7
+ // src/react/index.tsx
8
+
9
+ // src/react/reapply.ts
10
+ var reapply = (script) => {
11
+ try {
12
+ const config = JSON.parse(JSON.parse(script.slice(script.indexOf('})("') + 3, -1)));
13
+ const h = document.documentElement;
14
+ const cookies = "; " + document.cookie;
15
+ for (let i = 0, p; p = config[i++]; )
16
+ try {
17
+ const m = p[2];
18
+ let v = cookies.split("; " + p[0] + "=")[1];
19
+ if (v != null)
20
+ try {
21
+ v = decodeURIComponent(v.split(";")[0].replace(/^"(.*)"$/, "$1"));
22
+ if (m === 1) {
23
+ const n = parseFloat(v);
24
+ v = n === +v && isFinite(n) ? "" + n : null;
25
+ } else if (m) v = Object.prototype.hasOwnProperty.call(m, v) ? m[v] : null;
26
+ } catch {
27
+ v = null;
28
+ }
29
+ v ??= p[3];
30
+ for (let j = 0, t; t = p[1][j++]; )
31
+ if (t == "class") {
32
+ for (const k in m) h.classList.remove(m[k]);
33
+ if (v != null) h.classList.add(v);
34
+ } else if (t[0] == "-") {
35
+ if (v == null) h.style.removeProperty(t);
36
+ else h.style.setProperty(t, v);
37
+ } else if (v == null) h.removeAttribute(t);
38
+ else h.setAttribute(t, v);
39
+ } catch {
40
+ }
41
+ } catch {
42
+ }
43
+ };
44
+ var Snapshot = react.createContext(void 0);
45
+ var useLayout = typeof document == "undefined" ? react.useEffect : react.useLayoutEffect;
46
+ var seen = /* @__PURE__ */ new WeakSet();
47
+ function usePref(pref) {
48
+ const snapshot = react.useContext(Snapshot);
49
+ const value = react.useSyncExternalStore(
50
+ pref.subscribe,
51
+ pref.get,
52
+ () => snapshot ? pref.read(snapshot) : pref.defaultValue
53
+ );
54
+ react.useEffect(() => {
55
+ if (seen.has(pref)) return;
56
+ seen.add(pref);
57
+ try {
58
+ const current = pref.get();
59
+ if (current !== void 0 && pref.toCookie(current).maxAge > 604800 && ("; " + document.cookie).indexOf("; " + pref.name + "=") >= 0 && pref.read({ [pref.name]: pref.toCookie(current).value }) === current)
60
+ pref.set(() => current);
61
+ } catch {
62
+ }
63
+ }, [pref]);
64
+ return [value, pref.set];
65
+ }
66
+ function PrefsProvider({ children, snapshot, script, nonce }) {
67
+ const outer = react.useContext(Snapshot);
68
+ const merged = react.useMemo(
69
+ () => outer && snapshot ? { ...outer, ...snapshot } : snapshot ?? outer,
70
+ [outer, snapshot]
71
+ );
72
+ useLayout(() => {
73
+ if (!script) return;
74
+ const onVisible = () => {
75
+ if (document.visibilityState == "visible") reapply(script);
76
+ };
77
+ reapply(script);
78
+ document.addEventListener("visibilitychange", onVisible);
79
+ return () => document.removeEventListener("visibilitychange", onVisible);
80
+ }, [script]);
81
+ const [first] = react.useState(script && { __html: script });
82
+ const server = typeof document == "undefined";
83
+ return /* @__PURE__ */ jsxRuntime.jsxs(Snapshot.Provider, { value: merged, children: [
84
+ first ? /* @__PURE__ */ jsxRuntime.jsx(
85
+ "script",
86
+ {
87
+ type: server ? "text/javascript" : "text/plain",
88
+ nonce: server ? nonce : void 0,
89
+ suppressHydrationWarning: true,
90
+ dangerouslySetInnerHTML: first
91
+ }
92
+ ) : null,
93
+ children
94
+ ] });
95
+ }
96
+
97
+ exports.PrefsProvider = PrefsProvider;
98
+ exports.usePref = usePref;
@@ -0,0 +1,65 @@
1
+ import { ReactNode, ReactElement } from 'react';
2
+ import { p as PrefSetter } from '../types-BkCpm4d4.cjs';
3
+ import { PrefsSnapshot, Pref } from '../index.cjs';
4
+
5
+ /**
6
+ * Read and write one pref, like `useState`. Built on `useSyncExternalStore`, so every
7
+ * component using the same pref stays in sync, also across tabs. During SSR and
8
+ * hydration the value comes from the nearest `<PrefsProvider snapshot>`, or the
9
+ * default when there is none.
10
+ *
11
+ * Safari caps cookies written by scripts at 7 days, whatever `maxAge` says. So once
12
+ * per page load the hook re-writes the pref's cookie when it already exists, with the
13
+ * same value: the 7 days then count from the last visit, not the last change. Only a
14
+ * pref whose `maxAge` is longer than 7 days is refreshed, so a short-lived one still
15
+ * expires on time. A pref no hook uses is refreshed only by `set()`. A cookie set by
16
+ * the server (`Set-Cookie`, e.g. middleware writing `pref.toCookie(value)`) is not
17
+ * capped, but this refresh re-writes it from the page, so that only helps a pref no
18
+ * hook reads.
19
+ * @example
20
+ * const [sidebar, setSidebar] = usePref(prefs.sidebar)
21
+ * <button onClick={() => setSidebar((open) => !open)}>Toggle</button>
22
+ */
23
+ declare function usePref<T, V>(pref: Pref<T, V>): [value: V, setValue: PrefSetter<T, V>];
24
+ interface PrefsProviderProps {
25
+ children?: ReactNode;
26
+ /**
27
+ * Raw pref cookies of the current request, from `snapshotPrefs()`. Hooks render
28
+ * these values during SSR and hydration ("server" mode). Omit it on static pages
29
+ * ("script" mode): hooks then render defaults until hydration ends. A nested
30
+ * provider adds its snapshot to the outer one.
31
+ */
32
+ snapshot?: PrefsSnapshot | undefined;
33
+ /**
34
+ * Inline script from `prefsScript()`. Rendered once as the provider's first child, so
35
+ * place the provider at the top of `<body>`. Only the first value is rendered; a
36
+ * later one is still applied on `<html>`. It runs before paint on the initial
37
+ * document and is inert on the client, so React does not warn about it. The
38
+ * provider applies its reflections again with plain DOM calls, without running it,
39
+ * on mount (React can reset `<html>` attributes on remount) and whenever the tab
40
+ * becomes visible, so reflections also follow changes made in other tabs to prefs
41
+ * that nothing in this tab subscribes to.
42
+ */
43
+ script?: string | undefined;
44
+ /**
45
+ * CSP nonce for the inline script. Rendered on the server only, since browsers hide
46
+ * it after load. The client never runs a script, so it does not need the nonce.
47
+ */
48
+ nonce?: string | undefined;
49
+ }
50
+ /**
51
+ * Carries the server snapshot to `usePref()` and renders the pre-paint script.
52
+ * Optional in client-only apps. In Next.js App Router use `PrefsProvider` from
53
+ * `cookie-prefs/next` instead, which fills both props for you.
54
+ * @example
55
+ * <PrefsProvider
56
+ * snapshot={snapshotPrefs(prefs, request.headers.get('cookie'))}
57
+ * script={prefsScript(prefs)}
58
+ * >
59
+ * <App />
60
+ * </PrefsProvider>
61
+ */
62
+ declare function PrefsProvider({ children, snapshot, script, nonce }: PrefsProviderProps): ReactElement;
63
+
64
+ export { PrefSetter, PrefsProvider, usePref };
65
+ export type { PrefsProviderProps };
@@ -0,0 +1,65 @@
1
+ import { ReactNode, ReactElement } from 'react';
2
+ import { p as PrefSetter } from '../types-BkCpm4d4.js';
3
+ import { PrefsSnapshot, Pref } from '../index.js';
4
+
5
+ /**
6
+ * Read and write one pref, like `useState`. Built on `useSyncExternalStore`, so every
7
+ * component using the same pref stays in sync, also across tabs. During SSR and
8
+ * hydration the value comes from the nearest `<PrefsProvider snapshot>`, or the
9
+ * default when there is none.
10
+ *
11
+ * Safari caps cookies written by scripts at 7 days, whatever `maxAge` says. So once
12
+ * per page load the hook re-writes the pref's cookie when it already exists, with the
13
+ * same value: the 7 days then count from the last visit, not the last change. Only a
14
+ * pref whose `maxAge` is longer than 7 days is refreshed, so a short-lived one still
15
+ * expires on time. A pref no hook uses is refreshed only by `set()`. A cookie set by
16
+ * the server (`Set-Cookie`, e.g. middleware writing `pref.toCookie(value)`) is not
17
+ * capped, but this refresh re-writes it from the page, so that only helps a pref no
18
+ * hook reads.
19
+ * @example
20
+ * const [sidebar, setSidebar] = usePref(prefs.sidebar)
21
+ * <button onClick={() => setSidebar((open) => !open)}>Toggle</button>
22
+ */
23
+ declare function usePref<T, V>(pref: Pref<T, V>): [value: V, setValue: PrefSetter<T, V>];
24
+ interface PrefsProviderProps {
25
+ children?: ReactNode;
26
+ /**
27
+ * Raw pref cookies of the current request, from `snapshotPrefs()`. Hooks render
28
+ * these values during SSR and hydration ("server" mode). Omit it on static pages
29
+ * ("script" mode): hooks then render defaults until hydration ends. A nested
30
+ * provider adds its snapshot to the outer one.
31
+ */
32
+ snapshot?: PrefsSnapshot | undefined;
33
+ /**
34
+ * Inline script from `prefsScript()`. Rendered once as the provider's first child, so
35
+ * place the provider at the top of `<body>`. Only the first value is rendered; a
36
+ * later one is still applied on `<html>`. It runs before paint on the initial
37
+ * document and is inert on the client, so React does not warn about it. The
38
+ * provider applies its reflections again with plain DOM calls, without running it,
39
+ * on mount (React can reset `<html>` attributes on remount) and whenever the tab
40
+ * becomes visible, so reflections also follow changes made in other tabs to prefs
41
+ * that nothing in this tab subscribes to.
42
+ */
43
+ script?: string | undefined;
44
+ /**
45
+ * CSP nonce for the inline script. Rendered on the server only, since browsers hide
46
+ * it after load. The client never runs a script, so it does not need the nonce.
47
+ */
48
+ nonce?: string | undefined;
49
+ }
50
+ /**
51
+ * Carries the server snapshot to `usePref()` and renders the pre-paint script.
52
+ * Optional in client-only apps. In Next.js App Router use `PrefsProvider` from
53
+ * `cookie-prefs/next` instead, which fills both props for you.
54
+ * @example
55
+ * <PrefsProvider
56
+ * snapshot={snapshotPrefs(prefs, request.headers.get('cookie'))}
57
+ * script={prefsScript(prefs)}
58
+ * >
59
+ * <App />
60
+ * </PrefsProvider>
61
+ */
62
+ declare function PrefsProvider({ children, snapshot, script, nonce }: PrefsProviderProps): ReactElement;
63
+
64
+ export { PrefSetter, PrefsProvider, usePref };
65
+ export type { PrefsProviderProps };