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,165 @@
1
+ import {
2
+ KeyPath,
3
+ Locator,
4
+ MapPath,
5
+ create,
6
+ isMap,
7
+ keyReader,
8
+ live,
9
+ read,
10
+ reader,
11
+ write,
12
+ writeKey
13
+ } from "./chunk-7TXOG3GB.js";
14
+
15
+ // src/atoms/live-atom.ts
16
+ import { atom } from "jotai";
17
+ var docAtom = atom(null);
18
+ function readDoc(get, options) {
19
+ const holder = options.docAtom ?? docAtom;
20
+ const doc = get(holder);
21
+ if (!doc) {
22
+ throw new Error(
23
+ holder === docAtom ? "docAtom has not been set on this store" : "The doc atom passed to this atom holds no doc on this store"
24
+ );
25
+ }
26
+ return doc;
27
+ }
28
+ function liveAtom(spec, options = {}) {
29
+ return versionedLiveAtom(spec, options).live;
30
+ }
31
+ function versionedLiveAtom(spec, options, refreshers = []) {
32
+ const version = atom(0);
33
+ const getDoc = (get) => readDoc(get, options);
34
+ const sources = /* @__PURE__ */ new WeakMap();
35
+ const sourceFor = (doc) => {
36
+ let source = sources.get(doc);
37
+ if (!source) sources.set(doc, source = live(doc, spec));
38
+ return source;
39
+ };
40
+ const snapshot = atom(null);
41
+ const live2 = atom(
42
+ (get) => {
43
+ get(version);
44
+ for (const refresher of refreshers) get(refresher);
45
+ const snap = get(snapshot);
46
+ return snap ? snap.value : sourceFor(getDoc(get)).get();
47
+ },
48
+ (get, set, message) => {
49
+ if (message.type === "stop") return set(snapshot, null);
50
+ const source = sourceFor(getDoc(get));
51
+ message.register(source.subscribe((value) => set(snapshot, { value })));
52
+ set(snapshot, { value: source.get() });
53
+ }
54
+ );
55
+ live2.onMount = (send) => {
56
+ let stop;
57
+ send({ type: "start", register: (fn) => stop = fn });
58
+ return () => {
59
+ stop?.();
60
+ send({ type: "stop" });
61
+ };
62
+ };
63
+ return { live: live2, version };
64
+ }
65
+
66
+ // src/atoms/typed-atom.ts
67
+ import { atom as atom2 } from "jotai";
68
+ import * as Y from "yjs";
69
+ function typedAtom(locator, schema, shapeOrOptions, options = {}) {
70
+ if (locator instanceof KeyPath)
71
+ return typedKeyAtom(locator, schema, shapeOrOptions ?? {});
72
+ return refreshedTypedAtom(locator, schema, shapeOrOptions ?? {}, options, []);
73
+ }
74
+ var missingArray = "The key-value Y.Array is missing";
75
+ function typedKeyAtom(path, schema, options) {
76
+ const { locator, key } = path;
77
+ const { live: live2, version } = versionedLiveAtom(
78
+ { locate: () => locator, ...keyReader(schema, key) },
79
+ options
80
+ );
81
+ return atom2(
82
+ (get) => get(live2),
83
+ (get, set, update) => {
84
+ const doc = readDoc(get, options);
85
+ let result;
86
+ doc.transact(() => {
87
+ const array = locator.resolve(doc);
88
+ if (!(array instanceof Y.Array))
89
+ return void (result = { issues: [{ message: missingArray }] });
90
+ let value = update;
91
+ if (typeof update === "function") {
92
+ const current = keyReader(schema, key).project(array);
93
+ value = update(
94
+ current && !current.issues ? current.value : void 0
95
+ );
96
+ }
97
+ result = writeKey(schema, array, key, value);
98
+ });
99
+ if (!result.issues) set(version, (n) => n + 1);
100
+ return result;
101
+ }
102
+ );
103
+ }
104
+ function refreshedTypedAtom(locator, schema, shape, options, refreshers) {
105
+ const located = locator instanceof MapPath ? locator.locator : locator;
106
+ const last = located.steps.at(-1);
107
+ const parent = last && "key" in last ? { locator: new Locator(located.steps.slice(0, -1)), key: last.key } : void 0;
108
+ const { live: live2, version } = versionedLiveAtom(
109
+ { locate: () => located, ...reader(schema, shape) },
110
+ options,
111
+ refreshers
112
+ );
113
+ const update = (doc, patch) => {
114
+ const node = located.resolve(doc);
115
+ if (node === void 0) {
116
+ const map = parent?.locator.resolve(doc);
117
+ if (!parent || !isMap(map)) return { issues: [{ message: missingParent }] };
118
+ const whole = typeof patch === "function" ? patch(void 0) : patch;
119
+ return create(schema, shape, map, parent.key, whole);
120
+ }
121
+ if (!isMap(node)) return read(schema, shape, node);
122
+ const current = read(schema, shape, node);
123
+ const prev = current.issues ? void 0 : current.value;
124
+ const changes = typeof patch === "function" ? patch(prev) : patch;
125
+ const merged = {
126
+ ...unknownKeys(node, prev ?? changes, shape),
127
+ ...prev,
128
+ ...changes
129
+ };
130
+ return write(schema, shape, node, merged);
131
+ };
132
+ return atom2(
133
+ (get) => get(live2),
134
+ (get, set, patch) => {
135
+ const doc = readDoc(get, options);
136
+ let result;
137
+ doc.transact(() => result = update(doc, patch));
138
+ if (!result.issues) set(version, (n) => n + 1);
139
+ return result;
140
+ }
141
+ );
142
+ }
143
+ var missingParent = "The node is missing, and so is the Y.Map it would be created in";
144
+ function unknownKeys(node, value, shape) {
145
+ const out = {};
146
+ const known = (key) => Object.hasOwn(shape, key) || value !== null && typeof value === "object" && Object.hasOwn(value, key);
147
+ for (const [key, stored] of node.entries())
148
+ if (!known(key))
149
+ Object.defineProperty(out, key, {
150
+ value: stored,
151
+ enumerable: true,
152
+ writable: true,
153
+ configurable: true
154
+ });
155
+ return out;
156
+ }
157
+
158
+ export {
159
+ docAtom,
160
+ readDoc,
161
+ liveAtom,
162
+ versionedLiveAtom,
163
+ typedAtom,
164
+ refreshedTypedAtom
165
+ };
@@ -0,0 +1,150 @@
1
+ export { d as deepEqual, s as shallowEqual } from '../equality-AjtpnVrF.js';
2
+ import { E as Exact } from '../shape-CMa7XFjy.js';
3
+ export { A as ArrayPath, a as At, K as KeyPath, b as KeyValuePath, L as Live, c as LiveSpec, d as Locator, M as MapPath, O as ObserveOptions, P as ProjectOptions, e as Projection, S as Selector, f as at, l as live, o as observeLocated, s as select } from '../shape-CMa7XFjy.js';
4
+ import { StandardSchemaV1 } from '@standard-schema/spec';
5
+ import * as Y from 'yjs';
6
+
7
+ /**
8
+ * Projects a located `Y.Map` following `shape` and validates it with `schema`, returning the
9
+ * schema's own result. An absent node returns `undefined` without validating, and a node with a
10
+ * shape mismatch, or a shared type that isn't a `Y.Map`, returns the layer's own issues without
11
+ * validating.
12
+ *
13
+ * @example
14
+ * const Todo = z.object({ title: z.string(), done: z.boolean() })
15
+ * const result = read(Todo, { title: 'text' }, doc.getMap('todos').get(id) as Y.Map<unknown>)
16
+ * if (result?.issues) console.warn(result.issues)
17
+ * else if (result) console.log(result.value.title)
18
+ */
19
+ declare function read<Schema extends StandardSchemaV1, const S extends object>(schema: Schema, shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>, node: Y.AbstractType<any> | undefined): StandardSchemaV1.Result<StandardSchemaV1.InferOutput<Schema>> | undefined;
20
+ /**
21
+ * `read` packaged as a store binding's projection: `project` reads a located node through
22
+ * `schema` and `shape`, `deep` observes every change under it, `event` skips edits inside an
23
+ * `'xml'` field, which a read returns as the fragment itself, and `equals` compares two results
24
+ * deeply, since each read returns a fresh tree. It has the shape `project` of a
25
+ * `select` selector and a `liveAtom` spec take, so the schema layer and the observation core
26
+ * stay independent of each other.
27
+ */
28
+ interface Reader<T> {
29
+ project: (node: Y.AbstractType<any> | undefined) => StandardSchemaV1.Result<T> | undefined;
30
+ deep: true;
31
+ event: (event: Y.YEvent<any>) => boolean;
32
+ equals: (a: StandardSchemaV1.Result<T> | undefined, b: StandardSchemaV1.Result<T> | undefined) => boolean;
33
+ }
34
+ /**
35
+ * `read(schema, shape, node)` as a `Reader`, for `select...project(reader(schema, shape))`.
36
+ * `typedAtom` reads through it; use it for a read-only typed value outside Jotai.
37
+ *
38
+ * @example
39
+ * const Todo = z.object({ title: z.string(), done: z.boolean() })
40
+ * const todo = live(doc, select.map('todos').child(id).project(reader(Todo, { title: 'text' })))
41
+ * todo.subscribe((result) => console.log(result?.issues ?? result?.value))
42
+ */
43
+ declare function reader<Schema extends StandardSchemaV1, const S extends object>(schema: Schema, shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>): Reader<StandardSchemaV1.InferOutput<Schema>>;
44
+
45
+ /**
46
+ * Validates `value` with `schema` and, if it's valid, merges it into the located `Y.Map` so only
47
+ * the differences change. Returns the schema's own result; an invalid value changes nothing.
48
+ * Fields the value lacks are deleted, so pass the whole value; a typed atom merges a patch first.
49
+ *
50
+ * @example
51
+ * const Todo = z.object({ title: z.string(), done: z.boolean() })
52
+ * const node = doc.getMap('todos').get(id) as Y.Map<unknown>
53
+ * const result = write(Todo, { title: 'text' }, node, { title: 'Ship it', done: true })
54
+ * if (result.issues) console.warn(result.issues) // the doc is unchanged
55
+ */
56
+ declare function write<Schema extends StandardSchemaV1, const S extends object>(schema: Schema, shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>, node: Y.Map<unknown>, value: StandardSchemaV1.InferOutput<Schema>): StandardSchemaV1.Result<StandardSchemaV1.InferOutput<Schema>>;
57
+ /**
58
+ * Validates `value` with `schema` and, if it's valid, stores it as a new `Y.Map` under `key` of
59
+ * `parent`, replacing whatever was stored there. Returns the schema's own result; an invalid
60
+ * value creates nothing, and a value the shape can't store throws before anything is created.
61
+ *
62
+ * @example
63
+ * const Todo = z.object({ title: z.string(), done: z.boolean() })
64
+ * create(Todo, { title: 'text' }, doc.getMap('todos'), 'todo-1', { title: 'Buy milk', done: false })
65
+ */
66
+ declare function create<Schema extends StandardSchemaV1, const S extends object>(schema: Schema, shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>, parent: Y.Map<unknown>, key: string, value: StandardSchemaV1.InferOutput<Schema>): StandardSchemaV1.Result<StandardSchemaV1.InferOutput<Schema>>;
67
+
68
+ /**
69
+ * Thrown by `read` and `write` when the schema's `~standard.validate` returns a Promise. The layer
70
+ * validates synchronously only, so an async schema is a configuration error, not bad data.
71
+ *
72
+ * @example
73
+ * const Slow = z.object({ title: z.string() }).refine(async () => true)
74
+ * try {
75
+ * store.set(typedAtom(select.map('cards').child('c1'), Slow, {}), { title: 'Hi' })
76
+ * } catch (error) {
77
+ * if (error instanceof AsyncValidationUnsupportedError) console.error(error.vendor) // 'zod'
78
+ * }
79
+ */
80
+ declare class AsyncValidationUnsupportedError extends Error {
81
+ readonly vendor: string;
82
+ constructor(vendor: string);
83
+ }
84
+ /**
85
+ * Thrown by `write` when a plain field or `array()` item holds a value Yjs can't store faithfully: anything but
86
+ * JSON values, `undefined` and `Uint8Array` bytes, a cycle, a `__proto__` key, or a `constructor`
87
+ * key on the field's own object. The schema accepted it, so it's a schema that's too loose, not bad
88
+ * data. Nothing is written.
89
+ *
90
+ * @example
91
+ * const Event = z.object({ at: z.date() }) // a Date syncs as {}, so it can't be stored
92
+ * try {
93
+ * store.set(typedAtom(select.map('events').child('e1'), Event, {}), { at: new Date() })
94
+ * } catch (error) {
95
+ * if (error instanceof UnsupportedValueError) console.error(error.path) // ['at']
96
+ * }
97
+ */
98
+ declare class UnsupportedValueError extends Error {
99
+ /** Where the value sits in the written value, starting at the field's key. */
100
+ readonly path: readonly PropertyKey[];
101
+ constructor(path: readonly PropertyKey[]);
102
+ }
103
+
104
+ type Result<Schema extends StandardSchemaV1> = StandardSchemaV1.Result<StandardSchemaV1.InferOutput<Schema>>;
105
+ /**
106
+ * Reads the current value of `key` in a key-value array (y-utility's `YKeyValue`: the rightmost
107
+ * `{ key, val }` entry per key wins) and validates it with `schema`, returning the schema's own
108
+ * result. A missing array or a key with no entry returns `undefined` without validating. A value
109
+ * holding a shared type returns the layer's own issue without validating, since a `YKeyValue`
110
+ * holds plain values only.
111
+ *
112
+ * A current value the schema rejects reads as `{ issues }`, like an invalid map field: it does not
113
+ * fall back to an older entry, which a `YKeyValue` deletes anyway. Writing a valid value repairs it.
114
+ *
115
+ * @example
116
+ * const result = readKey(z.number(), doc.getArray('master'), 'tone')
117
+ * if (result && !result.issues) console.log(result.value)
118
+ */
119
+ declare function readKey<Schema extends StandardSchemaV1>(schema: Schema, array: Y.AbstractType<any> | undefined, key: string): Result<Schema> | undefined;
120
+ /**
121
+ * Validates `value` with `schema` and, if it's valid, sets `key` of the key-value array as
122
+ * `YKeyValue#set` does: pushes `{ key, val }` to its end and deletes every older entry for `key`,
123
+ * in one transaction. Returns the schema's own result; an invalid value changes nothing, and so
124
+ * does a value equal to the current one. Throws `UnsupportedValueError` for a value Yjs can't store
125
+ * as written, since the schema accepted it.
126
+ *
127
+ * @example
128
+ * const result = writeKey(z.number().min(-1).max(1), doc.getArray('master'), 'tone', -0.6)
129
+ * if (result.issues) console.warn(result.issues) // the doc is unchanged
130
+ */
131
+ declare function writeKey<Schema extends StandardSchemaV1>(schema: Schema, array: Y.Array<any>, key: string, value: StandardSchemaV1.InferOutput<Schema>): Result<Schema>;
132
+ /**
133
+ * `readKey(schema, node, key)` packaged as a projection for `select.keyValue(name).project(...)`:
134
+ * it counts only changes that add or delete an entry for `key`, and compares results deeply.
135
+ * `typedAtom(path.key(k), schema)` reads through it.
136
+ *
137
+ * @example
138
+ * const tone = live(doc, select.keyValue('master').project(keyReader(z.number(), 'tone')))
139
+ * tone.subscribe((result) => console.log(result?.issues ?? result?.value))
140
+ */
141
+ declare function keyReader<Schema extends StandardSchemaV1>(schema: Schema, key: string): KeyReader<StandardSchemaV1.InferOutput<Schema>>;
142
+ /** What `keyReader` returns: a projection of one key's validated value, with its event filter. */
143
+ interface KeyReader<T> {
144
+ project: (node: Y.AbstractType<any> | undefined) => StandardSchemaV1.Result<T> | undefined;
145
+ deep: false;
146
+ event: (event: Y.YEvent<any>) => boolean;
147
+ equals: (a: StandardSchemaV1.Result<T> | undefined, b: StandardSchemaV1.Result<T> | undefined) => boolean;
148
+ }
149
+
150
+ export { AsyncValidationUnsupportedError, type KeyReader, type Reader, UnsupportedValueError, create, keyReader, read, readKey, reader, write, writeKey };
@@ -0,0 +1,44 @@
1
+ import {
2
+ ArrayPath,
3
+ AsyncValidationUnsupportedError,
4
+ KeyPath,
5
+ KeyValuePath,
6
+ Locator,
7
+ MapPath,
8
+ UnsupportedValueError,
9
+ at,
10
+ create,
11
+ deepEqual2 as deepEqual,
12
+ keyReader,
13
+ live,
14
+ observeLocated,
15
+ read,
16
+ readKey,
17
+ reader,
18
+ select,
19
+ shallowEqual,
20
+ write,
21
+ writeKey
22
+ } from "../chunk-7TXOG3GB.js";
23
+ export {
24
+ ArrayPath,
25
+ AsyncValidationUnsupportedError,
26
+ KeyPath,
27
+ KeyValuePath,
28
+ Locator,
29
+ MapPath,
30
+ UnsupportedValueError,
31
+ at,
32
+ create,
33
+ deepEqual,
34
+ keyReader,
35
+ live,
36
+ observeLocated,
37
+ read,
38
+ readKey,
39
+ reader,
40
+ select,
41
+ shallowEqual,
42
+ write,
43
+ writeKey
44
+ };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Whether two values are the same, or objects or arrays whose own keys hold the same values
3
+ * (`Object.is`). The default `equals` of a `LiveSpec`.
4
+ *
5
+ * @example
6
+ * shallowEqual({ done: 1, total: 2 }, { done: 1, total: 2 }) // true
7
+ * shallowEqual({ tags: ['a'] }, { tags: ['a'] }) // false: two different arrays
8
+ */
9
+ declare const shallowEqual: (a: unknown, b: unknown) => boolean;
10
+ /**
11
+ * Compares arrays and plain objects all the way down, and bytes byte by byte.
12
+ * Any other object (a `Map`, a `Set`, a `Date`, a shared type) equals only itself.
13
+ *
14
+ * @example
15
+ * deepEqual({ tags: ['a'] }, { tags: ['a'] }) // true
16
+ * const tags = liveAtom({ ...select.map('card').get('tags', []), equals: deepEqual })
17
+ */
18
+ declare const deepEqual: (a: unknown, b: unknown) => boolean;
19
+
20
+ export { deepEqual as d, shallowEqual as s };
@@ -0,0 +1,102 @@
1
+ import { d as Locator, M as MapPath, E as Exact, b as KeyValuePath } from './shape-CMa7XFjy.js';
2
+ export { g as ArrayKind, A as ArrayPath, a as At, K as KeyPath, c as LiveSpec, h as MapKind, O as ObserveOptions, P as ProjectOptions, e as Projection, R as RecordKind, S as Selector, i as Shape, j as array, f as at, k as isMap, m as map, r as record, s as select } from './shape-CMa7XFjy.js';
3
+ export { d as deepEqual, s as shallowEqual } from './equality-AjtpnVrF.js';
4
+ import { T as TypedAtom, A as AtomOptions } from './typed-atom-t7tvnXSS.js';
5
+ export { K as KeyUpdate, P as Patch, a as TypedKeyAtom, d as docAtom, l as liveAtom, t as typedAtom } from './typed-atom-t7tvnXSS.js';
6
+ import { StandardSchemaV1 } from '@standard-schema/spec';
7
+ import { Atom, WritableAtom } from 'jotai';
8
+ import { AtomFamily } from 'jotai-family';
9
+ import 'yjs';
10
+
11
+ /** What a collection's `create` returns: the schema's result, with the new item's id when valid. */
12
+ type CreateResult<T> = (StandardSchemaV1.SuccessResult<T> & {
13
+ readonly id: string;
14
+ }) | StandardSchemaV1.FailureResult;
15
+ /**
16
+ * Atoms over a `Y.Map` of items, each item a `Y.Map` read through one schema. Write with
17
+ * `store.set` or `useSetAtom`, like any Jotai atom.
18
+ */
19
+ interface Collection<T> {
20
+ /**
21
+ * The ids of every entry of the map, sorted so every peer sees the same order; `[]` while the
22
+ * map is missing. Notifies only when an id is added or removed, never when an item's fields
23
+ * change.
24
+ */
25
+ readonly ids: Atom<string[]>;
26
+ /**
27
+ * The typed atom of the item under `id`, the same atom for the same id: it reads `undefined`,
28
+ * `{ issues }` or `{ value }` and merges a patch when set, as `typedAtom` does; setting a
29
+ * missing item creates it. The collection's `remove` drops the item's atom from the family, and
30
+ * `item.remove(id)` or `item.setShouldRemove` can drop others; an atom a caller still holds keeps
31
+ * working after it's dropped.
32
+ */
33
+ readonly item: AtomFamily<string, TypedAtom<T>>;
34
+ /**
35
+ * Validates a whole value and adds it as a new item under `id`, or under a random UUID when no
36
+ * id is given. Returns the schema's result with the id. An invalid value, an id already in use,
37
+ * or a missing map adds nothing and returns `{ issues }`: the value's own issues when it has
38
+ * any, else one saying why it couldn't be added.
39
+ */
40
+ readonly create: WritableAtom<null, [value: T, id?: string], CreateResult<T>>;
41
+ /** Removes the item under `id`. Returns whether there was one. */
42
+ readonly remove: WritableAtom<null, [id: string], boolean>;
43
+ }
44
+ /**
45
+ * A collection over the `Y.Map` at `locator`, whose every entry is an item `Y.Map` read through
46
+ * `schema` and `shape`. `ids` lists the items and stays quiet while their fields change, `item(id)`
47
+ * is a `typedAtom` per item, and `create` and `remove` add and delete items.
48
+ *
49
+ * Like any duratom atom, `ids` and `item(id)` can read stale while nothing is subscribed, except
50
+ * right after the collection's own `create` or `remove`, or a write through `item(id)` that
51
+ * created the item. An entry a peer stored as something other than a `Y.Map` is still listed in
52
+ * `ids`, so it can be found and repaired; its `item` atom reads it as `{ issues }`, or as
53
+ * `undefined` for a plain value.
54
+ *
55
+ * @example
56
+ * const Todo = z.object({ title: z.string(), done: z.boolean() })
57
+ * const todos = collection(select.map('todos'), Todo, { title: 'text' })
58
+ *
59
+ * const { id } = store.set(todos.create, { title: 'Buy milk', done: false }) as { id: string }
60
+ * store.get(todos.ids) // [id]
61
+ * store.set(todos.item(id), { done: true }) // changes only done
62
+ * store.set(todos.remove, id)
63
+ */
64
+ declare function collection<Schema extends StandardSchemaV1, const S extends object>(locator: Locator<any> | MapPath<any>, schema: Schema, shape: Exact<S, StandardSchemaV1.InferOutput<Schema>>, options?: AtomOptions): Collection<StandardSchemaV1.InferOutput<Schema>>;
65
+
66
+ type Schemas = Record<string, StandardSchemaV1>;
67
+ type Values<S extends Schemas> = {
68
+ [K in keyof S]: StandardSchemaV1.InferOutput<S[K]>;
69
+ };
70
+ /**
71
+ * A Jotai atom over the keys of a key-value array that `schemas` names, each read through its
72
+ * own schema. It reads as an object with one result per key: `undefined` while the key has no
73
+ * entry, `{ issues }` while its value is invalid, `{ value }` otherwise. Setting it takes a patch
74
+ * of the keys to change, or a function of their valid values returning one.
75
+ */
76
+ type KeyValueAtom<S extends Schemas> = WritableAtom<{
77
+ [K in keyof S]: StandardSchemaV1.Result<Values<S>[K]> | undefined;
78
+ }, [
79
+ patch: Partial<Values<S>> | ((prev: Partial<Values<S>>) => Partial<Values<S>>)
80
+ ], StandardSchemaV1.Result<Partial<Values<S>>>>;
81
+ /**
82
+ * A typed, writable atom over a whole key-value array (y-utility's `YKeyValue`), with one schema
83
+ * per key. Keys `schemas` doesn't name are left out of the read and never written. It re-renders
84
+ * only when an entry for one of its keys changes a result; for one key alone, use
85
+ * `typedAtom(path.key(k), schema)`, which also ignores the other keys.
86
+ *
87
+ * Setting it validates every key of the patch first: when any is invalid, nothing is written and
88
+ * the result holds their issues, each path starting at its key. Otherwise each key is written as
89
+ * `YKeyValue#set` does, in one transaction. A missing array changes nothing.
90
+ *
91
+ * @example
92
+ * const master = keyValueAtom(select.keyValue('master'), {
93
+ * tone: z.number().min(-1).max(1),
94
+ * filter: z.object({ x: z.number(), y: z.number() }),
95
+ * })
96
+ *
97
+ * store.get(master).tone // undefined, { issues } or { value }
98
+ * store.set(master, { tone: -0.6 })
99
+ */
100
+ declare function keyValueAtom<const S extends Schemas>(path: KeyValuePath<any>, schemas: S, options?: AtomOptions): KeyValueAtom<S>;
101
+
102
+ export { AtomOptions, type Collection, type CreateResult, type KeyValueAtom, KeyValuePath, Locator, MapPath, TypedAtom, collection, keyValueAtom };
package/dist/index.js ADDED
@@ -0,0 +1,182 @@
1
+ import {
2
+ docAtom,
3
+ liveAtom,
4
+ readDoc,
5
+ refreshedTypedAtom,
6
+ typedAtom,
7
+ versionedLiveAtom
8
+ } from "./chunk-URKFBGPT.js";
9
+ import {
10
+ ArrayPath,
11
+ KeyPath,
12
+ KeyValuePath,
13
+ Locator,
14
+ MapPath,
15
+ array,
16
+ assertStorable,
17
+ at,
18
+ copy,
19
+ create,
20
+ currentEntries,
21
+ deepEqual,
22
+ deepEqual2,
23
+ isMap,
24
+ map,
25
+ readValue,
26
+ record,
27
+ select,
28
+ setEntry,
29
+ shallowEqual,
30
+ touchesKeys,
31
+ validate
32
+ } from "./chunk-7TXOG3GB.js";
33
+
34
+ // src/atoms/collection.ts
35
+ import { atom } from "jotai";
36
+ import { atomFamily } from "jotai-family";
37
+ function collection(locator, schema, shape, options = {}) {
38
+ const path = locator instanceof MapPath ? locator : new MapPath(locator);
39
+ const membership = atom(0);
40
+ const changed = (set) => set(membership, (n) => n + 1);
41
+ const has = (get, id) => {
42
+ const map2 = path.locator.resolve(readDoc(get, options));
43
+ return isMap(map2) && map2.has(id);
44
+ };
45
+ const { live: ids } = versionedLiveAtom(path.keys(), options, [membership]);
46
+ const item = atomFamily((id) => {
47
+ const typed = refreshedTypedAtom(path.child(id), schema, shape, options, [membership]);
48
+ return atom(
49
+ (get) => get(typed),
50
+ (get, set, patch) => {
51
+ const existed = has(get, id);
52
+ const result = set(typed, patch);
53
+ if (!result.issues && !existed) changed(set);
54
+ return result;
55
+ }
56
+ );
57
+ });
58
+ const refuse = (value, message) => {
59
+ const checked = validate(schema, value);
60
+ return checked.issues ? checked : { issues: [{ message }] };
61
+ };
62
+ const create2 = atom(null, (get, set, value, id) => {
63
+ const doc = readDoc(get, options);
64
+ const key = id ?? randomId();
65
+ let result;
66
+ doc.transact(() => {
67
+ const map2 = path.locator.resolve(doc);
68
+ if (!isMap(map2)) result = refuse(value, missingMap);
69
+ else if (map2.has(key)) result = refuse(value, taken(key));
70
+ else result = create(schema, shape, map2, key, value);
71
+ });
72
+ if (result.issues) return result;
73
+ changed(set);
74
+ return { value: result.value, id: key };
75
+ });
76
+ const remove = atom(null, (get, set, id) => {
77
+ const doc = readDoc(get, options);
78
+ const map2 = path.locator.resolve(doc);
79
+ if (!isMap(map2) || !map2.has(id)) return false;
80
+ map2.delete(id);
81
+ changed(set);
82
+ item.remove(id);
83
+ return true;
84
+ });
85
+ return { ids, item, create: create2, remove };
86
+ }
87
+ var missingMap = "The collection's Y.Map is missing, so there is nowhere to create the item";
88
+ var taken = (id) => `An item with id ${JSON.stringify(id)} already exists`;
89
+ function randomId() {
90
+ if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
91
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
92
+ bytes[6] = bytes[6] & 15 | 64;
93
+ bytes[8] = bytes[8] & 63 | 128;
94
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
95
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
96
+ }
97
+
98
+ // src/atoms/key-value-atom.ts
99
+ import { atom as atom2 } from "jotai";
100
+ import * as Y from "yjs";
101
+ function keyValueAtom(path, schemas, options = {}) {
102
+ if (!(path instanceof KeyValuePath)) throw new TypeError("keyValueAtom needs a KeyValuePath.");
103
+ const keys = Object.keys(schemas);
104
+ const project = (node) => {
105
+ const entries = node instanceof Y.Array ? currentEntries(node) : void 0;
106
+ const out = {};
107
+ for (const key of keys) {
108
+ const entry = entries?.get(key);
109
+ out[key] = entry && readValue(schemas[key], entry.val, key);
110
+ }
111
+ return out;
112
+ };
113
+ const { live, version } = versionedLiveAtom(
114
+ { locate: () => path.locator, project, event: touchesKeys(keys), equals: deepEqual },
115
+ options
116
+ );
117
+ return atom2(
118
+ (get) => get(live),
119
+ (get, set, update) => {
120
+ const doc = readDoc(get, options);
121
+ let result;
122
+ doc.transact(() => {
123
+ const array2 = path.locator.resolve(doc);
124
+ if (!(array2 instanceof Y.Array)) {
125
+ result = { issues: [{ message: "The key-value Y.Array is missing" }] };
126
+ return;
127
+ }
128
+ let patch = update;
129
+ if (typeof update === "function") {
130
+ const prev = {};
131
+ for (const [key, read] of Object.entries(project(array2)))
132
+ if (read && !read.issues) prev[key] = read.value;
133
+ patch = update(prev);
134
+ }
135
+ const issues = [];
136
+ const valid = [];
137
+ const output = {};
138
+ for (const [key, value] of Object.entries(patch)) {
139
+ const schema = Object.hasOwn(schemas, key) ? schemas[key] : void 0;
140
+ if (!schema) {
141
+ issues.push({ message: `Unknown key ${JSON.stringify(key)}`, path: [key] });
142
+ continue;
143
+ }
144
+ const checked = validate(schema, value);
145
+ if (checked.issues)
146
+ for (const issue of checked.issues)
147
+ issues.push({ ...issue, path: [key, ...issue.path ?? []] });
148
+ else {
149
+ valid.push([key, value]);
150
+ output[key] = checked.value;
151
+ }
152
+ }
153
+ if (issues.length > 0) return void (result = { issues });
154
+ for (const [key, value] of valid) assertStorable(value, { key, parent: void 0 });
155
+ for (const [key, value] of valid) setEntry(array2, key, copy(value), deepEqual);
156
+ result = { value: output };
157
+ });
158
+ if (!result.issues) set(version, (n) => n + 1);
159
+ return result;
160
+ }
161
+ );
162
+ }
163
+ export {
164
+ ArrayPath,
165
+ KeyPath,
166
+ KeyValuePath,
167
+ Locator,
168
+ MapPath,
169
+ array,
170
+ at,
171
+ collection,
172
+ deepEqual2 as deepEqual,
173
+ docAtom,
174
+ isMap,
175
+ keyValueAtom,
176
+ liveAtom,
177
+ map,
178
+ record,
179
+ select,
180
+ shallowEqual,
181
+ typedAtom
182
+ };