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.3.0 to 1.4.0

92

lib/src/parser.js

@@ -74,3 +74,4 @@ "use strict";

throw ZodError_1.ZodError.fromString("Non-string type: " + typeof obj);
return obj;
// return obj as any;
break;
case z.ZodTypes.number:

@@ -82,3 +83,4 @@ if (typeof obj !== 'number')

}
return obj;
// return obj as any;
break;
case z.ZodTypes.bigint:

@@ -88,15 +90,19 @@ if (typeof obj !== 'bigint') {

}
return obj;
// return obj;
break;
case z.ZodTypes.boolean:
if (typeof obj !== 'boolean')
throw ZodError_1.ZodError.fromString("Non-boolean type: " + typeof obj);
return obj;
// return obj as any;
break;
case z.ZodTypes.undefined:
if (obj !== undefined)
throw ZodError_1.ZodError.fromString("Non-undefined type:Found: " + typeof obj);
return undefined;
// return undefined;
break;
case z.ZodTypes.null:
if (obj !== null)
throw ZodError_1.ZodError.fromString("Non-null type: " + typeof obj);
return null;
// return null;
break;
case z.ZodTypes.array:

@@ -109,3 +115,3 @@ if (!Array.isArray(obj))

}
var parsedArray = obj.map(function (item, i) {
obj.map(function (item, i) {
try {

@@ -123,3 +129,4 @@ var parsedItem = def.type.parse(item, params);

}
return parsedArray;
break;
// return parsedArray as any;
case z.ZodTypes.object:

@@ -154,15 +161,22 @@ if (typeof obj !== 'object')

}
return parsedObject;
// return parsedObject;
break;
case z.ZodTypes.union:
var isValid = false;
for (var _i = 0, _a = def.options; _i < _a.length; _i++) {
var option = _a[_i];
try {
return option.parse(obj, params);
// return obj;
option.parse(obj, params);
isValid = true;
}
catch (err) { }
catch (err) {
// isValid = false;
}
}
throw ZodError_1.ZodError.fromString("Type mismatch in union.\nReceived: " + JSON.stringify(obj, null, 2) + "\n\nExpected: " + def.options
.map(function (x) { return x._def.t; })
.join(' OR '));
if (isValid === false) {
throw ZodError_1.ZodError.fromString("Error parsing union.\nReceived: " + JSON.stringify(obj, null, 2) + "\nExpected: " + def.options
.map(function (x) { return x._def.t; })
.join(' OR '));
}
break;
case z.ZodTypes.intersection:

@@ -182,6 +196,6 @@ var errors = [];

}
if (!errors.length) {
return obj;
if (errors.length) {
throw ZodError_1.ZodError.fromString(errors.join('\n'));
}
throw ZodError_1.ZodError.fromString(errors.join('\n'));
break;
case z.ZodTypes.tuple:

@@ -211,6 +225,9 @@ if (!Array.isArray(obj)) {

}
return parsedTuple;
// return parsedTuple as any;
break;
case z.ZodTypes.lazy:
var lazySchema = def.getter();
return lazySchema.parse(obj, params);
lazySchema.parse(obj, params);
// return lazySchema.parse(obj, params);
break;
// return obj;

@@ -221,5 +238,5 @@ case z.ZodTypes.literal:

// if (['string','']typeof obj === 'object') throw ZodError.fromString(`Invalid type: ${object}.`);
if (obj === def.value)
return obj;
throw ZodError_1.ZodError.fromString(obj + " !== " + def.value);
if (obj !== def.value)
throw ZodError_1.ZodError.fromString(obj + " !== " + def.value);
break;
case z.ZodTypes.enum:

@@ -229,3 +246,4 @@ if (def.values.indexOf(obj) === -1) {

}
return obj;
// return obj;
break;
// case z.ZodTypes.function:

@@ -250,13 +268,16 @@ // return obj;

throw recordError;
return parsedRecord;
// return parsedRecord;
break;
case z.ZodTypes.date:
if (obj instanceof Date) {
if (!isNaN(obj.getTime())) {
return obj;
}
else {
if (isNaN(obj.getTime())) {
// return obj;
// } else {
throw ZodError_1.ZodError.fromString("Invalid date.");
}
}
throw ZodError_1.ZodError.fromString("Non-Date type: " + typeof obj);
else {
throw ZodError_1.ZodError.fromString("Non-Date type: " + typeof obj);
}
break;
case z.ZodTypes.promise:

@@ -274,2 +295,5 @@ if (!obj.then || typeof obj.then !== 'function') {

// }
if (def.checks) {
throw ZodError_1.ZodError.fromString("Can't apply custom validators to Promise schemas.");
}
return new Promise(function (res, rej) { return __awaiter(_this, void 0, void 0, function () {

@@ -299,2 +323,10 @@ var objValue, parsed;

}
var customChecks = def.checks || [];
for (var _b = 0, customChecks_1 = customChecks; _b < customChecks_1.length; _b++) {
var check = customChecks_1[_b];
if (check.check(obj) !== true) {
throw ZodError_1.ZodError.fromString(check.message || "Failed custom check.");
}
}
return obj;
// assertNever();

@@ -301,0 +333,0 @@ // return obj;

"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) {

@@ -44,45 +9,59 @@ if (mod && mod.__esModule) return mod;

};
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();
// const CellResults = z.object({
// kind: z.literal('results'),
// results: z
// .array(
// z.union([
// z.object({
// kind: z.literal('data'),
// data: z.tuple([z.string(), z.string(), z.string()]),
// }),
// z.object({
// kind: z.literal('error'),
// error: z.tuple([z.string(), z.string(), z.object({})]),
// }),
// z.object({
// kind: z.literal('skipped'),
// }),
// ]),
// )
// .nonempty(),
// });
// export const CellResultsAPIValidator = z.union([
// z.object({
// kind: z.literal('error'),
// error: z.object({
// message: z.string(),
// type: z.string(),
// }),
// }),
// CellResults,
// ]);
// CellResults.parse({
// kind: 'results',
// results: [
// {
// kind: 'error',
// error: [
// 'InvalidReferenceError',
// "object type or alias 'User' does not exist",
// {
// '65521': '7',
// '65522': '11',
// '65523': '1',
// '65524': '8',
// },
// ],
// },
// ],
// });
var obj = z
.object({
asdf: z.string(),
})
.refine({ check: function (val) { return val.asdf.includes('hello'); } });
console.log(obj.parse({ asdf: 'hello there' }));
console.log(obj.parse({ asdf: 'bye bye' }));
//# sourceMappingURL=playground.js.map

@@ -27,4 +27,9 @@ import { ParseParams } from '../parser';

};
declare type Check<T> = {
message?: string;
check: (arg: T) => boolean;
};
export interface ZodTypeDef {
t: ZodTypes;
checks?: Check<any>[];
}

@@ -43,2 +48,3 @@ export declare type TypeOf<T extends {

check(u: Type | unknown): u is Type;
refine: <Val extends Check<this["_type"]>>(check: Val) => this;
constructor(def: Def);

@@ -49,1 +55,2 @@ abstract toJSON: () => object;

}
export {};

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

function ZodType(def) {
var _this = this;
this.refine = function (check) {
_this._def.checks = _this._def.checks || [];
_this._def.checks.push(check);
return _this;
};
this.parse = parser_1.ZodParser(def);

@@ -41,0 +47,0 @@ this._def = def;

@@ -7,2 +7,6 @@ import * as z from './base';

t: z.ZodTypes.string;
validation: {
uuid?: true;
custom?: ((val: any) => boolean)[];
};
}

@@ -9,0 +13,0 @@ export declare class ZodString extends z.ZodType<string, ZodStringDef> {

@@ -36,5 +36,16 @@ "use strict";

}
// 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],
// },
// });
// }
ZodString.create = function () {
return new ZodString({
t: z.ZodTypes.string,
validation: {},
});

@@ -41,0 +52,0 @@ };

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

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

}
}
}

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

</p>
<div style="display:flex;flex-direction:row;justify-content:center;flex-wrap:wrap;">

@@ -12,2 +13,4 @@ [![License][license-image]][license-url]

</div>
[license-url]: https://opensource.org/licenses/MIT

@@ -18,9 +21,9 @@ [license-image]: https://img.shields.io/github/license/vriad/zod

Created and maintained by [@vriad](https://twitter.com/vriad). The motivation for this library and a detailed comparison to various alternatives can be found at https://vriad.com/blog/zod.
<!-- Created and maintained by [@vriad](https://twitter.com/vriad). The motivation for this library and a detailed comparison to various alternatives can be found at https://vriad.com/blog/zod.
If you find this package useful, leave a star to help more folks find it ⭐️🤏
If you find this package useful, leave a star to help more folks find it ⭐️🤏 -->
<br/>
<!-- <br/> -->
### Table of contents
#### Table of contents

@@ -33,2 +36,3 @@ - [Installation](#installation)

- [Type inference](#type-inference)
- [Custom validation](#custom-validation)
- [Objects](#objects)

@@ -46,9 +50,8 @@ - [.nonstrict](#unknown-keys)

- [.nullable](#nullable-types)
- [Enums](#enums)
- [.enum](#enums)
- [Intersections](#intersections)
- [Tuples](#tuples)
- [Intersections](#intersections)
- [Recursive types](#recursive-types)
- [Promises](#promises)
- [Function schemas](#function-schemas)
- [Promises](#promises)
<!-- - [Masking](#masking) -->
- [Errors](#errors)

@@ -74,3 +77,3 @@ - [Changelog](#changelog)

### TypeScript versions
#### TypeScript versions

@@ -120,5 +123,7 @@ Zod 1.0.x is compatible with TypeScript 3.2+.

### Parsing
Given a Zod schema, you can call its `.parse(data)` method to check `data` is valid. If it is, a value is returned with full type information! Otherwise, an error is thrown.
IMPORTANT: The variable you pass into `.parse` is not the same variable you get back out. Assuming the value passes validation, you get back a deep clone of the object you passed in.
IMPORTANT: As of Zod 1.4, the value returned by `.parse` is _the same variable you passed in_. Previously it returned a deep clone. One exception: "parsing" a `Promise` schemas returns a new Promise for reasons explained in the documentation.

@@ -131,2 +136,4 @@ ```ts

### Type guards
You can also use a Zod schema as a type guard using the schema's `.check()` method, like so:

@@ -160,2 +167,17 @@

### Custom validation
Every Zod schema has a `.refine` method that lets you define custom validation checks. Zod was designed to mirror TypeScript as closely as possible. But there are many so-called "refinement types" you may wish to check for that can't be represented in TypeScript's type system. For instance: checking that a number is an Int or that a string is a valid email address.
In these cases, you would use the `.refine` method.
```ts
const myString = z.string().refine({
check: val => val.length <= 255, // `val` has `string` type
message: "String can't be more than 255 characters", // optional
});
```
As you can see, the argument is an object with two properties: `check` (the validation function) and `message` a custom error message for failed validations. The argument to the `check` function (`val` in the example above) is properly typed automatically.
## Type inference

@@ -508,2 +530,20 @@

## Tuples
These differ from arrays in that they have a fixed number of elements, and each element can have a different type.
```ts
const athleteSchema = z.tuple([
// takes an array of schemas
z.string(), // name
z.number(), // jersey number
z.object({
pointsScored: z.number(),
}), // statistics
]);
type Athlete = z.infer<typeof athleteSchema>;
// type Athlete = [string, number, { pointsScored: number }]
```
## Unions

@@ -520,3 +560,3 @@

### Optional types
#### Optional types

@@ -543,3 +583,3 @@ Unions are the basis for defining optional schemas. An "optional string" is just the union of `string` and `undefined`.

### Nullable types
#### Nullable types

@@ -579,3 +619,3 @@ Similarly, you can create nullable types like so:

## Enums
#### Enums

@@ -642,20 +682,2 @@ You can combine unions and string literals to create an enum schemas.

## Tuples
These differ from arrays in that they have a fixed number of elements, and each element can have a different type.
```ts
const athleteSchema = z.tuple([
// takes an array of schemas
z.string(), // name
z.number(), // jersey number
z.object({
pointsScored: z.number(),
}), // statistics
]);
type Athlete = z.infer<typeof athleteSchema>;
// type Athlete = [string, number, { pointsScored: number }]
```
## Recursive types

@@ -713,3 +735,3 @@

### Cyclical objects
#### Cyclical objects

@@ -734,3 +756,3 @@ Validation still works as expected even when there are cycles in the data.

As of zod@1.2.7, there is also support for Promise schemas!
As of zod@1.3, there is also support for Promise schemas!

@@ -762,3 +784,3 @@ ```ts

### Non-native promise implementations
#### Non-native promise implementations

@@ -789,3 +811,3 @@ 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.

```ts
const myValidatedFunction = myFunction(x => {
const myValidatedFunction = myFunction.implement(x => {
// TypeScript knows x is a string!

@@ -863,3 +885,3 @@ return x.trim().length;

### Picking
#### Picking
```ts

@@ -886,3 +908,3 @@ const User = z.object({

### Nested objects
#### Nested objects

@@ -915,3 +937,3 @@ Masking also works on nested object schemas:

### Recursive schemas -->
#### Recursive schemas -->

@@ -1025,3 +1047,3 @@ ## Errors

### Joi
#### Joi

@@ -1032,3 +1054,3 @@ [https://github.com/hapijs/joi](https://github.com/hapijs/joi)

### Yup
#### Yup

@@ -1071,3 +1093,3 @@ [https://github.com/jquense/yup](https://github.com/jquense/yup)

### io-ts
#### io-ts

@@ -1117,3 +1139,3 @@ [https://github.com/gcanti/io-ts](https://github.com/gcanti/io-ts)

### Runtypes
#### Runtypes

@@ -1124,12 +1146,15 @@ [https://github.com/pelotom/runtypes](https://github.com/pelotom/runtypes)

| zod version | release notes |
| ----------- | ---------------------------------------------------------- |
| zod@1.2.5 | `.partial` and `.deepPartial` on object schemas |
| zod@1.2.3 | Date schemas |
| zod@1.2.0 | `.pick`, `.omit`, and `.augment` on object schemas |
| zod@1.1.0 | Records |
| zod@1.0.11 | `.nonstrict` |
| zod@1.0.10 | Type assertions with `.check` |
| zod@1.0.4 | Empty tuples |
| zod@1.0.0 | Type assertions, literals, enums, detailed error reporting |
| zod@1.0.0 | Initial release |
| zod version | release notes |
| ----------- | ------------------------------------------------------------------- |
| zod@1.4 | Refinement types (`.refine`), `.parse` no longer returns deep clone |
| zod@1.3 | Promise schemas |
| zod@1.2.6 | `.parse` accepts `unknown`, `bigint` schemas |
| zod@1.2.5 | `.partial` and `.deepPartial` on object schemas |
| zod@1.2.3 | Date schemas |
| zod@1.2.0 | `.pick`, `.omit`, and `.augment` on object schemas |
| zod@1.1.0 | Records |
| zod@1.0.11 | `.nonstrict` |
| zod@1.0.10 | Type assertions with `.check` |
| zod@1.0.4 | Empty tuples |
| zod@1.0.0 | Type assertions, literals, enums, detailed error reporting |
| zod@1.0.0 | Initial release |

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