syncora 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/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ - Initial public release.
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aftab Ahmad Khan
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.
package/README.md ADDED
@@ -0,0 +1,149 @@
1
+ # syncora
2
+
3
+ **Topics:** `mern` · `mern-packages` · `merndev` · `mongodb` · `nodejs` · `npm-pm` · `observability` · `optimistic` · `react` · `realtime` · `subscription` · `sync` · `syncora` · `typescript` · `websocket`
4
+
5
+ Realtime sync engine for MERN apps. Subscribe to collections from the browser with a single hook, get live updates over WebSockets, mutate with optimistic UI, and reconnect transparently. Works with the built-in in-memory store, your MongoDB change stream, or any custom backing store you plug in.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install syncora
11
+ ```
12
+
13
+ (`react` is an optional peer for the React hook.)
14
+
15
+ ## Server
16
+
17
+ ```ts
18
+ import { createServer } from "node:http";
19
+ import { SyncServer } from "syncora";
20
+
21
+ const http = createServer();
22
+ const sync = new SyncServer({ server: http });
23
+
24
+ http.listen(4000);
25
+ ```
26
+
27
+ Or stand it up standalone:
28
+
29
+ ```ts
30
+ const sync = new SyncServer({ port: 4000 });
31
+ console.log("listening on", sync.address());
32
+ ```
33
+
34
+ Insert/update/delete via the store and every subscribed client gets the change:
35
+
36
+ ```ts
37
+ sync.store.insert("todos", { _id: "t1", title: "Buy milk", done: false });
38
+ sync.store.update("todos", "t1", { done: true });
39
+ sync.store.delete("todos", "t1");
40
+ ```
41
+
42
+ ### Plug in MongoDB change streams
43
+
44
+ ```ts
45
+ import { EventEmitter } from "node:events";
46
+ import { MongoClient } from "mongodb";
47
+
48
+ const emitter = new EventEmitter();
49
+ const off = sync.attachChangeStream(emitter);
50
+
51
+ const mongo = await MongoClient.connect(process.env.MONGODB_URI!);
52
+ const todos = mongo.db().collection("todos");
53
+ todos.watch().on("change", (event) => {
54
+ if (event.operationType === "insert") {
55
+ emitter.emit("change", {
56
+ type: "insert",
57
+ collection: "todos",
58
+ document: event.fullDocument,
59
+ version: Number(event.clusterTime.toString()),
60
+ });
61
+ }
62
+ // …handle update / delete similarly
63
+ });
64
+ ```
65
+
66
+ ## Vanilla client
67
+
68
+ ```ts
69
+ import { SyncoraClient } from "syncora";
70
+
71
+ const client = new SyncoraClient({ url: "ws://localhost:4000" });
72
+
73
+ const todos = client.subscribe("todos", { filter: { done: false } });
74
+ todos.onChange(({ data }) => console.log(data));
75
+
76
+ await client.mutate("todos", "insert", { document: { _id: "t9", title: "Ship it" } });
77
+ await client.mutate("todos", "update", { documentId: "t9", patch: { done: true } });
78
+ await client.mutate("todos", "delete", { documentId: "t9" });
79
+ ```
80
+
81
+ Reconnects with exponential back-off, replays queued mutations and resubscribes on every reconnect.
82
+
83
+ ## React hook
84
+
85
+ ```tsx
86
+ import { SyncoraClient } from "syncora";
87
+ import { createSyncoraHooks } from "syncora/react";
88
+
89
+ const client = new SyncoraClient({ url: "ws://localhost:4000" });
90
+ export const { useSyncora } = createSyncoraHooks(client);
91
+
92
+ export function Todos() {
93
+ const { data, insert, update, remove, isConnected } = useSyncora<{ _id: string; title: string; done: boolean }>(
94
+ "todos",
95
+ { filter: { done: false }, optimistic: true },
96
+ );
97
+
98
+ return (
99
+ <div>
100
+ <p>{isConnected ? "live" : "reconnecting…"}</p>
101
+ <ul>
102
+ {data.map((t) => (
103
+ <li key={t._id}>
104
+ <input type="checkbox" checked={t.done} onChange={() => update(t._id, { done: !t.done })} />
105
+ {t.title}
106
+ <button onClick={() => remove(t._id)}>delete</button>
107
+ </li>
108
+ ))}
109
+ </ul>
110
+ <button onClick={() => insert({ _id: crypto.randomUUID(), title: "New", done: false })}>add</button>
111
+ </div>
112
+ );
113
+ }
114
+ ```
115
+
116
+ With `optimistic: true`, mutations are applied to the local cache immediately and reconciled when the server acks (or reverted on the next snapshot).
117
+
118
+ ## Filter operators
119
+
120
+ `syncora` ships a tiny filter engine compatible with the most common MongoDB operators:
121
+
122
+ - equality and dotted paths (`{ "user.name": "alice" }`)
123
+ - `$eq`, `$ne`, `$in`, `$nin`, `$gt`, `$gte`, `$lt`, `$lte`, `$exists`
124
+ - `$or`, `$and`
125
+
126
+ ## Auth & permissions
127
+
128
+ ```ts
129
+ new SyncServer({
130
+ authorize: ({ headers }) => Boolean(headers["x-token"]),
131
+ permit: (clientId, message) =>
132
+ message.type !== "mutation" || message.collection !== "secrets",
133
+ });
134
+ ```
135
+
136
+ ## Custom stores
137
+
138
+ Implement the `SyncStore` interface to back syncora with Postgres, Redis, or anything else:
139
+
140
+ ```ts
141
+ import { SyncServer, type SyncStore } from "syncora";
142
+
143
+ const myStore: SyncStore = { /* … */ };
144
+ const sync = new SyncServer({ store: myStore });
145
+ ```
146
+
147
+ ## License
148
+
149
+ MIT
@@ -0,0 +1,116 @@
1
+ // src/filter.ts
2
+ function matches(doc, filter) {
3
+ if (!filter) return true;
4
+ for (const [key, expected] of Object.entries(filter)) {
5
+ if (key === "$or" && Array.isArray(expected)) {
6
+ if (!expected.some((sub) => matches(doc, sub))) return false;
7
+ continue;
8
+ }
9
+ if (key === "$and" && Array.isArray(expected)) {
10
+ if (!expected.every((sub) => matches(doc, sub))) return false;
11
+ continue;
12
+ }
13
+ const actual = lookupPath(doc, key);
14
+ if (!matchValue(actual, expected)) return false;
15
+ }
16
+ return true;
17
+ }
18
+ function matchValue(actual, expected) {
19
+ if (expected && typeof expected === "object" && !Array.isArray(expected)) {
20
+ const exp = expected;
21
+ if (Object.keys(exp).some((k) => k.startsWith("$"))) {
22
+ for (const [op, val] of Object.entries(exp)) {
23
+ switch (op) {
24
+ case "$eq":
25
+ if (actual !== val) return false;
26
+ break;
27
+ case "$ne":
28
+ if (actual === val) return false;
29
+ break;
30
+ case "$in":
31
+ if (!Array.isArray(val) || !val.includes(actual)) return false;
32
+ break;
33
+ case "$nin":
34
+ if (!Array.isArray(val) || val.includes(actual)) return false;
35
+ break;
36
+ case "$gt":
37
+ if (!(typeof actual === "number" && typeof val === "number" && actual > val)) return false;
38
+ break;
39
+ case "$gte":
40
+ if (!(typeof actual === "number" && typeof val === "number" && actual >= val)) return false;
41
+ break;
42
+ case "$lt":
43
+ if (!(typeof actual === "number" && typeof val === "number" && actual < val)) return false;
44
+ break;
45
+ case "$lte":
46
+ if (!(typeof actual === "number" && typeof val === "number" && actual <= val)) return false;
47
+ break;
48
+ case "$exists":
49
+ if (Boolean(val) !== (actual !== void 0)) return false;
50
+ break;
51
+ default:
52
+ return false;
53
+ }
54
+ }
55
+ return true;
56
+ }
57
+ }
58
+ return actual === expected;
59
+ }
60
+ function lookupPath(source, path) {
61
+ if (!path.includes(".")) return source[path];
62
+ let cur = source;
63
+ for (const part of path.split(".")) {
64
+ if (cur && typeof cur === "object" && part in cur) {
65
+ cur = cur[part];
66
+ } else {
67
+ return void 0;
68
+ }
69
+ }
70
+ return cur;
71
+ }
72
+
73
+ // src/apply.ts
74
+ function applyEventToDocuments(documents, version, event, filter) {
75
+ if (event.type === "snapshot") {
76
+ const next = event.documents.filter((d) => matches(d, filter));
77
+ return { data: next, version: event.version };
78
+ }
79
+ if (event.type === "insert") {
80
+ if (!matches(event.document, filter)) return { data: documents, version: event.version };
81
+ const next = [...documents.filter((d) => d._id !== event.document._id), event.document];
82
+ return { data: next, version: event.version };
83
+ }
84
+ if (event.type === "update") {
85
+ const next = documents.map(
86
+ (d) => d._id === event.documentId ? { ...d, ...event.patch, _id: d._id } : d
87
+ );
88
+ if (filter) {
89
+ const filtered = next.filter((d) => matches(d, filter));
90
+ return { data: filtered, version: event.version };
91
+ }
92
+ return { data: next, version: event.version };
93
+ }
94
+ if (event.type === "delete") {
95
+ return { data: documents.filter((d) => d._id !== event.documentId), version: event.version };
96
+ }
97
+ return { data: documents, version };
98
+ }
99
+ function applyOptimisticInsert(documents, document) {
100
+ return [...documents.filter((d) => d._id !== document._id), document];
101
+ }
102
+ function applyOptimisticUpdate(documents, id, patch) {
103
+ return documents.map((d) => d._id === id ? { ...d, ...patch, _id: id } : d);
104
+ }
105
+ function applyOptimisticDelete(documents, id) {
106
+ return documents.filter((d) => d._id !== id);
107
+ }
108
+
109
+ export {
110
+ matches,
111
+ applyEventToDocuments,
112
+ applyOptimisticInsert,
113
+ applyOptimisticUpdate,
114
+ applyOptimisticDelete
115
+ };
116
+ //# sourceMappingURL=chunk-VZXBPBHO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/filter.ts","../src/apply.ts"],"sourcesContent":["import type { Filter, SyncDocument } from \"./types.js\";\n\nexport function matches(doc: SyncDocument, filter: Filter | undefined): boolean {\n if (!filter) return true;\n for (const [key, expected] of Object.entries(filter)) {\n if (key === \"$or\" && Array.isArray(expected)) {\n if (!expected.some((sub) => matches(doc, sub as Filter))) return false;\n continue;\n }\n if (key === \"$and\" && Array.isArray(expected)) {\n if (!expected.every((sub) => matches(doc, sub as Filter))) return false;\n continue;\n }\n const actual = lookupPath(doc as Record<string, unknown>, key);\n if (!matchValue(actual, expected)) return false;\n }\n return true;\n}\n\nfunction matchValue(actual: unknown, expected: unknown): boolean {\n if (expected && typeof expected === \"object\" && !Array.isArray(expected)) {\n const exp = expected as Record<string, unknown>;\n if (Object.keys(exp).some((k) => k.startsWith(\"$\"))) {\n for (const [op, val] of Object.entries(exp)) {\n switch (op) {\n case \"$eq\": if (actual !== val) return false; break;\n case \"$ne\": if (actual === val) return false; break;\n case \"$in\":\n if (!Array.isArray(val) || !val.includes(actual)) return false;\n break;\n case \"$nin\":\n if (!Array.isArray(val) || val.includes(actual)) return false;\n break;\n case \"$gt\": if (!(typeof actual === \"number\" && typeof val === \"number\" && actual > val)) return false; break;\n case \"$gte\": if (!(typeof actual === \"number\" && typeof val === \"number\" && actual >= val)) return false; break;\n case \"$lt\": if (!(typeof actual === \"number\" && typeof val === \"number\" && actual < val)) return false; break;\n case \"$lte\": if (!(typeof actual === \"number\" && typeof val === \"number\" && actual <= val)) return false; break;\n case \"$exists\":\n if (Boolean(val) !== (actual !== undefined)) return false;\n break;\n default:\n return false;\n }\n }\n return true;\n }\n }\n return actual === expected;\n}\n\nfunction lookupPath(source: Record<string, unknown>, path: string): unknown {\n if (!path.includes(\".\")) return source[path];\n let cur: unknown = source;\n for (const part of path.split(\".\")) {\n if (cur && typeof cur === \"object\" && part in (cur as Record<string, unknown>)) {\n cur = (cur as Record<string, unknown>)[part];\n } else {\n return undefined;\n }\n }\n return cur;\n}\n","import { matches } from \"./filter.js\";\nimport type { ChangeEvent, Filter, SyncDocument } from \"./types.js\";\n\nexport function applyEventToDocuments<T extends SyncDocument>(\n documents: T[],\n version: number,\n event: ChangeEvent,\n filter?: Filter,\n): { data: T[]; version: number } {\n if (event.type === \"snapshot\") {\n const next = (event.documents as T[]).filter((d) => matches(d, filter));\n return { data: next, version: event.version };\n }\n if (event.type === \"insert\") {\n if (!matches(event.document, filter)) return { data: documents, version: event.version };\n const next = [...documents.filter((d) => d._id !== event.document._id), event.document as T];\n return { data: next, version: event.version };\n }\n if (event.type === \"update\") {\n const next = documents.map((d) =>\n d._id === event.documentId ? ({ ...d, ...event.patch, _id: d._id } as T) : d,\n );\n if (filter) {\n const filtered = next.filter((d) => matches(d, filter));\n return { data: filtered, version: event.version };\n }\n return { data: next, version: event.version };\n }\n if (event.type === \"delete\") {\n return { data: documents.filter((d) => d._id !== event.documentId), version: event.version };\n }\n return { data: documents, version };\n}\n\nexport function applyOptimisticInsert<T extends SyncDocument>(documents: T[], document: T): T[] {\n return [...documents.filter((d) => d._id !== document._id), document];\n}\n\nexport function applyOptimisticUpdate<T extends SyncDocument>(\n documents: T[],\n id: string,\n patch: Partial<T>,\n): T[] {\n return documents.map((d) => (d._id === id ? ({ ...d, ...patch, _id: id } as T) : d));\n}\n\nexport function applyOptimisticDelete<T extends SyncDocument>(documents: T[], id: string): T[] {\n return documents.filter((d) => d._id !== id);\n}\n"],"mappings":";AAEO,SAAS,QAAQ,KAAmB,QAAqC;AAC9E,MAAI,CAAC,OAAQ,QAAO;AACpB,aAAW,CAAC,KAAK,QAAQ,KAAK,OAAO,QAAQ,MAAM,GAAG;AACpD,QAAI,QAAQ,SAAS,MAAM,QAAQ,QAAQ,GAAG;AAC5C,UAAI,CAAC,SAAS,KAAK,CAAC,QAAQ,QAAQ,KAAK,GAAa,CAAC,EAAG,QAAO;AACjE;AAAA,IACF;AACA,QAAI,QAAQ,UAAU,MAAM,QAAQ,QAAQ,GAAG;AAC7C,UAAI,CAAC,SAAS,MAAM,CAAC,QAAQ,QAAQ,KAAK,GAAa,CAAC,EAAG,QAAO;AAClE;AAAA,IACF;AACA,UAAM,SAAS,WAAW,KAAgC,GAAG;AAC7D,QAAI,CAAC,WAAW,QAAQ,QAAQ,EAAG,QAAO;AAAA,EAC5C;AACA,SAAO;AACT;AAEA,SAAS,WAAW,QAAiB,UAA4B;AAC/D,MAAI,YAAY,OAAO,aAAa,YAAY,CAAC,MAAM,QAAQ,QAAQ,GAAG;AACxE,UAAM,MAAM;AACZ,QAAI,OAAO,KAAK,GAAG,EAAE,KAAK,CAAC,MAAM,EAAE,WAAW,GAAG,CAAC,GAAG;AACnD,iBAAW,CAAC,IAAI,GAAG,KAAK,OAAO,QAAQ,GAAG,GAAG;AAC3C,gBAAQ,IAAI;AAAA,UACV,KAAK;AAAO,gBAAI,WAAW,IAAK,QAAO;AAAO;AAAA,UAC9C,KA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O,SAAS,sBAA8C,WAAgB,IAAiB;AAC7F,SAAO,UAAU,OAAO,CAAC,MAAM,EAAE,QAAQ,EAAE;AAC7C;","names":[]}
@@ -0,0 +1,136 @@
1
+ interface SyncDocument {
2
+ _id: string;
3
+ [key: string]: unknown;
4
+ }
5
+ type ChangeEvent<T extends SyncDocument = SyncDocument> = {
6
+ type: "insert";
7
+ collection: string;
8
+ document: T;
9
+ version: number;
10
+ } | {
11
+ type: "update";
12
+ collection: string;
13
+ documentId: string;
14
+ patch: Partial<T>;
15
+ version: number;
16
+ } | {
17
+ type: "delete";
18
+ collection: string;
19
+ documentId: string;
20
+ version: number;
21
+ } | {
22
+ type: "snapshot";
23
+ collection: string;
24
+ documents: T[];
25
+ version: number;
26
+ };
27
+ type ClientMessage = {
28
+ type: "subscribe";
29
+ subscriptionId: string;
30
+ collection: string;
31
+ filter?: Record<string, unknown>;
32
+ } | {
33
+ type: "unsubscribe";
34
+ subscriptionId: string;
35
+ } | {
36
+ type: "mutation";
37
+ mutationId: string;
38
+ collection: string;
39
+ op: "insert" | "update" | "delete";
40
+ document?: SyncDocument;
41
+ patch?: Partial<SyncDocument>;
42
+ documentId?: string;
43
+ };
44
+ type ServerMessage = {
45
+ type: "hello";
46
+ clientId: string;
47
+ serverVersion: number;
48
+ } | {
49
+ type: "event";
50
+ subscriptionId: string;
51
+ event: ChangeEvent;
52
+ } | {
53
+ type: "ack";
54
+ mutationId: string;
55
+ ok: boolean;
56
+ error?: string;
57
+ } | {
58
+ type: "error";
59
+ message: string;
60
+ };
61
+ interface Filter {
62
+ [field: string]: unknown;
63
+ }
64
+ interface StoreSnapshot<T extends SyncDocument = SyncDocument> {
65
+ documents: T[];
66
+ version: number;
67
+ }
68
+
69
+ type WSLike = {
70
+ send(data: string): void;
71
+ close(): void;
72
+ addEventListener(event: "open", cb: () => void): void;
73
+ addEventListener(event: "close", cb: () => void): void;
74
+ addEventListener(event: "error", cb: (event: unknown) => void): void;
75
+ addEventListener(event: "message", cb: (event: {
76
+ data: unknown;
77
+ }) => void): void;
78
+ readyState?: number;
79
+ };
80
+ type WSConstructor = new (url: string) => WSLike;
81
+ interface SyncoraClientOptions {
82
+ url: string;
83
+ WebSocket?: WSConstructor;
84
+ reconnectDelayMs?: number;
85
+ maxReconnectDelayMs?: number;
86
+ onConnect?: (clientId: string) => void;
87
+ onDisconnect?: () => void;
88
+ onError?: (error: unknown) => void;
89
+ }
90
+ interface Subscription<T extends SyncDocument = SyncDocument> {
91
+ id: string;
92
+ collection: string;
93
+ filter?: Filter;
94
+ data: T[];
95
+ version: number;
96
+ unsubscribe(): void;
97
+ onChange(listener: (state: {
98
+ data: T[];
99
+ version: number;
100
+ }) => void): () => void;
101
+ }
102
+ declare class SyncoraClient {
103
+ private url;
104
+ private WS;
105
+ private socket?;
106
+ private subscriptions;
107
+ private pendingMutations;
108
+ private reconnectDelay;
109
+ private maxReconnectDelay;
110
+ private currentDelay;
111
+ private intentionalClose;
112
+ private clientId?;
113
+ private outbox;
114
+ private connectedListeners;
115
+ private disconnectedListeners;
116
+ private onError?;
117
+ constructor(options: SyncoraClientOptions);
118
+ isConnected(): boolean;
119
+ close(): void;
120
+ onConnect(handler: (clientId: string) => void): () => void;
121
+ onDisconnect(handler: () => void): () => void;
122
+ subscribe<T extends SyncDocument = SyncDocument>(collection: string, options?: {
123
+ filter?: Filter;
124
+ }): Subscription<T>;
125
+ mutate(collection: string, op: "insert" | "update" | "delete", payload?: {
126
+ document?: SyncDocument;
127
+ documentId?: string;
128
+ patch?: Partial<SyncDocument>;
129
+ }): Promise<void>;
130
+ private connect;
131
+ private scheduleReconnect;
132
+ private handleMessage;
133
+ private send;
134
+ }
135
+
136
+ export { type ChangeEvent as C, type Filter as F, type ServerMessage as S, type ClientMessage as a, type StoreSnapshot as b, type Subscription as c, type SyncDocument as d, SyncoraClient as e, type SyncoraClientOptions as f };
@@ -0,0 +1,136 @@
1
+ interface SyncDocument {
2
+ _id: string;
3
+ [key: string]: unknown;
4
+ }
5
+ type ChangeEvent<T extends SyncDocument = SyncDocument> = {
6
+ type: "insert";
7
+ collection: string;
8
+ document: T;
9
+ version: number;
10
+ } | {
11
+ type: "update";
12
+ collection: string;
13
+ documentId: string;
14
+ patch: Partial<T>;
15
+ version: number;
16
+ } | {
17
+ type: "delete";
18
+ collection: string;
19
+ documentId: string;
20
+ version: number;
21
+ } | {
22
+ type: "snapshot";
23
+ collection: string;
24
+ documents: T[];
25
+ version: number;
26
+ };
27
+ type ClientMessage = {
28
+ type: "subscribe";
29
+ subscriptionId: string;
30
+ collection: string;
31
+ filter?: Record<string, unknown>;
32
+ } | {
33
+ type: "unsubscribe";
34
+ subscriptionId: string;
35
+ } | {
36
+ type: "mutation";
37
+ mutationId: string;
38
+ collection: string;
39
+ op: "insert" | "update" | "delete";
40
+ document?: SyncDocument;
41
+ patch?: Partial<SyncDocument>;
42
+ documentId?: string;
43
+ };
44
+ type ServerMessage = {
45
+ type: "hello";
46
+ clientId: string;
47
+ serverVersion: number;
48
+ } | {
49
+ type: "event";
50
+ subscriptionId: string;
51
+ event: ChangeEvent;
52
+ } | {
53
+ type: "ack";
54
+ mutationId: string;
55
+ ok: boolean;
56
+ error?: string;
57
+ } | {
58
+ type: "error";
59
+ message: string;
60
+ };
61
+ interface Filter {
62
+ [field: string]: unknown;
63
+ }
64
+ interface StoreSnapshot<T extends SyncDocument = SyncDocument> {
65
+ documents: T[];
66
+ version: number;
67
+ }
68
+
69
+ type WSLike = {
70
+ send(data: string): void;
71
+ close(): void;
72
+ addEventListener(event: "open", cb: () => void): void;
73
+ addEventListener(event: "close", cb: () => void): void;
74
+ addEventListener(event: "error", cb: (event: unknown) => void): void;
75
+ addEventListener(event: "message", cb: (event: {
76
+ data: unknown;
77
+ }) => void): void;
78
+ readyState?: number;
79
+ };
80
+ type WSConstructor = new (url: string) => WSLike;
81
+ interface SyncoraClientOptions {
82
+ url: string;
83
+ WebSocket?: WSConstructor;
84
+ reconnectDelayMs?: number;
85
+ maxReconnectDelayMs?: number;
86
+ onConnect?: (clientId: string) => void;
87
+ onDisconnect?: () => void;
88
+ onError?: (error: unknown) => void;
89
+ }
90
+ interface Subscription<T extends SyncDocument = SyncDocument> {
91
+ id: string;
92
+ collection: string;
93
+ filter?: Filter;
94
+ data: T[];
95
+ version: number;
96
+ unsubscribe(): void;
97
+ onChange(listener: (state: {
98
+ data: T[];
99
+ version: number;
100
+ }) => void): () => void;
101
+ }
102
+ declare class SyncoraClient {
103
+ private url;
104
+ private WS;
105
+ private socket?;
106
+ private subscriptions;
107
+ private pendingMutations;
108
+ private reconnectDelay;
109
+ private maxReconnectDelay;
110
+ private currentDelay;
111
+ private intentionalClose;
112
+ private clientId?;
113
+ private outbox;
114
+ private connectedListeners;
115
+ private disconnectedListeners;
116
+ private onError?;
117
+ constructor(options: SyncoraClientOptions);
118
+ isConnected(): boolean;
119
+ close(): void;
120
+ onConnect(handler: (clientId: string) => void): () => void;
121
+ onDisconnect(handler: () => void): () => void;
122
+ subscribe<T extends SyncDocument = SyncDocument>(collection: string, options?: {
123
+ filter?: Filter;
124
+ }): Subscription<T>;
125
+ mutate(collection: string, op: "insert" | "update" | "delete", payload?: {
126
+ document?: SyncDocument;
127
+ documentId?: string;
128
+ patch?: Partial<SyncDocument>;
129
+ }): Promise<void>;
130
+ private connect;
131
+ private scheduleReconnect;
132
+ private handleMessage;
133
+ private send;
134
+ }
135
+
136
+ export { type ChangeEvent as C, type Filter as F, type ServerMessage as S, type ClientMessage as a, type StoreSnapshot as b, type Subscription as c, type SyncDocument as d, SyncoraClient as e, type SyncoraClientOptions as f };