@scalar/nextjs-api-reference 0.6.0 → 0.7.1

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