@zenstackhq/tanstack-query 3.0.0-beta.17 → 3.0.0-beta.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vue.cjs ADDED
@@ -0,0 +1,1192 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/vue.ts
32
+ var vue_exports = {};
33
+ __export(vue_exports, {
34
+ VueQueryContextKey: () => VueQueryContextKey,
35
+ provideHooksContext: () => provideHooksContext,
36
+ provideQuerySettingsContext: () => provideQuerySettingsContext,
37
+ useClientQueries: () => useClientQueries,
38
+ useInternalInfiniteQuery: () => useInternalInfiniteQuery,
39
+ useInternalMutation: () => useInternalMutation,
40
+ useInternalQuery: () => useInternalQuery,
41
+ useModelQueries: () => useModelQueries
42
+ });
43
+ module.exports = __toCommonJS(vue_exports);
44
+ var import_vue_query = require("@tanstack/vue-query");
45
+ var import_common_helpers4 = require("@zenstackhq/common-helpers");
46
+ var import_vue = require("vue");
47
+
48
+ // src/utils/common.ts
49
+ var import_common_helpers3 = require("@zenstackhq/common-helpers");
50
+
51
+ // src/utils/mutator.ts
52
+ var import_common_helpers2 = require("@zenstackhq/common-helpers");
53
+
54
+ // src/utils/nested-write-visitor.ts
55
+ var import_common_helpers = require("@zenstackhq/common-helpers");
56
+
57
+ // src/utils/types.ts
58
+ var ORMWriteActions = [
59
+ "create",
60
+ "createMany",
61
+ "createManyAndReturn",
62
+ "connectOrCreate",
63
+ "update",
64
+ "updateMany",
65
+ "updateManyAndReturn",
66
+ "upsert",
67
+ "connect",
68
+ "disconnect",
69
+ "set",
70
+ "delete",
71
+ "deleteMany"
72
+ ];
73
+
74
+ // src/utils/nested-write-visitor.ts
75
+ var NestedWriteVisitor = class {
76
+ static {
77
+ __name(this, "NestedWriteVisitor");
78
+ }
79
+ schema;
80
+ callback;
81
+ constructor(schema, callback) {
82
+ this.schema = schema;
83
+ this.callback = callback;
84
+ }
85
+ isWriteAction(value) {
86
+ return ORMWriteActions.includes(value);
87
+ }
88
+ /**
89
+ * Start visiting
90
+ *
91
+ * @see NestedWriterVisitorCallback
92
+ */
93
+ async visit(model, action, args) {
94
+ if (!args) {
95
+ return;
96
+ }
97
+ let topData = args;
98
+ switch (action) {
99
+ // create has its data wrapped in 'data' field
100
+ case "create":
101
+ topData = topData.data;
102
+ break;
103
+ case "delete":
104
+ case "deleteMany":
105
+ topData = topData.where;
106
+ break;
107
+ }
108
+ await this.doVisit(model, action, topData, void 0, void 0, []);
109
+ }
110
+ async doVisit(model, action, data, parent, field, nestingPath) {
111
+ if (!data) {
112
+ return;
113
+ }
114
+ const toplevel = field == void 0;
115
+ const context = {
116
+ parent,
117
+ field,
118
+ nestingPath: [
119
+ ...nestingPath
120
+ ]
121
+ };
122
+ const pushNewContext = /* @__PURE__ */ __name((field2, model2, where, unique = false) => {
123
+ return {
124
+ ...context,
125
+ nestingPath: [
126
+ ...context.nestingPath,
127
+ {
128
+ field: field2,
129
+ model: model2,
130
+ where,
131
+ unique
132
+ }
133
+ ]
134
+ };
135
+ }, "pushNewContext");
136
+ switch (action) {
137
+ case "create":
138
+ for (const item of this.enumerateReverse(data)) {
139
+ const newContext = pushNewContext(field, model, {});
140
+ let callbackResult;
141
+ if (this.callback.create) {
142
+ callbackResult = await this.callback.create(model, item, newContext);
143
+ }
144
+ if (callbackResult !== false) {
145
+ const subPayload = typeof callbackResult === "object" ? callbackResult : item;
146
+ await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
147
+ }
148
+ }
149
+ break;
150
+ case "createMany":
151
+ case "createManyAndReturn":
152
+ {
153
+ const newContext = pushNewContext(field, model, {});
154
+ let callbackResult;
155
+ if (this.callback.createMany) {
156
+ callbackResult = await this.callback.createMany(model, data, newContext);
157
+ }
158
+ if (callbackResult !== false) {
159
+ const subPayload = typeof callbackResult === "object" ? callbackResult : data.data;
160
+ await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
161
+ }
162
+ }
163
+ break;
164
+ case "connectOrCreate":
165
+ for (const item of this.enumerateReverse(data)) {
166
+ const newContext = pushNewContext(field, model, item.where);
167
+ let callbackResult;
168
+ if (this.callback.connectOrCreate) {
169
+ callbackResult = await this.callback.connectOrCreate(model, item, newContext);
170
+ }
171
+ if (callbackResult !== false) {
172
+ const subPayload = typeof callbackResult === "object" ? callbackResult : item.create;
173
+ await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
174
+ }
175
+ }
176
+ break;
177
+ case "connect":
178
+ if (this.callback.connect) {
179
+ for (const item of this.enumerateReverse(data)) {
180
+ const newContext = pushNewContext(field, model, item, true);
181
+ await this.callback.connect(model, item, newContext);
182
+ }
183
+ }
184
+ break;
185
+ case "disconnect":
186
+ if (this.callback.disconnect) {
187
+ for (const item of this.enumerateReverse(data)) {
188
+ const newContext = pushNewContext(field, model, item, typeof item === "object");
189
+ await this.callback.disconnect(model, item, newContext);
190
+ }
191
+ }
192
+ break;
193
+ case "set":
194
+ if (this.callback.set) {
195
+ for (const item of this.enumerateReverse(data)) {
196
+ const newContext = pushNewContext(field, model, item, true);
197
+ await this.callback.set(model, item, newContext);
198
+ }
199
+ }
200
+ break;
201
+ case "update":
202
+ for (const item of this.enumerateReverse(data)) {
203
+ const newContext = pushNewContext(field, model, item.where);
204
+ let callbackResult;
205
+ if (this.callback.update) {
206
+ callbackResult = await this.callback.update(model, item, newContext);
207
+ }
208
+ if (callbackResult !== false) {
209
+ const subPayload = typeof callbackResult === "object" ? callbackResult : typeof item.data === "object" ? item.data : item;
210
+ await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
211
+ }
212
+ }
213
+ break;
214
+ case "updateMany":
215
+ case "updateManyAndReturn":
216
+ for (const item of this.enumerateReverse(data)) {
217
+ const newContext = pushNewContext(field, model, item.where);
218
+ let callbackResult;
219
+ if (this.callback.updateMany) {
220
+ callbackResult = await this.callback.updateMany(model, item, newContext);
221
+ }
222
+ if (callbackResult !== false) {
223
+ const subPayload = typeof callbackResult === "object" ? callbackResult : item;
224
+ await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
225
+ }
226
+ }
227
+ break;
228
+ case "upsert": {
229
+ for (const item of this.enumerateReverse(data)) {
230
+ const newContext = pushNewContext(field, model, item.where);
231
+ let callbackResult;
232
+ if (this.callback.upsert) {
233
+ callbackResult = await this.callback.upsert(model, item, newContext);
234
+ }
235
+ if (callbackResult !== false) {
236
+ if (typeof callbackResult === "object") {
237
+ await this.visitSubPayload(model, action, callbackResult, newContext.nestingPath);
238
+ } else {
239
+ await this.visitSubPayload(model, action, item.create, newContext.nestingPath);
240
+ await this.visitSubPayload(model, action, item.update, newContext.nestingPath);
241
+ }
242
+ }
243
+ }
244
+ break;
245
+ }
246
+ case "delete": {
247
+ if (this.callback.delete) {
248
+ for (const item of this.enumerateReverse(data)) {
249
+ const newContext = pushNewContext(field, model, toplevel ? item.where : item);
250
+ await this.callback.delete(model, item, newContext);
251
+ }
252
+ }
253
+ break;
254
+ }
255
+ case "deleteMany":
256
+ if (this.callback.deleteMany) {
257
+ for (const item of this.enumerateReverse(data)) {
258
+ const newContext = pushNewContext(field, model, toplevel ? item.where : item);
259
+ await this.callback.deleteMany(model, item, newContext);
260
+ }
261
+ }
262
+ break;
263
+ default: {
264
+ throw new Error(`unhandled action type ${action}`);
265
+ }
266
+ }
267
+ }
268
+ async visitSubPayload(model, action, payload, nestingPath) {
269
+ for (const item of (0, import_common_helpers.enumerate)(payload)) {
270
+ if (!item || typeof item !== "object") {
271
+ continue;
272
+ }
273
+ for (const field of Object.keys(item)) {
274
+ const fieldDef = this.schema.models[model]?.fields[field];
275
+ if (!fieldDef) {
276
+ continue;
277
+ }
278
+ if (fieldDef.relation) {
279
+ if (item[field]) {
280
+ for (const [subAction, subData] of Object.entries(item[field])) {
281
+ if (this.isWriteAction(subAction) && subData) {
282
+ await this.doVisit(fieldDef.type, subAction, subData, item[field], fieldDef, [
283
+ ...nestingPath
284
+ ]);
285
+ }
286
+ }
287
+ }
288
+ } else {
289
+ if (this.callback.field) {
290
+ await this.callback.field(fieldDef, action, item[field], {
291
+ parent: item,
292
+ nestingPath,
293
+ field: fieldDef
294
+ });
295
+ }
296
+ }
297
+ }
298
+ }
299
+ }
300
+ // enumerate a (possible) array in reverse order, so that the enumeration
301
+ // callback can safely delete the current item
302
+ *enumerateReverse(data) {
303
+ if (Array.isArray(data)) {
304
+ for (let i = data.length - 1; i >= 0; i--) {
305
+ yield data[i];
306
+ }
307
+ } else {
308
+ yield data;
309
+ }
310
+ }
311
+ };
312
+
313
+ // src/utils/mutator.ts
314
+ async function applyMutation(queryModel, queryOp, queryData, mutationModel, mutationOp, mutationArgs, schema, logging) {
315
+ if (!queryData || typeof queryData !== "object" && !Array.isArray(queryData)) {
316
+ return void 0;
317
+ }
318
+ if (!queryOp.startsWith("find")) {
319
+ return void 0;
320
+ }
321
+ return await doApplyMutation(queryModel, queryData, mutationModel, mutationOp, mutationArgs, schema, logging);
322
+ }
323
+ __name(applyMutation, "applyMutation");
324
+ async function doApplyMutation(queryModel, queryData, mutationModel, mutationOp, mutationArgs, schema, logging) {
325
+ let resultData = queryData;
326
+ let updated = false;
327
+ const visitor = new NestedWriteVisitor(schema, {
328
+ create: /* @__PURE__ */ __name((model, args) => {
329
+ if (model === queryModel && Array.isArray(resultData)) {
330
+ const r = createMutate(queryModel, resultData, args, schema, logging);
331
+ if (r) {
332
+ resultData = r;
333
+ updated = true;
334
+ }
335
+ }
336
+ }, "create"),
337
+ createMany: /* @__PURE__ */ __name((model, args) => {
338
+ if (model === queryModel && args?.data && Array.isArray(resultData)) {
339
+ for (const oneArg of (0, import_common_helpers2.enumerate)(args.data)) {
340
+ const r = createMutate(queryModel, resultData, oneArg, schema, logging);
341
+ if (r) {
342
+ resultData = r;
343
+ updated = true;
344
+ }
345
+ }
346
+ }
347
+ }, "createMany"),
348
+ update: /* @__PURE__ */ __name((model, args) => {
349
+ if (model === queryModel && !Array.isArray(resultData)) {
350
+ const r = updateMutate(queryModel, resultData, model, args, schema, logging);
351
+ if (r) {
352
+ resultData = r;
353
+ updated = true;
354
+ }
355
+ }
356
+ }, "update"),
357
+ upsert: /* @__PURE__ */ __name((model, args) => {
358
+ if (model === queryModel && args?.where && args?.create && args?.update) {
359
+ const r = upsertMutate(queryModel, resultData, model, args, schema, logging);
360
+ if (r) {
361
+ resultData = r;
362
+ updated = true;
363
+ }
364
+ }
365
+ }, "upsert"),
366
+ delete: /* @__PURE__ */ __name((model, args) => {
367
+ if (model === queryModel) {
368
+ const r = deleteMutate(queryModel, resultData, model, args, schema, logging);
369
+ if (r) {
370
+ resultData = r;
371
+ updated = true;
372
+ }
373
+ }
374
+ }, "delete")
375
+ });
376
+ await visitor.visit(mutationModel, mutationOp, mutationArgs);
377
+ const modelFields = schema.models[queryModel]?.fields;
378
+ (0, import_common_helpers2.invariant)(modelFields, `Model ${queryModel} not found in schema`);
379
+ if (Array.isArray(resultData)) {
380
+ let arrayCloned = false;
381
+ for (let i = 0; i < resultData.length; i++) {
382
+ const item = resultData[i];
383
+ if (!item || typeof item !== "object" || item.$optimistic) {
384
+ continue;
385
+ }
386
+ const r = await doApplyMutation(queryModel, item, mutationModel, mutationOp, mutationArgs, schema, logging);
387
+ if (r && typeof r === "object") {
388
+ if (!arrayCloned) {
389
+ resultData = [
390
+ ...resultData
391
+ ];
392
+ arrayCloned = true;
393
+ }
394
+ resultData[i] = r;
395
+ updated = true;
396
+ }
397
+ }
398
+ } else if (resultData !== null && typeof resultData === "object") {
399
+ const currentData = {
400
+ ...resultData
401
+ };
402
+ for (const [key, value] of Object.entries(currentData)) {
403
+ const fieldDef = modelFields[key];
404
+ if (!fieldDef?.relation) {
405
+ continue;
406
+ }
407
+ const r = await doApplyMutation(fieldDef.type, value, mutationModel, mutationOp, mutationArgs, schema, logging);
408
+ if (r && typeof r === "object") {
409
+ resultData = {
410
+ ...resultData,
411
+ [key]: r
412
+ };
413
+ updated = true;
414
+ }
415
+ }
416
+ }
417
+ return updated ? resultData : void 0;
418
+ }
419
+ __name(doApplyMutation, "doApplyMutation");
420
+ function createMutate(queryModel, currentData, newData, schema, logging) {
421
+ if (!newData) {
422
+ return void 0;
423
+ }
424
+ const modelFields = schema.models[queryModel]?.fields;
425
+ if (!modelFields) {
426
+ return void 0;
427
+ }
428
+ const insert = {};
429
+ const newDataFields = Object.keys(newData);
430
+ Object.entries(modelFields).forEach(([name, field]) => {
431
+ if (field.relation && newData[name]) {
432
+ assignForeignKeyFields(field, insert, newData[name]);
433
+ return;
434
+ }
435
+ if (newDataFields.includes(name)) {
436
+ insert[name] = (0, import_common_helpers2.clone)(newData[name]);
437
+ } else {
438
+ const defaultAttr = field.attributes?.find((attr) => attr.name === "@default");
439
+ if (field.type === "DateTime") {
440
+ if (defaultAttr || field.attributes?.some((attr) => attr.name === "@updatedAt")) {
441
+ insert[name] = /* @__PURE__ */ new Date();
442
+ return;
443
+ }
444
+ }
445
+ const defaultArg = defaultAttr?.args?.[0]?.value;
446
+ if (defaultArg?.kind === "literal") {
447
+ insert[name] = defaultArg.value;
448
+ }
449
+ }
450
+ });
451
+ const idFields = getIdFields(schema, queryModel);
452
+ idFields.forEach((f) => {
453
+ if (insert[f.name] === void 0) {
454
+ if (f.type === "Int" || f.type === "BigInt") {
455
+ const currMax = Array.isArray(currentData) ? Math.max(...[
456
+ ...currentData
457
+ ].map((item) => {
458
+ const idv = parseInt(item[f.name]);
459
+ return isNaN(idv) ? 0 : idv;
460
+ })) : 0;
461
+ insert[f.name] = currMax + 1;
462
+ } else {
463
+ insert[f.name] = crypto.randomUUID();
464
+ }
465
+ }
466
+ });
467
+ insert.$optimistic = true;
468
+ if (logging) {
469
+ console.log(`Optimistic create for ${queryModel}:`, insert);
470
+ }
471
+ return [
472
+ insert,
473
+ ...Array.isArray(currentData) ? currentData : []
474
+ ];
475
+ }
476
+ __name(createMutate, "createMutate");
477
+ function updateMutate(queryModel, currentData, mutateModel, mutateArgs, schema, logging) {
478
+ if (!currentData || typeof currentData !== "object") {
479
+ return void 0;
480
+ }
481
+ if (!mutateArgs?.where || typeof mutateArgs.where !== "object") {
482
+ return void 0;
483
+ }
484
+ if (!mutateArgs?.data || typeof mutateArgs.data !== "object") {
485
+ return void 0;
486
+ }
487
+ if (!idFieldsMatch(mutateModel, currentData, mutateArgs.where, schema)) {
488
+ return void 0;
489
+ }
490
+ const modelFields = schema.models[queryModel]?.fields;
491
+ if (!modelFields) {
492
+ return void 0;
493
+ }
494
+ let updated = false;
495
+ let resultData = currentData;
496
+ for (const [key, value] of Object.entries(mutateArgs.data)) {
497
+ const fieldInfo = modelFields[key];
498
+ if (!fieldInfo) {
499
+ continue;
500
+ }
501
+ if (fieldInfo.relation && !value?.connect) {
502
+ continue;
503
+ }
504
+ if (!updated) {
505
+ resultData = {
506
+ ...currentData
507
+ };
508
+ }
509
+ if (fieldInfo.relation) {
510
+ assignForeignKeyFields(fieldInfo, resultData, value);
511
+ } else {
512
+ resultData[key] = (0, import_common_helpers2.clone)(value);
513
+ }
514
+ resultData.$optimistic = true;
515
+ updated = true;
516
+ if (logging) {
517
+ console.log(`Optimistic update for ${queryModel}:`, resultData);
518
+ }
519
+ }
520
+ return updated ? resultData : void 0;
521
+ }
522
+ __name(updateMutate, "updateMutate");
523
+ function upsertMutate(queryModel, currentData, model, args, schema, logging) {
524
+ let updated = false;
525
+ let resultData = currentData;
526
+ if (Array.isArray(resultData)) {
527
+ const foundIndex = resultData.findIndex((x) => idFieldsMatch(model, x, args.where, schema));
528
+ if (foundIndex >= 0) {
529
+ const updateResult = updateMutate(queryModel, resultData[foundIndex], model, {
530
+ where: args.where,
531
+ data: args.update
532
+ }, schema, logging);
533
+ if (updateResult) {
534
+ resultData = [
535
+ ...resultData.slice(0, foundIndex),
536
+ updateResult,
537
+ ...resultData.slice(foundIndex + 1)
538
+ ];
539
+ updated = true;
540
+ }
541
+ } else {
542
+ const createResult = createMutate(queryModel, resultData, args.create, schema, logging);
543
+ if (createResult) {
544
+ resultData = createResult;
545
+ updated = true;
546
+ }
547
+ }
548
+ } else {
549
+ const updateResult = updateMutate(queryModel, resultData, model, {
550
+ where: args.where,
551
+ data: args.update
552
+ }, schema, logging);
553
+ if (updateResult) {
554
+ resultData = updateResult;
555
+ updated = true;
556
+ }
557
+ }
558
+ return updated ? resultData : void 0;
559
+ }
560
+ __name(upsertMutate, "upsertMutate");
561
+ function deleteMutate(queryModel, currentData, mutateModel, mutateArgs, schema, logging) {
562
+ if (!currentData || !mutateArgs) {
563
+ return void 0;
564
+ }
565
+ if (queryModel !== mutateModel) {
566
+ return void 0;
567
+ }
568
+ let updated = false;
569
+ let result = currentData;
570
+ if (Array.isArray(currentData)) {
571
+ for (const item of currentData) {
572
+ if (idFieldsMatch(mutateModel, item, mutateArgs, schema)) {
573
+ result = result.filter((x) => x !== item);
574
+ updated = true;
575
+ if (logging) {
576
+ console.log(`Optimistic delete for ${queryModel}:`, item);
577
+ }
578
+ }
579
+ }
580
+ } else {
581
+ if (idFieldsMatch(mutateModel, currentData, mutateArgs, schema)) {
582
+ result = null;
583
+ updated = true;
584
+ if (logging) {
585
+ console.log(`Optimistic delete for ${queryModel}:`, currentData);
586
+ }
587
+ }
588
+ }
589
+ return updated ? result : void 0;
590
+ }
591
+ __name(deleteMutate, "deleteMutate");
592
+ function idFieldsMatch(model, x, y, schema) {
593
+ if (!x || !y || typeof x !== "object" || typeof y !== "object") {
594
+ return false;
595
+ }
596
+ const idFields = getIdFields(schema, model);
597
+ if (idFields.length === 0) {
598
+ return false;
599
+ }
600
+ return idFields.every((f) => x[f.name] === y[f.name]);
601
+ }
602
+ __name(idFieldsMatch, "idFieldsMatch");
603
+ function assignForeignKeyFields(field, resultData, mutationData) {
604
+ if (!mutationData?.connect) {
605
+ return;
606
+ }
607
+ if (!field.relation?.fields || !field.relation.references) {
608
+ return;
609
+ }
610
+ for (const [idField, fkField] of (0, import_common_helpers2.zip)(field.relation.references, field.relation.fields)) {
611
+ if (idField in mutationData.connect) {
612
+ resultData[fkField] = mutationData.connect[idField];
613
+ }
614
+ }
615
+ }
616
+ __name(assignForeignKeyFields, "assignForeignKeyFields");
617
+ function getIdFields(schema, model) {
618
+ return (schema.models[model]?.idFields ?? []).map((f) => schema.models[model].fields[f]);
619
+ }
620
+ __name(getIdFields, "getIdFields");
621
+
622
+ // src/utils/nested-read-visitor.ts
623
+ var NestedReadVisitor = class {
624
+ static {
625
+ __name(this, "NestedReadVisitor");
626
+ }
627
+ schema;
628
+ callback;
629
+ constructor(schema, callback) {
630
+ this.schema = schema;
631
+ this.callback = callback;
632
+ }
633
+ doVisit(model, field, kind, args) {
634
+ if (this.callback.field) {
635
+ const r = this.callback.field(model, field, kind, args);
636
+ if (r === false) {
637
+ return;
638
+ }
639
+ }
640
+ if (!args || typeof args !== "object") {
641
+ return;
642
+ }
643
+ let selectInclude;
644
+ let nextKind;
645
+ if (args.select) {
646
+ selectInclude = args.select;
647
+ nextKind = "select";
648
+ } else if (args.include) {
649
+ selectInclude = args.include;
650
+ nextKind = "include";
651
+ }
652
+ if (selectInclude && typeof selectInclude === "object") {
653
+ for (const [k, v] of Object.entries(selectInclude)) {
654
+ if (k === "_count" && typeof v === "object" && v) {
655
+ this.doVisit(model, field, kind, v);
656
+ } else {
657
+ const field2 = this.schema.models[model]?.fields[k];
658
+ if (field2) {
659
+ this.doVisit(field2.type, field2, nextKind, v);
660
+ }
661
+ }
662
+ }
663
+ }
664
+ }
665
+ visit(model, args) {
666
+ this.doVisit(model, void 0, void 0, args);
667
+ }
668
+ };
669
+
670
+ // src/utils/query-analysis.ts
671
+ function getReadModels(model, schema, args) {
672
+ const result = /* @__PURE__ */ new Set();
673
+ result.add(model);
674
+ const visitor = new NestedReadVisitor(schema, {
675
+ field: /* @__PURE__ */ __name((model2) => {
676
+ result.add(model2);
677
+ return true;
678
+ }, "field")
679
+ });
680
+ visitor.visit(model, args);
681
+ return [
682
+ ...result
683
+ ];
684
+ }
685
+ __name(getReadModels, "getReadModels");
686
+ async function getMutatedModels(model, operation, mutationArgs, schema) {
687
+ const result = /* @__PURE__ */ new Set();
688
+ result.add(model);
689
+ if (mutationArgs) {
690
+ const addModel = /* @__PURE__ */ __name((model2) => void result.add(model2), "addModel");
691
+ const addCascades = /* @__PURE__ */ __name((model2) => {
692
+ const cascades = /* @__PURE__ */ new Set();
693
+ const visited = /* @__PURE__ */ new Set();
694
+ collectDeleteCascades(model2, schema, cascades, visited);
695
+ cascades.forEach((m) => addModel(m));
696
+ }, "addCascades");
697
+ const visitor = new NestedWriteVisitor(schema, {
698
+ create: addModel,
699
+ createMany: addModel,
700
+ connectOrCreate: addModel,
701
+ connect: addModel,
702
+ disconnect: addModel,
703
+ set: addModel,
704
+ update: addModel,
705
+ updateMany: addModel,
706
+ upsert: addModel,
707
+ delete: /* @__PURE__ */ __name((model2) => {
708
+ addModel(model2);
709
+ addCascades(model2);
710
+ }, "delete"),
711
+ deleteMany: /* @__PURE__ */ __name((model2) => {
712
+ addModel(model2);
713
+ addCascades(model2);
714
+ }, "deleteMany")
715
+ });
716
+ await visitor.visit(model, operation, mutationArgs);
717
+ }
718
+ result.forEach((m) => {
719
+ getBaseRecursively(m, schema, result);
720
+ });
721
+ return [
722
+ ...result
723
+ ];
724
+ }
725
+ __name(getMutatedModels, "getMutatedModels");
726
+ function collectDeleteCascades(model, schema, result, visited) {
727
+ if (visited.has(model)) {
728
+ return;
729
+ }
730
+ visited.add(model);
731
+ const modelDef = schema.models[model];
732
+ if (!modelDef) {
733
+ return;
734
+ }
735
+ for (const [modelName, modelDef2] of Object.entries(schema.models)) {
736
+ if (!modelDef2) {
737
+ continue;
738
+ }
739
+ for (const fieldDef of Object.values(modelDef2.fields)) {
740
+ if (fieldDef.relation?.onDelete === "Cascade" && fieldDef.type === model) {
741
+ if (!result.has(modelName)) {
742
+ result.add(modelName);
743
+ }
744
+ collectDeleteCascades(modelName, schema, result, visited);
745
+ }
746
+ }
747
+ }
748
+ }
749
+ __name(collectDeleteCascades, "collectDeleteCascades");
750
+ function getBaseRecursively(model, schema, result) {
751
+ const modelDef = schema.models[model];
752
+ if (!modelDef) {
753
+ return;
754
+ }
755
+ if (modelDef.baseModel) {
756
+ result.add(modelDef.baseModel);
757
+ getBaseRecursively(modelDef.baseModel, schema, result);
758
+ }
759
+ }
760
+ __name(getBaseRecursively, "getBaseRecursively");
761
+
762
+ // src/utils/serialization.ts
763
+ var import_buffer = require("buffer");
764
+ var import_decimal = __toESM(require("decimal.js"), 1);
765
+ var import_superjson = __toESM(require("superjson"), 1);
766
+ import_superjson.default.registerCustom({
767
+ isApplicable: /* @__PURE__ */ __name((v) => v instanceof import_decimal.default || // interop with decimal.js
768
+ v?.toStringTag === "[object Decimal]", "isApplicable"),
769
+ serialize: /* @__PURE__ */ __name((v) => v.toJSON(), "serialize"),
770
+ deserialize: /* @__PURE__ */ __name((v) => new import_decimal.default(v), "deserialize")
771
+ }, "Decimal");
772
+ import_superjson.default.registerCustom({
773
+ isApplicable: /* @__PURE__ */ __name((v) => import_buffer.Buffer.isBuffer(v), "isApplicable"),
774
+ serialize: /* @__PURE__ */ __name((v) => v.toString("base64"), "serialize"),
775
+ deserialize: /* @__PURE__ */ __name((v) => import_buffer.Buffer.from(v, "base64"), "deserialize")
776
+ }, "Bytes");
777
+ function serialize(value) {
778
+ const { json, meta } = import_superjson.default.serialize(value);
779
+ return {
780
+ data: json,
781
+ meta
782
+ };
783
+ }
784
+ __name(serialize, "serialize");
785
+ function deserialize(value, meta) {
786
+ return import_superjson.default.deserialize({
787
+ json: value,
788
+ meta
789
+ });
790
+ }
791
+ __name(deserialize, "deserialize");
792
+
793
+ // src/utils/common.ts
794
+ var DEFAULT_QUERY_ENDPOINT = "/api/model";
795
+ var QUERY_KEY_PREFIX = "zenstack";
796
+ async function fetcher(url, options, customFetch) {
797
+ const _fetch = customFetch ?? fetch;
798
+ const res = await _fetch(url, options);
799
+ if (!res.ok) {
800
+ const errData = unmarshal(await res.text());
801
+ if (errData.error?.rejectedByPolicy && errData.error?.rejectReason === "cannot-read-back") {
802
+ return void 0;
803
+ }
804
+ const error = new Error("An error occurred while fetching the data.");
805
+ error.info = errData.error;
806
+ error.status = res.status;
807
+ throw error;
808
+ }
809
+ const textResult = await res.text();
810
+ try {
811
+ return unmarshal(textResult).data;
812
+ } catch (err) {
813
+ console.error(`Unable to deserialize data:`, textResult);
814
+ throw err;
815
+ }
816
+ }
817
+ __name(fetcher, "fetcher");
818
+ function getQueryKey(model, operation, args, options = {
819
+ infinite: false,
820
+ optimisticUpdate: true
821
+ }) {
822
+ const infinite = options.infinite;
823
+ const optimisticUpdate2 = options.infinite ? false : options.optimisticUpdate;
824
+ return [
825
+ QUERY_KEY_PREFIX,
826
+ model,
827
+ operation,
828
+ args,
829
+ {
830
+ infinite,
831
+ optimisticUpdate: optimisticUpdate2
832
+ }
833
+ ];
834
+ }
835
+ __name(getQueryKey, "getQueryKey");
836
+ function marshal(value) {
837
+ const { data, meta } = serialize(value);
838
+ if (meta) {
839
+ return JSON.stringify({
840
+ ...data,
841
+ meta: {
842
+ serialization: meta
843
+ }
844
+ });
845
+ } else {
846
+ return JSON.stringify(data);
847
+ }
848
+ }
849
+ __name(marshal, "marshal");
850
+ function unmarshal(value) {
851
+ const parsed = JSON.parse(value);
852
+ if (typeof parsed === "object" && parsed?.data && parsed?.meta?.serialization) {
853
+ const deserializedData = deserialize(parsed.data, parsed.meta.serialization);
854
+ return {
855
+ ...parsed,
856
+ data: deserializedData
857
+ };
858
+ } else {
859
+ return parsed;
860
+ }
861
+ }
862
+ __name(unmarshal, "unmarshal");
863
+ function makeUrl(endpoint, model, operation, args) {
864
+ const baseUrl = `${endpoint}/${(0, import_common_helpers3.lowerCaseFirst)(model)}/${operation}`;
865
+ if (!args) {
866
+ return baseUrl;
867
+ }
868
+ const { data, meta } = serialize(args);
869
+ let result = `${baseUrl}?q=${encodeURIComponent(JSON.stringify(data))}`;
870
+ if (meta) {
871
+ result += `&meta=${encodeURIComponent(JSON.stringify({
872
+ serialization: meta
873
+ }))}`;
874
+ }
875
+ return result;
876
+ }
877
+ __name(makeUrl, "makeUrl");
878
+ function setupInvalidation(model, operation, schema, options, invalidate, logging = false) {
879
+ const origOnSuccess = options?.onSuccess;
880
+ options.onSuccess = async (...args) => {
881
+ const [_, variables] = args;
882
+ const predicate = await getInvalidationPredicate(model, operation, variables, schema, logging);
883
+ await invalidate(predicate);
884
+ return origOnSuccess?.(...args);
885
+ };
886
+ }
887
+ __name(setupInvalidation, "setupInvalidation");
888
+ async function getInvalidationPredicate(model, operation, mutationArgs, schema, logging = false) {
889
+ const mutatedModels = await getMutatedModels(model, operation, mutationArgs, schema);
890
+ return ({ queryKey }) => {
891
+ const [_, queryModel, , args] = queryKey;
892
+ if (mutatedModels.includes(queryModel)) {
893
+ if (logging) {
894
+ console.log(`Invalidating query ${JSON.stringify(queryKey)} due to mutation "${model}.${operation}"`);
895
+ }
896
+ return true;
897
+ }
898
+ if (args) {
899
+ if (findNestedRead(queryModel, mutatedModels, schema, args)) {
900
+ if (logging) {
901
+ console.log(`Invalidating query ${JSON.stringify(queryKey)} due to mutation "${model}.${operation}"`);
902
+ }
903
+ return true;
904
+ }
905
+ }
906
+ return false;
907
+ };
908
+ }
909
+ __name(getInvalidationPredicate, "getInvalidationPredicate");
910
+ function findNestedRead(visitingModel, targetModels, schema, args) {
911
+ const modelsRead = getReadModels(visitingModel, schema, args);
912
+ return targetModels.some((m) => modelsRead.includes(m));
913
+ }
914
+ __name(findNestedRead, "findNestedRead");
915
+ function setupOptimisticUpdate(model, operation, schema, options, queryCache, setCache, invalidate, logging = false) {
916
+ const origOnMutate = options?.onMutate;
917
+ const origOnSettled = options?.onSettled;
918
+ options.onMutate = async (...args) => {
919
+ const [variables] = args;
920
+ await optimisticUpdate(model, operation, variables, options, schema, queryCache, setCache, logging);
921
+ return origOnMutate?.(...args);
922
+ };
923
+ options.onSettled = async (...args) => {
924
+ if (invalidate) {
925
+ const [, , variables] = args;
926
+ const predicate = await getInvalidationPredicate(model, operation, variables, schema, logging);
927
+ await invalidate(predicate);
928
+ }
929
+ return origOnSettled?.(...args);
930
+ };
931
+ }
932
+ __name(setupOptimisticUpdate, "setupOptimisticUpdate");
933
+ async function optimisticUpdate(mutationModel, mutationOp, mutationArgs, options, schema, queryCache, setCache, logging = false) {
934
+ for (const cacheItem of queryCache) {
935
+ const { queryKey, state: { data, error } } = cacheItem;
936
+ if (!isZenStackQueryKey(queryKey)) {
937
+ continue;
938
+ }
939
+ if (error) {
940
+ if (logging) {
941
+ console.warn(`Skipping optimistic update for ${JSON.stringify(queryKey)} due to error:`, error);
942
+ }
943
+ continue;
944
+ }
945
+ const [_, queryModel, queryOperation, queryArgs, queryOptions] = queryKey;
946
+ if (!queryOptions?.optimisticUpdate) {
947
+ if (logging) {
948
+ console.log(`Skipping optimistic update for ${JSON.stringify(queryKey)} due to opt-out`);
949
+ }
950
+ continue;
951
+ }
952
+ if (options.optimisticDataProvider) {
953
+ const providerResult = await options.optimisticDataProvider({
954
+ queryModel,
955
+ queryOperation,
956
+ queryArgs,
957
+ currentData: data,
958
+ mutationArgs
959
+ });
960
+ if (providerResult?.kind === "Skip") {
961
+ if (logging) {
962
+ console.log(`Skipping optimistic update for ${JSON.stringify(queryKey)} due to provider`);
963
+ }
964
+ continue;
965
+ } else if (providerResult?.kind === "Update") {
966
+ if (logging) {
967
+ console.log(`Optimistically updating query ${JSON.stringify(queryKey)} due to provider`);
968
+ }
969
+ setCache(queryKey, providerResult.data);
970
+ continue;
971
+ }
972
+ }
973
+ const mutatedData = await applyMutation(queryModel, queryOperation, data, mutationModel, mutationOp, mutationArgs, schema, logging);
974
+ if (mutatedData !== void 0) {
975
+ if (logging) {
976
+ console.log(`Optimistically updating query ${JSON.stringify(queryKey)} due to mutation "${mutationModel}.${mutationOp}"`);
977
+ }
978
+ setCache(queryKey, mutatedData);
979
+ }
980
+ }
981
+ }
982
+ __name(optimisticUpdate, "optimisticUpdate");
983
+ function isZenStackQueryKey(queryKey) {
984
+ if (queryKey.length < 5) {
985
+ return false;
986
+ }
987
+ if (queryKey[0] !== QUERY_KEY_PREFIX) {
988
+ return false;
989
+ }
990
+ return true;
991
+ }
992
+ __name(isZenStackQueryKey, "isZenStackQueryKey");
993
+
994
+ // src/vue.ts
995
+ var VueQueryContextKey = "zenstack-vue-query-context";
996
+ function provideHooksContext(context) {
997
+ (0, import_vue.provide)(VueQueryContextKey, context);
998
+ }
999
+ __name(provideHooksContext, "provideHooksContext");
1000
+ function provideQuerySettingsContext(context) {
1001
+ (0, import_vue.provide)(VueQueryContextKey, context);
1002
+ }
1003
+ __name(provideQuerySettingsContext, "provideQuerySettingsContext");
1004
+ function getQuerySettings() {
1005
+ const { endpoint, ...rest } = (0, import_vue.inject)(VueQueryContextKey, {
1006
+ endpoint: DEFAULT_QUERY_ENDPOINT,
1007
+ fetch: void 0,
1008
+ logging: false
1009
+ });
1010
+ return {
1011
+ endpoint: endpoint ?? DEFAULT_QUERY_ENDPOINT,
1012
+ ...rest
1013
+ };
1014
+ }
1015
+ __name(getQuerySettings, "getQuerySettings");
1016
+ function useClientQueries(schema) {
1017
+ return Object.keys(schema.models).reduce((acc, model) => {
1018
+ acc[(0, import_common_helpers4.lowerCaseFirst)(model)] = useModelQueries(schema, model);
1019
+ return acc;
1020
+ }, {});
1021
+ }
1022
+ __name(useClientQueries, "useClientQueries");
1023
+ function useModelQueries(schema, model) {
1024
+ const modelDef = Object.values(schema.models).find((m) => m.name.toLowerCase() === model.toLowerCase());
1025
+ if (!modelDef) {
1026
+ throw new Error(`Model "${model}" not found in schema`);
1027
+ }
1028
+ const modelName = modelDef.name;
1029
+ return {
1030
+ useFindUnique: /* @__PURE__ */ __name((args, options) => {
1031
+ return useInternalQuery(schema, modelName, "findUnique", args, options);
1032
+ }, "useFindUnique"),
1033
+ useFindFirst: /* @__PURE__ */ __name((args, options) => {
1034
+ return useInternalQuery(schema, modelName, "findFirst", args, options);
1035
+ }, "useFindFirst"),
1036
+ useFindMany: /* @__PURE__ */ __name((args, options) => {
1037
+ return useInternalQuery(schema, modelName, "findMany", args, options);
1038
+ }, "useFindMany"),
1039
+ useInfiniteFindMany: /* @__PURE__ */ __name((args, options) => {
1040
+ return useInternalInfiniteQuery(schema, modelName, "findMany", args, options);
1041
+ }, "useInfiniteFindMany"),
1042
+ useCreate: /* @__PURE__ */ __name((options) => {
1043
+ return useInternalMutation(schema, modelName, "POST", "create", options);
1044
+ }, "useCreate"),
1045
+ useCreateMany: /* @__PURE__ */ __name((options) => {
1046
+ return useInternalMutation(schema, modelName, "POST", "createMany", options);
1047
+ }, "useCreateMany"),
1048
+ useCreateManyAndReturn: /* @__PURE__ */ __name((options) => {
1049
+ return useInternalMutation(schema, modelName, "POST", "createManyAndReturn", options);
1050
+ }, "useCreateManyAndReturn"),
1051
+ useUpdate: /* @__PURE__ */ __name((options) => {
1052
+ return useInternalMutation(schema, modelName, "PUT", "update", options);
1053
+ }, "useUpdate"),
1054
+ useUpdateMany: /* @__PURE__ */ __name((options) => {
1055
+ return useInternalMutation(schema, modelName, "PUT", "updateMany", options);
1056
+ }, "useUpdateMany"),
1057
+ useUpdateManyAndReturn: /* @__PURE__ */ __name((options) => {
1058
+ return useInternalMutation(schema, modelName, "PUT", "updateManyAndReturn", options);
1059
+ }, "useUpdateManyAndReturn"),
1060
+ useUpsert: /* @__PURE__ */ __name((options) => {
1061
+ return useInternalMutation(schema, modelName, "POST", "upsert", options);
1062
+ }, "useUpsert"),
1063
+ useDelete: /* @__PURE__ */ __name((options) => {
1064
+ return useInternalMutation(schema, modelName, "DELETE", "delete", options);
1065
+ }, "useDelete"),
1066
+ useDeleteMany: /* @__PURE__ */ __name((options) => {
1067
+ return useInternalMutation(schema, modelName, "DELETE", "deleteMany", options);
1068
+ }, "useDeleteMany"),
1069
+ useCount: /* @__PURE__ */ __name((args, options) => {
1070
+ return useInternalQuery(schema, modelName, "count", args, options);
1071
+ }, "useCount"),
1072
+ useAggregate: /* @__PURE__ */ __name((args, options) => {
1073
+ return useInternalQuery(schema, modelName, "aggregate", args, options);
1074
+ }, "useAggregate"),
1075
+ useGroupBy: /* @__PURE__ */ __name((args, options) => {
1076
+ return useInternalQuery(schema, modelName, "groupBy", args, options);
1077
+ }, "useGroupBy")
1078
+ };
1079
+ }
1080
+ __name(useModelQueries, "useModelQueries");
1081
+ function useInternalQuery(_schema, model, operation, args, options) {
1082
+ const argsValue = (0, import_vue.toValue)(args);
1083
+ const { optimisticUpdate: optimisticUpdate2, ...restOptions } = (0, import_vue.toValue)(options) ?? {};
1084
+ const queryKey = getQueryKey(model, operation, argsValue, {
1085
+ infinite: false,
1086
+ optimisticUpdate: optimisticUpdate2 !== false
1087
+ });
1088
+ const { endpoint, fetch: fetch2 } = getQuerySettings();
1089
+ const finalOptions = {
1090
+ queryKey,
1091
+ queryFn: /* @__PURE__ */ __name(({ queryKey: queryKey2, signal }) => {
1092
+ const [_prefix, _model, _op, args2] = queryKey2;
1093
+ const reqUrl = makeUrl(endpoint, model, operation, args2);
1094
+ return fetcher(reqUrl, {
1095
+ signal
1096
+ }, fetch2);
1097
+ }, "queryFn"),
1098
+ ...restOptions
1099
+ };
1100
+ return {
1101
+ queryKey,
1102
+ ...(0, import_vue_query.useQuery)(finalOptions)
1103
+ };
1104
+ }
1105
+ __name(useInternalQuery, "useInternalQuery");
1106
+ function useInternalInfiniteQuery(_schema, model, operation, args, options) {
1107
+ options = options ?? {
1108
+ getNextPageParam: /* @__PURE__ */ __name(() => void 0, "getNextPageParam")
1109
+ };
1110
+ const { endpoint, fetch: fetch2 } = getQuerySettings();
1111
+ const argsValue = (0, import_vue.toValue)(args);
1112
+ const optionsValue = (0, import_vue.toValue)(options);
1113
+ const queryKey = getQueryKey(model, operation, argsValue, {
1114
+ infinite: true,
1115
+ optimisticUpdate: false
1116
+ });
1117
+ const finalOptions = {
1118
+ queryKey,
1119
+ queryFn: /* @__PURE__ */ __name(({ queryKey: queryKey2, signal }) => {
1120
+ const [_prefix, _model, _op, args2] = queryKey2;
1121
+ const reqUrl = makeUrl(endpoint, model, operation, args2);
1122
+ return fetcher(reqUrl, {
1123
+ signal
1124
+ }, fetch2);
1125
+ }, "queryFn"),
1126
+ initialPageParam: argsValue,
1127
+ ...optionsValue
1128
+ };
1129
+ return {
1130
+ queryKey,
1131
+ ...(0, import_vue_query.useInfiniteQuery)(finalOptions)
1132
+ };
1133
+ }
1134
+ __name(useInternalInfiniteQuery, "useInternalInfiniteQuery");
1135
+ function useInternalMutation(schema, model, method, operation, options) {
1136
+ const { endpoint, fetch: fetch2, logging } = getQuerySettings();
1137
+ const queryClient = (0, import_vue_query.useQueryClient)();
1138
+ const mutationFn = /* @__PURE__ */ __name((data) => {
1139
+ const reqUrl = method === "DELETE" ? makeUrl(endpoint, model, operation, data) : makeUrl(endpoint, model, operation);
1140
+ const fetchInit = {
1141
+ method,
1142
+ ...method !== "DELETE" && {
1143
+ headers: {
1144
+ "content-type": "application/json"
1145
+ },
1146
+ body: marshal(data)
1147
+ }
1148
+ };
1149
+ return fetcher(reqUrl, fetchInit, fetch2);
1150
+ }, "mutationFn");
1151
+ const optionsValue = (0, import_vue.toValue)(options);
1152
+ const finalOptions = {
1153
+ ...optionsValue,
1154
+ mutationFn
1155
+ };
1156
+ const invalidateQueries = optionsValue?.invalidateQueries !== false;
1157
+ const optimisticUpdate2 = !!optionsValue?.optimisticUpdate;
1158
+ if (operation) {
1159
+ if (invalidateQueries) {
1160
+ setupInvalidation(model, operation, schema, finalOptions, (predicate) => queryClient.invalidateQueries({
1161
+ predicate
1162
+ }), logging);
1163
+ }
1164
+ if (optimisticUpdate2) {
1165
+ setupOptimisticUpdate(model, operation, schema, finalOptions, queryClient.getQueryCache().getAll(), (queryKey, data) => {
1166
+ queryClient.setQueryData(queryKey, data);
1167
+ queryClient.cancelQueries({
1168
+ queryKey
1169
+ }, {
1170
+ revert: false,
1171
+ silent: true
1172
+ });
1173
+ }, invalidateQueries ? (predicate) => queryClient.invalidateQueries({
1174
+ predicate
1175
+ }) : void 0, logging);
1176
+ }
1177
+ }
1178
+ return (0, import_vue_query.useMutation)(finalOptions);
1179
+ }
1180
+ __name(useInternalMutation, "useInternalMutation");
1181
+ // Annotate the CommonJS export names for ESM import in node:
1182
+ 0 && (module.exports = {
1183
+ VueQueryContextKey,
1184
+ provideHooksContext,
1185
+ provideQuerySettingsContext,
1186
+ useClientQueries,
1187
+ useInternalInfiniteQuery,
1188
+ useInternalMutation,
1189
+ useInternalQuery,
1190
+ useModelQueries
1191
+ });
1192
+ //# sourceMappingURL=vue.cjs.map