@lunora/db 1.0.0-alpha.2 → 1.0.0-alpha.21

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-DgAuvqvn.mjs";
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,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-DgAuvqvn.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,80 @@
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-DgAuvqvn.js";
4
+ /** The local store a client mutator's optimistic body writes against. */
5
+ interface ClientMutatorContext {
6
+ /** The wired collections, keyed by name — apply optimistic inserts/updates/deletes here. */
7
+ collections: Record<string, Collection<Row, string>>;
8
+ }
9
+ /** A client-side custom mutator: an optimistic body plus the path of its authoritative server impl. */
10
+ interface ClientMutatorDef<TArgs> {
11
+ /** Brand so codegen / `bindMutators` can recognize a mutator definition. */
12
+ __lunoraClientMutator: true;
13
+ /** The optimistic update applied to the local collections before the server confirms. */
14
+ apply: (context: ClientMutatorContext, args: TArgs) => void;
15
+ /** The Lunora function path of the server-authoritative mutator (`defineMutator` on the server). */
16
+ serverRef: string;
17
+ }
18
+ /**
19
+ * Declare a client-side custom mutator. `apply` runs optimistically against the
20
+ * local TanStack collections; `serverRef` names the authoritative server mutator
21
+ * the write is pushed to over the watermark protocol. The server impl is the
22
+ * linearization point — this body is a prediction the server can override.
23
+ */
24
+ declare const defineMutator: <TArgs = Record<string, unknown>>(definition: {
25
+ apply: (context: ClientMutatorContext, args: TArgs) => void;
26
+ serverRef: string;
27
+ }) => ClientMutatorDef<TArgs>;
28
+ type AnyMutatorMap = Record<string, ClientMutatorDef<any>>;
29
+ /** Args type of a mutator definition. */
30
+ type ArgsOf<M> = M extends ClientMutatorDef<infer A> ? A : never;
31
+ /** Inputs `bindMutators` needs to run a mutator: the local store + how the overlay drops. */
32
+ interface BindMutatorsContext {
33
+ /**
34
+ * Resolves the optimistic-overlay drop against confirmed server watermarks.
35
+ * When supplied, a mutation's overlay is held until the sync stream echoes
36
+ * `lastMutationId >= clientSeq` (via {@link CheckpointRegistry.resolve}) — no
37
+ * flicker. When omitted, the overlay drops as soon as the server accepts the
38
+ * write (the by-value sync diff then converges the synced row in place).
39
+ */
40
+ checkpoints?: CheckpointRegistry;
41
+ /** The wired collections the optimistic bodies write against. */
42
+ collections: Record<string, Collection<Row, string>>;
43
+ /** Optional shard key the mutator's server push is routed to. */
44
+ shardKey?: string;
45
+ }
46
+ /** Calling a bound mutator runs the optimistic body + pushes the server write; returns the TanStack transaction. */
47
+ type BoundMutators<M extends AnyMutatorMap> = { [K in keyof M]: (args: ArgsOf<M[K]>) => Transaction };
48
+ /**
49
+ * Bind a set of client mutators to a client + local store. Each returned handle,
50
+ * when called, opens a TanStack optimistic transaction: the mutator's `apply`
51
+ * body writes the predicted rows into the collections, and the transaction's
52
+ * `mutationFn` pushes the authoritative write through
53
+ * {@link LunoraClient.callMutator} under a monotonic per-client `clientSeq`.
54
+ *
55
+ * Rebase-on-poke is free — TanStack DB re-derives every pending optimistic overlay
56
+ * over the latest synced base on each sync tick. The overlay is dropped when the
57
+ * server confirms the write (and, if `checkpoints` is supplied, once it echoes the
58
+ * matching watermark so the synced row has landed).
59
+ *
60
+ * The `clientSeq` generator is seeded from the server's echoed watermark
61
+ * ({@link LunoraClient.confirmedMutationWatermark}) on every issue, so a reload —
62
+ * which resets this in-memory counter while the server keeps a durable per-client
63
+ * watermark — never reissues a sequence the DO has already applied. As a backstop
64
+ * for the very first push of a fresh session (before any ack has taught the client
65
+ * the watermark), a push the DO swallows as a replay (`applied === false`) is
66
+ * reissued above the now-known watermark instead of being mistaken for a confirmed
67
+ * write — closing the silent-drop window without risking a double-apply (a fresh
68
+ * session's first stale push provably cannot be an honest replay).
69
+ *
70
+ * Pushes are **serialized per binding** (a FIFO chain): the DO rejects any push
71
+ * with `clientSeq > watermark + 1` as `OUT_OF_ORDER` and drops the write, so two
72
+ * mutators fired concurrently must not race the network into a gap. Each push
73
+ * waits for the previous one's ack and assigns its `clientSeq` *inside* the
74
+ * critical section — from the live watermark — so the sequence is always exactly
75
+ * `watermark + 1`. Because a failed mutation never advances the server watermark,
76
+ * a permanently-rejected predecessor can't wedge the chain: the next push simply
77
+ * reclaims the same `watermark + 1` instead of leaving a hole the DO waits on.
78
+ */
79
+ declare const bindMutators: <M extends AnyMutatorMap>(client: LunoraClient, context: BindMutatorsContext, mutators: M) => BoundMutators<M>;
80
+ export { BindMutatorsContext as B, ClientMutatorContext as C, BoundMutators as a, ClientMutatorDef as b, bindMutators as c, defineMutator as d };
@@ -0,0 +1,80 @@
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-DgAuvqvn.mjs";
4
+ /** The local store a client mutator's optimistic body writes against. */
5
+ interface ClientMutatorContext {
6
+ /** The wired collections, keyed by name — apply optimistic inserts/updates/deletes here. */
7
+ collections: Record<string, Collection<Row, string>>;
8
+ }
9
+ /** A client-side custom mutator: an optimistic body plus the path of its authoritative server impl. */
10
+ interface ClientMutatorDef<TArgs> {
11
+ /** Brand so codegen / `bindMutators` can recognize a mutator definition. */
12
+ __lunoraClientMutator: true;
13
+ /** The optimistic update applied to the local collections before the server confirms. */
14
+ apply: (context: ClientMutatorContext, args: TArgs) => void;
15
+ /** The Lunora function path of the server-authoritative mutator (`defineMutator` on the server). */
16
+ serverRef: string;
17
+ }
18
+ /**
19
+ * Declare a client-side custom mutator. `apply` runs optimistically against the
20
+ * local TanStack collections; `serverRef` names the authoritative server mutator
21
+ * the write is pushed to over the watermark protocol. The server impl is the
22
+ * linearization point — this body is a prediction the server can override.
23
+ */
24
+ declare const defineMutator: <TArgs = Record<string, unknown>>(definition: {
25
+ apply: (context: ClientMutatorContext, args: TArgs) => void;
26
+ serverRef: string;
27
+ }) => ClientMutatorDef<TArgs>;
28
+ type AnyMutatorMap = Record<string, ClientMutatorDef<any>>;
29
+ /** Args type of a mutator definition. */
30
+ type ArgsOf<M> = M extends ClientMutatorDef<infer A> ? A : never;
31
+ /** Inputs `bindMutators` needs to run a mutator: the local store + how the overlay drops. */
32
+ interface BindMutatorsContext {
33
+ /**
34
+ * Resolves the optimistic-overlay drop against confirmed server watermarks.
35
+ * When supplied, a mutation's overlay is held until the sync stream echoes
36
+ * `lastMutationId >= clientSeq` (via {@link CheckpointRegistry.resolve}) — no
37
+ * flicker. When omitted, the overlay drops as soon as the server accepts the
38
+ * write (the by-value sync diff then converges the synced row in place).
39
+ */
40
+ checkpoints?: CheckpointRegistry;
41
+ /** The wired collections the optimistic bodies write against. */
42
+ collections: Record<string, Collection<Row, string>>;
43
+ /** Optional shard key the mutator's server push is routed to. */
44
+ shardKey?: string;
45
+ }
46
+ /** Calling a bound mutator runs the optimistic body + pushes the server write; returns the TanStack transaction. */
47
+ type BoundMutators<M extends AnyMutatorMap> = { [K in keyof M]: (args: ArgsOf<M[K]>) => Transaction };
48
+ /**
49
+ * Bind a set of client mutators to a client + local store. Each returned handle,
50
+ * when called, opens a TanStack optimistic transaction: the mutator's `apply`
51
+ * body writes the predicted rows into the collections, and the transaction's
52
+ * `mutationFn` pushes the authoritative write through
53
+ * {@link LunoraClient.callMutator} under a monotonic per-client `clientSeq`.
54
+ *
55
+ * Rebase-on-poke is free — TanStack DB re-derives every pending optimistic overlay
56
+ * over the latest synced base on each sync tick. The overlay is dropped when the
57
+ * server confirms the write (and, if `checkpoints` is supplied, once it echoes the
58
+ * matching watermark so the synced row has landed).
59
+ *
60
+ * The `clientSeq` generator is seeded from the server's echoed watermark
61
+ * ({@link LunoraClient.confirmedMutationWatermark}) on every issue, so a reload —
62
+ * which resets this in-memory counter while the server keeps a durable per-client
63
+ * watermark — never reissues a sequence the DO has already applied. As a backstop
64
+ * for the very first push of a fresh session (before any ack has taught the client
65
+ * the watermark), a push the DO swallows as a replay (`applied === false`) is
66
+ * reissued above the now-known watermark instead of being mistaken for a confirmed
67
+ * write — closing the silent-drop window without risking a double-apply (a fresh
68
+ * session's first stale push provably cannot be an honest replay).
69
+ *
70
+ * Pushes are **serialized per binding** (a FIFO chain): the DO rejects any push
71
+ * with `clientSeq > watermark + 1` as `OUT_OF_ORDER` and drops the write, so two
72
+ * mutators fired concurrently must not race the network into a gap. Each push
73
+ * waits for the previous one's ack and assigns its `clientSeq` *inside* the
74
+ * critical section — from the live watermark — so the sequence is always exactly
75
+ * `watermark + 1`. Because a failed mutation never advances the server watermark,
76
+ * a permanently-rejected predecessor can't wedge the chain: the next push simply
77
+ * reclaims the same `watermark + 1` instead of leaving a hole the DO waits on.
78
+ */
79
+ declare const bindMutators: <M extends AnyMutatorMap>(client: LunoraClient, context: BindMutatorsContext, mutators: M) => BoundMutators<M>;
80
+ export { BindMutatorsContext as B, ClientMutatorContext as C, BoundMutators as a, ClientMutatorDef as b, bindMutators as c, defineMutator as d };
@@ -0,0 +1,107 @@
1
+ import { createCollection, safeRandomUUID } from '@tanstack/db';
2
+ import { startOfflineExecutor, NonRetriableError } from '@tanstack/offline-transactions';
3
+ import { lunoraCollectionOptions } from './createCheckpointRegistry-Bf4JtkVH.mjs';
4
+ import { createOptimisticOnlineDetector, runOutboxMutation, OUTBOX_MUTATION_FN_NAME } from './OUTBOX_MUTATION_FN_NAME-Cf8iP6Wa.mjs';
5
+
6
+ const defineCollections = (client, defs, options = {}) => {
7
+ const collections = {};
8
+ const scope = {};
9
+ const mutationFns = {};
10
+ const entries = Object.entries(defs);
11
+ for (const [name, definition] of entries) {
12
+ const insert = definition.insert;
13
+ const { config, scope: scopeFunction } = lunoraCollectionOptions({
14
+ client,
15
+ getKey: definition.getKey,
16
+ id: name,
17
+ // `AnyDef` erases `list` to `any` (`TList = any`); it's a `FunctionReference` here.
18
+ list: definition.list,
19
+ ...definition.load === void 0 ? {} : { load: definition.load },
20
+ onError: definition.onError,
21
+ scopeBy: definition.scopeBy,
22
+ shardKey: definition.shardKey
23
+ });
24
+ collections[name] = createCollection(config);
25
+ if (definition.scopeBy !== void 0) {
26
+ scope[name] = scopeFunction;
27
+ }
28
+ if (insert) {
29
+ mutationFns[name] = async ({ idempotencyKey, transaction }) => {
30
+ for (const [mutationIndex, mutation] of transaction.mutations.entries()) {
31
+ const row = mutation.modified;
32
+ const mutationId = `${idempotencyKey}:${String(mutationIndex)}`;
33
+ try {
34
+ await runOutboxMutation(() => client.mutation(insert.mutation, insert.toArgs(row), { mutationId }));
35
+ } catch (error) {
36
+ if (error instanceof NonRetriableError && options.onWriteRejected) {
37
+ try {
38
+ options.onWriteRejected({ code: error.code, collection: name, error, row });
39
+ } catch {
40
+ }
41
+ }
42
+ throw error;
43
+ }
44
+ }
45
+ };
46
+ }
47
+ }
48
+ mutationFns[OUTBOX_MUTATION_FN_NAME] = async ({ transaction }) => {
49
+ const meta = transaction.metadata;
50
+ if (!meta) {
51
+ return;
52
+ }
53
+ if (meta.identity !== client.currentIdentity()) {
54
+ throw new NonRetriableError("outbox write dropped: identity changed since it was queued");
55
+ }
56
+ await runOutboxMutation(
57
+ () => client.mutation({ __lunoraRef: meta.functionPath }, meta.args, { mutationId: meta.idempotencyKey, shardKey: meta.shardKey })
58
+ );
59
+ };
60
+ const executor = startOfflineExecutor({
61
+ collections,
62
+ mutationFns,
63
+ onlineDetector: createOptimisticOnlineDetector(),
64
+ ...options.onLeadershipChange ? { onLeadershipChange: options.onLeadershipChange } : {},
65
+ ...options.onStorageFailure ? { onStorageFailure: options.onStorageFailure } : {},
66
+ // A persisted write whose target collection was removed/renamed in a deploy
67
+ // hits an unregistered mutationFn. The executor drops it as a
68
+ // NonRetriableError *before* our per-collection `mutationFns` catch runs, so
69
+ // this hook is the only place to surface it on `onWriteRejected`.
70
+ onUnknownMutationFn: (name, tx) => {
71
+ try {
72
+ options.onWriteRejected?.({
73
+ code: "UNKNOWN_MUTATION_FN",
74
+ collection: name,
75
+ error: new Error(`offline write dropped: mutation "${name}" no longer exists (removed or renamed in a deploy?)`),
76
+ // Best-effort recovered row: the persisted `modified` shape isn't a
77
+ // validated `Row`, and a batched transaction surfaces only its first
78
+ // mutation's row. Enough to describe the dropped write to the user.
79
+ row: tx.mutations[0]?.modified
80
+ });
81
+ } catch {
82
+ }
83
+ }
84
+ });
85
+ const actions = {};
86
+ for (const [name, definition] of entries) {
87
+ const insert = definition.insert;
88
+ const collection = collections[name];
89
+ if (!insert || !collection) {
90
+ continue;
91
+ }
92
+ const action = executor.createOfflineAction({
93
+ mutationFnName: name,
94
+ onMutate: ({ id, input }) => {
95
+ collection.insert(insert.optimistic(input, id));
96
+ }
97
+ });
98
+ actions[name] = (input) => {
99
+ const id = safeRandomUUID();
100
+ const transaction = action({ id, input });
101
+ return { id, transaction };
102
+ };
103
+ }
104
+ return { actions, collections, executor, pendingCount: () => executor.getPendingCount(), scope };
105
+ };
106
+
107
+ export { defineCollections };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/db",
3
- "version": "1.0.0-alpha.2",
3
+ "version": "1.0.0-alpha.21",
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",
@@ -25,7 +25,7 @@
25
25
  "directory": "packages/db"
26
26
  },
27
27
  "files": [
28
- "dist",
28
+ "./dist",
29
29
  "__assets__",
30
30
  "README.md",
31
31
  "LICENSE.md"
@@ -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.2"
57
+ "@lunora/client": "1.0.0-alpha.21",
58
+ "@lunora/errors": "1.0.0-alpha.4"
50
59
  },
51
60
  "peerDependencies": {
52
61
  "@tanstack/db": "^0.6.0",