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