@convex-dev/agent 0.1.6-alpha.1 → 0.1.7-alpha.0

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 (115) hide show
  1. package/README.md +23 -12
  2. package/dist/commonjs/client/_generated/_ignore.d.ts +1 -0
  3. package/dist/commonjs/client/_generated/_ignore.d.ts.map +1 -0
  4. package/dist/commonjs/client/_generated/_ignore.js +3 -0
  5. package/dist/commonjs/client/_generated/_ignore.js.map +1 -0
  6. package/dist/commonjs/client/files.d.ts +57 -0
  7. package/dist/commonjs/client/files.d.ts.map +1 -0
  8. package/dist/commonjs/client/files.js +124 -0
  9. package/dist/commonjs/client/files.js.map +1 -0
  10. package/dist/commonjs/client/index.d.ts +489 -318
  11. package/dist/commonjs/client/index.d.ts.map +1 -1
  12. package/dist/commonjs/client/index.js +652 -550
  13. package/dist/commonjs/client/index.js.map +1 -1
  14. package/dist/commonjs/client/types.d.ts +35 -5
  15. package/dist/commonjs/client/types.d.ts.map +1 -1
  16. package/dist/commonjs/component/_generated/api.d.ts +53 -711
  17. package/dist/commonjs/component/files.d.ts +66 -21
  18. package/dist/commonjs/component/files.d.ts.map +1 -1
  19. package/dist/commonjs/component/files.js +71 -26
  20. package/dist/commonjs/component/files.js.map +1 -1
  21. package/dist/commonjs/component/messages.d.ts +37 -499
  22. package/dist/commonjs/component/messages.d.ts.map +1 -1
  23. package/dist/commonjs/component/messages.js +44 -124
  24. package/dist/commonjs/component/messages.js.map +1 -1
  25. package/dist/commonjs/component/schema.d.ts +951 -3785
  26. package/dist/commonjs/component/schema.d.ts.map +1 -1
  27. package/dist/commonjs/component/schema.js +8 -25
  28. package/dist/commonjs/component/schema.js.map +1 -1
  29. package/dist/commonjs/component/streams.d.ts +3 -3
  30. package/dist/commonjs/mapping.d.ts +28 -19
  31. package/dist/commonjs/mapping.d.ts.map +1 -1
  32. package/dist/commonjs/mapping.js +136 -81
  33. package/dist/commonjs/mapping.js.map +1 -1
  34. package/dist/commonjs/react/index.d.ts.map +1 -1
  35. package/dist/commonjs/react/index.js +2 -1
  36. package/dist/commonjs/react/index.js.map +1 -1
  37. package/dist/commonjs/react/toUIMessages.d.ts.map +1 -1
  38. package/dist/commonjs/react/toUIMessages.js +12 -6
  39. package/dist/commonjs/react/toUIMessages.js.map +1 -1
  40. package/dist/commonjs/react/usePaginatedQuery.d.ts +241 -0
  41. package/dist/commonjs/react/usePaginatedQuery.d.ts.map +1 -0
  42. package/dist/commonjs/react/usePaginatedQuery.js +647 -0
  43. package/dist/commonjs/react/usePaginatedQuery.js.map +1 -0
  44. package/dist/commonjs/validators.d.ts +851 -3388
  45. package/dist/commonjs/validators.d.ts.map +1 -1
  46. package/dist/commonjs/validators.js +11 -37
  47. package/dist/commonjs/validators.js.map +1 -1
  48. package/dist/commonjs.tsbuildinfo +1 -1
  49. package/dist/esm/client/_generated/_ignore.d.ts +1 -0
  50. package/dist/esm/client/_generated/_ignore.d.ts.map +1 -0
  51. package/dist/esm/client/_generated/_ignore.js +3 -0
  52. package/dist/esm/client/_generated/_ignore.js.map +1 -0
  53. package/dist/esm/client/files.d.ts +57 -0
  54. package/dist/esm/client/files.d.ts.map +1 -0
  55. package/dist/esm/client/files.js +124 -0
  56. package/dist/esm/client/files.js.map +1 -0
  57. package/dist/esm/client/index.d.ts +489 -318
  58. package/dist/esm/client/index.d.ts.map +1 -1
  59. package/dist/esm/client/index.js +652 -550
  60. package/dist/esm/client/index.js.map +1 -1
  61. package/dist/esm/client/types.d.ts +35 -5
  62. package/dist/esm/client/types.d.ts.map +1 -1
  63. package/dist/esm/component/_generated/api.d.ts +53 -711
  64. package/dist/esm/component/files.d.ts +66 -21
  65. package/dist/esm/component/files.d.ts.map +1 -1
  66. package/dist/esm/component/files.js +71 -26
  67. package/dist/esm/component/files.js.map +1 -1
  68. package/dist/esm/component/messages.d.ts +37 -499
  69. package/dist/esm/component/messages.d.ts.map +1 -1
  70. package/dist/esm/component/messages.js +44 -124
  71. package/dist/esm/component/messages.js.map +1 -1
  72. package/dist/esm/component/schema.d.ts +951 -3785
  73. package/dist/esm/component/schema.d.ts.map +1 -1
  74. package/dist/esm/component/schema.js +8 -25
  75. package/dist/esm/component/schema.js.map +1 -1
  76. package/dist/esm/component/streams.d.ts +3 -3
  77. package/dist/esm/mapping.d.ts +28 -19
  78. package/dist/esm/mapping.d.ts.map +1 -1
  79. package/dist/esm/mapping.js +136 -81
  80. package/dist/esm/mapping.js.map +1 -1
  81. package/dist/esm/react/index.d.ts.map +1 -1
  82. package/dist/esm/react/index.js +2 -1
  83. package/dist/esm/react/index.js.map +1 -1
  84. package/dist/esm/react/toUIMessages.d.ts.map +1 -1
  85. package/dist/esm/react/toUIMessages.js +12 -6
  86. package/dist/esm/react/toUIMessages.js.map +1 -1
  87. package/dist/esm/react/usePaginatedQuery.d.ts +241 -0
  88. package/dist/esm/react/usePaginatedQuery.d.ts.map +1 -0
  89. package/dist/esm/react/usePaginatedQuery.js +647 -0
  90. package/dist/esm/react/usePaginatedQuery.js.map +1 -0
  91. package/dist/esm/validators.d.ts +851 -3388
  92. package/dist/esm/validators.d.ts.map +1 -1
  93. package/dist/esm/validators.js +11 -37
  94. package/dist/esm/validators.js.map +1 -1
  95. package/dist/esm.tsbuildinfo +1 -1
  96. package/package.json +11 -9
  97. package/src/client/_generated/_ignore.ts +1 -0
  98. package/src/client/files.ts +167 -0
  99. package/src/client/index.test.ts +127 -1
  100. package/src/client/index.ts +970 -812
  101. package/src/client/setup.test.ts +29 -0
  102. package/src/client/types.ts +41 -3
  103. package/src/component/_generated/api.d.ts +53 -711
  104. package/src/component/files.test.ts +130 -0
  105. package/src/component/files.ts +83 -27
  106. package/src/component/messages.test.ts +2 -1
  107. package/src/component/messages.ts +46 -136
  108. package/src/component/schema.ts +7 -28
  109. package/src/mapping.test.ts +163 -0
  110. package/src/mapping.ts +173 -103
  111. package/src/react/deltas.test.ts +4 -1
  112. package/src/react/index.ts +2 -1
  113. package/src/react/toUIMessages.ts +12 -6
  114. package/src/react/usePaginatedQuery.ts +933 -0
  115. package/src/validators.ts +33 -47
@@ -0,0 +1,933 @@
1
+ import { useMemo, useState } from "react";
2
+
3
+ import type { OptimisticLocalStore } from "convex/browser";
4
+ import type {
5
+ FunctionReturnType,
6
+ PaginationOptions,
7
+ paginationOptsValidator,
8
+ PaginationResult,
9
+ } from "convex/server";
10
+ import {
11
+ ConvexError,
12
+ convexToJson,
13
+ type Infer,
14
+ type Value,
15
+ } from "convex/values";
16
+ import { useQueries } from "convex/react";
17
+ import {
18
+ type FunctionArgs,
19
+ type FunctionReference,
20
+ getFunctionName,
21
+ } from "convex/server";
22
+ import type { BetterOmit, Expand } from "convex/server";
23
+ import { useConvex } from "convex/react";
24
+ import { compareValues } from "convex/values";
25
+
26
+ /* eslint-disable @typescript-eslint/no-explicit-any */
27
+
28
+ /**
29
+ * A {@link server.FunctionReference} that is usable with {@link usePaginatedQuery}.
30
+ *
31
+ * This function reference must:
32
+ * - Refer to a public query
33
+ * - Have an argument named "paginationOpts" of type {@link server.PaginationOptions}
34
+ * - Have a return type of {@link server.PaginationResult}.
35
+ *
36
+ * @public
37
+ */
38
+ export type PaginatedQueryReference = FunctionReference<
39
+ "query",
40
+ "public",
41
+ { paginationOpts: PaginationOptions },
42
+ PaginationResult<any>
43
+ >;
44
+
45
+ // Incrementing integer for each page queried in the usePaginatedQuery hook.
46
+ type QueryPageKey = number;
47
+
48
+ type UsePaginatedQueryState = {
49
+ query: FunctionReference<"query">;
50
+ args: Record<string, Value>;
51
+ id: number;
52
+ nextPageKey: QueryPageKey;
53
+ pageKeys: QueryPageKey[];
54
+ queries: Record<
55
+ QueryPageKey,
56
+ {
57
+ query: FunctionReference<"query">;
58
+ // Use the validator type as a test that it matches the args
59
+ // we generate.
60
+ args: { paginationOpts: Infer<typeof paginationOptsValidator> };
61
+ }
62
+ >;
63
+ ongoingSplits: Record<QueryPageKey, [QueryPageKey, QueryPageKey]>;
64
+ skip: boolean;
65
+ };
66
+
67
+ const splitQuery =
68
+ (key: QueryPageKey, splitCursor: string, continueCursor: string) =>
69
+ (prevState: UsePaginatedQueryState) => {
70
+ console.log("splitQuery", key, splitCursor, continueCursor);
71
+ const queries = { ...prevState.queries };
72
+ const splitKey1 = prevState.nextPageKey;
73
+ const splitKey2 = prevState.nextPageKey + 1;
74
+ const nextPageKey = prevState.nextPageKey + 2;
75
+ queries[splitKey1] = {
76
+ query: prevState.query,
77
+ args: {
78
+ ...prevState.args,
79
+ paginationOpts: {
80
+ ...prevState.queries[key].args.paginationOpts,
81
+ endCursor: splitCursor,
82
+ },
83
+ },
84
+ };
85
+ queries[splitKey2] = {
86
+ query: prevState.query,
87
+ args: {
88
+ ...prevState.args,
89
+ paginationOpts: {
90
+ ...prevState.queries[key].args.paginationOpts,
91
+ cursor: splitCursor,
92
+ endCursor: continueCursor,
93
+ },
94
+ },
95
+ };
96
+ const ongoingSplits = { ...prevState.ongoingSplits };
97
+ ongoingSplits[key] = [splitKey1, splitKey2];
98
+ return {
99
+ ...prevState,
100
+ nextPageKey,
101
+ queries,
102
+ ongoingSplits,
103
+ };
104
+ };
105
+
106
+ const completeSplitQuery =
107
+ (key: QueryPageKey) => (prevState: UsePaginatedQueryState) => {
108
+ console.log("completeSplitQuery", key);
109
+ const completedSplit = prevState.ongoingSplits[key];
110
+ if (completedSplit === undefined) {
111
+ return prevState;
112
+ }
113
+ const queries = { ...prevState.queries };
114
+ delete queries[key];
115
+ const ongoingSplits = { ...prevState.ongoingSplits };
116
+ delete ongoingSplits[key];
117
+ let pageKeys = prevState.pageKeys.slice();
118
+ const pageIndex = prevState.pageKeys.findIndex((v) => v === key);
119
+ if (pageIndex >= 0) {
120
+ pageKeys = [
121
+ ...prevState.pageKeys.slice(0, pageIndex),
122
+ ...completedSplit,
123
+ ...prevState.pageKeys.slice(pageIndex + 1),
124
+ ];
125
+ }
126
+ return {
127
+ ...prevState,
128
+ queries,
129
+ pageKeys,
130
+ ongoingSplits,
131
+ };
132
+ };
133
+
134
+ /**
135
+ * This is a clone of the `usePaginatedQuery` hook from `convex-helpers`.
136
+ * The difference is that we lazily pin the end cursor on loading a new page.
137
+ * This will be standard behavior in a future version of `convex/react`, but
138
+ * for now it allows the agent to have correct behavior when loading a new page
139
+ * where new items are still coming in.
140
+ */
141
+ export function usePaginatedQuery<Query extends PaginatedQueryReference>(
142
+ query: Query,
143
+ args: PaginatedQueryArgs<Query> | "skip",
144
+ options: { initialNumItems: number }
145
+ ): UsePaginatedQueryReturnType<Query> {
146
+ console.log("usePaginatedQuery", query, args, options);
147
+ if (
148
+ typeof options?.initialNumItems !== "number" ||
149
+ options.initialNumItems < 0
150
+ ) {
151
+ throw new Error(
152
+ `\`options.initialNumItems\` must be a positive number. Received \`${options?.initialNumItems}\`.`
153
+ );
154
+ }
155
+ const skip = args === "skip";
156
+ const argsObject = skip ? {} : args;
157
+ const queryName = getFunctionName(query);
158
+ const createInitialState = useMemo(() => {
159
+ return () => {
160
+ const id = nextPaginationId();
161
+ console.log("createInitialState", id, queryName, argsObject);
162
+ return {
163
+ query,
164
+ args: argsObject as Record<string, Value>,
165
+ id,
166
+ nextPageKey: 1,
167
+ pageKeys: skip ? [] : [0],
168
+ queries: skip
169
+ ? ({} as UsePaginatedQueryState["queries"])
170
+ : {
171
+ 0: {
172
+ query,
173
+ args: {
174
+ ...argsObject,
175
+ paginationOpts: {
176
+ numItems: options.initialNumItems,
177
+ cursor: null,
178
+ id,
179
+ },
180
+ },
181
+ },
182
+ },
183
+ ongoingSplits: {},
184
+ skip,
185
+ };
186
+ };
187
+ // ESLint doesn't like that we're stringifying the args. We do this because
188
+ // we want to avoid rerendering if the args are a different
189
+ // object that serializes to the same result.
190
+ // eslint-disable-next-line react-hooks/exhaustive-deps
191
+ }, [
192
+ // eslint-disable-next-line react-hooks/exhaustive-deps
193
+ JSON.stringify(convexToJson(argsObject as Value)),
194
+ queryName,
195
+ options.initialNumItems,
196
+ skip,
197
+ ]);
198
+
199
+ const [state, setState] =
200
+ useState<UsePaginatedQueryState>(createInitialState);
201
+
202
+ // `currState` is the state that we'll render based on.
203
+ let currState = state;
204
+ if (
205
+ getFunctionName(query) !== getFunctionName(state.query) ||
206
+ JSON.stringify(convexToJson(argsObject as Value)) !==
207
+ JSON.stringify(convexToJson(state.args)) ||
208
+ skip !== state.skip
209
+ ) {
210
+ currState = createInitialState();
211
+ console.log("resetting state", currState);
212
+ setState(currState);
213
+ }
214
+ const convexClient = useConvex();
215
+ const logger = convexClient.logger;
216
+
217
+ const resultsObject = useQueries(currState.queries);
218
+
219
+ const [results, maybeLastResult]: [
220
+ Value[],
221
+ undefined | PaginationResult<Value>,
222
+ ] = useMemo(() => {
223
+ let currResult = undefined;
224
+
225
+ const allItems = [];
226
+ for (const pageKey of currState.pageKeys) {
227
+ currResult = resultsObject[pageKey];
228
+ console.log({
229
+ pageKey,
230
+ continue: currResult?.continueCursor,
231
+ cursor: currState.queries[pageKey]?.args?.paginationOpts?.cursor,
232
+ split: currResult?.splitCursor,
233
+ status: currResult?.pageStatus,
234
+ length: currResult?.page?.length,
235
+ });
236
+ if (currResult === undefined) {
237
+ break;
238
+ }
239
+
240
+ if (currResult instanceof Error) {
241
+ if (
242
+ currResult.message.includes("InvalidCursor") ||
243
+ (currResult instanceof ConvexError &&
244
+ typeof currResult.data === "object" &&
245
+ currResult.data?.isConvexSystemError === true &&
246
+ currResult.data?.paginationError === "InvalidCursor")
247
+ ) {
248
+ // - InvalidCursor: If the cursor is invalid, probably the paginated
249
+ // database query was data-dependent and changed underneath us. The
250
+ // cursor in the params or journal no longer matches the current
251
+ // database query.
252
+
253
+ // In all cases, we want to restart pagination to throw away all our
254
+ // existing cursors.
255
+ logger.warn(
256
+ "usePaginatedQuery hit error, resetting pagination state: " +
257
+ currResult.message
258
+ );
259
+ setState(createInitialState);
260
+ return [[], undefined];
261
+ } else {
262
+ throw currResult;
263
+ }
264
+ }
265
+ const ongoingSplit = currState.ongoingSplits[pageKey];
266
+ if (ongoingSplit !== undefined) {
267
+ console.log("ongoingSplit", pageKey, ongoingSplit);
268
+ if (
269
+ resultsObject[ongoingSplit[0]] !== undefined &&
270
+ resultsObject[ongoingSplit[1]] !== undefined
271
+ ) {
272
+ // Both pages of the split have results now. Swap them in.
273
+ console.log("completeSplitQuery", pageKey);
274
+ setState(completeSplitQuery(pageKey));
275
+ }
276
+ } else if (
277
+ currResult.splitCursor &&
278
+ (currResult.pageStatus === "SplitRecommended" ||
279
+ currResult.pageStatus === "SplitRequired" ||
280
+ currResult.page.length > options.initialNumItems * 2)
281
+ ) {
282
+ console.log(
283
+ "splitQuery",
284
+ pageKey,
285
+ currResult.pageStatus,
286
+ currResult.page.length
287
+ );
288
+ // If a single page has more than double the expected number of items,
289
+ // or if the server requests a split, split the page into two.
290
+ setState(
291
+ splitQuery(pageKey, currResult.splitCursor, currResult.continueCursor)
292
+ );
293
+ }
294
+ if (currResult.pageStatus === "SplitRequired") {
295
+ // If pageStatus is 'SplitRequired', it means the server was not able to
296
+ // fetch the full page. So we stop results before the incomplete
297
+ // page and return 'LoadingMore' while the page is splitting.
298
+ return [allItems, undefined];
299
+ }
300
+ allItems.push(...currResult.page);
301
+ }
302
+ return [allItems, currResult];
303
+ // eslint-disable-next-line react-hooks/exhaustive-deps
304
+ }, [
305
+ resultsObject,
306
+ currState.pageKeys,
307
+ currState.ongoingSplits,
308
+ options.initialNumItems,
309
+ createInitialState,
310
+ logger,
311
+ ]);
312
+
313
+ const statusObject = useMemo(() => {
314
+ if (maybeLastResult === undefined) {
315
+ if (currState.nextPageKey === 1) {
316
+ return {
317
+ status: "LoadingFirstPage",
318
+ isLoading: true,
319
+ loadMore: (_numItems: number) => {
320
+ // Intentional noop.
321
+ },
322
+ } as const;
323
+ } else {
324
+ console.log("LoadingMore", maybeLastResult);
325
+ return {
326
+ status: "LoadingMore",
327
+ isLoading: true,
328
+ loadMore: (_numItems: number) => {
329
+ // Intentional noop.
330
+ },
331
+ } as const;
332
+ }
333
+ }
334
+ if (maybeLastResult.isDone) {
335
+ console.log("Exhausted", maybeLastResult);
336
+ return {
337
+ status: "Exhausted",
338
+ isLoading: false,
339
+ loadMore: (_numItems: number) => {
340
+ // Intentional noop.
341
+ },
342
+ } as const;
343
+ }
344
+ const continueCursor = maybeLastResult.continueCursor;
345
+ let alreadyLoadingMore = false;
346
+ return {
347
+ status: "CanLoadMore",
348
+ isLoading: false,
349
+ loadMore: (numItems: number) => {
350
+ if (!alreadyLoadingMore) {
351
+ alreadyLoadingMore = true;
352
+ setState((prevState) => {
353
+ const lastPageKey = prevState.pageKeys.at(-1)!;
354
+ const replaceKey = prevState.nextPageKey;
355
+ const newKey = prevState.nextPageKey + 1;
356
+ const nextPageKey = prevState.nextPageKey + 2;
357
+ const pageKeys = prevState.pageKeys; //[...prevState.pageKeys, prevState.nextPageKey];
358
+ const queries = { ...prevState.queries };
359
+ console.log(
360
+ "loading more",
361
+ lastPageKey,
362
+ replaceKey,
363
+ newKey,
364
+ nextPageKey,
365
+ pageKeys
366
+ );
367
+
368
+ queries[replaceKey] = {
369
+ query: prevState.query,
370
+ args: {
371
+ ...prevState.args,
372
+ paginationOpts: {
373
+ ...(queries[prevState.pageKeys.at(-1)!]!.args
374
+ .paginationOpts as unknown as PaginationOptions),
375
+ endCursor: continueCursor,
376
+ },
377
+ },
378
+ };
379
+ queries[newKey] = {
380
+ query: prevState.query,
381
+ args: {
382
+ ...prevState.args,
383
+ paginationOpts: {
384
+ numItems,
385
+ cursor: continueCursor,
386
+ id: prevState.id,
387
+ },
388
+ },
389
+ };
390
+ return {
391
+ ...prevState,
392
+ nextPageKey,
393
+ pageKeys,
394
+ queries,
395
+ ongoingSplits: {
396
+ ...prevState.ongoingSplits,
397
+ [lastPageKey]: [replaceKey, newKey],
398
+ },
399
+ };
400
+ });
401
+ }
402
+ },
403
+ } as const;
404
+ }, [maybeLastResult, currState.nextPageKey]);
405
+
406
+ return {
407
+ results,
408
+ ...statusObject,
409
+ };
410
+ }
411
+
412
+ let paginationId = 0;
413
+ /**
414
+ * Generate a new, unique ID for a pagination session.
415
+ *
416
+ * Every usage of {@link usePaginatedQuery} puts a unique ID into the
417
+ * query function arguments as a "cache-buster". This serves two purposes:
418
+ *
419
+ * 1. All calls to {@link usePaginatedQuery} have independent query
420
+ * journals.
421
+ *
422
+ * Every time we start a new pagination session, we'll load the first page of
423
+ * results and receive a fresh journal. Without the ID, we might instead reuse
424
+ * a query subscription already present in our client. This isn't desirable
425
+ * because the existing query function result may have grown or shrunk from the
426
+ * requested `initialNumItems`.
427
+ *
428
+ * 2. We can restart the pagination session on some types of errors.
429
+ *
430
+ * Sometimes we want to restart pagination from the beginning if we hit an error.
431
+ * Similar to (1), we'd like to ensure that this new session actually requests
432
+ * its first page from the server and doesn't reuse a query result already
433
+ * present in the client that may have hit the error.
434
+ *
435
+ * @returns The pagination ID.
436
+ */
437
+ function nextPaginationId(): number {
438
+ paginationId++;
439
+ return paginationId;
440
+ }
441
+
442
+ /**
443
+ * Reset pagination id for tests only, so tests know what it is.
444
+ */
445
+ export function resetPaginationId() {
446
+ paginationId = 0;
447
+ }
448
+
449
+ /**
450
+ * The result of calling the {@link usePaginatedQuery} hook.
451
+ *
452
+ * This includes:
453
+ * - `results` - An array of the currently loaded results.
454
+ * - `isLoading` - Whether the hook is currently loading results.
455
+ * - `status` - The status of the pagination. The possible statuses are:
456
+ * - "LoadingFirstPage": The hook is loading the first page of results.
457
+ * - "CanLoadMore": This query may have more items to fetch. Call `loadMore` to
458
+ * fetch another page.
459
+ * - "LoadingMore": We're currently loading another page of results.
460
+ * - "Exhausted": We've paginated to the end of the list.
461
+ * - `loadMore(n)` A callback to fetch more results. This will only fetch more
462
+ * results if the status is "CanLoadMore".
463
+ *
464
+ * @public
465
+ */
466
+ export type UsePaginatedQueryResult<Item> = {
467
+ results: Item[];
468
+ loadMore: (numItems: number) => void;
469
+ } & (
470
+ | {
471
+ status: "LoadingFirstPage";
472
+ isLoading: true;
473
+ }
474
+ | {
475
+ status: "CanLoadMore";
476
+ isLoading: false;
477
+ }
478
+ | {
479
+ status: "LoadingMore";
480
+ isLoading: true;
481
+ }
482
+ | {
483
+ status: "Exhausted";
484
+ isLoading: false;
485
+ }
486
+ );
487
+
488
+ /**
489
+ * The possible pagination statuses in {@link UsePaginatedQueryResult}.
490
+ *
491
+ * This is a union of string literal types.
492
+ * @public
493
+ */
494
+ export type PaginationStatus = UsePaginatedQueryResult<any>["status"];
495
+
496
+ /**
497
+ * Given a {@link PaginatedQueryReference}, get the type of the arguments
498
+ * object for the query, excluding the `paginationOpts` argument.
499
+ *
500
+ * @public
501
+ */
502
+ export type PaginatedQueryArgs<Query extends PaginatedQueryReference> = Expand<
503
+ BetterOmit<FunctionArgs<Query>, "paginationOpts">
504
+ >;
505
+
506
+ /**
507
+ * Given a {@link PaginatedQueryReference}, get the type of the item being
508
+ * paginated over.
509
+ * @public
510
+ */
511
+ export type PaginatedQueryItem<Query extends PaginatedQueryReference> =
512
+ FunctionReturnType<Query>["page"][number];
513
+
514
+ /**
515
+ * The return type of {@link usePaginatedQuery}.
516
+ *
517
+ * @public
518
+ */
519
+ export type UsePaginatedQueryReturnType<Query extends PaginatedQueryReference> =
520
+ UsePaginatedQueryResult<PaginatedQueryItem<Query>>;
521
+
522
+ /**
523
+ * Optimistically update the values in a paginated list.
524
+ *
525
+ * This optimistic update is designed to be used to update data loaded with
526
+ * {@link usePaginatedQuery}. It updates the list by applying
527
+ * `updateValue` to each element of the list across all of the loaded pages.
528
+ *
529
+ * This will only apply to queries with a matching names and arguments.
530
+ *
531
+ * Example usage:
532
+ * ```ts
533
+ * const myMutation = useMutation(api.myModule.myMutation)
534
+ * .withOptimisticUpdate((localStore, mutationArg) => {
535
+ *
536
+ * // Optimistically update the document with ID `mutationArg`
537
+ * // to have an additional property.
538
+ *
539
+ * optimisticallyUpdateValueInPaginatedQuery(
540
+ * localStore,
541
+ * api.myModule.paginatedQuery
542
+ * {},
543
+ * currentValue => {
544
+ * if (mutationArg === currentValue._id) {
545
+ * return {
546
+ * ...currentValue,
547
+ * "newProperty": "newValue",
548
+ * };
549
+ * }
550
+ * return currentValue;
551
+ * }
552
+ * );
553
+ *
554
+ * });
555
+ * ```
556
+ *
557
+ * @param localStore - An {@link OptimisticLocalStore} to update.
558
+ * @param query - A {@link FunctionReference} for the paginated query to update.
559
+ * @param args - The arguments object to the query function, excluding the
560
+ * `paginationOpts` property.
561
+ * @param updateValue - A function to produce the new values.
562
+ *
563
+ * @public
564
+ */
565
+ export function optimisticallyUpdateValueInPaginatedQuery<
566
+ Query extends PaginatedQueryReference,
567
+ >(
568
+ localStore: OptimisticLocalStore,
569
+ query: Query,
570
+ args: PaginatedQueryArgs<Query>,
571
+ updateValue: (
572
+ currentValue: PaginatedQueryItem<Query>
573
+ ) => PaginatedQueryItem<Query>
574
+ ): void {
575
+ const expectedArgs = JSON.stringify(convexToJson(args as Value));
576
+
577
+ for (const queryResult of localStore.getAllQueries(query)) {
578
+ if (queryResult.value !== undefined) {
579
+ const { paginationOpts: _, ...innerArgs } = queryResult.args as {
580
+ paginationOpts: PaginationOptions;
581
+ };
582
+ if (JSON.stringify(convexToJson(innerArgs as Value)) === expectedArgs) {
583
+ const value = queryResult.value;
584
+ if (
585
+ typeof value === "object" &&
586
+ value !== null &&
587
+ Array.isArray(value.page)
588
+ ) {
589
+ localStore.setQuery(query, queryResult.args, {
590
+ ...value,
591
+ page: value.page.map(updateValue),
592
+ });
593
+ }
594
+ }
595
+ }
596
+ }
597
+ }
598
+
599
+ /**
600
+ * Updates a paginated query to insert an element at the top of the list.
601
+ *
602
+ * This is regardless of the sort order, so if the list is in descending order,
603
+ * the inserted element will be treated as the "biggest" element, but if it's
604
+ * ascending, it'll be treated as the "smallest".
605
+ *
606
+ * Example:
607
+ * ```ts
608
+ * const createTask = useMutation(api.tasks.create)
609
+ * .withOptimisticUpdate((localStore, mutationArgs) => {
610
+ * insertAtTop({
611
+ * paginatedQuery: api.tasks.list,
612
+ * argsToMatch: { listId: mutationArgs.listId },
613
+ * localQueryStore: localStore,
614
+ * item: { _id: crypto.randomUUID() as Id<"tasks">, title: mutationArgs.title, completed: false },
615
+ * });
616
+ * });
617
+ * ```
618
+ *
619
+ * @param options.paginatedQuery - A function reference to the paginated query.
620
+ * @param options.argsToMatch - Optional arguments that must be in each relevant paginated query.
621
+ * This is useful if you use the same query function with different arguments to load
622
+ * different lists.
623
+ * @param options.localQueryStore
624
+ * @param options.item The item to insert.
625
+ * @returns
626
+ */
627
+ export function insertAtTop<Query extends PaginatedQueryReference>(options: {
628
+ paginatedQuery: Query;
629
+ argsToMatch?: Partial<PaginatedQueryArgs<Query>>;
630
+ localQueryStore: OptimisticLocalStore;
631
+ item: PaginatedQueryItem<Query>;
632
+ }) {
633
+ const { paginatedQuery, argsToMatch, localQueryStore, item } = options;
634
+ const queries = localQueryStore.getAllQueries(paginatedQuery);
635
+ const queriesThatMatch = queries.filter((q) => {
636
+ if (argsToMatch === undefined) {
637
+ return true;
638
+ }
639
+ return Object.keys(argsToMatch).every(
640
+ // @ts-expect-error -- This should be safe since both should be plain objects
641
+ (k) => compareValues(argsToMatch[k], q.args[k]) === 0
642
+ );
643
+ });
644
+ const firstPage = queriesThatMatch.find(
645
+ (q) => q.args.paginationOpts.cursor === null
646
+ );
647
+ if (firstPage === undefined || firstPage.value === undefined) {
648
+ // first page is not loaded, so don't update it until it loads
649
+ return;
650
+ }
651
+ localQueryStore.setQuery(paginatedQuery, firstPage.args, {
652
+ ...firstPage.value,
653
+ page: [item, ...firstPage.value.page],
654
+ });
655
+ }
656
+
657
+ /**
658
+ * Updates a paginated query to insert an element at the bottom of the list.
659
+ *
660
+ * This is regardless of the sort order, so if the list is in descending order,
661
+ * the inserted element will be treated as the "smallest" element, but if it's
662
+ * ascending, it'll be treated as the "biggest".
663
+ *
664
+ * This only has an effect if the last page is loaded, since otherwise it would result
665
+ * in the element being inserted at the end of whatever is loaded (which is the middle of the list)
666
+ * and then popping out once the optimistic update is over.
667
+ *
668
+ * @param options.paginatedQuery - A function reference to the paginated query.
669
+ * @param options.argsToMatch - Optional arguments that must be in each relevant paginated query.
670
+ * This is useful if you use the same query function with different arguments to load
671
+ * different lists.
672
+ * @param options.localQueryStore
673
+ * @param options.element The element to insert.
674
+ * @returns
675
+ */
676
+ export function insertAtBottomIfLoaded<
677
+ Query extends PaginatedQueryReference,
678
+ >(options: {
679
+ paginatedQuery: Query;
680
+ argsToMatch?: Partial<PaginatedQueryArgs<Query>>;
681
+ localQueryStore: OptimisticLocalStore;
682
+ item: PaginatedQueryItem<Query>;
683
+ }) {
684
+ const { paginatedQuery, localQueryStore, item, argsToMatch } = options;
685
+ const queries = localQueryStore.getAllQueries(paginatedQuery);
686
+ const queriesThatMatch = queries.filter((q) => {
687
+ if (argsToMatch === undefined) {
688
+ return true;
689
+ }
690
+ return Object.keys(argsToMatch).every(
691
+ // @ts-expect-error -- This should be safe since both should be plain objects
692
+ (k) => compareValues(argsToMatch[k], q.args[k]) === 0
693
+ );
694
+ });
695
+ const lastPage = queriesThatMatch.find(
696
+ (q) => q.value !== undefined && q.value.isDone
697
+ );
698
+ if (lastPage === undefined) {
699
+ // last page is not loaded, so don't update it since the item would immediately pop out
700
+ // when the server updates
701
+ return;
702
+ }
703
+ localQueryStore.setQuery(paginatedQuery, lastPage.args, {
704
+ ...lastPage.value!,
705
+ page: [...lastPage.value!.page, item],
706
+ });
707
+ }
708
+
709
+ type LocalQueryResult<Query extends FunctionReference<"query">> = {
710
+ args: FunctionArgs<Query>;
711
+ value: undefined | FunctionReturnType<Query>;
712
+ };
713
+
714
+ type LoadedResult<Query extends FunctionReference<"query">> = {
715
+ args: FunctionArgs<Query>;
716
+ value: FunctionReturnType<Query>;
717
+ };
718
+
719
+ /**
720
+ * This is a helper function for inserting an item at a specific position in a paginated query.
721
+ *
722
+ * You must provide the sortOrder and a function for deriving the sort key (an array of values) from an item in the list.
723
+ *
724
+ * This will only work if the server query uses the same sort order and sort key as the optimistic update.
725
+ *
726
+ * Example:
727
+ * ```ts
728
+ * const createTask = useMutation(api.tasks.create)
729
+ * .withOptimisticUpdate((localStore, mutationArgs) => {
730
+ * insertAtPosition({
731
+ * paginatedQuery: api.tasks.listByPriority,
732
+ * argsToMatch: { listId: mutationArgs.listId },
733
+ * sortOrder: "asc",
734
+ * sortKeyFromItem: (item) => [item.priority, item._creationTime],
735
+ * localQueryStore: localStore,
736
+ * item: {
737
+ * _id: crypto.randomUUID() as Id<"tasks">,
738
+ * _creationTime: Date.now(),
739
+ * title: mutationArgs.title,
740
+ * completed: false,
741
+ * priority: mutationArgs.priority,
742
+ * },
743
+ * });
744
+ * });
745
+ * ```
746
+ * @param options.paginatedQuery - A function reference to the paginated query.
747
+ * @param options.argsToMatch - Optional arguments that must be in each relevant paginated query.
748
+ * This is useful if you use the same query function with different arguments to load
749
+ * different lists.
750
+ * @param options.sortOrder - The sort order of the paginated query ("asc" or "desc").
751
+ * @param options.sortKeyFromItem - A function for deriving the sort key (an array of values) from an element in the list.
752
+ * Including a tie-breaker field like `_creationTime` is recommended.
753
+ * @param options.localQueryStore
754
+ * @param options.item - The item to insert.
755
+ * @returns
756
+ */
757
+ export function insertAtPosition<
758
+ Query extends PaginatedQueryReference,
759
+ >(options: {
760
+ paginatedQuery: Query;
761
+ argsToMatch?: Partial<PaginatedQueryArgs<Query>>;
762
+ sortOrder: "asc" | "desc";
763
+ sortKeyFromItem: (element: PaginatedQueryItem<Query>) => Value | Value[];
764
+ localQueryStore: OptimisticLocalStore;
765
+ item: PaginatedQueryItem<Query>;
766
+ }) {
767
+ const {
768
+ paginatedQuery,
769
+ sortOrder,
770
+ sortKeyFromItem,
771
+ localQueryStore,
772
+ item,
773
+ argsToMatch,
774
+ } = options;
775
+
776
+ const queries: LocalQueryResult<Query>[] =
777
+ localQueryStore.getAllQueries(paginatedQuery);
778
+ // Group into sets of pages for the same usePaginatedQuery. Grouping is by all
779
+ // args except paginationOpts, but including paginationOpts.id.
780
+ const queryGroups: Record<string, LocalQueryResult<Query>[]> = {};
781
+ for (const query of queries) {
782
+ if (
783
+ argsToMatch !== undefined &&
784
+ !Object.keys(argsToMatch).every(
785
+ (k) =>
786
+ // @ts-expect-error why is this not working?
787
+ argsToMatch[k] === query.args[k]
788
+ )
789
+ ) {
790
+ continue;
791
+ }
792
+ const key = JSON.stringify(
793
+ Object.fromEntries(
794
+ Object.entries(query.args).map(([k, v]) => [
795
+ k,
796
+ k === "paginationOpts" ? (v as any).id : v,
797
+ ])
798
+ )
799
+ );
800
+ queryGroups[key] ??= [];
801
+ queryGroups[key].push(query);
802
+ }
803
+ for (const pageQueries of Object.values(queryGroups)) {
804
+ insertAtPositionInPages({
805
+ pageQueries,
806
+ paginatedQuery,
807
+ sortOrder,
808
+ sortKeyFromItem,
809
+ localQueryStore,
810
+ item,
811
+ });
812
+ }
813
+ }
814
+
815
+ function insertAtPositionInPages<
816
+ Query extends PaginatedQueryReference,
817
+ >(options: {
818
+ pageQueries: LocalQueryResult<Query>[];
819
+ paginatedQuery: Query;
820
+ sortOrder: "asc" | "desc";
821
+ sortKeyFromItem: (element: PaginatedQueryItem<Query>) => Value | Value[];
822
+ localQueryStore: OptimisticLocalStore;
823
+ item: PaginatedQueryItem<Query>;
824
+ }) {
825
+ const {
826
+ pageQueries,
827
+ sortOrder,
828
+ sortKeyFromItem,
829
+ localQueryStore,
830
+ item,
831
+ paginatedQuery,
832
+ } = options;
833
+ const insertedKey = sortKeyFromItem(item);
834
+ const loadedPages: LoadedResult<Query>[] = pageQueries.filter(
835
+ (q): q is LoadedResult<Query> =>
836
+ q.value !== undefined && q.value.page.length > 0
837
+ );
838
+ const sortedPages = loadedPages.sort((a, b) => {
839
+ const aKey = sortKeyFromItem(a.value.page[0]);
840
+ const bKey = sortKeyFromItem(b.value.page[0]);
841
+ if (sortOrder === "asc") {
842
+ return compareValues(aKey, bKey);
843
+ } else {
844
+ return compareValues(bKey, aKey);
845
+ }
846
+ });
847
+
848
+ // check if the inserted element is before the first page
849
+ const firstLoadedPage = sortedPages[0];
850
+ if (firstLoadedPage === undefined) {
851
+ // no pages, so don't update until they load
852
+ return;
853
+ }
854
+ const firstPageKey = sortKeyFromItem(firstLoadedPage.value.page[0]);
855
+ const isBeforeFirstPage =
856
+ sortOrder === "asc"
857
+ ? compareValues(insertedKey, firstPageKey) <= 0
858
+ : compareValues(insertedKey, firstPageKey) >= 0;
859
+ if (isBeforeFirstPage) {
860
+ if (firstLoadedPage.args.paginationOpts.cursor === null) {
861
+ localQueryStore.setQuery(paginatedQuery, firstLoadedPage.args, {
862
+ ...firstLoadedPage.value,
863
+ page: [item, ...firstLoadedPage.value.page],
864
+ });
865
+ } else {
866
+ // if the very first page is not loaded
867
+ return;
868
+ }
869
+ return;
870
+ }
871
+
872
+ const lastLoadedPage = sortedPages[sortedPages.length - 1];
873
+ if (lastLoadedPage === undefined) {
874
+ // no pages, so don't update until they load
875
+ return;
876
+ }
877
+ const lastPageKey = sortKeyFromItem(
878
+ lastLoadedPage.value.page[lastLoadedPage.value.page.length - 1]
879
+ );
880
+ const isAfterLastPage =
881
+ sortOrder === "asc"
882
+ ? compareValues(insertedKey, lastPageKey) >= 0
883
+ : compareValues(insertedKey, lastPageKey) <= 0;
884
+ if (isAfterLastPage) {
885
+ // Only update if the last page is done loading, otherwise it will pop out
886
+ // when the server updates the query
887
+ if (lastLoadedPage.value.isDone) {
888
+ localQueryStore.setQuery(paginatedQuery, lastLoadedPage.args, {
889
+ ...lastLoadedPage.value,
890
+ page: [...lastLoadedPage.value.page, item],
891
+ });
892
+ }
893
+ return;
894
+ }
895
+
896
+ // if sorted in ascending order, find the first page that starts with a key greater than the inserted element,
897
+ // and update the page before it
898
+ // if sorted in descending order, find the first page that starts with a key less than the inserted element,
899
+ // and update the page before it
900
+
901
+ const successorPageIndex = sortedPages.findIndex((p) =>
902
+ sortOrder === "asc"
903
+ ? compareValues(sortKeyFromItem(p.value.page[0]), insertedKey) > 0
904
+ : compareValues(sortKeyFromItem(p.value.page[0]), insertedKey) < 0
905
+ );
906
+ const pageToUpdate =
907
+ successorPageIndex === -1
908
+ ? sortedPages[sortedPages.length - 1]
909
+ : sortedPages[successorPageIndex - 1];
910
+ if (pageToUpdate === undefined) {
911
+ // no pages, so don't update until they load
912
+ return;
913
+ }
914
+ // If ascending, find the first element that is greater than or equal to the inserted element
915
+ // If descending, find the first element that is less than or equal to the inserted element
916
+ const indexWithinPage = pageToUpdate.value.page.findIndex((e) =>
917
+ sortOrder === "asc"
918
+ ? compareValues(sortKeyFromItem(e), insertedKey) >= 0
919
+ : compareValues(sortKeyFromItem(e), insertedKey) <= 0
920
+ );
921
+ const newPage =
922
+ indexWithinPage === -1
923
+ ? [...pageToUpdate.value.page, item]
924
+ : [
925
+ ...pageToUpdate.value.page.slice(0, indexWithinPage),
926
+ item,
927
+ ...pageToUpdate.value.page.slice(indexWithinPage),
928
+ ];
929
+ localQueryStore.setQuery(paginatedQuery, pageToUpdate.args, {
930
+ ...pageToUpdate.value,
931
+ page: newPage,
932
+ });
933
+ }