reflectdb 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.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1260 -0
  3. package/dist/cjs/client/index.cjs +1252 -0
  4. package/dist/cjs/client/index.d.cts +629 -0
  5. package/dist/cjs/client/storage/indexeddb.cjs +253 -0
  6. package/dist/cjs/client/storage/indexeddb.d.cts +85 -0
  7. package/dist/cjs/core/index.cjs +202 -0
  8. package/dist/cjs/core/index.d.cts +473 -0
  9. package/dist/cjs/react/index.cjs +1512 -0
  10. package/dist/cjs/react/index.d.cts +748 -0
  11. package/dist/cjs/server/drizzle.cjs +413 -0
  12. package/dist/cjs/server/drizzle.d.cts +233 -0
  13. package/dist/cjs/server/index.cjs +4486 -0
  14. package/dist/cjs/server/index.d.cts +1988 -0
  15. package/dist/cjs/svelte/index.cjs +1414 -0
  16. package/dist/cjs/svelte/index.d.cts +645 -0
  17. package/dist/cjs/transport/bun-ws.cjs +244 -0
  18. package/dist/cjs/transport/bun-ws.d.cts +215 -0
  19. package/dist/cjs/transport/polling.cjs +285 -0
  20. package/dist/cjs/transport/polling.d.cts +210 -0
  21. package/dist/cjs/transport/sse.cjs +312 -0
  22. package/dist/cjs/transport/sse.d.cts +205 -0
  23. package/dist/cjs/transport/ws.cjs +330 -0
  24. package/dist/cjs/transport/ws.d.cts +236 -0
  25. package/dist/cjs/vanilla/index.cjs +1430 -0
  26. package/dist/cjs/vanilla/index.d.cts +657 -0
  27. package/dist/client/index.d.ts +629 -0
  28. package/dist/client/index.js +106 -0
  29. package/dist/client/storage/indexeddb.d.ts +85 -0
  30. package/dist/client/storage/indexeddb.js +213 -0
  31. package/dist/core/index.d.ts +473 -0
  32. package/dist/core/index.js +56 -0
  33. package/dist/react/index.d.ts +748 -0
  34. package/dist/react/index.js +366 -0
  35. package/dist/server/drizzle.d.ts +233 -0
  36. package/dist/server/drizzle.js +9 -0
  37. package/dist/server/index.d.ts +1988 -0
  38. package/dist/server/index.js +3959 -0
  39. package/dist/shared/esm-3tkwvysa.js +54 -0
  40. package/dist/shared/esm-b7xs9cde.js +4 -0
  41. package/dist/shared/esm-rw7jjtrv.js +58 -0
  42. package/dist/shared/esm-wkwx6bd9.js +25 -0
  43. package/dist/shared/esm-ytrd3hbq.js +1007 -0
  44. package/dist/shared/esm-z1xse19c.js +369 -0
  45. package/dist/svelte/index.d.ts +645 -0
  46. package/dist/svelte/index.js +262 -0
  47. package/dist/transport/bun-ws.d.ts +215 -0
  48. package/dist/transport/bun-ws.js +140 -0
  49. package/dist/transport/polling.d.ts +210 -0
  50. package/dist/transport/polling.js +181 -0
  51. package/dist/transport/sse.d.ts +205 -0
  52. package/dist/transport/sse.js +208 -0
  53. package/dist/transport/ws.d.ts +236 -0
  54. package/dist/transport/ws.js +226 -0
  55. package/dist/vanilla/index.d.ts +657 -0
  56. package/dist/vanilla/index.js +278 -0
  57. package/package.json +253 -0
@@ -0,0 +1,244 @@
1
+ var import_node_module = require("node:module");
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ function __accessProp(key) {
7
+ return this[key];
8
+ }
9
+ var __toCommonJS = (from) => {
10
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
11
+ if (entry)
12
+ return entry;
13
+ entry = __defProp({}, "__esModule", { value: true });
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (var key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(entry, key))
17
+ __defProp(entry, key, {
18
+ get: __accessProp.bind(from, key),
19
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
20
+ });
21
+ }
22
+ __moduleCache.set(from, entry);
23
+ return entry;
24
+ };
25
+ var __moduleCache;
26
+ var __returnValue = (v) => v;
27
+ function __exportSetter(name, newValue) {
28
+ this[name] = __returnValue.bind(null, newValue);
29
+ }
30
+ var __export = (target, all) => {
31
+ for (var name in all)
32
+ __defProp(target, name, {
33
+ get: all[name],
34
+ enumerable: true,
35
+ configurable: true,
36
+ set: __exportSetter.bind(all, name)
37
+ });
38
+ };
39
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
40
+
41
+ // src/core/types.ts
42
+ var exports_types = {};
43
+ __export(exports_types, {
44
+ reasonFromError: () => reasonFromError,
45
+ isErrorReason: () => isErrorReason,
46
+ TransportSendError: () => TransportSendError,
47
+ TOMBSTONE_RETENTION_MS: () => TOMBSTONE_RETENTION_MS,
48
+ SUPPORTED_PROTOCOL_VERSIONS: () => SUPPORTED_PROTOCOL_VERSIONS,
49
+ SERVER_TOMBSTONE_RETENTION_MS: () => SERVER_TOMBSTONE_RETENTION_MS,
50
+ PROTOCOL_VERSION: () => PROTOCOL_VERSION,
51
+ MutationError: () => MutationError,
52
+ MAX_CLOCK_DRIFT_MS: () => MAX_CLOCK_DRIFT_MS,
53
+ MAX_BATCH_SIZE: () => MAX_BATCH_SIZE
54
+ });
55
+ function isErrorReason(value) {
56
+ return typeof value === "string" && VALID_ERROR_REASONS.has(value);
57
+ }
58
+ function reasonFromError(err) {
59
+ if (err instanceof MutationError && isErrorReason(err.reason)) {
60
+ return err.reason;
61
+ }
62
+ return "server_error";
63
+ }
64
+ var TransportSendError, PROTOCOL_VERSION = 1, SUPPORTED_PROTOCOL_VERSIONS, MAX_CLOCK_DRIFT_MS, MAX_BATCH_SIZE = 100, TOMBSTONE_RETENTION_MS, SERVER_TOMBSTONE_RETENTION_MS, MutationError, VALID_ERROR_REASONS;
65
+ var init_types = __esm(() => {
66
+ TransportSendError = class TransportSendError extends Error {
67
+ clientId;
68
+ cause;
69
+ constructor(clientId, message, cause) {
70
+ super(message);
71
+ this.clientId = clientId;
72
+ this.cause = cause;
73
+ this.name = "TransportSendError";
74
+ }
75
+ };
76
+ SUPPORTED_PROTOCOL_VERSIONS = [1];
77
+ MAX_CLOCK_DRIFT_MS = 5 * 60 * 1000;
78
+ TOMBSTONE_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
79
+ SERVER_TOMBSTONE_RETENTION_MS = 90 * 24 * 60 * 60 * 1000;
80
+ MutationError = class MutationError extends Error {
81
+ reason;
82
+ constructor(reason, message) {
83
+ super(message ?? reason);
84
+ this.reason = reason;
85
+ }
86
+ };
87
+ VALID_ERROR_REASONS = new Set([
88
+ "outside_shape",
89
+ "readonly_query",
90
+ "rate_limited",
91
+ "buffer_full",
92
+ "server_conflict",
93
+ "custom_conflict",
94
+ "merge_stale",
95
+ "clock_drift",
96
+ "replay",
97
+ "batch_too_large",
98
+ "schema_outdated",
99
+ "auth_revoked",
100
+ "compacted",
101
+ "mutation_rejected",
102
+ "server_error",
103
+ "unknown_query"
104
+ ]);
105
+ });
106
+
107
+ // src/transport/bun-ws.ts
108
+ init_types();
109
+ var exports_bun_ws = {};
110
+ __export(exports_bun_ws, {
111
+ createBunWsServerTransport: () => createBunWsServerTransport
112
+ });
113
+ module.exports = __toCommonJS(exports_bun_ws);
114
+ function trySend(clientId, ws, data, maxBufferedBytes) {
115
+ if (ws.readyState !== undefined && ws.readyState !== 1) {
116
+ throw new TransportSendError(clientId, `bun-ws not open (readyState=${ws.readyState})`);
117
+ }
118
+ if (maxBufferedBytes > 0 && typeof ws.getBufferedAmount === "function") {
119
+ const buffered = ws.getBufferedAmount();
120
+ if (buffered > maxBufferedBytes) {
121
+ throw new TransportSendError(clientId, `bun-ws outbound buffer over limit (${buffered} > ${maxBufferedBytes})`);
122
+ }
123
+ }
124
+ try {
125
+ ws.send(data);
126
+ } catch (err) {
127
+ throw new TransportSendError(clientId, `bun-ws send failed: ${err instanceof Error ? err.message : String(err)}`, err);
128
+ }
129
+ }
130
+ function createBunWsServerTransport(cfg = {}) {
131
+ const clients = new Map;
132
+ const lastSeen = new Map;
133
+ const maxMessageBytes = cfg.maxMessageBytes ?? 1e6;
134
+ const pingIntervalMs = cfg.pingIntervalMs ?? 30000;
135
+ const pongTimeoutMs = cfg.pongTimeoutMs ?? pingIntervalMs * 2;
136
+ const maxBufferedBytes = cfg.maxBufferedBytes ?? 8000000;
137
+ let messageHandler = null;
138
+ let connectHandler = null;
139
+ let disconnectHandler = null;
140
+ let heartbeatTimer = null;
141
+ if (pingIntervalMs > 0) {
142
+ heartbeatTimer = setInterval(() => {
143
+ const now = Date.now();
144
+ for (const [id, ws] of clients) {
145
+ const last = lastSeen.get(id) ?? now;
146
+ if (now - last > pongTimeoutMs) {
147
+ try {
148
+ ws.close();
149
+ } catch {}
150
+ continue;
151
+ }
152
+ try {
153
+ ws.ping?.();
154
+ } catch {}
155
+ }
156
+ }, pingIntervalMs);
157
+ if (typeof heartbeatTimer.unref === "function") {
158
+ heartbeatTimer.unref();
159
+ }
160
+ }
161
+ const websocket = {
162
+ open(ws) {
163
+ const { id, req } = ws.data;
164
+ clients.set(id, ws);
165
+ lastSeen.set(id, Date.now());
166
+ connectHandler?.(id, req ?? new Request("https://ws-connect"));
167
+ },
168
+ message(ws, data) {
169
+ const { id } = ws.data;
170
+ lastSeen.set(id, Date.now());
171
+ const byteLen = typeof data === "string" ? typeof Buffer !== "undefined" ? Buffer.byteLength(data, "utf8") : new Blob([data]).size : data.length;
172
+ if (byteLen > maxMessageBytes) {
173
+ console.warn(`[reflectdb] bun-ws: message from ${id} exceeds ${maxMessageBytes} bytes (${byteLen}), closing`);
174
+ try {
175
+ ws.close();
176
+ } catch {}
177
+ return;
178
+ }
179
+ const raw = typeof data === "string" ? data : new TextDecoder().decode(data);
180
+ try {
181
+ messageHandler?.(id, JSON.parse(raw));
182
+ } catch (err) {
183
+ console.warn(`[reflectdb] bun-ws: malformed message from ${id}:`, err instanceof Error ? err.message : String(err));
184
+ }
185
+ },
186
+ close(ws) {
187
+ const { id } = ws.data;
188
+ clients.delete(id);
189
+ lastSeen.delete(id);
190
+ disconnectHandler?.(id);
191
+ },
192
+ pong(ws) {
193
+ lastSeen.set(ws.data.id, Date.now());
194
+ }
195
+ };
196
+ const transport = {
197
+ async send(clientId, message) {
198
+ const ws = clients.get(clientId);
199
+ if (!ws) {
200
+ throw new TransportSendError(clientId, "no socket registered for client");
201
+ }
202
+ trySend(clientId, ws, JSON.stringify(message), maxBufferedBytes);
203
+ },
204
+ async broadcast(_roomId, message, exclude) {
205
+ const data = JSON.stringify(message);
206
+ for (const [id, ws] of clients) {
207
+ if (id === exclude)
208
+ continue;
209
+ try {
210
+ trySend(id, ws, data, maxBufferedBytes);
211
+ } catch (err) {
212
+ console.warn("[reflectdb] bun-ws broadcast skipped a client:", err instanceof Error ? err.message : err);
213
+ }
214
+ }
215
+ },
216
+ disconnect(clientId) {
217
+ const ws = clients.get(clientId);
218
+ if (!ws)
219
+ return;
220
+ try {
221
+ ws.close();
222
+ } catch {}
223
+ clients.delete(clientId);
224
+ },
225
+ onMessage(handler) {
226
+ messageHandler = handler;
227
+ },
228
+ onConnect(handler) {
229
+ connectHandler = handler;
230
+ },
231
+ onDisconnect(handler) {
232
+ disconnectHandler = handler;
233
+ },
234
+ async close() {
235
+ if (heartbeatTimer)
236
+ clearInterval(heartbeatTimer);
237
+ for (const ws of clients.values())
238
+ ws.close();
239
+ clients.clear();
240
+ lastSeen.clear();
241
+ }
242
+ };
243
+ return { transport, websocket };
244
+ }
@@ -0,0 +1,215 @@
1
+ type OpType = "insert" | "update" | "delete";
2
+ type ErrorReason = "outside_shape" | "readonly_query" | "rate_limited" | "buffer_full" | "server_conflict" | "custom_conflict" | "merge_stale" | "clock_drift" | "replay" | "batch_too_large" | "schema_outdated" | "auth_revoked" | "compacted" | "mutation_rejected" | "server_error" | "unknown_query";
3
+ interface HelloMessage {
4
+ type: "hello";
5
+ /** Highest protocol version the client prefers. Retained for back-compat. */
6
+ protocolVersion: number;
7
+ /** All versions the client can speak. Omit for legacy single-version clients. */
8
+ supportedVersions?: readonly number[];
9
+ clientId: string;
10
+ token: string;
11
+ }
12
+ interface BootstrapMessage {
13
+ type: "bootstrap";
14
+ syncParams?: Record<string, Record<string, unknown>>;
15
+ }
16
+ interface ResumeMessage {
17
+ type: "resume";
18
+ since: string;
19
+ }
20
+ interface OpsMessage {
21
+ type: "ops";
22
+ ops: ClientOp[];
23
+ token: string;
24
+ }
25
+ interface ClientOp {
26
+ id: string;
27
+ table: string;
28
+ op: OpType;
29
+ rowId: string;
30
+ payload: Record<string, unknown> | null;
31
+ hlc: string;
32
+ batchId?: string;
33
+ batchSize?: number;
34
+ batchSeq?: number;
35
+ }
36
+ interface SyncDeclareMessage {
37
+ type: "sync_declare";
38
+ table: string;
39
+ params?: Record<string, unknown>;
40
+ window?: number;
41
+ }
42
+ interface LoadMoreMessage {
43
+ type: "load_more";
44
+ table: string;
45
+ count: number;
46
+ }
47
+ interface UnsyncMessage {
48
+ type: "unsync";
49
+ table: string;
50
+ }
51
+ interface AuthMessage {
52
+ type: "auth";
53
+ token: string;
54
+ }
55
+ interface EphemeralMessage {
56
+ type: "ephemeral";
57
+ key: string;
58
+ userId: string;
59
+ data: Record<string, unknown>;
60
+ ttlMs?: number;
61
+ }
62
+ interface HelloAckMessage {
63
+ type: "hello_ack";
64
+ protocolVersion: number;
65
+ serverId: string;
66
+ }
67
+ interface HelloRejectMessage {
68
+ type: "hello_reject";
69
+ reason: string;
70
+ supported: number[];
71
+ }
72
+ interface SnapshotMessage {
73
+ type: "snapshot";
74
+ table: string;
75
+ rows: Record<string, unknown>[];
76
+ colClocks: Record<string, Record<string, string>>;
77
+ append?: boolean;
78
+ totalCount?: number;
79
+ /**
80
+ * Primary key column name for this table. Self-contained per message so the
81
+ * client doesn't depend on `bootstrap_complete.tableMeta` arriving first.
82
+ * When omitted (older servers), the client falls back to tableMeta, then "id".
83
+ */
84
+ pk?: string;
85
+ }
86
+ interface BootstrapCompleteMessage {
87
+ type: "bootstrap_complete";
88
+ serverHlc: string;
89
+ tableMeta: Record<string, TableMeta>;
90
+ }
91
+ interface TableMeta {
92
+ serverSet: string[];
93
+ readonly: string[];
94
+ broadcast: "consistent" | "eager" | "eager-durable";
95
+ /** Primary key column name. Defaults to "id" when omitted (older servers). */
96
+ pk?: string;
97
+ }
98
+ interface DeltaMessage {
99
+ type: "delta";
100
+ table: string;
101
+ op: OpType;
102
+ rowId: string;
103
+ payload: Record<string, unknown> | null;
104
+ hlc: string;
105
+ colClocks?: Record<string, string>;
106
+ }
107
+ interface AckMessage {
108
+ type: "ack";
109
+ opIds: string[];
110
+ }
111
+ interface RejectMessage {
112
+ type: "reject";
113
+ opId?: string;
114
+ batchId?: string;
115
+ reason: ErrorReason;
116
+ serverRow?: Record<string, unknown>;
117
+ }
118
+ interface ResumeCompleteMessage {
119
+ type: "resume_complete";
120
+ serverHlc: string;
121
+ }
122
+ interface ResumeRejectedMessage {
123
+ type: "resume_rejected";
124
+ reason: string;
125
+ serverHlc: string;
126
+ }
127
+ interface ShapeChangedMessage {
128
+ type: "shape_changed";
129
+ table: string;
130
+ reason: "auth_changed" | "params_changed" | "server_policy";
131
+ }
132
+ interface DisconnectMessage {
133
+ type: "disconnect";
134
+ reason: string;
135
+ }
136
+ interface ReauthMessage {
137
+ type: "reauth";
138
+ }
139
+ interface CountChangedMessage {
140
+ type: "count_changed";
141
+ table: string;
142
+ totalCount: number;
143
+ }
144
+ interface EphemeralEvent {
145
+ type: "ephemeral";
146
+ key: string;
147
+ clientId: string;
148
+ userId: string;
149
+ data: Record<string, unknown>;
150
+ ttlMs?: number;
151
+ }
152
+ type ClientMessage = HelloMessage | BootstrapMessage | ResumeMessage | OpsMessage | SyncDeclareMessage | LoadMoreMessage | UnsyncMessage | AuthMessage | EphemeralMessage;
153
+ type ServerMessage = HelloAckMessage | HelloRejectMessage | SnapshotMessage | BootstrapCompleteMessage | DeltaMessage | AckMessage | RejectMessage | ResumeCompleteMessage | ResumeRejectedMessage | ShapeChangedMessage | DisconnectMessage | ReauthMessage | EphemeralEvent | CountChangedMessage;
154
+ interface ServerTransport {
155
+ /**
156
+ * Deliver a message to one client.
157
+ *
158
+ * MUST reject (ideally with `TransportSendError`) when the frame could not
159
+ * be handed to the peer — unknown/closed socket, full outbound queue, or a
160
+ * throw from the underlying socket. Resolving on a dropped frame makes the
161
+ * broadcast engine commit result-cache state the client never received.
162
+ */
163
+ send(clientId: string, message: ServerMessage): Promise<void>;
164
+ broadcast(roomId: string, message: ServerMessage, exclude?: string): Promise<void>;
165
+ onMessage(handler: (clientId: string, message: ClientMessage) => void): void;
166
+ onConnect(handler: (clientId: string, req: Request) => void): void;
167
+ onDisconnect(handler: (clientId: string) => void): void;
168
+ close(): Promise<void>;
169
+ /**
170
+ * Force-disconnect a single client. Optional — if absent, the handler relies
171
+ * on the client honoring a `disconnect` server-message. Required for any
172
+ * transport that carries authentication state, since an adversarial client
173
+ * can otherwise ignore the message and continue using a revoked session.
174
+ */
175
+ disconnect?(clientId: string): Promise<void> | void;
176
+ }
177
+ interface BunWsTransportData {
178
+ id: string;
179
+ /** Original upgrade request — forwarded to the onConnect handler if provided */
180
+ req?: Request;
181
+ }
182
+ /** Bun's ServerWebSocket shape (subset used by this transport) */
183
+ interface BunServerWebSocket<T> {
184
+ data: T;
185
+ send(data: string): void;
186
+ ping?: (data?: string) => void;
187
+ close(): void;
188
+ readyState?: number;
189
+ /** Bun exposes queued-but-unflushed bytes here; used for backpressure. */
190
+ getBufferedAmount?: () => number;
191
+ }
192
+ interface BunWsServerConfig {
193
+ /** Max inbound message bytes before the connection is closed. Default: 1 MB. */
194
+ maxMessageBytes?: number;
195
+ /** Ping interval in ms. 0 disables. Default: 30_000. */
196
+ pingIntervalMs?: number;
197
+ /** Close a connection if no message/pong seen in this window. Default: 2× pingInterval. */
198
+ pongTimeoutMs?: number;
199
+ /**
200
+ * Outbound backpressure ceiling in bytes. `send` rejects once the socket has
201
+ * more than this queued, so a slow reader can't grow server memory without
202
+ * bound. 0 disables. Default: 8 MB.
203
+ */
204
+ maxBufferedBytes?: number;
205
+ }
206
+ declare function createBunWsServerTransport(cfg?: BunWsServerConfig): {
207
+ transport: ServerTransport;
208
+ websocket: {
209
+ open(ws: BunServerWebSocket<BunWsTransportData>): void;
210
+ message(ws: BunServerWebSocket<BunWsTransportData>, data: string | Uint8Array): void;
211
+ close(ws: BunServerWebSocket<BunWsTransportData>): void;
212
+ pong?(ws: BunServerWebSocket<BunWsTransportData>): void;
213
+ };
214
+ };
215
+ export { createBunWsServerTransport, BunWsTransportData, BunWsServerConfig };