foldkit-mirror 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,32 +1,131 @@
1
1
  # `foldkit-mirror`
2
2
 
3
- Keeps part of a Foldkit Model in the URL or in a key-value store, so a filter
4
- survives a shared link and a draft survives a reload. You name a slice of the
5
- Model; the mirror writes it out whenever it changes and reads it back on
6
- navigation or cold load. Nothing else about the application changes: the Model
7
- is still the only truth, and `update` is still the only reducer.
8
-
9
- You do not declare keys, codecs, or defaults. They are derived from the field
10
- refs you point at: a key's name is the field's name, its text form comes from
11
- the field's encoded type, and a value equal to the Model's initial one is left
12
- out of the store entirely. The URL query string and Effect's `KeyValueStore`
13
- are the two stores that ship.
14
-
15
- **Use it when** the state is disposable, per-device, and cheap to lose: a
16
- filter, a sort, a page, an open panel, a preference, an unsent draft. **Not
17
- for** anything that must converge. A mirror is last-write-wins against a store
18
- with no log and no ordering, so two tabs writing the same key-value document
19
- simply overwrite each other. That is what separates it from
20
- [`foldkit-sync`](https://github.com/doeixd/foldkit-plus/tree/main/packages/sync)
21
- (an ordered durable log that converges) and from
22
- [`foldkit-remote`](https://github.com/doeixd/foldkit-plus/tree/main/packages/remote)
23
- (a normalized cache of another owner's facts). The design is in
24
- [`docs/design/MIRROR.md`](https://github.com/doeixd/foldkit-plus/blob/main/docs/design/MIRROR.md).
25
-
26
- | State | Owner | Mirror |
27
- | ---------------------------------------------- | --------------- | ----------------------------- |
28
- | Filter, sort, page, search text, an open panel | the local Model | the URL (`Mirror.url`) |
29
- | Preferences, a draft, a collapsed sidebar | the local Model | `KeyValueStore` (`Mirror.kv`) |
3
+ Keeps part of a Foldkit Model represented somewhere else — usually the URL or a
4
+ key-value store — **without making that representation the owner of the state**.
5
+
6
+ A filter can become `?filter=active`; a draft can survive a reload; a collapsed
7
+ sidebar can be remembered. In every case the Model remains authoritative and
8
+ `update` remains the only place application state changes.
9
+
10
+ The mental model is:
11
+
12
+ ```text
13
+ Model slice
14
+ |
15
+ | encode when it changes
16
+ v
17
+ URL / KeyValueStore
18
+
19
+ URL / KeyValueStore
20
+ |
21
+ | decode on navigation / cold load
22
+ v
23
+ Model slice
24
+ ```
25
+
26
+ A mirror is therefore a **secondary representation**, not a second store of
27
+ truth.
28
+
29
+ Use it for disposable, per-device state that is cheap to lose: filters, sort,
30
+ page, open panels, preferences, drafts, and similar local state. Do **not** use
31
+ it for state that several clients must converge on. A mirror is last-write-wins
32
+ with no durable log or ordering.
33
+
34
+ That is the boundary between the three nearby packages:
35
+
36
+ ```text
37
+ Mirror
38
+ Model owns the value
39
+ URL / store represents it
40
+ losing the representation is acceptable
41
+
42
+ Sync
43
+ client-authored state must survive offline
44
+ durable operations replay and converge
45
+
46
+ Remote
47
+ server owns the fact
48
+ client Model caches a disposable copy
49
+ ```
50
+
51
+ ## Which state belongs here?
52
+
53
+ | State | Owner | Representation |
54
+ | --- | --- | --- |
55
+ | Filter, sort, page, search text, open panel | local Model | URL via `Mirror.url` |
56
+ | Preference, draft, collapsed sidebar | local Model | `KeyValueStore` via `Mirror.kv` |
57
+ | Shared/offline edits that must converge | Sync/Durable | not Mirror |
58
+ | Server-derived facts | server / Remote | not Mirror |
59
+
60
+ A useful rule across Foldkit Plus remains **one owner per datum**. A mirror
61
+ observes a local field; it does not claim that field.
62
+
63
+ ## Two lifecycles to remember
64
+
65
+ The URL and a key-value store represent the same ownership model, but they come
66
+ back into the application at different times.
67
+
68
+ ### URL mirror
69
+
70
+ ```text
71
+ Model changes filter
72
+ |
73
+ v
74
+ Filters.subscriptions
75
+ |
76
+ v
77
+ history.pushState / replaceState
78
+ |
79
+ user navigates
80
+ v
81
+ UrlChanged
82
+ |
83
+ v
84
+ Filters.reduce(model, url)
85
+ |
86
+ v
87
+ Model
88
+ ```
89
+
90
+ The URL participates in navigation, so the runtime hands navigation back to the
91
+ application and the mirror reduces the URL into its slice.
92
+
93
+ ### Key-value mirror
94
+
95
+ ```text
96
+ cold load
97
+ |
98
+ v
99
+ Prefs.restore Command
100
+ |
101
+ v
102
+ MirrorRestored Message
103
+ |
104
+ v
105
+ Prefs.reduce(model, message)
106
+ |
107
+ v
108
+ Model
109
+
110
+ later Model changes
111
+ |
112
+ v
113
+ Prefs.subscriptions
114
+ |
115
+ v
116
+ KeyValueStore
117
+ ```
118
+
119
+ That is why the full integration has three seams:
120
+
121
+ ```text
122
+ reduce read an external representation back into Model
123
+ restore ask a store for its cold-load value
124
+ subscriptions write Model changes outward
125
+ ```
126
+
127
+ A URL mirror does not need a restore Command because the initial URL is already
128
+ available to application startup. A store mirror does.
30
129
 
31
130
  ## Install
32
131
 
@@ -34,176 +133,478 @@ simply overwrite each other. That is what separates it from
34
133
  pnpm add foldkit-mirror
35
134
  ```
36
135
 
37
- `foldkit` and `effect` are peer dependencies; `foldkit-surface` comes with it.
136
+ `foldkit` and `effect` are peer dependencies; `foldkit-surface` comes with the
137
+ package.
38
138
 
39
- ## Quick start
139
+ ## Sixty seconds: put a filter in the URL
40
140
 
41
- Declare the mirrors over the application, then wire their three seams: `reduce`
42
- in `update`, `restore` in a Command, and `subscriptions` for the writes.
141
+ Start from a normal Surface application:
43
142
 
44
143
  ```ts
45
144
  import { Schema } from 'effect'
46
- import type { KeyValueStore } from 'effect/unstable/persistence'
47
145
  import { defineMessageUnion } from 'foldkit/message'
48
- import * as Subscription from 'foldkit/subscription'
49
- import type * as Update from 'foldkit/update'
50
146
  import { Url } from 'foldkit/url'
51
- import { Projection, Surface } from 'foldkit-surface'
147
+ import { Surface } from 'foldkit-surface'
52
148
  import { Mirror } from 'foldkit-mirror'
53
149
 
54
150
  const Model = Schema.Struct({
55
151
  filter: Schema.Literals(['all', 'active', 'done']),
56
152
  page: Schema.Number,
57
- q: Schema.String,
58
- sidebar: Schema.Literals(['open', 'closed']),
59
- draft: Schema.String,
60
153
  })
61
154
  type Model = typeof Model.Type
62
155
 
63
- // `Mirror.messages` contributes `MirrorRestored`, which a store mirror reduces.
64
- const Message = defineMessageUnion({ ...Mirror.messages, UrlChanged: { url: Url } })
156
+ const Message = defineMessageUnion({
157
+ UrlChanged: { url: Url },
158
+ })
65
159
  type Message = typeof Message.Type
66
160
 
67
- const initial: Model = { filter: 'all', page: 1, q: '', sidebar: 'open', draft: '' }
68
- const App = Surface.application({ Model, Message, initial, update })
161
+ const initial: Model = {
162
+ filter: 'all',
163
+ page: 1,
164
+ }
165
+
166
+ const App = Surface.application({
167
+ Model,
168
+ Message,
169
+ initial,
170
+ update,
171
+ })
172
+ ```
173
+
174
+ Declare which local fields the URL represents:
69
175
 
70
- // The URL shows the filters, as ?filter=…&page=…&q=…; keys default to the field names.
176
+ ```ts
71
177
  const Filters = Mirror.url(App, {
72
178
  name: 'filters',
73
- fields: [App.fields.filter, App.fields.page, App.fields.q],
74
- keys: { q: { history: 'replace' } }, // the rest push a history entry
179
+ fields: [
180
+ App.fields.filter,
181
+ App.fields.page,
182
+ ],
75
183
  })
184
+ ```
185
+
186
+ With the default values, the URL stays clean. If the Model becomes:
187
+
188
+ ```ts
189
+ {
190
+ filter: 'active',
191
+ page: 2,
192
+ }
193
+ ```
194
+
195
+ the mirror represents that as approximately:
196
+
197
+ ```text
198
+ ?filter=active&page=2
199
+ ```
200
+
201
+ The field names, default values, and basic text codecs come from the application
202
+ fields; they are not declared again.
203
+
204
+ Navigation comes back through the application's normal URL Message:
205
+
206
+ ```ts
207
+ function update(model: Model, message: Message) {
208
+ switch (message._tag) {
209
+ case 'UrlChanged':
210
+ return {
211
+ model: Filters.reduce(model, message.url),
212
+ }
213
+ }
214
+ }
215
+ ```
216
+
217
+ And the mirror's Subscription writes Model changes outward:
218
+
219
+ ```ts
220
+ import * as Subscription from 'foldkit/subscription'
221
+
222
+ const subscriptions = Subscription.make<Model, Message>()(() => ({
223
+ ...Filters.subscriptions,
224
+ }))
225
+ ```
226
+
227
+ That is the entire URL loop:
228
+
229
+ ```text
230
+ Model -> subscription -> URL
231
+ URL -> UrlChanged -> reduce -> Model
232
+ ```
233
+
234
+ ## Add remembered local state with `Mirror.kv`
235
+
236
+ For state that should survive reload but does not belong in the URL, use an
237
+ Effect `KeyValueStore`:
238
+
239
+ ```ts
240
+ import { Projection } from 'foldkit-surface'
76
241
 
77
- // A key-value store keeps the preference and the draft across sessions.
78
242
  const Prefs = Mirror.kv(App, {
79
243
  key: 'todo/prefs',
80
- fields: Projection.pick(App.fields.sidebar, App.fields.draft),
244
+ fields: Projection.pick(
245
+ App.fields.sidebar,
246
+ App.fields.draft,
247
+ ),
81
248
  })
249
+ ```
250
+
251
+ A key-value mirror restores through a Message, so include Mirror's cases in the
252
+ application union:
82
253
 
83
- type Return = Update.Return<Model, Message, KeyValueStore.KeyValueStore>
254
+ ```ts
255
+ const Message = defineMessageUnion({
256
+ ...Mirror.messages,
257
+ UrlChanged: { url: Url },
258
+ })
259
+ ```
84
260
 
261
+ Then reduce only its restore Message:
262
+
263
+ ```ts
85
264
  function update(model: Model, message: Message): Return {
86
- if (Mirror.reduces(message)) return { model: Prefs.reduce(model, message) }
265
+ if (Mirror.reduces(message)) {
266
+ return {
267
+ model: Prefs.reduce(model, message),
268
+ }
269
+ }
270
+
87
271
  switch (message._tag) {
88
272
  case 'UrlChanged':
89
- return { model: Filters.reduce(model, message.url) }
273
+ return {
274
+ model: Filters.reduce(model, message.url),
275
+ }
90
276
  }
91
277
  }
278
+ ```
92
279
 
93
- // Cold load: the URL is reduced in, and the store is asked for the rest.
280
+ Ask the store for its representation at cold load:
281
+
282
+ ```ts
94
283
  const init = (url: Url): Return => ({
284
+ // URL wins first because startup already has it.
95
285
  model: Filters.reduce(initial, url),
286
+
287
+ // The store responds later with MirrorRestored.
96
288
  commands: [Prefs.restore],
97
289
  })
290
+ ```
291
+
292
+ And write both representations from the same Model:
98
293
 
99
- // The writes: one entry per mirror, keyed `<name>.mirror`.
100
- const subscriptions = Subscription.make<Model, Message, KeyValueStore.KeyValueStore>()(() => ({
294
+ ```ts
295
+ const subscriptions = Subscription.make<
296
+ Model,
297
+ Message,
298
+ KeyValueStore.KeyValueStore
299
+ >()(() => ({
101
300
  ...Filters.subscriptions,
102
301
  ...Prefs.subscriptions,
103
302
  }))
104
303
  ```
105
304
 
106
- The slice is field refs straight from `App.fields`, or a writable projection
107
- over them (`Projection.pick`, `Projection.compose`) — the same object
108
- `foldkit-sync` replicates. The URL comes in through the `onUrlChange` the
109
- runtime already has for routing; `Filters.reduce` takes a Foldkit `Url` or an
110
- href. The store comes in through one `MirrorRestored` case spread from
111
- `Mirror.messages`. Links are `Filters.href(model, { page: 2 })`, the mirrored
112
- keys applied to the current URL. An application built without `initial` passes
113
- `initial` in the mirror's config; defaults are read from it. Under
114
- `foldkit-sync`'s `mount`, the `url` option (`init`, `onUrlChange`) is where the
115
- URL mirror plugs in.
116
-
117
- ## What the Model being the truth gives
118
-
119
- - **Defaults for free.** `App.initial` holds every field's default, so a key
120
- equal to its initial value is elided from the store; there is no
121
- `.withDefault`. A key that should always be written opts in with
122
- `keys: { page: { keep: true } }`.
123
- - **Batching for free.** The entry's dependencies are the encoded keys: one
124
- Model change yields at most one write, whatever it touched, and a change
125
- that encodes to the same keys writes nothing. Back and forward cannot loop:
126
- `popstate` reduces into the Model, the entry sees the same keys, and stops.
127
- - **Codecs for free.** A key's codec is derived from the field's encoded form
128
- of the initial value: a string is itself, a number is parsed as one, a
129
- boolean is `true`/`false`, and anything else is JSON. `keys: { tags: { codec } }`
130
- gives a key a `Schema.Codec<Value, string>` of its own when the URL should
131
- read nicely (`?tags=a,b`).
132
-
133
- ## Reading back
134
-
135
- Each kind of mirror has the `reduce` its store calls for:
136
-
137
- - A URL mirror's `reduce(model, url)` takes a Foldkit `Url` or an href and
138
- sets the whole slice: a key the URL lacks is the initial value, and a key
139
- that fails to decode is too, so `?page=abc` shows page one rather than
140
- breaking the page. `mirror.decode(keys)` returns the value and the issues
141
- for a caller that wants to say so. Only the mirror's keys are read; the
142
- path, the hash, and every other key are left alone.
143
- - A store mirror's `reduce(model, message)` takes the `MirrorRestored` its
144
- `restore` Command yields and sets only the fields the Model still holds at
145
- their initial value, so a change the user made before the store answered is
146
- kept. Another mirror's Message is ignored.
147
-
148
- Both are the kernel's `fromKeys(model, keys)` and `restoreKeys(model, keys)`,
149
- which `Mirror.make` exposes for any store.
150
-
151
- `Mirror.reduces(message)` narrows the application's union to Mirror's cases.
152
-
153
- ## Writing
154
-
155
- The entry writes only what changed, waits `throttle` first (50 ms for the
156
- URL, 250 ms for a store; browsers rate-limit history writes), and a newer
157
- slice supersedes a pending write, which is what Foldkit's dependency restart
158
- does. A write pushes a history entry only for a changed key whose `history`
159
- is `push` (the default); a `replace` key, and a key going back to its default,
160
- replace. The store ignores the intent. Outside a browser the URL store writes
161
- nothing, so a server render is safe.
162
-
163
- A key-value mirror keeps one JSON document under `key`, with a version and a
164
- `scope` (a user, a tenant); a document of another version or scope, or a
165
- malformed one, is discarded and removed rather than restored, as
166
- `RemotePersistence` does, because a mirror holds no unsent user edits. A
167
- store failure is absorbed: the mirror is disposable state and never fails the
168
- application. A slice back at its defaults removes the document.
305
+ The important part is what did **not** change: `sidebar` and `draft` are still
306
+ ordinary Model fields. The key-value store is merely how those fields are
307
+ remembered between sessions.
308
+
309
+ ## One list per application with wiring
310
+
311
+ The hand-wiring above — reduce by tag, restore at startup, spread the
312
+ Subscriptions — is one value when the application uses `foldkit-bundle`:
313
+
314
+ ```ts
315
+ import { Bundle } from 'foldkit-bundle'
316
+
317
+ const Page = Bundle.parent({ Model, Message })
318
+ const wiring = Page.assemble(Filters.wiring('UrlChanged'), Prefs.wiring())
319
+ const update = wiring.update(model => ({ model }))
320
+ const subscriptions = wiring.subscriptions()
321
+ const url = wiring.url(url => Message.UrlChanged({ url }))
322
+ ```
323
+
324
+ `Filters.wiring('UrlChanged')` routes the application's URL Message into
325
+ `Filters.reduce` and reads the URL at startup; `Prefs.wiring()` routes its own
326
+ `MirrorRestored` into `Prefs.reduce` and runs `Prefs.restore` at startup. Two
327
+ key-value mirrors share the `MirrorRestored` tag, so each wiring routes only
328
+ its own mirror's Message and the assembly accepts both.
329
+
330
+ ## Slice = field refs or a writable Projection
331
+
332
+ A mirror accepts either field refs directly:
333
+
334
+ ```ts
335
+ fields: [
336
+ App.fields.filter,
337
+ App.fields.page,
338
+ ]
339
+ ```
340
+
341
+ or a writable Projection:
342
+
343
+ ```ts
344
+ fields: Projection.pick(
345
+ App.fields.sidebar,
346
+ App.fields.draft,
347
+ )
348
+ ```
349
+
350
+ That is the same structural vocabulary used elsewhere in Foldkit Plus. The
351
+ projection tells Mirror what it may observe and write back; it does not transfer
352
+ ownership away from the application.
353
+
354
+ ## What the Model being the truth gives you
355
+
356
+ Because Mirror derives its representation from application fields, several
357
+ behaviors fall out automatically.
358
+
359
+ ### Defaults
360
+
361
+ `App.initial` is the default source. A field equal to its initial value is omitted
362
+ from the representation by default:
363
+
364
+ ```text
365
+ initial: { filter: 'all', page: 1 }
366
+ Model: { filter: 'all', page: 1 }
367
+ URL: /todos
368
+ ```
369
+
370
+ Changing only the filter yields:
371
+
372
+ ```text
373
+ /todos?filter=active
374
+ ```
375
+
376
+ A key that should remain explicit can opt in:
377
+
378
+ ```ts
379
+ keys: {
380
+ page: { keep: true },
381
+ }
382
+ ```
383
+
384
+ An application created without `initial` passes the initial Model in the mirror
385
+ config instead.
386
+
387
+ ### Codecs
388
+
389
+ Mirror derives a key's text representation from the field's encoded type:
390
+
391
+ ```text
392
+ string -> text
393
+ number -> parsed number
394
+ boolean -> true / false
395
+ other -> JSON
396
+ ```
397
+
398
+ Override a field when a friendlier representation is useful:
399
+
400
+ ```ts
401
+ keys: {
402
+ tags: {
403
+ codec: TagsAsCommaSeparatedText,
404
+ },
405
+ }
406
+ ```
407
+
408
+ `mirror.decode(keys)` returns both the successfully decoded values and any
409
+ issues when a caller wants to surface invalid input.
410
+
411
+ ### Batching and loop avoidance
412
+
413
+ Subscriptions depend on the encoded slice, not every Model transition. One
414
+ transition that changes several mirrored fields still produces at most one write,
415
+ and a change that encodes to the same key set produces none.
416
+
417
+ That also prevents URL feedback loops:
418
+
419
+ ```text
420
+ popstate
421
+ -> reduce URL into Model
422
+ -> subscription sees same encoded keys
423
+ -> no second navigation write
424
+ ```
425
+
426
+ ## How state changes here
427
+
428
+ Ordinary edits use Message/`update`/`evo` like anywhere else; the mirror
429
+ observes and represents. Restoration runs the other direction: the
430
+ declared writable projection installs the URL/KV value into the Model on
431
+ startup. The projection is declared up front, so restoration can only ever
432
+ write the fields the application already linked.
433
+
434
+ ## URL history behavior
435
+
436
+ URL keys default to `history: 'push'`. A field such as free-form search text can
437
+ replace the current entry instead:
438
+
439
+ ```ts
440
+ const Filters = Mirror.url(App, {
441
+ name: 'filters',
442
+ fields: [
443
+ App.fields.filter,
444
+ App.fields.page,
445
+ App.fields.q,
446
+ ],
447
+ keys: {
448
+ q: { history: 'replace' },
449
+ },
450
+ })
451
+ ```
452
+
453
+ A key returning to its default is removed and uses replace semantics rather than
454
+ creating a new history step.
455
+
456
+ `Filters.href(model, { page: 2 })` applies the mirrored key changes to the
457
+ current URL without touching unrelated query keys, the path, or the hash.
458
+
459
+ By default the mirror uses the query string. `location: 'hash'` stores its keys
460
+ in the hash instead.
461
+
462
+ Outside a browser the URL store writes nothing, so server rendering is safe.
463
+
464
+ ## Key-value restore semantics
465
+
466
+ A store restore is intentionally conservative. `Prefs.reduce(model, message)`
467
+ only restores fields that are **still at their initial value**.
468
+
469
+ That protects an edit made before the asynchronous restore finished:
470
+
471
+ ```text
472
+ initial draft = ''
473
+ store draft = 'remembered'
474
+
475
+ user types 'new text' before restore returns
476
+
477
+ MirrorRestored arrives
478
+ |
479
+ v
480
+ current draft is no longer initial
481
+ |
482
+ v
483
+ keep 'new text'
484
+ ```
485
+
486
+ When URL and KV mirrors both represent one field, cold-load precedence is:
487
+
488
+ ```text
489
+ URL value, when present
490
+ >
491
+ key-value restore
492
+ >
493
+ initial value
494
+ ```
495
+
496
+ because startup reduces the URL first and the later store restore only fills
497
+ fields still at their defaults.
498
+
499
+ ## Writing and persistence behavior
500
+
501
+ Writes are throttled so rapidly changing local state does not hammer the external
502
+ representation:
503
+
504
+ ```text
505
+ URL mirror default: 50 ms
506
+ KV mirror default: 250 ms
507
+ ```
508
+
509
+ A newer slice supersedes a pending write through Foldkit's dependency restart
510
+ behavior.
511
+
512
+ A key-value mirror stores one versioned JSON document under its configured key.
513
+ It may also be scoped to a user or tenant:
514
+
515
+ ```ts
516
+ Mirror.kv(App, {
517
+ key: 'todo/prefs',
518
+ scope: principal.userId,
519
+ fields: ...,
520
+ })
521
+ ```
522
+
523
+ A document with another version/scope, or a malformed document, is discarded and
524
+ removed. This is safe because Mirror represents **disposable state**, not unsent
525
+ user operations.
526
+
527
+ Store failures are absorbed and logged rather than failing the application. A
528
+ slice back at all defaults removes the stored document.
169
529
 
170
530
  ## Contracts and `Module`
171
531
 
172
- `mirror.contract` is of kind `mirror`: it observes the slice's fields and owns
173
- nothing, so `Module.manifest` shows the field as `local` with the mirror
174
- beside it. A key-value mirror names `MirrorRestored` among its Messages, so a
175
- union that did not spread `Mirror.messages` is an `unknown-message` finding.
176
- A URL key belongs to one mirror per application: a second mirror claiming it
177
- is an error at construction naming the first.
532
+ Every mirror exposes a `contract` of kind `mirror`.
533
+
534
+ Conceptually:
535
+
536
+ ```text
537
+ field owner: local application Model
538
+ mirror: observer / representation
539
+ ```
540
+
541
+ So `Module.manifest` still reports the field as local with the mirror beside it.
542
+ A mirror never becomes a second owner.
543
+
544
+ A key-value mirror declares `MirrorRestored` among its Messages. If the
545
+ application union forgot to spread `Mirror.messages`, `Module.validate` can
546
+ report that as an unknown Message dependency.
547
+
548
+ A URL key belongs to one URL mirror per application. Constructing another mirror
549
+ that claims the same key fails and names the original owner of that URL key.
550
+
551
+ ## The generic store seam
552
+
553
+ `Mirror.url` and `Mirror.kv` are convenience constructors over the kernel:
554
+
555
+ ```ts
556
+ Mirror.make(App, store, config)
557
+ ```
558
+
559
+ A `MirrorStore` only needs:
560
+
561
+ ```ts
562
+ interface MirrorStore<R = never> {
563
+ readonly read: Effect.Effect<Encoded | undefined, never, R>
564
+ readonly write: (
565
+ write: {
566
+ set: Encoded
567
+ remove: ReadonlyArray<string>
568
+ intent: 'push' | 'replace'
569
+ },
570
+ ) => Effect.Effect<void, never, R>
571
+ }
572
+ ```
573
+
574
+ Built-ins:
575
+
576
+ ```text
577
+ MirrorStore.url(...) browser URL representation
578
+ MirrorStore.kv(...) Effect KeyValueStore representation
579
+ MirrorStore.memory(...) test/in-memory representation
580
+ ```
178
581
 
179
- ## The kernel
582
+ `applyToHref(href, { set, remove })` is the pure URL transformation used by the
583
+ URL store.
180
584
 
181
- `Mirror.make(App, store, config)` keeps a slice in any `MirrorStore`: `read`
182
- the keys, `write({ set, remove, intent })`. `MirrorStore.url(keys, location)`,
183
- `MirrorStore.kv({ key, scope })`, and `MirrorStore.memory()` (records its
184
- writes, for tests) are the three; `applyToHref(href, { set, remove })` is the
185
- pure URL step `href` and the URL store share.
585
+ Most applications should use `Mirror.url` / `Mirror.kv` rather than starting at
586
+ this kernel.
186
587
 
187
588
  ## Limits
188
589
 
189
- - A mirror is last-write-wins. Two tabs writing one key-value document do not
190
- converge; that is `foldkit-sync`'s job.
191
- - Arrays and objects are JSON in the URL by default. Give the key a codec for
192
- a readable form.
193
- - Two mirrors may name one field (a filter both linkable and remembered). On a
194
- cold load the URL wins when it names the key, then the store, then the
195
- initial value: `init` reduces the URL first, and `restore` applies only
196
- fields still at their initial value.
197
- - The URL store touches only its keys and needs a browser `location`; it uses
198
- the query string unless `location: 'hash'` says otherwise. A Foldkit router's
199
- `route.query(schema)` composes with it when they name different keys.
590
+ - A mirror is last-write-wins. Two tabs writing one KV document do not converge;
591
+ use `foldkit-sync` when ordering and convergence matter.
592
+ - Arrays and objects use JSON in the URL by default; provide a codec for a more
593
+ readable representation.
594
+ - Two different mirror kinds may observe the same Model field. That is not two
595
+ owners; cold-load precedence follows the URL -> KV -> initial rule above.
596
+ - A URL mirror only touches the keys it owns. It composes with a Foldkit
597
+ router's `route.query(schema)` when they use different keys.
598
+ - Mirror stores have no durable operation log, conflict resolution, or
599
+ multi-device synchronization.
200
600
 
201
601
  ## See also
202
602
 
203
- - [Mirrored state](https://github.com/doeixd/foldkit-plus/blob/main/docs/mirror.md) — the mental model, and when a
204
- mirror is the wrong tool.
205
- - [The design note](https://github.com/doeixd/foldkit-plus/blob/main/docs/design/MIRROR.md) — why a mirror is not
206
- an owner.
207
- - [`foldkit-sync`](https://github.com/doeixd/foldkit-plus/tree/main/packages/sync) — for state that must converge instead; its mount's `url` option
208
- is where a URL mirror plugs in.
209
- - [`examples/todo-app`](https://github.com/doeixd/foldkit-plus/tree/main/examples/todo-app) — a linkable filter and a remembered draft.
603
+ - [Mirrored state](../../docs/mirror.md) — the conceptual guide and package
604
+ choice rules.
605
+ - [Mirror design note](../../docs/design/MIRROR.md) — why mirroring is
606
+ observation rather than ownership.
607
+ - [`foldkit-sync`](../sync) — state that must survive offline and converge.
608
+ - [`foldkit-remote`](../remote) — a cache of facts owned by the server.
609
+ - [`examples/todo-app`](../../examples/todo-app) — a linkable filter and a
610
+ remembered draft in a real application.
package/dist/index.d.mts CHANGED
@@ -1,8 +1,9 @@
1
1
  import { Duration, Effect, Schema } from "effect";
2
2
  import { KeyValueStore } from "effect/unstable/persistence";
3
- import { Contract, FieldRef, WritableProjection } from "foldkit-surface";
4
- import { Command } from "foldkit/command";
5
3
  import { EntryWithoutKeepAlive } from "foldkit/subscription";
4
+ import { Contract, FieldRef, Wiring, WritableProjection } from "foldkit-surface";
5
+ import { Command } from "foldkit/command";
6
+ import * as Update from "foldkit/update";
6
7
  import { Url } from "foldkit/url";
7
8
  //#region src/index.d.ts
8
9
  /** The keys a mirror holds in a store, as the store holds them: strings. */
@@ -162,12 +163,36 @@ export interface UrlMirror<AppModel, Value extends Record<string, unknown>, Name
162
163
  readonly kind: 'url';
163
164
  /** The Model with the URL's keys (a Foldkit `Url` or an href) as the whole slice: `fromKeys`. */
164
165
  readonly reduce: (model: AppModel, url: Url | string) => AppModel;
166
+ /**
167
+ * How this mirror joins an assembly: it routes the application's URL Message
168
+ * (a variant with a `url` field, tagged `tag`) into `reduce`, reads the URL at
169
+ * startup, and brings its Subscriptions and contract. Several URL mirrors share
170
+ * the URL Message.
171
+ */
172
+ readonly wiring: <const Tag extends string>(tag: Tag) => UrlMirrorWiring<AppModel, Tag>;
165
173
  }
174
+ /** The Message a URL mirror routes: the application's URL variant. */
175
+ export type UrlChangedMessage<Tag extends string> = {
176
+ readonly _tag: Tag;
177
+ readonly url: Url;
178
+ };
179
+ export type UrlMirrorWiring<AppModel, Tag extends string> = Wiring<AppModel, UrlChangedMessage<Tag>> & {
180
+ readonly onUrl: (model: AppModel, url: Url) => AppModel;
181
+ };
182
+ export type KvMirrorWiring<AppModel> = Wiring<AppModel, MirrorRestored, KeyValueStore.KeyValueStore> & {
183
+ readonly init: Update.Step<AppModel, MirrorRestored, KeyValueStore.KeyValueStore>;
184
+ };
166
185
  /** A slice kept in Effect's `KeyValueStore`. */
167
186
  export interface KvMirror<AppModel, Value extends Record<string, unknown>, Name extends string = string> extends Mirror<AppModel, Value, KeyValueStore.KeyValueStore, Name> {
168
187
  readonly kind: 'kv';
169
188
  /** The Model with a `MirrorRestored` for this mirror applied: `restoreKeys`; another mirror's is ignored. */
170
189
  readonly reduce: (model: AppModel, message: MirrorRestored) => AppModel;
190
+ /**
191
+ * How this mirror joins an assembly: it routes its own `MirrorRestored` into
192
+ * `reduce`, runs `restore` at startup, and brings its Subscriptions and
193
+ * contract. Other key-value mirrors share the `MirrorRestored` tag.
194
+ */
195
+ readonly wiring: () => KvMirrorWiring<AppModel>;
171
196
  }
172
197
  /** An application a mirror is declared over: its identity token, and its initial Model when it has one. */
173
198
  export interface MirrorApp<AppModel> {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;;YAwBY,UAAU,SAAS;;iBAGd;WACN,MAAM;;;iBA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,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;;;;;;;WAOhD,eAAe,oBAAoB,KAAK,QAAQ,gBAAgB,UAAU;;;YAIzE,kBAAkB;WACnB,MAAM;WACN,KAAK;;YAGJ,gBAAgB,UAAU,sBAAsB,OAC1D,UACA,kBAAkB;WAET,QAAQ,OAAO,UAAU,KAAK,QAAQ;;YAGrC,eAAe,YAAY,OACrC,UACA,gBACA,cAAc;WAEL,MAAM,OAAO,KAAK,UAAU,gBAAgB,cAAc;;;iBAIpD,SACf,UACA,cAAc,yBACd,sCACQ,OAAO,UAAU,OAAO,cAAc,eAAe;WACpD;;WAEA,SAAS,OAAO,UAAU,SAAS,mBAAmB;;;;;;WAMtD,cAAc,eAAe;;;iBAqCvB,UAAU;WAChB;WACA,UAAU;;qBAwLR;;;;;;;;;;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;;;;;;EAsCrC,KAAA,UAAU,OAAO,8BAAmB,KAClC,UAAU,UAAU,KAAG,QACpB,eAAe,GAAG,UACzB,SAAS,UAAU,IAAI,WAAW,IAAI;;EAkClC,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 CHANGED
@@ -1,6 +1,7 @@
1
- import { Effect, Result, Schema, Stream } from "effect";
1
+ import { Effect, Option, Result, Schema, Stream } from "effect";
2
2
  import { KeyValueStore } from "effect/unstable/persistence";
3
3
  import * as Navigation from "foldkit/navigation";
4
+ import * as Subscription from "foldkit/subscription";
4
5
  import { Projection } from "foldkit-surface";
5
6
  //#region src/index.ts
6
7
  /**
@@ -290,7 +291,7 @@ const make = (app, kind, store, config, throttle) => {
290
291
  owns: [],
291
292
  observes: fields.dependencies,
292
293
  messages: kind === "kv" ? ["MirrorRestored"] : [],
293
- requirements: []
294
+ metadata: []
294
295
  };
295
296
  const restore = {
296
297
  name: `Mirror.restore(${name})`,
@@ -334,6 +335,7 @@ const make = (app, kind, store, config, throttle) => {
334
335
  keysOfUrl
335
336
  };
336
337
  };
338
+ const brandEntries = (entries) => Subscription.make()(() => entries);
337
339
  const Mirror = {
338
340
  /** Mirror's Message cases, to spread into the application's union. */
339
341
  messages: mirrorMessageCases,
@@ -348,10 +350,20 @@ const Mirror = {
348
350
  url: (app, config) => {
349
351
  const owned = Object.keys(projectionOf(config.fields).schema.fields).map((field) => config.keys?.[field]?.key ?? field);
350
352
  const { mirror, keysOfUrl } = make(app, "url", MirrorStore.url(owned, config.location ?? "search"), config, config.throttle ?? "50 millis");
353
+ const reduce = (model, url) => mirror.fromKeys(model, keysOfUrl(url));
351
354
  return {
352
355
  ...mirror,
353
356
  kind: "url",
354
- reduce: (model, url) => mirror.fromKeys(model, keysOfUrl(url))
357
+ reduce,
358
+ wiring: (tag) => ({
359
+ key: `mirror:${mirror.name}`,
360
+ handles: [tag],
361
+ shared: [tag],
362
+ route: (model, message) => message._tag === tag ? Option.some({ model: reduce(model, message.url) }) : Option.none(),
363
+ onUrl: reduce,
364
+ subscriptions: brandEntries(mirror.subscriptions),
365
+ contract: mirror.contract
366
+ })
355
367
  };
356
368
  },
357
369
  /**
@@ -367,10 +379,23 @@ const Mirror = {
367
379
  ...config,
368
380
  name: config.name ?? config.key
369
381
  }, config.throttle ?? "250 millis");
382
+ const reduce = (model, message) => message.name === mirror.name ? mirror.restoreKeys(model, message.keys) : model;
370
383
  return {
371
384
  ...mirror,
372
385
  kind: "kv",
373
- reduce: (model, message) => message.name === mirror.name ? mirror.restoreKeys(model, message.keys) : model
386
+ reduce,
387
+ wiring: () => ({
388
+ key: `mirror:${mirror.name}`,
389
+ handles: ["MirrorRestored"],
390
+ shared: ["MirrorRestored"],
391
+ route: (model, message) => message._tag === "MirrorRestored" && message.name === mirror.name ? Option.some({ model: reduce(model, message) }) : Option.none(),
392
+ init: (model) => ({
393
+ model,
394
+ commands: [mirror.restore]
395
+ }),
396
+ subscriptions: brandEntries(mirror.subscriptions),
397
+ contract: mirror.contract
398
+ })
374
399
  };
375
400
  },
376
401
  /** The kernel form: a slice kept in any `MirrorStore`, read back with `fromKeys` or `restoreKeys`. */
@@ -1 +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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;GACb,KAAK,OAAO;GACZ,GAAI,OAAO,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,OAAO,MAAM;EAC9D,CAAC,GACD;GAAE,GAAG;GAAQ,MAAM,OAAO,QAAQ,OAAO;EAAI,GAC7C,OAAO,YAAY,YACrB;EACA,OAAO;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"}
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, Option, Result, Schema, Stream } from 'effect'\nimport { KeyValueStore } from 'effect/unstable/persistence'\nimport type { Command } from 'foldkit/command'\nimport * as Navigation from 'foldkit/navigation'\nimport * as Subscription from 'foldkit/subscription'\nimport type { EntryWithoutKeepAlive } from 'foldkit/subscription'\nimport type * as Update from 'foldkit/update'\nimport type { Url } from 'foldkit/url'\nimport {\n Projection,\n type Contract,\n type FieldRef,\n type Wiring,\n type WritableProjection,\n} 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 * How this mirror joins an assembly: it routes the application's URL Message\n * (a variant with a `url` field, tagged `tag`) into `reduce`, reads the URL at\n * startup, and brings its Subscriptions and contract. Several URL mirrors share\n * the URL Message.\n */\n readonly wiring: <const Tag extends string>(tag: Tag) => UrlMirrorWiring<AppModel, Tag>\n}\n\n/** The Message a URL mirror routes: the application's URL variant. */\nexport type UrlChangedMessage<Tag extends string> = {\n readonly _tag: Tag\n readonly url: Url\n}\n\nexport type UrlMirrorWiring<AppModel, Tag extends string> = Wiring<\n AppModel,\n UrlChangedMessage<Tag>\n> & {\n readonly onUrl: (model: AppModel, url: Url) => AppModel\n}\n\nexport type KvMirrorWiring<AppModel> = Wiring<\n AppModel,\n MirrorRestored,\n KeyValueStore.KeyValueStore\n> & {\n readonly init: Update.Step<AppModel, MirrorRestored, KeyValueStore.KeyValueStore>\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 * How this mirror joins an assembly: it routes its own `MirrorRestored` into\n * `reduce`, runs `restore` at startup, and brings its Subscriptions and\n * contract. Other key-value mirrors share the `MirrorRestored` tag.\n */\n readonly wiring: () => KvMirrorWiring<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 metadata: [],\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\n// A mirror's Subscription entries are unbranded so an application can spread them\n// into its own `Subscription.make`; wiring hands them over as a branded record.\nconst brandEntries = <AppModel, R>(\n entries: Readonly<Record<string, EntryWithoutKeepAlive<AppModel, never, MirrorDependencies, R>>>,\n): Subscription.Subscriptions<AppModel, never, R> =>\n Subscription.make<AppModel, never, R>()(() => entries)\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 const reduce = (model: SliceRoot<S>, url: Url | string) =>\n mirror.fromKeys(model, keysOfUrl(url))\n return {\n ...mirror,\n kind: 'url',\n reduce,\n wiring: tag => ({\n key: `mirror:${mirror.name}`,\n handles: [tag],\n shared: [tag],\n route: (model, message) =>\n message._tag === tag ? Option.some({ model: reduce(model, message.url) }) : Option.none(),\n onUrl: reduce,\n subscriptions: brandEntries(mirror.subscriptions),\n contract: mirror.contract,\n }),\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 const reduce = (model: SliceRoot<S>, message: MirrorRestored) =>\n message.name === mirror.name ? mirror.restoreKeys(model, message.keys) : model\n return {\n ...mirror,\n kind: 'kv',\n reduce,\n wiring: () => ({\n key: `mirror:${mirror.name}`,\n handles: ['MirrorRestored'],\n shared: ['MirrorRestored'],\n // Another mirror's restore is not this one's: `None` lets the next mirror take it.\n route: (model, message) =>\n message._tag === 'MirrorRestored' && message.name === mirror.name\n ? Option.some({ model: reduce(model, message) })\n : Option.none(),\n init: model => ({ model, commands: [mirror.restore] }),\n subscriptions: brandEntries(mirror.subscriptions),\n contract: mirror.contract,\n }),\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":";;;;;;;;;;;;;;;;;;AA6DA,MAAM,aAAa,SAAqE;CACtF,MAAM,SAAS,KAAK,QAAQ,GA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KAAK,KAAK,UAAU,OAAO,QAAQ,OAAO,YAAY,CAAC,CAAC,CAAC;AAC7D"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-mirror",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
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
5
  "keywords": [
6
6
  "foldkit",
@@ -38,7 +38,7 @@
38
38
  "LICENSE"
39
39
  ],
40
40
  "dependencies": {
41
- "foldkit-surface": "0.1.1"
41
+ "foldkit-surface": "0.3.0"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "effect": "^4.0.0-rc.112",
@@ -49,7 +49,8 @@
49
49
  "foldkit": "0.158.2",
50
50
  "jsdom": "26.1.0",
51
51
  "tsdown": "^0.23.0",
52
- "typescript": "^5.7.2"
52
+ "typescript": "5.9.3",
53
+ "foldkit-bundle": "0.2.0"
53
54
  },
54
55
  "scripts": {
55
56
  "build": "tsdown",