@lunora/replica 0.0.0 → 1.0.0-alpha.10

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 +194 -29
  3. package/dist/adapters/better-sqlite3.d.mts +28 -0
  4. package/dist/adapters/better-sqlite3.d.ts +28 -0
  5. package/dist/adapters/better-sqlite3.mjs +1 -0
  6. package/dist/adapters/sqlite-wasm.d.mts +36 -0
  7. package/dist/adapters/sqlite-wasm.d.ts +36 -0
  8. package/dist/adapters/sqlite-wasm.mjs +1 -0
  9. package/dist/adapters/sqljs.d.mts +20 -0
  10. package/dist/adapters/sqljs.d.ts +20 -0
  11. package/dist/adapters/sqljs.mjs +1 -0
  12. package/dist/index.d.mts +971 -0
  13. package/dist/index.d.ts +971 -0
  14. package/dist/index.mjs +1 -0
  15. package/dist/packem_shared/EventEmitter-ovTsLeAj.mjs +1 -0
  16. package/dist/packem_shared/EventLog-DmlRY_4Z.mjs +1 -0
  17. package/dist/packem_shared/EventLogDO-Cb-7iN9w.mjs +1 -0
  18. package/dist/packem_shared/EventLogDOClient-C6gA3b3u.mjs +1 -0
  19. package/dist/packem_shared/EventSource-B5UTlkl9.mjs +1 -0
  20. package/dist/packem_shared/EventsSync-pK_hg9KP.mjs +1 -0
  21. package/dist/packem_shared/InMemorySnapshotStore-C4taIG5K.mjs +1 -0
  22. package/dist/packem_shared/LocalMirror-Q7cPH_rX.mjs +4 -0
  23. package/dist/packem_shared/MaterializerRuntime-B-I9jKDe.mjs +1 -0
  24. package/dist/packem_shared/SubscriptionManager-CbSjG_GA.mjs +1 -0
  25. package/dist/packem_shared/applyDiff-BUzddc6r.mjs +1 -0
  26. package/dist/packem_shared/applyDiffToDb-1M2I3BHi.mjs +1 -0
  27. package/dist/packem_shared/classifyChanges-BnOMcDGj.mjs +1 -0
  28. package/dist/packem_shared/defineEvents-CJZV8Bgi.mjs +1 -0
  29. package/dist/packem_shared/eventsContext-Dxow9Y7S.mjs +1 -0
  30. package/dist/packem_shared/isClientSeq-DSXBJskD.mjs +1 -0
  31. package/dist/packem_shared/local-mirror.d-CyGOpUES.d.ts +530 -0
  32. package/dist/packem_shared/local-mirror.d-DTavX_y0.d.mts +530 -0
  33. package/dist/packem_shared/subscribeToMirror-Dru_AYBu.mjs +1 -0
  34. package/dist/packem_shared/types.d-CkMkSwLJ.d.mts +24 -0
  35. package/dist/packem_shared/types.d-CkMkSwLJ.d.ts +24 -0
  36. package/dist/react.d.mts +67 -0
  37. package/dist/react.d.ts +67 -0
  38. package/dist/react.mjs +1 -0
  39. package/package.json +88 -7
@@ -0,0 +1,971 @@
1
+ export { createBetterSqlite3Adapter } from "./adapters/better-sqlite3.mjs";
2
+ export { createSqliteWasmAdapter } from "./adapters/sqlite-wasm.mjs";
3
+ export { createSqlJsAdapter } from "./adapters/sqljs.mjs";
4
+ import { S as SqliteAdapter } from "./packem_shared/types.d-CkMkSwLJ.mjs";
5
+ import { T as TableDiff, I as InputEvent, S as Seq, E as EventLogEntry, a as EventLog, A as AppendOptions, L as LocalMirror } from "./packem_shared/local-mirror.d-DTavX_y0.mjs";
6
+ export { type C as ClientSeq, type b as EventLogOptions, type c as EventLogSnapshot, type G as GlobalSeq, type d as LocalMirrorOptions, type M as MirrorTableDef, type R as RowChange, e as classifyChanges, f as createTableDiff, g as diffSize, i as isClientSeq, h as isDiffEmpty, j as isGlobalSeq, k as isInputEvent, m as mergeDiffs } from "./packem_shared/local-mirror.d-DTavX_y0.mjs";
7
+ /**
8
+ * Apply a single {@link TableDiff} to an in-memory row map and return
9
+ * the updated map.
10
+ *
11
+ * The function creates a **shallow copy** of the input map so the caller's
12
+ * reference stays untouched unless they choose to replace it.
13
+ * @example
14
+ * ```ts
15
+ * const rows = new Map<string, Record<string, unknown>>();
16
+ * rows.set("id-1", { name: "alice" });
17
+ *
18
+ * const diff = createTableDiff("users", [
19
+ * { type: "insert", data: { id: "id-2", name: "bob" } },
20
+ * { type: "update", id: "id-1", data: { name: "alice-updated" } },
21
+ * ]);
22
+ *
23
+ * const updated = applyDiff(rows, diff);
24
+ * updated.get("id-1")?.name // "alice-updated"
25
+ * updated.get("id-2")?.name // "bob"
26
+ * ```
27
+ * @experimental
28
+ */
29
+ declare const applyDiff: (current: ReadonlyMap<string, Record<string, unknown>>, diff: TableDiff) => Map<string, Record<string, unknown>>;
30
+ /**
31
+ * Apply an array of diffs **in order**, returning the final row map.
32
+ *
33
+ * This is equivalent to calling {@link applyDiff} repeatedly but copies the
34
+ * input map exactly once rather than once per diff — catch-up replay of an
35
+ * N-diff backlog is a single copy, not N+1.
36
+ * @experimental
37
+ */
38
+ declare const applyDiffs: (current: ReadonlyMap<string, Record<string, unknown>>, diffs: ReadonlyArray<TableDiff>) => Map<string, Record<string, unknown>>;
39
+ /**
40
+ * Merge the row-level effect of a {@link TableDiff} into plain JSON
41
+ * state keyed by table name, returning a new snapshot.
42
+ * @param snapshot Current snapshot, e.g. `{ users: Map&lt;id, row>, posts: Map&lt;id, row> }`.
43
+ * @param diff Contains the target table name and the row-level changes to merge.
44
+ * @returns A shallow copy of `snapshot` with `diff.table`'s map updated.
45
+ * @experimental
46
+ */
47
+ declare const applyDiffToSnapshot: (snapshot: ReadonlyMap<string, ReadonlyMap<string, Record<string, unknown>>>, diff: TableDiff) => Map<string, Map<string, Record<string, unknown>>>;
48
+ /** Map a namespace-and-name pair to a qualified event type string. */
49
+ type QualifiedType<Ns extends string, Name extends string> = `${Ns}.${Name}`;
50
+ /**
51
+ * Extract the payload type from an event schema.
52
+ *
53
+ * A `@lunora/values` validator (e.g. `v.object(...)`) carries its output type on
54
+ * the phantom `__type` field (the same hook `Infer` reads), so match that FIRST
55
+ * — otherwise a validator, being object-shaped, would fall through to the
56
+ * `Record` branch and resolve to the validator instance itself rather than its
57
+ * validated `{ … }` output. A bare factory function or plain descriptor object
58
+ * is still supported as a fallback.
59
+ */
60
+ type PayloadOf<T> = T extends {
61
+ readonly __type: infer P;
62
+ } ? P : T extends ((payload: infer P) => unknown) ? P : T extends Record<string, unknown> ? T : never;
63
+ type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
64
+ /**
65
+ * Produce `{ "ns.name": Payload }` for every event, merged.
66
+ */
67
+ type EventTypeMap<TDefinition extends Record<string, Record<string, unknown>>> = UnionToIntersection<{ [Ns in keyof TDefinition & string]: { [Name in keyof TDefinition[Ns] & string]: { [K in QualifiedType<Ns, Name>]: PayloadOf<TDefinition[Ns][Name]>; }; }[keyof TDefinition[Ns] & string]; }[keyof TDefinition & string]>;
68
+ /**
69
+ * A factory function that creates an {@link InputEvent} for a specific event type.
70
+ *
71
+ * The returned event has no `seq` — it is an optimistic / command payload
72
+ * that the event log will assign a sequence number to on append.
73
+ * @experimental
74
+ */
75
+ interface EventFactory<Type extends string, Payload> {
76
+ (payload: Payload): InputEvent<Type, Payload>;
77
+ /** The fully qualified event type string (e.g. `"chat.messageSent"`). */
78
+ readonly type: Type;
79
+ }
80
+ /**
81
+ * The namespace object returned for each group of events.
82
+ * @experimental
83
+ */
84
+ type EventNamespace<Ns extends string, TDefinition extends Record<string, unknown>> = { [Name in keyof TDefinition & string]: EventFactory<QualifiedType<Ns, Name>, PayloadOf<TDefinition[Name]>>; };
85
+ /**
86
+ * The full result of {@link defineEvents}.
87
+ * @experimental
88
+ */
89
+ type EventsDefinition<TDefinition extends Record<string, Record<string, unknown>>> = { [Ns in keyof TDefinition & string]: EventNamespace<Ns, TDefinition[Ns]>; } & {
90
+ /** Type-level map of event type → payload shape. Useful for generic code. */
91
+ readonly _types: EventTypeMap<TDefinition>;
92
+ };
93
+ /**
94
+ * Declare typed event types for event sourcing.
95
+ *
96
+ * Each key under a namespace becomes a factory function that produces
97
+ * an {@link InputEvent} — an optimistic / command event that the event
98
+ * log will assign a sequence number to on append.
99
+ * @param definition A nested object where the outer keys are namespaces
100
+ * and the inner keys are event names mapped to their
101
+ * payload schemas (or simple type-descriptor objects).
102
+ * @returns An object with the same nesting structure, where each leaf is
103
+ * a factory function plus a `.type` property.
104
+ */
105
+ interface DefineEventsOptions {
106
+ /**
107
+ * Optional version prefix for all event types.
108
+ *
109
+ * When set, every qualified event type is prefixed with `"v&lt;N>."`, enabling
110
+ * versioned event naming like `"v1.chat.messageSent"` or `"v2.chat.messageSent"`.
111
+ * This allows materializers to evolve their handling logic based on the event
112
+ * version without breaking backward compatibility.
113
+ * @example "v1" → event type becomes "v1.chat.messageSent"
114
+ */
115
+ readonly version?: string;
116
+ }
117
+ /**
118
+ * `defineEvents` is part of the experimental `@lunora/replica` API and may change without a major version bump.
119
+ * @experimental
120
+ */
121
+ declare const defineEvents: <TDefinition extends Record<string, Record<string, unknown>>>(definition: TDefinition, options?: DefineEventsOptions) => EventsDefinition<TDefinition>;
122
+ /**
123
+ * Shape of the `events[]` items sent in a POST `/append` body.
124
+ *
125
+ * Like {@link InputEvent} but with `timestamp` optional — omit it to
126
+ * let the server assign the timestamp.
127
+ * @experimental
128
+ */
129
+ interface AppendEventInput {
130
+ /** Globally-unique client identifier (for offline/optimistic support). */
131
+ readonly clientId?: string;
132
+ /** Causal parent sequence number (ClientSeq for optimistic, GlobalSeq for confirmed). */
133
+ readonly parentSeqNum?: Seq;
134
+ /** Arbitrary JSON-serialisable payload. */
135
+ readonly payload: unknown;
136
+ /** Session identifier within the client. */
137
+ readonly sessionId?: string;
138
+ /** Millisecond timestamp (epoch) — omit to let the server assign it. */
139
+ readonly timestamp?: number;
140
+ /** Event type discriminator. */
141
+ readonly type: string;
142
+ }
143
+ /**
144
+ * Options for constructing an {@link EventLogDOClient}.
145
+ * @experimental
146
+ */
147
+ interface EventLogDOClientOptions {
148
+ /**
149
+ * A function that dispatches an HTTP request to the target EventLogDO
150
+ * instance. In a Cloudflare Worker this is:
151
+ *
152
+ * ```ts
153
+ * (req) => env.MY_DO_NAMESPACE.get(id).fetch(req)
154
+ * ```
155
+ */
156
+ fetch: (request: Request) => Promise<Response>;
157
+ }
158
+ /**
159
+ * Lightweight HTTP client for EventLogDO's RPC surface.
160
+ *
161
+ * Each method maps to one of the DO's endpoints, throws on non-OK status,
162
+ * and returns the parsed response body.
163
+ * @experimental
164
+ */
165
+ declare class EventLogDOClient {
166
+ #private;
167
+ constructor(options: EventLogDOClientOptions);
168
+ /**
169
+ * Append one or more events to the log.
170
+ * @param events The events to append.
171
+ * @param options Idempotency controls for the batch.
172
+ * @param options.batchId Optional idempotency key for the whole batch — a
173
+ * retried `append` call with the same `batchId` (e.g. after a network
174
+ * timeout that hid a successful response) returns the originally-persisted
175
+ * entries instead of inserting duplicates.
176
+ * @returns The persisted entries with their assigned `seq` numbers.
177
+ */
178
+ append(events: AppendEventInput[], options?: {
179
+ batchId?: string;
180
+ }): Promise<EventLogEntry[]>;
181
+ /**
182
+ * Fetch all entries with `seq >= sinceSeq`.
183
+ *
184
+ * Pass `sinceSeq = 0` to fetch the entire log.
185
+ */
186
+ getSince(sinceSeq: number): Promise<EventLogEntry[]>;
187
+ /**
188
+ * Fetch a paginated range of entries.
189
+ * @returns `{ entries, hasMore }` — `hasMore` is `true` when another
190
+ * page exists (i.e. the DO returned `limit + 1` rows).
191
+ */
192
+ getRange(fromSeq: number, limit?: number): Promise<{
193
+ entries: EventLogEntry[];
194
+ hasMore: boolean;
195
+ }>;
196
+ /**
197
+ * Return the total number of entries currently in the log.
198
+ */
199
+ getSize(): Promise<number>;
200
+ /**
201
+ * Return the full log state — all entries plus the next seq number.
202
+ */
203
+ getState(): Promise<{
204
+ entries: EventLogEntry[];
205
+ nextSeq: number;
206
+ }>;
207
+ }
208
+ /**
209
+ * Type-safe event emitter that powers the event-sourcing runtime.
210
+ * @example
211
+ * ```ts
212
+ * type MyEvents = { userCreated: { id: string; name: string }; error: { message: string } };
213
+ *
214
+ * const emitter = new EventEmitter<MyEvents>();
215
+ * emitter.on("userCreated", (payload) => console.log(payload.name));
216
+ * emitter.emit("userCreated", { id: "1", name: "alice" });
217
+ * ```
218
+ * @experimental
219
+ */
220
+ declare class EventEmitter<EventMap extends Record<string, unknown>> {
221
+ #private;
222
+ /**
223
+ * Register a handler for a specific event type.
224
+ * @returns An unsubscribe function (equivalent to calling {@link off}).
225
+ */
226
+ on<K extends keyof EventMap>(event: K, handler: (payload: EventMap[K]) => void): () => void;
227
+ /**
228
+ * Remove a previously registered handler.
229
+ */
230
+ off<K extends keyof EventMap>(event: K, handler: (payload: EventMap[K]) => void): void;
231
+ /**
232
+ * Register a wildcard handler that fires for **every** event type.
233
+ * @returns An unsubscribe function.
234
+ */
235
+ onAny(handler: (event: keyof EventMap, payload: unknown) => void): () => void;
236
+ /**
237
+ * Remove a wildcard handler.
238
+ */
239
+ offAny(handler: (event: keyof EventMap, payload: unknown) => void): void;
240
+ /**
241
+ * Emit an event. All registered handlers (typed + wildcard) are invoked
242
+ * synchronously. Exceptions from handlers are caught and silently
243
+ * swallowed — they **must not** break the emitter loop.
244
+ * @returns `true` if at least one handler was called.
245
+ */
246
+ emit<K extends keyof EventMap>(event: K, payload: EventMap[K]): boolean;
247
+ /**
248
+ * Return `true` when at least one listener is registered for `event`.
249
+ */
250
+ hasListeners(event: keyof EventMap): boolean;
251
+ /**
252
+ * Return the number of typed listeners for a specific event.
253
+ */
254
+ listenerCount(event: keyof EventMap): number;
255
+ /**
256
+ * Remove all listeners.
257
+ */
258
+ clear(): void;
259
+ }
260
+ /**
261
+ * Strategy for handling events whose `type` the reducer does not recognise.
262
+ *
263
+ * - `"warn"` _(default)_ — log a warning and skip the event (state unchanged).
264
+ * - `"ignore"` — skip silently (no warning, no error).
265
+ * - `"fail"` — throw an error, halting the apply / replay cycle.
266
+ * - A **callback** — invoked with the entry; return truthy to mark it as
267
+ * handled (no warning), falsy to fall through to the configured fallback.
268
+ * @experimental
269
+ */
270
+ type UnknownEventHandling = "warn" | "ignore" | "fail" | ((entry: EventLogEntry) => boolean);
271
+ /**
272
+ * Events emitted by the {@link EventSource} runtime.
273
+ *
274
+ * A `type` (not `interface`) so it satisfies `EventEmitter`'s
275
+ * `Record&lt;string, unknown>` constraint — interfaces have no implicit index
276
+ * signature and aren't assignable to `Record&lt;string, unknown>`.
277
+ * @experimental
278
+ */
279
+ type EventSourceEvents = {
280
+ /** Fired (once) after the initial replay completes. */
281
+ ready: {
282
+ entryCount: number;
283
+ };
284
+ /** Fired when a replay error occurs — the runtime will skip the bad entry. */
285
+ "replay-error": {
286
+ entry: EventLogEntry;
287
+ error: Error;
288
+ };
289
+ /** Fired after an event has been applied and the state updated. */
290
+ "state-changed": {
291
+ entry: EventLogEntry;
292
+ state: Record<string, unknown>;
293
+ };
294
+ };
295
+ /**
296
+ * Sentinel a reducer can return to EXPLICITLY signal it does not handle a
297
+ * given event's `type` — as opposed to returning the current `state`
298
+ * reference unchanged to represent a legitimate, idempotent no-op for a type
299
+ * it DOES recognise.
300
+ *
301
+ * Reference equality alone can't tell these two cases apart (REPLICA-07): a
302
+ * reducer that intentionally returns `state` for a type it fully understands
303
+ * (e.g. "already applied this event, nothing to do") would otherwise be
304
+ * misclassified as "unhandled" and trigger {@link UnknownEventHandling} — a
305
+ * spurious warning, or worse, a thrown error under `"fail"`. Return `UNHANDLED`
306
+ * only for a `type` your reducer truly does not recognise; every other return
307
+ * (including a `state` returned by reference) is treated as handled.
308
+ *
309
+ * Reducers that always recognise every event they're given (a single
310
+ * always-matching type, or a catch-all) can ignore this entirely.
311
+ * @experimental
312
+ */
313
+ declare const UNHANDLED: unique symbol;
314
+ /**
315
+ * A function that reduces an event into a state mutation.
316
+ *
317
+ * Pure functions are strongly encouraged: given the same event payload
318
+ * and state, they must produce the same next state. Return {@link UNHANDLED}
319
+ * to explicitly mark an event `type` this reducer does not process — see
320
+ * {@link UNHANDLED} for why reference equality against the input `state`
321
+ * cannot be used for this instead.
322
+ * @experimental
323
+ */
324
+ type EventReducer<S> = (state: S, entry: EventLogEntry) => S | typeof UNHANDLED;
325
+ /**
326
+ * Options for constructing an {@link EventSource}.
327
+ * @experimental
328
+ */
329
+ interface EventSourceOptions {
330
+ /**
331
+ * Cap this runtime's internal `log` to this many entries (REPLICA-06).
332
+ * `replayFromLog` copies every entry it replays from the source log into
333
+ * `this.log` too — a second, uncapped copy of the same history — so a
334
+ * long-lived `EventSource` fed by repeated replay accumulates entries in
335
+ * both places forever without a cap.
336
+ *
337
+ * `undefined` (the default) preserves unbounded retention.
338
+ */
339
+ maxLogEntries?: number;
340
+ /**
341
+ * How to handle events whose `type` is not recognised by the reducer.
342
+ * @default "warn"
343
+ */
344
+ unknownEventHandling?: UnknownEventHandling;
345
+ }
346
+ /**
347
+ * Event-sourcing runtime that maintains a derived state by replaying an
348
+ * append-only {@link EventLog}.
349
+ *
350
+ * Usage:
351
+ * ```ts
352
+ * const source = new EventSource(initialState, myReducer);
353
+ * await source.replayFromLog(existingLog);
354
+ *
355
+ * // Later, when a new event arrives:
356
+ * const entry = source.applyEvent("user-created", { id: "1", name: "alice" });
357
+ * console.log(source.state); // updated state
358
+ * ```
359
+ * @experimental
360
+ */
361
+ declare class EventSource<S extends Record<string, unknown> = Record<string, unknown>> {
362
+ #private;
363
+ readonly emitter: EventEmitter<EventSourceEvents>;
364
+ readonly log: EventLog;
365
+ constructor(initialState: S, reducer: EventReducer<S>, options?: EventSourceOptions);
366
+ /**
367
+ * The current derived state. Read-only snapshot; mutate through events.
368
+ */
369
+ get state(): Readonly<S>;
370
+ /**
371
+ * Whether the initial replay from an existing log has completed.
372
+ */
373
+ get replayed(): boolean;
374
+ /**
375
+ * Append a new event to the log and apply it to the current state.
376
+ *
377
+ * Accepts either an {@link InputEvent} (e.g. from a `defineEvents` factory)
378
+ * or the traditional `(type, payload)` pair.
379
+ * @returns The newly created log entry (with its assigned `seq`).
380
+ */
381
+ applyEvent(event: InputEvent, options?: AppendOptions): EventLogEntry;
382
+ applyEvent(type: string, payload: unknown, options?: AppendOptions): EventLogEntry;
383
+ /**
384
+ * Replay all entries from an existing {@link EventLog} to bootstrap
385
+ * the current state.
386
+ *
387
+ * Idempotent across calls: only source entries past the `#lastAppliedSeq`
388
+ * watermark are applied, so re-invoking picks up just the new entries.
389
+ * @param log The external log to replay from.
390
+ */
391
+ replayFromLog(log: EventLog): void;
392
+ /**
393
+ * Reset the runtime to a base state, optionally resuming from a watermark.
394
+ *
395
+ * Useful after loading a snapshot from the DO: pass the snapshot's state as
396
+ * `initialState` and its highest applied source `seq` as `resumeFromSeq`, so
397
+ * the next {@link replayFromLog} applies ONLY the events after the snapshot
398
+ * (`getSince(resumeFromSeq + 1)`) rather than replaying the whole log on top
399
+ * of the snapshot — which would double-apply non-idempotent reducers.
400
+ *
401
+ * Omit `resumeFromSeq` (default `-1`) for a full reset that replays from the
402
+ * beginning.
403
+ * @param initialState The base state to reset to (e.g. a loaded snapshot).
404
+ * @param resumeFromSeq Highest source `seq` already baked into `initialState`, or `-1` to replay all.
405
+ */
406
+ reset(initialState: S, resumeFromSeq?: number): void;
407
+ /**
408
+ * Return an async generator that yields every event as it is applied,
409
+ * starting from the events currently in the log and continuing with
410
+ * every future `applyEvent` / `replayFromLog` call.
411
+ *
412
+ * The generator runs indefinitely — it never returns. Callers should
413
+ * break out of the `for await` loop or use an `AbortSignal` to stop.
414
+ * @example
415
+ * ```ts
416
+ * for await (const entry of source.events()) {
417
+ * console.log("event applied:", entry);
418
+ * }
419
+ * ```
420
+ */
421
+ events(signal?: AbortSignal): AsyncGenerator<EventLogEntry>;
422
+ }
423
+ /**
424
+ * Interface for persisting event-sourced state snapshots.
425
+ *
426
+ * In a Lunora app the primary implementation is backed by the
427
+ * SnapshotDO (a Durable Object) on the server side. On the client
428
+ * the {@link InMemorySnapshotStore} is used for the offline-first
429
+ * local mirror, while a production client would implement this
430
+ * over IndexedDB or OPFS.
431
+ * @experimental
432
+ */
433
+ interface SnapshotStore {
434
+ /** Delete all snapshots. */
435
+ clear: () => Promise<void>;
436
+ /** Delete a single snapshot. */
437
+ delete: (key: string) => Promise<void>;
438
+ /** List all snapshot keys. */
439
+ list: () => Promise<string[]>;
440
+ /** Load a previously saved snapshot, or `null` when not found. */
441
+ load: (key: string) => Promise<unknown>;
442
+ /** Persist a snapshot under `key`. */
443
+ save: (key: string, snapshot: unknown) => Promise<void>;
444
+ }
445
+ /**
446
+ * In-memory snapshot store. Useful for testing and for the local
447
+ * offline-first mirror where persistence is handled at a higher
448
+ * layer (IndexedDB adapter).
449
+ * @experimental
450
+ */
451
+ declare class InMemorySnapshotStore implements SnapshotStore {
452
+ #private;
453
+ save(key: string, snapshot: unknown): Promise<void>;
454
+ load(key: string): Promise<unknown>;
455
+ list(): Promise<string[]>;
456
+ delete(key: string): Promise<void>;
457
+ clear(): Promise<void>;
458
+ }
459
+ /**
460
+ * A function that reduces an event entry into a state mutation.
461
+ *
462
+ * Pure functions are strongly encouraged: given the same event and state,
463
+ * they must produce the same next state for deterministic replay.
464
+ * @experimental
465
+ */
466
+ type MaterializerReducer<S> = (state: S, entry: EventLogEntry) => S;
467
+ /**
468
+ * Options for defining a single materializer.
469
+ * @experimental
470
+ */
471
+ interface MaterializerDef<S> {
472
+ /**
473
+ * Reducer invoked for every event in the log.
474
+ *
475
+ * Return the current state unchanged to skip the event.
476
+ */
477
+ handle: MaterializerReducer<S>;
478
+ /** Factory for the initial (empty) state. */
479
+ initial: () => S;
480
+ /** Unique name (used as the snapshot storage key). */
481
+ readonly name: string;
482
+ }
483
+ /**
484
+ * A constructed materializer ready to be used with a {@link MaterializerRuntime}.
485
+ * @experimental
486
+ */
487
+ interface Materializer<S> {
488
+ /** Apply a single event entry through the reducer. */
489
+ apply: (entry: EventLogEntry) => void;
490
+ readonly def: MaterializerDef<S>;
491
+ /** Reset to the initial state. */
492
+ reset: () => void;
493
+ /** Replace the runtime state (used on snapshot restore / replay). */
494
+ setState: (state: S) => void;
495
+ /** Current (runtime) derived state. */
496
+ readonly state: Readonly<S>;
497
+ }
498
+ /**
499
+ * Declare a materializer — a named reducer that derives state from events.
500
+ *
501
+ * The returned {@link Materializer} object can be used standalone or passed
502
+ * to a {@link MaterializerRuntime} for automatic log subscription.
503
+ * @experimental
504
+ */
505
+ declare const defineMaterializer: <S>(definition: MaterializerDef<S>) => Materializer<S>;
506
+ /**
507
+ * A materializer of any state shape. The {@link MaterializerRuntime} holds a
508
+ * heterogeneous collection and only ever calls `apply(entry)` / `setState(...)`
509
+ * (with cast values) / reads `def.name` — it never needs the concrete state
510
+ * type. `Materializer&lt;unknown>` won't do: `setState(state: S)` makes
511
+ * `Materializer&lt;S>` invariant in `S`, so `Materializer&lt;number>` isn't assignable
512
+ * to `Materializer&lt;unknown>`. Erasing the type param is the idiomatic fix.
513
+ */
514
+ type AnyMaterializer = Materializer<any>;
515
+ /**
516
+ * Options for constructing a {@link MaterializerRuntime}.
517
+ * @experimental
518
+ */
519
+ interface MaterializerRuntimeOptions {
520
+ /**
521
+ * Optional EventLogDO client for persistent event log integration.
522
+ *
523
+ * When provided, the runtime can bootstrap from the DO on startup
524
+ * (recover from snapshots → catch up via `getSince`) and append
525
+ * new events through the DO automatically.
526
+ */
527
+ doClient?: EventLogDOClient;
528
+ /** Optional snapshot store for persisting/recovering materialized state. */
529
+ snapshotStore?: SnapshotStore;
530
+ /**
531
+ * How to handle events whose type no materializer handles.
532
+ * @default "warn"
533
+ */
534
+ unknownEventHandling?: UnknownEventHandling;
535
+ }
536
+ /**
537
+ * Runtime that drives one or more materializers from an event log.
538
+ *
539
+ * Handles:
540
+ * - Replaying the full log on startup
541
+ * - Applying new events as they arrive
542
+ * - Periodic snapshot persistence
543
+ * - Recovery from snapshots (replay only what's missing)
544
+ * @experimental
545
+ */
546
+ declare class MaterializerRuntime {
547
+ #private;
548
+ constructor(materializers: AnyMaterializer[], options?: MaterializerRuntimeOptions);
549
+ /**
550
+ * The lowest per-materializer watermark — the seq of the next event that
551
+ * at least one materializer has not yet applied. `0` when there are no
552
+ * materializers.
553
+ */
554
+ get appliedSeq(): number;
555
+ /**
556
+ * Replay a batch of entries, applying each entry only to the
557
+ * materializers whose own watermark is behind it — a materializer at or
558
+ * past an entry's seq (e.g. recovered from a snapshot, or already caught
559
+ * up) skips it, so no materializer ever double-applies an event.
560
+ * @returns The number of entries applied to at least one materializer.
561
+ */
562
+ applyEntries(entries: ReadonlyArray<EventLogEntry>): number;
563
+ /**
564
+ * Attempt to recover materialized state from a snapshot store.
565
+ *
566
+ * When a snapshot is found for a materializer, its state AND its own
567
+ * watermark are restored from that snapshot. A materializer with no
568
+ * snapshot keeps its current watermark (`0` for a fresh runtime) — it
569
+ * does NOT inherit another materializer's watermark, so it still catches
570
+ * up from the very beginning (REPLICA-04: previously a shared watermark
571
+ * was bumped to the MAX across snapshots, permanently skipping events 0..N
572
+ * for any un-snapshotted or lagging materializer).
573
+ * @returns The highest snapshot `appliedSeq` across all materializers, or
574
+ * `0` — kept for backward compatibility; callers that need the fetch
575
+ * watermark for catch-up should use the per-materializer minimum instead
576
+ * (see `initialize`).
577
+ */
578
+ recoverFromSnapshots(): Promise<number>;
579
+ /**
580
+ * Persist the current state of all materializers as snapshots, each
581
+ * tagged with ITS OWN watermark (not a shared one).
582
+ */
583
+ persistSnapshots(): Promise<void>;
584
+ /**
585
+ * Bootstrap the runtime from the EventLogDO.
586
+ *
587
+ * 1. Recover materialized state from snapshots (if a snapshotStore is
588
+ * configured).
589
+ * 2. Fetch all entries since the MINIMUM per-materializer watermark from
590
+ * the DO — not the maximum — so a materializer with no snapshot (or a
591
+ * lower one) still receives every event it hasn't seen (REPLICA-04).
592
+ * 3. Apply them through the materializers; `applyEntries` skips each
593
+ * entry for any materializer already past it, so nothing is double-applied.
594
+ *
595
+ * Call this once on startup / after the DO binding is available.
596
+ * @returns The number of entries applied during catch-up.
597
+ */
598
+ initialize(): Promise<number>;
599
+ /**
600
+ * Append an event to the EventLogDO and apply it through all
601
+ * materializers.
602
+ *
603
+ * This is a convenience over calling `doClient.append(...)` +
604
+ * `runtime.applyEntries(...)` yourself — it persists the event
605
+ * **then** applies the returned entry (with its assigned seq).
606
+ * @returns The persisted entry with its DO-assigned `seq`.
607
+ */
608
+ appendEvent(input: AppendEventInput): Promise<EventLogEntry>;
609
+ /**
610
+ * Reset all materializers to their initial state and clear snapshots.
611
+ */
612
+ reset(): void;
613
+ /**
614
+ * The list of registered materializers.
615
+ */
616
+ get materializers(): ReadonlyArray<Materializer<unknown>>;
617
+ }
618
+ /**
619
+ * Apply a {@link TableDiff} to the given SQLite database by translating
620
+ * each row change into an INSERT, UPDATE, or DELETE statement.
621
+ *
622
+ * All statements are wrapped in a single transaction.
623
+ * @param database SQLite adapter the statements run against.
624
+ * @param diff The table diff to apply.
625
+ * @param pkColumn Primary key column for DELETE/UPDATE (default `"id"`).
626
+ * @experimental
627
+ */
628
+ declare const applyDiffToDatabase: (database: SqliteAdapter, diff: TableDiff, pkColumn?: string) => void;
629
+ /**
630
+ * Apply multiple diffs **in order** within a single transaction.
631
+ *
632
+ * Each diff uses `"id"` as the primary key column. For tables with a custom
633
+ * PK, use {@link applyDiffToDatabase} per-diff and pass the PK explicitly.
634
+ * @experimental
635
+ */
636
+ declare const applyDiffsToDatabase: (database: SqliteAdapter, diffs: ReadonlyArray<TableDiff>) => void;
637
+ interface EventLogDOState {
638
+ storage: {
639
+ sql: {
640
+ exec: (query: string, ...params: unknown[]) => unknown;
641
+ };
642
+ /**
643
+ * The DO platform's native atomic-transaction primitive (async;
644
+ * commits on resolve, rolls back on throw/reject). Test doubles that
645
+ * omit it fall back to a bare (non-transactional) call — see
646
+ * `#handleAppend`.
647
+ */
648
+ transaction?: <T>(closure: () => Promise<T> | T) => Promise<T>;
649
+ };
650
+ }
651
+ /**
652
+ * `EventLogDO` is part of the experimental `@lunora/replica` API and may change without a major version bump.
653
+ * @experimental
654
+ */
655
+ declare class EventLogDO {
656
+ #private;
657
+ protected state: EventLogDOState;
658
+ protected env: unknown;
659
+ constructor(state: EventLogDOState, env: unknown);
660
+ fetch(request: Request): Promise<Response>;
661
+ }
662
+ /**
663
+ * `next()` advances the middleware chain. Called with no argument it forwards
664
+ * the current context unchanged; called with `{ ctx }` it shallow-merges the
665
+ * extension, and the result type reflects the widened context.
666
+ */
667
+ interface MiddlewareNext<ContextIn> {
668
+ (): Promise<ContextIn>;
669
+ <Extension extends Record<string, unknown>>(options: {
670
+ ctx: Extension;
671
+ }): Promise<ContextIn & Extension>;
672
+ }
673
+ /**
674
+ * A middleware receives the current context and a `next` continuation. Its
675
+ * return type becomes the builder's new context, so `return next({ ctx })`
676
+ * propagates the extension into every downstream `.use()` and the handler.
677
+ */
678
+ type Middleware<ContextIn, ContextOut> = (options: {
679
+ ctx: ContextIn;
680
+ next: MiddlewareNext<ContextIn>;
681
+ }) => ContextOut | Promise<ContextOut>;
682
+ /**
683
+ * The per-request `ctx.events` facade that {@link eventsContext} attaches.
684
+ *
685
+ * Each method delegates to the corresponding {@link EventLogDOClient} method,
686
+ * so handlers never need to import or reference the DO client directly.
687
+ * @experimental
688
+ */
689
+ interface EventsFacade {
690
+ /**
691
+ * Append one or more events to the log.
692
+ * @returns The persisted entries with their assigned `seq` numbers.
693
+ */
694
+ append: (events: {
695
+ payload: unknown;
696
+ timestamp?: number;
697
+ type: string;
698
+ }[]) => Promise<EventLogEntry[]>;
699
+ /**
700
+ * Fetch a paginated range of entries.
701
+ * @returns `{ entries, hasMore }` — `hasMore` is `true` when another
702
+ * page exists.
703
+ */
704
+ getRange: (fromSeq: number, limit?: number) => Promise<{
705
+ entries: EventLogEntry[];
706
+ hasMore: boolean;
707
+ }>;
708
+ /**
709
+ * Fetch all entries with `seq >= sinceSeq`.
710
+ *
711
+ * Pass `sinceSeq = 0` to fetch the entire log.
712
+ */
713
+ getSince: (sinceSeq: number) => Promise<EventLogEntry[]>;
714
+ /** Return the total number of entries currently in the log. */
715
+ getSize: () => Promise<number>;
716
+ /** Return the full log state — all entries plus the next seq number. */
717
+ getState: () => Promise<{
718
+ entries: EventLogEntry[];
719
+ nextSeq: number;
720
+ }>;
721
+ }
722
+ /**
723
+ * The context shape produced by {@link eventsContext}.
724
+ * @experimental
725
+ */
726
+ interface EventsContextOutput {
727
+ /** Typed event log facade backed by an {@link EventLogDOClient}. */
728
+ readonly events: EventsFacade;
729
+ }
730
+ /**
731
+ * Create a middleware that attaches a typed `ctx.events` facade backed by
732
+ * the given {@link EventLogDOClient}.
733
+ *
734
+ * The facade surfaces `append`, `getSince`, `getRange`, `getSize`, and
735
+ * `getState` — every method the DO client exposes — so handlers can read
736
+ * and write the event log without reaching for the DO stub directly.
737
+ *
738
+ * The middleware is unopinionated about which context it extends — it works
739
+ * with `MutationCtx`, `ActionCtx`, or `QueryCtx` equally.
740
+ * @param client A configured {@link EventLogDOClient} instance.
741
+ * @returns A Lunora middleware that injects `ctx.events`.
742
+ *
743
+ * ```ts
744
+ * const client = new EventLogDOClient({
745
+ * fetch: (req) => env.EVENTS.get(id).fetch(req),
746
+ * });
747
+ *
748
+ * export const logEvent = mutation
749
+ * .use(eventsContext(client))
750
+ * .mutation(async ({ ctx, args }) => {
751
+ * const [entry] = await ctx.events.append([{ type: "order.placed", payload: args }]);
752
+ * return entry;
753
+ * });
754
+ * ```
755
+ * @experimental
756
+ */
757
+ declare const eventsContext: <Context>(client: EventLogDOClient) => Middleware<Context, Context & EventsContextOutput>;
758
+ /**
759
+ * A dependency-light subscription sink interface that mirrors what
760
+ * `LunoraClient.subscribe` expects, so the mirror helper doesn't
761
+ * need to import `@lunora/client`.
762
+ * @experimental
763
+ */
764
+ interface SubscriptionClient {
765
+ subscribe: (functionRef: {
766
+ __lunoraRef: string;
767
+ }, args: Record<string, unknown>, callback: (data: unknown) => void, options?: {
768
+ shardKey?: string;
769
+ }) => () => void;
770
+ }
771
+ /**
772
+ * Subscribe a Lunora-query to the local mirror so every server push
773
+ * is applied to the local SQLite store.
774
+ *
775
+ * Each frame from a Lunora live query is the FULL current result set, so the
776
+ * callback treats it as a snapshot: it upserts every row present and emits a
777
+ * `delete` for any id that was mirrored on a previous frame but is absent now —
778
+ * otherwise rows that drop out of the server result would linger stale in the
779
+ * local mirror. Rows are keyed by their `id` field (the mirror's default primary
780
+ * key); a row without an `id` can't be reconciled on removal, and — because the
781
+ * mirror table's `id` column is `NOT NULL` — will fail the insert.
782
+ *
783
+ * The mirror table name is derived from the function ref alone (not `args`), so
784
+ * do NOT mirror two subscriptions to the same function with different `args`
785
+ * into the same mirror: they'd share one table and the snapshot-delete pass of
786
+ * one could remove rows still live in the other.
787
+ *
788
+ * Call the returned unsubscribe function to tear down both the client
789
+ * subscription and future mirror writes.
790
+ * @example
791
+ * ```ts
792
+ * const unsub = subscribeToMirror(client, mirror, api.todos.list, { userId });
793
+ * // Later:
794
+ * unsub();
795
+ * ```
796
+ * @experimental
797
+ */
798
+ declare const subscribeToMirror: (client: SubscriptionClient, mirror: LocalMirror, functionRef: {
799
+ __lunoraRef: string;
800
+ }, args: Record<string, unknown>, shardKey?: string) => (() => void);
801
+ /**
802
+ * Callback signature for state-change subscriptions.
803
+ * @experimental
804
+ */
805
+ type StateChangeCallback = (state: Readonly<Record<string, unknown>>) => void;
806
+ /**
807
+ * Callback signature for event-type subscriptions.
808
+ * @experimental
809
+ */
810
+ type EventCallback = (entry: EventLogEntry) => void;
811
+ /**
812
+ * Manages subscriptions to state changes and individual event types
813
+ * for the event-sourcing runtime.
814
+ *
815
+ * Each subscription returns an unsubscribe function — the caller is
816
+ * expected to call it during cleanup (e.g. in a React `useEffect`
817
+ * return or a Svelte `onDestroy`).
818
+ * @example
819
+ * ```ts
820
+ * const subs = new SubscriptionManager();
821
+ *
822
+ * // Subscribe to every state change
823
+ * const unsub1 = subs.onStateChange((state) => console.log("new state", state));
824
+ *
825
+ * // Subscribe to a specific event type
826
+ * const unsub2 = subs.onEvent("user-created", (entry) => console.log("user created", entry.payload));
827
+ *
828
+ * // Later, when state or events arrive:
829
+ * subs.notifyState({ users: [] });
830
+ * subs.notifyEvent({ seq: 1, type: "user-created", payload: { id: "1" }, timestamp: 100 });
831
+ *
832
+ * // Cleanup
833
+ * unsub1();
834
+ * unsub2();
835
+ * ```
836
+ * @experimental
837
+ */
838
+ declare class SubscriptionManager {
839
+ #private;
840
+ /**
841
+ * Subscribe to every state change emitted by the event source.
842
+ * @returns Unsubscribe function.
843
+ */
844
+ onStateChange(callback: StateChangeCallback): () => void;
845
+ /**
846
+ * Subscribe to a specific event type.
847
+ * @param eventType The event type to listen for (matches `entry.type`).
848
+ * @param callback Invoked with each matching entry.
849
+ * @returns Unsubscribe function.
850
+ */
851
+ onEvent(eventType: string, callback: EventCallback): () => void;
852
+ /**
853
+ * Notify all state-change subscribers with the current state.
854
+ */
855
+ notifyState(state: Readonly<Record<string, unknown>>): void;
856
+ /**
857
+ * Notify event-type subscribers whose `eventType` matches.
858
+ */
859
+ notifyEvent(entry: EventLogEntry): void;
860
+ /**
861
+ * Return the total number of active subscriptions.
862
+ */
863
+ get size(): number;
864
+ /**
865
+ * Remove all subscriptions.
866
+ */
867
+ clear(): void;
868
+ }
869
+ /**
870
+ * Options for constructing an {@link EventsSync}.
871
+ * @experimental
872
+ */
873
+ interface EventsSyncOptions {
874
+ /**
875
+ * Replay a batch of events through the derived-state machine.
876
+ *
877
+ * Called with every batch of new events fetched from the log. The
878
+ * consumer should feed these events into their state machine
879
+ * (e.g. an {@link import("@lunora/replica").EventSource | EventSource})
880
+ * so that the machine's state reflects the latest log position.
881
+ */
882
+ applyEvents: (events: ReadonlyArray<EventLogEntry>) => void;
883
+ /**
884
+ * Fetch all events whose `seq >= sinceSeq`.
885
+ *
886
+ * In a server-side context, this typically wraps
887
+ * {@link import("@lunora/replica").EventLogDOClient.getSince |
888
+ * EventLogDOClient.getSince()}.
889
+ * In a client context it could call a Lunora action that proxies to the
890
+ * event log, or read from an IndexedDB cache.
891
+ *
892
+ * Return an empty array when there are no new events.
893
+ */
894
+ fetchEventsSince: (sinceSeq: number) => Promise<ReadonlyArray<EventLogEntry>>;
895
+ /**
896
+ * Produce {@link TableDiff | TableDiffs} from the current derived state.
897
+ *
898
+ * Called after every batch of events has been applied. The consumer
899
+ * compares the state _before_ and _after_ the batch and returns the
900
+ * diffs needed to bring the LocalMirror up to date.
901
+ *
902
+ * Return an empty array when there are no changes to push to the mirror.
903
+ */
904
+ getTableDiffs: () => TableDiff[];
905
+ /**
906
+ * The local SQLite mirror to apply diffs to.
907
+ */
908
+ mirror: LocalMirror;
909
+ /**
910
+ * Called when an error occurs during a poll cycle.
911
+ *
912
+ * Defaults to `console.error`. Set to a no-op to suppress error logging.
913
+ */
914
+ onError?: (error: unknown) => void;
915
+ /**
916
+ * How often to poll for new events (in milliseconds).
917
+ * @default 5000
918
+ */
919
+ pollInterval?: number;
920
+ }
921
+ /**
922
+ * Periodically polls an event log, replays events through a state machine,
923
+ * converts the resulting state into {@link TableDiff | TableDiffs}, and
924
+ * applies them to a {@link LocalMirror}.
925
+ *
926
+ * The class is **transport-agnostic** — it accepts a generic
927
+ * `fetchEventsSince` function rather than coupling to a specific source
928
+ * (EventLogDO, WebSocket push, IndexedDB, etc.).
929
+ *
930
+ * ## Lifecycle
931
+ *
932
+ * 1. Call `start()` to begin periodic polling.
933
+ * 2. Call `sync()` to perform an immediate one-shot sync.
934
+ * 3. Call `stop()` to halt polling.
935
+ *
936
+ * The current watermark is exposed via `watermark` and advances
937
+ * monotonically as events are applied.
938
+ * @experimental
939
+ */
940
+ declare class EventsSync {
941
+ #private;
942
+ constructor(options: EventsSyncOptions);
943
+ /**
944
+ * The current watermark — the next `seq` the sync will fetch from.
945
+ *
946
+ * Starts at `0` (fetch everything). Advances to `max(seq) + 1` after
947
+ * each successful poll cycle.
948
+ */
949
+ get watermark(): number;
950
+ /**
951
+ * Start polling for new events on the configured interval.
952
+ *
953
+ * Does nothing if polling is already active.
954
+ * Does **not** perform an initial sync — call {@link sync} once if you
955
+ * need to catch up immediately.
956
+ */
957
+ start(): void;
958
+ /**
959
+ * Stop polling for new events.
960
+ *
961
+ * Safe to call when not started.
962
+ */
963
+ stop(): void;
964
+ /**
965
+ * Perform a one-shot sync: fetch events since the current watermark,
966
+ * apply them through the state machine, and push diffs to the mirror.
967
+ * @returns The number of events that were fetched and applied.
968
+ */
969
+ sync(): Promise<number>;
970
+ }
971
+ export { type AppendEventInput, type AppendOptions, type EventCallback, EventEmitter, type EventFactory, EventLog, EventLogDO, EventLogDOClient, type EventLogDOClientOptions, type EventLogEntry, type EventNamespace, type EventReducer, EventSource, type EventSourceEvents, type EventSourceOptions, type EventsContextOutput, type EventsDefinition, type EventsFacade, EventsSync, type EventsSyncOptions, InMemorySnapshotStore, type InputEvent, LocalMirror, type Materializer, type MaterializerDef, type MaterializerReducer, MaterializerRuntime, type MaterializerRuntimeOptions, type Seq, type SnapshotStore, type SqliteAdapter, type StateChangeCallback, type SubscriptionClient, SubscriptionManager, type TableDiff, UNHANDLED, type UnknownEventHandling, applyDiff, applyDiffToDatabase as applyDiffToDb, applyDiffToSnapshot, applyDiffs, applyDiffsToDatabase as applyDiffsToDb, defineEvents, defineMaterializer, eventsContext, subscribeToMirror };