@midsummer-ai/sdk 0.1.0-next.901 → 0.1.0-staging.3106

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/auth-1W-SzpD3.mjs +441 -0
  2. package/build-DQo-JrlN.d.mts +120 -0
  3. package/bytes-C2pcyl9u.mjs +280 -0
  4. package/{connection-CDk7H1FL.mjs → connection-Cu2GSOaR.mjs} +171 -31
  5. package/database/build.d.mts +2 -2
  6. package/database/build.mjs +1404 -117
  7. package/database/client.d.mts +85 -9
  8. package/database/client.mjs +550 -32
  9. package/database/contract.d.mts +92 -2
  10. package/database/contract.mjs +2179 -3
  11. package/database/errors.d.mts +1 -22
  12. package/database/react.d.mts +133 -0
  13. package/database/react.mjs +488 -0
  14. package/database/server.d.mts +2 -3
  15. package/database/server.mjs +3 -320
  16. package/database/stand-in.d.mts +95 -9
  17. package/database/stand-in.mjs +1436 -116
  18. package/errors-x2vXKi0u.d.mts +25 -0
  19. package/index-DNNXNny7.d.mts +410 -0
  20. package/key-BrRdFY-n.mjs +11 -0
  21. package/package.json +114 -1
  22. package/schema-CTHQMRsW.mjs +217 -0
  23. package/server-B5HK2Ou9.d.mts +574 -0
  24. package/server-EDRbF2u-.mjs +1893 -0
  25. package/{store-BzI9at5x.mjs → store-lIZ5GxVv.mjs} +1 -1
  26. package/{tabs-D-P8_ci_.mjs → tabs-zCh8kceo.mjs} +1 -1
  27. package/vector/contract.d.mts +1 -1
  28. package/vector/contract.mjs +773 -1
  29. package/vector/index.d.mts +2 -2
  30. package/vector/index.mjs +71 -3
  31. package/vector/stand-in.d.mts +1 -1
  32. package/vector/stand-in.mjs +326 -23
  33. package/vector/wire.d.mts +11 -2
  34. package/vector/wire.mjs +179 -14
  35. package/build-SQ44jwSa.d.mts +0 -41
  36. package/index-DdoK0y7D.d.mts +0 -192
  37. package/schema-BF-Y1EVu.mjs +0 -142
  38. package/schema-DS8x1Dn8.mjs +0 -115
  39. package/schema-f7E9uzUn.d.mts +0 -74
  40. package/server-C7O7CICU.d.mts +0 -182
@@ -1,23 +1,2 @@
1
- //#region src/database/errors.d.ts
2
- /**
3
- * Why a Database refused a call, as the client throws it: the same codes from the Stand-in and the
4
- * Database.
5
- *
6
- * - `refused`: the function threw; nothing it wrote was kept.
7
- * - `short`: a `take` asked for more than a field holds; nothing moved.
8
- * - `notfound`: a patch or replace named a row that is not there.
9
- * - `invalid`: the arguments, the answer or a write did not fit their shapes.
10
- * - `internal`: an internal function, which no client may call.
11
- * - `no function`: no function of that name.
12
- * - `busy`, `quota`, `paused`: a limit the Project's plan or budget sets; `busy` may be sent again.
13
- * - `denied`: the caller may not do this: a Database Key or token was refused, or a token that only reads asked to write.
14
- * - `unavailable`: the Database could not be reached, or could not finish the call.
15
- */
16
- type DatabaseErrorCode = "refused" | "short" | "notfound" | "invalid" | "internal" | "no function" | "busy" | "quota" | "paused" | "denied" | "unavailable";
17
- declare class DatabaseError extends Error {
18
- readonly code: DatabaseErrorCode | (string & {});
19
- readonly detail?: unknown;
20
- constructor(code: DatabaseErrorCode | (string & {}), message?: string, detail?: unknown);
21
- }
22
- //#endregion
1
+ import { n as DatabaseErrorCode, t as DatabaseError } from "../errors-x2vXKi0u.mjs";
23
2
  export { DatabaseError, DatabaseErrorCode };
@@ -0,0 +1,133 @@
1
+ import { t as DatabaseError } from "../errors-x2vXKi0u.mjs";
2
+ import { Database, Reference } from "./client.mjs";
3
+ import { ReactNode } from "react";
4
+ //#region src/database/react.d.ts
5
+ type ArgsOf<F> = F extends Reference<any, infer A, any> ? A : never;
6
+ type ReturnsOf<F> = F extends Reference<any, any, infer R> ? R : never;
7
+ type EmptyObject = Record<string, never>;
8
+ /** A function's arguments, left out when it takes none. */
9
+ type OptionalArgs<F> = keyof ArgsOf<F> extends never ? [args?: ArgsOf<F> | EmptyObject] : [args: ArgsOf<F>];
10
+ /** A query's arguments, or `"skip"`, left out when it takes none. */
11
+ type ArgsOrSkip<F> = keyof ArgsOf<F> extends never ? [args?: ArgsOf<F> | EmptyObject | "skip"] : [args: ArgsOf<F> | "skip"];
12
+ /** What an optimistic update reads and changes: the queries shown now, as they would be once the mutation commits. */
13
+ interface OptimisticLocalStore {
14
+ /** The query's value as shown now; undefined when it is not shown or has no value yet. */
15
+ getQuery<F extends Reference<"query">>(fn: F, ...args: OptionalArgs<F>): ReturnsOf<F> | undefined;
16
+ /** Shows `value` for the query until the update is dropped. Give a new value; never change the one read. */
17
+ setQuery<F extends Reference<"query">>(fn: F, args: ArgsOf<F>, value: ReturnsOf<F> | undefined): void;
18
+ /** Every shown query of this function, with its arguments. */
19
+ getAllQueries<F extends Reference<"query">>(fn: F): Array<{
20
+ args: ArgsOf<F>;
21
+ value: ReturnsOf<F> | undefined;
22
+ }>;
23
+ }
24
+ type OptimisticUpdate<Args> = (store: OptimisticLocalStore, args: Args) => void;
25
+ /** What `useMutation` gives: call it to run the mutation. */
26
+ interface ReactMutation<F extends Reference<"mutation">> {
27
+ (...args: OptionalArgs<F>): Promise<ReturnsOf<F>>;
28
+ /** The same mutation, showing `update` from the moment it is called until the Database replies. */
29
+ withOptimisticUpdate(update: OptimisticUpdate<ArgsOf<F>>): ReactMutation<F>;
30
+ }
31
+ type ReactAction<F extends Reference<"action">> = (...args: OptionalArgs<F>) => Promise<ReturnsOf<F>>;
32
+ type PaginationStatus = "LoadingFirstPage" | "CanLoadMore" | "LoadingMore" | "Exhausted";
33
+ /** A page as a paginated query returns it: `ctx.db.query(...).paginate(paginationOpts)`. */
34
+ interface PaginationResult<T> {
35
+ readonly page: ReadonlyArray<T>;
36
+ readonly isDone: boolean;
37
+ readonly continueCursor: string;
38
+ }
39
+ interface PaginationOptions {
40
+ readonly numItems: number;
41
+ readonly cursor: string | null;
42
+ readonly endCursor?: string | null;
43
+ }
44
+ type PageItem<F> = ReturnsOf<F> extends PaginationResult<infer T> ? T : unknown;
45
+ /** A paginated query's arguments without `paginationOpts`, which the hook sends. */
46
+ type PageArgs<F> = Omit<ArgsOf<F>, "paginationOpts">;
47
+ interface UsePaginatedQueryResult<T> {
48
+ readonly results: T[];
49
+ readonly status: PaginationStatus;
50
+ readonly isLoading: boolean;
51
+ /** Asks for `numItems` more; does nothing unless the status is `CanLoadMore`. */
52
+ loadMore(numItems: number): void;
53
+ }
54
+ interface Shown {
55
+ readonly value: unknown;
56
+ readonly error: DatabaseError | undefined;
57
+ }
58
+ /**
59
+ * The provider's watches and optimistic updates: what every hook under one `DatabaseProvider` reads.
60
+ *
61
+ * A query an update sets is held at the value it had when the first such update began, and the
62
+ * pending updates are drawn over that, so a value that already has a write is never drawn with the
63
+ * write again. Once every update on a query has succeeded, the query is read once more: that read
64
+ * goes after their results, so it has all their writes. Its value is the query's from the moment it
65
+ * arrives, and the updates stop being drawn on it. A refused read leaves this to the watch's next
66
+ * value or refusal. Until a query is confirmed, other writes to it are shown only then.
67
+ */
68
+ declare class QueryStore {
69
+ readonly db: Database;
70
+ private readonly entries;
71
+ private pending;
72
+ /** Each query that pending updates are drawn on: its value when the first of them began. */
73
+ private readonly held;
74
+ /** Each query being confirmed: the read's number, and the updates it confirms. */
75
+ private readonly confirming;
76
+ private reads;
77
+ constructor(db: Database);
78
+ shown(key: string): Shown;
79
+ /** Watches the query while `listener` is held; returns its release. A release and a hold in one turn keep the watch. */
80
+ hold(fn: Reference<"query">, args: unknown, listener: () => void): () => void;
81
+ /**
82
+ * Shows `update` now and returns its settle, told whether the mutation succeeded. An update that
83
+ * throws is taken out and its error thrown here, before the mutation is sent.
84
+ */
85
+ begin(update: OptimisticUpdate<any>, args: unknown): (succeeded: boolean) => void;
86
+ /** The updates still drawn on `key`. */
87
+ private drawn;
88
+ /** Confirms `key` once every update drawn on it has succeeded: at once when it is not watched, else by a read. */
89
+ private settle;
90
+ /**
91
+ * A value or refusal from the watch. It confirms a query whose read was refused. A read still out
92
+ * was sent before this value, so its answer may be older: the query is read again instead.
93
+ */
94
+ private watched;
95
+ /** `items` are no longer drawn on `key`; it is held while other updates still are. */
96
+ private confirm;
97
+ /** Takes a refused or broken update out: the queries only it was drawn on show the Database's value again. */
98
+ private remove;
99
+ private base;
100
+ /**
101
+ * Runs the pending updates again over the held values and tells every hook whose shown value changed.
102
+ * An update that throws is taken out: thrown to its caller when it is `first`, reported otherwise.
103
+ */
104
+ private refresh;
105
+ }
106
+ /** Gives every hook below it `client`, a connection from `connect`. */
107
+ declare function DatabaseProvider({ client, children }: {
108
+ readonly client: Database;
109
+ readonly children?: ReactNode;
110
+ }): import("react").FunctionComponentElement<import("react").ProviderProps<QueryStore | null>>;
111
+ /** The `Database` the nearest `DatabaseProvider` was given. */
112
+ declare function useDatabase(): Database;
113
+ /**
114
+ * The query's value, shown again after every change: undefined while it loads, and while `args` is
115
+ * `"skip"`. A refusal throws its `DatabaseError` here, for the nearest error boundary.
116
+ */
117
+ declare function useQuery<F extends Reference<"query">>(fn: F, ...rest: ArgsOrSkip<F>): ReturnsOf<F> | undefined;
118
+ /** Runs the mutation; `.withOptimisticUpdate(update)` shows its effect before the Database replies. */
119
+ declare function useMutation<F extends Reference<"mutation">>(fn: F): ReactMutation<F>;
120
+ /** Runs the action. */
121
+ declare function useAction<F extends Reference<"action">>(fn: F): ReactAction<F>;
122
+ /**
123
+ * A paginated query, page after page, each watched: the query takes `paginationOpts` and returns
124
+ * `ctx.db.query(...).paginate(paginationOpts)`, which keeps every row up to `paginationOpts.endCursor`
125
+ * when it is given. A page loaded once keeps its rows: a row added to it or removed from it changes
126
+ * that page alone, and no loaded row leaves or is shown twice. A row added after the end of a list
127
+ * read to its end is loaded too.
128
+ */
129
+ declare function usePaginatedQuery<F extends Reference<"query">>(fn: F, args: PageArgs<F> | "skip", options: {
130
+ readonly initialNumItems: number;
131
+ }): UsePaginatedQueryResult<PageItem<F>>;
132
+ //#endregion
133
+ export { DatabaseProvider, OptimisticLocalStore, OptimisticUpdate, PaginationOptions, PaginationResult, PaginationStatus, ReactAction, ReactMutation, UsePaginatedQueryResult, useAction, useDatabase, useMutation, usePaginatedQuery, useQuery };
@@ -0,0 +1,488 @@
1
+ "use client";
2
+ import { t as callKey } from "../key-BrRdFY-n.mjs";
3
+ import { createContext, createElement, useCallback, useContext, useMemo, useSyncExternalStore } from "react";
4
+ //#region src/database/react.ts
5
+ /**
6
+ * `@midsummer-ai/sdk/react`: a Project's Database in React, in the shape a Convex app already uses.
7
+ *
8
+ * import { connect } from "@midsummer-ai/sdk/database"
9
+ * import { DatabaseProvider, useQuery, useMutation } from "@midsummer-ai/sdk/react"
10
+ * import { api } from "../db/_generated/api"
11
+ *
12
+ * const db = await connect({ url, token, refresh })
13
+ * root.render(<DatabaseProvider client={db}><App /></DatabaseProvider>)
14
+ *
15
+ * function Channel({ channel }: { channel: string }) {
16
+ * const messages = useQuery(api.messages.list, { channel }) // undefined while loading
17
+ * const send = useMutation(api.messages.send).withOptimisticUpdate((store, { body }) => {
18
+ * const shown = store.getQuery(api.messages.list, { channel })
19
+ * if (shown !== undefined) store.setQuery(api.messages.list, { channel }, [...shown, { body }])
20
+ * })
21
+ * ...
22
+ * }
23
+ *
24
+ * A signed-in user's token reaches the provider through `connect`. Your server checks its own sign-in
25
+ * and returns `{ url, token }` for that user from a route; `refresh` asks the route again before the
26
+ * token runs out and when the Database refuses it:
27
+ *
28
+ * const userToken = () => fetch("/db-token").then((response) => response.json() as Promise<{ url: string; token: string }>)
29
+ * const first = await userToken()
30
+ * const db = await connect({ url: first.url, token: first.token, refresh: async () => (await userToken()).token })
31
+ *
32
+ * A query is watched while a component shows it, and components that show the same query with the
33
+ * same arguments share one watch. Pass `"skip"` for the arguments to watch nothing. A query the
34
+ * Database refuses throws its `DatabaseError` where it is shown, for the nearest error boundary.
35
+ * An optimistic update is shown at once and is dropped when the mutation is refused, or once it
36
+ * succeeds and the Database's own value for each query it set has its write (see `QueryStore`).
37
+ *
38
+ * React is a peer dependency: a Project that does not import this entry does not need it.
39
+ */
40
+ const LOADING = Object.freeze({
41
+ value: void 0,
42
+ error: void 0
43
+ });
44
+ const keyOf = (fn, args) => callKey(fn.name, args);
45
+ /**
46
+ * The provider's watches and optimistic updates: what every hook under one `DatabaseProvider` reads.
47
+ *
48
+ * A query an update sets is held at the value it had when the first such update began, and the
49
+ * pending updates are drawn over that, so a value that already has a write is never drawn with the
50
+ * write again. Once every update on a query has succeeded, the query is read once more: that read
51
+ * goes after their results, so it has all their writes. Its value is the query's from the moment it
52
+ * arrives, and the updates stop being drawn on it. A refused read leaves this to the watch's next
53
+ * value or refusal. Until a query is confirmed, other writes to it are shown only then.
54
+ */
55
+ var QueryStore = class {
56
+ db;
57
+ entries = /* @__PURE__ */ new Map();
58
+ pending = [];
59
+ /** Each query that pending updates are drawn on: its value when the first of them began. */
60
+ held = /* @__PURE__ */ new Map();
61
+ /** Each query being confirmed: the read's number, and the updates it confirms. */
62
+ confirming = /* @__PURE__ */ new Map();
63
+ reads = 0;
64
+ constructor(db) {
65
+ this.db = db;
66
+ }
67
+ shown(key) {
68
+ return this.entries.get(key)?.shown ?? LOADING;
69
+ }
70
+ /** Watches the query while `listener` is held; returns its release. A release and a hold in one turn keep the watch. */
71
+ hold(fn, args, listener) {
72
+ const key = keyOf(fn, args);
73
+ let entry = this.entries.get(key);
74
+ if (!entry) {
75
+ entry = {
76
+ fn,
77
+ args,
78
+ server: void 0,
79
+ error: void 0,
80
+ shown: LOADING,
81
+ listeners: /* @__PURE__ */ new Set(),
82
+ stop: null,
83
+ leaving: null
84
+ };
85
+ this.entries.set(key, entry);
86
+ const it = entry;
87
+ it.stop = this.db.watch(fn, args, (value) => {
88
+ it.server = value;
89
+ it.error = void 0;
90
+ this.watched(key);
91
+ this.refresh();
92
+ }, (error) => {
93
+ it.error = error;
94
+ this.watched(key);
95
+ this.refresh();
96
+ });
97
+ this.refresh();
98
+ }
99
+ if (entry.leaving) {
100
+ clearTimeout(entry.leaving);
101
+ entry.leaving = null;
102
+ }
103
+ entry.listeners.add(listener);
104
+ const it = entry;
105
+ return () => {
106
+ it.listeners.delete(listener);
107
+ if (it.listeners.size || it.leaving) return;
108
+ it.leaving = setTimeout(() => {
109
+ it.leaving = null;
110
+ if (it.listeners.size || this.entries.get(key) !== it) return;
111
+ this.entries.delete(key);
112
+ it.stop?.();
113
+ this.settle(key);
114
+ this.refresh();
115
+ }, 0);
116
+ };
117
+ }
118
+ /**
119
+ * Shows `update` now and returns its settle, told whether the mutation succeeded. An update that
120
+ * throws is taken out and its error thrown here, before the mutation is sent.
121
+ */
122
+ begin(update, args) {
123
+ const item = {
124
+ update,
125
+ args,
126
+ keys: /* @__PURE__ */ new Set(),
127
+ succeeded: false,
128
+ confirmed: /* @__PURE__ */ new Set()
129
+ };
130
+ this.pending.push(item);
131
+ this.refresh(item);
132
+ return (succeeded) => {
133
+ if (!this.pending.includes(item)) return;
134
+ if (!succeeded) {
135
+ this.remove(item);
136
+ this.refresh();
137
+ return;
138
+ }
139
+ item.succeeded = true;
140
+ if (!item.keys.size) this.pending = this.pending.filter((one) => one !== item);
141
+ for (const key of item.keys) this.settle(key);
142
+ this.refresh();
143
+ };
144
+ }
145
+ /** The updates still drawn on `key`. */
146
+ drawn(key) {
147
+ return this.pending.filter((item) => item.keys.has(key) && !item.confirmed.has(key));
148
+ }
149
+ /** Confirms `key` once every update drawn on it has succeeded: at once when it is not watched, else by a read. */
150
+ settle(key) {
151
+ const items = this.drawn(key);
152
+ if (items.some((item) => !item.succeeded)) return;
153
+ const entry = this.entries.get(key);
154
+ if (!entry || !items.length) {
155
+ this.confirm(key, items);
156
+ return;
157
+ }
158
+ const n = this.reads += 1;
159
+ this.confirming.set(key, {
160
+ n,
161
+ items
162
+ });
163
+ this.db.query(entry.fn, entry.args).then((value) => {
164
+ if (this.confirming.get(key)?.n !== n) return;
165
+ if (this.entries.get(key) === entry) {
166
+ entry.server = value;
167
+ entry.error = void 0;
168
+ }
169
+ this.confirm(key, items);
170
+ this.refresh();
171
+ }, () => {
172
+ if (this.confirming.get(key)?.n === n) this.confirming.set(key, {
173
+ n: 0,
174
+ items
175
+ });
176
+ });
177
+ }
178
+ /**
179
+ * A value or refusal from the watch. It confirms a query whose read was refused. A read still out
180
+ * was sent before this value, so its answer may be older: the query is read again instead.
181
+ */
182
+ watched(key) {
183
+ const confirming = this.confirming.get(key);
184
+ if (confirming?.n === 0) this.confirm(key, confirming.items);
185
+ else if (confirming) this.settle(key);
186
+ }
187
+ /** `items` are no longer drawn on `key`; it is held while other updates still are. */
188
+ confirm(key, items) {
189
+ this.confirming.delete(key);
190
+ for (const item of items) {
191
+ item.confirmed.add(key);
192
+ if ([...item.keys].every((one) => item.confirmed.has(one))) this.pending = this.pending.filter((one) => one !== item);
193
+ }
194
+ if (this.drawn(key).length) this.held.set(key, this.entries.get(key)?.server);
195
+ else this.held.delete(key);
196
+ }
197
+ /** Takes a refused or broken update out: the queries only it was drawn on show the Database's value again. */
198
+ remove(item) {
199
+ this.pending = this.pending.filter((one) => one !== item);
200
+ for (const key of item.keys) if (!this.drawn(key).length) {
201
+ this.held.delete(key);
202
+ this.confirming.delete(key);
203
+ } else this.settle(key);
204
+ }
205
+ base(key) {
206
+ return this.held.has(key) ? this.held.get(key) : this.entries.get(key)?.server;
207
+ }
208
+ /**
209
+ * Runs the pending updates again over the held values and tells every hook whose shown value changed.
210
+ * An update that throws is taken out: thrown to its caller when it is `first`, reported otherwise.
211
+ */
212
+ refresh(first) {
213
+ const overlay = /* @__PURE__ */ new Map();
214
+ const read = (key) => overlay.has(key) ? overlay.get(key).value : this.base(key);
215
+ for (const item of this.pending) {
216
+ const store = {
217
+ getQuery: (fn, ...args) => read(keyOf(fn, args[0])),
218
+ setQuery: (fn, args, value) => {
219
+ const key = keyOf(fn, args);
220
+ if (item === first && !item.keys.has(key)) {
221
+ item.keys.add(key);
222
+ if (!this.held.has(key)) this.held.set(key, this.entries.get(key)?.server);
223
+ this.confirming.delete(key);
224
+ }
225
+ if (!item.confirmed.has(key)) overlay.set(key, {
226
+ args,
227
+ value
228
+ });
229
+ },
230
+ getAllQueries: (fn) => {
231
+ return [...new Set([...this.entries.keys(), ...overlay.keys()].filter((key) => key.startsWith(`${fn.name}|`)))].map((key) => ({
232
+ args: overlay.get(key)?.args ?? this.entries.get(key).args,
233
+ value: read(key)
234
+ }));
235
+ }
236
+ };
237
+ try {
238
+ item.update(store, item.args);
239
+ } catch (error) {
240
+ this.remove(item);
241
+ if (item === first) throw error;
242
+ console.error("An optimistic update threw and was dropped:", error);
243
+ return this.refresh();
244
+ }
245
+ }
246
+ const told = [];
247
+ for (const [key, entry] of this.entries) {
248
+ const value = overlay.has(key) ? overlay.get(key).value : this.base(key);
249
+ const error = overlay.has(key) || this.held.has(key) ? void 0 : entry.error;
250
+ if (value === entry.shown.value && error === entry.shown.error) continue;
251
+ entry.shown = value === void 0 && error === void 0 ? LOADING : {
252
+ value,
253
+ error
254
+ };
255
+ told.push(...entry.listeners);
256
+ }
257
+ for (const listener of told) listener();
258
+ }
259
+ };
260
+ const StoreContext = createContext(null);
261
+ /** Gives every hook below it `client`, a connection from `connect`. */
262
+ function DatabaseProvider({ client, children }) {
263
+ const store = useMemo(() => new QueryStore(client), [client]);
264
+ return createElement(StoreContext.Provider, { value: store }, children);
265
+ }
266
+ function useStore() {
267
+ const store = useContext(StoreContext);
268
+ if (!store) throw new Error("A Database hook is used outside a DatabaseProvider. Wrap the app in <DatabaseProvider client={db}>.");
269
+ return store;
270
+ }
271
+ /** The `Database` the nearest `DatabaseProvider` was given. */
272
+ function useDatabase() {
273
+ return useStore().db;
274
+ }
275
+ /**
276
+ * The query's value, shown again after every change: undefined while it loads, and while `args` is
277
+ * `"skip"`. A refusal throws its `DatabaseError` here, for the nearest error boundary.
278
+ */
279
+ function useQuery(fn, ...rest) {
280
+ const store = useStore();
281
+ const given = rest[0];
282
+ const args = given === "skip" ? null : given ?? {};
283
+ const key = args === null ? null : keyOf(fn, args);
284
+ const subscribe = useCallback((listener) => key === null ? () => {} : store.hold(fn, args, listener), [store, key]);
285
+ const shown = useSyncExternalStore(subscribe, () => key === null ? LOADING : store.shown(key), () => LOADING);
286
+ if (shown.error) throw shown.error;
287
+ return shown.value;
288
+ }
289
+ /** Runs the mutation; `.withOptimisticUpdate(update)` shows its effect before the Database replies. */
290
+ function useMutation(fn) {
291
+ const store = useStore();
292
+ return useMemo(() => mutationOf(store, fn, null), [store, fn.name]);
293
+ }
294
+ function mutationOf(store, fn, update) {
295
+ const run = (async (...rest) => {
296
+ const args = rest[0] ?? {};
297
+ const settle = update ? store.begin(update, args) : null;
298
+ try {
299
+ const value = await store.db.mutation(fn, args);
300
+ settle?.(true);
301
+ return value;
302
+ } catch (error) {
303
+ settle?.(false);
304
+ throw error;
305
+ }
306
+ });
307
+ run.withOptimisticUpdate = (next) => {
308
+ if (update) throw new Error("This mutation already has an optimistic update.");
309
+ return mutationOf(store, fn, next);
310
+ };
311
+ return run;
312
+ }
313
+ /** Runs the action. */
314
+ function useAction(fn) {
315
+ const store = useStore();
316
+ return useMemo(() => (...rest) => store.db.action(fn, rest[0] ?? {}), [store, fn.name]);
317
+ }
318
+ /**
319
+ * A paginated query, page after page, each watched: the query takes `paginationOpts` and returns
320
+ * `ctx.db.query(...).paginate(paginationOpts)`, which keeps every row up to `paginationOpts.endCursor`
321
+ * when it is given. A page loaded once keeps its rows: a row added to it or removed from it changes
322
+ * that page alone, and no loaded row leaves or is shown twice. A row added after the end of a list
323
+ * read to its end is loaded too.
324
+ */
325
+ function usePaginatedQuery(fn, args, options) {
326
+ const store = useStore();
327
+ const argsKey = args === "skip" ? null : callKey(fn.name, args);
328
+ const pages = useMemo(() => argsKey === null ? null : new Pages(store, fn, args, options.initialNumItems), [store, argsKey]);
329
+ const subscribe = useCallback((listener) => pages ? pages.subscribe(listener) : () => {}, [pages]);
330
+ const shown = useSyncExternalStore(subscribe, () => pages ? pages.shown : SKIPPED, () => SKIPPED);
331
+ if (shown.error) throw shown.error;
332
+ const loadMore = useCallback((numItems) => {
333
+ pages?.more(numItems);
334
+ }, [pages]);
335
+ return useMemo(() => ({
336
+ results: shown.results,
337
+ status: shown.status,
338
+ isLoading: shown.status === "LoadingFirstPage" || shown.status === "LoadingMore",
339
+ loadMore
340
+ }), [shown, loadMore]);
341
+ }
342
+ const SKIPPED = Object.freeze({
343
+ results: [],
344
+ status: "LoadingFirstPage",
345
+ error: void 0
346
+ });
347
+ /**
348
+ * One paginated query's pages. A page is asked for by `numItems` from where the page before it ends;
349
+ * once it has a value it is watched again pinned to that end (`endCursor`), so it covers the same
350
+ * rows from then on and grows or shrinks with them, and the next page starts where it ends.
351
+ */
352
+ var Pages = class {
353
+ store;
354
+ fn;
355
+ args;
356
+ specs;
357
+ held = /* @__PURE__ */ new Map();
358
+ /** Each page's last value: a pinned page shows its unpinned value until its own comes. */
359
+ last = [];
360
+ /** Whether the list was read to its end: a row added after the end is then loaded too. */
361
+ exhausted = false;
362
+ listener = null;
363
+ /** The page values `shown` was made from. */
364
+ used = [];
365
+ shown = SKIPPED;
366
+ constructor(store, fn, args, initial) {
367
+ this.store = store;
368
+ this.fn = fn;
369
+ this.args = args;
370
+ this.specs = [{
371
+ cursor: null,
372
+ end: null,
373
+ numItems: initial
374
+ }];
375
+ }
376
+ subscribe(listener) {
377
+ this.listener = listener;
378
+ this.walk();
379
+ return () => {
380
+ this.listener = null;
381
+ for (const release of this.held.values()) release();
382
+ this.held.clear();
383
+ };
384
+ }
385
+ /** Asks for a next page; false when there is none to ask for yet. */
386
+ more(numItems) {
387
+ if (this.shown.status !== "CanLoadMore") return false;
388
+ this.specs.push({
389
+ cursor: this.specs.at(-1).end,
390
+ end: null,
391
+ numItems
392
+ });
393
+ this.walk();
394
+ return true;
395
+ }
396
+ walking = false;
397
+ again = false;
398
+ /** Watches the pages and shows them; again while a page just watched or pinned had a value at once. */
399
+ walk() {
400
+ if (!this.listener) return;
401
+ if (this.walking) {
402
+ this.again = true;
403
+ return;
404
+ }
405
+ this.walking = true;
406
+ try {
407
+ do {
408
+ this.again = false;
409
+ this.step();
410
+ } while (this.again && this.listener);
411
+ } finally {
412
+ this.walking = false;
413
+ }
414
+ }
415
+ step() {
416
+ const want = /* @__PURE__ */ new Map();
417
+ const used = [];
418
+ let status = null, error;
419
+ for (const [i, spec] of this.specs.entries()) {
420
+ const paginationOpts = spec.end === null ? {
421
+ numItems: spec.numItems,
422
+ cursor: spec.cursor
423
+ } : {
424
+ numItems: spec.numItems,
425
+ cursor: spec.cursor,
426
+ endCursor: spec.end
427
+ };
428
+ const args = {
429
+ ...this.args,
430
+ paginationOpts
431
+ };
432
+ const key = keyOf(this.fn, args);
433
+ want.set(key, { args });
434
+ const shown = this.store.shown(key);
435
+ if (shown.error) {
436
+ error = shown.error;
437
+ break;
438
+ }
439
+ const value = shown.value;
440
+ if (value !== void 0) {
441
+ this.last[i] = value;
442
+ if (spec.end === null) {
443
+ spec.end = value.continueCursor;
444
+ this.again = true;
445
+ }
446
+ }
447
+ const page = this.last[i];
448
+ if (!page) {
449
+ status = i === 0 ? "LoadingFirstPage" : "LoadingMore";
450
+ break;
451
+ }
452
+ used.push(page);
453
+ }
454
+ if (status === null && !error) {
455
+ const done = used.at(-1).isDone;
456
+ if (!done && this.exhausted) {
457
+ this.specs.push({
458
+ cursor: this.specs.at(-1).end,
459
+ end: null,
460
+ numItems: this.specs.at(-1).numItems
461
+ });
462
+ this.again = true;
463
+ status = "LoadingMore";
464
+ } else status = done ? "Exhausted" : "CanLoadMore";
465
+ this.exhausted = status === "Exhausted" || this.exhausted && status === "LoadingMore";
466
+ }
467
+ for (const [key, { args }] of want) {
468
+ if (this.held.has(key)) continue;
469
+ this.held.set(key, this.store.hold(this.fn, args, () => this.walk()));
470
+ if (this.store.shown(key) !== LOADING) this.again = true;
471
+ }
472
+ for (const [key, release] of this.held) if (!want.has(key)) {
473
+ release();
474
+ this.held.delete(key);
475
+ }
476
+ const next = status ?? "LoadingFirstPage";
477
+ if (next === this.shown.status && error === this.shown.error && used.length === this.used.length && used.every((page, i) => page === this.used[i])) return;
478
+ this.used = used;
479
+ this.shown = {
480
+ results: used.flatMap((page) => page.page),
481
+ status: next,
482
+ error
483
+ };
484
+ this.listener?.();
485
+ }
486
+ };
487
+ //#endregion
488
+ export { DatabaseProvider, useAction, useDatabase, useMutation, usePaginatedQuery, useQuery };
@@ -1,3 +1,2 @@
1
- import { a as defineSchema, c as shapeError, i as Table, l as v, n as Schema, o as defineTable, r as Shape, s as indexFields, t as IndexDeclaration } from "../schema-f7E9uzUn.mjs";
2
- import { C as take, S as query, _ as internalAction, a as InsufficientError, b as isFunction, c as RangeOptions, d as Row, f as Rows, g as increment, h as give, i as FunctionReference, l as Refusal, m as action, n as Document, o as NotFoundError, p as ScheduledRun, r as FunctionKind, s as Operator, t as Capabilities, u as RegisteredFunction, v as internalMutation, x as mutation, y as internalQuery } from "../server-C7O7CICU.mjs";
3
- export { Capabilities, Document, FunctionKind, FunctionReference, type IndexDeclaration, InsufficientError, NotFoundError, Operator, RangeOptions, Refusal, RegisteredFunction, Row, Rows, ScheduledRun, type Schema, type Shape, type Table, action, defineSchema, defineTable, give, increment, indexFields, internalAction, internalMutation, internalQuery, isFunction, mutation, query, shapeError, take, v };
1
+ import { $ as VectorIndex, A as increment, B as paginationOptsValidator, C as UserIdentity, D as give, E as fetchOver, F as isIdOf, G as VectorFilter, H as readLimited, I as isRouter, J as IndexDeclaration, K as VectorSearch, L as limits, M as internalMutation, N as internalQuery, O as httpAction, P as isFunction, Q as Table, R as mutation, S as TooLarge, T as cronJobs, U as scheduleOf, V as query, W as take, X as SearchIndex, Y as Schema, Z as Shape, _ as Refusal, a as FileMetadata, at as tableCode, b as Rows, c as FunctionReference, d as HttpRouter, et as defineSchema, f as IndexBounds, g as RangeOptions, h as Operator, i as Document, it as shapeError, j as internalAction, k as httpRouter, l as HttpMethod, m as NotFoundError, n as CronJob, nt as indexFields, o as Files, ot as v, p as InsufficientError, q as ID_FORM, r as Crons, rt as isIdForm, s as FunctionKind, t as Capabilities, tt as defineTable, u as HttpRoute, v as RegisteredFunction, w as action, x as ScheduledRun, y as Row, z as nextCron } from "../server-B5HK2Ou9.mjs";
2
+ export { Capabilities, CronJob, Crons, Document, FileMetadata, Files, FunctionKind, FunctionReference, HttpMethod, HttpRoute, HttpRouter, ID_FORM, IndexBounds, type IndexDeclaration, InsufficientError, NotFoundError, Operator, RangeOptions, Refusal, RegisteredFunction, Row, Rows, ScheduledRun, type Schema, type SearchIndex, type Shape, type Table, TooLarge, UserIdentity, type VectorFilter, type VectorIndex, type VectorSearch, action, cronJobs, defineSchema, defineTable, fetchOver, give, httpAction, httpRouter, increment, indexFields, internalAction, internalMutation, internalQuery, isFunction, isIdForm, isIdOf, isRouter, limits, mutation, nextCron, paginationOptsValidator, query, readLimited, scheduleOf, shapeError, tableCode, take, v };