schemas.js 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093
  1. import * as checks from "./checks.js";
  2. import * as core from "./core.js";
  3. import { Doc } from "./doc.js";
  4. import { parse, parseAsync, safeParse, safeParseAsync } from "./parse.js";
  5. import * as regexes from "./regexes.js";
  6. import * as util from "./util.js";
  7. import { version } from "./versions.js";
  8. export const $ZodType = /*@__PURE__*/ core.$constructor("$ZodType", (inst, def) => {
  9. var _a;
  10. inst ?? (inst = {});
  11. inst._zod.def = def; // set _def property
  12. inst._zod.bag = inst._zod.bag || {}; // initialize _bag object
  13. inst._zod.version = version;
  14. const checks = [...(inst._zod.def.checks ?? [])];
  15. // if inst is itself a checks.$ZodCheck, run it as a check
  16. if (inst._zod.traits.has("$ZodCheck")) {
  17. checks.unshift(inst);
  18. }
  19. for (const ch of checks) {
  20. for (const fn of ch._zod.onattach) {
  21. fn(inst);
  22. }
  23. }
  24. if (checks.length === 0) {
  25. // deferred initializer
  26. // inst._zod.parse is not yet defined
  27. (_a = inst._zod).deferred ?? (_a.deferred = []);
  28. inst._zod.deferred?.push(() => {
  29. inst._zod.run = inst._zod.parse;
  30. });
  31. }
  32. else {
  33. const runChecks = (payload, checks, ctx) => {
  34. let isAborted = util.aborted(payload);
  35. let asyncResult;
  36. for (const ch of checks) {
  37. if (ch._zod.def.when) {
  38. const shouldRun = ch._zod.def.when(payload);
  39. if (!shouldRun)
  40. continue;
  41. }
  42. else if (isAborted) {
  43. continue;
  44. }
  45. const currLen = payload.issues.length;
  46. const _ = ch._zod.check(payload);
  47. if (_ instanceof Promise && ctx?.async === false) {
  48. throw new core.$ZodAsyncError();
  49. }
  50. if (asyncResult || _ instanceof Promise) {
  51. asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
  52. await _;
  53. const nextLen = payload.issues.length;
  54. if (nextLen === currLen)
  55. return;
  56. if (!isAborted)
  57. isAborted = util.aborted(payload, currLen);
  58. });
  59. }
  60. else {
  61. const nextLen = payload.issues.length;
  62. if (nextLen === currLen)
  63. continue;
  64. if (!isAborted)
  65. isAborted = util.aborted(payload, currLen);
  66. }
  67. }
  68. if (asyncResult) {
  69. return asyncResult.then(() => {
  70. return payload;
  71. });
  72. }
  73. return payload;
  74. };
  75. const handleCanaryResult = (canary, payload, ctx) => {
  76. // abort if the canary is aborted
  77. if (util.aborted(canary)) {
  78. canary.aborted = true;
  79. return canary;
  80. }
  81. // run checks first, then
  82. const checkResult = runChecks(payload, checks, ctx);
  83. if (checkResult instanceof Promise) {
  84. if (ctx.async === false)
  85. throw new core.$ZodAsyncError();
  86. return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));
  87. }
  88. return inst._zod.parse(checkResult, ctx);
  89. };
  90. inst._zod.run = (payload, ctx) => {
  91. if (ctx.skipChecks) {
  92. return inst._zod.parse(payload, ctx);
  93. }
  94. if (ctx.direction === "backward") {
  95. // run canary
  96. // initial pass (no checks)
  97. const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });
  98. if (canary instanceof Promise) {
  99. return canary.then((canary) => {
  100. return handleCanaryResult(canary, payload, ctx);
  101. });
  102. }
  103. return handleCanaryResult(canary, payload, ctx);
  104. }
  105. // forward
  106. const result = inst._zod.parse(payload, ctx);
  107. if (result instanceof Promise) {
  108. if (ctx.async === false)
  109. throw new core.$ZodAsyncError();
  110. return result.then((result) => runChecks(result, checks, ctx));
  111. }
  112. return runChecks(result, checks, ctx);
  113. };
  114. }
  115. // Lazy initialize ~standard to avoid creating objects for every schema
  116. util.defineLazy(inst, "~standard", () => ({
  117. validate: (value) => {
  118. try {
  119. const r = safeParse(inst, value);
  120. return r.success ? { value: r.data } : { issues: r.error?.issues };
  121. }
  122. catch (_) {
  123. return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));
  124. }
  125. },
  126. vendor: "zod",
  127. version: 1,
  128. }));
  129. });
  130. export { clone } from "./util.js";
  131. export const $ZodString = /*@__PURE__*/ core.$constructor("$ZodString", (inst, def) => {
  132. $ZodType.init(inst, def);
  133. inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);
  134. inst._zod.parse = (payload, _) => {
  135. if (def.coerce)
  136. try {
  137. payload.value = String(payload.value);
  138. }
  139. catch (_) { }
  140. if (typeof payload.value === "string")
  141. return payload;
  142. payload.issues.push({
  143. expected: "string",
  144. code: "invalid_type",
  145. input: payload.value,
  146. inst,
  147. });
  148. return payload;
  149. };
  150. });
  151. export const $ZodStringFormat = /*@__PURE__*/ core.$constructor("$ZodStringFormat", (inst, def) => {
  152. // check initialization must come first
  153. checks.$ZodCheckStringFormat.init(inst, def);
  154. $ZodString.init(inst, def);
  155. });
  156. export const $ZodGUID = /*@__PURE__*/ core.$constructor("$ZodGUID", (inst, def) => {
  157. def.pattern ?? (def.pattern = regexes.guid);
  158. $ZodStringFormat.init(inst, def);
  159. });
  160. export const $ZodUUID = /*@__PURE__*/ core.$constructor("$ZodUUID", (inst, def) => {
  161. if (def.version) {
  162. const versionMap = {
  163. v1: 1,
  164. v2: 2,
  165. v3: 3,
  166. v4: 4,
  167. v5: 5,
  168. v6: 6,
  169. v7: 7,
  170. v8: 8,
  171. };
  172. const v = versionMap[def.version];
  173. if (v === undefined)
  174. throw new Error(`Invalid UUID version: "${def.version}"`);
  175. def.pattern ?? (def.pattern = regexes.uuid(v));
  176. }
  177. else
  178. def.pattern ?? (def.pattern = regexes.uuid());
  179. $ZodStringFormat.init(inst, def);
  180. });
  181. export const $ZodEmail = /*@__PURE__*/ core.$constructor("$ZodEmail", (inst, def) => {
  182. def.pattern ?? (def.pattern = regexes.email);
  183. $ZodStringFormat.init(inst, def);
  184. });
  185. export const $ZodURL = /*@__PURE__*/ core.$constructor("$ZodURL", (inst, def) => {
  186. $ZodStringFormat.init(inst, def);
  187. inst._zod.check = (payload) => {
  188. try {
  189. // Trim whitespace from input
  190. const trimmed = payload.value.trim();
  191. // @ts-ignore
  192. const url = new URL(trimmed);
  193. if (def.hostname) {
  194. def.hostname.lastIndex = 0;
  195. if (!def.hostname.test(url.hostname)) {
  196. payload.issues.push({
  197. code: "invalid_format",
  198. format: "url",
  199. note: "Invalid hostname",
  200. pattern: def.hostname.source,
  201. input: payload.value,
  202. inst,
  203. continue: !def.abort,
  204. });
  205. }
  206. }
  207. if (def.protocol) {
  208. def.protocol.lastIndex = 0;
  209. if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) {
  210. payload.issues.push({
  211. code: "invalid_format",
  212. format: "url",
  213. note: "Invalid protocol",
  214. pattern: def.protocol.source,
  215. input: payload.value,
  216. inst,
  217. continue: !def.abort,
  218. });
  219. }
  220. }
  221. // Set the output value based on normalize flag
  222. if (def.normalize) {
  223. // Use normalized URL
  224. payload.value = url.href;
  225. }
  226. else {
  227. // Preserve the original input (trimmed)
  228. payload.value = trimmed;
  229. }
  230. return;
  231. }
  232. catch (_) {
  233. payload.issues.push({
  234. code: "invalid_format",
  235. format: "url",
  236. input: payload.value,
  237. inst,
  238. continue: !def.abort,
  239. });
  240. }
  241. };
  242. });
  243. export const $ZodEmoji = /*@__PURE__*/ core.$constructor("$ZodEmoji", (inst, def) => {
  244. def.pattern ?? (def.pattern = regexes.emoji());
  245. $ZodStringFormat.init(inst, def);
  246. });
  247. export const $ZodNanoID = /*@__PURE__*/ core.$constructor("$ZodNanoID", (inst, def) => {
  248. def.pattern ?? (def.pattern = regexes.nanoid);
  249. $ZodStringFormat.init(inst, def);
  250. });
  251. export const $ZodCUID = /*@__PURE__*/ core.$constructor("$ZodCUID", (inst, def) => {
  252. def.pattern ?? (def.pattern = regexes.cuid);
  253. $ZodStringFormat.init(inst, def);
  254. });
  255. export const $ZodCUID2 = /*@__PURE__*/ core.$constructor("$ZodCUID2", (inst, def) => {
  256. def.pattern ?? (def.pattern = regexes.cuid2);
  257. $ZodStringFormat.init(inst, def);
  258. });
  259. export const $ZodULID = /*@__PURE__*/ core.$constructor("$ZodULID", (inst, def) => {
  260. def.pattern ?? (def.pattern = regexes.ulid);
  261. $ZodStringFormat.init(inst, def);
  262. });
  263. export const $ZodXID = /*@__PURE__*/ core.$constructor("$ZodXID", (inst, def) => {
  264. def.pattern ?? (def.pattern = regexes.xid);
  265. $ZodStringFormat.init(inst, def);
  266. });
  267. export const $ZodKSUID = /*@__PURE__*/ core.$constructor("$ZodKSUID", (inst, def) => {
  268. def.pattern ?? (def.pattern = regexes.ksuid);
  269. $ZodStringFormat.init(inst, def);
  270. });
  271. export const $ZodISODateTime = /*@__PURE__*/ core.$constructor("$ZodISODateTime", (inst, def) => {
  272. def.pattern ?? (def.pattern = regexes.datetime(def));
  273. $ZodStringFormat.init(inst, def);
  274. });
  275. export const $ZodISODate = /*@__PURE__*/ core.$constructor("$ZodISODate", (inst, def) => {
  276. def.pattern ?? (def.pattern = regexes.date);
  277. $ZodStringFormat.init(inst, def);
  278. });
  279. export const $ZodISOTime = /*@__PURE__*/ core.$constructor("$ZodISOTime", (inst, def) => {
  280. def.pattern ?? (def.pattern = regexes.time(def));
  281. $ZodStringFormat.init(inst, def);
  282. });
  283. export const $ZodISODuration = /*@__PURE__*/ core.$constructor("$ZodISODuration", (inst, def) => {
  284. def.pattern ?? (def.pattern = regexes.duration);
  285. $ZodStringFormat.init(inst, def);
  286. });
  287. export const $ZodIPv4 = /*@__PURE__*/ core.$constructor("$ZodIPv4", (inst, def) => {
  288. def.pattern ?? (def.pattern = regexes.ipv4);
  289. $ZodStringFormat.init(inst, def);
  290. inst._zod.bag.format = `ipv4`;
  291. });
  292. export const $ZodIPv6 = /*@__PURE__*/ core.$constructor("$ZodIPv6", (inst, def) => {
  293. def.pattern ?? (def.pattern = regexes.ipv6);
  294. $ZodStringFormat.init(inst, def);
  295. inst._zod.bag.format = `ipv6`;
  296. inst._zod.check = (payload) => {
  297. try {
  298. // @ts-ignore
  299. new URL(`http://[${payload.value}]`);
  300. // return;
  301. }
  302. catch {
  303. payload.issues.push({
  304. code: "invalid_format",
  305. format: "ipv6",
  306. input: payload.value,
  307. inst,
  308. continue: !def.abort,
  309. });
  310. }
  311. };
  312. });
  313. export const $ZodMAC = /*@__PURE__*/ core.$constructor("$ZodMAC", (inst, def) => {
  314. def.pattern ?? (def.pattern = regexes.mac(def.delimiter));
  315. $ZodStringFormat.init(inst, def);
  316. inst._zod.bag.format = `mac`;
  317. });
  318. export const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor("$ZodCIDRv4", (inst, def) => {
  319. def.pattern ?? (def.pattern = regexes.cidrv4);
  320. $ZodStringFormat.init(inst, def);
  321. });
  322. export const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor("$ZodCIDRv6", (inst, def) => {
  323. def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation
  324. $ZodStringFormat.init(inst, def);
  325. inst._zod.check = (payload) => {
  326. const parts = payload.value.split("/");
  327. try {
  328. if (parts.length !== 2)
  329. throw new Error();
  330. const [address, prefix] = parts;
  331. if (!prefix)
  332. throw new Error();
  333. const prefixNum = Number(prefix);
  334. if (`${prefixNum}` !== prefix)
  335. throw new Error();
  336. if (prefixNum < 0 || prefixNum > 128)
  337. throw new Error();
  338. // @ts-ignore
  339. new URL(`http://[${address}]`);
  340. }
  341. catch {
  342. payload.issues.push({
  343. code: "invalid_format",
  344. format: "cidrv6",
  345. input: payload.value,
  346. inst,
  347. continue: !def.abort,
  348. });
  349. }
  350. };
  351. });
  352. ////////////////////////////// ZodBase64 //////////////////////////////
  353. export function isValidBase64(data) {
  354. if (data === "")
  355. return true;
  356. if (data.length % 4 !== 0)
  357. return false;
  358. try {
  359. // @ts-ignore
  360. atob(data);
  361. return true;
  362. }
  363. catch {
  364. return false;
  365. }
  366. }
  367. export const $ZodBase64 = /*@__PURE__*/ core.$constructor("$ZodBase64", (inst, def) => {
  368. def.pattern ?? (def.pattern = regexes.base64);
  369. $ZodStringFormat.init(inst, def);
  370. inst._zod.bag.contentEncoding = "base64";
  371. inst._zod.check = (payload) => {
  372. if (isValidBase64(payload.value))
  373. return;
  374. payload.issues.push({
  375. code: "invalid_format",
  376. format: "base64",
  377. input: payload.value,
  378. inst,
  379. continue: !def.abort,
  380. });
  381. };
  382. });
  383. ////////////////////////////// ZodBase64 //////////////////////////////
  384. export function isValidBase64URL(data) {
  385. if (!regexes.base64url.test(data))
  386. return false;
  387. const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/"));
  388. const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
  389. return isValidBase64(padded);
  390. }
  391. export const $ZodBase64URL = /*@__PURE__*/ core.$constructor("$ZodBase64URL", (inst, def) => {
  392. def.pattern ?? (def.pattern = regexes.base64url);
  393. $ZodStringFormat.init(inst, def);
  394. inst._zod.bag.contentEncoding = "base64url";
  395. inst._zod.check = (payload) => {
  396. if (isValidBase64URL(payload.value))
  397. return;
  398. payload.issues.push({
  399. code: "invalid_format",
  400. format: "base64url",
  401. input: payload.value,
  402. inst,
  403. continue: !def.abort,
  404. });
  405. };
  406. });
  407. export const $ZodE164 = /*@__PURE__*/ core.$constructor("$ZodE164", (inst, def) => {
  408. def.pattern ?? (def.pattern = regexes.e164);
  409. $ZodStringFormat.init(inst, def);
  410. });
  411. ////////////////////////////// ZodJWT //////////////////////////////
  412. export function isValidJWT(token, algorithm = null) {
  413. try {
  414. const tokensParts = token.split(".");
  415. if (tokensParts.length !== 3)
  416. return false;
  417. const [header] = tokensParts;
  418. if (!header)
  419. return false;
  420. // @ts-ignore
  421. const parsedHeader = JSON.parse(atob(header));
  422. if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
  423. return false;
  424. if (!parsedHeader.alg)
  425. return false;
  426. if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
  427. return false;
  428. return true;
  429. }
  430. catch {
  431. return false;
  432. }
  433. }
  434. export const $ZodJWT = /*@__PURE__*/ core.$constructor("$ZodJWT", (inst, def) => {
  435. $ZodStringFormat.init(inst, def);
  436. inst._zod.check = (payload) => {
  437. if (isValidJWT(payload.value, def.alg))
  438. return;
  439. payload.issues.push({
  440. code: "invalid_format",
  441. format: "jwt",
  442. input: payload.value,
  443. inst,
  444. continue: !def.abort,
  445. });
  446. };
  447. });
  448. export const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor("$ZodCustomStringFormat", (inst, def) => {
  449. $ZodStringFormat.init(inst, def);
  450. inst._zod.check = (payload) => {
  451. if (def.fn(payload.value))
  452. return;
  453. payload.issues.push({
  454. code: "invalid_format",
  455. format: def.format,
  456. input: payload.value,
  457. inst,
  458. continue: !def.abort,
  459. });
  460. };
  461. });
  462. export const $ZodNumber = /*@__PURE__*/ core.$constructor("$ZodNumber", (inst, def) => {
  463. $ZodType.init(inst, def);
  464. inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;
  465. inst._zod.parse = (payload, _ctx) => {
  466. if (def.coerce)
  467. try {
  468. payload.value = Number(payload.value);
  469. }
  470. catch (_) { }
  471. const input = payload.value;
  472. if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
  473. return payload;
  474. }
  475. const received = typeof input === "number"
  476. ? Number.isNaN(input)
  477. ? "NaN"
  478. : !Number.isFinite(input)
  479. ? "Infinity"
  480. : undefined
  481. : undefined;
  482. payload.issues.push({
  483. expected: "number",
  484. code: "invalid_type",
  485. input,
  486. inst,
  487. ...(received ? { received } : {}),
  488. });
  489. return payload;
  490. };
  491. });
  492. export const $ZodNumberFormat = /*@__PURE__*/ core.$constructor("$ZodNumberFormat", (inst, def) => {
  493. checks.$ZodCheckNumberFormat.init(inst, def);
  494. $ZodNumber.init(inst, def); // no format checks
  495. });
  496. export const $ZodBoolean = /*@__PURE__*/ core.$constructor("$ZodBoolean", (inst, def) => {
  497. $ZodType.init(inst, def);
  498. inst._zod.pattern = regexes.boolean;
  499. inst._zod.parse = (payload, _ctx) => {
  500. if (def.coerce)
  501. try {
  502. payload.value = Boolean(payload.value);
  503. }
  504. catch (_) { }
  505. const input = payload.value;
  506. if (typeof input === "boolean")
  507. return payload;
  508. payload.issues.push({
  509. expected: "boolean",
  510. code: "invalid_type",
  511. input,
  512. inst,
  513. });
  514. return payload;
  515. };
  516. });
  517. export const $ZodBigInt = /*@__PURE__*/ core.$constructor("$ZodBigInt", (inst, def) => {
  518. $ZodType.init(inst, def);
  519. inst._zod.pattern = regexes.bigint;
  520. inst._zod.parse = (payload, _ctx) => {
  521. if (def.coerce)
  522. try {
  523. payload.value = BigInt(payload.value);
  524. }
  525. catch (_) { }
  526. if (typeof payload.value === "bigint")
  527. return payload;
  528. payload.issues.push({
  529. expected: "bigint",
  530. code: "invalid_type",
  531. input: payload.value,
  532. inst,
  533. });
  534. return payload;
  535. };
  536. });
  537. export const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor("$ZodBigIntFormat", (inst, def) => {
  538. checks.$ZodCheckBigIntFormat.init(inst, def);
  539. $ZodBigInt.init(inst, def); // no format checks
  540. });
  541. export const $ZodSymbol = /*@__PURE__*/ core.$constructor("$ZodSymbol", (inst, def) => {
  542. $ZodType.init(inst, def);
  543. inst._zod.parse = (payload, _ctx) => {
  544. const input = payload.value;
  545. if (typeof input === "symbol")
  546. return payload;
  547. payload.issues.push({
  548. expected: "symbol",
  549. code: "invalid_type",
  550. input,
  551. inst,
  552. });
  553. return payload;
  554. };
  555. });
  556. export const $ZodUndefined = /*@__PURE__*/ core.$constructor("$ZodUndefined", (inst, def) => {
  557. $ZodType.init(inst, def);
  558. inst._zod.pattern = regexes.undefined;
  559. inst._zod.values = new Set([undefined]);
  560. inst._zod.optin = "optional";
  561. inst._zod.optout = "optional";
  562. inst._zod.parse = (payload, _ctx) => {
  563. const input = payload.value;
  564. if (typeof input === "undefined")
  565. return payload;
  566. payload.issues.push({
  567. expected: "undefined",
  568. code: "invalid_type",
  569. input,
  570. inst,
  571. });
  572. return payload;
  573. };
  574. });
  575. export const $ZodNull = /*@__PURE__*/ core.$constructor("$ZodNull", (inst, def) => {
  576. $ZodType.init(inst, def);
  577. inst._zod.pattern = regexes.null;
  578. inst._zod.values = new Set([null]);
  579. inst._zod.parse = (payload, _ctx) => {
  580. const input = payload.value;
  581. if (input === null)
  582. return payload;
  583. payload.issues.push({
  584. expected: "null",
  585. code: "invalid_type",
  586. input,
  587. inst,
  588. });
  589. return payload;
  590. };
  591. });
  592. export const $ZodAny = /*@__PURE__*/ core.$constructor("$ZodAny", (inst, def) => {
  593. $ZodType.init(inst, def);
  594. inst._zod.parse = (payload) => payload;
  595. });
  596. export const $ZodUnknown = /*@__PURE__*/ core.$constructor("$ZodUnknown", (inst, def) => {
  597. $ZodType.init(inst, def);
  598. inst._zod.parse = (payload) => payload;
  599. });
  600. export const $ZodNever = /*@__PURE__*/ core.$constructor("$ZodNever", (inst, def) => {
  601. $ZodType.init(inst, def);
  602. inst._zod.parse = (payload, _ctx) => {
  603. payload.issues.push({
  604. expected: "never",
  605. code: "invalid_type",
  606. input: payload.value,
  607. inst,
  608. });
  609. return payload;
  610. };
  611. });
  612. export const $ZodVoid = /*@__PURE__*/ core.$constructor("$ZodVoid", (inst, def) => {
  613. $ZodType.init(inst, def);
  614. inst._zod.parse = (payload, _ctx) => {
  615. const input = payload.value;
  616. if (typeof input === "undefined")
  617. return payload;
  618. payload.issues.push({
  619. expected: "void",
  620. code: "invalid_type",
  621. input,
  622. inst,
  623. });
  624. return payload;
  625. };
  626. });
  627. export const $ZodDate = /*@__PURE__*/ core.$constructor("$ZodDate", (inst, def) => {
  628. $ZodType.init(inst, def);
  629. inst._zod.parse = (payload, _ctx) => {
  630. if (def.coerce) {
  631. try {
  632. payload.value = new Date(payload.value);
  633. }
  634. catch (_err) { }
  635. }
  636. const input = payload.value;
  637. const isDate = input instanceof Date;
  638. const isValidDate = isDate && !Number.isNaN(input.getTime());
  639. if (isValidDate)
  640. return payload;
  641. payload.issues.push({
  642. expected: "date",
  643. code: "invalid_type",
  644. input,
  645. ...(isDate ? { received: "Invalid Date" } : {}),
  646. inst,
  647. });
  648. return payload;
  649. };
  650. });
  651. function handleArrayResult(result, final, index) {
  652. if (result.issues.length) {
  653. final.issues.push(...util.prefixIssues(index, result.issues));
  654. }
  655. final.value[index] = result.value;
  656. }
  657. export const $ZodArray = /*@__PURE__*/ core.$constructor("$ZodArray", (inst, def) => {
  658. $ZodType.init(inst, def);
  659. inst._zod.parse = (payload, ctx) => {
  660. const input = payload.value;
  661. if (!Array.isArray(input)) {
  662. payload.issues.push({
  663. expected: "array",
  664. code: "invalid_type",
  665. input,
  666. inst,
  667. });
  668. return payload;
  669. }
  670. payload.value = Array(input.length);
  671. const proms = [];
  672. for (let i = 0; i < input.length; i++) {
  673. const item = input[i];
  674. const result = def.element._zod.run({
  675. value: item,
  676. issues: [],
  677. }, ctx);
  678. if (result instanceof Promise) {
  679. proms.push(result.then((result) => handleArrayResult(result, payload, i)));
  680. }
  681. else {
  682. handleArrayResult(result, payload, i);
  683. }
  684. }
  685. if (proms.length) {
  686. return Promise.all(proms).then(() => payload);
  687. }
  688. return payload; //handleArrayResultsAsync(parseResults, final);
  689. };
  690. });
  691. function handlePropertyResult(result, final, key, input, isOptionalOut) {
  692. if (result.issues.length) {
  693. // For optional-out schemas, ignore errors on absent keys
  694. if (isOptionalOut && !(key in input)) {
  695. return;
  696. }
  697. final.issues.push(...util.prefixIssues(key, result.issues));
  698. }
  699. if (result.value === undefined) {
  700. if (key in input) {
  701. final.value[key] = undefined;
  702. }
  703. }
  704. else {
  705. final.value[key] = result.value;
  706. }
  707. }
  708. function normalizeDef(def) {
  709. const keys = Object.keys(def.shape);
  710. for (const k of keys) {
  711. if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) {
  712. throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
  713. }
  714. }
  715. const okeys = util.optionalKeys(def.shape);
  716. return {
  717. ...def,
  718. keys,
  719. keySet: new Set(keys),
  720. numKeys: keys.length,
  721. optionalKeys: new Set(okeys),
  722. };
  723. }
  724. function handleCatchall(proms, input, payload, ctx, def, inst) {
  725. const unrecognized = [];
  726. // iterate over input keys
  727. const keySet = def.keySet;
  728. const _catchall = def.catchall._zod;
  729. const t = _catchall.def.type;
  730. const isOptionalOut = _catchall.optout === "optional";
  731. for (const key in input) {
  732. if (keySet.has(key))
  733. continue;
  734. if (t === "never") {
  735. unrecognized.push(key);
  736. continue;
  737. }
  738. const r = _catchall.run({ value: input[key], issues: [] }, ctx);
  739. if (r instanceof Promise) {
  740. proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));
  741. }
  742. else {
  743. handlePropertyResult(r, payload, key, input, isOptionalOut);
  744. }
  745. }
  746. if (unrecognized.length) {
  747. payload.issues.push({
  748. code: "unrecognized_keys",
  749. keys: unrecognized,
  750. input,
  751. inst,
  752. });
  753. }
  754. if (!proms.length)
  755. return payload;
  756. return Promise.all(proms).then(() => {
  757. return payload;
  758. });
  759. }
  760. export const $ZodObject = /*@__PURE__*/ core.$constructor("$ZodObject", (inst, def) => {
  761. // requires cast because technically $ZodObject doesn't extend
  762. $ZodType.init(inst, def);
  763. // const sh = def.shape;
  764. const desc = Object.getOwnPropertyDescriptor(def, "shape");
  765. if (!desc?.get) {
  766. const sh = def.shape;
  767. Object.defineProperty(def, "shape", {
  768. get: () => {
  769. const newSh = { ...sh };
  770. Object.defineProperty(def, "shape", {
  771. value: newSh,
  772. });
  773. return newSh;
  774. },
  775. });
  776. }
  777. const _normalized = util.cached(() => normalizeDef(def));
  778. util.defineLazy(inst._zod, "propValues", () => {
  779. const shape = def.shape;
  780. const propValues = {};
  781. for (const key in shape) {
  782. const field = shape[key]._zod;
  783. if (field.values) {
  784. propValues[key] ?? (propValues[key] = new Set());
  785. for (const v of field.values)
  786. propValues[key].add(v);
  787. }
  788. }
  789. return propValues;
  790. });
  791. const isObject = util.isObject;
  792. const catchall = def.catchall;
  793. let value;
  794. inst._zod.parse = (payload, ctx) => {
  795. value ?? (value = _normalized.value);
  796. const input = payload.value;
  797. if (!isObject(input)) {
  798. payload.issues.push({
  799. expected: "object",
  800. code: "invalid_type",
  801. input,
  802. inst,
  803. });
  804. return payload;
  805. }
  806. payload.value = {};
  807. const proms = [];
  808. const shape = value.shape;
  809. for (const key of value.keys) {
  810. const el = shape[key];
  811. const isOptionalOut = el._zod.optout === "optional";
  812. const r = el._zod.run({ value: input[key], issues: [] }, ctx);
  813. if (r instanceof Promise) {
  814. proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));
  815. }
  816. else {
  817. handlePropertyResult(r, payload, key, input, isOptionalOut);
  818. }
  819. }
  820. if (!catchall) {
  821. return proms.length ? Promise.all(proms).then(() => payload) : payload;
  822. }
  823. return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
  824. };
  825. });
  826. export const $ZodObjectJIT = /*@__PURE__*/ core.$constructor("$ZodObjectJIT", (inst, def) => {
  827. // requires cast because technically $ZodObject doesn't extend
  828. $ZodObject.init(inst, def);
  829. const superParse = inst._zod.parse;
  830. const _normalized = util.cached(() => normalizeDef(def));
  831. const generateFastpass = (shape) => {
  832. const doc = new Doc(["shape", "payload", "ctx"]);
  833. const normalized = _normalized.value;
  834. const parseStr = (key) => {
  835. const k = util.esc(key);
  836. return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
  837. };
  838. doc.write(`const input = payload.value;`);
  839. const ids = Object.create(null);
  840. let counter = 0;
  841. for (const key of normalized.keys) {
  842. ids[key] = `key_${counter++}`;
  843. }
  844. // A: preserve key order {
  845. doc.write(`const newResult = {};`);
  846. for (const key of normalized.keys) {
  847. const id = ids[key];
  848. const k = util.esc(key);
  849. const schema = shape[key];
  850. const isOptionalOut = schema?._zod?.optout === "optional";
  851. doc.write(`const ${id} = ${parseStr(key)};`);
  852. if (isOptionalOut) {
  853. // For optional-out schemas, ignore errors on absent keys
  854. doc.write(`
  855. if (${id}.issues.length) {
  856. if (${k} in input) {
  857. payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
  858. ...iss,
  859. path: iss.path ? [${k}, ...iss.path] : [${k}]
  860. })));
  861. }
  862. }
  863. if (${id}.value === undefined) {
  864. if (${k} in input) {
  865. newResult[${k}] = undefined;
  866. }
  867. } else {
  868. newResult[${k}] = ${id}.value;
  869. }
  870. `);
  871. }
  872. else {
  873. doc.write(`
  874. if (${id}.issues.length) {
  875. payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
  876. ...iss,
  877. path: iss.path ? [${k}, ...iss.path] : [${k}]
  878. })));
  879. }
  880. if (${id}.value === undefined) {
  881. if (${k} in input) {
  882. newResult[${k}] = undefined;
  883. }
  884. } else {
  885. newResult[${k}] = ${id}.value;
  886. }
  887. `);
  888. }
  889. }
  890. doc.write(`payload.value = newResult;`);
  891. doc.write(`return payload;`);
  892. const fn = doc.compile();
  893. return (payload, ctx) => fn(shape, payload, ctx);
  894. };
  895. let fastpass;
  896. const isObject = util.isObject;
  897. const jit = !core.globalConfig.jitless;
  898. const allowsEval = util.allowsEval;
  899. const fastEnabled = jit && allowsEval.value; // && !def.catchall;
  900. const catchall = def.catchall;
  901. let value;
  902. inst._zod.parse = (payload, ctx) => {
  903. value ?? (value = _normalized.value);
  904. const input = payload.value;
  905. if (!isObject(input)) {
  906. payload.issues.push({
  907. expected: "object",
  908. code: "invalid_type",
  909. input,
  910. inst,
  911. });
  912. return payload;
  913. }
  914. if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
  915. // always synchronous
  916. if (!fastpass)
  917. fastpass = generateFastpass(def.shape);
  918. payload = fastpass(payload, ctx);
  919. if (!catchall)
  920. return payload;
  921. return handleCatchall([], input, payload, ctx, value, inst);
  922. }
  923. return superParse(payload, ctx);
  924. };
  925. });
  926. function handleUnionResults(results, final, inst, ctx) {
  927. for (const result of results) {
  928. if (result.issues.length === 0) {
  929. final.value = result.value;
  930. return final;
  931. }
  932. }
  933. const nonaborted = results.filter((r) => !util.aborted(r));
  934. if (nonaborted.length === 1) {
  935. final.value = nonaborted[0].value;
  936. return nonaborted[0];
  937. }
  938. final.issues.push({
  939. code: "invalid_union",
  940. input: final.value,
  941. inst,
  942. errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),
  943. });
  944. return final;
  945. }
  946. export const $ZodUnion = /*@__PURE__*/ core.$constructor("$ZodUnion", (inst, def) => {
  947. $ZodType.init(inst, def);
  948. util.defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined);
  949. util.defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined);
  950. util.defineLazy(inst._zod, "values", () => {
  951. if (def.options.every((o) => o._zod.values)) {
  952. return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
  953. }
  954. return undefined;
  955. });
  956. util.defineLazy(inst._zod, "pattern", () => {
  957. if (def.options.every((o) => o._zod.pattern)) {
  958. const patterns = def.options.map((o) => o._zod.pattern);
  959. return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join("|")})$`);
  960. }
  961. return undefined;
  962. });
  963. const single = def.options.length === 1;
  964. const first = def.options[0]._zod.run;
  965. inst._zod.parse = (payload, ctx) => {
  966. if (single) {
  967. return first(payload, ctx);
  968. }
  969. let async = false;
  970. const results = [];
  971. for (const option of def.options) {
  972. const result = option._zod.run({
  973. value: payload.value,
  974. issues: [],
  975. }, ctx);
  976. if (result instanceof Promise) {
  977. results.push(result);
  978. async = true;
  979. }
  980. else {
  981. if (result.issues.length === 0)
  982. return result;
  983. results.push(result);
  984. }
  985. }
  986. if (!async)
  987. return handleUnionResults(results, payload, inst, ctx);
  988. return Promise.all(results).then((results) => {
  989. return handleUnionResults(results, payload, inst, ctx);
  990. });
  991. };
  992. });
  993. function handleExclusiveUnionResults(results, final, inst, ctx) {
  994. const successes = results.filter((r) => r.issues.length === 0);
  995. if (successes.length === 1) {
  996. final.value = successes[0].value;
  997. return final;
  998. }
  999. if (successes.length === 0) {
  1000. // No matches - same as regular union
  1001. final.issues.push({
  1002. code: "invalid_union",
  1003. input: final.value,
  1004. inst,
  1005. errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),
  1006. });
  1007. }
  1008. else {
  1009. // Multiple matches - exclusive union failure
  1010. final.issues.push({
  1011. code: "invalid_union",
  1012. input: final.value,
  1013. inst,
  1014. errors: [],
  1015. inclusive: false,
  1016. });
  1017. }
  1018. return final;
  1019. }
  1020. export const $ZodXor = /*@__PURE__*/ core.$constructor("$ZodXor", (inst, def) => {
  1021. $ZodUnion.init(inst, def);
  1022. def.inclusive = false;
  1023. const single = def.options.length === 1;
  1024. const first = def.options[0]._zod.run;
  1025. inst._zod.parse = (payload, ctx) => {
  1026. if (single) {
  1027. return first(payload, ctx);
  1028. }
  1029. let async = false;
  1030. const results = [];
  1031. for (const option of def.options) {
  1032. const result = option._zod.run({
  1033. value: payload.value,
  1034. issues: [],
  1035. }, ctx);
  1036. if (result instanceof Promise) {
  1037. results.push(result);
  1038. async = true;
  1039. }
  1040. else {
  1041. results.push(result);
  1042. }
  1043. }
  1044. if (!async)
  1045. return handleExclusiveUnionResults(results, payload, inst, ctx);
  1046. return Promise.all(results).then((results) => {
  1047. return handleExclusiveUnionResults(results, payload, inst, ctx);
  1048. });
  1049. };
  1050. });
  1051. export const $ZodDiscriminatedUnion =
  1052. /*@__PURE__*/
  1053. core.$constructor("$ZodDiscriminatedUnion", (inst, def) => {
  1054. def.inclusive = false;
  1055. $ZodUnion.init(inst, def);
  1056. const _super = inst._zod.parse;
  1057. util.defineLazy(inst._zod, "propValues", () => {
  1058. const propValues = {};
  1059. for (const option of def.options) {
  1060. const pv = option._zod.propValues;
  1061. if (!pv || Object.keys(pv).length === 0)
  1062. throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
  1063. for (const [k, v] of Object.entries(pv)) {
  1064. if (!propValues[k])
  1065. propValues[k] = new Set();
  1066. for (const val of v) {
  1067. propValues[k].add(val);
  1068. }
  1069. }
  1070. }
  1071. return propValues;
  1072. });
  1073. const disc = util.cached(() => {
  1074. const opts = def.options;
  1075. const map = new Map();
  1076. for (const o of opts) {
  1077. const values = o._zod.propValues?.[def.discriminator];
  1078. if (!values || values.size === 0)
  1079. throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
  1080. for (const v of values) {
  1081. if (map.has(v)) {
  1082. throw new Error(`Duplicate discriminator value "${String(v)}"`);
  1083. }
  1084. map.set(v, o);
  1085. }
  1086. }
  1087. return map;
  1088. });
  1089. inst._zod.parse = (payload, ctx) => {
  1090. const input = payload.value;
  1091. if (!util.isObject(input)) {
  1092. payload.issues.push({
  1093. code: "invalid_type",
  1094. expected: "object",
  1095. input,
  1096. inst,
  1097. });
  1098. return payload;
  1099. }
  1100. const opt = disc.value.get(input?.[def.discriminator]);
  1101. if (opt) {
  1102. return opt._zod.run(payload, ctx);
  1103. }
  1104. if (def.unionFallback) {
  1105. return _super(payload, ctx);
  1106. }
  1107. // no matching discriminator
  1108. payload.issues.push({
  1109. code: "invalid_union",
  1110. errors: [],
  1111. note: "No matching discriminator",
  1112. discriminator: def.discriminator,
  1113. input,
  1114. path: [def.discriminator],
  1115. inst,
  1116. });
  1117. return payload;
  1118. };
  1119. });
  1120. export const $ZodIntersection = /*@__PURE__*/ core.$constructor("$ZodIntersection", (inst, def) => {
  1121. $ZodType.init(inst, def);
  1122. inst._zod.parse = (payload, ctx) => {
  1123. const input = payload.value;
  1124. const left = def.left._zod.run({ value: input, issues: [] }, ctx);
  1125. const right = def.right._zod.run({ value: input, issues: [] }, ctx);
  1126. const async = left instanceof Promise || right instanceof Promise;
  1127. if (async) {
  1128. return Promise.all([left, right]).then(([left, right]) => {
  1129. return handleIntersectionResults(payload, left, right);
  1130. });
  1131. }
  1132. return handleIntersectionResults(payload, left, right);
  1133. };
  1134. });
  1135. function mergeValues(a, b) {
  1136. // const aType = parse.t(a);
  1137. // const bType = parse.t(b);
  1138. if (a === b) {
  1139. return { valid: true, data: a };
  1140. }
  1141. if (a instanceof Date && b instanceof Date && +a === +b) {
  1142. return { valid: true, data: a };
  1143. }
  1144. if (util.isPlainObject(a) && util.isPlainObject(b)) {
  1145. const bKeys = Object.keys(b);
  1146. const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
  1147. const newObj = { ...a, ...b };
  1148. for (const key of sharedKeys) {
  1149. const sharedValue = mergeValues(a[key], b[key]);
  1150. if (!sharedValue.valid) {
  1151. return {
  1152. valid: false,
  1153. mergeErrorPath: [key, ...sharedValue.mergeErrorPath],
  1154. };
  1155. }
  1156. newObj[key] = sharedValue.data;
  1157. }
  1158. return { valid: true, data: newObj };
  1159. }
  1160. if (Array.isArray(a) && Array.isArray(b)) {
  1161. if (a.length !== b.length) {
  1162. return { valid: false, mergeErrorPath: [] };
  1163. }
  1164. const newArray = [];
  1165. for (let index = 0; index < a.length; index++) {
  1166. const itemA = a[index];
  1167. const itemB = b[index];
  1168. const sharedValue = mergeValues(itemA, itemB);
  1169. if (!sharedValue.valid) {
  1170. return {
  1171. valid: false,
  1172. mergeErrorPath: [index, ...sharedValue.mergeErrorPath],
  1173. };
  1174. }
  1175. newArray.push(sharedValue.data);
  1176. }
  1177. return { valid: true, data: newArray };
  1178. }
  1179. return { valid: false, mergeErrorPath: [] };
  1180. }
  1181. function handleIntersectionResults(result, left, right) {
  1182. // Track which side(s) report each key as unrecognized
  1183. const unrecKeys = new Map();
  1184. let unrecIssue;
  1185. for (const iss of left.issues) {
  1186. if (iss.code === "unrecognized_keys") {
  1187. unrecIssue ?? (unrecIssue = iss);
  1188. for (const k of iss.keys) {
  1189. if (!unrecKeys.has(k))
  1190. unrecKeys.set(k, {});
  1191. unrecKeys.get(k).l = true;
  1192. }
  1193. }
  1194. else {
  1195. result.issues.push(iss);
  1196. }
  1197. }
  1198. for (const iss of right.issues) {
  1199. if (iss.code === "unrecognized_keys") {
  1200. for (const k of iss.keys) {
  1201. if (!unrecKeys.has(k))
  1202. unrecKeys.set(k, {});
  1203. unrecKeys.get(k).r = true;
  1204. }
  1205. }
  1206. else {
  1207. result.issues.push(iss);
  1208. }
  1209. }
  1210. // Report only keys unrecognized by BOTH sides
  1211. const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
  1212. if (bothKeys.length && unrecIssue) {
  1213. result.issues.push({ ...unrecIssue, keys: bothKeys });
  1214. }
  1215. if (util.aborted(result))
  1216. return result;
  1217. const merged = mergeValues(left.value, right.value);
  1218. if (!merged.valid) {
  1219. throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);
  1220. }
  1221. result.value = merged.data;
  1222. return result;
  1223. }
  1224. export const $ZodTuple = /*@__PURE__*/ core.$constructor("$ZodTuple", (inst, def) => {
  1225. $ZodType.init(inst, def);
  1226. const items = def.items;
  1227. inst._zod.parse = (payload, ctx) => {
  1228. const input = payload.value;
  1229. if (!Array.isArray(input)) {
  1230. payload.issues.push({
  1231. input,
  1232. inst,
  1233. expected: "tuple",
  1234. code: "invalid_type",
  1235. });
  1236. return payload;
  1237. }
  1238. payload.value = [];
  1239. const proms = [];
  1240. const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== "optional");
  1241. const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex;
  1242. if (!def.rest) {
  1243. const tooBig = input.length > items.length;
  1244. const tooSmall = input.length < optStart - 1;
  1245. if (tooBig || tooSmall) {
  1246. payload.issues.push({
  1247. ...(tooBig
  1248. ? { code: "too_big", maximum: items.length, inclusive: true }
  1249. : { code: "too_small", minimum: items.length }),
  1250. input,
  1251. inst,
  1252. origin: "array",
  1253. });
  1254. return payload;
  1255. }
  1256. }
  1257. let i = -1;
  1258. for (const item of items) {
  1259. i++;
  1260. if (i >= input.length)
  1261. if (i >= optStart)
  1262. continue;
  1263. const result = item._zod.run({
  1264. value: input[i],
  1265. issues: [],
  1266. }, ctx);
  1267. if (result instanceof Promise) {
  1268. proms.push(result.then((result) => handleTupleResult(result, payload, i)));
  1269. }
  1270. else {
  1271. handleTupleResult(result, payload, i);
  1272. }
  1273. }
  1274. if (def.rest) {
  1275. const rest = input.slice(items.length);
  1276. for (const el of rest) {
  1277. i++;
  1278. const result = def.rest._zod.run({
  1279. value: el,
  1280. issues: [],
  1281. }, ctx);
  1282. if (result instanceof Promise) {
  1283. proms.push(result.then((result) => handleTupleResult(result, payload, i)));
  1284. }
  1285. else {
  1286. handleTupleResult(result, payload, i);
  1287. }
  1288. }
  1289. }
  1290. if (proms.length)
  1291. return Promise.all(proms).then(() => payload);
  1292. return payload;
  1293. };
  1294. });
  1295. function handleTupleResult(result, final, index) {
  1296. if (result.issues.length) {
  1297. final.issues.push(...util.prefixIssues(index, result.issues));
  1298. }
  1299. final.value[index] = result.value;
  1300. }
  1301. export const $ZodRecord = /*@__PURE__*/ core.$constructor("$ZodRecord", (inst, def) => {
  1302. $ZodType.init(inst, def);
  1303. inst._zod.parse = (payload, ctx) => {
  1304. const input = payload.value;
  1305. if (!util.isPlainObject(input)) {
  1306. payload.issues.push({
  1307. expected: "record",
  1308. code: "invalid_type",
  1309. input,
  1310. inst,
  1311. });
  1312. return payload;
  1313. }
  1314. const proms = [];
  1315. const values = def.keyType._zod.values;
  1316. if (values) {
  1317. payload.value = {};
  1318. const recordKeys = new Set();
  1319. for (const key of values) {
  1320. if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
  1321. recordKeys.add(typeof key === "number" ? key.toString() : key);
  1322. const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
  1323. if (result instanceof Promise) {
  1324. proms.push(result.then((result) => {
  1325. if (result.issues.length) {
  1326. payload.issues.push(...util.prefixIssues(key, result.issues));
  1327. }
  1328. payload.value[key] = result.value;
  1329. }));
  1330. }
  1331. else {
  1332. if (result.issues.length) {
  1333. payload.issues.push(...util.prefixIssues(key, result.issues));
  1334. }
  1335. payload.value[key] = result.value;
  1336. }
  1337. }
  1338. }
  1339. let unrecognized;
  1340. for (const key in input) {
  1341. if (!recordKeys.has(key)) {
  1342. unrecognized = unrecognized ?? [];
  1343. unrecognized.push(key);
  1344. }
  1345. }
  1346. if (unrecognized && unrecognized.length > 0) {
  1347. payload.issues.push({
  1348. code: "unrecognized_keys",
  1349. input,
  1350. inst,
  1351. keys: unrecognized,
  1352. });
  1353. }
  1354. }
  1355. else {
  1356. payload.value = {};
  1357. for (const key of Reflect.ownKeys(input)) {
  1358. if (key === "__proto__")
  1359. continue;
  1360. let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
  1361. if (keyResult instanceof Promise) {
  1362. throw new Error("Async schemas not supported in object keys currently");
  1363. }
  1364. // Numeric string fallback: if key is a numeric string and failed, retry with Number(key)
  1365. // This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals
  1366. const checkNumericKey = typeof key === "string" && regexes.number.test(key) && keyResult.issues.length;
  1367. if (checkNumericKey) {
  1368. const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);
  1369. if (retryResult instanceof Promise) {
  1370. throw new Error("Async schemas not supported in object keys currently");
  1371. }
  1372. if (retryResult.issues.length === 0) {
  1373. keyResult = retryResult;
  1374. }
  1375. }
  1376. if (keyResult.issues.length) {
  1377. if (def.mode === "loose") {
  1378. // Pass through unchanged
  1379. payload.value[key] = input[key];
  1380. }
  1381. else {
  1382. // Default "strict" behavior: error on invalid key
  1383. payload.issues.push({
  1384. code: "invalid_key",
  1385. origin: "record",
  1386. issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),
  1387. input: key,
  1388. path: [key],
  1389. inst,
  1390. });
  1391. }
  1392. continue;
  1393. }
  1394. const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
  1395. if (result instanceof Promise) {
  1396. proms.push(result.then((result) => {
  1397. if (result.issues.length) {
  1398. payload.issues.push(...util.prefixIssues(key, result.issues));
  1399. }
  1400. payload.value[keyResult.value] = result.value;
  1401. }));
  1402. }
  1403. else {
  1404. if (result.issues.length) {
  1405. payload.issues.push(...util.prefixIssues(key, result.issues));
  1406. }
  1407. payload.value[keyResult.value] = result.value;
  1408. }
  1409. }
  1410. }
  1411. if (proms.length) {
  1412. return Promise.all(proms).then(() => payload);
  1413. }
  1414. return payload;
  1415. };
  1416. });
  1417. export const $ZodMap = /*@__PURE__*/ core.$constructor("$ZodMap", (inst, def) => {
  1418. $ZodType.init(inst, def);
  1419. inst._zod.parse = (payload, ctx) => {
  1420. const input = payload.value;
  1421. if (!(input instanceof Map)) {
  1422. payload.issues.push({
  1423. expected: "map",
  1424. code: "invalid_type",
  1425. input,
  1426. inst,
  1427. });
  1428. return payload;
  1429. }
  1430. const proms = [];
  1431. payload.value = new Map();
  1432. for (const [key, value] of input) {
  1433. const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
  1434. const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);
  1435. if (keyResult instanceof Promise || valueResult instanceof Promise) {
  1436. proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {
  1437. handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);
  1438. }));
  1439. }
  1440. else {
  1441. handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);
  1442. }
  1443. }
  1444. if (proms.length)
  1445. return Promise.all(proms).then(() => payload);
  1446. return payload;
  1447. };
  1448. });
  1449. function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {
  1450. if (keyResult.issues.length) {
  1451. if (util.propertyKeyTypes.has(typeof key)) {
  1452. final.issues.push(...util.prefixIssues(key, keyResult.issues));
  1453. }
  1454. else {
  1455. final.issues.push({
  1456. code: "invalid_key",
  1457. origin: "map",
  1458. input,
  1459. inst,
  1460. issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),
  1461. });
  1462. }
  1463. }
  1464. if (valueResult.issues.length) {
  1465. if (util.propertyKeyTypes.has(typeof key)) {
  1466. final.issues.push(...util.prefixIssues(key, valueResult.issues));
  1467. }
  1468. else {
  1469. final.issues.push({
  1470. origin: "map",
  1471. code: "invalid_element",
  1472. input,
  1473. inst,
  1474. key: key,
  1475. issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),
  1476. });
  1477. }
  1478. }
  1479. final.value.set(keyResult.value, valueResult.value);
  1480. }
  1481. export const $ZodSet = /*@__PURE__*/ core.$constructor("$ZodSet", (inst, def) => {
  1482. $ZodType.init(inst, def);
  1483. inst._zod.parse = (payload, ctx) => {
  1484. const input = payload.value;
  1485. if (!(input instanceof Set)) {
  1486. payload.issues.push({
  1487. input,
  1488. inst,
  1489. expected: "set",
  1490. code: "invalid_type",
  1491. });
  1492. return payload;
  1493. }
  1494. const proms = [];
  1495. payload.value = new Set();
  1496. for (const item of input) {
  1497. const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);
  1498. if (result instanceof Promise) {
  1499. proms.push(result.then((result) => handleSetResult(result, payload)));
  1500. }
  1501. else
  1502. handleSetResult(result, payload);
  1503. }
  1504. if (proms.length)
  1505. return Promise.all(proms).then(() => payload);
  1506. return payload;
  1507. };
  1508. });
  1509. function handleSetResult(result, final) {
  1510. if (result.issues.length) {
  1511. final.issues.push(...result.issues);
  1512. }
  1513. final.value.add(result.value);
  1514. }
  1515. export const $ZodEnum = /*@__PURE__*/ core.$constructor("$ZodEnum", (inst, def) => {
  1516. $ZodType.init(inst, def);
  1517. const values = util.getEnumValues(def.entries);
  1518. const valuesSet = new Set(values);
  1519. inst._zod.values = valuesSet;
  1520. inst._zod.pattern = new RegExp(`^(${values
  1521. .filter((k) => util.propertyKeyTypes.has(typeof k))
  1522. .map((o) => (typeof o === "string" ? util.escapeRegex(o) : o.toString()))
  1523. .join("|")})$`);
  1524. inst._zod.parse = (payload, _ctx) => {
  1525. const input = payload.value;
  1526. if (valuesSet.has(input)) {
  1527. return payload;
  1528. }
  1529. payload.issues.push({
  1530. code: "invalid_value",
  1531. values,
  1532. input,
  1533. inst,
  1534. });
  1535. return payload;
  1536. };
  1537. });
  1538. export const $ZodLiteral = /*@__PURE__*/ core.$constructor("$ZodLiteral", (inst, def) => {
  1539. $ZodType.init(inst, def);
  1540. if (def.values.length === 0) {
  1541. throw new Error("Cannot create literal schema with no valid values");
  1542. }
  1543. const values = new Set(def.values);
  1544. inst._zod.values = values;
  1545. inst._zod.pattern = new RegExp(`^(${def.values
  1546. .map((o) => (typeof o === "string" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))
  1547. .join("|")})$`);
  1548. inst._zod.parse = (payload, _ctx) => {
  1549. const input = payload.value;
  1550. if (values.has(input)) {
  1551. return payload;
  1552. }
  1553. payload.issues.push({
  1554. code: "invalid_value",
  1555. values: def.values,
  1556. input,
  1557. inst,
  1558. });
  1559. return payload;
  1560. };
  1561. });
  1562. export const $ZodFile = /*@__PURE__*/ core.$constructor("$ZodFile", (inst, def) => {
  1563. $ZodType.init(inst, def);
  1564. inst._zod.parse = (payload, _ctx) => {
  1565. const input = payload.value;
  1566. // @ts-ignore
  1567. if (input instanceof File)
  1568. return payload;
  1569. payload.issues.push({
  1570. expected: "file",
  1571. code: "invalid_type",
  1572. input,
  1573. inst,
  1574. });
  1575. return payload;
  1576. };
  1577. });
  1578. export const $ZodTransform = /*@__PURE__*/ core.$constructor("$ZodTransform", (inst, def) => {
  1579. $ZodType.init(inst, def);
  1580. inst._zod.parse = (payload, ctx) => {
  1581. if (ctx.direction === "backward") {
  1582. throw new core.$ZodEncodeError(inst.constructor.name);
  1583. }
  1584. const _out = def.transform(payload.value, payload);
  1585. if (ctx.async) {
  1586. const output = _out instanceof Promise ? _out : Promise.resolve(_out);
  1587. return output.then((output) => {
  1588. payload.value = output;
  1589. return payload;
  1590. });
  1591. }
  1592. if (_out instanceof Promise) {
  1593. throw new core.$ZodAsyncError();
  1594. }
  1595. payload.value = _out;
  1596. return payload;
  1597. };
  1598. });
  1599. function handleOptionalResult(result, input) {
  1600. if (result.issues.length && input === undefined) {
  1601. return { issues: [], value: undefined };
  1602. }
  1603. return result;
  1604. }
  1605. export const $ZodOptional = /*@__PURE__*/ core.$constructor("$ZodOptional", (inst, def) => {
  1606. $ZodType.init(inst, def);
  1607. inst._zod.optin = "optional";
  1608. inst._zod.optout = "optional";
  1609. util.defineLazy(inst._zod, "values", () => {
  1610. return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;
  1611. });
  1612. util.defineLazy(inst._zod, "pattern", () => {
  1613. const pattern = def.innerType._zod.pattern;
  1614. return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;
  1615. });
  1616. inst._zod.parse = (payload, ctx) => {
  1617. if (def.innerType._zod.optin === "optional") {
  1618. const result = def.innerType._zod.run(payload, ctx);
  1619. if (result instanceof Promise)
  1620. return result.then((r) => handleOptionalResult(r, payload.value));
  1621. return handleOptionalResult(result, payload.value);
  1622. }
  1623. if (payload.value === undefined) {
  1624. return payload;
  1625. }
  1626. return def.innerType._zod.run(payload, ctx);
  1627. };
  1628. });
  1629. export const $ZodExactOptional = /*@__PURE__*/ core.$constructor("$ZodExactOptional", (inst, def) => {
  1630. // Call parent init - inherits optin/optout = "optional"
  1631. $ZodOptional.init(inst, def);
  1632. // Override values/pattern to NOT add undefined
  1633. util.defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  1634. util.defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern);
  1635. // Override parse to just delegate (no undefined handling)
  1636. inst._zod.parse = (payload, ctx) => {
  1637. return def.innerType._zod.run(payload, ctx);
  1638. };
  1639. });
  1640. export const $ZodNullable = /*@__PURE__*/ core.$constructor("$ZodNullable", (inst, def) => {
  1641. $ZodType.init(inst, def);
  1642. util.defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
  1643. util.defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
  1644. util.defineLazy(inst._zod, "pattern", () => {
  1645. const pattern = def.innerType._zod.pattern;
  1646. return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;
  1647. });
  1648. util.defineLazy(inst._zod, "values", () => {
  1649. return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;
  1650. });
  1651. inst._zod.parse = (payload, ctx) => {
  1652. // Forward direction (decode): allow null to pass through
  1653. if (payload.value === null)
  1654. return payload;
  1655. return def.innerType._zod.run(payload, ctx);
  1656. };
  1657. });
  1658. export const $ZodDefault = /*@__PURE__*/ core.$constructor("$ZodDefault", (inst, def) => {
  1659. $ZodType.init(inst, def);
  1660. // inst._zod.qin = "true";
  1661. inst._zod.optin = "optional";
  1662. util.defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  1663. inst._zod.parse = (payload, ctx) => {
  1664. if (ctx.direction === "backward") {
  1665. return def.innerType._zod.run(payload, ctx);
  1666. }
  1667. // Forward direction (decode): apply defaults for undefined input
  1668. if (payload.value === undefined) {
  1669. payload.value = def.defaultValue;
  1670. /**
  1671. * $ZodDefault returns the default value immediately in forward direction.
  1672. * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */
  1673. return payload;
  1674. }
  1675. // Forward direction: continue with default handling
  1676. const result = def.innerType._zod.run(payload, ctx);
  1677. if (result instanceof Promise) {
  1678. return result.then((result) => handleDefaultResult(result, def));
  1679. }
  1680. return handleDefaultResult(result, def);
  1681. };
  1682. });
  1683. function handleDefaultResult(payload, def) {
  1684. if (payload.value === undefined) {
  1685. payload.value = def.defaultValue;
  1686. }
  1687. return payload;
  1688. }
  1689. export const $ZodPrefault = /*@__PURE__*/ core.$constructor("$ZodPrefault", (inst, def) => {
  1690. $ZodType.init(inst, def);
  1691. inst._zod.optin = "optional";
  1692. util.defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  1693. inst._zod.parse = (payload, ctx) => {
  1694. if (ctx.direction === "backward") {
  1695. return def.innerType._zod.run(payload, ctx);
  1696. }
  1697. // Forward direction (decode): apply prefault for undefined input
  1698. if (payload.value === undefined) {
  1699. payload.value = def.defaultValue;
  1700. }
  1701. return def.innerType._zod.run(payload, ctx);
  1702. };
  1703. });
  1704. export const $ZodNonOptional = /*@__PURE__*/ core.$constructor("$ZodNonOptional", (inst, def) => {
  1705. $ZodType.init(inst, def);
  1706. util.defineLazy(inst._zod, "values", () => {
  1707. const v = def.innerType._zod.values;
  1708. return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;
  1709. });
  1710. inst._zod.parse = (payload, ctx) => {
  1711. const result = def.innerType._zod.run(payload, ctx);
  1712. if (result instanceof Promise) {
  1713. return result.then((result) => handleNonOptionalResult(result, inst));
  1714. }
  1715. return handleNonOptionalResult(result, inst);
  1716. };
  1717. });
  1718. function handleNonOptionalResult(payload, inst) {
  1719. if (!payload.issues.length && payload.value === undefined) {
  1720. payload.issues.push({
  1721. code: "invalid_type",
  1722. expected: "nonoptional",
  1723. input: payload.value,
  1724. inst,
  1725. });
  1726. }
  1727. return payload;
  1728. }
  1729. export const $ZodSuccess = /*@__PURE__*/ core.$constructor("$ZodSuccess", (inst, def) => {
  1730. $ZodType.init(inst, def);
  1731. inst._zod.parse = (payload, ctx) => {
  1732. if (ctx.direction === "backward") {
  1733. throw new core.$ZodEncodeError("ZodSuccess");
  1734. }
  1735. const result = def.innerType._zod.run(payload, ctx);
  1736. if (result instanceof Promise) {
  1737. return result.then((result) => {
  1738. payload.value = result.issues.length === 0;
  1739. return payload;
  1740. });
  1741. }
  1742. payload.value = result.issues.length === 0;
  1743. return payload;
  1744. };
  1745. });
  1746. export const $ZodCatch = /*@__PURE__*/ core.$constructor("$ZodCatch", (inst, def) => {
  1747. $ZodType.init(inst, def);
  1748. util.defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
  1749. util.defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
  1750. util.defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  1751. inst._zod.parse = (payload, ctx) => {
  1752. if (ctx.direction === "backward") {
  1753. return def.innerType._zod.run(payload, ctx);
  1754. }
  1755. // Forward direction (decode): apply catch logic
  1756. const result = def.innerType._zod.run(payload, ctx);
  1757. if (result instanceof Promise) {
  1758. return result.then((result) => {
  1759. payload.value = result.value;
  1760. if (result.issues.length) {
  1761. payload.value = def.catchValue({
  1762. ...payload,
  1763. error: {
  1764. issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),
  1765. },
  1766. input: payload.value,
  1767. });
  1768. payload.issues = [];
  1769. }
  1770. return payload;
  1771. });
  1772. }
  1773. payload.value = result.value;
  1774. if (result.issues.length) {
  1775. payload.value = def.catchValue({
  1776. ...payload,
  1777. error: {
  1778. issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),
  1779. },
  1780. input: payload.value,
  1781. });
  1782. payload.issues = [];
  1783. }
  1784. return payload;
  1785. };
  1786. });
  1787. export const $ZodNaN = /*@__PURE__*/ core.$constructor("$ZodNaN", (inst, def) => {
  1788. $ZodType.init(inst, def);
  1789. inst._zod.parse = (payload, _ctx) => {
  1790. if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) {
  1791. payload.issues.push({
  1792. input: payload.value,
  1793. inst,
  1794. expected: "nan",
  1795. code: "invalid_type",
  1796. });
  1797. return payload;
  1798. }
  1799. return payload;
  1800. };
  1801. });
  1802. export const $ZodPipe = /*@__PURE__*/ core.$constructor("$ZodPipe", (inst, def) => {
  1803. $ZodType.init(inst, def);
  1804. util.defineLazy(inst._zod, "values", () => def.in._zod.values);
  1805. util.defineLazy(inst._zod, "optin", () => def.in._zod.optin);
  1806. util.defineLazy(inst._zod, "optout", () => def.out._zod.optout);
  1807. util.defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
  1808. inst._zod.parse = (payload, ctx) => {
  1809. if (ctx.direction === "backward") {
  1810. const right = def.out._zod.run(payload, ctx);
  1811. if (right instanceof Promise) {
  1812. return right.then((right) => handlePipeResult(right, def.in, ctx));
  1813. }
  1814. return handlePipeResult(right, def.in, ctx);
  1815. }
  1816. const left = def.in._zod.run(payload, ctx);
  1817. if (left instanceof Promise) {
  1818. return left.then((left) => handlePipeResult(left, def.out, ctx));
  1819. }
  1820. return handlePipeResult(left, def.out, ctx);
  1821. };
  1822. });
  1823. function handlePipeResult(left, next, ctx) {
  1824. if (left.issues.length) {
  1825. // prevent further checks
  1826. left.aborted = true;
  1827. return left;
  1828. }
  1829. return next._zod.run({ value: left.value, issues: left.issues }, ctx);
  1830. }
  1831. export const $ZodCodec = /*@__PURE__*/ core.$constructor("$ZodCodec", (inst, def) => {
  1832. $ZodType.init(inst, def);
  1833. util.defineLazy(inst._zod, "values", () => def.in._zod.values);
  1834. util.defineLazy(inst._zod, "optin", () => def.in._zod.optin);
  1835. util.defineLazy(inst._zod, "optout", () => def.out._zod.optout);
  1836. util.defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
  1837. inst._zod.parse = (payload, ctx) => {
  1838. const direction = ctx.direction || "forward";
  1839. if (direction === "forward") {
  1840. const left = def.in._zod.run(payload, ctx);
  1841. if (left instanceof Promise) {
  1842. return left.then((left) => handleCodecAResult(left, def, ctx));
  1843. }
  1844. return handleCodecAResult(left, def, ctx);
  1845. }
  1846. else {
  1847. const right = def.out._zod.run(payload, ctx);
  1848. if (right instanceof Promise) {
  1849. return right.then((right) => handleCodecAResult(right, def, ctx));
  1850. }
  1851. return handleCodecAResult(right, def, ctx);
  1852. }
  1853. };
  1854. });
  1855. function handleCodecAResult(result, def, ctx) {
  1856. if (result.issues.length) {
  1857. // prevent further checks
  1858. result.aborted = true;
  1859. return result;
  1860. }
  1861. const direction = ctx.direction || "forward";
  1862. if (direction === "forward") {
  1863. const transformed = def.transform(result.value, result);
  1864. if (transformed instanceof Promise) {
  1865. return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));
  1866. }
  1867. return handleCodecTxResult(result, transformed, def.out, ctx);
  1868. }
  1869. else {
  1870. const transformed = def.reverseTransform(result.value, result);
  1871. if (transformed instanceof Promise) {
  1872. return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));
  1873. }
  1874. return handleCodecTxResult(result, transformed, def.in, ctx);
  1875. }
  1876. }
  1877. function handleCodecTxResult(left, value, nextSchema, ctx) {
  1878. // Check if transform added any issues
  1879. if (left.issues.length) {
  1880. left.aborted = true;
  1881. return left;
  1882. }
  1883. return nextSchema._zod.run({ value, issues: left.issues }, ctx);
  1884. }
  1885. export const $ZodReadonly = /*@__PURE__*/ core.$constructor("$ZodReadonly", (inst, def) => {
  1886. $ZodType.init(inst, def);
  1887. util.defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
  1888. util.defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  1889. util.defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
  1890. util.defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
  1891. inst._zod.parse = (payload, ctx) => {
  1892. if (ctx.direction === "backward") {
  1893. return def.innerType._zod.run(payload, ctx);
  1894. }
  1895. const result = def.innerType._zod.run(payload, ctx);
  1896. if (result instanceof Promise) {
  1897. return result.then(handleReadonlyResult);
  1898. }
  1899. return handleReadonlyResult(result);
  1900. };
  1901. });
  1902. function handleReadonlyResult(payload) {
  1903. payload.value = Object.freeze(payload.value);
  1904. return payload;
  1905. }
  1906. export const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor("$ZodTemplateLiteral", (inst, def) => {
  1907. $ZodType.init(inst, def);
  1908. const regexParts = [];
  1909. for (const part of def.parts) {
  1910. if (typeof part === "object" && part !== null) {
  1911. // is Zod schema
  1912. if (!part._zod.pattern) {
  1913. // if (!source)
  1914. throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);
  1915. }
  1916. const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;
  1917. if (!source)
  1918. throw new Error(`Invalid template literal part: ${part._zod.traits}`);
  1919. const start = source.startsWith("^") ? 1 : 0;
  1920. const end = source.endsWith("$") ? source.length - 1 : source.length;
  1921. regexParts.push(source.slice(start, end));
  1922. }
  1923. else if (part === null || util.primitiveTypes.has(typeof part)) {
  1924. regexParts.push(util.escapeRegex(`${part}`));
  1925. }
  1926. else {
  1927. throw new Error(`Invalid template literal part: ${part}`);
  1928. }
  1929. }
  1930. inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`);
  1931. inst._zod.parse = (payload, _ctx) => {
  1932. if (typeof payload.value !== "string") {
  1933. payload.issues.push({
  1934. input: payload.value,
  1935. inst,
  1936. expected: "string",
  1937. code: "invalid_type",
  1938. });
  1939. return payload;
  1940. }
  1941. inst._zod.pattern.lastIndex = 0;
  1942. if (!inst._zod.pattern.test(payload.value)) {
  1943. payload.issues.push({
  1944. input: payload.value,
  1945. inst,
  1946. code: "invalid_format",
  1947. format: def.format ?? "template_literal",
  1948. pattern: inst._zod.pattern.source,
  1949. });
  1950. return payload;
  1951. }
  1952. return payload;
  1953. };
  1954. });
  1955. export const $ZodFunction = /*@__PURE__*/ core.$constructor("$ZodFunction", (inst, def) => {
  1956. $ZodType.init(inst, def);
  1957. inst._def = def;
  1958. inst._zod.def = def;
  1959. inst.implement = (func) => {
  1960. if (typeof func !== "function") {
  1961. throw new Error("implement() must be called with a function");
  1962. }
  1963. return function (...args) {
  1964. const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;
  1965. const result = Reflect.apply(func, this, parsedArgs);
  1966. if (inst._def.output) {
  1967. return parse(inst._def.output, result);
  1968. }
  1969. return result;
  1970. };
  1971. };
  1972. inst.implementAsync = (func) => {
  1973. if (typeof func !== "function") {
  1974. throw new Error("implementAsync() must be called with a function");
  1975. }
  1976. return async function (...args) {
  1977. const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;
  1978. const result = await Reflect.apply(func, this, parsedArgs);
  1979. if (inst._def.output) {
  1980. return await parseAsync(inst._def.output, result);
  1981. }
  1982. return result;
  1983. };
  1984. };
  1985. inst._zod.parse = (payload, _ctx) => {
  1986. if (typeof payload.value !== "function") {
  1987. payload.issues.push({
  1988. code: "invalid_type",
  1989. expected: "function",
  1990. input: payload.value,
  1991. inst,
  1992. });
  1993. return payload;
  1994. }
  1995. // Check if output is a promise type to determine if we should use async implementation
  1996. const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise";
  1997. if (hasPromiseOutput) {
  1998. payload.value = inst.implementAsync(payload.value);
  1999. }
  2000. else {
  2001. payload.value = inst.implement(payload.value);
  2002. }
  2003. return payload;
  2004. };
  2005. inst.input = (...args) => {
  2006. const F = inst.constructor;
  2007. if (Array.isArray(args[0])) {
  2008. return new F({
  2009. type: "function",
  2010. input: new $ZodTuple({
  2011. type: "tuple",
  2012. items: args[0],
  2013. rest: args[1],
  2014. }),
  2015. output: inst._def.output,
  2016. });
  2017. }
  2018. return new F({
  2019. type: "function",
  2020. input: args[0],
  2021. output: inst._def.output,
  2022. });
  2023. };
  2024. inst.output = (output) => {
  2025. const F = inst.constructor;
  2026. return new F({
  2027. type: "function",
  2028. input: inst._def.input,
  2029. output,
  2030. });
  2031. };
  2032. return inst;
  2033. });
  2034. export const $ZodPromise = /*@__PURE__*/ core.$constructor("$ZodPromise", (inst, def) => {
  2035. $ZodType.init(inst, def);
  2036. inst._zod.parse = (payload, ctx) => {
  2037. return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));
  2038. };
  2039. });
  2040. export const $ZodLazy = /*@__PURE__*/ core.$constructor("$ZodLazy", (inst, def) => {
  2041. $ZodType.init(inst, def);
  2042. // let _innerType!: any;
  2043. // util.defineLazy(def, "getter", () => {
  2044. // if (!_innerType) {
  2045. // _innerType = def.getter();
  2046. // }
  2047. // return () => _innerType;
  2048. // });
  2049. util.defineLazy(inst._zod, "innerType", () => def.getter());
  2050. util.defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern);
  2051. util.defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues);
  2052. util.defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? undefined);
  2053. util.defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? undefined);
  2054. inst._zod.parse = (payload, ctx) => {
  2055. const inner = inst._zod.innerType;
  2056. return inner._zod.run(payload, ctx);
  2057. };
  2058. });
  2059. export const $ZodCustom = /*@__PURE__*/ core.$constructor("$ZodCustom", (inst, def) => {
  2060. checks.$ZodCheck.init(inst, def);
  2061. $ZodType.init(inst, def);
  2062. inst._zod.parse = (payload, _) => {
  2063. return payload;
  2064. };
  2065. inst._zod.check = (payload) => {
  2066. const input = payload.value;
  2067. const r = def.fn(input);
  2068. if (r instanceof Promise) {
  2069. return r.then((r) => handleRefineResult(r, payload, input, inst));
  2070. }
  2071. handleRefineResult(r, payload, input, inst);
  2072. return;
  2073. };
  2074. });
  2075. function handleRefineResult(result, payload, input, inst) {
  2076. if (!result) {
  2077. const _iss = {
  2078. code: "custom",
  2079. input,
  2080. inst, // incorporates params.error into issue reporting
  2081. path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting
  2082. continue: !inst._zod.def.abort,
  2083. // params: inst._zod.def.params,
  2084. };
  2085. if (inst._zod.def.params)
  2086. _iss.params = inst._zod.def.params;
  2087. payload.issues.push(util.issue(_iss));
  2088. }
  2089. }