@lunora/replica 1.0.0-alpha.5 → 1.0.0-alpha.7

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