@zenstackhq/tanstack-query 3.0.0-beta.34 → 3.1.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 (56) hide show
  1. package/dist/common/client.d.ts +4 -0
  2. package/dist/common/client.js +38 -0
  3. package/dist/common/client.js.map +1 -0
  4. package/dist/common/query-key.d.ts +39 -0
  5. package/dist/common/query-key.js +38 -0
  6. package/dist/common/query-key.js.map +1 -0
  7. package/dist/common/types.d.ts +60 -0
  8. package/dist/common/types.js +2 -0
  9. package/dist/common/types.js.map +1 -0
  10. package/dist/react.d.ts +99 -150
  11. package/dist/react.js +248 -1178
  12. package/dist/react.js.map +1 -1
  13. package/dist/svelte/index.svelte.d.ts +79 -0
  14. package/dist/svelte/index.svelte.js +245 -0
  15. package/dist/vue.d.ts +313 -342
  16. package/dist/vue.js +224 -1138
  17. package/dist/vue.js.map +1 -1
  18. package/package.json +36 -48
  19. package/.turbo/turbo-build.log +0 -47
  20. package/dist/react.cjs +0 -1240
  21. package/dist/react.cjs.map +0 -1
  22. package/dist/react.d.cts +0 -616
  23. package/dist/svelte.cjs +0 -1224
  24. package/dist/svelte.cjs.map +0 -1
  25. package/dist/svelte.d.cts +0 -381
  26. package/dist/svelte.d.ts +0 -381
  27. package/dist/svelte.js +0 -1183
  28. package/dist/svelte.js.map +0 -1
  29. package/dist/types-C8iIZD-7.d.cts +0 -99
  30. package/dist/types-C8iIZD-7.d.ts +0 -99
  31. package/dist/vue.cjs +0 -1192
  32. package/dist/vue.cjs.map +0 -1
  33. package/dist/vue.d.cts +0 -382
  34. package/eslint.config.js +0 -4
  35. package/src/react.ts +0 -562
  36. package/src/svelte.ts +0 -502
  37. package/src/utils/common.ts +0 -448
  38. package/src/utils/mutator.ts +0 -441
  39. package/src/utils/nested-read-visitor.ts +0 -61
  40. package/src/utils/nested-write-visitor.ts +0 -359
  41. package/src/utils/query-analysis.ts +0 -116
  42. package/src/utils/serialization.ts +0 -39
  43. package/src/utils/types.ts +0 -43
  44. package/src/vue.ts +0 -448
  45. package/test/react-query.test.tsx +0 -1787
  46. package/test/react-typing-test.ts +0 -113
  47. package/test/schemas/basic/input.ts +0 -110
  48. package/test/schemas/basic/models.ts +0 -14
  49. package/test/schemas/basic/schema-lite.ts +0 -172
  50. package/test/schemas/basic/schema.zmodel +0 -35
  51. package/test/svelte-typing-test.ts +0 -111
  52. package/test/vue-typing-test.ts +0 -111
  53. package/tsconfig.json +0 -7
  54. package/tsconfig.test.json +0 -8
  55. package/tsup.config.ts +0 -15
  56. package/vitest.config.ts +0 -11
@@ -1,448 +0,0 @@
1
- import { lowerCaseFirst } from '@zenstackhq/common-helpers';
2
- import type { SchemaDef } from '@zenstackhq/schema';
3
- import { applyMutation } from './mutator';
4
- import { getMutatedModels, getReadModels } from './query-analysis';
5
- import { deserialize, serialize } from './serialization';
6
- import type { ORMWriteActionType } from './types';
7
-
8
- /**
9
- * The default query endpoint.
10
- */
11
- export const DEFAULT_QUERY_ENDPOINT = '/api/model';
12
-
13
- /**
14
- * Prefix for react-query keys.
15
- */
16
- export const QUERY_KEY_PREFIX = 'zenstack';
17
-
18
- /**
19
- * Function signature for `fetch`.
20
- */
21
- export type FetchFn = (url: string, options?: RequestInit) => Promise<Response>;
22
-
23
- /**
24
- * Type for query and mutation errors.
25
- */
26
- export type QueryError = Error & {
27
- /**
28
- * Additional error information.
29
- */
30
- info?: unknown;
31
-
32
- /**
33
- * HTTP status code.
34
- */
35
- status?: number;
36
- };
37
-
38
- /**
39
- * Result of optimistic data provider.
40
- */
41
- export type OptimisticDataProviderResult = {
42
- /**
43
- * Kind of the result.
44
- * - Update: use the `data` field to update the query cache.
45
- * - Skip: skip the optimistic update for this query.
46
- * - ProceedDefault: proceed with the default optimistic update.
47
- */
48
- kind: 'Update' | 'Skip' | 'ProceedDefault';
49
-
50
- /**
51
- * Data to update the query cache. Only applicable if `kind` is 'Update'.
52
- *
53
- * If the data is an object with fields updated, it should have a `$optimistic`
54
- * field set to `true`. If it's an array and an element object is created or updated,
55
- * the element should have a `$optimistic` field set to `true`.
56
- */
57
- data?: any;
58
- };
59
-
60
- /**
61
- * Optimistic data provider.
62
- *
63
- * @param args Arguments.
64
- * @param args.queryModel The model of the query.
65
- * @param args.queryOperation The operation of the query, `findMany`, `count`, etc.
66
- * @param args.queryArgs The arguments of the query.
67
- * @param args.currentData The current cache data for the query.
68
- * @param args.mutationArgs The arguments of the mutation.
69
- */
70
- export type OptimisticDataProvider = (args: {
71
- queryModel: string;
72
- queryOperation: string;
73
- queryArgs: any;
74
- currentData: any;
75
- mutationArgs: any;
76
- }) => OptimisticDataProviderResult | Promise<OptimisticDataProviderResult>;
77
-
78
- /**
79
- * Extra mutation options.
80
- */
81
- export type ExtraMutationOptions = {
82
- /**
83
- * Whether to automatically invalidate queries potentially affected by the mutation. Defaults to `true`.
84
- */
85
- invalidateQueries?: boolean;
86
-
87
- /**
88
- * Whether to optimistically update queries potentially affected by the mutation. Defaults to `false`.
89
- */
90
- optimisticUpdate?: boolean;
91
-
92
- /**
93
- * A callback for computing optimistic update data for each query cache entry.
94
- */
95
- optimisticDataProvider?: OptimisticDataProvider;
96
- };
97
-
98
- /**
99
- * Extra query options.
100
- */
101
- export type ExtraQueryOptions = {
102
- /**
103
- * Whether to opt-in to optimistic updates for this query. Defaults to `true`.
104
- */
105
- optimisticUpdate?: boolean;
106
- };
107
-
108
- /**
109
- * Context type for configuring the hooks.
110
- */
111
- export type APIContext = {
112
- /**
113
- * The endpoint to use for the queries.
114
- */
115
- endpoint?: string;
116
-
117
- /**
118
- * A custom fetch function for sending the HTTP requests.
119
- */
120
- fetch?: FetchFn;
121
-
122
- /**
123
- * If logging is enabled.
124
- */
125
- logging?: boolean;
126
- };
127
-
128
- export async function fetcher<R>(url: string, options?: RequestInit, customFetch?: FetchFn): Promise<R> {
129
- const _fetch = customFetch ?? fetch;
130
- const res = await _fetch(url, options);
131
- if (!res.ok) {
132
- const errData = unmarshal(await res.text());
133
- if (errData.error?.rejectedByPolicy && errData.error?.rejectReason === 'cannot-read-back') {
134
- // policy doesn't allow mutation result to be read back, just return undefined
135
- return undefined as any;
136
- }
137
- const error: QueryError = new Error('An error occurred while fetching the data.');
138
- error.info = errData.error;
139
- error.status = res.status;
140
- throw error;
141
- }
142
-
143
- const textResult = await res.text();
144
- try {
145
- return unmarshal(textResult).data as R;
146
- } catch (err) {
147
- console.error(`Unable to deserialize data:`, textResult);
148
- throw err;
149
- }
150
- }
151
-
152
- type QueryKey = [
153
- string /* prefix */,
154
- string /* model */,
155
- string /* operation */,
156
- unknown /* args */,
157
- {
158
- infinite: boolean;
159
- optimisticUpdate: boolean;
160
- } /* flags */,
161
- ];
162
-
163
- /**
164
- * Computes query key for the given model, operation and query args.
165
- * @param model Model name.
166
- * @param operation Query operation (e.g, `findMany`) or request URL. If it's a URL, the last path segment will be used as the operation name.
167
- * @param args Query arguments.
168
- * @param options Query options, including `infinite` indicating if it's an infinite query (defaults to false), and `optimisticUpdate` indicating if optimistic updates are enabled (defaults to true).
169
- * @returns Query key
170
- */
171
- export function getQueryKey(
172
- model: string,
173
- operation: string,
174
- args: unknown,
175
- options: { infinite: boolean; optimisticUpdate: boolean } = { infinite: false, optimisticUpdate: true },
176
- ): QueryKey {
177
- const infinite = options.infinite;
178
- // infinite query doesn't support optimistic updates
179
- const optimisticUpdate = options.infinite ? false : options.optimisticUpdate;
180
- return [QUERY_KEY_PREFIX, model, operation!, args, { infinite, optimisticUpdate }];
181
- }
182
-
183
- export function marshal(value: unknown) {
184
- const { data, meta } = serialize(value);
185
- if (meta) {
186
- return JSON.stringify({ ...(data as any), meta: { serialization: meta } });
187
- } else {
188
- return JSON.stringify(data);
189
- }
190
- }
191
-
192
- export function unmarshal(value: string) {
193
- const parsed = JSON.parse(value);
194
- if (typeof parsed === 'object' && parsed?.data && parsed?.meta?.serialization) {
195
- const deserializedData = deserialize(parsed.data, parsed.meta.serialization);
196
- return { ...parsed, data: deserializedData };
197
- } else {
198
- return parsed;
199
- }
200
- }
201
-
202
- export function makeUrl(endpoint: string, model: string, operation: string, args?: unknown) {
203
- const baseUrl = `${endpoint}/${lowerCaseFirst(model)}/${operation}`;
204
- if (!args) {
205
- return baseUrl;
206
- }
207
-
208
- const { data, meta } = serialize(args);
209
- let result = `${baseUrl}?q=${encodeURIComponent(JSON.stringify(data))}`;
210
- if (meta) {
211
- result += `&meta=${encodeURIComponent(JSON.stringify({ serialization: meta }))}`;
212
- }
213
- return result;
214
- }
215
-
216
- type InvalidationPredicate = ({ queryKey }: { queryKey: readonly unknown[] }) => boolean;
217
- type InvalidateFunc = (predicate: InvalidationPredicate) => Promise<void>;
218
- type MutationOptions = {
219
- onMutate?: (...args: any[]) => any;
220
- onSuccess?: (...args: any[]) => any;
221
- onSettled?: (...args: any[]) => any;
222
- };
223
-
224
- // sets up invalidation hook for a mutation
225
- export function setupInvalidation(
226
- model: string,
227
- operation: string,
228
- schema: SchemaDef,
229
- options: MutationOptions,
230
- invalidate: InvalidateFunc,
231
- logging = false,
232
- ) {
233
- const origOnSuccess = options?.onSuccess;
234
- options.onSuccess = async (...args: unknown[]) => {
235
- const [_, variables] = args;
236
- const predicate = await getInvalidationPredicate(
237
- model,
238
- operation as ORMWriteActionType,
239
- variables,
240
- schema,
241
- logging,
242
- );
243
- await invalidate(predicate);
244
- return origOnSuccess?.(...args);
245
- };
246
- }
247
-
248
- // gets a predicate for evaluating whether a query should be invalidated
249
- async function getInvalidationPredicate(
250
- model: string,
251
- operation: ORMWriteActionType,
252
- mutationArgs: any,
253
- schema: SchemaDef,
254
- logging = false,
255
- ) {
256
- const mutatedModels = await getMutatedModels(model, operation, mutationArgs, schema);
257
-
258
- return ({ queryKey }: { queryKey: readonly unknown[] }) => {
259
- const [_, queryModel, , args] = queryKey as QueryKey;
260
-
261
- if (mutatedModels.includes(queryModel)) {
262
- // direct match
263
- if (logging) {
264
- console.log(`Invalidating query ${JSON.stringify(queryKey)} due to mutation "${model}.${operation}"`);
265
- }
266
- return true;
267
- }
268
-
269
- if (args) {
270
- // traverse query args to find nested reads that match the model under mutation
271
- if (findNestedRead(queryModel, mutatedModels, schema, args)) {
272
- if (logging) {
273
- console.log(
274
- `Invalidating query ${JSON.stringify(queryKey)} due to mutation "${model}.${operation}"`,
275
- );
276
- }
277
- return true;
278
- }
279
- }
280
-
281
- return false;
282
- };
283
- }
284
-
285
- // find nested reads that match the given models
286
- function findNestedRead(visitingModel: string, targetModels: string[], schema: SchemaDef, args: any) {
287
- const modelsRead = getReadModels(visitingModel, schema, args);
288
- return targetModels.some((m) => modelsRead.includes(m));
289
- }
290
-
291
- type QueryCache = {
292
- queryKey: readonly unknown[];
293
- state: {
294
- data: unknown;
295
- error: unknown;
296
- };
297
- }[];
298
-
299
- type SetCacheFunc = (queryKey: readonly unknown[], data: unknown) => void;
300
-
301
- /**
302
- * Sets up optimistic update and invalidation (after settled) for a mutation.
303
- */
304
- export function setupOptimisticUpdate(
305
- model: string,
306
- operation: string,
307
- schema: SchemaDef,
308
- options: MutationOptions & ExtraMutationOptions,
309
- queryCache: QueryCache,
310
- setCache: SetCacheFunc,
311
- invalidate?: InvalidateFunc,
312
- logging = false,
313
- ) {
314
- const origOnMutate = options?.onMutate;
315
- const origOnSettled = options?.onSettled;
316
-
317
- // optimistic update on mutate
318
- options.onMutate = async (...args: unknown[]) => {
319
- const [variables] = args;
320
- await optimisticUpdate(
321
- model,
322
- operation as ORMWriteActionType,
323
- variables,
324
- options,
325
- schema,
326
- queryCache,
327
- setCache,
328
- logging,
329
- );
330
- return origOnMutate?.(...args);
331
- };
332
-
333
- // invalidate on settled
334
- options.onSettled = async (...args: unknown[]) => {
335
- if (invalidate) {
336
- const [, , variables] = args;
337
- const predicate = await getInvalidationPredicate(
338
- model,
339
- operation as ORMWriteActionType,
340
- variables,
341
- schema,
342
- logging,
343
- );
344
- await invalidate(predicate);
345
- }
346
- return origOnSettled?.(...args);
347
- };
348
- }
349
-
350
- // optimistically updates query cache
351
- async function optimisticUpdate(
352
- mutationModel: string,
353
- mutationOp: string,
354
- mutationArgs: any,
355
- options: MutationOptions & ExtraMutationOptions,
356
- schema: SchemaDef,
357
- queryCache: QueryCache,
358
- setCache: SetCacheFunc,
359
- logging = false,
360
- ) {
361
- for (const cacheItem of queryCache) {
362
- const {
363
- queryKey,
364
- state: { data, error },
365
- } = cacheItem;
366
-
367
- if (!isZenStackQueryKey(queryKey)) {
368
- // skip non-zenstack queries
369
- continue;
370
- }
371
-
372
- if (error) {
373
- if (logging) {
374
- console.warn(`Skipping optimistic update for ${JSON.stringify(queryKey)} due to error:`, error);
375
- }
376
- continue;
377
- }
378
-
379
- const [_, queryModel, queryOperation, queryArgs, queryOptions] = queryKey;
380
- if (!queryOptions?.optimisticUpdate) {
381
- if (logging) {
382
- console.log(`Skipping optimistic update for ${JSON.stringify(queryKey)} due to opt-out`);
383
- }
384
- continue;
385
- }
386
-
387
- if (options.optimisticDataProvider) {
388
- const providerResult = await options.optimisticDataProvider({
389
- queryModel,
390
- queryOperation,
391
- queryArgs,
392
- currentData: data,
393
- mutationArgs,
394
- });
395
-
396
- if (providerResult?.kind === 'Skip') {
397
- // skip
398
- if (logging) {
399
- console.log(`Skipping optimistic update for ${JSON.stringify(queryKey)} due to provider`);
400
- }
401
- continue;
402
- } else if (providerResult?.kind === 'Update') {
403
- // update cache
404
- if (logging) {
405
- console.log(`Optimistically updating query ${JSON.stringify(queryKey)} due to provider`);
406
- }
407
- setCache(queryKey, providerResult.data);
408
- continue;
409
- }
410
- }
411
-
412
- // proceed with default optimistic update
413
- const mutatedData = await applyMutation(
414
- queryModel,
415
- queryOperation,
416
- data,
417
- mutationModel,
418
- mutationOp as ORMWriteActionType,
419
- mutationArgs,
420
- schema,
421
- logging,
422
- );
423
-
424
- if (mutatedData !== undefined) {
425
- // mutation applicable to this query, update cache
426
- if (logging) {
427
- console.log(
428
- `Optimistically updating query ${JSON.stringify(
429
- queryKey,
430
- )} due to mutation "${mutationModel}.${mutationOp}"`,
431
- );
432
- }
433
- setCache(queryKey, mutatedData);
434
- }
435
- }
436
- }
437
-
438
- function isZenStackQueryKey(queryKey: readonly unknown[]): queryKey is QueryKey {
439
- if (queryKey.length < 5) {
440
- return false;
441
- }
442
-
443
- if (queryKey[0] !== QUERY_KEY_PREFIX) {
444
- return false;
445
- }
446
-
447
- return true;
448
- }