@playcademy/sdk 0.0.1-beta.25 → 0.0.1-beta.27

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/types.js CHANGED
@@ -10,4290 +10,12 @@ var __export = (target, all) => {
10
10
  };
11
11
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
12
12
 
13
- // ../../node_modules/zod/dist/esm/v3/helpers/util.js
14
- var util, objectUtil, ZodParsedType, getParsedType = (data) => {
15
- const t = typeof data;
16
- switch (t) {
17
- case "undefined":
18
- return ZodParsedType.undefined;
19
- case "string":
20
- return ZodParsedType.string;
21
- case "number":
22
- return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
23
- case "boolean":
24
- return ZodParsedType.boolean;
25
- case "function":
26
- return ZodParsedType.function;
27
- case "bigint":
28
- return ZodParsedType.bigint;
29
- case "symbol":
30
- return ZodParsedType.symbol;
31
- case "object":
32
- if (Array.isArray(data)) {
33
- return ZodParsedType.array;
34
- }
35
- if (data === null) {
36
- return ZodParsedType.null;
37
- }
38
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
39
- return ZodParsedType.promise;
40
- }
41
- if (typeof Map !== "undefined" && data instanceof Map) {
42
- return ZodParsedType.map;
43
- }
44
- if (typeof Set !== "undefined" && data instanceof Set) {
45
- return ZodParsedType.set;
46
- }
47
- if (typeof Date !== "undefined" && data instanceof Date) {
48
- return ZodParsedType.date;
49
- }
50
- return ZodParsedType.object;
51
- default:
52
- return ZodParsedType.unknown;
53
- }
54
- };
55
- var init_util = __esm(() => {
56
- (function(util2) {
57
- util2.assertEqual = (_) => {};
58
- function assertIs(_arg) {}
59
- util2.assertIs = assertIs;
60
- function assertNever(_x) {
61
- throw new Error;
62
- }
63
- util2.assertNever = assertNever;
64
- util2.arrayToEnum = (items) => {
65
- const obj = {};
66
- for (const item of items) {
67
- obj[item] = item;
68
- }
69
- return obj;
70
- };
71
- util2.getValidEnumValues = (obj) => {
72
- const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
73
- const filtered = {};
74
- for (const k of validKeys) {
75
- filtered[k] = obj[k];
76
- }
77
- return util2.objectValues(filtered);
78
- };
79
- util2.objectValues = (obj) => {
80
- return util2.objectKeys(obj).map(function(e) {
81
- return obj[e];
82
- });
83
- };
84
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
85
- const keys = [];
86
- for (const key in object) {
87
- if (Object.prototype.hasOwnProperty.call(object, key)) {
88
- keys.push(key);
89
- }
90
- }
91
- return keys;
92
- };
93
- util2.find = (arr, checker) => {
94
- for (const item of arr) {
95
- if (checker(item))
96
- return item;
97
- }
98
- return;
99
- };
100
- util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
101
- function joinValues(array, separator = " | ") {
102
- return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
103
- }
104
- util2.joinValues = joinValues;
105
- util2.jsonStringifyReplacer = (_, value) => {
106
- if (typeof value === "bigint") {
107
- return value.toString();
108
- }
109
- return value;
110
- };
111
- })(util || (util = {}));
112
- (function(objectUtil2) {
113
- objectUtil2.mergeShapes = (first, second) => {
114
- return {
115
- ...first,
116
- ...second
117
- };
118
- };
119
- })(objectUtil || (objectUtil = {}));
120
- ZodParsedType = util.arrayToEnum([
121
- "string",
122
- "nan",
123
- "number",
124
- "integer",
125
- "float",
126
- "boolean",
127
- "date",
128
- "bigint",
129
- "symbol",
130
- "function",
131
- "undefined",
132
- "null",
133
- "array",
134
- "object",
135
- "unknown",
136
- "promise",
137
- "void",
138
- "never",
139
- "map",
140
- "set"
141
- ]);
142
- });
143
-
144
- // ../../node_modules/zod/dist/esm/v3/ZodError.js
145
- var ZodIssueCode, quotelessJson = (obj) => {
146
- const json = JSON.stringify(obj, null, 2);
147
- return json.replace(/"([^"]+)":/g, "$1:");
148
- }, ZodError;
149
- var init_ZodError = __esm(() => {
150
- init_util();
151
- ZodIssueCode = util.arrayToEnum([
152
- "invalid_type",
153
- "invalid_literal",
154
- "custom",
155
- "invalid_union",
156
- "invalid_union_discriminator",
157
- "invalid_enum_value",
158
- "unrecognized_keys",
159
- "invalid_arguments",
160
- "invalid_return_type",
161
- "invalid_date",
162
- "invalid_string",
163
- "too_small",
164
- "too_big",
165
- "invalid_intersection_types",
166
- "not_multiple_of",
167
- "not_finite"
168
- ]);
169
- ZodError = class ZodError extends Error {
170
- get errors() {
171
- return this.issues;
172
- }
173
- constructor(issues) {
174
- super();
175
- this.issues = [];
176
- this.addIssue = (sub) => {
177
- this.issues = [...this.issues, sub];
178
- };
179
- this.addIssues = (subs = []) => {
180
- this.issues = [...this.issues, ...subs];
181
- };
182
- const actualProto = new.target.prototype;
183
- if (Object.setPrototypeOf) {
184
- Object.setPrototypeOf(this, actualProto);
185
- } else {
186
- this.__proto__ = actualProto;
187
- }
188
- this.name = "ZodError";
189
- this.issues = issues;
190
- }
191
- format(_mapper) {
192
- const mapper = _mapper || function(issue) {
193
- return issue.message;
194
- };
195
- const fieldErrors = { _errors: [] };
196
- const processError = (error) => {
197
- for (const issue of error.issues) {
198
- if (issue.code === "invalid_union") {
199
- issue.unionErrors.map(processError);
200
- } else if (issue.code === "invalid_return_type") {
201
- processError(issue.returnTypeError);
202
- } else if (issue.code === "invalid_arguments") {
203
- processError(issue.argumentsError);
204
- } else if (issue.path.length === 0) {
205
- fieldErrors._errors.push(mapper(issue));
206
- } else {
207
- let curr = fieldErrors;
208
- let i = 0;
209
- while (i < issue.path.length) {
210
- const el = issue.path[i];
211
- const terminal = i === issue.path.length - 1;
212
- if (!terminal) {
213
- curr[el] = curr[el] || { _errors: [] };
214
- } else {
215
- curr[el] = curr[el] || { _errors: [] };
216
- curr[el]._errors.push(mapper(issue));
217
- }
218
- curr = curr[el];
219
- i++;
220
- }
221
- }
222
- }
223
- };
224
- processError(this);
225
- return fieldErrors;
226
- }
227
- static assert(value) {
228
- if (!(value instanceof ZodError)) {
229
- throw new Error(`Not a ZodError: ${value}`);
230
- }
231
- }
232
- toString() {
233
- return this.message;
234
- }
235
- get message() {
236
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
237
- }
238
- get isEmpty() {
239
- return this.issues.length === 0;
240
- }
241
- flatten(mapper = (issue) => issue.message) {
242
- const fieldErrors = {};
243
- const formErrors = [];
244
- for (const sub of this.issues) {
245
- if (sub.path.length > 0) {
246
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
247
- fieldErrors[sub.path[0]].push(mapper(sub));
248
- } else {
249
- formErrors.push(mapper(sub));
250
- }
251
- }
252
- return { formErrors, fieldErrors };
253
- }
254
- get formErrors() {
255
- return this.flatten();
256
- }
257
- };
258
- ZodError.create = (issues) => {
259
- const error = new ZodError(issues);
260
- return error;
261
- };
262
- });
263
-
264
- // ../../node_modules/zod/dist/esm/v3/locales/en.js
265
- var errorMap = (issue, _ctx) => {
266
- let message;
267
- switch (issue.code) {
268
- case ZodIssueCode.invalid_type:
269
- if (issue.received === ZodParsedType.undefined) {
270
- message = "Required";
271
- } else {
272
- message = `Expected ${issue.expected}, received ${issue.received}`;
273
- }
274
- break;
275
- case ZodIssueCode.invalid_literal:
276
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
277
- break;
278
- case ZodIssueCode.unrecognized_keys:
279
- message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
280
- break;
281
- case ZodIssueCode.invalid_union:
282
- message = `Invalid input`;
283
- break;
284
- case ZodIssueCode.invalid_union_discriminator:
285
- message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
286
- break;
287
- case ZodIssueCode.invalid_enum_value:
288
- message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
289
- break;
290
- case ZodIssueCode.invalid_arguments:
291
- message = `Invalid function arguments`;
292
- break;
293
- case ZodIssueCode.invalid_return_type:
294
- message = `Invalid function return type`;
295
- break;
296
- case ZodIssueCode.invalid_date:
297
- message = `Invalid date`;
298
- break;
299
- case ZodIssueCode.invalid_string:
300
- if (typeof issue.validation === "object") {
301
- if ("includes" in issue.validation) {
302
- message = `Invalid input: must include "${issue.validation.includes}"`;
303
- if (typeof issue.validation.position === "number") {
304
- message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
305
- }
306
- } else if ("startsWith" in issue.validation) {
307
- message = `Invalid input: must start with "${issue.validation.startsWith}"`;
308
- } else if ("endsWith" in issue.validation) {
309
- message = `Invalid input: must end with "${issue.validation.endsWith}"`;
310
- } else {
311
- util.assertNever(issue.validation);
312
- }
313
- } else if (issue.validation !== "regex") {
314
- message = `Invalid ${issue.validation}`;
315
- } else {
316
- message = "Invalid";
317
- }
318
- break;
319
- case ZodIssueCode.too_small:
320
- if (issue.type === "array")
321
- message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
322
- else if (issue.type === "string")
323
- message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
324
- else if (issue.type === "number")
325
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
326
- else if (issue.type === "date")
327
- message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
328
- else
329
- message = "Invalid input";
330
- break;
331
- case ZodIssueCode.too_big:
332
- if (issue.type === "array")
333
- message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
334
- else if (issue.type === "string")
335
- message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
336
- else if (issue.type === "number")
337
- message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
338
- else if (issue.type === "bigint")
339
- message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
340
- else if (issue.type === "date")
341
- message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
342
- else
343
- message = "Invalid input";
344
- break;
345
- case ZodIssueCode.custom:
346
- message = `Invalid input`;
347
- break;
348
- case ZodIssueCode.invalid_intersection_types:
349
- message = `Intersection results could not be merged`;
350
- break;
351
- case ZodIssueCode.not_multiple_of:
352
- message = `Number must be a multiple of ${issue.multipleOf}`;
353
- break;
354
- case ZodIssueCode.not_finite:
355
- message = "Number must be finite";
356
- break;
357
- default:
358
- message = _ctx.defaultError;
359
- util.assertNever(issue);
360
- }
361
- return { message };
362
- }, en_default;
363
- var init_en = __esm(() => {
364
- init_ZodError();
365
- init_util();
366
- en_default = errorMap;
367
- });
368
-
369
- // ../../node_modules/zod/dist/esm/v3/errors.js
370
- function setErrorMap(map) {
371
- overrideErrorMap = map;
372
- }
373
- function getErrorMap() {
374
- return overrideErrorMap;
375
- }
376
- var overrideErrorMap;
377
- var init_errors = __esm(() => {
378
- init_en();
379
- overrideErrorMap = en_default;
380
- });
381
-
382
- // ../../node_modules/zod/dist/esm/v3/helpers/parseUtil.js
383
- function addIssueToContext(ctx, issueData) {
384
- const overrideMap = getErrorMap();
385
- const issue = makeIssue({
386
- issueData,
387
- data: ctx.data,
388
- path: ctx.path,
389
- errorMaps: [
390
- ctx.common.contextualErrorMap,
391
- ctx.schemaErrorMap,
392
- overrideMap,
393
- overrideMap === en_default ? undefined : en_default
394
- ].filter((x) => !!x)
395
- });
396
- ctx.common.issues.push(issue);
397
- }
398
-
399
- class ParseStatus {
400
- constructor() {
401
- this.value = "valid";
402
- }
403
- dirty() {
404
- if (this.value === "valid")
405
- this.value = "dirty";
406
- }
407
- abort() {
408
- if (this.value !== "aborted")
409
- this.value = "aborted";
410
- }
411
- static mergeArray(status, results) {
412
- const arrayValue = [];
413
- for (const s of results) {
414
- if (s.status === "aborted")
415
- return INVALID;
416
- if (s.status === "dirty")
417
- status.dirty();
418
- arrayValue.push(s.value);
419
- }
420
- return { status: status.value, value: arrayValue };
421
- }
422
- static async mergeObjectAsync(status, pairs) {
423
- const syncPairs = [];
424
- for (const pair of pairs) {
425
- const key = await pair.key;
426
- const value = await pair.value;
427
- syncPairs.push({
428
- key,
429
- value
430
- });
431
- }
432
- return ParseStatus.mergeObjectSync(status, syncPairs);
433
- }
434
- static mergeObjectSync(status, pairs) {
435
- const finalObject = {};
436
- for (const pair of pairs) {
437
- const { key, value } = pair;
438
- if (key.status === "aborted")
439
- return INVALID;
440
- if (value.status === "aborted")
441
- return INVALID;
442
- if (key.status === "dirty")
443
- status.dirty();
444
- if (value.status === "dirty")
445
- status.dirty();
446
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
447
- finalObject[key.value] = value.value;
448
- }
449
- }
450
- return { status: status.value, value: finalObject };
451
- }
452
- }
453
- var makeIssue = (params) => {
454
- const { data, path, errorMaps, issueData } = params;
455
- const fullPath = [...path, ...issueData.path || []];
456
- const fullIssue = {
457
- ...issueData,
458
- path: fullPath
459
- };
460
- if (issueData.message !== undefined) {
461
- return {
462
- ...issueData,
463
- path: fullPath,
464
- message: issueData.message
465
- };
466
- }
467
- let errorMessage = "";
468
- const maps = errorMaps.filter((m) => !!m).slice().reverse();
469
- for (const map of maps) {
470
- errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
471
- }
472
- return {
473
- ...issueData,
474
- path: fullPath,
475
- message: errorMessage
476
- };
477
- }, EMPTY_PATH, INVALID, DIRTY = (value) => ({ status: "dirty", value }), OK = (value) => ({ status: "valid", value }), isAborted = (x) => x.status === "aborted", isDirty = (x) => x.status === "dirty", isValid = (x) => x.status === "valid", isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
478
- var init_parseUtil = __esm(() => {
479
- init_errors();
480
- init_en();
481
- EMPTY_PATH = [];
482
- INVALID = Object.freeze({
483
- status: "aborted"
484
- });
485
- });
486
-
487
- // ../../node_modules/zod/dist/esm/v3/helpers/typeAliases.js
488
- var init_typeAliases = () => {};
489
-
490
- // ../../node_modules/zod/dist/esm/v3/helpers/errorUtil.js
491
- var errorUtil;
492
- var init_errorUtil = __esm(() => {
493
- (function(errorUtil2) {
494
- errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
495
- errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
496
- })(errorUtil || (errorUtil = {}));
497
- });
498
-
499
- // ../../node_modules/zod/dist/esm/v3/types.js
500
- class ParseInputLazyPath {
501
- constructor(parent, value, path, key) {
502
- this._cachedPath = [];
503
- this.parent = parent;
504
- this.data = value;
505
- this._path = path;
506
- this._key = key;
507
- }
508
- get path() {
509
- if (!this._cachedPath.length) {
510
- if (Array.isArray(this._key)) {
511
- this._cachedPath.push(...this._path, ...this._key);
512
- } else {
513
- this._cachedPath.push(...this._path, this._key);
514
- }
515
- }
516
- return this._cachedPath;
517
- }
518
- }
519
- function processCreateParams(params) {
520
- if (!params)
521
- return {};
522
- const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
523
- if (errorMap2 && (invalid_type_error || required_error)) {
524
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
525
- }
526
- if (errorMap2)
527
- return { errorMap: errorMap2, description };
528
- const customMap = (iss, ctx) => {
529
- const { message } = params;
530
- if (iss.code === "invalid_enum_value") {
531
- return { message: message ?? ctx.defaultError };
532
- }
533
- if (typeof ctx.data === "undefined") {
534
- return { message: message ?? required_error ?? ctx.defaultError };
535
- }
536
- if (iss.code !== "invalid_type")
537
- return { message: ctx.defaultError };
538
- return { message: message ?? invalid_type_error ?? ctx.defaultError };
539
- };
540
- return { errorMap: customMap, description };
541
- }
542
-
543
- class ZodType {
544
- get description() {
545
- return this._def.description;
546
- }
547
- _getType(input) {
548
- return getParsedType(input.data);
549
- }
550
- _getOrReturnCtx(input, ctx) {
551
- return ctx || {
552
- common: input.parent.common,
553
- data: input.data,
554
- parsedType: getParsedType(input.data),
555
- schemaErrorMap: this._def.errorMap,
556
- path: input.path,
557
- parent: input.parent
558
- };
559
- }
560
- _processInputParams(input) {
561
- return {
562
- status: new ParseStatus,
563
- ctx: {
564
- common: input.parent.common,
565
- data: input.data,
566
- parsedType: getParsedType(input.data),
567
- schemaErrorMap: this._def.errorMap,
568
- path: input.path,
569
- parent: input.parent
570
- }
571
- };
572
- }
573
- _parseSync(input) {
574
- const result = this._parse(input);
575
- if (isAsync(result)) {
576
- throw new Error("Synchronous parse encountered promise.");
577
- }
578
- return result;
579
- }
580
- _parseAsync(input) {
581
- const result = this._parse(input);
582
- return Promise.resolve(result);
583
- }
584
- parse(data, params) {
585
- const result = this.safeParse(data, params);
586
- if (result.success)
587
- return result.data;
588
- throw result.error;
589
- }
590
- safeParse(data, params) {
591
- const ctx = {
592
- common: {
593
- issues: [],
594
- async: params?.async ?? false,
595
- contextualErrorMap: params?.errorMap
596
- },
597
- path: params?.path || [],
598
- schemaErrorMap: this._def.errorMap,
599
- parent: null,
600
- data,
601
- parsedType: getParsedType(data)
602
- };
603
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
604
- return handleResult(ctx, result);
605
- }
606
- "~validate"(data) {
607
- const ctx = {
608
- common: {
609
- issues: [],
610
- async: !!this["~standard"].async
611
- },
612
- path: [],
613
- schemaErrorMap: this._def.errorMap,
614
- parent: null,
615
- data,
616
- parsedType: getParsedType(data)
617
- };
618
- if (!this["~standard"].async) {
619
- try {
620
- const result = this._parseSync({ data, path: [], parent: ctx });
621
- return isValid(result) ? {
622
- value: result.value
623
- } : {
624
- issues: ctx.common.issues
625
- };
626
- } catch (err) {
627
- if (err?.message?.toLowerCase()?.includes("encountered")) {
628
- this["~standard"].async = true;
629
- }
630
- ctx.common = {
631
- issues: [],
632
- async: true
633
- };
634
- }
635
- }
636
- return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
637
- value: result.value
638
- } : {
639
- issues: ctx.common.issues
640
- });
641
- }
642
- async parseAsync(data, params) {
643
- const result = await this.safeParseAsync(data, params);
644
- if (result.success)
645
- return result.data;
646
- throw result.error;
647
- }
648
- async safeParseAsync(data, params) {
649
- const ctx = {
650
- common: {
651
- issues: [],
652
- contextualErrorMap: params?.errorMap,
653
- async: true
654
- },
655
- path: params?.path || [],
656
- schemaErrorMap: this._def.errorMap,
657
- parent: null,
658
- data,
659
- parsedType: getParsedType(data)
660
- };
661
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
662
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
663
- return handleResult(ctx, result);
664
- }
665
- refine(check, message) {
666
- const getIssueProperties = (val) => {
667
- if (typeof message === "string" || typeof message === "undefined") {
668
- return { message };
669
- } else if (typeof message === "function") {
670
- return message(val);
671
- } else {
672
- return message;
673
- }
674
- };
675
- return this._refinement((val, ctx) => {
676
- const result = check(val);
677
- const setError = () => ctx.addIssue({
678
- code: ZodIssueCode.custom,
679
- ...getIssueProperties(val)
680
- });
681
- if (typeof Promise !== "undefined" && result instanceof Promise) {
682
- return result.then((data) => {
683
- if (!data) {
684
- setError();
685
- return false;
686
- } else {
687
- return true;
688
- }
689
- });
690
- }
691
- if (!result) {
692
- setError();
693
- return false;
694
- } else {
695
- return true;
696
- }
697
- });
698
- }
699
- refinement(check, refinementData) {
700
- return this._refinement((val, ctx) => {
701
- if (!check(val)) {
702
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
703
- return false;
704
- } else {
705
- return true;
706
- }
707
- });
708
- }
709
- _refinement(refinement) {
710
- return new ZodEffects({
711
- schema: this,
712
- typeName: ZodFirstPartyTypeKind.ZodEffects,
713
- effect: { type: "refinement", refinement }
714
- });
715
- }
716
- superRefine(refinement) {
717
- return this._refinement(refinement);
718
- }
719
- constructor(def) {
720
- this.spa = this.safeParseAsync;
721
- this._def = def;
722
- this.parse = this.parse.bind(this);
723
- this.safeParse = this.safeParse.bind(this);
724
- this.parseAsync = this.parseAsync.bind(this);
725
- this.safeParseAsync = this.safeParseAsync.bind(this);
726
- this.spa = this.spa.bind(this);
727
- this.refine = this.refine.bind(this);
728
- this.refinement = this.refinement.bind(this);
729
- this.superRefine = this.superRefine.bind(this);
730
- this.optional = this.optional.bind(this);
731
- this.nullable = this.nullable.bind(this);
732
- this.nullish = this.nullish.bind(this);
733
- this.array = this.array.bind(this);
734
- this.promise = this.promise.bind(this);
735
- this.or = this.or.bind(this);
736
- this.and = this.and.bind(this);
737
- this.transform = this.transform.bind(this);
738
- this.brand = this.brand.bind(this);
739
- this.default = this.default.bind(this);
740
- this.catch = this.catch.bind(this);
741
- this.describe = this.describe.bind(this);
742
- this.pipe = this.pipe.bind(this);
743
- this.readonly = this.readonly.bind(this);
744
- this.isNullable = this.isNullable.bind(this);
745
- this.isOptional = this.isOptional.bind(this);
746
- this["~standard"] = {
747
- version: 1,
748
- vendor: "zod",
749
- validate: (data) => this["~validate"](data)
750
- };
751
- }
752
- optional() {
753
- return ZodOptional.create(this, this._def);
754
- }
755
- nullable() {
756
- return ZodNullable.create(this, this._def);
757
- }
758
- nullish() {
759
- return this.nullable().optional();
760
- }
761
- array() {
762
- return ZodArray.create(this);
763
- }
764
- promise() {
765
- return ZodPromise.create(this, this._def);
766
- }
767
- or(option) {
768
- return ZodUnion.create([this, option], this._def);
769
- }
770
- and(incoming) {
771
- return ZodIntersection.create(this, incoming, this._def);
772
- }
773
- transform(transform) {
774
- return new ZodEffects({
775
- ...processCreateParams(this._def),
776
- schema: this,
777
- typeName: ZodFirstPartyTypeKind.ZodEffects,
778
- effect: { type: "transform", transform }
779
- });
780
- }
781
- default(def) {
782
- const defaultValueFunc = typeof def === "function" ? def : () => def;
783
- return new ZodDefault({
784
- ...processCreateParams(this._def),
785
- innerType: this,
786
- defaultValue: defaultValueFunc,
787
- typeName: ZodFirstPartyTypeKind.ZodDefault
788
- });
789
- }
790
- brand() {
791
- return new ZodBranded({
792
- typeName: ZodFirstPartyTypeKind.ZodBranded,
793
- type: this,
794
- ...processCreateParams(this._def)
795
- });
796
- }
797
- catch(def) {
798
- const catchValueFunc = typeof def === "function" ? def : () => def;
799
- return new ZodCatch({
800
- ...processCreateParams(this._def),
801
- innerType: this,
802
- catchValue: catchValueFunc,
803
- typeName: ZodFirstPartyTypeKind.ZodCatch
804
- });
805
- }
806
- describe(description) {
807
- const This = this.constructor;
808
- return new This({
809
- ...this._def,
810
- description
811
- });
812
- }
813
- pipe(target) {
814
- return ZodPipeline.create(this, target);
815
- }
816
- readonly() {
817
- return ZodReadonly.create(this);
818
- }
819
- isOptional() {
820
- return this.safeParse(undefined).success;
821
- }
822
- isNullable() {
823
- return this.safeParse(null).success;
824
- }
825
- }
826
- function timeRegexSource(args) {
827
- let secondsRegexSource = `[0-5]\\d`;
828
- if (args.precision) {
829
- secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
830
- } else if (args.precision == null) {
831
- secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
832
- }
833
- const secondsQuantifier = args.precision ? "+" : "?";
834
- return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
835
- }
836
- function timeRegex(args) {
837
- return new RegExp(`^${timeRegexSource(args)}$`);
838
- }
839
- function datetimeRegex(args) {
840
- let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
841
- const opts = [];
842
- opts.push(args.local ? `Z?` : `Z`);
843
- if (args.offset)
844
- opts.push(`([+-]\\d{2}:?\\d{2})`);
845
- regex = `${regex}(${opts.join("|")})`;
846
- return new RegExp(`^${regex}$`);
847
- }
848
- function isValidIP(ip, version) {
849
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
850
- return true;
851
- }
852
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
853
- return true;
854
- }
855
- return false;
856
- }
857
- function isValidJWT(jwt, alg) {
858
- if (!jwtRegex.test(jwt))
859
- return false;
860
- try {
861
- const [header] = jwt.split(".");
862
- const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
863
- const decoded = JSON.parse(atob(base64));
864
- if (typeof decoded !== "object" || decoded === null)
865
- return false;
866
- if ("typ" in decoded && decoded?.typ !== "JWT")
867
- return false;
868
- if (!decoded.alg)
869
- return false;
870
- if (alg && decoded.alg !== alg)
871
- return false;
872
- return true;
873
- } catch {
874
- return false;
875
- }
876
- }
877
- function isValidCidr(ip, version) {
878
- if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
879
- return true;
880
- }
881
- if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
882
- return true;
883
- }
884
- return false;
885
- }
886
- function floatSafeRemainder(val, step) {
887
- const valDecCount = (val.toString().split(".")[1] || "").length;
888
- const stepDecCount = (step.toString().split(".")[1] || "").length;
889
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
890
- const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
891
- const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
892
- return valInt % stepInt / 10 ** decCount;
893
- }
894
- function deepPartialify(schema) {
895
- if (schema instanceof ZodObject) {
896
- const newShape = {};
897
- for (const key in schema.shape) {
898
- const fieldSchema = schema.shape[key];
899
- newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
900
- }
901
- return new ZodObject({
902
- ...schema._def,
903
- shape: () => newShape
904
- });
905
- } else if (schema instanceof ZodArray) {
906
- return new ZodArray({
907
- ...schema._def,
908
- type: deepPartialify(schema.element)
909
- });
910
- } else if (schema instanceof ZodOptional) {
911
- return ZodOptional.create(deepPartialify(schema.unwrap()));
912
- } else if (schema instanceof ZodNullable) {
913
- return ZodNullable.create(deepPartialify(schema.unwrap()));
914
- } else if (schema instanceof ZodTuple) {
915
- return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
916
- } else {
917
- return schema;
918
- }
919
- }
920
- function mergeValues(a, b) {
921
- const aType = getParsedType(a);
922
- const bType = getParsedType(b);
923
- if (a === b) {
924
- return { valid: true, data: a };
925
- } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
926
- const bKeys = util.objectKeys(b);
927
- const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
928
- const newObj = { ...a, ...b };
929
- for (const key of sharedKeys) {
930
- const sharedValue = mergeValues(a[key], b[key]);
931
- if (!sharedValue.valid) {
932
- return { valid: false };
933
- }
934
- newObj[key] = sharedValue.data;
935
- }
936
- return { valid: true, data: newObj };
937
- } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
938
- if (a.length !== b.length) {
939
- return { valid: false };
940
- }
941
- const newArray = [];
942
- for (let index = 0;index < a.length; index++) {
943
- const itemA = a[index];
944
- const itemB = b[index];
945
- const sharedValue = mergeValues(itemA, itemB);
946
- if (!sharedValue.valid) {
947
- return { valid: false };
948
- }
949
- newArray.push(sharedValue.data);
950
- }
951
- return { valid: true, data: newArray };
952
- } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
953
- return { valid: true, data: a };
954
- } else {
955
- return { valid: false };
956
- }
957
- }
958
- function createZodEnum(values, params) {
959
- return new ZodEnum({
960
- values,
961
- typeName: ZodFirstPartyTypeKind.ZodEnum,
962
- ...processCreateParams(params)
963
- });
964
- }
965
- function cleanParams(params, data) {
966
- const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
967
- const p2 = typeof p === "string" ? { message: p } : p;
968
- return p2;
969
- }
970
- function custom(check, _params = {}, fatal) {
971
- if (check)
972
- return ZodAny.create().superRefine((data, ctx) => {
973
- const r = check(data);
974
- if (r instanceof Promise) {
975
- return r.then((r2) => {
976
- if (!r2) {
977
- const params = cleanParams(_params, data);
978
- const _fatal = params.fatal ?? fatal ?? true;
979
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
980
- }
981
- });
982
- }
983
- if (!r) {
984
- const params = cleanParams(_params, data);
985
- const _fatal = params.fatal ?? fatal ?? true;
986
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
987
- }
988
- return;
989
- });
990
- return ZodAny.create();
991
- }
992
- var __classPrivateFieldGet = function(receiver, state, kind, f) {
993
- if (kind === "a" && !f)
994
- throw new TypeError("Private accessor was defined without a getter");
995
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
996
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
997
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
998
- }, __classPrivateFieldSet = function(receiver, state, value, kind, f) {
999
- if (kind === "m")
1000
- throw new TypeError("Private method is not writable");
1001
- if (kind === "a" && !f)
1002
- throw new TypeError("Private accessor was defined without a setter");
1003
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
1004
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
1005
- return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
1006
- }, _ZodEnum_cache, _ZodNativeEnum_cache, handleResult = (ctx, result) => {
1007
- if (isValid(result)) {
1008
- return { success: true, data: result.value };
1009
- } else {
1010
- if (!ctx.common.issues.length) {
1011
- throw new Error("Validation failed but no issues detected.");
1012
- }
1013
- return {
1014
- success: false,
1015
- get error() {
1016
- if (this._error)
1017
- return this._error;
1018
- const error = new ZodError(ctx.common.issues);
1019
- this._error = error;
1020
- return this._error;
1021
- }
1022
- };
1023
- }
1024
- }, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator = (type) => {
1025
- if (type instanceof ZodLazy) {
1026
- return getDiscriminator(type.schema);
1027
- } else if (type instanceof ZodEffects) {
1028
- return getDiscriminator(type.innerType());
1029
- } else if (type instanceof ZodLiteral) {
1030
- return [type.value];
1031
- } else if (type instanceof ZodEnum) {
1032
- return type.options;
1033
- } else if (type instanceof ZodNativeEnum) {
1034
- return util.objectValues(type.enum);
1035
- } else if (type instanceof ZodDefault) {
1036
- return getDiscriminator(type._def.innerType);
1037
- } else if (type instanceof ZodUndefined) {
1038
- return [undefined];
1039
- } else if (type instanceof ZodNull) {
1040
- return [null];
1041
- } else if (type instanceof ZodOptional) {
1042
- return [undefined, ...getDiscriminator(type.unwrap())];
1043
- } else if (type instanceof ZodNullable) {
1044
- return [null, ...getDiscriminator(type.unwrap())];
1045
- } else if (type instanceof ZodBranded) {
1046
- return getDiscriminator(type.unwrap());
1047
- } else if (type instanceof ZodReadonly) {
1048
- return getDiscriminator(type.unwrap());
1049
- } else if (type instanceof ZodCatch) {
1050
- return getDiscriminator(type._def.innerType);
1051
- } else {
1052
- return [];
1053
- }
1054
- }, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, instanceOfType = (cls, params = {
1055
- message: `Input not instance of ${cls.name}`
1056
- }) => custom((data) => data instanceof cls, params), stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring = () => stringType().optional(), onumber = () => numberType().optional(), oboolean = () => booleanType().optional(), coerce, NEVER;
1057
- var init_types = __esm(() => {
1058
- init_ZodError();
1059
- init_errors();
1060
- init_errorUtil();
1061
- init_parseUtil();
1062
- init_util();
1063
- cuidRegex = /^c[^\s-]{8,}$/i;
1064
- cuid2Regex = /^[0-9a-z]+$/;
1065
- ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
1066
- uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
1067
- nanoidRegex = /^[a-z0-9_-]{21}$/i;
1068
- jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
1069
- durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
1070
- emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1071
- ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
1072
- ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
1073
- ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
1074
- ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
1075
- base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
1076
- base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
1077
- dateRegex = new RegExp(`^${dateRegexSource}$`);
1078
- ZodString = class ZodString extends ZodType {
1079
- _parse(input) {
1080
- if (this._def.coerce) {
1081
- input.data = String(input.data);
1082
- }
1083
- const parsedType = this._getType(input);
1084
- if (parsedType !== ZodParsedType.string) {
1085
- const ctx2 = this._getOrReturnCtx(input);
1086
- addIssueToContext(ctx2, {
1087
- code: ZodIssueCode.invalid_type,
1088
- expected: ZodParsedType.string,
1089
- received: ctx2.parsedType
1090
- });
1091
- return INVALID;
1092
- }
1093
- const status = new ParseStatus;
1094
- let ctx = undefined;
1095
- for (const check of this._def.checks) {
1096
- if (check.kind === "min") {
1097
- if (input.data.length < check.value) {
1098
- ctx = this._getOrReturnCtx(input, ctx);
1099
- addIssueToContext(ctx, {
1100
- code: ZodIssueCode.too_small,
1101
- minimum: check.value,
1102
- type: "string",
1103
- inclusive: true,
1104
- exact: false,
1105
- message: check.message
1106
- });
1107
- status.dirty();
1108
- }
1109
- } else if (check.kind === "max") {
1110
- if (input.data.length > check.value) {
1111
- ctx = this._getOrReturnCtx(input, ctx);
1112
- addIssueToContext(ctx, {
1113
- code: ZodIssueCode.too_big,
1114
- maximum: check.value,
1115
- type: "string",
1116
- inclusive: true,
1117
- exact: false,
1118
- message: check.message
1119
- });
1120
- status.dirty();
1121
- }
1122
- } else if (check.kind === "length") {
1123
- const tooBig = input.data.length > check.value;
1124
- const tooSmall = input.data.length < check.value;
1125
- if (tooBig || tooSmall) {
1126
- ctx = this._getOrReturnCtx(input, ctx);
1127
- if (tooBig) {
1128
- addIssueToContext(ctx, {
1129
- code: ZodIssueCode.too_big,
1130
- maximum: check.value,
1131
- type: "string",
1132
- inclusive: true,
1133
- exact: true,
1134
- message: check.message
1135
- });
1136
- } else if (tooSmall) {
1137
- addIssueToContext(ctx, {
1138
- code: ZodIssueCode.too_small,
1139
- minimum: check.value,
1140
- type: "string",
1141
- inclusive: true,
1142
- exact: true,
1143
- message: check.message
1144
- });
1145
- }
1146
- status.dirty();
1147
- }
1148
- } else if (check.kind === "email") {
1149
- if (!emailRegex.test(input.data)) {
1150
- ctx = this._getOrReturnCtx(input, ctx);
1151
- addIssueToContext(ctx, {
1152
- validation: "email",
1153
- code: ZodIssueCode.invalid_string,
1154
- message: check.message
1155
- });
1156
- status.dirty();
1157
- }
1158
- } else if (check.kind === "emoji") {
1159
- if (!emojiRegex) {
1160
- emojiRegex = new RegExp(_emojiRegex, "u");
1161
- }
1162
- if (!emojiRegex.test(input.data)) {
1163
- ctx = this._getOrReturnCtx(input, ctx);
1164
- addIssueToContext(ctx, {
1165
- validation: "emoji",
1166
- code: ZodIssueCode.invalid_string,
1167
- message: check.message
1168
- });
1169
- status.dirty();
1170
- }
1171
- } else if (check.kind === "uuid") {
1172
- if (!uuidRegex.test(input.data)) {
1173
- ctx = this._getOrReturnCtx(input, ctx);
1174
- addIssueToContext(ctx, {
1175
- validation: "uuid",
1176
- code: ZodIssueCode.invalid_string,
1177
- message: check.message
1178
- });
1179
- status.dirty();
1180
- }
1181
- } else if (check.kind === "nanoid") {
1182
- if (!nanoidRegex.test(input.data)) {
1183
- ctx = this._getOrReturnCtx(input, ctx);
1184
- addIssueToContext(ctx, {
1185
- validation: "nanoid",
1186
- code: ZodIssueCode.invalid_string,
1187
- message: check.message
1188
- });
1189
- status.dirty();
1190
- }
1191
- } else if (check.kind === "cuid") {
1192
- if (!cuidRegex.test(input.data)) {
1193
- ctx = this._getOrReturnCtx(input, ctx);
1194
- addIssueToContext(ctx, {
1195
- validation: "cuid",
1196
- code: ZodIssueCode.invalid_string,
1197
- message: check.message
1198
- });
1199
- status.dirty();
1200
- }
1201
- } else if (check.kind === "cuid2") {
1202
- if (!cuid2Regex.test(input.data)) {
1203
- ctx = this._getOrReturnCtx(input, ctx);
1204
- addIssueToContext(ctx, {
1205
- validation: "cuid2",
1206
- code: ZodIssueCode.invalid_string,
1207
- message: check.message
1208
- });
1209
- status.dirty();
1210
- }
1211
- } else if (check.kind === "ulid") {
1212
- if (!ulidRegex.test(input.data)) {
1213
- ctx = this._getOrReturnCtx(input, ctx);
1214
- addIssueToContext(ctx, {
1215
- validation: "ulid",
1216
- code: ZodIssueCode.invalid_string,
1217
- message: check.message
1218
- });
1219
- status.dirty();
1220
- }
1221
- } else if (check.kind === "url") {
1222
- try {
1223
- new URL(input.data);
1224
- } catch {
1225
- ctx = this._getOrReturnCtx(input, ctx);
1226
- addIssueToContext(ctx, {
1227
- validation: "url",
1228
- code: ZodIssueCode.invalid_string,
1229
- message: check.message
1230
- });
1231
- status.dirty();
1232
- }
1233
- } else if (check.kind === "regex") {
1234
- check.regex.lastIndex = 0;
1235
- const testResult = check.regex.test(input.data);
1236
- if (!testResult) {
1237
- ctx = this._getOrReturnCtx(input, ctx);
1238
- addIssueToContext(ctx, {
1239
- validation: "regex",
1240
- code: ZodIssueCode.invalid_string,
1241
- message: check.message
1242
- });
1243
- status.dirty();
1244
- }
1245
- } else if (check.kind === "trim") {
1246
- input.data = input.data.trim();
1247
- } else if (check.kind === "includes") {
1248
- if (!input.data.includes(check.value, check.position)) {
1249
- ctx = this._getOrReturnCtx(input, ctx);
1250
- addIssueToContext(ctx, {
1251
- code: ZodIssueCode.invalid_string,
1252
- validation: { includes: check.value, position: check.position },
1253
- message: check.message
1254
- });
1255
- status.dirty();
1256
- }
1257
- } else if (check.kind === "toLowerCase") {
1258
- input.data = input.data.toLowerCase();
1259
- } else if (check.kind === "toUpperCase") {
1260
- input.data = input.data.toUpperCase();
1261
- } else if (check.kind === "startsWith") {
1262
- if (!input.data.startsWith(check.value)) {
1263
- ctx = this._getOrReturnCtx(input, ctx);
1264
- addIssueToContext(ctx, {
1265
- code: ZodIssueCode.invalid_string,
1266
- validation: { startsWith: check.value },
1267
- message: check.message
1268
- });
1269
- status.dirty();
1270
- }
1271
- } else if (check.kind === "endsWith") {
1272
- if (!input.data.endsWith(check.value)) {
1273
- ctx = this._getOrReturnCtx(input, ctx);
1274
- addIssueToContext(ctx, {
1275
- code: ZodIssueCode.invalid_string,
1276
- validation: { endsWith: check.value },
1277
- message: check.message
1278
- });
1279
- status.dirty();
1280
- }
1281
- } else if (check.kind === "datetime") {
1282
- const regex = datetimeRegex(check);
1283
- if (!regex.test(input.data)) {
1284
- ctx = this._getOrReturnCtx(input, ctx);
1285
- addIssueToContext(ctx, {
1286
- code: ZodIssueCode.invalid_string,
1287
- validation: "datetime",
1288
- message: check.message
1289
- });
1290
- status.dirty();
1291
- }
1292
- } else if (check.kind === "date") {
1293
- const regex = dateRegex;
1294
- if (!regex.test(input.data)) {
1295
- ctx = this._getOrReturnCtx(input, ctx);
1296
- addIssueToContext(ctx, {
1297
- code: ZodIssueCode.invalid_string,
1298
- validation: "date",
1299
- message: check.message
1300
- });
1301
- status.dirty();
1302
- }
1303
- } else if (check.kind === "time") {
1304
- const regex = timeRegex(check);
1305
- if (!regex.test(input.data)) {
1306
- ctx = this._getOrReturnCtx(input, ctx);
1307
- addIssueToContext(ctx, {
1308
- code: ZodIssueCode.invalid_string,
1309
- validation: "time",
1310
- message: check.message
1311
- });
1312
- status.dirty();
1313
- }
1314
- } else if (check.kind === "duration") {
1315
- if (!durationRegex.test(input.data)) {
1316
- ctx = this._getOrReturnCtx(input, ctx);
1317
- addIssueToContext(ctx, {
1318
- validation: "duration",
1319
- code: ZodIssueCode.invalid_string,
1320
- message: check.message
1321
- });
1322
- status.dirty();
1323
- }
1324
- } else if (check.kind === "ip") {
1325
- if (!isValidIP(input.data, check.version)) {
1326
- ctx = this._getOrReturnCtx(input, ctx);
1327
- addIssueToContext(ctx, {
1328
- validation: "ip",
1329
- code: ZodIssueCode.invalid_string,
1330
- message: check.message
1331
- });
1332
- status.dirty();
1333
- }
1334
- } else if (check.kind === "jwt") {
1335
- if (!isValidJWT(input.data, check.alg)) {
1336
- ctx = this._getOrReturnCtx(input, ctx);
1337
- addIssueToContext(ctx, {
1338
- validation: "jwt",
1339
- code: ZodIssueCode.invalid_string,
1340
- message: check.message
1341
- });
1342
- status.dirty();
1343
- }
1344
- } else if (check.kind === "cidr") {
1345
- if (!isValidCidr(input.data, check.version)) {
1346
- ctx = this._getOrReturnCtx(input, ctx);
1347
- addIssueToContext(ctx, {
1348
- validation: "cidr",
1349
- code: ZodIssueCode.invalid_string,
1350
- message: check.message
1351
- });
1352
- status.dirty();
1353
- }
1354
- } else if (check.kind === "base64") {
1355
- if (!base64Regex.test(input.data)) {
1356
- ctx = this._getOrReturnCtx(input, ctx);
1357
- addIssueToContext(ctx, {
1358
- validation: "base64",
1359
- code: ZodIssueCode.invalid_string,
1360
- message: check.message
1361
- });
1362
- status.dirty();
1363
- }
1364
- } else if (check.kind === "base64url") {
1365
- if (!base64urlRegex.test(input.data)) {
1366
- ctx = this._getOrReturnCtx(input, ctx);
1367
- addIssueToContext(ctx, {
1368
- validation: "base64url",
1369
- code: ZodIssueCode.invalid_string,
1370
- message: check.message
1371
- });
1372
- status.dirty();
1373
- }
1374
- } else {
1375
- util.assertNever(check);
1376
- }
1377
- }
1378
- return { status: status.value, value: input.data };
1379
- }
1380
- _regex(regex, validation, message) {
1381
- return this.refinement((data) => regex.test(data), {
1382
- validation,
1383
- code: ZodIssueCode.invalid_string,
1384
- ...errorUtil.errToObj(message)
1385
- });
1386
- }
1387
- _addCheck(check) {
1388
- return new ZodString({
1389
- ...this._def,
1390
- checks: [...this._def.checks, check]
1391
- });
1392
- }
1393
- email(message) {
1394
- return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1395
- }
1396
- url(message) {
1397
- return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1398
- }
1399
- emoji(message) {
1400
- return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1401
- }
1402
- uuid(message) {
1403
- return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1404
- }
1405
- nanoid(message) {
1406
- return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1407
- }
1408
- cuid(message) {
1409
- return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1410
- }
1411
- cuid2(message) {
1412
- return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1413
- }
1414
- ulid(message) {
1415
- return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1416
- }
1417
- base64(message) {
1418
- return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1419
- }
1420
- base64url(message) {
1421
- return this._addCheck({
1422
- kind: "base64url",
1423
- ...errorUtil.errToObj(message)
1424
- });
1425
- }
1426
- jwt(options) {
1427
- return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
1428
- }
1429
- ip(options) {
1430
- return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1431
- }
1432
- cidr(options) {
1433
- return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
1434
- }
1435
- datetime(options) {
1436
- if (typeof options === "string") {
1437
- return this._addCheck({
1438
- kind: "datetime",
1439
- precision: null,
1440
- offset: false,
1441
- local: false,
1442
- message: options
1443
- });
1444
- }
1445
- return this._addCheck({
1446
- kind: "datetime",
1447
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
1448
- offset: options?.offset ?? false,
1449
- local: options?.local ?? false,
1450
- ...errorUtil.errToObj(options?.message)
1451
- });
1452
- }
1453
- date(message) {
1454
- return this._addCheck({ kind: "date", message });
1455
- }
1456
- time(options) {
1457
- if (typeof options === "string") {
1458
- return this._addCheck({
1459
- kind: "time",
1460
- precision: null,
1461
- message: options
1462
- });
1463
- }
1464
- return this._addCheck({
1465
- kind: "time",
1466
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
1467
- ...errorUtil.errToObj(options?.message)
1468
- });
1469
- }
1470
- duration(message) {
1471
- return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1472
- }
1473
- regex(regex, message) {
1474
- return this._addCheck({
1475
- kind: "regex",
1476
- regex,
1477
- ...errorUtil.errToObj(message)
1478
- });
1479
- }
1480
- includes(value, options) {
1481
- return this._addCheck({
1482
- kind: "includes",
1483
- value,
1484
- position: options?.position,
1485
- ...errorUtil.errToObj(options?.message)
1486
- });
1487
- }
1488
- startsWith(value, message) {
1489
- return this._addCheck({
1490
- kind: "startsWith",
1491
- value,
1492
- ...errorUtil.errToObj(message)
1493
- });
1494
- }
1495
- endsWith(value, message) {
1496
- return this._addCheck({
1497
- kind: "endsWith",
1498
- value,
1499
- ...errorUtil.errToObj(message)
1500
- });
1501
- }
1502
- min(minLength, message) {
1503
- return this._addCheck({
1504
- kind: "min",
1505
- value: minLength,
1506
- ...errorUtil.errToObj(message)
1507
- });
1508
- }
1509
- max(maxLength, message) {
1510
- return this._addCheck({
1511
- kind: "max",
1512
- value: maxLength,
1513
- ...errorUtil.errToObj(message)
1514
- });
1515
- }
1516
- length(len, message) {
1517
- return this._addCheck({
1518
- kind: "length",
1519
- value: len,
1520
- ...errorUtil.errToObj(message)
1521
- });
1522
- }
1523
- nonempty(message) {
1524
- return this.min(1, errorUtil.errToObj(message));
1525
- }
1526
- trim() {
1527
- return new ZodString({
1528
- ...this._def,
1529
- checks: [...this._def.checks, { kind: "trim" }]
1530
- });
1531
- }
1532
- toLowerCase() {
1533
- return new ZodString({
1534
- ...this._def,
1535
- checks: [...this._def.checks, { kind: "toLowerCase" }]
1536
- });
1537
- }
1538
- toUpperCase() {
1539
- return new ZodString({
1540
- ...this._def,
1541
- checks: [...this._def.checks, { kind: "toUpperCase" }]
1542
- });
1543
- }
1544
- get isDatetime() {
1545
- return !!this._def.checks.find((ch) => ch.kind === "datetime");
1546
- }
1547
- get isDate() {
1548
- return !!this._def.checks.find((ch) => ch.kind === "date");
1549
- }
1550
- get isTime() {
1551
- return !!this._def.checks.find((ch) => ch.kind === "time");
1552
- }
1553
- get isDuration() {
1554
- return !!this._def.checks.find((ch) => ch.kind === "duration");
1555
- }
1556
- get isEmail() {
1557
- return !!this._def.checks.find((ch) => ch.kind === "email");
1558
- }
1559
- get isURL() {
1560
- return !!this._def.checks.find((ch) => ch.kind === "url");
1561
- }
1562
- get isEmoji() {
1563
- return !!this._def.checks.find((ch) => ch.kind === "emoji");
1564
- }
1565
- get isUUID() {
1566
- return !!this._def.checks.find((ch) => ch.kind === "uuid");
1567
- }
1568
- get isNANOID() {
1569
- return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1570
- }
1571
- get isCUID() {
1572
- return !!this._def.checks.find((ch) => ch.kind === "cuid");
1573
- }
1574
- get isCUID2() {
1575
- return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1576
- }
1577
- get isULID() {
1578
- return !!this._def.checks.find((ch) => ch.kind === "ulid");
1579
- }
1580
- get isIP() {
1581
- return !!this._def.checks.find((ch) => ch.kind === "ip");
1582
- }
1583
- get isCIDR() {
1584
- return !!this._def.checks.find((ch) => ch.kind === "cidr");
1585
- }
1586
- get isBase64() {
1587
- return !!this._def.checks.find((ch) => ch.kind === "base64");
1588
- }
1589
- get isBase64url() {
1590
- return !!this._def.checks.find((ch) => ch.kind === "base64url");
1591
- }
1592
- get minLength() {
1593
- let min = null;
1594
- for (const ch of this._def.checks) {
1595
- if (ch.kind === "min") {
1596
- if (min === null || ch.value > min)
1597
- min = ch.value;
1598
- }
1599
- }
1600
- return min;
1601
- }
1602
- get maxLength() {
1603
- let max = null;
1604
- for (const ch of this._def.checks) {
1605
- if (ch.kind === "max") {
1606
- if (max === null || ch.value < max)
1607
- max = ch.value;
1608
- }
1609
- }
1610
- return max;
1611
- }
1612
- };
1613
- ZodString.create = (params) => {
1614
- return new ZodString({
1615
- checks: [],
1616
- typeName: ZodFirstPartyTypeKind.ZodString,
1617
- coerce: params?.coerce ?? false,
1618
- ...processCreateParams(params)
1619
- });
1620
- };
1621
- ZodNumber = class ZodNumber extends ZodType {
1622
- constructor() {
1623
- super(...arguments);
1624
- this.min = this.gte;
1625
- this.max = this.lte;
1626
- this.step = this.multipleOf;
1627
- }
1628
- _parse(input) {
1629
- if (this._def.coerce) {
1630
- input.data = Number(input.data);
1631
- }
1632
- const parsedType = this._getType(input);
1633
- if (parsedType !== ZodParsedType.number) {
1634
- const ctx2 = this._getOrReturnCtx(input);
1635
- addIssueToContext(ctx2, {
1636
- code: ZodIssueCode.invalid_type,
1637
- expected: ZodParsedType.number,
1638
- received: ctx2.parsedType
1639
- });
1640
- return INVALID;
1641
- }
1642
- let ctx = undefined;
1643
- const status = new ParseStatus;
1644
- for (const check of this._def.checks) {
1645
- if (check.kind === "int") {
1646
- if (!util.isInteger(input.data)) {
1647
- ctx = this._getOrReturnCtx(input, ctx);
1648
- addIssueToContext(ctx, {
1649
- code: ZodIssueCode.invalid_type,
1650
- expected: "integer",
1651
- received: "float",
1652
- message: check.message
1653
- });
1654
- status.dirty();
1655
- }
1656
- } else if (check.kind === "min") {
1657
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1658
- if (tooSmall) {
1659
- ctx = this._getOrReturnCtx(input, ctx);
1660
- addIssueToContext(ctx, {
1661
- code: ZodIssueCode.too_small,
1662
- minimum: check.value,
1663
- type: "number",
1664
- inclusive: check.inclusive,
1665
- exact: false,
1666
- message: check.message
1667
- });
1668
- status.dirty();
1669
- }
1670
- } else if (check.kind === "max") {
1671
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1672
- if (tooBig) {
1673
- ctx = this._getOrReturnCtx(input, ctx);
1674
- addIssueToContext(ctx, {
1675
- code: ZodIssueCode.too_big,
1676
- maximum: check.value,
1677
- type: "number",
1678
- inclusive: check.inclusive,
1679
- exact: false,
1680
- message: check.message
1681
- });
1682
- status.dirty();
1683
- }
1684
- } else if (check.kind === "multipleOf") {
1685
- if (floatSafeRemainder(input.data, check.value) !== 0) {
1686
- ctx = this._getOrReturnCtx(input, ctx);
1687
- addIssueToContext(ctx, {
1688
- code: ZodIssueCode.not_multiple_of,
1689
- multipleOf: check.value,
1690
- message: check.message
1691
- });
1692
- status.dirty();
1693
- }
1694
- } else if (check.kind === "finite") {
1695
- if (!Number.isFinite(input.data)) {
1696
- ctx = this._getOrReturnCtx(input, ctx);
1697
- addIssueToContext(ctx, {
1698
- code: ZodIssueCode.not_finite,
1699
- message: check.message
1700
- });
1701
- status.dirty();
1702
- }
1703
- } else {
1704
- util.assertNever(check);
1705
- }
1706
- }
1707
- return { status: status.value, value: input.data };
1708
- }
1709
- gte(value, message) {
1710
- return this.setLimit("min", value, true, errorUtil.toString(message));
1711
- }
1712
- gt(value, message) {
1713
- return this.setLimit("min", value, false, errorUtil.toString(message));
1714
- }
1715
- lte(value, message) {
1716
- return this.setLimit("max", value, true, errorUtil.toString(message));
1717
- }
1718
- lt(value, message) {
1719
- return this.setLimit("max", value, false, errorUtil.toString(message));
1720
- }
1721
- setLimit(kind, value, inclusive, message) {
1722
- return new ZodNumber({
1723
- ...this._def,
1724
- checks: [
1725
- ...this._def.checks,
1726
- {
1727
- kind,
1728
- value,
1729
- inclusive,
1730
- message: errorUtil.toString(message)
1731
- }
1732
- ]
1733
- });
1734
- }
1735
- _addCheck(check) {
1736
- return new ZodNumber({
1737
- ...this._def,
1738
- checks: [...this._def.checks, check]
1739
- });
1740
- }
1741
- int(message) {
1742
- return this._addCheck({
1743
- kind: "int",
1744
- message: errorUtil.toString(message)
1745
- });
1746
- }
1747
- positive(message) {
1748
- return this._addCheck({
1749
- kind: "min",
1750
- value: 0,
1751
- inclusive: false,
1752
- message: errorUtil.toString(message)
1753
- });
1754
- }
1755
- negative(message) {
1756
- return this._addCheck({
1757
- kind: "max",
1758
- value: 0,
1759
- inclusive: false,
1760
- message: errorUtil.toString(message)
1761
- });
1762
- }
1763
- nonpositive(message) {
1764
- return this._addCheck({
1765
- kind: "max",
1766
- value: 0,
1767
- inclusive: true,
1768
- message: errorUtil.toString(message)
1769
- });
1770
- }
1771
- nonnegative(message) {
1772
- return this._addCheck({
1773
- kind: "min",
1774
- value: 0,
1775
- inclusive: true,
1776
- message: errorUtil.toString(message)
1777
- });
1778
- }
1779
- multipleOf(value, message) {
1780
- return this._addCheck({
1781
- kind: "multipleOf",
1782
- value,
1783
- message: errorUtil.toString(message)
1784
- });
1785
- }
1786
- finite(message) {
1787
- return this._addCheck({
1788
- kind: "finite",
1789
- message: errorUtil.toString(message)
1790
- });
1791
- }
1792
- safe(message) {
1793
- return this._addCheck({
1794
- kind: "min",
1795
- inclusive: true,
1796
- value: Number.MIN_SAFE_INTEGER,
1797
- message: errorUtil.toString(message)
1798
- })._addCheck({
1799
- kind: "max",
1800
- inclusive: true,
1801
- value: Number.MAX_SAFE_INTEGER,
1802
- message: errorUtil.toString(message)
1803
- });
1804
- }
1805
- get minValue() {
1806
- let min = null;
1807
- for (const ch of this._def.checks) {
1808
- if (ch.kind === "min") {
1809
- if (min === null || ch.value > min)
1810
- min = ch.value;
1811
- }
1812
- }
1813
- return min;
1814
- }
1815
- get maxValue() {
1816
- let max = null;
1817
- for (const ch of this._def.checks) {
1818
- if (ch.kind === "max") {
1819
- if (max === null || ch.value < max)
1820
- max = ch.value;
1821
- }
1822
- }
1823
- return max;
1824
- }
1825
- get isInt() {
1826
- return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
1827
- }
1828
- get isFinite() {
1829
- let max = null;
1830
- let min = null;
1831
- for (const ch of this._def.checks) {
1832
- if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
1833
- return true;
1834
- } else if (ch.kind === "min") {
1835
- if (min === null || ch.value > min)
1836
- min = ch.value;
1837
- } else if (ch.kind === "max") {
1838
- if (max === null || ch.value < max)
1839
- max = ch.value;
1840
- }
1841
- }
1842
- return Number.isFinite(min) && Number.isFinite(max);
1843
- }
1844
- };
1845
- ZodNumber.create = (params) => {
1846
- return new ZodNumber({
1847
- checks: [],
1848
- typeName: ZodFirstPartyTypeKind.ZodNumber,
1849
- coerce: params?.coerce || false,
1850
- ...processCreateParams(params)
1851
- });
1852
- };
1853
- ZodBigInt = class ZodBigInt extends ZodType {
1854
- constructor() {
1855
- super(...arguments);
1856
- this.min = this.gte;
1857
- this.max = this.lte;
1858
- }
1859
- _parse(input) {
1860
- if (this._def.coerce) {
1861
- try {
1862
- input.data = BigInt(input.data);
1863
- } catch {
1864
- return this._getInvalidInput(input);
1865
- }
1866
- }
1867
- const parsedType = this._getType(input);
1868
- if (parsedType !== ZodParsedType.bigint) {
1869
- return this._getInvalidInput(input);
1870
- }
1871
- let ctx = undefined;
1872
- const status = new ParseStatus;
1873
- for (const check of this._def.checks) {
1874
- if (check.kind === "min") {
1875
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1876
- if (tooSmall) {
1877
- ctx = this._getOrReturnCtx(input, ctx);
1878
- addIssueToContext(ctx, {
1879
- code: ZodIssueCode.too_small,
1880
- type: "bigint",
1881
- minimum: check.value,
1882
- inclusive: check.inclusive,
1883
- message: check.message
1884
- });
1885
- status.dirty();
1886
- }
1887
- } else if (check.kind === "max") {
1888
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1889
- if (tooBig) {
1890
- ctx = this._getOrReturnCtx(input, ctx);
1891
- addIssueToContext(ctx, {
1892
- code: ZodIssueCode.too_big,
1893
- type: "bigint",
1894
- maximum: check.value,
1895
- inclusive: check.inclusive,
1896
- message: check.message
1897
- });
1898
- status.dirty();
1899
- }
1900
- } else if (check.kind === "multipleOf") {
1901
- if (input.data % check.value !== BigInt(0)) {
1902
- ctx = this._getOrReturnCtx(input, ctx);
1903
- addIssueToContext(ctx, {
1904
- code: ZodIssueCode.not_multiple_of,
1905
- multipleOf: check.value,
1906
- message: check.message
1907
- });
1908
- status.dirty();
1909
- }
1910
- } else {
1911
- util.assertNever(check);
1912
- }
1913
- }
1914
- return { status: status.value, value: input.data };
1915
- }
1916
- _getInvalidInput(input) {
1917
- const ctx = this._getOrReturnCtx(input);
1918
- addIssueToContext(ctx, {
1919
- code: ZodIssueCode.invalid_type,
1920
- expected: ZodParsedType.bigint,
1921
- received: ctx.parsedType
1922
- });
1923
- return INVALID;
1924
- }
1925
- gte(value, message) {
1926
- return this.setLimit("min", value, true, errorUtil.toString(message));
1927
- }
1928
- gt(value, message) {
1929
- return this.setLimit("min", value, false, errorUtil.toString(message));
1930
- }
1931
- lte(value, message) {
1932
- return this.setLimit("max", value, true, errorUtil.toString(message));
1933
- }
1934
- lt(value, message) {
1935
- return this.setLimit("max", value, false, errorUtil.toString(message));
1936
- }
1937
- setLimit(kind, value, inclusive, message) {
1938
- return new ZodBigInt({
1939
- ...this._def,
1940
- checks: [
1941
- ...this._def.checks,
1942
- {
1943
- kind,
1944
- value,
1945
- inclusive,
1946
- message: errorUtil.toString(message)
1947
- }
1948
- ]
1949
- });
1950
- }
1951
- _addCheck(check) {
1952
- return new ZodBigInt({
1953
- ...this._def,
1954
- checks: [...this._def.checks, check]
1955
- });
1956
- }
1957
- positive(message) {
1958
- return this._addCheck({
1959
- kind: "min",
1960
- value: BigInt(0),
1961
- inclusive: false,
1962
- message: errorUtil.toString(message)
1963
- });
1964
- }
1965
- negative(message) {
1966
- return this._addCheck({
1967
- kind: "max",
1968
- value: BigInt(0),
1969
- inclusive: false,
1970
- message: errorUtil.toString(message)
1971
- });
1972
- }
1973
- nonpositive(message) {
1974
- return this._addCheck({
1975
- kind: "max",
1976
- value: BigInt(0),
1977
- inclusive: true,
1978
- message: errorUtil.toString(message)
1979
- });
1980
- }
1981
- nonnegative(message) {
1982
- return this._addCheck({
1983
- kind: "min",
1984
- value: BigInt(0),
1985
- inclusive: true,
1986
- message: errorUtil.toString(message)
1987
- });
1988
- }
1989
- multipleOf(value, message) {
1990
- return this._addCheck({
1991
- kind: "multipleOf",
1992
- value,
1993
- message: errorUtil.toString(message)
1994
- });
1995
- }
1996
- get minValue() {
1997
- let min = null;
1998
- for (const ch of this._def.checks) {
1999
- if (ch.kind === "min") {
2000
- if (min === null || ch.value > min)
2001
- min = ch.value;
2002
- }
2003
- }
2004
- return min;
2005
- }
2006
- get maxValue() {
2007
- let max = null;
2008
- for (const ch of this._def.checks) {
2009
- if (ch.kind === "max") {
2010
- if (max === null || ch.value < max)
2011
- max = ch.value;
2012
- }
2013
- }
2014
- return max;
2015
- }
2016
- };
2017
- ZodBigInt.create = (params) => {
2018
- return new ZodBigInt({
2019
- checks: [],
2020
- typeName: ZodFirstPartyTypeKind.ZodBigInt,
2021
- coerce: params?.coerce ?? false,
2022
- ...processCreateParams(params)
2023
- });
2024
- };
2025
- ZodBoolean = class ZodBoolean extends ZodType {
2026
- _parse(input) {
2027
- if (this._def.coerce) {
2028
- input.data = Boolean(input.data);
2029
- }
2030
- const parsedType = this._getType(input);
2031
- if (parsedType !== ZodParsedType.boolean) {
2032
- const ctx = this._getOrReturnCtx(input);
2033
- addIssueToContext(ctx, {
2034
- code: ZodIssueCode.invalid_type,
2035
- expected: ZodParsedType.boolean,
2036
- received: ctx.parsedType
2037
- });
2038
- return INVALID;
2039
- }
2040
- return OK(input.data);
2041
- }
2042
- };
2043
- ZodBoolean.create = (params) => {
2044
- return new ZodBoolean({
2045
- typeName: ZodFirstPartyTypeKind.ZodBoolean,
2046
- coerce: params?.coerce || false,
2047
- ...processCreateParams(params)
2048
- });
2049
- };
2050
- ZodDate = class ZodDate extends ZodType {
2051
- _parse(input) {
2052
- if (this._def.coerce) {
2053
- input.data = new Date(input.data);
2054
- }
2055
- const parsedType = this._getType(input);
2056
- if (parsedType !== ZodParsedType.date) {
2057
- const ctx2 = this._getOrReturnCtx(input);
2058
- addIssueToContext(ctx2, {
2059
- code: ZodIssueCode.invalid_type,
2060
- expected: ZodParsedType.date,
2061
- received: ctx2.parsedType
2062
- });
2063
- return INVALID;
2064
- }
2065
- if (Number.isNaN(input.data.getTime())) {
2066
- const ctx2 = this._getOrReturnCtx(input);
2067
- addIssueToContext(ctx2, {
2068
- code: ZodIssueCode.invalid_date
2069
- });
2070
- return INVALID;
2071
- }
2072
- const status = new ParseStatus;
2073
- let ctx = undefined;
2074
- for (const check of this._def.checks) {
2075
- if (check.kind === "min") {
2076
- if (input.data.getTime() < check.value) {
2077
- ctx = this._getOrReturnCtx(input, ctx);
2078
- addIssueToContext(ctx, {
2079
- code: ZodIssueCode.too_small,
2080
- message: check.message,
2081
- inclusive: true,
2082
- exact: false,
2083
- minimum: check.value,
2084
- type: "date"
2085
- });
2086
- status.dirty();
2087
- }
2088
- } else if (check.kind === "max") {
2089
- if (input.data.getTime() > check.value) {
2090
- ctx = this._getOrReturnCtx(input, ctx);
2091
- addIssueToContext(ctx, {
2092
- code: ZodIssueCode.too_big,
2093
- message: check.message,
2094
- inclusive: true,
2095
- exact: false,
2096
- maximum: check.value,
2097
- type: "date"
2098
- });
2099
- status.dirty();
2100
- }
2101
- } else {
2102
- util.assertNever(check);
2103
- }
2104
- }
2105
- return {
2106
- status: status.value,
2107
- value: new Date(input.data.getTime())
2108
- };
2109
- }
2110
- _addCheck(check) {
2111
- return new ZodDate({
2112
- ...this._def,
2113
- checks: [...this._def.checks, check]
2114
- });
2115
- }
2116
- min(minDate, message) {
2117
- return this._addCheck({
2118
- kind: "min",
2119
- value: minDate.getTime(),
2120
- message: errorUtil.toString(message)
2121
- });
2122
- }
2123
- max(maxDate, message) {
2124
- return this._addCheck({
2125
- kind: "max",
2126
- value: maxDate.getTime(),
2127
- message: errorUtil.toString(message)
2128
- });
2129
- }
2130
- get minDate() {
2131
- let min = null;
2132
- for (const ch of this._def.checks) {
2133
- if (ch.kind === "min") {
2134
- if (min === null || ch.value > min)
2135
- min = ch.value;
2136
- }
2137
- }
2138
- return min != null ? new Date(min) : null;
2139
- }
2140
- get maxDate() {
2141
- let max = null;
2142
- for (const ch of this._def.checks) {
2143
- if (ch.kind === "max") {
2144
- if (max === null || ch.value < max)
2145
- max = ch.value;
2146
- }
2147
- }
2148
- return max != null ? new Date(max) : null;
2149
- }
2150
- };
2151
- ZodDate.create = (params) => {
2152
- return new ZodDate({
2153
- checks: [],
2154
- coerce: params?.coerce || false,
2155
- typeName: ZodFirstPartyTypeKind.ZodDate,
2156
- ...processCreateParams(params)
2157
- });
2158
- };
2159
- ZodSymbol = class ZodSymbol extends ZodType {
2160
- _parse(input) {
2161
- const parsedType = this._getType(input);
2162
- if (parsedType !== ZodParsedType.symbol) {
2163
- const ctx = this._getOrReturnCtx(input);
2164
- addIssueToContext(ctx, {
2165
- code: ZodIssueCode.invalid_type,
2166
- expected: ZodParsedType.symbol,
2167
- received: ctx.parsedType
2168
- });
2169
- return INVALID;
2170
- }
2171
- return OK(input.data);
2172
- }
2173
- };
2174
- ZodSymbol.create = (params) => {
2175
- return new ZodSymbol({
2176
- typeName: ZodFirstPartyTypeKind.ZodSymbol,
2177
- ...processCreateParams(params)
2178
- });
2179
- };
2180
- ZodUndefined = class ZodUndefined extends ZodType {
2181
- _parse(input) {
2182
- const parsedType = this._getType(input);
2183
- if (parsedType !== ZodParsedType.undefined) {
2184
- const ctx = this._getOrReturnCtx(input);
2185
- addIssueToContext(ctx, {
2186
- code: ZodIssueCode.invalid_type,
2187
- expected: ZodParsedType.undefined,
2188
- received: ctx.parsedType
2189
- });
2190
- return INVALID;
2191
- }
2192
- return OK(input.data);
2193
- }
2194
- };
2195
- ZodUndefined.create = (params) => {
2196
- return new ZodUndefined({
2197
- typeName: ZodFirstPartyTypeKind.ZodUndefined,
2198
- ...processCreateParams(params)
2199
- });
2200
- };
2201
- ZodNull = class ZodNull extends ZodType {
2202
- _parse(input) {
2203
- const parsedType = this._getType(input);
2204
- if (parsedType !== ZodParsedType.null) {
2205
- const ctx = this._getOrReturnCtx(input);
2206
- addIssueToContext(ctx, {
2207
- code: ZodIssueCode.invalid_type,
2208
- expected: ZodParsedType.null,
2209
- received: ctx.parsedType
2210
- });
2211
- return INVALID;
2212
- }
2213
- return OK(input.data);
2214
- }
2215
- };
2216
- ZodNull.create = (params) => {
2217
- return new ZodNull({
2218
- typeName: ZodFirstPartyTypeKind.ZodNull,
2219
- ...processCreateParams(params)
2220
- });
2221
- };
2222
- ZodAny = class ZodAny extends ZodType {
2223
- constructor() {
2224
- super(...arguments);
2225
- this._any = true;
2226
- }
2227
- _parse(input) {
2228
- return OK(input.data);
2229
- }
2230
- };
2231
- ZodAny.create = (params) => {
2232
- return new ZodAny({
2233
- typeName: ZodFirstPartyTypeKind.ZodAny,
2234
- ...processCreateParams(params)
2235
- });
2236
- };
2237
- ZodUnknown = class ZodUnknown extends ZodType {
2238
- constructor() {
2239
- super(...arguments);
2240
- this._unknown = true;
2241
- }
2242
- _parse(input) {
2243
- return OK(input.data);
2244
- }
2245
- };
2246
- ZodUnknown.create = (params) => {
2247
- return new ZodUnknown({
2248
- typeName: ZodFirstPartyTypeKind.ZodUnknown,
2249
- ...processCreateParams(params)
2250
- });
2251
- };
2252
- ZodNever = class ZodNever extends ZodType {
2253
- _parse(input) {
2254
- const ctx = this._getOrReturnCtx(input);
2255
- addIssueToContext(ctx, {
2256
- code: ZodIssueCode.invalid_type,
2257
- expected: ZodParsedType.never,
2258
- received: ctx.parsedType
2259
- });
2260
- return INVALID;
2261
- }
2262
- };
2263
- ZodNever.create = (params) => {
2264
- return new ZodNever({
2265
- typeName: ZodFirstPartyTypeKind.ZodNever,
2266
- ...processCreateParams(params)
2267
- });
2268
- };
2269
- ZodVoid = class ZodVoid extends ZodType {
2270
- _parse(input) {
2271
- const parsedType = this._getType(input);
2272
- if (parsedType !== ZodParsedType.undefined) {
2273
- const ctx = this._getOrReturnCtx(input);
2274
- addIssueToContext(ctx, {
2275
- code: ZodIssueCode.invalid_type,
2276
- expected: ZodParsedType.void,
2277
- received: ctx.parsedType
2278
- });
2279
- return INVALID;
2280
- }
2281
- return OK(input.data);
2282
- }
2283
- };
2284
- ZodVoid.create = (params) => {
2285
- return new ZodVoid({
2286
- typeName: ZodFirstPartyTypeKind.ZodVoid,
2287
- ...processCreateParams(params)
2288
- });
2289
- };
2290
- ZodArray = class ZodArray extends ZodType {
2291
- _parse(input) {
2292
- const { ctx, status } = this._processInputParams(input);
2293
- const def = this._def;
2294
- if (ctx.parsedType !== ZodParsedType.array) {
2295
- addIssueToContext(ctx, {
2296
- code: ZodIssueCode.invalid_type,
2297
- expected: ZodParsedType.array,
2298
- received: ctx.parsedType
2299
- });
2300
- return INVALID;
2301
- }
2302
- if (def.exactLength !== null) {
2303
- const tooBig = ctx.data.length > def.exactLength.value;
2304
- const tooSmall = ctx.data.length < def.exactLength.value;
2305
- if (tooBig || tooSmall) {
2306
- addIssueToContext(ctx, {
2307
- code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2308
- minimum: tooSmall ? def.exactLength.value : undefined,
2309
- maximum: tooBig ? def.exactLength.value : undefined,
2310
- type: "array",
2311
- inclusive: true,
2312
- exact: true,
2313
- message: def.exactLength.message
2314
- });
2315
- status.dirty();
2316
- }
2317
- }
2318
- if (def.minLength !== null) {
2319
- if (ctx.data.length < def.minLength.value) {
2320
- addIssueToContext(ctx, {
2321
- code: ZodIssueCode.too_small,
2322
- minimum: def.minLength.value,
2323
- type: "array",
2324
- inclusive: true,
2325
- exact: false,
2326
- message: def.minLength.message
2327
- });
2328
- status.dirty();
2329
- }
2330
- }
2331
- if (def.maxLength !== null) {
2332
- if (ctx.data.length > def.maxLength.value) {
2333
- addIssueToContext(ctx, {
2334
- code: ZodIssueCode.too_big,
2335
- maximum: def.maxLength.value,
2336
- type: "array",
2337
- inclusive: true,
2338
- exact: false,
2339
- message: def.maxLength.message
2340
- });
2341
- status.dirty();
2342
- }
2343
- }
2344
- if (ctx.common.async) {
2345
- return Promise.all([...ctx.data].map((item, i) => {
2346
- return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2347
- })).then((result2) => {
2348
- return ParseStatus.mergeArray(status, result2);
2349
- });
2350
- }
2351
- const result = [...ctx.data].map((item, i) => {
2352
- return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2353
- });
2354
- return ParseStatus.mergeArray(status, result);
2355
- }
2356
- get element() {
2357
- return this._def.type;
2358
- }
2359
- min(minLength, message) {
2360
- return new ZodArray({
2361
- ...this._def,
2362
- minLength: { value: minLength, message: errorUtil.toString(message) }
2363
- });
2364
- }
2365
- max(maxLength, message) {
2366
- return new ZodArray({
2367
- ...this._def,
2368
- maxLength: { value: maxLength, message: errorUtil.toString(message) }
2369
- });
2370
- }
2371
- length(len, message) {
2372
- return new ZodArray({
2373
- ...this._def,
2374
- exactLength: { value: len, message: errorUtil.toString(message) }
2375
- });
2376
- }
2377
- nonempty(message) {
2378
- return this.min(1, message);
2379
- }
2380
- };
2381
- ZodArray.create = (schema, params) => {
2382
- return new ZodArray({
2383
- type: schema,
2384
- minLength: null,
2385
- maxLength: null,
2386
- exactLength: null,
2387
- typeName: ZodFirstPartyTypeKind.ZodArray,
2388
- ...processCreateParams(params)
2389
- });
2390
- };
2391
- ZodObject = class ZodObject extends ZodType {
2392
- constructor() {
2393
- super(...arguments);
2394
- this._cached = null;
2395
- this.nonstrict = this.passthrough;
2396
- this.augment = this.extend;
2397
- }
2398
- _getCached() {
2399
- if (this._cached !== null)
2400
- return this._cached;
2401
- const shape = this._def.shape();
2402
- const keys = util.objectKeys(shape);
2403
- this._cached = { shape, keys };
2404
- return this._cached;
2405
- }
2406
- _parse(input) {
2407
- const parsedType = this._getType(input);
2408
- if (parsedType !== ZodParsedType.object) {
2409
- const ctx2 = this._getOrReturnCtx(input);
2410
- addIssueToContext(ctx2, {
2411
- code: ZodIssueCode.invalid_type,
2412
- expected: ZodParsedType.object,
2413
- received: ctx2.parsedType
2414
- });
2415
- return INVALID;
2416
- }
2417
- const { status, ctx } = this._processInputParams(input);
2418
- const { shape, keys: shapeKeys } = this._getCached();
2419
- const extraKeys = [];
2420
- if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2421
- for (const key in ctx.data) {
2422
- if (!shapeKeys.includes(key)) {
2423
- extraKeys.push(key);
2424
- }
2425
- }
2426
- }
2427
- const pairs = [];
2428
- for (const key of shapeKeys) {
2429
- const keyValidator = shape[key];
2430
- const value = ctx.data[key];
2431
- pairs.push({
2432
- key: { status: "valid", value: key },
2433
- value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2434
- alwaysSet: key in ctx.data
2435
- });
2436
- }
2437
- if (this._def.catchall instanceof ZodNever) {
2438
- const unknownKeys = this._def.unknownKeys;
2439
- if (unknownKeys === "passthrough") {
2440
- for (const key of extraKeys) {
2441
- pairs.push({
2442
- key: { status: "valid", value: key },
2443
- value: { status: "valid", value: ctx.data[key] }
2444
- });
2445
- }
2446
- } else if (unknownKeys === "strict") {
2447
- if (extraKeys.length > 0) {
2448
- addIssueToContext(ctx, {
2449
- code: ZodIssueCode.unrecognized_keys,
2450
- keys: extraKeys
2451
- });
2452
- status.dirty();
2453
- }
2454
- } else if (unknownKeys === "strip") {} else {
2455
- throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2456
- }
2457
- } else {
2458
- const catchall = this._def.catchall;
2459
- for (const key of extraKeys) {
2460
- const value = ctx.data[key];
2461
- pairs.push({
2462
- key: { status: "valid", value: key },
2463
- value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2464
- alwaysSet: key in ctx.data
2465
- });
2466
- }
2467
- }
2468
- if (ctx.common.async) {
2469
- return Promise.resolve().then(async () => {
2470
- const syncPairs = [];
2471
- for (const pair of pairs) {
2472
- const key = await pair.key;
2473
- const value = await pair.value;
2474
- syncPairs.push({
2475
- key,
2476
- value,
2477
- alwaysSet: pair.alwaysSet
2478
- });
2479
- }
2480
- return syncPairs;
2481
- }).then((syncPairs) => {
2482
- return ParseStatus.mergeObjectSync(status, syncPairs);
2483
- });
2484
- } else {
2485
- return ParseStatus.mergeObjectSync(status, pairs);
2486
- }
2487
- }
2488
- get shape() {
2489
- return this._def.shape();
2490
- }
2491
- strict(message) {
2492
- errorUtil.errToObj;
2493
- return new ZodObject({
2494
- ...this._def,
2495
- unknownKeys: "strict",
2496
- ...message !== undefined ? {
2497
- errorMap: (issue, ctx) => {
2498
- const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
2499
- if (issue.code === "unrecognized_keys")
2500
- return {
2501
- message: errorUtil.errToObj(message).message ?? defaultError
2502
- };
2503
- return {
2504
- message: defaultError
2505
- };
2506
- }
2507
- } : {}
2508
- });
2509
- }
2510
- strip() {
2511
- return new ZodObject({
2512
- ...this._def,
2513
- unknownKeys: "strip"
2514
- });
2515
- }
2516
- passthrough() {
2517
- return new ZodObject({
2518
- ...this._def,
2519
- unknownKeys: "passthrough"
2520
- });
2521
- }
2522
- extend(augmentation) {
2523
- return new ZodObject({
2524
- ...this._def,
2525
- shape: () => ({
2526
- ...this._def.shape(),
2527
- ...augmentation
2528
- })
2529
- });
2530
- }
2531
- merge(merging) {
2532
- const merged = new ZodObject({
2533
- unknownKeys: merging._def.unknownKeys,
2534
- catchall: merging._def.catchall,
2535
- shape: () => ({
2536
- ...this._def.shape(),
2537
- ...merging._def.shape()
2538
- }),
2539
- typeName: ZodFirstPartyTypeKind.ZodObject
2540
- });
2541
- return merged;
2542
- }
2543
- setKey(key, schema) {
2544
- return this.augment({ [key]: schema });
2545
- }
2546
- catchall(index) {
2547
- return new ZodObject({
2548
- ...this._def,
2549
- catchall: index
2550
- });
2551
- }
2552
- pick(mask) {
2553
- const shape = {};
2554
- for (const key of util.objectKeys(mask)) {
2555
- if (mask[key] && this.shape[key]) {
2556
- shape[key] = this.shape[key];
2557
- }
2558
- }
2559
- return new ZodObject({
2560
- ...this._def,
2561
- shape: () => shape
2562
- });
2563
- }
2564
- omit(mask) {
2565
- const shape = {};
2566
- for (const key of util.objectKeys(this.shape)) {
2567
- if (!mask[key]) {
2568
- shape[key] = this.shape[key];
2569
- }
2570
- }
2571
- return new ZodObject({
2572
- ...this._def,
2573
- shape: () => shape
2574
- });
2575
- }
2576
- deepPartial() {
2577
- return deepPartialify(this);
2578
- }
2579
- partial(mask) {
2580
- const newShape = {};
2581
- for (const key of util.objectKeys(this.shape)) {
2582
- const fieldSchema = this.shape[key];
2583
- if (mask && !mask[key]) {
2584
- newShape[key] = fieldSchema;
2585
- } else {
2586
- newShape[key] = fieldSchema.optional();
2587
- }
2588
- }
2589
- return new ZodObject({
2590
- ...this._def,
2591
- shape: () => newShape
2592
- });
2593
- }
2594
- required(mask) {
2595
- const newShape = {};
2596
- for (const key of util.objectKeys(this.shape)) {
2597
- if (mask && !mask[key]) {
2598
- newShape[key] = this.shape[key];
2599
- } else {
2600
- const fieldSchema = this.shape[key];
2601
- let newField = fieldSchema;
2602
- while (newField instanceof ZodOptional) {
2603
- newField = newField._def.innerType;
2604
- }
2605
- newShape[key] = newField;
2606
- }
2607
- }
2608
- return new ZodObject({
2609
- ...this._def,
2610
- shape: () => newShape
2611
- });
2612
- }
2613
- keyof() {
2614
- return createZodEnum(util.objectKeys(this.shape));
2615
- }
2616
- };
2617
- ZodObject.create = (shape, params) => {
2618
- return new ZodObject({
2619
- shape: () => shape,
2620
- unknownKeys: "strip",
2621
- catchall: ZodNever.create(),
2622
- typeName: ZodFirstPartyTypeKind.ZodObject,
2623
- ...processCreateParams(params)
2624
- });
2625
- };
2626
- ZodObject.strictCreate = (shape, params) => {
2627
- return new ZodObject({
2628
- shape: () => shape,
2629
- unknownKeys: "strict",
2630
- catchall: ZodNever.create(),
2631
- typeName: ZodFirstPartyTypeKind.ZodObject,
2632
- ...processCreateParams(params)
2633
- });
2634
- };
2635
- ZodObject.lazycreate = (shape, params) => {
2636
- return new ZodObject({
2637
- shape,
2638
- unknownKeys: "strip",
2639
- catchall: ZodNever.create(),
2640
- typeName: ZodFirstPartyTypeKind.ZodObject,
2641
- ...processCreateParams(params)
2642
- });
2643
- };
2644
- ZodUnion = class ZodUnion extends ZodType {
2645
- _parse(input) {
2646
- const { ctx } = this._processInputParams(input);
2647
- const options = this._def.options;
2648
- function handleResults(results) {
2649
- for (const result of results) {
2650
- if (result.result.status === "valid") {
2651
- return result.result;
2652
- }
2653
- }
2654
- for (const result of results) {
2655
- if (result.result.status === "dirty") {
2656
- ctx.common.issues.push(...result.ctx.common.issues);
2657
- return result.result;
2658
- }
2659
- }
2660
- const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2661
- addIssueToContext(ctx, {
2662
- code: ZodIssueCode.invalid_union,
2663
- unionErrors
2664
- });
2665
- return INVALID;
2666
- }
2667
- if (ctx.common.async) {
2668
- return Promise.all(options.map(async (option) => {
2669
- const childCtx = {
2670
- ...ctx,
2671
- common: {
2672
- ...ctx.common,
2673
- issues: []
2674
- },
2675
- parent: null
2676
- };
2677
- return {
2678
- result: await option._parseAsync({
2679
- data: ctx.data,
2680
- path: ctx.path,
2681
- parent: childCtx
2682
- }),
2683
- ctx: childCtx
2684
- };
2685
- })).then(handleResults);
2686
- } else {
2687
- let dirty = undefined;
2688
- const issues = [];
2689
- for (const option of options) {
2690
- const childCtx = {
2691
- ...ctx,
2692
- common: {
2693
- ...ctx.common,
2694
- issues: []
2695
- },
2696
- parent: null
2697
- };
2698
- const result = option._parseSync({
2699
- data: ctx.data,
2700
- path: ctx.path,
2701
- parent: childCtx
2702
- });
2703
- if (result.status === "valid") {
2704
- return result;
2705
- } else if (result.status === "dirty" && !dirty) {
2706
- dirty = { result, ctx: childCtx };
2707
- }
2708
- if (childCtx.common.issues.length) {
2709
- issues.push(childCtx.common.issues);
2710
- }
2711
- }
2712
- if (dirty) {
2713
- ctx.common.issues.push(...dirty.ctx.common.issues);
2714
- return dirty.result;
2715
- }
2716
- const unionErrors = issues.map((issues2) => new ZodError(issues2));
2717
- addIssueToContext(ctx, {
2718
- code: ZodIssueCode.invalid_union,
2719
- unionErrors
2720
- });
2721
- return INVALID;
2722
- }
2723
- }
2724
- get options() {
2725
- return this._def.options;
2726
- }
2727
- };
2728
- ZodUnion.create = (types, params) => {
2729
- return new ZodUnion({
2730
- options: types,
2731
- typeName: ZodFirstPartyTypeKind.ZodUnion,
2732
- ...processCreateParams(params)
2733
- });
2734
- };
2735
- ZodDiscriminatedUnion = class ZodDiscriminatedUnion extends ZodType {
2736
- _parse(input) {
2737
- const { ctx } = this._processInputParams(input);
2738
- if (ctx.parsedType !== ZodParsedType.object) {
2739
- addIssueToContext(ctx, {
2740
- code: ZodIssueCode.invalid_type,
2741
- expected: ZodParsedType.object,
2742
- received: ctx.parsedType
2743
- });
2744
- return INVALID;
2745
- }
2746
- const discriminator = this.discriminator;
2747
- const discriminatorValue = ctx.data[discriminator];
2748
- const option = this.optionsMap.get(discriminatorValue);
2749
- if (!option) {
2750
- addIssueToContext(ctx, {
2751
- code: ZodIssueCode.invalid_union_discriminator,
2752
- options: Array.from(this.optionsMap.keys()),
2753
- path: [discriminator]
2754
- });
2755
- return INVALID;
2756
- }
2757
- if (ctx.common.async) {
2758
- return option._parseAsync({
2759
- data: ctx.data,
2760
- path: ctx.path,
2761
- parent: ctx
2762
- });
2763
- } else {
2764
- return option._parseSync({
2765
- data: ctx.data,
2766
- path: ctx.path,
2767
- parent: ctx
2768
- });
2769
- }
2770
- }
2771
- get discriminator() {
2772
- return this._def.discriminator;
2773
- }
2774
- get options() {
2775
- return this._def.options;
2776
- }
2777
- get optionsMap() {
2778
- return this._def.optionsMap;
2779
- }
2780
- static create(discriminator, options, params) {
2781
- const optionsMap = new Map;
2782
- for (const type of options) {
2783
- const discriminatorValues = getDiscriminator(type.shape[discriminator]);
2784
- if (!discriminatorValues.length) {
2785
- throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
2786
- }
2787
- for (const value of discriminatorValues) {
2788
- if (optionsMap.has(value)) {
2789
- throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
2790
- }
2791
- optionsMap.set(value, type);
2792
- }
2793
- }
2794
- return new ZodDiscriminatedUnion({
2795
- typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
2796
- discriminator,
2797
- options,
2798
- optionsMap,
2799
- ...processCreateParams(params)
2800
- });
2801
- }
2802
- };
2803
- ZodIntersection = class ZodIntersection extends ZodType {
2804
- _parse(input) {
2805
- const { status, ctx } = this._processInputParams(input);
2806
- const handleParsed = (parsedLeft, parsedRight) => {
2807
- if (isAborted(parsedLeft) || isAborted(parsedRight)) {
2808
- return INVALID;
2809
- }
2810
- const merged = mergeValues(parsedLeft.value, parsedRight.value);
2811
- if (!merged.valid) {
2812
- addIssueToContext(ctx, {
2813
- code: ZodIssueCode.invalid_intersection_types
2814
- });
2815
- return INVALID;
2816
- }
2817
- if (isDirty(parsedLeft) || isDirty(parsedRight)) {
2818
- status.dirty();
2819
- }
2820
- return { status: status.value, value: merged.data };
2821
- };
2822
- if (ctx.common.async) {
2823
- return Promise.all([
2824
- this._def.left._parseAsync({
2825
- data: ctx.data,
2826
- path: ctx.path,
2827
- parent: ctx
2828
- }),
2829
- this._def.right._parseAsync({
2830
- data: ctx.data,
2831
- path: ctx.path,
2832
- parent: ctx
2833
- })
2834
- ]).then(([left, right]) => handleParsed(left, right));
2835
- } else {
2836
- return handleParsed(this._def.left._parseSync({
2837
- data: ctx.data,
2838
- path: ctx.path,
2839
- parent: ctx
2840
- }), this._def.right._parseSync({
2841
- data: ctx.data,
2842
- path: ctx.path,
2843
- parent: ctx
2844
- }));
2845
- }
2846
- }
2847
- };
2848
- ZodIntersection.create = (left, right, params) => {
2849
- return new ZodIntersection({
2850
- left,
2851
- right,
2852
- typeName: ZodFirstPartyTypeKind.ZodIntersection,
2853
- ...processCreateParams(params)
2854
- });
2855
- };
2856
- ZodTuple = class ZodTuple extends ZodType {
2857
- _parse(input) {
2858
- const { status, ctx } = this._processInputParams(input);
2859
- if (ctx.parsedType !== ZodParsedType.array) {
2860
- addIssueToContext(ctx, {
2861
- code: ZodIssueCode.invalid_type,
2862
- expected: ZodParsedType.array,
2863
- received: ctx.parsedType
2864
- });
2865
- return INVALID;
2866
- }
2867
- if (ctx.data.length < this._def.items.length) {
2868
- addIssueToContext(ctx, {
2869
- code: ZodIssueCode.too_small,
2870
- minimum: this._def.items.length,
2871
- inclusive: true,
2872
- exact: false,
2873
- type: "array"
2874
- });
2875
- return INVALID;
2876
- }
2877
- const rest = this._def.rest;
2878
- if (!rest && ctx.data.length > this._def.items.length) {
2879
- addIssueToContext(ctx, {
2880
- code: ZodIssueCode.too_big,
2881
- maximum: this._def.items.length,
2882
- inclusive: true,
2883
- exact: false,
2884
- type: "array"
2885
- });
2886
- status.dirty();
2887
- }
2888
- const items = [...ctx.data].map((item, itemIndex) => {
2889
- const schema = this._def.items[itemIndex] || this._def.rest;
2890
- if (!schema)
2891
- return null;
2892
- return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
2893
- }).filter((x) => !!x);
2894
- if (ctx.common.async) {
2895
- return Promise.all(items).then((results) => {
2896
- return ParseStatus.mergeArray(status, results);
2897
- });
2898
- } else {
2899
- return ParseStatus.mergeArray(status, items);
2900
- }
2901
- }
2902
- get items() {
2903
- return this._def.items;
2904
- }
2905
- rest(rest) {
2906
- return new ZodTuple({
2907
- ...this._def,
2908
- rest
2909
- });
2910
- }
2911
- };
2912
- ZodTuple.create = (schemas, params) => {
2913
- if (!Array.isArray(schemas)) {
2914
- throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
2915
- }
2916
- return new ZodTuple({
2917
- items: schemas,
2918
- typeName: ZodFirstPartyTypeKind.ZodTuple,
2919
- rest: null,
2920
- ...processCreateParams(params)
2921
- });
2922
- };
2923
- ZodRecord = class ZodRecord extends ZodType {
2924
- get keySchema() {
2925
- return this._def.keyType;
2926
- }
2927
- get valueSchema() {
2928
- return this._def.valueType;
2929
- }
2930
- _parse(input) {
2931
- const { status, ctx } = this._processInputParams(input);
2932
- if (ctx.parsedType !== ZodParsedType.object) {
2933
- addIssueToContext(ctx, {
2934
- code: ZodIssueCode.invalid_type,
2935
- expected: ZodParsedType.object,
2936
- received: ctx.parsedType
2937
- });
2938
- return INVALID;
2939
- }
2940
- const pairs = [];
2941
- const keyType = this._def.keyType;
2942
- const valueType = this._def.valueType;
2943
- for (const key in ctx.data) {
2944
- pairs.push({
2945
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
2946
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
2947
- alwaysSet: key in ctx.data
2948
- });
2949
- }
2950
- if (ctx.common.async) {
2951
- return ParseStatus.mergeObjectAsync(status, pairs);
2952
- } else {
2953
- return ParseStatus.mergeObjectSync(status, pairs);
2954
- }
2955
- }
2956
- get element() {
2957
- return this._def.valueType;
2958
- }
2959
- static create(first, second, third) {
2960
- if (second instanceof ZodType) {
2961
- return new ZodRecord({
2962
- keyType: first,
2963
- valueType: second,
2964
- typeName: ZodFirstPartyTypeKind.ZodRecord,
2965
- ...processCreateParams(third)
2966
- });
2967
- }
2968
- return new ZodRecord({
2969
- keyType: ZodString.create(),
2970
- valueType: first,
2971
- typeName: ZodFirstPartyTypeKind.ZodRecord,
2972
- ...processCreateParams(second)
2973
- });
2974
- }
2975
- };
2976
- ZodMap = class ZodMap extends ZodType {
2977
- get keySchema() {
2978
- return this._def.keyType;
2979
- }
2980
- get valueSchema() {
2981
- return this._def.valueType;
2982
- }
2983
- _parse(input) {
2984
- const { status, ctx } = this._processInputParams(input);
2985
- if (ctx.parsedType !== ZodParsedType.map) {
2986
- addIssueToContext(ctx, {
2987
- code: ZodIssueCode.invalid_type,
2988
- expected: ZodParsedType.map,
2989
- received: ctx.parsedType
2990
- });
2991
- return INVALID;
2992
- }
2993
- const keyType = this._def.keyType;
2994
- const valueType = this._def.valueType;
2995
- const pairs = [...ctx.data.entries()].map(([key, value], index) => {
2996
- return {
2997
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
2998
- value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
2999
- };
3000
- });
3001
- if (ctx.common.async) {
3002
- const finalMap = new Map;
3003
- return Promise.resolve().then(async () => {
3004
- for (const pair of pairs) {
3005
- const key = await pair.key;
3006
- const value = await pair.value;
3007
- if (key.status === "aborted" || value.status === "aborted") {
3008
- return INVALID;
3009
- }
3010
- if (key.status === "dirty" || value.status === "dirty") {
3011
- status.dirty();
3012
- }
3013
- finalMap.set(key.value, value.value);
3014
- }
3015
- return { status: status.value, value: finalMap };
3016
- });
3017
- } else {
3018
- const finalMap = new Map;
3019
- for (const pair of pairs) {
3020
- const key = pair.key;
3021
- const value = pair.value;
3022
- if (key.status === "aborted" || value.status === "aborted") {
3023
- return INVALID;
3024
- }
3025
- if (key.status === "dirty" || value.status === "dirty") {
3026
- status.dirty();
3027
- }
3028
- finalMap.set(key.value, value.value);
3029
- }
3030
- return { status: status.value, value: finalMap };
3031
- }
3032
- }
3033
- };
3034
- ZodMap.create = (keyType, valueType, params) => {
3035
- return new ZodMap({
3036
- valueType,
3037
- keyType,
3038
- typeName: ZodFirstPartyTypeKind.ZodMap,
3039
- ...processCreateParams(params)
3040
- });
3041
- };
3042
- ZodSet = class ZodSet extends ZodType {
3043
- _parse(input) {
3044
- const { status, ctx } = this._processInputParams(input);
3045
- if (ctx.parsedType !== ZodParsedType.set) {
3046
- addIssueToContext(ctx, {
3047
- code: ZodIssueCode.invalid_type,
3048
- expected: ZodParsedType.set,
3049
- received: ctx.parsedType
3050
- });
3051
- return INVALID;
3052
- }
3053
- const def = this._def;
3054
- if (def.minSize !== null) {
3055
- if (ctx.data.size < def.minSize.value) {
3056
- addIssueToContext(ctx, {
3057
- code: ZodIssueCode.too_small,
3058
- minimum: def.minSize.value,
3059
- type: "set",
3060
- inclusive: true,
3061
- exact: false,
3062
- message: def.minSize.message
3063
- });
3064
- status.dirty();
3065
- }
3066
- }
3067
- if (def.maxSize !== null) {
3068
- if (ctx.data.size > def.maxSize.value) {
3069
- addIssueToContext(ctx, {
3070
- code: ZodIssueCode.too_big,
3071
- maximum: def.maxSize.value,
3072
- type: "set",
3073
- inclusive: true,
3074
- exact: false,
3075
- message: def.maxSize.message
3076
- });
3077
- status.dirty();
3078
- }
3079
- }
3080
- const valueType = this._def.valueType;
3081
- function finalizeSet(elements2) {
3082
- const parsedSet = new Set;
3083
- for (const element of elements2) {
3084
- if (element.status === "aborted")
3085
- return INVALID;
3086
- if (element.status === "dirty")
3087
- status.dirty();
3088
- parsedSet.add(element.value);
3089
- }
3090
- return { status: status.value, value: parsedSet };
3091
- }
3092
- const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3093
- if (ctx.common.async) {
3094
- return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3095
- } else {
3096
- return finalizeSet(elements);
3097
- }
3098
- }
3099
- min(minSize, message) {
3100
- return new ZodSet({
3101
- ...this._def,
3102
- minSize: { value: minSize, message: errorUtil.toString(message) }
3103
- });
3104
- }
3105
- max(maxSize, message) {
3106
- return new ZodSet({
3107
- ...this._def,
3108
- maxSize: { value: maxSize, message: errorUtil.toString(message) }
3109
- });
3110
- }
3111
- size(size, message) {
3112
- return this.min(size, message).max(size, message);
3113
- }
3114
- nonempty(message) {
3115
- return this.min(1, message);
3116
- }
3117
- };
3118
- ZodSet.create = (valueType, params) => {
3119
- return new ZodSet({
3120
- valueType,
3121
- minSize: null,
3122
- maxSize: null,
3123
- typeName: ZodFirstPartyTypeKind.ZodSet,
3124
- ...processCreateParams(params)
3125
- });
3126
- };
3127
- ZodFunction = class ZodFunction extends ZodType {
3128
- constructor() {
3129
- super(...arguments);
3130
- this.validate = this.implement;
3131
- }
3132
- _parse(input) {
3133
- const { ctx } = this._processInputParams(input);
3134
- if (ctx.parsedType !== ZodParsedType.function) {
3135
- addIssueToContext(ctx, {
3136
- code: ZodIssueCode.invalid_type,
3137
- expected: ZodParsedType.function,
3138
- received: ctx.parsedType
3139
- });
3140
- return INVALID;
3141
- }
3142
- function makeArgsIssue(args, error) {
3143
- return makeIssue({
3144
- data: args,
3145
- path: ctx.path,
3146
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3147
- issueData: {
3148
- code: ZodIssueCode.invalid_arguments,
3149
- argumentsError: error
3150
- }
3151
- });
3152
- }
3153
- function makeReturnsIssue(returns, error) {
3154
- return makeIssue({
3155
- data: returns,
3156
- path: ctx.path,
3157
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3158
- issueData: {
3159
- code: ZodIssueCode.invalid_return_type,
3160
- returnTypeError: error
3161
- }
3162
- });
3163
- }
3164
- const params = { errorMap: ctx.common.contextualErrorMap };
3165
- const fn = ctx.data;
3166
- if (this._def.returns instanceof ZodPromise) {
3167
- const me = this;
3168
- return OK(async function(...args) {
3169
- const error = new ZodError([]);
3170
- const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3171
- error.addIssue(makeArgsIssue(args, e));
3172
- throw error;
3173
- });
3174
- const result = await Reflect.apply(fn, this, parsedArgs);
3175
- const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3176
- error.addIssue(makeReturnsIssue(result, e));
3177
- throw error;
3178
- });
3179
- return parsedReturns;
3180
- });
3181
- } else {
3182
- const me = this;
3183
- return OK(function(...args) {
3184
- const parsedArgs = me._def.args.safeParse(args, params);
3185
- if (!parsedArgs.success) {
3186
- throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3187
- }
3188
- const result = Reflect.apply(fn, this, parsedArgs.data);
3189
- const parsedReturns = me._def.returns.safeParse(result, params);
3190
- if (!parsedReturns.success) {
3191
- throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3192
- }
3193
- return parsedReturns.data;
3194
- });
3195
- }
3196
- }
3197
- parameters() {
3198
- return this._def.args;
3199
- }
3200
- returnType() {
3201
- return this._def.returns;
3202
- }
3203
- args(...items) {
3204
- return new ZodFunction({
3205
- ...this._def,
3206
- args: ZodTuple.create(items).rest(ZodUnknown.create())
3207
- });
3208
- }
3209
- returns(returnType) {
3210
- return new ZodFunction({
3211
- ...this._def,
3212
- returns: returnType
3213
- });
3214
- }
3215
- implement(func) {
3216
- const validatedFunc = this.parse(func);
3217
- return validatedFunc;
3218
- }
3219
- strictImplement(func) {
3220
- const validatedFunc = this.parse(func);
3221
- return validatedFunc;
3222
- }
3223
- static create(args, returns, params) {
3224
- return new ZodFunction({
3225
- args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3226
- returns: returns || ZodUnknown.create(),
3227
- typeName: ZodFirstPartyTypeKind.ZodFunction,
3228
- ...processCreateParams(params)
3229
- });
3230
- }
3231
- };
3232
- ZodLazy = class ZodLazy extends ZodType {
3233
- get schema() {
3234
- return this._def.getter();
3235
- }
3236
- _parse(input) {
3237
- const { ctx } = this._processInputParams(input);
3238
- const lazySchema = this._def.getter();
3239
- return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3240
- }
3241
- };
3242
- ZodLazy.create = (getter, params) => {
3243
- return new ZodLazy({
3244
- getter,
3245
- typeName: ZodFirstPartyTypeKind.ZodLazy,
3246
- ...processCreateParams(params)
3247
- });
3248
- };
3249
- ZodLiteral = class ZodLiteral extends ZodType {
3250
- _parse(input) {
3251
- if (input.data !== this._def.value) {
3252
- const ctx = this._getOrReturnCtx(input);
3253
- addIssueToContext(ctx, {
3254
- received: ctx.data,
3255
- code: ZodIssueCode.invalid_literal,
3256
- expected: this._def.value
3257
- });
3258
- return INVALID;
3259
- }
3260
- return { status: "valid", value: input.data };
3261
- }
3262
- get value() {
3263
- return this._def.value;
3264
- }
3265
- };
3266
- ZodLiteral.create = (value, params) => {
3267
- return new ZodLiteral({
3268
- value,
3269
- typeName: ZodFirstPartyTypeKind.ZodLiteral,
3270
- ...processCreateParams(params)
3271
- });
3272
- };
3273
- ZodEnum = class ZodEnum extends ZodType {
3274
- constructor() {
3275
- super(...arguments);
3276
- _ZodEnum_cache.set(this, undefined);
3277
- }
3278
- _parse(input) {
3279
- if (typeof input.data !== "string") {
3280
- const ctx = this._getOrReturnCtx(input);
3281
- const expectedValues = this._def.values;
3282
- addIssueToContext(ctx, {
3283
- expected: util.joinValues(expectedValues),
3284
- received: ctx.parsedType,
3285
- code: ZodIssueCode.invalid_type
3286
- });
3287
- return INVALID;
3288
- }
3289
- if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
3290
- __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
3291
- }
3292
- if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
3293
- const ctx = this._getOrReturnCtx(input);
3294
- const expectedValues = this._def.values;
3295
- addIssueToContext(ctx, {
3296
- received: ctx.data,
3297
- code: ZodIssueCode.invalid_enum_value,
3298
- options: expectedValues
3299
- });
3300
- return INVALID;
3301
- }
3302
- return OK(input.data);
3303
- }
3304
- get options() {
3305
- return this._def.values;
3306
- }
3307
- get enum() {
3308
- const enumValues = {};
3309
- for (const val of this._def.values) {
3310
- enumValues[val] = val;
3311
- }
3312
- return enumValues;
3313
- }
3314
- get Values() {
3315
- const enumValues = {};
3316
- for (const val of this._def.values) {
3317
- enumValues[val] = val;
3318
- }
3319
- return enumValues;
3320
- }
3321
- get Enum() {
3322
- const enumValues = {};
3323
- for (const val of this._def.values) {
3324
- enumValues[val] = val;
3325
- }
3326
- return enumValues;
3327
- }
3328
- extract(values, newDef = this._def) {
3329
- return ZodEnum.create(values, {
3330
- ...this._def,
3331
- ...newDef
3332
- });
3333
- }
3334
- exclude(values, newDef = this._def) {
3335
- return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3336
- ...this._def,
3337
- ...newDef
3338
- });
3339
- }
3340
- };
3341
- _ZodEnum_cache = new WeakMap;
3342
- ZodEnum.create = createZodEnum;
3343
- ZodNativeEnum = class ZodNativeEnum extends ZodType {
3344
- constructor() {
3345
- super(...arguments);
3346
- _ZodNativeEnum_cache.set(this, undefined);
3347
- }
3348
- _parse(input) {
3349
- const nativeEnumValues = util.getValidEnumValues(this._def.values);
3350
- const ctx = this._getOrReturnCtx(input);
3351
- if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3352
- const expectedValues = util.objectValues(nativeEnumValues);
3353
- addIssueToContext(ctx, {
3354
- expected: util.joinValues(expectedValues),
3355
- received: ctx.parsedType,
3356
- code: ZodIssueCode.invalid_type
3357
- });
3358
- return INVALID;
3359
- }
3360
- if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
3361
- __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
3362
- }
3363
- if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
3364
- const expectedValues = util.objectValues(nativeEnumValues);
3365
- addIssueToContext(ctx, {
3366
- received: ctx.data,
3367
- code: ZodIssueCode.invalid_enum_value,
3368
- options: expectedValues
3369
- });
3370
- return INVALID;
3371
- }
3372
- return OK(input.data);
3373
- }
3374
- get enum() {
3375
- return this._def.values;
3376
- }
3377
- };
3378
- _ZodNativeEnum_cache = new WeakMap;
3379
- ZodNativeEnum.create = (values, params) => {
3380
- return new ZodNativeEnum({
3381
- values,
3382
- typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3383
- ...processCreateParams(params)
3384
- });
3385
- };
3386
- ZodPromise = class ZodPromise extends ZodType {
3387
- unwrap() {
3388
- return this._def.type;
3389
- }
3390
- _parse(input) {
3391
- const { ctx } = this._processInputParams(input);
3392
- if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3393
- addIssueToContext(ctx, {
3394
- code: ZodIssueCode.invalid_type,
3395
- expected: ZodParsedType.promise,
3396
- received: ctx.parsedType
3397
- });
3398
- return INVALID;
3399
- }
3400
- const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3401
- return OK(promisified.then((data) => {
3402
- return this._def.type.parseAsync(data, {
3403
- path: ctx.path,
3404
- errorMap: ctx.common.contextualErrorMap
3405
- });
3406
- }));
3407
- }
3408
- };
3409
- ZodPromise.create = (schema, params) => {
3410
- return new ZodPromise({
3411
- type: schema,
3412
- typeName: ZodFirstPartyTypeKind.ZodPromise,
3413
- ...processCreateParams(params)
3414
- });
3415
- };
3416
- ZodEffects = class ZodEffects extends ZodType {
3417
- innerType() {
3418
- return this._def.schema;
3419
- }
3420
- sourceType() {
3421
- return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3422
- }
3423
- _parse(input) {
3424
- const { status, ctx } = this._processInputParams(input);
3425
- const effect = this._def.effect || null;
3426
- const checkCtx = {
3427
- addIssue: (arg) => {
3428
- addIssueToContext(ctx, arg);
3429
- if (arg.fatal) {
3430
- status.abort();
3431
- } else {
3432
- status.dirty();
3433
- }
3434
- },
3435
- get path() {
3436
- return ctx.path;
3437
- }
3438
- };
3439
- checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3440
- if (effect.type === "preprocess") {
3441
- const processed = effect.transform(ctx.data, checkCtx);
3442
- if (ctx.common.async) {
3443
- return Promise.resolve(processed).then(async (processed2) => {
3444
- if (status.value === "aborted")
3445
- return INVALID;
3446
- const result = await this._def.schema._parseAsync({
3447
- data: processed2,
3448
- path: ctx.path,
3449
- parent: ctx
3450
- });
3451
- if (result.status === "aborted")
3452
- return INVALID;
3453
- if (result.status === "dirty")
3454
- return DIRTY(result.value);
3455
- if (status.value === "dirty")
3456
- return DIRTY(result.value);
3457
- return result;
3458
- });
3459
- } else {
3460
- if (status.value === "aborted")
3461
- return INVALID;
3462
- const result = this._def.schema._parseSync({
3463
- data: processed,
3464
- path: ctx.path,
3465
- parent: ctx
3466
- });
3467
- if (result.status === "aborted")
3468
- return INVALID;
3469
- if (result.status === "dirty")
3470
- return DIRTY(result.value);
3471
- if (status.value === "dirty")
3472
- return DIRTY(result.value);
3473
- return result;
3474
- }
3475
- }
3476
- if (effect.type === "refinement") {
3477
- const executeRefinement = (acc) => {
3478
- const result = effect.refinement(acc, checkCtx);
3479
- if (ctx.common.async) {
3480
- return Promise.resolve(result);
3481
- }
3482
- if (result instanceof Promise) {
3483
- throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3484
- }
3485
- return acc;
3486
- };
3487
- if (ctx.common.async === false) {
3488
- const inner = this._def.schema._parseSync({
3489
- data: ctx.data,
3490
- path: ctx.path,
3491
- parent: ctx
3492
- });
3493
- if (inner.status === "aborted")
3494
- return INVALID;
3495
- if (inner.status === "dirty")
3496
- status.dirty();
3497
- executeRefinement(inner.value);
3498
- return { status: status.value, value: inner.value };
3499
- } else {
3500
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
3501
- if (inner.status === "aborted")
3502
- return INVALID;
3503
- if (inner.status === "dirty")
3504
- status.dirty();
3505
- return executeRefinement(inner.value).then(() => {
3506
- return { status: status.value, value: inner.value };
3507
- });
3508
- });
3509
- }
3510
- }
3511
- if (effect.type === "transform") {
3512
- if (ctx.common.async === false) {
3513
- const base = this._def.schema._parseSync({
3514
- data: ctx.data,
3515
- path: ctx.path,
3516
- parent: ctx
3517
- });
3518
- if (!isValid(base))
3519
- return base;
3520
- const result = effect.transform(base.value, checkCtx);
3521
- if (result instanceof Promise) {
3522
- throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3523
- }
3524
- return { status: status.value, value: result };
3525
- } else {
3526
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
3527
- if (!isValid(base))
3528
- return base;
3529
- return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3530
- status: status.value,
3531
- value: result
3532
- }));
3533
- });
3534
- }
3535
- }
3536
- util.assertNever(effect);
3537
- }
3538
- };
3539
- ZodEffects.create = (schema, effect, params) => {
3540
- return new ZodEffects({
3541
- schema,
3542
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3543
- effect,
3544
- ...processCreateParams(params)
3545
- });
3546
- };
3547
- ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3548
- return new ZodEffects({
3549
- schema,
3550
- effect: { type: "preprocess", transform: preprocess },
3551
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3552
- ...processCreateParams(params)
3553
- });
3554
- };
3555
- ZodOptional = class ZodOptional extends ZodType {
3556
- _parse(input) {
3557
- const parsedType = this._getType(input);
3558
- if (parsedType === ZodParsedType.undefined) {
3559
- return OK(undefined);
3560
- }
3561
- return this._def.innerType._parse(input);
3562
- }
3563
- unwrap() {
3564
- return this._def.innerType;
3565
- }
3566
- };
3567
- ZodOptional.create = (type, params) => {
3568
- return new ZodOptional({
3569
- innerType: type,
3570
- typeName: ZodFirstPartyTypeKind.ZodOptional,
3571
- ...processCreateParams(params)
3572
- });
3573
- };
3574
- ZodNullable = class ZodNullable extends ZodType {
3575
- _parse(input) {
3576
- const parsedType = this._getType(input);
3577
- if (parsedType === ZodParsedType.null) {
3578
- return OK(null);
3579
- }
3580
- return this._def.innerType._parse(input);
3581
- }
3582
- unwrap() {
3583
- return this._def.innerType;
3584
- }
3585
- };
3586
- ZodNullable.create = (type, params) => {
3587
- return new ZodNullable({
3588
- innerType: type,
3589
- typeName: ZodFirstPartyTypeKind.ZodNullable,
3590
- ...processCreateParams(params)
3591
- });
3592
- };
3593
- ZodDefault = class ZodDefault extends ZodType {
3594
- _parse(input) {
3595
- const { ctx } = this._processInputParams(input);
3596
- let data = ctx.data;
3597
- if (ctx.parsedType === ZodParsedType.undefined) {
3598
- data = this._def.defaultValue();
3599
- }
3600
- return this._def.innerType._parse({
3601
- data,
3602
- path: ctx.path,
3603
- parent: ctx
3604
- });
3605
- }
3606
- removeDefault() {
3607
- return this._def.innerType;
3608
- }
3609
- };
3610
- ZodDefault.create = (type, params) => {
3611
- return new ZodDefault({
3612
- innerType: type,
3613
- typeName: ZodFirstPartyTypeKind.ZodDefault,
3614
- defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3615
- ...processCreateParams(params)
3616
- });
3617
- };
3618
- ZodCatch = class ZodCatch extends ZodType {
3619
- _parse(input) {
3620
- const { ctx } = this._processInputParams(input);
3621
- const newCtx = {
3622
- ...ctx,
3623
- common: {
3624
- ...ctx.common,
3625
- issues: []
3626
- }
3627
- };
3628
- const result = this._def.innerType._parse({
3629
- data: newCtx.data,
3630
- path: newCtx.path,
3631
- parent: {
3632
- ...newCtx
3633
- }
3634
- });
3635
- if (isAsync(result)) {
3636
- return result.then((result2) => {
3637
- return {
3638
- status: "valid",
3639
- value: result2.status === "valid" ? result2.value : this._def.catchValue({
3640
- get error() {
3641
- return new ZodError(newCtx.common.issues);
3642
- },
3643
- input: newCtx.data
3644
- })
3645
- };
3646
- });
3647
- } else {
3648
- return {
3649
- status: "valid",
3650
- value: result.status === "valid" ? result.value : this._def.catchValue({
3651
- get error() {
3652
- return new ZodError(newCtx.common.issues);
3653
- },
3654
- input: newCtx.data
3655
- })
3656
- };
3657
- }
3658
- }
3659
- removeCatch() {
3660
- return this._def.innerType;
3661
- }
3662
- };
3663
- ZodCatch.create = (type, params) => {
3664
- return new ZodCatch({
3665
- innerType: type,
3666
- typeName: ZodFirstPartyTypeKind.ZodCatch,
3667
- catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3668
- ...processCreateParams(params)
3669
- });
3670
- };
3671
- ZodNaN = class ZodNaN extends ZodType {
3672
- _parse(input) {
3673
- const parsedType = this._getType(input);
3674
- if (parsedType !== ZodParsedType.nan) {
3675
- const ctx = this._getOrReturnCtx(input);
3676
- addIssueToContext(ctx, {
3677
- code: ZodIssueCode.invalid_type,
3678
- expected: ZodParsedType.nan,
3679
- received: ctx.parsedType
3680
- });
3681
- return INVALID;
3682
- }
3683
- return { status: "valid", value: input.data };
3684
- }
3685
- };
3686
- ZodNaN.create = (params) => {
3687
- return new ZodNaN({
3688
- typeName: ZodFirstPartyTypeKind.ZodNaN,
3689
- ...processCreateParams(params)
3690
- });
3691
- };
3692
- BRAND = Symbol("zod_brand");
3693
- ZodBranded = class ZodBranded extends ZodType {
3694
- _parse(input) {
3695
- const { ctx } = this._processInputParams(input);
3696
- const data = ctx.data;
3697
- return this._def.type._parse({
3698
- data,
3699
- path: ctx.path,
3700
- parent: ctx
3701
- });
3702
- }
3703
- unwrap() {
3704
- return this._def.type;
3705
- }
3706
- };
3707
- ZodPipeline = class ZodPipeline extends ZodType {
3708
- _parse(input) {
3709
- const { status, ctx } = this._processInputParams(input);
3710
- if (ctx.common.async) {
3711
- const handleAsync = async () => {
3712
- const inResult = await this._def.in._parseAsync({
3713
- data: ctx.data,
3714
- path: ctx.path,
3715
- parent: ctx
3716
- });
3717
- if (inResult.status === "aborted")
3718
- return INVALID;
3719
- if (inResult.status === "dirty") {
3720
- status.dirty();
3721
- return DIRTY(inResult.value);
3722
- } else {
3723
- return this._def.out._parseAsync({
3724
- data: inResult.value,
3725
- path: ctx.path,
3726
- parent: ctx
3727
- });
3728
- }
3729
- };
3730
- return handleAsync();
3731
- } else {
3732
- const inResult = this._def.in._parseSync({
3733
- data: ctx.data,
3734
- path: ctx.path,
3735
- parent: ctx
3736
- });
3737
- if (inResult.status === "aborted")
3738
- return INVALID;
3739
- if (inResult.status === "dirty") {
3740
- status.dirty();
3741
- return {
3742
- status: "dirty",
3743
- value: inResult.value
3744
- };
3745
- } else {
3746
- return this._def.out._parseSync({
3747
- data: inResult.value,
3748
- path: ctx.path,
3749
- parent: ctx
3750
- });
3751
- }
3752
- }
3753
- }
3754
- static create(a, b) {
3755
- return new ZodPipeline({
3756
- in: a,
3757
- out: b,
3758
- typeName: ZodFirstPartyTypeKind.ZodPipeline
3759
- });
3760
- }
3761
- };
3762
- ZodReadonly = class ZodReadonly extends ZodType {
3763
- _parse(input) {
3764
- const result = this._def.innerType._parse(input);
3765
- const freeze = (data) => {
3766
- if (isValid(data)) {
3767
- data.value = Object.freeze(data.value);
3768
- }
3769
- return data;
3770
- };
3771
- return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
3772
- }
3773
- unwrap() {
3774
- return this._def.innerType;
3775
- }
3776
- };
3777
- ZodReadonly.create = (type, params) => {
3778
- return new ZodReadonly({
3779
- innerType: type,
3780
- typeName: ZodFirstPartyTypeKind.ZodReadonly,
3781
- ...processCreateParams(params)
3782
- });
3783
- };
3784
- late = {
3785
- object: ZodObject.lazycreate
3786
- };
3787
- (function(ZodFirstPartyTypeKind2) {
3788
- ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
3789
- ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
3790
- ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
3791
- ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
3792
- ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
3793
- ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
3794
- ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
3795
- ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
3796
- ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
3797
- ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
3798
- ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
3799
- ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
3800
- ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
3801
- ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
3802
- ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
3803
- ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
3804
- ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
3805
- ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
3806
- ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
3807
- ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
3808
- ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
3809
- ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
3810
- ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
3811
- ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
3812
- ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
3813
- ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
3814
- ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
3815
- ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
3816
- ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
3817
- ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
3818
- ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
3819
- ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
3820
- ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
3821
- ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
3822
- ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
3823
- ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
3824
- })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
3825
- stringType = ZodString.create;
3826
- numberType = ZodNumber.create;
3827
- nanType = ZodNaN.create;
3828
- bigIntType = ZodBigInt.create;
3829
- booleanType = ZodBoolean.create;
3830
- dateType = ZodDate.create;
3831
- symbolType = ZodSymbol.create;
3832
- undefinedType = ZodUndefined.create;
3833
- nullType = ZodNull.create;
3834
- anyType = ZodAny.create;
3835
- unknownType = ZodUnknown.create;
3836
- neverType = ZodNever.create;
3837
- voidType = ZodVoid.create;
3838
- arrayType = ZodArray.create;
3839
- objectType = ZodObject.create;
3840
- strictObjectType = ZodObject.strictCreate;
3841
- unionType = ZodUnion.create;
3842
- discriminatedUnionType = ZodDiscriminatedUnion.create;
3843
- intersectionType = ZodIntersection.create;
3844
- tupleType = ZodTuple.create;
3845
- recordType = ZodRecord.create;
3846
- mapType = ZodMap.create;
3847
- setType = ZodSet.create;
3848
- functionType = ZodFunction.create;
3849
- lazyType = ZodLazy.create;
3850
- literalType = ZodLiteral.create;
3851
- enumType = ZodEnum.create;
3852
- nativeEnumType = ZodNativeEnum.create;
3853
- promiseType = ZodPromise.create;
3854
- effectsType = ZodEffects.create;
3855
- optionalType = ZodOptional.create;
3856
- nullableType = ZodNullable.create;
3857
- preprocessType = ZodEffects.createWithPreprocess;
3858
- pipelineType = ZodPipeline.create;
3859
- coerce = {
3860
- string: (arg) => ZodString.create({ ...arg, coerce: true }),
3861
- number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
3862
- boolean: (arg) => ZodBoolean.create({
3863
- ...arg,
3864
- coerce: true
3865
- }),
3866
- bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
3867
- date: (arg) => ZodDate.create({ ...arg, coerce: true })
3868
- };
3869
- NEVER = INVALID;
3870
- });
3871
-
3872
- // ../../node_modules/zod/dist/esm/v3/external.js
3873
- var exports_external = {};
3874
- __export(exports_external, {
3875
- void: () => voidType,
3876
- util: () => util,
3877
- unknown: () => unknownType,
3878
- union: () => unionType,
3879
- undefined: () => undefinedType,
3880
- tuple: () => tupleType,
3881
- transformer: () => effectsType,
3882
- symbol: () => symbolType,
3883
- string: () => stringType,
3884
- strictObject: () => strictObjectType,
3885
- setErrorMap: () => setErrorMap,
3886
- set: () => setType,
3887
- record: () => recordType,
3888
- quotelessJson: () => quotelessJson,
3889
- promise: () => promiseType,
3890
- preprocess: () => preprocessType,
3891
- pipeline: () => pipelineType,
3892
- ostring: () => ostring,
3893
- optional: () => optionalType,
3894
- onumber: () => onumber,
3895
- oboolean: () => oboolean,
3896
- objectUtil: () => objectUtil,
3897
- object: () => objectType,
3898
- number: () => numberType,
3899
- nullable: () => nullableType,
3900
- null: () => nullType,
3901
- never: () => neverType,
3902
- nativeEnum: () => nativeEnumType,
3903
- nan: () => nanType,
3904
- map: () => mapType,
3905
- makeIssue: () => makeIssue,
3906
- literal: () => literalType,
3907
- lazy: () => lazyType,
3908
- late: () => late,
3909
- isValid: () => isValid,
3910
- isDirty: () => isDirty,
3911
- isAsync: () => isAsync,
3912
- isAborted: () => isAborted,
3913
- intersection: () => intersectionType,
3914
- instanceof: () => instanceOfType,
3915
- getParsedType: () => getParsedType,
3916
- getErrorMap: () => getErrorMap,
3917
- function: () => functionType,
3918
- enum: () => enumType,
3919
- effect: () => effectsType,
3920
- discriminatedUnion: () => discriminatedUnionType,
3921
- defaultErrorMap: () => en_default,
3922
- datetimeRegex: () => datetimeRegex,
3923
- date: () => dateType,
3924
- custom: () => custom,
3925
- coerce: () => coerce,
3926
- boolean: () => booleanType,
3927
- bigint: () => bigIntType,
3928
- array: () => arrayType,
3929
- any: () => anyType,
3930
- addIssueToContext: () => addIssueToContext,
3931
- ZodVoid: () => ZodVoid,
3932
- ZodUnknown: () => ZodUnknown,
3933
- ZodUnion: () => ZodUnion,
3934
- ZodUndefined: () => ZodUndefined,
3935
- ZodType: () => ZodType,
3936
- ZodTuple: () => ZodTuple,
3937
- ZodTransformer: () => ZodEffects,
3938
- ZodSymbol: () => ZodSymbol,
3939
- ZodString: () => ZodString,
3940
- ZodSet: () => ZodSet,
3941
- ZodSchema: () => ZodType,
3942
- ZodRecord: () => ZodRecord,
3943
- ZodReadonly: () => ZodReadonly,
3944
- ZodPromise: () => ZodPromise,
3945
- ZodPipeline: () => ZodPipeline,
3946
- ZodParsedType: () => ZodParsedType,
3947
- ZodOptional: () => ZodOptional,
3948
- ZodObject: () => ZodObject,
3949
- ZodNumber: () => ZodNumber,
3950
- ZodNullable: () => ZodNullable,
3951
- ZodNull: () => ZodNull,
3952
- ZodNever: () => ZodNever,
3953
- ZodNativeEnum: () => ZodNativeEnum,
3954
- ZodNaN: () => ZodNaN,
3955
- ZodMap: () => ZodMap,
3956
- ZodLiteral: () => ZodLiteral,
3957
- ZodLazy: () => ZodLazy,
3958
- ZodIssueCode: () => ZodIssueCode,
3959
- ZodIntersection: () => ZodIntersection,
3960
- ZodFunction: () => ZodFunction,
3961
- ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
3962
- ZodError: () => ZodError,
3963
- ZodEnum: () => ZodEnum,
3964
- ZodEffects: () => ZodEffects,
3965
- ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
3966
- ZodDefault: () => ZodDefault,
3967
- ZodDate: () => ZodDate,
3968
- ZodCatch: () => ZodCatch,
3969
- ZodBranded: () => ZodBranded,
3970
- ZodBoolean: () => ZodBoolean,
3971
- ZodBigInt: () => ZodBigInt,
3972
- ZodArray: () => ZodArray,
3973
- ZodAny: () => ZodAny,
3974
- Schema: () => ZodType,
3975
- ParseStatus: () => ParseStatus,
3976
- OK: () => OK,
3977
- NEVER: () => NEVER,
3978
- INVALID: () => INVALID,
3979
- EMPTY_PATH: () => EMPTY_PATH,
3980
- DIRTY: () => DIRTY,
3981
- BRAND: () => BRAND
3982
- });
3983
- var init_external = __esm(() => {
3984
- init_errors();
3985
- init_parseUtil();
3986
- init_typeAliases();
3987
- init_util();
3988
- init_types();
3989
- init_ZodError();
3990
- });
3991
-
3992
- // ../../node_modules/zod/dist/esm/v3/index.js
3993
- var init_v3 = __esm(() => {
3994
- init_external();
3995
- init_external();
3996
- });
3997
-
3998
- // ../../node_modules/zod/dist/esm/index.js
3999
- var init_esm = __esm(() => {
4000
- init_v3();
4001
- });
4002
-
4003
- // ../../node_modules/drizzle-zod/index.mjs
4004
- import { isTable, getTableColumns, getViewSelectedFields, is, Column, SQL, isView } from "drizzle-orm";
4005
- function isColumnType(column, columnTypes) {
4006
- return columnTypes.includes(column.columnType);
4007
- }
4008
- function isWithEnum(column) {
4009
- return "enumValues" in column && Array.isArray(column.enumValues) && column.enumValues.length > 0;
4010
- }
4011
- function columnToSchema(column, factory) {
4012
- const z$1 = factory?.zodInstance ?? exports_external;
4013
- const coerce2 = factory?.coerce ?? {};
4014
- let schema;
4015
- if (isWithEnum(column)) {
4016
- schema = column.enumValues.length ? z$1.enum(column.enumValues) : z$1.string();
4017
- }
4018
- if (!schema) {
4019
- if (isColumnType(column, ["PgGeometry", "PgPointTuple"])) {
4020
- schema = z$1.tuple([z$1.number(), z$1.number()]);
4021
- } else if (isColumnType(column, ["PgGeometryObject", "PgPointObject"])) {
4022
- schema = z$1.object({ x: z$1.number(), y: z$1.number() });
4023
- } else if (isColumnType(column, ["PgHalfVector", "PgVector"])) {
4024
- schema = z$1.array(z$1.number());
4025
- schema = column.dimensions ? schema.length(column.dimensions) : schema;
4026
- } else if (isColumnType(column, ["PgLine"])) {
4027
- schema = z$1.tuple([z$1.number(), z$1.number(), z$1.number()]);
4028
- } else if (isColumnType(column, ["PgLineABC"])) {
4029
- schema = z$1.object({
4030
- a: z$1.number(),
4031
- b: z$1.number(),
4032
- c: z$1.number()
4033
- });
4034
- } else if (isColumnType(column, ["PgArray"])) {
4035
- schema = z$1.array(columnToSchema(column.baseColumn, z$1));
4036
- schema = column.size ? schema.length(column.size) : schema;
4037
- } else if (column.dataType === "array") {
4038
- schema = z$1.array(z$1.any());
4039
- } else if (column.dataType === "number") {
4040
- schema = numberColumnToSchema(column, z$1, coerce2);
4041
- } else if (column.dataType === "bigint") {
4042
- schema = bigintColumnToSchema(column, z$1, coerce2);
4043
- } else if (column.dataType === "boolean") {
4044
- schema = coerce2 === true || coerce2.boolean ? z$1.coerce.boolean() : z$1.boolean();
4045
- } else if (column.dataType === "date") {
4046
- schema = coerce2 === true || coerce2.date ? z$1.coerce.date() : z$1.date();
4047
- } else if (column.dataType === "string") {
4048
- schema = stringColumnToSchema(column, z$1, coerce2);
4049
- } else if (column.dataType === "json") {
4050
- schema = jsonSchema;
4051
- } else if (column.dataType === "custom") {
4052
- schema = z$1.any();
4053
- } else if (column.dataType === "buffer") {
4054
- schema = bufferSchema;
4055
- }
4056
- }
4057
- if (!schema) {
4058
- schema = z$1.any();
4059
- }
4060
- return schema;
4061
- }
4062
- function numberColumnToSchema(column, z, coerce2) {
4063
- let unsigned = column.getSQLType().includes("unsigned");
4064
- let min;
4065
- let max;
4066
- let integer = false;
4067
- if (isColumnType(column, ["MySqlTinyInt", "SingleStoreTinyInt"])) {
4068
- min = unsigned ? 0 : CONSTANTS.INT8_MIN;
4069
- max = unsigned ? CONSTANTS.INT8_UNSIGNED_MAX : CONSTANTS.INT8_MAX;
4070
- integer = true;
4071
- } else if (isColumnType(column, [
4072
- "PgSmallInt",
4073
- "PgSmallSerial",
4074
- "MySqlSmallInt",
4075
- "SingleStoreSmallInt"
4076
- ])) {
4077
- min = unsigned ? 0 : CONSTANTS.INT16_MIN;
4078
- max = unsigned ? CONSTANTS.INT16_UNSIGNED_MAX : CONSTANTS.INT16_MAX;
4079
- integer = true;
4080
- } else if (isColumnType(column, [
4081
- "PgReal",
4082
- "MySqlFloat",
4083
- "MySqlMediumInt",
4084
- "SingleStoreMediumInt",
4085
- "SingleStoreFloat"
4086
- ])) {
4087
- min = unsigned ? 0 : CONSTANTS.INT24_MIN;
4088
- max = unsigned ? CONSTANTS.INT24_UNSIGNED_MAX : CONSTANTS.INT24_MAX;
4089
- integer = isColumnType(column, ["MySqlMediumInt", "SingleStoreMediumInt"]);
4090
- } else if (isColumnType(column, [
4091
- "PgInteger",
4092
- "PgSerial",
4093
- "MySqlInt",
4094
- "SingleStoreInt"
4095
- ])) {
4096
- min = unsigned ? 0 : CONSTANTS.INT32_MIN;
4097
- max = unsigned ? CONSTANTS.INT32_UNSIGNED_MAX : CONSTANTS.INT32_MAX;
4098
- integer = true;
4099
- } else if (isColumnType(column, [
4100
- "PgDoublePrecision",
4101
- "MySqlReal",
4102
- "MySqlDouble",
4103
- "SingleStoreReal",
4104
- "SingleStoreDouble",
4105
- "SQLiteReal"
4106
- ])) {
4107
- min = unsigned ? 0 : CONSTANTS.INT48_MIN;
4108
- max = unsigned ? CONSTANTS.INT48_UNSIGNED_MAX : CONSTANTS.INT48_MAX;
4109
- } else if (isColumnType(column, [
4110
- "PgBigInt53",
4111
- "PgBigSerial53",
4112
- "MySqlBigInt53",
4113
- "MySqlSerial",
4114
- "SingleStoreBigInt53",
4115
- "SingleStoreSerial",
4116
- "SQLiteInteger"
4117
- ])) {
4118
- unsigned = unsigned || isColumnType(column, ["MySqlSerial", "SingleStoreSerial"]);
4119
- min = unsigned ? 0 : Number.MIN_SAFE_INTEGER;
4120
- max = Number.MAX_SAFE_INTEGER;
4121
- integer = true;
4122
- } else if (isColumnType(column, ["MySqlYear", "SingleStoreYear"])) {
4123
- min = 1901;
4124
- max = 2155;
4125
- integer = true;
4126
- } else {
4127
- min = Number.MIN_SAFE_INTEGER;
4128
- max = Number.MAX_SAFE_INTEGER;
4129
- }
4130
- let schema = coerce2 === true || coerce2?.number ? z.coerce.number() : z.number();
4131
- schema = schema.min(min).max(max);
4132
- return integer ? schema.int() : schema;
4133
- }
4134
- function bigintColumnToSchema(column, z, coerce2) {
4135
- const unsigned = column.getSQLType().includes("unsigned");
4136
- const min = unsigned ? 0n : CONSTANTS.INT64_MIN;
4137
- const max = unsigned ? CONSTANTS.INT64_UNSIGNED_MAX : CONSTANTS.INT64_MAX;
4138
- const schema = coerce2 === true || coerce2?.bigint ? z.coerce.bigint() : z.bigint();
4139
- return schema.min(min).max(max);
4140
- }
4141
- function stringColumnToSchema(column, z, coerce2) {
4142
- if (isColumnType(column, ["PgUUID"])) {
4143
- return z.string().uuid();
4144
- }
4145
- let max;
4146
- let regex;
4147
- let fixed = false;
4148
- if (isColumnType(column, ["PgVarchar", "SQLiteText"])) {
4149
- max = column.length;
4150
- } else if (isColumnType(column, ["MySqlVarChar", "SingleStoreVarChar"])) {
4151
- max = column.length ?? CONSTANTS.INT16_UNSIGNED_MAX;
4152
- } else if (isColumnType(column, ["MySqlText", "SingleStoreText"])) {
4153
- if (column.textType === "longtext") {
4154
- max = CONSTANTS.INT32_UNSIGNED_MAX;
4155
- } else if (column.textType === "mediumtext") {
4156
- max = CONSTANTS.INT24_UNSIGNED_MAX;
4157
- } else if (column.textType === "text") {
4158
- max = CONSTANTS.INT16_UNSIGNED_MAX;
4159
- } else {
4160
- max = CONSTANTS.INT8_UNSIGNED_MAX;
4161
- }
4162
- }
4163
- if (isColumnType(column, [
4164
- "PgChar",
4165
- "MySqlChar",
4166
- "SingleStoreChar"
4167
- ])) {
4168
- max = column.length;
4169
- fixed = true;
4170
- }
4171
- if (isColumnType(column, ["PgBinaryVector"])) {
4172
- regex = /^[01]+$/;
4173
- max = column.dimensions;
4174
- }
4175
- let schema = coerce2 === true || coerce2?.string ? z.coerce.string() : z.string();
4176
- schema = regex ? schema.regex(regex) : schema;
4177
- return max && fixed ? schema.length(max) : max ? schema.max(max) : schema;
4178
- }
4179
- function getColumns(tableLike) {
4180
- return isTable(tableLike) ? getTableColumns(tableLike) : getViewSelectedFields(tableLike);
4181
- }
4182
- function handleColumns(columns, refinements, conditions, factory) {
4183
- const columnSchemas = {};
4184
- for (const [key, selected] of Object.entries(columns)) {
4185
- if (!is(selected, Column) && !is(selected, SQL) && !is(selected, SQL.Aliased) && typeof selected === "object") {
4186
- const columns2 = isTable(selected) || isView(selected) ? getColumns(selected) : selected;
4187
- columnSchemas[key] = handleColumns(columns2, refinements[key] ?? {}, conditions, factory);
4188
- continue;
4189
- }
4190
- const refinement = refinements[key];
4191
- if (refinement !== undefined && typeof refinement !== "function") {
4192
- columnSchemas[key] = refinement;
4193
- continue;
4194
- }
4195
- const column = is(selected, Column) ? selected : undefined;
4196
- const schema = column ? columnToSchema(column, factory) : exports_external.any();
4197
- const refined = typeof refinement === "function" ? refinement(schema) : schema;
4198
- if (conditions.never(column)) {
4199
- continue;
4200
- } else {
4201
- columnSchemas[key] = refined;
4202
- }
4203
- if (column) {
4204
- if (conditions.nullable(column)) {
4205
- columnSchemas[key] = columnSchemas[key].nullable();
4206
- }
4207
- if (conditions.optional(column)) {
4208
- columnSchemas[key] = columnSchemas[key].optional();
4209
- }
4210
- }
4211
- }
4212
- return exports_external.object(columnSchemas);
4213
- }
4214
- function handleEnum(enum_, factory) {
4215
- const zod = factory?.zodInstance ?? exports_external;
4216
- return zod.enum(enum_.enumValues);
4217
- }
4218
- var CONSTANTS, isPgEnum, literalSchema, jsonSchema, bufferSchema, selectConditions, insertConditions, updateConditions, createSelectSchema = (entity, refine) => {
4219
- if (isPgEnum(entity)) {
4220
- return handleEnum(entity);
4221
- }
4222
- const columns = getColumns(entity);
4223
- return handleColumns(columns, refine ?? {}, selectConditions);
4224
- }, createInsertSchema = (entity, refine) => {
4225
- const columns = getColumns(entity);
4226
- return handleColumns(columns, refine ?? {}, insertConditions);
4227
- }, createUpdateSchema = (entity, refine) => {
4228
- const columns = getColumns(entity);
4229
- return handleColumns(columns, refine ?? {}, updateConditions);
4230
- };
4231
- var init_drizzle_zod = __esm(() => {
4232
- init_esm();
4233
- CONSTANTS = {
4234
- INT8_MIN: -128,
4235
- INT8_MAX: 127,
4236
- INT8_UNSIGNED_MAX: 255,
4237
- INT16_MIN: -32768,
4238
- INT16_MAX: 32767,
4239
- INT16_UNSIGNED_MAX: 65535,
4240
- INT24_MIN: -8388608,
4241
- INT24_MAX: 8388607,
4242
- INT24_UNSIGNED_MAX: 16777215,
4243
- INT32_MIN: -2147483648,
4244
- INT32_MAX: 2147483647,
4245
- INT32_UNSIGNED_MAX: 4294967295,
4246
- INT48_MIN: -140737488355328,
4247
- INT48_MAX: 140737488355327,
4248
- INT48_UNSIGNED_MAX: 281474976710655,
4249
- INT64_MIN: -9223372036854775808n,
4250
- INT64_MAX: 9223372036854775807n,
4251
- INT64_UNSIGNED_MAX: 18446744073709551615n
4252
- };
4253
- isPgEnum = isWithEnum;
4254
- literalSchema = exports_external.union([exports_external.string(), exports_external.number(), exports_external.boolean(), exports_external.null()]);
4255
- jsonSchema = exports_external.union([literalSchema, exports_external.record(exports_external.any()), exports_external.array(exports_external.any())]);
4256
- bufferSchema = exports_external.custom((v) => v instanceof Buffer);
4257
- selectConditions = {
4258
- never: () => false,
4259
- optional: () => false,
4260
- nullable: (column) => !column.notNull
4261
- };
4262
- insertConditions = {
4263
- never: (column) => column?.generated?.type === "always" || column?.generatedIdentity?.type === "always",
4264
- optional: (column) => !column.notNull || column.notNull && column.hasDefault,
4265
- nullable: (column) => !column.notNull
4266
- };
4267
- updateConditions = {
4268
- never: (column) => column?.generated?.type === "always" || column?.generatedIdentity?.type === "always",
4269
- optional: () => true,
4270
- nullable: (column) => !column.notNull
4271
- };
4272
- });
4273
-
4274
- // ../data/src/schemas/auth.ts
4275
- import {
4276
- pgTable,
4277
- text,
4278
- timestamp,
4279
- pgEnum,
4280
- boolean,
4281
- uniqueIndex
4282
- } from "drizzle-orm/pg-core";
4283
- var userRoleEnum, developerStatusEnum, users, accounts, sessions, verification, InsertUserSchema, SelectUserSchema, UpdateUserSchema, InsertAccountSchema, SelectAccountSchema, InsertSessionSchema, SelectSessionSchema, InsertVerificationSchema, SelectVerificationSchema, developerStatusValues, DeveloperStatusResponseSchema;
4284
- var init_auth = __esm(() => {
4285
- init_drizzle_zod();
4286
- init_esm();
4287
- userRoleEnum = pgEnum("user_role", [
4288
- "admin",
4289
- "player",
4290
- "developer"
4291
- ]);
4292
- developerStatusEnum = pgEnum("developer_status", [
4293
- "none",
4294
- "pending",
4295
- "approved"
4296
- ]);
13
+ // ../data/src/domains/user/table.ts
14
+ import { boolean, pgEnum, pgTable, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
15
+ var userRoleEnum, developerStatusEnum, users, accounts, sessions, verification;
16
+ var init_table = __esm(() => {
17
+ userRoleEnum = pgEnum("user_role", ["admin", "player", "developer"]);
18
+ developerStatusEnum = pgEnum("developer_status", ["none", "pending", "approved"]);
4297
19
  users = pgTable("user", {
4298
20
  id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
4299
21
  name: text("name").notNull(),
@@ -4338,9 +60,7 @@ var init_auth = __esm(() => {
4338
60
  mode: "date",
4339
61
  withTimezone: true
4340
62
  }).notNull()
4341
- }, (table) => [
4342
- uniqueIndex("account_provider_providerId_idx").on(table.accountId, table.providerId)
4343
- ]);
63
+ }, (table) => [uniqueIndex("account_provider_providerId_idx").on(table.accountId, table.providerId)]);
4344
64
  sessions = pgTable("session", {
4345
65
  id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
4346
66
  userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
@@ -4377,211 +97,38 @@ var init_auth = __esm(() => {
4377
97
  withTimezone: true
4378
98
  }).notNull()
4379
99
  });
4380
- InsertUserSchema = createInsertSchema(users, {
4381
- email: exports_external.string().email(),
4382
- name: exports_external.string().optional()
4383
- }).omit({ id: true });
4384
- SelectUserSchema = createSelectSchema(users);
4385
- UpdateUserSchema = createUpdateSchema(users);
4386
- InsertAccountSchema = createInsertSchema(accounts);
4387
- SelectAccountSchema = createSelectSchema(accounts);
4388
- InsertSessionSchema = createInsertSchema(sessions);
4389
- SelectSessionSchema = createSelectSchema(sessions);
4390
- InsertVerificationSchema = createInsertSchema(verification);
4391
- SelectVerificationSchema = createSelectSchema(verification);
4392
- developerStatusValues = developerStatusEnum.enumValues;
4393
- DeveloperStatusResponseSchema = exports_external.object({
4394
- status: exports_external.enum(developerStatusValues)
4395
- });
4396
100
  });
4397
101
 
4398
- // ../data/src/schemas/game.ts
4399
- import {
4400
- pgTable as pgTable2,
4401
- text as text2,
4402
- timestamp as timestamp2,
4403
- jsonb,
4404
- varchar,
4405
- uuid,
4406
- pgEnum as pgEnum2,
4407
- uniqueIndex as uniqueIndex2
4408
- } from "drizzle-orm/pg-core";
4409
- var gamePlatformEnum, gameBootModeEnum, games, gameSessions, gameStates, safeRelativePathRegex, invalidPathMessage = "Path must be relative, contain only alphanumeric, -, _, ., / characters, and not contain .. segments.", validateRelativePath = (path, fieldName) => {
4410
- if (path == null)
4411
- return true;
4412
- if (typeof path !== "string" || !safeRelativePathRegex.test(path)) {
4413
- throw new exports_external.ZodError([
4414
- {
4415
- code: exports_external.ZodIssueCode.custom,
4416
- path: [fieldName],
4417
- message: invalidPathMessage
4418
- }
4419
- ]);
4420
- }
4421
- return true;
4422
- }, validateStylesArray = (styles, fieldName) => {
4423
- if (styles == null)
4424
- return true;
4425
- if (!Array.isArray(styles)) {
4426
- throw new exports_external.ZodError([
4427
- {
4428
- code: exports_external.ZodIssueCode.custom,
4429
- path: [fieldName],
4430
- message: "Styles must be an array of strings."
4431
- }
4432
- ]);
4433
- }
4434
- styles.forEach((style, index) => {
4435
- if (typeof style !== "string") {
4436
- throw new exports_external.ZodError([
4437
- {
4438
- code: exports_external.ZodIssueCode.custom,
4439
- path: [`${fieldName}[${index}]`],
4440
- message: "Each style must be a string."
4441
- }
4442
- ]);
4443
- }
4444
- validateRelativePath(style, `${fieldName}[${index}]`);
4445
- });
4446
- return true;
4447
- }, VersionSchema, InsertGameSchema, SelectGameSchema, UpdateGameSchema, InsertGameSessionSchema, SelectGameSessionSchema, UpdateGameSessionSchema, InsertGameStateSchema, SelectGameStateSchema, UpdateGameStateSchema, UpsertGameMetadataSchema, InitiateUploadSchema, ProcessZipSchema, StartSessionInputSchema, ManifestV1Schema;
4448
- var init_game = __esm(() => {
4449
- init_drizzle_zod();
4450
- init_esm();
4451
- init_auth();
4452
- init_map();
4453
- gamePlatformEnum = pgEnum2("game_platform", [
4454
- "web",
4455
- "godot",
4456
- "unity"
4457
- ]);
4458
- gameBootModeEnum = pgEnum2("game_boot_mode", ["iframe", "module"]);
4459
- games = pgTable2("games", {
102
+ // ../data/src/domains/developer/table.ts
103
+ import { pgTable as pgTable2, text as text2, timestamp as timestamp2, uuid, varchar } from "drizzle-orm/pg-core";
104
+ var developerKeys;
105
+ var init_table2 = __esm(() => {
106
+ init_table();
107
+ developerKeys = pgTable2("developer_keys", {
4460
108
  id: uuid("id").primaryKey().defaultRandom(),
4461
- developerId: text2("developer_id").references(() => users.id, {
4462
- onDelete: "set null"
4463
- }),
4464
- slug: varchar("slug", { length: 255 }).notNull().unique(),
4465
- displayName: varchar("display_name", { length: 255 }).notNull(),
4466
- version: varchar("version", { length: 50 }).notNull(),
4467
- assetBundleBase: text2("asset_bundle_base").notNull(),
4468
- platform: gamePlatformEnum("platform").notNull().default("web"),
4469
- mapElementId: uuid("map_element_id").references(() => mapElements.id, {
4470
- onDelete: "set null"
4471
- }),
4472
- metadata: jsonb("metadata").default("{}"),
4473
- createdAt: timestamp2("created_at", { withTimezone: true }).defaultNow(),
4474
- updatedAt: timestamp2("updated_at", { withTimezone: true }).defaultNow()
4475
- });
4476
- gameSessions = pgTable2("game_sessions", {
4477
- id: uuid("id").primaryKey().defaultRandom(),
4478
- userId: text2("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
4479
- gameId: uuid("game_id").notNull().references(() => games.id, { onDelete: "cascade" }),
4480
- startedAt: timestamp2("started_at", { withTimezone: true }).notNull().defaultNow(),
4481
- endedAt: timestamp2("ended_at", { withTimezone: true })
4482
- });
4483
- gameStates = pgTable2("game_states", {
4484
109
  userId: text2("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
4485
- gameId: uuid("game_id").notNull().references(() => games.id, { onDelete: "cascade" }),
4486
- data: jsonb("data").default("{}"),
4487
- updatedAt: timestamp2("updated_at", { withTimezone: true }).defaultNow()
4488
- }, (table) => [
4489
- uniqueIndex2("unique_user_game_idx").on(table.userId, table.gameId)
4490
- ]);
4491
- safeRelativePathRegex = /^(?!.*\.\.)(?!\/)[\w\-./]+$/;
4492
- VersionSchema = exports_external.string().min(1).max(50);
4493
- InsertGameSchema = createInsertSchema(games, {
4494
- metadata: exports_external.record(exports_external.string(), exports_external.unknown()).optional().default({}),
4495
- mapElementId: exports_external.string().uuid().optional().nullable()
4496
- }).omit({
4497
- id: true,
4498
- slug: true,
4499
- createdAt: true,
4500
- updatedAt: true,
4501
- version: true
4502
- });
4503
- SelectGameSchema = createSelectSchema(games);
4504
- UpdateGameSchema = createUpdateSchema(games, {
4505
- metadata: exports_external.record(exports_external.string(), exports_external.unknown()).optional(),
4506
- displayName: exports_external.string().optional(),
4507
- mapElementId: exports_external.string().uuid().optional().nullable(),
4508
- platform: exports_external.enum(gamePlatformEnum.enumValues).optional()
4509
- }).omit({
4510
- id: true,
4511
- slug: true,
4512
- createdAt: true,
4513
- developerId: true,
4514
- version: true
4515
- });
4516
- InsertGameSessionSchema = createInsertSchema(gameSessions).omit({
4517
- id: true,
4518
- startedAt: true
4519
- });
4520
- SelectGameSessionSchema = createSelectSchema(gameSessions);
4521
- UpdateGameSessionSchema = createUpdateSchema(gameSessions).omit({
4522
- id: true,
4523
- userId: true,
4524
- gameId: true,
4525
- startedAt: true
4526
- });
4527
- InsertGameStateSchema = createInsertSchema(gameStates, {
4528
- data: exports_external.record(exports_external.string(), exports_external.unknown()).optional().default({})
4529
- }).omit({ updatedAt: true });
4530
- SelectGameStateSchema = createSelectSchema(gameStates);
4531
- UpdateGameStateSchema = createUpdateSchema(gameStates, {
4532
- data: exports_external.record(exports_external.string(), exports_external.unknown()).optional()
4533
- }).omit({ userId: true, gameId: true });
4534
- UpsertGameMetadataSchema = exports_external.object({
4535
- displayName: exports_external.string().min(1),
4536
- mapElementId: exports_external.string().uuid().optional().nullable(),
4537
- platform: exports_external.enum(gamePlatformEnum.enumValues),
4538
- metadata: exports_external.record(exports_external.string(), exports_external.unknown()).optional().default({})
4539
- });
4540
- InitiateUploadSchema = exports_external.object({
4541
- fileName: exports_external.string().min(1).refine((name) => name.endsWith(".zip"), {
4542
- message: "File must be a .zip file"
4543
- }),
4544
- gameId: exports_external.string().uuid()
4545
- });
4546
- ProcessZipSchema = exports_external.object({
4547
- tempS3Key: exports_external.string().min(1),
4548
- gameId: exports_external.string().uuid(),
4549
- version: exports_external.string().min(1),
4550
- slug: exports_external.string().min(1),
4551
- metadata: UpsertGameMetadataSchema,
4552
- originalFileName: exports_external.string().min(1).endsWith(".zip")
4553
- });
4554
- StartSessionInputSchema = exports_external.object({
4555
- gameId: exports_external.string().uuid()
4556
- });
4557
- ManifestV1Schema = exports_external.object({
4558
- version: exports_external.string().min(1),
4559
- bootMode: exports_external.enum(gameBootModeEnum.enumValues),
4560
- entryPoint: exports_external.string().refine((val) => validateRelativePath(val, "entryPoint")),
4561
- styles: exports_external.array(exports_external.string()).optional().refine((val) => validateStylesArray(val, "styles")),
4562
- platform: exports_external.enum(gamePlatformEnum.enumValues),
4563
- createdAt: exports_external.string().datetime()
110
+ label: varchar("label", { length: 255 }),
111
+ keyHash: text2("key_hash").notNull().unique(),
112
+ createdAt: timestamp2("created_at", { withTimezone: true }).notNull().defaultNow()
4564
113
  });
4565
114
  });
4566
115
 
4567
- // ../data/src/schemas/map.ts
116
+ // ../data/src/domains/map/table.ts
117
+ import { relations } from "drizzle-orm";
4568
118
  import {
119
+ doublePrecision,
120
+ jsonb,
121
+ pgEnum as pgEnum2,
4569
122
  pgTable as pgTable3,
4570
- jsonb as jsonb2,
4571
- varchar as varchar2,
4572
- uuid as uuid2,
4573
- pgEnum as pgEnum3,
4574
- uniqueIndex as uniqueIndex3,
4575
123
  text as text3,
4576
- doublePrecision
124
+ uniqueIndex as uniqueIndex2,
125
+ uuid as uuid2,
126
+ varchar as varchar2
4577
127
  } from "drizzle-orm/pg-core";
4578
- import { relations } from "drizzle-orm";
4579
- var interactionTypeEnum, maps, mapElements, mapElementsRelations, mapsRelations, MapElementMetadataZodSchema, SelectMapSchema, InsertMapElementSchema, SelectMapElementSchema, UpdateMapElementSchema;
4580
- var init_map = __esm(() => {
4581
- init_drizzle_zod();
4582
- init_esm();
4583
- init_game();
4584
- interactionTypeEnum = pgEnum3("interaction_type", [
128
+ var interactionTypeEnum, maps, mapElements, mapElementsRelations, mapsRelations;
129
+ var init_table3 = __esm(() => {
130
+ init_table4();
131
+ interactionTypeEnum = pgEnum2("interaction_type", [
4585
132
  "game_entry",
4586
133
  "game_registry",
4587
134
  "info",
@@ -4611,10 +158,8 @@ var init_map = __esm(() => {
4611
158
  gameId: uuid2("game_id").references(() => games.id, {
4612
159
  onDelete: "set null"
4613
160
  }),
4614
- metadata: jsonb2("metadata").$type().default({})
4615
- }, (table) => [
4616
- uniqueIndex3("map_id_element_slug_unique_idx").on(table.mapId, table.elementSlug)
4617
- ]);
161
+ metadata: jsonb("metadata").$type().default({})
162
+ }, (table) => [uniqueIndex2("map_id_element_slug_unique_idx").on(table.mapId, table.elementSlug)]);
4618
163
  mapElementsRelations = relations(mapElements, ({ one }) => ({
4619
164
  game: one(games, {
4620
165
  fields: [mapElements.gameId],
@@ -4628,29 +173,201 @@ var init_map = __esm(() => {
4628
173
  mapsRelations = relations(maps, ({ many }) => ({
4629
174
  elements: many(mapElements)
4630
175
  }));
4631
- MapElementMetadataZodSchema = exports_external.object({
4632
- description: exports_external.string().optional(),
4633
- sourceTiledObjects: exports_external.array(exports_external.record(exports_external.string(), exports_external.unknown())).optional()
4634
- }).catchall(exports_external.unknown());
4635
- SelectMapSchema = createSelectSchema(maps);
4636
- InsertMapElementSchema = createInsertSchema(mapElements, {
4637
- metadata: MapElementMetadataZodSchema.optional().default({}),
4638
- interactionType: exports_external.enum(interactionTypeEnum.enumValues)
4639
- }).omit({ id: true });
4640
- SelectMapElementSchema = createSelectSchema(mapElements, {
4641
- metadata: MapElementMetadataZodSchema.optional().default({}),
4642
- interactionType: exports_external.enum(interactionTypeEnum.enumValues)
176
+ });
177
+
178
+ // ../data/src/domains/game/table.ts
179
+ import {
180
+ jsonb as jsonb2,
181
+ pgEnum as pgEnum3,
182
+ pgTable as pgTable4,
183
+ text as text4,
184
+ timestamp as timestamp3,
185
+ uniqueIndex as uniqueIndex3,
186
+ uuid as uuid3,
187
+ varchar as varchar3
188
+ } from "drizzle-orm/pg-core";
189
+ var gamePlatformEnum, gameBootModeEnum, games, gameSessions, gameStates;
190
+ var init_table4 = __esm(() => {
191
+ init_table3();
192
+ init_table();
193
+ gamePlatformEnum = pgEnum3("game_platform", ["web", "godot", "unity"]);
194
+ gameBootModeEnum = pgEnum3("game_boot_mode", ["iframe", "module"]);
195
+ games = pgTable4("games", {
196
+ id: uuid3("id").primaryKey().defaultRandom(),
197
+ developerId: text4("developer_id").references(() => users.id, {
198
+ onDelete: "set null"
199
+ }),
200
+ slug: varchar3("slug", { length: 255 }).notNull().unique(),
201
+ displayName: varchar3("display_name", { length: 255 }).notNull(),
202
+ version: varchar3("version", { length: 50 }).notNull(),
203
+ assetBundleBase: text4("asset_bundle_base").notNull(),
204
+ platform: gamePlatformEnum("platform").notNull().default("web"),
205
+ mapElementId: uuid3("map_element_id").references(() => mapElements.id, {
206
+ onDelete: "set null"
207
+ }),
208
+ metadata: jsonb2("metadata").default("{}"),
209
+ createdAt: timestamp3("created_at", { withTimezone: true }).defaultNow(),
210
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).defaultNow()
211
+ });
212
+ gameSessions = pgTable4("game_sessions", {
213
+ id: uuid3("id").primaryKey().defaultRandom(),
214
+ userId: text4("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
215
+ gameId: uuid3("game_id").notNull().references(() => games.id, { onDelete: "cascade" }),
216
+ startedAt: timestamp3("started_at", { withTimezone: true }).notNull().defaultNow(),
217
+ endedAt: timestamp3("ended_at", { withTimezone: true })
218
+ });
219
+ gameStates = pgTable4("game_states", {
220
+ userId: text4("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
221
+ gameId: uuid3("game_id").notNull().references(() => games.id, { onDelete: "cascade" }),
222
+ data: jsonb2("data").default("{}"),
223
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).defaultNow()
224
+ }, (table) => [uniqueIndex3("unique_user_game_idx").on(table.userId, table.gameId)]);
225
+ });
226
+
227
+ // ../data/src/domains/inventory/table.ts
228
+ import { relations as relations2, sql } from "drizzle-orm";
229
+ import {
230
+ boolean as boolean2,
231
+ integer,
232
+ jsonb as jsonb3,
233
+ pgEnum as pgEnum4,
234
+ pgTable as pgTable5,
235
+ text as text5,
236
+ timestamp as timestamp4,
237
+ uniqueIndex as uniqueIndex4,
238
+ uuid as uuid4
239
+ } from "drizzle-orm/pg-core";
240
+ var itemTypeEnum, items, inventoryItems, currencies, shopListings, itemsRelations, currenciesRelations, shopListingsRelations, inventoryItemsRelations;
241
+ var init_table5 = __esm(() => {
242
+ init_table4();
243
+ init_table();
244
+ itemTypeEnum = pgEnum4("item_type", [
245
+ "currency",
246
+ "badge",
247
+ "trophy",
248
+ "collectible",
249
+ "consumable",
250
+ "unlock",
251
+ "upgrade",
252
+ "other"
253
+ ]);
254
+ items = pgTable5("items", {
255
+ id: uuid4("id").primaryKey().defaultRandom(),
256
+ slug: text5("slug").notNull(),
257
+ gameId: uuid4("game_id").references(() => games.id, {
258
+ onDelete: "cascade"
259
+ }),
260
+ displayName: text5("display_name").notNull(),
261
+ description: text5("description"),
262
+ type: itemTypeEnum("type").notNull().default("other"),
263
+ imageUrl: text5("image_url"),
264
+ metadata: jsonb3("metadata").default({}),
265
+ createdAt: timestamp4("created_at").defaultNow().notNull()
266
+ }, (table) => [
267
+ uniqueIndex4("items_game_slug_idx").on(table.gameId, table.slug),
268
+ uniqueIndex4("items_global_slug_idx").on(table.slug).where(sql`game_id IS NULL`)
269
+ ]);
270
+ inventoryItems = pgTable5("inventory_items", {
271
+ id: uuid4("id").primaryKey().defaultRandom(),
272
+ userId: text5("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
273
+ itemId: uuid4("item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
274
+ quantity: integer("quantity").notNull().default(1),
275
+ updatedAt: timestamp4("updated_at", { withTimezone: true }).defaultNow()
276
+ }, (table) => [uniqueIndex4("unique_user_item_idx").on(table.userId, table.itemId)]);
277
+ currencies = pgTable5("currencies", {
278
+ id: uuid4("id").primaryKey().defaultRandom(),
279
+ itemId: uuid4("item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
280
+ symbol: text5("symbol"),
281
+ isPrimary: boolean2("is_primary").default(false).notNull(),
282
+ createdAt: timestamp4("created_at").defaultNow().notNull(),
283
+ updatedAt: timestamp4("updated_at", { withTimezone: true }).defaultNow().$onUpdate(() => new Date)
284
+ }, (table) => [uniqueIndex4("currency_item_id_idx").on(table.itemId)]);
285
+ shopListings = pgTable5("shop_listings", {
286
+ id: uuid4("id").primaryKey().defaultRandom(),
287
+ itemId: uuid4("item_id").notNull().references(() => items.id, { onDelete: "cascade" }),
288
+ currencyId: uuid4("currency_id").notNull().references(() => currencies.id, { onDelete: "restrict" }),
289
+ price: integer("price").notNull(),
290
+ sellBackPercentage: integer("sell_back_percentage"),
291
+ stock: integer("stock"),
292
+ isActive: boolean2("is_active").default(true).notNull(),
293
+ availableFrom: timestamp4("available_from", { withTimezone: true }),
294
+ availableUntil: timestamp4("available_until", { withTimezone: true }),
295
+ createdAt: timestamp4("created_at").defaultNow().notNull(),
296
+ updatedAt: timestamp4("updated_at", { withTimezone: true }).defaultNow().$onUpdate(() => new Date)
297
+ }, (table) => [uniqueIndex4("unique_item_currency_listing_idx").on(table.itemId, table.currencyId)]);
298
+ itemsRelations = relations2(items, ({ many }) => ({
299
+ shopListings: many(shopListings),
300
+ inventoryItems: many(inventoryItems)
301
+ }));
302
+ currenciesRelations = relations2(currencies, ({ many }) => ({
303
+ shopListings: many(shopListings)
304
+ }));
305
+ shopListingsRelations = relations2(shopListings, ({ one }) => ({
306
+ item: one(items, {
307
+ fields: [shopListings.itemId],
308
+ references: [items.id]
309
+ }),
310
+ currency: one(currencies, {
311
+ fields: [shopListings.currencyId],
312
+ references: [currencies.id]
313
+ })
314
+ }));
315
+ inventoryItemsRelations = relations2(inventoryItems, ({ one }) => ({
316
+ item: one(items, {
317
+ fields: [inventoryItems.itemId],
318
+ references: [items.id]
319
+ }),
320
+ user: one(users, {
321
+ fields: [inventoryItems.userId],
322
+ references: [users.id]
323
+ })
324
+ }));
325
+ });
326
+
327
+ // ../data/src/domains/level/table.ts
328
+ import { relations as relations3 } from "drizzle-orm";
329
+ import { integer as integer2, pgTable as pgTable6, text as text6, timestamp as timestamp5, uniqueIndex as uniqueIndex5, uuid as uuid5 } from "drizzle-orm/pg-core";
330
+ var userLevels, levelConfigs, userLevelsRelations;
331
+ var init_table6 = __esm(() => {
332
+ init_table();
333
+ userLevels = pgTable6("user_levels", {
334
+ userId: text6("user_id").primaryKey().references(() => users.id, { onDelete: "cascade" }),
335
+ currentLevel: integer2("current_level").notNull().default(1),
336
+ currentXp: integer2("current_xp").notNull().default(0),
337
+ totalXP: integer2("total_xp").notNull().default(0),
338
+ lastLevelUpAt: timestamp5("last_level_up_at", { withTimezone: true }),
339
+ createdAt: timestamp5("created_at").defaultNow().notNull(),
340
+ updatedAt: timestamp5("updated_at", { withTimezone: true }).defaultNow().$onUpdate(() => new Date)
4643
341
  });
4644
- UpdateMapElementSchema = createUpdateSchema(mapElements, {
4645
- metadata: MapElementMetadataZodSchema.optional(),
4646
- interactionType: exports_external.enum(interactionTypeEnum.enumValues).optional()
4647
- }).omit({ id: true });
342
+ levelConfigs = pgTable6("level_configs", {
343
+ id: uuid5("id").primaryKey().defaultRandom(),
344
+ level: integer2("level").notNull().unique(),
345
+ xpRequired: integer2("xp_required").notNull(),
346
+ creditsReward: integer2("credits_reward").notNull().default(0),
347
+ createdAt: timestamp5("created_at").defaultNow().notNull()
348
+ }, (table) => [uniqueIndex5("unique_level_config_idx").on(table.level)]);
349
+ userLevelsRelations = relations3(userLevels, ({ one }) => ({
350
+ user: one(users, {
351
+ fields: [userLevels.userId],
352
+ references: [users.id]
353
+ })
354
+ }));
355
+ });
356
+
357
+ // ../data/src/tables.index.ts
358
+ var init_tables_index = __esm(() => {
359
+ init_table();
360
+ init_table2();
361
+ init_table4();
362
+ init_table5();
363
+ init_table3();
364
+ init_table6();
4648
365
  });
4649
366
 
4650
367
  // ../data/src/constants.ts
4651
368
  var ITEM_SLUGS, CURRENCIES, BADGES, INTERACTION_TYPE;
4652
369
  var init_constants = __esm(() => {
4653
- init_map();
370
+ init_tables_index();
4654
371
  ITEM_SLUGS = {
4655
372
  PLAYCADEMY_CREDITS: "PLAYCADEMY_CREDITS",
4656
373
  PLAYCADEMY_XP: "PLAYCADEMY_XP",