Socket
Socket
Sign inDemoInstall

zod

Package Overview
Dependencies
Maintainers
1
Versions
361
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

zod - npm Package Compare versions

Comparing version 1.2.6 to 1.3.0

lib/src/types/bigint.d.ts

1

lib/src/helpers/Mocker.d.ts

@@ -5,2 +5,3 @@ export declare class Mocker {

readonly number: number;
readonly bigint: bigint;
readonly boolean: boolean;

@@ -7,0 +8,0 @@ readonly date: Date;

@@ -32,2 +32,9 @@ "use strict";

});
Object.defineProperty(Mocker.prototype, "bigint", {
get: function () {
return BigInt(Math.floor(Math.random() * 10000));
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mocker.prototype, "boolean", {

@@ -34,0 +41,0 @@ get: function () {

2

lib/src/helpers/primitive.d.ts

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

export declare type Primitive = string | number | boolean | null | undefined;
export declare type Primitive = string | number | bigint | boolean | null | undefined;
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;
}

@@ -15,3 +15,10 @@ "use strict";

util.assertNever = assertNever;
util.getObjectType = function (value) {
var objectName = toString.call(value).slice(8, -1);
if (objectName) {
return objectName;
}
return undefined;
};
})(util = exports.util || (exports.util = {}));
//# sourceMappingURL=util.js.map
import { ZodString, ZodStringDef } from './types/string';
import { ZodNumber, ZodNumberDef } from './types/number';
import { ZodBigInt, ZodBigIntDef } from './types/bigint';
import { ZodBoolean, ZodBooleanDef } from './types/boolean';

@@ -17,7 +18,9 @@ import { ZodDate, ZodDateDef } from './types/date';

import { ZodEnum, ZodEnumDef } from './types/enum';
import { ZodPromise, ZodPromiseDef } from './types/promise';
import { TypeOf, ZodType, ZodAny } from './types/base';
import { ZodError } from './ZodError';
declare type ZodDef = ZodStringDef | ZodNumberDef | ZodBooleanDef | ZodDateDef | ZodUndefinedDef | ZodNullDef | ZodArrayDef | ZodObjectDef | ZodUnionDef | ZodIntersectionDef | ZodTupleDef | ZodRecordDef | ZodLazyDef | ZodLiteralDef | ZodEnumDef;
declare type ZodDef = ZodStringDef | ZodNumberDef | ZodBigIntDef | ZodBooleanDef | ZodDateDef | ZodUndefinedDef | ZodNullDef | ZodArrayDef | ZodObjectDef | ZodUnionDef | ZodIntersectionDef | ZodTupleDef | ZodRecordDef | ZodLazyDef | ZodLiteralDef | ZodEnumDef | ZodPromiseDef;
declare const stringType: () => ZodString;
declare const numberType: () => ZodNumber;
declare const bigIntType: () => ZodBigInt;
declare const booleanType: () => ZodBoolean;

@@ -33,3 +36,3 @@ declare const dateType: () => ZodDate;

declare const intersectionType: <T extends ZodType<any, import("./types/base").ZodTypeDef>, U extends ZodType<any, import("./types/base").ZodTypeDef>>(left: T, right: U) => ZodIntersection<T, U>;
declare const tupleType: <T extends [ZodType<any, import("./types/base").ZodTypeDef>, ...ZodType<any, import("./types/base").ZodTypeDef>[]] | []>(schemas: T) => ZodTuple<T>;
declare const tupleType: <T extends [] | [ZodType<any, import("./types/base").ZodTypeDef>, ...ZodType<any, import("./types/base").ZodTypeDef>[]]>(schemas: T) => ZodTuple<T>;
declare const recordType: <Value extends ZodType<any, import("./types/base").ZodTypeDef> = ZodType<any, import("./types/base").ZodTypeDef>>(valueType: Value) => ZodRecord<Value>;

@@ -40,7 +43,8 @@ declare const functionType: <T extends ZodTuple<any>, U extends ZodType<any, import("./types/base").ZodTypeDef>>(args: T, returns: U) => ZodFunction<T, U>;

declare const enumType: <U extends string, T extends [U, ...U[]]>(values: T) => ZodEnum<T>;
declare const promiseType: <T extends ZodType<any, import("./types/base").ZodTypeDef>>(schema: T) => ZodPromise<T>;
declare const ostring: () => ZodUnion<[ZodString, ZodUndefined]>;
declare const onumber: () => ZodUnion<[ZodNumber, ZodUndefined]>;
declare const oboolean: () => ZodUnion<[ZodBoolean, ZodUndefined]>;
export { stringType as string, numberType as number, booleanType as boolean, dateType as date, undefinedType as undefined, nullType as null, 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, ostring, onumber, oboolean, };
export { ZodString, ZodNumber, ZodBoolean, ZodDate, ZodUndefined, ZodNull, ZodArray, ZodObject, ZodUnion, ZodIntersection, ZodTuple, ZodRecord, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodType, ZodAny, ZodDef, ZodError, };
export { stringType as string, numberType as number, bigIntType as bigint, booleanType as boolean, dateType as date, undefinedType as undefined, nullType as null, 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, };
export { ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodUndefined, ZodNull, ZodArray, ZodObject, ZodUnion, ZodIntersection, ZodTuple, ZodRecord, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodPromise, ZodType, ZodAny, ZodDef, ZodError, };
export { TypeOf, TypeOf as infer };

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

exports.ZodNumber = number_1.ZodNumber;
var bigint_1 = require("./types/bigint");
exports.ZodBigInt = bigint_1.ZodBigInt;
var boolean_1 = require("./types/boolean");

@@ -37,2 +39,4 @@ exports.ZodBoolean = boolean_1.ZodBoolean;

exports.ZodEnum = enum_1.ZodEnum;
var promise_1 = require("./types/promise");
exports.ZodPromise = promise_1.ZodPromise;
var base_1 = require("./types/base");

@@ -46,2 +50,4 @@ exports.ZodType = base_1.ZodType;

exports.number = numberType;
var bigIntType = bigint_1.ZodBigInt.create;
exports.bigint = bigIntType;
var booleanType = boolean_1.ZodBoolean.create;

@@ -77,2 +83,4 @@ exports.boolean = booleanType;

exports.enum = enumType;
var promiseType = promise_1.ZodPromise.create;
exports.promise = promiseType;
var ostring = function () { return stringType().optional(); };

@@ -79,0 +87,0 @@ exports.ostring = ostring;

"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("./types/base"));
var _1 = require(".");
// import { util } from './helpers/util';;
// import { ZodArray } from './types/array';
// import { ZodObject } from './types/object';
// import { ZodUnion } from './types/union';
// import { ZodIntersection } from './types/intersection';
// import { ZodTuple } from './types/tuple';
// import { ZodRecord } from './types/record';
// import { ZodLazy } from './types/lazy';
// import { ZodError } from './ZodError';
var sampleParamVisitor_1 = require("./sampleParamVisitor");
// import { ZodObject } from './types/object';
// type Params = any; //{ [k: string]: boolean | Params } | boolean;
exports.Masker = sampleParamVisitor_1.ParamVisitor(function (schema, params) {
var def = schema._def;
console.log("visiting " + def.t);
console.log("params: " + JSON.stringify(params, null, 2), null, 2);
if (def.t === z.ZodTypes.object) {
console.log(schema);
// console.log(JSON.stringify(params, null, 2));
var visitedShape = {};
for (var key in def.shape) {
if (params[key]) {
visitedShape[key] = def.shape[key];
}
}
return _1.ZodObject.create(visitedShape);
}
else {
return schema;
}
});
// export const Masker = (visit: (_schema: z.ZodAny, params: Params) => z.ZodAny) => (
// schema: z.ZodAny,
// params: Params,
// ) => {
// import * as z from './types/base';
// import { ZodDef, ZodObject } from '.';
// // import { util } from './helpers/util';;
// // import { ZodArray } from './types/array';
// // import { ZodObject } from './types/object';
// // import { ZodUnion } from './types/union';
// // import { ZodIntersection } from './types/intersection';
// // import { ZodTuple } from './types/tuple';
// // import { ZodRecord } from './types/record';
// // import { ZodLazy } from './types/lazy';
// // import { ZodError } from './ZodError';
// import { ParamVisitor } from './sampleParamVisitor';
// // import { ZodObject } from './types/object';
// // type Params = any; //{ [k: string]: boolean | Params } | boolean;
// export const Masker = ParamVisitor((schema, params) => {
// const def: ZodDef = schema._def as any;
// if (params === true) return schema;
// if (typeof params !== 'object') throw new Error('Invalid params');
// if (Array.isArray(params)) throw new Error('Invalid params');
// switch (def.t) {
// case z.ZodTypes.string:
// return visit(schema, params);
// case z.ZodTypes.number:
// return visit(schema, params);
// case z.ZodTypes.boolean:
// return visit(schema, params);
// case z.ZodTypes.date:
// return visit(schema, params);
// case z.ZodTypes.undefined:
// return visit(schema, params);
// case z.ZodTypes.null:
// return visit(schema, params);
// case z.ZodTypes.array:
// return visit(
// new ZodArray({
// ...def,
// type: visit(def.type, params),
// }),
// params,
// );
// case z.ZodTypes.object:
// const visitedShape: any = {};
// for (const key in def.shape) {
// if (params[key]) {
// visitedShape[key] = visit(def.shape[key], params[key]);
// // if(params[key] === true){
// // visitedShape[key] = def.shape[key]
// // }else if(typeof params === "object"){
// // visitedShape[key] = visit(def.shape[key], params[key]);
// // }
// }
// console.log(`visiting ${def.t}`);
// console.log(`params: ${JSON.stringify(params, null, 2)}`, null, 2);
// if (def.t === z.ZodTypes.object) {
// console.log(schema);
// // console.log(JSON.stringify(params, null, 2));
// const visitedShape: any = {};
// for (const key in def.shape) {
// if (params[key]) {
// visitedShape[key] = def.shape[key];
// }
// return visit(
// new ZodObject({
// ...def,
// shape: visitedShape,
// }),
// params,
// );
// case z.ZodTypes.union:
// return visit(
// new ZodUnion({
// ...def,
// options: def.options.map(option => visit(option, params)) as any,
// }),
// params,
// );
// case z.ZodTypes.intersection:
// return visit(
// new ZodIntersection({
// ...def,
// left: visit(def.left, params),
// right: visit(def.left, params),
// }),
// params,
// );
// case z.ZodTypes.tuple:
// return visit(
// new ZodTuple({
// ...def,
// items: def.items.map(item => visit(item, params)) as any,
// }),
// params,
// );
// case z.ZodTypes.record:
// return visit(
// new ZodRecord({
// ...def,
// valueType: visit(def.valueType, params),
// }),
// params,
// );
// case z.ZodTypes.lazy:
// return visit(
// new ZodLazy({
// ...def,
// getter: () => visit(def.getter(), params),
// }),
// params,
// );
// case z.ZodTypes.literal:
// return visit(schema, params);
// case z.ZodTypes.enum:
// return visit(schema, params);
// default:
// util.assertNever(def);
// break;
// }
// return ZodObject.create(visitedShape);
// } else {
// return schema;
// }
// throw ZodError.fromString(`Unknown schema type.`);
// };
// });
// // export const Masker = (visit: (_schema: z.ZodAny, params: Params) => z.ZodAny) => (
// // schema: z.ZodAny,
// // params: Params,
// // ) => {
// // const def: ZodDef = schema._def as any;
// // if (params === true) return schema;
// // if (typeof params !== 'object') throw new Error('Invalid params');
// // if (Array.isArray(params)) throw new Error('Invalid params');
// // switch (def.t) {
// // case z.ZodTypes.string:
// // return visit(schema, params);
// // case z.ZodTypes.number:
// // return visit(schema, params);
// // case z.ZodTypes.boolean:
// // return visit(schema, params);
// // case z.ZodTypes.date:
// // return visit(schema, params);
// // case z.ZodTypes.undefined:
// // return visit(schema, params);
// // case z.ZodTypes.null:
// // return visit(schema, params);
// // case z.ZodTypes.array:
// // return visit(
// // new ZodArray({
// // ...def,
// // type: visit(def.type, params),
// // }),
// // params,
// // );
// // case z.ZodTypes.object:
// // const visitedShape: any = {};
// // for (const key in def.shape) {
// // if (params[key]) {
// // visitedShape[key] = visit(def.shape[key], params[key]);
// // // if(params[key] === true){
// // // visitedShape[key] = def.shape[key]
// // // }else if(typeof params === "object"){
// // // visitedShape[key] = visit(def.shape[key], params[key]);
// // // }
// // }
// // }
// // return visit(
// // new ZodObject({
// // ...def,
// // shape: visitedShape,
// // }),
// // params,
// // );
// // case z.ZodTypes.union:
// // return visit(
// // new ZodUnion({
// // ...def,
// // options: def.options.map(option => visit(option, params)) as any,
// // }),
// // params,
// // );
// // case z.ZodTypes.intersection:
// // return visit(
// // new ZodIntersection({
// // ...def,
// // left: visit(def.left, params),
// // right: visit(def.left, params),
// // }),
// // params,
// // );
// // case z.ZodTypes.tuple:
// // return visit(
// // new ZodTuple({
// // ...def,
// // items: def.items.map(item => visit(item, params)) as any,
// // }),
// // params,
// // );
// // case z.ZodTypes.record:
// // return visit(
// // new ZodRecord({
// // ...def,
// // valueType: visit(def.valueType, params),
// // }),
// // params,
// // );
// // case z.ZodTypes.lazy:
// // return visit(
// // new ZodLazy({
// // ...def,
// // getter: () => visit(def.getter(), params),
// // }),
// // params,
// // );
// // case z.ZodTypes.literal:
// // return visit(schema, params);
// // case z.ZodTypes.enum:
// // return visit(schema, params);
// // default:
// // util.assertNever(def);
// // break;
// // }
// // throw ZodError.fromString(`Unknown schema type.`);
// // };
//# sourceMappingURL=masker.js.map
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importStar = (this && this.__importStar) || function (mod) {

@@ -9,2 +44,3 @@ if (mod && mod.__esModule) return mod;

};
var _this = this;
Object.defineProperty(exports, "__esModule", { value: true });

@@ -47,2 +83,7 @@ var z = __importStar(require("./types/base"));

return obj;
case z.ZodTypes.bigint:
if (typeof obj !== 'bigint') {
throw ZodError_1.ZodError.fromString("Non-bigint type: " + typeof obj + ".");
}
return obj;
case z.ZodTypes.boolean:

@@ -211,3 +252,33 @@ if (typeof obj !== 'boolean')

}
throw ZodError_1.ZodError.fromString("Non-Date type: " + obj.type);
throw ZodError_1.ZodError.fromString("Non-Date type: " + typeof obj);
case z.ZodTypes.promise:
if (!obj.then || typeof obj.then !== 'function') {
console.log(JSON.stringify(obj, null, 2));
throw ZodError_1.ZodError.fromString("Non-Promise type: " + typeof obj);
}
if (!obj.catch || typeof obj.catch !== 'function') {
console.log(JSON.stringify(obj, null, 2));
throw ZodError_1.ZodError.fromString("Non-Promise type: " + typeof obj);
}
// if (util.getObjectType(obj) !== 'Promise') {
// throw ZodError.fromString(`Non-Promise type.`);
// }
return new Promise(function (res, rej) { return __awaiter(_this, void 0, void 0, function () {
var objValue, parsed;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, obj];
case 1:
objValue = _a.sent();
try {
parsed = def.type.parse(objValue);
res(parsed);
}
catch (err) {
rej(err);
}
return [2 /*return*/];
}
});
}); });
default:

@@ -214,0 +285,0 @@ // function

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

declare const partial: <P extends {
deep: boolean;
}>(params?: P | undefined) => P;
declare const qwer: {
deep: boolean;
};
export {};
"use strict";
var partial = function (params) {
return params || { deep: true };
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var qwer = partial();
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
var _this = this;
Object.defineProperty(exports, "__esModule", { value: true });
var z = __importStar(require("."));
var util_1 = require("./helpers/util");
var promSchema = z.promise(z.object({
name: z.string(),
age: z.number(),
}));
var y = function () { return util_1.util.getObjectType(new Promise(function () { })); };
y.toString();
var run = function () { return __awaiter(_this, void 0, void 0, function () {
var bad;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, promSchema.parse(Promise.resolve({ name: 'Bobby', age: 10 }))];
case 1:
_a.sent();
bad = promSchema.parse(Promise.resolve({ name: 'Bobby', age: '10' }));
// await bad;
bad
.then(function (val) {
console.log(JSON.stringify(val, null, 2));
})
.catch(function (err) {
if (err instanceof z.ZodError) {
console.log(JSON.stringify(err.errors, null, 2));
}
});
return [2 /*return*/, bad];
}
});
}); };
run().catch(function (err) {
console.log('caught zod error!');
console.log(err);
});
// expect(bad).toThrow();
// const failPromise = promSchema.parse(Promise.resolve({ name: 'Bobby', age: '10' }));
// failPromise.catch(err => {
// console.log(err);
// console.log(err.message);
// expect(err instanceof ZodError).toBeTruthy();
// });
//# sourceMappingURL=playground.js.map
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var z = __importStar(require("./types/base"));
var _1 = require(".");
var util_1 = require("./helpers/util");
// import { ZodArray } from './types/array';
// import { ZodObject } from './types/object';
// import { ZodUnion } from './types/union';
// import { ZodIntersection } from './types/intersection';
// import { ZodTuple } from './types/tuple';
// import { ZodRecord } from './types/record';
// import { ZodLazy } from './types/lazy';
var ZodError_1 = require("./ZodError");
exports.ParamVisitor = function (visit) { return function (schema, params) {
var def = schema._def;
switch (def.t) {
case z.ZodTypes.string:
return visit(schema, params);
case z.ZodTypes.number:
return visit(schema, params);
case z.ZodTypes.boolean:
return visit(schema, params);
case z.ZodTypes.date:
return visit(schema, params);
case z.ZodTypes.undefined:
return visit(schema, params);
case z.ZodTypes.null:
return visit(schema, params);
case z.ZodTypes.array:
return visit(new _1.ZodArray(__assign({}, def, { type: visit(def.type, params) })), params);
case z.ZodTypes.object:
var visitedShape = {};
for (var key in def.shape) {
visitedShape[key] = visit(def.shape[key], params[key]);
}
return visit(new _1.ZodObject(__assign({}, def, { shape: visitedShape })), params);
case z.ZodTypes.union:
return visit(new _1.ZodUnion(__assign({}, def, { options: def.options.map(function (option) { return visit(option, params); }) })), params);
case z.ZodTypes.intersection:
return visit(new _1.ZodIntersection(__assign({}, def, { left: visit(def.left, params), right: visit(def.left, params) })), params);
case z.ZodTypes.tuple:
return visit(new _1.ZodTuple(__assign({}, def, { items: def.items.map(function (item) { return visit(item, params); }) })), params);
case z.ZodTypes.record:
return visit(new _1.ZodRecord(__assign({}, def, { valueType: visit(def.valueType, params) })), params);
case z.ZodTypes.lazy:
return visit(new _1.ZodLazy(__assign({}, def, { getter: function () { return visit(def.getter(), params); } })), params);
case z.ZodTypes.literal:
return visit(schema, params);
case z.ZodTypes.enum:
return visit(schema, params);
default:
util_1.util.assertNever(def);
break;
}
throw ZodError_1.ZodError.fromString("Unknown schema type.");
}; };
// import * as z from './types/base';
// import { ZodDef, ZodArray, ZodObject, ZodUnion, ZodIntersection, ZodTuple, ZodRecord, ZodLazy } from '.';
// import { util } from './helpers/util';
// // import { ZodArray } from './types/array';
// // import { ZodObject } from './types/object';
// // import { ZodUnion } from './types/union';
// // import { ZodIntersection } from './types/intersection';
// // import { ZodTuple } from './types/tuple';
// // import { ZodRecord } from './types/record';
// // import { ZodLazy } from './types/lazy';
// import { ZodError } from './ZodError';
// type Params = any;
// export const ParamVisitor = (visit: (_schema: z.ZodAny, params: Params) => z.ZodAny) => (
// schema: z.ZodAny,
// params: Params,
// ): z.ZodAny => {
// const def: ZodDef = schema._def as any;
// switch (def.t) {
// case z.ZodTypes.string:
// return visit(schema, params);
// case z.ZodTypes.number:
// return visit(schema, params);
// case z.ZodTypes.boolean:
// return visit(schema, params);
// case z.ZodTypes.date:
// return visit(schema, params);
// case z.ZodTypes.undefined:
// return visit(schema, params);
// case z.ZodTypes.null:
// return visit(schema, params);
// case z.ZodTypes.array:
// return visit(
// new ZodArray({
// ...def,
// type: visit(def.type, params),
// }),
// params,
// );
// case z.ZodTypes.object:
// const visitedShape: any = {};
// for (const key in def.shape) {
// visitedShape[key] = visit(def.shape[key], params[key]);
// }
// return visit(
// new ZodObject({
// ...def,
// shape: visitedShape,
// }),
// params,
// );
// case z.ZodTypes.union:
// return visit(
// new ZodUnion({
// ...def,
// options: def.options.map(option => visit(option, params)) as any,
// }),
// params,
// );
// case z.ZodTypes.intersection:
// return visit(
// new ZodIntersection({
// ...def,
// left: visit(def.left, params),
// right: visit(def.left, params),
// }),
// params,
// );
// case z.ZodTypes.tuple:
// return visit(
// new ZodTuple({
// ...def,
// items: def.items.map(item => visit(item, params)) as any,
// }),
// params,
// );
// case z.ZodTypes.record:
// return visit(
// new ZodRecord({
// ...def,
// valueType: visit(def.valueType, params),
// }),
// params,
// );
// case z.ZodTypes.lazy:
// return visit(
// new ZodLazy({
// ...def,
// getter: () => visit(def.getter(), params),
// }),
// params,
// );
// case z.ZodTypes.literal:
// return visit(schema, params);
// case z.ZodTypes.enum:
// return visit(schema, params);
// default:
// util.assertNever(def);
// break;
// }
// throw ZodError.fromString(`Unknown schema type.`);
// };
//# sourceMappingURL=sampleParamVisitor.js.map
"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("./types/base"));
var util_1 = require("./helpers/util");
exports.sampleVisitor = function (schema) {
var _def = schema._def;
var def = _def;
switch (def.t) {
case z.ZodTypes.string:
break;
case z.ZodTypes.number:
break;
case z.ZodTypes.boolean:
break;
case z.ZodTypes.date:
break;
case z.ZodTypes.undefined:
break;
case z.ZodTypes.null:
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.record:
break;
case z.ZodTypes.lazy:
break;
case z.ZodTypes.literal:
break;
case z.ZodTypes.enum:
break;
default:
util_1.util.assertNever(def);
break;
}
};
// import * as z from './types/base';
// import { ZodDef } from '.';
// import { util } from './helpers/util';
// export const sampleVisitor = (schema: z.ZodAny) => {
// const _def = schema._def;
// const def: ZodDef = _def as any;
// switch (def.t) {
// case z.ZodTypes.string:
// break;
// case z.ZodTypes.number:
// break;
// case z.ZodTypes.boolean:
// break;
// case z.ZodTypes.date:
// break;
// case z.ZodTypes.undefined:
// break;
// case z.ZodTypes.null:
// 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.record:
// break;
// case z.ZodTypes.lazy:
// break;
// case z.ZodTypes.literal:
// break;
// case z.ZodTypes.enum:
// break;
// default:
// util.assertNever(def);
// break;
// }
// };
//# sourceMappingURL=sampleVisitor.js.map

@@ -5,2 +5,3 @@ import { ParseParams } from '../parser';

number = "number",
bigint = "bigint",
boolean = "boolean",

@@ -20,3 +21,4 @@ date = "date",

literal = "literal",
enum = "enum"
enum = "enum",
promise = "promise"
}

@@ -41,3 +43,3 @@ export declare type ZodAny = ZodType<any>;

is(u: Type): u is Type;
check(u: Type): u is Type;
check(u: Type | unknown): u is Type;
constructor(def: Def);

@@ -44,0 +46,0 @@ abstract toJSON: () => object;

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

ZodTypes["number"] = "number";
ZodTypes["bigint"] = "bigint";
ZodTypes["boolean"] = "boolean";

@@ -25,2 +26,3 @@ ZodTypes["date"] = "date";

ZodTypes["enum"] = "enum";
ZodTypes["promise"] = "promise";
})(ZodTypes = exports.ZodTypes || (exports.ZodTypes = {}));

@@ -27,0 +29,0 @@ // interface Assertable<T> {

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

nullable: () => ZodUnion<[this, ZodNull]>;
static create: <T_1 extends [z.ZodType<any, z.ZodTypeDef>, ...z.ZodType<any, z.ZodTypeDef>[]] | []>(schemas: T_1) => ZodTuple<T_1>;
static create: <T_1 extends [] | [z.ZodType<any, z.ZodTypeDef>, ...z.ZodType<any, z.ZodTypeDef>[]]>(schemas: T_1) => ZodTuple<T_1>;
}

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

var z = __importStar(require("./types/base"));
var _1 = require(".");
var util_1 = require("./helpers/util");

@@ -40,2 +41,4 @@ var array_1 = require("./types/array");

return visit(schema);
case z.ZodTypes.bigint:
return visit(schema);
case z.ZodTypes.boolean:

@@ -71,2 +74,4 @@ return visit(schema);

return visit(schema);
case z.ZodTypes.promise:
return visit(new _1.ZodPromise(__assign({}, def, { type: visit(def.type) })));
default:

@@ -73,0 +78,0 @@ util_1.util.assertNever(def);

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

@@ -64,2 +64,2 @@ "main": "./lib/src/index.js",

}
}
}

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

- [Function schemas](#function-schemas)
- [Promises](#promises)
<!-- - [Masking](#masking) -->

@@ -95,2 +96,3 @@ - [Errors](#errors)

const numberSchema = z.number(); // => ZodType<number>
const bigintSchema = z.bigint(); // => ZodType<bigint>
const booleanSchema = z.boolean(); // => ZodType<boolean>

@@ -717,2 +719,35 @@ const dateSchema = z.date(); // => ZodType<Date>

## Promises
As of zod@1.2.7, there is also support for Promise schemas!
```ts
const numberPromise = z.promise(z.number());
```
"Parsing" works a little differently with promise schemas. Validation happens in two parts:
1. Zod synchronously checks that the input is an instance of Promise (i.e. an object with `.then` and `.catch` methods.).
2. Zod _waits for the promise to resolve_ then validates the resolved value.
```ts
numberPromise.parse('tuna');
// ZodError: Non-Promise type: string
numberPromise.parse(Promise.resolve('tuna'));
// => Promise<number>
const test = async () => {
await numberPromise.parse(Promise.resolve('tuna'));
// ZodError: Non-number type: string
await numberPromise.parse(Promise.resolve(3.14));
// => 3.14
};
```
### Non-native promise implementations
When "parsing" a promise, Zod checks that the passed value is an object with `.then` and `.catch` methods - that's it. So you should be able to pass non-native Promises (Bluebird, etc) into `z.promise(...).parse` with no trouble. One gotcha: the return type of the parse function will be a _native_ `Promise`, so if you have downstream logic that uses non-standard Promise methods, this won't work.
## Function schemas

@@ -725,3 +760,3 @@

- `args: ZodTuple` The first argument is a tuple (created with `z.tuple([...])` and defines the schema of the arguments to your function. If the function doesn't accept arguments, you can pass an empty tuple (`z.tuple([])`).
- `returnType: ZodType` The second argument is the function's return type. This can be any Zod schema.
- `returnType: any Zod schema` The second argument is the function's return type. This can be any Zod schema.

@@ -738,3 +773,3 @@ ```ts

`z.function` actually returns a higher-order "function factory". Every "factory" has `.implement()` method which accepts a function as input and returns a new function.
Function schemas have an `.implement()` method which accepts a function as input and returns a new function.

@@ -756,7 +791,6 @@ ```ts

const args = z.tuple([
z.object({ nameStartsWith: z.string() }), // filters
z.object({ skip: z.number(), limit: z.number() }), // pagination
z.object({ id: z.string() }), // get by ID
]);
const returnType = z.array(
const returnType = z.promise(
z.object({

@@ -770,35 +804,28 @@ id: string(),

const searchUsers = FetcherEndpoint.validate((filters, pagination) => {
// the arguments automatically have the appropriate types
// as defined by the args tuple passed to `z.function()`
// without needing to provide types in the function declaration
const getUserByID = FetcherEndpoint.validate(args => {
args; // => { id: string }
filters.nameStartsWith; // autocompletes
filters.ageLessThan; // TypeError
const user = await User.findByID(args.id);
const users = User.findAll({
// ... apply filters here
});
// TypeScript statically verifies that value returned by
// this function is of type { id: string; name: string; }[]
// this function is of type Promise<{ id: string; name: string; }>
return 'salmon'; // TypeError
return 'salmon'; // TypeError
return user; // success
});
```
const users = searchUsers(
{
nameStartsWith: 'John',
},
{
skip: 0,
limit: 20,
},
);
This is particularly useful for defining HTTP or RPC endpoints that accept complex payloads that require validation. Moreover, you can define your endpoints once with Zod and share the code with both your client and server code to achieve end-to-end type safety.
// `typeof users` => { id: string; name: string; }[]
```ts
// Express example
server.get(`/user/:id`, async (req, res) => {
const user = await getUserByID({ id: req.params.id }).catch(err => {
res.status(400).send(err.message);
});
res.status(200).send(user);
});
```
This is particularly useful for defining HTTP or RPC endpoints that accept complex payloads that require validation. Moreover, you can define your endpoints once with Zod and share the code with both your client and server code to achieve end-to-end type safety.
<!--

@@ -874,2 +901,3 @@ ## Masking

### Recursive schemas -->

@@ -876,0 +904,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc