index.mjs 136 KB

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