@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,75 @@
1
+ class SubscriptionManager {
2
+ #subscriptions = /* @__PURE__ */ new Map();
3
+ #nextId = 0;
4
+ // ── Registration ──────────────────────────────────────────────────
5
+ /**
6
+ * Subscribe to every state change emitted by the event source.
7
+ * @returns Unsubscribe function.
8
+ */
9
+ onStateChange(callback) {
10
+ const id = String(this.#nextId);
11
+ this.#nextId += 1;
12
+ const sub = { kind: "state", id, callback };
13
+ this.#subscriptions.set(id, sub);
14
+ return () => {
15
+ this.#subscriptions.delete(id);
16
+ };
17
+ }
18
+ /**
19
+ * Subscribe to a specific event type.
20
+ * @param eventType The event type to listen for (matches `entry.type`).
21
+ * @param callback Invoked with each matching entry.
22
+ * @returns Unsubscribe function.
23
+ */
24
+ onEvent(eventType, callback) {
25
+ const id = String(this.#nextId);
26
+ this.#nextId += 1;
27
+ const sub = { kind: "event", id, eventType, callback };
28
+ this.#subscriptions.set(id, sub);
29
+ return () => {
30
+ this.#subscriptions.delete(id);
31
+ };
32
+ }
33
+ // ── Notification ──────────────────────────────────────────────────
34
+ /**
35
+ * Notify all state-change subscribers with the current state.
36
+ */
37
+ notifyState(state) {
38
+ for (const sub of this.#subscriptions.values()) {
39
+ if (sub.kind === "state") {
40
+ try {
41
+ sub.callback(state);
42
+ } catch {
43
+ }
44
+ }
45
+ }
46
+ }
47
+ /**
48
+ * Notify event-type subscribers whose `eventType` matches.
49
+ */
50
+ notifyEvent(entry) {
51
+ for (const sub of this.#subscriptions.values()) {
52
+ if (sub.kind === "event" && sub.eventType === entry.type) {
53
+ try {
54
+ sub.callback(entry);
55
+ } catch {
56
+ }
57
+ }
58
+ }
59
+ }
60
+ // ── Introspection ─────────────────────────────────────────────────
61
+ /**
62
+ * Return the total number of active subscriptions.
63
+ */
64
+ get size() {
65
+ return this.#subscriptions.size;
66
+ }
67
+ /**
68
+ * Remove all subscriptions.
69
+ */
70
+ clear() {
71
+ this.#subscriptions.clear();
72
+ }
73
+ }
74
+
75
+ export { SubscriptionManager };
@@ -0,0 +1,40 @@
1
+ const applyDiff = (current, diff) => {
2
+ const next = new Map(current);
3
+ for (const change of diff.changes) {
4
+ switch (change.type) {
5
+ case "delete": {
6
+ next.delete(change.id);
7
+ break;
8
+ }
9
+ case "insert": {
10
+ const rawId = change.data.id;
11
+ const id = typeof rawId === "string" || typeof rawId === "number" ? String(rawId) : crypto.randomUUID();
12
+ next.set(id, { ...change.data, id });
13
+ break;
14
+ }
15
+ case "update": {
16
+ const existing = next.get(change.id);
17
+ if (existing) {
18
+ next.set(change.id, { ...existing, ...change.data });
19
+ }
20
+ break;
21
+ }
22
+ }
23
+ }
24
+ return next;
25
+ };
26
+ const applyDiffs = (current, diffs) => {
27
+ let result = new Map(current);
28
+ for (const diff of diffs) {
29
+ result = applyDiff(result, diff);
30
+ }
31
+ return result;
32
+ };
33
+ const applyDiffToSnapshot = (snapshot, diff) => {
34
+ const next = new Map(snapshot);
35
+ const tableMap = next.get(diff.table) ?? /* @__PURE__ */ new Map();
36
+ next.set(diff.table, applyDiff(tableMap, diff));
37
+ return next;
38
+ };
39
+
40
+ export { applyDiff, applyDiffToSnapshot, applyDiffs };
@@ -0,0 +1,58 @@
1
+ const escapeIdentifier = (id) => `\`${id.replaceAll("`", "``")}\``;
2
+ const setClause = (keys) => keys.map((key) => `${escapeIdentifier(key)} = ?`).join(", ");
3
+ const colList = (keys) => `(${keys.map((key) => escapeIdentifier(key)).join(", ")})`;
4
+ const valueList = (count) => `(${Array.from({ length: count }).fill("?").join(", ")})`;
5
+ const applySingleDiff = (database, diff, pkColumn) => {
6
+ if (diff.changes.length === 0) {
7
+ return;
8
+ }
9
+ const table = escapeIdentifier(diff.table);
10
+ const pk = escapeIdentifier(pkColumn);
11
+ for (const change of diff.changes) {
12
+ switch (change.type) {
13
+ case "delete": {
14
+ database.exec(`DELETE FROM ${table} WHERE ${pk} = ?`, [change.id]);
15
+ break;
16
+ }
17
+ case "insert": {
18
+ const { data } = change;
19
+ const keys = Object.keys(data);
20
+ if (keys.length === 0) {
21
+ continue;
22
+ }
23
+ const sql = `INSERT OR REPLACE INTO ${table} ${colList(keys)} VALUES ${valueList(keys.length)}`;
24
+ const values = keys.map((k) => data[k]);
25
+ database.exec(sql, values);
26
+ break;
27
+ }
28
+ case "update": {
29
+ const { data } = change;
30
+ const keys = Object.keys(data);
31
+ if (keys.length === 0) {
32
+ continue;
33
+ }
34
+ const sql = `UPDATE ${table} SET ${setClause(keys)} WHERE ${pk} = ?`;
35
+ const values = [...keys.map((k) => data[k]), change.id];
36
+ database.exec(sql, values);
37
+ break;
38
+ }
39
+ }
40
+ }
41
+ };
42
+ const applyDiffToDatabase = (database, diff, pkColumn) => {
43
+ database.transaction(() => {
44
+ applySingleDiff(database, diff, pkColumn ?? "id");
45
+ });
46
+ };
47
+ const applyDiffsToDatabase = (database, diffs) => {
48
+ if (diffs.length === 0) {
49
+ return;
50
+ }
51
+ database.transaction(() => {
52
+ for (const diff of diffs) {
53
+ applySingleDiff(database, diff, "id");
54
+ }
55
+ });
56
+ };
57
+
58
+ export { applyDiffToDatabase as applyDiffToDb, applyDiffsToDatabase as applyDiffsToDb, escapeIdentifier };
@@ -0,0 +1,38 @@
1
+ const createTableDiff = (table, changes, timestamp) => {
2
+ return {
3
+ table,
4
+ changes,
5
+ timestamp: timestamp ?? Date.now()
6
+ };
7
+ };
8
+ const isDiffEmpty = (diff) => diff.changes.length === 0;
9
+ const diffSize = (diff) => diff.changes.length;
10
+ const classifyChanges = (diff) => {
11
+ const inserts = [];
12
+ const updates = [];
13
+ const deletes = [];
14
+ for (const change of diff.changes) {
15
+ if (change.type === "insert") {
16
+ inserts.push(change);
17
+ } else if (change.type === "update") {
18
+ updates.push(change);
19
+ } else {
20
+ deletes.push(change);
21
+ }
22
+ }
23
+ return { inserts, updates, deletes };
24
+ };
25
+ const mergeDiffs = (diffs) => {
26
+ if (diffs.length === 0) {
27
+ return null;
28
+ }
29
+ const first = diffs[0];
30
+ const last = diffs[diffs.length - 1];
31
+ return createTableDiff(
32
+ first.table,
33
+ diffs.flatMap((d) => d.changes),
34
+ last.timestamp
35
+ );
36
+ };
37
+
38
+ export { classifyChanges, createTableDiff, diffSize, isDiffEmpty, mergeDiffs };
@@ -0,0 +1,28 @@
1
+ const defineEvents = (definition, options) => {
2
+ const result = {};
3
+ const typeMap = {};
4
+ const prefix = options?.version ? `${options.version}.` : "";
5
+ for (const [namespace, events] of Object.entries(definition)) {
6
+ const nsObject = {};
7
+ for (const [name] of Object.entries(events)) {
8
+ const qualifiedType = `${prefix}${namespace}.${name}`;
9
+ typeMap[qualifiedType] = void 0;
10
+ const factory = Object.assign(
11
+ (payload) => {
12
+ return {
13
+ type: qualifiedType,
14
+ payload,
15
+ timestamp: Date.now()
16
+ };
17
+ },
18
+ { type: qualifiedType }
19
+ );
20
+ nsObject[name] = factory;
21
+ }
22
+ result[namespace] = nsObject;
23
+ }
24
+ result._types = typeMap;
25
+ return result;
26
+ };
27
+
28
+ export { defineEvents };
@@ -0,0 +1,6 @@
1
+ const eventsContext = (client) => {
2
+ const facade = client;
3
+ return async ({ ctx: _context, next }) => next({ ctx: { events: facade } });
4
+ };
5
+
6
+ export { eventsContext };
@@ -0,0 +1,5 @@
1
+ const isGlobalSeq = (seq) => typeof seq === "number";
2
+ const isClientSeq = (seq) => typeof seq !== "number" && "rebaseGeneration" in seq;
3
+ const isInputEvent = (value) => typeof value === "object" && value !== null && "type" in value && typeof value.type === "string" && "payload" in value && "timestamp" in value;
4
+
5
+ export { isClientSeq, isGlobalSeq, isInputEvent };
@@ -0,0 +1,412 @@
1
+ import { S as SqliteAdapter } from "./types.d-VfJ76cK4.mjs";
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 };