foldkit-mirror 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 +171 -0
- package/dist/index.d.mts +209 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +382 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +47 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Patrick Glenn
|
|
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
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# `foldkit-mirror`
|
|
2
|
+
|
|
3
|
+
A Foldkit Model slice kept in the URL or a key-value store. The Model is the
|
|
4
|
+
only truth; a mirror names a slice of it and keeps an external keyed string
|
|
5
|
+
store in step: the slice is written to the store whenever it changes, and read
|
|
6
|
+
back into the Model on navigation or cold load. The URL query string and
|
|
7
|
+
Effect's `KeyValueStore` are the two stores.
|
|
8
|
+
|
|
9
|
+
A mirror is not an owner. It is last-write-wins to a dumb store with no log,
|
|
10
|
+
which is what separates it from
|
|
11
|
+
[`foldkit-sync`](https://github.com/doeixd/foldkit-plus/tree/main/packages/sync)
|
|
12
|
+
(an ordered durable log that converges) and from
|
|
13
|
+
[`foldkit-remote`](https://github.com/doeixd/foldkit-plus/tree/main/packages/remote)
|
|
14
|
+
(a normalized cache of another owner's facts). The design is in
|
|
15
|
+
[`docs/design/MIRROR.md`](https://github.com/doeixd/foldkit-plus/blob/main/docs/design/MIRROR.md).
|
|
16
|
+
|
|
17
|
+
| State | Owner | Mirror |
|
|
18
|
+
| ---------------------------------------------- | --------------- | ----------------------------- |
|
|
19
|
+
| Filter, sort, page, search text, an open panel | the local Model | the URL (`Mirror.url`) |
|
|
20
|
+
| Preferences, a draft, a collapsed sidebar | the local Model | `KeyValueStore` (`Mirror.kv`) |
|
|
21
|
+
|
|
22
|
+
## Quick start
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { Schema } from 'effect'
|
|
26
|
+
import { defineMessageUnion } from 'foldkit/message'
|
|
27
|
+
import * as Subscription from 'foldkit/subscription'
|
|
28
|
+
import { Projection, Surface } from 'foldkit-surface'
|
|
29
|
+
import { Mirror } from 'foldkit-mirror'
|
|
30
|
+
|
|
31
|
+
const Model = Schema.Struct({
|
|
32
|
+
filter: Schema.Literals(['all', 'active', 'done']),
|
|
33
|
+
page: Schema.Number,
|
|
34
|
+
q: Schema.String,
|
|
35
|
+
sidebar: Schema.Literals(['open', 'closed']),
|
|
36
|
+
draft: Schema.String,
|
|
37
|
+
})
|
|
38
|
+
const Message = defineMessageUnion({ ...Mirror.messages, UrlChanged: { href: Schema.String }, … })
|
|
39
|
+
const App = Surface.application({ Model, Message, initial, update })
|
|
40
|
+
|
|
41
|
+
// The URL shows the filters, as ?filter=…&page=…&q=…; keys default to the field names.
|
|
42
|
+
const Filters = Mirror.url(App, {
|
|
43
|
+
fields: [App.fields.filter, App.fields.page, App.fields.q],
|
|
44
|
+
keys: { q: { history: 'replace' } }, // the rest push a history entry
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
// A key-value store keeps preferences and the draft across sessions.
|
|
48
|
+
const Prefs = Mirror.kv(App, {
|
|
49
|
+
key: 'todo/prefs',
|
|
50
|
+
scope: userId,
|
|
51
|
+
fields: [App.fields.sidebar, App.fields.draft],
|
|
52
|
+
})
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Wiring, in the application:
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
init: url => ({ model: Filters.reduce(initial, url), commands: [Prefs.restore] })
|
|
59
|
+
|
|
60
|
+
function update(model: Model, message: Message): Update.Return<Model, Message, KeyValueStore> {
|
|
61
|
+
if (Mirror.reduces(message)) return { model: Prefs.reduce(model, message) }
|
|
62
|
+
switch (message._tag) {
|
|
63
|
+
case 'UrlChanged':
|
|
64
|
+
return { model: Filters.reduce(model, message.href) }
|
|
65
|
+
…
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const subscriptions = Subscription.make<Model, Message, KeyValueStore>()(() => ({
|
|
70
|
+
...Filters.subscriptions,
|
|
71
|
+
...Prefs.subscriptions,
|
|
72
|
+
}))
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
`update` stays the only reducer. The slice is field refs straight from
|
|
76
|
+
`App.fields`, or a writable projection over them (`Projection.pick`,
|
|
77
|
+
`Projection.compose`), the same object `foldkit-sync` replicates. The URL comes
|
|
78
|
+
in through the `onUrlChange` the runtime already has for routing
|
|
79
|
+
(`Filters.reduce` takes a Foldkit `Url` or an href); the store comes in
|
|
80
|
+
through one `MirrorRestored` case spread from `Mirror.messages`
|
|
81
|
+
(`Prefs.reduce` takes that Message). Each mirror's `subscriptions` is one
|
|
82
|
+
Subscription entry, keyed `<name>.mirror`, that writes the store when the
|
|
83
|
+
encoded slice changes. Links are `Filters.href(model, { page: 2 })`, the
|
|
84
|
+
mirrored keys applied to the current URL. An application built without
|
|
85
|
+
`initial` passes `initial` in the mirror's config; defaults are read from it.
|
|
86
|
+
Under `Sync.mount`, the `url` option (`init`, `onUrlChange`) is where the URL
|
|
87
|
+
mirror plugs in.
|
|
88
|
+
|
|
89
|
+
## What the Model being the truth gives
|
|
90
|
+
|
|
91
|
+
- **Defaults for free.** `App.initial` holds every field's default, so a key
|
|
92
|
+
equal to its initial value is elided from the store; there is no
|
|
93
|
+
`.withDefault`. A key that should always be written opts in with
|
|
94
|
+
`keys: { page: { keep: true } }`.
|
|
95
|
+
- **Batching for free.** The entry's dependencies are the encoded keys: one
|
|
96
|
+
Model change yields at most one write, whatever it touched, and a change
|
|
97
|
+
that encodes to the same keys writes nothing. Back and forward cannot loop:
|
|
98
|
+
`popstate` reduces into the Model, the entry sees the same keys, and stops.
|
|
99
|
+
- **Codecs for free.** A key's codec is derived from the field's encoded form
|
|
100
|
+
of the initial value: a string is itself, a number is parsed as one, a
|
|
101
|
+
boolean is `true`/`false`, and anything else is JSON. `keys: { tags: { codec } }`
|
|
102
|
+
gives a key a `Schema.Codec<Value, string>` of its own when the URL should
|
|
103
|
+
read nicely (`?tags=a,b`).
|
|
104
|
+
|
|
105
|
+
## Reading back
|
|
106
|
+
|
|
107
|
+
Each kind of mirror has the `reduce` its store calls for:
|
|
108
|
+
|
|
109
|
+
- A URL mirror's `reduce(model, url)` takes a Foldkit `Url` or an href and
|
|
110
|
+
sets the whole slice: a key the URL lacks is the initial value, and a key
|
|
111
|
+
that fails to decode is too, so `?page=abc` shows page one rather than
|
|
112
|
+
breaking the page. `mirror.decode(keys)` returns the value and the issues
|
|
113
|
+
for a caller that wants to say so. Only the mirror's keys are read; the
|
|
114
|
+
path, the hash, and every other key are left alone.
|
|
115
|
+
- A store mirror's `reduce(model, message)` takes the `MirrorRestored` its
|
|
116
|
+
`restore` Command yields and sets only the fields the Model still holds at
|
|
117
|
+
their initial value, so a change the user made before the store answered is
|
|
118
|
+
kept. Another mirror's Message is ignored.
|
|
119
|
+
|
|
120
|
+
Both are the kernel's `fromKeys(model, keys)` and `restoreKeys(model, keys)`,
|
|
121
|
+
which `Mirror.make` exposes for any store.
|
|
122
|
+
|
|
123
|
+
`Mirror.reduces(message)` narrows the application's union to Mirror's cases.
|
|
124
|
+
|
|
125
|
+
## Writing
|
|
126
|
+
|
|
127
|
+
The entry writes only what changed, waits `throttle` first (50 ms for the
|
|
128
|
+
URL, 250 ms for a store; browsers rate-limit history writes), and a newer
|
|
129
|
+
slice supersedes a pending write, which is what Foldkit's dependency restart
|
|
130
|
+
does. A write pushes a history entry only for a changed key whose `history`
|
|
131
|
+
is `push` (the default); a `replace` key, and a key going back to its default,
|
|
132
|
+
replace. The store ignores the intent. Outside a browser the URL store writes
|
|
133
|
+
nothing, so a server render is safe.
|
|
134
|
+
|
|
135
|
+
A key-value mirror keeps one JSON document under `key`, with a version and a
|
|
136
|
+
`scope` (a user, a tenant); a document of another version or scope, or a
|
|
137
|
+
malformed one, is discarded and removed rather than restored, as
|
|
138
|
+
`RemotePersistence` does, because a mirror holds no unsent user edits. A
|
|
139
|
+
store failure is absorbed: the mirror is disposable state and never fails the
|
|
140
|
+
application. A slice back at its defaults removes the document.
|
|
141
|
+
|
|
142
|
+
## Contracts and `Module`
|
|
143
|
+
|
|
144
|
+
`mirror.contract` is of kind `mirror`: it observes the slice's fields and owns
|
|
145
|
+
nothing, so `Module.manifest` shows the field as `local` with the mirror
|
|
146
|
+
beside it. A key-value mirror names `MirrorRestored` among its Messages, so a
|
|
147
|
+
union that did not spread `Mirror.messages` is an `unknown-message` finding.
|
|
148
|
+
A URL key belongs to one mirror per application: a second mirror claiming it
|
|
149
|
+
is an error at construction naming the first.
|
|
150
|
+
|
|
151
|
+
## The kernel
|
|
152
|
+
|
|
153
|
+
`Mirror.make(App, store, config)` keeps a slice in any `MirrorStore`: `read`
|
|
154
|
+
the keys, `write({ set, remove, intent })`. `MirrorStore.url(keys, location)`,
|
|
155
|
+
`MirrorStore.kv({ key, scope })`, and `MirrorStore.memory()` (records its
|
|
156
|
+
writes, for tests) are the three; `applyToHref(href, { set, remove })` is the
|
|
157
|
+
pure URL step `href` and the URL store share.
|
|
158
|
+
|
|
159
|
+
## Limits
|
|
160
|
+
|
|
161
|
+
- A mirror is last-write-wins. Two tabs writing one key-value document do not
|
|
162
|
+
converge; that is `foldkit-sync`'s job.
|
|
163
|
+
- Arrays and objects are JSON in the URL by default. Give the key a codec for
|
|
164
|
+
a readable form.
|
|
165
|
+
- Two mirrors may name one field (a filter both linkable and remembered). On a
|
|
166
|
+
cold load the URL wins when it names the key, then the store, then the
|
|
167
|
+
initial value: `init` reduces the URL first, and `restore` applies only
|
|
168
|
+
fields still at their initial value.
|
|
169
|
+
- The URL store touches only its keys and needs a browser `location`; a
|
|
170
|
+
Foldkit router's `route.query(schema)` composes with it when they name
|
|
171
|
+
different keys.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { Duration, Effect, Schema } from "effect";
|
|
2
|
+
import { KeyValueStore } from "effect/unstable/persistence";
|
|
3
|
+
import { Contract, FieldRef, WritableProjection } from "foldkit-surface";
|
|
4
|
+
import { Command } from "foldkit/command";
|
|
5
|
+
import { EntryWithoutKeepAlive } from "foldkit/subscription";
|
|
6
|
+
import { Url } from "foldkit/url";
|
|
7
|
+
//#region src/index.d.ts
|
|
8
|
+
/** The keys a mirror holds in a store, as the store holds them: strings. */
|
|
9
|
+
export type Encoded = Readonly<Record<string, string>>;
|
|
10
|
+
/** The read entry's dependencies: the encoded slice, as a Struct so Foldkit can compare it. */
|
|
11
|
+
export interface MirrorDependencies {
|
|
12
|
+
readonly keys: Encoded;
|
|
13
|
+
}
|
|
14
|
+
/** One write to a store: the keys to set, the keys to drop, and how the URL should record it. */
|
|
15
|
+
export interface MirrorWrite {
|
|
16
|
+
readonly set: Encoded;
|
|
17
|
+
readonly remove: ReadonlyArray<string>;
|
|
18
|
+
/** `push` adds a history entry; `replace` does not. A store without history ignores it. */
|
|
19
|
+
readonly intent: 'push' | 'replace';
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* A keyed string store a mirror writes to and reads from. Errors are the
|
|
23
|
+
* store's to absorb: a mirror is disposable state, and a failed write must
|
|
24
|
+
* not fail the application.
|
|
25
|
+
*/
|
|
26
|
+
export interface MirrorStore<R = never> {
|
|
27
|
+
readonly read: Effect.Effect<Encoded | undefined, never, R>;
|
|
28
|
+
readonly write: (write: MirrorWrite) => Effect.Effect<void, never, R>;
|
|
29
|
+
}
|
|
30
|
+
/** `MirrorStore.url`: where in the URL the keys live. */
|
|
31
|
+
export type UrlLocation = 'search' | 'hash';
|
|
32
|
+
/** `href` with the mirror's keys set and dropped in its location; every other key, the path, and the other part stay. */
|
|
33
|
+
export declare const applyToHref: (href: string, write: Pick<MirrorWrite, "set" | "remove">, location?: UrlLocation) => string;
|
|
34
|
+
/** An in-memory store that records its writes, for tests and for a mirror with no host. */
|
|
35
|
+
export interface MemoryStore extends MirrorStore {
|
|
36
|
+
/** What the store holds now. */
|
|
37
|
+
readonly current: () => Encoded | undefined;
|
|
38
|
+
/** Every write, in order. */
|
|
39
|
+
readonly writes: ReadonlyArray<MirrorWrite>;
|
|
40
|
+
}
|
|
41
|
+
export declare const MirrorStore: {
|
|
42
|
+
/** The URL's query string (or hash), through `foldkit/navigation`. `owned` are the keys the mirror may touch. */
|
|
43
|
+
url: (owned: ReadonlyArray<string>, location: UrlLocation) => MirrorStore;
|
|
44
|
+
/** One JSON document under `key` in Effect's `KeyValueStore`, scoped and versioned. */
|
|
45
|
+
kv: (options: {
|
|
46
|
+
readonly key: string;
|
|
47
|
+
readonly scope?: string | undefined;
|
|
48
|
+
}) => MirrorStore<KeyValueStore.KeyValueStore>;
|
|
49
|
+
memory: (initial?: Encoded) => MemoryStore;
|
|
50
|
+
};
|
|
51
|
+
/** Mirror's Message cases, for `defineMessageUnion({ ...Mirror.messages, … })`. */
|
|
52
|
+
export declare const mirrorMessageCases: {
|
|
53
|
+
/** A store was read (`mirror.restore`); `keys` are what it held for the mirror named. */
|
|
54
|
+
MirrorRestored: {
|
|
55
|
+
name: Schema.String;
|
|
56
|
+
keys: Schema.$Record<Schema.String, Schema.String>;
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
export interface MirrorRestored {
|
|
60
|
+
readonly _tag: 'MirrorRestored';
|
|
61
|
+
readonly name: string;
|
|
62
|
+
readonly keys: Encoded;
|
|
63
|
+
}
|
|
64
|
+
export type MirrorMessage = MirrorRestored;
|
|
65
|
+
/** The value type of a field schema. */
|
|
66
|
+
type TypeOf<S> = S extends {
|
|
67
|
+
readonly Type: infer T;
|
|
68
|
+
} ? T : never;
|
|
69
|
+
/**
|
|
70
|
+
* The slice a mirror keeps: field refs straight from `App.fields`, or a
|
|
71
|
+
* writable projection over them (`Projection.pick`, `Projection.compose`),
|
|
72
|
+
* the same object `foldkit-sync` replicates.
|
|
73
|
+
*/
|
|
74
|
+
export type Slice = WritableProjection<any, any> | readonly FieldRef<any, any, string>[];
|
|
75
|
+
/** The Struct fields of a slice. */
|
|
76
|
+
export type SliceFields<S extends Slice> = S extends WritableProjection<any, infer Fields> ? Fields : S extends readonly FieldRef<any, any, string>[] ? { readonly [R in S[number] as R['key']]: R['Schema']; } : never;
|
|
77
|
+
/** The Model a slice is of. */
|
|
78
|
+
export type SliceRoot<S extends Slice> = S extends WritableProjection<infer Root, any> ? Root : S extends readonly FieldRef<infer Root, any, string>[] ? Root : never;
|
|
79
|
+
/** The value a slice reads. */
|
|
80
|
+
export type SliceValue<S extends Slice> = Schema.Struct.Type<SliceFields<S>>;
|
|
81
|
+
/** How one field is kept: its store key, its history intent, whether its default is written, and its text codec. */
|
|
82
|
+
export interface KeyOptions<Value> {
|
|
83
|
+
/** The store key; default the field name. */
|
|
84
|
+
readonly key?: string | undefined;
|
|
85
|
+
/** Whether a change of this key adds a history entry; default `push`. Only the URL has history. */
|
|
86
|
+
readonly history?: 'push' | 'replace' | undefined;
|
|
87
|
+
/** Write the key even when the value is the initial one; default false, so a default is elided. */
|
|
88
|
+
readonly keep?: boolean | undefined;
|
|
89
|
+
/** The text codec; default derived from the field schema. */
|
|
90
|
+
readonly codec?: Schema.Codec<Value, string, never, never> | undefined;
|
|
91
|
+
}
|
|
92
|
+
export interface MirrorConfig<S extends Slice, Name extends string = string> {
|
|
93
|
+
/** Names the mirror in its contract and its Messages; default from the kind and keys. */
|
|
94
|
+
readonly name?: Name | undefined;
|
|
95
|
+
/** The slice: field refs (`[App.fields.filter, App.fields.q]`) or a writable projection over them. */
|
|
96
|
+
readonly fields: S;
|
|
97
|
+
readonly keys?: { readonly [K in keyof SliceFields<S>]?: KeyOptions<TypeOf<SliceFields<S>[K]>>; } | undefined;
|
|
98
|
+
/** The Model's initial value, when the application was built without one; defaults are read from it. */
|
|
99
|
+
readonly initial?: SliceRoot<S> | undefined;
|
|
100
|
+
/**
|
|
101
|
+
* How long a changed slice waits before it is written; a newer change
|
|
102
|
+
* supersedes a pending write. Browsers rate-limit history writes, so the
|
|
103
|
+
* URL waits 50 ms by default; a store waits 250 ms.
|
|
104
|
+
*/
|
|
105
|
+
readonly throttle?: Duration.Input | undefined;
|
|
106
|
+
}
|
|
107
|
+
export interface UrlMirrorConfig<S extends Slice, Name extends string = string> extends MirrorConfig<S, Name> {
|
|
108
|
+
/** Where in the URL the keys live; default the query string. */
|
|
109
|
+
readonly location?: UrlLocation | undefined;
|
|
110
|
+
}
|
|
111
|
+
export interface KvMirrorConfig<S extends Slice, Name extends string = string> extends MirrorConfig<S, Name> {
|
|
112
|
+
/** The store key the mirror's document lives under; also the mirror's name unless one is given. */
|
|
113
|
+
readonly key: Name;
|
|
114
|
+
/** A user, a tenant: a document of another scope is discarded rather than restored. */
|
|
115
|
+
readonly scope?: string | undefined;
|
|
116
|
+
}
|
|
117
|
+
/** One key that failed to decode; the field keeps its initial value. */
|
|
118
|
+
export interface DecodeIssue {
|
|
119
|
+
readonly key: string;
|
|
120
|
+
readonly message: string;
|
|
121
|
+
}
|
|
122
|
+
export interface Decoded<Value> {
|
|
123
|
+
/** The fields the store named and decoded. */
|
|
124
|
+
readonly value: Partial<Value>;
|
|
125
|
+
readonly issues: ReadonlyArray<DecodeIssue>;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* A Model slice kept in a store. `Value` is the slice's value type; the keys,
|
|
129
|
+
* codecs, and intents are values on the mirror, not type parameters.
|
|
130
|
+
* `Mirror.url` and `Mirror.kv` add the `reduce` their store calls for.
|
|
131
|
+
*/
|
|
132
|
+
export interface Mirror<AppModel, Value extends Record<string, unknown>, R = never, Name extends string = string> {
|
|
133
|
+
readonly kind: 'url' | 'kv' | 'memory';
|
|
134
|
+
readonly name: Name;
|
|
135
|
+
/** Store key per field. */
|
|
136
|
+
readonly keys: Readonly<Record<keyof Value & string, string>>;
|
|
137
|
+
/** For `Module`: observes the slice, owns nothing. */
|
|
138
|
+
readonly contract: Contract;
|
|
139
|
+
/** The store's keys for a Model, defaults elided unless a key is `keep`. */
|
|
140
|
+
readonly encode: (model: AppModel) => Encoded;
|
|
141
|
+
/** The fields a store's keys name; a key that fails to decode is an issue, not a value. */
|
|
142
|
+
readonly decode: (keys: Encoded) => Decoded<Value>;
|
|
143
|
+
/**
|
|
144
|
+
* The Model with a store's keys as the whole slice: a key the store lacks,
|
|
145
|
+
* or one that fails to decode, is the initial value.
|
|
146
|
+
*/
|
|
147
|
+
readonly fromKeys: (model: AppModel, keys: Encoded) => AppModel;
|
|
148
|
+
/**
|
|
149
|
+
* The Model with a store's keys applied to the fields it still holds at
|
|
150
|
+
* their initial value, so a change made before the store answered is kept.
|
|
151
|
+
*/
|
|
152
|
+
readonly restoreKeys: (model: AppModel, keys: Encoded) => AppModel;
|
|
153
|
+
/** A link: the keys of `model` with `patch` applied, on `base` (default the current URL, else `/`). */
|
|
154
|
+
readonly href: (model: AppModel, patch?: Partial<Value>, base?: string) => string;
|
|
155
|
+
/** A Command that reads the store and yields `MirrorRestored` for this mirror. */
|
|
156
|
+
readonly restore: Command<MirrorMessage, never, R>;
|
|
157
|
+
/** One Subscription entry, `<name>.mirror`: writes the store when the encoded slice changes. */
|
|
158
|
+
readonly subscriptions: { readonly [K in `${Name}.mirror`]: EntryWithoutKeepAlive<AppModel, never, MirrorDependencies, R>; };
|
|
159
|
+
}
|
|
160
|
+
/** A slice kept in the URL. */
|
|
161
|
+
export interface UrlMirror<AppModel, Value extends Record<string, unknown>, Name extends string = string> extends Mirror<AppModel, Value, never, Name> {
|
|
162
|
+
readonly kind: 'url';
|
|
163
|
+
/** The Model with the URL's keys (a Foldkit `Url` or an href) as the whole slice: `fromKeys`. */
|
|
164
|
+
readonly reduce: (model: AppModel, url: Url | string) => AppModel;
|
|
165
|
+
}
|
|
166
|
+
/** A slice kept in Effect's `KeyValueStore`. */
|
|
167
|
+
export interface KvMirror<AppModel, Value extends Record<string, unknown>, Name extends string = string> extends Mirror<AppModel, Value, KeyValueStore.KeyValueStore, Name> {
|
|
168
|
+
readonly kind: 'kv';
|
|
169
|
+
/** The Model with a `MirrorRestored` for this mirror applied: `restoreKeys`; another mirror's is ignored. */
|
|
170
|
+
readonly reduce: (model: AppModel, message: MirrorRestored) => AppModel;
|
|
171
|
+
}
|
|
172
|
+
/** An application a mirror is declared over: its identity token, and its initial Model when it has one. */
|
|
173
|
+
export interface MirrorApp<AppModel> {
|
|
174
|
+
readonly owner: object;
|
|
175
|
+
readonly initial?: AppModel | undefined;
|
|
176
|
+
}
|
|
177
|
+
export declare const Mirror: {
|
|
178
|
+
/** Mirror's Message cases, to spread into the application's union. */
|
|
179
|
+
messages: {
|
|
180
|
+
/** A store was read (`mirror.restore`); `keys` are what it held for the mirror named. */
|
|
181
|
+
MirrorRestored: {
|
|
182
|
+
name: Schema.String;
|
|
183
|
+
keys: Schema.$Record<Schema.String, Schema.String>;
|
|
184
|
+
};
|
|
185
|
+
};
|
|
186
|
+
/** Narrows the application's union to Mirror's cases, by tag. */
|
|
187
|
+
reduces: <M extends {
|
|
188
|
+
readonly _tag: string;
|
|
189
|
+
}>(message: M) => message is Extract<M, {
|
|
190
|
+
readonly _tag: "MirrorRestored";
|
|
191
|
+
}>;
|
|
192
|
+
/**
|
|
193
|
+
* A slice kept in the URL: `Projection.pick(App.fields.filter, App.fields.q)`
|
|
194
|
+
* as `?filter=…&q=…`, defaults elided, written when it changes (one history
|
|
195
|
+
* write per Model change) and read back with `reduce(model, url)` on
|
|
196
|
+
* `onUrlChange` and on cold load.
|
|
197
|
+
*/
|
|
198
|
+
url: <S extends Slice, Name extends string = string>(app: MirrorApp<SliceRoot<S>>, config: UrlMirrorConfig<S, Name>) => UrlMirror<SliceRoot<S>, SliceValue<S>, Name>;
|
|
199
|
+
/**
|
|
200
|
+
* A slice kept in Effect's `KeyValueStore` under `key`, as one scoped,
|
|
201
|
+
* versioned JSON document: written when it changes, read back by the
|
|
202
|
+
* `restore` Command whose `MirrorRestored` `reduce` applies.
|
|
203
|
+
*/
|
|
204
|
+
kv: <S extends Slice, Name extends string = string>(app: MirrorApp<SliceRoot<S>>, config: KvMirrorConfig<S, Name>) => KvMirror<SliceRoot<S>, SliceValue<S>, Name>;
|
|
205
|
+
/** The kernel form: a slice kept in any `MirrorStore`, read back with `fromKeys` or `restoreKeys`. */
|
|
206
|
+
make: <S extends Slice, R, Name extends string = string>(app: MirrorApp<SliceRoot<S>>, store: MirrorStore<R>, config: MirrorConfig<S, Name>) => Mirror<SliceRoot<S>, SliceValue<S>, R, Name>;
|
|
207
|
+
};
|
|
208
|
+
//#endregion
|
|
209
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources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WACA,MAAM;;WAEN,MAAM,SAAS,aAAa;;WAE5B,UAAU;;WAEV,SAAS,OAAO,aAAa;;WAE7B,SAAS,MAAM,YAAY,QAAQ;;;;;WAKnC,WAAW,OAAO,UAAU,MAAM,YAAY;;;;;WAK9C,cAAc,OAAO,UAAU,MAAM,YAAY;;WAEjD,OAAO,OAAO,UAAU,QAAQ,QAAQ,QAAQ;;WAEhD,SAAS,QAAQ,sBAAsB;;WAEvC,2BACG,QAAQ,gBAAgB,sBAAsB,iBAAiB,oBAAoB;;;iBAKhF,UACf,UACA,cAAc,yBACd,sCACQ,OAAO,UAAU,cAAc;WAC9B;;WAEA,SAAS,OAAO,UAAU,KAAK,iBAAiB;;;iBAI1C,SACf,UACA,cAAc,yBACd,sCACQ,OAAO,UAAU,OAAO,cAAc,eAAe;WACpD;;WAEA,SAAS,OAAO,UAAU,SAAS,mBAAmB;;;iBAqChD,UAAU;WAChB;WACA,UAAU;;qBAiLR;;;;;;;;;;EAKD,UAAA;aAAqB;KAAc,SAClC,MACR,WAAW,QAAQ;aAAc;;;;;;;;EAS9B,MAAA,UAAU,OAAO,8BAAmB,KACnC,UAAU,UAAU,KAAG,QACpB,gBAAgB,GAAG,UAC1B,UAAU,UAAU,IAAI,WAAW,IAAI;;;;;;EA0BrC,KAAA,UAAU,OAAO,8BAAmB,KAClC,UAAU,UAAU,KAAG,QACpB,eAAe,GAAG,UACzB,SAAS,UAAU,IAAI,WAAW,IAAI;;EAoBlC,OAAA,UAAU,OAAO,GAAG,8BAAmB,KACvC,UAAU,UAAU,KAAG,OACrB,YAAY,IAAE,QACb,aAAa,GAAG,UACvB,OAAO,UAAU,IAAI,WAAW,IAAI,GAAG"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import { Effect, Result, Schema, Stream } from "effect";
|
|
2
|
+
import { KeyValueStore } from "effect/unstable/persistence";
|
|
3
|
+
import * as Navigation from "foldkit/navigation";
|
|
4
|
+
import { Projection } from "foldkit-surface";
|
|
5
|
+
//#region src/index.ts
|
|
6
|
+
/**
|
|
7
|
+
* `foldkit-mirror` — a Model slice kept in the URL or a key-value store.
|
|
8
|
+
*
|
|
9
|
+
* The Model is the only truth. A mirror names a slice of it (a writable
|
|
10
|
+
* projection over field refs) and keeps an external keyed string store in
|
|
11
|
+
* step with it: the slice is written to the store whenever it changes, and
|
|
12
|
+
* read back into the Model on navigation or cold load. The URL query string
|
|
13
|
+
* and Effect's `KeyValueStore` are the two stores; a mirror is not an owner,
|
|
14
|
+
* and it is last-write-wins with no log, which is what separates it from
|
|
15
|
+
* `foldkit-sync`. See `docs/design/MIRROR.md`.
|
|
16
|
+
*/
|
|
17
|
+
/** Splits a same-origin href into its three parts; `search` and `hash` keep their leading `?`/`#`. */
|
|
18
|
+
const splitHref = (href) => {
|
|
19
|
+
const hashAt = href.indexOf("#");
|
|
20
|
+
const hash = hashAt < 0 ? "" : href.slice(hashAt);
|
|
21
|
+
const rest = hashAt < 0 ? href : href.slice(0, hashAt);
|
|
22
|
+
const searchAt = rest.indexOf("?");
|
|
23
|
+
return {
|
|
24
|
+
pathname: searchAt < 0 ? rest : rest.slice(0, searchAt),
|
|
25
|
+
search: searchAt < 0 ? "" : rest.slice(searchAt),
|
|
26
|
+
hash
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
/** The keys a query string holds among `owned`, in URL order. */
|
|
30
|
+
const readParams = (query, owned) => {
|
|
31
|
+
const params = new URLSearchParams(query.startsWith("?") || query.startsWith("#") ? query.slice(1) : query);
|
|
32
|
+
const out = {};
|
|
33
|
+
for (const key of owned) {
|
|
34
|
+
const value = params.get(key);
|
|
35
|
+
if (value !== null) out[key] = value;
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
};
|
|
39
|
+
/** `href` with the mirror's keys set and dropped in its location; every other key, the path, and the other part stay. */
|
|
40
|
+
const applyToHref = (href, write, location = "search") => {
|
|
41
|
+
const parts = splitHref(href);
|
|
42
|
+
const current = location === "search" ? parts.search : parts.hash;
|
|
43
|
+
const params = new URLSearchParams(current.slice(1));
|
|
44
|
+
for (const key of write.remove) params.delete(key);
|
|
45
|
+
for (const [key, value] of Object.entries(write.set)) params.set(key, value);
|
|
46
|
+
const query = params.toString();
|
|
47
|
+
const next = query === "" ? "" : `${location === "search" ? "?" : "#"}${query}`;
|
|
48
|
+
return location === "search" ? `${parts.pathname}${next}${parts.hash}` : `${parts.pathname}${parts.search}${next}`;
|
|
49
|
+
};
|
|
50
|
+
const currentHref = () => {
|
|
51
|
+
const loc = globalThis.location;
|
|
52
|
+
return loc === void 0 ? void 0 : `${loc.pathname}${loc.search}${loc.hash}`;
|
|
53
|
+
};
|
|
54
|
+
const urlStore = (owned, location) => ({
|
|
55
|
+
read: Effect.sync(() => {
|
|
56
|
+
const href = currentHref();
|
|
57
|
+
if (href === void 0) return void 0;
|
|
58
|
+
const parts = splitHref(href);
|
|
59
|
+
return readParams(location === "search" ? parts.search : parts.hash, owned);
|
|
60
|
+
}),
|
|
61
|
+
write: (write) => Effect.suspend(() => {
|
|
62
|
+
const href = currentHref();
|
|
63
|
+
if (href === void 0) return Effect.void;
|
|
64
|
+
const next = applyToHref(href, write, location);
|
|
65
|
+
if (next === href) return Effect.void;
|
|
66
|
+
return write.intent === "push" ? Navigation.pushUrl(next) : Navigation.replaceUrl(next);
|
|
67
|
+
})
|
|
68
|
+
});
|
|
69
|
+
const KV_VERSION = 1;
|
|
70
|
+
const KvDocument = Schema.Struct({
|
|
71
|
+
version: Schema.Number,
|
|
72
|
+
scope: Schema.optional(Schema.String),
|
|
73
|
+
keys: Schema.Record(Schema.String, Schema.String)
|
|
74
|
+
});
|
|
75
|
+
const kvStore = (options) => {
|
|
76
|
+
const decode = Schema.decodeUnknownResult(Schema.fromJsonString(KvDocument));
|
|
77
|
+
const encode = Schema.encodeSync(Schema.fromJsonString(KvDocument));
|
|
78
|
+
return {
|
|
79
|
+
read: Effect.gen(function* () {
|
|
80
|
+
const kv = yield* KeyValueStore.KeyValueStore;
|
|
81
|
+
const raw = yield* Effect.result(kv.get(options.key));
|
|
82
|
+
if (Result.isFailure(raw)) {
|
|
83
|
+
yield* Effect.logWarning(`Mirror: could not read "${options.key}"`, raw.failure);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (raw.success === void 0) return void 0;
|
|
87
|
+
const document = decode(raw.success);
|
|
88
|
+
if (Result.isFailure(document) || document.success.version !== KV_VERSION || document.success.scope !== options.scope) {
|
|
89
|
+
yield* Effect.result(kv.remove(options.key));
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
return document.success.keys;
|
|
93
|
+
}),
|
|
94
|
+
write: (write) => Effect.gen(function* () {
|
|
95
|
+
const kv = yield* KeyValueStore.KeyValueStore;
|
|
96
|
+
const text = encode({
|
|
97
|
+
version: KV_VERSION,
|
|
98
|
+
...options.scope === void 0 ? {} : { scope: options.scope },
|
|
99
|
+
keys: write.set
|
|
100
|
+
});
|
|
101
|
+
const outcome = yield* Effect.result(Object.keys(write.set).length === 0 ? kv.remove(options.key) : kv.set(options.key, text));
|
|
102
|
+
if (Result.isFailure(outcome)) yield* Effect.logWarning(`Mirror: could not write "${options.key}"`, outcome.failure);
|
|
103
|
+
})
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
const memoryStore = (initial) => {
|
|
107
|
+
let held = initial;
|
|
108
|
+
const writes = [];
|
|
109
|
+
return {
|
|
110
|
+
read: Effect.sync(() => held),
|
|
111
|
+
write: (write) => Effect.sync(() => {
|
|
112
|
+
writes.push(write);
|
|
113
|
+
const next = { ...held ?? {} };
|
|
114
|
+
for (const key of write.remove) delete next[key];
|
|
115
|
+
Object.assign(next, write.set);
|
|
116
|
+
held = next;
|
|
117
|
+
}),
|
|
118
|
+
current: () => held,
|
|
119
|
+
writes
|
|
120
|
+
};
|
|
121
|
+
};
|
|
122
|
+
const MirrorStore = {
|
|
123
|
+
/** The URL's query string (or hash), through `foldkit/navigation`. `owned` are the keys the mirror may touch. */
|
|
124
|
+
url: urlStore,
|
|
125
|
+
/** One JSON document under `key` in Effect's `KeyValueStore`, scoped and versioned. */
|
|
126
|
+
kv: kvStore,
|
|
127
|
+
memory: memoryStore
|
|
128
|
+
};
|
|
129
|
+
/** Mirror's Message cases, for `defineMessageUnion({ ...Mirror.messages, … })`. */
|
|
130
|
+
const mirrorMessageCases = {
|
|
131
|
+
/** A store was read (`mirror.restore`); `keys` are what it held for the mirror named. */
|
|
132
|
+
MirrorRestored: {
|
|
133
|
+
name: Schema.String,
|
|
134
|
+
keys: Schema.Record(Schema.String, Schema.String)
|
|
135
|
+
} };
|
|
136
|
+
const failure = (message) => Result.fail(message);
|
|
137
|
+
/**
|
|
138
|
+
* A key's codec, from an override or derived from the field: the field's
|
|
139
|
+
* encoded form of the initial value says whether the key is text, a number,
|
|
140
|
+
* a boolean, or JSON, and the field schema validates whatever was parsed.
|
|
141
|
+
*/
|
|
142
|
+
const codecFor = (field, initial, override) => {
|
|
143
|
+
if (override !== void 0) {
|
|
144
|
+
const decode = Schema.decodeUnknownResult(override);
|
|
145
|
+
const encode = Schema.encodeSync(override);
|
|
146
|
+
return {
|
|
147
|
+
decode: (text) => Result.mapError(decode(text), (error) => error.message),
|
|
148
|
+
encode: (value) => encode(value)
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
const encodeField = Schema.encodeSync(field);
|
|
152
|
+
const decodeField = Schema.decodeUnknownResult(field);
|
|
153
|
+
const shape = typeof encodeField(initial);
|
|
154
|
+
const validate = (candidate) => Result.mapError(decodeField(candidate), (error) => error.message);
|
|
155
|
+
return {
|
|
156
|
+
decode: (text) => {
|
|
157
|
+
switch (shape) {
|
|
158
|
+
case "string": return validate(text);
|
|
159
|
+
case "number": {
|
|
160
|
+
const value = text.trim() === "" ? NaN : Number(text);
|
|
161
|
+
return Number.isNaN(value) ? failure(`"${text}" is not a number`) : validate(value);
|
|
162
|
+
}
|
|
163
|
+
case "boolean": return text === "true" || text === "false" ? validate(text === "true") : failure(`"${text}" is not "true" or "false"`);
|
|
164
|
+
default: try {
|
|
165
|
+
return validate(JSON.parse(text));
|
|
166
|
+
} catch {
|
|
167
|
+
return failure(`"${text}" is not JSON`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
},
|
|
171
|
+
encode: (value) => {
|
|
172
|
+
const encoded = encodeField(value);
|
|
173
|
+
return shape === "string" || shape === "number" || shape === "boolean" ? String(encoded) : JSON.stringify(encoded);
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
};
|
|
177
|
+
const projectionOf = (slice) => Array.isArray(slice) ? Projection.pick(...slice) : slice;
|
|
178
|
+
const nameOf = (kind, keys, given) => given ?? `${kind}(${keys.join(",")})`;
|
|
179
|
+
const claimed = /* @__PURE__ */ new WeakMap();
|
|
180
|
+
const claim = (owner, location, keys, name) => {
|
|
181
|
+
let byKey = claimed.get(owner);
|
|
182
|
+
if (byKey === void 0) {
|
|
183
|
+
byKey = /* @__PURE__ */ new Map();
|
|
184
|
+
claimed.set(owner, byKey);
|
|
185
|
+
}
|
|
186
|
+
for (const key of keys) {
|
|
187
|
+
const at = `${location}:${key}`;
|
|
188
|
+
const holder = byKey.get(at);
|
|
189
|
+
if (holder !== void 0 && holder !== name) throw new Error(`Mirror.url: key "${key}" in the ${location} is already mirrored by "${holder}"; "${name}" cannot mirror it too`);
|
|
190
|
+
byKey.set(at, name);
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
/** A Foldkit `Url` carries `search` and `hash` without their `?` and `#`; an href has them. */
|
|
194
|
+
const withPrefix = (prefix, part) => part === "" || part.startsWith(prefix) ? part : `${prefix}${part}`;
|
|
195
|
+
const hrefOf = (url) => typeof url === "string" ? url : `${url.pathname}${withPrefix("?", url.search._tag === "Some" ? url.search.value : "")}${withPrefix("#", url.hash._tag === "Some" ? url.hash.value : "")}`;
|
|
196
|
+
const make = (app, kind, store, config, throttle) => {
|
|
197
|
+
const fields = projectionOf(config.fields);
|
|
198
|
+
const names = Object.keys(fields.schema.fields);
|
|
199
|
+
const options = config.keys ?? {};
|
|
200
|
+
const initial = config.initial ?? app.initial;
|
|
201
|
+
if (initial === void 0) throw new Error(`Mirror.${kind}: defaults are read from the initial Model, so build the application with \`initial\` or pass \`initial\` in the config`);
|
|
202
|
+
const initialSlice = fields.get(initial);
|
|
203
|
+
const location = config.location ?? "search";
|
|
204
|
+
const keyOf = {};
|
|
205
|
+
const fieldOf = {};
|
|
206
|
+
const codecs = {};
|
|
207
|
+
const history = {};
|
|
208
|
+
const keep = /* @__PURE__ */ new Set();
|
|
209
|
+
const initialText = {};
|
|
210
|
+
for (const field of names) {
|
|
211
|
+
const option = options[field];
|
|
212
|
+
const key = option?.key ?? field;
|
|
213
|
+
if (fieldOf[key] !== void 0) throw new Error(`Mirror: fields "${fieldOf[key]}" and "${field}" both use the key "${key}"; give one another key`);
|
|
214
|
+
keyOf[field] = key;
|
|
215
|
+
fieldOf[key] = field;
|
|
216
|
+
codecs[field] = codecFor(fields.schema.fields[field], initialSlice[field], option?.codec);
|
|
217
|
+
history[field] = option?.history ?? "push";
|
|
218
|
+
if (option?.keep === true) keep.add(field);
|
|
219
|
+
initialText[field] = codecs[field].encode(initialSlice[field]);
|
|
220
|
+
}
|
|
221
|
+
const owned = names.map((field) => keyOf[field]);
|
|
222
|
+
const name = nameOf(kind, owned, config.name);
|
|
223
|
+
if (kind === "url") claim(app.owner, location, owned, name);
|
|
224
|
+
const encodeSlice = (slice) => {
|
|
225
|
+
const out = {};
|
|
226
|
+
for (const field of names) {
|
|
227
|
+
const text = codecs[field].encode(slice[field]);
|
|
228
|
+
if (!keep.has(field) && text === initialText[field]) continue;
|
|
229
|
+
out[keyOf[field]] = text;
|
|
230
|
+
}
|
|
231
|
+
return out;
|
|
232
|
+
};
|
|
233
|
+
const encode = (model) => encodeSlice(fields.get(model));
|
|
234
|
+
const decode = (keys) => {
|
|
235
|
+
const value = {};
|
|
236
|
+
const issues = [];
|
|
237
|
+
for (const field of names) {
|
|
238
|
+
const key = keyOf[field];
|
|
239
|
+
const text = keys[key];
|
|
240
|
+
if (text === void 0) continue;
|
|
241
|
+
const decoded = codecs[field].decode(text);
|
|
242
|
+
if (Result.isFailure(decoded)) issues.push({
|
|
243
|
+
key,
|
|
244
|
+
message: decoded.failure
|
|
245
|
+
});
|
|
246
|
+
else value[field] = decoded.success;
|
|
247
|
+
}
|
|
248
|
+
return {
|
|
249
|
+
value,
|
|
250
|
+
issues
|
|
251
|
+
};
|
|
252
|
+
};
|
|
253
|
+
const keysOfUrl = (source) => {
|
|
254
|
+
const parts = splitHref(hrefOf(source));
|
|
255
|
+
return readParams(location === "search" ? parts.search : parts.hash, owned);
|
|
256
|
+
};
|
|
257
|
+
const fromKeys = (model, keys) => {
|
|
258
|
+
const decoded = decode(keys).value;
|
|
259
|
+
return fields.set(model, {
|
|
260
|
+
...initialSlice,
|
|
261
|
+
...decoded
|
|
262
|
+
});
|
|
263
|
+
};
|
|
264
|
+
const restoreKeys = (model, keys) => {
|
|
265
|
+
const current = fields.get(model);
|
|
266
|
+
const restored = decode(keys).value;
|
|
267
|
+
const next = { ...current };
|
|
268
|
+
for (const field of names) {
|
|
269
|
+
if (codecs[field].encode(current[field]) !== initialText[field]) continue;
|
|
270
|
+
if (field in restored) next[field] = restored[field];
|
|
271
|
+
}
|
|
272
|
+
return fields.set(model, next);
|
|
273
|
+
};
|
|
274
|
+
const href = (model, patch, base) => {
|
|
275
|
+
const slice = {
|
|
276
|
+
...fields.get(model),
|
|
277
|
+
...patch
|
|
278
|
+
};
|
|
279
|
+
const set = encodeSlice(slice);
|
|
280
|
+
const remove = owned.filter((key) => !(key in set));
|
|
281
|
+
return applyToHref(base ?? currentHref() ?? "/", {
|
|
282
|
+
set,
|
|
283
|
+
remove
|
|
284
|
+
}, location);
|
|
285
|
+
};
|
|
286
|
+
const contract = {
|
|
287
|
+
kind: "mirror",
|
|
288
|
+
name,
|
|
289
|
+
owner: app.owner,
|
|
290
|
+
owns: [],
|
|
291
|
+
observes: fields.dependencies,
|
|
292
|
+
messages: kind === "kv" ? ["MirrorRestored"] : [],
|
|
293
|
+
requirements: []
|
|
294
|
+
};
|
|
295
|
+
const restore = {
|
|
296
|
+
name: `Mirror.restore(${name})`,
|
|
297
|
+
effect: store.read.pipe(Effect.map((keys) => ({
|
|
298
|
+
_tag: "MirrorRestored",
|
|
299
|
+
name,
|
|
300
|
+
keys: keys ?? {}
|
|
301
|
+
})))
|
|
302
|
+
};
|
|
303
|
+
const sync = (encoded) => Effect.gen(function* () {
|
|
304
|
+
const current = (yield* store.read) ?? {};
|
|
305
|
+
const remove = owned.filter((key) => !(key in encoded) && key in current);
|
|
306
|
+
const changed = owned.filter((key) => key in encoded && current[key] !== encoded[key]);
|
|
307
|
+
if (remove.length === 0 && changed.length === 0) return;
|
|
308
|
+
const intent = changed.some((key) => history[fieldOf[key]] === "push") ? "push" : "replace";
|
|
309
|
+
yield* store.write({
|
|
310
|
+
set: encoded,
|
|
311
|
+
remove,
|
|
312
|
+
intent
|
|
313
|
+
});
|
|
314
|
+
});
|
|
315
|
+
const entry = {
|
|
316
|
+
dependenciesSchema: Schema.Struct({ keys: Schema.Record(Schema.String, Schema.String) }),
|
|
317
|
+
modelToDependencies: (model) => ({ keys: encode(model) }),
|
|
318
|
+
dependenciesToStream: ({ keys }) => Stream.fromEffect(sync(keys).pipe(Effect.delay(throttle))).pipe(Stream.drain)
|
|
319
|
+
};
|
|
320
|
+
return {
|
|
321
|
+
mirror: {
|
|
322
|
+
kind,
|
|
323
|
+
name,
|
|
324
|
+
keys: keyOf,
|
|
325
|
+
contract,
|
|
326
|
+
encode,
|
|
327
|
+
decode,
|
|
328
|
+
fromKeys,
|
|
329
|
+
restoreKeys,
|
|
330
|
+
href,
|
|
331
|
+
restore,
|
|
332
|
+
subscriptions: { [`${name}.mirror`]: entry }
|
|
333
|
+
},
|
|
334
|
+
keysOfUrl
|
|
335
|
+
};
|
|
336
|
+
};
|
|
337
|
+
const Mirror = {
|
|
338
|
+
/** Mirror's Message cases, to spread into the application's union. */
|
|
339
|
+
messages: mirrorMessageCases,
|
|
340
|
+
/** Narrows the application's union to Mirror's cases, by tag. */
|
|
341
|
+
reduces: (message) => Object.hasOwn(mirrorMessageCases, message._tag),
|
|
342
|
+
/**
|
|
343
|
+
* A slice kept in the URL: `Projection.pick(App.fields.filter, App.fields.q)`
|
|
344
|
+
* as `?filter=…&q=…`, defaults elided, written when it changes (one history
|
|
345
|
+
* write per Model change) and read back with `reduce(model, url)` on
|
|
346
|
+
* `onUrlChange` and on cold load.
|
|
347
|
+
*/
|
|
348
|
+
url: (app, config) => {
|
|
349
|
+
const owned = Object.keys(projectionOf(config.fields).schema.fields).map((field) => config.keys?.[field]?.key ?? field);
|
|
350
|
+
const { mirror, keysOfUrl } = make(app, "url", MirrorStore.url(owned, config.location ?? "search"), config, config.throttle ?? "50 millis");
|
|
351
|
+
return {
|
|
352
|
+
...mirror,
|
|
353
|
+
kind: "url",
|
|
354
|
+
reduce: (model, url) => mirror.fromKeys(model, keysOfUrl(url))
|
|
355
|
+
};
|
|
356
|
+
},
|
|
357
|
+
/**
|
|
358
|
+
* A slice kept in Effect's `KeyValueStore` under `key`, as one scoped,
|
|
359
|
+
* versioned JSON document: written when it changes, read back by the
|
|
360
|
+
* `restore` Command whose `MirrorRestored` `reduce` applies.
|
|
361
|
+
*/
|
|
362
|
+
kv: (app, config) => {
|
|
363
|
+
const { mirror } = make(app, "kv", MirrorStore.kv({
|
|
364
|
+
key: config.key,
|
|
365
|
+
...config.scope === void 0 ? {} : { scope: config.scope }
|
|
366
|
+
}), {
|
|
367
|
+
...config,
|
|
368
|
+
name: config.name ?? config.key
|
|
369
|
+
}, config.throttle ?? "250 millis");
|
|
370
|
+
return {
|
|
371
|
+
...mirror,
|
|
372
|
+
kind: "kv",
|
|
373
|
+
reduce: (model, message) => message.name === mirror.name ? mirror.restoreKeys(model, message.keys) : model
|
|
374
|
+
};
|
|
375
|
+
},
|
|
376
|
+
/** The kernel form: a slice kept in any `MirrorStore`, read back with `fromKeys` or `restoreKeys`. */
|
|
377
|
+
make: (app, store, config) => make(app, "memory", store, config, config.throttle ?? 0).mirror
|
|
378
|
+
};
|
|
379
|
+
//#endregion
|
|
380
|
+
export { Mirror, MirrorStore, applyToHref, mirrorMessageCases };
|
|
381
|
+
|
|
382
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-mirror` — a Model slice kept in the URL or a key-value store.\n *\n * The Model is the only truth. A mirror names a slice of it (a writable\n * projection over field refs) and keeps an external keyed string store in\n * step with it: the slice is written to the store whenever it changes, and\n * read back into the Model on navigation or cold load. The URL query string\n * and Effect's `KeyValueStore` are the two stores; a mirror is not an owner,\n * and it is last-write-wins with no log, which is what separates it from\n * `foldkit-sync`. See `docs/design/MIRROR.md`.\n */\nimport { Duration, Effect, Result, Schema, Stream } from 'effect'\nimport { KeyValueStore } from 'effect/unstable/persistence'\nimport type { Command } from 'foldkit/command'\nimport * as Navigation from 'foldkit/navigation'\nimport type { EntryWithoutKeepAlive } from 'foldkit/subscription'\nimport type { Url } from 'foldkit/url'\nimport { Projection, type Contract, type FieldRef, type WritableProjection } from 'foldkit-surface'\n\n// ---------------------------------------------------------------------------\n// Stores\n// ---------------------------------------------------------------------------\n\n/** The keys a mirror holds in a store, as the store holds them: strings. */\nexport type Encoded = Readonly<Record<string, string>>\n\n/** The read entry's dependencies: the encoded slice, as a Struct so Foldkit can compare it. */\nexport interface MirrorDependencies {\n readonly keys: Encoded\n}\n\n/** One write to a store: the keys to set, the keys to drop, and how the URL should record it. */\nexport interface MirrorWrite {\n readonly set: Encoded\n readonly remove: ReadonlyArray<string>\n /** `push` adds a history entry; `replace` does not. A store without history ignores it. */\n readonly intent: 'push' | 'replace'\n}\n\n/**\n * A keyed string store a mirror writes to and reads from. Errors are the\n * store's to absorb: a mirror is disposable state, and a failed write must\n * not fail the application.\n */\nexport interface MirrorStore<R = never> {\n readonly read: Effect.Effect<Encoded | undefined, never, R>\n readonly write: (write: MirrorWrite) => Effect.Effect<void, never, R>\n}\n\n/** `MirrorStore.url`: where in the URL the keys live. */\nexport type UrlLocation = 'search' | 'hash'\n\n/** Splits a same-origin href into its three parts; `search` and `hash` keep their leading `?`/`#`. */\nconst splitHref = (href: string): { pathname: string; search: string; hash: string } => {\n const hashAt = href.indexOf('#')\n const hash = hashAt < 0 ? '' : href.slice(hashAt)\n const rest = hashAt < 0 ? href : href.slice(0, hashAt)\n const searchAt = rest.indexOf('?')\n return {\n pathname: searchAt < 0 ? rest : rest.slice(0, searchAt),\n search: searchAt < 0 ? '' : rest.slice(searchAt),\n hash,\n }\n}\n\n/** The keys a query string holds among `owned`, in URL order. */\nconst readParams = (query: string, owned: ReadonlyArray<string>): Encoded => {\n const params = new URLSearchParams(\n query.startsWith('?') || query.startsWith('#') ? query.slice(1) : query,\n )\n const out: Record<string, string> = {}\n for (const key of owned) {\n const value = params.get(key)\n if (value !== null) out[key] = value\n }\n return out\n}\n\n/** `href` with the mirror's keys set and dropped in its location; every other key, the path, and the other part stay. */\nexport const applyToHref = (\n href: string,\n write: Pick<MirrorWrite, 'set' | 'remove'>,\n location: UrlLocation = 'search',\n): string => {\n const parts = splitHref(href)\n const current = location === 'search' ? parts.search : parts.hash\n const params = new URLSearchParams(current.slice(1))\n for (const key of write.remove) params.delete(key)\n for (const [key, value] of Object.entries(write.set)) params.set(key, value)\n const query = params.toString()\n const next = query === '' ? '' : `${location === 'search' ? '?' : '#'}${query}`\n return location === 'search'\n ? `${parts.pathname}${next}${parts.hash}`\n : `${parts.pathname}${parts.search}${next}`\n}\n\nconst currentHref = (): string | undefined => {\n const loc = (globalThis as { location?: Location }).location\n return loc === undefined ? undefined : `${loc.pathname}${loc.search}${loc.hash}`\n}\n\nconst urlStore = (owned: ReadonlyArray<string>, location: UrlLocation): MirrorStore => ({\n read: Effect.sync(() => {\n const href = currentHref()\n if (href === undefined) return undefined\n const parts = splitHref(href)\n return readParams(location === 'search' ? parts.search : parts.hash, owned)\n }),\n write: write =>\n Effect.suspend(() => {\n // Outside a browser (SSR, a test without a DOM) there is no URL to write.\n const href = currentHref()\n if (href === undefined) return Effect.void\n const next = applyToHref(href, write, location)\n if (next === href) return Effect.void\n return write.intent === 'push' ? Navigation.pushUrl(next) : Navigation.replaceUrl(next)\n }),\n})\n\nconst KV_VERSION = 1\n\nconst KvDocument = Schema.Struct({\n version: Schema.Number,\n scope: Schema.optional(Schema.String),\n keys: Schema.Record(Schema.String, Schema.String),\n})\n\nconst kvStore = (options: {\n readonly key: string\n readonly scope?: string | undefined\n}): MirrorStore<KeyValueStore.KeyValueStore> => {\n const decode = Schema.decodeUnknownResult(Schema.fromJsonString(KvDocument))\n const encode = Schema.encodeSync(Schema.fromJsonString(KvDocument))\n return {\n read: Effect.gen(function* () {\n const kv = yield* KeyValueStore.KeyValueStore\n const raw = yield* Effect.result(kv.get(options.key))\n if (Result.isFailure(raw)) {\n yield* Effect.logWarning(`Mirror: could not read \"${options.key}\"`, raw.failure)\n return undefined\n }\n if (raw.success === undefined) return undefined\n const document = decode(raw.success)\n // Another version, another scope, or malformed: disposable, so drop it and start clean.\n if (\n Result.isFailure(document) ||\n document.success.version !== KV_VERSION ||\n document.success.scope !== options.scope\n ) {\n yield* Effect.result(kv.remove(options.key))\n return undefined\n }\n return document.success.keys\n }),\n write: write =>\n Effect.gen(function* () {\n const kv = yield* KeyValueStore.KeyValueStore\n const text = encode({\n version: KV_VERSION,\n ...(options.scope === undefined ? {} : { scope: options.scope }),\n keys: write.set,\n })\n const outcome = yield* Effect.result(\n Object.keys(write.set).length === 0 ? kv.remove(options.key) : kv.set(options.key, text),\n )\n if (Result.isFailure(outcome)) {\n yield* Effect.logWarning(`Mirror: could not write \"${options.key}\"`, outcome.failure)\n }\n }),\n }\n}\n\n/** An in-memory store that records its writes, for tests and for a mirror with no host. */\nexport interface MemoryStore extends MirrorStore {\n /** What the store holds now. */\n readonly current: () => Encoded | undefined\n /** Every write, in order. */\n readonly writes: ReadonlyArray<MirrorWrite>\n}\n\nconst memoryStore = (initial?: Encoded): MemoryStore => {\n let held: Encoded | undefined = initial\n const writes: MirrorWrite[] = []\n return {\n read: Effect.sync(() => held),\n write: write =>\n Effect.sync(() => {\n writes.push(write)\n const next: Record<string, string> = { ...(held ?? {}) }\n for (const key of write.remove) delete next[key]\n Object.assign(next, write.set)\n held = next\n }),\n current: () => held,\n writes,\n }\n}\n\nexport const MirrorStore = {\n /** The URL's query string (or hash), through `foldkit/navigation`. `owned` are the keys the mirror may touch. */\n url: urlStore,\n /** One JSON document under `key` in Effect's `KeyValueStore`, scoped and versioned. */\n kv: kvStore,\n memory: memoryStore,\n}\n\n// ---------------------------------------------------------------------------\n// Messages\n// ---------------------------------------------------------------------------\n\n/** Mirror's Message cases, for `defineMessageUnion({ ...Mirror.messages, … })`. */\nexport const mirrorMessageCases = {\n /** A store was read (`mirror.restore`); `keys` are what it held for the mirror named. */\n MirrorRestored: { name: Schema.String, keys: Schema.Record(Schema.String, Schema.String) },\n} satisfies Record<string, Schema.Struct.Fields>\n\nexport interface MirrorRestored {\n readonly _tag: 'MirrorRestored'\n readonly name: string\n readonly keys: Encoded\n}\n\nexport type MirrorMessage = MirrorRestored\n\n// ---------------------------------------------------------------------------\n// Key codecs\n// ---------------------------------------------------------------------------\n\n/** A key's text form and back; the decode names what is wrong when it fails. */\ninterface KeyCodec {\n readonly decode: (text: string) => Result.Result<unknown, string>\n readonly encode: (value: unknown) => string\n}\n\nconst failure = (message: string): Result.Result<never, string> => Result.fail(message)\n\n/**\n * A key's codec, from an override or derived from the field: the field's\n * encoded form of the initial value says whether the key is text, a number,\n * a boolean, or JSON, and the field schema validates whatever was parsed.\n */\nconst codecFor = (\n field: Schema.Codec<unknown, unknown, never, never>,\n initial: unknown,\n override: Schema.Codec<unknown, string, never, never> | undefined,\n): KeyCodec => {\n if (override !== undefined) {\n const decode = Schema.decodeUnknownResult(override)\n const encode = Schema.encodeSync(override)\n return {\n decode: text => Result.mapError(decode(text), error => error.message),\n encode: value => encode(value),\n }\n }\n const encodeField = Schema.encodeSync(field)\n const decodeField = Schema.decodeUnknownResult(field)\n const shape = typeof encodeField(initial)\n const validate = (candidate: unknown) =>\n Result.mapError(decodeField(candidate), error => error.message)\n return {\n decode: text => {\n switch (shape) {\n case 'string':\n return validate(text)\n case 'number': {\n const value = text.trim() === '' ? Number.NaN : Number(text)\n return Number.isNaN(value) ? failure(`\"${text}\" is not a number`) : validate(value)\n }\n case 'boolean':\n return text === 'true' || text === 'false'\n ? validate(text === 'true')\n : failure(`\"${text}\" is not \"true\" or \"false\"`)\n default: {\n try {\n return validate(JSON.parse(text))\n } catch {\n return failure(`\"${text}\" is not JSON`)\n }\n }\n }\n },\n encode: value => {\n const encoded = encodeField(value)\n return shape === 'string' || shape === 'number' || shape === 'boolean'\n ? String(encoded)\n : JSON.stringify(encoded)\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// Mirrors\n// ---------------------------------------------------------------------------\n\n/** The value type of a field schema. */\ntype TypeOf<S> = S extends { readonly Type: infer T } ? T : never\n\n/**\n * The slice a mirror keeps: field refs straight from `App.fields`, or a\n * writable projection over them (`Projection.pick`, `Projection.compose`),\n * the same object `foldkit-sync` replicates.\n */\nexport type Slice = WritableProjection<any, any> | readonly FieldRef<any, any, string>[]\n\n/** The Struct fields of a slice. */\nexport type SliceFields<S extends Slice> =\n S extends WritableProjection<any, infer Fields>\n ? Fields\n : S extends readonly FieldRef<any, any, string>[]\n ? { readonly [R in S[number] as R['key']]: R['Schema'] }\n : never\n\n/** The Model a slice is of. */\nexport type SliceRoot<S extends Slice> =\n S extends WritableProjection<infer Root, any>\n ? Root\n : S extends readonly FieldRef<infer Root, any, string>[]\n ? Root\n : never\n\n/** The value a slice reads. */\nexport type SliceValue<S extends Slice> = Schema.Struct.Type<SliceFields<S>>\n\nconst projectionOf = <S extends Slice>(\n slice: S,\n): WritableProjection<SliceRoot<S>, SliceFields<S>> =>\n (Array.isArray(slice)\n ? Projection.pick(...(slice as readonly FieldRef<any, any, string>[]))\n : slice) as WritableProjection<SliceRoot<S>, SliceFields<S>>\n\n/** How one field is kept: its store key, its history intent, whether its default is written, and its text codec. */\nexport interface KeyOptions<Value> {\n /** The store key; default the field name. */\n readonly key?: string | undefined\n /** Whether a change of this key adds a history entry; default `push`. Only the URL has history. */\n readonly history?: 'push' | 'replace' | undefined\n /** Write the key even when the value is the initial one; default false, so a default is elided. */\n readonly keep?: boolean | undefined\n /** The text codec; default derived from the field schema. */\n readonly codec?: Schema.Codec<Value, string, never, never> | undefined\n}\n\nexport interface MirrorConfig<S extends Slice, Name extends string = string> {\n /** Names the mirror in its contract and its Messages; default from the kind and keys. */\n readonly name?: Name | undefined\n /** The slice: field refs (`[App.fields.filter, App.fields.q]`) or a writable projection over them. */\n readonly fields: S\n readonly keys?:\n { readonly [K in keyof SliceFields<S>]?: KeyOptions<TypeOf<SliceFields<S>[K]>> } | undefined\n /** The Model's initial value, when the application was built without one; defaults are read from it. */\n readonly initial?: SliceRoot<S> | undefined\n /**\n * How long a changed slice waits before it is written; a newer change\n * supersedes a pending write. Browsers rate-limit history writes, so the\n * URL waits 50 ms by default; a store waits 250 ms.\n */\n readonly throttle?: Duration.Input | undefined\n}\n\nexport interface UrlMirrorConfig<\n S extends Slice,\n Name extends string = string,\n> extends MirrorConfig<S, Name> {\n /** Where in the URL the keys live; default the query string. */\n readonly location?: UrlLocation | undefined\n}\n\nexport interface KvMirrorConfig<S extends Slice, Name extends string = string> extends MirrorConfig<\n S,\n Name\n> {\n /** The store key the mirror's document lives under; also the mirror's name unless one is given. */\n readonly key: Name\n /** A user, a tenant: a document of another scope is discarded rather than restored. */\n readonly scope?: string | undefined\n}\n\n/** One key that failed to decode; the field keeps its initial value. */\nexport interface DecodeIssue {\n readonly key: string\n readonly message: string\n}\n\nexport interface Decoded<Value> {\n /** The fields the store named and decoded. */\n readonly value: Partial<Value>\n readonly issues: ReadonlyArray<DecodeIssue>\n}\n\n/**\n * A Model slice kept in a store. `Value` is the slice's value type; the keys,\n * codecs, and intents are values on the mirror, not type parameters.\n * `Mirror.url` and `Mirror.kv` add the `reduce` their store calls for.\n */\nexport interface Mirror<\n AppModel,\n Value extends Record<string, unknown>,\n R = never,\n Name extends string = string,\n> {\n readonly kind: 'url' | 'kv' | 'memory'\n readonly name: Name\n /** Store key per field. */\n readonly keys: Readonly<Record<keyof Value & string, string>>\n /** For `Module`: observes the slice, owns nothing. */\n readonly contract: Contract\n /** The store's keys for a Model, defaults elided unless a key is `keep`. */\n readonly encode: (model: AppModel) => Encoded\n /** The fields a store's keys name; a key that fails to decode is an issue, not a value. */\n readonly decode: (keys: Encoded) => Decoded<Value>\n /**\n * The Model with a store's keys as the whole slice: a key the store lacks,\n * or one that fails to decode, is the initial value.\n */\n readonly fromKeys: (model: AppModel, keys: Encoded) => AppModel\n /**\n * The Model with a store's keys applied to the fields it still holds at\n * their initial value, so a change made before the store answered is kept.\n */\n readonly restoreKeys: (model: AppModel, keys: Encoded) => AppModel\n /** A link: the keys of `model` with `patch` applied, on `base` (default the current URL, else `/`). */\n readonly href: (model: AppModel, patch?: Partial<Value>, base?: string) => string\n /** A Command that reads the store and yields `MirrorRestored` for this mirror. */\n readonly restore: Command<MirrorMessage, never, R>\n /** One Subscription entry, `<name>.mirror`: writes the store when the encoded slice changes. */\n readonly subscriptions: {\n readonly [K in `${Name}.mirror`]: EntryWithoutKeepAlive<AppModel, never, MirrorDependencies, R>\n }\n}\n\n/** A slice kept in the URL. */\nexport interface UrlMirror<\n AppModel,\n Value extends Record<string, unknown>,\n Name extends string = string,\n> extends Mirror<AppModel, Value, never, Name> {\n readonly kind: 'url'\n /** The Model with the URL's keys (a Foldkit `Url` or an href) as the whole slice: `fromKeys`. */\n readonly reduce: (model: AppModel, url: Url | string) => AppModel\n}\n\n/** A slice kept in Effect's `KeyValueStore`. */\nexport interface KvMirror<\n AppModel,\n Value extends Record<string, unknown>,\n Name extends string = string,\n> extends Mirror<AppModel, Value, KeyValueStore.KeyValueStore, Name> {\n readonly kind: 'kv'\n /** The Model with a `MirrorRestored` for this mirror applied: `restoreKeys`; another mirror's is ignored. */\n readonly reduce: (model: AppModel, message: MirrorRestored) => AppModel\n}\n\nconst nameOf = (\n kind: Mirror<unknown, Record<string, unknown>>['kind'],\n keys: ReadonlyArray<string>,\n given: string | undefined,\n): string => given ?? `${kind}(${keys.join(',')})`\n\n// A URL key belongs to one mirror per application; the same mirror may be\n// declared again (a module re-evaluated, a test), another may not take it.\nconst claimed = new WeakMap<object, Map<string, string>>()\n\nconst claim = (\n owner: object,\n location: UrlLocation,\n keys: ReadonlyArray<string>,\n name: string,\n): void => {\n let byKey = claimed.get(owner)\n if (byKey === undefined) {\n byKey = new Map()\n claimed.set(owner, byKey)\n }\n for (const key of keys) {\n const at = `${location}:${key}`\n const holder = byKey.get(at)\n if (holder !== undefined && holder !== name) {\n throw new Error(\n `Mirror.url: key \"${key}\" in the ${location} is already mirrored by \"${holder}\"; \"${name}\" cannot mirror it too`,\n )\n }\n byKey.set(at, name)\n }\n}\n\n/** An application a mirror is declared over: its identity token, and its initial Model when it has one. */\nexport interface MirrorApp<AppModel> {\n readonly owner: object\n readonly initial?: AppModel | undefined\n}\n\n/** A Foldkit `Url` carries `search` and `hash` without their `?` and `#`; an href has them. */\nconst withPrefix = (prefix: '?' | '#', part: string): string =>\n part === '' || part.startsWith(prefix) ? part : `${prefix}${part}`\n\nconst hrefOf = (url: Url | string): string =>\n typeof url === 'string'\n ? url\n : `${url.pathname}${withPrefix('?', url.search._tag === 'Some' ? url.search.value : '')}${withPrefix(\n '#',\n url.hash._tag === 'Some' ? url.hash.value : '',\n )}`\n\nconst make = <S extends Slice, R, Name extends string>(\n app: MirrorApp<SliceRoot<S>>,\n kind: Mirror<unknown, Record<string, unknown>>['kind'],\n store: MirrorStore<R>,\n config: MirrorConfig<S, Name> & { readonly location?: UrlLocation | undefined },\n throttle: Duration.Input,\n) => {\n type AppModel = SliceRoot<S>\n type Value = SliceValue<S>\n const fields = projectionOf(config.fields)\n const names = Object.keys(fields.schema.fields)\n const options = (config.keys ?? {}) as Readonly<Record<string, KeyOptions<unknown> | undefined>>\n const initial = config.initial ?? app.initial\n if (initial === undefined) {\n throw new Error(\n `Mirror.${kind}: defaults are read from the initial Model, so build the application with \\`initial\\` or pass \\`initial\\` in the config`,\n )\n }\n const initialSlice = fields.get(initial) as Readonly<Record<string, unknown>>\n const location = config.location ?? 'search'\n\n const keyOf: Record<string, string> = {}\n const fieldOf: Record<string, string> = {}\n const codecs: Record<string, KeyCodec> = {}\n const history: Record<string, 'push' | 'replace'> = {}\n const keep = new Set<string>()\n const initialText: Record<string, string> = {}\n for (const field of names) {\n const option = options[field]\n const key = option?.key ?? field\n if (fieldOf[key] !== undefined) {\n throw new Error(\n `Mirror: fields \"${fieldOf[key]}\" and \"${field}\" both use the key \"${key}\"; give one another key`,\n )\n }\n keyOf[field] = key\n fieldOf[key] = field\n codecs[field] = codecFor(\n fields.schema.fields[field] as Schema.Codec<unknown, unknown, never, never>,\n initialSlice[field],\n option?.codec as Schema.Codec<unknown, string, never, never> | undefined,\n )\n history[field] = option?.history ?? 'push'\n if (option?.keep === true) keep.add(field)\n initialText[field] = codecs[field].encode(initialSlice[field])\n }\n const owned = names.map(field => keyOf[field]!)\n const name = nameOf(kind, owned, config.name) as Name\n if (kind === 'url') claim(app.owner, location, owned, name)\n\n const encodeSlice = (slice: Readonly<Record<string, unknown>>): Encoded => {\n const out: Record<string, string> = {}\n for (const field of names) {\n const text = codecs[field]!.encode(slice[field])\n if (!keep.has(field) && text === initialText[field]) continue\n out[keyOf[field]!] = text\n }\n return out\n }\n const encode = (model: AppModel): Encoded =>\n encodeSlice(fields.get(model) as Readonly<Record<string, unknown>>)\n\n const decode = (keys: Encoded): Decoded<Value> => {\n const value: Record<string, unknown> = {}\n const issues: DecodeIssue[] = []\n for (const field of names) {\n const key = keyOf[field]!\n const text = keys[key]\n if (text === undefined) continue\n const decoded = codecs[field]!.decode(text)\n if (Result.isFailure(decoded)) issues.push({ key, message: decoded.failure })\n else value[field] = decoded.success\n }\n return { value: value as Partial<Value>, issues }\n }\n\n const keysOfUrl = (source: Url | string): Encoded => {\n const parts = splitHref(hrefOf(source))\n return readParams(location === 'search' ? parts.search : parts.hash, owned)\n }\n\n const fromKeys = (model: AppModel, keys: Encoded): AppModel => {\n const decoded = decode(keys).value as Readonly<Record<string, unknown>>\n return fields.set(model, { ...initialSlice, ...decoded } as never)\n }\n\n const restoreKeys = (model: AppModel, keys: Encoded): AppModel => {\n const current = fields.get(model) as Readonly<Record<string, unknown>>\n const restored = decode(keys).value as Readonly<Record<string, unknown>>\n const next: Record<string, unknown> = { ...current }\n for (const field of names) {\n // A change the user made before the store answered wins over the store.\n if (codecs[field]!.encode(current[field]) !== initialText[field]) continue\n if (field in restored) next[field] = restored[field]\n }\n return fields.set(model, next as never)\n }\n\n const href = (model: AppModel, patch?: Partial<Value>, base?: string): string => {\n const slice = { ...(fields.get(model) as Readonly<Record<string, unknown>>), ...patch }\n const set = encodeSlice(slice)\n const remove = owned.filter(key => !(key in set))\n return applyToHref(base ?? currentHref() ?? '/', { set, remove }, location)\n }\n\n const contract: Contract = {\n kind: 'mirror',\n name,\n owner: app.owner,\n owns: [],\n observes: fields.dependencies,\n messages: kind === 'kv' ? ['MirrorRestored'] : [],\n requirements: [],\n }\n\n const restore: Command<MirrorMessage, never, R> = {\n name: `Mirror.restore(${name})`,\n effect: store.read.pipe(\n Effect.map((keys): MirrorMessage => ({ _tag: 'MirrorRestored', name, keys: keys ?? {} })),\n ),\n }\n\n // Writes only what changed, and pushes only for a changed key that pushes:\n // a removal (a key back at its default) never adds a history entry.\n const sync = (encoded: Encoded): Effect.Effect<void, never, R> =>\n Effect.gen(function* () {\n const current = (yield* store.read) ?? {}\n const remove = owned.filter(key => !(key in encoded) && key in current)\n const changed = owned.filter(key => key in encoded && current[key] !== encoded[key])\n if (remove.length === 0 && changed.length === 0) return\n const intent = changed.some(key => history[fieldOf[key]!] === 'push') ? 'push' : 'replace'\n yield* store.write({ set: encoded, remove, intent })\n })\n\n const entry: EntryWithoutKeepAlive<AppModel, never, MirrorDependencies, R> = {\n dependenciesSchema: Schema.Struct({ keys: Schema.Record(Schema.String, Schema.String) }),\n modelToDependencies: model => ({ keys: encode(model) }),\n dependenciesToStream: ({ keys }) =>\n Stream.fromEffect(sync(keys).pipe(Effect.delay(throttle))).pipe(Stream.drain),\n }\n\n const mirror: Mirror<AppModel, Value, R, Name> = {\n kind,\n name,\n keys: keyOf as Readonly<Record<keyof Value & string, string>>,\n contract,\n encode,\n decode,\n fromKeys,\n restoreKeys,\n href,\n restore,\n subscriptions: { [`${name}.mirror`]: entry } as Mirror<\n AppModel,\n Value,\n R,\n Name\n >['subscriptions'],\n }\n return { mirror, keysOfUrl }\n}\n\nexport const Mirror = {\n /** Mirror's Message cases, to spread into the application's union. */\n messages: mirrorMessageCases,\n\n /** Narrows the application's union to Mirror's cases, by tag. */\n reduces: <M extends { readonly _tag: string }>(\n message: M,\n ): message is Extract<M, { readonly _tag: 'MirrorRestored' }> =>\n Object.hasOwn(mirrorMessageCases, message._tag),\n\n /**\n * A slice kept in the URL: `Projection.pick(App.fields.filter, App.fields.q)`\n * as `?filter=…&q=…`, defaults elided, written when it changes (one history\n * write per Model change) and read back with `reduce(model, url)` on\n * `onUrlChange` and on cold load.\n */\n url: <S extends Slice, Name extends string = string>(\n app: MirrorApp<SliceRoot<S>>,\n config: UrlMirrorConfig<S, Name>,\n ): UrlMirror<SliceRoot<S>, SliceValue<S>, Name> => {\n const owned = Object.keys(projectionOf(config.fields).schema.fields).map(\n field =>\n (config.keys as Readonly<Record<string, KeyOptions<unknown> | undefined>> | undefined)?.[\n field\n ]?.key ?? field,\n )\n const { mirror, keysOfUrl } = make(\n app,\n 'url',\n MirrorStore.url(owned, config.location ?? 'search'),\n config,\n config.throttle ?? '50 millis',\n )\n return {\n ...mirror,\n kind: 'url',\n reduce: (model, url) => mirror.fromKeys(model, keysOfUrl(url)),\n }\n },\n\n /**\n * A slice kept in Effect's `KeyValueStore` under `key`, as one scoped,\n * versioned JSON document: written when it changes, read back by the\n * `restore` Command whose `MirrorRestored` `reduce` applies.\n */\n kv: <S extends Slice, Name extends string = string>(\n app: MirrorApp<SliceRoot<S>>,\n config: KvMirrorConfig<S, Name>,\n ): KvMirror<SliceRoot<S>, SliceValue<S>, Name> => {\n const { mirror } = make(\n app,\n 'kv',\n MirrorStore.kv({\n key: config.key,\n ...(config.scope === undefined ? {} : { scope: config.scope }),\n }),\n { ...config, name: config.name ?? config.key },\n config.throttle ?? '250 millis',\n )\n return {\n ...mirror,\n kind: 'kv',\n reduce: (model, message) =>\n message.name === mirror.name ? mirror.restoreKeys(model, message.keys) : model,\n }\n },\n\n /** The kernel form: a slice kept in any `MirrorStore`, read back with `fromKeys` or `restoreKeys`. */\n make: <S extends Slice, R, Name extends string = string>(\n app: MirrorApp<SliceRoot<S>>,\n store: MirrorStore<R>,\n config: MirrorConfig<S, Name>,\n ): Mirror<SliceRoot<S>, SliceValue<S>, R, Name> =>\n make(app, 'memory', store, config, config.throttle ?? 0).mirror,\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqDA,MAAM,aAAa,SAAqE;CACtF,MAAM,SAAS,KAAK,QAAQ,GAAG;CAC/B,MAAM,OAAO,SAAS,IAAI,KAAK,KAAK,MAAM,MAAM;CAChD,MAAM,OAAO,SAAS,IAAI,OAAO,KAAK,MAAM,GAAG,MAAM;CACrD,MAAM,WAAW,KAAK,QAAQ,GAAG;CACjC,OAAO;EACL,UAAU,WAAW,IAAI,OAAO,KAAK,MAAM,GAAG,QAAQ;EACtD,QAAQ,WAAW,IAAI,KAAK,KAAK,MAAM,QAAQ;EAC/C;CACF;AACF;;AAGA,MAAM,cAAc,OAAe,UAA0C;CAC3E,MAAM,SAAS,IAAI,gBACjB,MAAM,WAAW,GAAG,K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AAO;GACL,GAAG;GACH,MAAM;GACN,SAAS,OAAO,YACd,QAAQ,SAAS,OAAO,OAAO,OAAO,YAAY,OAAO,QAAQ,IAAI,IAAI;EAC7E;CACF;;CAGA,OACE,KACA,OACA,WAEA,KAAK,KAAK,UAAU,OAAO,QAAQ,OAAO,YAAY,CAAC,CAAC,CAAC;AAC7D"}
|
package/package.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "foldkit-mirror",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A Foldkit Model slice kept in the URL or a key-value store: written when the slice changes, read back on navigation or cold load.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Patrick Glenn <doeixd@gmail.com>",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/doeixd/foldkit-plus.git",
|
|
11
|
+
"directory": "packages/mirror"
|
|
12
|
+
},
|
|
13
|
+
"homepage": "https://github.com/doeixd/foldkit-plus/tree/main/packages/mirror#readme",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/doeixd/foldkit-plus/issues"
|
|
16
|
+
},
|
|
17
|
+
"sideEffects": false,
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.mts",
|
|
21
|
+
"import": "./dist/index.mjs"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"README.md",
|
|
27
|
+
"LICENSE"
|
|
28
|
+
],
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"foldkit-surface": "0.1.0"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"effect": "^4.0.0-rc.112",
|
|
34
|
+
"foldkit": "^0.158.2"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"effect": "4.0.0-rc.112",
|
|
38
|
+
"foldkit": "0.158.2",
|
|
39
|
+
"jsdom": "26.1.0",
|
|
40
|
+
"tsdown": "^0.23.0",
|
|
41
|
+
"typescript": "^5.7.2"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "tsdown",
|
|
45
|
+
"typecheck": "tsc -b"
|
|
46
|
+
}
|
|
47
|
+
}
|