@lunora/replica 0.0.0 → 1.0.0-alpha.3

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