duratom 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,52 @@
1
+ import { StandardSchemaV1 } from '@standard-schema/spec';
2
+ import { DependencyList } from 'react';
3
+ import * as Y from 'yjs';
4
+ import { A as AtomOptions, P as Patch } from '../typed-atom-t7tvnXSS.js';
5
+ import { c as LiveSpec, d as Locator, M as MapPath, E as Exact } from '../shape-CMa7XFjy.js';
6
+ import 'jotai';
7
+
8
+ type SpecOptions<N extends Y.AbstractType<any>, T> = Omit<LiveSpec<N, T>, 'locate' | 'project'> & AtomOptions;
9
+ /**
10
+ * Hook form of `liveAtom`, taking a whole spec, such as a selector from `select`, or a function
11
+ * that builds it: `useLiveAtom(() => select..., [id])` builds it only when `deps` change, rather
12
+ * than on every render. The atom is rebuilt only when `deps` change, so list whatever the spec
13
+ * closes over (an id, say), as with useMemo. `deps` is required: a spec built inline from props
14
+ * would otherwise keep its first value. `options.docAtom` reads another doc than `docAtom`.
15
+ *
16
+ * @example
17
+ * const title = useLiveAtom(() => select.map('cards').child(id).get('title', ''), [id])
18
+ */
19
+ declare function useLiveAtom<N extends Y.AbstractType<any>, T>(spec: LiveSpec<N, T> | (() => LiveSpec<N, T>), deps: DependencyList, options?: AtomOptions): T;
20
+ /**
21
+ * Hook form of `liveAtom`. The atom is rebuilt only when `deps` change, so list whatever
22
+ * `locate` and `project` close over (an id, say), as with useMemo. `options.docAtom` reads
23
+ * another doc than `docAtom`.
24
+ *
25
+ * @example
26
+ * const title = useLiveAtom(
27
+ * (at) => at.map('cards').child(id),
28
+ * (card: Y.Map<unknown> | undefined) => String(card?.get('title') ?? ''),
29
+ * { keys: ['title'] },
30
+ * [id],
31
+ * )
32
+ */
33
+ declare function useLiveAtom<N extends Y.AbstractType<any>, T>(locate: LiveSpec<N, T>['locate'], project: LiveSpec<N, T>['project'], options?: SpecOptions<N, T>, deps?: DependencyList): T;
34
+ /**
35
+ * Hook form of `typedAtom`, returning `[result, set]` as `useAtom` does: `result` is `undefined`
36
+ * while the node is missing, `{ issues }` while it's invalid and `{ value }` otherwise, and
37
+ * `set(patch)` merges a patch and returns the schema's result. `locator` can be a function that
38
+ * builds it, so it's built only when `deps` change. The atom is rebuilt only when `deps` change,
39
+ * so list whatever the locator closes over (an id, say), as with useMemo; `schema` and `shape`
40
+ * are taken from the render that built it. `options.docAtom` reads another doc than `docAtom`.
41
+ *
42
+ * @example
43
+ * const Card = z.object({ title: z.string(), priority: z.enum(['low', 'high']) })
44
+ * const [card, setCard] = useTypedAtom(() => select.map('cards').child(id), Card, { title: 'text' }, [id])
45
+ * if (card && !card.issues) setCard({ priority: 'high' })
46
+ */
47
+ declare function useTypedAtom<Schema extends StandardSchemaV1, const S extends object>(locator: Locator<any> | MapPath<any> | (() => Locator<any> | MapPath<any>), schema: Schema, shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>, deps: DependencyList, options?: AtomOptions): [
48
+ result: StandardSchemaV1.Result<StandardSchemaV1.InferOutput<Schema>> | undefined,
49
+ set: (patch: Patch<StandardSchemaV1.InferOutput<Schema>>) => StandardSchemaV1.Result<StandardSchemaV1.InferOutput<Schema>>
50
+ ];
51
+
52
+ export { useLiveAtom, useTypedAtom };
@@ -0,0 +1,43 @@
1
+ import {
2
+ liveAtom,
3
+ typedAtom
4
+ } from "../chunk-URKFBGPT.js";
5
+ import "../chunk-7TXOG3GB.js";
6
+
7
+ // src/react/index.ts
8
+ import { useAtom, useAtomValue } from "jotai";
9
+ import { useMemo } from "react";
10
+ function useLiveAtom(...args) {
11
+ let spec;
12
+ let deps;
13
+ let docAtom;
14
+ if (typeof args[1] === "function") {
15
+ const { docAtom: own, ...rest } = args[2] ?? {};
16
+ spec = { locate: args[0], project: args[1], ...rest };
17
+ deps = args[3] ?? [];
18
+ docAtom = own;
19
+ } else {
20
+ spec = args[0];
21
+ deps = args[1];
22
+ docAtom = args[2]?.docAtom;
23
+ }
24
+ const a = useMemo(
25
+ () => liveAtom(typeof spec === "function" ? spec() : spec, { docAtom }),
26
+ // eslint-disable-next-line react-hooks/exhaustive-deps
27
+ [...deps, docAtom]
28
+ );
29
+ return useAtomValue(a);
30
+ }
31
+ function useTypedAtom(locator, schema, shape, deps, options) {
32
+ const docAtom = options?.docAtom;
33
+ const a = useMemo(
34
+ () => typedAtom(typeof locator === "function" ? locator() : locator, schema, shape, { docAtom }),
35
+ // eslint-disable-next-line react-hooks/exhaustive-deps
36
+ [...deps, docAtom]
37
+ );
38
+ return useAtom(a);
39
+ }
40
+ export {
41
+ useLiveAtom,
42
+ useTypedAtom
43
+ };
@@ -0,0 +1,390 @@
1
+ import * as Y from 'yjs';
2
+
3
+ type Step = {
4
+ root: string;
5
+ kind: 'map' | 'array';
6
+ } | {
7
+ key: string;
8
+ };
9
+ /**
10
+ * A path from a root type to the node a component cares about. It is a path
11
+ * rather than a bare function of the doc so the subscription can watch the key
12
+ * in each parent map: that is how a node that does not exist yet (a card that
13
+ * another tab has not created) or that gets deleted is noticed without
14
+ * observing the whole doc.
15
+ *
16
+ * @example
17
+ * const card = at.map('cards').child<Y.Map<unknown>>('card-1')
18
+ * card.resolve(doc) // the Y.Map, or undefined while it's missing
19
+ */
20
+ declare class Locator<N extends Y.AbstractType<any> = Y.AbstractType<any>> {
21
+ readonly steps: readonly Step[];
22
+ constructor(steps: readonly Step[]);
23
+ /** Descend into the Y type stored under `key` of a map. */
24
+ child<C extends Y.AbstractType<any> = Y.AbstractType<any>>(key: string): Locator<C>;
25
+ resolve(doc: Y.Doc): N | undefined;
26
+ }
27
+ /**
28
+ * Starts a `Locator` at a root type of the doc. `select` builds on it, and is what most code
29
+ * uses; `at` is for a `LiveSpec` written by hand.
30
+ *
31
+ * @example
32
+ * const spec = {
33
+ * locate: () => at.map('cards').child<Y.Map<unknown>>('card-1'),
34
+ * project: (card: Y.Map<unknown> | undefined) => card?.size ?? 0,
35
+ * }
36
+ */
37
+ declare const at: {
38
+ map: <V = unknown>(name: string) => Locator<Y.Map<V>>;
39
+ array: <V = unknown>(name: string) => Locator<Y.Array<V>>;
40
+ };
41
+ /** The type of `at`, which a `LiveSpec`'s `locate` gets. */
42
+ type At = typeof at;
43
+
44
+ /** Which changes to the located node count, for `observeLocated`, `live` and every atom. */
45
+ interface ObserveOptions {
46
+ /** Use `observeDeep` on the located node, so changes in nested types count. */
47
+ deep?: boolean;
48
+ /**
49
+ * Only count Y.Map changes to these keys. In deep mode, changes to the located
50
+ * node itself (children added or removed) always count.
51
+ */
52
+ keys?: readonly string[];
53
+ /** Return false to ignore a transaction by its origin. */
54
+ origin?: (origin: unknown) => boolean;
55
+ /**
56
+ * Return false to ignore a change by its event. It decides whether a
57
+ * transaction counts, not what is seen: in deep mode it is called with the
58
+ * transaction's events under the node until one is accepted, so it may not
59
+ * see them all. It runs while the observer runs, so `event.changes` and
60
+ * `event.path` (relative to the located node) can be read.
61
+ */
62
+ event?: (event: Y.YEvent<any>) => boolean;
63
+ }
64
+ /**
65
+ * Calls `onChange` after a transaction that may have changed what the locator
66
+ * points at. Watches the located node (and nothing else in the doc) plus, for
67
+ * each step of the path, that one key of the parent map. Returns an unsubscribe.
68
+ *
69
+ * @example
70
+ * const stop = observeLocated(doc, at.map('cards').child('card-1'), { deep: true }, () =>
71
+ * console.log('card-1 changed, or was created or deleted'),
72
+ * )
73
+ * stop()
74
+ */
75
+ declare function observeLocated(doc: Y.Doc, locator: Locator, options: ObserveOptions, onChange: () => void): () => void;
76
+
77
+ /**
78
+ * What `live` and `liveAtom` read: where the node is, how to turn it into a value, and when the
79
+ * value counts as changed. `select` builds one; write your own for anything it can't express.
80
+ */
81
+ interface LiveSpec<N extends Y.AbstractType<any>, T> extends ObserveOptions {
82
+ locate: (at: At) => Locator<N>;
83
+ /** Plain snapshot. `undefined` when the located node does not exist. */
84
+ project: (node: N | undefined) => T;
85
+ /** Whether two projections are the same; an equal result keeps the old reference and does not notify. Default: shallow. */
86
+ equals?: (a: T, b: T) => boolean;
87
+ }
88
+ /** A read-only value over one node of a doc, in the shape `useSyncExternalStore` takes. */
89
+ interface Live<T, N extends Y.AbstractType<any> = Y.AbstractType<any>> {
90
+ /** The current projection. Keeps the same reference until `equals` says it changed. */
91
+ get(): T;
92
+ /**
93
+ * Calls `listener(value, prev)` after a change, with the new and the previous
94
+ * projection. The first subscriber starts observing, the last one to leave stops.
95
+ */
96
+ subscribe(listener: (value: T, prev: T) => void): () => void;
97
+ /** The located node as it is now, `undefined` when it does not exist. */
98
+ resolve(): N | undefined;
99
+ /**
100
+ * Runs `fn` in one transaction of the doc with the located node as it is
101
+ * now, `undefined` when it does not exist, and returns what `fn` returns.
102
+ * The change comes back through `subscribe` like any other, so a write whose
103
+ * origin the `origin` filter rejects leaves `get()` behind the doc until the
104
+ * next accepted change.
105
+ */
106
+ write<R>(fn: (node: N | undefined, doc: Y.Doc) => R, origin?: unknown): R;
107
+ }
108
+ /**
109
+ * A live projection of one node of `doc`. While anything is subscribed it
110
+ * observes only the located node (see `observeLocated`), re-runs `project` on
111
+ * matching transactions and notifies only when `equals` says the result
112
+ * changed. With no subscribers nothing is observed and `get` projects the
113
+ * current doc on each call.
114
+ *
115
+ * A change skipped by the `origin` filter is not remembered while subscribed:
116
+ * the value catches up at the next accepted change. With no subscribers there
117
+ * is nothing to filter, so `get` shows every change made so far.
118
+ *
119
+ * @example
120
+ * const title = live(doc, select.map('cards').child('card-1').get('title', ''))
121
+ * const stop = title.subscribe((value, prev) => console.log(prev, '->', value))
122
+ * title.get() // the title now
123
+ * stop()
124
+ */
125
+ declare function live<N extends Y.AbstractType<any>, T>(doc: Y.Doc, spec: LiveSpec<N, T>): Live<T, N>;
126
+
127
+ /**
128
+ * A ready `LiveSpec`: path, observed keys, projection and equality in one
129
+ * plain object. Pass it to `live` or a binding's `liveAtom` as it is, or
130
+ * spread it to add an option (`{ ...selector, origin }`).
131
+ */
132
+ type Selector<T> = LiveSpec<any, T>;
133
+ /** Options of `project`: how to observe the node and compare projections. */
134
+ interface ProjectOptions<T> {
135
+ /** Default: `deepEqual`, since a custom projection usually builds a fresh value. */
136
+ equals?: (a: T, b: T) => boolean;
137
+ /** Default: true without `keys`, so a change anywhere under the node counts; false with `keys`. */
138
+ deep?: boolean;
139
+ keys?: readonly string[];
140
+ /** Return false to ignore a change by its event, as `ObserveOptions#event` says. */
141
+ event?: (event: Y.YEvent<any>) => boolean;
142
+ }
143
+ /**
144
+ * A projection packaged with how to observe and compare it, such as
145
+ * `reader(schema, shape)` from `@y-modern/schema`. Hand it to `project`, or
146
+ * spread it into a spec beside `locate`. It takes the node as stored, of any
147
+ * shared type, so it can report one of another kind than its path says, as
148
+ * `reader` does, rather than see it as missing.
149
+ */
150
+ interface Projection<T> extends ProjectOptions<T> {
151
+ project: (node: Y.AbstractType<any> | undefined) => T;
152
+ }
153
+ /**
154
+ * What a fallback guarantees: its kind, not its literal. `typeof` tells a string from a number,
155
+ * not `'open'` from `'garbage'`, so a literal fallback type widens to its primitive.
156
+ */
157
+ type Checked<D> = D extends string ? string : D extends number ? number : D extends boolean ? boolean : D;
158
+ /** A path to a node. End it with a projection to get a `Selector`. */
159
+ declare abstract class Path<N extends Y.AbstractType<any>> {
160
+ readonly locator: Locator<N>;
161
+ constructor(locator: Locator<N>);
162
+ protected abstract is(node: unknown): node is N;
163
+ protected selector<T>(project: (node: N | undefined) => T, options?: Omit<LiveSpec<any, T>, 'locate' | 'project'>): Selector<T>;
164
+ /** `toJSON()` of the node and everything under it, `empty` when missing. Observes deeply; compared deeply. */
165
+ protected json<E>(empty: E): Selector<E>;
166
+ /**
167
+ * Your own projection of the node, `undefined` when it is missing or of
168
+ * another kind. Observes deeply and compares with `deepEqual` unless
169
+ * `options` say otherwise; `keys` alone observes only those keys.
170
+ */
171
+ project<T>(project: (node: N | undefined) => T, options?: ProjectOptions<T>): Selector<T>;
172
+ /**
173
+ * A packaged projection, such as `reader(schema, shape)`, with its own
174
+ * observe options and `equals`. It gets the node as stored, whatever its kind.
175
+ */
176
+ project<T>(projection: Projection<T>): Selector<T>;
177
+ }
178
+ /**
179
+ * A path to a `Y.Map`. Descend with `child`, or end with a projection to get a `Selector`.
180
+ * `select.map(name)` starts one; `typedAtom` and `collection` take one as their locator.
181
+ *
182
+ * @example
183
+ * const card = select.map('cards').child('card-1')
184
+ * const title = liveAtom(card.text('title'))
185
+ * const flags = liveAtom(card.pick({ done: false, starred: false }))
186
+ */
187
+ declare class MapPath<V = unknown> extends Path<Y.Map<V>> {
188
+ protected is(node: unknown): node is Y.Map<V>;
189
+ /** Descend into the `Y.Map` stored under `key`. */
190
+ child<W = V extends Y.Map<infer X> ? X : unknown>(key: string): MapPath<W>;
191
+ /** Descend into the `Y.Array` stored under `key`. */
192
+ child<W = V extends Y.Array<infer X> ? X : unknown>(key: string, kind: 'array'): ArrayPath<W>;
193
+ /** Descend into the `Y.Array` under `key` that holds a y-utility `YKeyValue`. */
194
+ child<W = unknown>(key: string, kind: 'keyValue'): KeyValuePath<W>;
195
+ /** The value under `key`, or `undefined` when it or the map is missing. Observes only `key`. */
196
+ get(key: string): Selector<V | undefined>;
197
+ /**
198
+ * The value under `key` when it has the same type as `fallback` (`typeof`,
199
+ * with null, arrays, bytes and plain objects told apart), else `fallback`. So
200
+ * a missing map, a missing key and a value of the wrong type all read as
201
+ * `fallback`. An `undefined` fallback reads the value as `get(key)` does.
202
+ * A literal type widens to its primitive, since only the kind is checked; the
203
+ * items of an array and the fields of an object aren't checked. An array or
204
+ * object fallback is read frozen, a bytes fallback as a copy. Observes only `key`.
205
+ */
206
+ get<D>(key: string, fallback: D): Selector<undefined extends D ? V | Checked<D> : Checked<D>>;
207
+ /**
208
+ * An object with each key of `defaults`, read as `get(key, defaults[key])`
209
+ * reads it. Observes only those keys; compared shallowly.
210
+ */
211
+ pick<D extends Record<string, unknown>>(defaults: D): Selector<{
212
+ [K in keyof D]: Checked<D[K]>;
213
+ }>;
214
+ /**
215
+ * The string of the `Y.Text` under `key`, `''` when it is missing or not a
216
+ * `Y.Text` (a `Y.XmlText` included). Follows edits to the text.
217
+ */
218
+ text(key: string): Selector<string>;
219
+ /**
220
+ * The map's keys, sorted so every peer sees the same order. `[]` when the
221
+ * map is missing. Only a key added or deleted counts, not a value replaced.
222
+ * Its own `event` filter does that, so a spec that adds an `event` filter
223
+ * calls it from its own: `{ ...ids, event: (e) => ids.event!(e) && mine(e) }`.
224
+ */
225
+ keys(): Selector<string[]>;
226
+ /** `toJSON()` of the map and everything under it, `{}` when missing. Observes deeply; compared deeply. */
227
+ toJSON(): Selector<Record<string, unknown>>;
228
+ }
229
+ /**
230
+ * A path to a `Y.Array`. End it with a projection to get a `Selector`.
231
+ *
232
+ * @example
233
+ * const log = select.map('board').child('log', 'array')
234
+ * const entries = liveAtom(log.length())
235
+ */
236
+ declare class ArrayPath<V = unknown> extends Path<Y.Array<V>> {
237
+ protected is(node: unknown): node is Y.Array<V>;
238
+ /** The items as stored, `[]` when the array is missing. Compared shallowly. */
239
+ toArray(): Selector<V[]>;
240
+ /** The number of items, 0 when the array is missing. */
241
+ length(): Selector<number>;
242
+ /** `toJSON()` of the array and everything under it, `[]` when missing. Observes deeply; compared deeply. */
243
+ toJSON(): Selector<unknown[]>;
244
+ }
245
+ /**
246
+ * A path to a `Y.Array` that holds y-utility's `YKeyValue`: `{ key, val }` entries where the
247
+ * rightmost entry per key is the current one. duratom reads and writes the same entries as
248
+ * `YKeyValue`, so the two can share a doc. Items that aren't entries are skipped. End it with a
249
+ * projection, or pass `key(k)` to `typedAtom` for a validated, writable atom over one key.
250
+ *
251
+ * @example
252
+ * const master = select.keyValue('master')
253
+ * const tone = liveAtom(master.get('tone', 0))
254
+ * const toneAtom = typedAtom(master.key('tone'), z.number().min(-1).max(1))
255
+ */
256
+ declare class KeyValuePath<V = unknown> extends Path<Y.Array<unknown>> {
257
+ protected is(node: unknown): node is Y.Array<unknown>;
258
+ /** The entry for `key`, for `typedAtom(path.key(k), schema)`. */
259
+ key(key: string): KeyPath;
260
+ /**
261
+ * The current value of `key` as stored, `undefined` when it has no entry or the array is
262
+ * missing. Notifies only when an entry for `key` is added or deleted and the value changed.
263
+ */
264
+ get(key: string): Selector<V | undefined>;
265
+ /**
266
+ * The current value of `key` when it has `fallback`'s kind, else `fallback`, as `MapPath#get`
267
+ * checks it. Notifies only when an entry for `key` changes the value.
268
+ */
269
+ get<D>(key: string, fallback: D): Selector<undefined extends D ? V | Checked<D> : Checked<D>>;
270
+ /** The keys that have an entry, sorted so every peer sees the same order. `[]` when missing. */
271
+ keys(): Selector<string[]>;
272
+ /** The current value of every key, as stored. `{}` when missing. Compared deeply. */
273
+ toJSON(): Selector<Record<string, V>>;
274
+ }
275
+ /**
276
+ * One key of a key-value array (see `KeyValuePath`): `select.keyValue(name).key(k)`. `typedAtom`
277
+ * takes one for a validated atom over that key's current value.
278
+ *
279
+ * @example
280
+ * const tone = select.keyValue('master').key('tone')
281
+ * const toneAtom = typedAtom(tone, z.number())
282
+ */
283
+ declare class KeyPath {
284
+ /** Where the key-value array is. */
285
+ readonly locator: Locator<Y.Array<unknown>>;
286
+ readonly key: string;
287
+ constructor(
288
+ /** Where the key-value array is. */
289
+ locator: Locator<Y.Array<unknown>>, key: string);
290
+ }
291
+ /**
292
+ * Builds selectors: `select.map('cards').child(id).get('title', '')`. Starts
293
+ * at a root type of the doc, like `at`.
294
+ *
295
+ * @example
296
+ * const title = liveAtom(select.map('cards').child('card-1').get('title', ''))
297
+ * const ids = liveAtom(select.map('cards').keys())
298
+ * const order = liveAtom(select.array<string>('order').toArray())
299
+ * const tone = liveAtom(select.keyValue('master').get('tone', 0))
300
+ */
301
+ declare const select: {
302
+ map: <V = unknown>(name: string) => MapPath<V>;
303
+ array: <V = unknown>(name: string) => ArrayPath<V>;
304
+ /** A root `Y.Array` that holds a y-utility `YKeyValue`. */
305
+ keyValue: <V = unknown>(name: string) => KeyValuePath<V>;
306
+ };
307
+
308
+ /**
309
+ * Which fields of a node are Shared fields, and of what kind. Every key it doesn't mention is a
310
+ * Plain field. Keys are constrained to the fields of `T`, the schema's output, in any member of a
311
+ * union, and each kind to fields its read value can fill.
312
+ */
313
+ type Shape<T> = {
314
+ readonly [K in KeyOf<T>]?: KindOf<FieldOf<T, K>>;
315
+ };
316
+ /** A `map(shape)` field: a `Y.Map` with the fixed keys `shape` describes. */
317
+ interface MapKind<S> {
318
+ readonly kind: 'map';
319
+ readonly shape: S;
320
+ }
321
+ /** A `record(itemShape)` field: a `Y.Map` of item `Y.Map`s, each following `itemShape`. */
322
+ interface RecordKind<S> {
323
+ readonly kind: 'record';
324
+ readonly shape: S;
325
+ }
326
+ /** An `array()` field: a Shared array of plain values. */
327
+ interface ArrayKind {
328
+ readonly kind: 'array';
329
+ }
330
+ /** Any field object, the form every shape and nested shape takes. */
331
+ type AnyShape = {
332
+ readonly [key: string]: Kind | undefined;
333
+ };
334
+ type Kind = 'text' | 'xml' | MapKind<AnyShape> | RecordKind<AnyShape> | ArrayKind;
335
+ /**
336
+ * A nested `Y.Map` with the fixed keys `shape` describes, read as a plain object.
337
+ *
338
+ * @example
339
+ * const Card = z.object({ title: z.string(), meta: z.object({ note: z.string() }) })
340
+ * const card = typedAtom(select.map('cards').child('card-1'), Card, { meta: map({ note: 'text' }) })
341
+ */
342
+ declare const map: <const S extends AnyShape>(shape: S) => MapKind<S>;
343
+ /**
344
+ * A `Y.Map` with dynamic keys whose every value is a `Y.Map` following `itemShape`.
345
+ *
346
+ * @example
347
+ * const Board = z.object({ cards: z.record(z.string(), z.object({ title: z.string() })) })
348
+ * const board = typedAtom(select.map('boards').child('b1'), Board, { cards: record({ title: 'text' }) })
349
+ */
350
+ declare const record: <const S extends AnyShape>(itemShape: S) => RecordKind<S>;
351
+ /**
352
+ * A `Y.Array` of plain values, read as a plain array. Writing it changes only the items that
353
+ * differ, so items peers add at once are all kept.
354
+ *
355
+ * @example
356
+ * const Card = z.object({ tags: z.array(z.string()) })
357
+ * const card = typedAtom(select.map('cards').child('card-1'), Card, { tags: array() })
358
+ */
359
+ declare const array: () => ArrayKind;
360
+ /** The kinds a field of type `F` can be declared as. */
361
+ type KindOf<F> = (string extends F ? 'text' : never) | (Y.XmlFragment extends F ? 'xml' : never) | ([ObjectOf<F>] extends [never] ? never : MapKind<Shape<ObjectOf<F>>>) | ([ItemOf<F>] extends [never] ? never : RecordKind<Shape<ItemOf<F>>>) | (unknown extends F ? ArrayKind : [Extract<F, readonly unknown[]>] extends [never] ? never : ArrayKind);
362
+ /** The plain-object members of `F`, which a `map` or `record` field reads as. */
363
+ type ObjectOf<F> = unknown extends F ? Record<string, unknown> : Exclude<Extract<F, object>, readonly unknown[] | Y.AbstractType<any> | Uint8Array | ((...args: never) => unknown) | Date | RegExp | ReadonlyMap<any, any> | ReadonlySet<any> | WeakMap<any, any> | WeakSet<any> | PromiseLike<unknown>>;
364
+ /** The plain-object items of the plain-object members of `F`, read as a `record`. */
365
+ type ItemOf<F> = ObjectOf<ObjectOf<F>[keyof ObjectOf<F>]>;
366
+ /** The keys of every member of a union, not only the keys they share. `unknown` has any key. */
367
+ type KeyOf<T> = unknown extends T ? string : T extends unknown ? keyof T : never;
368
+ /** The type of field `K` across the members of `T` that have it. */
369
+ type FieldOf<T, K> = unknown extends T ? unknown : T extends unknown ? K extends keyof T ? T[K] : never : never;
370
+ /**
371
+ * Rejects keys of `S` that `T` doesn't have, at every depth of nested `map` and `record` shapes,
372
+ * also when the shape is declared apart from the call. `S` is constrained to `object` only:
373
+ * against the all-optional `Shape<T>`, a shape with no key of `T` wouldn't infer as itself, and
374
+ * its typo keys would go unchecked.
375
+ */
376
+ type Exact<S, T> = S & Shape<T> & {
377
+ readonly [K in keyof S]: K extends KeyOf<T> ? ExactKind<S[K], FieldOf<T, K>> : never;
378
+ };
379
+ type ExactKind<V, F> = V extends MapKind<infer N> ? MapKind<Exact<N, ObjectOf<F>>> : V extends RecordKind<infer N> ? RecordKind<Exact<N, ItemOf<F>>> : V;
380
+ /**
381
+ * Whether `value` is a `Y.Map` that duratom reads as one: a `Y.XmlHook` extends `Y.Map`, but peers
382
+ * decode it as its own type, so it isn't.
383
+ *
384
+ * @example
385
+ * const stored = doc.getMap('todos').get(id)
386
+ * if (isMap(stored)) console.log(stored.get('title'))
387
+ */
388
+ declare const isMap: (value: unknown) => value is Y.Map<unknown>;
389
+
390
+ export { ArrayPath as A, type Exact as E, KeyPath as K, type Live as L, MapPath as M, type ObserveOptions as O, type ProjectOptions as P, type RecordKind as R, type Selector as S, type At as a, KeyValuePath as b, type LiveSpec as c, Locator as d, type Projection as e, at as f, type ArrayKind as g, type MapKind as h, type Shape as i, array as j, isMap as k, live as l, map as m, observeLocated as o, record as r, select as s };
@@ -0,0 +1,127 @@
1
+ import { StandardSchemaV1 } from '@standard-schema/spec';
2
+ import { Atom, PrimitiveAtom, WritableAtom } from 'jotai';
3
+ import { c as LiveSpec, d as Locator, M as MapPath, E as Exact, K as KeyPath } from './shape-CMa7XFjy.js';
4
+ import * as Y from 'yjs';
5
+
6
+ /**
7
+ * Holds the live Y.Doc handle that atoms read by default. Set once per store; the doc never
8
+ * changes, so this atom never notifies.
9
+ *
10
+ * @example
11
+ * const store = createStore()
12
+ * store.set(docAtom, new Y.Doc())
13
+ */
14
+ declare const docAtom: PrimitiveAtom<Y.Doc | null> & {
15
+ init: Y.Doc | null;
16
+ };
17
+ /** Options every duratom atom takes. */
18
+ interface AtomOptions {
19
+ /**
20
+ * The atom holding the doc this atom reads, for apps with several docs. Defaults to
21
+ * `docAtom`.
22
+ *
23
+ * @example
24
+ * const boardDocAtom = atom<Y.Doc | null>(null)
25
+ * const title = liveAtom(select.map('meta').get('title', ''), { docAtom: boardDocAtom })
26
+ */
27
+ docAtom?: Atom<Y.Doc | null | undefined>;
28
+ }
29
+ /**
30
+ * A read-only atom over one node of the doc in `docAtom` (or the doc atom given in `options`),
31
+ * built on `live` from `duratom/core`. While something is subscribed it observes only the
32
+ * located node, re-runs `project` on matching transactions and updates only when `equals` says
33
+ * the result changed. Unsubscribes when the last subscriber goes away.
34
+ *
35
+ * Read while nothing is subscribed (`store.get` outside a component), it can be stale: Jotai
36
+ * keeps an unmounted atom's value until one of its atom dependencies changes, and a doc edit
37
+ * isn't one. It projects the doc on its first read and again whenever it is mounted, but not
38
+ * after later doc edits made while unmounted. Subscribe (`useAtomValue`, `store.sub`) to follow
39
+ * the doc; outside Jotai, `live` from `duratom/core` reads the doc as it is now.
40
+ *
41
+ * A change skipped by the `origin` filter is not remembered: the value catches up at the next
42
+ * accepted change.
43
+ *
44
+ * @example
45
+ * const titleAtom = liveAtom(select.map('cards').child('card-1').get('title', ''))
46
+ */
47
+ declare function liveAtom<N extends Y.AbstractType<any>, T>(spec: LiveSpec<N, T>, options?: AtomOptions): Atom<T>;
48
+
49
+ /**
50
+ * What a typed atom's setter takes: a patch of the fields to change, or a function of the node's
51
+ * value as it is in the doc at write time (`undefined` while it has no valid value) returning one.
52
+ */
53
+ type Patch<T> = Partial<T> | ((prev: T | undefined) => Partial<T>);
54
+ /**
55
+ * A Jotai atom over one `Y.Map` of the doc, read through a schema. It reads as `undefined` while
56
+ * the node is missing, `{ issues }` while it doesn't satisfy the schema, and `{ value }`
57
+ * otherwise. Setting it merges a patch and returns the schema's result.
58
+ */
59
+ type TypedAtom<T> = WritableAtom<StandardSchemaV1.Result<T> | undefined, [
60
+ patch: Patch<T>
61
+ ], StandardSchemaV1.Result<T>>;
62
+ /**
63
+ * What a key atom's setter takes: the whole new value, or a function of the key's value as it is
64
+ * in the doc at write time (`undefined` while it has no valid value) returning one.
65
+ */
66
+ type KeyUpdate<T> = T | ((prev: T | undefined) => T);
67
+ /**
68
+ * A Jotai atom over one key of a key-value array (y-utility's `YKeyValue`), read through a schema.
69
+ * It reads as `undefined` while the key has no entry, `{ issues }` while its current value doesn't
70
+ * satisfy the schema, and `{ value }` otherwise. Setting it validates and writes the whole value,
71
+ * and returns the schema's result.
72
+ */
73
+ type TypedKeyAtom<T> = WritableAtom<StandardSchemaV1.Result<T> | undefined, [
74
+ update: KeyUpdate<T>
75
+ ], StandardSchemaV1.Result<T>>;
76
+ /**
77
+ * A typed, writable atom over the `Y.Map` at `locator`, read through `schema` and `shape`: a
78
+ * `liveAtom` over `reader(schema, shape)` with a setter. It observes only that node, skips edits
79
+ * inside its `'xml'` fields, and re-renders only when the result changes. Like a `liveAtom`, it
80
+ * can read stale while nothing is subscribed, except right after its own setter wrote.
81
+ *
82
+ * Setting it reads the node as it is in the doc at write time, not the atom's last value, and
83
+ * merges the patch into it: fields the patch leaves out, and keys the schema doesn't know, are
84
+ * written back unchanged, so `write` changes only the patched fields and a peer's concurrent
85
+ * edit to another field survives. A function patch gets that fresh value as `prev`.
86
+ *
87
+ * Invalid data never throws: the setter returns the schema's result, and `{ issues }` changes
88
+ * nothing.
89
+ *
90
+ * While the node has no valid value, the patch is the whole value and a function patch gets
91
+ * `undefined` as `prev`. On a missing node a valid value creates the `Y.Map` in its parent; when
92
+ * the parent map is missing too, nothing is created and the result holds one issue saying so. On
93
+ * an invalid node a valid value replaces what the schema rejected, keeping keys neither the shape
94
+ * nor the value names: that is how a node a peer broke is repaired. A shared type of another kind
95
+ * where the map belongs reads as issues, and only writing its parent can replace it.
96
+ *
97
+ * @example
98
+ * const Card = z.object({ title: z.string(), priority: z.enum(['low', 'high']) })
99
+ * const cardAtom = typedAtom(select.map('cards').child('card-1'), Card, { title: 'text' })
100
+ *
101
+ * store.get(cardAtom) // undefined, { issues } or { value }
102
+ * store.set(cardAtom, { title: 'Ship it', priority: 'low' }) // creates the card
103
+ * store.set(cardAtom, { priority: 'high' }) // changes only priority
104
+ */
105
+ declare function typedAtom<Schema extends StandardSchemaV1, const S extends object>(locator: Locator<any> | MapPath<any>, schema: Schema, shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>, options?: AtomOptions): TypedAtom<StandardSchemaV1.InferOutput<Schema>>;
106
+ /**
107
+ * A typed, writable atom over one key of a key-value array (y-utility's `YKeyValue`), read
108
+ * through `schema`: `select.keyValue(name).key(k)`. It reads the key's current entry (the
109
+ * rightmost) as `undefined`, `{ issues }` or `{ value }`, and re-renders only when an entry for
110
+ * that key changes its result, not when other keys change or a stale entry is cleaned up. A
111
+ * current value the schema rejects reads as `{ issues }`; it does not fall back to an older entry.
112
+ *
113
+ * Setting it validates the whole value, then writes it as `YKeyValue#set` does: pushes
114
+ * `{ key, val }` and deletes the key's older entries, so a `YKeyValue` on the same doc reads it.
115
+ * A function gets the key's valid value at write time, or `undefined`. `{ issues }` changes
116
+ * nothing, and so does a missing array. Values are plain: a `YKeyValue` holds no shared types.
117
+ *
118
+ * @example
119
+ * const toneAtom = typedAtom(select.keyValue('master').key('tone'), z.number().min(-1).max(1))
120
+ *
121
+ * store.get(toneAtom) // undefined, { issues } or { value }
122
+ * store.set(toneAtom, -0.6)
123
+ * store.set(toneAtom, (prev) => Math.min(1, (prev ?? 0) + 0.1))
124
+ */
125
+ declare function typedAtom<Schema extends StandardSchemaV1>(key: KeyPath, schema: Schema, options?: AtomOptions): TypedKeyAtom<StandardSchemaV1.InferOutput<Schema>>;
126
+
127
+ export { type AtomOptions as A, type KeyUpdate as K, type Patch as P, type TypedAtom as T, type TypedKeyAtom as a, docAtom as d, liveAtom as l, typedAtom as t };