UNPKG

zod

Version:

TypeScript-first schema declaration and validation library with static type inference

1,707 lines (1,423 loc) • 120 kB
import type { $ZodTypeDiscriminable } from "./api.js"; import * as checks from "./checks.js"; import * as core from "./core.js"; import { Doc } from "./doc.js"; import type * as errors from "./errors.js"; import { safeParse, safeParseAsync } from "./parse.js"; import * as regexes from "./regexes.js"; import type { StandardSchemaV1 } from "./standard-schema.js"; import * as util from "./util.js"; import { version } from "./versions.js"; ///////////////////////////// PARSE ////////////////////////////// export interface ParseContext<T extends errors.$ZodIssueBase = never> { /** Customize error messages. */ readonly error?: errors.$ZodErrorMap<T>; /** Include the `input` field in issue objects. Default `false`. */ readonly reportInput?: boolean; /** Skip eval-based fast path. Default `false`. */ readonly jitless?: boolean; /** Abort validation after the first error. Default `false`. */ // readonly abortEarly?: boolean; } /** @internal */ export interface ParseContextInternal<T extends errors.$ZodIssueBase = never> extends ParseContext<T> { readonly async?: boolean | undefined; } export interface ParsePayload<T = unknown> { value: T; issues: errors.$ZodRawIssue[]; } export type CheckFn<T> = (input: ParsePayload<T>) => util.MaybeAsync<void>; ///////////////////////////// SCHEMAS ////////////////////////////// export interface $ZodTypeDef { type: | "string" | "number" | "int" | "boolean" | "bigint" | "symbol" | "null" | "undefined" | "void" // merge with undefined? | "never" | "any" | "unknown" | "date" | "object" | "record" | "file" | "array" | "tuple" | "union" | "intersection" | "map" | "set" | "enum" | "literal" | "nullable" | "optional" | "nonoptional" | "success" | "transform" | "default" | "prefault" | "catch" | "nan" | "pipe" | "readonly" | "template_literal" | "promise" | "lazy" | "custom"; error?: errors.$ZodErrorMap<never> | undefined; checks?: checks.$ZodCheck<never>[]; } export interface _$ZodTypeInternals { /** The `@zod/core` version of this schema */ version: typeof version; /** Schema definition. */ def: $ZodTypeDef; // types: Types; /** @internal Randomly generated ID for this schema. */ // id: string; /** @internal List of deferred initializers. */ deferred: util.AnyFunc[] | undefined; /** @internal Parses input and runs all checks (refinements). */ run(payload: ParsePayload<any>, ctx: ParseContextInternal): util.MaybeAsync<ParsePayload>; /** @internal Parses input, doesn't run checks. */ parse(payload: ParsePayload<any>, ctx: ParseContextInternal): util.MaybeAsync<ParsePayload>; /** @internal Stores identifiers for the set of traits implemented by this schema. */ traits: Set<string>; /** @internal Indicates that a schema output type should be considered optional inside objects. * @default Required */ /** @internal */ optin?: "optional" | undefined; /** @internal */ optout?: "optional" | undefined; /** @internal The set of literal values that will pass validation. Must be an exhaustive set. Used to determine optionality in z.record(). * * Defined on: enum, const, literal, null, undefined * Passthrough: optional, nullable, branded, default, catch, pipe * Todo: unions? */ values?: util.PrimitiveSet | undefined; /** Default value bubbled up from */ // default?: unknown | undefined; /** @internal A set of literal discriminators used for the fast path in discriminated unions. */ propValues?: util.PropValues | undefined; /** @internal This flag indicates that a schema validation can be represented with a regular expression. Used to determine allowable schemas in z.templateLiteral(). */ pattern: RegExp | undefined; /** @internal The constructor function of this schema. */ constr: new ( def: any ) => $ZodType; /** @internal A catchall object for bag metadata related to this schema. Commonly modified by checks using `onattach`. */ bag: Record<string, unknown>; /** @internal The set of issues this schema might throw during type checking. */ isst: errors.$ZodIssueBase; /** An optional method used to override `toJSONSchema` logic. */ toJSONSchema?: () => unknown; /** @internal The parent of this schema. Only set during certain clone operations. */ parent?: $ZodType | undefined; } /** @internal */ export interface $ZodTypeInternals<out O = unknown, out I = unknown> extends _$ZodTypeInternals { /** @internal The inferred output type */ output: O; //extends { $out: infer O } ? O : Out; /** @internal The inferred input type */ input: I; //extends { $in: infer I } ? I : In; } export type $ZodStandardSchema<T> = StandardSchemaV1.Props<core.input<T>, core.output<T>>; export type SomeType = { _zod: _$ZodTypeInternals }; export interface $ZodType< O = unknown, I = unknown, Internals extends $ZodTypeInternals<O, I> = $ZodTypeInternals<O, I>, > { _zod: Internals; "~standard": $ZodStandardSchema<this>; } export interface _$ZodType<T extends $ZodTypeInternals = $ZodTypeInternals> extends $ZodType<T["output"], T["input"], T> { // _zod: T; } export const $ZodType: core.$constructor<$ZodType> = /*@__PURE__*/ core.$constructor("$ZodType", (inst, def) => { inst ??= {} as any; inst._zod.def = def; // set _def property inst._zod.bag = inst._zod.bag || {}; // initialize _bag object inst._zod.version = version; const checks = [...(inst._zod.def.checks ?? [])]; // if inst is itself a checks.$ZodCheck, run it as a check if (inst._zod.traits.has("$ZodCheck")) { checks.unshift(inst as any); } // for (const ch of checks) { for (const fn of ch._zod.onattach) { fn(inst); } } if (checks.length === 0) { // deferred initializer // inst._zod.parse is not yet defined inst._zod.deferred ??= []; inst._zod.deferred?.push(() => { inst._zod.run = inst._zod.parse; }); } else { const runChecks = ( payload: ParsePayload, checks: checks.$ZodCheck<never>[], ctx?: ParseContextInternal | undefined ): util.MaybeAsync<ParsePayload> => { let isAborted = util.aborted(payload); let asyncResult!: Promise<unknown> | undefined; for (const ch of checks) { if (ch._zod.def.when) { const shouldRun = ch._zod.def.when(payload); if (!shouldRun) continue; } else if (isAborted) { continue; } const currLen = payload.issues.length; const _ = ch._zod.check(payload as any) as any as ParsePayload; if (_ instanceof Promise && ctx?.async === false) { throw new core.$ZodAsyncError(); } if (asyncResult || _ instanceof Promise) { asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { await _; const nextLen = payload.issues.length; if (nextLen === currLen) return; if (!isAborted) isAborted = util.aborted(payload, currLen); }); } else { const nextLen = payload.issues.length; if (nextLen === currLen) continue; if (!isAborted) isAborted = util.aborted(payload, currLen); } } if (asyncResult) { return asyncResult.then(() => { return payload; }); } return payload; }; inst._zod.run = (payload, ctx) => { const result = inst._zod.parse(payload, ctx); if (result instanceof Promise) { if (ctx.async === false) throw new core.$ZodAsyncError(); return result.then((result) => runChecks(result, checks, ctx)); } return runChecks(result, checks, ctx); }; } inst["~standard"] = { validate: (value: unknown) => { try { const r = safeParse(inst, value); return r.success ? { value: r.data } : { issues: r.error?.issues }; } catch (_) { return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues })); } }, vendor: "zod", version: 1 as const, }; }); export { clone } from "./util.js"; ////////////////////////////////////////// ////////////////////////////////////////// ////////// ////////// ////////// $ZodString ////////// ////////// ////////// ////////////////////////////////////////// ////////////////////////////////////////// export interface $ZodStringDef extends $ZodTypeDef { type: "string"; coerce?: boolean; checks?: checks.$ZodCheck<string>[]; } export interface $ZodStringInternals<Input> extends $ZodTypeInternals<string, Input> { def: $ZodStringDef; /** @deprecated Internal API, use with caution (not deprecated) */ pattern: RegExp; /** @deprecated Internal API, use with caution (not deprecated) */ isst: errors.$ZodIssueInvalidType; bag: util.LoosePartial<{ minimum: number; maximum: number; patterns: Set<RegExp>; format: string; contentEncoding: string; }>; } export interface $ZodString<Input = unknown> extends _$ZodType<$ZodStringInternals<Input>> { // _zod: $ZodStringInternals<Input>; } export const $ZodString: core.$constructor<$ZodString> = /*@__PURE__*/ core.$constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag); inst._zod.parse = (payload, _) => { if (def.coerce) try { payload.value = String(payload.value); } catch (_) {} if (typeof payload.value === "string") return payload; payload.issues.push({ expected: "string", code: "invalid_type", input: payload.value, inst, }); return payload; }; }); ////////////////////////////// ZodStringFormat ////////////////////////////// export interface $ZodStringFormatDef<Format extends string = string> extends $ZodStringDef, checks.$ZodCheckStringFormatDef<Format> {} export interface $ZodStringFormatInternals<Format extends string = string> extends $ZodStringInternals<string>, checks.$ZodCheckStringFormatInternals { def: $ZodStringFormatDef<Format>; } export interface $ZodStringFormat<Format extends string = string> extends $ZodType { _zod: $ZodStringFormatInternals<Format>; } export const $ZodStringFormat: core.$constructor<$ZodStringFormat> = /*@__PURE__*/ core.$constructor( "$ZodStringFormat", (inst, def): void => { // check initialization must come first checks.$ZodCheckStringFormat.init(inst, def); $ZodString.init(inst, def); } ); ////////////////////////////// ZodGUID ////////////////////////////// export interface $ZodGUIDDef extends $ZodStringFormatDef<"guid"> {} export interface $ZodGUIDInternals extends $ZodStringFormatInternals<"guid"> {} export interface $ZodGUID extends $ZodType { _zod: $ZodGUIDInternals; } export const $ZodGUID: core.$constructor<$ZodGUID> = /*@__PURE__*/ core.$constructor("$ZodGUID", (inst, def): void => { def.pattern ??= regexes.guid; $ZodStringFormat.init(inst, def); }); ////////////////////////////// ZodUUID ////////////////////////////// export interface $ZodUUIDDef extends $ZodStringFormatDef<"uuid"> { version?: "v1" | "v2" | "v3" | "v4" | "v5" | "v6" | "v7" | "v8"; } export interface $ZodUUIDInternals extends $ZodStringFormatInternals<"uuid"> { def: $ZodUUIDDef; } export interface $ZodUUID extends $ZodType { _zod: $ZodUUIDInternals; } export const $ZodUUID: core.$constructor<$ZodUUID> = /*@__PURE__*/ core.$constructor("$ZodUUID", (inst, def): void => { if (def.version) { const versionMap: Record<string, number> = { v1: 1, v2: 2, v3: 3, v4: 4, v5: 5, v6: 6, v7: 7, v8: 8, }; const v = versionMap[def.version]; if (v === undefined) throw new Error(`Invalid UUID version: "${def.version}"`); def.pattern ??= regexes.uuid(v); } else def.pattern ??= regexes.uuid(); $ZodStringFormat.init(inst, def); }); ////////////////////////////// ZodEmail ////////////////////////////// export interface $ZodEmailDef extends $ZodStringFormatDef<"email"> {} export interface $ZodEmailInternals extends $ZodStringFormatInternals<"email"> {} export interface $ZodEmail extends $ZodType { _zod: $ZodEmailInternals; } export const $ZodEmail: core.$constructor<$ZodEmail> = /*@__PURE__*/ core.$constructor( "$ZodEmail", (inst, def): void => { def.pattern ??= regexes.email; $ZodStringFormat.init(inst, def); } ); ////////////////////////////// ZodURL ////////////////////////////// export interface $ZodURLDef extends $ZodStringFormatDef<"url"> { hostname?: RegExp | undefined; protocol?: RegExp | undefined; normalize?: boolean | undefined; } export interface $ZodURLInternals extends $ZodStringFormatInternals<"url"> { def: $ZodURLDef; } export interface $ZodURL extends $ZodType { _zod: $ZodURLInternals; } export const $ZodURL: core.$constructor<$ZodURL> = /*@__PURE__*/ core.$constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { // Trim whitespace from input const trimmed = payload.value.trim(); // @ts-ignore const url = new URL(trimmed); if (def.hostname) { def.hostname.lastIndex = 0; if (!def.hostname.test(url.hostname)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid hostname", pattern: regexes.hostname.source, input: payload.value, inst, continue: !def.abort, }); } } if (def.protocol) { def.protocol.lastIndex = 0; if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid protocol", pattern: def.protocol.source, input: payload.value, inst, continue: !def.abort, }); } } // Set the output value based on normalize flag if (def.normalize) { // Use normalized URL payload.value = url.href; } else { // Preserve the original input (trimmed) payload.value = trimmed; } return; } catch (_) { payload.issues.push({ code: "invalid_format", format: "url", input: payload.value, inst, continue: !def.abort, }); } }; }); ////////////////////////////// ZodEmoji ////////////////////////////// export interface $ZodEmojiDef extends $ZodStringFormatDef<"emoji"> {} export interface $ZodEmojiInternals extends $ZodStringFormatInternals<"emoji"> {} export interface $ZodEmoji extends $ZodType { _zod: $ZodEmojiInternals; } export const $ZodEmoji: core.$constructor<$ZodEmoji> = /*@__PURE__*/ core.$constructor( "$ZodEmoji", (inst, def): void => { def.pattern ??= regexes.emoji(); $ZodStringFormat.init(inst, def); } ); ////////////////////////////// ZodNanoID ////////////////////////////// export interface $ZodNanoIDDef extends $ZodStringFormatDef<"nanoid"> {} export interface $ZodNanoIDInternals extends $ZodStringFormatInternals<"nanoid"> {} export interface $ZodNanoID extends $ZodType { _zod: $ZodNanoIDInternals; } export const $ZodNanoID: core.$constructor<$ZodNanoID> = /*@__PURE__*/ core.$constructor( "$ZodNanoID", (inst, def): void => { def.pattern ??= regexes.nanoid; $ZodStringFormat.init(inst, def); } ); ////////////////////////////// ZodCUID ////////////////////////////// export interface $ZodCUIDDef extends $ZodStringFormatDef<"cuid"> {} export interface $ZodCUIDInternals extends $ZodStringFormatInternals<"cuid"> {} export interface $ZodCUID extends $ZodType { _zod: $ZodCUIDInternals; } export const $ZodCUID: core.$constructor<$ZodCUID> = /*@__PURE__*/ core.$constructor("$ZodCUID", (inst, def): void => { def.pattern ??= regexes.cuid; $ZodStringFormat.init(inst, def); }); ////////////////////////////// ZodCUID2 ////////////////////////////// export interface $ZodCUID2Def extends $ZodStringFormatDef<"cuid2"> {} export interface $ZodCUID2Internals extends $ZodStringFormatInternals<"cuid2"> {} export interface $ZodCUID2 extends $ZodType { _zod: $ZodCUID2Internals; } export const $ZodCUID2: core.$constructor<$ZodCUID2> = /*@__PURE__*/ core.$constructor( "$ZodCUID2", (inst, def): void => { def.pattern ??= regexes.cuid2; $ZodStringFormat.init(inst, def); } ); ////////////////////////////// ZodULID ////////////////////////////// export interface $ZodULIDDef extends $ZodStringFormatDef<"ulid"> {} export interface $ZodULIDInternals extends $ZodStringFormatInternals<"ulid"> {} export interface $ZodULID extends $ZodType { _zod: $ZodULIDInternals; } export const $ZodULID: core.$constructor<$ZodULID> = /*@__PURE__*/ core.$constructor("$ZodULID", (inst, def): void => { def.pattern ??= regexes.ulid; $ZodStringFormat.init(inst, def); }); ////////////////////////////// ZodXID ////////////////////////////// export interface $ZodXIDDef extends $ZodStringFormatDef<"xid"> {} export interface $ZodXIDInternals extends $ZodStringFormatInternals<"xid"> {} export interface $ZodXID extends $ZodType { _zod: $ZodXIDInternals; } export const $ZodXID: core.$constructor<$ZodXID> = /*@__PURE__*/ core.$constructor("$ZodXID", (inst, def): void => { def.pattern ??= regexes.xid; $ZodStringFormat.init(inst, def); }); ////////////////////////////// ZodKSUID ////////////////////////////// export interface $ZodKSUIDDef extends $ZodStringFormatDef<"ksuid"> {} export interface $ZodKSUIDInternals extends $ZodStringFormatInternals<"ksuid"> {} export interface $ZodKSUID extends $ZodType { _zod: $ZodKSUIDInternals; } export const $ZodKSUID: core.$constructor<$ZodKSUID> = /*@__PURE__*/ core.$constructor( "$ZodKSUID", (inst, def): void => { def.pattern ??= regexes.ksuid; $ZodStringFormat.init(inst, def); } ); ////////////////////////////// ZodISODateTime ////////////////////////////// export interface $ZodISODateTimeDef extends $ZodStringFormatDef<"datetime"> { precision: number | null; offset: boolean; local: boolean; } export interface $ZodISODateTimeInternals extends $ZodStringFormatInternals { def: $ZodISODateTimeDef; } export interface $ZodISODateTime extends $ZodType { _zod: $ZodISODateTimeInternals; } export const $ZodISODateTime: core.$constructor<$ZodISODateTime> = /*@__PURE__*/ core.$constructor( "$ZodISODateTime", (inst, def): void => { def.pattern ??= regexes.datetime(def); $ZodStringFormat.init(inst, def); } ); ////////////////////////////// ZodISODate ////////////////////////////// export interface $ZodISODateDef extends $ZodStringFormatDef<"date"> {} export interface $ZodISODateInternals extends $ZodStringFormatInternals<"date"> {} export interface $ZodISODate extends $ZodType { _zod: $ZodISODateInternals; } export const $ZodISODate: core.$constructor<$ZodISODate> = /*@__PURE__*/ core.$constructor( "$ZodISODate", (inst, def): void => { def.pattern ??= regexes.date; $ZodStringFormat.init(inst, def); } ); ////////////////////////////// ZodISOTime ////////////////////////////// export interface $ZodISOTimeDef extends $ZodStringFormatDef<"time"> { precision?: number | null; } export interface $ZodISOTimeInternals extends $ZodStringFormatInternals<"time"> { def: $ZodISOTimeDef; } export interface $ZodISOTime extends $ZodType { _zod: $ZodISOTimeInternals; } export const $ZodISOTime: core.$constructor<$ZodISOTime> = /*@__PURE__*/ core.$constructor( "$ZodISOTime", (inst, def): void => { def.pattern ??= regexes.time(def); $ZodStringFormat.init(inst, def); } ); ////////////////////////////// ZodISODuration ////////////////////////////// export interface $ZodISODurationDef extends $ZodStringFormatDef<"duration"> {} export interface $ZodISODurationInternals extends $ZodStringFormatInternals<"duration"> {} export interface $ZodISODuration extends $ZodType { _zod: $ZodISODurationInternals; } export const $ZodISODuration: core.$constructor<$ZodISODuration> = /*@__PURE__*/ core.$constructor( "$ZodISODuration", (inst, def): void => { def.pattern ??= regexes.duration; $ZodStringFormat.init(inst, def); } ); ////////////////////////////// ZodIPv4 ////////////////////////////// export interface $ZodIPv4Def extends $ZodStringFormatDef<"ipv4"> { version?: "v4"; } export interface $ZodIPv4Internals extends $ZodStringFormatInternals<"ipv4"> { def: $ZodIPv4Def; } export interface $ZodIPv4 extends $ZodType { _zod: $ZodIPv4Internals; } export const $ZodIPv4: core.$constructor<$ZodIPv4> = /*@__PURE__*/ core.$constructor("$ZodIPv4", (inst, def): void => { def.pattern ??= regexes.ipv4; $ZodStringFormat.init(inst, def); inst._zod.onattach.push((inst) => { const bag = inst._zod.bag as $ZodStringInternals<unknown>["bag"]; bag.format = `ipv4`; }); }); ////////////////////////////// ZodIPv6 ////////////////////////////// export interface $ZodIPv6Def extends $ZodStringFormatDef<"ipv6"> { version?: "v6"; } export interface $ZodIPv6Internals extends $ZodStringFormatInternals<"ipv6"> { def: $ZodIPv6Def; } export interface $ZodIPv6 extends $ZodType { _zod: $ZodIPv6Internals; } export const $ZodIPv6: core.$constructor<$ZodIPv6> = /*@__PURE__*/ core.$constructor("$ZodIPv6", (inst, def): void => { def.pattern ??= regexes.ipv6; $ZodStringFormat.init(inst, def); inst._zod.onattach.push((inst) => { const bag = inst._zod.bag as $ZodStringInternals<unknown>["bag"]; bag.format = `ipv6`; }); inst._zod.check = (payload) => { try { // @ts-ignore new URL(`http://[${payload.value}]`); // return; } catch { payload.issues.push({ code: "invalid_format", format: "ipv6", input: payload.value, inst, continue: !def.abort, }); } }; }); ////////////////////////////// ZodCIDRv4 ////////////////////////////// export interface $ZodCIDRv4Def extends $ZodStringFormatDef<"cidrv4"> { version?: "v4"; } export interface $ZodCIDRv4Internals extends $ZodStringFormatInternals<"cidrv4"> { def: $ZodCIDRv4Def; } export interface $ZodCIDRv4 extends $ZodType { _zod: $ZodCIDRv4Internals; } export const $ZodCIDRv4: core.$constructor<$ZodCIDRv4> = /*@__PURE__*/ core.$constructor( "$ZodCIDRv4", (inst, def): void => { def.pattern ??= regexes.cidrv4; $ZodStringFormat.init(inst, def); } ); ////////////////////////////// ZodCIDRv6 ////////////////////////////// export interface $ZodCIDRv6Def extends $ZodStringFormatDef<"cidrv6"> { version?: "v6"; } export interface $ZodCIDRv6Internals extends $ZodStringFormatInternals<"cidrv6"> { def: $ZodCIDRv6Def; } export interface $ZodCIDRv6 extends $ZodType { _zod: $ZodCIDRv6Internals; } export const $ZodCIDRv6: core.$constructor<$ZodCIDRv6> = /*@__PURE__*/ core.$constructor( "$ZodCIDRv6", (inst, def): void => { def.pattern ??= regexes.cidrv6; // not used for validation $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { const [address, prefix] = payload.value.split("/"); try { if (!prefix) throw new Error(); const prefixNum = Number(prefix); if (`${prefixNum}` !== prefix) throw new Error(); if (prefixNum < 0 || prefixNum > 128) throw new Error(); // @ts-ignore new URL(`http://[${address}]`); } catch { payload.issues.push({ code: "invalid_format", format: "cidrv6", input: payload.value, inst, continue: !def.abort, }); } }; } ); ////////////////////////////// ZodBase64 ////////////////////////////// export function isValidBase64(data: string): boolean { if (data === "") return true; if (data.length % 4 !== 0) return false; try { // @ts-ignore atob(data); return true; } catch { return false; } } export interface $ZodBase64Def extends $ZodStringFormatDef<"base64"> {} export interface $ZodBase64Internals extends $ZodStringFormatInternals<"base64"> {} export interface $ZodBase64 extends $ZodType { _zod: $ZodBase64Internals; } export const $ZodBase64: core.$constructor<$ZodBase64> = /*@__PURE__*/ core.$constructor( "$ZodBase64", (inst, def): void => { def.pattern ??= regexes.base64; $ZodStringFormat.init(inst, def); inst._zod.onattach.push((inst) => { inst._zod.bag.contentEncoding = "base64"; }); inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; payload.issues.push({ code: "invalid_format", format: "base64", input: payload.value, inst, continue: !def.abort, }); }; } ); ////////////////////////////// ZodBase64 ////////////////////////////// export function isValidBase64URL(data: string): boolean { if (!regexes.base64url.test(data)) return false; const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); return isValidBase64(padded); } export interface $ZodBase64URLDef extends $ZodStringFormatDef<"base64url"> {} export interface $ZodBase64URLInternals extends $ZodStringFormatInternals<"base64url"> {} export interface $ZodBase64URL extends $ZodType { _zod: $ZodBase64URLInternals; } export const $ZodBase64URL: core.$constructor<$ZodBase64URL> = /*@__PURE__*/ core.$constructor( "$ZodBase64URL", (inst, def): void => { def.pattern ??= regexes.base64url; $ZodStringFormat.init(inst, def); inst._zod.onattach.push((inst) => { inst._zod.bag.contentEncoding = "base64url"; }); inst._zod.check = (payload) => { if (isValidBase64URL(payload.value)) return; payload.issues.push({ code: "invalid_format", format: "base64url", input: payload.value, inst, continue: !def.abort, }); }; } ); ////////////////////////////// ZodE164 ////////////////////////////// export interface $ZodE164Def extends $ZodStringFormatDef<"e164"> {} export interface $ZodE164Internals extends $ZodStringFormatInternals<"e164"> {} export interface $ZodE164 extends $ZodType { _zod: $ZodE164Internals; } export const $ZodE164: core.$constructor<$ZodE164> = /*@__PURE__*/ core.$constructor("$ZodE164", (inst, def): void => { def.pattern ??= regexes.e164; $ZodStringFormat.init(inst, def); }); ////////////////////////////// ZodJWT ////////////////////////////// export function isValidJWT(token: string, algorithm: util.JWTAlgorithm | null = null): boolean { try { const tokensParts = token.split("."); if (tokensParts.length !== 3) return false; const [header] = tokensParts; if (!header) return false; // @ts-ignore const parsedHeader = JSON.parse(atob(header)); if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false; if (!parsedHeader.alg) return false; if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false; return true; } catch { return false; } } export interface $ZodJWTDef extends $ZodStringFormatDef<"jwt"> { alg?: util.JWTAlgorithm | undefined; } export interface $ZodJWTInternals extends $ZodStringFormatInternals<"jwt"> { def: $ZodJWTDef; } export interface $ZodJWT extends $ZodType { _zod: $ZodJWTInternals; } export const $ZodJWT: core.$constructor<$ZodJWT> = /*@__PURE__*/ core.$constructor("$ZodJWT", (inst, def): void => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { if (isValidJWT(payload.value, def.alg)) return; payload.issues.push({ code: "invalid_format", format: "jwt", input: payload.value, inst, continue: !def.abort, }); }; }); ////////////////////////////// ZodCustomStringFormat ////////////////////////////// export interface $ZodCustomStringFormatDef<Format extends string = string> extends $ZodStringFormatDef<Format> { fn: (val: string) => unknown; } export interface $ZodCustomStringFormatInternals<Format extends string = string> extends $ZodStringFormatInternals<Format> { def: $ZodCustomStringFormatDef<Format>; } export interface $ZodCustomStringFormat<Format extends string = string> extends $ZodStringFormat<Format> { _zod: $ZodCustomStringFormatInternals<Format>; } export const $ZodCustomStringFormat: core.$constructor<$ZodCustomStringFormat> = /*@__PURE__*/ core.$constructor( "$ZodCustomStringFormat", (inst, def): void => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { if (def.fn(payload.value)) return; payload.issues.push({ code: "invalid_format", format: def.format, input: payload.value, inst, continue: !def.abort, }); }; } ); ///////////////////////////////////////// ///////////////////////////////////////// ////////// ////////// ////////// ZodNumber ////////// ////////// ////////// ///////////////////////////////////////// ///////////////////////////////////////// export interface $ZodNumberDef extends $ZodTypeDef { type: "number"; coerce?: boolean; // checks: checks.$ZodCheck<number>[]; } export interface $ZodNumberInternals<Input = unknown> extends $ZodTypeInternals<number, Input> { def: $ZodNumberDef; /** @deprecated Internal API, use with caution (not deprecated) */ pattern: RegExp; /** @deprecated Internal API, use with caution (not deprecated) */ isst: errors.$ZodIssueInvalidType; bag: util.LoosePartial<{ minimum: number; maximum: number; exclusiveMinimum: number; exclusiveMaximum: number; format: string; pattern: RegExp; }>; } export interface $ZodNumber<Input = unknown> extends $ZodType { _zod: $ZodNumberInternals<Input>; } export const $ZodNumber: core.$constructor<$ZodNumber> = /*@__PURE__*/ core.$constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_) {} const input = payload.value; if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { return payload; } const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : undefined : undefined; payload.issues.push({ expected: "number", code: "invalid_type", input, inst, ...(received ? { received } : {}), }); return payload; }; }); /////////////////////////////////////////////// ////////// ZodNumberFormat ////////// /////////////////////////////////////////////// export interface $ZodNumberFormatDef extends $ZodNumberDef, checks.$ZodCheckNumberFormatDef {} export interface $ZodNumberFormatInternals extends $ZodNumberInternals<number>, checks.$ZodCheckNumberFormatInternals { def: $ZodNumberFormatDef; isst: errors.$ZodIssueInvalidType; } export interface $ZodNumberFormat extends $ZodType { _zod: $ZodNumberFormatInternals; } export const $ZodNumberFormat: core.$constructor<$ZodNumberFormat> = /*@__PURE__*/ core.$constructor( "$ZodNumber", (inst, def) => { checks.$ZodCheckNumberFormat.init(inst, def); $ZodNumber.init(inst, def); // no format checksp } ); /////////////////////////////////////////// /////////////////////////////////////////// ////////// /////////// ////////// $ZodBoolean ////////// ////////// /////////// /////////////////////////////////////////// /////////////////////////////////////////// export interface $ZodBooleanDef extends $ZodTypeDef { type: "boolean"; coerce?: boolean; checks?: checks.$ZodCheck<boolean>[]; } export interface $ZodBooleanInternals<T = unknown> extends $ZodTypeInternals<boolean, T> { pattern: RegExp; def: $ZodBooleanDef; isst: errors.$ZodIssueInvalidType; } export interface $ZodBoolean<T = unknown> extends $ZodType { _zod: $ZodBooleanInternals<T>; } export const $ZodBoolean: core.$constructor<$ZodBoolean> = /*@__PURE__*/ core.$constructor( "$ZodBoolean", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = regexes.boolean; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Boolean(payload.value); } catch (_) {} const input = payload.value; if (typeof input === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", input, inst, }); return payload; }; } ); ////////////////////////////////////////// ////////////////////////////////////////// ////////// ////////// ////////// $ZodBigInt ////////// ////////// ////////// ////////////////////////////////////////// ////////////////////////////////////////// export interface $ZodBigIntDef extends $ZodTypeDef { type: "bigint"; coerce?: boolean; // checks: checks.$ZodCheck<bigint>[]; } export interface $ZodBigIntInternals<T = unknown> extends $ZodTypeInternals<bigint, T> { pattern: RegExp; /** @internal Internal API, use with caution */ def: $ZodBigIntDef; isst: errors.$ZodIssueInvalidType; bag: util.LoosePartial<{ minimum: bigint; maximum: bigint; format: string; }>; } export interface $ZodBigInt<T = unknown> extends $ZodType { _zod: $ZodBigIntInternals<T>; } export const $ZodBigInt: core.$constructor<$ZodBigInt> = /*@__PURE__*/ core.$constructor("$ZodBigInt", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = regexes.bigint; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = BigInt(payload.value); } catch (_) {} if (typeof payload.value === "bigint") return payload; payload.issues.push({ expected: "bigint", code: "invalid_type", input: payload.value, inst, }); return payload; }; }); /////////////////////////////////////////////// ////////// ZodBigIntFormat ////////// /////////////////////////////////////////////// export interface $ZodBigIntFormatDef extends $ZodBigIntDef, checks.$ZodCheckBigIntFormatDef { check: "bigint_format"; } export interface $ZodBigIntFormatInternals extends $ZodBigIntInternals<bigint>, checks.$ZodCheckBigIntFormatInternals { def: $ZodBigIntFormatDef; } export interface $ZodBigIntFormat extends $ZodType { _zod: $ZodBigIntFormatInternals; } export const $ZodBigIntFormat: core.$constructor<$ZodBigIntFormat> = /*@__PURE__*/ core.$constructor( "$ZodBigInt", (inst, def) => { checks.$ZodCheckBigIntFormat.init(inst, def); $ZodBigInt.init(inst, def); // no format checks } ); //////////////////////////////////////////// //////////////////////////////////////////// ////////// ////////// ////////// $ZodSymbol ////////// ////////// ////////// //////////////////////////////////////////// //////////////////////////////////////////// export interface $ZodSymbolDef extends $ZodTypeDef { type: "symbol"; } export interface $ZodSymbolInternals extends $ZodTypeInternals<symbol, symbol> { def: $ZodSymbolDef; isst: errors.$ZodIssueInvalidType; } export interface $ZodSymbol extends $ZodType { _zod: $ZodSymbolInternals; } export const $ZodSymbol: core.$constructor<$ZodSymbol> = /*@__PURE__*/ core.$constructor("$ZodSymbol", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "symbol") return payload; payload.issues.push({ expected: "symbol", code: "invalid_type", input, inst, }); return payload; }; }); //////////////////////////////////////////// //////////////////////////////////////////// ////////// ////////// ////////// $ZodUndefined ////////// ////////// ////////// //////////////////////////////////////////// //////////////////////////////////////////// export interface $ZodUndefinedDef extends $ZodTypeDef { type: "undefined"; } export interface $ZodUndefinedInternals extends $ZodTypeInternals<undefined, undefined> { pattern: RegExp; def: $ZodUndefinedDef; values: util.PrimitiveSet; isst: errors.$ZodIssueInvalidType; } export interface $ZodUndefined extends $ZodType { _zod: $ZodUndefinedInternals; } export const $ZodUndefined: core.$constructor<$ZodUndefined> = /*@__PURE__*/ core.$constructor( "$ZodUndefined", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = regexes.undefined; inst._zod.values = new Set([undefined]); inst._zod.optin = "optional"; inst._zod.optout = "optional"; inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "undefined") return payload; payload.issues.push({ expected: "undefined", code: "invalid_type", input, inst, }); return payload; }; } ); /////////////////////////////////////// /////////////////////////////////////// ////////// ////////// ////////// $ZodNull ///////// ////////// ////////// /////////////////////////////////////// /////////////////////////////////////// export interface $ZodNullDef extends $ZodTypeDef { type: "null"; } export interface $ZodNullInternals extends $ZodTypeInternals<null, null> { pattern: RegExp; def: $ZodNullDef; values: util.PrimitiveSet; isst: errors.$ZodIssueInvalidType; } export interface $ZodNull extends $ZodType { _zod: $ZodNullInternals; } export const $ZodNull: core.$constructor<$ZodNull> = /*@__PURE__*/ core.$constructor("$ZodNull", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = regexes.null; inst._zod.values = new Set([null]); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (input === null) return payload; payload.issues.push({ expected: "null", code: "invalid_type", input, inst, }); return payload; }; }); ////////////////////////////////////// ////////////////////////////////////// ////////// ////////// ////////// $ZodAny ////////// ////////// ////////// ////////////////////////////////////// ////////////////////////////////////// export interface $ZodAnyDef extends $ZodTypeDef { type: "any"; } export interface $ZodAnyInternals extends $ZodTypeInternals<any, any> { def: $ZodAnyDef; isst: never; } export interface $ZodAny extends $ZodType { _zod: $ZodAnyInternals; } export const $ZodAny: core.$constructor<$ZodAny> = /*@__PURE__*/ core.$constructor("$ZodAny", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload) => payload; }); ////////////////////////////////////////// ////////////////////////////////////////// ////////// ////////// ////////// $ZodUnknown ////////// ////////// ////////// ////////////////////////////////////////// ////////////////////////////////////////// export interface $ZodUnknownDef extends $ZodTypeDef { type: "unknown"; } export interface $ZodUnknownInternals extends $ZodTypeInternals<unknown, unknown> { def: $ZodUnknownDef; isst: never; } export interface $ZodUnknown extends $ZodType { _zod: $ZodUnknownInternals; } export const $ZodUnknown: core.$constructor<$ZodUnknown> = /*@__PURE__*/ core.$constructor( "$ZodUnknown", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload) => payload; } ); ///////////////////////////////////////// ///////////////////////////////////////// ////////// ////////// ////////// $ZodNever ////////// ////////// ////////// ///////////////////////////////////////// ///////////////////////////////////////// export interface $ZodNeverDef extends $ZodTypeDef { type: "never"; } export interface $ZodNeverInternals extends $ZodTypeInternals<never, never> { def: $ZodNeverDef; isst: errors.$ZodIssueInvalidType; } export interface $ZodNever extends $ZodType { _zod: $ZodNeverInternals; } export const $ZodNever: core.$constructor<$ZodNever> = /*@__PURE__*/ core.$constructor("$ZodNever", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { payload.issues.push({ expected: "never", code: "invalid_type", input: payload.value, inst, }); return payload; }; }); //////////////////////////////////////// //////////////////////////////////////// ////////// ////////// ////////// $ZodVoid ////////// ////////// ////////// //////////////////////////////////////// //////////////////////////////////////// export interface $ZodVoidDef extends $ZodTypeDef { type: "void"; } export interface $ZodVoidInternals extends $ZodTypeInternals<void, void> { def: $ZodVoidDef; isst: errors.$ZodIssueInvalidType; } export interface $ZodVoid extends $ZodType { _zod: $ZodVoidInternals; } export const $ZodVoid: core.$constructor<$ZodVoid> = /*@__PURE__*/ core.$constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (typeof input === "undefined") return payload; payload.issues.push({ expected: "void", code: "invalid_type", input, inst, }); return payload; }; }); /////////////////////////////////////// /////////////////////////////////////// ////////// //////// ////////// $ZodDate //////// ////////// //////// /////////////////////////////////////// /////////////////////////////////////// export interface $ZodDateDef extends $ZodTypeDef { type: "date"; coerce?: boolean; } export interface $ZodDateInternals<T = unknown> extends $ZodTypeInternals<Date, T> { def: $ZodDateDef; isst: errors.$ZodIssueInvalidType; // | errors.$ZodIssueInvalidDate; bag: util.LoosePartial<{ minimum: Date; maximum: Date; format: string; }>; } export interface $ZodDate<T = unknown> extends $ZodType { _zod: $ZodDateInternals<T>; } export const $ZodDate: core.$constructor<$ZodDate> = /*@__PURE__*/ core.$constructor("$ZodDate", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { if (def.coerce) { try { payload.value = new Date(payload.value as string | number | Date); } catch (_err: any) {} } const input = payload.value; const isDate = input instanceof Date; const isValidDate = isDate && !Number.isNaN(input.getTime()); if (isValidDate) return payload; payload.issues.push({ expected: "date", code: "invalid_type", input, ...(isDate ? { received: "Invalid Date" } : {}), inst, }); return payload; }; }); ///////////////////////////////////////// ///////////////////////////////////////// ////////// ////////// ////////// $ZodArray ////////// ////////// ////////// ///////////////////////////////////////// ///////////////////////////////////////// export interface $ZodArrayDef<T extends SomeType = $ZodType> extends $ZodTypeDef { type: "array"; element: T; } export interface $ZodArrayInternals<T extends SomeType = $ZodType> extends _$ZodTypeInternals { //$ZodTypeInternals<core.output<T>[], core.input<T>[]> { def: $ZodArrayDef<T>; isst: errors.$ZodIssueInvalidType; output: core.output<T>[]; input: core.input<T>[]; } export interface $ZodArray<T extends SomeType = $ZodType> extends $ZodType<any, any, $ZodArrayInternals<T>> {} function handleArrayResult(result: ParsePayload<any>, final: ParsePayload<any[]>, index: number) { if (result.issues.length) { final.issues.push(...util.prefixIssues(index, result.issues)); } final.value[index] = result.value; } export const $ZodArray: core.$constructor<$ZodArray> = /*@__PURE__*/ core.$constructor("$ZodArray", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!Array.isArray(input)) { payload.issues.push({ expected: "array", code: "invalid_type", input, inst, }); return payload; } payload.value = Array(input.length); const proms: Promise<any>[] = []; for (let i = 0; i < input.length; i++) { const item = input[i]; const result = def.element._zod.run( { value: item, issues: [], }, ctx ); if (result instanceof Promise) { proms.push(result.then((result) => handleArrayResult(result, payload, i))); } else { handleArrayResult(result, payload, i); } } if (proms.length) { return Promise.all(proms).then(() => payload); } return payload; //handleArrayResultsAsync(parseResults, final); }; }); ////////////////////////////////////////// ////////////////////////////////////////// ////////// ////////// ////////// $ZodObject ////////// ////////// ////////// ////////////////////////////////////////// ////////////////////////////////////////// type OptionalOutSchema = { _zod: { optout: "optional" } }; type OptionalInSchema = { _zod: { optin: "optional" } }; export type $InferObjectOutput<T extends $ZodLooseShape, Extra extends Record<string, unknown>> = string extends keyof T ? util.IsAny<T[keyof T]> extends true ? Record<string, unknown> : Record<string, core.output<T[keyof T]>> : keyof (T & Extra) extends never ? Record<string, never> : util.Prettify< { -readonly [k in keyof T as T[k] extends OptionalOutSchema ? never : k]: T[k]["_zod"]["output"]; } & { -readonly [k in keyof T as T[k] extends OptionalOutSchema ? k : never]?: T[k]["_zod"]["output"]; } & Extra >; // experimental // export type $InferObjectOutput<T extends $ZodLooseShape, Extra extends Record<string, unknown>> = keyof (T & // Extra) extends never // ? Record<string, never> // : string extends keyof T // ? util.Prettify< // { // [k: string]: util.IsAny<T[string]["_zod"]["output"]> extends true ? unknown : T[string]["_zod"]["output"]; // } & $InferObjectOutputNoIndex<util.OmitIndexSignature<T>, Extra> // > // : util.Prettify<$InferObjectOutputNoIndex<T, Extra>>; // export type $InferObjectOutputNoIndex<T extends $ZodLooseShape, Extra extends Record<string, unknown>> = { // [k in keyof T as string extends k // ? never // : k extends string // ? T[k] extends OptionalOutSchema // ? never // : k // : never]: T[k]["_zod"]["output"]; // } & { // [k in keyof T as string extends k // ? never // : k extends string // ? T[k] extends OptionalOutSchema // ? k // : never // : never]?: T[k]["_zod"]["output"]; // } & Extra; export type $InferObjectInput<T extends $ZodLooseShape, Extra extends Record<string, unknown>> = string extends keyof T ? util.IsAny<T[keyof T]> extends true ? Record<string, unknown> : Record<string, core.input<T[keyof T]>> : keyof (T & Extra) extends never ? Record<string, never> : util.Prettify< { -readonly [k in keyof T as T[k] extends OptionalInSchema ? never : k]: T[k]["_zod"]["input"]; } & { -readonly [k in keyof T as T[k] extends OptionalInSchema ? k : never]?: T[k]["_zod"]["input"]; } & Extra >; function handlePropertyResult(result: ParsePayload, final: ParsePayload, key: PropertyKey, input: any) { if (result.issues.length) { final.issues.push(...util.prefixIssues(key, result.issues)); } if (result.value === undefined) { if (key in input) { (final.value as any)[key] = undefined; } } else { (final.value as any)[key] = result.value; } } export type $ZodObjectConfig = { out: Record<string, unknown>; in: Record<string, unknown> }; export type $loose = { out: Record<string, unknown>; in: Record<string, unknown>; }; export type $strict = { out: {}; in: {}; }; export type $strip = { out: {}; in: {}; }; export type $catchall<T extends SomeType> = { out: { [k: string]: core.output<T> }; in: { [k: string]: core.input<T> }; }; export type $ZodShape = Readonly<{ [k: string]: $ZodType }>; export interface $ZodObjectDef<Shape extends $ZodShape = $ZodShape> extends $ZodTypeDef { type: "object"; shape: Shape; catchall?: $ZodType | undefined; } export interface $ZodObjectInternals< /** @ts-ignore Cast variance */ out Shape extends Readonly<$ZodShape> = Readonly<$ZodShape>, out Config extends $ZodObjectConfig = $ZodObjectConfig, > extends _$ZodTypeInternals { def: $ZodObjectDef<Shape>; config: Config; isst: errors.$ZodIssueInvalidType | errors.$ZodIssueUnrecognizedKeys; propValues: util.PropValues; output: $InferObjectOutput<Shape, Config["out"]>; input: $InferObjectInput<Shape, Config["in"]>; optin?: "optional" | undefined; optout?: "optional" | undefined; } export type $ZodLooseShape = Record<string, any>