@zenstackhq/zod 3.5.6 → 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.js DELETED
@@ -1,826 +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/factory.ts
9
- import { ExpressionUtils as ExpressionUtils2, SchemaAccessor } from "@zenstackhq/schema";
10
- import Decimal2 from "decimal.js";
11
- import z2 from "zod";
12
-
13
- // src/error.ts
14
- var SchemaFactoryError = class extends Error {
15
- static {
16
- __name(this, "SchemaFactoryError");
17
- }
18
- constructor(message) {
19
- super(message);
20
- }
21
- };
22
-
23
- // src/utils.ts
24
- var utils_exports = {};
25
- __export(utils_exports, {
26
- addBigIntValidation: () => addBigIntValidation,
27
- addCustomValidation: () => addCustomValidation,
28
- addDecimalValidation: () => addDecimalValidation,
29
- addListValidation: () => addListValidation,
30
- addNumberValidation: () => addNumberValidation,
31
- addStringValidation: () => addStringValidation,
32
- collectFieldRefs: () => collectFieldRefs
33
- });
34
- import { ExpressionUtils } from "@zenstackhq/schema";
35
- import Decimal from "decimal.js";
36
- import { z } from "zod";
37
- function getArgValue(expr) {
38
- if (!expr || !ExpressionUtils.isLiteral(expr)) {
39
- return void 0;
40
- }
41
- return expr.value;
42
- }
43
- __name(getArgValue, "getArgValue");
44
- function addStringValidation(schema, attributes) {
45
- if (!attributes || attributes.length === 0) {
46
- return schema;
47
- }
48
- let result = schema;
49
- for (const attr of attributes) {
50
- switch (attr.name) {
51
- case "@length": {
52
- const min = getArgValue(attr.args?.find((a) => a.name === "min")?.value);
53
- if (min !== void 0) {
54
- result = result.min(min);
55
- }
56
- const max = getArgValue(attr.args?.find((a) => a.name === "max")?.value);
57
- if (max !== void 0) {
58
- result = result.max(max);
59
- }
60
- break;
61
- }
62
- case "@startsWith": {
63
- const value = getArgValue(attr.args?.[0]?.value);
64
- if (value !== void 0) {
65
- result = result.startsWith(value);
66
- }
67
- break;
68
- }
69
- case "@endsWith": {
70
- const value = getArgValue(attr.args?.[0]?.value);
71
- if (value !== void 0) {
72
- result = result.endsWith(value);
73
- }
74
- break;
75
- }
76
- case "@contains": {
77
- const value = getArgValue(attr.args?.[0]?.value);
78
- if (value !== void 0) {
79
- result = result.includes(value);
80
- }
81
- break;
82
- }
83
- case "@regex": {
84
- const pattern = getArgValue(attr.args?.[0]?.value);
85
- if (pattern !== void 0) {
86
- result = result.regex(new RegExp(pattern));
87
- }
88
- break;
89
- }
90
- case "@email":
91
- result = result.email();
92
- break;
93
- case "@datetime":
94
- result = result.datetime();
95
- break;
96
- case "@url":
97
- result = result.url();
98
- break;
99
- case "@trim":
100
- result = result.trim();
101
- break;
102
- case "@lower":
103
- result = result.toLowerCase();
104
- break;
105
- case "@upper":
106
- result = result.toUpperCase();
107
- break;
108
- }
109
- }
110
- return result;
111
- }
112
- __name(addStringValidation, "addStringValidation");
113
- function addNumberValidation(schema, attributes) {
114
- if (!attributes || attributes.length === 0) {
115
- return schema;
116
- }
117
- let result = schema;
118
- for (const attr of attributes) {
119
- const val = getArgValue(attr.args?.[0]?.value);
120
- if (val === void 0) {
121
- continue;
122
- }
123
- switch (attr.name) {
124
- case "@gt":
125
- result = result.gt(val);
126
- break;
127
- case "@gte":
128
- result = result.gte(val);
129
- break;
130
- case "@lt":
131
- result = result.lt(val);
132
- break;
133
- case "@lte":
134
- result = result.lte(val);
135
- break;
136
- }
137
- }
138
- return result;
139
- }
140
- __name(addNumberValidation, "addNumberValidation");
141
- function addBigIntValidation(schema, attributes) {
142
- if (!attributes || attributes.length === 0) {
143
- return schema;
144
- }
145
- let result = schema;
146
- for (const attr of attributes) {
147
- const val = getArgValue(attr.args?.[0]?.value);
148
- if (val === void 0) {
149
- continue;
150
- }
151
- switch (attr.name) {
152
- case "@gt":
153
- result = result.gt(BigInt(val));
154
- break;
155
- case "@gte":
156
- result = result.gte(BigInt(val));
157
- break;
158
- case "@lt":
159
- result = result.lt(BigInt(val));
160
- break;
161
- case "@lte":
162
- result = result.lte(BigInt(val));
163
- break;
164
- }
165
- }
166
- return result;
167
- }
168
- __name(addBigIntValidation, "addBigIntValidation");
169
- function addDecimalValidation(schema, attributes, addExtraValidation) {
170
- let result = schema;
171
- if (schema instanceof z.ZodString) {
172
- result = schema.superRefine((v, ctx) => {
173
- try {
174
- new Decimal(v);
175
- } catch (err) {
176
- ctx.addIssue({
177
- code: "custom",
178
- message: `Invalid decimal: ${err}`
179
- });
180
- }
181
- }).transform((val) => new Decimal(val));
182
- }
183
- function refine(schema2, op, value) {
184
- return schema2.superRefine((v, ctx) => {
185
- const base = z.number();
186
- const { error } = base[op](value).safeParse(v.toNumber());
187
- error?.issues.forEach((issue) => {
188
- if (op === "gt" || op === "gte") {
189
- ctx.addIssue({
190
- code: "too_small",
191
- origin: "number",
192
- minimum: value,
193
- type: "decimal",
194
- inclusive: op === "gte",
195
- message: issue.message
196
- });
197
- } else {
198
- ctx.addIssue({
199
- code: "too_big",
200
- origin: "number",
201
- maximum: value,
202
- type: "decimal",
203
- inclusive: op === "lte",
204
- message: issue.message
205
- });
206
- }
207
- });
208
- });
209
- }
210
- __name(refine, "refine");
211
- if (attributes && addExtraValidation) {
212
- for (const attr of attributes) {
213
- const val = getArgValue(attr.args?.[0]?.value);
214
- if (val === void 0) {
215
- continue;
216
- }
217
- switch (attr.name) {
218
- case "@gt":
219
- result = refine(result, "gt", val);
220
- break;
221
- case "@gte":
222
- result = refine(result, "gte", val);
223
- break;
224
- case "@lt":
225
- result = refine(result, "lt", val);
226
- break;
227
- case "@lte":
228
- result = refine(result, "lte", val);
229
- break;
230
- }
231
- }
232
- }
233
- return result;
234
- }
235
- __name(addDecimalValidation, "addDecimalValidation");
236
- function addListValidation(schema, attributes) {
237
- if (!attributes || attributes.length === 0) {
238
- return schema;
239
- }
240
- let result = schema;
241
- for (const attr of attributes) {
242
- if (attr.name === "@length") {
243
- const min = getArgValue(attr.args?.find((a) => a.name === "min")?.value);
244
- if (min !== void 0) {
245
- result = result.min(min);
246
- }
247
- const max = getArgValue(attr.args?.find((a) => a.name === "max")?.value);
248
- if (max !== void 0) {
249
- result = result.max(max);
250
- }
251
- }
252
- }
253
- return result;
254
- }
255
- __name(addListValidation, "addListValidation");
256
- function collectFieldRefs(expr) {
257
- const refs = /* @__PURE__ */ new Set();
258
- function walk(e) {
259
- switch (e.kind) {
260
- case "field":
261
- refs.add(e.field);
262
- break;
263
- case "unary":
264
- walk(e.operand);
265
- break;
266
- case "binary":
267
- walk(e.left);
268
- walk(e.right);
269
- break;
270
- case "call":
271
- e.args?.forEach(walk);
272
- break;
273
- case "array":
274
- e.items.forEach(walk);
275
- break;
276
- case "member":
277
- walk(e.receiver);
278
- break;
279
- }
280
- }
281
- __name(walk, "walk");
282
- walk(expr);
283
- return refs;
284
- }
285
- __name(collectFieldRefs, "collectFieldRefs");
286
- function addCustomValidation(schema, attributes, presentFields) {
287
- const attrs = attributes?.filter((a) => a.name === "@@validate");
288
- if (!attrs || attrs.length === 0) {
289
- return schema;
290
- }
291
- let result = schema;
292
- for (const attr of attrs) {
293
- const expr = attr.args?.[0]?.value;
294
- if (!expr) {
295
- continue;
296
- }
297
- if (presentFields !== void 0) {
298
- const refs = collectFieldRefs(expr);
299
- if ([
300
- ...refs
301
- ].some((ref) => !presentFields.has(ref))) {
302
- continue;
303
- }
304
- }
305
- const message = getArgValue(attr.args?.[1]?.value);
306
- const pathExpr = attr.args?.[2]?.value;
307
- let path = void 0;
308
- if (pathExpr && ExpressionUtils.isArray(pathExpr)) {
309
- path = pathExpr.items.map((e) => ExpressionUtils.getLiteralValue(e));
310
- }
311
- result = applyValidation(result, expr, message, path);
312
- }
313
- return result;
314
- }
315
- __name(addCustomValidation, "addCustomValidation");
316
- function applyValidation(schema, expr, message, path) {
317
- const options = {};
318
- if (message) {
319
- options.error = message;
320
- }
321
- if (path) {
322
- options.path = path;
323
- }
324
- return schema.refine((data) => Boolean(evalExpression(data, expr)), options);
325
- }
326
- __name(applyValidation, "applyValidation");
327
- function evalExpression(data, expr) {
328
- switch (expr.kind) {
329
- case "literal":
330
- return expr.value;
331
- case "array":
332
- return expr.items.map((item) => evalExpression(data, item));
333
- case "field":
334
- return evalField(data, expr);
335
- case "member":
336
- return evalMember(data, expr);
337
- case "unary":
338
- return evalUnary(data, expr);
339
- case "binary":
340
- return evalBinary(data, expr);
341
- case "call":
342
- return evalCall(data, expr);
343
- case "this":
344
- return data ?? null;
345
- case "null":
346
- return null;
347
- case "binding":
348
- throw new SchemaFactoryError("Binding expression is not supported in validation expressions");
349
- }
350
- }
351
- __name(evalExpression, "evalExpression");
352
- function evalField(data, e) {
353
- return data?.[e.field] ?? null;
354
- }
355
- __name(evalField, "evalField");
356
- function evalUnary(data, expr) {
357
- const operand = evalExpression(data, expr.operand);
358
- switch (expr.op) {
359
- case "!":
360
- return !operand;
361
- default:
362
- throw new SchemaFactoryError(`Unsupported unary operator: ${expr.op}`);
363
- }
364
- }
365
- __name(evalUnary, "evalUnary");
366
- function evalBinary(data, expr) {
367
- const left = evalExpression(data, expr.left);
368
- const right = evalExpression(data, expr.right);
369
- switch (expr.op) {
370
- case "&&":
371
- return Boolean(left) && Boolean(right);
372
- case "||":
373
- return Boolean(left) || Boolean(right);
374
- case "==":
375
- return left == right;
376
- case "!=":
377
- return left != right;
378
- case "<":
379
- return left < right;
380
- case "<=":
381
- return left <= right;
382
- case ">":
383
- return left > right;
384
- case ">=":
385
- return left >= right;
386
- case "?":
387
- if (!Array.isArray(left)) {
388
- return false;
389
- }
390
- return left.some((item) => item === right);
391
- case "!":
392
- if (!Array.isArray(left)) {
393
- return false;
394
- }
395
- return left.every((item) => item === right);
396
- case "^":
397
- if (!Array.isArray(left)) {
398
- return false;
399
- }
400
- return !left.some((item) => item === right);
401
- case "in":
402
- if (!Array.isArray(right)) {
403
- return false;
404
- }
405
- return right.includes(left);
406
- default:
407
- throw new SchemaFactoryError(`Unsupported binary operator: ${expr.op}`);
408
- }
409
- }
410
- __name(evalBinary, "evalBinary");
411
- function evalMember(data, expr) {
412
- let result = evalExpression(data, expr.receiver);
413
- for (const member of expr.members) {
414
- if (!result || typeof result !== "object") {
415
- return void 0;
416
- }
417
- result = result[member];
418
- }
419
- return result ?? null;
420
- }
421
- __name(evalMember, "evalMember");
422
- function evalCall(data, expr) {
423
- const f = expr.function;
424
- const fieldArg = expr.args?.[0] ? evalExpression(data, expr.args[0]) : void 0;
425
- switch (f) {
426
- // string functions
427
- case "length": {
428
- if (fieldArg === void 0 || fieldArg === null) {
429
- return false;
430
- }
431
- invariant(typeof fieldArg === "string" || Array.isArray(fieldArg), `"${f}" first argument must be a string or a list`);
432
- return fieldArg.length;
433
- }
434
- case "startsWith":
435
- case "endsWith":
436
- case "contains": {
437
- if (fieldArg === void 0 || fieldArg === null) {
438
- return false;
439
- }
440
- invariant(typeof fieldArg === "string", `"${f}" first argument must be a string`);
441
- invariant(expr.args?.[1], `"${f}" requires a search argument`);
442
- const search = getArgValue(expr.args?.[1]);
443
- const caseInsensitive = getArgValue(expr.args?.[2]) ?? false;
444
- const applyStringOp = /* @__PURE__ */ __name((x, y) => {
445
- switch (f) {
446
- case "startsWith":
447
- return x.startsWith(y);
448
- case "endsWith":
449
- return x.endsWith(y);
450
- case "contains":
451
- return x.includes(y);
452
- }
453
- }, "applyStringOp");
454
- return caseInsensitive ? applyStringOp(fieldArg.toLowerCase(), search.toLowerCase()) : applyStringOp(fieldArg, search);
455
- }
456
- case "regex": {
457
- if (fieldArg === void 0 || fieldArg === null) {
458
- return false;
459
- }
460
- invariant(typeof fieldArg === "string", `"${f}" first argument must be a string`);
461
- const pattern = getArgValue(expr.args?.[1]);
462
- invariant(pattern !== void 0, `"${f}" requires a pattern argument`);
463
- return new RegExp(pattern).test(fieldArg);
464
- }
465
- case "isEmail":
466
- case "isUrl":
467
- case "isDateTime": {
468
- if (fieldArg === void 0 || fieldArg === null) {
469
- return false;
470
- }
471
- invariant(typeof fieldArg === "string", `"${f}" first argument must be a string`);
472
- const fn = f === "isEmail" ? "email" : f === "isUrl" ? "url" : "datetime";
473
- return z.string()[fn]().safeParse(fieldArg).success;
474
- }
475
- // list functions
476
- case "has":
477
- case "hasEvery":
478
- case "hasSome": {
479
- invariant(expr.args?.[1], `${f} requires a search argument`);
480
- if (fieldArg === void 0 || fieldArg === null) {
481
- return false;
482
- }
483
- invariant(Array.isArray(fieldArg), `"${f}" first argument must be an array field`);
484
- const search = evalExpression(data, expr.args?.[1]);
485
- if (f === "has") {
486
- return fieldArg.some((item) => item === search);
487
- } else if (f === "hasEvery") {
488
- invariant(Array.isArray(search), "hasEvery second argument must be an array");
489
- return search.every((v) => fieldArg.some((item) => item === v));
490
- } else {
491
- invariant(Array.isArray(search), "hasSome second argument must be an array");
492
- return search.some((v) => fieldArg.some((item) => item === v));
493
- }
494
- }
495
- case "isEmpty": {
496
- if (fieldArg === void 0 || fieldArg === null) {
497
- return false;
498
- }
499
- invariant(Array.isArray(fieldArg), `"${f}" first argument must be an array field`);
500
- return fieldArg.length === 0;
501
- }
502
- default:
503
- throw new SchemaFactoryError(`Unsupported function "${f}"`);
504
- }
505
- }
506
- __name(evalCall, "evalCall");
507
- function invariant(condition, message) {
508
- if (!condition) {
509
- throw new SchemaFactoryError(message ?? "Invariant failed");
510
- }
511
- }
512
- __name(invariant, "invariant");
513
-
514
- // src/factory.ts
515
- function createSchemaFactory(schema) {
516
- return new SchemaFactory(schema);
517
- }
518
- __name(createSchemaFactory, "createSchemaFactory");
519
- var rawOptionsSchema = z2.lazy(() => z2.object({
520
- select: z2.record(z2.string(), z2.union([
521
- z2.boolean(),
522
- rawOptionsSchema
523
- ])).optional(),
524
- include: z2.record(z2.string(), z2.union([
525
- z2.boolean(),
526
- rawOptionsSchema
527
- ])).optional(),
528
- omit: z2.record(z2.string(), z2.boolean()).optional()
529
- }).superRefine((val, ctx) => {
530
- if (val.select && val.include) {
531
- ctx.addIssue({
532
- code: "custom",
533
- message: "`select` and `include` cannot be used together"
534
- });
535
- }
536
- if (val.select && val.omit) {
537
- ctx.addIssue({
538
- code: "custom",
539
- message: "`select` and `omit` cannot be used together"
540
- });
541
- }
542
- }));
543
- var SchemaFactory = class SchemaFactory2 {
544
- static {
545
- __name(this, "SchemaFactory");
546
- }
547
- schema;
548
- constructor(_schema) {
549
- this.schema = new SchemaAccessor(_schema);
550
- }
551
- makeModelSchema(model, options) {
552
- const modelDef = this.schema.requireModel(model);
553
- if (!options) {
554
- const fields2 = {};
555
- for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
556
- if (fieldDef.relation) {
557
- const relatedModelName = fieldDef.type;
558
- const lazySchema = z2.lazy(() => this.makeModelSchema(relatedModelName));
559
- fields2[fieldName] = this.applyDescription(this.applyCardinality(lazySchema, fieldDef).optional(), fieldDef.attributes);
560
- } else {
561
- fields2[fieldName] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes);
562
- }
563
- }
564
- const shape2 = z2.strictObject(fields2);
565
- return this.applyDescription(addCustomValidation(shape2, modelDef.attributes), modelDef.attributes);
566
- }
567
- const rawOptions = rawOptionsSchema.parse(options);
568
- const fields = this.buildFieldsWithOptions(model, rawOptions);
569
- const shape = z2.strictObject(fields);
570
- const presentFields = this.buildPresentFields(model, rawOptions);
571
- const withValidation = addCustomValidation(shape, modelDef.attributes, presentFields);
572
- return this.applyDescription(withValidation, modelDef.attributes);
573
- }
574
- makeModelCreateSchema(model) {
575
- const modelDef = this.schema.requireModel(model);
576
- const fields = {};
577
- for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
578
- if (fieldDef.relation || fieldDef.computed || fieldDef.isDiscriminator) {
579
- continue;
580
- }
581
- let fieldSchema = this.makeScalarFieldSchema(fieldDef);
582
- if (fieldDef.optional || fieldDef.default !== void 0 || fieldDef.updatedAt) {
583
- fieldSchema = fieldSchema.optional();
584
- }
585
- fields[fieldName] = this.applyDescription(fieldSchema, fieldDef.attributes);
586
- }
587
- const shape = z2.strictObject(fields);
588
- return this.applyDescription(addCustomValidation(shape, modelDef.attributes), modelDef.attributes);
589
- }
590
- makeModelUpdateSchema(model) {
591
- const modelDef = this.schema.requireModel(model);
592
- const fields = {};
593
- for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
594
- if (fieldDef.relation || fieldDef.computed || fieldDef.isDiscriminator) {
595
- continue;
596
- }
597
- let fieldSchema = this.makeScalarFieldSchema(fieldDef);
598
- fieldSchema = fieldSchema.optional();
599
- fields[fieldName] = this.applyDescription(fieldSchema, fieldDef.attributes);
600
- }
601
- const shape = z2.strictObject(fields);
602
- return this.applyDescription(addCustomValidation(shape, modelDef.attributes), modelDef.attributes);
603
- }
604
- // -------------------------------------------------------------------------
605
- // Options-aware field building
606
- // -------------------------------------------------------------------------
607
- /**
608
- * Internal loose options shape used at runtime (we've already validated the
609
- * type-level constraints via the overload signatures).
610
- */
611
- buildFieldsWithOptions(model, options) {
612
- const { select, include, omit } = options;
613
- const modelDef = this.schema.requireModel(model);
614
- const fields = {};
615
- if (select) {
616
- for (const [key, value] of Object.entries(select)) {
617
- if (!value) continue;
618
- const fieldDef = modelDef.fields[key];
619
- if (!fieldDef) {
620
- throw new SchemaFactoryError(`Field "${key}" does not exist on model "${model}"`);
621
- }
622
- if (fieldDef.relation) {
623
- const subOptions = typeof value === "object" ? value : void 0;
624
- const relSchema = this.makeRelationFieldSchema(fieldDef, subOptions);
625
- fields[key] = this.applyDescription(this.applyCardinality(relSchema, fieldDef).optional(), fieldDef.attributes);
626
- } else {
627
- if (typeof value === "object") {
628
- throw new SchemaFactoryError(`Field "${key}" on model "${model}" is a scalar field and cannot have nested options`);
629
- }
630
- fields[key] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes);
631
- }
632
- }
633
- } else {
634
- if (omit) {
635
- for (const key of Object.keys(omit)) {
636
- const fieldDef = modelDef.fields[key];
637
- if (!fieldDef) {
638
- throw new SchemaFactoryError(`Field "${key}" does not exist on model "${model}"`);
639
- }
640
- if (fieldDef.relation) {
641
- throw new SchemaFactoryError(`Field "${key}" on model "${model}" is a relation field and cannot be used in "omit"`);
642
- }
643
- }
644
- }
645
- for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
646
- if (fieldDef.relation) continue;
647
- if (omit?.[fieldName] === true) continue;
648
- fields[fieldName] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes);
649
- }
650
- if (include) {
651
- for (const [key, value] of Object.entries(include)) {
652
- if (!value) continue;
653
- const fieldDef = modelDef.fields[key];
654
- if (!fieldDef) {
655
- throw new SchemaFactoryError(`Field "${key}" does not exist on model "${model}"`);
656
- }
657
- if (!fieldDef.relation) {
658
- throw new SchemaFactoryError(`Field "${key}" on model "${model}" is not a relation field and cannot be used in "include"`);
659
- }
660
- const subOptions = typeof value === "object" ? value : void 0;
661
- const relSchema = this.makeRelationFieldSchema(fieldDef, subOptions);
662
- fields[key] = this.applyDescription(this.applyCardinality(relSchema, fieldDef).optional(), fieldDef.attributes);
663
- }
664
- }
665
- }
666
- return fields;
667
- }
668
- /**
669
- * Returns the set of scalar field names that will be present in the
670
- * resulting schema after applying `options`. Used by `addCustomValidation`
671
- * to skip `@@validate` rules that reference an absent field.
672
- *
673
- * Only scalar fields matter here because `@@validate` conditions are
674
- * restricted by the ZModel compiler to scalar fields of the same model.
675
- */
676
- buildPresentFields(model, options) {
677
- const { select, omit } = options;
678
- const modelDef = this.schema.requireModel(model);
679
- const fields = /* @__PURE__ */ new Set();
680
- if (select) {
681
- for (const [key, value] of Object.entries(select)) {
682
- if (!value) continue;
683
- const fieldDef = modelDef.fields[key];
684
- if (fieldDef && !fieldDef.relation) {
685
- fields.add(key);
686
- }
687
- }
688
- } else {
689
- for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
690
- if (fieldDef.relation) continue;
691
- if (omit?.[fieldName] === true) continue;
692
- fields.add(fieldName);
693
- }
694
- }
695
- return fields;
696
- }
697
- /**
698
- * Build the inner Zod schema for a relation field, optionally with nested
699
- * query options. Does NOT apply cardinality/optional wrappers — the caller
700
- * does that.
701
- */
702
- makeRelationFieldSchema(fieldDef, subOptions) {
703
- const relatedModelName = fieldDef.type;
704
- if (subOptions) {
705
- return this.makeModelSchema(relatedModelName, subOptions);
706
- }
707
- return z2.lazy(() => this.makeModelSchema(relatedModelName));
708
- }
709
- makeScalarFieldSchema(fieldDef) {
710
- const { type, attributes } = fieldDef;
711
- const enumDef = this.schema.getEnum(type);
712
- if (enumDef) {
713
- return this.applyCardinality(this.makeEnumSchema(type), fieldDef);
714
- }
715
- const typedefDef = this.schema.getTypeDef(type);
716
- if (typedefDef) {
717
- return this.applyCardinality(this.makeTypeSchema(type), fieldDef);
718
- }
719
- let base;
720
- switch (type) {
721
- case "String":
722
- base = addStringValidation(z2.string(), attributes);
723
- break;
724
- case "Int":
725
- base = addNumberValidation(z2.number().int(), attributes);
726
- break;
727
- case "Float":
728
- base = addNumberValidation(z2.number(), attributes);
729
- break;
730
- case "Boolean":
731
- base = z2.boolean();
732
- break;
733
- case "BigInt":
734
- base = addBigIntValidation(z2.bigint(), attributes);
735
- break;
736
- case "Decimal":
737
- base = z2.union([
738
- addNumberValidation(z2.number(), attributes),
739
- addDecimalValidation(z2.string(), attributes, true),
740
- addDecimalValidation(z2.instanceof(Decimal2), attributes, true)
741
- ]);
742
- break;
743
- case "DateTime":
744
- base = z2.union([
745
- z2.date(),
746
- z2.iso.datetime()
747
- ]);
748
- break;
749
- case "Bytes":
750
- base = z2.instanceof(Uint8Array);
751
- break;
752
- case "Json":
753
- base = this.makeJsonSchema();
754
- break;
755
- case "Unsupported":
756
- base = z2.unknown();
757
- break;
758
- default: {
759
- const _exhaustive = type;
760
- throw new SchemaFactoryError(`Unsupported field type: ${_exhaustive}`);
761
- }
762
- }
763
- return this.applyCardinality(base, fieldDef);
764
- }
765
- makeJsonSchema() {
766
- return z2.union([
767
- z2.string(),
768
- z2.number(),
769
- z2.boolean(),
770
- z2.null(),
771
- z2.array(z2.lazy(() => this.makeJsonSchema())),
772
- z2.object({}).catchall(z2.lazy(() => this.makeJsonSchema()))
773
- ]);
774
- }
775
- applyCardinality(schema, fieldDef) {
776
- let result = schema;
777
- if (fieldDef.array) {
778
- result = result.array();
779
- }
780
- if (fieldDef.optional) {
781
- result = result.nullable().optional();
782
- }
783
- return result;
784
- }
785
- makeTypeSchema(type) {
786
- const typeDef = this.schema.requireTypeDef(type);
787
- const fields = {};
788
- for (const [fieldName, fieldDef] of Object.entries(typeDef.fields)) {
789
- fields[fieldName] = this.applyDescription(this.makeScalarFieldSchema(fieldDef), fieldDef.attributes);
790
- }
791
- const shape = z2.strictObject(fields);
792
- return this.applyDescription(addCustomValidation(shape, typeDef.attributes), typeDef.attributes);
793
- }
794
- makeEnumSchema(_enum) {
795
- const enumDef = this.schema.requireEnum(_enum);
796
- const schema = z2.enum(Object.keys(enumDef.values));
797
- return this.applyDescription(schema, enumDef.attributes);
798
- }
799
- getMetaDescription(attributes) {
800
- if (!attributes) return void 0;
801
- for (const attr of attributes) {
802
- if (attr.name !== "@meta" && attr.name !== "@@meta") continue;
803
- const nameExpr = attr.args?.[0]?.value;
804
- if (!nameExpr || ExpressionUtils2.getLiteralValue(nameExpr) !== "description") continue;
805
- const valueExpr = attr.args?.[1]?.value;
806
- if (valueExpr) {
807
- return ExpressionUtils2.getLiteralValue(valueExpr);
808
- }
809
- }
810
- return void 0;
811
- }
812
- applyDescription(schema, attributes) {
813
- const description = this.getMetaDescription(attributes);
814
- if (description) {
815
- return schema.meta({
816
- description
817
- });
818
- }
819
- return schema;
820
- }
821
- };
822
- export {
823
- utils_exports as ZodUtils,
824
- createSchemaFactory
825
- };
826
- //# sourceMappingURL=index.js.map