cookie-prefs 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +133 -2
- package/dist/index.cjs +234 -0
- package/dist/index.d.cts +126 -0
- package/dist/index.d.ts +126 -0
- package/dist/index.js +228 -0
- package/dist/next/index.cjs +43 -0
- package/dist/next/index.d.cts +48 -0
- package/dist/next/index.d.ts +48 -0
- package/dist/next/index.js +40 -0
- package/dist/react/index.cjs +98 -0
- package/dist/react/index.d.cts +65 -0
- package/dist/react/index.d.ts +65 -0
- package/dist/react/index.js +95 -0
- package/dist/theme/index.cjs +169 -0
- package/dist/theme/index.d.cts +97 -0
- package/dist/theme/index.d.ts +97 -0
- package/dist/theme/index.js +166 -0
- package/dist/types-91el0WaV.d.cts +208 -0
- package/dist/types-91el0WaV.d.ts +208 -0
- package/package.json +169 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Stanislav Kozachenko
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,134 @@
|
|
|
1
|
-
#
|
|
1
|
+
# cookie-prefs
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://github.com/StanislavKozachenko/cookie-prefs/actions/workflows/ci.yml)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
|
|
6
|
+
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.
|
|
7
|
+
|
|
8
|
+
- Readable in Server Components and on the client, with no hydration flash.
|
|
9
|
+
- Reflected on `<html>` before first paint (class, `data-*` attribute or CSS variable), so CSS can react to a preference without JavaScript.
|
|
10
|
+
- Synced across tabs.
|
|
11
|
+
- Typed end to end; invalid or missing cookies read as the default and never throw.
|
|
12
|
+
- The core has zero dependencies and fits a 2 kB gzip budget. `react` and `next` are optional peer dependencies.
|
|
13
|
+
- `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.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npm install cookie-prefs
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Peer dependencies, both optional: `react >=18` (for `cookie-prefs/react`, `cookie-prefs/next`, `cookie-prefs/theme`) and `next >=14` (for `cookie-prefs/next`).
|
|
22
|
+
|
|
23
|
+
## Quick start (Next.js App Router)
|
|
24
|
+
|
|
25
|
+
Define the prefs once in a plain module that both server and client code import:
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
// app/prefs.ts
|
|
29
|
+
import { definePrefs, pref } from 'cookie-prefs'
|
|
30
|
+
|
|
31
|
+
export const prefs = definePrefs({
|
|
32
|
+
theme: pref.enum(['light', 'dark', 'system']).default('system').reflect('class'),
|
|
33
|
+
sidebar: pref.boolean().default(true).reflect('data-sidebar'),
|
|
34
|
+
pageSize: pref.number().default(25),
|
|
35
|
+
locale: pref.string(), // string | undefined
|
|
36
|
+
})
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Add the provider to the root layout, at the top of `<body>`, and `suppressHydrationWarning` on `<html>` (the inline script changes its attributes before React hydrates):
|
|
40
|
+
|
|
41
|
+
```tsx
|
|
42
|
+
// app/layout.tsx
|
|
43
|
+
import { PrefsProvider } from 'cookie-prefs/next'
|
|
44
|
+
import { prefs } from './prefs'
|
|
45
|
+
|
|
46
|
+
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
47
|
+
return (
|
|
48
|
+
<html lang="en" suppressHydrationWarning>
|
|
49
|
+
<body>
|
|
50
|
+
<PrefsProvider prefs={prefs}>{children}</PrefsProvider>
|
|
51
|
+
</body>
|
|
52
|
+
</html>
|
|
53
|
+
)
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Use a pref in a Client Component like `useState`:
|
|
58
|
+
|
|
59
|
+
```tsx
|
|
60
|
+
'use client'
|
|
61
|
+
import { usePref } from 'cookie-prefs/react'
|
|
62
|
+
import { prefs } from './prefs'
|
|
63
|
+
|
|
64
|
+
export function SidebarToggle() {
|
|
65
|
+
const [sidebar, setSidebar] = usePref(prefs.sidebar)
|
|
66
|
+
return <button onClick={() => setSidebar((open) => !open)}>{sidebar ? 'Hide' : 'Show'}</button>
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Read it in a Server Component (this makes the route dynamic):
|
|
71
|
+
|
|
72
|
+
```tsx
|
|
73
|
+
import { getPrefs } from 'cookie-prefs/next'
|
|
74
|
+
import { prefs } from './prefs'
|
|
75
|
+
|
|
76
|
+
export default async function Page() {
|
|
77
|
+
const { sidebar, pageSize } = await getPrefs(prefs) // typed: boolean, number
|
|
78
|
+
return <Shell collapsed={!sidebar} pageSize={pageSize} />
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Write it on the server with `toCookie`, for example in a Server Action:
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
'use server'
|
|
86
|
+
import { cookies } from 'next/headers'
|
|
87
|
+
import { prefs } from './prefs'
|
|
88
|
+
|
|
89
|
+
export async function setLocale(locale: string) {
|
|
90
|
+
const store = await cookies()
|
|
91
|
+
store.set(prefs.locale.toCookie(locale))
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## The entries
|
|
96
|
+
|
|
97
|
+
| Import | What it is | Guide |
|
|
98
|
+
| -------------------- | ------------------------------------------------------------------------------------------- | ----- |
|
|
99
|
+
| `cookie-prefs` | Core, no DOM required: `definePrefs`, `pref.*`, `readPrefs`, `snapshotPrefs`, `prefsScript` | [Core](docs/core.md) |
|
|
100
|
+
| `cookie-prefs/react` | `usePref`, and `PrefsProvider` for SSR outside Next.js | [Core](docs/core.md#cookie-prefsreact-outside-nextjs) |
|
|
101
|
+
| `cookie-prefs/next` | Server-only: `PrefsProvider`, `getPrefs` (App Router) | [Next.js](docs/nextjs.md) |
|
|
102
|
+
| `cookie-prefs/theme` | next-themes compatible `ThemeProvider` and `useTheme` | [Theme](docs/theme.md) |
|
|
103
|
+
|
|
104
|
+
## Next.js modes
|
|
105
|
+
|
|
106
|
+
`PrefsProvider` runs in `script` mode by default (the route stays static, hooks render defaults until hydration) or `mode="server"` (the route becomes dynamic, hooks render the exact cookie values). Cache Components, `router.refresh()` and nonce are covered in the [Next.js guide](docs/nextjs.md).
|
|
107
|
+
|
|
108
|
+
## Reflection
|
|
109
|
+
|
|
110
|
+
`.reflect('class' | 'data-*' | '--name')` mirrors a pref on `<html>` before first paint, so CSS reacts to it without JavaScript. See [Reflection](docs/reflection.md), including the warning about reflecting free-form strings.
|
|
111
|
+
|
|
112
|
+
## Migrating from next-themes
|
|
113
|
+
|
|
114
|
+
```diff
|
|
115
|
+
- import { ThemeProvider, useTheme } from 'next-themes'
|
|
116
|
+
+ import { ThemeProvider, useTheme } from 'cookie-prefs/theme'
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
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).
|
|
120
|
+
|
|
121
|
+
## Security and platform notes
|
|
122
|
+
|
|
123
|
+
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).
|
|
124
|
+
|
|
125
|
+
## Compatibility
|
|
126
|
+
|
|
127
|
+
- React 18 and 19.
|
|
128
|
+
- Next.js 14 and newer, App Router. For the Pages Router use `cookie-prefs/react` with `snapshotPrefs`. `>=14` is the supported range; the project's end-to-end tests do not cover every Next.js major.
|
|
129
|
+
- CI runs lint, type checks, build and tests on Node.js 22 and 24, on Linux, Windows and macOS. The package declares no `engines`.
|
|
130
|
+
- ESM and CJS builds with types for every entry.
|
|
131
|
+
|
|
132
|
+
## More
|
|
133
|
+
|
|
134
|
+
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).
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/core/cookie.ts
|
|
4
|
+
var rawOf = (source, name) => {
|
|
5
|
+
if (typeof source == "string") {
|
|
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
|
+
);
|
|
12
|
+
}
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
return typeof source?.get == "function" ? source.get(name)?.value : source?.[name];
|
|
16
|
+
};
|
|
17
|
+
var merge = (...sources) => Object.fromEntries(sources.flatMap((s) => Object.entries({ ...s }).filter((e) => e[1] != null)));
|
|
18
|
+
var defaults = { path: "/", maxAge: 3456e4, sameSite: "lax" };
|
|
19
|
+
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" : "");
|
|
20
|
+
|
|
21
|
+
// src/core/builder.ts
|
|
22
|
+
var builder = (def) => ({
|
|
23
|
+
...def,
|
|
24
|
+
default: (d) => builder({ ...def, d }),
|
|
25
|
+
options: (o) => builder({ ...def, o: merge(def.o, o) }),
|
|
26
|
+
reflect: (r, m) => builder({ ...def, r: [].concat(r), m })
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
// src/core/reflect.ts
|
|
30
|
+
var domOf = (kind, value) => value == null ? null : typeof kind == "object" ? kind[value] ?? null : String(value);
|
|
31
|
+
var apply = (targets, kind, s) => {
|
|
32
|
+
const h = document.documentElement;
|
|
33
|
+
try {
|
|
34
|
+
for (const t of targets)
|
|
35
|
+
if (t == "class") {
|
|
36
|
+
for (const k in kind) h.classList.remove(kind[k]);
|
|
37
|
+
if (s != null) h.classList.add(s);
|
|
38
|
+
} else if (t[0] == "-") {
|
|
39
|
+
if (s == null) h.style.removeProperty(t);
|
|
40
|
+
else h.style.setProperty(t, s);
|
|
41
|
+
} else if (s == null) h.removeAttribute(t);
|
|
42
|
+
else h.setAttribute(t, s);
|
|
43
|
+
} catch {
|
|
44
|
+
}
|
|
45
|
+
};
|
|
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){}})(';
|
|
47
|
+
var script = (config) => config.length ? SOURCE + JSON.stringify(JSON.stringify(config)).replace(
|
|
48
|
+
/[<>&\u2028\u2029]/g,
|
|
49
|
+
(c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
|
|
50
|
+
) + ")" : "";
|
|
51
|
+
|
|
52
|
+
// src/core/sync.ts
|
|
53
|
+
var CHANNEL = "cookie-prefs";
|
|
54
|
+
var subs = /* @__PURE__ */ new Set();
|
|
55
|
+
var off;
|
|
56
|
+
var changed = () => subs.forEach((check) => check());
|
|
57
|
+
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
|
+
};
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
var post = () => {
|
|
77
|
+
if (!globalThis.cookieStore && typeof BroadcastChannel == "function") {
|
|
78
|
+
const channel = new BroadcastChannel(CHANNEL);
|
|
79
|
+
channel.postMessage(0);
|
|
80
|
+
channel.close();
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
// src/core/store.ts
|
|
85
|
+
var REFLECTION = /* @__PURE__ */ Symbol.for("cookie-prefs.reflection.1");
|
|
86
|
+
var hasDom = () => typeof document != "undefined";
|
|
87
|
+
var bind = (key, def, prefix, options) => {
|
|
88
|
+
const name = encodeURIComponent(def.o?.name ?? prefix + key);
|
|
89
|
+
const attrs = merge(defaults, options, def.o, { name });
|
|
90
|
+
const fallback = def.d;
|
|
91
|
+
const targets = def.r;
|
|
92
|
+
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`);
|
|
95
|
+
const cache = /* @__PURE__ */ new Map();
|
|
96
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
97
|
+
let last;
|
|
98
|
+
const read = (source) => {
|
|
99
|
+
try {
|
|
100
|
+
const raw = rawOf(source, name);
|
|
101
|
+
if (typeof raw == "string" && raw.length <= 4096) {
|
|
102
|
+
if (!cache.has(raw)) {
|
|
103
|
+
if (cache.size > 9) cache.clear();
|
|
104
|
+
cache.set(raw, def.p(raw));
|
|
105
|
+
}
|
|
106
|
+
const value = cache.get(raw);
|
|
107
|
+
if (value !== void 0) return value;
|
|
108
|
+
}
|
|
109
|
+
} catch {
|
|
110
|
+
}
|
|
111
|
+
return fallback;
|
|
112
|
+
};
|
|
113
|
+
let warned = false;
|
|
114
|
+
const get = () => {
|
|
115
|
+
try {
|
|
116
|
+
return read(document.cookie);
|
|
117
|
+
} catch {
|
|
118
|
+
}
|
|
119
|
+
if (typeof process == "object" && process.env.NODE_ENV != "production" && !warned) {
|
|
120
|
+
warned = true;
|
|
121
|
+
console.warn(
|
|
122
|
+
`cookie-prefs: ${key}.get() cannot read document.cookie here and returns the default. On the server use read() or getPrefs().`
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
return fallback;
|
|
126
|
+
};
|
|
127
|
+
const check = () => {
|
|
128
|
+
const value = get();
|
|
129
|
+
if (targets) apply(targets, kind, domOf(kind, value));
|
|
130
|
+
if (!Object.is(value, last)) {
|
|
131
|
+
last = value;
|
|
132
|
+
listeners.forEach((listener) => listener(value));
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
const write = (value) => {
|
|
136
|
+
try {
|
|
137
|
+
document.cookie = serialize(attrs, value);
|
|
138
|
+
post();
|
|
139
|
+
} catch {
|
|
140
|
+
}
|
|
141
|
+
check();
|
|
142
|
+
};
|
|
143
|
+
const handle = {
|
|
144
|
+
key,
|
|
145
|
+
name,
|
|
146
|
+
defaultValue: fallback,
|
|
147
|
+
get,
|
|
148
|
+
set: (value) => {
|
|
149
|
+
if (hasDom()) write(def.s(typeof value == "function" ? value(get()) : value));
|
|
150
|
+
},
|
|
151
|
+
reset: () => {
|
|
152
|
+
if (hasDom()) write();
|
|
153
|
+
},
|
|
154
|
+
subscribe: (listener) => {
|
|
155
|
+
if (!hasDom()) return () => {
|
|
156
|
+
};
|
|
157
|
+
if (!listeners.size) {
|
|
158
|
+
hub(check, true);
|
|
159
|
+
check();
|
|
160
|
+
}
|
|
161
|
+
listeners.add(listener);
|
|
162
|
+
return () => {
|
|
163
|
+
listeners.delete(listener);
|
|
164
|
+
if (!listeners.size) hub(check, false);
|
|
165
|
+
};
|
|
166
|
+
},
|
|
167
|
+
read,
|
|
168
|
+
toCookie: (value) => ({ ...attrs, value: def.s(value) })
|
|
169
|
+
};
|
|
170
|
+
if (targets)
|
|
171
|
+
Object.defineProperty(handle, REFLECTION, {
|
|
172
|
+
value: [name, targets, kind, domOf(kind, fallback)]
|
|
173
|
+
});
|
|
174
|
+
return handle;
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
// src/index.ts
|
|
178
|
+
var pref = {
|
|
179
|
+
enum: (values) => builder({ values, p: (raw) => values.includes(raw) ? raw : void 0, s: String }),
|
|
180
|
+
boolean: () => builder({
|
|
181
|
+
k: { true: "true", false: "false" },
|
|
182
|
+
p: (raw) => raw == "true" || (raw == "false" ? false : void 0),
|
|
183
|
+
s: String
|
|
184
|
+
}),
|
|
185
|
+
number: () => builder({
|
|
186
|
+
k: 1,
|
|
187
|
+
p: (raw) => {
|
|
188
|
+
const n = parseFloat(raw);
|
|
189
|
+
return n === +raw && isFinite(n) ? n : void 0;
|
|
190
|
+
},
|
|
191
|
+
s: String
|
|
192
|
+
}),
|
|
193
|
+
string: () => builder({ k: 0, p: (raw) => raw, s: String }),
|
|
194
|
+
json: (schema) => builder({
|
|
195
|
+
p: (raw) => {
|
|
196
|
+
const result = schema["~standard"].validate(JSON.parse(raw));
|
|
197
|
+
return "then" in result || result.issues ? void 0 : result.value;
|
|
198
|
+
},
|
|
199
|
+
s: JSON.stringify
|
|
200
|
+
}),
|
|
201
|
+
custom: (codec) => builder({ p: (raw) => codec.parse(raw), s: (value) => codec.serialize(value) })
|
|
202
|
+
};
|
|
203
|
+
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
|
+
}
|
|
208
|
+
function readPrefs(prefs, source) {
|
|
209
|
+
const values = {};
|
|
210
|
+
for (const key in prefs) values[key] = prefs[key].read(source);
|
|
211
|
+
return values;
|
|
212
|
+
}
|
|
213
|
+
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;
|
|
223
|
+
}
|
|
224
|
+
function prefsScript(prefs) {
|
|
225
|
+
return script(
|
|
226
|
+
Object.values(prefs).map((handle) => handle[REFLECTION]).filter((r) => !!r)
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
exports.definePrefs = definePrefs;
|
|
231
|
+
exports.pref = pref;
|
|
232
|
+
exports.prefsScript = prefsScript;
|
|
233
|
+
exports.readPrefs = readPrefs;
|
|
234
|
+
exports.snapshotPrefs = snapshotPrefs;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
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-91el0WaV.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-91el0WaV.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Structural copy of the Standard Schema v1 interface (https://standardschema.dev, MIT).
|
|
6
|
+
* Types only: the core never depends on a validator package. Any zod, valibot or
|
|
7
|
+
* arktype schema matches this shape.
|
|
8
|
+
*/
|
|
9
|
+
interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
10
|
+
readonly '~standard': StandardSchemaV1Props<Input, Output>;
|
|
11
|
+
}
|
|
12
|
+
interface StandardSchemaV1Props<Input = unknown, Output = Input> {
|
|
13
|
+
readonly version: 1;
|
|
14
|
+
readonly vendor: string;
|
|
15
|
+
readonly validate: (value: unknown, options?: StandardSchemaV1Options | undefined) => StandardSchemaV1Result<Output> | Promise<StandardSchemaV1Result<Output>>;
|
|
16
|
+
readonly types?: StandardSchemaV1Types<Input, Output> | undefined;
|
|
17
|
+
}
|
|
18
|
+
interface StandardSchemaV1Options {
|
|
19
|
+
readonly libraryOptions?: Record<string, unknown> | undefined;
|
|
20
|
+
}
|
|
21
|
+
type StandardSchemaV1Result<Output> = {
|
|
22
|
+
readonly value: Output;
|
|
23
|
+
readonly issues?: undefined;
|
|
24
|
+
} | {
|
|
25
|
+
readonly issues: ReadonlyArray<StandardSchemaV1Issue>;
|
|
26
|
+
};
|
|
27
|
+
interface StandardSchemaV1Issue {
|
|
28
|
+
readonly message: string;
|
|
29
|
+
readonly path?: ReadonlyArray<PropertyKey | {
|
|
30
|
+
readonly key: PropertyKey;
|
|
31
|
+
}> | undefined;
|
|
32
|
+
}
|
|
33
|
+
interface StandardSchemaV1Types<Input = unknown, Output = Input> {
|
|
34
|
+
readonly input: Input;
|
|
35
|
+
readonly output: Output;
|
|
36
|
+
}
|
|
37
|
+
/** Input type of a Standard Schema. */
|
|
38
|
+
type InferSchemaInput<S extends StandardSchemaV1> = NonNullable<S['~standard']['types']>['input'];
|
|
39
|
+
/** Output type of a Standard Schema. */
|
|
40
|
+
type InferSchemaOutput<S extends StandardSchemaV1> = NonNullable<S['~standard']['types']>['output'];
|
|
41
|
+
|
|
42
|
+
/** Pref builders. Each returns an immutable builder to pass to `definePrefs()`. */
|
|
43
|
+
interface PrefFactory {
|
|
44
|
+
/**
|
|
45
|
+
* One of a fixed list of strings, stored as is. Any other cookie value reads as the default.
|
|
46
|
+
* @example pref.enum(['light', 'dark', 'system']).default('system')
|
|
47
|
+
*/
|
|
48
|
+
enum<const T extends readonly [string, ...string[]]>(values: T): EnumPrefBuilder<T[number], T[number] | undefined>;
|
|
49
|
+
/**
|
|
50
|
+
* `true` or `false`, stored as `'true'` / `'false'`.
|
|
51
|
+
* @example pref.boolean().default(true)
|
|
52
|
+
*/
|
|
53
|
+
boolean(): ScalarPrefBuilder<boolean>;
|
|
54
|
+
/**
|
|
55
|
+
* A finite number. `NaN` and `Infinity` read as the default.
|
|
56
|
+
* @example pref.number().default(25)
|
|
57
|
+
*/
|
|
58
|
+
number(): ScalarPrefBuilder<number>;
|
|
59
|
+
/**
|
|
60
|
+
* Any string, stored URI-encoded.
|
|
61
|
+
* @example pref.string() // string | undefined
|
|
62
|
+
*/
|
|
63
|
+
string(): ScalarPrefBuilder<string>;
|
|
64
|
+
/**
|
|
65
|
+
* A JSON value checked by any Standard Schema validator (zod, valibot, arktype).
|
|
66
|
+
* Validation must be synchronous; a schema that returns a Promise reads as the default.
|
|
67
|
+
* Writes take the schema's input (it is stored as JSON and validated on read), reads
|
|
68
|
+
* and `.default()` its output; they differ only for transforming schemas.
|
|
69
|
+
* @example pref.json(z.array(z.string())).default([])
|
|
70
|
+
*/
|
|
71
|
+
json<S extends StandardSchemaV1>(schema: S): PrefBuilder<Exclude<InferSchemaInput<S>, undefined>, InferSchemaOutput<S> | undefined, InferSchemaOutput<S>>;
|
|
72
|
+
/**
|
|
73
|
+
* Your own codec. `parse` returning `undefined` or throwing reads as the default.
|
|
74
|
+
* @example pref.custom({ parse: (raw) => new Date(raw), serialize: (d) => d.toISOString() })
|
|
75
|
+
*/
|
|
76
|
+
custom<T>(codec: PrefCodec<T>): PrefBuilder<T>;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Pref builders.
|
|
80
|
+
* @example
|
|
81
|
+
* const prefs = definePrefs({
|
|
82
|
+
* theme: pref.enum(['light', 'dark', 'system']).default('system'),
|
|
83
|
+
* sidebar: pref.boolean().default(true),
|
|
84
|
+
* })
|
|
85
|
+
*/
|
|
86
|
+
declare const pref: PrefFactory;
|
|
87
|
+
/**
|
|
88
|
+
* Bind pref builders to cookie names (`prefix + key`) and return one handle per key.
|
|
89
|
+
* Each pref is its own cookie. Call once at module level and import the result in
|
|
90
|
+
* both server and client code.
|
|
91
|
+
* @example
|
|
92
|
+
* export const prefs = definePrefs(
|
|
93
|
+
* {
|
|
94
|
+
* theme: pref.enum(['light', 'dark', 'system']).default('system').reflect('class'),
|
|
95
|
+
* sidebar: pref.boolean().default(true),
|
|
96
|
+
* },
|
|
97
|
+
* { prefix: 'app.' },
|
|
98
|
+
* )
|
|
99
|
+
* prefs.sidebar.set((open) => !open)
|
|
100
|
+
*/
|
|
101
|
+
declare function definePrefs<S extends PrefShape>(shape: S, options?: PrefsOptions): Prefs<S>;
|
|
102
|
+
/**
|
|
103
|
+
* Read typed values of all prefs from request cookies. Pure; never throws.
|
|
104
|
+
* @example
|
|
105
|
+
* const { theme, sidebar } = readPrefs(prefs, request.headers.get('cookie'))
|
|
106
|
+
*/
|
|
107
|
+
declare function readPrefs<P extends PrefsRecord>(prefs: P, source: CookieSource): PrefValues<P>;
|
|
108
|
+
/**
|
|
109
|
+
* Pick the raw cookie values of these prefs from request cookies, for
|
|
110
|
+
* `<PrefsProvider snapshot>`. Only the prefs' own cookies are copied, keyed by
|
|
111
|
+
* `Pref.name`, with URI-decoded values.
|
|
112
|
+
* @example
|
|
113
|
+
* <PrefsProvider snapshot={snapshotPrefs(prefs, request.headers.get('cookie'))}>
|
|
114
|
+
*/
|
|
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
|
+
|
|
125
|
+
export { CookieSource, EnumPrefBuilder, PrefBuilder, PrefCodec, PrefShape, PrefValues, Prefs, PrefsOptions, PrefsRecord, PrefsSnapshot, ScalarPrefBuilder, definePrefs, pref, prefsScript, readPrefs, snapshotPrefs };
|
|
126
|
+
export type { PrefFactory, StandardSchemaV1 };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
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-91el0WaV.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-91el0WaV.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Structural copy of the Standard Schema v1 interface (https://standardschema.dev, MIT).
|
|
6
|
+
* Types only: the core never depends on a validator package. Any zod, valibot or
|
|
7
|
+
* arktype schema matches this shape.
|
|
8
|
+
*/
|
|
9
|
+
interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
10
|
+
readonly '~standard': StandardSchemaV1Props<Input, Output>;
|
|
11
|
+
}
|
|
12
|
+
interface StandardSchemaV1Props<Input = unknown, Output = Input> {
|
|
13
|
+
readonly version: 1;
|
|
14
|
+
readonly vendor: string;
|
|
15
|
+
readonly validate: (value: unknown, options?: StandardSchemaV1Options | undefined) => StandardSchemaV1Result<Output> | Promise<StandardSchemaV1Result<Output>>;
|
|
16
|
+
readonly types?: StandardSchemaV1Types<Input, Output> | undefined;
|
|
17
|
+
}
|
|
18
|
+
interface StandardSchemaV1Options {
|
|
19
|
+
readonly libraryOptions?: Record<string, unknown> | undefined;
|
|
20
|
+
}
|
|
21
|
+
type StandardSchemaV1Result<Output> = {
|
|
22
|
+
readonly value: Output;
|
|
23
|
+
readonly issues?: undefined;
|
|
24
|
+
} | {
|
|
25
|
+
readonly issues: ReadonlyArray<StandardSchemaV1Issue>;
|
|
26
|
+
};
|
|
27
|
+
interface StandardSchemaV1Issue {
|
|
28
|
+
readonly message: string;
|
|
29
|
+
readonly path?: ReadonlyArray<PropertyKey | {
|
|
30
|
+
readonly key: PropertyKey;
|
|
31
|
+
}> | undefined;
|
|
32
|
+
}
|
|
33
|
+
interface StandardSchemaV1Types<Input = unknown, Output = Input> {
|
|
34
|
+
readonly input: Input;
|
|
35
|
+
readonly output: Output;
|
|
36
|
+
}
|
|
37
|
+
/** Input type of a Standard Schema. */
|
|
38
|
+
type InferSchemaInput<S extends StandardSchemaV1> = NonNullable<S['~standard']['types']>['input'];
|
|
39
|
+
/** Output type of a Standard Schema. */
|
|
40
|
+
type InferSchemaOutput<S extends StandardSchemaV1> = NonNullable<S['~standard']['types']>['output'];
|
|
41
|
+
|
|
42
|
+
/** Pref builders. Each returns an immutable builder to pass to `definePrefs()`. */
|
|
43
|
+
interface PrefFactory {
|
|
44
|
+
/**
|
|
45
|
+
* One of a fixed list of strings, stored as is. Any other cookie value reads as the default.
|
|
46
|
+
* @example pref.enum(['light', 'dark', 'system']).default('system')
|
|
47
|
+
*/
|
|
48
|
+
enum<const T extends readonly [string, ...string[]]>(values: T): EnumPrefBuilder<T[number], T[number] | undefined>;
|
|
49
|
+
/**
|
|
50
|
+
* `true` or `false`, stored as `'true'` / `'false'`.
|
|
51
|
+
* @example pref.boolean().default(true)
|
|
52
|
+
*/
|
|
53
|
+
boolean(): ScalarPrefBuilder<boolean>;
|
|
54
|
+
/**
|
|
55
|
+
* A finite number. `NaN` and `Infinity` read as the default.
|
|
56
|
+
* @example pref.number().default(25)
|
|
57
|
+
*/
|
|
58
|
+
number(): ScalarPrefBuilder<number>;
|
|
59
|
+
/**
|
|
60
|
+
* Any string, stored URI-encoded.
|
|
61
|
+
* @example pref.string() // string | undefined
|
|
62
|
+
*/
|
|
63
|
+
string(): ScalarPrefBuilder<string>;
|
|
64
|
+
/**
|
|
65
|
+
* A JSON value checked by any Standard Schema validator (zod, valibot, arktype).
|
|
66
|
+
* Validation must be synchronous; a schema that returns a Promise reads as the default.
|
|
67
|
+
* Writes take the schema's input (it is stored as JSON and validated on read), reads
|
|
68
|
+
* and `.default()` its output; they differ only for transforming schemas.
|
|
69
|
+
* @example pref.json(z.array(z.string())).default([])
|
|
70
|
+
*/
|
|
71
|
+
json<S extends StandardSchemaV1>(schema: S): PrefBuilder<Exclude<InferSchemaInput<S>, undefined>, InferSchemaOutput<S> | undefined, InferSchemaOutput<S>>;
|
|
72
|
+
/**
|
|
73
|
+
* Your own codec. `parse` returning `undefined` or throwing reads as the default.
|
|
74
|
+
* @example pref.custom({ parse: (raw) => new Date(raw), serialize: (d) => d.toISOString() })
|
|
75
|
+
*/
|
|
76
|
+
custom<T>(codec: PrefCodec<T>): PrefBuilder<T>;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Pref builders.
|
|
80
|
+
* @example
|
|
81
|
+
* const prefs = definePrefs({
|
|
82
|
+
* theme: pref.enum(['light', 'dark', 'system']).default('system'),
|
|
83
|
+
* sidebar: pref.boolean().default(true),
|
|
84
|
+
* })
|
|
85
|
+
*/
|
|
86
|
+
declare const pref: PrefFactory;
|
|
87
|
+
/**
|
|
88
|
+
* Bind pref builders to cookie names (`prefix + key`) and return one handle per key.
|
|
89
|
+
* Each pref is its own cookie. Call once at module level and import the result in
|
|
90
|
+
* both server and client code.
|
|
91
|
+
* @example
|
|
92
|
+
* export const prefs = definePrefs(
|
|
93
|
+
* {
|
|
94
|
+
* theme: pref.enum(['light', 'dark', 'system']).default('system').reflect('class'),
|
|
95
|
+
* sidebar: pref.boolean().default(true),
|
|
96
|
+
* },
|
|
97
|
+
* { prefix: 'app.' },
|
|
98
|
+
* )
|
|
99
|
+
* prefs.sidebar.set((open) => !open)
|
|
100
|
+
*/
|
|
101
|
+
declare function definePrefs<S extends PrefShape>(shape: S, options?: PrefsOptions): Prefs<S>;
|
|
102
|
+
/**
|
|
103
|
+
* Read typed values of all prefs from request cookies. Pure; never throws.
|
|
104
|
+
* @example
|
|
105
|
+
* const { theme, sidebar } = readPrefs(prefs, request.headers.get('cookie'))
|
|
106
|
+
*/
|
|
107
|
+
declare function readPrefs<P extends PrefsRecord>(prefs: P, source: CookieSource): PrefValues<P>;
|
|
108
|
+
/**
|
|
109
|
+
* Pick the raw cookie values of these prefs from request cookies, for
|
|
110
|
+
* `<PrefsProvider snapshot>`. Only the prefs' own cookies are copied, keyed by
|
|
111
|
+
* `Pref.name`, with URI-decoded values.
|
|
112
|
+
* @example
|
|
113
|
+
* <PrefsProvider snapshot={snapshotPrefs(prefs, request.headers.get('cookie'))}>
|
|
114
|
+
*/
|
|
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
|
+
|
|
125
|
+
export { CookieSource, EnumPrefBuilder, PrefBuilder, PrefCodec, PrefShape, PrefValues, Prefs, PrefsOptions, PrefsRecord, PrefsSnapshot, ScalarPrefBuilder, definePrefs, pref, prefsScript, readPrefs, snapshotPrefs };
|
|
126
|
+
export type { PrefFactory, StandardSchemaV1 };
|