@zenstackhq/client-helpers 3.5.5 → 3.6.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,643 @@
1
+ import { clone, enumerate, invariant, zip } from "@zenstackhq/common-helpers";
2
+ //#region src/constants.ts
3
+ /**
4
+ * The default query endpoint.
5
+ */
6
+ const DEFAULT_QUERY_ENDPOINT = "/api/model";
7
+ //#endregion
8
+ //#region src/logging.ts
9
+ /**
10
+ * Logs a message using the provided logger.
11
+ */
12
+ function log(logger, message) {
13
+ if (typeof logger === "function") logger(message);
14
+ else if (logger) console.log(message);
15
+ }
16
+ //#endregion
17
+ //#region src/nested-read-visitor.ts
18
+ /**
19
+ * Visitor for nested read payload.
20
+ */
21
+ var NestedReadVisitor = class {
22
+ constructor(schema, callback) {
23
+ this.schema = schema;
24
+ this.callback = callback;
25
+ }
26
+ doVisit(model, field, kind, args) {
27
+ if (this.callback.field) {
28
+ if (this.callback.field(model, field, kind, args) === false) return;
29
+ }
30
+ if (!args || typeof args !== "object") return;
31
+ let selectInclude;
32
+ let nextKind;
33
+ if (args.select) {
34
+ selectInclude = args.select;
35
+ nextKind = "select";
36
+ } else if (args.include) {
37
+ selectInclude = args.include;
38
+ nextKind = "include";
39
+ }
40
+ if (selectInclude && typeof selectInclude === "object") for (const [k, v] of Object.entries(selectInclude)) if (k === "_count" && typeof v === "object" && v) this.doVisit(model, field, kind, v);
41
+ else {
42
+ const field = this.schema.models[model]?.fields[k];
43
+ if (field) this.doVisit(field.type, field, nextKind, v);
44
+ }
45
+ }
46
+ visit(model, args) {
47
+ this.doVisit(model, void 0, void 0, args);
48
+ }
49
+ };
50
+ //#endregion
51
+ //#region src/types.ts
52
+ /**
53
+ * List of ORM write actions.
54
+ */
55
+ const ORMWriteActions = [
56
+ "create",
57
+ "createMany",
58
+ "createManyAndReturn",
59
+ "connectOrCreate",
60
+ "update",
61
+ "updateMany",
62
+ "updateManyAndReturn",
63
+ "upsert",
64
+ "connect",
65
+ "disconnect",
66
+ "set",
67
+ "delete",
68
+ "deleteMany"
69
+ ];
70
+ //#endregion
71
+ //#region src/nested-write-visitor.ts
72
+ /**
73
+ * Recursive visitor for nested write (create/update) payload.
74
+ */
75
+ var NestedWriteVisitor = class {
76
+ constructor(schema, callback) {
77
+ this.schema = schema;
78
+ this.callback = callback;
79
+ }
80
+ isWriteAction(value) {
81
+ return ORMWriteActions.includes(value);
82
+ }
83
+ /**
84
+ * Start visiting
85
+ *
86
+ * @see NestedWriteVisitorCallback
87
+ */
88
+ async visit(model, action, args) {
89
+ if (!args) return;
90
+ let topData = args;
91
+ switch (action) {
92
+ case "create":
93
+ topData = topData.data;
94
+ break;
95
+ case "delete":
96
+ case "deleteMany":
97
+ topData = topData.where;
98
+ break;
99
+ }
100
+ await this.doVisit(model, action, topData, void 0, void 0, []);
101
+ }
102
+ async doVisit(model, action, data, parent, field, nestingPath) {
103
+ if (!data) return;
104
+ const toplevel = field == void 0;
105
+ const context = {
106
+ parent,
107
+ field,
108
+ nestingPath: [...nestingPath]
109
+ };
110
+ const pushNewContext = (field, model, where, unique = false) => {
111
+ return {
112
+ ...context,
113
+ nestingPath: [...context.nestingPath, {
114
+ field,
115
+ model,
116
+ where,
117
+ unique
118
+ }]
119
+ };
120
+ };
121
+ switch (action) {
122
+ case "create":
123
+ for (const item of this.enumerateReverse(data)) {
124
+ const newContext = pushNewContext(field, model, {});
125
+ let callbackResult;
126
+ if (this.callback.create) callbackResult = await this.callback.create(model, item, newContext);
127
+ if (callbackResult !== false) {
128
+ const subPayload = typeof callbackResult === "object" ? callbackResult : item;
129
+ await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
130
+ }
131
+ }
132
+ break;
133
+ case "createMany":
134
+ case "createManyAndReturn":
135
+ {
136
+ const newContext = pushNewContext(field, model, {});
137
+ let callbackResult;
138
+ if (this.callback.createMany) callbackResult = await this.callback.createMany(model, data, newContext);
139
+ if (callbackResult !== false) {
140
+ const subPayload = typeof callbackResult === "object" ? callbackResult : data.data;
141
+ await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
142
+ }
143
+ }
144
+ break;
145
+ case "connectOrCreate":
146
+ for (const item of this.enumerateReverse(data)) {
147
+ const newContext = pushNewContext(field, model, item.where);
148
+ let callbackResult;
149
+ if (this.callback.connectOrCreate) callbackResult = await this.callback.connectOrCreate(model, item, newContext);
150
+ if (callbackResult !== false) {
151
+ const subPayload = typeof callbackResult === "object" ? callbackResult : item.create;
152
+ await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
153
+ }
154
+ }
155
+ break;
156
+ case "connect":
157
+ if (this.callback.connect) for (const item of this.enumerateReverse(data)) {
158
+ const newContext = pushNewContext(field, model, item, true);
159
+ await this.callback.connect(model, item, newContext);
160
+ }
161
+ break;
162
+ case "disconnect":
163
+ if (this.callback.disconnect) for (const item of this.enumerateReverse(data)) {
164
+ const newContext = pushNewContext(field, model, item, typeof item === "object");
165
+ await this.callback.disconnect(model, item, newContext);
166
+ }
167
+ break;
168
+ case "set":
169
+ if (this.callback.set) for (const item of this.enumerateReverse(data)) {
170
+ const newContext = pushNewContext(field, model, item, true);
171
+ await this.callback.set(model, item, newContext);
172
+ }
173
+ break;
174
+ case "update":
175
+ for (const item of this.enumerateReverse(data)) {
176
+ const newContext = pushNewContext(field, model, item.where);
177
+ let callbackResult;
178
+ if (this.callback.update) callbackResult = await this.callback.update(model, item, newContext);
179
+ if (callbackResult !== false) {
180
+ const subPayload = typeof callbackResult === "object" ? callbackResult : typeof item.data === "object" ? item.data : item;
181
+ await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
182
+ }
183
+ }
184
+ break;
185
+ case "updateMany":
186
+ case "updateManyAndReturn":
187
+ for (const item of this.enumerateReverse(data)) {
188
+ const newContext = pushNewContext(field, model, item.where);
189
+ let callbackResult;
190
+ if (this.callback.updateMany) callbackResult = await this.callback.updateMany(model, item, newContext);
191
+ if (callbackResult !== false) {
192
+ const subPayload = typeof callbackResult === "object" ? callbackResult : item;
193
+ await this.visitSubPayload(model, action, subPayload, newContext.nestingPath);
194
+ }
195
+ }
196
+ break;
197
+ case "upsert":
198
+ for (const item of this.enumerateReverse(data)) {
199
+ const newContext = pushNewContext(field, model, item.where);
200
+ let callbackResult;
201
+ if (this.callback.upsert) callbackResult = await this.callback.upsert(model, item, newContext);
202
+ if (callbackResult !== false) if (typeof callbackResult === "object") await this.visitSubPayload(model, action, callbackResult, newContext.nestingPath);
203
+ else {
204
+ await this.visitSubPayload(model, action, item.create, newContext.nestingPath);
205
+ await this.visitSubPayload(model, action, item.update, newContext.nestingPath);
206
+ }
207
+ }
208
+ break;
209
+ case "delete":
210
+ if (this.callback.delete) for (const item of this.enumerateReverse(data)) {
211
+ const newContext = pushNewContext(field, model, toplevel ? item.where : item);
212
+ await this.callback.delete(model, item, newContext);
213
+ }
214
+ break;
215
+ case "deleteMany":
216
+ if (this.callback.deleteMany) for (const item of this.enumerateReverse(data)) {
217
+ const newContext = pushNewContext(field, model, toplevel ? item.where : item);
218
+ await this.callback.deleteMany(model, item, newContext);
219
+ }
220
+ break;
221
+ default: throw new Error(`unhandled action type ${action}`);
222
+ }
223
+ }
224
+ async visitSubPayload(model, action, payload, nestingPath) {
225
+ for (const item of enumerate(payload)) {
226
+ if (!item || typeof item !== "object") continue;
227
+ for (const field of Object.keys(item)) {
228
+ const fieldDef = this.schema.models[model]?.fields[field];
229
+ if (!fieldDef) continue;
230
+ if (fieldDef.relation) {
231
+ if (item[field]) {
232
+ for (const [subAction, subData] of Object.entries(item[field])) if (this.isWriteAction(subAction) && subData) await this.doVisit(fieldDef.type, subAction, subData, item[field], fieldDef, [...nestingPath]);
233
+ }
234
+ } else if (this.callback.field) await this.callback.field(fieldDef, action, item[field], {
235
+ parent: item,
236
+ nestingPath,
237
+ field: fieldDef
238
+ });
239
+ }
240
+ }
241
+ }
242
+ *enumerateReverse(data) {
243
+ if (Array.isArray(data)) for (let i = data.length - 1; i >= 0; i--) yield data[i];
244
+ else yield data;
245
+ }
246
+ };
247
+ //#endregion
248
+ //#region src/query-analysis.ts
249
+ /**
250
+ * Gets models read (including nested ones) given a query args.
251
+ */
252
+ function getReadModels(model, schema, args) {
253
+ const result = /* @__PURE__ */ new Set();
254
+ result.add(model);
255
+ new NestedReadVisitor(schema, { field: (model) => {
256
+ result.add(model);
257
+ return true;
258
+ } }).visit(model, args);
259
+ return [...result];
260
+ }
261
+ /**
262
+ * Gets mutated models (including nested ones) given a mutation args.
263
+ */
264
+ async function getMutatedModels(model, operation, mutationArgs, schema) {
265
+ const result = /* @__PURE__ */ new Set();
266
+ result.add(model);
267
+ if (mutationArgs) {
268
+ const addModel = (model) => void result.add(model);
269
+ const addCascades = (model) => {
270
+ const cascades = /* @__PURE__ */ new Set();
271
+ collectDeleteCascades(model, schema, cascades, /* @__PURE__ */ new Set());
272
+ cascades.forEach((m) => addModel(m));
273
+ };
274
+ await new NestedWriteVisitor(schema, {
275
+ create: addModel,
276
+ createMany: addModel,
277
+ connectOrCreate: addModel,
278
+ connect: addModel,
279
+ disconnect: addModel,
280
+ set: addModel,
281
+ update: addModel,
282
+ updateMany: addModel,
283
+ upsert: addModel,
284
+ delete: (model) => {
285
+ addModel(model);
286
+ addCascades(model);
287
+ },
288
+ deleteMany: (model) => {
289
+ addModel(model);
290
+ addCascades(model);
291
+ }
292
+ }).visit(model, operation, mutationArgs);
293
+ }
294
+ result.forEach((m) => {
295
+ getBaseRecursively(m, schema, result);
296
+ });
297
+ return [...result];
298
+ }
299
+ function collectDeleteCascades(model, schema, result, visited) {
300
+ if (visited.has(model)) return;
301
+ visited.add(model);
302
+ if (!schema.models[model]) return;
303
+ for (const [modelName, modelDef] of Object.entries(schema.models)) {
304
+ if (!modelDef) continue;
305
+ for (const fieldDef of Object.values(modelDef.fields)) if (fieldDef.relation?.onDelete === "Cascade" && fieldDef.type === model) {
306
+ if (!result.has(modelName)) result.add(modelName);
307
+ collectDeleteCascades(modelName, schema, result, visited);
308
+ }
309
+ }
310
+ }
311
+ function getBaseRecursively(model, schema, result) {
312
+ const modelDef = schema.models[model];
313
+ if (!modelDef) return;
314
+ if (modelDef.baseModel) {
315
+ result.add(modelDef.baseModel);
316
+ getBaseRecursively(modelDef.baseModel, schema, result);
317
+ }
318
+ }
319
+ //#endregion
320
+ //#region src/invalidation.ts
321
+ /**
322
+ * Create a function that invalidates queries affected by the given mutation operation.
323
+ *
324
+ * @param model Model under mutation.
325
+ * @param operation Mutation operation (e.g, `update`).
326
+ * @param schema The schema.
327
+ * @param invalidator Function to invalidate queries matching a predicate. It should internally
328
+ * enumerate all query cache entries and invalidate those for which the predicate returns true.
329
+ * @param logging Logging option.
330
+ */
331
+ function createInvalidator(model, operation, schema, invalidator, logging) {
332
+ return async (...args) => {
333
+ const [_, variables] = args;
334
+ await invalidator(await getInvalidationPredicate(model, operation, variables, schema, logging));
335
+ };
336
+ }
337
+ async function getInvalidationPredicate(model, operation, mutationArgs, schema, logging) {
338
+ const mutatedModels = await getMutatedModels(model, operation, mutationArgs, schema);
339
+ return ({ model, args }) => {
340
+ if (mutatedModels.includes(model)) {
341
+ if (logging) log(logging, `Marking "${model}" query for invalidation due to mutation "${operation}", query args: ${JSON.stringify(args)}`);
342
+ return true;
343
+ }
344
+ if (args) {
345
+ if (findNestedRead(model, mutatedModels, schema, args)) {
346
+ if (logging) log(logging, `Marking "${model}" query for invalidation due to mutation "${operation}", query args: ${JSON.stringify(args)}`);
347
+ return true;
348
+ }
349
+ }
350
+ return false;
351
+ };
352
+ }
353
+ function findNestedRead(visitingModel, targetModels, schema, args) {
354
+ const modelsRead = getReadModels(visitingModel, schema, args);
355
+ return targetModels.some((m) => modelsRead.includes(m));
356
+ }
357
+ //#endregion
358
+ //#region src/mutator.ts
359
+ /**
360
+ * Tries to apply a mutation to a query result.
361
+ *
362
+ * @param queryModel the model of the query
363
+ * @param queryOp the operation of the query
364
+ * @param queryData the result data of the query
365
+ * @param mutationModel the model of the mutation
366
+ * @param mutationOp the operation of the mutation
367
+ * @param mutationArgs the arguments of the mutation
368
+ * @param schema the schema
369
+ * @param logging logging configuration
370
+ * @returns the updated query data if the mutation is applicable, otherwise undefined
371
+ */
372
+ async function applyMutation(queryModel, queryOp, queryData, mutationModel, mutationOp, mutationArgs, schema, logging) {
373
+ if (!queryData || typeof queryData !== "object" && !Array.isArray(queryData)) return;
374
+ if (!queryOp.startsWith("find")) return;
375
+ return await doApplyMutation(queryModel, queryData, mutationModel, mutationOp, mutationArgs, schema, logging);
376
+ }
377
+ async function doApplyMutation(queryModel, queryData, mutationModel, mutationOp, mutationArgs, schema, logging) {
378
+ let resultData = queryData;
379
+ let updated = false;
380
+ await new NestedWriteVisitor(schema, {
381
+ create: (model, args) => {
382
+ if (model === queryModel && Array.isArray(resultData)) {
383
+ const r = createMutate(queryModel, resultData, args, schema, logging);
384
+ if (r) {
385
+ resultData = r;
386
+ updated = true;
387
+ }
388
+ }
389
+ },
390
+ createMany: (model, args) => {
391
+ if (model === queryModel && args?.data && Array.isArray(resultData)) for (const oneArg of enumerate(args.data)) {
392
+ const r = createMutate(queryModel, resultData, oneArg, schema, logging);
393
+ if (r) {
394
+ resultData = r;
395
+ updated = true;
396
+ }
397
+ }
398
+ },
399
+ update: (model, args) => {
400
+ if (model === queryModel && !Array.isArray(resultData)) {
401
+ const r = updateMutate(queryModel, resultData, model, args, schema, logging);
402
+ if (r) {
403
+ resultData = r;
404
+ updated = true;
405
+ }
406
+ }
407
+ },
408
+ upsert: (model, args) => {
409
+ if (model === queryModel && args?.where && args?.create && args?.update) {
410
+ const r = upsertMutate(queryModel, resultData, model, args, schema, logging);
411
+ if (r) {
412
+ resultData = r;
413
+ updated = true;
414
+ }
415
+ }
416
+ },
417
+ delete: (model, args) => {
418
+ if (model === queryModel) {
419
+ const r = deleteMutate(queryModel, resultData, model, args, schema, logging);
420
+ if (r) {
421
+ resultData = r;
422
+ updated = true;
423
+ }
424
+ }
425
+ }
426
+ }).visit(mutationModel, mutationOp, mutationArgs);
427
+ const modelFields = schema.models[queryModel]?.fields;
428
+ invariant(modelFields, `Model ${queryModel} not found in schema`);
429
+ if (Array.isArray(resultData)) {
430
+ let arrayCloned = false;
431
+ for (let i = 0; i < resultData.length; i++) {
432
+ const item = resultData[i];
433
+ if (!item || typeof item !== "object" || item.$optimistic) continue;
434
+ const r = await doApplyMutation(queryModel, item, mutationModel, mutationOp, mutationArgs, schema, logging);
435
+ if (r && typeof r === "object") {
436
+ if (!arrayCloned) {
437
+ resultData = [...resultData];
438
+ arrayCloned = true;
439
+ }
440
+ resultData[i] = r;
441
+ updated = true;
442
+ }
443
+ }
444
+ } else if (resultData !== null && typeof resultData === "object") {
445
+ const currentData = { ...resultData };
446
+ for (const [key, value] of Object.entries(currentData)) {
447
+ const fieldDef = modelFields[key];
448
+ if (!fieldDef?.relation) continue;
449
+ const r = await doApplyMutation(fieldDef.type, value, mutationModel, mutationOp, mutationArgs, schema, logging);
450
+ if (r && typeof r === "object") {
451
+ resultData = {
452
+ ...resultData,
453
+ [key]: r
454
+ };
455
+ updated = true;
456
+ }
457
+ }
458
+ }
459
+ return updated ? resultData : void 0;
460
+ }
461
+ function createMutate(queryModel, currentData, newData, schema, logging) {
462
+ if (!newData) return;
463
+ const modelFields = schema.models[queryModel]?.fields;
464
+ if (!modelFields) return;
465
+ const insert = {};
466
+ const newDataFields = Object.keys(newData);
467
+ Object.entries(modelFields).forEach(([name, field]) => {
468
+ if (field.relation && newData[name]) {
469
+ assignForeignKeyFields(field, insert, newData[name]);
470
+ return;
471
+ }
472
+ if (newDataFields.includes(name)) insert[name] = clone(newData[name]);
473
+ else {
474
+ const defaultAttr = field.attributes?.find((attr) => attr.name === "@default");
475
+ if (field.type === "DateTime") {
476
+ if (defaultAttr || field.attributes?.some((attr) => attr.name === "@updatedAt")) {
477
+ insert[name] = /* @__PURE__ */ new Date();
478
+ return;
479
+ }
480
+ }
481
+ const defaultArg = defaultAttr?.args?.[0]?.value;
482
+ if (defaultArg?.kind === "literal") insert[name] = defaultArg.value;
483
+ }
484
+ });
485
+ getIdFields(schema, queryModel).forEach((f) => {
486
+ if (insert[f.name] === void 0) if (f.type === "Int" || f.type === "BigInt") {
487
+ const currMax = Array.isArray(currentData) ? Math.max(...[...currentData].map((item) => {
488
+ const idv = parseInt(item[f.name]);
489
+ return isNaN(idv) ? 0 : idv;
490
+ })) : 0;
491
+ insert[f.name] = currMax + 1;
492
+ } else insert[f.name] = crypto.randomUUID();
493
+ });
494
+ insert.$optimistic = true;
495
+ if (logging) log(logging, `Applying optimistic create for ${queryModel}: ${JSON.stringify(insert)}`);
496
+ return [insert, ...Array.isArray(currentData) ? currentData : []];
497
+ }
498
+ function updateMutate(queryModel, currentData, mutateModel, mutateArgs, schema, logging) {
499
+ if (!currentData || typeof currentData !== "object") return;
500
+ if (!mutateArgs?.where || typeof mutateArgs.where !== "object") return;
501
+ if (!mutateArgs?.data || typeof mutateArgs.data !== "object") return;
502
+ if (!idFieldsMatch(mutateModel, currentData, mutateArgs.where, schema)) return;
503
+ const modelFields = schema.models[queryModel]?.fields;
504
+ if (!modelFields) return;
505
+ let updated = false;
506
+ let resultData = currentData;
507
+ for (const [key, value] of Object.entries(mutateArgs.data)) {
508
+ const fieldInfo = modelFields[key];
509
+ if (!fieldInfo) continue;
510
+ if (fieldInfo.relation && !value?.connect) continue;
511
+ if (!updated) resultData = { ...currentData };
512
+ if (fieldInfo.relation) assignForeignKeyFields(fieldInfo, resultData, value);
513
+ else resultData[key] = clone(value);
514
+ resultData.$optimistic = true;
515
+ updated = true;
516
+ if (logging) log(logging, `Applying optimistic update for ${queryModel}: ${JSON.stringify(resultData)}`);
517
+ }
518
+ return updated ? resultData : void 0;
519
+ }
520
+ function upsertMutate(queryModel, currentData, model, args, schema, logging) {
521
+ let updated = false;
522
+ let resultData = currentData;
523
+ if (Array.isArray(resultData)) {
524
+ const foundIndex = resultData.findIndex((x) => idFieldsMatch(model, x, args.where, schema));
525
+ if (foundIndex >= 0) {
526
+ const updateResult = updateMutate(queryModel, resultData[foundIndex], model, {
527
+ where: args.where,
528
+ data: args.update
529
+ }, schema, logging);
530
+ if (updateResult) {
531
+ resultData = [
532
+ ...resultData.slice(0, foundIndex),
533
+ updateResult,
534
+ ...resultData.slice(foundIndex + 1)
535
+ ];
536
+ updated = true;
537
+ }
538
+ } else {
539
+ const createResult = createMutate(queryModel, resultData, args.create, schema, logging);
540
+ if (createResult) {
541
+ resultData = createResult;
542
+ updated = true;
543
+ }
544
+ }
545
+ } else {
546
+ const updateResult = updateMutate(queryModel, resultData, model, {
547
+ where: args.where,
548
+ data: args.update
549
+ }, schema, logging);
550
+ if (updateResult) {
551
+ resultData = updateResult;
552
+ updated = true;
553
+ }
554
+ }
555
+ return updated ? resultData : void 0;
556
+ }
557
+ function deleteMutate(queryModel, currentData, mutateModel, mutateArgs, schema, logging) {
558
+ if (!currentData || !mutateArgs) return;
559
+ if (queryModel !== mutateModel) return;
560
+ let updated = false;
561
+ let result = currentData;
562
+ if (Array.isArray(currentData)) {
563
+ for (const item of currentData) if (idFieldsMatch(mutateModel, item, mutateArgs, schema)) {
564
+ result = result.filter((x) => x !== item);
565
+ updated = true;
566
+ if (logging) log(logging, `Applying optimistic delete for ${queryModel}: ${JSON.stringify(item)}`);
567
+ }
568
+ } else if (idFieldsMatch(mutateModel, currentData, mutateArgs, schema)) {
569
+ result = null;
570
+ updated = true;
571
+ if (logging) log(logging, `Applying optimistic delete for ${queryModel}: ${JSON.stringify(currentData)}`);
572
+ }
573
+ return updated ? result : void 0;
574
+ }
575
+ function idFieldsMatch(model, x, y, schema) {
576
+ if (!x || !y || typeof x !== "object" || typeof y !== "object") return false;
577
+ const idFields = getIdFields(schema, model);
578
+ if (idFields.length === 0) return false;
579
+ return idFields.every((f) => x[f.name] === y[f.name]);
580
+ }
581
+ function assignForeignKeyFields(field, resultData, mutationData) {
582
+ if (!mutationData?.connect) return;
583
+ if (!field.relation?.fields || !field.relation.references) return;
584
+ for (const [idField, fkField] of zip(field.relation.references, field.relation.fields)) if (idField in mutationData.connect) resultData[fkField] = mutationData.connect[idField];
585
+ }
586
+ function getIdFields(schema, model) {
587
+ return (schema.models[model]?.idFields ?? []).map((f) => schema.models[model].fields[f]);
588
+ }
589
+ //#endregion
590
+ //#region src/optimistic.ts
591
+ /**
592
+ * Creates a function that performs optimistic updates for queries potentially
593
+ * affected by the given mutation operation.
594
+ *
595
+ * @param model Model under mutation.
596
+ * @param operation Mutation operation (e.g, `update`).
597
+ * @param schema The schema.
598
+ * @param options Optimistic update options.
599
+ * @param getAllQueries Callback to get all cached queries.
600
+ * @param logging Logging option.
601
+ */
602
+ function createOptimisticUpdater(model, operation, schema, options, getAllQueries, logging) {
603
+ return async (...args) => {
604
+ const [mutationArgs] = args;
605
+ for (const queryInfo of getAllQueries()) {
606
+ const logInfo = JSON.stringify({
607
+ model: queryInfo.model,
608
+ operation: queryInfo.operation,
609
+ args: queryInfo.args
610
+ });
611
+ if (!queryInfo.optimisticUpdate) {
612
+ if (logging) log(logging, `Skipping optimistic update for ${logInfo} due to opt-out`);
613
+ continue;
614
+ }
615
+ if (options.optimisticDataProvider) {
616
+ const providerResult = await options.optimisticDataProvider({
617
+ queryModel: queryInfo.model,
618
+ queryOperation: queryInfo.operation,
619
+ queryArgs: queryInfo.args,
620
+ currentData: queryInfo.data,
621
+ mutationArgs
622
+ });
623
+ if (providerResult?.kind === "Skip") {
624
+ if (logging) log(logging, `Skipping optimistic updating due to provider result: ${logInfo}`);
625
+ continue;
626
+ } else if (providerResult?.kind === "Update") {
627
+ if (logging) log(logging, `Optimistically updating due to provider result: ${logInfo}`);
628
+ queryInfo.updateData(providerResult.data, true);
629
+ continue;
630
+ }
631
+ }
632
+ const mutatedData = await applyMutation(queryInfo.model, queryInfo.operation, queryInfo.data, model, operation, mutationArgs, schema, logging);
633
+ if (mutatedData !== void 0) {
634
+ if (logging) log(logging, `Optimistically updating due to mutation "${model}.${operation}": ${logInfo}`);
635
+ queryInfo.updateData(mutatedData, true);
636
+ }
637
+ }
638
+ };
639
+ }
640
+ //#endregion
641
+ export { DEFAULT_QUERY_ENDPOINT, NestedReadVisitor, NestedWriteVisitor, ORMWriteActions, applyMutation, createInvalidator, createOptimisticUpdater, getMutatedModels, getReadModels, log };
642
+
643
+ //# sourceMappingURL=index.mjs.map