@lunora/db 0.0.0 → 1.0.0-alpha.2
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/LICENSE.md +105 -0
- package/README.md +122 -9
- package/__assets__/package-og.svg +14 -0
- package/dist/index.d.mts +142 -0
- package/dist/index.d.ts +142 -0
- package/dist/index.mjs +6 -0
- package/dist/packem_shared/createOptimisticOnlineDetector-CRulWqZ7.mjs +65 -0
- package/dist/packem_shared/defineCollections-BAmslSrF.mjs +109 -0
- package/package.json +44 -17
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { FunctionReference, SubscriptionError, LunoraClient } from '@lunora/client';
|
|
2
|
+
import { Transaction, Collection } from '@tanstack/db';
|
|
3
|
+
import { OnlineDetector, OfflineExecutor } from '@tanstack/offline-transactions';
|
|
4
|
+
/** A row carrying the Lunora document id. */
|
|
5
|
+
type Row = Record<string, unknown> & {
|
|
6
|
+
_id: string;
|
|
7
|
+
};
|
|
8
|
+
/** The subset of a TanStack DB sync write channel that {@link makeDiffEmit} drives. */
|
|
9
|
+
interface SyncWriter<T extends object> {
|
|
10
|
+
begin: () => void;
|
|
11
|
+
commit: () => void;
|
|
12
|
+
write: (message: {
|
|
13
|
+
type: "insert" | "update";
|
|
14
|
+
value: T;
|
|
15
|
+
} | {
|
|
16
|
+
key: string;
|
|
17
|
+
type: "delete";
|
|
18
|
+
}) => void;
|
|
19
|
+
}
|
|
20
|
+
/** Index a row list into a keyed map. */
|
|
21
|
+
declare const toMap: <T extends object>(rows: ReadonlyArray<T>, getKey: (row: T) => string) => Map<string, T>;
|
|
22
|
+
/**
|
|
23
|
+
* Build an `emit(next)` that diffs a desired keyed snapshot into a collection's
|
|
24
|
+
* sync channel — only changed rows are written, so a reconnect snapshot or a
|
|
25
|
+
* scope change never churns the synced view out from under a pending optimistic
|
|
26
|
+
* row. The last-synced base is tracked in `synced`.
|
|
27
|
+
*
|
|
28
|
+
* Change detection compares rows by `JSON.stringify`, which is key-order
|
|
29
|
+
* sensitive — safe here because `synced` only ever holds server snapshots, whose
|
|
30
|
+
* column order is stable across reconnects (same query projection). A sync source
|
|
31
|
+
* with unstable key ordering would need a structural compare instead.
|
|
32
|
+
*/
|
|
33
|
+
declare const makeDiffEmit: <T extends object>(synced: Map<string, T>, writer: SyncWriter<T>) => (next: Map<string, T>) => void;
|
|
34
|
+
/**
|
|
35
|
+
* Run a Lunora mutation under the outbox's retry policy.
|
|
36
|
+
*
|
|
37
|
+
* The retryable/permanent split keys on whether the failure carries a server
|
|
38
|
+
* application error `code` (set by `@lunora/client`'s rpc when the server returns
|
|
39
|
+
* a `{ error: { code, … } }` envelope — validation, conflict, etc.). A coded
|
|
40
|
+
* error is a definite verdict: surface it as a `NonRetriableError` so the executor
|
|
41
|
+
* stops and TanStack DB rolls the optimistic insert back. Everything without a
|
|
42
|
+
* code is transient — a `fetch` network failure (`TypeError`) or an HTTP/infra
|
|
43
|
+
* blip the rpc surfaces as a code-less `Error` (a 5xx gateway page, a non-JSON
|
|
44
|
+
* body) — so it's rethrown as-is and the durable outbox replays it. Keying on
|
|
45
|
+
* `error instanceof TypeError` alone would wrongly drop the latter.
|
|
46
|
+
*/
|
|
47
|
+
declare const runOutboxMutation: (mutate: () => Promise<unknown>) => Promise<void>;
|
|
48
|
+
/**
|
|
49
|
+
* An "always attempt" online detector. We deliberately don't trust
|
|
50
|
+
* `navigator.onLine`: some environments (and Playwright's `setOffline` under
|
|
51
|
+
* Firefox) leave it stuck, which would freeze the outbox. Instead the executor
|
|
52
|
+
* always tries the send and {@link runOutboxMutation}'s transient-error retry
|
|
53
|
+
* handles real offline; the periodic tick nudges the executor to drain the outbox
|
|
54
|
+
* so a queued write replays promptly once connectivity returns.
|
|
55
|
+
*
|
|
56
|
+
* `isOnline` is therefore intentionally always `true` — it gates the executor's
|
|
57
|
+
* attempts, not a UI signal. A consumer that wants to show real connectivity
|
|
58
|
+
* should read `navigator.onLine` itself, separately from this detector.
|
|
59
|
+
*/
|
|
60
|
+
declare const createOptimisticOnlineDetector: () => OnlineDetector;
|
|
61
|
+
/** Element type of an array (the row type a `list` query returns). */
|
|
62
|
+
type Element<T> = T extends ReadonlyArray<infer E> ? E : never;
|
|
63
|
+
/** `true` for the `any` type, `false` otherwise. */
|
|
64
|
+
type IsAny<T> = 0 extends 1 & T ? true : false;
|
|
65
|
+
/**
|
|
66
|
+
* The row type a `list` query syncs. For `TList = any` (the heterogeneous-map
|
|
67
|
+
* constraint) it resolves to the permissive {@link Row}, not `never` — otherwise
|
|
68
|
+
* the constraint would force every `optimistic` to return `never`. For a concrete
|
|
69
|
+
* `FunctionReference` it's the element type of the query's array return.
|
|
70
|
+
*/
|
|
71
|
+
type RowOfList<TList> = IsAny<TList> extends true ? Row : TList extends FunctionReference<infer _K, infer _A, infer R> ? Element<R> & Row : never;
|
|
72
|
+
/** Maps a write through the durable outbox: optimistic insert + a retried mutation. */
|
|
73
|
+
interface InsertBinding<TRow extends Row, TInput> {
|
|
74
|
+
/** The Lunora mutation that persists the row. */
|
|
75
|
+
mutation: FunctionReference;
|
|
76
|
+
/** Build the optimistic row to insert from the action input + the generated client id. */
|
|
77
|
+
optimistic: (input: TInput, id: string) => TRow;
|
|
78
|
+
/** Build the mutation args from the persisted optimistic row (forward `_id` as the `clientId`). */
|
|
79
|
+
toArgs: (row: TRow) => Record<string, unknown>;
|
|
80
|
+
}
|
|
81
|
+
/** Declarative binding of a Lunora table to a live collection (+ optional write action). */
|
|
82
|
+
interface CollectionDef<TList extends FunctionReference, TInput = never> {
|
|
83
|
+
/** Row key extractor — defaults to `row._id`. */
|
|
84
|
+
getKey?: (row: RowOfList<TList>) => string;
|
|
85
|
+
/** Optional write binding — present iff this collection is written through the outbox. */
|
|
86
|
+
insert?: InsertBinding<RowOfList<TList>, TInput>;
|
|
87
|
+
/** The Lunora query that lists the rows (the sync source). */
|
|
88
|
+
list: TList;
|
|
89
|
+
/**
|
|
90
|
+
* Notified when the underlying `list` subscription errors (e.g. the server
|
|
91
|
+
* rejects it). Without this the error would be swallowed and the collection
|
|
92
|
+
* could hang in `loading`; the binding always moves the collection out of
|
|
93
|
+
* `loading` on error, and forwards the error here if supplied.
|
|
94
|
+
*/
|
|
95
|
+
onError?: (error: SubscriptionError) => void;
|
|
96
|
+
/** A field that scopes the list (e.g. a shard key); makes the collection re-pointable via `scope`. */
|
|
97
|
+
scopeBy?: string;
|
|
98
|
+
}
|
|
99
|
+
type AnyDef = CollectionDef<any, any>;
|
|
100
|
+
/**
|
|
101
|
+
* The public row type a collection exposes — the element type of its `list`
|
|
102
|
+
* query's return, with no `& Row`: a `Collection<T>` is invariant in `T`, so the
|
|
103
|
+
* exposed type must be exactly the document type, not a subtype.
|
|
104
|
+
*/
|
|
105
|
+
type RowOf<C extends AnyDef> = C["list"] extends FunctionReference<infer _K, infer _A, infer R> ? Element<R> : never;
|
|
106
|
+
/** The action input type, inferred structurally from the def's optimistic insert. */
|
|
107
|
+
type InputOf<C> = C extends {
|
|
108
|
+
insert: {
|
|
109
|
+
optimistic: (input: infer I, id: string) => unknown;
|
|
110
|
+
};
|
|
111
|
+
} ? I : never;
|
|
112
|
+
/** The wired data layer `defineCollections` returns. */
|
|
113
|
+
interface LunoraDb<D extends Record<string, AnyDef>> {
|
|
114
|
+
/** Optimistic, durable, retried write actions — present for `insert` collections. */
|
|
115
|
+
actions: { [K in keyof D]: D[K] extends {
|
|
116
|
+
insert: object;
|
|
117
|
+
} ? (input: InputOf<D[K]>) => {
|
|
118
|
+
id: string;
|
|
119
|
+
transaction: Transaction;
|
|
120
|
+
} : never };
|
|
121
|
+
/** The live, synced collections — feed these to `useLiveQuery`. */
|
|
122
|
+
collections: { [K in keyof D]: Collection<RowOf<D[K]>, string> };
|
|
123
|
+
/** The shared offline executor (the outbox). */
|
|
124
|
+
executor: OfflineExecutor;
|
|
125
|
+
/** Re-point a `scopeBy` collection's subscription (omit `args` to detach) — present for scoped collections. */
|
|
126
|
+
scope: { [K in keyof D]: D[K] extends {
|
|
127
|
+
scopeBy: string;
|
|
128
|
+
} ? (args?: Record<string, unknown>) => void : never };
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Wire a set of Lunora tables into a TanStack DB data layer in one declaration:
|
|
132
|
+
* each entry becomes a live, auto-indexed collection synced from its `list` query,
|
|
133
|
+
* and `insert` entries get an optimistic write action backed by the
|
|
134
|
+
* offline-transactions outbox (durable, retried, client-id-keyed). Scoped
|
|
135
|
+
* (`scopeBy`) collections are re-pointable for sharded queries.
|
|
136
|
+
*
|
|
137
|
+
* This is the hand-written form; `@lunora/codegen` can emit a fully-typed call to
|
|
138
|
+
* it from `schema.ts`, so an app writes nothing.
|
|
139
|
+
*/
|
|
140
|
+
declare const defineCollections: <D extends Record<string, AnyDef>>(client: LunoraClient, defs: D) => LunoraDb<D>;
|
|
141
|
+
declare const VERSION = "0.0.0";
|
|
142
|
+
export { type CollectionDef, type InsertBinding, type LunoraDb, type Row, type SyncWriter, VERSION, createOptimisticOnlineDetector, defineCollections, makeDiffEmit, runOutboxMutation, toMap };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { FunctionReference, SubscriptionError, LunoraClient } from '@lunora/client';
|
|
2
|
+
import { Transaction, Collection } from '@tanstack/db';
|
|
3
|
+
import { OnlineDetector, OfflineExecutor } from '@tanstack/offline-transactions';
|
|
4
|
+
/** A row carrying the Lunora document id. */
|
|
5
|
+
type Row = Record<string, unknown> & {
|
|
6
|
+
_id: string;
|
|
7
|
+
};
|
|
8
|
+
/** The subset of a TanStack DB sync write channel that {@link makeDiffEmit} drives. */
|
|
9
|
+
interface SyncWriter<T extends object> {
|
|
10
|
+
begin: () => void;
|
|
11
|
+
commit: () => void;
|
|
12
|
+
write: (message: {
|
|
13
|
+
type: "insert" | "update";
|
|
14
|
+
value: T;
|
|
15
|
+
} | {
|
|
16
|
+
key: string;
|
|
17
|
+
type: "delete";
|
|
18
|
+
}) => void;
|
|
19
|
+
}
|
|
20
|
+
/** Index a row list into a keyed map. */
|
|
21
|
+
declare const toMap: <T extends object>(rows: ReadonlyArray<T>, getKey: (row: T) => string) => Map<string, T>;
|
|
22
|
+
/**
|
|
23
|
+
* Build an `emit(next)` that diffs a desired keyed snapshot into a collection's
|
|
24
|
+
* sync channel — only changed rows are written, so a reconnect snapshot or a
|
|
25
|
+
* scope change never churns the synced view out from under a pending optimistic
|
|
26
|
+
* row. The last-synced base is tracked in `synced`.
|
|
27
|
+
*
|
|
28
|
+
* Change detection compares rows by `JSON.stringify`, which is key-order
|
|
29
|
+
* sensitive — safe here because `synced` only ever holds server snapshots, whose
|
|
30
|
+
* column order is stable across reconnects (same query projection). A sync source
|
|
31
|
+
* with unstable key ordering would need a structural compare instead.
|
|
32
|
+
*/
|
|
33
|
+
declare const makeDiffEmit: <T extends object>(synced: Map<string, T>, writer: SyncWriter<T>) => (next: Map<string, T>) => void;
|
|
34
|
+
/**
|
|
35
|
+
* Run a Lunora mutation under the outbox's retry policy.
|
|
36
|
+
*
|
|
37
|
+
* The retryable/permanent split keys on whether the failure carries a server
|
|
38
|
+
* application error `code` (set by `@lunora/client`'s rpc when the server returns
|
|
39
|
+
* a `{ error: { code, … } }` envelope — validation, conflict, etc.). A coded
|
|
40
|
+
* error is a definite verdict: surface it as a `NonRetriableError` so the executor
|
|
41
|
+
* stops and TanStack DB rolls the optimistic insert back. Everything without a
|
|
42
|
+
* code is transient — a `fetch` network failure (`TypeError`) or an HTTP/infra
|
|
43
|
+
* blip the rpc surfaces as a code-less `Error` (a 5xx gateway page, a non-JSON
|
|
44
|
+
* body) — so it's rethrown as-is and the durable outbox replays it. Keying on
|
|
45
|
+
* `error instanceof TypeError` alone would wrongly drop the latter.
|
|
46
|
+
*/
|
|
47
|
+
declare const runOutboxMutation: (mutate: () => Promise<unknown>) => Promise<void>;
|
|
48
|
+
/**
|
|
49
|
+
* An "always attempt" online detector. We deliberately don't trust
|
|
50
|
+
* `navigator.onLine`: some environments (and Playwright's `setOffline` under
|
|
51
|
+
* Firefox) leave it stuck, which would freeze the outbox. Instead the executor
|
|
52
|
+
* always tries the send and {@link runOutboxMutation}'s transient-error retry
|
|
53
|
+
* handles real offline; the periodic tick nudges the executor to drain the outbox
|
|
54
|
+
* so a queued write replays promptly once connectivity returns.
|
|
55
|
+
*
|
|
56
|
+
* `isOnline` is therefore intentionally always `true` — it gates the executor's
|
|
57
|
+
* attempts, not a UI signal. A consumer that wants to show real connectivity
|
|
58
|
+
* should read `navigator.onLine` itself, separately from this detector.
|
|
59
|
+
*/
|
|
60
|
+
declare const createOptimisticOnlineDetector: () => OnlineDetector;
|
|
61
|
+
/** Element type of an array (the row type a `list` query returns). */
|
|
62
|
+
type Element<T> = T extends ReadonlyArray<infer E> ? E : never;
|
|
63
|
+
/** `true` for the `any` type, `false` otherwise. */
|
|
64
|
+
type IsAny<T> = 0 extends 1 & T ? true : false;
|
|
65
|
+
/**
|
|
66
|
+
* The row type a `list` query syncs. For `TList = any` (the heterogeneous-map
|
|
67
|
+
* constraint) it resolves to the permissive {@link Row}, not `never` — otherwise
|
|
68
|
+
* the constraint would force every `optimistic` to return `never`. For a concrete
|
|
69
|
+
* `FunctionReference` it's the element type of the query's array return.
|
|
70
|
+
*/
|
|
71
|
+
type RowOfList<TList> = IsAny<TList> extends true ? Row : TList extends FunctionReference<infer _K, infer _A, infer R> ? Element<R> & Row : never;
|
|
72
|
+
/** Maps a write through the durable outbox: optimistic insert + a retried mutation. */
|
|
73
|
+
interface InsertBinding<TRow extends Row, TInput> {
|
|
74
|
+
/** The Lunora mutation that persists the row. */
|
|
75
|
+
mutation: FunctionReference;
|
|
76
|
+
/** Build the optimistic row to insert from the action input + the generated client id. */
|
|
77
|
+
optimistic: (input: TInput, id: string) => TRow;
|
|
78
|
+
/** Build the mutation args from the persisted optimistic row (forward `_id` as the `clientId`). */
|
|
79
|
+
toArgs: (row: TRow) => Record<string, unknown>;
|
|
80
|
+
}
|
|
81
|
+
/** Declarative binding of a Lunora table to a live collection (+ optional write action). */
|
|
82
|
+
interface CollectionDef<TList extends FunctionReference, TInput = never> {
|
|
83
|
+
/** Row key extractor — defaults to `row._id`. */
|
|
84
|
+
getKey?: (row: RowOfList<TList>) => string;
|
|
85
|
+
/** Optional write binding — present iff this collection is written through the outbox. */
|
|
86
|
+
insert?: InsertBinding<RowOfList<TList>, TInput>;
|
|
87
|
+
/** The Lunora query that lists the rows (the sync source). */
|
|
88
|
+
list: TList;
|
|
89
|
+
/**
|
|
90
|
+
* Notified when the underlying `list` subscription errors (e.g. the server
|
|
91
|
+
* rejects it). Without this the error would be swallowed and the collection
|
|
92
|
+
* could hang in `loading`; the binding always moves the collection out of
|
|
93
|
+
* `loading` on error, and forwards the error here if supplied.
|
|
94
|
+
*/
|
|
95
|
+
onError?: (error: SubscriptionError) => void;
|
|
96
|
+
/** A field that scopes the list (e.g. a shard key); makes the collection re-pointable via `scope`. */
|
|
97
|
+
scopeBy?: string;
|
|
98
|
+
}
|
|
99
|
+
type AnyDef = CollectionDef<any, any>;
|
|
100
|
+
/**
|
|
101
|
+
* The public row type a collection exposes — the element type of its `list`
|
|
102
|
+
* query's return, with no `& Row`: a `Collection<T>` is invariant in `T`, so the
|
|
103
|
+
* exposed type must be exactly the document type, not a subtype.
|
|
104
|
+
*/
|
|
105
|
+
type RowOf<C extends AnyDef> = C["list"] extends FunctionReference<infer _K, infer _A, infer R> ? Element<R> : never;
|
|
106
|
+
/** The action input type, inferred structurally from the def's optimistic insert. */
|
|
107
|
+
type InputOf<C> = C extends {
|
|
108
|
+
insert: {
|
|
109
|
+
optimistic: (input: infer I, id: string) => unknown;
|
|
110
|
+
};
|
|
111
|
+
} ? I : never;
|
|
112
|
+
/** The wired data layer `defineCollections` returns. */
|
|
113
|
+
interface LunoraDb<D extends Record<string, AnyDef>> {
|
|
114
|
+
/** Optimistic, durable, retried write actions — present for `insert` collections. */
|
|
115
|
+
actions: { [K in keyof D]: D[K] extends {
|
|
116
|
+
insert: object;
|
|
117
|
+
} ? (input: InputOf<D[K]>) => {
|
|
118
|
+
id: string;
|
|
119
|
+
transaction: Transaction;
|
|
120
|
+
} : never };
|
|
121
|
+
/** The live, synced collections — feed these to `useLiveQuery`. */
|
|
122
|
+
collections: { [K in keyof D]: Collection<RowOf<D[K]>, string> };
|
|
123
|
+
/** The shared offline executor (the outbox). */
|
|
124
|
+
executor: OfflineExecutor;
|
|
125
|
+
/** Re-point a `scopeBy` collection's subscription (omit `args` to detach) — present for scoped collections. */
|
|
126
|
+
scope: { [K in keyof D]: D[K] extends {
|
|
127
|
+
scopeBy: string;
|
|
128
|
+
} ? (args?: Record<string, unknown>) => void : never };
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Wire a set of Lunora tables into a TanStack DB data layer in one declaration:
|
|
132
|
+
* each entry becomes a live, auto-indexed collection synced from its `list` query,
|
|
133
|
+
* and `insert` entries get an optimistic write action backed by the
|
|
134
|
+
* offline-transactions outbox (durable, retried, client-id-keyed). Scoped
|
|
135
|
+
* (`scopeBy`) collections are re-pointable for sharded queries.
|
|
136
|
+
*
|
|
137
|
+
* This is the hand-written form; `@lunora/codegen` can emit a fully-typed call to
|
|
138
|
+
* it from `schema.ts`, so an app writes nothing.
|
|
139
|
+
*/
|
|
140
|
+
declare const defineCollections: <D extends Record<string, AnyDef>>(client: LunoraClient, defs: D) => LunoraDb<D>;
|
|
141
|
+
declare const VERSION = "0.0.0";
|
|
142
|
+
export { type CollectionDef, type InsertBinding, type LunoraDb, type Row, type SyncWriter, VERSION, createOptimisticOnlineDetector, defineCollections, makeDiffEmit, runOutboxMutation, toMap };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { defineCollections } from './packem_shared/defineCollections-BAmslSrF.mjs';
|
|
2
|
+
export { createOptimisticOnlineDetector, makeDiffEmit, runOutboxMutation, toMap } from './packem_shared/createOptimisticOnlineDetector-CRulWqZ7.mjs';
|
|
3
|
+
|
|
4
|
+
const VERSION = "0.0.0";
|
|
5
|
+
|
|
6
|
+
export { VERSION };
|
|
@@ -0,0 +1,65 @@
|
|
|
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 };
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { createCollection, BTreeIndex } from '@tanstack/db';
|
|
2
|
+
import { startOfflineExecutor } from '@tanstack/offline-transactions';
|
|
3
|
+
import { toMap, createOptimisticOnlineDetector, makeDiffEmit, runOutboxMutation } from './createOptimisticOnlineDetector-CRulWqZ7.mjs';
|
|
4
|
+
|
|
5
|
+
const defineCollections = (client, defs) => {
|
|
6
|
+
const collections = {};
|
|
7
|
+
const scope = {};
|
|
8
|
+
const subscriptions = {};
|
|
9
|
+
const emitters = {};
|
|
10
|
+
const errorHandlers = {};
|
|
11
|
+
const mutationFns = {};
|
|
12
|
+
const entries = Object.entries(defs);
|
|
13
|
+
for (const [name, definition] of entries) {
|
|
14
|
+
const getKey = definition.getKey ?? ((row) => row._id);
|
|
15
|
+
const insert = definition.insert;
|
|
16
|
+
const synced = /* @__PURE__ */ new Map();
|
|
17
|
+
collections[name] = createCollection({
|
|
18
|
+
// Auto-build ordered (B-tree) indexes for whatever the app's live
|
|
19
|
+
// queries join / filter / sort on, so they stay fast as data grows.
|
|
20
|
+
autoIndex: "eager",
|
|
21
|
+
defaultIndexType: BTreeIndex,
|
|
22
|
+
getKey,
|
|
23
|
+
id: name,
|
|
24
|
+
sync: {
|
|
25
|
+
sync: (writer) => {
|
|
26
|
+
const emit = makeDiffEmit(synced, writer);
|
|
27
|
+
emitters[name] = emit;
|
|
28
|
+
const onError = (error) => {
|
|
29
|
+
writer.markReady();
|
|
30
|
+
definition.onError?.(error);
|
|
31
|
+
};
|
|
32
|
+
errorHandlers[name] = onError;
|
|
33
|
+
if (definition.scopeBy === void 0) {
|
|
34
|
+
subscriptions[name] = client.subscribe(
|
|
35
|
+
definition.list,
|
|
36
|
+
{},
|
|
37
|
+
(rows) => {
|
|
38
|
+
emit(toMap(rows, getKey));
|
|
39
|
+
writer.markReady();
|
|
40
|
+
},
|
|
41
|
+
{ onError }
|
|
42
|
+
);
|
|
43
|
+
} else {
|
|
44
|
+
writer.markReady();
|
|
45
|
+
}
|
|
46
|
+
return () => {
|
|
47
|
+
emitters[name] = void 0;
|
|
48
|
+
errorHandlers[name] = void 0;
|
|
49
|
+
subscriptions[name]?.();
|
|
50
|
+
subscriptions[name] = void 0;
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
if (definition.scopeBy !== void 0) {
|
|
56
|
+
scope[name] = (args) => {
|
|
57
|
+
subscriptions[name]?.();
|
|
58
|
+
subscriptions[name] = void 0;
|
|
59
|
+
emitters[name]?.(/* @__PURE__ */ new Map());
|
|
60
|
+
if (args === void 0) {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
subscriptions[name] = client.subscribe(
|
|
64
|
+
definition.list,
|
|
65
|
+
args,
|
|
66
|
+
(rows) => {
|
|
67
|
+
emitters[name]?.(toMap(rows, getKey));
|
|
68
|
+
},
|
|
69
|
+
{ onError: (error) => errorHandlers[name]?.(error) }
|
|
70
|
+
);
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
if (insert) {
|
|
74
|
+
mutationFns[name] = async ({ transaction }) => {
|
|
75
|
+
for (const mutation of transaction.mutations) {
|
|
76
|
+
const row = mutation.modified;
|
|
77
|
+
await runOutboxMutation(() => client.mutation(insert.mutation, insert.toArgs(row)));
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const executor = startOfflineExecutor({
|
|
83
|
+
collections,
|
|
84
|
+
mutationFns,
|
|
85
|
+
onlineDetector: createOptimisticOnlineDetector()
|
|
86
|
+
});
|
|
87
|
+
const actions = {};
|
|
88
|
+
for (const [name, definition] of entries) {
|
|
89
|
+
const insert = definition.insert;
|
|
90
|
+
const collection = collections[name];
|
|
91
|
+
if (!insert || !collection) {
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
const action = executor.createOfflineAction({
|
|
95
|
+
mutationFnName: name,
|
|
96
|
+
onMutate: ({ id, input }) => {
|
|
97
|
+
collection.insert(insert.optimistic(input, id));
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
actions[name] = (input) => {
|
|
101
|
+
const id = crypto.randomUUID();
|
|
102
|
+
const transaction = action({ id, input });
|
|
103
|
+
return { id, transaction };
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
return { actions, collections, executor, scope };
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
export { defineCollections };
|
package/package.json
CHANGED
|
@@ -1,31 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/db",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "1.0.0-alpha.2",
|
|
4
4
|
"description": "TanStack DB binding: typed, live-synced collections and a durable offline outbox over the Lunora client",
|
|
5
|
-
"
|
|
5
|
+
"keywords": [
|
|
6
|
+
"cloudflare",
|
|
7
|
+
"durable-objects",
|
|
8
|
+
"live-query",
|
|
9
|
+
"lunora",
|
|
10
|
+
"offline-first",
|
|
11
|
+
"optimistic-updates",
|
|
12
|
+
"tanstack-db",
|
|
13
|
+
"workers"
|
|
14
|
+
],
|
|
6
15
|
"homepage": "https://lunora.sh",
|
|
16
|
+
"bugs": "https://github.com/anolilab/lunora/issues",
|
|
17
|
+
"license": "FSL-1.1-Apache-2.0",
|
|
18
|
+
"author": {
|
|
19
|
+
"name": "Daniel Bannert",
|
|
20
|
+
"email": "d.bannert@anolilab.de"
|
|
21
|
+
},
|
|
7
22
|
"repository": {
|
|
8
23
|
"type": "git",
|
|
9
24
|
"url": "git+https://github.com/anolilab/lunora.git",
|
|
10
25
|
"directory": "packages/db"
|
|
11
26
|
},
|
|
12
|
-
"
|
|
13
|
-
"
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
"
|
|
17
|
-
"cloudflare",
|
|
18
|
-
"workers",
|
|
19
|
-
"durable-objects",
|
|
20
|
-
"tanstack-db",
|
|
21
|
-
"offline-first",
|
|
22
|
-
"optimistic-updates",
|
|
23
|
-
"live-query"
|
|
27
|
+
"files": [
|
|
28
|
+
"dist",
|
|
29
|
+
"__assets__",
|
|
30
|
+
"README.md",
|
|
31
|
+
"LICENSE.md"
|
|
24
32
|
],
|
|
33
|
+
"type": "module",
|
|
34
|
+
"sideEffects": false,
|
|
35
|
+
"main": "./dist/index.mjs",
|
|
36
|
+
"module": "./dist/index.mjs",
|
|
37
|
+
"types": "./dist/index.d.ts",
|
|
38
|
+
"exports": {
|
|
39
|
+
".": {
|
|
40
|
+
"types": "./dist/index.d.ts",
|
|
41
|
+
"import": "./dist/index.mjs"
|
|
42
|
+
},
|
|
43
|
+
"./package.json": "./package.json"
|
|
44
|
+
},
|
|
25
45
|
"publishConfig": {
|
|
26
46
|
"access": "public"
|
|
27
47
|
},
|
|
28
|
-
"
|
|
29
|
-
"
|
|
30
|
-
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"@lunora/client": "1.0.0-alpha.2"
|
|
50
|
+
},
|
|
51
|
+
"peerDependencies": {
|
|
52
|
+
"@tanstack/db": "^0.6.0",
|
|
53
|
+
"@tanstack/offline-transactions": "^1.0.0"
|
|
54
|
+
},
|
|
55
|
+
"engines": {
|
|
56
|
+
"node": "^22.15.0 || >=24.11.0"
|
|
57
|
+
}
|
|
31
58
|
}
|