2026-06-06 20:12:40 +07:00
parent de84b2bf48
commit 97ac0f71f5
13682 changed files with 1125938 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Colin McDonnell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+14
View File
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: af4a370001ac54f8892925544d56e2f4
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/LICENSE
uploadId: 920982
+208
View File
@@ -0,0 +1,208 @@
<p align="center">
<img src="logo.svg" width="200px" align="center" alt="Zod logo" />
<h1 align="center">Zod</h1>
<p align="center">
TypeScript-first schema validation with static type inference
<br/>
by <a href="https://x.com/colinhacks">@colinhacks</a>
</p>
</p>
<br/>
<p align="center">
<a href="https://github.com/colinhacks/zod/actions?query=branch%3Amaster"><img src="https://github.com/colinhacks/zod/actions/workflows/test.yml/badge.svg?event=push&branch=master" alt="Zod CI status" /></a>
<a href="https://opensource.org/licenses/MIT" rel="nofollow"><img src="https://img.shields.io/github/license/colinhacks/zod" alt="License"></a>
<a href="https://www.npmjs.com/package/zod" rel="nofollow"><img src="https://img.shields.io/npm/dw/zod.svg" alt="npm"></a>
<a href="https://discord.gg/KaSRdyX2vc" rel="nofollow"><img src="https://img.shields.io/discord/893487829802418277?label=Discord&logo=discord&logoColor=white" alt="discord server"></a>
<a href="https://github.com/colinhacks/zod" rel="nofollow"><img src="https://img.shields.io/github/stars/colinhacks/zod" alt="stars"></a>
</p>
<div align="center">
<a href="https://zod.dev/api">Docs</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://discord.gg/RcG33DQJdf">Discord</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://twitter.com/colinhacks">𝕏</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://bsky.app/profile/zod.dev">Bluesky</a>
<br />
</div>
<br/>
<br/>
<h2 align="center">Featured sponsor: Jazz</h2>
<div align="center">
<a href="https://jazz.tools/?utm_source=zod">
<picture width="85%" >
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/garden-co/jazz/938f6767e46cdfded60e50d99bf3b533f4809c68/homepage/homepage/public/Zod%20sponsor%20message.png">
<img alt="jazz logo" src="https://raw.githubusercontent.com/garden-co/jazz/938f6767e46cdfded60e50d99bf3b533f4809c68/homepage/homepage/public/Zod%20sponsor%20message.png" width="85%">
</picture>
</a>
<br/>
<p><sub>Learn more about <a target="_blank" rel="noopener noreferrer" href="mailto:sponsorship@colinhacks.com">featured sponsorships</a></sub></p>
</div>
<br/>
<br/>
<br/>
### [Read the docs →](https://zod.dev/api)
<br/>
<br/>
## What is Zod?
Zod is a TypeScript-first validation library. Define a schema and parse some data with it. You'll get back a strongly typed, validated result.
```ts
import * as z from "zod/v4";
const User = z.object({
name: z.string(),
});
// some untrusted data...
const input = {
/* stuff */
};
// the parsed result is validated and type safe!
const data = User.parse(input);
// so you can use it with confidence :)
console.log(data.name);
```
<br/>
## Features
- Zero external dependencies
- Works in Node.js and all modern browsers
- Tiny: `2kb` core bundle (gzipped)
- Immutable API: methods return a new instance
- Concise interface
- Works with TypeScript and plain JS
- Built-in JSON Schema conversion
- Extensive ecosystem
<br/>
## Installation
```sh
npm install zod
```
<br/>
## Basic usage
Before you can do anything else, you need to define a schema. For the purposes of this guide, we'll use a simple object schema.
```ts
import * as z from "zod/v4";
const Player = z.object({
username: z.string(),
xp: z.number(),
});
```
### Parsing data
Given any Zod schema, use `.parse` to validate an input. If it's valid, Zod returns a strongly-typed _deep clone_ of the input.
```ts
Player.parse({ username: "billie", xp: 100 });
// => returns { username: "billie", xp: 100 }
```
**Note** — If your schema uses certain asynchronous APIs like `async` [refinements](#refine) or [transforms](#transform), you'll need to use the `.parseAsync()` method instead.
```ts
const schema = z.string().refine(async (val) => val.length <= 8);
await schema.parseAsync("hello");
// => "hello"
```
### Handling errors
When validation fails, the `.parse()` method will throw a `ZodError` instance with granular information about the validation issues.
```ts
try {
Player.parse({ username: 42, xp: "100" });
} catch (err) {
if (err instanceof z.ZodError) {
err.issues;
/* [
{
expected: 'string',
code: 'invalid_type',
path: [ 'username' ],
message: 'Invalid input: expected string'
},
{
expected: 'number',
code: 'invalid_type',
path: [ 'xp' ],
message: 'Invalid input: expected number'
}
] */
}
}
```
To avoid a `try/catch` block, you can use the `.safeParse()` method to get back a plain result object containing either the successfully parsed data or a `ZodError`. The result type is a [discriminated union](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions), so you can handle both cases conveniently.
```ts
const result = Player.safeParse({ username: 42, xp: "100" });
if (!result.success) {
result.error; // ZodError instance
} else {
result.data; // { username: string; xp: number }
}
```
**Note** — If your schema uses certain asynchronous APIs like `async` [refinements](#refine) or [transforms](#transform), you'll need to use the `.safeParseAsync()` method instead.
```ts
const schema = z.string().refine(async (val) => val.length <= 8);
await schema.safeParseAsync("hello");
// => { success: true; data: "hello" }
```
### Inferring types
Zod infers a static type from your schema definitions. You can extract this type with the `z.infer<>` utility and use it however you like.
```ts
const Player = z.object({
username: z.string(),
xp: z.number(),
});
// extract the inferred type
type Player = z.infer<typeof Player>;
// use it in your code
const player: Player = { username: "billie", xp: 100 };
```
In some cases, the input & output types of a schema can diverge. For instance, the `.transform()` API can convert the input from one type to another. In these cases, you can extract the input and output types independently:
```ts
const mySchema = z.string().transform((val) => val.length);
type MySchemaIn = z.input<typeof mySchema>;
// => string
type MySchemaOut = z.output<typeof mySchema>; // equivalent to z.infer<typeof mySchema>
// number
```
+14
View File
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 13cc108437a454d7db2a4963cf5106a0
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/README.md
uploadId: 920982
+33
View File
@@ -0,0 +1,33 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.z = void 0;
const z = __importStar(require("./v3/external.cjs"));
exports.z = z;
__exportStar(require("./v3/external.cjs"), exports);
exports.default = z;
+14
View File
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 3b1c2e172d7d141c3a4685fd97d45d8a
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/index.cjs
uploadId: 920982
+4
View File
@@ -0,0 +1,4 @@
import * as z from "./v3/external.cjs";
export * from "./v3/external.cjs";
export { z };
export default z;
+14
View File
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: c21045a0d50db4b758784900938363a8
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/index.d.cts
uploadId: 920982
+4
View File
@@ -0,0 +1,4 @@
import * as z from "./v3/external.js";
export * from "./v3/external.js";
export { z };
export default z;
+14
View File
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: b85a221ad0a44402d85692c3b47e1232
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/index.d.ts
uploadId: 920982
+4
View File
@@ -0,0 +1,4 @@
import * as z from "./v3/external.js";
export * from "./v3/external.js";
export { z };
export default z;
+14
View File
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 38b6d5af71bc5450b810ec04fb62ae4d
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/index.js
uploadId: 920982
+118
View File
@@ -0,0 +1,118 @@
{
"name": "zod",
"version": "3.25.76",
"type": "module",
"author": "Colin McDonnell <zod@colinhacks.com>",
"description": "TypeScript-first schema declaration and validation library with static type inference",
"files": [
"src",
"**/*.js",
"**/*.mjs",
"**/*.cjs",
"**/*.d.ts",
"**/*.d.mts",
"**/*.d.cts"
],
"funding": "https://github.com/sponsors/colinhacks",
"homepage": "https://zod.dev",
"keywords": [
"typescript",
"schema",
"validation",
"type",
"inference"
],
"license": "MIT",
"sideEffects": false,
"main": "./index.cjs",
"types": "./index.d.cts",
"module": "./index.js",
"zshy": {
"exports": {
"./package.json": "./package.json",
".": "./src/index.ts",
"./v3": "./src/v3/index.ts",
"./v4": "./src/v4/index.ts",
"./v4-mini": "./src/v4-mini/index.ts",
"./v4/mini": "./src/v4/mini/index.ts",
"./v4/core": "./src/v4/core/index.ts",
"./v4/locales": "./src/v4/locales/index.ts",
"./v4/locales/*": "./src/v4/locales/*"
},
"sourceDialects": [
"@zod/source"
]
},
"exports": {
"./package.json": "./package.json",
".": {
"@zod/source": "./src/index.ts",
"types": "./index.d.cts",
"import": "./index.js",
"require": "./index.cjs"
},
"./v3": {
"@zod/source": "./src/v3/index.ts",
"types": "./v3/index.d.cts",
"import": "./v3/index.js",
"require": "./v3/index.cjs"
},
"./v4": {
"@zod/source": "./src/v4/index.ts",
"types": "./v4/index.d.cts",
"import": "./v4/index.js",
"require": "./v4/index.cjs"
},
"./v4-mini": {
"@zod/source": "./src/v4-mini/index.ts",
"types": "./v4-mini/index.d.cts",
"import": "./v4-mini/index.js",
"require": "./v4-mini/index.cjs"
},
"./v4/mini": {
"@zod/source": "./src/v4/mini/index.ts",
"types": "./v4/mini/index.d.cts",
"import": "./v4/mini/index.js",
"require": "./v4/mini/index.cjs"
},
"./v4/core": {
"@zod/source": "./src/v4/core/index.ts",
"types": "./v4/core/index.d.cts",
"import": "./v4/core/index.js",
"require": "./v4/core/index.cjs"
},
"./v4/locales": {
"@zod/source": "./src/v4/locales/index.ts",
"types": "./v4/locales/index.d.cts",
"import": "./v4/locales/index.js",
"require": "./v4/locales/index.cjs"
},
"./v4/locales/*": {
"@zod/source": "./src/v4/locales/*",
"types": "./v4/locales/*",
"import": "./v4/locales/*",
"require": "./v4/locales/*"
}
},
"repository": {
"type": "git",
"url": "git+https://github.com/colinhacks/zod.git"
},
"bugs": {
"url": "https://github.com/colinhacks/zod/issues"
},
"support": {
"backing": {
"npm-funding": true
}
},
"scripts": {
"clean": "git clean -xdf . -e node_modules",
"build": "zshy --project tsconfig.build.json",
"postbuild": "pnpm biome check --write .",
"test:watch": "pnpm vitest",
"test": "pnpm vitest run",
"bump:beta": "pnpm version \"v$(pnpm pkg get version | jq -r)-beta.$(date +%Y%m%dT%H%M%S)\"",
"pub:beta": "pnpm bump:beta && pnpm publish --tag next --publish-branch v4 --no-git-checks --dry-run"
}
}
+14
View File
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 4151151691e3a46138ac1c341fbba5b4
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/package.json
uploadId: 920982
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 584be45115d0e4af78b34314bb3719f7
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+4
View File
@@ -0,0 +1,4 @@
import * as z from "./v3/external.js";
export * from "./v3/external.js";
export { z };
export default z;
+14
View File
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 4c41bad7dd5874bdc9ca6560da202b33
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/index.ts
uploadId: 920982
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 07cc27bd031ec406392e232f89605dd1
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+330
View File
@@ -0,0 +1,330 @@
import type { Primitive } from "./helpers/typeAliases.js";
import { util, type ZodParsedType } from "./helpers/util.js";
import type { TypeOf, ZodType } from "./index.js";
type allKeys<T> = T extends any ? keyof T : never;
export type inferFlattenedErrors<T extends ZodType<any, any, any>, U = string> = typeToFlattenedError<TypeOf<T>, U>;
export type typeToFlattenedError<T, U = string> = {
formErrors: U[];
fieldErrors: {
[P in allKeys<T>]?: U[];
};
};
export const ZodIssueCode = util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite",
]);
export type ZodIssueCode = keyof typeof ZodIssueCode;
export type ZodIssueBase = {
path: (string | number)[];
message?: string | undefined;
};
export interface ZodInvalidTypeIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_type;
expected: ZodParsedType;
received: ZodParsedType;
}
export interface ZodInvalidLiteralIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_literal;
expected: unknown;
received: unknown;
}
export interface ZodUnrecognizedKeysIssue extends ZodIssueBase {
code: typeof ZodIssueCode.unrecognized_keys;
keys: string[];
}
export interface ZodInvalidUnionIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_union;
unionErrors: ZodError[];
}
export interface ZodInvalidUnionDiscriminatorIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_union_discriminator;
options: Primitive[];
}
export interface ZodInvalidEnumValueIssue extends ZodIssueBase {
received: string | number;
code: typeof ZodIssueCode.invalid_enum_value;
options: (string | number)[];
}
export interface ZodInvalidArgumentsIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_arguments;
argumentsError: ZodError;
}
export interface ZodInvalidReturnTypeIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_return_type;
returnTypeError: ZodError;
}
export interface ZodInvalidDateIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_date;
}
export type StringValidation =
| "email"
| "url"
| "emoji"
| "uuid"
| "nanoid"
| "regex"
| "cuid"
| "cuid2"
| "ulid"
| "datetime"
| "date"
| "time"
| "duration"
| "ip"
| "cidr"
| "base64"
| "jwt"
| "base64url"
| { includes: string; position?: number | undefined }
| { startsWith: string }
| { endsWith: string };
export interface ZodInvalidStringIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_string;
validation: StringValidation;
}
export interface ZodTooSmallIssue extends ZodIssueBase {
code: typeof ZodIssueCode.too_small;
minimum: number | bigint;
inclusive: boolean;
exact?: boolean;
type: "array" | "string" | "number" | "set" | "date" | "bigint";
}
export interface ZodTooBigIssue extends ZodIssueBase {
code: typeof ZodIssueCode.too_big;
maximum: number | bigint;
inclusive: boolean;
exact?: boolean;
type: "array" | "string" | "number" | "set" | "date" | "bigint";
}
export interface ZodInvalidIntersectionTypesIssue extends ZodIssueBase {
code: typeof ZodIssueCode.invalid_intersection_types;
}
export interface ZodNotMultipleOfIssue extends ZodIssueBase {
code: typeof ZodIssueCode.not_multiple_of;
multipleOf: number | bigint;
}
export interface ZodNotFiniteIssue extends ZodIssueBase {
code: typeof ZodIssueCode.not_finite;
}
export interface ZodCustomIssue extends ZodIssueBase {
code: typeof ZodIssueCode.custom;
params?: { [k: string]: any };
}
export type DenormalizedError = { [k: string]: DenormalizedError | string[] };
export type ZodIssueOptionalMessage =
| ZodInvalidTypeIssue
| ZodInvalidLiteralIssue
| ZodUnrecognizedKeysIssue
| ZodInvalidUnionIssue
| ZodInvalidUnionDiscriminatorIssue
| ZodInvalidEnumValueIssue
| ZodInvalidArgumentsIssue
| ZodInvalidReturnTypeIssue
| ZodInvalidDateIssue
| ZodInvalidStringIssue
| ZodTooSmallIssue
| ZodTooBigIssue
| ZodInvalidIntersectionTypesIssue
| ZodNotMultipleOfIssue
| ZodNotFiniteIssue
| ZodCustomIssue;
export type ZodIssue = ZodIssueOptionalMessage & {
fatal?: boolean | undefined;
message: string;
};
export const quotelessJson = (obj: any) => {
const json = JSON.stringify(obj, null, 2);
return json.replace(/"([^"]+)":/g, "$1:");
};
type recursiveZodFormattedError<T> = T extends [any, ...any[]]
? { [K in keyof T]?: ZodFormattedError<T[K]> }
: T extends any[]
? { [k: number]: ZodFormattedError<T[number]> }
: T extends object
? { [K in keyof T]?: ZodFormattedError<T[K]> }
: unknown;
export type ZodFormattedError<T, U = string> = {
_errors: U[];
} & recursiveZodFormattedError<NonNullable<T>>;
export type inferFormattedError<T extends ZodType<any, any, any>, U = string> = ZodFormattedError<TypeOf<T>, U>;
export class ZodError<T = any> extends Error {
issues: ZodIssue[] = [];
get errors() {
return this.issues;
}
constructor(issues: ZodIssue[]) {
super();
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) {
// eslint-disable-next-line ban/ban
Object.setPrototypeOf(this, actualProto);
} else {
(this as any).__proto__ = actualProto;
}
this.name = "ZodError";
this.issues = issues;
}
format(): ZodFormattedError<T>;
format<U>(mapper: (issue: ZodIssue) => U): ZodFormattedError<T, U>;
format(_mapper?: any) {
const mapper: (issue: ZodIssue) => any =
_mapper ||
function (issue: ZodIssue) {
return issue.message;
};
const fieldErrors: ZodFormattedError<T> = { _errors: [] } as any;
const processError = (error: ZodError) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union") {
issue.unionErrors.map(processError);
} else if (issue.code === "invalid_return_type") {
processError(issue.returnTypeError);
} else if (issue.code === "invalid_arguments") {
processError(issue.argumentsError);
} else if (issue.path.length === 0) {
(fieldErrors as any)._errors.push(mapper(issue));
} else {
let curr: any = fieldErrors;
let i = 0;
while (i < issue.path.length) {
const el = issue.path[i]!;
const terminal = i === issue.path.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
// if (typeof el === "string") {
// curr[el] = curr[el] || { _errors: [] };
// } else if (typeof el === "number") {
// const errorArray: any = [];
// errorArray._errors = [];
// curr[el] = curr[el] || errorArray;
// }
} else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
}
}
};
processError(this);
return fieldErrors;
}
static create = (issues: ZodIssue[]) => {
const error = new ZodError(issues);
return error;
};
static assert(value: unknown): asserts value is ZodError {
if (!(value instanceof ZodError)) {
throw new Error(`Not a ZodError: ${value}`);
}
}
override toString() {
return this.message;
}
override get message() {
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
}
get isEmpty(): boolean {
return this.issues.length === 0;
}
addIssue = (sub: ZodIssue) => {
this.issues = [...this.issues, sub];
};
addIssues = (subs: ZodIssue[] = []) => {
this.issues = [...this.issues, ...subs];
};
flatten(): typeToFlattenedError<T>;
flatten<U>(mapper?: (issue: ZodIssue) => U): typeToFlattenedError<T, U>;
flatten<U = string>(mapper: (issue: ZodIssue) => U = (issue: ZodIssue) => issue.message as any): any {
const fieldErrors: any = {};
const formErrors: U[] = [];
for (const sub of this.issues) {
if (sub.path.length > 0) {
const firstEl = sub.path[0]!;
fieldErrors[firstEl] = fieldErrors[firstEl] || [];
fieldErrors[firstEl].push(mapper(sub));
} else {
formErrors.push(mapper(sub));
}
}
return { formErrors, fieldErrors };
}
get formErrors() {
return this.flatten();
}
}
type stripPath<T extends object> = T extends any ? util.OmitKeys<T, "path"> : never;
export type IssueData = stripPath<ZodIssueOptionalMessage> & {
path?: (string | number)[];
fatal?: boolean | undefined;
};
export type ErrorMapCtx = {
defaultError: string;
data: any;
};
export type ZodErrorMap = (issue: ZodIssueOptionalMessage, _ctx: ErrorMapCtx) => { message: string };
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: c21319f6f82d740e7aa4e8de0ee4c646
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/ZodError.ts
uploadId: 920982
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ab0bc0135708e49fb9d9a55ff149b67b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,58 @@
import Benchmark from "benchmark";
const datetimeValidationSuite = new Benchmark.Suite("datetime");
const DATA = "2021-01-01";
const MONTHS_31 = new Set([1, 3, 5, 7, 8, 10, 12]);
const MONTHS_30 = new Set([4, 6, 9, 11]);
const simpleDatetimeRegex = /^(\d{4})-(\d{2})-(\d{2})$/;
const datetimeRegexNoLeapYearValidation =
/^\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\d|2\d))$/;
const datetimeRegexWithLeapYearValidation =
/^((\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\d|3[01])|(0[469]|11)-(0[1-9]|[12]\d|30)|(02)-(0[1-9]|1\d|2[0-8])))$/;
datetimeValidationSuite
.add("new Date()", () => {
return !Number.isNaN(new Date(DATA).getTime());
})
.add("regex (no validation)", () => {
return simpleDatetimeRegex.test(DATA);
})
.add("regex (no leap year)", () => {
return datetimeRegexNoLeapYearValidation.test(DATA);
})
.add("regex (w/ leap year)", () => {
return datetimeRegexWithLeapYearValidation.test(DATA);
})
.add("capture groups + code", () => {
const match = DATA.match(simpleDatetimeRegex);
if (!match) return false;
// Extract year, month, and day from the capture groups
const year = Number.parseInt(match[1], 10);
const month = Number.parseInt(match[2], 10); // month is 0-indexed in JavaScript Date, so subtract 1
const day = Number.parseInt(match[3], 10);
if (month === 2) {
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
return day <= 29;
}
return day <= 28;
}
if (MONTHS_30.has(month)) {
return day <= 30;
}
if (MONTHS_31.has(month)) {
return day <= 31;
}
return false;
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${datetimeValidationSuite.name!}: ${e.target}`);
});
export default {
suites: [datetimeValidationSuite],
};
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 40b6ce99cbf974b778a82aa36bdbcf35
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/benchmarks/datetime.ts
uploadId: 920982
@@ -0,0 +1,80 @@
import Benchmark from "benchmark";
import { z } from "zod/v3";
const doubleSuite = new Benchmark.Suite("z.discriminatedUnion: double");
const manySuite = new Benchmark.Suite("z.discriminatedUnion: many");
const aSchema = z.object({
type: z.literal("a"),
});
const objA = {
type: "a",
};
const bSchema = z.object({
type: z.literal("b"),
});
const objB = {
type: "b",
};
const cSchema = z.object({
type: z.literal("c"),
});
const objC = {
type: "c",
};
const dSchema = z.object({
type: z.literal("d"),
});
const double = z.discriminatedUnion("type", [aSchema, bSchema]);
const many = z.discriminatedUnion("type", [aSchema, bSchema, cSchema, dSchema]);
doubleSuite
.add("valid: a", () => {
double.parse(objA);
})
.add("valid: b", () => {
double.parse(objB);
})
.add("invalid: null", () => {
try {
double.parse(null);
} catch (_err) {}
})
.add("invalid: wrong shape", () => {
try {
double.parse(objC);
} catch (_err) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${(doubleSuite as any).name}: ${e.target}`);
});
manySuite
.add("valid: a", () => {
many.parse(objA);
})
.add("valid: c", () => {
many.parse(objC);
})
.add("invalid: null", () => {
try {
many.parse(null);
} catch (_err) {}
})
.add("invalid: wrong shape", () => {
try {
many.parse({ type: "unknown" });
} catch (_err) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${(manySuite as any).name}: ${e.target}`);
});
export default {
suites: [doubleSuite, manySuite],
};
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 0fbda57d5717d4f59a18202b67c70206
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/benchmarks/discriminatedUnion.ts
uploadId: 920982
@@ -0,0 +1,59 @@
import type Benchmark from "benchmark";
import datetimeBenchmarks from "./datetime.js";
import discriminatedUnionBenchmarks from "./discriminatedUnion.js";
import ipv4Benchmarks from "./ipv4.js";
import objectBenchmarks from "./object.js";
import primitiveBenchmarks from "./primitives.js";
import realworld from "./realworld.js";
import stringBenchmarks from "./string.js";
import unionBenchmarks from "./union.js";
const argv = process.argv.slice(2);
let suites: Benchmark.Suite[] = [];
if (!argv.length) {
suites = [
...realworld.suites,
...primitiveBenchmarks.suites,
...stringBenchmarks.suites,
...objectBenchmarks.suites,
...unionBenchmarks.suites,
...discriminatedUnionBenchmarks.suites,
];
} else {
if (argv.includes("--realworld")) {
suites.push(...realworld.suites);
}
if (argv.includes("--primitives")) {
suites.push(...primitiveBenchmarks.suites);
}
if (argv.includes("--string")) {
suites.push(...stringBenchmarks.suites);
}
if (argv.includes("--object")) {
suites.push(...objectBenchmarks.suites);
}
if (argv.includes("--union")) {
suites.push(...unionBenchmarks.suites);
}
if (argv.includes("--discriminatedUnion")) {
suites.push(...datetimeBenchmarks.suites);
}
if (argv.includes("--datetime")) {
suites.push(...datetimeBenchmarks.suites);
}
if (argv.includes("--ipv4")) {
suites.push(...ipv4Benchmarks.suites);
}
}
for (const suite of suites) {
suite.run({});
}
// exit on Ctrl-C
process.on("SIGINT", function () {
console.log("Exiting...");
process.exit();
});
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: b456c42660d544f4da01005cd3251c3b
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/benchmarks/index.ts
uploadId: 920982
@@ -0,0 +1,57 @@
import Benchmark from "benchmark";
const suite = new Benchmark.Suite("ipv4");
const DATA = "127.0.0.1";
const ipv4RegexA =
/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
const ipv4RegexB =
/^(?:(?:(?=(25[0-5]))\1|(?=(2[0-4][0-9]))\2|(?=(1[0-9]{2}))\3|(?=([0-9]{1,2}))\4)\.){3}(?:(?=(25[0-5]))\5|(?=(2[0-4][0-9]))\6|(?=(1[0-9]{2}))\7|(?=([0-9]{1,2}))\8)$/;
const ipv4RegexC = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
const ipv4RegexD = /^(\b25[0-5]|\b2[0-4][0-9]|\b[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/;
const ipv4RegexE = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.){3}(25[0-5]|(2[0-4]|1\d|[1-9]|)\d)$/;
const ipv4RegexF = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/;
const ipv4RegexG = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)(\.(?!$)|$)){4}$/;
const ipv4RegexH = /^((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\.(?!$)|$)){4}$/;
const ipv4RegexI =
/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
suite
.add("A", () => {
return ipv4RegexA.test(DATA);
})
.add("B", () => {
return ipv4RegexB.test(DATA);
})
.add("C", () => {
return ipv4RegexC.test(DATA);
})
.add("D", () => {
return ipv4RegexD.test(DATA);
})
.add("E", () => {
return ipv4RegexE.test(DATA);
})
.add("F", () => {
return ipv4RegexF.test(DATA);
})
.add("G", () => {
return ipv4RegexG.test(DATA);
})
.add("H", () => {
return ipv4RegexH.test(DATA);
})
.add("I", () => {
return ipv4RegexI.test(DATA);
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${suite.name!}: ${e.target}`);
});
export default {
suites: [suite],
};
if (require.main === module) {
suite.run();
}
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: b1f8dea3f0a914e6ba353191fa808f95
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/benchmarks/ipv4.ts
uploadId: 920982
@@ -0,0 +1,69 @@
import Benchmark from "benchmark";
import { z } from "zod/v3";
const emptySuite = new Benchmark.Suite("z.object: empty");
const shortSuite = new Benchmark.Suite("z.object: short");
const longSuite = new Benchmark.Suite("z.object: long");
const empty = z.object({});
const short = z.object({
string: z.string(),
});
const long = z.object({
string: z.string(),
number: z.number(),
boolean: z.boolean(),
});
emptySuite
.add("valid", () => {
empty.parse({});
})
.add("valid: extra keys", () => {
empty.parse({ string: "string" });
})
.add("invalid: null", () => {
try {
empty.parse(null);
} catch (_err) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${(emptySuite as any).name}: ${e.target}`);
});
shortSuite
.add("valid", () => {
short.parse({ string: "string" });
})
.add("valid: extra keys", () => {
short.parse({ string: "string", number: 42 });
})
.add("invalid: null", () => {
try {
short.parse(null);
} catch (_err) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${(shortSuite as any).name}: ${e.target}`);
});
longSuite
.add("valid", () => {
long.parse({ string: "string", number: 42, boolean: true });
})
.add("valid: extra keys", () => {
long.parse({ string: "string", number: 42, boolean: true, list: [] });
})
.add("invalid: null", () => {
try {
long.parse(null);
} catch (_err) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${(longSuite as any).name}: ${e.target}`);
});
export default {
suites: [emptySuite, shortSuite, longSuite],
};
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: fd42beb0df6b04f049781775e2dbde28
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/benchmarks/object.ts
uploadId: 920982
@@ -0,0 +1,162 @@
import Benchmark from "benchmark";
import { z } from "zod/v3";
import { Mocker } from "../tests/Mocker.js";
const val = new Mocker();
const enumSuite = new Benchmark.Suite("z.enum");
const enumSchema = z.enum(["a", "b", "c"]);
enumSuite
.add("valid", () => {
enumSchema.parse("a");
})
.add("invalid", () => {
try {
enumSchema.parse("x");
} catch (_e: any) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`z.enum: ${e.target}`);
});
const longEnumSuite = new Benchmark.Suite("long z.enum");
const longEnumSchema = z.enum([
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
]);
longEnumSuite
.add("valid", () => {
longEnumSchema.parse("five");
})
.add("invalid", () => {
try {
longEnumSchema.parse("invalid");
} catch (_e: any) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`long z.enum: ${e.target}`);
});
const undefinedSuite = new Benchmark.Suite("z.undefined");
const undefinedSchema = z.undefined();
undefinedSuite
.add("valid", () => {
undefinedSchema.parse(undefined);
})
.add("invalid", () => {
try {
undefinedSchema.parse(1);
} catch (_e: any) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`z.undefined: ${e.target}`);
});
const literalSuite = new Benchmark.Suite("z.literal");
const short = "short";
const bad = "bad";
const literalSchema = z.literal("short");
literalSuite
.add("valid", () => {
literalSchema.parse(short);
})
.add("invalid", () => {
try {
literalSchema.parse(bad);
} catch (_e: any) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`z.literal: ${e.target}`);
});
const numberSuite = new Benchmark.Suite("z.number");
const numberSchema = z.number().int();
numberSuite
.add("valid", () => {
numberSchema.parse(1);
})
.add("invalid type", () => {
try {
numberSchema.parse("bad");
} catch (_e: any) {}
})
.add("invalid number", () => {
try {
numberSchema.parse(0.5);
} catch (_e: any) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`z.number: ${e.target}`);
});
const dateSuite = new Benchmark.Suite("z.date");
const plainDate = z.date();
const minMaxDate = z.date().min(new Date("2021-01-01")).max(new Date("2030-01-01"));
dateSuite
.add("valid", () => {
plainDate.parse(new Date());
})
.add("invalid", () => {
try {
plainDate.parse(1);
} catch (_e: any) {}
})
.add("valid min and max", () => {
minMaxDate.parse(new Date("2023-01-01"));
})
.add("invalid min", () => {
try {
minMaxDate.parse(new Date("2019-01-01"));
} catch (_e: any) {}
})
.add("invalid max", () => {
try {
minMaxDate.parse(new Date("2031-01-01"));
} catch (_e: any) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`z.date: ${e.target}`);
});
const symbolSuite = new Benchmark.Suite("z.symbol");
const symbolSchema = z.symbol();
symbolSuite
.add("valid", () => {
symbolSchema.parse(val.symbol);
})
.add("invalid", () => {
try {
symbolSchema.parse(1);
} catch (_e: any) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`z.symbol: ${e.target}`);
});
export default {
suites: [enumSuite, longEnumSuite, undefinedSuite, literalSuite, numberSuite, dateSuite, symbolSuite],
};
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 9e9d4843efd104db49e2c42338a428e0
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/benchmarks/primitives.ts
uploadId: 920982
@@ -0,0 +1,63 @@
import Benchmark from "benchmark";
import { z } from "zod/v3";
const shortSuite = new Benchmark.Suite("realworld");
const People = z.array(
z.object({
type: z.literal("person"),
hair: z.enum(["blue", "brown"]),
active: z.boolean(),
name: z.string(),
age: z.number().int(),
hobbies: z.array(z.string()),
address: z.object({
street: z.string(),
zip: z.string(),
country: z.string(),
}),
})
);
let i = 0;
function num() {
return ++i;
}
function str() {
return (++i % 100).toString(16);
}
function array<T>(fn: () => T): T[] {
return Array.from({ length: ++i % 10 }, () => fn());
}
const people = Array.from({ length: 100 }, () => {
return {
type: "person",
hair: i % 2 ? "blue" : "brown",
active: !!(i % 2),
name: str(),
age: num(),
hobbies: array(str),
address: {
street: str(),
zip: str(),
country: str(),
},
};
});
shortSuite
.add("valid", () => {
People.parse(people);
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${(shortSuite as any).name}: ${e.target}`);
});
export default {
suites: [shortSuite],
};
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 36ac6ac69e94341ea95d143902cf7f59
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/benchmarks/realworld.ts
uploadId: 920982
@@ -0,0 +1,55 @@
import Benchmark from "benchmark";
import { z } from "zod/v3";
const SUITE_NAME = "z.string";
const suite = new Benchmark.Suite(SUITE_NAME);
const empty = "";
const short = "short";
const long = "long".repeat(256);
const manual = (str: unknown) => {
if (typeof str !== "string") {
throw new Error("Not a string");
}
return str;
};
const stringSchema = z.string();
const optionalStringSchema = z.string().optional();
const optionalNullableStringSchema = z.string().optional().nullable();
suite
.add("empty string", () => {
stringSchema.parse(empty);
})
.add("short string", () => {
stringSchema.parse(short);
})
.add("long string", () => {
stringSchema.parse(long);
})
.add("optional string", () => {
optionalStringSchema.parse(long);
})
.add("nullable string", () => {
optionalNullableStringSchema.parse(long);
})
.add("nullable (null) string", () => {
optionalNullableStringSchema.parse(null);
})
.add("invalid: null", () => {
try {
stringSchema.parse(null);
} catch (_err) {}
})
.add("manual parser: long", () => {
manual(long);
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${SUITE_NAME}: ${e.target}`);
});
export default {
suites: [suite],
};
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: c84839bced9d247358ebd551f785ed76
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/benchmarks/string.ts
uploadId: 920982
@@ -0,0 +1,80 @@
import Benchmark from "benchmark";
import { z } from "zod/v3";
const doubleSuite = new Benchmark.Suite("z.union: double");
const manySuite = new Benchmark.Suite("z.union: many");
const aSchema = z.object({
type: z.literal("a"),
});
const objA = {
type: "a",
};
const bSchema = z.object({
type: z.literal("b"),
});
const objB = {
type: "b",
};
const cSchema = z.object({
type: z.literal("c"),
});
const objC = {
type: "c",
};
const dSchema = z.object({
type: z.literal("d"),
});
const double = z.union([aSchema, bSchema]);
const many = z.union([aSchema, bSchema, cSchema, dSchema]);
doubleSuite
.add("valid: a", () => {
double.parse(objA);
})
.add("valid: b", () => {
double.parse(objB);
})
.add("invalid: null", () => {
try {
double.parse(null);
} catch (_err) {}
})
.add("invalid: wrong shape", () => {
try {
double.parse(objC);
} catch (_err) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${(doubleSuite as any).name}: ${e.target}`);
});
manySuite
.add("valid: a", () => {
many.parse(objA);
})
.add("valid: c", () => {
many.parse(objC);
})
.add("invalid: null", () => {
try {
many.parse(null);
} catch (_err) {}
})
.add("invalid: wrong shape", () => {
try {
many.parse({ type: "unknown" });
} catch (_err) {}
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${(manySuite as any).name}: ${e.target}`);
});
export default {
suites: [doubleSuite, manySuite],
};
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: ee902e4609bab43578265c53951fe20e
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/benchmarks/union.ts
uploadId: 920982
+13
View File
@@ -0,0 +1,13 @@
import type { ZodErrorMap } from "./ZodError.js";
import defaultErrorMap from "./locales/en.js";
let overrideErrorMap = defaultErrorMap;
export { defaultErrorMap };
export function setErrorMap(map: ZodErrorMap) {
overrideErrorMap = map;
}
export function getErrorMap() {
return overrideErrorMap;
}
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: b09a76af4953647d88f9480824797d72
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/errors.ts
uploadId: 920982
+6
View File
@@ -0,0 +1,6 @@
export * from "./errors.js";
export * from "./helpers/parseUtil.js";
export * from "./helpers/typeAliases.js";
export * from "./helpers/util.js";
export * from "./types.js";
export * from "./ZodError.js";
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 2b6a77121ec7a4872a29c242e71ee8dc
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/external.ts
uploadId: 920982
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8fe40a81bd153476b85f3a6750e6c649
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,17 @@
export namespace enumUtil {
type UnionToIntersectionFn<T> = (T extends unknown ? (k: () => T) => void : never) extends (
k: infer Intersection
) => void
? Intersection
: never;
type GetUnionLast<T> = UnionToIntersectionFn<T> extends () => infer Last ? Last : never;
type UnionToTuple<T, Tuple extends unknown[] = []> = [T] extends [never]
? Tuple
: UnionToTuple<Exclude<T, GetUnionLast<T>>, [GetUnionLast<T>, ...Tuple]>;
type CastToStringTuple<T> = T extends [string, ...string[]] ? T : never;
export type UnionToTupleString<T> = CastToStringTuple<UnionToTuple<T>>;
}
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: ec1638b94c22d4adf998650b71135721
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/helpers/enumUtil.ts
uploadId: 920982
@@ -0,0 +1,8 @@
export namespace errorUtil {
export type ErrMessage = string | { message?: string | undefined };
export const errToObj = (message?: ErrMessage): { message?: string | undefined } =>
typeof message === "string" ? { message } : message || {};
// biome-ignore lint:
export const toString = (message?: ErrMessage): string | undefined =>
typeof message === "string" ? message : message?.message;
}
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 8a61d22fb3e0242099592fcb963d2532
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/helpers/errorUtil.ts
uploadId: 920982
@@ -0,0 +1,176 @@
import type { IssueData, ZodErrorMap, ZodIssue } from "../ZodError.js";
import { getErrorMap } from "../errors.js";
import defaultErrorMap from "../locales/en.js";
import type { ZodParsedType } from "./util.js";
export const makeIssue = (params: {
data: any;
path: (string | number)[];
errorMaps: ZodErrorMap[];
issueData: IssueData;
}): ZodIssue => {
const { data, path, errorMaps, issueData } = params;
const fullPath = [...path, ...(issueData.path || [])];
const fullIssue = {
...issueData,
path: fullPath,
};
if (issueData.message !== undefined) {
return {
...issueData,
path: fullPath,
message: issueData.message,
};
}
let errorMessage = "";
const maps = errorMaps
.filter((m) => !!m)
.slice()
.reverse();
for (const map of maps) {
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
}
return {
...issueData,
path: fullPath,
message: errorMessage,
};
};
export type ParseParams = {
path: (string | number)[];
errorMap: ZodErrorMap;
async: boolean;
};
export type ParsePathComponent = string | number;
export type ParsePath = ParsePathComponent[];
export const EMPTY_PATH: ParsePath = [];
export interface ParseContext {
readonly common: {
readonly issues: ZodIssue[];
readonly contextualErrorMap?: ZodErrorMap | undefined;
readonly async: boolean;
};
readonly path: ParsePath;
readonly schemaErrorMap?: ZodErrorMap | undefined;
readonly parent: ParseContext | null;
readonly data: any;
readonly parsedType: ZodParsedType;
}
export type ParseInput = {
data: any;
path: (string | number)[];
parent: ParseContext;
};
export function addIssueToContext(ctx: ParseContext, issueData: IssueData): void {
const overrideMap = getErrorMap();
const issue = makeIssue({
issueData: issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap, // contextual error map is first priority
ctx.schemaErrorMap, // then schema-bound map if available
overrideMap, // then global override map
overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map
].filter((x) => !!x),
});
ctx.common.issues.push(issue);
}
export type ObjectPair = {
key: SyncParseReturnType<any>;
value: SyncParseReturnType<any>;
};
export class ParseStatus {
value: "aborted" | "dirty" | "valid" = "valid";
dirty(): void {
if (this.value === "valid") this.value = "dirty";
}
abort(): void {
if (this.value !== "aborted") this.value = "aborted";
}
static mergeArray(status: ParseStatus, results: SyncParseReturnType<any>[]): SyncParseReturnType {
const arrayValue: any[] = [];
for (const s of results) {
if (s.status === "aborted") return INVALID;
if (s.status === "dirty") status.dirty();
arrayValue.push(s.value);
}
return { status: status.value, value: arrayValue };
}
static async mergeObjectAsync(
status: ParseStatus,
pairs: { key: ParseReturnType<any>; value: ParseReturnType<any> }[]
): Promise<SyncParseReturnType<any>> {
const syncPairs: ObjectPair[] = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value,
});
}
return ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(
status: ParseStatus,
pairs: {
key: SyncParseReturnType<any>;
value: SyncParseReturnType<any>;
alwaysSet?: boolean;
}[]
): SyncParseReturnType {
const finalObject: any = {};
for (const pair of pairs) {
const { key, value } = pair;
if (key.status === "aborted") return INVALID;
if (value.status === "aborted") return INVALID;
if (key.status === "dirty") status.dirty();
if (value.status === "dirty") status.dirty();
if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
finalObject[key.value] = value.value;
}
}
return { status: status.value, value: finalObject };
}
}
export interface ParseResult {
status: "aborted" | "dirty" | "valid";
data: any;
}
export type INVALID = { status: "aborted" };
export const INVALID: INVALID = Object.freeze({
status: "aborted",
});
export type DIRTY<T> = { status: "dirty"; value: T };
export const DIRTY = <T>(value: T): DIRTY<T> => ({ status: "dirty", value });
export type OK<T> = { status: "valid"; value: T };
export const OK = <T>(value: T): OK<T> => ({ status: "valid", value });
export type SyncParseReturnType<T = any> = OK<T> | DIRTY<T> | INVALID;
export type AsyncParseReturnType<T> = Promise<SyncParseReturnType<T>>;
export type ParseReturnType<T> = SyncParseReturnType<T> | AsyncParseReturnType<T>;
export const isAborted = (x: ParseReturnType<any>): x is INVALID => (x as any).status === "aborted";
export const isDirty = <T>(x: ParseReturnType<T>): x is OK<T> | DIRTY<T> => (x as any).status === "dirty";
export const isValid = <T>(x: ParseReturnType<T>): x is OK<T> => (x as any).status === "valid";
export const isAsync = <T>(x: ParseReturnType<T>): x is AsyncParseReturnType<T> =>
typeof Promise !== "undefined" && x instanceof Promise;
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: ddfbcbd7e97dd4c2b9804d2db107a44b
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/helpers/parseUtil.ts
uploadId: 920982
@@ -0,0 +1,34 @@
import type {
ZodArray,
ZodNullable,
ZodObject,
ZodOptional,
ZodRawShape,
ZodTuple,
ZodTupleItems,
ZodTypeAny,
} from "../types.js";
export namespace partialUtil {
export type DeepPartial<T extends ZodTypeAny> = T extends ZodObject<ZodRawShape>
? ZodObject<
{ [k in keyof T["shape"]]: ZodOptional<DeepPartial<T["shape"][k]>> },
T["_def"]["unknownKeys"],
T["_def"]["catchall"]
>
: T extends ZodArray<infer Type, infer Card>
? ZodArray<DeepPartial<Type>, Card>
: T extends ZodOptional<infer Type>
? ZodOptional<DeepPartial<Type>>
: T extends ZodNullable<infer Type>
? ZodNullable<DeepPartial<Type>>
: T extends ZodTuple<infer Items>
? {
[k in keyof Items]: Items[k] extends ZodTypeAny ? DeepPartial<Items[k]> : never;
} extends infer PI
? PI extends ZodTupleItems
? ZodTuple<PI>
: never
: never
: T;
}
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: c3d8e8907dde14b1abb576559862ac9f
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/helpers/partialUtil.ts
uploadId: 920982
@@ -0,0 +1,2 @@
export type Primitive = string | number | symbol | bigint | boolean | null | undefined;
export type Scalars = Primitive | Primitive[];
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: ab5c7bc2ab8ca4849856fcebdc145eb6
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/helpers/typeAliases.ts
uploadId: 920982
@@ -0,0 +1,224 @@
export namespace util {
type AssertEqual<T, U> = (<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2 ? true : false;
export type isAny<T> = 0 extends 1 & T ? true : false;
export const assertEqual = <A, B>(_: AssertEqual<A, B>): void => {};
export function assertIs<T>(_arg: T): void {}
export function assertNever(_x: never): never {
throw new Error();
}
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export type OmitKeys<T, K extends string> = Pick<T, Exclude<keyof T, K>>;
export type MakePartial<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
export type Exactly<T, X> = T & Record<Exclude<keyof X, keyof T>, never>;
export type InexactPartial<T> = { [k in keyof T]?: T[k] | undefined };
export const arrayToEnum = <T extends string, U extends [T, ...T[]]>(items: U): { [k in U[number]]: k } => {
const obj: any = {};
for (const item of items) {
obj[item] = item;
}
return obj;
};
export const getValidEnumValues = (obj: any): any[] => {
const validKeys = objectKeys(obj).filter((k: any) => typeof obj[obj[k]] !== "number");
const filtered: any = {};
for (const k of validKeys) {
filtered[k] = obj[k];
}
return objectValues(filtered);
};
export const objectValues = (obj: any): any[] => {
return objectKeys(obj).map(function (e) {
return obj[e];
});
};
export const objectKeys: ObjectConstructor["keys"] =
typeof Object.keys === "function" // eslint-disable-line ban/ban
? (obj: any) => Object.keys(obj) // eslint-disable-line ban/ban
: (object: any) => {
const keys = [];
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
keys.push(key);
}
}
return keys;
};
export const find = <T>(arr: T[], checker: (arg: T) => any): T | undefined => {
for (const item of arr) {
if (checker(item)) return item;
}
return undefined;
};
export type identity<T> = objectUtil.identity<T>;
export type flatten<T> = objectUtil.flatten<T>;
export type noUndefined<T> = T extends undefined ? never : T;
export const isInteger: NumberConstructor["isInteger"] =
typeof Number.isInteger === "function"
? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
: (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
export function joinValues<T extends any[]>(array: T, separator = " | "): string {
return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator);
}
export const jsonStringifyReplacer = (_: string, value: any): any => {
if (typeof value === "bigint") {
return value.toString();
}
return value;
};
}
export namespace objectUtil {
export type MergeShapes<U, V> =
// fast path when there is no keys overlap
keyof U & keyof V extends never
? U & V
: {
[k in Exclude<keyof U, keyof V>]: U[k];
} & V;
type optionalKeys<T extends object> = {
[k in keyof T]: undefined extends T[k] ? k : never;
}[keyof T];
type requiredKeys<T extends object> = {
[k in keyof T]: undefined extends T[k] ? never : k;
}[keyof T];
export type addQuestionMarks<T extends object, _O = any> = {
[K in requiredKeys<T>]: T[K];
} & {
[K in optionalKeys<T>]?: T[K];
} & { [k in keyof T]?: unknown };
export type identity<T> = T;
export type flatten<T> = identity<{ [k in keyof T]: T[k] }>;
export type noNeverKeys<T> = {
[k in keyof T]: [T[k]] extends [never] ? never : k;
}[keyof T];
export type noNever<T> = identity<{
[k in noNeverKeys<T>]: k extends keyof T ? T[k] : never;
}>;
export const mergeShapes = <U, T>(first: U, second: T): T & U => {
return {
...first,
...second, // second overwrites first
};
};
export type extendShape<A extends object, B extends object> = keyof A & keyof B extends never // fast path when there is no keys overlap
? A & B
: {
[K in keyof A as K extends keyof B ? never : K]: A[K];
} & {
[K in keyof B]: B[K];
};
}
export const ZodParsedType: {
string: "string";
nan: "nan";
number: "number";
integer: "integer";
float: "float";
boolean: "boolean";
date: "date";
bigint: "bigint";
symbol: "symbol";
function: "function";
undefined: "undefined";
null: "null";
array: "array";
object: "object";
unknown: "unknown";
promise: "promise";
void: "void";
never: "never";
map: "map";
set: "set";
} = util.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set",
]);
export type ZodParsedType = keyof typeof ZodParsedType;
export const getParsedType = (data: any): ZodParsedType => {
const t = typeof data;
switch (t) {
case "undefined":
return ZodParsedType.undefined;
case "string":
return ZodParsedType.string;
case "number":
return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
case "boolean":
return ZodParsedType.boolean;
case "function":
return ZodParsedType.function;
case "bigint":
return ZodParsedType.bigint;
case "symbol":
return ZodParsedType.symbol;
case "object":
if (Array.isArray(data)) {
return ZodParsedType.array;
}
if (data === null) {
return ZodParsedType.null;
}
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
return ZodParsedType.promise;
}
if (typeof Map !== "undefined" && data instanceof Map) {
return ZodParsedType.map;
}
if (typeof Set !== "undefined" && data instanceof Set) {
return ZodParsedType.set;
}
if (typeof Date !== "undefined" && data instanceof Date) {
return ZodParsedType.date;
}
return ZodParsedType.object;
default:
return ZodParsedType.unknown;
}
};
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 209db2b1caa354164beb4926fe648dfb
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/helpers/util.ts
uploadId: 920982
+4
View File
@@ -0,0 +1,4 @@
import * as z from "./external.js";
export * from "./external.js";
export { z };
export default z;
+14
View File
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: a0517969776334d77b06b1ea3d1c575d
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/index.ts
uploadId: 920982
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 9bfbcf7571ed345ddb3f468055a97b5d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+124
View File
@@ -0,0 +1,124 @@
import { type ZodErrorMap, ZodIssueCode } from "../ZodError.js";
import { util, ZodParsedType } from "../helpers/util.js";
const errorMap: ZodErrorMap = (issue, _ctx) => {
let message: string;
switch (issue.code) {
case ZodIssueCode.invalid_type:
if (issue.received === ZodParsedType.undefined) {
message = "Required";
} else {
message = `Expected ${issue.expected}, received ${issue.received}`;
}
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
break;
case ZodIssueCode.invalid_union:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodIssueCode.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodIssueCode.invalid_date:
message = `Invalid date`;
break;
case ZodIssueCode.invalid_string:
if (typeof issue.validation === "object") {
if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;
if (typeof issue.validation.position === "number") {
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
}
} else if ("startsWith" in issue.validation) {
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
} else if ("endsWith" in issue.validation) {
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
} else {
util.assertNever(issue.validation);
}
} else if (issue.validation !== "regex") {
message = `Invalid ${issue.validation}`;
} else {
message = "Invalid";
}
break;
case ZodIssueCode.too_small:
if (issue.type === "array")
message = `Array must contain ${
issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`
} ${issue.minimum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${
issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`
} ${issue.minimum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${
issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `
}${issue.minimum}`;
else if (issue.type === "bigint")
message = `Number must be ${
issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `
}${issue.minimum}`;
else if (issue.type === "date")
message = `Date must be ${
issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `
}${new Date(Number(issue.minimum))}`;
else message = "Invalid input";
break;
case ZodIssueCode.too_big:
if (issue.type === "array")
message = `Array must contain ${
issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`
} ${issue.maximum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${
issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`
} ${issue.maximum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${
issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`
} ${issue.maximum}`;
else if (issue.type === "bigint")
message = `BigInt must be ${
issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`
} ${issue.maximum}`;
else if (issue.type === "date")
message = `Date must be ${
issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`
} ${new Date(Number(issue.maximum))}`;
else message = "Invalid input";
break;
case ZodIssueCode.custom:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util.assertNever(issue);
}
return { message };
};
export default errorMap;
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 6717c36cb235645fdb57514eeb3663b4
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/locales/en.ts
uploadId: 920982
@@ -0,0 +1,113 @@
/**
* The Standard Schema interface.
*/
export type StandardSchemaV1<Input = unknown, Output = Input> = {
/**
* The Standard Schema properties.
*/
readonly "~standard": StandardSchemaV1.Props<Input, Output>;
};
export declare namespace StandardSchemaV1 {
/**
* The Standard Schema properties interface.
*/
export interface Props<Input = unknown, Output = Input> {
/**
* The version number of the standard.
*/
readonly version: 1;
/**
* The vendor name of the schema library.
*/
readonly vendor: string;
/**
* Validates unknown input values.
*/
readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
/**
* Inferred types associated with the schema.
*/
readonly types?: Types<Input, Output> | undefined;
}
/**
* The result interface of the validate function.
*/
export type Result<Output> = SuccessResult<Output> | FailureResult;
/**
* The result interface if validation succeeds.
*/
export interface SuccessResult<Output> {
/**
* The typed output value.
*/
readonly value: Output;
/**
* The non-existent issues.
*/
readonly issues?: undefined;
}
/**
* The result interface if validation fails.
*/
export interface FailureResult {
/**
* The issues of failed validation.
*/
readonly issues: ReadonlyArray<Issue>;
}
/**
* The issue interface of the failure output.
*/
export interface Issue {
/**
* The error message of the issue.
*/
readonly message: string;
/**
* The path of the issue, if any.
*/
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
}
/**
* The path segment interface of the issue.
*/
export interface PathSegment {
/**
* The key representing a path segment.
*/
readonly key: PropertyKey;
}
/**
* The Standard Schema types interface.
*/
export interface Types<Input = unknown, Output = Input> {
/**
* The input type of the schema.
*/
readonly input: Input;
/**
* The output type of the schema.
*/
readonly output: Output;
}
/**
* Infers the input type of a Standard Schema.
*/
export type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["input"];
/**
* Infers the output type of a Standard Schema.
*/
export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
// biome-ignore lint/complexity/noUselessEmptyExport: needed for granular visibility control of TS namespace
export {};
}
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 1e0c689e0c3844d00a2700951404d7c9
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/standard-schema.ts
uploadId: 920982
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 968fb479754f444b78a0668ab1dbf0e8
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,54 @@
function getRandomInt(max: number) {
return Math.floor(Math.random() * Math.floor(max));
}
const testSymbol = Symbol("test");
export class Mocker {
pick = (...args: any[]): any => {
return args[getRandomInt(args.length)];
};
get string(): string {
return Math.random().toString(36).substring(7);
}
get number(): number {
return Math.random() * 100;
}
get bigint(): bigint {
return BigInt(Math.floor(Math.random() * 10000));
}
get boolean(): boolean {
return Math.random() < 0.5;
}
get date(): Date {
return new Date(Math.floor(Date.now() * Math.random()));
}
get symbol(): symbol {
return testSymbol;
}
get null(): null {
return null;
}
get undefined(): undefined {
return undefined;
}
get stringOptional(): string | undefined {
return this.pick(this.string, this.undefined);
}
get stringNullable(): string | null {
return this.pick(this.string, this.null);
}
get numberOptional(): number | undefined {
return this.pick(this.number, this.undefined);
}
get numberNullable(): number | null {
return this.pick(this.number, this.null);
}
get booleanOptional(): boolean | undefined {
return this.pick(this.boolean, this.undefined);
}
get booleanNullable(): boolean | null {
return this.pick(this.boolean, this.null);
}
}
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 71b1a464121e4494a97e1d5ea8dd5d90
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/Mocker.ts
uploadId: 920982
@@ -0,0 +1,157 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
import { util } from "../helpers/util.js";
const Test = z.object({
f1: z.number(),
f2: z.string().optional(),
f3: z.string().nullable(),
f4: z.array(z.object({ t: z.union([z.string(), z.boolean()]) })),
});
type TestFlattenedErrors = z.inferFlattenedErrors<typeof Test, { message: string; code: number }>;
type TestFormErrors = z.inferFlattenedErrors<typeof Test>;
test("default flattened errors type inference", () => {
type TestTypeErrors = {
formErrors: string[];
fieldErrors: { [P in keyof z.TypeOf<typeof Test>]?: string[] | undefined };
};
util.assertEqual<z.inferFlattenedErrors<typeof Test>, TestTypeErrors>(true);
util.assertEqual<z.inferFlattenedErrors<typeof Test, { message: string }>, TestTypeErrors>(false);
});
test("custom flattened errors type inference", () => {
type ErrorType = { message: string; code: number };
type TestTypeErrors = {
formErrors: ErrorType[];
fieldErrors: {
[P in keyof z.TypeOf<typeof Test>]?: ErrorType[] | undefined;
};
};
util.assertEqual<z.inferFlattenedErrors<typeof Test>, TestTypeErrors>(false);
util.assertEqual<z.inferFlattenedErrors<typeof Test, { message: string; code: number }>, TestTypeErrors>(true);
util.assertEqual<z.inferFlattenedErrors<typeof Test, { message: string }>, TestTypeErrors>(false);
});
test("form errors type inference", () => {
type TestTypeErrors = {
formErrors: string[];
fieldErrors: { [P in keyof z.TypeOf<typeof Test>]?: string[] | undefined };
};
util.assertEqual<z.inferFlattenedErrors<typeof Test>, TestTypeErrors>(true);
});
test(".flatten() type assertion", () => {
const parsed = Test.safeParse({}) as z.SafeParseError<void>;
const validFlattenedErrors: TestFlattenedErrors = parsed.error.flatten(() => ({ message: "", code: 0 }));
// @ts-expect-error should fail assertion between `TestFlattenedErrors` and unmapped `flatten()`.
const invalidFlattenedErrors: TestFlattenedErrors = parsed.error.flatten();
const validFormErrors: TestFormErrors = parsed.error.flatten();
// @ts-expect-error should fail assertion between `TestFormErrors` and mapped `flatten()`.
const invalidFormErrors: TestFormErrors = parsed.error.flatten(() => ({
message: "string",
code: 0,
}));
[validFlattenedErrors, invalidFlattenedErrors, validFormErrors, invalidFormErrors];
});
test(".formErrors type assertion", () => {
const parsed = Test.safeParse({}) as z.SafeParseError<void>;
const validFormErrors: TestFormErrors = parsed.error.formErrors;
// @ts-expect-error should fail assertion between `TestFlattenedErrors` and `.formErrors`.
const invalidFlattenedErrors: TestFlattenedErrors = parsed.error.formErrors;
[validFormErrors, invalidFlattenedErrors];
});
test("all errors", () => {
const propertySchema = z.string();
const schema = z
.object({
a: propertySchema,
b: propertySchema,
})
.refine(
(val) => {
return val.a === val.b;
},
{ message: "Must be equal" }
);
try {
schema.parse({
a: "asdf",
b: "qwer",
});
} catch (error) {
if (error instanceof z.ZodError) {
expect(error.flatten()).toEqual({
formErrors: ["Must be equal"],
fieldErrors: {},
});
}
}
try {
schema.parse({
a: null,
b: null,
});
} catch (_error) {
const error = _error as z.ZodError;
expect(error.flatten()).toEqual({
formErrors: [],
fieldErrors: {
a: ["Expected string, received null"],
b: ["Expected string, received null"],
},
});
expect(error.flatten((iss) => iss.message.toUpperCase())).toEqual({
formErrors: [],
fieldErrors: {
a: ["EXPECTED STRING, RECEIVED NULL"],
b: ["EXPECTED STRING, RECEIVED NULL"],
},
});
// Test identity
expect(error.flatten((i: z.ZodIssue) => i)).toEqual({
formErrors: [],
fieldErrors: {
a: [
{
code: "invalid_type",
expected: "string",
message: "Expected string, received null",
path: ["a"],
received: "null",
},
],
b: [
{
code: "invalid_type",
expected: "string",
message: "Expected string, received null",
path: ["b"],
received: "null",
},
],
},
});
// Test mapping
expect(error.flatten((i: z.ZodIssue) => i.message.length)).toEqual({
formErrors: [],
fieldErrors: {
a: ["Expected string, received null".length],
b: ["Expected string, received null".length],
},
});
}
});
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 18134daf64ab6491ab66658dee27cf10
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/all-errors.test.ts
uploadId: 920982
@@ -0,0 +1,28 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
import { util } from "../helpers/util.js";
test("check any inference", () => {
const t1 = z.any();
t1.optional();
t1.nullable();
type t1 = z.infer<typeof t1>;
util.assertEqual<t1, any>(true);
});
test("check unknown inference", () => {
const t1 = z.unknown();
t1.optional();
t1.nullable();
type t1 = z.infer<typeof t1>;
util.assertEqual<t1, unknown>(true);
});
test("check never inference", () => {
const t1 = z.never();
expect(() => t1.parse(undefined)).toThrow();
expect(() => t1.parse("asdf")).toThrow();
expect(() => t1.parse(null)).toThrow();
});
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 4634264d444ea42438f79f9c8474c960
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/anyunknown.test.ts
uploadId: 920982
@@ -0,0 +1,71 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
import { util } from "../helpers/util.js";
const minTwo = z.string().array().min(2);
const maxTwo = z.string().array().max(2);
const justTwo = z.string().array().length(2);
const intNum = z.string().array().nonempty();
const nonEmptyMax = z.string().array().nonempty().max(2);
type t1 = z.infer<typeof nonEmptyMax>;
util.assertEqual<[string, ...string[]], t1>(true);
type t2 = z.infer<typeof minTwo>;
util.assertEqual<string[], t2>(true);
test("passing validations", () => {
minTwo.parse(["a", "a"]);
minTwo.parse(["a", "a", "a"]);
maxTwo.parse(["a", "a"]);
maxTwo.parse(["a"]);
justTwo.parse(["a", "a"]);
intNum.parse(["a"]);
nonEmptyMax.parse(["a"]);
});
test("failing validations", () => {
expect(() => minTwo.parse(["a"])).toThrow();
expect(() => maxTwo.parse(["a", "a", "a"])).toThrow();
expect(() => justTwo.parse(["a"])).toThrow();
expect(() => justTwo.parse(["a", "a", "a"])).toThrow();
expect(() => intNum.parse([])).toThrow();
expect(() => nonEmptyMax.parse([])).toThrow();
expect(() => nonEmptyMax.parse(["a", "a", "a"])).toThrow();
});
test("parse empty array in nonempty", () => {
expect(() =>
z
.array(z.string())
.nonempty()
.parse([] as any)
).toThrow();
});
test("get element", () => {
justTwo.element.parse("asdf");
expect(() => justTwo.element.parse(12)).toThrow();
});
test("continue parsing despite array size error", () => {
const schema = z.object({
people: z.string().array().min(2),
});
const result = schema.safeParse({
people: [123],
});
expect(result.success).toEqual(false);
if (!result.success) {
expect(result.error.issues.length).toEqual(2);
}
});
test("parse should fail given sparse array", () => {
const schema = z.array(z.string()).nonempty().min(1).max(3);
expect(() => schema.parse(new Array(3))).toThrow();
});
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 2278321852763431aa3ea18a8b1f88e2
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/array.test.ts
uploadId: 920982
@@ -0,0 +1,388 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
/// string
const stringSchema = z.string();
test("string async parse", async () => {
const goodData = "XXX";
const badData = 12;
const goodResult = await stringSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await stringSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// number
const numberSchema = z.number();
test("number async parse", async () => {
const goodData = 1234.2353;
const badData = "1234";
const goodResult = await numberSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await numberSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// bigInt
const bigIntSchema = z.bigint();
test("bigInt async parse", async () => {
const goodData = BigInt(145);
const badData = 134;
const goodResult = await bigIntSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await bigIntSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// boolean
const booleanSchema = z.boolean();
test("boolean async parse", async () => {
const goodData = true;
const badData = 1;
const goodResult = await booleanSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await booleanSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// date
const dateSchema = z.date();
test("date async parse", async () => {
const goodData = new Date();
const badData = new Date().toISOString();
const goodResult = await dateSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await dateSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// undefined
const undefinedSchema = z.undefined();
test("undefined async parse", async () => {
const goodData = undefined;
const badData = "XXX";
const goodResult = await undefinedSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(undefined);
const badResult = await undefinedSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// null
const nullSchema = z.null();
test("null async parse", async () => {
const goodData = null;
const badData = undefined;
const goodResult = await nullSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await nullSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// any
const anySchema = z.any();
test("any async parse", async () => {
const goodData = [{}];
// const badData = 'XXX';
const goodResult = await anySchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
// const badResult = await anySchema.safeParseAsync(badData);
// expect(badResult.success).toBe(false);
// if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// unknown
const unknownSchema = z.unknown();
test("unknown async parse", async () => {
const goodData = ["asdf", 124, () => {}];
// const badData = 'XXX';
const goodResult = await unknownSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
// const badResult = await unknownSchema.safeParseAsync(badData);
// expect(badResult.success).toBe(false);
// if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// void
const voidSchema = z.void();
test("void async parse", async () => {
const goodData = undefined;
const badData = 0;
const goodResult = await voidSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await voidSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// array
const arraySchema = z.array(z.string());
test("array async parse", async () => {
const goodData = ["XXX"];
const badData = "XXX";
const goodResult = await arraySchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await arraySchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// object
const objectSchema = z.object({ string: z.string() });
test("object async parse", async () => {
const goodData = { string: "XXX" };
const badData = { string: 12 };
const goodResult = await objectSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await objectSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// union
const unionSchema = z.union([z.string(), z.undefined()]);
test("union async parse", async () => {
const goodData = undefined;
const badData = null;
const goodResult = await unionSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await unionSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// record
const recordSchema = z.record(z.object({}));
test("record async parse", async () => {
const goodData = { adsf: {}, asdf: {} };
const badData = [{}];
const goodResult = await recordSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await recordSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// function
const functionSchema = z.function();
test("function async parse", async () => {
const goodData = () => {};
const badData = "XXX";
const goodResult = await functionSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(typeof goodResult.data).toEqual("function");
const badResult = await functionSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// literal
const literalSchema = z.literal("asdf");
test("literal async parse", async () => {
const goodData = "asdf";
const badData = "asdff";
const goodResult = await literalSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await literalSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// enum
const enumSchema = z.enum(["fish", "whale"]);
test("enum async parse", async () => {
const goodData = "whale";
const badData = "leopard";
const goodResult = await enumSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await enumSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// nativeEnum
enum nativeEnumTest {
asdf = "qwer",
}
// @ts-ignore
const nativeEnumSchema = z.nativeEnum(nativeEnumTest);
test("nativeEnum async parse", async () => {
const goodData = nativeEnumTest.asdf;
const badData = "asdf";
const goodResult = await nativeEnumSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) expect(goodResult.data).toEqual(goodData);
const badResult = await nativeEnumSchema.safeParseAsync(badData);
expect(badResult.success).toBe(false);
if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError);
});
/// promise
const promiseSchema = z.promise(z.number());
test("promise async parse good", async () => {
const goodData = Promise.resolve(123);
const goodResult = await promiseSchema.safeParseAsync(goodData);
expect(goodResult.success).toBe(true);
if (goodResult.success) {
expect(goodResult.data).toBeInstanceOf(Promise);
const data = await goodResult.data;
expect(data).toEqual(123);
// expect(goodResult.data).resolves.toEqual(124);
// return goodResult.data;
} else {
throw new Error("success should be true");
}
});
test("promise async parse bad", async () => {
const badData = Promise.resolve("XXX");
const badResult = await promiseSchema.safeParseAsync(badData);
expect(badResult.success).toBe(true);
if (badResult.success) {
await expect(badResult.data).rejects.toBeInstanceOf(z.ZodError);
} else {
throw new Error("success should be true");
}
});
test("async validation non-empty strings", async () => {
const base = z.object({
hello: z.string().refine((x) => x && x.length > 0),
foo: z.string().refine((x) => x && x.length > 0),
});
const testval = { hello: "", foo: "" };
const result1 = base.safeParse(testval);
const result2 = base.safeParseAsync(testval);
const r1 = result1;
await result2.then((r2) => {
if (r1.success === false && r2.success === false) expect(r1.error.issues.length).toBe(r2.error.issues.length); // <--- r1 has length 2, r2 has length 1
});
});
test("async validation multiple errors 1", async () => {
const base = z.object({
hello: z.string(),
foo: z.number(),
});
const testval = { hello: 3, foo: "hello" };
const result1 = base.safeParse(testval);
const result2 = base.safeParseAsync(testval);
const r1 = result1;
await result2.then((r2) => {
if (r1.success === false && r2.success === false) expect(r2.error.issues.length).toBe(r1.error.issues.length);
});
});
test("async validation multiple errors 2", async () => {
const base = (is_async?: boolean) =>
z.object({
hello: z.string(),
foo: z.object({
bar: z.number().refine(is_async ? async () => false : () => false),
}),
});
const testval = { hello: 3, foo: { bar: 4 } };
const result1 = base().safeParse(testval);
const result2 = base(true).safeParseAsync(testval);
const r1 = result1;
await result2.then((r2) => {
if (r1.success === false && r2.success === false) expect(r2.error.issues.length).toBe(r1.error.issues.length);
});
});
test("ensure early async failure prevents follow-up refinement checks", async () => {
let count = 0;
const base = z.object({
hello: z.string(),
foo: z
.number()
.refine(async () => {
count++;
return true;
})
.refine(async () => {
count++;
return true;
}, "Good"),
});
const testval = { hello: "bye", foo: 3 };
const result = await base.safeParseAsync(testval);
if (result.success === false) {
expect(result.error.issues.length).toBe(1);
expect(count).toBe(1);
}
// await result.then((r) => {
// if (r.success === false) expect(r.error.issues.length).toBe(1);
// expect(count).toBe(2);
// });
});
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 9478adf90c4f64b5dbf11ba4550e428b
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/async-parsing.test.ts
uploadId: 920982
@@ -0,0 +1,46 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
test("parse async test", async () => {
const schema1 = z.string().refine(async (_val) => false);
expect(() => schema1.parse("asdf")).toThrow();
const schema2 = z.string().refine((_val) => Promise.resolve(true));
return await expect(() => schema2.parse("asdf")).toThrow();
});
test("parseAsync async test", async () => {
const schema1 = z.string().refine(async (_val) => true);
await schema1.parseAsync("asdf");
const schema2 = z.string().refine(async (_val) => false);
return await expect(schema2.parseAsync("asdf")).rejects.toBeDefined();
// expect(async () => await schema2.parseAsync('asdf')).toThrow();
});
test("parseAsync async test", async () => {
// expect.assertions(2);
const schema1 = z.string().refine((_val) => Promise.resolve(true));
const v1 = await schema1.parseAsync("asdf");
expect(v1).toEqual("asdf");
const schema2 = z.string().refine((_val) => Promise.resolve(false));
await expect(schema2.parseAsync("asdf")).rejects.toBeDefined();
const schema3 = z.string().refine((_val) => Promise.resolve(true));
await expect(schema3.parseAsync("asdf")).resolves.toEqual("asdf");
return await expect(schema3.parseAsync("qwer")).resolves.toEqual("qwer");
});
test("parseAsync async with value", async () => {
const schema1 = z.string().refine(async (val) => {
return val.length > 5;
});
await expect(schema1.parseAsync("asdf")).rejects.toBeDefined();
const v = await schema1.parseAsync("asdf123");
return await expect(v).toEqual("asdf123");
});
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 02a378f3b65be4f25830cbb42e60d43d
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/async-refinements.test.ts
uploadId: 920982
@@ -0,0 +1,29 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
import { util } from "../helpers/util.js";
test("type guard", () => {
const stringToNumber = z.string().transform((arg) => arg.length);
const s1 = z.object({
stringToNumber,
});
type t1 = z.input<typeof s1>;
const data = { stringToNumber: "asdf" };
const parsed = s1.safeParse(data);
if (parsed.success) {
util.assertEqual<typeof data, t1>(true);
}
});
test("test this binding", () => {
const callback = (predicate: (val: string) => boolean) => {
return predicate("hello");
};
expect(callback((value) => z.string().safeParse(value).success)).toBe(true); // true
expect(callback((value) => z.string().safeParse(value).success)).toBe(true); // true
});
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: dc99a72ff450d4f979e28898ae1df5a4
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/base.test.ts
uploadId: 920982
@@ -0,0 +1,55 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
const gtFive = z.bigint().gt(BigInt(5));
const gteFive = z.bigint().gte(BigInt(5));
const ltFive = z.bigint().lt(BigInt(5));
const lteFive = z.bigint().lte(BigInt(5));
const positive = z.bigint().positive();
const negative = z.bigint().negative();
const nonnegative = z.bigint().nonnegative();
const nonpositive = z.bigint().nonpositive();
const multipleOfFive = z.bigint().multipleOf(BigInt(5));
test("passing validations", () => {
z.bigint().parse(BigInt(1));
z.bigint().parse(BigInt(0));
z.bigint().parse(BigInt(-1));
gtFive.parse(BigInt(6));
gteFive.parse(BigInt(5));
gteFive.parse(BigInt(6));
ltFive.parse(BigInt(4));
lteFive.parse(BigInt(5));
lteFive.parse(BigInt(4));
positive.parse(BigInt(3));
negative.parse(BigInt(-2));
nonnegative.parse(BigInt(0));
nonnegative.parse(BigInt(7));
nonpositive.parse(BigInt(0));
nonpositive.parse(BigInt(-12));
multipleOfFive.parse(BigInt(15));
});
test("failing validations", () => {
expect(() => gtFive.parse(BigInt(5))).toThrow();
expect(() => gteFive.parse(BigInt(4))).toThrow();
expect(() => ltFive.parse(BigInt(5))).toThrow();
expect(() => lteFive.parse(BigInt(6))).toThrow();
expect(() => positive.parse(BigInt(0))).toThrow();
expect(() => positive.parse(BigInt(-2))).toThrow();
expect(() => negative.parse(BigInt(0))).toThrow();
expect(() => negative.parse(BigInt(3))).toThrow();
expect(() => nonnegative.parse(BigInt(-1))).toThrow();
expect(() => nonpositive.parse(BigInt(1))).toThrow();
expect(() => multipleOfFive.parse(BigInt(13))).toThrow();
});
test("min max getters", () => {
expect(z.bigint().min(BigInt(5)).minValue).toEqual(BigInt(5));
expect(z.bigint().min(BigInt(5)).min(BigInt(10)).minValue).toEqual(BigInt(10));
expect(z.bigint().max(BigInt(5)).maxValue).toEqual(BigInt(5));
expect(z.bigint().max(BigInt(5)).max(BigInt(1)).maxValue).toEqual(BigInt(1));
});
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: f8338621e648d4f74afb790c7a4515e0
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/bigint.test.ts
uploadId: 920982
@@ -0,0 +1,53 @@
// @ts-ignore TS6133
import { test } from "vitest";
import * as z from "zod/v3";
import { util } from "../helpers/util.js";
test("branded types", () => {
const mySchema = z
.object({
name: z.string(),
})
.brand<"superschema">();
// simple branding
type MySchema = z.infer<typeof mySchema>;
util.assertEqual<MySchema, { name: string } & { [z.BRAND]: { superschema: true } }>(true);
const doStuff = (arg: MySchema) => arg;
doStuff(mySchema.parse({ name: "hello there" }));
// inheritance
const extendedSchema = mySchema.brand<"subschema">();
type ExtendedSchema = z.infer<typeof extendedSchema>;
util.assertEqual<ExtendedSchema, { name: string } & z.BRAND<"superschema"> & z.BRAND<"subschema">>(true);
doStuff(extendedSchema.parse({ name: "hello again" }));
// number branding
const numberSchema = z.number().brand<42>();
type NumberSchema = z.infer<typeof numberSchema>;
util.assertEqual<NumberSchema, number & { [z.BRAND]: { 42: true } }>(true);
// symbol branding
const MyBrand: unique symbol = Symbol("hello");
type MyBrand = typeof MyBrand;
const symbolBrand = z.number().brand<"sup">().brand<typeof MyBrand>();
type SymbolBrand = z.infer<typeof symbolBrand>;
// number & { [z.BRAND]: { sup: true, [MyBrand]: true } }
util.assertEqual<SymbolBrand, number & z.BRAND<"sup"> & z.BRAND<MyBrand>>(true);
// keeping brands out of input types
const age = z.number().brand<"age">();
type Age = z.infer<typeof age>;
type AgeInput = z.input<typeof age>;
util.assertEqual<AgeInput, Age>(false);
util.assertEqual<number, AgeInput>(true);
util.assertEqual<number & z.BRAND<"age">, Age>(true);
// @ts-expect-error
doStuff({ name: "hello there!" });
});
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: b0efa5d7ca88b435b84f240f27450b1d
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/branded.test.ts
uploadId: 920982
@@ -0,0 +1,220 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import { z } from "zod/v3";
import { util } from "../helpers/util.js";
test("basic catch", () => {
expect(z.string().catch("default").parse(undefined)).toBe("default");
});
test("catch fn does not run when parsing succeeds", () => {
let isCalled = false;
const cb = () => {
isCalled = true;
return "asdf";
};
expect(z.string().catch(cb).parse("test")).toBe("test");
expect(isCalled).toEqual(false);
});
test("basic catch async", async () => {
const result = await z.string().catch("default").parseAsync(1243);
expect(result).toBe("default");
});
test("catch replace wrong types", () => {
expect(z.string().catch("default").parse(true)).toBe("default");
expect(z.string().catch("default").parse(true)).toBe("default");
expect(z.string().catch("default").parse(15)).toBe("default");
expect(z.string().catch("default").parse([])).toBe("default");
expect(z.string().catch("default").parse(new Map())).toBe("default");
expect(z.string().catch("default").parse(new Set())).toBe("default");
expect(z.string().catch("default").parse({})).toBe("default");
});
test("catch with transform", () => {
const stringWithDefault = z
.string()
.transform((val) => val.toUpperCase())
.catch("default");
expect(stringWithDefault.parse(undefined)).toBe("default");
expect(stringWithDefault.parse(15)).toBe("default");
expect(stringWithDefault).toBeInstanceOf(z.ZodCatch);
expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodEffects);
expect(stringWithDefault._def.innerType._def.schema).toBeInstanceOf(z.ZodSchema);
type inp = z.input<typeof stringWithDefault>;
util.assertEqual<inp, unknown>(true);
type out = z.output<typeof stringWithDefault>;
util.assertEqual<out, string>(true);
});
test("catch on existing optional", () => {
const stringWithDefault = z.string().optional().catch("asdf");
expect(stringWithDefault.parse(undefined)).toBe(undefined);
expect(stringWithDefault.parse(15)).toBe("asdf");
expect(stringWithDefault).toBeInstanceOf(z.ZodCatch);
expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodOptional);
expect(stringWithDefault._def.innerType._def.innerType).toBeInstanceOf(z.ZodString);
type inp = z.input<typeof stringWithDefault>;
util.assertEqual<inp, unknown>(true);
type out = z.output<typeof stringWithDefault>;
util.assertEqual<out, string | undefined>(true);
});
test("optional on catch", () => {
const stringWithDefault = z.string().catch("asdf").optional();
type inp = z.input<typeof stringWithDefault>;
util.assertEqual<inp, unknown>(true);
type out = z.output<typeof stringWithDefault>;
util.assertEqual<out, string | undefined>(true);
});
test("complex chain example", () => {
const complex = z
.string()
.catch("asdf")
.transform((val) => val + "!")
.transform((val) => val.toUpperCase())
.catch("qwer")
.removeCatch()
.optional()
.catch("asdfasdf");
expect(complex.parse("qwer")).toBe("QWER!");
expect(complex.parse(15)).toBe("ASDF!");
expect(complex.parse(true)).toBe("ASDF!");
});
test("removeCatch", () => {
const stringWithRemovedDefault = z.string().catch("asdf").removeCatch();
type out = z.output<typeof stringWithRemovedDefault>;
util.assertEqual<out, string>(true);
});
test("nested", () => {
const inner = z.string().catch("asdf");
const outer = z.object({ inner }).catch({
inner: "asdf",
});
type input = z.input<typeof outer>;
util.assertEqual<input, unknown>(true);
type out = z.output<typeof outer>;
util.assertEqual<out, { inner: string }>(true);
expect(outer.parse(undefined)).toEqual({ inner: "asdf" });
expect(outer.parse({})).toEqual({ inner: "asdf" });
expect(outer.parse({ inner: undefined })).toEqual({ inner: "asdf" });
});
test("chained catch", () => {
const stringWithDefault = z.string().catch("inner").catch("outer");
const result = stringWithDefault.parse(undefined);
expect(result).toEqual("inner");
const resultDiff = stringWithDefault.parse(5);
expect(resultDiff).toEqual("inner");
});
test("factory", () => {
z.ZodCatch.create(z.string(), {
catch: "asdf",
}).parse(undefined);
});
test("native enum", () => {
enum Fruits {
apple = "apple",
orange = "orange",
}
const schema = z.object({
fruit: z.nativeEnum(Fruits).catch(Fruits.apple),
});
expect(schema.parse({})).toEqual({ fruit: Fruits.apple });
expect(schema.parse({ fruit: 15 })).toEqual({ fruit: Fruits.apple });
});
test("enum", () => {
const schema = z.object({
fruit: z.enum(["apple", "orange"]).catch("apple"),
});
expect(schema.parse({})).toEqual({ fruit: "apple" });
expect(schema.parse({ fruit: true })).toEqual({ fruit: "apple" });
expect(schema.parse({ fruit: 15 })).toEqual({ fruit: "apple" });
});
test("reported issues with nested usage", () => {
const schema = z.object({
string: z.string(),
obj: z.object({
sub: z.object({
lit: z.literal("a"),
subCatch: z.number().catch(23),
}),
midCatch: z.number().catch(42),
}),
number: z.number().catch(0),
bool: z.boolean(),
});
try {
schema.parse({
string: {},
obj: {
sub: {
lit: "b",
subCatch: "24",
},
midCatch: 444,
},
number: "",
bool: "yes",
});
} catch (error) {
const issues = (error as z.ZodError).issues;
expect(issues.length).toEqual(3);
expect(issues[0].message).toMatch("string");
expect(issues[1].message).toMatch("literal");
expect(issues[2].message).toMatch("boolean");
}
});
test("catch error", () => {
let catchError: z.ZodError | undefined = undefined;
const schema = z.object({
age: z.number(),
name: z.string().catch((ctx) => {
catchError = ctx.error;
return "John Doe";
}),
});
const result = schema.safeParse({
age: null,
name: null,
});
expect(result.success).toEqual(false);
expect(!result.success && result.error.issues.length).toEqual(1);
expect(!result.success && result.error.issues[0].message).toMatch("number");
expect(catchError).toBeInstanceOf(z.ZodError);
expect(catchError !== undefined && (catchError as z.ZodError).issues.length).toEqual(1);
expect(catchError !== undefined && (catchError as z.ZodError).issues[0].message).toMatch("string");
});
test("ctx.input", () => {
const schema = z.string().catch((ctx) => {
return String(ctx.input);
});
expect(schema.parse(123)).toEqual("123");
});
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 5c892754b15dd48c9824070b2b969456
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/catch.test.ts
uploadId: 920982
@@ -0,0 +1,133 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
test("string coercion", () => {
const schema = z.coerce.string();
expect(schema.parse("sup")).toEqual("sup");
expect(schema.parse("")).toEqual("");
expect(schema.parse(12)).toEqual("12");
expect(schema.parse(0)).toEqual("0");
expect(schema.parse(-12)).toEqual("-12");
expect(schema.parse(3.14)).toEqual("3.14");
expect(schema.parse(BigInt(15))).toEqual("15");
expect(schema.parse(Number.NaN)).toEqual("NaN");
expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual("Infinity");
expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual("-Infinity");
expect(schema.parse(true)).toEqual("true");
expect(schema.parse(false)).toEqual("false");
expect(schema.parse(null)).toEqual("null");
expect(schema.parse(undefined)).toEqual("undefined");
expect(schema.parse({ hello: "world!" })).toEqual("[object Object]");
expect(schema.parse(["item", "another_item"])).toEqual("item,another_item");
expect(schema.parse([])).toEqual("");
expect(schema.parse(new Date("2022-01-01T00:00:00.000Z"))).toEqual(new Date("2022-01-01T00:00:00.000Z").toString());
});
test("number coercion", () => {
const schema = z.coerce.number();
expect(schema.parse("12")).toEqual(12);
expect(schema.parse("0")).toEqual(0);
expect(schema.parse("-12")).toEqual(-12);
expect(schema.parse("3.14")).toEqual(3.14);
expect(schema.parse("")).toEqual(0);
expect(() => schema.parse("NOT_A_NUMBER")).toThrow(); // z.ZodError
expect(schema.parse(12)).toEqual(12);
expect(schema.parse(0)).toEqual(0);
expect(schema.parse(-12)).toEqual(-12);
expect(schema.parse(3.14)).toEqual(3.14);
expect(schema.parse(BigInt(15))).toEqual(15);
expect(() => schema.parse(Number.NaN)).toThrow(); // z.ZodError
expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual(Number.POSITIVE_INFINITY);
expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual(Number.NEGATIVE_INFINITY);
expect(schema.parse(true)).toEqual(1);
expect(schema.parse(false)).toEqual(0);
expect(schema.parse(null)).toEqual(0);
expect(() => schema.parse(undefined)).toThrow(); // z.ZodError
expect(() => schema.parse({ hello: "world!" })).toThrow(); // z.ZodError
expect(() => schema.parse(["item", "another_item"])).toThrow(); // z.ZodError
expect(schema.parse([])).toEqual(0);
expect(schema.parse(new Date(1670139203496))).toEqual(1670139203496);
});
test("boolean coercion", () => {
const schema = z.coerce.boolean();
expect(schema.parse("true")).toEqual(true);
expect(schema.parse("false")).toEqual(true);
expect(schema.parse("0")).toEqual(true);
expect(schema.parse("1")).toEqual(true);
expect(schema.parse("")).toEqual(false);
expect(schema.parse(1)).toEqual(true);
expect(schema.parse(0)).toEqual(false);
expect(schema.parse(-1)).toEqual(true);
expect(schema.parse(3.14)).toEqual(true);
expect(schema.parse(BigInt(15))).toEqual(true);
expect(schema.parse(Number.NaN)).toEqual(false);
expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual(true);
expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual(true);
expect(schema.parse(true)).toEqual(true);
expect(schema.parse(false)).toEqual(false);
expect(schema.parse(null)).toEqual(false);
expect(schema.parse(undefined)).toEqual(false);
expect(schema.parse({ hello: "world!" })).toEqual(true);
expect(schema.parse(["item", "another_item"])).toEqual(true);
expect(schema.parse([])).toEqual(true);
expect(schema.parse(new Date(1670139203496))).toEqual(true);
});
test("bigint coercion", () => {
const schema = z.coerce.bigint();
expect(schema.parse("5")).toEqual(BigInt(5));
expect(schema.parse("0")).toEqual(BigInt(0));
expect(schema.parse("-5")).toEqual(BigInt(-5));
expect(() => schema.parse("3.14")).toThrow(); // not a z.ZodError!
expect(schema.parse("")).toEqual(BigInt(0));
expect(() => schema.parse("NOT_A_NUMBER")).toThrow(); // not a z.ZodError!
expect(schema.parse(5)).toEqual(BigInt(5));
expect(schema.parse(0)).toEqual(BigInt(0));
expect(schema.parse(-5)).toEqual(BigInt(-5));
expect(() => schema.parse(3.14)).toThrow(); // not a z.ZodError!
expect(schema.parse(BigInt(5))).toEqual(BigInt(5));
expect(() => schema.parse(Number.NaN)).toThrow(); // not a z.ZodError!
expect(() => schema.parse(Number.POSITIVE_INFINITY)).toThrow(); // not a z.ZodError!
expect(() => schema.parse(Number.NEGATIVE_INFINITY)).toThrow(); // not a z.ZodError!
expect(schema.parse(true)).toEqual(BigInt(1));
expect(schema.parse(false)).toEqual(BigInt(0));
expect(() => schema.parse(null)).toThrow(); // not a z.ZodError!
expect(() => schema.parse(undefined)).toThrow(); // not a z.ZodError!
expect(() => schema.parse({ hello: "world!" })).toThrow(); // not a z.ZodError!
expect(() => schema.parse(["item", "another_item"])).toThrow(); // not a z.ZodError!
expect(schema.parse([])).toEqual(BigInt(0));
expect(schema.parse(new Date(1670139203496))).toEqual(BigInt(1670139203496));
});
test("date coercion", () => {
const schema = z.coerce.date();
expect(schema.parse(new Date().toDateString())).toBeInstanceOf(Date);
expect(schema.parse(new Date().toISOString())).toBeInstanceOf(Date);
expect(schema.parse(new Date().toUTCString())).toBeInstanceOf(Date);
expect(schema.parse("5")).toBeInstanceOf(Date);
expect(schema.parse("2000-01-01")).toBeInstanceOf(Date);
// expect(schema.parse("0")).toBeInstanceOf(Date);
// expect(schema.parse("-5")).toBeInstanceOf(Date);
// expect(schema.parse("3.14")).toBeInstanceOf(Date);
expect(() => schema.parse("")).toThrow(); // z.ZodError
expect(() => schema.parse("NOT_A_DATE")).toThrow(); // z.ZodError
expect(schema.parse(5)).toBeInstanceOf(Date);
expect(schema.parse(0)).toBeInstanceOf(Date);
expect(schema.parse(-5)).toBeInstanceOf(Date);
expect(schema.parse(3.14)).toBeInstanceOf(Date);
expect(() => schema.parse(BigInt(5))).toThrow(); // not a z.ZodError!
expect(() => schema.parse(Number.NaN)).toThrow(); // z.ZodError
expect(() => schema.parse(Number.POSITIVE_INFINITY)).toThrow(); // z.ZodError
expect(() => schema.parse(Number.NEGATIVE_INFINITY)).toThrow(); // z.ZodError
expect(schema.parse(true)).toBeInstanceOf(Date);
expect(schema.parse(false)).toBeInstanceOf(Date);
expect(schema.parse(null)).toBeInstanceOf(Date);
expect(() => schema.parse(undefined)).toThrow(); // z.ZodError
expect(() => schema.parse({ hello: "world!" })).toThrow(); // z.ZodError
expect(() => schema.parse(["item", "another_item"])).toThrow(); // z.ZodError
expect(() => schema.parse([])).toThrow(); // z.ZodError
expect(schema.parse(new Date())).toBeInstanceOf(Date);
});
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: a5c9436a89b504ffba7032eb15f5e226
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/coerce.test.ts
uploadId: 920982
@@ -0,0 +1,56 @@
import { test } from "vitest";
import * as z from "zod/v3";
const crazySchema = z.object({
tuple: z.tuple([
z.string().nullable().optional(),
z.number().nullable().optional(),
z.boolean().nullable().optional(),
z.null().nullable().optional(),
z.undefined().nullable().optional(),
z.literal("1234").nullable().optional(),
]),
merged: z
.object({
k1: z.string().optional(),
})
.merge(z.object({ k1: z.string().nullable(), k2: z.number() })),
union: z.array(z.union([z.literal("asdf"), z.literal(12)])).nonempty(),
array: z.array(z.number()),
// sumTransformer: z.transformer(z.array(z.number()), z.number(), (arg) => {
// return arg.reduce((a, b) => a + b, 0);
// }),
sumMinLength: z.array(z.number()).refine((arg) => arg.length > 5),
intersection: z.intersection(z.object({ p1: z.string().optional() }), z.object({ p1: z.number().optional() })),
enum: z.intersection(z.enum(["zero", "one"]), z.enum(["one", "two"])),
nonstrict: z.object({ points: z.number() }).nonstrict(),
numProm: z.promise(z.number()),
lenfun: z.function(z.tuple([z.string()]), z.boolean()),
});
// const asyncCrazySchema = crazySchema.extend({
// // async_transform: z.transformer(
// // z.array(z.number()),
// // z.number(),
// // async (arg) => {
// // return arg.reduce((a, b) => a + b, 0);
// // }
// // ),
// async_refine: z.array(z.number()).refine(async (arg) => arg.length > 5),
// });
test("parse", () => {
crazySchema.parse({
tuple: ["asdf", 1234, true, null, undefined, "1234"],
merged: { k1: "asdf", k2: 12 },
union: ["asdf", 12, "asdf", 12, "asdf", 12],
array: [12, 15, 16],
// sumTransformer: [12, 15, 16],
sumMinLength: [12, 15, 16, 98, 24, 63],
intersection: {},
enum: "one",
nonstrict: { points: 1234 },
numProm: Promise.resolve(12),
lenfun: (x: string) => x.length,
});
});
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 61997eb59c2104f998e3b0b8a28ec235
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/complex.test.ts
uploadId: 920982
@@ -0,0 +1,31 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
test("passing validations", () => {
const example1 = z.custom<number>((x) => typeof x === "number");
example1.parse(1234);
expect(() => example1.parse({})).toThrow();
});
test("string params", () => {
const example1 = z.custom<number>((x) => typeof x !== "number", "customerr");
const result = example1.safeParse(1234);
expect(result.success).toEqual(false);
// @ts-ignore
expect(JSON.stringify(result.error).includes("customerr")).toEqual(true);
});
test("async validations", async () => {
const example1 = z.custom<number>(async (x) => {
return typeof x === "number";
});
const r1 = await example1.safeParseAsync(1234);
expect(r1.success).toEqual(true);
expect(r1.data).toEqual(1234);
const r2 = await example1.safeParseAsync("asdf");
expect(r2.success).toEqual(false);
expect(r2.error!.issues.length).toEqual(1);
});
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 5549596eccf384561bb8ddfcde7674d9
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/custom.test.ts
uploadId: 920982
@@ -0,0 +1,32 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
const beforeBenchmarkDate = new Date(2022, 10, 4);
const benchmarkDate = new Date(2022, 10, 5);
const afterBenchmarkDate = new Date(2022, 10, 6);
const minCheck = z.date().min(benchmarkDate);
const maxCheck = z.date().max(benchmarkDate);
test("passing validations", () => {
minCheck.parse(benchmarkDate);
minCheck.parse(afterBenchmarkDate);
maxCheck.parse(benchmarkDate);
maxCheck.parse(beforeBenchmarkDate);
});
test("failing validations", () => {
expect(() => minCheck.parse(beforeBenchmarkDate)).toThrow();
expect(() => maxCheck.parse(afterBenchmarkDate)).toThrow();
});
test("min max getters", () => {
expect(minCheck.minDate).toEqual(benchmarkDate);
expect(minCheck.min(afterBenchmarkDate).minDate).toEqual(afterBenchmarkDate);
expect(maxCheck.maxDate).toEqual(benchmarkDate);
expect(maxCheck.max(beforeBenchmarkDate).maxDate).toEqual(beforeBenchmarkDate);
});
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: b94e5792be3e54a5d81c8a945cc244af
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/date.test.ts
uploadId: 920982
@@ -0,0 +1,186 @@
// @ts-ignore TS6133
import { test } from "vitest";
import * as z from "zod/v3";
test("test", () => {
z;
});
// const fish = z.object({
// name: z.string(),
// props: z.object({
// color: z.string(),
// numScales: z.number(),
// }),
// });
// const nonStrict = z
// .object({
// name: z.string(),
// color: z.string(),
// })
// .nonstrict();
// test('object pick type', () => {
// const modNonStrictFish = nonStrict.omit({ name: true });
// modNonStrictFish.parse({ color: 'asdf' });
// const bad1 = () => fish.pick({ props: { unknown: true } } as any);
// const bad2 = () => fish.omit({ name: true, props: { unknown: true } } as any);
// expect(bad1).toThrow();
// expect(bad2).toThrow();
// });
// test('f1', () => {
// const f1 = fish.pick(true);
// f1.parse({ name: 'a', props: { color: 'b', numScales: 3 } });
// });
// test('f2', () => {
// const f2 = fish.pick({ props: true });
// f2.parse({ props: { color: 'asdf', numScales: 1 } });
// const badcheck2 = () => f2.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any);
// expect(badcheck2).toThrow();
// });
// test('f3', () => {
// const f3 = fish.pick({ props: { color: true } });
// f3.parse({ props: { color: 'b' } });
// const badcheck3 = () => f3.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any);
// expect(badcheck3).toThrow();
// });
// test('f4', () => {
// const badcheck4 = () => fish.pick({ props: { color: true, unknown: true } });
// expect(badcheck4).toThrow();
// });
// test('f6', () => {
// const f6 = fish.omit({ props: true });
// const badcheck6 = () => f6.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any);
// f6.parse({ name: 'adsf' });
// expect(badcheck6).toThrow();
// });
// test('f7', () => {
// const f7 = fish.omit({ props: { color: true } });
// f7.parse({ name: 'a', props: { numScales: 3 } });
// const badcheck7 = () => f7.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any);
// expect(badcheck7).toThrow();
// });
// test('f8', () => {
// const badcheck8 = () => fish.omit({ props: { color: true, unknown: true } });
// expect(badcheck8).toThrow();
// });
// test('f9', () => {
// const f9 = nonStrict.pick(true);
// f9.parse({ name: 'a', color: 'asdf' });
// });
// test('f10', () => {
// const f10 = nonStrict.pick({ name: true });
// f10.parse({ name: 'a' });
// const val = f10.parse({ name: 'a', color: 'b' });
// expect(val).toEqual({ name: 'a' });
// });
// test('f12', () => {
// const badfcheck12 = () => nonStrict.omit({ color: true, asdf: true });
// expect(badfcheck12).toThrow();
// });
// test('array masking', () => {
// const fishArray = z.array(fish);
// const modFishArray = fishArray.pick({
// name: true,
// props: {
// numScales: true,
// },
// });
// modFishArray.parse([{ name: 'fish', props: { numScales: 12 } }]);
// const bad1 = () => modFishArray.parse([{ name: 'fish', props: { numScales: 12, color: 'asdf' } }] as any);
// expect(bad1).toThrow();
// });
// test('array masking', () => {
// const fishArray = z.array(fish);
// const fail = () =>
// fishArray.pick({
// name: true,
// props: {
// whatever: true,
// },
// } as any);
// expect(fail).toThrow();
// });
// test('array masking', () => {
// const fishArray = z.array(fish);
// const fail = () =>
// fishArray.omit({
// whateve: true,
// } as any);
// expect(fail).toThrow();
// });
// test('array masking', () => {
// const fishArray = z.array(fish);
// const modFishList = fishArray.omit({
// name: true,
// props: {
// color: true,
// },
// });
// modFishList.parse([{ props: { numScales: 12 } }]);
// const fail = () => modFishList.parse([{ name: 'hello', props: { numScales: 12 } }] as any);
// expect(fail).toThrow();
// });
// test('primitive array masking', () => {
// const fishArray = z.array(z.number());
// const fail = () => fishArray.pick({} as any);
// expect(fail).toThrow();
// });
// test('other array masking', () => {
// const fishArray = z.array(z.array(z.number()));
// const fail = () => fishArray.pick({} as any);
// expect(fail).toThrow();
// });
// test('invalid mask #1', () => {
// const fail = () => fish.pick(1 as any);
// expect(fail).toThrow();
// });
// test('invalid mask #2', () => {
// const fail = () => fish.pick([] as any);
// expect(fail).toThrow();
// });
// test('invalid mask #3', () => {
// const fail = () => fish.pick(false as any);
// expect(fail).toThrow();
// });
// test('invalid mask #4', () => {
// const fail = () => fish.pick('asdf' as any);
// expect(fail).toThrow();
// });
// test('invalid mask #5', () => {
// const fail = () => fish.omit(1 as any);
// expect(fail).toThrow();
// });
// test('invalid mask #6', () => {
// const fail = () => fish.omit([] as any);
// expect(fail).toThrow();
// });
// test('invalid mask #7', () => {
// const fail = () => fish.omit(false as any);
// expect(fail).toThrow();
// });
// test('invalid mask #8', () => {
// const fail = () => fish.omit('asdf' as any);
// expect(fail).toThrow();
// });
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 054f9ccbd01e941c2aec8d7037175307
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/deepmasking.test.ts
uploadId: 920982
@@ -0,0 +1,112 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import { z } from "zod/v3";
import { util } from "../helpers/util.js";
test("basic defaults", () => {
expect(z.string().default("default").parse(undefined)).toBe("default");
});
test("default with transform", () => {
const stringWithDefault = z
.string()
.transform((val) => val.toUpperCase())
.default("default");
expect(stringWithDefault.parse(undefined)).toBe("DEFAULT");
expect(stringWithDefault).toBeInstanceOf(z.ZodDefault);
expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodEffects);
expect(stringWithDefault._def.innerType._def.schema).toBeInstanceOf(z.ZodSchema);
type inp = z.input<typeof stringWithDefault>;
util.assertEqual<inp, string | undefined>(true);
type out = z.output<typeof stringWithDefault>;
util.assertEqual<out, string>(true);
});
test("default on existing optional", () => {
const stringWithDefault = z.string().optional().default("asdf");
expect(stringWithDefault.parse(undefined)).toBe("asdf");
expect(stringWithDefault).toBeInstanceOf(z.ZodDefault);
expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodOptional);
expect(stringWithDefault._def.innerType._def.innerType).toBeInstanceOf(z.ZodString);
type inp = z.input<typeof stringWithDefault>;
util.assertEqual<inp, string | undefined>(true);
type out = z.output<typeof stringWithDefault>;
util.assertEqual<out, string>(true);
});
test("optional on default", () => {
const stringWithDefault = z.string().default("asdf").optional();
type inp = z.input<typeof stringWithDefault>;
util.assertEqual<inp, string | undefined>(true);
type out = z.output<typeof stringWithDefault>;
util.assertEqual<out, string | undefined>(true);
});
test("complex chain example", () => {
const complex = z
.string()
.default("asdf")
.transform((val) => val.toUpperCase())
.default("qwer")
.removeDefault()
.optional()
.default("asdfasdf");
expect(complex.parse(undefined)).toBe("ASDFASDF");
});
test("removeDefault", () => {
const stringWithRemovedDefault = z.string().default("asdf").removeDefault();
type out = z.output<typeof stringWithRemovedDefault>;
util.assertEqual<out, string>(true);
});
test("nested", () => {
const inner = z.string().default("asdf");
const outer = z.object({ inner }).default({
inner: undefined,
});
type input = z.input<typeof outer>;
util.assertEqual<input, { inner?: string | undefined } | undefined>(true);
type out = z.output<typeof outer>;
util.assertEqual<out, { inner: string }>(true);
expect(outer.parse(undefined)).toEqual({ inner: "asdf" });
expect(outer.parse({})).toEqual({ inner: "asdf" });
expect(outer.parse({ inner: undefined })).toEqual({ inner: "asdf" });
});
test("chained defaults", () => {
const stringWithDefault = z.string().default("inner").default("outer");
const result = stringWithDefault.parse(undefined);
expect(result).toEqual("outer");
});
test("factory", () => {
expect(z.ZodDefault.create(z.string(), { default: "asdf" }).parse(undefined)).toEqual("asdf");
});
test("native enum", () => {
enum Fruits {
apple = "apple",
orange = "orange",
}
const schema = z.object({
fruit: z.nativeEnum(Fruits).default(Fruits.apple),
});
expect(schema.parse({})).toEqual({ fruit: Fruits.apple });
});
test("enum", () => {
const schema = z.object({
fruit: z.enum(["apple", "orange"]).default("apple"),
});
expect(schema.parse({})).toEqual({ fruit: "apple" });
});
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: f5d7a2696a1224d3abc9dd88f2b893bf
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/default.test.ts
uploadId: 920982
@@ -0,0 +1,33 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
const description = "a description";
test("passing `description` to schema should add a description", () => {
expect(z.string({ description }).description).toEqual(description);
expect(z.number({ description }).description).toEqual(description);
expect(z.boolean({ description }).description).toEqual(description);
});
test("`.describe` should add a description", () => {
expect(z.string().describe(description).description).toEqual(description);
expect(z.number().describe(description).description).toEqual(description);
expect(z.boolean().describe(description).description).toEqual(description);
});
test("description should carry over to chained schemas", () => {
const schema = z.string({ description });
expect(schema.description).toEqual(description);
expect(schema.optional().description).toEqual(description);
expect(schema.optional().nullable().default("default").description).toEqual(description);
});
test("description should not carry over to chained array schema", () => {
const schema = z.string().describe(description);
expect(schema.description).toEqual(description);
expect(schema.array().description).toEqual(undefined);
expect(z.array(schema).description).toEqual(undefined);
});
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 43d71b1bc3f4d42b1b8c6c17d3752077
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/description.test.ts
uploadId: 920982
@@ -0,0 +1,315 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
test("valid", () => {
expect(
z
.discriminatedUnion("type", [
z.object({ type: z.literal("a"), a: z.string() }),
z.object({ type: z.literal("b"), b: z.string() }),
])
.parse({ type: "a", a: "abc" })
).toEqual({ type: "a", a: "abc" });
});
test("valid - discriminator value of various primitive types", () => {
const schema = z.discriminatedUnion("type", [
z.object({ type: z.literal("1"), val: z.literal(1) }),
z.object({ type: z.literal(1), val: z.literal(2) }),
z.object({ type: z.literal(BigInt(1)), val: z.literal(3) }),
z.object({ type: z.literal("true"), val: z.literal(4) }),
z.object({ type: z.literal(true), val: z.literal(5) }),
z.object({ type: z.literal("null"), val: z.literal(6) }),
z.object({ type: z.literal(null), val: z.literal(7) }),
z.object({ type: z.literal("undefined"), val: z.literal(8) }),
z.object({ type: z.literal(undefined), val: z.literal(9) }),
z.object({ type: z.literal("transform"), val: z.literal(10) }),
z.object({ type: z.literal("refine"), val: z.literal(11) }),
z.object({ type: z.literal("superRefine"), val: z.literal(12) }),
]);
expect(schema.parse({ type: "1", val: 1 })).toEqual({ type: "1", val: 1 });
expect(schema.parse({ type: 1, val: 2 })).toEqual({ type: 1, val: 2 });
expect(schema.parse({ type: BigInt(1), val: 3 })).toEqual({
type: BigInt(1),
val: 3,
});
expect(schema.parse({ type: "true", val: 4 })).toEqual({
type: "true",
val: 4,
});
expect(schema.parse({ type: true, val: 5 })).toEqual({
type: true,
val: 5,
});
expect(schema.parse({ type: "null", val: 6 })).toEqual({
type: "null",
val: 6,
});
expect(schema.parse({ type: null, val: 7 })).toEqual({
type: null,
val: 7,
});
expect(schema.parse({ type: "undefined", val: 8 })).toEqual({
type: "undefined",
val: 8,
});
expect(schema.parse({ type: undefined, val: 9 })).toEqual({
type: undefined,
val: 9,
});
});
test("invalid - null", () => {
try {
z.discriminatedUnion("type", [
z.object({ type: z.literal("a"), a: z.string() }),
z.object({ type: z.literal("b"), b: z.string() }),
]).parse(null);
throw new Error();
} catch (e: any) {
expect(JSON.parse(e.message)).toEqual([
{
code: z.ZodIssueCode.invalid_type,
expected: z.ZodParsedType.object,
message: "Expected object, received null",
received: z.ZodParsedType.null,
path: [],
},
]);
}
});
test("invalid discriminator value", () => {
try {
z.discriminatedUnion("type", [
z.object({ type: z.literal("a"), a: z.string() }),
z.object({ type: z.literal("b"), b: z.string() }),
]).parse({ type: "x", a: "abc" });
throw new Error();
} catch (e: any) {
expect(JSON.parse(e.message)).toEqual([
{
code: z.ZodIssueCode.invalid_union_discriminator,
options: ["a", "b"],
message: "Invalid discriminator value. Expected 'a' | 'b'",
path: ["type"],
},
]);
}
});
test("valid discriminator value, invalid data", () => {
try {
z.discriminatedUnion("type", [
z.object({ type: z.literal("a"), a: z.string() }),
z.object({ type: z.literal("b"), b: z.string() }),
]).parse({ type: "a", b: "abc" });
throw new Error();
} catch (e: any) {
expect(JSON.parse(e.message)).toEqual([
{
code: z.ZodIssueCode.invalid_type,
expected: z.ZodParsedType.string,
message: "Required",
path: ["a"],
received: z.ZodParsedType.undefined,
},
]);
}
});
test("wrong schema - missing discriminator", () => {
try {
z.discriminatedUnion("type", [
z.object({ type: z.literal("a"), a: z.string() }),
z.object({ b: z.string() }) as any,
]);
throw new Error();
} catch (e: any) {
expect(e.message.includes("could not be extracted")).toBe(true);
}
});
test("wrong schema - duplicate discriminator values", () => {
try {
z.discriminatedUnion("type", [
z.object({ type: z.literal("a"), a: z.string() }),
z.object({ type: z.literal("a"), b: z.string() }),
]);
throw new Error();
} catch (e: any) {
expect(e.message.includes("has duplicate value")).toEqual(true);
}
});
test("async - valid", async () => {
expect(
await z
.discriminatedUnion("type", [
z.object({
type: z.literal("a"),
a: z
.string()
.refine(async () => true)
.transform(async (val) => Number(val)),
}),
z.object({
type: z.literal("b"),
b: z.string(),
}),
])
.parseAsync({ type: "a", a: "1" })
).toEqual({ type: "a", a: 1 });
});
test("async - invalid", async () => {
try {
await z
.discriminatedUnion("type", [
z.object({
type: z.literal("a"),
a: z
.string()
.refine(async () => true)
.transform(async (val) => val),
}),
z.object({
type: z.literal("b"),
b: z.string(),
}),
])
.parseAsync({ type: "a", a: 1 });
throw new Error();
} catch (e: any) {
expect(JSON.parse(e.message)).toEqual([
{
code: "invalid_type",
expected: "string",
received: "number",
path: ["a"],
message: "Expected string, received number",
},
]);
}
});
test("valid - literals with .default or .preprocess", () => {
const schema = z.discriminatedUnion("type", [
z.object({
type: z.literal("foo").default("foo"),
a: z.string(),
}),
z.object({
type: z.literal("custom"),
method: z.string(),
}),
z.object({
type: z.preprocess((val) => String(val), z.literal("bar")),
c: z.string(),
}),
]);
expect(schema.parse({ type: "foo", a: "foo" })).toEqual({
type: "foo",
a: "foo",
});
});
test("enum and nativeEnum", () => {
enum MyEnum {
d = 0,
e = "e",
}
const schema = z.discriminatedUnion("key", [
z.object({
key: z.literal("a"),
// Add other properties specific to this option
}),
z.object({
key: z.enum(["b", "c"]),
// Add other properties specific to this option
}),
z.object({
key: z.nativeEnum(MyEnum),
// Add other properties specific to this option
}),
]);
// type schema = z.infer<typeof schema>;
schema.parse({ key: "a" });
schema.parse({ key: "b" });
schema.parse({ key: "c" });
schema.parse({ key: MyEnum.d });
schema.parse({ key: MyEnum.e });
schema.parse({ key: "e" });
});
test("branded", () => {
const schema = z.discriminatedUnion("key", [
z.object({
key: z.literal("a"),
// Add other properties specific to this option
}),
z.object({
key: z.literal("b").brand("asdfaf"),
// Add other properties specific to this option
}),
]);
// type schema = z.infer<typeof schema>;
schema.parse({ key: "a" });
schema.parse({ key: "b" });
expect(() => {
schema.parse({ key: "c" });
}).toThrow();
});
test("optional and nullable", () => {
const schema = z.discriminatedUnion("key", [
z.object({
key: z.literal("a").optional(),
a: z.literal(true),
}),
z.object({
key: z.literal("b").nullable(),
b: z.literal(true),
// Add other properties specific to this option
}),
]);
type schema = z.infer<typeof schema>;
z.util.assertEqual<schema, { key?: "a" | undefined; a: true } | { key: "b" | null; b: true }>(true);
schema.parse({ key: "a", a: true });
schema.parse({ key: undefined, a: true });
schema.parse({ key: "b", b: true });
schema.parse({ key: null, b: true });
expect(() => {
schema.parse({ key: null, a: true });
}).toThrow();
expect(() => {
schema.parse({ key: "b", a: true });
}).toThrow();
const value = schema.parse({ key: null, b: true });
if (!("key" in value)) value.a;
if (value.key === undefined) value.a;
if (value.key === "a") value.a;
if (value.key === "b") value.b;
if (value.key === null) value.b;
});
test("readonly array of options", () => {
const options = [
z.object({ type: z.literal("x"), val: z.literal(1) }),
z.object({ type: z.literal("y"), val: z.literal(2) }),
] as const;
expect(z.discriminatedUnion("type", options).parse({ type: "x", val: 1 })).toEqual({ type: "x", val: 1 });
});
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: ebc6d33c463da4e46ac95cd5dd152c70
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336030
packageName: Synaptic AI Pro - Natural Language Control for Unity
packageVersion: 1.2.23
assetPath: Assets/Synaptic AI Pro/MCPServer/node_modules/zod/src/v3/tests/discriminated-unions.test.ts
uploadId: 920982

Some files were not shown because too many files have changed in this diff Show More