extends true
+ ? 'never'
+ : IsNever extends true
+ ? 'true'
+ : IsTrue
extends true
+ ? 'true'
+ : true extends IsObject
+ ? 'object'
+ : true extends IsObjectArray
+ ? 'array'
+ : 'any'];
+}
diff --git a/deno_lib/helpers/objectUtil.ts b/deno_lib/helpers/objectUtil.ts
new file mode 100644
index 000000000..c4252a70a
--- /dev/null
+++ b/deno_lib/helpers/objectUtil.ts
@@ -0,0 +1,130 @@
+import { ZodRawShape, ZodTypes } from '../types/base.ts';
+import { ZodIntersection } from '../types/intersection.ts';
+import { ZodObject, AnyZodObject } from '../types/object.ts';
+
+export 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 = {
+ [k in Exclude]: U[k];
+ } &
+ V;
+
+ type optionalKeys = {
+ [k in keyof T]: undefined extends T[k] ? k : never;
+ }[keyof T];
+
+ type requiredKeys = Exclude>;
+
+ export type addQuestionMarks = {
+ [k in optionalKeys]?: T[k];
+ } &
+ { [k in requiredKeys]: T[k] };
+
+ // type ObjectIntersection = addQuestionMarks<
+ // {
+ // [k in keyof T]: T[k]['_type'];
+ // }
+ // >;
+
+ export type identity = T;
+ export type flatten = identity<{ [k in keyof T]: T[k] }>;
+
+ export type NoNeverKeys = {
+ [k in keyof T]: [T[k]] extends [never] ? never : k;
+ }[keyof T];
+
+ export type NoNever = identity<
+ {
+ [k in NoNeverKeys]: k extends keyof T ? T[k] : never;
+ }
+ >;
+
+ // export type ObjectType = flatten<
+ // ObjectIntersection
+ // >;
+ // type ObjectIntersectionInput = addQuestionMarks<
+ // {
+ // [k in keyof T]: T[k]['_input'];
+ // }
+ // >;
+ // type ObjectIntersectionOutput = addQuestionMarks<
+ // {
+ // [k in keyof T]: T[k]['_output'];
+ // }
+ // >;
+
+ // export type objectInputType> = flatten<
+ // addQuestionMarks<
+ // {
+ // [k in keyof T['_shape']]: T['_shape'][k]['_input'];
+ // }
+ // >
+ // >;
+
+ // export type objectOutputType> = flatten<
+ // addQuestionMarks<
+ // {
+ // [k in keyof T['_shape']]: T['_shape'][k]['_output'];
+ // }
+ // >
+ // >;
+
+ export const mergeShapes = (
+ first: U,
+ second: T,
+ ): T & U => {
+ const firstKeys = Object.keys(first);
+ const secondKeys = Object.keys(second);
+ const sharedKeys = firstKeys.filter(k => secondKeys.indexOf(k) !== -1);
+
+ const sharedShape: any = {};
+ for (const k of sharedKeys) {
+ sharedShape[k] = ZodIntersection.create(first[k], second[k]);
+ }
+ return {
+ ...(first as object),
+ ...(second as object),
+ ...sharedShape,
+ };
+ };
+
+ export const mergeObjects = (first: First) => <
+ Second extends AnyZodObject
+ >(
+ second: Second,
+ ): ZodObject<
+ First['_shape'] & Second['_shape'],
+ First['_unknownKeys'],
+ First['_catchall']
+ // MergeObjectParams,
+ // First['_input'] & Second['_input'],
+ // First['_output'] & Second['_output']
+ > => {
+ const mergedShape = mergeShapes(first._def.shape(), second._def.shape());
+ const merged: any = new ZodObject({
+ t: ZodTypes.object,
+ checks: [...(first._def.checks || []), ...(second._def.checks || [])],
+ unknownKeys: first._def.unknownKeys,
+ catchall: first._def.catchall,
+ // params: {
+ // strict: first.params.strict && second.params.strict,
+ // },
+ shape: () => mergedShape,
+ }) as any;
+ return merged;
+ };
+}
diff --git a/deno_lib/helpers/partialUtil.ts b/deno_lib/helpers/partialUtil.ts
new file mode 100644
index 000000000..a0c1d5c02
--- /dev/null
+++ b/deno_lib/helpers/partialUtil.ts
@@ -0,0 +1,36 @@
+import * as z from '../index.ts';
+import { AnyZodObject } from '../types/object.ts';
+
+export namespace partialUtil {
+ export type RootDeepPartial = {
+ // optional: T extends z.ZodOptional ? T : z.ZodOptional;
+ // array: T extends z.ZodArray ? z.ZodArray> : never;
+ object: T extends AnyZodObject
+ ? z.ZodObject<
+ { [k in keyof T['_shape']]: DeepPartial },
+ T['_unknownKeys'],
+ T['_catchall']
+ >
+ : never;
+ rest: ReturnType; // z.ZodOptional;
+ }[T extends AnyZodObject
+ ? 'object' // T extends z.ZodOptional // ? 'optional' // :
+ : 'rest'];
+
+ export type DeepPartial = {
+ // optional: T extends z.ZodOptional ? T : z.ZodOptional;
+ // array: T extends z.ZodArray ? z.ZodArray> : never;
+ object: T extends z.ZodObject
+ ? z.ZodOptional<
+ z.ZodObject<
+ { [k in keyof Shape]: DeepPartial },
+ Params,
+ Catchall
+ >
+ >
+ : never;
+ rest: ReturnType;
+ }[T extends z.ZodObject
+ ? 'object' // T extends z.ZodOptional // ? 'optional' // :
+ : 'rest'];
+}
diff --git a/deno_lib/helpers/primitive.ts b/deno_lib/helpers/primitive.ts
new file mode 100644
index 000000000..3a0252f9a
--- /dev/null
+++ b/deno_lib/helpers/primitive.ts
@@ -0,0 +1,3 @@
+export type Primitive = string | number | bigint | boolean | null | undefined;
+
+export type Scalars = Primitive | Primitive[];
diff --git a/deno_lib/helpers/util.ts b/deno_lib/helpers/util.ts
new file mode 100644
index 000000000..f3e3af4ac
--- /dev/null
+++ b/deno_lib/helpers/util.ts
@@ -0,0 +1,60 @@
+export const INVALID = Symbol('invalid_data');
+export namespace util {
+ export type AssertEqual = T extends Expected
+ ? Expected extends T
+ ? true
+ : false
+ : false;
+
+ export function assertNever(_x: never): never {
+ throw new Error();
+ }
+
+ export type Omit = Pick>;
+ export type OmitKeys = Pick>;
+ export type MakePartial = Omit &
+ Partial>;
+
+ export const arrayToEnum = (
+ items: U,
+ ): { [k in U[number]]: k } => {
+ const obj: any = {};
+ for (const item of items) {
+ obj[item] = item;
+ }
+ return obj as any;
+ };
+
+ export const getValidEnumValues = (obj: any) => {
+ const validKeys = Object.keys(obj).filter(
+ (k: any) => typeof obj[obj[k]] !== 'number',
+ );
+ const filtered: any = {};
+ for (const k of validKeys) {
+ filtered[k] = obj[k];
+ }
+ return getValues(filtered);
+ };
+
+ export const getValues = (obj: any) => {
+ return Object.keys(obj).map(function(e) {
+ return obj[e];
+ });
+ };
+
+ export const objectValues = (obj: any) => {
+ return Object.keys(obj).map(function(e) {
+ return obj[e];
+ });
+ };
+
+ export const find = (
+ arr: T[],
+ checker: (arg: T) => any,
+ ): T | undefined => {
+ for (const item of arr) {
+ if (checker(item)) return item;
+ }
+ return undefined;
+ };
+}
diff --git a/deno_lib/index.ts b/deno_lib/index.ts
new file mode 100644
index 000000000..4a2fb38b8
--- /dev/null
+++ b/deno_lib/index.ts
@@ -0,0 +1,202 @@
+/* ZOD */
+
+import { ZodString, ZodStringDef } from './types/string.ts';
+import { ZodNumber, ZodNumberDef } from './types/number.ts';
+import { ZodBigInt, ZodBigIntDef } from './types/bigint.ts';
+import { ZodBoolean, ZodBooleanDef } from './types/boolean.ts';
+import { ZodDate, ZodDateDef } from './types/date.ts';
+import { ZodUndefined, ZodUndefinedDef } from './types/undefined.ts';
+import { ZodNull, ZodNullDef } from './types/null.ts';
+import { ZodAny, ZodAnyDef } from './types/any.ts';
+import { ZodUnknown, ZodUnknownDef } from './types/unknown.ts';
+import { ZodNever, ZodNeverDef } from './types/never.ts';
+import { ZodVoid, ZodVoidDef } from './types/void.ts';
+import { ZodArray, ZodArrayDef } from './types/array.ts';
+import { ZodObject, ZodObjectDef } from './types/object.ts';
+import { ZodUnion, ZodUnionDef } from './types/union.ts';
+import { ZodIntersection, ZodIntersectionDef } from './types/intersection.ts';
+import { ZodTuple, ZodTupleDef } from './types/tuple.ts';
+import { ZodRecord, ZodRecordDef } from './types/record.ts';
+import { ZodMap, ZodMapDef } from './types/map.ts';
+import { ZodFunction, ZodFunctionDef } from './types/function.ts';
+import { ZodLazy, ZodLazyDef } from './types/lazy.ts';
+import { ZodLiteral, ZodLiteralDef } from './types/literal.ts';
+import { ZodEnum, ZodEnumDef } from './types/enum.ts';
+import { ZodNativeEnum, ZodNativeEnumDef } from './types/nativeEnum.ts';
+import { ZodPromise, ZodPromiseDef } from './types/promise.ts';
+import { ZodTransformer, ZodTransformerDef } from './types/transformer.ts';
+import { ZodOptional, ZodOptionalDef } from './types/optional.ts';
+import { ZodNullable, ZodNullableDef } from './types/nullable.ts';
+import {
+ TypeOf,
+ input,
+ output,
+ ZodType,
+ ZodTypeAny,
+ ZodTypeDef,
+ ZodTypes,
+} from './types/base.ts';
+
+// export { ZodIssueCode } from './ZodError.ts';
+
+import { ZodParsedType } from './parser.ts';
+import { ZodErrorMap } from './defaultErrorMap.ts';
+import { ZodCodeGenerator } from './codegen.ts';
+
+export { ZodTypeDef, ZodTypes };
+type ZodDef =
+ | ZodStringDef
+ | ZodNumberDef
+ | ZodBigIntDef
+ | ZodBooleanDef
+ | ZodDateDef
+ | ZodUndefinedDef
+ | ZodNullDef
+ | ZodAnyDef
+ | ZodUnknownDef
+ | ZodNeverDef
+ | ZodVoidDef
+ | ZodArrayDef
+ | ZodObjectDef
+ | ZodUnionDef
+ | ZodIntersectionDef
+ | ZodTupleDef
+ | ZodRecordDef
+ | ZodMapDef
+ | ZodFunctionDef
+ | ZodLazyDef
+ | ZodLiteralDef
+ | ZodEnumDef
+ | ZodTransformerDef
+ | ZodNativeEnumDef
+ | ZodOptionalDef
+ | ZodNullableDef
+ | ZodPromiseDef;
+
+const stringType = ZodString.create;
+const numberType = ZodNumber.create;
+const bigIntType = ZodBigInt.create;
+const booleanType = ZodBoolean.create;
+const dateType = ZodDate.create;
+const undefinedType = ZodUndefined.create;
+const nullType = ZodNull.create;
+const anyType = ZodAny.create;
+const unknownType = ZodUnknown.create;
+const neverType = ZodNever.create;
+const voidType = ZodVoid.create;
+const arrayType = ZodArray.create;
+const objectType = ZodObject.create;
+const unionType = ZodUnion.create;
+const intersectionType = ZodIntersection.create;
+const tupleType = ZodTuple.create;
+const recordType = ZodRecord.create;
+const mapType = ZodMap.create;
+const functionType = ZodFunction.create;
+const lazyType = ZodLazy.create;
+const literalType = ZodLiteral.create;
+const enumType = ZodEnum.create;
+const nativeEnumType = ZodNativeEnum.create;
+const promiseType = ZodPromise.create;
+const transformerType = ZodTransformer.create;
+const optionalType = ZodOptional.create;
+const nullableType = ZodNullable.create;
+const ostring = () => stringType().optional();
+const onumber = () => numberType().optional();
+const oboolean = () => booleanType().optional();
+
+const codegen = ZodCodeGenerator.create;
+
+export const custom = (
+ check?: (data: unknown) => any,
+ params?: Parameters[1],
+): ZodType => {
+ if (check) return anyType().refine(check, params);
+ return anyType();
+};
+
+const instanceOfType = any>(
+ cls: T,
+ params: Parameters[1] = {
+ message: `Input not instance of ${cls.name}`,
+ },
+) => custom>(data => data instanceof cls, params);
+
+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,
+ mapType as map,
+ 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 const late = {
+ object: ZodObject.lazycreate,
+};
+
+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.ts';
diff --git a/deno_lib/isScalar.ts b/deno_lib/isScalar.ts
new file mode 100644
index 000000000..d545de29f
--- /dev/null
+++ b/deno_lib/isScalar.ts
@@ -0,0 +1,100 @@
+import * as z from './index.ts';
+import { util } from './helpers/util.ts';
+
+export const isScalar = (
+ schema: z.ZodType,
+ params: { root: boolean } = { root: true },
+): boolean => {
+ const def = schema._def as z.ZodDef;
+
+ let returnValue = false;
+ switch (def.t) {
+ case z.ZodTypes.string:
+ returnValue = true;
+ break;
+ case z.ZodTypes.number:
+ returnValue = true;
+ break;
+ case z.ZodTypes.bigint:
+ returnValue = true;
+ break;
+ case z.ZodTypes.boolean:
+ returnValue = true;
+ break;
+ case z.ZodTypes.undefined:
+ returnValue = true;
+ break;
+ case z.ZodTypes.null:
+ returnValue = true;
+ break;
+ case z.ZodTypes.any:
+ returnValue = false;
+ break;
+ case z.ZodTypes.unknown:
+ returnValue = false;
+ break;
+ case z.ZodTypes.never:
+ returnValue = false;
+ break;
+ case z.ZodTypes.void:
+ returnValue = false;
+ break;
+ case z.ZodTypes.array:
+ if (params.root === false) return false;
+ returnValue = isScalar(def.type, { root: false });
+ break;
+ case z.ZodTypes.object:
+ returnValue = false;
+ break;
+ case z.ZodTypes.union:
+ returnValue = def.options.every(x => isScalar(x));
+ break;
+ case z.ZodTypes.intersection:
+ returnValue = isScalar(def.left) && isScalar(def.right);
+ break;
+ case z.ZodTypes.tuple:
+ returnValue = def.items.every(x => isScalar(x, { root: false }));
+ break;
+ case z.ZodTypes.lazy:
+ returnValue = isScalar(def.getter());
+ break;
+ case z.ZodTypes.literal:
+ returnValue = true;
+ break;
+ case z.ZodTypes.enum:
+ returnValue = true;
+ break;
+ case z.ZodTypes.nativeEnum:
+ returnValue = true;
+ break;
+ case z.ZodTypes.function:
+ returnValue = false;
+ break;
+ case z.ZodTypes.record:
+ returnValue = false;
+ break;
+ case z.ZodTypes.map:
+ returnValue = false;
+ break;
+ case z.ZodTypes.date:
+ returnValue = true;
+ break;
+ case z.ZodTypes.promise:
+ returnValue = false;
+ break;
+ case z.ZodTypes.transformer:
+ returnValue = isScalar(def.output);
+ break;
+
+ case z.ZodTypes.optional:
+ returnValue = isScalar(def.innerType);
+ break;
+ case z.ZodTypes.nullable:
+ returnValue = isScalar(def.innerType);
+ break;
+ default:
+ util.assertNever(def);
+ // returnValue = false; break;
+ }
+ return returnValue;
+};
diff --git a/deno_lib/mod.ts b/deno_lib/mod.ts
new file mode 100644
index 000000000..a6d139036
--- /dev/null
+++ b/deno_lib/mod.ts
@@ -0,0 +1 @@
+export * from "./cjs/index.ts";
\ No newline at end of file
diff --git a/deno_lib/parser.ts b/deno_lib/parser.ts
new file mode 100644
index 000000000..7d3cfa020
--- /dev/null
+++ b/deno_lib/parser.ts
@@ -0,0 +1,1207 @@
+import * as z from './types/base.ts';
+import { ZodDef, ZodNever } from './index.ts';
+import {
+ ZodError,
+ ZodIssueCode,
+ ZodIssue,
+ ZodIssueOptionalMessage,
+} from './ZodError.ts';
+import { INVALID, util } from './helpers/util.ts';
+import { ZodErrorMap, defaultErrorMap } from './defaultErrorMap.ts';
+import { PseudoPromise } from './PseudoPromise.ts';
+
+export const getParsedType = (data: any): ZodParsedType => {
+ if (typeof data === 'string') return 'string';
+ if (typeof data === 'number') {
+ if (Number.isNaN(data)) return 'nan';
+ return 'number';
+ }
+ if (typeof data === 'boolean') return 'boolean';
+ if (typeof data === 'bigint') return 'bigint';
+ if (typeof data === 'symbol') return 'symbol';
+ if (data instanceof Date) return 'date';
+ if (typeof data === 'function') return 'function';
+ if (data === undefined) return 'undefined';
+ if (typeof data === 'undefined') return 'undefined';
+ if (typeof data === 'object') {
+ if (Array.isArray(data)) return 'array';
+ if (data === null) return 'null';
+ if (
+ data.then &&
+ typeof data.then === 'function' &&
+ data.catch &&
+ typeof data.catch === 'function'
+ ) {
+ return 'promise';
+ }
+ if (data instanceof Map) {
+ return 'map';
+ }
+ return 'object';
+ }
+ return 'unknown';
+};
+
+export const ZodParsedType = util.arrayToEnum([
+ 'string',
+ 'nan',
+ 'number',
+ 'integer',
+ 'boolean',
+ 'date',
+ 'bigint',
+ 'symbol',
+ 'function',
+ 'undefined',
+ 'null',
+ 'array',
+ 'object',
+ 'unknown',
+ 'promise',
+ 'void',
+ 'never',
+ 'map',
+]);
+
+export type ZodParsedType = keyof typeof ZodParsedType;
+
+// conditional required to distribute union
+type stripPath = T extends any
+ ? util.OmitKeys
+ : never;
+export type MakeErrorData = stripPath & {
+ path?: (string | number)[];
+};
+
+// export const INVALID = Symbol('invalid_data');
+
+// const NODATA = Symbol('no_data');
+
+export type ParseParams = {
+ seen?: {
+ schema: z.ZodType;
+ objects: { input: any; error?: ZodError; output: any }[];
+ }[];
+ path?: (string | number)[];
+ errorMap?: ZodErrorMap;
+ async?: boolean;
+ runAsyncValidationsInSeries?: boolean;
+};
+
+export const ZodParser = (schema: z.ZodType) => (
+ data: any,
+ baseParams: ParseParams = { seen: [], errorMap: defaultErrorMap, path: [] },
+) => {
+ const params: Required = {
+ seen: baseParams.seen || [],
+ path: baseParams.path || [],
+ errorMap: baseParams.errorMap || defaultErrorMap,
+ async: baseParams.async ?? false,
+ runAsyncValidationsInSeries:
+ baseParams.runAsyncValidationsInSeries ?? false,
+ };
+
+ const makeError = (errorData: MakeErrorData): ZodIssue => {
+ const errorArg = {
+ ...errorData,
+ path: [...params.path, ...(errorData.path || [])],
+ };
+ const ctxArg = { data };
+
+ const defaultError =
+ defaultErrorMap === params.errorMap
+ ? { message: `Invalid value.` }
+ : defaultErrorMap(errorArg, {
+ ...ctxArg,
+ defaultError: `Invalid value.`,
+ });
+ return {
+ ...errorData,
+ path: [...params.path, ...(errorData.path || [])],
+ message:
+ errorData.message ||
+ params.errorMap(errorArg, {
+ ...ctxArg,
+ defaultError: defaultError.message,
+ }).message,
+ };
+ };
+
+ const def: ZodDef = schema._def as any;
+
+ let PROMISE: PseudoPromise = new PseudoPromise();
+ (PROMISE as any)._default = true;
+
+ const RESULT: { input: any; output: any; error?: ZodError } = {
+ input: data,
+ output: INVALID,
+ };
+
+ 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) {
+
+ // 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 }] });
+ // }
+ // }
+
+ const ERROR = new ZodError([]);
+ const THROW = () => {
+ RESULT.error = ERROR;
+ throw ERROR;
+ };
+ const HANDLE = (err: Error) => {
+ if (err instanceof ZodError) {
+ ERROR.addIssues(err.issues);
+ }
+ throw err;
+ };
+ // const defaultPROMISE = Symbol('return_value');
+ // let returnValue: PseudoPromise; // = defaultReturnValue;
+ const parsedType = getParsedType(data);
+
+ // console.log(
+ // `\n============\nPARSING ${def.t.toUpperCase()} at ${params.path.join(
+ // '.',
+ // )}`,
+ // );
+ // console.log(JSON.stringify(data, null, 2));
+ switch (def.t) {
+ case z.ZodTypes.string:
+ if (parsedType !== ZodParsedType.string) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_type,
+ expected: ZodParsedType.string,
+ received: parsedType,
+ }),
+ );
+ // setError(error);
+ THROW();
+ }
+ PROMISE = PseudoPromise.resolve(data);
+
+ break;
+ case z.ZodTypes.number:
+ if (parsedType !== ZodParsedType.number) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_type,
+ expected: ZodParsedType.number,
+ received: parsedType,
+ }),
+ );
+ // setError(error);
+ THROW();
+ }
+ if (Number.isNaN(data)) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_type,
+ expected: ZodParsedType.number,
+ received: ZodParsedType.nan,
+ }),
+ );
+ // setError(error);
+ THROW();
+ }
+ PROMISE = PseudoPromise.resolve(data);
+ break;
+ case z.ZodTypes.bigint:
+ if (parsedType !== ZodParsedType.bigint) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_type,
+ expected: ZodParsedType.number,
+ received: parsedType,
+ }),
+ );
+ // setError(error);
+ THROW();
+ }
+ PROMISE = PseudoPromise.resolve(data);
+ break;
+ case z.ZodTypes.boolean:
+ if (parsedType !== ZodParsedType.boolean) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_type,
+ expected: ZodParsedType.boolean,
+ received: parsedType,
+ }),
+ );
+ // setError(error);
+ THROW();
+ }
+ PROMISE = PseudoPromise.resolve(data);
+ break;
+ case z.ZodTypes.undefined:
+ if (parsedType !== ZodParsedType.undefined) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_type,
+ expected: ZodParsedType.undefined,
+ received: parsedType,
+ }),
+ );
+ // setError(error);
+ THROW();
+ }
+ PROMISE = PseudoPromise.resolve(data);
+ break;
+ case z.ZodTypes.null:
+ if (parsedType !== ZodParsedType.null) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_type,
+ expected: ZodParsedType.null,
+ received: parsedType,
+ }),
+ );
+ // setError(error);
+ THROW();
+ }
+ PROMISE = PseudoPromise.resolve(data);
+ break;
+ case z.ZodTypes.any:
+ PROMISE = PseudoPromise.resolve(data);
+ break;
+ case z.ZodTypes.unknown:
+ PROMISE = PseudoPromise.resolve(data);
+ break;
+ case z.ZodTypes.never:
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_type,
+ expected: ZodParsedType.never,
+ received: parsedType,
+ }),
+ );
+ PROMISE = PseudoPromise.resolve(INVALID);
+ break;
+ case z.ZodTypes.void:
+ if (
+ parsedType !== ZodParsedType.undefined &&
+ parsedType !== ZodParsedType.null
+ ) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_type,
+ expected: ZodParsedType.void,
+ received: parsedType,
+ }),
+ );
+ // setError(error);
+ THROW();
+ }
+ PROMISE = PseudoPromise.resolve(data);
+ break;
+ case z.ZodTypes.array:
+ RESULT.output = [];
+ if (parsedType !== ZodParsedType.array) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_type,
+ expected: ZodParsedType.array,
+ received: parsedType,
+ }),
+ );
+ // setError(error);
+ THROW();
+ }
+ // const data: any[] = data;
+ if (def.nonempty === true && data.length === 0) {
+ ERROR.addIssue(
+ makeError({ code: ZodIssueCode.nonempty_array_is_empty }),
+ );
+ THROW();
+ }
+ // 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.addIssues(zerr.issues);
+ // }
+ // });
+ PROMISE = PseudoPromise.all(
+ (data as any[]).map((item, i) => {
+ try {
+ return PseudoPromise.resolve(
+ def.type.parse(item, {
+ ...params,
+ path: [...params.path, i],
+ }),
+ );
+ } catch (err) {
+ if (!(err instanceof ZodError)) {
+ throw err;
+ }
+ ERROR.addIssues(err.issues);
+ return PseudoPromise.resolve(INVALID);
+ }
+ }),
+ );
+ // if (!ERROR.isEmpty) {
+ // THROW();
+ // }
+ break;
+ case z.ZodTypes.map:
+ if (parsedType !== ZodParsedType.map) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_type,
+ expected: ZodParsedType.map,
+ received: parsedType,
+ }),
+ );
+ THROW();
+ }
+
+ const dataMap: Map = data;
+ const returnedMap = new Map();
+
+ PROMISE = PseudoPromise.all(
+ [...dataMap.entries()].map(([key, value], index) => {
+ return PseudoPromise.all([
+ new PseudoPromise()
+ .then(() => {
+ return def.keyType.parse(key, {
+ ...params,
+ path: [...params.path, index, 'key'],
+ });
+ })
+ .catch(err => {
+ if (!(err instanceof ZodError)) {
+ throw err;
+ }
+
+ ERROR.addIssues(err.issues);
+ return INVALID;
+ }),
+ new PseudoPromise()
+ .then(() => {
+ const mapValue = def.valueType.parse(value, {
+ ...params,
+ path: [...params.path, index, 'value'],
+ });
+ return [key, mapValue];
+ })
+ .catch(err => {
+ if (!(err instanceof ZodError)) {
+ throw err;
+ }
+
+ ERROR.addIssues(err.issues);
+ return INVALID;
+ }),
+ ])
+ .then((item: any) => {
+ try {
+ if (item[0] !== INVALID && item[1] !== INVALID) {
+ returnedMap.set(item[0], item[1]);
+ } else {
+ }
+ } catch (err) {}
+ })
+ .catch(err => {
+ if (!(err instanceof ZodError)) {
+ throw err;
+ }
+
+ ERROR.addIssues(err.issues);
+ return INVALID;
+ });
+ // const promises = [
+ // PseudoPromise.resolve(
+ // def.keyType.parse(key, {
+ // ...params,
+ // path: [...params.path, index, 'key'],
+ // }),
+ // ).catch(err => {
+ // if (!(err instanceof ZodError)) {
+ // throw err;
+ // }
+
+ // ERROR.addIssues(err.issues);
+ // return INVALID;
+ // }),
+ // PseudoPromise.resolve(
+ // def.valueType.parse(value, {
+ // ...params,
+ // path: [...params.path, index, 'value'],
+ // }),
+ // ).catch(err => {
+ // if (!(err instanceof ZodError)) {
+ // throw err;
+ // }
+
+ // ERROR.addIssues(err.issues);
+ // return INVALID;
+ // }),
+ // ];
+
+ // try {
+ // promises.push(
+ // PseudoPromise.resolve(
+ // def.keyType.parse(key, {
+ // ...params,
+ // path: [...params.path, index, 'key'],
+ // }),
+ // ),
+ // );
+ // } catch (err) {
+ // if (!(err instanceof ZodError)) {
+ // throw err;
+ // }
+
+ // ERROR.addIssues(err.issues);
+ // promises.push(PseudoPromise.resolve(INVALID));
+ // }
+
+ // try {
+ // promises.push(
+ // PseudoPromise.resolve(
+ // def.valueType.parse(value, {
+ // ...params,
+ // path: [...params.path, index, 'value'],
+ // }),
+ // ),
+ // );
+ // } catch (err) {
+ // if (err instanceof ZodError) {
+ // const zerr: ZodError = err;
+ // ERROR.addIssues(zerr.issues);
+ // promises.push(PseudoPromise.resolve(INVALID));
+ // } else {
+ // throw err;
+ // }
+ // }
+
+ // return PseudoPromise.all(promises).then(pairs =>{
+ // for(const [key,value] of pairs){}
+ // });
+ }),
+ )
+ .then(() => {
+ if (!ERROR.isEmpty) {
+ throw ERROR;
+ }
+ })
+ .then(() => {
+ return returnedMap;
+ })
+ .then(() => {
+ return returnedMap;
+ });
+ break;
+ case z.ZodTypes.object:
+ RESULT.output = {};
+ if (parsedType !== ZodParsedType.object) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_type,
+ expected: ZodParsedType.object,
+ received: parsedType,
+ }),
+ );
+ THROW();
+ }
+
+ const objectPromises: { [k: string]: PseudoPromise } = {};
+
+ const shape = def.shape();
+ const shapeKeys = Object.keys(shape);
+ const dataKeys = Object.keys(data);
+ const extraKeys = dataKeys.filter(k => shapeKeys.indexOf(k) === -1);
+
+ for (const key of shapeKeys) {
+ const keyValidator = shapeKeys.includes(key)
+ ? shape[key]
+ : !(def.catchall instanceof ZodNever)
+ ? def.catchall
+ : undefined;
+
+ if (!keyValidator) continue;
+
+ // check if schema and value are both optional
+
+ // const keyDataType = getParsedType(data[key]);
+ if (!Object.keys(data).includes(key)) {
+ try {
+ const output = keyValidator.parse(undefined, {
+ ...params,
+ path: [...params.path, key],
+ });
+ if (output === undefined) {
+ // schema is optional
+ // data is undefined
+ // don't explicity add undefined to outut
+ continue;
+ }
+ } catch (err) {}
+ }
+
+ objectPromises[key] = new PseudoPromise().then(() => {
+ try {
+ const parsedValue = keyValidator.parse(data[key], {
+ ...params,
+ path: [...params.path, key],
+ });
+ return parsedValue;
+ } catch (err) {
+ if (err instanceof ZodError) {
+ const zerr: ZodError = err;
+ ERROR.addIssues(zerr.issues);
+ return INVALID;
+ } else {
+ throw err;
+ }
+ }
+ });
+ }
+
+ if (def.catchall instanceof ZodNever) {
+ if (def.unknownKeys === 'passthrough') {
+ for (const key of extraKeys) {
+ objectPromises[key] = PseudoPromise.resolve(data[key]);
+ }
+ } else if (def.unknownKeys === 'strict') {
+ if (extraKeys.length > 0) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.unrecognized_keys,
+ keys: extraKeys,
+ }),
+ );
+ }
+ } else if (def.unknownKeys === 'strip') {
+ // do nothing
+ } else {
+ util.assertNever(def.unknownKeys);
+ }
+ } else {
+ // run cathcall validation
+ for (const key of extraKeys) {
+ objectPromises[key] = new PseudoPromise().then(() => {
+ try {
+ const parsedValue = def.catchall.parse(data[key], {
+ ...params,
+ path: [...params.path, key],
+ });
+ return parsedValue;
+ } catch (err) {
+ if (err instanceof ZodError) {
+ const zerr: ZodError = err;
+ ERROR.addIssues(zerr.issues);
+ return INVALID;
+ } else {
+ throw err;
+ }
+ }
+ });
+ }
+ }
+
+ PROMISE = PseudoPromise.object(objectPromises)
+ .then(resolvedObject => {
+ Object.assign(RESULT.output, resolvedObject);
+ return RESULT.output;
+ })
+ .catch(err => {
+ if (err instanceof ZodError) {
+ ERROR.addIssues(err.issues);
+ return INVALID;
+ }
+ throw err;
+ });
+
+ break;
+ case z.ZodTypes.union:
+ // let parsedUnion: any;
+ let isValid = false;
+ const unionErrors: ZodError[] = [];
+ // const INVALID = Symbol('invalid_data');
+ PROMISE = PseudoPromise.all(
+ def.options.map(opt => {
+ try {
+ const unionValueProm = PseudoPromise.resolve(
+ opt.parse(data, params),
+ );
+ isValid = true;
+ return unionValueProm;
+ // return parsed;
+ } catch (err) {
+ if (err instanceof ZodError) {
+ unionErrors.push(err);
+ return PseudoPromise.resolve(INVALID);
+ }
+ throw err;
+ }
+ // }
+ }),
+ )
+ .then((unionResults: any[]) => {
+ return util.find(unionResults, (val: any) => val !== INVALID);
+ })
+ .then((unionResult: any) => {
+ // const unionResults: any[] = _unionResults;
+ if (!isValid) {
+ const nonTypeErrors = unionErrors.filter(err => {
+ return err.issues[0].code !== 'invalid_type';
+ });
+ if (nonTypeErrors.length === 1) {
+ ERROR.addIssues(nonTypeErrors[0].issues);
+ } else {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_union,
+ unionErrors,
+ }),
+ );
+ }
+ 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.issues[0].code !== 'invalid_type';
+ // });
+ // if (filteredErrors.length === 1) {
+ // ERROR.addIssues(filteredErrors[0].issues);
+ // } else {
+ // ERROR.addIssue(
+ // makeError({
+ // code: ZodIssueCode.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.all([
+ new PseudoPromise().then(() => {
+ try {
+ return def.left.parse(data, params);
+ } catch (err) {
+ if (err instanceof ZodError) {
+ ERROR.addIssues(err.issues);
+ return INVALID;
+ }
+ throw err;
+ }
+ }),
+ new PseudoPromise().then(() => {
+ try {
+ return def.right.parse(data, params);
+ } catch (err) {
+ if (err instanceof ZodError) {
+ ERROR.addIssues(err.issues);
+ return INVALID;
+ }
+ throw err;
+ }
+ }),
+ ]).then(([parsedLeft, parsedRight]: any) => {
+ if (parsedLeft === INVALID || parsedRight === INVALID) return INVALID;
+
+ const parsedLeftType = getParsedType(parsedLeft);
+ const parsedRightType = getParsedType(parsedRight);
+
+ if (parsedLeft === parsedRight) {
+ return parsedLeft;
+ } else if (
+ parsedLeftType === ZodParsedType.object &&
+ parsedRightType === ZodParsedType.object
+ ) {
+ return { ...parsedLeft, ...parsedRight };
+ } else {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_intersection_types,
+ }),
+ );
+ }
+ });
+
+ break;
+
+ case z.ZodTypes.optional:
+ if (parsedType === ZodParsedType.undefined) {
+ PROMISE = PseudoPromise.resolve(undefined);
+ break;
+ }
+
+ PROMISE = new PseudoPromise().then(() => {
+ try {
+ return def.innerType.parse(data, params);
+ } catch (err) {
+ if (err instanceof ZodError) {
+ ERROR.addIssues(err.issues);
+ return INVALID;
+ }
+ throw err;
+ }
+ });
+ break;
+ case z.ZodTypes.nullable:
+ if (parsedType === ZodParsedType.null) {
+ PROMISE = PseudoPromise.resolve(null);
+ break;
+ }
+
+ PROMISE = new PseudoPromise().then(() => {
+ try {
+ return def.innerType.parse(data, params);
+ } catch (err) {
+ if (err instanceof ZodError) {
+ ERROR.addIssues(err.issues);
+ return INVALID;
+ }
+ throw err;
+ }
+ });
+ break;
+ case z.ZodTypes.tuple:
+ if (parsedType !== ZodParsedType.array) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_type,
+ expected: ZodParsedType.array,
+ received: parsedType,
+ }),
+ );
+ // setError(error);
+ THROW();
+ }
+ if (data.length > def.items.length) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.too_big,
+ maximum: def.items.length,
+ inclusive: true,
+ type: 'array',
+ }),
+ );
+ } else if (data.length < def.items.length) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.too_small,
+ minimum: def.items.length,
+ inclusive: true,
+ type: 'array',
+ }),
+ );
+ }
+
+ // const parsedTuple: any[] = [];
+ const tupleData: any[] = data;
+ // const parsedTuple: any = [];
+ // const tuplePromises: PseudoPromise[] = [];
+
+ PROMISE = PseudoPromise.all(
+ tupleData.map((item, index) => {
+ const itemParser = def.items[index];
+ return new PseudoPromise().then(() => {
+ try {
+ return itemParser.parse(item, {
+ ...params,
+ path: [...params.path, index],
+ });
+ } catch (err) {
+ if (err instanceof ZodError) {
+ ERROR.addIssues(err.issues);
+ 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.addIssues(err.issues);
+ // }
+ // }),
+ // );
+ // // parsedTuple.push(itemParser.parse(item, { ...params, path: [...params.path, index] }));
+ // }
+ // PROMISE = parsedTuple;
+ break;
+ case z.ZodTypes.lazy:
+ const lazySchema = def.getter();
+ PROMISE = PseudoPromise.resolve(lazySchema.parse(data, params));
+ break;
+ case z.ZodTypes.literal:
+ if (data !== def.value) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_literal_value,
+ expected: def.value,
+ }),
+ );
+ }
+ PROMISE = PseudoPromise.resolve(data);
+ break;
+ case z.ZodTypes.enum:
+ if (def.values.indexOf(data) === -1) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_enum_value,
+ options: def.values,
+ }),
+ );
+ }
+ PROMISE = PseudoPromise.resolve(data);
+ break;
+ case z.ZodTypes.nativeEnum:
+ if (util.getValidEnumValues(def.values).indexOf(data) === -1) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_enum_value,
+ options: util.objectValues(def.values),
+ }),
+ );
+ }
+ PROMISE = PseudoPromise.resolve(data);
+ break;
+ case z.ZodTypes.function:
+ if (parsedType !== ZodParsedType.function) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_type,
+ expected: ZodParsedType.function,
+ received: parsedType,
+ }),
+ );
+ // setError(error);
+ THROW();
+ }
+ const validatedFunc = (...args: any[]) => {
+ try {
+ def.args.parse(args as any, params);
+ } catch (err) {
+ if (err instanceof ZodError) {
+ const argsError = new ZodError([]);
+ argsError.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_arguments,
+ argumentsError: err,
+ }),
+ );
+ throw argsError;
+ }
+ throw err;
+ }
+
+ const result = data(...(args as any));
+
+ try {
+ return def.returns.parse(result, params);
+ } catch (err) {
+ if (err instanceof ZodError) {
+ const returnsError = new ZodError([]);
+ returnsError.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_return_type,
+ returnTypeError: err,
+ }),
+ );
+ throw returnsError;
+ }
+ throw err;
+ }
+ };
+ PROMISE = PseudoPromise.resolve(validatedFunc);
+ // return validatedFunc;
+ break;
+ case z.ZodTypes.record:
+ if (parsedType !== ZodParsedType.object) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_type,
+ expected: ZodParsedType.object,
+ received: parsedType,
+ }),
+ );
+ // setError(error);
+ THROW();
+ }
+
+ const parsedRecordPromises: { [k: string]: PseudoPromise } = {};
+ for (const key in data) {
+ parsedRecordPromises[key] = new PseudoPromise().then(() => {
+ try {
+ return def.valueType.parse(data[key], {
+ ...params,
+ path: [...params.path, key],
+ });
+ } catch (err) {
+ if (err instanceof ZodError) {
+ ERROR.addIssues(err.issues);
+ return INVALID;
+ }
+ throw err;
+ }
+ });
+ }
+ PROMISE = PseudoPromise.object(parsedRecordPromises);
+ // PROMISE = parsedRecord;
+ break;
+ case z.ZodTypes.date:
+ if (!(data instanceof Date)) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_type,
+ expected: ZodParsedType.date,
+ received: parsedType,
+ }),
+ );
+ // setError(error);
+ THROW();
+ }
+ if (isNaN(data.getTime())) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_date,
+ }),
+ );
+ // setError(error);
+ THROW();
+ }
+ PROMISE = PseudoPromise.resolve(data);
+ break;
+
+ case z.ZodTypes.promise:
+ if (parsedType !== ZodParsedType.promise && params.async !== true) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.invalid_type,
+ expected: ZodParsedType.promise,
+ received: parsedType,
+ }),
+ );
+ // setError(error);
+ THROW();
+ }
+
+ const promisified =
+ parsedType === ZodParsedType.promise ? data : Promise.resolve(data);
+
+ PROMISE = PseudoPromise.resolve(
+ promisified.then((resolvedData: any) => {
+ try {
+ const parsed = def.type.parse(resolvedData, params);
+ return parsed;
+ } catch (err) {
+ if (err instanceof ZodError) {
+ ERROR.addIssues(err.issues);
+ }
+ 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()
+ .then(() => {
+ return def.input.parse(data, params);
+ })
+ .catch(HANDLE)
+ .then(inputParseResult => {
+ // try {
+ // console.log(`TRANSFORMING`);
+ // console.log(JSON.stringify(inputParseResult, null, 2));
+ const 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.",
+ );
+ }
+ }
+
+ // console.log(`RESULT`);
+ // console.log(JSON.stringify(transformed, null, 2));
+ return transformed;
+ // } catch (err) {
+ // if (err instanceof ZodError) {
+ // ERROR.addIssues(err.issues);
+ // return INVALID;
+ // }
+ // throw err;
+ // }
+ })
+ .then(transformedResult => {
+ // try {
+ return def.output.parse(transformedResult, params);
+ // } catch (err) {
+ // if (err instanceof ZodError) {
+ // ERROR.addIssues(err.issues);
+ // return INVALID;
+ // }
+ // throw err;
+ // }
+ })
+ .catch(HANDLE);
+ break;
+ default:
+ PROMISE = PseudoPromise.resolve('adsf' as never);
+ util.assertNever(def);
+ }
+
+ if ((PROMISE as any)._default === true) {
+ throw new Error('Result is not materialized.');
+ }
+
+ if (!ERROR.isEmpty) {
+ THROW();
+ }
+
+ const customChecks = def.checks || [];
+
+ const checkCtx: z.RefinementCtx = {
+ addIssue: (arg: MakeErrorData) => {
+ ERROR.addIssue(makeError(arg));
+ },
+ path: params.path,
+ };
+ if (params.async === false) {
+ const 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 (const check of customChecks) {
+ const 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.addIssue(makeError(noMethodCheck));
+ // }
+ }
+ if (!ERROR.isEmpty) {
+ THROW();
+ }
+ // if (resolvedValue === INVALID) {
+ // throw new ZodError([]).addIssue(
+ // makeError({
+ // code: ZodIssueCode.custom,
+ // message: 'Invalid',
+ // }),
+ // );
+ // }
+ return resolvedValue as any;
+ } else {
+ // if (params.async == true) {
+ const checker = async () => {
+ let resolvedValue = await PROMISE.getValueAsync();
+
+ // if (resolvedValue !== INVALID) {
+ // // let someError: boolean = false;
+
+ // }
+ if (resolvedValue !== INVALID) {
+ if (params.runAsyncValidationsInSeries) {
+ let someError = false;
+ await customChecks.reduce((previousPromise, check) => {
+ return previousPromise.then(async () => {
+ if (!someError) {
+ const len = ERROR.issues.length;
+ await check.check(resolvedValue, checkCtx);
+ if (len < ERROR.issues.length) someError = true;
+ }
+ });
+ }, Promise.resolve());
+ } else {
+ await Promise.all(
+ customChecks.map(async check => {
+ await check.check(resolvedValue, checkCtx);
+ }),
+ );
+ }
+ } else {
+ if (ERROR.isEmpty) {
+ ERROR.addIssue(
+ makeError({
+ code: ZodIssueCode.custom,
+ message: 'Invalid',
+ }),
+ );
+ }
+ }
+
+ if (!ERROR.isEmpty) {
+ THROW();
+ }
+
+ return resolvedValue;
+ };
+
+ return checker();
+ }
+};
diff --git a/deno_lib/playground.ts b/deno_lib/playground.ts
new file mode 100644
index 000000000..e69de29bb
diff --git a/deno_lib/switcher.ts b/deno_lib/switcher.ts
new file mode 100644
index 000000000..1b5c62b88
--- /dev/null
+++ b/deno_lib/switcher.ts
@@ -0,0 +1,64 @@
+import * as z from './index.ts';
+import { util } from './helpers/util.ts';
+
+export const visitor = (schema: z.ZodType) => {
+ const def = schema._def as z.ZodDef;
+ switch (def.t) {
+ case z.ZodTypes.string:
+ break;
+ case z.ZodTypes.number:
+ break;
+ case z.ZodTypes.bigint:
+ break;
+ case z.ZodTypes.boolean:
+ break;
+ case z.ZodTypes.undefined:
+ break;
+ case z.ZodTypes.null:
+ break;
+ case z.ZodTypes.any:
+ break;
+ case z.ZodTypes.unknown:
+ break;
+ case z.ZodTypes.never:
+ break;
+ case z.ZodTypes.void:
+ break;
+ case z.ZodTypes.array:
+ break;
+ case z.ZodTypes.object:
+ break;
+ case z.ZodTypes.union:
+ break;
+ case z.ZodTypes.intersection:
+ break;
+ case z.ZodTypes.tuple:
+ break;
+ case z.ZodTypes.lazy:
+ break;
+ case z.ZodTypes.literal:
+ break;
+ case z.ZodTypes.enum:
+ break;
+ case z.ZodTypes.nativeEnum:
+ break;
+ case z.ZodTypes.function:
+ break;
+ case z.ZodTypes.record:
+ break;
+ case z.ZodTypes.date:
+ break;
+ case z.ZodTypes.promise:
+ break;
+ case z.ZodTypes.transformer:
+ break;
+ case z.ZodTypes.optional:
+ break;
+ case z.ZodTypes.nullable:
+ break;
+ case z.ZodTypes.map:
+ break;
+ default:
+ util.assertNever(def);
+ }
+};
diff --git a/deno_lib/types/any.ts b/deno_lib/types/any.ts
new file mode 100644
index 000000000..d35835588
--- /dev/null
+++ b/deno_lib/types/any.ts
@@ -0,0 +1,20 @@
+import * as z from './base.ts';
+// import { ZodUndefined } from './undefined.ts';
+// import { ZodNull } from './null.ts';
+// import { ZodUnion } from './union.ts';
+
+export interface ZodAnyDef extends z.ZodTypeDef {
+ t: z.ZodTypes.any;
+}
+
+export class ZodAny extends z.ZodType {
+ // opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
+ // null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
+ toJSON = () => this._def;
+
+ static create = (): ZodAny => {
+ return new ZodAny({
+ t: z.ZodTypes.any,
+ });
+ };
+}
diff --git a/deno_lib/types/array.ts b/deno_lib/types/array.ts
new file mode 100644
index 000000000..0534218e4
--- /dev/null
+++ b/deno_lib/types/array.ts
@@ -0,0 +1,108 @@
+import * as z from './base.ts';
+// import { ZodUndefined } from './undefined.ts';
+// import { ZodNull } from './null.ts';
+// import { ZodUnion } from './union.ts';
+import { ZodIssueCode } from '../ZodError.ts';
+
+export interface ZodArrayDef
+ extends z.ZodTypeDef {
+ t: z.ZodTypes.array;
+ type: T;
+ nonempty: boolean;
+}
+
+export class ZodArray extends z.ZodType<
+ T['_output'][],
+ ZodArrayDef,
+ T['_input'][]
+> {
+ toJSON = () => {
+ return {
+ t: this._def.t,
+ nonempty: this._def.nonempty,
+ type: this._def.type.toJSON(),
+ };
+ };
+
+ get element() {
+ return this._def.type;
+ }
+
+ // opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
+
+ // null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
+
+ min = (minLength: number, message?: string | { message?: string }) =>
+ this.refinement(data => data.length >= minLength, {
+ code: ZodIssueCode.too_small,
+ type: 'array',
+ inclusive: true,
+ minimum: minLength,
+ ...(typeof message === 'string' ? { message } : message),
+ });
+
+ max = (maxLength: number, message?: string | { message?: string }) =>
+ this.refinement(data => data.length <= maxLength, {
+ // check: data => data.length <= maxLength,
+ code: ZodIssueCode.too_big,
+ type: 'array',
+ inclusive: true,
+ maximum: maxLength,
+ ...(typeof message === 'string' ? { message } : message),
+ });
+
+ length = (len: number, message?: string) =>
+ this.min(len, { message }).max(len, { message });
+
+ nonempty: () => ZodNonEmptyArray = () => {
+ return new ZodNonEmptyArray({ ...this._def, nonempty: true });
+ };
+
+ static create = (schema: T): ZodArray => {
+ return new ZodArray({
+ t: z.ZodTypes.array,
+ type: schema,
+ nonempty: false,
+ });
+ };
+}
+
+export class ZodNonEmptyArray extends z.ZodType<
+ [T['_output'], ...T['_output'][]],
+ ZodArrayDef,
+ [T['_input'], ...T['_input'][]]
+> {
+ toJSON = () => {
+ return {
+ t: this._def.t,
+ type: this._def.type.toJSON(),
+ };
+ };
+
+ // opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
+
+ // null nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
+
+ min = (minLength: number, message?: string | { message?: string }) =>
+ this.refinement(data => data.length >= minLength, {
+ // check: data => data.length >= minLength,
+ code: ZodIssueCode.too_small,
+ minimum: minLength,
+ type: 'array',
+ inclusive: true,
+ ...(typeof message === 'string' ? { message } : message),
+ });
+
+ max = (maxLength: number, message?: string | { message?: string }) =>
+ this.refinement(data => data.length <= maxLength, {
+ // check:
+ code: ZodIssueCode.too_big,
+ maximum: maxLength,
+ type: 'array',
+ inclusive: true,
+ ...(typeof message === 'string' ? { message } : message),
+ });
+
+ length = (len: number, message?: string) =>
+ this.min(len, { message }).max(len, { message });
+}
diff --git a/deno_lib/types/base.ts b/deno_lib/types/base.ts
new file mode 100644
index 000000000..a5645986d
--- /dev/null
+++ b/deno_lib/types/base.ts
@@ -0,0 +1,364 @@
+import {
+ ZodIssueCode,
+ ZodArray,
+ ZodTransformer,
+ ZodError,
+ ZodOptional,
+ ZodNullable,
+} from '../index.ts';
+import { ZodParser, ParseParams, MakeErrorData } from '../parser.ts';
+import { ZodOptionalType } from './optional.ts';
+import { ZodNullableType } from './nullable.ts';
+import { ZodCustomIssue } from '../ZodError.ts';
+import { util } from '../helpers/util.ts';
+
+export enum ZodTypes {
+ string = 'string',
+ number = 'number',
+ bigint = 'bigint',
+ boolean = 'boolean',
+ date = 'date',
+ undefined = 'undefined',
+ null = 'null',
+ array = 'array',
+ object = 'object',
+ union = 'union',
+ intersection = 'intersection',
+ tuple = 'tuple',
+ record = 'record',
+ map = 'map',
+ function = 'function',
+ lazy = 'lazy',
+ literal = 'literal',
+ enum = 'enum',
+ nativeEnum = 'nativeEnum',
+ promise = 'promise',
+ any = 'any',
+ unknown = 'unknown',
+ never = 'never',
+ void = 'void',
+ transformer = 'transformer',
+ optional = 'optional',
+ nullable = 'nullable',
+}
+
+export type ZodTypeAny = ZodType;
+export type ZodRawShape = { [k: string]: ZodTypeAny };
+
+export const inputSchema = (schema: ZodType): ZodType => {
+ if (schema instanceof ZodTransformer) {
+ return inputSchema(schema._def.input);
+ } else {
+ return schema;
+ }
+};
+
+export const outputSchema = (schema: ZodType): ZodType => {
+ if (schema instanceof ZodTransformer) {
+ return inputSchema(schema._def.output);
+ } else {
+ return schema;
+ }
+};
+
+export type RefinementCtx = {
+ addIssue: (arg: MakeErrorData) => void;
+ path: (string | number)[];
+};
+type InternalCheck = {
+ check: (arg: T, ctx: RefinementCtx) => any;
+ // refinementError: (arg: T) => MakeErrorData;
+};
+
+// type Check = {
+// check: (arg: T) => any;
+// path?: (string | number)[];
+// // message?: string;
+// // params?: {[k:string]:any}
+// } & util.Omit;
+
+type CustomErrorParams = Partial>;
+// type Check = {
+// check: (arg: T) => any;
+// refinementError: (arg: T) => CustomErrorParams;
+// };
+
+export interface ZodTypeDef {
+ t: ZodTypes;
+ checks?: InternalCheck[];
+ accepts?: ZodType;
+}
+
+export type TypeOf> = T['_output'];
+export type input