Socket
Socket
Sign inDemoInstall

zod

Package Overview
Dependencies
Maintainers
2
Versions
361
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

zod - npm Package Compare versions

Comparing version 2.0.0-alpha.7 to 2.0.0-beta.1

CHANGELOG.md

6

lib/src/codegen.d.ts

@@ -1,2 +0,2 @@

import * as z from '.';
import * as z from './index';
declare type TypeResult = {

@@ -11,9 +11,9 @@ schema: any;

randomId: () => string;
findBySchema: (schema: z.ZodType<any, any>) => TypeResult | undefined;
findBySchema: (schema: z.ZodType<any, any, any>) => TypeResult | undefined;
findById: (id: string) => TypeResult;
dump: () => string;
setType: (id: string, type: string) => TypeResult;
generate: (schema: z.ZodType<any, any>) => TypeResult;
generate: (schema: z.ZodType<any, any, any>) => TypeResult;
static create: () => z.ZodCodeGenerator;
}
export {};
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodCodeGenerator = void 0;
// import { ZodTypes, SomeSkiiType, SkiiType } from '.';
var z = __importStar(require("."));
var z = __importStar(require("./index"));
var util_1 = require("./helpers/util");
// type adsf = {str:string} | {qwer:number};
// const y:adsf = {plpl:true}
var isOptional = function (schema) {
var def = schema._def;
if (def.t === z.ZodTypes.undefined)
return true;
else if (def.t === z.ZodTypes.intersection) {
return isOptional(def.right) && isOptional(def.left);
}
else if (def.t === z.ZodTypes.union) {
return def.options.map(isOptional).some(function (x) { return x === true; });
}
return false;
// const def: z.ZodDef = schema._def;
// if (def.t === z.ZodTypes.undefined) return true;
// else if (def.t === z.ZodTypes.intersection) {
// return isOptional(def.right) && isOptional(def.left);
// } else if (def.t === z.ZodTypes.union) {
// return def.options.map(isOptional).some(x => x === true);
// }
// return false;
return schema.isOptional();
};

@@ -47,5 +30,2 @@ var ZodCodeGenerator = /** @class */ (function () {

return "IZod" + _this.serial++;
// return `I${Math.random()
// .toString(26)
// .substring(2, 15)}`
};

@@ -61,7 +41,6 @@ this.findBySchema = function (schema) {

};
// add = (id: string, schema: SkiiType<any, any>, type: string) => {
// this.seen.push({ id, schema, type });
// };
this.dump = function () {
return "\ntype Identity<T> = T;\n\n" + _this.seen.map(function (item) { return "type " + item.id + " = Identity<" + item.type + ">;"; }).join('\n\n') + "\n";
return "\ntype Identity<T> = T;\n\n" + _this.seen
.map(function (item) { return "type " + item.id + " = Identity<" + item.type + ">;"; })
.join('\n\n') + "\n";
};

@@ -78,3 +57,2 @@ this.setType = function (id, type) {

var def = schema._def;
// const schema: SomeSkiiType = _schema as any;
var id = _this.randomId();

@@ -87,6 +65,2 @@ var ty = {

_this.seen.push(ty);
// const rawDef = schema.__def as any;
// const ARR = rawDef.array ? `[]` : ``;
// const NUL = rawDef.nullable ? ` | null` : ``;
// const UND = rawDef.optional ? ` | undefined` : ``;
switch (def.t) {

@@ -111,2 +85,4 @@ case z.ZodTypes.string:

return _this.setType(id, "unknown");
case z.ZodTypes.never:
return _this.setType(id, "never");
case z.ZodTypes.void:

@@ -129,3 +105,5 @@ return _this.setType(id, "void");

}
var baseStruct = "{\n" + objectLines.map(function (line) { return " " + line + ";"; }).join('\n') + "\n}";
var baseStruct = "{\n" + objectLines
.map(function (line) { return " " + line + ";"; })
.join('\n') + "\n}";
_this.setType(id, "" + baseStruct);

@@ -140,3 +118,5 @@ break;

}
var baseTuple = "[\n" + tupleLines.map(function (line) { return " " + line + ","; }).join('\n') + "\n]";
var baseTuple = "[\n" + tupleLines
.map(function (line) { return " " + line + ","; })
.join('\n') + "\n]";
return _this.setType(id, "" + baseTuple);

@@ -164,5 +144,14 @@ case z.ZodTypes.array:

return _this.setType(id, "{[k:string]: " + _this.generate(def.valueType).id + "}");
case z.ZodTypes.transformer:
return _this.setType(id, _this.generate(def.output).id);
case z.ZodTypes.lazy:
var lazyType = def.getter();
return _this.setType(id, _this.generate(lazyType).id);
case z.ZodTypes.nativeEnum:
// const lazyType = def.getter();
return _this.setType(id, 'asdf');
case z.ZodTypes.optional:
return _this.setType(id, _this.generate(def.innerType).id + " | undefined");
case z.ZodTypes.nullable:
return _this.setType(id, _this.generate(def.innerType).id + " | null");
default:

@@ -169,0 +158,0 @@ util_1.util.assertNever(def);

@@ -10,3 +10,3 @@ import { Primitive } from './primitive';

[k: string]: any;
} ? (T extends Array<any> ? false : true) : false;
} ? T extends Array<any> ? false : true : false;
declare type IsObjectArray<T> = T extends Array<{

@@ -13,0 +13,0 @@ [k: string]: any;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// type test = any[] extends Record<string, any> ? true : false;
// type test1 = maskUtil.Params<{ name: string }>;
// type test2 = maskUtil.Params<{ name: string }[]>;
// type test3 = maskUtil.Params<{ name: string } | undefined>;
// type test4 = maskUtil.Params<undefined>;
// type test5 = maskUtil.Params<null>;
// type test6 = maskUtil.Params<string>;
// type test7 = maskUtil.Params<string | boolean | undefined>;
// type test8 = maskUtil.Params<{ properties: { name: string; number: number } }>;
// type test9 = IsObjectArray<[]>;
// type test10 = IsObject<[]>;
// type test11 = true extends IsObject<{ firstName: string; lastName: string }[]> ? true : false;
// type test11b = true extends IsObjectArray<{ firstName: string; lastName: string }[]> ? true : false;
// type test12 = maskUtil.Pick<{ firstName: string }, true>;
// type test13 = maskUtil.Pick<{ firstName: string }, {}>;
// type test14 = maskUtil.PickTest<{ firstName: string; lastName: string }, {}>;
// type test15 = maskUtil.Pick<
// { firstName: string | undefined; lastName: string | undefined | null }[] | undefined,
// { firstName: true }
// >;
// type test16 = maskUtil.Pick<{ username: string; points: number }, { points: true }>;
// type test16 = {} extends true ? true : false;
// export namespace maskUtil {
// export type Params<T> = {
// never: never;
// undefined: never;
// primitive: true;
// primitivearr: true;
// tuple: true;
// array: true | (T extends Array<infer U> ? Params<U> : never);
// obj: { [k in keyof T]?: Params<T[k]> };
// unknown: unknown;
// }[T extends never
// ? 'never'
// : T extends undefined
// ? 'undefined'
// : T extends Primitive
// ? 'primitive'
// : T extends [any, ...any[]]
// ? 'tuple'
// : T extends Array<any>
// ? 'array'
// : T extends AnyObject
// ? 'obj'
// : 'unknown'];
// export type Mask<T, P extends Params<T>> = {
// false: never;
// true: T;
// inferenceerror: 'InferenceError! Please file an issue with your code.';
// primitiveerror: 'PrimitiveError! Please file an issue with your code';
// objarray: T extends Array<infer U> ? Mask<U, P>[] : never;
// obj: T extends AnyObject
// ? {
// [k in keyof T]: k extends keyof P ? Mask<T[k], P[k]> : never;
// }
// : never;
// unknown: 'MaskedTypeUnknownError! Please file an issue with your code.';
// }[P extends false
// ? 'false'
// : P extends true
// ? 'true'
// : P extends boolean
// ? 'inferenceerror'
// : T extends Primitive
// ? 'primitiveerror'
// : T extends Array<any>
// ? 'objarray'
// : T extends AnyObject
// ? 'obj'
// : 'unknown'];
// }
//# sourceMappingURL=maskUtil.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Mocker = void 0;
function getRandomInt(max) {

@@ -23,3 +22,3 @@ return Math.floor(Math.random() * Math.floor(max));

},
enumerable: false,
enumerable: true,
configurable: true

@@ -31,3 +30,3 @@ });

},
enumerable: false,
enumerable: true,
configurable: true

@@ -39,3 +38,3 @@ });

},
enumerable: false,
enumerable: true,
configurable: true

@@ -47,3 +46,3 @@ });

},
enumerable: false,
enumerable: true,
configurable: true

@@ -55,3 +54,3 @@ });

},
enumerable: false,
enumerable: true,
configurable: true

@@ -63,3 +62,3 @@ });

},
enumerable: false,
enumerable: true,
configurable: true

@@ -71,3 +70,3 @@ });

},
enumerable: false,
enumerable: true,
configurable: true

@@ -79,3 +78,3 @@ });

},
enumerable: false,
enumerable: true,
configurable: true

@@ -87,3 +86,3 @@ });

},
enumerable: false,
enumerable: true,
configurable: true

@@ -95,3 +94,3 @@ });

},
enumerable: false,
enumerable: true,
configurable: true

@@ -103,3 +102,3 @@ });

},
enumerable: false,
enumerable: true,
configurable: true

@@ -111,3 +110,3 @@ });

},
enumerable: false,
enumerable: true,
configurable: true

@@ -119,3 +118,3 @@ });

},
enumerable: false,
enumerable: true,
configurable: true

@@ -122,0 +121,0 @@ });

import { ZodRawShape } from '../types/base';
import { ZodObject } from '../types/object';
import { ZodObject, AnyZodObject } from '../types/object';
export declare namespace objectUtil {
export interface ZodObjectParams {
strict: boolean;
}
export type MergeObjectParams<First extends ZodObjectParams, Second extends ZodObjectParams> = {
strict: First['strict'] extends false ? false : Second['strict'] extends false ? false : true;
};
export type MergeShapes<U extends ZodRawShape, V extends ZodRawShape> = {
[k in Exclude<keyof U, keyof V>]: U[k];
} & V;
export type Flatten<T extends object> = {
[k in keyof T]: T[k];
};
type OptionalKeys<T extends object> = {
type optionalKeys<T extends object> = {
[k in keyof T]: undefined extends T[k] ? k : never;
}[keyof T];
type RequiredKeys<T extends object> = Exclude<keyof T, OptionalKeys<T>>;
type AddQuestionMarks<T extends object> = {
[k in OptionalKeys<T>]?: T[k];
type requiredKeys<T extends object> = Exclude<keyof T, optionalKeys<T>>;
export type addQuestionMarks<T extends object> = {
[k in optionalKeys<T>]?: T[k];
} & {
[k in RequiredKeys<T>]: T[k];
[k in requiredKeys<T>]: T[k];
};
type ObjectIntersection<T extends ZodRawShape> = AddQuestionMarks<{
[k in keyof T]: T[k]['_type'];
}>;
type Identity<T> = T;
type FlattenObject<T extends ZodRawShape> = Identity<{
export type identity<T> = T;
export type flatten<T extends object> = identity<{
[k in keyof T]: T[k];
}>;
export type NoNeverKeys<T extends object> = {
[k in keyof T]: T[k] extends never ? never : k;
export type NoNeverKeys<T extends ZodRawShape> = {
[k in keyof T]: [T[k]] extends [never] ? never : k;
}[keyof T];
export type NoNever<T extends object> = {
[k in NoNeverKeys<T>]: T[k];
};
export type ObjectType<T extends ZodRawShape> = FlattenObject<ObjectIntersection<NoNever<T>>>;
export type NoNever<T extends ZodRawShape> = identity<{
[k in NoNeverKeys<T>]: k extends keyof T ? T[k] : never;
}>;
export const mergeShapes: <U extends ZodRawShape, T extends ZodRawShape>(first: U, second: T) => T & U;
export const mergeObjects: <First extends ZodObject<any, any, any>>(first: First) => <Second extends ZodObject<any, any, any>>(second: Second) => ZodObject<First["_shape"] & Second["_shape"], MergeObjectParams<First["_params"], Second["_params"]>, First["_type"] & Second["_type"]>;
export const mergeObjects: <First extends AnyZodObject>(first: First) => <Second extends AnyZodObject>(second: Second) => ZodObject<First["_shape"] & Second["_shape"], First["_unknownKeys"], First["_catchall"]>;
export {};
}

@@ -21,3 +21,2 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.objectUtil = void 0;
var base_1 = require("../types/base");

@@ -28,3 +27,32 @@ var intersection_1 = require("../types/intersection");

(function (objectUtil) {
// export type ObjectType<T extends ZodRawShape> = FlattenObject<ObjectIntersection<T>>;
// export interface ZodObjectParams {
// strict: boolean;
// }
// export type ObjectType<T extends ZodRawShape> = flatten<
// ObjectIntersection<T>
// >;
// type ObjectIntersectionInput<T extends ZodRawShape> = addQuestionMarks<
// {
// [k in keyof T]: T[k]['_input'];
// }
// >;
// type ObjectIntersectionOutput<T extends ZodRawShape> = addQuestionMarks<
// {
// [k in keyof T]: T[k]['_output'];
// }
// >;
// export type objectInputType<T extends ZodObject<any, any, any>> = flatten<
// addQuestionMarks<
// {
// [k in keyof T['_shape']]: T['_shape'][k]['_input'];
// }
// >
// >;
// export type objectOutputType<T extends ZodObject<any, any, any>> = flatten<
// addQuestionMarks<
// {
// [k in keyof T['_shape']]: T['_shape'][k]['_output'];
// }
// >
// >;
objectUtil.mergeShapes = function (first, second) {

@@ -46,6 +74,7 @@ var firstKeys = Object.keys(first);

checks: __spreadArrays((first._def.checks || []), (second._def.checks || [])),
// strict: first.params.strict && second.params.strict,
params: {
strict: first.params.strict && second.params.strict,
},
unknownKeys: first._def.unknownKeys,
catchall: first._def.catchall,
// params: {
// strict: first.params.strict && second.params.strict,
// },
shape: function () { return mergedShape; },

@@ -52,0 +81,0 @@ });

@@ -1,16 +0,16 @@

import { ZodTypeAny } from '../types/base';
import * as z from '..';
import * as z from '../index';
import { AnyZodObject } from '../types/object';
export declare namespace partialUtil {
type RootDeepPartial<T extends ZodTypeAny> = {
object: T extends z.ZodObject<infer Shape, infer Params> ? z.ZodObject<{
[k in keyof Shape]: DeepPartial<Shape[k]>;
}, Params> : never;
rest: z.ZodUnion<[T, z.ZodUndefined]>;
type RootDeepPartial<T extends z.ZodTypeAny> = {
object: T extends AnyZodObject ? z.ZodObject<{
[k in keyof T['_shape']]: DeepPartial<T['_shape'][k]>;
}, T['_unknownKeys'], T['_catchall']> : never;
rest: ReturnType<T['optional']>;
}[T extends z.ZodObject<any> ? 'object' : 'rest'];
type DeepPartial<T extends ZodTypeAny> = {
object: T extends z.ZodObject<infer Shape, infer Params> ? z.ZodUnion<[z.ZodObject<{
type DeepPartial<T extends z.ZodTypeAny> = {
object: T extends z.ZodObject<infer Shape, infer Params> ? z.ZodOptional<z.ZodObject<{
[k in keyof Shape]: DeepPartial<Shape[k]>;
}, Params>, z.ZodUndefined]> : never;
rest: z.ZodUnion<[T, z.ZodUndefined]>;
}, Params>> : never;
rest: ReturnType<T['optional']>;
}[T extends z.ZodObject<any> ? 'object' : 'rest'];
}
export declare namespace util {
type AssertEqual<T, Expected> = T extends Expected ? (Expected extends T ? true : false) : false;
type AssertEqual<T, Expected> = T extends Expected ? Expected extends T ? true : false : false;
function assertNever(_x: never): never;
const getObjectType: (value: unknown) => string | undefined;
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
type OmitKeys<T, K extends string> = Pick<T, Exclude<keyof T, K>>;
type MakePartial<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
const arrayToEnum: <T extends string, U extends [T, ...T[]]>(items: U) => { [k in U[number]]: k; };
const getValidEnumValues: (obj: any) => any[];
const getValues: (obj: any) => any[];
const objectValues: (obj: any) => any[];
const find: <T>(arr: T[], checker: (arg: T) => any) => T | undefined;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.util = void 0;
var util;
(function (util) {
// export type ObjectsEqual<X extends object, Y extends object> = AssertEqual<X, Y> extends true
// ? 'bad' extends { [k in keyof X & keyof Y]: AssertEqual<X[k], Y[k]> extends true ? 'good' : 'bad' }[keyof X &
// keyof Y]
// ? { [k in keyof X & keyof Y]: AssertEqual<X[k], Y[k]> extends true ? 'good' : 'bad' }
// : true
// : false;
function assertNever(_x) {

@@ -16,12 +9,2 @@ throw new Error();

util.assertNever = assertNever;
util.getObjectType = function (value) {
var objectName = toString.call(value).slice(8, -1);
if (objectName) {
return objectName;
}
return undefined;
};
// const infer = <T extends string, U extends [T, ...T[]]>(items: U): U => {
// return items;
// };
util.arrayToEnum = function (items) {

@@ -35,3 +18,30 @@ var obj = {};

};
util.getValidEnumValues = function (obj) {
var validKeys = Object.keys(obj).filter(function (k) { return typeof obj[obj[k]] !== 'number'; });
var filtered = {};
for (var _i = 0, validKeys_1 = validKeys; _i < validKeys_1.length; _i++) {
var k = validKeys_1[_i];
filtered[k] = obj[k];
}
return util.getValues(filtered);
};
util.getValues = function (obj) {
return Object.keys(obj).map(function (e) {
return obj[e];
});
};
util.objectValues = function (obj) {
return Object.keys(obj).map(function (e) {
return obj[e];
});
};
util.find = function (arr, checker) {
for (var _i = 0, arr_1 = arr; _i < arr_1.length; _i++) {
var item = arr_1[_i];
if (checker(item))
return item;
}
return undefined;
};
})(util = exports.util || (exports.util = {}));
//# sourceMappingURL=util.js.map

@@ -10,2 +10,3 @@ import { ZodString, ZodStringDef } from './types/string';

import { ZodUnknown, ZodUnknownDef } from './types/unknown';
import { ZodNever, ZodNeverDef } from './types/never';
import { ZodVoid, ZodVoidDef } from './types/void';

@@ -22,10 +23,13 @@ import { ZodArray, ZodArrayDef } from './types/array';

import { ZodEnum, ZodEnumDef } from './types/enum';
import { ZodNativeEnum, ZodNativeEnumDef } from './types/nativeEnum';
import { ZodPromise, ZodPromiseDef } from './types/promise';
import { TypeOf, ZodType, ZodTypeAny, ZodTypeDef, ZodTypes } from './types/base';
import { ZodError, ZodErrorCode } from './ZodError';
import { ZodErrorMap } from './errorMap';
import { toZod } from './toZod';
import { ZodTransformer, ZodTransformerDef } from './types/transformer';
import { ZodOptional, ZodOptionalDef } from './types/optional';
import { ZodNullable, ZodNullableDef } from './types/nullable';
import { TypeOf, input, output, ZodType, ZodTypeAny, ZodTypeDef, ZodTypes } from './types/base';
import { ZodParsedType } from './parser';
import { ZodErrorMap } from './defaultErrorMap';
import { ZodCodeGenerator } from './codegen';
export { ZodTypeDef, ZodTypes };
declare type ZodDef = ZodStringDef | ZodNumberDef | ZodBigIntDef | ZodBooleanDef | ZodDateDef | ZodUndefinedDef | ZodNullDef | ZodAnyDef | ZodUnknownDef | ZodVoidDef | ZodArrayDef | ZodObjectDef | ZodUnionDef | ZodIntersectionDef | ZodTupleDef | ZodRecordDef | ZodFunctionDef | ZodLazyDef | ZodLiteralDef | ZodEnumDef | ZodPromiseDef;
declare type ZodDef = ZodStringDef | ZodNumberDef | ZodBigIntDef | ZodBooleanDef | ZodDateDef | ZodUndefinedDef | ZodNullDef | ZodAnyDef | ZodUnknownDef | ZodNeverDef | ZodVoidDef | ZodArrayDef | ZodObjectDef | ZodUnionDef | ZodIntersectionDef | ZodTupleDef | ZodRecordDef | ZodFunctionDef | ZodLazyDef | ZodLiteralDef | ZodEnumDef | ZodTransformerDef | ZodNativeEnumDef | ZodOptionalDef | ZodNullableDef | ZodPromiseDef;
declare const stringType: () => ZodString;

@@ -40,7 +44,6 @@ declare const numberType: () => ZodNumber;

declare const unknownType: () => ZodUnknown;
declare const neverType: () => ZodNever;
declare const voidType: () => ZodVoid;
declare const arrayType: <T extends ZodTypeAny>(schema: T) => ZodArray<T>;
declare const objectType: <T extends import("./types/base").ZodRawShape>(shape: T) => ZodObject<T, {
strict: true;
}, { [k_4 in keyof ({ [k_2 in { [k_1 in keyof { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }]: undefined extends { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }[k_1] ? k_1 : never; }[import("./helpers/objectUtil").objectUtil.NoNeverKeys<T>]]?: { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }[k_2] | undefined; } & { [k_3 in Exclude<import("./helpers/objectUtil").objectUtil.NoNeverKeys<T>, { [k_1 in keyof { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }]: undefined extends { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }[k_1] ? k_1 : never; }[import("./helpers/objectUtil").objectUtil.NoNeverKeys<T>]>]: { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }[k_3]; })]: ({ [k_2 in { [k_1 in keyof { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }]: undefined extends { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }[k_1] ? k_1 : never; }[import("./helpers/objectUtil").objectUtil.NoNeverKeys<T>]]?: { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }[k_2] | undefined; } & { [k_3 in Exclude<import("./helpers/objectUtil").objectUtil.NoNeverKeys<T>, { [k_1 in keyof { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }]: undefined extends { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }[k_1] ? k_1 : never; }[import("./helpers/objectUtil").objectUtil.NoNeverKeys<T>]>]: { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }[k_3]; })[k_4]; }>;
declare const objectType: <T extends import("./types/base").ZodRawShape>(shape: T) => ZodObject<T, "allow", ZodTypeAny>;
declare const unionType: <T extends [ZodTypeAny, ZodTypeAny, ...ZodTypeAny[]]>(types: T) => ZodUnion<T>;

@@ -50,21 +53,26 @@ declare const intersectionType: <T extends ZodTypeAny, U extends ZodTypeAny>(left: T, right: U) => ZodIntersection<T, U>;

declare const recordType: <Value extends ZodTypeAny = ZodTypeAny>(valueType: Value) => ZodRecord<Value>;
declare const functionType: <T extends ZodTuple<any> = ZodTuple<[]>, U extends ZodTypeAny = ZodVoid>(args?: T | undefined, returns?: U | undefined) => ZodFunction<T, U>;
declare const functionType: <T extends ZodTuple<any> = ZodTuple<[]>, U extends ZodTypeAny = ZodUnknown>(args?: T | undefined, returns?: U | undefined) => ZodFunction<T, U>;
declare const lazyType: <T extends ZodTypeAny>(getter: () => T) => ZodLazy<T>;
declare const literalType: <T extends import("./helpers/primitive").Primitive>(value: T) => ZodLiteral<T>;
declare const enumType: <U extends string, T extends [U, ...U[]]>(values: T) => ZodEnum<T>;
declare const nativeEnumType: <T extends {
[k: string]: string | number;
[nu: number]: string;
}>(values: T) => ZodNativeEnum<T>;
declare const promiseType: <T extends ZodTypeAny>(schema: T) => ZodPromise<T>;
declare const ostring: () => ZodUnion<[ZodString, ZodUndefined]>;
declare const onumber: () => ZodUnion<[ZodNumber, ZodUndefined]>;
declare const oboolean: () => ZodUnion<[ZodBoolean, ZodUndefined]>;
declare const transformerType: <I extends ZodTypeAny, O extends ZodTypeAny>(input: I, output: O, transformer: (arg: I["_output"]) => O["_input"] | Promise<O["_input"]>) => ZodTransformer<I, O>;
declare const optionalType: <T extends ZodTypeAny>(type: T) => import("./types/optional").ZodOptionalType<T>;
declare const nullableType: <T extends ZodTypeAny>(type: T) => import("./types/nullable").ZodNullableType<T>;
declare const ostring: () => ZodOptional<ZodString>;
declare const onumber: () => ZodOptional<ZodNumber>;
declare const oboolean: () => ZodOptional<ZodBoolean>;
declare const codegen: () => ZodCodeGenerator;
export { stringType as string, numberType as number, bigIntType as bigint, booleanType as boolean, dateType as date, undefinedType as undefined, nullType as null, anyType as any, unknownType as unknown, voidType as void, arrayType as array, objectType as object, unionType as union, intersectionType as intersection, tupleType as tuple, recordType as record, functionType as function, literalType as literal, enumType as enum, promiseType as promise, ostring, onumber, oboolean, codegen, };
export { toZod };
export declare const lazy: {
object: <T extends import("./types/base").ZodRawShape>(shape: () => T) => ZodObject<T, {
strict: true;
}, { [k_4 in keyof ({ [k_2 in { [k_1 in keyof { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }]: undefined extends { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }[k_1] ? k_1 : never; }[import("./helpers/objectUtil").objectUtil.NoNeverKeys<T>]]?: { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }[k_2] | undefined; } & { [k_3 in Exclude<import("./helpers/objectUtil").objectUtil.NoNeverKeys<T>, { [k_1 in keyof { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }]: undefined extends { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }[k_1] ? k_1 : never; }[import("./helpers/objectUtil").objectUtil.NoNeverKeys<T>]>]: { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }[k_3]; })]: ({ [k_2 in { [k_1 in keyof { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }]: undefined extends { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }[k_1] ? k_1 : never; }[import("./helpers/objectUtil").objectUtil.NoNeverKeys<T>]]?: { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }[k_2] | undefined; } & { [k_3 in Exclude<import("./helpers/objectUtil").objectUtil.NoNeverKeys<T>, { [k_1 in keyof { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }]: undefined extends { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }[k_1] ? k_1 : never; }[import("./helpers/objectUtil").objectUtil.NoNeverKeys<T>]>]: { [k in keyof import("./helpers/objectUtil").objectUtil.NoNever<T>]: import("./helpers/objectUtil").objectUtil.NoNever<T>[k]["_type"]; }[k_3]; })[k_4]; }>;
export declare const custom: <T>(check: (data: unknown) => any, params?: string | Partial<Pick<import("./ZodError").ZodCustomError, "path" | "message" | "params">> | undefined) => ZodType<T, ZodTypeDef, T>;
declare const instanceOfType: <T extends new (...args: any[]) => any>(cls: T, params?: string | Partial<Pick<import("./ZodError").ZodCustomError, "path" | "message" | "params">> | undefined) => ZodType<InstanceType<T>, ZodTypeDef, InstanceType<T>>;
export { stringType as string, numberType as number, bigIntType as bigint, booleanType as boolean, dateType as date, undefinedType as undefined, nullType as null, anyType as any, unknownType as unknown, neverType as never, voidType as void, arrayType as array, objectType as object, unionType as union, intersectionType as intersection, tupleType as tuple, recordType as record, functionType as function, lazyType as lazy, literalType as literal, enumType as enum, nativeEnumType as nativeEnum, promiseType as promise, instanceOfType as instanceof, transformerType as transformer, optionalType as optional, nullableType as nullable, ostring, onumber, oboolean, codegen, };
export declare const late: {
object: <T extends import("./types/base").ZodRawShape>(shape: () => T) => ZodObject<T, "allow", ZodTypeAny>;
};
export { ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodVoid, ZodArray, ZodObject, ZodUnion, ZodIntersection, ZodTuple, ZodRecord, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodPromise, ZodType, ZodType as Schema, ZodTypeAny, ZodDef, ZodError, ZodErrorMap, ZodErrorCode, ZodCodeGenerator, };
export declare type lazyobject<T extends object> = ZodObject<{
[k in keyof T]: ZodType<T[k], any>;
}>;
export { TypeOf, TypeOf as infer };
export { ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, ZodIntersection, ZodTuple, ZodRecord, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodTransformer, ZodOptional, ZodNullable, ZodType, ZodType as Schema, ZodType as ZodSchema, ZodTypeAny, ZodDef, ZodErrorMap, ZodParsedType, ZodCodeGenerator, };
export { TypeOf, TypeOf as infer, input, output };
export * from './ZodError';
"use strict";
/* ZOD */
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodCodeGenerator = exports.ZodErrorCode = exports.ZodError = exports.Schema = exports.ZodType = exports.ZodPromise = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.lazy = exports.codegen = exports.oboolean = exports.onumber = exports.ostring = exports.promise = exports.enum = exports.literal = exports.function = exports.record = exports.tuple = exports.intersection = exports.union = exports.object = exports.array = exports.void = exports.unknown = exports.any = exports.null = exports.undefined = exports.date = exports.boolean = exports.bigint = exports.number = exports.string = exports.ZodTypes = void 0;
var string_1 = require("./types/string");
Object.defineProperty(exports, "ZodString", { enumerable: true, get: function () { return string_1.ZodString; } });
exports.ZodString = string_1.ZodString;
var number_1 = require("./types/number");
Object.defineProperty(exports, "ZodNumber", { enumerable: true, get: function () { return number_1.ZodNumber; } });
exports.ZodNumber = number_1.ZodNumber;
var bigint_1 = require("./types/bigint");
Object.defineProperty(exports, "ZodBigInt", { enumerable: true, get: function () { return bigint_1.ZodBigInt; } });
exports.ZodBigInt = bigint_1.ZodBigInt;
var boolean_1 = require("./types/boolean");
Object.defineProperty(exports, "ZodBoolean", { enumerable: true, get: function () { return boolean_1.ZodBoolean; } });
exports.ZodBoolean = boolean_1.ZodBoolean;
var date_1 = require("./types/date");
Object.defineProperty(exports, "ZodDate", { enumerable: true, get: function () { return date_1.ZodDate; } });
exports.ZodDate = date_1.ZodDate;
var undefined_1 = require("./types/undefined");
Object.defineProperty(exports, "ZodUndefined", { enumerable: true, get: function () { return undefined_1.ZodUndefined; } });
exports.ZodUndefined = undefined_1.ZodUndefined;
var null_1 = require("./types/null");
Object.defineProperty(exports, "ZodNull", { enumerable: true, get: function () { return null_1.ZodNull; } });
exports.ZodNull = null_1.ZodNull;
var any_1 = require("./types/any");
Object.defineProperty(exports, "ZodAny", { enumerable: true, get: function () { return any_1.ZodAny; } });
exports.ZodAny = any_1.ZodAny;
var unknown_1 = require("./types/unknown");
Object.defineProperty(exports, "ZodUnknown", { enumerable: true, get: function () { return unknown_1.ZodUnknown; } });
exports.ZodUnknown = unknown_1.ZodUnknown;
var never_1 = require("./types/never");
exports.ZodNever = never_1.ZodNever;
var void_1 = require("./types/void");
Object.defineProperty(exports, "ZodVoid", { enumerable: true, get: function () { return void_1.ZodVoid; } });
exports.ZodVoid = void_1.ZodVoid;
var array_1 = require("./types/array");
Object.defineProperty(exports, "ZodArray", { enumerable: true, get: function () { return array_1.ZodArray; } });
exports.ZodArray = array_1.ZodArray;
var object_1 = require("./types/object");
Object.defineProperty(exports, "ZodObject", { enumerable: true, get: function () { return object_1.ZodObject; } });
exports.ZodObject = object_1.ZodObject;
var union_1 = require("./types/union");
Object.defineProperty(exports, "ZodUnion", { enumerable: true, get: function () { return union_1.ZodUnion; } });
exports.ZodUnion = union_1.ZodUnion;
var intersection_1 = require("./types/intersection");
Object.defineProperty(exports, "ZodIntersection", { enumerable: true, get: function () { return intersection_1.ZodIntersection; } });
exports.ZodIntersection = intersection_1.ZodIntersection;
var tuple_1 = require("./types/tuple");
Object.defineProperty(exports, "ZodTuple", { enumerable: true, get: function () { return tuple_1.ZodTuple; } });
exports.ZodTuple = tuple_1.ZodTuple;
var record_1 = require("./types/record");
Object.defineProperty(exports, "ZodRecord", { enumerable: true, get: function () { return record_1.ZodRecord; } });
exports.ZodRecord = record_1.ZodRecord;
var function_1 = require("./types/function");
Object.defineProperty(exports, "ZodFunction", { enumerable: true, get: function () { return function_1.ZodFunction; } });
exports.ZodFunction = function_1.ZodFunction;
var lazy_1 = require("./types/lazy");
Object.defineProperty(exports, "ZodLazy", { enumerable: true, get: function () { return lazy_1.ZodLazy; } });
exports.ZodLazy = lazy_1.ZodLazy;
var literal_1 = require("./types/literal");
Object.defineProperty(exports, "ZodLiteral", { enumerable: true, get: function () { return literal_1.ZodLiteral; } });
exports.ZodLiteral = literal_1.ZodLiteral;
var enum_1 = require("./types/enum");
Object.defineProperty(exports, "ZodEnum", { enumerable: true, get: function () { return enum_1.ZodEnum; } });
exports.ZodEnum = enum_1.ZodEnum;
var nativeEnum_1 = require("./types/nativeEnum");
exports.ZodNativeEnum = nativeEnum_1.ZodNativeEnum;
var promise_1 = require("./types/promise");
Object.defineProperty(exports, "ZodPromise", { enumerable: true, get: function () { return promise_1.ZodPromise; } });
exports.ZodPromise = promise_1.ZodPromise;
var transformer_1 = require("./types/transformer");
exports.ZodTransformer = transformer_1.ZodTransformer;
var optional_1 = require("./types/optional");
exports.ZodOptional = optional_1.ZodOptional;
var nullable_1 = require("./types/nullable");
exports.ZodNullable = nullable_1.ZodNullable;
var base_1 = require("./types/base");
Object.defineProperty(exports, "ZodType", { enumerable: true, get: function () { return base_1.ZodType; } });
Object.defineProperty(exports, "Schema", { enumerable: true, get: function () { return base_1.ZodType; } });
Object.defineProperty(exports, "ZodTypes", { enumerable: true, get: function () { return base_1.ZodTypes; } });
var ZodError_1 = require("./ZodError");
Object.defineProperty(exports, "ZodError", { enumerable: true, get: function () { return ZodError_1.ZodError; } });
Object.defineProperty(exports, "ZodErrorCode", { enumerable: true, get: function () { return ZodError_1.ZodErrorCode; } });
exports.ZodType = base_1.ZodType;
exports.Schema = base_1.ZodType;
exports.ZodSchema = base_1.ZodType;
exports.ZodTypes = base_1.ZodTypes;
// import { ZodError, ZodErrorCode } from './ZodError';
var parser_1 = require("./parser");
exports.ZodParsedType = parser_1.ZodParsedType;
var codegen_1 = require("./codegen");
Object.defineProperty(exports, "ZodCodeGenerator", { enumerable: true, get: function () { return codegen_1.ZodCodeGenerator; } });
exports.ZodCodeGenerator = codegen_1.ZodCodeGenerator;
var stringType = string_1.ZodString.create;

@@ -74,2 +87,4 @@ exports.string = stringType;

exports.unknown = unknownType;
var neverType = never_1.ZodNever.create;
exports.never = neverType;
var voidType = void_1.ZodVoid.create;

@@ -91,5 +106,4 @@ exports.void = voidType;

exports.function = functionType;
// const lazyType = ZodLazy.create;
// const lazyobjectType = ZodLazyObject.create;
// const recursionType = ZodObject.recursion;
var lazyType = lazy_1.ZodLazy.create;
exports.lazy = lazyType;
var literalType = literal_1.ZodLiteral.create;

@@ -99,4 +113,12 @@ exports.literal = literalType;

exports.enum = enumType;
var nativeEnumType = nativeEnum_1.ZodNativeEnum.create;
exports.nativeEnum = nativeEnumType;
var promiseType = promise_1.ZodPromise.create;
exports.promise = promiseType;
var transformerType = transformer_1.ZodTransformer.create;
exports.transformer = transformerType;
var optionalType = optional_1.ZodOptional.create;
exports.optional = optionalType;
var nullableType = nullable_1.ZodNullable.create;
exports.nullable = nullableType;
var ostring = function () { return stringType().optional(); };

@@ -110,5 +132,14 @@ exports.ostring = ostring;

exports.codegen = codegen;
exports.lazy = {
exports.custom = function (check, params) { return anyType().refine(check, params); };
var instanceOfType = function (cls, params) {
if (params === void 0) { params = {
message: "Input not instance of " + cls.name,
}; }
return exports.custom(function (data) { return data instanceof cls; }, params);
};
exports.instanceof = instanceOfType;
exports.late = {
object: object_1.ZodObject.lazycreate,
};
__export(require("./ZodError"));
//# sourceMappingURL=index.js.map
import * as z from './types/base';
import { ZodErrorMap } from './errorMap';
export declare type ParseParams = {
seen?: {
schema: any;
objects: any[];
}[];
path?: (string | number)[];
errorMap?: ZodErrorMap;
};
export declare const getParsedType: (data: any) => ParsedType;
export declare const ParsedType: {
object: "object";
symbol: "symbol";
unknown: "unknown";
function: "function";
import { ZodError, ZodSuberrorOptionalMessage } from './ZodError';
import { util } from './helpers/util';
import { ZodErrorMap } from './defaultErrorMap';
export declare const getParsedType: (data: any) => "string" | "nan" | "number" | "integer" | "boolean" | "date" | "bigint" | "symbol" | "function" | "undefined" | "null" | "array" | "object" | "unknown" | "promise" | "void" | "never";
export declare const ZodParsedType: {
string: "string";
nan: "nan";
number: "number";
nan: "nan";
integer: "integer";
boolean: "boolean";
date: "date";
bigint: "bigint";
symbol: "symbol";
function: "function";
undefined: "undefined";
null: "null";
array: "array";
object: "object";
unknown: "unknown";
promise: "promise";
void: "void";
never: "never";
};
export declare type ParsedType = keyof typeof ParsedType;
export declare const ZodParser: (schemaDef: z.ZodTypeDef) => (obj: any, baseParams?: ParseParams) => any;
export declare type ZodParsedType = keyof typeof ZodParsedType;
declare type stripPath<T extends object> = T extends any ? util.OmitKeys<T, 'path'> : never;
export declare type MakeErrorData = stripPath<ZodSuberrorOptionalMessage> & {
path?: (string | number)[];
};
export declare type ParseParams = {
seen?: {
schema: z.ZodType<any>;
objects: {
input: any;
error?: ZodError;
output: any;
}[];
}[];
path?: (string | number)[];
errorMap?: ZodErrorMap;
async?: boolean;
};
export declare const ZodParser: (schema: z.ZodType<any, z.ZodTypeDef, any>) => (data: any, baseParams?: ParseParams) => any;
export {};

@@ -13,21 +13,2 @@ "use strict";

};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -76,8 +57,16 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodParser = exports.ParsedType = exports.getParsedType = void 0;
var z = __importStar(require("./types/base"));
var index_1 = require("./index");
var ZodError_1 = require("./ZodError");
var util_1 = require("./helpers/util");
var errorMap_1 = require("./errorMap");
var defaultErrorMap_1 = require("./defaultErrorMap");
var PseudoPromise_1 = require("./PseudoPromise");
exports.getParsedType = function (data) {

@@ -103,4 +92,2 @@ if (typeof data === 'string')

return 'undefined';
if (data === null)
return 'null';
if (typeof data === 'undefined')

@@ -111,8 +98,8 @@ return 'undefined';

return 'array';
if (!data)
return 'null';
if (data.then &&
typeof data.then === 'function' &&
data.catch &&
typeof data.catch === 'function'
// && util.getObjectType(data) !== 'Promise'
) {
typeof data.catch === 'function') {
return 'promise';

@@ -124,6 +111,7 @@ }

};
exports.ParsedType = util_1.util.arrayToEnum([
exports.ZodParsedType = util_1.util.arrayToEnum([
'string',
'nan',
'number',
'integer',
'boolean',

@@ -141,311 +129,537 @@ 'date',

'void',
'never',
]);
exports.ZodParser = function (schemaDef) { return function (obj, baseParams) {
if (baseParams === void 0) { baseParams = { seen: [], errorMap: errorMap_1.defaultErrorMap, path: [] }; }
var INVALID = Symbol('invalid_data');
var NODATA = Symbol('no_data');
exports.ZodParser = function (schema) { return function (data, baseParams) {
if (baseParams === void 0) { baseParams = { seen: [], errorMap: defaultErrorMap_1.defaultErrorMap, path: [] }; }
var params = {
seen: baseParams.seen || [],
path: baseParams.path || [],
errorMap: baseParams.errorMap || errorMap_1.defaultErrorMap,
errorMap: baseParams.errorMap || defaultErrorMap_1.defaultErrorMap,
async: baseParams.async || false,
};
var makeError = function (errorData) {
var errorArg = __assign(__assign({}, errorData), { path: params.path });
var ctxArg = { metadata: {}, data: obj };
var defaultError = errorMap_1.defaultErrorMap === params.errorMap
? "Invalid value"
: errorMap_1.defaultErrorMap(errorArg, __assign(__assign({}, ctxArg), { defaultError: "Invalid value." }));
return __assign(__assign({}, errorData), { path: params.path, message: errorData.message || params.errorMap(errorArg, __assign(__assign({}, ctxArg), { defaultError: defaultError })) });
var errorArg = __assign(__assign({}, errorData), { path: __spreadArrays(params.path, (errorData.path || [])) });
var ctxArg = { data: data };
var defaultError = defaultErrorMap_1.defaultErrorMap === params.errorMap
? { message: "Invalid value." }
: defaultErrorMap_1.defaultErrorMap(errorArg, __assign(__assign({}, ctxArg), { defaultError: "Invalid value." }));
return __assign(__assign({}, errorData), { path: __spreadArrays(params.path, (errorData.path || [])), message: errorData.message ||
params.errorMap(errorArg, __assign(__assign({}, ctxArg), { defaultError: defaultError.message })).message });
};
var def = schemaDef;
// const { seen } = params;
// const y:ZodObject<any> = "asdf" as any;
// console.log(`visit ${schemaDef.t}: ${typeof obj} - ${obj.name || ''}`);
// if (!['number', 'string', 'boolean', 'undefined'].includes(typeof obj)) {
var schemaSeen = params.seen.find(function (x) { return x.schema === schemaDef; });
if (schemaSeen) {
if (schemaSeen.objects.indexOf(obj) !== -1) {
// console.log(`seen ${typeof obj} before: ${obj.name}`);
return obj;
}
else {
schemaSeen.objects.push(obj);
}
}
else {
params.seen.push({ schema: schemaDef, objects: [obj] });
}
// }
var error = new ZodError_1.ZodError([]);
var parsedType = exports.getParsedType(obj);
// runs all invalid_type checks
// if (Object.keys(ParsedType).includes(def.t)) {
// if (parsedType !== def.t) {
// console.log(`def.t: ${def.t}`);
// console.log(`found: ${parsedType}`);
// error.addError(
// makeError({ code: ZodErrorCode.invalid_type, expected: def.t as ParsedType, received: parsedType }),
// );
// throw error;
var def = schema._def;
var PROMISE = new PseudoPromise_1.PseudoPromise();
PROMISE._default = true;
var RESULT = {
input: data,
output: NODATA,
};
params.seen = params.seen || [];
// partially working cycle detection system
// params.seen.push({ schema, objects: [] });
// const schemaSeen = util.find(params.seen, x => x.schema === schema)!; // params.seen.find(x => x.schema === schemaDef)!;
// const objectSeen = util.find(schemaSeen.objects, arg => arg.input === data); //.find(x => x.data === data);
// if (objectSeen) {
// console.log('object seen');
// if (objectSeen.error) {
// don't throw previous error
// the path with be wrong for arrays
// let the validation re-run and generate a new error
// } else if (objectSeen.output !== NODATA) {
// return the previous value
// return objectSeen.output;
// }
// } else {
// schemaSeen.objects.push(RESULT);
// }
// else {
// params.seen.push({ schema: schemaDef, objects: [{ data, promise: PROM }] });
// }
// }
var ERROR = new ZodError_1.ZodError([]);
var THROW = function () {
RESULT.error = ERROR;
throw ERROR;
};
// const defaultPROMISE = Symbol('return_value');
// let returnValue: PseudoPromise<any>; // = defaultReturnValue;
var parsedType = exports.getParsedType(data);
switch (def.t) {
case z.ZodTypes.string:
// error.addError()
if (parsedType !== exports.ParsedType.string) {
//throw ZodError.fromString(`Non-string type: ${typeof obj}`);
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_type, expected: exports.ParsedType.string, received: parsedType }));
throw error;
if (parsedType !== exports.ZodParsedType.string) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_type,
expected: exports.ZodParsedType.string,
received: parsedType,
}));
// setError(error);
THROW();
}
// return obj as any;
PROMISE = PseudoPromise_1.PseudoPromise.resolve(data);
break;
case z.ZodTypes.number:
if (parsedType !== exports.ParsedType.number) {
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_type, expected: exports.ParsedType.number, received: parsedType }));
throw error;
if (parsedType !== exports.ZodParsedType.number) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_type,
expected: exports.ZodParsedType.number,
received: parsedType,
}));
// setError(error);
THROW();
}
if (Number.isNaN(obj)) {
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_type, expected: exports.ParsedType.number, received: exports.ParsedType.nan }));
throw error;
if (Number.isNaN(data)) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_type,
expected: exports.ZodParsedType.number,
received: exports.ZodParsedType.nan,
}));
// setError(error);
THROW();
}
// return obj as any;
PROMISE = PseudoPromise_1.PseudoPromise.resolve(data);
break;
case z.ZodTypes.bigint:
if (parsedType !== exports.ParsedType.bigint) {
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_type, expected: exports.ParsedType.number, received: parsedType }));
throw error;
// throw ZodError.fromString(`Non-bigint type: ${typeof obj}.`);
if (parsedType !== exports.ZodParsedType.bigint) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_type,
expected: exports.ZodParsedType.number,
received: parsedType,
}));
// setError(error);
THROW();
}
// return obj;
PROMISE = PseudoPromise_1.PseudoPromise.resolve(data);
break;
case z.ZodTypes.boolean:
if (parsedType !== exports.ParsedType.boolean) {
// throw ZodError.fromString(`Non-boolean type: ${typeof obj}`);
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_type, expected: exports.ParsedType.boolean, received: parsedType }));
throw error;
if (parsedType !== exports.ZodParsedType.boolean) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_type,
expected: exports.ZodParsedType.boolean,
received: parsedType,
}));
// setError(error);
THROW();
}
// return obj as any;
PROMISE = PseudoPromise_1.PseudoPromise.resolve(data);
break;
case z.ZodTypes.undefined:
if (parsedType !== exports.ParsedType.undefined) {
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_type, expected: exports.ParsedType.undefined, received: parsedType }));
throw error;
// throw ZodError.fromString(`Non-undefined type:Found: ${typeof obj}`);
if (parsedType !== exports.ZodParsedType.undefined) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_type,
expected: exports.ZodParsedType.undefined,
received: parsedType,
}));
// setError(error);
THROW();
}
// return undefined;
PROMISE = PseudoPromise_1.PseudoPromise.resolve(data);
break;
case z.ZodTypes.null:
if (parsedType !== exports.ParsedType.null) {
// throw ZodError.fromString(`Non-null type: ${typeof obj}`);
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_type, expected: exports.ParsedType.null, received: parsedType }));
throw error;
if (parsedType !== exports.ZodParsedType.null) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_type,
expected: exports.ZodParsedType.null,
received: parsedType,
}));
// setError(error);
THROW();
}
PROMISE = PseudoPromise_1.PseudoPromise.resolve(data);
break;
case z.ZodTypes.any:
PROMISE = PseudoPromise_1.PseudoPromise.resolve(data);
break;
case z.ZodTypes.unknown:
PROMISE = PseudoPromise_1.PseudoPromise.resolve(data);
break;
case z.ZodTypes.never:
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_type,
expected: exports.ZodParsedType.never,
received: parsedType,
}));
PROMISE = PseudoPromise_1.PseudoPromise.resolve(INVALID);
break;
case z.ZodTypes.void:
if (parsedType !== exports.ParsedType.undefined && parsedType !== exports.ParsedType.null) {
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_type, expected: exports.ParsedType.void, received: parsedType }));
throw error;
if (parsedType !== exports.ZodParsedType.undefined &&
parsedType !== exports.ZodParsedType.null) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_type,
expected: exports.ZodParsedType.void,
received: parsedType,
}));
// setError(error);
THROW();
}
PROMISE = PseudoPromise_1.PseudoPromise.resolve(data);
break;
case z.ZodTypes.array:
if (parsedType !== exports.ParsedType.array) {
// throw ZodError.fromString(`Non-array type: ${typeof obj}`);
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_type, expected: exports.ParsedType.array, received: parsedType }));
throw error;
RESULT.output = [];
if (parsedType !== exports.ZodParsedType.array) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_type,
expected: exports.ZodParsedType.array,
received: parsedType,
}));
// setError(error);
THROW();
}
var data = obj;
// const arrayError = ZodError.create([]);
if (def.nonempty === true && obj.length === 0) {
error.addError(makeError({ code: ZodError_1.ZodErrorCode.nonempty_array_is_empty }));
throw error;
// throw ZodError.fromString('Array cannot be empty');
// const data: any[] = data;
if (def.nonempty === true && data.length === 0) {
ERROR.addError(makeError({ code: ZodError_1.ZodErrorCode.nonempty_array_is_empty }));
THROW();
}
data.map(function (item, i) {
// PROMISE = (data as any[]).map((item, i) => {
// try {
// return def.type.parse(item, { ...params, path: [...params.path, i] });
// } catch (err) {
// const zerr: ZodError = err;
// ERROR.addErrors(zerr.errors);
// }
// });
PROMISE = PseudoPromise_1.PseudoPromise.all(data.map(function (item, i) {
try {
var parsedItem = def.type.parse(item, __assign(__assign({}, params), { path: __spreadArrays(params.path, [i]) }));
return parsedItem;
return PseudoPromise_1.PseudoPromise.resolve(def.type.parse(item, __assign(__assign({}, params), { path: __spreadArrays(params.path, [i]) })));
}
catch (err) {
var zerr = err;
error.addErrors(zerr.errors);
// arrayError.mergeChild(i, err);
if (err instanceof ZodError_1.ZodError) {
var zerr = err;
ERROR.addErrors(zerr.errors);
return PseudoPromise_1.PseudoPromise.resolve(INVALID);
}
throw err;
}
});
if (!error.isEmpty) {
// throw ZodError.fromString(arrayErrors.join('\n\n'));
throw error;
}
}));
// if (!ERROR.isEmpty) {
// THROW();
// }
break;
// return parsedArray as any;
case z.ZodTypes.object:
if (parsedType !== exports.ParsedType.object) {
// throw ZodError.fromString(`Non-object type: ${typeof obj}`);
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_type, expected: exports.ParsedType.object, received: parsedType }));
throw error;
RESULT.output = {};
if (parsedType !== exports.ZodParsedType.object) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_type,
expected: exports.ZodParsedType.object,
received: parsedType,
}));
THROW();
}
console.log(def.shape);
var objectPromises = {};
var shape = def.shape();
if (def.params.strict) {
var shapeKeys_1 = Object.keys(shape);
var objKeys = Object.keys(obj);
var extraKeys = objKeys.filter(function (k) { return shapeKeys_1.indexOf(k) === -1; });
if (extraKeys.length) {
// console.log(def);
error.addError(makeError({ code: ZodError_1.ZodErrorCode.unrecognized_keys, keys: extraKeys }));
// throw error;
// throw ZodError.fromString(`Unexpected key(s) in object: ${extraKeys.map(k => `'${k}'`).join(', ')}`);
}
var shapeKeys_2 = Object.keys(shape);
var dataKeys = Object.keys(data);
var extraKeys = dataKeys.filter(function (k) { return shapeKeys_2.indexOf(k) === -1; });
var _loop_1 = function (key) {
var keyValidator = shapeKeys_2.includes(key)
? def.shape()[key]
: !(def.catchall instanceof index_1.ZodNever)
? def.catchall
: undefined;
if (!keyValidator)
return "continue";
objectPromises[key] = new PseudoPromise_1.PseudoPromise().then(function () {
try {
return keyValidator.parse(data[key], __assign(__assign({}, params), { path: __spreadArrays(params.path, [key]) }));
}
catch (err) {
if (err instanceof ZodError_1.ZodError) {
var zerr = err;
ERROR.addErrors(zerr.errors);
return INVALID;
}
else {
throw err;
}
}
});
};
for (var _i = 0, shapeKeys_1 = shapeKeys_2; _i < shapeKeys_1.length; _i++) {
var key = shapeKeys_1[_i];
_loop_1(key);
}
// const parsedObject: any = {};
// const objectError = ZodError.create([]);
for (var key in shape) {
try {
// const parsedEntry =
def.shape()[key].parse(obj[key], __assign(__assign({}, params), { path: __spreadArrays(params.path, [key]) }));
// parsedObject[key] = parsedEntry;
if (def.catchall instanceof index_1.ZodNever) {
if (def.unknownKeys === 'allow') {
for (var _a = 0, extraKeys_1 = extraKeys; _a < extraKeys_1.length; _a++) {
var key = extraKeys_1[_a];
objectPromises[key] = PseudoPromise_1.PseudoPromise.resolve(data[key]);
}
}
catch (err) {
var zerr = err;
error.addErrors(zerr.errors);
// objectError.mergeChild(key, err);
else if (def.unknownKeys === 'strict') {
if (extraKeys.length > 0) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.unrecognized_keys,
keys: extraKeys,
}));
}
}
else if (def.unknownKeys === 'strip') {
// do nothing
}
else {
util_1.util.assertNever(def.unknownKeys);
}
}
// if (!objectError.isEmpty) {
// throw objectError; //ZodError.fromString(objectErrors.join('\n'));
// }
// return parsedObject;
PROMISE = PseudoPromise_1.PseudoPromise.object(objectPromises).then(function (resolvedObject) {
Object.assign(RESULT.output, resolvedObject);
return RESULT.output;
});
break;
case z.ZodTypes.union:
var isValid = false;
// const unionErrors: string[] = [];
// unionError.addError('union', 'Error parsing union type.');
var unionErrors = [];
for (var _i = 0, _a = def.options; _i < _a.length; _i++) {
var option = _a[_i];
// let parsedUnion: any;
var isValid_1 = false;
var unionErrors_1 = [];
// const INVALID = Symbol('invalid_data');
PROMISE = PseudoPromise_1.PseudoPromise.all(def.options.map(function (opt) {
try {
option.parse(obj, params);
isValid = true;
var unionValueProm = PseudoPromise_1.PseudoPromise.resolve(opt.parse(data, params));
isValid_1 = true;
return unionValueProm;
// return parsed;
}
catch (err) {
unionErrors.push(err);
// unionErrors.push(`\tunion option #${def.options.indexOf(option)}: ${err.message}`);
// isValid = false;
if (err instanceof ZodError_1.ZodError) {
unionErrors_1.push(err);
return PseudoPromise_1.PseudoPromise.resolve(INVALID);
}
throw err;
}
}
// if all but one of the union types threw a type error
// merge in the one non-type-error ZodError the usual way
if (!isValid) {
var filteredErrors = unionErrors.filter(function (err) {
return err.errors[0].code !== 'invalid_type';
});
if (filteredErrors.length === 1) {
error.addErrors(filteredErrors[0].errors);
// }
}))
.then(function (unionResults) {
return util_1.util.find(unionResults, function (val) { return val !== INVALID; });
})
.then(function (unionResult) {
// const unionResults: any[] = _unionResults;
if (!isValid_1) {
var filteredErrors = unionErrors_1.filter(function (err) {
return err.errors[0].code !== 'invalid_type';
});
if (filteredErrors.length === 1) {
ERROR.addErrors(filteredErrors[0].errors);
}
else {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_union,
unionErrors: unionErrors_1,
}));
}
return INVALID;
}
return unionResult;
});
// .then(unionResults => (unionResults as any).find((res: any) => res !== INVALID));
// for (const option of def.options) {
// try {
// parsedUnion = option.parse(data, params);
// isValid = true;
// break;
// } catch (err) {
// unionErrors.push(err);
// }
// }
// if (!isValid) {
// const filteredErrors = unionErrors.filter(err => {
// return err.errors[0].code !== 'invalid_type';
// });
// if (filteredErrors.length === 1) {
// ERROR.addErrors(filteredErrors[0].errors);
// } else {
// ERROR.addError(
// makeError({
// code: ZodErrorCode.invalid_union,
// unionErrors: unionErrors,
// }),
// );
// }
// }
// PROMISE = parsedUnion;
break;
case z.ZodTypes.intersection:
// let parsedIntersection:any;
// let parsedLeft: any;
// let parsedRight: any;
// PROMISE = PseudoPromise.resolve(data);
PROMISE = PseudoPromise_1.PseudoPromise.all([
new PseudoPromise_1.PseudoPromise().then(function () {
try {
return def.left.parse(data, params);
}
catch (err) {
if (err instanceof ZodError_1.ZodError) {
ERROR.addErrors(err.errors);
return INVALID;
}
throw err;
}
}),
new PseudoPromise_1.PseudoPromise().then(function () {
try {
return def.right.parse(data, params);
}
catch (err) {
if (err instanceof ZodError_1.ZodError) {
ERROR.addErrors(err.errors);
return INVALID;
}
throw err;
}
}),
]).then(function (_a) {
var parsedLeft = _a[0], parsedRight = _a[1];
if (parsedLeft === INVALID || parsedRight === INVALID)
return INVALID;
var parsedLeftType = exports.getParsedType(parsedLeft);
var parsedRightType = exports.getParsedType(parsedRight);
if (parsedLeft === parsedRight) {
return parsedLeft;
}
else if (parsedLeftType === exports.ZodParsedType.object &&
parsedRightType === exports.ZodParsedType.object) {
return __assign(__assign({}, parsedLeft), parsedRight);
}
else {
error.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_union,
suberrors: unionErrors,
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_intersection_types,
}));
}
}
// if (!isValid) {
// throw ZodError.fromString('\n' + unionErrors.join('\n'));
// throw ZodError.fromString(
// `Error parsing union.\nReceived: ${JSON.stringify(obj, null, 2)}\nExpected: ${def.options
// .map(x => x._def.t)
// .join(' OR ')}`,
// );
// }
});
break;
case z.ZodTypes.intersection:
// const errors: string[] = [];
try {
def.left.parse(obj, params);
case z.ZodTypes.optional:
if (parsedType === exports.ZodParsedType.undefined) {
PROMISE = PseudoPromise_1.PseudoPromise.resolve(undefined);
break;
}
catch (err) {
error.addErrors(err.errors);
// errors.push(`Left side of intersection: ${err.message}`);
}
try {
def.right.parse(obj, params);
}
catch (err) {
error.addErrors(err.errors);
// errors.push(`Right side of intersection: ${err.message}`);
}
// if (errors.length) {
// throw ZodError.fromString(errors.join('\n'));
// }
PROMISE = new PseudoPromise_1.PseudoPromise().then(function () {
try {
return def.innerType.parse(data, params);
}
catch (err) {
if (err instanceof ZodError_1.ZodError) {
ERROR.addErrors(err.errors);
return INVALID;
}
throw err;
}
});
break;
case z.ZodTypes.tuple:
if (parsedType !== exports.ParsedType.array) {
// tupleError.addError('','Non-array type detected; invalid tuple.')
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_type, expected: exports.ParsedType.array, received: parsedType }));
throw error;
// throw ZodError.fromString('Non-array type detected; invalid tuple.');
case z.ZodTypes.nullable:
if (parsedType === exports.ZodParsedType.null) {
PROMISE = PseudoPromise_1.PseudoPromise.resolve(null);
break;
}
if (def.items.length !== obj.length) {
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_array_length, expected: def.items.length, received: obj.length }));
// tupleError.addError('',`Incorrect number of elements in tuple: expected ${def.items.length}, got ${obj.length}`)
// throw ZodError.fromString(
// `Incorrect number of elements in tuple: expected ${def.items.length}, got ${obj.length}`,
// );
}
// const data:any[] = obj;
// const tupleError = ZodError.create([]);
var parsedTuple = [];
var tupleData = obj;
for (var index in tupleData) {
var item = tupleData[index];
var itemParser = def.items[index];
PROMISE = new PseudoPromise_1.PseudoPromise().then(function () {
try {
parsedTuple.push(itemParser.parse(item, __assign(__assign({}, params), { path: __spreadArrays(params.path, [index]) })));
return def.innerType.parse(data, params);
}
catch (err) {
// console.log(`mering child: ${index}`);
error.addErrors(err.errors);
// tupleError.mergeChild(index, err);
if (err instanceof ZodError_1.ZodError) {
ERROR.addErrors(err.errors);
return INVALID;
}
throw err;
}
});
break;
case z.ZodTypes.tuple:
if (parsedType !== exports.ZodParsedType.array) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_type,
expected: exports.ZodParsedType.array,
received: parsedType,
}));
// setError(error);
THROW();
}
// if (!tupleError.isEmpty) {
// throw tupleError;
if (data.length > def.items.length) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.too_big,
maximum: def.items.length,
inclusive: true,
type: 'array',
}));
}
else if (data.length < def.items.length) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.too_small,
minimum: def.items.length,
inclusive: true,
type: 'array',
}));
}
// const parsedTuple: any[] = [];
var tupleData = data;
// const parsedTuple: any = [];
// const tuplePromises: PseudoPromise[] = [];
PROMISE = PseudoPromise_1.PseudoPromise.all(tupleData.map(function (item, index) {
var itemParser = def.items[index];
return new PseudoPromise_1.PseudoPromise().then(function () {
try {
return itemParser.parse(item, __assign(__assign({}, params), { path: __spreadArrays(params.path, [index]) }));
}
catch (err) {
if (err instanceof ZodError_1.ZodError) {
ERROR.addErrors(err.errors);
return INVALID;
}
throw err;
}
});
}));
// for (const index in tupleData) {
// const item = tupleData[index];
// const itemParser = def.items[index];
// tuplePromises.push(
// new PseudoPromise().then(() => {
// try {
// return itemParser.parse(item, { ...params, path: [...params.path, index] });
// } catch (err) {
// ERROR.addErrors(err.errors);
// }
// }),
// );
// // parsedTuple.push(itemParser.parse(item, { ...params, path: [...params.path, index] }));
// }
// return parsedTuple as any;
// PROMISE = parsedTuple;
break;
case z.ZodTypes.lazy:
var lazySchema = def.getter();
lazySchema.parse(obj, params);
// return lazySchema.parse(obj, params);
PROMISE = PseudoPromise_1.PseudoPromise.resolve(lazySchema.parse(data, params));
break;
// return obj;
case z.ZodTypes.literal:
// const literalValue = def.value;
// if (typeof literalValue === 'object' && obj !== null) throw ZodError.fromString(`Can't process non-primitive literals.`);
// if (['string','']typeof obj === 'object') throw ZodError.fromString(`Invalid type: ${object}.`);
if (obj !== def.value) {
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_literal_value, expected: def.value }));
// throw ZodError.fromString(`${obj} !== ${def.value}`);
if (data !== def.value) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_literal_value,
expected: def.value,
}));
}
PROMISE = PseudoPromise_1.PseudoPromise.resolve(data);
break;
case z.ZodTypes.enum:
if (def.values.indexOf(obj) === -1) {
error.addError(makeError({
if (def.values.indexOf(data) === -1) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_enum_value,
options: def.values,
}));
// throw ZodError.fromString(`"${obj}" does not match any value in enum`);
}
// return obj;
PROMISE = PseudoPromise_1.PseudoPromise.resolve(data);
break;
case z.ZodTypes.nativeEnum:
if (util_1.util.getValidEnumValues(def.values).indexOf(data) === -1) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_enum_value,
options: util_1.util.objectValues(def.values),
}));
}
PROMISE = PseudoPromise_1.PseudoPromise.resolve(data);
break;
case z.ZodTypes.function:
if (parsedType !== exports.ParsedType.function) {
error.addError(makeError({
if (parsedType !== exports.ZodParsedType.function) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_type,
expected: exports.ParsedType.function,
expected: exports.ZodParsedType.function,
received: parsedType,
}));
throw error;
// throw ZodError.fromString(`Non-function type: "${typeof obj}"`);
// setError(error);
THROW();
}

@@ -458,3 +672,3 @@ var validatedFunc = function () {

try {
def.args.parse(args);
def.args.parse(args, params);
}

@@ -466,3 +680,3 @@ catch (err) {

code: ZodError_1.ZodErrorCode.invalid_arguments,
suberrors: [err],
argumentsError: err,
}));

@@ -473,5 +687,5 @@ throw argsError;

}
var result = obj.apply(void 0, args);
var result = data.apply(void 0, args);
try {
def.returns.parse(result);
return def.returns.parse(result, params);
}

@@ -483,3 +697,3 @@ catch (err) {

code: ZodError_1.ZodErrorCode.invalid_return_type,
suberrors: [err],
returnTypeError: err,
}));

@@ -490,118 +704,219 @@ throw returnsError;

}
def.returns.parse(result);
return result;
};
return validatedFunc;
// return obj;
PROMISE = PseudoPromise_1.PseudoPromise.resolve(validatedFunc);
// return validatedFunc;
break;
case z.ZodTypes.record:
if (parsedType !== exports.ParsedType.object) {
error.addError(makeError({
if (parsedType !== exports.ZodParsedType.object) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_type,
expected: exports.ParsedType.object,
expected: exports.ZodParsedType.object,
received: parsedType,
}));
throw error;
// setError(error);
THROW();
}
// if (typeof obj !== 'object') throw ZodError.fromString(`Non-object type: ${typeof obj}`);
// if (Array.isArray(obj)) throw ZodError.fromString(`Non-object type: array`);
// const parsedRecord: any = {};
// const recordError = new ZodError([]);
for (var key in obj) {
try {
// parsedRecord[key] =
def.valueType.parse(obj[key], __assign(__assign({}, params), { path: __spreadArrays(params.path, [key]) }));
}
catch (err) {
error.addErrors(err.errors);
// recordError.mergeChild(key, err);
}
var parsedRecordPromises = {};
var _loop_2 = function (key) {
parsedRecordPromises[key] = new PseudoPromise_1.PseudoPromise().then(function () {
try {
return def.valueType.parse(data[key], __assign(__assign({}, params), { path: __spreadArrays(params.path, [key]) }));
}
catch (err) {
if (err instanceof ZodError_1.ZodError) {
ERROR.addErrors(err.errors);
return INVALID;
}
throw err;
}
});
};
for (var key in data) {
_loop_2(key);
}
// if (!recordError.isEmpty) throw recordError;
// return parsedRecord;
PROMISE = PseudoPromise_1.PseudoPromise.object(parsedRecordPromises);
// PROMISE = parsedRecord;
break;
case z.ZodTypes.date:
if (!(obj instanceof Date)) {
error.addError(makeError({
if (!(data instanceof Date)) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_type,
expected: exports.ParsedType.date,
expected: exports.ZodParsedType.date,
received: parsedType,
}));
throw error;
// setError(error);
THROW();
}
if (isNaN(obj.getTime())) {
// if (isNaN(obj.getTime())) {
// return obj;
// } else {
error.addError(makeError({
if (isNaN(data.getTime())) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_date,
}));
throw error;
// throw ZodError.fromString(`Invalid date.`);
// }
// setError(error);
THROW();
}
PROMISE = PseudoPromise_1.PseudoPromise.resolve(data);
break;
case z.ZodTypes.promise:
if (parsedType !== exports.ParsedType.promise) {
error.addError(makeError({
if (parsedType !== exports.ZodParsedType.promise && params.async !== true) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.invalid_type,
expected: exports.ParsedType.promise,
expected: exports.ZodParsedType.promise,
received: parsedType,
}));
throw error;
// setError(error);
THROW();
}
// if (!obj.then || typeof obj.then !== 'function') {
// console.log(JSON.stringify(obj, null, 2));
// throw ZodError.fromString(`Non-Promise type: ${typeof obj}`);
// }
// if (!obj.catch || typeof obj.catch !== 'function') {
// console.log(JSON.stringify(obj, null, 2));
// throw ZodError.fromString(`Non-Promise type: ${typeof obj}`);
// }
// if (util.getObjectType(obj) !== 'Promise') {
// throw ZodError.fromString(`Non-Promise type.`);
// }
// if (def.checks) {
// throw ZodError.fromString("Can't apply custom validators to Promise schemas.");
// }
return new Promise(function (res, rej) { return __awaiter(void 0, void 0, void 0, function () {
var objValue, parsed;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, obj];
case 1:
objValue = _a.sent();
try {
parsed = def.type.parse(objValue, params);
res(parsed);
}
catch (err) {
rej(err);
}
return [2 /*return*/];
var promisified = parsedType === exports.ZodParsedType.promise ? data : Promise.resolve(data);
PROMISE = PseudoPromise_1.PseudoPromise.resolve(promisified.then(function (resolvedData) {
try {
var parsed = def.type.parse(resolvedData, params);
return parsed;
}
catch (err) {
if (err instanceof ZodError_1.ZodError) {
ERROR.addErrors(err.errors);
}
});
}); });
throw err;
}
}));
// new Promise(async (res, rej) => {
// const dataValue = await data;
// try {
// const parsed = def.type.parse(dataValue, params);
// res(parsed);
// } catch (err) {
// rej(err);
// }
// }),
// );
break;
case z.ZodTypes.transformer:
PROMISE = new PseudoPromise_1.PseudoPromise()
.then(function () {
try {
return def.input.parse(data, params);
}
catch (err) {
if (err instanceof ZodError_1.ZodError) {
ERROR.addErrors(err.errors);
}
throw err;
}
})
.then(function (inputParseResult) {
try {
var transformed = def.transformer(inputParseResult);
if (transformed instanceof Promise && params.async === false) {
if (z.inputSchema(def.output)._def.t !== z.ZodTypes.promise) {
throw new Error("You can't call .parse on a schema containing async transformations.");
}
}
return transformed;
}
catch (err) {
if (err instanceof ZodError_1.ZodError) {
ERROR.addErrors(err.errors);
return INVALID;
}
throw err;
}
})
.then(function (transformedResult) {
try {
return def.output.parse(transformedResult, params);
}
catch (err) {
if (err instanceof ZodError_1.ZodError) {
ERROR.addErrors(err.errors);
return INVALID;
}
throw err;
}
});
break;
default:
// function
// return obj;
PROMISE = PseudoPromise_1.PseudoPromise.resolve('adsf');
util_1.util.assertNever(def);
// break;
}
if (PROMISE._default === true) {
throw new Error('Result is not materialized.');
}
if (!ERROR.isEmpty) {
THROW();
}
var customChecks = def.checks || [];
for (var _b = 0, customChecks_1 = customChecks; _b < customChecks_1.length; _b++) {
var check = customChecks_1[_b];
if (!check.check(obj)) {
error.addError(makeError({
code: ZodError_1.ZodErrorCode.custom_error,
params: check.params,
message: check.message,
}));
// throw ZodError.fromString(check.message || `Failed custom check.`);
var checkCtx = {
makeError: function (arg) {
ERROR.addError(makeError(arg));
},
};
if (params.async === false) {
var resolvedValue = PROMISE.getValueSync();
// const SYNC_ERROR =
// "You can't use .parse on a schema containing async refinements or transformations. Use .parseAsync instead.";
// if (resolvedValue instanceof Promise) {
// if (def.t !== z.ZodTypes.promise) {
// throw new Error(SYNC_ERROR);
// }
// }
for (var _b = 0, customChecks_1 = customChecks; _b < customChecks_1.length; _b++) {
var check = customChecks_1[_b];
var checkResult = check.check(resolvedValue, checkCtx);
if (checkResult instanceof Promise)
throw new Error("You can't use .parse on a schema containing async refinements. Use .parseAsync instead.");
// if (!checkResult) {
// const { check: checkMethod, ...noMethodCheck } = check;
// ERROR.addError(makeError(noMethodCheck));
// }
}
if (!ERROR.isEmpty) {
THROW();
}
// if (resolvedValue === INVALID) {
// throw new ZodError([]).addError(
// makeError({
// code: ZodErrorCode.custom_error,
// message: 'Invalid',
// }),
// );
// }
return resolvedValue;
}
if (!error.isEmpty) {
throw error;
else {
// if (params.async == true) {
var checker = function () { return __awaiter(void 0, void 0, void 0, function () {
var resolvedValue;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, PROMISE.getValueAsync()];
case 1:
resolvedValue = _a.sent();
return [4 /*yield*/, Promise.all(customChecks.map(function (check) { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, check.check(resolvedValue, checkCtx)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
}); }))];
case 2:
_a.sent();
if (resolvedValue === INVALID && ERROR.isEmpty) {
ERROR.addError(makeError({
code: ZodError_1.ZodErrorCode.custom_error,
message: 'Invalid',
}));
}
if (!ERROR.isEmpty) {
THROW();
}
return [2 /*return*/, resolvedValue];
}
});
}); };
return checker();
}
return obj;
}; };
//# sourceMappingURL=parser.js.map
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;

@@ -23,32 +47,18 @@ };

var z = __importStar(require("."));
// import { User, Post } from './userpost';
// const gen = z.codegen();
// gen.generate(User);
// gen.generate(Post);
// console.log(gen.dump());
var errorMap = function (error, ctx) {
if (error.code === z.ZodErrorCode.invalid_type) {
if (error.expected === 'string') {
return "This ain't no string!";
}
}
if (error.code === z.ZodErrorCode.custom_error) {
return JSON.stringify(error.params, null, 2);
}
return ctx.defaultError;
};
try {
z.string()
.refinement({
check: function (val) { return val.length > 12; },
// params: { test: 15 },
message: 'override',
})
.parse('asdf', { errorMap: errorMap });
}
catch (err) {
var zerr = err;
console.log(zerr.errors[0].message);
// expect(zerr.errors[0].message).toEqual('override');
}
var run = function () { return __awaiter(void 0, void 0, void 0, function () {
var coercedString;
return __generator(this, function (_a) {
console.log(z
.string()
.transform(function (val) { return val.replace('pretty', 'extremely'); })
.transform(function (val) { return val.toUpperCase(); })
.transform(function (val) { return val.split(' ').join('πŸ‘'); })
.parse('zod 2 is pretty cool'));
coercedString = z.unknown().transform(z.string(), function (val) { return "" + val; });
console.log(typeof coercedString.parse(false));
console.log(typeof coercedString.parse(12));
return [2 /*return*/];
});
}); };
run();
//# sourceMappingURL=playground.js.map
import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
import { ZodUnion } from './union';
export interface ZodAnyDef extends z.ZodTypeDef {

@@ -9,6 +6,4 @@ t: z.ZodTypes.any;

export declare class ZodAny extends z.ZodType<any, ZodAnyDef> {
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
toJSON: () => ZodAnyDef;
static create: () => ZodAny;
}

@@ -15,27 +15,11 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodAny = void 0;
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var union_1 = require("./union");
var ZodAny = /** @class */ (function (_super) {

@@ -45,4 +29,4 @@ __extends(ZodAny, _super);

var _this = _super !== null && _super.apply(this, arguments) || this;
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
_this.toJSON = function () { return _this._def; };

@@ -49,0 +33,0 @@ return _this;

import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
import { ZodUnion } from './union';
export interface ZodArrayDef<T extends z.ZodTypeAny = z.ZodTypeAny> extends z.ZodTypeDef {

@@ -10,3 +7,3 @@ t: z.ZodTypes.array;

}
export declare class ZodArray<T extends z.ZodTypeAny> extends z.ZodType<T['_type'][], ZodArrayDef<T>> {
export declare class ZodArray<T extends z.ZodTypeAny> extends z.ZodType<T['_output'][], ZodArrayDef<T>, T['_input'][]> {
toJSON: () => {

@@ -18,11 +15,13 @@ t: z.ZodTypes.array;

get element(): T;
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
min: (minLength: number, msg?: string | undefined) => this;
max: (maxLength: number, msg?: string | undefined) => this;
length: (len: number, msg?: string | undefined) => this;
min: (minLength: number, message?: string | {
message?: string | undefined;
} | undefined) => this;
max: (maxLength: number, message?: string | {
message?: string | undefined;
} | undefined) => this;
length: (len: number, message?: string | undefined) => this;
nonempty: () => ZodNonEmptyArray<T>;
static create: <T_1 extends z.ZodTypeAny>(schema: T_1) => ZodArray<T_1>;
}
export declare class ZodNonEmptyArray<T extends z.ZodTypeAny> extends z.ZodType<[T['_type'], ...T['_type'][]], ZodArrayDef<T>> {
export declare class ZodNonEmptyArray<T extends z.ZodTypeAny> extends z.ZodType<[T['_output'], ...T['_output'][]], ZodArrayDef<T>, [T['_input'], ...T['_input'][]]> {
toJSON: () => {

@@ -32,4 +31,9 @@ t: z.ZodTypes.array;

};
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
min: (minLength: number, message?: string | {
message?: string | undefined;
} | undefined) => this;
max: (maxLength: number, message?: string | {
message?: string | undefined;
} | undefined) => this;
length: (len: number, message?: string | undefined) => this;
}

@@ -26,27 +26,15 @@ "use strict";

};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodNonEmptyArray = exports.ZodArray = void 0;
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var union_1 = require("./union");
// import { ZodUndefined } from './undefined';
// import { ZodNull } from './null';
// import { ZodUnion } from './union';
var ZodError_1 = require("../ZodError");
var ZodArray = /** @class */ (function (_super) {

@@ -63,12 +51,14 @@ __extends(ZodArray, _super);

};
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
_this.min = function (minLength, msg) {
return _this.refine(function (data) { return data.length >= minLength; }, msg || "Array must contain " + minLength + " or more items.");
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
_this.min = function (minLength, message) {
return _this.refinement(function (data) { return data.length >= minLength; }, __assign({ code: ZodError_1.ZodErrorCode.too_small, type: 'array', inclusive: true, minimum: minLength }, (typeof message === 'string' ? { message: message } : message)));
};
_this.max = function (maxLength, msg) {
return _this.refine(function (data) { return data.length <= maxLength; }, msg || "Array must contain " + maxLength + " or fewer items.");
_this.max = function (maxLength, message) {
return _this.refinement(function (data) { return data.length <= maxLength; }, __assign({
// check: data => data.length <= maxLength,
code: ZodError_1.ZodErrorCode.too_big, type: 'array', inclusive: true, maximum: maxLength }, (typeof message === 'string' ? { message: message } : message)));
};
_this.length = function (len, msg) {
return _this.refine(function (data) { return data.length == len; }, msg || "Array must contain " + len + " items.");
_this.length = function (len, message) {
return _this.min(len, { message: message }).max(len, { message: message });
};

@@ -84,11 +74,5 @@ _this.nonempty = function () {

},
enumerable: false,
enumerable: true,
configurable: true
});
// pick = <Mask extends zodmaskUtil.Params<T>>(mask: Mask): ZodArray<zodmaskUtil.pick<T, Mask>> => {
// return applyMask(this, mask, 'pick');
// };
// omit = <Mask extends zodmaskUtil.Params<T>>(mask: Mask): ZodArray<zodmaskUtil.omit<T, Mask>> => {
// return applyMask(this, mask, 'omit');
// };
ZodArray.create = function (schema) {

@@ -114,12 +98,18 @@ return new ZodArray({

};
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
_this.min = function (minLength, message) {
return _this.refinement(function (data) { return data.length >= minLength; }, __assign({
// check: data => data.length >= minLength,
code: ZodError_1.ZodErrorCode.too_small, minimum: minLength, type: 'array', inclusive: true }, (typeof message === 'string' ? { message: message } : message)));
};
_this.max = function (maxLength, message) {
return _this.refinement(function (data) { return data.length <= maxLength; }, __assign({
// check:
code: ZodError_1.ZodErrorCode.too_big, maximum: maxLength, type: 'array', inclusive: true }, (typeof message === 'string' ? { message: message } : message)));
};
_this.length = function (len, message) {
return _this.min(len, { message: message }).max(len, { message: message });
};
return _this;
// static create = <T extends z.ZodTypeAny>(schema: T): ZodArray<T> => {
// return new ZodArray({
// t: z.ZodTypes.array,
// nonempty: true,
// type: schema,
// });
// };
}

@@ -126,0 +116,0 @@ return ZodNonEmptyArray;

@@ -1,2 +0,6 @@

import { ParseParams } from '../parser';
import { ParseParams, MakeErrorData } from '../parser';
import { ZodArray, ZodTransformer, ZodError } from '../index';
import { ZodOptionalType } from './optional';
import { ZodNullableType } from './nullable';
import { ZodCustomError } from '../ZodError';
export declare enum ZodTypes {

@@ -18,44 +22,72 @@ string = "string",

lazy = "lazy",
lazyobject = "lazyobject",
literal = "literal",
enum = "enum",
nativeEnum = "nativeEnum",
promise = "promise",
any = "any",
unknown = "unknown",
void = "void"
never = "never",
void = "void",
transformer = "transformer",
optional = "optional",
nullable = "nullable"
}
export declare type ZodTypeAny = ZodType<any>;
export declare type ZodTypeAny = ZodType<any, any>;
export declare type ZodRawShape = {
[k: string]: ZodTypeAny;
};
declare type Check<T> = {
check: (arg: T) => any;
message?: string;
params?: {
[k: string]: any;
};
export declare const inputSchema: (schema: ZodType<any, ZodTypeDef, any>) => ZodType<any, ZodTypeDef, any>;
export declare const outputSchema: (schema: ZodType<any, ZodTypeDef, any>) => ZodType<any, ZodTypeDef, any>;
declare type InternalCheck<T> = {
check: (arg: T, ctx: {
makeError: (arg: MakeErrorData) => void;
}) => any;
};
export interface ZodTypeDef {
t: ZodTypes;
checks?: Check<any>[];
checks?: InternalCheck<any>[];
accepts?: ZodType<any, any>;
}
export declare type TypeOf<T extends {
_type: any;
}> = T['_type'];
export declare type Infer<T extends {
_type: any;
}> = T['_type'];
export declare abstract class ZodType<Type, Def extends ZodTypeDef = ZodTypeDef> {
readonly _type: Type;
export declare type TypeOf<T extends ZodType<any>> = T['_output'];
export declare type input<T extends ZodType<any>> = T['_input'];
export declare type output<T extends ZodType<any>> = T['_output'];
export declare type infer<T extends ZodType<any>> = T['_output'];
export declare abstract class ZodType<Output, Def extends ZodTypeDef = ZodTypeDef, Input = Output> {
readonly _type: Output;
readonly _output: Output;
readonly _def: Def;
parse: (x: Type | unknown, params?: ParseParams) => Type;
is(u: Type): u is Type;
check(u: Type | unknown): u is Type;
refine: <Val extends (arg: Type) => any>(check: Val, message?: string) => this;
refinement: (refinement: Check<Type>) => this;
readonly _input: Input;
parse: (x: unknown, params?: ParseParams) => Output;
safeParse: (x: unknown, params?: ParseParams) => {
success: true;
data: Output;
} | {
success: false;
error: ZodError;
};
parseAsync: (x: unknown, params?: ParseParams) => Promise<Output>;
safeParseAsync: (x: unknown, params?: ParseParams) => Promise<{
success: true;
data: Output;
} | {
success: false;
error: ZodError;
}>;
is(u: Input): u is Input;
check(u: unknown): u is Input;
refine: <Func extends (arg: Output) => any>(check: Func, message?: string | Partial<Pick<ZodCustomError, "path" | "message" | "params">>) => this;
refinement: (check: (arg: Output) => any, refinementData: MakeErrorData) => this;
protected _refinement: (refinement: InternalCheck<Output>['check']) => this;
constructor(def: Def);
abstract toJSON: () => object;
abstract optional: () => any;
abstract nullable: () => any;
optional: () => ZodOptionalType<this>;
or: () => ZodOptionalType<this>;
nullable: () => ZodNullableType<this>;
array: () => ZodArray<this>;
transform<This extends this, U extends ZodType<any>, Tx extends (arg: This['_output']) => U['_input'] | Promise<U['_input']>>(input: U, transformer: Tx): ZodTransformer<This, U>;
transform<This extends this, Tx extends (arg: This['_output']) => This['_input'] | Promise<This['_input']>>(transformer: Tx): ZodTransformer<This, This>;
default: <T extends Output = Output, Opt extends ReturnType<this['optional']> = ReturnType<this['optional']>>(def: T) => ZodTransformer<Opt, this>;
isOptional: () => boolean;
isNullable: () => boolean;
}
export {};

@@ -13,2 +13,38 @@ "use strict";

};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __spreadArrays = (this && this.__spreadArrays) || function () {

@@ -22,4 +58,4 @@ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;

Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodType = exports.ZodTypes = void 0;
var parser_1 = require("../parser");
var index_1 = require("../index");
var ZodTypes;

@@ -36,3 +72,2 @@ (function (ZodTypes) {

ZodTypes["object"] = "object";
// interface = 'interface',
ZodTypes["union"] = "union";

@@ -44,61 +79,155 @@ ZodTypes["intersection"] = "intersection";

ZodTypes["lazy"] = "lazy";
ZodTypes["lazyobject"] = "lazyobject";
ZodTypes["literal"] = "literal";
ZodTypes["enum"] = "enum";
ZodTypes["nativeEnum"] = "nativeEnum";
ZodTypes["promise"] = "promise";
ZodTypes["any"] = "any";
ZodTypes["unknown"] = "unknown";
ZodTypes["never"] = "never";
ZodTypes["void"] = "void";
ZodTypes["transformer"] = "transformer";
ZodTypes["optional"] = "optional";
ZodTypes["nullable"] = "nullable";
})(ZodTypes = exports.ZodTypes || (exports.ZodTypes = {}));
// interface Assertable<T> {
// is(value: any): value is T;
// assert(value: any): asserts value is T;
// }
exports.inputSchema = function (schema) {
if (schema instanceof index_1.ZodTransformer) {
return exports.inputSchema(schema._def.input);
}
else {
return schema;
}
};
exports.outputSchema = function (schema) {
if (schema instanceof index_1.ZodTransformer) {
return exports.inputSchema(schema._def.output);
}
else {
return schema;
}
};
var ZodType = /** @class */ (function () {
// mask = <P extends maskUtil.Params<Type>>(_params: P): ZodType<maskUtil.Pick<Type, P>> => {
// return Masker(this, _params) as any;
// };
// pick = <Params extends maskUtil.Params<Type>>(_params: Params): maskUtil.Mask<Type, Params> => {
// return 'asdf' as any;
// };
// Wrapper = class<Type, Schema> {
// value: Type;
// schema: Schema;
// constructor(schema: Schema, value: Type) {
// this.value = value;
// this.schema = schema;
// }
// };
// wrap: (value: this['_type'], params?: ParseParams) => any = (value, params) => {
// const parsed = this.parse(value, params);
// return new this.Wrapper<this['_type'], this>(this, parsed);
// // return new ZodValue(this, this.parse(value, params));
// };
// wrap: (value: Type, params?: ParseParams) => ZodWrapped<this> = (value, params) => {
// const parsed = this.parse(value, params);
// return new ZodWrapped(this, parsed);
// // return new ZodValue(this, this.parse(value, params));
// };
function ZodType(def) {
var _this = this;
this.safeParse = function (data, params) {
try {
var parsed = _this.parse(data, params);
return { success: true, data: parsed };
}
catch (err) {
if (err instanceof index_1.ZodError) {
return { success: false, error: err };
}
throw err;
}
};
this.parseAsync = function (value, params) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.parse(value, __assign(__assign({}, params), { async: true }))];
case 1: return [2 /*return*/, _a.sent()];
}
});
}); };
this.safeParseAsync = function (data, params) { return __awaiter(_this, void 0, void 0, function () {
var parsed, err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.parseAsync(data, params)];
case 1:
parsed = _a.sent();
return [2 /*return*/, { success: true, data: parsed }];
case 2:
err_1 = _a.sent();
if (err_1 instanceof index_1.ZodError) {
return [2 /*return*/, { success: false, error: err_1 }];
}
throw err_1;
case 3: return [2 /*return*/];
}
});
}); };
this.refine = function (check, message) {
if (message === void 0) { message = 'Invalid value.'; }
// const newChecks = [...this._def.checks || [], { check, message }];
// console.log((this as any).constructor);
return new _this.constructor(__assign(__assign({}, _this._def), { checks: __spreadArrays((_this._def.checks || []), [{ check: check, message: message }]) }));
// return this;
if (typeof message === 'string') {
return _this._refinement(function (val, ctx) {
var result = check(val);
var setError = function () {
return ctx.makeError({
code: index_1.ZodErrorCode.custom_error,
message: message,
});
};
if (result instanceof Promise) {
return result.then(function (data) {
if (!data)
setError();
});
}
if (!result) {
setError();
return result;
}
});
}
return _this._refinement(function (val, ctx) {
var result = check(val);
var setError = function () {
return ctx.makeError(__assign({ code: index_1.ZodErrorCode.custom_error }, message));
};
if (result instanceof Promise) {
return result.then(function (data) {
if (!data)
setError();
});
}
if (!result) {
setError();
return result;
}
});
};
this.refinement = function (refinement) {
// const finalRefinement = {
// check: refinement.check,
// code: refinement.code || 'custom-refinement-failed',
// message: refinement.message,
// };
// const newChecks = [...this._def.checks || [], { check, message }];
// console.log((this as any).constructor);
return new _this.constructor(__assign(__assign({}, _this._def), { checks: __spreadArrays((_this._def.checks || []), [refinement]) }));
// return this;
this.refinement = function (check, refinementData) {
return _this._refinement(function (val, ctx) {
if (!check(val)) {
ctx.makeError(refinementData);
}
});
};
this.parse = parser_1.ZodParser(def);
this._refinement = function (refinement) {
return new _this.constructor(__assign(__assign({}, _this._def), { checks: __spreadArrays((_this._def.checks || []), [{ check: refinement }]) }));
};
// abstract // opt optional: () => any;
this.optional = function () { return index_1.ZodOptional.create(_this); };
this.or = this.optional;
this.nullable = function () {
return index_1.ZodNullable.create(_this);
};
// nullable: () => ZodUnion<[this, ZodNull]> = () =>
// ZodUnion.create([this, ZodNull.create()]);
this.array = function () { return index_1.ZodArray.create(_this); };
this.default = function (def) {
return index_1.ZodTransformer.create(_this.optional(), _this, function (x) {
return (x || def);
});
};
// default: (val: Type) => ZodTransformer<ZodType<Type | undefined>, this> = val => {
// return ZodTransformer.create(this.optional(), this, x => {
// return (x || val) as any;
// }) as any;
// };
// codec = (): ZodCodec<this, this> => {
// return ZodCodec.create(this, this, x => x);
// };
// transform: <U extends ZodType<any>, Tx extends (arg: Type) => U['_type']>(
// x: U,s
// transformer: Tx,
// ) => ZodCodec<this, U> = (input, transformer) => {
// return ZodCodec.create(input, this, transformer);
// };
this.isOptional = function () { return _this.safeParse(undefined).success; };
this.isNullable = function () { return _this.safeParse(null).success; };
this._def = def;
this.parse = parser_1.ZodParser(this);
}

@@ -123,14 +252,11 @@ ZodType.prototype.is = function (u) {

};
ZodType.prototype.transform = function (input, transformer) {
if (transformer) {
return index_1.ZodTransformer.create(this, input, transformer);
}
return index_1.ZodTransformer.create(this, this, input);
};
return ZodType;
}());
exports.ZodType = ZodType;
// export class ZodWrapped<T extends ZodType<any, any>> {
// value: T['_type'];
// schema: T;
// constructor(schema: T, value: T['_type']) {
// this.schema = schema;
// this.value = value;
// }
// // toJSON =()=>this.toJSON();
// }
//# sourceMappingURL=base.js.map
import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
import { ZodUnion } from './union';
export interface ZodBigIntDef extends z.ZodTypeDef {

@@ -9,6 +6,4 @@ t: z.ZodTypes.bigint;

export declare class ZodBigInt extends z.ZodType<bigint, ZodBigIntDef> {
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
toJSON: () => ZodBigIntDef;
static create: () => ZodBigInt;
}

@@ -15,33 +15,17 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodBigInt = void 0;
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var union_1 = require("./union");
var ZodBigInt = /** @class */ (function (_super) {
__extends(ZodBigInt, _super);
function ZodBigInt() {
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
_this.toJSON = function () { return _this._def; };

@@ -48,0 +32,0 @@ return _this;

import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
import { ZodUnion } from './union';
export interface ZodBooleanDef extends z.ZodTypeDef {

@@ -9,6 +6,4 @@ t: z.ZodTypes.boolean;

export declare class ZodBoolean extends z.ZodType<boolean, ZodBooleanDef> {
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
toJSON: () => ZodBooleanDef;
static create: () => ZodBoolean;
}

@@ -15,33 +15,17 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodBoolean = void 0;
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var union_1 = require("./union");
var ZodBoolean = /** @class */ (function (_super) {
__extends(ZodBoolean, _super);
function ZodBoolean() {
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
_this.toJSON = function () { return _this._def; };

@@ -48,0 +32,0 @@ return _this;

import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
import { ZodUnion } from './union';
export interface ZodDateDef extends z.ZodTypeDef {

@@ -9,6 +6,4 @@ t: z.ZodTypes.date;

export declare class ZodDate extends z.ZodType<Date, ZodDateDef> {
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
toJSON: () => ZodDateDef;
static create: () => ZodDate;
}

@@ -15,33 +15,17 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodDate = void 0;
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var union_1 = require("./union");
var ZodDate = /** @class */ (function (_super) {
__extends(ZodDate, _super);
function ZodDate() {
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
_this.toJSON = function () { return _this._def; };

@@ -48,0 +32,0 @@ return _this;

import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
import { ZodUnion } from './union';
export declare type ArrayKeys = keyof any[];

@@ -16,6 +13,5 @@ export declare type Indices<T> = Exclude<keyof T, ArrayKeys>;

export declare class ZodEnum<T extends [string, ...string[]]> extends z.ZodType<T[number], ZodEnumDef<T>> {
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
toJSON: () => ZodEnumDef<T>;
get OptionsList(): T;
get options(): T;
get enum(): Values<T>;
get Values(): Values<T>;

@@ -22,0 +18,0 @@ get Enum(): Values<T>;

@@ -15,43 +15,39 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodEnum = void 0;
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var union_1 = require("./union");
var ZodEnum = /** @class */ (function (_super) {
__extends(ZodEnum, _super);
function ZodEnum() {
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
_this.toJSON = function () { return _this._def; };
return _this;
}
Object.defineProperty(ZodEnum.prototype, "OptionsList", {
Object.defineProperty(ZodEnum.prototype, "options", {
get: function () {
return this._def.values;
},
enumerable: false,
enumerable: true,
configurable: true
});
Object.defineProperty(ZodEnum.prototype, "enum", {
get: function () {
var enumValues = {};
for (var _i = 0, _a = this._def.values; _i < _a.length; _i++) {
var val = _a[_i];
enumValues[val] = val;
}
return enumValues;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ZodEnum.prototype, "Values", {

@@ -66,3 +62,3 @@ get: function () {

},
enumerable: false,
enumerable: true,
configurable: true

@@ -79,3 +75,3 @@ });

},
enumerable: false,
enumerable: true,
configurable: true

@@ -82,0 +78,0 @@ });

import * as z from './base';
import { ZodTuple } from './tuple';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
import { ZodUnion } from './union';
import { ZodVoid } from './void';
import { ZodUnknown } from './unknown';
export interface ZodFunctionDef<Args extends ZodTuple<any> = ZodTuple<any>, Returns extends z.ZodTypeAny = z.ZodTypeAny> extends z.ZodTypeDef {

@@ -12,13 +9,11 @@ t: z.ZodTypes.function;

}
export declare type TypeOfFunction<Args extends ZodTuple<any>, Returns extends z.ZodTypeAny> = Args['_type'] extends Array<any> ? (...args: Args['_type']) => Returns['_type'] : never;
export declare class ZodFunction<Args extends ZodTuple<any>, Returns extends z.ZodTypeAny> extends z.ZodType<TypeOfFunction<Args, Returns>, ZodFunctionDef> {
export declare type OuterTypeOfFunction<Args extends ZodTuple<any>, Returns extends z.ZodTypeAny> = Args['_input'] extends Array<any> ? (...args: Args['_input']) => Returns['_output'] : never;
export declare type InnerTypeOfFunction<Args extends ZodTuple<any>, Returns extends z.ZodTypeAny> = Args['_output'] extends Array<any> ? (...args: Args['_output']) => Returns['_input'] : never;
export declare class ZodFunction<Args extends ZodTuple<any>, Returns extends z.ZodTypeAny> extends z.ZodType<OuterTypeOfFunction<Args, Returns>, ZodFunctionDef, InnerTypeOfFunction<Args, Returns>> {
readonly _def: ZodFunctionDef<Args, Returns>;
readonly _type: TypeOfFunction<Args, Returns>;
args: <Items extends [] | [z.ZodTypeAny, ...z.ZodTypeAny[]]>(...items: Items) => ZodFunction<ZodTuple<Items>, Returns>;
returns: <NewReturnType extends z.ZodType<any, any>>(returnType: NewReturnType) => ZodFunction<Args, NewReturnType>;
implement: (func: TypeOfFunction<Args, Returns>) => TypeOfFunction<Args, Returns>;
validate: (func: TypeOfFunction<Args, Returns>) => TypeOfFunction<Args, Returns>;
static create: <T extends ZodTuple<any> = ZodTuple<[]>, U extends z.ZodTypeAny = ZodVoid>(args?: T | undefined, returns?: U | undefined) => ZodFunction<T, U>;
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
returns: <NewReturnType extends z.ZodType<any, any, any>>(returnType: NewReturnType) => ZodFunction<Args, NewReturnType>;
implement: <F extends InnerTypeOfFunction<Args, Returns>>(func: F) => F;
validate: <F extends InnerTypeOfFunction<Args, Returns>>(func: F) => F;
static create: <T extends ZodTuple<any> = ZodTuple<[]>, U extends z.ZodTypeAny = ZodUnknown>(args?: T | undefined, returns?: U | undefined) => ZodFunction<T, U>;
toJSON: () => {

@@ -25,0 +20,0 @@ t: z.ZodTypes.function;

@@ -26,29 +26,14 @@ "use strict";

};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodFunction = void 0;
var z = __importStar(require("./base"));
var tuple_1 = require("./tuple");
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var union_1 = require("./union");
var void_1 = require("./void");
var unknown_1 = require("./unknown");
// type as df = string extends unknown ? true : false
var ZodFunction = /** @class */ (function (_super) {

@@ -58,2 +43,3 @@ __extends(ZodFunction, _super);

var _this = _super !== null && _super.apply(this, arguments) || this;
// readonly _type!: TypeOfFunction<Args, Returns>;
_this.args = function () {

@@ -69,20 +55,9 @@ var items = [];

};
// implement = this.parse;
_this.implement = function (func) {
var validatedFunc = _this.parse(func);
// const validatedFunc = (...args: any[]) => {
// try {
// this._def.args.parse(args as any);
// const result = func(...(args as any));
// this._def.returns.parse(result);
// return result;
// } catch (err) {
// throw err;
// }
// };
return validatedFunc;
};
_this.validate = _this.implement;
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
_this.toJSON = function () {

@@ -101,3 +76,3 @@ return {

args: args || tuple_1.ZodTuple.create([]),
returns: returns || void_1.ZodVoid.create(),
returns: returns || unknown_1.ZodUnknown.create(),
});

@@ -104,0 +79,0 @@ };

import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
import { ZodUnion } from './union';
export interface ZodIntersectionDef<T extends z.ZodTypeAny = z.ZodTypeAny, U extends z.ZodTypeAny = z.ZodTypeAny> extends z.ZodTypeDef {

@@ -10,5 +7,3 @@ t: z.ZodTypes.intersection;

}
export declare class ZodIntersection<T extends z.ZodTypeAny, U extends z.ZodTypeAny> extends z.ZodType<T['_type'] & U['_type'], ZodIntersectionDef<T, U>> {
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
export declare class ZodIntersection<T extends z.ZodTypeAny, U extends z.ZodTypeAny> extends z.ZodType<T['_output'] & U['_output'], ZodIntersectionDef<T, U>, T['_input'] & U['_input']> {
toJSON: () => {

@@ -15,0 +10,0 @@ t: z.ZodTypes.intersection;

@@ -15,33 +15,17 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodIntersection = void 0;
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var union_1 = require("./union");
var ZodIntersection = /** @class */ (function (_super) {
__extends(ZodIntersection, _super);
function ZodIntersection() {
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
_this.toJSON = function () { return ({

@@ -48,0 +32,0 @@ t: _this._def.t,

import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
import { ZodUnion } from './union';
export interface ZodLazyDef<T extends z.ZodTypeAny = z.ZodTypeAny> extends z.ZodTypeDef {

@@ -9,8 +6,6 @@ t: z.ZodTypes.lazy;

}
export declare class ZodLazy<T extends z.ZodTypeAny> extends z.ZodType<z.TypeOf<T>, ZodLazyDef<T>> {
export declare class ZodLazy<T extends z.ZodTypeAny> extends z.ZodType<z.output<T>, ZodLazyDef<T>, z.input<T>> {
get schema(): T;
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
toJSON: () => never;
static create: <T_1 extends z.ZodTypeAny>(getter: () => T_1) => ZodLazy<T_1>;
}

@@ -15,27 +15,11 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodLazy = void 0;
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var union_1 = require("./union");
var ZodLazy = /** @class */ (function (_super) {

@@ -45,4 +29,4 @@ __extends(ZodLazy, _super);

var _this = _super !== null && _super.apply(this, arguments) || this;
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
_this.toJSON = function () {

@@ -52,5 +36,2 @@ throw new Error("Can't JSONify recursive structure");

return _this;
// static recursion = <Rels extends { [k: string]: any }, T extends ZodObject<any>>(
// getter: () => T,
// ) => {};
}

@@ -61,3 +42,3 @@ Object.defineProperty(ZodLazy.prototype, "schema", {

},
enumerable: false,
enumerable: true,
configurable: true

@@ -74,3 +55,2 @@ });

exports.ZodLazy = ZodLazy;
// type
//# sourceMappingURL=lazy.js.map
import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
import { ZodUnion } from './union';
import { Primitive } from '../helpers/primitive';

@@ -11,6 +8,4 @@ export interface ZodLiteralDef<T extends any = any> extends z.ZodTypeDef {

export declare class ZodLiteral<T extends any> extends z.ZodType<T, ZodLiteralDef<T>> {
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
toJSON: () => ZodLiteralDef<T>;
static create: <T_1 extends Primitive>(value: T_1) => ZodLiteral<T_1>;
}

@@ -15,37 +15,20 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodLiteral = void 0;
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var union_1 = require("./union");
var ZodLiteral = /** @class */ (function (_super) {
__extends(ZodLiteral, _super);
function ZodLiteral() {
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
_this.toJSON = function () { return _this._def; };
return _this;
}
// static create = <U extends Primitive, T extends LiteralValue<U>>(value: T): ZodLiteral<T> => {
ZodLiteral.create = function (value) {

@@ -52,0 +35,0 @@ return new ZodLiteral({

import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodUnion } from './union';
export interface ZodNullDef extends z.ZodTypeDef {

@@ -8,6 +6,4 @@ t: z.ZodTypes.null;

export declare class ZodNull extends z.ZodType<null, ZodNullDef> {
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
toJSON: () => ZodNullDef;
static create: () => ZodNull;
}

@@ -15,32 +15,17 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodNull = void 0;
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");
var union_1 = require("./union");
var ZodNull = /** @class */ (function (_super) {
__extends(ZodNull, _super);
function ZodNull() {
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, ZodNull.create()]); };
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
_this.toJSON = function () { return _this._def; };

@@ -47,0 +32,0 @@ return _this;

import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
import { ZodUnion } from './union';
export interface ZodNumberDef extends z.ZodTypeDef {

@@ -9,13 +6,25 @@ t: z.ZodTypes.number;

export declare class ZodNumber extends z.ZodType<number, ZodNumberDef> {
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
toJSON: () => ZodNumberDef;
static create: () => ZodNumber;
min: (minimum: number, msg?: string | undefined) => this;
max: (maximum: number, msg?: string | undefined) => this;
int: (msg?: string | undefined) => this;
positive: (msg?: string | undefined) => this;
negative: (msg?: string | undefined) => this;
nonpositive: (msg?: string | undefined) => this;
nonnegative: (msg?: string | undefined) => this;
min: (minimum: number, message?: string | {
message?: string | undefined;
} | undefined) => this;
max: (maximum: number, message?: string | {
message?: string | undefined;
} | undefined) => this;
int: (message?: string | {
message?: string | undefined;
} | undefined) => this;
positive: (message?: string | {
message?: string | undefined;
} | undefined) => this;
negative: (message?: string | {
message?: string | undefined;
} | undefined) => this;
nonpositive: (message?: string | {
message?: string | undefined;
} | undefined) => this;
nonnegative: (message?: string | {
message?: string | undefined;
} | undefined) => this;
}

@@ -15,41 +15,55 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodNumber = void 0;
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var union_1 = require("./union");
// import { ZodUndefined } from './undefined';
// import { ZodNull } from './null';
// import { ZodUnion } from './union';
var ZodError_1 = require("../ZodError");
var errorUtil_1 = require("../helpers/errorUtil");
var ZodNumber = /** @class */ (function (_super) {
__extends(ZodNumber, _super);
function ZodNumber() {
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
_this.toJSON = function () { return _this._def; };
_this.min = function (minimum, msg) { return _this.refine(function (data) { return data >= minimum; }, msg || "Value must be >= " + minimum); };
_this.max = function (maximum, msg) { return _this.refine(function (data) { return data <= maximum; }, msg || "Value must be <= " + maximum); };
_this.int = function (msg) { return _this.refine(function (data) { return Number.isInteger(data); }, msg || 'Value must be an integer.'); };
_this.positive = function (msg) { return _this.refine(function (data) { return data > 0; }, msg || "Value must be positive"); };
_this.negative = function (msg) { return _this.refine(function (data) { return data < 0; }, msg || "Value must be negative"); };
_this.nonpositive = function (msg) { return _this.refine(function (data) { return data <= 0; }, msg || "Value must be non-positive"); };
_this.nonnegative = function (msg) { return _this.refine(function (data) { return data >= 0; }, msg || "Value must be non-negative"); };
_this.min = function (minimum, message) {
return _this.refinement(function (data) { return data >= minimum; }, __assign({ code: ZodError_1.ZodErrorCode.too_small, minimum: minimum, type: 'number', inclusive: true }, errorUtil_1.errorUtil.errToObj(message)));
};
_this.max = function (maximum, message) {
return _this.refinement(function (data) { return data <= maximum; }, __assign({ code: ZodError_1.ZodErrorCode.too_big, maximum: maximum, type: 'number', inclusive: true }, errorUtil_1.errorUtil.errToObj(message)));
};
_this.int = function (message) {
return _this.refinement(function (data) { return Number.isInteger(data); }, __assign({ code: ZodError_1.ZodErrorCode.invalid_type, expected: 'integer', received: 'number' }, errorUtil_1.errorUtil.errToObj(message)));
};
_this.positive = function (message) {
return _this.refinement(function (data) { return data > 0; }, __assign({ code: ZodError_1.ZodErrorCode.too_small, minimum: 0, type: 'number', inclusive: false }, errorUtil_1.errorUtil.errToObj(message)));
};
_this.negative = function (message) {
return _this.refinement(function (data) { return data < 0; }, __assign({ code: ZodError_1.ZodErrorCode.too_big, maximum: 0, type: 'number', inclusive: false }, errorUtil_1.errorUtil.errToObj(message)));
};
_this.nonpositive = function (message) {
return _this.refinement(function (data) { return data <= 0; }, __assign({ code: ZodError_1.ZodErrorCode.too_big, maximum: 0, type: 'number', inclusive: true }, errorUtil_1.errorUtil.errToObj(message)));
};
_this.nonnegative = function (message) {
return _this.refinement(function (data) { return data >= 0; }, __assign({ code: ZodError_1.ZodErrorCode.too_small, minimum: 0, type: 'number', inclusive: true }, errorUtil_1.errorUtil.errToObj(message)));
};
return _this;

@@ -56,0 +70,0 @@ }

import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
import { ZodUnion } from './union';
import { objectUtil } from '../helpers/objectUtil';
import { partialUtil } from '../helpers/partialUtil';
export interface ZodObjectDef<T extends z.ZodRawShape = z.ZodRawShape, Params extends ZodObjectParams = ZodObjectParams> extends z.ZodTypeDef {
declare type UnknownKeysParam = 'allow' | 'strict' | 'strip';
export interface ZodObjectDef<T extends z.ZodRawShape = z.ZodRawShape, UnknownKeys extends UnknownKeysParam = UnknownKeysParam, Catchall extends z.ZodTypeAny = z.ZodTypeAny> extends z.ZodTypeDef {
t: z.ZodTypes.object;
shape: () => T;
params: Params;
catchall: Catchall;
unknownKeys: UnknownKeys;
}
interface ZodObjectParams {
strict: boolean;
}
declare type SetKey<Target extends object, Key extends string, Value extends any> = objectUtil.Flatten<{
[k in Exclude<keyof Target, Key>]: Target[k];
} & {
[k in Key]: Value;
export declare type baseObjectOutputType<Shape extends z.ZodRawShape> = objectUtil.flatten<objectUtil.addQuestionMarks<{
[k in keyof Shape]: Shape[k]['_output'];
}>>;
export declare type objectOutputType<Shape extends z.ZodRawShape, Catchall extends z.ZodTypeAny> = z.ZodTypeAny extends Catchall ? baseObjectOutputType<Shape> : objectUtil.flatten<baseObjectOutputType<Shape> & {
[k: string]: Catchall['_output'];
}>;
declare type ZodObjectType<T extends z.ZodRawShape, Params extends ZodObjectParams> = Params['strict'] extends true ? objectUtil.ObjectType<T> : objectUtil.Flatten<objectUtil.ObjectType<T> & {
[k: string]: any;
export declare type baseObjectInputType<Shape extends z.ZodRawShape> = objectUtil.flatten<objectUtil.addQuestionMarks<{
[k in keyof Shape]: Shape[k]['_input'];
}>>;
export declare type objectInputType<Shape extends z.ZodRawShape, Catchall extends z.ZodTypeAny> = z.ZodTypeAny extends Catchall ? baseObjectInputType<Shape> : objectUtil.flatten<baseObjectInputType<Shape> & {
[k: string]: Catchall['_input'];
}>;
export declare class ZodObject<T extends z.ZodRawShape, Params extends ZodObjectParams = {
strict: true;
}, Type extends ZodObjectType<T, Params> = ZodObjectType<T, Params>> extends z.ZodType<Type, //ZodObjectType<T, Params>, // { [k in keyof T]: T[k]['_type'] },
ZodObjectDef<T, Params>> {
export declare type Scalars = string | string[] | number | number[] | boolean | boolean[] | bigint | bigint[] | undefined | null;
export declare type AnyZodObject = ZodObject<any, any, any>;
export declare class ZodObject<T extends z.ZodRawShape, UnknownKeys extends UnknownKeysParam = 'allow', Catchall extends z.ZodTypeAny = z.ZodTypeAny> extends z.ZodType<objectOutputType<T, Catchall>, ZodObjectDef<T, UnknownKeys, Catchall>, objectInputType<T, Catchall>> {
readonly _shape: T;
readonly _params: Params;
readonly _unknownKeys: UnknownKeys;
readonly _catchall: Catchall;
get shape(): T;
get params(): Params;
toJSON: () => {

@@ -37,11 +36,8 @@ t: z.ZodTypes.object;

};
nonstrict: () => ZodObject<T, objectUtil.Flatten<{ [k in Exclude<keyof Params, "strict">]: Params[k]; } & {
strict: false;
}>, Type & {
[k: string]: any;
}>;
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
augment: <Augmentation extends z.ZodRawShape>(augmentation: Augmentation) => ZodObject<{ [k in Exclude<keyof T, keyof Augmentation>]: T[k]; } & { [k_1 in keyof Augmentation]: Augmentation[k_1]; }, Params, ZodObjectType<{ [k in Exclude<keyof T, keyof Augmentation>]: T[k]; } & { [k_1 in keyof Augmentation]: Augmentation[k_1]; }, Params>>;
extend: <Augmentation extends z.ZodRawShape>(augmentation: Augmentation) => ZodObject<{ [k in Exclude<keyof T, keyof Augmentation>]: T[k]; } & { [k_1 in keyof Augmentation]: Augmentation[k_1]; }, Params, ZodObjectType<{ [k in Exclude<keyof T, keyof Augmentation>]: T[k]; } & { [k_1 in keyof Augmentation]: Augmentation[k_1]; }, Params>>;
strict: () => ZodObject<T, "strict", Catchall>;
stripUnknown: () => ZodObject<T, "strip", Catchall>;
allowUnknown: () => ZodObject<T, "allow", Catchall>;
nonstrict: () => ZodObject<T, "allow", Catchall>;
augment: <Augmentation extends z.ZodRawShape>(augmentation: Augmentation) => ZodObject<{ [k in Exclude<keyof T, keyof Augmentation>]: T[k]; } & { [k_1 in keyof Augmentation]: Augmentation[k_1]; }, UnknownKeys, Catchall>;
extend: <Augmentation extends z.ZodRawShape>(augmentation: Augmentation) => ZodObject<{ [k in Exclude<keyof T, keyof Augmentation>]: T[k]; } & { [k_1 in keyof Augmentation]: Augmentation[k_1]; }, UnknownKeys, Catchall>;
/**

@@ -52,14 +48,13 @@ * Prior to zod@1.0.12 there was a bug in the

*/
merge: <MergeShape extends z.ZodRawShape, MergeParams extends ZodObjectParams>(other: ZodObject<MergeShape, MergeParams>) => ZodObject<T & MergeShape, objectUtil.MergeObjectParams<Params, MergeParams>>;
pick: <Mask extends { [k in keyof T]?: true | undefined; }>(mask: Mask) => ZodObject<{ [k_1 in keyof Mask]: k_1 extends keyof T ? T[k_1] : never; }, Params, ZodObjectType<{ [k_1 in keyof Mask]: k_1 extends keyof T ? T[k_1] : never; }, Params>>;
omit: <Mask extends { [k in keyof T]?: true | undefined; }>(mask: Mask) => ZodObject<{ [k_1 in keyof T]: k_1 extends keyof Mask ? never : T[k_1]; }, Params, ZodObjectType<{ [k_1 in keyof T]: k_1 extends keyof Mask ? never : T[k_1]; }, Params>>;
partial: () => ZodObject<{ [k in keyof T]: ZodUnion<[T[k], ZodUndefined]>; }, Params, ZodObjectType<{ [k in keyof T]: ZodUnion<[T[k], ZodUndefined]>; }, Params>>;
deepPartial: () => partialUtil.RootDeepPartial<ZodObject<T>>;
static create: <T_1 extends z.ZodRawShape>(shape: T_1) => ZodObject<T_1, {
strict: true;
}, { [k_4 in keyof ({ [k_2 in { [k_1 in keyof { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }]: undefined extends { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }[k_1] ? k_1 : never; }[objectUtil.NoNeverKeys<T_1>]]?: { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }[k_2] | undefined; } & { [k_3 in Exclude<objectUtil.NoNeverKeys<T_1>, { [k_1 in keyof { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }]: undefined extends { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }[k_1] ? k_1 : never; }[objectUtil.NoNeverKeys<T_1>]>]: { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }[k_3]; })]: ({ [k_2 in { [k_1 in keyof { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }]: undefined extends { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }[k_1] ? k_1 : never; }[objectUtil.NoNeverKeys<T_1>]]?: { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }[k_2] | undefined; } & { [k_3 in Exclude<objectUtil.NoNeverKeys<T_1>, { [k_1 in keyof { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }]: undefined extends { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }[k_1] ? k_1 : never; }[objectUtil.NoNeverKeys<T_1>]>]: { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }[k_3]; })[k_4]; }>;
static lazycreate: <T_1 extends z.ZodRawShape>(shape: () => T_1) => ZodObject<T_1, {
strict: true;
}, { [k_4 in keyof ({ [k_2 in { [k_1 in keyof { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }]: undefined extends { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }[k_1] ? k_1 : never; }[objectUtil.NoNeverKeys<T_1>]]?: { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }[k_2] | undefined; } & { [k_3 in Exclude<objectUtil.NoNeverKeys<T_1>, { [k_1 in keyof { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }]: undefined extends { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }[k_1] ? k_1 : never; }[objectUtil.NoNeverKeys<T_1>]>]: { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }[k_3]; })]: ({ [k_2 in { [k_1 in keyof { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }]: undefined extends { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }[k_1] ? k_1 : never; }[objectUtil.NoNeverKeys<T_1>]]?: { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }[k_2] | undefined; } & { [k_3 in Exclude<objectUtil.NoNeverKeys<T_1>, { [k_1 in keyof { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }]: undefined extends { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }[k_1] ? k_1 : never; }[objectUtil.NoNeverKeys<T_1>]>]: { [k in keyof objectUtil.NoNever<T_1>]: objectUtil.NoNever<T_1>[k]["_type"]; }[k_3]; })[k_4]; }>;
merge: <Incoming extends AnyZodObject>(other: Incoming) => ZodObject<T & Incoming['_shape'], UnknownKeys, Catchall>;
catchall: <Index extends z.ZodTypeAny>(index: Index) => ZodObject<T, UnknownKeys, Index>;
pick: <Mask extends { [k in keyof T]?: true | undefined; }>(mask: Mask) => ZodObject<{ [k_3 in { [k_2 in keyof { [k_1 in keyof Mask]: k_1 extends keyof T ? T[k_1] : never; }]: [{ [k_1 in keyof Mask]: k_1 extends keyof T ? T[k_1] : never; }[k_2]] extends [never] ? never : k_2; }[keyof Mask]]: k_3 extends keyof Mask ? { [k_1 in keyof Mask]: k_1 extends keyof T ? T[k_1] : never; }[k_3] : never; }, UnknownKeys, Catchall>;
omit: <Mask extends { [k in keyof T]?: true | undefined; }>(mask: Mask) => ZodObject<{ [k_3 in { [k_2 in keyof { [k_1 in keyof T]: k_1 extends keyof Mask ? never : T[k_1]; }]: [{ [k_1 in keyof T]: k_1 extends keyof Mask ? never : T[k_1]; }[k_2]] extends [never] ? never : k_2; }[keyof T]]: k_3 extends keyof T ? { [k_1 in keyof T]: k_1 extends keyof Mask ? never : T[k_1]; }[k_3] : never; }, UnknownKeys, Catchall>;
partial: () => ZodObject<{ [k in keyof T]: ReturnType<T[k]["optional"]>; }, UnknownKeys, Catchall>;
primitives: () => ZodObject<{ [k_2 in { [k_1 in keyof { [k in keyof T]: [T[k]["_output"]] extends [Scalars] ? T[k] : never; }]: [{ [k in keyof T]: [T[k]["_output"]] extends [Scalars] ? T[k] : never; }[k_1]] extends [never] ? never : k_1; }[keyof T]]: k_2 extends keyof T ? { [k in keyof T]: [T[k]["_output"]] extends [Scalars] ? T[k] : never; }[k_2] : never; }, UnknownKeys, Catchall>;
nonprimitives: () => ZodObject<{ [k_2 in { [k_1 in keyof { [k in keyof T]: [T[k]["_output"]] extends [Scalars] ? never : T[k]; }]: [{ [k in keyof T]: [T[k]["_output"]] extends [Scalars] ? never : T[k]; }[k_1]] extends [never] ? never : k_1; }[keyof T]]: k_2 extends keyof T ? { [k in keyof T]: [T[k]["_output"]] extends [Scalars] ? never : T[k]; }[k_2] : never; }, UnknownKeys, Catchall>;
deepPartial: () => partialUtil.RootDeepPartial<this>;
static create: <T_1 extends z.ZodRawShape>(shape: T_1) => ZodObject<T_1, "allow", z.ZodTypeAny>;
static lazycreate: <T_1 extends z.ZodRawShape>(shape: () => T_1) => ZodObject<T_1, "allow", z.ZodTypeAny>;
}
export {};

@@ -26,37 +26,20 @@ "use strict";

};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodObject = void 0;
var z = __importStar(require("./base")); // change
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var union_1 = require("./union");
var z = __importStar(require("./base"));
// import { ZodUndefined } from './undefined';
// import { ZodNull } from './null';
// import { ZodUnion } from './union';
var objectUtil_1 = require("../helpers/objectUtil");
// import { ZodString } from './string';
// import { maskUtil } from '../helpers/maskUtil';
// import { zodmaskUtil } from '../helpers/zodmaskUtil';
// import { applyMask } from '../masker';
var isScalar_1 = require("../isScalar");
var __1 = require("..");
var AugmentFactory = function (def) { return function (augmentation) {
return new ZodObject(__assign(__assign({}, def), { shape: function () { return (__assign(__assign({}, def.shape()), augmentation)); } }));
}; };
// const infer = <T extends ZodObjectDef<any>>(def: T): T => def;
// const qewr = infer({ t: z.ZodTypes.object, shape: { asfd: ZodString.create() }, params: { strict: true } });
var objectDefToJson = function (def) { return ({

@@ -71,2 +54,7 @@ t: def.t,

}); };
// export type AnyZodObject = ZodObject<
// z.ZodRawShape,
// UnknownKeysParam,
// z.ZodTypeAny
// >;
var ZodObject = /** @class */ (function (_super) {

@@ -76,30 +64,23 @@ __extends(ZodObject, _super);

var _this = _super !== null && _super.apply(this, arguments) || this;
// get params() {
// return this._def.params;
// }
// get t() {
// return this;
// }
_this.toJSON = function () { return objectDefToJson(_this._def); };
_this.nonstrict = function () {
return new ZodObject({
shape: _this._def.shape,
// strict: false,
t: z.ZodTypes.object,
params: __assign(__assign({}, _this._params), { strict: false }),
});
_this.strict = function () {
return new ZodObject(__assign(__assign({}, _this._def), { unknownKeys: 'strict' }));
};
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
//
_this.stripUnknown = function () {
return new ZodObject(__assign(__assign({}, _this._def), { unknownKeys: 'strip' }));
};
_this.allowUnknown = function () {
return new ZodObject(__assign(__assign({}, _this._def), { unknownKeys: 'allow' }));
};
_this.nonstrict = _this.allowUnknown;
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
// nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
_this.augment = AugmentFactory(_this._def);
_this.extend = AugmentFactory(_this._def);
// augment = <Augmentation extends z.ZodRawShape>(
// augmentation: Augmentation,
// ): ZodObject<
// { [k in Exclude<keyof T, keyof Augmentation>]: T[k] } & { [k in keyof Augmentation]: Augmentation[k] },
// Params
// > => {
// return new ZodObject({
// ...this._def,
// shape: {
// ...this._def.shape,
// ...augmentation,
// },
// }) as any;
// };
/**

@@ -111,2 +92,5 @@ * Prior to zod@1.0.12 there was a bug in the

_this.merge = objectUtil_1.objectUtil.mergeObjects(_this);
_this.catchall = function (index) {
return new ZodObject(__assign(__assign({}, _this._def), { catchall: index }));
};
_this.pick = function (mask) {

@@ -119,7 +103,6 @@ var shape = {};

};
// omitKeys = <OmitKeys extends (keyof T)[]>(...omit:OmitKeys):OmitKeys => omit;
_this.omit = function (mask) {
var shape = {};
Object.keys(_this.shape).map(function (key) {
if (!Object.keys(mask).includes(key)) {
if (Object.keys(mask).indexOf(key) === -1) {
shape[key] = _this.shape[key];

@@ -133,16 +116,69 @@ }

for (var key in _this.shape) {
newShape[key] = _this.shape[key].optional();
var fieldSchema = _this.shape[key];
newShape[key] = fieldSchema.isOptional()
? fieldSchema
: fieldSchema.optional();
}
return new ZodObject(__assign(__assign({}, _this._def), { shape: function () { return newShape; } }));
};
// require: <This extends this>() => makeKeysRequired<This> = () => {
// const newShape: any = {};
// for (const key in this.shape) {
// const val = this.shape[key];
// console.log(`key ${key}:`);
// console.log(val);
// if (val instanceof ZodUnion) {
// console.log(`${key} is union!`);
// const options = (val as ZodUnion<any>)._def.options;
// if (options.length === 2) {
// console.log(`found ${options.length} options`);
// // .length === 2;
// if (options[0] instanceof ZodUndefined) {
// newShape[key] = options[1];
// } else if (options[1] instanceof ZodUndefined) {
// newShape[key] = options[0];
// }
// } else {
// newShape[key] = val;
// }
// } else {
// newShape[key] = val;
// }
// }
// return new ZodObject({
// ...this._def,
// shape: () => newShape,
// }) as any;
// };
_this.primitives = function () {
var newShape = {};
for (var key in _this.shape) {
if (isScalar_1.isScalar(_this.shape[key])) {
newShape[key] = _this.shape[key];
}
}
return new ZodObject(__assign(__assign({}, _this._def), { shape: function () { return newShape; } }));
};
_this.nonprimitives = function () {
var newShape = {};
for (var key in _this.shape) {
if (!isScalar_1.isScalar(_this.shape[key])) {
newShape[key] = _this.shape[key];
}
}
return new ZodObject(__assign(__assign({}, _this._def), { shape: function () { return newShape; } }));
};
_this.deepPartial = function () {
var newShape = {};
// const shape = this.shape;
for (var key in _this.shape) {
var fieldSchema = _this.shape[key];
if (fieldSchema instanceof ZodObject) {
newShape[key] = fieldSchema.deepPartial().optional();
newShape[key] = fieldSchema.isOptional()
? fieldSchema
: fieldSchema.deepPartial().optional();
}
else {
newShape[key] = _this.shape[key].optional();
newShape[key] = fieldSchema.isOptional()
? fieldSchema
: fieldSchema.optional();
}

@@ -158,55 +194,12 @@ }

},
enumerable: false,
enumerable: true,
configurable: true
});
Object.defineProperty(ZodObject.prototype, "params", {
get: function () {
return this._def.params;
},
enumerable: false,
configurable: true
});
// pick = <Mask extends zodmaskUtil.Params<ZodObject<T>>>(
// mask: Mask,
// ): zodmaskUtil.pick<ZodObject<T, Params>, Mask> => {
// return applyMask(this, mask, 'pick');
// };
// omit = <Mask extends zodmaskUtil.Params<ZodObject<T>>>(
// mask: Mask,
// ): zodmaskUtil.omit<ZodObject<T, Params>, Mask> => {
// return applyMask(this, mask, 'omit');
// };
// relations = <Rels extends { [k: string]: any }>(
// lazyShape: { [k in keyof Rels]: ZodLazy<z.ZodType<Rels[k]>> },
// ): RelationsReturnType<Rels, T> => {
// // const relationShape: any = {};
// // for (const key in lazyShape) {
// // relationShape[key] = lazyShape[key]();
// // }
// // console.log(relationShape);
// // const relationKeys = Object.keys(lazyShape);
// // const existingKeys = Object.keys(this._def.shape);
// return new ZodObject({
// t: z.ZodTypes.object,
// strict: this._def.strict,
// shape: {
// ...this._def.shape,
// ...lazyShape,
// },
// }) as any;
// };
// static recursion = <R extends { [k: string]: any }>() => <T extends ZodObject<any>>(
// shape: withRefsInputType<T, R>,
// ): ZodObject<withRefsReturnType<T, R>> => {
// // const getters =
// return new ZodObject({ t: z.ZodTypes.object, strict: true, shape(); });
// };
// keyof: ()=>ZodEnum<{[k in T]: k}>
ZodObject.create = function (shape) {
return new ZodObject({
t: z.ZodTypes.object,
// strict: true,
shape: function () { return shape; },
params: {
strict: true,
},
unknownKeys: 'allow',
catchall: __1.ZodNever.create(),
});

@@ -217,7 +210,5 @@ };

t: z.ZodTypes.object,
// strict: true,
shape: shape,
params: {
strict: true,
},
unknownKeys: 'allow',
catchall: __1.ZodNever.create(),
});

@@ -224,0 +215,0 @@ };

import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
import { ZodUnion } from './union';
export interface ZodPromiseDef<T extends z.ZodTypeAny = z.ZodTypeAny> extends z.ZodTypeDef {

@@ -9,3 +6,3 @@ t: z.ZodTypes.promise;

}
export declare class ZodPromise<T extends z.ZodTypeAny> extends z.ZodType<Promise<T['_type']>, ZodPromiseDef<T>> {
export declare class ZodPromise<T extends z.ZodTypeAny> extends z.ZodType<Promise<T['_output']>, ZodPromiseDef<T>, Promise<T['_input']>> {
toJSON: () => {

@@ -15,5 +12,3 @@ t: z.ZodTypes.promise;

};
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
static create: <T_1 extends z.ZodTypeAny>(schema: T_1) => ZodPromise<T_1>;
}

@@ -15,27 +15,11 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodPromise = void 0;
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var union_1 = require("./union");
var ZodPromise = /** @class */ (function (_super) {

@@ -51,6 +35,6 @@ __extends(ZodPromise, _super);

};
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
return _this;
}
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
ZodPromise.create = function (schema) {

@@ -57,0 +41,0 @@ return new ZodPromise({

import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
import { ZodUnion } from './union';
export interface ZodRecordDef<Value extends z.ZodTypeAny = z.ZodTypeAny> extends z.ZodTypeDef {

@@ -9,4 +6,4 @@ t: z.ZodTypes.record;

}
export declare class ZodRecord<Value extends z.ZodTypeAny = z.ZodTypeAny> extends z.ZodType<Record<string, Value['_type']>, // { [k in keyof T]: T[k]['_type'] },
ZodRecordDef<Value>> {
export declare class ZodRecord<Value extends z.ZodTypeAny = z.ZodTypeAny> extends z.ZodType<Record<string, Value['_output']>, // { [k in keyof T]: T[k]['_type'] },
ZodRecordDef<Value>, Record<string, Value['_input']>> {
readonly _value: Value;

@@ -17,5 +14,3 @@ toJSON: () => {

};
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
static create: <Value_1 extends z.ZodTypeAny = z.ZodTypeAny>(valueType: Value_1) => ZodRecord<Value_1>;
}

@@ -15,27 +15,11 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodRecord = void 0;
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var union_1 = require("./union");
var ZodRecord = /** @class */ (function (_super) {

@@ -49,6 +33,6 @@ __extends(ZodRecord, _super);

}); };
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
return _this;
}
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
ZodRecord.create = function (valueType) {

@@ -55,0 +39,0 @@ return new ZodRecord({

import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
import { ZodUnion } from './union';
import { StringValidation } from '../ZodError';
import { errorUtil } from '../helpers/errorUtil';
export interface ZodStringDef extends z.ZodTypeDef {

@@ -13,12 +12,31 @@ t: z.ZodTypes.string;

export declare class ZodString extends z.ZodType<string, ZodStringDef> {
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
inputSchema: this;
outputSchema: this;
toJSON: () => ZodStringDef;
min: (minLength: number, msg?: string | undefined) => this;
max: (maxLength: number, msg?: string | undefined) => this;
length: (len: number, msg?: string | undefined) => this;
email: (msg?: string | undefined) => this;
url: (msg?: string | undefined) => this;
nonempty: (msg?: string | undefined) => this;
min: (minLength: number, message?: string | {
message?: string | undefined;
} | undefined) => this;
max: (maxLength: number, message?: string | {
message?: string | undefined;
} | undefined) => this;
length(len: number, message?: errorUtil.ErrMessage): this;
protected _regex: (regex: RegExp, validation: StringValidation, message?: string | {
message?: string | undefined;
} | undefined) => this;
email: (message?: string | {
message?: string | undefined;
} | undefined) => this;
url: (message?: string | {
message?: string | undefined;
} | undefined) => this;
uuid: (message?: string | {
message?: string | undefined;
} | undefined) => this;
regex: (regexp: RegExp, message?: string | {
message?: string | undefined;
} | undefined) => this;
nonempty: (message?: string | {
message?: string | undefined;
} | undefined) => this;
static create: () => ZodString;
}

@@ -15,31 +15,29 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodString = void 0;
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var union_1 = require("./union");
// eslint-disable-next-line
// import { ZodUndefined } from './undefined';
// import { ZodNull } from './null';
// import { ZodUnion } from './union';
var ZodError_1 = require("../ZodError");
var errorUtil_1 = require("../helpers/errorUtil");
var emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
// eslint-disable-next-line
var urlRegex = /^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;
var uuidRegex = /([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}){1}/i;
var ZodString = /** @class */ (function (_super) {

@@ -49,32 +47,43 @@ __extends(ZodString, _super);

var _this = _super !== null && _super.apply(this, arguments) || this;
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
_this.inputSchema = _this;
_this.outputSchema = _this;
_this.toJSON = function () { return _this._def; };
_this.min = function (minLength, msg) {
return _this.refine(function (data) { return data.length >= minLength; }, msg || "Value must be " + minLength + " or more characters long");
_this.min = function (minLength, message) {
return _this.refinement(function (data) { return data.length >= minLength; }, __assign({ code: ZodError_1.ZodErrorCode.too_small, minimum: minLength, type: 'string', inclusive: true }, errorUtil_1.errorUtil.errToObj(message)));
};
_this.max = function (maxLength, msg) {
return _this.refine(function (data) { return data.length <= maxLength; }, msg || "Value must be " + maxLength + " or fewer characters long");
_this.max = function (maxLength, message) {
return _this.refinement(function (data) { return data.length <= maxLength; }, __assign({ code: ZodError_1.ZodErrorCode.too_big, maximum: maxLength, type: 'string', inclusive: true }, errorUtil_1.errorUtil.errToObj(message)));
};
_this.length = function (len, msg) {
return _this.refine(function (data) { return data.length == len; }, msg || "Value must be " + len + " characters long.");
_this._regex = function (regex, validation, message) {
return _this.refinement(function (data) { return regex.test(data); }, __assign({ validation: validation, code: ZodError_1.ZodErrorCode.invalid_string }, errorUtil_1.errorUtil.errToObj(message)));
};
_this.email = function (msg) { return _this.refine(function (data) { return emailRegex.test(data); }, msg || 'Invalid email address.'); };
_this.url = function (msg) { return _this.refine(function (data) { return urlRegex.test(data); }, msg || 'Invalid URL.'); };
_this.nonempty = function (msg) { return _this.refine(function (data) { return data.length > 0; }, msg || 'Value cannot be empty string'); };
_this.email = function (message) {
return _this._regex(emailRegex, 'email', message);
};
_this.url = function (message) {
return _this.refinement(function (data) {
try {
new URL(data);
return true;
}
catch (_a) {
return false;
}
}, __assign({ code: ZodError_1.ZodErrorCode.invalid_string, validation: 'url' }, errorUtil_1.errorUtil.errToObj(message)));
};
// url = (message?: errorUtil.ErrMessage) => this._regex(urlRegex, 'url', message);
_this.uuid = function (message) {
return _this._regex(uuidRegex, 'uuid', message);
};
_this.regex = function (regexp, message) {
return _this._regex(regexp, 'regex', message);
};
_this.nonempty = function (message) {
return _this.min(1, errorUtil_1.errorUtil.errToObj(message));
};
return _this;
}
// validate = <Val extends (arg:this['_type'])=>boolean>(check:Val)=>{
// const currChecks = this._def.validation.custom || [];
// return new ZodString({
// ...this._def,
// validation: {
// ...this._def.validation,
// custom: [...currChecks, check],
// },
// });
// }
// wrap: (value: this['_type'], params?: ParseParams) => ZodValue<this> = (value, params) => {
// return new ZodValue(this, this.parse(value, params));
// };
ZodString.prototype.length = function (len, message) {
return this.min(len, message).max(len, message);
};
ZodString.create = function () {

@@ -89,10 +98,2 @@ return new ZodString({

exports.ZodString = ZodString;
// export class ZodValue<S extends z.ZodType<any, any>> {
// value: S['_type'];
// schema: S;
// constructor(schema: S, value: S['_type']) {
// this.value = value;
// this.schema = schema;
// }
// }
//# sourceMappingURL=string.js.map
import * as z from './base';
import { ZodUnion } from './union';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
export declare type TypeOfTuple<T extends [z.ZodTypeAny, ...z.ZodTypeAny[]] | []> = {
[k in keyof T]: T[k] extends z.ZodType<infer U> ? U : never;
export declare type OutputTypeOfTuple<T extends [z.ZodTypeAny, ...z.ZodTypeAny[]] | []> = {
[k in keyof T]: T[k] extends z.ZodType<any, any> ? T[k]['_output'] : never;
};
export declare type InputTypeOfTuple<T extends [z.ZodTypeAny, ...z.ZodTypeAny[]] | []> = {
[k in keyof T]: T[k] extends z.ZodType<any, any> ? T[k]['_input'] : never;
};
export interface ZodTupleDef<T extends [z.ZodTypeAny, ...z.ZodTypeAny[]] | [] = [z.ZodTypeAny, ...z.ZodTypeAny[]]> extends z.ZodTypeDef {

@@ -12,3 +12,3 @@ t: z.ZodTypes.tuple;

}
export declare class ZodTuple<T extends [z.ZodTypeAny, ...z.ZodTypeAny[]] | [] = [z.ZodTypeAny, ...z.ZodTypeAny[]]> extends z.ZodType<TypeOfTuple<T>, ZodTupleDef<T>> {
export declare class ZodTuple<T extends [z.ZodTypeAny, ...z.ZodTypeAny[]] | [] = [z.ZodTypeAny, ...z.ZodTypeAny[]]> extends z.ZodType<OutputTypeOfTuple<T>, ZodTupleDef<T>, InputTypeOfTuple<T>> {
toJSON: () => {

@@ -18,5 +18,4 @@ t: z.ZodTypes.tuple;

};
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
get items(): T;
static create: <T_1 extends [] | [z.ZodTypeAny, ...z.ZodTypeAny[]]>(schemas: T_1) => ZodTuple<T_1>;
}

@@ -15,27 +15,11 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodTuple = void 0;
var z = __importStar(require("./base"));
var union_1 = require("./union");
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var ZodTuple = /** @class */ (function (_super) {

@@ -49,6 +33,13 @@ __extends(ZodTuple, _super);

}); };
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
return _this;
}
Object.defineProperty(ZodTuple.prototype, "items", {
get: function () {
return this._def.items;
},
enumerable: true,
configurable: true
});
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
ZodTuple.create = function (schemas) {

@@ -55,0 +46,0 @@ return new ZodTuple({

import * as z from './base';
import { ZodUnion } from './union';
import { ZodNull } from './null';
export interface ZodUndefinedDef extends z.ZodTypeDef {

@@ -9,5 +7,3 @@ t: z.ZodTypes.undefined;

toJSON: () => z.ZodTypeDef;
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
static create: () => ZodUndefined;
}

@@ -15,26 +15,11 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodUndefined = void 0;
var z = __importStar(require("./base"));
var union_1 = require("./union");
var null_1 = require("./null");
var ZodUndefined = /** @class */ (function (_super) {

@@ -45,6 +30,6 @@ __extends(ZodUndefined, _super);

_this.toJSON = function () { return _this._def; };
_this.optional = function () { return union_1.ZodUnion.create([_this, ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
return _this;
}
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
ZodUndefined.create = function () {

@@ -51,0 +36,0 @@ return new ZodUndefined({

import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
export interface ZodUnionDef<T extends [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]] = [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]> extends z.ZodTypeDef {

@@ -8,11 +6,6 @@ t: z.ZodTypes.union;

}
export declare class ZodUnion<T extends [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]> extends z.ZodType<T[number]['_type'], ZodUnionDef<T>> {
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
toJSON: () => {
t: z.ZodTypes.union;
options: object[];
};
export declare class ZodUnion<T extends [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]> extends z.ZodType<T[number]['_output'], ZodUnionDef<T>, T[number]['_input']> {
toJSON: () => object;
get options(): T;
static create: <T_1 extends [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]>(types: T_1) => ZodUnion<T_1>;
static make: <T_1 extends [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]>(...types: T_1) => ZodUnion<T_1>;
}

@@ -15,32 +15,17 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodUnion = void 0;
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var ZodUnion = /** @class */ (function (_super) {
__extends(ZodUnion, _super);
function ZodUnion() {
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.optional = function () { return ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return ZodUnion.create([_this, null_1.ZodNull.create()]); };
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
_this.toJSON = function () { return ({

@@ -52,2 +37,12 @@ t: _this._def.t,

}
Object.defineProperty(ZodUnion.prototype, "options", {
get: function () {
return this._def.options;
},
enumerable: true,
configurable: true
});
// distribute = <F extends (arg: T[number]) => z.ZodTypeAny>(f: F): ZodUnion<{ [k in keyof T]: ReturnType<F> }> => {
// return ZodUnion.create(this._def.options.map(f) as any);
// };
ZodUnion.create = function (types) {

@@ -59,12 +54,2 @@ return new ZodUnion({

};
ZodUnion.make = function () {
var types = [];
for (var _i = 0; _i < arguments.length; _i++) {
types[_i] = arguments[_i];
}
return new ZodUnion({
t: z.ZodTypes.union,
options: types,
});
};
return ZodUnion;

@@ -71,0 +56,0 @@ }(z.ZodType));

import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
import { ZodUnion } from './union';
export interface ZodUnknownDef extends z.ZodTypeDef {

@@ -9,6 +6,4 @@ t: z.ZodTypes.unknown;

export declare class ZodUnknown extends z.ZodType<unknown, ZodUnknownDef> {
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
toJSON: () => ZodUnknownDef;
static create: () => ZodUnknown;
}

@@ -15,27 +15,11 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodUnknown = void 0;
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var union_1 = require("./union");
var ZodUnknown = /** @class */ (function (_super) {

@@ -45,4 +29,4 @@ __extends(ZodUnknown, _super);

var _this = _super !== null && _super.apply(this, arguments) || this;
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
_this.toJSON = function () { return _this._def; };

@@ -49,0 +33,0 @@ return _this;

import * as z from './base';
import { ZodUndefined } from './undefined';
import { ZodNull } from './null';
import { ZodUnion } from './union';
export interface ZodVoidDef extends z.ZodTypeDef {

@@ -9,6 +6,4 @@ t: z.ZodTypes.void;

export declare class ZodVoid extends z.ZodType<void, ZodVoidDef> {
optional: () => ZodUnion<[this, ZodUndefined]>;
nullable: () => ZodUnion<[this, ZodNull]>;
toJSON: () => ZodVoidDef;
static create: () => ZodVoid;
}

@@ -15,27 +15,11 @@ "use strict";

})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodVoid = void 0;
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");
var null_1 = require("./null");
var union_1 = require("./union");
var ZodVoid = /** @class */ (function (_super) {

@@ -45,4 +29,4 @@ __extends(ZodVoid, _super);

var _this = _super !== null && _super.apply(this, arguments) || this;
_this.optional = function () { return union_1.ZodUnion.create([_this, undefined_1.ZodUndefined.create()]); };
_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
// null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
_this.toJSON = function () { return _this._def; };

@@ -49,0 +33,0 @@ return _this;

@@ -1,2 +0,2 @@

import { ParsedType } from './parser';
import { ZodParsedType } from './parser';
export declare const ZodErrorCode: {

@@ -7,4 +7,2 @@ invalid_type: "invalid_type";

invalid_union: "invalid_union";
invalid_array_length: "invalid_array_length";
array_empty: "array_empty";
invalid_literal_value: "invalid_literal_value";

@@ -16,2 +14,6 @@ invalid_enum_value: "invalid_enum_value";

invalid_date: "invalid_date";
invalid_string: "invalid_string";
too_small: "too_small";
too_big: "too_big";
invalid_intersection_types: "invalid_intersection_types";
};

@@ -21,44 +23,60 @@ export declare type ZodErrorCode = keyof typeof ZodErrorCode;

path: (string | number)[];
code: ZodErrorCode;
message?: string;
suberrors?: ZodError[];
};
interface InvalidTypeError extends ZodSuberrorBase {
export interface ZodInvalidTypeError extends ZodSuberrorBase {
code: typeof ZodErrorCode.invalid_type;
expected: ParsedType;
received: ParsedType;
expected: ZodParsedType;
received: ZodParsedType;
}
interface NonEmptyArrayIsEmptyError extends ZodSuberrorBase {
export interface ZodNonEmptyArrayIsEmptyError extends ZodSuberrorBase {
code: typeof ZodErrorCode.nonempty_array_is_empty;
}
interface UnrecognizedKeysError extends ZodSuberrorBase {
export interface ZodUnrecognizedKeysError extends ZodSuberrorBase {
code: typeof ZodErrorCode.unrecognized_keys;
keys: string[];
}
interface InvalidUnionError extends ZodSuberrorBase {
export interface ZodInvalidUnionError extends ZodSuberrorBase {
code: typeof ZodErrorCode.invalid_union;
unionErrors: ZodError[];
}
interface InvalidArrayLengthError extends ZodSuberrorBase {
code: typeof ZodErrorCode.invalid_array_length;
expected: number;
received: number;
}
interface InvalidLiteralValueError extends ZodSuberrorBase {
export interface ZodInvalidLiteralValueError extends ZodSuberrorBase {
code: typeof ZodErrorCode.invalid_literal_value;
expected: string | number | boolean;
}
interface InvalidEnumValueError extends ZodSuberrorBase {
export interface ZodInvalidEnumValueError extends ZodSuberrorBase {
code: typeof ZodErrorCode.invalid_enum_value;
options: string[];
options: (string | number)[];
}
interface InvalidArgumentsError extends ZodSuberrorBase {
export interface ZodInvalidArgumentsError extends ZodSuberrorBase {
code: typeof ZodErrorCode.invalid_arguments;
argumentsError: ZodError;
}
interface InvalidReturnTypeError extends ZodSuberrorBase {
export interface ZodInvalidReturnTypeError extends ZodSuberrorBase {
code: typeof ZodErrorCode.invalid_return_type;
returnTypeError: ZodError;
}
interface InvalidDateError extends ZodSuberrorBase {
export interface ZodInvalidDateError extends ZodSuberrorBase {
code: typeof ZodErrorCode.invalid_date;
}
interface CustomError extends ZodSuberrorBase {
export declare type StringValidation = 'email' | 'url' | 'uuid' | 'regex';
export interface ZodInvalidStringError extends ZodSuberrorBase {
code: typeof ZodErrorCode.invalid_string;
validation: StringValidation;
}
export interface ZodTooSmallError extends ZodSuberrorBase {
code: typeof ZodErrorCode.too_small;
minimum: number;
inclusive: boolean;
type: 'array' | 'string' | 'number';
}
export interface ZodTooBigError extends ZodSuberrorBase {
code: typeof ZodErrorCode.too_big;
maximum: number;
inclusive: boolean;
type: 'array' | 'string' | 'number';
}
export interface ZodInvalidIntersectionTypesError extends ZodSuberrorBase {
code: typeof ZodErrorCode.invalid_intersection_types;
}
export interface ZodCustomError extends ZodSuberrorBase {
code: typeof ZodErrorCode.custom_error;

@@ -69,6 +87,7 @@ params?: {

}
export declare type ZodSuberrorOptionalMessage = InvalidTypeError | NonEmptyArrayIsEmptyError | UnrecognizedKeysError | InvalidUnionError | InvalidArrayLengthError | InvalidLiteralValueError | InvalidEnumValueError | InvalidArgumentsError | InvalidReturnTypeError | InvalidDateError | CustomError;
export declare type ZodSuberrorOptionalMessage = ZodInvalidTypeError | ZodNonEmptyArrayIsEmptyError | ZodUnrecognizedKeysError | ZodInvalidUnionError | ZodInvalidLiteralValueError | ZodInvalidEnumValueError | ZodInvalidArgumentsError | ZodInvalidReturnTypeError | ZodInvalidDateError | ZodInvalidStringError | ZodTooSmallError | ZodTooBigError | ZodInvalidIntersectionTypesError | ZodCustomError;
export declare type ZodSuberror = ZodSuberrorOptionalMessage & {
message: string;
};
export declare const quotelessJson: (obj: any) => string;
export declare class ZodError extends Error {

@@ -82,3 +101,14 @@ errors: ZodSuberror[];

addErrors: (subs?: ZodSuberror[]) => void;
flatten: () => {
formErrors: string[];
fieldErrors: {
[k: string]: string[];
};
};
get formErrors(): {
formErrors: string[];
fieldErrors: {
[k: string]: string[];
};
};
}
export {};

@@ -23,3 +23,2 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodError = exports.ZodErrorCode = void 0;
var util_1 = require("./helpers/util");

@@ -31,4 +30,2 @@ exports.ZodErrorCode = util_1.util.arrayToEnum([

'invalid_union',
'invalid_array_length',
'array_empty',
'invalid_literal_value',

@@ -40,3 +37,11 @@ 'invalid_enum_value',

'invalid_date',
'invalid_string',
'too_small',
'too_big',
'invalid_intersection_types',
]);
exports.quotelessJson = function (obj) {
var json = JSON.stringify(obj, null, 2); // {"name":"John Smith"}
return json.replace(/"([^"]+)":/g, '$1:');
};
var ZodError = /** @class */ (function (_super) {

@@ -55,2 +60,17 @@ __extends(ZodError, _super);

};
_this.flatten = function () {
var fieldErrors = {};
var formErrors = [];
for (var _i = 0, _a = _this.errors; _i < _a.length; _i++) {
var sub = _a[_i];
if (sub.path.length > 0) {
fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
fieldErrors[sub.path[0]].push(sub.message);
}
else {
formErrors.push(sub.message);
}
}
return { formErrors: formErrors, fieldErrors: fieldErrors };
};
// restore prototype chain

@@ -64,10 +84,24 @@ var actualProto = _newTarget.prototype;

get: function () {
return this.errors
.map(function (_a) {
var path = _a.path, message = _a.message;
return path.length ? path.join('.') + ": " + message : "" + message;
})
.join('\n');
return JSON.stringify(this.errors, null, 2);
// const errorMessage: string[] = [
// `${this.errors.length} validation issue(s)`,
// '',
// ];
// for (const err of this.errors) {
// errorMessage.push(
// ` Issue #${this.errors.indexOf(err)}: ${err.code} at ${err.path.join(
// './index',
// )}`,
// );
// errorMessage.push(` ` + err.message);
// errorMessage.push('');
// }
// return errorMessage.join('\n');
// return quotelessJson(this);
// .map(({ path, message }) => {
// return path.length ? `${path.join('./index')}: ${message}` : `${message}`;
// })
// .join('\n');
},
enumerable: false,
enumerable: true,
configurable: true

@@ -79,8 +113,14 @@ });

},
enumerable: false,
enumerable: true,
configurable: true
});
Object.defineProperty(ZodError.prototype, "formErrors", {
get: function () {
return this.flatten();
},
enumerable: true,
configurable: true
});
ZodError.create = function (errors) {
var error = new ZodError(errors);
// error.errors = errors;
return error;

@@ -87,0 +127,0 @@ };

{
"name": "zod",
"version": "2.0.0-alpha.7",
"version": "2.0.0-beta.1",
"description": "TypeScript-first schema declaration and validation library with static type inference",

@@ -39,9 +39,10 @@ "main": "./lib/src/index.js",

"build": "yarn run clean && tsc --p tsconfig.package.json",
"buildall": "yarn add typescript@3.4 && yarn build && yarn add typescript@3.5 && yarn build && yarn add typescript@3.6 && yarn build && yarn add typescript@3.7 && yarn build && yarn add typescript@3.8 && yarn build && yarn add typescript@3.9 && yarn build && yarn add typescript@4 && yarn build && yarn add typescript@3.4",
"format": "prettier --write \"src/**/*.ts\" \"src/**/*.js\"",
"lint": "tslint -p tsconfig.json",
"test": "jest --config jestconfig.json --coverage && yarn run badge",
"testone": "jest --config jestconfig.json ",
"test": "jest --coverage && yarn run badge",
"testone": "jest",
"badge": "make-coverage-badge --output-path ./coverage.svg",
"prepublishOnly": "npm run build",
"play": "nodemon -e ts -w . -x ts-node src/playground.ts"
"play": "nodemon -e ts -w . -x ts-node src/playground.ts --project tsconfig.package.json"
},

@@ -57,4 +58,4 @@ "devDependencies": {

"tslint-config-prettier": "^1.18.0",
"typescript": "3.9"
"typescript": "3.7"
}
}

@@ -6,11 +6,11 @@ <p align="center">

<p align="center">
<a href="https://opensource.org/licenses/MIT" rel="nofollow"><img src="https://img.shields.io/github/license/vriad/zod" alt="License"></a>
<a href="https://www.npmjs.com/package/zod" rel="nofollow"><img src="https://img.shields.io/npm/dw/zod.svg" alt="npm"></a>
<a href="https://www.npmjs.com/package/zod" rel="nofollow"><img src="https://img.shields.io/github/stars/vriad/zod" alt="stars"></a>
<a href="./src/__tests__" rel="nofollow"><img src="./coverage.svg" alt="coverage"></a>
<a href="https://twitter.com/vriad" rel="nofollow"><img src="https://img.shields.io/badge/created%20by-@vriad-4BBAAB.svg" alt="Created by Colin McDonnell"></a>
<a href="https://opensource.org/licenses/MIT" rel="nofollow"><img src="https://img.shields.io/github/license/vriad/zod" alt="License"></a>
<a href="https://www.npmjs.com/package/zod" rel="nofollow"><img src="https://img.shields.io/npm/dw/zod.svg" alt="npm"></a>
<a href="https://www.npmjs.com/package/zod" rel="nofollow"><img src="https://img.shields.io/github/stars/vriad/zod" alt="stars"></a>
<a href="./src/__tests__" rel="nofollow"><img src="./coverage.svg" alt="coverage"></a>
</p>
<p align="center">
if you're happy and you know it, star this repo ⭐
<br/>
created by <a href="https://twitter.com/vriad" target="_blank">@vriad</a> πŸ‘‹
</p>

@@ -20,8 +20,85 @@

<!-- Created and maintained by [@vriad](https://twitter.com/vriad). The motivation for this library and a detailed comparison to various alternatives can be found at https://vriad.com/blog/zod.
<!-- **Zod 2 is coming! Follow [@vriad](https://twitter.com/vriad) to stay updated and discuss the future of Zod.** -->
If you find this package useful, leave a star to help more folks find it ⭐️🀏 -->
### **Sept 17 β€” Zod 2 is now in beta!**
<!-- <br/> -->
You should be able to upgrade from v1 to v2 without any breaking changes to your code. Zod 2 is recommended for all new projects.
```
npm install zod@beta
yarn add zod@beta
```
Here are some of the new features.
- Transformers! These let you provide default values, do casting/coersion, and a lot more. Read more here: [Transformers](#transformers)
- Asynchronous refinements and new `.parseAsync` and `.safeParseAsync` methods. Read more here: [Refinements](#refinements)
- New object methods: `.stripUnknown()`, `.strict()`, and `.catchall()`. Read more here: [Objects](#objects)
In almost all cases, you'll be able to upgrade to Zod 2 without changing any code. Here are some of the (very minor) breaking changes:
- Parsing now returns a _deep clone_ of the data you pass in. Previously it returned the exact same object you passed in.
- Relatedly, Zod _no longer_ supports cyclical _data_. Recursive schemas are still supported, but Zod can't properly parse nested objects that contain cycles.
- Object schemas now _allow_ unknown keys by default, instead of throwing an error
- Optional and nullable schemas are now represented with the dedicated ZodOptional and ZodNullable classes, instead of using ZodUnion.
---
Aug 30 β€”Β zod@1.11 was released with lots of cool features!
- All schemas now have a `.safeParse` method. This lets you validate data in a more functional way, similar to `io-ts`: https://github.com/vriad/zod#safe-parse
- String schemas have a new `.regex` refinement method: https://github.com/vriad/zod#strings
- Object schemas now have two new methods: `.primitives()` and `.nonprimitives()`. These methods let you quickly pick or omit primitive fields from objects, useful for validating API inputs: https://github.com/vriad/zod#primitives-and-nonprimitives
- Zod now provides `z.nativeEnum()`, which lets you create z Zod schema from an existing TypeScript `enum`: https://github.com/vriad/zod#native-enums
<!-- > ⚠️ You might be encountering issues building your project if you're using zod@<1.10.2. This is the result of a bug in the TypeScript compiler. To solve this without updating, set `"skipLibCheck": true` in your tsconfig.json "compilerOptions". This issue is resolved in zod@1.10.2 and later. -->
# What is Zod
Zod is a TypeScript-first schema declaration and validation library. I'm using the term "schema" to broadly refer to any data type/structure, from a simple `string` to a complex nested object.
Zod is designed to be as developer-friendly as possible. My goal is to eliminate duplicative type declarations wherever possible. With Zod, you declare a validator _once_ and Zod will automatically infer the static TypeScript type. It's easy to compose simpler types into complex data structures.
Some other great aspects:
- Zero dependencies
- Plain JavaScript: works in browsers and Node.js
- Tiny: 8kb minified + zipped
- Immutability: methods (i.e. `.optional()` return a new instance
- Concise, chainable interface
- Functional approach: [parse, don't validate](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/)
# Sponsorship
I work on Zod in my free time, so if you're making money from a product that is built with Zod, I'd massively appreciate sponsorship at any level. For solo devs, I recommend the [Chipotle Bowl tier](https://github.com/sponsors/vriad) or the [Cup of Coffee tier](https://github.com/sponsors/vriad).
### Sponsors
<table>
<tr>
<td align="center">
<a href="https://github.com/kevinsimper">
<img src="https://avatars1.githubusercontent.com/u/1126497?s=460&v=4" width="100px;" alt="" />
</a>
<br>
<b>Kevin Simper</b>
<br>
<a href="https://github.com/kevinsimper">@kevinsimper</a>
</td>
<td align="center">
<a href="https://twitter.com/flybayer">
<img src="https://avatars2.githubusercontent.com/u/8813276?s=460&u=4ff8beb9a67b173015c4b426a92d89cab960af1b&v=4" width="100px;" alt=""/>
</a>
<br>
<b>Brandon Bayer</b>
<br/>
<a href="https://twitter.com/flybayer">@flybayer</a>,
<span>creator of <a href="https://blitzjs.com">Blitz.js</a></span>
<br />
</td>
</tr>
</table>
_To get your name + Twitter + website here, sponsor Zod at the [Freelancer](https://github.com/sponsors/vriad) or [Consultancy](https://github.com/sponsors/vriad) tier._
# Table of contents

@@ -35,11 +112,14 @@

- [Type inference](#type-inference)
- [Custom validation](#custom-validation)
- [Refinements](#refinements)
- [Strings](#strings)
- [Numbers](#numbers)
- [Objects](#objects)
- [.nonstrict](#unknown-keys)
- [.shape](#shape-property)
- [.merge](#merging)
- [.extend](#extending)
- [.pick/.omit](#masking)
- [.extend](#extending-objects)
- [.pick/.omit](#pick-and-omit)
- [.partial/.deepPartial](#partials)
- [.stripUnknown](#strip-unknown-keys)
- [.strict](#disallow-unknown-keys)
- [.primitives/.nonprimitives](#primitives-and-nonprimitives)
- [Records](#records)

@@ -51,3 +131,3 @@ - [Arrays](#arrays)

- [.nullable](#nullable-types)
- [.enum](#enums)
- [Enums](#enums)
- [Intersections](#intersections)

@@ -59,3 +139,5 @@ - [Tuples](#tuples)

- [Promises](#promises)
- [Instanceof](#instanceof)
- [Function schemas](#function-schemas)
- [Transformers](#transformers)
- [Errors](#errors)

@@ -71,21 +153,39 @@ - [Comparison](#comparison)

To install the latest version:
To use the beta of Zod 2 (recommended for new projects).
```sh
npm install --save zod
```
yarn add zod@beta
npm install zod@beta
```
To install the most recent v1 version:
```sh
yarn add zod
npm install zod
```
#### TypeScript versions
#### TypeScript requirements
⚠ Zod 2.0.x requires TypeScript 4.0+
- Zod 2.x requires TypeScript 3.7+
- Zod 1.x requires TypeScript 3.3+
> You must use strict mode for Zod to correctly infer the types of your schemas! Add `"strict": true` inside "compilerOptions" in your `tsconfig.json`.
> Support for TS 3.2 was dropped with the release of zod@1.10 on 19 July 2020
You must enable `strictNullChecks` or use `strict` mode which includes `strictNullChecks`. Otherwise Zod can't correctly infer the types of your schemas!
```ts
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strictNullChecks": true
}
}
```
# Usage
Zod is a validation library designed for optimal developer experience. It's a TypeScript-first schema declaration library with rigorous (and correct!) inferred types, incredible developer experience, and a few killer features missing from the existing libraries.
Zod is a validation library designed for optimal developer experience. It's a TypeScript-first schema declaration library with rigorous inferred types, incredible developer experience, and a few killer features missing from the existing libraries.

@@ -121,2 +221,3 @@ <!-- - It infers the statically types of your schemas

z.null();
z.void();

@@ -142,8 +243,10 @@ // catch-all types

`.parse(data:unknown)`
`.parse(data:unknown): T`
Given any Zod schema, you can call its `.parse` method to check `data` is valid. If it is, a value is returned with full type information! Otherwise, an error is thrown.
> IMPORTANT: As of Zod 1.4, the value returned by `.parse` is _the same variable you passed in_. Previously it returned a deep clone. The only exception to this is `Promise` schemas, which return a new Promise for reasons explained in the documentation.
> IMPORTANT: In Zod 2 and Zod 1.11+, the value returned by `.parse` is a _deep clone_ of the variable you passed in. This was also the case in zod@1.4 and earlier.
<!-- The only exception to this is `Union` and `Intersection` schemas, which return the same value you pass in. -->
```ts

@@ -155,2 +258,40 @@ const stringSchema = z.string();

### Safe parse
`.safeParse(data:unknown): { success: true; data: T; } | { success: false; error: ZodError; }`
If you don't want Zod to throw when validation errors occur, you can use `.safeParse`. This method returns an object, even if validation errors occur:
```ts
stringSchema.safeParse(12);
// => { successs: false; error: ZodError }
stringSchema.safeParse('billie');
// => { successs: true; data: 'billie' }
```
There is also an asynchronous version:
```ts
await stringSchema.safeParseAsync('billie');
```
> You must use .parseAsync() or .safeParseAsync() if your schema contains asynchronous refinements for transformers.
The result is a _discriminated union_ so you can handle errors very conveniently:
```ts
const result = stringSchema.safeParse('billie');
if (!result.success) {
// handle error then return
return;
}
// underneath the if statement, TypeScript knows
// that validation passed
console.log(result.data);
```
> Errors thrown from within refinement functions will _not_ be caught.
### Type guards

@@ -186,25 +327,100 @@

To learn more about error handling with Zod, jump to [Errors](#errors).
### Refinements
### Custom validation
`.refine(validator: (data:T)=>any, params?: RefineParams)`
`.refine(validator: (data:T)=>any, err?: string)`
Zod let you provide custom validation logic via _refinements_.
Zod was designed to mirror TypeScript as closely as possible. But there are many so-called "refinement types" you may wish to check for that can't be represented in TypeScript's type system. For instance: checking that a number is an Int or that a string is a valid email address.
For this instances, you can define custom a validation check on _any_ Zod schema with `.refine`:
For example, you can define a custom validation check on _any_ Zod schema with `.refine`:
```ts
const myString = z.string().refine(val => val.length <= 255, "String can't be more than 255 characters");
const myString = z.string().refine(val => val.length <= 255, {
message: "String can't be more than 255 characters",
});
```
Here is the type signature for `.refine`:
Refinements can also be async:
```ts
const userId = z.string().refine(async id => {
// verify that ID exists in database
return true;
});
```
> If you use async refinements, you must use the `.parseAsync` method to parse data! Otherwise Zod will throw an error.
As you can see, `.refine` takes two arguments.
1. The first is the validation function. This function takes one input (of type `T` β€” the inferred type of the schema) and returns `any`. Any truthy value will pass validation. (Prior to zod@1.6.2 the validation function had to return a boolean.)
2. The second argument is a custom error message. Read more about error handling in Zod [here](#errors)
2. The second argument accepts some options. You can use this to customize certain error-handling behavior:
Check out [validator.js](https://github.com/validatorjs/validator.js) for a bunch of useful string validation functions.
```ts
type RefineParams = {
// override error message
message?: string;
// appended to error path
path?: (string | number)[];
// params object you can use to customize message
// in error map
params?: object;
};
```
These options let you define powerful custom behavior. Zod is commonly used for form validation. If you want to verify that "password" and "confirm" match, you can do so like this:
```ts
const passwordForm = z
.object({
password: z.string(),
confirm: z.string(),
})
.refine(data => data.password === data.confirm, {
message: "Passwords don't match",
path: ['confirm'], // path of error
})
.parse({ password: 'asdf', confirm: 'qwer' });
```
Because you provided a `path` parameter, the resulting error will be:
```ts
ZodError {
errors: [{
"code": "custom_error",
"path": [ "confirm" ],
"message": "Passwords don't match"
}]
}
```
Note that the `path` is set to `["confirm"]`, so you can easily display this error underneath the "Confirm password" textbox.
Important note, the value passed to the `path` option is _concatenated_ to the actual error path. So if you took `passwordForm` from above and nested it inside another object, you would still get the error path you expect.
```ts
const allForms = z.object({ passwordForm }).parse({
passwordForm: {
password: 'asdf',
confirm: 'qwer',
},
});
```
would result in
```
ZodError {
errors: [{
"code": "custom_error",
"path": [ "passwordForm", "confirm" ],
"message": "Passwords don't match"
}]
}
```
## Type inference

@@ -236,14 +452,19 @@

z.string().url();
z.string().uuid();
z.string().regex(regex);
```
> Check out [validator.js](https://github.com/validatorjs/validator.js) for a bunch of other useful string validation functions.
### Custom error messages
Like `.refine`, the final argument accepts a custom error message.
Like `.refine`, The final (optional) argument is an object that lets you provide a custom error in the `message` field.
```ts
z.string().min(5, 'Must be 5 or more characters long');
z.string().max(5, 'Must be 5 or fewer characters long');
z.string().length(5, 'Must be exactly 5 characters long');
z.string().email('Invalid email address.');
z.string().url('Invalid url');
z.string().min(5, { message: 'Must be 5 or more characters long' });
z.string().max(5, { message: 'Must be 5 or fewer characters long' });
z.string().length(5, { message: 'Must be exactly 5 characters long' });
z.string().email({ message: 'Invalid email address.' });
z.string().url({ message: 'Invalid url' });
z.string().uuid({ message: 'Invalid UUID' });
```

@@ -257,4 +478,2 @@

All of these validations allow you to _optionally_ specify a custom error message as a final `string` argument.
```ts

@@ -272,2 +491,8 @@ z.number().min(5);

You can optionally pass in a params object as the second argument to provide a custom error message.
```ts
z.number().max(5, { message: 'thisπŸ‘isπŸ‘tooπŸ‘big' });
```
## Objects

@@ -279,3 +504,3 @@

name: z.string(),
neutered: z.boolean(),
age: z.number(),
});

@@ -287,4 +512,4 @@

type Dog = {
name:string;
neutered: boolean;
name: string;
age: number;
}

@@ -295,3 +520,3 @@ */

name: 'Cujo',
neutered: true,
age: 4,
}); // passes, returns Dog

@@ -301,3 +526,3 @@

name: 'Fido',
}; // TypeError: missing required property `neutered`
}; // TypeError: missing required property `age`
```

@@ -330,3 +555,3 @@

const Teacher = BaseTeacher.merge(HasId);
const Teacher = BaseTeacher.merge(HasID);
type Teacher = z.infer<typeof Teacher>; // => { subjects: string[], id: string }

@@ -361,5 +586,5 @@ ```

#### Augmentation
#### Extending objects
You can augment an object schema with the `.extend` method.
You can add additional fields an object schema with the `.extend` method.

@@ -389,3 +614,3 @@ > Before zod@1.8 this method was called `.augment`. The `augment` method is still available for backwards compatibility but it is deprecated and will be removed in a future release.

#### Masking
#### Pick and omit

@@ -480,60 +705,116 @@ Object masking is one of Zod's killer features. It lets you create slight variations of your object schemas easily and succinctly. Inspired by TypeScript's built-in `Pick` and `Omit` utility types, all Zod object schemas have `.pick` and `.omit` methods that return a "masked" version of the schema.

> Important limitation: deep partials only work as expected in hierarchies of object schemas. It also can't be used on recursive schemas currently, since creating a recursive schema requires casting to the generic `ZodType` type (which doesn't include all the methods of the `ZodObject` class). Currently an improved version of Zod is under development that will have better support for recursive schemas.
> Important limitation: deep partials only work as expected in hierarchies of object schemas. It also can't be used on recursive schemas currently, since creating a recursive schema requires casting to the generic `ZodSchema` type (which doesn't include all the methods of the `ZodObject` class). Currently an improved version of Zod is under development that will have better support for recursive schemas.
#### Unknown keys
By default, Zod object schemas _do not_ allow unknown keys!
Zod object schemas allow unknown keys.
> ⚠️ Before Zod 2 object schema did NOT allow unknown keys by default.
Zod will return
```ts
const dogSchema = z.object({
const person = z.object({
name: z.string(),
neutered: z.boolean(),
});
dogSchema.parse({
name: 'Spot',
neutered: true,
color: 'brown',
}); // Error(`Unexpected keys in object: 'color'`)
person.parse({
name: 'bob dylan',
extraKey: 61,
});
// => { name: "bob dylan", extraKey: 61 }
```
This is an intentional decision to make Zod's behavior consistent with TypeScript. Consider this:
#### Strip unknown keys
If you want to strip out unknown keys, use `.stripUnknown`:
```ts
type Dog = z.infer<typeof dogSchema>;
const person = z
.object({
name: z.string(),
})
.stripUnknown();
const spot: Dog = {
name: 'Spot',
neutered: true,
color: 'brown',
};
// TypeError: Object literal may only specify known
// properties, and 'color' does not exist in type Dog
person.parse({
name: 'bob dylan',
extraKey: 61,
});
// => { name: "bob dylan" }
```
TypeScript doesn't allow unknown keys when assigning to an object type, so neither does Zod (by default). If you want to allow this, just call the `.nonstrict()` method on any object schema:
#### Disallow unknown keys
You can _disallow_ unknown keys with `.strict()`
```ts
const dogSchemaNonstrict = dogSchema.nonstrict();
const person = z
.object({
name: z.string(),
})
.strict();
dogSchemaNonstrict.parse({
name: 'Spot',
neutered: true,
color: 'brown',
}); // passes
person.parse({
name: 'bob dylan',
extraKey: 61,
});
// => throws ZodError
```
This change is reflected in the inferred type as well:
#### Primitives and nonprimitives
Zod provides a convenience method for automatically picking all primitive or non-primitive fields from an object schema.
```ts
type NonstrictDog = z.infer<typeof dogSchemaNonstrict>;
/*
{
name:string;
neutered: boolean;
[k:string]: any;
}
*/
const Post = z.object({
title: z.string()
});
const User = z.object({
id: z.number(),
name: z.string(),
posts: z.array(Post)
});
const UserFields = User.primitives();
typeof UserFields = z.infer<typeof UserFields>;
// => { id: number; name; string; }
const UserRelations = User.nonprimitives();
typeof UserFields = z.infer<typeof UserFields>;
// => { posts: Post[] }
```
These schemas are considering "primitive":
- string
- number
- boolean
- bigint
- date
- null/undefined
- enums
- any array of the above types
- any union of the above types
#### Catchall
You can add a `catchall` schema with `.catchall()`. All unknown keys will be validated against the catchall schema.
```ts
const person = z
.object({
name: z.string(),
})
.catchall(z.number());
person.parse({
name: 'bob dylan',
validExtraKey: 61, // works fine
});
// => { name: "bob dylan" }
```
> Using `.catchall()` overrides `.stripUnknown()` or `.strict()`. All keys are now considered "known".
## Records

@@ -624,15 +905,52 @@

There are two ways to define array schemas:
#### `z.array(arg: ZodSchema)`
First, you can create an array schema with the `z.array()` function; it accepts another ZodSchema, which defines the type of each array element.
```ts
const dogsList = z.array(dogSchema);
const stringArray = z.array(z.string());
// inferred type: string[]
```
dogsList.parse([{ name: 'Fido', age: 4, neutered: true }]); // passes
#### the `.array()` method
dogsList.parse([]); // passes
Second, you can call the `.array()` method on **any** Zod schema:
```ts
const stringArray = z.string().array();
// inferred type: string[]
```
You have to be careful with the `.array()` method. It returns a new `ZodArray` instance. This means you need to be careful about the _order_ in which you call methods. These two schemas are very different:
```ts
z.string()
.undefined()
.array(); // (string | undefined)[]
z.string()
.array()
.undefined(); // string[] | undefined
```
<!-- You can define arrays of **any** other Zod schema, no matter how complicated.
```ts
const dogsList = z.array(dogSchema);
dogsList.parse([{ name: 'Fido', age: 4, neutered: true }]); // passes
dogsList.parse([]); // passes
``` -->
#### Non-empty lists
```ts
const nonEmptyDogsList = z.array(dogSchema).nonempty();
nonEmptyDogsList.parse([]); // throws: "Array cannot be empty"
const nonEmptyStrings = z
.string()
.array()
.nonempty();
// [string, ...string[]]
nonEmptyStrings.parse([]); // throws: "Array cannot be empty"
nonEmptyStrings.parse(['Ariana Grande']); // passes
```

@@ -664,8 +982,22 @@

### Optional types
Zod will test the input against each of the "options" in order and return the first value that validates successfully.
Unions are the basis for defining optional schemas. An "optional string" is just the union of `string` and `undefined`.
<!-- ```ts
z.union([
z
.string()
.refine(val => val.length > 5)
.transform(val => val.toUpperCase()),
z.string().transform(val => val.toLowerCase()),
]).parse('AsDf'); // => "asdf"
``` -->
## Optional types
<!-- Unions are the basis for defining optional schemas. An "optional string" is just the union of `string` and `undefined`. -->
You can make any schema optional with `z.optional()`:
```ts
const A = z.union([z.string(), z.undefined()]);
const A = z.optional(z.string());

@@ -676,6 +1008,6 @@ A.parse(undefined); // => passes, returns undefined

Zod provides a shorthand way to make any schema optional:
You can also call the `.optional()` method on an existing schema:
```ts
const B = z.string().optional(); // equivalent to A
const B = z.boolean().optional();

@@ -688,3 +1020,3 @@ const C = z.object({

### Nullable types
## Nullable types

@@ -694,6 +1026,8 @@ Similarly, you can create nullable types like so:

```ts
const D = z.union([z.string(), z.null()]);
const D = z.nullable(z.string());
D.parse('asdf'); // => "asdf"
D.parse(null); // => null
```
Or you can use the shorthand `.nullable()`:
Or you can use the `.optional()` method on any existing schema:

@@ -707,3 +1041,3 @@ ```ts

```ts
<!-- ```ts
/* Custom Union Types */

@@ -724,10 +1058,18 @@

type F = z.infer<typeof F>; // string | number | boolean | undefined | null;
```
``` -->
### Enums
## Enums
An enum is just a union of string literals, so you can "build your own enum" like this:
There are two ways to define enums in Zod.
### Zod enums
An enum is just a union of string literals, so you _could_ define an enum like this:
```ts
const FishEnum = z.union([z.literal('Salmon'), z.literal('Tuna'), z.literal('Trout')]);
const FishEnum = z.union([
z.literal('Salmon'),
z.literal('Tuna'),
z.literal('Trout'),
]);

@@ -738,6 +1080,7 @@ FishEnum.parse('Salmon'); // => "Salmon"

But for convenience Zod provides a built-in `z.enum()` function, like so:
For convenience Zod provides a built-in `z.enum()` function. Here's is the equivalent code:
```ts
const FishEnum = z.enum(['Salmon', 'Tuna', 'Trout']);
type FishEnum = z.infer<typeof FishEnum>;

@@ -747,25 +1090,12 @@ // 'Salmon' | 'Tuna' | 'Trout'

> You need to either need to pass the literal array directly into z.enum:
>
> ```ts
> const FishEnum = z.enum(['Salmon', 'Tuna', 'Trout']);
> ```
>
> or use `as const` (introduced in TypeScript 3.4):
>
> ```ts
> const fishTypes = ['Salmon', 'Tuna', 'Trout'] as const;
> const FishEnum = z.enum(fishTypes);
> ```
>
> otherwise type inference won't work properly.
> Important! You need to pass the literal array _directly_ into z.enum(). Do not define it separately, than pass it in as a variable! This is required for proper type inference.
#### Autocompletion
**Autocompletion**
You can get autocompletion of enum values with the `.Values` property of an enum schema:
To get autocompletion with a Zod enum, use the `.enum` property of your schema:
```ts
FishEnum.Values.Salmon; // => autocompletes
FishEnum.enum.Salmon; // => autocompletes
FishEnum.Values;
FishEnum.enum;
/*

@@ -780,4 +1110,76 @@ => {

You can also retrieve the list of options as a tuple with the `.options` property:
```ts
FishEnum.options; // ["Salmon", "Tuna", "Trout"]);
```
### Native enums
> ⚠️ `nativeEnum()` requires TypeScript 3.6 or higher!
Zod enums are the recommended approach to defining and validating enums. But there may be scenarios where you need to validate against an enum from a third-party library, or perhaps you don't want to rewrite your existing enums. For this you can use `z.nativeEnum()`.
**Numeric enums**
```ts
enum Fruits {
Apple,
Banana,
}
const FruitEnum = z.nativeEnum(Fruits);
type FruitEnum = z.infer<typeof FruitEnum>; // Fruits
FruitEnum.parse(Fruits.Apple); // passes
FruitEnum.parse(Fruits.Banana); // passes
FruitEnum.parse(0); // passes
FruitEnum.parse(1); // passes
FruitEnum.parse(3); // fails
```
**String enums**
```ts
enum Fruits {
Apple = 'apple',
Banana = 'banana',
Cantaloupe, // you can mix numerical and string enums
}
const FruitEnum = z.nativeEnum(Fruits);
type FruitEnum = z.infer<typeof FruitEnum>; // Fruits
FruitEnum.parse(Fruits.Apple); // passes
FruitEnum.parse(Fruits.Cantaloupe); // passes
FruitEnum.parse('apple'); // passes
FruitEnum.parse('banana'); // passes
FruitEnum.parse(0); // passes
FruitEnum.parse('Cantaloupe'); // fails
```
**Const enums**
The `.nativeEnum()` function works for `as const` objects as well. ⚠️ `as const` required TypeScript 3.4+!
```ts
const Fruits = {
Apple: 'apple',
Banana: 'banana',
Cantaloupe: 3,
} as const;
const FruitEnum = z.nativeEnum(Fruits);
type FruitEnum = z.infer<typeof FruitEnum>; // "apple" | "banana" | 3
FruitEnum.parse('apple'); // passes
FruitEnum.parse('banana'); // passes
FruitEnum.parse(3); // passes
FruitEnum.parse('Cantaloupe'); // fails
```
## Intersections
<!-- > ⚠️ Intersections are deprecated. If you are trying to merge objects, use the `.merge` method instead. -->
Intersections are useful for creating "logical AND" types.

@@ -796,18 +1198,18 @@

This is particularly useful for defining "schema mixins" that you can apply to multiple schemas.
Intersections in Zod are not smart. Whatever data you pass into `.parse()` gets passed into the two intersected schemas. Because Zod object schemas don't allow any unknown keys by default, there are some unintuitive behavior surrounding intersections of object schemas.
```ts
const HasId = z.object({
id: z.string(),
````ts
const A = z.object({
a: z.string(),
});
const BaseTeacher = z.object({
name: z.string(),
const B = z.object({
b: z.string(),
});
const Teacher = z.intersection(BaseTeacher, HasId);
const AB = z.intersection(A, B);
type Teacher = z.infer<typeof Teacher>;
// { id:string; name:string };
```
``` -->

@@ -830,3 +1232,3 @@ ## Tuples

// type Athlete = [string, number, { pointsScored: number }]
```
````

@@ -843,3 +1245,3 @@ ## Recursive types

const Category: z.ZodType<Category> = z.lazy(() =>
const Category: z.ZodSchema<Category> = z.lazy(() =>
z.object({

@@ -881,3 +1283,3 @@ name: z.string(),

// a new Zod schema containing relations
const Category: z.ZodType<Category> = BaseCategory.merge(
const Category: z.ZodSchema<Category> = BaseCategory.merge(
z.object({

@@ -891,3 +1293,3 @@ subcategories: z.lazy(() => z.array(Category)),

There isn't a built-in method for validating any JSON, because representing that requires recursive type aliases (a feature that TypeScript started supporting with version 3.7). In order to support a wider range of TypeScript versions (see the top of the README for details) we aren't providing a JSON type out of the box at this time. If you want to validate JSON and you're using TypeScript 3.7+, you can use this snippet to achieve that:
If you want to validate any JSON value, you can use the snippet below. This requires TypeScript 3.7 or higher!

@@ -898,6 +1300,8 @@ ```ts

const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
const jsonSchema: z.ZodType<Json> = z.lazy(() => z.union([Literal, z.array(Json), z.record(Json)]));
const jsonSchema: z.ZodSchema<Json> = z.lazy(() =>
z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)]),
);
jsonSchema.parse({
// ...
// data
});

@@ -910,4 +1314,6 @@ ```

Validation still works as expected even when there are cycles in the data.
As of Zod 2, Zod _no longer_ supports cyclical objects. If you absolutely need this feature you can still use Zod v1.
<!-- Validation still works as expected even when there are cycles in the data.
```ts

@@ -925,8 +1331,6 @@ const cyclicalCategory: any = {

// => parsedCategory: Category;
```
``` -->
## Promises
As of zod@1.3, there is also support for Promise schemas!
```ts

@@ -961,2 +1365,19 @@ const numberPromise = z.promise(z.number());

## Instanceof
You can use `z.instanceof` to create a schema that checks if the input is an instance of a class.
```ts
class Test {
name: string;
}
const TestSchema = z.instanceof(Test);
const blob: any = 'whatever';
if (TestSchema.check(blob)) {
blob.name; // Test instance
}
```
## Function schemas

@@ -966,7 +1387,30 @@

You can create a function schema with `z.function(args, returnType)` which accepts these arguments.
You can create a function schema with `z.function(args, returnType)`.
```ts
const myFunction = z.function();
type myFunction = z.infer<typeof myFunction>;
// => ()=>unknown
```
You can use the `.args` and `.returns` methods to refine your function schema:
```ts
const myFunction = z
.function()
.args(z.string(), z.number()) // accepts an arbitrary number of arguments
.returns(z.boolean());
type myFunction = z.infer<typeof myFunction>;
// => (arg0: string, arg1: number)=>boolean
```
<!-- `z.function()` accepts two arguments:
- `args: ZodTuple` The first argument is a tuple (created with `z.tuple([...])` and defines the schema of the arguments to your function. If the function doesn't accept arguments, you can pass an empty tuple (`z.tuple([])`).
- `returnType: any Zod schema` The second argument is the function's return type. This can be any Zod schema.
- `returnType: any Zod schema` The second argument is the function's return type. This can be any Zod schema. -->
> You can use the special `z.void()` option if your function doesn't return anything. This will let Zod properly infer the type of void-returning functions. (Void-returning function can actually return either undefined or null.)
<!--
```ts

@@ -980,33 +1424,37 @@ const args = z.tuple([z.string()]);

// => (arg0: string)=>number
```
``` -->
Function schemas have an `.implement()` method which accepts a function as input and returns a new function.
Function schemas have an `.implement()` method which accepts a function and returns a new function.
```ts
const myValidatedFunction = myFunction.implement(x => {
// TypeScript knows x is a string!
return x.trim().length;
});
const trimmedLength = z
.function()
.args(z.string()) // accepts an arbitrary number of arguments
.returns(z.number())
.implement(x => {
// TypeScript knows x is a string!
return x.trim().length;
});
trimmedLength('sandwich'); // => 8
trimmedLength(' asdf '); // => 4
```
`myValidatedFunction` now automatically validates both its inputs and return value against the schemas provided to `z.function`. If either is invalid, the function throws.
`myValidatedFunction` now automatically validates both its inputs and return value against the schemas provided to `z.function`. If either is invalid, the function throws. This way you can confidently write application logic in a "validated function" without worrying about invalid inputs, scattering `schema.validate()` calls in your endpoint definitions,or writing duplicative types for your functions.
This way you can confidently write application logic in a "validated function" without worrying about invalid inputs, scattering `schema.validate()` calls in your endpoint definitions,or writing duplicative types for your functions.
Here's a more complex example showing how to write a typesafe API query endpoint:
```ts
const args = z.tuple([
z.object({ id: z.string() }), // get by ID
]);
const FetcherEndpoint = z
.function(args, returnType)
.args(z.object({ id: z.string() }))
.returns(
z.promise(
z.object({
id: string(),
name: string(),
}),
),
);
const returnType = z.promise(
z.object({
id: string(),
name: string(),
}),
);
const FetcherEndpoint = z.function(args, returnType);
const getUserByID = FetcherEndpoint.validate(args => {

@@ -1021,3 +1469,3 @@ args; // => { id: string }

return user; // success
return user; // compiles successfully
});

@@ -1112,67 +1560,111 @@ ```

## Errors
## Transformers
Zod includes a custom `Error` subclass called `ZodError`. All validation errors thrown by Zod are instances of `ZodError`.
You can integrate custom data transformations into your schemas with transformers. Transformers are just another type of Zod schema.
A `ZodError` instance has an `errors` property of type
### z.transformer()
```ts
// ZodError#errors
{
path: (string | number)[],
message: string
}[]
const countLength = z.transformer(
z.string(),
z.number(),
myString => myString.length,
);
countLength.parse('string'); // => 6
```
This array represents all errors Zod encounters when attempting to parse a value.
This lets you perform coercion, similar to Yup. You still need to provide the coercion logic yourself.
```ts
const person = z.object({
name: {
first: z.string(),
last: z.string(),
const coercedString = z.transformer(z.unknown(), z.string(), val => {
return `${val}`;
});
coercedString.parse(false); // => "false"
coercedString.parse(12); // => "12"
```
Transformations can also be async.
```ts
const IdToUser = z.transformer(
z.string().uuid(),
UserSchema,
userId => async id => {
return await getUserById(id);
},
age: z.number(),
address: z.array(z.string()),
);
```
> ⚠️ If your schema contains asynchronous transformers, you must use .parseAsync() or .safeParseAsync() to parse data. Otherwise Zod will throw an error.
### .transform()
For convenience, ALL Zod schemas (not just transformers) has a `.transform` method. The first argument lets you specify a "destination schema" which defines the type that the data should be transformed _into_.
```ts
const lengthChecker = z.string().transform(z.boolean(), val => {
return val.length > 5;
});
try {
person.parse({
name: { first: 'Dave', last: 42 },
age: 'threeve',
address: ['123 Maple Street', {}],
});
} catch (err) {
if (err instanceof ZodError) {
console.log(JSON.stringify(err.errors));
/*
[
{
"path": [ "name", "last" ],
"message": "Non-string type: number"
},
{
"path": [ "age" ],
"message": "Non-number type: string"
},
{
"path": [ "address", 1 ],
"message": "Non-string type: object"
}
]
*/
lengthChecker.parse('asdf'); // => false;
lengthChecker.parse('qwerty'); // => true;
```
// err.message returns a formatted error message
console.log(err.message);
/*
`name.last`: Non-string type: number
`age`: Non-number type: string
`address.1`: Non-string type: object
*/
} else {
// should never happen
}
}
You can omit the first argument, in which case Zod assumes you aren't transforming the data type:
```ts
z.string()
.transform(val => val.replace('pretty', 'extremely'))
.transform(val => val.toUpperCase())
.transform(val => val.split(' ').join('πŸ‘'))
.parse('zod 2 is pretty cool');
// => "ZODπŸ‘2πŸ‘ISπŸ‘EXTREMELYπŸ‘COOL"
```
### Default values
Using transformers, Zod lets you supply default values for your schemas.
```ts
const stringWithDefault = z.transformer(
z.string().optional(),
z.string(),
val => val || 'default value',
);
```
Equivalently you can express this using the built-in `.default()` method, available on all Zod schemas.
```ts
z.string().default('default value');
```
### Type inference for transformers
There are special rules surrounding type inference for transformers.
```ts
const stringToNumber = z.transformer(
z.string(),
z.number(),
myString => myString.length,
);
// z.infer<> gives the return type
type type = z.infer<stringToNumber>; // number
// it is equivalent to z.output<>
type out = z.output<stringToNumber>; // number
// you can use z.input<> to get the input type
type in = z.input<stringToNumber>; // string
```
## Errors
There is a dedicated guide on Zod's error handling system here: [ERROR_HANDLING.md](https://github.com/vriad/zod/blob/master/ERROR_HANDLING.md)
# Comparison

@@ -1220,2 +1712,11 @@

- Missing object methods: (pick, omit, partial, deepPartial, merge, extend)
- Missing nonempty arrays with proper typing (`[T, ...T[]]`)
- Missing lazy/recursive types
- Missing promise schemas
- Missing function schemas
- Missing union & intersection schemas
- Missing support for parsing cyclical data (maybe)
- Missing error customization
#### Joi

@@ -1225,3 +1726,3 @@

Doesn't support static type inference. Boo. πŸ˜•
Doesn't support static type inference πŸ˜•

@@ -1234,48 +1735,15 @@ #### Yup

Yup supports static type inference! But unfortunately the inferred types aren't actually correct.
Differences
##### Incorrect object typing (now fixed!)
- Supports for casting and transformation
- All object fields are optional by default
- Non-standard `.required()`ΒΉ
- Missing object methods: (pick, omit, partial, deepPartial, merge, extend)
- Missing nonempty arrays with proper typing (`[T, ...T[]]`)
- Missing promise schemas
- Missing function schemas
- Missing union & intersection schemas
This issue was fixed on May 19, 2020 ([here](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/44589)).
ΒΉ Yup has a strange interpretation of the word `required`. Instead of meaning "not undefined", Yup uses it to mean "not empty". So `yup.string().required()` will not accept an empty string, and `yup.array(yup.string()).required()` will not accept an empty array. For Zod arrays there is a dedicated `.nonempty()` method to indicate this, or you can implement it with a custom refinement.
<del>Currently, the yup package treats all object properties as optional by default:</del>.
```ts
const schema = yup.object({
asdf: yup.string(),
});
schema.validate({}); // passes
```
Yet the inferred type indicates that all properties are required:
```ts
type SchemaType = yup.InferType<typeof schema>;
// returns { asdf: string }
// should be { asdf?: string }
```
##### Unintuitive `.required()` behavior
In general, Yup's interpretation of `.required()` is odd and non-standard. Instead of meaning "not undefined", Yup uses it to mean "not empty". So `yup.string().required()` will not accept an empty string, and `yup.array(yup.string()).required()` will not accept an empty array. For Zod arrays there is a dedicated `.nonempty()` method to indicate this, or you can implement it with a custom validator.
```ts
const numList = yup
.array()
.of(yup.string())
.required();
// interpreted as a non-empty list
numList.validateSync([]); // fails
// yet the inferred type doesn't reflect this
type NumList = yup.InferType<typeof numList>;
// returns string[]
// should be [string,...string[]]
```
##### Unions and intersections
Finally, Yup doesn't support any generic `union` or `intersection` operator.
#### io-ts

@@ -1287,6 +1755,4 @@

In our experience, io-ts prioritizes functional programming purity over developer experience in many cases. This is a valid and admirable design goal, but it makes io-ts particularly hard to integrate into an existing codebase with a more procedural or object-oriented bias.
In our experience, io-ts prioritizes functional programming purity over developer experience in many cases. This is a valid and admirable design goal, but it makes io-ts particularly hard to integrate into an existing codebase with a more procedural or object-oriented bias. For instance, consider how to define an object with optional properties in io-ts:
For instance, consider how to define an object with optional properties in io-ts:
```ts

@@ -1325,4 +1791,16 @@ import * as t from 'io-ts';

`io-ts` also requires the use of gcanti's functional programming library `fp-ts` to parse results and handle errors. This is another fantastic resource for developers looking to keep their codebase strictly functional. But depending on `fp-ts` necessarily comes with a lot of intellectual overhead; a developer has to be familiar with functional programming concepts, `fp-ts`'s nomenclature, and the `Either` monad to do a simple schema validation. It's just not worth it for many people.
`io-ts` also requires the use of gcanti's functional programming library `fp-ts` to parse results and handle errors. This is another fantastic resource for developers looking to keep their codebase strictly functional. But depending on `fp-ts` necessarily comes with a lot of intellectual overhead; a developer has to be familiar with functional programming concepts and the `fp-ts` nomenclature to use the library.
- Supports codecs with serialization & deserialization transforms
- Supports branded types
- Supports advanced functional programming, higher-kinded types, `fp-ts` compatibility
- Missing object methods: (pick, omit, partial, deepPartial, merge, extend)
- Missing nonempty arrays with proper typing (`[T, ...T[]]`)
- Missing lazy/recursive types
- Missing promise schemas
- Missing function schemas
- Missing union & intersection schemas
- Missing support for parsing cyclical data (maybe)
- Missing error customization
#### Runtypes

@@ -1334,2 +1812,12 @@

- Supports "pattern matching": computed properties that distribute over unions
- Supports readonly types
- Missing object methods: (pick, omit, partial, deepPartial, merge, extend)
- Missing nonempty arrays with proper typing (`[T, ...T[]]`)
- Missing lazy/recursive types
- Missing promise schemas
- Missing union & intersection schemas
- Missing error customization
- Missing record schemas (their "record" is equivalent to Zod "object")
#### Ow

@@ -1339,3 +1827,3 @@

Ow is focused on function input validation. It's a library that makes it easy to express complicated assert statements, but it doesn't let you parse untyped data. They support a much wider variety of types; Zod has a nearly one-to-one mapping iwhtwith TypeScript's type system, whereas ow lets you validate several highly-specific types out of the box (e.g. `int32Array`, see full list in their README).
Ow is focused on function input validation. It's a library that makes it easy to express complicated assert statements, but it doesn't let you parse untyped data. They support a much wider variety of types; Zod has a nearly one-to-one mapping with TypeScript's type system, whereas ow lets you validate several highly-specific types out of the box (e.g. `int32Array`, see full list in their README).

@@ -1346,17 +1834,2 @@ If you want to validate function inputs, use function schemas in Zod! It's a much simpler approach that lets you reuse a function type declaration without repeating yourself (namely, copy-pasting a bunch of ow assertions at the beginning of every function). Also Zod lets you validate your return types as well, so you can be sure there won't be any unexpected data passed downstream.

| zod version | release notes |
| ----------- | ------------------------------------------------------------------------------------------------------------------- |
| zod@1.7 | Added several built-in validators to string, number, and array schemas. Calls to `.refine` now return new instance. |
| zod@1.5 | Any and unknown types |
| zod@1.4 | Refinement types (`.refine`), `.parse` no longer returns deep clone |
| zod@1.3 | Promise schemas |
| zod@1.2.6 | `.parse` accepts `unknown`, `bigint` schemas |
| zod@1.2.5 | `.partial` and `.deepPartial` on object schemas |
| zod@1.2.3 | Date schemas |
| zod@1.2.0 | `.pick`, `.omit`, and `.extend` on object schemas |
| zod@1.1.0 | Records |
| zod@1.0.11 | `.nonstrict` |
| zod@1.0.10 | Type assertions with `.check` |
| zod@1.0.4 | Empty tuples |
| zod@1.0.0 | Type assertions, literals, enums, detailed error reporting |
| zod@1.0.0 | Initial release |
View the changelog at [CHANGELOG.md](https://github.com/vriad/zod/blob/master/CHANGELOG.md)

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚑️ by Socket Inc