cookie-prefs 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,12 +1,14 @@
1
1
  # cookie-prefs
2
2
 
3
- ![cookie-prefs: typed user preferences the server knows before the first render](.github/social-preview.png)
3
+ ![A preference is changed and saved as a cookie; after a reload the localStorage version jumps from the server's defaults while the cookie-prefs version is already right](.github/demo.gif)
4
4
 
5
5
  [![npm](https://img.shields.io/npm/v/cookie-prefs.svg)](https://www.npmjs.com/package/cookie-prefs)
6
6
  [![npm downloads](https://img.shields.io/npm/dm/cookie-prefs.svg)](https://www.npmjs.com/package/cookie-prefs)
7
7
  [![CI](https://github.com/StanislavKozachenko/cookie-prefs/actions/workflows/ci.yml/badge.svg)](https://github.com/StanislavKozachenko/cookie-prefs/actions/workflows/ci.yml)
8
8
  [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
9
9
 
10
+ **[Live demo](https://cookie-prefs.vercel.app)**: the same dashboard on cookies and on `localStorage`, [side by side](https://cookie-prefs.vercel.app/compare). The side-by-side reload in the recording above is throttled (1.6 Mbps, 4x CPU slowdown) to keep the first paint on screen.
11
+
10
12
  Typed, cookie-backed user preferences for React and Next.js: theme, sidebar, density, locale, anything small. nuqs keeps state in the URL; cookie-prefs keeps it in cookies, so the server knows it before the first render.
11
13
 
12
14
  - Readable in Server Components and on the client, with no hydration flash.
@@ -16,6 +18,20 @@ Typed, cookie-backed user preferences for React and Next.js: theme, sidebar, den
16
18
  - The core has zero dependencies and fits a 2 kB gzip budget. `react` and `next` are optional peer dependencies.
17
19
  - `cookie-prefs/theme` is an API-compatible replacement for [next-themes](https://github.com/pacocoursey/next-themes) (its last release, 0.4.6, was in March 2025) that stores the choice in a cookie.
18
20
 
21
+ ## When to use what
22
+
23
+ | | `localStorage` | URL state ([nuqs](https://nuqs.dev)) | next-themes | cookie-prefs |
24
+ | ----------------------------------------- | --------------------------------- | ------------------------------------ | ------------------ | ----------------------------- |
25
+ | Meant for | client-only state | state worth sharing as a link | the theme | small per-user preferences |
26
+ | The server knows it before rendering | No | Yes | No | Yes |
27
+ | Server-rendered content matches on reload | No, corrected after hydration | Yes | Theme class only | Yes |
28
+ | Typed | By hand | Yes | Theme names | Yes |
29
+ | Synced across tabs | By hand (`storage` event) | No | Yes | Yes |
30
+ | Travels with a shared link | No | Yes | No | No |
31
+ | Sent with every request | No | Yes, in the URL | No | Yes, so keep it small |
32
+
33
+ They combine: filters and pagination belong in the URL, the theme and layout in cookies.
34
+
19
35
  ## Install
20
36
 
21
37
  ```sh
@@ -71,6 +87,15 @@ export function SidebarToggle() {
71
87
  }
72
88
  ```
73
89
 
90
+ Several at once with `usePrefs`, which takes a partial patch:
91
+
92
+ ```tsx
93
+ import { usePrefs } from 'cookie-prefs/react'
94
+
95
+ const [{ theme, sidebar }, set] = usePrefs(prefs)
96
+ set({ sidebar: false, theme: 'dark' })
97
+ ```
98
+
74
99
  Read it in a Server Component (this makes the route dynamic):
75
100
 
76
101
  ```tsx
@@ -98,12 +123,24 @@ export async function setLocale(locale: string) {
98
123
 
99
124
  ## The entries
100
125
 
101
- | Import | What it is | Guide |
102
- | -------------------- | ------------------------------------------------------------------------------------------- | ----- |
103
- | `cookie-prefs` | Core, no DOM required: `definePrefs`, `pref.*`, `readPrefs`, `snapshotPrefs`, `prefsScript` | [Core](docs/core.md) |
104
- | `cookie-prefs/react` | `usePref`, and `PrefsProvider` for SSR outside Next.js | [Core](docs/core.md#cookie-prefsreact-outside-nextjs) |
105
- | `cookie-prefs/next` | Server-only: `PrefsProvider`, `getPrefs` (App Router) | [Next.js](docs/nextjs.md) |
106
- | `cookie-prefs/theme` | next-themes compatible `ThemeProvider` and `useTheme` | [Theme](docs/theme.md) |
126
+ | Import | What it is | Guide |
127
+ | --------------------- | ------------------------------------------------------------------------------ | ----- |
128
+ | `cookie-prefs` | Core, no DOM required: `definePrefs`, `pref.*`, `readPrefs`, `snapshotPrefs` | [Core](docs/core.md) |
129
+ | `cookie-prefs/react` | `usePref`, `usePrefs`, and `PrefsProvider` for SSR outside Next.js | [Core](docs/core.md#cookie-prefsreact-outside-nextjs) |
130
+ | `cookie-prefs/script` | `prefsScript`, the pre-paint script for `PrefsProvider` outside Next.js | [Core](docs/core.md#cookie-prefsreact-outside-nextjs) |
131
+ | `cookie-prefs/next` | Server-only: `PrefsProvider`, `getPrefs` (App Router) | [Next.js](docs/nextjs.md) |
132
+ | `cookie-prefs/theme` | next-themes compatible `ThemeProvider` and `useTheme` | [Theme](docs/theme.md) |
133
+ | `cookie-prefs/theme/next` | Server-only: `getTheme`, the stored theme in the App Router (opt-in) | [Theme](docs/theme.md#reading-the-theme-on-the-server) |
134
+ | `cookie-prefs/theme/server` | `readTheme`, the stored theme from request cookies on any server | [Theme](docs/theme.md#reading-the-theme-on-the-server) |
135
+ | `cookie-prefs/theme/color` | `ThemeColor`, keeps `<meta name="theme-color">` in sync with the theme (opt-in) | [Theme](docs/theme.md#browser-ui-colour-theme-color) |
136
+
137
+ ## Renaming an enum value
138
+
139
+ Users keep their choice when an enum value is renamed: a cookie holding an old name reads as its new value on the server, on the client and in the pre-paint script, and the next `set()` writes the new name.
140
+
141
+ ```ts
142
+ density: pref.enum(['compact', 'comfortable']).default('comfortable').migrate({ cozy: 'comfortable' }),
143
+ ```
107
144
 
108
145
  ## Next.js modes
109
146
 
@@ -122,6 +159,10 @@ export async function setLocale(locale: string) {
122
159
 
123
160
  Props and hook fields keep their next-themes names and defaults; the choice lives in a cookie, and existing `localStorage` themes are moved once. Setup and the full list of differences are in the [Theme guide](docs/theme.md).
124
161
 
162
+ To render from the stored theme on the server (`<html className>`), opt in with `await getTheme({ themes })` from `cookie-prefs/theme/next`, or `readTheme(cookieHeader, { themes })` from `cookie-prefs/theme/server` outside Next.js. It makes the route dynamic, returns `'system'` unresolved, and the inline script stays in charge before hydration; see [Reading the theme on the server](docs/theme.md#reading-the-theme-on-the-server).
163
+
164
+ To colour the browser UI per theme (`<meta name="theme-color">`, next-themes #78), render `<ThemeColor colors={{ light: '#ffffff', dark: '#0a0a0a' }} />` from `cookie-prefs/theme/color` inside `ThemeProvider`. It is right before hydration, follows `setTheme`, the OS scheme, `forcedTheme` and other tabs, and takes precedence over `viewport.themeColor`; see [Browser UI colour](docs/theme.md#browser-ui-colour-theme-color).
165
+
125
166
  ## Security and platform notes
126
167
 
127
168
  Prefs are readable by every script on the page: never store secrets. The pre-paint script needs a CSP nonce under strict policies, and Safari caps script-written cookies at 7 days (cookie-prefs refreshes the long-lived ones once per page load). Details, Trusted Types, iframes and non-goals are in [Security and platform notes](docs/security.md).
@@ -136,3 +177,5 @@ Prefs are readable by every script on the page: never store secrets. The pre-pai
136
177
  ## More
137
178
 
138
179
  Guides: [Core and React](docs/core.md), [Next.js](docs/nextjs.md), [Reflection](docs/reflection.md), [Theme](docs/theme.md), [Security and non-goals](docs/security.md). Design decisions, verified facts and limitations: [docs/design.md](docs/design.md). Contributing: [CONTRIBUTING.md](CONTRIBUTING.md). License: [MIT](LICENSE).
180
+
181
+ Roadmap to 1.0: [docs/roadmap.md](docs/roadmap.md).
package/dist/index.cjs CHANGED
@@ -20,6 +20,7 @@ var builder = (def) => ({
20
20
  ...def,
21
21
  default: (d) => builder({ ...def, d }),
22
22
  options: (o) => builder({ ...def, o: merge(def.o, o) }),
23
+ migrate: (a) => builder({ ...def, a: merge(def.a, a) }),
23
24
  reflect: (r, m) => builder({ ...def, r: [].concat(r), m })
24
25
  });
25
26
 
@@ -40,11 +41,6 @@ var apply = (targets, kind, s) => {
40
41
  } catch {
41
42
  }
42
43
  };
43
- var SOURCE = '(function(P){var r=document.documentElement,C="; "+document.cookie,k=0,j,p,t,n,i,e;for(P=JSON.parse(P);p=P[k++];)try{t=p[2];n=C.split("; "+p[0]+"=")[1];if(n!=null)try{n=decodeURIComponent(n.split(";")[0].replace(/^"(.*)"$/,"$1"));if(t===1){t=parseFloat(n);n=t===+n&&isFinite(t)?""+t:null}else if(t)n={}.hasOwnProperty.call(t,n)?t[n]:null}catch(e){n=null}if(n==null)n=p[3];for(j=0;i=p[1][j++];)if(i=="class"){for(e in t)r.classList.remove(t[e]);n!=null&&r.classList.add(n)}else i[0]=="-"?n==null?r.style.removeProperty(i):r.style.setProperty(i,n):n==null?r.removeAttribute(i):r.setAttribute(i,n)}catch(e){}})(';
44
- var script = (config) => config.length ? SOURCE + JSON.stringify(JSON.stringify(config)).replace(
45
- /[<>&\u2028\u2029]/g,
46
- (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
47
- ) + ")" : "";
48
44
 
49
45
  // src/core/sync.ts
50
46
  var open = () => {
@@ -55,16 +51,23 @@ var open = () => {
55
51
  };
56
52
  var subs = /* @__PURE__ */ new Set();
57
53
  var channel;
54
+ var timer;
58
55
  var changed = () => subs.forEach((check) => check());
59
56
  var shown = () => document.visibilityState == "visible" && changed();
57
+ var retry = (delay) => {
58
+ clearTimeout(timer);
59
+ if (delay < 4096 && document.visibilityState == "visible") timer = setTimeout(retry, delay, delay * 2);
60
+ changed();
61
+ };
60
62
  var hub = (check, on) => {
61
63
  if (on ? subs.add(check).size == 1 : subs.delete(check) && !subs.size) {
62
64
  const method = on ? "addEventListener" : "removeEventListener";
63
65
  globalThis.cookieStore?.[method]("change", changed);
64
66
  document[method]("visibilitychange", shown);
67
+ clearTimeout(timer);
65
68
  channel?.close();
66
69
  channel = on ? open() : void 0;
67
- if (channel) channel.onmessage = changed;
70
+ if (channel) channel.onmessage = () => retry(16);
68
71
  }
69
72
  };
70
73
  var post = () => {
@@ -80,7 +83,14 @@ var bind = (key, def, prefix, options) => {
80
83
  const attrs = merge(defaults, options, def.o, { name });
81
84
  const fallback = def.d;
82
85
  const targets = def.r;
83
- const kind = def.values ? Object.fromEntries(def.values.map((v) => [v, merge({ [v]: v }, def.m)[v]])) : def.k;
86
+ const values = def.values;
87
+ const enums = values && new Map(
88
+ Object.entries({ ...def.a }).filter((e) => values.includes(e[1])).concat(values.map((v) => [v, v]))
89
+ );
90
+ const kind = enums ? Object.fromEntries(
91
+ [...enums].map(([raw, v]) => [raw, merge({ [v]: v }, def.m)[v]])
92
+ ) : def.k;
93
+ const parse = enums ? (raw) => enums.get(raw) : def.p;
84
94
  if (typeof process == "object" && process.env.NODE_ENV != "production") {
85
95
  if (!name) throw TypeError(`cookie-prefs: ${key} needs a non-empty cookie name`);
86
96
  if (targets?.includes("class") && Object.values({ ...kind }).some((c) => !/^[^\t\n\f\r ]+$/.test(c)))
@@ -95,7 +105,7 @@ var bind = (key, def, prefix, options) => {
95
105
  if (typeof raw == "string" && raw.length <= 4096) {
96
106
  if (!cache.has(raw) || typeof document == "undefined") {
97
107
  if (cache.size > 9) cache.clear();
98
- cache.set(raw, def.p(raw));
108
+ cache.set(raw, parse(raw));
99
109
  }
100
110
  const value = cache.get(raw);
101
111
  if (value !== void 0) return value;
@@ -179,7 +189,7 @@ var bind = (key, def, prefix, options) => {
179
189
 
180
190
  // src/index.ts
181
191
  var pref = {
182
- enum: (values) => builder({ values, p: (raw) => values.includes(raw) ? raw : void 0, s: String }),
192
+ enum: (values) => builder({ values, s: String }),
183
193
  boolean: () => builder({
184
194
  k: { true: "true", false: "false" },
185
195
  p: (raw) => raw == "true" || (raw == "false" ? false : void 0),
@@ -223,14 +233,8 @@ function snapshotPrefs(prefs, source) {
223
233
  })
224
234
  );
225
235
  }
226
- function prefsScript(prefs) {
227
- return script(
228
- Object.values(prefs).map((handle) => handle[REFLECTION]).filter((r) => !!r)
229
- );
230
- }
231
236
 
232
237
  exports.definePrefs = definePrefs;
233
238
  exports.pref = pref;
234
- exports.prefsScript = prefsScript;
235
239
  exports.readPrefs = readPrefs;
236
240
  exports.snapshotPrefs = snapshotPrefs;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as EnumPrefBuilder, S as ScalarPrefBuilder, P as PrefBuilder, a as PrefCodec, b as PrefShape, c as PrefsOptions, d as Prefs, e as PrefsRecord, C as CookieSource, f as PrefValues, g as PrefsSnapshot } from './types-CQ_6o7nc.cjs';
2
- export { A as AnyPref, h as AnyPrefBuilder, i as CookieGetter, j as CookieInit, k as CookieOptions, l as CookieSameSite, m as EnumReflectTarget, n as Pref, o as PrefOptions, p as PrefSetter, q as PrefTypes, r as PrefValue, R as ReflectTarget } from './types-CQ_6o7nc.cjs';
1
+ import { E as EnumPrefBuilder, S as ScalarPrefBuilder, P as PrefBuilder, a as PrefCodec, b as PrefShape, c as PrefsOptions, d as Prefs, e as PrefsRecord, C as CookieSource, f as PrefValues, g as PrefsSnapshot } from './types-BITLlZeg.cjs';
2
+ export { A as AnyPref, h as AnyPrefBuilder, i as CookieGetter, j as CookieInit, k as CookieOptions, l as CookieSameSite, m as EnumReflectTarget, n as Pref, o as PrefOptions, p as PrefSetter, q as PrefTypes, r as PrefValue, R as ReflectTarget } from './types-BITLlZeg.cjs';
3
3
 
4
4
  /**
5
5
  * Structural copy of the Standard Schema v1 interface (https://standardschema.dev, MIT).
@@ -113,14 +113,6 @@ declare function readPrefs<P extends PrefsRecord>(prefs: P, source: CookieSource
113
113
  * <PrefsProvider snapshot={snapshotPrefs(prefs, request.headers.get('cookie'))}>
114
114
  */
115
115
  declare function snapshotPrefs(prefs: PrefsRecord, source: CookieSource): PrefsSnapshot;
116
- /**
117
- * Source of a blocking inline script that applies every `.reflect()` declaration to
118
- * `<html>` from `document.cookie` before first paint. Returns `''` when no pref
119
- * reflects. The output is fixed code plus escaped JSON config, safe to inline.
120
- * @example
121
- * <script nonce={nonce} dangerouslySetInnerHTML={{ __html: prefsScript(prefs) }} />
122
- */
123
- declare function prefsScript(prefs: PrefsRecord): string;
124
116
 
125
- export { CookieSource, EnumPrefBuilder, PrefBuilder, PrefCodec, PrefShape, PrefValues, Prefs, PrefsOptions, PrefsRecord, PrefsSnapshot, ScalarPrefBuilder, definePrefs, pref, prefsScript, readPrefs, snapshotPrefs };
117
+ export { CookieSource, EnumPrefBuilder, PrefBuilder, PrefCodec, PrefShape, PrefValues, Prefs, PrefsOptions, PrefsRecord, PrefsSnapshot, ScalarPrefBuilder, definePrefs, pref, readPrefs, snapshotPrefs };
126
118
  export type { PrefFactory, StandardSchemaV1 };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as EnumPrefBuilder, S as ScalarPrefBuilder, P as PrefBuilder, a as PrefCodec, b as PrefShape, c as PrefsOptions, d as Prefs, e as PrefsRecord, C as CookieSource, f as PrefValues, g as PrefsSnapshot } from './types-CQ_6o7nc.js';
2
- export { A as AnyPref, h as AnyPrefBuilder, i as CookieGetter, j as CookieInit, k as CookieOptions, l as CookieSameSite, m as EnumReflectTarget, n as Pref, o as PrefOptions, p as PrefSetter, q as PrefTypes, r as PrefValue, R as ReflectTarget } from './types-CQ_6o7nc.js';
1
+ import { E as EnumPrefBuilder, S as ScalarPrefBuilder, P as PrefBuilder, a as PrefCodec, b as PrefShape, c as PrefsOptions, d as Prefs, e as PrefsRecord, C as CookieSource, f as PrefValues, g as PrefsSnapshot } from './types-BITLlZeg.js';
2
+ export { A as AnyPref, h as AnyPrefBuilder, i as CookieGetter, j as CookieInit, k as CookieOptions, l as CookieSameSite, m as EnumReflectTarget, n as Pref, o as PrefOptions, p as PrefSetter, q as PrefTypes, r as PrefValue, R as ReflectTarget } from './types-BITLlZeg.js';
3
3
 
4
4
  /**
5
5
  * Structural copy of the Standard Schema v1 interface (https://standardschema.dev, MIT).
@@ -113,14 +113,6 @@ declare function readPrefs<P extends PrefsRecord>(prefs: P, source: CookieSource
113
113
  * <PrefsProvider snapshot={snapshotPrefs(prefs, request.headers.get('cookie'))}>
114
114
  */
115
115
  declare function snapshotPrefs(prefs: PrefsRecord, source: CookieSource): PrefsSnapshot;
116
- /**
117
- * Source of a blocking inline script that applies every `.reflect()` declaration to
118
- * `<html>` from `document.cookie` before first paint. Returns `''` when no pref
119
- * reflects. The output is fixed code plus escaped JSON config, safe to inline.
120
- * @example
121
- * <script nonce={nonce} dangerouslySetInnerHTML={{ __html: prefsScript(prefs) }} />
122
- */
123
- declare function prefsScript(prefs: PrefsRecord): string;
124
116
 
125
- export { CookieSource, EnumPrefBuilder, PrefBuilder, PrefCodec, PrefShape, PrefValues, Prefs, PrefsOptions, PrefsRecord, PrefsSnapshot, ScalarPrefBuilder, definePrefs, pref, prefsScript, readPrefs, snapshotPrefs };
117
+ export { CookieSource, EnumPrefBuilder, PrefBuilder, PrefCodec, PrefShape, PrefValues, Prefs, PrefsOptions, PrefsRecord, PrefsSnapshot, ScalarPrefBuilder, definePrefs, pref, readPrefs, snapshotPrefs };
126
118
  export type { PrefFactory, StandardSchemaV1 };
package/dist/index.js CHANGED
@@ -18,6 +18,7 @@ var builder = (def) => ({
18
18
  ...def,
19
19
  default: (d) => builder({ ...def, d }),
20
20
  options: (o) => builder({ ...def, o: merge(def.o, o) }),
21
+ migrate: (a) => builder({ ...def, a: merge(def.a, a) }),
21
22
  reflect: (r, m) => builder({ ...def, r: [].concat(r), m })
22
23
  });
23
24
 
@@ -38,11 +39,6 @@ var apply = (targets, kind, s) => {
38
39
  } catch {
39
40
  }
40
41
  };
41
- var SOURCE = '(function(P){var r=document.documentElement,C="; "+document.cookie,k=0,j,p,t,n,i,e;for(P=JSON.parse(P);p=P[k++];)try{t=p[2];n=C.split("; "+p[0]+"=")[1];if(n!=null)try{n=decodeURIComponent(n.split(";")[0].replace(/^"(.*)"$/,"$1"));if(t===1){t=parseFloat(n);n=t===+n&&isFinite(t)?""+t:null}else if(t)n={}.hasOwnProperty.call(t,n)?t[n]:null}catch(e){n=null}if(n==null)n=p[3];for(j=0;i=p[1][j++];)if(i=="class"){for(e in t)r.classList.remove(t[e]);n!=null&&r.classList.add(n)}else i[0]=="-"?n==null?r.style.removeProperty(i):r.style.setProperty(i,n):n==null?r.removeAttribute(i):r.setAttribute(i,n)}catch(e){}})(';
42
- var script = (config) => config.length ? SOURCE + JSON.stringify(JSON.stringify(config)).replace(
43
- /[<>&\u2028\u2029]/g,
44
- (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
45
- ) + ")" : "";
46
42
 
47
43
  // src/core/sync.ts
48
44
  var open = () => {
@@ -53,16 +49,23 @@ var open = () => {
53
49
  };
54
50
  var subs = /* @__PURE__ */ new Set();
55
51
  var channel;
52
+ var timer;
56
53
  var changed = () => subs.forEach((check) => check());
57
54
  var shown = () => document.visibilityState == "visible" && changed();
55
+ var retry = (delay) => {
56
+ clearTimeout(timer);
57
+ if (delay < 4096 && document.visibilityState == "visible") timer = setTimeout(retry, delay, delay * 2);
58
+ changed();
59
+ };
58
60
  var hub = (check, on) => {
59
61
  if (on ? subs.add(check).size == 1 : subs.delete(check) && !subs.size) {
60
62
  const method = on ? "addEventListener" : "removeEventListener";
61
63
  globalThis.cookieStore?.[method]("change", changed);
62
64
  document[method]("visibilitychange", shown);
65
+ clearTimeout(timer);
63
66
  channel?.close();
64
67
  channel = on ? open() : void 0;
65
- if (channel) channel.onmessage = changed;
68
+ if (channel) channel.onmessage = () => retry(16);
66
69
  }
67
70
  };
68
71
  var post = () => {
@@ -78,7 +81,14 @@ var bind = (key, def, prefix, options) => {
78
81
  const attrs = merge(defaults, options, def.o, { name });
79
82
  const fallback = def.d;
80
83
  const targets = def.r;
81
- const kind = def.values ? Object.fromEntries(def.values.map((v) => [v, merge({ [v]: v }, def.m)[v]])) : def.k;
84
+ const values = def.values;
85
+ const enums = values && new Map(
86
+ Object.entries({ ...def.a }).filter((e) => values.includes(e[1])).concat(values.map((v) => [v, v]))
87
+ );
88
+ const kind = enums ? Object.fromEntries(
89
+ [...enums].map(([raw, v]) => [raw, merge({ [v]: v }, def.m)[v]])
90
+ ) : def.k;
91
+ const parse = enums ? (raw) => enums.get(raw) : def.p;
82
92
  if (typeof process == "object" && process.env.NODE_ENV != "production") {
83
93
  if (!name) throw TypeError(`cookie-prefs: ${key} needs a non-empty cookie name`);
84
94
  if (targets?.includes("class") && Object.values({ ...kind }).some((c) => !/^[^\t\n\f\r ]+$/.test(c)))
@@ -93,7 +103,7 @@ var bind = (key, def, prefix, options) => {
93
103
  if (typeof raw == "string" && raw.length <= 4096) {
94
104
  if (!cache.has(raw) || typeof document == "undefined") {
95
105
  if (cache.size > 9) cache.clear();
96
- cache.set(raw, def.p(raw));
106
+ cache.set(raw, parse(raw));
97
107
  }
98
108
  const value = cache.get(raw);
99
109
  if (value !== void 0) return value;
@@ -177,7 +187,7 @@ var bind = (key, def, prefix, options) => {
177
187
 
178
188
  // src/index.ts
179
189
  var pref = {
180
- enum: (values) => builder({ values, p: (raw) => values.includes(raw) ? raw : void 0, s: String }),
190
+ enum: (values) => builder({ values, s: String }),
181
191
  boolean: () => builder({
182
192
  k: { true: "true", false: "false" },
183
193
  p: (raw) => raw == "true" || (raw == "false" ? false : void 0),
@@ -221,10 +231,5 @@ function snapshotPrefs(prefs, source) {
221
231
  })
222
232
  );
223
233
  }
224
- function prefsScript(prefs) {
225
- return script(
226
- Object.values(prefs).map((handle) => handle[REFLECTION]).filter((r) => !!r)
227
- );
228
- }
229
234
 
230
- export { definePrefs, pref, prefsScript, readPrefs, snapshotPrefs };
235
+ export { definePrefs, pref, readPrefs, snapshotPrefs };
@@ -2,6 +2,7 @@
2
2
 
3
3
  var headers_js = require('next/headers.js');
4
4
  var cookiePrefs = require('cookie-prefs');
5
+ var script = require('cookie-prefs/script');
5
6
  var react = require('cookie-prefs/react');
6
7
  var jsxRuntime = require('react/jsx-runtime');
7
8
 
@@ -32,16 +33,14 @@ async function getPrefs(prefs) {
32
33
  async function PrefsProvider({
33
34
  prefs,
34
35
  mode,
35
- nonce,
36
- children
36
+ ...props
37
37
  }) {
38
38
  return /* @__PURE__ */ jsxRuntime.jsx(
39
39
  react.PrefsProvider,
40
40
  {
41
+ ...props,
41
42
  snapshot: mode == "server" ? await requestSnapshot(prefs) : void 0,
42
- script: cookiePrefs.prefsScript(prefs),
43
- nonce,
44
- children
43
+ script: script.prefsScript(prefs)
45
44
  }
46
45
  );
47
46
  }
@@ -42,7 +42,7 @@ interface NextPrefsProviderProps<P extends PrefsRecord> {
42
42
  * </body>
43
43
  * </html>
44
44
  */
45
- declare function PrefsProvider<P extends PrefsRecord>({ prefs, mode, nonce, children, }: NextPrefsProviderProps<P>): Promise<ReactElement>;
45
+ declare function PrefsProvider<P extends PrefsRecord>({ prefs, mode, ...props }: NextPrefsProviderProps<P>): Promise<ReactElement>;
46
46
 
47
47
  export { PrefsProvider, getPrefs };
48
48
  export type { NextPrefsProviderProps };
@@ -42,7 +42,7 @@ interface NextPrefsProviderProps<P extends PrefsRecord> {
42
42
  * </body>
43
43
  * </html>
44
44
  */
45
- declare function PrefsProvider<P extends PrefsRecord>({ prefs, mode, nonce, children, }: NextPrefsProviderProps<P>): Promise<ReactElement>;
45
+ declare function PrefsProvider<P extends PrefsRecord>({ prefs, mode, ...props }: NextPrefsProviderProps<P>): Promise<ReactElement>;
46
46
 
47
47
  export { PrefsProvider, getPrefs };
48
48
  export type { NextPrefsProviderProps };
@@ -1,5 +1,6 @@
1
1
  import { headers, cookies } from 'next/headers.js';
2
- import { readPrefs, prefsScript, snapshotPrefs } from 'cookie-prefs';
2
+ import { readPrefs, snapshotPrefs } from 'cookie-prefs';
3
+ import { prefsScript } from 'cookie-prefs/script';
3
4
  import { PrefsProvider as PrefsProvider$1 } from 'cookie-prefs/react';
4
5
  import { jsx } from 'react/jsx-runtime';
5
6
 
@@ -30,16 +31,14 @@ async function getPrefs(prefs) {
30
31
  async function PrefsProvider({
31
32
  prefs,
32
33
  mode,
33
- nonce,
34
- children
34
+ ...props
35
35
  }) {
36
36
  return /* @__PURE__ */ jsx(
37
37
  PrefsProvider$1,
38
38
  {
39
+ ...props,
39
40
  snapshot: mode == "server" ? await requestSnapshot(prefs) : void 0,
40
- script: prefsScript(prefs),
41
- nonce,
42
- children
41
+ script: prefsScript(prefs)
43
42
  }
44
43
  );
45
44
  }
@@ -46,11 +46,7 @@ var useLayout = typeof document == "undefined" ? react.useEffect : react.useLayo
46
46
  var seen = /* @__PURE__ */ new WeakSet();
47
47
  function usePref(pref) {
48
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
- );
49
+ const value = react.useSyncExternalStore(pref.subscribe, pref.get, () => pref.read(snapshot));
54
50
  react.useEffect(() => {
55
51
  if (seen.has(pref)) return;
56
52
  seen.add(pref);
@@ -63,12 +59,24 @@ function usePref(pref) {
63
59
  }, [pref]);
64
60
  return [value, pref.set];
65
61
  }
62
+ function usePrefs(prefs) {
63
+ const entries = Object.entries(prefs);
64
+ const values = entries.map(([key, handle]) => [key, usePref(handle)[0]]);
65
+ return [
66
+ // Keys and values as dependencies: a new object only when a value (or the record's
67
+ // shape) changes. Built with `fromEntries`, so a key named `__proto__` stays a key.
68
+ react.useMemo(() => Object.fromEntries(values), values.flat()),
69
+ react.useMemo(
70
+ () => (patch) => {
71
+ for (const [key, value] of Object.entries(patch)) if (value !== void 0) prefs[key].set(value);
72
+ },
73
+ entries.flat()
74
+ )
75
+ ];
76
+ }
66
77
  function PrefsProvider({ children, snapshot, script, nonce }) {
67
78
  const outer = react.useContext(Snapshot);
68
- const merged = react.useMemo(
69
- () => outer && snapshot ? { ...outer, ...snapshot } : snapshot ?? outer,
70
- [outer, snapshot]
71
- );
79
+ const merged = react.useMemo(() => snapshot ? { ...outer, ...snapshot } : outer, [outer, snapshot]);
72
80
  useLayout(() => {
73
81
  if (!script) return;
74
82
  const onVisible = () => {
@@ -96,3 +104,4 @@ function PrefsProvider({ children, snapshot, script, nonce }) {
96
104
 
97
105
  exports.PrefsProvider = PrefsProvider;
98
106
  exports.usePref = usePref;
107
+ exports.usePrefs = usePrefs;
@@ -1,6 +1,6 @@
1
1
  import { ReactNode, ReactElement } from 'react';
2
- import { p as PrefSetter } from '../types-CQ_6o7nc.cjs';
3
- import { PrefsSnapshot, Pref } from '../index.cjs';
2
+ import { p as PrefSetter } from '../types-BITLlZeg.cjs';
3
+ import { PrefsSnapshot, PrefsRecord, PrefTypes, Pref, PrefValues } from '../index.cjs';
4
4
 
5
5
  /**
6
6
  * Read and write one pref, like `useState`. Built on `useSyncExternalStore`, so every
@@ -23,6 +23,31 @@ import { PrefsSnapshot, Pref } from '../index.cjs';
23
23
  * <button onClick={() => setSidebar((open) => !open)}>Toggle</button>
24
24
  */
25
25
  declare function usePref<T, V>(pref: Pref<T, V>): [value: V, setValue: PrefSetter<T, V>];
26
+ /**
27
+ * Writes several prefs of a record at once: each key takes what that pref's `set()`
28
+ * takes, a value or an updater of the previous value. Keys left out (or `undefined`)
29
+ * are not touched.
30
+ */
31
+ type PrefsSetter<P extends PrefsRecord> = (patch: {
32
+ [K in keyof P]?: P[K] extends {
33
+ readonly '~types'?: PrefTypes<infer T, infer V>;
34
+ } ? T | ((prev: V) => T) : never;
35
+ }) => void;
36
+ /**
37
+ * Read and write several prefs at once: `usePref` for every handle in `prefs` (the
38
+ * record from `definePrefs()`, or any record of its handles), with the same server
39
+ * snapshot, hydration, cross-tab sync and Safari refresh. `values` is typed like
40
+ * `readPrefs()` and stays the same object until one of the prefs changes, so it is safe
41
+ * in dependency arrays. The setter takes a partial patch and passes each entry to that
42
+ * pref's `set()`, in order: a value or an updater of the previous value. An entry set
43
+ * to `undefined` is skipped like a missing key; clear a pref with `reset()`. The setter
44
+ * stays the same function while the record holds the same handles. Like any hook, it
45
+ * needs the same keys on every render.
46
+ * @example
47
+ * const [{ theme, sidebar }, set] = usePrefs(prefs)
48
+ * <button onClick={() => set({ sidebar: (open) => !open, theme: 'dark' })}>Focus</button>
49
+ */
50
+ declare function usePrefs<P extends PrefsRecord>(prefs: P): [values: PrefValues<P>, setValues: PrefsSetter<P>];
26
51
  interface PrefsProviderProps {
27
52
  children?: ReactNode;
28
53
  /**
@@ -33,14 +58,14 @@ interface PrefsProviderProps {
33
58
  */
34
59
  snapshot?: PrefsSnapshot | undefined;
35
60
  /**
36
- * Inline script from `prefsScript()`. Rendered once as the provider's first child, so
37
- * place the provider at the top of `<body>`. Only the first value is rendered; a
38
- * later one is still applied on `<html>`. It runs before paint on the initial
39
- * document and is inert on the client, so React does not warn about it. The
40
- * provider applies its reflections again with plain DOM calls, without running it,
41
- * on mount (React can reset `<html>` attributes on remount) and whenever the tab
42
- * becomes visible, so reflections also follow changes made in other tabs to prefs
43
- * that nothing in this tab subscribes to.
61
+ * Inline script from `prefsScript()` (`cookie-prefs/script`). Rendered once as the
62
+ * provider's first child, so place the provider at the top of `<body>`. Only the
63
+ * first value is rendered; a later one is still applied on `<html>`. It runs before
64
+ * paint on the initial document and is inert on the client, so React does not warn
65
+ * about it. The provider applies its reflections again with plain DOM calls, without
66
+ * running it, on mount (React can reset `<html>` attributes on remount) and whenever
67
+ * the tab becomes visible, so reflections also follow changes made in other tabs to
68
+ * prefs that nothing in this tab subscribes to.
44
69
  */
45
70
  script?: string | undefined;
46
71
  /**
@@ -63,5 +88,5 @@ interface PrefsProviderProps {
63
88
  */
64
89
  declare function PrefsProvider({ children, snapshot, script, nonce }: PrefsProviderProps): ReactElement;
65
90
 
66
- export { PrefSetter, PrefsProvider, usePref };
67
- export type { PrefsProviderProps };
91
+ export { PrefSetter, PrefsProvider, usePref, usePrefs };
92
+ export type { PrefsProviderProps, PrefsSetter };
@@ -1,6 +1,6 @@
1
1
  import { ReactNode, ReactElement } from 'react';
2
- import { p as PrefSetter } from '../types-CQ_6o7nc.js';
3
- import { PrefsSnapshot, Pref } from '../index.js';
2
+ import { p as PrefSetter } from '../types-BITLlZeg.js';
3
+ import { PrefsSnapshot, PrefsRecord, PrefTypes, Pref, PrefValues } from '../index.js';
4
4
 
5
5
  /**
6
6
  * Read and write one pref, like `useState`. Built on `useSyncExternalStore`, so every
@@ -23,6 +23,31 @@ import { PrefsSnapshot, Pref } from '../index.js';
23
23
  * <button onClick={() => setSidebar((open) => !open)}>Toggle</button>
24
24
  */
25
25
  declare function usePref<T, V>(pref: Pref<T, V>): [value: V, setValue: PrefSetter<T, V>];
26
+ /**
27
+ * Writes several prefs of a record at once: each key takes what that pref's `set()`
28
+ * takes, a value or an updater of the previous value. Keys left out (or `undefined`)
29
+ * are not touched.
30
+ */
31
+ type PrefsSetter<P extends PrefsRecord> = (patch: {
32
+ [K in keyof P]?: P[K] extends {
33
+ readonly '~types'?: PrefTypes<infer T, infer V>;
34
+ } ? T | ((prev: V) => T) : never;
35
+ }) => void;
36
+ /**
37
+ * Read and write several prefs at once: `usePref` for every handle in `prefs` (the
38
+ * record from `definePrefs()`, or any record of its handles), with the same server
39
+ * snapshot, hydration, cross-tab sync and Safari refresh. `values` is typed like
40
+ * `readPrefs()` and stays the same object until one of the prefs changes, so it is safe
41
+ * in dependency arrays. The setter takes a partial patch and passes each entry to that
42
+ * pref's `set()`, in order: a value or an updater of the previous value. An entry set
43
+ * to `undefined` is skipped like a missing key; clear a pref with `reset()`. The setter
44
+ * stays the same function while the record holds the same handles. Like any hook, it
45
+ * needs the same keys on every render.
46
+ * @example
47
+ * const [{ theme, sidebar }, set] = usePrefs(prefs)
48
+ * <button onClick={() => set({ sidebar: (open) => !open, theme: 'dark' })}>Focus</button>
49
+ */
50
+ declare function usePrefs<P extends PrefsRecord>(prefs: P): [values: PrefValues<P>, setValues: PrefsSetter<P>];
26
51
  interface PrefsProviderProps {
27
52
  children?: ReactNode;
28
53
  /**
@@ -33,14 +58,14 @@ interface PrefsProviderProps {
33
58
  */
34
59
  snapshot?: PrefsSnapshot | undefined;
35
60
  /**
36
- * Inline script from `prefsScript()`. Rendered once as the provider's first child, so
37
- * place the provider at the top of `<body>`. Only the first value is rendered; a
38
- * later one is still applied on `<html>`. It runs before paint on the initial
39
- * document and is inert on the client, so React does not warn about it. The
40
- * provider applies its reflections again with plain DOM calls, without running it,
41
- * on mount (React can reset `<html>` attributes on remount) and whenever the tab
42
- * becomes visible, so reflections also follow changes made in other tabs to prefs
43
- * that nothing in this tab subscribes to.
61
+ * Inline script from `prefsScript()` (`cookie-prefs/script`). Rendered once as the
62
+ * provider's first child, so place the provider at the top of `<body>`. Only the
63
+ * first value is rendered; a later one is still applied on `<html>`. It runs before
64
+ * paint on the initial document and is inert on the client, so React does not warn
65
+ * about it. The provider applies its reflections again with plain DOM calls, without
66
+ * running it, on mount (React can reset `<html>` attributes on remount) and whenever
67
+ * the tab becomes visible, so reflections also follow changes made in other tabs to
68
+ * prefs that nothing in this tab subscribes to.
44
69
  */
45
70
  script?: string | undefined;
46
71
  /**
@@ -63,5 +88,5 @@ interface PrefsProviderProps {
63
88
  */
64
89
  declare function PrefsProvider({ children, snapshot, script, nonce }: PrefsProviderProps): ReactElement;
65
90
 
66
- export { PrefSetter, PrefsProvider, usePref };
67
- export type { PrefsProviderProps };
91
+ export { PrefSetter, PrefsProvider, usePref, usePrefs };
92
+ export type { PrefsProviderProps, PrefsSetter };
@@ -44,11 +44,7 @@ var useLayout = typeof document == "undefined" ? useEffect : useLayoutEffect;
44
44
  var seen = /* @__PURE__ */ new WeakSet();
45
45
  function usePref(pref) {
46
46
  const snapshot = useContext(Snapshot);
47
- const value = useSyncExternalStore(
48
- pref.subscribe,
49
- pref.get,
50
- () => snapshot ? pref.read(snapshot) : pref.defaultValue
51
- );
47
+ const value = useSyncExternalStore(pref.subscribe, pref.get, () => pref.read(snapshot));
52
48
  useEffect(() => {
53
49
  if (seen.has(pref)) return;
54
50
  seen.add(pref);
@@ -61,12 +57,24 @@ function usePref(pref) {
61
57
  }, [pref]);
62
58
  return [value, pref.set];
63
59
  }
60
+ function usePrefs(prefs) {
61
+ const entries = Object.entries(prefs);
62
+ const values = entries.map(([key, handle]) => [key, usePref(handle)[0]]);
63
+ return [
64
+ // Keys and values as dependencies: a new object only when a value (or the record's
65
+ // shape) changes. Built with `fromEntries`, so a key named `__proto__` stays a key.
66
+ useMemo(() => Object.fromEntries(values), values.flat()),
67
+ useMemo(
68
+ () => (patch) => {
69
+ for (const [key, value] of Object.entries(patch)) if (value !== void 0) prefs[key].set(value);
70
+ },
71
+ entries.flat()
72
+ )
73
+ ];
74
+ }
64
75
  function PrefsProvider({ children, snapshot, script, nonce }) {
65
76
  const outer = useContext(Snapshot);
66
- const merged = useMemo(
67
- () => outer && snapshot ? { ...outer, ...snapshot } : snapshot ?? outer,
68
- [outer, snapshot]
69
- );
77
+ const merged = useMemo(() => snapshot ? { ...outer, ...snapshot } : outer, [outer, snapshot]);
70
78
  useLayout(() => {
71
79
  if (!script) return;
72
80
  const onVisible = () => {
@@ -92,4 +100,4 @@ function PrefsProvider({ children, snapshot, script, nonce }) {
92
100
  ] });
93
101
  }
94
102
 
95
- export { PrefsProvider, usePref };
103
+ export { PrefsProvider, usePref, usePrefs };