cookie-prefs 0.1.1 → 0.1.3

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
package/dist/index.cjs CHANGED
@@ -4,11 +4,8 @@
4
4
  var rawOf = (source, name) => {
5
5
  if (typeof source == "string") {
6
6
  for (const part of source.split(";")) {
7
- const i = part.indexOf("=");
8
- if (i > 0 && part.slice(0, i).trim() == name)
9
- return decodeURIComponent(
10
- part.slice(i + 1).trim().replace(/^"(.*)"$/, "$1")
11
- );
7
+ const m = /^[\t ]*((?:[\t ]*[^\t =]+)*)[\t ]*(=?)[\t ]*((?:[\t ]*[^\t ]+)*)/.exec(part);
8
+ if (m[2] && m[1] == name) return decodeURIComponent(m[3].replace(/^"(.*)"$/, "$1"));
12
9
  }
13
10
  return;
14
11
  }
@@ -43,55 +40,52 @@ var apply = (targets, kind, s) => {
43
40
  } catch {
44
41
  }
45
42
  };
46
- 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){}})(';
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){}})(';
47
44
  var script = (config) => config.length ? SOURCE + JSON.stringify(JSON.stringify(config)).replace(
48
45
  /[<>&\u2028\u2029]/g,
49
46
  (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
50
47
  ) + ")" : "";
51
48
 
52
49
  // src/core/sync.ts
53
- var CHANNEL = "cookie-prefs";
50
+ var open = () => {
51
+ try {
52
+ return globalThis.cookieStore ? void 0 : new BroadcastChannel("cookie-prefs");
53
+ } catch {
54
+ }
55
+ };
54
56
  var subs = /* @__PURE__ */ new Set();
55
- var off;
57
+ var channel;
56
58
  var changed = () => subs.forEach((check) => check());
59
+ var shown = () => document.visibilityState == "visible" && changed();
57
60
  var hub = (check, on) => {
58
- if (on) subs.add(check);
59
- else subs.delete(check);
60
- if (!subs.size) {
61
- off?.();
62
- off = void 0;
63
- } else if (!off) {
64
- const store = globalThis.cookieStore;
65
- if (store) {
66
- store.addEventListener("change", changed);
67
- off = () => store.removeEventListener("change", changed);
68
- } else if (typeof BroadcastChannel == "function") {
69
- const channel = new BroadcastChannel(CHANNEL);
70
- channel.onmessage = changed;
71
- off = () => channel.close();
72
- } else off = () => {
73
- };
61
+ if (on ? subs.add(check).size == 1 : subs.delete(check) && !subs.size) {
62
+ const method = on ? "addEventListener" : "removeEventListener";
63
+ globalThis.cookieStore?.[method]("change", changed);
64
+ document[method]("visibilitychange", shown);
65
+ channel?.close();
66
+ channel = on ? open() : void 0;
67
+ if (channel) channel.onmessage = changed;
74
68
  }
75
69
  };
76
70
  var post = () => {
77
- if (!globalThis.cookieStore && typeof BroadcastChannel == "function") {
78
- const channel = new BroadcastChannel(CHANNEL);
79
- channel.postMessage(0);
80
- channel.close();
81
- }
71
+ const channel2 = open();
72
+ channel2?.postMessage(0);
73
+ channel2?.close();
82
74
  };
83
75
 
84
76
  // src/core/store.ts
85
77
  var REFLECTION = /* @__PURE__ */ Symbol.for("cookie-prefs.reflection.1");
86
- var hasDom = () => typeof document != "undefined";
87
78
  var bind = (key, def, prefix, options) => {
88
79
  const name = encodeURIComponent(def.o?.name ?? prefix + key);
89
80
  const attrs = merge(defaults, options, def.o, { name });
90
81
  const fallback = def.d;
91
82
  const targets = def.r;
92
83
  const kind = def.values ? Object.fromEntries(def.values.map((v) => [v, merge({ [v]: v }, def.m)[v]])) : def.k;
93
- if (typeof process == "object" && process.env.NODE_ENV != "production" && targets?.includes("class") && Object.values({ ...kind }).some((c) => !/^[^\t\n\f\r ]+$/.test(c)))
94
- throw TypeError(`cookie-prefs: ${key}.reflect('class') needs non-empty classes without whitespace`);
84
+ if (typeof process == "object" && process.env.NODE_ENV != "production") {
85
+ if (!name) throw TypeError(`cookie-prefs: ${key} needs a non-empty cookie name`);
86
+ if (targets?.includes("class") && Object.values({ ...kind }).some((c) => !/^[^\t\n\f\r ]+$/.test(c)))
87
+ throw TypeError(`cookie-prefs: ${key}.reflect('class') needs non-empty classes without whitespace`);
88
+ }
95
89
  const cache = /* @__PURE__ */ new Map();
96
90
  const listeners = /* @__PURE__ */ new Set();
97
91
  let last;
@@ -99,7 +93,7 @@ var bind = (key, def, prefix, options) => {
99
93
  try {
100
94
  const raw = rawOf(source, name);
101
95
  if (typeof raw == "string" && raw.length <= 4096) {
102
- if (!cache.has(raw)) {
96
+ if (!cache.has(raw) || typeof document == "undefined") {
103
97
  if (cache.size > 9) cache.clear();
104
98
  cache.set(raw, def.p(raw));
105
99
  }
@@ -129,7 +123,16 @@ var bind = (key, def, prefix, options) => {
129
123
  if (targets) apply(targets, kind, domOf(kind, value));
130
124
  if (!Object.is(value, last)) {
131
125
  last = value;
132
- listeners.forEach((listener) => listener(value));
126
+ listeners.forEach((listener) => {
127
+ if (Object.is(value, last))
128
+ try {
129
+ listener(value);
130
+ } catch (e) {
131
+ setTimeout(() => {
132
+ throw e;
133
+ });
134
+ }
135
+ });
133
136
  }
134
137
  };
135
138
  const write = (value) => {
@@ -146,13 +149,13 @@ var bind = (key, def, prefix, options) => {
146
149
  defaultValue: fallback,
147
150
  get,
148
151
  set: (value) => {
149
- if (hasDom()) write(def.s(typeof value == "function" ? value(get()) : value));
152
+ if (typeof document != "undefined") write(def.s(typeof value == "function" ? value(get()) : value));
150
153
  },
151
154
  reset: () => {
152
- if (hasDom()) write();
155
+ if (typeof document != "undefined") write();
153
156
  },
154
157
  subscribe: (listener) => {
155
- if (!hasDom()) return () => {
158
+ if (typeof document == "undefined") return () => {
156
159
  };
157
160
  if (!listeners.size) {
158
161
  hub(check, true);
@@ -201,25 +204,24 @@ var pref = {
201
204
  custom: (codec) => builder({ p: (raw) => codec.parse(raw), s: (value) => codec.serialize(value) })
202
205
  };
203
206
  function definePrefs(shape, { prefix, ...options } = {}) {
204
- const prefs = {};
205
- for (const key in shape) prefs[key] = bind(key, shape[key], prefix ?? "", options);
206
- return prefs;
207
+ return Object.fromEntries(
208
+ Object.entries(shape).map(([key, def]) => [key, bind(key, def, prefix ?? "", options)])
209
+ );
207
210
  }
208
211
  function readPrefs(prefs, source) {
209
- const values = {};
210
- for (const key in prefs) values[key] = prefs[key].read(source);
211
- return values;
212
+ return Object.fromEntries(Object.entries(prefs).map(([key, handle]) => [key, handle.read(source)]));
212
213
  }
213
214
  function snapshotPrefs(prefs, source) {
214
- const snapshot = {};
215
- for (const { name } of Object.values(prefs)) {
216
- try {
217
- const raw = rawOf(source, name);
218
- if (typeof raw == "string") snapshot[name] = raw;
219
- } catch {
220
- }
221
- }
222
- return snapshot;
215
+ return Object.fromEntries(
216
+ Object.values(prefs).flatMap(({ name }) => {
217
+ try {
218
+ const raw = rawOf(source, name);
219
+ if (typeof raw == "string") return [[name, raw]];
220
+ } catch {
221
+ }
222
+ return [];
223
+ })
224
+ );
223
225
  }
224
226
  function prefsScript(prefs) {
225
227
  return script(
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-BkCpm4d4.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-BkCpm4d4.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-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';
3
3
 
4
4
  /**
5
5
  * Structural copy of the Standard Schema v1 interface (https://standardschema.dev, MIT).
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-BkCpm4d4.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-BkCpm4d4.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-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';
3
3
 
4
4
  /**
5
5
  * Structural copy of the Standard Schema v1 interface (https://standardschema.dev, MIT).
package/dist/index.js CHANGED
@@ -2,11 +2,8 @@
2
2
  var rawOf = (source, name) => {
3
3
  if (typeof source == "string") {
4
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
- );
5
+ const m = /^[\t ]*((?:[\t ]*[^\t =]+)*)[\t ]*(=?)[\t ]*((?:[\t ]*[^\t ]+)*)/.exec(part);
6
+ if (m[2] && m[1] == name) return decodeURIComponent(m[3].replace(/^"(.*)"$/, "$1"));
10
7
  }
11
8
  return;
12
9
  }
@@ -41,55 +38,52 @@ var apply = (targets, kind, s) => {
41
38
  } catch {
42
39
  }
43
40
  };
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){}})(';
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){}})(';
45
42
  var script = (config) => config.length ? SOURCE + JSON.stringify(JSON.stringify(config)).replace(
46
43
  /[<>&\u2028\u2029]/g,
47
44
  (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
48
45
  ) + ")" : "";
49
46
 
50
47
  // src/core/sync.ts
51
- var CHANNEL = "cookie-prefs";
48
+ var open = () => {
49
+ try {
50
+ return globalThis.cookieStore ? void 0 : new BroadcastChannel("cookie-prefs");
51
+ } catch {
52
+ }
53
+ };
52
54
  var subs = /* @__PURE__ */ new Set();
53
- var off;
55
+ var channel;
54
56
  var changed = () => subs.forEach((check) => check());
57
+ var shown = () => document.visibilityState == "visible" && changed();
55
58
  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
- };
59
+ if (on ? subs.add(check).size == 1 : subs.delete(check) && !subs.size) {
60
+ const method = on ? "addEventListener" : "removeEventListener";
61
+ globalThis.cookieStore?.[method]("change", changed);
62
+ document[method]("visibilitychange", shown);
63
+ channel?.close();
64
+ channel = on ? open() : void 0;
65
+ if (channel) channel.onmessage = changed;
72
66
  }
73
67
  };
74
68
  var post = () => {
75
- if (!globalThis.cookieStore && typeof BroadcastChannel == "function") {
76
- const channel = new BroadcastChannel(CHANNEL);
77
- channel.postMessage(0);
78
- channel.close();
79
- }
69
+ const channel2 = open();
70
+ channel2?.postMessage(0);
71
+ channel2?.close();
80
72
  };
81
73
 
82
74
  // src/core/store.ts
83
75
  var REFLECTION = /* @__PURE__ */ Symbol.for("cookie-prefs.reflection.1");
84
- var hasDom = () => typeof document != "undefined";
85
76
  var bind = (key, def, prefix, options) => {
86
77
  const name = encodeURIComponent(def.o?.name ?? prefix + key);
87
78
  const attrs = merge(defaults, options, def.o, { name });
88
79
  const fallback = def.d;
89
80
  const targets = def.r;
90
81
  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`);
82
+ if (typeof process == "object" && process.env.NODE_ENV != "production") {
83
+ if (!name) throw TypeError(`cookie-prefs: ${key} needs a non-empty cookie name`);
84
+ if (targets?.includes("class") && Object.values({ ...kind }).some((c) => !/^[^\t\n\f\r ]+$/.test(c)))
85
+ throw TypeError(`cookie-prefs: ${key}.reflect('class') needs non-empty classes without whitespace`);
86
+ }
93
87
  const cache = /* @__PURE__ */ new Map();
94
88
  const listeners = /* @__PURE__ */ new Set();
95
89
  let last;
@@ -97,7 +91,7 @@ var bind = (key, def, prefix, options) => {
97
91
  try {
98
92
  const raw = rawOf(source, name);
99
93
  if (typeof raw == "string" && raw.length <= 4096) {
100
- if (!cache.has(raw)) {
94
+ if (!cache.has(raw) || typeof document == "undefined") {
101
95
  if (cache.size > 9) cache.clear();
102
96
  cache.set(raw, def.p(raw));
103
97
  }
@@ -127,7 +121,16 @@ var bind = (key, def, prefix, options) => {
127
121
  if (targets) apply(targets, kind, domOf(kind, value));
128
122
  if (!Object.is(value, last)) {
129
123
  last = value;
130
- listeners.forEach((listener) => listener(value));
124
+ listeners.forEach((listener) => {
125
+ if (Object.is(value, last))
126
+ try {
127
+ listener(value);
128
+ } catch (e) {
129
+ setTimeout(() => {
130
+ throw e;
131
+ });
132
+ }
133
+ });
131
134
  }
132
135
  };
133
136
  const write = (value) => {
@@ -144,13 +147,13 @@ var bind = (key, def, prefix, options) => {
144
147
  defaultValue: fallback,
145
148
  get,
146
149
  set: (value) => {
147
- if (hasDom()) write(def.s(typeof value == "function" ? value(get()) : value));
150
+ if (typeof document != "undefined") write(def.s(typeof value == "function" ? value(get()) : value));
148
151
  },
149
152
  reset: () => {
150
- if (hasDom()) write();
153
+ if (typeof document != "undefined") write();
151
154
  },
152
155
  subscribe: (listener) => {
153
- if (!hasDom()) return () => {
156
+ if (typeof document == "undefined") return () => {
154
157
  };
155
158
  if (!listeners.size) {
156
159
  hub(check, true);
@@ -199,25 +202,24 @@ var pref = {
199
202
  custom: (codec) => builder({ p: (raw) => codec.parse(raw), s: (value) => codec.serialize(value) })
200
203
  };
201
204
  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
+ return Object.fromEntries(
206
+ Object.entries(shape).map(([key, def]) => [key, bind(key, def, prefix ?? "", options)])
207
+ );
205
208
  }
206
209
  function readPrefs(prefs, source) {
207
- const values = {};
208
- for (const key in prefs) values[key] = prefs[key].read(source);
209
- return values;
210
+ return Object.fromEntries(Object.entries(prefs).map(([key, handle]) => [key, handle.read(source)]));
210
211
  }
211
212
  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;
213
+ return Object.fromEntries(
214
+ Object.values(prefs).flatMap(({ name }) => {
215
+ try {
216
+ const raw = rawOf(source, name);
217
+ if (typeof raw == "string") return [[name, raw]];
218
+ } catch {
219
+ }
220
+ return [];
221
+ })
222
+ );
221
223
  }
222
224
  function prefsScript(prefs) {
223
225
  return script(
@@ -9,7 +9,7 @@ var jsxRuntime = require('react/jsx-runtime');
9
9
  var requestSnapshot = async (prefs) => {
10
10
  const header = (await headers_js.headers()).get("cookie") ?? "";
11
11
  const store = await headers_js.cookies();
12
- const snapshot = cookiePrefs.snapshotPrefs(prefs, header);
12
+ let snapshot = cookiePrefs.snapshotPrefs(prefs, header);
13
13
  for (const { name } of Object.values(prefs)) {
14
14
  const value = store.get(name)?.value;
15
15
  const key = name + "=";
@@ -20,7 +20,7 @@ var requestSnapshot = async (prefs) => {
20
20
  } catch {
21
21
  }
22
22
  })) {
23
- if (value) snapshot[name] = value;
23
+ if (value) snapshot = { ...snapshot, [name]: value };
24
24
  else delete snapshot[name];
25
25
  }
26
26
  }
@@ -31,12 +31,19 @@ async function getPrefs(prefs) {
31
31
  }
32
32
  async function PrefsProvider({
33
33
  prefs,
34
- mode = "script",
34
+ mode,
35
35
  nonce,
36
36
  children
37
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 });
38
+ return /* @__PURE__ */ jsxRuntime.jsx(
39
+ react.PrefsProvider,
40
+ {
41
+ snapshot: mode == "server" ? await requestSnapshot(prefs) : void 0,
42
+ script: cookiePrefs.prefsScript(prefs),
43
+ nonce,
44
+ children
45
+ }
46
+ );
40
47
  }
41
48
 
42
49
  exports.PrefsProvider = PrefsProvider;
@@ -7,7 +7,7 @@ import { jsx } from 'react/jsx-runtime';
7
7
  var requestSnapshot = async (prefs) => {
8
8
  const header = (await headers()).get("cookie") ?? "";
9
9
  const store = await cookies();
10
- const snapshot = snapshotPrefs(prefs, header);
10
+ let snapshot = snapshotPrefs(prefs, header);
11
11
  for (const { name } of Object.values(prefs)) {
12
12
  const value = store.get(name)?.value;
13
13
  const key = name + "=";
@@ -18,7 +18,7 @@ var requestSnapshot = async (prefs) => {
18
18
  } catch {
19
19
  }
20
20
  })) {
21
- if (value) snapshot[name] = value;
21
+ if (value) snapshot = { ...snapshot, [name]: value };
22
22
  else delete snapshot[name];
23
23
  }
24
24
  }
@@ -29,12 +29,19 @@ async function getPrefs(prefs) {
29
29
  }
30
30
  async function PrefsProvider({
31
31
  prefs,
32
- mode = "script",
32
+ mode,
33
33
  nonce,
34
34
  children
35
35
  }) {
36
- const snapshot = mode == "server" ? await requestSnapshot(prefs) : void 0;
37
- return /* @__PURE__ */ jsx(PrefsProvider$1, { snapshot, script: prefsScript(prefs), nonce, children });
36
+ return /* @__PURE__ */ jsx(
37
+ PrefsProvider$1,
38
+ {
39
+ snapshot: mode == "server" ? await requestSnapshot(prefs) : void 0,
40
+ script: prefsScript(prefs),
41
+ nonce,
42
+ children
43
+ }
44
+ );
38
45
  }
39
46
 
40
47
  export { PrefsProvider, getPrefs };
@@ -22,7 +22,7 @@ var reapply = (script) => {
22
22
  if (m === 1) {
23
23
  const n = parseFloat(v);
24
24
  v = n === +v && isFinite(n) ? "" + n : null;
25
- } else if (m) v = Object.prototype.hasOwnProperty.call(m, v) ? m[v] : null;
25
+ } else if (m) v = {}.hasOwnProperty.call(m, v) ? m[v] : null;
26
26
  } catch {
27
27
  v = null;
28
28
  }
@@ -56,7 +56,7 @@ function usePref(pref) {
56
56
  seen.add(pref);
57
57
  try {
58
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)
59
+ if (current !== void 0 && pref.toCookie(current).maxAge > 604800 && ("; " + document.cookie).split("; " + pref.name + "=")[1]?.split(";")[0] === encodeURIComponent(pref.toCookie(current).value))
60
60
  pref.set(() => current);
61
61
  } catch {
62
62
  }
@@ -1,5 +1,5 @@
1
1
  import { ReactNode, ReactElement } from 'react';
2
- import { p as PrefSetter } from '../types-BkCpm4d4.cjs';
2
+ import { p as PrefSetter } from '../types-CQ_6o7nc.cjs';
3
3
  import { PrefsSnapshot, Pref } from '../index.cjs';
4
4
 
5
5
  /**
@@ -12,10 +12,12 @@ import { PrefsSnapshot, Pref } from '../index.cjs';
12
12
  * per page load the hook re-writes the pref's cookie when it already exists, with the
13
13
  * same value: the 7 days then count from the last visit, not the last change. Only a
14
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.
15
+ * expires on time. Only a cookie that holds a valid value exactly as `set()` writes
16
+ * it is refreshed: an invalid or unknown value (another subdomain's, a newer
17
+ * release's) is left alone until `set()`. A pref no hook uses is refreshed only by
18
+ * `set()`. A cookie set by the server (`Set-Cookie`, e.g. middleware writing
19
+ * `pref.toCookie(value)`) is not capped, but this refresh re-writes it from the page,
20
+ * so that only helps a pref no hook reads.
19
21
  * @example
20
22
  * const [sidebar, setSidebar] = usePref(prefs.sidebar)
21
23
  * <button onClick={() => setSidebar((open) => !open)}>Toggle</button>
@@ -1,5 +1,5 @@
1
1
  import { ReactNode, ReactElement } from 'react';
2
- import { p as PrefSetter } from '../types-BkCpm4d4.js';
2
+ import { p as PrefSetter } from '../types-CQ_6o7nc.js';
3
3
  import { PrefsSnapshot, Pref } from '../index.js';
4
4
 
5
5
  /**
@@ -12,10 +12,12 @@ import { PrefsSnapshot, Pref } from '../index.js';
12
12
  * per page load the hook re-writes the pref's cookie when it already exists, with the
13
13
  * same value: the 7 days then count from the last visit, not the last change. Only a
14
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.
15
+ * expires on time. Only a cookie that holds a valid value exactly as `set()` writes
16
+ * it is refreshed: an invalid or unknown value (another subdomain's, a newer
17
+ * release's) is left alone until `set()`. A pref no hook uses is refreshed only by
18
+ * `set()`. A cookie set by the server (`Set-Cookie`, e.g. middleware writing
19
+ * `pref.toCookie(value)`) is not capped, but this refresh re-writes it from the page,
20
+ * so that only helps a pref no hook reads.
19
21
  * @example
20
22
  * const [sidebar, setSidebar] = usePref(prefs.sidebar)
21
23
  * <button onClick={() => setSidebar((open) => !open)}>Toggle</button>
@@ -20,7 +20,7 @@ var reapply = (script) => {
20
20
  if (m === 1) {
21
21
  const n = parseFloat(v);
22
22
  v = n === +v && isFinite(n) ? "" + n : null;
23
- } else if (m) v = Object.prototype.hasOwnProperty.call(m, v) ? m[v] : null;
23
+ } else if (m) v = {}.hasOwnProperty.call(m, v) ? m[v] : null;
24
24
  } catch {
25
25
  v = null;
26
26
  }
@@ -54,7 +54,7 @@ function usePref(pref) {
54
54
  seen.add(pref);
55
55
  try {
56
56
  const current = pref.get();
57
- if (current !== void 0 && pref.toCookie(current).maxAge > 604800 && ("; " + document.cookie).indexOf("; " + pref.name + "=") >= 0 && pref.read({ [pref.name]: pref.toCookie(current).value }) === current)
57
+ if (current !== void 0 && pref.toCookie(current).maxAge > 604800 && ("; " + document.cookie).split("; " + pref.name + "=")[1]?.split(";")[0] === encodeURIComponent(pref.toCookie(current).value))
58
58
  pref.set(() => current);
59
59
  } catch {
60
60
  }
@@ -9,20 +9,18 @@ var jsxRuntime = require('react/jsx-runtime');
9
9
 
10
10
  // src/theme/script.ts
11
11
  var MEDIA = "(prefers-color-scheme: dark)";
12
- var SOURCE = `(function(k,l,a,m,d,f,s,c){var D=document,h=D.documentElement,o={}.hasOwnProperty,x,i,j;if(!f){x=('; '+D.cookie).split('; '+k+'=')[1];try{x=x!=null?decodeURIComponent(x.split(';')[0].replace(/^"(.*)"$/,'$1')):localStorage.getItem(l)}catch(e){x=null}f=x!=null&&o.call(m,x)?x:d}if(f=='system'&&s)f=matchMedia('` + MEDIA + "').matches?'dark':'light';x=o.call(m,f)?m[f]:f;for(i=0;i<a.length;i++)try{if(a[i]=='class'){for(j in m)h.classList.remove(m[j]);h.classList.add(x)}else h.setAttribute(a[i],x)}catch(e){}if(c!=null)h.style.colorScheme=/^(light|dark)$/.test(f)?f:c})";
13
- var themeScript = (config) => SOURCE + ".apply(0," + JSON.stringify(config).replace(
12
+ var SOURCE = `(function(k,l,a,m,d,f,s,c){var h=document.documentElement,x,i,j;if(!f){x=('; '+document.cookie).split('; '+k+'=')[1];try{x=x!=null?decodeURIComponent(x.split(';')[0].replace(/^"(.*)"$/,'$1')):localStorage.getItem(l)}catch(e){x=null}f=x!=null&&{}.hasOwnProperty.call(m,x)?x:d}if(f=='system'&&s)f=matchMedia('` + MEDIA + "').matches?'dark':'light';x={}.hasOwnProperty.call(m,f)?m[f]:f;for(i=0;i<a.length;i++)try{if(a[i]=='class'){for(j in m)h.classList.remove(m[j]);h.classList.add(x)}else h.setAttribute(a[i],x)}catch(e){}if(c!=null)h.style.colorScheme=/^(light|dark)$/.test(f)?f:c}).apply(0,JSON.parse(";
13
+ var themeScript = (config) => SOURCE + JSON.stringify(JSON.stringify(config)).replace(
14
14
  /[<>&\u2028\u2029]/g,
15
15
  (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
16
- ) + ")";
17
- var has = (map, key) => Object.prototype.hasOwnProperty.call(map, key);
16
+ ) + "))";
18
17
  var media = () => globalThis.matchMedia?.(MEDIA);
19
18
  var system = () => media()?.matches ? "dark" : "light";
20
- var LIGHT_DARK = /^(light|dark)$/;
21
19
  var paint = ([, , attributes, dom, , forced, enableSystem, colorScheme], theme) => {
22
20
  const h = document.documentElement;
23
21
  let t = forced || theme;
24
22
  if (t == "system" && enableSystem) t = system();
25
- const name = has(dom, t) ? dom[t] : t;
23
+ const name = {}.hasOwnProperty.call(dom, t) ? dom[t] : t;
26
24
  for (const attribute of attributes)
27
25
  try {
28
26
  if (attribute == "class") {
@@ -31,19 +29,18 @@ var paint = ([, , attributes, dom, , forced, enableSystem, colorScheme], theme)
31
29
  } else h.setAttribute(attribute, name);
32
30
  } catch {
33
31
  }
34
- if (colorScheme != null) h.style.colorScheme = LIGHT_DARK.test(t) ? t : colorScheme;
32
+ if (colorScheme != null) h.style.colorScheme = /^(light|dark)$/.test(t) ? t : colorScheme;
35
33
  };
36
34
  var pauseTransitions = (nonce) => {
37
35
  const css = document.createElement("style");
38
36
  if (nonce) css.setAttribute("nonce", nonce);
39
- css.appendChild(document.createTextNode("*,*::before,*::after{transition:none!important}"));
37
+ css.textContent = "*,*::before,*::after{transition:none!important}";
40
38
  document.head.appendChild(css);
41
39
  return () => {
42
- restyle();
40
+ void getComputedStyle(document.documentElement).opacity;
43
41
  setTimeout(() => css.remove(), 1);
44
42
  };
45
43
  };
46
- var restyle = () => getComputedStyle(document.documentElement).opacity;
47
44
  var Context = react.createContext(void 0);
48
45
  var outside = { setTheme: () => {
49
46
  }, themes: [] };
@@ -59,7 +56,7 @@ var subscribeSystem = (onChange) => {
59
56
  };
60
57
  };
61
58
  var none = () => void 0;
62
- var exists = (name) => ("; " + document.cookie).indexOf("; " + name + "=") >= 0;
59
+ var textOf = (name) => ("; " + document.cookie).split("; " + name + "=")[1]?.split(";")[0];
63
60
  var seen = /* @__PURE__ */ new Set();
64
61
  function ThemeProvider(props) {
65
62
  return react.useContext(Context) ? /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: props.children }) : /* @__PURE__ */ jsxRuntime.jsx(Theme, { ...props });
@@ -91,7 +88,7 @@ function Theme({
91
88
  forcedTheme || null,
92
89
  enableSystem ? 1 : 0,
93
90
  // `color-scheme` for other themes: the default when it is light or dark, as in next-themes
94
- enableColorScheme ? LIGHT_DARK.test(defaultTheme) ? defaultTheme : "" : null
91
+ enableColorScheme ? /^(light|dark)$/.test(defaultTheme) ? defaultTheme : "" : null
95
92
  ];
96
93
  const script = themeScript(fresh);
97
94
  const [first] = react.useState({ __html: script });
@@ -101,7 +98,7 @@ function Theme({
101
98
  }).theme;
102
99
  const setTheme2 = (next) => {
103
100
  const name = typeof next == "function" ? next(handle2.get()) : next;
104
- if (has(dom, name)) handle2.set(name);
101
+ if ({}.hasOwnProperty.call(dom, name)) handle2.set(name);
105
102
  };
106
103
  return [handle2, fresh, listed, setTheme2];
107
104
  }, [script, JSON.stringify(cookie)]);
@@ -113,14 +110,16 @@ function Theme({
113
110
  const once = !seen.has(handle.name);
114
111
  seen.add(handle.name);
115
112
  try {
116
- if (!exists(handle.name)) {
113
+ const text = textOf(handle.name);
114
+ if (text == null) {
117
115
  const stored = localStorage.getItem(config[1]);
118
116
  if (stored != null) {
119
- const valid = has(config[3], stored);
117
+ const valid = {}.hasOwnProperty.call(config[3], stored);
120
118
  if (valid) handle.set(stored);
121
- if (!valid || exists(handle.name)) localStorage.removeItem(config[1]);
119
+ if (!valid || textOf(handle.name) != null) localStorage.removeItem(config[1]);
122
120
  }
123
- } else if (once && handle.toCookie(handle.get()).maxAge > 604800) handle.set(handle.get());
121
+ } else if (once && text == encodeURIComponent(handle.get()) && handle.toCookie(handle.get()).maxAge > 604800)
122
+ handle.set(handle.get());
124
123
  } catch {
125
124
  }
126
125
  const resume = disableTransitionOnChange && pauseTransitions(nonce);
@@ -74,8 +74,11 @@ interface UseThemeProps<T extends string = string> {
74
74
  * Safari caps cookies written by scripts at 7 days, so once per page load the
75
75
  * provider re-writes an existing theme cookie: the choice lasts 7 days after the
76
76
  * last visit there, not after the last change. Only when `cookie.maxAge` is longer
77
- * than 7 days, so a shorter lifetime still ends on time. A cookie set by the server
78
- * (`Set-Cookie`, e.g. middleware) is not capped until the provider re-writes it.
77
+ * than 7 days, so a shorter lifetime still ends on time, and only when the cookie
78
+ * holds a listed theme exactly as the provider writes it: a theme it does not list
79
+ * (another subdomain's, a newer release's) is left alone until `setTheme()`. A
80
+ * cookie set by the server (`Set-Cookie`, e.g. middleware) is not capped until the
81
+ * provider re-writes it.
79
82
  * @example
80
83
  * <html lang="en" suppressHydrationWarning>
81
84
  * <body>
@@ -74,8 +74,11 @@ interface UseThemeProps<T extends string = string> {
74
74
  * Safari caps cookies written by scripts at 7 days, so once per page load the
75
75
  * provider re-writes an existing theme cookie: the choice lasts 7 days after the
76
76
  * last visit there, not after the last change. Only when `cookie.maxAge` is longer
77
- * than 7 days, so a shorter lifetime still ends on time. A cookie set by the server
78
- * (`Set-Cookie`, e.g. middleware) is not capped until the provider re-writes it.
77
+ * than 7 days, so a shorter lifetime still ends on time, and only when the cookie
78
+ * holds a listed theme exactly as the provider writes it: a theme it does not list
79
+ * (another subdomain's, a newer release's) is left alone until `setTheme()`. A
80
+ * cookie set by the server (`Set-Cookie`, e.g. middleware) is not capped until the
81
+ * provider re-writes it.
79
82
  * @example
80
83
  * <html lang="en" suppressHydrationWarning>
81
84
  * <body>
@@ -7,20 +7,18 @@ import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
7
7
 
8
8
  // src/theme/script.ts
9
9
  var MEDIA = "(prefers-color-scheme: dark)";
10
- var SOURCE = `(function(k,l,a,m,d,f,s,c){var D=document,h=D.documentElement,o={}.hasOwnProperty,x,i,j;if(!f){x=('; '+D.cookie).split('; '+k+'=')[1];try{x=x!=null?decodeURIComponent(x.split(';')[0].replace(/^"(.*)"$/,'$1')):localStorage.getItem(l)}catch(e){x=null}f=x!=null&&o.call(m,x)?x:d}if(f=='system'&&s)f=matchMedia('` + MEDIA + "').matches?'dark':'light';x=o.call(m,f)?m[f]:f;for(i=0;i<a.length;i++)try{if(a[i]=='class'){for(j in m)h.classList.remove(m[j]);h.classList.add(x)}else h.setAttribute(a[i],x)}catch(e){}if(c!=null)h.style.colorScheme=/^(light|dark)$/.test(f)?f:c})";
11
- var themeScript = (config) => SOURCE + ".apply(0," + JSON.stringify(config).replace(
10
+ var SOURCE = `(function(k,l,a,m,d,f,s,c){var h=document.documentElement,x,i,j;if(!f){x=('; '+document.cookie).split('; '+k+'=')[1];try{x=x!=null?decodeURIComponent(x.split(';')[0].replace(/^"(.*)"$/,'$1')):localStorage.getItem(l)}catch(e){x=null}f=x!=null&&{}.hasOwnProperty.call(m,x)?x:d}if(f=='system'&&s)f=matchMedia('` + MEDIA + "').matches?'dark':'light';x={}.hasOwnProperty.call(m,f)?m[f]:f;for(i=0;i<a.length;i++)try{if(a[i]=='class'){for(j in m)h.classList.remove(m[j]);h.classList.add(x)}else h.setAttribute(a[i],x)}catch(e){}if(c!=null)h.style.colorScheme=/^(light|dark)$/.test(f)?f:c}).apply(0,JSON.parse(";
11
+ var themeScript = (config) => SOURCE + JSON.stringify(JSON.stringify(config)).replace(
12
12
  /[<>&\u2028\u2029]/g,
13
13
  (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
14
- ) + ")";
15
- var has = (map, key) => Object.prototype.hasOwnProperty.call(map, key);
14
+ ) + "))";
16
15
  var media = () => globalThis.matchMedia?.(MEDIA);
17
16
  var system = () => media()?.matches ? "dark" : "light";
18
- var LIGHT_DARK = /^(light|dark)$/;
19
17
  var paint = ([, , attributes, dom, , forced, enableSystem, colorScheme], theme) => {
20
18
  const h = document.documentElement;
21
19
  let t = forced || theme;
22
20
  if (t == "system" && enableSystem) t = system();
23
- const name = has(dom, t) ? dom[t] : t;
21
+ const name = {}.hasOwnProperty.call(dom, t) ? dom[t] : t;
24
22
  for (const attribute of attributes)
25
23
  try {
26
24
  if (attribute == "class") {
@@ -29,19 +27,18 @@ var paint = ([, , attributes, dom, , forced, enableSystem, colorScheme], theme)
29
27
  } else h.setAttribute(attribute, name);
30
28
  } catch {
31
29
  }
32
- if (colorScheme != null) h.style.colorScheme = LIGHT_DARK.test(t) ? t : colorScheme;
30
+ if (colorScheme != null) h.style.colorScheme = /^(light|dark)$/.test(t) ? t : colorScheme;
33
31
  };
34
32
  var pauseTransitions = (nonce) => {
35
33
  const css = document.createElement("style");
36
34
  if (nonce) css.setAttribute("nonce", nonce);
37
- css.appendChild(document.createTextNode("*,*::before,*::after{transition:none!important}"));
35
+ css.textContent = "*,*::before,*::after{transition:none!important}";
38
36
  document.head.appendChild(css);
39
37
  return () => {
40
- restyle();
38
+ void getComputedStyle(document.documentElement).opacity;
41
39
  setTimeout(() => css.remove(), 1);
42
40
  };
43
41
  };
44
- var restyle = () => getComputedStyle(document.documentElement).opacity;
45
42
  var Context = createContext(void 0);
46
43
  var outside = { setTheme: () => {
47
44
  }, themes: [] };
@@ -57,7 +54,7 @@ var subscribeSystem = (onChange) => {
57
54
  };
58
55
  };
59
56
  var none = () => void 0;
60
- var exists = (name) => ("; " + document.cookie).indexOf("; " + name + "=") >= 0;
57
+ var textOf = (name) => ("; " + document.cookie).split("; " + name + "=")[1]?.split(";")[0];
61
58
  var seen = /* @__PURE__ */ new Set();
62
59
  function ThemeProvider(props) {
63
60
  return useContext(Context) ? /* @__PURE__ */ jsx(Fragment, { children: props.children }) : /* @__PURE__ */ jsx(Theme, { ...props });
@@ -89,7 +86,7 @@ function Theme({
89
86
  forcedTheme || null,
90
87
  enableSystem ? 1 : 0,
91
88
  // `color-scheme` for other themes: the default when it is light or dark, as in next-themes
92
- enableColorScheme ? LIGHT_DARK.test(defaultTheme) ? defaultTheme : "" : null
89
+ enableColorScheme ? /^(light|dark)$/.test(defaultTheme) ? defaultTheme : "" : null
93
90
  ];
94
91
  const script = themeScript(fresh);
95
92
  const [first] = useState({ __html: script });
@@ -99,7 +96,7 @@ function Theme({
99
96
  }).theme;
100
97
  const setTheme2 = (next) => {
101
98
  const name = typeof next == "function" ? next(handle2.get()) : next;
102
- if (has(dom, name)) handle2.set(name);
99
+ if ({}.hasOwnProperty.call(dom, name)) handle2.set(name);
103
100
  };
104
101
  return [handle2, fresh, listed, setTheme2];
105
102
  }, [script, JSON.stringify(cookie)]);
@@ -111,14 +108,16 @@ function Theme({
111
108
  const once = !seen.has(handle.name);
112
109
  seen.add(handle.name);
113
110
  try {
114
- if (!exists(handle.name)) {
111
+ const text = textOf(handle.name);
112
+ if (text == null) {
115
113
  const stored = localStorage.getItem(config[1]);
116
114
  if (stored != null) {
117
- const valid = has(config[3], stored);
115
+ const valid = {}.hasOwnProperty.call(config[3], stored);
118
116
  if (valid) handle.set(stored);
119
- if (!valid || exists(handle.name)) localStorage.removeItem(config[1]);
117
+ if (!valid || textOf(handle.name) != null) localStorage.removeItem(config[1]);
120
118
  }
121
- } else if (once && handle.toCookie(handle.get()).maxAge > 604800) handle.set(handle.get());
119
+ } else if (once && text == encodeURIComponent(handle.get()) && handle.toCookie(handle.get()).maxAge > 604800)
120
+ handle.set(handle.get());
122
121
  } catch {
123
122
  }
124
123
  const resume = disableTransitionOnChange && pauseTransitions(nonce);
@@ -36,7 +36,11 @@ interface PrefsOptions extends CookieOptions {
36
36
  }
37
37
  /** Options for a single pref, passed to `.options()`. They override `PrefsOptions`. */
38
38
  interface PrefOptions extends CookieOptions {
39
- /** Full cookie name for this pref. `prefix` is not applied to it. @default prefix + key */
39
+ /**
40
+ * Full cookie name for this pref. `prefix` is not applied to it. Must not be empty
41
+ * (`definePrefs()` throws in development).
42
+ * @default prefix + key
43
+ */
40
44
  name?: string | undefined;
41
45
  }
42
46
  /**
@@ -166,18 +170,32 @@ interface Pref<T, V = T> {
166
170
  readonly defaultValue: V;
167
171
  /**
168
172
  * Current value from `document.cookie`. Returns the default where there is no
169
- * DOM; on the server use `read()` instead.
173
+ * DOM; on the server use `read()` instead. The same cookie returns the same object,
174
+ * shared with every other reader: treat json and custom values as read-only.
170
175
  */
171
176
  get(): V;
172
177
  /** Write the cookie in the browser and notify subscribers in this and other tabs. No-op on the server. */
173
178
  set(value: T | ((prev: V) => T)): void;
174
179
  /** Delete the cookie, so the value goes back to the default. No-op on the server. */
175
180
  reset(): void;
176
- /** Listen for changes from this tab and other tabs. Returns an unsubscribe function. */
181
+ /**
182
+ * Listen for changes from this tab and other tabs. Returns an unsubscribe function.
183
+ * Listeners run synchronously, in subscription order. A listener that throws does not
184
+ * stop the others and never makes `set()` or `reset()` throw: its error is thrown
185
+ * again from a `setTimeout` callback, so it reaches the global error handler
186
+ * (`window.onerror`, error monitoring) instead of being swallowed. A listener that
187
+ * writes the pref notifies everyone of the new value at once; the rest of the older
188
+ * round is skipped. Listeners are a set: the same function subscribed twice is called
189
+ * once per change and removed by the first unsubscribe.
190
+ */
177
191
  subscribe(listener: (value: V) => void): () => void;
178
192
  /**
179
193
  * Read the value from request cookies (stores and maps hold URI-decoded values).
180
- * Pure; never throws. Cached per raw string, so the same cookie returns the same object.
194
+ * Pure; never throws. In the browser, like `get()`, it is cached per raw string: the
195
+ * same cookie returns the same object to every caller. Without a DOM (on the server)
196
+ * every call parses again, so requests never share a parsed value. Treat json and
197
+ * custom values, and the `.default()` value (always returned as is), as read-only:
198
+ * copy them before changing anything.
181
199
  */
182
200
  read(source: CookieSource): V;
183
201
  /**
@@ -36,7 +36,11 @@ interface PrefsOptions extends CookieOptions {
36
36
  }
37
37
  /** Options for a single pref, passed to `.options()`. They override `PrefsOptions`. */
38
38
  interface PrefOptions extends CookieOptions {
39
- /** Full cookie name for this pref. `prefix` is not applied to it. @default prefix + key */
39
+ /**
40
+ * Full cookie name for this pref. `prefix` is not applied to it. Must not be empty
41
+ * (`definePrefs()` throws in development).
42
+ * @default prefix + key
43
+ */
40
44
  name?: string | undefined;
41
45
  }
42
46
  /**
@@ -166,18 +170,32 @@ interface Pref<T, V = T> {
166
170
  readonly defaultValue: V;
167
171
  /**
168
172
  * Current value from `document.cookie`. Returns the default where there is no
169
- * DOM; on the server use `read()` instead.
173
+ * DOM; on the server use `read()` instead. The same cookie returns the same object,
174
+ * shared with every other reader: treat json and custom values as read-only.
170
175
  */
171
176
  get(): V;
172
177
  /** Write the cookie in the browser and notify subscribers in this and other tabs. No-op on the server. */
173
178
  set(value: T | ((prev: V) => T)): void;
174
179
  /** Delete the cookie, so the value goes back to the default. No-op on the server. */
175
180
  reset(): void;
176
- /** Listen for changes from this tab and other tabs. Returns an unsubscribe function. */
181
+ /**
182
+ * Listen for changes from this tab and other tabs. Returns an unsubscribe function.
183
+ * Listeners run synchronously, in subscription order. A listener that throws does not
184
+ * stop the others and never makes `set()` or `reset()` throw: its error is thrown
185
+ * again from a `setTimeout` callback, so it reaches the global error handler
186
+ * (`window.onerror`, error monitoring) instead of being swallowed. A listener that
187
+ * writes the pref notifies everyone of the new value at once; the rest of the older
188
+ * round is skipped. Listeners are a set: the same function subscribed twice is called
189
+ * once per change and removed by the first unsubscribe.
190
+ */
177
191
  subscribe(listener: (value: V) => void): () => void;
178
192
  /**
179
193
  * Read the value from request cookies (stores and maps hold URI-decoded values).
180
- * Pure; never throws. Cached per raw string, so the same cookie returns the same object.
194
+ * Pure; never throws. In the browser, like `get()`, it is cached per raw string: the
195
+ * same cookie returns the same object to every caller. Without a DOM (on the server)
196
+ * every call parses again, so requests never share a parsed value. Treat json and
197
+ * custom values, and the `.default()` value (always returned as is), as read-only:
198
+ * copy them before changing anything.
181
199
  */
182
200
  read(source: CookieSource): V;
183
201
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cookie-prefs",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Typed cookie-backed user preference state for React and Next.js",
5
5
  "keywords": [
6
6
  "react",
@@ -92,6 +92,7 @@
92
92
  "typecheck": "tsc --noEmit",
93
93
  "lint": "eslint .",
94
94
  "size": "size-limit",
95
+ "e2e": "node e2e/scripts/run.mjs",
95
96
  "check:package": "publint && attw --pack .",
96
97
  "prepublishOnly": "npm run lint && npm run typecheck && npm run build && npm test && npm run check:package && npm run size"
97
98
  },
@@ -123,7 +124,7 @@
123
124
  {
124
125
  "name": "cookie-prefs/theme",
125
126
  "path": "dist/theme/index.js",
126
- "limit": "1910 B",
127
+ "limit": "1900 B",
127
128
  "gzip": true,
128
129
  "ignore": [
129
130
  "cookie-prefs"