@k8ordo/state 2.3.1 → 4.0.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 +16 -13
- package/dist/cookie-state.d.mts +30 -12
- package/dist/cookie-state.mjs +25 -3
- package/dist/hash/codec.d.mts +16 -0
- package/dist/hash/codec.mjs +35 -0
- package/dist/index.d.mts +6 -8
- package/dist/index.mjs +2 -3
- package/dist/page-state.d.mts +36 -23
- package/dist/page-state.mjs +25 -9
- package/dist/row/codec.d.mts +16 -11
- package/dist/row/codec.mjs +13 -7
- package/dist/storage-state.d.mts +1 -1
- package/dist/store/cookie-store.d.mts +7 -2
- package/dist/store/cookie-store.mjs +35 -9
- package/dist/store/memory-store.d.mts +1 -1
- package/dist/store/page-store.d.mts +1 -1
- package/dist/store/page-store.mjs +55 -10
- package/dist/store/storage-store.d.mts +1 -1
- package/dist/store/storage-store.mjs +25 -4
- package/dist/testing.d.mts +20 -0
- package/dist/testing.mjs +46 -0
- package/dist/url/codec.d.mts +3 -0
- package/dist/url/codec.mjs +1 -1
- package/dist/use-app-state.d.mts +8 -7
- package/docs/GUIDE.md +264 -109
- package/docs/llms.txt +43 -21
- package/package.json +13 -9
- package/dist/base.d.mts +0 -7
- package/dist/base.mjs +0 -14
- package/dist/register.d.mts +0 -39
- package/dist/register.mjs +0 -1
package/README.md
CHANGED
|
@@ -28,21 +28,21 @@ pnpm add @k8ordo/state zod
|
|
|
28
28
|
|
|
29
29
|
<!-- peers -->
|
|
30
30
|
|
|
31
|
-
| Package | Version | Required | Needed for
|
|
32
|
-
| ---------------- | ------- | -------- |
|
|
33
|
-
| `react` | ≥19.3.0 | yes | `useAppState`
|
|
34
|
-
| `zod` | ^4.6.6 | yes | the schemas (`zod/mini` works, and is the lighter pick)
|
|
35
|
-
| `@k8ordo/router` | ^
|
|
36
|
-
| `typescript` | ≥7.0.0 | optional | the shipped type declarations
|
|
37
|
-
| `@types/react` | ≥19.3.0 | optional | the shipped type declarations
|
|
31
|
+
| Package | Version | Required | Needed for |
|
|
32
|
+
| ---------------- | ------- | -------- | ---------------------------------------------------------------------- |
|
|
33
|
+
| `react` | ≥19.3.0 | yes | `useAppState` |
|
|
34
|
+
| `zod` | ^4.6.6 | yes | the schemas (`zod/mini` works, and is the lighter pick) |
|
|
35
|
+
| `@k8ordo/router` | ^4.0.0 | optional | page state that stays with the page on screen while the next one loads |
|
|
36
|
+
| `typescript` | ≥7.0.0 | optional | the shipped type declarations |
|
|
37
|
+
| `@types/react` | ≥19.3.0 | optional | the shipped type declarations |
|
|
38
38
|
|
|
39
39
|
<!-- /peers -->
|
|
40
40
|
|
|
41
41
|
The schema ships to the browser here — the client parses and serializes with
|
|
42
42
|
it — so reach for `zod/mini` unless the app already pays for classic `zod`.
|
|
43
|
-
`@k8ordo/router`
|
|
44
|
-
|
|
45
|
-
|
|
43
|
+
Under `@k8ordo/router` — `@k8ordo/framework` included — a page state keeps
|
|
44
|
+
the values of the page on screen while the next one loads; the two agree on
|
|
45
|
+
that through a global symbol, so neither imports the other.
|
|
46
46
|
|
|
47
47
|
## Quick Start
|
|
48
48
|
|
|
@@ -123,8 +123,11 @@ in `defineCookieState` instead of `defineLocalState`: in server mode,
|
|
|
123
123
|
render, so the default never flashes.
|
|
124
124
|
|
|
125
125
|
`update()` applies synchronously, batches per handler into one write (memory
|
|
126
|
-
applies per call), and returns `{ committed, finished }` handles.
|
|
127
|
-
|
|
126
|
+
applies per call), and returns `{ committed, finished }` handles.
|
|
127
|
+
`href(url, values)` puts the state on the URL the router built —
|
|
128
|
+
`href('/products')` from `@k8ordo/router`, a Next.js `Route`, or `''` for
|
|
129
|
+
the page itself — rewriting only its own params and omitting every field at
|
|
130
|
+
its default, so every link is canonical. A value the schema
|
|
128
131
|
rejects — a URL a user edited, a row an older schema wrote — falls back to its
|
|
129
132
|
own default, field by field.
|
|
130
133
|
|
|
@@ -132,7 +135,7 @@ The [design guide](docs/GUIDE.md) covers the rest: the places and when each
|
|
|
132
135
|
fits, history-entry state, cookie state the server renders (and why it is
|
|
133
136
|
never a secret), migrating stored rows with `version` and `migrate`,
|
|
134
137
|
batching and update handles, subscription granularity,
|
|
135
|
-
router requirements,
|
|
138
|
+
router requirements, building a link on the router's URL, reading local state before
|
|
136
139
|
hydration with `inlineRead()`, and GET forms with `@k8ordo/form`.
|
|
137
140
|
|
|
138
141
|
## AI Agent Documentation
|
package/dist/cookie-state.d.mts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
-
import { StateSchema } from "./schema/object.mjs";
|
|
2
1
|
import { Versioning } from "./row/codec.mjs";
|
|
2
|
+
import { StateSchema } from "./schema/object.mjs";
|
|
3
3
|
import { output } from "zod/v4/core";
|
|
4
|
+
type CookieReader = {
|
|
5
|
+
readonly get: (name: string) => string | undefined;
|
|
6
|
+
};
|
|
4
7
|
/**
|
|
5
8
|
* App-scope state that lives in a cookie: device-persistent and shared across
|
|
6
9
|
* tabs like local state, and — unlike it — sent with every request, so a
|
|
@@ -17,18 +20,33 @@ export type CookieState<Schema extends StateSchema = StateSchema> = {
|
|
|
17
20
|
/** The cookie the values are written under: `k8ordo-state.<key>`. */
|
|
18
21
|
cookieName: string;
|
|
19
22
|
/**
|
|
20
|
-
* Reads the values out of a request's cookies on the server —
|
|
21
|
-
* `
|
|
22
|
-
*
|
|
23
|
+
* Reads the values out of a request's cookies on the server — anything
|
|
24
|
+
* whose `get(name)` gives a cookie's percent-decoded value:
|
|
25
|
+
* `request.cookies` in a page and `cookies()` in a guard, a route.ts or a
|
|
26
|
+
* Server Action under `@k8ordo/framework`'s server mode,
|
|
27
|
+
* `{ get: (name) => store.get(name)?.value }` over Next.js's
|
|
28
|
+
* `cookies()`. Absent, corrupt, or rejected fields get their defaults.
|
|
23
29
|
*/
|
|
24
|
-
parseCookies: (cookies:
|
|
30
|
+
parseCookies: (cookies: CookieReader) => output<Schema>;
|
|
25
31
|
/**
|
|
26
|
-
* The
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
* the
|
|
32
|
+
* The same cookie written from a server, as the arguments of its cookie
|
|
33
|
+
* API: `cookies().set(...density.cookie({ density: 'compact' }, cookies()))`
|
|
34
|
+
* under `@k8ordo/framework`'s server mode. `patch` goes over the values
|
|
35
|
+
* `current` holds — read as `parseCookies` reads them — as `update()` lays
|
|
36
|
+
* it over the cookie in the browser, so the fields it leaves out keep what
|
|
37
|
+
* the visitor saved; the result passes the schema. The value is the JSON
|
|
38
|
+
* left for that API to percent-encode, and the options are the browser
|
|
39
|
+
* store's own attributes with `httpOnly: false`, which keeps the cookie
|
|
40
|
+
* readable to the browser store. A cookie whose `migrate` throws is never
|
|
41
|
+
* written over: this throws instead, the error as its `cause`.
|
|
31
42
|
*/
|
|
32
|
-
|
|
43
|
+
cookie: (patch: Readonly<Partial<output<Schema>>>, current: CookieReader) => readonly [name: string, value: string, options: CookieAttributes];
|
|
44
|
+
};
|
|
45
|
+
type CookieAttributes = {
|
|
46
|
+
readonly path: '/';
|
|
47
|
+
readonly sameSite: 'lax';
|
|
48
|
+
readonly maxAge: number;
|
|
49
|
+
readonly httpOnly: false;
|
|
33
50
|
};
|
|
34
|
-
export declare const defineCookieState: <Schema extends StateSchema>(key: string, schema: Schema, versioning?: Versioning<Schema>) => CookieState<Schema>;
|
|
51
|
+
export declare const defineCookieState: <Schema extends StateSchema>(key: string, schema: Schema, versioning?: Versioning<Schema>) => CookieState<Schema>;
|
|
52
|
+
export {};
|
package/dist/cookie-state.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createRowCodec } from "./row/codec.mjs";
|
|
2
|
-
import { cookieInitialSnapshot, cookieStoreOf, parseCookieText } from "./store/cookie-store.mjs";
|
|
2
|
+
import { COOKIE_ATTRIBUTES, cookieInitialSnapshot, cookieStoreOf, parseCookieText } from "./store/cookie-store.mjs";
|
|
3
|
+
import { resolvePatch } from "./store/core.mjs";
|
|
3
4
|
import { setKind } from "./store/kind.mjs";
|
|
4
5
|
// src/cookie-state.ts
|
|
5
6
|
const COOKIE_NAME_PREFIX = "k8ordo-state.";
|
|
@@ -8,13 +9,34 @@ const defineCookieState = (key, schema, versioning) => {
|
|
|
8
9
|
const cookieName = `${COOKIE_NAME_PREFIX}${key}`;
|
|
9
10
|
if (!TOKEN.test(cookieName)) throw new TypeError(`"${key}" cannot name a cookie — use letters, digits and !#$%&'*+-.^_\`|~`);
|
|
10
11
|
const codec = createRowCodec(schema, "cookie", key, versioning);
|
|
12
|
+
const readRow = (cookies) => codec.read(parseCookieText(cookies.get(cookieName)));
|
|
11
13
|
const def = {
|
|
12
14
|
kind: "cookie",
|
|
13
15
|
key,
|
|
14
16
|
schema,
|
|
15
17
|
cookieName,
|
|
16
|
-
parseCookies: (cookies) =>
|
|
17
|
-
|
|
18
|
+
parseCookies: (cookies) => {
|
|
19
|
+
const row = readRow(cookies);
|
|
20
|
+
if (row.failed) console.error(`parseCookies: the migrate of "${key}" threw on the cookie ${cookieName}, which reads as nothing stored and is left as it is`, row.error);
|
|
21
|
+
return row.values;
|
|
22
|
+
},
|
|
23
|
+
cookie: (patch, current) => {
|
|
24
|
+
const row = readRow(current);
|
|
25
|
+
if (row.failed) throw new Error(`cookie: the migrate of "${key}" threw on the cookie ${cookieName}, which is left as it is rather than written over`, { cause: row.error });
|
|
26
|
+
const resolved = resolvePatch(patch, row.values, codec.keys, key);
|
|
27
|
+
const values = codec.salvage({
|
|
28
|
+
...row.values,
|
|
29
|
+
...resolved
|
|
30
|
+
});
|
|
31
|
+
return [
|
|
32
|
+
cookieName,
|
|
33
|
+
JSON.stringify(codec.row(values)),
|
|
34
|
+
{
|
|
35
|
+
...COOKIE_ATTRIBUTES,
|
|
36
|
+
httpOnly: false
|
|
37
|
+
}
|
|
38
|
+
];
|
|
39
|
+
}
|
|
18
40
|
};
|
|
19
41
|
setKind(def, {
|
|
20
42
|
store: () => cookieStoreOf(def, codec),
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { $ZodType } from "zod/v4/core";
|
|
2
|
+
export type HashCodec = {
|
|
3
|
+
fallback: unknown;
|
|
4
|
+
/** Reads `location.hash`: `''`, or the fragment with its `#`. */
|
|
5
|
+
parse: (hash: string) => unknown;
|
|
6
|
+
/** The fragment a value is written as, without `#`; `''` at the default. */
|
|
7
|
+
fragment: (value: unknown) => string;
|
|
8
|
+
/** The value as it will come back: written to a fragment and read again. */
|
|
9
|
+
salvage: (value: unknown) => unknown;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* The fragment is one string, so the hash slot is one value under one schema
|
|
13
|
+
* rather than an object of fields. A fragment the schema rejects is not this
|
|
14
|
+
* state's — an anchor, most likely — and reads as the default.
|
|
15
|
+
*/
|
|
16
|
+
export declare const createHashCodec: (schema: $ZodType) => HashCodec;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { sameValue } from "../schema/object.mjs";
|
|
2
|
+
import { refuseBoolean, serializeValue } from "../url/codec.mjs";
|
|
3
|
+
import { safeParse } from "zod/v4/core";
|
|
4
|
+
// src/hash/codec.ts
|
|
5
|
+
const decodeOrKeep = (text) => {
|
|
6
|
+
try {
|
|
7
|
+
return decodeURIComponent(text);
|
|
8
|
+
} catch {
|
|
9
|
+
return text;
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* The fragment is one string, so the hash slot is one value under one schema
|
|
14
|
+
* rather than an object of fields. A fragment the schema rejects is not this
|
|
15
|
+
* state's — an anchor, most likely — and reads as the default.
|
|
16
|
+
*/
|
|
17
|
+
const createHashCodec = (schema) => {
|
|
18
|
+
const absent = safeParse(schema, void 0);
|
|
19
|
+
if (!absent.success) throw new TypeError("hash must tolerate absence — add .default() or .optional()");
|
|
20
|
+
refuseBoolean(schema, "hash");
|
|
21
|
+
const fallback = absent.data;
|
|
22
|
+
const parse = (hash) => {
|
|
23
|
+
if (hash.length <= 1) return fallback;
|
|
24
|
+
const read = safeParse(schema, decodeOrKeep(hash.slice(1)));
|
|
25
|
+
return read.success ? read.data : fallback;
|
|
26
|
+
};
|
|
27
|
+
const fragment = (value) => value === void 0 || sameValue(fallback, value) ? "" : encodeURIComponent(serializeValue(schema, "hash", value));
|
|
28
|
+
return {
|
|
29
|
+
fallback,
|
|
30
|
+
parse,
|
|
31
|
+
fragment,
|
|
32
|
+
salvage: (value) => parse(`#${fragment(value)}`)
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
export { createHashCodec };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
|
-
import { StateSchema } from "./schema/object.mjs";
|
|
2
|
-
import { Versioning } from "./row/codec.mjs";
|
|
3
|
-
import { CookieState, defineCookieState } from "./cookie-state.mjs";
|
|
4
|
-
import { Register, RegisteredPath } from "./register.mjs";
|
|
5
|
-
import { UrlInput } from "./url/codec.mjs";
|
|
6
1
|
import { OutputOf, PageState, definePageState, urlReader } from "./page-state.mjs";
|
|
7
2
|
import { LocalState, SessionState, defineLocalState, defineSessionState } from "./storage-state.mjs";
|
|
3
|
+
import { CookieState, defineCookieState } from "./cookie-state.mjs";
|
|
8
4
|
import { MemoryState, defineMemoryState } from "./memory-state.mjs";
|
|
5
|
+
import { AnyState, useAppState } from "./use-app-state.mjs";
|
|
9
6
|
import { UpdateHandle } from "./store/core.mjs";
|
|
10
7
|
import { UpdateOptions } from "./store/page-store.mjs";
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
|
|
8
|
+
import { StateSchema } from "./schema/object.mjs";
|
|
9
|
+
import { Versioning } from "./row/codec.mjs";
|
|
10
|
+
import { UrlInput } from "./url/codec.mjs";
|
|
11
|
+
export { type AnyState, type CookieState, type LocalState, type MemoryState, type OutputOf, type PageState, type SessionState, type StateSchema, type UpdateHandle, type UpdateOptions, type UrlInput, type Versioning, defineCookieState, defineLocalState, defineMemoryState, definePageState, defineSessionState, urlReader, useAppState };
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { resetStateRegistry } from "./store/registry.mjs";
|
|
2
|
-
import { defineCookieState } from "./cookie-state.mjs";
|
|
3
1
|
import { definePageState, urlReader } from "./page-state.mjs";
|
|
4
2
|
import { defineLocalState, defineSessionState } from "./storage-state.mjs";
|
|
3
|
+
import { defineCookieState } from "./cookie-state.mjs";
|
|
5
4
|
import { defineMemoryState } from "./memory-state.mjs";
|
|
6
5
|
import { useAppState } from "./use-app-state.mjs";
|
|
7
|
-
export { defineCookieState, defineLocalState, defineMemoryState, definePageState, defineSessionState,
|
|
6
|
+
export { defineCookieState, defineLocalState, defineMemoryState, definePageState, defineSessionState, urlReader, useAppState };
|
package/dist/page-state.d.mts
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
|
-
import { StateSchema } from "./schema/object.mjs";
|
|
2
1
|
import { StoredCodec } from "./entry/codec.mjs";
|
|
3
|
-
import {
|
|
2
|
+
import { HashCodec } from "./hash/codec.mjs";
|
|
3
|
+
import { StateSchema } from "./schema/object.mjs";
|
|
4
4
|
import { UrlCodec, UrlInput } from "./url/codec.mjs";
|
|
5
|
-
import { output } from "zod/v4/core";
|
|
5
|
+
import { $ZodType, output } from "zod/v4/core";
|
|
6
6
|
export type OutputOf<Schema> = Schema extends StateSchema ? output<Schema> : Record<never, never>;
|
|
7
|
-
|
|
7
|
+
/** The one field the hash slot adds to the flat state. */
|
|
8
|
+
export type HashOf<Hash> = Hash extends $ZodType ? {
|
|
9
|
+
hash: output<Hash>;
|
|
10
|
+
} : Record<never, never>;
|
|
11
|
+
export type PageState<Url extends StateSchema | undefined = StateSchema | undefined, Entry extends StateSchema | undefined = StateSchema | undefined, Hash extends $ZodType | undefined = $ZodType | undefined> = {
|
|
8
12
|
kind: 'page';
|
|
9
13
|
/** Identity of this state: store registry slot, entry-state namespace. */
|
|
10
14
|
key: string;
|
|
@@ -12,42 +16,51 @@ export type PageState<Url extends StateSchema | undefined = StateSchema | undefi
|
|
|
12
16
|
url: Url;
|
|
13
17
|
/** The entry schema as passed. */
|
|
14
18
|
entry: Entry;
|
|
19
|
+
/** The hash schema as passed. */
|
|
20
|
+
hash: Hash;
|
|
15
21
|
/** Reads the url slot on the server. Absent params get their defaults. */
|
|
16
22
|
parseUrl: (input: UrlInput) => OutputOf<Url>;
|
|
17
23
|
/**
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
24
|
+
* Puts this state on a URL: the destination as the router built it —
|
|
25
|
+
* `@k8ordo/router`'s `href()`, a Next.js `Route` — or `''` for the page
|
|
26
|
+
* itself. Only this definition's url params are rewritten, in their
|
|
27
|
+
* canonical form: unspecified fields mean their default, and defaults are
|
|
28
|
+
* omitted. The URL's other params stay. With a hash slot the fragment is
|
|
29
|
+
* the value's (none at the default); without one the URL's own fragment
|
|
30
|
+
* stays. Nothing is added to the path — a `base` is the router's, and its
|
|
31
|
+
* `href()` has put it there — and the URL literal survives in the type,
|
|
32
|
+
* which is what typed-route checks read. When the URL handed in already
|
|
33
|
+
* carries this definition's params or a fragment, the type is an
|
|
34
|
+
* approximation: those params are rewritten, and the query goes in before
|
|
35
|
+
* the fragment.
|
|
22
36
|
*/
|
|
23
|
-
href: <
|
|
24
|
-
/** The query string alone (no `?`), for handrolled URL composition. */
|
|
25
|
-
search: (values?: Readonly<Partial<OutputOf<Url>>>) => string;
|
|
37
|
+
href: <U extends string>(url: U, values?: Readonly<Partial<OutputOf<Url> & HashOf<Hash>>>) => U | `${U}?${string}` | (Hash extends $ZodType ? `${U}#${string}` : never);
|
|
26
38
|
};
|
|
27
39
|
type SharedKeys<Url, Entry> = Extract<keyof OutputOf<Url>, keyof OutputOf<Entry>> & string;
|
|
40
|
+
type NamedHash<Url, Entry> = Extract<keyof OutputOf<Url> | keyof OutputOf<Entry>, 'hash'>;
|
|
28
41
|
/**
|
|
29
42
|
* The flat merged state cannot host one name twice; when it would, the error
|
|
30
43
|
* carries the offending field name instead of a bare "not assignable".
|
|
31
44
|
*/
|
|
32
|
-
type DisjointGuard<Url, Entry> =
|
|
45
|
+
type DisjointGuard<Url, Entry, Hash> = [Url, Entry, Hash] extends [undefined, undefined, undefined] ? {
|
|
46
|
+
url: 'declare at least one of url, entry and hash';
|
|
47
|
+
} : [SharedKeys<Url, Entry>] extends [never] ? [Hash] extends [undefined] ? unknown : [NamedHash<Url, Entry>] extends [never] ? unknown : {
|
|
48
|
+
hash: 'a url or entry field is named hash, the name the hash value takes in the state';
|
|
49
|
+
} : {
|
|
33
50
|
entry: `field declared in both url and entry: ${SharedKeys<Url, Entry>}`;
|
|
34
51
|
};
|
|
35
52
|
export type PageInternals = {
|
|
36
53
|
url: UrlCodec | null;
|
|
37
54
|
entry: StoredCodec | null;
|
|
38
|
-
|
|
55
|
+
hash: HashCodec | null;
|
|
56
|
+
/** url keys first, then entry keys, then `hash` — the flat snapshot's full key set. */
|
|
39
57
|
keys: readonly string[];
|
|
40
58
|
};
|
|
41
|
-
export declare function definePageState<Url extends StateSchema>(key: string, config: {
|
|
42
|
-
url
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
}): PageState<undefined, Entry>;
|
|
47
|
-
export declare function definePageState<Url extends StateSchema, Entry extends StateSchema>(key: string, config: {
|
|
48
|
-
url: Url;
|
|
49
|
-
entry: Entry;
|
|
50
|
-
} & DisjointGuard<Url, Entry>): PageState<Url, Entry>;
|
|
59
|
+
export declare function definePageState<Url extends StateSchema | undefined = undefined, Entry extends StateSchema | undefined = undefined, Hash extends $ZodType | undefined = undefined>(key: string, config: {
|
|
60
|
+
url?: Url;
|
|
61
|
+
entry?: Entry;
|
|
62
|
+
hash?: Hash;
|
|
63
|
+
} & DisjointGuard<Url, Entry, Hash>): PageState<Url, Entry, Hash>;
|
|
51
64
|
/**
|
|
52
65
|
* Reads the url slot a schema describes out of a URL's search, the way
|
|
53
66
|
* `parseUrl` reads it for the definition the schema came from — defaults
|
package/dist/page-state.mjs
CHANGED
|
@@ -1,33 +1,49 @@
|
|
|
1
|
-
import { withBase } from "./base.mjs";
|
|
2
1
|
import { createStoredCodec } from "./entry/codec.mjs";
|
|
2
|
+
import { createHashCodec } from "./hash/codec.mjs";
|
|
3
3
|
import { setKind } from "./store/kind.mjs";
|
|
4
4
|
import { pageInitialSnapshot, pageStoreOf } from "./store/page-store.mjs";
|
|
5
5
|
import { createUrlCodec } from "./url/codec.mjs";
|
|
6
6
|
// src/page-state.ts
|
|
7
|
+
const keyOf = (pair) => new URLSearchParams(pair).keys().next().value ?? "";
|
|
7
8
|
function definePageState(key, config) {
|
|
8
9
|
const url = config.url === void 0 ? null : createUrlCodec(config.url);
|
|
9
10
|
const entry = config.entry === void 0 ? null : createStoredCodec(config.entry, "entry");
|
|
10
|
-
|
|
11
|
+
const hash = config.hash === void 0 ? null : createHashCodec(config.hash);
|
|
12
|
+
if (url === null && entry === null && hash === null) throw new TypeError(`"${key}" declares neither url, entry nor hash`);
|
|
13
|
+
if (hash !== null && (url?.keys.includes("hash") === true || entry?.keys.includes("hash") === true)) throw new TypeError(`"${key}" declares hash beside a url or entry field named hash — the hash value takes that name in the state`);
|
|
11
14
|
const shared = url === null || entry === null ? [] : url.keys.filter((field) => entry.keys.includes(field));
|
|
12
15
|
if (shared.length > 0) throw new TypeError(`"${key}" declares in both url and entry: ${shared.join(", ")}`);
|
|
13
|
-
const
|
|
16
|
+
const ownKeys = new Set(url?.keys);
|
|
14
17
|
const def = {
|
|
15
18
|
kind: "page",
|
|
16
19
|
key,
|
|
17
20
|
url: config.url,
|
|
18
21
|
entry: config.entry,
|
|
22
|
+
hash: config.hash,
|
|
19
23
|
parseUrl: (input) => url === null ? {} : url.parse(input),
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
const
|
|
23
|
-
const
|
|
24
|
-
|
|
24
|
+
href: (destination, values = {}) => {
|
|
25
|
+
const hashAt = destination.indexOf("#");
|
|
26
|
+
const beforeHash = hashAt === -1 ? destination : destination.slice(0, hashAt);
|
|
27
|
+
const queryAt = beforeHash.indexOf("?");
|
|
28
|
+
const path = queryAt === -1 ? beforeHash : beforeHash.slice(0, queryAt);
|
|
29
|
+
const kept = (queryAt === -1 ? "" : beforeHash.slice(queryAt + 1)).split("&").filter((pair) => pair !== "" && !ownKeys.has(keyOf(pair)));
|
|
30
|
+
const own = url === null ? "" : url.search(values);
|
|
31
|
+
const query = [...kept, ...own === "" ? [] : [own]].join("&");
|
|
32
|
+
const located = query === "" ? path : `${path}?${query}`;
|
|
33
|
+
if (hash === null) return hashAt === -1 ? located : `${located}${destination.slice(hashAt)}`;
|
|
34
|
+
const fragment = hash.fragment(values.hash);
|
|
35
|
+
return fragment === "" ? located : `${located}#${fragment}`;
|
|
25
36
|
}
|
|
26
37
|
};
|
|
27
38
|
const page = {
|
|
28
39
|
url,
|
|
29
40
|
entry,
|
|
30
|
-
|
|
41
|
+
hash,
|
|
42
|
+
keys: [
|
|
43
|
+
...url?.keys ?? [],
|
|
44
|
+
...entry?.keys ?? [],
|
|
45
|
+
...hash === null ? [] : ["hash"]
|
|
46
|
+
]
|
|
31
47
|
};
|
|
32
48
|
setKind(def, {
|
|
33
49
|
store: () => pageStoreOf(def, page),
|
package/dist/row/codec.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { StateSchema, StateValues } from "../schema/object.mjs";
|
|
2
1
|
import { StoredCodec } from "../entry/codec.mjs";
|
|
2
|
+
import { StateSchema, StateValues } from "../schema/object.mjs";
|
|
3
3
|
import { input } from "zod/v4/core";
|
|
4
4
|
/**
|
|
5
5
|
* How a local or cookie state reads rows an older version of its schema
|
|
@@ -18,8 +18,10 @@ export type Versioning<Schema extends StateSchema = StateSchema> = {
|
|
|
18
18
|
* written before the definition declared a version. The result passes the
|
|
19
19
|
* schema field by field like any read, so its keys are the schema's but its
|
|
20
20
|
* values may be anything: map what you can, hand old values over as they
|
|
21
|
-
* are, and leave the rest out. A throw reads as nothing stored and
|
|
22
|
-
*
|
|
21
|
+
* are, and leave the rest out. A throw reads as nothing stored and is
|
|
22
|
+
* reported — `reportError` in the browser, `console.error` from
|
|
23
|
+
* `parseCookies` — and the row stays as it was, through an `update()` too,
|
|
24
|
+
* for a fixed `migrate` to read.
|
|
23
25
|
*/
|
|
24
26
|
migrate: (old: Readonly<Record<string, unknown>>, fromVersion: number) => { readonly [Key in keyof input<Schema>]?: unknown; };
|
|
25
27
|
};
|
|
@@ -29,15 +31,18 @@ export type Versioning<Schema extends StateSchema = StateSchema> = {
|
|
|
29
31
|
* never what an unversioned row holds (the values are always an object), so
|
|
30
32
|
* the two never read as each other.
|
|
31
33
|
*/
|
|
34
|
+
export type RowRead = {
|
|
35
|
+
values: StateValues;
|
|
36
|
+
stale: boolean;
|
|
37
|
+
failed: false;
|
|
38
|
+
} | {
|
|
39
|
+
values: StateValues;
|
|
40
|
+
stale: false;
|
|
41
|
+
failed: true;
|
|
42
|
+
error: unknown;
|
|
43
|
+
};
|
|
32
44
|
export type RowCodec = Omit<StoredCodec, 'parse'> & {
|
|
33
|
-
|
|
34
|
-
* The values in a parsed row. `stale` when the row was written by an older
|
|
35
|
-
* version and migrated here, so the caller writes it back.
|
|
36
|
-
*/
|
|
37
|
-
read: (row: unknown) => {
|
|
38
|
-
values: StateValues;
|
|
39
|
-
stale: boolean;
|
|
40
|
-
};
|
|
45
|
+
read: (row: unknown) => RowRead;
|
|
41
46
|
/** The JSON-ready row for these values. */
|
|
42
47
|
row: (values: Readonly<StateValues>) => unknown;
|
|
43
48
|
/** The version rows are written with, `undefined` when unversioned. */
|
package/dist/row/codec.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { isRecord } from "../schema/object.mjs";
|
|
2
1
|
import { createStoredCodec } from "../entry/codec.mjs";
|
|
2
|
+
import { isRecord } from "../schema/object.mjs";
|
|
3
3
|
// src/row/codec.ts
|
|
4
4
|
const envelopeOf = (row) => {
|
|
5
5
|
if (isRecord(row)) return {
|
|
@@ -18,7 +18,8 @@ const createRowCodec = (schema, slot, key, versioning) => {
|
|
|
18
18
|
...stored,
|
|
19
19
|
read: (row) => ({
|
|
20
20
|
values: stored.parse(row),
|
|
21
|
-
stale: false
|
|
21
|
+
stale: false,
|
|
22
|
+
failed: false
|
|
22
23
|
}),
|
|
23
24
|
row: (values) => values,
|
|
24
25
|
version: void 0
|
|
@@ -29,24 +30,29 @@ const createRowCodec = (schema, slot, key, versioning) => {
|
|
|
29
30
|
const envelope = envelopeOf(row);
|
|
30
31
|
if (envelope === null) return {
|
|
31
32
|
values: stored.parse(void 0),
|
|
32
|
-
stale: false
|
|
33
|
+
stale: false,
|
|
34
|
+
failed: false
|
|
33
35
|
};
|
|
34
36
|
if (envelope.fromVersion >= version) return {
|
|
35
37
|
values: stored.parse(envelope.values),
|
|
36
|
-
stale: false
|
|
38
|
+
stale: false,
|
|
39
|
+
failed: false
|
|
37
40
|
};
|
|
38
41
|
let migrated;
|
|
39
42
|
try {
|
|
40
43
|
migrated = migrate(envelope.values, envelope.fromVersion);
|
|
41
|
-
} catch {
|
|
44
|
+
} catch (error) {
|
|
42
45
|
return {
|
|
43
46
|
values: stored.parse(void 0),
|
|
44
|
-
stale: false
|
|
47
|
+
stale: false,
|
|
48
|
+
failed: true,
|
|
49
|
+
error
|
|
45
50
|
};
|
|
46
51
|
}
|
|
47
52
|
return {
|
|
48
53
|
values: stored.parse(migrated),
|
|
49
|
-
stale: true
|
|
54
|
+
stale: true,
|
|
55
|
+
failed: false
|
|
50
56
|
};
|
|
51
57
|
};
|
|
52
58
|
return {
|
package/dist/storage-state.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { StateSchema } from "./schema/object.mjs";
|
|
2
1
|
import { Versioning } from "./row/codec.mjs";
|
|
2
|
+
import { StateSchema } from "./schema/object.mjs";
|
|
3
3
|
type StorageState<Kind extends 'local' | 'session', Schema extends StateSchema> = {
|
|
4
4
|
kind: Kind;
|
|
5
5
|
/** Identity of this state: the storage key and the store registry slot. */
|
|
@@ -1,7 +1,12 @@
|
|
|
1
|
-
import { StateValues } from "../schema/object.mjs";
|
|
2
|
-
import { RowCodec } from "../row/codec.mjs";
|
|
3
1
|
import { CookieState } from "../cookie-state.mjs";
|
|
2
|
+
import { RowCodec } from "../row/codec.mjs";
|
|
3
|
+
import { StateValues } from "../schema/object.mjs";
|
|
4
4
|
import { Store } from "./core.mjs";
|
|
5
|
+
export declare const COOKIE_ATTRIBUTES: {
|
|
6
|
+
readonly path: '/';
|
|
7
|
+
readonly sameSite: 'lax';
|
|
8
|
+
readonly maxAge: number;
|
|
9
|
+
};
|
|
5
10
|
export declare const parseCookieText: (text: string | undefined) => unknown;
|
|
6
11
|
export declare const cookieStoreOf: (def: CookieState, codec: RowCodec) => Store;
|
|
7
12
|
/**
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { createHandle, createStoreCore, resolvePatch } from "./core.mjs";
|
|
2
2
|
import { getOrCreateStore } from "./registry.mjs";
|
|
3
3
|
// src/store/cookie-store.ts
|
|
4
|
-
const
|
|
4
|
+
const COOKIE_ATTRIBUTES = {
|
|
5
|
+
path: "/",
|
|
6
|
+
sameSite: "lax",
|
|
7
|
+
maxAge: 3456e4
|
|
8
|
+
};
|
|
5
9
|
const rawCookie = (name) => {
|
|
6
10
|
for (const part of document.cookie.split(";")) {
|
|
7
11
|
const at = part.indexOf("=");
|
|
@@ -26,8 +30,19 @@ const decoded = (raw) => {
|
|
|
26
30
|
};
|
|
27
31
|
const createCookieStore = (def, codec) => {
|
|
28
32
|
const { cookieName } = def;
|
|
29
|
-
const readRow = () =>
|
|
30
|
-
|
|
33
|
+
const readRow = () => {
|
|
34
|
+
const text = rawCookie(cookieName);
|
|
35
|
+
return {
|
|
36
|
+
...codec.read(parseCookieText(decoded(text))),
|
|
37
|
+
text
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
let reported = null;
|
|
41
|
+
const reportFailed = (text, error) => {
|
|
42
|
+
if (text === reported) return;
|
|
43
|
+
reported = text;
|
|
44
|
+
reportError(error);
|
|
45
|
+
};
|
|
31
46
|
let pending = null;
|
|
32
47
|
let handle = null;
|
|
33
48
|
let writing = 0;
|
|
@@ -38,7 +53,12 @@ const createCookieStore = (def, codec) => {
|
|
|
38
53
|
return;
|
|
39
54
|
}
|
|
40
55
|
missed = false;
|
|
41
|
-
const
|
|
56
|
+
const row = readRow();
|
|
57
|
+
if (row.failed) {
|
|
58
|
+
reportFailed(row.text, row.error);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const { values: fresh, stale } = row;
|
|
42
62
|
if (stale) writeBack();
|
|
43
63
|
core.applyNext(pending === null ? fresh : {
|
|
44
64
|
...fresh,
|
|
@@ -51,16 +71,21 @@ const createCookieStore = (def, codec) => {
|
|
|
51
71
|
cookieStore.addEventListener("change", onChange);
|
|
52
72
|
const write = async (patch, current) => {
|
|
53
73
|
try {
|
|
74
|
+
const row = readRow();
|
|
75
|
+
if (row.failed) {
|
|
76
|
+
writing -= 1;
|
|
77
|
+
if (missed) sync();
|
|
78
|
+
current.fail(row.error);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
54
81
|
const target = codec.salvage({
|
|
55
|
-
...
|
|
82
|
+
...row.values,
|
|
56
83
|
...patch
|
|
57
84
|
});
|
|
58
85
|
const init = {
|
|
59
86
|
name: cookieName,
|
|
60
87
|
value: encodeURIComponent(JSON.stringify(codec.row(target))),
|
|
61
|
-
|
|
62
|
-
sameSite: "lax",
|
|
63
|
-
maxAge: MAX_AGE
|
|
88
|
+
...COOKIE_ATTRIBUTES
|
|
64
89
|
};
|
|
65
90
|
await cookieStore.set(init);
|
|
66
91
|
} catch (error) {
|
|
@@ -91,6 +116,7 @@ const createCookieStore = (def, codec) => {
|
|
|
91
116
|
const first = readRow();
|
|
92
117
|
const core = createStoreCore(codec.keys, first.values);
|
|
93
118
|
if (first.stale) writeBack();
|
|
119
|
+
if (first.failed) reportFailed(first.text, first.error);
|
|
94
120
|
const update = (patch) => {
|
|
95
121
|
const resolved = resolvePatch(patch, core.snapshot(), codec.keys, def.key);
|
|
96
122
|
if (pending === null) {
|
|
@@ -130,4 +156,4 @@ const cookieInitialSnapshot = (codec, initialCookie) => {
|
|
|
130
156
|
}
|
|
131
157
|
return base;
|
|
132
158
|
};
|
|
133
|
-
export { cookieInitialSnapshot, cookieStoreOf, parseCookieText };
|
|
159
|
+
export { COOKIE_ATTRIBUTES, cookieInitialSnapshot, cookieStoreOf, parseCookieText };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { StateValues } from "../schema/object.mjs";
|
|
2
1
|
import { MemoryState } from "../memory-state.mjs";
|
|
2
|
+
import { StateValues } from "../schema/object.mjs";
|
|
3
3
|
import { Store } from "./core.mjs";
|
|
4
4
|
export declare const memoryStoreOf: (def: MemoryState) => Store;
|
|
5
5
|
/** SSR renders the initial values — static, so no cross-request concern. */
|