@lunora/db 1.0.0-alpha.8 → 1.0.0-alpha.81

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 (33) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +7 -1
  3. package/dist/collections/index.d.mts +2 -2
  4. package/dist/collections/index.d.ts +2 -2
  5. package/dist/collections/index.mjs +1 -2
  6. package/dist/index.d.mts +144 -5
  7. package/dist/index.d.ts +144 -5
  8. package/dist/index.mjs +1 -8
  9. package/dist/mutators/index.d.mts +2 -2
  10. package/dist/mutators/index.d.ts +2 -2
  11. package/dist/mutators/index.mjs +1 -1
  12. package/dist/packem_shared/CHECKPOINT_FALLBACK_MS-DAWfz0yD.mjs +1 -0
  13. package/dist/packem_shared/DIRECT_TRANSACTION_METADATA_KEY-C-CHKj3n.mjs +1 -0
  14. package/dist/packem_shared/OUTBOX_MUTATION_FN_NAME-BfFCughR.mjs +1 -0
  15. package/dist/packem_shared/applyPlanToCollections-C_eyqNF9.mjs +1 -0
  16. package/dist/packem_shared/collection-options.d-BA8jp3ji.d.mts +357 -0
  17. package/dist/packem_shared/collection-options.d-BA8jp3ji.d.ts +357 -0
  18. package/dist/packem_shared/defineCollections-Czhhf-A8.mjs +1 -0
  19. package/dist/packem_shared/index.d-BCKTZhCD.d.mts +235 -0
  20. package/dist/packem_shared/index.d-BZ00iQoq.d.ts +235 -0
  21. package/dist/packem_shared/index.d-C3aBVnK7.d.ts +174 -0
  22. package/dist/packem_shared/index.d-Depww9_D.d.mts +174 -0
  23. package/package.json +3 -2
  24. package/dist/packem_shared/OUTBOX_MUTATION_FN_NAME-DZrP1gna.mjs +0 -100
  25. package/dist/packem_shared/bindMutators-Bh6giR9x.mjs +0 -66
  26. package/dist/packem_shared/collection-options.d-CbS3J_Fm.d.mts +0 -207
  27. package/dist/packem_shared/collection-options.d-CbS3J_Fm.d.ts +0 -207
  28. package/dist/packem_shared/createCheckpointRegistry-C1kzNWCs.mjs +0 -124
  29. package/dist/packem_shared/define-collections.d-DTS0ANuU.d.mts +0 -85
  30. package/dist/packem_shared/define-collections.d-Po97lX6i.d.ts +0 -85
  31. package/dist/packem_shared/define-mutators.d-C3DO284A.d.ts +0 -80
  32. package/dist/packem_shared/define-mutators.d-DNVJIpW8.d.mts +0 -80
  33. package/dist/packem_shared/defineCollections-DR6fcIkQ.mjs +0 -74
@@ -0,0 +1,357 @@
1
+ import { OutboxSink, LunoraClient, FunctionReference, SubscriptionError } from '@lunora/client';
2
+ import { CollectionConfig } from '@tanstack/db';
3
+ import { OnlineDetector } from '@tanstack/offline-transactions';
4
+ /**
5
+ * Reserved `mutationFns` key the unified outbox routes raw `client.mutation`
6
+ * offline writes through. `defineCollections` registers a handler under this
7
+ * name that reads `transaction.metadata` (functionPath + args) and replays the
8
+ * write, so a db app's direct mutations ride the same durable executor as its
9
+ * collection inserts instead of the standalone {@link OutboxSink} fallback.
10
+ */
11
+ declare const OUTBOX_MUTATION_FN_NAME = "__lunora_outbox__";
12
+ /**
13
+ * Provenance stamped on a durable write at enqueue time: the two questions a
14
+ * replay cannot answer from the persisted row once the write outlives the
15
+ * session that made it — WHO queued it, and WHICH shard it belongs to.
16
+ *
17
+ * Shared so both replay paths (`db.actions.*` and the reserved
18
+ * `__lunora_outbox__` handler) check the same fields; they drifted apart once
19
+ * already, and only one of them had the identity guard.
20
+ */
21
+ interface WriteProvenance extends Record<string, unknown> {
22
+ /** Issuing identity fingerprint; a replay drops the write when it no longer matches. */
23
+ identity: string | null;
24
+ /** Captured, not re-read at replay: a queued write follows the shard it was made against even if the app reboots pointed at another. */
25
+ shardKey?: string;
26
+ }
27
+ /** The metadata an outbox-routed transaction carries so its replay can call `client.mutation`. */
28
+ interface OutboxMutationMetadata extends WriteProvenance {
29
+ args: Record<string, unknown>;
30
+ clientId: string;
31
+ functionPath: string;
32
+ /** Stable `${clientId}:${mutationId}` replay key; passed back as the mutation id so a committed-but-unacked replay is server-idempotent. */
33
+ idempotencyKey: string;
34
+ mutationId: number;
35
+ }
36
+ /** A committable outbox transaction handle (the `OfflineTransaction` the executor mints). */
37
+ interface OutboxTransaction {
38
+ commit?: () => Promise<unknown>;
39
+ mutate: (callback: () => void) => unknown;
40
+ }
41
+ /**
42
+ * The slice of the TanStack `OfflineExecutor` the {@link createExecutorOutboxSink}
43
+ * drives. Declared structurally so `@lunora/db`'s outbox glue doesn't widen its
44
+ * coupling to the executor's full surface (and stays unit-testable with a fake).
45
+ */
46
+ interface OutboxExecutor {
47
+ createOfflineTransaction: (options: {
48
+ autoCommit?: boolean;
49
+ idempotencyKey?: string;
50
+ metadata?: Record<string, unknown>;
51
+ mutationFnName: string;
52
+ }) => OutboxTransaction;
53
+ getPendingCount: () => number;
54
+ }
55
+ /** Tuning for {@link createExecutorOutboxSink}. */
56
+ interface ExecutorOutboxSinkOptions {
57
+ /** Max persisted-but-unconfirmed writes before `enqueue` rejects with `OFFLINE_QUEUE_OVERFLOW` (default 1000, matching `OfflineQueue`). */
58
+ maxItems?: number;
59
+ /** `mutationFns` key the replay handler is registered under (default {@link OUTBOX_MUTATION_FN_NAME}). */
60
+ mutationFnName?: string;
61
+ }
62
+ /**
63
+ * The blessed {@link OutboxSink} over the TanStack `OfflineExecutor` — the single
64
+ * durable write path for a `@lunora/db` app. It persists each offline write as an
65
+ * executor transaction carrying the `client.mutation` target in `metadata`, then
66
+ * ports the two semantics the executor lacks vs the built-in `OfflineQueue`.
67
+ *
68
+ * First: a `maxItems` cap that **rejects** a new write at capacity with an
69
+ * `OFFLINE_QUEUE_OVERFLOW`-coded error — the {@link OutboxSink} contract, matching
70
+ * `OfflineQueue`. Rejecting (rather than evicting the oldest) preserves the
71
+ * at-least-once promise: an already-persisted write is never silently dropped, and
72
+ * the caller surfaces back-pressure to the issuing mutation (which rolls its
73
+ * optimistic write back).
74
+ * Second: the identity guard lives in the replay handler (`defineCollections`), which drops a write whose captured `identity` no longer matches — see {@link OutboxMutationMetadata}.
75
+ */
76
+ declare const createExecutorOutboxSink: (executor: OutboxExecutor, options?: ExecutorOutboxSinkOptions) => OutboxSink;
77
+ /** A row carrying the Lunora document id. */
78
+ type Row = Record<string, unknown> & {
79
+ _id: string;
80
+ };
81
+ /** The subset of a TanStack DB sync write channel that {@link makeDiffEmit} drives. */
82
+ interface SyncWriter<T extends object> {
83
+ begin: () => void;
84
+ commit: () => void;
85
+ write: (message: {
86
+ type: "insert" | "update";
87
+ value: T;
88
+ } | {
89
+ key: string;
90
+ type: "delete";
91
+ }) => void;
92
+ }
93
+ /** Index a row list into a keyed map. */
94
+ declare const toMap: <T extends object>(rows: ReadonlyArray<T>, getKey: (row: T) => string) => Map<string, T>;
95
+ /**
96
+ * Build an `emit(next)` that diffs a desired keyed snapshot into a collection's
97
+ * sync channel — only changed rows are written, so a reconnect snapshot or a
98
+ * scope change never churns the synced view out from under a pending optimistic
99
+ * row. The last-synced base is tracked in `syncedJson`.
100
+ *
101
+ * Change detection compares rows by `JSON.stringify`, which is key-order
102
+ * sensitive — safe here because server snapshots have stable column order
103
+ * across reconnects (same query projection). A sync source with unstable key
104
+ * ordering would need a structural compare instead.
105
+ *
106
+ * `syncedJson` holds the JSON-serialized form of each last-synced row, keyed
107
+ * by row id. It is the **sole** synced-state map — no parallel row-object map
108
+ * is kept. Each incoming value is serialized exactly once per tick (for both
109
+ * comparison and cache update), so the previous value is never re-serialized.
110
+ *
111
+ * Lifecycle: `syncedJson` must be owned by the caller at the same scope as any
112
+ * other per-collection state (e.g. outside the `sync.sync` callback), so the
113
+ * cache persists correctly across sync restarts. A new `makeDiffEmit` closure
114
+ * created on restart receives the same map reference and starts from the
115
+ * committed synced state — no spurious diffs on reconnect.
116
+ */
117
+ declare const makeDiffEmit: <T extends object>(syncedJson: Map<string, string>, writer: SyncWriter<T>) => (next: Map<string, T>) => void;
118
+ /**
119
+ * Run a Lunora mutation under the outbox's retry policy.
120
+ *
121
+ * The retryable/permanent split keys on whether the failure carries a server
122
+ * application error `code` (set by `@lunora/client`'s rpc when the server returns
123
+ * a `{ error: { code, … } }` envelope — validation, conflict, etc.). A coded
124
+ * error is a definite verdict: surface it as a `NonRetriableError` so the executor
125
+ * stops and TanStack DB rolls the optimistic insert back. Everything without a
126
+ * code is transient — a `fetch` network failure (`TypeError`) or an HTTP/infra
127
+ * blip the rpc surfaces as a code-less `Error` (a 5xx gateway page, a non-JSON
128
+ * body) — so it's rethrown as-is and the durable outbox replays it. Keying on
129
+ * `error instanceof TypeError` alone would wrongly drop the latter.
130
+ */
131
+ declare const runOutboxMutation: (mutate: () => Promise<unknown>) => Promise<void>;
132
+ /**
133
+ * An "always attempt" online detector. We deliberately don't trust
134
+ * `navigator.onLine`: some environments (and Playwright's `setOffline` under
135
+ * Firefox) leave it stuck, which would freeze the outbox. Instead the executor
136
+ * always tries the send and {@link runOutboxMutation}'s transient-error retry
137
+ * handles real offline; the periodic tick nudges the executor to drain the outbox
138
+ * so a queued write replays promptly once connectivity returns.
139
+ *
140
+ * `isOnline` is therefore intentionally always `true` — it gates the executor's
141
+ * attempts, not a UI signal. A consumer that wants to show real connectivity
142
+ * should read `navigator.onLine` itself, separately from this detector.
143
+ */
144
+ declare const createOptimisticOnlineDetector: () => OnlineDetector;
145
+ /** A watermark pair — the two monotonic lines a checkpoint registry gates on. */
146
+ interface CheckpointWatermark {
147
+ /** Op-log cursor the server has durably applied. */
148
+ checkpoint?: number;
149
+ /** Highest `clientSeq` the server has echoed back for this client. */
150
+ mutationId?: number;
151
+ }
152
+ /** Reported when the fallback releases an overlay the sync stream never confirmed. */
153
+ interface CheckpointFallbackEvent {
154
+ /** Which gate released. */
155
+ kind: "checkpoint" | "mutationId";
156
+ /** How long the release waited past the server acknowledgement, in ms. */
157
+ waitedMs: number;
158
+ /** The watermark that was acknowledged but never confirmed by a sync frame. */
159
+ watermark: number;
160
+ }
161
+ /** Counters for {@link CheckpointRegistry.stats} — feeds a debug/diagnostics surface. */
162
+ interface CheckpointRegistryStats {
163
+ /** How many times the fallback timer released an overlay (a non-zero value means sync frames are being lost). */
164
+ fallbacks: number;
165
+ /** Overlays currently waiting on a checkpoint cursor. */
166
+ pendingCheckpointWaiters: number;
167
+ /** Overlays currently waiting on a mutation id. */
168
+ pendingMutationWaiters: number;
169
+ }
170
+ /** Tuning for {@link createCheckpointRegistry}. */
171
+ interface CheckpointRegistryOptions {
172
+ /**
173
+ * How long an {@link CheckpointRegistry.acknowledge}d watermark waits for the
174
+ * authoritative sync frame before the overlay is released anyway. Default 3000.
175
+ * `0` disables the fallback (an overlay then waits forever for the frame — the
176
+ * pre-fallback behavior, which hangs on a dropped poke).
177
+ */
178
+ fallbackMs?: number;
179
+ /**
180
+ * Notified each time the fallback fires. A fallback is never *correct* — it
181
+ * means a poke or `settled` frame that should have confirmed the write never
182
+ * arrived — so this is the hook for a warning or a metric. Defaults to a
183
+ * one-shot `console.warn`.
184
+ */
185
+ onFallback?: (event: CheckpointFallbackEvent) => void;
186
+ }
187
+ /**
188
+ * Resolves the TanStack optimistic-overlay drop against the server's confirmed
189
+ * watermarks. A mutator's optimistic transaction returns `awaitMutationId(id)`
190
+ * (or `awaitCheckpoint(cursor)`); TanStack keeps the overlay until that promise
191
+ * settles, so the row de-duplicates exactly as the synced server value lands — no
192
+ * flash of the optimistic row disappearing then reappearing.
193
+ *
194
+ * Two inputs, deliberately distinct:
195
+ *
196
+ * - {@link CheckpointRegistry.resolve} is the **authoritative** advance, called by whoever owns
197
+ * the watermark stream — a `data`/`delta` frame's `lastMutationId`, or a shape poke's
198
+ * `checkpoint`. The synced rows have landed, so gates open immediately.
199
+ * - {@link CheckpointRegistry.acknowledge} is the **provisional** advance, called when the server
200
+ * has accepted the write (the mutator RPC ack) but the matching rows have not
201
+ * necessarily been delivered yet. Releasing here would drop the overlay before
202
+ * the synced row exists — a visible flicker — so instead it arms a bounded
203
+ * fallback. If the authoritative frame lands first the fallback is cancelled;
204
+ * if it never lands, the overlay is released after `fallbackMs` and the event is
205
+ * reported rather than hanging forever.
206
+ *
207
+ * That pairing is why a lost poke degrades to a late overlay drop instead of a
208
+ * permanently stuck `isPersisted` promise.
209
+ */
210
+ interface CheckpointRegistry {
211
+ /**
212
+ * Record a server-accepted watermark whose rows may not have synced yet: arms
213
+ * the bounded fallback described on {@link CheckpointRegistry}. Safe to call
214
+ * repeatedly; a watermark already passed is a no-op.
215
+ */
216
+ acknowledge: (watermark: CheckpointWatermark) => void;
217
+ /** Resolve once the server has acknowledged the op-log `cursor`. */
218
+ awaitCheckpoint: (cursor: number) => Promise<void>;
219
+ /** Resolve once the server has echoed a `lastMutationId >= id` for this client. */
220
+ awaitMutationId: (id: number) => Promise<void>;
221
+ /**
222
+ * Tear the registry down: `clearTimeout` every armed fallback timer and empty
223
+ * the armed set. Idempotent. A discarded registry (Vite HMR dispose, sign-out)
224
+ * can otherwise hold up to `fallbackMs` of pending `setTimeout`s alive through
225
+ * their closures — keeping a Node/SSR event loop from draining. Distinct from
226
+ * {@link CheckpointRegistry.resolve}: `resolve` settles parked *waiters* (and disarms the timers it
227
+ * subsumes as a side effect); `dispose` guarantees no armed timer survives,
228
+ * independent of any watermark.
229
+ */
230
+ dispose: () => void;
231
+ /** Advance the gates from a sync frame's watermark; later callers past the mark settle immediately. */
232
+ resolve: (watermark: CheckpointWatermark) => void;
233
+ /** Diagnostics counters — notably how often the fallback had to fire. */
234
+ stats: () => CheckpointRegistryStats;
235
+ }
236
+ /** Default fallback window: long enough that a slow-but-arriving poke wins, short enough that a UI isn't visibly stuck. */
237
+ declare const CHECKPOINT_FALLBACK_MS = 3e3;
238
+ /**
239
+ * A standalone checkpoint/mutation-id registry. Prefer {@link getShardCheckpoints}
240
+ * unless you are wiring a bespoke watermark stream — a registry must be shared by
241
+ * every collection on a shard (see that function for why).
242
+ */
243
+ declare const createCheckpointRegistry: (options?: CheckpointRegistryOptions) => CheckpointRegistry;
244
+ /**
245
+ * Release every pending overlay gate for `client` and drop its shard registries.
246
+ *
247
+ * The hot-reload / teardown escape hatch. When a module that owns collections and
248
+ * mutators is replaced — a Vite HMR update, a sign-out that rebuilds the data layer
249
+ * — the *old* bindings may still have transactions parked in `awaitMutationId`. The
250
+ * subscriptions that would have resolved them are gone with the old module, so
251
+ * without this those promises never settle and every one of their
252
+ * `transaction.isPersisted` waiters hangs forever.
253
+ *
254
+ * Resolving to `Infinity` settles the parked waiters (the writes were already sent;
255
+ * the server is authoritative regardless), and dropping the registries means the
256
+ * replacement module's bindings start from a clean per-shard gate.
257
+ *
258
+ * ```ts
259
+ * // In the module that owns the data layer:
260
+ * import.meta.hot?.dispose(() => releaseShardCheckpoints(client));
261
+ * ```
262
+ */
263
+ declare const releaseShardCheckpoints: (client: LunoraClient) => void;
264
+ /**
265
+ * The shared checkpoint registry for `client` + `shardKey` — created on first use.
266
+ * This is the registry {@link lunoraCollectionOptions} and
267
+ * {@link import("./define-mutators").bindMutators} default to, which is what makes
268
+ * a multi-collection shard work without the caller relaying pokes between
269
+ * registries by hand.
270
+ *
271
+ * `options` applies **only when the registry is created**. Because the point is that
272
+ * every collection and mutator on a shard shares one gate, a later call cannot
273
+ * retune an existing registry — it returns the existing one and `options` is ignored.
274
+ * To control `fallbackMs` / `onFallback`, build the registry yourself with
275
+ * {@link createCheckpointRegistry} and pass it explicitly to every
276
+ * `lunoraCollectionOptions` and `bindMutators` call for that shard.
277
+ */
278
+ declare const getShardCheckpoints: (client: LunoraClient, shardKey?: string, options?: CheckpointRegistryOptions) => CheckpointRegistry;
279
+ /**
280
+ * A replication-shape sync source (the local-first partial-replication path).
281
+ * Mutually exclusive with {@link LunoraCollectionConfig.list}: the collection
282
+ * live-syncs the named shape's rowset via the client's poke protocol
283
+ * (`subscribeShape`) instead of a full-table `list` query subscription.
284
+ */
285
+ interface ShapeSource {
286
+ /** Validated shape parameters (the partition selector — e.g. `{ channelId }`). */
287
+ args?: Record<string, unknown>;
288
+ /** The `defineShape` export name registered in `LUNORA_SHAPES`. */
289
+ name: string;
290
+ /** Routes the subscription to a specific shard's DO when the table is sharded. */
291
+ shardKey?: string;
292
+ }
293
+ /** Declarative inputs for {@link lunoraCollectionOptions}. */
294
+ interface LunoraCollectionConfig<TRow extends Row> {
295
+ /**
296
+ * The registry optimistic overlays are gated on. Defaults to the shared
297
+ * per-shard registry ({@link getShardCheckpoints}), which is what a
298
+ * multi-collection shard needs — pass one explicitly only to isolate a
299
+ * collection's gate (tests) or to supply custom {@link CheckpointRegistryOptions}.
300
+ */
301
+ checkpoints?: CheckpointRegistry;
302
+ /** The Lunora client to subscribe through. */
303
+ client: LunoraClient;
304
+ /** Row key extractor — defaults to `row._id`. */
305
+ getKey?: (row: TRow) => string;
306
+ /** Collection id (TanStack identity) — defaults to the `list` function path (or `shape:` + the shape name). */
307
+ id?: string;
308
+ /** The Lunora query that lists the rows (the full-table sync source). Mutually exclusive with {@link LunoraCollectionConfig.shape}. */
309
+ list?: FunctionReference;
310
+ /**
311
+ * When the collection starts syncing. `"lazy"` (default) starts on the first
312
+ * `useLiveQuery` subscriber; `"eager"` starts at creation (TanStack's
313
+ * `startSync`) — for small "instant" reference data you want warm at boot.
314
+ * No effect on a `scopeBy` collection, which has nothing to sync until scoped.
315
+ * (Even eager, TanStack pauses sync while there are no subscribers, per its
316
+ * `gcTime` lifecycle — "warm while referenced", not pinned forever.)
317
+ */
318
+ load?: "eager" | "lazy";
319
+ /** Notified when the underlying subscription errors; the collection always leaves `loading` regardless. */
320
+ onError?: (error: SubscriptionError) => void;
321
+ /** When set, the collection stays empty until {@link LunoraCollectionOptions.scope} points it at args (sharded). */
322
+ scopeBy?: string;
323
+ /** A replication shape as the sync source (partial replication). Mutually exclusive with {@link LunoraCollectionConfig.list}. */
324
+ shape?: ShapeSource;
325
+ /**
326
+ * Routes the `list` subscription — and the confirmed-mutation watermark its
327
+ * data/`settled` frames advance the checkpoint gate from — to a specific
328
+ * shard's DO. Applies to the `list` source; a `shape` carries its own
329
+ * {@link ShapeSource.shardKey}. Without it the list path falls back to the
330
+ * default ("") watermark bucket, which must not be compared against a
331
+ * per-shard mutator's sequence line (it would drop a sharded overlay early or
332
+ * hang it forever).
333
+ */
334
+ shardKey?: string;
335
+ }
336
+ /** The result of {@link lunoraCollectionOptions}: a TanStack collection config plus its sync controls. */
337
+ interface LunoraCollectionOptions<TRow extends Row> {
338
+ /** Resolves optimistic-overlay drops against the server's confirmed watermarks. */
339
+ checkpoints: CheckpointRegistry;
340
+ /** Pass to TanStack's `createCollection`. */
341
+ config: CollectionConfig<TRow, string>;
342
+ /** Re-point a `scopeBy` collection's subscription (omit `args` to detach). No-op for unscoped collections. */
343
+ scope: (args?: Record<string, unknown>) => void;
344
+ }
345
+ /**
346
+ * Build a TanStack DB collection config (+ sync controls) that live-syncs a
347
+ * Lunora `list` query through the client. This is the reusable core lifted out of
348
+ * {@link import("./define-collections").defineCollections}: the same `makeDiffEmit`
349
+ * diff-into-channel, `autoIndex:"eager"` + B-tree indexes, scoped-resubscribe, and
350
+ * fail-safe `markReady`-on-error behavior, exposed as a standalone
351
+ * collection-options creator so apps (and codegen) can compose it directly.
352
+ *
353
+ * The returned `checkpoints` registry lets a mutator runtime resolve optimistic
354
+ * overlays against confirmed server watermarks (see {@link CheckpointRegistry}).
355
+ */
356
+ declare const lunoraCollectionOptions: <TRow extends Row>(options: LunoraCollectionConfig<TRow>) => LunoraCollectionOptions<TRow>;
357
+ export { CHECKPOINT_FALLBACK_MS as C, ExecutorOutboxSinkOptions as E, LunoraCollectionConfig as L, OUTBOX_MUTATION_FN_NAME as O, Row as R, SyncWriter as S, CheckpointFallbackEvent as a, CheckpointRegistry as b, CheckpointRegistryOptions as c, CheckpointRegistryStats as d, CheckpointWatermark as e, LunoraCollectionOptions as f, OutboxExecutor as g, OutboxMutationMetadata as h, createCheckpointRegistry as i, createExecutorOutboxSink as j, createOptimisticOnlineDetector as k, getShardCheckpoints as l, lunoraCollectionOptions as m, makeDiffEmit as n, runOutboxMutation as o, releaseShardCheckpoints as r, toMap as t };