Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

index.mjs 134KB

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