Skip to main content
Module

x/zod/types.ts

TypeScript-first schema validation with static type inference
Extremely Popular
Go to Latest
File
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071
import { errorUtil } from "./helpers/errorUtil.ts";import { ASYNC, getParsedType, INVALID, isAsync, isInvalid, isOk, makeIssue, OK, ParseContext, ParseParamsNoData, ParseReturnType, pathFromArray, pathToArray, SyncParseReturnType, ZodParsedType,} from "./helpers/parseUtil.ts";import { partialUtil } from "./helpers/partialUtil.ts";import { util } from "./helpers/util.ts";import { PseudoPromise } from "./PseudoPromise.ts";import { MakeErrorData, overrideErrorMap, StringValidation, ZodCustomIssue, ZodError, ZodIssue, ZodIssueCode,} from "./ZodError.ts";
//////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodType //////////////////// ////////////////////////////////////////////////////////////////////////////////////////
export type RefinementCtx = { addIssue: (arg: MakeErrorData) => void; path: (string | number)[]; issueFound: boolean;};export type ZodRawShape = { [k: string]: ZodTypeAny };export type ZodTypeAny = ZodType<any, any, any>;export type TypeOf<T extends ZodType<any>> = T["_output"];export type input<T extends ZodType<any>> = T["_input"];export type output<T extends ZodType<any>> = T["_output"];export type { TypeOf as infer };
export type CustomErrorParams = Partial<util.Omit<ZodCustomIssue, "code">>;export interface ZodTypeDef {}
type AsyncTasks = Promise<void>[] | null;const createTasks = (ctx: ParseContext): AsyncTasks => ctx.params.async ? [] : null;
const createRootContext = (params: Partial<ParseParamsNoData>): ParseContext => new ParseContext(pathFromArray(params.path || []), [], { async: params.async ?? false, errorMap: params.errorMap || overrideErrorMap, });
const handleResult = <Input, Output>( ctx: ParseContext, result: SyncParseReturnType<Output>, parentError: ZodError | undefined): | { success: true; data: Output } | { success: false; error: ZodError<Input> } => { if (isOk(result)) { return { success: true, data: result.value }; } else { parentError?.addIssues(ctx.issues); const error = new ZodError(ctx.issues); return { success: false, error }; }};
export abstract class ZodType< Output, Def extends ZodTypeDef = ZodTypeDef, Input = Output> { readonly _type!: Output; readonly _output!: Output; readonly _input!: Input; readonly _def!: Def;
abstract _parse( _ctx: ParseContext, _data: any, _parsedType: ZodParsedType ): ParseReturnType<Output>;
_parseSync( _ctx: ParseContext, _data: any, _parsedType: ZodParsedType ): SyncParseReturnType<Output> { const result = this._parse(_ctx, _data, _parsedType); if (isAsync(result)) { throw new Error("Synchronous parse encountered promise."); } return result; }
parse: (data: unknown, params?: Partial<ParseParamsNoData>) => Output = ( data, params ) => { const result = this.safeParse(data, params); if (result.success) return result.data; throw result.error; };
safeParse: ( data: unknown, params?: Partial<ParseParamsNoData> ) => | { success: true; data: Output } | { success: false; error: ZodError<Input> } = (data, params) => { const ctx = createRootContext({ ...params, async: false }); const result = this._parseSync(ctx, data, getParsedType(data)); return handleResult(ctx, result, params?.parentError); };
parseAsync: ( x: unknown, params?: Partial<ParseParamsNoData> ) => Promise<Output> = async (data, params) => { const result = await this.safeParseAsync(data, params); if (result.success) return result.data; throw result.error; };
safeParseAsync: ( x: unknown, params?: Partial<ParseParamsNoData> ) => Promise< { success: true; data: Output } | { success: false; error: ZodError } > = async (data, params) => { const ctx = createRootContext({ ...params, async: true }); const maybeAsyncResult = this._parse(ctx, data, getParsedType(data)); const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult.promise : Promise.resolve(maybeAsyncResult)); return handleResult(ctx, result, params?.parentError); };
/** Alias of safeParseAsync */ spa = this.safeParseAsync;
/** The .is method has been removed in Zod 3. For details see https://github.com/colinhacks/zod/tree/v3. */ is: never;
/** The .check method has been removed in Zod 3. For details see https://github.com/colinhacks/zod/tree/v3. */ check: never;
refine: <Func extends (arg: Output) => any, This extends this = this>( check: Func, message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams) ) => ZodEffectsType<This> = (check, message) => { const getIssueProperties: any = (val: Output) => { if (typeof message === "string" || typeof message === "undefined") { return { message }; } else if (typeof message === "function") { return message(val); } else { return message; } }; return this._refinement((val, ctx) => { const result = check(val); const setError = () => ctx.addIssue({ code: ZodIssueCode.custom, ...getIssueProperties(val), }); if (result instanceof Promise) { return result.then((data) => { if (!data) { setError(); return false; } else { return true; } }); } if (!result) { setError(); return false; } else { return true; } }); };
refinement: <This extends this = this>( check: (arg: Output) => any, refinementData: | MakeErrorData | ((arg: Output, ctx: RefinementCtx) => MakeErrorData) ) => ZodEffectsType<This> = (check, refinementData) => { return this._refinement((val, ctx) => { if (!check(val)) { ctx.addIssue( typeof refinementData === "function" ? refinementData(val, ctx) : refinementData ); return false; } else { return true; } }); };
_refinement<This extends this>( refinement: InternalCheck<Output>["refinement"] ): ZodEffectsType<This> { let returnType; if (this instanceof ZodEffects) { returnType = new ZodEffects({ ...this._def, effects: [ ...(this._def.effects || []), { type: "refinement", refinement }, ], }) as any; } else { returnType = new ZodEffects({ schema: this, effects: [{ type: "refinement", refinement }], }) as any; } return returnType; } superRefine = this._refinement;
constructor(def: Def) { this._def = def; this.transform = this.transform.bind(this) as any; this.default = this.default.bind(this); }
optional: <This extends this = this>() => ZodOptional<This> = () => ZodOptional.create(this) as any; nullable: <This extends this = this>() => ZodNullable<This> = () => ZodNullable.create(this) as any; nullish: <This extends this = this>() => ZodNullable< ZodOptional<This> > = () => this.optional().nullable();
array: () => ZodArray<this> = () => ZodArray.create(this);
or<T extends ZodTypeAny>(option: T): ZodUnion<[this, T]> { return ZodUnion.create([this, option]) as any; }
and<T extends ZodTypeAny>(incoming: T): ZodIntersection<this, T> { return ZodIntersection.create(this, incoming); }
transform<NewOut>( transform: (arg: Output) => NewOut | Promise<NewOut> ): ZodEffects<this, NewOut> { return new ZodEffects({ schema: this, effects: [{ type: "transform", transform }], }) as any; }
default<This extends this = this>( def: util.noUndefined<Input> ): ZodDefault<This>; default<This extends this = this>( def: () => util.noUndefined<Input> ): ZodDefault<This>; default(def: any) { const defaultValueFunc = typeof def === "function" ? def : () => def; // if (this instanceof ZodOptional) { // return new ZodOptional({ // ...this._def, // defaultValue: defaultValueFunc, // }) as any; // } return new ZodDefault({ innerType: this, defaultValue: defaultValueFunc, }) as any; }
isOptional: () => boolean = () => this.safeParse(undefined).success; isNullable: () => boolean = () => this.safeParse(null).success;}
//////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodString //////////////////// ////////////////////////////////////////////////////////////////////////////////////////////type ZodStringCheck = | { kind: "min"; value: number; message?: string } | { kind: "max"; value: number; message?: string } | { kind: "email"; message?: string } | { kind: "url"; message?: string } | { kind: "uuid"; message?: string } | { kind: "regex"; regex: RegExp; message?: string };
export interface ZodStringDef extends ZodTypeDef { checks: ZodStringCheck[];}
const uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;// from https://stackoverflow.com/a/46181/1550155// old version: too slow, didn't support unicode// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;// eslint-disable-next-lineconst emailRegex = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
export class ZodString extends ZodType<string, ZodStringDef> { _parse( ctx: ParseContext, data: string, parsedType: ZodParsedType ): ParseReturnType<string> { if (parsedType !== ZodParsedType.string) { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.string, received: parsedType, }); return INVALID; } let invalid = false;
for (const check of this._def.checks) { if (check.kind === "min") { if (data.length < check.value) { invalid = true; ctx.addIssue(data, { code: ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, message: check.message, }); } } else if (check.kind === "max") { if (data.length > check.value) { invalid = true; ctx.addIssue(data, { code: ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, message: check.message, // ...errorUtil.errToObj(this._def.maxLength.message), }); } } else if (check.kind === "email") { if (!emailRegex.test(data)) { invalid = true; ctx.addIssue(data, { validation: "email", code: ZodIssueCode.invalid_string, message: check.message, }); } } else if (check.kind === "uuid") { if (!uuidRegex.test(data)) { invalid = true; ctx.addIssue(data, { validation: "uuid", code: ZodIssueCode.invalid_string, message: check.message, }); } } else if (check.kind === "url") { try { new URL(data); } catch { invalid = true; ctx.addIssue(data, { validation: "url", code: ZodIssueCode.invalid_string, message: check.message, }); } } else if (check.kind === "regex") { if (!check.regex.test(data)) { invalid = true; ctx.addIssue(data, { validation: "regex", code: ZodIssueCode.invalid_string, message: check.message, }); } } }
return invalid ? INVALID : OK(data); }
protected _regex = ( regex: RegExp, validation: StringValidation, message?: errorUtil.ErrMessage ) => this.refinement((data) => regex.test(data), { validation, code: ZodIssueCode.invalid_string, ...errorUtil.errToObj(message), });
email = (message?: errorUtil.ErrMessage) => new ZodString({ ...this._def, checks: [ ...this._def.checks, { kind: "email", ...errorUtil.errToObj(message) }, ], });
url = (message?: errorUtil.ErrMessage) => new ZodString({ ...this._def, checks: [ ...this._def.checks, { kind: "url", ...errorUtil.errToObj(message) }, ], });
uuid = (message?: errorUtil.ErrMessage) => new ZodString({ ...this._def, checks: [ ...this._def.checks, { kind: "uuid", ...errorUtil.errToObj(message) }, ], });
regex = (regex: RegExp, message?: errorUtil.ErrMessage) => new ZodString({ ...this._def, checks: [ ...this._def.checks, { kind: "regex", regex: regex, ...errorUtil.errToObj(message) }, ], });
min = (minLength: number, message?: errorUtil.ErrMessage) => new ZodString({ ...this._def, checks: [ ...this._def.checks, { kind: "min", value: minLength, ...errorUtil.errToObj(message) }, ], });
max = (maxLength: number, message?: errorUtil.ErrMessage) => new ZodString({ ...this._def, checks: [ ...this._def.checks, { kind: "max", value: maxLength, ...errorUtil.errToObj(message) }, ], });
length(len: number, message?: errorUtil.ErrMessage) { return this.min(len, message).max(len, message); }
/** * Deprecated. * Use z.string().min(1) instead. */ nonempty = (message?: errorUtil.ErrMessage) => this.min(1, errorUtil.errToObj(message));
get isEmail() { return !!this._def.checks.find((ch) => ch.kind === "email"); } get isURL() { return !!this._def.checks.find((ch) => ch.kind === "url"); } get isUUID() { return !!this._def.checks.find((ch) => ch.kind === "uuid"); } get minLength() { let min: number | null = -Infinity; this._def.checks.map((ch) => { if (ch.kind === "min") { if (min === null || ch.value > min) { min = ch.value; } } }); return min; } get maxLength() { let max: number | null = null; this._def.checks.map((ch) => { if (ch.kind === "min") { if (max === null || ch.value < max) { max = ch.value; } } }); return max; } static create = (): ZodString => { return new ZodString({ checks: [], }); };}
//////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodNumber //////////////////// ////////////////////////////////////////////////////////////////////////////////////////////type ZodNumberCheck = | { kind: "min"; value: number; inclusive: boolean; message?: string } | { kind: "max"; value: number; inclusive: boolean; message?: string } | { kind: "int"; message?: string };
export interface ZodNumberDef extends ZodTypeDef { checks: ZodNumberCheck[];}
export class ZodNumber extends ZodType<number, ZodNumberDef> { _parse( ctx: ParseContext, data: number, parsedType: ZodParsedType ): ParseReturnType<number> { if (parsedType !== ZodParsedType.number) { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.number, received: parsedType, });
return INVALID; }
let invalid = false;
for (const check of this._def.checks) { if (check.kind === "int") { if (!Number.isInteger(data)) { invalid = true; ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: "integer", received: "float", message: check.message, }); } } else if (check.kind === "min") { // const MIN = check.value; const tooSmall = check.inclusive ? data < check.value : data <= check.value; if (tooSmall) { invalid = true; ctx.addIssue(data, { code: ZodIssueCode.too_small, minimum: check.value, type: "number", inclusive: check.inclusive, message: check.message, }); } } else if (check.kind === "max") { const tooBig = check.inclusive ? data > check.value : data >= check.value; if (tooBig) { invalid = true; ctx.addIssue(data, { code: ZodIssueCode.too_big, maximum: check.value, type: "number", inclusive: check.inclusive, message: check.message, }); } } }
return invalid ? INVALID : OK(data); }
static create = (): ZodNumber => { return new ZodNumber({ checks: [], }); };
min = (value: number, message?: errorUtil.ErrMessage) => new ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind: "min", value: value, inclusive: true, message: errorUtil.toString(message), }, ], });
max = (value: number, message?: errorUtil.ErrMessage) => new ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind: "max", value: value, inclusive: true, message: errorUtil.toString(message), }, ], });
int = (message?: errorUtil.ErrMessage) => new ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind: "int", message: errorUtil.toString(message), }, ], });
positive = (message?: errorUtil.ErrMessage) => new ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind: "min", value: 0, inclusive: false, message: errorUtil.toString(message), }, ], });
negative = (message?: errorUtil.ErrMessage) => new ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind: "max", value: 0, inclusive: false, message: errorUtil.toString(message), }, ], });
nonpositive = (message?: errorUtil.ErrMessage) => new ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind: "max", value: 0, inclusive: true, message: errorUtil.toString(message), }, ], });
nonnegative = (message?: errorUtil.ErrMessage) => new ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind: "min", value: 0, inclusive: true, message: errorUtil.toString(message), }, ], });
get minValue() { let min: number | null = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; }
get maxValue() { let max: number | null = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; }
get isInt() { return !!this._def.checks.find((ch) => ch.kind === "int"); }}
//////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodBigInt //////////////////// ////////////////////////////////////////////////////////////////////////////////////////////
export type ZodBigIntDef = ZodTypeDef;
export class ZodBigInt extends ZodType<bigint, ZodBigIntDef> { _parse( ctx: ParseContext, data: bigint, parsedType: ZodParsedType ): ParseReturnType<bigint> { if (parsedType !== ZodParsedType.bigint) { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.bigint, received: parsedType, });
return INVALID; } return OK(data); }
static create = (): ZodBigInt => { return new ZodBigInt({}); };}
////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////// ZodBoolean //////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////export type ZodBooleanDef = ZodTypeDef;
export class ZodBoolean extends ZodType<boolean, ZodBooleanDef> { _parse( ctx: ParseContext, data: boolean, parsedType: ZodParsedType ): ParseReturnType<boolean> { if (parsedType !== ZodParsedType.boolean) { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.boolean, received: parsedType, });
return INVALID; } return OK(data); }
static create = (): ZodBoolean => { return new ZodBoolean({}); };}
//////////////////////////////////////////////////////////////////////////////////////// ////////////////// ZodDate ////////////////// //////////////////////////////////////////////////////////////////////////////////////export type ZodDateDef = ZodTypeDef;
export class ZodDate extends ZodType<Date, ZodDateDef> { _parse( ctx: ParseContext, data: Date, parsedType: ZodParsedType ): ParseReturnType<Date> { if (parsedType !== ZodParsedType.date) { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.date, received: parsedType, });
return INVALID; } if (isNaN(data.getTime())) { ctx.addIssue(data, { code: ZodIssueCode.invalid_date, });
return INVALID; }
return OK(new Date((data as Date).getTime())); }
static create = (): ZodDate => { return new ZodDate({}); };}
////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodUndefined //////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////export type ZodUndefinedDef = ZodTypeDef;
export class ZodUndefined extends ZodType<undefined> { _parse( ctx: ParseContext, data: undefined, parsedType: ZodParsedType ): ParseReturnType<undefined> { if (parsedType !== ZodParsedType.undefined) { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.undefined, received: parsedType, });
return INVALID; } return OK(data); }
static create = (): ZodUndefined => { return new ZodUndefined({}); };}
//////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodNull //////////////////// ////////////////////////////////////////////////////////////////////////////////////////export type ZodNullDef = ZodTypeDef;
export class ZodNull extends ZodType<null, ZodNullDef> { _parse( ctx: ParseContext, data: null, parsedType: ZodParsedType ): ParseReturnType<null> { if (parsedType !== ZodParsedType.null) { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.null, received: parsedType, });
return INVALID; } return OK(data); } static create = (): ZodNull => { return new ZodNull({}); };}
////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodAny //////////////////// //////////////////////////////////////////////////////////////////////////////////////export type ZodAnyDef = ZodTypeDef;
export class ZodAny extends ZodType<any, ZodAnyDef> { // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. _any: true = true; _parse( _ctx: ParseContext, data: any, _parsedType: ZodParsedType ): ParseReturnType<any> { return OK(data); } static create = (): ZodAny => { return new ZodAny({}); };}
////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodUnknown //////////////////// //////////////////////////////////////////////////////////////////////////////////////////////export type ZodUnknownDef = ZodTypeDef;
export class ZodUnknown extends ZodType<unknown, ZodUnknownDef> { // required _unknown: true = true; _parse( _ctx: ParseContext, data: any, _parsedType: ZodParsedType ): ParseReturnType<unknown> { return OK(data); }
static create = (): ZodUnknown => { return new ZodUnknown({}); };}
////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodNever //////////////////// //////////////////////////////////////////////////////////////////////////////////////////export type ZodNeverDef = ZodTypeDef;
export class ZodNever extends ZodType<never, ZodNeverDef> { _parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<never> { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.never, received: parsedType, }); return INVALID; } static create = (): ZodNever => { return new ZodNever({}); };}
//////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodVoid //////////////////// ////////////////////////////////////////////////////////////////////////////////////////export type ZodVoidDef = ZodTypeDef;
export class ZodVoid extends ZodType<void, ZodVoidDef> { _parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<void> { if ( parsedType !== ZodParsedType.undefined && parsedType !== ZodParsedType.null ) { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.void, received: parsedType, });
return INVALID; } return OK(data); }
static create = (): ZodVoid => { return new ZodVoid({}); };}
////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodArray //////////////////// //////////////////////////////////////////////////////////////////////////////////////////export interface ZodArrayDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { type: T; minLength: { value: number; message?: string } | null; maxLength: { value: number; message?: string } | null;}
const parseArray = <T>( ctx: ParseContext, data: any[], parsedType: ZodParsedType, def: ZodArrayDef<any>, nonEmpty: boolean): ParseReturnType<T[]> => { if (parsedType !== ZodParsedType.array) { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: parsedType, });
return INVALID; }
let invalid = false; if (def.minLength !== null) { if (data.length < def.minLength.value) { invalid = true; ctx.addIssue(data, { code: ZodIssueCode.too_small, minimum: def.minLength.value, type: "array", inclusive: true, message: def.minLength.message, }); } }
if (def.maxLength !== null) { if (data.length > def.maxLength.value) { invalid = true; ctx.addIssue(data, { code: ZodIssueCode.too_big, maximum: def.maxLength.value, type: "array", inclusive: true, message: def.maxLength.message, }); } }
if (nonEmpty && data.length < 1) { invalid = true; ctx.addIssue(data, { code: ZodIssueCode.too_small, minimum: 1, type: "array", inclusive: true, // message: this._def.minLength.message, // ...errorUtil.errToObj(this._def.minLength.message), }); }
if (invalid) { return INVALID; }
const tasks = createTasks(ctx); const result: T[] = new Array(data.length); const type = def.type; const handleParsed = ( index: number, parsedItem: ParseReturnType<T> ): void => { if (isOk(parsedItem)) { result[index] = parsedItem.value; } else if (isInvalid(parsedItem)) { invalid = true; } else { tasks?.push( parsedItem.promise.then((parsed) => handleParsed(index, parsed)) ); } };
data.forEach((item, index) => { handleParsed( index, type._parse(ctx.stepInto(index), item, getParsedType(item)) ); });
if (tasks !== null && tasks.length > 0) { return ASYNC( Promise.all(tasks).then(() => (invalid ? INVALID : OK(result))) ); } else { return invalid ? INVALID : OK(result); }};
export class ZodArray<T extends ZodTypeAny> extends ZodType< T["_output"][], ZodArrayDef<T>, T["_input"][]> { _parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<T["_output"][]> { const nonEmpty = false; return parseArray(ctx, data, parsedType, this._def, nonEmpty); }
get element() { return this._def.type; }
min = (minLength: number, message?: errorUtil.ErrMessage): this => new ZodArray({ ...this._def, minLength: { value: minLength, message: errorUtil.toString(message) }, }) as any;
max = (maxLength: number, message?: errorUtil.ErrMessage): this => new ZodArray({ ...this._def, maxLength: { value: maxLength, message: errorUtil.toString(message) }, }) as any;
length = (len: number, message?: errorUtil.ErrMessage): this => this.min(len, message).max(len, message) as any;
nonempty: () => ZodNonEmptyArray<T> = () => { return new ZodNonEmptyArray({ ...this._def }); };
static create = <T extends ZodTypeAny>(schema: T): ZodArray<T> => { return new ZodArray({ type: schema, minLength: null, maxLength: null, }); };}
////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodNonEmptyArray //////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////export interface ZodNonEmptyArrayDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { type: T; minLength: { value: number; message?: string } | null; maxLength: { value: number; message?: string } | null;}
export class ZodNonEmptyArray<T extends ZodTypeAny> extends ZodType< [T["_output"], ...T["_output"][]], ZodNonEmptyArrayDef<T>, [T["_input"], ...T["_input"][]]> { _parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<[T["_output"], ...T["_output"][]]> { const nonEmpty = true; return parseArray( ctx, data, parsedType, this._def, nonEmpty ) as ParseReturnType<[T["_output"], ...T["_output"][]]>; }
min = (minLength: number, message?: errorUtil.ErrMessage) => new ZodNonEmptyArray({ ...this._def, minLength: { value: minLength, message: errorUtil.toString(message) }, });
max = (maxLength: number, message?: errorUtil.ErrMessage) => new ZodNonEmptyArray({ ...this._def, maxLength: { value: maxLength, message: errorUtil.toString(message) }, });
length = (len: number, message?: errorUtil.ErrMessage) => this.min(len, message).max(len, message);
static create = <T extends ZodTypeAny>(schema: T): ZodNonEmptyArray<T> => { return new ZodNonEmptyArray({ type: schema, minLength: null, maxLength: null, }); };}
//////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodObject //////////////////// ////////////////////////////////////////////////////////////////////////////////////////////
export namespace objectUtil { export type MergeShapes<U extends ZodRawShape, V extends ZodRawShape> = { [k in Exclude<keyof U, keyof V>]: U[k]; } & V;
type optionalKeys<T extends object> = { [k in keyof T]: undefined extends T[k] ? k : never; }[keyof T];
type requiredKeys<T extends object> = Exclude<keyof T, optionalKeys<T>>;
export type addQuestionMarks<T extends object> = { [k in optionalKeys<T>]?: T[k]; } & { [k in requiredKeys<T>]: T[k] };
export type identity<T> = T; export type flatten<T extends object> = identity<{ [k in keyof T]: T[k] }>;
export type noNeverKeys<T extends ZodRawShape> = { [k in keyof T]: [T[k]] extends [never] ? never : k; }[keyof T];
export type noNever<T extends ZodRawShape> = identity< { [k in noNeverKeys<T>]: k extends keyof T ? T[k] : never; } >;
export const mergeShapes = <U extends ZodRawShape, T extends ZodRawShape>( first: U, second: T ): T & U => { return { ...first, ...second, // second overwrites first }; };
export const intersectShapes = <U extends ZodRawShape, T extends ZodRawShape>( first: U, second: T ): T & U => { const firstKeys = Object.keys(first); const secondKeys = Object.keys(second); const sharedKeys = firstKeys.filter((k) => secondKeys.indexOf(k) !== -1);
const sharedShape: any = {}; for (const k of sharedKeys) { sharedShape[k] = ZodIntersection.create(first[k], second[k]); } return { ...(first as object), ...(second as object), ...sharedShape, }; };}export const mergeObjects = <First extends AnyZodObject>(first: First) => < Second extends AnyZodObject>( second: Second): ZodObject< First["_shape"] & Second["_shape"], First["_unknownKeys"], First["_catchall"]> => { const mergedShape = objectUtil.mergeShapes( first._def.shape(), second._def.shape() ); const merged: any = new ZodObject({ // effects: [...(first._def.effects || []), ...(second._def.effects || [])], unknownKeys: first._def.unknownKeys, catchall: first._def.catchall, shape: () => mergedShape, }) as any; return merged;};
type extend<A, B> = { [k in Exclude<keyof A, keyof B>]: A[k];} & { [k in keyof B]: B[k] };
const AugmentFactory = <Def extends ZodObjectDef>(def: Def) => < Augmentation extends ZodRawShape>( augmentation: Augmentation): ZodObject< extend<ReturnType<Def["shape"]>, Augmentation>, // { // [k in Exclude< // keyof ReturnType<Def["shape"]>, // keyof Augmentation // >]: ReturnType<Def["shape"]>[k]; // } & // { [k in keyof Augmentation]: Augmentation[k] }, Def["unknownKeys"], Def["catchall"]> => { return new ZodObject({ ...def, shape: () => ({ ...def.shape(), ...augmentation, }), }) as any;};
type UnknownKeysParam = "passthrough" | "strict" | "strip";
export type Primitive = string | number | bigint | boolean | null | undefined;export type Scalars = Primitive | Primitive[];
export interface ZodObjectDef< T extends ZodRawShape = ZodRawShape, UnknownKeys extends UnknownKeysParam = UnknownKeysParam, Catchall extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { shape: () => T; catchall: Catchall; unknownKeys: UnknownKeys;}
export type baseObjectOutputType< Shape extends ZodRawShape> = objectUtil.flatten< objectUtil.addQuestionMarks< { [k in keyof Shape]: Shape[k]["_output"]; } >>;
export type objectOutputType< Shape extends ZodRawShape, Catchall extends ZodTypeAny> = ZodTypeAny extends Catchall ? baseObjectOutputType<Shape> : objectUtil.flatten< baseObjectOutputType<Shape> & { [k: string]: Catchall["_output"] } >;
export type baseObjectInputType<Shape extends ZodRawShape> = objectUtil.flatten< objectUtil.addQuestionMarks< { [k in keyof Shape]: Shape[k]["_input"]; } >>;
export type objectInputType< Shape extends ZodRawShape, Catchall extends ZodTypeAny> = ZodTypeAny extends Catchall ? baseObjectInputType<Shape> : objectUtil.flatten< baseObjectInputType<Shape> & { [k: string]: Catchall["_input"] } >;
type deoptional<T extends ZodTypeAny> = T extends ZodOptional<infer U> ? deoptional<U> : T;
export class ZodObject< T extends ZodRawShape, UnknownKeys extends UnknownKeysParam = "strip", Catchall extends ZodTypeAny = ZodTypeAny, Output = objectOutputType<T, Catchall>, Input = objectInputType<T, Catchall>> extends ZodType<Output, ZodObjectDef<T, UnknownKeys, Catchall>, Input> { readonly _shape!: T; readonly _unknownKeys!: UnknownKeys; readonly _catchall!: Catchall; private _cached: { shape: T; keys: string[] } | null = null;
_getCached(): { shape: T; keys: string[] } { if (this._cached !== null) return this._cached; const shape = this._def.shape(); const keys = Object.keys(shape); return (this._cached = { shape, keys }); }
_parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<Output> { if (parsedType !== ZodParsedType.object) { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: parsedType, });
return INVALID; }
const { shape, keys: shapeKeys } = this._getCached();
let invalid = false; const tasks = createTasks(ctx); const resultObject: Record<string, any> = {};
const handleParsed = ( key: string, parsedValue: ParseReturnType<any> ): void => { if (isOk(parsedValue)) { const value = parsedValue.value; if (typeof value !== "undefined" || key in data) { // key was valid but result was undefined: add it to the result object // only if key was in the input data object - if it wasn't, then it's // an optional key that should not be added resultObject[key] = value; } } else if (isInvalid(parsedValue)) { invalid = true; } else { tasks?.push( parsedValue.promise.then((parsed) => handleParsed(key, parsed)) ); } };
for (const key of shapeKeys) { const keyValidator = shape[key]; const value = data[key]; handleParsed( key, keyValidator._parse(ctx.stepInto(key), value, getParsedType(value)) ); }
if (this._def.catchall instanceof ZodNever) { const unknownKeys = this._def.unknownKeys;
if (unknownKeys === "passthrough") { const dataKeys = Object.keys(data); const extraKeys = dataKeys.filter((k) => !(k in shape)); for (const key of extraKeys) { resultObject[key] = data[key]; } } else if (unknownKeys === "strict") { const dataKeys = Object.keys(data); const extraKeys = dataKeys.filter((k) => !(k in shape)); if (extraKeys.length > 0) { invalid = true; ctx.addIssue(data, { code: ZodIssueCode.unrecognized_keys, keys: extraKeys, }); } } else if (unknownKeys === "strip") { } else { throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } } else { // run catchall validation const catchall = this._def.catchall; const dataKeys = Object.keys(data); const extraKeys = dataKeys.filter((k) => !(k in shape)); for (const key of extraKeys) { const value = data[key]; handleParsed( key, catchall._parse(ctx.stepInto(key), value, getParsedType(value)) ); } }
if (tasks !== null && tasks.length > 0) { return ASYNC( Promise.all(tasks).then(() => invalid ? INVALID : OK(resultObject as Output) ) ); } else { return invalid ? INVALID : OK(resultObject as Output); } }
get shape() { return this._def.shape(); }
strict = (): ZodObject<T, "strict", Catchall> => new ZodObject({ ...this._def, unknownKeys: "strict", }) as any;
strip = (): ZodObject<T, "strip", Catchall> => new ZodObject({ ...this._def, unknownKeys: "strip", }) as any;
passthrough = (): ZodObject<T, "passthrough", Catchall> => new ZodObject({ ...this._def, unknownKeys: "passthrough", }) as any;
/** * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. * If you want to pass through unknown properies, use `.passthrough()` instead. */ nonstrict = this.passthrough;
augment = AugmentFactory<ZodObjectDef<T, UnknownKeys, Catchall>>(this._def); extend = AugmentFactory<ZodObjectDef<T, UnknownKeys, Catchall>>(this._def);
setKey = <Key extends string, Schema extends ZodTypeAny>( key: Key, schema: Schema ): ZodObject<T & { [k in Key]: Schema }, UnknownKeys, Catchall> => { return this.augment({ [key]: schema }) as any; };
/** * Prior to zod@1.0.12 there was a bug in the * inferred type of merged objects. Please * upgrade if you are experiencing issues. */ merge: <Incoming extends AnyZodObject>( merging: Incoming ) => //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => { ZodObject<extend<T, Incoming["_shape"]>, UnknownKeys, Catchall> = ( merging ) => { const mergedShape = objectUtil.mergeShapes( this._def.shape(), merging._def.shape() ); const merged: any = new ZodObject({ // effects: [], // wipe all refinements unknownKeys: merging._def.unknownKeys, catchall: merging._def.catchall, shape: () => mergedShape, }) as any; return merged; };
catchall = <Index extends ZodTypeAny>( index: Index ): ZodObject<T, UnknownKeys, Index> => { return new ZodObject({ ...this._def, catchall: index, }) as any; };
pick = <Mask extends { [k in keyof T]?: true }>( mask: Mask ): ZodObject< objectUtil.noNever<{ [k in keyof Mask]: k extends keyof T ? T[k] : never }>, UnknownKeys, Catchall > => { const shape: any = {}; Object.keys(mask).map((key) => { shape[key] = this.shape[key]; }); return new ZodObject({ ...this._def, shape: () => shape, }) as any; };
omit = <Mask extends { [k in keyof T]?: true }>( mask: Mask ): ZodObject< objectUtil.noNever<{ [k in keyof T]: k extends keyof Mask ? never : T[k] }>, UnknownKeys, Catchall > => { const shape: any = {}; Object.keys(this.shape).map((key) => { if (Object.keys(mask).indexOf(key) === -1) { shape[key] = this.shape[key]; } }); return new ZodObject({ ...this._def, shape: () => shape, }) as any; };
partial = (): ZodObject< { [k in keyof T]: ReturnType<T[k]["optional"]> }, UnknownKeys, Catchall > => { const newShape: any = {}; for (const key in this.shape) { const fieldSchema = this.shape[key]; newShape[key] = fieldSchema.isOptional() ? fieldSchema : fieldSchema.optional(); } return new ZodObject({ ...this._def, shape: () => newShape, }) as any; };
deepPartial: () => partialUtil.RootDeepPartial<this> = () => { const newShape: any = {};
for (const key in this.shape) { const fieldSchema = this.shape[key]; if (fieldSchema instanceof ZodObject) { newShape[key] = fieldSchema.isOptional() ? fieldSchema : (fieldSchema.deepPartial() as any).optional(); } else { newShape[key] = fieldSchema.isOptional() ? fieldSchema : fieldSchema.optional(); } } return new ZodObject({ ...this._def, shape: () => newShape, }) as any; };
required = (): ZodObject< { [k in keyof T]: deoptional<T[k]> }, UnknownKeys, Catchall > => { const newShape: any = {}; for (const key in this.shape) { const fieldSchema = this.shape[key]; let newField = fieldSchema; while (newField instanceof ZodOptional) { newField = (newField as ZodOptional<any>)._def.innerType; }
newShape[key] = newField; } return new ZodObject({ ...this._def, shape: () => newShape, }) as any; };
static create = <T extends ZodRawShape>(shape: T): ZodObject<T> => { return new ZodObject({ shape: () => shape, unknownKeys: "strip", catchall: ZodNever.create(), }) as any; };
static strictCreate = <T extends ZodRawShape>( shape: T ): ZodObject<T, "strict"> => { return new ZodObject({ shape: () => shape, unknownKeys: "strict", catchall: ZodNever.create(), }) as any; };
static lazycreate = <T extends ZodRawShape>(shape: () => T): ZodObject<T> => { return new ZodObject({ shape, unknownKeys: "strip", catchall: ZodNever.create(), }) as any; };}
export type AnyZodObject = ZodObject<any, any, any>;
////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodUnion //////////////////// //////////////////////////////////////////////////////////////////////////////////////////type ZodUnionOptions = [ZodTypeAny, ...ZodTypeAny[]];export interface ZodUnionDef< T extends ZodUnionOptions = [ZodTypeAny, ZodTypeAny, ...ZodTypeAny[]]> extends ZodTypeDef { options: T;}
// export type toOpts<T> = T extends ZodUnionOptions ? T : never;// export type ZodUnionType<// A extends ZodTypeAny,// B extends ZodTypeAny// > = A extends ZodUnion<infer AOpts>// ? B extends ZodUnion<infer BOpts>// ? ZodUnion<toOpts<[...AOpts, ...BOpts]>>// : ZodUnion<toOpts<[...AOpts, B]>>// : B extends ZodUnion<infer BOpts>// ? ZodUnion<toOpts<[A, ...BOpts]>>// : ZodUnion<toOpts<[A, B]>>;
export class ZodUnion<T extends ZodUnionOptions> extends ZodType< T[number]["_output"], ZodUnionDef<T>, T[number]["_input"]> { _parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<T[number]["_output"]> { const options = this._def.options; const noMatch = (allIssues: ZodIssue[][]) => { const unionErrors = allIssues.map((issues) => new ZodError(issues)); const nonTypeErrors = unionErrors.filter((err) => { return err.issues[0].code !== "invalid_type"; }); if (nonTypeErrors.length === 1) { // TODO encapsulate nonTypeErrors[0].issues.forEach((issue) => ctx.issues.push(issue)); } else { ctx.addIssue(data, { code: ZodIssueCode.invalid_union, unionErrors, }); } return INVALID; };
if (ctx.params.async) { const contexts = options.map( () => new ParseContext(ctx.path, [], ctx.params) ); return PseudoPromise.all( options.map((option, index) => option._parse(contexts[index], data, parsedType) ) ).then((parsedOptions) => { for (const parsedOption of parsedOptions) { if (isOk(parsedOption)) { return parsedOption; } } return noMatch(contexts.map((ctx) => ctx.issues)); }); } else { const allIssues: ZodIssue[][] = []; for (const option of options) { const optionCtx = new ParseContext(ctx.path, [], ctx.params); const parsedOption = option._parseSync(optionCtx, data, parsedType); if (isInvalid(parsedOption)) { allIssues.push(optionCtx.issues); } else { return parsedOption; } } return noMatch(allIssues); } }
get options() { return this._def.options; }
static create = <T extends [ZodTypeAny, ZodTypeAny, ...ZodTypeAny[]]>( types: T ): ZodUnion<T> => { return new ZodUnion({ options: types, }); };}
//////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodIntersection //////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////export interface ZodIntersectionDef< T extends ZodTypeAny = ZodTypeAny, U extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { left: T; right: U;}
function mergeValues( a: any, b: any): { valid: true; data: any } | { valid: false } { const aType = getParsedType(a); const bType = getParsedType(b);
if (a === b) { return { valid: true, data: a }; } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { const bKeysSet = new Set(Object.keys(b)); const sharedKeys = Object.keys(a).filter((key) => bKeysSet.has(key));
const newObj: any = { ...a, ...b }; for (const key of sharedKeys) { const sharedValue = mergeValues(a[key], b[key]); if (!sharedValue.valid) { return { valid: false }; } newObj[key] = sharedValue.data; }
return { valid: true, data: newObj }; } else { return { valid: false }; }}
export class ZodIntersection< T extends ZodTypeAny, U extends ZodTypeAny> extends ZodType< T["_output"] & U["_output"], ZodIntersectionDef<T, U>, T["_input"] & U["_input"]> { _parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<T & U> { const handleParsed = ( parsedLeft: SyncParseReturnType<T>, parsedRight: SyncParseReturnType<U> ): SyncParseReturnType<T & U> => { if (isInvalid(parsedLeft) || isInvalid(parsedRight)) { return INVALID; }
const merged = mergeValues(parsedLeft.value, parsedRight.value); if (!merged.valid) { ctx.addIssue(data, { code: ZodIssueCode.invalid_intersection_types, }); return INVALID; } return OK(merged.data); };
if (ctx.params.async) { return PseudoPromise.all([ this._def.left._parse(ctx, data, parsedType), this._def.right._parse(ctx, data, parsedType), ]).then(([left, right]: any) => handleParsed(left, right)); } else { return handleParsed( this._def.left._parseSync(ctx, data, parsedType), this._def.right._parseSync(ctx, data, parsedType) ); } }
static create = <T extends ZodTypeAny, U extends ZodTypeAny>( left: T, right: U ): ZodIntersection<T, U> => { return new ZodIntersection({ left: left, right: right, }); };}
////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodTuple //////////////////// //////////////////////////////////////////////////////////////////////////////////////////export type OutputTypeOfTuple<T extends [ZodTypeAny, ...ZodTypeAny[]] | []> = { [k in keyof T]: T[k] extends ZodType<any, any> ? T[k]["_output"] : never;};
export type InputTypeOfTuple<T extends [ZodTypeAny, ...ZodTypeAny[]] | []> = { [k in keyof T]: T[k] extends ZodType<any, any> ? T[k]["_input"] : never;};
export interface ZodTupleDef< T extends [ZodTypeAny, ...ZodTypeAny[]] | [] = [ZodTypeAny, ...ZodTypeAny[]]> extends ZodTypeDef { items: T;}
export class ZodTuple< T extends [ZodTypeAny, ...ZodTypeAny[]] | [] = [ZodTypeAny, ...ZodTypeAny[]]> extends ZodType<OutputTypeOfTuple<T>, ZodTupleDef<T>, InputTypeOfTuple<T>> { _parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<any> { if (parsedType !== ZodParsedType.array) { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: parsedType, }); return INVALID; }
if (data.length > this._def.items.length) { ctx.addIssue(data, { code: ZodIssueCode.too_big, maximum: this._def.items.length, inclusive: true, type: "array", }); return INVALID; } else if (data.length < this._def.items.length) { ctx.addIssue(data, { code: ZodIssueCode.too_small, minimum: this._def.items.length, inclusive: true, type: "array", }); return INVALID; }
const tasks = createTasks(ctx); const items = this._def.items as ZodType<any>[]; const parseResult: any[] = new Array(items.length); let invalid = false;
const handleParsed = (index: number, parsedItem: ParseReturnType<any>) => { if (isOk(parsedItem)) { parseResult[index] = parsedItem.value; } else if (isInvalid(parsedItem)) { invalid = true; } else { tasks?.push( parsedItem.promise.then((parsed) => handleParsed(index, parsed)) ); } };
items.forEach((item, index) => { handleParsed( index, item._parse( ctx.stepInto(index), data[index], getParsedType(data[index]) ) ); });
if (tasks !== null && tasks.length > 0) { return ASYNC( Promise.all(tasks).then(() => (invalid ? INVALID : OK(parseResult))) ); } else { return invalid ? INVALID : OK(parseResult); } }
get items() { return this._def.items; }
static create = <T extends [ZodTypeAny, ...ZodTypeAny[]] | []>( schemas: T ): ZodTuple<T> => { return new ZodTuple({ items: schemas, }); };}
//////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodRecord //////////////////// ////////////////////////////////////////////////////////////////////////////////////////////export interface ZodRecordDef<Value extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { valueType: Value;}
export class ZodRecord<Value extends ZodTypeAny = ZodTypeAny> extends ZodType< Record<string, Value["_output"]>, ZodRecordDef<Value>, Record<string, Value["_input"]>> { _parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<Record<string, any>> { if (parsedType !== ZodParsedType.object) { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: parsedType, }); return INVALID; }
const tasks = createTasks(ctx); const valueType = this._def.valueType; const parseResult: Record<string, ParseReturnType<any>> = {}; let invalid = false; const handleParsed = ( key: string, parsedKey: ParseReturnType<any> ): void => { if (isOk(parsedKey)) { parseResult[key] = parsedKey.value; } else if (isInvalid(parsedKey)) { invalid = true; } else { tasks?.push( parsedKey.promise.then((parsed) => handleParsed(key, parsed)) ); } };
for (const key in data) { handleParsed( key, valueType._parse(ctx.stepInto(key), data[key], getParsedType(data[key])) ); }
if (tasks !== null && tasks.length > 0) { return ASYNC( Promise.all(tasks).then(() => (invalid ? INVALID : OK(parseResult))) ); } else { return invalid ? INVALID : OK(parseResult); } }
static create = <Value extends ZodTypeAny = ZodTypeAny>( valueType: Value ): ZodRecord<Value> => { return new ZodRecord({ valueType, }); };}
////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodMap //////////////////// //////////////////////////////////////////////////////////////////////////////////////export interface ZodMapDef< Key extends ZodTypeAny = ZodTypeAny, Value extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { valueType: Value; keyType: Key;}
export class ZodMap< Key extends ZodTypeAny = ZodTypeAny, Value extends ZodTypeAny = ZodTypeAny> extends ZodType< Map<Key["_output"], Value["_output"]>, ZodMapDef<Key, Value>, Map<Key["_input"], Value["_input"]>> { _parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<Map<any, any>> { if (parsedType !== ZodParsedType.map) { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.map, received: parsedType, });
return INVALID; }
const keyType = this._def.keyType; const valueType = this._def.valueType; const dataMap: Map<unknown, unknown> = data; const parseResult = new Map(); const tasks = createTasks(ctx); let invalid = false; const handleParsed = ( parsedKey: ParseReturnType<any>, parsedValue: ParseReturnType<any> ): void => { if (isAsync(parsedKey) || isAsync(parsedValue)) { tasks?.push( PseudoPromise.all([parsedKey, parsedValue]).promise.then(([k, v]) => handleParsed(k, v) ) ); } else if (isInvalid(parsedKey) || isInvalid(parsedValue)) { invalid = true; } else { parseResult.set(parsedKey.value, parsedValue.value); } };
[...dataMap.entries()].forEach(([key, value], index) => { const entryCtx = ctx.stepInto(index); const parsedKey = keyType._parse( entryCtx.stepInto("key"), key, getParsedType(key) ); const parsedValue = valueType._parse( entryCtx.stepInto("value"), value, getParsedType(value) ); handleParsed(parsedKey, parsedValue); });
if (tasks !== null && tasks.length > 0) { return ASYNC( Promise.all(tasks).then(() => (invalid ? INVALID : OK(parseResult))) ); } else { return invalid ? INVALID : OK(parseResult); } } static create = < Key extends ZodTypeAny = ZodTypeAny, Value extends ZodTypeAny = ZodTypeAny >( keyType: Key, valueType: Value ): ZodMap<Key, Value> => { return new ZodMap({ valueType, keyType, }); };}
////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodSet //////////////////// //////////////////////////////////////////////////////////////////////////////////////export interface ZodSetDef<Value extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { valueType: Value;}
export class ZodSet<Value extends ZodTypeAny = ZodTypeAny> extends ZodType< Set<Value["_output"]>, ZodSetDef<Value>, Set<Value["_input"]>> { _parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<Set<any>> { if (parsedType !== ZodParsedType.set) { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.set, received: parsedType, });
return INVALID; }
const dataSet: Set<unknown> = data; const valueType = this._def.valueType; const parsedSet = new Set(); const tasks = createTasks(ctx); let invalid = false;
const handleParsed = (parsedItem: ParseReturnType<any>): void => { if (isOk(parsedItem)) { parsedSet.add(parsedItem.value); } else if (isInvalid(parsedItem)) { invalid = true; } else { tasks?.push(parsedItem.promise.then((parsed) => handleParsed(parsed))); } };
[...dataSet.values()].forEach((item, i) => handleParsed(valueType._parse(ctx.stepInto(i), item, getParsedType(item))) );
if (tasks !== null && tasks.length > 0) { return ASYNC( Promise.all(tasks).then(() => (invalid ? INVALID : OK(parsedSet))) ); } else { return invalid ? INVALID : OK(parsedSet); } }
static create = <Value extends ZodTypeAny = ZodTypeAny>( valueType: Value ): ZodSet<Value> => { return new ZodSet({ valueType, }); };}
//////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodFunction //////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////export interface ZodFunctionDef< Args extends ZodTuple<any> = ZodTuple<any>, Returns extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { args: Args; returns: Returns;}
export type OuterTypeOfFunction< Args extends ZodTuple<any>, Returns extends ZodTypeAny> = Args["_input"] extends Array<any> ? (...args: Args["_input"]) => Returns["_output"] : never;
export type InnerTypeOfFunction< Args extends ZodTuple<any>, Returns extends ZodTypeAny> = Args["_output"] extends Array<any> ? (...args: Args["_output"]) => Returns["_input"] : never;
export class ZodFunction< Args extends ZodTuple<any>, Returns extends ZodTypeAny> extends ZodType< OuterTypeOfFunction<Args, Returns>, ZodFunctionDef<Args, Returns>, InnerTypeOfFunction<Args, Returns>> { _parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<any> { if (parsedType !== ZodParsedType.function) { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.function, received: parsedType, });
return INVALID; }
const handleArgs = ( args: any, parsedArgs: | { success: true; data: any } | { success: false; error: ZodError } ): any => { if (!parsedArgs.success) { const issue = makeIssue( args, pathToArray(ctx.path), ctx.params.errorMap, { code: ZodIssueCode.invalid_arguments, argumentsError: parsedArgs.error, } ); throw new ZodError([issue]); } return parsedArgs.data; };
const handleReturns = ( returns: any, parsedReturns: | { success: true; data: any } | { success: false; error: ZodError } ): any => { if (!parsedReturns.success) { const issue = makeIssue( returns, pathToArray(ctx.path), ctx.params.errorMap, { code: ZodIssueCode.invalid_return_type, returnTypeError: parsedReturns.error, } ); throw new ZodError([issue]); } return parsedReturns.data; };
const params = { errorMap: ctx.params.errorMap }; const fn = data;
if (this._def.returns instanceof ZodPromise) { return OK(async (...args: any[]) => { const parsedArgs = handleArgs( args, await this._def.args.spa(args, params) ); const result = await fn(...(parsedArgs as any)); return handleReturns( result, await this._def.returns.spa(result, params) ); }); } else { return OK((...args: any[]) => { const parsedArgs = handleArgs( args, this._def.args.safeParse(args, params) ); const result = fn(...(parsedArgs as any)); return handleReturns( result, this._def.returns.safeParse(result, params) ); }); } }
parameters() { return this._def.args; }
returnType() { return this._def.returns; }
args = <Items extends Parameters<typeof ZodTuple["create"]>[0]>( ...items: Items ): ZodFunction<ZodTuple<Items>, Returns> => { return new ZodFunction({ ...this._def, args: ZodTuple.create(items), }); };
returns = <NewReturnType extends ZodType<any, any>>( returnType: NewReturnType ): ZodFunction<Args, NewReturnType> => { return new ZodFunction({ ...this._def, returns: returnType, }); };
implement = <F extends InnerTypeOfFunction<Args, Returns>>(func: F): F => { const validatedFunc = this.parse(func); return validatedFunc as any; };
strictImplement = ( func: InnerTypeOfFunction<Args, Returns> ): InnerTypeOfFunction<Args, Returns> => { const validatedFunc = this.parse(func); return validatedFunc as any; };
validate = this.implement;
static create = < T extends ZodTuple<any> = ZodTuple<[]>, U extends ZodTypeAny = ZodUnknown >( args?: T, returns?: U ): ZodFunction<T, U> => { return new ZodFunction({ args: args || ZodTuple.create([]), returns: returns || ZodUnknown.create(), }) as any; };}
//////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodLazy //////////////////// ////////////////////////////////////////////////////////////////////////////////////////export interface ZodLazyDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { getter: () => T;}
export class ZodLazy<T extends ZodTypeAny> extends ZodType< output<T>, ZodLazyDef<T>, input<T>> { get schema(): T { return this._def.getter(); }
_parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<output<T>> { const lazySchema = this._def.getter(); return lazySchema._parse(ctx, data, parsedType); }
static create = <T extends ZodTypeAny>(getter: () => T): ZodLazy<T> => { return new ZodLazy({ getter: getter, }); };}
////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodLiteral //////////////////// //////////////////////////////////////////////////////////////////////////////////////////////export interface ZodLiteralDef<T extends any = any> extends ZodTypeDef { value: T;}
export class ZodLiteral<T extends any> extends ZodType<T, ZodLiteralDef<T>> { _parse( ctx: ParseContext, data: any, _parsedType: ZodParsedType ): ParseReturnType<T> { if (data !== this._def.value) { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: this._def.value as any, received: data, }); return INVALID; } return OK(data); }
get value() { return this._def.value; }
static create = <T extends Primitive>(value: T): ZodLiteral<T> => { return new ZodLiteral({ value: value, }); };}
//////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodEnum //////////////////// ////////////////////////////////////////////////////////////////////////////////////////export type ArrayKeys = keyof any[];export type Indices<T> = Exclude<keyof T, ArrayKeys>;
type EnumValues = [string, ...string[]];
type Values<T extends EnumValues> = { [k in T[number]]: k;};
export interface ZodEnumDef<T extends EnumValues = EnumValues> extends ZodTypeDef { values: T;}
export class ZodEnum<T extends [string, ...string[]]> extends ZodType< T[number], ZodEnumDef<T>> { _parse( ctx: ParseContext, data: any, _parsedType: ZodParsedType ): ParseReturnType<T[number]> { if (this._def.values.indexOf(data) === -1) { ctx.addIssue(data, { code: ZodIssueCode.invalid_enum_value, options: this._def.values, }); return INVALID; } return OK(data); }
get options() { return this._def.values; }
get enum(): Values<T> { const enumValues: any = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues as any; }
get Values(): Values<T> { const enumValues: any = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues as any; }
get Enum(): Values<T> { const enumValues: any = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues as any; }
static create = <U extends string, T extends [U, ...U[]]>( values: T ): ZodEnum<T> => { return new ZodEnum({ values: values, }) as any; };}
//////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodNativeEnum //////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////export interface ZodNativeEnumDef<T extends EnumLike = EnumLike> extends ZodTypeDef { values: T;}
type EnumLike = { [k: string]: string | number; [nu: number]: string };
export class ZodNativeEnum<T extends EnumLike> extends ZodType< T[keyof T], ZodNativeEnumDef<T>> { _parse( ctx: ParseContext, data: any, _parsedType: ZodParsedType ): ParseReturnType<T[keyof T]> { const nativeEnumValues = util.getValidEnumValues(this._def.values); if (nativeEnumValues.indexOf(data) === -1) { ctx.addIssue(data, { code: ZodIssueCode.invalid_enum_value, options: util.objectValues(nativeEnumValues), }); return INVALID; } return OK(data); } static create = <T extends EnumLike>(values: T): ZodNativeEnum<T> => { return new ZodNativeEnum({ values: values, }); };}
////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodPromise //////////////////// //////////////////////////////////////////////////////////////////////////////////////////////export interface ZodPromiseDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { type: T;}
export class ZodPromise<T extends ZodTypeAny> extends ZodType< Promise<T["_output"]>, ZodPromiseDef<T>, Promise<T["_input"]>> { _parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<Promise<T["_output"]>> { if (parsedType !== ZodParsedType.promise && ctx.params.async === false) { ctx.addIssue(data, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.promise, received: parsedType, });
return INVALID; }
const promisified = parsedType === ZodParsedType.promise ? data : Promise.resolve(data);
return OK( promisified.then((data: any) => { return this._def.type.parseAsync(data, { path: pathToArray(ctx.path), errorMap: ctx.params.errorMap, }); }) ); }
static create = <T extends ZodTypeAny>(schema: T): ZodPromise<T> => { return new ZodPromise({ type: schema, }); };}
////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodEffects //////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////type ZodEffectsType<T extends ZodTypeAny> = T extends ZodEffects<any, any> ? T : ZodEffects<T, T["_output"]>;
export type InternalCheck<T> = { type: "refinement"; refinement: (arg: T, ctx: RefinementCtx) => any;};export type Mod<T> = { type: "transform"; transform: (arg: T) => any;};export type Effect<T> = InternalCheck<T> | Mod<T>;
export interface ZodEffectsDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { schema: T; effects?: Effect<any>[];}
export class ZodEffects< T extends ZodTypeAny, Output = T["_type"]> extends ZodType<Output, ZodEffectsDef<T>, T["_input"]> { innerType() { return this._def.schema; }
_parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<Output> { const isSync = ctx.params.async === false; const effects = this._def.effects || []; const checkCtx: RefinementCtx = { issueFound: false, addIssue: function (arg: MakeErrorData) { this.issueFound = true; ctx.addIssue(data, arg); }, get path() { return pathToArray(ctx.path); }, };
let invalid = false; const applyEffect = ( acc: any, effect: Effect<any> ): SyncParseReturnType<any> | Promise<SyncParseReturnType<any>> => { switch (effect.type) { case "refinement": const result = effect.refinement(acc, checkCtx); if (result instanceof Promise) { if (isSync) { throw new Error( "You can't use .parse() on a schema containing async refinements. Use .parseAsync instead." ); } else { return result.then((_res) => { const issueFound = checkCtx.issueFound; invalid = invalid || issueFound; return acc; }); } } else { const issueFound = checkCtx.issueFound; invalid = invalid || issueFound; return acc; } case "transform": const transformed = effect.transform(acc); if (transformed instanceof Promise && isSync) { throw new Error( `You can't use .parse() on a schema containing async transformations. Use .parseAsync instead.` ); } return transformed; default: throw new Error(`Invalid effect type.`); } };
if (isSync) { const base = this._def.schema._parseSync(ctx, data, parsedType); if (isOk(base)) { const result = effects.reduce(applyEffect, base.value); return invalid ? INVALID : OK(result); } else { return INVALID; } } else { const applyAsyncEffects = (base: any): ParseReturnType<any> => { const result = effects.reduce((acc, eff) => { return acc instanceof Promise ? acc.then((val) => applyEffect(val, eff)) : applyEffect(acc, eff); }, base); if (result instanceof Promise) { return ASYNC( result.then((val: Output) => (invalid ? INVALID : OK(val))) ); } else { return invalid ? INVALID : OK(result); } }; const baseResult = this._def.schema._parse(ctx, data, parsedType); if (isOk(baseResult)) { return applyAsyncEffects(baseResult.value); } else if (isInvalid(baseResult)) { return INVALID; } else { return ASYNC( baseResult.promise.then((base) => { if (isInvalid(base)) return INVALID; const result = applyAsyncEffects(base.value); return isAsync(result) ? result.promise : result; }) ); } } }
constructor(def: ZodEffectsDef<T>) { super(def); // if (def.schema instanceof ZodEffects) { // throw new Error("ZodEffects cannot be nested."); // } }
static create = <I extends ZodTypeAny>( schema: I ): ZodEffects<I, I["_output"]> => { const newTx = new ZodEffects({ schema, });
return newTx; };}
export { ZodEffects as ZodTransformer };
//////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodOptional //////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////export interface ZodOptionalDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { innerType: T;}
export type ZodOptionalType<T extends ZodTypeAny> = ZodOptional<T>;
export class ZodOptional<T extends ZodTypeAny> extends ZodType< T["_output"] | undefined, ZodOptionalDef<T>, T["_input"] | undefined> { _parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<T["_output"] | undefined> { if (parsedType === ZodParsedType.undefined) { return OK(undefined); } return this._def.innerType._parse(ctx, data, parsedType); }
unwrap() { return this._def.innerType; }
static create = <T extends ZodTypeAny>(type: T): ZodOptional<T> => { return new ZodOptional({ innerType: type, }) as any; };}
//////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodNullable //////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////export interface ZodNullableDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { innerType: T;}
export type ZodNullableType<T extends ZodTypeAny> = ZodNullable<T>;
export class ZodNullable<T extends ZodTypeAny> extends ZodType< T["_output"] | null, ZodNullableDef<T>, T["_input"] | null> { _parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<T["_output"] | null> { if (parsedType === ZodParsedType.null) { return OK(null); } return this._def.innerType._parse(ctx, data, parsedType); }
unwrap() { return this._def.innerType; }
static create = <T extends ZodTypeAny>(type: T): ZodNullable<T> => { return new ZodNullable({ innerType: type, }) as any; };}
////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// ZodDefault //////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////export interface ZodDefaultDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { innerType: T; defaultValue: () => util.noUndefined<T["_input"]>;}
export class ZodDefault<T extends ZodTypeAny> extends ZodType< util.noUndefined<T["_output"]>, ZodDefaultDef<T>, T["_input"] | undefined> { _parse( ctx: ParseContext, data: any, parsedType: ZodParsedType ): ParseReturnType<util.noUndefined<T["_output"]>> { if (parsedType === ZodParsedType.undefined) { data = this._def.defaultValue(); } return this._def.innerType._parse(ctx, data, getParsedType(data)); }
removeDefault() { return this._def.innerType; }
static create = <T extends ZodTypeAny>(type: T): ZodOptional<T> => { return new ZodOptional({ innerType: type, }) as any; };}
export const custom = <T>( check?: (data: unknown) => any, params?: Parameters<ZodTypeAny["refine"]>[1]): ZodType<T> => { if (check) return ZodAny.create().refine(check, params); return ZodAny.create();};
export { ZodType as Schema, ZodType as ZodSchema };
export const late = { object: ZodObject.lazycreate,};
export type ZodFirstPartySchemaTypes = | ZodString | ZodNumber | ZodBigInt | ZodBoolean | ZodDate | ZodUndefined | ZodNull | ZodAny | ZodUnknown | ZodNever | ZodVoid | ZodArray<any> | ZodObject<any> | ZodUnion<any> | ZodIntersection<any, any> | ZodTuple | ZodRecord | ZodMap | ZodSet | ZodFunction<any, any> | ZodLazy<any> | ZodLiteral<any> | ZodEnum<any> | ZodEffects<any> | ZodNativeEnum<any> | ZodOptional<any> | ZodNullable<any> | ZodDefault<any> | ZodPromise<any>;
const instanceOfType = <T extends new (...args: any[]) => any>( cls: T, params: Parameters<ZodTypeAny["refine"]>[1] = { message: `Input not instance of ${cls.name}`, }) => custom<InstanceType<T>>((data) => data instanceof cls, params);
const stringType = ZodString.create;const numberType = ZodNumber.create;const bigIntType = ZodBigInt.create;const booleanType = ZodBoolean.create;const dateType = ZodDate.create;const undefinedType = ZodUndefined.create;const nullType = ZodNull.create;const anyType = ZodAny.create;const unknownType = ZodUnknown.create;const neverType = ZodNever.create;const voidType = ZodVoid.create;const arrayType = ZodArray.create;const objectType = ZodObject.create;const strictObjectType = ZodObject.strictCreate;const unionType = ZodUnion.create;const intersectionType = ZodIntersection.create;const tupleType = ZodTuple.create;const recordType = ZodRecord.create;const mapType = ZodMap.create;const setType = ZodSet.create;const functionType = ZodFunction.create;const lazyType = ZodLazy.create;const literalType = ZodLiteral.create;const enumType = ZodEnum.create;const nativeEnumType = ZodNativeEnum.create;const promiseType = ZodPromise.create;const effectsType = ZodEffects.create;const optionalType = ZodOptional.create;const nullableType = ZodNullable.create;const ostring = () => stringType().optional();const onumber = () => numberType().optional();const oboolean = () => booleanType().optional();
export { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void,};