Socket
Socket
Sign inDemoInstall

zod

Package Overview
Dependencies
0
Maintainers
1
Versions
360
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.8.0 to 1.9.0

14

lib/src/codegen.js

@@ -10,7 +10,4 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
// import { ZodTypes, SomeSkiiType, SkiiType } from '.';
var z = __importStar(require("."));
var util_1 = require("./helpers/util");
// type adsf = {str:string} | {qwer:number};
// const y:adsf = {plpl:true}
var isOptional = function (schema) {

@@ -35,5 +32,2 @@ var def = schema._def;

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

@@ -49,5 +43,2 @@ this.findBySchema = function (schema) {

};
// add = (id: string, schema: SkiiType<any, any>, type: string) => {
// this.seen.push({ id, schema, type });
// };
this.dump = function () {

@@ -66,3 +57,2 @@ return "\ntype Identity<T> = T;\n\n" + _this.seen.map(function (item) { return "type " + item.id + " = Identity<" + item.type + ">;"; }).join('\n\n') + "\n";

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

@@ -75,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) {

@@ -81,0 +67,0 @@ case z.ZodTypes.string:

"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

2

lib/src/helpers/objectUtil.js

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

(function (objectUtil) {
// export type ObjectType<T extends ZodRawShape> = FlattenObject<ObjectIntersection<T>>;
objectUtil.mergeShapes = function (first, second) {

@@ -37,3 +36,2 @@ var firstKeys = Object.keys(first);

checks: (first._def.checks || []).concat((second._def.checks || [])),
// strict: first.params.strict && second.params.strict,
params: {

@@ -40,0 +38,0 @@ strict: first.params.strict && second.params.strict,

export declare namespace util {
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>>;

@@ -6,0 +5,0 @@ type OmitKeys<T, K extends string> = Pick<T, Exclude<keyof T, K>>;

@@ -5,8 +5,2 @@ "use strict";

(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 +10,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) {

@@ -28,0 +12,0 @@ var obj = {};

11

lib/src/index.d.ts

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

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, lazyType as lazy, literalType as literal, enumType as enum, promiseType as promise, ostring, onumber, oboolean, codegen, };
declare const instanceOfType: <T extends new (...args: any[]) => any>(cls: T, params?: string | Pick<{
check: (arg: any) => any;
path?: (string | number)[] | undefined;
} & Pick<import("./ZodError").CustomError, "message" | "params">, "message" | "path" | "params"> | undefined) => ZodType<InstanceType<T>, ZodTypeDef>;
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, lazyType as lazy, literalType as literal, enumType as enum, promiseType as promise, instanceOfType as instanceof, ostring, onumber, oboolean, codegen, };
export declare const late: {

@@ -63,6 +67,3 @@ object: <T extends import("./types/base").ZodRawShape>(shape: () => T) => ZodObject<T, {

};
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, ZodParsedType, ZodCodeGenerator, };
export declare type lazyobject<T extends object> = ZodObject<{
[k in keyof T]: ZodType<T[k], any>;
}>;
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, ZodType as ZodSchema, ZodTypeAny, ZodDef, ZodError, ZodErrorMap, ZodErrorCode, ZodParsedType, ZodCodeGenerator, };
export { TypeOf, TypeOf as infer };

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

exports.Schema = base_1.ZodType;
exports.ZodSchema = base_1.ZodType;
exports.ZodTypes = base_1.ZodTypes;

@@ -94,4 +95,2 @@ var ZodError_1 = require("./ZodError");

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

@@ -111,2 +110,10 @@ exports.literal = literalType;

exports.codegen = codegen;
var 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 custom(function (data) { return data instanceof cls; }, params);
};
exports.instanceof = instanceOfType;
exports.late = {

@@ -113,0 +120,0 @@ object: object_1.ZodObject.lazycreate,

@@ -88,8 +88,3 @@ "use strict";

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

@@ -135,10 +130,5 @@ }

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;

@@ -156,22 +146,8 @@ }

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;
// }
// }
switch (def.t) {
case z.ZodTypes.string:
// error.addError()
if (parsedType !== exports.ZodParsedType.string) {
//throw ZodError.fromString(`Non-string type: ${typeof obj}`);
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_type, expected: exports.ZodParsedType.string, received: parsedType }));
throw error;
}
// return obj as any;
break;

@@ -187,3 +163,2 @@ case z.ZodTypes.number:

}
// return obj as any;
break;

@@ -194,13 +169,9 @@ case z.ZodTypes.bigint:

throw error;
// throw ZodError.fromString(`Non-bigint type: ${typeof obj}.`);
}
// return obj;
break;
case z.ZodTypes.boolean:
if (parsedType !== exports.ZodParsedType.boolean) {
// throw ZodError.fromString(`Non-boolean type: ${typeof obj}`);
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_type, expected: exports.ZodParsedType.boolean, received: parsedType }));
throw error;
}
// return obj as any;
break;

@@ -211,9 +182,6 @@ case z.ZodTypes.undefined:

throw error;
// throw ZodError.fromString(`Non-undefined type:Found: ${typeof obj}`);
}
// return undefined;
break;
case z.ZodTypes.null:
if (parsedType !== exports.ZodParsedType.null) {
// throw ZodError.fromString(`Non-null type: ${typeof obj}`);
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_type, expected: exports.ZodParsedType.null, received: parsedType }));

@@ -235,3 +203,2 @@ throw error;

if (parsedType !== exports.ZodParsedType.array) {
// throw ZodError.fromString(`Non-array type: ${typeof obj}`);
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_type, expected: exports.ZodParsedType.array, received: parsedType }));

@@ -241,7 +208,5 @@ throw error;

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');
}

@@ -256,14 +221,10 @@ data.map(function (item, i) {

error.addErrors(zerr.errors);
// arrayError.mergeChild(i, err);
}
});
if (!error.isEmpty) {
// throw ZodError.fromString(arrayErrors.join('\n\n'));
throw error;
}
break;
// return parsedArray as any;
case z.ZodTypes.object:
if (parsedType !== exports.ZodParsedType.object) {
// throw ZodError.fromString(`Non-object type: ${typeof obj}`);
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_type, expected: exports.ZodParsedType.object, received: parsedType }));

@@ -278,15 +239,8 @@ throw error;

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(', ')}`);
}
}
// const parsedObject: any = {};
// const objectError = ZodError.create([]);
for (var key in shape) {
try {
// const parsedEntry =
def.shape()[key].parse(obj[key], __assign({}, params, { path: params.path.concat([key]) }));
// parsedObject[key] = parsedEntry;
}

@@ -296,14 +250,7 @@ catch (err) {

error.addErrors(zerr.errors);
// objectError.mergeChild(key, err);
}
}
// if (!objectError.isEmpty) {
// throw objectError; //ZodError.fromString(objectErrors.join('\n'));
// }
// return parsedObject;
break;
case z.ZodTypes.union:
var isValid = false;
// const unionErrors: string[] = [];
// unionError.addError('union', 'Error parsing union type.');
var unionErrors = [];

@@ -318,8 +265,4 @@ for (var _i = 0, _a = def.options; _i < _a.length; _i++) {

unionErrors.push(err);
// unionErrors.push(`\tunion option #${def.options.indexOf(option)}: ${err.message}`);
// isValid = false;
}
}
// 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) {

@@ -339,13 +282,4 @@ var filteredErrors = unionErrors.filter(function (err) {

}
// 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 {

@@ -356,3 +290,2 @@ def.left.parse(obj, params);

error.addErrors(err.errors);
// errors.push(`Left side of intersection: ${err.message}`);
}

@@ -364,31 +297,15 @@ try {

error.addErrors(err.errors);
// errors.push(`Right side of intersection: ${err.message}`);
}
// if (errors.length) {
// throw ZodError.fromString(errors.join('\n'));
// }
break;
case z.ZodTypes.tuple:
if (parsedType !== exports.ZodParsedType.array) {
// tupleError.addError('','Non-array type detected; invalid tuple.')
error.addError(makeError({ code: ZodError_1.ZodErrorCode.invalid_type, expected: exports.ZodParsedType.array, received: parsedType }));
throw error;
// throw ZodError.fromString('Non-array type detected; invalid tuple.');
}
if (obj.length > def.items.length) {
error.addError(makeError({ code: ZodError_1.ZodErrorCode.too_big, maximum: def.items.length, inclusive: true, type: 'array' }));
// 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}`,
// );
}
else if (obj.length < def.items.length) {
error.addError(makeError({ code: ZodError_1.ZodErrorCode.too_small, minimum: def.items.length, inclusive: true, type: 'array' }));
// 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 = [];

@@ -403,11 +320,5 @@ var tupleData = obj;

catch (err) {
// console.log(`mering child: ${index}`);
error.addErrors(err.errors);
// tupleError.mergeChild(index, err);
}
}
// if (!tupleError.isEmpty) {
// throw tupleError;
// }
// return parsedTuple as any;
break;

@@ -417,12 +328,6 @@ case z.ZodTypes.lazy:

lazySchema.parse(obj, params);
// return lazySchema.parse(obj, 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}`);
}

@@ -436,5 +341,3 @@ break;

}));
// throw ZodError.fromString(`"${obj}" does not match any value in enum`);
}
// return obj;
break;

@@ -449,3 +352,2 @@ case z.ZodTypes.function:

throw error;
// throw ZodError.fromString(`Non-function type: "${typeof obj}"`);
}

@@ -490,3 +392,2 @@ var validatedFunc = function () {

return validatedFunc;
// return obj;
case z.ZodTypes.record:

@@ -501,9 +402,4 @@ if (parsedType !== exports.ZodParsedType.object) {

}
// 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({}, params, { path: params.path.concat([key]) }));

@@ -513,7 +409,4 @@ }

error.addErrors(err.errors);
// recordError.mergeChild(key, err);
}
}
// if (!recordError.isEmpty) throw recordError;
// return parsedRecord;
break;

@@ -530,5 +423,3 @@ case z.ZodTypes.date:

if (isNaN(obj.getTime())) {
// if (isNaN(obj.getTime())) {
// return obj;
// } else {
console.log('NAN');
error.addError(makeError({

@@ -538,4 +429,2 @@ code: ZodError_1.ZodErrorCode.invalid_date,

throw error;
// throw ZodError.fromString(`Invalid date.`);
// }
}

@@ -552,16 +441,2 @@ break;

}
// 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(_this, void 0, void 0, function () {

@@ -586,6 +461,3 @@ var objValue, parsed;

default:
// function
// return obj;
util_1.util.assertNever(def);
// break;
}

@@ -592,0 +464,0 @@ var customChecks = def.checks || [];

"use strict";
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 });
var z = __importStar(require("."));
z.object({
password: z.string(),
confirm: z.string(),
})
.refine(function (data) { return data.confirm === data.password; }, { path: ['confirm'] })
.parseAsync({ password: 'asdf', confirm: 'qewr' })
.catch(function (err) { return console.log(JSON.stringify(err, null, 2)); });
// const run = async () => {
// const errorMap: z.ZodErrorMap = (error, ctx) => {
// /*
// If error.message is set, that means the user is trying to
// override the error message. This is how method-specific
// error overrides work, like this:
// z.string().min(5, { message: "TOO SMALL 🤬" })
// It is a best practice to return `error.message` if it is set.
// */
// if (error.message) return { message: error.message };
// /*
// This is where you override the various error codes
// */
// switch (error.code) {
// case z.ZodErrorCode.invalid_type:
// if (error.expected === 'string') {
// return { message: `This ain't a string!` };
// }
// break;
// case z.ZodErrorCode.custom_error:
// // produce a custom message using error.params
// // error.params won't be set unless you passed
// // a `params` arguments into a custom validator
// const params = error.params || {};
// if (params.myField) {
// return { message: `Bad input: ${params.myField}` };
// }
// break;
// }
// // fall back to default message!
// return { message: ctx.defaultError };
// };
// try {
// z.string().parse(12, { errorMap });
// } catch (err) {
// console.log(JSON.stringify(err.errors, null, 2));
// }
// };
// run();
// import * as z from '.';
// z.date().parse(new Date('invalid'));
//# sourceMappingURL=playground.js.map

@@ -55,9 +55,6 @@ "use strict";

};
// this.refine(data => data.length >= minLength, msg || `Array must contain ${minLength} or more items.`);
_this.max = function (maxLength, message) {
return _this._refinement(__assign({ check: function (data) { return data.length <= maxLength; }, code: __1.ZodErrorCode.too_big, type: 'array', inclusive: true, maximum: maxLength }, (typeof message === 'string' ? { message: message } : message)));
};
// this.refine(data => data.length <= maxLength, msg || `Array must contain ${maxLength} or fewer items.`);
_this.length = function (len, message) { return _this.min(len, { message: message }).max(len, { message: message }); };
// .refine(data => data.length === len, msg || `Array must contain ${len} items.`);
_this.nonempty = function () {

@@ -75,8 +72,2 @@ return new ZodNonEmptyArray(__assign({}, _this._def, { nonempty: 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) {

@@ -107,3 +98,2 @@ return new ZodArray({

};
// this.refine(data => data.length >= minLength, msg || `Array must contain ${minLength} or more items.`);
_this.max = function (maxLength, message) {

@@ -114,9 +104,2 @@ return _this._refinement(__assign({ check: function (data) { return data.length >= maxLength; }, code: __1.ZodErrorCode.too_big, maximum: maxLength, type: 'array', inclusive: true }, (typeof message === 'string' ? { message: 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,
// });
// };
}

@@ -123,0 +106,0 @@ return ZodNonEmptyArray;

import { ParseParams, MakeErrorData } from '../parser';
import { util } from '../helpers/util';
import { ZodArray } from '..';
import { CustomError } from '../ZodError';

@@ -20,3 +21,2 @@ export declare enum ZodTypes {

lazy = "lazy",
lazyobject = "lazyobject",
literal = "literal",

@@ -64,3 +64,4 @@ enum = "enum",

abstract nullable: () => any;
array: () => ZodArray<this>;
}
export {};

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

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

@@ -35,3 +34,2 @@ ZodTypes["intersection"] = "intersection";

ZodTypes["lazy"] = "lazy";
ZodTypes["lazyobject"] = "lazyobject";
ZodTypes["literal"] = "literal";

@@ -44,6 +42,2 @@ ZodTypes["enum"] = "enum";

})(ZodTypes = exports.ZodTypes || (exports.ZodTypes = {}));
// interface Assertable<T> {
// is(value: any): value is T;
// assert(value: any): asserts value is T;
// }
var ZodType = /** @class */ (function () {

@@ -59,3 +53,2 @@ function ZodType(def) {

catch (err) {
// console.log(err);
return rej(err);

@@ -78,2 +71,3 @@ }

};
this.array = function () { return __1.ZodArray.create(_this); };
this.parse = parser_1.ZodParser(def);

@@ -80,0 +74,0 @@ this._def = def;

@@ -19,3 +19,4 @@ import * as z from './base';

toJSON: () => ZodEnumDef<T>;
readonly OptionsList: T;
readonly options: T;
readonly enum: Values<T>;
readonly Values: Values<T>;

@@ -22,0 +23,0 @@ readonly Enum: Values<T>;

@@ -36,3 +36,3 @@ "use strict";

}
Object.defineProperty(ZodEnum.prototype, "OptionsList", {
Object.defineProperty(ZodEnum.prototype, "options", {
get: function () {

@@ -44,2 +44,14 @@ return this._def.values;

});
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", {

@@ -46,0 +58,0 @@ get: function () {

@@ -54,15 +54,4 @@ "use strict";

};
// 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;

@@ -69,0 +58,0 @@ };

@@ -37,5 +37,2 @@ "use strict";

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

@@ -58,3 +55,2 @@ Object.defineProperty(ZodLazy.prototype, "schema", {

exports.ZodLazy = ZodLazy;
// type
//# sourceMappingURL=lazy.js.map

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

}
// static create = <U extends Primitive, T extends LiteralValue<U>>(value: T): ZodLiteral<T> => {
ZodLiteral.create = function (value) {

@@ -39,0 +38,0 @@ return new ZodLiteral({

@@ -47,27 +47,20 @@ "use strict";

_this.toJSON = function () { return _this._def; };
// min = (minimum: number, msg?: string) => this.refine(data => data >= minimum, msg || `Value must be >= ${minimum}`);
_this.min = function (minimum, message) {
return _this._refinement(__assign({ check: function (data) { return data >= minimum; }, code: __1.ZodErrorCode.too_small, minimum: minimum, type: 'number', inclusive: true }, errorUtil_1.errorUtil.errToObj(message)));
};
// max = (maximum: number, msg?: string) => this.refine(data => data <= maximum, msg || `Value must be <= ${maximum}`);
_this.max = function (maximum, message) {
return _this._refinement(__assign({ check: function (data) { return data <= maximum; }, code: __1.ZodErrorCode.too_big, maximum: maximum, type: 'number', inclusive: true }, errorUtil_1.errorUtil.errToObj(message)));
};
// int = (msg?: string) => this.refine(data => Number.isInteger(data), msg || 'Value must be an integer.');
_this.int = function (message) {
return _this._refinement(__assign({ check: function (data) { return Number.isInteger(data); }, code: __1.ZodErrorCode.invalid_type, expected: 'integer', received: 'number' }, errorUtil_1.errorUtil.errToObj(message)));
};
// positive = (msg?: string) => this.refine(data => data > 0, msg || `Value must be positive`);
_this.positive = function (message) {
return _this._refinement(__assign({ check: function (data) { return data > 0; }, code: __1.ZodErrorCode.too_small, minimum: 0, type: 'number', inclusive: false }, errorUtil_1.errorUtil.errToObj(message)));
};
// negative = (msg?: string) => this.refine(data => data < 0, msg || `Value must be negative`);
_this.negative = function (message) {
return _this._refinement(__assign({ check: function (data) { return data < 0; }, code: __1.ZodErrorCode.too_big, maximum: 0, type: 'number', inclusive: false }, errorUtil_1.errorUtil.errToObj(message)));
};
// nonpositive = (msg?: string) => this.refine(data => data <= 0, msg || `Value must be non-positive`);
_this.nonpositive = function (message) {
return _this._refinement(__assign({ check: function (data) { return data <= 0; }, code: __1.ZodErrorCode.too_big, maximum: 0, type: 'number', inclusive: true }, errorUtil_1.errorUtil.errToObj(message)));
};
// nonnegative = (msg?: string) => this.refine(data => data >= 0, msg || `Value must be non-negative`);
_this.nonnegative = function (message) {

@@ -74,0 +67,0 @@ return _this._refinement(__assign({ check: function (data) { return data >= 0; }, code: __1.ZodErrorCode.too_small, minimum: 0, type: 'number', inclusive: true }, errorUtil_1.errorUtil.errToObj(message)));

@@ -20,4 +20,3 @@ import * as z from './base';

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>> {
}, Type extends ZodObjectType<T, Params> = ZodObjectType<T, Params>> extends z.ZodType<Type, ZodObjectDef<T, Params>> {
readonly _shape: T;

@@ -24,0 +23,0 @@ readonly _params: Params;

@@ -34,3 +34,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var z = __importStar(require("./base")); // change
var z = __importStar(require("./base"));
var undefined_1 = require("./undefined");

@@ -40,11 +40,5 @@ var null_1 = require("./null");

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 AugmentFactory = function (def) { return function (augmentation) {
return new ZodObject(__assign({}, def, { shape: function () { return (__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 ({

@@ -67,3 +61,2 @@ t: def.t,

shape: _this._def.shape,
// strict: false,
t: z.ZodTypes.object,

@@ -75,19 +68,4 @@ params: __assign({}, _this._params, { strict: false }),

_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.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;
// };
/**

@@ -106,3 +84,2 @@ * Prior to zod@1.0.12 there was a bug in the

};
// omitKeys = <OmitKeys extends (keyof T)[]>(...omit:OmitKeys):OmitKeys => omit;
_this.omit = function (mask) {

@@ -126,3 +103,2 @@ var shape = {};

var newShape = {};
// const shape = this.shape;
for (var key in _this.shape) {

@@ -155,41 +131,5 @@ var fieldSchema = _this.shape[key];

});
// 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(); });
// };
ZodObject.create = function (shape) {
return new ZodObject({
t: z.ZodTypes.object,
// strict: true,
shape: function () { return shape; },

@@ -204,3 +144,2 @@ params: {

t: z.ZodTypes.object,
// strict: true,
shape: shape,

@@ -207,0 +146,0 @@ params: {

@@ -53,19 +53,12 @@ "use strict";

};
// this.refine(data => data.length >= minLength, msg || `Value must be ${minLength} or more characters long`);
_this.max = function (maxLength, message) {
return _this._refinement(__assign({ check: function (data) { return data.length <= maxLength; }, code: __1.ZodErrorCode.too_big, maximum: maxLength, type: 'string', inclusive: true }, errorUtil_1.errorUtil.errToObj(message)));
};
// max = (maxLength: number, msg?: string) =>
// this.refine(data => data.length <= maxLength, msg || `Value must be ${maxLength} or fewer characters long`);
_this.length = function (len, message) { return _this.min(len, message).max(len, message); };
// length = (len: number, msg?: string) =>
// this.refine(data => data.length == len, msg || `Value must be ${len} characters long.`);
_this.email = function (message) {
return _this._refinement(__assign({ check: function (data) { return emailRegex.test(data); }, code: __1.ZodErrorCode.invalid_string, validation: 'email' }, errorUtil_1.errorUtil.errToObj(message)));
};
//this.refine(data => emailRegex.test(data), errorUtil.errToObj(message));
_this.url = function (message) {
return _this._refinement(__assign({ check: function (data) { return urlRegex.test(data); }, code: __1.ZodErrorCode.invalid_string, validation: 'url' }, errorUtil_1.errorUtil.errToObj(message)));
};
// url = (message?: errorUtil.ErrMessage) => this.refine(data => urlRegex.test(data), errorUtil.errToObj(message));
_this.uuid = function (message) {

@@ -77,15 +70,2 @@ return _this._refinement(__assign({ check: function (data) { return uuidRegex.test(data); }, code: __1.ZodErrorCode.invalid_string, validation: 'uuid' }, errorUtil_1.errorUtil.errToObj(message)));

}
// 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.create = function () {

@@ -100,10 +80,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

@@ -16,3 +16,2 @@ import * as z from './base';

static create: <T_1 extends [z.ZodType<any, z.ZodTypeDef>, z.ZodType<any, z.ZodTypeDef>, ...z.ZodType<any, z.ZodTypeDef>[]]>(types: T_1) => ZodUnion<T_1>;
static make: <T_1 extends [z.ZodType<any, z.ZodTypeDef>, z.ZodType<any, z.ZodTypeDef>, ...z.ZodType<any, z.ZodTypeDef>[]]>(...types: T_1) => ZodUnion<T_1>;
}

@@ -44,12 +44,2 @@ "use strict";

};
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;

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

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

'invalid_union',
// 'invalid_tuple_length',
'invalid_literal_value',

@@ -30,7 +29,3 @@ 'invalid_enum_value',

'invalid_date',
// 'too_short',
// 'too_long',
'invalid_string',
// 'invalid_url',
// 'invalid_uuid',
'too_small',

@@ -79,3 +74,2 @@ 'too_big',

var error = new ZodError(errors);
// error.errors = errors;
return error;

@@ -82,0 +76,0 @@ };

{
"name": "zod",
"version": "1.8.0",
"version": "1.9.0",
"description": "TypeScript-first schema declaration and validation library with static type inference",

@@ -5,0 +5,0 @@ "main": "./lib/src/index.js",

@@ -56,2 +56,3 @@ <p align="center">

- [Promises](#promises)
- [Instanceof](#instanceof)
- [Function schemas](#function-schemas)

@@ -520,3 +521,3 @@ - [Errors](#errors)

> 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.

@@ -664,15 +665,52 @@ #### Unknown keys

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
```

@@ -780,3 +818,3 @@

> You need to either need to pass the literal array directly into z.enum:
> You need to pass the literal array directly into z.enum():
>

@@ -787,19 +825,12 @@ > ```ts

>
> 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.
> If you define the array as a separate variable, then pass it into z.enum, type inference won't work properly.
#### Autocompletion
You can get autocompletion of enum values with the `.Values` property of an enum schema:
You can autocomplete the enum values with the `.enum` property of an enum schema:
```ts
FishEnum.Values.Salmon; // => autocompletes
FishEnum.enum.Salmon; // => autocompletes
FishEnum.Values;
FishEnum.enum;
/*

@@ -814,2 +845,8 @@ => {

You can also retrieve the list of options as a tuple with the `.options` property:
```ts
FishEnum.options; // ["Salmon", "Tuna", "Trout"]);
```
## Intersections

@@ -875,3 +912,3 @@

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

@@ -913,3 +950,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({

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

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([Literal, z.array(Json), z.record(Json)]));

@@ -990,2 +1027,19 @@ jsonSchema.parse({

## 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

@@ -1307,2 +1361,3 @@

| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| zod@1.9 | Added z.instanceof() and z.custom(). Implemented ZodSchema.array() method. |
| zod@1.8 | Introduced z.void(). Major overhaul to error handling system, including the introduction of custom error maps. Wrote new [error handling guide](https://github.com/vriad/zod/blob/beta/ERROR_HANDLING.md). |

@@ -1309,0 +1364,0 @@ | zod@1.7 | Added several built-in validators to string, number, and array schemas. Calls to `.refine` now return new instance. |

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

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc