@loro-dev/flock 1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,133 @@
1
+ # @loro-dev/flock
2
+
3
+ TypeScript bindings for the Flock Conflict-free Replicated Data Type (CRDT). Flock stores JSON-like values at composite keys, keeps causal metadata, and synchronises peers through mergeable export bundles. This package wraps the core MoonBit implementation and exposes a typed `Flock` class for JavaScript runtimes (Node.js ≥18, modern browsers, and workers).
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ pnpm add @loro-dev/flock
9
+ # or
10
+ npm install @loro-dev/flock
11
+ # or
12
+ yarn add @loro-dev/flock
13
+ ```
14
+
15
+ The library ships ESM, CommonJS, and TypeScript declaration files. It has no runtime dependencies beyond the standard Web Crypto API for secure peer identifiers (falls back to `Math.random` when unavailable).
16
+
17
+ ## Quick Start
18
+
19
+ ```ts
20
+ import { Flock } from "@loro-dev/flock";
21
+
22
+ // Each replica uses a stable 32-byte peer id to maintain version vectors.
23
+ const peerId = crypto.getRandomValues(new Uint8Array(32));
24
+ const store = new Flock(peerId);
25
+
26
+ store.put(["users", "42"], { name: "Ada", online: true });
27
+ console.log(store.get(["users", "42"]));
28
+
29
+ // Share incremental updates with a remote replica.
30
+ const bundle = store.exportJson();
31
+
32
+ // On another node, merge and materialise the same data.
33
+ const other = new Flock();
34
+ other.importJson(bundle);
35
+ other.merge(store);
36
+
37
+ // Subscribe to local or remote mutations.
38
+ const unsubscribe = store.subscribe(({ source, events }) => {
39
+ for (const { key, value } of events) {
40
+ console.log(`[${source}]`, key, value ?? "<deleted>");
41
+ }
42
+ });
43
+
44
+ store.delete(["users", "42"]);
45
+ unsubscribe();
46
+ ```
47
+
48
+ ## Replication Workflow
49
+
50
+ - Call `exportJson()` to serialise local changes since an optional version vector.
51
+ - Distribute bundles via your transport of choice (HTTP, WebSocket, etc.).
52
+ - Apply remote bundles with `importJson()` and reconcile replicas using `merge()`.
53
+ - Track causal progress with `version()` and `getMaxPhysicalTime()` when orchestrating incremental syncs.
54
+ - Use `Flock.checkConsistency()` in tests to assert that two replicas converged to the same state.
55
+
56
+ ## Type Basics
57
+
58
+ - `Value`: JSON-compatible data (`string`, `number`, `boolean`, `null`, nested arrays/objects).
59
+ - `KeyPart`: `string | number | boolean`. Keys are arrays of parts (e.g. `["users", 42]`). Invalid keys raise at runtime.
60
+ - `ExportRecord`: `{ c: string; d?: Value }` – CRDT payload with hybrid logical clock data.
61
+ - `ExportBundle`: `Record<string, ExportRecord>` mapping composite keys to last-writer metadata.
62
+ - `VersionVector`: `Record<string, { physicalTime: number; logicalCounter: number }>` indexed by hex peer identifiers.
63
+ - `ScanRow`: `{ key: KeyPart[]; raw: ExportRecord; value?: Value }` returned by `scan()`.
64
+ - `EventBatch`: `{ source: string; events: Array<{ key: KeyPart[]; value?: Value }> }` emitted to subscribers.
65
+
66
+ All types are exported from the package entry point for use in TypeScript projects.
67
+
68
+ ## API Reference
69
+
70
+ ### Constructor
71
+
72
+ `new Flock(peerId?: Uint8Array)` – creates a replica. When omitted, a random 256-bit peer id is generated. The id persists only in memory; persist it yourself for durable replicas.
73
+
74
+ ### Static Members
75
+
76
+ - `Flock.fromJson(bundle: ExportBundle, peerId: Uint8Array): Flock` – instantiate directly from a full snapshot bundle.
77
+ - `Flock.checkConsistency(a: Flock, b: Flock): boolean` – deep equality check useful for tests; returns `true` when both replicas expose the same key/value pairs and metadata.
78
+
79
+ ### Replica Management
80
+
81
+ - `setPeerId(peerId: Uint8Array): void` – replace the current peer id. Use cautiously; changing ids affects causality tracking.
82
+ - `peerId(): Uint8Array` – returns the 32-byte identifier for the replica.
83
+ - `getMaxPhysicalTime(): number` – highest physical timestamp observed by this replica (same units as the timestamps you pass to `now`, e.g. `Date.now()` output). Helpful for synchronising clocks and diagnosing divergence.
84
+ - `version(): VersionVector` – current version vector including logical counters per peer.
85
+ - `checkInvariants(): void` – throws if internal CRDT invariants are violated. Intended for assertions in tests or diagnostics, not for production control flow.
86
+
87
+ ### Mutations
88
+
89
+ - `put(key: KeyPart[], value: Value, now?: number): void` – write a JSON value. The optional `now` overrides the physical time (numeric timestamp such as `Date.now()` output) used for the replica’s hybrid logical clock. Invalid keys or non-finite timestamps throw.
90
+ - `set(key: KeyPart[], value: Value, now?: number): void` – alias of `put` for frameworks that prefer “set” terminology.
91
+ - `delete(key: KeyPart[], now?: number): void` – tombstone a key. The optional time override follows the same rules as `put`.
92
+ - `putMvr(key: KeyPart[], value: Value, now?: number): void` – attach a value to the key’s Multi-Value Register. Unlike `put`, concurrent writes remain alongside each other.
93
+
94
+ ### Reads
95
+
96
+ - `get(key: KeyPart[]): Value | undefined` – fetch the latest visible value. Deleted keys resolve to `undefined`.
97
+ - `getMvr(key: KeyPart[]): Value[]` – read all concurrent values associated with a key’s Multi-Value Register (empty array when unset).
98
+ - `kvToJson(): ExportBundle` – snapshot of every key/value pair including tombstones. Useful for debugging or serialising the entire store.
99
+ - `scan(options?: ScanOptions): ScanRow[]` – in-order range scan. Supports:
100
+ - `start` / `end`: `{ kind: "inclusive" | "exclusive"; key: KeyPart[] }` or `{ kind: "unbounded" }`.
101
+ - `prefix`: restrict results to keys beginning with the provided prefix.
102
+ Results include the materialised value (if any) and raw CRDT record.
103
+
104
+ ### Replication
105
+
106
+ - `exportJson(from?: VersionVector): ExportBundle` – export causal updates. Provide a `VersionVector` from a remote replica to stream only novel changes; omit to export the entire dataset.
107
+ - `importJson(bundle: ExportBundle): void` – apply a bundle received from another replica. Invalid payloads throw.
108
+ - `merge(other: Flock): void` – merge another replica instance directly (both replicas end up with the joined state).
109
+
110
+ ### Events
111
+
112
+ - `subscribe(listener: (batch: EventBatch) => void): () => void` – register for mutation batches. Each callback receives the `source` ("local" for writes on this replica, peer id for remote batches when available) and an ordered list of events. Return value unsubscribes the listener.
113
+
114
+ ### Utilities
115
+
116
+ - `exportJson`, `importJson`, `kvToJson`, and `fromJson` all work with plain JavaScript objects, so they serialise cleanly through JSON or structured clone.
117
+ - Keys are encoded using MoonBit’s memcomparable format; use simple scalars and natural ordering for predictable scans.
118
+
119
+ ## Error Handling
120
+
121
+ - Methods that accept keys validate them at runtime. Passing unsupported key parts (like objects or `undefined`) throws a `TypeError`.
122
+ - Passing malformed bundles or version vectors throws a `TypeError` or propagates an underlying runtime error from the native module.
123
+ - Always wrap replication IO in `try/catch` when dealing with untrusted data.
124
+
125
+ ## Testing Tips
126
+
127
+ - Use `Flock.checkConsistency()` to assert two replicas match after a sequence of operations.
128
+ - `checkInvariants()` is safe inside unit tests to catch bugs in integration layers.
129
+ - Vitest users can combine `exportJson` snapshots with `expect` to capture deterministic state transitions.
130
+
131
+ ## License
132
+
133
+ MIT © Loro contributors
@@ -0,0 +1,145 @@
1
+ //#region src/index.d.ts
2
+ type MaybePromise<T> = T | Promise<T>;
3
+ type ExportOptions = {
4
+ from?: VersionVector;
5
+ hooks?: ExportHooks;
6
+ };
7
+ type ImportOptions = {
8
+ bundle: ExportBundle;
9
+ hooks?: ImportHooks;
10
+ };
11
+ type VersionVectorEntry = {
12
+ physicalTime: number;
13
+ logicalCounter: number;
14
+ };
15
+ type VersionVector = Record<string, VersionVectorEntry>;
16
+ type Value = string | number | boolean | null | Array<Value> | {
17
+ [key: string]: Value;
18
+ };
19
+ type KeyPart = Value;
20
+ type MetadataMap = Record<string, unknown>;
21
+ type ExportRecord = {
22
+ c: string;
23
+ d?: Value;
24
+ m?: MetadataMap;
25
+ };
26
+ type ExportBundle = Record<string, ExportRecord>;
27
+ type EntryClock = {
28
+ physicalTime: number;
29
+ logicalCounter: number;
30
+ peerIdHex: string;
31
+ peerId: Uint8Array;
32
+ };
33
+ type ExportPayload = {
34
+ data?: Value;
35
+ metadata?: MetadataMap;
36
+ };
37
+ type ExportHookContext = {
38
+ key: KeyPart[];
39
+ clock: EntryClock;
40
+ raw: ExportRecord;
41
+ };
42
+ type ExportHooks = {
43
+ transform?: (context: ExportHookContext, payload: ExportPayload) => MaybePromise<ExportPayload | void>;
44
+ };
45
+ type ImportPayload = ExportPayload;
46
+ type ImportHookContext = ExportHookContext;
47
+ type ImportAccept = {
48
+ accept: true;
49
+ };
50
+ type ImportSkip = {
51
+ accept: false;
52
+ reason: string;
53
+ };
54
+ type ImportDecision = ImportAccept | ImportSkip | ImportPayload | void;
55
+ type ImportHooks = {
56
+ preprocess?: (context: ImportHookContext, payload: ImportPayload) => MaybePromise<ImportDecision>;
57
+ };
58
+ type ImportReport = {
59
+ accepted: number;
60
+ skipped: Array<{
61
+ key: KeyPart[];
62
+ reason: string;
63
+ }>;
64
+ };
65
+ type PutPayload = ExportPayload;
66
+ type PutHookContext = {
67
+ key: KeyPart[];
68
+ now?: number;
69
+ };
70
+ type PutHooks = {
71
+ transform?: (context: PutHookContext, payload: PutPayload) => MaybePromise<PutPayload | void>;
72
+ };
73
+ type PutWithMetaOptions = {
74
+ metadata?: MetadataMap;
75
+ now?: number;
76
+ hooks?: PutHooks;
77
+ };
78
+ type ScanBound = {
79
+ kind: "inclusive";
80
+ key: KeyPart[];
81
+ } | {
82
+ kind: "exclusive";
83
+ key: KeyPart[];
84
+ } | {
85
+ kind: "unbounded";
86
+ };
87
+ type ScanOptions = {
88
+ start?: ScanBound;
89
+ end?: ScanBound;
90
+ prefix?: KeyPart[];
91
+ };
92
+ type ScanRow = {
93
+ key: KeyPart[];
94
+ raw: ExportRecord;
95
+ value?: Value;
96
+ };
97
+ type EventPayload = ExportPayload;
98
+ type Event = {
99
+ key: KeyPart[];
100
+ value?: Value;
101
+ metadata?: MetadataMap;
102
+ payload: EventPayload;
103
+ };
104
+ type EventBatch = {
105
+ source: string;
106
+ events: Event[];
107
+ };
108
+ declare class Flock {
109
+ private inner;
110
+ constructor(peerId?: Uint8Array);
111
+ private static fromInner;
112
+ static fromJson(bundle: ExportBundle, peerId: Uint8Array): Flock;
113
+ static checkConsistency(a: Flock, b: Flock): boolean;
114
+ checkInvariants(): void;
115
+ setPeerId(peerId: Uint8Array): void;
116
+ private putWithMetaInternal;
117
+ private putWithMetaWithHooks;
118
+ put(key: KeyPart[], value: Value, now?: number): void;
119
+ putWithMeta(key: KeyPart[], value: Value, options?: PutWithMetaOptions): void | Promise<void>;
120
+ set(key: KeyPart[], value: Value, now?: number): void;
121
+ delete(key: KeyPart[], now?: number): void;
122
+ get(key: KeyPart[]): Value | undefined;
123
+ merge(other: Flock): void;
124
+ version(): VersionVector;
125
+ private exportJsonInternal;
126
+ private exportJsonWithHooks;
127
+ exportJson(): ExportBundle;
128
+ exportJson(from: VersionVector): ExportBundle;
129
+ exportJson(options: ExportOptions): Promise<ExportBundle>;
130
+ private importJsonInternal;
131
+ private importJsonWithHooks;
132
+ importJson(bundle: ExportBundle): ImportReport;
133
+ importJson(options: ImportOptions): Promise<ImportReport>;
134
+ getMaxPhysicalTime(): number;
135
+ peerId(): Uint8Array;
136
+ digest(): string;
137
+ kvToJson(): ExportBundle;
138
+ putMvr(key: KeyPart[], value: Value, now?: number): void;
139
+ getMvr(key: KeyPart[]): Value[];
140
+ scan(options?: ScanOptions): ScanRow[];
141
+ subscribe(listener: (batch: EventBatch) => void): () => void;
142
+ }
143
+ //#endregion
144
+ export { EntryClock, Event, EventBatch, EventPayload, ExportBundle, ExportHookContext, ExportHooks, ExportPayload, ExportRecord, Flock, ImportAccept, ImportDecision, ImportHookContext, ImportHooks, ImportPayload, ImportReport, ImportSkip, KeyPart, MetadataMap, PutHookContext, PutHooks, PutPayload, PutWithMetaOptions, ScanBound, ScanOptions, ScanRow, Value, VersionVector, VersionVectorEntry };
145
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1,145 @@
1
+ //#region src/index.d.ts
2
+ type MaybePromise<T> = T | Promise<T>;
3
+ type ExportOptions = {
4
+ from?: VersionVector;
5
+ hooks?: ExportHooks;
6
+ };
7
+ type ImportOptions = {
8
+ bundle: ExportBundle;
9
+ hooks?: ImportHooks;
10
+ };
11
+ type VersionVectorEntry = {
12
+ physicalTime: number;
13
+ logicalCounter: number;
14
+ };
15
+ type VersionVector = Record<string, VersionVectorEntry>;
16
+ type Value = string | number | boolean | null | Array<Value> | {
17
+ [key: string]: Value;
18
+ };
19
+ type KeyPart = Value;
20
+ type MetadataMap = Record<string, unknown>;
21
+ type ExportRecord = {
22
+ c: string;
23
+ d?: Value;
24
+ m?: MetadataMap;
25
+ };
26
+ type ExportBundle = Record<string, ExportRecord>;
27
+ type EntryClock = {
28
+ physicalTime: number;
29
+ logicalCounter: number;
30
+ peerIdHex: string;
31
+ peerId: Uint8Array;
32
+ };
33
+ type ExportPayload = {
34
+ data?: Value;
35
+ metadata?: MetadataMap;
36
+ };
37
+ type ExportHookContext = {
38
+ key: KeyPart[];
39
+ clock: EntryClock;
40
+ raw: ExportRecord;
41
+ };
42
+ type ExportHooks = {
43
+ transform?: (context: ExportHookContext, payload: ExportPayload) => MaybePromise<ExportPayload | void>;
44
+ };
45
+ type ImportPayload = ExportPayload;
46
+ type ImportHookContext = ExportHookContext;
47
+ type ImportAccept = {
48
+ accept: true;
49
+ };
50
+ type ImportSkip = {
51
+ accept: false;
52
+ reason: string;
53
+ };
54
+ type ImportDecision = ImportAccept | ImportSkip | ImportPayload | void;
55
+ type ImportHooks = {
56
+ preprocess?: (context: ImportHookContext, payload: ImportPayload) => MaybePromise<ImportDecision>;
57
+ };
58
+ type ImportReport = {
59
+ accepted: number;
60
+ skipped: Array<{
61
+ key: KeyPart[];
62
+ reason: string;
63
+ }>;
64
+ };
65
+ type PutPayload = ExportPayload;
66
+ type PutHookContext = {
67
+ key: KeyPart[];
68
+ now?: number;
69
+ };
70
+ type PutHooks = {
71
+ transform?: (context: PutHookContext, payload: PutPayload) => MaybePromise<PutPayload | void>;
72
+ };
73
+ type PutWithMetaOptions = {
74
+ metadata?: MetadataMap;
75
+ now?: number;
76
+ hooks?: PutHooks;
77
+ };
78
+ type ScanBound = {
79
+ kind: "inclusive";
80
+ key: KeyPart[];
81
+ } | {
82
+ kind: "exclusive";
83
+ key: KeyPart[];
84
+ } | {
85
+ kind: "unbounded";
86
+ };
87
+ type ScanOptions = {
88
+ start?: ScanBound;
89
+ end?: ScanBound;
90
+ prefix?: KeyPart[];
91
+ };
92
+ type ScanRow = {
93
+ key: KeyPart[];
94
+ raw: ExportRecord;
95
+ value?: Value;
96
+ };
97
+ type EventPayload = ExportPayload;
98
+ type Event = {
99
+ key: KeyPart[];
100
+ value?: Value;
101
+ metadata?: MetadataMap;
102
+ payload: EventPayload;
103
+ };
104
+ type EventBatch = {
105
+ source: string;
106
+ events: Event[];
107
+ };
108
+ declare class Flock {
109
+ private inner;
110
+ constructor(peerId?: Uint8Array);
111
+ private static fromInner;
112
+ static fromJson(bundle: ExportBundle, peerId: Uint8Array): Flock;
113
+ static checkConsistency(a: Flock, b: Flock): boolean;
114
+ checkInvariants(): void;
115
+ setPeerId(peerId: Uint8Array): void;
116
+ private putWithMetaInternal;
117
+ private putWithMetaWithHooks;
118
+ put(key: KeyPart[], value: Value, now?: number): void;
119
+ putWithMeta(key: KeyPart[], value: Value, options?: PutWithMetaOptions): void | Promise<void>;
120
+ set(key: KeyPart[], value: Value, now?: number): void;
121
+ delete(key: KeyPart[], now?: number): void;
122
+ get(key: KeyPart[]): Value | undefined;
123
+ merge(other: Flock): void;
124
+ version(): VersionVector;
125
+ private exportJsonInternal;
126
+ private exportJsonWithHooks;
127
+ exportJson(): ExportBundle;
128
+ exportJson(from: VersionVector): ExportBundle;
129
+ exportJson(options: ExportOptions): Promise<ExportBundle>;
130
+ private importJsonInternal;
131
+ private importJsonWithHooks;
132
+ importJson(bundle: ExportBundle): ImportReport;
133
+ importJson(options: ImportOptions): Promise<ImportReport>;
134
+ getMaxPhysicalTime(): number;
135
+ peerId(): Uint8Array;
136
+ digest(): string;
137
+ kvToJson(): ExportBundle;
138
+ putMvr(key: KeyPart[], value: Value, now?: number): void;
139
+ getMvr(key: KeyPart[]): Value[];
140
+ scan(options?: ScanOptions): ScanRow[];
141
+ subscribe(listener: (batch: EventBatch) => void): () => void;
142
+ }
143
+ //#endregion
144
+ export { EntryClock, Event, EventBatch, EventPayload, ExportBundle, ExportHookContext, ExportHooks, ExportPayload, ExportRecord, Flock, ImportAccept, ImportDecision, ImportHookContext, ImportHooks, ImportPayload, ImportReport, ImportSkip, KeyPart, MetadataMap, PutHookContext, PutHooks, PutPayload, PutWithMetaOptions, ScanBound, ScanOptions, ScanRow, Value, VersionVector, VersionVectorEntry };
145
+ //# sourceMappingURL=index.d.ts.map