@vercel/cli-support 65.6.0-snapshot-1ef3a0de66d0 → 65.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/dist/chunks/{add-6UOKR26K.js → add-7G5PAIUN.js} +1 -1
  2. package/dist/chunks/{add-RPAOJH5O.js → add-LA2T477X.js} +1 -1
  3. package/dist/chunks/{add-GULZ6EGJ.js → add-TPDABQQA.js} +1 -1
  4. package/dist/chunks/{build-MLAKPRSC.js → build-A463NBA2.js} +1 -1
  5. package/dist/chunks/{chunk-CU2FTX57.js → chunk-2H4UEVTG.js} +1 -1
  6. package/dist/chunks/{chunk-L4XLDN6T.js → chunk-2KINJIWA.js} +1 -1
  7. package/dist/chunks/{chunk-5K426HWC.js → chunk-3DFEM7ZL.js} +1 -1
  8. package/dist/chunks/{chunk-JXAEI2GJ.js → chunk-3UD4MZMH.js} +1 -1
  9. package/dist/chunks/{chunk-7G4PQR6J.js → chunk-43WS2YU4.js} +1 -1
  10. package/dist/chunks/{chunk-2QIJEHNE.js → chunk-4KO6U4CW.js} +2 -2
  11. package/dist/chunks/{chunk-YIRSRF6D.js → chunk-4P6IRBBK.js} +1 -1
  12. package/dist/chunks/{chunk-ZUYPTLVO.js → chunk-5ULKEPKM.js} +1 -1
  13. package/dist/chunks/{chunk-ZUNQHI5Y.js → chunk-6GSI4VMJ.js} +1 -1
  14. package/dist/chunks/{chunk-DAUAVRFC.js → chunk-7CNJTFWP.js} +1 -1
  15. package/dist/chunks/{chunk-SW3JRXUW.js → chunk-A4UOBMZR.js} +1 -1
  16. package/dist/chunks/{chunk-4G7ZQONX.js → chunk-A7E3WORN.js} +1 -1
  17. package/dist/chunks/{chunk-QUSEBFDO.js → chunk-CNE5UGJC.js} +1 -1
  18. package/dist/chunks/{chunk-HVDGNAPM.js → chunk-DCX2PBSX.js} +1 -1
  19. package/dist/chunks/{chunk-MZQEDXOH.js → chunk-DFXYDOFX.js} +2 -2
  20. package/dist/chunks/{chunk-5WYPJ2T5.js → chunk-E32IBIXV.js} +2 -2
  21. package/dist/chunks/{chunk-3NG2EYQ5.js → chunk-EOK43KMC.js} +1 -1
  22. package/dist/chunks/{chunk-CWO4HMKU.js → chunk-F6MHQRDG.js} +1 -1
  23. package/dist/chunks/{chunk-YALEYPMP.js → chunk-FN3W5CJQ.js} +1 -1
  24. package/dist/chunks/{chunk-R3BEQTZZ.js → chunk-FSBAVQQP.js} +1 -1
  25. package/dist/chunks/{chunk-JSAY52FE.js → chunk-FVIVFDCB.js} +1 -1
  26. package/dist/chunks/{chunk-ORJBK5FT.js → chunk-G62JX3C5.js} +1 -1
  27. package/dist/chunks/{chunk-ODAV7Z2H.js → chunk-GAGROISK.js} +1 -1
  28. package/dist/chunks/{chunk-WICRM2JL.js → chunk-GKCTMBCM.js} +1 -1
  29. package/dist/chunks/{chunk-JMLKK7RL.js → chunk-GTHPBDPB.js} +2 -2
  30. package/dist/chunks/{chunk-NZPGWZLV.js → chunk-H3E4YX2M.js} +1 -1
  31. package/dist/chunks/{chunk-PRFIFS3Q.js → chunk-HKZKGIBQ.js} +1 -1
  32. package/dist/chunks/chunk-HNNCK5KD.js +13 -0
  33. package/dist/chunks/{chunk-FAEC4BER.js → chunk-HOOQ7ZMB.js} +1 -1
  34. package/dist/chunks/{chunk-AOC6XXOO.js → chunk-HTOZY5SI.js} +1 -1
  35. package/dist/chunks/{chunk-LT5UZRMK.js → chunk-I64T5ZML.js} +1 -1
  36. package/dist/chunks/chunk-I7U2XP4X.js +10 -0
  37. package/dist/chunks/{chunk-RWPQOJTT.js → chunk-I7YEXDVF.js} +1 -1
  38. package/dist/chunks/{chunk-PHHZ6J7Q.js → chunk-IEZKTS2C.js} +1 -1
  39. package/dist/chunks/{chunk-ARQMFBV4.js → chunk-IUMJJFEP.js} +1 -1
  40. package/dist/chunks/{chunk-JGMJP4T3.js → chunk-JPEIHA57.js} +1 -1
  41. package/dist/chunks/{chunk-CLVEFWEX.js → chunk-JW57JYRO.js} +1 -1
  42. package/dist/chunks/{chunk-VUQWLLNI.js → chunk-KBFHUWSQ.js} +1 -1
  43. package/dist/chunks/{chunk-JWUXHL35.js → chunk-LAINBICC.js} +1 -1
  44. package/dist/chunks/{chunk-VQ755MPP.js → chunk-LCMNJNSQ.js} +1 -1
  45. package/dist/chunks/{chunk-IC3THLYP.js → chunk-LIXU6EGC.js} +1 -1
  46. package/dist/chunks/{chunk-SDOPVIKJ.js → chunk-MJ7JIQL3.js} +1 -1
  47. package/dist/chunks/{chunk-WDUHDLUA.js → chunk-MMKG5W42.js} +1 -1
  48. package/dist/chunks/{chunk-XAU3KTPX.js → chunk-MYTOHLYZ.js} +1 -1
  49. package/dist/chunks/{chunk-GP55VEOQ.js → chunk-N36OHJVQ.js} +1 -1
  50. package/dist/chunks/{chunk-6WMO5G45.js → chunk-OEPDTNS3.js} +1 -1
  51. package/dist/chunks/{chunk-EFEQQXRU.js → chunk-OGSTNJJ5.js} +1 -1
  52. package/dist/chunks/{chunk-ED3VA7D4.js → chunk-OORHGYZ3.js} +1 -1
  53. package/dist/chunks/{chunk-ZQUVDDPB.js → chunk-OS5I5TXU.js} +1 -1
  54. package/dist/chunks/{chunk-JHNLBVO2.js → chunk-QBP6E2YB.js} +1 -1
  55. package/dist/chunks/{chunk-NVNE3W7S.js → chunk-QDQ4NHQN.js} +1 -1
  56. package/dist/chunks/{chunk-OQX4YVGU.js → chunk-QFUCWOCL.js} +1 -1
  57. package/dist/chunks/{chunk-GFD6UAAO.js → chunk-QRYQADGN.js} +1 -1
  58. package/dist/chunks/{chunk-WSVYZKI6.js → chunk-RD2VHI66.js} +1 -1
  59. package/dist/chunks/{chunk-36NK2Z3C.js → chunk-RNTS4MJP.js} +1 -1
  60. package/dist/chunks/{chunk-JCGEXU7T.js → chunk-RQYXFSED.js} +2 -2
  61. package/dist/chunks/{chunk-ETEVOJQJ.js → chunk-S22GZWJS.js} +1 -1
  62. package/dist/chunks/{chunk-MLGQ233X.js → chunk-S52O6DKC.js} +1 -1
  63. package/dist/chunks/{chunk-NM44RWS6.js → chunk-SAUBWYQJ.js} +1 -1
  64. package/dist/chunks/{chunk-5EMSOR2P.js → chunk-SKDLXVRO.js} +1 -1
  65. package/dist/chunks/{chunk-AIRQFG5A.js → chunk-SXRZZDON.js} +1 -1
  66. package/dist/chunks/{chunk-VLYVVC3P.js → chunk-TKKGZI7O.js} +5 -5
  67. package/dist/chunks/{chunk-4HJGSSSZ.js → chunk-TYL6IYR4.js} +1 -1
  68. package/dist/chunks/{chunk-I2WEQWCA.js → chunk-UWGWRZP5.js} +1 -1
  69. package/dist/chunks/chunk-V6NMCQUQ.js +7 -0
  70. package/dist/chunks/chunk-VH5Z5VHD.js +10 -0
  71. package/dist/chunks/{chunk-QDPYU6KS.js → chunk-VKJVYR4T.js} +1 -1
  72. package/dist/chunks/chunk-WRHQTUHU.js +8 -0
  73. package/dist/chunks/{chunk-TGOGYSBO.js → chunk-WZAJYSJZ.js} +1 -1
  74. package/dist/chunks/{chunk-KWKEBKUR.js → chunk-X4K3UJN7.js} +1 -1
  75. package/dist/chunks/{clear-UZWOOGOH.js → clear-ISIDZTUZ.js} +1 -1
  76. package/dist/chunks/{compile-vercel-config-2RQDL3RD.js → compile-vercel-config-CZVX4OWQ.js} +1 -1
  77. package/dist/chunks/{config-RMJWRS7O.js → config-GMCTHBY6.js} +1 -1
  78. package/dist/chunks/{config-C76IGJ6B.js → config-MAFBMJV3.js} +1 -1
  79. package/dist/chunks/config-validator.mjs +1 -1
  80. package/dist/chunks/{delete-OKOBDL7Z.js → delete-LLQFSC7R.js} +1 -1
  81. package/dist/chunks/{delete-2WBR5JQW.js → delete-PIFKRZEO.js} +1 -1
  82. package/dist/chunks/{detect-projects-XPB3R7VS.js → detect-projects-EYF4ZSYF.js} +1 -1
  83. package/dist/chunks/{detect-services-DRHV22O5.js → detect-services-LNYPPBJP.js} +1 -1
  84. package/dist/chunks/{disable-DFEABU2Z.js → disable-7JLE53D2.js} +1 -1
  85. package/dist/chunks/{discard-KGBEMNFT.js → discard-EXDT6QIK.js} +1 -1
  86. package/dist/chunks/{edit-5XIRLUKG.js → edit-3NOKVF5V.js} +1 -1
  87. package/dist/chunks/{edit-PJIDMKUS.js → edit-BQCPB3ZR.js} +1 -1
  88. package/dist/chunks/{enable-UDWDPFOI.js → enable-KYVZIXZM.js} +1 -1
  89. package/dist/chunks/{export-W75EA6EQ.js → export-4RZRCFX7.js} +1 -1
  90. package/dist/chunks/{fetch-proxy-45DGILKR.js → fetch-proxy-MOKBS56A.js} +1 -1
  91. package/dist/chunks/{future-PHSAEQIE.js → future-YZGJX6FF.js} +1 -1
  92. package/dist/chunks/{generate-cert-for-deploy-C67VL5Z6.js → generate-cert-for-deploy-I236CHA2.js} +1 -1
  93. package/dist/chunks/{image-U5CV2PRP.js → image-EIMVSQLG.js} +1 -1
  94. package/dist/chunks/{import-builders-PHIIX7HW.js → import-builders-JEJRMLNC.js} +1 -1
  95. package/dist/chunks/{inspect-DQQI3PM7.js → inspect-2SCDEURI.js} +1 -1
  96. package/dist/chunks/{inspect-AU3MX7E2.js → inspect-BMBFYISW.js} +1 -1
  97. package/dist/chunks/{inspect-RNWLPR7I.js → inspect-IOKO45PV.js} +1 -1
  98. package/dist/chunks/{inspect-LJK7I6RZ.js → inspect-P246VXF5.js} +1 -1
  99. package/dist/chunks/{inspect-WHPWW4BI.js → inspect-UJAAVGJT.js} +1 -1
  100. package/dist/chunks/{list-QNRFVMMQ.js → list-34Z62YFO.js} +1 -1
  101. package/dist/chunks/{list-JV26NNYL.js → list-PC4ZVIHQ.js} +1 -1
  102. package/dist/chunks/{list-YF4FXWUZ.js → list-WL3WA7CS.js} +1 -1
  103. package/dist/chunks/{login-A4KNOUNA.js → login-BOBO3TKA.js} +1 -1
  104. package/dist/chunks/{login-COGE7JQU.js → login-RAN3UBFA.js} +1 -1
  105. package/dist/chunks/{logs-KMQATUYR.js → logs-L3VFH7SK.js} +1 -1
  106. package/dist/chunks/{ls-HMYU2ZGA.js → ls-FKECGTP3.js} +1 -1
  107. package/dist/chunks/{ls-DTFLHFOW.js → ls-FL3FCE2T.js} +1 -1
  108. package/dist/chunks/{ls-IHF33MQP.js → ls-HQHXDVPG.js} +1 -1
  109. package/dist/chunks/{ls-RNRMYD3V.js → ls-MDTI26PW.js} +1 -1
  110. package/dist/chunks/{ls-ZQLCDIQJ.js → ls-NQVH63KO.js} +1 -1
  111. package/dist/chunks/{ls-QD54I4S7.js → ls-PQBYVYPW.js} +1 -1
  112. package/dist/chunks/{ls-FOKMPVIB.js → ls-ZK5ESMRT.js} +1 -1
  113. package/dist/chunks/{mutate-RMIFQOF6.js → mutate-6OEPBAJF.js} +1 -1
  114. package/dist/chunks/{notifications-BFBNV2HY.js → notifications-A46PC7QX.js} +1 -1
  115. package/dist/chunks/{open-L6HEXHAI.js → open-QWJQWDZD.js} +1 -1
  116. package/dist/chunks/{openapi-6JKCOR7K.js → openapi-5QWHDLKR.js} +1 -1
  117. package/dist/chunks/{permissions-UYGTYRKA.js → permissions-MCOS247Q.js} +1 -1
  118. package/dist/chunks/{plugin-offer-NBHRXMNR.js → plugin-offer-ZMTZG6FR.js} +1 -1
  119. package/dist/chunks/{prompt-missing-credentials-2IYIF2JI.js → prompt-missing-credentials-AUJFBZRC.js} +1 -1
  120. package/dist/chunks/{publish-T2VSTPG4.js → publish-CQ5FHKNN.js} +1 -1
  121. package/dist/chunks/{pull-4GL47Z2S.js → pull-RVNTGJ4C.js} +1 -1
  122. package/dist/chunks/{purchase-domain-if-available-BHFBD3LW.js → purchase-domain-if-available-6FAGFFWC.js} +1 -1
  123. package/dist/chunks/{push-CQPIDVTL.js → push-IBOUSKO7.js} +1 -1
  124. package/dist/chunks/{query-HN45ORIB.js → query-OG4FG2AO.js} +1 -1
  125. package/dist/chunks/{reauthenticate-FTHGAWK3.js → reauthenticate-TVQDXIFS.js} +1 -1
  126. package/dist/chunks/{reorder-7BD5JZKQ.js → reorder-LWKTDFSH.js} +1 -1
  127. package/dist/chunks/{reply-2INQJ5KM.js → reply-5CE2KUD7.js} +1 -1
  128. package/dist/chunks/{resolve-DHAJC3I7.js → resolve-S35UEM35.js} +1 -1
  129. package/dist/chunks/{resolve-agent-team-KGYPHN5F.js → resolve-agent-team-DXHF7XLU.js} +1 -1
  130. package/dist/chunks/{restore-OQKNWEFQ.js → restore-K66POLY7.js} +1 -1
  131. package/dist/chunks/{rm-CTP4UZH7.js → rm-6PBYTCDC.js} +1 -1
  132. package/dist/chunks/{rm-OG3OXA6H.js → rm-C4FXH2RT.js} +1 -1
  133. package/dist/chunks/{rm-GFHEXQQW.js → rm-C73EKJS4.js} +1 -1
  134. package/dist/chunks/{rm-PFZYHXEN.js → rm-MNT5XIGK.js} +1 -1
  135. package/dist/chunks/{rm-XAW3WJ3I.js → rm-VJOHV243.js} +1 -1
  136. package/dist/chunks/{routes-XKEWEA3P.js → routes-LQGTKBXU.js} +1 -1
  137. package/dist/chunks/{rule-inspect-MKQE5IVJ.js → rule-inspect-4EBB5IDK.js} +1 -1
  138. package/dist/chunks/{schema-TFN5PSYE.js → schema-H5RRV4J3.js} +1 -1
  139. package/dist/chunks/{schema-XFER2RCF.js → schema-S32JRZH5.js} +1 -1
  140. package/dist/chunks/{select-org-PFTR6HQZ.js → select-org-VTLOMQYC.js} +1 -1
  141. package/dist/chunks/{set-KWOZNGRL.js → set-52J54LJU.js} +1 -1
  142. package/dist/chunks/{setup-and-link-BRYK42L7.js → setup-and-link-XGBTMVW7.js} +1 -1
  143. package/dist/chunks/{skills-2MOFBKIE.js → skills-CY57F35A.js} +1 -1
  144. package/dist/chunks/{tags-BHZUQTOQ.js → tags-WAVSTC2G.js} +1 -1
  145. package/dist/chunks/{types-IWO5QLAV.js → types-EK3C4EHF.js} +1 -1
  146. package/dist/chunks/{update-LP7ZZUFZ.js → update-4LNUD2AB.js} +1 -1
  147. package/dist/commands/build/index.js +1 -1
  148. package/dist/commands/deploy/index.js +9 -6
  149. package/dist/commands/dev/index.js +3 -3
  150. package/dist/commands/env/index.js +1 -1
  151. package/dist/commands/link/index.js +1 -1
  152. package/dist/commands/list/index.js +1 -1
  153. package/dist/commands/project/index.js +1 -1
  154. package/dist/commands-account.js +7 -3
  155. package/dist/commands-ai.js +3 -3
  156. package/dist/commands-blob.js +1 -1
  157. package/dist/commands-core.js +26 -14
  158. package/dist/commands-deployments.js +1 -1
  159. package/dist/commands-flags.js +1 -1
  160. package/dist/commands-integrations.js +1 -1
  161. package/dist/commands-observability.js +2 -2
  162. package/dist/commands-routing.js +2 -2
  163. package/dist/index.js +5 -5
  164. package/dist/internal-build.js +2 -2
  165. package/dist/native-download.js +2 -1
  166. package/dist/package.json +58 -58
  167. package/dist/vc.js +26 -7
  168. package/dist/version.mjs +1 -1
  169. package/package.json +51 -51
  170. package/dist/chunks/chunk-6IATT2ID.js +0 -8
  171. package/dist/chunks/chunk-EE2FTI3R.js +0 -7
  172. package/dist/chunks/chunk-EWP5WICJ.js +0 -10
  173. package/dist/chunks/chunk-XE24Y6NM.js +0 -10
  174. package/dist/chunks/chunk-YQDOADMG.js +0 -10
@@ -4,8 +4,11 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{parseMeta}from"../../chunks/chunk-CZSOZKHX.js";import{fetchDeploymentBuildEnv,resolvePerDirectoryLinkRoot}from"../../chunks/chunk-5EMSOR2P.js";import{getEnabledProtection,getProtectionForDeployment}from"../../chunks/chunk-EE2FTI3R.js";import{isIgnoredFile,singleFileConfig,singleFileProjectSettings,validatePaths,validateRootDirectory}from"../../chunks/chunk-NVNE3W7S.js";import{promptExperimentalServicesMigration}from"../../chunks/chunk-MLGQ233X.js";import"../../chunks/chunk-ZQUVDDPB.js";import"../../chunks/chunk-HVDGNAPM.js";import{getBuildMachineResourceConfig}from"../../chunks/chunk-ZF27J6FQ.js";import{pickOverrides}from"../../chunks/chunk-WSVYZKI6.js";import{DeployTelemetryClient,Now,UploadErrorMissingArchive,formatVerificationFailure,printDeploymentStatus,printPrebuiltFilePathMapIgnoreWarning,verifyDeployment}from"../../chunks/chunk-JCGEXU7T.js";import{getProductionUrl}from"../../chunks/chunk-VT6RIZJH.js";import{require_dist as require_dist2,require_ignore}from"../../chunks/chunk-MZQEDXOH.js";import"../../chunks/chunk-OCR5CRTH.js";import"../../chunks/chunk-ZFRNVIHI.js";import"../../chunks/chunk-XAU3KTPX.js";import{parseEnv}from"../../chunks/chunk-JWUXHL35.js";import"../../chunks/chunk-6Y2ZL5XJ.js";import"../../chunks/chunk-MFW6IJIK.js";import{applyDeprecatedTargetFlag,parseTarget}from"../../chunks/chunk-EQT2VHL2.js";import{compileVercelConfig}from"../../chunks/chunk-I2WEQWCA.js";import"../../chunks/chunk-6IATT2ID.js";import{isGuidanceEnabled}from"../../chunks/chunk-TAAWMNNL.js";import"../../chunks/chunk-RWPQOJTT.js";import{require_semver}from"../../chunks/chunk-BPUANOGW.js";import"../../chunks/chunk-U56NHYAH.js";import{parseRepoUrl}from"../../chunks/chunk-J6L5MDTX.js";import"../../chunks/chunk-EAUDC24V.js";import"../../chunks/chunk-RRDNKB2X.js";import"../../chunks/chunk-MVGTMPMI.js";import"../../chunks/chunk-SACGQMVQ.js";import{ensureLink}from"../../chunks/chunk-JMLKK7RL.js";import{getDeployment}from"../../chunks/chunk-VAWZZK3Y.js";import{mapCertError}from"../../chunks/chunk-OKNDHNH6.js";import"../../chunks/chunk-PVASGBEF.js";import"../../chunks/chunk-SDOPVIKJ.js";import"../../chunks/chunk-3E364MJE.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-V6Y6UK6B.js";import"../../chunks/chunk-J24BABG4.js";import"../../chunks/chunk-U4Z2MMOF.js";import{require_async_sema}from"../../chunks/chunk-NZ2TFADV.js";import"../../chunks/chunk-IQ7FPAI4.js";import{stamp_default}from"../../chunks/chunk-A2RZZQEP.js";import{table}from"../../chunks/chunk-5SIC5273.js";import{getRenamedOption,reportRenamedOptionError}from"../../chunks/chunk-JSAY52FE.js";import"../../chunks/chunk-Q7D7RGXM.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-P6ZTEDX2.js";import{continueSubcommand,deployCommand,deprecatedArchiveSplitTgz,describeSubcommand,getCommandAliases,initSubcommand}from"../../chunks/chunk-WDUHDLUA.js";import"../../chunks/chunk-O7COT3YB.js";import"../../chunks/chunk-2FHZYQPY.js";import"../../chunks/chunk-M7LUSXMG.js";import"../../chunks/chunk-C6IITJ5S.js";import"../../chunks/chunk-TZT3VYZ3.js";import"../../chunks/chunk-HMWDOAWO.js";import"../../chunks/chunk-QNL22LAW.js";import"../../chunks/chunk-UWMPVTXG.js";import"../../chunks/chunk-5CZNUB7Y.js";import"../../chunks/chunk-AUY363W7.js";import"../../chunks/chunk-OTYF3ZZW.js";import"../../chunks/chunk-3H36RI7C.js";import"../../chunks/chunk-BGWS5R5R.js";import"../../chunks/chunk-UJQ6PBRF.js";import"../../chunks/chunk-LFOWP74R.js";import"../../chunks/chunk-GVPVWHFK.js";import"../../chunks/chunk-N5CXIFE2.js";import"../../chunks/chunk-FNA4MIOH.js";import"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-VWHIWUGJ.js";import{printError}from"../../chunks/chunk-VQ755MPP.js";import{help}from"../../chunks/chunk-SLDWAIO3.js";import"../../chunks/chunk-67GZ5REA.js";import"../../chunks/chunk-BS32OUOC.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import{TelemetryClient}from"../../chunks/chunk-5WYPJ2T5.js";import{require_ci_info}from"../../chunks/chunk-2EYYB6YN.js";import"../../chunks/chunk-WICRM2JL.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import"../../chunks/chunk-NWGBDBZI.js";import{AGENT_REASON,AGENT_STATUS,argvHasNonInteractive,buildCommandWithYes,outputAgentError,withGlobalFlags,writeAgentError}from"../../chunks/chunk-XE24Y6NM.js";import"../../chunks/chunk-EPO7P734.js";import{VERCEL_DIR,VERCEL_DIR_PROJECT,addToGitIgnore,createGitMeta,findProjectsFromPath,getGitConfigPath,getGitExecutable,getLinkFromDir,getProjectLink,getRepoLink,getVercelDirectory,highlight,isOwnerLookupUnavailableLink,isRemoteLookupSkippedLink,linkFolderToProject,parseGitConfig,pluckRemoteUrls,readLocalConfig,require_lib,require_types,traceOperation}from"../../chunks/chunk-VLYVVC3P.js";import{printAlignedLabel}from"../../chunks/chunk-26QK3I2S.js";import"../../chunks/chunk-55H6G46X.js";import"../../chunks/chunk-4NTBYNFR.js";import{isArgumentError,parseArguments}from"../../chunks/chunk-F22QLVTX.js";import{quoteArg}from"../../chunks/chunk-F53OKXYI.js";import{validateJsonOutput,wantsMachineReadableOutput,warnDeprecatedInput}from"../../chunks/chunk-7SAEZ4NC.js";import"../../chunks/chunk-LUX4PBJL.js";import"../../chunks/chunk-OPORM35X.js";import"../../chunks/chunk-4SAVH3H7.js";import{AliasDomainConfigured,BuildError,BuildsRateLimited,ConflictingConfigFiles,ConflictingFilePath,ConflictingPathSegment,DeploymentNotFound,DeploymentsRateLimited,DeprecatedNowJson,DomainNotFound,DomainNotVerified,DomainPermissionDenied,DomainVerificationFailed,InvalidDomain,InvalidToken,MissingBuildScript,NotDomainOwner,NowError,SchemaValidationFailed,TooManyRequests,UserAborted,code,isAPIError,require_bytes}from"../../chunks/chunk-YCJHUYBJ.js";import{getCommandName,getCommandNamePlain,packageName}from"../../chunks/chunk-JESNVRVR.js";import{cliErrorFromUnknown,emoji,link_default,output_manager_default,prependEmoji,recordCliError,require_build_utils}from"../../chunks/chunk-DWOJP4ST.js";import"../../chunks/chunk-BLUPZPAS.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import"../../chunks/chunk-D3AHZ5LI.js";import"../../chunks/chunk-2GHZGOWT.js";import"../../chunks/chunk-YHPPP3SF.js";import"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-PUKYAALC.js";import{getFlagsSpecification}from"../../chunks/chunk-A2UZ2O7H.js";import"../../chunks/chunk-2BKALEOP.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-SCV7XEEO.js";import{getFetchDispatcher}from"../../chunks/chunk-MY4MONOH.js";import{__export,__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_build_utils11=__toESM(require_build_utils(),1),import_client=__toESM(require_dist2(),1),import_error_utils2=__toESM(require_dist(),1);var import_bytes=__toESM(require_bytes(),1),import_chalk=__toESM(require_source(),1),import_fs_extra4=__toESM(require_lib(),1),import_ms=__toESM(require_ms(),1);import{tmpdir}from"os";import{basename as basename3,dirname as dirname3,extname,join as join17,resolve as resolve3}from"path";async function createDeploy(client,now,contextName,path2,createArgs,org,isSettingUpProject,archive){try{return await now.create(path2,createArgs,org,isSettingUpProject,archive)}catch(err){if(isAPIError(err)){if(err.code==="rate_limited")throw new DeploymentsRateLimited(err.message);if(err.code==="domain_missing")throw new DomainNotFound(err.value);if(err.code==="domain_not_found"&&err.domain)throw new DomainNotFound(err.domain);if(err.code==="domain_not_verified"&&err.domain)throw new DomainNotVerified(err.domain);if(err.code==="domain_not_verified"&&err.value)throw new DomainVerificationFailed(err.value);if(err.code==="not_domain_owner")throw new NotDomainOwner(err.message);if(err.code==="builds_rate_limited")throw new BuildsRateLimited(err.message,{ctaLabel:err.ctaLabel,ctaUrl:err.ctaUrl,action:err.action,link:err.link});if(err.code==="forbidden")throw new DomainPermissionDenied(err.value,contextName);if(err.code==="bad_request"&&err.keyword)throw new SchemaValidationFailed(err.message,err.keyword,err.dataPath,err.params);if(err.code==="domain_configured")throw new AliasDomainConfigured(err);if(err.code==="missing_build_script")throw new MissingBuildScript(err);if(err.code==="conflicting_file_path")throw new ConflictingFilePath(err);if(err.code==="conflicting_path_segment")throw new ConflictingPathSegment(err);if(err.code==="cert_missing"){let{default:generateCertForDeploy}=await import("../../chunks/generate-cert-for-deploy-C67VL5Z6.js"),result=await generateCertForDeploy(client,contextName,err.value);return result instanceof NowError?result:createDeploy(client,now,contextName,path2,createArgs,org,isSettingUpProject)}if(err.code==="not_found")throw new DeploymentNotFound({context:contextName});let certError=mapCertError(err);if(certError)return certError}throw err}}var ENV_PAIR_FLAGS=["--env","--build-env"],ENV_VALUE_PLACEHOLDER="<VALUE>",CANONICAL_FLAGS={"--token":null,"--confirm":"--yes","--target":"--environment","--team":"--scope","--name":null,"--no-clipboard":null,"--no-logs":null};function buildCreateIfMissingCommand(positionals,flags,argv){let out=["deploy",...positionals],seen=new Set,hasPlaceholder=!1;for(let[typedName,value]of Object.entries(flags)){let name=typedName in CANONICAL_FLAGS?CANONICAL_FLAGS[typedName]:typedName;if(!(!name||name==="--create-if-missing"||seen.has(name))){if(seen.add(name),name==="--non-interactive"){out.push(argvHasNonInteractive(argv)?"--non-interactive":"--non-interactive=false");continue}for(let item of Array.isArray(value)?value:[value])if(item===!0)out.push(name);else if(typeof item=="string"||typeof item=="number"){let text=String(item),shown=ENV_PAIR_FLAGS.includes(name)?withPlaceholder(text):text;hasPlaceholder||=shown!==text,out.push(name,shown)}}}out.push("--create-if-missing");let command=[packageName,...out.map(quoteToken)].join(" ");return hasPlaceholder?{command,note:`replace each ${ENV_VALUE_PLACEHOLDER} with the Environment Variable's value`}:{command}}function findEnvPlaceholder(flags){for(let flag of ENV_PAIR_FLAGS){let value=flags[flag];for(let pair of Array.isArray(value)?value:[value])if(typeof pair=="string"&&pair.endsWith(`=${ENV_VALUE_PLACEHOLDER}`))return{flag,key:pair.slice(0,pair.indexOf("="))}}}function withPlaceholder(pair){let equals=pair.indexOf("=");return equals>=0?`${pair.slice(0,equals)}=${ENV_VALUE_PLACEHOLDER}`:pair}function quoteToken(token){return/^[A-Za-z0-9_./@:=,+-]+$/.test(token)?token:quoteArg(token)}async function getDeploymentChecks(client,deploymentId){return await client.fetch(`/v1/deployments/${encodeURIComponent(deploymentId)}/checks`)}async function getDeploymentCheckRuns(client,deploymentId){return await client.fetch(`/v2/deployments/${encodeURIComponent(deploymentId)}/check-runs`)}function parseNdjson(text){let entries=[];for(let line of text.split(`
8
- `))if(line.trim())try{entries.push(JSON.parse(line))}catch{}return entries}async function getDeploymentCheckRunLogs(client,deploymentId,checkRunId){let url=`/v2/deployments/${encodeURIComponent(deploymentId)}/check-runs/${encodeURIComponent(checkRunId)}/logs`;await new Promise(resolve4=>setTimeout(resolve4,1e3));for(let attempt=0;attempt<5;attempt++){attempt>0&&await new Promise(resolve4=>setTimeout(resolve4,2e3));let res=await client.fetch(url,{json:!1}),text=typeof res=="string"?res:await res.text(),entries=parseNdjson(text);if(entries.some(e=>e.level==="eof"))return entries.filter(e=>e.level!=="eof"&&e.level!=="debug").map(({level,timestamp,message})=>({level,timestamp,message}))}return[]}var import_fs_extra=__toESM(require_lib(),1);import{join}from"path";async function getPrebuiltJson(directory){try{return await import_fs_extra.default.readJSON(join(directory,"builds.json"))}catch{}return null}import{resolve}from"path";var SUPPORTED_PROVIDERS=new Set(["github","gitlab","bitbucket"]),defaultDeps={getGitConfigPath,parseGitConfig,fetchProject:(client,project)=>client.fetch(`/v9/projects/${encodeURIComponent(project.id)}`,{accountId:project.accountId}),buildCommand:(client,command)=>withGlobalFlags(client,command,{preserveProject:!0})};async function getGitConnectRecommendation(client,cwd,project,options={}){let{alreadyOffered=!1,deps=defaultDeps}=options;try{if(project.link||alreadyOffered)return;let gitConfigPath=deps.getGitConfigPath({cwd});if(!gitConfigPath)return;let gitConfig=await deps.parseGitConfig(gitConfigPath),remoteUrls=gitConfig&&pluckRemoteUrls(gitConfig);if(!remoteUrls)return;let remotes=Object.values(remoteUrls);if(!remotes.some(remoteUrl=>{let repo=parseRepoUrl(remoteUrl);return repo&&SUPPORTED_PROVIDERS.has(repo.provider)})||client.nonInteractive&&remotes.length!==1||(await deps.fetchProject(client,project)).link)return;let cwdFlag=resolve(cwd)===resolve(client.cwd)?"":` --cwd ${quoteArg(cwd)}`;return deps.buildCommand(client,`git connect${cwdFlag}`)}catch(error){output_manager_default.debug(`Failed to resolve Git connection guidance: ${error}`);return}}var import_types=__toESM(require_types(),1),validArchiveFormats=new Set(import_types.VALID_ARCHIVE_FORMATS);function isValidArchive(archive){return validArchiveFormats.has(archive)}var DEPRECATED_SHORTHANDS={"-e":"--env","-b":"--build-env"};function getDeployFlagsSpecification(options){return{...getFlagsSpecification(options),...DEPRECATED_SHORTHANDS}}function warnDeprecatedShorthands(client,options){let flags;try{({flags}=parseArguments(client.argv.slice(2),{...getFlagsSpecification(options),"-e":[String],"-b":[String]},{permissive:!0}))}catch{return}for(let[shorthand,name]of Object.entries(DEPRECATED_SHORTHANDS))flags[shorthand]!==void 0&&warnDeprecatedInput(client,shorthand,name)}function getErrorCta(source){if(typeof source.ctaLabel=="string"&&typeof source.ctaUrl=="string")return{label:source.ctaLabel,url:source.ctaUrl};if(typeof source.action=="string"&&typeof source.link=="string")return{label:source.action,url:source.link}}var DescribeError=class extends Error{constructor(reason,message){super(message);this.reason=reason}};var DescribeTelemetryClient=class extends TelemetryClient{trackCliOptionDeployment(value){value&&this.trackCliOption({option:"deployment",value:this.redactedValue})}trackCliOptionId(value){value&&this.trackCliOption({option:"id",value:this.redactedValue})}trackCliOptionAwsAccountId(value){value&&this.trackCliOption({option:"aws-account-id",value:this.redactedValue})}trackCliFlagJson(value){value&&this.trackCliFlag("json")}};import{createHash as createHash3}from"node:crypto";import{createHash as createHash2}from"node:crypto";function getFunctionConfig(lambda){return{runtime:lambda.runtime,handler:lambda.handler,architecture:lambda.architecture,environment:Object.fromEntries(Object.entries(lambda.environment).filter(entry=>typeof entry[1]=="string")),..."launcherType"in lambda&&lambda.launcherType==="Nodejs"?{launcherType:lambda.launcherType,awsLambdaHandler:lambda.awsLambdaHandler,shouldAddHelpers:lambda.shouldAddHelpers,shouldAddSourcemapSupport:lambda.shouldAddSourcemapSupport,shouldDisableAutomaticFetchInstrumentation:lambda.shouldDisableAutomaticFetchInstrumentation,useWebApi:lambda.useWebApi}:{},memory:lambda.memory,affinity:lambda.affinity,maxConcurrency:lambda.maxConcurrency,maxDuration:lambda.maxDuration,regions:lambda.regions,functionFailoverRegions:lambda.functionFailoverRegions,supportsResponseStreaming:lambda.supportsResponseStreaming,framework:lambda.framework&&{...lambda.framework}}}var import_build_utils=__toESM(require_build_utils(),1),ROOT_BOOTSTRAP_PATH="bootstrap",USER_BOOTSTRAP_PATH="___vc_bootstrap",NATIVELY_WRAPPER_SUPPORTED_FAMILIES=["nodejs","python","ruby","java","dotnetcore","bun","executable"],BOOTSTRAP_SHIM=`#!/bin/sh
7
+ import{parseMeta}from"../../chunks/chunk-CZSOZKHX.js";import{fetchDeploymentBuildEnv,resolvePerDirectoryLinkRoot}from"../../chunks/chunk-SKDLXVRO.js";import{isIgnoredFile,singleFileConfig,singleFileProjectSettings,validatePaths,validateRootDirectory}from"../../chunks/chunk-QDQ4NHQN.js";import{promptExperimentalServicesMigration}from"../../chunks/chunk-S52O6DKC.js";import"../../chunks/chunk-OS5I5TXU.js";import"../../chunks/chunk-DCX2PBSX.js";import{getBuildMachineResourceConfig}from"../../chunks/chunk-ZF27J6FQ.js";import{pickOverrides}from"../../chunks/chunk-RD2VHI66.js";import{DeployTelemetryClient,Now,UploadErrorMissingArchive,formatVerificationFailure,printDeploymentStatus,printPrebuiltFilePathMapIgnoreWarning,verifyDeployment}from"../../chunks/chunk-RQYXFSED.js";import{require_dist as require_dist2,require_ignore}from"../../chunks/chunk-DFXYDOFX.js";import"../../chunks/chunk-OCR5CRTH.js";import"../../chunks/chunk-ZFRNVIHI.js";import"../../chunks/chunk-MYTOHLYZ.js";import{parseEnv}from"../../chunks/chunk-LAINBICC.js";import"../../chunks/chunk-6Y2ZL5XJ.js";import"../../chunks/chunk-MFW6IJIK.js";import{applyDeprecatedTargetFlag,parseTarget}from"../../chunks/chunk-EQT2VHL2.js";import{compileVercelConfig}from"../../chunks/chunk-UWGWRZP5.js";import"../../chunks/chunk-WRHQTUHU.js";import{isGuidanceEnabled}from"../../chunks/chunk-TAAWMNNL.js";import"../../chunks/chunk-I7YEXDVF.js";import{require_semver}from"../../chunks/chunk-BPUANOGW.js";import"../../chunks/chunk-U56NHYAH.js";import{parseRepoUrl}from"../../chunks/chunk-J6L5MDTX.js";import"../../chunks/chunk-EAUDC24V.js";import"../../chunks/chunk-RRDNKB2X.js";import"../../chunks/chunk-MVGTMPMI.js";import"../../chunks/chunk-SACGQMVQ.js";import{getEnabledProtection,getProtectionForDeployment}from"../../chunks/chunk-V6NMCQUQ.js";import{getProductionUrl}from"../../chunks/chunk-VT6RIZJH.js";import{ensureLink}from"../../chunks/chunk-GTHPBDPB.js";import{getDeployment}from"../../chunks/chunk-VAWZZK3Y.js";import{mapCertError}from"../../chunks/chunk-OKNDHNH6.js";import"../../chunks/chunk-PVASGBEF.js";import"../../chunks/chunk-MJ7JIQL3.js";import"../../chunks/chunk-3E364MJE.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-V6Y6UK6B.js";import"../../chunks/chunk-J24BABG4.js";import"../../chunks/chunk-U4Z2MMOF.js";import{require_async_sema}from"../../chunks/chunk-NZ2TFADV.js";import"../../chunks/chunk-IQ7FPAI4.js";import{stamp_default}from"../../chunks/chunk-A2RZZQEP.js";import{table}from"../../chunks/chunk-5SIC5273.js";import{getRenamedOption,reportRenamedOptionError}from"../../chunks/chunk-FVIVFDCB.js";import"../../chunks/chunk-Q7D7RGXM.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-P6ZTEDX2.js";import{continueSubcommand,deployCommand,deprecatedArchiveSplitTgz,describeSubcommand,getCommandAliases,initSubcommand}from"../../chunks/chunk-MMKG5W42.js";import"../../chunks/chunk-O7COT3YB.js";import"../../chunks/chunk-2FHZYQPY.js";import"../../chunks/chunk-M7LUSXMG.js";import"../../chunks/chunk-C6IITJ5S.js";import"../../chunks/chunk-TZT3VYZ3.js";import"../../chunks/chunk-HMWDOAWO.js";import"../../chunks/chunk-QNL22LAW.js";import"../../chunks/chunk-UWMPVTXG.js";import"../../chunks/chunk-5CZNUB7Y.js";import"../../chunks/chunk-AUY363W7.js";import"../../chunks/chunk-OTYF3ZZW.js";import"../../chunks/chunk-3H36RI7C.js";import"../../chunks/chunk-BGWS5R5R.js";import"../../chunks/chunk-UJQ6PBRF.js";import"../../chunks/chunk-LFOWP74R.js";import"../../chunks/chunk-GVPVWHFK.js";import"../../chunks/chunk-N5CXIFE2.js";import"../../chunks/chunk-FNA4MIOH.js";import"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-VWHIWUGJ.js";import{printError}from"../../chunks/chunk-LCMNJNSQ.js";import{help}from"../../chunks/chunk-SLDWAIO3.js";import"../../chunks/chunk-67GZ5REA.js";import"../../chunks/chunk-BS32OUOC.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import{TelemetryClient}from"../../chunks/chunk-E32IBIXV.js";import{require_ci_info}from"../../chunks/chunk-2EYYB6YN.js";import"../../chunks/chunk-GKCTMBCM.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import"../../chunks/chunk-NWGBDBZI.js";import{AGENT_REASON,AGENT_STATUS,argvHasNonInteractive,buildCommandWithYes,outputAgentError,withGlobalFlags,writeAgentError}from"../../chunks/chunk-I7U2XP4X.js";import"../../chunks/chunk-EPO7P734.js";import{VERCEL_DIR,VERCEL_DIR_PROJECT,addToGitIgnore,createGitMeta,findProjectsFromPath,getGitConfigPath,getGitExecutable,getLinkFromDir,getProjectLink,getRepoLink,getVercelDirectory,highlight,isOwnerLookupUnavailableLink,isRemoteLookupSkippedLink,linkFolderToProject,parseGitConfig,pluckRemoteUrls,readLocalConfig,require_lib,require_types,sleep,traceOperation}from"../../chunks/chunk-TKKGZI7O.js";import{printAlignedLabel}from"../../chunks/chunk-26QK3I2S.js";import"../../chunks/chunk-55H6G46X.js";import"../../chunks/chunk-4NTBYNFR.js";import{isArgumentError,parseArguments}from"../../chunks/chunk-F22QLVTX.js";import{quoteArg}from"../../chunks/chunk-F53OKXYI.js";import{validateJsonOutput,wantsMachineReadableOutput,warnDeprecatedInput}from"../../chunks/chunk-7SAEZ4NC.js";import"../../chunks/chunk-LUX4PBJL.js";import"../../chunks/chunk-OPORM35X.js";import"../../chunks/chunk-4SAVH3H7.js";import{AliasDomainConfigured,BuildError,BuildsRateLimited,ConflictingConfigFiles,ConflictingFilePath,ConflictingPathSegment,DeploymentNotFound,DeploymentsRateLimited,DeprecatedNowJson,DomainNotFound,DomainNotVerified,DomainPermissionDenied,DomainVerificationFailed,InvalidDomain,InvalidToken,MissingBuildScript,NotDomainOwner,NowError,SchemaValidationFailed,TooManyRequests,UserAborted,code,isAPIError,parseRetryAfterHeaderAsMillis,require_bytes}from"../../chunks/chunk-YCJHUYBJ.js";import{getCommandName,getCommandNamePlain,packageName}from"../../chunks/chunk-JESNVRVR.js";import{cliErrorFromUnknown,emoji,link_default,output_manager_default,prependEmoji,recordCliError,require_build_utils}from"../../chunks/chunk-DWOJP4ST.js";import"../../chunks/chunk-BLUPZPAS.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import"../../chunks/chunk-D3AHZ5LI.js";import"../../chunks/chunk-2GHZGOWT.js";import"../../chunks/chunk-YHPPP3SF.js";import"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-PUKYAALC.js";import{getFlagsSpecification}from"../../chunks/chunk-A2UZ2O7H.js";import"../../chunks/chunk-2BKALEOP.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-SCV7XEEO.js";import{fetch,getFetchDispatcher}from"../../chunks/chunk-MY4MONOH.js";import{__export,__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_build_utils11=__toESM(require_build_utils(),1),import_client=__toESM(require_dist2(),1),import_error_utils2=__toESM(require_dist(),1);var import_bytes=__toESM(require_bytes(),1),import_chalk=__toESM(require_source(),1),import_fs_extra4=__toESM(require_lib(),1),import_ms=__toESM(require_ms(),1);import{tmpdir}from"os";import{basename as basename3,dirname as dirname3,extname,join as join17,resolve as resolve3}from"path";async function createDeploy(client,now,contextName,path2,createArgs,org,isSettingUpProject,archive){try{return await now.create(path2,createArgs,org,isSettingUpProject,archive)}catch(err){if(isAPIError(err)){if(err.code==="rate_limited")throw new DeploymentsRateLimited(err.message);if(err.code==="domain_missing")throw new DomainNotFound(err.value);if(err.code==="domain_not_found"&&err.domain)throw new DomainNotFound(err.domain);if(err.code==="domain_not_verified"&&err.domain)throw new DomainNotVerified(err.domain);if(err.code==="domain_not_verified"&&err.value)throw new DomainVerificationFailed(err.value);if(err.code==="not_domain_owner")throw new NotDomainOwner(err.message);if(err.code==="builds_rate_limited")throw new BuildsRateLimited(err.message,{ctaLabel:err.ctaLabel,ctaUrl:err.ctaUrl,action:err.action,link:err.link});if(err.code==="forbidden")throw new DomainPermissionDenied(err.value,contextName);if(err.code==="bad_request"&&err.keyword)throw new SchemaValidationFailed(err.message,err.keyword,err.dataPath,err.params);if(err.code==="domain_configured")throw new AliasDomainConfigured(err);if(err.code==="missing_build_script")throw new MissingBuildScript(err);if(err.code==="conflicting_file_path")throw new ConflictingFilePath(err);if(err.code==="conflicting_path_segment")throw new ConflictingPathSegment(err);if(err.code==="cert_missing"){let{default:generateCertForDeploy}=await import("../../chunks/generate-cert-for-deploy-I236CHA2.js"),result=await generateCertForDeploy(client,contextName,err.value);return result instanceof NowError?result:createDeploy(client,now,contextName,path2,createArgs,org,isSettingUpProject)}if(err.code==="not_found")throw new DeploymentNotFound({context:contextName});let certError=mapCertError(err);if(certError)return certError}throw err}}var ENV_PAIR_FLAGS=["--env","--build-env"],ENV_VALUE_PLACEHOLDER="<VALUE>",CANONICAL_FLAGS={"--token":null,"--confirm":"--yes","--target":"--environment","--team":"--scope","--name":null,"--no-clipboard":null,"--no-logs":null};function buildCreateIfMissingCommand(positionals,flags,argv){let out=["deploy",...positionals],seen=new Set,hasPlaceholder=!1;for(let[typedName,value]of Object.entries(flags)){let name=typedName in CANONICAL_FLAGS?CANONICAL_FLAGS[typedName]:typedName;if(!(!name||name==="--create-if-missing"||seen.has(name))){if(seen.add(name),name==="--non-interactive"){out.push(argvHasNonInteractive(argv)?"--non-interactive":"--non-interactive=false");continue}for(let item of Array.isArray(value)?value:[value])if(item===!0)out.push(name);else if(typeof item=="string"||typeof item=="number"){let text=String(item),shown=ENV_PAIR_FLAGS.includes(name)?withPlaceholder(text):text;hasPlaceholder||=shown!==text,out.push(name,shown)}}}out.push("--create-if-missing");let command=[packageName,...out.map(quoteToken)].join(" ");return hasPlaceholder?{command,note:`replace each ${ENV_VALUE_PLACEHOLDER} with the Environment Variable's value`}:{command}}function findEnvPlaceholder(flags){for(let flag of ENV_PAIR_FLAGS){let value=flags[flag];for(let pair of Array.isArray(value)?value:[value])if(typeof pair=="string"&&pair.endsWith(`=${ENV_VALUE_PLACEHOLDER}`))return{flag,key:pair.slice(0,pair.indexOf("="))}}}function withPlaceholder(pair){let equals=pair.indexOf("=");return equals>=0?`${pair.slice(0,equals)}=${ENV_VALUE_PLACEHOLDER}`:pair}function quoteToken(token){return/^[A-Za-z0-9_./@:=,+-]+$/.test(token)?token:quoteArg(token)}async function getDeploymentChecks(client,deploymentId){return await client.fetch(`/v1/deployments/${encodeURIComponent(deploymentId)}/checks`)}async function getDeploymentCheckRuns(client,deploymentId){return await client.fetch(`/v2/deployments/${encodeURIComponent(deploymentId)}/check-runs`)}function parseNdjson(text){let entries=[];for(let line of text.split(`
8
+ `))if(line.trim())try{entries.push(JSON.parse(line))}catch{}return entries}async function getDeploymentCheckRunLogs(client,deploymentId,checkRunId){let url=`/v2/deployments/${encodeURIComponent(deploymentId)}/check-runs/${encodeURIComponent(checkRunId)}/logs`;await new Promise(resolve4=>setTimeout(resolve4,1e3));for(let attempt=0;attempt<5;attempt++){attempt>0&&await new Promise(resolve4=>setTimeout(resolve4,2e3));let res=await client.fetch(url,{json:!1}),text=typeof res=="string"?res:await res.text(),entries=parseNdjson(text);if(entries.some(e=>e.level==="eof"))return entries.filter(e=>e.level!=="eof"&&e.level!=="debug").map(({level,timestamp,message})=>({level,timestamp,message}))}return[]}var import_fs_extra=__toESM(require_lib(),1);import{join}from"path";async function getPrebuiltJson(directory){try{return await import_fs_extra.default.readJSON(join(directory,"builds.json"))}catch{}return null}import{resolve}from"path";var SUPPORTED_PROVIDERS=new Set(["github","gitlab","bitbucket"]),defaultDeps={getGitConfigPath,parseGitConfig,fetchProject:(client,project)=>client.fetch(`/v9/projects/${encodeURIComponent(project.id)}`,{accountId:project.accountId}),buildCommand:(client,command)=>withGlobalFlags(client,command,{preserveProject:!0})};async function getGitConnectRecommendation(client,cwd,project,options={}){let{alreadyOffered=!1,deps=defaultDeps}=options;try{if(project.link||alreadyOffered)return;let gitConfigPath=deps.getGitConfigPath({cwd});if(!gitConfigPath)return;let gitConfig=await deps.parseGitConfig(gitConfigPath),remoteUrls=gitConfig&&pluckRemoteUrls(gitConfig);if(!remoteUrls)return;let remotes=Object.values(remoteUrls);if(!remotes.some(remoteUrl=>{let repo=parseRepoUrl(remoteUrl);return repo&&SUPPORTED_PROVIDERS.has(repo.provider)})||client.nonInteractive&&remotes.length!==1||(await deps.fetchProject(client,project)).link)return;let cwdFlag=resolve(cwd)===resolve(client.cwd)?"":` --cwd ${quoteArg(cwd)}`;return deps.buildCommand(client,`git connect${cwdFlag}`)}catch(error){output_manager_default.debug(`Failed to resolve Git connection guidance: ${error}`);return}}var import_types=__toESM(require_types(),1),validArchiveFormats=new Set(import_types.VALID_ARCHIVE_FORMATS);function isValidArchive(archive){return validArchiveFormats.has(archive)}var DEPRECATED_SHORTHANDS={"-e":"--env","-b":"--build-env"};function getDeployFlagsSpecification(options){return{...getFlagsSpecification(options),...DEPRECATED_SHORTHANDS}}function warnDeprecatedShorthands(client,options){let flags;try{({flags}=parseArguments(client.argv.slice(2),{...getFlagsSpecification(options),"-e":[String],"-b":[String]},{permissive:!0}))}catch{return}for(let[shorthand,name]of Object.entries(DEPRECATED_SHORTHANDS))flags[shorthand]!==void 0&&warnDeprecatedInput(client,shorthand,name)}function getErrorCta(source){if(typeof source.ctaLabel=="string"&&typeof source.ctaUrl=="string")return{label:source.ctaLabel,url:source.ctaUrl};if(typeof source.action=="string"&&typeof source.link=="string")return{label:source.action,url:source.link}}var DescribeError=class extends Error{constructor(reason,message){super(message);this.reason=reason}};var DescribeTelemetryClient=class extends TelemetryClient{trackCliOptionDeployment(value){value&&this.trackCliOption({option:"deployment",value:this.redactedValue})}trackCliOptionId(value){value&&this.trackCliOption({option:"id",value:this.redactedValue})}trackCliOptionAwsAccountId(value){value&&this.trackCliOption({option:"aws-account-id",value:this.redactedValue})}trackCliFlagJson(value){value&&this.trackCliFlag("json")}};var attempts=3;function downloadLayer(client,url){return client.retry((bail,attempt)=>client.withTrace("vc.cli.describe.layer_download",async trace=>{trace?.span.setAttributes({attempt:String(attempt),http_method:"GET"}),attempt>1&&await sleep(Math.random()*1e3);let response;try{let res=await fetch(url,{signal:AbortSignal.timeout(6e4)});if(response=res,trace?.span.setAttributes({http_status_code:String(res.status)}),res.ok)return new Uint8Array(await client.withTrace("vc.cli.describe.layer_body",()=>res.arrayBuffer()))}catch(error2){await response?.body?.cancel().catch(()=>{});let reason=error2 instanceof Error&&error2.name==="TimeoutError"?"timeout":"network_error";throw trace?.span.setAttributes({failure_reason:reason}),downloadError(attempt,reason)}await response.body?.cancel().catch(()=>{}),trace?.span.setAttributes({failure_reason:"http_error"});let error=downloadError(attempt,`HTTP ${response.status}`);if(response.status!==408&&response.status!==429&&response.status<500)return bail(error);let retryAfter=parseRetryAfterHeaderAsMillis(response.headers.get("retry-after"));if(retryAfter!==void 0&&retryAfter>6e4)return bail(error);throw attempt<attempts&&retryAfter&&await sleep(retryAfter),error}),{retries:attempts-1})}function downloadError(attempt,reason){return new DescribeError("layer_download_failed",`Could not download a required runtime layer.
9
+ Cause: ${reason}
10
+ Attempts: ${attempt}
11
+ Retry this describe command.`)}import{createHash as createHash3}from"node:crypto";import{createHash as createHash2}from"node:crypto";function getFunctionConfig(lambda){return{runtime:lambda.runtime,handler:lambda.handler,architecture:lambda.architecture,environment:Object.fromEntries(Object.entries(lambda.environment).filter(entry=>typeof entry[1]=="string")),..."launcherType"in lambda&&lambda.launcherType==="Nodejs"?{launcherType:lambda.launcherType,awsLambdaHandler:lambda.awsLambdaHandler,shouldAddHelpers:lambda.shouldAddHelpers,shouldAddSourcemapSupport:lambda.shouldAddSourcemapSupport,shouldDisableAutomaticFetchInstrumentation:lambda.shouldDisableAutomaticFetchInstrumentation,useWebApi:lambda.useWebApi}:{},memory:lambda.memory,affinity:lambda.affinity,maxConcurrency:lambda.maxConcurrency,maxDuration:lambda.maxDuration,regions:lambda.regions,functionFailoverRegions:lambda.functionFailoverRegions,supportsResponseStreaming:lambda.supportsResponseStreaming,framework:lambda.framework&&{...lambda.framework}}}var import_build_utils=__toESM(require_build_utils(),1),ROOT_BOOTSTRAP_PATH="bootstrap",USER_BOOTSTRAP_PATH="___vc_bootstrap",NATIVELY_WRAPPER_SUPPORTED_FAMILIES=["nodejs","python","ruby","java","dotnetcore","bun","executable"],BOOTSTRAP_SHIM=`#!/bin/sh
9
12
  USER_BOOTSTRAP="/var/task/${USER_BOOTSTRAP_PATH}"
10
13
 
11
14
  if [ -n "\${AWS_LAMBDA_EXEC_WRAPPER:-}" ]; then
@@ -16,11 +19,11 @@ if [ -n "\${AWS_LAMBDA_EXEC_WRAPPER:-}" ]; then
16
19
  fi
17
20
 
18
21
  exec "$USER_BOOTSTRAP" "$@"
19
- `;function hydrateLambdaFiles(lambda,encryptedEnv){let files=lambda.files??{};if(lambda.runtime==="container"||!encryptedEnv.filename||!encryptedEnv.contentBase64)return files;if(files[encryptedEnv.filename]=new import_build_utils.FileBlob({data:Buffer.from(encryptedEnv.contentBase64,"base64")}),lambda.supportsWrapper!==!0&&!NATIVELY_WRAPPER_SUPPORTED_FAMILIES.some(family=>lambda.runtime.startsWith(family))){if(!lambda.runtime.startsWith("provided"))throw new Error(`Serverless Function runtime ${lambda.runtime} does not support more than 4KB for environment variables`);let userBootstrap=files[ROOT_BOOTSTRAP_PATH];if(!userBootstrap)throw new Error(`Serverless Function runtime ${lambda.runtime} does not support more than 4KB for environment variables`);if(files[USER_BOOTSTRAP_PATH])throw new Error(`Cannot wrap "provided.*" lambda: reserved file path ${USER_BOOTSTRAP_PATH} is already in use. Please rename your file.`);files[USER_BOOTSTRAP_PATH]=userBootstrap,delete files[ROOT_BOOTSTRAP_PATH],files[ROOT_BOOTSTRAP_PATH]=new import_build_utils.FileBlob({data:BOOTSTRAP_SHIM,mode:33261})}return files}import{join as join10}from"node:path";var import_build_utils8=__toESM(require_build_utils(),1);var import_build_utils2=__toESM(require_build_utils(),1);import{join as join2}from"path";import{readFile}from"node:fs/promises";async function maybeReadJSON(path2){let contents;try{contents=await readFile(path2,"utf8")}catch(err){if(err.code!=="ENOENT")throw err;return}try{return JSON.parse(contents.charCodeAt(0)===65279?contents.slice(1):contents)}catch(err){throw err.message=`${path2}: ${err.message}`,err}}async function getBuildOutputConfig(outputDir){let configPath=getBuildOutputConfigPath(outputDir),config=await maybeReadJSON(configPath);if(!config)return;if(config.version!==3)throw new Error(`Expected \`version: 3\` in "${configPath}" file (received \`${config.version}\`)`);validateDeploymentId(config.deploymentId),validateExperimentalServicesV2(config.experimentalServicesV2);let framework=validateFrameworkVersion(config.framework);return{...config,framework}}function getBuildOutputConfigPath(outputDir){return join2(outputDir,"config.json")}var MAX_DEPLOYMENT_ID_LENGTH=32,MAX_FRAMEWORK_SLUG_LENGTH=50,MAX_FRAMEWORK_VERSION_LENGTH=50,VALID_DEPLOYMENT_ID_PATTERN=/^[a-zA-Z0-9_-]+$/;function validateDeploymentId(deploymentId){if(deploymentId&&deploymentId.length>MAX_DEPLOYMENT_ID_LENGTH)throw new import_build_utils2.NowBuildError({message:`The configured deploymentId "${deploymentId}" exceeds the maximum length of ${MAX_DEPLOYMENT_ID_LENGTH} characters. Please use a shorter deploymentId.`,code:"VC_BUILD_INVALID_DEPLOYMENT_ID_LENGTH"});if(deploymentId&&!VALID_DEPLOYMENT_ID_PATTERN.test(deploymentId))throw new import_build_utils2.NowBuildError({message:`The configured deploymentId "${deploymentId}" contains invalid characters. Only alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (_) are allowed.`,code:"VC_BUILD_INVALID_DEPLOYMENT_ID_CHARACTERS"})}function validateFrameworkVersion(framework){if(!framework)return;let{slug,version}=framework;if(typeof slug=="string"){if(typeof version!="string")throw new import_build_utils2.NowBuildError({message:`Invalid config.json: "version" type "${typeof version}" should be "string"`,code:"VC_BUILD_INVALID_CONFIG_JSON_FRAMEWORK_VERSION_TYPE"});if(slug.length>MAX_FRAMEWORK_SLUG_LENGTH){let trimmedSlug=slug.slice(0,MAX_FRAMEWORK_SLUG_LENGTH);throw new import_build_utils2.NowBuildError({message:`Invalid config.json: "framework.slug" length ${slug.length} > ${MAX_FRAMEWORK_SLUG_LENGTH}. "${trimmedSlug}..."`,code:"VC_BUILD_INVALID_CONFIG_JSON_FRAMEWORK_SLUG_LENGTH"})}if(version.length>MAX_FRAMEWORK_VERSION_LENGTH){let trimmedVersion=version.slice(0,MAX_FRAMEWORK_VERSION_LENGTH);throw new import_build_utils2.NowBuildError({message:`Invalid config.json: "framework.version" length ${version.length} > ${MAX_FRAMEWORK_VERSION_LENGTH}. "${trimmedVersion}..."`,code:"VC_BUILD_INVALID_CONFIG_JSON_FRAMEWORK_VERSION_LENGTH"})}return framework}}function validateExperimentalServicesV2(experimentalServicesV2){if(experimentalServicesV2!==void 0&&(!experimentalServicesV2||typeof experimentalServicesV2!="object"||Array.isArray(experimentalServicesV2)))throw new import_build_utils2.NowBuildError({code:"INVALID_BUILD_OUTPUT_CONFIG",message:'Invalid config.json: "experimentalServicesV2" must be an object.'})}async function getBuildOutputConfigOrThrow(outputDir){let config=await getBuildOutputConfig(outputDir);if(config)return config;throw new Error(`Config file was not found at "${getBuildOutputConfigPath(outputDir)}"`)}import{join as join3}from"path";function getFunctionSourcePath(source){return source.service?join3("services",source.service,source.output.path):source.output.path}var import_build_utils3=__toESM(require_build_utils(),1);function isRouteMiddleware(route){return"middlewarePath"in route&&typeof route.middlewarePath=="string"}var cache=new WeakMap;function getMiddlewareRouting(buildResult){let cached=cache.get(buildResult.functions);if(cached&&cached.routes===buildResult.routes)return cached.routing;let routing=new Map,{lambdas,edgeFunctions}=buildResult.functions;for(let route of buildResult.routes){if(!isRouteMiddleware(route))continue;let outputPath=route.middlewarePath;!lambdas.has(outputPath)&&!edgeFunctions.has(outputPath)&&(outputPath=outputPath.replace(/^\//,""));let output=lambdas.get(outputPath)??edgeFunctions.get(outputPath);if(!outputPath||!output)throw new import_build_utils3.NowBuildError({message:`Mapping ${route.middlewarePath} not found. Maybe you provided a wrong middlewarePath?`,code:"middleware_path_not_found"});let index=routing.get(outputPath)?.index??routing.size;routing.set(outputPath,output.type==="EdgeFunction"?{type:"middleware",middlewarePath:route.middlewarePath,outputPath,edgeFunction:output,index}:{type:"middleware-lambda",middlewarePath:route.middlewarePath,outputPath,index})}return cache.set(buildResult.functions,{routes:buildResult.routes,routing}),routing}import{join as join4}from"path";function getServiceOutputEntries(config){return Object.entries(config.experimentalServicesV2??{}).map(([name,service])=>({name,directory:join4("services",name),service}))}var import_semver=__toESM(require_semver(),1),import_build_utils4=__toESM(require_build_utils(),1);import{createHash}from"crypto";import fs2 from"fs";var fileSizeCache=new Map,getFileSize=path2=>{if(!path2)return Promise.resolve(0);let cached=fileSizeCache.get(path2);if(cached)return cached;let promise=fs2.promises.lstat(path2).then(stats=>stats.size);return fileSizeCache.set(path2,promise),promise},collectUncompressedSize=async(files,ignoreFn)=>{let size=0;return await Promise.all(Object.keys(files).map(async fileKey=>{if(!ignoreFn?.(fileKey)){if(files[fileKey].type==="FileBlob")size+=files[fileKey].data.length;else if(files[fileKey].type==="FileFsRef"){let curSize=files[fileKey].size??await getFileSize(files[fileKey].fsPath);size+=curSize}}})),size};var MIB=1024*1024,MAX_UNCOMPRESSED_FUNCTION_SIZE_BYTES=250*MIB,LAMBDA_RESERVED_UNCOMPRESSED_SIZE_BYTES=25*MIB,LARGE_FUNCTION_THRESHOLD_BYTES=MAX_UNCOMPRESSED_FUNCTION_SIZE_BYTES-LAMBDA_RESERVED_UNCOMPRESSED_SIZE_BYTES,MANIFEST_FILE_NAMES=["routes-manifest.json","server/pages-manifest.json","server/app-paths-manifest.json","app-path-routes-manifest.json"],TEST_DYNAMIC_ROUTE=/\/\[[^\/]+?\](?=\/|$)/;function isNextjsDynamicRoute(route){return route=route.startsWith("/")?route:`/${route}`,TEST_DYNAMIC_ROUTE.test(route)}function computeLambdaFieldsSignature(lambda,lambdaFields){let parts=[];for(let field of lambdaFields)parts.push(JSON.stringify(lambda[field]));return parts.join("|")}async function getLambdaFileSizeMetadata(lambdaFiles){let fileKeys=Object.keys(lambdaFiles),fileSizes=new Map,uncompressedSize=0;for(let fileKey of fileKeys){let file=lambdaFiles[fileKey];if(file===void 0)throw new Error("Expected lambdaFiles[fileKey] to be defined");let fileSize=0;file.type==="FileBlob"?fileSize=file.data.length:file.type==="FileFsRef"&&(fileSize=await collectUncompressedSize({[fileKey]:file},void 0)),fileSizes.set(fileKey,fileSize),uncompressedSize+=fileSize}return{fileKeys,fileSizes,uncompressedSize}}async function groupLambdas(lambdas,options){let{force}=options,lambdaFields=["allowQuery","affinity","architecture","awsLambdaHandler","environment","experimentalResponseStreaming","experimentalTriggers","framework","handler","maxConcurrency","maxDuration","memory","operationType","regions","runtime","runtimeLanguage","shouldAddHelpers","shouldAddSourcemapSupport","shouldDisableAutomaticFetchInstrumentation","supportsCancellation","supportsMultiPayloads","supportsResponseStreaming","supportsWrapper","useWebApi","functionFailoverRegions"],_typeCheck=lambdaFields,fieldsToCompare=force==="all"?["runtime","maxConcurrency"]:lambdaFields,maxUncompressedFunctionSize=LARGE_FUNCTION_THRESHOLD_BYTES,maxBundleSizeMb=options.maxBundleSizeMb;if(maxBundleSizeMb!==void 0&&Number.isFinite(maxBundleSizeMb)){let customMaxUncompressedFunctionSize=Math.floor(maxBundleSizeMb*MIB);output_manager_default.warn(`Warn: custom max uncompressed function size of ${customMaxUncompressedFunctionSize/MIB}MiB configured`),maxUncompressedFunctionSize=Math.min(customMaxUncompressedFunctionSize,MAX_UNCOMPRESSED_FUNCTION_SIZE_BYTES)}let seenLambdas=new Map;for(let[name,lambda]of Object.entries(lambdas)){if(!lambda.experimentalAllowBundling||!lambda.files)continue;let existingNames=seenLambdas.get(lambda);existingNames?existingNames.push(name):seenLambdas.set(lambda,[name])}let handlerDigestPromiseCache=new Map,getHandlerDigest=handlerFile=>{if(!handlerFile)return Promise.resolve(void 0);let cached=handlerDigestPromiseCache.get(handlerFile);if(cached)return cached;let promise=(async()=>{try{let handlerStream=handlerFile.toStream(),handlerBuffer=await(0,import_build_utils4.streamToBuffer)(handlerStream),handlerBytes=new Uint8Array(handlerBuffer.buffer,handlerBuffer.byteOffset,handlerBuffer.byteLength);return createHash("sha1").update(handlerBytes).digest("hex")}catch{return}})();return handlerDigestPromiseCache.set(handlerFile,promise),promise},bundlesBySignature=new Map,allBundledLambdas=[];for(let[lambda,lambdaNames]of seenLambdas){let lambdaFiles=lambda.files;if(!lambdaFiles)continue;let signature=computeLambdaFieldsSignature(lambda,fieldsToCompare),{fileKeys,fileSizes,uncompressedSize}=await getLambdaFileSizeMetadata(lambdaFiles),handlerDigest=await getHandlerDigest(lambdaFiles[lambda.handler]),compatibleBundles=bundlesBySignature.get(signature),isLarge=uncompressedSize>=LARGE_FUNCTION_THRESHOLD_BYTES,foundMatchingBundle=!1;if(compatibleBundles&&!isLarge)for(let bundleMeta of compatibleBundles){if(bundleMeta.isLarge||!(handlerDigest===bundleMeta.handlerDigest)&&force!=="all")continue;let uncompressedBytesIncrease=0;for(let fileKey of fileKeys){let incomingFileSize=fileSizes.get(fileKey)??0,existingFileSize=bundleMeta.fileSizesByKey.get(fileKey);existingFileSize===void 0?uncompressedBytesIncrease+=incomingFileSize:uncompressedBytesIncrease+=incomingFileSize-existingFileSize}let newTotalSize=bundleMeta.uncompressedBytes+uncompressedBytesIncrease;if(newTotalSize<=maxUncompressedFunctionSize){foundMatchingBundle=!0,bundleMeta.uncompressedBytes=newTotalSize,bundleMeta.lambdaNames.push(...lambdaNames);for(let fileKey of fileKeys)bundleMeta.fileSizesByKey.set(fileKey,fileSizes.get(fileKey)??0);let potentialLambdaFiles=bundleMeta.lambda.files;potentialLambdaFiles&&(bundleMeta.lambda.files=Object.assign(potentialLambdaFiles,lambdaFiles));break}}if(!foundMatchingBundle){let newBundleMeta={lambda,signature,handlerDigest,isLarge,uncompressedBytes:uncompressedSize,fileSizesByKey:new Map(fileSizes),lambdaNames:[...lambdaNames]},signatureBundles=bundlesBySignature.get(signature);signatureBundles||(signatureBundles=[],bundlesBySignature.set(signature,signatureBundles)),signatureBundles.push(newBundleMeta),allBundledLambdas.push(newBundleMeta)}}let finalLambdas=Object.assign({},lambdas);options.debug&&(output_manager_default.debug("GROUP_LAMBDAS: "+JSON.stringify(allBundledLambdas.map(bundleMeta=>({lambdaNames:bundleMeta.lambdaNames,signature:bundleMeta.signature,uncompressedBytes:bundleMeta.uncompressedBytes})),null,2)),output_manager_default.debug(`total grouped lambdas: ${allBundledLambdas.length}`));for(let bundleMeta of allBundledLambdas){let lambda=bundleMeta.lambda;for(let lambdaName of bundleMeta.lambdaNames)finalLambdas[lambdaName]=lambda;if(lambda.framework?.slug==="nextjs"&&lambda.framework.version){let CORRECTED_MANIFESTS_VERSION="v12.2.0";if(import_semver.default.gte(lambda.framework.version,CORRECTED_MANIFESTS_VERSION)){let pageFiles=[],manifestFileKeys={},manifestFileNames=MANIFEST_FILE_NAMES;for(let fileKey of Object.keys(lambda.files||{})){let isPageFile=fileKey.includes("server/pages/"),isAppFile=fileKey.includes("server/app/");if(isPageFile||isAppFile){let relativePageFile=fileKey.split(`server/${isPageFile?"pages":"app"}/`).pop();relativePageFile&&pageFiles.push(relativePageFile)}for(let manifestFileName of manifestFileNames)fileKey.endsWith(`/${manifestFileName}`)&&(manifestFileKeys[manifestFileName]=fileKey)}let appPathRoutesManifestFilesKey=manifestFileKeys["app-path-routes-manifest.json"],appPathRoutesManifestFile=appPathRoutesManifestFilesKey&&lambda.files?.[appPathRoutesManifestFilesKey],appPathRoutesManifest=appPathRoutesManifestFile?await(0,import_build_utils4.streamToBuffer)(appPathRoutesManifestFile.toStream()).then(res=>JSON.parse(res.toString("utf8"))).catch(()=>({})):{};for(let manifestFileName of manifestFileNames){let manifestFilesKey=manifestFileKeys[manifestFileName],manifestFile=manifestFilesKey&&lambda.files?.[manifestFilesKey];if(!manifestFile)continue;let manifestData=JSON.parse((await(0,import_build_utils4.streamToBuffer)(manifestFile.toStream())).toString("utf8")),normalizedPages=new Set(pageFiles.map(page=>(page=`/${page.replace(/\.js$/,"")}`,page==="/index"&&(page="/"),appPathRoutesManifest[page]||page)));switch(manifestFileName){case"routes-manifest.json":{let filterItem=item=>normalizedPages.has(item.page);manifestData.dynamicRoutes=manifestData.dynamicRoutes?.filter(filterItem),manifestData.staticRoutes=manifestData.staticRoutes?.filter(filterItem);break}case"server/pages-manifest.json":{for(let key of Object.keys(manifestData))isNextjsDynamicRoute(key)&&!normalizedPages.has(key)&&delete manifestData[key];break}case"server/app-paths-manifest.json":{if(appPathRoutesManifest)for(let key of Object.keys(manifestData)){let normalizedKey=appPathRoutesManifest[key]||key.replace(/(^|\/)(page|route)$/,"");isNextjsDynamicRoute(normalizedKey)&&!normalizedPages.has(normalizedKey)&&delete manifestData[key]}break}}lambda.files&&(lambda.files[manifestFilesKey]=new import_build_utils4.FileBlob({contentType:"application/json",data:JSON.stringify(manifestData)}))}}}}return finalLambdas}async function groupBundleableLambdas(params){let lambdas={};for(let[path2,lambda]of params.functions.lambdas)lambda.experimentalAllowBundling&&(lambdas[path2]=lambda);for(let[path2,prerender]of params.functions.prerenders)prerender.lambda.experimentalAllowBundling&&(lambdas[path2]=prerender.lambda);if(Object.keys(lambdas).length===0)return;let grouped=await groupLambdas(lambdas,{force:void 0,maxBundleSizeMb:params.options.maxBundleSizeMb,debug:params.options.debugGroupLambdas});for(let[path2,lambda]of Object.entries(grouped))if(params.functions.lambdas.has(path2))params.functions.lambdas.set(path2,lambda);else{let prerender=params.functions.prerenders.get(path2);if(prerender)prerender.lambda=lambda;else throw new Error(`Grouped lambda "${path2}" does not match any build output`)}}function*iterateNativeFunctionOutputs(functions){for(let outputs of[functions.lambdas,functions.prerenders])for(let[path2,output]of outputs)yield{path:path2,lambda:output.type==="Lambda"?output:output.lambda,prerender:output.type==="Prerender"?output:void 0}}import{join as join9}from"node:path";import{readFile as readFile3}from"node:fs/promises";var import_build_utils6=__toESM(require_build_utils(),1);import{join as join5,relative}from"path";import{readdir,stat}from"fs/promises";var SUFFIX=".func";async function*createFunctionEntriesIterator(dir,root=dir){let entries;try{entries=await readdir(dir,{withFileTypes:!0})}catch(error){if(!(typeof error=="object"&&error!==null&&"code"in error)||error.code!=="ENOENT"&&error.code!=="ENOTDIR")throw error;entries=[]}let names;for(let entry of entries){let absolutePath=join5(dir,entry.name),isSymbolicLink=entry.isSymbolicLink();if(entry.isDirectory()||isSymbolicLink&&(await stat(absolutePath)).isDirectory())if(entry.name.endsWith(SUFFIX)){names??=new Set(entries.map(e=>e.name));let baseName=entry.name.slice(0,-SUFFIX.length);yield{hasPrerenderConfig:names.has(`${baseName}.prerender-config.json`),isSymbolicLink,path:relative(root,absolutePath.substring(0,absolutePath.length-SUFFIX.length))}}else yield*createFunctionEntriesIterator(absolutePath,root)}}import{dirname,isAbsolute,join as join6,relative as relative2,resolve as resolve2,sep}from"node:path";var import_build_utils5=__toESM(require_build_utils(),1);import{lstat,readlink,realpath,readdir as readdir2,stat as stat2}from"node:fs/promises";import assert from"assert";import path from"path";async function glob(options){if(!path.isAbsolute(options.cwd))throw new Error(`basePath/cwd must be an absolute path (${options.cwd})`);let results={},statCache={},symlinks={},files=await walkAll(options.cwd,!!options.follow,statCache,symlinks),dirs=new Set,dirsWithEntries=new Set;for(let relativePath of files){let fsPath=path.join(options.cwd,relativePath),stats=statCache[fsPath];assert(stats,`statCache does not contain value for ${relativePath}`);let isSymlink=symlinks[fsPath];if(options.follow&&(isSymlink||(await lstat(fsPath)).isSymbolicLink())){let target=await readlink(fsPath),absoluteTarget=path.resolve(path.dirname(fsPath),target);if(path.relative(options.cwd,absoluteTarget).startsWith(`..${path.sep}`))continue}if(isSymlink||stats.isFile()||stats.isDirectory()){isSymlink&&(stats=await lstat(fsPath));let dirname4=path.dirname(relativePath);if(dirsWithEntries.add(dirname4),stats.isDirectory()){dirs.add(relativePath);continue}results[relativePath]=new import_build_utils5.FileFsRef({mode:stats.mode,fsPath,size:stats.size})}}if(options.includeDirectories)for(let relativePath of dirs){if(dirsWithEntries.has(relativePath))continue;let fsPath=path.join(options.cwd,relativePath),stats=statCache[fsPath];results[relativePath]=new import_build_utils5.FileFsRef({mode:stats.mode,fsPath,size:stats.size})}return results}async function walkAll(cwd,follow,statCache,symlinks){let files=[];async function walk(dirAbs,realDir,ancestors){let entries;try{entries=await readdir2(dirAbs,{withFileTypes:!0})}catch(err){let code2=err.code;if(code2==="ENOENT"||code2==="ENOTDIR")return;throw err}await Promise.all(entries.map(async entry=>{let abs=path.join(dirAbs,entry.name);if(entry.isSymbolicLink())if(follow){let stats=await stat2(abs).catch(()=>lstat(abs).catch(()=>null));if(stats===null)return;if(statCache[abs]=stats,files.push(abs),stats.isDirectory()){let real=await realpath(abs).catch(()=>null);real!==null&&!ancestors.has(real)&&await walk(abs,real,new Set(ancestors).add(real))}}else{let stats=await lstat(abs).catch(()=>null);if(stats===null)return;statCache[abs]=stats,symlinks[abs]=!0,files.push(abs)}else if(entry.isDirectory()){let stats=await lstat(abs).catch(()=>null);if(stats===null)return;statCache[abs]=stats,files.push(abs);let real=path.join(realDir,entry.name);await walk(abs,real,new Set(ancestors).add(real))}else{let stats=await lstat(abs).catch(()=>null);if(stats===null)return;statCache[abs]=stats,files.push(abs)}}))}let cwdReal=follow?await realpath(cwd).catch(()=>null):cwd;return cwdReal!==null&&await walk(cwd,cwdReal,new Set([cwdReal])),files.map(abs=>path.relative(cwd,abs)).sort((a,b)=>a.localeCompare(b,"en"))}import{isNativeError}from"node:util/types";import{readlink as readlink2,realpath as realpath2}from"node:fs/promises";async function readFunctions(params){let fileFsRefsCache=new Map,entries=[],functionsDir=join6(params.outputDir,"functions"),iterator=enumerate(createFunctionEntriesIterator(functionsDir));await Promise.all(Array.from({length:params.concurrency??32},async()=>{for await(let[index,entry]of iterator)entries[index]=await deserializeFunctionEntry({prebuilt:params.prebuilt,entry,fileFsRefsCache,functionsDir,repoRootPath:params.repoRootPath})}));let serverActionsManifestPaths=new Set,edgeFunctions=new Map,unsortedPrerenders=new Map,functionSymlinks=new Map,lambdas=new Map;for(let functionEntry of entries)functionEntry.symlinkTarget!==void 0&&functionSymlinks.set(functionEntry.path,functionEntry.symlinkTarget),functionEntry.serverActionsManifestPath&&serverActionsManifestPaths.add(functionEntry.serverActionsManifestPath),functionEntry.output?.type==="Prerender"?unsortedPrerenders.set(functionEntry.path,functionEntry.output):functionEntry.output?.type==="Lambda"?lambdas.set(functionEntry.path,functionEntry.output):functionEntry.output?.type==="EdgeFunction"&&edgeFunctions.set(functionEntry.path,functionEntry.output);for(let[path2,target]of functionSymlinks){let destFunction=unsortedPrerenders.get(target)?.lambda??edgeFunctions.get(target)??lambdas.get(target);if(!destFunction)throw new Error(`Could not find target "${target}" Lambda or EdgeFunction for path "${path2}"`);let srcPrerender=unsortedPrerenders.get(path2);if(!srcPrerender)destFunction.type==="Lambda"?lambdas.set(path2,destFunction):destFunction.type==="EdgeFunction"&&edgeFunctions.set(path2,destFunction);else{if(destFunction.type!=="Lambda")throw new Error(`Unexpected function type "${destFunction.type}" at path "${path2}"`);srcPrerender.lambda=destFunction}}let prerenders=new Map;for(let[path2,prerender]of[...unsortedPrerenders].sort((a,b)=>(a[1].group??0)-(b[1].group??0)))validatePrerender(prerender),prerenders.set(path2,prerender);return{edgeFunctions,lambdas,prerenders,serverActionsManifestPaths}}async function*enumerate(iterable){let index=0;for await(let item of iterable)yield[index++,item]}async function deserializeFunctionEntry(params){let functionDir=join6(params.functionsDir,`${params.entry.path}.func`),prerenderConfigPath=join6(params.functionsDir,`${params.entry.path}.prerender-config.json`),configPromise=params.entry.hasPrerenderConfig?maybeReadJSON(prerenderConfigPath):void 0;configPromise?.catch(()=>{});let lambda,serverActionsManifestPath,symlinkTarget;if(params.entry.isSymbolicLink)symlinkTarget=await readlink2(functionDir).then(link=>join6(dirname(params.entry.path),link).slice(0,-5));else{let functionConfigPath=join6(functionDir,".vc-config.json"),[functionConfig,files]=await Promise.all([maybeReadJSON(functionConfigPath),glob({cwd:functionDir,includeDirectories:!0})]);if(!functionConfig)throw new Error(`Could not load function config: "${functionConfigPath}"`);if(delete files[".vc-config.json"],functionConfig.filePathMap&&await hydrateFilesMap(files,functionConfig.filePathMap,params.repoRootPath,params.fileFsRefsCache,params.prebuilt),"type"in functionConfig&&functionConfig.type==="EdgeFunction"||functionConfig.runtime==="edge")return{path:params.entry.path,output:new import_build_utils6.EdgeFunction({deploymentTarget:"v8-worker",...functionConfig,files})};let supportsResponseStreaming=functionConfig.supportsResponseStreaming??functionConfig.experimentalResponseStreaming;lambda="launcherType"in functionConfig&&functionConfig.launcherType==="Nodejs"?new import_build_utils6.NodejsLambda({...functionConfig,files,supportsResponseStreaming:functionConfig.awsLambdaHandler===void 0||functionConfig.awsLambdaHandler===""||supportsResponseStreaming}):new import_build_utils6.Lambda({...functionConfig,files,supportsResponseStreaming}),serverActionsManifestPath=functionConfig.filePathMap?.[".next/server/server-reference-manifest.json"]}if(configPromise){let prerenderConfig=await configPromise;if(prerenderConfig)return{path:params.entry.path,symlinkTarget,serverActionsManifestPath,output:new import_build_utils6.Prerender({...prerenderConfig,fallback:await deserializePrerenderFallback(prerenderConfigPath,prerenderConfig.fallback,params),initialMetadata:sanitizeInitialMetadata(prerenderConfig.initialMetadata),lambda})}}return{path:params.entry.path,symlinkTarget,output:lambda,serverActionsManifestPath}}function validatePrerender(prerender){if(prerender.lambda===void 0)throw new Error('Prerender "buildResult" is missing "lambda" property')}async function hydrateFilesMap(files,filesMap,repoRootPath,fileFsRefsCache,prebuilt){let rootPath=prebuilt?await realpath2(repoRootPath):void 0;async function hydrateFile(projectPath){let fsPath=join6(repoRootPath,projectPath);rootPath!==void 0&&await validatePrebuiltFilePath(fsPath,rootPath,`file map source "${projectPath}"`,!0);let file=await import_build_utils6.FileFsRef.fromFsPath({fsPath});return fileFsRefsCache.set(projectPath,file),file}let pending;for(let functionPath in filesMap){let projectPath=filesMap[functionPath],cached=fileFsRefsCache.get(projectPath);if(cached&&!(cached instanceof Promise)){files[functionPath]=cached;continue}let filePromise=cached;if(!filePromise){let promise=hydrateFile(projectPath);fileFsRefsCache.set(projectPath,promise),filePromise=promise}(pending??=[]).push(filePromise.then(file=>{files[functionPath]=file}))}pending&&await Promise.all(pending)}async function validatePrebuiltFilePath(fsPath,rootPath,source,enableDanglingSymlinks=!1){let resolvedPath;try{resolvedPath=await realpath2(fsPath)}catch(error){if(!enableDanglingSymlinks||!isNativeError(error)||!("code"in error)||error.code!=="ENOENT")throw error;let target=await readlink2(fsPath),parentPath=await validatePrebuiltFilePath(dirname(fsPath),rootPath,source);resolvedPath=resolve2(parentPath,target)}let sourcePath=relative2(rootPath,resolvedPath);if(sourcePath===".."||sourcePath.startsWith(`..${sep}`)||isAbsolute(sourcePath))throw new import_build_utils6.NowBuildError({code:"INVALID_PREBUILT_FILE_PATH",message:`Prebuilt ${source} must be inside the uploaded project.`});return resolvedPath}function sanitizeInitialMetadata(initialMetadata){try{if(typeof initialMetadata!="object"||initialMetadata===null||Array.isArray(initialMetadata))return;let{compute,htmlSize}=initialMetadata;return compute!=="blocking"&&compute!=="resuming"&&compute!=="static"||htmlSize!==void 0&&(!Number.isSafeInteger(htmlSize)||htmlSize<0)?void 0:{compute,...htmlSize!==void 0&&{htmlSize}}}catch{return}}async function deserializePrerenderFallback(prerenderConfigPath,fallback,options){if(fallback==null)return null;let path2=typeof fallback=="string"?fallback:fallback.fsPath,fsPath=join6(dirname(prerenderConfigPath),path2);return options.prebuilt&&await validatePrebuiltFilePath(fsPath,await realpath2(options.repoRootPath),`prerender fallback "${path2}"`),typeof fallback=="string"?import_build_utils6.FileFsRef.fromFsPath({fsPath}):fallback.mode!==void 0?new import_build_utils6.FileFsRef({mode:fallback.mode,size:fallback.size,contentType:fallback.contentType,fsPath}):import_build_utils6.FileFsRef.fromFsPath({mode:fallback.mode,size:fallback.size,contentType:fallback.contentType,fsPath})}var import_build_utils7=__toESM(require_build_utils(),1);import{join as join7}from"path";async function readServiceOutputConfig(outputDir,entry){let config=await getBuildOutputConfig(join7(outputDir,entry.directory));if(!config&&entry.service.root===void 0)throw new import_build_utils7.NowBuildError({code:"MISSING_SERVICE_BUILD_OUTPUT",message:`Service "${entry.name}" is configured in experimentalServicesV2 but is missing build output at ".vercel/output/services/${entry.name}/config.json".`});return config}var import_async_sema=__toESM(require_async_sema(),1),import_ignore=__toESM(require_ignore(),1);import{basename,isAbsolute as isAbsolute2,join as join8,relative as relative3,sep as sep2}from"node:path";import{readFile as readFile2,readdir as readdir3,realpath as realpath3,stat as stat3}from"node:fs/promises";function contains(root,path2){let rel=relative3(root,path2);return rel!==".."&&!rel.startsWith(`..${sep2}`)&&!isAbsolute2(rel)}function invalidSource(){throw new DescribeError("invalid_build_output","Build output references files outside the authorized output or includes excluded source files. Remove unsafe links and excluded file mappings, then rebuild.")}var vcs=(0,import_ignore.default)().add([".hg",".git",".gitmodules",".svn","CVS"]),dependencies=(0,import_ignore.default)().add(["node_modules",".next",".yarn/cache",".pnp*",".venv","venv","__pycache__","/target"]);async function readIgnore(root){let read=name=>readFile2(join8(root,name),"utf8").catch(error=>{if(error.code==="ENOENT")return"";throw error}),[vercelignore,nowignore]=await Promise.all([read(".vercelignore"),read(".nowignore")]);if(vercelignore&&nowignore)throw new DescribeError("invalid_build_output","Cannot use both .vercelignore and .nowignore. Remove the deprecated .nowignore file and retry.");return(0,import_ignore.default)().add((vercelignore||nowignore).replace(/(\n|^)\.\//g,"$1"))}async function validateBuildOutput(options){let root=await realpath3(options.repoRootPath),output=await realpath3(options.outputDir),expectedOutput=join8(root,relative3(options.repoRootPath,options.outputDir));(!contains(root,output)||relative3(expectedOutput,output)!=="")&&invalidSource();let project=options.directory?await realpath3(options.directory):root,bases=[root];if(project!==root&&contains(root,project))for(let segment of relative3(root,project).split(sep2))bases.push(join8(bases[bases.length-1],segment));let ignores=await Promise.all(bases.map(async base=>({base,rules:await readIgnore(base)}))),sema=new import_async_sema.default(32),limit=async fn=>{await sema.acquire();try{return await fn()}finally{sema.release()}},checkSource=async path2=>{let resolved=await limit(()=>realpath3(path2));for(let source of[join8(root,relative3(options.repoRootPath,path2)),resolved]){contains(root,source)||invalidSource();let rel=relative3(root,source).split(sep2).join("/");if(rel&&(vcs.ignores(rel)&&invalidSource(),!contains(output,source)))for(let{base,rules}of ignores){if(!contains(base,source))continue;let relToBase=relative3(base,source).split(sep2).join("/");relToBase&&rules.ignores(relToBase)&&!dependencies.ignores(relToBase)&&invalidSource()}}return resolved},checked=new Map,validateSource=path2=>{let result=checked.get(path2);return result||(result=checkSource(path2),checked.set(path2,result)),result},configs=[],visited=new Set;async function walk(dir,ancestors){visited.add(dir);let next=new Set(ancestors).add(dir),entries=await Promise.all((await limit(()=>readdir3(dir))).map(async name=>{let path2=join8(dir,name),resolved=await limit(()=>realpath3(path2));return(!contains(output,resolved)||next.has(resolved))&&invalidSource(),{path:path2,resolved,stats:await limit(()=>stat3(resolved))}}));for(let{path:path2,resolved,stats}of entries)stats.isDirectory()?visited.has(resolved)||await walk(resolved,next):basename(path2)===".vc-config.json"&&configs.push(resolved)}return await walk(output,new Set),await Promise.all(configs.map(async path2=>{let config=JSON.parse(await limit(()=>readFile2(path2,"utf8")));await Promise.all(Object.values(config.filePathMap??{}).map(source=>(typeof source!="string"&&invalidSource(),validateSource(join8(options.repoRootPath,source)))))})),validateSource}var external_exports={};__export(external_exports,{BRAND:()=>BRAND,DIRTY:()=>DIRTY,EMPTY_PATH:()=>EMPTY_PATH,INVALID:()=>INVALID,NEVER:()=>NEVER,OK:()=>OK,ParseStatus:()=>ParseStatus,Schema:()=>ZodType,ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBigInt:()=>ZodBigInt,ZodBoolean:()=>ZodBoolean,ZodBranded:()=>ZodBranded,ZodCatch:()=>ZodCatch,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodEffects:()=>ZodEffects,ZodEnum:()=>ZodEnum,ZodError:()=>ZodError,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodFunction:()=>ZodFunction,ZodIntersection:()=>ZodIntersection,ZodIssueCode:()=>ZodIssueCode,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNativeEnum:()=>ZodNativeEnum,ZodNever:()=>ZodNever,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodParsedType:()=>ZodParsedType,ZodPipeline:()=>ZodPipeline,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRecord:()=>ZodRecord,ZodSchema:()=>ZodType,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodSymbol:()=>ZodSymbol,ZodTransformer:()=>ZodEffects,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,addIssueToContext:()=>addIssueToContext,any:()=>anyType,array:()=>arrayType,bigint:()=>bigIntType,boolean:()=>booleanType,coerce:()=>coerce,custom:()=>custom,date:()=>dateType,datetimeRegex:()=>datetimeRegex,defaultErrorMap:()=>en_default,discriminatedUnion:()=>discriminatedUnionType,effect:()=>effectsType,enum:()=>enumType,function:()=>functionType,getErrorMap:()=>getErrorMap,getParsedType:()=>getParsedType,instanceof:()=>instanceOfType,intersection:()=>intersectionType,isAborted:()=>isAborted,isAsync:()=>isAsync,isDirty:()=>isDirty,isValid:()=>isValid,late:()=>late,lazy:()=>lazyType,literal:()=>literalType,makeIssue:()=>makeIssue,map:()=>mapType,nan:()=>nanType,nativeEnum:()=>nativeEnumType,never:()=>neverType,null:()=>nullType,nullable:()=>nullableType,number:()=>numberType,object:()=>objectType,objectUtil:()=>objectUtil,oboolean:()=>oboolean,onumber:()=>onumber,optional:()=>optionalType,ostring:()=>ostring,pipeline:()=>pipelineType,preprocess:()=>preprocessType,promise:()=>promiseType,quotelessJson:()=>quotelessJson,record:()=>recordType,set:()=>setType,setErrorMap:()=>setErrorMap,strictObject:()=>strictObjectType,string:()=>stringType,symbol:()=>symbolType,transformer:()=>effectsType,tuple:()=>tupleType,undefined:()=>undefinedType,union:()=>unionType,unknown:()=>unknownType,util:()=>util,void:()=>voidType});var util;(function(util2){util2.assertEqual=_=>{};function assertIs(_arg){}util2.assertIs=assertIs;function assertNever(_x){throw new Error}util2.assertNever=assertNever,util2.arrayToEnum=items=>{let obj={};for(let item of items)obj[item]=item;return obj},util2.getValidEnumValues=obj=>{let validKeys=util2.objectKeys(obj).filter(k=>typeof obj[obj[k]]!="number"),filtered={};for(let k of validKeys)filtered[k]=obj[k];return util2.objectValues(filtered)},util2.objectValues=obj=>util2.objectKeys(obj).map(function(e){return obj[e]}),util2.objectKeys=typeof Object.keys=="function"?obj=>Object.keys(obj):object=>{let keys=[];for(let key in object)Object.prototype.hasOwnProperty.call(object,key)&&keys.push(key);return keys},util2.find=(arr,checker)=>{for(let item of arr)if(checker(item))return item},util2.isInteger=typeof Number.isInteger=="function"?val=>Number.isInteger(val):val=>typeof val=="number"&&Number.isFinite(val)&&Math.floor(val)===val;function joinValues(array,separator=" | "){return array.map(val=>typeof val=="string"?`'${val}'`:val).join(separator)}util2.joinValues=joinValues,util2.jsonStringifyReplacer=(_,value)=>typeof value=="bigint"?value.toString():value})(util||(util={}));var objectUtil;(function(objectUtil2){objectUtil2.mergeShapes=(first,second)=>({...first,...second})})(objectUtil||(objectUtil={}));var ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=data=>{switch(typeof data){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(data)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(data)?ZodParsedType.array:data===null?ZodParsedType.null:data.then&&typeof data.then=="function"&&data.catch&&typeof data.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&data instanceof Map?ZodParsedType.map:typeof Set<"u"&&data instanceof Set?ZodParsedType.set:typeof Date<"u"&&data instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}};var ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),quotelessJson=obj=>JSON.stringify(obj,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError=class _ZodError extends Error{get errors(){return this.issues}constructor(issues){super(),this.issues=[],this.addIssue=sub=>{this.issues=[...this.issues,sub]},this.addIssues=(subs=[])=>{this.issues=[...this.issues,...subs]};let actualProto=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,actualProto):this.__proto__=actualProto,this.name="ZodError",this.issues=issues}format(_mapper){let mapper=_mapper||function(issue){return issue.message},fieldErrors={_errors:[]},processError=error=>{for(let issue of error.issues)if(issue.code==="invalid_union")issue.unionErrors.map(processError);else if(issue.code==="invalid_return_type")processError(issue.returnTypeError);else if(issue.code==="invalid_arguments")processError(issue.argumentsError);else if(issue.path.length===0)fieldErrors._errors.push(mapper(issue));else{let curr=fieldErrors,i=0;for(;i<issue.path.length;){let el=issue.path[i];i===issue.path.length-1?(curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue))):curr[el]=curr[el]||{_errors:[]},curr=curr[el],i++}}};return processError(this),fieldErrors}static assert(value){if(!(value instanceof _ZodError))throw new Error(`Not a ZodError: ${value}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(mapper=issue=>issue.message){let fieldErrors={},formErrors=[];for(let sub of this.issues)if(sub.path.length>0){let firstEl=sub.path[0];fieldErrors[firstEl]=fieldErrors[firstEl]||[],fieldErrors[firstEl].push(mapper(sub))}else formErrors.push(mapper(sub));return{formErrors,fieldErrors}}get formErrors(){return this.flatten()}};ZodError.create=issues=>new ZodError(issues);var errorMap=(issue,_ctx)=>{let message;switch(issue.code){case ZodIssueCode.invalid_type:issue.received===ZodParsedType.undefined?message="Required":message=`Expected ${issue.expected}, received ${issue.received}`;break;case ZodIssueCode.invalid_literal:message=`Invalid literal value, expected ${JSON.stringify(issue.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:message=`Unrecognized key(s) in object: ${util.joinValues(issue.keys,", ")}`;break;case ZodIssueCode.invalid_union:message="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:message=`Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;break;case ZodIssueCode.invalid_enum_value:message=`Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;break;case ZodIssueCode.invalid_arguments:message="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:message="Invalid function return type";break;case ZodIssueCode.invalid_date:message="Invalid date";break;case ZodIssueCode.invalid_string:typeof issue.validation=="object"?"includes"in issue.validation?(message=`Invalid input: must include "${issue.validation.includes}"`,typeof issue.validation.position=="number"&&(message=`${message} at one or more positions greater than or equal to ${issue.validation.position}`)):"startsWith"in issue.validation?message=`Invalid input: must start with "${issue.validation.startsWith}"`:"endsWith"in issue.validation?message=`Invalid input: must end with "${issue.validation.endsWith}"`:util.assertNever(issue.validation):issue.validation!=="regex"?message=`Invalid ${issue.validation}`:message="Invalid";break;case ZodIssueCode.too_small:issue.type==="array"?message=`Array must contain ${issue.exact?"exactly":issue.inclusive?"at least":"more than"} ${issue.minimum} element(s)`:issue.type==="string"?message=`String must contain ${issue.exact?"exactly":issue.inclusive?"at least":"over"} ${issue.minimum} character(s)`:issue.type==="number"?message=`Number must be ${issue.exact?"exactly equal to ":issue.inclusive?"greater than or equal to ":"greater than "}${issue.minimum}`:issue.type==="bigint"?message=`Number must be ${issue.exact?"exactly equal to ":issue.inclusive?"greater than or equal to ":"greater than "}${issue.minimum}`:issue.type==="date"?message=`Date must be ${issue.exact?"exactly equal to ":issue.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(issue.minimum))}`:message="Invalid input";break;case ZodIssueCode.too_big:issue.type==="array"?message=`Array must contain ${issue.exact?"exactly":issue.inclusive?"at most":"less than"} ${issue.maximum} element(s)`:issue.type==="string"?message=`String must contain ${issue.exact?"exactly":issue.inclusive?"at most":"under"} ${issue.maximum} character(s)`:issue.type==="number"?message=`Number must be ${issue.exact?"exactly":issue.inclusive?"less than or equal to":"less than"} ${issue.maximum}`:issue.type==="bigint"?message=`BigInt must be ${issue.exact?"exactly":issue.inclusive?"less than or equal to":"less than"} ${issue.maximum}`:issue.type==="date"?message=`Date must be ${issue.exact?"exactly":issue.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(issue.maximum))}`:message="Invalid input";break;case ZodIssueCode.custom:message="Invalid input";break;case ZodIssueCode.invalid_intersection_types:message="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:message=`Number must be a multiple of ${issue.multipleOf}`;break;case ZodIssueCode.not_finite:message="Number must be finite";break;default:message=_ctx.defaultError,util.assertNever(issue)}return{message}},en_default=errorMap;var overrideErrorMap=en_default;function setErrorMap(map){overrideErrorMap=map}function getErrorMap(){return overrideErrorMap}var makeIssue=params=>{let{data,path:path2,errorMaps,issueData}=params,fullPath=[...path2,...issueData.path||[]],fullIssue={...issueData,path:fullPath};if(issueData.message!==void 0)return{...issueData,path:fullPath,message:issueData.message};let errorMessage="",maps=errorMaps.filter(m=>!!m).slice().reverse();for(let map of maps)errorMessage=map(fullIssue,{data,defaultError:errorMessage}).message;return{...issueData,path:fullPath,message:errorMessage}},EMPTY_PATH=[];function addIssueToContext(ctx,issueData){let overrideMap=getErrorMap(),issue=makeIssue({issueData,data:ctx.data,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,overrideMap,overrideMap===en_default?void 0:en_default].filter(x=>!!x)});ctx.common.issues.push(issue)}var ParseStatus=class _ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(status,results){let arrayValue=[];for(let s of results){if(s.status==="aborted")return INVALID;s.status==="dirty"&&status.dirty(),arrayValue.push(s.value)}return{status:status.value,value:arrayValue}}static async mergeObjectAsync(status,pairs){let syncPairs=[];for(let pair of pairs){let key=await pair.key,value=await pair.value;syncPairs.push({key,value})}return _ParseStatus.mergeObjectSync(status,syncPairs)}static mergeObjectSync(status,pairs){let finalObject={};for(let pair of pairs){let{key,value}=pair;if(key.status==="aborted"||value.status==="aborted")return INVALID;key.status==="dirty"&&status.dirty(),value.status==="dirty"&&status.dirty(),key.value!=="__proto__"&&(typeof value.value<"u"||pair.alwaysSet)&&(finalObject[key.value]=value.value)}return{status:status.value,value:finalObject}}},INVALID=Object.freeze({status:"aborted"}),DIRTY=value=>({status:"dirty",value}),OK=value=>({status:"valid",value}),isAborted=x=>x.status==="aborted",isDirty=x=>x.status==="dirty",isValid=x=>x.status==="valid",isAsync=x=>typeof Promise<"u"&&x instanceof Promise;var errorUtil;(function(errorUtil2){errorUtil2.errToObj=message=>typeof message=="string"?{message}:message||{},errorUtil2.toString=message=>typeof message=="string"?message:message?.message})(errorUtil||(errorUtil={}));var ParseInputLazyPath=class{constructor(parent,value,path2,key){this._cachedPath=[],this.parent=parent,this.data=value,this._path=path2,this._key=key}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},handleResult=(ctx,result)=>{if(isValid(result))return{success:!0,data:result.value};if(!ctx.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let error=new ZodError(ctx.common.issues);return this._error=error,this._error}}};function processCreateParams(params){if(!params)return{};let{errorMap:errorMap2,invalid_type_error,required_error,description}=params;if(errorMap2&&(invalid_type_error||required_error))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return errorMap2?{errorMap:errorMap2,description}:{errorMap:(iss,ctx)=>{let{message}=params;return iss.code==="invalid_enum_value"?{message:message??ctx.defaultError}:typeof ctx.data>"u"?{message:message??required_error??ctx.defaultError}:iss.code!=="invalid_type"?{message:ctx.defaultError}:{message:message??invalid_type_error??ctx.defaultError}},description}}var ZodType=class{get description(){return this._def.description}_getType(input){return getParsedType(input.data)}_getOrReturnCtx(input,ctx){return ctx||{common:input.parent.common,data:input.data,parsedType:getParsedType(input.data),schemaErrorMap:this._def.errorMap,path:input.path,parent:input.parent}}_processInputParams(input){return{status:new ParseStatus,ctx:{common:input.parent.common,data:input.data,parsedType:getParsedType(input.data),schemaErrorMap:this._def.errorMap,path:input.path,parent:input.parent}}}_parseSync(input){let result=this._parse(input);if(isAsync(result))throw new Error("Synchronous parse encountered promise.");return result}_parseAsync(input){let result=this._parse(input);return Promise.resolve(result)}parse(data,params){let result=this.safeParse(data,params);if(result.success)return result.data;throw result.error}safeParse(data,params){let ctx={common:{issues:[],async:params?.async??!1,contextualErrorMap:params?.errorMap},path:params?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data,parsedType:getParsedType(data)},result=this._parseSync({data,path:ctx.path,parent:ctx});return handleResult(ctx,result)}"~validate"(data){let ctx={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data,parsedType:getParsedType(data)};if(!this["~standard"].async)try{let result=this._parseSync({data,path:[],parent:ctx});return isValid(result)?{value:result.value}:{issues:ctx.common.issues}}catch(err){err?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),ctx.common={issues:[],async:!0}}return this._parseAsync({data,path:[],parent:ctx}).then(result=>isValid(result)?{value:result.value}:{issues:ctx.common.issues})}async parseAsync(data,params){let result=await this.safeParseAsync(data,params);if(result.success)return result.data;throw result.error}async safeParseAsync(data,params){let ctx={common:{issues:[],contextualErrorMap:params?.errorMap,async:!0},path:params?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data,parsedType:getParsedType(data)},maybeAsyncResult=this._parse({data,path:ctx.path,parent:ctx}),result=await(isAsync(maybeAsyncResult)?maybeAsyncResult:Promise.resolve(maybeAsyncResult));return handleResult(ctx,result)}refine(check,message){let getIssueProperties=val=>typeof message=="string"||typeof message>"u"?{message}:typeof message=="function"?message(val):message;return this._refinement((val,ctx)=>{let result=check(val),setError=()=>ctx.addIssue({code:ZodIssueCode.custom,...getIssueProperties(val)});return typeof Promise<"u"&&result instanceof Promise?result.then(data=>data?!0:(setError(),!1)):result?!0:(setError(),!1)})}refinement(check,refinementData){return this._refinement((val,ctx)=>check(val)?!0:(ctx.addIssue(typeof refinementData=="function"?refinementData(val,ctx):refinementData),!1))}_refinement(refinement){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement}})}superRefine(refinement){return this._refinement(refinement)}constructor(def){this.spa=this.safeParseAsync,this._def=def,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:data=>this["~validate"](data)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(option){return ZodUnion.create([this,option],this._def)}and(incoming){return ZodIntersection.create(this,incoming,this._def)}transform(transform){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform}})}default(def){let defaultValueFunc=typeof def=="function"?def:()=>def;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:defaultValueFunc,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(def){let catchValueFunc=typeof def=="function"?def:()=>def;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:catchValueFunc,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(description){let This=this.constructor;return new This({...this._def,description})}pipe(target){return ZodPipeline.create(this,target)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",emojiRegex,ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(args){let secondsRegexSource="[0-5]\\d";args.precision?secondsRegexSource=`${secondsRegexSource}\\.\\d{${args.precision}}`:args.precision==null&&(secondsRegexSource=`${secondsRegexSource}(\\.\\d+)?`);let secondsQuantifier=args.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`}function timeRegex(args){return new RegExp(`^${timeRegexSource(args)}$`)}function datetimeRegex(args){let regex=`${dateRegexSource}T${timeRegexSource(args)}`,opts=[];return opts.push(args.local?"Z?":"Z"),args.offset&&opts.push("([+-]\\d{2}:?\\d{2})"),regex=`${regex}(${opts.join("|")})`,new RegExp(`^${regex}$`)}function isValidIP(ip,version){return!!((version==="v4"||!version)&&ipv4Regex.test(ip)||(version==="v6"||!version)&&ipv6Regex.test(ip))}function isValidJWT(jwt,alg){if(!jwtRegex.test(jwt))return!1;try{let[header]=jwt.split(".");if(!header)return!1;let base64=header.replace(/-/g,"+").replace(/_/g,"/").padEnd(header.length+(4-header.length%4)%4,"="),decoded=JSON.parse(atob(base64));return!(typeof decoded!="object"||decoded===null||"typ"in decoded&&decoded?.typ!=="JWT"||!decoded.alg||alg&&decoded.alg!==alg)}catch{return!1}}function isValidCidr(ip,version){return!!((version==="v4"||!version)&&ipv4CidrRegex.test(ip)||(version==="v6"||!version)&&ipv6CidrRegex.test(ip))}var ZodString=class _ZodString extends ZodType{_parse(input){if(this._def.coerce&&(input.data=String(input.data)),this._getType(input)!==ZodParsedType.string){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:ctx2.parsedType}),INVALID}let status=new ParseStatus,ctx;for(let check of this._def.checks)if(check.kind==="min")input.data.length<check.value&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"string",inclusive:!0,exact:!1,message:check.message}),status.dirty());else if(check.kind==="max")input.data.length>check.value&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"string",inclusive:!0,exact:!1,message:check.message}),status.dirty());else if(check.kind==="length"){let tooBig=input.data.length>check.value,tooSmall=input.data.length<check.value;(tooBig||tooSmall)&&(ctx=this._getOrReturnCtx(input,ctx),tooBig?addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"string",inclusive:!0,exact:!0,message:check.message}):tooSmall&&addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"string",inclusive:!0,exact:!0,message:check.message}),status.dirty())}else if(check.kind==="email")emailRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"email",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty());else if(check.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"emoji",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty());else if(check.kind==="uuid")uuidRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"uuid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty());else if(check.kind==="nanoid")nanoidRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty());else if(check.kind==="cuid")cuidRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"cuid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty());else if(check.kind==="cuid2")cuid2Regex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty());else if(check.kind==="ulid")ulidRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"ulid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty());else if(check.kind==="url")try{new URL(input.data)}catch{ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"url",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else check.kind==="regex"?(check.regex.lastIndex=0,check.regex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"regex",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty())):check.kind==="trim"?input.data=input.data.trim():check.kind==="includes"?input.data.includes(check.value,check.position)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{includes:check.value,position:check.position},message:check.message}),status.dirty()):check.kind==="toLowerCase"?input.data=input.data.toLowerCase():check.kind==="toUpperCase"?input.data=input.data.toUpperCase():check.kind==="startsWith"?input.data.startsWith(check.value)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{startsWith:check.value},message:check.message}),status.dirty()):check.kind==="endsWith"?input.data.endsWith(check.value)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{endsWith:check.value},message:check.message}),status.dirty()):check.kind==="datetime"?datetimeRegex(check).test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"datetime",message:check.message}),status.dirty()):check.kind==="date"?dateRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"date",message:check.message}),status.dirty()):check.kind==="time"?timeRegex(check).test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"time",message:check.message}),status.dirty()):check.kind==="duration"?durationRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"duration",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()):check.kind==="ip"?isValidIP(input.data,check.version)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"ip",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()):check.kind==="jwt"?isValidJWT(input.data,check.alg)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"jwt",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()):check.kind==="cidr"?isValidCidr(input.data,check.version)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"cidr",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()):check.kind==="base64"?base64Regex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"base64",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()):check.kind==="base64url"?base64urlRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"base64url",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()):util.assertNever(check);return{status:status.value,value:input.data}}_regex(regex,validation,message){return this.refinement(data=>regex.test(data),{validation,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(message)})}_addCheck(check){return new _ZodString({...this._def,checks:[...this._def.checks,check]})}email(message){return this._addCheck({kind:"email",...errorUtil.errToObj(message)})}url(message){return this._addCheck({kind:"url",...errorUtil.errToObj(message)})}emoji(message){return this._addCheck({kind:"emoji",...errorUtil.errToObj(message)})}uuid(message){return this._addCheck({kind:"uuid",...errorUtil.errToObj(message)})}nanoid(message){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(message)})}cuid(message){return this._addCheck({kind:"cuid",...errorUtil.errToObj(message)})}cuid2(message){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(message)})}ulid(message){return this._addCheck({kind:"ulid",...errorUtil.errToObj(message)})}base64(message){return this._addCheck({kind:"base64",...errorUtil.errToObj(message)})}base64url(message){return this._addCheck({kind:"base64url",...errorUtil.errToObj(message)})}jwt(options){return this._addCheck({kind:"jwt",...errorUtil.errToObj(options)})}ip(options){return this._addCheck({kind:"ip",...errorUtil.errToObj(options)})}cidr(options){return this._addCheck({kind:"cidr",...errorUtil.errToObj(options)})}datetime(options){return typeof options=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:options}):this._addCheck({kind:"datetime",precision:typeof options?.precision>"u"?null:options?.precision,offset:options?.offset??!1,local:options?.local??!1,...errorUtil.errToObj(options?.message)})}date(message){return this._addCheck({kind:"date",message})}time(options){return typeof options=="string"?this._addCheck({kind:"time",precision:null,message:options}):this._addCheck({kind:"time",precision:typeof options?.precision>"u"?null:options?.precision,...errorUtil.errToObj(options?.message)})}duration(message){return this._addCheck({kind:"duration",...errorUtil.errToObj(message)})}regex(regex,message){return this._addCheck({kind:"regex",regex,...errorUtil.errToObj(message)})}includes(value,options){return this._addCheck({kind:"includes",value,position:options?.position,...errorUtil.errToObj(options?.message)})}startsWith(value,message){return this._addCheck({kind:"startsWith",value,...errorUtil.errToObj(message)})}endsWith(value,message){return this._addCheck({kind:"endsWith",value,...errorUtil.errToObj(message)})}min(minLength,message){return this._addCheck({kind:"min",value:minLength,...errorUtil.errToObj(message)})}max(maxLength,message){return this._addCheck({kind:"max",value:maxLength,...errorUtil.errToObj(message)})}length(len,message){return this._addCheck({kind:"length",value:len,...errorUtil.errToObj(message)})}nonempty(message){return this.min(1,errorUtil.errToObj(message))}trim(){return new _ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new _ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new _ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(ch=>ch.kind==="datetime")}get isDate(){return!!this._def.checks.find(ch=>ch.kind==="date")}get isTime(){return!!this._def.checks.find(ch=>ch.kind==="time")}get isDuration(){return!!this._def.checks.find(ch=>ch.kind==="duration")}get isEmail(){return!!this._def.checks.find(ch=>ch.kind==="email")}get isURL(){return!!this._def.checks.find(ch=>ch.kind==="url")}get isEmoji(){return!!this._def.checks.find(ch=>ch.kind==="emoji")}get isUUID(){return!!this._def.checks.find(ch=>ch.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(ch=>ch.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(ch=>ch.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(ch=>ch.kind==="cuid2")}get isULID(){return!!this._def.checks.find(ch=>ch.kind==="ulid")}get isIP(){return!!this._def.checks.find(ch=>ch.kind==="ip")}get isCIDR(){return!!this._def.checks.find(ch=>ch.kind==="cidr")}get isBase64(){return!!this._def.checks.find(ch=>ch.kind==="base64")}get isBase64url(){return!!this._def.checks.find(ch=>ch.kind==="base64url")}get minLength(){let min=null;for(let ch of this._def.checks)ch.kind==="min"&&(min===null||ch.value>min)&&(min=ch.value);return min}get maxLength(){let max=null;for(let ch of this._def.checks)ch.kind==="max"&&(max===null||ch.value<max)&&(max=ch.value);return max}};ZodString.create=params=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:params?.coerce??!1,...processCreateParams(params)});function floatSafeRemainder(val,step){let valDecCount=(val.toString().split(".")[1]||"").length,stepDecCount=(step.toString().split(".")[1]||"").length,decCount=valDecCount>stepDecCount?valDecCount:stepDecCount,valInt=Number.parseInt(val.toFixed(decCount).replace(".","")),stepInt=Number.parseInt(step.toFixed(decCount).replace(".",""));return valInt%stepInt/10**decCount}var ZodNumber=class _ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(input){if(this._def.coerce&&(input.data=Number(input.data)),this._getType(input)!==ZodParsedType.number){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:ctx2.parsedType}),INVALID}let ctx,status=new ParseStatus;for(let check of this._def.checks)check.kind==="int"?util.isInteger(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:check.message}),status.dirty()):check.kind==="min"?(check.inclusive?input.data<check.value:input.data<=check.value)&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"number",inclusive:check.inclusive,exact:!1,message:check.message}),status.dirty()):check.kind==="max"?(check.inclusive?input.data>check.value:input.data>=check.value)&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"number",inclusive:check.inclusive,exact:!1,message:check.message}),status.dirty()):check.kind==="multipleOf"?floatSafeRemainder(input.data,check.value)!==0&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check.value,message:check.message}),status.dirty()):check.kind==="finite"?Number.isFinite(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.not_finite,message:check.message}),status.dirty()):util.assertNever(check);return{status:status.value,value:input.data}}gte(value,message){return this.setLimit("min",value,!0,errorUtil.toString(message))}gt(value,message){return this.setLimit("min",value,!1,errorUtil.toString(message))}lte(value,message){return this.setLimit("max",value,!0,errorUtil.toString(message))}lt(value,message){return this.setLimit("max",value,!1,errorUtil.toString(message))}setLimit(kind,value,inclusive,message){return new _ZodNumber({...this._def,checks:[...this._def.checks,{kind,value,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check){return new _ZodNumber({...this._def,checks:[...this._def.checks,check]})}int(message){return this._addCheck({kind:"int",message:errorUtil.toString(message)})}positive(message){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(message)})}negative(message){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(message)})}nonpositive(message){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(message)})}nonnegative(message){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(message)})}multipleOf(value,message){return this._addCheck({kind:"multipleOf",value,message:errorUtil.toString(message)})}finite(message){return this._addCheck({kind:"finite",message:errorUtil.toString(message)})}safe(message){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(message)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(message)})}get minValue(){let min=null;for(let ch of this._def.checks)ch.kind==="min"&&(min===null||ch.value>min)&&(min=ch.value);return min}get maxValue(){let max=null;for(let ch of this._def.checks)ch.kind==="max"&&(max===null||ch.value<max)&&(max=ch.value);return max}get isInt(){return!!this._def.checks.find(ch=>ch.kind==="int"||ch.kind==="multipleOf"&&util.isInteger(ch.value))}get isFinite(){let max=null,min=null;for(let ch of this._def.checks){if(ch.kind==="finite"||ch.kind==="int"||ch.kind==="multipleOf")return!0;ch.kind==="min"?(min===null||ch.value>min)&&(min=ch.value):ch.kind==="max"&&(max===null||ch.value<max)&&(max=ch.value)}return Number.isFinite(min)&&Number.isFinite(max)}};ZodNumber.create=params=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:params?.coerce||!1,...processCreateParams(params)});var ZodBigInt=class _ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(input){if(this._def.coerce)try{input.data=BigInt(input.data)}catch{return this._getInvalidInput(input)}if(this._getType(input)!==ZodParsedType.bigint)return this._getInvalidInput(input);let ctx,status=new ParseStatus;for(let check of this._def.checks)check.kind==="min"?(check.inclusive?input.data<check.value:input.data<=check.value)&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,type:"bigint",minimum:check.value,inclusive:check.inclusive,message:check.message}),status.dirty()):check.kind==="max"?(check.inclusive?input.data>check.value:input.data>=check.value)&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,type:"bigint",maximum:check.value,inclusive:check.inclusive,message:check.message}),status.dirty()):check.kind==="multipleOf"?input.data%check.value!==BigInt(0)&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check.value,message:check.message}),status.dirty()):util.assertNever(check);return{status:status.value,value:input.data}}_getInvalidInput(input){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:ctx.parsedType}),INVALID}gte(value,message){return this.setLimit("min",value,!0,errorUtil.toString(message))}gt(value,message){return this.setLimit("min",value,!1,errorUtil.toString(message))}lte(value,message){return this.setLimit("max",value,!0,errorUtil.toString(message))}lt(value,message){return this.setLimit("max",value,!1,errorUtil.toString(message))}setLimit(kind,value,inclusive,message){return new _ZodBigInt({...this._def,checks:[...this._def.checks,{kind,value,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check){return new _ZodBigInt({...this._def,checks:[...this._def.checks,check]})}positive(message){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(message)})}negative(message){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(message)})}nonpositive(message){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(message)})}nonnegative(message){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(message)})}multipleOf(value,message){return this._addCheck({kind:"multipleOf",value,message:errorUtil.toString(message)})}get minValue(){let min=null;for(let ch of this._def.checks)ch.kind==="min"&&(min===null||ch.value>min)&&(min=ch.value);return min}get maxValue(){let max=null;for(let ch of this._def.checks)ch.kind==="max"&&(max===null||ch.value<max)&&(max=ch.value);return max}};ZodBigInt.create=params=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:params?.coerce??!1,...processCreateParams(params)});var ZodBoolean=class extends ZodType{_parse(input){if(this._def.coerce&&(input.data=!!input.data),this._getType(input)!==ZodParsedType.boolean){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:ctx.parsedType}),INVALID}return OK(input.data)}};ZodBoolean.create=params=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:params?.coerce||!1,...processCreateParams(params)});var ZodDate=class _ZodDate extends ZodType{_parse(input){if(this._def.coerce&&(input.data=new Date(input.data)),this._getType(input)!==ZodParsedType.date){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:ctx2.parsedType}),INVALID}if(Number.isNaN(input.data.getTime())){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_date}),INVALID}let status=new ParseStatus,ctx;for(let check of this._def.checks)check.kind==="min"?input.data.getTime()<check.value&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,message:check.message,inclusive:!0,exact:!1,minimum:check.value,type:"date"}),status.dirty()):check.kind==="max"?input.data.getTime()>check.value&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,message:check.message,inclusive:!0,exact:!1,maximum:check.value,type:"date"}),status.dirty()):util.assertNever(check);return{status:status.value,value:new Date(input.data.getTime())}}_addCheck(check){return new _ZodDate({...this._def,checks:[...this._def.checks,check]})}min(minDate,message){return this._addCheck({kind:"min",value:minDate.getTime(),message:errorUtil.toString(message)})}max(maxDate,message){return this._addCheck({kind:"max",value:maxDate.getTime(),message:errorUtil.toString(message)})}get minDate(){let min=null;for(let ch of this._def.checks)ch.kind==="min"&&(min===null||ch.value>min)&&(min=ch.value);return min!=null?new Date(min):null}get maxDate(){let max=null;for(let ch of this._def.checks)ch.kind==="max"&&(max===null||ch.value<max)&&(max=ch.value);return max!=null?new Date(max):null}};ZodDate.create=params=>new ZodDate({checks:[],coerce:params?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(params)});var ZodSymbol=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.symbol){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:ctx.parsedType}),INVALID}return OK(input.data)}};ZodSymbol.create=params=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(params)});var ZodUndefined=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.undefined){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:ctx.parsedType}),INVALID}return OK(input.data)}};ZodUndefined.create=params=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(params)});var ZodNull=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.null){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:ctx.parsedType}),INVALID}return OK(input.data)}};ZodNull.create=params=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(params)});var ZodAny=class extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(input){return OK(input.data)}};ZodAny.create=params=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(params)});var ZodUnknown=class extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(input){return OK(input.data)}};ZodUnknown.create=params=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(params)});var ZodNever=class extends ZodType{_parse(input){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:ctx.parsedType}),INVALID}};ZodNever.create=params=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(params)});var ZodVoid=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.undefined){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:ctx.parsedType}),INVALID}return OK(input.data)}};ZodVoid.create=params=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(params)});var ZodArray=class _ZodArray extends ZodType{_parse(input){let{ctx,status}=this._processInputParams(input),def=this._def;if(ctx.parsedType!==ZodParsedType.array)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:ctx.parsedType}),INVALID;if(def.exactLength!==null){let tooBig=ctx.data.length>def.exactLength.value,tooSmall=ctx.data.length<def.exactLength.value;(tooBig||tooSmall)&&(addIssueToContext(ctx,{code:tooBig?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:tooSmall?def.exactLength.value:void 0,maximum:tooBig?def.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:def.exactLength.message}),status.dirty())}if(def.minLength!==null&&ctx.data.length<def.minLength.value&&(addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:def.minLength.value,type:"array",inclusive:!0,exact:!1,message:def.minLength.message}),status.dirty()),def.maxLength!==null&&ctx.data.length>def.maxLength.value&&(addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:def.maxLength.value,type:"array",inclusive:!0,exact:!1,message:def.maxLength.message}),status.dirty()),ctx.common.async)return Promise.all([...ctx.data].map((item,i)=>def.type._parseAsync(new ParseInputLazyPath(ctx,item,ctx.path,i)))).then(result2=>ParseStatus.mergeArray(status,result2));let result=[...ctx.data].map((item,i)=>def.type._parseSync(new ParseInputLazyPath(ctx,item,ctx.path,i)));return ParseStatus.mergeArray(status,result)}get element(){return this._def.type}min(minLength,message){return new _ZodArray({...this._def,minLength:{value:minLength,message:errorUtil.toString(message)}})}max(maxLength,message){return new _ZodArray({...this._def,maxLength:{value:maxLength,message:errorUtil.toString(message)}})}length(len,message){return new _ZodArray({...this._def,exactLength:{value:len,message:errorUtil.toString(message)}})}nonempty(message){return this.min(1,message)}};ZodArray.create=(schema,params)=>new ZodArray({type:schema,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(params)});function deepPartialify(schema){if(schema instanceof ZodObject){let newShape={};for(let key in schema.shape){let fieldSchema=schema.shape[key];newShape[key]=ZodOptional.create(deepPartialify(fieldSchema))}return new ZodObject({...schema._def,shape:()=>newShape})}else return schema instanceof ZodArray?new ZodArray({...schema._def,type:deepPartialify(schema.element)}):schema instanceof ZodOptional?ZodOptional.create(deepPartialify(schema.unwrap())):schema instanceof ZodNullable?ZodNullable.create(deepPartialify(schema.unwrap())):schema instanceof ZodTuple?ZodTuple.create(schema.items.map(item=>deepPartialify(item))):schema}var ZodObject=class _ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let shape=this._def.shape(),keys=util.objectKeys(shape);return this._cached={shape,keys},this._cached}_parse(input){if(this._getType(input)!==ZodParsedType.object){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx2.parsedType}),INVALID}let{status,ctx}=this._processInputParams(input),{shape,keys:shapeKeys}=this._getCached(),extraKeys=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(let key in ctx.data)shapeKeys.includes(key)||extraKeys.push(key);let pairs=[];for(let key of shapeKeys){let keyValidator=shape[key],value=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:keyValidator._parse(new ParseInputLazyPath(ctx,value,ctx.path,key)),alwaysSet:key in ctx.data})}if(this._def.catchall instanceof ZodNever){let unknownKeys=this._def.unknownKeys;if(unknownKeys==="passthrough")for(let key of extraKeys)pairs.push({key:{status:"valid",value:key},value:{status:"valid",value:ctx.data[key]}});else if(unknownKeys==="strict")extraKeys.length>0&&(addIssueToContext(ctx,{code:ZodIssueCode.unrecognized_keys,keys:extraKeys}),status.dirty());else if(unknownKeys!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let catchall=this._def.catchall;for(let key of extraKeys){let value=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:catchall._parse(new ParseInputLazyPath(ctx,value,ctx.path,key)),alwaysSet:key in ctx.data})}}return ctx.common.async?Promise.resolve().then(async()=>{let syncPairs=[];for(let pair of pairs){let key=await pair.key,value=await pair.value;syncPairs.push({key,value,alwaysSet:pair.alwaysSet})}return syncPairs}).then(syncPairs=>ParseStatus.mergeObjectSync(status,syncPairs)):ParseStatus.mergeObjectSync(status,pairs)}get shape(){return this._def.shape()}strict(message){return errorUtil.errToObj,new _ZodObject({...this._def,unknownKeys:"strict",...message!==void 0?{errorMap:(issue,ctx)=>{let defaultError=this._def.errorMap?.(issue,ctx).message??ctx.defaultError;return issue.code==="unrecognized_keys"?{message:errorUtil.errToObj(message).message??defaultError}:{message:defaultError}}}:{}})}strip(){return new _ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new _ZodObject({...this._def,unknownKeys:"passthrough"})}extend(augmentation){return new _ZodObject({...this._def,shape:()=>({...this._def.shape(),...augmentation})})}merge(merging){return new _ZodObject({unknownKeys:merging._def.unknownKeys,catchall:merging._def.catchall,shape:()=>({...this._def.shape(),...merging._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(key,schema){return this.augment({[key]:schema})}catchall(index){return new _ZodObject({...this._def,catchall:index})}pick(mask){let shape={};for(let key of util.objectKeys(mask))mask[key]&&this.shape[key]&&(shape[key]=this.shape[key]);return new _ZodObject({...this._def,shape:()=>shape})}omit(mask){let shape={};for(let key of util.objectKeys(this.shape))mask[key]||(shape[key]=this.shape[key]);return new _ZodObject({...this._def,shape:()=>shape})}deepPartial(){return deepPartialify(this)}partial(mask){let newShape={};for(let key of util.objectKeys(this.shape)){let fieldSchema=this.shape[key];mask&&!mask[key]?newShape[key]=fieldSchema:newShape[key]=fieldSchema.optional()}return new _ZodObject({...this._def,shape:()=>newShape})}required(mask){let newShape={};for(let key of util.objectKeys(this.shape))if(mask&&!mask[key])newShape[key]=this.shape[key];else{let newField=this.shape[key];for(;newField instanceof ZodOptional;)newField=newField._def.innerType;newShape[key]=newField}return new _ZodObject({...this._def,shape:()=>newShape})}keyof(){return createZodEnum(util.objectKeys(this.shape))}};ZodObject.create=(shape,params)=>new ZodObject({shape:()=>shape,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)});ZodObject.strictCreate=(shape,params)=>new ZodObject({shape:()=>shape,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)});ZodObject.lazycreate=(shape,params)=>new ZodObject({shape,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)});var ZodUnion=class extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),options=this._def.options;function handleResults(results){for(let result of results)if(result.result.status==="valid")return result.result;for(let result of results)if(result.result.status==="dirty")return ctx.common.issues.push(...result.ctx.common.issues),result.result;let unionErrors=results.map(result=>new ZodError(result.ctx.common.issues));return addIssueToContext(ctx,{code:ZodIssueCode.invalid_union,unionErrors}),INVALID}if(ctx.common.async)return Promise.all(options.map(async option=>{let childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null};return{result:await option._parseAsync({data:ctx.data,path:ctx.path,parent:childCtx}),ctx:childCtx}})).then(handleResults);{let dirty,issues=[];for(let option of options){let childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null},result=option._parseSync({data:ctx.data,path:ctx.path,parent:childCtx});if(result.status==="valid")return result;result.status==="dirty"&&!dirty&&(dirty={result,ctx:childCtx}),childCtx.common.issues.length&&issues.push(childCtx.common.issues)}if(dirty)return ctx.common.issues.push(...dirty.ctx.common.issues),dirty.result;let unionErrors=issues.map(issues2=>new ZodError(issues2));return addIssueToContext(ctx,{code:ZodIssueCode.invalid_union,unionErrors}),INVALID}}get options(){return this._def.options}};ZodUnion.create=(types,params)=>new ZodUnion({options:types,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(params)});var getDiscriminator=type=>type instanceof ZodLazy?getDiscriminator(type.schema):type instanceof ZodEffects?getDiscriminator(type.innerType()):type instanceof ZodLiteral?[type.value]:type instanceof ZodEnum?type.options:type instanceof ZodNativeEnum?util.objectValues(type.enum):type instanceof ZodDefault?getDiscriminator(type._def.innerType):type instanceof ZodUndefined?[void 0]:type instanceof ZodNull?[null]:type instanceof ZodOptional?[void 0,...getDiscriminator(type.unwrap())]:type instanceof ZodNullable?[null,...getDiscriminator(type.unwrap())]:type instanceof ZodBranded||type instanceof ZodReadonly?getDiscriminator(type.unwrap()):type instanceof ZodCatch?getDiscriminator(type._def.innerType):[],ZodDiscriminatedUnion=class _ZodDiscriminatedUnion extends ZodType{_parse(input){let{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.object)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx.parsedType}),INVALID;let discriminator=this.discriminator,discriminatorValue=ctx.data[discriminator],option=this.optionsMap.get(discriminatorValue);return option?ctx.common.async?option._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}):option._parseSync({data:ctx.data,path:ctx.path,parent:ctx}):(addIssueToContext(ctx,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[discriminator]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(discriminator,options,params){let optionsMap=new Map;for(let type of options){let discriminatorValues=getDiscriminator(type.shape[discriminator]);if(!discriminatorValues.length)throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);for(let value of discriminatorValues){if(optionsMap.has(value))throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);optionsMap.set(value,type)}}return new _ZodDiscriminatedUnion({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator,options,optionsMap,...processCreateParams(params)})}};function mergeValues(a,b){let aType=getParsedType(a),bType=getParsedType(b);if(a===b)return{valid:!0,data:a};if(aType===ZodParsedType.object&&bType===ZodParsedType.object){let bKeys=util.objectKeys(b),sharedKeys=util.objectKeys(a).filter(key=>bKeys.indexOf(key)!==-1),newObj={...a,...b};for(let key of sharedKeys){let sharedValue=mergeValues(a[key],b[key]);if(!sharedValue.valid)return{valid:!1};newObj[key]=sharedValue.data}return{valid:!0,data:newObj}}else if(aType===ZodParsedType.array&&bType===ZodParsedType.array){if(a.length!==b.length)return{valid:!1};let newArray=[];for(let index=0;index<a.length;index++){let itemA=a[index],itemB=b[index],sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid)return{valid:!1};newArray.push(sharedValue.data)}return{valid:!0,data:newArray}}else return aType===ZodParsedType.date&&bType===ZodParsedType.date&&+a==+b?{valid:!0,data:a}:{valid:!1}}var ZodIntersection=class extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input),handleParsed=(parsedLeft,parsedRight)=>{if(isAborted(parsedLeft)||isAborted(parsedRight))return INVALID;let merged=mergeValues(parsedLeft.value,parsedRight.value);return merged.valid?((isDirty(parsedLeft)||isDirty(parsedRight))&&status.dirty(),{status:status.value,value:merged.data}):(addIssueToContext(ctx,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return ctx.common.async?Promise.all([this._def.left._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}),this._def.right._parseAsync({data:ctx.data,path:ctx.path,parent:ctx})]).then(([left,right])=>handleParsed(left,right)):handleParsed(this._def.left._parseSync({data:ctx.data,path:ctx.path,parent:ctx}),this._def.right._parseSync({data:ctx.data,path:ctx.path,parent:ctx}))}};ZodIntersection.create=(left,right,params)=>new ZodIntersection({left,right,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(params)});var ZodTuple=class _ZodTuple extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.array)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:ctx.parsedType}),INVALID;if(ctx.data.length<this._def.items.length)return addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&ctx.data.length>this._def.items.length&&(addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),status.dirty());let items=[...ctx.data].map((item,itemIndex)=>{let schema=this._def.items[itemIndex]||this._def.rest;return schema?schema._parse(new ParseInputLazyPath(ctx,item,ctx.path,itemIndex)):null}).filter(x=>!!x);return ctx.common.async?Promise.all(items).then(results=>ParseStatus.mergeArray(status,results)):ParseStatus.mergeArray(status,items)}get items(){return this._def.items}rest(rest){return new _ZodTuple({...this._def,rest})}};ZodTuple.create=(schemas,params)=>{if(!Array.isArray(schemas))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:schemas,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(params)})};var ZodRecord=class _ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.object)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx.parsedType}),INVALID;let pairs=[],keyType=this._def.keyType,valueType=this._def.valueType;for(let key in ctx.data)pairs.push({key:keyType._parse(new ParseInputLazyPath(ctx,key,ctx.path,key)),value:valueType._parse(new ParseInputLazyPath(ctx,ctx.data[key],ctx.path,key)),alwaysSet:key in ctx.data});return ctx.common.async?ParseStatus.mergeObjectAsync(status,pairs):ParseStatus.mergeObjectSync(status,pairs)}get element(){return this._def.valueType}static create(first,second,third){return second instanceof ZodType?new _ZodRecord({keyType:first,valueType:second,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(third)}):new _ZodRecord({keyType:ZodString.create(),valueType:first,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(second)})}},ZodMap=class extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.map)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:ctx.parsedType}),INVALID;let keyType=this._def.keyType,valueType=this._def.valueType,pairs=[...ctx.data.entries()].map(([key,value],index)=>({key:keyType._parse(new ParseInputLazyPath(ctx,key,ctx.path,[index,"key"])),value:valueType._parse(new ParseInputLazyPath(ctx,value,ctx.path,[index,"value"]))}));if(ctx.common.async){let finalMap=new Map;return Promise.resolve().then(async()=>{for(let pair of pairs){let key=await pair.key,value=await pair.value;if(key.status==="aborted"||value.status==="aborted")return INVALID;(key.status==="dirty"||value.status==="dirty")&&status.dirty(),finalMap.set(key.value,value.value)}return{status:status.value,value:finalMap}})}else{let finalMap=new Map;for(let pair of pairs){let key=pair.key,value=pair.value;if(key.status==="aborted"||value.status==="aborted")return INVALID;(key.status==="dirty"||value.status==="dirty")&&status.dirty(),finalMap.set(key.value,value.value)}return{status:status.value,value:finalMap}}}};ZodMap.create=(keyType,valueType,params)=>new ZodMap({valueType,keyType,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(params)});var ZodSet=class _ZodSet extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.set)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:ctx.parsedType}),INVALID;let def=this._def;def.minSize!==null&&ctx.data.size<def.minSize.value&&(addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:def.minSize.value,type:"set",inclusive:!0,exact:!1,message:def.minSize.message}),status.dirty()),def.maxSize!==null&&ctx.data.size>def.maxSize.value&&(addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:def.maxSize.value,type:"set",inclusive:!0,exact:!1,message:def.maxSize.message}),status.dirty());let valueType=this._def.valueType;function finalizeSet(elements2){let parsedSet=new Set;for(let element of elements2){if(element.status==="aborted")return INVALID;element.status==="dirty"&&status.dirty(),parsedSet.add(element.value)}return{status:status.value,value:parsedSet}}let elements=[...ctx.data.values()].map((item,i)=>valueType._parse(new ParseInputLazyPath(ctx,item,ctx.path,i)));return ctx.common.async?Promise.all(elements).then(elements2=>finalizeSet(elements2)):finalizeSet(elements)}min(minSize,message){return new _ZodSet({...this._def,minSize:{value:minSize,message:errorUtil.toString(message)}})}max(maxSize,message){return new _ZodSet({...this._def,maxSize:{value:maxSize,message:errorUtil.toString(message)}})}size(size,message){return this.min(size,message).max(size,message)}nonempty(message){return this.min(1,message)}};ZodSet.create=(valueType,params)=>new ZodSet({valueType,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(params)});var ZodFunction=class _ZodFunction extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(input){let{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.function)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:ctx.parsedType}),INVALID;function makeArgsIssue(args,error){return makeIssue({data:args,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,getErrorMap(),en_default].filter(x=>!!x),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:error}})}function makeReturnsIssue(returns,error){return makeIssue({data:returns,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,getErrorMap(),en_default].filter(x=>!!x),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:error}})}let params={errorMap:ctx.common.contextualErrorMap},fn=ctx.data;if(this._def.returns instanceof ZodPromise){let me=this;return OK(async function(...args){let error=new ZodError([]),parsedArgs=await me._def.args.parseAsync(args,params).catch(e=>{throw error.addIssue(makeArgsIssue(args,e)),error}),result=await Reflect.apply(fn,this,parsedArgs);return await me._def.returns._def.type.parseAsync(result,params).catch(e=>{throw error.addIssue(makeReturnsIssue(result,e)),error})})}else{let me=this;return OK(function(...args){let parsedArgs=me._def.args.safeParse(args,params);if(!parsedArgs.success)throw new ZodError([makeArgsIssue(args,parsedArgs.error)]);let result=Reflect.apply(fn,this,parsedArgs.data),parsedReturns=me._def.returns.safeParse(result,params);if(!parsedReturns.success)throw new ZodError([makeReturnsIssue(result,parsedReturns.error)]);return parsedReturns.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...items){return new _ZodFunction({...this._def,args:ZodTuple.create(items).rest(ZodUnknown.create())})}returns(returnType){return new _ZodFunction({...this._def,returns:returnType})}implement(func){return this.parse(func)}strictImplement(func){return this.parse(func)}static create(args,returns,params){return new _ZodFunction({args:args||ZodTuple.create([]).rest(ZodUnknown.create()),returns:returns||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(params)})}},ZodLazy=class extends ZodType{get schema(){return this._def.getter()}_parse(input){let{ctx}=this._processInputParams(input);return this._def.getter()._parse({data:ctx.data,path:ctx.path,parent:ctx})}};ZodLazy.create=(getter,params)=>new ZodLazy({getter,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(params)});var ZodLiteral=class extends ZodType{_parse(input){if(input.data!==this._def.value){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:input.data}}get value(){return this._def.value}};ZodLiteral.create=(value,params)=>new ZodLiteral({value,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(params)});function createZodEnum(values,params){return new ZodEnum({values,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(params)})}var ZodEnum=class _ZodEnum extends ZodType{_parse(input){if(typeof input.data!="string"){let ctx=this._getOrReturnCtx(input),expectedValues=this._def.values;return addIssueToContext(ctx,{expected:util.joinValues(expectedValues),received:ctx.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(input.data)){let ctx=this._getOrReturnCtx(input),expectedValues=this._def.values;return addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_enum_value,options:expectedValues}),INVALID}return OK(input.data)}get options(){return this._def.values}get enum(){let enumValues={};for(let val of this._def.values)enumValues[val]=val;return enumValues}get Values(){let enumValues={};for(let val of this._def.values)enumValues[val]=val;return enumValues}get Enum(){let enumValues={};for(let val of this._def.values)enumValues[val]=val;return enumValues}extract(values,newDef=this._def){return _ZodEnum.create(values,{...this._def,...newDef})}exclude(values,newDef=this._def){return _ZodEnum.create(this.options.filter(opt=>!values.includes(opt)),{...this._def,...newDef})}};ZodEnum.create=createZodEnum;var ZodNativeEnum=class extends ZodType{_parse(input){let nativeEnumValues=util.getValidEnumValues(this._def.values),ctx=this._getOrReturnCtx(input);if(ctx.parsedType!==ZodParsedType.string&&ctx.parsedType!==ZodParsedType.number){let expectedValues=util.objectValues(nativeEnumValues);return addIssueToContext(ctx,{expected:util.joinValues(expectedValues),received:ctx.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(input.data)){let expectedValues=util.objectValues(nativeEnumValues);return addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_enum_value,options:expectedValues}),INVALID}return OK(input.data)}get enum(){return this._def.values}};ZodNativeEnum.create=(values,params)=>new ZodNativeEnum({values,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(params)});var ZodPromise=class extends ZodType{unwrap(){return this._def.type}_parse(input){let{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.promise&&ctx.common.async===!1)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:ctx.parsedType}),INVALID;let promisified=ctx.parsedType===ZodParsedType.promise?ctx.data:Promise.resolve(ctx.data);return OK(promisified.then(data=>this._def.type.parseAsync(data,{path:ctx.path,errorMap:ctx.common.contextualErrorMap})))}};ZodPromise.create=(schema,params)=>new ZodPromise({type:schema,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(params)});var ZodEffects=class extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(input){let{status,ctx}=this._processInputParams(input),effect=this._def.effect||null,checkCtx={addIssue:arg=>{addIssueToContext(ctx,arg),arg.fatal?status.abort():status.dirty()},get path(){return ctx.path}};if(checkCtx.addIssue=checkCtx.addIssue.bind(checkCtx),effect.type==="preprocess"){let processed=effect.transform(ctx.data,checkCtx);if(ctx.common.async)return Promise.resolve(processed).then(async processed2=>{if(status.value==="aborted")return INVALID;let result=await this._def.schema._parseAsync({data:processed2,path:ctx.path,parent:ctx});return result.status==="aborted"?INVALID:result.status==="dirty"?DIRTY(result.value):status.value==="dirty"?DIRTY(result.value):result});{if(status.value==="aborted")return INVALID;let result=this._def.schema._parseSync({data:processed,path:ctx.path,parent:ctx});return result.status==="aborted"?INVALID:result.status==="dirty"?DIRTY(result.value):status.value==="dirty"?DIRTY(result.value):result}}if(effect.type==="refinement"){let executeRefinement=acc=>{let result=effect.refinement(acc,checkCtx);if(ctx.common.async)return Promise.resolve(result);if(result instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return acc};if(ctx.common.async===!1){let inner=this._def.schema._parseSync({data:ctx.data,path:ctx.path,parent:ctx});return inner.status==="aborted"?INVALID:(inner.status==="dirty"&&status.dirty(),executeRefinement(inner.value),{status:status.value,value:inner.value})}else return this._def.schema._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}).then(inner=>inner.status==="aborted"?INVALID:(inner.status==="dirty"&&status.dirty(),executeRefinement(inner.value).then(()=>({status:status.value,value:inner.value}))))}if(effect.type==="transform")if(ctx.common.async===!1){let base=this._def.schema._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(!isValid(base))return INVALID;let result=effect.transform(base.value,checkCtx);if(result instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:status.value,value:result}}else return this._def.schema._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}).then(base=>isValid(base)?Promise.resolve(effect.transform(base.value,checkCtx)).then(result=>({status:status.value,value:result})):INVALID);util.assertNever(effect)}};ZodEffects.create=(schema,effect,params)=>new ZodEffects({schema,typeName:ZodFirstPartyTypeKind.ZodEffects,effect,...processCreateParams(params)});ZodEffects.createWithPreprocess=(preprocess,schema,params)=>new ZodEffects({schema,effect:{type:"preprocess",transform:preprocess},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(params)});var ZodOptional=class extends ZodType{_parse(input){return this._getType(input)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(input)}unwrap(){return this._def.innerType}};ZodOptional.create=(type,params)=>new ZodOptional({innerType:type,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(params)});var ZodNullable=class extends ZodType{_parse(input){return this._getType(input)===ZodParsedType.null?OK(null):this._def.innerType._parse(input)}unwrap(){return this._def.innerType}};ZodNullable.create=(type,params)=>new ZodNullable({innerType:type,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(params)});var ZodDefault=class extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),data=ctx.data;return ctx.parsedType===ZodParsedType.undefined&&(data=this._def.defaultValue()),this._def.innerType._parse({data,path:ctx.path,parent:ctx})}removeDefault(){return this._def.innerType}};ZodDefault.create=(type,params)=>new ZodDefault({innerType:type,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof params.default=="function"?params.default:()=>params.default,...processCreateParams(params)});var ZodCatch=class extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),newCtx={...ctx,common:{...ctx.common,issues:[]}},result=this._def.innerType._parse({data:newCtx.data,path:newCtx.path,parent:{...newCtx}});return isAsync(result)?result.then(result2=>({status:"valid",value:result2.status==="valid"?result2.value:this._def.catchValue({get error(){return new ZodError(newCtx.common.issues)},input:newCtx.data})})):{status:"valid",value:result.status==="valid"?result.value:this._def.catchValue({get error(){return new ZodError(newCtx.common.issues)},input:newCtx.data})}}removeCatch(){return this._def.innerType}};ZodCatch.create=(type,params)=>new ZodCatch({innerType:type,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof params.catch=="function"?params.catch:()=>params.catch,...processCreateParams(params)});var ZodNaN=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.nan){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:ctx.parsedType}),INVALID}return{status:"valid",value:input.data}}};ZodNaN.create=params=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(params)});var BRAND=Symbol("zod_brand"),ZodBranded=class extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),data=ctx.data;return this._def.type._parse({data,path:ctx.path,parent:ctx})}unwrap(){return this._def.type}},ZodPipeline=class _ZodPipeline extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.common.async)return(async()=>{let inResult=await this._def.in._parseAsync({data:ctx.data,path:ctx.path,parent:ctx});return inResult.status==="aborted"?INVALID:inResult.status==="dirty"?(status.dirty(),DIRTY(inResult.value)):this._def.out._parseAsync({data:inResult.value,path:ctx.path,parent:ctx})})();{let inResult=this._def.in._parseSync({data:ctx.data,path:ctx.path,parent:ctx});return inResult.status==="aborted"?INVALID:inResult.status==="dirty"?(status.dirty(),{status:"dirty",value:inResult.value}):this._def.out._parseSync({data:inResult.value,path:ctx.path,parent:ctx})}}static create(a,b){return new _ZodPipeline({in:a,out:b,typeName:ZodFirstPartyTypeKind.ZodPipeline})}},ZodReadonly=class extends ZodType{_parse(input){let result=this._def.innerType._parse(input),freeze=data=>(isValid(data)&&(data.value=Object.freeze(data.value)),data);return isAsync(result)?result.then(data=>freeze(data)):freeze(result)}unwrap(){return this._def.innerType}};ZodReadonly.create=(type,params)=>new ZodReadonly({innerType:type,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(params)});function cleanParams(params,data){let p=typeof params=="function"?params(data):typeof params=="string"?{message:params}:params;return typeof p=="string"?{message:p}:p}function custom(check,_params={},fatal){return check?ZodAny.create().superRefine((data,ctx)=>{let r=check(data);if(r instanceof Promise)return r.then(r2=>{if(!r2){let params=cleanParams(_params,data),_fatal=params.fatal??fatal??!0;ctx.addIssue({code:"custom",...params,fatal:_fatal})}});if(!r){let params=cleanParams(_params,data),_fatal=params.fatal??fatal??!0;ctx.addIssue({code:"custom",...params,fatal:_fatal})}}):ZodAny.create()}var late={object:ZodObject.lazycreate},ZodFirstPartyTypeKind;(function(ZodFirstPartyTypeKind2){ZodFirstPartyTypeKind2.ZodString="ZodString",ZodFirstPartyTypeKind2.ZodNumber="ZodNumber",ZodFirstPartyTypeKind2.ZodNaN="ZodNaN",ZodFirstPartyTypeKind2.ZodBigInt="ZodBigInt",ZodFirstPartyTypeKind2.ZodBoolean="ZodBoolean",ZodFirstPartyTypeKind2.ZodDate="ZodDate",ZodFirstPartyTypeKind2.ZodSymbol="ZodSymbol",ZodFirstPartyTypeKind2.ZodUndefined="ZodUndefined",ZodFirstPartyTypeKind2.ZodNull="ZodNull",ZodFirstPartyTypeKind2.ZodAny="ZodAny",ZodFirstPartyTypeKind2.ZodUnknown="ZodUnknown",ZodFirstPartyTypeKind2.ZodNever="ZodNever",ZodFirstPartyTypeKind2.ZodVoid="ZodVoid",ZodFirstPartyTypeKind2.ZodArray="ZodArray",ZodFirstPartyTypeKind2.ZodObject="ZodObject",ZodFirstPartyTypeKind2.ZodUnion="ZodUnion",ZodFirstPartyTypeKind2.ZodDiscriminatedUnion="ZodDiscriminatedUnion",ZodFirstPartyTypeKind2.ZodIntersection="ZodIntersection",ZodFirstPartyTypeKind2.ZodTuple="ZodTuple",ZodFirstPartyTypeKind2.ZodRecord="ZodRecord",ZodFirstPartyTypeKind2.ZodMap="ZodMap",ZodFirstPartyTypeKind2.ZodSet="ZodSet",ZodFirstPartyTypeKind2.ZodFunction="ZodFunction",ZodFirstPartyTypeKind2.ZodLazy="ZodLazy",ZodFirstPartyTypeKind2.ZodLiteral="ZodLiteral",ZodFirstPartyTypeKind2.ZodEnum="ZodEnum",ZodFirstPartyTypeKind2.ZodEffects="ZodEffects",ZodFirstPartyTypeKind2.ZodNativeEnum="ZodNativeEnum",ZodFirstPartyTypeKind2.ZodOptional="ZodOptional",ZodFirstPartyTypeKind2.ZodNullable="ZodNullable",ZodFirstPartyTypeKind2.ZodDefault="ZodDefault",ZodFirstPartyTypeKind2.ZodCatch="ZodCatch",ZodFirstPartyTypeKind2.ZodPromise="ZodPromise",ZodFirstPartyTypeKind2.ZodBranded="ZodBranded",ZodFirstPartyTypeKind2.ZodPipeline="ZodPipeline",ZodFirstPartyTypeKind2.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));var instanceOfType=(cls,params={message:`Input not instance of ${cls.name}`})=>custom(data=>data instanceof cls,params),stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ostring=()=>stringType().optional(),onumber=()=>numberType().optional(),oboolean=()=>booleanType().optional(),coerce={string:arg=>ZodString.create({...arg,coerce:!0}),number:arg=>ZodNumber.create({...arg,coerce:!0}),boolean:arg=>ZodBoolean.create({...arg,coerce:!0}),bigint:arg=>ZodBigInt.create({...arg,coerce:!0}),date:arg=>ZodDate.create({...arg,coerce:!0})};var NEVER=INVALID;async function prepareFunctions(options){await traceOperation(options.trace,"vc.cli.describe.validate_output",()=>validateBuildOutput(options));let config=await traceOperation(options.trace,"vc.cli.describe.read_config",()=>getBuildOutputConfigOrThrow(options.outputDir));if("daemons"in config&&config.daemons&&Object.keys(config.daemons).length)throw new DescribeError("unsupported_output","This build contains daemons. Describe supports native AWS Lambda functions only.");if(!serviceInventorySchema.safeParse(config.experimentalServicesV2??{}).success)throw new DescribeError("invalid_build_output","Invalid service inventory in config.json. Rebuild the service outputs before running describe.");let scopes=[{directory:"",config}];for(let entry of getServiceOutputEntries(config)){if(entry.service.bindings?.length)throw new DescribeError("unsupported_output","This build contains service bindings, which cannot be provisioned as AWS Lambda functions. Remove the bindings and rebuild before running describe.");let serviceConfig=await readServiceOutputConfig(options.outputDir,entry).catch(error=>{throw error instanceof import_build_utils8.NowBuildError&&error.code==="MISSING_SERVICE_BUILD_OUTPUT"?new DescribeError("invalid_build_output",`Service "${entry.name}" is missing build output at ".vercel/output/services/${entry.name}/config.json". Rebuild the service before running describe.`):error});serviceConfig&&scopes.push({config:serviceConfig,directory:entry.directory,service:entry.name})}let groups=[],paths=new Set;for(let scope of scopes){let functions=await traceOperation(options.trace,"vc.cli.describe.read_functions",()=>readFunctions({outputDir:join9(options.outputDir,scope.directory),repoRootPath:options.repoRootPath,prebuilt:!0}));if(functions.edgeFunctions.size)throw new DescribeError("unsupported_output","This build contains Edge Functions, which cannot be provisioned as AWS Lambda functions.");await traceOperation(options.trace,"vc.cli.describe.group_functions",()=>groupBundleableLambdas({functions,options:{}}));let scopeGroups=new Map,middlewarePaths=getMiddlewareRouting({routes:scope.config.routes??[],functions});for(let output of iterateNativeFunctionOutputs(functions)){let lambda=output.lambda,directory=join9(scope.directory,"functions",`${output.path}.func`),functionConfig=JSON.parse(await readFile3(join9(options.outputDir,directory,".vc-config.json"),"utf8"));if(lambda.runtime==="container"||functionConfig.hive||functionConfig.affinity)throw new DescribeError("unsupported_output","This build contains container or Hive functions. Describe supports native AWS Lambda functions only.");let sourcePath=getFunctionSourcePath({output:{path:output.path},service:scope.service});if(paths.has(sourcePath))throw new DescribeError("invalid_build_output",`Multiple function outputs use "${sourcePath}". Rename the conflicting output and rebuild before running describe.`);paths.add(sourcePath);let outputs=scopeGroups.get(lambda)??[];scopeGroups.set(lambda,outputs),outputs.push({sourceKind:output.prerender?"prerender":"lambda",middleware:output.prerender===void 0&&middlewarePaths.has(output.path)?{}:void 0,path:sourcePath,directory,service:scope.service})}for(let[lambda,outputs]of scopeGroups)groups.push({lambda,outputs})}return{groups,services:config.services}}var serviceInventorySchema=external_exports.record(external_exports.string().regex(new RegExp(import_build_utils8.SERVICE_NAME_PATTERN)),external_exports.object({root:external_exports.string().optional(),bindings:external_exports.array(external_exports.unknown()).optional()}));import{writeFile}from"node:fs/promises";var descriptorSchema=external_exports.object({Architectures:external_exports.array(external_exports.string()).optional(),Environment:external_exports.object({Variables:external_exports.record(external_exports.string())}),EphemeralStorage:external_exports.object({Size:external_exports.number()}).optional(),FunctionName:external_exports.string().min(1),Handler:external_exports.string(),Layers:external_exports.array(external_exports.string()),MemorySize:external_exports.number(),Region:external_exports.string().min(1),ResolvableLayers:external_exports.record(external_exports.object({url:external_exports.string()})),Runtime:external_exports.string(),Tags:external_exports.record(external_exports.string()),Timeout:external_exports.number().optional()});async function describeFunctions(client,params){let functions=await client.withTrace("vc.cli.describe.prepare_functions",trace=>prepareFunctions({trace,directory:params.directory,repoRootPath:params.repoRootPath,outputDir:params.outputDir})),buildEnv=await client.withTrace("vc.cli.describe.build_env",async()=>external_exports.object({VERCEL_ENCRYPTED_ENV_FILENAME:external_exports.string().min(1),VERCEL_ENCRYPTED_ENV_CONTENT:external_exports.string().min(1)}).parse((await fetchDeploymentBuildEnv(client,params.deploymentId,{quiet:params.quiet})).buildEnv)),lambdas=(await Promise.all(functions.groups.map(({lambda,outputs})=>client.withTrace("vc.cli.describe.function",async()=>{lambda.files=await client.withTrace("vc.cli.describe.hydrate",()=>hydrateLambdaFiles(lambda,{filename:buildEnv.VERCEL_ENCRYPTED_ENV_FILENAME,contentBase64:buildEnv.VERCEL_ENCRYPTED_ENV_CONTENT}));let zip=await client.withTrace("vc.cli.describe.zip",()=>lambda.createZip()),bytes2=new Uint8Array(zip.buffer,zip.byteOffset,zip.byteLength),digest=await client.withTrace("vc.cli.describe.hash_zip",()=>createHash2("sha256").update(bytes2).digest("hex"),{byte_count:String(bytes2.length)});await client.withTrace("vc.cli.describe.write_zip",()=>writeFile(join10(params.zipDirectory,`${digest}.zip`),bytes2,{mode:384}),{byte_count:String(bytes2.length)});let config=await client.withTrace("vc.cli.describe.configuration",()=>getFunctionConfig(lambda)),input={...config,framework:config.framework&&{slug:config.framework.slug},digest,size:bytes2.length};return outputs.map(output=>({...output,lambda:input}))},{function_count:"1"})))).flat(),{descriptors}=await client.withTrace("vc.cli.describe.descriptors",async()=>external_exports.object({descriptors:external_exports.array(external_exports.array(descriptorSchema).min(1))}).parse(await client.fetch(`/v2/deployments/${params.deploymentId}/builds/function-descriptors`,{method:"POST",body:JSON.stringify({lambdas:lambdas.map(output=>({lambda:output.lambda,path:output.path,service:output.service,sourceKind:output.sourceKind,middleware:output.middleware})),services:functions.services}),headers:{"content-type":"application/json"},accountId:params.teamId,retry:{retries:0}})),{function_count:String(lambdas.length)});if(descriptors.length!==lambdas.length)throw new Error("Descriptor count does not match function outputs");return lambdas.map(({path:path2,directory,lambda},index)=>{let regional=descriptors[index];if(new Set(regional.map(d=>d.FunctionName)).size!==1)throw new Error("Inconsistent regional function name");return{path:path2,directory,digest:lambda.digest,size:lambda.size,regional}})}import{isDeepStrictEqual}from"node:util";import{join as join12}from"node:path";import{mkdir as mkdir2,mkdtemp,rename,rm,stat as stat5,writeFile as writeFile3}from"node:fs/promises";var import_build_utils9=__toESM(require_build_utils(),1);import{basename as basename2,dirname as dirname2,join as join11,relative as relative4,sep as sep3}from"node:path";import{copyFile,cp,lstat as lstat2,mkdir,readFile as readFile4,readdir as readdir4,realpath as realpath4,stat as stat4,symlink,writeFile as writeFile2}from"node:fs/promises";async function prepareContinuation(params){let{directory,outputDir,destination,manifest,repoRootPath=directory}=params,validateSource=await traceOperation(params.trace,"vc.cli.describe.validate_continuation",()=>validateBuildOutput({directory,outputDir,repoRootPath})),outputRoot=await realpath4(outputDir),functionDirectories=new Set(params.functions.map(fn=>fn.directory)),functionAliases=[];await traceOperation(params.trace,"vc.cli.describe.copy_continuation",()=>cp(outputDir,destination,{recursive:!0,dereference:!0,filter:async(path2,target)=>{let rel=relative4(outputDir,path2);return basename2(path2)!==".vc-config.json"&&rel.split(sep3).slice(0,-1).some(segment=>segment.endsWith(".func"))?!1:functionDirectories.has(rel)&&(await lstat2(path2)).isSymbolicLink()?(functionAliases.push({path:target,target:join11(destination,relative4(outputRoot,await realpath4(path2)))}),!1):!0}}));for(let{path:path2,target}of functionAliases)await mkdir(dirname2(path2),{recursive:!0}),await symlink(relative4(dirname2(path2),target),path2);await traceOperation(params.trace,"vc.cli.describe.write_manifest",()=>writeFile2(join11(destination,"provision.json"),JSON.stringify(manifest)));let manifests=new Set(await traceOperation(params.trace,"vc.cli.describe.package_manifests",()=>packageManifests(directory)));if(repoRootPath!==directory)for(let path2 of await traceOperation(params.trace,"vc.cli.describe.package_manifests",()=>packageManifests(repoRootPath)))manifests.add(path2);for(let directory2 of functionDirectories)await traceOperation(params.trace,"vc.cli.describe.rewrite_function",async()=>{let configPath=join11(destination,directory2,".vc-config.json"),config=JSON.parse(await readFile4(configPath,"utf8"));for(let[file,source]of Object.entries(config.filePathMap??{}))basename2(file)==="package.json"&&manifests.add(join11(repoRootPath,source));delete config.filePathMap,await writeFile2(configPath,JSON.stringify({...config,architecture:new import_build_utils9.Lambda({...config,files:{}}).architecture}))},{function_count:"1"});let[firstFunction]=functionDirectories;if(firstFunction!==void 0)for(let[i,path2]of[...manifests].entries()){let target=join11(destination,firstFunction,"__byoc_security__",String(i));await mkdir(target,{recursive:!0}),await traceOperation(params.trace,"vc.cli.describe.copy_manifest",async()=>copyFile(await validateSource(path2),join11(target,"package.json")))}}async function packageManifests(root){let modules=join11(root,"node_modules"),names=await readdir4(modules).catch(()=>[]),packages=await Promise.all(names.map(async name=>name.startsWith(".")?[]:name.startsWith("@")?(await readdir4(join11(modules,name)).catch(()=>[])).map(entry=>join11(modules,name,entry)):[join11(modules,name)]));return(await Promise.all([root,...packages.flat()].map(dir=>{let path2=join11(dir,"package.json");return stat4(path2).then(()=>path2,()=>{})}))).filter(p=>p!==void 0)}async function describeDeployment(client,params){return client.withTrace("vc.cli.describe",async trace=>{let output=join12(params.directory,".vercel",params.deploymentId),buildOutput=join12(params.directory,".vercel/output"),build=join12(output,"build"),repoRootPath=params.repoRootPath??params.directory,source=await client.withTrace("vc.cli.describe.resolve_source",async()=>{let source2=await exists(buildOutput)&&!await exists(join12(buildOutput,"provision.json"))?buildOutput:build;if(!await exists(join12(source2,"config.json")))throw new DescribeError("prebuilt_not_found",`No local build output found. Run \`vercel build --deployment ${params.deploymentId}\` before \`vercel deploy describe\`.`);return source2}),staging=await client.withTrace("vc.cli.describe.staging",async()=>(await mkdir2(join12(params.directory,".vercel"),{recursive:!0}),mkdtemp(join12(params.directory,".vercel",`.describe-${params.deploymentId}-`)))),removeStaging=!0,functions=new Map,layers={},manifest={};try{await client.withTrace("vc.cli.describe.prepare_directories",async()=>{await mkdir2(join12(staging,"zips")),await mkdir2(join12(staging,"layers"))});let described=await client.withTrace("vc.cli.describe.functions",()=>describeFunctions(client,{deploymentId:params.deploymentId,directory:params.directory,repoRootPath,outputDir:source,quiet:params.quiet,teamId:params.teamId,zipDirectory:join12(staging,"zips")}));return trace?.span.setAttributes({function_count:String(described.length)}),await client.withTrace("vc.cli.describe.resolve_layers",async layerScope=>{for(let{path:path2,digest,size,regional}of described){for(let descriptor of regional){let layerNames=[];for(let arn of descriptor.Layers){let layer=descriptor.ResolvableLayers[arn];if(!layer)throw new DescribeError("invalid_response","The deployment API did not provide a download URL for a required runtime layer.");let name=createHash3("sha256").update(arn).digest("hex");layerNames.push(name),await client.withTrace("vc.cli.describe.layer",async layerTrace=>{if(layerTrace?.span.setAttributes({cache_hit:layers[name]?"true":"false"}),layers[name])return;let response=await client.withTrace("vc.cli.describe.layer_download",async download=>{let response2=await fetch(layer.url,{signal:AbortSignal.timeout(6e4)});return download?.span.setAttributes({http_method:"GET",http_status_code:String(response2.status)}),response2});if(!response.ok)throw new DescribeError("layer_download_failed","Could not download a required runtime layer. Retry this describe command.");let bytes2=new Uint8Array(await client.withTrace("vc.cli.describe.layer_body",()=>response.arrayBuffer()));layerTrace?.span.setAttributes({byte_count:String(bytes2.length)});let file=`layers/${await client.withTrace("vc.cli.describe.layer_hash",()=>createHash3("sha256").update(bytes2).digest("hex"),{byte_count:String(bytes2.length)})}.zip`;await client.withTrace("vc.cli.describe.layer_write",()=>writeFile3(join12(staging,file),bytes2,{mode:384}),{byte_count:String(bytes2.length)}),layers[name]=file})}let{Region,Layers,ResolvableLayers,...configuration}=descriptor,fn={code:`zips/${digest}.zip`,region:Region,layers:layerNames,configuration},key=`${descriptor.Region}:${descriptor.FunctionName}`,previous=functions.get(key);if(previous&&!isDeepStrictEqual(previous,fn))throw new DescribeError("invalid_response","Conflicting descriptors for the same regional function");functions.set(key,fn)}manifest[path2]={awsAccountId:params.awsAccountId,digest,functionName:regional[0].FunctionName,regions:[...new Set(regional.map(d=>d.Region))],size}}layerScope?.span.setAttributes({layer_count:String(Object.keys(layers).length)})}),trace?.span.setAttributes({layer_count:String(Object.keys(layers).length)}),await client.withTrace("vc.cli.describe.write_descriptor",()=>writeFile3(join12(staging,"descriptor.json"),JSON.stringify({awsAccountId:params.awsAccountId,deploymentId:params.deploymentId,functions:[...functions.values()],layers,version:1},null,2),{mode:384})),await client.withTrace("vc.cli.describe.continuation",trace2=>prepareContinuation({trace:trace2,destination:join12(staging,"output"),directory:params.directory,functions:described,manifest,outputDir:source,repoRootPath})),await client.withTrace("vc.cli.describe.persist",async()=>{await mkdir2(output,{recursive:!0,mode:448});let backup=join12(staging,"backup");await mkdir2(backup);let moves=[],move=async(from,to)=>{await rename(from,to),moves.push([from,to])},preserve=async(path2,name)=>{await exists(path2)&&await move(path2,join12(backup,name))};try{for(let name of["zips","layers","descriptor.json"])await preserve(join12(output,name),name),await move(join12(staging,name),join12(output,name));source===buildOutput?(await preserve(build,"build"),await move(buildOutput,build)):await preserve(buildOutput,"output"),await move(join12(staging,"output"),buildOutput)}catch(error){throw removeStaging=!1,await client.withTrace("vc.cli.describe.rollback",async()=>{for(let[from,to]of moves.reverse())await rename(to,from)}),removeStaging=!0,error}}),output}finally{removeStaging&&await client.withTrace("vc.cli.describe.cleanup",()=>rm(staging,{recursive:!0,force:!0}))}})}var exists=path2=>stat5(path2).then(()=>!0,error=>{if(error.code==="ENOENT")return!1;throw error});import{join as join14}from"node:path";import{join as join13,relative as relative5}from"node:path";async function resolveDescribeProject(client){try{let link=await getLinkFromDir(join13(client.cwd,".vercel"));if(link){let{repoRoot,resolvedRootDirectory}=resolvePerDirectoryLinkRoot(client.cwd,link.settings?.rootDirectory);return{...link,directory:join13(repoRoot,resolvedRootDirectory),repoRootPath:repoRoot}}let repo=await getRepoLink(client,client.cwd);if(!repo?.repoConfig?.projects.length)throw new DescribeError("not_linked","No linked project found. Run `vercel link`, or restore CI project settings with `vercel pull --yes`.");let matches=findProjectsFromPath(repo.repoConfig.projects,relative5(repo.rootPath,client.cwd)),candidates=matches.length?matches:repo.repoConfig.projects;if(candidates.length!==1)throw new DescribeError("ambiguous_project","Multiple projects are linked here. Run this command from the intended project directory, or pass --cwd <PROJECT_DIRECTORY>.");let project=await getProjectLink(client,client.cwd,candidates[0].id,!0);if(!project?.repoRoot)throw new Error("Project link changed");return{...project,directory:join13(project.repoRoot,project.projectRootDirectory||""),repoRootPath:project.repoRoot}}catch(error){throw error instanceof DescribeError?error:new DescribeError("invalid_project_link","Could not read the local project link. Check that .vercel/project.json or .vercel/repo.json is readable and contains valid project settings.")}}async function describe(client){let asJson=wantsMachineReadableOutput("deploy",client.argv),warnings=[],fail=(reason,message,code2=1)=>(asJson?client.stderr.write(`${JSON.stringify({status:"error",reason,message,...warnings.length>0?{warnings}:{}})}
22
+ `;function hydrateLambdaFiles(lambda,encryptedEnv){let files=lambda.files??{};if(lambda.runtime==="container"||!encryptedEnv.filename||!encryptedEnv.contentBase64)return files;if(files[encryptedEnv.filename]=new import_build_utils.FileBlob({data:Buffer.from(encryptedEnv.contentBase64,"base64")}),lambda.supportsWrapper!==!0&&!NATIVELY_WRAPPER_SUPPORTED_FAMILIES.some(family=>lambda.runtime.startsWith(family))){if(!lambda.runtime.startsWith("provided"))throw new Error(`Serverless Function runtime ${lambda.runtime} does not support more than 4KB for environment variables`);let userBootstrap=files[ROOT_BOOTSTRAP_PATH];if(!userBootstrap)throw new Error(`Serverless Function runtime ${lambda.runtime} does not support more than 4KB for environment variables`);if(files[USER_BOOTSTRAP_PATH])throw new Error(`Cannot wrap "provided.*" lambda: reserved file path ${USER_BOOTSTRAP_PATH} is already in use. Please rename your file.`);files[USER_BOOTSTRAP_PATH]=userBootstrap,delete files[ROOT_BOOTSTRAP_PATH],files[ROOT_BOOTSTRAP_PATH]=new import_build_utils.FileBlob({data:BOOTSTRAP_SHIM,mode:33261})}return files}import{join as join10}from"node:path";var import_build_utils8=__toESM(require_build_utils(),1);var import_build_utils2=__toESM(require_build_utils(),1);import{join as join2}from"path";import{readFile}from"node:fs/promises";async function maybeReadJSON(path2){let contents;try{contents=await readFile(path2,"utf8")}catch(err){if(err.code!=="ENOENT")throw err;return}try{return JSON.parse(contents.charCodeAt(0)===65279?contents.slice(1):contents)}catch(err){throw err.message=`${path2}: ${err.message}`,err}}async function getBuildOutputConfig(outputDir){let configPath=getBuildOutputConfigPath(outputDir),config=await maybeReadJSON(configPath);if(!config)return;if(config.version!==3)throw new Error(`Expected \`version: 3\` in "${configPath}" file (received \`${config.version}\`)`);validateDeploymentId(config.deploymentId),validateExperimentalServicesV2(config.experimentalServicesV2);let framework=validateFrameworkVersion(config.framework);return{...config,framework}}function getBuildOutputConfigPath(outputDir){return join2(outputDir,"config.json")}var MAX_DEPLOYMENT_ID_LENGTH=32,MAX_FRAMEWORK_SLUG_LENGTH=50,MAX_FRAMEWORK_VERSION_LENGTH=50,VALID_DEPLOYMENT_ID_PATTERN=/^[a-zA-Z0-9_-]+$/;function validateDeploymentId(deploymentId){if(deploymentId&&deploymentId.length>MAX_DEPLOYMENT_ID_LENGTH)throw new import_build_utils2.NowBuildError({message:`The configured deploymentId "${deploymentId}" exceeds the maximum length of ${MAX_DEPLOYMENT_ID_LENGTH} characters. Please use a shorter deploymentId.`,code:"VC_BUILD_INVALID_DEPLOYMENT_ID_LENGTH"});if(deploymentId&&!VALID_DEPLOYMENT_ID_PATTERN.test(deploymentId))throw new import_build_utils2.NowBuildError({message:`The configured deploymentId "${deploymentId}" contains invalid characters. Only alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (_) are allowed.`,code:"VC_BUILD_INVALID_DEPLOYMENT_ID_CHARACTERS"})}function validateFrameworkVersion(framework){if(!framework)return;let{slug,version}=framework;if(typeof slug=="string"){if(typeof version!="string")throw new import_build_utils2.NowBuildError({message:`Invalid config.json: "version" type "${typeof version}" should be "string"`,code:"VC_BUILD_INVALID_CONFIG_JSON_FRAMEWORK_VERSION_TYPE"});if(slug.length>MAX_FRAMEWORK_SLUG_LENGTH){let trimmedSlug=slug.slice(0,MAX_FRAMEWORK_SLUG_LENGTH);throw new import_build_utils2.NowBuildError({message:`Invalid config.json: "framework.slug" length ${slug.length} > ${MAX_FRAMEWORK_SLUG_LENGTH}. "${trimmedSlug}..."`,code:"VC_BUILD_INVALID_CONFIG_JSON_FRAMEWORK_SLUG_LENGTH"})}if(version.length>MAX_FRAMEWORK_VERSION_LENGTH){let trimmedVersion=version.slice(0,MAX_FRAMEWORK_VERSION_LENGTH);throw new import_build_utils2.NowBuildError({message:`Invalid config.json: "framework.version" length ${version.length} > ${MAX_FRAMEWORK_VERSION_LENGTH}. "${trimmedVersion}..."`,code:"VC_BUILD_INVALID_CONFIG_JSON_FRAMEWORK_VERSION_LENGTH"})}return framework}}function validateExperimentalServicesV2(experimentalServicesV2){if(experimentalServicesV2!==void 0&&(!experimentalServicesV2||typeof experimentalServicesV2!="object"||Array.isArray(experimentalServicesV2)))throw new import_build_utils2.NowBuildError({code:"INVALID_BUILD_OUTPUT_CONFIG",message:'Invalid config.json: "experimentalServicesV2" must be an object.'})}async function getBuildOutputConfigOrThrow(outputDir){let config=await getBuildOutputConfig(outputDir);if(config)return config;throw new Error(`Config file was not found at "${getBuildOutputConfigPath(outputDir)}"`)}import{join as join3}from"path";function getFunctionSourcePath(source){return source.service?join3("services",source.service,source.output.path):source.output.path}var import_build_utils3=__toESM(require_build_utils(),1);function isRouteMiddleware(route){return"middlewarePath"in route&&typeof route.middlewarePath=="string"}var cache=new WeakMap;function getMiddlewareRouting(buildResult){let cached=cache.get(buildResult.functions);if(cached&&cached.routes===buildResult.routes)return cached.routing;let routing=new Map,{lambdas,edgeFunctions}=buildResult.functions;for(let route of buildResult.routes){if(!isRouteMiddleware(route))continue;let outputPath=route.middlewarePath;!lambdas.has(outputPath)&&!edgeFunctions.has(outputPath)&&(outputPath=outputPath.replace(/^\//,""));let output=lambdas.get(outputPath)??edgeFunctions.get(outputPath);if(!outputPath||!output)throw new import_build_utils3.NowBuildError({message:`Mapping ${route.middlewarePath} not found. Maybe you provided a wrong middlewarePath?`,code:"middleware_path_not_found"});let index=routing.get(outputPath)?.index??routing.size;routing.set(outputPath,output.type==="EdgeFunction"?{type:"middleware",middlewarePath:route.middlewarePath,outputPath,edgeFunction:output,index}:{type:"middleware-lambda",middlewarePath:route.middlewarePath,outputPath,index})}return cache.set(buildResult.functions,{routes:buildResult.routes,routing}),routing}import{join as join4}from"path";function getServiceOutputEntries(config){return Object.entries(config.experimentalServicesV2??{}).map(([name,service])=>({name,directory:join4("services",name),service}))}var import_semver=__toESM(require_semver(),1),import_build_utils4=__toESM(require_build_utils(),1);import{createHash}from"crypto";import fs2 from"fs";var fileSizeCache=new Map,getFileSize=path2=>{if(!path2)return Promise.resolve(0);let cached=fileSizeCache.get(path2);if(cached)return cached;let promise=fs2.promises.lstat(path2).then(stats=>stats.size);return fileSizeCache.set(path2,promise),promise},collectUncompressedSize=async(files,ignoreFn)=>{let size=0;return await Promise.all(Object.keys(files).map(async fileKey=>{if(!ignoreFn?.(fileKey)){if(files[fileKey].type==="FileBlob")size+=files[fileKey].data.length;else if(files[fileKey].type==="FileFsRef"){let curSize=files[fileKey].size??await getFileSize(files[fileKey].fsPath);size+=curSize}}})),size};var MIB=1024*1024,MAX_UNCOMPRESSED_FUNCTION_SIZE_BYTES=250*MIB,LAMBDA_RESERVED_UNCOMPRESSED_SIZE_BYTES=25*MIB,LARGE_FUNCTION_THRESHOLD_BYTES=MAX_UNCOMPRESSED_FUNCTION_SIZE_BYTES-LAMBDA_RESERVED_UNCOMPRESSED_SIZE_BYTES,MANIFEST_FILE_NAMES=["routes-manifest.json","server/pages-manifest.json","server/app-paths-manifest.json","app-path-routes-manifest.json"],TEST_DYNAMIC_ROUTE=/\/\[[^\/]+?\](?=\/|$)/;function isNextjsDynamicRoute(route){return route=route.startsWith("/")?route:`/${route}`,TEST_DYNAMIC_ROUTE.test(route)}function computeLambdaFieldsSignature(lambda,lambdaFields){let parts=[];for(let field of lambdaFields)parts.push(JSON.stringify(lambda[field]));return parts.join("|")}async function getLambdaFileSizeMetadata(lambdaFiles){let fileKeys=Object.keys(lambdaFiles),fileSizes=new Map,uncompressedSize=0;for(let fileKey of fileKeys){let file=lambdaFiles[fileKey];if(file===void 0)throw new Error("Expected lambdaFiles[fileKey] to be defined");let fileSize=0;file.type==="FileBlob"?fileSize=file.data.length:file.type==="FileFsRef"&&(fileSize=await collectUncompressedSize({[fileKey]:file},void 0)),fileSizes.set(fileKey,fileSize),uncompressedSize+=fileSize}return{fileKeys,fileSizes,uncompressedSize}}async function groupLambdas(lambdas,options){let{force}=options,lambdaFields=["allowQuery","affinity","architecture","awsLambdaHandler","environment","experimentalResponseStreaming","experimentalTriggers","framework","handler","maxConcurrency","maxDuration","memory","operationType","regions","runtime","runtimeLanguage","shouldAddHelpers","shouldAddSourcemapSupport","shouldDisableAutomaticFetchInstrumentation","supportsCancellation","supportsMultiPayloads","supportsResponseStreaming","supportsWrapper","useWebApi","functionFailoverRegions"],_typeCheck=lambdaFields,fieldsToCompare=force==="all"?["runtime","maxConcurrency"]:lambdaFields,maxUncompressedFunctionSize=LARGE_FUNCTION_THRESHOLD_BYTES,maxBundleSizeMb=options.maxBundleSizeMb;if(maxBundleSizeMb!==void 0&&Number.isFinite(maxBundleSizeMb)){let customMaxUncompressedFunctionSize=Math.floor(maxBundleSizeMb*MIB);output_manager_default.warn(`Warn: custom max uncompressed function size of ${customMaxUncompressedFunctionSize/MIB}MiB configured`),maxUncompressedFunctionSize=Math.min(customMaxUncompressedFunctionSize,MAX_UNCOMPRESSED_FUNCTION_SIZE_BYTES)}let seenLambdas=new Map;for(let[name,lambda]of Object.entries(lambdas)){if(!lambda.experimentalAllowBundling||!lambda.files)continue;let existingNames=seenLambdas.get(lambda);existingNames?existingNames.push(name):seenLambdas.set(lambda,[name])}let handlerDigestPromiseCache=new Map,getHandlerDigest=handlerFile=>{if(!handlerFile)return Promise.resolve(void 0);let cached=handlerDigestPromiseCache.get(handlerFile);if(cached)return cached;let promise=(async()=>{try{let handlerStream=handlerFile.toStream(),handlerBuffer=await(0,import_build_utils4.streamToBuffer)(handlerStream),handlerBytes=new Uint8Array(handlerBuffer.buffer,handlerBuffer.byteOffset,handlerBuffer.byteLength);return createHash("sha1").update(handlerBytes).digest("hex")}catch{return}})();return handlerDigestPromiseCache.set(handlerFile,promise),promise},bundlesBySignature=new Map,allBundledLambdas=[];for(let[lambda,lambdaNames]of seenLambdas){let lambdaFiles=lambda.files;if(!lambdaFiles)continue;let signature=computeLambdaFieldsSignature(lambda,fieldsToCompare),{fileKeys,fileSizes,uncompressedSize}=await getLambdaFileSizeMetadata(lambdaFiles),handlerDigest=await getHandlerDigest(lambdaFiles[lambda.handler]),compatibleBundles=bundlesBySignature.get(signature),isLarge=uncompressedSize>=LARGE_FUNCTION_THRESHOLD_BYTES,foundMatchingBundle=!1;if(compatibleBundles&&!isLarge)for(let bundleMeta of compatibleBundles){if(bundleMeta.isLarge||!(handlerDigest===bundleMeta.handlerDigest)&&force!=="all")continue;let uncompressedBytesIncrease=0;for(let fileKey of fileKeys){let incomingFileSize=fileSizes.get(fileKey)??0,existingFileSize=bundleMeta.fileSizesByKey.get(fileKey);existingFileSize===void 0?uncompressedBytesIncrease+=incomingFileSize:uncompressedBytesIncrease+=incomingFileSize-existingFileSize}let newTotalSize=bundleMeta.uncompressedBytes+uncompressedBytesIncrease;if(newTotalSize<=maxUncompressedFunctionSize){foundMatchingBundle=!0,bundleMeta.uncompressedBytes=newTotalSize,bundleMeta.lambdaNames.push(...lambdaNames);for(let fileKey of fileKeys)bundleMeta.fileSizesByKey.set(fileKey,fileSizes.get(fileKey)??0);let potentialLambdaFiles=bundleMeta.lambda.files;potentialLambdaFiles&&(bundleMeta.lambda.files=Object.assign(potentialLambdaFiles,lambdaFiles));break}}if(!foundMatchingBundle){let newBundleMeta={lambda,signature,handlerDigest,isLarge,uncompressedBytes:uncompressedSize,fileSizesByKey:new Map(fileSizes),lambdaNames:[...lambdaNames]},signatureBundles=bundlesBySignature.get(signature);signatureBundles||(signatureBundles=[],bundlesBySignature.set(signature,signatureBundles)),signatureBundles.push(newBundleMeta),allBundledLambdas.push(newBundleMeta)}}let finalLambdas=Object.assign({},lambdas);options.debug&&(output_manager_default.debug("GROUP_LAMBDAS: "+JSON.stringify(allBundledLambdas.map(bundleMeta=>({lambdaNames:bundleMeta.lambdaNames,signature:bundleMeta.signature,uncompressedBytes:bundleMeta.uncompressedBytes})),null,2)),output_manager_default.debug(`total grouped lambdas: ${allBundledLambdas.length}`));for(let bundleMeta of allBundledLambdas){let lambda=bundleMeta.lambda;for(let lambdaName of bundleMeta.lambdaNames)finalLambdas[lambdaName]=lambda;if(lambda.framework?.slug==="nextjs"&&lambda.framework.version){let CORRECTED_MANIFESTS_VERSION="v12.2.0";if(import_semver.default.gte(lambda.framework.version,CORRECTED_MANIFESTS_VERSION)){let pageFiles=[],manifestFileKeys={},manifestFileNames=MANIFEST_FILE_NAMES;for(let fileKey of Object.keys(lambda.files||{})){let isPageFile=fileKey.includes("server/pages/"),isAppFile=fileKey.includes("server/app/");if(isPageFile||isAppFile){let relativePageFile=fileKey.split(`server/${isPageFile?"pages":"app"}/`).pop();relativePageFile&&pageFiles.push(relativePageFile)}for(let manifestFileName of manifestFileNames)fileKey.endsWith(`/${manifestFileName}`)&&(manifestFileKeys[manifestFileName]=fileKey)}let appPathRoutesManifestFilesKey=manifestFileKeys["app-path-routes-manifest.json"],appPathRoutesManifestFile=appPathRoutesManifestFilesKey&&lambda.files?.[appPathRoutesManifestFilesKey],appPathRoutesManifest=appPathRoutesManifestFile?await(0,import_build_utils4.streamToBuffer)(appPathRoutesManifestFile.toStream()).then(res=>JSON.parse(res.toString("utf8"))).catch(()=>({})):{};for(let manifestFileName of manifestFileNames){let manifestFilesKey=manifestFileKeys[manifestFileName],manifestFile=manifestFilesKey&&lambda.files?.[manifestFilesKey];if(!manifestFile)continue;let manifestData=JSON.parse((await(0,import_build_utils4.streamToBuffer)(manifestFile.toStream())).toString("utf8")),normalizedPages=new Set(pageFiles.map(page=>(page=`/${page.replace(/\.js$/,"")}`,page==="/index"&&(page="/"),appPathRoutesManifest[page]||page)));switch(manifestFileName){case"routes-manifest.json":{let filterItem=item=>normalizedPages.has(item.page);manifestData.dynamicRoutes=manifestData.dynamicRoutes?.filter(filterItem),manifestData.staticRoutes=manifestData.staticRoutes?.filter(filterItem);break}case"server/pages-manifest.json":{for(let key of Object.keys(manifestData))isNextjsDynamicRoute(key)&&!normalizedPages.has(key)&&delete manifestData[key];break}case"server/app-paths-manifest.json":{if(appPathRoutesManifest)for(let key of Object.keys(manifestData)){let normalizedKey=appPathRoutesManifest[key]||key.replace(/(^|\/)(page|route)$/,"");isNextjsDynamicRoute(normalizedKey)&&!normalizedPages.has(normalizedKey)&&delete manifestData[key]}break}}lambda.files&&(lambda.files[manifestFilesKey]=new import_build_utils4.FileBlob({contentType:"application/json",data:JSON.stringify(manifestData)}))}}}}return finalLambdas}async function groupBundleableLambdas(params){let lambdas={};for(let[path2,lambda]of params.functions.lambdas)lambda.experimentalAllowBundling&&(lambdas[path2]=lambda);for(let[path2,prerender]of params.functions.prerenders)prerender.lambda.experimentalAllowBundling&&(lambdas[path2]=prerender.lambda);if(Object.keys(lambdas).length===0)return;let grouped=await groupLambdas(lambdas,{force:void 0,maxBundleSizeMb:params.options.maxBundleSizeMb,debug:params.options.debugGroupLambdas});for(let[path2,lambda]of Object.entries(grouped))if(params.functions.lambdas.has(path2))params.functions.lambdas.set(path2,lambda);else{let prerender=params.functions.prerenders.get(path2);if(prerender)prerender.lambda=lambda;else throw new Error(`Grouped lambda "${path2}" does not match any build output`)}}function*iterateNativeFunctionOutputs(functions){for(let outputs of[functions.lambdas,functions.prerenders])for(let[path2,output]of outputs)yield{path:path2,lambda:output.type==="Lambda"?output:output.lambda,prerender:output.type==="Prerender"?output:void 0}}import{join as join9}from"node:path";import{readFile as readFile3}from"node:fs/promises";var import_build_utils6=__toESM(require_build_utils(),1);import{join as join5,relative}from"path";import{readdir,stat}from"fs/promises";var SUFFIX=".func";async function*createFunctionEntriesIterator(dir,root=dir){let entries;try{entries=await readdir(dir,{withFileTypes:!0})}catch(error){if(!(typeof error=="object"&&error!==null&&"code"in error)||error.code!=="ENOENT"&&error.code!=="ENOTDIR")throw error;entries=[]}let names;for(let entry of entries){let absolutePath=join5(dir,entry.name),isSymbolicLink=entry.isSymbolicLink();if(entry.isDirectory()||isSymbolicLink&&(await stat(absolutePath)).isDirectory())if(entry.name.endsWith(SUFFIX)){names??=new Set(entries.map(e=>e.name));let baseName=entry.name.slice(0,-SUFFIX.length);yield{hasPrerenderConfig:names.has(`${baseName}.prerender-config.json`),isSymbolicLink,path:relative(root,absolutePath.substring(0,absolutePath.length-SUFFIX.length))}}else yield*createFunctionEntriesIterator(absolutePath,root)}}import{dirname,isAbsolute,join as join6,relative as relative2,resolve as resolve2,sep}from"node:path";var import_build_utils5=__toESM(require_build_utils(),1);import{lstat,readlink,realpath,readdir as readdir2,stat as stat2}from"node:fs/promises";import assert from"assert";import path from"path";async function glob(options){if(!path.isAbsolute(options.cwd))throw new Error(`basePath/cwd must be an absolute path (${options.cwd})`);let results={},statCache={},symlinks={},files=await walkAll(options.cwd,!!options.follow,statCache,symlinks),dirs=new Set,dirsWithEntries=new Set;for(let relativePath of files){let fsPath=path.join(options.cwd,relativePath),stats=statCache[fsPath];assert(stats,`statCache does not contain value for ${relativePath}`);let isSymlink=symlinks[fsPath];if(options.follow&&(isSymlink||(await lstat(fsPath)).isSymbolicLink())){let target=await readlink(fsPath),absoluteTarget=path.resolve(path.dirname(fsPath),target);if(path.relative(options.cwd,absoluteTarget).startsWith(`..${path.sep}`))continue}if(isSymlink||stats.isFile()||stats.isDirectory()){isSymlink&&(stats=await lstat(fsPath));let dirname4=path.dirname(relativePath);if(dirsWithEntries.add(dirname4),stats.isDirectory()){dirs.add(relativePath);continue}results[relativePath]=new import_build_utils5.FileFsRef({mode:stats.mode,fsPath,size:stats.size})}}if(options.includeDirectories)for(let relativePath of dirs){if(dirsWithEntries.has(relativePath))continue;let fsPath=path.join(options.cwd,relativePath),stats=statCache[fsPath];results[relativePath]=new import_build_utils5.FileFsRef({mode:stats.mode,fsPath,size:stats.size})}return results}async function walkAll(cwd,follow,statCache,symlinks){let files=[];async function walk(dirAbs,realDir,ancestors){let entries;try{entries=await readdir2(dirAbs,{withFileTypes:!0})}catch(err){let code2=err.code;if(code2==="ENOENT"||code2==="ENOTDIR")return;throw err}await Promise.all(entries.map(async entry=>{let abs=path.join(dirAbs,entry.name);if(entry.isSymbolicLink())if(follow){let stats=await stat2(abs).catch(()=>lstat(abs).catch(()=>null));if(stats===null)return;if(statCache[abs]=stats,files.push(abs),stats.isDirectory()){let real=await realpath(abs).catch(()=>null);real!==null&&!ancestors.has(real)&&await walk(abs,real,new Set(ancestors).add(real))}}else{let stats=await lstat(abs).catch(()=>null);if(stats===null)return;statCache[abs]=stats,symlinks[abs]=!0,files.push(abs)}else if(entry.isDirectory()){let stats=await lstat(abs).catch(()=>null);if(stats===null)return;statCache[abs]=stats,files.push(abs);let real=path.join(realDir,entry.name);await walk(abs,real,new Set(ancestors).add(real))}else{let stats=await lstat(abs).catch(()=>null);if(stats===null)return;statCache[abs]=stats,files.push(abs)}}))}let cwdReal=follow?await realpath(cwd).catch(()=>null):cwd;return cwdReal!==null&&await walk(cwd,cwdReal,new Set([cwdReal])),files.map(abs=>path.relative(cwd,abs)).sort((a,b)=>a.localeCompare(b,"en"))}import{isNativeError}from"node:util/types";import{readlink as readlink2,realpath as realpath2}from"node:fs/promises";async function readFunctions(params){let fileFsRefsCache=new Map,entries=[],functionsDir=join6(params.outputDir,"functions"),iterator=enumerate(createFunctionEntriesIterator(functionsDir));await Promise.all(Array.from({length:params.concurrency??32},async()=>{for await(let[index,entry]of iterator)entries[index]=await deserializeFunctionEntry({prebuilt:params.prebuilt,entry,fileFsRefsCache,functionsDir,repoRootPath:params.repoRootPath})}));let serverActionsManifestPaths=new Set,edgeFunctions=new Map,unsortedPrerenders=new Map,functionSymlinks=new Map,lambdas=new Map;for(let functionEntry of entries)functionEntry.symlinkTarget!==void 0&&functionSymlinks.set(functionEntry.path,functionEntry.symlinkTarget),functionEntry.serverActionsManifestPath&&serverActionsManifestPaths.add(functionEntry.serverActionsManifestPath),functionEntry.output?.type==="Prerender"?unsortedPrerenders.set(functionEntry.path,functionEntry.output):functionEntry.output?.type==="Lambda"?lambdas.set(functionEntry.path,functionEntry.output):functionEntry.output?.type==="EdgeFunction"&&edgeFunctions.set(functionEntry.path,functionEntry.output);for(let[path2,target]of functionSymlinks){let destFunction=unsortedPrerenders.get(target)?.lambda??edgeFunctions.get(target)??lambdas.get(target);if(!destFunction)throw new Error(`Could not find target "${target}" Lambda or EdgeFunction for path "${path2}"`);let srcPrerender=unsortedPrerenders.get(path2);if(!srcPrerender)destFunction.type==="Lambda"?lambdas.set(path2,destFunction):destFunction.type==="EdgeFunction"&&edgeFunctions.set(path2,destFunction);else{if(destFunction.type!=="Lambda")throw new Error(`Unexpected function type "${destFunction.type}" at path "${path2}"`);srcPrerender.lambda=destFunction}}let prerenders=new Map;for(let[path2,prerender]of[...unsortedPrerenders].sort((a,b)=>(a[1].group??0)-(b[1].group??0)))validatePrerender(prerender),prerenders.set(path2,prerender);return{edgeFunctions,lambdas,prerenders,serverActionsManifestPaths}}async function*enumerate(iterable){let index=0;for await(let item of iterable)yield[index++,item]}async function deserializeFunctionEntry(params){let functionDir=join6(params.functionsDir,`${params.entry.path}.func`),prerenderConfigPath=join6(params.functionsDir,`${params.entry.path}.prerender-config.json`),configPromise=params.entry.hasPrerenderConfig?maybeReadJSON(prerenderConfigPath):void 0;configPromise?.catch(()=>{});let lambda,serverActionsManifestPath,symlinkTarget;if(params.entry.isSymbolicLink)symlinkTarget=await readlink2(functionDir).then(link=>join6(dirname(params.entry.path),link).slice(0,-5));else{let functionConfigPath=join6(functionDir,".vc-config.json"),[functionConfig,files]=await Promise.all([maybeReadJSON(functionConfigPath),glob({cwd:functionDir,includeDirectories:!0})]);if(!functionConfig)throw new Error(`Could not load function config: "${functionConfigPath}"`);if(delete files[".vc-config.json"],functionConfig.filePathMap&&await hydrateFilesMap(files,functionConfig.filePathMap,params.repoRootPath,params.fileFsRefsCache,params.prebuilt),"type"in functionConfig&&functionConfig.type==="EdgeFunction"||functionConfig.runtime==="edge")return{path:params.entry.path,output:new import_build_utils6.EdgeFunction({deploymentTarget:"v8-worker",...functionConfig,files})};let supportsResponseStreaming=functionConfig.supportsResponseStreaming??functionConfig.experimentalResponseStreaming;lambda="launcherType"in functionConfig&&functionConfig.launcherType==="Nodejs"?new import_build_utils6.NodejsLambda({...functionConfig,files,supportsResponseStreaming:functionConfig.awsLambdaHandler===void 0||functionConfig.awsLambdaHandler===""||supportsResponseStreaming}):new import_build_utils6.Lambda({...functionConfig,files,supportsResponseStreaming}),serverActionsManifestPath=functionConfig.filePathMap?.[".next/server/server-reference-manifest.json"]}if(configPromise){let prerenderConfig=await configPromise;if(prerenderConfig)return{path:params.entry.path,symlinkTarget,serverActionsManifestPath,output:new import_build_utils6.Prerender({...prerenderConfig,fallback:await deserializePrerenderFallback(prerenderConfigPath,prerenderConfig.fallback,params),initialMetadata:sanitizeInitialMetadata(prerenderConfig.initialMetadata),lambda})}}return{path:params.entry.path,symlinkTarget,output:lambda,serverActionsManifestPath}}function validatePrerender(prerender){if(prerender.lambda===void 0)throw new Error('Prerender "buildResult" is missing "lambda" property')}async function hydrateFilesMap(files,filesMap,repoRootPath,fileFsRefsCache,prebuilt){let rootPath=prebuilt?await realpath2(repoRootPath):void 0;async function hydrateFile(projectPath){let fsPath=join6(repoRootPath,projectPath);rootPath!==void 0&&await validatePrebuiltFilePath(fsPath,rootPath,`file map source "${projectPath}"`,!0);let file=await import_build_utils6.FileFsRef.fromFsPath({fsPath});return fileFsRefsCache.set(projectPath,file),file}let pending;for(let functionPath in filesMap){let projectPath=filesMap[functionPath],cached=fileFsRefsCache.get(projectPath);if(cached&&!(cached instanceof Promise)){files[functionPath]=cached;continue}let filePromise=cached;if(!filePromise){let promise=hydrateFile(projectPath);fileFsRefsCache.set(projectPath,promise),filePromise=promise}(pending??=[]).push(filePromise.then(file=>{files[functionPath]=file}))}pending&&await Promise.all(pending)}async function validatePrebuiltFilePath(fsPath,rootPath,source,enableDanglingSymlinks=!1){let resolvedPath;try{resolvedPath=await realpath2(fsPath)}catch(error){if(!enableDanglingSymlinks||!isNativeError(error)||!("code"in error)||error.code!=="ENOENT")throw error;let target=await readlink2(fsPath),parentPath=await validatePrebuiltFilePath(dirname(fsPath),rootPath,source);resolvedPath=resolve2(parentPath,target)}let sourcePath=relative2(rootPath,resolvedPath);if(sourcePath===".."||sourcePath.startsWith(`..${sep}`)||isAbsolute(sourcePath))throw new import_build_utils6.NowBuildError({code:"INVALID_PREBUILT_FILE_PATH",message:`Prebuilt ${source} must be inside the uploaded project.`});return resolvedPath}function sanitizeInitialMetadata(initialMetadata){try{if(typeof initialMetadata!="object"||initialMetadata===null||Array.isArray(initialMetadata))return;let{compute,htmlSize}=initialMetadata;return compute!=="blocking"&&compute!=="resuming"&&compute!=="static"||htmlSize!==void 0&&(!Number.isSafeInteger(htmlSize)||htmlSize<0)?void 0:{compute,...htmlSize!==void 0&&{htmlSize}}}catch{return}}async function deserializePrerenderFallback(prerenderConfigPath,fallback,options){if(fallback==null)return null;let path2=typeof fallback=="string"?fallback:fallback.fsPath,fsPath=join6(dirname(prerenderConfigPath),path2);return options.prebuilt&&await validatePrebuiltFilePath(fsPath,await realpath2(options.repoRootPath),`prerender fallback "${path2}"`),typeof fallback=="string"?import_build_utils6.FileFsRef.fromFsPath({fsPath}):fallback.mode!==void 0?new import_build_utils6.FileFsRef({mode:fallback.mode,size:fallback.size,contentType:fallback.contentType,fsPath}):import_build_utils6.FileFsRef.fromFsPath({mode:fallback.mode,size:fallback.size,contentType:fallback.contentType,fsPath})}var import_build_utils7=__toESM(require_build_utils(),1);import{join as join7}from"path";async function readServiceOutputConfig(outputDir,entry){let config=await getBuildOutputConfig(join7(outputDir,entry.directory));if(!config&&entry.service.root===void 0)throw new import_build_utils7.NowBuildError({code:"MISSING_SERVICE_BUILD_OUTPUT",message:`Service "${entry.name}" is configured in experimentalServicesV2 but is missing build output at ".vercel/output/services/${entry.name}/config.json".`});return config}var import_async_sema=__toESM(require_async_sema(),1),import_ignore=__toESM(require_ignore(),1);import{basename,isAbsolute as isAbsolute2,join as join8,relative as relative3,sep as sep2}from"node:path";import{readFile as readFile2,readdir as readdir3,realpath as realpath3,stat as stat3}from"node:fs/promises";function contains(root,path2){let rel=relative3(root,path2);return rel!==".."&&!rel.startsWith(`..${sep2}`)&&!isAbsolute2(rel)}function invalidSource(){throw new DescribeError("invalid_build_output","Build output references files outside the authorized output or includes excluded source files. Remove unsafe links and excluded file mappings, then rebuild.")}var vcs=(0,import_ignore.default)().add([".hg",".git",".gitmodules",".svn","CVS"]),dependencies=(0,import_ignore.default)().add(["node_modules",".next",".yarn/cache",".pnp*",".venv","venv","__pycache__","/target"]);async function readIgnore(root){let read=name=>readFile2(join8(root,name),"utf8").catch(error=>{if(error.code==="ENOENT")return"";throw error}),[vercelignore,nowignore]=await Promise.all([read(".vercelignore"),read(".nowignore")]);if(vercelignore&&nowignore)throw new DescribeError("invalid_build_output","Cannot use both .vercelignore and .nowignore. Remove the deprecated .nowignore file and retry.");return(0,import_ignore.default)().add((vercelignore||nowignore).replace(/(\n|^)\.\//g,"$1"))}async function validateBuildOutput(options){let root=await realpath3(options.repoRootPath),output=await realpath3(options.outputDir),expectedOutput=join8(root,relative3(options.repoRootPath,options.outputDir));(!contains(root,output)||relative3(expectedOutput,output)!=="")&&invalidSource();let project=options.directory?await realpath3(options.directory):root,bases=[root];if(project!==root&&contains(root,project))for(let segment of relative3(root,project).split(sep2))bases.push(join8(bases[bases.length-1],segment));let ignores=await Promise.all(bases.map(async base=>({base,rules:await readIgnore(base)}))),sema=new import_async_sema.default(32),limit=async fn=>{await sema.acquire();try{return await fn()}finally{sema.release()}},checkSource=async path2=>{let resolved=await limit(()=>realpath3(path2));for(let source of[join8(root,relative3(options.repoRootPath,path2)),resolved]){contains(root,source)||invalidSource();let rel=relative3(root,source).split(sep2).join("/");if(rel&&(vcs.ignores(rel)&&invalidSource(),!contains(output,source)))for(let{base,rules}of ignores){if(!contains(base,source))continue;let relToBase=relative3(base,source).split(sep2).join("/");relToBase&&rules.ignores(relToBase)&&!dependencies.ignores(relToBase)&&invalidSource()}}return resolved},checked=new Map,validateSource=path2=>{let result=checked.get(path2);return result||(result=checkSource(path2),checked.set(path2,result)),result},configs=[],visited=new Set;async function walk(dir,ancestors){visited.add(dir);let next=new Set(ancestors).add(dir),entries=await Promise.all((await limit(()=>readdir3(dir))).map(async name=>{let path2=join8(dir,name),resolved=await limit(()=>realpath3(path2));return(!contains(output,resolved)||next.has(resolved))&&invalidSource(),{path:path2,resolved,stats:await limit(()=>stat3(resolved))}}));for(let{path:path2,resolved,stats}of entries)stats.isDirectory()?visited.has(resolved)||await walk(resolved,next):basename(path2)===".vc-config.json"&&configs.push(resolved)}return await walk(output,new Set),await Promise.all(configs.map(async path2=>{let config=JSON.parse(await limit(()=>readFile2(path2,"utf8")));await Promise.all(Object.values(config.filePathMap??{}).map(source=>(typeof source!="string"&&invalidSource(),validateSource(join8(options.repoRootPath,source)))))})),validateSource}var external_exports={};__export(external_exports,{BRAND:()=>BRAND,DIRTY:()=>DIRTY,EMPTY_PATH:()=>EMPTY_PATH,INVALID:()=>INVALID,NEVER:()=>NEVER,OK:()=>OK,ParseStatus:()=>ParseStatus,Schema:()=>ZodType,ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBigInt:()=>ZodBigInt,ZodBoolean:()=>ZodBoolean,ZodBranded:()=>ZodBranded,ZodCatch:()=>ZodCatch,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodEffects:()=>ZodEffects,ZodEnum:()=>ZodEnum,ZodError:()=>ZodError,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodFunction:()=>ZodFunction,ZodIntersection:()=>ZodIntersection,ZodIssueCode:()=>ZodIssueCode,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNativeEnum:()=>ZodNativeEnum,ZodNever:()=>ZodNever,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodParsedType:()=>ZodParsedType,ZodPipeline:()=>ZodPipeline,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRecord:()=>ZodRecord,ZodSchema:()=>ZodType,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodSymbol:()=>ZodSymbol,ZodTransformer:()=>ZodEffects,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,addIssueToContext:()=>addIssueToContext,any:()=>anyType,array:()=>arrayType,bigint:()=>bigIntType,boolean:()=>booleanType,coerce:()=>coerce,custom:()=>custom,date:()=>dateType,datetimeRegex:()=>datetimeRegex,defaultErrorMap:()=>en_default,discriminatedUnion:()=>discriminatedUnionType,effect:()=>effectsType,enum:()=>enumType,function:()=>functionType,getErrorMap:()=>getErrorMap,getParsedType:()=>getParsedType,instanceof:()=>instanceOfType,intersection:()=>intersectionType,isAborted:()=>isAborted,isAsync:()=>isAsync,isDirty:()=>isDirty,isValid:()=>isValid,late:()=>late,lazy:()=>lazyType,literal:()=>literalType,makeIssue:()=>makeIssue,map:()=>mapType,nan:()=>nanType,nativeEnum:()=>nativeEnumType,never:()=>neverType,null:()=>nullType,nullable:()=>nullableType,number:()=>numberType,object:()=>objectType,objectUtil:()=>objectUtil,oboolean:()=>oboolean,onumber:()=>onumber,optional:()=>optionalType,ostring:()=>ostring,pipeline:()=>pipelineType,preprocess:()=>preprocessType,promise:()=>promiseType,quotelessJson:()=>quotelessJson,record:()=>recordType,set:()=>setType,setErrorMap:()=>setErrorMap,strictObject:()=>strictObjectType,string:()=>stringType,symbol:()=>symbolType,transformer:()=>effectsType,tuple:()=>tupleType,undefined:()=>undefinedType,union:()=>unionType,unknown:()=>unknownType,util:()=>util,void:()=>voidType});var util;(function(util2){util2.assertEqual=_=>{};function assertIs(_arg){}util2.assertIs=assertIs;function assertNever(_x){throw new Error}util2.assertNever=assertNever,util2.arrayToEnum=items=>{let obj={};for(let item of items)obj[item]=item;return obj},util2.getValidEnumValues=obj=>{let validKeys=util2.objectKeys(obj).filter(k=>typeof obj[obj[k]]!="number"),filtered={};for(let k of validKeys)filtered[k]=obj[k];return util2.objectValues(filtered)},util2.objectValues=obj=>util2.objectKeys(obj).map(function(e){return obj[e]}),util2.objectKeys=typeof Object.keys=="function"?obj=>Object.keys(obj):object=>{let keys=[];for(let key in object)Object.prototype.hasOwnProperty.call(object,key)&&keys.push(key);return keys},util2.find=(arr,checker)=>{for(let item of arr)if(checker(item))return item},util2.isInteger=typeof Number.isInteger=="function"?val=>Number.isInteger(val):val=>typeof val=="number"&&Number.isFinite(val)&&Math.floor(val)===val;function joinValues(array,separator=" | "){return array.map(val=>typeof val=="string"?`'${val}'`:val).join(separator)}util2.joinValues=joinValues,util2.jsonStringifyReplacer=(_,value)=>typeof value=="bigint"?value.toString():value})(util||(util={}));var objectUtil;(function(objectUtil2){objectUtil2.mergeShapes=(first,second)=>({...first,...second})})(objectUtil||(objectUtil={}));var ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=data=>{switch(typeof data){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(data)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(data)?ZodParsedType.array:data===null?ZodParsedType.null:data.then&&typeof data.then=="function"&&data.catch&&typeof data.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&data instanceof Map?ZodParsedType.map:typeof Set<"u"&&data instanceof Set?ZodParsedType.set:typeof Date<"u"&&data instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}};var ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),quotelessJson=obj=>JSON.stringify(obj,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError=class _ZodError extends Error{get errors(){return this.issues}constructor(issues){super(),this.issues=[],this.addIssue=sub=>{this.issues=[...this.issues,sub]},this.addIssues=(subs=[])=>{this.issues=[...this.issues,...subs]};let actualProto=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,actualProto):this.__proto__=actualProto,this.name="ZodError",this.issues=issues}format(_mapper){let mapper=_mapper||function(issue){return issue.message},fieldErrors={_errors:[]},processError=error=>{for(let issue of error.issues)if(issue.code==="invalid_union")issue.unionErrors.map(processError);else if(issue.code==="invalid_return_type")processError(issue.returnTypeError);else if(issue.code==="invalid_arguments")processError(issue.argumentsError);else if(issue.path.length===0)fieldErrors._errors.push(mapper(issue));else{let curr=fieldErrors,i=0;for(;i<issue.path.length;){let el=issue.path[i];i===issue.path.length-1?(curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue))):curr[el]=curr[el]||{_errors:[]},curr=curr[el],i++}}};return processError(this),fieldErrors}static assert(value){if(!(value instanceof _ZodError))throw new Error(`Not a ZodError: ${value}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(mapper=issue=>issue.message){let fieldErrors={},formErrors=[];for(let sub of this.issues)if(sub.path.length>0){let firstEl=sub.path[0];fieldErrors[firstEl]=fieldErrors[firstEl]||[],fieldErrors[firstEl].push(mapper(sub))}else formErrors.push(mapper(sub));return{formErrors,fieldErrors}}get formErrors(){return this.flatten()}};ZodError.create=issues=>new ZodError(issues);var errorMap=(issue,_ctx)=>{let message;switch(issue.code){case ZodIssueCode.invalid_type:issue.received===ZodParsedType.undefined?message="Required":message=`Expected ${issue.expected}, received ${issue.received}`;break;case ZodIssueCode.invalid_literal:message=`Invalid literal value, expected ${JSON.stringify(issue.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:message=`Unrecognized key(s) in object: ${util.joinValues(issue.keys,", ")}`;break;case ZodIssueCode.invalid_union:message="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:message=`Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;break;case ZodIssueCode.invalid_enum_value:message=`Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;break;case ZodIssueCode.invalid_arguments:message="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:message="Invalid function return type";break;case ZodIssueCode.invalid_date:message="Invalid date";break;case ZodIssueCode.invalid_string:typeof issue.validation=="object"?"includes"in issue.validation?(message=`Invalid input: must include "${issue.validation.includes}"`,typeof issue.validation.position=="number"&&(message=`${message} at one or more positions greater than or equal to ${issue.validation.position}`)):"startsWith"in issue.validation?message=`Invalid input: must start with "${issue.validation.startsWith}"`:"endsWith"in issue.validation?message=`Invalid input: must end with "${issue.validation.endsWith}"`:util.assertNever(issue.validation):issue.validation!=="regex"?message=`Invalid ${issue.validation}`:message="Invalid";break;case ZodIssueCode.too_small:issue.type==="array"?message=`Array must contain ${issue.exact?"exactly":issue.inclusive?"at least":"more than"} ${issue.minimum} element(s)`:issue.type==="string"?message=`String must contain ${issue.exact?"exactly":issue.inclusive?"at least":"over"} ${issue.minimum} character(s)`:issue.type==="number"?message=`Number must be ${issue.exact?"exactly equal to ":issue.inclusive?"greater than or equal to ":"greater than "}${issue.minimum}`:issue.type==="bigint"?message=`Number must be ${issue.exact?"exactly equal to ":issue.inclusive?"greater than or equal to ":"greater than "}${issue.minimum}`:issue.type==="date"?message=`Date must be ${issue.exact?"exactly equal to ":issue.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(issue.minimum))}`:message="Invalid input";break;case ZodIssueCode.too_big:issue.type==="array"?message=`Array must contain ${issue.exact?"exactly":issue.inclusive?"at most":"less than"} ${issue.maximum} element(s)`:issue.type==="string"?message=`String must contain ${issue.exact?"exactly":issue.inclusive?"at most":"under"} ${issue.maximum} character(s)`:issue.type==="number"?message=`Number must be ${issue.exact?"exactly":issue.inclusive?"less than or equal to":"less than"} ${issue.maximum}`:issue.type==="bigint"?message=`BigInt must be ${issue.exact?"exactly":issue.inclusive?"less than or equal to":"less than"} ${issue.maximum}`:issue.type==="date"?message=`Date must be ${issue.exact?"exactly":issue.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(issue.maximum))}`:message="Invalid input";break;case ZodIssueCode.custom:message="Invalid input";break;case ZodIssueCode.invalid_intersection_types:message="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:message=`Number must be a multiple of ${issue.multipleOf}`;break;case ZodIssueCode.not_finite:message="Number must be finite";break;default:message=_ctx.defaultError,util.assertNever(issue)}return{message}},en_default=errorMap;var overrideErrorMap=en_default;function setErrorMap(map){overrideErrorMap=map}function getErrorMap(){return overrideErrorMap}var makeIssue=params=>{let{data,path:path2,errorMaps,issueData}=params,fullPath=[...path2,...issueData.path||[]],fullIssue={...issueData,path:fullPath};if(issueData.message!==void 0)return{...issueData,path:fullPath,message:issueData.message};let errorMessage="",maps=errorMaps.filter(m=>!!m).slice().reverse();for(let map of maps)errorMessage=map(fullIssue,{data,defaultError:errorMessage}).message;return{...issueData,path:fullPath,message:errorMessage}},EMPTY_PATH=[];function addIssueToContext(ctx,issueData){let overrideMap=getErrorMap(),issue=makeIssue({issueData,data:ctx.data,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,overrideMap,overrideMap===en_default?void 0:en_default].filter(x=>!!x)});ctx.common.issues.push(issue)}var ParseStatus=class _ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(status,results){let arrayValue=[];for(let s of results){if(s.status==="aborted")return INVALID;s.status==="dirty"&&status.dirty(),arrayValue.push(s.value)}return{status:status.value,value:arrayValue}}static async mergeObjectAsync(status,pairs){let syncPairs=[];for(let pair of pairs){let key=await pair.key,value=await pair.value;syncPairs.push({key,value})}return _ParseStatus.mergeObjectSync(status,syncPairs)}static mergeObjectSync(status,pairs){let finalObject={};for(let pair of pairs){let{key,value}=pair;if(key.status==="aborted"||value.status==="aborted")return INVALID;key.status==="dirty"&&status.dirty(),value.status==="dirty"&&status.dirty(),key.value!=="__proto__"&&(typeof value.value<"u"||pair.alwaysSet)&&(finalObject[key.value]=value.value)}return{status:status.value,value:finalObject}}},INVALID=Object.freeze({status:"aborted"}),DIRTY=value=>({status:"dirty",value}),OK=value=>({status:"valid",value}),isAborted=x=>x.status==="aborted",isDirty=x=>x.status==="dirty",isValid=x=>x.status==="valid",isAsync=x=>typeof Promise<"u"&&x instanceof Promise;var errorUtil;(function(errorUtil2){errorUtil2.errToObj=message=>typeof message=="string"?{message}:message||{},errorUtil2.toString=message=>typeof message=="string"?message:message?.message})(errorUtil||(errorUtil={}));var ParseInputLazyPath=class{constructor(parent,value,path2,key){this._cachedPath=[],this.parent=parent,this.data=value,this._path=path2,this._key=key}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},handleResult=(ctx,result)=>{if(isValid(result))return{success:!0,data:result.value};if(!ctx.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let error=new ZodError(ctx.common.issues);return this._error=error,this._error}}};function processCreateParams(params){if(!params)return{};let{errorMap:errorMap2,invalid_type_error,required_error,description}=params;if(errorMap2&&(invalid_type_error||required_error))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return errorMap2?{errorMap:errorMap2,description}:{errorMap:(iss,ctx)=>{let{message}=params;return iss.code==="invalid_enum_value"?{message:message??ctx.defaultError}:typeof ctx.data>"u"?{message:message??required_error??ctx.defaultError}:iss.code!=="invalid_type"?{message:ctx.defaultError}:{message:message??invalid_type_error??ctx.defaultError}},description}}var ZodType=class{get description(){return this._def.description}_getType(input){return getParsedType(input.data)}_getOrReturnCtx(input,ctx){return ctx||{common:input.parent.common,data:input.data,parsedType:getParsedType(input.data),schemaErrorMap:this._def.errorMap,path:input.path,parent:input.parent}}_processInputParams(input){return{status:new ParseStatus,ctx:{common:input.parent.common,data:input.data,parsedType:getParsedType(input.data),schemaErrorMap:this._def.errorMap,path:input.path,parent:input.parent}}}_parseSync(input){let result=this._parse(input);if(isAsync(result))throw new Error("Synchronous parse encountered promise.");return result}_parseAsync(input){let result=this._parse(input);return Promise.resolve(result)}parse(data,params){let result=this.safeParse(data,params);if(result.success)return result.data;throw result.error}safeParse(data,params){let ctx={common:{issues:[],async:params?.async??!1,contextualErrorMap:params?.errorMap},path:params?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data,parsedType:getParsedType(data)},result=this._parseSync({data,path:ctx.path,parent:ctx});return handleResult(ctx,result)}"~validate"(data){let ctx={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data,parsedType:getParsedType(data)};if(!this["~standard"].async)try{let result=this._parseSync({data,path:[],parent:ctx});return isValid(result)?{value:result.value}:{issues:ctx.common.issues}}catch(err){err?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),ctx.common={issues:[],async:!0}}return this._parseAsync({data,path:[],parent:ctx}).then(result=>isValid(result)?{value:result.value}:{issues:ctx.common.issues})}async parseAsync(data,params){let result=await this.safeParseAsync(data,params);if(result.success)return result.data;throw result.error}async safeParseAsync(data,params){let ctx={common:{issues:[],contextualErrorMap:params?.errorMap,async:!0},path:params?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data,parsedType:getParsedType(data)},maybeAsyncResult=this._parse({data,path:ctx.path,parent:ctx}),result=await(isAsync(maybeAsyncResult)?maybeAsyncResult:Promise.resolve(maybeAsyncResult));return handleResult(ctx,result)}refine(check,message){let getIssueProperties=val=>typeof message=="string"||typeof message>"u"?{message}:typeof message=="function"?message(val):message;return this._refinement((val,ctx)=>{let result=check(val),setError=()=>ctx.addIssue({code:ZodIssueCode.custom,...getIssueProperties(val)});return typeof Promise<"u"&&result instanceof Promise?result.then(data=>data?!0:(setError(),!1)):result?!0:(setError(),!1)})}refinement(check,refinementData){return this._refinement((val,ctx)=>check(val)?!0:(ctx.addIssue(typeof refinementData=="function"?refinementData(val,ctx):refinementData),!1))}_refinement(refinement){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement}})}superRefine(refinement){return this._refinement(refinement)}constructor(def){this.spa=this.safeParseAsync,this._def=def,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:data=>this["~validate"](data)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(option){return ZodUnion.create([this,option],this._def)}and(incoming){return ZodIntersection.create(this,incoming,this._def)}transform(transform){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform}})}default(def){let defaultValueFunc=typeof def=="function"?def:()=>def;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:defaultValueFunc,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(def){let catchValueFunc=typeof def=="function"?def:()=>def;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:catchValueFunc,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(description){let This=this.constructor;return new This({...this._def,description})}pipe(target){return ZodPipeline.create(this,target)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",emojiRegex,ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(args){let secondsRegexSource="[0-5]\\d";args.precision?secondsRegexSource=`${secondsRegexSource}\\.\\d{${args.precision}}`:args.precision==null&&(secondsRegexSource=`${secondsRegexSource}(\\.\\d+)?`);let secondsQuantifier=args.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`}function timeRegex(args){return new RegExp(`^${timeRegexSource(args)}$`)}function datetimeRegex(args){let regex=`${dateRegexSource}T${timeRegexSource(args)}`,opts=[];return opts.push(args.local?"Z?":"Z"),args.offset&&opts.push("([+-]\\d{2}:?\\d{2})"),regex=`${regex}(${opts.join("|")})`,new RegExp(`^${regex}$`)}function isValidIP(ip,version){return!!((version==="v4"||!version)&&ipv4Regex.test(ip)||(version==="v6"||!version)&&ipv6Regex.test(ip))}function isValidJWT(jwt,alg){if(!jwtRegex.test(jwt))return!1;try{let[header]=jwt.split(".");if(!header)return!1;let base64=header.replace(/-/g,"+").replace(/_/g,"/").padEnd(header.length+(4-header.length%4)%4,"="),decoded=JSON.parse(atob(base64));return!(typeof decoded!="object"||decoded===null||"typ"in decoded&&decoded?.typ!=="JWT"||!decoded.alg||alg&&decoded.alg!==alg)}catch{return!1}}function isValidCidr(ip,version){return!!((version==="v4"||!version)&&ipv4CidrRegex.test(ip)||(version==="v6"||!version)&&ipv6CidrRegex.test(ip))}var ZodString=class _ZodString extends ZodType{_parse(input){if(this._def.coerce&&(input.data=String(input.data)),this._getType(input)!==ZodParsedType.string){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:ctx2.parsedType}),INVALID}let status=new ParseStatus,ctx;for(let check of this._def.checks)if(check.kind==="min")input.data.length<check.value&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"string",inclusive:!0,exact:!1,message:check.message}),status.dirty());else if(check.kind==="max")input.data.length>check.value&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"string",inclusive:!0,exact:!1,message:check.message}),status.dirty());else if(check.kind==="length"){let tooBig=input.data.length>check.value,tooSmall=input.data.length<check.value;(tooBig||tooSmall)&&(ctx=this._getOrReturnCtx(input,ctx),tooBig?addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"string",inclusive:!0,exact:!0,message:check.message}):tooSmall&&addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"string",inclusive:!0,exact:!0,message:check.message}),status.dirty())}else if(check.kind==="email")emailRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"email",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty());else if(check.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"emoji",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty());else if(check.kind==="uuid")uuidRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"uuid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty());else if(check.kind==="nanoid")nanoidRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty());else if(check.kind==="cuid")cuidRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"cuid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty());else if(check.kind==="cuid2")cuid2Regex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty());else if(check.kind==="ulid")ulidRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"ulid",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty());else if(check.kind==="url")try{new URL(input.data)}catch{ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"url",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()}else check.kind==="regex"?(check.regex.lastIndex=0,check.regex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"regex",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty())):check.kind==="trim"?input.data=input.data.trim():check.kind==="includes"?input.data.includes(check.value,check.position)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{includes:check.value,position:check.position},message:check.message}),status.dirty()):check.kind==="toLowerCase"?input.data=input.data.toLowerCase():check.kind==="toUpperCase"?input.data=input.data.toUpperCase():check.kind==="startsWith"?input.data.startsWith(check.value)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{startsWith:check.value},message:check.message}),status.dirty()):check.kind==="endsWith"?input.data.endsWith(check.value)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{endsWith:check.value},message:check.message}),status.dirty()):check.kind==="datetime"?datetimeRegex(check).test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"datetime",message:check.message}),status.dirty()):check.kind==="date"?dateRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"date",message:check.message}),status.dirty()):check.kind==="time"?timeRegex(check).test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"time",message:check.message}),status.dirty()):check.kind==="duration"?durationRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"duration",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()):check.kind==="ip"?isValidIP(input.data,check.version)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"ip",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()):check.kind==="jwt"?isValidJWT(input.data,check.alg)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"jwt",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()):check.kind==="cidr"?isValidCidr(input.data,check.version)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"cidr",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()):check.kind==="base64"?base64Regex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"base64",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()):check.kind==="base64url"?base64urlRegex.test(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{validation:"base64url",code:ZodIssueCode.invalid_string,message:check.message}),status.dirty()):util.assertNever(check);return{status:status.value,value:input.data}}_regex(regex,validation,message){return this.refinement(data=>regex.test(data),{validation,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(message)})}_addCheck(check){return new _ZodString({...this._def,checks:[...this._def.checks,check]})}email(message){return this._addCheck({kind:"email",...errorUtil.errToObj(message)})}url(message){return this._addCheck({kind:"url",...errorUtil.errToObj(message)})}emoji(message){return this._addCheck({kind:"emoji",...errorUtil.errToObj(message)})}uuid(message){return this._addCheck({kind:"uuid",...errorUtil.errToObj(message)})}nanoid(message){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(message)})}cuid(message){return this._addCheck({kind:"cuid",...errorUtil.errToObj(message)})}cuid2(message){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(message)})}ulid(message){return this._addCheck({kind:"ulid",...errorUtil.errToObj(message)})}base64(message){return this._addCheck({kind:"base64",...errorUtil.errToObj(message)})}base64url(message){return this._addCheck({kind:"base64url",...errorUtil.errToObj(message)})}jwt(options){return this._addCheck({kind:"jwt",...errorUtil.errToObj(options)})}ip(options){return this._addCheck({kind:"ip",...errorUtil.errToObj(options)})}cidr(options){return this._addCheck({kind:"cidr",...errorUtil.errToObj(options)})}datetime(options){return typeof options=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:options}):this._addCheck({kind:"datetime",precision:typeof options?.precision>"u"?null:options?.precision,offset:options?.offset??!1,local:options?.local??!1,...errorUtil.errToObj(options?.message)})}date(message){return this._addCheck({kind:"date",message})}time(options){return typeof options=="string"?this._addCheck({kind:"time",precision:null,message:options}):this._addCheck({kind:"time",precision:typeof options?.precision>"u"?null:options?.precision,...errorUtil.errToObj(options?.message)})}duration(message){return this._addCheck({kind:"duration",...errorUtil.errToObj(message)})}regex(regex,message){return this._addCheck({kind:"regex",regex,...errorUtil.errToObj(message)})}includes(value,options){return this._addCheck({kind:"includes",value,position:options?.position,...errorUtil.errToObj(options?.message)})}startsWith(value,message){return this._addCheck({kind:"startsWith",value,...errorUtil.errToObj(message)})}endsWith(value,message){return this._addCheck({kind:"endsWith",value,...errorUtil.errToObj(message)})}min(minLength,message){return this._addCheck({kind:"min",value:minLength,...errorUtil.errToObj(message)})}max(maxLength,message){return this._addCheck({kind:"max",value:maxLength,...errorUtil.errToObj(message)})}length(len,message){return this._addCheck({kind:"length",value:len,...errorUtil.errToObj(message)})}nonempty(message){return this.min(1,errorUtil.errToObj(message))}trim(){return new _ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new _ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new _ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(ch=>ch.kind==="datetime")}get isDate(){return!!this._def.checks.find(ch=>ch.kind==="date")}get isTime(){return!!this._def.checks.find(ch=>ch.kind==="time")}get isDuration(){return!!this._def.checks.find(ch=>ch.kind==="duration")}get isEmail(){return!!this._def.checks.find(ch=>ch.kind==="email")}get isURL(){return!!this._def.checks.find(ch=>ch.kind==="url")}get isEmoji(){return!!this._def.checks.find(ch=>ch.kind==="emoji")}get isUUID(){return!!this._def.checks.find(ch=>ch.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(ch=>ch.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(ch=>ch.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(ch=>ch.kind==="cuid2")}get isULID(){return!!this._def.checks.find(ch=>ch.kind==="ulid")}get isIP(){return!!this._def.checks.find(ch=>ch.kind==="ip")}get isCIDR(){return!!this._def.checks.find(ch=>ch.kind==="cidr")}get isBase64(){return!!this._def.checks.find(ch=>ch.kind==="base64")}get isBase64url(){return!!this._def.checks.find(ch=>ch.kind==="base64url")}get minLength(){let min=null;for(let ch of this._def.checks)ch.kind==="min"&&(min===null||ch.value>min)&&(min=ch.value);return min}get maxLength(){let max=null;for(let ch of this._def.checks)ch.kind==="max"&&(max===null||ch.value<max)&&(max=ch.value);return max}};ZodString.create=params=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:params?.coerce??!1,...processCreateParams(params)});function floatSafeRemainder(val,step){let valDecCount=(val.toString().split(".")[1]||"").length,stepDecCount=(step.toString().split(".")[1]||"").length,decCount=valDecCount>stepDecCount?valDecCount:stepDecCount,valInt=Number.parseInt(val.toFixed(decCount).replace(".","")),stepInt=Number.parseInt(step.toFixed(decCount).replace(".",""));return valInt%stepInt/10**decCount}var ZodNumber=class _ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(input){if(this._def.coerce&&(input.data=Number(input.data)),this._getType(input)!==ZodParsedType.number){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:ctx2.parsedType}),INVALID}let ctx,status=new ParseStatus;for(let check of this._def.checks)check.kind==="int"?util.isInteger(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:check.message}),status.dirty()):check.kind==="min"?(check.inclusive?input.data<check.value:input.data<=check.value)&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"number",inclusive:check.inclusive,exact:!1,message:check.message}),status.dirty()):check.kind==="max"?(check.inclusive?input.data>check.value:input.data>=check.value)&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"number",inclusive:check.inclusive,exact:!1,message:check.message}),status.dirty()):check.kind==="multipleOf"?floatSafeRemainder(input.data,check.value)!==0&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check.value,message:check.message}),status.dirty()):check.kind==="finite"?Number.isFinite(input.data)||(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.not_finite,message:check.message}),status.dirty()):util.assertNever(check);return{status:status.value,value:input.data}}gte(value,message){return this.setLimit("min",value,!0,errorUtil.toString(message))}gt(value,message){return this.setLimit("min",value,!1,errorUtil.toString(message))}lte(value,message){return this.setLimit("max",value,!0,errorUtil.toString(message))}lt(value,message){return this.setLimit("max",value,!1,errorUtil.toString(message))}setLimit(kind,value,inclusive,message){return new _ZodNumber({...this._def,checks:[...this._def.checks,{kind,value,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check){return new _ZodNumber({...this._def,checks:[...this._def.checks,check]})}int(message){return this._addCheck({kind:"int",message:errorUtil.toString(message)})}positive(message){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(message)})}negative(message){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(message)})}nonpositive(message){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(message)})}nonnegative(message){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(message)})}multipleOf(value,message){return this._addCheck({kind:"multipleOf",value,message:errorUtil.toString(message)})}finite(message){return this._addCheck({kind:"finite",message:errorUtil.toString(message)})}safe(message){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(message)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(message)})}get minValue(){let min=null;for(let ch of this._def.checks)ch.kind==="min"&&(min===null||ch.value>min)&&(min=ch.value);return min}get maxValue(){let max=null;for(let ch of this._def.checks)ch.kind==="max"&&(max===null||ch.value<max)&&(max=ch.value);return max}get isInt(){return!!this._def.checks.find(ch=>ch.kind==="int"||ch.kind==="multipleOf"&&util.isInteger(ch.value))}get isFinite(){let max=null,min=null;for(let ch of this._def.checks){if(ch.kind==="finite"||ch.kind==="int"||ch.kind==="multipleOf")return!0;ch.kind==="min"?(min===null||ch.value>min)&&(min=ch.value):ch.kind==="max"&&(max===null||ch.value<max)&&(max=ch.value)}return Number.isFinite(min)&&Number.isFinite(max)}};ZodNumber.create=params=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:params?.coerce||!1,...processCreateParams(params)});var ZodBigInt=class _ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(input){if(this._def.coerce)try{input.data=BigInt(input.data)}catch{return this._getInvalidInput(input)}if(this._getType(input)!==ZodParsedType.bigint)return this._getInvalidInput(input);let ctx,status=new ParseStatus;for(let check of this._def.checks)check.kind==="min"?(check.inclusive?input.data<check.value:input.data<=check.value)&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,type:"bigint",minimum:check.value,inclusive:check.inclusive,message:check.message}),status.dirty()):check.kind==="max"?(check.inclusive?input.data>check.value:input.data>=check.value)&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,type:"bigint",maximum:check.value,inclusive:check.inclusive,message:check.message}),status.dirty()):check.kind==="multipleOf"?input.data%check.value!==BigInt(0)&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check.value,message:check.message}),status.dirty()):util.assertNever(check);return{status:status.value,value:input.data}}_getInvalidInput(input){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:ctx.parsedType}),INVALID}gte(value,message){return this.setLimit("min",value,!0,errorUtil.toString(message))}gt(value,message){return this.setLimit("min",value,!1,errorUtil.toString(message))}lte(value,message){return this.setLimit("max",value,!0,errorUtil.toString(message))}lt(value,message){return this.setLimit("max",value,!1,errorUtil.toString(message))}setLimit(kind,value,inclusive,message){return new _ZodBigInt({...this._def,checks:[...this._def.checks,{kind,value,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check){return new _ZodBigInt({...this._def,checks:[...this._def.checks,check]})}positive(message){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(message)})}negative(message){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(message)})}nonpositive(message){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(message)})}nonnegative(message){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(message)})}multipleOf(value,message){return this._addCheck({kind:"multipleOf",value,message:errorUtil.toString(message)})}get minValue(){let min=null;for(let ch of this._def.checks)ch.kind==="min"&&(min===null||ch.value>min)&&(min=ch.value);return min}get maxValue(){let max=null;for(let ch of this._def.checks)ch.kind==="max"&&(max===null||ch.value<max)&&(max=ch.value);return max}};ZodBigInt.create=params=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:params?.coerce??!1,...processCreateParams(params)});var ZodBoolean=class extends ZodType{_parse(input){if(this._def.coerce&&(input.data=!!input.data),this._getType(input)!==ZodParsedType.boolean){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:ctx.parsedType}),INVALID}return OK(input.data)}};ZodBoolean.create=params=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:params?.coerce||!1,...processCreateParams(params)});var ZodDate=class _ZodDate extends ZodType{_parse(input){if(this._def.coerce&&(input.data=new Date(input.data)),this._getType(input)!==ZodParsedType.date){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:ctx2.parsedType}),INVALID}if(Number.isNaN(input.data.getTime())){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_date}),INVALID}let status=new ParseStatus,ctx;for(let check of this._def.checks)check.kind==="min"?input.data.getTime()<check.value&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_small,message:check.message,inclusive:!0,exact:!1,minimum:check.value,type:"date"}),status.dirty()):check.kind==="max"?input.data.getTime()>check.value&&(ctx=this._getOrReturnCtx(input,ctx),addIssueToContext(ctx,{code:ZodIssueCode.too_big,message:check.message,inclusive:!0,exact:!1,maximum:check.value,type:"date"}),status.dirty()):util.assertNever(check);return{status:status.value,value:new Date(input.data.getTime())}}_addCheck(check){return new _ZodDate({...this._def,checks:[...this._def.checks,check]})}min(minDate,message){return this._addCheck({kind:"min",value:minDate.getTime(),message:errorUtil.toString(message)})}max(maxDate,message){return this._addCheck({kind:"max",value:maxDate.getTime(),message:errorUtil.toString(message)})}get minDate(){let min=null;for(let ch of this._def.checks)ch.kind==="min"&&(min===null||ch.value>min)&&(min=ch.value);return min!=null?new Date(min):null}get maxDate(){let max=null;for(let ch of this._def.checks)ch.kind==="max"&&(max===null||ch.value<max)&&(max=ch.value);return max!=null?new Date(max):null}};ZodDate.create=params=>new ZodDate({checks:[],coerce:params?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(params)});var ZodSymbol=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.symbol){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:ctx.parsedType}),INVALID}return OK(input.data)}};ZodSymbol.create=params=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(params)});var ZodUndefined=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.undefined){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:ctx.parsedType}),INVALID}return OK(input.data)}};ZodUndefined.create=params=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(params)});var ZodNull=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.null){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:ctx.parsedType}),INVALID}return OK(input.data)}};ZodNull.create=params=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(params)});var ZodAny=class extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(input){return OK(input.data)}};ZodAny.create=params=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(params)});var ZodUnknown=class extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(input){return OK(input.data)}};ZodUnknown.create=params=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(params)});var ZodNever=class extends ZodType{_parse(input){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:ctx.parsedType}),INVALID}};ZodNever.create=params=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(params)});var ZodVoid=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.undefined){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:ctx.parsedType}),INVALID}return OK(input.data)}};ZodVoid.create=params=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(params)});var ZodArray=class _ZodArray extends ZodType{_parse(input){let{ctx,status}=this._processInputParams(input),def=this._def;if(ctx.parsedType!==ZodParsedType.array)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:ctx.parsedType}),INVALID;if(def.exactLength!==null){let tooBig=ctx.data.length>def.exactLength.value,tooSmall=ctx.data.length<def.exactLength.value;(tooBig||tooSmall)&&(addIssueToContext(ctx,{code:tooBig?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:tooSmall?def.exactLength.value:void 0,maximum:tooBig?def.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:def.exactLength.message}),status.dirty())}if(def.minLength!==null&&ctx.data.length<def.minLength.value&&(addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:def.minLength.value,type:"array",inclusive:!0,exact:!1,message:def.minLength.message}),status.dirty()),def.maxLength!==null&&ctx.data.length>def.maxLength.value&&(addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:def.maxLength.value,type:"array",inclusive:!0,exact:!1,message:def.maxLength.message}),status.dirty()),ctx.common.async)return Promise.all([...ctx.data].map((item,i)=>def.type._parseAsync(new ParseInputLazyPath(ctx,item,ctx.path,i)))).then(result2=>ParseStatus.mergeArray(status,result2));let result=[...ctx.data].map((item,i)=>def.type._parseSync(new ParseInputLazyPath(ctx,item,ctx.path,i)));return ParseStatus.mergeArray(status,result)}get element(){return this._def.type}min(minLength,message){return new _ZodArray({...this._def,minLength:{value:minLength,message:errorUtil.toString(message)}})}max(maxLength,message){return new _ZodArray({...this._def,maxLength:{value:maxLength,message:errorUtil.toString(message)}})}length(len,message){return new _ZodArray({...this._def,exactLength:{value:len,message:errorUtil.toString(message)}})}nonempty(message){return this.min(1,message)}};ZodArray.create=(schema,params)=>new ZodArray({type:schema,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(params)});function deepPartialify(schema){if(schema instanceof ZodObject){let newShape={};for(let key in schema.shape){let fieldSchema=schema.shape[key];newShape[key]=ZodOptional.create(deepPartialify(fieldSchema))}return new ZodObject({...schema._def,shape:()=>newShape})}else return schema instanceof ZodArray?new ZodArray({...schema._def,type:deepPartialify(schema.element)}):schema instanceof ZodOptional?ZodOptional.create(deepPartialify(schema.unwrap())):schema instanceof ZodNullable?ZodNullable.create(deepPartialify(schema.unwrap())):schema instanceof ZodTuple?ZodTuple.create(schema.items.map(item=>deepPartialify(item))):schema}var ZodObject=class _ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let shape=this._def.shape(),keys=util.objectKeys(shape);return this._cached={shape,keys},this._cached}_parse(input){if(this._getType(input)!==ZodParsedType.object){let ctx2=this._getOrReturnCtx(input);return addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx2.parsedType}),INVALID}let{status,ctx}=this._processInputParams(input),{shape,keys:shapeKeys}=this._getCached(),extraKeys=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(let key in ctx.data)shapeKeys.includes(key)||extraKeys.push(key);let pairs=[];for(let key of shapeKeys){let keyValidator=shape[key],value=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:keyValidator._parse(new ParseInputLazyPath(ctx,value,ctx.path,key)),alwaysSet:key in ctx.data})}if(this._def.catchall instanceof ZodNever){let unknownKeys=this._def.unknownKeys;if(unknownKeys==="passthrough")for(let key of extraKeys)pairs.push({key:{status:"valid",value:key},value:{status:"valid",value:ctx.data[key]}});else if(unknownKeys==="strict")extraKeys.length>0&&(addIssueToContext(ctx,{code:ZodIssueCode.unrecognized_keys,keys:extraKeys}),status.dirty());else if(unknownKeys!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let catchall=this._def.catchall;for(let key of extraKeys){let value=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:catchall._parse(new ParseInputLazyPath(ctx,value,ctx.path,key)),alwaysSet:key in ctx.data})}}return ctx.common.async?Promise.resolve().then(async()=>{let syncPairs=[];for(let pair of pairs){let key=await pair.key,value=await pair.value;syncPairs.push({key,value,alwaysSet:pair.alwaysSet})}return syncPairs}).then(syncPairs=>ParseStatus.mergeObjectSync(status,syncPairs)):ParseStatus.mergeObjectSync(status,pairs)}get shape(){return this._def.shape()}strict(message){return errorUtil.errToObj,new _ZodObject({...this._def,unknownKeys:"strict",...message!==void 0?{errorMap:(issue,ctx)=>{let defaultError=this._def.errorMap?.(issue,ctx).message??ctx.defaultError;return issue.code==="unrecognized_keys"?{message:errorUtil.errToObj(message).message??defaultError}:{message:defaultError}}}:{}})}strip(){return new _ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new _ZodObject({...this._def,unknownKeys:"passthrough"})}extend(augmentation){return new _ZodObject({...this._def,shape:()=>({...this._def.shape(),...augmentation})})}merge(merging){return new _ZodObject({unknownKeys:merging._def.unknownKeys,catchall:merging._def.catchall,shape:()=>({...this._def.shape(),...merging._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(key,schema){return this.augment({[key]:schema})}catchall(index){return new _ZodObject({...this._def,catchall:index})}pick(mask){let shape={};for(let key of util.objectKeys(mask))mask[key]&&this.shape[key]&&(shape[key]=this.shape[key]);return new _ZodObject({...this._def,shape:()=>shape})}omit(mask){let shape={};for(let key of util.objectKeys(this.shape))mask[key]||(shape[key]=this.shape[key]);return new _ZodObject({...this._def,shape:()=>shape})}deepPartial(){return deepPartialify(this)}partial(mask){let newShape={};for(let key of util.objectKeys(this.shape)){let fieldSchema=this.shape[key];mask&&!mask[key]?newShape[key]=fieldSchema:newShape[key]=fieldSchema.optional()}return new _ZodObject({...this._def,shape:()=>newShape})}required(mask){let newShape={};for(let key of util.objectKeys(this.shape))if(mask&&!mask[key])newShape[key]=this.shape[key];else{let newField=this.shape[key];for(;newField instanceof ZodOptional;)newField=newField._def.innerType;newShape[key]=newField}return new _ZodObject({...this._def,shape:()=>newShape})}keyof(){return createZodEnum(util.objectKeys(this.shape))}};ZodObject.create=(shape,params)=>new ZodObject({shape:()=>shape,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)});ZodObject.strictCreate=(shape,params)=>new ZodObject({shape:()=>shape,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)});ZodObject.lazycreate=(shape,params)=>new ZodObject({shape,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)});var ZodUnion=class extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),options=this._def.options;function handleResults(results){for(let result of results)if(result.result.status==="valid")return result.result;for(let result of results)if(result.result.status==="dirty")return ctx.common.issues.push(...result.ctx.common.issues),result.result;let unionErrors=results.map(result=>new ZodError(result.ctx.common.issues));return addIssueToContext(ctx,{code:ZodIssueCode.invalid_union,unionErrors}),INVALID}if(ctx.common.async)return Promise.all(options.map(async option=>{let childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null};return{result:await option._parseAsync({data:ctx.data,path:ctx.path,parent:childCtx}),ctx:childCtx}})).then(handleResults);{let dirty,issues=[];for(let option of options){let childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null},result=option._parseSync({data:ctx.data,path:ctx.path,parent:childCtx});if(result.status==="valid")return result;result.status==="dirty"&&!dirty&&(dirty={result,ctx:childCtx}),childCtx.common.issues.length&&issues.push(childCtx.common.issues)}if(dirty)return ctx.common.issues.push(...dirty.ctx.common.issues),dirty.result;let unionErrors=issues.map(issues2=>new ZodError(issues2));return addIssueToContext(ctx,{code:ZodIssueCode.invalid_union,unionErrors}),INVALID}}get options(){return this._def.options}};ZodUnion.create=(types,params)=>new ZodUnion({options:types,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(params)});var getDiscriminator=type=>type instanceof ZodLazy?getDiscriminator(type.schema):type instanceof ZodEffects?getDiscriminator(type.innerType()):type instanceof ZodLiteral?[type.value]:type instanceof ZodEnum?type.options:type instanceof ZodNativeEnum?util.objectValues(type.enum):type instanceof ZodDefault?getDiscriminator(type._def.innerType):type instanceof ZodUndefined?[void 0]:type instanceof ZodNull?[null]:type instanceof ZodOptional?[void 0,...getDiscriminator(type.unwrap())]:type instanceof ZodNullable?[null,...getDiscriminator(type.unwrap())]:type instanceof ZodBranded||type instanceof ZodReadonly?getDiscriminator(type.unwrap()):type instanceof ZodCatch?getDiscriminator(type._def.innerType):[],ZodDiscriminatedUnion=class _ZodDiscriminatedUnion extends ZodType{_parse(input){let{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.object)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx.parsedType}),INVALID;let discriminator=this.discriminator,discriminatorValue=ctx.data[discriminator],option=this.optionsMap.get(discriminatorValue);return option?ctx.common.async?option._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}):option._parseSync({data:ctx.data,path:ctx.path,parent:ctx}):(addIssueToContext(ctx,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[discriminator]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(discriminator,options,params){let optionsMap=new Map;for(let type of options){let discriminatorValues=getDiscriminator(type.shape[discriminator]);if(!discriminatorValues.length)throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);for(let value of discriminatorValues){if(optionsMap.has(value))throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);optionsMap.set(value,type)}}return new _ZodDiscriminatedUnion({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator,options,optionsMap,...processCreateParams(params)})}};function mergeValues(a,b){let aType=getParsedType(a),bType=getParsedType(b);if(a===b)return{valid:!0,data:a};if(aType===ZodParsedType.object&&bType===ZodParsedType.object){let bKeys=util.objectKeys(b),sharedKeys=util.objectKeys(a).filter(key=>bKeys.indexOf(key)!==-1),newObj={...a,...b};for(let key of sharedKeys){let sharedValue=mergeValues(a[key],b[key]);if(!sharedValue.valid)return{valid:!1};newObj[key]=sharedValue.data}return{valid:!0,data:newObj}}else if(aType===ZodParsedType.array&&bType===ZodParsedType.array){if(a.length!==b.length)return{valid:!1};let newArray=[];for(let index=0;index<a.length;index++){let itemA=a[index],itemB=b[index],sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid)return{valid:!1};newArray.push(sharedValue.data)}return{valid:!0,data:newArray}}else return aType===ZodParsedType.date&&bType===ZodParsedType.date&&+a==+b?{valid:!0,data:a}:{valid:!1}}var ZodIntersection=class extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input),handleParsed=(parsedLeft,parsedRight)=>{if(isAborted(parsedLeft)||isAborted(parsedRight))return INVALID;let merged=mergeValues(parsedLeft.value,parsedRight.value);return merged.valid?((isDirty(parsedLeft)||isDirty(parsedRight))&&status.dirty(),{status:status.value,value:merged.data}):(addIssueToContext(ctx,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return ctx.common.async?Promise.all([this._def.left._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}),this._def.right._parseAsync({data:ctx.data,path:ctx.path,parent:ctx})]).then(([left,right])=>handleParsed(left,right)):handleParsed(this._def.left._parseSync({data:ctx.data,path:ctx.path,parent:ctx}),this._def.right._parseSync({data:ctx.data,path:ctx.path,parent:ctx}))}};ZodIntersection.create=(left,right,params)=>new ZodIntersection({left,right,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(params)});var ZodTuple=class _ZodTuple extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.array)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:ctx.parsedType}),INVALID;if(ctx.data.length<this._def.items.length)return addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&ctx.data.length>this._def.items.length&&(addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),status.dirty());let items=[...ctx.data].map((item,itemIndex)=>{let schema=this._def.items[itemIndex]||this._def.rest;return schema?schema._parse(new ParseInputLazyPath(ctx,item,ctx.path,itemIndex)):null}).filter(x=>!!x);return ctx.common.async?Promise.all(items).then(results=>ParseStatus.mergeArray(status,results)):ParseStatus.mergeArray(status,items)}get items(){return this._def.items}rest(rest){return new _ZodTuple({...this._def,rest})}};ZodTuple.create=(schemas,params)=>{if(!Array.isArray(schemas))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:schemas,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(params)})};var ZodRecord=class _ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.object)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx.parsedType}),INVALID;let pairs=[],keyType=this._def.keyType,valueType=this._def.valueType;for(let key in ctx.data)pairs.push({key:keyType._parse(new ParseInputLazyPath(ctx,key,ctx.path,key)),value:valueType._parse(new ParseInputLazyPath(ctx,ctx.data[key],ctx.path,key)),alwaysSet:key in ctx.data});return ctx.common.async?ParseStatus.mergeObjectAsync(status,pairs):ParseStatus.mergeObjectSync(status,pairs)}get element(){return this._def.valueType}static create(first,second,third){return second instanceof ZodType?new _ZodRecord({keyType:first,valueType:second,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(third)}):new _ZodRecord({keyType:ZodString.create(),valueType:first,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(second)})}},ZodMap=class extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.map)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:ctx.parsedType}),INVALID;let keyType=this._def.keyType,valueType=this._def.valueType,pairs=[...ctx.data.entries()].map(([key,value],index)=>({key:keyType._parse(new ParseInputLazyPath(ctx,key,ctx.path,[index,"key"])),value:valueType._parse(new ParseInputLazyPath(ctx,value,ctx.path,[index,"value"]))}));if(ctx.common.async){let finalMap=new Map;return Promise.resolve().then(async()=>{for(let pair of pairs){let key=await pair.key,value=await pair.value;if(key.status==="aborted"||value.status==="aborted")return INVALID;(key.status==="dirty"||value.status==="dirty")&&status.dirty(),finalMap.set(key.value,value.value)}return{status:status.value,value:finalMap}})}else{let finalMap=new Map;for(let pair of pairs){let key=pair.key,value=pair.value;if(key.status==="aborted"||value.status==="aborted")return INVALID;(key.status==="dirty"||value.status==="dirty")&&status.dirty(),finalMap.set(key.value,value.value)}return{status:status.value,value:finalMap}}}};ZodMap.create=(keyType,valueType,params)=>new ZodMap({valueType,keyType,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(params)});var ZodSet=class _ZodSet extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.set)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:ctx.parsedType}),INVALID;let def=this._def;def.minSize!==null&&ctx.data.size<def.minSize.value&&(addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:def.minSize.value,type:"set",inclusive:!0,exact:!1,message:def.minSize.message}),status.dirty()),def.maxSize!==null&&ctx.data.size>def.maxSize.value&&(addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:def.maxSize.value,type:"set",inclusive:!0,exact:!1,message:def.maxSize.message}),status.dirty());let valueType=this._def.valueType;function finalizeSet(elements2){let parsedSet=new Set;for(let element of elements2){if(element.status==="aborted")return INVALID;element.status==="dirty"&&status.dirty(),parsedSet.add(element.value)}return{status:status.value,value:parsedSet}}let elements=[...ctx.data.values()].map((item,i)=>valueType._parse(new ParseInputLazyPath(ctx,item,ctx.path,i)));return ctx.common.async?Promise.all(elements).then(elements2=>finalizeSet(elements2)):finalizeSet(elements)}min(minSize,message){return new _ZodSet({...this._def,minSize:{value:minSize,message:errorUtil.toString(message)}})}max(maxSize,message){return new _ZodSet({...this._def,maxSize:{value:maxSize,message:errorUtil.toString(message)}})}size(size,message){return this.min(size,message).max(size,message)}nonempty(message){return this.min(1,message)}};ZodSet.create=(valueType,params)=>new ZodSet({valueType,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(params)});var ZodFunction=class _ZodFunction extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(input){let{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.function)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:ctx.parsedType}),INVALID;function makeArgsIssue(args,error){return makeIssue({data:args,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,getErrorMap(),en_default].filter(x=>!!x),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:error}})}function makeReturnsIssue(returns,error){return makeIssue({data:returns,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,getErrorMap(),en_default].filter(x=>!!x),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:error}})}let params={errorMap:ctx.common.contextualErrorMap},fn=ctx.data;if(this._def.returns instanceof ZodPromise){let me=this;return OK(async function(...args){let error=new ZodError([]),parsedArgs=await me._def.args.parseAsync(args,params).catch(e=>{throw error.addIssue(makeArgsIssue(args,e)),error}),result=await Reflect.apply(fn,this,parsedArgs);return await me._def.returns._def.type.parseAsync(result,params).catch(e=>{throw error.addIssue(makeReturnsIssue(result,e)),error})})}else{let me=this;return OK(function(...args){let parsedArgs=me._def.args.safeParse(args,params);if(!parsedArgs.success)throw new ZodError([makeArgsIssue(args,parsedArgs.error)]);let result=Reflect.apply(fn,this,parsedArgs.data),parsedReturns=me._def.returns.safeParse(result,params);if(!parsedReturns.success)throw new ZodError([makeReturnsIssue(result,parsedReturns.error)]);return parsedReturns.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...items){return new _ZodFunction({...this._def,args:ZodTuple.create(items).rest(ZodUnknown.create())})}returns(returnType){return new _ZodFunction({...this._def,returns:returnType})}implement(func){return this.parse(func)}strictImplement(func){return this.parse(func)}static create(args,returns,params){return new _ZodFunction({args:args||ZodTuple.create([]).rest(ZodUnknown.create()),returns:returns||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(params)})}},ZodLazy=class extends ZodType{get schema(){return this._def.getter()}_parse(input){let{ctx}=this._processInputParams(input);return this._def.getter()._parse({data:ctx.data,path:ctx.path,parent:ctx})}};ZodLazy.create=(getter,params)=>new ZodLazy({getter,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(params)});var ZodLiteral=class extends ZodType{_parse(input){if(input.data!==this._def.value){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:input.data}}get value(){return this._def.value}};ZodLiteral.create=(value,params)=>new ZodLiteral({value,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(params)});function createZodEnum(values,params){return new ZodEnum({values,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(params)})}var ZodEnum=class _ZodEnum extends ZodType{_parse(input){if(typeof input.data!="string"){let ctx=this._getOrReturnCtx(input),expectedValues=this._def.values;return addIssueToContext(ctx,{expected:util.joinValues(expectedValues),received:ctx.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(input.data)){let ctx=this._getOrReturnCtx(input),expectedValues=this._def.values;return addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_enum_value,options:expectedValues}),INVALID}return OK(input.data)}get options(){return this._def.values}get enum(){let enumValues={};for(let val of this._def.values)enumValues[val]=val;return enumValues}get Values(){let enumValues={};for(let val of this._def.values)enumValues[val]=val;return enumValues}get Enum(){let enumValues={};for(let val of this._def.values)enumValues[val]=val;return enumValues}extract(values,newDef=this._def){return _ZodEnum.create(values,{...this._def,...newDef})}exclude(values,newDef=this._def){return _ZodEnum.create(this.options.filter(opt=>!values.includes(opt)),{...this._def,...newDef})}};ZodEnum.create=createZodEnum;var ZodNativeEnum=class extends ZodType{_parse(input){let nativeEnumValues=util.getValidEnumValues(this._def.values),ctx=this._getOrReturnCtx(input);if(ctx.parsedType!==ZodParsedType.string&&ctx.parsedType!==ZodParsedType.number){let expectedValues=util.objectValues(nativeEnumValues);return addIssueToContext(ctx,{expected:util.joinValues(expectedValues),received:ctx.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(input.data)){let expectedValues=util.objectValues(nativeEnumValues);return addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_enum_value,options:expectedValues}),INVALID}return OK(input.data)}get enum(){return this._def.values}};ZodNativeEnum.create=(values,params)=>new ZodNativeEnum({values,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(params)});var ZodPromise=class extends ZodType{unwrap(){return this._def.type}_parse(input){let{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.promise&&ctx.common.async===!1)return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:ctx.parsedType}),INVALID;let promisified=ctx.parsedType===ZodParsedType.promise?ctx.data:Promise.resolve(ctx.data);return OK(promisified.then(data=>this._def.type.parseAsync(data,{path:ctx.path,errorMap:ctx.common.contextualErrorMap})))}};ZodPromise.create=(schema,params)=>new ZodPromise({type:schema,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(params)});var ZodEffects=class extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(input){let{status,ctx}=this._processInputParams(input),effect=this._def.effect||null,checkCtx={addIssue:arg=>{addIssueToContext(ctx,arg),arg.fatal?status.abort():status.dirty()},get path(){return ctx.path}};if(checkCtx.addIssue=checkCtx.addIssue.bind(checkCtx),effect.type==="preprocess"){let processed=effect.transform(ctx.data,checkCtx);if(ctx.common.async)return Promise.resolve(processed).then(async processed2=>{if(status.value==="aborted")return INVALID;let result=await this._def.schema._parseAsync({data:processed2,path:ctx.path,parent:ctx});return result.status==="aborted"?INVALID:result.status==="dirty"?DIRTY(result.value):status.value==="dirty"?DIRTY(result.value):result});{if(status.value==="aborted")return INVALID;let result=this._def.schema._parseSync({data:processed,path:ctx.path,parent:ctx});return result.status==="aborted"?INVALID:result.status==="dirty"?DIRTY(result.value):status.value==="dirty"?DIRTY(result.value):result}}if(effect.type==="refinement"){let executeRefinement=acc=>{let result=effect.refinement(acc,checkCtx);if(ctx.common.async)return Promise.resolve(result);if(result instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return acc};if(ctx.common.async===!1){let inner=this._def.schema._parseSync({data:ctx.data,path:ctx.path,parent:ctx});return inner.status==="aborted"?INVALID:(inner.status==="dirty"&&status.dirty(),executeRefinement(inner.value),{status:status.value,value:inner.value})}else return this._def.schema._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}).then(inner=>inner.status==="aborted"?INVALID:(inner.status==="dirty"&&status.dirty(),executeRefinement(inner.value).then(()=>({status:status.value,value:inner.value}))))}if(effect.type==="transform")if(ctx.common.async===!1){let base=this._def.schema._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(!isValid(base))return INVALID;let result=effect.transform(base.value,checkCtx);if(result instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:status.value,value:result}}else return this._def.schema._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}).then(base=>isValid(base)?Promise.resolve(effect.transform(base.value,checkCtx)).then(result=>({status:status.value,value:result})):INVALID);util.assertNever(effect)}};ZodEffects.create=(schema,effect,params)=>new ZodEffects({schema,typeName:ZodFirstPartyTypeKind.ZodEffects,effect,...processCreateParams(params)});ZodEffects.createWithPreprocess=(preprocess,schema,params)=>new ZodEffects({schema,effect:{type:"preprocess",transform:preprocess},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(params)});var ZodOptional=class extends ZodType{_parse(input){return this._getType(input)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(input)}unwrap(){return this._def.innerType}};ZodOptional.create=(type,params)=>new ZodOptional({innerType:type,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(params)});var ZodNullable=class extends ZodType{_parse(input){return this._getType(input)===ZodParsedType.null?OK(null):this._def.innerType._parse(input)}unwrap(){return this._def.innerType}};ZodNullable.create=(type,params)=>new ZodNullable({innerType:type,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(params)});var ZodDefault=class extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),data=ctx.data;return ctx.parsedType===ZodParsedType.undefined&&(data=this._def.defaultValue()),this._def.innerType._parse({data,path:ctx.path,parent:ctx})}removeDefault(){return this._def.innerType}};ZodDefault.create=(type,params)=>new ZodDefault({innerType:type,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof params.default=="function"?params.default:()=>params.default,...processCreateParams(params)});var ZodCatch=class extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),newCtx={...ctx,common:{...ctx.common,issues:[]}},result=this._def.innerType._parse({data:newCtx.data,path:newCtx.path,parent:{...newCtx}});return isAsync(result)?result.then(result2=>({status:"valid",value:result2.status==="valid"?result2.value:this._def.catchValue({get error(){return new ZodError(newCtx.common.issues)},input:newCtx.data})})):{status:"valid",value:result.status==="valid"?result.value:this._def.catchValue({get error(){return new ZodError(newCtx.common.issues)},input:newCtx.data})}}removeCatch(){return this._def.innerType}};ZodCatch.create=(type,params)=>new ZodCatch({innerType:type,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof params.catch=="function"?params.catch:()=>params.catch,...processCreateParams(params)});var ZodNaN=class extends ZodType{_parse(input){if(this._getType(input)!==ZodParsedType.nan){let ctx=this._getOrReturnCtx(input);return addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:ctx.parsedType}),INVALID}return{status:"valid",value:input.data}}};ZodNaN.create=params=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(params)});var BRAND=Symbol("zod_brand"),ZodBranded=class extends ZodType{_parse(input){let{ctx}=this._processInputParams(input),data=ctx.data;return this._def.type._parse({data,path:ctx.path,parent:ctx})}unwrap(){return this._def.type}},ZodPipeline=class _ZodPipeline extends ZodType{_parse(input){let{status,ctx}=this._processInputParams(input);if(ctx.common.async)return(async()=>{let inResult=await this._def.in._parseAsync({data:ctx.data,path:ctx.path,parent:ctx});return inResult.status==="aborted"?INVALID:inResult.status==="dirty"?(status.dirty(),DIRTY(inResult.value)):this._def.out._parseAsync({data:inResult.value,path:ctx.path,parent:ctx})})();{let inResult=this._def.in._parseSync({data:ctx.data,path:ctx.path,parent:ctx});return inResult.status==="aborted"?INVALID:inResult.status==="dirty"?(status.dirty(),{status:"dirty",value:inResult.value}):this._def.out._parseSync({data:inResult.value,path:ctx.path,parent:ctx})}}static create(a,b){return new _ZodPipeline({in:a,out:b,typeName:ZodFirstPartyTypeKind.ZodPipeline})}},ZodReadonly=class extends ZodType{_parse(input){let result=this._def.innerType._parse(input),freeze=data=>(isValid(data)&&(data.value=Object.freeze(data.value)),data);return isAsync(result)?result.then(data=>freeze(data)):freeze(result)}unwrap(){return this._def.innerType}};ZodReadonly.create=(type,params)=>new ZodReadonly({innerType:type,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(params)});function cleanParams(params,data){let p=typeof params=="function"?params(data):typeof params=="string"?{message:params}:params;return typeof p=="string"?{message:p}:p}function custom(check,_params={},fatal){return check?ZodAny.create().superRefine((data,ctx)=>{let r=check(data);if(r instanceof Promise)return r.then(r2=>{if(!r2){let params=cleanParams(_params,data),_fatal=params.fatal??fatal??!0;ctx.addIssue({code:"custom",...params,fatal:_fatal})}});if(!r){let params=cleanParams(_params,data),_fatal=params.fatal??fatal??!0;ctx.addIssue({code:"custom",...params,fatal:_fatal})}}):ZodAny.create()}var late={object:ZodObject.lazycreate},ZodFirstPartyTypeKind;(function(ZodFirstPartyTypeKind2){ZodFirstPartyTypeKind2.ZodString="ZodString",ZodFirstPartyTypeKind2.ZodNumber="ZodNumber",ZodFirstPartyTypeKind2.ZodNaN="ZodNaN",ZodFirstPartyTypeKind2.ZodBigInt="ZodBigInt",ZodFirstPartyTypeKind2.ZodBoolean="ZodBoolean",ZodFirstPartyTypeKind2.ZodDate="ZodDate",ZodFirstPartyTypeKind2.ZodSymbol="ZodSymbol",ZodFirstPartyTypeKind2.ZodUndefined="ZodUndefined",ZodFirstPartyTypeKind2.ZodNull="ZodNull",ZodFirstPartyTypeKind2.ZodAny="ZodAny",ZodFirstPartyTypeKind2.ZodUnknown="ZodUnknown",ZodFirstPartyTypeKind2.ZodNever="ZodNever",ZodFirstPartyTypeKind2.ZodVoid="ZodVoid",ZodFirstPartyTypeKind2.ZodArray="ZodArray",ZodFirstPartyTypeKind2.ZodObject="ZodObject",ZodFirstPartyTypeKind2.ZodUnion="ZodUnion",ZodFirstPartyTypeKind2.ZodDiscriminatedUnion="ZodDiscriminatedUnion",ZodFirstPartyTypeKind2.ZodIntersection="ZodIntersection",ZodFirstPartyTypeKind2.ZodTuple="ZodTuple",ZodFirstPartyTypeKind2.ZodRecord="ZodRecord",ZodFirstPartyTypeKind2.ZodMap="ZodMap",ZodFirstPartyTypeKind2.ZodSet="ZodSet",ZodFirstPartyTypeKind2.ZodFunction="ZodFunction",ZodFirstPartyTypeKind2.ZodLazy="ZodLazy",ZodFirstPartyTypeKind2.ZodLiteral="ZodLiteral",ZodFirstPartyTypeKind2.ZodEnum="ZodEnum",ZodFirstPartyTypeKind2.ZodEffects="ZodEffects",ZodFirstPartyTypeKind2.ZodNativeEnum="ZodNativeEnum",ZodFirstPartyTypeKind2.ZodOptional="ZodOptional",ZodFirstPartyTypeKind2.ZodNullable="ZodNullable",ZodFirstPartyTypeKind2.ZodDefault="ZodDefault",ZodFirstPartyTypeKind2.ZodCatch="ZodCatch",ZodFirstPartyTypeKind2.ZodPromise="ZodPromise",ZodFirstPartyTypeKind2.ZodBranded="ZodBranded",ZodFirstPartyTypeKind2.ZodPipeline="ZodPipeline",ZodFirstPartyTypeKind2.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));var instanceOfType=(cls,params={message:`Input not instance of ${cls.name}`})=>custom(data=>data instanceof cls,params),stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ostring=()=>stringType().optional(),onumber=()=>numberType().optional(),oboolean=()=>booleanType().optional(),coerce={string:arg=>ZodString.create({...arg,coerce:!0}),number:arg=>ZodNumber.create({...arg,coerce:!0}),boolean:arg=>ZodBoolean.create({...arg,coerce:!0}),bigint:arg=>ZodBigInt.create({...arg,coerce:!0}),date:arg=>ZodDate.create({...arg,coerce:!0})};var NEVER=INVALID;async function prepareFunctions(options){await traceOperation(options.trace,"vc.cli.describe.validate_output",()=>validateBuildOutput(options));let config=await traceOperation(options.trace,"vc.cli.describe.read_config",()=>getBuildOutputConfigOrThrow(options.outputDir));if("daemons"in config&&config.daemons&&Object.keys(config.daemons).length)throw new DescribeError("unsupported_output","This build contains daemons. Describe supports native AWS Lambda functions only.");if(!serviceInventorySchema.safeParse(config.experimentalServicesV2??{}).success)throw new DescribeError("invalid_build_output","Invalid service inventory in config.json. Rebuild the service outputs before running describe.");let scopes=[{directory:"",config}];for(let entry of getServiceOutputEntries(config)){if(entry.service.bindings?.length)throw new DescribeError("unsupported_output","This build contains service bindings, which cannot be provisioned as AWS Lambda functions. Remove the bindings and rebuild before running describe.");let serviceConfig=await readServiceOutputConfig(options.outputDir,entry).catch(error=>{throw error instanceof import_build_utils8.NowBuildError&&error.code==="MISSING_SERVICE_BUILD_OUTPUT"?new DescribeError("invalid_build_output",`Service "${entry.name}" is missing build output at ".vercel/output/services/${entry.name}/config.json". Rebuild the service before running describe.`):error});serviceConfig&&scopes.push({config:serviceConfig,directory:entry.directory,service:entry.name})}let groups=[],paths=new Set;for(let scope of scopes){let functions=await traceOperation(options.trace,"vc.cli.describe.read_functions",()=>readFunctions({outputDir:join9(options.outputDir,scope.directory),repoRootPath:options.repoRootPath,prebuilt:!0}));if(functions.edgeFunctions.size)throw new DescribeError("unsupported_output","This build contains Edge Functions, which cannot be provisioned as AWS Lambda functions.");await traceOperation(options.trace,"vc.cli.describe.group_functions",()=>groupBundleableLambdas({functions,options:{}}));let scopeGroups=new Map,middlewarePaths=getMiddlewareRouting({routes:scope.config.routes??[],functions});for(let output of iterateNativeFunctionOutputs(functions)){let lambda=output.lambda,directory=join9(scope.directory,"functions",`${output.path}.func`),functionConfig=JSON.parse(await readFile3(join9(options.outputDir,directory,".vc-config.json"),"utf8"));if(lambda.runtime==="container"||functionConfig.hive||functionConfig.affinity)throw new DescribeError("unsupported_output","This build contains container or Hive functions. Describe supports native AWS Lambda functions only.");let sourcePath=getFunctionSourcePath({output:{path:output.path},service:scope.service});if(paths.has(sourcePath))throw new DescribeError("invalid_build_output",`Multiple function outputs use "${sourcePath}". Rename the conflicting output and rebuild before running describe.`);paths.add(sourcePath);let outputs=scopeGroups.get(lambda)??[];scopeGroups.set(lambda,outputs),outputs.push({sourceKind:output.prerender?"prerender":"lambda",middleware:output.prerender===void 0&&middlewarePaths.has(output.path)?{}:void 0,path:sourcePath,directory,service:scope.service})}for(let[lambda,outputs]of scopeGroups)groups.push({lambda,outputs})}return{groups,services:config.services}}var serviceInventorySchema=external_exports.record(external_exports.string().regex(new RegExp(import_build_utils8.SERVICE_NAME_PATTERN)),external_exports.object({root:external_exports.string().optional(),bindings:external_exports.array(external_exports.unknown()).optional()}));import{writeFile}from"node:fs/promises";var descriptorSchema=external_exports.object({Architectures:external_exports.array(external_exports.string()).optional(),Environment:external_exports.object({Variables:external_exports.record(external_exports.string())}),EphemeralStorage:external_exports.object({Size:external_exports.number()}).optional(),FunctionName:external_exports.string().min(1),Handler:external_exports.string(),Layers:external_exports.array(external_exports.string()),MemorySize:external_exports.number(),Region:external_exports.string().min(1),ResolvableLayers:external_exports.record(external_exports.object({url:external_exports.string()})),Runtime:external_exports.string(),Tags:external_exports.record(external_exports.string()),Timeout:external_exports.number().optional()});async function describeFunctions(client,params){let functions=await client.withTrace("vc.cli.describe.prepare_functions",trace=>prepareFunctions({trace,directory:params.directory,repoRootPath:params.repoRootPath,outputDir:params.outputDir})),buildEnv=await client.withTrace("vc.cli.describe.build_env",async()=>external_exports.object({VERCEL_ENCRYPTED_ENV_FILENAME:external_exports.string().min(1),VERCEL_ENCRYPTED_ENV_CONTENT:external_exports.string().min(1)}).parse((await fetchDeploymentBuildEnv(client,params.deploymentId,{quiet:params.quiet})).buildEnv)),lambdas=(await Promise.all(functions.groups.map(({lambda,outputs})=>client.withTrace("vc.cli.describe.function",async()=>{lambda.files=await client.withTrace("vc.cli.describe.hydrate",()=>hydrateLambdaFiles(lambda,{filename:buildEnv.VERCEL_ENCRYPTED_ENV_FILENAME,contentBase64:buildEnv.VERCEL_ENCRYPTED_ENV_CONTENT}));let zip=await client.withTrace("vc.cli.describe.zip",()=>lambda.createZip()),bytes2=new Uint8Array(zip.buffer,zip.byteOffset,zip.byteLength),digest=await client.withTrace("vc.cli.describe.hash_zip",()=>createHash2("sha256").update(bytes2).digest("hex"),{byte_count:String(bytes2.length)});await client.withTrace("vc.cli.describe.write_zip",()=>writeFile(join10(params.zipDirectory,`${digest}.zip`),bytes2,{mode:384}),{byte_count:String(bytes2.length)});let config=await client.withTrace("vc.cli.describe.configuration",()=>getFunctionConfig(lambda)),input={...config,framework:config.framework&&{slug:config.framework.slug},digest,size:bytes2.length};return outputs.map(output=>({...output,lambda:input}))},{function_count:"1"})))).flat(),{descriptors}=await client.withTrace("vc.cli.describe.descriptors",async()=>external_exports.object({descriptors:external_exports.array(external_exports.array(descriptorSchema).min(1))}).parse(await client.fetch(`/v2/deployments/${params.deploymentId}/builds/function-descriptors`,{method:"POST",body:JSON.stringify({lambdas:lambdas.map(output=>({lambda:output.lambda,path:output.path,service:output.service,sourceKind:output.sourceKind,middleware:output.middleware})),services:functions.services}),headers:{"content-type":"application/json"},accountId:params.teamId,retry:{retries:0}})),{function_count:String(lambdas.length)});if(descriptors.length!==lambdas.length)throw new Error("Descriptor count does not match function outputs");return lambdas.map(({path:path2,directory,lambda},index)=>{let regional=descriptors[index];if(new Set(regional.map(d=>d.FunctionName)).size!==1)throw new Error("Inconsistent regional function name");return{path:path2,directory,digest:lambda.digest,size:lambda.size,regional}})}import{isDeepStrictEqual}from"node:util";import{join as join12}from"node:path";import{mkdir as mkdir2,mkdtemp,rename,rm,stat as stat5,writeFile as writeFile3}from"node:fs/promises";var import_build_utils9=__toESM(require_build_utils(),1);import{basename as basename2,dirname as dirname2,join as join11,relative as relative4,sep as sep3}from"node:path";import{copyFile,cp,lstat as lstat2,mkdir,readFile as readFile4,readdir as readdir4,realpath as realpath4,stat as stat4,symlink,writeFile as writeFile2}from"node:fs/promises";async function prepareContinuation(params){let{directory,outputDir,destination,manifest,repoRootPath=directory}=params,validateSource=await traceOperation(params.trace,"vc.cli.describe.validate_continuation",()=>validateBuildOutput({directory,outputDir,repoRootPath})),outputRoot=await realpath4(outputDir),functionDirectories=new Set(params.functions.map(fn=>fn.directory)),functionAliases=[];await traceOperation(params.trace,"vc.cli.describe.copy_continuation",()=>cp(outputDir,destination,{recursive:!0,dereference:!0,filter:async(path2,target)=>{let rel=relative4(outputDir,path2);return basename2(path2)!==".vc-config.json"&&rel.split(sep3).slice(0,-1).some(segment=>segment.endsWith(".func"))?!1:functionDirectories.has(rel)&&(await lstat2(path2)).isSymbolicLink()?(functionAliases.push({path:target,target:join11(destination,relative4(outputRoot,await realpath4(path2)))}),!1):!0}}));for(let{path:path2,target}of functionAliases)await mkdir(dirname2(path2),{recursive:!0}),await symlink(relative4(dirname2(path2),target),path2);await traceOperation(params.trace,"vc.cli.describe.write_manifest",()=>writeFile2(join11(destination,"provision.json"),JSON.stringify(manifest)));let manifests=new Set(await traceOperation(params.trace,"vc.cli.describe.package_manifests",()=>packageManifests(directory)));if(repoRootPath!==directory)for(let path2 of await traceOperation(params.trace,"vc.cli.describe.package_manifests",()=>packageManifests(repoRootPath)))manifests.add(path2);for(let directory2 of functionDirectories)await traceOperation(params.trace,"vc.cli.describe.rewrite_function",async()=>{let configPath=join11(destination,directory2,".vc-config.json"),config=JSON.parse(await readFile4(configPath,"utf8"));for(let[file,source]of Object.entries(config.filePathMap??{}))basename2(file)==="package.json"&&manifests.add(join11(repoRootPath,source));delete config.filePathMap,await writeFile2(configPath,JSON.stringify({...config,architecture:new import_build_utils9.Lambda({...config,files:{}}).architecture}))},{function_count:"1"});let[firstFunction]=functionDirectories;if(firstFunction!==void 0)for(let[i,path2]of[...manifests].entries()){let target=join11(destination,firstFunction,"__byoc_security__",String(i));await mkdir(target,{recursive:!0}),await traceOperation(params.trace,"vc.cli.describe.copy_manifest",async()=>copyFile(await validateSource(path2),join11(target,"package.json")))}}async function packageManifests(root){let modules=join11(root,"node_modules"),names=await readdir4(modules).catch(()=>[]),packages=await Promise.all(names.map(async name=>name.startsWith(".")?[]:name.startsWith("@")?(await readdir4(join11(modules,name)).catch(()=>[])).map(entry=>join11(modules,name,entry)):[join11(modules,name)]));return(await Promise.all([root,...packages.flat()].map(dir=>{let path2=join11(dir,"package.json");return stat4(path2).then(()=>path2,()=>{})}))).filter(p=>p!==void 0)}async function describeDeployment(client,params){return client.withTrace("vc.cli.describe",async trace=>{let output=join12(params.directory,".vercel",params.deploymentId),buildOutput=join12(params.directory,".vercel/output"),build=join12(output,"build"),repoRootPath=params.repoRootPath??params.directory,source=await client.withTrace("vc.cli.describe.resolve_source",async()=>{let source2=await exists(buildOutput)&&!await exists(join12(buildOutput,"provision.json"))?buildOutput:build;if(!await exists(join12(source2,"config.json")))throw new DescribeError("prebuilt_not_found",`No local build output found. Run \`vercel build --deployment ${params.deploymentId}\` before \`vercel deploy describe\`.`);return source2}),staging=await client.withTrace("vc.cli.describe.staging",async()=>(await mkdir2(join12(params.directory,".vercel"),{recursive:!0}),mkdtemp(join12(params.directory,".vercel",`.describe-${params.deploymentId}-`)))),removeStaging=!0,functions=new Map,layers={},manifest={};try{await client.withTrace("vc.cli.describe.prepare_directories",async()=>{await mkdir2(join12(staging,"zips")),await mkdir2(join12(staging,"layers"))});let described=await client.withTrace("vc.cli.describe.functions",()=>describeFunctions(client,{deploymentId:params.deploymentId,directory:params.directory,repoRootPath,outputDir:source,quiet:params.quiet,teamId:params.teamId,zipDirectory:join12(staging,"zips")}));return trace?.span.setAttributes({function_count:String(described.length)}),await client.withTrace("vc.cli.describe.resolve_layers",async layerScope=>{for(let{path:path2,digest,size,regional}of described){for(let descriptor of regional){let layerNames=[];for(let arn of descriptor.Layers){let layer=descriptor.ResolvableLayers[arn];if(!layer)throw new DescribeError("invalid_response","The deployment API did not provide a download URL for a required runtime layer.");let name=createHash3("sha256").update(arn).digest("hex");layerNames.push(name),await client.withTrace("vc.cli.describe.layer",async layerTrace=>{if(layerTrace?.span.setAttributes({cache_hit:layers[name]?"true":"false"}),layers[name])return;let bytes2=await downloadLayer(client,layer.url);layerTrace?.span.setAttributes({byte_count:String(bytes2.length)});let file=`layers/${await client.withTrace("vc.cli.describe.layer_hash",()=>createHash3("sha256").update(bytes2).digest("hex"),{byte_count:String(bytes2.length)})}.zip`;await client.withTrace("vc.cli.describe.layer_write",()=>writeFile3(join12(staging,file),bytes2,{mode:384}),{byte_count:String(bytes2.length)}),layers[name]=file})}let{Region,Layers,ResolvableLayers,...configuration}=descriptor,fn={code:`zips/${digest}.zip`,region:Region,layers:layerNames,configuration},key=`${descriptor.Region}:${descriptor.FunctionName}`,previous=functions.get(key);if(previous&&!isDeepStrictEqual(previous,fn))throw new DescribeError("invalid_response","Conflicting descriptors for the same regional function");functions.set(key,fn)}manifest[path2]={awsAccountId:params.awsAccountId,digest,functionName:regional[0].FunctionName,regions:[...new Set(regional.map(d=>d.Region))],size}}layerScope?.span.setAttributes({layer_count:String(Object.keys(layers).length)})}),trace?.span.setAttributes({layer_count:String(Object.keys(layers).length)}),await client.withTrace("vc.cli.describe.write_descriptor",()=>writeFile3(join12(staging,"descriptor.json"),JSON.stringify({awsAccountId:params.awsAccountId,deploymentId:params.deploymentId,functions:[...functions.values()],layers,version:1},null,2),{mode:384})),await client.withTrace("vc.cli.describe.continuation",trace2=>prepareContinuation({trace:trace2,destination:join12(staging,"output"),directory:params.directory,functions:described,manifest,outputDir:source,repoRootPath})),await client.withTrace("vc.cli.describe.persist",async()=>{await mkdir2(output,{recursive:!0,mode:448});let backup=join12(staging,"backup");await mkdir2(backup);let moves=[],move=async(from,to)=>{await rename(from,to),moves.push([from,to])},preserve=async(path2,name)=>{await exists(path2)&&await move(path2,join12(backup,name))};try{for(let name of["zips","layers","descriptor.json"])await preserve(join12(output,name),name),await move(join12(staging,name),join12(output,name));source===buildOutput?(await preserve(build,"build"),await move(buildOutput,build)):await preserve(buildOutput,"output"),await move(join12(staging,"output"),buildOutput)}catch(error){throw removeStaging=!1,await client.withTrace("vc.cli.describe.rollback",async()=>{for(let[from,to]of moves.reverse())await rename(to,from)}),removeStaging=!0,error}}),output}finally{removeStaging&&await client.withTrace("vc.cli.describe.cleanup",()=>rm(staging,{recursive:!0,force:!0}))}})}var exists=path2=>stat5(path2).then(()=>!0,error=>{if(error.code==="ENOENT")return!1;throw error});import{join as join14}from"node:path";import{join as join13,relative as relative5}from"node:path";async function resolveDescribeProject(client){try{let link=await getLinkFromDir(join13(client.cwd,".vercel"));if(link){let{repoRoot,resolvedRootDirectory}=resolvePerDirectoryLinkRoot(client.cwd,link.settings?.rootDirectory);return{...link,directory:join13(repoRoot,resolvedRootDirectory),repoRootPath:repoRoot}}let repo=await getRepoLink(client,client.cwd);if(!repo?.repoConfig?.projects.length)throw new DescribeError("not_linked","No linked project found. Run `vercel link`, or restore CI project settings with `vercel pull --yes`.");let matches=findProjectsFromPath(repo.repoConfig.projects,relative5(repo.rootPath,client.cwd)),candidates=matches.length?matches:repo.repoConfig.projects;if(candidates.length!==1)throw new DescribeError("ambiguous_project","Multiple projects are linked here. Run this command from the intended project directory, or pass --cwd <PROJECT_DIRECTORY>.");let project=await getProjectLink(client,client.cwd,candidates[0].id,!0);if(!project?.repoRoot)throw new Error("Project link changed");return{...project,directory:join13(project.repoRoot,project.projectRootDirectory||""),repoRootPath:project.repoRoot}}catch(error){throw error instanceof DescribeError?error:new DescribeError("invalid_project_link","Could not read the local project link. Check that .vercel/project.json or .vercel/repo.json is readable and contains valid project settings.")}}async function describe(client){let asJson=wantsMachineReadableOutput("deploy",client.argv),warnings=[],fail=(reason,message,code2=1)=>(asJson?client.stderr.write(`${JSON.stringify({status:"error",reason,message,...warnings.length>0?{warnings}:{}})}
20
23
  `):output_manager_default.error(message),code2),parsed;try{parsed=parseArguments(client.argv.slice(2),getFlagsSpecification(describeSubcommand.options))}catch(error){return fail("invalid_arguments",`${isArgumentError(error)?error.message:"Invalid describe options"}. Run \`vercel deploy describe --help\` for usage.`,2)}asJson=parsed.flags["--json"]===!0;let deployment=getRenamedOption(parsed.flags,"--deployment","--id",{json:asJson});if("error"in deployment)return fail("invalid_arguments",deployment.error,2);deployment.warning&&(warnings=[deployment.warning]);let deploymentId=deployment.value,awsAccountId=parsed.flags["--aws-account-id"];if((parsed.args[0]==="deploy"?parsed.args.slice(1):parsed.args).length>1)return fail("invalid_arguments","Unexpected positional arguments. Run `vercel deploy describe --help` for usage.",2);if(!deploymentId||!/^dpl_[a-zA-Z0-9]+$/.test(deploymentId))return fail("invalid_arguments","Provide a deployment ID with --deployment, such as --deployment dpl_xxx.",2);if(!awsAccountId||!/^\d{12}$/.test(awsAccountId))return fail("invalid_arguments","Provide a 12-digit AWS account ID with --aws-account-id.",2);if(process.platform==="win32")return fail("unsupported_platform","vercel deploy describe is not supported on Windows yet. Run it on macOS or Linux.");let telemetry=new DescribeTelemetryClient({opts:{store:client.telemetryEventStore}});telemetry.trackCliOptionDeployment(parsed.flags["--deployment"]),telemetry.trackCliOptionId(parsed.flags["--id"]),telemetry.trackCliOptionAwsAccountId(awsAccountId),telemetry.trackCliFlagJson(parsed.flags["--json"]);try{let project=await resolveDescribeProject(client),explicitTeam=parsed.flags["--scope"]?client.config.currentTeam:process.env.VERCEL_ORG_ID;if(explicitTeam&&explicitTeam!==project.orgId)return fail("scope_mismatch","The selected team does not match the local project link. Use the linked team, or run `vercel pull --yes` with the intended VERCEL_ORG_ID and VERCEL_PROJECT_ID.");if(process.env.VERCEL_PROJECT_ID&&process.env.VERCEL_PROJECT_ID!==project.projectId)return fail("project_mismatch","VERCEL_PROJECT_ID differs from the linked project. Run `vercel pull --yes` to restore settings for the intended project.");client.config.currentTeam=project.orgId.startsWith("team_")?project.orgId:void 0,asJson||output_manager_default.log(`Preparing ${deploymentId} in team ${project.orgId} for AWS account ${awsAccountId}`);let directory=await describeDeployment(client,{directory:project.directory,repoRootPath:project.repoRootPath,deploymentId,awsAccountId,teamId:project.orgId,quiet:asJson}),descriptor=join14(directory,"descriptor.json");if(asJson)client.stdout.write(`${JSON.stringify({deployment:{id:deploymentId},awsAccountId,directory,descriptor,...warnings.length>0?{warnings}:{}})}
21
24
  `);else{client.stdout.write(`${descriptor}
22
25
  `),output_manager_default.log(`Prepared function packages in ${directory}`);let cwd=project.directory===client.cwd?"":` --cwd ${quoteArg(project.directory)}`;output_manager_default.log(`Provision the functions in descriptor.json, then run:
23
- vercel deploy continue --deployment ${deploymentId}${cwd}`)}return 0}catch(error){return output_manager_default.debug(error instanceof Error?error.stack??error.message:String(error)),error instanceof DescribeError?fail(error.reason,error.message):error instanceof InvalidToken||isAPIError(error)&&error.status===401?fail("not_authorized","Could not authenticate with Vercel. Check VERCEL_TOKEN in CI, or run `vercel login`."):isAPIError(error)&&error.status===403?fail("not_authorized","Vercel denied access to this deployment. Check that your token has access to the linked project and team."):isAPIError(error)&&error.status===404?fail("not_found",`Deployment ${deploymentId} was not found, or manual provisioning is not enabled for this team.`):isAPIError(error)&&error.status<500&&error.serverMessage?fail("api_error",error.serverMessage):fail("describe_failed","Could not prepare deployment functions. Check the local build and deployment access, then rerun this command.")}}var import_fs_extra3=__toESM(require_lib(),1);import{join as join16}from"path";var import_fs_extra2=__toESM(require_lib(),1),import_ci_info=__toESM(require_ci_info(),1),import_build_utils10=__toESM(require_build_utils(),1),import_error_utils=__toESM(require_dist(),1);import{join as join15}from"path";var VERCEL_DIR_ANONYMOUS="anonymous.json";function anonymousStatePath(cwd){return join15(cwd,VERCEL_DIR,VERCEL_DIR_ANONYMOUS)}async function readAnonymousState(cwd){try{let state=await(0,import_fs_extra2.readJSON)(anonymousStatePath(cwd));if(typeof state?.projectId=="string"&&typeof state.token=="string"&&typeof state.claimUrl=="string"&&typeof state.expiresAt=="number")return state}catch{}return null}async function writeAnonymousState(cwd,state){let path2=anonymousStatePath(cwd);await(0,import_fs_extra2.outputJSON)(path2,state,{spaces:2,mode:384}),await(0,import_fs_extra2.chmod)(path2,384),await addToGitIgnore(cwd)}async function clearAnonymousState(cwd){await(0,import_fs_extra2.remove)(anonymousStatePath(cwd))}async function bootstrapAnonymousProject(client){let{projectId,token,claimUrl,expiresAt}=await client.fetch("/v1/anonymous/projects?surface=cli",{method:"POST",body:{},useCurrentTeam:!1,retry:{retries:0}});return{projectId,token,claimUrl,expiresAt}}async function ensureAnonymousLink(client,cwd,{requireExistingState=!1,confirmed=!0}={}){if(import_ci_info.default.isCI||!!((0,import_build_utils10.getPlatformEnv)("ORG_ID")&&(0,import_build_utils10.getPlatformEnv)("PROJECT_ID"))||!!await getLinkFromDir(getVercelDirectory(cwd))||!!(await getRepoLink(client,cwd))?.repoConfig)return"refused";let state=await readAnonymousState(cwd);if(state&&state.expiresAt<=Date.now())return output_manager_default.prettyError({message:`Your temporary deployment has expired. Run ${getCommandName("login")} to create an account and keep deploying this app.`}),"failed";if(!state&&requireExistingState)return"refused";if(!confirmed&&!state)return"confirmation-required";if(!state){try{state=await bootstrapAnonymousProject(client)}catch(err){return output_manager_default.debug(`Anonymous bootstrap failed: ${(0,import_error_utils.errorToString)(err)}`),"refused"}await writeAnonymousState(cwd,state),output_manager_default.log("Not authenticated. Deploying anonymously.")}return client.authConfig={token:state.token,skipWrite:!0},delete process.env.VERCEL_TEAM_ID,{status:"linked",anonymous:!0,expiresAt:state.expiresAt,claimUrl:state.claimUrl,org:{type:"user",id:"",slug:"anonymous"},project:{id:state.projectId,name:state.projectId}}}function validateAnonymousTarget(isAnonymous,target){return isAnonymous&&target&&target!=="production"?(output_manager_default.error(`Anonymous deployments always target production, so "${target}" is not available. Remove the ${param("--environment")} option, or run ${getCommandName("login")} to deploy to other environments.`),!1):!0}async function setupAnonymousDeployment(client,cwd,{isAnonymous,dryRun}){isAnonymous||await clearAnonymousState(cwd);let anonymousLink;if(isAnonymous){let anonymous=await ensureAnonymousLink(client,cwd,{requireExistingState:dryRun});if(anonymous==="refused"){output_manager_default.log("Temporary deployments aren't available for this attempt. Log in to continue.");let{default:promptMissingCredentials}=await import("../../chunks/prompt-missing-credentials-2IYIF2JI.js"),loginExitCode=await promptMissingCredentials(client);if(loginExitCode!==0)return loginExitCode;isAnonymous=!1}else{if(anonymous==="failed")return 1;if(anonymous==="confirmation-required")return 1;anonymousLink=anonymous}}return{isAnonymous,anonymousLink}}async function handleAnonymousDeploymentError({client,cwd,error,link,isV0,retry}){if(!(!link||!isAPIError(error))){if(error.code==="anonymous_project_claimed"){if(client.nonInteractive||!client.stdin.isTTY)return output_manager_default.prettyError({message:`This project was claimed successfully. Run ${getCommandName("login")} to continue deploying it.`}),1;output_manager_default.log("This project was claimed successfully. Log in to continue deploying it.");let loginExitCode;try{let{default:login}=await import("../../chunks/login-COGE7JQU.js");loginExitCode=await login(client,{shouldParseArgs:!1})}catch(loginError){return printError(loginError),1}if(loginExitCode!==0)return loginExitCode;let claimedProjectLink=await ensureLink("deploy",client,cwd,{autoConfirm:!0,projectName:link.project.id,failIfNotFound:!0,allowOwnerLookupFallback:!0,v0:isV0});return typeof claimedProjectLink=="number"?claimedProjectLink:(await linkFolderToProject(client,cwd,{projectId:claimedProjectLink.project.id,orgId:claimedProjectLink.org.id},claimedProjectLink.project.name,claimedProjectLink.org.slug,"link",!0,!1),await clearAnonymousState(cwd),retry())}if(error.status===401||error.status===410)return await clearAnonymousState(cwd),output_manager_default.prettyError({message:`Your temporary deployment has expired. Run ${getCommandName("login")} to create an account and keep deploying this app.`}),1}}async function runImplicitBuild(client,cwd){let projectJsonPath=join16(cwd,VERCEL_DIR,VERCEL_DIR_PROJECT),projectJsonExists=await import_fs_extra3.default.pathExists(projectJsonPath);projectJsonExists||await import_fs_extra3.default.outputJSON(projectJsonPath,{settings:{}},{spaces:2}),await import_fs_extra3.default.pathExists(join16(cwd,"package.json"))&&output_manager_default.log("Building your project locally\u2026");let originalArgv=client.argv,originalCwd=client.cwd,originalStdout=client.stdout,previousVercelFirstDeployment=process.env.VERCEL_FIRST_DEPLOYMENT;client.cwd=cwd,client.setArgv([...originalArgv.slice(0,2),"build","--prod","--yes"]),process.env.VERCEL_FIRST_DEPLOYMENT="1",client.stdout=createSinkStream();try{let build=(await import("../build/index.js")).default;return await build(client)}finally{client.setArgv(originalArgv),client.cwd=originalCwd,client.stdout=originalStdout,previousVercelFirstDeployment===void 0?delete process.env.VERCEL_FIRST_DEPLOYMENT:process.env.VERCEL_FIRST_DEPLOYMENT=previousVercelFirstDeployment,projectJsonExists||await import_fs_extra3.default.remove(projectJsonPath)}}function createSinkStream(){return{isTTY:!1,write:()=>!0}}var COMMAND_CONFIG={init:getCommandAliases(initSubcommand),continue:getCommandAliases(continueSubcommand),describe:getCommandAliases(describeSubcommand)},deploy_default=async client=>{let telemetryClient=new DeployTelemetryClient({opts:{store:client.telemetryEventStore}}),parsedArguments=null,flagsSpecification=getDeployFlagsSpecification(deployCommand.options);try{parsedArguments=parseArguments(client.argv.slice(2),flagsSpecification,{permissive:!0})}catch(error){return printError(error),2}let subArgs=parsedArguments.args[0]===deployCommand.name?parsedArguments.args.slice(1):parsedArguments.args,{subcommand,subcommandOriginal}=getSubcommand(subArgs,COMMAND_CONFIG);function printSubcommandHelp(command){output_manager_default.print(help(command,{stream:client.stderr,parent:deployCommand,columns:client.stderr.columns}))}switch(subcommand){case"init":return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy",subcommandOriginal),printSubcommandHelp(initSubcommand),0):(telemetryClient.trackCliSubcommandInit(subcommandOriginal),handleInitDeployment(client,telemetryClient));case"continue":return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy",subcommandOriginal),printSubcommandHelp(continueSubcommand),0):(telemetryClient.trackCliSubcommandContinue(subcommandOriginal),handleContinueSubcommand(client,telemetryClient));case"describe":return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy",subcommandOriginal),printSubcommandHelp(describeSubcommand),0):(telemetryClient.trackCliSubcommandDescribe(subcommandOriginal),describe(client));default:return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy"),output_manager_default.print(help(deployCommand,{stream:client.stderr,columns:client.stderr.columns})),0):handleDefaultDeploy(client,telemetryClient)}};async function handleInitDeployment(client,telemetryClient){let flagsSpecification=getDeployFlagsSpecification(initSubcommand.options),parsedArguments;try{parsedArguments=parseArguments(client.argv.slice(2),flagsSpecification)}catch(error2){return printError(error2),2}warnDeprecatedShorthands(client,initSubcommand.options),telemetryClient.trackCliFlagJson(parsedArguments.flags["--json"]),telemetryClient.trackCliOptionFormat(parsedArguments.flags["--format"]),telemetryClient.trackCliOptionProject(parsedArguments.flags["--project"]);let projectNameOrId=parsedArguments.flags["--project"],formatResult=validateJsonOutput(parsedArguments.flags);if(!formatResult.valid)return output_manager_default.error(formatResult.error),2;let asJson=formatResult.jsonOutput||client.nonInteractive;if(!applyDeprecatedTargetFlag(client,parsedArguments.flags))return 2;let args=parsedArguments.args;args[0]==="deploy"&&(args=args.slice(1)),args[0]==="init"&&(args=args.slice(1));let paths;args.length>0?(paths=args.map(item=>resolve3(client.cwd,item)),telemetryClient.trackCliArgumentProjectPath(paths[0])):paths=[client.cwd];let pathValidation=await validatePaths(client,paths);if(!pathValidation.valid)return pathValidation.exitCode;await compileVercelConfig(paths[0]);let localConfig=paths[0]===client.cwd?client.localConfig||readLocalConfig(paths[0]):readLocalConfig(paths[0]);if(localConfig){client.localConfig=localConfig;let{version}=localConfig,file=highlight(localConfig[import_client.fileNameSymbol]),prop=code("version");if(version)if(typeof version=="number"){if(version!==2){let two=code(String(2));return output_manager_default.error(`The value of the ${prop} property within ${file} can only be ${two}.`),1}}else return output_manager_default.error(`The ${prop} property inside your ${file} file must be a number.`),1}let{log,debug,error}=output_manager_default,quiet=!client.stdout.isTTY,{path:cwd}=pathValidation,autoConfirm=parsedArguments.flags["--yes"],target=parseTarget({flagName:"environment",flags:parsedArguments.flags});telemetryClient.trackTargetEnvironment(target);let parsedArchive=parsedArguments.flags["--archive"];if(typeof parsedArchive=="string"&&!(isValidArchive(parsedArchive)||parsedArchive===deprecatedArchiveSplitTgz))return output_manager_default.error(`Format must be one of: ${import_client.VALID_ARCHIVE_FORMATS.join(", ")}`),2;parsedArchive===deprecatedArchiveSplitTgz&&output_manager_default.print(`${prependEmoji(`${param("--archive=tgz")} now has the same behavior as ${param("--archive=split-tgz")}. Please use ${param("--archive=tgz")} instead.`,emoji("warning"))}
26
+ vercel deploy continue --deployment ${deploymentId}${cwd}`)}return 0}catch(error){return output_manager_default.debug(error instanceof Error?error.stack??error.message:String(error)),error instanceof DescribeError?fail(error.reason,error.message):error instanceof InvalidToken||isAPIError(error)&&error.status===401?fail("not_authorized","Could not authenticate with Vercel. Check VERCEL_TOKEN in CI, or run `vercel login`."):isAPIError(error)&&error.status===403?fail("not_authorized","Vercel denied access to this deployment. Check that your token has access to the linked project and team."):isAPIError(error)&&error.status===404?fail("not_found",`Deployment ${deploymentId} was not found, or manual provisioning is not enabled for this team.`):isAPIError(error)&&error.status<500&&error.serverMessage?fail("api_error",error.serverMessage):fail("describe_failed","Could not prepare deployment functions. Check the local build and deployment access, then rerun this command.")}}var import_fs_extra3=__toESM(require_lib(),1);import{join as join16}from"path";var import_fs_extra2=__toESM(require_lib(),1),import_ci_info=__toESM(require_ci_info(),1),import_build_utils10=__toESM(require_build_utils(),1),import_error_utils=__toESM(require_dist(),1);import{join as join15}from"path";var VERCEL_DIR_ANONYMOUS="anonymous.json";function anonymousStatePath(cwd){return join15(cwd,VERCEL_DIR,VERCEL_DIR_ANONYMOUS)}async function readAnonymousState(cwd){try{let state=await(0,import_fs_extra2.readJSON)(anonymousStatePath(cwd));if(typeof state?.projectId=="string"&&typeof state.token=="string"&&typeof state.claimUrl=="string"&&typeof state.expiresAt=="number")return state}catch{}return null}async function writeAnonymousState(cwd,state){let path2=anonymousStatePath(cwd);await(0,import_fs_extra2.outputJSON)(path2,state,{spaces:2,mode:384}),await(0,import_fs_extra2.chmod)(path2,384),await addToGitIgnore(cwd)}async function clearAnonymousState(cwd){await(0,import_fs_extra2.remove)(anonymousStatePath(cwd))}async function bootstrapAnonymousProject(client){let{projectId,token,claimUrl,expiresAt}=await client.fetch("/v1/anonymous/projects?surface=cli",{method:"POST",body:{},useCurrentTeam:!1,retry:{retries:0}});return{projectId,token,claimUrl,expiresAt}}async function ensureAnonymousLink(client,cwd,{requireExistingState=!1,confirmed=!0}={}){if(import_ci_info.default.isCI||!!((0,import_build_utils10.getPlatformEnv)("ORG_ID")&&(0,import_build_utils10.getPlatformEnv)("PROJECT_ID"))||!!await getLinkFromDir(getVercelDirectory(cwd))||!!(await getRepoLink(client,cwd))?.repoConfig)return"refused";let state=await readAnonymousState(cwd);if(state&&state.expiresAt<=Date.now())return output_manager_default.prettyError({message:`Your temporary deployment has expired. Run ${getCommandName("login")} to create an account and keep deploying this app.`}),"failed";if(!state&&requireExistingState)return"refused";if(!confirmed&&!state)return"confirmation-required";if(!state){try{state=await bootstrapAnonymousProject(client)}catch(err){return output_manager_default.debug(`Anonymous bootstrap failed: ${(0,import_error_utils.errorToString)(err)}`),"refused"}await writeAnonymousState(cwd,state),output_manager_default.log("Not authenticated. Deploying anonymously.")}return client.authConfig={token:state.token,skipWrite:!0},delete process.env.VERCEL_TEAM_ID,{status:"linked",anonymous:!0,expiresAt:state.expiresAt,claimUrl:state.claimUrl,org:{type:"user",id:"",slug:"anonymous"},project:{id:state.projectId,name:state.projectId}}}function validateAnonymousTarget(isAnonymous,target){return isAnonymous&&target&&target!=="production"?(output_manager_default.error(`Anonymous deployments always target production, so "${target}" is not available. Remove the ${param("--environment")} option, or run ${getCommandName("login")} to deploy to other environments.`),!1):!0}async function setupAnonymousDeployment(client,cwd,{isAnonymous,dryRun}){isAnonymous||await clearAnonymousState(cwd);let anonymousLink;if(isAnonymous){let anonymous=await ensureAnonymousLink(client,cwd,{requireExistingState:dryRun});if(anonymous==="refused"){output_manager_default.log("Temporary deployments aren't available for this attempt. Log in to continue.");let{default:promptMissingCredentials}=await import("../../chunks/prompt-missing-credentials-AUJFBZRC.js"),loginExitCode=await promptMissingCredentials(client);if(loginExitCode!==0)return loginExitCode;isAnonymous=!1}else{if(anonymous==="failed")return 1;if(anonymous==="confirmation-required")return 1;anonymousLink=anonymous}}return{isAnonymous,anonymousLink}}async function handleAnonymousDeploymentError({client,cwd,error,link,isV0,retry}){if(!(!link||!isAPIError(error))){if(error.code==="anonymous_project_claimed"){if(client.nonInteractive||!client.stdin.isTTY)return output_manager_default.prettyError({message:`This project was claimed successfully. Run ${getCommandName("login")} to continue deploying it.`}),1;output_manager_default.log("This project was claimed successfully. Log in to continue deploying it.");let loginExitCode;try{let{default:login}=await import("../../chunks/login-RAN3UBFA.js");loginExitCode=await login(client,{shouldParseArgs:!1})}catch(loginError){return printError(loginError),1}if(loginExitCode!==0)return loginExitCode;let claimedProjectLink=await ensureLink("deploy",client,cwd,{autoConfirm:!0,projectName:link.project.id,failIfNotFound:!0,allowOwnerLookupFallback:!0,v0:isV0});return typeof claimedProjectLink=="number"?claimedProjectLink:(await linkFolderToProject(client,cwd,{projectId:claimedProjectLink.project.id,orgId:claimedProjectLink.org.id},claimedProjectLink.project.name,claimedProjectLink.org.slug,"link",!0,!1),await clearAnonymousState(cwd),retry())}if(error.status===401||error.status===410)return await clearAnonymousState(cwd),output_manager_default.prettyError({message:`Your temporary deployment has expired. Run ${getCommandName("login")} to create an account and keep deploying this app.`}),1}}async function runImplicitBuild(client,cwd){let projectJsonPath=join16(cwd,VERCEL_DIR,VERCEL_DIR_PROJECT),projectJsonExists=await import_fs_extra3.default.pathExists(projectJsonPath);projectJsonExists||await import_fs_extra3.default.outputJSON(projectJsonPath,{settings:{}},{spaces:2}),await import_fs_extra3.default.pathExists(join16(cwd,"package.json"))&&output_manager_default.log("Building your project locally\u2026");let originalArgv=client.argv,originalCwd=client.cwd,originalStdout=client.stdout,previousVercelFirstDeployment=process.env.VERCEL_FIRST_DEPLOYMENT;client.cwd=cwd,client.setArgv([...originalArgv.slice(0,2),"build","--prod","--yes"]),process.env.VERCEL_FIRST_DEPLOYMENT="1",client.stdout=createSinkStream();try{let build=(await import("../build/index.js")).default;return await build(client)}finally{client.setArgv(originalArgv),client.cwd=originalCwd,client.stdout=originalStdout,previousVercelFirstDeployment===void 0?delete process.env.VERCEL_FIRST_DEPLOYMENT:process.env.VERCEL_FIRST_DEPLOYMENT=previousVercelFirstDeployment,projectJsonExists||await import_fs_extra3.default.remove(projectJsonPath)}}function createSinkStream(){return{isTTY:!1,write:()=>!0}}var COMMAND_CONFIG={init:getCommandAliases(initSubcommand),continue:getCommandAliases(continueSubcommand),describe:getCommandAliases(describeSubcommand)},deploy_default=async client=>{let telemetryClient=new DeployTelemetryClient({opts:{store:client.telemetryEventStore}}),parsedArguments=null,flagsSpecification=getDeployFlagsSpecification(deployCommand.options);try{parsedArguments=parseArguments(client.argv.slice(2),flagsSpecification,{permissive:!0})}catch(error){return printError(error),2}let subArgs=parsedArguments.args[0]===deployCommand.name?parsedArguments.args.slice(1):parsedArguments.args,{subcommand,subcommandOriginal}=getSubcommand(subArgs,COMMAND_CONFIG);function printSubcommandHelp(command){output_manager_default.print(help(command,{stream:client.stderr,parent:deployCommand,columns:client.stderr.columns}))}switch(subcommand){case"init":return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy",subcommandOriginal),printSubcommandHelp(initSubcommand),0):(telemetryClient.trackCliSubcommandInit(subcommandOriginal),handleInitDeployment(client,telemetryClient));case"continue":return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy",subcommandOriginal),printSubcommandHelp(continueSubcommand),0):(telemetryClient.trackCliSubcommandContinue(subcommandOriginal),handleContinueSubcommand(client,telemetryClient));case"describe":return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy",subcommandOriginal),printSubcommandHelp(describeSubcommand),0):(telemetryClient.trackCliSubcommandDescribe(subcommandOriginal),describe(client));default:return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy"),output_manager_default.print(help(deployCommand,{stream:client.stderr,columns:client.stderr.columns})),0):handleDefaultDeploy(client,telemetryClient)}};async function handleInitDeployment(client,telemetryClient){let flagsSpecification=getDeployFlagsSpecification(initSubcommand.options),parsedArguments;try{parsedArguments=parseArguments(client.argv.slice(2),flagsSpecification)}catch(error2){return printError(error2),2}warnDeprecatedShorthands(client,initSubcommand.options),telemetryClient.trackCliFlagJson(parsedArguments.flags["--json"]),telemetryClient.trackCliOptionFormat(parsedArguments.flags["--format"]),telemetryClient.trackCliOptionProject(parsedArguments.flags["--project"]);let projectNameOrId=parsedArguments.flags["--project"],formatResult=validateJsonOutput(parsedArguments.flags);if(!formatResult.valid)return output_manager_default.error(formatResult.error),2;let asJson=formatResult.jsonOutput||client.nonInteractive;if(!applyDeprecatedTargetFlag(client,parsedArguments.flags))return 2;let args=parsedArguments.args;args[0]==="deploy"&&(args=args.slice(1)),args[0]==="init"&&(args=args.slice(1));let paths;args.length>0?(paths=args.map(item=>resolve3(client.cwd,item)),telemetryClient.trackCliArgumentProjectPath(paths[0])):paths=[client.cwd];let pathValidation=await validatePaths(client,paths);if(!pathValidation.valid)return pathValidation.exitCode;await compileVercelConfig(paths[0]);let localConfig=paths[0]===client.cwd?client.localConfig||readLocalConfig(paths[0]):readLocalConfig(paths[0]);if(localConfig){client.localConfig=localConfig;let{version}=localConfig,file=highlight(localConfig[import_client.fileNameSymbol]),prop=code("version");if(version)if(typeof version=="number"){if(version!==2){let two=code(String(2));return output_manager_default.error(`The value of the ${prop} property within ${file} can only be ${two}.`),1}}else return output_manager_default.error(`The ${prop} property inside your ${file} file must be a number.`),1}let{log,debug,error}=output_manager_default,quiet=!client.stdout.isTTY,{path:cwd}=pathValidation,autoConfirm=parsedArguments.flags["--yes"],target=parseTarget({flagName:"environment",flags:parsedArguments.flags});telemetryClient.trackTargetEnvironment(target);let parsedArchive=parsedArguments.flags["--archive"];if(typeof parsedArchive=="string"&&!(isValidArchive(parsedArchive)||parsedArchive===deprecatedArchiveSplitTgz))return output_manager_default.error(`Format must be one of: ${import_client.VALID_ARCHIVE_FORMATS.join(", ")}`),2;parsedArchive===deprecatedArchiveSplitTgz&&output_manager_default.print(`${prependEmoji(`${param("--archive=tgz")} now has the same behavior as ${param("--archive=split-tgz")}. Please use ${param("--archive=tgz")} instead.`,emoji("warning"))}
24
27
  `);let cliMeta=parseMeta(parsedArguments.flags["--meta"]),isV0=cliMeta.v0==="true";getGitExecutable(cwd);let link=await ensureLink("deploy",client,cwd,{autoConfirm,projectName:projectNameOrId??localConfig?.name,failIfNotFound:!!projectNameOrId,v0:isV0});if(typeof link=="number")return link;let{org,project}=link,rootDirectory=project.rootDirectory,sourceFilesOutsideRootDirectory=project.sourceFilesOutsideRootDirectory??!0;link.repoRoot&&(cwd=link.repoRoot);let contextName=org.slug;if(client.config.currentTeam=org.type==="team"?org.id:void 0,rootDirectory&&await validateRootDirectory(cwd,join17(cwd,rootDirectory),project?`To change your Project Settings, go to https://vercel.com/${org?.slug}/${project.name}/settings`:"")===!1)return 1;if(await promptExperimentalServicesMigration({client,cwd:join17(cwd,rootDirectory||""),autoConfirm:!!parsedArguments.flags["--yes"],nonInteractive:client.nonInteractive})&&(localConfig=readLocalConfig(join17(cwd,rootDirectory||""))),rootDirectory){let rootDirectoryPath=join17(cwd,rootDirectory);await compileVercelConfig(rootDirectoryPath);let rootDirectoryConfig=readLocalConfig(rootDirectoryPath);rootDirectoryConfig?(debug(`Read local config from root directory (${rootDirectory})`),localConfig=rootDirectoryConfig):localConfig&&output_manager_default.print(`${prependEmoji(`The ${highlight(localConfig[import_client.fileNameSymbol])} file should be inside of the provided root directory.`,emoji("warning"))}
25
28
  `)}localConfig=localConfig||{},localConfig.name&&output_manager_default.print(`${prependEmoji(`The ${code("name")} property in ${highlight(localConfig[import_client.fileNameSymbol])} is deprecated (https://vercel.link/name-prop)`,emoji("warning"))}
26
29
  `);let isObject=item=>Object.prototype.toString.call(item)==="[object Object]";if(typeof localConfig.env<"u"&&!isObject(localConfig.env))return error(`The ${code("env")} property in ${highlight(localConfig[import_client.fileNameSymbol])} needs to be an object`),1;if(typeof localConfig.build<"u"){if(!isObject(localConfig.build))return error(`The ${code("build")} property in ${highlight(localConfig[import_client.fileNameSymbol])} needs to be an object`),1;if(typeof localConfig.build.env<"u"&&!isObject(localConfig.build.env))return error(`The ${code("build.env")} property in ${highlight(localConfig[import_client.fileNameSymbol])} needs to be an object`),1}let meta=Object.assign({},parseMeta(localConfig.meta),cliMeta),gitMetadata=client.withTrace("vc.cli.deploy.git_metadata",()=>createGitMeta(join17(cwd,project.rootDirectory||""),project));gitMetadata.catch(()=>{});let deploymentEnv=Object.assign({},parseEnv(localConfig.env),parseEnv(parsedArguments.flags["--env"])),deploymentBuildEnv=Object.assign({},parseEnv(localConfig.build&&localConfig.build.env),parseEnv(parsedArguments.flags["--build-env"]));try{await addProcessEnv(log,deploymentEnv),await addProcessEnv(log,deploymentBuildEnv)}catch(err){return error((0,import_error_utils2.errorToString)(err)),1}let regionFlag=(parsedArguments.flags["--regions"]||"").split(",").map(s=>s.trim()).filter(Boolean),regions=regionFlag.length>0?regionFlag:localConfig.regions,currentTeam=org.type==="team"?org.id:void 0,now=new Now({client,currentTeam}),deployStamp=stamp_default(),localConfigurationOverrides=pickOverrides(localConfig),name=project.name;if(!name)throw new Error("`name` not found on project or provided by existing project");let noWait=!0;try{let autoAssignCustomDomains=parsedArguments.flags["--skip-domain"]?!1:void 0,createArgs={name,env:deploymentEnv,build:{env:deploymentBuildEnv},forceNew:parsedArguments.flags["--force"],withCache:parsedArguments.flags["--with-cache"],prebuilt:!0,vercelOutputDir:void 0,rootDirectory,quiet,nowConfig:{...localConfig,images:void 0},regions,meta,gitMetadata,deployStamp,target,skipAutoDetectionConfirmation:autoConfirm,noWait,withFullLogs:!1,autoAssignCustomDomains,manual:!0,jsonOutput:asJson,linkedProject:project};(!localConfig.builds||localConfig.builds.length===0)&&(createArgs.projectSettings={sourceFilesOutsideRootDirectory,rootDirectory,...localConfigurationOverrides});let{packageJson}=await(0,import_build_utils11.findPackageJson)(join17(cwd,project?.rootDirectory??""),!0,cwd),nodeVersion;if(packageJson?.engines?.node)try{let{range}=await(0,import_build_utils11.getSupportedNodeVersion)(packageJson.engines.node);nodeVersion=range}catch(error2){error2 instanceof Error&&output_manager_default.warn(error2.message)}createArgs.projectSettings||(createArgs.projectSettings={}),createArgs.projectSettings.nodeVersion=nodeVersion;let deployment=await createDeploy(client,now,contextName,cwd,createArgs,org,!project,parsedArchive?"tgz":void 0);if(deployment instanceof NotDomainOwner)return recordCliError({code:"not_domain_owner"}),client.nonInteractive?(client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.ERROR,reason:"not_domain_owner",message:deployment.message,next:[{command:withGlobalFlags(client,"deploy"),when:"retry deploy"}]},null,2)}
@@ -52,9 +55,9 @@ See all options:
52
55
  `),1):(error("Uploading failed. Please try again."),1)}catch(err){recordCliError(cliErrorFromUnknown(err)),(0,import_error_utils2.isError)(err)&&debug(`Error: ${err}
53
56
  ${err.stack}`);let anonymousExitCode=await handleAnonymousDeploymentError({client,cwd,error:err,link:anonymousLink,isV0,retry:()=>handleDefaultDeploy(client,telemetryClient)});if(anonymousExitCode!==void 0)return anonymousExitCode;if(err instanceof UploadErrorMissingArchive)return client.nonInteractive?(client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.ERROR,reason:"missing_archive",message:err.message,next:[{command:redeployCommand,when:"retry deploy"}]},null,2)}
54
57
  `),1):(output_manager_default.prettyError(err),1);if(err instanceof NotDomainOwner)return recordCliError({code:"not_domain_owner"},{override:!0}),client.nonInteractive?(client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.ERROR,reason:"not_domain_owner",message:err.message,next:[{command:redeployCommand,when:"retry deploy"}]},null,2)}
55
- `),1):(output_manager_default.error(err.message),1);if(err instanceof DomainNotFound&&err.meta&&err.meta.domain){output_manager_default.debug(`The domain ${err.meta.domain} was not found, trying to purchase it`);let{default:purchaseDomainIfAvailable}=await import("../../chunks/purchase-domain-if-available-BHFBD3LW.js"),purchase=await purchaseDomainIfAvailable(client,err.meta.domain,contextName);return purchase===!0?(output_manager_default.success(`Successfully purchased the domain ${err.meta.domain}!`),0):purchase===!1||purchase instanceof UserAborted?(handleCreateDeployError(deployment,localConfig),1):(handleCreateDeployError(purchase,localConfig)!==1&&output_manager_default.error(purchase.message),1)}if(err instanceof DomainNotFound||err instanceof DomainNotVerified||err instanceof NotDomainOwner||err instanceof DomainPermissionDenied||err instanceof DomainVerificationFailed||err instanceof SchemaValidationFailed||err instanceof InvalidDomain||err instanceof DeploymentNotFound||err instanceof BuildsRateLimited||err instanceof DeploymentsRateLimited||err instanceof AliasDomainConfigured||err instanceof MissingBuildScript||err instanceof ConflictingFilePath||err instanceof ConflictingPathSegment||err instanceof ConflictingConfigFiles)return client.nonInteractive&&client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.ERROR,reason:"deploy_failed",message:err instanceof Error?err.message:String(err),next:[{command:redeployCommand,when:"retry deploy"}]},null,2)}
58
+ `),1):(output_manager_default.error(err.message),1);if(err instanceof DomainNotFound&&err.meta&&err.meta.domain){output_manager_default.debug(`The domain ${err.meta.domain} was not found, trying to purchase it`);let{default:purchaseDomainIfAvailable}=await import("../../chunks/purchase-domain-if-available-6FAGFFWC.js"),purchase=await purchaseDomainIfAvailable(client,err.meta.domain,contextName);return purchase===!0?(output_manager_default.success(`Successfully purchased the domain ${err.meta.domain}!`),0):purchase===!1||purchase instanceof UserAborted?(handleCreateDeployError(deployment,localConfig),1):(handleCreateDeployError(purchase,localConfig)!==1&&output_manager_default.error(purchase.message),1)}if(err instanceof DomainNotFound||err instanceof DomainNotVerified||err instanceof NotDomainOwner||err instanceof DomainPermissionDenied||err instanceof DomainVerificationFailed||err instanceof SchemaValidationFailed||err instanceof InvalidDomain||err instanceof DeploymentNotFound||err instanceof BuildsRateLimited||err instanceof DeploymentsRateLimited||err instanceof AliasDomainConfigured||err instanceof MissingBuildScript||err instanceof ConflictingFilePath||err instanceof ConflictingPathSegment||err instanceof ConflictingConfigFiles)return client.nonInteractive&&client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.ERROR,reason:"deploy_failed",message:err instanceof Error?err.message:String(err),next:[{command:redeployCommand,when:"retry deploy"}]},null,2)}
56
59
  `),handleCreateDeployError(err,localConfig),1;if(err instanceof BuildError){let buildFailedNext=[...now.url?[{command:withGlobalFlags(client,`inspect ${now.url} --logs`),when:"read build logs"}]:[],{command:redeployCommand,when:"retry deploy"}];if(now.url)try{let failedDeployment=await getDeployment(client,contextName,now.url);if(asJson){output_manager_default.stopSpinner();let deploymentJson=getDeploymentOutputJson(failedDeployment,client.apiUrl,{name:"BUILD_ERROR",message:err.message}),payload=client.nonInteractive?{status:AGENT_STATUS.ERROR,reason:"build_failed",message:err.message,deployment:deploymentJson,next:buildFailedNext}:deploymentJson;client.stdout.write(`${JSON.stringify(payload,null,2)}
57
- `)}else if(withFullLogs===!1){let{displayBuildLogsUntilFinalError}=await import("../../chunks/logs-KMQATUYR.js");await displayBuildLogsUntilFinalError(client,failedDeployment,err.message)}}catch{if(asJson){output_manager_default.stopSpinner();let payload=client.nonInteractive?{status:AGENT_STATUS.ERROR,reason:"build_failed",message:err.message,url:`https://${now.url}`,next:buildFailedNext}:{error:{name:"BUILD_ERROR",message:err.message},url:`https://${now.url}`};client.stdout.write(`${JSON.stringify(payload,null,2)}
60
+ `)}else if(withFullLogs===!1){let{displayBuildLogsUntilFinalError}=await import("../../chunks/logs-L3VFH7SK.js");await displayBuildLogsUntilFinalError(client,failedDeployment,err.message)}}catch{if(asJson){output_manager_default.stopSpinner();let payload=client.nonInteractive?{status:AGENT_STATUS.ERROR,reason:"build_failed",message:err.message,url:`https://${now.url}`,next:buildFailedNext}:{error:{name:"BUILD_ERROR",message:err.message},url:`https://${now.url}`};client.stdout.write(`${JSON.stringify(payload,null,2)}
58
61
  `)}else output_manager_default.log(`To check build logs run: ${getCommandName(`inspect ${now.url} --logs`)}`),output_manager_default.log(`Or inspect them in your browser at https://${now.url}/_logs`)}else client.nonInteractive&&(output_manager_default.stopSpinner(),client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.ERROR,reason:"build_failed",message:err.message,next:buildFailedNext},null,2)}
59
62
  `));return 1}if(isAPIError(err)&&err.code==="size_limit_exceeded"){let{sizeLimit=0}=err,message=`File size limit exceeded (${(0,import_bytes.default)(sizeLimit)})`;return client.nonInteractive&&client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.ERROR,reason:"size_limit_exceeded",message,next:[{command:redeployCommand,when:"retry deploy"}]},null,2)}
60
63
  `),error(message),1}return client.nonInteractive&&client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.ERROR,reason:"deploy_failed",message:err instanceof Error?err.message:String(err),next:[{command:redeployCommand,when:"retry deploy"}]},null,2)}