@lunora/db 1.0.0-alpha.3 → 1.0.0-alpha.31

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.
@@ -0,0 +1,166 @@
1
+ import { FunctionReference, SubscriptionError, LunoraClient } from '@lunora/client';
2
+ import { Transaction, Collection } from '@tanstack/db';
3
+ import { OfflineExecutor, StorageDiagnostic } from '@tanstack/offline-transactions';
4
+ import { R as Row } from "./collection-options.d-B_2IXvdU.js";
5
+ /** Element type of an array (the row type a `list` query returns). */
6
+ type Element<T> = T extends ReadonlyArray<infer E> ? E : never;
7
+ /** `true` for the `any` type, `false` otherwise. */
8
+ type IsAny<T> = 0 extends 1 & T ? true : false;
9
+ /**
10
+ * The row type a `list` query syncs. For `TList = any` (the heterogeneous-map
11
+ * constraint) it resolves to the permissive {@link Row}, not `never` — otherwise
12
+ * the constraint would force every `optimistic` to return `never`. For a concrete
13
+ * `FunctionReference` it's the element type of the query's array return.
14
+ */
15
+ type RowOfList<TList> = IsAny<TList> extends true ? Row : TList extends FunctionReference<infer _K, infer _A, infer R> ? Element<R> & Row : never;
16
+ /** Maps a write through the durable outbox: optimistic insert + a retried mutation. */
17
+ interface InsertBinding<TRow extends Row, TInput> {
18
+ /** The Lunora mutation that persists the row. */
19
+ mutation: FunctionReference;
20
+ /** Build the optimistic row to insert from the action input + the generated client id. */
21
+ optimistic: (input: TInput, id: string) => TRow;
22
+ /** Build the mutation args from the persisted optimistic row (forward `_id` as the `clientId`). */
23
+ toArgs: (row: TRow) => Record<string, unknown>;
24
+ }
25
+ /** Declarative binding of a Lunora table to a live collection (+ optional write action). */
26
+ interface CollectionDef<TList extends FunctionReference, TInput = never> {
27
+ /** Row key extractor — defaults to `row._id`. */
28
+ getKey?: (row: RowOfList<TList>) => string;
29
+ /** Optional write binding — present iff this collection is written through the outbox. */
30
+ insert?: InsertBinding<RowOfList<TList>, TInput>;
31
+ /** The Lunora query that lists the rows (the sync source). */
32
+ list: TList;
33
+ /**
34
+ * When this collection starts syncing — `"lazy"` (default) on the first
35
+ * `useLiveQuery` subscriber, or `"eager"` at creation, for small "instant"
36
+ * reference data you want warm at boot. Pairs with `scopeBy` for partial
37
+ * (per-scope) loading — together they give the full lazy/partial/eager
38
+ * (Linear `lazy`/`partial`/`instant`) load taxonomy declaratively. No effect
39
+ * on a `scopeBy` collection (nothing to sync until scoped).
40
+ */
41
+ load?: "eager" | "lazy";
42
+ /**
43
+ * Notified when the underlying `list` subscription errors (e.g. the server
44
+ * rejects it). Without this the error would be swallowed and the collection
45
+ * could hang in `loading`; the binding always moves the collection out of
46
+ * `loading` on error, and forwards the error here if supplied.
47
+ */
48
+ onError?: (error: SubscriptionError) => void;
49
+ /** A field that scopes the list (e.g. a shard key); makes the collection re-pointable via `scope`. */
50
+ scopeBy?: string;
51
+ /**
52
+ * Routes the `list` subscription (and the confirmed-mutation watermark its
53
+ * frames advance the checkpoint gate from) to a specific shard's DO — so a
54
+ * sharded collection's overlay gate compares against that shard's mutator
55
+ * sequence line, not the default ("") watermark bucket.
56
+ */
57
+ shardKey?: string;
58
+ }
59
+ type AnyDef = CollectionDef<any, any>;
60
+ /**
61
+ * The public row type a collection exposes — the element type of its `list`
62
+ * query's return, with no `& Row`: a `Collection&lt;T>` is invariant in `T`, so the
63
+ * exposed type must be exactly the document type, not a subtype.
64
+ */
65
+ type RowOf<C extends AnyDef> = C["list"] extends FunctionReference<infer _K, infer _A, infer R> ? Element<R> : never;
66
+ /** The action input type, inferred structurally from the def's optimistic insert. */
67
+ type InputOf<C> = C extends {
68
+ insert: {
69
+ optimistic: (input: infer I, id: string) => unknown;
70
+ };
71
+ } ? I : never;
72
+ /** A queued write that was permanently dropped, passed to {@link DefineCollectionsOptions.onWriteRejected}. */
73
+ interface WriteRejectedEvent {
74
+ /**
75
+ * The machine-readable reason — the server's error `code` (e.g. `CONFLICT`,
76
+ * `FORBIDDEN`), or `UNKNOWN_MUTATION_FN` when the write referenced a collection
77
+ * that no longer exists (removed in a deploy). Mirrors the client's
78
+ * `MutationSettledEvent.code` so a consumer can branch on the verdict.
79
+ */
80
+ code?: string;
81
+ /** The collection/table name the write targeted. */
82
+ collection: string;
83
+ /** The error that dropped the write (message carried by the underlying `NonRetriableError`). */
84
+ error: Error;
85
+ /**
86
+ * The optimistic row being rolled back (the rollback follows the callback).
87
+ * Absent only if the dropped transaction carried no recoverable row (e.g. some
88
+ * `UNKNOWN_MUTATION_FN` cases).
89
+ */
90
+ row?: Row;
91
+ }
92
+ /** Options for {@link defineCollections}. */
93
+ interface DefineCollectionsOptions {
94
+ /**
95
+ * Invoked when a leadership change occurs across tabs (only the leader tab
96
+ * drains the durable outbox). Informational — useful for diagnostics; the
97
+ * library handles the election itself.
98
+ */
99
+ onLeadershipChange?: (isLeader: boolean) => void;
100
+ /**
101
+ * Invoked when the durable outbox's storage layer fails — IndexedDB
102
+ * unavailable (private mode), blocked, or quota exceeded. The standalone
103
+ * client surfaces this via `offlineQueue.onPersistenceError`; this is the
104
+ * collection-layer counterpart. A storage failure means a write is NOT durable
105
+ * and won't survive a reload, so surface it (e.g. "your change may not be
106
+ * saved if you close this tab").
107
+ */
108
+ onStorageFailure?: (diagnostic: StorageDiagnostic) => void;
109
+ /**
110
+ * Invoked as a queued write is permanently dropped: a coded application error
111
+ * from the server (validation, RLS denial, conflict, surfaced as a
112
+ * `NonRetriableError`), OR a write whose target collection no longer exists —
113
+ * removed/renamed in a deploy (`code: "UNKNOWN_MUTATION_FN"`). This is the
114
+ * aggregate, fire-and-forget-safe channel: unlike awaiting the per-action
115
+ * `transaction` returned by `actions[name](...)`, it fires even when the caller
116
+ * never retained that handle, so a UI can surface "couldn't save" instead of a
117
+ * silently vanishing row. Transient failures (offline, 5xx) are retried by the
118
+ * outbox, not reported here.
119
+ *
120
+ * Timing: the callback runs at the point of rejection; the executor's
121
+ * optimistic-row rollback follows immediately after. The event's `row` is the
122
+ * (about-to-be-removed) optimistic row, so don't depend on the collection
123
+ * already reflecting the removal from inside the handler — use `row`/`error`
124
+ * directly (e.g. for a toast).
125
+ */
126
+ onWriteRejected?: (event: WriteRejectedEvent) => void;
127
+ }
128
+ /** The wired data layer `defineCollections` returns. */
129
+ interface LunoraDb<D extends Record<string, AnyDef>> {
130
+ /** Optimistic, durable, retried write actions — present for `insert` collections. */
131
+ actions: { [K in keyof D]: D[K] extends {
132
+ insert: object;
133
+ } ? (input: InputOf<D[K]>) => {
134
+ id: string;
135
+ transaction: Transaction;
136
+ } : never; };
137
+ /** The live, synced collections — feed these to `useLiveQuery`. */
138
+ collections: { [K in keyof D]: Collection<RowOf<D[K]>, string>; };
139
+ /** The shared offline executor (the outbox). */
140
+ executor: OfflineExecutor;
141
+ /**
142
+ * Number of writes still pending in the durable outbox — the depth for a
143
+ * "N changes waiting to sync" indicator. A convenience over reaching through
144
+ * `executor.getPendingCount()`. **Pull-only** (the underlying TanStack
145
+ * executor exposes no change subscription): read it after a `db.actions.*`
146
+ * call and on connection-status changes, or poll. The standalone
147
+ * `LunoraClient` exposes the reactive `onPendingChange` for its built-in queue.
148
+ */
149
+ pendingCount: () => number;
150
+ /** Re-point a `scopeBy` collection's subscription (omit `args` to detach) — present for scoped collections. */
151
+ scope: { [K in keyof D]: D[K] extends {
152
+ scopeBy: string;
153
+ } ? (args?: Record<string, unknown>) => void : never; };
154
+ }
155
+ /**
156
+ * Wire a set of Lunora tables into a TanStack DB data layer in one declaration:
157
+ * each entry becomes a live, auto-indexed collection synced from its `list` query,
158
+ * and `insert` entries get an optimistic write action backed by the
159
+ * offline-transactions outbox (durable, retried, client-id-keyed). Scoped
160
+ * (`scopeBy`) collections are re-pointable for sharded queries.
161
+ *
162
+ * This is the hand-written form; `@lunora/codegen` can emit a fully-typed call to
163
+ * it from `schema.ts`, so an app writes nothing.
164
+ */
165
+ declare const defineCollections: <D extends Record<string, AnyDef>>(client: LunoraClient, defs: D, options?: DefineCollectionsOptions) => LunoraDb<D>;
166
+ export { CollectionDef as C, DefineCollectionsOptions as D, InsertBinding as I, LunoraDb as L, WriteRejectedEvent as W, defineCollections as d };
@@ -0,0 +1,148 @@
1
+ import { LunoraClient } from '@lunora/client';
2
+ import { Collection, Transaction } from '@tanstack/db';
3
+ import { C as CheckpointRegistry, R as Row } from "./collection-options.d-B_2IXvdU.mjs";
4
+ /**
5
+ * TanStack DB's "direct transaction" marker.
6
+ *
7
+ * A completed transaction's optimistic rows are discarded as **stale** unless
8
+ * either a synced transaction for the same key is already queued, or the
9
+ * transaction carried this flag (`CollectionStateManager.recomputeOptimisticState`
10
+ * → `pendingOptimisticDirectUpserts`). Marked rows instead survive until a sync
11
+ * operation for that key actually lands, which is precisely the semantics a Lunora
12
+ * custom mutator needs: the server is the linearization point, so the prediction
13
+ * must stay visible until the authoritative row arrives. Without it, a text edit
14
+ * visibly reverts to the last synced value the moment the push is acked.
15
+ *
16
+ * The literal is pinned here because `@tanstack/db` does not re-export the constant
17
+ * from its package root (it lives in the unexported
18
+ * `collection/transaction-metadata` module). `__tests__/define-mutators.test.ts`
19
+ * reads that module off disk and fails if the upstream value ever changes.
20
+ */
21
+ declare const DIRECT_TRANSACTION_METADATA_KEY = "__tanstack_db_direct";
22
+ /** The local store a client mutator's optimistic body writes against. */
23
+ interface ClientMutatorContext {
24
+ /** The wired collections, keyed by name — apply optimistic inserts/updates/deletes here. */
25
+ collections: Record<string, Collection<Row, string>>;
26
+ }
27
+ /**
28
+ * A generated mutator reference (`api.mutators.sendMessage`), accepted by
29
+ * {@link defineMutator} in place of a hand-written path string.
30
+ *
31
+ * Declared structurally rather than imported from `@lunora/client` so this module
32
+ * keeps its narrow dependency surface; the shape matches `FunctionReference`, and
33
+ * the phantom marker carries the server mutator's arg type so the client body's
34
+ * args are **inferred** instead of restated.
35
+ */
36
+ interface MutatorReference<TArgs = unknown> {
37
+ readonly __lunoraPhantom?: {
38
+ args: TArgs;
39
+ kind: unknown;
40
+ returns: unknown;
41
+ };
42
+ readonly __lunoraRef: string;
43
+ }
44
+ /** Args type carried by a {@link MutatorReference}. */
45
+ type ArgsOfReference<R> = R extends MutatorReference<infer A> ? A : never;
46
+ /** A client-side custom mutator: an optimistic body plus the path of its authoritative server impl. */
47
+ interface ClientMutatorDef<TArgs> {
48
+ /** Brand so codegen / `bindMutators` can recognize a mutator definition. */
49
+ __lunoraClientMutator: true;
50
+ /** The optimistic update applied to the local collections before the server confirms. */
51
+ apply: (context: ClientMutatorContext, args: TArgs) => void;
52
+ /** The Lunora function path of the server-authoritative mutator (`defineMutator` on the server). */
53
+ serverRef: string;
54
+ }
55
+ /**
56
+ * Declare a client-side custom mutator. `apply` runs optimistically against the
57
+ * local TanStack collections; `serverRef` names the authoritative server mutator
58
+ * the write is pushed to over the watermark protocol. The server impl is the
59
+ * linearization point — this body is a prediction the server can override.
60
+ *
61
+ * **Pass a generated reference, not a string.** `serverRef: api.mutators.sendMessage`
62
+ * both binds the path at compile time — a rename, a typo, or a moved file becomes a
63
+ * type error instead of a mutation that silently fails at runtime — and **infers
64
+ * `TArgs` from the server mutator's own validators**, so the arg type is declared
65
+ * once on the server rather than restated in every client body:
66
+ *
67
+ * ```ts
68
+ * // Typed + checked: args inferred from the server mutator.
69
+ * defineMutator({
70
+ * apply: ({ collections }, args) => { … }, // args: { channelId: Id<"channels">; text: string }
71
+ * serverRef: api.mutators.sendMessage,
72
+ * });
73
+ *
74
+ * // Escape hatch: a path string still works, but nothing checks it and you must
75
+ * // restate the args yourself.
76
+ * defineMutator<{ text: string }>({ apply, serverRef: "mutators:sendMessage" });
77
+ * ```
78
+ */
79
+ declare const defineMutator: {
80
+ <TArgs = Record<string, unknown>>(definition: {
81
+ apply: (context: ClientMutatorContext, args: TArgs) => void;
82
+ serverRef: string;
83
+ }): ClientMutatorDef<TArgs>;
84
+ <R extends MutatorReference<never>>(definition: {
85
+ apply: (context: ClientMutatorContext, args: ArgsOfReference<R>) => void;
86
+ serverRef: R;
87
+ }): ClientMutatorDef<ArgsOfReference<R>>;
88
+ };
89
+ type AnyMutatorMap = Record<string, ClientMutatorDef<any>>;
90
+ /** Args type of a mutator definition. */
91
+ type ArgsOf<M> = M extends ClientMutatorDef<infer A> ? A : never;
92
+ /** Inputs `bindMutators` needs to run a mutator: the local store + how the overlay drops. */
93
+ interface BindMutatorsContext {
94
+ /**
95
+ * Resolves the optimistic-overlay drop against confirmed server watermarks: a
96
+ * mutation's overlay is held until the sync stream echoes
97
+ * `lastMutationId >= clientSeq` (via {@link CheckpointRegistry.resolve}), so the
98
+ * row never flashes out and back.
99
+ *
100
+ * Defaults to the shared per-shard registry for `client` + {@link shardKey}
101
+ * ({@link getShardCheckpoints}) — the same one
102
+ * {@link import("./collection-options").lunoraCollectionOptions} defaults to, so
103
+ * a shard's collections and its mutators gate on one watermark line without the
104
+ * caller wiring them together. Pass `false` to drop the overlay as soon as the
105
+ * server accepts the write (the by-value sync diff then converges the synced row
106
+ * in place).
107
+ */
108
+ checkpoints?: CheckpointRegistry | false;
109
+ /** The wired collections the optimistic bodies write against. */
110
+ collections: Record<string, Collection<Row, string>>;
111
+ /** Optional shard key the mutator's server push is routed to. */
112
+ shardKey?: string;
113
+ }
114
+ /** Calling a bound mutator runs the optimistic body + pushes the server write; returns the TanStack transaction. */
115
+ type BoundMutators<M extends AnyMutatorMap> = { [K in keyof M]: (args: ArgsOf<M[K]>) => Transaction; };
116
+ /**
117
+ * Bind a set of client mutators to a client + local store. Each returned handle,
118
+ * when called, opens a TanStack optimistic transaction: the mutator's `apply`
119
+ * body writes the predicted rows into the collections, and the transaction's
120
+ * `mutationFn` pushes the authoritative write through
121
+ * {@link LunoraClient.callMutator} under a monotonic per-client `clientSeq`.
122
+ *
123
+ * Rebase-on-poke is free — TanStack DB re-derives every pending optimistic overlay
124
+ * over the latest synced base on each sync tick. The overlay is dropped when the
125
+ * server confirms the write (and, if `checkpoints` is supplied, once it echoes the
126
+ * matching watermark so the synced row has landed).
127
+ *
128
+ * The `clientSeq` generator is seeded from the server's echoed watermark
129
+ * ({@link LunoraClient.confirmedMutationWatermark}) on every issue, so a reload —
130
+ * which resets this in-memory counter while the server keeps a durable per-client
131
+ * watermark — never reissues a sequence the DO has already applied. As a backstop
132
+ * for the very first push of a fresh session (before any ack has taught the client
133
+ * the watermark), a push the DO swallows as a replay (`applied === false`) is
134
+ * reissued above the now-known watermark instead of being mistaken for a confirmed
135
+ * write — closing the silent-drop window without risking a double-apply (a fresh
136
+ * session's first stale push provably cannot be an honest replay).
137
+ *
138
+ * Pushes are **serialized per binding** (a FIFO chain): the DO rejects any push
139
+ * with `clientSeq > watermark + 1` as `OUT_OF_ORDER` and drops the write, so two
140
+ * mutators fired concurrently must not race the network into a gap. Each push
141
+ * waits for the previous one's ack and assigns its `clientSeq` *inside* the
142
+ * critical section — from the live watermark — so the sequence is always exactly
143
+ * `watermark + 1`. Because a failed mutation never advances the server watermark,
144
+ * a permanently-rejected predecessor can't wedge the chain: the next push simply
145
+ * reclaims the same `watermark + 1` instead of leaving a hole the DO waits on.
146
+ */
147
+ declare const bindMutators: <M extends AnyMutatorMap>(client: LunoraClient, context: BindMutatorsContext, mutators: M) => BoundMutators<M>;
148
+ export { BindMutatorsContext as B, ClientMutatorContext as C, DIRECT_TRANSACTION_METADATA_KEY as D, MutatorReference as M, BoundMutators as a, ClientMutatorDef as b, bindMutators as c, defineMutator as d };
@@ -0,0 +1,148 @@
1
+ import { LunoraClient } from '@lunora/client';
2
+ import { Collection, Transaction } from '@tanstack/db';
3
+ import { C as CheckpointRegistry, R as Row } from "./collection-options.d-B_2IXvdU.js";
4
+ /**
5
+ * TanStack DB's "direct transaction" marker.
6
+ *
7
+ * A completed transaction's optimistic rows are discarded as **stale** unless
8
+ * either a synced transaction for the same key is already queued, or the
9
+ * transaction carried this flag (`CollectionStateManager.recomputeOptimisticState`
10
+ * → `pendingOptimisticDirectUpserts`). Marked rows instead survive until a sync
11
+ * operation for that key actually lands, which is precisely the semantics a Lunora
12
+ * custom mutator needs: the server is the linearization point, so the prediction
13
+ * must stay visible until the authoritative row arrives. Without it, a text edit
14
+ * visibly reverts to the last synced value the moment the push is acked.
15
+ *
16
+ * The literal is pinned here because `@tanstack/db` does not re-export the constant
17
+ * from its package root (it lives in the unexported
18
+ * `collection/transaction-metadata` module). `__tests__/define-mutators.test.ts`
19
+ * reads that module off disk and fails if the upstream value ever changes.
20
+ */
21
+ declare const DIRECT_TRANSACTION_METADATA_KEY = "__tanstack_db_direct";
22
+ /** The local store a client mutator's optimistic body writes against. */
23
+ interface ClientMutatorContext {
24
+ /** The wired collections, keyed by name — apply optimistic inserts/updates/deletes here. */
25
+ collections: Record<string, Collection<Row, string>>;
26
+ }
27
+ /**
28
+ * A generated mutator reference (`api.mutators.sendMessage`), accepted by
29
+ * {@link defineMutator} in place of a hand-written path string.
30
+ *
31
+ * Declared structurally rather than imported from `@lunora/client` so this module
32
+ * keeps its narrow dependency surface; the shape matches `FunctionReference`, and
33
+ * the phantom marker carries the server mutator's arg type so the client body's
34
+ * args are **inferred** instead of restated.
35
+ */
36
+ interface MutatorReference<TArgs = unknown> {
37
+ readonly __lunoraPhantom?: {
38
+ args: TArgs;
39
+ kind: unknown;
40
+ returns: unknown;
41
+ };
42
+ readonly __lunoraRef: string;
43
+ }
44
+ /** Args type carried by a {@link MutatorReference}. */
45
+ type ArgsOfReference<R> = R extends MutatorReference<infer A> ? A : never;
46
+ /** A client-side custom mutator: an optimistic body plus the path of its authoritative server impl. */
47
+ interface ClientMutatorDef<TArgs> {
48
+ /** Brand so codegen / `bindMutators` can recognize a mutator definition. */
49
+ __lunoraClientMutator: true;
50
+ /** The optimistic update applied to the local collections before the server confirms. */
51
+ apply: (context: ClientMutatorContext, args: TArgs) => void;
52
+ /** The Lunora function path of the server-authoritative mutator (`defineMutator` on the server). */
53
+ serverRef: string;
54
+ }
55
+ /**
56
+ * Declare a client-side custom mutator. `apply` runs optimistically against the
57
+ * local TanStack collections; `serverRef` names the authoritative server mutator
58
+ * the write is pushed to over the watermark protocol. The server impl is the
59
+ * linearization point — this body is a prediction the server can override.
60
+ *
61
+ * **Pass a generated reference, not a string.** `serverRef: api.mutators.sendMessage`
62
+ * both binds the path at compile time — a rename, a typo, or a moved file becomes a
63
+ * type error instead of a mutation that silently fails at runtime — and **infers
64
+ * `TArgs` from the server mutator's own validators**, so the arg type is declared
65
+ * once on the server rather than restated in every client body:
66
+ *
67
+ * ```ts
68
+ * // Typed + checked: args inferred from the server mutator.
69
+ * defineMutator({
70
+ * apply: ({ collections }, args) => { … }, // args: { channelId: Id<"channels">; text: string }
71
+ * serverRef: api.mutators.sendMessage,
72
+ * });
73
+ *
74
+ * // Escape hatch: a path string still works, but nothing checks it and you must
75
+ * // restate the args yourself.
76
+ * defineMutator<{ text: string }>({ apply, serverRef: "mutators:sendMessage" });
77
+ * ```
78
+ */
79
+ declare const defineMutator: {
80
+ <TArgs = Record<string, unknown>>(definition: {
81
+ apply: (context: ClientMutatorContext, args: TArgs) => void;
82
+ serverRef: string;
83
+ }): ClientMutatorDef<TArgs>;
84
+ <R extends MutatorReference<never>>(definition: {
85
+ apply: (context: ClientMutatorContext, args: ArgsOfReference<R>) => void;
86
+ serverRef: R;
87
+ }): ClientMutatorDef<ArgsOfReference<R>>;
88
+ };
89
+ type AnyMutatorMap = Record<string, ClientMutatorDef<any>>;
90
+ /** Args type of a mutator definition. */
91
+ type ArgsOf<M> = M extends ClientMutatorDef<infer A> ? A : never;
92
+ /** Inputs `bindMutators` needs to run a mutator: the local store + how the overlay drops. */
93
+ interface BindMutatorsContext {
94
+ /**
95
+ * Resolves the optimistic-overlay drop against confirmed server watermarks: a
96
+ * mutation's overlay is held until the sync stream echoes
97
+ * `lastMutationId >= clientSeq` (via {@link CheckpointRegistry.resolve}), so the
98
+ * row never flashes out and back.
99
+ *
100
+ * Defaults to the shared per-shard registry for `client` + {@link shardKey}
101
+ * ({@link getShardCheckpoints}) — the same one
102
+ * {@link import("./collection-options").lunoraCollectionOptions} defaults to, so
103
+ * a shard's collections and its mutators gate on one watermark line without the
104
+ * caller wiring them together. Pass `false` to drop the overlay as soon as the
105
+ * server accepts the write (the by-value sync diff then converges the synced row
106
+ * in place).
107
+ */
108
+ checkpoints?: CheckpointRegistry | false;
109
+ /** The wired collections the optimistic bodies write against. */
110
+ collections: Record<string, Collection<Row, string>>;
111
+ /** Optional shard key the mutator's server push is routed to. */
112
+ shardKey?: string;
113
+ }
114
+ /** Calling a bound mutator runs the optimistic body + pushes the server write; returns the TanStack transaction. */
115
+ type BoundMutators<M extends AnyMutatorMap> = { [K in keyof M]: (args: ArgsOf<M[K]>) => Transaction; };
116
+ /**
117
+ * Bind a set of client mutators to a client + local store. Each returned handle,
118
+ * when called, opens a TanStack optimistic transaction: the mutator's `apply`
119
+ * body writes the predicted rows into the collections, and the transaction's
120
+ * `mutationFn` pushes the authoritative write through
121
+ * {@link LunoraClient.callMutator} under a monotonic per-client `clientSeq`.
122
+ *
123
+ * Rebase-on-poke is free — TanStack DB re-derives every pending optimistic overlay
124
+ * over the latest synced base on each sync tick. The overlay is dropped when the
125
+ * server confirms the write (and, if `checkpoints` is supplied, once it echoes the
126
+ * matching watermark so the synced row has landed).
127
+ *
128
+ * The `clientSeq` generator is seeded from the server's echoed watermark
129
+ * ({@link LunoraClient.confirmedMutationWatermark}) on every issue, so a reload —
130
+ * which resets this in-memory counter while the server keeps a durable per-client
131
+ * watermark — never reissues a sequence the DO has already applied. As a backstop
132
+ * for the very first push of a fresh session (before any ack has taught the client
133
+ * the watermark), a push the DO swallows as a replay (`applied === false`) is
134
+ * reissued above the now-known watermark instead of being mistaken for a confirmed
135
+ * write — closing the silent-drop window without risking a double-apply (a fresh
136
+ * session's first stale push provably cannot be an honest replay).
137
+ *
138
+ * Pushes are **serialized per binding** (a FIFO chain): the DO rejects any push
139
+ * with `clientSeq > watermark + 1` as `OUT_OF_ORDER` and drops the write, so two
140
+ * mutators fired concurrently must not race the network into a gap. Each push
141
+ * waits for the previous one's ack and assigns its `clientSeq` *inside* the
142
+ * critical section — from the live watermark — so the sequence is always exactly
143
+ * `watermark + 1`. Because a failed mutation never advances the server watermark,
144
+ * a permanently-rejected predecessor can't wedge the chain: the next push simply
145
+ * reclaims the same `watermark + 1` instead of leaving a hole the DO waits on.
146
+ */
147
+ declare const bindMutators: <M extends AnyMutatorMap>(client: LunoraClient, context: BindMutatorsContext, mutators: M) => BoundMutators<M>;
148
+ export { BindMutatorsContext as B, ClientMutatorContext as C, DIRECT_TRANSACTION_METADATA_KEY as D, MutatorReference as M, BoundMutators as a, ClientMutatorDef as b, bindMutators as c, defineMutator as d };
@@ -0,0 +1 @@
1
+ import{createCollection as I,safeRandomUUID as R}from"@tanstack/db";import{startOfflineExecutor as U,NonRetriableError as w}from"@tanstack/offline-transactions";import{lunoraCollectionOptions as _}from"./CHECKPOINT_FALLBACK_MS-vBJLOBjX.mjs";import{createOutboxCarrier as b,createOptimisticOnlineDetector as E,OUTBOX_MUTATION_FN_NAME as C,registerOutboxCarrier as M,runOutboxMutation as N}from"./OUTBOX_MUTATION_FN_NAME-CebgkYw2.mjs";const S=(a,K,e={})=>{const c={},p={},l={},y=Object.entries(K);for(const[t,o]of y){const n=o.insert,{config:d,scope:m}=_({client:a,getKey:o.getKey,id:t,list:o.list,...o.load===void 0?{}:{load:o.load},onError:o.onError,scopeBy:o.scopeBy,shardKey:o.shardKey});c[t]=I(d),o.scopeBy!==void 0&&(p[t]=m),n&&(l[t]=async({idempotencyKey:r,transaction:i})=>{for(const[f,x]of i.mutations.entries()){const O=x.modified,F=`${r}:${String(f)}`;try{await N(()=>a.mutation(n.mutation,n.toArgs(O),{mutationId:F}))}catch(u){if(u instanceof w&&e.onWriteRejected)try{e.onWriteRejected({code:u.code,collection:t,error:u,row:O})}catch{}throw u}}})}l[C]=async({transaction:t})=>{const o=t.metadata;if(o){if(o.identity!==a.currentIdentity())throw new w("outbox write dropped: identity changed since it was queued");await N(()=>a.mutation({__lunoraRef:o.functionPath},o.args,{mutationId:o.idempotencyKey,shardKey:o.shardKey}))}};const g=b(),s=U({collections:{...c,[C]:g},mutationFns:l,onlineDetector:E(),...e.onLeadershipChange?{onLeadershipChange:e.onLeadershipChange}:{},...e.onStorageFailure?{onStorageFailure:e.onStorageFailure}:{},onUnknownMutationFn:(t,o)=>{try{e.onWriteRejected?.({code:"UNKNOWN_MUTATION_FN",collection:t,error:new Error(`offline write dropped: mutation "${t}" no longer exists (removed or renamed in a deploy?)`),row:o.mutations[0]?.modified})}catch{}}});M(s,g);const h={};for(const[t,o]of y){const n=o.insert,d=c[t];if(!n||!d)continue;const m=s.createOfflineAction({mutationFnName:t,onMutate:({id:r,input:i})=>{d.insert(n.optimistic(i,r))}});h[t]=r=>{const i=R(),f=m({id:i,input:r});return{id:i,transaction:f}}}return{actions:h,collections:c,executor:s,pendingCount:()=>s.getPendingCount(),scope:p}};export{S as defineCollections};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/db",
3
- "version": "1.0.0-alpha.3",
3
+ "version": "1.0.0-alpha.31",
4
4
  "description": "TanStack DB binding: typed, live-synced collections and a durable offline outbox over the Lunora client",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -40,13 +40,22 @@
40
40
  "types": "./dist/index.d.ts",
41
41
  "import": "./dist/index.mjs"
42
42
  },
43
+ "./collections": {
44
+ "types": "./dist/collections/index.d.ts",
45
+ "import": "./dist/collections/index.mjs"
46
+ },
47
+ "./mutators": {
48
+ "types": "./dist/mutators/index.d.ts",
49
+ "import": "./dist/mutators/index.mjs"
50
+ },
43
51
  "./package.json": "./package.json"
44
52
  },
45
53
  "publishConfig": {
46
54
  "access": "public"
47
55
  },
48
56
  "dependencies": {
49
- "@lunora/client": "1.0.0-alpha.3"
57
+ "@lunora/client": "1.0.0-alpha.31",
58
+ "@lunora/errors": "1.0.0-alpha.8"
50
59
  },
51
60
  "peerDependencies": {
52
61
  "@tanstack/db": "^0.6.0",
@@ -1,65 +0,0 @@
1
- import { NonRetriableError } from '@tanstack/offline-transactions';
2
-
3
- const OUTBOX_DRAIN_INTERVAL_MS = 1e3;
4
- const toMap = (rows, getKey) => {
5
- const map = /* @__PURE__ */ new Map();
6
- for (const row of rows) {
7
- map.set(getKey(row), row);
8
- }
9
- return map;
10
- };
11
- const makeDiffEmit = (synced, writer) => (next) => {
12
- writer.begin();
13
- for (const [key, value] of next) {
14
- const previous = synced.get(key);
15
- if (previous === void 0) {
16
- writer.write({ type: "insert", value });
17
- } else if (JSON.stringify(previous) !== JSON.stringify(value)) {
18
- writer.write({ type: "update", value });
19
- }
20
- }
21
- for (const key of synced.keys()) {
22
- if (!next.has(key)) {
23
- writer.write({ key, type: "delete" });
24
- }
25
- }
26
- writer.commit();
27
- synced.clear();
28
- for (const [key, value] of next) {
29
- synced.set(key, value);
30
- }
31
- };
32
- const runOutboxMutation = async (mutate) => {
33
- try {
34
- await mutate();
35
- } catch (error) {
36
- if (typeof error.code === "string") {
37
- throw new NonRetriableError(error instanceof Error ? error.message : String(error));
38
- }
39
- throw error;
40
- }
41
- };
42
- const createOptimisticOnlineDetector = () => {
43
- const intervals = /* @__PURE__ */ new Set();
44
- return {
45
- dispose: () => {
46
- for (const handle of intervals) {
47
- clearInterval(handle);
48
- }
49
- intervals.clear();
50
- },
51
- isOnline: () => true,
52
- notifyOnline: () => {
53
- },
54
- subscribe: (callback) => {
55
- const handle = setInterval(callback, OUTBOX_DRAIN_INTERVAL_MS);
56
- intervals.add(handle);
57
- return () => {
58
- clearInterval(handle);
59
- intervals.delete(handle);
60
- };
61
- }
62
- };
63
- };
64
-
65
- export { createOptimisticOnlineDetector, makeDiffEmit, runOutboxMutation, toMap };