@lunora/db 1.0.0-alpha.4 → 1.0.0-alpha.6

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,85 @@
1
+ import { FunctionReference, SubscriptionError, LunoraClient } from '@lunora/client';
2
+ import { Transaction, Collection } from '@tanstack/db';
3
+ import { OfflineExecutor } from '@tanstack/offline-transactions';
4
+ import { R as Row } from "./collection-options.d-CbS3J_Fm.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
+ * Notified when the underlying `list` subscription errors (e.g. the server
35
+ * rejects it). Without this the error would be swallowed and the collection
36
+ * could hang in `loading`; the binding always moves the collection out of
37
+ * `loading` on error, and forwards the error here if supplied.
38
+ */
39
+ onError?: (error: SubscriptionError) => void;
40
+ /** A field that scopes the list (e.g. a shard key); makes the collection re-pointable via `scope`. */
41
+ scopeBy?: string;
42
+ }
43
+ type AnyDef = CollectionDef<any, any>;
44
+ /**
45
+ * The public row type a collection exposes — the element type of its `list`
46
+ * query's return, with no `& Row`: a `Collection&lt;T>` is invariant in `T`, so the
47
+ * exposed type must be exactly the document type, not a subtype.
48
+ */
49
+ type RowOf<C extends AnyDef> = C["list"] extends FunctionReference<infer _K, infer _A, infer R> ? Element<R> : never;
50
+ /** The action input type, inferred structurally from the def's optimistic insert. */
51
+ type InputOf<C> = C extends {
52
+ insert: {
53
+ optimistic: (input: infer I, id: string) => unknown;
54
+ };
55
+ } ? I : never;
56
+ /** The wired data layer `defineCollections` returns. */
57
+ interface LunoraDb<D extends Record<string, AnyDef>> {
58
+ /** Optimistic, durable, retried write actions — present for `insert` collections. */
59
+ actions: { [K in keyof D]: D[K] extends {
60
+ insert: object;
61
+ } ? (input: InputOf<D[K]>) => {
62
+ id: string;
63
+ transaction: Transaction;
64
+ } : never };
65
+ /** The live, synced collections — feed these to `useLiveQuery`. */
66
+ collections: { [K in keyof D]: Collection<RowOf<D[K]>, string> };
67
+ /** The shared offline executor (the outbox). */
68
+ executor: OfflineExecutor;
69
+ /** Re-point a `scopeBy` collection's subscription (omit `args` to detach) — present for scoped collections. */
70
+ scope: { [K in keyof D]: D[K] extends {
71
+ scopeBy: string;
72
+ } ? (args?: Record<string, unknown>) => void : never };
73
+ }
74
+ /**
75
+ * Wire a set of Lunora tables into a TanStack DB data layer in one declaration:
76
+ * each entry becomes a live, auto-indexed collection synced from its `list` query,
77
+ * and `insert` entries get an optimistic write action backed by the
78
+ * offline-transactions outbox (durable, retried, client-id-keyed). Scoped
79
+ * (`scopeBy`) collections are re-pointable for sharded queries.
80
+ *
81
+ * This is the hand-written form; `@lunora/codegen` can emit a fully-typed call to
82
+ * it from `schema.ts`, so an app writes nothing.
83
+ */
84
+ declare const defineCollections: <D extends Record<string, AnyDef>>(client: LunoraClient, defs: D) => LunoraDb<D>;
85
+ export { CollectionDef as C, InsertBinding as I, LunoraDb as L, 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-CbS3J_Fm.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-CbS3J_Fm.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,74 @@
1
+ import { createCollection } from '@tanstack/db';
2
+ import { startOfflineExecutor, NonRetriableError } from '@tanstack/offline-transactions';
3
+ import { lunoraCollectionOptions } from './createCheckpointRegistry-DztP2nI8.mjs';
4
+ import { createOptimisticOnlineDetector, runOutboxMutation, OUTBOX_MUTATION_FN_NAME } from './OUTBOX_MUTATION_FN_NAME-DZrP1gna.mjs';
5
+
6
+ const defineCollections = (client, defs) => {
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
+ onError: definition.onError,
20
+ scopeBy: definition.scopeBy
21
+ });
22
+ collections[name] = createCollection(config);
23
+ if (definition.scopeBy !== void 0) {
24
+ scope[name] = scopeFunction;
25
+ }
26
+ if (insert) {
27
+ mutationFns[name] = async ({ transaction }) => {
28
+ for (const mutation of transaction.mutations) {
29
+ const row = mutation.modified;
30
+ await runOutboxMutation(() => client.mutation(insert.mutation, insert.toArgs(row)));
31
+ }
32
+ };
33
+ }
34
+ }
35
+ mutationFns[OUTBOX_MUTATION_FN_NAME] = async ({ transaction }) => {
36
+ const meta = transaction.metadata;
37
+ if (!meta) {
38
+ return;
39
+ }
40
+ if (meta.identity !== client.currentIdentity()) {
41
+ throw new NonRetriableError("outbox write dropped: identity changed since it was queued");
42
+ }
43
+ await runOutboxMutation(
44
+ () => client.mutation({ __lunoraRef: meta.functionPath }, meta.args, { mutationId: meta.idempotencyKey, shardKey: meta.shardKey })
45
+ );
46
+ };
47
+ const executor = startOfflineExecutor({
48
+ collections,
49
+ mutationFns,
50
+ onlineDetector: createOptimisticOnlineDetector()
51
+ });
52
+ const actions = {};
53
+ for (const [name, definition] of entries) {
54
+ const insert = definition.insert;
55
+ const collection = collections[name];
56
+ if (!insert || !collection) {
57
+ continue;
58
+ }
59
+ const action = executor.createOfflineAction({
60
+ mutationFnName: name,
61
+ onMutate: ({ id, input }) => {
62
+ collection.insert(insert.optimistic(input, id));
63
+ }
64
+ });
65
+ actions[name] = (input) => {
66
+ const id = crypto.randomUUID();
67
+ const transaction = action({ id, input });
68
+ return { id, transaction };
69
+ };
70
+ }
71
+ return { actions, collections, executor, scope };
72
+ };
73
+
74
+ export { defineCollections };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/db",
3
- "version": "1.0.0-alpha.4",
3
+ "version": "1.0.0-alpha.6",
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,21 @@
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.4"
57
+ "@lunora/client": "1.0.0-alpha.6"
50
58
  },
51
59
  "peerDependencies": {
52
60
  "@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 };
@@ -1,109 +0,0 @@
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 };