您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

index.umd.js 152KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Zod = {}));
  5. })(this, (function (exports) { 'use strict';
  6. exports.util = void 0;
  7. (function (util) {
  8. util.assertEqual = (val) => val;
  9. function assertIs(_arg) { }
  10. util.assertIs = assertIs;
  11. function assertNever(_x) {
  12. throw new Error();
  13. }
  14. util.assertNever = assertNever;
  15. util.arrayToEnum = (items) => {
  16. const obj = {};
  17. for (const item of items) {
  18. obj[item] = item;
  19. }
  20. return obj;
  21. };
  22. util.getValidEnumValues = (obj) => {
  23. const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
  24. const filtered = {};
  25. for (const k of validKeys) {
  26. filtered[k] = obj[k];
  27. }
  28. return util.objectValues(filtered);
  29. };
  30. util.objectValues = (obj) => {
  31. return util.objectKeys(obj).map(function (e) {
  32. return obj[e];
  33. });
  34. };
  35. util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
  36. ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
  37. : (object) => {
  38. const keys = [];
  39. for (const key in object) {
  40. if (Object.prototype.hasOwnProperty.call(object, key)) {
  41. keys.push(key);
  42. }
  43. }
  44. return keys;
  45. };
  46. util.find = (arr, checker) => {
  47. for (const item of arr) {
  48. if (checker(item))
  49. return item;
  50. }
  51. return undefined;
  52. };
  53. util.isInteger = typeof Number.isInteger === "function"
  54. ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
  55. : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
  56. function joinValues(array, separator = " | ") {
  57. return array
  58. .map((val) => (typeof val === "string" ? `'${val}'` : val))
  59. .join(separator);
  60. }
  61. util.joinValues = joinValues;
  62. util.jsonStringifyReplacer = (_, value) => {
  63. if (typeof value === "bigint") {
  64. return value.toString();
  65. }
  66. return value;
  67. };
  68. })(exports.util || (exports.util = {}));
  69. exports.objectUtil = void 0;
  70. (function (objectUtil) {
  71. objectUtil.mergeShapes = (first, second) => {
  72. return {
  73. ...first,
  74. ...second, // second overwrites first
  75. };
  76. };
  77. })(exports.objectUtil || (exports.objectUtil = {}));
  78. const ZodParsedType = exports.util.arrayToEnum([
  79. "string",
  80. "nan",
  81. "number",
  82. "integer",
  83. "float",
  84. "boolean",
  85. "date",
  86. "bigint",
  87. "symbol",
  88. "function",
  89. "undefined",
  90. "null",
  91. "array",
  92. "object",
  93. "unknown",
  94. "promise",
  95. "void",
  96. "never",
  97. "map",
  98. "set",
  99. ]);
  100. const getParsedType = (data) => {
  101. const t = typeof data;
  102. switch (t) {
  103. case "undefined":
  104. return ZodParsedType.undefined;
  105. case "string":
  106. return ZodParsedType.string;
  107. case "number":
  108. return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
  109. case "boolean":
  110. return ZodParsedType.boolean;
  111. case "function":
  112. return ZodParsedType.function;
  113. case "bigint":
  114. return ZodParsedType.bigint;
  115. case "symbol":
  116. return ZodParsedType.symbol;
  117. case "object":
  118. if (Array.isArray(data)) {
  119. return ZodParsedType.array;
  120. }
  121. if (data === null) {
  122. return ZodParsedType.null;
  123. }
  124. if (data.then &&
  125. typeof data.then === "function" &&
  126. data.catch &&
  127. typeof data.catch === "function") {
  128. return ZodParsedType.promise;
  129. }
  130. if (typeof Map !== "undefined" && data instanceof Map) {
  131. return ZodParsedType.map;
  132. }
  133. if (typeof Set !== "undefined" && data instanceof Set) {
  134. return ZodParsedType.set;
  135. }
  136. if (typeof Date !== "undefined" && data instanceof Date) {
  137. return ZodParsedType.date;
  138. }
  139. return ZodParsedType.object;
  140. default:
  141. return ZodParsedType.unknown;
  142. }
  143. };
  144. const ZodIssueCode = exports.util.arrayToEnum([
  145. "invalid_type",
  146. "invalid_literal",
  147. "custom",
  148. "invalid_union",
  149. "invalid_union_discriminator",
  150. "invalid_enum_value",
  151. "unrecognized_keys",
  152. "invalid_arguments",
  153. "invalid_return_type",
  154. "invalid_date",
  155. "invalid_string",
  156. "too_small",
  157. "too_big",
  158. "invalid_intersection_types",
  159. "not_multiple_of",
  160. "not_finite",
  161. ]);
  162. const quotelessJson = (obj) => {
  163. const json = JSON.stringify(obj, null, 2);
  164. return json.replace(/"([^"]+)":/g, "$1:");
  165. };
  166. class ZodError extends Error {
  167. constructor(issues) {
  168. super();
  169. this.issues = [];
  170. this.addIssue = (sub) => {
  171. this.issues = [...this.issues, sub];
  172. };
  173. this.addIssues = (subs = []) => {
  174. this.issues = [...this.issues, ...subs];
  175. };
  176. const actualProto = new.target.prototype;
  177. if (Object.setPrototypeOf) {
  178. // eslint-disable-next-line ban/ban
  179. Object.setPrototypeOf(this, actualProto);
  180. }
  181. else {
  182. this.__proto__ = actualProto;
  183. }
  184. this.name = "ZodError";
  185. this.issues = issues;
  186. }
  187. get errors() {
  188. return this.issues;
  189. }
  190. format(_mapper) {
  191. const mapper = _mapper ||
  192. function (issue) {
  193. return issue.message;
  194. };
  195. const fieldErrors = { _errors: [] };
  196. const processError = (error) => {
  197. for (const issue of error.issues) {
  198. if (issue.code === "invalid_union") {
  199. issue.unionErrors.map(processError);
  200. }
  201. else if (issue.code === "invalid_return_type") {
  202. processError(issue.returnTypeError);
  203. }
  204. else if (issue.code === "invalid_arguments") {
  205. processError(issue.argumentsError);
  206. }
  207. else if (issue.path.length === 0) {
  208. fieldErrors._errors.push(mapper(issue));
  209. }
  210. else {
  211. let curr = fieldErrors;
  212. let i = 0;
  213. while (i < issue.path.length) {
  214. const el = issue.path[i];
  215. const terminal = i === issue.path.length - 1;
  216. if (!terminal) {
  217. curr[el] = curr[el] || { _errors: [] };
  218. // if (typeof el === "string") {
  219. // curr[el] = curr[el] || { _errors: [] };
  220. // } else if (typeof el === "number") {
  221. // const errorArray: any = [];
  222. // errorArray._errors = [];
  223. // curr[el] = curr[el] || errorArray;
  224. // }
  225. }
  226. else {
  227. curr[el] = curr[el] || { _errors: [] };
  228. curr[el]._errors.push(mapper(issue));
  229. }
  230. curr = curr[el];
  231. i++;
  232. }
  233. }
  234. }
  235. };
  236. processError(this);
  237. return fieldErrors;
  238. }
  239. toString() {
  240. return this.message;
  241. }
  242. get message() {
  243. return JSON.stringify(this.issues, exports.util.jsonStringifyReplacer, 2);
  244. }
  245. get isEmpty() {
  246. return this.issues.length === 0;
  247. }
  248. flatten(mapper = (issue) => issue.message) {
  249. const fieldErrors = {};
  250. const formErrors = [];
  251. for (const sub of this.issues) {
  252. if (sub.path.length > 0) {
  253. fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
  254. fieldErrors[sub.path[0]].push(mapper(sub));
  255. }
  256. else {
  257. formErrors.push(mapper(sub));
  258. }
  259. }
  260. return { formErrors, fieldErrors };
  261. }
  262. get formErrors() {
  263. return this.flatten();
  264. }
  265. }
  266. ZodError.create = (issues) => {
  267. const error = new ZodError(issues);
  268. return error;
  269. };
  270. const errorMap = (issue, _ctx) => {
  271. let message;
  272. switch (issue.code) {
  273. case ZodIssueCode.invalid_type:
  274. if (issue.received === ZodParsedType.undefined) {
  275. message = "Required";
  276. }
  277. else {
  278. message = `Expected ${issue.expected}, received ${issue.received}`;
  279. }
  280. break;
  281. case ZodIssueCode.invalid_literal:
  282. message = `Invalid literal value, expected ${JSON.stringify(issue.expected, exports.util.jsonStringifyReplacer)}`;
  283. break;
  284. case ZodIssueCode.unrecognized_keys:
  285. message = `Unrecognized key(s) in object: ${exports.util.joinValues(issue.keys, ", ")}`;
  286. break;
  287. case ZodIssueCode.invalid_union:
  288. message = `Invalid input`;
  289. break;
  290. case ZodIssueCode.invalid_union_discriminator:
  291. message = `Invalid discriminator value. Expected ${exports.util.joinValues(issue.options)}`;
  292. break;
  293. case ZodIssueCode.invalid_enum_value:
  294. message = `Invalid enum value. Expected ${exports.util.joinValues(issue.options)}, received '${issue.received}'`;
  295. break;
  296. case ZodIssueCode.invalid_arguments:
  297. message = `Invalid function arguments`;
  298. break;
  299. case ZodIssueCode.invalid_return_type:
  300. message = `Invalid function return type`;
  301. break;
  302. case ZodIssueCode.invalid_date:
  303. message = `Invalid date`;
  304. break;
  305. case ZodIssueCode.invalid_string:
  306. if (typeof issue.validation === "object") {
  307. if ("includes" in issue.validation) {
  308. message = `Invalid input: must include "${issue.validation.includes}"`;
  309. if (typeof issue.validation.position === "number") {
  310. message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
  311. }
  312. }
  313. else if ("startsWith" in issue.validation) {
  314. message = `Invalid input: must start with "${issue.validation.startsWith}"`;
  315. }
  316. else if ("endsWith" in issue.validation) {
  317. message = `Invalid input: must end with "${issue.validation.endsWith}"`;
  318. }
  319. else {
  320. exports.util.assertNever(issue.validation);
  321. }
  322. }
  323. else if (issue.validation !== "regex") {
  324. message = `Invalid ${issue.validation}`;
  325. }
  326. else {
  327. message = "Invalid";
  328. }
  329. break;
  330. case ZodIssueCode.too_small:
  331. if (issue.type === "array")
  332. message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
  333. else if (issue.type === "string")
  334. message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
  335. else if (issue.type === "number")
  336. message = `Number must be ${issue.exact
  337. ? `exactly equal to `
  338. : issue.inclusive
  339. ? `greater than or equal to `
  340. : `greater than `}${issue.minimum}`;
  341. else if (issue.type === "date")
  342. message = `Date must be ${issue.exact
  343. ? `exactly equal to `
  344. : issue.inclusive
  345. ? `greater than or equal to `
  346. : `greater than `}${new Date(Number(issue.minimum))}`;
  347. else
  348. message = "Invalid input";
  349. break;
  350. case ZodIssueCode.too_big:
  351. if (issue.type === "array")
  352. message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
  353. else if (issue.type === "string")
  354. message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
  355. else if (issue.type === "number")
  356. message = `Number must be ${issue.exact
  357. ? `exactly`
  358. : issue.inclusive
  359. ? `less than or equal to`
  360. : `less than`} ${issue.maximum}`;
  361. else if (issue.type === "bigint")
  362. message = `BigInt must be ${issue.exact
  363. ? `exactly`
  364. : issue.inclusive
  365. ? `less than or equal to`
  366. : `less than`} ${issue.maximum}`;
  367. else if (issue.type === "date")
  368. message = `Date must be ${issue.exact
  369. ? `exactly`
  370. : issue.inclusive
  371. ? `smaller than or equal to`
  372. : `smaller than`} ${new Date(Number(issue.maximum))}`;
  373. else
  374. message = "Invalid input";
  375. break;
  376. case ZodIssueCode.custom:
  377. message = `Invalid input`;
  378. break;
  379. case ZodIssueCode.invalid_intersection_types:
  380. message = `Intersection results could not be merged`;
  381. break;
  382. case ZodIssueCode.not_multiple_of:
  383. message = `Number must be a multiple of ${issue.multipleOf}`;
  384. break;
  385. case ZodIssueCode.not_finite:
  386. message = "Number must be finite";
  387. break;
  388. default:
  389. message = _ctx.defaultError;
  390. exports.util.assertNever(issue);
  391. }
  392. return { message };
  393. };
  394. let overrideErrorMap = errorMap;
  395. function setErrorMap(map) {
  396. overrideErrorMap = map;
  397. }
  398. function getErrorMap() {
  399. return overrideErrorMap;
  400. }
  401. const makeIssue = (params) => {
  402. const { data, path, errorMaps, issueData } = params;
  403. const fullPath = [...path, ...(issueData.path || [])];
  404. const fullIssue = {
  405. ...issueData,
  406. path: fullPath,
  407. };
  408. let errorMessage = "";
  409. const maps = errorMaps
  410. .filter((m) => !!m)
  411. .slice()
  412. .reverse();
  413. for (const map of maps) {
  414. errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
  415. }
  416. return {
  417. ...issueData,
  418. path: fullPath,
  419. message: issueData.message || errorMessage,
  420. };
  421. };
  422. const EMPTY_PATH = [];
  423. function addIssueToContext(ctx, issueData) {
  424. const issue = makeIssue({
  425. issueData: issueData,
  426. data: ctx.data,
  427. path: ctx.path,
  428. errorMaps: [
  429. ctx.common.contextualErrorMap,
  430. ctx.schemaErrorMap,
  431. getErrorMap(),
  432. errorMap, // then global default map
  433. ].filter((x) => !!x),
  434. });
  435. ctx.common.issues.push(issue);
  436. }
  437. class ParseStatus {
  438. constructor() {
  439. this.value = "valid";
  440. }
  441. dirty() {
  442. if (this.value === "valid")
  443. this.value = "dirty";
  444. }
  445. abort() {
  446. if (this.value !== "aborted")
  447. this.value = "aborted";
  448. }
  449. static mergeArray(status, results) {
  450. const arrayValue = [];
  451. for (const s of results) {
  452. if (s.status === "aborted")
  453. return INVALID;
  454. if (s.status === "dirty")
  455. status.dirty();
  456. arrayValue.push(s.value);
  457. }
  458. return { status: status.value, value: arrayValue };
  459. }
  460. static async mergeObjectAsync(status, pairs) {
  461. const syncPairs = [];
  462. for (const pair of pairs) {
  463. syncPairs.push({
  464. key: await pair.key,
  465. value: await pair.value,
  466. });
  467. }
  468. return ParseStatus.mergeObjectSync(status, syncPairs);
  469. }
  470. static mergeObjectSync(status, pairs) {
  471. const finalObject = {};
  472. for (const pair of pairs) {
  473. const { key, value } = pair;
  474. if (key.status === "aborted")
  475. return INVALID;
  476. if (value.status === "aborted")
  477. return INVALID;
  478. if (key.status === "dirty")
  479. status.dirty();
  480. if (value.status === "dirty")
  481. status.dirty();
  482. if (typeof value.value !== "undefined" || pair.alwaysSet) {
  483. finalObject[key.value] = value.value;
  484. }
  485. }
  486. return { status: status.value, value: finalObject };
  487. }
  488. }
  489. const INVALID = Object.freeze({
  490. status: "aborted",
  491. });
  492. const DIRTY = (value) => ({ status: "dirty", value });
  493. const OK = (value) => ({ status: "valid", value });
  494. const isAborted = (x) => x.status === "aborted";
  495. const isDirty = (x) => x.status === "dirty";
  496. const isValid = (x) => x.status === "valid";
  497. const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
  498. var errorUtil;
  499. (function (errorUtil) {
  500. errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  501. errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
  502. })(errorUtil || (errorUtil = {}));
  503. class ParseInputLazyPath {
  504. constructor(parent, value, path, key) {
  505. this._cachedPath = [];
  506. this.parent = parent;
  507. this.data = value;
  508. this._path = path;
  509. this._key = key;
  510. }
  511. get path() {
  512. if (!this._cachedPath.length) {
  513. if (this._key instanceof Array) {
  514. this._cachedPath.push(...this._path, ...this._key);
  515. }
  516. else {
  517. this._cachedPath.push(...this._path, this._key);
  518. }
  519. }
  520. return this._cachedPath;
  521. }
  522. }
  523. const handleResult = (ctx, result) => {
  524. if (isValid(result)) {
  525. return { success: true, data: result.value };
  526. }
  527. else {
  528. if (!ctx.common.issues.length) {
  529. throw new Error("Validation failed but no issues detected.");
  530. }
  531. return {
  532. success: false,
  533. get error() {
  534. if (this._error)
  535. return this._error;
  536. const error = new ZodError(ctx.common.issues);
  537. this._error = error;
  538. return this._error;
  539. },
  540. };
  541. }
  542. };
  543. function processCreateParams(params) {
  544. if (!params)
  545. return {};
  546. const { errorMap, invalid_type_error, required_error, description } = params;
  547. if (errorMap && (invalid_type_error || required_error)) {
  548. throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  549. }
  550. if (errorMap)
  551. return { errorMap: errorMap, description };
  552. const customMap = (iss, ctx) => {
  553. if (iss.code !== "invalid_type")
  554. return { message: ctx.defaultError };
  555. if (typeof ctx.data === "undefined") {
  556. return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
  557. }
  558. return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
  559. };
  560. return { errorMap: customMap, description };
  561. }
  562. class ZodType {
  563. constructor(def) {
  564. /** Alias of safeParseAsync */
  565. this.spa = this.safeParseAsync;
  566. this._def = def;
  567. this.parse = this.parse.bind(this);
  568. this.safeParse = this.safeParse.bind(this);
  569. this.parseAsync = this.parseAsync.bind(this);
  570. this.safeParseAsync = this.safeParseAsync.bind(this);
  571. this.spa = this.spa.bind(this);
  572. this.refine = this.refine.bind(this);
  573. this.refinement = this.refinement.bind(this);
  574. this.superRefine = this.superRefine.bind(this);
  575. this.optional = this.optional.bind(this);
  576. this.nullable = this.nullable.bind(this);
  577. this.nullish = this.nullish.bind(this);
  578. this.array = this.array.bind(this);
  579. this.promise = this.promise.bind(this);
  580. this.or = this.or.bind(this);
  581. this.and = this.and.bind(this);
  582. this.transform = this.transform.bind(this);
  583. this.brand = this.brand.bind(this);
  584. this.default = this.default.bind(this);
  585. this.catch = this.catch.bind(this);
  586. this.describe = this.describe.bind(this);
  587. this.pipe = this.pipe.bind(this);
  588. this.isNullable = this.isNullable.bind(this);
  589. this.isOptional = this.isOptional.bind(this);
  590. }
  591. get description() {
  592. return this._def.description;
  593. }
  594. _getType(input) {
  595. return getParsedType(input.data);
  596. }
  597. _getOrReturnCtx(input, ctx) {
  598. return (ctx || {
  599. common: input.parent.common,
  600. data: input.data,
  601. parsedType: getParsedType(input.data),
  602. schemaErrorMap: this._def.errorMap,
  603. path: input.path,
  604. parent: input.parent,
  605. });
  606. }
  607. _processInputParams(input) {
  608. return {
  609. status: new ParseStatus(),
  610. ctx: {
  611. common: input.parent.common,
  612. data: input.data,
  613. parsedType: getParsedType(input.data),
  614. schemaErrorMap: this._def.errorMap,
  615. path: input.path,
  616. parent: input.parent,
  617. },
  618. };
  619. }
  620. _parseSync(input) {
  621. const result = this._parse(input);
  622. if (isAsync(result)) {
  623. throw new Error("Synchronous parse encountered promise.");
  624. }
  625. return result;
  626. }
  627. _parseAsync(input) {
  628. const result = this._parse(input);
  629. return Promise.resolve(result);
  630. }
  631. parse(data, params) {
  632. const result = this.safeParse(data, params);
  633. if (result.success)
  634. return result.data;
  635. throw result.error;
  636. }
  637. safeParse(data, params) {
  638. var _a;
  639. const ctx = {
  640. common: {
  641. issues: [],
  642. async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
  643. contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
  644. },
  645. path: (params === null || params === void 0 ? void 0 : params.path) || [],
  646. schemaErrorMap: this._def.errorMap,
  647. parent: null,
  648. data,
  649. parsedType: getParsedType(data),
  650. };
  651. const result = this._parseSync({ data, path: ctx.path, parent: ctx });
  652. return handleResult(ctx, result);
  653. }
  654. async parseAsync(data, params) {
  655. const result = await this.safeParseAsync(data, params);
  656. if (result.success)
  657. return result.data;
  658. throw result.error;
  659. }
  660. async safeParseAsync(data, params) {
  661. const ctx = {
  662. common: {
  663. issues: [],
  664. contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
  665. async: true,
  666. },
  667. path: (params === null || params === void 0 ? void 0 : params.path) || [],
  668. schemaErrorMap: this._def.errorMap,
  669. parent: null,
  670. data,
  671. parsedType: getParsedType(data),
  672. };
  673. const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
  674. const result = await (isAsync(maybeAsyncResult)
  675. ? maybeAsyncResult
  676. : Promise.resolve(maybeAsyncResult));
  677. return handleResult(ctx, result);
  678. }
  679. refine(check, message) {
  680. const getIssueProperties = (val) => {
  681. if (typeof message === "string" || typeof message === "undefined") {
  682. return { message };
  683. }
  684. else if (typeof message === "function") {
  685. return message(val);
  686. }
  687. else {
  688. return message;
  689. }
  690. };
  691. return this._refinement((val, ctx) => {
  692. const result = check(val);
  693. const setError = () => ctx.addIssue({
  694. code: ZodIssueCode.custom,
  695. ...getIssueProperties(val),
  696. });
  697. if (typeof Promise !== "undefined" && result instanceof Promise) {
  698. return result.then((data) => {
  699. if (!data) {
  700. setError();
  701. return false;
  702. }
  703. else {
  704. return true;
  705. }
  706. });
  707. }
  708. if (!result) {
  709. setError();
  710. return false;
  711. }
  712. else {
  713. return true;
  714. }
  715. });
  716. }
  717. refinement(check, refinementData) {
  718. return this._refinement((val, ctx) => {
  719. if (!check(val)) {
  720. ctx.addIssue(typeof refinementData === "function"
  721. ? refinementData(val, ctx)
  722. : refinementData);
  723. return false;
  724. }
  725. else {
  726. return true;
  727. }
  728. });
  729. }
  730. _refinement(refinement) {
  731. return new ZodEffects({
  732. schema: this,
  733. typeName: exports.ZodFirstPartyTypeKind.ZodEffects,
  734. effect: { type: "refinement", refinement },
  735. });
  736. }
  737. superRefine(refinement) {
  738. return this._refinement(refinement);
  739. }
  740. optional() {
  741. return ZodOptional.create(this, this._def);
  742. }
  743. nullable() {
  744. return ZodNullable.create(this, this._def);
  745. }
  746. nullish() {
  747. return this.nullable().optional();
  748. }
  749. array() {
  750. return ZodArray.create(this, this._def);
  751. }
  752. promise() {
  753. return ZodPromise.create(this, this._def);
  754. }
  755. or(option) {
  756. return ZodUnion.create([this, option], this._def);
  757. }
  758. and(incoming) {
  759. return ZodIntersection.create(this, incoming, this._def);
  760. }
  761. transform(transform) {
  762. return new ZodEffects({
  763. ...processCreateParams(this._def),
  764. schema: this,
  765. typeName: exports.ZodFirstPartyTypeKind.ZodEffects,
  766. effect: { type: "transform", transform },
  767. });
  768. }
  769. default(def) {
  770. const defaultValueFunc = typeof def === "function" ? def : () => def;
  771. return new ZodDefault({
  772. ...processCreateParams(this._def),
  773. innerType: this,
  774. defaultValue: defaultValueFunc,
  775. typeName: exports.ZodFirstPartyTypeKind.ZodDefault,
  776. });
  777. }
  778. brand() {
  779. return new ZodBranded({
  780. typeName: exports.ZodFirstPartyTypeKind.ZodBranded,
  781. type: this,
  782. ...processCreateParams(this._def),
  783. });
  784. }
  785. catch(def) {
  786. const catchValueFunc = typeof def === "function" ? def : () => def;
  787. return new ZodCatch({
  788. ...processCreateParams(this._def),
  789. innerType: this,
  790. catchValue: catchValueFunc,
  791. typeName: exports.ZodFirstPartyTypeKind.ZodCatch,
  792. });
  793. }
  794. describe(description) {
  795. const This = this.constructor;
  796. return new This({
  797. ...this._def,
  798. description,
  799. });
  800. }
  801. pipe(target) {
  802. return ZodPipeline.create(this, target);
  803. }
  804. isOptional() {
  805. return this.safeParse(undefined).success;
  806. }
  807. isNullable() {
  808. return this.safeParse(null).success;
  809. }
  810. }
  811. const cuidRegex = /^c[^\s-]{8,}$/i;
  812. const cuid2Regex = /^[a-z][a-z0-9]*$/;
  813. const ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/;
  814. const uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
  815. // from https://stackoverflow.com/a/46181/1550155
  816. // old version: too slow, didn't support unicode
  817. // 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;
  818. //old email regex
  819. // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
  820. // eslint-disable-next-line
  821. const emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
  822. // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
  823. const emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u;
  824. const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
  825. const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
  826. // Adapted from https://stackoverflow.com/a/3143231
  827. const datetimeRegex = (args) => {
  828. if (args.precision) {
  829. if (args.offset) {
  830. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
  831. }
  832. else {
  833. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`);
  834. }
  835. }
  836. else if (args.precision === 0) {
  837. if (args.offset) {
  838. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
  839. }
  840. else {
  841. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
  842. }
  843. }
  844. else {
  845. if (args.offset) {
  846. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
  847. }
  848. else {
  849. return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
  850. }
  851. }
  852. };
  853. function isValidIP(ip, version) {
  854. if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
  855. return true;
  856. }
  857. if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
  858. return true;
  859. }
  860. return false;
  861. }
  862. class ZodString extends ZodType {
  863. constructor() {
  864. super(...arguments);
  865. this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), {
  866. validation,
  867. code: ZodIssueCode.invalid_string,
  868. ...errorUtil.errToObj(message),
  869. });
  870. /**
  871. * @deprecated Use z.string().min(1) instead.
  872. * @see {@link ZodString.min}
  873. */
  874. this.nonempty = (message) => this.min(1, errorUtil.errToObj(message));
  875. this.trim = () => new ZodString({
  876. ...this._def,
  877. checks: [...this._def.checks, { kind: "trim" }],
  878. });
  879. this.toLowerCase = () => new ZodString({
  880. ...this._def,
  881. checks: [...this._def.checks, { kind: "toLowerCase" }],
  882. });
  883. this.toUpperCase = () => new ZodString({
  884. ...this._def,
  885. checks: [...this._def.checks, { kind: "toUpperCase" }],
  886. });
  887. }
  888. _parse(input) {
  889. if (this._def.coerce) {
  890. input.data = String(input.data);
  891. }
  892. const parsedType = this._getType(input);
  893. if (parsedType !== ZodParsedType.string) {
  894. const ctx = this._getOrReturnCtx(input);
  895. addIssueToContext(ctx, {
  896. code: ZodIssueCode.invalid_type,
  897. expected: ZodParsedType.string,
  898. received: ctx.parsedType,
  899. }
  900. //
  901. );
  902. return INVALID;
  903. }
  904. const status = new ParseStatus();
  905. let ctx = undefined;
  906. for (const check of this._def.checks) {
  907. if (check.kind === "min") {
  908. if (input.data.length < check.value) {
  909. ctx = this._getOrReturnCtx(input, ctx);
  910. addIssueToContext(ctx, {
  911. code: ZodIssueCode.too_small,
  912. minimum: check.value,
  913. type: "string",
  914. inclusive: true,
  915. exact: false,
  916. message: check.message,
  917. });
  918. status.dirty();
  919. }
  920. }
  921. else if (check.kind === "max") {
  922. if (input.data.length > check.value) {
  923. ctx = this._getOrReturnCtx(input, ctx);
  924. addIssueToContext(ctx, {
  925. code: ZodIssueCode.too_big,
  926. maximum: check.value,
  927. type: "string",
  928. inclusive: true,
  929. exact: false,
  930. message: check.message,
  931. });
  932. status.dirty();
  933. }
  934. }
  935. else if (check.kind === "length") {
  936. const tooBig = input.data.length > check.value;
  937. const tooSmall = input.data.length < check.value;
  938. if (tooBig || tooSmall) {
  939. ctx = this._getOrReturnCtx(input, ctx);
  940. if (tooBig) {
  941. addIssueToContext(ctx, {
  942. code: ZodIssueCode.too_big,
  943. maximum: check.value,
  944. type: "string",
  945. inclusive: true,
  946. exact: true,
  947. message: check.message,
  948. });
  949. }
  950. else if (tooSmall) {
  951. addIssueToContext(ctx, {
  952. code: ZodIssueCode.too_small,
  953. minimum: check.value,
  954. type: "string",
  955. inclusive: true,
  956. exact: true,
  957. message: check.message,
  958. });
  959. }
  960. status.dirty();
  961. }
  962. }
  963. else if (check.kind === "email") {
  964. if (!emailRegex.test(input.data)) {
  965. ctx = this._getOrReturnCtx(input, ctx);
  966. addIssueToContext(ctx, {
  967. validation: "email",
  968. code: ZodIssueCode.invalid_string,
  969. message: check.message,
  970. });
  971. status.dirty();
  972. }
  973. }
  974. else if (check.kind === "emoji") {
  975. if (!emojiRegex.test(input.data)) {
  976. ctx = this._getOrReturnCtx(input, ctx);
  977. addIssueToContext(ctx, {
  978. validation: "emoji",
  979. code: ZodIssueCode.invalid_string,
  980. message: check.message,
  981. });
  982. status.dirty();
  983. }
  984. }
  985. else if (check.kind === "uuid") {
  986. if (!uuidRegex.test(input.data)) {
  987. ctx = this._getOrReturnCtx(input, ctx);
  988. addIssueToContext(ctx, {
  989. validation: "uuid",
  990. code: ZodIssueCode.invalid_string,
  991. message: check.message,
  992. });
  993. status.dirty();
  994. }
  995. }
  996. else if (check.kind === "cuid") {
  997. if (!cuidRegex.test(input.data)) {
  998. ctx = this._getOrReturnCtx(input, ctx);
  999. addIssueToContext(ctx, {
  1000. validation: "cuid",
  1001. code: ZodIssueCode.invalid_string,
  1002. message: check.message,
  1003. });
  1004. status.dirty();
  1005. }
  1006. }
  1007. else if (check.kind === "cuid2") {
  1008. if (!cuid2Regex.test(input.data)) {
  1009. ctx = this._getOrReturnCtx(input, ctx);
  1010. addIssueToContext(ctx, {
  1011. validation: "cuid2",
  1012. code: ZodIssueCode.invalid_string,
  1013. message: check.message,
  1014. });
  1015. status.dirty();
  1016. }
  1017. }
  1018. else if (check.kind === "ulid") {
  1019. if (!ulidRegex.test(input.data)) {
  1020. ctx = this._getOrReturnCtx(input, ctx);
  1021. addIssueToContext(ctx, {
  1022. validation: "ulid",
  1023. code: ZodIssueCode.invalid_string,
  1024. message: check.message,
  1025. });
  1026. status.dirty();
  1027. }
  1028. }
  1029. else if (check.kind === "url") {
  1030. try {
  1031. new URL(input.data);
  1032. }
  1033. catch (_a) {
  1034. ctx = this._getOrReturnCtx(input, ctx);
  1035. addIssueToContext(ctx, {
  1036. validation: "url",
  1037. code: ZodIssueCode.invalid_string,
  1038. message: check.message,
  1039. });
  1040. status.dirty();
  1041. }
  1042. }
  1043. else if (check.kind === "regex") {
  1044. check.regex.lastIndex = 0;
  1045. const testResult = check.regex.test(input.data);
  1046. if (!testResult) {
  1047. ctx = this._getOrReturnCtx(input, ctx);
  1048. addIssueToContext(ctx, {
  1049. validation: "regex",
  1050. code: ZodIssueCode.invalid_string,
  1051. message: check.message,
  1052. });
  1053. status.dirty();
  1054. }
  1055. }
  1056. else if (check.kind === "trim") {
  1057. input.data = input.data.trim();
  1058. }
  1059. else if (check.kind === "includes") {
  1060. if (!input.data.includes(check.value, check.position)) {
  1061. ctx = this._getOrReturnCtx(input, ctx);
  1062. addIssueToContext(ctx, {
  1063. code: ZodIssueCode.invalid_string,
  1064. validation: { includes: check.value, position: check.position },
  1065. message: check.message,
  1066. });
  1067. status.dirty();
  1068. }
  1069. }
  1070. else if (check.kind === "toLowerCase") {
  1071. input.data = input.data.toLowerCase();
  1072. }
  1073. else if (check.kind === "toUpperCase") {
  1074. input.data = input.data.toUpperCase();
  1075. }
  1076. else if (check.kind === "startsWith") {
  1077. if (!input.data.startsWith(check.value)) {
  1078. ctx = this._getOrReturnCtx(input, ctx);
  1079. addIssueToContext(ctx, {
  1080. code: ZodIssueCode.invalid_string,
  1081. validation: { startsWith: check.value },
  1082. message: check.message,
  1083. });
  1084. status.dirty();
  1085. }
  1086. }
  1087. else if (check.kind === "endsWith") {
  1088. if (!input.data.endsWith(check.value)) {
  1089. ctx = this._getOrReturnCtx(input, ctx);
  1090. addIssueToContext(ctx, {
  1091. code: ZodIssueCode.invalid_string,
  1092. validation: { endsWith: check.value },
  1093. message: check.message,
  1094. });
  1095. status.dirty();
  1096. }
  1097. }
  1098. else if (check.kind === "datetime") {
  1099. const regex = datetimeRegex(check);
  1100. if (!regex.test(input.data)) {
  1101. ctx = this._getOrReturnCtx(input, ctx);
  1102. addIssueToContext(ctx, {
  1103. code: ZodIssueCode.invalid_string,
  1104. validation: "datetime",
  1105. message: check.message,
  1106. });
  1107. status.dirty();
  1108. }
  1109. }
  1110. else if (check.kind === "ip") {
  1111. if (!isValidIP(input.data, check.version)) {
  1112. ctx = this._getOrReturnCtx(input, ctx);
  1113. addIssueToContext(ctx, {
  1114. validation: "ip",
  1115. code: ZodIssueCode.invalid_string,
  1116. message: check.message,
  1117. });
  1118. status.dirty();
  1119. }
  1120. }
  1121. else {
  1122. exports.util.assertNever(check);
  1123. }
  1124. }
  1125. return { status: status.value, value: input.data };
  1126. }
  1127. _addCheck(check) {
  1128. return new ZodString({
  1129. ...this._def,
  1130. checks: [...this._def.checks, check],
  1131. });
  1132. }
  1133. email(message) {
  1134. return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
  1135. }
  1136. url(message) {
  1137. return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
  1138. }
  1139. emoji(message) {
  1140. return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
  1141. }
  1142. uuid(message) {
  1143. return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
  1144. }
  1145. cuid(message) {
  1146. return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
  1147. }
  1148. cuid2(message) {
  1149. return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
  1150. }
  1151. ulid(message) {
  1152. return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
  1153. }
  1154. ip(options) {
  1155. return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
  1156. }
  1157. datetime(options) {
  1158. var _a;
  1159. if (typeof options === "string") {
  1160. return this._addCheck({
  1161. kind: "datetime",
  1162. precision: null,
  1163. offset: false,
  1164. message: options,
  1165. });
  1166. }
  1167. return this._addCheck({
  1168. kind: "datetime",
  1169. precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
  1170. offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
  1171. ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
  1172. });
  1173. }
  1174. regex(regex, message) {
  1175. return this._addCheck({
  1176. kind: "regex",
  1177. regex: regex,
  1178. ...errorUtil.errToObj(message),
  1179. });
  1180. }
  1181. includes(value, options) {
  1182. return this._addCheck({
  1183. kind: "includes",
  1184. value: value,
  1185. position: options === null || options === void 0 ? void 0 : options.position,
  1186. ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
  1187. });
  1188. }
  1189. startsWith(value, message) {
  1190. return this._addCheck({
  1191. kind: "startsWith",
  1192. value: value,
  1193. ...errorUtil.errToObj(message),
  1194. });
  1195. }
  1196. endsWith(value, message) {
  1197. return this._addCheck({
  1198. kind: "endsWith",
  1199. value: value,
  1200. ...errorUtil.errToObj(message),
  1201. });
  1202. }
  1203. min(minLength, message) {
  1204. return this._addCheck({
  1205. kind: "min",
  1206. value: minLength,
  1207. ...errorUtil.errToObj(message),
  1208. });
  1209. }
  1210. max(maxLength, message) {
  1211. return this._addCheck({
  1212. kind: "max",
  1213. value: maxLength,
  1214. ...errorUtil.errToObj(message),
  1215. });
  1216. }
  1217. length(len, message) {
  1218. return this._addCheck({
  1219. kind: "length",
  1220. value: len,
  1221. ...errorUtil.errToObj(message),
  1222. });
  1223. }
  1224. get isDatetime() {
  1225. return !!this._def.checks.find((ch) => ch.kind === "datetime");
  1226. }
  1227. get isEmail() {
  1228. return !!this._def.checks.find((ch) => ch.kind === "email");
  1229. }
  1230. get isURL() {
  1231. return !!this._def.checks.find((ch) => ch.kind === "url");
  1232. }
  1233. get isEmoji() {
  1234. return !!this._def.checks.find((ch) => ch.kind === "emoji");
  1235. }
  1236. get isUUID() {
  1237. return !!this._def.checks.find((ch) => ch.kind === "uuid");
  1238. }
  1239. get isCUID() {
  1240. return !!this._def.checks.find((ch) => ch.kind === "cuid");
  1241. }
  1242. get isCUID2() {
  1243. return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  1244. }
  1245. get isULID() {
  1246. return !!this._def.checks.find((ch) => ch.kind === "ulid");
  1247. }
  1248. get isIP() {
  1249. return !!this._def.checks.find((ch) => ch.kind === "ip");
  1250. }
  1251. get minLength() {
  1252. let min = null;
  1253. for (const ch of this._def.checks) {
  1254. if (ch.kind === "min") {
  1255. if (min === null || ch.value > min)
  1256. min = ch.value;
  1257. }
  1258. }
  1259. return min;
  1260. }
  1261. get maxLength() {
  1262. let max = null;
  1263. for (const ch of this._def.checks) {
  1264. if (ch.kind === "max") {
  1265. if (max === null || ch.value < max)
  1266. max = ch.value;
  1267. }
  1268. }
  1269. return max;
  1270. }
  1271. }
  1272. ZodString.create = (params) => {
  1273. var _a;
  1274. return new ZodString({
  1275. checks: [],
  1276. typeName: exports.ZodFirstPartyTypeKind.ZodString,
  1277. coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
  1278. ...processCreateParams(params),
  1279. });
  1280. };
  1281. // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
  1282. function floatSafeRemainder(val, step) {
  1283. const valDecCount = (val.toString().split(".")[1] || "").length;
  1284. const stepDecCount = (step.toString().split(".")[1] || "").length;
  1285. const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  1286. const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
  1287. const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
  1288. return (valInt % stepInt) / Math.pow(10, decCount);
  1289. }
  1290. class ZodNumber extends ZodType {
  1291. constructor() {
  1292. super(...arguments);
  1293. this.min = this.gte;
  1294. this.max = this.lte;
  1295. this.step = this.multipleOf;
  1296. }
  1297. _parse(input) {
  1298. if (this._def.coerce) {
  1299. input.data = Number(input.data);
  1300. }
  1301. const parsedType = this._getType(input);
  1302. if (parsedType !== ZodParsedType.number) {
  1303. const ctx = this._getOrReturnCtx(input);
  1304. addIssueToContext(ctx, {
  1305. code: ZodIssueCode.invalid_type,
  1306. expected: ZodParsedType.number,
  1307. received: ctx.parsedType,
  1308. });
  1309. return INVALID;
  1310. }
  1311. let ctx = undefined;
  1312. const status = new ParseStatus();
  1313. for (const check of this._def.checks) {
  1314. if (check.kind === "int") {
  1315. if (!exports.util.isInteger(input.data)) {
  1316. ctx = this._getOrReturnCtx(input, ctx);
  1317. addIssueToContext(ctx, {
  1318. code: ZodIssueCode.invalid_type,
  1319. expected: "integer",
  1320. received: "float",
  1321. message: check.message,
  1322. });
  1323. status.dirty();
  1324. }
  1325. }
  1326. else if (check.kind === "min") {
  1327. const tooSmall = check.inclusive
  1328. ? input.data < check.value
  1329. : input.data <= check.value;
  1330. if (tooSmall) {
  1331. ctx = this._getOrReturnCtx(input, ctx);
  1332. addIssueToContext(ctx, {
  1333. code: ZodIssueCode.too_small,
  1334. minimum: check.value,
  1335. type: "number",
  1336. inclusive: check.inclusive,
  1337. exact: false,
  1338. message: check.message,
  1339. });
  1340. status.dirty();
  1341. }
  1342. }
  1343. else if (check.kind === "max") {
  1344. const tooBig = check.inclusive
  1345. ? input.data > check.value
  1346. : input.data >= check.value;
  1347. if (tooBig) {
  1348. ctx = this._getOrReturnCtx(input, ctx);
  1349. addIssueToContext(ctx, {
  1350. code: ZodIssueCode.too_big,
  1351. maximum: check.value,
  1352. type: "number",
  1353. inclusive: check.inclusive,
  1354. exact: false,
  1355. message: check.message,
  1356. });
  1357. status.dirty();
  1358. }
  1359. }
  1360. else if (check.kind === "multipleOf") {
  1361. if (floatSafeRemainder(input.data, check.value) !== 0) {
  1362. ctx = this._getOrReturnCtx(input, ctx);
  1363. addIssueToContext(ctx, {
  1364. code: ZodIssueCode.not_multiple_of,
  1365. multipleOf: check.value,
  1366. message: check.message,
  1367. });
  1368. status.dirty();
  1369. }
  1370. }
  1371. else if (check.kind === "finite") {
  1372. if (!Number.isFinite(input.data)) {
  1373. ctx = this._getOrReturnCtx(input, ctx);
  1374. addIssueToContext(ctx, {
  1375. code: ZodIssueCode.not_finite,
  1376. message: check.message,
  1377. });
  1378. status.dirty();
  1379. }
  1380. }
  1381. else {
  1382. exports.util.assertNever(check);
  1383. }
  1384. }
  1385. return { status: status.value, value: input.data };
  1386. }
  1387. gte(value, message) {
  1388. return this.setLimit("min", value, true, errorUtil.toString(message));
  1389. }
  1390. gt(value, message) {
  1391. return this.setLimit("min", value, false, errorUtil.toString(message));
  1392. }
  1393. lte(value, message) {
  1394. return this.setLimit("max", value, true, errorUtil.toString(message));
  1395. }
  1396. lt(value, message) {
  1397. return this.setLimit("max", value, false, errorUtil.toString(message));
  1398. }
  1399. setLimit(kind, value, inclusive, message) {
  1400. return new ZodNumber({
  1401. ...this._def,
  1402. checks: [
  1403. ...this._def.checks,
  1404. {
  1405. kind,
  1406. value,
  1407. inclusive,
  1408. message: errorUtil.toString(message),
  1409. },
  1410. ],
  1411. });
  1412. }
  1413. _addCheck(check) {
  1414. return new ZodNumber({
  1415. ...this._def,
  1416. checks: [...this._def.checks, check],
  1417. });
  1418. }
  1419. int(message) {
  1420. return this._addCheck({
  1421. kind: "int",
  1422. message: errorUtil.toString(message),
  1423. });
  1424. }
  1425. positive(message) {
  1426. return this._addCheck({
  1427. kind: "min",
  1428. value: 0,
  1429. inclusive: false,
  1430. message: errorUtil.toString(message),
  1431. });
  1432. }
  1433. negative(message) {
  1434. return this._addCheck({
  1435. kind: "max",
  1436. value: 0,
  1437. inclusive: false,
  1438. message: errorUtil.toString(message),
  1439. });
  1440. }
  1441. nonpositive(message) {
  1442. return this._addCheck({
  1443. kind: "max",
  1444. value: 0,
  1445. inclusive: true,
  1446. message: errorUtil.toString(message),
  1447. });
  1448. }
  1449. nonnegative(message) {
  1450. return this._addCheck({
  1451. kind: "min",
  1452. value: 0,
  1453. inclusive: true,
  1454. message: errorUtil.toString(message),
  1455. });
  1456. }
  1457. multipleOf(value, message) {
  1458. return this._addCheck({
  1459. kind: "multipleOf",
  1460. value: value,
  1461. message: errorUtil.toString(message),
  1462. });
  1463. }
  1464. finite(message) {
  1465. return this._addCheck({
  1466. kind: "finite",
  1467. message: errorUtil.toString(message),
  1468. });
  1469. }
  1470. safe(message) {
  1471. return this._addCheck({
  1472. kind: "min",
  1473. inclusive: true,
  1474. value: Number.MIN_SAFE_INTEGER,
  1475. message: errorUtil.toString(message),
  1476. })._addCheck({
  1477. kind: "max",
  1478. inclusive: true,
  1479. value: Number.MAX_SAFE_INTEGER,
  1480. message: errorUtil.toString(message),
  1481. });
  1482. }
  1483. get minValue() {
  1484. let min = null;
  1485. for (const ch of this._def.checks) {
  1486. if (ch.kind === "min") {
  1487. if (min === null || ch.value > min)
  1488. min = ch.value;
  1489. }
  1490. }
  1491. return min;
  1492. }
  1493. get maxValue() {
  1494. let max = null;
  1495. for (const ch of this._def.checks) {
  1496. if (ch.kind === "max") {
  1497. if (max === null || ch.value < max)
  1498. max = ch.value;
  1499. }
  1500. }
  1501. return max;
  1502. }
  1503. get isInt() {
  1504. return !!this._def.checks.find((ch) => ch.kind === "int" ||
  1505. (ch.kind === "multipleOf" && exports.util.isInteger(ch.value)));
  1506. }
  1507. get isFinite() {
  1508. let max = null, min = null;
  1509. for (const ch of this._def.checks) {
  1510. if (ch.kind === "finite" ||
  1511. ch.kind === "int" ||
  1512. ch.kind === "multipleOf") {
  1513. return true;
  1514. }
  1515. else if (ch.kind === "min") {
  1516. if (min === null || ch.value > min)
  1517. min = ch.value;
  1518. }
  1519. else if (ch.kind === "max") {
  1520. if (max === null || ch.value < max)
  1521. max = ch.value;
  1522. }
  1523. }
  1524. return Number.isFinite(min) && Number.isFinite(max);
  1525. }
  1526. }
  1527. ZodNumber.create = (params) => {
  1528. return new ZodNumber({
  1529. checks: [],
  1530. typeName: exports.ZodFirstPartyTypeKind.ZodNumber,
  1531. coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
  1532. ...processCreateParams(params),
  1533. });
  1534. };
  1535. class ZodBigInt extends ZodType {
  1536. constructor() {
  1537. super(...arguments);
  1538. this.min = this.gte;
  1539. this.max = this.lte;
  1540. }
  1541. _parse(input) {
  1542. if (this._def.coerce) {
  1543. input.data = BigInt(input.data);
  1544. }
  1545. const parsedType = this._getType(input);
  1546. if (parsedType !== ZodParsedType.bigint) {
  1547. const ctx = this._getOrReturnCtx(input);
  1548. addIssueToContext(ctx, {
  1549. code: ZodIssueCode.invalid_type,
  1550. expected: ZodParsedType.bigint,
  1551. received: ctx.parsedType,
  1552. });
  1553. return INVALID;
  1554. }
  1555. let ctx = undefined;
  1556. const status = new ParseStatus();
  1557. for (const check of this._def.checks) {
  1558. if (check.kind === "min") {
  1559. const tooSmall = check.inclusive
  1560. ? input.data < check.value
  1561. : input.data <= check.value;
  1562. if (tooSmall) {
  1563. ctx = this._getOrReturnCtx(input, ctx);
  1564. addIssueToContext(ctx, {
  1565. code: ZodIssueCode.too_small,
  1566. type: "bigint",
  1567. minimum: check.value,
  1568. inclusive: check.inclusive,
  1569. message: check.message,
  1570. });
  1571. status.dirty();
  1572. }
  1573. }
  1574. else if (check.kind === "max") {
  1575. const tooBig = check.inclusive
  1576. ? input.data > check.value
  1577. : input.data >= check.value;
  1578. if (tooBig) {
  1579. ctx = this._getOrReturnCtx(input, ctx);
  1580. addIssueToContext(ctx, {
  1581. code: ZodIssueCode.too_big,
  1582. type: "bigint",
  1583. maximum: check.value,
  1584. inclusive: check.inclusive,
  1585. message: check.message,
  1586. });
  1587. status.dirty();
  1588. }
  1589. }
  1590. else if (check.kind === "multipleOf") {
  1591. if (input.data % check.value !== BigInt(0)) {
  1592. ctx = this._getOrReturnCtx(input, ctx);
  1593. addIssueToContext(ctx, {
  1594. code: ZodIssueCode.not_multiple_of,
  1595. multipleOf: check.value,
  1596. message: check.message,
  1597. });
  1598. status.dirty();
  1599. }
  1600. }
  1601. else {
  1602. exports.util.assertNever(check);
  1603. }
  1604. }
  1605. return { status: status.value, value: input.data };
  1606. }
  1607. gte(value, message) {
  1608. return this.setLimit("min", value, true, errorUtil.toString(message));
  1609. }
  1610. gt(value, message) {
  1611. return this.setLimit("min", value, false, errorUtil.toString(message));
  1612. }
  1613. lte(value, message) {
  1614. return this.setLimit("max", value, true, errorUtil.toString(message));
  1615. }
  1616. lt(value, message) {
  1617. return this.setLimit("max", value, false, errorUtil.toString(message));
  1618. }
  1619. setLimit(kind, value, inclusive, message) {
  1620. return new ZodBigInt({
  1621. ...this._def,
  1622. checks: [
  1623. ...this._def.checks,
  1624. {
  1625. kind,
  1626. value,
  1627. inclusive,
  1628. message: errorUtil.toString(message),
  1629. },
  1630. ],
  1631. });
  1632. }
  1633. _addCheck(check) {
  1634. return new ZodBigInt({
  1635. ...this._def,
  1636. checks: [...this._def.checks, check],
  1637. });
  1638. }
  1639. positive(message) {
  1640. return this._addCheck({
  1641. kind: "min",
  1642. value: BigInt(0),
  1643. inclusive: false,
  1644. message: errorUtil.toString(message),
  1645. });
  1646. }
  1647. negative(message) {
  1648. return this._addCheck({
  1649. kind: "max",
  1650. value: BigInt(0),
  1651. inclusive: false,
  1652. message: errorUtil.toString(message),
  1653. });
  1654. }
  1655. nonpositive(message) {
  1656. return this._addCheck({
  1657. kind: "max",
  1658. value: BigInt(0),
  1659. inclusive: true,
  1660. message: errorUtil.toString(message),
  1661. });
  1662. }
  1663. nonnegative(message) {
  1664. return this._addCheck({
  1665. kind: "min",
  1666. value: BigInt(0),
  1667. inclusive: true,
  1668. message: errorUtil.toString(message),
  1669. });
  1670. }
  1671. multipleOf(value, message) {
  1672. return this._addCheck({
  1673. kind: "multipleOf",
  1674. value,
  1675. message: errorUtil.toString(message),
  1676. });
  1677. }
  1678. get minValue() {
  1679. let min = null;
  1680. for (const ch of this._def.checks) {
  1681. if (ch.kind === "min") {
  1682. if (min === null || ch.value > min)
  1683. min = ch.value;
  1684. }
  1685. }
  1686. return min;
  1687. }
  1688. get maxValue() {
  1689. let max = null;
  1690. for (const ch of this._def.checks) {
  1691. if (ch.kind === "max") {
  1692. if (max === null || ch.value < max)
  1693. max = ch.value;
  1694. }
  1695. }
  1696. return max;
  1697. }
  1698. }
  1699. ZodBigInt.create = (params) => {
  1700. var _a;
  1701. return new ZodBigInt({
  1702. checks: [],
  1703. typeName: exports.ZodFirstPartyTypeKind.ZodBigInt,
  1704. coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
  1705. ...processCreateParams(params),
  1706. });
  1707. };
  1708. class ZodBoolean extends ZodType {
  1709. _parse(input) {
  1710. if (this._def.coerce) {
  1711. input.data = Boolean(input.data);
  1712. }
  1713. const parsedType = this._getType(input);
  1714. if (parsedType !== ZodParsedType.boolean) {
  1715. const ctx = this._getOrReturnCtx(input);
  1716. addIssueToContext(ctx, {
  1717. code: ZodIssueCode.invalid_type,
  1718. expected: ZodParsedType.boolean,
  1719. received: ctx.parsedType,
  1720. });
  1721. return INVALID;
  1722. }
  1723. return OK(input.data);
  1724. }
  1725. }
  1726. ZodBoolean.create = (params) => {
  1727. return new ZodBoolean({
  1728. typeName: exports.ZodFirstPartyTypeKind.ZodBoolean,
  1729. coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
  1730. ...processCreateParams(params),
  1731. });
  1732. };
  1733. class ZodDate extends ZodType {
  1734. _parse(input) {
  1735. if (this._def.coerce) {
  1736. input.data = new Date(input.data);
  1737. }
  1738. const parsedType = this._getType(input);
  1739. if (parsedType !== ZodParsedType.date) {
  1740. const ctx = this._getOrReturnCtx(input);
  1741. addIssueToContext(ctx, {
  1742. code: ZodIssueCode.invalid_type,
  1743. expected: ZodParsedType.date,
  1744. received: ctx.parsedType,
  1745. });
  1746. return INVALID;
  1747. }
  1748. if (isNaN(input.data.getTime())) {
  1749. const ctx = this._getOrReturnCtx(input);
  1750. addIssueToContext(ctx, {
  1751. code: ZodIssueCode.invalid_date,
  1752. });
  1753. return INVALID;
  1754. }
  1755. const status = new ParseStatus();
  1756. let ctx = undefined;
  1757. for (const check of this._def.checks) {
  1758. if (check.kind === "min") {
  1759. if (input.data.getTime() < check.value) {
  1760. ctx = this._getOrReturnCtx(input, ctx);
  1761. addIssueToContext(ctx, {
  1762. code: ZodIssueCode.too_small,
  1763. message: check.message,
  1764. inclusive: true,
  1765. exact: false,
  1766. minimum: check.value,
  1767. type: "date",
  1768. });
  1769. status.dirty();
  1770. }
  1771. }
  1772. else if (check.kind === "max") {
  1773. if (input.data.getTime() > check.value) {
  1774. ctx = this._getOrReturnCtx(input, ctx);
  1775. addIssueToContext(ctx, {
  1776. code: ZodIssueCode.too_big,
  1777. message: check.message,
  1778. inclusive: true,
  1779. exact: false,
  1780. maximum: check.value,
  1781. type: "date",
  1782. });
  1783. status.dirty();
  1784. }
  1785. }
  1786. else {
  1787. exports.util.assertNever(check);
  1788. }
  1789. }
  1790. return {
  1791. status: status.value,
  1792. value: new Date(input.data.getTime()),
  1793. };
  1794. }
  1795. _addCheck(check) {
  1796. return new ZodDate({
  1797. ...this._def,
  1798. checks: [...this._def.checks, check],
  1799. });
  1800. }
  1801. min(minDate, message) {
  1802. return this._addCheck({
  1803. kind: "min",
  1804. value: minDate.getTime(),
  1805. message: errorUtil.toString(message),
  1806. });
  1807. }
  1808. max(maxDate, message) {
  1809. return this._addCheck({
  1810. kind: "max",
  1811. value: maxDate.getTime(),
  1812. message: errorUtil.toString(message),
  1813. });
  1814. }
  1815. get minDate() {
  1816. let min = null;
  1817. for (const ch of this._def.checks) {
  1818. if (ch.kind === "min") {
  1819. if (min === null || ch.value > min)
  1820. min = ch.value;
  1821. }
  1822. }
  1823. return min != null ? new Date(min) : null;
  1824. }
  1825. get maxDate() {
  1826. let max = null;
  1827. for (const ch of this._def.checks) {
  1828. if (ch.kind === "max") {
  1829. if (max === null || ch.value < max)
  1830. max = ch.value;
  1831. }
  1832. }
  1833. return max != null ? new Date(max) : null;
  1834. }
  1835. }
  1836. ZodDate.create = (params) => {
  1837. return new ZodDate({
  1838. checks: [],
  1839. coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
  1840. typeName: exports.ZodFirstPartyTypeKind.ZodDate,
  1841. ...processCreateParams(params),
  1842. });
  1843. };
  1844. class ZodSymbol extends ZodType {
  1845. _parse(input) {
  1846. const parsedType = this._getType(input);
  1847. if (parsedType !== ZodParsedType.symbol) {
  1848. const ctx = this._getOrReturnCtx(input);
  1849. addIssueToContext(ctx, {
  1850. code: ZodIssueCode.invalid_type,
  1851. expected: ZodParsedType.symbol,
  1852. received: ctx.parsedType,
  1853. });
  1854. return INVALID;
  1855. }
  1856. return OK(input.data);
  1857. }
  1858. }
  1859. ZodSymbol.create = (params) => {
  1860. return new ZodSymbol({
  1861. typeName: exports.ZodFirstPartyTypeKind.ZodSymbol,
  1862. ...processCreateParams(params),
  1863. });
  1864. };
  1865. class ZodUndefined extends ZodType {
  1866. _parse(input) {
  1867. const parsedType = this._getType(input);
  1868. if (parsedType !== ZodParsedType.undefined) {
  1869. const ctx = this._getOrReturnCtx(input);
  1870. addIssueToContext(ctx, {
  1871. code: ZodIssueCode.invalid_type,
  1872. expected: ZodParsedType.undefined,
  1873. received: ctx.parsedType,
  1874. });
  1875. return INVALID;
  1876. }
  1877. return OK(input.data);
  1878. }
  1879. }
  1880. ZodUndefined.create = (params) => {
  1881. return new ZodUndefined({
  1882. typeName: exports.ZodFirstPartyTypeKind.ZodUndefined,
  1883. ...processCreateParams(params),
  1884. });
  1885. };
  1886. class ZodNull extends ZodType {
  1887. _parse(input) {
  1888. const parsedType = this._getType(input);
  1889. if (parsedType !== ZodParsedType.null) {
  1890. const ctx = this._getOrReturnCtx(input);
  1891. addIssueToContext(ctx, {
  1892. code: ZodIssueCode.invalid_type,
  1893. expected: ZodParsedType.null,
  1894. received: ctx.parsedType,
  1895. });
  1896. return INVALID;
  1897. }
  1898. return OK(input.data);
  1899. }
  1900. }
  1901. ZodNull.create = (params) => {
  1902. return new ZodNull({
  1903. typeName: exports.ZodFirstPartyTypeKind.ZodNull,
  1904. ...processCreateParams(params),
  1905. });
  1906. };
  1907. class ZodAny extends ZodType {
  1908. constructor() {
  1909. super(...arguments);
  1910. // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
  1911. this._any = true;
  1912. }
  1913. _parse(input) {
  1914. return OK(input.data);
  1915. }
  1916. }
  1917. ZodAny.create = (params) => {
  1918. return new ZodAny({
  1919. typeName: exports.ZodFirstPartyTypeKind.ZodAny,
  1920. ...processCreateParams(params),
  1921. });
  1922. };
  1923. class ZodUnknown extends ZodType {
  1924. constructor() {
  1925. super(...arguments);
  1926. // required
  1927. this._unknown = true;
  1928. }
  1929. _parse(input) {
  1930. return OK(input.data);
  1931. }
  1932. }
  1933. ZodUnknown.create = (params) => {
  1934. return new ZodUnknown({
  1935. typeName: exports.ZodFirstPartyTypeKind.ZodUnknown,
  1936. ...processCreateParams(params),
  1937. });
  1938. };
  1939. class ZodNever extends ZodType {
  1940. _parse(input) {
  1941. const ctx = this._getOrReturnCtx(input);
  1942. addIssueToContext(ctx, {
  1943. code: ZodIssueCode.invalid_type,
  1944. expected: ZodParsedType.never,
  1945. received: ctx.parsedType,
  1946. });
  1947. return INVALID;
  1948. }
  1949. }
  1950. ZodNever.create = (params) => {
  1951. return new ZodNever({
  1952. typeName: exports.ZodFirstPartyTypeKind.ZodNever,
  1953. ...processCreateParams(params),
  1954. });
  1955. };
  1956. class ZodVoid extends ZodType {
  1957. _parse(input) {
  1958. const parsedType = this._getType(input);
  1959. if (parsedType !== ZodParsedType.undefined) {
  1960. const ctx = this._getOrReturnCtx(input);
  1961. addIssueToContext(ctx, {
  1962. code: ZodIssueCode.invalid_type,
  1963. expected: ZodParsedType.void,
  1964. received: ctx.parsedType,
  1965. });
  1966. return INVALID;
  1967. }
  1968. return OK(input.data);
  1969. }
  1970. }
  1971. ZodVoid.create = (params) => {
  1972. return new ZodVoid({
  1973. typeName: exports.ZodFirstPartyTypeKind.ZodVoid,
  1974. ...processCreateParams(params),
  1975. });
  1976. };
  1977. class ZodArray extends ZodType {
  1978. _parse(input) {
  1979. const { ctx, status } = this._processInputParams(input);
  1980. const def = this._def;
  1981. if (ctx.parsedType !== ZodParsedType.array) {
  1982. addIssueToContext(ctx, {
  1983. code: ZodIssueCode.invalid_type,
  1984. expected: ZodParsedType.array,
  1985. received: ctx.parsedType,
  1986. });
  1987. return INVALID;
  1988. }
  1989. if (def.exactLength !== null) {
  1990. const tooBig = ctx.data.length > def.exactLength.value;
  1991. const tooSmall = ctx.data.length < def.exactLength.value;
  1992. if (tooBig || tooSmall) {
  1993. addIssueToContext(ctx, {
  1994. code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
  1995. minimum: (tooSmall ? def.exactLength.value : undefined),
  1996. maximum: (tooBig ? def.exactLength.value : undefined),
  1997. type: "array",
  1998. inclusive: true,
  1999. exact: true,
  2000. message: def.exactLength.message,
  2001. });
  2002. status.dirty();
  2003. }
  2004. }
  2005. if (def.minLength !== null) {
  2006. if (ctx.data.length < def.minLength.value) {
  2007. addIssueToContext(ctx, {
  2008. code: ZodIssueCode.too_small,
  2009. minimum: def.minLength.value,
  2010. type: "array",
  2011. inclusive: true,
  2012. exact: false,
  2013. message: def.minLength.message,
  2014. });
  2015. status.dirty();
  2016. }
  2017. }
  2018. if (def.maxLength !== null) {
  2019. if (ctx.data.length > def.maxLength.value) {
  2020. addIssueToContext(ctx, {
  2021. code: ZodIssueCode.too_big,
  2022. maximum: def.maxLength.value,
  2023. type: "array",
  2024. inclusive: true,
  2025. exact: false,
  2026. message: def.maxLength.message,
  2027. });
  2028. status.dirty();
  2029. }
  2030. }
  2031. if (ctx.common.async) {
  2032. return Promise.all([...ctx.data].map((item, i) => {
  2033. return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
  2034. })).then((result) => {
  2035. return ParseStatus.mergeArray(status, result);
  2036. });
  2037. }
  2038. const result = [...ctx.data].map((item, i) => {
  2039. return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
  2040. });
  2041. return ParseStatus.mergeArray(status, result);
  2042. }
  2043. get element() {
  2044. return this._def.type;
  2045. }
  2046. min(minLength, message) {
  2047. return new ZodArray({
  2048. ...this._def,
  2049. minLength: { value: minLength, message: errorUtil.toString(message) },
  2050. });
  2051. }
  2052. max(maxLength, message) {
  2053. return new ZodArray({
  2054. ...this._def,
  2055. maxLength: { value: maxLength, message: errorUtil.toString(message) },
  2056. });
  2057. }
  2058. length(len, message) {
  2059. return new ZodArray({
  2060. ...this._def,
  2061. exactLength: { value: len, message: errorUtil.toString(message) },
  2062. });
  2063. }
  2064. nonempty(message) {
  2065. return this.min(1, message);
  2066. }
  2067. }
  2068. ZodArray.create = (schema, params) => {
  2069. return new ZodArray({
  2070. type: schema,
  2071. minLength: null,
  2072. maxLength: null,
  2073. exactLength: null,
  2074. typeName: exports.ZodFirstPartyTypeKind.ZodArray,
  2075. ...processCreateParams(params),
  2076. });
  2077. };
  2078. function deepPartialify(schema) {
  2079. if (schema instanceof ZodObject) {
  2080. const newShape = {};
  2081. for (const key in schema.shape) {
  2082. const fieldSchema = schema.shape[key];
  2083. newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
  2084. }
  2085. return new ZodObject({
  2086. ...schema._def,
  2087. shape: () => newShape,
  2088. });
  2089. }
  2090. else if (schema instanceof ZodArray) {
  2091. return new ZodArray({
  2092. ...schema._def,
  2093. type: deepPartialify(schema.element),
  2094. });
  2095. }
  2096. else if (schema instanceof ZodOptional) {
  2097. return ZodOptional.create(deepPartialify(schema.unwrap()));
  2098. }
  2099. else if (schema instanceof ZodNullable) {
  2100. return ZodNullable.create(deepPartialify(schema.unwrap()));
  2101. }
  2102. else if (schema instanceof ZodTuple) {
  2103. return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
  2104. }
  2105. else {
  2106. return schema;
  2107. }
  2108. }
  2109. class ZodObject extends ZodType {
  2110. constructor() {
  2111. super(...arguments);
  2112. this._cached = null;
  2113. /**
  2114. * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
  2115. * If you want to pass through unknown properties, use `.passthrough()` instead.
  2116. */
  2117. this.nonstrict = this.passthrough;
  2118. // extend<
  2119. // Augmentation extends ZodRawShape,
  2120. // NewOutput extends util.flatten<{
  2121. // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  2122. // ? Augmentation[k]["_output"]
  2123. // : k extends keyof Output
  2124. // ? Output[k]
  2125. // : never;
  2126. // }>,
  2127. // NewInput extends util.flatten<{
  2128. // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  2129. // ? Augmentation[k]["_input"]
  2130. // : k extends keyof Input
  2131. // ? Input[k]
  2132. // : never;
  2133. // }>
  2134. // >(
  2135. // augmentation: Augmentation
  2136. // ): ZodObject<
  2137. // extendShape<T, Augmentation>,
  2138. // UnknownKeys,
  2139. // Catchall,
  2140. // NewOutput,
  2141. // NewInput
  2142. // > {
  2143. // return new ZodObject({
  2144. // ...this._def,
  2145. // shape: () => ({
  2146. // ...this._def.shape(),
  2147. // ...augmentation,
  2148. // }),
  2149. // }) as any;
  2150. // }
  2151. /**
  2152. * @deprecated Use `.extend` instead
  2153. * */
  2154. this.augment = this.extend;
  2155. }
  2156. _getCached() {
  2157. if (this._cached !== null)
  2158. return this._cached;
  2159. const shape = this._def.shape();
  2160. const keys = exports.util.objectKeys(shape);
  2161. return (this._cached = { shape, keys });
  2162. }
  2163. _parse(input) {
  2164. const parsedType = this._getType(input);
  2165. if (parsedType !== ZodParsedType.object) {
  2166. const ctx = this._getOrReturnCtx(input);
  2167. addIssueToContext(ctx, {
  2168. code: ZodIssueCode.invalid_type,
  2169. expected: ZodParsedType.object,
  2170. received: ctx.parsedType,
  2171. });
  2172. return INVALID;
  2173. }
  2174. const { status, ctx } = this._processInputParams(input);
  2175. const { shape, keys: shapeKeys } = this._getCached();
  2176. const extraKeys = [];
  2177. if (!(this._def.catchall instanceof ZodNever &&
  2178. this._def.unknownKeys === "strip")) {
  2179. for (const key in ctx.data) {
  2180. if (!shapeKeys.includes(key)) {
  2181. extraKeys.push(key);
  2182. }
  2183. }
  2184. }
  2185. const pairs = [];
  2186. for (const key of shapeKeys) {
  2187. const keyValidator = shape[key];
  2188. const value = ctx.data[key];
  2189. pairs.push({
  2190. key: { status: "valid", value: key },
  2191. value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
  2192. alwaysSet: key in ctx.data,
  2193. });
  2194. }
  2195. if (this._def.catchall instanceof ZodNever) {
  2196. const unknownKeys = this._def.unknownKeys;
  2197. if (unknownKeys === "passthrough") {
  2198. for (const key of extraKeys) {
  2199. pairs.push({
  2200. key: { status: "valid", value: key },
  2201. value: { status: "valid", value: ctx.data[key] },
  2202. });
  2203. }
  2204. }
  2205. else if (unknownKeys === "strict") {
  2206. if (extraKeys.length > 0) {
  2207. addIssueToContext(ctx, {
  2208. code: ZodIssueCode.unrecognized_keys,
  2209. keys: extraKeys,
  2210. });
  2211. status.dirty();
  2212. }
  2213. }
  2214. else if (unknownKeys === "strip") ;
  2215. else {
  2216. throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
  2217. }
  2218. }
  2219. else {
  2220. // run catchall validation
  2221. const catchall = this._def.catchall;
  2222. for (const key of extraKeys) {
  2223. const value = ctx.data[key];
  2224. pairs.push({
  2225. key: { status: "valid", value: key },
  2226. value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
  2227. ),
  2228. alwaysSet: key in ctx.data,
  2229. });
  2230. }
  2231. }
  2232. if (ctx.common.async) {
  2233. return Promise.resolve()
  2234. .then(async () => {
  2235. const syncPairs = [];
  2236. for (const pair of pairs) {
  2237. const key = await pair.key;
  2238. syncPairs.push({
  2239. key,
  2240. value: await pair.value,
  2241. alwaysSet: pair.alwaysSet,
  2242. });
  2243. }
  2244. return syncPairs;
  2245. })
  2246. .then((syncPairs) => {
  2247. return ParseStatus.mergeObjectSync(status, syncPairs);
  2248. });
  2249. }
  2250. else {
  2251. return ParseStatus.mergeObjectSync(status, pairs);
  2252. }
  2253. }
  2254. get shape() {
  2255. return this._def.shape();
  2256. }
  2257. strict(message) {
  2258. errorUtil.errToObj;
  2259. return new ZodObject({
  2260. ...this._def,
  2261. unknownKeys: "strict",
  2262. ...(message !== undefined
  2263. ? {
  2264. errorMap: (issue, ctx) => {
  2265. var _a, _b, _c, _d;
  2266. const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
  2267. if (issue.code === "unrecognized_keys")
  2268. return {
  2269. message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,
  2270. };
  2271. return {
  2272. message: defaultError,
  2273. };
  2274. },
  2275. }
  2276. : {}),
  2277. });
  2278. }
  2279. strip() {
  2280. return new ZodObject({
  2281. ...this._def,
  2282. unknownKeys: "strip",
  2283. });
  2284. }
  2285. passthrough() {
  2286. return new ZodObject({
  2287. ...this._def,
  2288. unknownKeys: "passthrough",
  2289. });
  2290. }
  2291. // const AugmentFactory =
  2292. // <Def extends ZodObjectDef>(def: Def) =>
  2293. // <Augmentation extends ZodRawShape>(
  2294. // augmentation: Augmentation
  2295. // ): ZodObject<
  2296. // extendShape<ReturnType<Def["shape"]>, Augmentation>,
  2297. // Def["unknownKeys"],
  2298. // Def["catchall"]
  2299. // > => {
  2300. // return new ZodObject({
  2301. // ...def,
  2302. // shape: () => ({
  2303. // ...def.shape(),
  2304. // ...augmentation,
  2305. // }),
  2306. // }) as any;
  2307. // };
  2308. extend(augmentation) {
  2309. return new ZodObject({
  2310. ...this._def,
  2311. shape: () => ({
  2312. ...this._def.shape(),
  2313. ...augmentation,
  2314. }),
  2315. });
  2316. }
  2317. /**
  2318. * Prior to zod@1.0.12 there was a bug in the
  2319. * inferred type of merged objects. Please
  2320. * upgrade if you are experiencing issues.
  2321. */
  2322. merge(merging) {
  2323. const merged = new ZodObject({
  2324. unknownKeys: merging._def.unknownKeys,
  2325. catchall: merging._def.catchall,
  2326. shape: () => ({
  2327. ...this._def.shape(),
  2328. ...merging._def.shape(),
  2329. }),
  2330. typeName: exports.ZodFirstPartyTypeKind.ZodObject,
  2331. });
  2332. return merged;
  2333. }
  2334. // merge<
  2335. // Incoming extends AnyZodObject,
  2336. // Augmentation extends Incoming["shape"],
  2337. // NewOutput extends {
  2338. // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  2339. // ? Augmentation[k]["_output"]
  2340. // : k extends keyof Output
  2341. // ? Output[k]
  2342. // : never;
  2343. // },
  2344. // NewInput extends {
  2345. // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  2346. // ? Augmentation[k]["_input"]
  2347. // : k extends keyof Input
  2348. // ? Input[k]
  2349. // : never;
  2350. // }
  2351. // >(
  2352. // merging: Incoming
  2353. // ): ZodObject<
  2354. // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  2355. // Incoming["_def"]["unknownKeys"],
  2356. // Incoming["_def"]["catchall"],
  2357. // NewOutput,
  2358. // NewInput
  2359. // > {
  2360. // const merged: any = new ZodObject({
  2361. // unknownKeys: merging._def.unknownKeys,
  2362. // catchall: merging._def.catchall,
  2363. // shape: () =>
  2364. // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  2365. // typeName: ZodFirstPartyTypeKind.ZodObject,
  2366. // }) as any;
  2367. // return merged;
  2368. // }
  2369. setKey(key, schema) {
  2370. return this.augment({ [key]: schema });
  2371. }
  2372. // merge<Incoming extends AnyZodObject>(
  2373. // merging: Incoming
  2374. // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  2375. // ZodObject<
  2376. // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  2377. // Incoming["_def"]["unknownKeys"],
  2378. // Incoming["_def"]["catchall"]
  2379. // > {
  2380. // // const mergedShape = objectUtil.mergeShapes(
  2381. // // this._def.shape(),
  2382. // // merging._def.shape()
  2383. // // );
  2384. // const merged: any = new ZodObject({
  2385. // unknownKeys: merging._def.unknownKeys,
  2386. // catchall: merging._def.catchall,
  2387. // shape: () =>
  2388. // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  2389. // typeName: ZodFirstPartyTypeKind.ZodObject,
  2390. // }) as any;
  2391. // return merged;
  2392. // }
  2393. catchall(index) {
  2394. return new ZodObject({
  2395. ...this._def,
  2396. catchall: index,
  2397. });
  2398. }
  2399. pick(mask) {
  2400. const shape = {};
  2401. exports.util.objectKeys(mask).forEach((key) => {
  2402. if (mask[key] && this.shape[key]) {
  2403. shape[key] = this.shape[key];
  2404. }
  2405. });
  2406. return new ZodObject({
  2407. ...this._def,
  2408. shape: () => shape,
  2409. });
  2410. }
  2411. omit(mask) {
  2412. const shape = {};
  2413. exports.util.objectKeys(this.shape).forEach((key) => {
  2414. if (!mask[key]) {
  2415. shape[key] = this.shape[key];
  2416. }
  2417. });
  2418. return new ZodObject({
  2419. ...this._def,
  2420. shape: () => shape,
  2421. });
  2422. }
  2423. /**
  2424. * @deprecated
  2425. */
  2426. deepPartial() {
  2427. return deepPartialify(this);
  2428. }
  2429. partial(mask) {
  2430. const newShape = {};
  2431. exports.util.objectKeys(this.shape).forEach((key) => {
  2432. const fieldSchema = this.shape[key];
  2433. if (mask && !mask[key]) {
  2434. newShape[key] = fieldSchema;
  2435. }
  2436. else {
  2437. newShape[key] = fieldSchema.optional();
  2438. }
  2439. });
  2440. return new ZodObject({
  2441. ...this._def,
  2442. shape: () => newShape,
  2443. });
  2444. }
  2445. required(mask) {
  2446. const newShape = {};
  2447. exports.util.objectKeys(this.shape).forEach((key) => {
  2448. if (mask && !mask[key]) {
  2449. newShape[key] = this.shape[key];
  2450. }
  2451. else {
  2452. const fieldSchema = this.shape[key];
  2453. let newField = fieldSchema;
  2454. while (newField instanceof ZodOptional) {
  2455. newField = newField._def.innerType;
  2456. }
  2457. newShape[key] = newField;
  2458. }
  2459. });
  2460. return new ZodObject({
  2461. ...this._def,
  2462. shape: () => newShape,
  2463. });
  2464. }
  2465. keyof() {
  2466. return createZodEnum(exports.util.objectKeys(this.shape));
  2467. }
  2468. }
  2469. ZodObject.create = (shape, params) => {
  2470. return new ZodObject({
  2471. shape: () => shape,
  2472. unknownKeys: "strip",
  2473. catchall: ZodNever.create(),
  2474. typeName: exports.ZodFirstPartyTypeKind.ZodObject,
  2475. ...processCreateParams(params),
  2476. });
  2477. };
  2478. ZodObject.strictCreate = (shape, params) => {
  2479. return new ZodObject({
  2480. shape: () => shape,
  2481. unknownKeys: "strict",
  2482. catchall: ZodNever.create(),
  2483. typeName: exports.ZodFirstPartyTypeKind.ZodObject,
  2484. ...processCreateParams(params),
  2485. });
  2486. };
  2487. ZodObject.lazycreate = (shape, params) => {
  2488. return new ZodObject({
  2489. shape,
  2490. unknownKeys: "strip",
  2491. catchall: ZodNever.create(),
  2492. typeName: exports.ZodFirstPartyTypeKind.ZodObject,
  2493. ...processCreateParams(params),
  2494. });
  2495. };
  2496. class ZodUnion extends ZodType {
  2497. _parse(input) {
  2498. const { ctx } = this._processInputParams(input);
  2499. const options = this._def.options;
  2500. function handleResults(results) {
  2501. // return first issue-free validation if it exists
  2502. for (const result of results) {
  2503. if (result.result.status === "valid") {
  2504. return result.result;
  2505. }
  2506. }
  2507. for (const result of results) {
  2508. if (result.result.status === "dirty") {
  2509. // add issues from dirty option
  2510. ctx.common.issues.push(...result.ctx.common.issues);
  2511. return result.result;
  2512. }
  2513. }
  2514. // return invalid
  2515. const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
  2516. addIssueToContext(ctx, {
  2517. code: ZodIssueCode.invalid_union,
  2518. unionErrors,
  2519. });
  2520. return INVALID;
  2521. }
  2522. if (ctx.common.async) {
  2523. return Promise.all(options.map(async (option) => {
  2524. const childCtx = {
  2525. ...ctx,
  2526. common: {
  2527. ...ctx.common,
  2528. issues: [],
  2529. },
  2530. parent: null,
  2531. };
  2532. return {
  2533. result: await option._parseAsync({
  2534. data: ctx.data,
  2535. path: ctx.path,
  2536. parent: childCtx,
  2537. }),
  2538. ctx: childCtx,
  2539. };
  2540. })).then(handleResults);
  2541. }
  2542. else {
  2543. let dirty = undefined;
  2544. const issues = [];
  2545. for (const option of options) {
  2546. const childCtx = {
  2547. ...ctx,
  2548. common: {
  2549. ...ctx.common,
  2550. issues: [],
  2551. },
  2552. parent: null,
  2553. };
  2554. const result = option._parseSync({
  2555. data: ctx.data,
  2556. path: ctx.path,
  2557. parent: childCtx,
  2558. });
  2559. if (result.status === "valid") {
  2560. return result;
  2561. }
  2562. else if (result.status === "dirty" && !dirty) {
  2563. dirty = { result, ctx: childCtx };
  2564. }
  2565. if (childCtx.common.issues.length) {
  2566. issues.push(childCtx.common.issues);
  2567. }
  2568. }
  2569. if (dirty) {
  2570. ctx.common.issues.push(...dirty.ctx.common.issues);
  2571. return dirty.result;
  2572. }
  2573. const unionErrors = issues.map((issues) => new ZodError(issues));
  2574. addIssueToContext(ctx, {
  2575. code: ZodIssueCode.invalid_union,
  2576. unionErrors,
  2577. });
  2578. return INVALID;
  2579. }
  2580. }
  2581. get options() {
  2582. return this._def.options;
  2583. }
  2584. }
  2585. ZodUnion.create = (types, params) => {
  2586. return new ZodUnion({
  2587. options: types,
  2588. typeName: exports.ZodFirstPartyTypeKind.ZodUnion,
  2589. ...processCreateParams(params),
  2590. });
  2591. };
  2592. /////////////////////////////////////////////////////
  2593. /////////////////////////////////////////////////////
  2594. ////////// //////////
  2595. ////////// ZodDiscriminatedUnion //////////
  2596. ////////// //////////
  2597. /////////////////////////////////////////////////////
  2598. /////////////////////////////////////////////////////
  2599. const getDiscriminator = (type) => {
  2600. if (type instanceof ZodLazy) {
  2601. return getDiscriminator(type.schema);
  2602. }
  2603. else if (type instanceof ZodEffects) {
  2604. return getDiscriminator(type.innerType());
  2605. }
  2606. else if (type instanceof ZodLiteral) {
  2607. return [type.value];
  2608. }
  2609. else if (type instanceof ZodEnum) {
  2610. return type.options;
  2611. }
  2612. else if (type instanceof ZodNativeEnum) {
  2613. // eslint-disable-next-line ban/ban
  2614. return Object.keys(type.enum);
  2615. }
  2616. else if (type instanceof ZodDefault) {
  2617. return getDiscriminator(type._def.innerType);
  2618. }
  2619. else if (type instanceof ZodUndefined) {
  2620. return [undefined];
  2621. }
  2622. else if (type instanceof ZodNull) {
  2623. return [null];
  2624. }
  2625. else {
  2626. return null;
  2627. }
  2628. };
  2629. class ZodDiscriminatedUnion extends ZodType {
  2630. _parse(input) {
  2631. const { ctx } = this._processInputParams(input);
  2632. if (ctx.parsedType !== ZodParsedType.object) {
  2633. addIssueToContext(ctx, {
  2634. code: ZodIssueCode.invalid_type,
  2635. expected: ZodParsedType.object,
  2636. received: ctx.parsedType,
  2637. });
  2638. return INVALID;
  2639. }
  2640. const discriminator = this.discriminator;
  2641. const discriminatorValue = ctx.data[discriminator];
  2642. const option = this.optionsMap.get(discriminatorValue);
  2643. if (!option) {
  2644. addIssueToContext(ctx, {
  2645. code: ZodIssueCode.invalid_union_discriminator,
  2646. options: Array.from(this.optionsMap.keys()),
  2647. path: [discriminator],
  2648. });
  2649. return INVALID;
  2650. }
  2651. if (ctx.common.async) {
  2652. return option._parseAsync({
  2653. data: ctx.data,
  2654. path: ctx.path,
  2655. parent: ctx,
  2656. });
  2657. }
  2658. else {
  2659. return option._parseSync({
  2660. data: ctx.data,
  2661. path: ctx.path,
  2662. parent: ctx,
  2663. });
  2664. }
  2665. }
  2666. get discriminator() {
  2667. return this._def.discriminator;
  2668. }
  2669. get options() {
  2670. return this._def.options;
  2671. }
  2672. get optionsMap() {
  2673. return this._def.optionsMap;
  2674. }
  2675. /**
  2676. * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
  2677. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
  2678. * have a different value for each object in the union.
  2679. * @param discriminator the name of the discriminator property
  2680. * @param types an array of object schemas
  2681. * @param params
  2682. */
  2683. static create(discriminator, options, params) {
  2684. // Get all the valid discriminator values
  2685. const optionsMap = new Map();
  2686. // try {
  2687. for (const type of options) {
  2688. const discriminatorValues = getDiscriminator(type.shape[discriminator]);
  2689. if (!discriminatorValues) {
  2690. throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
  2691. }
  2692. for (const value of discriminatorValues) {
  2693. if (optionsMap.has(value)) {
  2694. throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
  2695. }
  2696. optionsMap.set(value, type);
  2697. }
  2698. }
  2699. return new ZodDiscriminatedUnion({
  2700. typeName: exports.ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
  2701. discriminator,
  2702. options,
  2703. optionsMap,
  2704. ...processCreateParams(params),
  2705. });
  2706. }
  2707. }
  2708. function mergeValues(a, b) {
  2709. const aType = getParsedType(a);
  2710. const bType = getParsedType(b);
  2711. if (a === b) {
  2712. return { valid: true, data: a };
  2713. }
  2714. else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
  2715. const bKeys = exports.util.objectKeys(b);
  2716. const sharedKeys = exports.util
  2717. .objectKeys(a)
  2718. .filter((key) => bKeys.indexOf(key) !== -1);
  2719. const newObj = { ...a, ...b };
  2720. for (const key of sharedKeys) {
  2721. const sharedValue = mergeValues(a[key], b[key]);
  2722. if (!sharedValue.valid) {
  2723. return { valid: false };
  2724. }
  2725. newObj[key] = sharedValue.data;
  2726. }
  2727. return { valid: true, data: newObj };
  2728. }
  2729. else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
  2730. if (a.length !== b.length) {
  2731. return { valid: false };
  2732. }
  2733. const newArray = [];
  2734. for (let index = 0; index < a.length; index++) {
  2735. const itemA = a[index];
  2736. const itemB = b[index];
  2737. const sharedValue = mergeValues(itemA, itemB);
  2738. if (!sharedValue.valid) {
  2739. return { valid: false };
  2740. }
  2741. newArray.push(sharedValue.data);
  2742. }
  2743. return { valid: true, data: newArray };
  2744. }
  2745. else if (aType === ZodParsedType.date &&
  2746. bType === ZodParsedType.date &&
  2747. +a === +b) {
  2748. return { valid: true, data: a };
  2749. }
  2750. else {
  2751. return { valid: false };
  2752. }
  2753. }
  2754. class ZodIntersection extends ZodType {
  2755. _parse(input) {
  2756. const { status, ctx } = this._processInputParams(input);
  2757. const handleParsed = (parsedLeft, parsedRight) => {
  2758. if (isAborted(parsedLeft) || isAborted(parsedRight)) {
  2759. return INVALID;
  2760. }
  2761. const merged = mergeValues(parsedLeft.value, parsedRight.value);
  2762. if (!merged.valid) {
  2763. addIssueToContext(ctx, {
  2764. code: ZodIssueCode.invalid_intersection_types,
  2765. });
  2766. return INVALID;
  2767. }
  2768. if (isDirty(parsedLeft) || isDirty(parsedRight)) {
  2769. status.dirty();
  2770. }
  2771. return { status: status.value, value: merged.data };
  2772. };
  2773. if (ctx.common.async) {
  2774. return Promise.all([
  2775. this._def.left._parseAsync({
  2776. data: ctx.data,
  2777. path: ctx.path,
  2778. parent: ctx,
  2779. }),
  2780. this._def.right._parseAsync({
  2781. data: ctx.data,
  2782. path: ctx.path,
  2783. parent: ctx,
  2784. }),
  2785. ]).then(([left, right]) => handleParsed(left, right));
  2786. }
  2787. else {
  2788. return handleParsed(this._def.left._parseSync({
  2789. data: ctx.data,
  2790. path: ctx.path,
  2791. parent: ctx,
  2792. }), this._def.right._parseSync({
  2793. data: ctx.data,
  2794. path: ctx.path,
  2795. parent: ctx,
  2796. }));
  2797. }
  2798. }
  2799. }
  2800. ZodIntersection.create = (left, right, params) => {
  2801. return new ZodIntersection({
  2802. left: left,
  2803. right: right,
  2804. typeName: exports.ZodFirstPartyTypeKind.ZodIntersection,
  2805. ...processCreateParams(params),
  2806. });
  2807. };
  2808. class ZodTuple extends ZodType {
  2809. _parse(input) {
  2810. const { status, ctx } = this._processInputParams(input);
  2811. if (ctx.parsedType !== ZodParsedType.array) {
  2812. addIssueToContext(ctx, {
  2813. code: ZodIssueCode.invalid_type,
  2814. expected: ZodParsedType.array,
  2815. received: ctx.parsedType,
  2816. });
  2817. return INVALID;
  2818. }
  2819. if (ctx.data.length < this._def.items.length) {
  2820. addIssueToContext(ctx, {
  2821. code: ZodIssueCode.too_small,
  2822. minimum: this._def.items.length,
  2823. inclusive: true,
  2824. exact: false,
  2825. type: "array",
  2826. });
  2827. return INVALID;
  2828. }
  2829. const rest = this._def.rest;
  2830. if (!rest && ctx.data.length > this._def.items.length) {
  2831. addIssueToContext(ctx, {
  2832. code: ZodIssueCode.too_big,
  2833. maximum: this._def.items.length,
  2834. inclusive: true,
  2835. exact: false,
  2836. type: "array",
  2837. });
  2838. status.dirty();
  2839. }
  2840. const items = [...ctx.data]
  2841. .map((item, itemIndex) => {
  2842. const schema = this._def.items[itemIndex] || this._def.rest;
  2843. if (!schema)
  2844. return null;
  2845. return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
  2846. })
  2847. .filter((x) => !!x); // filter nulls
  2848. if (ctx.common.async) {
  2849. return Promise.all(items).then((results) => {
  2850. return ParseStatus.mergeArray(status, results);
  2851. });
  2852. }
  2853. else {
  2854. return ParseStatus.mergeArray(status, items);
  2855. }
  2856. }
  2857. get items() {
  2858. return this._def.items;
  2859. }
  2860. rest(rest) {
  2861. return new ZodTuple({
  2862. ...this._def,
  2863. rest,
  2864. });
  2865. }
  2866. }
  2867. ZodTuple.create = (schemas, params) => {
  2868. if (!Array.isArray(schemas)) {
  2869. throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  2870. }
  2871. return new ZodTuple({
  2872. items: schemas,
  2873. typeName: exports.ZodFirstPartyTypeKind.ZodTuple,
  2874. rest: null,
  2875. ...processCreateParams(params),
  2876. });
  2877. };
  2878. class ZodRecord extends ZodType {
  2879. get keySchema() {
  2880. return this._def.keyType;
  2881. }
  2882. get valueSchema() {
  2883. return this._def.valueType;
  2884. }
  2885. _parse(input) {
  2886. const { status, ctx } = this._processInputParams(input);
  2887. if (ctx.parsedType !== ZodParsedType.object) {
  2888. addIssueToContext(ctx, {
  2889. code: ZodIssueCode.invalid_type,
  2890. expected: ZodParsedType.object,
  2891. received: ctx.parsedType,
  2892. });
  2893. return INVALID;
  2894. }
  2895. const pairs = [];
  2896. const keyType = this._def.keyType;
  2897. const valueType = this._def.valueType;
  2898. for (const key in ctx.data) {
  2899. pairs.push({
  2900. key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
  2901. value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
  2902. });
  2903. }
  2904. if (ctx.common.async) {
  2905. return ParseStatus.mergeObjectAsync(status, pairs);
  2906. }
  2907. else {
  2908. return ParseStatus.mergeObjectSync(status, pairs);
  2909. }
  2910. }
  2911. get element() {
  2912. return this._def.valueType;
  2913. }
  2914. static create(first, second, third) {
  2915. if (second instanceof ZodType) {
  2916. return new ZodRecord({
  2917. keyType: first,
  2918. valueType: second,
  2919. typeName: exports.ZodFirstPartyTypeKind.ZodRecord,
  2920. ...processCreateParams(third),
  2921. });
  2922. }
  2923. return new ZodRecord({
  2924. keyType: ZodString.create(),
  2925. valueType: first,
  2926. typeName: exports.ZodFirstPartyTypeKind.ZodRecord,
  2927. ...processCreateParams(second),
  2928. });
  2929. }
  2930. }
  2931. class ZodMap extends ZodType {
  2932. _parse(input) {
  2933. const { status, ctx } = this._processInputParams(input);
  2934. if (ctx.parsedType !== ZodParsedType.map) {
  2935. addIssueToContext(ctx, {
  2936. code: ZodIssueCode.invalid_type,
  2937. expected: ZodParsedType.map,
  2938. received: ctx.parsedType,
  2939. });
  2940. return INVALID;
  2941. }
  2942. const keyType = this._def.keyType;
  2943. const valueType = this._def.valueType;
  2944. const pairs = [...ctx.data.entries()].map(([key, value], index) => {
  2945. return {
  2946. key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
  2947. value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),
  2948. };
  2949. });
  2950. if (ctx.common.async) {
  2951. const finalMap = new Map();
  2952. return Promise.resolve().then(async () => {
  2953. for (const pair of pairs) {
  2954. const key = await pair.key;
  2955. const value = await pair.value;
  2956. if (key.status === "aborted" || value.status === "aborted") {
  2957. return INVALID;
  2958. }
  2959. if (key.status === "dirty" || value.status === "dirty") {
  2960. status.dirty();
  2961. }
  2962. finalMap.set(key.value, value.value);
  2963. }
  2964. return { status: status.value, value: finalMap };
  2965. });
  2966. }
  2967. else {
  2968. const finalMap = new Map();
  2969. for (const pair of pairs) {
  2970. const key = pair.key;
  2971. const value = pair.value;
  2972. if (key.status === "aborted" || value.status === "aborted") {
  2973. return INVALID;
  2974. }
  2975. if (key.status === "dirty" || value.status === "dirty") {
  2976. status.dirty();
  2977. }
  2978. finalMap.set(key.value, value.value);
  2979. }
  2980. return { status: status.value, value: finalMap };
  2981. }
  2982. }
  2983. }
  2984. ZodMap.create = (keyType, valueType, params) => {
  2985. return new ZodMap({
  2986. valueType,
  2987. keyType,
  2988. typeName: exports.ZodFirstPartyTypeKind.ZodMap,
  2989. ...processCreateParams(params),
  2990. });
  2991. };
  2992. class ZodSet extends ZodType {
  2993. _parse(input) {
  2994. const { status, ctx } = this._processInputParams(input);
  2995. if (ctx.parsedType !== ZodParsedType.set) {
  2996. addIssueToContext(ctx, {
  2997. code: ZodIssueCode.invalid_type,
  2998. expected: ZodParsedType.set,
  2999. received: ctx.parsedType,
  3000. });
  3001. return INVALID;
  3002. }
  3003. const def = this._def;
  3004. if (def.minSize !== null) {
  3005. if (ctx.data.size < def.minSize.value) {
  3006. addIssueToContext(ctx, {
  3007. code: ZodIssueCode.too_small,
  3008. minimum: def.minSize.value,
  3009. type: "set",
  3010. inclusive: true,
  3011. exact: false,
  3012. message: def.minSize.message,
  3013. });
  3014. status.dirty();
  3015. }
  3016. }
  3017. if (def.maxSize !== null) {
  3018. if (ctx.data.size > def.maxSize.value) {
  3019. addIssueToContext(ctx, {
  3020. code: ZodIssueCode.too_big,
  3021. maximum: def.maxSize.value,
  3022. type: "set",
  3023. inclusive: true,
  3024. exact: false,
  3025. message: def.maxSize.message,
  3026. });
  3027. status.dirty();
  3028. }
  3029. }
  3030. const valueType = this._def.valueType;
  3031. function finalizeSet(elements) {
  3032. const parsedSet = new Set();
  3033. for (const element of elements) {
  3034. if (element.status === "aborted")
  3035. return INVALID;
  3036. if (element.status === "dirty")
  3037. status.dirty();
  3038. parsedSet.add(element.value);
  3039. }
  3040. return { status: status.value, value: parsedSet };
  3041. }
  3042. const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
  3043. if (ctx.common.async) {
  3044. return Promise.all(elements).then((elements) => finalizeSet(elements));
  3045. }
  3046. else {
  3047. return finalizeSet(elements);
  3048. }
  3049. }
  3050. min(minSize, message) {
  3051. return new ZodSet({
  3052. ...this._def,
  3053. minSize: { value: minSize, message: errorUtil.toString(message) },
  3054. });
  3055. }
  3056. max(maxSize, message) {
  3057. return new ZodSet({
  3058. ...this._def,
  3059. maxSize: { value: maxSize, message: errorUtil.toString(message) },
  3060. });
  3061. }
  3062. size(size, message) {
  3063. return this.min(size, message).max(size, message);
  3064. }
  3065. nonempty(message) {
  3066. return this.min(1, message);
  3067. }
  3068. }
  3069. ZodSet.create = (valueType, params) => {
  3070. return new ZodSet({
  3071. valueType,
  3072. minSize: null,
  3073. maxSize: null,
  3074. typeName: exports.ZodFirstPartyTypeKind.ZodSet,
  3075. ...processCreateParams(params),
  3076. });
  3077. };
  3078. class ZodFunction extends ZodType {
  3079. constructor() {
  3080. super(...arguments);
  3081. this.validate = this.implement;
  3082. }
  3083. _parse(input) {
  3084. const { ctx } = this._processInputParams(input);
  3085. if (ctx.parsedType !== ZodParsedType.function) {
  3086. addIssueToContext(ctx, {
  3087. code: ZodIssueCode.invalid_type,
  3088. expected: ZodParsedType.function,
  3089. received: ctx.parsedType,
  3090. });
  3091. return INVALID;
  3092. }
  3093. function makeArgsIssue(args, error) {
  3094. return makeIssue({
  3095. data: args,
  3096. path: ctx.path,
  3097. errorMaps: [
  3098. ctx.common.contextualErrorMap,
  3099. ctx.schemaErrorMap,
  3100. getErrorMap(),
  3101. errorMap,
  3102. ].filter((x) => !!x),
  3103. issueData: {
  3104. code: ZodIssueCode.invalid_arguments,
  3105. argumentsError: error,
  3106. },
  3107. });
  3108. }
  3109. function makeReturnsIssue(returns, error) {
  3110. return makeIssue({
  3111. data: returns,
  3112. path: ctx.path,
  3113. errorMaps: [
  3114. ctx.common.contextualErrorMap,
  3115. ctx.schemaErrorMap,
  3116. getErrorMap(),
  3117. errorMap,
  3118. ].filter((x) => !!x),
  3119. issueData: {
  3120. code: ZodIssueCode.invalid_return_type,
  3121. returnTypeError: error,
  3122. },
  3123. });
  3124. }
  3125. const params = { errorMap: ctx.common.contextualErrorMap };
  3126. const fn = ctx.data;
  3127. if (this._def.returns instanceof ZodPromise) {
  3128. return OK(async (...args) => {
  3129. const error = new ZodError([]);
  3130. const parsedArgs = await this._def.args
  3131. .parseAsync(args, params)
  3132. .catch((e) => {
  3133. error.addIssue(makeArgsIssue(args, e));
  3134. throw error;
  3135. });
  3136. const result = await fn(...parsedArgs);
  3137. const parsedReturns = await this._def.returns._def.type
  3138. .parseAsync(result, params)
  3139. .catch((e) => {
  3140. error.addIssue(makeReturnsIssue(result, e));
  3141. throw error;
  3142. });
  3143. return parsedReturns;
  3144. });
  3145. }
  3146. else {
  3147. return OK((...args) => {
  3148. const parsedArgs = this._def.args.safeParse(args, params);
  3149. if (!parsedArgs.success) {
  3150. throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
  3151. }
  3152. const result = fn(...parsedArgs.data);
  3153. const parsedReturns = this._def.returns.safeParse(result, params);
  3154. if (!parsedReturns.success) {
  3155. throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
  3156. }
  3157. return parsedReturns.data;
  3158. });
  3159. }
  3160. }
  3161. parameters() {
  3162. return this._def.args;
  3163. }
  3164. returnType() {
  3165. return this._def.returns;
  3166. }
  3167. args(...items) {
  3168. return new ZodFunction({
  3169. ...this._def,
  3170. args: ZodTuple.create(items).rest(ZodUnknown.create()),
  3171. });
  3172. }
  3173. returns(returnType) {
  3174. return new ZodFunction({
  3175. ...this._def,
  3176. returns: returnType,
  3177. });
  3178. }
  3179. implement(func) {
  3180. const validatedFunc = this.parse(func);
  3181. return validatedFunc;
  3182. }
  3183. strictImplement(func) {
  3184. const validatedFunc = this.parse(func);
  3185. return validatedFunc;
  3186. }
  3187. static create(args, returns, params) {
  3188. return new ZodFunction({
  3189. args: (args
  3190. ? args
  3191. : ZodTuple.create([]).rest(ZodUnknown.create())),
  3192. returns: returns || ZodUnknown.create(),
  3193. typeName: exports.ZodFirstPartyTypeKind.ZodFunction,
  3194. ...processCreateParams(params),
  3195. });
  3196. }
  3197. }
  3198. class ZodLazy extends ZodType {
  3199. get schema() {
  3200. return this._def.getter();
  3201. }
  3202. _parse(input) {
  3203. const { ctx } = this._processInputParams(input);
  3204. const lazySchema = this._def.getter();
  3205. return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  3206. }
  3207. }
  3208. ZodLazy.create = (getter, params) => {
  3209. return new ZodLazy({
  3210. getter: getter,
  3211. typeName: exports.ZodFirstPartyTypeKind.ZodLazy,
  3212. ...processCreateParams(params),
  3213. });
  3214. };
  3215. class ZodLiteral extends ZodType {
  3216. _parse(input) {
  3217. if (input.data !== this._def.value) {
  3218. const ctx = this._getOrReturnCtx(input);
  3219. addIssueToContext(ctx, {
  3220. received: ctx.data,
  3221. code: ZodIssueCode.invalid_literal,
  3222. expected: this._def.value,
  3223. });
  3224. return INVALID;
  3225. }
  3226. return { status: "valid", value: input.data };
  3227. }
  3228. get value() {
  3229. return this._def.value;
  3230. }
  3231. }
  3232. ZodLiteral.create = (value, params) => {
  3233. return new ZodLiteral({
  3234. value: value,
  3235. typeName: exports.ZodFirstPartyTypeKind.ZodLiteral,
  3236. ...processCreateParams(params),
  3237. });
  3238. };
  3239. function createZodEnum(values, params) {
  3240. return new ZodEnum({
  3241. values: values,
  3242. typeName: exports.ZodFirstPartyTypeKind.ZodEnum,
  3243. ...processCreateParams(params),
  3244. });
  3245. }
  3246. class ZodEnum extends ZodType {
  3247. _parse(input) {
  3248. if (typeof input.data !== "string") {
  3249. const ctx = this._getOrReturnCtx(input);
  3250. const expectedValues = this._def.values;
  3251. addIssueToContext(ctx, {
  3252. expected: exports.util.joinValues(expectedValues),
  3253. received: ctx.parsedType,
  3254. code: ZodIssueCode.invalid_type,
  3255. });
  3256. return INVALID;
  3257. }
  3258. if (this._def.values.indexOf(input.data) === -1) {
  3259. const ctx = this._getOrReturnCtx(input);
  3260. const expectedValues = this._def.values;
  3261. addIssueToContext(ctx, {
  3262. received: ctx.data,
  3263. code: ZodIssueCode.invalid_enum_value,
  3264. options: expectedValues,
  3265. });
  3266. return INVALID;
  3267. }
  3268. return OK(input.data);
  3269. }
  3270. get options() {
  3271. return this._def.values;
  3272. }
  3273. get enum() {
  3274. const enumValues = {};
  3275. for (const val of this._def.values) {
  3276. enumValues[val] = val;
  3277. }
  3278. return enumValues;
  3279. }
  3280. get Values() {
  3281. const enumValues = {};
  3282. for (const val of this._def.values) {
  3283. enumValues[val] = val;
  3284. }
  3285. return enumValues;
  3286. }
  3287. get Enum() {
  3288. const enumValues = {};
  3289. for (const val of this._def.values) {
  3290. enumValues[val] = val;
  3291. }
  3292. return enumValues;
  3293. }
  3294. extract(values) {
  3295. return ZodEnum.create(values);
  3296. }
  3297. exclude(values) {
  3298. return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
  3299. }
  3300. }
  3301. ZodEnum.create = createZodEnum;
  3302. class ZodNativeEnum extends ZodType {
  3303. _parse(input) {
  3304. const nativeEnumValues = exports.util.getValidEnumValues(this._def.values);
  3305. const ctx = this._getOrReturnCtx(input);
  3306. if (ctx.parsedType !== ZodParsedType.string &&
  3307. ctx.parsedType !== ZodParsedType.number) {
  3308. const expectedValues = exports.util.objectValues(nativeEnumValues);
  3309. addIssueToContext(ctx, {
  3310. expected: exports.util.joinValues(expectedValues),
  3311. received: ctx.parsedType,
  3312. code: ZodIssueCode.invalid_type,
  3313. });
  3314. return INVALID;
  3315. }
  3316. if (nativeEnumValues.indexOf(input.data) === -1) {
  3317. const expectedValues = exports.util.objectValues(nativeEnumValues);
  3318. addIssueToContext(ctx, {
  3319. received: ctx.data,
  3320. code: ZodIssueCode.invalid_enum_value,
  3321. options: expectedValues,
  3322. });
  3323. return INVALID;
  3324. }
  3325. return OK(input.data);
  3326. }
  3327. get enum() {
  3328. return this._def.values;
  3329. }
  3330. }
  3331. ZodNativeEnum.create = (values, params) => {
  3332. return new ZodNativeEnum({
  3333. values: values,
  3334. typeName: exports.ZodFirstPartyTypeKind.ZodNativeEnum,
  3335. ...processCreateParams(params),
  3336. });
  3337. };
  3338. class ZodPromise extends ZodType {
  3339. unwrap() {
  3340. return this._def.type;
  3341. }
  3342. _parse(input) {
  3343. const { ctx } = this._processInputParams(input);
  3344. if (ctx.parsedType !== ZodParsedType.promise &&
  3345. ctx.common.async === false) {
  3346. addIssueToContext(ctx, {
  3347. code: ZodIssueCode.invalid_type,
  3348. expected: ZodParsedType.promise,
  3349. received: ctx.parsedType,
  3350. });
  3351. return INVALID;
  3352. }
  3353. const promisified = ctx.parsedType === ZodParsedType.promise
  3354. ? ctx.data
  3355. : Promise.resolve(ctx.data);
  3356. return OK(promisified.then((data) => {
  3357. return this._def.type.parseAsync(data, {
  3358. path: ctx.path,
  3359. errorMap: ctx.common.contextualErrorMap,
  3360. });
  3361. }));
  3362. }
  3363. }
  3364. ZodPromise.create = (schema, params) => {
  3365. return new ZodPromise({
  3366. type: schema,
  3367. typeName: exports.ZodFirstPartyTypeKind.ZodPromise,
  3368. ...processCreateParams(params),
  3369. });
  3370. };
  3371. class ZodEffects extends ZodType {
  3372. innerType() {
  3373. return this._def.schema;
  3374. }
  3375. sourceType() {
  3376. return this._def.schema._def.typeName === exports.ZodFirstPartyTypeKind.ZodEffects
  3377. ? this._def.schema.sourceType()
  3378. : this._def.schema;
  3379. }
  3380. _parse(input) {
  3381. const { status, ctx } = this._processInputParams(input);
  3382. const effect = this._def.effect || null;
  3383. if (effect.type === "preprocess") {
  3384. const processed = effect.transform(ctx.data);
  3385. if (ctx.common.async) {
  3386. return Promise.resolve(processed).then((processed) => {
  3387. return this._def.schema._parseAsync({
  3388. data: processed,
  3389. path: ctx.path,
  3390. parent: ctx,
  3391. });
  3392. });
  3393. }
  3394. else {
  3395. return this._def.schema._parseSync({
  3396. data: processed,
  3397. path: ctx.path,
  3398. parent: ctx,
  3399. });
  3400. }
  3401. }
  3402. const checkCtx = {
  3403. addIssue: (arg) => {
  3404. addIssueToContext(ctx, arg);
  3405. if (arg.fatal) {
  3406. status.abort();
  3407. }
  3408. else {
  3409. status.dirty();
  3410. }
  3411. },
  3412. get path() {
  3413. return ctx.path;
  3414. },
  3415. };
  3416. checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
  3417. if (effect.type === "refinement") {
  3418. const executeRefinement = (acc
  3419. // effect: RefinementEffect<any>
  3420. ) => {
  3421. const result = effect.refinement(acc, checkCtx);
  3422. if (ctx.common.async) {
  3423. return Promise.resolve(result);
  3424. }
  3425. if (result instanceof Promise) {
  3426. throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
  3427. }
  3428. return acc;
  3429. };
  3430. if (ctx.common.async === false) {
  3431. const inner = this._def.schema._parseSync({
  3432. data: ctx.data,
  3433. path: ctx.path,
  3434. parent: ctx,
  3435. });
  3436. if (inner.status === "aborted")
  3437. return INVALID;
  3438. if (inner.status === "dirty")
  3439. status.dirty();
  3440. // return value is ignored
  3441. executeRefinement(inner.value);
  3442. return { status: status.value, value: inner.value };
  3443. }
  3444. else {
  3445. return this._def.schema
  3446. ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  3447. .then((inner) => {
  3448. if (inner.status === "aborted")
  3449. return INVALID;
  3450. if (inner.status === "dirty")
  3451. status.dirty();
  3452. return executeRefinement(inner.value).then(() => {
  3453. return { status: status.value, value: inner.value };
  3454. });
  3455. });
  3456. }
  3457. }
  3458. if (effect.type === "transform") {
  3459. if (ctx.common.async === false) {
  3460. const base = this._def.schema._parseSync({
  3461. data: ctx.data,
  3462. path: ctx.path,
  3463. parent: ctx,
  3464. });
  3465. if (!isValid(base))
  3466. return base;
  3467. const result = effect.transform(base.value, checkCtx);
  3468. if (result instanceof Promise) {
  3469. throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
  3470. }
  3471. return { status: status.value, value: result };
  3472. }
  3473. else {
  3474. return this._def.schema
  3475. ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
  3476. .then((base) => {
  3477. if (!isValid(base))
  3478. return base;
  3479. return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
  3480. });
  3481. }
  3482. }
  3483. exports.util.assertNever(effect);
  3484. }
  3485. }
  3486. ZodEffects.create = (schema, effect, params) => {
  3487. return new ZodEffects({
  3488. schema,
  3489. typeName: exports.ZodFirstPartyTypeKind.ZodEffects,
  3490. effect,
  3491. ...processCreateParams(params),
  3492. });
  3493. };
  3494. ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
  3495. return new ZodEffects({
  3496. schema,
  3497. effect: { type: "preprocess", transform: preprocess },
  3498. typeName: exports.ZodFirstPartyTypeKind.ZodEffects,
  3499. ...processCreateParams(params),
  3500. });
  3501. };
  3502. class ZodOptional extends ZodType {
  3503. _parse(input) {
  3504. const parsedType = this._getType(input);
  3505. if (parsedType === ZodParsedType.undefined) {
  3506. return OK(undefined);
  3507. }
  3508. return this._def.innerType._parse(input);
  3509. }
  3510. unwrap() {
  3511. return this._def.innerType;
  3512. }
  3513. }
  3514. ZodOptional.create = (type, params) => {
  3515. return new ZodOptional({
  3516. innerType: type,
  3517. typeName: exports.ZodFirstPartyTypeKind.ZodOptional,
  3518. ...processCreateParams(params),
  3519. });
  3520. };
  3521. class ZodNullable extends ZodType {
  3522. _parse(input) {
  3523. const parsedType = this._getType(input);
  3524. if (parsedType === ZodParsedType.null) {
  3525. return OK(null);
  3526. }
  3527. return this._def.innerType._parse(input);
  3528. }
  3529. unwrap() {
  3530. return this._def.innerType;
  3531. }
  3532. }
  3533. ZodNullable.create = (type, params) => {
  3534. return new ZodNullable({
  3535. innerType: type,
  3536. typeName: exports.ZodFirstPartyTypeKind.ZodNullable,
  3537. ...processCreateParams(params),
  3538. });
  3539. };
  3540. class ZodDefault extends ZodType {
  3541. _parse(input) {
  3542. const { ctx } = this._processInputParams(input);
  3543. let data = ctx.data;
  3544. if (ctx.parsedType === ZodParsedType.undefined) {
  3545. data = this._def.defaultValue();
  3546. }
  3547. return this._def.innerType._parse({
  3548. data,
  3549. path: ctx.path,
  3550. parent: ctx,
  3551. });
  3552. }
  3553. removeDefault() {
  3554. return this._def.innerType;
  3555. }
  3556. }
  3557. ZodDefault.create = (type, params) => {
  3558. return new ZodDefault({
  3559. innerType: type,
  3560. typeName: exports.ZodFirstPartyTypeKind.ZodDefault,
  3561. defaultValue: typeof params.default === "function"
  3562. ? params.default
  3563. : () => params.default,
  3564. ...processCreateParams(params),
  3565. });
  3566. };
  3567. class ZodCatch extends ZodType {
  3568. _parse(input) {
  3569. const { ctx } = this._processInputParams(input);
  3570. // newCtx is used to not collect issues from inner types in ctx
  3571. const newCtx = {
  3572. ...ctx,
  3573. common: {
  3574. ...ctx.common,
  3575. issues: [],
  3576. },
  3577. };
  3578. const result = this._def.innerType._parse({
  3579. data: newCtx.data,
  3580. path: newCtx.path,
  3581. parent: {
  3582. ...newCtx,
  3583. },
  3584. });
  3585. if (isAsync(result)) {
  3586. return result.then((result) => {
  3587. return {
  3588. status: "valid",
  3589. value: result.status === "valid"
  3590. ? result.value
  3591. : this._def.catchValue({
  3592. get error() {
  3593. return new ZodError(newCtx.common.issues);
  3594. },
  3595. input: newCtx.data,
  3596. }),
  3597. };
  3598. });
  3599. }
  3600. else {
  3601. return {
  3602. status: "valid",
  3603. value: result.status === "valid"
  3604. ? result.value
  3605. : this._def.catchValue({
  3606. get error() {
  3607. return new ZodError(newCtx.common.issues);
  3608. },
  3609. input: newCtx.data,
  3610. }),
  3611. };
  3612. }
  3613. }
  3614. removeCatch() {
  3615. return this._def.innerType;
  3616. }
  3617. }
  3618. ZodCatch.create = (type, params) => {
  3619. return new ZodCatch({
  3620. innerType: type,
  3621. typeName: exports.ZodFirstPartyTypeKind.ZodCatch,
  3622. catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
  3623. ...processCreateParams(params),
  3624. });
  3625. };
  3626. class ZodNaN extends ZodType {
  3627. _parse(input) {
  3628. const parsedType = this._getType(input);
  3629. if (parsedType !== ZodParsedType.nan) {
  3630. const ctx = this._getOrReturnCtx(input);
  3631. addIssueToContext(ctx, {
  3632. code: ZodIssueCode.invalid_type,
  3633. expected: ZodParsedType.nan,
  3634. received: ctx.parsedType,
  3635. });
  3636. return INVALID;
  3637. }
  3638. return { status: "valid", value: input.data };
  3639. }
  3640. }
  3641. ZodNaN.create = (params) => {
  3642. return new ZodNaN({
  3643. typeName: exports.ZodFirstPartyTypeKind.ZodNaN,
  3644. ...processCreateParams(params),
  3645. });
  3646. };
  3647. const BRAND = Symbol("zod_brand");
  3648. class ZodBranded extends ZodType {
  3649. _parse(input) {
  3650. const { ctx } = this._processInputParams(input);
  3651. const data = ctx.data;
  3652. return this._def.type._parse({
  3653. data,
  3654. path: ctx.path,
  3655. parent: ctx,
  3656. });
  3657. }
  3658. unwrap() {
  3659. return this._def.type;
  3660. }
  3661. }
  3662. class ZodPipeline extends ZodType {
  3663. _parse(input) {
  3664. const { status, ctx } = this._processInputParams(input);
  3665. if (ctx.common.async) {
  3666. const handleAsync = async () => {
  3667. const inResult = await this._def.in._parseAsync({
  3668. data: ctx.data,
  3669. path: ctx.path,
  3670. parent: ctx,
  3671. });
  3672. if (inResult.status === "aborted")
  3673. return INVALID;
  3674. if (inResult.status === "dirty") {
  3675. status.dirty();
  3676. return DIRTY(inResult.value);
  3677. }
  3678. else {
  3679. return this._def.out._parseAsync({
  3680. data: inResult.value,
  3681. path: ctx.path,
  3682. parent: ctx,
  3683. });
  3684. }
  3685. };
  3686. return handleAsync();
  3687. }
  3688. else {
  3689. const inResult = this._def.in._parseSync({
  3690. data: ctx.data,
  3691. path: ctx.path,
  3692. parent: ctx,
  3693. });
  3694. if (inResult.status === "aborted")
  3695. return INVALID;
  3696. if (inResult.status === "dirty") {
  3697. status.dirty();
  3698. return {
  3699. status: "dirty",
  3700. value: inResult.value,
  3701. };
  3702. }
  3703. else {
  3704. return this._def.out._parseSync({
  3705. data: inResult.value,
  3706. path: ctx.path,
  3707. parent: ctx,
  3708. });
  3709. }
  3710. }
  3711. }
  3712. static create(a, b) {
  3713. return new ZodPipeline({
  3714. in: a,
  3715. out: b,
  3716. typeName: exports.ZodFirstPartyTypeKind.ZodPipeline,
  3717. });
  3718. }
  3719. }
  3720. const custom = (check, params = {},
  3721. /*
  3722. * @deprecated
  3723. *
  3724. * Pass `fatal` into the params object instead:
  3725. *
  3726. * ```ts
  3727. * z.string().custom((val) => val.length > 5, { fatal: false })
  3728. * ```
  3729. *
  3730. */
  3731. fatal) => {
  3732. if (check)
  3733. return ZodAny.create().superRefine((data, ctx) => {
  3734. var _a, _b;
  3735. if (!check(data)) {
  3736. const p = typeof params === "function"
  3737. ? params(data)
  3738. : typeof params === "string"
  3739. ? { message: params }
  3740. : params;
  3741. const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
  3742. const p2 = typeof p === "string" ? { message: p } : p;
  3743. ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });
  3744. }
  3745. });
  3746. return ZodAny.create();
  3747. };
  3748. const late = {
  3749. object: ZodObject.lazycreate,
  3750. };
  3751. exports.ZodFirstPartyTypeKind = void 0;
  3752. (function (ZodFirstPartyTypeKind) {
  3753. ZodFirstPartyTypeKind["ZodString"] = "ZodString";
  3754. ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
  3755. ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
  3756. ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
  3757. ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
  3758. ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
  3759. ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
  3760. ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
  3761. ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
  3762. ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
  3763. ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
  3764. ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
  3765. ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
  3766. ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
  3767. ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
  3768. ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
  3769. ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  3770. ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
  3771. ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
  3772. ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
  3773. ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
  3774. ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
  3775. ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
  3776. ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
  3777. ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
  3778. ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
  3779. ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
  3780. ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
  3781. ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
  3782. ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
  3783. ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
  3784. ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
  3785. ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
  3786. ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
  3787. ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
  3788. })(exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {}));
  3789. const instanceOfType = (
  3790. // const instanceOfType = <T extends new (...args: any[]) => any>(
  3791. cls, params = {
  3792. message: `Input not instance of ${cls.name}`,
  3793. }) => custom((data) => data instanceof cls, params);
  3794. const stringType = ZodString.create;
  3795. const numberType = ZodNumber.create;
  3796. const nanType = ZodNaN.create;
  3797. const bigIntType = ZodBigInt.create;
  3798. const booleanType = ZodBoolean.create;
  3799. const dateType = ZodDate.create;
  3800. const symbolType = ZodSymbol.create;
  3801. const undefinedType = ZodUndefined.create;
  3802. const nullType = ZodNull.create;
  3803. const anyType = ZodAny.create;
  3804. const unknownType = ZodUnknown.create;
  3805. const neverType = ZodNever.create;
  3806. const voidType = ZodVoid.create;
  3807. const arrayType = ZodArray.create;
  3808. const objectType = ZodObject.create;
  3809. const strictObjectType = ZodObject.strictCreate;
  3810. const unionType = ZodUnion.create;
  3811. const discriminatedUnionType = ZodDiscriminatedUnion.create;
  3812. const intersectionType = ZodIntersection.create;
  3813. const tupleType = ZodTuple.create;
  3814. const recordType = ZodRecord.create;
  3815. const mapType = ZodMap.create;
  3816. const setType = ZodSet.create;
  3817. const functionType = ZodFunction.create;
  3818. const lazyType = ZodLazy.create;
  3819. const literalType = ZodLiteral.create;
  3820. const enumType = ZodEnum.create;
  3821. const nativeEnumType = ZodNativeEnum.create;
  3822. const promiseType = ZodPromise.create;
  3823. const effectsType = ZodEffects.create;
  3824. const optionalType = ZodOptional.create;
  3825. const nullableType = ZodNullable.create;
  3826. const preprocessType = ZodEffects.createWithPreprocess;
  3827. const pipelineType = ZodPipeline.create;
  3828. const ostring = () => stringType().optional();
  3829. const onumber = () => numberType().optional();
  3830. const oboolean = () => booleanType().optional();
  3831. const coerce = {
  3832. string: ((arg) => ZodString.create({ ...arg, coerce: true })),
  3833. number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
  3834. boolean: ((arg) => ZodBoolean.create({
  3835. ...arg,
  3836. coerce: true,
  3837. })),
  3838. bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
  3839. date: ((arg) => ZodDate.create({ ...arg, coerce: true })),
  3840. };
  3841. const NEVER = INVALID;
  3842. var z = /*#__PURE__*/Object.freeze({
  3843. __proto__: null,
  3844. defaultErrorMap: errorMap,
  3845. setErrorMap: setErrorMap,
  3846. getErrorMap: getErrorMap,
  3847. makeIssue: makeIssue,
  3848. EMPTY_PATH: EMPTY_PATH,
  3849. addIssueToContext: addIssueToContext,
  3850. ParseStatus: ParseStatus,
  3851. INVALID: INVALID,
  3852. DIRTY: DIRTY,
  3853. OK: OK,
  3854. isAborted: isAborted,
  3855. isDirty: isDirty,
  3856. isValid: isValid,
  3857. isAsync: isAsync,
  3858. get util () { return exports.util; },
  3859. get objectUtil () { return exports.objectUtil; },
  3860. ZodParsedType: ZodParsedType,
  3861. getParsedType: getParsedType,
  3862. ZodType: ZodType,
  3863. ZodString: ZodString,
  3864. ZodNumber: ZodNumber,
  3865. ZodBigInt: ZodBigInt,
  3866. ZodBoolean: ZodBoolean,
  3867. ZodDate: ZodDate,
  3868. ZodSymbol: ZodSymbol,
  3869. ZodUndefined: ZodUndefined,
  3870. ZodNull: ZodNull,
  3871. ZodAny: ZodAny,
  3872. ZodUnknown: ZodUnknown,
  3873. ZodNever: ZodNever,
  3874. ZodVoid: ZodVoid,
  3875. ZodArray: ZodArray,
  3876. ZodObject: ZodObject,
  3877. ZodUnion: ZodUnion,
  3878. ZodDiscriminatedUnion: ZodDiscriminatedUnion,
  3879. ZodIntersection: ZodIntersection,
  3880. ZodTuple: ZodTuple,
  3881. ZodRecord: ZodRecord,
  3882. ZodMap: ZodMap,
  3883. ZodSet: ZodSet,
  3884. ZodFunction: ZodFunction,
  3885. ZodLazy: ZodLazy,
  3886. ZodLiteral: ZodLiteral,
  3887. ZodEnum: ZodEnum,
  3888. ZodNativeEnum: ZodNativeEnum,
  3889. ZodPromise: ZodPromise,
  3890. ZodEffects: ZodEffects,
  3891. ZodTransformer: ZodEffects,
  3892. ZodOptional: ZodOptional,
  3893. ZodNullable: ZodNullable,
  3894. ZodDefault: ZodDefault,
  3895. ZodCatch: ZodCatch,
  3896. ZodNaN: ZodNaN,
  3897. BRAND: BRAND,
  3898. ZodBranded: ZodBranded,
  3899. ZodPipeline: ZodPipeline,
  3900. custom: custom,
  3901. Schema: ZodType,
  3902. ZodSchema: ZodType,
  3903. late: late,
  3904. get ZodFirstPartyTypeKind () { return exports.ZodFirstPartyTypeKind; },
  3905. coerce: coerce,
  3906. any: anyType,
  3907. array: arrayType,
  3908. bigint: bigIntType,
  3909. boolean: booleanType,
  3910. date: dateType,
  3911. discriminatedUnion: discriminatedUnionType,
  3912. effect: effectsType,
  3913. 'enum': enumType,
  3914. 'function': functionType,
  3915. 'instanceof': instanceOfType,
  3916. intersection: intersectionType,
  3917. lazy: lazyType,
  3918. literal: literalType,
  3919. map: mapType,
  3920. nan: nanType,
  3921. nativeEnum: nativeEnumType,
  3922. never: neverType,
  3923. 'null': nullType,
  3924. nullable: nullableType,
  3925. number: numberType,
  3926. object: objectType,
  3927. oboolean: oboolean,
  3928. onumber: onumber,
  3929. optional: optionalType,
  3930. ostring: ostring,
  3931. pipeline: pipelineType,
  3932. preprocess: preprocessType,
  3933. promise: promiseType,
  3934. record: recordType,
  3935. set: setType,
  3936. strictObject: strictObjectType,
  3937. string: stringType,
  3938. symbol: symbolType,
  3939. transformer: effectsType,
  3940. tuple: tupleType,
  3941. 'undefined': undefinedType,
  3942. union: unionType,
  3943. unknown: unknownType,
  3944. 'void': voidType,
  3945. NEVER: NEVER,
  3946. ZodIssueCode: ZodIssueCode,
  3947. quotelessJson: quotelessJson,
  3948. ZodError: ZodError
  3949. });
  3950. exports.BRAND = BRAND;
  3951. exports.DIRTY = DIRTY;
  3952. exports.EMPTY_PATH = EMPTY_PATH;
  3953. exports.INVALID = INVALID;
  3954. exports.NEVER = NEVER;
  3955. exports.OK = OK;
  3956. exports.ParseStatus = ParseStatus;
  3957. exports.Schema = ZodType;
  3958. exports.ZodAny = ZodAny;
  3959. exports.ZodArray = ZodArray;
  3960. exports.ZodBigInt = ZodBigInt;
  3961. exports.ZodBoolean = ZodBoolean;
  3962. exports.ZodBranded = ZodBranded;
  3963. exports.ZodCatch = ZodCatch;
  3964. exports.ZodDate = ZodDate;
  3965. exports.ZodDefault = ZodDefault;
  3966. exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion;
  3967. exports.ZodEffects = ZodEffects;
  3968. exports.ZodEnum = ZodEnum;
  3969. exports.ZodError = ZodError;
  3970. exports.ZodFunction = ZodFunction;
  3971. exports.ZodIntersection = ZodIntersection;
  3972. exports.ZodIssueCode = ZodIssueCode;
  3973. exports.ZodLazy = ZodLazy;
  3974. exports.ZodLiteral = ZodLiteral;
  3975. exports.ZodMap = ZodMap;
  3976. exports.ZodNaN = ZodNaN;
  3977. exports.ZodNativeEnum = ZodNativeEnum;
  3978. exports.ZodNever = ZodNever;
  3979. exports.ZodNull = ZodNull;
  3980. exports.ZodNullable = ZodNullable;
  3981. exports.ZodNumber = ZodNumber;
  3982. exports.ZodObject = ZodObject;
  3983. exports.ZodOptional = ZodOptional;
  3984. exports.ZodParsedType = ZodParsedType;
  3985. exports.ZodPipeline = ZodPipeline;
  3986. exports.ZodPromise = ZodPromise;
  3987. exports.ZodRecord = ZodRecord;
  3988. exports.ZodSchema = ZodType;
  3989. exports.ZodSet = ZodSet;
  3990. exports.ZodString = ZodString;
  3991. exports.ZodSymbol = ZodSymbol;
  3992. exports.ZodTransformer = ZodEffects;
  3993. exports.ZodTuple = ZodTuple;
  3994. exports.ZodType = ZodType;
  3995. exports.ZodUndefined = ZodUndefined;
  3996. exports.ZodUnion = ZodUnion;
  3997. exports.ZodUnknown = ZodUnknown;
  3998. exports.ZodVoid = ZodVoid;
  3999. exports.addIssueToContext = addIssueToContext;
  4000. exports.any = anyType;
  4001. exports.array = arrayType;
  4002. exports.bigint = bigIntType;
  4003. exports.boolean = booleanType;
  4004. exports.coerce = coerce;
  4005. exports.custom = custom;
  4006. exports.date = dateType;
  4007. exports["default"] = z;
  4008. exports.defaultErrorMap = errorMap;
  4009. exports.discriminatedUnion = discriminatedUnionType;
  4010. exports.effect = effectsType;
  4011. exports["enum"] = enumType;
  4012. exports["function"] = functionType;
  4013. exports.getErrorMap = getErrorMap;
  4014. exports.getParsedType = getParsedType;
  4015. exports["instanceof"] = instanceOfType;
  4016. exports.intersection = intersectionType;
  4017. exports.isAborted = isAborted;
  4018. exports.isAsync = isAsync;
  4019. exports.isDirty = isDirty;
  4020. exports.isValid = isValid;
  4021. exports.late = late;
  4022. exports.lazy = lazyType;
  4023. exports.literal = literalType;
  4024. exports.makeIssue = makeIssue;
  4025. exports.map = mapType;
  4026. exports.nan = nanType;
  4027. exports.nativeEnum = nativeEnumType;
  4028. exports.never = neverType;
  4029. exports["null"] = nullType;
  4030. exports.nullable = nullableType;
  4031. exports.number = numberType;
  4032. exports.object = objectType;
  4033. exports.oboolean = oboolean;
  4034. exports.onumber = onumber;
  4035. exports.optional = optionalType;
  4036. exports.ostring = ostring;
  4037. exports.pipeline = pipelineType;
  4038. exports.preprocess = preprocessType;
  4039. exports.promise = promiseType;
  4040. exports.quotelessJson = quotelessJson;
  4041. exports.record = recordType;
  4042. exports.set = setType;
  4043. exports.setErrorMap = setErrorMap;
  4044. exports.strictObject = strictObjectType;
  4045. exports.string = stringType;
  4046. exports.symbol = symbolType;
  4047. exports.transformer = effectsType;
  4048. exports.tuple = tupleType;
  4049. exports["undefined"] = undefinedType;
  4050. exports.union = unionType;
  4051. exports.unknown = unknownType;
  4052. exports["void"] = voidType;
  4053. exports.z = z;
  4054. Object.defineProperty(exports, '__esModule', { value: true });
  4055. }));