@zenstackhq/sdk 3.5.6 → 3.6.1

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.js DELETED
@@ -1,1731 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
- var __export = (target, all) => {
4
- for (var name in all)
5
- __defProp(target, name, { get: all[name], enumerable: true });
6
- };
7
-
8
- // src/model-utils.ts
9
- var model_utils_exports = {};
10
- __export(model_utils_exports, {
11
- DELEGATE_AUX_RELATION_PREFIX: () => DELEGATE_AUX_RELATION_PREFIX,
12
- getAttribute: () => getAttribute,
13
- getAuthDecl: () => getAuthDecl,
14
- getContainingModel: () => getContainingModel,
15
- getDelegateOriginModel: () => getDelegateOriginModel,
16
- getIdFields: () => getIdFields,
17
- getOwnedFields: () => getOwnedFields,
18
- hasAttribute: () => hasAttribute,
19
- isDelegateModel: () => isDelegateModel,
20
- isFromStdlib: () => isFromStdlib,
21
- isIdField: () => isIdField,
22
- isUniqueField: () => isUniqueField,
23
- resolved: () => resolved
24
- });
25
- import { isDataModel, isLiteralExpr, isModel, isTypeDef } from "@zenstackhq/language/ast";
26
- import { getAllFields, getModelIdFields, getModelUniqueFields } from "@zenstackhq/language/utils";
27
- function isIdField(field, contextModel) {
28
- if (hasAttribute(field, "@id")) {
29
- return true;
30
- }
31
- const modelLevelIds = getModelIdFields(contextModel);
32
- if (modelLevelIds.map((f) => f.name).includes(field.name)) {
33
- return true;
34
- }
35
- const allFields = getAllFields(contextModel);
36
- if (allFields.some((f) => hasAttribute(f, "@id")) || modelLevelIds.length > 0) {
37
- return false;
38
- }
39
- const firstUniqueField = allFields.find((f) => hasAttribute(f, "@unique"));
40
- if (firstUniqueField) {
41
- return firstUniqueField.name === field.name;
42
- }
43
- const modelLevelUnique = getModelUniqueFields(contextModel);
44
- if (modelLevelUnique.map((f) => f.name).includes(field.name)) {
45
- return true;
46
- }
47
- return false;
48
- }
49
- __name(isIdField, "isIdField");
50
- function hasAttribute(decl, name) {
51
- return !!getAttribute(decl, name);
52
- }
53
- __name(hasAttribute, "hasAttribute");
54
- function getAttribute(decl, name) {
55
- return decl.attributes.find((attr) => attr.decl.$refText === name);
56
- }
57
- __name(getAttribute, "getAttribute");
58
- function isDelegateModel(node) {
59
- return isDataModel(node) && hasAttribute(node, "@@delegate");
60
- }
61
- __name(isDelegateModel, "isDelegateModel");
62
- function getOwnedFields(model) {
63
- const fields = [
64
- ...model.fields
65
- ];
66
- for (const mixin of model.mixins) {
67
- if (mixin.ref) {
68
- fields.push(...getOwnedFields(mixin.ref));
69
- }
70
- }
71
- return fields;
72
- }
73
- __name(getOwnedFields, "getOwnedFields");
74
- function getDelegateOriginModel(field, contextModel) {
75
- let base = contextModel.baseModel?.ref;
76
- while (base) {
77
- if (isDelegateModel(base) && getOwnedFields(base).some((f) => f.name === field.name)) {
78
- return base.name;
79
- }
80
- base = base.baseModel?.ref;
81
- }
82
- return void 0;
83
- }
84
- __name(getDelegateOriginModel, "getDelegateOriginModel");
85
- function isUniqueField(field) {
86
- if (hasAttribute(field, "@unique")) {
87
- return true;
88
- }
89
- const modelIds = getAttribute(field.$container, "@@unique");
90
- if (modelIds && modelIds.args.some((arg) => isLiteralExpr(arg.value) && arg.value.value === field.name)) {
91
- return true;
92
- }
93
- return false;
94
- }
95
- __name(isUniqueField, "isUniqueField");
96
- function isFromStdlib(node) {
97
- const model = getContainingModel(node);
98
- return !!model && !!model.$document && model.$document.uri.path.endsWith("stdlib.zmodel");
99
- }
100
- __name(isFromStdlib, "isFromStdlib");
101
- function getContainingModel(node) {
102
- if (!node) {
103
- return null;
104
- }
105
- return isModel(node) ? node : getContainingModel(node.$container);
106
- }
107
- __name(getContainingModel, "getContainingModel");
108
- function resolved(ref) {
109
- if (!ref.ref) {
110
- throw new Error(`Reference not resolved: ${ref.$refText}`);
111
- }
112
- return ref.ref;
113
- }
114
- __name(resolved, "resolved");
115
- function getAuthDecl(model) {
116
- let found = model.declarations.find((d) => (isDataModel(d) || isTypeDef(d)) && d.attributes.some((attr) => attr.decl.$refText === "@@auth"));
117
- if (!found) {
118
- found = model.declarations.find((d) => (isDataModel(d) || isTypeDef(d)) && d.name === "User");
119
- }
120
- return found;
121
- }
122
- __name(getAuthDecl, "getAuthDecl");
123
- function getIdFields(dm) {
124
- return getAllFields(dm).filter((f) => isIdField(f, dm)).map((f) => f.name);
125
- }
126
- __name(getIdFields, "getIdFields");
127
- var DELEGATE_AUX_RELATION_PREFIX = "delegate_aux";
128
-
129
- // src/prisma/prisma-schema-generator.ts
130
- import { lowerCaseFirst } from "@zenstackhq/common-helpers";
131
- import { ZModelCodeGenerator } from "@zenstackhq/language";
132
- import { BooleanLiteral, DataModel, DataSource as DataSource2, Enum as Enum2, GeneratorDecl, isArrayExpr, isDataModel as isDataModel2, isDataSource, isGeneratorDecl, isInvocationExpr, isLiteralExpr as isLiteralExpr2, isNullExpr, isReferenceExpr, isStringLiteral, isTypeDef as isTypeDef2, NumberLiteral, StringLiteral } from "@zenstackhq/language/ast";
133
- import { getAllAttributes, getAllFields as getAllFields2, getStringLiteral, isAuthInvocation, isDelegateModel as isDelegateModel2 } from "@zenstackhq/language/utils";
134
- import { AstUtils } from "langium";
135
- import { match } from "ts-pattern";
136
-
137
- // src/prisma/indent-string.ts
138
- function indentString(string, count = 4) {
139
- const indent = " ";
140
- return string.replace(/^(?!\s*$)/gm, indent.repeat(count));
141
- }
142
- __name(indentString, "indentString");
143
-
144
- // src/prisma/prisma-builder.ts
145
- var PrismaModel = class {
146
- static {
147
- __name(this, "PrismaModel");
148
- }
149
- datasources = [];
150
- generators = [];
151
- models = [];
152
- enums = [];
153
- addDataSource(name, fields = []) {
154
- const ds = new DataSource(name, fields);
155
- this.datasources.push(ds);
156
- return ds;
157
- }
158
- addGenerator(name, fields) {
159
- const generator = new Generator(name, fields);
160
- this.generators.push(generator);
161
- return generator;
162
- }
163
- addModel(name) {
164
- const model = new Model(name, false);
165
- this.models.push(model);
166
- return model;
167
- }
168
- addView(name) {
169
- const model = new Model(name, true);
170
- this.models.push(model);
171
- return model;
172
- }
173
- addEnum(name) {
174
- const e = new Enum(name);
175
- this.enums.push(e);
176
- return e;
177
- }
178
- toString() {
179
- return [
180
- ...this.datasources,
181
- ...this.generators,
182
- ...this.enums,
183
- ...this.models
184
- ].map((d) => d.toString()).join("\n\n");
185
- }
186
- };
187
- var DataSource = class {
188
- static {
189
- __name(this, "DataSource");
190
- }
191
- name;
192
- fields;
193
- constructor(name, fields = []) {
194
- this.name = name;
195
- this.fields = fields;
196
- }
197
- toString() {
198
- return `datasource ${this.name} {
199
- ` + this.fields.map((f) => indentString(`${f.name} = ${f.text}`)).join("\n") + `
200
- }`;
201
- }
202
- };
203
- var Generator = class {
204
- static {
205
- __name(this, "Generator");
206
- }
207
- name;
208
- fields;
209
- constructor(name, fields) {
210
- this.name = name;
211
- this.fields = fields;
212
- }
213
- toString() {
214
- return `generator ${this.name} {
215
- ` + this.fields.map((f) => indentString(`${f.name} = ${f.text}`)).join("\n") + `
216
- }`;
217
- }
218
- };
219
- var DeclarationBase = class {
220
- static {
221
- __name(this, "DeclarationBase");
222
- }
223
- documentations;
224
- constructor(documentations = []) {
225
- this.documentations = documentations;
226
- }
227
- addComment(name) {
228
- this.documentations.push(name);
229
- return name;
230
- }
231
- toString() {
232
- return this.documentations.map((x) => `${x}
233
- `).join("");
234
- }
235
- };
236
- var ContainerDeclaration = class extends DeclarationBase {
237
- static {
238
- __name(this, "ContainerDeclaration");
239
- }
240
- attributes;
241
- constructor(documentations = [], attributes = []) {
242
- super(documentations), this.attributes = attributes;
243
- }
244
- };
245
- var FieldDeclaration = class extends DeclarationBase {
246
- static {
247
- __name(this, "FieldDeclaration");
248
- }
249
- attributes;
250
- constructor(documentations = [], attributes = []) {
251
- super(documentations), this.attributes = attributes;
252
- }
253
- };
254
- var Model = class extends ContainerDeclaration {
255
- static {
256
- __name(this, "Model");
257
- }
258
- name;
259
- isView;
260
- fields = [];
261
- constructor(name, isView, documentations = []) {
262
- super(documentations), this.name = name, this.isView = isView;
263
- }
264
- addField(name, type, attributes = [], documentations = [], addToFront = false) {
265
- const field = new ModelField(name, type, attributes, documentations);
266
- if (addToFront) {
267
- this.fields.unshift(field);
268
- } else {
269
- this.fields.push(field);
270
- }
271
- return field;
272
- }
273
- addAttribute(name, args = []) {
274
- const attr = new ContainerAttribute(name, args);
275
- this.attributes.push(attr);
276
- return attr;
277
- }
278
- toString() {
279
- const result = [
280
- ...this.fields
281
- ];
282
- if (this.attributes.length > 0) {
283
- result.push("");
284
- }
285
- result.push(...this.attributes);
286
- return super.toString() + `${this.isView ? "view" : "model"} ${this.name} {
287
- ` + indentString(result.map((d) => d.toString()).join("\n")) + `
288
- }`;
289
- }
290
- };
291
- var ModelFieldType = class {
292
- static {
293
- __name(this, "ModelFieldType");
294
- }
295
- type;
296
- array;
297
- optional;
298
- constructor(type, array, optional) {
299
- this.type = type;
300
- this.array = array;
301
- this.optional = optional;
302
- }
303
- toString() {
304
- return `${this.type}${this.array ? "[]" : ""}${this.optional ? "?" : ""}`;
305
- }
306
- };
307
- var ModelField = class extends FieldDeclaration {
308
- static {
309
- __name(this, "ModelField");
310
- }
311
- name;
312
- type;
313
- constructor(name, type, attributes = [], documentations = []) {
314
- super(documentations, attributes), this.name = name, this.type = type;
315
- }
316
- addAttribute(name, args = []) {
317
- const attr = new FieldAttribute(name, args);
318
- this.attributes.push(attr);
319
- return attr;
320
- }
321
- toString() {
322
- return super.toString() + `${this.name} ${this.type}` + (this.attributes.length > 0 ? " " + this.attributes.map((a) => a.toString()).join(" ") : "");
323
- }
324
- };
325
- var FieldAttribute = class {
326
- static {
327
- __name(this, "FieldAttribute");
328
- }
329
- name;
330
- args;
331
- constructor(name, args = []) {
332
- this.name = name;
333
- this.args = args;
334
- }
335
- toString() {
336
- return `${this.name}(` + this.args.map((a) => a.toString()).join(", ") + `)`;
337
- }
338
- };
339
- var ContainerAttribute = class {
340
- static {
341
- __name(this, "ContainerAttribute");
342
- }
343
- name;
344
- args;
345
- constructor(name, args = []) {
346
- this.name = name;
347
- this.args = args;
348
- }
349
- toString() {
350
- return `${this.name}(` + this.args.map((a) => a.toString()).join(", ") + `)`;
351
- }
352
- };
353
- var AttributeArg = class {
354
- static {
355
- __name(this, "AttributeArg");
356
- }
357
- name;
358
- value;
359
- constructor(name, value) {
360
- this.name = name;
361
- this.value = value;
362
- }
363
- toString() {
364
- return this.name ? `${this.name}: ${this.value}` : this.value.toString();
365
- }
366
- };
367
- var AttributeArgValue = class {
368
- static {
369
- __name(this, "AttributeArgValue");
370
- }
371
- type;
372
- value;
373
- constructor(type, value) {
374
- this.type = type;
375
- this.value = value;
376
- switch (type) {
377
- case "String":
378
- if (typeof value !== "string") throw new Error("Value must be string");
379
- break;
380
- case "Number":
381
- if (typeof value !== "number" && typeof value !== "string") throw new Error("Value must be number or string");
382
- break;
383
- case "Boolean":
384
- if (typeof value !== "boolean") throw new Error("Value must be boolean");
385
- break;
386
- case "Array":
387
- if (!Array.isArray(value)) throw new Error("Value must be array");
388
- break;
389
- case "FieldReference":
390
- if (typeof value !== "string" && !(value instanceof FieldReference)) throw new Error("Value must be string or FieldReference");
391
- break;
392
- case "FunctionCall":
393
- if (!(value instanceof FunctionCall)) throw new Error("Value must be FunctionCall");
394
- break;
395
- }
396
- }
397
- toString() {
398
- switch (this.type) {
399
- case "String":
400
- return JSON.stringify(this.value);
401
- case "Number":
402
- return this.value.toString();
403
- case "FieldReference": {
404
- if (typeof this.value === "string") {
405
- return this.value;
406
- } else {
407
- const fr = this.value;
408
- let r = fr.field;
409
- if (fr.args.length > 0) {
410
- r += "(" + fr.args.map((a) => a.toString()).join(",") + ")";
411
- }
412
- return r;
413
- }
414
- }
415
- case "FunctionCall":
416
- return this.value.toString();
417
- case "Boolean":
418
- return this.value ? "true" : "false";
419
- case "Array":
420
- return "[" + this.value.map((v) => v.toString()).join(", ") + "]";
421
- default:
422
- throw new Error(`Unknown attribute value type ${this.type}`);
423
- }
424
- }
425
- };
426
- var FieldReference = class {
427
- static {
428
- __name(this, "FieldReference");
429
- }
430
- field;
431
- args;
432
- constructor(field, args = []) {
433
- this.field = field;
434
- this.args = args;
435
- }
436
- };
437
- var FieldReferenceArg = class {
438
- static {
439
- __name(this, "FieldReferenceArg");
440
- }
441
- name;
442
- value;
443
- constructor(name, value) {
444
- this.name = name;
445
- this.value = value;
446
- }
447
- toString() {
448
- return `${this.name}: ${this.value}`;
449
- }
450
- };
451
- var FunctionCall = class {
452
- static {
453
- __name(this, "FunctionCall");
454
- }
455
- func;
456
- args;
457
- constructor(func, args = []) {
458
- this.func = func;
459
- this.args = args;
460
- }
461
- toString() {
462
- return `${this.func}(` + this.args.map((a) => a.toString()).join(", ") + ")";
463
- }
464
- };
465
- var FunctionCallArg = class {
466
- static {
467
- __name(this, "FunctionCallArg");
468
- }
469
- value;
470
- constructor(value) {
471
- this.value = value;
472
- }
473
- toString() {
474
- return this.value;
475
- }
476
- };
477
- var Enum = class extends ContainerDeclaration {
478
- static {
479
- __name(this, "Enum");
480
- }
481
- name;
482
- fields = [];
483
- constructor(name, documentations = []) {
484
- super(documentations), this.name = name;
485
- }
486
- addField(name, attributes = [], documentations = []) {
487
- const field = new EnumField(name, attributes, documentations);
488
- this.fields.push(field);
489
- return field;
490
- }
491
- addAttribute(name, args = []) {
492
- const attr = new ContainerAttribute(name, args);
493
- this.attributes.push(attr);
494
- return attr;
495
- }
496
- addComment(name) {
497
- this.documentations.push(name);
498
- return name;
499
- }
500
- toString() {
501
- return super.toString() + `enum ${this.name} {
502
- ` + indentString([
503
- ...this.fields,
504
- ...this.attributes
505
- ].map((d) => d.toString()).join("\n")) + "\n}";
506
- }
507
- };
508
- var EnumField = class extends DeclarationBase {
509
- static {
510
- __name(this, "EnumField");
511
- }
512
- name;
513
- attributes;
514
- constructor(name, attributes = [], documentations = []) {
515
- super(documentations), this.name = name, this.attributes = attributes;
516
- }
517
- addAttribute(name, args = []) {
518
- const attr = new FieldAttribute(name, args);
519
- this.attributes.push(attr);
520
- return attr;
521
- }
522
- toString() {
523
- return super.toString() + this.name + (this.attributes.length > 0 ? " " + this.attributes.map((a) => a.toString()).join(" ") : "");
524
- }
525
- };
526
-
527
- // src/prisma/prisma-schema-generator.ts
528
- var IDENTIFIER_NAME_MAX_LENGTH = 50 - DELEGATE_AUX_RELATION_PREFIX.length;
529
- var NON_PRISMA_DATASOURCE_FIELDS = [
530
- "defaultSchema"
531
- ];
532
- var PrismaSchemaGenerator = class {
533
- static {
534
- __name(this, "PrismaSchemaGenerator");
535
- }
536
- zmodel;
537
- PRELUDE = `//////////////////////////////////////////////////////////////////////////////////////////////
538
- // DO NOT MODIFY THIS FILE //
539
- // This file is automatically generated by ZenStack CLI and should not be manually updated. //
540
- //////////////////////////////////////////////////////////////////////////////////////////////
541
-
542
- `;
543
- // a mapping from full names to shortened names
544
- shortNameMap = /* @__PURE__ */ new Map();
545
- constructor(zmodel) {
546
- this.zmodel = zmodel;
547
- }
548
- async generate() {
549
- const prisma = new PrismaModel();
550
- for (const decl of this.zmodel.declarations) {
551
- switch (decl.$type) {
552
- case DataSource2:
553
- this.generateDataSource(prisma, decl);
554
- break;
555
- case Enum2:
556
- this.generateEnum(prisma, decl);
557
- break;
558
- case DataModel:
559
- this.generateModel(prisma, decl);
560
- break;
561
- case GeneratorDecl:
562
- this.generateGenerator(prisma, decl);
563
- break;
564
- }
565
- }
566
- if (!this.zmodel.declarations.some(isGeneratorDecl)) {
567
- this.generateDefaultGenerator(prisma);
568
- }
569
- return this.PRELUDE + prisma.toString();
570
- }
571
- generateDataSource(prisma, dataSource) {
572
- const fields = dataSource.fields.filter((f) => !NON_PRISMA_DATASOURCE_FIELDS.includes(f.name)).map((f) => ({
573
- name: f.name,
574
- text: this.configExprToText(f.value)
575
- }));
576
- prisma.addDataSource(dataSource.name, fields);
577
- }
578
- configExprToText(expr) {
579
- if (isLiteralExpr2(expr)) {
580
- return this.literalToText(expr);
581
- } else if (isInvocationExpr(expr)) {
582
- const fc = this.makeFunctionCall(expr);
583
- return fc.toString();
584
- } else {
585
- return this.configArrayToText(expr);
586
- }
587
- }
588
- configArrayToText(expr) {
589
- return "[" + expr.items.map((item) => {
590
- if (isLiteralExpr2(item)) {
591
- return this.literalToText(item);
592
- } else {
593
- return item.name + (item.args.length > 0 ? "(" + item.args.map((arg) => this.configInvocationArgToText(arg)).join(", ") + ")" : "");
594
- }
595
- }).join(", ") + "]";
596
- }
597
- configInvocationArgToText(arg) {
598
- return `${arg.name}: ${this.literalToText(arg.value)}`;
599
- }
600
- literalToText(expr) {
601
- return JSON.stringify(expr.value);
602
- }
603
- generateGenerator(prisma, decl) {
604
- prisma.addGenerator(decl.name, decl.fields.map((f) => ({
605
- name: f.name,
606
- text: this.configExprToText(f.value)
607
- })));
608
- }
609
- generateDefaultGenerator(prisma) {
610
- const gen = prisma.addGenerator("client", [
611
- {
612
- name: "provider",
613
- text: '"prisma-client-js"'
614
- }
615
- ]);
616
- const previewFeatures = [];
617
- const dataSource = this.zmodel.declarations.find(isDataSource);
618
- if (dataSource?.fields.some((f) => f.name === "extensions")) {
619
- previewFeatures.push("postgresqlExtensions");
620
- }
621
- if (this.zmodel.declarations.some((d) => isDataModel2(d) && d.isView)) {
622
- previewFeatures.push("views");
623
- }
624
- if (previewFeatures.length > 0) {
625
- gen.fields.push({
626
- name: "previewFeatures",
627
- text: JSON.stringify(previewFeatures)
628
- });
629
- }
630
- }
631
- generateModel(prisma, decl) {
632
- const model = decl.isView ? prisma.addView(decl.name) : prisma.addModel(decl.name);
633
- const allFields = getAllFields2(decl, true);
634
- for (const field of allFields) {
635
- if (model_utils_exports.hasAttribute(field, "@computed")) {
636
- continue;
637
- }
638
- if (model_utils_exports.isIdField(field, decl) || !getDelegateOriginModel(field, decl)) {
639
- this.generateModelField(model, field, decl);
640
- }
641
- }
642
- const allAttributes = getAllAttributes(decl).filter((attr) => this.isPrismaAttribute(attr));
643
- for (const attr of allAttributes) {
644
- this.generateContainerAttribute(model, attr);
645
- }
646
- if (this.datasourceHasSchemasSetting(decl.$container) && !allAttributes.some((attr) => attr.decl.ref?.name === "@@schema")) {
647
- model.addAttribute("@@schema", [
648
- new AttributeArg(void 0, new AttributeArgValue("String", this.getDefaultPostgresSchemaName(decl.$container)))
649
- ]);
650
- }
651
- decl.comments.forEach((c) => model.addComment(c));
652
- this.generateDelegateRelationForBase(model, decl);
653
- this.generateDelegateRelationForConcrete(model, decl);
654
- }
655
- getDatasourceField(zmodel, fieldName) {
656
- const dataSource = zmodel.declarations.find(isDataSource);
657
- return dataSource?.fields.find((f) => f.name === fieldName);
658
- }
659
- datasourceHasSchemasSetting(zmodel) {
660
- return !!this.getDatasourceField(zmodel, "schemas");
661
- }
662
- getDefaultPostgresSchemaName(zmodel) {
663
- const defaultSchemaField = this.getDatasourceField(zmodel, "defaultSchema");
664
- return getStringLiteral(defaultSchemaField?.value) ?? "public";
665
- }
666
- isPrismaAttribute(attr) {
667
- if (!attr.decl.ref) {
668
- return false;
669
- }
670
- return attr.decl.ref.attributes.some((a) => a.decl.ref?.name === "@@@prisma");
671
- }
672
- getUnsupportedFieldType(fieldType) {
673
- if (fieldType.unsupported) {
674
- const value = getStringLiteral(fieldType.unsupported.value);
675
- if (value) {
676
- return `Unsupported("${value}")`;
677
- } else {
678
- return void 0;
679
- }
680
- } else {
681
- return void 0;
682
- }
683
- }
684
- generateModelField(model, field, contextModel, addToFront = false) {
685
- let fieldType;
686
- if (field.type.type) {
687
- fieldType = field.type.type;
688
- } else if (field.type.reference?.ref) {
689
- if (isTypeDef2(field.type.reference.ref)) {
690
- fieldType = "Json";
691
- } else {
692
- fieldType = field.type.reference.ref.name;
693
- }
694
- } else {
695
- const unsupported = this.getUnsupportedFieldType(field.type);
696
- if (unsupported) {
697
- fieldType = unsupported;
698
- }
699
- }
700
- if (!fieldType) {
701
- throw new Error(`Field type is not resolved: ${field.$container.name}.${field.name}`);
702
- }
703
- const isArray = (
704
- // typed-JSON fields should be translated to scalar Json type
705
- isTypeDef2(field.type.reference?.ref) ? false : field.type.array
706
- );
707
- const type = new ModelFieldType(fieldType, isArray, field.type.optional);
708
- const attributes = field.attributes.filter((attr) => this.isPrismaAttribute(attr)).filter((attr) => !this.isDefaultWithAuthInvocation(attr)).filter((attr) => (
709
- // when building physical schema, exclude `@default` for id fields inherited from delegate base
710
- !(model_utils_exports.isIdField(field, contextModel) && getDelegateOriginModel(field, contextModel) && attr.decl.$refText === "@default")
711
- )).map((attr) => this.makeFieldAttribute(attr));
712
- const docs = [
713
- ...field.comments
714
- ];
715
- const result = model.addField(field.name, type, attributes, docs, addToFront);
716
- return result;
717
- }
718
- isDefaultWithAuthInvocation(attr) {
719
- if (attr.decl.ref?.name !== "@default") {
720
- return false;
721
- }
722
- const expr = attr.args[0]?.value;
723
- if (!expr) {
724
- return false;
725
- }
726
- return AstUtils.streamAst(expr).some(isAuthInvocation);
727
- }
728
- makeFieldAttribute(attr) {
729
- const attrName = attr.decl.ref.name;
730
- return new FieldAttribute(attrName, attr.args.map((arg) => this.makeAttributeArg(arg)));
731
- }
732
- makeAttributeArg(arg) {
733
- return new AttributeArg(arg.name, this.makeAttributeArgValue(arg.value));
734
- }
735
- makeAttributeArgValue(node) {
736
- if (isLiteralExpr2(node)) {
737
- const argType = match(node.$type).with(StringLiteral, () => "String").with(NumberLiteral, () => "Number").with(BooleanLiteral, () => "Boolean").exhaustive();
738
- return new AttributeArgValue(argType, node.value);
739
- } else if (isArrayExpr(node)) {
740
- return new AttributeArgValue("Array", new Array(...node.items.map((item) => this.makeAttributeArgValue(item))));
741
- } else if (isReferenceExpr(node)) {
742
- return new AttributeArgValue("FieldReference", new FieldReference(node.target.ref.name, node.args.map((arg) => new FieldReferenceArg(arg.name, this.exprToText(arg.value)))));
743
- } else if (isInvocationExpr(node)) {
744
- return new AttributeArgValue("FunctionCall", this.makeFunctionCall(node));
745
- } else {
746
- throw Error(`Unsupported attribute argument expression type: ${node.$type}`);
747
- }
748
- }
749
- exprToText(expr) {
750
- return new ZModelCodeGenerator({
751
- quote: "double"
752
- }).generate(expr);
753
- }
754
- makeFunctionCall(node) {
755
- return new FunctionCall(node.function.ref.name, node.args.map((arg) => {
756
- const val = match(arg.value).when(isStringLiteral, (v) => `"${v.value}"`).when(isLiteralExpr2, (v) => v.value.toString()).when(isNullExpr, () => "null").otherwise(() => {
757
- throw new Error("Function call argument must be literal or null");
758
- });
759
- return new FunctionCallArg(val);
760
- }));
761
- }
762
- generateContainerAttribute(container, attr) {
763
- const attrName = attr.decl.ref.name;
764
- container.attributes.push(new ContainerAttribute(attrName, attr.args.map((arg) => this.makeAttributeArg(arg))));
765
- }
766
- generateEnum(prisma, decl) {
767
- const _enum = prisma.addEnum(decl.name);
768
- for (const field of decl.fields) {
769
- this.generateEnumField(_enum, field);
770
- }
771
- const allAttributes = decl.attributes.filter((attr) => this.isPrismaAttribute(attr));
772
- for (const attr of allAttributes) {
773
- this.generateContainerAttribute(_enum, attr);
774
- }
775
- if (this.datasourceHasSchemasSetting(decl.$container) && !allAttributes.some((attr) => attr.decl.ref?.name === "@@schema")) {
776
- _enum.addAttribute("@@schema", [
777
- new AttributeArg(void 0, new AttributeArgValue("String", this.getDefaultPostgresSchemaName(decl.$container)))
778
- ]);
779
- }
780
- decl.comments.forEach((c) => _enum.addComment(c));
781
- }
782
- generateEnumField(_enum, field) {
783
- const attributes = field.attributes.filter((attr) => this.isPrismaAttribute(attr)).map((attr) => this.makeFieldAttribute(attr));
784
- const docs = [
785
- ...field.comments
786
- ];
787
- _enum.addField(field.name, attributes, docs);
788
- }
789
- generateDelegateRelationForBase(model, decl) {
790
- if (!isDelegateModel2(decl)) {
791
- return;
792
- }
793
- const concreteModels = this.getConcreteModels(decl);
794
- concreteModels.forEach((concrete) => {
795
- const auxName = this.truncate(`${DELEGATE_AUX_RELATION_PREFIX}_${lowerCaseFirst(concrete.name)}`);
796
- model.addField(auxName, new ModelFieldType(concrete.name, false, true));
797
- });
798
- }
799
- generateDelegateRelationForConcrete(model, concreteDecl) {
800
- const base = concreteDecl.baseModel?.ref;
801
- if (!base) {
802
- return;
803
- }
804
- const idFields = getIdFields(base);
805
- const relationField = this.truncate(`${DELEGATE_AUX_RELATION_PREFIX}_${lowerCaseFirst(base.name)}`);
806
- model.addField(relationField, base.name, [
807
- new FieldAttribute("@relation", [
808
- new AttributeArg("fields", new AttributeArgValue("Array", idFields.map((idField) => new AttributeArgValue("FieldReference", new FieldReference(idField))))),
809
- new AttributeArg("references", new AttributeArgValue("Array", idFields.map((idField) => new AttributeArgValue("FieldReference", new FieldReference(idField))))),
810
- new AttributeArg("onDelete", new AttributeArgValue("FieldReference", new FieldReference("Cascade"))),
811
- new AttributeArg("onUpdate", new AttributeArgValue("FieldReference", new FieldReference("Cascade")))
812
- ])
813
- ]);
814
- }
815
- getConcreteModels(dataModel) {
816
- if (!isDelegateModel2(dataModel)) {
817
- return [];
818
- }
819
- return dataModel.$container.declarations.filter((d) => isDataModel2(d) && d !== dataModel && d.baseModel?.ref === dataModel);
820
- }
821
- truncate(name) {
822
- if (name.length <= IDENTIFIER_NAME_MAX_LENGTH) {
823
- return name;
824
- }
825
- const existing = this.shortNameMap.get(name);
826
- if (existing) {
827
- return existing;
828
- }
829
- const baseName = name.slice(0, IDENTIFIER_NAME_MAX_LENGTH);
830
- let index = 0;
831
- let shortName = `${baseName}_${index}`;
832
- while (true) {
833
- const conflict = Array.from(this.shortNameMap.values()).find((v) => v === shortName);
834
- if (!conflict) {
835
- this.shortNameMap.set(name, shortName);
836
- break;
837
- }
838
- index++;
839
- shortName = `${baseName}_${index}`;
840
- }
841
- return shortName;
842
- }
843
- };
844
-
845
- // src/ts-schema-generator.ts
846
- import { invariant } from "@zenstackhq/common-helpers";
847
- import { isArrayExpr as isArrayExpr2, isBinaryExpr, isCollectionPredicateBinding, isDataField, isDataModel as isDataModel3, isDataSource as isDataSource2, isEnum, isEnumField, isInvocationExpr as isInvocationExpr2, isLiteralExpr as isLiteralExpr3, isMemberAccessExpr, isNullExpr as isNullExpr2, isProcedure, isReferenceExpr as isReferenceExpr2, isThisExpr, isTypeDef as isTypeDef3, isUnaryExpr } from "@zenstackhq/language/ast";
848
- import { getAllAttributes as getAllAttributes2, getAllFields as getAllFields3, getAttributeArg, isDataFieldReference } from "@zenstackhq/language/utils";
849
- import fs from "fs";
850
- import path from "path";
851
- import { match as match2 } from "ts-pattern";
852
- import * as ts from "typescript";
853
- var TsSchemaGenerator = class {
854
- static {
855
- __name(this, "TsSchemaGenerator");
856
- }
857
- usedExpressionUtils = false;
858
- usedAttributeApplication = false;
859
- usedFieldDefault = false;
860
- async generate(model, options) {
861
- fs.mkdirSync(options.outDir, {
862
- recursive: true
863
- });
864
- this.generateSchema(model, options);
865
- if (options.generateModelTypes !== false) {
866
- this.generateModelsAndTypeDefs(model, options);
867
- }
868
- if (options.generateInputTypes !== false) {
869
- this.generateInputTypes(model, options);
870
- }
871
- }
872
- generateSchema(model, options) {
873
- const targets = [];
874
- if (!options.liteOnly) {
875
- targets.push({
876
- lite: false,
877
- file: "schema.ts"
878
- });
879
- }
880
- if (options.lite || options.liteOnly) {
881
- targets.push({
882
- lite: true,
883
- file: "schema-lite.ts"
884
- });
885
- }
886
- for (const { lite, file } of targets) {
887
- this.usedExpressionUtils = false;
888
- this.usedAttributeApplication = false;
889
- this.usedFieldDefault = false;
890
- const statements = [];
891
- this.generateSchemaStatements(model, statements, lite);
892
- this.generateBannerComments(statements);
893
- const schemaOutputFile = path.join(options.outDir, file);
894
- const sourceFile = ts.createSourceFile(schemaOutputFile, "", ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS);
895
- const printer = ts.createPrinter();
896
- const result = printer.printList(ts.ListFormat.MultiLine, ts.factory.createNodeArray(statements), sourceFile);
897
- fs.writeFileSync(schemaOutputFile, result);
898
- }
899
- }
900
- generateSchemaStatements(model, statements, lite) {
901
- const schemaClass = this.createSchemaClass(model, lite);
902
- const schemaImportDecl = ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(void 0, void 0, ts.factory.createNamedImports([
903
- ts.factory.createImportSpecifier(true, void 0, ts.factory.createIdentifier("SchemaDef")),
904
- ...this.usedAttributeApplication ? [
905
- ts.factory.createImportSpecifier(true, void 0, ts.factory.createIdentifier("AttributeApplication"))
906
- ] : [],
907
- ...this.usedFieldDefault ? [
908
- ts.factory.createImportSpecifier(true, void 0, ts.factory.createIdentifier("FieldDefault"))
909
- ] : [],
910
- ...this.usedExpressionUtils ? [
911
- ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier("ExpressionUtils"))
912
- ] : []
913
- ])), ts.factory.createStringLiteral("@zenstackhq/schema"));
914
- statements.push(schemaImportDecl);
915
- statements.push(schemaClass);
916
- const schemaDecl = ts.factory.createVariableStatement([
917
- ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)
918
- ], ts.factory.createVariableDeclarationList([
919
- ts.factory.createVariableDeclaration("schema", void 0, void 0, ts.factory.createNewExpression(ts.factory.createIdentifier("SchemaType"), void 0, []))
920
- ], ts.NodeFlags.Const));
921
- statements.push(schemaDecl);
922
- }
923
- createExpressionUtilsCall(method, args) {
924
- this.usedExpressionUtils = true;
925
- return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("ExpressionUtils"), method), void 0, args || []);
926
- }
927
- createSchemaClass(model, lite) {
928
- const members = [
929
- // provider
930
- ts.factory.createPropertyDeclaration(void 0, "provider", void 0, void 0, this.createAsConst(this.createProviderObject(model))),
931
- // models
932
- ts.factory.createPropertyDeclaration(void 0, "models", void 0, void 0, this.createAsConst(this.createModelsObject(model, lite))),
933
- // typeDefs
934
- ...model.declarations.some(isTypeDef3) ? [
935
- ts.factory.createPropertyDeclaration(void 0, "typeDefs", void 0, void 0, this.createAsConst(this.createTypeDefsObject(model, lite)))
936
- ] : []
937
- ];
938
- const enums = model.declarations.filter(isEnum);
939
- if (enums.length > 0) {
940
- members.push(ts.factory.createPropertyDeclaration(void 0, "enums", void 0, void 0, this.createAsConst(ts.factory.createObjectLiteralExpression(enums.map((e) => ts.factory.createPropertyAssignment(e.name, this.createEnumObject(e))), true))));
941
- }
942
- const authType = getAuthDecl(model);
943
- if (authType) {
944
- members.push(ts.factory.createPropertyDeclaration(void 0, "authType", void 0, void 0, this.createAsConst(this.createLiteralNode(authType.name))));
945
- }
946
- const procedures = model.declarations.filter(isProcedure);
947
- if (procedures.length > 0) {
948
- members.push(ts.factory.createPropertyDeclaration(void 0, "procedures", void 0, void 0, this.createAsConst(this.createProceduresObject(procedures))));
949
- }
950
- members.push(ts.factory.createPropertyDeclaration(void 0, "plugins", void 0, void 0, ts.factory.createObjectLiteralExpression([], true)));
951
- const schemaClass = ts.factory.createClassDeclaration([
952
- ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)
953
- ], "SchemaType", void 0, [
954
- ts.factory.createHeritageClause(ts.SyntaxKind.ImplementsKeyword, [
955
- ts.factory.createExpressionWithTypeArguments(ts.factory.createIdentifier("SchemaDef"), void 0)
956
- ])
957
- ], members);
958
- return schemaClass;
959
- }
960
- createAsConst(expr) {
961
- return ts.factory.createAsExpression(expr, ts.factory.createTypeReferenceNode("const"));
962
- }
963
- createAttributesTypeAssertion(expr) {
964
- this.usedAttributeApplication = true;
965
- return ts.factory.createAsExpression(expr, ts.factory.createTypeOperatorNode(ts.SyntaxKind.ReadonlyKeyword, ts.factory.createArrayTypeNode(ts.factory.createTypeReferenceNode("AttributeApplication"))));
966
- }
967
- createDefaultTypeAssertion(expr) {
968
- this.usedFieldDefault = true;
969
- return ts.factory.createAsExpression(expr, ts.factory.createTypeReferenceNode("FieldDefault"));
970
- }
971
- createProviderObject(model) {
972
- const dsProvider = this.getDataSourceProvider(model);
973
- const defaultSchema = this.getDataSourceDefaultSchema(model);
974
- return ts.factory.createObjectLiteralExpression([
975
- ts.factory.createPropertyAssignment("type", ts.factory.createStringLiteral(dsProvider)),
976
- ...defaultSchema ? [
977
- ts.factory.createPropertyAssignment("defaultSchema", ts.factory.createStringLiteral(defaultSchema))
978
- ] : []
979
- ], true);
980
- }
981
- createModelsObject(model, lite) {
982
- return ts.factory.createObjectLiteralExpression(this.getAllDataModels(model).map((dm) => ts.factory.createPropertyAssignment(dm.name, this.createDataModelObject(dm, lite))), true);
983
- }
984
- getAllDataModels(model) {
985
- return model.declarations.filter((d) => isDataModel3(d) && !hasAttribute(d, "@@ignore"));
986
- }
987
- getAllTypeDefs(model) {
988
- return model.declarations.filter((d) => isTypeDef3(d) && !hasAttribute(d, "@@ignore"));
989
- }
990
- createTypeDefsObject(model, lite) {
991
- return ts.factory.createObjectLiteralExpression(this.getAllTypeDefs(model).map((td) => ts.factory.createPropertyAssignment(td.name, this.createTypeDefObject(td, lite))), true);
992
- }
993
- createDataModelObject(dm, lite) {
994
- const allFields = getAllFields3(dm);
995
- const allAttributes = lite ? [] : getAllAttributes2(dm).filter((attr) => {
996
- if (attr.decl.$refText === "@@delegate" && attr.$container !== dm) {
997
- return false;
998
- }
999
- return true;
1000
- });
1001
- const subModels = this.getSubModels(dm);
1002
- const fields = [
1003
- // name
1004
- ts.factory.createPropertyAssignment("name", ts.factory.createStringLiteral(dm.name)),
1005
- // baseModel
1006
- ...dm.baseModel ? [
1007
- ts.factory.createPropertyAssignment("baseModel", ts.factory.createStringLiteral(dm.baseModel.$refText))
1008
- ] : [],
1009
- // fields
1010
- ts.factory.createPropertyAssignment("fields", ts.factory.createObjectLiteralExpression(allFields.map((field) => ts.factory.createPropertyAssignment(field.name, this.createDataFieldObject(field, dm, lite))), true)),
1011
- // attributes
1012
- ...allAttributes.length > 0 ? [
1013
- ts.factory.createPropertyAssignment("attributes", this.createAttributesTypeAssertion(ts.factory.createArrayLiteralExpression(allAttributes.map((attr) => this.createAttributeObject(attr)), true)))
1014
- ] : [],
1015
- // idFields
1016
- ts.factory.createPropertyAssignment("idFields", ts.factory.createArrayLiteralExpression(getIdFields(dm).map((idField) => ts.factory.createStringLiteral(idField)))),
1017
- // uniqueFields
1018
- ts.factory.createPropertyAssignment("uniqueFields", this.createUniqueFieldsObject(dm)),
1019
- // isDelegate
1020
- ...isDelegateModel(dm) ? [
1021
- ts.factory.createPropertyAssignment("isDelegate", ts.factory.createTrue())
1022
- ] : [],
1023
- // subModels
1024
- ...subModels.length > 0 ? [
1025
- ts.factory.createPropertyAssignment("subModels", ts.factory.createArrayLiteralExpression(subModels.map((subModel) => ts.factory.createStringLiteral(subModel))))
1026
- ] : [],
1027
- ...dm.isView ? [
1028
- ts.factory.createPropertyAssignment("isView", ts.factory.createTrue())
1029
- ] : []
1030
- ];
1031
- const computedFields = dm.fields.filter((f) => hasAttribute(f, "@computed"));
1032
- if (computedFields.length > 0) {
1033
- fields.push(ts.factory.createPropertyAssignment("computedFields", this.createComputedFieldsObject(computedFields)));
1034
- }
1035
- return ts.factory.createObjectLiteralExpression(fields, true);
1036
- }
1037
- getSubModels(dm) {
1038
- return dm.$container.declarations.filter(isDataModel3).filter((d) => d.baseModel?.ref === dm).map((d) => d.name);
1039
- }
1040
- createTypeDefObject(td, lite) {
1041
- const allFields = getAllFields3(td);
1042
- const allAttributes = getAllAttributes2(td);
1043
- const fields = [
1044
- // name
1045
- ts.factory.createPropertyAssignment("name", ts.factory.createStringLiteral(td.name)),
1046
- // fields
1047
- ts.factory.createPropertyAssignment("fields", ts.factory.createObjectLiteralExpression(allFields.map((field) => ts.factory.createPropertyAssignment(field.name, this.createDataFieldObject(field, void 0, lite))), true)),
1048
- // attributes
1049
- ...allAttributes.length > 0 ? [
1050
- ts.factory.createPropertyAssignment("attributes", this.createAttributesTypeAssertion(ts.factory.createArrayLiteralExpression(allAttributes.map((attr) => this.createAttributeObject(attr)), true)))
1051
- ] : []
1052
- ];
1053
- return ts.factory.createObjectLiteralExpression(fields, true);
1054
- }
1055
- createComputedFieldsObject(fields) {
1056
- return ts.factory.createObjectLiteralExpression(fields.map((field) => ts.factory.createMethodDeclaration(void 0, void 0, field.name, void 0, void 0, [
1057
- // parameter: `context: { modelAlias: string }`
1058
- ts.factory.createParameterDeclaration(void 0, void 0, "_context", void 0, ts.factory.createTypeLiteralNode([
1059
- ts.factory.createPropertySignature(void 0, "modelAlias", void 0, ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword))
1060
- ]), void 0)
1061
- ], ts.factory.createTypeReferenceNode(this.mapFieldTypeToTSType(field.type)), ts.factory.createBlock([
1062
- ts.factory.createThrowStatement(ts.factory.createNewExpression(ts.factory.createIdentifier("Error"), void 0, [
1063
- ts.factory.createStringLiteral("This is a stub for computed field")
1064
- ]))
1065
- ], true))), true);
1066
- }
1067
- createUpdatedAtObject(ignoreArg) {
1068
- return ts.factory.createObjectLiteralExpression([
1069
- ts.factory.createPropertyAssignment("ignore", ts.factory.createArrayLiteralExpression(ignoreArg.value.items.map((item) => ts.factory.createStringLiteral(item.target.$refText))))
1070
- ]);
1071
- }
1072
- mapFieldTypeToTSType(type) {
1073
- let result = match2(type.type).with("String", () => "string").with("Boolean", () => "boolean").with("Int", () => "number").with("Float", () => "number").with("BigInt", () => "bigint").with("Decimal", () => "number").otherwise(() => "unknown");
1074
- if (type.array) {
1075
- result = `${result}[]`;
1076
- }
1077
- if (type.optional) {
1078
- result = `${result} | null`;
1079
- }
1080
- return result;
1081
- }
1082
- createDataFieldObject(field, contextModel, lite) {
1083
- const objectFields = [
1084
- // name
1085
- ts.factory.createPropertyAssignment("name", ts.factory.createStringLiteral(field.name)),
1086
- // type
1087
- ts.factory.createPropertyAssignment("type", this.generateFieldTypeLiteral(field))
1088
- ];
1089
- if (contextModel && model_utils_exports.isIdField(field, contextModel)) {
1090
- objectFields.push(ts.factory.createPropertyAssignment("id", ts.factory.createTrue()));
1091
- }
1092
- if (isUniqueField(field)) {
1093
- objectFields.push(ts.factory.createPropertyAssignment("unique", ts.factory.createTrue()));
1094
- }
1095
- if (field.type.optional) {
1096
- objectFields.push(ts.factory.createPropertyAssignment("optional", ts.factory.createTrue()));
1097
- }
1098
- if (field.type.array) {
1099
- objectFields.push(ts.factory.createPropertyAssignment("array", ts.factory.createTrue()));
1100
- }
1101
- const updatedAtAttrib = getAttribute(field, "@updatedAt");
1102
- if (updatedAtAttrib) {
1103
- const ignoreArg = updatedAtAttrib.args.find((arg) => arg.$resolvedParam?.name === "ignore");
1104
- objectFields.push(ts.factory.createPropertyAssignment("updatedAt", ignoreArg ? this.createUpdatedAtObject(ignoreArg) : ts.factory.createTrue()));
1105
- }
1106
- if (hasAttribute(field, "@omit")) {
1107
- objectFields.push(ts.factory.createPropertyAssignment("omit", ts.factory.createTrue()));
1108
- }
1109
- if (contextModel && // id fields are duplicated in inherited models
1110
- !isIdField(field, contextModel)) {
1111
- const delegateOrigin = getDelegateOriginModel(field, contextModel);
1112
- if (delegateOrigin) {
1113
- objectFields.push(ts.factory.createPropertyAssignment("originModel", ts.factory.createStringLiteral(delegateOrigin)));
1114
- }
1115
- }
1116
- if (this.isDiscriminatorField(field)) {
1117
- objectFields.push(ts.factory.createPropertyAssignment("isDiscriminator", ts.factory.createTrue()));
1118
- }
1119
- if (!lite && field.attributes.length > 0) {
1120
- objectFields.push(ts.factory.createPropertyAssignment("attributes", this.createAttributesTypeAssertion(ts.factory.createArrayLiteralExpression(field.attributes.map((attr) => this.createAttributeObject(attr))))));
1121
- }
1122
- const defaultValue = this.getFieldMappedDefault(field);
1123
- if (defaultValue !== void 0) {
1124
- let defaultExpr;
1125
- if (defaultValue === null) {
1126
- defaultExpr = this.createExpressionUtilsCall("_null");
1127
- } else if (typeof defaultValue === "object" && !Array.isArray(defaultValue)) {
1128
- if ("call" in defaultValue) {
1129
- defaultExpr = this.createExpressionUtilsCall("call", [
1130
- ts.factory.createStringLiteral(defaultValue.call),
1131
- ...defaultValue.args.length > 0 ? [
1132
- ts.factory.createArrayLiteralExpression(defaultValue.args.map((arg) => this.createExpressionUtilsCall("literal", [
1133
- this.createLiteralNode(arg)
1134
- ])))
1135
- ] : []
1136
- ]);
1137
- } else if ("authMember" in defaultValue) {
1138
- defaultExpr = this.createExpressionUtilsCall("member", [
1139
- this.createExpressionUtilsCall("call", [
1140
- ts.factory.createStringLiteral("auth")
1141
- ]),
1142
- ts.factory.createArrayLiteralExpression(defaultValue.authMember.map((m) => ts.factory.createStringLiteral(m)))
1143
- ]);
1144
- } else {
1145
- throw new Error(`Unsupported default value type for field ${field.name}`);
1146
- }
1147
- } else if (Array.isArray(defaultValue)) {
1148
- defaultExpr = ts.factory.createArrayLiteralExpression(defaultValue.map((item) => this.createLiteralNode(item)));
1149
- } else {
1150
- defaultExpr = this.createLiteralNode(defaultValue);
1151
- }
1152
- objectFields.push(ts.factory.createPropertyAssignment("default", this.createDefaultTypeAssertion(defaultExpr)));
1153
- }
1154
- if (hasAttribute(field, "@computed")) {
1155
- objectFields.push(ts.factory.createPropertyAssignment("computed", ts.factory.createTrue()));
1156
- }
1157
- if (isDataModel3(field.type.reference?.ref)) {
1158
- objectFields.push(ts.factory.createPropertyAssignment("relation", this.createRelationObject(field)));
1159
- }
1160
- const fkFor = this.getForeignKeyFor(field);
1161
- if (fkFor && fkFor.length > 0) {
1162
- objectFields.push(ts.factory.createPropertyAssignment("foreignKeyFor", ts.factory.createAsExpression(ts.factory.createArrayLiteralExpression(fkFor.map((fk) => ts.factory.createStringLiteral(fk)), true), ts.factory.createTypeOperatorNode(ts.SyntaxKind.ReadonlyKeyword, ts.factory.createArrayTypeNode(ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword))))));
1163
- }
1164
- return ts.factory.createObjectLiteralExpression(objectFields, true);
1165
- }
1166
- isDiscriminatorField(field) {
1167
- const origin = field.$container;
1168
- return getAttribute(origin, "@@delegate")?.args.some((arg) => arg.$resolvedParam.name === "discriminator" && isDataFieldReference(arg.value) && arg.value.target.ref === field);
1169
- }
1170
- getDataSourceProvider(model) {
1171
- const dataSource = model.declarations.find(isDataSource2);
1172
- invariant(dataSource, "No data source found in the model");
1173
- const providerExpr = dataSource.fields.find((f) => f.name === "provider")?.value;
1174
- invariant(isLiteralExpr3(providerExpr) && typeof providerExpr.value === "string", "Provider must be a string literal");
1175
- return providerExpr.value;
1176
- }
1177
- getDataSourceDefaultSchema(model) {
1178
- const dataSource = model.declarations.find(isDataSource2);
1179
- invariant(dataSource, "No data source found in the model");
1180
- const defaultSchemaExpr = dataSource.fields.find((f) => f.name === "defaultSchema")?.value;
1181
- if (!defaultSchemaExpr) {
1182
- return void 0;
1183
- }
1184
- invariant(isLiteralExpr3(defaultSchemaExpr) && typeof defaultSchemaExpr.value === "string", "Default schema must be a string literal");
1185
- return defaultSchemaExpr.value;
1186
- }
1187
- getFieldMappedDefault(field) {
1188
- const defaultAttr = getAttribute(field, "@default");
1189
- if (!defaultAttr) {
1190
- return void 0;
1191
- }
1192
- const defaultValue = defaultAttr.args[0]?.value;
1193
- invariant(defaultValue, "Expected a default value");
1194
- return this.getMappedValue(defaultValue, field.type);
1195
- }
1196
- getMappedValue(expr, fieldType) {
1197
- if (isLiteralExpr3(expr)) {
1198
- const lit = expr.value;
1199
- return fieldType.type === "Boolean" ? lit : [
1200
- "Int",
1201
- "Float",
1202
- "Decimal",
1203
- "BigInt"
1204
- ].includes(fieldType.type) ? Number(lit) : lit;
1205
- } else if (isArrayExpr2(expr)) {
1206
- return expr.items.map((item) => this.getMappedValue(item, fieldType));
1207
- } else if (isReferenceExpr2(expr) && isEnumField(expr.target.ref)) {
1208
- return expr.target.ref.name;
1209
- } else if (isInvocationExpr2(expr)) {
1210
- return {
1211
- call: expr.function.$refText,
1212
- args: expr.args.map((arg) => this.getLiteral(arg.value))
1213
- };
1214
- } else if (this.isAuthMemberAccess(expr)) {
1215
- return {
1216
- authMember: this.getMemberAccessChain(expr)
1217
- };
1218
- } else if (isNullExpr2(expr)) {
1219
- return null;
1220
- } else {
1221
- throw new Error(`Unsupported expression type: ${expr.$type}`);
1222
- }
1223
- }
1224
- getMemberAccessChain(expr) {
1225
- if (!isMemberAccessExpr(expr.operand)) {
1226
- return [
1227
- expr.member.$refText
1228
- ];
1229
- } else {
1230
- return [
1231
- ...this.getMemberAccessChain(expr.operand),
1232
- expr.member.$refText
1233
- ];
1234
- }
1235
- }
1236
- isAuthMemberAccess(expr) {
1237
- if (isMemberAccessExpr(expr)) {
1238
- return this.isAuthInvocation(expr.operand) || this.isAuthMemberAccess(expr.operand);
1239
- } else {
1240
- return false;
1241
- }
1242
- }
1243
- isAuthInvocation(expr) {
1244
- return isInvocationExpr2(expr) && expr.function.$refText === "auth" && model_utils_exports.isFromStdlib(expr.function.ref);
1245
- }
1246
- createRelationObject(field) {
1247
- const relationFields = [];
1248
- const oppositeRelation = this.getOppositeRelationField(field);
1249
- if (oppositeRelation) {
1250
- relationFields.push(ts.factory.createPropertyAssignment("opposite", ts.factory.createStringLiteral(oppositeRelation.name)));
1251
- }
1252
- const relationName = this.getRelationName(field);
1253
- if (relationName) {
1254
- relationFields.push(ts.factory.createPropertyAssignment("name", ts.factory.createStringLiteral(relationName)));
1255
- }
1256
- const relation = getAttribute(field, "@relation");
1257
- const fkFields = [];
1258
- if (relation) {
1259
- for (const arg of relation.args) {
1260
- const param = arg.$resolvedParam.name;
1261
- if (param === "fields" || param === "references") {
1262
- const fieldNames = this.getReferenceNames(arg.value);
1263
- if (fieldNames) {
1264
- if (param === "fields") {
1265
- fkFields.push(...fieldNames);
1266
- }
1267
- relationFields.push(ts.factory.createPropertyAssignment(param, ts.factory.createArrayLiteralExpression(fieldNames.map((el) => ts.factory.createStringLiteral(el)))));
1268
- }
1269
- }
1270
- if (param === "onDelete" || param === "onUpdate") {
1271
- const action = arg.value.target.$refText;
1272
- relationFields.push(ts.factory.createPropertyAssignment(param, ts.factory.createStringLiteral(action)));
1273
- }
1274
- }
1275
- }
1276
- if (fkFields.length > 0) {
1277
- const allHaveDefault = fkFields.every((fieldName) => {
1278
- const fieldDef = field.$container.fields.find((f) => f.name === fieldName);
1279
- return fieldDef && hasAttribute(fieldDef, "@default");
1280
- });
1281
- if (allHaveDefault) {
1282
- relationFields.push(ts.factory.createPropertyAssignment("hasDefault", ts.factory.createTrue()));
1283
- }
1284
- }
1285
- return ts.factory.createObjectLiteralExpression(relationFields);
1286
- }
1287
- getReferenceNames(expr) {
1288
- return isArrayExpr2(expr) && expr.items.map((item) => item.target.$refText);
1289
- }
1290
- getForeignKeyFor(field) {
1291
- const result = [];
1292
- for (const f of field.$container.fields) {
1293
- const relation = getAttribute(f, "@relation");
1294
- if (relation) {
1295
- for (const arg of relation.args) {
1296
- if (arg.name === "fields" && isArrayExpr2(arg.value) && arg.value.items.some((el) => isReferenceExpr2(el) && el.target.ref === field)) {
1297
- result.push(f.name);
1298
- }
1299
- }
1300
- }
1301
- }
1302
- return result;
1303
- }
1304
- getOppositeRelationField(field) {
1305
- if (!field.type.reference?.ref || !isDataModel3(field.type.reference?.ref)) {
1306
- return void 0;
1307
- }
1308
- const sourceModel = field.$container;
1309
- const targetModel = field.type.reference.ref;
1310
- const relationName = this.getRelationName(field);
1311
- for (const otherField of targetModel.fields) {
1312
- if (otherField === field) {
1313
- continue;
1314
- }
1315
- if (otherField.type.reference?.ref === sourceModel) {
1316
- if (relationName) {
1317
- const otherRelationName = this.getRelationName(otherField);
1318
- if (otherRelationName === relationName) {
1319
- return otherField;
1320
- }
1321
- } else {
1322
- return otherField;
1323
- }
1324
- }
1325
- }
1326
- return void 0;
1327
- }
1328
- getRelationName(field) {
1329
- const relation = getAttribute(field, "@relation");
1330
- if (relation) {
1331
- const nameArg = relation.args.find((arg) => arg.$resolvedParam.name === "name");
1332
- if (nameArg) {
1333
- invariant(isLiteralExpr3(nameArg.value), "name must be a literal");
1334
- return nameArg.value.value;
1335
- }
1336
- }
1337
- return void 0;
1338
- }
1339
- createUniqueFieldsObject(dm) {
1340
- const properties = [];
1341
- const allFields = getAllFields3(dm);
1342
- for (const field of allFields) {
1343
- if (hasAttribute(field, "@id") || hasAttribute(field, "@unique")) {
1344
- properties.push(ts.factory.createPropertyAssignment(field.name, ts.factory.createObjectLiteralExpression([
1345
- ts.factory.createPropertyAssignment("type", this.generateFieldTypeLiteral(field))
1346
- ])));
1347
- }
1348
- }
1349
- const allAttributes = getAllAttributes2(dm);
1350
- const seenKeys = /* @__PURE__ */ new Set();
1351
- for (const attr of allAttributes) {
1352
- if (attr.decl.$refText === "@@id" || attr.decl.$refText === "@@unique") {
1353
- const fieldsArg = getAttributeArg(attr, "fields");
1354
- if (!fieldsArg) {
1355
- continue;
1356
- }
1357
- const fieldNames = this.getReferenceNames(fieldsArg);
1358
- if (!fieldNames) {
1359
- continue;
1360
- }
1361
- if (fieldNames.length === 1) {
1362
- const fieldDef = allFields.find((f) => f.name === fieldNames[0]);
1363
- properties.push(ts.factory.createPropertyAssignment(fieldNames[0], ts.factory.createObjectLiteralExpression([
1364
- ts.factory.createPropertyAssignment("type", this.generateFieldTypeLiteral(fieldDef))
1365
- ])));
1366
- } else {
1367
- const key = this.getCompoundUniqueKey(attr, fieldNames);
1368
- if (seenKeys.has(key)) {
1369
- continue;
1370
- }
1371
- seenKeys.add(key);
1372
- properties.push(ts.factory.createPropertyAssignment(key, ts.factory.createObjectLiteralExpression(fieldNames.map((field) => {
1373
- const fieldDef = allFields.find((f) => f.name === field);
1374
- return ts.factory.createPropertyAssignment(field, ts.factory.createObjectLiteralExpression([
1375
- ts.factory.createPropertyAssignment("type", this.generateFieldTypeLiteral(fieldDef))
1376
- ]));
1377
- }))));
1378
- }
1379
- }
1380
- }
1381
- return ts.factory.createObjectLiteralExpression(properties, true);
1382
- }
1383
- getCompoundUniqueKey(attr, fieldNames) {
1384
- const nameArg = attr.args.find((arg) => arg.$resolvedParam.name === "name");
1385
- if (nameArg && isLiteralExpr3(nameArg.value)) {
1386
- return nameArg.value.value;
1387
- } else {
1388
- return fieldNames.join("_");
1389
- }
1390
- }
1391
- generateFieldTypeLiteral(field) {
1392
- invariant(field.type.type || field.type.reference || field.type.unsupported, "Field type must be a primitive, reference, or Unsupported");
1393
- return field.type.type ? ts.factory.createStringLiteral(field.type.type) : field.type.reference ? ts.factory.createStringLiteral(field.type.reference.$refText) : ts.factory.createStringLiteral("Unsupported");
1394
- }
1395
- createEnumObject(e) {
1396
- return ts.factory.createObjectLiteralExpression([
1397
- ts.factory.createPropertyAssignment("name", ts.factory.createStringLiteral(e.name)),
1398
- ts.factory.createPropertyAssignment("values", ts.factory.createObjectLiteralExpression(e.fields.map((f) => ts.factory.createPropertyAssignment(f.name, ts.factory.createStringLiteral(f.name))), true)),
1399
- // only generate `fields` if there are attributes on the fields
1400
- ...e.fields.some((f) => f.attributes.length > 0) ? [
1401
- ts.factory.createPropertyAssignment("fields", ts.factory.createObjectLiteralExpression(e.fields.map((field) => ts.factory.createPropertyAssignment(field.name, ts.factory.createObjectLiteralExpression([
1402
- ts.factory.createPropertyAssignment("name", ts.factory.createStringLiteral(field.name)),
1403
- ...field.attributes.length > 0 ? [
1404
- ts.factory.createPropertyAssignment("attributes", this.createAttributesTypeAssertion(ts.factory.createArrayLiteralExpression(field.attributes?.map((attr) => this.createAttributeObject(attr)) ?? [], true)))
1405
- ] : []
1406
- ], true))), true))
1407
- ] : [],
1408
- ...e.attributes.length > 0 ? [
1409
- ts.factory.createPropertyAssignment("attributes", this.createAttributesTypeAssertion(ts.factory.createArrayLiteralExpression(e.attributes.map((attr) => this.createAttributeObject(attr)), true)))
1410
- ] : []
1411
- ], true);
1412
- }
1413
- getLiteral(expr) {
1414
- if (!isLiteralExpr3(expr)) {
1415
- throw new Error("Expected a literal expression");
1416
- }
1417
- switch (expr?.$type) {
1418
- case "StringLiteral":
1419
- case "BooleanLiteral":
1420
- return expr.value;
1421
- case "NumberLiteral":
1422
- return parseFloat(expr.value);
1423
- default:
1424
- throw new Error("Unsupported literal type");
1425
- }
1426
- }
1427
- createLiteralNode(arg) {
1428
- return arg === null ? ts.factory.createNull() : typeof arg === "string" ? ts.factory.createStringLiteral(arg) : typeof arg === "number" ? this.createNumberLiteral(arg) : arg === true ? ts.factory.createTrue() : arg === false ? ts.factory.createFalse() : void 0;
1429
- }
1430
- createNumberLiteral(arg) {
1431
- return arg < 0 ? ts.factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, ts.factory.createNumericLiteral(-arg)) : ts.factory.createNumericLiteral(arg);
1432
- }
1433
- createProceduresObject(procedures) {
1434
- return ts.factory.createObjectLiteralExpression(procedures.map((proc) => ts.factory.createPropertyAssignment(proc.name, this.createProcedureObject(proc))), true);
1435
- }
1436
- createProcedureObject(proc) {
1437
- const params = ts.factory.createObjectLiteralExpression(proc.params.map((param) => ts.factory.createPropertyAssignment(param.name, ts.factory.createObjectLiteralExpression([
1438
- ts.factory.createPropertyAssignment("name", ts.factory.createStringLiteral(param.name)),
1439
- ...param.optional ? [
1440
- ts.factory.createPropertyAssignment("optional", ts.factory.createTrue())
1441
- ] : [],
1442
- ...param.type.array ? [
1443
- ts.factory.createPropertyAssignment("array", ts.factory.createTrue())
1444
- ] : [],
1445
- ts.factory.createPropertyAssignment("type", ts.factory.createStringLiteral(param.type.type ?? param.type.reference.$refText))
1446
- ]))), true);
1447
- return ts.factory.createObjectLiteralExpression([
1448
- ts.factory.createPropertyAssignment("params", params),
1449
- ts.factory.createPropertyAssignment("returnType", ts.factory.createStringLiteral(proc.returnType.type ?? proc.returnType.reference.$refText)),
1450
- ...proc.returnType.array ? [
1451
- ts.factory.createPropertyAssignment("returnArray", ts.factory.createTrue())
1452
- ] : [],
1453
- ...proc.mutation ? [
1454
- ts.factory.createPropertyAssignment("mutation", ts.factory.createTrue())
1455
- ] : []
1456
- ], true);
1457
- }
1458
- generateBannerComments(statements) {
1459
- const banner = `////////////////////////////////////////////////////////////////////////////////////////////
1460
- // DO NOT MODIFY THIS FILE //
1461
- // This file is automatically generated by ZenStack CLI and should not be manually updated. //
1462
- //////////////////////////////////////////////////////////////////////////////////////////////
1463
-
1464
- /* eslint-disable */
1465
-
1466
- `;
1467
- ts.addSyntheticLeadingComment(statements[0], ts.SyntaxKind.SingleLineCommentTrivia, banner);
1468
- }
1469
- createAttributeObject(attr) {
1470
- return ts.factory.createObjectLiteralExpression([
1471
- ts.factory.createPropertyAssignment("name", ts.factory.createStringLiteral(attr.decl.$refText)),
1472
- ...attr.args.length > 0 ? [
1473
- ts.factory.createPropertyAssignment("args", ts.factory.createArrayLiteralExpression(attr.args.map((arg) => this.createAttributeArg(arg))))
1474
- ] : []
1475
- ]);
1476
- }
1477
- createAttributeArg(arg) {
1478
- return ts.factory.createObjectLiteralExpression([
1479
- // name
1480
- ...arg.$resolvedParam?.name ? [
1481
- ts.factory.createPropertyAssignment("name", ts.factory.createStringLiteral(arg.$resolvedParam.name))
1482
- ] : [],
1483
- // value
1484
- ts.factory.createPropertyAssignment("value", this.createExpression(arg.value))
1485
- ]);
1486
- }
1487
- createExpression(value) {
1488
- return match2(value).when(isLiteralExpr3, (expr) => this.createLiteralExpression(expr.$type, expr.value)).when(isInvocationExpr2, (expr) => this.createCallExpression(expr)).when(isReferenceExpr2, (expr) => this.createRefExpression(expr)).when(isArrayExpr2, (expr) => this.createArrayExpression(expr)).when(isUnaryExpr, (expr) => this.createUnaryExpression(expr)).when(isBinaryExpr, (expr) => this.createBinaryExpression(expr)).when(isMemberAccessExpr, (expr) => this.createMemberExpression(expr)).when(isNullExpr2, () => this.createNullExpression()).when(isThisExpr, () => this.createThisExpression()).otherwise(() => {
1489
- throw new Error(`Unsupported attribute arg value: ${value.$type}`);
1490
- });
1491
- }
1492
- createThisExpression() {
1493
- return this.createExpressionUtilsCall("_this");
1494
- }
1495
- createMemberExpression(expr) {
1496
- const members = [];
1497
- let current = expr;
1498
- while (isMemberAccessExpr(current)) {
1499
- members.unshift(current.member.$refText);
1500
- current = current.operand;
1501
- }
1502
- const receiver = current;
1503
- const args = [
1504
- this.createExpression(receiver),
1505
- ts.factory.createArrayLiteralExpression(members.map((m) => ts.factory.createStringLiteral(m)))
1506
- ];
1507
- return this.createExpressionUtilsCall("member", args);
1508
- }
1509
- createNullExpression() {
1510
- return this.createExpressionUtilsCall("_null");
1511
- }
1512
- createBinaryExpression(expr) {
1513
- const args = [
1514
- this.createExpression(expr.left),
1515
- this.createLiteralNode(expr.operator),
1516
- this.createExpression(expr.right)
1517
- ];
1518
- if (expr.binding) {
1519
- args.push(this.createLiteralNode(expr.binding.name));
1520
- }
1521
- return this.createExpressionUtilsCall("binary", args);
1522
- }
1523
- createUnaryExpression(expr) {
1524
- return this.createExpressionUtilsCall("unary", [
1525
- this.createLiteralNode(expr.operator),
1526
- this.createExpression(expr.operand)
1527
- ]);
1528
- }
1529
- createArrayExpression(expr) {
1530
- const arrayResolved = expr.$resolvedType?.decl;
1531
- const arrayType = typeof arrayResolved === "string" ? arrayResolved : arrayResolved?.name;
1532
- invariant(arrayType, "Array type must be resolved to a string or declaration");
1533
- return this.createExpressionUtilsCall("array", [
1534
- this.createLiteralNode(arrayType),
1535
- ts.factory.createArrayLiteralExpression(expr.items.map((item) => this.createExpression(item)))
1536
- ]);
1537
- }
1538
- createRefExpression(expr) {
1539
- const target = expr.target.ref;
1540
- return match2(target).when(isDataField, () => this.createExpressionUtilsCall("field", [
1541
- this.createLiteralNode(expr.target.$refText)
1542
- ])).when(isEnumField, () => this.createLiteralExpression("StringLiteral", expr.target.$refText)).when(isCollectionPredicateBinding, () => this.createExpressionUtilsCall("binding", [
1543
- this.createLiteralNode(expr.target.$refText)
1544
- ])).otherwise(() => {
1545
- throw Error(`Unsupported reference type: ${expr.target.$refText}`);
1546
- });
1547
- }
1548
- createCallExpression(expr) {
1549
- return this.createExpressionUtilsCall("call", [
1550
- ts.factory.createStringLiteral(expr.function.$refText),
1551
- ...expr.args.length > 0 ? [
1552
- ts.factory.createArrayLiteralExpression(expr.args.map((arg) => this.createExpression(arg.value)))
1553
- ] : []
1554
- ]);
1555
- }
1556
- createLiteralExpression(type, value) {
1557
- return match2(type).with("BooleanLiteral", () => this.createExpressionUtilsCall("literal", [
1558
- this.createLiteralNode(value)
1559
- ])).with("NumberLiteral", () => this.createExpressionUtilsCall("literal", [
1560
- ts.factory.createIdentifier(value)
1561
- ])).with("StringLiteral", () => this.createExpressionUtilsCall("literal", [
1562
- this.createLiteralNode(value)
1563
- ])).otherwise(() => {
1564
- throw new Error(`Unsupported literal type: ${type}`);
1565
- });
1566
- }
1567
- generateModelsAndTypeDefs(model, options) {
1568
- const statements = [];
1569
- statements.push(this.generateSchemaImport(model, true, true, !!(options.lite || options.liteOnly), options.importWithFileExtension));
1570
- statements.push(ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(true, void 0, ts.factory.createNamedImports([
1571
- ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier(`ModelResult as $ModelResult`)),
1572
- ...model.declarations.some(isTypeDef3) ? [
1573
- ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier(`TypeDefResult as $TypeDefResult`))
1574
- ] : []
1575
- ])), ts.factory.createStringLiteral("@zenstackhq/orm")));
1576
- const dataModels = this.getAllDataModels(model);
1577
- for (const dm of dataModels) {
1578
- let modelType = ts.factory.createTypeAliasDeclaration([
1579
- ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)
1580
- ], dm.name, void 0, ts.factory.createTypeReferenceNode("$ModelResult", [
1581
- ts.factory.createTypeReferenceNode("$Schema"),
1582
- ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(dm.name))
1583
- ]));
1584
- if (dm.comments.length > 0) {
1585
- modelType = this.generateDocs(modelType, dm);
1586
- }
1587
- statements.push(modelType);
1588
- }
1589
- const typeDefs = this.getAllTypeDefs(model);
1590
- for (const td of typeDefs) {
1591
- let typeDef = ts.factory.createTypeAliasDeclaration([
1592
- ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)
1593
- ], td.name, void 0, ts.factory.createTypeReferenceNode("$TypeDefResult", [
1594
- ts.factory.createTypeReferenceNode("$Schema"),
1595
- ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(td.name))
1596
- ]));
1597
- if (td.comments.length > 0) {
1598
- typeDef = this.generateDocs(typeDef, td);
1599
- }
1600
- statements.push(typeDef);
1601
- }
1602
- const enums = model.declarations.filter(isEnum);
1603
- for (const e of enums) {
1604
- let enumDecl = ts.factory.createVariableStatement([
1605
- ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)
1606
- ], ts.factory.createVariableDeclarationList([
1607
- ts.factory.createVariableDeclaration(e.name, void 0, void 0, ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("$schema"), ts.factory.createIdentifier("enums")), ts.factory.createIdentifier(e.name)), ts.factory.createIdentifier("values")))
1608
- ], ts.NodeFlags.Const));
1609
- if (e.comments.length > 0) {
1610
- enumDecl = this.generateDocs(enumDecl, e);
1611
- }
1612
- statements.push(enumDecl);
1613
- let typeAlias = ts.factory.createTypeAliasDeclaration([
1614
- ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)
1615
- ], e.name, void 0, ts.factory.createIndexedAccessTypeNode(ts.factory.createTypeQueryNode(ts.factory.createIdentifier(e.name)), ts.factory.createTypeOperatorNode(ts.SyntaxKind.KeyOfKeyword, ts.factory.createTypeQueryNode(ts.factory.createIdentifier(e.name)))));
1616
- if (e.comments.length > 0) {
1617
- typeAlias = this.generateDocs(typeAlias, e);
1618
- }
1619
- statements.push(typeAlias);
1620
- }
1621
- this.generateBannerComments(statements);
1622
- const outputFile = path.join(options.outDir, "models.ts");
1623
- const sourceFile = ts.createSourceFile(outputFile, "", ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS);
1624
- const printer = ts.createPrinter();
1625
- const result = printer.printList(ts.ListFormat.MultiLine, ts.factory.createNodeArray(statements), sourceFile);
1626
- fs.writeFileSync(outputFile, result);
1627
- }
1628
- generateSchemaImport(model, schemaObject, schemaType, useLite, importWithFileExtension) {
1629
- const importSpecifiers = [];
1630
- if (schemaObject) {
1631
- if (model.declarations.some(isEnum)) {
1632
- importSpecifiers.push(ts.factory.createImportSpecifier(false, ts.factory.createIdentifier("schema"), ts.factory.createIdentifier("$schema")));
1633
- }
1634
- }
1635
- if (schemaType) {
1636
- importSpecifiers.push(ts.factory.createImportSpecifier(true, ts.factory.createIdentifier("SchemaType"), ts.factory.createIdentifier("$Schema")));
1637
- }
1638
- let importFrom = useLite ? "./schema-lite" : "./schema";
1639
- if (importWithFileExtension) {
1640
- importFrom += importWithFileExtension.startsWith(".") ? importWithFileExtension : `.${importWithFileExtension}`;
1641
- }
1642
- return ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(false, void 0, ts.factory.createNamedImports(importSpecifiers)), ts.factory.createStringLiteral(importFrom));
1643
- }
1644
- generateDocs(tsDecl, decl) {
1645
- return ts.addSyntheticLeadingComment(tsDecl, ts.SyntaxKind.MultiLineCommentTrivia, `*
1646
- * ${decl.comments.map((c) => c.replace(/^\s*\/*\s*/, "")).join("\n * ")}
1647
- `, true);
1648
- }
1649
- generateInputTypes(model, options) {
1650
- const dataModels = this.getAllDataModels(model);
1651
- const statements = [];
1652
- statements.push(this.generateSchemaImport(model, false, true, !!(options.lite || options.liteOnly), options.importWithFileExtension));
1653
- const inputTypes = [
1654
- "FindManyArgs",
1655
- "FindUniqueArgs",
1656
- "FindFirstArgs",
1657
- "ExistsArgs",
1658
- "CreateArgs",
1659
- "CreateManyArgs",
1660
- "CreateManyAndReturnArgs",
1661
- "UpdateArgs",
1662
- "UpdateManyArgs",
1663
- "UpdateManyAndReturnArgs",
1664
- "UpsertArgs",
1665
- "DeleteArgs",
1666
- "DeleteManyArgs",
1667
- "CountArgs",
1668
- "AggregateArgs",
1669
- "GroupByArgs",
1670
- "WhereInput",
1671
- "SelectInput",
1672
- "IncludeInput",
1673
- "OmitInput"
1674
- ];
1675
- const inputTypeNameFixes = {
1676
- SelectInput: "Select",
1677
- IncludeInput: "Include",
1678
- OmitInput: "Omit"
1679
- };
1680
- statements.push(ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(true, void 0, ts.factory.createNamedImports([
1681
- ...inputTypes.map((inputType) => ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier(`${inputType} as $${inputType}`))),
1682
- ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier("QueryOptions as $QueryOptions"))
1683
- ])), ts.factory.createStringLiteral("@zenstackhq/orm")));
1684
- statements.push(ts.factory.createImportDeclaration(void 0, ts.factory.createImportClause(true, void 0, ts.factory.createNamedImports([
1685
- ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier("SimplifiedPlainResult as $Result")),
1686
- ts.factory.createImportSpecifier(false, void 0, ts.factory.createIdentifier("SelectIncludeOmit as $SelectIncludeOmit"))
1687
- ])), ts.factory.createStringLiteral("@zenstackhq/orm")));
1688
- for (const dm of dataModels) {
1689
- for (const inputType of inputTypes) {
1690
- const exportName = inputTypeNameFixes[inputType] ? `${dm.name}${inputTypeNameFixes[inputType]}` : `${dm.name}${inputType}`;
1691
- statements.push(ts.factory.createTypeAliasDeclaration([
1692
- ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)
1693
- ], exportName, void 0, ts.factory.createTypeReferenceNode(`$${inputType}`, [
1694
- ts.factory.createTypeReferenceNode("$Schema"),
1695
- ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(dm.name))
1696
- ])));
1697
- }
1698
- statements.push(ts.factory.createTypeAliasDeclaration([
1699
- ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)
1700
- ], `${dm.name}GetPayload`, [
1701
- ts.factory.createTypeParameterDeclaration(void 0, "Args", ts.factory.createTypeReferenceNode("$SelectIncludeOmit", [
1702
- ts.factory.createTypeReferenceNode("$Schema"),
1703
- ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(dm.name)),
1704
- ts.factory.createLiteralTypeNode(ts.factory.createTrue())
1705
- ])),
1706
- ts.factory.createTypeParameterDeclaration(void 0, "Options", ts.factory.createTypeReferenceNode("$QueryOptions", [
1707
- ts.factory.createTypeReferenceNode("$Schema")
1708
- ]), ts.factory.createTypeReferenceNode("$QueryOptions", [
1709
- ts.factory.createTypeReferenceNode("$Schema")
1710
- ]))
1711
- ], ts.factory.createTypeReferenceNode("$Result", [
1712
- ts.factory.createTypeReferenceNode("$Schema"),
1713
- ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(dm.name)),
1714
- ts.factory.createTypeReferenceNode("Args"),
1715
- ts.factory.createTypeReferenceNode("Options")
1716
- ])));
1717
- }
1718
- this.generateBannerComments(statements);
1719
- const outputFile = path.join(options.outDir, "input.ts");
1720
- const sourceFile = ts.createSourceFile(outputFile, "", ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS);
1721
- const printer = ts.createPrinter();
1722
- const result = printer.printList(ts.ListFormat.MultiLine, ts.factory.createNodeArray(statements), sourceFile);
1723
- fs.writeFileSync(outputFile, result);
1724
- }
1725
- };
1726
- export {
1727
- model_utils_exports as ModelUtils,
1728
- PrismaSchemaGenerator,
1729
- TsSchemaGenerator
1730
- };
1731
- //# sourceMappingURL=index.js.map