This commit is contained in:
2026-10-19 12:16:49 -04:00
parent d7ecab6494
commit 6d3f470922
10446 changed files with 1626249 additions and 2216 deletions
+53
View File
@@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.slugify = exports.toUpperCase = exports.toLowerCase = exports.trim = exports.normalize = exports.overwrite = exports.mime = exports.properties = exports.property = exports.endsWith = exports.startsWith = exports.includes = exports.uppercase = exports.lowercase = exports.regex = exports.length = exports.minLength = exports.maxLength = exports.size = exports.minSize = exports.maxSize = exports.multipleOf = exports.nonnegative = exports.nonpositive = exports.negative = exports.positive = exports.gte = exports.gt = exports.lte = exports.lt = void 0;
var index_js_1 = require("../core/index.cjs");
Object.defineProperty(exports, "lt", { enumerable: true, get: function () { return index_js_1._lt; } });
Object.defineProperty(exports, "lte", { enumerable: true, get: function () { return index_js_1._lte; } });
Object.defineProperty(exports, "gt", { enumerable: true, get: function () { return index_js_1._gt; } });
Object.defineProperty(exports, "gte", { enumerable: true, get: function () { return index_js_1._gte; } });
Object.defineProperty(exports, "positive", { enumerable: true, get: function () { return index_js_1._positive; } });
Object.defineProperty(exports, "negative", { enumerable: true, get: function () { return index_js_1._negative; } });
Object.defineProperty(exports, "nonpositive", { enumerable: true, get: function () { return index_js_1._nonpositive; } });
Object.defineProperty(exports, "nonnegative", { enumerable: true, get: function () { return index_js_1._nonnegative; } });
Object.defineProperty(exports, "multipleOf", { enumerable: true, get: function () { return index_js_1._multipleOf; } });
Object.defineProperty(exports, "maxSize", { enumerable: true, get: function () { return index_js_1._maxSize; } });
Object.defineProperty(exports, "minSize", { enumerable: true, get: function () { return index_js_1._minSize; } });
Object.defineProperty(exports, "size", { enumerable: true, get: function () { return index_js_1._size; } });
Object.defineProperty(exports, "maxLength", { enumerable: true, get: function () { return index_js_1._maxLength; } });
Object.defineProperty(exports, "minLength", { enumerable: true, get: function () { return index_js_1._minLength; } });
Object.defineProperty(exports, "length", { enumerable: true, get: function () { return index_js_1._length; } });
Object.defineProperty(exports, "regex", { enumerable: true, get: function () { return index_js_1._regex; } });
Object.defineProperty(exports, "lowercase", { enumerable: true, get: function () { return index_js_1._lowercase; } });
Object.defineProperty(exports, "uppercase", { enumerable: true, get: function () { return index_js_1._uppercase; } });
Object.defineProperty(exports, "includes", { enumerable: true, get: function () { return index_js_1._includes; } });
Object.defineProperty(exports, "startsWith", { enumerable: true, get: function () { return index_js_1._startsWith; } });
Object.defineProperty(exports, "endsWith", { enumerable: true, get: function () { return index_js_1._endsWith; } });
Object.defineProperty(exports, "property", { enumerable: true, get: function () { return index_js_1._property; } });
Object.defineProperty(exports, "properties", { enumerable: true, get: function () { return index_js_1._properties; } });
Object.defineProperty(exports, "mime", { enumerable: true, get: function () { return index_js_1._mime; } });
Object.defineProperty(exports, "overwrite", { enumerable: true, get: function () { return index_js_1._overwrite; } });
Object.defineProperty(exports, "normalize", { enumerable: true, get: function () { return index_js_1._normalize; } });
Object.defineProperty(exports, "trim", { enumerable: true, get: function () { return index_js_1._trim; } });
Object.defineProperty(exports, "toLowerCase", { enumerable: true, get: function () { return index_js_1._toLowerCase; } });
Object.defineProperty(exports, "toUpperCase", { enumerable: true, get: function () { return index_js_1._toUpperCase; } });
Object.defineProperty(exports, "slugify", { enumerable: true, get: function () { return index_js_1._slugify; } });
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+1
View File
@@ -0,0 +1 @@
export { _lt as lt, _lte as lte, _gt as gt, _gte as gte, _positive as positive, _negative as negative, _nonpositive as nonpositive, _nonnegative as nonnegative, _multipleOf as multipleOf, _maxSize as maxSize, _minSize as minSize, _size as size, _maxLength as maxLength, _minLength as minLength, _length as length, _regex as regex, _lowercase as lowercase, _uppercase as uppercase, _includes as includes, _startsWith as startsWith, _endsWith as endsWith, _property as property, _properties as properties, _mime as mime, _overwrite as overwrite, _normalize as normalize, _trim as trim, _toLowerCase as toLowerCase, _toUpperCase as toUpperCase, _slugify as slugify, type $RefinementCtx as RefinementCtx, } from "../core/index.cjs";
+1
View File
@@ -0,0 +1 @@
export { _lt as lt, _lte as lte, _gt as gt, _gte as gte, _positive as positive, _negative as negative, _nonpositive as nonpositive, _nonnegative as nonnegative, _multipleOf as multipleOf, _maxSize as maxSize, _minSize as minSize, _size as size, _maxLength as maxLength, _minLength as minLength, _length as length, _regex as regex, _lowercase as lowercase, _uppercase as uppercase, _includes as includes, _startsWith as startsWith, _endsWith as endsWith, _property as property, _properties as properties, _mime as mime, _overwrite as overwrite, _normalize as normalize, _trim as trim, _toLowerCase as toLowerCase, _toUpperCase as toUpperCase, _slugify as slugify, type $RefinementCtx as RefinementCtx, } from "../core/index.js";
+1
View File
@@ -0,0 +1 @@
export { _lt as lt, _lte as lte, _gt as gt, _gte as gte, _positive as positive, _negative as negative, _nonpositive as nonpositive, _nonnegative as nonnegative, _multipleOf as multipleOf, _maxSize as maxSize, _minSize as minSize, _size as size, _maxLength as maxLength, _minLength as minLength, _length as length, _regex as regex, _lowercase as lowercase, _uppercase as uppercase, _includes as includes, _startsWith as startsWith, _endsWith as endsWith, _property as property, _properties as properties, _mime as mime, _overwrite as overwrite, _normalize as normalize, _trim as trim, _toLowerCase as toLowerCase, _toUpperCase as toUpperCase, _slugify as slugify, } from "../core/index.js";
+66
View File
@@ -0,0 +1,66 @@
"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.string = string;
exports.number = number;
exports.boolean = boolean;
exports.bigint = bigint;
exports.date = date;
const core = __importStar(require("../core/index.cjs"));
const schemas = __importStar(require("./schemas.cjs"));
function string(params) {
return core._coercedString(schemas.ZodString, params);
}
function number(params) {
return core._coercedNumber(schemas.ZodNumber, params);
}
function boolean(params) {
return core._coercedBoolean(schemas.ZodBoolean, params);
}
function bigint(params) {
return core._coercedBigint(schemas.ZodBigInt, params);
}
function date(params) {
return core._coercedDate(schemas.ZodDate, params);
}
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+17
View File
@@ -0,0 +1,17 @@
import * as core from "../core/index.cjs";
import * as schemas from "./schemas.cjs";
export interface ZodCoercedString<T = unknown> extends schemas._ZodString<core.$ZodStringInternals<T>> {
}
export declare function string<T = unknown>(params?: string | core.$ZodStringParams): ZodCoercedString<T>;
export interface ZodCoercedNumber<T = unknown> extends schemas._ZodNumber<core.$ZodNumberInternals<T>> {
}
export declare function number<T = unknown>(params?: string | core.$ZodNumberParams): ZodCoercedNumber<T>;
export interface ZodCoercedBoolean<T = unknown> extends schemas._ZodBoolean<core.$ZodBooleanInternals<T>> {
}
export declare function boolean<T = unknown>(params?: string | core.$ZodBooleanParams): ZodCoercedBoolean<T>;
export interface ZodCoercedBigInt<T = unknown> extends schemas._ZodBigInt<core.$ZodBigIntInternals<T>> {
}
export declare function bigint<T = unknown>(params?: string | core.$ZodBigIntParams): ZodCoercedBigInt<T>;
export interface ZodCoercedDate<T = unknown> extends schemas._ZodDate<core.$ZodDateInternals<T>> {
}
export declare function date<T = unknown>(params?: string | core.$ZodDateParams): ZodCoercedDate<T>;
+17
View File
@@ -0,0 +1,17 @@
import * as core from "../core/index.js";
import * as schemas from "./schemas.js";
export interface ZodCoercedString<T = unknown> extends schemas._ZodString<core.$ZodStringInternals<T>> {
}
export declare function string<T = unknown>(params?: string | core.$ZodStringParams): ZodCoercedString<T>;
export interface ZodCoercedNumber<T = unknown> extends schemas._ZodNumber<core.$ZodNumberInternals<T>> {
}
export declare function number<T = unknown>(params?: string | core.$ZodNumberParams): ZodCoercedNumber<T>;
export interface ZodCoercedBoolean<T = unknown> extends schemas._ZodBoolean<core.$ZodBooleanInternals<T>> {
}
export declare function boolean<T = unknown>(params?: string | core.$ZodBooleanParams): ZodCoercedBoolean<T>;
export interface ZodCoercedBigInt<T = unknown> extends schemas._ZodBigInt<core.$ZodBigIntInternals<T>> {
}
export declare function bigint<T = unknown>(params?: string | core.$ZodBigIntParams): ZodCoercedBigInt<T>;
export interface ZodCoercedDate<T = unknown> extends schemas._ZodDate<core.$ZodDateInternals<T>> {
}
export declare function date<T = unknown>(params?: string | core.$ZodDateParams): ZodCoercedDate<T>;
+17
View File
@@ -0,0 +1,17 @@
import * as core from "../core/index.js";
import * as schemas from "./schemas.js";
export function string(params) {
return core._coercedString(schemas.ZodString, params);
}
export function number(params) {
return core._coercedNumber(schemas.ZodNumber, params);
}
export function boolean(params) {
return core._coercedBoolean(schemas.ZodBoolean, params);
}
export function bigint(params) {
return core._coercedBigint(schemas.ZodBigInt, params);
}
export function date(params) {
return core._coercedDate(schemas.ZodDate, params);
}
+80
View File
@@ -0,0 +1,80 @@
"use strict";
// Zod 3 compat layer
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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodFirstPartyTypeKind = exports.config = exports.$brand = exports.ZodIssueCode = void 0;
exports.setErrorMap = setErrorMap;
exports.getErrorMap = getErrorMap;
const core = __importStar(require("../core/index.cjs"));
/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */
exports.ZodIssueCode = {
invalid_type: "invalid_type",
too_big: "too_big",
too_small: "too_small",
invalid_format: "invalid_format",
not_multiple_of: "not_multiple_of",
unrecognized_keys: "unrecognized_keys",
invalid_union: "invalid_union",
invalid_key: "invalid_key",
invalid_element: "invalid_element",
invalid_value: "invalid_value",
custom: "custom",
};
var index_js_1 = require("../core/index.cjs");
Object.defineProperty(exports, "$brand", { enumerable: true, get: function () { return index_js_1.$brand; } });
Object.defineProperty(exports, "config", { enumerable: true, get: function () { return index_js_1.config; } });
/** @deprecated Use `z.config(params)` instead. */
function setErrorMap(map) {
core.config({
customError: map,
});
}
/** @deprecated Use `z.config()` instead. */
function getErrorMap() {
return core.config().customError;
}
/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */
var ZodFirstPartyTypeKind;
(function (ZodFirstPartyTypeKind) {
})(ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = ZodFirstPartyTypeKind = {}));
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+48
View File
@@ -0,0 +1,48 @@
import * as core from "../core/index.cjs";
import type { ZodType } from "./schemas.cjs";
/** @deprecated Use `z.output<T>` instead. */
export type TypeOf<T> = core.output<T>;
/** @deprecated Use `z.output<T>` instead. */
export type Infer<T> = core.output<T>;
/** @deprecated Use `z.core.$ZodTypes` instead */
export type ZodFirstPartySchemaTypes = core.$ZodTypes;
/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */
export declare const ZodIssueCode: {
readonly invalid_type: "invalid_type";
readonly too_big: "too_big";
readonly too_small: "too_small";
readonly invalid_format: "invalid_format";
readonly not_multiple_of: "not_multiple_of";
readonly unrecognized_keys: "unrecognized_keys";
readonly invalid_union: "invalid_union";
readonly invalid_key: "invalid_key";
readonly invalid_element: "invalid_element";
readonly invalid_value: "invalid_value";
readonly custom: "custom";
};
/** @deprecated Use `z.core.$ZodFlattenedError<z.output<T>>` instead; it takes an inferred type, not a schema. */
export type inferFlattenedErrors<T extends core.$ZodType, U = string> = core.$ZodFlattenedError<core.output<T>, U>;
/** @deprecated Use `z.core.$ZodFormattedError<z.output<T>>` instead; it takes an inferred type, not a schema. */
export type inferFormattedError<T extends core.$ZodType<any, any>, U = string> = core.$ZodFormattedError<core.output<T>, U>;
/** Use `z.$brand` instead */
export type BRAND<T extends string | number | symbol = string | number | symbol> = {
[core.$brand]: {
[k in T]: true;
};
};
export { $brand, config } from "../core/index.cjs";
/** @deprecated Use `z.config(params)` instead. */
export declare function setErrorMap(map: core.$ZodErrorMap): void;
/** @deprecated Use `z.config()` instead. */
export declare function getErrorMap(): core.$ZodErrorMap<core.$ZodIssue> | undefined;
/** @deprecated Use z.ZodType (without generics) instead. */
export type ZodTypeAny<Output = unknown, Input = unknown, Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> = ZodType<Output, Input, Internals>;
/** @deprecated Use `z.ZodType` */
export type ZodSchema<Output = unknown, Input = unknown, Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> = ZodType<Output, Input, Internals>;
/** @deprecated Use `z.ZodType` */
export type Schema<Output = unknown, Input = unknown, Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> = ZodType<Output, Input, Internals>;
/** Included for Zod 3 compatibility */
export type ZodRawShape = core.$ZodShape;
/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */
export declare enum ZodFirstPartyTypeKind {
}
+48
View File
@@ -0,0 +1,48 @@
import * as core from "../core/index.js";
import type { ZodType } from "./schemas.js";
/** @deprecated Use `z.output<T>` instead. */
export type TypeOf<T> = core.output<T>;
/** @deprecated Use `z.output<T>` instead. */
export type Infer<T> = core.output<T>;
/** @deprecated Use `z.core.$ZodTypes` instead */
export type ZodFirstPartySchemaTypes = core.$ZodTypes;
/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */
export declare const ZodIssueCode: {
readonly invalid_type: "invalid_type";
readonly too_big: "too_big";
readonly too_small: "too_small";
readonly invalid_format: "invalid_format";
readonly not_multiple_of: "not_multiple_of";
readonly unrecognized_keys: "unrecognized_keys";
readonly invalid_union: "invalid_union";
readonly invalid_key: "invalid_key";
readonly invalid_element: "invalid_element";
readonly invalid_value: "invalid_value";
readonly custom: "custom";
};
/** @deprecated Use `z.core.$ZodFlattenedError<z.output<T>>` instead; it takes an inferred type, not a schema. */
export type inferFlattenedErrors<T extends core.$ZodType, U = string> = core.$ZodFlattenedError<core.output<T>, U>;
/** @deprecated Use `z.core.$ZodFormattedError<z.output<T>>` instead; it takes an inferred type, not a schema. */
export type inferFormattedError<T extends core.$ZodType<any, any>, U = string> = core.$ZodFormattedError<core.output<T>, U>;
/** Use `z.$brand` instead */
export type BRAND<T extends string | number | symbol = string | number | symbol> = {
[core.$brand]: {
[k in T]: true;
};
};
export { $brand, config } from "../core/index.js";
/** @deprecated Use `z.config(params)` instead. */
export declare function setErrorMap(map: core.$ZodErrorMap): void;
/** @deprecated Use `z.config()` instead. */
export declare function getErrorMap(): core.$ZodErrorMap<core.$ZodIssue> | undefined;
/** @deprecated Use z.ZodType (without generics) instead. */
export type ZodTypeAny<Output = unknown, Input = unknown, Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> = ZodType<Output, Input, Internals>;
/** @deprecated Use `z.ZodType` */
export type ZodSchema<Output = unknown, Input = unknown, Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> = ZodType<Output, Input, Internals>;
/** @deprecated Use `z.ZodType` */
export type Schema<Output = unknown, Input = unknown, Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> = ZodType<Output, Input, Internals>;
/** Included for Zod 3 compatibility */
export type ZodRawShape = core.$ZodShape;
/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */
export declare enum ZodFirstPartyTypeKind {
}
+31
View File
@@ -0,0 +1,31 @@
// Zod 3 compat layer
import * as core from "../core/index.js";
/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */
export const ZodIssueCode = {
invalid_type: "invalid_type",
too_big: "too_big",
too_small: "too_small",
invalid_format: "invalid_format",
not_multiple_of: "not_multiple_of",
unrecognized_keys: "unrecognized_keys",
invalid_union: "invalid_union",
invalid_key: "invalid_key",
invalid_element: "invalid_element",
invalid_value: "invalid_value",
custom: "custom",
};
export { $brand, config } from "../core/index.js";
/** @deprecated Use `z.config(params)` instead. */
export function setErrorMap(map) {
core.config({
customError: map,
});
}
/** @deprecated Use `z.config()` instead. */
export function getErrorMap() {
return core.config().customError;
}
/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */
export var ZodFirstPartyTypeKind;
(function (ZodFirstPartyTypeKind) {
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
+58
View File
@@ -0,0 +1,58 @@
"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deepPartial = deepPartial;
const visit_js_1 = require("../core/visit.cjs");
const schemas = __importStar(require("./schemas.cjs"));
/** Returns a copy of the schema with every nested object's properties made optional. */
function deepPartial(schema) {
return (0, visit_js_1.visit)(schema, {
object: (s) => s.partial(),
// Every partialed option now admits `undefined`, which the constructor rejects as a duplicate.
union: (s) => {
const def = s._zod.def;
return def.discriminator === undefined ? s : schemas.union(def.options);
},
});
}
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+14
View File
@@ -0,0 +1,14 @@
import type * as core from "../core/index.cjs";
import * as schemas from "./schemas.cjs";
/** Distributes `.partial()` through every object in a schema type, preserving the wrappers around them. */
export type DeepPartial<T extends core.SomeType> = T extends schemas.ZodObject<infer Shape, infer Config> ? schemas.ZodObject<{
-readonly [K in keyof Shape]: schemas.ZodOptional<DeepPartial<Shape[K]>>;
}, Config> : T extends schemas.ZodDiscriminatedUnion<infer Options, any> ? schemas.ZodUnion<{
-readonly [I in keyof Options]: Options[I] extends core.SomeType ? DeepPartial<Options[I]> : Options[I];
}> : T extends schemas.ZodUnion<infer Options> ? schemas.ZodUnion<{
-readonly [I in keyof Options]: Options[I] extends core.SomeType ? DeepPartial<Options[I]> : Options[I];
}> : T extends schemas.ZodArray<infer El> ? schemas.ZodArray<DeepPartial<El>> : T extends schemas.ZodTuple<infer Items, infer Rest> ? schemas.ZodTuple<{
-readonly [K in keyof Items]: Items[K] extends core.SomeType ? DeepPartial<Items[K]> : Items[K];
}, Rest extends core.SomeType ? DeepPartial<Rest> : Rest> : T extends schemas.ZodIntersection<infer A, infer B> ? schemas.ZodIntersection<DeepPartial<A>, DeepPartial<B>> : T extends schemas.ZodRecord<infer K, infer V> ? schemas.ZodRecord<K, DeepPartial<V>> : T extends schemas.ZodMap<infer K, infer V> ? schemas.ZodMap<K, DeepPartial<V>> : T extends schemas.ZodSet<infer El> ? schemas.ZodSet<DeepPartial<El>> : T extends schemas.ZodOptional<infer Inner> ? schemas.ZodOptional<DeepPartial<Inner>> : T extends schemas.ZodNullable<infer Inner> ? schemas.ZodNullable<DeepPartial<Inner>> : T extends schemas.ZodDefault<infer Inner> ? schemas.ZodDefault<DeepPartial<Inner>> : T extends schemas.ZodPrefault<infer Inner> ? schemas.ZodPrefault<DeepPartial<Inner>> : T extends schemas.ZodNonOptional<infer Inner> ? schemas.ZodNonOptional<DeepPartial<Inner>> : T extends schemas.ZodCatch<infer Inner> ? schemas.ZodCatch<DeepPartial<Inner>> : T extends schemas.ZodReadonly<infer Inner> ? schemas.ZodReadonly<DeepPartial<Inner>> : T extends schemas.ZodSuccess<infer Inner> ? schemas.ZodSuccess<DeepPartial<Inner>> : T extends schemas.ZodPromise<infer Inner> ? schemas.ZodPromise<DeepPartial<Inner>> : T extends schemas.ZodCodec<infer A, infer B> ? schemas.ZodCodec<DeepPartial<A>, DeepPartial<B>> : T extends schemas.ZodPreprocess<infer B> ? schemas.ZodPreprocess<DeepPartial<B>> : T extends schemas.ZodPipe<infer A, infer B> ? schemas.ZodPipe<DeepPartial<A>, DeepPartial<B>> : T extends schemas.ZodLazy<infer Inner> ? schemas.ZodLazy<DeepPartial<Inner>> : T;
/** Returns a copy of the schema with every nested object's properties made optional. */
export declare function deepPartial<T extends core.SomeType>(schema: T): DeepPartial<T>;
+14
View File
@@ -0,0 +1,14 @@
import type * as core from "../core/index.js";
import * as schemas from "./schemas.js";
/** Distributes `.partial()` through every object in a schema type, preserving the wrappers around them. */
export type DeepPartial<T extends core.SomeType> = T extends schemas.ZodObject<infer Shape, infer Config> ? schemas.ZodObject<{
-readonly [K in keyof Shape]: schemas.ZodOptional<DeepPartial<Shape[K]>>;
}, Config> : T extends schemas.ZodDiscriminatedUnion<infer Options, any> ? schemas.ZodUnion<{
-readonly [I in keyof Options]: Options[I] extends core.SomeType ? DeepPartial<Options[I]> : Options[I];
}> : T extends schemas.ZodUnion<infer Options> ? schemas.ZodUnion<{
-readonly [I in keyof Options]: Options[I] extends core.SomeType ? DeepPartial<Options[I]> : Options[I];
}> : T extends schemas.ZodArray<infer El> ? schemas.ZodArray<DeepPartial<El>> : T extends schemas.ZodTuple<infer Items, infer Rest> ? schemas.ZodTuple<{
-readonly [K in keyof Items]: Items[K] extends core.SomeType ? DeepPartial<Items[K]> : Items[K];
}, Rest extends core.SomeType ? DeepPartial<Rest> : Rest> : T extends schemas.ZodIntersection<infer A, infer B> ? schemas.ZodIntersection<DeepPartial<A>, DeepPartial<B>> : T extends schemas.ZodRecord<infer K, infer V> ? schemas.ZodRecord<K, DeepPartial<V>> : T extends schemas.ZodMap<infer K, infer V> ? schemas.ZodMap<K, DeepPartial<V>> : T extends schemas.ZodSet<infer El> ? schemas.ZodSet<DeepPartial<El>> : T extends schemas.ZodOptional<infer Inner> ? schemas.ZodOptional<DeepPartial<Inner>> : T extends schemas.ZodNullable<infer Inner> ? schemas.ZodNullable<DeepPartial<Inner>> : T extends schemas.ZodDefault<infer Inner> ? schemas.ZodDefault<DeepPartial<Inner>> : T extends schemas.ZodPrefault<infer Inner> ? schemas.ZodPrefault<DeepPartial<Inner>> : T extends schemas.ZodNonOptional<infer Inner> ? schemas.ZodNonOptional<DeepPartial<Inner>> : T extends schemas.ZodCatch<infer Inner> ? schemas.ZodCatch<DeepPartial<Inner>> : T extends schemas.ZodReadonly<infer Inner> ? schemas.ZodReadonly<DeepPartial<Inner>> : T extends schemas.ZodSuccess<infer Inner> ? schemas.ZodSuccess<DeepPartial<Inner>> : T extends schemas.ZodPromise<infer Inner> ? schemas.ZodPromise<DeepPartial<Inner>> : T extends schemas.ZodCodec<infer A, infer B> ? schemas.ZodCodec<DeepPartial<A>, DeepPartial<B>> : T extends schemas.ZodPreprocess<infer B> ? schemas.ZodPreprocess<DeepPartial<B>> : T extends schemas.ZodPipe<infer A, infer B> ? schemas.ZodPipe<DeepPartial<A>, DeepPartial<B>> : T extends schemas.ZodLazy<infer Inner> ? schemas.ZodLazy<DeepPartial<Inner>> : T;
/** Returns a copy of the schema with every nested object's properties made optional. */
export declare function deepPartial<T extends core.SomeType>(schema: T): DeepPartial<T>;
+13
View File
@@ -0,0 +1,13 @@
import { visit } from "../core/visit.js";
import * as schemas from "./schemas.js";
/** Returns a copy of the schema with every nested object's properties made optional. */
export function deepPartial(schema) {
return visit(schema, {
object: (s) => s.partial(),
// Every partialed option now admits `undefined`, which the constructor rejects as a duplicate.
union: (s) => {
const def = s._zod.def;
return def.discriminator === undefined ? s : schemas.union(def.options);
},
});
}
+102
View File
@@ -0,0 +1,102 @@
"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodRealError = exports.ZodError = void 0;
const core = __importStar(require("../core/index.cjs"));
const index_js_1 = require("../core/index.cjs");
const util = __importStar(require("../core/util.cjs"));
/* Prototypes that already carry the lazy helper methods. Seeded with the
* intrinsics so that `init` on a foreign object — it accepts any object —
* can never install an accessor onto a prototype we do not own. */
const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
/* Helper methods live as non-enumerable lazy getters on the shared
* prototype instead of own properties on every instance. On first
* access the getter allocates the per-instance closure and caches it
* as a non-enumerable own property, so detached usage still works and
* the allocation only happens for methods actually touched. */
function _lazyMethod(proto, key, make) {
Object.defineProperty(proto, key, {
configurable: true,
enumerable: false,
get() {
const value = make(this);
Object.defineProperty(this, key, { value, configurable: true, writable: true });
return value;
},
set(value) {
Object.defineProperty(this, key, { value, configurable: true, writable: true });
},
});
}
const initializer = (inst, issues) => {
index_js_1.$ZodError.init(inst, issues);
inst.name = "ZodError";
const proto = Object.getPrototypeOf(inst);
if (_installedErrorProtos.has(proto))
return;
_installedErrorProtos.add(proto);
_lazyMethod(proto, "format", (self) => (mapper) => core.formatError(self, mapper));
_lazyMethod(proto, "flatten", (self) => (mapper) => core.flattenError(self, mapper));
_lazyMethod(proto, "addIssue", (self) => (issue) => {
self.issues.push(issue);
self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);
});
_lazyMethod(proto, "addIssues", (self) => (issues) => {
self.issues.push(...issues);
self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);
});
Object.defineProperty(proto, "isEmpty", {
configurable: true,
enumerable: false,
get() {
return this.issues.length === 0;
},
});
};
exports.ZodError = core.$constructor("ZodError", initializer);
exports.ZodRealError = core.$constructor("ZodError", initializer, undefined, {
Parent: Error,
});
// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */
// export type ErrorMapCtx = core.$ZodErrorMapCtx;
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+29
View File
@@ -0,0 +1,29 @@
import * as core from "../core/index.cjs";
import { $ZodError } from "../core/index.cjs";
/** @deprecated Use `z.core.$ZodIssue` from `@zod/core` instead, especially if you are building a library on top of Zod. */
export type ZodIssue = core.$ZodIssue;
/** An Error-like class used to store Zod validation issues. */
export interface ZodError<T = unknown> extends $ZodError<T> {
/** @deprecated Use the `z.treeifyError(err)` function instead. */
format(): core.$ZodFormattedError<T>;
format<U>(mapper: (issue: core.$ZodIssue) => U): core.$ZodFormattedError<T, U>;
/** @deprecated Use the `z.treeifyError(err)` function instead. */
flatten(): core.$ZodFlattenedError<T>;
flatten<U>(mapper: (issue: core.$ZodIssue) => U): core.$ZodFlattenedError<T, U>;
/** @deprecated Push directly to `.issues` instead. */
addIssue(issue: core.$ZodIssue): void;
/** @deprecated Push directly to `.issues` instead. */
addIssues(issues: core.$ZodIssue[]): void;
/** @deprecated Check `err.issues.length === 0` instead. */
isEmpty: boolean;
}
export declare const ZodError: core.$constructor<ZodError>;
export declare const ZodRealError: core.$constructor<ZodError>;
/** @deprecated Use `z.core.$ZodFlattenedError` instead. */
export type ZodFlattenedError<T, U = string> = core.$ZodFlattenedError<T, U>;
/** @deprecated Use `z.core.$ZodFormattedError` instead. */
export type ZodFormattedError<T, U = string> = core.$ZodFormattedError<T, U>;
/** @deprecated Use `z.core.$ZodErrorMap` instead. */
export type ZodErrorMap<T extends core.$ZodIssueBase = core.$ZodIssue> = core.$ZodErrorMap<T>;
/** @deprecated Use `z.core.$ZodRawIssue` instead. */
export type IssueData = core.$ZodRawIssue;
+29
View File
@@ -0,0 +1,29 @@
import * as core from "../core/index.js";
import { $ZodError } from "../core/index.js";
/** @deprecated Use `z.core.$ZodIssue` from `@zod/core` instead, especially if you are building a library on top of Zod. */
export type ZodIssue = core.$ZodIssue;
/** An Error-like class used to store Zod validation issues. */
export interface ZodError<T = unknown> extends $ZodError<T> {
/** @deprecated Use the `z.treeifyError(err)` function instead. */
format(): core.$ZodFormattedError<T>;
format<U>(mapper: (issue: core.$ZodIssue) => U): core.$ZodFormattedError<T, U>;
/** @deprecated Use the `z.treeifyError(err)` function instead. */
flatten(): core.$ZodFlattenedError<T>;
flatten<U>(mapper: (issue: core.$ZodIssue) => U): core.$ZodFlattenedError<T, U>;
/** @deprecated Push directly to `.issues` instead. */
addIssue(issue: core.$ZodIssue): void;
/** @deprecated Push directly to `.issues` instead. */
addIssues(issues: core.$ZodIssue[]): void;
/** @deprecated Check `err.issues.length === 0` instead. */
isEmpty: boolean;
}
export declare const ZodError: core.$constructor<ZodError>;
export declare const ZodRealError: core.$constructor<ZodError>;
/** @deprecated Use `z.core.$ZodFlattenedError` instead. */
export type ZodFlattenedError<T, U = string> = core.$ZodFlattenedError<T, U>;
/** @deprecated Use `z.core.$ZodFormattedError` instead. */
export type ZodFormattedError<T, U = string> = core.$ZodFormattedError<T, U>;
/** @deprecated Use `z.core.$ZodErrorMap` instead. */
export type ZodErrorMap<T extends core.$ZodIssueBase = core.$ZodIssue> = core.$ZodErrorMap<T>;
/** @deprecated Use `z.core.$ZodRawIssue` instead. */
export type IssueData = core.$ZodRawIssue;
+57
View File
@@ -0,0 +1,57 @@
import * as core from "../core/index.js";
import { $ZodError } from "../core/index.js";
import * as util from "../core/util.js";
/* Prototypes that already carry the lazy helper methods. Seeded with the
* intrinsics so that `init` on a foreign object — it accepts any object —
* can never install an accessor onto a prototype we do not own. */
const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
/* Helper methods live as non-enumerable lazy getters on the shared
* prototype instead of own properties on every instance. On first
* access the getter allocates the per-instance closure and caches it
* as a non-enumerable own property, so detached usage still works and
* the allocation only happens for methods actually touched. */
function _lazyMethod(proto, key, make) {
Object.defineProperty(proto, key, {
configurable: true,
enumerable: false,
get() {
const value = make(this);
Object.defineProperty(this, key, { value, configurable: true, writable: true });
return value;
},
set(value) {
Object.defineProperty(this, key, { value, configurable: true, writable: true });
},
});
}
const initializer = (inst, issues) => {
$ZodError.init(inst, issues);
inst.name = "ZodError";
const proto = Object.getPrototypeOf(inst);
if (_installedErrorProtos.has(proto))
return;
_installedErrorProtos.add(proto);
_lazyMethod(proto, "format", (self) => (mapper) => core.formatError(self, mapper));
_lazyMethod(proto, "flatten", (self) => (mapper) => core.flattenError(self, mapper));
_lazyMethod(proto, "addIssue", (self) => (issue) => {
self.issues.push(issue);
self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);
});
_lazyMethod(proto, "addIssues", (self) => (issues) => {
self.issues.push(...issues);
self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);
});
Object.defineProperty(proto, "isEmpty", {
configurable: true,
enumerable: false,
get() {
return this.issues.length === 0;
},
});
};
export const ZodError = /*@__PURE__*/ core.$constructor("ZodError", initializer);
export const ZodRealError = /*@__PURE__*/ core.$constructor("ZodError", initializer, undefined, {
Parent: Error,
});
// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */
// export type ErrorMapCtx = core.$ZodErrorMapCtx;
+97
View File
@@ -0,0 +1,97 @@
"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.coerce = exports.iso = exports.ZodISODuration = exports.ZodISOTime = exports.ZodISODate = exports.ZodISODateTime = exports.locales = exports.output = exports.input = exports.deepPartial = exports.fromJSONSchema = exports.toJSONSchema = exports.getDiscriminatedOption = exports.ZodCompileUnsupportedError = exports.ZodCompileAsyncError = exports.withParser = exports.compile = exports.toZod = exports.INVALID = exports.NEVER = exports.util = exports.TimePrecision = exports.flattenError = exports.formatError = exports.prettifyError = exports.treeifyError = exports.regexes = exports.clone = exports.$brand = exports.$input = exports.$output = exports.memoizer = exports.config = exports.registry = exports.globalRegistry = exports.core = void 0;
exports.core = __importStar(require("../core/index.cjs"));
__exportStar(require("./schemas.cjs"), exports);
__exportStar(require("./checks.cjs"), exports);
__exportStar(require("./errors.cjs"), exports);
__exportStar(require("./parse.cjs"), exports);
__exportStar(require("./compat.cjs"), exports);
var index_js_1 = require("../core/index.cjs");
Object.defineProperty(exports, "globalRegistry", { enumerable: true, get: function () { return index_js_1.globalRegistry; } });
Object.defineProperty(exports, "registry", { enumerable: true, get: function () { return index_js_1.registry; } });
Object.defineProperty(exports, "config", { enumerable: true, get: function () { return index_js_1.config; } });
Object.defineProperty(exports, "memoizer", { enumerable: true, get: function () { return index_js_1.memoizer; } });
Object.defineProperty(exports, "$output", { enumerable: true, get: function () { return index_js_1.$output; } });
Object.defineProperty(exports, "$input", { enumerable: true, get: function () { return index_js_1.$input; } });
Object.defineProperty(exports, "$brand", { enumerable: true, get: function () { return index_js_1.$brand; } });
Object.defineProperty(exports, "clone", { enumerable: true, get: function () { return index_js_1.clone; } });
Object.defineProperty(exports, "regexes", { enumerable: true, get: function () { return index_js_1.regexes; } });
Object.defineProperty(exports, "treeifyError", { enumerable: true, get: function () { return index_js_1.treeifyError; } });
Object.defineProperty(exports, "prettifyError", { enumerable: true, get: function () { return index_js_1.prettifyError; } });
Object.defineProperty(exports, "formatError", { enumerable: true, get: function () { return index_js_1.formatError; } });
Object.defineProperty(exports, "flattenError", { enumerable: true, get: function () { return index_js_1.flattenError; } });
Object.defineProperty(exports, "TimePrecision", { enumerable: true, get: function () { return index_js_1.TimePrecision; } });
Object.defineProperty(exports, "util", { enumerable: true, get: function () { return index_js_1.util; } });
Object.defineProperty(exports, "NEVER", { enumerable: true, get: function () { return index_js_1.NEVER; } });
Object.defineProperty(exports, "INVALID", { enumerable: true, get: function () { return index_js_1.INVALID; } });
Object.defineProperty(exports, "toZod", { enumerable: true, get: function () { return index_js_1.toZod; } });
Object.defineProperty(exports, "compile", { enumerable: true, get: function () { return index_js_1.compile; } });
Object.defineProperty(exports, "withParser", { enumerable: true, get: function () { return index_js_1.withParser; } });
Object.defineProperty(exports, "ZodCompileAsyncError", { enumerable: true, get: function () { return index_js_1.ZodCompileAsyncError; } });
Object.defineProperty(exports, "ZodCompileUnsupportedError", { enumerable: true, get: function () { return index_js_1.ZodCompileUnsupportedError; } });
Object.defineProperty(exports, "getDiscriminatedOption", { enumerable: true, get: function () { return index_js_1.getDiscriminatedOption; } });
var json_schema_processors_js_1 = require("../core/json-schema-processors.cjs");
Object.defineProperty(exports, "toJSONSchema", { enumerable: true, get: function () { return json_schema_processors_js_1.toJSONSchema; } });
var from_json_schema_js_1 = require("./from-json-schema.cjs");
Object.defineProperty(exports, "fromJSONSchema", { enumerable: true, get: function () { return from_json_schema_js_1.fromJSONSchema; } });
var deep_partial_js_1 = require("./deep-partial.cjs");
Object.defineProperty(exports, "deepPartial", { enumerable: true, get: function () { return deep_partial_js_1.deepPartial; } });
// Types and values both, from one module — re-exporting the types from core would collide.
var in_out_js_1 = require("./in-out.cjs");
Object.defineProperty(exports, "input", { enumerable: true, get: function () { return in_out_js_1.input; } });
Object.defineProperty(exports, "output", { enumerable: true, get: function () { return in_out_js_1.output; } });
exports.locales = __importStar(require("../locales/index.cjs"));
// iso must be exported from top-level https://github.com/colinhacks/zod/issues/4491
var iso_js_1 = require("./iso.cjs");
Object.defineProperty(exports, "ZodISODateTime", { enumerable: true, get: function () { return iso_js_1.ZodISODateTime; } });
Object.defineProperty(exports, "ZodISODate", { enumerable: true, get: function () { return iso_js_1.ZodISODate; } });
Object.defineProperty(exports, "ZodISOTime", { enumerable: true, get: function () { return iso_js_1.ZodISOTime; } });
Object.defineProperty(exports, "ZodISODuration", { enumerable: true, get: function () { return iso_js_1.ZodISODuration; } });
exports.iso = __importStar(require("./iso.cjs"));
exports.coerce = __importStar(require("./coerce.cjs"));
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+19
View File
@@ -0,0 +1,19 @@
export * as core from "../core/index.cjs";
export * from "./schemas.cjs";
export * from "./checks.cjs";
export * from "./errors.cjs";
export * from "./parse.cjs";
export * from "./compat.cjs";
export type { infer } from "../core/index.cjs";
export type { JSONType } from "../core/util.cjs";
export type { CompileOptions } from "../core/index.cjs";
export { globalRegistry, type GlobalMeta, registry, config, memoizer, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, INVALID, toZod, compile, withParser, ZodCompileAsyncError, ZodCompileUnsupportedError, getDiscriminatedOption, } from "../core/index.cjs";
export { toJSONSchema } from "../core/json-schema-processors.cjs";
export { fromJSONSchema } from "./from-json-schema.cjs";
export { deepPartial } from "./deep-partial.cjs";
export { input, output } from "./in-out.cjs";
export * as locales from "../locales/index.cjs";
export { ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration } from "./iso.cjs";
export * as iso from "./iso.cjs";
export type { ZodCoercedString, ZodCoercedNumber, ZodCoercedBigInt, ZodCoercedBoolean, ZodCoercedDate, } from "./coerce.cjs";
export * as coerce from "./coerce.cjs";
+19
View File
@@ -0,0 +1,19 @@
export * as core from "../core/index.js";
export * from "./schemas.js";
export * from "./checks.js";
export * from "./errors.js";
export * from "./parse.js";
export * from "./compat.js";
export type { infer } from "../core/index.js";
export type { JSONType } from "../core/util.js";
export type { CompileOptions } from "../core/index.js";
export { globalRegistry, type GlobalMeta, registry, config, memoizer, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, INVALID, toZod, compile, withParser, ZodCompileAsyncError, ZodCompileUnsupportedError, getDiscriminatedOption, } from "../core/index.js";
export { toJSONSchema } from "../core/json-schema-processors.js";
export { fromJSONSchema } from "./from-json-schema.js";
export { deepPartial } from "./deep-partial.js";
export { input, output } from "./in-out.js";
export * as locales from "../locales/index.js";
export { ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration } from "./iso.js";
export * as iso from "./iso.js";
export type { ZodCoercedString, ZodCoercedNumber, ZodCoercedBigInt, ZodCoercedBoolean, ZodCoercedDate, } from "./coerce.js";
export * as coerce from "./coerce.js";
+17
View File
@@ -0,0 +1,17 @@
export * as core from "../core/index.js";
export * from "./schemas.js";
export * from "./checks.js";
export * from "./errors.js";
export * from "./parse.js";
export * from "./compat.js";
export { globalRegistry, registry, config, memoizer, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, INVALID, toZod, compile, withParser, ZodCompileAsyncError, ZodCompileUnsupportedError, getDiscriminatedOption, } from "../core/index.js";
export { toJSONSchema } from "../core/json-schema-processors.js";
export { fromJSONSchema } from "./from-json-schema.js";
export { deepPartial } from "./deep-partial.js";
// Types and values both, from one module — re-exporting the types from core would collide.
export { input, output } from "./in-out.js";
export * as locales from "../locales/index.js";
// iso must be exported from top-level https://github.com/colinhacks/zod/issues/4491
export { ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration } from "./iso.js";
export * as iso from "./iso.js";
export * as coerce from "./coerce.js";
+926
View File
@@ -0,0 +1,926 @@
"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromJSONSchema = fromJSONSchema;
const registries_js_1 = require("../core/registries.cjs");
const util_js_1 = require("../core/util.cjs");
const _checks = __importStar(require("./checks.cjs"));
const _iso = __importStar(require("./iso.cjs"));
const _schemas = __importStar(require("./schemas.cjs"));
// Local z object to avoid circular dependency with ../index.js
const z = {
..._schemas,
..._checks,
iso: _iso,
};
// Keys that are recognized and handled by the conversion logic
const RECOGNIZED_KEYS = /*@__PURE__*/ new Set([
// Schema identification
"$schema",
"$ref",
"$defs",
"definitions",
// Core schema keywords
"$id",
"id",
"$comment",
"$anchor",
"$vocabulary",
"$dynamicRef",
"$dynamicAnchor",
// Type
"type",
"enum",
"const",
// Composition
"anyOf",
"oneOf",
"allOf",
"not",
// Object
"properties",
"required",
"additionalProperties",
"patternProperties",
"propertyNames",
"minProperties",
"maxProperties",
// Array
"items",
"prefixItems",
"additionalItems",
"minItems",
"maxItems",
"uniqueItems",
"contains",
"minContains",
"maxContains",
// String
"minLength",
"maxLength",
"pattern",
"format",
// Number
"minimum",
"maximum",
"exclusiveMinimum",
"exclusiveMaximum",
"multipleOf",
// Already handled metadata
"description",
"default",
// Content
"contentEncoding",
"contentMediaType",
"contentSchema",
// Unsupported (error-throwing)
"unevaluatedItems",
"unevaluatedProperties",
"if",
"then",
"else",
"dependentSchemas",
"dependentRequired",
// OpenAPI
"nullable",
"readOnly",
]);
function detectVersion(schema, defaultTarget) {
const $schema = schema.$schema;
if ($schema === "https://json-schema.org/draft/2020-12/schema") {
return "draft-2020-12";
}
if ($schema === "http://json-schema.org/draft-07/schema#") {
return "draft-7";
}
if ($schema === "http://json-schema.org/draft-04/schema#") {
return "draft-4";
}
// Use defaultTarget if provided, otherwise default to draft-2020-12
return defaultTarget ?? "draft-2020-12";
}
// Positional schemas constrain the elements that are present; only minItems makes them required.
function applyMinItems(items, minItems) {
return items.map((item, index) => (index < minItems ? item : item.optional()));
}
// Inverse of the encoding applied to $ref pointer segments in to-json-schema.ts. Per RFC 6901 the `~1` replacement must run before `~0`.
function decodeJSONPointerSegment(segment) {
return segment.replace(/~1/g, "/").replace(/~0/g, "~");
}
function resolveRef(ref, ctx) {
if (!ref.startsWith("#")) {
throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
}
const path = ref.slice(1).split("/").filter(Boolean);
// Handle root reference "#"
if (path.length === 0) {
return ctx.rootSchema;
}
const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
if (path[0] === defsKey) {
const key = path[1] === undefined ? undefined : decodeJSONPointerSegment(path[1]);
if (!key || !ctx.defs[key]) {
throw new Error(`Reference not found: ${ref}`);
}
return ctx.defs[key];
}
throw new Error(`Reference not found: ${ref}`);
}
/**
* Enforces the keywords that constrain an object's own keys — `propertyNames`,
* `minProperties`, `maxProperties` — before `objectSchema` runs. The guard has
* to see the raw input: an object parse drops `__proto__` and can add keys from
* a property `default`, so its output is not the set of names the instance
* actually carried.
*/
function checkObjectGuards(objectSchema, guards) {
// An identity transform, not z.any(), so `toJSONSchema` reports the object on both the input and the output side of the pipe.
const guard = z
.transform((value) => value)
.check((payload) => {
const value = payload.value;
if (typeof value !== "object" || value === null || Array.isArray(value))
return;
const keys = Object.getOwnPropertyNames(value);
if (guards.minProperties !== undefined && keys.length < guards.minProperties) {
payload.issues.push({
origin: "object",
code: "too_small",
minimum: guards.minProperties,
inclusive: true,
message: `Too small: expected object to have >=${guards.minProperties} properties`,
input: value,
inst: objectSchema,
continue: true,
});
}
if (guards.maxProperties !== undefined && keys.length > guards.maxProperties) {
payload.issues.push({
origin: "object",
code: "too_big",
maximum: guards.maxProperties,
inclusive: true,
message: `Too big: expected object to have <=${guards.maxProperties} properties`,
input: value,
inst: objectSchema,
continue: true,
});
}
if (guards.keySchema) {
for (const key of keys) {
const result = guards.keySchema.safeParse(key);
if (result.success)
continue;
payload.issues.push({
code: "invalid_key",
origin: "record",
issues: result.error.issues,
input: key,
path: [key],
continue: true,
});
}
}
});
return guard.pipe(objectSchema);
}
/**
* An injective string for JSON data: two values share a key exactly when `uniqueItems` calls them
* equal, so duplicate detection is a Map lookup rather than a pairwise walk. Strings and keys are
* length-prefixed so no value can spell another one. `null` means "never equal to anything" — a
* cycle or a NaN, neither of which JSON can express.
*/
function canonicalKey(value, seen) {
if (value === null)
return "z";
const type = typeof value;
if (type !== "object") {
if (type === "number" && Number.isNaN(value))
return null;
const raw = String(value);
return `${type[0]}${raw.length}:${raw}`;
}
if (seen.has(value))
return null;
seen.add(value);
try {
if (Array.isArray(value)) {
const parts = [];
for (const item of value) {
const key = canonicalKey(item, seen);
if (key === null)
return null;
parts.push(key);
}
return `a${parts.length}:[${parts.join(",")}]`;
}
const keys = Object.keys(value).sort();
const parts = [];
for (const k of keys) {
const key = canonicalKey(value[k], seen);
if (key === null)
return null;
parts.push(`${k.length}:${k}=${key}`);
}
return `o${parts.length}:{${parts.join(",")}}`;
}
finally {
seen.delete(value);
}
}
// keywords whose value is a schema or an array of them
const SCHEMA_KEYWORDS = /*@__PURE__*/ new Set([
"items",
"prefixItems",
"additionalItems",
"additionalProperties",
"contains",
"propertyNames",
"not",
"if",
"then",
"else",
"allOf",
"anyOf",
"oneOf",
"unevaluatedItems",
"unevaluatedProperties",
"contentSchema",
]);
// keywords whose value maps names to schemas. draft-7 `dependencies` also allows an array of property names, which holds no schema to walk
const SCHEMA_MAP_KEYWORDS = /*@__PURE__*/ new Set([
"properties",
"patternProperties",
"dependentSchemas",
"dependencies",
"$defs",
"definitions",
]);
/**
* True when a subschema holds a `$ref` anywhere a schema can appear. Only those positions are
* walked: `$ref` under `default` or an `x-` annotation is instance data with an ordinary key, and
* reading it as a reference would drop a constraint that resolves perfectly well.
*/
function containsRef(value) {
if (typeof value !== "object" || value === null)
return false;
if (Array.isArray(value))
return value.some(containsRef);
if (typeof value.$ref === "string")
return true;
return Object.entries(value).some(([key, sub]) => {
if (SCHEMA_KEYWORDS.has(key))
return containsRef(sub);
if (!SCHEMA_MAP_KEYWORDS.has(key) || typeof sub !== "object" || sub === null)
return false;
return Object.values(sub).some(containsRef);
});
}
function plural(n) {
return n === 1 ? "element" : "elements";
}
/**
* Enforces `uniqueItems` and the `contains` family before `arraySchema` runs, for the same reason
* `checkObjectGuards` runs pre-pipe: an item parse can apply a nested `default`, so the parsed
* array is not the instance the keywords are defined over. A guard issue aborts the pipe, so
* `minItems`/`maxItems` are not also reported on the same parse — instance correctness is worth
* more than co-reporting two issues.
*/
function checkArrayGuards(arraySchema, guards) {
// An identity transform, not z.any(), so `toJSONSchema` reports the array on both the input and the output side of the pipe.
const guard = z
.transform((value) => value)
.check((payload) => {
const items = payload.value;
if (!Array.isArray(items))
return;
if (guards.uniqueItems === true) {
const firstSeen = new Map();
for (let i = 0; i < items.length; i++) {
const key = canonicalKey(items[i], new Set());
if (key === null)
continue;
const first = firstSeen.get(key);
if (first === undefined) {
firstSeen.set(key, i);
continue;
}
payload.issues.push({
code: "custom",
message: `Array items must be unique: element at index ${i} duplicates the one at index ${first}`,
input: items,
path: [i],
continue: true,
});
}
}
if (guards.containsSchema) {
const minContains = guards.minContains ?? 1;
// one past the ceiling already proves the failure, and nothing above it changes the verdict
const ceiling = guards.maxContains !== undefined ? guards.maxContains + 1 : Number.POSITIVE_INFINITY;
let matches = 0;
for (const item of items) {
if (guards.containsSchema.safeParse(item).success && ++matches >= ceiling)
break;
}
if (matches < minContains) {
// the scan ran to the end, so this count is exact
payload.issues.push({
code: "custom",
message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,
input: items,
continue: true,
});
}
if (guards.maxContains !== undefined && matches > guards.maxContains) {
payload.issues.push({
code: "custom",
message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,
input: items,
continue: true,
});
}
}
});
return guard.pipe(arraySchema);
}
function getTupleRest(restSchema, ctx) {
if (restSchema === false) {
return undefined;
}
if (restSchema === undefined || restSchema === true) {
return z.any();
}
return convertSchema(restSchema, ctx);
}
// the RFC 3339 full-time keyword, narrower than `z.iso.time()`; local because sharing it via `timeSource` pins that builder into every bundle (+139 B gzipped on a mini `z.boolean()`)
const fullTime = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;
function convertBaseSchema(schema, ctx) {
// Handle unsupported features
if (schema.not !== undefined) {
// Special case: { not: {} } represents never
if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) {
return z.never();
}
throw new Error("not is not supported in Zod (except { not: {} } for never)");
}
if (schema.unevaluatedItems !== undefined) {
throw new Error("unevaluatedItems is not supported");
}
if (schema.unevaluatedProperties !== undefined) {
throw new Error("unevaluatedProperties is not supported");
}
if (schema.if !== undefined || schema.then !== undefined || schema.else !== undefined) {
throw new Error("Conditional schemas (if/then/else) are not supported");
}
if (schema.dependentSchemas !== undefined || schema.dependentRequired !== undefined) {
throw new Error("dependentSchemas and dependentRequired are not supported");
}
// Handle $ref
if (schema.$ref) {
const refPath = schema.$ref;
if (ctx.refs.has(refPath)) {
return ctx.refs.get(refPath);
}
if (ctx.processing.has(refPath)) {
// Circular reference - use lazy
return z.lazy(() => {
if (!ctx.refs.has(refPath)) {
throw new Error(`Circular reference not resolved: ${refPath}`);
}
return ctx.refs.get(refPath);
});
}
ctx.processing.add(refPath);
const resolved = resolveRef(refPath, ctx);
const zodSchema = convertSchema(resolved, ctx);
ctx.refs.set(refPath, zodSchema);
ctx.processing.delete(refPath);
return zodSchema;
}
// Handle enum
if (schema.enum !== undefined) {
const enumValues = schema.enum;
// Special case: OpenAPI 3.0 null representation { type: "string", nullable: true, enum: [null] }
if (ctx.version === "openapi-3.0" &&
schema.nullable === true &&
enumValues.length === 1 &&
enumValues[0] === null) {
return z.null();
}
if (enumValues.length === 0) {
return z.never();
}
if (enumValues.length === 1) {
return z.literal(enumValues[0]);
}
// Check if all values are strings
if (enumValues.every((v) => typeof v === "string")) {
return z.enum(enumValues);
}
// Mixed types - use union of literals
const literalSchemas = enumValues.map((v) => z.literal(v));
if (literalSchemas.length < 2) {
return literalSchemas[0];
}
return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]);
}
// Handle const
if (schema.const !== undefined) {
return z.literal(schema.const);
}
// Handle type
const type = schema.type;
if (Array.isArray(type)) {
// Expand type array into anyOf union
const typeSchemas = type.map((t) => {
const typeSchema = { ...schema, type: t };
return convertBaseSchema(typeSchema, ctx);
});
if (typeSchemas.length === 0) {
return z.never();
}
if (typeSchemas.length === 1) {
return typeSchemas[0];
}
return z.union(typeSchemas);
}
if (!type) {
// No type specified - empty schema (any)
return z.any();
}
let zodSchema;
switch (type) {
case "string": {
let stringSchema = z.string();
// Apply format using .check() with Zod format functions
if (schema.format) {
const format = schema.format;
// Map common formats to Zod check functions
if (format === "email") {
stringSchema = stringSchema.check(z.email());
}
else if (format === "uri" || format === "uri-reference") {
stringSchema = stringSchema.check(z.url());
}
else if (format === "uuid" || format === "guid") {
stringSchema = stringSchema.check(z.uuid());
}
else if (format === "date-time") {
stringSchema = stringSchema.check(z.iso.datetime({ offset: true }));
}
else if (format === "date") {
stringSchema = stringSchema.check(z.iso.date());
}
else if (format === "time") {
stringSchema = stringSchema.check(z.regex(fullTime));
}
else if (format === "duration") {
stringSchema = stringSchema.check(z.iso.duration());
}
else if (format === "hostname") {
stringSchema = stringSchema.check(z.hostname());
}
else if (format === "ipv4") {
stringSchema = stringSchema.check(z.ipv4());
}
else if (format === "ipv6") {
stringSchema = stringSchema.check(z.ipv6());
}
else if (format === "mac") {
stringSchema = stringSchema.check(z.mac());
}
else if (format === "cidr") {
stringSchema = stringSchema.check(z.cidrv4());
}
else if (format === "cidr-v6") {
stringSchema = stringSchema.check(z.cidrv6());
}
else if (format === "base64") {
stringSchema = stringSchema.check(z.base64());
}
else if (format === "base64url") {
stringSchema = stringSchema.check(z.base64url());
}
else if (format === "e164") {
stringSchema = stringSchema.check(z.e164());
}
else if (format === "credit_card") {
stringSchema = stringSchema.check(z.creditCard());
}
else if (format === "iban") {
stringSchema = stringSchema.check(z.iban());
}
else if (format === "jwt") {
stringSchema = stringSchema.check(z.jwt());
}
else if (format === "emoji") {
stringSchema = stringSchema.check(z.emoji());
}
else if (format === "nanoid") {
stringSchema = stringSchema.check(z.nanoid());
}
else if (format === "cuid") {
stringSchema = stringSchema.check(z.cuid());
}
else if (format === "cuid2") {
stringSchema = stringSchema.check(z.cuid2());
}
else if (format === "ulid") {
stringSchema = stringSchema.check(z.ulid());
}
else if (format === "xid") {
stringSchema = stringSchema.check(z.xid());
}
else if (format === "ksuid") {
stringSchema = stringSchema.check(z.ksuid());
}
// Note: json-string format is not currently supported by Zod
// Custom formats are ignored - keep as plain string
}
// Apply constraints
if (typeof schema.minLength === "number") {
stringSchema = stringSchema.min(schema.minLength);
}
if (typeof schema.maxLength === "number") {
stringSchema = stringSchema.max(schema.maxLength);
}
if (schema.pattern) {
// JSON Schema patterns are not implicitly anchored (match anywhere in string)
stringSchema = stringSchema.regex(new RegExp(schema.pattern));
}
zodSchema = stringSchema;
break;
}
case "number":
case "integer": {
let numberSchema = type === "integer" ? z.number().int() : z.number();
// Apply constraints
// In draft-04, `exclusiveMinimum: true` makes the sibling `minimum` exclusive rather than an independent bound, so the inclusive `.min()` is skipped; emitting it too would be dominated by the exclusive check and report a second, weaker issue.
if (typeof schema.minimum === "number" && schema.exclusiveMinimum !== true) {
numberSchema = numberSchema.min(schema.minimum);
}
if (typeof schema.maximum === "number" && schema.exclusiveMaximum !== true) {
numberSchema = numberSchema.max(schema.maximum);
}
if (typeof schema.exclusiveMinimum === "number") {
numberSchema = numberSchema.gt(schema.exclusiveMinimum);
}
else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") {
numberSchema = numberSchema.gt(schema.minimum);
}
if (typeof schema.exclusiveMaximum === "number") {
numberSchema = numberSchema.lt(schema.exclusiveMaximum);
}
else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") {
numberSchema = numberSchema.lt(schema.maximum);
}
if (typeof schema.multipleOf === "number") {
numberSchema = numberSchema.multipleOf(schema.multipleOf);
}
zodSchema = numberSchema;
break;
}
case "boolean": {
zodSchema = z.boolean();
break;
}
case "null": {
zodSchema = z.null();
break;
}
case "object": {
const shape = {};
const properties = schema.properties || {};
const requiredSet = new Set(schema.required || []);
const additionalSchema = typeof schema.additionalProperties === "object"
? convertSchema(schema.additionalProperties, ctx)
: undefined;
// Convert properties - mark optional ones
for (const [key, propSchema] of Object.entries(properties)) {
const propZodSchema = convertSchema(propSchema, ctx);
// If not in required array, make it optional. assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter
(0, util_js_1.assignProp)(shape, key, requiredSet.has(key) ? propZodSchema : propZodSchema.optional());
}
// Handle patternProperties
if (schema.patternProperties) {
// patternProperties: keys matching pattern must satisfy corresponding schema. Use loose records so non-matching keys pass through
const patternProps = schema.patternProperties;
const patternKeys = Object.keys(patternProps);
const looseRecords = [];
for (const pattern of patternKeys) {
const patternValue = convertSchema(patternProps[pattern], ctx);
const keySchema = z.string().regex(new RegExp(pattern));
looseRecords.push(z.looseRecord(keySchema, patternValue));
}
// Build intersection: object schema + all pattern property records
const schemasToIntersect = [];
if (Object.keys(shape).length > 0) {
// Use passthrough so patternProperties can validate additional keys
schemasToIntersect.push(z.object(shape).passthrough());
}
schemasToIntersect.push(...looseRecords);
if (schemasToIntersect.length === 0) {
zodSchema = z.object({}).passthrough();
}
else if (schemasToIntersect.length === 1) {
zodSchema = schemasToIntersect[0];
}
else {
// Chain intersections: (A & B) & C & D ...
let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]);
for (let i = 2; i < schemasToIntersect.length; i++) {
result = z.intersection(result, schemasToIntersect[i]);
}
zodSchema = result;
}
// When additionalProperties is false, reject keys that are neither defined in properties nor matched by any patternProperty.
if (schema.additionalProperties === false) {
const propertyKeys = Object.keys(shape);
const patterns = patternKeys.map((p) => new RegExp(p));
const basePatternSchema = zodSchema;
zodSchema = zodSchema.check((payload) => {
if (!(0, util_js_1.isPlainObject)(payload.value))
return;
const unrecognized = [];
for (const key of Object.keys(payload.value)) {
if (propertyKeys.includes(key))
continue;
if (patterns.some((regex) => regex.test(key)))
continue;
unrecognized.push(key);
}
if (unrecognized.length) {
payload.issues.push({
code: "unrecognized_keys",
keys: unrecognized,
input: payload.value,
inst: basePatternSchema,
});
}
});
}
}
else {
// Handle additionalProperties. In JSON Schema, additionalProperties defaults to true (allow any extra properties). In Zod, objects strip unknown keys by default, so we need to handle this explicitly
const objectSchema = z.object(shape);
if (schema.additionalProperties === false) {
// Strict mode - no extra properties allowed
zodSchema = objectSchema.strict();
}
else if (additionalSchema) {
// Extra properties must match the specified schema
zodSchema = objectSchema.catchall(additionalSchema);
}
else {
// additionalProperties is true or undefined - allow any extra properties (passthrough)
zodSchema = objectSchema.passthrough();
}
}
// propertyNames constrains key *names* only, and says nothing about which keys are required or how their values validate. Layering it on top of the result keeps properties/patternProperties/additionalProperties composing underneath. `true` allows every name, so it needs no guard.
const hasKeyGuard = schema.propertyNames !== undefined && schema.propertyNames !== true;
const minProperties = typeof schema.minProperties === "number" ? schema.minProperties : undefined;
const maxProperties = typeof schema.maxProperties === "number" ? schema.maxProperties : undefined;
if (hasKeyGuard || minProperties !== undefined || maxProperties !== undefined) {
let keySchema;
if (hasKeyGuard) {
// Keys are always strings, so a propertyNames subschema that omits `type` still constrains them — without this it would convert to z.any().
const keyJSONSchema = typeof schema.propertyNames === "object" && schema.propertyNames.type === undefined
? { type: "string", ...schema.propertyNames }
: schema.propertyNames;
keySchema = convertSchema(keyJSONSchema, ctx);
}
zodSchema = checkObjectGuards(zodSchema, { keySchema, minProperties, maxProperties });
}
break;
}
case "array": {
// Check if this is a tuple (prefixItems or items as array)
const prefixItems = schema.prefixItems;
const items = schema.items;
if (prefixItems && Array.isArray(prefixItems)) {
// Tuple with prefixItems (draft-2020-12)
const minItems = typeof schema.minItems === "number" ? schema.minItems : 0;
const tupleItems = prefixItems.map((item) => convertSchema(item, ctx));
const positionalItems = applyMinItems(tupleItems, minItems);
const rest = !Array.isArray(items) ? getTupleRest(items, ctx) : undefined;
const tupleSchema = z.tuple(positionalItems);
zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema;
// Apply minItems/maxItems constraints to tuples
if (typeof schema.minItems === "number") {
zodSchema = zodSchema.check(z.minLength(schema.minItems));
}
if (typeof schema.maxItems === "number") {
zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
}
}
else if (Array.isArray(items)) {
// Tuple with items array (draft-7)
const minItems = typeof schema.minItems === "number" ? schema.minItems : 0;
const tupleItems = items.map((item) => convertSchema(item, ctx));
const positionalItems = applyMinItems(tupleItems, minItems);
const rest = getTupleRest(schema.additionalItems, ctx);
const tupleSchema = z.tuple(positionalItems);
zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema;
// Apply minItems/maxItems constraints to tuples
if (typeof schema.minItems === "number") {
zodSchema = zodSchema.check(z.minLength(schema.minItems));
}
if (typeof schema.maxItems === "number") {
zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
}
}
else if (items !== undefined) {
// Regular array
const element = convertSchema(items, ctx);
let arraySchema = z.array(element);
// Apply constraints
if (typeof schema.minItems === "number") {
arraySchema = arraySchema.min(schema.minItems);
}
if (typeof schema.maxItems === "number") {
arraySchema = arraySchema.max(schema.maxItems);
}
zodSchema = arraySchema;
}
else {
// No items specified - array of any
zodSchema = z.array(z.any());
}
// minContains/maxContains only constrain anything when `contains` itself is present
if (schema.uniqueItems === true || schema.contains !== undefined) {
zodSchema = checkArrayGuards(zodSchema, {
uniqueItems: schema.uniqueItems === true,
containsSchema: schema.contains !== undefined ? convertSchema(schema.contains, ctx) : undefined,
minContains: typeof schema.minContains === "number" ? schema.minContains : undefined,
maxContains: typeof schema.maxContains === "number" ? schema.maxContains : undefined,
});
}
break;
}
default:
throw new Error(`Unsupported type: ${type}`);
}
return zodSchema;
}
function convertSchema(schema, ctx) {
if (typeof schema === "boolean") {
return schema ? z.any() : z.never();
}
// Convert base schema first (ignoring composition keywords)
let baseSchema = convertBaseSchema(schema, ctx);
const hasExplicitType = schema.type || schema.enum !== undefined || schema.const !== undefined;
// Process composition keywords LAST (they can appear together)
// Handle anyOf - wrap base schema with union
if (schema.anyOf && Array.isArray(schema.anyOf)) {
const options = schema.anyOf.map((s) => convertSchema(s, ctx));
const anyOfUnion = z.union(options);
baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion;
}
// Handle oneOf - exclusive union (exactly one must match)
if (schema.oneOf && Array.isArray(schema.oneOf)) {
const options = schema.oneOf.map((s) => convertSchema(s, ctx));
const oneOfUnion = z.xor(options);
baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion;
}
// Handle allOf - wrap base schema with intersection
if (schema.allOf && Array.isArray(schema.allOf)) {
if (schema.allOf.length === 0) {
baseSchema = hasExplicitType ? baseSchema : z.any();
}
else {
let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx);
const startIdx = hasExplicitType ? 0 : 1;
for (let i = startIdx; i < schema.allOf.length; i++) {
result = z.intersection(result, convertSchema(schema.allOf[i], ctx));
}
baseSchema = result;
}
}
// Handle nullable (OpenAPI 3.0)
if (schema.nullable === true && ctx.version === "openapi-3.0") {
baseSchema = z.nullable(baseSchema);
}
// Handle readOnly
if (schema.readOnly === true) {
baseSchema = z.readonly(baseSchema);
}
// Apply `default` so it wraps the fully-composed schema. This ensures `parse(undefined) -> default` works regardless of which branch of `convertBaseSchema` produced the inner schema (enum/const/not/typed/etc.).
if (schema.default !== undefined) {
baseSchema = baseSchema.default(schema.default);
}
// Collect non-description annotation metadata into the user-supplied registry. Description is handled separately below via `.describe()` to preserve the contract that `schema.description` reads from globalRegistry.
const extraMeta = {};
const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"];
for (const key of coreMetadataKeys) {
if (key in schema) {
extraMeta[key] = schema[key];
}
}
const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"];
for (const key of contentMetadataKeys) {
if (key in schema) {
extraMeta[key] = schema[key];
}
}
// `propertyNames` and `contains` are enforced by a guard, which `toJSONSchema` cannot infer, so the original keyword is carried as metadata to keep the round-trip lossless. Only where it was actually applied: on any other type it is inert, and on a `$ref` the metadata would land on the target every reference shares. A carried subschema is copied verbatim while the root `$defs` stay behind, so one holding a `$ref` is dropped rather than emitted as a dangling reference.
if (schema.type === "object" && schema.$ref === undefined) {
if (schema.propertyNames !== undefined && !containsRef(schema.propertyNames)) {
extraMeta.propertyNames = schema.propertyNames;
}
for (const key of ["minProperties", "maxProperties"]) {
if (schema[key] !== undefined)
extraMeta[key] = schema[key];
}
}
if (schema.type === "array" && schema.$ref === undefined) {
if (schema.contains !== undefined && !containsRef(schema.contains)) {
extraMeta.contains = schema.contains;
}
for (const key of ["uniqueItems", "minContains", "maxContains"]) {
if (schema[key] !== undefined)
extraMeta[key] = schema[key];
}
}
for (const key of Object.keys(schema)) {
if (!RECOGNIZED_KEYS.has(key)) {
(0, util_js_1.assignProp)(extraMeta, key, schema[key]);
}
}
if (Object.keys(extraMeta).length > 0) {
ctx.registry.add(baseSchema, extraMeta);
}
// Apply description last. `.describe()` clones the schema and sets `_zod.parent` on the clone, so registry lookups on the returned reference still resolve `extraMeta` via parent inheritance.
if (schema.description) {
baseSchema = baseSchema.describe(schema.description);
}
return baseSchema;
}
/**
* Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change. */
function fromJSONSchema(schema, params) {
// Handle boolean schemas
if (typeof schema === "boolean") {
return schema ? z.any() : z.never();
}
// Normalize input via a JSON round-trip. This guarantees the converter walks a plain, finite, JSON-valid object graph: cyclic inputs fail here, getter/Proxy-based properties are materialized into static values, and class instances collapse to plain objects.
let normalized;
try {
normalized = JSON.parse(JSON.stringify(schema));
}
catch {
throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
}
const version = detectVersion(normalized, params?.defaultTarget);
const defs = (normalized.$defs || normalized.definitions || {});
const ctx = {
version,
defs,
refs: new Map(),
processing: new Set(),
rootSchema: normalized,
registry: params?.registry ?? registries_js_1.globalRegistry,
};
return convertSchema(normalized, ctx);
}
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+12
View File
@@ -0,0 +1,12 @@
import type * as JSONSchema from "../core/json-schema.cjs";
import { type $ZodRegistry } from "../core/registries.cjs";
import type { ZodType } from "./schemas.cjs";
type JSONSchemaVersion = "draft-2020-12" | "draft-7" | "draft-4" | "openapi-3.0";
interface FromJSONSchemaParams {
defaultTarget?: JSONSchemaVersion;
registry?: $ZodRegistry<any>;
}
/**
* Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change. */
export declare function fromJSONSchema(schema: JSONSchema.JSONSchema | boolean, params?: FromJSONSchemaParams): ZodType;
export {};
+12
View File
@@ -0,0 +1,12 @@
import type * as JSONSchema from "../core/json-schema.js";
import { type $ZodRegistry } from "../core/registries.js";
import type { ZodType } from "./schemas.js";
type JSONSchemaVersion = "draft-2020-12" | "draft-7" | "draft-4" | "openapi-3.0";
interface FromJSONSchemaParams {
defaultTarget?: JSONSchemaVersion;
registry?: $ZodRegistry<any>;
}
/**
* Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change. */
export declare function fromJSONSchema(schema: JSONSchema.JSONSchema | boolean, params?: FromJSONSchemaParams): ZodType;
export {};
+881
View File
@@ -0,0 +1,881 @@
import { globalRegistry } from "../core/registries.js";
import { assignProp, isPlainObject } from "../core/util.js";
import * as _checks from "./checks.js";
import * as _iso from "./iso.js";
import * as _schemas from "./schemas.js";
// Local z object to avoid circular dependency with ../index.js
const z = {
..._schemas,
..._checks,
iso: _iso,
};
// Keys that are recognized and handled by the conversion logic
const RECOGNIZED_KEYS = /*@__PURE__*/ new Set([
// Schema identification
"$schema",
"$ref",
"$defs",
"definitions",
// Core schema keywords
"$id",
"id",
"$comment",
"$anchor",
"$vocabulary",
"$dynamicRef",
"$dynamicAnchor",
// Type
"type",
"enum",
"const",
// Composition
"anyOf",
"oneOf",
"allOf",
"not",
// Object
"properties",
"required",
"additionalProperties",
"patternProperties",
"propertyNames",
"minProperties",
"maxProperties",
// Array
"items",
"prefixItems",
"additionalItems",
"minItems",
"maxItems",
"uniqueItems",
"contains",
"minContains",
"maxContains",
// String
"minLength",
"maxLength",
"pattern",
"format",
// Number
"minimum",
"maximum",
"exclusiveMinimum",
"exclusiveMaximum",
"multipleOf",
// Already handled metadata
"description",
"default",
// Content
"contentEncoding",
"contentMediaType",
"contentSchema",
// Unsupported (error-throwing)
"unevaluatedItems",
"unevaluatedProperties",
"if",
"then",
"else",
"dependentSchemas",
"dependentRequired",
// OpenAPI
"nullable",
"readOnly",
]);
function detectVersion(schema, defaultTarget) {
const $schema = schema.$schema;
if ($schema === "https://json-schema.org/draft/2020-12/schema") {
return "draft-2020-12";
}
if ($schema === "http://json-schema.org/draft-07/schema#") {
return "draft-7";
}
if ($schema === "http://json-schema.org/draft-04/schema#") {
return "draft-4";
}
// Use defaultTarget if provided, otherwise default to draft-2020-12
return defaultTarget ?? "draft-2020-12";
}
// Positional schemas constrain the elements that are present; only minItems makes them required.
function applyMinItems(items, minItems) {
return items.map((item, index) => (index < minItems ? item : item.optional()));
}
// Inverse of the encoding applied to $ref pointer segments in to-json-schema.ts. Per RFC 6901 the `~1` replacement must run before `~0`.
function decodeJSONPointerSegment(segment) {
return segment.replace(/~1/g, "/").replace(/~0/g, "~");
}
function resolveRef(ref, ctx) {
if (!ref.startsWith("#")) {
throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
}
const path = ref.slice(1).split("/").filter(Boolean);
// Handle root reference "#"
if (path.length === 0) {
return ctx.rootSchema;
}
const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
if (path[0] === defsKey) {
const key = path[1] === undefined ? undefined : decodeJSONPointerSegment(path[1]);
if (!key || !ctx.defs[key]) {
throw new Error(`Reference not found: ${ref}`);
}
return ctx.defs[key];
}
throw new Error(`Reference not found: ${ref}`);
}
/**
* Enforces the keywords that constrain an object's own keys — `propertyNames`,
* `minProperties`, `maxProperties` — before `objectSchema` runs. The guard has
* to see the raw input: an object parse drops `__proto__` and can add keys from
* a property `default`, so its output is not the set of names the instance
* actually carried.
*/
function checkObjectGuards(objectSchema, guards) {
// An identity transform, not z.any(), so `toJSONSchema` reports the object on both the input and the output side of the pipe.
const guard = z
.transform((value) => value)
.check((payload) => {
const value = payload.value;
if (typeof value !== "object" || value === null || Array.isArray(value))
return;
const keys = Object.getOwnPropertyNames(value);
if (guards.minProperties !== undefined && keys.length < guards.minProperties) {
payload.issues.push({
origin: "object",
code: "too_small",
minimum: guards.minProperties,
inclusive: true,
message: `Too small: expected object to have >=${guards.minProperties} properties`,
input: value,
inst: objectSchema,
continue: true,
});
}
if (guards.maxProperties !== undefined && keys.length > guards.maxProperties) {
payload.issues.push({
origin: "object",
code: "too_big",
maximum: guards.maxProperties,
inclusive: true,
message: `Too big: expected object to have <=${guards.maxProperties} properties`,
input: value,
inst: objectSchema,
continue: true,
});
}
if (guards.keySchema) {
for (const key of keys) {
const result = guards.keySchema.safeParse(key);
if (result.success)
continue;
payload.issues.push({
code: "invalid_key",
origin: "record",
issues: result.error.issues,
input: key,
path: [key],
continue: true,
});
}
}
});
return guard.pipe(objectSchema);
}
/**
* An injective string for JSON data: two values share a key exactly when `uniqueItems` calls them
* equal, so duplicate detection is a Map lookup rather than a pairwise walk. Strings and keys are
* length-prefixed so no value can spell another one. `null` means "never equal to anything" — a
* cycle or a NaN, neither of which JSON can express.
*/
function canonicalKey(value, seen) {
if (value === null)
return "z";
const type = typeof value;
if (type !== "object") {
if (type === "number" && Number.isNaN(value))
return null;
const raw = String(value);
return `${type[0]}${raw.length}:${raw}`;
}
if (seen.has(value))
return null;
seen.add(value);
try {
if (Array.isArray(value)) {
const parts = [];
for (const item of value) {
const key = canonicalKey(item, seen);
if (key === null)
return null;
parts.push(key);
}
return `a${parts.length}:[${parts.join(",")}]`;
}
const keys = Object.keys(value).sort();
const parts = [];
for (const k of keys) {
const key = canonicalKey(value[k], seen);
if (key === null)
return null;
parts.push(`${k.length}:${k}=${key}`);
}
return `o${parts.length}:{${parts.join(",")}}`;
}
finally {
seen.delete(value);
}
}
// keywords whose value is a schema or an array of them
const SCHEMA_KEYWORDS = /*@__PURE__*/ new Set([
"items",
"prefixItems",
"additionalItems",
"additionalProperties",
"contains",
"propertyNames",
"not",
"if",
"then",
"else",
"allOf",
"anyOf",
"oneOf",
"unevaluatedItems",
"unevaluatedProperties",
"contentSchema",
]);
// keywords whose value maps names to schemas. draft-7 `dependencies` also allows an array of property names, which holds no schema to walk
const SCHEMA_MAP_KEYWORDS = /*@__PURE__*/ new Set([
"properties",
"patternProperties",
"dependentSchemas",
"dependencies",
"$defs",
"definitions",
]);
/**
* True when a subschema holds a `$ref` anywhere a schema can appear. Only those positions are
* walked: `$ref` under `default` or an `x-` annotation is instance data with an ordinary key, and
* reading it as a reference would drop a constraint that resolves perfectly well.
*/
function containsRef(value) {
if (typeof value !== "object" || value === null)
return false;
if (Array.isArray(value))
return value.some(containsRef);
if (typeof value.$ref === "string")
return true;
return Object.entries(value).some(([key, sub]) => {
if (SCHEMA_KEYWORDS.has(key))
return containsRef(sub);
if (!SCHEMA_MAP_KEYWORDS.has(key) || typeof sub !== "object" || sub === null)
return false;
return Object.values(sub).some(containsRef);
});
}
function plural(n) {
return n === 1 ? "element" : "elements";
}
/**
* Enforces `uniqueItems` and the `contains` family before `arraySchema` runs, for the same reason
* `checkObjectGuards` runs pre-pipe: an item parse can apply a nested `default`, so the parsed
* array is not the instance the keywords are defined over. A guard issue aborts the pipe, so
* `minItems`/`maxItems` are not also reported on the same parse — instance correctness is worth
* more than co-reporting two issues.
*/
function checkArrayGuards(arraySchema, guards) {
// An identity transform, not z.any(), so `toJSONSchema` reports the array on both the input and the output side of the pipe.
const guard = z
.transform((value) => value)
.check((payload) => {
const items = payload.value;
if (!Array.isArray(items))
return;
if (guards.uniqueItems === true) {
const firstSeen = new Map();
for (let i = 0; i < items.length; i++) {
const key = canonicalKey(items[i], new Set());
if (key === null)
continue;
const first = firstSeen.get(key);
if (first === undefined) {
firstSeen.set(key, i);
continue;
}
payload.issues.push({
code: "custom",
message: `Array items must be unique: element at index ${i} duplicates the one at index ${first}`,
input: items,
path: [i],
continue: true,
});
}
}
if (guards.containsSchema) {
const minContains = guards.minContains ?? 1;
// one past the ceiling already proves the failure, and nothing above it changes the verdict
const ceiling = guards.maxContains !== undefined ? guards.maxContains + 1 : Number.POSITIVE_INFINITY;
let matches = 0;
for (const item of items) {
if (guards.containsSchema.safeParse(item).success && ++matches >= ceiling)
break;
}
if (matches < minContains) {
// the scan ran to the end, so this count is exact
payload.issues.push({
code: "custom",
message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,
input: items,
continue: true,
});
}
if (guards.maxContains !== undefined && matches > guards.maxContains) {
payload.issues.push({
code: "custom",
message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,
input: items,
continue: true,
});
}
}
});
return guard.pipe(arraySchema);
}
function getTupleRest(restSchema, ctx) {
if (restSchema === false) {
return undefined;
}
if (restSchema === undefined || restSchema === true) {
return z.any();
}
return convertSchema(restSchema, ctx);
}
// the RFC 3339 full-time keyword, narrower than `z.iso.time()`; local because sharing it via `timeSource` pins that builder into every bundle (+139 B gzipped on a mini `z.boolean()`)
const fullTime = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;
function convertBaseSchema(schema, ctx) {
// Handle unsupported features
if (schema.not !== undefined) {
// Special case: { not: {} } represents never
if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) {
return z.never();
}
throw new Error("not is not supported in Zod (except { not: {} } for never)");
}
if (schema.unevaluatedItems !== undefined) {
throw new Error("unevaluatedItems is not supported");
}
if (schema.unevaluatedProperties !== undefined) {
throw new Error("unevaluatedProperties is not supported");
}
if (schema.if !== undefined || schema.then !== undefined || schema.else !== undefined) {
throw new Error("Conditional schemas (if/then/else) are not supported");
}
if (schema.dependentSchemas !== undefined || schema.dependentRequired !== undefined) {
throw new Error("dependentSchemas and dependentRequired are not supported");
}
// Handle $ref
if (schema.$ref) {
const refPath = schema.$ref;
if (ctx.refs.has(refPath)) {
return ctx.refs.get(refPath);
}
if (ctx.processing.has(refPath)) {
// Circular reference - use lazy
return z.lazy(() => {
if (!ctx.refs.has(refPath)) {
throw new Error(`Circular reference not resolved: ${refPath}`);
}
return ctx.refs.get(refPath);
});
}
ctx.processing.add(refPath);
const resolved = resolveRef(refPath, ctx);
const zodSchema = convertSchema(resolved, ctx);
ctx.refs.set(refPath, zodSchema);
ctx.processing.delete(refPath);
return zodSchema;
}
// Handle enum
if (schema.enum !== undefined) {
const enumValues = schema.enum;
// Special case: OpenAPI 3.0 null representation { type: "string", nullable: true, enum: [null] }
if (ctx.version === "openapi-3.0" &&
schema.nullable === true &&
enumValues.length === 1 &&
enumValues[0] === null) {
return z.null();
}
if (enumValues.length === 0) {
return z.never();
}
if (enumValues.length === 1) {
return z.literal(enumValues[0]);
}
// Check if all values are strings
if (enumValues.every((v) => typeof v === "string")) {
return z.enum(enumValues);
}
// Mixed types - use union of literals
const literalSchemas = enumValues.map((v) => z.literal(v));
if (literalSchemas.length < 2) {
return literalSchemas[0];
}
return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]);
}
// Handle const
if (schema.const !== undefined) {
return z.literal(schema.const);
}
// Handle type
const type = schema.type;
if (Array.isArray(type)) {
// Expand type array into anyOf union
const typeSchemas = type.map((t) => {
const typeSchema = { ...schema, type: t };
return convertBaseSchema(typeSchema, ctx);
});
if (typeSchemas.length === 0) {
return z.never();
}
if (typeSchemas.length === 1) {
return typeSchemas[0];
}
return z.union(typeSchemas);
}
if (!type) {
// No type specified - empty schema (any)
return z.any();
}
let zodSchema;
switch (type) {
case "string": {
let stringSchema = z.string();
// Apply format using .check() with Zod format functions
if (schema.format) {
const format = schema.format;
// Map common formats to Zod check functions
if (format === "email") {
stringSchema = stringSchema.check(z.email());
}
else if (format === "uri" || format === "uri-reference") {
stringSchema = stringSchema.check(z.url());
}
else if (format === "uuid" || format === "guid") {
stringSchema = stringSchema.check(z.uuid());
}
else if (format === "date-time") {
stringSchema = stringSchema.check(z.iso.datetime({ offset: true }));
}
else if (format === "date") {
stringSchema = stringSchema.check(z.iso.date());
}
else if (format === "time") {
stringSchema = stringSchema.check(z.regex(fullTime));
}
else if (format === "duration") {
stringSchema = stringSchema.check(z.iso.duration());
}
else if (format === "hostname") {
stringSchema = stringSchema.check(z.hostname());
}
else if (format === "ipv4") {
stringSchema = stringSchema.check(z.ipv4());
}
else if (format === "ipv6") {
stringSchema = stringSchema.check(z.ipv6());
}
else if (format === "mac") {
stringSchema = stringSchema.check(z.mac());
}
else if (format === "cidr") {
stringSchema = stringSchema.check(z.cidrv4());
}
else if (format === "cidr-v6") {
stringSchema = stringSchema.check(z.cidrv6());
}
else if (format === "base64") {
stringSchema = stringSchema.check(z.base64());
}
else if (format === "base64url") {
stringSchema = stringSchema.check(z.base64url());
}
else if (format === "e164") {
stringSchema = stringSchema.check(z.e164());
}
else if (format === "credit_card") {
stringSchema = stringSchema.check(z.creditCard());
}
else if (format === "iban") {
stringSchema = stringSchema.check(z.iban());
}
else if (format === "jwt") {
stringSchema = stringSchema.check(z.jwt());
}
else if (format === "emoji") {
stringSchema = stringSchema.check(z.emoji());
}
else if (format === "nanoid") {
stringSchema = stringSchema.check(z.nanoid());
}
else if (format === "cuid") {
stringSchema = stringSchema.check(z.cuid());
}
else if (format === "cuid2") {
stringSchema = stringSchema.check(z.cuid2());
}
else if (format === "ulid") {
stringSchema = stringSchema.check(z.ulid());
}
else if (format === "xid") {
stringSchema = stringSchema.check(z.xid());
}
else if (format === "ksuid") {
stringSchema = stringSchema.check(z.ksuid());
}
// Note: json-string format is not currently supported by Zod
// Custom formats are ignored - keep as plain string
}
// Apply constraints
if (typeof schema.minLength === "number") {
stringSchema = stringSchema.min(schema.minLength);
}
if (typeof schema.maxLength === "number") {
stringSchema = stringSchema.max(schema.maxLength);
}
if (schema.pattern) {
// JSON Schema patterns are not implicitly anchored (match anywhere in string)
stringSchema = stringSchema.regex(new RegExp(schema.pattern));
}
zodSchema = stringSchema;
break;
}
case "number":
case "integer": {
let numberSchema = type === "integer" ? z.number().int() : z.number();
// Apply constraints
// In draft-04, `exclusiveMinimum: true` makes the sibling `minimum` exclusive rather than an independent bound, so the inclusive `.min()` is skipped; emitting it too would be dominated by the exclusive check and report a second, weaker issue.
if (typeof schema.minimum === "number" && schema.exclusiveMinimum !== true) {
numberSchema = numberSchema.min(schema.minimum);
}
if (typeof schema.maximum === "number" && schema.exclusiveMaximum !== true) {
numberSchema = numberSchema.max(schema.maximum);
}
if (typeof schema.exclusiveMinimum === "number") {
numberSchema = numberSchema.gt(schema.exclusiveMinimum);
}
else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") {
numberSchema = numberSchema.gt(schema.minimum);
}
if (typeof schema.exclusiveMaximum === "number") {
numberSchema = numberSchema.lt(schema.exclusiveMaximum);
}
else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") {
numberSchema = numberSchema.lt(schema.maximum);
}
if (typeof schema.multipleOf === "number") {
numberSchema = numberSchema.multipleOf(schema.multipleOf);
}
zodSchema = numberSchema;
break;
}
case "boolean": {
zodSchema = z.boolean();
break;
}
case "null": {
zodSchema = z.null();
break;
}
case "object": {
const shape = {};
const properties = schema.properties || {};
const requiredSet = new Set(schema.required || []);
const additionalSchema = typeof schema.additionalProperties === "object"
? convertSchema(schema.additionalProperties, ctx)
: undefined;
// Convert properties - mark optional ones
for (const [key, propSchema] of Object.entries(properties)) {
const propZodSchema = convertSchema(propSchema, ctx);
// If not in required array, make it optional. assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter
assignProp(shape, key, requiredSet.has(key) ? propZodSchema : propZodSchema.optional());
}
// Handle patternProperties
if (schema.patternProperties) {
// patternProperties: keys matching pattern must satisfy corresponding schema. Use loose records so non-matching keys pass through
const patternProps = schema.patternProperties;
const patternKeys = Object.keys(patternProps);
const looseRecords = [];
for (const pattern of patternKeys) {
const patternValue = convertSchema(patternProps[pattern], ctx);
const keySchema = z.string().regex(new RegExp(pattern));
looseRecords.push(z.looseRecord(keySchema, patternValue));
}
// Build intersection: object schema + all pattern property records
const schemasToIntersect = [];
if (Object.keys(shape).length > 0) {
// Use passthrough so patternProperties can validate additional keys
schemasToIntersect.push(z.object(shape).passthrough());
}
schemasToIntersect.push(...looseRecords);
if (schemasToIntersect.length === 0) {
zodSchema = z.object({}).passthrough();
}
else if (schemasToIntersect.length === 1) {
zodSchema = schemasToIntersect[0];
}
else {
// Chain intersections: (A & B) & C & D ...
let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]);
for (let i = 2; i < schemasToIntersect.length; i++) {
result = z.intersection(result, schemasToIntersect[i]);
}
zodSchema = result;
}
// When additionalProperties is false, reject keys that are neither defined in properties nor matched by any patternProperty.
if (schema.additionalProperties === false) {
const propertyKeys = Object.keys(shape);
const patterns = patternKeys.map((p) => new RegExp(p));
const basePatternSchema = zodSchema;
zodSchema = zodSchema.check((payload) => {
if (!isPlainObject(payload.value))
return;
const unrecognized = [];
for (const key of Object.keys(payload.value)) {
if (propertyKeys.includes(key))
continue;
if (patterns.some((regex) => regex.test(key)))
continue;
unrecognized.push(key);
}
if (unrecognized.length) {
payload.issues.push({
code: "unrecognized_keys",
keys: unrecognized,
input: payload.value,
inst: basePatternSchema,
});
}
});
}
}
else {
// Handle additionalProperties. In JSON Schema, additionalProperties defaults to true (allow any extra properties). In Zod, objects strip unknown keys by default, so we need to handle this explicitly
const objectSchema = z.object(shape);
if (schema.additionalProperties === false) {
// Strict mode - no extra properties allowed
zodSchema = objectSchema.strict();
}
else if (additionalSchema) {
// Extra properties must match the specified schema
zodSchema = objectSchema.catchall(additionalSchema);
}
else {
// additionalProperties is true or undefined - allow any extra properties (passthrough)
zodSchema = objectSchema.passthrough();
}
}
// propertyNames constrains key *names* only, and says nothing about which keys are required or how their values validate. Layering it on top of the result keeps properties/patternProperties/additionalProperties composing underneath. `true` allows every name, so it needs no guard.
const hasKeyGuard = schema.propertyNames !== undefined && schema.propertyNames !== true;
const minProperties = typeof schema.minProperties === "number" ? schema.minProperties : undefined;
const maxProperties = typeof schema.maxProperties === "number" ? schema.maxProperties : undefined;
if (hasKeyGuard || minProperties !== undefined || maxProperties !== undefined) {
let keySchema;
if (hasKeyGuard) {
// Keys are always strings, so a propertyNames subschema that omits `type` still constrains them — without this it would convert to z.any().
const keyJSONSchema = typeof schema.propertyNames === "object" && schema.propertyNames.type === undefined
? { type: "string", ...schema.propertyNames }
: schema.propertyNames;
keySchema = convertSchema(keyJSONSchema, ctx);
}
zodSchema = checkObjectGuards(zodSchema, { keySchema, minProperties, maxProperties });
}
break;
}
case "array": {
// Check if this is a tuple (prefixItems or items as array)
const prefixItems = schema.prefixItems;
const items = schema.items;
if (prefixItems && Array.isArray(prefixItems)) {
// Tuple with prefixItems (draft-2020-12)
const minItems = typeof schema.minItems === "number" ? schema.minItems : 0;
const tupleItems = prefixItems.map((item) => convertSchema(item, ctx));
const positionalItems = applyMinItems(tupleItems, minItems);
const rest = !Array.isArray(items) ? getTupleRest(items, ctx) : undefined;
const tupleSchema = z.tuple(positionalItems);
zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema;
// Apply minItems/maxItems constraints to tuples
if (typeof schema.minItems === "number") {
zodSchema = zodSchema.check(z.minLength(schema.minItems));
}
if (typeof schema.maxItems === "number") {
zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
}
}
else if (Array.isArray(items)) {
// Tuple with items array (draft-7)
const minItems = typeof schema.minItems === "number" ? schema.minItems : 0;
const tupleItems = items.map((item) => convertSchema(item, ctx));
const positionalItems = applyMinItems(tupleItems, minItems);
const rest = getTupleRest(schema.additionalItems, ctx);
const tupleSchema = z.tuple(positionalItems);
zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema;
// Apply minItems/maxItems constraints to tuples
if (typeof schema.minItems === "number") {
zodSchema = zodSchema.check(z.minLength(schema.minItems));
}
if (typeof schema.maxItems === "number") {
zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
}
}
else if (items !== undefined) {
// Regular array
const element = convertSchema(items, ctx);
let arraySchema = z.array(element);
// Apply constraints
if (typeof schema.minItems === "number") {
arraySchema = arraySchema.min(schema.minItems);
}
if (typeof schema.maxItems === "number") {
arraySchema = arraySchema.max(schema.maxItems);
}
zodSchema = arraySchema;
}
else {
// No items specified - array of any
zodSchema = z.array(z.any());
}
// minContains/maxContains only constrain anything when `contains` itself is present
if (schema.uniqueItems === true || schema.contains !== undefined) {
zodSchema = checkArrayGuards(zodSchema, {
uniqueItems: schema.uniqueItems === true,
containsSchema: schema.contains !== undefined ? convertSchema(schema.contains, ctx) : undefined,
minContains: typeof schema.minContains === "number" ? schema.minContains : undefined,
maxContains: typeof schema.maxContains === "number" ? schema.maxContains : undefined,
});
}
break;
}
default:
throw new Error(`Unsupported type: ${type}`);
}
return zodSchema;
}
function convertSchema(schema, ctx) {
if (typeof schema === "boolean") {
return schema ? z.any() : z.never();
}
// Convert base schema first (ignoring composition keywords)
let baseSchema = convertBaseSchema(schema, ctx);
const hasExplicitType = schema.type || schema.enum !== undefined || schema.const !== undefined;
// Process composition keywords LAST (they can appear together)
// Handle anyOf - wrap base schema with union
if (schema.anyOf && Array.isArray(schema.anyOf)) {
const options = schema.anyOf.map((s) => convertSchema(s, ctx));
const anyOfUnion = z.union(options);
baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion;
}
// Handle oneOf - exclusive union (exactly one must match)
if (schema.oneOf && Array.isArray(schema.oneOf)) {
const options = schema.oneOf.map((s) => convertSchema(s, ctx));
const oneOfUnion = z.xor(options);
baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion;
}
// Handle allOf - wrap base schema with intersection
if (schema.allOf && Array.isArray(schema.allOf)) {
if (schema.allOf.length === 0) {
baseSchema = hasExplicitType ? baseSchema : z.any();
}
else {
let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx);
const startIdx = hasExplicitType ? 0 : 1;
for (let i = startIdx; i < schema.allOf.length; i++) {
result = z.intersection(result, convertSchema(schema.allOf[i], ctx));
}
baseSchema = result;
}
}
// Handle nullable (OpenAPI 3.0)
if (schema.nullable === true && ctx.version === "openapi-3.0") {
baseSchema = z.nullable(baseSchema);
}
// Handle readOnly
if (schema.readOnly === true) {
baseSchema = z.readonly(baseSchema);
}
// Apply `default` so it wraps the fully-composed schema. This ensures `parse(undefined) -> default` works regardless of which branch of `convertBaseSchema` produced the inner schema (enum/const/not/typed/etc.).
if (schema.default !== undefined) {
baseSchema = baseSchema.default(schema.default);
}
// Collect non-description annotation metadata into the user-supplied registry. Description is handled separately below via `.describe()` to preserve the contract that `schema.description` reads from globalRegistry.
const extraMeta = {};
const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"];
for (const key of coreMetadataKeys) {
if (key in schema) {
extraMeta[key] = schema[key];
}
}
const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"];
for (const key of contentMetadataKeys) {
if (key in schema) {
extraMeta[key] = schema[key];
}
}
// `propertyNames` and `contains` are enforced by a guard, which `toJSONSchema` cannot infer, so the original keyword is carried as metadata to keep the round-trip lossless. Only where it was actually applied: on any other type it is inert, and on a `$ref` the metadata would land on the target every reference shares. A carried subschema is copied verbatim while the root `$defs` stay behind, so one holding a `$ref` is dropped rather than emitted as a dangling reference.
if (schema.type === "object" && schema.$ref === undefined) {
if (schema.propertyNames !== undefined && !containsRef(schema.propertyNames)) {
extraMeta.propertyNames = schema.propertyNames;
}
for (const key of ["minProperties", "maxProperties"]) {
if (schema[key] !== undefined)
extraMeta[key] = schema[key];
}
}
if (schema.type === "array" && schema.$ref === undefined) {
if (schema.contains !== undefined && !containsRef(schema.contains)) {
extraMeta.contains = schema.contains;
}
for (const key of ["uniqueItems", "minContains", "maxContains"]) {
if (schema[key] !== undefined)
extraMeta[key] = schema[key];
}
}
for (const key of Object.keys(schema)) {
if (!RECOGNIZED_KEYS.has(key)) {
assignProp(extraMeta, key, schema[key]);
}
}
if (Object.keys(extraMeta).length > 0) {
ctx.registry.add(baseSchema, extraMeta);
}
// Apply description last. `.describe()` clones the schema and sets `_zod.parent` on the clone, so registry lookups on the returned reference still resolve `extraMeta` via parent inheritance.
if (schema.description) {
baseSchema = baseSchema.describe(schema.description);
}
return baseSchema;
}
/**
* Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change. */
export function fromJSONSchema(schema, params) {
// Handle boolean schemas
if (typeof schema === "boolean") {
return schema ? z.any() : z.never();
}
// Normalize input via a JSON round-trip. This guarantees the converter walks a plain, finite, JSON-valid object graph: cyclic inputs fail here, getter/Proxy-based properties are materialized into static values, and class instances collapse to plain objects.
let normalized;
try {
normalized = JSON.parse(JSON.stringify(schema));
}
catch {
throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
}
const version = detectVersion(normalized, params?.defaultTarget);
const defs = (normalized.$defs || normalized.definitions || {});
const ctx = {
version,
defs,
refs: new Map(),
processing: new Set(),
rootSchema: normalized,
registry: params?.registry ?? globalRegistry,
};
return convertSchema(normalized, ctx);
}
+82
View File
@@ -0,0 +1,82 @@
"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.input = input;
exports.output = output;
const util_js_1 = require("../core/util.cjs");
const visit_js_1 = require("../core/visit.cjs");
const schemas = __importStar(require("./schemas.cjs"));
/** Appends a pipe's own checks to the side that replaces it, mirroring how `.check()` clones. */
function withChecks(side, checks) {
if (!checks?.length)
return side;
const def = side._zod.def;
return (0, util_js_1.clone)(side, (0, util_js_1.mergeDefs)(def, { checks: [...(def.checks ?? []), ...checks] }), { parent: true });
}
/** The out side, carrying the pipe's own checks: those run against the decoded value, which is what `out` produces. */
function outSide(def) {
return withChecks(def.out, def.checks);
}
/** The in side. `z.preprocess` pipes a transform into a schema, and a bare transform validates nothing, so the schema it feeds is the real input side — the resolution `toJSONSchema` already makes for this case. */
function inSide(def) {
return def.in._zod.traits.has("$ZodTransform") ? outSide(def) : def.in;
}
/** Returns a copy of the schema with every pipe replaced by its input side. A codec's checks are dropped: they constrain the decoded value the input side never produces. */
function input(schema) {
return (0, visit_js_1.visit)(schema, {
pipe: (s) => inSide(s._zod.def),
// A default value belongs to the output side, so a rewritten inner type leaves it stranded. `.default()` widens the declared input type with `undefined`, and `optional` is what carries that across.
default: (s, rewritten) => (rewritten ? schemas.optional(s._zod.def.innerType) : s),
// A catch value is output-side too, but `.catch()` leaves the declared input type alone, so the inner schema stands on its own.
catch: (s, rewritten) => (rewritten ? s._zod.def.innerType : s),
});
}
/** Returns a copy of the schema with every pipe replaced by its output side, carrying over the pipe's own checks. */
function output(schema) {
return (0, visit_js_1.visit)(schema, {
pipe: (s) => outSide(s._zod.def),
// A prefault value is fed through the schema, which makes it input-side, so a rewritten inner type leaves it stranded.
prefault: (s, rewritten) => (rewritten ? s._zod.def.innerType : s),
});
}
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+8
View File
@@ -0,0 +1,8 @@
import type * as core from "../core/index.cjs";
import * as schemas from "./schemas.cjs";
export type input<T> = core.input<T>;
export type output<T> = core.output<T>;
/** Returns a copy of the schema with every pipe replaced by its input side. A codec's checks are dropped: they constrain the decoded value the input side never produces. */
export declare function input<T extends core.$ZodType>(schema: T): schemas.ZodType<core.input<T>, core.input<T>>;
/** Returns a copy of the schema with every pipe replaced by its output side, carrying over the pipe's own checks. */
export declare function output<T extends core.$ZodType>(schema: T): schemas.ZodType<core.output<T>, core.output<T>>;
+8
View File
@@ -0,0 +1,8 @@
import type * as core from "../core/index.js";
import * as schemas from "./schemas.js";
export type input<T> = core.input<T>;
export type output<T> = core.output<T>;
/** Returns a copy of the schema with every pipe replaced by its input side. A codec's checks are dropped: they constrain the decoded value the input side never produces. */
export declare function input<T extends core.$ZodType>(schema: T): schemas.ZodType<core.input<T>, core.input<T>>;
/** Returns a copy of the schema with every pipe replaced by its output side, carrying over the pipe's own checks. */
export declare function output<T extends core.$ZodType>(schema: T): schemas.ZodType<core.output<T>, core.output<T>>;
+36
View File
@@ -0,0 +1,36 @@
import { clone, mergeDefs } from "../core/util.js";
import { visit } from "../core/visit.js";
import * as schemas from "./schemas.js";
/** Appends a pipe's own checks to the side that replaces it, mirroring how `.check()` clones. */
function withChecks(side, checks) {
if (!checks?.length)
return side;
const def = side._zod.def;
return clone(side, mergeDefs(def, { checks: [...(def.checks ?? []), ...checks] }), { parent: true });
}
/** The out side, carrying the pipe's own checks: those run against the decoded value, which is what `out` produces. */
function outSide(def) {
return withChecks(def.out, def.checks);
}
/** The in side. `z.preprocess` pipes a transform into a schema, and a bare transform validates nothing, so the schema it feeds is the real input side — the resolution `toJSONSchema` already makes for this case. */
function inSide(def) {
return def.in._zod.traits.has("$ZodTransform") ? outSide(def) : def.in;
}
/** Returns a copy of the schema with every pipe replaced by its input side. A codec's checks are dropped: they constrain the decoded value the input side never produces. */
export function input(schema) {
return visit(schema, {
pipe: (s) => inSide(s._zod.def),
// A default value belongs to the output side, so a rewritten inner type leaves it stranded. `.default()` widens the declared input type with `undefined`, and `optional` is what carries that across.
default: (s, rewritten) => (rewritten ? schemas.optional(s._zod.def.innerType) : s),
// A catch value is output-side too, but `.catch()` leaves the declared input type alone, so the inner schema stands on its own.
catch: (s, rewritten) => (rewritten ? s._zod.def.innerType : s),
});
}
/** Returns a copy of the schema with every pipe replaced by its output side, carrying over the pipe's own checks. */
export function output(schema) {
return visit(schema, {
pipe: (s) => outSide(s._zod.def),
// A prefault value is fed through the schema, which makes it input-side, so a rewritten inner type leaves it stranded.
prefault: (s, rewritten) => (rewritten ? s._zod.def.innerType : s),
});
}
+52
View File
@@ -0,0 +1,52 @@
"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.default = exports.z = void 0;
const z = __importStar(require("./external.cjs"));
exports.z = z;
exports.default = z;
__exportStar(require("./external.cjs"), exports);
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+3
View File
@@ -0,0 +1,3 @@
import * as z from "./external.cjs";
export * from "./external.cjs";
export { z, z as default };
+3
View File
@@ -0,0 +1,3 @@
import * as z from "./external.js";
export * from "./external.js";
export { z, z as default };
+4
View File
@@ -0,0 +1,4 @@
import * as z from "./external.js";
export * from "./external.js";
// See the note in `src/index.ts` — aliasing keeps the default export shakable.
export { z, z as default };
+68
View File
@@ -0,0 +1,68 @@
"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodISOTime = exports.ZodISODuration = exports.ZodISODateTime = exports.ZodISODate = void 0;
exports.datetime = datetime;
exports.date = date;
exports.time = time;
exports.duration = duration;
const core = __importStar(require("../core/index.cjs"));
const schemas_js_1 = require("./schemas.cjs");
var schemas_js_2 = require("./schemas.cjs");
Object.defineProperty(exports, "ZodISODate", { enumerable: true, get: function () { return schemas_js_2.ZodISODate; } });
Object.defineProperty(exports, "ZodISODateTime", { enumerable: true, get: function () { return schemas_js_2.ZodISODateTime; } });
Object.defineProperty(exports, "ZodISODuration", { enumerable: true, get: function () { return schemas_js_2.ZodISODuration; } });
Object.defineProperty(exports, "ZodISOTime", { enumerable: true, get: function () { return schemas_js_2.ZodISOTime; } });
function datetime(params) {
return core._isoDateTime(schemas_js_1.ZodISODateTime, params);
}
function date(params) {
return core._isoDate(schemas_js_1.ZodISODate, params);
}
function time(params) {
return core._isoTime(schemas_js_1.ZodISOTime, params);
}
function duration(params) {
return core._isoDuration(schemas_js_1.ZodISODuration, params);
}
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+7
View File
@@ -0,0 +1,7 @@
import * as core from "../core/index.cjs";
import { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from "./schemas.cjs";
export { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from "./schemas.cjs";
export declare function datetime(params?: string | core.$ZodISODateTimeParams): ZodISODateTime;
export declare function date(params?: string | core.$ZodISODateParams): ZodISODate;
export declare function time(params?: string | core.$ZodISOTimeParams): ZodISOTime;
export declare function duration(params?: string | core.$ZodISODurationParams): ZodISODuration;
+7
View File
@@ -0,0 +1,7 @@
import * as core from "../core/index.js";
import { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from "./schemas.js";
export { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from "./schemas.js";
export declare function datetime(params?: string | core.$ZodISODateTimeParams): ZodISODateTime;
export declare function date(params?: string | core.$ZodISODateParams): ZodISODate;
export declare function time(params?: string | core.$ZodISOTimeParams): ZodISOTime;
export declare function duration(params?: string | core.$ZodISODurationParams): ZodISODuration;
+15
View File
@@ -0,0 +1,15 @@
import * as core from "../core/index.js";
import { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from "./schemas.js";
export { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from "./schemas.js";
export function datetime(params) {
return core._isoDateTime(ZodISODateTime, params);
}
export function date(params) {
return core._isoDate(ZodISODate, params);
}
export function time(params) {
return core._isoTime(ZodISOTime, params);
}
export function duration(params) {
return core._isoDuration(ZodISODuration, params);
}
+7
View File
@@ -0,0 +1,7 @@
{
"type": "module",
"main": "./index.cjs",
"module": "./index.js",
"types": "./index.d.cts",
"sideEffects": false
}
+63
View File
@@ -0,0 +1,63 @@
"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.safeDecodeAsync = exports.safeEncodeAsync = exports.safeDecode = exports.safeEncode = exports.decodeAsync = exports.encodeAsync = exports.decode = exports.encode = exports.validateAsync = exports.validate = exports.safeParseAsync = exports.safeParse = exports.parseAsync = exports.parse = void 0;
const core = __importStar(require("../core/index.cjs"));
const errors_js_1 = require("./errors.cjs");
exports.parse = core._parse(errors_js_1.ZodRealError);
exports.parseAsync = core._parseAsync(errors_js_1.ZodRealError);
exports.safeParse = core._safeParse(errors_js_1.ZodRealError);
exports.safeParseAsync = core._safeParseAsync(errors_js_1.ZodRealError);
var index_js_1 = require("../core/index.cjs");
Object.defineProperty(exports, "validate", { enumerable: true, get: function () { return index_js_1.validate; } });
Object.defineProperty(exports, "validateAsync", { enumerable: true, get: function () { return index_js_1.validateAsync; } });
// Codec functions
exports.encode = core._encode(errors_js_1.ZodRealError);
exports.decode = core._decode(errors_js_1.ZodRealError);
exports.encodeAsync = core._encodeAsync(errors_js_1.ZodRealError);
exports.decodeAsync = core._decodeAsync(errors_js_1.ZodRealError);
exports.safeEncode = core._safeEncode(errors_js_1.ZodRealError);
exports.safeDecode = core._safeDecode(errors_js_1.ZodRealError);
exports.safeEncodeAsync = core._safeEncodeAsync(errors_js_1.ZodRealError);
exports.safeDecodeAsync = core._safeDecodeAsync(errors_js_1.ZodRealError);
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+44
View File
@@ -0,0 +1,44 @@
import * as core from "../core/index.cjs";
import { type ZodError } from "./errors.cjs";
export type ZodSafeParseResult<T> = ZodSafeParseSuccess<T> | ZodSafeParseError<T>;
export type ZodSafeParseSuccess<T> = {
success: true;
data: T;
error?: never;
};
export type ZodSafeParseError<T> = {
success: false;
data?: never;
error: ZodError<T>;
};
export declare const parse: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => core.output<T>;
export declare const parseAsync: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => Promise<core.output<T>>;
export declare const safeParse: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>) => ZodSafeParseResult<core.output<T>>;
export declare const safeParseAsync: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>) => Promise<ZodSafeParseResult<core.output<T>>>;
export { validate, validateAsync } from "../core/index.cjs";
export declare const encode: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => core.input<T>;
export declare const decode: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => core.output<T>;
export declare const encodeAsync: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => Promise<core.input<T>>;
export declare const decodeAsync: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => Promise<core.output<T>>;
export declare const safeEncode: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => ZodSafeParseResult<core.input<T>>;
export declare const safeDecode: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => ZodSafeParseResult<core.output<T>>;
export declare const safeEncodeAsync: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => Promise<ZodSafeParseResult<core.input<T>>>;
export declare const safeDecodeAsync: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => Promise<ZodSafeParseResult<core.output<T>>>;
+44
View File
@@ -0,0 +1,44 @@
import * as core from "../core/index.js";
import { type ZodError } from "./errors.js";
export type ZodSafeParseResult<T> = ZodSafeParseSuccess<T> | ZodSafeParseError<T>;
export type ZodSafeParseSuccess<T> = {
success: true;
data: T;
error?: never;
};
export type ZodSafeParseError<T> = {
success: false;
data?: never;
error: ZodError<T>;
};
export declare const parse: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => core.output<T>;
export declare const parseAsync: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => Promise<core.output<T>>;
export declare const safeParse: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>) => ZodSafeParseResult<core.output<T>>;
export declare const safeParseAsync: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>) => Promise<ZodSafeParseResult<core.output<T>>>;
export { validate, validateAsync } from "../core/index.js";
export declare const encode: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => core.input<T>;
export declare const decode: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => core.output<T>;
export declare const encodeAsync: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => Promise<core.input<T>>;
export declare const decodeAsync: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => Promise<core.output<T>>;
export declare const safeEncode: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => ZodSafeParseResult<core.input<T>>;
export declare const safeDecode: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => ZodSafeParseResult<core.output<T>>;
export declare const safeEncodeAsync: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => Promise<ZodSafeParseResult<core.input<T>>>;
export declare const safeDecodeAsync: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => Promise<ZodSafeParseResult<core.output<T>>>;
+16
View File
@@ -0,0 +1,16 @@
import * as core from "../core/index.js";
import { ZodRealError } from "./errors.js";
export const parse = /* @__PURE__ */ core._parse(ZodRealError);
export const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);
export const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);
export const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);
export { validate, validateAsync } from "../core/index.js";
// Codec functions
export const encode = /* @__PURE__ */ core._encode(ZodRealError);
export const decode = /* @__PURE__ */ core._decode(ZodRealError);
export const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);
export const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);
export const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);
export const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);
export const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);
export const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);
+1676
View File
File diff suppressed because it is too large Load Diff
+816
View File
@@ -0,0 +1,816 @@
import type { $ZodBigIntFormats } from "../core/checks.cjs";
import * as core from "../core/index.cjs";
import { util, type $ZodNumberFormats } from "../core/index.cjs";
import type { StandardSchemaWithJSONProps } from "../core/standard-schema.cjs";
import * as parse from "./parse.cjs";
export type ZodStandardSchemaWithJSON<T> = StandardSchemaWithJSONProps<core.input<T>, core.output<T>>;
export interface ZodType<out Output = unknown, out Input = unknown, out Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> extends core.$ZodType<Output, Input, Internals> {
def: Internals["def"];
type: Internals["def"]["type"];
/** @deprecated Use `.def` instead. */
_def: Internals["def"];
/** @deprecated Use `z.output<typeof schema>` instead. */
_output: Internals["output"];
/** @deprecated Use `z.input<typeof schema>` instead. */
_input: Internals["input"];
"~standard": ZodStandardSchemaWithJSON<this>;
/** Converts this schema to a JSON Schema representation. */
toJSONSchema(params?: core.ToJSONSchemaParams): core.ZodStandardJSONSchemaPayload<this>;
check(...checks: (core.CheckFn<core.output<this>> | core.$ZodCheck<core.output<this>>)[]): this;
with(...checks: (core.CheckFn<core.output<this>> | core.$ZodCheck<core.output<this>>)[]): this;
clone(def?: Internals["def"], params?: {
parent: boolean;
}): this;
register<R extends core.$ZodRegistry>(registry: R, ...meta: this extends R["_schema"] ? undefined extends R["_meta"] ? [core.$replace<R["_meta"], this>?] : [core.$replace<R["_meta"], this>] : ["Incompatible schema"]): this;
brand<T extends PropertyKey = PropertyKey, Dir extends "in" | "out" | "inout" = "out">(value?: T): PropertyKey extends T ? this : core.$ZodBranded<this, T, Dir>;
parse(data: unknown, params?: core.ParseContext<core.$ZodIssue>): core.output<this>;
safeParse(data: unknown, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.output<this>>;
parseAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<core.output<this>>;
safeParseAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.output<this>>>;
spa: (data: unknown, params?: core.ParseContext<core.$ZodIssue>) => Promise<parse.ZodSafeParseResult<core.output<this>>>;
validate(data: unknown, params?: core.ParseContext<core.$ZodIssue>): data is core.input<this>;
validateAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<boolean>;
encode(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): core.input<this>;
decode(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): core.output<this>;
encodeAsync(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<core.input<this>>;
decodeAsync(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<core.output<this>>;
safeEncode(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.input<this>>;
safeDecode(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.output<this>>;
safeEncodeAsync(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.input<this>>>;
safeDecodeAsync(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.output<this>>>;
refine<Ch extends (arg: core.output<this>) => unknown | Promise<unknown>>(check: Ch, params?: string | core.$ZodCustomParams): Ch extends (arg: any) => arg is infer R ? this & ZodType<R, core.input<this>> : this;
superRefine(refinement: (arg: core.output<this>, ctx: core.$RefinementCtx<core.output<this>>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): this;
overwrite(fn: (x: core.output<this>) => core.output<this>): this;
optional(): ZodOptional<this>;
exactOptional(): ZodExactOptional<this>;
nonoptional(params?: string | core.$ZodNonOptionalParams): ZodNonOptional<this>;
nullable(): ZodNullable<this>;
nullish(): ZodOptional<ZodNullable<this>>;
default(def: util.NoUndefined<core.output<this>>): ZodDefault<this>;
default(def: () => util.NoUndefined<core.output<this>>): ZodDefault<this>;
prefault(def: () => core.input<this>): ZodPrefault<this>;
prefault(def: core.input<this>): ZodPrefault<this>;
array(): ZodArray<this>;
or<T extends core.SomeType>(option: T): ZodUnion<[this, T]>;
and<T extends core.SomeType>(incoming: T): ZodIntersection<this, T>;
transform<NewOut>(transform: (arg: core.output<this>, ctx: core.$RefinementCtx<core.output<this>>) => NewOut | Promise<NewOut>): ZodPipe<this, ZodTransform<Awaited<NewOut>, core.output<this>>>;
catch(def: core.output<this>): ZodCatch<this>;
catch(def: (ctx: core.$ZodCatchCtx) => core.output<this>): ZodCatch<this>;
pipe<T extends core.$ZodType<any, core.output<this>>>(target: T | core.$ZodType<any, core.output<this>>): ZodPipe<this, T>;
readonly(): ZodReadonly<this>;
/** Returns a new instance that has been registered in `z.globalRegistry` with the specified description */
describe(description: string): this;
description?: string;
/** Returns the metadata associated with this instance in `z.globalRegistry` */
meta(): core.$replace<core.GlobalMeta, this> | undefined;
/** Returns a new instance that has been registered in `z.globalRegistry` with the specified metadata */
meta(data: core.$replace<core.GlobalMeta, this>): this;
/** @deprecated Try safe-parsing `undefined` (this is what `isOptional` does internally):
*
* ```ts
* const schema = z.string().optional();
* const isOptional = schema.safeParse(undefined).success; // true
* ```
*/
isOptional(): boolean;
/**
* @deprecated Try safe-parsing `null` (this is what `isNullable` does internally):
*
* ```ts
* const schema = z.string().nullable();
* const isNullable = schema.safeParse(null).success; // true
* ```
*/
isNullable(): boolean;
apply<T, TArgs extends unknown[] = []>(fn: (schema: this, ...args: TArgs) => T, ...args: TArgs): T;
}
export interface _ZodType<out Internals extends core.$ZodTypeInternals = core.$ZodTypeInternals> extends ZodType<any, any, Internals> {
}
export declare const ZodType: core.$constructor<ZodType>;
export interface _ZodString<T extends core.$ZodStringInternals<unknown> = core.$ZodStringInternals<unknown>> extends _ZodType<T> {
format: string | null;
minLength: number | null;
maxLength: number | null;
regex(regex: RegExp, params?: string | core.$ZodCheckRegexParams): this;
includes(value: string, params?: string | core.$ZodCheckIncludesParams): this;
startsWith(value: string, params?: string | core.$ZodCheckStartsWithParams): this;
endsWith(value: string, params?: string | core.$ZodCheckEndsWithParams): this;
min(minLength: number, params?: string | core.$ZodCheckMinLengthParams): this;
max(maxLength: number, params?: string | core.$ZodCheckMaxLengthParams): this;
length(len: number, params?: string | core.$ZodCheckLengthEqualsParams): this;
nonempty(params?: string | core.$ZodCheckMinLengthParams): this;
lowercase(params?: string | core.$ZodCheckLowerCaseParams): this;
uppercase(params?: string | core.$ZodCheckUpperCaseParams): this;
trim(): this;
normalize(form?: "NFC" | "NFD" | "NFKC" | "NFKD" | (string & {})): this;
toLowerCase(): this;
toUpperCase(): this;
slugify(): this;
}
/** @internal */
export declare const _ZodString: core.$constructor<_ZodString>;
export interface ZodString extends _ZodString<core.$ZodStringInternals<string>> {
/** @deprecated Use `z.email()` instead. */
email(params?: string | core.$ZodCheckEmailParams): this;
/** @deprecated Use `z.url()` instead. */
url(params?: string | core.$ZodCheckURLParams): this;
/** @deprecated Use `z.jwt()` instead. */
jwt(params?: string | core.$ZodCheckJWTParams): this;
/** @deprecated Use `z.emoji()` instead. */
emoji(params?: string | core.$ZodCheckEmojiParams): this;
/** @deprecated Use `z.guid()` instead. */
guid(params?: string | core.$ZodCheckGUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuid(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuidv4(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuidv6(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuidv7(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.nanoid()` instead. */
nanoid(params?: string | core.$ZodCheckNanoIDParams): this;
/** @deprecated Use `z.guid()` instead. */
guid(params?: string | core.$ZodCheckGUIDParams): this;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use `z.cuid2()` instead.
* See https://github.com/paralleldrive/cuid.
*/
cuid(params?: string | core.$ZodCheckCUIDParams): this;
/** @deprecated Use `z.cuid2()` instead. */
cuid2(params?: string | core.$ZodCheckCUID2Params): this;
/** @deprecated Use `z.ulid()` instead. */
ulid(params?: string | core.$ZodCheckULIDParams): this;
/** @deprecated Use `z.base64()` instead. */
base64(params?: string | core.$ZodCheckBase64Params): this;
/** @deprecated Use `z.base64url()` instead. */
base64url(params?: string | core.$ZodCheckBase64URLParams): this;
/** @deprecated Use `z.xid()` instead. */
xid(params?: string | core.$ZodCheckXIDParams): this;
/** @deprecated Use `z.ksuid()` instead. */
ksuid(params?: string | core.$ZodCheckKSUIDParams): this;
/** @deprecated Use `z.ipv4()` instead. */
ipv4(params?: string | core.$ZodCheckIPv4Params): this;
/** @deprecated Use `z.ipv6()` instead. */
ipv6(params?: string | core.$ZodCheckIPv6Params): this;
/** @deprecated Use `z.cidrv4()` instead. */
cidrv4(params?: string | core.$ZodCheckCIDRv4Params): this;
/** @deprecated Use `z.cidrv6()` instead. */
cidrv6(params?: string | core.$ZodCheckCIDRv6Params): this;
/** @deprecated Use `z.e164()` instead. */
e164(params?: string | core.$ZodCheckE164Params): this;
/** @deprecated Use `z.iso.datetime()` instead. */
datetime(params?: string | core.$ZodCheckISODateTimeParams): this;
/** @deprecated Use `z.iso.date()` instead. */
date(params?: string | core.$ZodCheckISODateParams): this;
/** @deprecated Use `z.iso.time()` instead. */
time(params?: string | core.$ZodCheckISOTimeParams): this;
/** @deprecated Use `z.iso.duration()` instead. */
duration(params?: string | core.$ZodCheckISODurationParams): this;
}
export declare const ZodString: core.$constructor<ZodString>;
export declare function string(params?: string | core.$ZodStringParams): ZodString;
export declare function string<T extends string>(params?: string | core.$ZodStringParams): core.$ZodType<T, T>;
export interface ZodStringFormat<Format extends string = string> extends _ZodString<core.$ZodStringFormatInternals<Format>> {
}
export declare const ZodStringFormat: core.$constructor<ZodStringFormat>;
export interface ZodISODateTime extends ZodStringFormat {
_zod: core.$ZodISODateTimeInternals;
}
export declare const ZodISODateTime: core.$constructor<ZodISODateTime>;
export interface ZodISODate extends ZodStringFormat {
_zod: core.$ZodISODateInternals;
}
export declare const ZodISODate: core.$constructor<ZodISODate>;
export interface ZodISOTime extends ZodStringFormat {
_zod: core.$ZodISOTimeInternals;
}
export declare const ZodISOTime: core.$constructor<ZodISOTime>;
export interface ZodISODuration extends ZodStringFormat {
_zod: core.$ZodISODurationInternals;
}
export declare const ZodISODuration: core.$constructor<ZodISODuration>;
export interface ZodEmail extends ZodStringFormat<"email"> {
_zod: core.$ZodEmailInternals;
}
export declare const ZodEmail: core.$constructor<ZodEmail>;
export declare function email(params?: string | core.$ZodEmailParams): ZodEmail;
export interface ZodGUID extends ZodStringFormat<"guid"> {
_zod: core.$ZodGUIDInternals;
}
export declare const ZodGUID: core.$constructor<ZodGUID>;
export declare function guid(params?: string | core.$ZodGUIDParams): ZodGUID;
export interface ZodUUID extends ZodStringFormat<"uuid"> {
_zod: core.$ZodUUIDInternals;
}
export declare const ZodUUID: core.$constructor<ZodUUID>;
export declare function uuid(params?: string | core.$ZodUUIDParams): ZodUUID;
export declare function uuidv4(params?: string | core.$ZodUUIDv4Params): ZodUUID;
export declare function uuidv6(params?: string | core.$ZodUUIDv6Params): ZodUUID;
export declare function uuidv7(params?: string | core.$ZodUUIDv7Params): ZodUUID;
export interface ZodURL extends ZodStringFormat<"url"> {
_zod: core.$ZodURLInternals;
}
export declare const ZodURL: core.$constructor<ZodURL>;
export declare function url(params?: string | core.$ZodURLParams): ZodURL;
export declare function httpUrl(params?: string | Omit<core.$ZodURLParams, "protocol" | "hostname">): ZodURL;
export interface ZodEmoji extends ZodStringFormat<"emoji"> {
_zod: core.$ZodEmojiInternals;
}
export declare const ZodEmoji: core.$constructor<ZodEmoji>;
export declare function emoji(params?: string | core.$ZodEmojiParams): ZodEmoji;
export interface ZodNanoID extends ZodStringFormat<"nanoid"> {
_zod: core.$ZodNanoIDInternals;
}
export declare const ZodNanoID: core.$constructor<ZodNanoID>;
export declare function nanoid(params?: string | core.$ZodNanoIDParams): ZodNanoID;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export interface ZodCUID extends ZodStringFormat<"cuid"> {
_zod: core.$ZodCUIDInternals;
}
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare const ZodCUID: core.$constructor<ZodCUID>;
/**
* Validates a CUID v1 string.
*
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare function cuid(params?: string | core.$ZodCUIDParams): ZodCUID;
export interface ZodCUID2 extends ZodStringFormat<"cuid2"> {
_zod: core.$ZodCUID2Internals;
}
export declare const ZodCUID2: core.$constructor<ZodCUID2>;
export declare function cuid2(params?: string | core.$ZodCUID2Params): ZodCUID2;
export interface ZodULID extends ZodStringFormat<"ulid"> {
_zod: core.$ZodULIDInternals;
}
export declare const ZodULID: core.$constructor<ZodULID>;
export declare function ulid(params?: string | core.$ZodULIDParams): ZodULID;
export interface ZodXID extends ZodStringFormat<"xid"> {
_zod: core.$ZodXIDInternals;
}
export declare const ZodXID: core.$constructor<ZodXID>;
export declare function xid(params?: string | core.$ZodXIDParams): ZodXID;
export interface ZodKSUID extends ZodStringFormat<"ksuid"> {
_zod: core.$ZodKSUIDInternals;
}
export declare const ZodKSUID: core.$constructor<ZodKSUID>;
export declare function ksuid(params?: string | core.$ZodKSUIDParams): ZodKSUID;
export interface ZodIPv4 extends ZodStringFormat<"ipv4"> {
_zod: core.$ZodIPv4Internals;
}
export declare const ZodIPv4: core.$constructor<ZodIPv4>;
export declare function ipv4(params?: string | core.$ZodIPv4Params): ZodIPv4;
export interface ZodMAC extends ZodStringFormat<"mac"> {
_zod: core.$ZodMACInternals;
}
export declare const ZodMAC: core.$constructor<ZodMAC>;
export declare function mac(params?: string | core.$ZodMACParams): ZodMAC;
export interface ZodIPv6 extends ZodStringFormat<"ipv6"> {
_zod: core.$ZodIPv6Internals;
}
export declare const ZodIPv6: core.$constructor<ZodIPv6>;
export declare function ipv6(params?: string | core.$ZodIPv6Params): ZodIPv6;
export interface ZodCIDRv4 extends ZodStringFormat<"cidrv4"> {
_zod: core.$ZodCIDRv4Internals;
}
export declare const ZodCIDRv4: core.$constructor<ZodCIDRv4>;
export declare function cidrv4(params?: string | core.$ZodCIDRv4Params): ZodCIDRv4;
export interface ZodCIDRv6 extends ZodStringFormat<"cidrv6"> {
_zod: core.$ZodCIDRv6Internals;
}
export declare const ZodCIDRv6: core.$constructor<ZodCIDRv6>;
export declare function cidrv6(params?: string | core.$ZodCIDRv6Params): ZodCIDRv6;
export interface ZodBase64 extends ZodStringFormat<"base64"> {
_zod: core.$ZodBase64Internals;
}
export declare const ZodBase64: core.$constructor<ZodBase64>;
export declare function base64(params?: string | core.$ZodBase64Params): ZodBase64;
export interface ZodBase64URL extends ZodStringFormat<"base64url"> {
_zod: core.$ZodBase64URLInternals;
}
export declare const ZodBase64URL: core.$constructor<ZodBase64URL>;
export declare function base64url(params?: string | core.$ZodBase64URLParams): ZodBase64URL;
export interface ZodE164 extends ZodStringFormat<"e164"> {
_zod: core.$ZodE164Internals;
}
export declare const ZodE164: core.$constructor<ZodE164>;
export declare function e164(params?: string | core.$ZodE164Params): ZodE164;
export interface ZodCreditCard extends ZodStringFormat<"credit_card"> {
_zod: core.$ZodCreditCardInternals;
}
export declare const ZodCreditCard: core.$constructor<ZodCreditCard>;
export declare function creditCard(params?: string | core.$ZodCreditCardParams): ZodCreditCard;
export interface ZodIBAN extends ZodStringFormat<"iban"> {
_zod: core.$ZodIBANInternals;
}
export declare const ZodIBAN: core.$constructor<ZodIBAN>;
export declare function iban(params?: string | core.$ZodIBANParams): ZodIBAN;
export interface ZodJWT extends ZodStringFormat<"jwt"> {
_zod: core.$ZodJWTInternals;
}
export declare const ZodJWT: core.$constructor<ZodJWT>;
export declare function jwt(params?: string | core.$ZodJWTParams): ZodJWT;
export interface ZodCustomStringFormat<Format extends string = string> extends ZodStringFormat<Format>, core.$ZodCustomStringFormat<Format> {
_zod: core.$ZodCustomStringFormatInternals<Format>;
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodCustomStringFormat: core.$constructor<ZodCustomStringFormat>;
export declare function stringFormat<Format extends string>(format: Format, fnOrRegex: ((arg: string) => util.MaybeAsync<unknown>) | RegExp, _params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<Format>;
export declare function hostname(_params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"hostname">;
export declare function hex(_params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"hex">;
export declare function currencyCode(_params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"currency_code">;
export declare function hash<Alg extends util.HashAlgorithm, Enc extends util.HashEncoding = "hex">(alg: Alg, params?: {
enc?: Enc;
} & core.$ZodStringFormatParams): ZodCustomStringFormat<`${Alg}_${Enc}`>;
export interface _ZodNumber<Internals extends core.$ZodNumberInternals = core.$ZodNumberInternals> extends _ZodType<Internals> {
gt(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
/** Identical to .min() */
gte(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
min(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
lt(value: number, params?: string | core.$ZodCheckLessThanParams): this;
/** Identical to .max() */
lte(value: number, params?: string | core.$ZodCheckLessThanParams): this;
max(value: number, params?: string | core.$ZodCheckLessThanParams): this;
/** Consider `z.int()` instead. This API is considered *legacy*; it will never be removed but a better alternative exists. */
int(params?: string | core.$ZodCheckNumberFormatParams): this;
/** @deprecated This is now identical to `.int()`. Only numbers in the safe integer range are accepted. */
safe(params?: string | core.$ZodCheckNumberFormatParams): this;
positive(params?: string | core.$ZodCheckGreaterThanParams): this;
nonnegative(params?: string | core.$ZodCheckGreaterThanParams): this;
negative(params?: string | core.$ZodCheckLessThanParams): this;
nonpositive(params?: string | core.$ZodCheckLessThanParams): this;
multipleOf(value: number, params?: string | core.$ZodCheckMultipleOfParams): this;
/** @deprecated Use `.multipleOf()` instead. */
step(value: number, params?: string | core.$ZodCheckMultipleOfParams): this;
/** @deprecated In v4 and later, z.number() does not allow infinite values by default. This is a no-op. */
finite(params?: unknown): this;
minValue: number | null;
maxValue: number | null;
/** @deprecated Check the `format` property instead. */
isInt: boolean;
/** @deprecated Number schemas no longer accept infinite values, so this always returns `true`. */
isFinite: boolean;
format: string | null;
}
export interface ZodNumber extends _ZodNumber<core.$ZodNumberInternals<number>> {
}
export declare const ZodNumber: core.$constructor<ZodNumber>;
export declare function number(params?: string | core.$ZodNumberParams): ZodNumber;
export interface ZodNumberFormat<Format extends $ZodNumberFormats = $ZodNumberFormats> extends ZodNumber {
_zod: core.$ZodNumberFormatInternals<Format>;
}
export declare const ZodNumberFormat: core.$constructor<ZodNumberFormat>;
export interface ZodInt extends ZodNumberFormat<"safeint"> {
}
export declare function int(params?: string | core.$ZodCheckNumberFormatParams): ZodInt;
export interface ZodFloat32 extends ZodNumberFormat<"float32"> {
}
export declare function float32(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat32;
export interface ZodFloat64 extends ZodNumberFormat<"float64"> {
}
export declare function float64(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat64;
export interface ZodInt32 extends ZodNumberFormat<"int32"> {
}
export declare function int32(params?: string | core.$ZodCheckNumberFormatParams): ZodInt32;
export interface ZodUInt32 extends ZodNumberFormat<"uint32"> {
}
export declare function uint32(params?: string | core.$ZodCheckNumberFormatParams): ZodUInt32;
export interface _ZodBoolean<T extends core.$ZodBooleanInternals = core.$ZodBooleanInternals> extends _ZodType<T> {
}
export interface ZodBoolean extends _ZodBoolean<core.$ZodBooleanInternals<boolean>> {
}
export declare const ZodBoolean: core.$constructor<ZodBoolean>;
export declare function boolean(params?: string | core.$ZodBooleanParams): ZodBoolean;
export interface _ZodBigInt<T extends core.$ZodBigIntInternals = core.$ZodBigIntInternals> extends _ZodType<T> {
gte(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
/** Alias of `.gte()` */
min(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
gt(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
/** Alias of `.lte()` */
lte(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
max(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
lt(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
positive(params?: string | core.$ZodCheckGreaterThanParams): this;
negative(params?: string | core.$ZodCheckLessThanParams): this;
nonpositive(params?: string | core.$ZodCheckLessThanParams): this;
nonnegative(params?: string | core.$ZodCheckGreaterThanParams): this;
multipleOf(value: bigint, params?: string | core.$ZodCheckMultipleOfParams): this;
minValue: bigint | null;
maxValue: bigint | null;
format: string | null;
}
export interface ZodBigInt extends _ZodBigInt<core.$ZodBigIntInternals<bigint>> {
}
export declare const ZodBigInt: core.$constructor<ZodBigInt>;
export declare function bigint(params?: string | core.$ZodBigIntParams): ZodBigInt;
export interface ZodBigIntFormat<Format extends $ZodBigIntFormats = $ZodBigIntFormats> extends ZodBigInt {
_zod: core.$ZodBigIntFormatInternals<Format>;
}
export declare const ZodBigIntFormat: core.$constructor<ZodBigIntFormat>;
export interface ZodInt64 extends ZodBigIntFormat<"int64"> {
}
export declare function int64(params?: string | core.$ZodBigIntFormatParams): ZodInt64;
export interface ZodUInt64 extends ZodBigIntFormat<"uint64"> {
}
export declare function uint64(params?: string | core.$ZodBigIntFormatParams): ZodUInt64;
export interface ZodSymbol extends _ZodType<core.$ZodSymbolInternals> {
}
export declare const ZodSymbol: core.$constructor<ZodSymbol>;
export declare function symbol(params?: string | core.$ZodSymbolParams): ZodSymbol;
export interface ZodUndefined extends _ZodType<core.$ZodUndefinedInternals> {
}
export declare const ZodUndefined: core.$constructor<ZodUndefined>;
declare function _undefined(params?: string | core.$ZodUndefinedParams): ZodUndefined;
export { _undefined as undefined };
export interface ZodNull extends _ZodType<core.$ZodNullInternals> {
}
export declare const ZodNull: core.$constructor<ZodNull>;
declare function _null(params?: string | core.$ZodNullParams): ZodNull;
export { _null as null };
export interface ZodAny extends _ZodType<core.$ZodAnyInternals> {
}
export declare const ZodAny: core.$constructor<ZodAny>;
export declare function any(): ZodAny;
export interface ZodUnknown extends _ZodType<core.$ZodUnknownInternals> {
}
export declare const ZodUnknown: core.$constructor<ZodUnknown>;
export declare function unknown(): ZodUnknown;
export interface ZodNever extends _ZodType<core.$ZodNeverInternals> {
}
export declare const ZodNever: core.$constructor<ZodNever>;
export declare function never(params?: string | core.$ZodNeverParams): ZodNever;
export interface ZodVoid extends _ZodType<core.$ZodVoidInternals> {
}
export declare const ZodVoid: core.$constructor<ZodVoid>;
declare function _void(params?: string | core.$ZodVoidParams): ZodVoid;
export { _void as void };
export interface _ZodDate<T extends core.$ZodDateInternals = core.$ZodDateInternals> extends _ZodType<T> {
min(value: number | Date, params?: string | core.$ZodCheckGreaterThanParams): this;
max(value: number | Date, params?: string | core.$ZodCheckLessThanParams): this;
/** @deprecated Not recommended. */
minDate: Date | null;
/** @deprecated Not recommended. */
maxDate: Date | null;
}
export interface ZodDate extends _ZodDate<core.$ZodDateInternals<Date>> {
}
export declare const ZodDate: core.$constructor<ZodDate>;
export declare function date(params?: string | core.$ZodDateParams): ZodDate;
export interface ZodArray<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodArrayInternals<T>>, core.$ZodArray<T> {
element: T;
min(minLength: number, params?: string | core.$ZodCheckMinLengthParams): this;
nonempty(params?: string | core.$ZodCheckMinLengthParams): this;
max(maxLength: number, params?: string | core.$ZodCheckMaxLengthParams): this;
length(len: number, params?: string | core.$ZodCheckLengthEqualsParams): this;
unwrap(): T;
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodArray: core.$constructor<ZodArray>;
export declare function array<T extends core.SomeType>(element: T, params?: string | core.$ZodArrayParams): ZodArray<T>;
export declare function keyof<T extends ZodObject>(schema: T): ZodEnum<util.KeysEnum<T["_zod"]["output"]>>;
export type SafeExtendShape<Base extends core.$ZodShape, Ext extends core.$ZodLooseShape> = {
[K in keyof Ext]: K extends keyof Base ? core.output<Ext[K]> extends core.output<Base[K]> ? core.input<Ext[K]> extends core.input<Base[K]> ? Ext[K] : never : never : Ext[K];
};
export interface ZodObject<
/** @ts-ignore Cast variance */
out Shape extends core.$ZodShape = core.$ZodLooseShape, out Config extends core.$ZodObjectConfig = core.$strip> extends _ZodType<core.$ZodObjectInternals<Shape, Config>>, core.$ZodObject<Shape, Config> {
"~standard": ZodStandardSchemaWithJSON<this>;
shape: Shape;
keyof(): ZodEnum<util.ToEnum<keyof Shape & string>>;
/** Define a schema to validate all unrecognized keys. This overrides the existing strict/loose behavior. */
catchall<T extends core.SomeType>(schema: T): ZodObject<Shape, core.$catchall<T>>;
/** @deprecated Use `z.looseObject()` or `.loose()` instead. */
passthrough(): ZodObject<Shape, core.$loose>;
/** Consider `z.looseObject(A.shape)` instead */
loose(): ZodObject<Shape, core.$loose>;
/** Consider `z.strictObject(A.shape)` instead */
strict(): ZodObject<Shape, core.$strict>;
/** This is the default behavior. This method call is likely unnecessary. */
strip(): ZodObject<Shape, core.$strip>;
extend<U extends core.$ZodLooseShape>(shape: U): ZodObject<util.Extend<Shape, util.Writeable<U>>, Config>;
safeExtend<U extends core.$ZodLooseShape>(shape: SafeExtendShape<Shape, U> & Partial<Record<keyof Shape, core.SomeType>>): ZodObject<util.Extend<Shape, util.Writeable<U>>, Config>;
/**
* @deprecated Use [`A.extend(B.shape)`](https://zod.dev/api?id=extend) instead.
*/
merge<U extends ZodObject>(other: U): ZodObject<util.Extend<Shape, U["shape"]>, U["_zod"]["config"]>;
pick<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<util.Flatten<Pick<Shape, Extract<keyof Shape, keyof M>>>, Config>;
omit<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<util.Flatten<Omit<Shape, Extract<keyof Shape, keyof M>>>, Config>;
partial(): ZodObject<{
-readonly [k in keyof Shape]: ZodOptional<Shape[k]>;
}, Config>;
partial<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
-readonly [k in keyof Shape]: k extends keyof M ? ZodOptional<Shape[k]> : Shape[k];
}, Config>;
exactPartial(): ZodObject<{
-readonly [k in keyof Shape]: ZodExactOptional<Shape[k]>;
}, Config>;
exactPartial<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
-readonly [k in keyof Shape]: k extends keyof M ? ZodExactOptional<Shape[k]> : Shape[k];
}, Config>;
required(): ZodObject<{
-readonly [k in keyof Shape]: ZodNonOptional<Shape[k]>;
}, Config>;
required<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
-readonly [k in keyof Shape]: k extends keyof M ? ZodNonOptional<Shape[k]> : Shape[k];
}, Config>;
}
export declare const ZodObject: core.$constructor<ZodObject>;
export declare function object<T extends core.$ZodLooseShape = Partial<Record<never, core.SomeType>>>(shape?: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$strip>;
export declare function strictObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$strict>;
export declare function looseObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$loose>;
export interface ZodUnion<T extends readonly core.SomeType[] = readonly core.$ZodType[]> extends _ZodType<core.$ZodUnionInternals<T>>, core.$ZodUnion<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
options: T;
}
export declare const ZodUnion: core.$constructor<ZodUnion>;
export declare function union<const T extends readonly core.SomeType[]>(options: T, params?: string | core.$ZodUnionParams): ZodUnion<T>;
export interface ZodXor<T extends readonly core.SomeType[] = readonly core.$ZodType[]> extends _ZodType<core.$ZodXorInternals<T>>, core.$ZodXor<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
options: T;
}
export declare const ZodXor: core.$constructor<ZodXor>;
/** Creates an exclusive union (XOR) where exactly one option must match.
* Unlike regular unions that succeed when any option matches, xor fails if
* zero or more than one option matches the input. */
export declare function xor<const T extends readonly core.SomeType[]>(options: T, params?: string | core.$ZodXorParams): ZodXor<T>;
export interface ZodDiscriminatedUnion<Options extends readonly core.SomeType[] = readonly core.$ZodType[], Disc extends string = string> extends ZodUnion<Options>, core.$ZodDiscriminatedUnion<Options, Disc> {
"~standard": ZodStandardSchemaWithJSON<this>;
_zod: core.$ZodDiscriminatedUnionInternals<Options, Disc>;
def: core.$ZodDiscriminatedUnionDef<Options, Disc>;
}
export declare const ZodDiscriminatedUnion: core.$constructor<ZodDiscriminatedUnion>;
export declare function discriminatedUnion<Types extends readonly [core.$ZodTypeDiscriminable, ...core.$ZodTypeDiscriminable[]], Disc extends string>(discriminator: Disc, options: Types, params?: string | core.$ZodDiscriminatedUnionParams): ZodDiscriminatedUnion<Types, Disc>;
export interface ZodIntersection<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodIntersectionInternals<A, B>>, core.$ZodIntersection<A, B> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodIntersection: core.$constructor<ZodIntersection>;
export declare function intersection<T extends core.SomeType, U extends core.SomeType>(left: T, right: U): ZodIntersection<T, U>;
export interface ZodTuple<T extends util.TupleItems = readonly core.$ZodType[], Rest extends core.SomeType | null = core.$ZodType | null> extends _ZodType<core.$ZodTupleInternals<T, Rest>>, core.$ZodTuple<T, Rest> {
"~standard": ZodStandardSchemaWithJSON<this>;
rest<Rest extends core.SomeType = core.$ZodType>(rest: Rest): ZodTuple<T, Rest>;
partial(): ZodTuple<{
-readonly [k in keyof T]: ZodOptional<T[k]>;
}, Rest>;
}
export declare const ZodTuple: core.$constructor<ZodTuple>;
export declare function tuple<T extends readonly [core.SomeType, ...core.SomeType[]]>(items: T, params?: string | core.$ZodTupleParams): ZodTuple<T, null>;
export declare function tuple<T extends readonly [core.SomeType, ...core.SomeType[]], Rest extends core.SomeType>(items: T, rest: Rest, params?: string | core.$ZodTupleParams): ZodTuple<T, Rest>;
export declare function tuple(items: [], params?: string | core.$ZodTupleParams): ZodTuple<[], null>;
export interface ZodRecord<Key extends core.$ZodRecordKey = core.$ZodRecordKey, Value extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodRecordInternals<Key, Value>>, core.$ZodRecord<Key, Value> {
"~standard": ZodStandardSchemaWithJSON<this>;
keyType: Key;
valueType: Value;
}
export declare const ZodRecord: core.$constructor<ZodRecord>;
export declare function record<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key, Value>;
export declare function partialRecord<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key & core.$partial, Value>;
export declare function looseRecord<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key, Value>;
export interface ZodMap<Key extends core.SomeType = core.$ZodType, Value extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodMapInternals<Key, Value>>, core.$ZodMap<Key, Value> {
"~standard": ZodStandardSchemaWithJSON<this>;
keyType: Key;
valueType: Value;
min(minSize: number, params?: string | core.$ZodCheckMinSizeParams): this;
nonempty(params?: string | core.$ZodCheckMinSizeParams): this;
max(maxSize: number, params?: string | core.$ZodCheckMaxSizeParams): this;
size(size: number, params?: string | core.$ZodCheckSizeEqualsParams): this;
}
export declare const ZodMap: core.$constructor<ZodMap>;
export declare function map<Key extends core.SomeType, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodMapParams): ZodMap<Key, Value>;
export interface ZodSet<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodSetInternals<T>>, core.$ZodSet<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
min(minSize: number, params?: string | core.$ZodCheckMinSizeParams): this;
nonempty(params?: string | core.$ZodCheckMinSizeParams): this;
max(maxSize: number, params?: string | core.$ZodCheckMaxSizeParams): this;
size(size: number, params?: string | core.$ZodCheckSizeEqualsParams): this;
}
export declare const ZodSet: core.$constructor<ZodSet>;
export declare function set<Value extends core.SomeType>(valueType: Value, params?: string | core.$ZodSetParams): ZodSet<Value>;
export interface ZodEnum<
/** @ts-ignore Cast variance */
out T extends util.EnumLike = util.EnumLike> extends _ZodType<core.$ZodEnumInternals<T>>, core.$ZodEnum<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
enum: T;
options: Array<T[keyof T]>;
extract<const U extends readonly (keyof T)[]>(values: U, params?: string | core.$ZodEnumParams): ZodEnum<util.Flatten<Pick<T, U[number]>>>;
exclude<const U extends readonly (keyof T)[]>(values: U, params?: string | core.$ZodEnumParams): ZodEnum<util.Flatten<Omit<T, U[number]>>>;
}
export declare const ZodEnum: core.$constructor<ZodEnum>;
declare function _enum<const T extends readonly string[]>(values: T, params?: string | core.$ZodEnumParams): ZodEnum<util.ToEnum<T[number]>>;
declare function _enum<const T extends util.EnumLike>(entries: T, params?: string | core.$ZodEnumParams): ZodEnum<T>;
export { _enum as enum };
/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.
*
* ```ts
* enum Colors { red, green, blue }
* z.enum(Colors);
* ```
*/
export declare function nativeEnum<T extends util.EnumLike>(entries: T, params?: string | core.$ZodEnumParams): ZodEnum<T>;
export interface ZodLiteral<T extends util.Literal = util.Literal> extends _ZodType<core.$ZodLiteralInternals<T>>, core.$ZodLiteral<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
values: Set<T>;
/** @legacy Use `.values` instead. Accessing this property will throw an error if the literal accepts multiple values. */
value: T;
}
export declare const ZodLiteral: core.$constructor<ZodLiteral>;
export declare function literal<const T extends ReadonlyArray<util.Literal>>(value: T, params?: string | core.$ZodLiteralParams): ZodLiteral<T[number]>;
export declare function literal<const T extends util.Literal>(value: T, params?: string | core.$ZodLiteralParams): ZodLiteral<T>;
export interface ZodFile extends _ZodType<core.$ZodFileInternals>, core.$ZodFile {
"~standard": ZodStandardSchemaWithJSON<this>;
min(size: number, params?: string | core.$ZodCheckMinSizeParams): this;
max(size: number, params?: string | core.$ZodCheckMaxSizeParams): this;
mime(types: util.MimeTypes | Array<util.MimeTypes>, params?: string | core.$ZodCheckMimeTypeParams): this;
}
export declare const ZodFile: core.$constructor<ZodFile>;
export declare function file(params?: string | core.$ZodFileParams): ZodFile;
export interface ZodTransform<O = unknown, I = unknown> extends _ZodType<core.$ZodTransformInternals<O, I>>, core.$ZodTransform<O, I> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodTransform: core.$constructor<ZodTransform>;
export declare function transform<I = unknown, O = I>(fn: (input: I, ctx: core.$RefinementCtx) => O): ZodTransform<Awaited<O>, I>;
export interface ZodOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodOptionalInternals<T>>, core.$ZodOptional<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodOptional: core.$constructor<ZodOptional>;
export declare function optional<T extends core.SomeType>(innerType: T): ZodOptional<T>;
export interface ZodExactOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodExactOptionalInternals<T>>, core.$ZodExactOptional<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodExactOptional: core.$constructor<ZodExactOptional>;
export declare function exactOptional<T extends core.SomeType>(innerType: T): ZodExactOptional<T>;
export interface ZodNullable<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodNullableInternals<T>>, core.$ZodNullable<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodNullable: core.$constructor<ZodNullable>;
export declare function nullable<T extends core.SomeType>(innerType: T): ZodNullable<T>;
export declare function nullish<T extends core.SomeType>(innerType: T): ZodOptional<ZodNullable<T>>;
export interface ZodDefault<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodDefaultInternals<T>>, core.$ZodDefault<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
/** @deprecated Use `.unwrap()` instead. */
removeDefault(): T;
}
export declare const ZodDefault: core.$constructor<ZodDefault>;
export declare function _default<T extends core.SomeType>(innerType: T, defaultValue: util.NoUndefined<core.output<T>> | (() => util.NoUndefined<core.output<T>>)): ZodDefault<T>;
export interface ZodPrefault<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPrefaultInternals<T>>, core.$ZodPrefault<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodPrefault: core.$constructor<ZodPrefault>;
export declare function prefault<T extends core.SomeType>(innerType: T, defaultValue: core.input<T> | (() => core.input<T>)): ZodPrefault<T>;
export interface ZodNonOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodNonOptionalInternals<T>>, core.$ZodNonOptional<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodNonOptional: core.$constructor<ZodNonOptional>;
export declare function nonoptional<T extends core.SomeType>(innerType: T, params?: string | core.$ZodNonOptionalParams): ZodNonOptional<T>;
export interface ZodSuccess<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodSuccessInternals<T>>, core.$ZodSuccess<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodSuccess: core.$constructor<ZodSuccess>;
export declare function success<T extends core.SomeType>(innerType: T): ZodSuccess<T>;
export interface ZodCatch<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodCatchInternals<T>>, core.$ZodCatch<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
/** @deprecated Use `.unwrap()` instead. */
removeCatch(): T;
}
export declare const ZodCatch: core.$constructor<ZodCatch>;
declare function _catch<T extends core.SomeType>(innerType: T, catchValue: core.output<T> | ((ctx: core.$ZodCatchCtx) => core.output<T>)): ZodCatch<T>;
export { _catch as catch };
export interface ZodNaN extends _ZodType<core.$ZodNaNInternals>, core.$ZodNaN {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodNaN: core.$constructor<ZodNaN>;
export declare function nan(params?: string | core.$ZodNaNParams): ZodNaN;
export interface ZodPipe<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPipeInternals<A, B>>, core.$ZodPipe<A, B> {
"~standard": ZodStandardSchemaWithJSON<this>;
in: A;
out: B;
}
export declare const ZodPipe: core.$constructor<ZodPipe>;
export declare function pipe<const A extends core.SomeType, B extends core.$ZodType<unknown, core.output<A>> = core.$ZodType<unknown, core.output<A>>>(in_: A, out: B | core.$ZodType<unknown, core.output<A>>): ZodPipe<A, B>;
export interface ZodCodec<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends ZodPipe<A, B>, core.$ZodCodec<A, B> {
"~standard": ZodStandardSchemaWithJSON<this>;
_zod: core.$ZodCodecInternals<A, B>;
def: core.$ZodCodecDef<A, B>;
}
export declare const ZodCodec: core.$constructor<ZodCodec>;
export declare function codec<const A extends core.SomeType, B extends core.SomeType = core.$ZodType>(in_: A, out: B, params: {
decode: (value: core.output<A>, payload: core.ParsePayload<core.output<A>>) => core.util.MaybeAsync<core.input<B>>;
encode: (value: core.input<B>, payload: core.ParsePayload<core.input<B>>) => core.util.MaybeAsync<core.output<A>>;
}): ZodCodec<A, B>;
export declare function invertCodec<A extends core.SomeType, B extends core.SomeType>(codec: ZodCodec<A, B>): ZodCodec<B, A>;
export interface ZodPreprocess<B extends core.SomeType = core.$ZodType, I = unknown> extends ZodPipe<core.$ZodTransform<unknown, I>, B>, core.$ZodPreprocess<B, I> {
"~standard": ZodStandardSchemaWithJSON<this>;
_zod: core.$ZodPreprocessInternals<B, I>;
def: core.$ZodPreprocessDef<B, I>;
}
export declare const ZodPreprocess: core.$constructor<ZodPreprocess>;
export interface ZodReadonly<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodReadonlyInternals<T>>, core.$ZodReadonly<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodReadonly: core.$constructor<ZodReadonly>;
export declare function readonly<T extends core.SomeType>(innerType: T): ZodReadonly<T>;
export interface ZodTemplateLiteral<Template extends string = string> extends _ZodType<core.$ZodTemplateLiteralInternals<Template>>, core.$ZodTemplateLiteral<Template> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodTemplateLiteral: core.$constructor<ZodTemplateLiteral>;
export declare function templateLiteral<const Parts extends core.$ZodTemplateLiteralPart[]>(parts: Parts, params?: string | core.$ZodTemplateLiteralParams): ZodTemplateLiteral<core.$PartsToTemplateLiteral<Parts>>;
export interface ZodLazy<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodLazyInternals<T>>, core.$ZodLazy<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodLazy: core.$constructor<ZodLazy>;
export declare function lazy<T extends core.SomeType>(getter: () => T): ZodLazy<T>;
export interface ZodPromise<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPromiseInternals<T>>, core.$ZodPromise<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodPromise: core.$constructor<ZodPromise>;
export declare function promise<T extends core.SomeType>(innerType: T): ZodPromise<T>;
export interface ZodFunction<Args extends core.$ZodFunctionIn = core.$ZodFunctionIn, Returns extends core.$ZodFunctionOut = core.$ZodFunctionOut> extends _ZodType<core.$ZodFunctionInternals<Args, Returns>>, core.$ZodFunction<Args, Returns> {
"~standard": ZodStandardSchemaWithJSON<this>;
_def: core.$ZodFunctionDef<Args, Returns>;
_input: core.$InferInnerFunctionType<Args, Returns>;
_output: core.$InferOuterFunctionType<Args, Returns>;
input<const Items extends util.TupleItems, const Rest extends core.$ZodFunctionOut = core.$ZodFunctionOut>(args: Items, rest?: Rest): ZodFunction<core.$ZodTuple<Items, Rest>, Returns>;
input<NewArgs extends core.$ZodFunctionIn>(args: NewArgs): ZodFunction<NewArgs, Returns>;
input(...args: any[]): ZodFunction<any, Returns>;
output<NewReturns extends core.$ZodType>(output: NewReturns): ZodFunction<Args, NewReturns>;
}
export declare const ZodFunction: core.$constructor<ZodFunction>;
export declare function _function(): ZodFunction;
export declare function _function<const In extends ReadonlyArray<core.$ZodType>>(params: {
input: In;
}): ZodFunction<ZodTuple<In, null>, core.$ZodFunctionOut>;
export declare function _function<const In extends ReadonlyArray<core.$ZodType>, const Out extends core.$ZodFunctionOut = core.$ZodFunctionOut>(params: {
input: In;
output: Out;
}): ZodFunction<ZodTuple<In, null>, Out>;
export declare function _function<const In extends core.$ZodFunctionIn = core.$ZodFunctionIn>(params: {
input: In;
}): ZodFunction<In, core.$ZodFunctionOut>;
export declare function _function<const Out extends core.$ZodFunctionOut = core.$ZodFunctionOut>(params: {
output: Out;
}): ZodFunction<core.$ZodFunctionIn, Out>;
export declare function _function<In extends core.$ZodFunctionIn = core.$ZodFunctionIn, Out extends core.$ZodType = core.$ZodType>(params?: {
input: In;
output: Out;
}): ZodFunction<In, Out>;
export { _function as function };
export interface ZodCustom<O = unknown, I = unknown> extends _ZodType<core.$ZodCustomInternals<O, I>>, core.$ZodCustom<O, I> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodCustom: core.$constructor<ZodCustom>;
export declare function check<O = unknown>(fn: core.CheckFn<O>): core.$ZodCheck<O>;
export declare function custom<O>(fn?: (data: unknown) => unknown, _params?: string | core.$ZodCustomParams | undefined): ZodCustom<O, O>;
export declare function refine<T>(fn: (arg: NoInfer<T>) => util.MaybeAsync<unknown>, _params?: string | core.$ZodCustomParams): core.$ZodCheck<T>;
export declare function superRefine<T>(fn: (arg: T, payload: core.$RefinementCtx<T>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): core.$ZodCheck<T>;
export declare const describe: typeof core.describe;
export declare const meta: typeof core.meta;
type ZodInstanceOfParams = core.Params<ZodCustom, core.$ZodIssueCustom, "type" | "check" | "checks" | "fn" | "abort" | "error" | "params" | "path">;
export interface ZodInstanceOf<T = unknown> extends ZodCustom<T, T> {
properties<Shape extends {
[k in keyof T as T[k] extends Function ? never : k]?: core.$ZodType<unknown, T[k]>;
}>(shape: Shape, params?: string | core.$ZodCheckPropertiesParams): ZodInstanceOf<T & core.$InferObjectInput<Shape, {}>>;
}
export declare const ZodInstanceOf: core.$constructor<ZodInstanceOf>;
declare function _instanceof<T extends typeof util.Class>(cls: T, params?: ZodInstanceOfParams): ZodInstanceOf<InstanceType<T>>;
export { _instanceof as instanceof };
export declare const stringbool: (_params?: string | core.$ZodStringBoolParams) => ZodCodec<ZodString, ZodBoolean>;
type _ZodJSONSchema = ZodUnion<[
ZodString,
ZodNumber,
ZodBoolean,
ZodNull,
ZodArray<ZodJSONSchema>,
ZodRecord<ZodString, ZodJSONSchema>
]>;
type _ZodJSONSchemaInternals = _ZodJSONSchema["_zod"];
export interface ZodJSONSchemaInternals extends _ZodJSONSchemaInternals {
output: util.JSONType;
input: util.JSONType;
}
export interface ZodJSONSchema extends _ZodJSONSchema {
_zod: ZodJSONSchemaInternals;
}
export declare function json(params?: string | core.$ZodCustomParams): ZodJSONSchema;
export declare function preprocess<A, U extends core.SomeType, B = unknown>(fn: (arg: B, ctx: core.$RefinementCtx) => A, schema: U): ZodPreprocess<U, B>;
+816
View File
@@ -0,0 +1,816 @@
import type { $ZodBigIntFormats } from "../core/checks.js";
import * as core from "../core/index.js";
import { util, type $ZodNumberFormats } from "../core/index.js";
import type { StandardSchemaWithJSONProps } from "../core/standard-schema.js";
import * as parse from "./parse.js";
export type ZodStandardSchemaWithJSON<T> = StandardSchemaWithJSONProps<core.input<T>, core.output<T>>;
export interface ZodType<out Output = unknown, out Input = unknown, out Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> extends core.$ZodType<Output, Input, Internals> {
def: Internals["def"];
type: Internals["def"]["type"];
/** @deprecated Use `.def` instead. */
_def: Internals["def"];
/** @deprecated Use `z.output<typeof schema>` instead. */
_output: Internals["output"];
/** @deprecated Use `z.input<typeof schema>` instead. */
_input: Internals["input"];
"~standard": ZodStandardSchemaWithJSON<this>;
/** Converts this schema to a JSON Schema representation. */
toJSONSchema(params?: core.ToJSONSchemaParams): core.ZodStandardJSONSchemaPayload<this>;
check(...checks: (core.CheckFn<core.output<this>> | core.$ZodCheck<core.output<this>>)[]): this;
with(...checks: (core.CheckFn<core.output<this>> | core.$ZodCheck<core.output<this>>)[]): this;
clone(def?: Internals["def"], params?: {
parent: boolean;
}): this;
register<R extends core.$ZodRegistry>(registry: R, ...meta: this extends R["_schema"] ? undefined extends R["_meta"] ? [core.$replace<R["_meta"], this>?] : [core.$replace<R["_meta"], this>] : ["Incompatible schema"]): this;
brand<T extends PropertyKey = PropertyKey, Dir extends "in" | "out" | "inout" = "out">(value?: T): PropertyKey extends T ? this : core.$ZodBranded<this, T, Dir>;
parse(data: unknown, params?: core.ParseContext<core.$ZodIssue>): core.output<this>;
safeParse(data: unknown, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.output<this>>;
parseAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<core.output<this>>;
safeParseAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.output<this>>>;
spa: (data: unknown, params?: core.ParseContext<core.$ZodIssue>) => Promise<parse.ZodSafeParseResult<core.output<this>>>;
validate(data: unknown, params?: core.ParseContext<core.$ZodIssue>): data is core.input<this>;
validateAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<boolean>;
encode(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): core.input<this>;
decode(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): core.output<this>;
encodeAsync(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<core.input<this>>;
decodeAsync(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<core.output<this>>;
safeEncode(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.input<this>>;
safeDecode(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.output<this>>;
safeEncodeAsync(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.input<this>>>;
safeDecodeAsync(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.output<this>>>;
refine<Ch extends (arg: core.output<this>) => unknown | Promise<unknown>>(check: Ch, params?: string | core.$ZodCustomParams): Ch extends (arg: any) => arg is infer R ? this & ZodType<R, core.input<this>> : this;
superRefine(refinement: (arg: core.output<this>, ctx: core.$RefinementCtx<core.output<this>>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): this;
overwrite(fn: (x: core.output<this>) => core.output<this>): this;
optional(): ZodOptional<this>;
exactOptional(): ZodExactOptional<this>;
nonoptional(params?: string | core.$ZodNonOptionalParams): ZodNonOptional<this>;
nullable(): ZodNullable<this>;
nullish(): ZodOptional<ZodNullable<this>>;
default(def: util.NoUndefined<core.output<this>>): ZodDefault<this>;
default(def: () => util.NoUndefined<core.output<this>>): ZodDefault<this>;
prefault(def: () => core.input<this>): ZodPrefault<this>;
prefault(def: core.input<this>): ZodPrefault<this>;
array(): ZodArray<this>;
or<T extends core.SomeType>(option: T): ZodUnion<[this, T]>;
and<T extends core.SomeType>(incoming: T): ZodIntersection<this, T>;
transform<NewOut>(transform: (arg: core.output<this>, ctx: core.$RefinementCtx<core.output<this>>) => NewOut | Promise<NewOut>): ZodPipe<this, ZodTransform<Awaited<NewOut>, core.output<this>>>;
catch(def: core.output<this>): ZodCatch<this>;
catch(def: (ctx: core.$ZodCatchCtx) => core.output<this>): ZodCatch<this>;
pipe<T extends core.$ZodType<any, core.output<this>>>(target: T | core.$ZodType<any, core.output<this>>): ZodPipe<this, T>;
readonly(): ZodReadonly<this>;
/** Returns a new instance that has been registered in `z.globalRegistry` with the specified description */
describe(description: string): this;
description?: string;
/** Returns the metadata associated with this instance in `z.globalRegistry` */
meta(): core.$replace<core.GlobalMeta, this> | undefined;
/** Returns a new instance that has been registered in `z.globalRegistry` with the specified metadata */
meta(data: core.$replace<core.GlobalMeta, this>): this;
/** @deprecated Try safe-parsing `undefined` (this is what `isOptional` does internally):
*
* ```ts
* const schema = z.string().optional();
* const isOptional = schema.safeParse(undefined).success; // true
* ```
*/
isOptional(): boolean;
/**
* @deprecated Try safe-parsing `null` (this is what `isNullable` does internally):
*
* ```ts
* const schema = z.string().nullable();
* const isNullable = schema.safeParse(null).success; // true
* ```
*/
isNullable(): boolean;
apply<T, TArgs extends unknown[] = []>(fn: (schema: this, ...args: TArgs) => T, ...args: TArgs): T;
}
export interface _ZodType<out Internals extends core.$ZodTypeInternals = core.$ZodTypeInternals> extends ZodType<any, any, Internals> {
}
export declare const ZodType: core.$constructor<ZodType>;
export interface _ZodString<T extends core.$ZodStringInternals<unknown> = core.$ZodStringInternals<unknown>> extends _ZodType<T> {
format: string | null;
minLength: number | null;
maxLength: number | null;
regex(regex: RegExp, params?: string | core.$ZodCheckRegexParams): this;
includes(value: string, params?: string | core.$ZodCheckIncludesParams): this;
startsWith(value: string, params?: string | core.$ZodCheckStartsWithParams): this;
endsWith(value: string, params?: string | core.$ZodCheckEndsWithParams): this;
min(minLength: number, params?: string | core.$ZodCheckMinLengthParams): this;
max(maxLength: number, params?: string | core.$ZodCheckMaxLengthParams): this;
length(len: number, params?: string | core.$ZodCheckLengthEqualsParams): this;
nonempty(params?: string | core.$ZodCheckMinLengthParams): this;
lowercase(params?: string | core.$ZodCheckLowerCaseParams): this;
uppercase(params?: string | core.$ZodCheckUpperCaseParams): this;
trim(): this;
normalize(form?: "NFC" | "NFD" | "NFKC" | "NFKD" | (string & {})): this;
toLowerCase(): this;
toUpperCase(): this;
slugify(): this;
}
/** @internal */
export declare const _ZodString: core.$constructor<_ZodString>;
export interface ZodString extends _ZodString<core.$ZodStringInternals<string>> {
/** @deprecated Use `z.email()` instead. */
email(params?: string | core.$ZodCheckEmailParams): this;
/** @deprecated Use `z.url()` instead. */
url(params?: string | core.$ZodCheckURLParams): this;
/** @deprecated Use `z.jwt()` instead. */
jwt(params?: string | core.$ZodCheckJWTParams): this;
/** @deprecated Use `z.emoji()` instead. */
emoji(params?: string | core.$ZodCheckEmojiParams): this;
/** @deprecated Use `z.guid()` instead. */
guid(params?: string | core.$ZodCheckGUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuid(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuidv4(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuidv6(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuidv7(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.nanoid()` instead. */
nanoid(params?: string | core.$ZodCheckNanoIDParams): this;
/** @deprecated Use `z.guid()` instead. */
guid(params?: string | core.$ZodCheckGUIDParams): this;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use `z.cuid2()` instead.
* See https://github.com/paralleldrive/cuid.
*/
cuid(params?: string | core.$ZodCheckCUIDParams): this;
/** @deprecated Use `z.cuid2()` instead. */
cuid2(params?: string | core.$ZodCheckCUID2Params): this;
/** @deprecated Use `z.ulid()` instead. */
ulid(params?: string | core.$ZodCheckULIDParams): this;
/** @deprecated Use `z.base64()` instead. */
base64(params?: string | core.$ZodCheckBase64Params): this;
/** @deprecated Use `z.base64url()` instead. */
base64url(params?: string | core.$ZodCheckBase64URLParams): this;
/** @deprecated Use `z.xid()` instead. */
xid(params?: string | core.$ZodCheckXIDParams): this;
/** @deprecated Use `z.ksuid()` instead. */
ksuid(params?: string | core.$ZodCheckKSUIDParams): this;
/** @deprecated Use `z.ipv4()` instead. */
ipv4(params?: string | core.$ZodCheckIPv4Params): this;
/** @deprecated Use `z.ipv6()` instead. */
ipv6(params?: string | core.$ZodCheckIPv6Params): this;
/** @deprecated Use `z.cidrv4()` instead. */
cidrv4(params?: string | core.$ZodCheckCIDRv4Params): this;
/** @deprecated Use `z.cidrv6()` instead. */
cidrv6(params?: string | core.$ZodCheckCIDRv6Params): this;
/** @deprecated Use `z.e164()` instead. */
e164(params?: string | core.$ZodCheckE164Params): this;
/** @deprecated Use `z.iso.datetime()` instead. */
datetime(params?: string | core.$ZodCheckISODateTimeParams): this;
/** @deprecated Use `z.iso.date()` instead. */
date(params?: string | core.$ZodCheckISODateParams): this;
/** @deprecated Use `z.iso.time()` instead. */
time(params?: string | core.$ZodCheckISOTimeParams): this;
/** @deprecated Use `z.iso.duration()` instead. */
duration(params?: string | core.$ZodCheckISODurationParams): this;
}
export declare const ZodString: core.$constructor<ZodString>;
export declare function string(params?: string | core.$ZodStringParams): ZodString;
export declare function string<T extends string>(params?: string | core.$ZodStringParams): core.$ZodType<T, T>;
export interface ZodStringFormat<Format extends string = string> extends _ZodString<core.$ZodStringFormatInternals<Format>> {
}
export declare const ZodStringFormat: core.$constructor<ZodStringFormat>;
export interface ZodISODateTime extends ZodStringFormat {
_zod: core.$ZodISODateTimeInternals;
}
export declare const ZodISODateTime: core.$constructor<ZodISODateTime>;
export interface ZodISODate extends ZodStringFormat {
_zod: core.$ZodISODateInternals;
}
export declare const ZodISODate: core.$constructor<ZodISODate>;
export interface ZodISOTime extends ZodStringFormat {
_zod: core.$ZodISOTimeInternals;
}
export declare const ZodISOTime: core.$constructor<ZodISOTime>;
export interface ZodISODuration extends ZodStringFormat {
_zod: core.$ZodISODurationInternals;
}
export declare const ZodISODuration: core.$constructor<ZodISODuration>;
export interface ZodEmail extends ZodStringFormat<"email"> {
_zod: core.$ZodEmailInternals;
}
export declare const ZodEmail: core.$constructor<ZodEmail>;
export declare function email(params?: string | core.$ZodEmailParams): ZodEmail;
export interface ZodGUID extends ZodStringFormat<"guid"> {
_zod: core.$ZodGUIDInternals;
}
export declare const ZodGUID: core.$constructor<ZodGUID>;
export declare function guid(params?: string | core.$ZodGUIDParams): ZodGUID;
export interface ZodUUID extends ZodStringFormat<"uuid"> {
_zod: core.$ZodUUIDInternals;
}
export declare const ZodUUID: core.$constructor<ZodUUID>;
export declare function uuid(params?: string | core.$ZodUUIDParams): ZodUUID;
export declare function uuidv4(params?: string | core.$ZodUUIDv4Params): ZodUUID;
export declare function uuidv6(params?: string | core.$ZodUUIDv6Params): ZodUUID;
export declare function uuidv7(params?: string | core.$ZodUUIDv7Params): ZodUUID;
export interface ZodURL extends ZodStringFormat<"url"> {
_zod: core.$ZodURLInternals;
}
export declare const ZodURL: core.$constructor<ZodURL>;
export declare function url(params?: string | core.$ZodURLParams): ZodURL;
export declare function httpUrl(params?: string | Omit<core.$ZodURLParams, "protocol" | "hostname">): ZodURL;
export interface ZodEmoji extends ZodStringFormat<"emoji"> {
_zod: core.$ZodEmojiInternals;
}
export declare const ZodEmoji: core.$constructor<ZodEmoji>;
export declare function emoji(params?: string | core.$ZodEmojiParams): ZodEmoji;
export interface ZodNanoID extends ZodStringFormat<"nanoid"> {
_zod: core.$ZodNanoIDInternals;
}
export declare const ZodNanoID: core.$constructor<ZodNanoID>;
export declare function nanoid(params?: string | core.$ZodNanoIDParams): ZodNanoID;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export interface ZodCUID extends ZodStringFormat<"cuid"> {
_zod: core.$ZodCUIDInternals;
}
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare const ZodCUID: core.$constructor<ZodCUID>;
/**
* Validates a CUID v1 string.
*
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare function cuid(params?: string | core.$ZodCUIDParams): ZodCUID;
export interface ZodCUID2 extends ZodStringFormat<"cuid2"> {
_zod: core.$ZodCUID2Internals;
}
export declare const ZodCUID2: core.$constructor<ZodCUID2>;
export declare function cuid2(params?: string | core.$ZodCUID2Params): ZodCUID2;
export interface ZodULID extends ZodStringFormat<"ulid"> {
_zod: core.$ZodULIDInternals;
}
export declare const ZodULID: core.$constructor<ZodULID>;
export declare function ulid(params?: string | core.$ZodULIDParams): ZodULID;
export interface ZodXID extends ZodStringFormat<"xid"> {
_zod: core.$ZodXIDInternals;
}
export declare const ZodXID: core.$constructor<ZodXID>;
export declare function xid(params?: string | core.$ZodXIDParams): ZodXID;
export interface ZodKSUID extends ZodStringFormat<"ksuid"> {
_zod: core.$ZodKSUIDInternals;
}
export declare const ZodKSUID: core.$constructor<ZodKSUID>;
export declare function ksuid(params?: string | core.$ZodKSUIDParams): ZodKSUID;
export interface ZodIPv4 extends ZodStringFormat<"ipv4"> {
_zod: core.$ZodIPv4Internals;
}
export declare const ZodIPv4: core.$constructor<ZodIPv4>;
export declare function ipv4(params?: string | core.$ZodIPv4Params): ZodIPv4;
export interface ZodMAC extends ZodStringFormat<"mac"> {
_zod: core.$ZodMACInternals;
}
export declare const ZodMAC: core.$constructor<ZodMAC>;
export declare function mac(params?: string | core.$ZodMACParams): ZodMAC;
export interface ZodIPv6 extends ZodStringFormat<"ipv6"> {
_zod: core.$ZodIPv6Internals;
}
export declare const ZodIPv6: core.$constructor<ZodIPv6>;
export declare function ipv6(params?: string | core.$ZodIPv6Params): ZodIPv6;
export interface ZodCIDRv4 extends ZodStringFormat<"cidrv4"> {
_zod: core.$ZodCIDRv4Internals;
}
export declare const ZodCIDRv4: core.$constructor<ZodCIDRv4>;
export declare function cidrv4(params?: string | core.$ZodCIDRv4Params): ZodCIDRv4;
export interface ZodCIDRv6 extends ZodStringFormat<"cidrv6"> {
_zod: core.$ZodCIDRv6Internals;
}
export declare const ZodCIDRv6: core.$constructor<ZodCIDRv6>;
export declare function cidrv6(params?: string | core.$ZodCIDRv6Params): ZodCIDRv6;
export interface ZodBase64 extends ZodStringFormat<"base64"> {
_zod: core.$ZodBase64Internals;
}
export declare const ZodBase64: core.$constructor<ZodBase64>;
export declare function base64(params?: string | core.$ZodBase64Params): ZodBase64;
export interface ZodBase64URL extends ZodStringFormat<"base64url"> {
_zod: core.$ZodBase64URLInternals;
}
export declare const ZodBase64URL: core.$constructor<ZodBase64URL>;
export declare function base64url(params?: string | core.$ZodBase64URLParams): ZodBase64URL;
export interface ZodE164 extends ZodStringFormat<"e164"> {
_zod: core.$ZodE164Internals;
}
export declare const ZodE164: core.$constructor<ZodE164>;
export declare function e164(params?: string | core.$ZodE164Params): ZodE164;
export interface ZodCreditCard extends ZodStringFormat<"credit_card"> {
_zod: core.$ZodCreditCardInternals;
}
export declare const ZodCreditCard: core.$constructor<ZodCreditCard>;
export declare function creditCard(params?: string | core.$ZodCreditCardParams): ZodCreditCard;
export interface ZodIBAN extends ZodStringFormat<"iban"> {
_zod: core.$ZodIBANInternals;
}
export declare const ZodIBAN: core.$constructor<ZodIBAN>;
export declare function iban(params?: string | core.$ZodIBANParams): ZodIBAN;
export interface ZodJWT extends ZodStringFormat<"jwt"> {
_zod: core.$ZodJWTInternals;
}
export declare const ZodJWT: core.$constructor<ZodJWT>;
export declare function jwt(params?: string | core.$ZodJWTParams): ZodJWT;
export interface ZodCustomStringFormat<Format extends string = string> extends ZodStringFormat<Format>, core.$ZodCustomStringFormat<Format> {
_zod: core.$ZodCustomStringFormatInternals<Format>;
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodCustomStringFormat: core.$constructor<ZodCustomStringFormat>;
export declare function stringFormat<Format extends string>(format: Format, fnOrRegex: ((arg: string) => util.MaybeAsync<unknown>) | RegExp, _params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<Format>;
export declare function hostname(_params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"hostname">;
export declare function hex(_params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"hex">;
export declare function currencyCode(_params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"currency_code">;
export declare function hash<Alg extends util.HashAlgorithm, Enc extends util.HashEncoding = "hex">(alg: Alg, params?: {
enc?: Enc;
} & core.$ZodStringFormatParams): ZodCustomStringFormat<`${Alg}_${Enc}`>;
export interface _ZodNumber<Internals extends core.$ZodNumberInternals = core.$ZodNumberInternals> extends _ZodType<Internals> {
gt(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
/** Identical to .min() */
gte(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
min(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
lt(value: number, params?: string | core.$ZodCheckLessThanParams): this;
/** Identical to .max() */
lte(value: number, params?: string | core.$ZodCheckLessThanParams): this;
max(value: number, params?: string | core.$ZodCheckLessThanParams): this;
/** Consider `z.int()` instead. This API is considered *legacy*; it will never be removed but a better alternative exists. */
int(params?: string | core.$ZodCheckNumberFormatParams): this;
/** @deprecated This is now identical to `.int()`. Only numbers in the safe integer range are accepted. */
safe(params?: string | core.$ZodCheckNumberFormatParams): this;
positive(params?: string | core.$ZodCheckGreaterThanParams): this;
nonnegative(params?: string | core.$ZodCheckGreaterThanParams): this;
negative(params?: string | core.$ZodCheckLessThanParams): this;
nonpositive(params?: string | core.$ZodCheckLessThanParams): this;
multipleOf(value: number, params?: string | core.$ZodCheckMultipleOfParams): this;
/** @deprecated Use `.multipleOf()` instead. */
step(value: number, params?: string | core.$ZodCheckMultipleOfParams): this;
/** @deprecated In v4 and later, z.number() does not allow infinite values by default. This is a no-op. */
finite(params?: unknown): this;
minValue: number | null;
maxValue: number | null;
/** @deprecated Check the `format` property instead. */
isInt: boolean;
/** @deprecated Number schemas no longer accept infinite values, so this always returns `true`. */
isFinite: boolean;
format: string | null;
}
export interface ZodNumber extends _ZodNumber<core.$ZodNumberInternals<number>> {
}
export declare const ZodNumber: core.$constructor<ZodNumber>;
export declare function number(params?: string | core.$ZodNumberParams): ZodNumber;
export interface ZodNumberFormat<Format extends $ZodNumberFormats = $ZodNumberFormats> extends ZodNumber {
_zod: core.$ZodNumberFormatInternals<Format>;
}
export declare const ZodNumberFormat: core.$constructor<ZodNumberFormat>;
export interface ZodInt extends ZodNumberFormat<"safeint"> {
}
export declare function int(params?: string | core.$ZodCheckNumberFormatParams): ZodInt;
export interface ZodFloat32 extends ZodNumberFormat<"float32"> {
}
export declare function float32(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat32;
export interface ZodFloat64 extends ZodNumberFormat<"float64"> {
}
export declare function float64(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat64;
export interface ZodInt32 extends ZodNumberFormat<"int32"> {
}
export declare function int32(params?: string | core.$ZodCheckNumberFormatParams): ZodInt32;
export interface ZodUInt32 extends ZodNumberFormat<"uint32"> {
}
export declare function uint32(params?: string | core.$ZodCheckNumberFormatParams): ZodUInt32;
export interface _ZodBoolean<T extends core.$ZodBooleanInternals = core.$ZodBooleanInternals> extends _ZodType<T> {
}
export interface ZodBoolean extends _ZodBoolean<core.$ZodBooleanInternals<boolean>> {
}
export declare const ZodBoolean: core.$constructor<ZodBoolean>;
export declare function boolean(params?: string | core.$ZodBooleanParams): ZodBoolean;
export interface _ZodBigInt<T extends core.$ZodBigIntInternals = core.$ZodBigIntInternals> extends _ZodType<T> {
gte(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
/** Alias of `.gte()` */
min(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
gt(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
/** Alias of `.lte()` */
lte(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
max(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
lt(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
positive(params?: string | core.$ZodCheckGreaterThanParams): this;
negative(params?: string | core.$ZodCheckLessThanParams): this;
nonpositive(params?: string | core.$ZodCheckLessThanParams): this;
nonnegative(params?: string | core.$ZodCheckGreaterThanParams): this;
multipleOf(value: bigint, params?: string | core.$ZodCheckMultipleOfParams): this;
minValue: bigint | null;
maxValue: bigint | null;
format: string | null;
}
export interface ZodBigInt extends _ZodBigInt<core.$ZodBigIntInternals<bigint>> {
}
export declare const ZodBigInt: core.$constructor<ZodBigInt>;
export declare function bigint(params?: string | core.$ZodBigIntParams): ZodBigInt;
export interface ZodBigIntFormat<Format extends $ZodBigIntFormats = $ZodBigIntFormats> extends ZodBigInt {
_zod: core.$ZodBigIntFormatInternals<Format>;
}
export declare const ZodBigIntFormat: core.$constructor<ZodBigIntFormat>;
export interface ZodInt64 extends ZodBigIntFormat<"int64"> {
}
export declare function int64(params?: string | core.$ZodBigIntFormatParams): ZodInt64;
export interface ZodUInt64 extends ZodBigIntFormat<"uint64"> {
}
export declare function uint64(params?: string | core.$ZodBigIntFormatParams): ZodUInt64;
export interface ZodSymbol extends _ZodType<core.$ZodSymbolInternals> {
}
export declare const ZodSymbol: core.$constructor<ZodSymbol>;
export declare function symbol(params?: string | core.$ZodSymbolParams): ZodSymbol;
export interface ZodUndefined extends _ZodType<core.$ZodUndefinedInternals> {
}
export declare const ZodUndefined: core.$constructor<ZodUndefined>;
declare function _undefined(params?: string | core.$ZodUndefinedParams): ZodUndefined;
export { _undefined as undefined };
export interface ZodNull extends _ZodType<core.$ZodNullInternals> {
}
export declare const ZodNull: core.$constructor<ZodNull>;
declare function _null(params?: string | core.$ZodNullParams): ZodNull;
export { _null as null };
export interface ZodAny extends _ZodType<core.$ZodAnyInternals> {
}
export declare const ZodAny: core.$constructor<ZodAny>;
export declare function any(): ZodAny;
export interface ZodUnknown extends _ZodType<core.$ZodUnknownInternals> {
}
export declare const ZodUnknown: core.$constructor<ZodUnknown>;
export declare function unknown(): ZodUnknown;
export interface ZodNever extends _ZodType<core.$ZodNeverInternals> {
}
export declare const ZodNever: core.$constructor<ZodNever>;
export declare function never(params?: string | core.$ZodNeverParams): ZodNever;
export interface ZodVoid extends _ZodType<core.$ZodVoidInternals> {
}
export declare const ZodVoid: core.$constructor<ZodVoid>;
declare function _void(params?: string | core.$ZodVoidParams): ZodVoid;
export { _void as void };
export interface _ZodDate<T extends core.$ZodDateInternals = core.$ZodDateInternals> extends _ZodType<T> {
min(value: number | Date, params?: string | core.$ZodCheckGreaterThanParams): this;
max(value: number | Date, params?: string | core.$ZodCheckLessThanParams): this;
/** @deprecated Not recommended. */
minDate: Date | null;
/** @deprecated Not recommended. */
maxDate: Date | null;
}
export interface ZodDate extends _ZodDate<core.$ZodDateInternals<Date>> {
}
export declare const ZodDate: core.$constructor<ZodDate>;
export declare function date(params?: string | core.$ZodDateParams): ZodDate;
export interface ZodArray<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodArrayInternals<T>>, core.$ZodArray<T> {
element: T;
min(minLength: number, params?: string | core.$ZodCheckMinLengthParams): this;
nonempty(params?: string | core.$ZodCheckMinLengthParams): this;
max(maxLength: number, params?: string | core.$ZodCheckMaxLengthParams): this;
length(len: number, params?: string | core.$ZodCheckLengthEqualsParams): this;
unwrap(): T;
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodArray: core.$constructor<ZodArray>;
export declare function array<T extends core.SomeType>(element: T, params?: string | core.$ZodArrayParams): ZodArray<T>;
export declare function keyof<T extends ZodObject>(schema: T): ZodEnum<util.KeysEnum<T["_zod"]["output"]>>;
export type SafeExtendShape<Base extends core.$ZodShape, Ext extends core.$ZodLooseShape> = {
[K in keyof Ext]: K extends keyof Base ? core.output<Ext[K]> extends core.output<Base[K]> ? core.input<Ext[K]> extends core.input<Base[K]> ? Ext[K] : never : never : Ext[K];
};
export interface ZodObject<
/** @ts-ignore Cast variance */
out Shape extends core.$ZodShape = core.$ZodLooseShape, out Config extends core.$ZodObjectConfig = core.$strip> extends _ZodType<core.$ZodObjectInternals<Shape, Config>>, core.$ZodObject<Shape, Config> {
"~standard": ZodStandardSchemaWithJSON<this>;
shape: Shape;
keyof(): ZodEnum<util.ToEnum<keyof Shape & string>>;
/** Define a schema to validate all unrecognized keys. This overrides the existing strict/loose behavior. */
catchall<T extends core.SomeType>(schema: T): ZodObject<Shape, core.$catchall<T>>;
/** @deprecated Use `z.looseObject()` or `.loose()` instead. */
passthrough(): ZodObject<Shape, core.$loose>;
/** Consider `z.looseObject(A.shape)` instead */
loose(): ZodObject<Shape, core.$loose>;
/** Consider `z.strictObject(A.shape)` instead */
strict(): ZodObject<Shape, core.$strict>;
/** This is the default behavior. This method call is likely unnecessary. */
strip(): ZodObject<Shape, core.$strip>;
extend<U extends core.$ZodLooseShape>(shape: U): ZodObject<util.Extend<Shape, util.Writeable<U>>, Config>;
safeExtend<U extends core.$ZodLooseShape>(shape: SafeExtendShape<Shape, U> & Partial<Record<keyof Shape, core.SomeType>>): ZodObject<util.Extend<Shape, util.Writeable<U>>, Config>;
/**
* @deprecated Use [`A.extend(B.shape)`](https://zod.dev/api?id=extend) instead.
*/
merge<U extends ZodObject>(other: U): ZodObject<util.Extend<Shape, U["shape"]>, U["_zod"]["config"]>;
pick<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<util.Flatten<Pick<Shape, Extract<keyof Shape, keyof M>>>, Config>;
omit<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<util.Flatten<Omit<Shape, Extract<keyof Shape, keyof M>>>, Config>;
partial(): ZodObject<{
-readonly [k in keyof Shape]: ZodOptional<Shape[k]>;
}, Config>;
partial<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
-readonly [k in keyof Shape]: k extends keyof M ? ZodOptional<Shape[k]> : Shape[k];
}, Config>;
exactPartial(): ZodObject<{
-readonly [k in keyof Shape]: ZodExactOptional<Shape[k]>;
}, Config>;
exactPartial<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
-readonly [k in keyof Shape]: k extends keyof M ? ZodExactOptional<Shape[k]> : Shape[k];
}, Config>;
required(): ZodObject<{
-readonly [k in keyof Shape]: ZodNonOptional<Shape[k]>;
}, Config>;
required<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
-readonly [k in keyof Shape]: k extends keyof M ? ZodNonOptional<Shape[k]> : Shape[k];
}, Config>;
}
export declare const ZodObject: core.$constructor<ZodObject>;
export declare function object<T extends core.$ZodLooseShape = Partial<Record<never, core.SomeType>>>(shape?: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$strip>;
export declare function strictObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$strict>;
export declare function looseObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$loose>;
export interface ZodUnion<T extends readonly core.SomeType[] = readonly core.$ZodType[]> extends _ZodType<core.$ZodUnionInternals<T>>, core.$ZodUnion<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
options: T;
}
export declare const ZodUnion: core.$constructor<ZodUnion>;
export declare function union<const T extends readonly core.SomeType[]>(options: T, params?: string | core.$ZodUnionParams): ZodUnion<T>;
export interface ZodXor<T extends readonly core.SomeType[] = readonly core.$ZodType[]> extends _ZodType<core.$ZodXorInternals<T>>, core.$ZodXor<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
options: T;
}
export declare const ZodXor: core.$constructor<ZodXor>;
/** Creates an exclusive union (XOR) where exactly one option must match.
* Unlike regular unions that succeed when any option matches, xor fails if
* zero or more than one option matches the input. */
export declare function xor<const T extends readonly core.SomeType[]>(options: T, params?: string | core.$ZodXorParams): ZodXor<T>;
export interface ZodDiscriminatedUnion<Options extends readonly core.SomeType[] = readonly core.$ZodType[], Disc extends string = string> extends ZodUnion<Options>, core.$ZodDiscriminatedUnion<Options, Disc> {
"~standard": ZodStandardSchemaWithJSON<this>;
_zod: core.$ZodDiscriminatedUnionInternals<Options, Disc>;
def: core.$ZodDiscriminatedUnionDef<Options, Disc>;
}
export declare const ZodDiscriminatedUnion: core.$constructor<ZodDiscriminatedUnion>;
export declare function discriminatedUnion<Types extends readonly [core.$ZodTypeDiscriminable, ...core.$ZodTypeDiscriminable[]], Disc extends string>(discriminator: Disc, options: Types, params?: string | core.$ZodDiscriminatedUnionParams): ZodDiscriminatedUnion<Types, Disc>;
export interface ZodIntersection<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodIntersectionInternals<A, B>>, core.$ZodIntersection<A, B> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodIntersection: core.$constructor<ZodIntersection>;
export declare function intersection<T extends core.SomeType, U extends core.SomeType>(left: T, right: U): ZodIntersection<T, U>;
export interface ZodTuple<T extends util.TupleItems = readonly core.$ZodType[], Rest extends core.SomeType | null = core.$ZodType | null> extends _ZodType<core.$ZodTupleInternals<T, Rest>>, core.$ZodTuple<T, Rest> {
"~standard": ZodStandardSchemaWithJSON<this>;
rest<Rest extends core.SomeType = core.$ZodType>(rest: Rest): ZodTuple<T, Rest>;
partial(): ZodTuple<{
-readonly [k in keyof T]: ZodOptional<T[k]>;
}, Rest>;
}
export declare const ZodTuple: core.$constructor<ZodTuple>;
export declare function tuple<T extends readonly [core.SomeType, ...core.SomeType[]]>(items: T, params?: string | core.$ZodTupleParams): ZodTuple<T, null>;
export declare function tuple<T extends readonly [core.SomeType, ...core.SomeType[]], Rest extends core.SomeType>(items: T, rest: Rest, params?: string | core.$ZodTupleParams): ZodTuple<T, Rest>;
export declare function tuple(items: [], params?: string | core.$ZodTupleParams): ZodTuple<[], null>;
export interface ZodRecord<Key extends core.$ZodRecordKey = core.$ZodRecordKey, Value extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodRecordInternals<Key, Value>>, core.$ZodRecord<Key, Value> {
"~standard": ZodStandardSchemaWithJSON<this>;
keyType: Key;
valueType: Value;
}
export declare const ZodRecord: core.$constructor<ZodRecord>;
export declare function record<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key, Value>;
export declare function partialRecord<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key & core.$partial, Value>;
export declare function looseRecord<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key, Value>;
export interface ZodMap<Key extends core.SomeType = core.$ZodType, Value extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodMapInternals<Key, Value>>, core.$ZodMap<Key, Value> {
"~standard": ZodStandardSchemaWithJSON<this>;
keyType: Key;
valueType: Value;
min(minSize: number, params?: string | core.$ZodCheckMinSizeParams): this;
nonempty(params?: string | core.$ZodCheckMinSizeParams): this;
max(maxSize: number, params?: string | core.$ZodCheckMaxSizeParams): this;
size(size: number, params?: string | core.$ZodCheckSizeEqualsParams): this;
}
export declare const ZodMap: core.$constructor<ZodMap>;
export declare function map<Key extends core.SomeType, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodMapParams): ZodMap<Key, Value>;
export interface ZodSet<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodSetInternals<T>>, core.$ZodSet<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
min(minSize: number, params?: string | core.$ZodCheckMinSizeParams): this;
nonempty(params?: string | core.$ZodCheckMinSizeParams): this;
max(maxSize: number, params?: string | core.$ZodCheckMaxSizeParams): this;
size(size: number, params?: string | core.$ZodCheckSizeEqualsParams): this;
}
export declare const ZodSet: core.$constructor<ZodSet>;
export declare function set<Value extends core.SomeType>(valueType: Value, params?: string | core.$ZodSetParams): ZodSet<Value>;
export interface ZodEnum<
/** @ts-ignore Cast variance */
out T extends util.EnumLike = util.EnumLike> extends _ZodType<core.$ZodEnumInternals<T>>, core.$ZodEnum<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
enum: T;
options: Array<T[keyof T]>;
extract<const U extends readonly (keyof T)[]>(values: U, params?: string | core.$ZodEnumParams): ZodEnum<util.Flatten<Pick<T, U[number]>>>;
exclude<const U extends readonly (keyof T)[]>(values: U, params?: string | core.$ZodEnumParams): ZodEnum<util.Flatten<Omit<T, U[number]>>>;
}
export declare const ZodEnum: core.$constructor<ZodEnum>;
declare function _enum<const T extends readonly string[]>(values: T, params?: string | core.$ZodEnumParams): ZodEnum<util.ToEnum<T[number]>>;
declare function _enum<const T extends util.EnumLike>(entries: T, params?: string | core.$ZodEnumParams): ZodEnum<T>;
export { _enum as enum };
/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.
*
* ```ts
* enum Colors { red, green, blue }
* z.enum(Colors);
* ```
*/
export declare function nativeEnum<T extends util.EnumLike>(entries: T, params?: string | core.$ZodEnumParams): ZodEnum<T>;
export interface ZodLiteral<T extends util.Literal = util.Literal> extends _ZodType<core.$ZodLiteralInternals<T>>, core.$ZodLiteral<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
values: Set<T>;
/** @legacy Use `.values` instead. Accessing this property will throw an error if the literal accepts multiple values. */
value: T;
}
export declare const ZodLiteral: core.$constructor<ZodLiteral>;
export declare function literal<const T extends ReadonlyArray<util.Literal>>(value: T, params?: string | core.$ZodLiteralParams): ZodLiteral<T[number]>;
export declare function literal<const T extends util.Literal>(value: T, params?: string | core.$ZodLiteralParams): ZodLiteral<T>;
export interface ZodFile extends _ZodType<core.$ZodFileInternals>, core.$ZodFile {
"~standard": ZodStandardSchemaWithJSON<this>;
min(size: number, params?: string | core.$ZodCheckMinSizeParams): this;
max(size: number, params?: string | core.$ZodCheckMaxSizeParams): this;
mime(types: util.MimeTypes | Array<util.MimeTypes>, params?: string | core.$ZodCheckMimeTypeParams): this;
}
export declare const ZodFile: core.$constructor<ZodFile>;
export declare function file(params?: string | core.$ZodFileParams): ZodFile;
export interface ZodTransform<O = unknown, I = unknown> extends _ZodType<core.$ZodTransformInternals<O, I>>, core.$ZodTransform<O, I> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodTransform: core.$constructor<ZodTransform>;
export declare function transform<I = unknown, O = I>(fn: (input: I, ctx: core.$RefinementCtx) => O): ZodTransform<Awaited<O>, I>;
export interface ZodOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodOptionalInternals<T>>, core.$ZodOptional<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodOptional: core.$constructor<ZodOptional>;
export declare function optional<T extends core.SomeType>(innerType: T): ZodOptional<T>;
export interface ZodExactOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodExactOptionalInternals<T>>, core.$ZodExactOptional<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodExactOptional: core.$constructor<ZodExactOptional>;
export declare function exactOptional<T extends core.SomeType>(innerType: T): ZodExactOptional<T>;
export interface ZodNullable<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodNullableInternals<T>>, core.$ZodNullable<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodNullable: core.$constructor<ZodNullable>;
export declare function nullable<T extends core.SomeType>(innerType: T): ZodNullable<T>;
export declare function nullish<T extends core.SomeType>(innerType: T): ZodOptional<ZodNullable<T>>;
export interface ZodDefault<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodDefaultInternals<T>>, core.$ZodDefault<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
/** @deprecated Use `.unwrap()` instead. */
removeDefault(): T;
}
export declare const ZodDefault: core.$constructor<ZodDefault>;
export declare function _default<T extends core.SomeType>(innerType: T, defaultValue: util.NoUndefined<core.output<T>> | (() => util.NoUndefined<core.output<T>>)): ZodDefault<T>;
export interface ZodPrefault<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPrefaultInternals<T>>, core.$ZodPrefault<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodPrefault: core.$constructor<ZodPrefault>;
export declare function prefault<T extends core.SomeType>(innerType: T, defaultValue: core.input<T> | (() => core.input<T>)): ZodPrefault<T>;
export interface ZodNonOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodNonOptionalInternals<T>>, core.$ZodNonOptional<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodNonOptional: core.$constructor<ZodNonOptional>;
export declare function nonoptional<T extends core.SomeType>(innerType: T, params?: string | core.$ZodNonOptionalParams): ZodNonOptional<T>;
export interface ZodSuccess<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodSuccessInternals<T>>, core.$ZodSuccess<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodSuccess: core.$constructor<ZodSuccess>;
export declare function success<T extends core.SomeType>(innerType: T): ZodSuccess<T>;
export interface ZodCatch<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodCatchInternals<T>>, core.$ZodCatch<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
/** @deprecated Use `.unwrap()` instead. */
removeCatch(): T;
}
export declare const ZodCatch: core.$constructor<ZodCatch>;
declare function _catch<T extends core.SomeType>(innerType: T, catchValue: core.output<T> | ((ctx: core.$ZodCatchCtx) => core.output<T>)): ZodCatch<T>;
export { _catch as catch };
export interface ZodNaN extends _ZodType<core.$ZodNaNInternals>, core.$ZodNaN {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodNaN: core.$constructor<ZodNaN>;
export declare function nan(params?: string | core.$ZodNaNParams): ZodNaN;
export interface ZodPipe<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPipeInternals<A, B>>, core.$ZodPipe<A, B> {
"~standard": ZodStandardSchemaWithJSON<this>;
in: A;
out: B;
}
export declare const ZodPipe: core.$constructor<ZodPipe>;
export declare function pipe<const A extends core.SomeType, B extends core.$ZodType<unknown, core.output<A>> = core.$ZodType<unknown, core.output<A>>>(in_: A, out: B | core.$ZodType<unknown, core.output<A>>): ZodPipe<A, B>;
export interface ZodCodec<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends ZodPipe<A, B>, core.$ZodCodec<A, B> {
"~standard": ZodStandardSchemaWithJSON<this>;
_zod: core.$ZodCodecInternals<A, B>;
def: core.$ZodCodecDef<A, B>;
}
export declare const ZodCodec: core.$constructor<ZodCodec>;
export declare function codec<const A extends core.SomeType, B extends core.SomeType = core.$ZodType>(in_: A, out: B, params: {
decode: (value: core.output<A>, payload: core.ParsePayload<core.output<A>>) => core.util.MaybeAsync<core.input<B>>;
encode: (value: core.input<B>, payload: core.ParsePayload<core.input<B>>) => core.util.MaybeAsync<core.output<A>>;
}): ZodCodec<A, B>;
export declare function invertCodec<A extends core.SomeType, B extends core.SomeType>(codec: ZodCodec<A, B>): ZodCodec<B, A>;
export interface ZodPreprocess<B extends core.SomeType = core.$ZodType, I = unknown> extends ZodPipe<core.$ZodTransform<unknown, I>, B>, core.$ZodPreprocess<B, I> {
"~standard": ZodStandardSchemaWithJSON<this>;
_zod: core.$ZodPreprocessInternals<B, I>;
def: core.$ZodPreprocessDef<B, I>;
}
export declare const ZodPreprocess: core.$constructor<ZodPreprocess>;
export interface ZodReadonly<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodReadonlyInternals<T>>, core.$ZodReadonly<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodReadonly: core.$constructor<ZodReadonly>;
export declare function readonly<T extends core.SomeType>(innerType: T): ZodReadonly<T>;
export interface ZodTemplateLiteral<Template extends string = string> extends _ZodType<core.$ZodTemplateLiteralInternals<Template>>, core.$ZodTemplateLiteral<Template> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodTemplateLiteral: core.$constructor<ZodTemplateLiteral>;
export declare function templateLiteral<const Parts extends core.$ZodTemplateLiteralPart[]>(parts: Parts, params?: string | core.$ZodTemplateLiteralParams): ZodTemplateLiteral<core.$PartsToTemplateLiteral<Parts>>;
export interface ZodLazy<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodLazyInternals<T>>, core.$ZodLazy<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodLazy: core.$constructor<ZodLazy>;
export declare function lazy<T extends core.SomeType>(getter: () => T): ZodLazy<T>;
export interface ZodPromise<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPromiseInternals<T>>, core.$ZodPromise<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodPromise: core.$constructor<ZodPromise>;
export declare function promise<T extends core.SomeType>(innerType: T): ZodPromise<T>;
export interface ZodFunction<Args extends core.$ZodFunctionIn = core.$ZodFunctionIn, Returns extends core.$ZodFunctionOut = core.$ZodFunctionOut> extends _ZodType<core.$ZodFunctionInternals<Args, Returns>>, core.$ZodFunction<Args, Returns> {
"~standard": ZodStandardSchemaWithJSON<this>;
_def: core.$ZodFunctionDef<Args, Returns>;
_input: core.$InferInnerFunctionType<Args, Returns>;
_output: core.$InferOuterFunctionType<Args, Returns>;
input<const Items extends util.TupleItems, const Rest extends core.$ZodFunctionOut = core.$ZodFunctionOut>(args: Items, rest?: Rest): ZodFunction<core.$ZodTuple<Items, Rest>, Returns>;
input<NewArgs extends core.$ZodFunctionIn>(args: NewArgs): ZodFunction<NewArgs, Returns>;
input(...args: any[]): ZodFunction<any, Returns>;
output<NewReturns extends core.$ZodType>(output: NewReturns): ZodFunction<Args, NewReturns>;
}
export declare const ZodFunction: core.$constructor<ZodFunction>;
export declare function _function(): ZodFunction;
export declare function _function<const In extends ReadonlyArray<core.$ZodType>>(params: {
input: In;
}): ZodFunction<ZodTuple<In, null>, core.$ZodFunctionOut>;
export declare function _function<const In extends ReadonlyArray<core.$ZodType>, const Out extends core.$ZodFunctionOut = core.$ZodFunctionOut>(params: {
input: In;
output: Out;
}): ZodFunction<ZodTuple<In, null>, Out>;
export declare function _function<const In extends core.$ZodFunctionIn = core.$ZodFunctionIn>(params: {
input: In;
}): ZodFunction<In, core.$ZodFunctionOut>;
export declare function _function<const Out extends core.$ZodFunctionOut = core.$ZodFunctionOut>(params: {
output: Out;
}): ZodFunction<core.$ZodFunctionIn, Out>;
export declare function _function<In extends core.$ZodFunctionIn = core.$ZodFunctionIn, Out extends core.$ZodType = core.$ZodType>(params?: {
input: In;
output: Out;
}): ZodFunction<In, Out>;
export { _function as function };
export interface ZodCustom<O = unknown, I = unknown> extends _ZodType<core.$ZodCustomInternals<O, I>>, core.$ZodCustom<O, I> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodCustom: core.$constructor<ZodCustom>;
export declare function check<O = unknown>(fn: core.CheckFn<O>): core.$ZodCheck<O>;
export declare function custom<O>(fn?: (data: unknown) => unknown, _params?: string | core.$ZodCustomParams | undefined): ZodCustom<O, O>;
export declare function refine<T>(fn: (arg: NoInfer<T>) => util.MaybeAsync<unknown>, _params?: string | core.$ZodCustomParams): core.$ZodCheck<T>;
export declare function superRefine<T>(fn: (arg: T, payload: core.$RefinementCtx<T>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): core.$ZodCheck<T>;
export declare const describe: typeof core.describe;
export declare const meta: typeof core.meta;
type ZodInstanceOfParams = core.Params<ZodCustom, core.$ZodIssueCustom, "type" | "check" | "checks" | "fn" | "abort" | "error" | "params" | "path">;
export interface ZodInstanceOf<T = unknown> extends ZodCustom<T, T> {
properties<Shape extends {
[k in keyof T as T[k] extends Function ? never : k]?: core.$ZodType<unknown, T[k]>;
}>(shape: Shape, params?: string | core.$ZodCheckPropertiesParams): ZodInstanceOf<T & core.$InferObjectInput<Shape, {}>>;
}
export declare const ZodInstanceOf: core.$constructor<ZodInstanceOf>;
declare function _instanceof<T extends typeof util.Class>(cls: T, params?: ZodInstanceOfParams): ZodInstanceOf<InstanceType<T>>;
export { _instanceof as instanceof };
export declare const stringbool: (_params?: string | core.$ZodStringBoolParams) => ZodCodec<ZodString, ZodBoolean>;
type _ZodJSONSchema = ZodUnion<[
ZodString,
ZodNumber,
ZodBoolean,
ZodNull,
ZodArray<ZodJSONSchema>,
ZodRecord<ZodString, ZodJSONSchema>
]>;
type _ZodJSONSchemaInternals = _ZodJSONSchema["_zod"];
export interface ZodJSONSchemaInternals extends _ZodJSONSchemaInternals {
output: util.JSONType;
input: util.JSONType;
}
export interface ZodJSONSchema extends _ZodJSONSchema {
_zod: ZodJSONSchemaInternals;
}
export declare function json(params?: string | core.$ZodCustomParams): ZodJSONSchema;
export declare function preprocess<A, U extends core.SomeType, B = unknown>(fn: (arg: B, ctx: core.$RefinementCtx) => A, schema: U): ZodPreprocess<U, B>;
+1535
View File
File diff suppressed because it is too large Load Diff
+1269
View File
File diff suppressed because it is too large Load Diff
+335
View File
@@ -0,0 +1,335 @@
import * as checks from "./checks.cjs";
import type * as core from "./core.cjs";
import type * as errors from "./errors.cjs";
import * as registries from "./registries.cjs";
import * as schemas from "./schemas.cjs";
import * as util from "./util.cjs";
export type Params<T extends schemas.$ZodType | checks.$ZodCheck, IssueTypes extends errors.$ZodIssueBase, OmitKeys extends keyof T["_zod"]["def"] = never> = util.Flatten<Partial<util.EmptyToNever<Omit<T["_zod"]["def"], OmitKeys> & ([IssueTypes] extends [never] ? {} : {
error?: string | errors.$ZodErrorMap<IssueTypes> | undefined;
/** @deprecated This parameter is deprecated. Use `error` instead. */
message?: string | undefined;
})>>>;
export type TypeParams<T extends schemas.$ZodType = schemas.$ZodType & {
_isst: never;
}, AlsoOmit extends Exclude<keyof T["_zod"]["def"], "type" | "checks" | "error"> = never> = Params<T, NonNullable<T["_zod"]["isst"]>, "type" | "checks" | "error" | AlsoOmit>;
export type CheckParams<T extends checks.$ZodCheck = checks.$ZodCheck, // & { _issc: never },
AlsoOmit extends Exclude<keyof T["_zod"]["def"], "check" | "error"> = never> = Params<T, NonNullable<T["_zod"]["issc"]>, "check" | "error" | AlsoOmit>;
export type StringFormatParams<T extends schemas.$ZodStringFormat = schemas.$ZodStringFormat, AlsoOmit extends Exclude<keyof T["_zod"]["def"], "type" | "coerce" | "checks" | "error" | "check" | "format"> = never> = Params<T, NonNullable<T["_zod"]["isst"] | T["_zod"]["issc"]>, "type" | "coerce" | "checks" | "error" | "check" | "format" | AlsoOmit>;
export type CheckStringFormatParams<T extends schemas.$ZodStringFormat = schemas.$ZodStringFormat, AlsoOmit extends Exclude<keyof T["_zod"]["def"], "type" | "coerce" | "checks" | "error" | "check" | "format"> = never> = Params<T, NonNullable<T["_zod"]["issc"]>, "type" | "coerce" | "checks" | "error" | "check" | "format" | AlsoOmit>;
export type CheckTypeParams<T extends schemas.$ZodType & checks.$ZodCheck = schemas.$ZodType & checks.$ZodCheck, AlsoOmit extends Exclude<keyof T["_zod"]["def"], "type" | "checks" | "error" | "check"> = never> = Params<T, NonNullable<T["_zod"]["isst"] | T["_zod"]["issc"]>, "type" | "checks" | "error" | "check" | AlsoOmit>;
export type $ZodStringParams = TypeParams<schemas.$ZodString<string>, "coerce"> & {
checks?: readonly checks.$ZodCheck<string>[];
};
export declare function _string<T extends schemas.$ZodString>(Class: util.SchemaClass<T>, params?: string | $ZodStringParams): T;
export declare function _coercedString<T extends schemas.$ZodString>(Class: util.SchemaClass<T>, params?: string | $ZodStringParams): T;
export type $ZodStringFormatParams = CheckTypeParams<schemas.$ZodStringFormat, "format" | "coerce" | "when" | "pattern">;
export type $ZodCheckStringFormatParams = CheckParams<checks.$ZodCheckStringFormat, "format">;
export type $ZodEmailParams = StringFormatParams<schemas.$ZodEmail, "when">;
export type $ZodCheckEmailParams = CheckStringFormatParams<schemas.$ZodEmail, "when">;
export declare function _email<T extends schemas.$ZodEmail>(Class: util.SchemaClass<T>, params?: string | $ZodEmailParams | $ZodCheckEmailParams): T;
export type $ZodGUIDParams = StringFormatParams<schemas.$ZodGUID, "pattern" | "when">;
export type $ZodCheckGUIDParams = CheckStringFormatParams<schemas.$ZodGUID, "pattern" | "when">;
export declare function _guid<T extends schemas.$ZodGUID>(Class: util.SchemaClass<T>, params?: string | $ZodGUIDParams | $ZodCheckGUIDParams): T;
export type $ZodUUIDParams = StringFormatParams<schemas.$ZodUUID, "pattern" | "when">;
export type $ZodCheckUUIDParams = CheckStringFormatParams<schemas.$ZodUUID, "pattern" | "when">;
export declare function _uuid<T extends schemas.$ZodUUID>(Class: util.SchemaClass<T>, params?: string | $ZodUUIDParams | $ZodCheckUUIDParams): T;
export type $ZodUUIDv4Params = StringFormatParams<schemas.$ZodUUID, "pattern" | "when">;
export type $ZodCheckUUIDv4Params = CheckStringFormatParams<schemas.$ZodUUID, "pattern" | "when">;
export declare function _uuidv4<T extends schemas.$ZodUUID>(Class: util.SchemaClass<T>, params?: string | $ZodUUIDv4Params | $ZodCheckUUIDv4Params): T;
export type $ZodUUIDv6Params = StringFormatParams<schemas.$ZodUUID, "pattern" | "when">;
export type $ZodCheckUUIDv6Params = CheckStringFormatParams<schemas.$ZodUUID, "pattern" | "when">;
export declare function _uuidv6<T extends schemas.$ZodUUID>(Class: util.SchemaClass<T>, params?: string | $ZodUUIDv6Params | $ZodCheckUUIDv6Params): T;
export type $ZodUUIDv7Params = StringFormatParams<schemas.$ZodUUID, "pattern" | "when">;
export type $ZodCheckUUIDv7Params = CheckStringFormatParams<schemas.$ZodUUID, "pattern" | "when">;
export declare function _uuidv7<T extends schemas.$ZodUUID>(Class: util.SchemaClass<T>, params?: string | $ZodUUIDv7Params | $ZodCheckUUIDv7Params): T;
export type $ZodURLParams = StringFormatParams<schemas.$ZodURL, "when">;
export type $ZodCheckURLParams = CheckStringFormatParams<schemas.$ZodURL, "when">;
export declare function _url<T extends schemas.$ZodURL>(Class: util.SchemaClass<T>, params?: string | $ZodURLParams | $ZodCheckURLParams): T;
export type $ZodEmojiParams = StringFormatParams<schemas.$ZodEmoji, "when">;
export type $ZodCheckEmojiParams = CheckStringFormatParams<schemas.$ZodEmoji, "when">;
export declare function _emoji<T extends schemas.$ZodEmoji>(Class: util.SchemaClass<T>, params?: string | $ZodEmojiParams | $ZodCheckEmojiParams): T;
export type $ZodNanoIDParams = StringFormatParams<schemas.$ZodNanoID, "when" | "pattern">;
export type $ZodCheckNanoIDParams = CheckStringFormatParams<schemas.$ZodNanoID, "when" | "pattern">;
export declare function _nanoid<T extends schemas.$ZodNanoID>(Class: util.SchemaClass<T>, params?: string | $ZodNanoIDParams | $ZodCheckNanoIDParams): T;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link _cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export type $ZodCUIDParams = StringFormatParams<schemas.$ZodCUID, "when">;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link _cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export type $ZodCheckCUIDParams = CheckStringFormatParams<schemas.$ZodCUID, "when">;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link _cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare function _cuid<T extends schemas.$ZodCUID>(Class: util.SchemaClass<T>, params?: string | $ZodCUIDParams | $ZodCheckCUIDParams): T;
export type $ZodCUID2Params = StringFormatParams<schemas.$ZodCUID2, "when">;
export type $ZodCheckCUID2Params = CheckStringFormatParams<schemas.$ZodCUID2, "when">;
export declare function _cuid2<T extends schemas.$ZodCUID2>(Class: util.SchemaClass<T>, params?: string | $ZodCUID2Params | $ZodCheckCUID2Params): T;
export type $ZodULIDParams = StringFormatParams<schemas.$ZodULID, "when">;
export type $ZodCheckULIDParams = CheckStringFormatParams<schemas.$ZodULID, "when">;
export declare function _ulid<T extends schemas.$ZodULID>(Class: util.SchemaClass<T>, params?: string | $ZodULIDParams | $ZodCheckULIDParams): T;
export type $ZodXIDParams = StringFormatParams<schemas.$ZodXID, "when">;
export type $ZodCheckXIDParams = CheckStringFormatParams<schemas.$ZodXID, "when">;
export declare function _xid<T extends schemas.$ZodXID>(Class: util.SchemaClass<T>, params?: string | $ZodXIDParams | $ZodCheckXIDParams): T;
export type $ZodKSUIDParams = StringFormatParams<schemas.$ZodKSUID, "when">;
export type $ZodCheckKSUIDParams = CheckStringFormatParams<schemas.$ZodKSUID, "when">;
export declare function _ksuid<T extends schemas.$ZodKSUID>(Class: util.SchemaClass<T>, params?: string | $ZodKSUIDParams | $ZodCheckKSUIDParams): T;
export type $ZodIPv4Params = StringFormatParams<schemas.$ZodIPv4, "pattern" | "when" | "version">;
export type $ZodCheckIPv4Params = CheckStringFormatParams<schemas.$ZodIPv4, "pattern" | "when" | "version">;
export declare function _ipv4<T extends schemas.$ZodIPv4>(Class: util.SchemaClass<T>, params?: string | $ZodIPv4Params | $ZodCheckIPv4Params): T;
export type $ZodIPv6Params = StringFormatParams<schemas.$ZodIPv6, "pattern" | "when" | "version">;
export type $ZodCheckIPv6Params = CheckStringFormatParams<schemas.$ZodIPv6, "pattern" | "when" | "version">;
export declare function _ipv6<T extends schemas.$ZodIPv6>(Class: util.SchemaClass<T>, params?: string | $ZodIPv6Params | $ZodCheckIPv6Params): T;
export type $ZodMACParams = StringFormatParams<schemas.$ZodMAC, "pattern" | "when">;
export type $ZodCheckMACParams = CheckStringFormatParams<schemas.$ZodMAC, "pattern" | "when">;
export declare function _mac<T extends schemas.$ZodMAC>(Class: util.SchemaClass<T>, params?: string | $ZodMACParams | $ZodCheckMACParams): T;
export type $ZodCIDRv4Params = StringFormatParams<schemas.$ZodCIDRv4, "pattern" | "when">;
export type $ZodCheckCIDRv4Params = CheckStringFormatParams<schemas.$ZodCIDRv4, "pattern" | "when">;
export declare function _cidrv4<T extends schemas.$ZodCIDRv4>(Class: util.SchemaClass<T>, params?: string | $ZodCIDRv4Params | $ZodCheckCIDRv4Params): T;
export type $ZodCIDRv6Params = StringFormatParams<schemas.$ZodCIDRv6, "pattern" | "when">;
export type $ZodCheckCIDRv6Params = CheckStringFormatParams<schemas.$ZodCIDRv6, "pattern" | "when">;
export declare function _cidrv6<T extends schemas.$ZodCIDRv6>(Class: util.SchemaClass<T>, params?: string | $ZodCIDRv6Params | $ZodCheckCIDRv6Params): T;
export type $ZodBase64Params = StringFormatParams<schemas.$ZodBase64, "pattern" | "when">;
export type $ZodCheckBase64Params = CheckStringFormatParams<schemas.$ZodBase64, "pattern" | "when">;
export declare function _base64<T extends schemas.$ZodBase64>(Class: util.SchemaClass<T>, params?: string | $ZodBase64Params | $ZodCheckBase64Params): T;
export type $ZodBase64URLParams = StringFormatParams<schemas.$ZodBase64URL, "pattern" | "when">;
export type $ZodCheckBase64URLParams = CheckStringFormatParams<schemas.$ZodBase64URL, "pattern" | "when">;
export declare function _base64url<T extends schemas.$ZodBase64URL>(Class: util.SchemaClass<T>, params?: string | $ZodBase64URLParams | $ZodCheckBase64URLParams): T;
export type $ZodE164Params = StringFormatParams<schemas.$ZodE164, "when">;
export type $ZodCheckE164Params = CheckStringFormatParams<schemas.$ZodE164, "when">;
export declare function _e164<T extends schemas.$ZodE164>(Class: util.SchemaClass<T>, params?: string | $ZodE164Params | $ZodCheckE164Params): T;
export type $ZodCreditCardParams = StringFormatParams<schemas.$ZodCreditCard, "pattern" | "when">;
export type $ZodCheckCreditCardParams = CheckStringFormatParams<schemas.$ZodCreditCard, "pattern" | "when">;
export declare function _creditCard<T extends schemas.$ZodCreditCard>(Class: util.SchemaClass<T>, params?: string | $ZodCreditCardParams | $ZodCheckCreditCardParams): T;
export type $ZodIBANParams = StringFormatParams<schemas.$ZodIBAN, "pattern" | "when">;
export type $ZodCheckIBANParams = CheckStringFormatParams<schemas.$ZodIBAN, "pattern" | "when">;
export declare function _iban<T extends schemas.$ZodIBAN>(Class: util.SchemaClass<T>, params?: string | $ZodIBANParams | $ZodCheckIBANParams): T;
export type $ZodJWTParams = StringFormatParams<schemas.$ZodJWT, "pattern" | "when">;
export type $ZodCheckJWTParams = CheckStringFormatParams<schemas.$ZodJWT, "pattern" | "when">;
export declare function _jwt<T extends schemas.$ZodJWT>(Class: util.SchemaClass<T>, params?: string | $ZodJWTParams | $ZodCheckJWTParams): T;
export declare const TimePrecision: {
readonly Any: null;
readonly Minute: -1;
readonly Second: 0;
readonly Millisecond: 3;
readonly Microsecond: 6;
};
export type $ZodISODateTimeParams = StringFormatParams<schemas.$ZodISODateTime, "pattern" | "when">;
export type $ZodCheckISODateTimeParams = CheckStringFormatParams<schemas.$ZodISODateTime, "pattern" | "when">;
export declare function _isoDateTime<T extends schemas.$ZodISODateTime>(Class: util.SchemaClass<T>, params?: string | $ZodISODateTimeParams | $ZodCheckISODateTimeParams): T;
export type $ZodISODateParams = StringFormatParams<schemas.$ZodISODate, "pattern" | "when">;
export type $ZodCheckISODateParams = CheckStringFormatParams<schemas.$ZodISODate, "pattern" | "when">;
export declare function _isoDate<T extends schemas.$ZodISODate>(Class: util.SchemaClass<T>, params?: string | $ZodISODateParams | $ZodCheckISODateParams): T;
export type $ZodISOTimeParams = StringFormatParams<schemas.$ZodISOTime, "pattern" | "when">;
export type $ZodCheckISOTimeParams = CheckStringFormatParams<schemas.$ZodISOTime, "pattern" | "when">;
export declare function _isoTime<T extends schemas.$ZodISOTime>(Class: util.SchemaClass<T>, params?: string | $ZodISOTimeParams | $ZodCheckISOTimeParams): T;
export type $ZodISODurationParams = StringFormatParams<schemas.$ZodISODuration, "when">;
export type $ZodCheckISODurationParams = CheckStringFormatParams<schemas.$ZodISODuration, "when">;
export declare function _isoDuration<T extends schemas.$ZodISODuration>(Class: util.SchemaClass<T>, params?: string | $ZodISODurationParams | $ZodCheckISODurationParams): T;
export type $ZodNumberParams = TypeParams<schemas.$ZodNumber<number>, "coerce"> & {
checks?: readonly checks.$ZodCheck<number>[];
};
export type $ZodNumberFormatParams = CheckTypeParams<schemas.$ZodNumberFormat, "format" | "coerce">;
export type $ZodCheckNumberFormatParams = CheckParams<checks.$ZodCheckNumberFormat, "format" | "when">;
export declare function _number<T extends schemas.$ZodNumber>(Class: util.SchemaClass<T>, params?: string | $ZodNumberParams): T;
export declare function _coercedNumber<T extends schemas.$ZodNumber>(Class: util.SchemaClass<T>, params?: string | $ZodNumberParams): T;
export declare function _int<T extends schemas.$ZodNumberFormat>(Class: util.SchemaClass<T>, params?: string | $ZodCheckNumberFormatParams): T;
export declare function _float32<T extends schemas.$ZodNumberFormat>(Class: util.SchemaClass<T>, params?: string | $ZodCheckNumberFormatParams): T;
export declare function _float64<T extends schemas.$ZodNumberFormat>(Class: util.SchemaClass<T>, params?: string | $ZodCheckNumberFormatParams): T;
export declare function _int32<T extends schemas.$ZodNumberFormat>(Class: util.SchemaClass<T>, params?: string | $ZodCheckNumberFormatParams): T;
export declare function _uint32<T extends schemas.$ZodNumberFormat>(Class: util.SchemaClass<T>, params?: string | $ZodCheckNumberFormatParams): T;
export type $ZodBooleanParams = TypeParams<schemas.$ZodBoolean<boolean>, "coerce">;
export declare function _boolean<T extends schemas.$ZodBoolean>(Class: util.SchemaClass<T>, params?: string | $ZodBooleanParams): T;
export declare function _coercedBoolean<T extends schemas.$ZodBoolean>(Class: util.SchemaClass<T>, params?: string | $ZodBooleanParams): T;
export type $ZodBigIntParams = TypeParams<schemas.$ZodBigInt<bigint>>;
export type $ZodBigIntFormatParams = CheckTypeParams<schemas.$ZodBigIntFormat, "format" | "coerce">;
export type $ZodCheckBigIntFormatParams = CheckParams<checks.$ZodCheckBigIntFormat, "format" | "when">;
export declare function _bigint<T extends schemas.$ZodBigInt>(Class: util.SchemaClass<T>, params?: string | $ZodBigIntParams): T;
export declare function _coercedBigint<T extends schemas.$ZodBigInt>(Class: util.SchemaClass<T>, params?: string | $ZodBigIntParams): T;
export declare function _int64<T extends schemas.$ZodBigIntFormat>(Class: util.SchemaClass<T>, params?: string | $ZodBigIntFormatParams): T;
export declare function _uint64<T extends schemas.$ZodBigIntFormat>(Class: util.SchemaClass<T>, params?: string | $ZodBigIntFormatParams): T;
export type $ZodSymbolParams = TypeParams<schemas.$ZodSymbol>;
export declare function _symbol<T extends schemas.$ZodSymbol>(Class: util.SchemaClass<T>, params?: string | $ZodSymbolParams): T;
export type $ZodUndefinedParams = TypeParams<schemas.$ZodUndefined>;
export declare function _undefined<T extends schemas.$ZodUndefined>(Class: util.SchemaClass<T>, params?: string | $ZodUndefinedParams): T;
export type $ZodNullParams = TypeParams<schemas.$ZodNull>;
export declare function _null<T extends schemas.$ZodNull>(Class: util.SchemaClass<T>, params?: string | $ZodNullParams): T;
export type $ZodAnyParams = TypeParams<schemas.$ZodAny>;
export declare function _any<T extends schemas.$ZodAny>(Class: util.SchemaClass<T>): T;
export type $ZodUnknownParams = TypeParams<schemas.$ZodUnknown>;
export declare function _unknown<T extends schemas.$ZodUnknown>(Class: util.SchemaClass<T>): T;
export type $ZodNeverParams = TypeParams<schemas.$ZodNever>;
export declare function _never<T extends schemas.$ZodNever>(Class: util.SchemaClass<T>, params?: string | $ZodNeverParams): T;
export type $ZodVoidParams = TypeParams<schemas.$ZodVoid>;
export declare function _void<T extends schemas.$ZodVoid>(Class: util.SchemaClass<T>, params?: string | $ZodVoidParams): T;
export type $ZodDateParams = TypeParams<schemas.$ZodDate, "coerce">;
export declare function _date<T extends schemas.$ZodDate>(Class: util.SchemaClass<T>, params?: string | $ZodDateParams): T;
export declare function _coercedDate<T extends schemas.$ZodDate>(Class: util.SchemaClass<T>, params?: string | $ZodDateParams): T;
export type $ZodNaNParams = TypeParams<schemas.$ZodNaN>;
export declare function _nan<T extends schemas.$ZodNaN>(Class: util.SchemaClass<T>, params?: string | $ZodNaNParams): T;
export type $ZodCheckLessThanParams = CheckParams<checks.$ZodCheckLessThan, "inclusive" | "value" | "when">;
export declare function _lt(value: util.Numeric, params?: string | $ZodCheckLessThanParams): checks.$ZodCheckLessThan<util.Numeric>;
export declare function _lte(value: util.Numeric, params?: string | $ZodCheckLessThanParams): checks.$ZodCheckLessThan<util.Numeric>;
export {
/** @deprecated Use `z.lte()` instead. */
_lte as _max, };
export type $ZodCheckGreaterThanParams = CheckParams<checks.$ZodCheckGreaterThan, "inclusive" | "value" | "when">;
export declare function _gt(value: util.Numeric, params?: string | $ZodCheckGreaterThanParams): checks.$ZodCheckGreaterThan;
export declare function _gte(value: util.Numeric, params?: string | $ZodCheckGreaterThanParams): checks.$ZodCheckGreaterThan;
export {
/** @deprecated Use `z.gte()` instead. */
_gte as _min, };
export declare function _positive(params?: string | $ZodCheckGreaterThanParams): checks.$ZodCheckGreaterThan;
export declare function _negative(params?: string | $ZodCheckLessThanParams): checks.$ZodCheckLessThan;
export declare function _nonpositive(params?: string | $ZodCheckLessThanParams): checks.$ZodCheckLessThan;
export declare function _nonnegative(params?: string | $ZodCheckGreaterThanParams): checks.$ZodCheckGreaterThan;
export type $ZodCheckMultipleOfParams = CheckParams<checks.$ZodCheckMultipleOf, "value" | "when">;
export declare function _multipleOf(value: number | bigint, params?: string | $ZodCheckMultipleOfParams): checks.$ZodCheckMultipleOf;
export type $ZodCheckMaxSizeParams = CheckParams<checks.$ZodCheckMaxSize, "maximum" | "when">;
export declare function _maxSize(maximum: number, params?: string | $ZodCheckMaxSizeParams): checks.$ZodCheckMaxSize<util.HasSize>;
export type $ZodCheckMinSizeParams = CheckParams<checks.$ZodCheckMinSize, "minimum" | "when">;
export declare function _minSize(minimum: number, params?: string | $ZodCheckMinSizeParams): checks.$ZodCheckMinSize<util.HasSize>;
export type $ZodCheckSizeEqualsParams = CheckParams<checks.$ZodCheckSizeEquals, "size" | "when">;
export declare function _size(size: number, params?: string | $ZodCheckSizeEqualsParams): checks.$ZodCheckSizeEquals<util.HasSize>;
export type $ZodCheckMaxLengthParams = CheckParams<checks.$ZodCheckMaxLength, "maximum" | "when">;
export declare function _maxLength(maximum: number, params?: string | $ZodCheckMaxLengthParams): checks.$ZodCheckMaxLength<util.HasLength>;
export type $ZodCheckMinLengthParams = CheckParams<checks.$ZodCheckMinLength, "minimum" | "when">;
export declare function _minLength(minimum: number, params?: string | $ZodCheckMinLengthParams): checks.$ZodCheckMinLength<util.HasLength>;
export type $ZodCheckLengthEqualsParams = CheckParams<checks.$ZodCheckLengthEquals, "length" | "when">;
export declare function _length(length: number, params?: string | $ZodCheckLengthEqualsParams): checks.$ZodCheckLengthEquals<util.HasLength>;
export type $ZodCheckRegexParams = CheckParams<checks.$ZodCheckRegex, "format" | "pattern" | "when">;
export declare function _regex(pattern: RegExp, params?: string | $ZodCheckRegexParams): checks.$ZodCheckRegex;
export type $ZodCheckLowerCaseParams = CheckParams<checks.$ZodCheckLowerCase, "format" | "when">;
export declare function _lowercase(params?: string | $ZodCheckLowerCaseParams): checks.$ZodCheckLowerCase;
export type $ZodCheckUpperCaseParams = CheckParams<checks.$ZodCheckUpperCase, "format" | "when">;
export declare function _uppercase(params?: string | $ZodCheckUpperCaseParams): checks.$ZodCheckUpperCase;
export type $ZodCheckIncludesParams = CheckParams<checks.$ZodCheckIncludes, "includes" | "format" | "when" | "pattern">;
export declare function _includes(includes: string, params?: string | $ZodCheckIncludesParams): checks.$ZodCheckIncludes;
export type $ZodCheckStartsWithParams = CheckParams<checks.$ZodCheckStartsWith, "prefix" | "format" | "when" | "pattern">;
export declare function _startsWith(prefix: string, params?: string | $ZodCheckStartsWithParams): checks.$ZodCheckStartsWith;
export type $ZodCheckEndsWithParams = CheckParams<checks.$ZodCheckEndsWith, "suffix" | "format" | "pattern" | "when">;
export declare function _endsWith(suffix: string, params?: string | $ZodCheckEndsWithParams): checks.$ZodCheckEndsWith;
export type $ZodCheckPropertyParams = CheckParams<checks.$ZodCheckProperty, "property" | "schema" | "when">;
export declare function _property<K extends string, T extends schemas.$ZodType>(property: K, schema: T, params?: string | $ZodCheckPropertyParams): checks.$ZodCheckProperty<{
[k in K]: util.Widen<core.input<T>>;
}>;
export type $ZodCheckPropertiesParams = CheckParams<checks.$ZodCheckProperties, "shape" | "when">;
export declare function _properties<Shape extends schemas.$ZodShape>(shape: Shape, params?: string | $ZodCheckPropertiesParams): checks.$ZodCheckProperties<Shape>;
export type $ZodCheckMimeTypeParams = CheckParams<checks.$ZodCheckMimeType, "mime" | "when">;
export declare function _mime(types: util.MimeTypes[], params?: string | $ZodCheckMimeTypeParams): checks.$ZodCheckMimeType;
export declare function _overwrite<T>(tx: (input: T) => T): checks.$ZodCheckOverwrite<T>;
export declare function _normalize(form?: "NFC" | "NFD" | "NFKC" | "NFKD" | (string & {})): checks.$ZodCheckOverwrite<string>;
export declare function _trim(): checks.$ZodCheckOverwrite<string>;
export declare function _toLowerCase(): checks.$ZodCheckOverwrite<string>;
export declare function _toUpperCase(): checks.$ZodCheckOverwrite<string>;
export declare function _slugify(): checks.$ZodCheckOverwrite<string>;
export type $ZodArrayParams = TypeParams<schemas.$ZodArray, "element">;
export declare function _array<T extends schemas.$ZodType>(Class: util.SchemaClass<schemas.$ZodArray>, element: T, params?: string | $ZodArrayParams): schemas.$ZodArray<T>;
export type $ZodObjectParams = TypeParams<schemas.$ZodObject, "shape" | "catchall">;
export type $ZodUnionParams = TypeParams<schemas.$ZodUnion, "options">;
export declare function _union<const T extends readonly schemas.$ZodObject[]>(Class: util.SchemaClass<schemas.$ZodUnion>, options: T, params?: string | $ZodUnionParams): schemas.$ZodUnion<T>;
export type $ZodXorParams = TypeParams<schemas.$ZodXor, "options">;
export declare function _xor<const T extends readonly schemas.$ZodObject[]>(Class: util.SchemaClass<schemas.$ZodXor>, options: T, params?: string | $ZodXorParams): schemas.$ZodXor<T>;
export interface $ZodTypeDiscriminableInternals<_Disc extends string = string> extends schemas._$ZodTypeInternals {
propValues: util.PropValues;
}
export interface $ZodTypeDiscriminable<_Disc extends string = string> extends schemas.SomeType {
_zod: $ZodTypeDiscriminableInternals;
}
export type $ZodDiscriminatedUnionParams = TypeParams<schemas.$ZodDiscriminatedUnion, "options" | "discriminator">;
export declare function _discriminatedUnion<Types extends [$ZodTypeDiscriminable, ...$ZodTypeDiscriminable[]], Disc extends string>(Class: util.SchemaClass<schemas.$ZodDiscriminatedUnion>, discriminator: Disc, options: Types, params?: string | $ZodDiscriminatedUnionParams): schemas.$ZodDiscriminatedUnion<Types, Disc>;
export type $ZodIntersectionParams = TypeParams<schemas.$ZodIntersection, "left" | "right">;
export declare function _intersection<T extends schemas.$ZodObject, U extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodIntersection>, left: T, right: U): schemas.$ZodIntersection<T, U>;
export type $ZodTupleParams = TypeParams<schemas.$ZodTuple, "items" | "rest">;
export declare function _tuple<T extends readonly [schemas.$ZodType, ...schemas.$ZodType[]]>(Class: util.SchemaClass<schemas.$ZodTuple>, items: T, params?: string | $ZodTupleParams): schemas.$ZodTuple<T, null>;
export declare function _tuple<T extends readonly [schemas.$ZodType, ...schemas.$ZodType[]], Rest extends schemas.$ZodType>(Class: util.SchemaClass<schemas.$ZodTuple>, items: T, rest: Rest, params?: string | $ZodTupleParams): schemas.$ZodTuple<T, Rest>;
export type $ZodRecordParams = TypeParams<schemas.$ZodRecord, "keyType" | "valueType" | "partial">;
export declare function _record<Key extends schemas.$ZodRecordKey, Value extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodRecord>, keyType: Key, valueType: Value, params?: string | $ZodRecordParams): schemas.$ZodRecord<Key, Value>;
export type $ZodMapParams = TypeParams<schemas.$ZodMap, "keyType" | "valueType">;
export declare function _map<Key extends schemas.$ZodObject, Value extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodMap>, keyType: Key, valueType: Value, params?: string | $ZodMapParams): schemas.$ZodMap<Key, Value>;
export type $ZodSetParams = TypeParams<schemas.$ZodSet, "valueType">;
export declare function _set<Value extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodSet>, valueType: Value, params?: string | $ZodSetParams): schemas.$ZodSet<Value>;
export type $ZodEnumParams = TypeParams<schemas.$ZodEnum, "entries">;
export declare function _enum<const T extends string[]>(Class: util.SchemaClass<schemas.$ZodEnum>, values: T, params?: string | $ZodEnumParams): schemas.$ZodEnum<util.ToEnum<T[number]>>;
export declare function _enum<T extends util.EnumLike>(Class: util.SchemaClass<schemas.$ZodEnum>, entries: T, params?: string | $ZodEnumParams): schemas.$ZodEnum<T>;
/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.
*
* ```ts
* enum Colors { red, green, blue }
* z.enum(Colors);
* ```
*/
export declare function _nativeEnum<T extends util.EnumLike>(Class: util.SchemaClass<schemas.$ZodEnum>, entries: T, params?: string | $ZodEnumParams): schemas.$ZodEnum<T>;
export type $ZodLiteralParams = TypeParams<schemas.$ZodLiteral, "values">;
export declare function _literal<const T extends Array<util.Literal>>(Class: util.SchemaClass<schemas.$ZodLiteral>, value: T, params?: string | $ZodLiteralParams): schemas.$ZodLiteral<T[number]>;
export declare function _literal<const T extends util.Literal>(Class: util.SchemaClass<schemas.$ZodLiteral>, value: T, params?: string | $ZodLiteralParams): schemas.$ZodLiteral<T>;
export type $ZodFileParams = TypeParams<schemas.$ZodFile>;
export declare function _file(Class: util.SchemaClass<schemas.$ZodFile>, params?: string | $ZodFileParams): schemas.$ZodFile;
export type $ZodTransformParams = TypeParams<schemas.$ZodTransform, "transform">;
export declare function _transform<I = unknown, O = I>(Class: util.SchemaClass<schemas.$ZodTransform>, fn: (input: I, ctx?: schemas.ParsePayload) => O): schemas.$ZodTransform<Awaited<O>, I>;
export type $ZodOptionalParams = TypeParams<schemas.$ZodOptional, "innerType">;
export declare function _optional<T extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodOptional>, innerType: T): schemas.$ZodOptional<T>;
export type $ZodNullableParams = TypeParams<schemas.$ZodNullable, "innerType">;
export declare function _nullable<T extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodNullable>, innerType: T): schemas.$ZodNullable<T>;
export type $ZodDefaultParams = TypeParams<schemas.$ZodDefault, "innerType" | "defaultValue">;
export declare function _default<T extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodDefault>, innerType: T, defaultValue: util.NoUndefined<core.output<T>> | (() => util.NoUndefined<core.output<T>>)): schemas.$ZodDefault<T>;
export type $ZodNonOptionalParams = TypeParams<schemas.$ZodNonOptional, "innerType">;
export declare function _nonoptional<T extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodNonOptional>, innerType: T, params?: string | $ZodNonOptionalParams): schemas.$ZodNonOptional<T>;
export type $ZodSuccessParams = TypeParams<schemas.$ZodSuccess, "innerType">;
export declare function _success<T extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodSuccess>, innerType: T): schemas.$ZodSuccess<T>;
export type $ZodCatchParams = TypeParams<schemas.$ZodCatch, "innerType" | "catchValue">;
export declare function _catch<T extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodCatch>, innerType: T, catchValue: core.output<T> | ((ctx: schemas.$ZodCatchCtx) => core.output<T>)): schemas.$ZodCatch<T>;
export type $ZodPipeParams = TypeParams<schemas.$ZodPipe, "in" | "out">;
export declare function _pipe<const A extends schemas.$ZodType, B extends schemas.$ZodType<unknown, core.output<A>> = schemas.$ZodType<unknown, core.output<A>>>(Class: util.SchemaClass<schemas.$ZodPipe>, in_: A, out: B | schemas.$ZodType<unknown, core.output<A>>): schemas.$ZodPipe<A, B>;
export type $ZodReadonlyParams = TypeParams<schemas.$ZodReadonly, "innerType">;
export declare function _readonly<T extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodReadonly>, innerType: T): schemas.$ZodReadonly<T>;
export type $ZodTemplateLiteralParams = TypeParams<schemas.$ZodTemplateLiteral, "parts">;
export declare function _templateLiteral<const Parts extends schemas.$ZodTemplateLiteralPart[]>(Class: util.SchemaClass<schemas.$ZodTemplateLiteral>, parts: Parts, params?: string | $ZodTemplateLiteralParams): schemas.$ZodTemplateLiteral<schemas.$PartsToTemplateLiteral<Parts>>;
export type $ZodLazyParams = TypeParams<schemas.$ZodLazy, "getter">;
export declare function _lazy<T extends schemas.$ZodType>(Class: util.SchemaClass<schemas.$ZodLazy>, getter: () => T): schemas.$ZodLazy<T>;
export type $ZodPromiseParams = TypeParams<schemas.$ZodPromise, "innerType">;
export declare function _promise<T extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodPromise>, innerType: T): schemas.$ZodPromise<T>;
export type $ZodCustomParams = CheckTypeParams<schemas.$ZodCustom, "fn">;
export declare function _custom<O = unknown, I = O>(Class: util.SchemaClass<schemas.$ZodCustom>, fn: (data: O) => unknown, _params: string | $ZodCustomParams | undefined): schemas.$ZodCustom<O, I>;
export declare function _refine<O = unknown, I = O>(Class: util.SchemaClass<schemas.$ZodCustom>, fn: (data: O) => unknown, _params: string | $ZodCustomParams | undefined): schemas.$ZodCustom<O, I>;
export type $ZodSuperRefineIssue<T extends errors.$ZodIssueBase = errors.$ZodIssue> = T extends any ? RawIssue<T> : never;
type RawIssue<T extends errors.$ZodIssueBase> = T extends any ? util.Flatten<util.MakePartial<T, "message" | "path"> & {
/** The schema or check that originated this issue. */
readonly inst?: schemas.$ZodType | checks.$ZodCheck;
/** If `true`, Zod will execute subsequent checks/refinements instead of immediately aborting */
readonly continue?: boolean | undefined;
} & Record<string, unknown>> : never;
export interface $RefinementCtx<T = unknown> extends schemas.ParsePayload<T> {
addIssue(arg: string | $ZodSuperRefineIssue): void;
}
export interface $ZodSuperRefineParams {
/** If provided, the refinement runs only when this returns `true`. By default, it is skipped if prior parsing produced aborting issues. */
when?: ((payload: schemas.ParsePayload) => boolean) | undefined;
}
export declare function _superRefine<T>(fn: (arg: T, payload: $RefinementCtx<T>) => void | Promise<void>, params?: $ZodSuperRefineParams): checks.$ZodCheck<T>;
export declare function _check<O = unknown>(fn: schemas.CheckFn<O>, params?: string | $ZodCustomParams): checks.$ZodCheck<O>;
export declare function describe<T>(description: string): checks.$ZodCheck<T>;
export declare function meta<T>(metadata: registries.GlobalMeta): checks.$ZodCheck<T>;
export interface $ZodStringBoolParams extends TypeParams {
truthy?: string[];
falsy?: string[];
/**
* Options: `"sensitive"`, `"insensitive"`
*
* @default `"insensitive"`
*/
case?: "sensitive" | "insensitive" | undefined;
}
export declare function _stringbool(Classes: {
Codec?: typeof schemas.$ZodCodec;
Boolean?: typeof schemas.$ZodBoolean;
String?: typeof schemas.$ZodString;
}, _params?: string | $ZodStringBoolParams): schemas.$ZodCodec<schemas.$ZodString, schemas.$ZodBoolean>;
export declare function _stringFormat<Format extends string>(Class: typeof schemas.$ZodCustomStringFormat, format: Format, fnOrRegex: ((arg: string) => util.MaybeAsync<unknown>) | RegExp, _params?: string | $ZodStringFormatParams): schemas.$ZodCustomStringFormat<Format>;
+335
View File
@@ -0,0 +1,335 @@
import * as checks from "./checks.js";
import type * as core from "./core.js";
import type * as errors from "./errors.js";
import * as registries from "./registries.js";
import * as schemas from "./schemas.js";
import * as util from "./util.js";
export type Params<T extends schemas.$ZodType | checks.$ZodCheck, IssueTypes extends errors.$ZodIssueBase, OmitKeys extends keyof T["_zod"]["def"] = never> = util.Flatten<Partial<util.EmptyToNever<Omit<T["_zod"]["def"], OmitKeys> & ([IssueTypes] extends [never] ? {} : {
error?: string | errors.$ZodErrorMap<IssueTypes> | undefined;
/** @deprecated This parameter is deprecated. Use `error` instead. */
message?: string | undefined;
})>>>;
export type TypeParams<T extends schemas.$ZodType = schemas.$ZodType & {
_isst: never;
}, AlsoOmit extends Exclude<keyof T["_zod"]["def"], "type" | "checks" | "error"> = never> = Params<T, NonNullable<T["_zod"]["isst"]>, "type" | "checks" | "error" | AlsoOmit>;
export type CheckParams<T extends checks.$ZodCheck = checks.$ZodCheck, // & { _issc: never },
AlsoOmit extends Exclude<keyof T["_zod"]["def"], "check" | "error"> = never> = Params<T, NonNullable<T["_zod"]["issc"]>, "check" | "error" | AlsoOmit>;
export type StringFormatParams<T extends schemas.$ZodStringFormat = schemas.$ZodStringFormat, AlsoOmit extends Exclude<keyof T["_zod"]["def"], "type" | "coerce" | "checks" | "error" | "check" | "format"> = never> = Params<T, NonNullable<T["_zod"]["isst"] | T["_zod"]["issc"]>, "type" | "coerce" | "checks" | "error" | "check" | "format" | AlsoOmit>;
export type CheckStringFormatParams<T extends schemas.$ZodStringFormat = schemas.$ZodStringFormat, AlsoOmit extends Exclude<keyof T["_zod"]["def"], "type" | "coerce" | "checks" | "error" | "check" | "format"> = never> = Params<T, NonNullable<T["_zod"]["issc"]>, "type" | "coerce" | "checks" | "error" | "check" | "format" | AlsoOmit>;
export type CheckTypeParams<T extends schemas.$ZodType & checks.$ZodCheck = schemas.$ZodType & checks.$ZodCheck, AlsoOmit extends Exclude<keyof T["_zod"]["def"], "type" | "checks" | "error" | "check"> = never> = Params<T, NonNullable<T["_zod"]["isst"] | T["_zod"]["issc"]>, "type" | "checks" | "error" | "check" | AlsoOmit>;
export type $ZodStringParams = TypeParams<schemas.$ZodString<string>, "coerce"> & {
checks?: readonly checks.$ZodCheck<string>[];
};
export declare function _string<T extends schemas.$ZodString>(Class: util.SchemaClass<T>, params?: string | $ZodStringParams): T;
export declare function _coercedString<T extends schemas.$ZodString>(Class: util.SchemaClass<T>, params?: string | $ZodStringParams): T;
export type $ZodStringFormatParams = CheckTypeParams<schemas.$ZodStringFormat, "format" | "coerce" | "when" | "pattern">;
export type $ZodCheckStringFormatParams = CheckParams<checks.$ZodCheckStringFormat, "format">;
export type $ZodEmailParams = StringFormatParams<schemas.$ZodEmail, "when">;
export type $ZodCheckEmailParams = CheckStringFormatParams<schemas.$ZodEmail, "when">;
export declare function _email<T extends schemas.$ZodEmail>(Class: util.SchemaClass<T>, params?: string | $ZodEmailParams | $ZodCheckEmailParams): T;
export type $ZodGUIDParams = StringFormatParams<schemas.$ZodGUID, "pattern" | "when">;
export type $ZodCheckGUIDParams = CheckStringFormatParams<schemas.$ZodGUID, "pattern" | "when">;
export declare function _guid<T extends schemas.$ZodGUID>(Class: util.SchemaClass<T>, params?: string | $ZodGUIDParams | $ZodCheckGUIDParams): T;
export type $ZodUUIDParams = StringFormatParams<schemas.$ZodUUID, "pattern" | "when">;
export type $ZodCheckUUIDParams = CheckStringFormatParams<schemas.$ZodUUID, "pattern" | "when">;
export declare function _uuid<T extends schemas.$ZodUUID>(Class: util.SchemaClass<T>, params?: string | $ZodUUIDParams | $ZodCheckUUIDParams): T;
export type $ZodUUIDv4Params = StringFormatParams<schemas.$ZodUUID, "pattern" | "when">;
export type $ZodCheckUUIDv4Params = CheckStringFormatParams<schemas.$ZodUUID, "pattern" | "when">;
export declare function _uuidv4<T extends schemas.$ZodUUID>(Class: util.SchemaClass<T>, params?: string | $ZodUUIDv4Params | $ZodCheckUUIDv4Params): T;
export type $ZodUUIDv6Params = StringFormatParams<schemas.$ZodUUID, "pattern" | "when">;
export type $ZodCheckUUIDv6Params = CheckStringFormatParams<schemas.$ZodUUID, "pattern" | "when">;
export declare function _uuidv6<T extends schemas.$ZodUUID>(Class: util.SchemaClass<T>, params?: string | $ZodUUIDv6Params | $ZodCheckUUIDv6Params): T;
export type $ZodUUIDv7Params = StringFormatParams<schemas.$ZodUUID, "pattern" | "when">;
export type $ZodCheckUUIDv7Params = CheckStringFormatParams<schemas.$ZodUUID, "pattern" | "when">;
export declare function _uuidv7<T extends schemas.$ZodUUID>(Class: util.SchemaClass<T>, params?: string | $ZodUUIDv7Params | $ZodCheckUUIDv7Params): T;
export type $ZodURLParams = StringFormatParams<schemas.$ZodURL, "when">;
export type $ZodCheckURLParams = CheckStringFormatParams<schemas.$ZodURL, "when">;
export declare function _url<T extends schemas.$ZodURL>(Class: util.SchemaClass<T>, params?: string | $ZodURLParams | $ZodCheckURLParams): T;
export type $ZodEmojiParams = StringFormatParams<schemas.$ZodEmoji, "when">;
export type $ZodCheckEmojiParams = CheckStringFormatParams<schemas.$ZodEmoji, "when">;
export declare function _emoji<T extends schemas.$ZodEmoji>(Class: util.SchemaClass<T>, params?: string | $ZodEmojiParams | $ZodCheckEmojiParams): T;
export type $ZodNanoIDParams = StringFormatParams<schemas.$ZodNanoID, "when" | "pattern">;
export type $ZodCheckNanoIDParams = CheckStringFormatParams<schemas.$ZodNanoID, "when" | "pattern">;
export declare function _nanoid<T extends schemas.$ZodNanoID>(Class: util.SchemaClass<T>, params?: string | $ZodNanoIDParams | $ZodCheckNanoIDParams): T;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link _cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export type $ZodCUIDParams = StringFormatParams<schemas.$ZodCUID, "when">;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link _cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export type $ZodCheckCUIDParams = CheckStringFormatParams<schemas.$ZodCUID, "when">;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link _cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare function _cuid<T extends schemas.$ZodCUID>(Class: util.SchemaClass<T>, params?: string | $ZodCUIDParams | $ZodCheckCUIDParams): T;
export type $ZodCUID2Params = StringFormatParams<schemas.$ZodCUID2, "when">;
export type $ZodCheckCUID2Params = CheckStringFormatParams<schemas.$ZodCUID2, "when">;
export declare function _cuid2<T extends schemas.$ZodCUID2>(Class: util.SchemaClass<T>, params?: string | $ZodCUID2Params | $ZodCheckCUID2Params): T;
export type $ZodULIDParams = StringFormatParams<schemas.$ZodULID, "when">;
export type $ZodCheckULIDParams = CheckStringFormatParams<schemas.$ZodULID, "when">;
export declare function _ulid<T extends schemas.$ZodULID>(Class: util.SchemaClass<T>, params?: string | $ZodULIDParams | $ZodCheckULIDParams): T;
export type $ZodXIDParams = StringFormatParams<schemas.$ZodXID, "when">;
export type $ZodCheckXIDParams = CheckStringFormatParams<schemas.$ZodXID, "when">;
export declare function _xid<T extends schemas.$ZodXID>(Class: util.SchemaClass<T>, params?: string | $ZodXIDParams | $ZodCheckXIDParams): T;
export type $ZodKSUIDParams = StringFormatParams<schemas.$ZodKSUID, "when">;
export type $ZodCheckKSUIDParams = CheckStringFormatParams<schemas.$ZodKSUID, "when">;
export declare function _ksuid<T extends schemas.$ZodKSUID>(Class: util.SchemaClass<T>, params?: string | $ZodKSUIDParams | $ZodCheckKSUIDParams): T;
export type $ZodIPv4Params = StringFormatParams<schemas.$ZodIPv4, "pattern" | "when" | "version">;
export type $ZodCheckIPv4Params = CheckStringFormatParams<schemas.$ZodIPv4, "pattern" | "when" | "version">;
export declare function _ipv4<T extends schemas.$ZodIPv4>(Class: util.SchemaClass<T>, params?: string | $ZodIPv4Params | $ZodCheckIPv4Params): T;
export type $ZodIPv6Params = StringFormatParams<schemas.$ZodIPv6, "pattern" | "when" | "version">;
export type $ZodCheckIPv6Params = CheckStringFormatParams<schemas.$ZodIPv6, "pattern" | "when" | "version">;
export declare function _ipv6<T extends schemas.$ZodIPv6>(Class: util.SchemaClass<T>, params?: string | $ZodIPv6Params | $ZodCheckIPv6Params): T;
export type $ZodMACParams = StringFormatParams<schemas.$ZodMAC, "pattern" | "when">;
export type $ZodCheckMACParams = CheckStringFormatParams<schemas.$ZodMAC, "pattern" | "when">;
export declare function _mac<T extends schemas.$ZodMAC>(Class: util.SchemaClass<T>, params?: string | $ZodMACParams | $ZodCheckMACParams): T;
export type $ZodCIDRv4Params = StringFormatParams<schemas.$ZodCIDRv4, "pattern" | "when">;
export type $ZodCheckCIDRv4Params = CheckStringFormatParams<schemas.$ZodCIDRv4, "pattern" | "when">;
export declare function _cidrv4<T extends schemas.$ZodCIDRv4>(Class: util.SchemaClass<T>, params?: string | $ZodCIDRv4Params | $ZodCheckCIDRv4Params): T;
export type $ZodCIDRv6Params = StringFormatParams<schemas.$ZodCIDRv6, "pattern" | "when">;
export type $ZodCheckCIDRv6Params = CheckStringFormatParams<schemas.$ZodCIDRv6, "pattern" | "when">;
export declare function _cidrv6<T extends schemas.$ZodCIDRv6>(Class: util.SchemaClass<T>, params?: string | $ZodCIDRv6Params | $ZodCheckCIDRv6Params): T;
export type $ZodBase64Params = StringFormatParams<schemas.$ZodBase64, "pattern" | "when">;
export type $ZodCheckBase64Params = CheckStringFormatParams<schemas.$ZodBase64, "pattern" | "when">;
export declare function _base64<T extends schemas.$ZodBase64>(Class: util.SchemaClass<T>, params?: string | $ZodBase64Params | $ZodCheckBase64Params): T;
export type $ZodBase64URLParams = StringFormatParams<schemas.$ZodBase64URL, "pattern" | "when">;
export type $ZodCheckBase64URLParams = CheckStringFormatParams<schemas.$ZodBase64URL, "pattern" | "when">;
export declare function _base64url<T extends schemas.$ZodBase64URL>(Class: util.SchemaClass<T>, params?: string | $ZodBase64URLParams | $ZodCheckBase64URLParams): T;
export type $ZodE164Params = StringFormatParams<schemas.$ZodE164, "when">;
export type $ZodCheckE164Params = CheckStringFormatParams<schemas.$ZodE164, "when">;
export declare function _e164<T extends schemas.$ZodE164>(Class: util.SchemaClass<T>, params?: string | $ZodE164Params | $ZodCheckE164Params): T;
export type $ZodCreditCardParams = StringFormatParams<schemas.$ZodCreditCard, "pattern" | "when">;
export type $ZodCheckCreditCardParams = CheckStringFormatParams<schemas.$ZodCreditCard, "pattern" | "when">;
export declare function _creditCard<T extends schemas.$ZodCreditCard>(Class: util.SchemaClass<T>, params?: string | $ZodCreditCardParams | $ZodCheckCreditCardParams): T;
export type $ZodIBANParams = StringFormatParams<schemas.$ZodIBAN, "pattern" | "when">;
export type $ZodCheckIBANParams = CheckStringFormatParams<schemas.$ZodIBAN, "pattern" | "when">;
export declare function _iban<T extends schemas.$ZodIBAN>(Class: util.SchemaClass<T>, params?: string | $ZodIBANParams | $ZodCheckIBANParams): T;
export type $ZodJWTParams = StringFormatParams<schemas.$ZodJWT, "pattern" | "when">;
export type $ZodCheckJWTParams = CheckStringFormatParams<schemas.$ZodJWT, "pattern" | "when">;
export declare function _jwt<T extends schemas.$ZodJWT>(Class: util.SchemaClass<T>, params?: string | $ZodJWTParams | $ZodCheckJWTParams): T;
export declare const TimePrecision: {
readonly Any: null;
readonly Minute: -1;
readonly Second: 0;
readonly Millisecond: 3;
readonly Microsecond: 6;
};
export type $ZodISODateTimeParams = StringFormatParams<schemas.$ZodISODateTime, "pattern" | "when">;
export type $ZodCheckISODateTimeParams = CheckStringFormatParams<schemas.$ZodISODateTime, "pattern" | "when">;
export declare function _isoDateTime<T extends schemas.$ZodISODateTime>(Class: util.SchemaClass<T>, params?: string | $ZodISODateTimeParams | $ZodCheckISODateTimeParams): T;
export type $ZodISODateParams = StringFormatParams<schemas.$ZodISODate, "pattern" | "when">;
export type $ZodCheckISODateParams = CheckStringFormatParams<schemas.$ZodISODate, "pattern" | "when">;
export declare function _isoDate<T extends schemas.$ZodISODate>(Class: util.SchemaClass<T>, params?: string | $ZodISODateParams | $ZodCheckISODateParams): T;
export type $ZodISOTimeParams = StringFormatParams<schemas.$ZodISOTime, "pattern" | "when">;
export type $ZodCheckISOTimeParams = CheckStringFormatParams<schemas.$ZodISOTime, "pattern" | "when">;
export declare function _isoTime<T extends schemas.$ZodISOTime>(Class: util.SchemaClass<T>, params?: string | $ZodISOTimeParams | $ZodCheckISOTimeParams): T;
export type $ZodISODurationParams = StringFormatParams<schemas.$ZodISODuration, "when">;
export type $ZodCheckISODurationParams = CheckStringFormatParams<schemas.$ZodISODuration, "when">;
export declare function _isoDuration<T extends schemas.$ZodISODuration>(Class: util.SchemaClass<T>, params?: string | $ZodISODurationParams | $ZodCheckISODurationParams): T;
export type $ZodNumberParams = TypeParams<schemas.$ZodNumber<number>, "coerce"> & {
checks?: readonly checks.$ZodCheck<number>[];
};
export type $ZodNumberFormatParams = CheckTypeParams<schemas.$ZodNumberFormat, "format" | "coerce">;
export type $ZodCheckNumberFormatParams = CheckParams<checks.$ZodCheckNumberFormat, "format" | "when">;
export declare function _number<T extends schemas.$ZodNumber>(Class: util.SchemaClass<T>, params?: string | $ZodNumberParams): T;
export declare function _coercedNumber<T extends schemas.$ZodNumber>(Class: util.SchemaClass<T>, params?: string | $ZodNumberParams): T;
export declare function _int<T extends schemas.$ZodNumberFormat>(Class: util.SchemaClass<T>, params?: string | $ZodCheckNumberFormatParams): T;
export declare function _float32<T extends schemas.$ZodNumberFormat>(Class: util.SchemaClass<T>, params?: string | $ZodCheckNumberFormatParams): T;
export declare function _float64<T extends schemas.$ZodNumberFormat>(Class: util.SchemaClass<T>, params?: string | $ZodCheckNumberFormatParams): T;
export declare function _int32<T extends schemas.$ZodNumberFormat>(Class: util.SchemaClass<T>, params?: string | $ZodCheckNumberFormatParams): T;
export declare function _uint32<T extends schemas.$ZodNumberFormat>(Class: util.SchemaClass<T>, params?: string | $ZodCheckNumberFormatParams): T;
export type $ZodBooleanParams = TypeParams<schemas.$ZodBoolean<boolean>, "coerce">;
export declare function _boolean<T extends schemas.$ZodBoolean>(Class: util.SchemaClass<T>, params?: string | $ZodBooleanParams): T;
export declare function _coercedBoolean<T extends schemas.$ZodBoolean>(Class: util.SchemaClass<T>, params?: string | $ZodBooleanParams): T;
export type $ZodBigIntParams = TypeParams<schemas.$ZodBigInt<bigint>>;
export type $ZodBigIntFormatParams = CheckTypeParams<schemas.$ZodBigIntFormat, "format" | "coerce">;
export type $ZodCheckBigIntFormatParams = CheckParams<checks.$ZodCheckBigIntFormat, "format" | "when">;
export declare function _bigint<T extends schemas.$ZodBigInt>(Class: util.SchemaClass<T>, params?: string | $ZodBigIntParams): T;
export declare function _coercedBigint<T extends schemas.$ZodBigInt>(Class: util.SchemaClass<T>, params?: string | $ZodBigIntParams): T;
export declare function _int64<T extends schemas.$ZodBigIntFormat>(Class: util.SchemaClass<T>, params?: string | $ZodBigIntFormatParams): T;
export declare function _uint64<T extends schemas.$ZodBigIntFormat>(Class: util.SchemaClass<T>, params?: string | $ZodBigIntFormatParams): T;
export type $ZodSymbolParams = TypeParams<schemas.$ZodSymbol>;
export declare function _symbol<T extends schemas.$ZodSymbol>(Class: util.SchemaClass<T>, params?: string | $ZodSymbolParams): T;
export type $ZodUndefinedParams = TypeParams<schemas.$ZodUndefined>;
export declare function _undefined<T extends schemas.$ZodUndefined>(Class: util.SchemaClass<T>, params?: string | $ZodUndefinedParams): T;
export type $ZodNullParams = TypeParams<schemas.$ZodNull>;
export declare function _null<T extends schemas.$ZodNull>(Class: util.SchemaClass<T>, params?: string | $ZodNullParams): T;
export type $ZodAnyParams = TypeParams<schemas.$ZodAny>;
export declare function _any<T extends schemas.$ZodAny>(Class: util.SchemaClass<T>): T;
export type $ZodUnknownParams = TypeParams<schemas.$ZodUnknown>;
export declare function _unknown<T extends schemas.$ZodUnknown>(Class: util.SchemaClass<T>): T;
export type $ZodNeverParams = TypeParams<schemas.$ZodNever>;
export declare function _never<T extends schemas.$ZodNever>(Class: util.SchemaClass<T>, params?: string | $ZodNeverParams): T;
export type $ZodVoidParams = TypeParams<schemas.$ZodVoid>;
export declare function _void<T extends schemas.$ZodVoid>(Class: util.SchemaClass<T>, params?: string | $ZodVoidParams): T;
export type $ZodDateParams = TypeParams<schemas.$ZodDate, "coerce">;
export declare function _date<T extends schemas.$ZodDate>(Class: util.SchemaClass<T>, params?: string | $ZodDateParams): T;
export declare function _coercedDate<T extends schemas.$ZodDate>(Class: util.SchemaClass<T>, params?: string | $ZodDateParams): T;
export type $ZodNaNParams = TypeParams<schemas.$ZodNaN>;
export declare function _nan<T extends schemas.$ZodNaN>(Class: util.SchemaClass<T>, params?: string | $ZodNaNParams): T;
export type $ZodCheckLessThanParams = CheckParams<checks.$ZodCheckLessThan, "inclusive" | "value" | "when">;
export declare function _lt(value: util.Numeric, params?: string | $ZodCheckLessThanParams): checks.$ZodCheckLessThan<util.Numeric>;
export declare function _lte(value: util.Numeric, params?: string | $ZodCheckLessThanParams): checks.$ZodCheckLessThan<util.Numeric>;
export {
/** @deprecated Use `z.lte()` instead. */
_lte as _max, };
export type $ZodCheckGreaterThanParams = CheckParams<checks.$ZodCheckGreaterThan, "inclusive" | "value" | "when">;
export declare function _gt(value: util.Numeric, params?: string | $ZodCheckGreaterThanParams): checks.$ZodCheckGreaterThan;
export declare function _gte(value: util.Numeric, params?: string | $ZodCheckGreaterThanParams): checks.$ZodCheckGreaterThan;
export {
/** @deprecated Use `z.gte()` instead. */
_gte as _min, };
export declare function _positive(params?: string | $ZodCheckGreaterThanParams): checks.$ZodCheckGreaterThan;
export declare function _negative(params?: string | $ZodCheckLessThanParams): checks.$ZodCheckLessThan;
export declare function _nonpositive(params?: string | $ZodCheckLessThanParams): checks.$ZodCheckLessThan;
export declare function _nonnegative(params?: string | $ZodCheckGreaterThanParams): checks.$ZodCheckGreaterThan;
export type $ZodCheckMultipleOfParams = CheckParams<checks.$ZodCheckMultipleOf, "value" | "when">;
export declare function _multipleOf(value: number | bigint, params?: string | $ZodCheckMultipleOfParams): checks.$ZodCheckMultipleOf;
export type $ZodCheckMaxSizeParams = CheckParams<checks.$ZodCheckMaxSize, "maximum" | "when">;
export declare function _maxSize(maximum: number, params?: string | $ZodCheckMaxSizeParams): checks.$ZodCheckMaxSize<util.HasSize>;
export type $ZodCheckMinSizeParams = CheckParams<checks.$ZodCheckMinSize, "minimum" | "when">;
export declare function _minSize(minimum: number, params?: string | $ZodCheckMinSizeParams): checks.$ZodCheckMinSize<util.HasSize>;
export type $ZodCheckSizeEqualsParams = CheckParams<checks.$ZodCheckSizeEquals, "size" | "when">;
export declare function _size(size: number, params?: string | $ZodCheckSizeEqualsParams): checks.$ZodCheckSizeEquals<util.HasSize>;
export type $ZodCheckMaxLengthParams = CheckParams<checks.$ZodCheckMaxLength, "maximum" | "when">;
export declare function _maxLength(maximum: number, params?: string | $ZodCheckMaxLengthParams): checks.$ZodCheckMaxLength<util.HasLength>;
export type $ZodCheckMinLengthParams = CheckParams<checks.$ZodCheckMinLength, "minimum" | "when">;
export declare function _minLength(minimum: number, params?: string | $ZodCheckMinLengthParams): checks.$ZodCheckMinLength<util.HasLength>;
export type $ZodCheckLengthEqualsParams = CheckParams<checks.$ZodCheckLengthEquals, "length" | "when">;
export declare function _length(length: number, params?: string | $ZodCheckLengthEqualsParams): checks.$ZodCheckLengthEquals<util.HasLength>;
export type $ZodCheckRegexParams = CheckParams<checks.$ZodCheckRegex, "format" | "pattern" | "when">;
export declare function _regex(pattern: RegExp, params?: string | $ZodCheckRegexParams): checks.$ZodCheckRegex;
export type $ZodCheckLowerCaseParams = CheckParams<checks.$ZodCheckLowerCase, "format" | "when">;
export declare function _lowercase(params?: string | $ZodCheckLowerCaseParams): checks.$ZodCheckLowerCase;
export type $ZodCheckUpperCaseParams = CheckParams<checks.$ZodCheckUpperCase, "format" | "when">;
export declare function _uppercase(params?: string | $ZodCheckUpperCaseParams): checks.$ZodCheckUpperCase;
export type $ZodCheckIncludesParams = CheckParams<checks.$ZodCheckIncludes, "includes" | "format" | "when" | "pattern">;
export declare function _includes(includes: string, params?: string | $ZodCheckIncludesParams): checks.$ZodCheckIncludes;
export type $ZodCheckStartsWithParams = CheckParams<checks.$ZodCheckStartsWith, "prefix" | "format" | "when" | "pattern">;
export declare function _startsWith(prefix: string, params?: string | $ZodCheckStartsWithParams): checks.$ZodCheckStartsWith;
export type $ZodCheckEndsWithParams = CheckParams<checks.$ZodCheckEndsWith, "suffix" | "format" | "pattern" | "when">;
export declare function _endsWith(suffix: string, params?: string | $ZodCheckEndsWithParams): checks.$ZodCheckEndsWith;
export type $ZodCheckPropertyParams = CheckParams<checks.$ZodCheckProperty, "property" | "schema" | "when">;
export declare function _property<K extends string, T extends schemas.$ZodType>(property: K, schema: T, params?: string | $ZodCheckPropertyParams): checks.$ZodCheckProperty<{
[k in K]: util.Widen<core.input<T>>;
}>;
export type $ZodCheckPropertiesParams = CheckParams<checks.$ZodCheckProperties, "shape" | "when">;
export declare function _properties<Shape extends schemas.$ZodShape>(shape: Shape, params?: string | $ZodCheckPropertiesParams): checks.$ZodCheckProperties<Shape>;
export type $ZodCheckMimeTypeParams = CheckParams<checks.$ZodCheckMimeType, "mime" | "when">;
export declare function _mime(types: util.MimeTypes[], params?: string | $ZodCheckMimeTypeParams): checks.$ZodCheckMimeType;
export declare function _overwrite<T>(tx: (input: T) => T): checks.$ZodCheckOverwrite<T>;
export declare function _normalize(form?: "NFC" | "NFD" | "NFKC" | "NFKD" | (string & {})): checks.$ZodCheckOverwrite<string>;
export declare function _trim(): checks.$ZodCheckOverwrite<string>;
export declare function _toLowerCase(): checks.$ZodCheckOverwrite<string>;
export declare function _toUpperCase(): checks.$ZodCheckOverwrite<string>;
export declare function _slugify(): checks.$ZodCheckOverwrite<string>;
export type $ZodArrayParams = TypeParams<schemas.$ZodArray, "element">;
export declare function _array<T extends schemas.$ZodType>(Class: util.SchemaClass<schemas.$ZodArray>, element: T, params?: string | $ZodArrayParams): schemas.$ZodArray<T>;
export type $ZodObjectParams = TypeParams<schemas.$ZodObject, "shape" | "catchall">;
export type $ZodUnionParams = TypeParams<schemas.$ZodUnion, "options">;
export declare function _union<const T extends readonly schemas.$ZodObject[]>(Class: util.SchemaClass<schemas.$ZodUnion>, options: T, params?: string | $ZodUnionParams): schemas.$ZodUnion<T>;
export type $ZodXorParams = TypeParams<schemas.$ZodXor, "options">;
export declare function _xor<const T extends readonly schemas.$ZodObject[]>(Class: util.SchemaClass<schemas.$ZodXor>, options: T, params?: string | $ZodXorParams): schemas.$ZodXor<T>;
export interface $ZodTypeDiscriminableInternals<_Disc extends string = string> extends schemas._$ZodTypeInternals {
propValues: util.PropValues;
}
export interface $ZodTypeDiscriminable<_Disc extends string = string> extends schemas.SomeType {
_zod: $ZodTypeDiscriminableInternals;
}
export type $ZodDiscriminatedUnionParams = TypeParams<schemas.$ZodDiscriminatedUnion, "options" | "discriminator">;
export declare function _discriminatedUnion<Types extends [$ZodTypeDiscriminable, ...$ZodTypeDiscriminable[]], Disc extends string>(Class: util.SchemaClass<schemas.$ZodDiscriminatedUnion>, discriminator: Disc, options: Types, params?: string | $ZodDiscriminatedUnionParams): schemas.$ZodDiscriminatedUnion<Types, Disc>;
export type $ZodIntersectionParams = TypeParams<schemas.$ZodIntersection, "left" | "right">;
export declare function _intersection<T extends schemas.$ZodObject, U extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodIntersection>, left: T, right: U): schemas.$ZodIntersection<T, U>;
export type $ZodTupleParams = TypeParams<schemas.$ZodTuple, "items" | "rest">;
export declare function _tuple<T extends readonly [schemas.$ZodType, ...schemas.$ZodType[]]>(Class: util.SchemaClass<schemas.$ZodTuple>, items: T, params?: string | $ZodTupleParams): schemas.$ZodTuple<T, null>;
export declare function _tuple<T extends readonly [schemas.$ZodType, ...schemas.$ZodType[]], Rest extends schemas.$ZodType>(Class: util.SchemaClass<schemas.$ZodTuple>, items: T, rest: Rest, params?: string | $ZodTupleParams): schemas.$ZodTuple<T, Rest>;
export type $ZodRecordParams = TypeParams<schemas.$ZodRecord, "keyType" | "valueType" | "partial">;
export declare function _record<Key extends schemas.$ZodRecordKey, Value extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodRecord>, keyType: Key, valueType: Value, params?: string | $ZodRecordParams): schemas.$ZodRecord<Key, Value>;
export type $ZodMapParams = TypeParams<schemas.$ZodMap, "keyType" | "valueType">;
export declare function _map<Key extends schemas.$ZodObject, Value extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodMap>, keyType: Key, valueType: Value, params?: string | $ZodMapParams): schemas.$ZodMap<Key, Value>;
export type $ZodSetParams = TypeParams<schemas.$ZodSet, "valueType">;
export declare function _set<Value extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodSet>, valueType: Value, params?: string | $ZodSetParams): schemas.$ZodSet<Value>;
export type $ZodEnumParams = TypeParams<schemas.$ZodEnum, "entries">;
export declare function _enum<const T extends string[]>(Class: util.SchemaClass<schemas.$ZodEnum>, values: T, params?: string | $ZodEnumParams): schemas.$ZodEnum<util.ToEnum<T[number]>>;
export declare function _enum<T extends util.EnumLike>(Class: util.SchemaClass<schemas.$ZodEnum>, entries: T, params?: string | $ZodEnumParams): schemas.$ZodEnum<T>;
/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.
*
* ```ts
* enum Colors { red, green, blue }
* z.enum(Colors);
* ```
*/
export declare function _nativeEnum<T extends util.EnumLike>(Class: util.SchemaClass<schemas.$ZodEnum>, entries: T, params?: string | $ZodEnumParams): schemas.$ZodEnum<T>;
export type $ZodLiteralParams = TypeParams<schemas.$ZodLiteral, "values">;
export declare function _literal<const T extends Array<util.Literal>>(Class: util.SchemaClass<schemas.$ZodLiteral>, value: T, params?: string | $ZodLiteralParams): schemas.$ZodLiteral<T[number]>;
export declare function _literal<const T extends util.Literal>(Class: util.SchemaClass<schemas.$ZodLiteral>, value: T, params?: string | $ZodLiteralParams): schemas.$ZodLiteral<T>;
export type $ZodFileParams = TypeParams<schemas.$ZodFile>;
export declare function _file(Class: util.SchemaClass<schemas.$ZodFile>, params?: string | $ZodFileParams): schemas.$ZodFile;
export type $ZodTransformParams = TypeParams<schemas.$ZodTransform, "transform">;
export declare function _transform<I = unknown, O = I>(Class: util.SchemaClass<schemas.$ZodTransform>, fn: (input: I, ctx?: schemas.ParsePayload) => O): schemas.$ZodTransform<Awaited<O>, I>;
export type $ZodOptionalParams = TypeParams<schemas.$ZodOptional, "innerType">;
export declare function _optional<T extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodOptional>, innerType: T): schemas.$ZodOptional<T>;
export type $ZodNullableParams = TypeParams<schemas.$ZodNullable, "innerType">;
export declare function _nullable<T extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodNullable>, innerType: T): schemas.$ZodNullable<T>;
export type $ZodDefaultParams = TypeParams<schemas.$ZodDefault, "innerType" | "defaultValue">;
export declare function _default<T extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodDefault>, innerType: T, defaultValue: util.NoUndefined<core.output<T>> | (() => util.NoUndefined<core.output<T>>)): schemas.$ZodDefault<T>;
export type $ZodNonOptionalParams = TypeParams<schemas.$ZodNonOptional, "innerType">;
export declare function _nonoptional<T extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodNonOptional>, innerType: T, params?: string | $ZodNonOptionalParams): schemas.$ZodNonOptional<T>;
export type $ZodSuccessParams = TypeParams<schemas.$ZodSuccess, "innerType">;
export declare function _success<T extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodSuccess>, innerType: T): schemas.$ZodSuccess<T>;
export type $ZodCatchParams = TypeParams<schemas.$ZodCatch, "innerType" | "catchValue">;
export declare function _catch<T extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodCatch>, innerType: T, catchValue: core.output<T> | ((ctx: schemas.$ZodCatchCtx) => core.output<T>)): schemas.$ZodCatch<T>;
export type $ZodPipeParams = TypeParams<schemas.$ZodPipe, "in" | "out">;
export declare function _pipe<const A extends schemas.$ZodType, B extends schemas.$ZodType<unknown, core.output<A>> = schemas.$ZodType<unknown, core.output<A>>>(Class: util.SchemaClass<schemas.$ZodPipe>, in_: A, out: B | schemas.$ZodType<unknown, core.output<A>>): schemas.$ZodPipe<A, B>;
export type $ZodReadonlyParams = TypeParams<schemas.$ZodReadonly, "innerType">;
export declare function _readonly<T extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodReadonly>, innerType: T): schemas.$ZodReadonly<T>;
export type $ZodTemplateLiteralParams = TypeParams<schemas.$ZodTemplateLiteral, "parts">;
export declare function _templateLiteral<const Parts extends schemas.$ZodTemplateLiteralPart[]>(Class: util.SchemaClass<schemas.$ZodTemplateLiteral>, parts: Parts, params?: string | $ZodTemplateLiteralParams): schemas.$ZodTemplateLiteral<schemas.$PartsToTemplateLiteral<Parts>>;
export type $ZodLazyParams = TypeParams<schemas.$ZodLazy, "getter">;
export declare function _lazy<T extends schemas.$ZodType>(Class: util.SchemaClass<schemas.$ZodLazy>, getter: () => T): schemas.$ZodLazy<T>;
export type $ZodPromiseParams = TypeParams<schemas.$ZodPromise, "innerType">;
export declare function _promise<T extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodPromise>, innerType: T): schemas.$ZodPromise<T>;
export type $ZodCustomParams = CheckTypeParams<schemas.$ZodCustom, "fn">;
export declare function _custom<O = unknown, I = O>(Class: util.SchemaClass<schemas.$ZodCustom>, fn: (data: O) => unknown, _params: string | $ZodCustomParams | undefined): schemas.$ZodCustom<O, I>;
export declare function _refine<O = unknown, I = O>(Class: util.SchemaClass<schemas.$ZodCustom>, fn: (data: O) => unknown, _params: string | $ZodCustomParams | undefined): schemas.$ZodCustom<O, I>;
export type $ZodSuperRefineIssue<T extends errors.$ZodIssueBase = errors.$ZodIssue> = T extends any ? RawIssue<T> : never;
type RawIssue<T extends errors.$ZodIssueBase> = T extends any ? util.Flatten<util.MakePartial<T, "message" | "path"> & {
/** The schema or check that originated this issue. */
readonly inst?: schemas.$ZodType | checks.$ZodCheck;
/** If `true`, Zod will execute subsequent checks/refinements instead of immediately aborting */
readonly continue?: boolean | undefined;
} & Record<string, unknown>> : never;
export interface $RefinementCtx<T = unknown> extends schemas.ParsePayload<T> {
addIssue(arg: string | $ZodSuperRefineIssue): void;
}
export interface $ZodSuperRefineParams {
/** If provided, the refinement runs only when this returns `true`. By default, it is skipped if prior parsing produced aborting issues. */
when?: ((payload: schemas.ParsePayload) => boolean) | undefined;
}
export declare function _superRefine<T>(fn: (arg: T, payload: $RefinementCtx<T>) => void | Promise<void>, params?: $ZodSuperRefineParams): checks.$ZodCheck<T>;
export declare function _check<O = unknown>(fn: schemas.CheckFn<O>, params?: string | $ZodCustomParams): checks.$ZodCheck<O>;
export declare function describe<T>(description: string): checks.$ZodCheck<T>;
export declare function meta<T>(metadata: registries.GlobalMeta): checks.$ZodCheck<T>;
export interface $ZodStringBoolParams extends TypeParams {
truthy?: string[];
falsy?: string[];
/**
* Options: `"sensitive"`, `"insensitive"`
*
* @default `"insensitive"`
*/
case?: "sensitive" | "insensitive" | undefined;
}
export declare function _stringbool(Classes: {
Codec?: typeof schemas.$ZodCodec;
Boolean?: typeof schemas.$ZodBoolean;
String?: typeof schemas.$ZodString;
}, _params?: string | $ZodStringBoolParams): schemas.$ZodCodec<schemas.$ZodString, schemas.$ZodBoolean>;
export declare function _stringFormat<Format extends string>(Class: typeof schemas.$ZodCustomStringFormat, format: Format, fnOrRegex: ((arg: string) => util.MaybeAsync<unknown>) | RegExp, _params?: string | $ZodStringFormatParams): schemas.$ZodCustomStringFormat<Format>;
+1107
View File
File diff suppressed because it is too large Load Diff
+561
View File
@@ -0,0 +1,561 @@
"use strict";
// import { $ZodType } from "./schemas.js";
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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.$ZodCheckOverwrite = exports.$ZodCheckMimeType = exports.$ZodCheckProperties = exports.$ZodCheckProperty = exports.$ZodCheckEndsWith = exports.$ZodCheckStartsWith = exports.$ZodCheckIncludes = exports.$ZodCheckUpperCase = exports.$ZodCheckLowerCase = exports.$ZodCheckRegex = exports.$ZodCheckStringFormat = exports.$ZodCheckLengthEquals = exports.$ZodCheckMinLength = exports.$ZodCheckMaxLength = exports.$ZodCheckSizeEquals = exports.$ZodCheckMinSize = exports.$ZodCheckMaxSize = exports.$ZodCheckBigIntFormat = exports.$ZodCheckNumberFormat = exports.$ZodCheckMultipleOf = exports.$ZodCheckGreaterThan = exports.$ZodCheckLessThan = exports.$ZodCheck = void 0;
const core = __importStar(require("./core.cjs"));
const regexes = __importStar(require("./regexes.cjs"));
const util = __importStar(require("./util.cjs"));
exports.$ZodCheck = core.$constructor("$ZodCheck", (inst, def) => {
var _a;
inst._zod ?? (inst._zod = {});
inst._zod.def = def;
(_a = inst._zod).onattach ?? (_a.onattach = []);
});
/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */
const _whenHasSize = (payload) => {
const val = payload.value;
return !util.nullish(val) && val.size !== undefined;
};
/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */
const _whenHasLength = (payload) => {
const val = payload.value;
return !util.nullish(val) && val.length !== undefined;
};
const numericOriginMap = {
number: "number",
bigint: "bigint",
object: "date",
};
exports.$ZodCheckLessThan = core.$constructor("$ZodCheckLessThan", (inst, def) => {
exports.$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
return;
}
payload.issues.push({
origin: numericOriginMap[typeof payload.value] ?? origin,
code: "too_big",
maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
input: payload.value,
inclusive: def.inclusive,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckGreaterThan = core.$constructor("$ZodCheckGreaterThan", (inst, def) => {
exports.$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
return;
}
payload.issues.push({
origin: numericOriginMap[typeof payload.value] ?? origin,
code: "too_small",
minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
input: payload.value,
inclusive: def.inclusive,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckMultipleOf =
/*@__PURE__*/ core.$constructor("$ZodCheckMultipleOf", (inst, def) => {
exports.$ZodCheck.init(inst, def);
inst._zod.check = (payload) => {
if (typeof payload.value !== typeof def.value)
throw new Error("Cannot mix number and bigint in multiple_of check.");
const isMultiple = typeof payload.value === "bigint"
? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN
def.value !== BigInt(0) && payload.value % def.value === BigInt(0)
: util.floatSafeRemainder(payload.value, def.value) === 0;
if (isMultiple)
return;
payload.issues.push({
origin: typeof payload.value,
code: "not_multiple_of",
divisor: def.value,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckNumberFormat = core.$constructor("$ZodCheckNumberFormat", (inst, def) => {
exports.$ZodCheck.init(inst, def); // no format checks
def.format = def.format || "float64";
const isInt = def.format?.includes("int");
const origin = isInt ? "int" : "number";
const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];
inst._zod.check = (payload) => {
const input = payload.value;
if (isInt) {
if (!Number.isInteger(input)) {
// invalid_format issue
// payload.issues.push({
// expected: def.format,
// format: def.format,
// code: "invalid_format",
// input,
// inst,
// });
// invalid_type issue
payload.issues.push({
expected: origin,
format: def.format,
code: "invalid_type",
continue: false,
input,
inst,
});
return;
// not_multiple_of issue
// payload.issues.push({
// code: "not_multiple_of",
// origin: "number",
// input,
// inst,
// divisor: 1,
// });
}
if (!Number.isSafeInteger(input)) {
if (input > 0) {
// too_big
payload.issues.push({
input,
code: "too_big",
maximum: Number.MAX_SAFE_INTEGER,
note: "Integers must be within the safe integer range.",
inst,
origin,
inclusive: true,
continue: !def.abort,
});
}
else {
// too_small
payload.issues.push({
input,
code: "too_small",
minimum: Number.MIN_SAFE_INTEGER,
note: "Integers must be within the safe integer range.",
inst,
origin,
inclusive: true,
continue: !def.abort,
});
}
return;
}
}
if (input < minimum) {
payload.issues.push({
origin: "number",
input,
code: "too_small",
minimum,
inclusive: true,
inst,
continue: !def.abort,
});
}
if (input > maximum) {
payload.issues.push({
origin: "number",
input,
code: "too_big",
maximum,
inclusive: true,
inst,
continue: !def.abort,
});
}
};
});
exports.$ZodCheckBigIntFormat = core.$constructor("$ZodCheckBigIntFormat", (inst, def) => {
exports.$ZodCheck.init(inst, def); // no format checks
const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];
inst._zod.check = (payload) => {
const input = payload.value;
if (input < minimum) {
payload.issues.push({
origin: "bigint",
input,
code: "too_small",
minimum: minimum,
inclusive: true,
inst,
continue: !def.abort,
});
}
if (input > maximum) {
payload.issues.push({
origin: "bigint",
input,
code: "too_big",
maximum,
inclusive: true,
inst,
continue: !def.abort,
});
}
};
});
exports.$ZodCheckMaxSize = core.$constructor("$ZodCheckMaxSize", (inst, def) => {
var _a;
exports.$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = _whenHasSize);
inst._zod.check = (payload) => {
const input = payload.value;
const size = input.size;
if (size <= def.maximum)
return;
payload.issues.push({
origin: util.getSizableOrigin(input),
code: "too_big",
maximum: def.maximum,
inclusive: true,
input,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckMinSize = core.$constructor("$ZodCheckMinSize", (inst, def) => {
var _a;
exports.$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = _whenHasSize);
inst._zod.check = (payload) => {
const input = payload.value;
const size = input.size;
if (size >= def.minimum)
return;
payload.issues.push({
origin: util.getSizableOrigin(input),
code: "too_small",
minimum: def.minimum,
inclusive: true,
input,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckSizeEquals = core.$constructor("$ZodCheckSizeEquals", (inst, def) => {
var _a;
exports.$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = _whenHasSize);
inst._zod.check = (payload) => {
const input = payload.value;
const size = input.size;
if (size === def.size)
return;
const tooBig = size > def.size;
payload.issues.push({
origin: util.getSizableOrigin(input),
...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }),
inclusive: true,
exact: true,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckMaxLength = core.$constructor("$ZodCheckMaxLength", (inst, def) => {
var _a;
exports.$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
const units = input.length;
// Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted.
const length = typeof input === "string" && units > def.maximum ? util.codePointLength(input) : units;
if (length <= def.maximum)
return;
const origin = util.getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_big",
maximum: def.maximum,
inclusive: true,
input,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckMinLength = core.$constructor("$ZodCheckMinLength", (inst, def) => {
var _a;
exports.$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
const units = input.length;
// A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt.
const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2
? util.codePointLength(input)
: units;
if (length >= def.minimum)
return;
const origin = util.getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_small",
minimum: def.minimum,
inclusive: true,
input,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckLengthEquals = core.$constructor("$ZodCheckLengthEquals", (inst, def) => {
var _a;
exports.$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
const units = input.length;
// A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures.
const length = typeof input === "string" && units >= def.length && units <= def.length * 2
? util.codePointLength(input)
: units;
if (length === def.length)
return;
const origin = util.getLengthableOrigin(input);
const tooBig = length > def.length;
payload.issues.push({
origin,
...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }),
inclusive: true,
exact: true,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckStringFormat = core.$constructor("$ZodCheckStringFormat", (inst, def) => {
var _a, _b;
exports.$ZodCheck.init(inst, def);
if (def.pattern)
(_a = inst._zod).check ?? (_a.check = (payload) => {
def.pattern.lastIndex = 0;
if (def.pattern.test(payload.value))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: def.format,
input: payload.value,
...(def.pattern ? { pattern: def.pattern.toString() } : {}),
inst,
continue: !def.abort,
});
});
else
(_b = inst._zod).check ?? (_b.check = () => { });
});
exports.$ZodCheckRegex = core.$constructor("$ZodCheckRegex", (inst, def) => {
exports.$ZodCheckStringFormat.init(inst, def);
inst._zod.check = (payload) => {
def.pattern.lastIndex = 0;
if (def.pattern.test(payload.value))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "regex",
input: payload.value,
pattern: def.pattern.toString(),
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckLowerCase = core.$constructor("$ZodCheckLowerCase", (inst, def) => {
def.pattern ?? (def.pattern = regexes.lowercase);
exports.$ZodCheckStringFormat.init(inst, def);
});
exports.$ZodCheckUpperCase = core.$constructor("$ZodCheckUpperCase", (inst, def) => {
def.pattern ?? (def.pattern = regexes.uppercase);
exports.$ZodCheckStringFormat.init(inst, def);
});
exports.$ZodCheckIncludes = core.$constructor("$ZodCheckIncludes", (inst, def) => {
exports.$ZodCheck.init(inst, def);
const escapedRegex = util.escapeRegex(def.includes);
// `String.prototype.includes(sub, position)` matches `sub` at `position`
// OR LATER, so the pattern must allow at least `position` leading chars
// (`{N,}`), not exactly `position` chars (`{N}`).
const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);
def.pattern = pattern;
inst._zod.check = (payload) => {
if (payload.value.includes(def.includes, def.position))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "includes",
includes: def.includes,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckStartsWith = core.$constructor("$ZodCheckStartsWith", (inst, def) => {
exports.$ZodCheck.init(inst, def);
const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);
def.pattern ?? (def.pattern = pattern);
inst._zod.check = (payload) => {
if (payload.value.startsWith(def.prefix))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "starts_with",
prefix: def.prefix,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckEndsWith = core.$constructor("$ZodCheckEndsWith", (inst, def) => {
exports.$ZodCheck.init(inst, def);
const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);
def.pattern ?? (def.pattern = pattern);
inst._zod.check = (payload) => {
if (payload.value.endsWith(def.suffix))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "ends_with",
suffix: def.suffix,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
///////////////////////////////////
///// $ZodCheckProperty /////
///////////////////////////////////
function handleCheckPropertyResult(result, payload, property) {
if (result.issues.length) {
payload.issues.push(...util.prefixIssues(property, result.issues));
}
}
exports.$ZodCheckProperty = core.$constructor("$ZodCheckProperty", (inst, def) => {
exports.$ZodCheck.init(inst, def);
inst._zod.check = (payload) => {
const result = def.schema._zod.run({
value: payload.value[def.property],
issues: [],
}, {});
if (result instanceof Promise) {
return result.then((result) => handleCheckPropertyResult(result, payload, def.property));
}
handleCheckPropertyResult(result, payload, def.property);
return;
};
});
exports.$ZodCheckProperties = core.$constructor("$ZodCheckProperties", (inst, def) => {
exports.$ZodCheck.init(inst, def);
util.hide(inst, Symbol.iterator, function* () {
yield inst;
});
// key and schema snapshotted together: reading one live and the other cached lets a later mutation of the caller's shape object pair a stale key with a missing schema
let entries;
inst._zod.check = (payload) => {
// the base schema already typed the value, so only a nullish one is rejected here: the properties read on a primitive too, matching z.property() on a string's length
if (payload.value == null) {
payload.issues.push({ expected: "object", code: "invalid_type", input: payload.value, inst });
return undefined;
}
entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]]));
const input = payload.value;
let proms;
for (const [key, schema] of entries) {
const result = schema._zod.run({ value: input[key], issues: [] }, {});
if (result instanceof Promise) {
proms ?? (proms = []);
proms.push(result.then((result) => handleCheckPropertyResult(result, payload, key)));
}
else {
handleCheckPropertyResult(result, payload, key);
}
}
if (proms)
return Promise.all(proms).then(() => undefined);
return undefined;
};
});
exports.$ZodCheckMimeType = core.$constructor("$ZodCheckMimeType", (inst, def) => {
exports.$ZodCheck.init(inst, def);
const mimeSet = new Set(def.mime);
inst._zod.check = (payload) => {
if (mimeSet.has(payload.value.type))
return;
payload.issues.push({
code: "invalid_value",
values: def.mime,
input: payload.value.type,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckOverwrite = core.$constructor("$ZodCheckOverwrite", (inst, def) => {
exports.$ZodCheck.init(inst, def);
inst._zod.check = (payload) => {
payload.value = def.tx(payload.value);
};
});
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+294
View File
@@ -0,0 +1,294 @@
import * as core from "./core.cjs";
import type * as errors from "./errors.cjs";
import type * as schemas from "./schemas.cjs";
import * as util from "./util.cjs";
export interface $ZodCheckDef {
check: string;
error?: errors.$ZodErrorMap<never> | undefined;
/** If true, no later checks will be executed if this check fails. Default `false`. */
abort?: boolean | undefined;
/** If provided, the check runs only when this returns `true`. By default, it is skipped if prior parsing produced aborting issues. */
when?: ((payload: schemas.ParsePayload) => boolean) | undefined;
}
export interface $ZodCheckInternals<T> {
def: $ZodCheckDef;
/** The set of issues this check might throw. */
issc?: errors.$ZodIssueBase;
check(payload: schemas.ParsePayload<T>): util.MaybeAsync<void>;
onattach: ((schema: schemas.$ZodType) => void)[];
}
export interface $ZodCheck<in T = never> {
_zod: $ZodCheckInternals<T>;
}
export declare const $ZodCheck: core.$constructor<$ZodCheck<any>>;
export interface $ZodCheckLessThanDef extends $ZodCheckDef {
check: "less_than";
value: util.Numeric;
inclusive: boolean;
}
export interface $ZodCheckLessThanInternals<T extends util.Numeric = util.Numeric> extends $ZodCheckInternals<T> {
def: $ZodCheckLessThanDef;
issc: errors.$ZodIssueTooBig<T>;
}
export interface $ZodCheckLessThan<T extends util.Numeric = util.Numeric> extends $ZodCheck<T> {
_zod: $ZodCheckLessThanInternals<T>;
}
export declare const $ZodCheckLessThan: core.$constructor<$ZodCheckLessThan>;
export interface $ZodCheckGreaterThanDef extends $ZodCheckDef {
check: "greater_than";
value: util.Numeric;
inclusive: boolean;
}
export interface $ZodCheckGreaterThanInternals<T extends util.Numeric = util.Numeric> extends $ZodCheckInternals<T> {
def: $ZodCheckGreaterThanDef;
issc: errors.$ZodIssueTooSmall<T>;
}
export interface $ZodCheckGreaterThan<T extends util.Numeric = util.Numeric> extends $ZodCheck<T> {
_zod: $ZodCheckGreaterThanInternals<T>;
}
export declare const $ZodCheckGreaterThan: core.$constructor<$ZodCheckGreaterThan>;
export interface $ZodCheckMultipleOfDef<T extends number | bigint = number | bigint> extends $ZodCheckDef {
check: "multiple_of";
value: T;
}
export interface $ZodCheckMultipleOfInternals<T extends number | bigint = number | bigint> extends $ZodCheckInternals<T> {
def: $ZodCheckMultipleOfDef<T>;
issc: errors.$ZodIssueNotMultipleOf;
}
export interface $ZodCheckMultipleOf<T extends number | bigint = number | bigint> extends $ZodCheck<T> {
_zod: $ZodCheckMultipleOfInternals<T>;
}
export declare const $ZodCheckMultipleOf: core.$constructor<$ZodCheckMultipleOf<number | bigint>>;
export type $ZodNumberFormats = "int32" | "uint32" | "float32" | "float64" | "safeint";
export interface $ZodCheckNumberFormatDef<Format extends $ZodNumberFormats = $ZodNumberFormats> extends $ZodCheckDef {
check: "number_format";
format: Format;
}
export interface $ZodCheckNumberFormatInternals<Format extends $ZodNumberFormats = $ZodNumberFormats> extends $ZodCheckInternals<number> {
def: $ZodCheckNumberFormatDef<Format>;
issc: errors.$ZodIssueInvalidType | errors.$ZodIssueTooBig<"number"> | errors.$ZodIssueTooSmall<"number">;
}
export interface $ZodCheckNumberFormat<Format extends $ZodNumberFormats = $ZodNumberFormats> extends $ZodCheck<number> {
_zod: $ZodCheckNumberFormatInternals<Format>;
}
export declare const $ZodCheckNumberFormat: core.$constructor<$ZodCheckNumberFormat>;
export type $ZodBigIntFormats = "int64" | "uint64";
export interface $ZodCheckBigIntFormatDef<Format extends $ZodBigIntFormats = $ZodBigIntFormats> extends $ZodCheckDef {
check: "bigint_format";
format: Format;
}
export interface $ZodCheckBigIntFormatInternals<Format extends $ZodBigIntFormats = $ZodBigIntFormats> extends $ZodCheckInternals<bigint> {
def: $ZodCheckBigIntFormatDef<Format>;
issc: errors.$ZodIssueTooBig<"bigint"> | errors.$ZodIssueTooSmall<"bigint">;
}
export interface $ZodCheckBigIntFormat<Format extends $ZodBigIntFormats = $ZodBigIntFormats> extends $ZodCheck<bigint> {
_zod: $ZodCheckBigIntFormatInternals<Format>;
}
export declare const $ZodCheckBigIntFormat: core.$constructor<$ZodCheckBigIntFormat>;
export interface $ZodCheckMaxSizeDef extends $ZodCheckDef {
check: "max_size";
maximum: number;
}
export interface $ZodCheckMaxSizeInternals<T extends util.HasSize = util.HasSize> extends $ZodCheckInternals<T> {
def: $ZodCheckMaxSizeDef;
issc: errors.$ZodIssueTooBig<T>;
}
export interface $ZodCheckMaxSize<T extends util.HasSize = util.HasSize> extends $ZodCheck<T> {
_zod: $ZodCheckMaxSizeInternals<T>;
}
export declare const $ZodCheckMaxSize: core.$constructor<$ZodCheckMaxSize>;
export interface $ZodCheckMinSizeDef extends $ZodCheckDef {
check: "min_size";
minimum: number;
}
export interface $ZodCheckMinSizeInternals<T extends util.HasSize = util.HasSize> extends $ZodCheckInternals<T> {
def: $ZodCheckMinSizeDef;
issc: errors.$ZodIssueTooSmall<T>;
}
export interface $ZodCheckMinSize<T extends util.HasSize = util.HasSize> extends $ZodCheck<T> {
_zod: $ZodCheckMinSizeInternals<T>;
}
export declare const $ZodCheckMinSize: core.$constructor<$ZodCheckMinSize>;
export interface $ZodCheckSizeEqualsDef extends $ZodCheckDef {
check: "size_equals";
size: number;
}
export interface $ZodCheckSizeEqualsInternals<T extends util.HasSize = util.HasSize> extends $ZodCheckInternals<T> {
def: $ZodCheckSizeEqualsDef;
issc: errors.$ZodIssueTooBig<T> | errors.$ZodIssueTooSmall<T>;
}
export interface $ZodCheckSizeEquals<T extends util.HasSize = util.HasSize> extends $ZodCheck<T> {
_zod: $ZodCheckSizeEqualsInternals<T>;
}
export declare const $ZodCheckSizeEquals: core.$constructor<$ZodCheckSizeEquals>;
export interface $ZodCheckMaxLengthDef extends $ZodCheckDef {
check: "max_length";
maximum: number;
}
export interface $ZodCheckMaxLengthInternals<T extends util.HasLength = util.HasLength> extends $ZodCheckInternals<T> {
def: $ZodCheckMaxLengthDef;
issc: errors.$ZodIssueTooBig<T>;
}
export interface $ZodCheckMaxLength<T extends util.HasLength = util.HasLength> extends $ZodCheck<T> {
_zod: $ZodCheckMaxLengthInternals<T>;
}
export declare const $ZodCheckMaxLength: core.$constructor<$ZodCheckMaxLength>;
export interface $ZodCheckMinLengthDef extends $ZodCheckDef {
check: "min_length";
minimum: number;
}
export interface $ZodCheckMinLengthInternals<T extends util.HasLength = util.HasLength> extends $ZodCheckInternals<T> {
def: $ZodCheckMinLengthDef;
issc: errors.$ZodIssueTooSmall<T>;
}
export interface $ZodCheckMinLength<T extends util.HasLength = util.HasLength> extends $ZodCheck<T> {
_zod: $ZodCheckMinLengthInternals<T>;
}
export declare const $ZodCheckMinLength: core.$constructor<$ZodCheckMinLength>;
export interface $ZodCheckLengthEqualsDef extends $ZodCheckDef {
check: "length_equals";
length: number;
}
export interface $ZodCheckLengthEqualsInternals<T extends util.HasLength = util.HasLength> extends $ZodCheckInternals<T> {
def: $ZodCheckLengthEqualsDef;
issc: errors.$ZodIssueTooBig<T> | errors.$ZodIssueTooSmall<T>;
}
export interface $ZodCheckLengthEquals<T extends util.HasLength = util.HasLength> extends $ZodCheck<T> {
_zod: $ZodCheckLengthEqualsInternals<T>;
}
export declare const $ZodCheckLengthEquals: core.$constructor<$ZodCheckLengthEquals>;
export type $ZodStringFormats = "email" | "url" | "emoji" | "uuid" | "guid" | "nanoid" | "cuid" | "cuid2" | "ulid" | "xid" | "ksuid" | "datetime" | "date" | "time" | "duration" | "ipv4" | "ipv6" | "cidrv4" | "cidrv6" | "base64" | "base64url" | "json_string" | "e164" | "credit_card" | "iban" | "lowercase" | "uppercase" | "regex" | "jwt" | "starts_with" | "ends_with" | "includes";
export interface $ZodCheckStringFormatDef<Format extends string = string> extends $ZodCheckDef {
check: "string_format";
format: Format;
pattern?: RegExp | undefined;
}
export interface $ZodCheckStringFormatInternals extends $ZodCheckInternals<string> {
def: $ZodCheckStringFormatDef;
issc: errors.$ZodIssueInvalidStringFormat;
}
export interface $ZodCheckStringFormat extends $ZodCheck<string> {
_zod: $ZodCheckStringFormatInternals;
}
export declare const $ZodCheckStringFormat: core.$constructor<$ZodCheckStringFormat>;
export interface $ZodCheckRegexDef extends $ZodCheckStringFormatDef {
format: "regex";
pattern: RegExp;
}
export interface $ZodCheckRegexInternals extends $ZodCheckInternals<string> {
def: $ZodCheckRegexDef;
issc: errors.$ZodIssueInvalidStringFormat;
}
export interface $ZodCheckRegex extends $ZodCheck<string> {
_zod: $ZodCheckRegexInternals;
}
export declare const $ZodCheckRegex: core.$constructor<$ZodCheckRegex>;
export interface $ZodCheckLowerCaseDef extends $ZodCheckStringFormatDef<"lowercase"> {
}
export interface $ZodCheckLowerCaseInternals extends $ZodCheckInternals<string> {
def: $ZodCheckLowerCaseDef;
issc: errors.$ZodIssueInvalidStringFormat;
}
export interface $ZodCheckLowerCase extends $ZodCheck<string> {
_zod: $ZodCheckLowerCaseInternals;
}
export declare const $ZodCheckLowerCase: core.$constructor<$ZodCheckLowerCase>;
export interface $ZodCheckUpperCaseDef extends $ZodCheckStringFormatDef<"uppercase"> {
}
export interface $ZodCheckUpperCaseInternals extends $ZodCheckInternals<string> {
def: $ZodCheckUpperCaseDef;
issc: errors.$ZodIssueInvalidStringFormat;
}
export interface $ZodCheckUpperCase extends $ZodCheck<string> {
_zod: $ZodCheckUpperCaseInternals;
}
export declare const $ZodCheckUpperCase: core.$constructor<$ZodCheckUpperCase>;
export interface $ZodCheckIncludesDef extends $ZodCheckStringFormatDef<"includes"> {
includes: string;
position?: number | undefined;
}
export interface $ZodCheckIncludesInternals extends $ZodCheckInternals<string> {
def: $ZodCheckIncludesDef;
issc: errors.$ZodIssueInvalidStringFormat;
}
export interface $ZodCheckIncludes extends $ZodCheck<string> {
_zod: $ZodCheckIncludesInternals;
}
export declare const $ZodCheckIncludes: core.$constructor<$ZodCheckIncludes>;
export interface $ZodCheckStartsWithDef extends $ZodCheckStringFormatDef<"starts_with"> {
prefix: string;
}
export interface $ZodCheckStartsWithInternals extends $ZodCheckInternals<string> {
def: $ZodCheckStartsWithDef;
issc: errors.$ZodIssueInvalidStringFormat;
}
export interface $ZodCheckStartsWith extends $ZodCheck<string> {
_zod: $ZodCheckStartsWithInternals;
}
export declare const $ZodCheckStartsWith: core.$constructor<$ZodCheckStartsWith>;
export interface $ZodCheckEndsWithDef extends $ZodCheckStringFormatDef<"ends_with"> {
suffix: string;
}
export interface $ZodCheckEndsWithInternals extends $ZodCheckInternals<string> {
def: $ZodCheckEndsWithDef;
issc: errors.$ZodIssueInvalidStringFormat;
}
export interface $ZodCheckEndsWith extends $ZodCheckInternals<string> {
_zod: $ZodCheckEndsWithInternals;
}
export declare const $ZodCheckEndsWith: core.$constructor<$ZodCheckEndsWith>;
export interface $ZodCheckPropertyDef extends $ZodCheckDef {
check: "property";
property: string;
schema: schemas.$ZodType;
}
export interface $ZodCheckPropertyInternals<T extends object = object> extends $ZodCheckInternals<T> {
def: $ZodCheckPropertyDef;
issc: errors.$ZodIssue;
}
export interface $ZodCheckProperty<T extends object = object> extends $ZodCheck<T> {
_zod: $ZodCheckPropertyInternals<T>;
}
export declare const $ZodCheckProperty: core.$constructor<$ZodCheckProperty>;
export interface $ZodCheckPropertiesDef<Shape extends schemas.$ZodShape = schemas.$ZodShape> extends $ZodCheckDef {
check: "properties";
shape: Shape;
}
export type $ZodCheckPropertiesInput<Shape extends schemas.$ZodShape = schemas.$ZodShape> = {
-readonly [k in keyof Shape]: util.Widen<core.input<Shape[k]>>;
};
export interface $ZodCheckPropertiesInternals<Shape extends schemas.$ZodShape = schemas.$ZodShape> extends $ZodCheckInternals<$ZodCheckPropertiesInput<Shape>> {
def: $ZodCheckPropertiesDef<Shape>;
issc: errors.$ZodIssue;
}
export interface $ZodCheckProperties<Shape extends schemas.$ZodShape = schemas.$ZodShape> extends $ZodCheck<$ZodCheckPropertiesInput<Shape>> {
_zod: $ZodCheckPropertiesInternals<Shape>;
[Symbol.iterator](): Iterator<this>;
}
export declare const $ZodCheckProperties: core.$constructor<$ZodCheckProperties>;
export interface $ZodCheckMimeTypeDef extends $ZodCheckDef {
check: "mime_type";
mime: util.MimeTypes[];
}
export interface $ZodCheckMimeTypeInternals<T extends schemas.File = schemas.File> extends $ZodCheckInternals<T> {
def: $ZodCheckMimeTypeDef;
issc: errors.$ZodIssueInvalidValue;
}
export interface $ZodCheckMimeType<T extends schemas.File = schemas.File> extends $ZodCheck<T> {
_zod: $ZodCheckMimeTypeInternals<T>;
}
export declare const $ZodCheckMimeType: core.$constructor<$ZodCheckMimeType>;
export interface $ZodCheckOverwriteDef<T = unknown> extends $ZodCheckDef {
check: "overwrite";
tx(value: T): T;
}
export interface $ZodCheckOverwriteInternals<T = unknown> extends $ZodCheckInternals<T> {
def: $ZodCheckOverwriteDef<T>;
issc: never;
}
export interface $ZodCheckOverwrite<T = unknown> extends $ZodCheck<T> {
_zod: $ZodCheckOverwriteInternals<T>;
}
export declare const $ZodCheckOverwrite: core.$constructor<$ZodCheckOverwrite>;
export type $ZodChecks = $ZodCheckLessThan | $ZodCheckGreaterThan | $ZodCheckMultipleOf | $ZodCheckNumberFormat | $ZodCheckBigIntFormat | $ZodCheckMaxSize | $ZodCheckMinSize | $ZodCheckSizeEquals | $ZodCheckMaxLength | $ZodCheckMinLength | $ZodCheckLengthEquals | $ZodCheckStringFormat | $ZodCheckProperty | $ZodCheckMimeType | $ZodCheckOverwrite;
export type $ZodStringFormatChecks = $ZodCheckRegex | $ZodCheckLowerCase | $ZodCheckUpperCase | $ZodCheckIncludes | $ZodCheckStartsWith | $ZodCheckEndsWith | schemas.$ZodStringFormatTypes;
+294
View File
@@ -0,0 +1,294 @@
import * as core from "./core.js";
import type * as errors from "./errors.js";
import type * as schemas from "./schemas.js";
import * as util from "./util.js";
export interface $ZodCheckDef {
check: string;
error?: errors.$ZodErrorMap<never> | undefined;
/** If true, no later checks will be executed if this check fails. Default `false`. */
abort?: boolean | undefined;
/** If provided, the check runs only when this returns `true`. By default, it is skipped if prior parsing produced aborting issues. */
when?: ((payload: schemas.ParsePayload) => boolean) | undefined;
}
export interface $ZodCheckInternals<T> {
def: $ZodCheckDef;
/** The set of issues this check might throw. */
issc?: errors.$ZodIssueBase;
check(payload: schemas.ParsePayload<T>): util.MaybeAsync<void>;
onattach: ((schema: schemas.$ZodType) => void)[];
}
export interface $ZodCheck<in T = never> {
_zod: $ZodCheckInternals<T>;
}
export declare const $ZodCheck: core.$constructor<$ZodCheck<any>>;
export interface $ZodCheckLessThanDef extends $ZodCheckDef {
check: "less_than";
value: util.Numeric;
inclusive: boolean;
}
export interface $ZodCheckLessThanInternals<T extends util.Numeric = util.Numeric> extends $ZodCheckInternals<T> {
def: $ZodCheckLessThanDef;
issc: errors.$ZodIssueTooBig<T>;
}
export interface $ZodCheckLessThan<T extends util.Numeric = util.Numeric> extends $ZodCheck<T> {
_zod: $ZodCheckLessThanInternals<T>;
}
export declare const $ZodCheckLessThan: core.$constructor<$ZodCheckLessThan>;
export interface $ZodCheckGreaterThanDef extends $ZodCheckDef {
check: "greater_than";
value: util.Numeric;
inclusive: boolean;
}
export interface $ZodCheckGreaterThanInternals<T extends util.Numeric = util.Numeric> extends $ZodCheckInternals<T> {
def: $ZodCheckGreaterThanDef;
issc: errors.$ZodIssueTooSmall<T>;
}
export interface $ZodCheckGreaterThan<T extends util.Numeric = util.Numeric> extends $ZodCheck<T> {
_zod: $ZodCheckGreaterThanInternals<T>;
}
export declare const $ZodCheckGreaterThan: core.$constructor<$ZodCheckGreaterThan>;
export interface $ZodCheckMultipleOfDef<T extends number | bigint = number | bigint> extends $ZodCheckDef {
check: "multiple_of";
value: T;
}
export interface $ZodCheckMultipleOfInternals<T extends number | bigint = number | bigint> extends $ZodCheckInternals<T> {
def: $ZodCheckMultipleOfDef<T>;
issc: errors.$ZodIssueNotMultipleOf;
}
export interface $ZodCheckMultipleOf<T extends number | bigint = number | bigint> extends $ZodCheck<T> {
_zod: $ZodCheckMultipleOfInternals<T>;
}
export declare const $ZodCheckMultipleOf: core.$constructor<$ZodCheckMultipleOf<number | bigint>>;
export type $ZodNumberFormats = "int32" | "uint32" | "float32" | "float64" | "safeint";
export interface $ZodCheckNumberFormatDef<Format extends $ZodNumberFormats = $ZodNumberFormats> extends $ZodCheckDef {
check: "number_format";
format: Format;
}
export interface $ZodCheckNumberFormatInternals<Format extends $ZodNumberFormats = $ZodNumberFormats> extends $ZodCheckInternals<number> {
def: $ZodCheckNumberFormatDef<Format>;
issc: errors.$ZodIssueInvalidType | errors.$ZodIssueTooBig<"number"> | errors.$ZodIssueTooSmall<"number">;
}
export interface $ZodCheckNumberFormat<Format extends $ZodNumberFormats = $ZodNumberFormats> extends $ZodCheck<number> {
_zod: $ZodCheckNumberFormatInternals<Format>;
}
export declare const $ZodCheckNumberFormat: core.$constructor<$ZodCheckNumberFormat>;
export type $ZodBigIntFormats = "int64" | "uint64";
export interface $ZodCheckBigIntFormatDef<Format extends $ZodBigIntFormats = $ZodBigIntFormats> extends $ZodCheckDef {
check: "bigint_format";
format: Format;
}
export interface $ZodCheckBigIntFormatInternals<Format extends $ZodBigIntFormats = $ZodBigIntFormats> extends $ZodCheckInternals<bigint> {
def: $ZodCheckBigIntFormatDef<Format>;
issc: errors.$ZodIssueTooBig<"bigint"> | errors.$ZodIssueTooSmall<"bigint">;
}
export interface $ZodCheckBigIntFormat<Format extends $ZodBigIntFormats = $ZodBigIntFormats> extends $ZodCheck<bigint> {
_zod: $ZodCheckBigIntFormatInternals<Format>;
}
export declare const $ZodCheckBigIntFormat: core.$constructor<$ZodCheckBigIntFormat>;
export interface $ZodCheckMaxSizeDef extends $ZodCheckDef {
check: "max_size";
maximum: number;
}
export interface $ZodCheckMaxSizeInternals<T extends util.HasSize = util.HasSize> extends $ZodCheckInternals<T> {
def: $ZodCheckMaxSizeDef;
issc: errors.$ZodIssueTooBig<T>;
}
export interface $ZodCheckMaxSize<T extends util.HasSize = util.HasSize> extends $ZodCheck<T> {
_zod: $ZodCheckMaxSizeInternals<T>;
}
export declare const $ZodCheckMaxSize: core.$constructor<$ZodCheckMaxSize>;
export interface $ZodCheckMinSizeDef extends $ZodCheckDef {
check: "min_size";
minimum: number;
}
export interface $ZodCheckMinSizeInternals<T extends util.HasSize = util.HasSize> extends $ZodCheckInternals<T> {
def: $ZodCheckMinSizeDef;
issc: errors.$ZodIssueTooSmall<T>;
}
export interface $ZodCheckMinSize<T extends util.HasSize = util.HasSize> extends $ZodCheck<T> {
_zod: $ZodCheckMinSizeInternals<T>;
}
export declare const $ZodCheckMinSize: core.$constructor<$ZodCheckMinSize>;
export interface $ZodCheckSizeEqualsDef extends $ZodCheckDef {
check: "size_equals";
size: number;
}
export interface $ZodCheckSizeEqualsInternals<T extends util.HasSize = util.HasSize> extends $ZodCheckInternals<T> {
def: $ZodCheckSizeEqualsDef;
issc: errors.$ZodIssueTooBig<T> | errors.$ZodIssueTooSmall<T>;
}
export interface $ZodCheckSizeEquals<T extends util.HasSize = util.HasSize> extends $ZodCheck<T> {
_zod: $ZodCheckSizeEqualsInternals<T>;
}
export declare const $ZodCheckSizeEquals: core.$constructor<$ZodCheckSizeEquals>;
export interface $ZodCheckMaxLengthDef extends $ZodCheckDef {
check: "max_length";
maximum: number;
}
export interface $ZodCheckMaxLengthInternals<T extends util.HasLength = util.HasLength> extends $ZodCheckInternals<T> {
def: $ZodCheckMaxLengthDef;
issc: errors.$ZodIssueTooBig<T>;
}
export interface $ZodCheckMaxLength<T extends util.HasLength = util.HasLength> extends $ZodCheck<T> {
_zod: $ZodCheckMaxLengthInternals<T>;
}
export declare const $ZodCheckMaxLength: core.$constructor<$ZodCheckMaxLength>;
export interface $ZodCheckMinLengthDef extends $ZodCheckDef {
check: "min_length";
minimum: number;
}
export interface $ZodCheckMinLengthInternals<T extends util.HasLength = util.HasLength> extends $ZodCheckInternals<T> {
def: $ZodCheckMinLengthDef;
issc: errors.$ZodIssueTooSmall<T>;
}
export interface $ZodCheckMinLength<T extends util.HasLength = util.HasLength> extends $ZodCheck<T> {
_zod: $ZodCheckMinLengthInternals<T>;
}
export declare const $ZodCheckMinLength: core.$constructor<$ZodCheckMinLength>;
export interface $ZodCheckLengthEqualsDef extends $ZodCheckDef {
check: "length_equals";
length: number;
}
export interface $ZodCheckLengthEqualsInternals<T extends util.HasLength = util.HasLength> extends $ZodCheckInternals<T> {
def: $ZodCheckLengthEqualsDef;
issc: errors.$ZodIssueTooBig<T> | errors.$ZodIssueTooSmall<T>;
}
export interface $ZodCheckLengthEquals<T extends util.HasLength = util.HasLength> extends $ZodCheck<T> {
_zod: $ZodCheckLengthEqualsInternals<T>;
}
export declare const $ZodCheckLengthEquals: core.$constructor<$ZodCheckLengthEquals>;
export type $ZodStringFormats = "email" | "url" | "emoji" | "uuid" | "guid" | "nanoid" | "cuid" | "cuid2" | "ulid" | "xid" | "ksuid" | "datetime" | "date" | "time" | "duration" | "ipv4" | "ipv6" | "cidrv4" | "cidrv6" | "base64" | "base64url" | "json_string" | "e164" | "credit_card" | "iban" | "lowercase" | "uppercase" | "regex" | "jwt" | "starts_with" | "ends_with" | "includes";
export interface $ZodCheckStringFormatDef<Format extends string = string> extends $ZodCheckDef {
check: "string_format";
format: Format;
pattern?: RegExp | undefined;
}
export interface $ZodCheckStringFormatInternals extends $ZodCheckInternals<string> {
def: $ZodCheckStringFormatDef;
issc: errors.$ZodIssueInvalidStringFormat;
}
export interface $ZodCheckStringFormat extends $ZodCheck<string> {
_zod: $ZodCheckStringFormatInternals;
}
export declare const $ZodCheckStringFormat: core.$constructor<$ZodCheckStringFormat>;
export interface $ZodCheckRegexDef extends $ZodCheckStringFormatDef {
format: "regex";
pattern: RegExp;
}
export interface $ZodCheckRegexInternals extends $ZodCheckInternals<string> {
def: $ZodCheckRegexDef;
issc: errors.$ZodIssueInvalidStringFormat;
}
export interface $ZodCheckRegex extends $ZodCheck<string> {
_zod: $ZodCheckRegexInternals;
}
export declare const $ZodCheckRegex: core.$constructor<$ZodCheckRegex>;
export interface $ZodCheckLowerCaseDef extends $ZodCheckStringFormatDef<"lowercase"> {
}
export interface $ZodCheckLowerCaseInternals extends $ZodCheckInternals<string> {
def: $ZodCheckLowerCaseDef;
issc: errors.$ZodIssueInvalidStringFormat;
}
export interface $ZodCheckLowerCase extends $ZodCheck<string> {
_zod: $ZodCheckLowerCaseInternals;
}
export declare const $ZodCheckLowerCase: core.$constructor<$ZodCheckLowerCase>;
export interface $ZodCheckUpperCaseDef extends $ZodCheckStringFormatDef<"uppercase"> {
}
export interface $ZodCheckUpperCaseInternals extends $ZodCheckInternals<string> {
def: $ZodCheckUpperCaseDef;
issc: errors.$ZodIssueInvalidStringFormat;
}
export interface $ZodCheckUpperCase extends $ZodCheck<string> {
_zod: $ZodCheckUpperCaseInternals;
}
export declare const $ZodCheckUpperCase: core.$constructor<$ZodCheckUpperCase>;
export interface $ZodCheckIncludesDef extends $ZodCheckStringFormatDef<"includes"> {
includes: string;
position?: number | undefined;
}
export interface $ZodCheckIncludesInternals extends $ZodCheckInternals<string> {
def: $ZodCheckIncludesDef;
issc: errors.$ZodIssueInvalidStringFormat;
}
export interface $ZodCheckIncludes extends $ZodCheck<string> {
_zod: $ZodCheckIncludesInternals;
}
export declare const $ZodCheckIncludes: core.$constructor<$ZodCheckIncludes>;
export interface $ZodCheckStartsWithDef extends $ZodCheckStringFormatDef<"starts_with"> {
prefix: string;
}
export interface $ZodCheckStartsWithInternals extends $ZodCheckInternals<string> {
def: $ZodCheckStartsWithDef;
issc: errors.$ZodIssueInvalidStringFormat;
}
export interface $ZodCheckStartsWith extends $ZodCheck<string> {
_zod: $ZodCheckStartsWithInternals;
}
export declare const $ZodCheckStartsWith: core.$constructor<$ZodCheckStartsWith>;
export interface $ZodCheckEndsWithDef extends $ZodCheckStringFormatDef<"ends_with"> {
suffix: string;
}
export interface $ZodCheckEndsWithInternals extends $ZodCheckInternals<string> {
def: $ZodCheckEndsWithDef;
issc: errors.$ZodIssueInvalidStringFormat;
}
export interface $ZodCheckEndsWith extends $ZodCheckInternals<string> {
_zod: $ZodCheckEndsWithInternals;
}
export declare const $ZodCheckEndsWith: core.$constructor<$ZodCheckEndsWith>;
export interface $ZodCheckPropertyDef extends $ZodCheckDef {
check: "property";
property: string;
schema: schemas.$ZodType;
}
export interface $ZodCheckPropertyInternals<T extends object = object> extends $ZodCheckInternals<T> {
def: $ZodCheckPropertyDef;
issc: errors.$ZodIssue;
}
export interface $ZodCheckProperty<T extends object = object> extends $ZodCheck<T> {
_zod: $ZodCheckPropertyInternals<T>;
}
export declare const $ZodCheckProperty: core.$constructor<$ZodCheckProperty>;
export interface $ZodCheckPropertiesDef<Shape extends schemas.$ZodShape = schemas.$ZodShape> extends $ZodCheckDef {
check: "properties";
shape: Shape;
}
export type $ZodCheckPropertiesInput<Shape extends schemas.$ZodShape = schemas.$ZodShape> = {
-readonly [k in keyof Shape]: util.Widen<core.input<Shape[k]>>;
};
export interface $ZodCheckPropertiesInternals<Shape extends schemas.$ZodShape = schemas.$ZodShape> extends $ZodCheckInternals<$ZodCheckPropertiesInput<Shape>> {
def: $ZodCheckPropertiesDef<Shape>;
issc: errors.$ZodIssue;
}
export interface $ZodCheckProperties<Shape extends schemas.$ZodShape = schemas.$ZodShape> extends $ZodCheck<$ZodCheckPropertiesInput<Shape>> {
_zod: $ZodCheckPropertiesInternals<Shape>;
[Symbol.iterator](): Iterator<this>;
}
export declare const $ZodCheckProperties: core.$constructor<$ZodCheckProperties>;
export interface $ZodCheckMimeTypeDef extends $ZodCheckDef {
check: "mime_type";
mime: util.MimeTypes[];
}
export interface $ZodCheckMimeTypeInternals<T extends schemas.File = schemas.File> extends $ZodCheckInternals<T> {
def: $ZodCheckMimeTypeDef;
issc: errors.$ZodIssueInvalidValue;
}
export interface $ZodCheckMimeType<T extends schemas.File = schemas.File> extends $ZodCheck<T> {
_zod: $ZodCheckMimeTypeInternals<T>;
}
export declare const $ZodCheckMimeType: core.$constructor<$ZodCheckMimeType>;
export interface $ZodCheckOverwriteDef<T = unknown> extends $ZodCheckDef {
check: "overwrite";
tx(value: T): T;
}
export interface $ZodCheckOverwriteInternals<T = unknown> extends $ZodCheckInternals<T> {
def: $ZodCheckOverwriteDef<T>;
issc: never;
}
export interface $ZodCheckOverwrite<T = unknown> extends $ZodCheck<T> {
_zod: $ZodCheckOverwriteInternals<T>;
}
export declare const $ZodCheckOverwrite: core.$constructor<$ZodCheckOverwrite>;
export type $ZodChecks = $ZodCheckLessThan | $ZodCheckGreaterThan | $ZodCheckMultipleOf | $ZodCheckNumberFormat | $ZodCheckBigIntFormat | $ZodCheckMaxSize | $ZodCheckMinSize | $ZodCheckSizeEquals | $ZodCheckMaxLength | $ZodCheckMinLength | $ZodCheckLengthEquals | $ZodCheckStringFormat | $ZodCheckProperty | $ZodCheckMimeType | $ZodCheckOverwrite;
export type $ZodStringFormatChecks = $ZodCheckRegex | $ZodCheckLowerCase | $ZodCheckUpperCase | $ZodCheckIncludes | $ZodCheckStartsWith | $ZodCheckEndsWith | schemas.$ZodStringFormatTypes;
+516
View File
@@ -0,0 +1,516 @@
// import { $ZodType } from "./schemas.js";
import * as core from "./core.js";
import * as regexes from "./regexes.js";
import * as util from "./util.js";
export const $ZodCheck = /*@__PURE__*/ core.$constructor("$ZodCheck", (inst, def) => {
var _a;
inst._zod ?? (inst._zod = {});
inst._zod.def = def;
(_a = inst._zod).onattach ?? (_a.onattach = []);
});
/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */
const _whenHasSize = (payload) => {
const val = payload.value;
return !util.nullish(val) && val.size !== undefined;
};
/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */
const _whenHasLength = (payload) => {
const val = payload.value;
return !util.nullish(val) && val.length !== undefined;
};
const numericOriginMap = {
number: "number",
bigint: "bigint",
object: "date",
};
export const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor("$ZodCheckLessThan", (inst, def) => {
$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
return;
}
payload.issues.push({
origin: numericOriginMap[typeof payload.value] ?? origin,
code: "too_big",
maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
input: payload.value,
inclusive: def.inclusive,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor("$ZodCheckGreaterThan", (inst, def) => {
$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
return;
}
payload.issues.push({
origin: numericOriginMap[typeof payload.value] ?? origin,
code: "too_small",
minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
input: payload.value,
inclusive: def.inclusive,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckMultipleOf =
/*@__PURE__*/ core.$constructor("$ZodCheckMultipleOf", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.check = (payload) => {
if (typeof payload.value !== typeof def.value)
throw new Error("Cannot mix number and bigint in multiple_of check.");
const isMultiple = typeof payload.value === "bigint"
? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN
def.value !== BigInt(0) && payload.value % def.value === BigInt(0)
: util.floatSafeRemainder(payload.value, def.value) === 0;
if (isMultiple)
return;
payload.issues.push({
origin: typeof payload.value,
code: "not_multiple_of",
divisor: def.value,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor("$ZodCheckNumberFormat", (inst, def) => {
$ZodCheck.init(inst, def); // no format checks
def.format = def.format || "float64";
const isInt = def.format?.includes("int");
const origin = isInt ? "int" : "number";
const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];
inst._zod.check = (payload) => {
const input = payload.value;
if (isInt) {
if (!Number.isInteger(input)) {
// invalid_format issue
// payload.issues.push({
// expected: def.format,
// format: def.format,
// code: "invalid_format",
// input,
// inst,
// });
// invalid_type issue
payload.issues.push({
expected: origin,
format: def.format,
code: "invalid_type",
continue: false,
input,
inst,
});
return;
// not_multiple_of issue
// payload.issues.push({
// code: "not_multiple_of",
// origin: "number",
// input,
// inst,
// divisor: 1,
// });
}
if (!Number.isSafeInteger(input)) {
if (input > 0) {
// too_big
payload.issues.push({
input,
code: "too_big",
maximum: Number.MAX_SAFE_INTEGER,
note: "Integers must be within the safe integer range.",
inst,
origin,
inclusive: true,
continue: !def.abort,
});
}
else {
// too_small
payload.issues.push({
input,
code: "too_small",
minimum: Number.MIN_SAFE_INTEGER,
note: "Integers must be within the safe integer range.",
inst,
origin,
inclusive: true,
continue: !def.abort,
});
}
return;
}
}
if (input < minimum) {
payload.issues.push({
origin: "number",
input,
code: "too_small",
minimum,
inclusive: true,
inst,
continue: !def.abort,
});
}
if (input > maximum) {
payload.issues.push({
origin: "number",
input,
code: "too_big",
maximum,
inclusive: true,
inst,
continue: !def.abort,
});
}
};
});
export const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor("$ZodCheckBigIntFormat", (inst, def) => {
$ZodCheck.init(inst, def); // no format checks
const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];
inst._zod.check = (payload) => {
const input = payload.value;
if (input < minimum) {
payload.issues.push({
origin: "bigint",
input,
code: "too_small",
minimum: minimum,
inclusive: true,
inst,
continue: !def.abort,
});
}
if (input > maximum) {
payload.issues.push({
origin: "bigint",
input,
code: "too_big",
maximum,
inclusive: true,
inst,
continue: !def.abort,
});
}
};
});
export const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor("$ZodCheckMaxSize", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = _whenHasSize);
inst._zod.check = (payload) => {
const input = payload.value;
const size = input.size;
if (size <= def.maximum)
return;
payload.issues.push({
origin: util.getSizableOrigin(input),
code: "too_big",
maximum: def.maximum,
inclusive: true,
input,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor("$ZodCheckMinSize", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = _whenHasSize);
inst._zod.check = (payload) => {
const input = payload.value;
const size = input.size;
if (size >= def.minimum)
return;
payload.issues.push({
origin: util.getSizableOrigin(input),
code: "too_small",
minimum: def.minimum,
inclusive: true,
input,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor("$ZodCheckSizeEquals", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = _whenHasSize);
inst._zod.check = (payload) => {
const input = payload.value;
const size = input.size;
if (size === def.size)
return;
const tooBig = size > def.size;
payload.issues.push({
origin: util.getSizableOrigin(input),
...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }),
inclusive: true,
exact: true,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor("$ZodCheckMaxLength", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
const units = input.length;
// Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted.
const length = typeof input === "string" && units > def.maximum ? util.codePointLength(input) : units;
if (length <= def.maximum)
return;
const origin = util.getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_big",
maximum: def.maximum,
inclusive: true,
input,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor("$ZodCheckMinLength", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
const units = input.length;
// A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt.
const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2
? util.codePointLength(input)
: units;
if (length >= def.minimum)
return;
const origin = util.getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_small",
minimum: def.minimum,
inclusive: true,
input,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor("$ZodCheckLengthEquals", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
const units = input.length;
// A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures.
const length = typeof input === "string" && units >= def.length && units <= def.length * 2
? util.codePointLength(input)
: units;
if (length === def.length)
return;
const origin = util.getLengthableOrigin(input);
const tooBig = length > def.length;
payload.issues.push({
origin,
...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }),
inclusive: true,
exact: true,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor("$ZodCheckStringFormat", (inst, def) => {
var _a, _b;
$ZodCheck.init(inst, def);
if (def.pattern)
(_a = inst._zod).check ?? (_a.check = (payload) => {
def.pattern.lastIndex = 0;
if (def.pattern.test(payload.value))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: def.format,
input: payload.value,
...(def.pattern ? { pattern: def.pattern.toString() } : {}),
inst,
continue: !def.abort,
});
});
else
(_b = inst._zod).check ?? (_b.check = () => { });
});
export const $ZodCheckRegex = /*@__PURE__*/ core.$constructor("$ZodCheckRegex", (inst, def) => {
$ZodCheckStringFormat.init(inst, def);
inst._zod.check = (payload) => {
def.pattern.lastIndex = 0;
if (def.pattern.test(payload.value))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "regex",
input: payload.value,
pattern: def.pattern.toString(),
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor("$ZodCheckLowerCase", (inst, def) => {
def.pattern ?? (def.pattern = regexes.lowercase);
$ZodCheckStringFormat.init(inst, def);
});
export const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor("$ZodCheckUpperCase", (inst, def) => {
def.pattern ?? (def.pattern = regexes.uppercase);
$ZodCheckStringFormat.init(inst, def);
});
export const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor("$ZodCheckIncludes", (inst, def) => {
$ZodCheck.init(inst, def);
const escapedRegex = util.escapeRegex(def.includes);
// `String.prototype.includes(sub, position)` matches `sub` at `position`
// OR LATER, so the pattern must allow at least `position` leading chars
// (`{N,}`), not exactly `position` chars (`{N}`).
const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);
def.pattern = pattern;
inst._zod.check = (payload) => {
if (payload.value.includes(def.includes, def.position))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "includes",
includes: def.includes,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor("$ZodCheckStartsWith", (inst, def) => {
$ZodCheck.init(inst, def);
const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);
def.pattern ?? (def.pattern = pattern);
inst._zod.check = (payload) => {
if (payload.value.startsWith(def.prefix))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "starts_with",
prefix: def.prefix,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor("$ZodCheckEndsWith", (inst, def) => {
$ZodCheck.init(inst, def);
const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);
def.pattern ?? (def.pattern = pattern);
inst._zod.check = (payload) => {
if (payload.value.endsWith(def.suffix))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "ends_with",
suffix: def.suffix,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
///////////////////////////////////
///// $ZodCheckProperty /////
///////////////////////////////////
function handleCheckPropertyResult(result, payload, property) {
if (result.issues.length) {
payload.issues.push(...util.prefixIssues(property, result.issues));
}
}
export const $ZodCheckProperty = /*@__PURE__*/ core.$constructor("$ZodCheckProperty", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.check = (payload) => {
const result = def.schema._zod.run({
value: payload.value[def.property],
issues: [],
}, {});
if (result instanceof Promise) {
return result.then((result) => handleCheckPropertyResult(result, payload, def.property));
}
handleCheckPropertyResult(result, payload, def.property);
return;
};
});
export const $ZodCheckProperties = /*@__PURE__*/ core.$constructor("$ZodCheckProperties", (inst, def) => {
$ZodCheck.init(inst, def);
util.hide(inst, Symbol.iterator, function* () {
yield inst;
});
// key and schema snapshotted together: reading one live and the other cached lets a later mutation of the caller's shape object pair a stale key with a missing schema
let entries;
inst._zod.check = (payload) => {
// the base schema already typed the value, so only a nullish one is rejected here: the properties read on a primitive too, matching z.property() on a string's length
if (payload.value == null) {
payload.issues.push({ expected: "object", code: "invalid_type", input: payload.value, inst });
return undefined;
}
entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]]));
const input = payload.value;
let proms;
for (const [key, schema] of entries) {
const result = schema._zod.run({ value: input[key], issues: [] }, {});
if (result instanceof Promise) {
proms ?? (proms = []);
proms.push(result.then((result) => handleCheckPropertyResult(result, payload, key)));
}
else {
handleCheckPropertyResult(result, payload, key);
}
}
if (proms)
return Promise.all(proms).then(() => undefined);
return undefined;
};
});
export const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor("$ZodCheckMimeType", (inst, def) => {
$ZodCheck.init(inst, def);
const mimeSet = new Set(def.mime);
inst._zod.check = (payload) => {
if (mimeSet.has(payload.value.type))
return;
payload.issues.push({
code: "invalid_value",
values: def.mime,
input: payload.value.type,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor("$ZodCheckOverwrite", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.check = (payload) => {
payload.value = def.tx(payload.value);
};
});
+1916
View File
File diff suppressed because it is too large Load Diff
+65
View File
@@ -0,0 +1,65 @@
import type * as core from "./core.cjs";
import type { SomeType } from "./schemas.cjs";
/** @internal Sentinel the compiled fast path returns when validation fails. */
export declare const INVALID: unique symbol;
/** @internal */
export type INVALID = typeof INVALID;
interface CompileFnOptions {
debug?: boolean | undefined;
/** Emit a validator instead of a parser: skip building the output value where nothing reads it. */
assertOnly?: boolean | undefined;
}
type CompiledFn<T> = ((input: unknown) => T | INVALID) & {
code?: string | undefined;
/** False when this function's INVALID does not strictly mean "the runtime would reject". */
definite?: boolean | undefined;
};
/** Raised when the schema contains async refinements or transforms. Surfaces only under `compile(schema, { strict: true })`. */
export declare class ZodCompileAsyncError extends Error {
constructor(message?: string);
}
/**
* Raised when the schema contains a feature whose semantics the fast path
* can't fully model. Both the shim in `zod/compile` and the default
* `compile()` fall back to the runtime parser for that schema; only
* `compile(schema, { strict: true })` lets it surface.
*/
export declare class ZodCompileUnsupportedError extends Error {
/** Whether a container may absorb this refusal by running the child through the runtime (see `compileChild`). False when running only that node on the runtime is not equivalent to running the whole parse there — a runtime island gets no parse context, so a node that *consumes* issues rather than propagating them would finalize them against the wrong error map and still succeed. */
readonly islandable: boolean;
constructor(feature: string, islandable?: boolean);
}
export interface CompileOptions {
/** Throw the refusal instead of returning the schema uncompiled. */
strict?: boolean | undefined;
}
/**
* AOT-compile a Zod schema. Returns a clone whose `_zod.run` calls a generated
* fast path first and falls back to the original runtime parser on failure.
*
* - Forward direction only. Backward (encode), async, and `skipChecks` paths
* bypass the fast path and use the runtime directly.
* - Never throws. A schema the fast path can't model is returned unchanged and
* keeps using the runtime parser. Pass `{ strict: true }` to get the refusal
* as a thrown `ZodCompileUnsupportedError` / `ZodCompileAsyncError` instead.
* - The original schema is unchanged. The clone shares children by reference.
*/
export declare function compile<T extends SomeType>(schema: T, options?: CompileOptions): T;
/**
* Install an already-generated parser as a schema's fast path. Returns a clone; the original is
* unchanged.
*
* The parser takes the input and returns the parsed value, or `INVALID` to hand the parse to the
* runtime. It must be synchronous and forward-direction, and it must build fresh output rather than
* return its input — Zod cannot check either, and a wrong *success* is returned to the caller as-is.
*
* `compile()` is the ordinary entry point. This is for a build-time or native compiler that produces
* a parser where `new Function` is unavailable.
*/
export declare function withParser<T extends SomeType>(schema: T, parser: (input: unknown) => core.output<T> | INVALID): T;
/**
* @internal Generate the standalone compiled function: a parser by default, a validator under
* `assertOnly`. Returns the parsed value, `true` where nothing reads the output, or `INVALID`. Consumers use `compile()`.
*/
export declare function compileFn<T extends SomeType>(schema: T, options?: CompileFnOptions): CompiledFn<core.output<T>>;
export {};
+65
View File
@@ -0,0 +1,65 @@
import type * as core from "./core.js";
import type { SomeType } from "./schemas.js";
/** @internal Sentinel the compiled fast path returns when validation fails. */
export declare const INVALID: unique symbol;
/** @internal */
export type INVALID = typeof INVALID;
interface CompileFnOptions {
debug?: boolean | undefined;
/** Emit a validator instead of a parser: skip building the output value where nothing reads it. */
assertOnly?: boolean | undefined;
}
type CompiledFn<T> = ((input: unknown) => T | INVALID) & {
code?: string | undefined;
/** False when this function's INVALID does not strictly mean "the runtime would reject". */
definite?: boolean | undefined;
};
/** Raised when the schema contains async refinements or transforms. Surfaces only under `compile(schema, { strict: true })`. */
export declare class ZodCompileAsyncError extends Error {
constructor(message?: string);
}
/**
* Raised when the schema contains a feature whose semantics the fast path
* can't fully model. Both the shim in `zod/compile` and the default
* `compile()` fall back to the runtime parser for that schema; only
* `compile(schema, { strict: true })` lets it surface.
*/
export declare class ZodCompileUnsupportedError extends Error {
/** Whether a container may absorb this refusal by running the child through the runtime (see `compileChild`). False when running only that node on the runtime is not equivalent to running the whole parse there — a runtime island gets no parse context, so a node that *consumes* issues rather than propagating them would finalize them against the wrong error map and still succeed. */
readonly islandable: boolean;
constructor(feature: string, islandable?: boolean);
}
export interface CompileOptions {
/** Throw the refusal instead of returning the schema uncompiled. */
strict?: boolean | undefined;
}
/**
* AOT-compile a Zod schema. Returns a clone whose `_zod.run` calls a generated
* fast path first and falls back to the original runtime parser on failure.
*
* - Forward direction only. Backward (encode), async, and `skipChecks` paths
* bypass the fast path and use the runtime directly.
* - Never throws. A schema the fast path can't model is returned unchanged and
* keeps using the runtime parser. Pass `{ strict: true }` to get the refusal
* as a thrown `ZodCompileUnsupportedError` / `ZodCompileAsyncError` instead.
* - The original schema is unchanged. The clone shares children by reference.
*/
export declare function compile<T extends SomeType>(schema: T, options?: CompileOptions): T;
/**
* Install an already-generated parser as a schema's fast path. Returns a clone; the original is
* unchanged.
*
* The parser takes the input and returns the parsed value, or `INVALID` to hand the parse to the
* runtime. It must be synchronous and forward-direction, and it must build fresh output rather than
* return its input — Zod cannot check either, and a wrong *success* is returned to the caller as-is.
*
* `compile()` is the ordinary entry point. This is for a build-time or native compiler that produces
* a parser where `new Function` is unavailable.
*/
export declare function withParser<T extends SomeType>(schema: T, parser: (input: unknown) => core.output<T> | INVALID): T;
/**
* @internal Generate the standalone compiled function: a parser by default, a validator under
* `assertOnly`. Returns the parsed value, `true` where nothing reads the output, or `INVALID`. Consumers use `compile()`.
*/
export declare function compileFn<T extends SomeType>(schema: T, options?: CompileFnOptions): CompiledFn<core.output<T>>;
export {};
+1866
View File
File diff suppressed because it is too large Load Diff
+167
View File
@@ -0,0 +1,167 @@
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.globalConfig = exports.$ZodEncodeError = exports.$ZodAsyncError = exports.$brand = exports.NEVER = void 0;
exports.$constructor = $constructor;
exports.config = config;
const util_js_1 = require("./util.cjs");
/** A special constant with type `never` */
exports.NEVER = Object.freeze({
status: "aborted",
});
/* Shared descriptor for installing `_zod`; defineProperty reads it
* synchronously, so reusing one object avoids a per-instance allocation. */
const _zodDesc = { value: undefined, enumerable: false };
// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error
let _E = "captureStackTrace" in Error ? Error : null;
// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot
function newError(Definition) {
const E = _E;
if (E) {
const saved = E.stackTraceLimit;
if (typeof saved === "number") {
try {
E.stackTraceLimit = 0;
}
catch {
_E = null;
return new Definition();
}
try {
return new Definition();
}
finally {
E.stackTraceLimit = saved;
}
}
}
return new Definition();
}
function $constructor(name, initializer,
/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */
proto, params) {
// Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance.
const zodProto = {};
// Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy.
function Internals(def) {
this.def = def;
this.constr = _;
this.traits = new Set();
}
Internals.prototype = zodProto;
const protoMembers = proto;
// One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait.
const initialized = protoMembers && new WeakSet();
function init(inst, def) {
if (!inst._zod) {
_zodDesc.value = new Internals(def);
try {
Object.defineProperty(inst, "_zod", _zodDesc);
}
finally {
// Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next.
_zodDesc.value = undefined;
}
}
else if (inst._zod.traits.has(name)) {
return;
}
inst._zod.traits.add(name);
initializer(inst, def);
if (initialized) {
// `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before.
const own = Object.getPrototypeOf(inst);
const ctorProto = inst._zod.constr.prototype;
let up = own;
while (up && up !== ctorProto)
up = Object.getPrototypeOf(up);
const target = up ?? own;
if (!initialized.has(target)) {
initialized.add(target);
(0, util_js_1.members)(target, protoMembers);
}
}
// support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype
const proto = _.prototype;
for (const k in proto) {
if (!Object.prototype.hasOwnProperty.call(proto, k))
continue;
if (!(k in inst)) {
inst[k] = proto[k].bind(inst);
}
}
}
// doesn't work if Parent has a constructor with arguments
const Parent = params?.Parent ?? Object;
class Definition extends Parent {
}
Object.defineProperty(Definition, "name", { value: name });
function _(def) {
const inst = params?.Parent ? newError(Definition) : this;
init(inst, def);
const deferred = inst._zod.deferred;
if (deferred) {
for (const fn of deferred) {
fn();
}
// Released: initializers run once, and the list would otherwise be retained for the schema's lifetime.
inst._zod.deferred = undefined;
}
// Global post-processor hook. Internal: installed by `import "zod/compile"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation.
const pp = globalThis.__zod_globalConfig?.postProcessor;
if (pp)
pp(inst);
return inst;
}
Object.defineProperty(_, "init", { value: init });
Object.defineProperty(_, Symbol.hasInstance, {
value: (inst) => {
if (params?.Parent && inst instanceof params.Parent)
return true;
return inst?._zod?.traits?.has(name);
},
});
Object.defineProperty(_, "name", { value: name });
return _;
}
////////////////////////////// UTILITIES ///////////////////////////////////////
exports.$brand = Symbol("zod_brand");
class $ZodAsyncError extends Error {
constructor() {
super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
}
}
exports.$ZodAsyncError = $ZodAsyncError;
class $ZodEncodeError extends Error {
constructor(name) {
super(`Encountered unidirectional transform during encode: ${name}`);
this.name = "ZodEncodeError";
}
}
exports.$ZodEncodeError = $ZodEncodeError;
(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});
exports.globalConfig = globalThis.__zod_globalConfig;
function config(newConfig) {
if (newConfig)
Object.assign(exports.globalConfig, newConfig);
return exports.globalConfig;
}
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+82
View File
@@ -0,0 +1,82 @@
import type * as errors from "./errors.cjs";
import type * as schemas from "./schemas.cjs";
import type { Class, ProtoOf } from "./util.cjs";
type ZodTrait = {
_zod: {
def: any;
[k: string]: any;
};
};
export interface $constructor<T extends ZodTrait, D = T["_zod"]["def"]> {
new (def: D): T;
init(inst: T, def: D): asserts inst is T;
}
export interface $constructorParams {
Parent?: typeof Class;
}
/** A special constant with type `never` */
export declare const NEVER: never;
export declare function $constructor<T extends ZodTrait, D = T["_zod"]["def"]>(name: string, initializer: (inst: T, def: D) => void,
/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */
proto?: ProtoOf<T>, params?: $constructorParams): $constructor<T, D>;
export declare const $brand: unique symbol;
export type $brand<T extends string | number | symbol = string | number | symbol> = {
[$brand]: {
[k in T]: true;
};
};
export type $ZodBranded<T extends schemas.SomeType, Brand extends string | number | symbol, Dir extends "in" | "out" | "inout" = "out"> = T & (Dir extends "inout" ? {
_zod: {
input: input<T> & $brand<Brand>;
output: output<T> & $brand<Brand>;
};
} : Dir extends "in" ? {
_zod: {
input: input<T> & $brand<Brand>;
};
} : {
_zod: {
output: output<T> & $brand<Brand>;
};
});
export type $ZodNarrow<T extends schemas.SomeType, Out> = T & {
_zod: {
output: Out;
};
};
export declare class $ZodAsyncError extends Error {
constructor();
}
export declare class $ZodEncodeError extends Error {
constructor(name: string);
}
export type input<T> = T extends {
_zod: {
input: any;
};
} ? T["_zod"]["input"] : unknown;
export type output<T> = T extends {
_zod: {
output: any;
};
} ? T["_zod"]["output"] : unknown;
export type { output as infer };
export interface $ZodConfig {
/** Custom error map. Overrides `config().localeError`. */
customError?: errors.$ZodErrorMap | undefined;
/** Localized error map. Lowest priority. */
localeError?: errors.$ZodErrorMap | undefined;
/** Disable JIT schema compilation. Useful in environments that disallow `eval`. */
jitless?: boolean | undefined;
/** Enables parsing input that contains reference cycles. Read when a schema is constructed. */
memoizer?: schemas.$ZodMemoizer | undefined;
/**
* Internal: post-processor invoked on every freshly-constructed schema
* instance, after init and deferred fns run. Set by `import "zod/compile"`
* to install AOT compilation. Not part of the public API.
* @internal
*/
postProcessor?: ((inst: any) => void) | undefined;
}
export declare const globalConfig: $ZodConfig;
export declare function config(newConfig?: Partial<$ZodConfig>): $ZodConfig;
+82
View File
@@ -0,0 +1,82 @@
import type * as errors from "./errors.js";
import type * as schemas from "./schemas.js";
import type { Class, ProtoOf } from "./util.js";
type ZodTrait = {
_zod: {
def: any;
[k: string]: any;
};
};
export interface $constructor<T extends ZodTrait, D = T["_zod"]["def"]> {
new (def: D): T;
init(inst: T, def: D): asserts inst is T;
}
export interface $constructorParams {
Parent?: typeof Class;
}
/** A special constant with type `never` */
export declare const NEVER: never;
export declare function $constructor<T extends ZodTrait, D = T["_zod"]["def"]>(name: string, initializer: (inst: T, def: D) => void,
/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */
proto?: ProtoOf<T>, params?: $constructorParams): $constructor<T, D>;
export declare const $brand: unique symbol;
export type $brand<T extends string | number | symbol = string | number | symbol> = {
[$brand]: {
[k in T]: true;
};
};
export type $ZodBranded<T extends schemas.SomeType, Brand extends string | number | symbol, Dir extends "in" | "out" | "inout" = "out"> = T & (Dir extends "inout" ? {
_zod: {
input: input<T> & $brand<Brand>;
output: output<T> & $brand<Brand>;
};
} : Dir extends "in" ? {
_zod: {
input: input<T> & $brand<Brand>;
};
} : {
_zod: {
output: output<T> & $brand<Brand>;
};
});
export type $ZodNarrow<T extends schemas.SomeType, Out> = T & {
_zod: {
output: Out;
};
};
export declare class $ZodAsyncError extends Error {
constructor();
}
export declare class $ZodEncodeError extends Error {
constructor(name: string);
}
export type input<T> = T extends {
_zod: {
input: any;
};
} ? T["_zod"]["input"] : unknown;
export type output<T> = T extends {
_zod: {
output: any;
};
} ? T["_zod"]["output"] : unknown;
export type { output as infer };
export interface $ZodConfig {
/** Custom error map. Overrides `config().localeError`. */
customError?: errors.$ZodErrorMap | undefined;
/** Localized error map. Lowest priority. */
localeError?: errors.$ZodErrorMap | undefined;
/** Disable JIT schema compilation. Useful in environments that disallow `eval`. */
jitless?: boolean | undefined;
/** Enables parsing input that contains reference cycles. Read when a schema is constructed. */
memoizer?: schemas.$ZodMemoizer | undefined;
/**
* Internal: post-processor invoked on every freshly-constructed schema
* instance, after init and deferred fns run. Set by `import "zod/compile"`
* to install AOT compilation. Not part of the public API.
* @internal
*/
postProcessor?: ((inst: any) => void) | undefined;
}
export declare const globalConfig: $ZodConfig;
export declare function config(newConfig?: Partial<$ZodConfig>): $ZodConfig;
+141
View File
@@ -0,0 +1,141 @@
var _a;
import { members as installMembers } from "./util.js";
/** A special constant with type `never` */
export const NEVER = /*@__PURE__*/ Object.freeze({
status: "aborted",
});
/* Shared descriptor for installing `_zod`; defineProperty reads it
* synchronously, so reusing one object avoids a per-instance allocation. */
const _zodDesc = { value: undefined, enumerable: false };
// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error
let _E = "captureStackTrace" in Error ? Error : null;
// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot
function newError(Definition) {
const E = _E;
if (E) {
const saved = E.stackTraceLimit;
if (typeof saved === "number") {
try {
E.stackTraceLimit = 0;
}
catch {
_E = null;
return new Definition();
}
try {
return new Definition();
}
finally {
E.stackTraceLimit = saved;
}
}
}
return new Definition();
}
export /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer,
/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */
proto, params) {
// Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance.
const zodProto = {};
// Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy.
function Internals(def) {
this.def = def;
this.constr = _;
this.traits = new Set();
}
Internals.prototype = zodProto;
const protoMembers = proto;
// One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait.
const initialized = protoMembers && new WeakSet();
function init(inst, def) {
if (!inst._zod) {
_zodDesc.value = new Internals(def);
try {
Object.defineProperty(inst, "_zod", _zodDesc);
}
finally {
// Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next.
_zodDesc.value = undefined;
}
}
else if (inst._zod.traits.has(name)) {
return;
}
inst._zod.traits.add(name);
initializer(inst, def);
if (initialized) {
// `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before.
const own = Object.getPrototypeOf(inst);
const ctorProto = inst._zod.constr.prototype;
let up = own;
while (up && up !== ctorProto)
up = Object.getPrototypeOf(up);
const target = up ?? own;
if (!initialized.has(target)) {
initialized.add(target);
installMembers(target, protoMembers);
}
}
// support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype
const proto = _.prototype;
for (const k in proto) {
if (!Object.prototype.hasOwnProperty.call(proto, k))
continue;
if (!(k in inst)) {
inst[k] = proto[k].bind(inst);
}
}
}
// doesn't work if Parent has a constructor with arguments
const Parent = params?.Parent ?? Object;
class Definition extends Parent {
}
Object.defineProperty(Definition, "name", { value: name });
function _(def) {
const inst = params?.Parent ? newError(Definition) : this;
init(inst, def);
const deferred = inst._zod.deferred;
if (deferred) {
for (const fn of deferred) {
fn();
}
// Released: initializers run once, and the list would otherwise be retained for the schema's lifetime.
inst._zod.deferred = undefined;
}
// Global post-processor hook. Internal: installed by `import "zod/compile"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation.
const pp = globalThis.__zod_globalConfig?.postProcessor;
if (pp)
pp(inst);
return inst;
}
Object.defineProperty(_, "init", { value: init });
Object.defineProperty(_, Symbol.hasInstance, {
value: (inst) => {
if (params?.Parent && inst instanceof params.Parent)
return true;
return inst?._zod?.traits?.has(name);
},
});
Object.defineProperty(_, "name", { value: name });
return _;
}
////////////////////////////// UTILITIES ///////////////////////////////////////
export const $brand = /*@__PURE__*/ Symbol("zod_brand");
export class $ZodAsyncError extends Error {
constructor() {
super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
}
}
export class $ZodEncodeError extends Error {
constructor(name) {
super(`Encountered unidirectional transform during encode: ${name}`);
this.name = "ZodEncodeError";
}
}
(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});
export const globalConfig = globalThis.__zod_globalConfig;
export function config(newConfig) {
if (newConfig)
Object.assign(globalConfig, newConfig);
return globalConfig;
}
+61
View File
@@ -0,0 +1,61 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Doc = void 0;
class Doc {
constructor(args = [], closed = {}) {
this.content = [];
this.indent = 0;
this.args = args;
this.closed = closed;
}
// the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it
indented(fn) {
this.indent += 1;
try {
fn(this);
}
finally {
this.indent -= 1;
}
}
write(arg) {
if (typeof arg === "function") {
arg(this, { execution: "sync" });
arg(this, { execution: "async" });
return;
}
const content = arg;
const lines = content.split("\n").filter((x) => x);
const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
for (const line of dedented) {
this.content.push(line);
}
}
compile() {
const F = Function;
const content = this?.content ?? [``];
const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`);
return factory(...Object.values(this.closed));
}
}
exports.Doc = Doc;
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+16
View File
@@ -0,0 +1,16 @@
type ModeWriter = (doc: Doc, modes: {
execution: "sync" | "async";
}) => void;
export declare class Doc {
args: string[];
/** Bindings the compiled function closes over, by name. */
closed: Record<string, unknown>;
content: string[];
indent: number;
constructor(args?: string[], closed?: Record<string, unknown>);
indented(fn: (doc: Doc) => void): void;
write(fn: ModeWriter): void;
write(line: string): void;
compile(): any;
}
export {};
+16
View File
@@ -0,0 +1,16 @@
type ModeWriter = (doc: Doc, modes: {
execution: "sync" | "async";
}) => void;
export declare class Doc {
args: string[];
/** Bindings the compiled function closes over, by name. */
closed: Record<string, unknown>;
content: string[];
indent: number;
constructor(args?: string[], closed?: Record<string, unknown>);
indented(fn: (doc: Doc) => void): void;
write(fn: ModeWriter): void;
write(line: string): void;
compile(): any;
}
export {};
+38
View File
@@ -0,0 +1,38 @@
export class Doc {
constructor(args = [], closed = {}) {
this.content = [];
this.indent = 0;
this.args = args;
this.closed = closed;
}
// the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it
indented(fn) {
this.indent += 1;
try {
fn(this);
}
finally {
this.indent -= 1;
}
}
write(arg) {
if (typeof arg === "function") {
arg(this, { execution: "sync" });
arg(this, { execution: "async" });
return;
}
const content = arg;
const lines = content.split("\n").filter((x) => x);
const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
for (const line of dedented) {
this.content.push(line);
}
}
compile() {
const F = Function;
const content = this?.content ?? [``];
const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`);
return factory(...Object.values(this.closed));
}
}
+317
View File
@@ -0,0 +1,317 @@
"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.$ZodRealError = exports.$ZodError = void 0;
exports.flattenError = flattenError;
exports.formatError = formatError;
exports.treeifyError = treeifyError;
exports.toDotPath = toDotPath;
exports.prettifyError = prettifyError;
const core_js_1 = require("./core.cjs");
const util = __importStar(require("./util.cjs"));
/* Computing the message eagerly is expensive (pretty-printed JSON of all
* issues), so defer it until first read. The accessor functions and
* descriptors are shared across instances to keep error construction
* cheap; the computed message is cached on the internals object. The
* setter preserves plain assignment semantics for consumers that
* overwrite `message`. */
function _getMessage() {
const internals = this._zod;
internals.message ?? (internals.message = JSON.stringify(internals.def, util.jsonStringifyReplacer, 2));
return internals.message;
}
function _setMessage(value) {
this._zod.message = value;
}
const _messageDesc = {
get: _getMessage,
set: _setMessage,
enumerable: true,
configurable: true,
};
const _issuesDesc = { value: undefined, enumerable: false };
/* Prototypes that already carry the lazy `toString`. Seeded with the
* intrinsics so that `init` on a foreign object — it accepts any object —
* can never install an accessor onto a prototype we do not own. */
const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
const initializer = (inst, def) => {
inst.name = "$ZodError";
// `_zod` is already non-enumerable: $constructor's init defined it with this same descriptor
_issuesDesc.value = def;
Object.defineProperty(inst, "issues", _issuesDesc);
// Clear the shared slot; a retained `value` pins the last error's issues.
_issuesDesc.value = undefined;
Object.defineProperty(inst, "message", _messageDesc);
/* `toString` lives as a non-enumerable lazy getter on the shared
* prototype; on first access it caches a per-instance closure so
* detached usage still works. */
const proto = Object.getPrototypeOf(inst);
if (!_installedToString.has(proto)) {
_installedToString.add(proto);
Object.defineProperty(proto, "toString", {
configurable: true,
enumerable: false,
get() {
const value = () => this.message;
Object.defineProperty(this, "toString", { value, configurable: true, writable: true });
return value;
},
set(value) {
Object.defineProperty(this, "toString", { value, configurable: true, writable: true });
},
});
}
};
exports.$ZodError = (0, core_js_1.$constructor)("$ZodError", initializer);
exports.$ZodRealError = (0, core_js_1.$constructor)("$ZodError", initializer, undefined, {
Parent: Error,
});
/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member
* ("toString", "constructor") would otherwise read through to the prototype, and assigning
* "__proto__" would hit the setter instead of creating a key. */
function node(obj, key, make) {
if (!Object.prototype.hasOwnProperty.call(obj, key)) {
if (key === "__proto__") {
Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });
}
else {
obj[key] = make();
}
}
return obj[key];
}
function flattenError(error, mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of error.issues) {
if (sub.path.length > 0) {
node(fieldErrors, sub.path[0], () => []).push(mapper(sub));
}
else {
formErrors.push(mapper(sub));
}
}
return { formErrors, fieldErrors };
}
function formatError(error, mapper = (issue) => issue.message) {
const fieldErrors = { _errors: [] };
const processError = (error, path = []) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union" && issue.errors.length) {
issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));
}
else if (issue.code === "invalid_key") {
processError({ issues: issue.issues }, [...path, ...issue.path]);
}
else if (issue.code === "invalid_element") {
processError({ issues: issue.issues }, [...path, ...issue.path]);
}
else {
const fullpath = [...path, ...issue.path];
if (fullpath.length === 0) {
fieldErrors._errors.push(mapper(issue));
}
else {
let curr = fieldErrors;
let i = 0;
while (i < fullpath.length) {
const el = fullpath[i];
const terminal = i === fullpath.length - 1;
// `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child.
if (el === "_errors") {
if (terminal)
curr._errors.push(mapper(issue));
i++;
continue;
}
// A path element may collide with an inherited property name such as
// "__proto__" or "constructor". Truthiness checks read the prototype
// (so no node is created, then ._errors.push throws), and bracket
// assignment of "__proto__" hits the setter instead of creating an
// own key. Guard the read with hasOwnProperty and create the node
// with defineProperty so any path element becomes a real own key.
if (!Object.prototype.hasOwnProperty.call(curr, el)) {
Object.defineProperty(curr, el, {
value: { _errors: [] },
enumerable: true,
writable: true,
configurable: true,
});
}
const node = curr[el];
if (terminal) {
node._errors.push(mapper(issue));
}
curr = node;
i++;
}
}
}
}
};
processError(error);
return fieldErrors;
}
function treeifyError(error, mapper = (issue) => issue.message) {
const result = { errors: [] };
const processError = (error, path = []) => {
var _a;
for (const issue of error.issues) {
if (issue.code === "invalid_union" && issue.errors.length) {
// regular union error
issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));
}
else if (issue.code === "invalid_key") {
processError({ issues: issue.issues }, [...path, ...issue.path]);
}
else if (issue.code === "invalid_element") {
processError({ issues: issue.issues }, [...path, ...issue.path]);
}
else {
const fullpath = [...path, ...issue.path];
if (fullpath.length === 0) {
result.errors.push(mapper(issue));
continue;
}
let curr = result;
let i = 0;
while (i < fullpath.length) {
const el = fullpath[i];
const terminal = i === fullpath.length - 1;
if (typeof el === "string") {
curr.properties ?? (curr.properties = {});
// el may collide with an inherited property name ("__proto__",
// "constructor", ...); ??= reads the prototype so the node is never
// created and curr.errors.push throws. Guard with hasOwnProperty and
// create the node with defineProperty so "__proto__" becomes a real
// own key rather than invoking the prototype setter.
if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) {
Object.defineProperty(curr.properties, el, {
value: { errors: [] },
enumerable: true,
writable: true,
configurable: true,
});
}
curr = curr.properties[el];
}
else {
curr.items ?? (curr.items = []);
(_a = curr.items)[el] ?? (_a[el] = { errors: [] });
curr = curr.items[el];
}
if (terminal) {
curr.errors.push(mapper(issue));
}
i++;
}
}
}
};
processError(error);
return result;
}
/** Format a ZodError as a human-readable string in the following form.
*
* From
*
* ```ts
* ZodError {
* issues: [
* {
* expected: 'string',
* code: 'invalid_type',
* path: [ 'username' ],
* message: 'Invalid input: expected string'
* },
* {
* expected: 'number',
* code: 'invalid_type',
* path: [ 'favoriteNumbers', 1 ],
* message: 'Invalid input: expected number'
* }
* ];
* }
* ```
*
* to
*
* ```
* username
* ✖ Expected number, received string at "username
* favoriteNumbers[0]
* ✖ Invalid input: expected number
* ```
*/
function toDotPath(_path) {
const segs = [];
const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg));
for (const seg of path) {
if (typeof seg === "number")
segs.push(`[${seg}]`);
else if (typeof seg === "symbol")
segs.push(`[${JSON.stringify(String(seg))}]`);
else if (/[^\w$]/.test(seg))
segs.push(`[${JSON.stringify(seg)}]`);
else {
if (segs.length)
segs.push(".");
segs.push(seg);
}
}
return segs.join("");
}
function prettifyError(error) {
const lines = [];
// sort by path length
const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);
// Process each issue
for (const issue of issues) {
lines.push(`✖ ${issue.message}`);
if (issue.path?.length)
lines.push(` → at ${toDotPath(issue.path)}`);
}
// Convert Map to formatted string
return lines.join("\n");
}
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+225
View File
@@ -0,0 +1,225 @@
import type { $ZodCheck, $ZodStringFormats } from "./checks.cjs";
import { $constructor } from "./core.cjs";
import type { $ZodType } from "./schemas.cjs";
import type { StandardSchemaV1 } from "./standard-schema.cjs";
import * as util from "./util.cjs";
export interface $ZodIssueBase {
readonly code?: string;
readonly input?: unknown;
readonly path: PropertyKey[];
readonly message: string;
}
export type $ZodInvalidTypeExpected = "string" | "number" | "int" | "boolean" | "bigint" | "symbol" | "undefined" | "null" | "never" | "void" | "date" | "array" | "object" | "tuple" | "record" | "map" | "set" | "file" | "nonoptional" | "nan" | "function" | (string & {});
export interface $ZodIssueInvalidType<Input = unknown> extends $ZodIssueBase {
readonly code: "invalid_type";
readonly expected: $ZodInvalidTypeExpected;
readonly input?: Input;
}
export interface $ZodIssueTooBig<Input = unknown> extends $ZodIssueBase {
readonly code: "too_big";
readonly origin: "number" | "int" | "bigint" | "date" | "string" | "array" | "set" | "file" | (string & {});
readonly maximum: number | bigint;
readonly inclusive?: boolean;
readonly exact?: boolean;
readonly input?: Input;
}
export interface $ZodIssueTooSmall<Input = unknown> extends $ZodIssueBase {
readonly code: "too_small";
readonly origin: "number" | "int" | "bigint" | "date" | "string" | "array" | "set" | "file" | (string & {});
readonly minimum: number | bigint;
/** True if the allowable range includes the minimum */
readonly inclusive?: boolean;
/** True if the allowed value is fixed (e.g.` z.length(5)`), not a range (`z.minLength(5)`) */
readonly exact?: boolean;
readonly input?: Input;
}
export interface $ZodIssueInvalidStringFormat extends $ZodIssueBase {
readonly code: "invalid_format";
readonly format: $ZodStringFormats | (string & {});
readonly pattern?: string;
readonly input?: string;
}
export interface $ZodIssueNotMultipleOf<Input extends number | bigint = number | bigint> extends $ZodIssueBase {
readonly code: "not_multiple_of";
readonly divisor: number;
readonly input?: Input;
}
export interface $ZodIssueUnrecognizedKeys extends $ZodIssueBase {
readonly code: "unrecognized_keys";
readonly keys: string[];
readonly input?: Record<string, unknown>;
}
interface $ZodIssueInvalidUnionNoMatch extends $ZodIssueBase {
readonly code: "invalid_union";
readonly errors: $ZodIssue[][];
readonly input?: unknown;
readonly discriminator?: string | undefined;
readonly options?: util.Primitive[];
readonly inclusive?: true;
}
interface $ZodIssueInvalidUnionMultipleMatch extends $ZodIssueBase {
readonly code: "invalid_union";
readonly errors: [];
readonly input?: unknown;
readonly discriminator?: string | undefined;
readonly inclusive: false;
/** Indices of the options that matched */
readonly matches: number[];
}
export type $ZodIssueInvalidUnion = $ZodIssueInvalidUnionNoMatch | $ZodIssueInvalidUnionMultipleMatch;
export interface $ZodIssueInvalidKey<Input = unknown> extends $ZodIssueBase {
readonly code: "invalid_key";
readonly origin: "map" | "record";
readonly issues: $ZodIssue[];
readonly input?: Input;
}
export interface $ZodIssueInvalidElement<Input = unknown> extends $ZodIssueBase {
readonly code: "invalid_element";
readonly origin: "map" | "set";
readonly key: unknown;
readonly issues: $ZodIssue[];
readonly input?: Input;
}
export interface $ZodIssueInvalidValue<Input = unknown> extends $ZodIssueBase {
readonly code: "invalid_value";
readonly values: util.Primitive[];
readonly input?: Input;
}
export interface $ZodIssueCustom extends $ZodIssueBase {
readonly code: "custom";
readonly params?: Record<string, any> | undefined;
readonly input?: unknown;
}
export interface $ZodIssueStringCommonFormats extends $ZodIssueInvalidStringFormat {
format: Exclude<$ZodStringFormats, "regex" | "jwt" | "starts_with" | "ends_with" | "includes">;
}
export interface $ZodIssueStringInvalidRegex extends $ZodIssueInvalidStringFormat {
format: "regex";
pattern: string;
}
export interface $ZodIssueStringInvalidJWT extends $ZodIssueInvalidStringFormat {
format: "jwt";
algorithm?: string;
}
export interface $ZodIssueStringStartsWith extends $ZodIssueInvalidStringFormat {
format: "starts_with";
prefix: string;
}
export interface $ZodIssueStringEndsWith extends $ZodIssueInvalidStringFormat {
format: "ends_with";
suffix: string;
}
export interface $ZodIssueStringIncludes extends $ZodIssueInvalidStringFormat {
format: "includes";
includes: string;
}
export type $ZodStringFormatIssues = $ZodIssueStringCommonFormats | $ZodIssueStringInvalidRegex | $ZodIssueStringInvalidJWT | $ZodIssueStringStartsWith | $ZodIssueStringEndsWith | $ZodIssueStringIncludes;
export type $ZodIssue = $ZodIssueInvalidType | $ZodIssueTooBig | $ZodIssueTooSmall | $ZodIssueInvalidStringFormat | $ZodIssueNotMultipleOf | $ZodIssueUnrecognizedKeys | $ZodIssueInvalidUnion | $ZodIssueInvalidKey | $ZodIssueInvalidElement | $ZodIssueInvalidValue | $ZodIssueCustom;
export type $ZodIssueCode = $ZodIssue["code"];
export type $ZodInternalIssue<T extends $ZodIssueBase = $ZodIssue> = T extends any ? RawIssue<T> : never;
type RawIssue<T extends $ZodIssueBase> = T extends any ? util.Flatten<util.MakePartial<T, "message" | "path"> & {
/** The input data */
readonly input: unknown;
/** The schema or check that originated this issue. */
readonly inst?: $ZodType | $ZodCheck;
/** The schema that owns the issue. Equal to `inst` when a schema originated the issue, and the schema the check was attached to when a check did. */
readonly schema?: $ZodType | undefined;
/** If `true`, Zod will continue executing checks/refinements after this issue. */
readonly continue?: boolean | undefined;
} & Record<string, unknown>> : never;
export type $ZodRawIssue<T extends $ZodIssueBase = $ZodIssue> = $ZodInternalIssue<T>;
export interface $ZodErrorMap<T extends $ZodIssueBase = $ZodIssue> {
(issue: $ZodRawIssue<T>): {
message: string;
} | string | undefined | null;
}
export interface $ZodError<T = unknown> extends Error {
type: T;
issues: $ZodIssue[];
_zod: {
output: T;
def: $ZodIssue[];
};
stack?: string;
name: string;
}
export declare const $ZodError: $constructor<$ZodError>;
interface $ZodRealError<T = any> extends $ZodError<T> {
}
export declare const $ZodRealError: $constructor<$ZodRealError>;
export type $ZodFlattenedError<T, U = string> = _FlattenedError<T, U>;
type _FlattenedError<T, U = string> = {
formErrors: U[];
fieldErrors: {
[P in keyof T]?: U[];
};
};
export declare function flattenError<T>(error: $ZodError<T>): _FlattenedError<T>;
export declare function flattenError<T, U>(error: $ZodError<T>, mapper?: (issue: $ZodIssue) => U): _FlattenedError<T, U>;
type _ZodFormattedError<T, U = string> = T extends [any, ...any[]] ? {
[K in keyof T]?: $ZodFormattedError<T[K], U>;
} : T extends any[] ? {
[k: number]: $ZodFormattedError<T[number], U>;
} : T extends object ? util.Flatten<{
[K in keyof T]?: $ZodFormattedError<T[K], U>;
}> : any;
export type $ZodFormattedError<T, U = string> = {
_errors: U[];
} & util.Flatten<_ZodFormattedError<T, U>>;
export declare function formatError<T>(error: $ZodError<T>): $ZodFormattedError<T>;
export declare function formatError<T, U>(error: $ZodError<T>, mapper?: (issue: $ZodIssue) => U): $ZodFormattedError<T, U>;
export type $ZodErrorTree<T, U = string> = T extends util.Primitive ? {
errors: U[];
} : T extends [any, ...any[]] ? {
errors: U[];
items?: {
[K in keyof T]?: $ZodErrorTree<T[K], U>;
};
} : T extends any[] ? {
errors: U[];
items?: Array<$ZodErrorTree<T[number], U>>;
} : T extends object ? {
errors: U[];
properties?: {
[K in keyof T]?: $ZodErrorTree<T[K], U>;
};
} : {
errors: U[];
};
export declare function treeifyError<T>(error: $ZodError<T>): $ZodErrorTree<T>;
export declare function treeifyError<T, U>(error: $ZodError<T>, mapper?: (issue: $ZodIssue) => U): $ZodErrorTree<T, U>;
/** Format a ZodError as a human-readable string in the following form.
*
* From
*
* ```ts
* ZodError {
* issues: [
* {
* expected: 'string',
* code: 'invalid_type',
* path: [ 'username' ],
* message: 'Invalid input: expected string'
* },
* {
* expected: 'number',
* code: 'invalid_type',
* path: [ 'favoriteNumbers', 1 ],
* message: 'Invalid input: expected number'
* }
* ];
* }
* ```
*
* to
*
* ```
* username
* ✖ Expected number, received string at "username
* favoriteNumbers[0]
* ✖ Invalid input: expected number
* ```
*/
export declare function toDotPath(_path: readonly (string | number | symbol | StandardSchemaV1.PathSegment)[]): string;
export declare function prettifyError(error: StandardSchemaV1.FailureResult): string;
export {};
+225
View File
@@ -0,0 +1,225 @@
import type { $ZodCheck, $ZodStringFormats } from "./checks.js";
import { $constructor } from "./core.js";
import type { $ZodType } from "./schemas.js";
import type { StandardSchemaV1 } from "./standard-schema.js";
import * as util from "./util.js";
export interface $ZodIssueBase {
readonly code?: string;
readonly input?: unknown;
readonly path: PropertyKey[];
readonly message: string;
}
export type $ZodInvalidTypeExpected = "string" | "number" | "int" | "boolean" | "bigint" | "symbol" | "undefined" | "null" | "never" | "void" | "date" | "array" | "object" | "tuple" | "record" | "map" | "set" | "file" | "nonoptional" | "nan" | "function" | (string & {});
export interface $ZodIssueInvalidType<Input = unknown> extends $ZodIssueBase {
readonly code: "invalid_type";
readonly expected: $ZodInvalidTypeExpected;
readonly input?: Input;
}
export interface $ZodIssueTooBig<Input = unknown> extends $ZodIssueBase {
readonly code: "too_big";
readonly origin: "number" | "int" | "bigint" | "date" | "string" | "array" | "set" | "file" | (string & {});
readonly maximum: number | bigint;
readonly inclusive?: boolean;
readonly exact?: boolean;
readonly input?: Input;
}
export interface $ZodIssueTooSmall<Input = unknown> extends $ZodIssueBase {
readonly code: "too_small";
readonly origin: "number" | "int" | "bigint" | "date" | "string" | "array" | "set" | "file" | (string & {});
readonly minimum: number | bigint;
/** True if the allowable range includes the minimum */
readonly inclusive?: boolean;
/** True if the allowed value is fixed (e.g.` z.length(5)`), not a range (`z.minLength(5)`) */
readonly exact?: boolean;
readonly input?: Input;
}
export interface $ZodIssueInvalidStringFormat extends $ZodIssueBase {
readonly code: "invalid_format";
readonly format: $ZodStringFormats | (string & {});
readonly pattern?: string;
readonly input?: string;
}
export interface $ZodIssueNotMultipleOf<Input extends number | bigint = number | bigint> extends $ZodIssueBase {
readonly code: "not_multiple_of";
readonly divisor: number;
readonly input?: Input;
}
export interface $ZodIssueUnrecognizedKeys extends $ZodIssueBase {
readonly code: "unrecognized_keys";
readonly keys: string[];
readonly input?: Record<string, unknown>;
}
interface $ZodIssueInvalidUnionNoMatch extends $ZodIssueBase {
readonly code: "invalid_union";
readonly errors: $ZodIssue[][];
readonly input?: unknown;
readonly discriminator?: string | undefined;
readonly options?: util.Primitive[];
readonly inclusive?: true;
}
interface $ZodIssueInvalidUnionMultipleMatch extends $ZodIssueBase {
readonly code: "invalid_union";
readonly errors: [];
readonly input?: unknown;
readonly discriminator?: string | undefined;
readonly inclusive: false;
/** Indices of the options that matched */
readonly matches: number[];
}
export type $ZodIssueInvalidUnion = $ZodIssueInvalidUnionNoMatch | $ZodIssueInvalidUnionMultipleMatch;
export interface $ZodIssueInvalidKey<Input = unknown> extends $ZodIssueBase {
readonly code: "invalid_key";
readonly origin: "map" | "record";
readonly issues: $ZodIssue[];
readonly input?: Input;
}
export interface $ZodIssueInvalidElement<Input = unknown> extends $ZodIssueBase {
readonly code: "invalid_element";
readonly origin: "map" | "set";
readonly key: unknown;
readonly issues: $ZodIssue[];
readonly input?: Input;
}
export interface $ZodIssueInvalidValue<Input = unknown> extends $ZodIssueBase {
readonly code: "invalid_value";
readonly values: util.Primitive[];
readonly input?: Input;
}
export interface $ZodIssueCustom extends $ZodIssueBase {
readonly code: "custom";
readonly params?: Record<string, any> | undefined;
readonly input?: unknown;
}
export interface $ZodIssueStringCommonFormats extends $ZodIssueInvalidStringFormat {
format: Exclude<$ZodStringFormats, "regex" | "jwt" | "starts_with" | "ends_with" | "includes">;
}
export interface $ZodIssueStringInvalidRegex extends $ZodIssueInvalidStringFormat {
format: "regex";
pattern: string;
}
export interface $ZodIssueStringInvalidJWT extends $ZodIssueInvalidStringFormat {
format: "jwt";
algorithm?: string;
}
export interface $ZodIssueStringStartsWith extends $ZodIssueInvalidStringFormat {
format: "starts_with";
prefix: string;
}
export interface $ZodIssueStringEndsWith extends $ZodIssueInvalidStringFormat {
format: "ends_with";
suffix: string;
}
export interface $ZodIssueStringIncludes extends $ZodIssueInvalidStringFormat {
format: "includes";
includes: string;
}
export type $ZodStringFormatIssues = $ZodIssueStringCommonFormats | $ZodIssueStringInvalidRegex | $ZodIssueStringInvalidJWT | $ZodIssueStringStartsWith | $ZodIssueStringEndsWith | $ZodIssueStringIncludes;
export type $ZodIssue = $ZodIssueInvalidType | $ZodIssueTooBig | $ZodIssueTooSmall | $ZodIssueInvalidStringFormat | $ZodIssueNotMultipleOf | $ZodIssueUnrecognizedKeys | $ZodIssueInvalidUnion | $ZodIssueInvalidKey | $ZodIssueInvalidElement | $ZodIssueInvalidValue | $ZodIssueCustom;
export type $ZodIssueCode = $ZodIssue["code"];
export type $ZodInternalIssue<T extends $ZodIssueBase = $ZodIssue> = T extends any ? RawIssue<T> : never;
type RawIssue<T extends $ZodIssueBase> = T extends any ? util.Flatten<util.MakePartial<T, "message" | "path"> & {
/** The input data */
readonly input: unknown;
/** The schema or check that originated this issue. */
readonly inst?: $ZodType | $ZodCheck;
/** The schema that owns the issue. Equal to `inst` when a schema originated the issue, and the schema the check was attached to when a check did. */
readonly schema?: $ZodType | undefined;
/** If `true`, Zod will continue executing checks/refinements after this issue. */
readonly continue?: boolean | undefined;
} & Record<string, unknown>> : never;
export type $ZodRawIssue<T extends $ZodIssueBase = $ZodIssue> = $ZodInternalIssue<T>;
export interface $ZodErrorMap<T extends $ZodIssueBase = $ZodIssue> {
(issue: $ZodRawIssue<T>): {
message: string;
} | string | undefined | null;
}
export interface $ZodError<T = unknown> extends Error {
type: T;
issues: $ZodIssue[];
_zod: {
output: T;
def: $ZodIssue[];
};
stack?: string;
name: string;
}
export declare const $ZodError: $constructor<$ZodError>;
interface $ZodRealError<T = any> extends $ZodError<T> {
}
export declare const $ZodRealError: $constructor<$ZodRealError>;
export type $ZodFlattenedError<T, U = string> = _FlattenedError<T, U>;
type _FlattenedError<T, U = string> = {
formErrors: U[];
fieldErrors: {
[P in keyof T]?: U[];
};
};
export declare function flattenError<T>(error: $ZodError<T>): _FlattenedError<T>;
export declare function flattenError<T, U>(error: $ZodError<T>, mapper?: (issue: $ZodIssue) => U): _FlattenedError<T, U>;
type _ZodFormattedError<T, U = string> = T extends [any, ...any[]] ? {
[K in keyof T]?: $ZodFormattedError<T[K], U>;
} : T extends any[] ? {
[k: number]: $ZodFormattedError<T[number], U>;
} : T extends object ? util.Flatten<{
[K in keyof T]?: $ZodFormattedError<T[K], U>;
}> : any;
export type $ZodFormattedError<T, U = string> = {
_errors: U[];
} & util.Flatten<_ZodFormattedError<T, U>>;
export declare function formatError<T>(error: $ZodError<T>): $ZodFormattedError<T>;
export declare function formatError<T, U>(error: $ZodError<T>, mapper?: (issue: $ZodIssue) => U): $ZodFormattedError<T, U>;
export type $ZodErrorTree<T, U = string> = T extends util.Primitive ? {
errors: U[];
} : T extends [any, ...any[]] ? {
errors: U[];
items?: {
[K in keyof T]?: $ZodErrorTree<T[K], U>;
};
} : T extends any[] ? {
errors: U[];
items?: Array<$ZodErrorTree<T[number], U>>;
} : T extends object ? {
errors: U[];
properties?: {
[K in keyof T]?: $ZodErrorTree<T[K], U>;
};
} : {
errors: U[];
};
export declare function treeifyError<T>(error: $ZodError<T>): $ZodErrorTree<T>;
export declare function treeifyError<T, U>(error: $ZodError<T>, mapper?: (issue: $ZodIssue) => U): $ZodErrorTree<T, U>;
/** Format a ZodError as a human-readable string in the following form.
*
* From
*
* ```ts
* ZodError {
* issues: [
* {
* expected: 'string',
* code: 'invalid_type',
* path: [ 'username' ],
* message: 'Invalid input: expected string'
* },
* {
* expected: 'number',
* code: 'invalid_type',
* path: [ 'favoriteNumbers', 1 ],
* message: 'Invalid input: expected number'
* }
* ];
* }
* ```
*
* to
*
* ```
* username
* ✖ Expected number, received string at "username
* favoriteNumbers[0]
* ✖ Invalid input: expected number
* ```
*/
export declare function toDotPath(_path: readonly (string | number | symbol | StandardSchemaV1.PathSegment)[]): string;
export declare function prettifyError(error: StandardSchemaV1.FailureResult): string;
export {};
+267
View File
@@ -0,0 +1,267 @@
import { $constructor } from "./core.js";
import * as util from "./util.js";
/* Computing the message eagerly is expensive (pretty-printed JSON of all
* issues), so defer it until first read. The accessor functions and
* descriptors are shared across instances to keep error construction
* cheap; the computed message is cached on the internals object. The
* setter preserves plain assignment semantics for consumers that
* overwrite `message`. */
function _getMessage() {
const internals = this._zod;
internals.message ?? (internals.message = JSON.stringify(internals.def, util.jsonStringifyReplacer, 2));
return internals.message;
}
function _setMessage(value) {
this._zod.message = value;
}
const _messageDesc = {
get: _getMessage,
set: _setMessage,
enumerable: true,
configurable: true,
};
const _issuesDesc = { value: undefined, enumerable: false };
/* Prototypes that already carry the lazy `toString`. Seeded with the
* intrinsics so that `init` on a foreign object — it accepts any object —
* can never install an accessor onto a prototype we do not own. */
const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
const initializer = (inst, def) => {
inst.name = "$ZodError";
// `_zod` is already non-enumerable: $constructor's init defined it with this same descriptor
_issuesDesc.value = def;
Object.defineProperty(inst, "issues", _issuesDesc);
// Clear the shared slot; a retained `value` pins the last error's issues.
_issuesDesc.value = undefined;
Object.defineProperty(inst, "message", _messageDesc);
/* `toString` lives as a non-enumerable lazy getter on the shared
* prototype; on first access it caches a per-instance closure so
* detached usage still works. */
const proto = Object.getPrototypeOf(inst);
if (!_installedToString.has(proto)) {
_installedToString.add(proto);
Object.defineProperty(proto, "toString", {
configurable: true,
enumerable: false,
get() {
const value = () => this.message;
Object.defineProperty(this, "toString", { value, configurable: true, writable: true });
return value;
},
set(value) {
Object.defineProperty(this, "toString", { value, configurable: true, writable: true });
},
});
}
};
export const $ZodError = $constructor("$ZodError", initializer);
export const $ZodRealError = $constructor("$ZodError", initializer, undefined, {
Parent: Error,
});
/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member
* ("toString", "constructor") would otherwise read through to the prototype, and assigning
* "__proto__" would hit the setter instead of creating a key. */
function node(obj, key, make) {
if (!Object.prototype.hasOwnProperty.call(obj, key)) {
if (key === "__proto__") {
Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });
}
else {
obj[key] = make();
}
}
return obj[key];
}
export function flattenError(error, mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of error.issues) {
if (sub.path.length > 0) {
node(fieldErrors, sub.path[0], () => []).push(mapper(sub));
}
else {
formErrors.push(mapper(sub));
}
}
return { formErrors, fieldErrors };
}
export function formatError(error, mapper = (issue) => issue.message) {
const fieldErrors = { _errors: [] };
const processError = (error, path = []) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union" && issue.errors.length) {
issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));
}
else if (issue.code === "invalid_key") {
processError({ issues: issue.issues }, [...path, ...issue.path]);
}
else if (issue.code === "invalid_element") {
processError({ issues: issue.issues }, [...path, ...issue.path]);
}
else {
const fullpath = [...path, ...issue.path];
if (fullpath.length === 0) {
fieldErrors._errors.push(mapper(issue));
}
else {
let curr = fieldErrors;
let i = 0;
while (i < fullpath.length) {
const el = fullpath[i];
const terminal = i === fullpath.length - 1;
// `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child.
if (el === "_errors") {
if (terminal)
curr._errors.push(mapper(issue));
i++;
continue;
}
// A path element may collide with an inherited property name such as
// "__proto__" or "constructor". Truthiness checks read the prototype
// (so no node is created, then ._errors.push throws), and bracket
// assignment of "__proto__" hits the setter instead of creating an
// own key. Guard the read with hasOwnProperty and create the node
// with defineProperty so any path element becomes a real own key.
if (!Object.prototype.hasOwnProperty.call(curr, el)) {
Object.defineProperty(curr, el, {
value: { _errors: [] },
enumerable: true,
writable: true,
configurable: true,
});
}
const node = curr[el];
if (terminal) {
node._errors.push(mapper(issue));
}
curr = node;
i++;
}
}
}
}
};
processError(error);
return fieldErrors;
}
export function treeifyError(error, mapper = (issue) => issue.message) {
const result = { errors: [] };
const processError = (error, path = []) => {
var _a;
for (const issue of error.issues) {
if (issue.code === "invalid_union" && issue.errors.length) {
// regular union error
issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));
}
else if (issue.code === "invalid_key") {
processError({ issues: issue.issues }, [...path, ...issue.path]);
}
else if (issue.code === "invalid_element") {
processError({ issues: issue.issues }, [...path, ...issue.path]);
}
else {
const fullpath = [...path, ...issue.path];
if (fullpath.length === 0) {
result.errors.push(mapper(issue));
continue;
}
let curr = result;
let i = 0;
while (i < fullpath.length) {
const el = fullpath[i];
const terminal = i === fullpath.length - 1;
if (typeof el === "string") {
curr.properties ?? (curr.properties = {});
// el may collide with an inherited property name ("__proto__",
// "constructor", ...); ??= reads the prototype so the node is never
// created and curr.errors.push throws. Guard with hasOwnProperty and
// create the node with defineProperty so "__proto__" becomes a real
// own key rather than invoking the prototype setter.
if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) {
Object.defineProperty(curr.properties, el, {
value: { errors: [] },
enumerable: true,
writable: true,
configurable: true,
});
}
curr = curr.properties[el];
}
else {
curr.items ?? (curr.items = []);
(_a = curr.items)[el] ?? (_a[el] = { errors: [] });
curr = curr.items[el];
}
if (terminal) {
curr.errors.push(mapper(issue));
}
i++;
}
}
}
};
processError(error);
return result;
}
/** Format a ZodError as a human-readable string in the following form.
*
* From
*
* ```ts
* ZodError {
* issues: [
* {
* expected: 'string',
* code: 'invalid_type',
* path: [ 'username' ],
* message: 'Invalid input: expected string'
* },
* {
* expected: 'number',
* code: 'invalid_type',
* path: [ 'favoriteNumbers', 1 ],
* message: 'Invalid input: expected number'
* }
* ];
* }
* ```
*
* to
*
* ```
* username
* ✖ Expected number, received string at "username
* favoriteNumbers[0]
* ✖ Invalid input: expected number
* ```
*/
export function toDotPath(_path) {
const segs = [];
const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg));
for (const seg of path) {
if (typeof seg === "number")
segs.push(`[${seg}]`);
else if (typeof seg === "symbol")
segs.push(`[${JSON.stringify(String(seg))}]`);
else if (/[^\w$]/.test(seg))
segs.push(`[${JSON.stringify(seg)}]`);
else {
if (segs.length)
segs.push(".");
segs.push(seg);
}
}
return segs.join("");
}
export function prettifyError(error) {
const lines = [];
// sort by path length
const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);
// Process each issue
for (const issue of issues) {
lines.push(`✖ ${issue.message}`);
if (issue.path?.length)
lines.push(` → at ${toDotPath(issue.path)}`);
}
// Convert Map to formatted string
return lines.join("\n");
}
+70
View File
@@ -0,0 +1,70 @@
"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 __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);
};
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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.JSONSchema = exports.JSONSchemaGenerator = exports.toJSONSchema = exports.locales = exports.regexes = exports.toZod = exports.util = void 0;
__exportStar(require("./core.cjs"), exports);
__exportStar(require("./parse.cjs"), exports);
__exportStar(require("./errors.cjs"), exports);
__exportStar(require("./schemas.cjs"), exports);
__exportStar(require("./memoizer.cjs"), exports);
__exportStar(require("./checks.cjs"), exports);
__exportStar(require("./versions.cjs"), exports);
exports.util = __importStar(require("./util.cjs"));
var util_js_1 = require("./util.cjs");
Object.defineProperty(exports, "toZod", { enumerable: true, get: function () { return util_js_1.toZod; } });
exports.regexes = __importStar(require("./regexes.cjs"));
exports.locales = __importStar(require("../locales/index.cjs"));
__exportStar(require("./registries.cjs"), exports);
__exportStar(require("./doc.cjs"), exports);
__exportStar(require("./compile.cjs"), exports);
__exportStar(require("./api.cjs"), exports);
__exportStar(require("./to-json-schema.cjs"), exports);
var json_schema_processors_js_1 = require("./json-schema-processors.cjs");
Object.defineProperty(exports, "toJSONSchema", { enumerable: true, get: function () { return json_schema_processors_js_1.toJSONSchema; } });
var json_schema_generator_js_1 = require("./json-schema-generator.cjs");
Object.defineProperty(exports, "JSONSchemaGenerator", { enumerable: true, get: function () { return json_schema_generator_js_1.JSONSchemaGenerator; } });
exports.JSONSchema = __importStar(require("./json-schema.cjs"));
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+19
View File
@@ -0,0 +1,19 @@
export * from "./core.cjs";
export * from "./parse.cjs";
export * from "./errors.cjs";
export * from "./schemas.cjs";
export * from "./memoizer.cjs";
export * from "./checks.cjs";
export * from "./versions.cjs";
export * as util from "./util.cjs";
export { toZod } from "./util.cjs";
export * as regexes from "./regexes.cjs";
export * as locales from "../locales/index.cjs";
export * from "./registries.cjs";
export * from "./doc.cjs";
export * from "./compile.cjs";
export * from "./api.cjs";
export * from "./to-json-schema.cjs";
export { toJSONSchema } from "./json-schema-processors.cjs";
export { JSONSchemaGenerator } from "./json-schema-generator.cjs";
export * as JSONSchema from "./json-schema.cjs";
+19
View File
@@ -0,0 +1,19 @@
export * from "./core.js";
export * from "./parse.js";
export * from "./errors.js";
export * from "./schemas.js";
export * from "./memoizer.js";
export * from "./checks.js";
export * from "./versions.js";
export * as util from "./util.js";
export { toZod } from "./util.js";
export * as regexes from "./regexes.js";
export * as locales from "../locales/index.js";
export * from "./registries.js";
export * from "./doc.js";
export * from "./compile.js";
export * from "./api.js";
export * from "./to-json-schema.js";
export { toJSONSchema } from "./json-schema-processors.js";
export { JSONSchemaGenerator } from "./json-schema-generator.js";
export * as JSONSchema from "./json-schema.js";
+19
View File
@@ -0,0 +1,19 @@
export * from "./core.js";
export * from "./parse.js";
export * from "./errors.js";
export * from "./schemas.js";
export * from "./memoizer.js";
export * from "./checks.js";
export * from "./versions.js";
export * as util from "./util.js";
export { toZod } from "./util.js";
export * as regexes from "./regexes.js";
export * as locales from "../locales/index.js";
export * from "./registries.js";
export * from "./doc.js";
export * from "./compile.js";
export * from "./api.js";
export * from "./to-json-schema.js";
export { toJSONSchema } from "./json-schema-processors.js";
export { JSONSchemaGenerator } from "./json-schema-generator.js";
export * as JSONSchema from "./json-schema.js";
+122
View File
@@ -0,0 +1,122 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.JSONSchemaGenerator = void 0;
const json_schema_processors_js_1 = require("./json-schema-processors.cjs");
const to_json_schema_js_1 = require("./to-json-schema.cjs");
/**
* Legacy class-based interface for JSON Schema generation.
* This class wraps the new functional implementation to provide backward compatibility.
*
* @deprecated Use the `toJSONSchema` function instead for new code.
*
* @example
* ```typescript
* // Legacy usage (still supported)
* const gen = new JSONSchemaGenerator({ target: "draft-07" });
* gen.process(schema);
* const result = gen.emit(schema);
*
* // Preferred modern usage
* const result = toJSONSchema(schema, { target: "draft-07" });
* ```
*/
class JSONSchemaGenerator {
/** @deprecated Access via ctx instead */
get metadataRegistry() {
return this.ctx.metadataRegistry;
}
/** @deprecated Access via ctx instead */
get target() {
return this.ctx.target;
}
// annotated so the .d.cts emits an indexed access rather than an inline `import()` of an ESM path
/** @deprecated Access via ctx instead */
get unrepresentable() {
return this.ctx.unrepresentable;
}
/** @deprecated Access via ctx instead */
get override() {
return this.ctx.override;
}
/** @deprecated Access via ctx instead */
get io() {
return this.ctx.io;
}
/** @deprecated Access via ctx instead */
get counter() {
return this.ctx.counter;
}
set counter(value) {
this.ctx.counter = value;
}
/** @deprecated Access via ctx instead */
get seen() {
return this.ctx.seen;
}
constructor(params) {
// Normalize target for internal context
let normalizedTarget = params?.target ?? "draft-2020-12";
if (normalizedTarget === "draft-4")
normalizedTarget = "draft-04";
if (normalizedTarget === "draft-7")
normalizedTarget = "draft-07";
this.ctx = (0, to_json_schema_js_1.initializeContext)({
processors: json_schema_processors_js_1.allProcessors,
target: normalizedTarget,
...(params?.metadata && { metadata: params.metadata }),
...(params?.unrepresentable && { unrepresentable: params.unrepresentable }),
...(params?.override && { override: params.override }),
...(params?.io && { io: params.io }),
});
}
/**
* Process a schema to prepare it for JSON Schema generation.
* This must be called before emit().
*/
process(schema, _params = { path: [], schemaPath: [] }) {
return (0, to_json_schema_js_1.processSchema)(schema, this.ctx, _params);
}
/**
* Emit the final JSON Schema after processing.
* Must call process() first.
*/
emit(schema, _params) {
// Apply emit params to the context
if (_params) {
if (_params.cycles)
this.ctx.cycles = _params.cycles;
if (_params.reused)
this.ctx.reused = _params.reused;
if (_params.external)
this.ctx.external = _params.external;
}
// extractDefs/finalize skip their whole-map passes when they have already run for this `external`, but they also branch on `cycles`, `reused`, `seen.count` and the metadata registry — any of which can change between emits, including with no params at all. Drop the guards so the passes re-run. The registry conversion calls extractDefs/finalize directly and never routes through here, so it keeps skipping them.
this.ctx.sharedDefsExtractedFor = undefined;
this.ctx.sharedEmitDoneFor = undefined;
(0, to_json_schema_js_1.extractDefs)(this.ctx, schema);
const result = (0, to_json_schema_js_1.finalize)(this.ctx, schema);
// Strip ~standard property to match old implementation's return type
const { "~standard": _, ...plainResult } = result;
return plainResult;
}
}
exports.JSONSchemaGenerator = JSONSchemaGenerator;
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+65
View File
@@ -0,0 +1,65 @@
import type * as JSONSchema from "./json-schema.cjs";
import type { $ZodRegistry } from "./registries.cjs";
import type * as schemas from "./schemas.cjs";
import { type JSONSchemaGeneratorParams, type ProcessParams, type Seen, type ToJSONSchemaContext } from "./to-json-schema.cjs";
/**
* Parameters for the emit method of JSONSchemaGenerator.
* @deprecated Use toJSONSchema function instead
*/
export type EmitParams = Pick<JSONSchemaGeneratorParams, "cycles" | "reused" | "external">;
/**
* Parameters for JSONSchemaGenerator constructor.
* @deprecated Use toJSONSchema function instead
*/
type JSONSchemaGeneratorConstructorParams = Pick<JSONSchemaGeneratorParams, "metadata" | "target" | "unrepresentable" | "override" | "io">;
/**
* Legacy class-based interface for JSON Schema generation.
* This class wraps the new functional implementation to provide backward compatibility.
*
* @deprecated Use the `toJSONSchema` function instead for new code.
*
* @example
* ```typescript
* // Legacy usage (still supported)
* const gen = new JSONSchemaGenerator({ target: "draft-07" });
* gen.process(schema);
* const result = gen.emit(schema);
*
* // Preferred modern usage
* const result = toJSONSchema(schema, { target: "draft-07" });
* ```
*/
export declare class JSONSchemaGenerator {
private ctx;
/** @deprecated Access via ctx instead */
get metadataRegistry(): $ZodRegistry<Record<string, any>>;
/** @deprecated Access via ctx instead */
get target(): ({} & string) | "draft-2020-12" | "draft-07" | "openapi-3.0" | "draft-04";
/** @deprecated Access via ctx instead */
get unrepresentable(): ToJSONSchemaContext["unrepresentable"];
/** @deprecated Access via ctx instead */
get override(): (ctx: {
zodSchema: schemas.$ZodType;
jsonSchema: JSONSchema.BaseSchema;
path: (string | number)[];
}) => void;
/** @deprecated Access via ctx instead */
get io(): "input" | "output";
/** @deprecated Access via ctx instead */
get counter(): number;
set counter(value: number);
/** @deprecated Access via ctx instead */
get seen(): Map<schemas.$ZodType, Seen>;
constructor(params?: JSONSchemaGeneratorConstructorParams);
/**
* Process a schema to prepare it for JSON Schema generation.
* This must be called before emit().
*/
process(schema: schemas.$ZodType, _params?: ProcessParams): JSONSchema.BaseSchema;
/**
* Emit the final JSON Schema after processing.
* Must call process() first.
*/
emit(schema: schemas.$ZodType, _params?: EmitParams): JSONSchema.BaseSchema;
}
export {};
+65
View File
@@ -0,0 +1,65 @@
import type * as JSONSchema from "./json-schema.js";
import type { $ZodRegistry } from "./registries.js";
import type * as schemas from "./schemas.js";
import { type JSONSchemaGeneratorParams, type ProcessParams, type Seen, type ToJSONSchemaContext } from "./to-json-schema.js";
/**
* Parameters for the emit method of JSONSchemaGenerator.
* @deprecated Use toJSONSchema function instead
*/
export type EmitParams = Pick<JSONSchemaGeneratorParams, "cycles" | "reused" | "external">;
/**
* Parameters for JSONSchemaGenerator constructor.
* @deprecated Use toJSONSchema function instead
*/
type JSONSchemaGeneratorConstructorParams = Pick<JSONSchemaGeneratorParams, "metadata" | "target" | "unrepresentable" | "override" | "io">;
/**
* Legacy class-based interface for JSON Schema generation.
* This class wraps the new functional implementation to provide backward compatibility.
*
* @deprecated Use the `toJSONSchema` function instead for new code.
*
* @example
* ```typescript
* // Legacy usage (still supported)
* const gen = new JSONSchemaGenerator({ target: "draft-07" });
* gen.process(schema);
* const result = gen.emit(schema);
*
* // Preferred modern usage
* const result = toJSONSchema(schema, { target: "draft-07" });
* ```
*/
export declare class JSONSchemaGenerator {
private ctx;
/** @deprecated Access via ctx instead */
get metadataRegistry(): $ZodRegistry<Record<string, any>>;
/** @deprecated Access via ctx instead */
get target(): ({} & string) | "draft-2020-12" | "draft-07" | "openapi-3.0" | "draft-04";
/** @deprecated Access via ctx instead */
get unrepresentable(): ToJSONSchemaContext["unrepresentable"];
/** @deprecated Access via ctx instead */
get override(): (ctx: {
zodSchema: schemas.$ZodType;
jsonSchema: JSONSchema.BaseSchema;
path: (string | number)[];
}) => void;
/** @deprecated Access via ctx instead */
get io(): "input" | "output";
/** @deprecated Access via ctx instead */
get counter(): number;
set counter(value: number);
/** @deprecated Access via ctx instead */
get seen(): Map<schemas.$ZodType, Seen>;
constructor(params?: JSONSchemaGeneratorConstructorParams);
/**
* Process a schema to prepare it for JSON Schema generation.
* This must be called before emit().
*/
process(schema: schemas.$ZodType, _params?: ProcessParams): JSONSchema.BaseSchema;
/**
* Emit the final JSON Schema after processing.
* Must call process() first.
*/
emit(schema: schemas.$ZodType, _params?: EmitParams): JSONSchema.BaseSchema;
}
export {};
+99
View File
@@ -0,0 +1,99 @@
import { allProcessors } from "./json-schema-processors.js";
import { extractDefs, finalize, initializeContext, processSchema, } from "./to-json-schema.js";
/**
* Legacy class-based interface for JSON Schema generation.
* This class wraps the new functional implementation to provide backward compatibility.
*
* @deprecated Use the `toJSONSchema` function instead for new code.
*
* @example
* ```typescript
* // Legacy usage (still supported)
* const gen = new JSONSchemaGenerator({ target: "draft-07" });
* gen.process(schema);
* const result = gen.emit(schema);
*
* // Preferred modern usage
* const result = toJSONSchema(schema, { target: "draft-07" });
* ```
*/
export class JSONSchemaGenerator {
/** @deprecated Access via ctx instead */
get metadataRegistry() {
return this.ctx.metadataRegistry;
}
/** @deprecated Access via ctx instead */
get target() {
return this.ctx.target;
}
// annotated so the .d.cts emits an indexed access rather than an inline `import()` of an ESM path
/** @deprecated Access via ctx instead */
get unrepresentable() {
return this.ctx.unrepresentable;
}
/** @deprecated Access via ctx instead */
get override() {
return this.ctx.override;
}
/** @deprecated Access via ctx instead */
get io() {
return this.ctx.io;
}
/** @deprecated Access via ctx instead */
get counter() {
return this.ctx.counter;
}
set counter(value) {
this.ctx.counter = value;
}
/** @deprecated Access via ctx instead */
get seen() {
return this.ctx.seen;
}
constructor(params) {
// Normalize target for internal context
let normalizedTarget = params?.target ?? "draft-2020-12";
if (normalizedTarget === "draft-4")
normalizedTarget = "draft-04";
if (normalizedTarget === "draft-7")
normalizedTarget = "draft-07";
this.ctx = initializeContext({
processors: allProcessors,
target: normalizedTarget,
...(params?.metadata && { metadata: params.metadata }),
...(params?.unrepresentable && { unrepresentable: params.unrepresentable }),
...(params?.override && { override: params.override }),
...(params?.io && { io: params.io }),
});
}
/**
* Process a schema to prepare it for JSON Schema generation.
* This must be called before emit().
*/
process(schema, _params = { path: [], schemaPath: [] }) {
return processSchema(schema, this.ctx, _params);
}
/**
* Emit the final JSON Schema after processing.
* Must call process() first.
*/
emit(schema, _params) {
// Apply emit params to the context
if (_params) {
if (_params.cycles)
this.ctx.cycles = _params.cycles;
if (_params.reused)
this.ctx.reused = _params.reused;
if (_params.external)
this.ctx.external = _params.external;
}
// extractDefs/finalize skip their whole-map passes when they have already run for this `external`, but they also branch on `cycles`, `reused`, `seen.count` and the metadata registry — any of which can change between emits, including with no params at all. Drop the guards so the passes re-run. The registry conversion calls extractDefs/finalize directly and never routes through here, so it keeps skipping them.
this.ctx.sharedDefsExtractedFor = undefined;
this.ctx.sharedEmitDoneFor = undefined;
extractDefs(this.ctx, schema);
const result = finalize(this.ctx, schema);
// Strip ~standard property to match old implementation's return type
const { "~standard": _, ...plainResult } = result;
return plainResult;
}
}
+929
View File
@@ -0,0 +1,929 @@
"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.allProcessors = exports.lazyProcessor = exports.optionalProcessor = exports.promiseProcessor = exports.readonlyProcessor = exports.pipeProcessor = exports.catchProcessor = exports.prefaultProcessor = exports.defaultProcessor = exports.nonoptionalProcessor = exports.nullableProcessor = exports.recordProcessor = exports.tupleProcessor = exports.intersectionProcessor = exports.unionProcessor = exports.objectProcessor = exports.arrayProcessor = exports.setProcessor = exports.mapProcessor = exports.transformProcessor = exports.functionProcessor = exports.customProcessor = exports.successProcessor = exports.fileProcessor = exports.templateLiteralProcessor = exports.nanProcessor = exports.literalProcessor = exports.enumProcessor = exports.dateProcessor = exports.unknownProcessor = exports.anyProcessor = exports.neverProcessor = exports.voidProcessor = exports.undefinedProcessor = exports.nullProcessor = exports.symbolProcessor = exports.bigintProcessor = exports.booleanProcessor = exports.numberProcessor = exports.stringProcessor = void 0;
exports.aggregateChecks = aggregateChecks;
exports.toJSONSchema = toJSONSchema;
const regexes = __importStar(require("./regexes.cjs"));
const schemas_js_1 = require("./schemas.cjs");
const to_json_schema_js_1 = require("./to-json-schema.cjs");
const util_js_1 = require("./util.cjs");
const narrowMin = (agg, key, value) => {
if (agg[key] === undefined || value > agg[key])
agg[key] = value;
};
const narrowMax = (agg, key, value) => {
if (agg[key] === undefined || value < agg[key])
agg[key] = value;
};
const narrowBoth = (agg, value) => {
narrowMin(agg, "minimum", value);
narrowMax(agg, "maximum", value);
};
const addDivisor = (agg, value) => {
agg.multipleOf ?? (agg.multipleOf = []);
if (!agg.multipleOf.includes(value))
agg.multipleOf.push(value);
};
const addPattern = (agg, pattern) => {
agg.patterns ?? (agg.patterns = new Set());
agg.patterns.add(pattern);
};
const intersectMime = (agg, mime) => {
agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];
};
// last-wins, matching the bag's historical write order; the flag keeps an integer format from being lost to a later float one
const setFormat = (agg, format) => {
agg.format = format;
if (format.includes("int"))
agg.isInt = true;
};
const minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum);
const maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum);
const formatContributor = (ranges) => (agg, def) => {
setFormat(agg, def.format);
const [minimum, maximum] = ranges[def.format];
narrowMin(agg, "minimum", minimum);
narrowMax(agg, "maximum", maximum);
};
const contributors = {
greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value),
less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value),
multiple_of: (agg, def) => addDivisor(agg, def.value),
number_format: formatContributor(util_js_1.NUMBER_FORMAT_RANGES),
bigint_format: formatContributor(util_js_1.BIGINT_FORMAT_RANGES),
min_length: minContributor,
max_length: maxContributor,
length_equals: (agg, def) => narrowBoth(agg, def.length),
min_size: minContributor,
max_size: maxContributor,
size_equals: (agg, def) => narrowBoth(agg, def.size),
string_format: (agg, def) => {
setFormat(agg, def.format);
if (def.pattern)
addPattern(agg, def.pattern);
if (def.format === "base64" || def.format === "base64url")
agg.contentEncoding = def.format;
if (def.local || def.precision === -1)
agg.laxFormat = true;
},
mime_type: (agg, def) => intersectMime(agg, def.mime),
};
function aggregateChecks(schema) {
const agg = {};
const def = schema._zod.def;
// a format schema is its own first check, same rule as $ZodType init
const list = schema._zod.traits.has("$ZodCheck")
? [schema, ...(def.checks ?? [])]
: (def.checks ?? []);
for (const ch of list)
contributors[ch._zod.def.check]?.(agg, ch._zod.def);
// reconcile with the bag so third-party onattach contributions still land; first-party residue is never tighter than the fold, so merging it back is idempotent for one and additive for the other
const bag = schema._zod.bag;
if (bag.minimum !== undefined)
narrowMin(agg, "minimum", bag.minimum);
if (bag.exclusiveMinimum !== undefined)
narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum);
if (bag.maximum !== undefined)
narrowMax(agg, "maximum", bag.maximum);
if (bag.exclusiveMaximum !== undefined)
narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum);
if (bag.multipleOf !== undefined)
addDivisor(agg, bag.multipleOf);
if (bag.format !== undefined) {
agg.format ?? (agg.format = bag.format);
if (bag.format.includes("int"))
agg.isInt = true;
}
if (bag.mime)
intersectMime(agg, bag.mime);
for (const pattern of bag.patterns ?? [])
addPattern(agg, pattern);
return agg;
}
const formatMap = {
guid: "uuid",
url: "uri",
datetime: "date-time",
json_string: "json-string",
regex: "", // do not set
};
// ==================== SIMPLE TYPE PROCESSORS ====================
// the runtime patterns are lax so parse paths never overflow the regex stack; the emitted schema swaps in the exact block forms, which zod itself never executes
const exactPatterns = new Map([
[schemas_js_1.base64Charset, regexes.base64],
[schemas_js_1.base64urlCharset, regexes.base64url],
]);
const exactPattern = (p) => exactPatterns.get(p) ?? p;
const stringProcessor = (schema, ctx, _json, _params) => {
const json = _json;
json.type = "string";
const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);
if (typeof minimum === "number")
json.minLength = minimum;
if (typeof maximum === "number")
json.maxLength = maximum;
// custom pattern overrides format
if (format) {
json.format = formatMap[format] ?? format;
if (json.format === "")
delete json.format; // empty format is not valid
// `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids
if (format === "time" || laxFormat) {
delete json.format;
}
}
if (contentEncoding)
json.contentEncoding = contentEncoding;
if (patterns && patterns.size > 0) {
const patternList = [...patterns].map(exactPattern);
if (patternList.length === 1)
json.pattern = patternList[0].source;
else if (patternList.length > 1) {
json.allOf = [
...patternList.map((regex) => ({
...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0"
? { type: "string" }
: {}),
pattern: regex.source,
})),
];
}
}
};
exports.stringProcessor = stringProcessor;
const numberProcessor = (schema, ctx, _json, params) => {
const json = _json;
const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);
json.type = isInt ? "integer" : "number";
// when both minimum and exclusiveMinimum exist, pick the more restrictive one
const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
if (exMin) {
if (legacy) {
json.minimum = exclusiveMinimum;
json.exclusiveMinimum = true;
}
else {
json.exclusiveMinimum = exclusiveMinimum;
}
}
else if (typeof minimum === "number") {
json.minimum = minimum;
}
if (exMax) {
if (legacy) {
json.maximum = exclusiveMaximum;
json.exclusiveMaximum = true;
}
else {
json.exclusiveMaximum = exclusiveMaximum;
}
}
else if (typeof maximum === "number") {
json.maximum = maximum;
}
if (multipleOf) {
// JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form.
const divisors = new Set();
for (const divisor of multipleOf) {
if (Number.isFinite(divisor) && divisor !== 0)
divisors.add(Math.abs(divisor));
else
(0, to_json_schema_js_1.handleUnrepresentable)(schema, ctx, json, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);
}
// chained divisors are a conjunction the keyword cannot carry alone, so extras ride an allOf, same as stacked patterns
const [first, ...rest] = divisors;
if (first !== undefined)
json.multipleOf = first;
if (rest.length)
json.allOf = [...(json.allOf ?? []), ...rest.map((m) => ({ multipleOf: m }))];
}
};
exports.numberProcessor = numberProcessor;
const booleanProcessor = (_schema, _ctx, json, _params) => {
json.type = "boolean";
};
exports.booleanProcessor = booleanProcessor;
const bigintProcessor = (schema, ctx, json, params) => {
(0, to_json_schema_js_1.handleUnrepresentable)(schema, ctx, json, params, "BigInt cannot be represented in JSON Schema");
};
exports.bigintProcessor = bigintProcessor;
const symbolProcessor = (schema, ctx, json, params) => {
(0, to_json_schema_js_1.handleUnrepresentable)(schema, ctx, json, params, "Symbols cannot be represented in JSON Schema");
};
exports.symbolProcessor = symbolProcessor;
const nullProcessor = (_schema, ctx, json, _params) => {
if (ctx.target === "openapi-3.0") {
json.type = "string";
json.nullable = true;
json.enum = [null];
}
else {
json.type = "null";
}
};
exports.nullProcessor = nullProcessor;
const undefinedProcessor = (schema, ctx, json, params) => {
(0, to_json_schema_js_1.handleUnrepresentable)(schema, ctx, json, params, "Undefined cannot be represented in JSON Schema");
};
exports.undefinedProcessor = undefinedProcessor;
const voidProcessor = (schema, ctx, json, params) => {
(0, to_json_schema_js_1.handleUnrepresentable)(schema, ctx, json, params, "Void cannot be represented in JSON Schema");
};
exports.voidProcessor = voidProcessor;
const neverProcessor = (_schema, _ctx, json, _params) => {
json.not = {};
};
exports.neverProcessor = neverProcessor;
const anyProcessor = (_schema, _ctx, _json, _params) => {
// empty schema accepts anything
};
exports.anyProcessor = anyProcessor;
const unknownProcessor = (_schema, _ctx, _json, _params) => {
// empty schema accepts anything
};
exports.unknownProcessor = unknownProcessor;
const dateProcessor = (schema, ctx, json, params) => {
(0, to_json_schema_js_1.handleUnrepresentable)(schema, ctx, json, params, "Date cannot be represented in JSON Schema");
};
exports.dateProcessor = dateProcessor;
const enumProcessor = (schema, _ctx, json, _params) => {
const def = schema._zod.def;
const values = (0, util_js_1.getEnumValues)(def.entries);
// an empty enum accepts nothing, same as z.never()
if (values.length === 0) {
json.not = {};
return;
}
// Number enums can have both string and number values
if (values.every((v) => typeof v === "number"))
json.type = "number";
if (values.every((v) => typeof v === "string"))
json.type = "string";
json.enum = values;
};
exports.enumProcessor = enumProcessor;
const literalProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
// a literal with no values accepts nothing, same as z.never()
if (def.values.length === 0) {
json.not = {};
return;
}
const vals = [];
for (const val of def.values) {
if (val === undefined) {
// a custom schema replaces the whole literal, so there is nothing left to accumulate
if ((0, to_json_schema_js_1.handleUnrepresentable)(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema"))
return;
// otherwise do not add to vals
}
else if (typeof val === "bigint") {
if ((0, to_json_schema_js_1.handleUnrepresentable)(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema"))
return;
vals.push(Number(val));
}
else {
vals.push(val);
}
}
if (vals.length === 0) {
// do nothing (an undefined literal was stripped)
}
else if (vals.length === 1) {
const val = vals[0];
json.type = val === null ? "null" : typeof val;
if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
json.enum = [val];
}
else {
json.const = val;
}
}
else {
if (vals.every((v) => typeof v === "number"))
json.type = "number";
if (vals.every((v) => typeof v === "string"))
json.type = "string";
if (vals.every((v) => typeof v === "boolean"))
json.type = "boolean";
if (vals.every((v) => v === null))
json.type = "null";
json.enum = vals;
}
};
exports.literalProcessor = literalProcessor;
const nanProcessor = (schema, ctx, json, params) => {
(0, to_json_schema_js_1.handleUnrepresentable)(schema, ctx, json, params, "NaN cannot be represented in JSON Schema");
};
exports.nanProcessor = nanProcessor;
const templateLiteralProcessor = (schema, _ctx, json, _params) => {
const _json = json;
const pattern = schema._zod.pattern;
if (!pattern)
throw new Error("Pattern not found in template literal");
_json.type = "string";
_json.pattern = pattern.source;
};
exports.templateLiteralProcessor = templateLiteralProcessor;
const fileProcessor = (schema, _ctx, json, _params) => {
const _json = json;
_json.type = "string";
_json.format = "binary";
_json.contentEncoding = "binary";
const { minimum, maximum, mime } = aggregateChecks(schema);
if (minimum !== undefined)
_json.minLength = minimum;
if (maximum !== undefined)
_json.maxLength = maximum;
if (!mime)
return;
// an empty intersection means the mime checks share no value, so nothing passes at runtime; `anyOf` must be non-empty, so the false schema is `not: {}`
if (mime.length === 0)
_json.not = {};
else if (mime.length === 1)
_json.contentMediaType = mime[0];
// only contentMediaType differs, so the shared props stay at the root
else
_json.anyOf = mime.map((m) => ({ contentMediaType: m }));
};
exports.fileProcessor = fileProcessor;
const successProcessor = (_schema, _ctx, json, _params) => {
json.type = "boolean";
};
exports.successProcessor = successProcessor;
const customProcessor = (schema, ctx, json, params) => {
(0, to_json_schema_js_1.handleUnrepresentable)(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema");
};
exports.customProcessor = customProcessor;
const functionProcessor = (schema, ctx, json, params) => {
(0, to_json_schema_js_1.handleUnrepresentable)(schema, ctx, json, params, "Function types cannot be represented in JSON Schema");
};
exports.functionProcessor = functionProcessor;
const transformProcessor = (schema, ctx, json, params) => {
(0, to_json_schema_js_1.handleUnrepresentable)(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema");
};
exports.transformProcessor = transformProcessor;
const mapProcessor = (schema, ctx, json, params) => {
(0, to_json_schema_js_1.handleUnrepresentable)(schema, ctx, json, params, "Map cannot be represented in JSON Schema");
};
exports.mapProcessor = mapProcessor;
const setProcessor = (schema, ctx, json, params) => {
(0, to_json_schema_js_1.handleUnrepresentable)(schema, ctx, json, params, "Set cannot be represented in JSON Schema");
};
exports.setProcessor = setProcessor;
// ==================== COMPOSITE TYPE PROCESSORS ====================
const arrayProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
const { minimum, maximum } = aggregateChecks(schema);
if (typeof minimum === "number")
json.minItems = minimum;
if (typeof maximum === "number")
json.maxItems = maximum;
json.type = "array";
json.items = (0, to_json_schema_js_1.processSchema)(def.element, ctx, {
...params,
path: [...params.path, "items"],
});
};
exports.arrayProcessor = arrayProcessor;
// Transform and catch set `optin = "optional"` at runtime so the parser lets them observe an
// absent key, but their declared input type stays required. An input JSON Schema describes the
// declared type, so resolve past them to the schema that actually carries the optionality.
// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see
// wiki/optionality.md, "The JSON Schema emitter reads the *static* value".
function inputOptin(schema) {
const def = schema._zod.def;
if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) {
return inputOptin(def.out);
}
if (def.type === "catch") {
return inputOptin(def.innerType);
}
return schema._zod.optin;
}
const objectProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
const shape = def.shape;
// dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires
const symbolKeys = Object.getOwnPropertySymbols(shape);
if (symbolKeys.length &&
(0, to_json_schema_js_1.handleUnrepresentable)(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) {
return;
}
json.type = "object";
json.properties = {};
for (const key in shape) {
// assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into
(0, util_js_1.assignProp)(json.properties, key, (0, to_json_schema_js_1.processSchema)(shape[key], ctx, {
...params,
path: [...params.path, "properties", key],
}));
}
// required keys
const requiredKeys = [];
for (const key of Object.keys(shape)) {
const field = def.shape[key];
if (ctx.io === "input" ? inputOptin(field) === undefined : field._zod.optout === undefined) {
requiredKeys.push(key);
}
}
if (requiredKeys.length > 0) {
json.required = requiredKeys;
}
// catchall
if (def.catchall?._zod.def.type === "never") {
// strict
json.additionalProperties = false;
}
else if (!def.catchall) {
// regular
if (ctx.io === "output")
json.additionalProperties = false;
}
else if (def.catchall) {
json.additionalProperties = (0, to_json_schema_js_1.processSchema)(def.catchall, ctx, {
...params,
path: [...params.path, "additionalProperties"],
});
}
};
exports.objectProcessor = objectProcessor;
const unionProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
// Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions
const isExclusive = def.inclusive === false;
const options = def.options.map((x, i) => (0, to_json_schema_js_1.processSchema)(x, ctx, {
...params,
path: [...params.path, isExclusive ? "oneOf" : "anyOf", i],
}));
if (isExclusive) {
json.oneOf = options;
}
else {
json.anyOf = options;
}
};
exports.unionProcessor = unionProcessor;
const intersectionProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
const a = (0, to_json_schema_js_1.processSchema)(def.left, ctx, {
...params,
path: [...params.path, "allOf", 0],
});
const b = (0, to_json_schema_js_1.processSchema)(def.right, ctx, {
...params,
path: [...params.path, "allOf", 1],
});
const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
const allOf = [
...(isSimpleIntersection(a) ? a.allOf : [a]),
...(isSimpleIntersection(b) ? b.allOf : [b]),
];
json.allOf = allOf;
// Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`.
ctx.intersections.push(allOf);
};
exports.intersectionProcessor = intersectionProcessor;
const tupleProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
json.type = "array";
const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items";
const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems";
const prefixItems = def.items.map((x, i) => (0, to_json_schema_js_1.processSchema)(x, ctx, {
...params,
path: [...params.path, prefixPath, i],
}));
const rest = def.rest
? (0, to_json_schema_js_1.processSchema)(def.rest, ctx, {
...params,
path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])],
})
: null;
let minItems = def.items.length;
while (minItems > 0) {
const item = def.items[minItems - 1];
const optional = ctx.io === "input" ? inputOptin(item) !== undefined : item._zod.optout === "optional";
if (!optional)
break;
minItems--;
}
const maxItems = def.items.length;
const isClosed = !def.rest;
if (ctx.target === "draft-2020-12") {
json.prefixItems = prefixItems;
if (isClosed) {
json.items = false;
}
else if (rest) {
json.items = rest;
}
if (minItems > 0)
json.minItems = minItems;
if (isClosed)
json.maxItems = maxItems;
}
else if (ctx.target === "openapi-3.0") {
json.items = {
anyOf: prefixItems,
};
if (rest) {
json.items.anyOf.push(rest);
}
if (minItems > 0)
json.minItems = minItems;
if (isClosed)
json.maxItems = maxItems;
}
else {
json.items = prefixItems;
if (isClosed) {
json.additionalItems = false;
}
else if (rest) {
json.additionalItems = rest;
}
if (minItems > 0)
json.minItems = minItems;
if (isClosed)
json.maxItems = maxItems;
}
// explicit user-defined length checks take precedence
const { minimum, maximum } = aggregateChecks(schema);
if (typeof minimum === "number")
json.minItems = minimum;
if (typeof maximum === "number")
json.maxItems = maximum;
};
exports.tupleProcessor = tupleProcessor;
/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the
* numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key
* behind a wrapper only carries its own `type` before then, and a union key only has its branches.
*
* A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather
* than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this
* exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)`
* accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema
* outright. */
function stringifyKeyNames(bySchema, json, visited) {
// an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`.
if (json.$ref) {
// a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again
if (visited.has(json))
return json;
visited.add(json);
const def = bySchema.get(json)?.def;
if (!def)
return json;
const inlined = stringifyKeyNames(bySchema, def, visited);
return inlined === def ? json : inlined;
}
for (const keyword of ["anyOf", "oneOf"]) {
const branches = json[keyword];
if (!Array.isArray(branches))
continue;
const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));
// rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id`
if (mapped.some((branch, i) => branch !== branches[i]))
json = { ...json, [keyword]: mapped };
}
// a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric
const types = Array.isArray(json.type) ? json.type : [json.type];
const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer");
// a heterogeneous key carries no type at all, so its numeric members are caught here instead
const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined);
if (!numericType && !values?.some((v) => typeof v === "number"))
return json;
const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;
if (rest.enum)
rest.enum = rest.enum.map((v) => (typeof v === "number" ? String(v) : v));
else if (typeof rest.const === "number")
rest.const = String(rest.const);
// a heterogeneous key keeps its absent type: the stringified members already say what a key may be
if (!numericType)
return rest;
rest.type = "string";
if (!values)
rest.pattern = (types.includes("number") ? regexes.number : regexes.integer).source;
return rest;
}
/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */
const pendingRecords = new WeakMap();
function rewriteKeyNames(ctx) {
// an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it.
const bySchema = new Map();
for (const entry of ctx.seen.values()) {
if (entry.def && !bySchema.has(entry.schema))
bySchema.set(entry.schema, entry);
}
const rewrites = new Map();
for (const record of pendingRecords.get(ctx) ?? []) {
const seen = ctx.seen.get(record);
const names = (seen?.def ?? seen?.schema)?.propertyNames;
if (!names || names === true || rewrites.has(names))
continue;
const rewritten = stringifyKeyNames(bySchema, names, new Set());
if (rewritten !== names)
rewrites.set(names, rewritten);
}
if (!rewrites.size)
return;
// the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together
for (const entry of ctx.seen.values()) {
for (const carrier of [entry.schema, entry.def]) {
const rewritten = carrier && rewrites.get(carrier.propertyNames);
if (rewritten)
carrier.propertyNames = rewritten;
}
}
}
const recordProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
json.type = "object";
// For looseRecord with regex patterns, use patternProperties. This correctly represents "only validate keys matching the pattern" semantics and composes well with allOf (intersections)
const keyType = def.keyType;
const patterns = aggregateChecks(keyType).patterns;
if (def.mode === "loose" && patterns && patterns.size > 0) {
// Use patternProperties for looseRecord with regex patterns
const valueSchema = (0, to_json_schema_js_1.processSchema)(def.valueType, ctx, {
...params,
path: [...params.path, "patternProperties", "*"],
});
json.patternProperties = {};
for (const pattern of patterns) {
(0, util_js_1.assignProp)(json.patternProperties, exactPattern(pattern).source, valueSchema);
}
}
else {
// Default behavior: use propertyNames + additionalProperties
if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
json.propertyNames = (0, to_json_schema_js_1.processSchema)(def.keyType, ctx, {
...params,
path: [...params.path, "propertyNames"],
});
let pending = pendingRecords.get(ctx);
if (!pending) {
pending = [];
pendingRecords.set(ctx, pending);
ctx.deferred.push(() => rewriteKeyNames(ctx));
}
pending.push(schema);
}
json.additionalProperties = (0, to_json_schema_js_1.processSchema)(def.valueType, ctx, {
...params,
path: [...params.path, "additionalProperties"],
});
}
// Add required for keys with discrete values (enum, literal, etc.)
const keyValues = keyType._zod.values;
// Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined.
const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined;
if (keyValues && !def.partial && !omittableOnInput) {
const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
if (validKeyValues.length > 0) {
json.required = validKeyValues.map(String);
}
}
};
exports.recordProcessor = recordProcessor;
const nullableProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
const inner = (0, to_json_schema_js_1.processSchema)(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
if (ctx.target === "openapi-3.0") {
seen.ref = def.innerType;
json.nullable = true;
}
else {
json.anyOf = [inner, { type: "null" }];
}
};
exports.nullableProcessor = nullableProcessor;
const nonoptionalProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
(0, to_json_schema_js_1.processSchema)(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
};
exports.nonoptionalProcessor = nonoptionalProcessor;
/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON.
* A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other
* unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */
const UNREPRESENTABLE_DEFAULT = Symbol();
function serializeDefaultValue(value, schema, ctx, json, params) {
let unrepresentable = false;
const serialized = JSON.stringify(value, (_, val) => {
if (typeof val !== "bigint")
return val;
unrepresentable = true;
return null;
});
if (!unrepresentable)
return JSON.parse(serialized);
(0, to_json_schema_js_1.handleUnrepresentable)(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema");
return UNREPRESENTABLE_DEFAULT;
}
const defaultProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
(0, to_json_schema_js_1.processSchema)(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);
if (value !== UNREPRESENTABLE_DEFAULT)
json.default = value;
};
exports.defaultProcessor = defaultProcessor;
const prefaultProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
(0, to_json_schema_js_1.processSchema)(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
if (ctx.io !== "input")
return;
const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);
if (value !== UNREPRESENTABLE_DEFAULT)
json._prefault = value;
};
exports.prefaultProcessor = prefaultProcessor;
const catchProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
(0, to_json_schema_js_1.processSchema)(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
let catchValue;
try {
catchValue = def.catchValue(undefined);
}
catch {
(0, to_json_schema_js_1.handleUnrepresentable)(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema");
return;
}
json.default = catchValue;
};
exports.catchProcessor = catchProcessor;
const pipeProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
const inIsTransform = def.in._zod.traits.has("$ZodTransform");
const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out;
(0, to_json_schema_js_1.processSchema)(innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = innerType;
};
exports.pipeProcessor = pipeProcessor;
const readonlyProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
(0, to_json_schema_js_1.processSchema)(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
json.readOnly = true;
};
exports.readonlyProcessor = readonlyProcessor;
const promiseProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
(0, to_json_schema_js_1.processSchema)(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
};
exports.promiseProcessor = promiseProcessor;
const optionalProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
(0, to_json_schema_js_1.processSchema)(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
};
exports.optionalProcessor = optionalProcessor;
const lazyProcessor = (schema, ctx, _json, params) => {
const innerType = schema._zod.innerType;
(0, to_json_schema_js_1.processSchema)(innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = innerType;
};
exports.lazyProcessor = lazyProcessor;
// ==================== ALL PROCESSORS ====================
exports.allProcessors = {
string: exports.stringProcessor,
number: exports.numberProcessor,
boolean: exports.booleanProcessor,
bigint: exports.bigintProcessor,
symbol: exports.symbolProcessor,
null: exports.nullProcessor,
undefined: exports.undefinedProcessor,
void: exports.voidProcessor,
never: exports.neverProcessor,
any: exports.anyProcessor,
unknown: exports.unknownProcessor,
date: exports.dateProcessor,
enum: exports.enumProcessor,
literal: exports.literalProcessor,
nan: exports.nanProcessor,
template_literal: exports.templateLiteralProcessor,
file: exports.fileProcessor,
success: exports.successProcessor,
custom: exports.customProcessor,
function: exports.functionProcessor,
transform: exports.transformProcessor,
map: exports.mapProcessor,
set: exports.setProcessor,
array: exports.arrayProcessor,
object: exports.objectProcessor,
union: exports.unionProcessor,
intersection: exports.intersectionProcessor,
tuple: exports.tupleProcessor,
record: exports.recordProcessor,
nullable: exports.nullableProcessor,
nonoptional: exports.nonoptionalProcessor,
default: exports.defaultProcessor,
prefault: exports.prefaultProcessor,
catch: exports.catchProcessor,
pipe: exports.pipeProcessor,
readonly: exports.readonlyProcessor,
promise: exports.promiseProcessor,
optional: exports.optionalProcessor,
lazy: exports.lazyProcessor,
};
function toJSONSchema(input, params) {
if ("_idmap" in input) {
// Registry case
const registry = input;
const ctx = (0, to_json_schema_js_1.initializeContext)({ ...params, processors: exports.allProcessors });
const defs = {};
// First pass: process all schemas to build the seen map
for (const entry of registry._idmap.entries()) {
const [_, schema] = entry;
(0, to_json_schema_js_1.processSchema)(schema, ctx);
}
const schemas = {};
const external = {
registry,
uri: params?.uri,
defs,
};
// Update the context with external configuration
ctx.external = external;
// Second pass: emit each schema
for (const entry of registry._idmap.entries()) {
const [key, schema] = entry;
(0, to_json_schema_js_1.extractDefs)(ctx, schema);
(0, util_js_1.assignProp)(schemas, key, (0, to_json_schema_js_1.finalize)(ctx, schema));
}
if (Object.keys(defs).length > 0) {
const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
schemas.__shared = {
[defsSegment]: defs,
};
}
return { schemas };
}
// Single schema case
const ctx = (0, to_json_schema_js_1.initializeContext)({ ...params, processors: exports.allProcessors });
(0, to_json_schema_js_1.processSchema)(input, ctx);
(0, to_json_schema_js_1.extractDefs)(ctx, input);
return (0, to_json_schema_js_1.finalize)(ctx, input);
}
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+65
View File
@@ -0,0 +1,65 @@
import type { $ZodRegistry } from "./registries.cjs";
import type * as schemas from "./schemas.cjs";
import { type Processor, type RegistryToJSONSchemaParams, type ToJSONSchemaParams, type ZodStandardJSONSchemaPayload } from "./to-json-schema.cjs";
type Bound = number | bigint | Date;
interface CheckAggregate<N extends Bound = Bound> {
minimum?: N;
maximum?: N;
exclusiveMinimum?: N;
exclusiveMaximum?: N;
multipleOf?: number[];
format?: string;
isInt?: boolean;
patterns?: Set<RegExp>;
mime?: string[];
contentEncoding?: string;
laxFormat?: boolean;
}
export declare function aggregateChecks<N extends Bound = Bound>(schema: schemas.$ZodType): CheckAggregate<N>;
export declare const stringProcessor: Processor<schemas.$ZodString>;
export declare const numberProcessor: Processor<schemas.$ZodNumber>;
export declare const booleanProcessor: Processor<schemas.$ZodBoolean>;
export declare const bigintProcessor: Processor<schemas.$ZodBigInt>;
export declare const symbolProcessor: Processor<schemas.$ZodSymbol>;
export declare const nullProcessor: Processor<schemas.$ZodNull>;
export declare const undefinedProcessor: Processor<schemas.$ZodUndefined>;
export declare const voidProcessor: Processor<schemas.$ZodVoid>;
export declare const neverProcessor: Processor<schemas.$ZodNever>;
export declare const anyProcessor: Processor<schemas.$ZodAny>;
export declare const unknownProcessor: Processor<schemas.$ZodUnknown>;
export declare const dateProcessor: Processor<schemas.$ZodDate>;
export declare const enumProcessor: Processor<schemas.$ZodEnum>;
export declare const literalProcessor: Processor<schemas.$ZodLiteral>;
export declare const nanProcessor: Processor<schemas.$ZodNaN>;
export declare const templateLiteralProcessor: Processor<schemas.$ZodTemplateLiteral>;
export declare const fileProcessor: Processor<schemas.$ZodFile>;
export declare const successProcessor: Processor<schemas.$ZodSuccess>;
export declare const customProcessor: Processor<schemas.$ZodCustom>;
export declare const functionProcessor: Processor<schemas.$ZodFunction>;
export declare const transformProcessor: Processor<schemas.$ZodTransform>;
export declare const mapProcessor: Processor<schemas.$ZodMap>;
export declare const setProcessor: Processor<schemas.$ZodSet>;
export declare const arrayProcessor: Processor<schemas.$ZodArray>;
export declare const objectProcessor: Processor<schemas.$ZodObject>;
export declare const unionProcessor: Processor<schemas.$ZodUnion>;
export declare const intersectionProcessor: Processor<schemas.$ZodIntersection>;
export declare const tupleProcessor: Processor<schemas.$ZodTuple>;
export declare const recordProcessor: Processor<schemas.$ZodRecord>;
export declare const nullableProcessor: Processor<schemas.$ZodNullable>;
export declare const nonoptionalProcessor: Processor<schemas.$ZodNonOptional>;
export declare const defaultProcessor: Processor<schemas.$ZodDefault>;
export declare const prefaultProcessor: Processor<schemas.$ZodPrefault>;
export declare const catchProcessor: Processor<schemas.$ZodCatch>;
export declare const pipeProcessor: Processor<schemas.$ZodPipe>;
export declare const readonlyProcessor: Processor<schemas.$ZodReadonly>;
export declare const promiseProcessor: Processor<schemas.$ZodPromise>;
export declare const optionalProcessor: Processor<schemas.$ZodOptional>;
export declare const lazyProcessor: Processor<schemas.$ZodLazy>;
export declare const allProcessors: Record<string, Processor<any>>;
export declare function toJSONSchema<T extends schemas.$ZodType>(schema: T, params?: ToJSONSchemaParams): ZodStandardJSONSchemaPayload<T>;
export declare function toJSONSchema(registry: $ZodRegistry<{
id?: string | undefined;
}>, params?: RegistryToJSONSchemaParams): {
schemas: Record<string, ZodStandardJSONSchemaPayload<schemas.$ZodType>>;
};
export {};
+65
View File
@@ -0,0 +1,65 @@
import type { $ZodRegistry } from "./registries.js";
import type * as schemas from "./schemas.js";
import { type Processor, type RegistryToJSONSchemaParams, type ToJSONSchemaParams, type ZodStandardJSONSchemaPayload } from "./to-json-schema.js";
type Bound = number | bigint | Date;
interface CheckAggregate<N extends Bound = Bound> {
minimum?: N;
maximum?: N;
exclusiveMinimum?: N;
exclusiveMaximum?: N;
multipleOf?: number[];
format?: string;
isInt?: boolean;
patterns?: Set<RegExp>;
mime?: string[];
contentEncoding?: string;
laxFormat?: boolean;
}
export declare function aggregateChecks<N extends Bound = Bound>(schema: schemas.$ZodType): CheckAggregate<N>;
export declare const stringProcessor: Processor<schemas.$ZodString>;
export declare const numberProcessor: Processor<schemas.$ZodNumber>;
export declare const booleanProcessor: Processor<schemas.$ZodBoolean>;
export declare const bigintProcessor: Processor<schemas.$ZodBigInt>;
export declare const symbolProcessor: Processor<schemas.$ZodSymbol>;
export declare const nullProcessor: Processor<schemas.$ZodNull>;
export declare const undefinedProcessor: Processor<schemas.$ZodUndefined>;
export declare const voidProcessor: Processor<schemas.$ZodVoid>;
export declare const neverProcessor: Processor<schemas.$ZodNever>;
export declare const anyProcessor: Processor<schemas.$ZodAny>;
export declare const unknownProcessor: Processor<schemas.$ZodUnknown>;
export declare const dateProcessor: Processor<schemas.$ZodDate>;
export declare const enumProcessor: Processor<schemas.$ZodEnum>;
export declare const literalProcessor: Processor<schemas.$ZodLiteral>;
export declare const nanProcessor: Processor<schemas.$ZodNaN>;
export declare const templateLiteralProcessor: Processor<schemas.$ZodTemplateLiteral>;
export declare const fileProcessor: Processor<schemas.$ZodFile>;
export declare const successProcessor: Processor<schemas.$ZodSuccess>;
export declare const customProcessor: Processor<schemas.$ZodCustom>;
export declare const functionProcessor: Processor<schemas.$ZodFunction>;
export declare const transformProcessor: Processor<schemas.$ZodTransform>;
export declare const mapProcessor: Processor<schemas.$ZodMap>;
export declare const setProcessor: Processor<schemas.$ZodSet>;
export declare const arrayProcessor: Processor<schemas.$ZodArray>;
export declare const objectProcessor: Processor<schemas.$ZodObject>;
export declare const unionProcessor: Processor<schemas.$ZodUnion>;
export declare const intersectionProcessor: Processor<schemas.$ZodIntersection>;
export declare const tupleProcessor: Processor<schemas.$ZodTuple>;
export declare const recordProcessor: Processor<schemas.$ZodRecord>;
export declare const nullableProcessor: Processor<schemas.$ZodNullable>;
export declare const nonoptionalProcessor: Processor<schemas.$ZodNonOptional>;
export declare const defaultProcessor: Processor<schemas.$ZodDefault>;
export declare const prefaultProcessor: Processor<schemas.$ZodPrefault>;
export declare const catchProcessor: Processor<schemas.$ZodCatch>;
export declare const pipeProcessor: Processor<schemas.$ZodPipe>;
export declare const readonlyProcessor: Processor<schemas.$ZodReadonly>;
export declare const promiseProcessor: Processor<schemas.$ZodPromise>;
export declare const optionalProcessor: Processor<schemas.$ZodOptional>;
export declare const lazyProcessor: Processor<schemas.$ZodLazy>;
export declare const allProcessors: Record<string, Processor<any>>;
export declare function toJSONSchema<T extends schemas.$ZodType>(schema: T, params?: ToJSONSchemaParams): ZodStandardJSONSchemaPayload<T>;
export declare function toJSONSchema(registry: $ZodRegistry<{
id?: string | undefined;
}>, params?: RegistryToJSONSchemaParams): {
schemas: Record<string, ZodStandardJSONSchemaPayload<schemas.$ZodType>>;
};
export {};
+843
View File
@@ -0,0 +1,843 @@
import * as regexes from "./regexes.js";
import { base64Charset, base64urlCharset } from "./schemas.js";
import { extractDefs, finalize, handleUnrepresentable, initializeContext, processSchema, } from "./to-json-schema.js";
import { BIGINT_FORMAT_RANGES, NUMBER_FORMAT_RANGES, assignProp, getEnumValues } from "./util.js";
const narrowMin = (agg, key, value) => {
if (agg[key] === undefined || value > agg[key])
agg[key] = value;
};
const narrowMax = (agg, key, value) => {
if (agg[key] === undefined || value < agg[key])
agg[key] = value;
};
const narrowBoth = (agg, value) => {
narrowMin(agg, "minimum", value);
narrowMax(agg, "maximum", value);
};
const addDivisor = (agg, value) => {
agg.multipleOf ?? (agg.multipleOf = []);
if (!agg.multipleOf.includes(value))
agg.multipleOf.push(value);
};
const addPattern = (agg, pattern) => {
agg.patterns ?? (agg.patterns = new Set());
agg.patterns.add(pattern);
};
const intersectMime = (agg, mime) => {
agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];
};
// last-wins, matching the bag's historical write order; the flag keeps an integer format from being lost to a later float one
const setFormat = (agg, format) => {
agg.format = format;
if (format.includes("int"))
agg.isInt = true;
};
const minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum);
const maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum);
const formatContributor = (ranges) => (agg, def) => {
setFormat(agg, def.format);
const [minimum, maximum] = ranges[def.format];
narrowMin(agg, "minimum", minimum);
narrowMax(agg, "maximum", maximum);
};
const contributors = {
greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value),
less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value),
multiple_of: (agg, def) => addDivisor(agg, def.value),
number_format: formatContributor(NUMBER_FORMAT_RANGES),
bigint_format: formatContributor(BIGINT_FORMAT_RANGES),
min_length: minContributor,
max_length: maxContributor,
length_equals: (agg, def) => narrowBoth(agg, def.length),
min_size: minContributor,
max_size: maxContributor,
size_equals: (agg, def) => narrowBoth(agg, def.size),
string_format: (agg, def) => {
setFormat(agg, def.format);
if (def.pattern)
addPattern(agg, def.pattern);
if (def.format === "base64" || def.format === "base64url")
agg.contentEncoding = def.format;
if (def.local || def.precision === -1)
agg.laxFormat = true;
},
mime_type: (agg, def) => intersectMime(agg, def.mime),
};
export function aggregateChecks(schema) {
const agg = {};
const def = schema._zod.def;
// a format schema is its own first check, same rule as $ZodType init
const list = schema._zod.traits.has("$ZodCheck")
? [schema, ...(def.checks ?? [])]
: (def.checks ?? []);
for (const ch of list)
contributors[ch._zod.def.check]?.(agg, ch._zod.def);
// reconcile with the bag so third-party onattach contributions still land; first-party residue is never tighter than the fold, so merging it back is idempotent for one and additive for the other
const bag = schema._zod.bag;
if (bag.minimum !== undefined)
narrowMin(agg, "minimum", bag.minimum);
if (bag.exclusiveMinimum !== undefined)
narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum);
if (bag.maximum !== undefined)
narrowMax(agg, "maximum", bag.maximum);
if (bag.exclusiveMaximum !== undefined)
narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum);
if (bag.multipleOf !== undefined)
addDivisor(agg, bag.multipleOf);
if (bag.format !== undefined) {
agg.format ?? (agg.format = bag.format);
if (bag.format.includes("int"))
agg.isInt = true;
}
if (bag.mime)
intersectMime(agg, bag.mime);
for (const pattern of bag.patterns ?? [])
addPattern(agg, pattern);
return agg;
}
const formatMap = {
guid: "uuid",
url: "uri",
datetime: "date-time",
json_string: "json-string",
regex: "", // do not set
};
// ==================== SIMPLE TYPE PROCESSORS ====================
// the runtime patterns are lax so parse paths never overflow the regex stack; the emitted schema swaps in the exact block forms, which zod itself never executes
const exactPatterns = new Map([
[base64Charset, regexes.base64],
[base64urlCharset, regexes.base64url],
]);
const exactPattern = (p) => exactPatterns.get(p) ?? p;
export const stringProcessor = (schema, ctx, _json, _params) => {
const json = _json;
json.type = "string";
const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);
if (typeof minimum === "number")
json.minLength = minimum;
if (typeof maximum === "number")
json.maxLength = maximum;
// custom pattern overrides format
if (format) {
json.format = formatMap[format] ?? format;
if (json.format === "")
delete json.format; // empty format is not valid
// `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids
if (format === "time" || laxFormat) {
delete json.format;
}
}
if (contentEncoding)
json.contentEncoding = contentEncoding;
if (patterns && patterns.size > 0) {
const patternList = [...patterns].map(exactPattern);
if (patternList.length === 1)
json.pattern = patternList[0].source;
else if (patternList.length > 1) {
json.allOf = [
...patternList.map((regex) => ({
...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0"
? { type: "string" }
: {}),
pattern: regex.source,
})),
];
}
}
};
export const numberProcessor = (schema, ctx, _json, params) => {
const json = _json;
const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);
json.type = isInt ? "integer" : "number";
// when both minimum and exclusiveMinimum exist, pick the more restrictive one
const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
if (exMin) {
if (legacy) {
json.minimum = exclusiveMinimum;
json.exclusiveMinimum = true;
}
else {
json.exclusiveMinimum = exclusiveMinimum;
}
}
else if (typeof minimum === "number") {
json.minimum = minimum;
}
if (exMax) {
if (legacy) {
json.maximum = exclusiveMaximum;
json.exclusiveMaximum = true;
}
else {
json.exclusiveMaximum = exclusiveMaximum;
}
}
else if (typeof maximum === "number") {
json.maximum = maximum;
}
if (multipleOf) {
// JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form.
const divisors = new Set();
for (const divisor of multipleOf) {
if (Number.isFinite(divisor) && divisor !== 0)
divisors.add(Math.abs(divisor));
else
handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);
}
// chained divisors are a conjunction the keyword cannot carry alone, so extras ride an allOf, same as stacked patterns
const [first, ...rest] = divisors;
if (first !== undefined)
json.multipleOf = first;
if (rest.length)
json.allOf = [...(json.allOf ?? []), ...rest.map((m) => ({ multipleOf: m }))];
}
};
export const booleanProcessor = (_schema, _ctx, json, _params) => {
json.type = "boolean";
};
export const bigintProcessor = (schema, ctx, json, params) => {
handleUnrepresentable(schema, ctx, json, params, "BigInt cannot be represented in JSON Schema");
};
export const symbolProcessor = (schema, ctx, json, params) => {
handleUnrepresentable(schema, ctx, json, params, "Symbols cannot be represented in JSON Schema");
};
export const nullProcessor = (_schema, ctx, json, _params) => {
if (ctx.target === "openapi-3.0") {
json.type = "string";
json.nullable = true;
json.enum = [null];
}
else {
json.type = "null";
}
};
export const undefinedProcessor = (schema, ctx, json, params) => {
handleUnrepresentable(schema, ctx, json, params, "Undefined cannot be represented in JSON Schema");
};
export const voidProcessor = (schema, ctx, json, params) => {
handleUnrepresentable(schema, ctx, json, params, "Void cannot be represented in JSON Schema");
};
export const neverProcessor = (_schema, _ctx, json, _params) => {
json.not = {};
};
export const anyProcessor = (_schema, _ctx, _json, _params) => {
// empty schema accepts anything
};
export const unknownProcessor = (_schema, _ctx, _json, _params) => {
// empty schema accepts anything
};
export const dateProcessor = (schema, ctx, json, params) => {
handleUnrepresentable(schema, ctx, json, params, "Date cannot be represented in JSON Schema");
};
export const enumProcessor = (schema, _ctx, json, _params) => {
const def = schema._zod.def;
const values = getEnumValues(def.entries);
// an empty enum accepts nothing, same as z.never()
if (values.length === 0) {
json.not = {};
return;
}
// Number enums can have both string and number values
if (values.every((v) => typeof v === "number"))
json.type = "number";
if (values.every((v) => typeof v === "string"))
json.type = "string";
json.enum = values;
};
export const literalProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
// a literal with no values accepts nothing, same as z.never()
if (def.values.length === 0) {
json.not = {};
return;
}
const vals = [];
for (const val of def.values) {
if (val === undefined) {
// a custom schema replaces the whole literal, so there is nothing left to accumulate
if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema"))
return;
// otherwise do not add to vals
}
else if (typeof val === "bigint") {
if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema"))
return;
vals.push(Number(val));
}
else {
vals.push(val);
}
}
if (vals.length === 0) {
// do nothing (an undefined literal was stripped)
}
else if (vals.length === 1) {
const val = vals[0];
json.type = val === null ? "null" : typeof val;
if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
json.enum = [val];
}
else {
json.const = val;
}
}
else {
if (vals.every((v) => typeof v === "number"))
json.type = "number";
if (vals.every((v) => typeof v === "string"))
json.type = "string";
if (vals.every((v) => typeof v === "boolean"))
json.type = "boolean";
if (vals.every((v) => v === null))
json.type = "null";
json.enum = vals;
}
};
export const nanProcessor = (schema, ctx, json, params) => {
handleUnrepresentable(schema, ctx, json, params, "NaN cannot be represented in JSON Schema");
};
export const templateLiteralProcessor = (schema, _ctx, json, _params) => {
const _json = json;
const pattern = schema._zod.pattern;
if (!pattern)
throw new Error("Pattern not found in template literal");
_json.type = "string";
_json.pattern = pattern.source;
};
export const fileProcessor = (schema, _ctx, json, _params) => {
const _json = json;
_json.type = "string";
_json.format = "binary";
_json.contentEncoding = "binary";
const { minimum, maximum, mime } = aggregateChecks(schema);
if (minimum !== undefined)
_json.minLength = minimum;
if (maximum !== undefined)
_json.maxLength = maximum;
if (!mime)
return;
// an empty intersection means the mime checks share no value, so nothing passes at runtime; `anyOf` must be non-empty, so the false schema is `not: {}`
if (mime.length === 0)
_json.not = {};
else if (mime.length === 1)
_json.contentMediaType = mime[0];
// only contentMediaType differs, so the shared props stay at the root
else
_json.anyOf = mime.map((m) => ({ contentMediaType: m }));
};
export const successProcessor = (_schema, _ctx, json, _params) => {
json.type = "boolean";
};
export const customProcessor = (schema, ctx, json, params) => {
handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema");
};
export const functionProcessor = (schema, ctx, json, params) => {
handleUnrepresentable(schema, ctx, json, params, "Function types cannot be represented in JSON Schema");
};
export const transformProcessor = (schema, ctx, json, params) => {
handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema");
};
export const mapProcessor = (schema, ctx, json, params) => {
handleUnrepresentable(schema, ctx, json, params, "Map cannot be represented in JSON Schema");
};
export const setProcessor = (schema, ctx, json, params) => {
handleUnrepresentable(schema, ctx, json, params, "Set cannot be represented in JSON Schema");
};
// ==================== COMPOSITE TYPE PROCESSORS ====================
export const arrayProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
const { minimum, maximum } = aggregateChecks(schema);
if (typeof minimum === "number")
json.minItems = minimum;
if (typeof maximum === "number")
json.maxItems = maximum;
json.type = "array";
json.items = processSchema(def.element, ctx, {
...params,
path: [...params.path, "items"],
});
};
// Transform and catch set `optin = "optional"` at runtime so the parser lets them observe an
// absent key, but their declared input type stays required. An input JSON Schema describes the
// declared type, so resolve past them to the schema that actually carries the optionality.
// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see
// wiki/optionality.md, "The JSON Schema emitter reads the *static* value".
function inputOptin(schema) {
const def = schema._zod.def;
if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) {
return inputOptin(def.out);
}
if (def.type === "catch") {
return inputOptin(def.innerType);
}
return schema._zod.optin;
}
export const objectProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
const shape = def.shape;
// dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires
const symbolKeys = Object.getOwnPropertySymbols(shape);
if (symbolKeys.length &&
handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) {
return;
}
json.type = "object";
json.properties = {};
for (const key in shape) {
// assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into
assignProp(json.properties, key, processSchema(shape[key], ctx, {
...params,
path: [...params.path, "properties", key],
}));
}
// required keys
const requiredKeys = [];
for (const key of Object.keys(shape)) {
const field = def.shape[key];
if (ctx.io === "input" ? inputOptin(field) === undefined : field._zod.optout === undefined) {
requiredKeys.push(key);
}
}
if (requiredKeys.length > 0) {
json.required = requiredKeys;
}
// catchall
if (def.catchall?._zod.def.type === "never") {
// strict
json.additionalProperties = false;
}
else if (!def.catchall) {
// regular
if (ctx.io === "output")
json.additionalProperties = false;
}
else if (def.catchall) {
json.additionalProperties = processSchema(def.catchall, ctx, {
...params,
path: [...params.path, "additionalProperties"],
});
}
};
export const unionProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
// Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions
const isExclusive = def.inclusive === false;
const options = def.options.map((x, i) => processSchema(x, ctx, {
...params,
path: [...params.path, isExclusive ? "oneOf" : "anyOf", i],
}));
if (isExclusive) {
json.oneOf = options;
}
else {
json.anyOf = options;
}
};
export const intersectionProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
const a = processSchema(def.left, ctx, {
...params,
path: [...params.path, "allOf", 0],
});
const b = processSchema(def.right, ctx, {
...params,
path: [...params.path, "allOf", 1],
});
const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
const allOf = [
...(isSimpleIntersection(a) ? a.allOf : [a]),
...(isSimpleIntersection(b) ? b.allOf : [b]),
];
json.allOf = allOf;
// Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`.
ctx.intersections.push(allOf);
};
export const tupleProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
json.type = "array";
const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items";
const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems";
const prefixItems = def.items.map((x, i) => processSchema(x, ctx, {
...params,
path: [...params.path, prefixPath, i],
}));
const rest = def.rest
? processSchema(def.rest, ctx, {
...params,
path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])],
})
: null;
let minItems = def.items.length;
while (minItems > 0) {
const item = def.items[minItems - 1];
const optional = ctx.io === "input" ? inputOptin(item) !== undefined : item._zod.optout === "optional";
if (!optional)
break;
minItems--;
}
const maxItems = def.items.length;
const isClosed = !def.rest;
if (ctx.target === "draft-2020-12") {
json.prefixItems = prefixItems;
if (isClosed) {
json.items = false;
}
else if (rest) {
json.items = rest;
}
if (minItems > 0)
json.minItems = minItems;
if (isClosed)
json.maxItems = maxItems;
}
else if (ctx.target === "openapi-3.0") {
json.items = {
anyOf: prefixItems,
};
if (rest) {
json.items.anyOf.push(rest);
}
if (minItems > 0)
json.minItems = minItems;
if (isClosed)
json.maxItems = maxItems;
}
else {
json.items = prefixItems;
if (isClosed) {
json.additionalItems = false;
}
else if (rest) {
json.additionalItems = rest;
}
if (minItems > 0)
json.minItems = minItems;
if (isClosed)
json.maxItems = maxItems;
}
// explicit user-defined length checks take precedence
const { minimum, maximum } = aggregateChecks(schema);
if (typeof minimum === "number")
json.minItems = minimum;
if (typeof maximum === "number")
json.maxItems = maximum;
};
/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the
* numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key
* behind a wrapper only carries its own `type` before then, and a union key only has its branches.
*
* A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather
* than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this
* exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)`
* accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema
* outright. */
function stringifyKeyNames(bySchema, json, visited) {
// an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`.
if (json.$ref) {
// a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again
if (visited.has(json))
return json;
visited.add(json);
const def = bySchema.get(json)?.def;
if (!def)
return json;
const inlined = stringifyKeyNames(bySchema, def, visited);
return inlined === def ? json : inlined;
}
for (const keyword of ["anyOf", "oneOf"]) {
const branches = json[keyword];
if (!Array.isArray(branches))
continue;
const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));
// rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id`
if (mapped.some((branch, i) => branch !== branches[i]))
json = { ...json, [keyword]: mapped };
}
// a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric
const types = Array.isArray(json.type) ? json.type : [json.type];
const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer");
// a heterogeneous key carries no type at all, so its numeric members are caught here instead
const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined);
if (!numericType && !values?.some((v) => typeof v === "number"))
return json;
const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;
if (rest.enum)
rest.enum = rest.enum.map((v) => (typeof v === "number" ? String(v) : v));
else if (typeof rest.const === "number")
rest.const = String(rest.const);
// a heterogeneous key keeps its absent type: the stringified members already say what a key may be
if (!numericType)
return rest;
rest.type = "string";
if (!values)
rest.pattern = (types.includes("number") ? regexes.number : regexes.integer).source;
return rest;
}
/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */
const pendingRecords = new WeakMap();
function rewriteKeyNames(ctx) {
// an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it.
const bySchema = new Map();
for (const entry of ctx.seen.values()) {
if (entry.def && !bySchema.has(entry.schema))
bySchema.set(entry.schema, entry);
}
const rewrites = new Map();
for (const record of pendingRecords.get(ctx) ?? []) {
const seen = ctx.seen.get(record);
const names = (seen?.def ?? seen?.schema)?.propertyNames;
if (!names || names === true || rewrites.has(names))
continue;
const rewritten = stringifyKeyNames(bySchema, names, new Set());
if (rewritten !== names)
rewrites.set(names, rewritten);
}
if (!rewrites.size)
return;
// the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together
for (const entry of ctx.seen.values()) {
for (const carrier of [entry.schema, entry.def]) {
const rewritten = carrier && rewrites.get(carrier.propertyNames);
if (rewritten)
carrier.propertyNames = rewritten;
}
}
}
export const recordProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
json.type = "object";
// For looseRecord with regex patterns, use patternProperties. This correctly represents "only validate keys matching the pattern" semantics and composes well with allOf (intersections)
const keyType = def.keyType;
const patterns = aggregateChecks(keyType).patterns;
if (def.mode === "loose" && patterns && patterns.size > 0) {
// Use patternProperties for looseRecord with regex patterns
const valueSchema = processSchema(def.valueType, ctx, {
...params,
path: [...params.path, "patternProperties", "*"],
});
json.patternProperties = {};
for (const pattern of patterns) {
assignProp(json.patternProperties, exactPattern(pattern).source, valueSchema);
}
}
else {
// Default behavior: use propertyNames + additionalProperties
if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
json.propertyNames = processSchema(def.keyType, ctx, {
...params,
path: [...params.path, "propertyNames"],
});
let pending = pendingRecords.get(ctx);
if (!pending) {
pending = [];
pendingRecords.set(ctx, pending);
ctx.deferred.push(() => rewriteKeyNames(ctx));
}
pending.push(schema);
}
json.additionalProperties = processSchema(def.valueType, ctx, {
...params,
path: [...params.path, "additionalProperties"],
});
}
// Add required for keys with discrete values (enum, literal, etc.)
const keyValues = keyType._zod.values;
// Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined.
const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined;
if (keyValues && !def.partial && !omittableOnInput) {
const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
if (validKeyValues.length > 0) {
json.required = validKeyValues.map(String);
}
}
};
export const nullableProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
const inner = processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
if (ctx.target === "openapi-3.0") {
seen.ref = def.innerType;
json.nullable = true;
}
else {
json.anyOf = [inner, { type: "null" }];
}
};
export const nonoptionalProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
};
/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON.
* A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other
* unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */
const UNREPRESENTABLE_DEFAULT = Symbol();
function serializeDefaultValue(value, schema, ctx, json, params) {
let unrepresentable = false;
const serialized = JSON.stringify(value, (_, val) => {
if (typeof val !== "bigint")
return val;
unrepresentable = true;
return null;
});
if (!unrepresentable)
return JSON.parse(serialized);
handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema");
return UNREPRESENTABLE_DEFAULT;
}
export const defaultProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);
if (value !== UNREPRESENTABLE_DEFAULT)
json.default = value;
};
export const prefaultProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
if (ctx.io !== "input")
return;
const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);
if (value !== UNREPRESENTABLE_DEFAULT)
json._prefault = value;
};
export const catchProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
let catchValue;
try {
catchValue = def.catchValue(undefined);
}
catch {
handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema");
return;
}
json.default = catchValue;
};
export const pipeProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
const inIsTransform = def.in._zod.traits.has("$ZodTransform");
const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out;
processSchema(innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = innerType;
};
export const readonlyProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
json.readOnly = true;
};
export const promiseProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
};
export const optionalProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
};
export const lazyProcessor = (schema, ctx, _json, params) => {
const innerType = schema._zod.innerType;
processSchema(innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = innerType;
};
// ==================== ALL PROCESSORS ====================
export const allProcessors = {
string: stringProcessor,
number: numberProcessor,
boolean: booleanProcessor,
bigint: bigintProcessor,
symbol: symbolProcessor,
null: nullProcessor,
undefined: undefinedProcessor,
void: voidProcessor,
never: neverProcessor,
any: anyProcessor,
unknown: unknownProcessor,
date: dateProcessor,
enum: enumProcessor,
literal: literalProcessor,
nan: nanProcessor,
template_literal: templateLiteralProcessor,
file: fileProcessor,
success: successProcessor,
custom: customProcessor,
function: functionProcessor,
transform: transformProcessor,
map: mapProcessor,
set: setProcessor,
array: arrayProcessor,
object: objectProcessor,
union: unionProcessor,
intersection: intersectionProcessor,
tuple: tupleProcessor,
record: recordProcessor,
nullable: nullableProcessor,
nonoptional: nonoptionalProcessor,
default: defaultProcessor,
prefault: prefaultProcessor,
catch: catchProcessor,
pipe: pipeProcessor,
readonly: readonlyProcessor,
promise: promiseProcessor,
optional: optionalProcessor,
lazy: lazyProcessor,
};
export function toJSONSchema(input, params) {
if ("_idmap" in input) {
// Registry case
const registry = input;
const ctx = initializeContext({ ...params, processors: allProcessors });
const defs = {};
// First pass: process all schemas to build the seen map
for (const entry of registry._idmap.entries()) {
const [_, schema] = entry;
processSchema(schema, ctx);
}
const schemas = {};
const external = {
registry,
uri: params?.uri,
defs,
};
// Update the context with external configuration
ctx.external = external;
// Second pass: emit each schema
for (const entry of registry._idmap.entries()) {
const [key, schema] = entry;
extractDefs(ctx, schema);
assignProp(schemas, key, finalize(ctx, schema));
}
if (Object.keys(defs).length > 0) {
const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
schemas.__shared = {
[defsSegment]: defs,
};
}
return { schemas };
}
// Single schema case
const ctx = initializeContext({ ...params, processors: allProcessors });
processSchema(input, ctx);
extractDefs(ctx, input);
return finalize(ctx, input);
}
+21
View File
@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+89
View File
@@ -0,0 +1,89 @@
export type Schema = ObjectSchema | ArraySchema | StringSchema | NumberSchema | IntegerSchema | BooleanSchema | NullSchema;
export type _JSONSchema = boolean | JSONSchema;
export type SchemaType = "object" | "array" | "string" | "number" | "boolean" | "null" | "integer";
export type JSONSchema = {
[k: string]: unknown;
$schema?: "https://json-schema.org/draft/2020-12/schema" | "http://json-schema.org/draft-07/schema#" | "http://json-schema.org/draft-04/schema#";
$id?: string;
$anchor?: string;
$ref?: string;
$dynamicRef?: string;
$dynamicAnchor?: string;
$vocabulary?: Record<string, boolean>;
$comment?: string;
$defs?: Record<string, JSONSchema>;
type?: SchemaType | SchemaType[];
additionalItems?: _JSONSchema;
unevaluatedItems?: _JSONSchema;
prefixItems?: _JSONSchema[];
items?: _JSONSchema | _JSONSchema[];
contains?: _JSONSchema;
additionalProperties?: _JSONSchema;
unevaluatedProperties?: _JSONSchema;
properties?: Record<string, _JSONSchema>;
patternProperties?: Record<string, _JSONSchema>;
dependentSchemas?: Record<string, _JSONSchema>;
propertyNames?: _JSONSchema;
if?: _JSONSchema;
then?: _JSONSchema;
else?: _JSONSchema;
allOf?: JSONSchema[];
anyOf?: JSONSchema[];
oneOf?: JSONSchema[];
not?: _JSONSchema;
multipleOf?: number;
maximum?: number;
exclusiveMaximum?: number | boolean;
minimum?: number;
exclusiveMinimum?: number | boolean;
maxLength?: number;
minLength?: number;
pattern?: string;
maxItems?: number;
minItems?: number;
uniqueItems?: boolean;
maxContains?: number;
minContains?: number;
maxProperties?: number;
minProperties?: number;
required?: string[];
dependentRequired?: Record<string, string[]>;
enum?: Array<string | number | boolean | null>;
const?: string | number | boolean | null;
id?: string;
title?: string;
description?: string;
default?: unknown;
deprecated?: boolean;
readOnly?: boolean;
writeOnly?: boolean;
nullable?: boolean;
examples?: unknown[];
format?: string;
contentMediaType?: string;
contentEncoding?: string;
contentSchema?: JSONSchema;
_prefault?: unknown;
};
export type BaseSchema = JSONSchema;
export interface ObjectSchema extends JSONSchema {
type: "object";
}
export interface ArraySchema extends JSONSchema {
type: "array";
}
export interface StringSchema extends JSONSchema {
type: "string";
}
export interface NumberSchema extends JSONSchema {
type: "number";
}
export interface IntegerSchema extends JSONSchema {
type: "integer";
}
export interface BooleanSchema extends JSONSchema {
type: "boolean";
}
export interface NullSchema extends JSONSchema {
type: "null";
}
+89
View File
@@ -0,0 +1,89 @@
export type Schema = ObjectSchema | ArraySchema | StringSchema | NumberSchema | IntegerSchema | BooleanSchema | NullSchema;
export type _JSONSchema = boolean | JSONSchema;
export type SchemaType = "object" | "array" | "string" | "number" | "boolean" | "null" | "integer";
export type JSONSchema = {
[k: string]: unknown;
$schema?: "https://json-schema.org/draft/2020-12/schema" | "http://json-schema.org/draft-07/schema#" | "http://json-schema.org/draft-04/schema#";
$id?: string;
$anchor?: string;
$ref?: string;
$dynamicRef?: string;
$dynamicAnchor?: string;
$vocabulary?: Record<string, boolean>;
$comment?: string;
$defs?: Record<string, JSONSchema>;
type?: SchemaType | SchemaType[];
additionalItems?: _JSONSchema;
unevaluatedItems?: _JSONSchema;
prefixItems?: _JSONSchema[];
items?: _JSONSchema | _JSONSchema[];
contains?: _JSONSchema;
additionalProperties?: _JSONSchema;
unevaluatedProperties?: _JSONSchema;
properties?: Record<string, _JSONSchema>;
patternProperties?: Record<string, _JSONSchema>;
dependentSchemas?: Record<string, _JSONSchema>;
propertyNames?: _JSONSchema;
if?: _JSONSchema;
then?: _JSONSchema;
else?: _JSONSchema;
allOf?: JSONSchema[];
anyOf?: JSONSchema[];
oneOf?: JSONSchema[];
not?: _JSONSchema;
multipleOf?: number;
maximum?: number;
exclusiveMaximum?: number | boolean;
minimum?: number;
exclusiveMinimum?: number | boolean;
maxLength?: number;
minLength?: number;
pattern?: string;
maxItems?: number;
minItems?: number;
uniqueItems?: boolean;
maxContains?: number;
minContains?: number;
maxProperties?: number;
minProperties?: number;
required?: string[];
dependentRequired?: Record<string, string[]>;
enum?: Array<string | number | boolean | null>;
const?: string | number | boolean | null;
id?: string;
title?: string;
description?: string;
default?: unknown;
deprecated?: boolean;
readOnly?: boolean;
writeOnly?: boolean;
nullable?: boolean;
examples?: unknown[];
format?: string;
contentMediaType?: string;
contentEncoding?: string;
contentSchema?: JSONSchema;
_prefault?: unknown;
};
export type BaseSchema = JSONSchema;
export interface ObjectSchema extends JSONSchema {
type: "object";
}
export interface ArraySchema extends JSONSchema {
type: "array";
}
export interface StringSchema extends JSONSchema {
type: "string";
}
export interface NumberSchema extends JSONSchema {
type: "number";
}
export interface IntegerSchema extends JSONSchema {
type: "integer";
}
export interface BooleanSchema extends JSONSchema {
type: "boolean";
}
export interface NullSchema extends JSONSchema {
type: "null";
}
+1
View File
@@ -0,0 +1 @@
export {};
+360
View File
@@ -0,0 +1,360 @@
"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.$ZodCyclicError = void 0;
exports.isRecursiveSchema = isRecursiveSchema;
exports.memoizer = memoizer;
exports.isBackEdge = isBackEdge;
const util = __importStar(require("./util.cjs"));
class $ZodCyclicError extends Error {
constructor() {
super(`Cannot parse a reference cycle that closes through a transform`);
this.name = "ZodCyclicError";
}
}
exports.$ZodCyclicError = $ZodCyclicError;
/** Keyed off the context object every schema in one parse call already shares. */
const STATE = "~memo";
const NO_ISSUES = [];
// a value a cycle can close through
function isRef(value) {
return value !== null && typeof value === "object";
}
// Receivers prefix paths in place, so the cache and every hand-out need their own copies.
function cloneIssues(issues) {
return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }));
}
const recursive = /*@__PURE__*/ new WeakMap();
/** What the walk established, in order of certainty: ordered so the strongest answer among children wins. */
const NONE = 0;
const ASSUMED = 1;
const PROVEN = 2;
/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */
function isRecursive(inst, stack, resolve) {
const cached = recursive.get(inst);
if (cached !== undefined)
return cached ? PROVEN : NONE;
// Relative to the walk in progress, so not cached.
if (stack.has(inst))
return PROVEN;
stack.add(inst);
let result = NONE;
const check = (child) => {
if (result !== PROVEN && child?._zod) {
const answer = isRecursive(child, stack, resolve);
if (answer > result)
result = answer;
}
};
// `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen
const shape = (sh, spread) => {
let answer = NONE;
for (const key of Reflect.ownKeys(sh)) {
const desc = Object.getOwnPropertyDescriptor(sh, key);
// an object resolves its shape by spread, so a key it does not enumerate is never parsed; `z.properties` reads every own key and so keeps them all
if (spread && !desc.enumerable)
continue;
// resolving runs user code, and a factory mints a fresh subtree per read, so an edge the walk can't follow counts as a cycle
const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;
if (child > answer)
answer = child;
}
return answer;
};
const merge = (answer) => {
if (answer > result)
result = answer;
};
const def = inst._zod.def;
const kind = def.type;
switch (kind) {
case "object": {
const raw = util.rawShape(def);
// a def with no raw shape answers `shape` from an accessor of its own, and running that can mint a whole fresh subtree
merge(raw ? shape(raw, true) : ASSUMED);
check(def.catchall);
break;
}
case "array":
check(def.element);
break;
case "tuple":
for (const el of def.items)
check(el);
check(def.rest);
break;
case "record":
case "map":
check(def.keyType);
check(def.valueType);
break;
case "set":
check(def.valueType);
break;
case "union":
for (const el of def.options)
check(el);
break;
case "intersection":
check(def.left);
check(def.right);
break;
case "optional":
case "nullable":
case "default":
case "prefault":
case "catch":
case "readonly":
case "nonoptional":
case "promise":
case "success":
check(def.innerType);
break;
case "pipe":
check(def.in);
check(def.out);
break;
case "function":
check(def.input);
check(def.output);
break;
// `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
case "lazy": {
const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : undefined);
// walked with resolution off: one hop sees past the deferral, and a lazy that yields only another unresolved lazy is generative, so it stops there
merge(inner ? isRecursive(inner, stack, false) : ASSUMED);
break;
}
// a leaf by choice: `parts` are regex fragments, not data positions
case "template_literal":
// leaves
case "string":
case "number":
case "int":
case "boolean":
case "bigint":
case "symbol":
case "undefined":
case "null":
case "void":
case "never":
case "any":
case "unknown":
case "date":
case "nan":
case "enum":
case "literal":
case "file":
case "transform":
case "custom":
break;
default: {
// a new built-in kind becomes a compile error here
kind;
// a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code
for (const key in def) {
const desc = Object.getOwnPropertyDescriptor(def, key);
if (!desc || desc.get)
continue;
const value = desc.value;
if (!value || typeof value !== "object")
continue;
if (value._zod)
check(value);
else if (Array.isArray(value))
for (const el of value)
check(el);
}
}
}
stack.delete(inst);
return settle(inst, result);
}
/** An assumed answer must not outlive the resolution that settles it, so only a certain one is cached. */
function settle(inst, answer) {
if (answer !== ASSUMED)
recursive.set(inst, answer === PROVEN);
return answer;
}
/**
* Whether one parse can re-enter this schema, i.e. its subtree contains a cycle.
* Exported for `z.compile`, which refuses to compile such a schema: cycle
* breaking is driven from here off state keyed on the parse context, and a
* generated fast path has no context to key on.
*/
function isRecursiveSchema(inst) {
// z.compile never parses, so nothing would ever resolve a lazy for it; it runs once and already treats a throw here as recursive
return isRecursive(inst, new Set(), true) !== NONE;
}
function bucketFor(state, inst) {
let bucket = state.buckets.get(inst);
if (!bucket) {
bucket = new WeakMap();
state.buckets.set(inst, bucket);
}
return bucket;
}
// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving.
let handoff;
// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema.
const open = [];
const memo = {
alloc(_inst, payload, empty) {
const bucket = handoff;
if (!bucket)
return empty;
handoff = undefined;
const entry = { value: empty, issues: null };
bucket.set(payload.value, entry);
open.push(entry);
return empty;
},
guard(inst) {
var _a;
(_a = inst._zod).deferred ?? (_a.deferred = []);
inst._zod.deferred.push(() => {
const base = inst._zod.parse;
const wrapped = (payload, ctx) => {
// The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind.
if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value))
throw new $ZodCyclicError();
return base(payload, ctx);
};
inst._zod.parse = wrapped;
if (inst._zod.run === base)
inst._zod.run = wrapped;
});
},
attach(inst) {
var _a;
let isRecursiveInst;
let rechecked = false;
// a recursive schema is re-entered many times per parse and its bucket never changes
let lastCtx;
let lastBucket;
// Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically.
(_a = inst._zod).deferred ?? (_a.deferred = []);
inst._zod.deferred.push(() => {
const base = inst._zod.parse;
const wrapped = (payload, ctx) => {
if (isRecursiveInst === undefined) {
const walked = isRecursive(inst, new Set(), false);
if (walked === NONE) {
// Nothing here can ever fire, so take it back out.
inst._zod.parse = base;
if (inst._zod.run === wrapped)
inst._zod.run = base;
return base(payload, ctx);
}
// this parse resolves the deferred edges on its own path, so ask once more before latching
if (walked === PROVEN || rechecked)
isRecursiveInst = true;
else
rechecked = true;
}
const input = payload.value;
if (!isRef(input))
return base(payload, ctx);
let state = ctx[STATE];
if (!state) {
state = { buckets: new WeakMap(), backEdges: undefined };
ctx[STATE] = state;
}
let bucket;
if (lastCtx === ctx) {
bucket = lastBucket;
}
else {
bucket = bucketFor(state, inst);
lastCtx = ctx;
lastBucket = bucket;
}
const hit = bucket.get(input);
if (hit) {
payload.value = hit.value;
if (hit.issues) {
if (hit.issues.length)
payload.issues.push(...cloneIssues(hit.issues));
}
else {
// Still being parsed: its own checks cover it, so skip them here.
payload.memo = true;
state.backEdges ?? (state.backEdges = new WeakSet());
state.backEdges.add(hit.value);
}
return payload;
}
handoff = bucket;
const depth = open.length;
const result = base(payload, ctx);
handoff = undefined;
// A container that rejected its input outright allocated nothing.
const entry = open.length > depth ? open.pop() : undefined;
// Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined.
if (result instanceof Promise) {
return result.then((r) => {
if (entry)
entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;
return r;
});
}
if (entry)
entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;
return result;
};
inst._zod.parse = wrapped;
if (inst._zod.run === base)
inst._zod.run = wrapped;
});
},
};
/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */
function memoizer() {
return memo;
}
/** Whether this value is a node a back-edge resolved to before it finished. */
function isBackEdge(ctx, value) {
const backEdges = ctx[STATE]?.backEdges;
return backEdges !== undefined && isRef(value) && backEdges.has(value);
}
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+15
View File
@@ -0,0 +1,15 @@
import type { $ZodMemoizer, $ZodType } from "./schemas.cjs";
export declare class $ZodCyclicError extends Error {
constructor();
}
/**
* Whether one parse can re-enter this schema, i.e. its subtree contains a cycle.
* Exported for `z.compile`, which refuses to compile such a schema: cycle
* breaking is driven from here off state keyed on the parse context, and a
* generated fast path has no context to key on.
*/
export declare function isRecursiveSchema(inst: $ZodType): boolean;
/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */
export declare function memoizer(): $ZodMemoizer;
/** Whether this value is a node a back-edge resolved to before it finished. */
export declare function isBackEdge(ctx: object, value: unknown): boolean;
+15
View File
@@ -0,0 +1,15 @@
import type { $ZodMemoizer, $ZodType } from "./schemas.js";
export declare class $ZodCyclicError extends Error {
constructor();
}
/**
* Whether one parse can re-enter this schema, i.e. its subtree contains a cycle.
* Exported for `z.compile`, which refuses to compile such a schema: cycle
* breaking is driven from here off state keyed on the parse context, and a
* generated fast path has no context to key on.
*/
export declare function isRecursiveSchema(inst: $ZodType): boolean;
/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */
export declare function memoizer(): $ZodMemoizer;
/** Whether this value is a node a back-edge resolved to before it finished. */
export declare function isBackEdge(ctx: object, value: unknown): boolean;
+311
View File
@@ -0,0 +1,311 @@
import * as util from "./util.js";
export class $ZodCyclicError extends Error {
constructor() {
super(`Cannot parse a reference cycle that closes through a transform`);
this.name = "ZodCyclicError";
}
}
/** Keyed off the context object every schema in one parse call already shares. */
const STATE = "~memo";
const NO_ISSUES = [];
// a value a cycle can close through
function isRef(value) {
return value !== null && typeof value === "object";
}
// Receivers prefix paths in place, so the cache and every hand-out need their own copies.
function cloneIssues(issues) {
return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }));
}
const recursive = /*@__PURE__*/ new WeakMap();
/** What the walk established, in order of certainty: ordered so the strongest answer among children wins. */
const NONE = 0;
const ASSUMED = 1;
const PROVEN = 2;
/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */
function isRecursive(inst, stack, resolve) {
const cached = recursive.get(inst);
if (cached !== undefined)
return cached ? PROVEN : NONE;
// Relative to the walk in progress, so not cached.
if (stack.has(inst))
return PROVEN;
stack.add(inst);
let result = NONE;
const check = (child) => {
if (result !== PROVEN && child?._zod) {
const answer = isRecursive(child, stack, resolve);
if (answer > result)
result = answer;
}
};
// `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen
const shape = (sh, spread) => {
let answer = NONE;
for (const key of Reflect.ownKeys(sh)) {
const desc = Object.getOwnPropertyDescriptor(sh, key);
// an object resolves its shape by spread, so a key it does not enumerate is never parsed; `z.properties` reads every own key and so keeps them all
if (spread && !desc.enumerable)
continue;
// resolving runs user code, and a factory mints a fresh subtree per read, so an edge the walk can't follow counts as a cycle
const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;
if (child > answer)
answer = child;
}
return answer;
};
const merge = (answer) => {
if (answer > result)
result = answer;
};
const def = inst._zod.def;
const kind = def.type;
switch (kind) {
case "object": {
const raw = util.rawShape(def);
// a def with no raw shape answers `shape` from an accessor of its own, and running that can mint a whole fresh subtree
merge(raw ? shape(raw, true) : ASSUMED);
check(def.catchall);
break;
}
case "array":
check(def.element);
break;
case "tuple":
for (const el of def.items)
check(el);
check(def.rest);
break;
case "record":
case "map":
check(def.keyType);
check(def.valueType);
break;
case "set":
check(def.valueType);
break;
case "union":
for (const el of def.options)
check(el);
break;
case "intersection":
check(def.left);
check(def.right);
break;
case "optional":
case "nullable":
case "default":
case "prefault":
case "catch":
case "readonly":
case "nonoptional":
case "promise":
case "success":
check(def.innerType);
break;
case "pipe":
check(def.in);
check(def.out);
break;
case "function":
check(def.input);
check(def.output);
break;
// `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
case "lazy": {
const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : undefined);
// walked with resolution off: one hop sees past the deferral, and a lazy that yields only another unresolved lazy is generative, so it stops there
merge(inner ? isRecursive(inner, stack, false) : ASSUMED);
break;
}
// a leaf by choice: `parts` are regex fragments, not data positions
case "template_literal":
// leaves
case "string":
case "number":
case "int":
case "boolean":
case "bigint":
case "symbol":
case "undefined":
case "null":
case "void":
case "never":
case "any":
case "unknown":
case "date":
case "nan":
case "enum":
case "literal":
case "file":
case "transform":
case "custom":
break;
default: {
// a new built-in kind becomes a compile error here
kind;
// a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code
for (const key in def) {
const desc = Object.getOwnPropertyDescriptor(def, key);
if (!desc || desc.get)
continue;
const value = desc.value;
if (!value || typeof value !== "object")
continue;
if (value._zod)
check(value);
else if (Array.isArray(value))
for (const el of value)
check(el);
}
}
}
stack.delete(inst);
return settle(inst, result);
}
/** An assumed answer must not outlive the resolution that settles it, so only a certain one is cached. */
function settle(inst, answer) {
if (answer !== ASSUMED)
recursive.set(inst, answer === PROVEN);
return answer;
}
/**
* Whether one parse can re-enter this schema, i.e. its subtree contains a cycle.
* Exported for `z.compile`, which refuses to compile such a schema: cycle
* breaking is driven from here off state keyed on the parse context, and a
* generated fast path has no context to key on.
*/
export function isRecursiveSchema(inst) {
// z.compile never parses, so nothing would ever resolve a lazy for it; it runs once and already treats a throw here as recursive
return isRecursive(inst, new Set(), true) !== NONE;
}
function bucketFor(state, inst) {
let bucket = state.buckets.get(inst);
if (!bucket) {
bucket = new WeakMap();
state.buckets.set(inst, bucket);
}
return bucket;
}
// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving.
let handoff;
// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema.
const open = [];
const memo = {
alloc(_inst, payload, empty) {
const bucket = handoff;
if (!bucket)
return empty;
handoff = undefined;
const entry = { value: empty, issues: null };
bucket.set(payload.value, entry);
open.push(entry);
return empty;
},
guard(inst) {
var _a;
(_a = inst._zod).deferred ?? (_a.deferred = []);
inst._zod.deferred.push(() => {
const base = inst._zod.parse;
const wrapped = (payload, ctx) => {
// The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind.
if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value))
throw new $ZodCyclicError();
return base(payload, ctx);
};
inst._zod.parse = wrapped;
if (inst._zod.run === base)
inst._zod.run = wrapped;
});
},
attach(inst) {
var _a;
let isRecursiveInst;
let rechecked = false;
// a recursive schema is re-entered many times per parse and its bucket never changes
let lastCtx;
let lastBucket;
// Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically.
(_a = inst._zod).deferred ?? (_a.deferred = []);
inst._zod.deferred.push(() => {
const base = inst._zod.parse;
const wrapped = (payload, ctx) => {
if (isRecursiveInst === undefined) {
const walked = isRecursive(inst, new Set(), false);
if (walked === NONE) {
// Nothing here can ever fire, so take it back out.
inst._zod.parse = base;
if (inst._zod.run === wrapped)
inst._zod.run = base;
return base(payload, ctx);
}
// this parse resolves the deferred edges on its own path, so ask once more before latching
if (walked === PROVEN || rechecked)
isRecursiveInst = true;
else
rechecked = true;
}
const input = payload.value;
if (!isRef(input))
return base(payload, ctx);
let state = ctx[STATE];
if (!state) {
state = { buckets: new WeakMap(), backEdges: undefined };
ctx[STATE] = state;
}
let bucket;
if (lastCtx === ctx) {
bucket = lastBucket;
}
else {
bucket = bucketFor(state, inst);
lastCtx = ctx;
lastBucket = bucket;
}
const hit = bucket.get(input);
if (hit) {
payload.value = hit.value;
if (hit.issues) {
if (hit.issues.length)
payload.issues.push(...cloneIssues(hit.issues));
}
else {
// Still being parsed: its own checks cover it, so skip them here.
payload.memo = true;
state.backEdges ?? (state.backEdges = new WeakSet());
state.backEdges.add(hit.value);
}
return payload;
}
handoff = bucket;
const depth = open.length;
const result = base(payload, ctx);
handoff = undefined;
// A container that rejected its input outright allocated nothing.
const entry = open.length > depth ? open.pop() : undefined;
// Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined.
if (result instanceof Promise) {
return result.then((r) => {
if (entry)
entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;
return r;
});
}
if (entry)
entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;
return result;
};
inst._zod.parse = wrapped;
if (inst._zod.run === base)
inst._zod.run = wrapped;
});
},
};
/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */
export function memoizer() {
return memo;
}
/** Whether this value is a node a back-edge resolved to before it finished. */
export function isBackEdge(ctx, value) {
const backEdges = ctx[STATE]?.backEdges;
return backEdges !== undefined && isRef(value) && backEdges.has(value);
}
+7
View File
@@ -0,0 +1,7 @@
{
"type": "module",
"main": "./index.cjs",
"module": "./index.js",
"types": "./index.d.cts",
"sideEffects": false
}
+233
View File
@@ -0,0 +1,233 @@
"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.safeDecodeAsync = exports._safeDecodeAsync = exports.safeEncodeAsync = exports._safeEncodeAsync = exports.safeDecode = exports._safeDecode = exports.safeEncode = exports._safeEncode = exports.decodeAsync = exports._decodeAsync = exports.encodeAsync = exports._encodeAsync = exports.decode = exports._decode = exports.encode = exports._encode = exports.validateAsync = exports.validate = exports.safeParseAsync = exports._safeParseAsync = exports.safeParse = exports._safeParse = exports.parseAsync = exports._parseAsync = exports.parse = exports._parse = void 0;
const core = __importStar(require("./core.cjs"));
const errors = __importStar(require("./errors.cjs"));
const util = __importStar(require("./util.cjs"));
// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two.
function finalizeParams(callee, params) {
return { callee: params?.callee ?? callee, Err: params?.Err };
}
const _parse = (_Err) => {
const fn = (schema, value, _ctx, _params) => {
const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
const result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise) {
throw new core.$ZodAsyncError();
}
if (result.issues.length) {
const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));
util.captureStackTrace(e, _params?.callee ?? fn);
throw e;
}
return result.value;
};
return fn;
};
exports._parse = _parse;
exports.parse = (0, exports._parse)(errors.$ZodRealError);
const _parseAsync = (_Err) => {
const fn = async (schema, value, _ctx, params) => {
const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise)
result = await result;
if (result.issues.length) {
const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));
util.captureStackTrace(e, params?.callee ?? fn);
throw e;
}
return result.value;
};
return fn;
};
exports._parseAsync = _parseAsync;
exports.parseAsync = (0, exports._parseAsync)(errors.$ZodRealError);
const _safeParse = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
const result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise) {
throw new core.$ZodAsyncError();
}
return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };
};
exports._safeParse = _safeParse;
exports.safeParse = (0, exports._safeParse)(errors.$ZodRealError);
// the error is built on the first read of `error`: finalizing the issues and constructing the instance is most of a failing parse, and a caller that only branches on `success` never pays it. a getter in the literal keeps this small; the alternative, one shared accessor descriptor plus a hidden state slot, reads ~15% faster but costs ~75 B gzipped in every bundle
function failure(Err, issues, ctx) {
let error;
return {
success: false,
get error() {
if (!error) {
error = new Err(issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));
// finalizeIssue drops `input`, so the built error holds nothing; keeping the raw issues past this point pins the parsed value for the life of the result
issues = undefined;
ctx = undefined;
}
return error;
},
set error(e) {
error = e;
// a replacement makes the getter's branch unreachable, so the captures have to go here too
issues = undefined;
ctx = undefined;
},
};
}
const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise)
result = await result;
return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };
};
exports._safeParseAsync = _safeParseAsync;
exports.safeParseAsync = (0, exports._safeParseAsync)(errors.$ZodRealError);
// registry mirrors of the compiler's sentinels, so this module never imports the compiler
const COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid");
const COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback");
// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema.
exports.validate = ((schema, value, _ctx) => {
const validator = schema._zod.bag.validator;
if (validator !== undefined) {
if (validator(value) !== COMPILE_INVALID)
return true;
// a definite sentinel means the runtime would reject, so skip the re-parse; a ctx can still change the answer
if (validator.definite === true && _ctx === undefined)
return false;
}
return validateFallback(schema, value, _ctx);
});
function validateFallback(schema, value, _ctx) {
const ctx = _ctx
? { ..._ctx, async: false, abortEarly: true }
: { async: false, abortEarly: true };
const fallbackRun = schema._zod.bag.fallbackRun;
let result;
if (fallbackRun) {
// skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound
ctx[COMPILE_FALLBACK] = true;
result = fallbackRun({ value, issues: [] }, ctx);
}
else {
result = schema._zod.run({ value, issues: [] }, ctx);
}
if (result instanceof Promise) {
throw new core.$ZodAsyncError();
}
return result.issues.length === 0;
}
// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw
const validateAsync = async (schema, value, _ctx) => {
const ctx = _ctx
? { ..._ctx, async: true, abortEarly: true }
: { async: true, abortEarly: true };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise)
result = await result;
return result.issues.length === 0;
};
exports.validateAsync = validateAsync;
const _encode = (_Err) => {
const parse = (0, exports._parse)(_Err);
const fn = (schema, value, _ctx, _params) => {
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return parse(schema, value, ctx, finalizeParams(fn, _params));
};
return fn;
};
exports._encode = _encode;
exports.encode = (0, exports._encode)(errors.$ZodRealError);
const _decode = (_Err) => {
const parse = (0, exports._parse)(_Err);
const fn = (schema, value, _ctx, _params) => {
return parse(schema, value, _ctx, finalizeParams(fn, _params));
};
return fn;
};
exports._decode = _decode;
exports.decode = (0, exports._decode)(errors.$ZodRealError);
const _encodeAsync = (_Err) => {
const parseAsync = (0, exports._parseAsync)(_Err);
const fn = async (schema, value, _ctx, _params) => {
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params)));
};
return fn;
};
exports._encodeAsync = _encodeAsync;
exports.encodeAsync = (0, exports._encodeAsync)(errors.$ZodRealError);
const _decodeAsync = (_Err) => {
const parseAsync = (0, exports._parseAsync)(_Err);
const fn = async (schema, value, _ctx, _params) => {
return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));
};
return fn;
};
exports._decodeAsync = _decodeAsync;
exports.decodeAsync = (0, exports._decodeAsync)(errors.$ZodRealError);
const _safeEncode = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return (0, exports._safeParse)(_Err)(schema, value, ctx);
};
exports._safeEncode = _safeEncode;
exports.safeEncode = (0, exports._safeEncode)(errors.$ZodRealError);
const _safeDecode = (_Err) => (schema, value, _ctx) => {
return (0, exports._safeParse)(_Err)(schema, value, _ctx);
};
exports._safeDecode = _safeDecode;
exports.safeDecode = (0, exports._safeDecode)(errors.$ZodRealError);
const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return (0, exports._safeParseAsync)(_Err)(schema, value, ctx);
};
exports._safeEncodeAsync = _safeEncodeAsync;
exports.safeEncodeAsync = (0, exports._safeEncodeAsync)(errors.$ZodRealError);
const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
return (0, exports._safeParseAsync)(_Err)(schema, value, _ctx);
};
exports._safeDecodeAsync = _safeDecodeAsync;
exports.safeDecodeAsync = (0, exports._safeDecodeAsync)(errors.$ZodRealError);
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+52
View File
@@ -0,0 +1,52 @@
import * as core from "./core.cjs";
import * as errors from "./errors.cjs";
import type * as schemas from "./schemas.cjs";
import * as util from "./util.cjs";
export type $ZodErrorClass = {
new (issues: errors.$ZodIssue[]): errors.$ZodError;
};
type $ParseParams = {
callee?: util.AnyFunc;
Err?: $ZodErrorClass | undefined;
};
export type $Parse = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>, _params?: $ParseParams) => core.output<T>;
export declare const _parse: (_Err: $ZodErrorClass) => $Parse;
export declare const parse: $Parse;
export type $ParseAsync = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>, _params?: $ParseParams) => Promise<core.output<T>>;
export declare const _parseAsync: (_Err: $ZodErrorClass) => $ParseAsync;
export declare const parseAsync: $ParseAsync;
export type $SafeParse = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => util.SafeParseResult<core.output<T>>;
export declare const _safeParse: (_Err: $ZodErrorClass) => $SafeParse;
export declare const safeParse: $SafeParse;
export type $SafeParseAsync = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<util.SafeParseResult<core.output<T>>>;
export declare const _safeParseAsync: (_Err: $ZodErrorClass) => $SafeParseAsync;
export declare const safeParseAsync: $SafeParseAsync;
export type $Validate = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => value is core.input<T>;
export declare const validate: $Validate;
export type $ValidateAsync = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<boolean>;
export declare const validateAsync: $ValidateAsync;
export type $Encode = <T extends schemas.$ZodType>(schema: T, value: core.output<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>, _params?: $ParseParams) => core.input<T>;
export declare const _encode: (_Err: $ZodErrorClass) => $Encode;
export declare const encode: $Encode;
export type $Decode = <T extends schemas.$ZodType>(schema: T, value: core.input<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>, _params?: $ParseParams) => core.output<T>;
export declare const _decode: (_Err: $ZodErrorClass) => $Decode;
export declare const decode: $Decode;
export type $EncodeAsync = <T extends schemas.$ZodType>(schema: T, value: core.output<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>, _params?: $ParseParams) => Promise<core.input<T>>;
export declare const _encodeAsync: (_Err: $ZodErrorClass) => $EncodeAsync;
export declare const encodeAsync: $EncodeAsync;
export type $DecodeAsync = <T extends schemas.$ZodType>(schema: T, value: core.input<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>, _params?: $ParseParams) => Promise<core.output<T>>;
export declare const _decodeAsync: (_Err: $ZodErrorClass) => $DecodeAsync;
export declare const decodeAsync: $DecodeAsync;
export type $SafeEncode = <T extends schemas.$ZodType>(schema: T, value: core.output<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => util.SafeParseResult<core.input<T>>;
export declare const _safeEncode: (_Err: $ZodErrorClass) => $SafeEncode;
export declare const safeEncode: $SafeEncode;
export type $SafeDecode = <T extends schemas.$ZodType>(schema: T, value: core.input<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => util.SafeParseResult<core.output<T>>;
export declare const _safeDecode: (_Err: $ZodErrorClass) => $SafeDecode;
export declare const safeDecode: $SafeDecode;
export type $SafeEncodeAsync = <T extends schemas.$ZodType>(schema: T, value: core.output<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<util.SafeParseResult<core.input<T>>>;
export declare const _safeEncodeAsync: (_Err: $ZodErrorClass) => $SafeEncodeAsync;
export declare const safeEncodeAsync: $SafeEncodeAsync;
export type $SafeDecodeAsync = <T extends schemas.$ZodType>(schema: T, value: core.input<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<util.SafeParseResult<core.output<T>>>;
export declare const _safeDecodeAsync: (_Err: $ZodErrorClass) => $SafeDecodeAsync;
export declare const safeDecodeAsync: $SafeDecodeAsync;
export {};
+52
View File
@@ -0,0 +1,52 @@
import * as core from "./core.js";
import * as errors from "./errors.js";
import type * as schemas from "./schemas.js";
import * as util from "./util.js";
export type $ZodErrorClass = {
new (issues: errors.$ZodIssue[]): errors.$ZodError;
};
type $ParseParams = {
callee?: util.AnyFunc;
Err?: $ZodErrorClass | undefined;
};
export type $Parse = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>, _params?: $ParseParams) => core.output<T>;
export declare const _parse: (_Err: $ZodErrorClass) => $Parse;
export declare const parse: $Parse;
export type $ParseAsync = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>, _params?: $ParseParams) => Promise<core.output<T>>;
export declare const _parseAsync: (_Err: $ZodErrorClass) => $ParseAsync;
export declare const parseAsync: $ParseAsync;
export type $SafeParse = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => util.SafeParseResult<core.output<T>>;
export declare const _safeParse: (_Err: $ZodErrorClass) => $SafeParse;
export declare const safeParse: $SafeParse;
export type $SafeParseAsync = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<util.SafeParseResult<core.output<T>>>;
export declare const _safeParseAsync: (_Err: $ZodErrorClass) => $SafeParseAsync;
export declare const safeParseAsync: $SafeParseAsync;
export type $Validate = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => value is core.input<T>;
export declare const validate: $Validate;
export type $ValidateAsync = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<boolean>;
export declare const validateAsync: $ValidateAsync;
export type $Encode = <T extends schemas.$ZodType>(schema: T, value: core.output<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>, _params?: $ParseParams) => core.input<T>;
export declare const _encode: (_Err: $ZodErrorClass) => $Encode;
export declare const encode: $Encode;
export type $Decode = <T extends schemas.$ZodType>(schema: T, value: core.input<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>, _params?: $ParseParams) => core.output<T>;
export declare const _decode: (_Err: $ZodErrorClass) => $Decode;
export declare const decode: $Decode;
export type $EncodeAsync = <T extends schemas.$ZodType>(schema: T, value: core.output<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>, _params?: $ParseParams) => Promise<core.input<T>>;
export declare const _encodeAsync: (_Err: $ZodErrorClass) => $EncodeAsync;
export declare const encodeAsync: $EncodeAsync;
export type $DecodeAsync = <T extends schemas.$ZodType>(schema: T, value: core.input<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>, _params?: $ParseParams) => Promise<core.output<T>>;
export declare const _decodeAsync: (_Err: $ZodErrorClass) => $DecodeAsync;
export declare const decodeAsync: $DecodeAsync;
export type $SafeEncode = <T extends schemas.$ZodType>(schema: T, value: core.output<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => util.SafeParseResult<core.input<T>>;
export declare const _safeEncode: (_Err: $ZodErrorClass) => $SafeEncode;
export declare const safeEncode: $SafeEncode;
export type $SafeDecode = <T extends schemas.$ZodType>(schema: T, value: core.input<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => util.SafeParseResult<core.output<T>>;
export declare const _safeDecode: (_Err: $ZodErrorClass) => $SafeDecode;
export declare const safeDecode: $SafeDecode;
export type $SafeEncodeAsync = <T extends schemas.$ZodType>(schema: T, value: core.output<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<util.SafeParseResult<core.input<T>>>;
export declare const _safeEncodeAsync: (_Err: $ZodErrorClass) => $SafeEncodeAsync;
export declare const safeEncodeAsync: $SafeEncodeAsync;
export type $SafeDecodeAsync = <T extends schemas.$ZodType>(schema: T, value: core.input<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<util.SafeParseResult<core.output<T>>>;
export declare const _safeDecodeAsync: (_Err: $ZodErrorClass) => $SafeDecodeAsync;
export declare const safeDecodeAsync: $SafeDecodeAsync;
export {};
+175
View File
@@ -0,0 +1,175 @@
import * as core from "./core.js";
import * as errors from "./errors.js";
import * as util from "./util.js";
// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two.
function finalizeParams(callee, params) {
return { callee: params?.callee ?? callee, Err: params?.Err };
}
export const _parse = (_Err) => {
const fn = (schema, value, _ctx, _params) => {
const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
const result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise) {
throw new core.$ZodAsyncError();
}
if (result.issues.length) {
const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));
util.captureStackTrace(e, _params?.callee ?? fn);
throw e;
}
return result.value;
};
return fn;
};
export const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);
export const _parseAsync = (_Err) => {
const fn = async (schema, value, _ctx, params) => {
const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise)
result = await result;
if (result.issues.length) {
const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));
util.captureStackTrace(e, params?.callee ?? fn);
throw e;
}
return result.value;
};
return fn;
};
export const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);
export const _safeParse = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
const result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise) {
throw new core.$ZodAsyncError();
}
return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };
};
export const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);
// the error is built on the first read of `error`: finalizing the issues and constructing the instance is most of a failing parse, and a caller that only branches on `success` never pays it. a getter in the literal keeps this small; the alternative, one shared accessor descriptor plus a hidden state slot, reads ~15% faster but costs ~75 B gzipped in every bundle
function failure(Err, issues, ctx) {
let error;
return {
success: false,
get error() {
if (!error) {
error = new Err(issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));
// finalizeIssue drops `input`, so the built error holds nothing; keeping the raw issues past this point pins the parsed value for the life of the result
issues = undefined;
ctx = undefined;
}
return error;
},
set error(e) {
error = e;
// a replacement makes the getter's branch unreachable, so the captures have to go here too
issues = undefined;
ctx = undefined;
},
};
}
export const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise)
result = await result;
return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };
};
export const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);
// registry mirrors of the compiler's sentinels, so this module never imports the compiler
const COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid");
const COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback");
// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema.
export const validate = ((schema, value, _ctx) => {
const validator = schema._zod.bag.validator;
if (validator !== undefined) {
if (validator(value) !== COMPILE_INVALID)
return true;
// a definite sentinel means the runtime would reject, so skip the re-parse; a ctx can still change the answer
if (validator.definite === true && _ctx === undefined)
return false;
}
return validateFallback(schema, value, _ctx);
});
function validateFallback(schema, value, _ctx) {
const ctx = _ctx
? { ..._ctx, async: false, abortEarly: true }
: { async: false, abortEarly: true };
const fallbackRun = schema._zod.bag.fallbackRun;
let result;
if (fallbackRun) {
// skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound
ctx[COMPILE_FALLBACK] = true;
result = fallbackRun({ value, issues: [] }, ctx);
}
else {
result = schema._zod.run({ value, issues: [] }, ctx);
}
if (result instanceof Promise) {
throw new core.$ZodAsyncError();
}
return result.issues.length === 0;
}
// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw
export const validateAsync = async (schema, value, _ctx) => {
const ctx = _ctx
? { ..._ctx, async: true, abortEarly: true }
: { async: true, abortEarly: true };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise)
result = await result;
return result.issues.length === 0;
};
export const _encode = (_Err) => {
const parse = _parse(_Err);
const fn = (schema, value, _ctx, _params) => {
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return parse(schema, value, ctx, finalizeParams(fn, _params));
};
return fn;
};
export const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);
export const _decode = (_Err) => {
const parse = _parse(_Err);
const fn = (schema, value, _ctx, _params) => {
return parse(schema, value, _ctx, finalizeParams(fn, _params));
};
return fn;
};
export const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);
export const _encodeAsync = (_Err) => {
const parseAsync = _parseAsync(_Err);
const fn = async (schema, value, _ctx, _params) => {
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params)));
};
return fn;
};
export const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);
export const _decodeAsync = (_Err) => {
const parseAsync = _parseAsync(_Err);
const fn = async (schema, value, _ctx, _params) => {
return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));
};
return fn;
};
export const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);
export const _safeEncode = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return _safeParse(_Err)(schema, value, ctx);
};
export const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);
export const _safeDecode = (_Err) => (schema, value, _ctx) => {
return _safeParse(_Err)(schema, value, _ctx);
};
export const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);
export const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return _safeParseAsync(_Err)(schema, value, ctx);
};
export const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);
export const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
return _safeParseAsync(_Err)(schema, value, _ctx);
};
export const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);
+209
View File
@@ -0,0 +1,209 @@
"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sha1_base64 = exports.sha1_hex = exports.md5_base64url = exports.md5_base64 = exports.md5_hex = exports.hex = exports.uppercase = exports.lowercase = exports.undefined = exports.null = exports.boolean = exports.number = exports.integer = exports.bigint = exports.string = exports.anyString = exports.date = exports.iban = exports.currencyCode = exports.creditCard = exports.e164 = exports.httpProtocol = exports.domain = exports.hostname = exports.base64url = exports.base64 = exports.cidrv6 = exports.cidrv4 = exports.mac = exports.ipv6 = exports.ipv4 = exports.browserEmail = exports.idnEmail = exports.unicodeEmail = exports.rfc5322Email = exports.html5Email = exports.email = exports.uuid7 = exports.uuid6 = exports.uuid4 = exports.uuid = exports.guid = exports.extendedDuration = exports.duration = exports.nanoid = exports.ksuid = exports.xid = exports.ulid = exports.cuid2 = exports.cuid = void 0;
exports.sha512_base64url = exports.sha512_base64 = exports.sha512_hex = exports.sha384_base64url = exports.sha384_base64 = exports.sha384_hex = exports.sha256_base64url = exports.sha256_base64 = exports.sha256_hex = exports.sha1_base64url = void 0;
exports.nanoidOfLength = nanoidOfLength;
exports.emoji = emoji;
exports.time = time;
exports.datetime = datetime;
const util = __importStar(require("./util.cjs"));
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
exports.cuid = /^[cC][0-9a-z]{6,}$/;
exports.cuid2 = /^[0-9a-z]+$/;
exports.ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;
exports.xid = /^[0-9a-vA-V]{20}$/;
exports.ksuid = /^[A-Za-z0-9]{27}$/;
exports.nanoid = /^[a-zA-Z0-9_-]{21}$/;
function nanoidOfLength(length) {
return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);
}
/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
exports.duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */
exports.extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
exports.guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
/** Returns a regex for validating an RFC 9562/4122 UUID.
*
* @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
const uuid = (version) => {
if (!version)
return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
};
exports.uuid = uuid;
exports.uuid4 = (0, exports.uuid)(4);
exports.uuid6 = (0, exports.uuid)(6);
exports.uuid7 = (0, exports.uuid)(7);
/** Practical email validation */
exports.email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */
exports.html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
/** The classic emailregex.com regex for RFC 5322-compliant emails */
exports.rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */
exports.unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u;
exports.idnEmail = exports.unicodeEmail;
exports.browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. The leading lookahead then demands one anchor — a pictograph, a regional indicator, or the enclosing keycap — because `\p{Emoji_Component}` on its own covers ASCII digits, `#`, `*`, ZWJ, variation selectors and skin tone modifiers, none of which is an emoji without a base.
const _emoji = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;
function emoji() {
return new RegExp(_emoji, "u");
}
exports.ipv4 = /^(?:(?: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])$/;
exports.ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
const mac = (delimiter) => {
const escapedDelim = util.escapeRegex(delimiter ?? ":");
return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
};
exports.mac = mac;
exports.cidrv4 = /^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/;
exports.cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
exports.base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
exports.base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;
// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address
// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
exports.hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;
exports.domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/;
exports.httpProtocol = /^https?$/;
// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15
exports.e164 = /^\+[1-9]\d{6,14}$/;
// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro).
exports.creditCard = /^\d(?:[ -]?\d){11,18}$/;
// ISO 4217 alpha codes from the SIX list, regenerated by scripts/update-iso-4217.ts
exports.currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/;
// iban electronic format: 2-letter country, check digits 02-98 (the only values `98 - remainder` can produce), 11-30 bban characters
exports.iban = /^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/;
const dateSource = `(?:(?:\\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])))`;
/** Anchors a pattern source. The interpolation lives here rather than at the call site because
* esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it
* will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */
function anchor(source) {
return new RegExp(`^${source}$`);
}
exports.date = anchor(dateSource);
function timeSource(args) {
const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
const regex = typeof args.precision === "number"
? args.precision === -1
? `${hhmm}`
: args.precision === 0
? `${hhmm}:[0-5]\\d`
: `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`
: args.seconds
? `${hhmm}:[0-5]\\d(?:\\.\\d+)?`
: `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
return regex;
}
function time(args) {
return new RegExp(`^${timeSource(args)}$`);
}
// Adapted from https://stackoverflow.com/a/3143231
function datetime(args) {
const opts = ["Z"];
// if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`);
if (args.offset)
opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
// RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them
const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`;
const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;
return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
}
// the unbounded form of `string()` as a literal, so every plain string shares one instance instead of building its own
exports.anyString = /^[\s\S]{0,}$/;
const string = (params) => {
const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
return new RegExp(`^${regex}$`);
};
exports.string = string;
exports.bigint = /^-?\d+n?$/;
exports.integer = /^-?\d+$/;
exports.number = /^-?\d+(?:\.\d+)?$/;
exports.boolean = /^(?:true|false)$/i;
const _null = /^null$/i;
exports.null = _null;
const _undefined = /^undefined$/i;
exports.undefined = _undefined;
// regex for string with no uppercase letters
exports.lowercase = /^[^A-Z]*$/;
// regex for string with no lowercase letters
exports.uppercase = /^[^a-z]*$/;
// regex for hexadecimal strings (any length)
exports.hex = /^[0-9a-fA-F]*$/;
// Hash regexes for different algorithms and encodings
// Helper function to create base64 regex with exact length and padding
function fixedBase64(bodyLength, padding) {
return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);
}
// Helper function to create base64url regex with exact length (no padding)
function fixedBase64url(length) {
return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);
}
// MD5 (16 bytes): base64 = 24 chars total (22 + "==")
exports.md5_hex = /^[0-9a-fA-F]{32}$/;
exports.md5_base64 = fixedBase64(22, "==");
exports.md5_base64url = fixedBase64url(22);
// SHA1 (20 bytes): base64 = 28 chars total (27 + "=")
exports.sha1_hex = /^[0-9a-fA-F]{40}$/;
exports.sha1_base64 = fixedBase64(27, "=");
exports.sha1_base64url = fixedBase64url(27);
// SHA256 (32 bytes): base64 = 44 chars total (43 + "=")
exports.sha256_hex = /^[0-9a-fA-F]{64}$/;
exports.sha256_base64 = fixedBase64(43, "=");
exports.sha256_base64url = fixedBase64url(43);
// SHA384 (48 bytes): base64 = 64 chars total (no padding)
exports.sha384_hex = /^[0-9a-fA-F]{96}$/;
exports.sha384_base64 = fixedBase64(64, "");
exports.sha384_base64url = fixedBase64url(64);
// SHA512 (64 bytes): base64 = 88 chars total (86 + "==")
exports.sha512_hex = /^[0-9a-fA-F]{128}$/;
exports.sha512_base64 = fixedBase64(86, "==");
exports.sha512_base64url = fixedBase64url(86);
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+90
View File
@@ -0,0 +1,90 @@
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare const cuid: RegExp;
export declare const cuid2: RegExp;
export declare const ulid: RegExp;
export declare const xid: RegExp;
export declare const ksuid: RegExp;
export declare const nanoid: RegExp;
export declare function nanoidOfLength(length: number): RegExp;
/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
export declare const duration: RegExp;
/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */
export declare const extendedDuration: RegExp;
/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
export declare const guid: RegExp;
/** Returns a regex for validating an RFC 9562/4122 UUID.
*
* @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
export declare const uuid: (version?: number | undefined) => RegExp;
export declare const uuid4: RegExp;
export declare const uuid6: RegExp;
export declare const uuid7: RegExp;
/** Practical email validation */
export declare const email: RegExp;
/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */
export declare const html5Email: RegExp;
/** The classic emailregex.com regex for RFC 5322-compliant emails */
export declare const rfc5322Email: RegExp;
/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */
export declare const unicodeEmail: RegExp;
export declare const idnEmail: RegExp;
export declare const browserEmail: RegExp;
export declare function emoji(): RegExp;
export declare const ipv4: RegExp;
export declare const ipv6: RegExp;
export declare const mac: (delimiter?: string) => RegExp;
export declare const cidrv4: RegExp;
export declare const cidrv6: RegExp;
export declare const base64: RegExp;
export declare const base64url: RegExp;
export declare const hostname: RegExp;
export declare const domain: RegExp;
export declare const httpProtocol: RegExp;
export declare const e164: RegExp;
export declare const creditCard: RegExp;
export declare const currencyCode: RegExp;
export declare const iban: RegExp;
export declare const date: RegExp;
export declare function time(args: {
precision?: number | null;
}): RegExp;
export declare function datetime(args: {
precision?: number | null;
offset?: boolean;
local?: boolean;
}): RegExp;
export declare const anyString: RegExp;
export declare const string: (params?: {
minimum?: number | undefined;
maximum?: number | undefined;
}) => RegExp;
export declare const bigint: RegExp;
export declare const integer: RegExp;
export declare const number: RegExp;
export declare const boolean: RegExp;
declare const _null: RegExp;
export { _null as null };
declare const _undefined: RegExp;
export { _undefined as undefined };
export declare const lowercase: RegExp;
export declare const uppercase: RegExp;
export declare const hex: RegExp;
export declare const md5_hex: RegExp;
export declare const md5_base64: RegExp;
export declare const md5_base64url: RegExp;
export declare const sha1_hex: RegExp;
export declare const sha1_base64: RegExp;
export declare const sha1_base64url: RegExp;
export declare const sha256_hex: RegExp;
export declare const sha256_base64: RegExp;
export declare const sha256_base64url: RegExp;
export declare const sha384_hex: RegExp;
export declare const sha384_base64: RegExp;
export declare const sha384_base64url: RegExp;
export declare const sha512_hex: RegExp;
export declare const sha512_base64: RegExp;
export declare const sha512_base64url: RegExp;

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