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.
package/llms.txt ADDED
@@ -0,0 +1,24 @@
1
+ # duratom
2
+
3
+ > Durable, live Jotai atoms over a Y.Doc: read typed values, write validated patches, and re-render only when what an atom shows changes.
4
+
5
+ Rules an app must follow: set `docAtom` once per Jotai store; setting a typed atom merges a patch into the doc as it is at write time; invalid data comes back as `{ issues }`, never as an exception; a duratom atom follows the doc only while something is subscribed to it.
6
+
7
+ The npm package ships `llms-full.txt` (every doc in one file) and an agent skill at `skills/duratom/SKILL.md`.
8
+
9
+ ## Docs
10
+
11
+ - [Guide](https://duratom.karolnov.dev/): install, quick start, the main API by example
12
+ - [API reference](https://duratom.karolnov.dev/api): every export of `duratom`, `duratom/react` and `duratom/core`
13
+ - [Agent skill](https://github.com/KarolNov/duratom/blob/main/skills/duratom/SKILL.md): how to build with duratom, for coding agents
14
+
15
+ ## Recipes
16
+
17
+ - [Sync between devices](https://github.com/KarolNov/duratom/blob/main/docs/recipes/sync.md): Connect the doc in `docAtom` to a sync server with y-partyserver on Cloudflare; every atom then shows and edits the shared state, with no change to the atoms.
18
+ - [Offline storage](https://github.com/KarolNov/duratom/blob/main/docs/recipes/offline.md): Save the doc in the browser with y-indexeddb, so the app opens with the last state and works offline; atoms don't change.
19
+ - [Repair a broken node](https://github.com/KarolNov/duratom/blob/main/docs/recipes/repair.md): Fix a node a peer stored with data your schema rejects, by setting its typed atom with a whole valid value.
20
+
21
+ ## Optional
22
+
23
+ - [Full docs in one file](https://github.com/KarolNov/duratom/blob/main/llms-full.txt)
24
+ - [Example app](https://github.com/KarolNov/duratom/blob/main/examples/todo/README.md): a two-pane shared todo list
package/package.json CHANGED
@@ -1,6 +1,105 @@
1
1
  {
2
2
  "name": "duratom",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "Durable, live Jotai atoms over a Y.Doc: typed reads, validated writes, re-renders only on change.",
5
+ "keywords": [
6
+ "atoms",
7
+ "collaboration",
8
+ "crdt",
9
+ "jotai",
10
+ "local-first",
11
+ "react",
12
+ "standard-schema",
13
+ "yjs"
14
+ ],
15
+ "homepage": "https://duratom.karolnov.dev",
16
+ "bugs": {
17
+ "url": "https://github.com/KarolNov/duratom/issues"
18
+ },
19
+ "license": "MIT",
20
+ "author": "Karol Novljaković",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/KarolNov/duratom.git"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "llms.txt",
28
+ "llms-full.txt",
29
+ "skills"
30
+ ],
31
+ "type": "module",
32
+ "sideEffects": false,
33
+ "exports": {
34
+ ".": {
35
+ "types": "./dist/index.d.ts",
36
+ "import": "./dist/index.js"
37
+ },
38
+ "./react": {
39
+ "types": "./dist/react/index.d.ts",
40
+ "import": "./dist/react/index.js"
41
+ },
42
+ "./core": {
43
+ "types": "./dist/core/index.d.ts",
44
+ "import": "./dist/core/index.js"
45
+ }
46
+ },
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "dependencies": {
51
+ "@standard-schema/spec": "^1.0.0"
52
+ },
53
+ "devDependencies": {
54
+ "@cloudflare/workers-types": "^4.20260424.1",
55
+ "@testing-library/dom": "^10.4.2",
56
+ "@testing-library/react": "^16.3.3",
57
+ "@types/node": "^22.0.0",
58
+ "@types/react": "^19.0.0",
59
+ "@types/react-dom": "^19.0.0",
60
+ "arktype": "^2.2.8",
61
+ "jotai": "^3.0.1",
62
+ "jotai-family": "1.1.0",
63
+ "jsdom": "^30.1.1",
64
+ "oxfmt": "^0.71.0",
65
+ "partyserver": "0.5.10",
66
+ "react": "^19.0.0",
67
+ "react-dom": "^19.0.0",
68
+ "tsup": "^8.3.0",
69
+ "typescript": "^5.6.0",
70
+ "valibot": "^1.5.0",
71
+ "vite": "^8.3.2",
72
+ "vitepress": "1.6.4",
73
+ "vitest": "^5.0.3",
74
+ "wrangler": "4.156.0",
75
+ "y-indexeddb": "9.0.12",
76
+ "y-partyserver": "2.2.0",
77
+ "y-utility": "0.1.4",
78
+ "yjs": "^13.6.33",
79
+ "zod": "^4.6.7"
80
+ },
81
+ "peerDependencies": {
82
+ "jotai": "^2.9.0 || ^3.0.0",
83
+ "jotai-family": "^1.0.0",
84
+ "react": "^18.0.0 || ^19.0.0",
85
+ "yjs": "^13.6.33"
86
+ },
87
+ "peerDependenciesMeta": {
88
+ "react": {
89
+ "optional": true
90
+ }
91
+ },
92
+ "scripts": {
93
+ "build": "tsup",
94
+ "typecheck": "tsc --noEmit",
95
+ "test": "vitest run",
96
+ "format": "oxfmt --write",
97
+ "format:check": "oxfmt --check",
98
+ "docs": "node scripts/docs.ts",
99
+ "docs:check": "node scripts/docs.ts --check && tsc -p docs/tsconfig.json && tsc -p docs/snippets/server/tsconfig.json",
100
+ "site:build": "node scripts/site.ts",
101
+ "site:dev": "pnpm site:build && wrangler dev --config site/wrangler.jsonc",
102
+ "site:deploy": "pnpm site:build && wrangler deploy --config site/wrangler.jsonc",
103
+ "example:sync:deploy": "pnpm build && pnpm --filter duratom-example-sync run deploy"
104
+ }
6
105
  }
@@ -0,0 +1,171 @@
1
+ ---
2
+ name: duratom
3
+ description: Build React apps whose state lives in a Yjs Y.Doc, through duratom's Jotai atoms - typed reads, validated patch writes, collections, live projections, and the sync and offline recipes. Use when code imports duratom, duratom/react or duratom/core, or when the user wants collaborative, synced or offline-first state with Jotai and Yjs.
4
+ ---
5
+
6
+ # duratom
7
+
8
+ duratom turns nodes of a Yjs `Y.Doc` into Jotai atoms. A typed atom reads one `Y.Map` through a Standard Schema validator (zod, valibot, arktype) and writes validated patches into it; a collection covers a map of such items; a live atom reads any projection of a node. Each atom re-renders only when its own value changes. Sync and offline storage come from Yjs providers attached to the doc, never from duratom.
9
+
10
+ The whole documentation is in `node_modules/duratom/llms-full.txt`: the guide, the recipes and the API reference with every signature. Read it when this file doesn't answer a question; don't read duratom's source to find out how to use it.
11
+
12
+ ## Rules
13
+
14
+ 1. **Set `docAtom` once per Jotai store, before any atom is read.** `store.set(docAtom, doc)` and pass that store to `<Provider store={store}>`. Reading an atom with no doc throws `docAtom has not been set on this store`. For a second doc, make a doc atom (`atom<Y.Doc | null>(null)`) and pass `{ docAtom: thatAtom }` as the last argument of the atom.
15
+ 2. **Setting a typed atom merges a patch.** `set({ done: true })` changes only `done`, merging into the node as it is in the doc at write time, so a peer's concurrent edit to another field survives. Don't spread the atom's current value into the patch: `set({ ...todo.value, done: true })` writes back the fields it read, and can undo a peer's edit made since. For a value computed from the current one, use `set((prev) => ({ count: (prev?.count ?? 0) + 1 }))`; `prev` is read from the doc at write time.
16
+ 3. **Results, not exceptions.** A typed atom reads `undefined` (node missing), `{ issues }` (node fails the schema, such as a peer's bad data) or `{ value }`. Handle all three in the component. Setting returns the schema result too: `{ issues }` means nothing was written. Never wrap a set in try/catch for validation; check `result.issues`.
17
+ 4. **A missing node is created by setting its whole value.** While the node has no valid value, the patch must be the whole value; a partial one returns `{ issues }`. Its parent map must exist: root maps always do (`select.map('todos')`), nested ones may not.
18
+ 5. **Atoms follow the doc while subscribed.** Components using `useAtomValue` or `useAtom` are always current. `store.get(atom)` with nothing subscribed may return a value from before a peer's edit; subscribe with `store.sub`, or read the doc as it is now with `live` from `duratom/core`.
19
+ 6. **Name shared fields in the shape.** `{ title: 'text' }` stores `title` as a `Y.Text`, so concurrent typing merges. Fields the shape omits are plain values: last writer wins. Kinds: `'text'`, `'xml'`, `map(shape)`, `record(itemShape)`, `array()`. Use `{}` when every field is plain.
20
+ 7. **Schemas must validate synchronously and accept only JSON values and bytes.** An async refinement throws `AsyncValidationUnsupportedError`; a `Date`, `Map` or class instance throws `UnsupportedValueError`. Store dates as ISO strings or numbers.
21
+
22
+ ## Which API
23
+
24
+ | Need | Use |
25
+ | -------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
26
+ | One typed object at a known path | `typedAtom(select.map('root').child('key'), Schema, shape)` |
27
+ | A list of items with ids | `collection(select.map('items'), Schema, shape)`: `ids`, `item(id)`, `create`, `remove` |
28
+ | Often-written knobs in a y-utility YKeyValue | `typedAtom(select.keyValue('m').key('k'), Schema)` or `keyValueAtom(select.keyValue('m'), { k: Schema })` |
29
+ | One field, a count, a derived value | `liveAtom(select.map('m').get('field', fallback))` or `.project(fn)` |
30
+ | A selector that depends on props, in a hook | `useLiveAtom(() => select..., [deps])` from `duratom/react` |
31
+ | A typed object whose path depends on props | `useTypedAtom(() => select..., Schema, shape, [deps])` from `duratom/react` |
32
+ | No Jotai | `live`, `read`, `write` from `duratom/core` |
33
+ | Values derived from typed atoms | a plain Jotai `atom((get) => ...)` over them |
34
+
35
+ Paths: `select.map(name)` and `select.array(name)` start at a root type; `.child(key)` descends into a nested map, `.child(key, 'array')` into a nested array. Selectors end a path: `.get(key, fallback)`, `.pick(defaults)`, `.text(key)`, `.keys()`, `.toJSON()`, `.project(fn)` on a map; `.toArray()`, `.length()`, `.toJSON()` on an array. `select.keyValue(name)` (or `.child(key, 'keyValue')`) is a y-utility `YKeyValue` array: `.get(key, fallback)`, `.keys()`, `.toJSON()`, and `.key(k)` for `typedAtom`.
36
+
37
+ ## Setup
38
+
39
+ ```bash
40
+ npm install duratom jotai jotai-family yjs zod
41
+ ```
42
+
43
+ <!-- snippet: docs/snippets/quick-start.tsx -->
44
+
45
+ ```tsx
46
+ // src/main.tsx of a new Vite React app: npm create vite@latest my-app -- --template react-ts
47
+ import { docAtom, select, typedAtom } from 'duratom'
48
+ import { createStore, Provider, useAtom } from 'jotai'
49
+ import { StrictMode } from 'react'
50
+ import { createRoot } from 'react-dom/client'
51
+ import * as Y from 'yjs'
52
+ import { z } from 'zod'
53
+
54
+ // What a todo is, and where it lives in the doc: the map `first` in the root map `todos`.
55
+ // `title` is collaborative text, so two people typing in it both keep their edits.
56
+ const Todo = z.object({ title: z.string(), done: z.boolean() })
57
+ const todoAtom = typedAtom(select.map('todos').child('first'), Todo, { title: 'text' })
58
+
59
+ // One Y.Doc per Jotai store. A sync provider would connect this doc to other devices.
60
+ const store = createStore()
61
+ store.set(docAtom, new Y.Doc())
62
+
63
+ function TodoRow() {
64
+ // undefined while the todo is missing, { issues } while it's invalid, { value } otherwise.
65
+ const [todo, setTodo] = useAtom(todoAtom)
66
+ if (!todo) {
67
+ // Setting a missing node with a whole valid value creates it.
68
+ return <button onClick={() => setTodo({ title: 'Learn duratom', done: false })}>Add</button>
69
+ }
70
+ if (todo.issues) return <p>Can't read this todo: {todo.issues[0]?.message}</p>
71
+ return (
72
+ <label>
73
+ {/* A patch changes only the fields it names. */}
74
+ <input
75
+ type="checkbox"
76
+ checked={todo.value.done}
77
+ onChange={(e) => setTodo({ done: e.target.checked })}
78
+ />
79
+ <input value={todo.value.title} onChange={(e) => setTodo({ title: e.target.value })} />
80
+ </label>
81
+ )
82
+ }
83
+
84
+ createRoot(document.getElementById('root')!).render(
85
+ <StrictMode>
86
+ <Provider store={store}>
87
+ <TodoRow />
88
+ </Provider>
89
+ </StrictMode>,
90
+ )
91
+ ```
92
+
93
+ <!-- /snippet -->
94
+
95
+ ## Collections
96
+
97
+ <!-- snippet: docs/snippets/collection.tsx -->
98
+
99
+ ```tsx
100
+ import { collection, select } from 'duratom'
101
+ import { useAtom, useAtomValue, useSetAtom } from 'jotai'
102
+ import { z } from 'zod'
103
+
104
+ const Todo = z.object({ title: z.string().min(1), done: z.boolean() })
105
+
106
+ // Every todo in the root map `todos`, each one a Y.Map read through `Todo`.
107
+ const todos = collection(select.map('todos'), Todo, { title: 'text' })
108
+
109
+ export function TodoList() {
110
+ // Changes only when a todo is added or removed, not when one is edited.
111
+ const ids = useAtomValue(todos.ids)
112
+ const create = useSetAtom(todos.create)
113
+ const add = () => {
114
+ const result = create({ title: 'New todo', done: false })
115
+ if (result.issues) console.warn(result.issues)
116
+ }
117
+ return (
118
+ <>
119
+ <ul>
120
+ {ids.map((id) => (
121
+ <TodoItem key={id} id={id} />
122
+ ))}
123
+ </ul>
124
+ <button onClick={add}>Add</button>
125
+ </>
126
+ )
127
+ }
128
+
129
+ function TodoItem({ id }: { id: string }) {
130
+ // The same typed atom for the same id; it re-renders this row only.
131
+ const [todo, setTodo] = useAtom(todos.item(id))
132
+ const remove = useSetAtom(todos.remove)
133
+ if (!todo || todo.issues) return <li>Unreadable todo</li>
134
+ return (
135
+ <li>
136
+ <input
137
+ type="checkbox"
138
+ checked={todo.value.done}
139
+ onChange={(e) => setTodo({ done: e.target.checked })}
140
+ />
141
+ {todo.value.title}
142
+ <button onClick={() => remove(id)}>Remove</button>
143
+ </li>
144
+ )
145
+ }
146
+ ```
147
+
148
+ <!-- /snippet -->
149
+
150
+ `create(value, id?)` returns `{ value, id }` or `{ issues }`; it refuses an id already in use. Generated ids are random UUIDs and `ids` is sorted, so for creation order pass ids that sort by time. `item(id)` returns the same atom for the same id. A row reads `todos.item(id)` itself, so editing one item re-renders only its row.
151
+
152
+ ## Sync and offline
153
+
154
+ Attach a provider to the doc before or after putting it in `docAtom`; atoms don't change.
155
+
156
+ - Sync: `new YProvider(host, room, doc, { party })` from `y-partyserver/provider`, served by a `YServer` Durable Object. See `docs/recipes/sync.md` in `llms-full.txt` for the Worker and its `wrangler.jsonc`.
157
+ - Offline: `new IndexeddbPersistence(name, doc)` from `y-indexeddb`; `await persistence.whenSynced` before rendering to skip an empty first frame.
158
+ - Both: attach both providers to the same doc.
159
+
160
+ ## Broken data from a peer
161
+
162
+ A node a peer stored invalidly reads `{ issues }`, and a collection still lists its id. Show it as broken; to repair, set the item's atom with a whole valid value built from what's stored. Repair is app code; see `docs/recipes/repair.md`.
163
+
164
+ ## Checklist before finishing
165
+
166
+ - Every component reading a typed atom handles `undefined`, `{ issues }` and `{ value }`.
167
+ - Every set whose result matters checks `result.issues`.
168
+ - No patch spreads the atom's previous value; function patches use `prev`.
169
+ - Shared-text fields are `'text'` in the shape.
170
+ - Each Jotai store has `docAtom` set before render.
171
+ - Schemas have no async refinements and no `Date` or class values.