@lunora/replica 0.0.0 → 1.0.0-alpha.2

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 (39) hide show
  1. package/LICENSE.md +231 -0
  2. package/README.md +192 -29
  3. package/dist/adapters/better-sqlite3.d.mts +27 -0
  4. package/dist/adapters/better-sqlite3.d.ts +27 -0
  5. package/dist/adapters/better-sqlite3.mjs +29 -0
  6. package/dist/adapters/sqlite-wasm.d.mts +25 -0
  7. package/dist/adapters/sqlite-wasm.d.ts +25 -0
  8. package/dist/adapters/sqlite-wasm.mjs +56 -0
  9. package/dist/adapters/sqljs.d.mts +19 -0
  10. package/dist/adapters/sqljs.d.ts +19 -0
  11. package/dist/adapters/sqljs.mjs +55 -0
  12. package/dist/index.d.mts +865 -0
  13. package/dist/index.d.ts +865 -0
  14. package/dist/index.mjs +20 -0
  15. package/dist/packem_shared/EventEmitter-CMZfct03.mjs +92 -0
  16. package/dist/packem_shared/EventLog-zMy7AYP4.mjs +162 -0
  17. package/dist/packem_shared/EventLogDO-CZYUvvSr.mjs +235 -0
  18. package/dist/packem_shared/EventLogDOClient-DGiEdi96.mjs +86 -0
  19. package/dist/packem_shared/EventSource-DfV4VoRD.mjs +195 -0
  20. package/dist/packem_shared/EventsSync-DkVbU0WV.mjs +91 -0
  21. package/dist/packem_shared/InMemorySnapshotStore-BHVAD-Bp.mjs +24 -0
  22. package/dist/packem_shared/LocalMirror-GeJ26eNe.mjs +188 -0
  23. package/dist/packem_shared/MaterializerRuntime-HqNXqJxp.mjs +204 -0
  24. package/dist/packem_shared/SubscriptionManager-C5xbw0pg.mjs +75 -0
  25. package/dist/packem_shared/applyDiff-BtbIl1D3.mjs +40 -0
  26. package/dist/packem_shared/applyDiffToDb-DQ1xZp5J.mjs +58 -0
  27. package/dist/packem_shared/classifyChanges-aZmkxgVI.mjs +38 -0
  28. package/dist/packem_shared/defineEvents-DiBkPTh_.mjs +28 -0
  29. package/dist/packem_shared/eventsContext-Bk_p48hj.mjs +6 -0
  30. package/dist/packem_shared/isClientSeq-C46BkzqJ.mjs +5 -0
  31. package/dist/packem_shared/local-mirror.d-Bp19ueGy.d.mts +412 -0
  32. package/dist/packem_shared/local-mirror.d-GhuZAKgm.d.ts +412 -0
  33. package/dist/packem_shared/subscribeToMirror-CiaM-nQ7.mjs +45 -0
  34. package/dist/packem_shared/types.d-VfJ76cK4.d.mts +23 -0
  35. package/dist/packem_shared/types.d-VfJ76cK4.d.ts +23 -0
  36. package/dist/react.d.mts +65 -0
  37. package/dist/react.d.ts +65 -0
  38. package/dist/react.mjs +15 -0
  39. package/package.json +88 -7
@@ -0,0 +1,412 @@
1
+ import { S as SqliteAdapter } from "./types.d-VfJ76cK4.js";
2
+ /**
3
+ * Row-level change kind within a TableDiff.
4
+ *
5
+ * Each change represents one row that was inserted, updated, or deleted on
6
+ * the server since the last sync tick.
7
+ */
8
+ type RowChange = {
9
+ data: Record<string, unknown>;
10
+ type: "insert";
11
+ } | {
12
+ data: Record<string, unknown>;
13
+ id: string;
14
+ type: "update";
15
+ } | {
16
+ id: string;
17
+ type: "delete";
18
+ };
19
+ /**
20
+ * A scoped, ordered set of row changes for a single table.
21
+ *
22
+ * `TableDiff` is the unit of replication between the server and the local
23
+ * SQLite mirror. The server pushes diffs over the poke protocol; the
24
+ * client applies them via `applyDiff`.
25
+ */
26
+ interface TableDiff {
27
+ /** Ordered row changes — insert/update/delete, earliest first. */
28
+ readonly changes: ReadonlyArray<RowChange>;
29
+ /** Logical table name (matches the schema table name). */
30
+ readonly table: string;
31
+ /** Monotonic server timestamp (ms since epoch) when this diff was emitted. */
32
+ readonly timestamp: number;
33
+ }
34
+ /**
35
+ * Create a {@link TableDiff} with a snapshot of the current time.
36
+ */
37
+ declare const createTableDiff: (table: string, changes: ReadonlyArray<RowChange>, timestamp?: number) => TableDiff;
38
+ /**
39
+ * Return `true` when the diff contains no row changes.
40
+ */
41
+ declare const isDiffEmpty: (diff: TableDiff) => boolean;
42
+ /**
43
+ * Return the number of rows touched by the diff (inserts + updates + deletes).
44
+ */
45
+ declare const diffSize: (diff: TableDiff) => number;
46
+ /**
47
+ * Partition a {@link TableDiff} into three categories for batch processing.
48
+ */
49
+ declare const classifyChanges: (diff: TableDiff) => {
50
+ deletes: RowChange[];
51
+ inserts: RowChange[];
52
+ updates: RowChange[];
53
+ };
54
+ /**
55
+ * Merge several diffs for the same table into one (ordering preserved).
56
+ *
57
+ * Returns `null` when the input list is empty.
58
+ */
59
+ declare const mergeDiffs: (diffs: ReadonlyArray<TableDiff>) => TableDiff | null;
60
+ /**
61
+ * Sequence-number types for the event log.
62
+ *
63
+ * Three namespaces match the vocabulary established by event-sourcing:
64
+ *
65
+ * | Namespace | Shape | Producer | Consumer |
66
+ * |-----------|--------------------|---------------------------|------------------------------|
67
+ * | `Global` | `number` | `EventLog` / `EventLogDO` | Materializers, subscribers |
68
+ * | `Input` | No seq (optimistic) | `defineEvents` factories | `EventLog.append` / DO client|
69
+ * | `Client` | `{generation,seq}` | _(future: rebase engine)_ | _(future: rebase-aware code)_|
70
+ * @module
71
+ */
72
+ /**
73
+ * A server-authoritative (global) sequence number.
74
+ *
75
+ * Monotonically increasing, assigned by `EventLog` (in-memory) or
76
+ * `EventLogDO` (Durable Object). All confirmed log entries carry a
77
+ * `GlobalSeq`.
78
+ */
79
+ type GlobalSeq = number;
80
+ /**
81
+ * A client-originated composite sequence number designed to survive rebase.
82
+ *
83
+ * Carries the last-confirmed `global` seq, a monotonically increasing
84
+ * `client` counter, and a `rebaseGeneration` that increments whenever the
85
+ * client's local events are rebased onto a new upstream baseline.
86
+ */
87
+ interface ClientSeq {
88
+ /** Client-local monotonically increasing counter. */
89
+ readonly client: number;
90
+ /** The last-confirmed global sequence number. 0 for unconfirmed events. */
91
+ readonly global: number;
92
+ /** Incremented on every rebase. */
93
+ readonly rebaseGeneration: number;
94
+ }
95
+ /**
96
+ * Discriminated union of all sequence-number types.
97
+ */
98
+ type Seq = GlobalSeq | ClientSeq;
99
+ /**
100
+ * Narrow `Seq` to `GlobalSeq`.
101
+ */
102
+ declare const isGlobalSeq: (seq: Seq) => seq is GlobalSeq;
103
+ /**
104
+ * Narrow `Seq` to `ClientSeq`.
105
+ */
106
+ declare const isClientSeq: (seq: Seq) => seq is ClientSeq;
107
+ /**
108
+ * An event that has **not** yet been assigned a sequence number.
109
+ *
110
+ * Input events represent optimistic / command payloads before the server
111
+ * confirms them. They carry `type`, `payload`, and `timestamp` but no
112
+ * `seq` — the log assigns one on append.
113
+ *
114
+ * Create input events via `defineEvents` factories:
115
+ *
116
+ * ```ts
117
+ * const event = events.chat.messageSent({ channelId: "c1", text: "hello" });
118
+ * // event: InputEvent&lt;"chat.messageSent", { channelId: string; text: string }>
119
+ * ```
120
+ */
121
+ interface InputEvent<Type extends string = string, Payload = unknown> {
122
+ /** Arbitrary JSON-serialisable payload. */
123
+ readonly payload: Payload;
124
+ /** Millisecond timestamp (epoch) when the event was created. */
125
+ readonly timestamp: number;
126
+ /** Event type discriminator (e.g. `"chat.messageSent"`). */
127
+ readonly type: Type;
128
+ }
129
+ /**
130
+ * Type guard: check whether `value` is an {@link InputEvent}.
131
+ */
132
+ declare const isInputEvent: (value: unknown) => value is InputEvent;
133
+ /**
134
+ * A single entry in the append-only {@link EventLog}.
135
+ *
136
+ * Entries are immutable once appended; the `seq` field is assigned
137
+ * monotonically by the log and doubles as a watermark for catch-up
138
+ * replication between tabs or service-worker instances.
139
+ */
140
+ interface EventLogEntry {
141
+ /**
142
+ * Globally-unique client identifier that originated this event.
143
+ * Set by clients that support offline / optimistic writes.
144
+ * `undefined` when the event was created server-side.
145
+ */
146
+ readonly clientId?: string;
147
+ /**
148
+ * The sequence number of the causal parent event.
149
+ *
150
+ * A {@link GlobalSeq} for events confirmed by the server (pointing
151
+ * to the previous confirmed event), or a {@link ClientSeq} for
152
+ * optimistic / offline events pointing to the local predecessor.
153
+ * `undefined` for the first event in a log.
154
+ */
155
+ readonly parentSeqNum?: Seq;
156
+ /** Arbitrary JSON-serialisable payload. */
157
+ readonly payload: unknown;
158
+ /** Monotonically increasing sequence number (0-based). A {@link GlobalSeq}. */
159
+ readonly seq: GlobalSeq;
160
+ /**
161
+ * Session identifier from the originating client.
162
+ * Paired with `clientId` to disambiguate concurrent sessions.
163
+ */
164
+ readonly sessionId?: string;
165
+ /**
166
+ * Optional table diffs that this event produced.
167
+ * When present, a consumer can re-play the event by applying the diffs
168
+ * to its local mirror without re-executing the originating mutation.
169
+ */
170
+ readonly tableDiffs?: ReadonlyArray<TableDiff>;
171
+ /** Millisecond timestamp (epoch) when the entry was appended. */
172
+ readonly timestamp: number;
173
+ /** Event type discriminator (e.g. "row-insert", "mutation-apply"). */
174
+ readonly type: string;
175
+ }
176
+ /**
177
+ * Serialised snapshot of the log — used for persistence and transfer.
178
+ */
179
+ interface EventLogSnapshot {
180
+ readonly entries: ReadonlyArray<EventLogEntry>;
181
+ /** The sequence number of the last entry (head), or `null` for an empty log. */
182
+ readonly headSeq: GlobalSeq | null;
183
+ readonly nextSeq: number;
184
+ }
185
+ /**
186
+ * Optional metadata that can accompany an appended event.
187
+ */
188
+ interface AppendOptions {
189
+ /** Globally-unique client identifier. */
190
+ readonly clientId?: string;
191
+ /**
192
+ * Causal parent sequence number.
193
+ * Automatically set to the previous entry's seq when omitted.
194
+ */
195
+ readonly parentSeqNum?: Seq;
196
+ /** Session identifier within the client. */
197
+ readonly sessionId?: string;
198
+ }
199
+ /**
200
+ * An append-only, in-memory event log for local event sourcing.
201
+ *
202
+ * The log is the single source of truth for "what happened" and drives
203
+ * catch-up replication: a new tab or service worker asks for entries
204
+ * since its known `seq` watermark and re-applies them.
205
+ * @remarks This class is intentionally **not** a full SQLite-backed log.
206
+ * Persistence is the caller's responsibility (write the snapshot
207
+ * to IndexedDB / OPFS via {@link EventLog#snapshot}).
208
+ */
209
+ declare class EventLog {
210
+ #private;
211
+ /**
212
+ * Append a new entry to the log.
213
+ *
214
+ * Accepts either an {@link InputEvent} (e.g. from a `defineEvents` factory)
215
+ * or the traditional `(type, payload, tableDiffs?)` triple.
216
+ * @returns The newly created entry (already written to the log).
217
+ */
218
+ append(event: InputEvent, options?: AppendOptions): EventLogEntry;
219
+ append(type: string, payload: unknown, tableDiffs?: ReadonlyArray<TableDiff>, options?: AppendOptions): EventLogEntry;
220
+ /**
221
+ * Atomically append multiple events to the log.
222
+ *
223
+ * All events are assigned sequential global sequence numbers and
224
+ * automatically wired as a causal chain (each event's `parentSeqNum`
225
+ * points to the previous event in the batch, or to the log head for
226
+ * the first event).
227
+ * @param events An array of events to commit atomically.
228
+ * @returns The newly created entries in order.
229
+ */
230
+ commitAll(events: ReadonlyArray<InputEvent | {
231
+ payload: unknown;
232
+ type: string;
233
+ }>): EventLogEntry[];
234
+ /**
235
+ * Replace the log contents with a previously captured snapshot.
236
+ * This is the restore counterpart of {@link EventLog#snapshot}.
237
+ * Restores `headSeq` from the snapshot so auto-parenting continues
238
+ * after restore.
239
+ */
240
+ load(snapshot: EventLogSnapshot): void;
241
+ /**
242
+ * Return **all** entries whose `seq >= sinceSeq`.
243
+ * Useful for catch-up: "give me everything since my last watermark".
244
+ */
245
+ getSince(sinceSeq: number): ReadonlyArray<EventLogEntry>;
246
+ /**
247
+ * Paginated read starting at `fromSeq`.
248
+ * @returns `{ entries, hasMore }` where `hasMore` is `true` when more
249
+ * entries exist beyond the requested page.
250
+ */
251
+ getFrom(fromSeq: number, limit?: number): {
252
+ entries: ReadonlyArray<EventLogEntry>;
253
+ hasMore: boolean;
254
+ };
255
+ /**
256
+ * Return all entries as a snapshot suitable for serialisation.
257
+ */
258
+ snapshot(): EventLogSnapshot;
259
+ /** Number of entries currently in the log. */
260
+ get size(): number;
261
+ /** The next sequence number that will be assigned. */
262
+ get nextSeq(): number;
263
+ /** Return `true` when there are no entries. */
264
+ get isEmpty(): boolean;
265
+ /**
266
+ * The sequence number of the last (most recent) entry, or `null`
267
+ * when the log is empty. Used internally for auto-parenting and
268
+ * exposed for consumers that need the causal head.
269
+ */
270
+ get headSeq(): GlobalSeq | null;
271
+ /** Remove all entries (primarily for testing). */
272
+ clear(): void;
273
+ /**
274
+ * Return an async generator that yields every entry starting from
275
+ * `fromSeq` (default `0` = all entries).
276
+ *
277
+ * Because `EventLog` is purely in-memory, the generator yields all
278
+ * matching entries synchronously on first iteration and then completes.
279
+ * For a streaming / push-based variant see {@link EventSource.events}.
280
+ */
281
+ events(fromSeq?: number): AsyncGenerator<EventLogEntry>;
282
+ }
283
+ interface MirrorTableDef {
284
+ /** Primary key column name (defaults to `"id"`). */
285
+ readonly primaryKey?: string;
286
+ }
287
+ /**
288
+ * Options for constructing a {@link LocalMirror}.
289
+ */
290
+ interface LocalMirrorOptions {
291
+ /** Platform-specific SQLite adapter. */
292
+ readonly db: SqliteAdapter;
293
+ /**
294
+ * Table schemas the mirror should manage.
295
+ *
296
+ * On first use the mirror creates any missing tables automatically
297
+ * based on the columns observed in the first diff/row applied.
298
+ * If you want a fixed schema, pass it here with explicit column
299
+ * definitions in `columns`.
300
+ */
301
+ readonly tables?: Record<string, MirrorTableDef>;
302
+ }
303
+ /**
304
+ * Local SQLite mirror that maintains a client-side replica of server
305
+ * tables by applying {@link TableDiff} deltas.
306
+ *
307
+ * Usage:
308
+ * ```ts
309
+ * import { createSqlJsAdapter } from "@lunora/replica/adapters/sqljs";
310
+ * import initSqlJs from "sql.js";
311
+ *
312
+ * const SQL = await initSqlJs();
313
+ * const db = createSqlJsAdapter(new SQL.Database());
314
+ *
315
+ * const mirror = new LocalMirror({ db });
316
+ *
317
+ * // Apply a server diff:
318
+ * mirror.applyDiff(someDiff);
319
+ *
320
+ * // Query locally:
321
+ * const rows = mirror.query&lt;{ id: string; name: string }>(
322
+ * "SELECT id, name FROM users WHERE name LIKE ?",
323
+ * ["alice%"],
324
+ * );
325
+ * ```
326
+ */
327
+ type ChangeSubscriber = () => void;
328
+ declare class LocalMirror {
329
+ #private;
330
+ /**
331
+ * Convenience factory that creates a {@link LocalMirror} backed by a
332
+ * {@link createSqlJsAdapter sql.js adapter} without needing to import
333
+ * and wire sql.js manually.
334
+ *
335
+ * The caller provides an initialised sql.js database — this method wraps
336
+ * it in an adapter and constructs the mirror.
337
+ * @example
338
+ * ```ts
339
+ * import initSqlJs from "sql.js";
340
+ *
341
+ * const SQL = await initSqlJs();
342
+ * const mirror = LocalMirror.create(new SQL.Database(), {
343
+ * tables: { todos: { primaryKey: "id" } },
344
+ * });
345
+ * ```
346
+ */
347
+ static create(sqlJsDatabase: {
348
+ close: () => void;
349
+ exec: (sql: string) => {
350
+ columns: string[];
351
+ values: unknown[][];
352
+ }[];
353
+ run: (sql: string, params?: unknown[]) => void;
354
+ }, options?: {
355
+ tables?: Record<string, MirrorTableDef>;
356
+ }): LocalMirror;
357
+ constructor(options: LocalMirrorOptions);
358
+ /**
359
+ * Subscribe to data-change notifications. Fires after every {@link applyDiff}.
360
+ * Returns an unsubscribe function.
361
+ */
362
+ onChange(callback: ChangeSubscriber): () => void;
363
+ /**
364
+ * The in-memory event log tracking every diff applied to this mirror.
365
+ * Use {@link EventLog.getSince} for catch-up replication across tabs
366
+ * or service-worker instances.
367
+ */
368
+ get eventLog(): EventLog;
369
+ /**
370
+ * The raw SQLite adapter. Advanced consumers (e.g. the React hook)
371
+ * can use it for ad-hoc queries or bulk operations.
372
+ */
373
+ get db(): SqliteAdapter;
374
+ /**
375
+ * Apply a server-side diff to the local SQLite mirror.
376
+ *
377
+ * The diff is applied in a transaction and recorded in the event log
378
+ * so other tabs or the SW can catch up.
379
+ */
380
+ applyDiff(diff: TableDiff): void;
381
+ /**
382
+ * Run an arbitrary SQL query against the local mirror and return
383
+ * typed results.
384
+ * @example
385
+ * ```ts
386
+ * const users = mirror.query<{ id: string; name: string }>(
387
+ * "SELECT id, name FROM users WHERE active = ?",
388
+ * [true],
389
+ * );
390
+ * ```
391
+ */
392
+ query<T = Record<string, unknown>>(sql: string, params?: ReadonlyArray<unknown>): T[];
393
+ /**
394
+ * Delete every row from all known tables (preserves the event log
395
+ * and schema). Useful when re-syncing from scratch.
396
+ */
397
+ clearData(): void;
398
+ /**
399
+ * Dispose the mirror and close the database connection.
400
+ */
401
+ close(): void;
402
+ /**
403
+ * Register a table schema so the mirror can create the table on
404
+ * first use.
405
+ */
406
+ registerTable(name: string, definition: MirrorTableDef): void;
407
+ /**
408
+ * Return the list of mirrored table names.
409
+ */
410
+ get mirroredTables(): ReadonlyArray<string>;
411
+ }
412
+ export { AppendOptions as A, ClientSeq as C, EventLogEntry as E, GlobalSeq as G, InputEvent as I, LocalMirror as L, MirrorTableDef as M, RowChange as R, Seq as S, TableDiff as T, EventLog as a, EventLogSnapshot as b, LocalMirrorOptions as c, classifyChanges as d, createTableDiff as e, diffSize as f, isDiffEmpty as g, isGlobalSeq as h, isClientSeq as i, isInputEvent as j, mergeDiffs as m };
@@ -0,0 +1,45 @@
1
+ const deriveTableName = (functionRef) => `fn_${functionRef.replaceAll(/[/:.]/g, "_")}`;
2
+ const asRowArray = (data) => {
3
+ if (Array.isArray(data)) {
4
+ return data;
5
+ }
6
+ if (data !== null && typeof data === "object") {
7
+ return [data];
8
+ }
9
+ return [];
10
+ };
11
+ const subscribeToMirror = (client, mirror, functionRef, args, shardKey) => {
12
+ const tableName = deriveTableName(functionRef.__lunoraRef);
13
+ mirror.registerTable(tableName, {});
14
+ let knownIds = /* @__PURE__ */ new Set();
15
+ return client.subscribe(
16
+ functionRef,
17
+ args,
18
+ (data) => {
19
+ const rows = asRowArray(data);
20
+ const nextIds = /* @__PURE__ */ new Set();
21
+ const changes = [];
22
+ for (const row of rows) {
23
+ const record = row;
24
+ const rawId = record.id;
25
+ if (typeof rawId === "string" || typeof rawId === "number") {
26
+ nextIds.add(String(rawId));
27
+ }
28
+ changes.push({ type: "insert", data: record });
29
+ }
30
+ for (const id of knownIds) {
31
+ if (!nextIds.has(id)) {
32
+ changes.push({ type: "delete", id });
33
+ }
34
+ }
35
+ knownIds = nextIds;
36
+ if (changes.length === 0) {
37
+ return;
38
+ }
39
+ mirror.applyDiff({ table: tableName, changes, timestamp: Date.now() });
40
+ },
41
+ { shardKey }
42
+ );
43
+ };
44
+
45
+ export { subscribeToMirror };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Abstract SQLite driver interface used by the local mirror.
3
+ *
4
+ * Each runtime (browser via sql.js, React Native via expo-sqlite,
5
+ * Node via better-sqlite3) provides its own adapter implementing this
6
+ * interface so the rest of `@lunora/replica` stays platform-agnostic.
7
+ */
8
+ interface SqliteAdapter {
9
+ /** Close the database connection. */
10
+ close: () => void;
11
+ /** Execute a SQL statement (with optional bound params). */
12
+ exec: (sql: string, params?: ReadonlyArray<unknown>) => void;
13
+ /** Return the id of the last inserted row. */
14
+ lastInsertRowId: () => number;
15
+ /**
16
+ * Execute a SQL statement and return the result rows.
17
+ * Columns can be accessed by index or by name.
18
+ */
19
+ query: <T = Record<string, unknown>>(sql: string, params?: ReadonlyArray<unknown>) => T[];
20
+ /** Run all statements in a transaction. */
21
+ transaction: (function_: () => void) => void;
22
+ }
23
+ export { SqliteAdapter as S };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Abstract SQLite driver interface used by the local mirror.
3
+ *
4
+ * Each runtime (browser via sql.js, React Native via expo-sqlite,
5
+ * Node via better-sqlite3) provides its own adapter implementing this
6
+ * interface so the rest of `@lunora/replica` stays platform-agnostic.
7
+ */
8
+ interface SqliteAdapter {
9
+ /** Close the database connection. */
10
+ close: () => void;
11
+ /** Execute a SQL statement (with optional bound params). */
12
+ exec: (sql: string, params?: ReadonlyArray<unknown>) => void;
13
+ /** Return the id of the last inserted row. */
14
+ lastInsertRowId: () => number;
15
+ /**
16
+ * Execute a SQL statement and return the result rows.
17
+ * Columns can be accessed by index or by name.
18
+ */
19
+ query: <T = Record<string, unknown>>(sql: string, params?: ReadonlyArray<unknown>) => T[];
20
+ /** Run all statements in a transaction. */
21
+ transaction: (function_: () => void) => void;
22
+ }
23
+ export { SqliteAdapter as S };
@@ -0,0 +1,65 @@
1
+ import { L as LocalMirror } from "./packem_shared/local-mirror.d-Bp19ueGy.mjs";
2
+ import "./packem_shared/types.d-VfJ76cK4.mjs";
3
+ /**
4
+ * Options for the {@link useLocalQuery} hook.
5
+ */
6
+ interface UseLocalQueryOptions {
7
+ /**
8
+ * Optional shard key (reserved for future use; currently unused).
9
+ *
10
+ * Intended for multi-mirror setups where a single app maintains multiple
11
+ * SQLite databases sharded by a key (e.g. user id, tenant id). Currently
12
+ * has no effect — the hook always queries the mirror passed as the first
13
+ * argument.
14
+ */
15
+ shardKey?: string;
16
+ }
17
+ /**
18
+ * React hook that subscribes to a local SQLite query and returns
19
+ * live-updating results whenever the mirror applies a diff.
20
+ *
21
+ * Uses `useSyncExternalStore` to subscribe to the mirror's `onChange`
22
+ * callback — every diff triggers a re-query against the local SQLite.
23
+ *
24
+ * The hook works with React 18+ concurrent features, Suspense, and
25
+ * server-side rendering. During SSR the same value is returned as on
26
+ * the client (the mirror's current state at render time).
27
+ * @param mirror The {@link LocalMirror} instance to query. Must have been
28
+ * constructed with an {@link import("./adapters/types").SqliteAdapter}.
29
+ * @param sql Parameterised SQL query string. Use `?` placeholders for
30
+ * bound parameters (the adapter forwards them to the underlying SQLite
31
+ * engine without rewriting).
32
+ * @param params Optional positional bound parameters matching `?`
33
+ * placeholders in `sql`.
34
+ * @param _options Optional configuration (currently unused; reserved for
35
+ * future features like shard key routing).
36
+ * @returns An array of result rows typed via the generic parameter `T`, or
37
+ * `undefined` if the query fails (e.g. the target table doesn't exist yet
38
+ * because no matching diff has been applied). Treat `undefined` as a
39
+ * "loading" or "no data yet" signal in your component.
40
+ *
41
+ * **Error handling**: The hook catches SQL errors internally and returns
42
+ * `undefined`. Use a try-catch around `mirror.query(...)` directly if you
43
+ * need finer-grained error diagnostics.
44
+ * @example
45
+ * ```tsx
46
+ * import { useLocalQuery } from "@lunora/replica/react";
47
+ * import { mirror } from "./mirror";
48
+ *
49
+ * function UserList() {
50
+ * const users = useLocalQuery<{ id: string; name: string }>(
51
+ * mirror,
52
+ * "SELECT id, name FROM fn_todos_list WHERE name LIKE ?",
53
+ * ["%alice%"],
54
+ * );
55
+ *
56
+ * if (users === undefined) {
57
+ * return <p>Waiting for data…</p>;
58
+ * }
59
+ *
60
+ * return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
61
+ * }
62
+ * ```
63
+ */
64
+ declare const useLocalQuery: <T = Record<string, unknown>>(mirror: LocalMirror, sql: string, params?: ReadonlyArray<unknown>, _options?: UseLocalQueryOptions) => T[] | undefined;
65
+ export { UseLocalQueryOptions, useLocalQuery };
@@ -0,0 +1,65 @@
1
+ import { L as LocalMirror } from "./packem_shared/local-mirror.d-GhuZAKgm.js";
2
+ import "./packem_shared/types.d-VfJ76cK4.js";
3
+ /**
4
+ * Options for the {@link useLocalQuery} hook.
5
+ */
6
+ interface UseLocalQueryOptions {
7
+ /**
8
+ * Optional shard key (reserved for future use; currently unused).
9
+ *
10
+ * Intended for multi-mirror setups where a single app maintains multiple
11
+ * SQLite databases sharded by a key (e.g. user id, tenant id). Currently
12
+ * has no effect — the hook always queries the mirror passed as the first
13
+ * argument.
14
+ */
15
+ shardKey?: string;
16
+ }
17
+ /**
18
+ * React hook that subscribes to a local SQLite query and returns
19
+ * live-updating results whenever the mirror applies a diff.
20
+ *
21
+ * Uses `useSyncExternalStore` to subscribe to the mirror's `onChange`
22
+ * callback — every diff triggers a re-query against the local SQLite.
23
+ *
24
+ * The hook works with React 18+ concurrent features, Suspense, and
25
+ * server-side rendering. During SSR the same value is returned as on
26
+ * the client (the mirror's current state at render time).
27
+ * @param mirror The {@link LocalMirror} instance to query. Must have been
28
+ * constructed with an {@link import("./adapters/types").SqliteAdapter}.
29
+ * @param sql Parameterised SQL query string. Use `?` placeholders for
30
+ * bound parameters (the adapter forwards them to the underlying SQLite
31
+ * engine without rewriting).
32
+ * @param params Optional positional bound parameters matching `?`
33
+ * placeholders in `sql`.
34
+ * @param _options Optional configuration (currently unused; reserved for
35
+ * future features like shard key routing).
36
+ * @returns An array of result rows typed via the generic parameter `T`, or
37
+ * `undefined` if the query fails (e.g. the target table doesn't exist yet
38
+ * because no matching diff has been applied). Treat `undefined` as a
39
+ * "loading" or "no data yet" signal in your component.
40
+ *
41
+ * **Error handling**: The hook catches SQL errors internally and returns
42
+ * `undefined`. Use a try-catch around `mirror.query(...)` directly if you
43
+ * need finer-grained error diagnostics.
44
+ * @example
45
+ * ```tsx
46
+ * import { useLocalQuery } from "@lunora/replica/react";
47
+ * import { mirror } from "./mirror";
48
+ *
49
+ * function UserList() {
50
+ * const users = useLocalQuery<{ id: string; name: string }>(
51
+ * mirror,
52
+ * "SELECT id, name FROM fn_todos_list WHERE name LIKE ?",
53
+ * ["%alice%"],
54
+ * );
55
+ *
56
+ * if (users === undefined) {
57
+ * return <p>Waiting for data…</p>;
58
+ * }
59
+ *
60
+ * return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
61
+ * }
62
+ * ```
63
+ */
64
+ declare const useLocalQuery: <T = Record<string, unknown>>(mirror: LocalMirror, sql: string, params?: ReadonlyArray<unknown>, _options?: UseLocalQueryOptions) => T[] | undefined;
65
+ export { UseLocalQueryOptions, useLocalQuery };
package/dist/react.mjs ADDED
@@ -0,0 +1,15 @@
1
+ import { useSyncExternalStore } from 'react';
2
+
3
+ const useLocalQuery = (mirror, sql, params, _options) => {
4
+ const subscribe = (onStoreChange) => mirror.onChange(onStoreChange);
5
+ const getSnapshot = () => mirror.eventLog.size;
6
+ const getServerSnapshot = () => mirror.eventLog.size;
7
+ useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
8
+ try {
9
+ return mirror.query(sql, params);
10
+ } catch {
11
+ return void 0;
12
+ }
13
+ };
14
+
15
+ export { useLocalQuery };