attodo-sync 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,85 @@
1
- # Temporary Holding Version
1
+ # attodo-sync
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The sync engine for [attodo](https://tangled.org/orta.io/todos.at), an open spec for to-do apps on [atproto](https://atproto.com), for JavaScript. It is the Rust engine ([`attodo-sync` on crates.io](https://crates.io/crates/attodo-sync)) compiled to WebAssembly, not a port. Every attodo app runs the same code, so they all agree on what "done" or "today" means and on what each list holds.
4
+
5
+ To-dos live in permissioned spaces: a private one per account, and shared ones that belong to an Atmosphere Group. Each member writes only to their own repo. The engine merges everyone's copies field by field, verifies what it pulls against each repo's commits, and works offline.
6
+
7
+ ```sh
8
+ npm install attodo-sync
9
+ ```
10
+
11
+ It works the same in Node (22 or later) and in browsers or bundlers. The browser build loads its WebAssembly with top-level `await`. For control over how the WebAssembly loads, `attodo-sync/web` exports `init` and `initSync`.
12
+
13
+ ## Use
14
+
15
+ ```ts
16
+ import { Device, SimNetwork } from 'attodo-sync'
17
+
18
+ const me = 'did:plc:alice'
19
+ const personal = `at:space/${me}/at.todos.personalSpace/self`
20
+ const today = '2026-12-06' // the user's local date
21
+
22
+ // Once per install: a random clock id (0–1023) and seed.
23
+ const device = new Device(me, 7, 0x5eedn)
24
+ device.addSpace(personal, 'personal')
25
+
26
+ const milk = device.addTodo(personal, 'Buy milk', 'today', today, Date.now() * 1000)
27
+ device.toggleDone(milk, Date.now() * 1000)
28
+
29
+ // Your transport, or the in-memory network for demos and tests.
30
+ const net = new SimNetwork()
31
+ net.createSpace(personal)
32
+ const report = await device.syncSpace(net.client(me), personal, Date.now() * 1000)
33
+
34
+ for (const row of device.rows(device.lists(today).logbook, today)) console.log('✔', row.title)
35
+
36
+ // Keep it for next time: plain JSON.
37
+ const saved = device.toJson()
38
+ const again = Device.fromJson(saved)
39
+ ```
40
+
41
+ Times are epoch microseconds. Dates are `YYYY-MM-DD`. Spaces are space references (`at:space/<did>/<type>/<key>`).
42
+
43
+ ### Reading
44
+
45
+ | | |
46
+ | --- | --- |
47
+ | `lists(today)` | Inbox, Today, Evening, Upcoming, Anytime, Someday, Logbook and Trash (SPEC §6), as `Listed[]` |
48
+ | `spaceList(space)` | everything active in one space: a shared list's own view |
49
+ | `rows(listed, today)` | what to show for each: title, notes, state, date, deadline, evening, project, list title |
50
+ | `spaces()`, `spaceTitle(space)`, `personalSpace()` | the spaces this device syncs |
51
+ | `pending()` | how many changes haven't reached the hosts yet |
52
+
53
+ ### Editing
54
+
55
+ `addTodo`, `setTitle`, `setNotes`, `toggleDone`, `schedule`, `trash` and `deleteForever` apply at once, offline too, and are sent on the next sync. Scheduling a to-do in a shared list sets the user's private plan for it (§4.9), so the others don't see it. When the engine refuses an edit, it throws an `Error` named `EditFailure`. Its `code` says why: `ReadOnly`, `Deleted`, `NotFound`, `TooLarge`, `InvalidValue`, `UnknownSpace`.
56
+
57
+ ### Syncing
58
+
59
+ `syncSpace(transport, space, nowMicros)` pulls every writer's changes, then sends the user's. It rejects, with an `Error` named `SyncFailure` and a `code`, only if the space couldn't be synced at all (offline, rate limited, access lost). Problems with a single repo or a refused write go in the report it resolves to. Edits made while it runs apply at once and are kept. One sync per device runs at a time.
60
+
61
+ ## Writing a transport
62
+
63
+ The engine does no I/O. It calls five methods on the transport you pass it, which talk to the hosts (SPEC §8.2):
64
+
65
+ ```ts
66
+ interface Transport {
67
+ listWriters(space: string, since: string | undefined, cursor: string | undefined): Promise<Result<WritersPage>>
68
+ listRepoOps(space: string, repo: string, since: string, cursor: string | undefined): Promise<Result<OpsPage>>
69
+ getRecord(space: string, repo: string, path: RecordPath): Promise<Result<{ cid: string; value: JsonValue } | undefined>>
70
+ getSnapshot(space: string, repo: string): Promise<Result<Snapshot>>
71
+ applyWrites(space: string, writes: Write[]): Promise<Result<WriteOk>>
72
+ }
73
+ ```
74
+
75
+ Routing each call to the right host, OAuth, space credentials and checking response MACs are the transport's job. The engine verifies the rest itself: op logs and snapshots against the repo's commit, and CIDs against values.
76
+
77
+ - Answer `{ ok: true, value }` or `{ ok: false, error }`. `error` is a `TransportError`: `network`, `server` (5xx), `rateLimited` (429, with `retryAfterMs`), or `xrpc` with the error's name. A method that throws counts as a network error.
78
+ - Everything is plain JSON. TIDs and CIDs are strings. Record values are in the data model's JSON form (`$link`, `$bytes`), which `lexToJson` and `jsonToLex` from `@atproto/lex-json` convert. A commit's `data` is `{ $bytes }`.
79
+ - An answer the engine can't read counts as an invalid response from the host. That space is tried again on the next sync.
80
+
81
+ The package's type definitions document every shape. [`node/src/atproto/transport.ts`](https://github.com/orta/todos.at/blob/main/node/src/atproto/transport.ts) is a complete transport over `@atproto/lex-space`, used by the [`attodo`](https://www.npmjs.com/package/attodo) terminal app.
82
+
83
+ ## License
84
+
85
+ MIT OR Apache-2.0
@@ -0,0 +1,291 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+
4
+ /** Where a new to-do goes, or when to do one (SPEC §6.1). In a shared list, `inbox` means `anytime`. */
5
+ export type When = 'inbox' | 'today' | 'evening' | 'tomorrow' | 'anytime' | 'someday'
6
+ export type SpaceKind = 'personal' | 'shared'
7
+ /** A record value in the data model's JSON form (`$link`, `$bytes`), as `@atproto/lex-json` reads and writes it. */
8
+ export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue | undefined }
9
+
10
+ /** A to-do or project. `space` is a space reference (`at:space/…`), `collection` an NSID. */
11
+ export type ObjectRef = { space: string; collection: string; id: string }
12
+ /** An object in a list, with the date (`YYYY-MM-DD`) that placed it there, if any. */
13
+ export type Listed = { object: ObjectRef; date?: string }
14
+ /** The lists of SPEC §6. `today` includes `evening`. */
15
+ export type Lists = {
16
+ inbox: Listed[]; today: Listed[]; evening: Listed[]; upcoming: Listed[]
17
+ anytime: Listed[]; someday: Listed[]; logbook: Listed[]; trash: Listed[]
18
+ }
19
+ /** What a list shows for one to-do or project. */
20
+ export type Row = {
21
+ object: ObjectRef
22
+ title: string
23
+ notes?: string
24
+ /** `open`, `completed` or `canceled`. */
25
+ state: string
26
+ /** The date that placed it in the list, or else its scheduled date. */
27
+ date?: string
28
+ deadline?: string
29
+ evening: boolean
30
+ trashed: boolean
31
+ /** Its project's title. */
32
+ project?: string
33
+ /** The list's title, for a to-do in a shared list. */
34
+ spaceTitle?: string
35
+ }
36
+ /** A space this device syncs. `readOnly`: the user lost access; what was synced is kept. */
37
+ export type SpaceInfo = { space: string; kind: SpaceKind; title: string; readOnly: boolean }
38
+
39
+ /** A problem: a stable name (`Transport:Network`, `AccessLost:SpaceDeleted`, `Pull:Gap`…) and a description. */
40
+ export type Problem = { name: string; message: string }
41
+ /** What one `syncSpace` did. Nothing in it needs handling: it's for showing. */
42
+ export type SyncReport = {
43
+ pull: {
44
+ pulled: string[]
45
+ /** Repos re-read from a verified snapshot, and why. */
46
+ resynced: { repo: string; reason: Problem }[]
47
+ /** Repos that couldn't be read this time. */
48
+ failed: { repo: string; error: Problem }[]
49
+ }
50
+ flush: {
51
+ written: number
52
+ /** Writes the host refused (§8.5): dropped, and kept on the device for the user to see. */
53
+ rejected: { path: RecordPath; error: string; title?: string }[]
54
+ /** Records too large to write: they stay unsent. */
55
+ oversized: RecordPath[]
56
+ /** Background writes held back to keep the rate-limit reserve for edits. */
57
+ deferred: number
58
+ /** Why the flush stopped early, if it did. Unsent changes go next time. */
59
+ stopped?: Problem
60
+ }
61
+ }
62
+
63
+ export type RecordPath = { collection: string; rkey: string }
64
+ export type TransportError =
65
+ /** No response: the request may or may not have been applied. */
66
+ | { kind: 'network'; message: string }
67
+ /** A 5xx response, or one that doesn't parse or verify. */
68
+ | { kind: 'server'; status: number; message: string }
69
+ /** A 429: wait at least this long. */
70
+ | { kind: 'rateLimited'; retryAfterMs: number }
71
+ /** Any other XRPC error, by name (`RecordNotFound`, `InvalidRecord`, `SpaceDeleted`…). */
72
+ | { kind: 'xrpc'; status: number; error: string; message: string }
73
+ export type Result<T> = { ok: true; value: T } | { ok: false; error: TransportError }
74
+ /** An entry of `listWriters`; `repoRev` is absent for `repoRemoved`. TIDs are strings. */
75
+ export type WriterEntry = { repo: string; spaceRev: string; repoRev?: string }
76
+ export type WritersPage = { entries: WriterEntry[]; cursor?: string }
77
+ /** `com.atproto.space.defs#commit`, in its JSON form. */
78
+ export type Commit = { ver: number; repo: string; space: string; rev: string; data: { $bytes: string } }
79
+ /** `com.atproto.space.listRepoOps#opEntry`. CIDs are strings. */
80
+ export type OpEntry = { rev: string; path: RecordPath; cid?: string; prev?: string; value?: JsonValue }
81
+ export type OpsPage = { ops: OpEntry[]; commit: Commit; cursor?: string }
82
+ /** Every record of a repo, and the commit they should match. */
83
+ export type Snapshot = { commit: Commit; records: { path: RecordPath; cid: string; value: JsonValue }[] }
84
+ export type Write =
85
+ | { action: 'create' | 'update'; path: RecordPath; value: JsonValue }
86
+ | { action: 'delete'; path: RecordPath }
87
+ /** `RateLimit-*` headers; `resetMs` is epoch milliseconds. */
88
+ export type RateLimit = { limit: number; remaining: number; resetMs: number }
89
+ export type WriteOk = { rateLimit?: RateLimit }
90
+
91
+ /**
92
+ * The hosts, as the engine calls them (SPEC §8.2). An app implements this
93
+ * over its atproto client: it routes each call to the right host and
94
+ * handles OAuth, space credentials, request signatures and response MACs.
95
+ * Answer with a `Result`; a method that throws counts as a network error.
96
+ */
97
+ export interface Transport {
98
+ /** `listWriters` at the space host. `since` is a space revision. */
99
+ listWriters(space: string, since: string | undefined, cursor: string | undefined): Result<WritersPage> | Promise<Result<WritersPage>>
100
+ /** `listRepoOps` at the writer's PDS, its commit's MAC already checked. */
101
+ listRepoOps(space: string, repo: string, since: string, cursor: string | undefined): Result<OpsPage> | Promise<Result<OpsPage>>
102
+ /** `getRecord`: `value` absent for `RecordNotFound`. */
103
+ getRecord(space: string, repo: string, path: RecordPath): Result<{ cid: string; value: JsonValue } | undefined> | Promise<Result<{ cid: string; value: JsonValue } | undefined>>
104
+ /** A full copy of a repo (`getRepo`, or `listRecords` with `getLatestCommit`). */
105
+ getSnapshot(space: string, repo: string): Result<Snapshot> | Promise<Result<Snapshot>>
106
+ /** `applyWrites` to the user's own repo, as one atomic batch. */
107
+ applyWrites(space: string, writes: Write[]): Result<WriteOk> | Promise<Result<WriteOk>>
108
+ }
109
+
110
+ export type SavedOwnState = { record: JsonValue } | { exact: JsonValue } | 'delete'
111
+ export type SavedWriter = {
112
+ status: 'active' | { removed: { adoptAfterMs: number } }
113
+ listedRev?: string
114
+ /** The last verified commit: its rev, and the LtHash state (base64). */
115
+ head?: { rev: string; state: string }
116
+ /** By `collection/rkey`. */
117
+ records: { [path: string]: { cid: string; value: JsonValue } }
118
+ inactive?: string
119
+ }
120
+ /** A saved device (`Device.toJson`): plain JSON, to store as it is. */
121
+ export type DeviceJson = {
122
+ format: 1
123
+ me: string
124
+ clockId: number
125
+ /** A u64, in decimal. */
126
+ seed: string
127
+ budget: { blockedUntilMs: number; last?: RateLimit }
128
+ spaces: {
129
+ space: string
130
+ kind: SpaceKind
131
+ spaceRev?: string
132
+ access: 'readWrite' | { lost: { reason: string; retryAtMs: number } }
133
+ unlisted: boolean
134
+ writers: { [did: string]: SavedWriter }
135
+ own: { [path: string]: { state: SavedOwnState; userEdit: boolean } }
136
+ rejected: { [path: string]: { state: SavedOwnState; error: string } }
137
+ }[]
138
+ }
139
+
140
+ /** Thrown by an edit the engine refuses. `code`: `ReadOnly`, `NotFound`, `Deleted`, `TooLarge`, `InvalidValue`, `UnknownSpace`… */
141
+ export interface EditFailure extends Error { name: 'EditFailure'; code: string }
142
+ /** How `syncSpace` rejects when it can't sync the space at all. `code` is a `Problem` name. */
143
+ export interface SyncFailure extends Error { name: 'SyncFailure'; code: string }
144
+
145
+
146
+
147
+ /**
148
+ * One device's replica of the user's spaces.
149
+ */
150
+ export class Device {
151
+ free(): void;
152
+ [Symbol.dispose](): void;
153
+ /**
154
+ * Starts syncing a space; nothing if it's already synced.
155
+ */
156
+ addSpace(space: string, kind: SpaceKind): void;
157
+ /**
158
+ * Adds a to-do, with a fresh id from this device's clock.
159
+ */
160
+ addTodo(space: string, title: string, when: When, today: string, nowMicros: number): ObjectRef;
161
+ /**
162
+ * Deletes for good: every app stops showing it.
163
+ */
164
+ deleteForever(object: ObjectRef, nowMicros: number): void;
165
+ /**
166
+ * A device `toJson` saved. Throws on anything that doesn't read back
167
+ * exactly, rather than half-loading it.
168
+ */
169
+ static fromJson(saved: DeviceJson): Device;
170
+ /**
171
+ * The lists (SPEC §6) on `today` (`YYYY-MM-DD`, the user's local date).
172
+ */
173
+ lists(today: string): Lists;
174
+ /**
175
+ * A new device for the account `me`. `clockId` (0–1023) is this
176
+ * install's TID clock id, chosen at random once; `seed` seeds the
177
+ * jitter of its retries.
178
+ */
179
+ constructor(me: string, clockId: number, seed: bigint);
180
+ /**
181
+ * How many of the user's records have changes not yet on the hosts.
182
+ */
183
+ pending(): number;
184
+ personalSpace(): string | undefined;
185
+ /**
186
+ * What a list shows for each of `listed`.
187
+ */
188
+ rows(listed: Listed[], today: string): Row[];
189
+ /**
190
+ * When to do something: its own schedule in the personal space; in a
191
+ * shared list, the user's plan for it, which the others don't see.
192
+ */
193
+ schedule(object: ObjectRef, when: When, today: string, nowMicros: number): void;
194
+ /**
195
+ * Sets the notes; empty notes clear them.
196
+ */
197
+ setNotes(object: ObjectRef, notes: string, nowMicros: number): void;
198
+ setTitle(object: ObjectRef, title: string, nowMicros: number): void;
199
+ /**
200
+ * Every active to-do and project of one space, projects first, each in
201
+ * its order: a shared list's own list.
202
+ */
203
+ spaceList(space: string): Listed[];
204
+ /**
205
+ * "Personal", a shared list's title, or else its key.
206
+ */
207
+ spaceTitle(space: string): string;
208
+ /**
209
+ * Every space this device syncs.
210
+ */
211
+ spaces(): SpaceInfo[];
212
+ /**
213
+ * Syncs one space: pulls every writer, then sends the user's changes.
214
+ * Rejects with a `SyncFailure` only if the space couldn't be synced at
215
+ * all; problems with single repos or writes are in the report. Edits
216
+ * made meanwhile apply at once and are kept.
217
+ */
218
+ syncSpace(transport: Transport, space: string, nowMicros: number): Promise<SyncReport>;
219
+ /**
220
+ * The device's state, to keep between runs.
221
+ */
222
+ toJson(): DeviceJson;
223
+ /**
224
+ * Completes an open to-do, or reopens a closed one.
225
+ */
226
+ toggleDone(object: ObjectRef, nowMicros: number): void;
227
+ /**
228
+ * Moves to the Trash, or (`trashed: false`) puts back.
229
+ */
230
+ trash(object: ObjectRef, trashed: boolean, nowMicros: number): void;
231
+ readonly clockId: number;
232
+ /**
233
+ * The account's DID.
234
+ */
235
+ readonly me: string;
236
+ /**
237
+ * Whether a `syncSpace` is running.
238
+ */
239
+ readonly syncing: boolean;
240
+ }
241
+
242
+ /**
243
+ * An in-memory atproto network: a PDS per account and a space host,
244
+ * behaving as the reference implementations do. For demos and tests.
245
+ */
246
+ export class SimNetwork {
247
+ free(): void;
248
+ [Symbol.dispose](): void;
249
+ /**
250
+ * Lets `did` write to the space again.
251
+ */
252
+ allowWriter(space: string, did: string): void;
253
+ /**
254
+ * A transport for the account `did`.
255
+ */
256
+ client(did: string): SimTransport;
257
+ /**
258
+ * A space; `writers` and `readers` are the DIDs allowed (omitted:
259
+ * anyone, as for a personal space, which only its owner writes).
260
+ */
261
+ createSpace(space: string, writers?: string[] | null, readers?: string[] | null): void;
262
+ /**
263
+ * Fails a call `did` makes with `error`, unapplied: the next one, or
264
+ * the one after `skip` more have gone through.
265
+ */
266
+ fail(did: string, error: TransportError, skip?: number | null): void;
267
+ /**
268
+ * Applies the next `applyWrites` by `did`, but loses its response.
269
+ */
270
+ loseResponse(did: string): void;
271
+ constructor();
272
+ /**
273
+ * Takes `did` out of the space's writers.
274
+ */
275
+ removeWriter(space: string, did: string): void;
276
+ }
277
+
278
+ /**
279
+ * One account's view of a `SimNetwork`: a `Transport`. It answers through
280
+ * the same JSON boundary a real transport does.
281
+ */
282
+ export class SimTransport {
283
+ private constructor();
284
+ free(): void;
285
+ [Symbol.dispose](): void;
286
+ applyWrites(space: string, writes: Write[]): Promise<Result<WriteOk>>;
287
+ getRecord(space: string, repo: string, path: RecordPath): Promise<Result<{ cid: string; value: JsonValue } | undefined>>;
288
+ getSnapshot(space: string, repo: string): Promise<Result<Snapshot>>;
289
+ listRepoOps(space: string, repo: string, since: string, cursor?: string | null): Promise<Result<OpsPage>>;
290
+ listWriters(space: string, since?: string | null, cursor?: string | null): Promise<Result<WritersPage>>;
291
+ }