loro-repo 0.0.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 ADDED
@@ -0,0 +1,132 @@
1
+ # LoroRepo TypeScript bindings
2
+
3
+ LoroRepo is the collection-sync layer that sits above Flock. It keeps document metadata, CRDT bodies, and binary assets coordinated so apps can:
4
+
5
+ - fetch metadata first, then stream document bodies on demand,
6
+ - reuse the same API across centralized servers, Durable Objects, or peer-to-peer transports,
7
+ - progressively add asset sync, encryption, and garbage collection without changing app code.
8
+
9
+ ## What you get
10
+
11
+ - **Metadata-first coordination** – `repo.listDoc()` and `repo.watch()` expose LWW metadata so UIs can render collections before bodies arrive.
12
+ - **On-demand documents** – `openCollaborativeDoc()` gives you a repo-managed `LoroDoc` that persists and syncs automatically; `openDetachedDoc()` is a read-only snapshot.
13
+ - **Binary asset orchestration** – `linkAsset()`/`fetchAsset()` dedupe SHA-256 addressed blobs across docs, while `gcAssets()` sweeps unreferenced payloads.
14
+ - **Pluggable adapters** – supply your own `TransportAdapter`, `StorageAdapter`, and `AssetTransportAdapter` (or use the built-ins below) to target servers, CF Durable Objects, or local-first meshes.
15
+ - **Consistent events** – every event includes `by: "local" | "sync" | "live"` so you can react differently to local edits, explicit sync pulls, or realtime merges.
16
+
17
+ ## Quick start
18
+
19
+ ```ts
20
+ import {
21
+ LoroRepo,
22
+ BroadcastChannelTransportAdapter,
23
+ IndexedDBStorageAdaptor,
24
+ } from "loro-repo";
25
+ import { LoroDoc } from "loro-crdt";
26
+
27
+ type DocMeta = { title?: string; tags?: string[] };
28
+
29
+ const repo = new LoroRepo<DocMeta>({
30
+ transportAdapter: new BroadcastChannelTransportAdapter({ namespace: "notes" }),
31
+ storageAdapter: new IndexedDBStorageAdaptor({ dbName: "notes-db" }),
32
+ docFactory: async () => new LoroDoc(),
33
+ });
34
+
35
+ await repo.ready();
36
+ await repo.sync({ scope: "meta" }); // metadata-first
37
+
38
+ await repo.upsertDocMeta("note:welcome", { title: "Welcome" });
39
+
40
+ const handle = await repo.openCollaborativeDoc("note:welcome");
41
+ await handle.whenSyncedWithRemote;
42
+ handle.doc.getText("content").insert(0, "Hello from LoroRepo");
43
+ handle.doc.commit();
44
+ await handle.close();
45
+ ```
46
+
47
+ ## Using the API
48
+
49
+ - **Define your metadata contract** once via `new LoroRepo<Meta>()`. All metadata helpers (`upsertDocMeta`, `getDocMeta`, `listDoc`, `watch`) stay type-safe.
50
+ - **Choose sync lanes** with `repo.sync({ scope: "meta" | "doc" | "full", docIds?: string[] })` to pull remote changes on demand.
51
+ - **Join realtime rooms** by calling `joinMetaRoom()` / `joinDocRoom(docId)`; the behaviour depends entirely on the transport adapter you injected.
52
+ - **Manage assets** through `linkAsset`, `uploadAsset`, `fetchAsset` (alias `ensureAsset`), `listAssets`, and `gcAssets({ minKeepMs })`.
53
+ - **React to changes** by subscribing with `repo.watch(listener, { docIds, kinds, metadataFields, by })`.
54
+ - **Shut down cleanly** via `await repo.close()` to flush snapshots and dispose adapters.
55
+
56
+ ## Built-in adapters
57
+
58
+ - `BroadcastChannelTransportAdapter` (`src/transport/broadcast-channel.ts`)
59
+ Same-origin peer-to-peer transport that lets browser tabs exchange metadata/doc deltas through the BroadcastChannel API. Perfect for demos, offline PWAs, or local-first UIs; used in the quick-start snippet and the P2P Journal example.
60
+
61
+ - `WebSocketTransportAdapter` (`src/transport/websocket.ts`)
62
+ loro-websocket powered transport for centralized servers or Durable Objects. Provide `url`, `metadataRoomId`, and optional auth callbacks and it handles join/sync lifecycles for you:
63
+
64
+ ```ts
65
+ import { WebSocketTransportAdapter } from "loro-repo";
66
+
67
+ const transport = new WebSocketTransportAdapter({
68
+ url: "wss://sync.example.com/repo",
69
+ metadataRoomId: "workspace:meta",
70
+ docAuth: (docId) => authFor(docId),
71
+ });
72
+ ```
73
+
74
+ - `IndexedDBStorageAdaptor` (`src/storage/indexeddb.ts`)
75
+ Browser storage for metadata snapshots, doc snapshots/updates, and cached assets. Swap it out for SQLite/LevelDB/file-system adaptors when running on desktop or server environments.
76
+
77
+ - Asset transports
78
+ Bring your own `AssetTransportAdapter` (HTTP uploads, peer meshes, S3, etc.). LoroRepo dedupes via SHA-256 assetIds while your adaptor decides how to encrypt/store the bytes.
79
+
80
+ ## Core API surface
81
+
82
+ **Lifecycle**
83
+ - `new LoroRepo<Meta>(options)` – wire adapters (`transportAdapter`, `storageAdapter`, `assetTransportAdapter`, `docFactory`, `docFrontierDebounceMs`).
84
+ - `await repo.ready()` – hydrate metadata snapshot before touching docs.
85
+ - `await repo.sync({ scope: "meta" | "doc" | "full", docIds?: string[] })` – pull remote updates on demand.
86
+ - `await repo.close()` – persist pending work and dispose adapters.
87
+
88
+ **Metadata**
89
+ - `await repo.upsertDocMeta(docId, patch)` – LWW merge with your `Meta` type.
90
+ - `await repo.getDocMeta(docId)` – clone the stored metadata (or `undefined`).
91
+ - `await repo.listDoc(query?)` – list docs by prefix/range/limit (`RepoDocMeta<Meta>[]`).
92
+ - `repo.getMetaReplica()` – access raw `Flock` if you need advanced scans.
93
+
94
+ **Documents**
95
+ - `await repo.openCollaborativeDoc(docId)` – returns `{ doc, whenSyncedWithRemote, close }`; mutations persist and sync automatically.
96
+ - `await repo.openDetachedDoc(docId)` – isolated snapshot handle (no persistence, no live sync) ideal for read-only tasks.
97
+ - `await repo.whenDocInSyncWithRemote(docId)` – ensure a document caught up without opening it.
98
+ - `await repo.joinDocRoom(docId, params?)` – spawn a realtime session through your transport; use `subscription.unsubscribe()` when done.
99
+
100
+ **Assets**
101
+ - `await repo.linkAsset(docId, { content, mime?, tag?, policy?, assetId?, createdAt? })` – upload + link, returning the SHA-256 assetId.
102
+ - `await repo.uploadAsset(options)` – upload without linking to a doc (pre-warm caches).
103
+ - `await repo.fetchAsset(assetId)` / `ensureAsset(assetId)` – fetch metadata + lazy `content()` stream (prefers cached blobs).
104
+ - `await repo.listAssets(docId)` – view linked assets (`RepoAssetMetadata[]`).
105
+ - `await repo.unlinkAsset(docId, assetId)` – drop a link; GC picks up orphans.
106
+ - `await repo.gcAssets({ minKeepMs, batchSize })` – sweep stale unlinked blobs via the storage adapter.
107
+
108
+ **Events**
109
+ - `const handle = repo.watch(listener, { docIds, kinds, metadataFields, by })` – subscribe to `RepoEvent` unions (metadata/frontiers/asset lifecycle) with provenance.
110
+ - `handle.unsubscribe()` – stop receiving events.
111
+
112
+ **Realtime metadata**
113
+ - `await repo.joinMetaRoom(params?)` – opt into live metadata sync via the transport adapter; call `subscription.unsubscribe()` to leave.
114
+
115
+ ## Commands
116
+
117
+ | Command | Purpose |
118
+ | --- | --- |
119
+ | `pnpm --filter loro-repo typecheck` | Runs `tsc` with `noEmit`. |
120
+ | `pnpm --filter loro-repo test` | Executes the Vitest suites. |
121
+ | `pnpm --filter loro-repo check` | Runs typecheck + tests. |
122
+
123
+ Set `LORO_WEBSOCKET_E2E=1` when you want to run the websocket end-to-end spec.
124
+
125
+ ## Examples
126
+
127
+ - **P2P Journal (`examples/p2p-journal/`)** – Vite + React demo that pairs `BroadcastChannelTransportAdapter` with `IndexedDBStorageAdaptor` for tab-to-tab sync.
128
+ - **Sync script (`examples/sync-example.ts`)** – Node-based walkthrough that sets up two repos, a memory transport hub, and an in-memory filesystem to illustrate metadata-first fetch, selective doc sync, and asset flows.
129
+
130
+ ## Contributing
131
+
132
+ Follow Conventional Commits, run `pnpm --filter loro-repo check` before opening a PR, and reference the “LoroRepo Product Requirements” doc when explaining behavioural changes (metadata-first fetch, pluggable adapters, progressive encryption/GC). Keep generated artifacts in sync and avoid committing build outputs such as `target/`. If you add a new workflow or feature, link the relevant `prd/` entry so the intent stays discoverable.