@vercel/cli-support 66.3.0-snapshot-3206bcf0afd3 → 66.3.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 (188) hide show
  1. package/dist/chunks/{add-U6KDXZT2.js → add-AA7ATWNJ.js} +1 -1
  2. package/dist/chunks/{add-ECNHL7CN.js → add-D7V4UY7M.js} +1 -1
  3. package/dist/chunks/{add-3P4HAZZZ.js → add-IRTM2Q6Q.js} +1 -1
  4. package/dist/chunks/{alerts-MDU5KBQL.js → alerts-HNX4G7UF.js} +1 -1
  5. package/dist/chunks/{build-HM5K3QD7.js → build-3TNPGMCK.js} +1 -1
  6. package/dist/chunks/{chunk-TT4PL5J2.js → chunk-2DNOJRZY.js} +1 -1
  7. package/dist/chunks/{chunk-6QEQI5SY.js → chunk-3JP2EUHQ.js} +1 -1
  8. package/dist/chunks/{chunk-IL27CVNF.js → chunk-3LNBGHWC.js} +1 -1
  9. package/dist/chunks/{chunk-TSLAMIUI.js → chunk-3SAOTU5Z.js} +1 -1
  10. package/dist/chunks/{chunk-FDVLR2HV.js → chunk-3UR42KVA.js} +1 -1
  11. package/dist/chunks/{chunk-5O77DSX4.js → chunk-47ZBTGAH.js} +1 -1
  12. package/dist/chunks/{chunk-EA55QLHA.js → chunk-4AET2E4U.js} +1 -1
  13. package/dist/chunks/{chunk-QZMBBLOQ.js → chunk-4FKAPGH3.js} +1 -1
  14. package/dist/chunks/{chunk-5VGAD2ZS.js → chunk-4OC4CVBM.js} +1 -1
  15. package/dist/chunks/{chunk-76VUFE3K.js → chunk-5GDRVPSL.js} +1 -1
  16. package/dist/chunks/{chunk-XL2PHD4X.js → chunk-5HEF6CPE.js} +5 -5
  17. package/dist/chunks/{chunk-F52YOIDM.js → chunk-5PFQCTFC.js} +1 -1
  18. package/dist/chunks/{chunk-R5U4P7WK.js → chunk-5VI33HDO.js} +1 -1
  19. package/dist/chunks/{chunk-RX5HH3T6.js → chunk-5XBV4XTK.js} +1 -1
  20. package/dist/chunks/{chunk-6FDTVIJM.js → chunk-6JYMXLQZ.js} +1 -1
  21. package/dist/chunks/{chunk-PX55WGPZ.js → chunk-7J7LHIO4.js} +2 -2
  22. package/dist/chunks/{chunk-HQWR3EDU.js → chunk-A3ZPQUWM.js} +1 -1
  23. package/dist/chunks/{chunk-ZXNR7CNU.js → chunk-AIAS6KAV.js} +1 -1
  24. package/dist/chunks/{chunk-FRKDI2ZH.js → chunk-AYAUO37X.js} +1 -1
  25. package/dist/chunks/{chunk-WCCKCQ43.js → chunk-B7VPXDY2.js} +1 -1
  26. package/dist/chunks/{chunk-7THDUCSM.js → chunk-BLNGQEOB.js} +1 -1
  27. package/dist/chunks/{chunk-POKRDE5J.js → chunk-BQXFIDDA.js} +1 -1
  28. package/dist/chunks/{chunk-O3IQMUYI.js → chunk-CV7TBU72.js} +1 -1
  29. package/dist/chunks/{chunk-66VYZZTY.js → chunk-DGM7TXOL.js} +1 -1
  30. package/dist/chunks/{chunk-LOA7SZWH.js → chunk-DJZBJC2A.js} +1 -1
  31. package/dist/chunks/{chunk-O2HDXF5B.js → chunk-DLNT37B7.js} +1 -1
  32. package/dist/chunks/{chunk-KKO6DF57.js → chunk-DMNXLZPG.js} +1 -1
  33. package/dist/chunks/{chunk-HIV3C763.js → chunk-E3AER2ZV.js} +1 -1
  34. package/dist/chunks/{chunk-QQNN5X7M.js → chunk-EKZCZAUD.js} +1 -1
  35. package/dist/chunks/{chunk-UWISBHZI.js → chunk-FCYAT6R3.js} +1 -1
  36. package/dist/chunks/{chunk-NGHAU23V.js → chunk-FFOUIGIX.js} +1 -1
  37. package/dist/chunks/{chunk-CY5KJ42N.js → chunk-FSKZU5GL.js} +1 -1
  38. package/dist/chunks/{chunk-FZBYQQQQ.js → chunk-FXQUNFSH.js} +1 -1
  39. package/dist/chunks/{chunk-QYUKDP2E.js → chunk-G2PXZASE.js} +1 -1
  40. package/dist/chunks/{chunk-Q2R3VQER.js → chunk-G6RUNMW3.js} +1 -1
  41. package/dist/chunks/{chunk-7ECYJHY4.js → chunk-GKAL5XJ2.js} +1 -1
  42. package/dist/chunks/{chunk-KBJNREND.js → chunk-H5HAY5QD.js} +1 -1
  43. package/dist/chunks/{chunk-POFKUONR.js → chunk-I5JHC377.js} +1 -1
  44. package/dist/chunks/{chunk-UEJ332R4.js → chunk-IE3NP5SP.js} +1 -1
  45. package/dist/chunks/{chunk-TVELM5HH.js → chunk-IIIUFOO3.js} +1 -1
  46. package/dist/chunks/{chunk-SW26TCUB.js → chunk-IQDX4HQ6.js} +1 -1
  47. package/dist/chunks/{chunk-WOD4NOA2.js → chunk-IRWUACWI.js} +1 -1
  48. package/dist/chunks/{chunk-APSIPJAY.js → chunk-K4G4U7DO.js} +1 -1
  49. package/dist/chunks/{chunk-7OMVAZSA.js → chunk-K67DPRBW.js} +1 -1
  50. package/dist/chunks/{chunk-UMGQUJYO.js → chunk-K7Y5XK5I.js} +1 -1
  51. package/dist/chunks/{chunk-PB7GGE3Q.js → chunk-L6MIF7TR.js} +1 -1
  52. package/dist/chunks/{chunk-ZPXTTQJT.js → chunk-L77Q4FMH.js} +1 -1
  53. package/dist/chunks/{chunk-A3MC5BEZ.js → chunk-LEVOFTD6.js} +1 -1
  54. package/dist/chunks/{chunk-BLLDEVSD.js → chunk-MGG3COFN.js} +1 -1
  55. package/dist/chunks/{chunk-O4WJDJIL.js → chunk-N54TQNDY.js} +2 -2
  56. package/dist/chunks/{chunk-IWIXET6Q.js → chunk-OJHP5UDW.js} +1 -1
  57. package/dist/chunks/{chunk-2WQCAJBU.js → chunk-OZREKEPK.js} +1 -1
  58. package/dist/chunks/{chunk-G56HLQLB.js → chunk-P3MT7Z74.js} +1 -1
  59. package/dist/chunks/{chunk-KLETLUS6.js → chunk-PK5SI25Q.js} +1 -1
  60. package/dist/chunks/{chunk-K4KP5UR3.js → chunk-QRGX7HHA.js} +1 -1
  61. package/dist/chunks/{chunk-OYQOYJSJ.js → chunk-RS32ZNRX.js} +1 -1
  62. package/dist/chunks/{chunk-2HW7KKB5.js → chunk-SVU3REDI.js} +1 -1
  63. package/dist/chunks/{chunk-PNWRO3XW.js → chunk-SWYNL72F.js} +1 -1
  64. package/dist/chunks/{chunk-MU3DV4IW.js → chunk-TY3WOAB2.js} +1 -1
  65. package/dist/chunks/{chunk-Y4D7IX3M.js → chunk-U65RJEYM.js} +1 -1
  66. package/dist/chunks/{chunk-KTWGUBNP.js → chunk-ULJ4OAE3.js} +1 -1
  67. package/dist/chunks/chunk-ULUC26PZ.js +13 -0
  68. package/dist/chunks/chunk-UUI3ETQT.js +7 -0
  69. package/dist/chunks/{chunk-2ANPVGOC.js → chunk-UVC7YBW6.js} +1 -1
  70. package/dist/chunks/{chunk-X26PXKHC.js → chunk-V3E3S5NZ.js} +1 -1
  71. package/dist/chunks/{chunk-JGUMBEQH.js → chunk-VQUHN5HW.js} +1 -1
  72. package/dist/chunks/{chunk-A5FPKXEK.js → chunk-W6GX7PJ4.js} +1 -1
  73. package/dist/chunks/{chunk-ECQIO5K3.js → chunk-WNB3JZMX.js} +1 -1
  74. package/dist/chunks/{chunk-M23GYM4J.js → chunk-WWUJJI47.js} +2 -2
  75. package/dist/chunks/{chunk-TIOZWOR5.js → chunk-X36G7TQ3.js} +1 -1
  76. package/dist/chunks/{chunk-3FMDKPIO.js → chunk-XWCYHZL4.js} +1 -1
  77. package/dist/chunks/{chunk-LXZ45FUT.js → chunk-XX6VYGGD.js} +1 -1
  78. package/dist/chunks/{chunk-FSZJSIOF.js → chunk-YAODBCTH.js} +1 -1
  79. package/dist/chunks/{chunk-CRX7RINU.js → chunk-YT5VHDJF.js} +1 -1
  80. package/dist/chunks/{chunk-7KPAYK2N.js → chunk-ZBOHFQ7B.js} +1 -1
  81. package/dist/chunks/{chunk-A72AM25W.js → chunk-ZEXRYJPK.js} +1 -1
  82. package/dist/chunks/{chunk-3HCRJO4D.js → chunk-ZLUNCQCF.js} +1 -1
  83. package/dist/chunks/{clear-YJRG7CEK.js → clear-LAQS2IZP.js} +1 -1
  84. package/dist/chunks/{compile-vercel-config-GB4X7U3B.js → compile-vercel-config-BSZPZNDE.js} +1 -1
  85. package/dist/chunks/{config-ARJS37DC.js → config-RACUYTCP.js} +1 -1
  86. package/dist/chunks/{config-L6EQFXGH.js → config-WSYXQGDJ.js} +1 -1
  87. package/dist/chunks/{contract-UAIZFVBK.js → contract-L74DC7DR.js} +1 -1
  88. package/dist/chunks/{delete-CBLBTPK2.js → delete-2IXAHPKT.js} +1 -1
  89. package/dist/chunks/{delete-SY56OAFL.js → delete-PAG6CX7J.js} +1 -1
  90. package/dist/chunks/{describe-Z6RRPRGF.js → describe-FML7BGM3.js} +1 -1
  91. package/dist/chunks/{detect-services-PFR6C4LZ.js → detect-services-77BZUFRQ.js} +1 -1
  92. package/dist/chunks/{disable-E6GTV4NN.js → disable-SINBS6QV.js} +1 -1
  93. package/dist/chunks/{discard-NW6RI3KK.js → discard-DSPG3AGG.js} +1 -1
  94. package/dist/chunks/{edit-K7NN4KRI.js → edit-IGUAZVMB.js} +1 -1
  95. package/dist/chunks/{edit-E4SQL4UK.js → edit-QE652JLN.js} +1 -1
  96. package/dist/chunks/{enable-AY4NQ65W.js → enable-EI22EQNY.js} +1 -1
  97. package/dist/chunks/{export-CW5Q5MDC.js → export-4GR6ROVX.js} +1 -1
  98. package/dist/chunks/{future-3QDT3U5W.js → future-SZN7PTD5.js} +1 -1
  99. package/dist/chunks/{generate-cert-for-deploy-FQQZEMTU.js → generate-cert-for-deploy-OVN7FAM7.js} +1 -1
  100. package/dist/chunks/{image-PJBSA7SU.js → image-VRVPLM2G.js} +1 -1
  101. package/dist/chunks/{import-builders-K6D5OFHY.js → import-builders-EO654C2B.js} +1 -1
  102. package/dist/chunks/{inspect-G6ATTJHN.js → inspect-3I4RQZKD.js} +1 -1
  103. package/dist/chunks/{inspect-DO5J2KGE.js → inspect-3UU22APK.js} +1 -1
  104. package/dist/chunks/{inspect-K23UNJUJ.js → inspect-J77GNR6J.js} +1 -1
  105. package/dist/chunks/{inspect-QXRA3OU5.js → inspect-LOUW7DBU.js} +1 -1
  106. package/dist/chunks/{inspect-73R4TFWK.js → inspect-YRVZB5KK.js} +1 -1
  107. package/dist/chunks/{inspect-WHGJZAK3.js → inspect-YX57D7BT.js} +1 -1
  108. package/dist/chunks/{list-EUJMPCD6.js → list-4PTMG4PX.js} +1 -1
  109. package/dist/chunks/{list-ARMBYZH7.js → list-JZB7VBAL.js} +1 -1
  110. package/dist/chunks/{list-G6GK67GL.js → list-TLRTYR4T.js} +1 -1
  111. package/dist/chunks/{list-LRV6CWNG.js → list-VEWDGHHC.js} +1 -1
  112. package/dist/chunks/{login-JSDPVUSB.js → login-DTBPOVNW.js} +1 -1
  113. package/dist/chunks/{login-UIKDCM7X.js → login-FLRZ2P3G.js} +1 -1
  114. package/dist/chunks/{logs-NICAAFXU.js → logs-YAOOFTTO.js} +1 -1
  115. package/dist/chunks/{ls-ZW2V7TME.js → ls-7SAXJ6II.js} +1 -1
  116. package/dist/chunks/{ls-JDKTIVX6.js → ls-B2FU3Q52.js} +1 -1
  117. package/dist/chunks/{ls-E4Q4XPAI.js → ls-F66X3XB6.js} +1 -1
  118. package/dist/chunks/{ls-5STG344U.js → ls-HHF5ND74.js} +1 -1
  119. package/dist/chunks/{ls-H7YD27XH.js → ls-KWOOKVQC.js} +1 -1
  120. package/dist/chunks/{ls-HJVYRGQ3.js → ls-RDCIIYGZ.js} +1 -1
  121. package/dist/chunks/{ls-5ULLIYRA.js → ls-XI622GX2.js} +1 -1
  122. package/dist/chunks/{migrate-experimental-services-XEKA373Q.js → migrate-experimental-services-TJAX4SUC.js} +1 -1
  123. package/dist/chunks/{mutate-2GXUWHWY.js → mutate-GXHWSVRX.js} +1 -1
  124. package/dist/chunks/{notifications-YG44KHCP.js → notifications-JX5GDVGX.js} +1 -1
  125. package/dist/chunks/{open-GGWBQAKT.js → open-3KATFISG.js} +1 -1
  126. package/dist/chunks/{openapi-4KMLRPJV.js → openapi-6GESF6CU.js} +1 -1
  127. package/dist/chunks/{permissions-SJVEJGPH.js → permissions-7YZ7DUQ4.js} +1 -1
  128. package/dist/chunks/{plugin-offer-VNXKPNBY.js → plugin-offer-FWU44GUW.js} +1 -1
  129. package/dist/chunks/{prompt-missing-credentials-RJS5U5IJ.js → prompt-missing-credentials-QT37RTID.js} +1 -1
  130. package/dist/chunks/{publish-GGFL7JVW.js → publish-JP47GZSB.js} +1 -1
  131. package/dist/chunks/{pull-36Z6T5C7.js → pull-IKI7CJFO.js} +1 -1
  132. package/dist/chunks/{purchase-domain-if-available-IS62APPK.js → purchase-domain-if-available-GDQAK76N.js} +1 -1
  133. package/dist/chunks/{push-I37EBJMR.js → push-N6X5C74J.js} +1 -1
  134. package/dist/chunks/query-R2JV3ZQW.js +7 -0
  135. package/dist/chunks/raw-query-WIFJFDOU.js +8 -0
  136. package/dist/chunks/{reauthenticate-U3XWAOMM.js → reauthenticate-MWLCQBQI.js} +1 -1
  137. package/dist/chunks/{remove-T4EBT5XK.js → remove-FS3G7IMA.js} +1 -1
  138. package/dist/chunks/{reorder-JC3L7CJO.js → reorder-6VMRUXNV.js} +1 -1
  139. package/dist/chunks/{reply-5KJBWMPI.js → reply-OCGJHB2J.js} +1 -1
  140. package/dist/chunks/{resolve-3ZU3DHFZ.js → resolve-FRTWFQDV.js} +1 -1
  141. package/dist/chunks/resolve-agent-team-425ASUR4.js +7 -0
  142. package/dist/chunks/{restore-S4AWLRK7.js → restore-W746CAPM.js} +1 -1
  143. package/dist/chunks/{rm-QFQTQKZL.js → rm-2XTFNLPM.js} +1 -1
  144. package/dist/chunks/{rm-YAKU3AIF.js → rm-6BVGVK4Q.js} +1 -1
  145. package/dist/chunks/{rm-X47BKCHC.js → rm-GWRCFCWV.js} +1 -1
  146. package/dist/chunks/{rm-PO6GFUKD.js → rm-PS3ZQPQQ.js} +1 -1
  147. package/dist/chunks/{rm-FXS5DZLW.js → rm-VDSIAKZH.js} +1 -1
  148. package/dist/chunks/{rule-inspect-DTHMNVKJ.js → rule-inspect-RZEYDPVH.js} +1 -1
  149. package/dist/chunks/{schema-DB45ARBN.js → schema-DT5Z3KOQ.js} +1 -1
  150. package/dist/chunks/schema-Q6BY2KQG.js +14 -0
  151. package/dist/chunks/{select-org-MUG3UCJA.js → select-org-BU6WWRYV.js} +1 -1
  152. package/dist/chunks/{set-PKLCP3YM.js → set-JXOXE3GL.js} +1 -1
  153. package/dist/chunks/{set-MMOLNY72.js → set-KSFGCBXX.js} +1 -1
  154. package/dist/chunks/{setup-and-link-5OA6HGVD.js → setup-and-link-JVP4U43T.js} +1 -1
  155. package/dist/chunks/{skills-DO7WMK5K.js → skills-Y6SPYENI.js} +1 -1
  156. package/dist/chunks/{tags-GBA56ZTZ.js → tags-HFUSHLEB.js} +1 -1
  157. package/dist/chunks/{types-S7I5EBVX.js → types-FHWBRHGN.js} +1 -1
  158. package/dist/chunks/{update-7H2XLOJU.js → update-VQ2EGHJV.js} +1 -1
  159. package/dist/chunks/{usage-V2GS5NFF.js → usage-HI2Z6IKN.js} +1 -1
  160. package/dist/commands/build/index.js +1 -1
  161. package/dist/commands/deploy/index.js +4 -4
  162. package/dist/commands/dev/index.js +2 -2
  163. package/dist/commands/env/index.js +1 -1
  164. package/dist/commands/link/index.js +1 -1
  165. package/dist/commands/list/index.js +1 -1
  166. package/dist/commands/project/index.js +21 -6
  167. package/dist/commands/tunnel/index.js +1 -1
  168. package/dist/commands-account.js +2 -2
  169. package/dist/commands-ai.js +2 -2
  170. package/dist/commands-blob.js +1 -1
  171. package/dist/commands-core.js +7 -7
  172. package/dist/commands-deployments.js +1 -1
  173. package/dist/commands-flags.js +1 -1
  174. package/dist/commands-integrations.js +16 -7
  175. package/dist/commands-observability.js +2 -2
  176. package/dist/commands-routing.js +10 -10
  177. package/dist/index.js +5 -5
  178. package/dist/internal-build.js +1 -1
  179. package/dist/package.json +1 -1
  180. package/dist/version.mjs +1 -1
  181. package/package.json +11 -11
  182. package/dist/chunks/chunk-5IZI5QH6.js +0 -8
  183. package/dist/chunks/chunk-YJP25FL6.js +0 -7
  184. package/dist/chunks/chunk-ZGATYK5C.js +0 -13
  185. package/dist/chunks/query-UEIQYCYU.js +0 -7
  186. package/dist/chunks/raw-query-AY5G6GUK.js +0 -8
  187. package/dist/chunks/resolve-agent-team-XPLMABIA.js +0 -7
  188. package/dist/chunks/schema-NMGD2R2B.js +0 -14
@@ -4,7 +4,7 @@ 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{fetchDeploymentBuildEnv,isPlainPath,resolvePerDirectoryLinkRoot}from"../../chunks/chunk-6QEQI5SY.js";import{createErrorReporter,import_write_build_result,require_detect_builders_with_services,require_get_files,require_service_schedules,require_write_build_result,writeBuildResult}from"../../chunks/chunk-FDVLR2HV.js";import{importBuilders,import_import_builders,preloadVltBuilderImports}from"../../chunks/chunk-NGHAU23V.js";import"../../chunks/chunk-4CACOKMS.js";import{require_dist as require_dist4}from"../../chunks/chunk-DMZLFZBX.js";import{require_constants,require_entrypoint,validateConfig}from"../../chunks/chunk-A7E3EGDM.js";import{toDiagnostic}from"../../chunks/chunk-UECFEOOH.js";import{require_ajv}from"../../chunks/chunk-5CVEW3HD.js";import"../../chunks/chunk-MCRKBVZA.js";import{pullCommandLogic}from"../../chunks/chunk-ZXNR7CNU.js";import{readProjectSettings}from"../../chunks/chunk-A72AM25W.js";import{compileVercelConfig,findSourceVercelConfigFile,require_main}from"../../chunks/chunk-WCCKCQ43.js";import{require_semver}from"../../chunks/chunk-BPUANOGW.js";import{readJSONFile}from"../../chunks/chunk-R5U4P7WK.js";import"../../chunks/chunk-V6Y6UK6B.js";import"../../chunks/chunk-IL27CVNF.js";import"../../chunks/chunk-M32HBBPK.js";import"../../chunks/chunk-7THDUCSM.js";import{stamp_default}from"../../chunks/chunk-A2RZZQEP.js";import"../../chunks/chunk-Q7D7RGXM.js";import{require_dist as require_dist3}from"../../chunks/chunk-AMOI3EAW.js";import{require_minimatch}from"../../chunks/chunk-REJLEESP.js";import{require_dist as require_dist2}from"../../chunks/chunk-ISSNEDG5.js";import"../../chunks/chunk-G56HLQLB.js";import"../../chunks/chunk-O2HDXF5B.js";import{require_dist,require_frameworks}from"../../chunks/chunk-ZKNEIE44.js";import"../../chunks/chunk-KR4DMT3I.js";import{applyDeprecatedTargetFlag,parseTarget}from"../../chunks/chunk-HAGBKLAS.js";import"../../chunks/chunk-TT4PL5J2.js";import"../../chunks/chunk-POKRDE5J.js";import"../../chunks/chunk-QQNN5X7M.js";import"../../chunks/chunk-7YKFF6CE.js";import"../../chunks/chunk-3UZE566G.js";import"../../chunks/chunk-SZO73QV5.js";import"../../chunks/chunk-TAAWMNNL.js";import"../../chunks/chunk-25565AGS.js";import"../../chunks/chunk-PVASGBEF.js";import{ensureLink}from"../../chunks/chunk-O4WJDJIL.js";import{printProjectNotFoundError}from"../../chunks/chunk-A5FPKXEK.js";import"../../chunks/chunk-NBTFAXL4.js";import"../../chunks/chunk-TJUZVODP.js";import"../../chunks/chunk-GD7AV7BO.js";import{getRenamedOption}from"../../chunks/chunk-FSZJSIOF.js";import"../../chunks/chunk-Y2FVJ7YO.js";import{buildCommand}from"../../chunks/chunk-PY4WWD6Z.js";import"../../chunks/chunk-BPIGFKNN.js";import{toEnumerableError}from"../../chunks/chunk-CY5KJ42N.js";import{help}from"../../chunks/chunk-7KCRYDGK.js";import{remoteText}from"../../chunks/chunk-GLIQ4KNY.js";import"../../chunks/chunk-3G3FQYMW.js";import{detectExplicitScope}from"../../chunks/chunk-YJP25FL6.js";import{TelemetryClient}from"../../chunks/chunk-KDCODXVL.js";import"../../chunks/chunk-NWGBDBZI.js";import{AGENT_REASON,AGENT_STATUS,buildCommandWithGlobalFlags,writeAgentError}from"../../chunks/chunk-PNWRO3XW.js";import"../../chunks/chunk-DTUEHPME.js";import{DEFAULT_VERCEL_CONFIG_FILENAME,VERCEL_DIR,getLinkedProject,getProjectLink,require_dist2 as require_dist5,require_lib,resolveProjectCwd}from"../../chunks/chunk-XL2PHD4X.js";import"../../chunks/chunk-M7FED5YP.js";import"../../chunks/chunk-4HR3I3ML.js";import"../../chunks/chunk-LOA7SZWH.js";import"../../chunks/chunk-LUX4PBJL.js";import{ua_default}from"../../chunks/chunk-MTZYPCZ7.js";import"../../chunks/chunk-OPORM35X.js";import"../../chunks/chunk-D6REP5QQ.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-MY4MONOH.js";import"../../chunks/chunk-7HLAWGY2.js";import"../../chunks/chunk-MXTC4ZAQ.js";import{isArgumentError,parseArguments}from"../../chunks/chunk-LYL26S3N.js";import"../../chunks/chunk-2VBFQZ72.js";import"../../chunks/chunk-6GKP6VUF.js";import"../../chunks/chunk-4NTBYNFR.js";import"../../chunks/chunk-4SAVH3H7.js";import{CantParseJSONFile}from"../../chunks/chunk-GOI2VVI7.js";import{getCommandName,getCommandNamePlain,require_lib as require_lib2}from"../../chunks/chunk-B4KA3ZH2.js";import{pkg_default}from"../../chunks/chunk-BOJDM3O7.js";import{cliErrorFromUnknown,defineDiagnostics,dist_exports,emoji,init_dist,output_manager_default,prependEmoji,recordCliError}from"../../chunks/chunk-AP6DZGTK.js";import"../../chunks/chunk-BLUPZPAS.js";import"../../chunks/chunk-AW33SRYY.js";import{require_build_utils}from"../../chunks/chunk-5MDNVAE6.js";import"../../chunks/chunk-OCR5CRTH.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-SCV7XEEO.js";import"../../chunks/chunk-MCYG7CCE.js";import"../../chunks/chunk-YHPPP3SF.js";import"../../chunks/chunk-24SIHFEW.js";import{getFlagsSpecification,quoteArg}from"../../chunks/chunk-CFJBDBYH.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-BULSRTQE.js";import{__commonJS,__require,__toCommonJS,__toESM}from"../../chunks/chunk-BZENIQ7N.js";var require_build_runner=__commonJS({"../cli-builder-integration/dist/build-runner.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),build_runner_exports={};__export(build_runner_exports,{BuildRunner:()=>BuildRunner3,InprocessBuildRunner:()=>InprocessBuildRunner2});module.exports=__toCommonJS2(build_runner_exports);var BuildRunner3=class{constructor(ctx){this.ctx=ctx}},InprocessBuildRunner2=class extends BuildRunner3{constructor(ctx,builder){super(ctx),this.builder=builder}async build(){return await this.builder.build(this.ctx.buildOptions)}async diagnostics(){return await this.ctx.builderSpan.child("vc.builder.diagnostics").trace(async()=>await this.builder.diagnostics?.(this.ctx.buildOptions))}teardown(){}}}});var require_sort_builders=__commonJS({"../builder-orchestration/dist/sort-builders.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),sort_builders_exports={};__export(sort_builders_exports,{sortBuilders:()=>sortBuilders});module.exports=__toCommonJS2(sort_builders_exports);var import_frameworks=require_frameworks();function sortBuilders(builds){let frameworkRuntimeSet=new Set(import_frameworks.frameworkList.map(f=>f.useRuntime?.use||"@vercel/static-build"));frameworkRuntimeSet.delete("@vercel/go"),frameworkRuntimeSet.delete("@vercel/python"),frameworkRuntimeSet.delete("@vercel/ruby"),frameworkRuntimeSet.delete("@vercel/rust");let toNumber=build2=>build2.use==="@vercel/go"||build2.use==="@vercel/python"||build2.use==="@vercel/ruby"||build2.use==="@vercel/rust"?1:frameworkRuntimeSet.has(build2.use)?0:2;return builds.sort((build1,build2)=>toNumber(build1)-toNumber(build2))}}});var require_execute_builder=__commonJS({"../cli-builder-integration/dist/execute-builder.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),execute_builder_exports={};__export(execute_builder_exports,{executeBuilder:()=>executeBuilder2,sortBuildsForExecution:()=>sortBuildsForExecution2});module.exports=__toCommonJS2(execute_builder_exports);var import_sort_builders=require_sort_builders(),import_build_runner2=require_build_runner();async function executeBuilder2({builder,buildOptions,span,isFrontendBuilder,hasDetectedServices,framework,runner}){let buildRunner=runner??new import_build_runner2.InprocessBuildRunner({requirePath:"",buildOptions,cwd:buildOptions.workPath,expectsPreDeploy:!1,builderSpan:span},builder),rawBuildResult=await span.trace(()=>buildRunner.build()),buildResult=builder.version===-1&&"resultVersion"in rawBuildResult?rawBuildResult.result:rawBuildResult;return!hasDetectedServices&&buildOptions.config.zeroConfig&&isFrontendBuilder&&"output"in buildResult&&!buildResult.routes&&framework&&(buildResult.routes=await getFrameworkRoutes(framework,buildOptions.workPath)),{buildResult,rawBuildResult}}var sortBuildsForExecution2=import_sort_builders.sortBuilders;async function getFrameworkRoutes(framework,dirPrefix){return typeof framework.defaultRoutes=="function"?framework.defaultRoutes(dirPrefix):Array.isArray(framework.defaultRoutes)?framework.defaultRoutes:[]}}});var require_is_outside=__commonJS({"../cli-builder-integration/dist/is-outside.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),is_outside_exports={};__export(is_outside_exports,{isOutside:()=>isOutside});module.exports=__toCommonJS2(is_outside_exports);var import_path2=__require("path");function isOutside(directory,path){let relativePath=(0,import_path2.relative)(directory,path);return(0,import_path2.isAbsolute)(relativePath)||relativePath===".."||relativePath.startsWith(`..${import_path2.sep}`)}}});var require_schedule_services=__commonJS({"../cli-builder-integration/dist/schedule-services.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),schedule_services_exports={};__export(schedule_services_exports,{planScheduleServices:()=>planScheduleServices,rejectScheduleServiceNameConflicts:()=>rejectScheduleServiceNameConflicts});module.exports=__toCommonJS2(schedule_services_exports);var import_node_fs2=__require("node:fs"),import_promises=__require("node:fs/promises"),import_node_path2=__require("node:path"),import_build_utils3=__require("@vercel/build-utils"),import_fs_detectors=require_dist3(),import_entrypoint=require_entrypoint(),import_is_outside=require_is_outside(),EXPERIMENTS={python:{runtime:"Python",env:"VERCEL_EXPERIMENTAL_PYTHON_SCHEDULES",code:"PYTHON_SCHEDULES_NOT_ENABLED"},node:{runtime:"Node.js",env:"VERCEL_EXPERIMENTAL_NODE_SCHEDULES",code:"NODE_SCHEDULES_NOT_ENABLED"}},FUNCTIONS_HINTS={command:"Dockerfile, but schedules run as services and don't use top-level `functions`. Remove it. Per-schedule settings such as `maxDuration` and `regions` aren't available yet.",python:"module, but schedules run as services and don't use top-level `functions`. Remove it, and set `max_duration` and `regions` on `@schedule` instead.",node:"entrypoint, but schedules run as services and don't use top-level `functions`. Remove it, and set `maxDuration` and `regions` in its `export const config` instead."};async function planScheduleServices({schedules,workPath,repoRootPath=workPath,files,functions={}}){let services=[],targets=new Map,sourceFiles=[],fs2=new import_fs_detectors.LocalFileSystemDetector(workPath),projectRoot=await(0,import_promises.realpath)(workPath),repoRoot=await(0,import_promises.realpath)(repoRootPath);for(let schedule of schedules){if(!(0,import_build_utils3.isServiceSchedule)(schedule))continue;let{name,root,entrypoint}=schedule,kind="run"in schedule?"command":schedule.runtime,invalid=message=>new import_build_utils3.NowBuildError({code:"INVALID_SCHEDULE_SERVICE",message:`Can't build schedule "${name}": ${message}`}),experiment=kind==="command"?void 0:EXPERIMENTS[kind];if(experiment&&process.env[experiment.env]!=="1")throw new import_build_utils3.NowBuildError({code:experiment.code,message:`Can't build schedule "${name}": ${experiment.runtime} schedules are experimental. Set the environment variable ${experiment.env}=1 to build them.`});if((0,import_node_path2.isAbsolute)(root))throw invalid(`\`root\` "${root}" must be a relative path.`);let config={root,runtime:"container",entrypoint,functions:{}},{service,error}=kind==="command"?await(0,import_fs_detectors.resolveConfiguredServiceV2)(name,config,fs2):kind==="node"?resolveNodeScheduleService(schedule):resolvePythonScheduleService(schedule,workPath,files);if(!service)throw invalid(error.message);let source=service.builder.src,aboveProject=service.root===".."||service.root.startsWith("../"),notInProject=invalid(`"${source}" isn't in the project files. Check \`root\` and \`entrypoint\`, and that .vercelignore doesn't exclude it.`);if(!aboveProject&&!files.includes(source))throw notInProject;let[realRoot,realSource]=await Promise.all([(0,import_promises.realpath)((0,import_node_path2.join)(workPath,service.root)),(0,import_promises.realpath)((0,import_node_path2.join)(workPath,source))]).catch(()=>{throw notInProject}),boundary=aboveProject?repoRoot:projectRoot;if((0,import_is_outside.isOutside)(boundary,realRoot))throw invalid(aboveProject?`\`root\` "${root}" is outside the repository.`:`\`root\` "${root}" is a symlink to a directory outside the project.`);if((0,import_is_outside.isOutside)(boundary,realSource))throw invalid(aboveProject?`"${source}" is outside the repository.`:`"${source}" is a symlink to a file outside the project.`);if(Object.prototype.hasOwnProperty.call(functions,source))throw invalid(`\`functions["${source}"]\` names its ${FUNCTIONS_HINTS[kind]}`);if(services.push(service),"run"in schedule){let{run,root:_root,entrypoint:_entrypoint,...rest}=schedule;service.builder.config={...service.builder.config,schedulesCommand:{command:run}},targets.set(name,{...rest,service:name,function:name})}sourceFiles.push(source)}return{services,targets,sourceFiles}}function rejectScheduleServiceNameConflicts({services},serviceNames){let names=new Set(serviceNames),conflict=services.find(({name})=>names.has(name));if(conflict)throw new import_build_utils3.NowBuildError({code:"SCHEDULE_SERVICE_NAME_CONFLICT",message:`Schedule "${conflict.name}" runs as a service of the same name, but the build also has a service named "${conflict.name}". Rename the schedule.`})}function resolvePythonScheduleService({name,root,entrypoint},workPath,files){let parsed=(0,import_entrypoint.parsePythonScheduleModule)(entrypoint);if(!parsed)return{error:{message:`"${entrypoint}" isn't a Python module path.`}};let serviceRoot=(0,import_entrypoint.stripTrailingSlash)(import_node_path2.posix.normalize(root)),candidates=parsed.sourceFiles.map(file=>serviceRoot==="."?file:import_node_path2.posix.join(serviceRoot,file)),source=candidates.find(candidate=>serviceRoot===".."||serviceRoot.startsWith("../")?(0,import_node_fs2.existsSync)((0,import_node_path2.join)(workPath,candidate)):files.includes(candidate));return source?{service:createScheduleService({name,root:serviceRoot,runtime:"python",entrypoint:import_node_path2.posix.relative(serviceRoot,source),use:"@vercel/python",config:{schedulesModule:{module:parsed.moduleName}}})}:{error:{message:`module "${entrypoint}" isn't in the project files. Expected ${candidates.map(candidate=>`"${candidate}"`).join(" or ")}. Check \`root\` and \`entrypoint\`, and that .vercelignore doesn't exclude it.`}}}function resolveNodeScheduleService({name,root,entrypoint}){let file=import_node_path2.posix.normalize(entrypoint);return import_node_path2.posix.isAbsolute(file)||file===".."||file.startsWith("../")?{error:{message:`\`entrypoint\` "${entrypoint}" must be a file inside \`root\` "${root}".`}}:{service:createScheduleService({name,root:(0,import_entrypoint.stripTrailingSlash)(import_node_path2.posix.normalize(root)),runtime:"node",entrypoint:file,use:"@vercel/backends",config:{schedulesEntrypoint:!0}})}}function createScheduleService({name,root,runtime,entrypoint,use,config}){return{schema:"experimentalServicesV2",name,root,runtime,entrypoint,builder:{src:root==="."?entrypoint:import_node_path2.posix.join(root,entrypoint),use,config:{zeroConfig:!0,...root!=="."&&{workspace:root},...config}},functions:{}}}}});var require_get_daemon_builders=__commonJS({"../cli-builder-integration/dist/get-daemon-builders.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),get_daemon_builders_exports={};__export(get_daemon_builders_exports,{getDaemonBuilders:()=>getDaemonBuilders,splitDaemonEntrypoints:()=>splitDaemonEntrypoints,validateDaemonImageRepositories:()=>validateDaemonImageRepositories});module.exports=__toCommonJS2(get_daemon_builders_exports);var import_promises=__require("fs/promises"),import_path2=__require("path"),import_build_utils3=__require("@vercel/build-utils"),import_is_outside=require_is_outside();function splitDaemonEntrypoints(daemons){if(daemons!==void 0)return Object.fromEntries(Object.entries(daemons).map(([name,daemon])=>{let{path,buildTarget}=(0,import_build_utils3.splitDockerfileEntrypoint)(daemon.entrypoint);return[name,buildTarget===void 0?daemon:{...daemon,entrypoint:path,buildTarget}]}))}function validateDaemonImageRepositories(daemons){let owners=new Map;for(let name of Object.keys(daemons??{})){let repository=(0,import_build_utils3.getDaemonImageRepository)(name),owner=owners.get(repository);if(owner!==void 0)throw new import_build_utils3.NowBuildError({code:"INVALID_DAEMONS",message:`Can't build daemon "${name}": daemon "${owner}" uses the same image repository "${repository}". Rename one of them.`});owners.set(repository,name)}}async function getDaemonBuilders({workPath,repoRootPath=workPath,daemons,files}){if(daemons===void 0)return[];let root=await(0,import_promises.realpath)(workPath),repoRoot=await(0,import_promises.realpath)(repoRootPath);return Promise.all(Object.entries(daemons).map(async([name,daemon])=>{let source=(0,import_build_utils3.normalizePath)((0,import_path2.join)(daemon.root,daemon.entrypoint)),aboveProject=source.startsWith("../"),invalidSource=reason=>new import_build_utils3.NowBuildError({code:"INVALID_DAEMON_ROOT",message:`Can't build daemon "${name}": "${source}" ${reason}`}),notInProject=invalidSource("isn't in the project files. Check `root` and `entrypoint`, and that .vercelignore doesn't exclude it.");if((0,import_path2.isAbsolute)(daemon.root)||!aboveProject&&!files.includes(source))throw notInProject;let dockerfile=await(0,import_promises.realpath)((0,import_path2.join)(workPath,source)).catch(()=>{throw notInProject});if((0,import_is_outside.isOutside)(aboveProject?repoRoot:root,dockerfile))throw invalidSource(aboveProject?"is outside the repository.":"is a symlink to a file outside the project.");let invalidRoot=reason=>new import_build_utils3.NowBuildError({code:"INVALID_DAEMON_ROOT",message:`Can't build daemon "${name}": \`root\` "${daemon.root}" ${reason}`}),context=await(0,import_promises.realpath)((0,import_path2.join)(workPath,daemon.root)).catch(()=>{});if(!context||!(await(0,import_promises.stat)(context)).isDirectory())throw invalidRoot("isn't a directory.");if((0,import_is_outside.isOutside)(repoRoot,context))throw invalidRoot("is outside the repository.");return{src:source,use:"@vercel/container",config:{daemon:{name,...daemon}}}}))}}});var require_diagnostics=__commonJS({"../cli-builder-integration/dist/diagnostics.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),diagnostics_exports={};__export(diagnostics_exports,{buildDiagnostics:()=>buildDiagnostics});module.exports=__toCommonJS2(diagnostics_exports);var import_nostics2=(init_dist(),__toCommonJS(dist_exports)),buildDiagnostics=(0,import_nostics2.defineDiagnostics)({codes:{BUILD_BUILDER_LOAD_FAILED:{why:p=>`Failed to load Builder "${p.use}"`,fix:"Check that the builder is installed and spelled correctly in your Vercel configuration."},BUILD_CONCURRENT_INPROCESS:{why:p=>`Internal error: build for "${p.entrypoint}" was scheduled concurrently but cannot run in a subprocess`,fix:"This is a Vercel CLI error. Report it at https://vercel.com/help."},BUILD_WORKER_MULTIPLE_TOPICS:{why:p=>`Worker service "${p.name}" has ${p.topics} topics, but multiple topics are only supported for Python workers.`,fix:"Configure one topic per worker service, or use a Python worker for multiple topics."}}})}});var require_build_concurrency=__commonJS({"../cli-builder-integration/dist/build-concurrency.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),build_concurrency_exports={};__export(build_concurrency_exports,{getInstallScopeKey:()=>getInstallScopeKey,groupIntoScopeChains:()=>groupIntoScopeChains,resolveInstallScopeRoot:()=>resolveInstallScopeRoot,runBuildsWithConcurrency:()=>runBuildsWithConcurrency,runWithConcurrency:()=>runWithConcurrency});module.exports=__toCommonJS2(build_concurrency_exports);var import_node_fs2=__require("node:fs"),import_node_path2=__require("node:path"),import_build_utils3=__require("@vercel/build-utils");async function runWithConcurrency(items,limit,fn,onSecondaryError){let queue=[...items],max=Math.max(limit,1),active=0,failed=!1,firstError;if(await new Promise(finish=>{let enqueue=item=>{queue.push(item),pump()},pump=()=>{for(;active<max&&queue.length>0&&!failed;){let item=queue.shift();active++,fn(item,enqueue).then(()=>{active--,pump()},err=>{active--,failed?onSecondaryError?.(err,item):(failed=!0,firstError=err),pump()})}active===0&&finish()};pump()}),failed)throw firstError}function getInstallScopeKey({toolchain,installDirectory,installCommand}){return JSON.stringify([toolchain,(0,import_node_path2.normalize)(installDirectory),typeof installCommand=="string"?["cmd",installCommand.trim()]:"default"])}var NODE_LOCKFILES=["pnpm-lock.yaml","yarn.lock","package-lock.json","npm-shrinkwrap.json","bun.lock","bun.lockb","vlt-lock.json"];async function isUvWorkspaceRoot(pyprojectPath){if(!await fileExists(pyprojectPath))return!1;let pyproject=await(0,import_build_utils3.readConfigFile)(pyprojectPath,{silent:!0});return pyproject===null||pyproject.tool?.uv?.workspace!==void 0}async function isVltWorkspaceRoot(vltJsonPath){if(!await fileExists(vltJsonPath))return!1;try{let vltJson=JSON.parse(await import_node_fs2.promises.readFile(vltJsonPath,"utf8"));return!vltJson||typeof vltJson!="object"||"workspaces"in vltJson}catch{return!0}}async function fileExists(path){try{return await import_node_fs2.promises.stat(path),!0}catch{return!1}}var SERVICE_DIR_TOOLCHAINS=new Set(["go","ruby","rust","container"]);async function resolveInstallScopeRoot({toolchain,serviceDir,ceilingDir}){if(toolchain!=="node"&&toolchain!=="python")return SERVICE_DIR_TOOLCHAINS.has(toolchain)?(0,import_node_path2.normalize)(serviceDir):(0,import_node_path2.normalize)(ceilingDir);let ceiling=(0,import_node_path2.normalize)(ceilingDir),dir=(0,import_node_path2.normalize)(serviceDir);if(dir!==ceiling&&!dir.startsWith(ceiling+import_node_path2.sep))return dir;let nearestLockfileDir,nearestPackageJsonDir,done=!1;for(;!done;){if(toolchain==="node"){if(nearestLockfileDir===void 0){for(let lockfile of NODE_LOCKFILES)if(await fileExists((0,import_node_path2.join)(dir,lockfile))){nearestLockfileDir=dir;break}}if(await fileExists((0,import_node_path2.join)(dir,"pnpm-workspace.yaml"))||await isVltWorkspaceRoot((0,import_node_path2.join)(dir,"vlt.json")))return dir;try{let pkg=JSON.parse(await import_node_fs2.promises.readFile((0,import_node_path2.join)(dir,"package.json"),"utf8"));if(pkg&&typeof pkg=="object"){if("workspaces"in pkg)return dir;nearestPackageJsonDir??=dir}}catch{}}else if(await isUvWorkspaceRoot((0,import_node_path2.join)(dir,"pyproject.toml")))return dir;let parent=(0,import_node_path2.dirname)(dir);done=dir===ceiling||parent===dir,dir=parent}return nearestLockfileDir??nearestPackageJsonDir??(0,import_node_path2.normalize)(serviceDir)}async function runBuildsWithConcurrency({builds,concurrency,isEligible,resolveScope,forceSingleChain,runBuild,log,reportSecondaryError}){if(concurrency<=1){for(let build2 of builds)await runBuild(build2,!1);return}let parallelBuilds=[],sequentialBuilds=[];for(let build2 of builds)(isEligible(build2)?parallelBuilds:sequentialBuilds).push(build2);if(parallelBuilds.length>0){let chains,siblingsOf,scopeCount;if(forceSingleChain)chains=[parallelBuilds],siblingsOf=new Map,scopeCount=1;else{let scopeByBuild=new Map;for(let build2 of parallelBuilds)scopeByBuild.set(build2,await resolveScope(build2));({chains,siblingsOf}=groupIntoScopeChains(parallelBuilds,build2=>scopeByBuild.get(build2))),scopeCount=new Set(Array.from(scopeByBuild.values(),scope=>scope.outerKey)).size}let atOnce=Math.min(concurrency,chains.reduce((sum,chain)=>sum+Math.max(1,siblingsOf.get(chain[0])?.length??0),0));log(`Running ${parallelBuilds.length} builds across ${scopeCount} install scope${scopeCount===1?"":"s"}, up to ${atOnce} at a time (concurrency ${concurrency})`);let abortedRun=!1,activeBuildOfChain=new Map;await runWithConcurrency(chains,concurrency,async(chain,enqueue)=>{for(let build2 of chain){if(abortedRun)return;activeBuildOfChain.set(chain,build2);try{await runBuild(build2,!0)}catch(err){throw abortedRun=!0,err}let siblings=siblingsOf.get(build2);if(siblings)for(let sibling of siblings)enqueue([sibling])}},(err,chain)=>{let build2=activeBuildOfChain.get(chain);build2!==void 0&&reportSecondaryError(err,build2)})}for(let build2 of sequentialBuilds)await runBuild(build2,!1)}function groupIntoScopeChains(items,scopeOf){let groupByOuter=new Map,scopes=new Map;for(let item of items){let scope=scopeOf(item);scopes.set(item,scope);let group=groupByOuter.get(scope.outerKey)??[];group.push(item),groupByOuter.set(scope.outerKey,group)}let chains=[],siblingsOf=new Map;for(let group of groupByOuter.values()){if(group.every(item=>scopes.get(item).preinstalled)){for(let item of group)chains.push([item]);continue}let[leader,...rest]=group,leaderScope=scopes.get(leader);rest.every(item=>{let scope=scopes.get(item);return scope.innerKey===leaderScope.innerKey&&scope.siblingsSkipInstall})&&rest.length>0?(chains.push([leader]),siblingsOf.set(leader,rest)):chains.push(group)}return{chains,siblingsOf}}}});var require_workspace_install_targets=__commonJS({"../cli-builder-integration/dist/workspace-install-targets.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),workspace_install_targets_exports={};__export(workspace_install_targets_exports,{collectWorkspaceInstallTargets:()=>collectWorkspaceInstallTargets});module.exports=__toCommonJS2(workspace_install_targets_exports);var import_path2=__require("path"),import_build_utils3=__require("@vercel/build-utils"),import_fs_detectors=require_dist3();function isWorkspaceInstallTarget(target){return!!(target&&typeof target=="object"&&typeof target.installRoot=="string"&&typeof target.packageJsonPath=="string"&&typeof target.relativePath=="string")}async function collectWorkspaceInstallTargets({builds,existingTargets,repoRootPath,serviceByBuilder,workPath}){let targets=new Map(Array.isArray(existingTargets)?existingTargets.filter(isWorkspaceInstallTarget).map(target=>[target.packageJsonPath,target]):[]),targetPaths=[];for(let build2 of builds){let service=serviceByBuilder.get(build2);if(build2.use.startsWith("@vercel/node")||build2.use.startsWith("@vercel/backends")||service?.runtime==="node")if(service){let serviceRoot=(0,import_build_utils3.isExperimentalService)(service)?service.workspace:service.root;targetPaths.push(serviceRoot&&serviceRoot!=="."?(0,import_path2.join)(workPath,serviceRoot):workPath)}else typeof build2.src=="string"&&targetPaths.push((0,import_path2.join)(workPath,(0,import_path2.dirname)(build2.src)))}let installScopes=new Map;return await Promise.all(targetPaths.map(async targetPath=>{let{cliType,lockfilePath}=await(0,import_build_utils3.scanParentDirs)(targetPath,!1,repoRootPath);if(!lockfilePath||cliType!=="npm"&&cliType!=="pnpm"&&cliType!=="yarn"&&cliType!=="bun")return;let installRoot=(0,import_path2.dirname)(lockfilePath),scope=installScopes.get(installRoot)??{paths:[],type:cliType};scope.paths.push((0,import_path2.relative)(installRoot,targetPath)),installScopes.set(installRoot,scope)})),await Promise.all(Array.from(installScopes,async([installRoot,{paths,type}])=>{let resolved=await(0,import_fs_detectors.resolveWorkspacePackageTargets)({fs:new import_fs_detectors.LocalFileSystemDetector(installRoot),targetPaths:paths,type});if(!resolved){for(let[packageJsonPath,target]of targets)target.installRoot===installRoot&&targets.delete(packageJsonPath);return}for(let target of resolved){let packageJsonPath=(0,import_path2.join)(installRoot,target.packageJsonPath);targets.set(packageJsonPath,{...target,installRoot,packageJsonPath})}})),Array.from(targets.values())}}});var require_shared_workspace_install=__commonJS({"../cli-builder-integration/dist/shared-workspace-install.js"(exports,module){"use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM2=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),shared_workspace_install_exports={};__export(shared_workspace_install_exports,{planSharedWorkspaceInstalls:()=>planSharedWorkspaceInstalls,runSharedWorkspaceInstall:()=>runSharedWorkspaceInstall});module.exports=__toCommonJS2(shared_workspace_install_exports);var import_node_fs2=__require("node:fs"),import_node_path2=__require("node:path"),import_node_stream=__require("node:stream"),import_semver=__toESM2(require_semver()),import_build_utils3=__require("@vercel/build-utils"),import_fs_detectors=require_dist3(),import_build_concurrency=require_build_concurrency(),SHARED_INSTALL_BUILDERS=["@vercel/next","@vercel/backends","@vercel/node","@vercel/static-build"],PRE_INSTALL_PATCHED_FRAMEWORKS=new Set(["nuxtjs","gatsby"]),LAST_LEGACY_NEXT_VERSION="7.0.2";function hasWorkspacesField(rootPackageJson){return!!(rootPackageJson&&typeof rootPackageJson=="object"&&rootPackageJson.workspaces)}var INSTALLS_EVERY_WORKSPACE={async definesWorkspace(_installRoot,rootPackageJson){return hasWorkspacesField(rootPackageJson)},async installsWholeWorkspace(){return!0}},WORKSPACE_STRATEGIES={pnpm:{async definesWorkspace(installRoot){return await readFileOrNull((0,import_node_path2.join)(installRoot,"pnpm-workspace.yaml"))!==null},async installsWholeWorkspace(installRoot,env){let stdout=await captureStdout("pnpm",["config","get","recursive-install"],installRoot,env);return stdout!==null&&["","undefined","true"].includes(stdout)}},npm:{async definesWorkspace(_installRoot,rootPackageJson){return hasWorkspacesField(rootPackageJson)},async installsWholeWorkspace(installRoot,env){let stdout=await captureStdout("npm",["config","list","--json"],installRoot,env);if(stdout===null)return!1;try{let{workspace}=JSON.parse(stdout);return workspace==null||Array.isArray(workspace)&&workspace.length===0}catch{return!1}}},yarn:{...INSTALLS_EVERY_WORKSPACE,async installsWholeWorkspace(installRoot,env){return!await isYarnClassic(installRoot)||!await mentionsYarnFocus(installRoot,env)},async runsServiceScripts({rootPackageJsonPath,servicePackageJsonPaths}){if(!await isYarnClassic((0,import_node_path2.dirname)(rootPackageJsonPath)))return!0;if(!servicePackageJsonPaths.has(rootPackageJsonPath)&&await runsInstallCwdScripts(rootPackageJsonPath))return!1;for(let path of servicePackageJsonPaths)if(path!==rootPackageJsonPath&&await runsInstallCwdScripts(path))return!1;return!0}},bun:INSTALLS_EVERY_WORKSPACE},YARN_FOCUS_SETTING=/^[^#]*--(?:install\.)?focus\b/m;function getYarnRcPaths(cwd,env){let paths=[];for(let dir=cwd;paths.unshift((0,import_node_path2.join)(dir,".yarnrc"),(0,import_node_path2.join)(dir,".yarnrc.yml")),(0,import_node_path2.dirname)(dir)!==dir;dir=(0,import_node_path2.dirname)(dir));process.platform!=="win32"&&paths.push("/etc/yarn/config","/etc/yarnrc");let home=process.platform==="win32"?env.USERPROFILE:env.HOME;return home&&paths.push((0,import_node_path2.join)(home,".config","yarn","config"),(0,import_node_path2.join)(home,".yarn","config"),(0,import_node_path2.join)(home,".yarnrc"),(0,import_node_path2.join)(home,".yarnrc.yml")),env.YARN_CONFIG&&paths.push(env.YARN_CONFIG),paths}async function mentionsYarnFocus(installRoot,env){for(let path of getYarnRcPaths(installRoot,env)){let rc=await readFileOrNull(path);if(rc!==null&&YARN_FOCUS_SETTING.test(rc))return!0}return!1}async function isYarnClassic(installRoot){if((await readFileOrNull((0,import_node_path2.join)(installRoot,"yarn.lock")))?.includes("__metadata:"))return!1;let raw=await readFileOrNull((0,import_node_path2.join)(installRoot,"package.json"));try{let packageManager=JSON.parse(raw??"{}")?.packageManager,major=/^yarn@(\d+)/.exec(String(packageManager??""))?.[1];return major===void 0||Number(major)<2}catch{return!0}}var INSTALL_CWD_SCRIPTS=["prepare","prepublish","preinstall","install","postinstall"];async function runsInstallCwdScripts(packageJsonPath){return await hasScripts(packageJsonPath,INSTALL_CWD_SCRIPTS)||await readFileOrNull((0,import_node_path2.join)((0,import_node_path2.dirname)(packageJsonPath),"binding.gyp"))!==null}async function hasScripts(packageJsonPath,names){let raw=await readFileOrNull(packageJsonPath);if(raw===null)return!0;try{let scripts=JSON.parse(raw)?.scripts;return names.some(name=>typeof scripts?.[name]=="string")}catch{return!0}}function isWorkspaceType(cliType){return cliType in WORKSPACE_STRATEGIES}async function readFileOrNull(path){try{return await import_node_fs2.promises.readFile(path,"utf8")}catch{return null}}async function captureStdout(command,args,cwd,env){let stdout="";try{await(0,import_build_utils3.spawnAsync)(command,args,{cwd,env,timeout:6e4,outputStream:new import_node_stream.Writable({write(chunk,_encoding,callback){stdout+=chunk.toString(),callback()}}),errorStream:new import_node_stream.Writable({write(_chunk,_encoding,callback){callback()}})})}catch{return null}return stdout.trim()}function isBuilder(builderUse,name){return builderUse===name||builderUse.startsWith(`${name}@`)}function canShareInstall(candidate){return candidate.defaultInstall?isBuilder(candidate.builderUse,"@vercel/static-build")?typeof candidate.framework=="string"&&!PRE_INSTALL_PATCHED_FRAMEWORKS.has(candidate.framework):SHARED_INSTALL_BUILDERS.some(name=>isBuilder(candidate.builderUse,name)):!1}async function usesLegacyNext(installDir){let raw=await readFileOrNull((0,import_node_path2.join)(installDir,"package.json"));if(raw===null)return!1;let range;try{let pkg=JSON.parse(raw);range=pkg?.dependencies?.next??pkg?.devDependencies?.next}catch{return!1}return typeof range=="string"&&import_semver.default.validRange(range)!==null&&import_semver.default.intersects(range,`<=${LAST_LEGACY_NEXT_VERSION}`)}async function planSharedWorkspaceInstalls({candidates,repoRootPath,config,meta,projectCreatedAt,workspaceInstallTargets=[],onSkip}){let groups=new Map;for(let candidate of candidates){let installRoot=await(0,import_build_concurrency.resolveInstallScopeRoot)({toolchain:"node",serviceDir:candidate.serviceDir,ceilingDir:repoRootPath}),group=groups.get(installRoot)??[];group.push(candidate),groups.set(installRoot,group)}let installs=[];for(let[installRoot,group]of groups){let install=await planGroup({installRoot,group,repoRootPath,config,meta,projectCreatedAt,targetPaths:new Set(workspaceInstallTargets.filter(target=>target.installRoot&&(0,import_node_path2.normalize)(target.installRoot)===installRoot).map(target=>(0,import_node_path2.normalize)(target.packageJsonPath)))});typeof install=="string"?onSkip?.(installRoot,install):install&&installs.push(install)}return installs}function describeService(candidate,repoRootPath){return`"${(0,import_node_path2.relative)(repoRootPath,candidate.serviceDir)||"."}"`}function getUnsharedInstallReason(candidate,repoRootPath){if(canShareInstall(candidate))return;let service=describeService(candidate,repoRootPath);return candidate.defaultInstall?isBuilder(candidate.builderUse,"@vercel/static-build")?typeof candidate.framework=="string"?`${service} uses ${candidate.framework}, whose build changes package.json before installing`:`${service} has no detected framework`:`${service} is built by ${candidate.builderUse}, which runs its own install`:`${service} has its own install command`}async function planGroup({installRoot,group,repoRootPath,config,meta,projectCreatedAt,targetPaths}){let[first]=group;if(!first||group.length<2)return;for(let candidate of group){let reason=getUnsharedInstallReason(candidate,repoRootPath);if(reason)return reason}if(new Set(group.map(c=>(0,import_node_path2.normalize)(c.serviceDir))).size!==group.length)return"several services build from the same directory";let rootPackageJsonPath=(0,import_node_path2.join)(installRoot,"package.json"),rawRootPackageJson=await readFileOrNull(rootPackageJsonPath),rootPackageJson;try{rootPackageJson=rawRootPackageJson===null?null:JSON.parse(rawRootPackageJson)}catch{rootPackageJson=null}if(rootPackageJson===null)return"the workspace root has no readable package.json";let packageJsonPaths=new Set([rootPackageJsonPath]),servicePackageJsonPaths=new Set,workspaceType;for(let candidate of group){let service=describeService(candidate,repoRootPath);if(isBuilder(candidate.builderUse,"@vercel/next")&&await usesLegacyNext(candidate.installDir))return`${service} uses a legacy Next.js version`;let{cliType,lockfilePath,packageJsonPath}=await(0,import_build_utils3.scanParentDirs)(candidate.installDir,!1,repoRootPath);if(!isWorkspaceType(cliType))return`${service} installs with ${cliType}, which doesn't support a shared install`;if(workspaceType!==void 0&&cliType!==workspaceType)return"the services install with different package managers";if(!lockfilePath||(0,import_node_path2.normalize)((0,import_node_path2.dirname)(lockfilePath))!==installRoot||!packageJsonPath)return`${service} doesn't install from the workspace root's lockfile`;workspaceType=cliType,packageJsonPaths.add((0,import_node_path2.normalize)(packageJsonPath)),servicePackageJsonPaths.add((0,import_node_path2.normalize)(packageJsonPath))}if(!workspaceType)return;let strategy=WORKSPACE_STRATEGIES[workspaceType];if(!await strategy.definesWorkspace(installRoot,rootPackageJson))return`the workspace root doesn't define a ${workspaceType} workspace`;if(strategy.runsServiceScripts&&!await strategy.runsServiceScripts({rootPackageJsonPath,servicePackageJsonPaths}))return`a ${workspaceType} install at the workspace root would run different lifecycle scripts than each service's own install`;let memberDirs=Array.from(packageJsonPaths).filter(path=>path!==rootPackageJsonPath).map(path=>(0,import_node_path2.relative)(installRoot,(0,import_node_path2.dirname)(path)));if(memberDirs.length>0){let members=await(0,import_fs_detectors.resolveWorkspacePackageTargets)({fs:new import_fs_detectors.LocalFileSystemDetector(installRoot),targetPaths:memberDirs,type:workspaceType});if(!members)return"a service is not a member of the workspace";if(workspaceType==="bun"&&members.some(member=>!member.isRoot&&!member.name))return"a service's package has no name"}if(targetPaths.size>0){for(let path of packageJsonPaths)if(!targetPaths.has(path))return"the workspace-scoped install would not cover every service";for(let path of targetPaths)packageJsonPaths.add(path)}for(let candidate of group){let configPath=await findMemberPackageManagerConfig(candidate.installDir,installRoot);if(configPath)return`${describeService(candidate,repoRootPath)} has its own package-manager config (${(0,import_node_path2.relative)(repoRootPath,configPath)})`}let nodeVersion;for(let candidate of group){let candidateVersion=await(0,import_build_utils3.getNodeVersion)(getNodeVersionDir(candidate),void 0,config,meta);if(nodeVersion&&candidateVersion.runtime!==nodeVersion.runtime)return`the services need different Node.js versions (${nodeVersion.range} and ${candidateVersion.range})`;nodeVersion=candidateVersion}let env=await getInstallEnv({installRoot,nodeVersion,projectCreatedAt});return await strategy.installsWholeWorkspace(installRoot,env)?{installRoot,builds:group.map(c=>c.build),env,packageJsonPaths:Array.from(packageJsonPaths)}:`couldn't confirm that a ${workspaceType} install at the workspace root installs every service`}function getNodeVersionDir(candidate){return isBuilder(candidate.builderUse,"@vercel/backends")?candidate.serviceDir:candidate.installDir}var PACKAGE_MANAGER_CONFIG_FILES=[".npmrc",".yarnrc",".yarnrc.yml"];async function findMemberPackageManagerConfig(installDir,installRoot){let dir=(0,import_node_path2.normalize)(installDir);for(;dir.startsWith(installRoot+import_node_path2.sep);){for(let file of PACKAGE_MANAGER_CONFIG_FILES){let path=(0,import_node_path2.join)(dir,file);if(await readFileOrNull(path)!==null)return path}let parent=(0,import_node_path2.dirname)(dir);if(parent===dir)break;dir=parent}}async function getInstallEnv({installRoot,nodeVersion,projectCreatedAt}){let{cliType,lockfileVersion,packageJsonPackageManager,packageJsonDevEngines,turboSupportsCorepackHome}=await(0,import_build_utils3.scanParentDirs)(installRoot,!0);return(0,import_build_utils3.getEnvForPackageManager)({cliType,lockfileVersion,packageJsonPackageManager,packageJsonDevEngines,nodeVersion,env:process.env,turboSupportsCorepackHome,projectCreatedAt})}async function runSharedWorkspaceInstall({install,meta,projectCreatedAt,workspaceInstallTargets=[]}){await(0,import_build_utils3.runNpmInstall)(install.installRoot,[],{env:install.env},{runNpmInstallSet:new Set},projectCreatedAt,void 0,{targets:workspaceInstallTargets});let installed=meta.runNpmInstallSet instanceof Set?meta.runNpmInstallSet:new Set;for(let path of install.packageJsonPaths)installed.add(path);meta.runNpmInstallSet=installed}}});var require_uv_workspace_builds=__commonJS({"../cli-builder-integration/dist/uv-workspace-builds.js"(exports,module){"use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM2=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),uv_workspace_builds_exports={};__export(uv_workspace_builds_exports,{planUvWorkspaceBuilds:()=>planUvWorkspaceBuilds});module.exports=__toCommonJS2(uv_workspace_builds_exports);var import_node_fs2=__require("node:fs"),import_node_path2=__require("node:path"),import_minimatch=__toESM2(require_minimatch()),import_smol_toml=require_dist(),import_build_utils3=__require("@vercel/build-utils"),import_build_concurrency=require_build_concurrency(),INSTALL_SCRIPTS=["vercel-install","now-install","install"],BUILD_SCRIPTS=["vercel-build","now-build","build"],RUNS_UV=/\buv\b/i,PYTHON_MANIFESTS=["pyproject.toml","Pipfile.lock","Pipfile","requirements.frozen.txt","requirements-frozen.txt","requirements.txt","requirements.in",(0,import_node_path2.join)("requirements","prod.txt")];function readPyproject(path){return(0,import_build_utils3.readConfigFile)(path,{silent:!0})}function normalizeName(name){return name.toLowerCase().replace(/[-_.]+/g,"-")}function strings(value){return typeof value=="string"?[value]:Array.isArray(value)?value.flatMap(strings):value&&typeof value=="object"?Object.values(value).flatMap(strings):[]}function hasAnyKey(value,keys){return!value||typeof value!="object"?!1:Object.entries(value).some(([key,nested])=>keys.includes(key)||hasAnyKey(nested,keys))}async function buildsWithoutExtraRequirements(pyproject,serviceDir){let buildSystem=pyproject["build-system"];if((pyproject.tool?.uv?.package??buildSystem!==void 0)===!1)return!0;if(buildSystem?.["backend-path"]!==void 0)return!1;switch(buildSystem?.["build-backend"]){case"uv_build":case"flit_core.buildapi":return!0;case"hatchling.build":{let hatch=pyproject.tool?.hatch;return!hasAnyKey(hatch?.build,["dependencies","hooks"])&&!hasAnyKey(hatch?.metadata,["hooks"])&&!await exists((0,import_node_path2.join)(serviceDir,"hatch.toml"))&&!await exists((0,import_node_path2.join)(serviceDir,"hatch_build.py"))}default:return!1}}function hasDynamicDependencies(pyproject){if(!pyproject)return!0;let dynamic=pyproject.project?.dynamic;return Array.isArray(dynamic)&&dynamic.some(field=>field==="dependencies"||field==="optional-dependencies")}var LOCAL_DIRECT_REFERENCE=/@\s*(?:file:|\.{0,2}[\\/]|[A-Za-z]:[\\/])/;function usesLocalPackages(pyproject){let hasLocalSource=Object.values(pyproject.tool?.uv?.sources??{}).some(entry=>(Array.isArray(entry)?entry:[entry]).some(source=>!!source&&typeof source=="object"&&("workspace"in source||"path"in source||/^file:/i.test(String(source.url??""))))),uv=pyproject.tool?.uv,requirements=strings([pyproject.project?.dependencies,pyproject.project?.["optional-dependencies"],pyproject["dependency-groups"],pyproject["build-system"]?.requires,uv?.["dev-dependencies"],uv?.["override-dependencies"],uv?.["constraint-dependencies"],uv?.["build-constraint-dependencies"],uv?.["extra-build-dependencies"]]);return hasLocalSource||requirements.some(requirement=>LOCAL_DIRECT_REFERENCE.test(requirement))}async function lockSharesLocalPackages(root,serviceDirs){let lock;try{lock=(0,import_smol_toml.parse)(await import_node_fs2.promises.readFile((0,import_node_path2.join)(root,"uv.lock"),"utf8"))}catch{return!0}if(!Array.isArray(lock.package))return!0;let packages=lock.package.filter(pkg=>!!pkg&&typeof pkg=="object"&&typeof pkg.name=="string"),serviceNames=new Set,sharedLocalNames=new Set;for(let pkg of packages){let name=normalizeName(pkg.name);for(let kind of["directory","editable","path","virtual"]){let sourcePath=pkg.source?.[kind];typeof sourcePath=="string"&&(serviceDirs.has((0,import_node_path2.resolve)(root,sourcePath))?serviceNames.add(name):kind!=="virtual"&&sharedLocalNames.add(name))}}for(let pkg of packages){let self=normalizeName(pkg.name),dependencyNames=[pkg.dependencies,pkg["optional-dependencies"],pkg["dev-dependencies"]].flatMap(value=>(Array.isArray(value)?[value]:Object.values(value??{})).flatMap(list=>Array.isArray(list)?list.flatMap(dep=>dep&&typeof dep.name=="string"?[normalizeName(dep.name)]:[]):[]));for(let dependency of dependencyNames)if(sharedLocalNames.has(dependency)||serviceNames.has(dependency)&&dependency!==self)return!0}return!1}function stringList(value){return Array.isArray(value)?value.filter(item=>typeof item=="string"):[]}function isWorkspaceMember(workspace,root,dir){let path=(0,import_node_path2.relative)(root,dir).split(import_node_path2.sep).join("/"),matches=pattern=>(0,import_minimatch.default)(path,pattern.replace(/^\.\//,"").replace(/\/$/,""));return stringList(workspace.members).some(matches)&&!stringList(workspace.exclude).some(matches)}async function exists(path){try{return await import_node_fs2.promises.stat(path),!0}catch{return!1}}function isPythonBuilder(builderUse){return builderUse==="@vercel/python"||builderUse.startsWith("@vercel/python@")}async function installsOwnMember(candidate){if(!candidate.defaultInstall||!isPythonBuilder(candidate.builderUse))return!1;let serviceDir=(0,import_node_path2.normalize)(candidate.serviceDir),dir=(0,import_node_path2.normalize)(candidate.entrypointDir);if(dir!==serviceDir&&!dir.startsWith(serviceDir+import_node_path2.sep))return!1;for(;dir!==serviceDir;){for(let manifest of PYTHON_MANIFESTS)if(await exists((0,import_node_path2.join)(dir,manifest)))return!1;dir=(0,import_node_path2.dirname)(dir)}let pyprojectPath=(0,import_node_path2.join)(serviceDir,"pyproject.toml");if(!await exists(pyprojectPath))return!1;let pyproject=await readPyproject(pyprojectPath);if(!pyproject||typeof pyproject.project?.name!="string"||usesLocalPackages(pyproject)||!await buildsWithoutExtraRequirements(pyproject,serviceDir))return!1;let scripts=pyproject.tool?.vercel?.scripts??{};return INSTALL_SCRIPTS.some(name=>!!scripts[name])?!1:![candidate.buildCommand,...BUILD_SCRIPTS.map(name=>scripts[name])].some(command=>typeof command=="string"&&RUNS_UV.test(command))}async function planUvWorkspaceBuilds({candidates,repoRootPath}){let groups=new Map;for(let candidate of candidates){let root=await(0,import_build_concurrency.resolveInstallScopeRoot)({toolchain:"python",serviceDir:candidate.serviceDir,ceilingDir:repoRootPath}),group=groups.get(root)??[];group.push(candidate),groups.set(root,group)}let independent=new Set,lockedByFirst=new Set;for(let[root,group]of groups){if(group.length<2)continue;let serviceDirs=new Set(group.map(c=>(0,import_node_path2.normalize)(c.serviceDir)));if(serviceDirs.size!==group.length||serviceDirs.has(root))continue;let rootPyproject=await readPyproject((0,import_node_path2.join)(root,"pyproject.toml")),workspace=rootPyproject?.tool?.uv?.workspace;if(!(!rootPyproject||!workspace||usesLocalPackages(rootPyproject)||![...serviceDirs].every(dir=>isWorkspaceMember(workspace,root,dir))||!(await Promise.all(group.map(installsOwnMember))).every(Boolean)))if(await exists((0,import_node_path2.join)(root,"uv.lock"))){if(await lockSharesLocalPackages(root,serviceDirs))continue;for(let candidate of group)independent.add(candidate.build)}else{let pyprojects=await Promise.all([...serviceDirs].map(dir=>readPyproject((0,import_node_path2.join)(dir,"pyproject.toml"))));if([rootPyproject,...pyprojects].some(hasDynamicDependencies))continue;for(let candidate of group)lockedByFirst.add(candidate.build)}}return{independent,lockedByFirst}}}});var require_backend_rewrite_warning=__commonJS({"../cli-builder-integration/dist/backend-rewrite-warning.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),backend_rewrite_warning_exports={};__export(backend_rewrite_warning_exports,{BACKEND_REWRITE_BEHAVIOR_WARNING:()=>BACKEND_REWRITE_BEHAVIOR_WARNING,hasBackendRewriteBehaviorChange:()=>hasBackendRewriteBehaviorChange});module.exports=__toCommonJS2(backend_rewrite_warning_exports);var import_build_utils3=__require("@vercel/build-utils"),BACKEND_REWRITE_BEHAVIOR_WARNING="Internal rewrites in backend framework projects now route requests using the rewritten destination path. This behavior was previously unsupported and may change which application route handles a request. Review your rewrite configuration to ensure this behavior is expected.";function hasInternalPathRewrite(rewrites){return rewrites?.some(rewrite=>typeof rewrite.destination=="string"&&rewrite.destination.startsWith("/"))??!1}function isAffectedFramework(framework){return framework==="go"||framework==="container"||(0,import_build_utils3.isPythonFramework)(framework)||(0,import_build_utils3.isNodeBackendFramework)(framework)}function hasBackendRewriteBehaviorChange({projectRewrites,builders}){return hasInternalPathRewrite(projectRewrites)&&(builders??[]).some(builder=>isAffectedFramework(builder.config?.framework))}}});var require_service_route_ownership=__commonJS({"../cli-builder-integration/dist/service-route-ownership.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),service_route_ownership_exports={};__export(service_route_ownership_exports,{scopeRoutesToServiceOwnership:()=>scopeRoutesToServiceOwnership});module.exports=__toCommonJS2(service_route_ownership_exports);var import_routing_utils=require_dist2();function isWebServiceWithPrefix(service){return service.type==="web"&&typeof service.routePrefix=="string"}function getWebRoutePrefixes(services){let unique=new Set;for(let service of services)isWebServiceWithPrefix(service)&&unique.add((0,import_routing_utils.normalizeRoutePrefix)(service.routePrefix));return Array.from(unique)}function scopeRoutesToServiceOwnership({routes,owner,allServices}){if(!isWebServiceWithPrefix(owner))return routes;let allWebPrefixes=getWebRoutePrefixes(allServices),ownershipGuard=(0,import_routing_utils.getOwnershipGuard)(owner.routePrefix,allWebPrefixes);return ownershipGuard?routes.map(route=>"handle"in route||typeof route.src!="string"?route:{...route,src:(0,import_routing_utils.scopeRouteSourceToOwnership)(route.src,ownershipGuard)}):routes}}});var require_validate_cron_secret=__commonJS({"../cli-builder-integration/dist/validate-cron-secret.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),validate_cron_secret_exports={};__export(validate_cron_secret_exports,{validateCronSecret:()=>validateCronSecret});module.exports=__toCommonJS2(validate_cron_secret_exports);var import_build_utils3=__require("@vercel/build-utils");function validateCronSecret(cronSecret){if(!cronSecret)return null;if(cronSecret!==cronSecret.trim())return new import_build_utils3.NowBuildError({code:"INVALID_CRON_SECRET",message:"The `CRON_SECRET` environment variable contains leading or trailing whitespace, which is not allowed in HTTP header values.",link:"https://vercel.link/securing-cron-jobs",action:"Learn More"});let invalidChars=[];for(let i=0;i<cronSecret.length;i++){let code=cronSecret.charCodeAt(i);code===9||code>=32&&code<=126||invalidChars.push({char:cronSecret[i],index:i,code})}if(invalidChars.length>0){let descriptions=invalidChars.slice(0,3).map(({code,index})=>code<32?`control character (0x${code.toString(16).padStart(2,"0")}) at position ${index}`:code===127?`DEL character at position ${index}`:`non-ASCII character (0x${code.toString(16).padStart(2,"0")}) at position ${index}`),moreCount=invalidChars.length-3,moreText=moreCount>0?`, and ${moreCount} more`:"";return new import_build_utils3.NowBuildError({code:"INVALID_CRON_SECRET",message:`The \`CRON_SECRET\` environment variable contains characters that are not valid in HTTP headers: ${descriptions.join(", ")}${moreText}. Only visible ASCII characters (letters, digits, symbols), spaces, and tabs are allowed.`,link:"https://vercel.link/securing-cron-jobs",action:"Learn More"})}return null}}});var require_workload_root_static_app=__commonJS({"../cli-builder-integration/dist/workload-root-static-app.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),workload_root_static_app_exports={};__export(workload_root_static_app_exports,{omitStaticAppAtWorkloadRoot:()=>omitStaticAppAtWorkloadRoot});module.exports=__toCommonJS2(workload_root_static_app_exports);var import_promises=__require("node:fs/promises"),import_node_path2=__require("node:path"),import_build_utils3=__require("@vercel/build-utils"),import_fs_detectors=require_dist3(),realpathOrSelf=path=>(0,import_promises.realpath)(path).catch(()=>path);function isProjectRoot(outputDirectory){return import_node_path2.posix.normalize(`${outputDirectory}/`)==="./"}async function omitStaticAppAtWorkloadRoot({builds,serviceBuilds,workPath,workloads,outputDirectory,output}){let rootStaticBuilds=builds.filter(build2=>!serviceBuilds.has(build2)&&(0,import_fs_detectors.isOfficialRuntime)("static",build2.use)&&!build2.config?.outputDirectory);if(rootStaticBuilds.length===0||workloads.length===0||typeof outputDirectory=="string"&&isProjectRoot(outputDirectory))return builds;let[projectRoot,...roots]=await Promise.all([realpathOrSelf(workPath),...workloads.map(({root})=>realpathOrSelf((0,import_node_path2.join)(workPath,root)))]),workload=workloads.find((_,i)=>roots[i]===projectRoot);if(!workload)return builds;let rootOf=`"." is the root of ${workload.kind} "${workload.name}"`;if(outputDirectory)throw new import_build_utils3.NowBuildError({code:"EMPTY_OUTPUT_DIRECTORY",message:`Can't publish static files: outputDirectory "${outputDirectory}" is missing or empty, and ${rootOf}. Put the static files in "${outputDirectory}", or remove outputDirectory to deploy without static files.`});return output.log(`Not publishing static files: ${rootOf}. To publish static files, set outputDirectory to a directory that contains only static files.`),builds.filter(build2=>!rootStaticBuilds.includes(build2))}}});var require_validate_package_manifest=__commonJS({"../cli-builder-integration/dist/validate-package-manifest.js"(exports,module){"use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM2=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),validate_package_manifest_exports={};__export(validate_package_manifest_exports,{validatePackageManifest:()=>validatePackageManifest});module.exports=__toCommonJS2(validate_package_manifest_exports);var import_ajv=__toESM2(require_ajv()),import_build_utils3=__require("@vercel/build-utils"),ajv=new import_ajv.default,validate=ajv.compile(import_build_utils3.packageManifestSchema);function validatePackageManifest(data){return validate(data)?null:(validate.errors??[]).map(e=>`${e.dataPath||"(root)"} ${e.message}`).join("; ")}}});var require_framework=__commonJS({"../runtimes/dist/framework.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),framework_exports={};__export(framework_exports,{DETECTION_FRAMEWORKS:()=>DETECTION_FRAMEWORKS,filterFrameworksByRuntime:()=>filterFrameworksByRuntime,frameworksBySlug:()=>frameworksBySlug,getRuntimeFramework:()=>getRuntimeFramework,inferBuilderRuntimeFromFramework:()=>inferBuilderRuntimeFromFramework,inferRuntimeFromFramework:()=>inferRuntimeFromFramework,inferServerRuntimeFromFramework:()=>inferServerRuntimeFromFramework,isBFFFramework:()=>isBFFFramework,isFrontendFramework:()=>isFrontendFramework});module.exports=__toCommonJS2(framework_exports);var import_build_utils3=__require("@vercel/build-utils"),import_frameworks=require_frameworks(),import_constants=require_constants(),frameworksBySlug=new Map(import_frameworks.frameworkList.flatMap(f=>typeof f.slug=="string"?[[f.slug,f]]:[])),DETECTION_FRAMEWORKS=import_frameworks.frameworkList.filter(framework=>!framework.experimental||framework.runtimeFramework);function inferRuntimeFromFramework(framework){if(framework){if(framework in import_constants.RUNTIME_BUILDERS)return framework;if((0,import_build_utils3.isPythonFramework)(framework))return"python";if((0,import_build_utils3.isBackendFramework)(framework))return"node"}}var STATIC_BUILDER_RUNTIMES={hugo:"go",jekyll:"ruby",middleman:"ruby",zola:"rust"};function inferServerRuntimeFromFramework(framework){if(!framework||framework==="services")return;let builder=frameworksBySlug.get(framework)?.useRuntime?.use;if(builder)return import_constants.BUILDER_RUNTIMES[builder]??"node"}function inferBuilderRuntimeFromFramework(framework){if(!framework||framework==="container"||framework==="services")return;let f=frameworksBySlug.get(framework);if(!f)return;let declaredBuilder=f.useRuntime?.use;return declaredBuilder?import_constants.BUILDER_RUNTIMES[declaredBuilder]:STATIC_BUILDER_RUNTIMES[framework]??"node"}function isFrontendFramework(framework){return!!framework&&!inferRuntimeFromFramework(framework)}var BFF_FRAMEWORKS=new Set(["nextjs","nuxtjs","sveltekit","remix","solidstart"]);function isBFFFramework(framework){return!!framework&&BFF_FRAMEWORKS.has(framework)}function filterFrameworksByRuntime(frameworks,runtime){return runtime?frameworks.filter(f=>inferRuntimeFromFramework(f.slug)===runtime):[...frameworks]}function getRuntimeFramework(runtime){if(runtime)return frameworksBySlug.get(runtime)?.runtimeFramework?runtime:void 0}}});var require_manifest=__commonJS({"../cli-builder-integration/dist/manifest.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),manifest_exports={};__export(manifest_exports,{getBuildDiagnosticsFramework:()=>getBuildDiagnosticsFramework,getManifestBuildKey:()=>getManifestBuildKey,writeManifests:()=>writeManifests});module.exports=__toCommonJS2(manifest_exports);var import_path2=__require("path"),import_build_utils3=__require("@vercel/build-utils"),import_framework=require_framework();function getManifestBuildKey(builderUse,workspace,daemonName){return daemonName===void 0?`${builderUse}:${workspace}`:`${builderUse}:daemon:${daemonName}`}async function writeManifests(packageManifests,diagnostics,ops,outputDir){if(packageManifests.length===0)return;let projectManifest={},deployManifestBuilds={},deployManifestServices={};for(let{workspace,root,key,diagnosticsValues,manifest,service,builderUse}of packageManifests){let framework=diagnosticsValues?.framework??manifest.framework;projectManifest[key]={...manifest,workspace,builder:builderUse,framework,serviceName:service?.name,serviceType:service&&(0,import_build_utils3.isExperimentalService)(service)?service.type:void 0,routePrefix:service&&(0,import_build_utils3.isExperimentalService)(service)?service.routePrefix:void 0};let{version:_version,...manifestWithoutVersion}=manifest;if(deployManifestBuilds[key]={...manifestWithoutVersion,framework,root,workspace,builder:builderUse},service){let existing=deployManifestServices[service.name];existing?existing.builds.push(key):deployManifestServices[service.name]={builds:[key],bindings:(0,import_build_utils3.isExperimentalServiceV2)(service)?service.bindings:void 0}}}if(Object.keys(projectManifest).length===0)return;let projectManifestBlob=new import_build_utils3.FileBlob({data:JSON.stringify(projectManifest)});diagnostics["project-manifest.json"]=projectManifestBlob,ops.push((0,import_build_utils3.downloadFile)(projectManifestBlob,(0,import_path2.join)(outputDir,"diagnostics","project-manifest.json")).then(()=>{},err=>err));let deployManifestBlob=new import_build_utils3.FileBlob({data:JSON.stringify({manifestVersion:"2.0",builds:deployManifestBuilds,services:deployManifestServices})});diagnostics["deploy-manifest.json"]=deployManifestBlob,ops.push((0,import_build_utils3.downloadFile)(deployManifestBlob,(0,import_path2.join)(outputDir,"diagnostics","deploy-manifest.json")).then(()=>{},err=>err))}function getBuildDiagnosticsFramework({service,configFramework,detectedFramework}){return service?.framework??(configFramework==="services"?void 0:configFramework)??(0,import_framework.getRuntimeFramework)(service?.runtime)??detectedFramework}}});var require_build_embedding=__commonJS({"../cli-builder-integration/dist/build-embedding.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),build_embedding_exports={};__export(build_embedding_exports,{shouldEmbedFlagsDefinitions:()=>shouldEmbedFlagsDefinitions});module.exports=__toCommonJS2(build_embedding_exports);var import_build_utils3=__require("@vercel/build-utils");function isFlagsEmbedOption(input){return input==="force-on"||input==="force-off"}var SDK_KEY_REGEX=/^vf_(?:server|client)_/;function envHasSdkKey(){for(let value of Object.values(process.env))if(typeof value=="string"&&SDK_KEY_REGEX.test(value))return!0}async function shouldEmbedFlagsDefinitions(cwd,packageJson,vercelFlags){if(process.env.VERCEL_FLAGS_DISABLE_DEFINITION_EMBEDDING==="1")return!1;if(isFlagsEmbedOption(process.env.VERCEL_FLAGS_EMBED_DEFINITIONS))return process.env.VERCEL_FLAGS_EMBED_DEFINITIONS==="force-on";if(vercelFlags?.enabledAt!==void 0||envHasSdkKey())return!0;let hasVercelFlags=await(0,import_build_utils3.isPackageInstalled)("@flags-sdk/vercel",cwd),hasFlagsCore=await(0,import_build_utils3.isPackageInstalled)("@vercel/flags-core",cwd);if(hasVercelFlags||hasFlagsCore)return!0;let dependencies={...packageJson?.dependencies,...packageJson?.devDependencies,...packageJson?.optionalDependencies};return!!(dependencies["@flags-sdk/vercel"]||dependencies["@vercel/flags-core"])}}});var require_validate_build_output=__commonJS({"../cli-builder-integration/dist/validate-build-output.js"(exports,module){"use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM2=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),validate_build_output_exports={};__export(validate_build_output_exports,{reportBuildOutputProblems:()=>reportBuildOutputProblems,validateBuildOutput:()=>validateBuildOutput});module.exports=__toCommonJS2(validate_build_output_exports);var import_fs_extra2=__toESM2(require_lib()),import_path2=__require("path"),import_build_utils3=__require("@vercel/build-utils");function logDebug(message,output){output?.debug(message),(0,import_build_utils3.debug)(message)}async function validateOutputConfig(configPath,label,problems){if(!await import_fs_extra2.default.pathExists(configPath)){problems.push({severity:"error",message:`${label} is missing config.json.`});return}let config;try{config=await import_fs_extra2.default.readJSON(configPath)}catch(err){problems.push({severity:"error",message:`${label} config.json is not valid JSON: ${err instanceof Error?err.message:String(err)}.`});return}config&&config.version!==3&&problems.push({severity:"warning",message:`${label} config.json has unexpected version "${config.version}" (expected 3).`})}async function validateBuildOutput(outputDir,output){let problems=[];logDebug(`Validating build output at "${outputDir}"`,output);try{await validateOutputConfig((0,import_path2.join)(outputDir,"config.json"),"Build output",problems);let servicesDir=(0,import_path2.join)(outputDir,"services"),serviceNames=[];try{serviceNames=(await import_fs_extra2.default.readdir(servicesDir,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch(err){if(err?.code!=="ENOENT")throw err}let[hasFunctions,hasStatic,hasDaemons]=await Promise.all([import_fs_extra2.default.pathExists((0,import_path2.join)(outputDir,"functions")),import_fs_extra2.default.pathExists((0,import_path2.join)(outputDir,"static")),import_fs_extra2.default.pathExists((0,import_path2.join)(outputDir,"daemons"))]),hasServices=serviceNames.length>0;!hasFunctions&&!hasStatic&&!hasServices&&!hasDaemons&&problems.push({severity:"warning",message:'Build output contains no "functions", "static", or "services" directory; the build may not have produced any deployable output.'});for(let name of serviceNames){let serviceDir=(0,import_path2.join)(servicesDir,name),label=`Build output service "${name}"`;await validateOutputConfig((0,import_path2.join)(serviceDir,"config.json"),label,problems);let[svcHasFunctions,svcHasStatic]=await Promise.all([import_fs_extra2.default.pathExists((0,import_path2.join)(serviceDir,"functions")),import_fs_extra2.default.pathExists((0,import_path2.join)(serviceDir,"static"))]);!svcHasFunctions&&!svcHasStatic&&problems.push({severity:"warning",message:`${label} contains no "functions" or "static" directory; the service may not have produced any deployable output.`})}return logDebug(`Build output validation found ${problems.length} problem(s)`+(problems.length?`: ${problems.map(p=>`${p.severity}: ${p.message}`).join("; ")}`:""),output),problems}catch(err){return[{severity:"error",message:`Unexpected error while validating build output: ${err instanceof Error?err.message:String(err)}.`}]}}function reportBuildOutputProblems(problems,output){for(let problem of problems)problem.severity==="error"?output.error(problem.message):output.warn(problem.message)}}});var require_framework_detection=__commonJS({"../cli-builder-integration/dist/framework-detection.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),framework_detection_exports={};__export(framework_detection_exports,{detectAllFrameworks:()=>detectAllFrameworks,detectFirstDeploymentFramework:()=>detectFirstDeploymentFramework,isFirstDeployment:()=>isFirstDeployment,isFrameworkDetectionEnabled:()=>isFrameworkDetectionEnabled,warnIfFrameworkMismatch:()=>warnIfFrameworkMismatch});module.exports=__toCommonJS2(framework_detection_exports);var import_fs_detectors=require_dist3(),import_frameworks=require_frameworks(),import_build_utils3=__require("@vercel/build-utils");function logDebug(message,output){output?.debug(message),(0,import_build_utils3.debug)(message)}function isFrameworkDetectionEnabled(output){let raw=process.env.VERCEL_FRAMEWORK_DETECTION,enabled=raw==="1";return logDebug(`Framework detection: VERCEL_FRAMEWORK_DETECTION=${raw===void 0?"<unset>":JSON.stringify(raw)} -> ${enabled?"enabled":"disabled"}`,output),enabled}function isFirstDeployment(output){let raw=process.env.VERCEL_FIRST_DEPLOYMENT,result=raw==="1";return logDebug(`isFirstDeployment: VERCEL_FIRST_DEPLOYMENT=${raw===void 0?"<unset>":JSON.stringify(raw)} -> ${result}`,output),result}async function detectFirstDeploymentFramework(options){let{workPath,projectSettings,frameworkExplicitlyConfigured,output}=options;if(logDebug(`First deployment: evaluating framework detection (workPath="${workPath}", configuredFramework=${projectSettings.framework?`"${projectSettings.framework}"`:"<none>"})`,output),!isFirstDeployment(output))return logDebug("First deployment: skipping framework detection because this is not a first deployment",output),{status:"skipped"};if(frameworkExplicitlyConfigured||projectSettings.framework)return logDebug(`First deployment: skipping framework detection because a framework is already configured ("${projectSettings.framework}")`,output),{status:"skipped"};logDebug(`First deployment: no framework configured; detecting from source at "${workPath}"`,output);let detected=await(0,import_fs_detectors.detectFrameworkRecord)({fs:new import_fs_detectors.LocalFileSystemDetector(workPath),frameworkList:import_frameworks.frameworkList});if(!detected||!detected.slug)return logDebug("First deployment: no framework detected from source code",output),{status:"not-detected"};let{slug}=detected;return projectSettings.framework=slug,logDebug(`First deployment: detected framework "${slug}"${detected.detectedVersion?` (version ${detected.detectedVersion})`:""}; applied to project settings for this build`,output),{status:"detected",slug,...detected.detectedVersion&&{version:detected.detectedVersion}}}async function detectAllFrameworks(workPath,customFrameworkList,output){logDebug(`Framework cross-check: detecting frameworks at "${workPath}"`,output);let slugs=(await(0,import_fs_detectors.detectFrameworks)({fs:new import_fs_detectors.LocalFileSystemDetector(workPath),frameworkList:customFrameworkList??import_frameworks.frameworkList})).map(f=>f.slug).filter(slug=>!!slug);return logDebug(`Framework cross-check: detected [${slugs.join(", ")||"<none>"}]`,output),slugs}function isHighConfidenceDetection(slug){return import_frameworks.frameworkList.find(f=>f.slug===slug)?.detectionConfidence!=="weak"}function warnIfFrameworkMismatch(options,output){let{configuredFramework,detectedFrameworks,usedBuilders=[],usedFrameworks=[]}=options;if(detectedFrameworks.length===0)return logDebug("Framework cross-check: nothing detected from source; skipping validation",output),"none-detected";let confidentFrameworks=detectedFrameworks.filter(isHighConfidenceDetection);if(configuredFramework)return detectedFrameworks.includes(configuredFramework)?(logDebug(`Framework cross-check: configured framework "${configuredFramework}" matches detected frameworks; no mismatch`,output),"match"):confidentFrameworks.length===0?(logDebug(`Framework cross-check: configured framework "${configuredFramework}" not among detected [${detectedFrameworks.join(", ")}], but all detections are low-confidence; skipping warning`,output),"low-confidence"):(logDebug(`Framework cross-check: configured framework "${configuredFramework}" not among detected [${confidentFrameworks.join(", ")}]; warning`,output),output?.warn(`Your project is configured to use the "${configuredFramework}" framework, but the source code looks like it's for: ${confidentFrameworks.join(", ")}. This may be a misconfiguration.`,null,"https://vercel.com/docs/project-configuration","Learn More"),"configured-mismatch");if(detectedFrameworks.some(slug=>{if(usedFrameworks.includes(slug))return!0;let expectedBuilder=import_frameworks.frameworkList.find(f=>f.slug===slug)?.useRuntime?.use;return expectedBuilder?usedBuilders.some(use=>use===expectedBuilder||use.startsWith(`${expectedBuilder}@`)):!1}))return logDebug(`Framework cross-check: no framework configured, but the build used one of the detected frameworks [${detectedFrameworks.join(", ")}]; no mismatch`,output),"match";let warnableFrameworks=confidentFrameworks.filter(slug=>!!import_frameworks.frameworkList.find(f=>f.slug===slug)?.useRuntime?.use);return warnableFrameworks.length===0?(logDebug(`Framework cross-check: no framework configured and detections [${detectedFrameworks.join(", ")}] are low-confidence or have no dedicated runtime builder; skipping warning`,output),"low-confidence"):(logDebug(`Framework cross-check: no framework configured and the build did not use any of the detected frameworks [${warnableFrameworks.join(", ")}] (used builders: [${usedBuilders.join(", ")||"<none>"}]); warning`,output),output?.warn(`The source code looks like it's for: ${warnableFrameworks.join(", ")}, but no framework is configured for this project and the build did not use ${warnableFrameworks.length===1?"its builder":"their builders"}. Set the framework in your Project Settings if this is unexpected.`,null,"https://vercel.com/docs/project-configuration","Learn More"),"unused-mismatch")}}});var require_runtime=__commonJS({"../runtimes/dist/runtime.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),runtime_exports={};__export(runtime_exports,{getBuilderForRuntime:()=>getBuilderForRuntime,inferRuntime:()=>inferRuntime});module.exports=__toCommonJS2(runtime_exports);var import_constants=require_constants(),import_framework=require_framework();function getBuilderForRuntime(runtime){let builder=import_constants.RUNTIME_BUILDERS[runtime];if(!builder)throw new Error(`Unknown runtime: ${runtime}`);return builder}function inferRuntime(config){if(config.runtime&&config.runtime in import_constants.RUNTIME_BUILDERS)return config.runtime;let frameworkRuntime=(0,import_framework.inferRuntimeFromFramework)(config.framework);if(frameworkRuntime)return frameworkRuntime;if(config.builder){for(let[runtime,builderName]of Object.entries(import_constants.RUNTIME_BUILDERS))if(config.builder===builderName)return runtime}if(config.entrypoint){if(config.entrypoint==="pyproject.toml"||config.entrypoint.endsWith("/pyproject.toml"))return"python";for(let[ext,runtime]of Object.entries(import_constants.ENTRYPOINT_EXTENSIONS))if(config.entrypoint.endsWith(ext))return runtime}}}});var require_monorepo=__commonJS({"../cli-builder-integration/dist/monorepo.js"(exports,module){"use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM2=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),monorepo_exports={};__export(monorepo_exports,{applyServicesMonorepoDefaults:()=>applyServicesMonorepoDefaults,setMonorepoDefaultSettings:()=>setMonorepoDefaultSettings});module.exports=__toCommonJS2(monorepo_exports);var import_path2=__require("path"),import_fs_detectors=require_dist3(),import_runtime=require_runtime(),import_title=__toESM2(require_lib2()),import_fs_extra2=__toESM2(require_lib()),import_build_utils3=__require("@vercel/build-utils");async function setMonorepoDefaultSettings(cwd,workPath,projectSettings,output){let localFileSystem=new import_fs_detectors.LocalFileSystemDetector(cwd),projectName=(0,import_path2.basename)(workPath),relativeToRoot=(0,import_path2.relative)(workPath,cwd),setCommand=(command,value)=>{projectSettings[command]?(0,import_build_utils3.debug)(`Skipping auto-assignment of ${command} as it is already set via project settings or configuration overrides.`):projectSettings[command]=value};try{let result=await(0,import_fs_detectors.getMonorepoDefaultSettings)(projectName,(0,import_path2.relative)(cwd,workPath),relativeToRoot,localFileSystem);if(result===null)return;projectSettings.monorepoManager=result.monorepoManager;let{monorepoManager,...commands}=result;output.log(`Detected ${(0,import_title.default)(monorepoManager)}. Adjusting default settings...`),commands.buildCommand&&setCommand("buildCommand",commands.buildCommand),commands.installCommand&&setCommand("installCommand",commands.installCommand),commands.commandForIgnoringBuildStep&&setCommand("commandForIgnoringBuildStep",commands.commandForIgnoringBuildStep)}catch(error){if(error instanceof import_fs_detectors.MissingBuildPipeline||error instanceof import_fs_detectors.MissingBuildTarget){output.warn(`${error.message} Skipping automatic setting assignment.`);return}throw error}}async function hasVercelBuildScript(serviceRoot){try{return(await import_fs_extra2.default.readJSON((0,import_path2.join)(serviceRoot,"package.json")))?.scripts?.["vercel-build"]!==void 0}catch{return!1}}async function applyServicesMonorepoDefaults(cwd,workPath,services,projectSettings,output){let localFileSystem=new import_fs_detectors.LocalFileSystemDetector(cwd),result,announced=!1;for(let[name,config]of Object.entries(services)){if(config.buildCommand){(0,import_build_utils3.debug)(`Skipping auto-assignment of buildCommand for service "${name}" as it is already set in the services configuration.`);continue}let runtime=(0,import_runtime.inferRuntime)({runtime:config.runtime,framework:config.framework,entrypoint:config.entrypoint});if(runtime!==void 0&&runtime!=="node"){(0,import_build_utils3.debug)(`Skipping monorepo defaults for service "${name}": runtime "${runtime}" does not build via the monorepo task graph.`);continue}let serviceRoot=(0,import_path2.resolve)(workPath,config.root??"."),projectPath=(0,import_path2.relative)(cwd,serviceRoot);if((0,import_path2.isAbsolute)(projectPath)||projectPath===".."||projectPath.startsWith(`..${import_path2.sep}`)){(0,import_build_utils3.debug)(`Skipping monorepo defaults for service "${name}": root "${config.root}" is outside "${cwd}".`);continue}if(await hasVercelBuildScript(serviceRoot)){(0,import_build_utils3.debug)(`Skipping monorepo defaults for service "${name}": a \`vercel-build\` script is defined in its root package.json.`);continue}let posixProjectPath=(0,import_build_utils3.normalizePath)(projectPath),posixRelativeToRoot=(0,import_build_utils3.normalizePath)((0,import_path2.relative)(serviceRoot,cwd)),settings;try{settings=await(0,import_fs_detectors.getMonorepoDefaultSettings)((0,import_path2.basename)(serviceRoot),posixProjectPath||"/",posixRelativeToRoot,localFileSystem)}catch(error){if(error instanceof import_fs_detectors.MissingBuildPipeline){output.warn(`${error.message} Skipping automatic setting assignment.`);break}if(error instanceof import_fs_detectors.MissingBuildTarget){output.warn(`Service "${name}": ${error.message} Skipping automatic setting assignment.`);continue}throw error}if(settings===null)break;projectSettings.monorepoManager=settings.monorepoManager,settings.buildCommand&&(announced||(output.log(`Detected ${(0,import_title.default)(settings.monorepoManager)}. Adjusting default settings...`),announced=!0),(0,import_build_utils3.debug)(`Assigning buildCommand "${settings.buildCommand}" to service "${name}".`),result??={...services},result[name]={...config,buildCommand:settings.buildCommand})}return result??services}}});var require_corepack=__commonJS({"../cli-builder-integration/dist/corepack.js"(exports,module){"use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM2=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),corepack_exports={};__export(corepack_exports,{cleanupCorepack:()=>cleanupCorepack,initCorepack:()=>initCorepack});module.exports=__toCommonJS2(corepack_exports);var import_path2=__require("path"),import_build_utils3=__require("@vercel/build-utils"),import_fs_extra2=__toESM2(require_lib());async function initCorepack({repoRootPath,output,readJSONFile:readJSONFile2,isCantParseJSONFile,warmPackageManager=!1}){if(process.env.ENABLE_EXPERIMENTAL_COREPACK!=="1")return null;let pkg=await readJSONFile2((0,import_path2.join)(repoRootPath,"package.json"));if(isCantParseJSONFile(pkg))output.warn("Warning: Could not enable corepack because package.json is invalid JSON",pkg.meta?.parseErrorLocation??pkg.message);else if(!pkg?.packageManager)output.warn('Warning: Could not enable corepack because package.json is missing "packageManager" property');else{output.log(`Detected ENABLE_EXPERIMENTAL_COREPACK=1 and "${pkg.packageManager}" in package.json`);let corepackRootDir=(0,import_path2.join)(repoRootPath,".vercel","cache","corepack"),corepackHomeDir=(0,import_path2.join)(corepackRootDir,"home"),corepackShimDir=(0,import_path2.join)(corepackRootDir,"shim");await import_fs_extra2.default.mkdirp(corepackHomeDir),await import_fs_extra2.default.mkdirp(corepackShimDir),process.env.COREPACK_HOME=corepackHomeDir,process.env.PATH=`${corepackShimDir}${import_path2.delimiter}${process.env.PATH}`;let pkgManagerName=pkg.packageManager.split("@")[0];if(await(0,import_build_utils3.spawnAsync)("corepack",["enable",pkgManagerName,"--install-directory",corepackShimDir],{prettyCommand:`corepack enable ${pkgManagerName}`}),warmPackageManager)try{await(0,import_build_utils3.spawnAsync)(pkgManagerName,["--version"],{prettyCommand:`${pkgManagerName} --version`,stdio:"pipe"})}catch(err){output.debug(`Failed to pre-download "${pkg.packageManager}" via corepack: ${err instanceof Error?err.message:String(err)}`)}return corepackShimDir}return null}function cleanupCorepack(corepackShimDir){process.env.COREPACK_HOME&&delete process.env.COREPACK_HOME,process.env.PATH&&(process.env.PATH=process.env.PATH.replace(`${corepackShimDir}${import_path2.delimiter}`,""))}}});var require_do_build=__commonJS({"../cli-builder-integration/dist/do-build.js"(exports,module){"use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM2=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),do_build_exports={};__export(do_build_exports,{doBuild:()=>doBuild3,mergeDeploymentId:()=>mergeDeploymentId});module.exports=__toCommonJS2(do_build_exports);var import_fs_extra2=__toESM2(require_lib()),import_minimatch=__toESM2(require_minimatch()),import_path2=__require("path"),import_semver=__toESM2(require_semver()),import_build_utils3=__require("@vercel/build-utils"),import_client=require_dist5(),import_frameworks=require_frameworks(),import_fs_detectors=require_dist3(),import_service_topology=require_dist4(),import_detect_builders_with_services=require_detect_builders_with_services(),import_schedule_services=require_schedule_services(),import_get_daemon_builders=require_get_daemon_builders(),import_routing_utils=require_dist2(),import_write_build_result3=require_write_build_result(),import_build_runner2=require_build_runner(),import_execute_builder=require_execute_builder(),import_diagnostics3=require_diagnostics(),import_build_concurrency=require_build_concurrency(),import_workspace_install_targets=require_workspace_install_targets(),import_shared_workspace_install=require_shared_workspace_install(),import_uv_workspace_builds=require_uv_workspace_builds(),import_backend_rewrite_warning=require_backend_rewrite_warning(),import_service_route_ownership=require_service_route_ownership(),import_service_schedules=require_service_schedules(),import_validate_cron_secret=require_validate_cron_secret(),import_workload_root_static_app=require_workload_root_static_app(),import_validate_package_manifest=require_validate_package_manifest(),import_manifest=require_manifest(),import_build_embedding=require_build_embedding(),import_get_files=require_get_files(),import_validate_build_output=require_validate_build_output(),import_framework_detection=require_framework_detection(),import_monorepo=require_monorepo(),import_corepack=require_corepack();function pickOverrides(config){let overrides={};for(let property of["buildCommand","devCommand","framework","ignoreCommand","installCommand","outputDirectory"])config[property]!==void 0&&(overrides[property==="ignoreCommand"?"commandForIgnoringBuildStep":property]=config[property]);return overrides}var SERVICE_BUILD_IMMUTABLE_ENV_VARS=["VERCEL_IMMUTABLE_STATIC_FILES_ENABLED"];function hasNonEmptyObject(value){return value!=null&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length>0}function getGeneratedServiceAlreadyBuiltWarning(service){let framework=service.framework??"unknown",entrypoint=service.entrypoint??service.builder.src??"unknown";return`Detected already-built service "${service.name}" from lazily generated \`.vercel/output/config.json\` (framework: ${framework}, entrypoint: ${entrypoint}). It will not be treated as a service because its build output already exists at the top level. Configure it in \`vercel.json\` as a \`services\` entry to remove this warning.`}async function doBuild3(request,dependencies){let{project,buildsJson,cwd,outputDir,span,standalone=!1,localConfigPath,cliVersion,userAgent}=request,{output,createBuildRunner:createBuildRunner2,canBuildInSubprocess:canBuildInSubprocess2,importBuilders:importBuilders2,formatResolvedBuilders:formatResolvedBuilders2,writeBuildResult:writeBuildResult2,toEnumerableError:toEnumerableError2,readJSONFile:readJSONFile2,isCantParseJSONFile,validateConfig:validateConfig2,compileVercelConfig:compileVercelConfig2,findSourceVercelConfigFile:findSourceVercelConfigFile2,defaultVercelConfigFilename,startBuildTiming}=dependencies,VALID_DEPLOYMENT_ID_PATTERN=/^[a-zA-Z0-9_-]+$/,workPath=(0,import_path2.join)(cwd,project.settings.rootDirectory||"."),repoRootPath=cwd,sourceConfigFile=await findSourceVercelConfigFile2(workPath),corepackShimDir;if(sourceConfigFile){corepackShimDir=await(0,import_corepack.initCorepack)({repoRootPath,output,readJSONFile:readJSONFile2,isCantParseJSONFile,warmPackageManager:(0,import_build_utils3.resolveBuildConcurrency)()>1});let installDepsSpan=span.child("vc.installDeps"),installRan=!1;try{let installCommand=project.settings.installCommand;typeof installCommand=="string"?installCommand.trim()?(output.log("Running install command before config compilation..."),installRan=await(0,import_build_utils3.runCustomInstallCommand)({destPath:workPath,installCommand,spawnOpts:{env:process.env},projectCreatedAt:project.settings.createdAt})):output.debug("Skipping empty install command"):(output.log("Installing dependencies before config compilation..."),installRan=await(0,import_build_utils3.runNpmInstall)(workPath,[],{env:process.env},void 0,project.settings.createdAt))}finally{installDepsSpan.stop()}if(installRan){let{packageJsonPath}=await(0,import_build_utils3.scanParentDirs)(workPath,!1);packageJsonPath&&(process.env.VERCEL_INSTALL_COMPLETED_PATH=packageJsonPath),process.env.VERCEL_INSTALL_COMPLETED="1"}}let compileResult=await span.child("vc.compileVercelConfig").trace(()=>compileVercelConfig2(workPath)),vercelConfigPath=localConfigPath||compileResult.configPath||(0,import_path2.join)(workPath,"vercel.json"),[pkg,vercelConfig,hasInstrumentation]=await span.child("vc.readConfigInputs").trace(()=>Promise.all([readJSONFile2((0,import_path2.join)(workPath,"package.json")),readJSONFile2(vercelConfigPath),(0,import_fs_detectors.detectInstrumentation)(new import_fs_detectors.LocalFileSystemDetector(workPath))]));if(isCantParseJSONFile(pkg))throw pkg;if(isCantParseJSONFile(vercelConfig))throw vercelConfig;hasInstrumentation&&(output.debug("OpenTelemetry instrumentation detected. Automatic fetch instrumentation will be disabled."),process.env.VERCEL_TRACING_DISABLE_AUTOMATIC_FETCH_INSTRUMENTATION="1"),vercelConfig&&(vercelConfig[import_client.fileNameSymbol]=compileResult.wasCompiled?compileResult.sourceFile||defaultVercelConfigFilename:"vercel.json");let localConfig=vercelConfig||{},validateError=validateConfig2(localConfig);if(validateError)throw validateError;let authoredSchedules=(0,import_build_utils3.getNamedSchedules)(localConfig.schedules),daemonNames=(0,import_build_utils3.getDaemonNames)(localConfig),daemons=(0,import_get_daemon_builders.splitDaemonEntrypoints)(daemonNames.length>0?localConfig.daemons:void 0);if((0,import_get_daemon_builders.validateDaemonImageRepositories)(daemons),localConfig.crons&&localConfig.crons.length>0){let cronSecretError=(0,import_validate_cron_secret.validateCronSecret)(process.env.CRON_SECRET);if(cronSecretError)throw cronSecretError}let projectSettings={...project.settings,...pickOverrides(localConfig)};buildsJson.detectedFramework=await span.child("vc.detectFirstDeploymentFramework",{firstDeployment:String(process.env.VERCEL_FIRST_DEPLOYMENT==="1"),configuredFramework:projectSettings.framework??void 0}).trace(async s=>{let result=await(0,import_framework_detection.detectFirstDeploymentFramework)({workPath,projectSettings,frameworkExplicitlyConfigured:Object.prototype.hasOwnProperty.call(localConfig,"framework"),output});return s.setAttributes({detectionStatus:result.status,detectedFramework:result.slug,detectedFrameworkVersion:result.version}),result});let buildpackCommands={installCommand:projectSettings.installCommand??void 0,buildCommand:projectSettings.buildCommand??void 0};process.env.VERCEL_BUILD_MONOREPO_SUPPORT==="1"&&pkg?.scripts?.["vercel-build"]===void 0&&projectSettings.rootDirectory!==null&&projectSettings.rootDirectory!=="."&&await span.child("vc.setMonorepoDefaultSettings").trace(()=>(0,import_monorepo.setMonorepoDefaultSettings)(cwd,workPath,projectSettings,output)),await span.child("vc.prepareFlagsDefinitions").trace(async s=>{let shouldEmbed=await(0,import_build_embedding.shouldEmbedFlagsDefinitions)(cwd,pkg,projectSettings.vercelFlags);if(s.setAttributes({shouldEmbed:String(shouldEmbed)}),!shouldEmbed)return;let{prepareFlagsDefinitions}=await import("../../chunks/dist-33WTJLVQ.js");await prepareFlagsDefinitions({cwd,env:process.env,userAgentSuffix:userAgent,output})});let files=await span.child("vc.getFiles").trace(async s=>{let result=(await(0,import_get_files.staticFiles)(workPath,{},output)).map(f=>(0,import_build_utils3.normalizePath)((0,import_path2.relative)(workPath,f)));return s.setAttributes({fileCount:String(result.length)}),result}),scheduleServicePlan=await(0,import_schedule_services.planScheduleServices)({schedules:authoredSchedules,workPath,repoRootPath,files,functions:localConfig.functions}),scheduleServiceBuilds=new Set(scheduleServicePlan.services.map(service=>service.builder)),reservedServiceFiles=scheduleServicePlan.sourceFiles,detectedFrameworksPromise=span.child("vc.detectAllFrameworks",{enabled:String((0,import_framework_detection.isFrameworkDetectionEnabled)(output))}).trace(async s=>{if(!(0,import_framework_detection.isFrameworkDetectionEnabled)(output))return[];try{let slugs=await(0,import_framework_detection.detectAllFrameworks)(workPath,void 0,output);return s.setAttributes({detectedFrameworks:slugs.join(",")||void 0,detectedFrameworkCount:String(slugs.length)}),slugs}catch(err){return output.debug(`Framework cross-check detection failed: ${err}`),s.setAttributes({error:err instanceof Error?err.message:String(err)}),[]}}),routesResult=(0,import_routing_utils.getTransformedRoutes)(localConfig);if(routesResult.error)throw routesResult.error;if(localConfig.builds&&localConfig.functions)throw new import_build_utils3.NowBuildError({code:"bad_request",message:"The `functions` property cannot be used in conjunction with the `builds` property. Please remove one of them.",link:"https://vercel.link/functions-and-builds"});let daemonBuilds=await(0,import_get_daemon_builders.getDaemonBuilders)({workPath,repoRootPath,daemons,files}),builds=localConfig.builds||[],zeroConfigRoutes=[],zeroConfigFallbackRoutes=[],detectedServices,detectedResolvedServices,servicesToRecord,hasExperimentalServicesV1ConfiguredInVercelConfig=hasNonEmptyObject(localConfig.experimentalServices),hasExperimentalServicesV2ConfiguredInVercelConfig=hasNonEmptyObject(localConfig.services??localConfig.experimentalServicesV2);hasExperimentalServicesV1ConfiguredInVercelConfig&&output.warn("The `experimentalServices` property is deprecated. Migrate to `services`.");let configuredExperimentalServicesV2=hasExperimentalServicesV2ConfiguredInVercelConfig&&(localConfig.services??localConfig.experimentalServicesV2)?localConfig.services??localConfig.experimentalServicesV2:void 0,nestExperimentalServicesV2Output=hasExperimentalServicesV2ConfiguredInVercelConfig,detectedExperimentalServicesV1Config,detectedExperimentalServicesV2Config=configuredExperimentalServicesV2,monorepoDefaultedServices=new Set,isZeroConfig=!1;if(builds.length>0)output.warn("Due to `builds` existing in your configuration file, the Build and Development Settings defined in your Project Settings will not apply. Learn More: https://vercel.link/unused-build-settings"),builds=builds.flatMap(b=>expandBuild(files,b));else{isZeroConfig=!0;let servicesForDetection=configuredExperimentalServicesV2;if(process.env.VERCEL_BUILD_MONOREPO_SUPPORT==="1"&&configuredExperimentalServicesV2){servicesForDetection=await span.child("vc.applyServicesMonorepoDefaults").trace(()=>(0,import_monorepo.applyServicesMonorepoDefaults)(cwd,workPath,configuredExperimentalServicesV2,projectSettings,output));for(let[name,config2]of Object.entries(servicesForDetection))config2.buildCommand!==configuredExperimentalServicesV2[name]?.buildCommand&&monorepoDefaultedServices.add(name)}let detectedBuilders=await span.child("vc.detectBuilders").trace(()=>(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,{...localConfig,reservedServiceFiles,services:void 0,experimentalServicesV2:servicesForDetection,projectSettings,ignoreBuildScript:!0,featHandleMiss:!0,workPath}));if(detectedBuilders.errors&&detectedBuilders.errors.length>0)throw detectedBuilders.errors[0];for(let w of detectedBuilders.warnings)output.warn(w.message,null,w.link,w.action||"Learn More");detectedBuilders.builders?builds=detectedBuilders.builders:builds=[{src:"**",use:"@vercel/static"}],builds=await(0,import_workload_root_static_app.omitStaticAppAtWorkloadRoot)({builds,serviceBuilds:new Set(detectedBuilders.services?.map(service=>service.builder)),workPath,workloads:[...Object.entries(daemons??{}).map(([name,{root}])=>({kind:"daemon",name,root})),...scheduleServicePlan.services.map(({name,root})=>({kind:"schedule",name,root}))],outputDirectory:projectSettings.outputDirectory,output}),detectedResolvedServices=detectedBuilders.services,servicesToRecord=detectedResolvedServices,detectedServices=detectedBuilders.services?.filter(import_build_utils3.isExperimentalService);let autoDetectedV2Config=detectedBuilders.experimentalServicesV2;if(!hasExperimentalServicesV2ConfiguredInVercelConfig&&autoDetectedV2Config&&(nestExperimentalServicesV2Output=!0,detectedExperimentalServicesV2Config=autoDetectedV2Config),detectedBuilders.useImplicitEnvInjection&&detectedServices&&detectedServices.length>0){let serviceUrlEnvVars=(0,import_build_utils3.getExperimentalServiceUrlEnvVars)({services:detectedServices,frameworkList:import_frameworks.frameworkList,currentEnv:process.env,deploymentUrl:process.env.VERCEL_URL});for(let[key,value]of Object.entries(serviceUrlEnvVars))process.env[key]=value,output.debug(`Injected service URL env var: ${key}=${value}`)}let serviceRewrites=detectedBuilders.serviceRewrites,serviceRewriteRoutes=serviceRewrites&&serviceRewrites.length>0?(0,import_routing_utils.convertRewrites)(serviceRewrites):null;zeroConfigRoutes.push(...detectedBuilders.redirectRoutes||[]);let detectedHostRewriteRoutes=detectedBuilders.hostRewriteRoutes;zeroConfigRoutes=(0,import_routing_utils.appendRoutesToPhase)({routes:zeroConfigRoutes,newRoutes:detectedHostRewriteRoutes??null,phase:null});let detectedServiceRewriteRoutes=nestExperimentalServicesV2Output?[]:detectedBuilders.rewriteRoutes;zeroConfigRoutes.push(...(0,import_routing_utils.appendRoutesToPhase)({routes:[],newRoutes:[...detectedServiceRewriteRoutes||[],...serviceRewriteRoutes||[]],phase:"filesystem"})),zeroConfigRoutes=(0,import_routing_utils.appendRoutesToPhase)({routes:zeroConfigRoutes,newRoutes:detectedBuilders.errorRoutes,phase:"error"}),nestExperimentalServicesV2Output||(zeroConfigRoutes.push(...detectedBuilders.defaultRoutes||[]),zeroConfigFallbackRoutes=detectedBuilders.fallbackRoutes||[])}builds.push(...daemonBuilds),(0,import_backend_rewrite_warning.hasBackendRewriteBehaviorChange)({projectRewrites:localConfig.rewrites,builders:builds})&&output.warn(import_backend_rewrite_warning.BACKEND_REWRITE_BEHAVIOR_WARNING);let checkScheduleServiceNames=()=>(0,import_schedule_services.rejectScheduleServiceNameConflicts)(scheduleServicePlan,[...(servicesToRecord??[]).map(service=>service.name),...Object.keys(detectedExperimentalServicesV1Config??{}),...Object.keys(detectedExperimentalServicesV2Config??{})]);checkScheduleServiceNames(),builds.push(...scheduleServiceBuilds);let builderSpecs=new Set(builds.map(b=>b.use)),buildersWithPkgs=await span.child("vc.importBuilders").trace(async s=>{let builders=await importBuilders2(builderSpecs,cwd,s);return s.setAttributes({resolved:formatResolvedBuilders2(builders)}),builders}),filesMap=await span.child("vc.populateFilesMap").trace(async s=>{let map={};for(let path of files){let fsPath=(0,import_path2.join)(workPath,path),{mode}=await import_fs_extra2.default.stat(fsPath);map[path]=new import_build_utils3.FileFsRef({mode,fsPath})}return s.setAttributes({fileCount:String(files.length)}),map}),buildStamp=startBuildTiming();await import_fs_extra2.default.mkdirp(outputDir);let ops=[],buildsJsonBuilds=new Map,ensureBuildersImported=async buildsToImport=>{let missingBuilderSpecs=new Set(buildsToImport.map(build2=>build2.use).filter(builderSpec=>!buildersWithPkgs.has(builderSpec)));if(missingBuilderSpecs.size===0)return;let importedBuilders=await span.child("vc.importBuilders").trace(async s=>{let builders=await importBuilders2(missingBuilderSpecs,cwd,s);return s.setAttributes({resolved:formatResolvedBuilders2(builders)}),builders});buildersWithPkgs=new Map([...buildersWithPkgs.entries(),...importedBuilders.entries()])},addBuildsToBuildJson=async buildsToAdd=>{await ensureBuildersImported(buildsToAdd);for(let build2 of buildsToAdd){if(buildsJsonBuilds.has(build2))continue;let builderWithPkg=buildersWithPkgs.get(build2.use);if(!builderWithPkg)throw import_diagnostics3.buildDiagnostics.BUILD_BUILDER_LOAD_FAILED({use:build2.use});let{builder,pkg:builderPkg}=builderWithPkg;buildsJsonBuilds.set(build2,{require:builderPkg.name,requirePath:builderWithPkg.path,apiVersion:builder.version,...build2})}buildsJson.builds=Array.from(buildsJsonBuilds.values()),await writeBuildJson(buildsJson,outputDir)},meta={skipDownload:!0,cliVersion,runNpmInstallSet:new Set,...daemons&&{daemonContext:{projectRoot:workPath,daemons}}},scheduleServices=scheduleServicePlan.services.map(({name,root,entrypoint})=>({name,root,entrypoint})),setServicesContext=services=>{let v2Services=(services??[]).filter(import_build_utils3.isExperimentalServiceV2),protectedServices=[...scheduleServices,...v2Services.length>1?v2Services.map(service=>({name:service.name,root:service.root})):[]];protectedServices.length>0?meta.servicesContext={projectRoot:workPath,services:protectedServices}:delete meta.servicesContext};setServicesContext(detectedResolvedServices);let executedBuilds=[],buildResults=new Map,overrides=[];corepackShimDir||(corepackShimDir=await(0,import_corepack.initCorepack)({repoRootPath,output,readJSONFile:readJSONFile2,isCantParseJSONFile,warmPackageManager:(0,import_build_utils3.resolveBuildConcurrency)()>1}));let diagnostics={},packageManifests=[],apiDirFrameworkDetector=createApiDirFrameworkDetector((workPath2,frameworks)=>(0,import_framework_detection.detectAllFrameworks)(workPath2,frameworks,output)),getHasDetectedServices=()=>detectedResolvedServices!==void 0&&detectedResolvedServices.length>0,synthesizedServiceCrons=[],serviceByBuilder=new Map,serviceFileOverrides=new Map;if(getHasDetectedServices())for(let service of detectedResolvedServices)serviceByBuilder.set(service.builder,service);for(let service of scheduleServicePlan.services)serviceByBuilder.set(service.builder,service);let isNestedServiceBuild=build2=>scheduleServiceBuilds.has(build2)||nestExperimentalServicesV2Output&&serviceByBuilder.has(build2),preDeployEntries=[],liveRunners=new Set,buildOrdinals=new Map,generatedRootRoutes,buildDurationsMs=[],buildersWallMs=0,buildConcurrency,getUvWorkspaceCandidates=(builds2,getContext)=>{let candidates=[];for(let build2 of builds2){let context=getContext(build2);if(!context||context.toolchain!=="python"||typeof build2.src!="string")continue;let{service,serviceDir}=context,hasFunctionInstall=(0,import_build_utils3.isExperimentalServiceV2)(service)&&Object.values(service.functions??{}).some(fn=>typeof fn.installCommand=="string");candidates.push({build:build2,builderUse:build2.use,serviceDir,entrypointDir:(0,import_path2.join)(workPath,(0,import_path2.dirname)(build2.src)),defaultInstall:!service.installCommand?.trim()&&!hasFunctionInstall,buildCommand:service.buildCommand})}return candidates},installSharedWorkspaces=async(builds2,getContext)=>{let preinstalled=new Set,logKeptInstalls=(location,reason)=>output.log(`Services in "${location}" keep their own dependency installs and build one after another: ${reason}`),candidates=[];for(let build2 of builds2){let context=getContext(build2);if(!context||typeof build2.src!="string")return preinstalled;if(context.toolchain!=="node")continue;let{service,serviceDir}=context,hasFunctionInstall=(0,import_build_utils3.isExperimentalServiceV2)(service)&&Object.values(service.functions??{}).some(fn=>typeof fn.installCommand=="string");candidates.push({build:build2,builderUse:build2.use,framework:service.framework,serviceDir,installDir:(0,import_path2.join)(workPath,(0,import_path2.dirname)(build2.src)),defaultInstall:service.installCommand==null&&!hasFunctionInstall})}if(candidates.length<2)return preinstalled;if(process.env.NPM_AUTH_TOKEN)return output.log("Services keep their own dependency installs: NPM_AUTH_TOKEN is set"),preinstalled;if(process.env.VERCEL_INSTALL_COMPLETED==="1"&&typeof projectSettings.installCommand=="string")return output.log("Services keep their own dependency installs: the project ran its own install command first"),preinstalled;let workspaceInstallTargets=Array.isArray(meta.workspaceInstallTargets)?meta.workspaceInstallTargets:[],installs=await(0,import_shared_workspace_install.planSharedWorkspaceInstalls)({candidates,repoRootPath,config:{nodeVersion:projectSettings.nodeVersion??void 0,bunVersion:localConfig.bunVersion??void 0},meta,projectCreatedAt:projectSettings.createdAt,workspaceInstallTargets,onSkip:(installRoot,reason)=>logKeptInstalls((0,import_path2.relative)(repoRootPath,installRoot)||".",reason)});for(let install of installs){let location=(0,import_path2.relative)(repoRootPath,install.installRoot)||".";output.log(`Sharing one dependency install across ${install.builds.length} services in "${location}"`),await span.child("vc.sharedWorkspaceInstall",{services:String(install.builds.length)}).trace(()=>(0,import_shared_workspace_install.runSharedWorkspaceInstall)({install,meta,projectCreatedAt:projectSettings.createdAt,workspaceInstallTargets}));for(let build2 of install.builds)preinstalled.add(build2)}return preinstalled},runBuilders=async buildsToRun=>{await addBuildsToBuildJson(buildsToRun),process.env.VERCEL_EXPERIMENTAL_WORKSPACE_SCOPED_INSTALLS==="1"&&(meta.workspaceInstallTargets=await(0,import_workspace_install_targets.collectWorkspaceInstallTargets)({builds:buildsToRun,existingTargets:meta.workspaceInstallTargets,repoRootPath,serviceByBuilder,workPath}));let buildOne=async(build2,concurrent)=>{if(typeof build2.src!="string")return;let builderWithPkg=buildersWithPkgs.get(build2.use);if(!builderWithPkg)throw import_diagnostics3.buildDiagnostics.BUILD_BUILDER_LOAD_FAILED({use:build2.use});try{let{builder,pkg:builderPkg}=builderWithPkg,service=serviceByBuilder.get(build2),legacyExperimentalService=service&&(0,import_build_utils3.isExperimentalService)(service)?service:void 0,serviceWorkspace=service?(0,import_build_utils3.isExperimentalService)(service)?service.workspace:service.root:void 0,stripServiceRoutePrefix=!!legacyExperimentalService?.routePrefix&&legacyExperimentalService.routePrefix!=="/",buildWorkPath=workPath,buildEntrypoint=build2.src,buildFiles=filesMap;if(service&&serviceWorkspace&&serviceWorkspace!=="."){let wsPrefix=serviceWorkspace+"/";buildWorkPath=(0,import_path2.join)(workPath,serviceWorkspace),buildEntrypoint=build2.src.startsWith(wsPrefix)?build2.src.slice(wsPrefix.length):build2.src,buildFiles={};for(let[filePath,file]of Object.entries(filesMap))filePath.startsWith(wsPrefix)&&(buildFiles[filePath.slice(wsPrefix.length)]=file);output.debug(`Service "${service.name}": workspace-rooted build at "${buildWorkPath}", entrypoint "${buildEntrypoint}" (original: "${build2.src}")`)}let daemon=build2.config?.daemon;if(daemon&&!daemonBuilds.includes(build2))throw new import_build_utils3.NowBuildError({code:"INVALID_BUILDS_CONFIG",message:"Daemons are declared in `daemons`; `daemon` is not a `builds` configuration option."});if(daemon){buildWorkPath=(0,import_path2.join)(workPath,daemon.root),buildEntrypoint=daemon.entrypoint;let root=(0,import_build_utils3.normalizePath)((0,import_path2.relative)(workPath,buildWorkPath));if(root!==""){let prefix=`${root}/`;buildFiles={};for(let[filePath,file]of Object.entries(filesMap))filePath.startsWith(prefix)&&(buildFiles[filePath.slice(prefix.length)]=file)}}let restoreEnv=new Map,perBuildEnv=concurrent?{...process.env}:process.env,setBuildEnv=(key,value)=>{concurrent||restoreEnv.set(key,process.env[key]),value===void 0?delete perBuildEnv[key]:perBuildEnv[key]=value},settingsForEnv=service?{buildCommand:service.buildCommand??void 0,installCommand:service.installCommand??void 0,outputDirectory:projectSettings.outputDirectory??void 0,nodeVersion:projectSettings.nodeVersion??void 0}:projectSettings;for(let key of["buildCommand","installCommand","outputDirectory","nodeVersion"]){let value=settingsForEnv[key],envKey="VERCEL_PROJECT_SETTINGS_"+key.replace(/[A-Z]/g,letter=>`_${letter}`).toUpperCase();setBuildEnv(envKey,typeof value=="string"?value:void 0),typeof value=="string"&&output.debug(`Setting env ${envKey} to "${value}"`)}let isFrontendBuilder=build2.config&&"framework"in build2.config,builderFramework=build2.config?.framework??projectSettings.framework,isApiDir=isZeroConfig&&!service&&!isFrontendBuilder&&!daemon,detectFrameworkDir=daemon?(0,import_path2.join)(workPath,daemon.root):isApiDir?buildWorkPath:void 0,detectedFramework=detectFrameworkDir?await apiDirFrameworkDetector.detect(build2.use??"",detectFrameworkDir):void 0,buildConfig;if(isZeroConfig)if(service){let serviceBuildCommand=build2.config?.buildpack&&monorepoDefaultedServices.has(service.name)?void 0:service.buildCommand;buildConfig={...build2.config,...(0,import_build_utils3.isExperimentalServiceV2)(service)&&service.functions?{functions:service.functions,serviceName:service.name}:void 0,projectSettings:{...projectSettings,framework:service.framework??null,buildCommand:serviceBuildCommand??null,installCommand:service.installCommand??null},installCommand:service.installCommand??void 0,buildCommand:serviceBuildCommand??void 0,preDeployCommand:legacyExperimentalService?.preDeployCommand??void 0,framework:builderFramework,nodeVersion:projectSettings.nodeVersion,bunVersion:localConfig.bunVersion??void 0}}else buildConfig={outputDirectory:projectSettings.outputDirectory??void 0,...build2.config,projectSettings,installCommand:projectSettings.installCommand??void 0,devCommand:projectSettings.devCommand??void 0,buildCommand:projectSettings.buildCommand??void 0,...build2.config?.buildpack?buildpackCommands:void 0,framework:isFrontendBuilder?projectSettings.framework:void 0,nodeVersion:projectSettings.nodeVersion,bunVersion:localConfig.bunVersion??void 0};else buildConfig={...build2.config||{},bunVersion:localConfig.bunVersion??void 0};let diagnosticsFramework=(0,import_manifest.getBuildDiagnosticsFramework)({service,configFramework:buildConfig.framework,detectedFramework}),diagnosticsValues=diagnosticsFramework?{framework:diagnosticsFramework}:void 0,builderSpan=span.child("vc.builder",{"builder.name":builderPkg.name,"builder.version":builderPkg.version,"builder.dynamicallyInstalled":String(builderWithPkg.dynamicallyInstalled)}),daemonName=build2.config?.daemon?.name;(service||daemonName)&&builderSpan.setAttributes({"service.name":service?.name??daemonName,"service.runtime":getBuildToolchain(build2,service),"service.kind":service?"service":"daemon"});let serviceRoutePrefix=build2.config?.routePrefix,serviceConfigWorkspace=build2.config?.workspace,preDeployCmd=legacyExperimentalService?.preDeployCommand?.trim(),preDeployEntry=preDeployCmd&&service?{ordinal:buildOrdinals.get(build2)??Number.MAX_SAFE_INTEGER,service:service.name}:void 0;preDeployEntry&&preDeployEntries.push(preDeployEntry);let buildOptions={files:buildFiles,entrypoint:buildEntrypoint,workPath:buildWorkPath,repoRootPath,config:buildConfig,meta,span:builderSpan,...diagnosticsValues?{diagnosticsValues}:void 0,...preDeployCmd?{registerPreDeploy:callback=>{preDeployEntry.callback=callback}}:void 0,...service?{service:{name:service.name,...scheduleServiceBuilds.has(build2)?{type:"job",trigger:"schedule"}:void 0,...legacyExperimentalService?{type:legacyExperimentalService.type,trigger:legacyExperimentalService.trigger}:void 0,routePrefix:typeof serviceRoutePrefix=="string"?serviceRoutePrefix:void 0,workspace:typeof serviceConfigWorkspace=="string"?serviceConfigWorkspace:serviceWorkspace,...legacyExperimentalService?{schedule:legacyExperimentalService.schedule}:void 0}}:void 0};if(output.debug(`Building entrypoint "${build2.src}" with "${builderPkg.name}"`),detectedServices&&legacyExperimentalService?.env){let perServiceEnv=(0,import_build_utils3.getServiceUrlEnvVars)({requestedEnv:legacyExperimentalService.env,consumerService:legacyExperimentalService,services:detectedServices,frameworkList:import_frameworks.frameworkList,currentEnv:process.env,deploymentUrl:process.env.VERCEL_URL});for(let[key,value]of Object.entries(perServiceEnv))key in process.env||(setBuildEnv(key,value),output.debug(`Injected service URL env var: ${key}=${value}`))}if(service)for(let key of SERVICE_BUILD_IMMUTABLE_ENV_VARS)setBuildEnv(key,void 0);let buildResult,rawBuildResult,runnerContext={requirePath:builderWithPkg.path,buildOptions,cwd:buildWorkPath,expectsPreDeploy:!!preDeployCmd,builderSpan,serviceName:service?.name,env:perBuildEnv},runner=createBuildRunner2?.({ctx:runnerContext,builder,hasDetectedServices:getHasDetectedServices(),builderPath:builderWithPkg.path,hasBuildCallback:!!buildOptions.buildCallback})??new import_build_runner2.InprocessBuildRunner(runnerContext,builder);if(concurrent&&runner instanceof import_build_runner2.InprocessBuildRunner)throw import_diagnostics3.buildDiagnostics.BUILD_CONCURRENT_INPROCESS({entrypoint:buildOptions.entrypoint});liveRunners.add(runner);try{({buildResult,rawBuildResult}=await(0,import_execute_builder.executeBuilder)({builder,buildOptions,span:builderSpan,isFrontendBuilder,hasDetectedServices:getHasDetectedServices(),framework:import_frameworks.frameworkList.find(framework2=>framework2.slug===buildConfig.framework),runner}))}finally{builderSpan.duration!==void 0&&buildDurationsMs.push(builderSpan.duration/1e3);for(let[key,prior]of restoreEnv)prior===void 0?delete process.env[key]:process.env[key]=prior;try{let builderDiagnostics=await runner.diagnostics();if(builderDiagnostics){let prefix=service&&serviceWorkspace&&serviceWorkspace!=="."?serviceWorkspace+"/"+builderPkg.name+"/":"";for(let[key,value]of Object.entries(builderDiagnostics)){let fullKey=prefix+key;if(key.endsWith("package-manifest.json"))try{let data;value.type==="FileBlob"?data=value.data.toString():data=await streamToString(value.toStream());let packageManifest=JSON.parse(data),validationError=(0,import_validate_package_manifest.validatePackageManifest)(packageManifest);if(validationError)output.warn(`Invalid package-manifest.json from ${fullKey}: ${validationError}`);else{let workspace=service&&serviceWorkspace&&serviceWorkspace!=="."?serviceWorkspace:".",root=daemon?(0,import_build_utils3.normalizePath)((0,import_path2.join)(daemon.root,".")):workspace,buildType=packageManifest.buildType??(buildConfig.middleware===!0?"middleware":daemon?"daemon":isApiDir?"api-dir":"app"),entry={ordinal:buildOrdinals.get(build2)??Number.MAX_SAFE_INTEGER,workspace,root,key:(0,import_manifest.getManifestBuildKey)(builderPkg.name,workspace,daemon?.name),diagnosticsValues,manifest:{...packageManifest,buildType},service,builderUse:builderPkg.name},existingIndex=packageManifests.findIndex(m=>m.key===entry.key),existing=existingIndex===-1?void 0:packageManifests[existingIndex];existing?entry.ordinal<existing.ordinal&&(packageManifests[existingIndex]=entry):packageManifests.push(entry)}}catch(e){output.debug(`Failed to parse ${fullKey}: ${e instanceof Error?e.message:String(e)}`)}else diagnostics[fullKey]=value}}}catch(error){output.error("Collecting diagnostics failed"),output.debug(error)}}if(buildResult&&"output"in buildResult&&"runtime"in buildResult.output&&"type"in buildResult.output&&buildResult.output.type==="Lambda"){let lambdaRuntime=buildResult.output.runtime;if((0,import_build_utils3.getDiscontinuedNodeVersions)().some(o=>o.runtime===lambdaRuntime))throw new import_build_utils3.NowBuildError({code:"NODEJS_DISCONTINUED_VERSION",message:`The Runtime "${build2.use}" is using "${lambdaRuntime}", which is discontinued. Please upgrade your Runtime to a more recent version or consult the author for more details.`,link:"https://vercel.link/function-runtimes"})}if("output"in buildResult&&buildResult.output&&((0,import_build_utils3.isBackendBuilder)(build2)||build2.use==="@vercel/python")){let routesJsonPath=(0,import_path2.join)(buildWorkPath,".vercel","routes.json");if((0,import_fs_extra2.existsSync)(routesJsonPath))try{let routesJson=await readJSONFile2(routesJsonPath);if(routesJson&&typeof routesJson=="object"&&"routes"in routesJson&&Array.isArray(routesJson.routes)){let indexLambda="index"in buildResult.output?buildResult.output.index:void 0,convertedRoutes=[],convertedOutputs=indexLambda?{index:indexLambda}:{};for(let route of routesJson.routes){if(typeof route.source!="string")continue;let{src}=(0,import_routing_utils.sourceToRegex)(route.source),newRoute={src,dest:route.source};route.methods&&(newRoute.methods=route.methods),route.source!=="/"&&(indexLambda&&(convertedOutputs[route.source]=indexLambda),convertedRoutes.push(newRoute))}buildResult.routes=[{handle:"filesystem"},...convertedRoutes,{src:"/(.*)",dest:"/"}],indexLambda&&(buildResult.output=convertedOutputs)}}catch(error){output.error(`Failed to read routes.json: ${error}`)}}if(getHasDetectedServices()&&service&&legacyExperimentalService&&"routes"in buildResult&&Array.isArray(buildResult.routes)&&detectedServices&&(buildResult.routes=(0,import_service_route_ownership.scopeRoutesToServiceOwnership)({routes:buildResult.routes,owner:legacyExperimentalService,allServices:detectedServices})),legacyExperimentalService&&(0,import_build_utils3.isQueueBackedService)(legacyExperimentalService)&&"output"in buildResult&&attachQueueServiceTrigger(buildResult.output,legacyExperimentalService),legacyExperimentalService&&(0,import_build_utils3.isScheduleTriggeredService)(legacyExperimentalService)&&!("crons"in buildResult&&buildResult.crons?.length)){let staticSchedules=(0,import_service_schedules.getStaticServiceSchedules)(legacyExperimentalService.schedule);if(typeof legacyExperimentalService.runtime=="string"&&staticSchedules.length>0){let cronEntrypoint=legacyExperimentalService.entrypoint||legacyExperimentalService.builder.src||"index";for(let schedule of staticSchedules)synthesizedServiceCrons.push({ordinal:buildOrdinals.get(build2)??Number.MAX_SAFE_INTEGER,cron:{path:(0,import_build_utils3.getInternalServiceCronPath)(legacyExperimentalService.name,cronEntrypoint,legacyExperimentalService.handlerFunction||"cron"),schedule}})}else throw new import_build_utils3.NowBuildError({code:"CRON_SERVICE_NO_CRONS",message:`Scheduled service "${legacyExperimentalService.name}" did not produce any cron entries. The builder "${builderPkg.name}" may not support scheduled services.`})}let mergedBuildResult=buildResult;if("buildOutputPath"in buildResult){let buildOutputConfigPath=(0,import_path2.join)(buildResult.buildOutputPath,"config.json"),buildOutputConfig=await readJSONFile2(buildOutputConfigPath);if(isCantParseJSONFile(buildOutputConfig))throw buildOutputConfig;if(buildOutputConfig){if(buildResult.framework&&!buildOutputConfig.framework&&(buildOutputConfig.framework=buildResult.framework),!hasExperimentalServicesV1ConfiguredInVercelConfig&&!hasExperimentalServicesV2ConfiguredInVercelConfig){let outputConfigPath=(0,import_path2.join)(outputDir,"config.json"),outputConfig=await readJSONFile2(outputConfigPath);if(isCantParseJSONFile(outputConfig))throw outputConfig;let shouldMergeGeneratedOutputRoutes=!1;hasNonEmptyObject(outputConfig?.experimentalServices)&&!hasNonEmptyObject(buildOutputConfig.experimentalServices)&&(buildOutputConfig.experimentalServices=outputConfig.experimentalServices,shouldMergeGeneratedOutputRoutes=!0),hasNonEmptyObject(outputConfig?.experimentalServicesV2)&&!hasNonEmptyObject(buildOutputConfig.experimentalServicesV2)&&(buildOutputConfig.experimentalServicesV2=outputConfig.experimentalServicesV2,shouldMergeGeneratedOutputRoutes=!0),hasGeneratedServicesConfig(outputConfig)&&!hasGeneratedServicesConfig(buildOutputConfig)&&(buildOutputConfig.services=outputConfig.services,shouldMergeGeneratedOutputRoutes=!0),shouldMergeGeneratedOutputRoutes&&Array.isArray(outputConfig?.routes)&&(buildOutputConfig.routes=prependMissingBuildOutputRoutes(outputConfig.routes,buildOutputConfig.routes),generatedRootRoutes??=outputConfig.routes),(hasNonEmptyObject(buildOutputConfig.experimentalServices)||hasNonEmptyObject(buildOutputConfig.experimentalServicesV2)||hasGeneratedServicesConfig(buildOutputConfig))&&await import_fs_extra2.default.writeJSON(buildOutputConfigPath,buildOutputConfig,{spaces:2})}getHasDetectedServices()&&service&&legacyExperimentalService&&Array.isArray(buildOutputConfig.routes)&&detectedServices&&(buildOutputConfig.routes=(0,import_service_route_ownership.scopeRoutesToServiceOwnership)({routes:buildOutputConfig.routes,owner:legacyExperimentalService,allServices:detectedServices})),mergedBuildResult=buildOutputConfig}}buildResults.set(build2,mergedBuildResult),executedBuilds.push(build2);let buildOutputLength=0;"output"in buildResult&&(buildOutputLength=Array.isArray(buildResult.output)?buildResult.output.length:1);let writeBuildResultPromise=builderSpan.child("vc.builder.writeBuildResult",{buildOutputLength:String(buildOutputLength)}).trace(writeSpan=>writeBuildResult2({repoRootPath,outputDir,buildResult:rawBuildResult,build:build2,builder,builderPkg,vercelConfig:localConfig,standalone,workPath:buildWorkPath,service,nestServiceOutput:isNestedServiceBuild(build2),stripServiceRoutePrefix,span:writeSpan}));if(service&&isNestedServiceBuild(build2)){let override=await writeBuildResultPromise;override&&serviceFileOverrides.set(build2,override)}else ops.push(writeBuildResultPromise.then(override=>{override&&overrides.push({ordinal:buildOrdinals.get(build2)??Number.MAX_SAFE_INTEGER,override})},err=>err))}catch(err){let buildJsonBuild=buildsJsonBuilds.get(build2);throw buildJsonBuild&&(buildJsonBuild.error=toEnumerableError2(err)),err}finally{ops.push((0,import_build_utils3.download)(diagnostics,(0,import_path2.join)(outputDir,"diagnostics")).then(()=>{},err=>err))}},sortedBuilds=(0,import_execute_builder.sortBuildsForExecution)(buildsToRun);for(let build2 of sortedBuilds)buildOrdinals.has(build2)||buildOrdinals.set(build2,buildOrdinals.size);let concurrency=createBuildRunner2&&canBuildInSubprocess2?(0,import_build_utils3.resolveBuildConcurrency)():1,isEligible=build2=>{let bp=typeof build2.src=="string"?buildersWithPkgs.get(build2.use):void 0;return!!bp&&!!canBuildInSubprocess2&&canBuildInSubprocess2({hasDetectedServices:getHasDetectedServices(),builderPath:bp.path})},forceSingleChain=!hasExperimentalServicesV1ConfiguredInVercelConfig&&!hasExperimentalServicesV2ConfiguredInVercelConfig,getServiceBuildContext=build2=>{let service=getHasDetectedServices()&&typeof build2.src=="string"?serviceByBuilder.get(build2):void 0;if(!service)return;let serviceWorkspace=(0,import_build_utils3.isExperimentalService)(service)?service.workspace:service.root,serviceDir=serviceWorkspace&&serviceWorkspace!=="."?(0,import_path2.join)(workPath,serviceWorkspace):workPath,toolchain=getBuildToolchain(build2,service);return{service,serviceDir,toolchain}};buildConcurrency=concurrency;let buildersStart=performance.now();try{let preinstalledBuilds=concurrency>1&&!forceSingleChain?await installSharedWorkspaces(sortedBuilds.filter(isEligible),getServiceBuildContext):new Set,uvWorkspaceBuilds={independent:new Set,lockedByFirst:new Set};if(concurrency>1&&!forceSingleChain)try{uvWorkspaceBuilds=await(0,import_uv_workspace_builds.planUvWorkspaceBuilds)({candidates:getUvWorkspaceCandidates(sortedBuilds.filter(isEligible),getServiceBuildContext),repoRootPath})}catch(error){output.debug(`Building uv workspace services in order: ${error instanceof Error?error.message:String(error)}`)}await(0,import_build_concurrency.runBuildsWithConcurrency)({builds:sortedBuilds,concurrency,isEligible,forceSingleChain,resolveScope:async build2=>{let context=getServiceBuildContext(build2);if(!context){let key="no-service-context";return{outerKey:key,innerKey:`${key}:${build2.use}:${String(build2.src)}`,siblingsSkipInstall:!1}}let{service,serviceDir,toolchain}=context,customInstall=!!service.installCommand?.trim(),installRoot=await(0,import_build_concurrency.resolveInstallScopeRoot)({toolchain,serviceDir,ceilingDir:repoRootPath});return uvWorkspaceBuilds.independent.has(build2)||uvWorkspaceBuilds.lockedByFirst.has(build2)?{outerKey:`${toolchain}:${installRoot}`,innerKey:`uv-workspace:${installRoot}`,siblingsSkipInstall:!0,preinstalled:uvWorkspaceBuilds.independent.has(build2)}:{outerKey:`${toolchain}:${installRoot}`,innerKey:(0,import_build_concurrency.getInstallScopeKey)({toolchain,installDirectory:serviceDir,installCommand:service.installCommand}),siblingsSkipInstall:toolchain==="node"&&!customInstall,preinstalled:preinstalledBuilds.has(build2)}},runBuild:(build2,concurrent)=>buildOne(build2,concurrent),log:message=>output.log(message),reportSecondaryError:(err,build2)=>{output.error(`Build failed for "${build2.src}": ${err instanceof Error?err.message:String(err)}`)}})}finally{buildersWallMs+=performance.now()-buildersStart}},flushOps=async()=>{let errors=await Promise.all(ops.splice(0));for(let error of errors)if(error)throw error},normalizeBuilderSrc=src=>typeof src=="string"?(0,import_build_utils3.normalizePath)(src).replace(/^\.\//,""):void 0,getBuilderIdentity=build2=>{let normalizedSrc=normalizeBuilderSrc(build2.src);if(!normalizedSrc)return;let buildTarget=build2.config?.buildTarget;return typeof buildTarget=="string"?`${build2.use}:${normalizedSrc}#${buildTarget}`:`${build2.use}:${normalizedSrc}`},getAlreadyExecutedBuild=candidate=>{let candidateIdentity=getBuilderIdentity(candidate);if(candidateIdentity)return executedBuilds.find(build2=>!build2.config?.daemon&&!scheduleServiceBuilds.has(build2)&&getBuilderIdentity(build2)===candidateIdentity)},appendExperimentalServicesV1Routes=services=>{let serviceRoutes=(0,import_service_topology.generateServicesRoutes)(services);zeroConfigRoutes=(0,import_routing_utils.appendRoutesToPhase)({routes:zeroConfigRoutes,newRoutes:serviceRoutes.hostRewrites.length?serviceRoutes.hostRewrites:null,phase:null});let serviceRewriteRoutes=nestExperimentalServicesV2Output?[]:[...serviceRoutes.rewrites,...serviceRoutes.workers,...serviceRoutes.crons];zeroConfigRoutes.push(...(0,import_routing_utils.appendRoutesToPhase)({routes:[],newRoutes:serviceRewriteRoutes,phase:"filesystem"})),nestExperimentalServicesV2Output||(zeroConfigRoutes.push(...serviceRoutes.defaults),zeroConfigFallbackRoutes.push(...serviceRoutes.fallbacks))},sortBuildResultsByOrdinal=()=>{let orderedResults=Array.from(buildResults.entries()).sort(([a],[b])=>(buildOrdinals.get(a)??Number.MAX_SAFE_INTEGER)-(buildOrdinals.get(b)??Number.MAX_SAFE_INTEGER));buildResults.clear();for(let[build2,result]of orderedResults)buildResults.set(build2,result)};try{if(await runBuilders(builds),await flushOps(),sortBuildResultsByOrdinal(),!hasExperimentalServicesV1ConfiguredInVercelConfig&&!hasExperimentalServicesV2ConfiguredInVercelConfig){let generatedConfigPath=(0,import_path2.join)(outputDir,"config.json"),generatedConfig=await readJSONFile2(generatedConfigPath);if(isCantParseJSONFile(generatedConfig))throw generatedConfig;let defaultGeneratedOutputDir=(0,import_path2.join)(workPath,import_write_build_result3.OUTPUT_DIR),generatedConfigs=[generatedConfig];if((0,import_path2.resolve)(outputDir)!==(0,import_path2.resolve)(defaultGeneratedOutputDir)){let defaultGeneratedConfig=await readJSONFile2((0,import_path2.join)(defaultGeneratedOutputDir,"config.json"));if(isCantParseJSONFile(defaultGeneratedConfig))throw defaultGeneratedConfig;generatedConfigs.push(defaultGeneratedConfig)}let generatedServicesConfig=getGeneratedServicesConfig([...generatedConfigs,...buildResults.values()]),generatedExperimentalServicesV1Config=getGeneratedExperimentalServicesV1Config([...generatedConfigs,...buildResults.values()]);if(generatedServicesConfig||generatedExperimentalServicesV1Config){generatedServicesConfig&&(nestExperimentalServicesV2Output=!0),detectedExperimentalServicesV1Config=generatedExperimentalServicesV1Config,detectedExperimentalServicesV2Config=generatedServicesConfig;let generatedRootRoutesConfig=generatedServicesConfig?generatedConfigs.find(config2=>(hasGeneratedServicesConfig(config2)||hasNonEmptyObject(config2?.experimentalServicesV2))&&Array.isArray(config2?.routes)):void 0;generatedRootRoutesConfig?.routes&&(generatedRootRoutes??=generatedRootRoutesConfig.routes);let generatedBuilders=await span.child("vc.detectGeneratedServices").trace(()=>(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,{...localConfig,reservedServiceFiles,...generatedServicesConfig?{services:generatedServicesConfig,experimentalServicesV2:void 0}:{experimentalServicesV2:void 0,experimentalServices:generatedExperimentalServicesV1Config},projectSettings,ignoreBuildScript:!0,featHandleMiss:!0,workPath}));if(generatedBuilders.errors&&generatedBuilders.errors.length>0)throw generatedBuilders.errors[0];for(let w of generatedBuilders.warnings)output.warn(w.message,null,w.link,w.action||"Learn More");if(detectedResolvedServices=generatedBuilders.services,setServicesContext(detectedResolvedServices),!detectedResolvedServices||detectedResolvedServices.length===0?(detectedResolvedServices=void 0,detectedServices=void 0):(detectedServices=detectedResolvedServices.filter(import_build_utils3.isExperimentalService),detectedServices.length>0&&appendExperimentalServicesV1Routes(detectedServices)),detectedServices&&detectedServices.length>0&&generatedBuilders.useImplicitEnvInjection){let serviceUrlEnvVars=(0,import_build_utils3.getExperimentalServiceUrlEnvVars)({services:detectedServices,frameworkList:import_frameworks.frameworkList,currentEnv:process.env,deploymentUrl:process.env.VERCEL_URL});for(let[key,value]of Object.entries(serviceUrlEnvVars))process.env[key]=value,output.debug(`Injected service URL env var: ${key}=${value}`)}let buildsToRun=[],seenBuildsToRun=new Set,recordedServices2=[];for(let service of detectedResolvedServices||[]){let alreadyExecutedBuild=getAlreadyExecutedBuild(service.builder);if(alreadyExecutedBuild){if(generatedServicesConfig){output.warn(getGeneratedServiceAlreadyBuiltWarning(service));continue}serviceByBuilder.set(alreadyExecutedBuild,service),recordedServices2.push(service);continue}let serviceBuilderIdentity=getBuilderIdentity(service.builder);serviceBuilderIdentity&&!seenBuildsToRun.has(serviceBuilderIdentity)&&(serviceByBuilder.set(service.builder,service),seenBuildsToRun.add(serviceBuilderIdentity),buildsToRun.push(service.builder)),recordedServices2.push(service)}servicesToRecord=recordedServices2.length>0?recordedServices2:void 0,buildsToRun.length>0&&await runBuilders(buildsToRun)}}preDeployEntries.sort((a,b)=>a.ordinal-b.ordinal);for(let entry of preDeployEntries)entry.callback?await entry.callback():output.warn(`Service "${entry.service}" has a preDeployCommand but its builder does not support it. The command was not executed.`)}finally{let servicesCount=detectedResolvedServices?.length??0;(servicesCount>0||daemonBuilds.length>0)&&span.setAttributes({"services.count":String(servicesCount),"daemons.count":String(daemonBuilds.length),"build.concurrency":buildConcurrency===void 0?void 0:String(buildConcurrency),"services.build_ms.sum":String(Math.round(buildDurationsMs.reduce((sum,ms)=>sum+ms,0))),"services.build_ms.max":String(Math.round(Math.max(0,...buildDurationsMs))),"services.build_ms.wall":String(Math.round(buildersWallMs))});let settled=await Promise.all(ops.splice(0));for(let err of settled)err&&ops.push(Promise.resolve(err));for(let runner of liveRunners)try{runner.teardown()}catch(err){output.debug(`Runner teardown failed: ${err instanceof Error?err.message:String(err)}`)}}sortBuildResultsByOrdinal(),packageManifests.sort((a,b)=>a.ordinal-b.ordinal),await(0,import_manifest.writeManifests)(packageManifests,diagnostics,ops,outputDir),corepackShimDir&&(0,import_corepack.cleanupCorepack)(corepackShimDir);let collectSpan=span.child("vc.finalizeBuildOutput");await flushOps();let needBuildsJsonOverride=!1,speedInsightsVersion=await(0,import_build_utils3.getInstalledPackageVersion)("@vercel/speed-insights");speedInsightsVersion&&(buildsJson.features={...buildsJson.features??{},speedInsightsVersion},needBuildsJsonOverride=!0);let webAnalyticsVersion=await(0,import_build_utils3.getInstalledPackageVersion)("@vercel/analytics");webAnalyticsVersion&&(buildsJson.features={...buildsJson.features??{},webAnalyticsVersion},needBuildsJsonOverride=!0),needBuildsJsonOverride&&await writeBuildJson(buildsJson,outputDir);let configPath=(0,import_path2.join)(outputDir,"config.json"),existingConfig=await readJSONFile2(configPath);if(isCantParseJSONFile(existingConfig))throw existingConfig;if(existingConfig){if("deploymentId"in existingConfig&&typeof existingConfig.deploymentId=="string"){let deploymentId=existingConfig.deploymentId;if(deploymentId.length>32)throw new import_build_utils3.NowBuildError({code:"INVALID_DEPLOYMENT_ID",message:`The deploymentId "${deploymentId}" must be 32 characters or less. Please choose a shorter deploymentId in your config.`,link:"https://vercel.com/docs/skew-protection#custom-skew-protection-deployment-id"});if(!VALID_DEPLOYMENT_ID_PATTERN.test(deploymentId))throw new import_build_utils3.NowBuildError({code:"INVALID_DEPLOYMENT_ID",message:`The deploymentId "${deploymentId}" contains invalid characters. Only alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (_) are allowed.`,link:"https://vercel.com/docs/skew-protection#custom-skew-protection-deployment-id"})}existingConfig.overrides&&!nestExperimentalServicesV2Output&&overrides.push({ordinal:Number.MAX_SAFE_INTEGER,override:existingConfig.overrides})}let topLevelBuildResults=nestExperimentalServicesV2Output||scheduleServicePlan.services.length>0?new Map(Array.from(buildResults.entries()).filter(([build2])=>!isNestedServiceBuild(build2))):buildResults,builderRoutes=Array.from(topLevelBuildResults.entries()).filter(b=>"routes"in b[1]&&Array.isArray(b[1].routes)).map(b=>{let build2=b[0],buildResult=b[1],entrypoint=build2.src;if(getHasDetectedServices()&&typeof build2.src=="string"){let service=serviceByBuilder.get(build2);service&&(0,import_build_utils3.isExperimentalService)(service)&&service.type==="web"&&typeof service.routePrefix=="string"&&(entrypoint=getServicesMergeEntrypoint(service,build2.src))}return{use:build2.use,entrypoint,routes:buildResult.routes,projectMiddleware:build2.config?.middleware===!0}});zeroConfigRoutes.length&&builderRoutes.unshift({use:"@vercel/zero-config-routes",entrypoint:"/",routes:zeroConfigRoutes});let mergedRoutes=(0,import_routing_utils.mergeRoutes)({userRoutes:routesResult.routes,builds:builderRoutes});zeroConfigFallbackRoutes.length&&(mergedRoutes=(0,import_routing_utils.appendRoutesToPhase)({routes:mergedRoutes,newRoutes:zeroConfigFallbackRoutes,phase:"filesystem"}));let mergedImages=mergeImages(localConfig.images,topLevelBuildResults.values()),orderedServiceCrons=synthesizedServiceCrons.slice().sort((a,b)=>a.ordinal-b.ordinal).map(entry=>entry.cron),mergedCrons=mergeCrons([...localConfig.crons||[],...orderedServiceCrons],buildResults.values()),mergedWildcard=mergeWildcard(topLevelBuildResults.values()),mergedDeploymentId=await mergeDeploymentId(existingConfig?.deploymentId,topLevelBuildResults.values(),workPath,projectSettings.outputDirectory,readJSONFile2,isCantParseJSONFile);if(mergedDeploymentId){if(mergedDeploymentId.length>32)throw new import_build_utils3.NowBuildError({code:"INVALID_DEPLOYMENT_ID",message:`The deploymentId "${mergedDeploymentId}" must be 32 characters or less. Please choose a shorter deploymentId in your config.`,link:"https://vercel.com/docs/skew-protection#custom-skew-protection-deployment-id"});if(!VALID_DEPLOYMENT_ID_PATTERN.test(mergedDeploymentId))throw new import_build_utils3.NowBuildError({code:"INVALID_DEPLOYMENT_ID",message:`The deploymentId "${mergedDeploymentId}" contains invalid characters. Only alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (_) are allowed.`,link:"https://vercel.com/docs/skew-protection#custom-skew-protection-deployment-id"})}let topLevelBuildResultOverrides=Array.from(topLevelBuildResults.values()).map(result=>"overrides"in result?result.overrides:void 0).filter(value=>!!value),orderedOverrides=overrides.slice().sort((a,b)=>a.ordinal-b.ordinal).map(entry=>entry.override),mergedOverrides=overrides.length>0||topLevelBuildResultOverrides.length>0?Object.assign({},...orderedOverrides,...topLevelBuildResultOverrides):void 0,framework=topLevelBuildResults.size>0?await getFramework(workPath,topLevelBuildResults):void 0,rootRoutesToAppend=Array.from(topLevelBuildResults.values()).some(result=>(hasGeneratedServicesConfig(result)||"experimentalServicesV2"in result&&hasNonEmptyObject(result.experimentalServicesV2))&&"routes"in result&&Array.isArray(result.routes))?void 0:generatedRootRoutes??existingConfig?.routes,explicitRootRoutes=appendBuildOutputRouteTables(routesResult.routes,rootRoutesToAppend),mergedRoutesWithGeneratedServicesV2Routes=nestExperimentalServicesV2Output?appendBuildOutputRouteTables(mergedRoutes,rootRoutesToAppend):mergedRoutes,resolvedSchedules=mergeSchedules(authoredSchedules.flatMap(schedule=>(0,import_build_utils3.isServiceSchedule)(schedule)?scheduleServicePlan.targets.get(schedule.name)??[]:schedule),buildResults,build2=>isNestedServiceBuild(build2)?serviceByBuilder.get(build2)?.name:void 0);await writeDaemonDescriptors(outputDir,daemons,buildResults),checkScheduleServiceNames();let recordedServices=[...servicesToRecord??[],...scheduleServicePlan.services.map(({builder,...service})=>({...service,builder:{src:builder.src,use:builder.use}}))],outputServices={...detectedExperimentalServicesV2Config,...Object.fromEntries(scheduleServicePlan.services.map(service=>[service.name,{root:service.root,runtime:service.runtime,entrypoint:service.entrypoint}]))},config={version:3,daemons:Object.fromEntries(Object.keys(daemons??{}).map(name=>[name,{}])),routes:mergedRoutesWithGeneratedServicesV2Routes??explicitRootRoutes,afterCacheBypass:mergeAfterCacheBypass(topLevelBuildResults.values())??existingConfig?.afterCacheBypass,images:mergedImages,wildcard:mergedWildcard,overrides:mergedOverrides,framework,crons:mergedCrons,...resolvedSchedules.length>0&&{schedules:(0,import_build_utils3.toScheduleRecord)(resolvedSchedules)},...detectedExperimentalServicesV1Config&&Object.keys(detectedExperimentalServicesV1Config).length>0&&{experimentalServices:detectedExperimentalServicesV1Config},...Object.keys(outputServices).length>0&&{experimentalServicesV2:outputServices},...(!detectedExperimentalServicesV1Config||scheduleServicePlan.services.length>0)&&recordedServices.length>0&&{services:recordedServices},...mergedDeploymentId&&{deploymentId:mergedDeploymentId}};return await import_fs_extra2.default.writeJSON((0,import_path2.join)(outputDir,"config.json"),config,{spaces:2}),(nestExperimentalServicesV2Output||scheduleServicePlan.services.length>0)&&await writeServiceConfigs(outputDir,buildResults,new Map([...serviceByBuilder].filter(([build2])=>isNestedServiceBuild(build2))),serviceFileOverrides,detectedExperimentalServicesV2Config,readJSONFile2,isCantParseJSONFile),await writeFlagsJSON(buildResults.values(),outputDir,output),await span.child("vc.frameworkCrossCheck").trace(async s=>{let detectedFrameworks=await detectedFrameworksPromise,executedBuilders=Array.from(buildResults.keys()),usedBuilders=executedBuilders.map(b=>b.use).filter(use=>!!use),mismatchResult=(0,import_framework_detection.warnIfFrameworkMismatch)({configuredFramework:projectSettings.framework,detectedFrameworks,usedBuilders,usedFrameworks:executedBuilders.map(b=>b.config?.framework)},output);s.setAttributes({result:mismatchResult,configuredFramework:projectSettings.framework??void 0,detectedFrameworks:detectedFrameworks.join(",")||void 0,usedBuilders:usedBuilders.join(",")||void 0})}),await span.child("vc.validateBuildOutput").trace(async s=>{let outputProblems=await(0,import_validate_build_output.validateBuildOutput)(outputDir,output);s.setAttributes({problemCount:String(outputProblems.length),problems:outputProblems.map(p=>`${p.severity}: ${p.message}`).join("; ")||void 0}),(0,import_validate_build_output.reportBuildOutputProblems)(outputProblems,output)}),collectSpan.stop(),{buildDuration:buildStamp()}}async function getFramework(cwd,buildResults){let detectedFramework=await(0,import_fs_detectors.detectFrameworkRecord)({fs:new import_fs_detectors.LocalFileSystemDetector(cwd),frameworkList:import_frameworks.frameworkList});if(!detectedFramework){for(let buildResult of buildResults.values())if("framework"in buildResult&&buildResult.framework)return{slug:buildResult.framework.slug,version:buildResult.framework.version};return}if(detectedFramework.useRuntime){for(let[build2,buildResult]of buildResults.entries())if("framework"in buildResult&&build2.use===detectedFramework.useRuntime.use)return buildResult.framework?{slug:buildResult.framework.slug,version:buildResult.framework.version}:void 0}if(detectedFramework.slug){if(detectedFramework.detectedVersion&&import_semver.default.valid(detectedFramework.detectedVersion))return{slug:detectedFramework.slug,version:detectedFramework.detectedVersion};let frameworkVersion=(0,import_fs_detectors.detectFrameworkVersion)(detectedFramework);if(frameworkVersion)return{slug:detectedFramework.slug,version:frameworkVersion}}}function expandBuild(files,build2){if(!build2.use)throw new import_build_utils3.NowBuildError({code:"invalid_build_specification",message:"Field `use` is missing in build specification",link:"https://vercel.com/docs/concepts/projects/project-configuration#builds",action:"View Documentation"});let src=(0,import_path2.normalize)(build2.src||"**").split(import_path2.sep).join("/");if(src==="."||src==="./")throw new import_build_utils3.NowBuildError({code:"invalid_build_specification",message:"A build `src` path resolves to an empty string",link:"https://vercel.com/docs/concepts/projects/project-configuration#builds",action:"View Documentation"});return src[0]==="/"&&(src=src.substring(1)),files.filter(name=>name===src||(0,import_minimatch.default)(name,src,{dot:!0})).map(m=>({...build2,src:m}))}function mergeImages(images,buildResults){for(let result of buildResults)"images"in result&&result.images&&(images=Object.assign({},images,result.images));return images}function mergeCrons(crons=[],buildResults){for(let result of buildResults)"crons"in result&&result.crons&&(crons=crons.concat(result.crons));return crons}function mergeSchedules(authored,buildResults,getNestedServiceName){let schedules=[...authored],sources=new Map,claim=(schedule,source)=>{let{name}=schedule,existing=sources.get(name);if(existing)throw new import_build_utils3.NowBuildError({code:"SCHEDULE_NAME_CONFLICT",message:`Schedule "${name}" is defined by both ${existing} and ${source}. Schedule names must be unique within a deployment.`});sources.set(name,source)};for(let schedule of schedules)claim(schedule,"vercel.json");for(let[build2,result]of buildResults){if(!("schedules"in result)||result.schedules===void 0)continue;let source=`the build output of "${build2.use}"${build2.src?` for "${build2.src}"`:""}`,invalid=message=>new import_build_utils3.NowBuildError({code:"INVALID_BUILD_OUTPUT_SCHEDULE",message:`Schedules in ${source} ${message}`});if(!isPlainObject(result.schedules))throw invalid("must be an object keyed by schedule name.");let entries=Object.entries(result.schedules);if(entries.length===0)continue;let service=getNestedServiceName(build2);for(let[key,schedule]of entries){if(!isPlainObject(schedule))throw invalid("must be objects.");if("entrypoint"in schedule)throw invalid("cannot use `entrypoint`. Build Output schedules must target a `function`, `path`, or `topic`.");if("name"in schedule)throw invalid(`cannot set \`name\` on "${key}". The schedule's key is its name.`);if(service!==void 0){if(!("function"in schedule))throw invalid(`must target a \`function\`. "${key}" is in the build output of service "${service}", so it can only invoke that service's functions.`);if("service"in schedule)throw invalid(`cannot set \`service\` on "${key}". It is set to "${service}", the service that built it.`)}let named={name:key,...schedule,...service!==void 0&&{service}};claim(named,source),schedules.push(named)}}return schedules}function isPlainObject(value){return value!=null&&typeof value=="object"&&!Array.isArray(value)}function mergeWildcard(buildResults){let wildcard;for(let result of buildResults)"wildcard"in result&&result.wildcard&&(wildcard||(wildcard=[]),wildcard.push(...result.wildcard));return wildcard}function mergeAfterCacheBypass(buildResults){let rules;for(let result of buildResults)"afterCacheBypass"in result&&result.afterCacheBypass&&(rules=(rules??[]).concat(result.afterCacheBypass));return rules}function appendBuildOutputRouteTables(...routeTables){let routes=[];for(let routeTable of routeTables){if(!Array.isArray(routeTable)||routeTable.length===0)continue;let phase=null,phaseRoutes=[],flushPhase=()=>{phaseRoutes.length!==0&&(routes=(0,import_routing_utils.appendRoutesToPhase)({routes,newRoutes:phaseRoutes,phase}),phaseRoutes=[])};for(let route of routeTable)(0,import_routing_utils.isHandler)(route)?(flushPhase(),phase=route.handle):phaseRoutes.push(route);flushPhase()}return routes.length>0?routes:void 0}function appendServiceRouteTables(configuredRoutes,...builderRouteTables){if(!configuredRoutes.some(route=>!(0,import_routing_utils.isHandler)(route)&&route.transforms?.some(transform=>transform.type==="request.path")))return appendBuildOutputRouteTables(configuredRoutes,...builderRouteTables);let builderRoutesWithRequestPathFallbacks=builderRouteTables.map(routes=>routes?.map(route=>(0,import_routing_utils.isHandler)(route)||route.dest===void 0||!route.transforms||!route.transforms.some(transform=>transform.type==="request.path")?route:{...route,transforms:route.transforms.map(transform=>transform.type==="request.path"?{...transform,fallback:!0}:transform)}));return appendBuildOutputRouteTables(configuredRoutes,...builderRoutesWithRequestPathFallbacks)}function prependMissingBuildOutputRoutes(routesToPrepend,existingRoutes){if(!Array.isArray(routesToPrepend)||routesToPrepend.length===0)return existingRoutes;let existingRouteKeys=new Set((existingRoutes??[]).map(route=>JSON.stringify(route))),missingRoutes=routesToPrepend.filter(route=>!existingRouteKeys.has(JSON.stringify(route)));return appendBuildOutputRouteTables(missingRoutes,existingRoutes)}async function writeServiceConfigs(outputDir,buildResults,serviceByBuilder,serviceFileOverrides,experimentalServicesV2,readJSONFile2,isCantParseJSONFile){let serviceResults=new Map,serviceOverrides=new Map;for(let[build2,buildResult]of buildResults){let service=serviceByBuilder.get(build2);if(!service)continue;let results=serviceResults.get(service.name)||[];results.push(buildResult),serviceResults.set(service.name,results);let fileOverrides=serviceFileOverrides.get(build2);if(fileOverrides){let overrides=serviceOverrides.get(service.name)||[];overrides.push(fileOverrides),serviceOverrides.set(service.name,overrides)}}await Promise.all(Array.from(serviceResults.entries()).map(async([serviceName,results])=>{let configPath=(0,import_path2.join)(outputDir,"services",serviceName,"config.json"),existingConfig=await readJSONFile2(configPath);if(isCantParseJSONFile(existingConfig))throw existingConfig;let routes=results.flatMap(result=>"routes"in result&&Array.isArray(result.routes)?result.routes:[]),existingRoutes=routes.length>0?void 0:existingConfig?.routes,existingCrons=results.some(result=>"crons"in result&&result.crons?.length)?void 0:existingConfig?.crons,configuredRoutes=experimentalServicesV2?.[serviceName]?getExperimentalServicesV2Routes(experimentalServicesV2[serviceName]):[],overrides=[...results.map(result=>"overrides"in result?result.overrides:void 0).filter(value=>!!value),...serviceOverrides.get(serviceName)||[]],framework=results.find(result=>"framework"in result&&!!result.framework)?.framework,mergedRoutes=appendServiceRouteTables(configuredRoutes,routes,existingRoutes),config={...existingConfig,version:3,routes:mergedRoutes,afterCacheBypass:mergeAfterCacheBypass(results)??existingConfig?.afterCacheBypass,images:mergeImages(existingConfig?.images,results),wildcard:mergeWildcard(results)||existingConfig?.wildcard,overrides:overrides.length>0?Object.assign({},existingConfig?.overrides,...overrides):existingConfig?.overrides,framework:framework||existingConfig?.framework,crons:mergeCrons(existingCrons,results),services:void 0,experimentalServices:void 0,experimentalServicesV2:void 0};await import_fs_extra2.default.writeJSON(configPath,config,{spaces:2})}))}function getExperimentalServicesV2Routes(serviceConfig){let routesResult=(0,import_routing_utils.getTransformedRoutes)({routes:serviceConfig.routes,cleanUrls:serviceConfig.cleanUrls,trailingSlash:serviceConfig.trailingSlash,headers:serviceConfig.headers,redirects:serviceConfig.redirects,rewrites:serviceConfig.rewrites});if(routesResult.error)throw routesResult.error;return routesResult.routes??[]}function getGeneratedExperimentalServicesV1Config(buildResults){for(let result of buildResults)if(result&&"experimentalServices"in result&&hasNonEmptyObject(result.experimentalServices))return result.experimentalServices}function hasGeneratedServicesConfig(result){return result!=null&&"services"in result&&hasNonEmptyObject(result.services)}function getGeneratedServicesConfig(buildResults){for(let result of buildResults){if(hasGeneratedServicesConfig(result))return result.services;if(result&&"experimentalServicesV2"in result&&hasNonEmptyObject(result.experimentalServicesV2))return result.experimentalServicesV2}}async function mergeDeploymentId(existingDeploymentId,buildResults,workPath,outputDirectory,readJSONFile2,isCantParseJSONFile){if(existingDeploymentId)return existingDeploymentId;for(let result of buildResults)if("deploymentId"in result&&result.deploymentId)return result.deploymentId;let nextOutputDirs=new Set([outputDirectory,".next"].filter(dir=>!!dir));for(let nextOutputDir of nextOutputDirs)try{let routesManifestPath=(0,import_path2.join)(workPath,nextOutputDir,"routes-manifest.json");if(await import_fs_extra2.default.pathExists(routesManifestPath)){let routesManifest=await readJSONFile2(routesManifestPath);if(routesManifest&&!isCantParseJSONFile(routesManifest)&&routesManifest.deploymentId)return routesManifest.deploymentId}}catch{}}async function writeFlagsJSON(buildResults,outputDir,output){let flagsFilePath=(0,import_path2.join)(outputDir,"flags.json"),hasFlags=!0,flags=await import_fs_extra2.default.readJSON(flagsFilePath).catch(error=>{if(error.code==="ENOENT")return hasFlags=!1,{definitions:{}};throw error});for(let result of buildResults)if(!(!("flags"in result)||!result.flags||!result.flags.definitions))for(let[key,definition]of Object.entries(result.flags.definitions)){if(result.flags.definitions[key]){output.warn(`The flag "${key}" was found multiple times. Only its first occurrence will be considered.`);continue}hasFlags=!0,flags.definitions[key]=definition}hasFlags&&await import_fs_extra2.default.writeJSON(flagsFilePath,flags,{spaces:2})}function createApiDirFrameworkDetector(detectAllFrameworks2){let cache=new Map;return{detect(builderUse,workPath){let cacheKey=`${builderUse}:${workPath}`,cached=cache.get(cacheKey);return cached||(cached=detectApiDirFramework(builderUse,workPath,detectAllFrameworks2),cache.set(cacheKey,cached)),cached}}}async function detectApiDirFramework(builderUse,workPath,detectAllFrameworks2){let runtimeFrameworks=import_fs_detectors.builderToFrameworks.get(builderUse)??[];if(runtimeFrameworks.length===0)return;let detectedSlugs=await detectAllFrameworks2(workPath,runtimeFrameworks).catch(()=>[]);return detectedSlugs.length===1?detectedSlugs[0]:void 0}async function writeDaemonDescriptors(outputDir,daemons,buildResults){let namePattern=new RegExp(import_build_utils3.DAEMON_NAME_PATTERN),descriptors=new Map;for(let[build2,result]of buildResults){let returned="output"in result&&"daemons"in result?result.daemons:void 0;for(let[name,descriptor]of Object.entries(returned??{})){if(name!==build2.config?.daemon?.name||!namePattern.test(name))throw new Error(`Builder "${build2.use}" returned an unexpected daemon descriptor "${name}".`);descriptors.set(name,descriptor)}}for(let name of Object.keys(daemons??{})){let descriptor=descriptors.get(name);if(!descriptor)throw new import_build_utils3.NowBuildError({code:"MISSING_DAEMON_OUTPUT",message:`Failed to build daemon "${name}": its build returned no daemon descriptor.`});await import_fs_extra2.default.outputJSON((0,import_path2.join)(outputDir,"daemons",name,".vc-config.json"),descriptor,{spaces:2})}}async function writeBuildJson(buildsJson,outputDir){await import_fs_extra2.default.writeJSON((0,import_path2.join)(outputDir,"builds.json"),buildsJson,{spaces:2})}function getBuildToolchain(build2,service){return service?.runtime??["python","go","ruby","rust","container"].find(t=>build2.use.startsWith(`@vercel/${t}`))??"node"}function normalizeServiceRoutePrefix(routePrefix){let prefix=routePrefix.startsWith("/")?routePrefix:`/${routePrefix}`;return prefix!=="/"&&prefix.endsWith("/")&&(prefix=prefix.slice(0,-1)),prefix}function getServicesMergeEntrypoint(service,buildSrc){let routePrefix=typeof service.routePrefix=="string"?service.routePrefix:"/",normalized=normalizeServiceRoutePrefix(routePrefix);return`svc:${String(1e4-normalized.length).padStart(5,"0")}:${normalized}:${service.name}:${buildSrc}`}function attachQueueServiceTrigger(buildOutput,service){let topics=(0,import_build_utils3.getServiceQueueTopicConfigs)(service),consumer=(0,import_build_utils3.sanitizeConsumerName)((0,import_build_utils3.getInternalServiceFunctionPath)(service.name));if(service.builder.use!=="@vercel/python"&&topics.length>1)throw import_diagnostics3.buildDiagnostics.BUILD_WORKER_MULTIPLE_TOPICS({name:service.name,topics:topics.length});for(let topicConfig of topics){let trigger={type:"queue/v2beta",topic:topicConfig.topic,consumer};if(topicConfig.retryAfterSeconds!==void 0&&(trigger.retryAfterSeconds=topicConfig.retryAfterSeconds),topicConfig.initialDelaySeconds!==void 0&&(trigger.initialDelaySeconds=topicConfig.initialDelaySeconds),(0,import_write_build_result3.isLambda)(buildOutput))appendTrigger(buildOutput,trigger);else for(let output of Object.values(buildOutput))(0,import_write_build_result3.isLambda)(output)&&appendTrigger(output,trigger)}}function triggerMatches(trigger,existingTrigger){return trigger.type==="schedule/v1beta"?trigger.type===existingTrigger.type:trigger.type===existingTrigger.type&&trigger.topic===existingTrigger.topic&&trigger.consumer===existingTrigger.consumer}function appendTrigger(lambda,trigger){let existingTriggers=Array.isArray(lambda.experimentalTriggers)?lambda.experimentalTriggers:[];existingTriggers.some(existing=>triggerMatches(trigger,existing))||(lambda.experimentalTriggers=[...existingTriggers,trigger])}async function streamToString(stream){let chunks=[];for await(let chunk of stream){let buffer=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);chunks.push(Uint8Array.from(buffer))}return Buffer.concat(chunks).toString("utf-8")}}});var require_dist6=__commonJS({"../cli-builder-integration/dist/index.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),src_exports={};__export(src_exports,{BuildRunner:()=>import_build_runner2.BuildRunner,InprocessBuildRunner:()=>import_build_runner2.InprocessBuildRunner,doBuild:()=>import_do_build.doBuild,executeBuilder:()=>import_execute_builder.executeBuilder,sortBuildsForExecution:()=>import_execute_builder.sortBuildsForExecution});module.exports=__toCommonJS2(src_exports);var import_build_runner2=require_build_runner(),import_execute_builder=require_execute_builder(),import_do_build=require_do_build()}});var import_chalk=__toESM(require_source(),1),import_dotenv=__toESM(require_main(),1),import_fs_extra=__toESM(require_lib(),1),import_build_utils2=__toESM(require_build_utils(),1);import{dirname,join as join2,relative,resolve}from"path";import{readdirSync,statSync}from"fs";var import_cli_builder_integration=__toESM(require_dist6(),1);var import_build_utils=__toESM(require_build_utils(),1),import_build_runner=__toESM(require_build_runner(),1);import{fork}from"node:child_process";import{readFileSync,unlinkSync}from"node:fs";import{join}from"node:path";function toError(error){return error instanceof Error?error:Object.assign(new Error,error)}function mergeWorkerMeta(target,workerMeta){for(let[key,value]of Object.entries(workerMeta)){let existing=target[key];if(existing instanceof Set&&value instanceof Set)for(let entry of value)existing.add(entry);else existing===!0&&typeof value!="object"||(target[key]=value)}}function canBuildInSubprocess({hasDetectedServices,builderPath}){return hasDetectedServices&&!!builderPath}function rehydrateFile(obj){if(obj.type==="FileBlob"){let blob=Object.assign(Object.create(import_build_utils.FileBlob.prototype),obj);if(obj.dataPath){blob.data=readFileSync(obj.dataPath);try{unlinkSync(obj.dataPath)}catch{}delete blob.dataPath}return blob}return obj.type==="FileRef"?Object.assign(Object.create(import_build_utils.FileRef.prototype),obj):Object.assign(Object.create(import_build_utils.FileFsRef.prototype),obj)}function rehydrateFiles(files){if(files)for(let name of Object.keys(files))files[name]=rehydrateFile(files[name])}function rehydrateDiagnostics(diagnostics){let result={};for(let[name,file]of Object.entries(diagnostics))result[name]=rehydrateFile(file);return result}function rehydrateOutput(output,seen){if(!output||typeof output!="object"||seen.has(output))return;seen.add(output);let obj=output;if(obj.type==="Lambda")rehydrateFiles(obj.files),Object.setPrototypeOf(obj,import_build_utils.Lambda.prototype);else if(obj.type==="EdgeFunction")rehydrateFiles(obj.files);else if(obj.type==="Prerender")obj.lambda&&rehydrateOutput(obj.lambda,seen),obj.fallback&&rehydrateOutput(obj.fallback,seen);else if(obj.type==="FileFsRef"||obj.type==="FileBlob"||obj.type==="FileRef"){let rehydrated=rehydrateFile(obj);Object.assign(obj,rehydrated),Object.setPrototypeOf(obj,Object.getPrototypeOf(rehydrated))}}function rehydrateResult(result,outputVersion){let output=(result&&"resultVersion"in result?result.result:result).output;if(!output)return;let seen=new Set;if(outputVersion===3)rehydrateOutput(output,seen);else for(let value of Object.values(output))rehydrateOutput(value,seen)}function createServiceLinePrefixer(serviceName,dest){let tag=`[vc:service:${serviceName}] `,pending="";return{onData(chunk){pending+=chunk;let newlineIndex=pending.lastIndexOf(`
7
+ import{fetchDeploymentBuildEnv,isPlainPath,resolvePerDirectoryLinkRoot}from"../../chunks/chunk-3JP2EUHQ.js";import{createErrorReporter,import_write_build_result,require_detect_builders_with_services,require_get_files,require_service_schedules,require_write_build_result,writeBuildResult}from"../../chunks/chunk-3UR42KVA.js";import{importBuilders,import_import_builders,preloadVltBuilderImports}from"../../chunks/chunk-FFOUIGIX.js";import"../../chunks/chunk-4CACOKMS.js";import{require_dist as require_dist4}from"../../chunks/chunk-DMZLFZBX.js";import{require_constants,require_entrypoint,validateConfig}from"../../chunks/chunk-A7E3EGDM.js";import{toDiagnostic}from"../../chunks/chunk-UECFEOOH.js";import{require_ajv}from"../../chunks/chunk-5CVEW3HD.js";import"../../chunks/chunk-MCRKBVZA.js";import{pullCommandLogic}from"../../chunks/chunk-AIAS6KAV.js";import{readProjectSettings}from"../../chunks/chunk-ZEXRYJPK.js";import{compileVercelConfig,findSourceVercelConfigFile,require_main}from"../../chunks/chunk-B7VPXDY2.js";import{require_semver}from"../../chunks/chunk-BPUANOGW.js";import{readJSONFile}from"../../chunks/chunk-5VI33HDO.js";import"../../chunks/chunk-V6Y6UK6B.js";import"../../chunks/chunk-3LNBGHWC.js";import"../../chunks/chunk-M32HBBPK.js";import"../../chunks/chunk-BLNGQEOB.js";import{stamp_default}from"../../chunks/chunk-A2RZZQEP.js";import"../../chunks/chunk-Q7D7RGXM.js";import{require_dist as require_dist3}from"../../chunks/chunk-AMOI3EAW.js";import{require_minimatch}from"../../chunks/chunk-REJLEESP.js";import{require_dist as require_dist2}from"../../chunks/chunk-ISSNEDG5.js";import"../../chunks/chunk-P3MT7Z74.js";import"../../chunks/chunk-DLNT37B7.js";import{require_dist,require_frameworks}from"../../chunks/chunk-ZKNEIE44.js";import"../../chunks/chunk-KR4DMT3I.js";import{applyDeprecatedTargetFlag,parseTarget}from"../../chunks/chunk-HAGBKLAS.js";import"../../chunks/chunk-2DNOJRZY.js";import"../../chunks/chunk-BQXFIDDA.js";import"../../chunks/chunk-EKZCZAUD.js";import"../../chunks/chunk-7YKFF6CE.js";import"../../chunks/chunk-3UZE566G.js";import"../../chunks/chunk-SZO73QV5.js";import"../../chunks/chunk-TAAWMNNL.js";import"../../chunks/chunk-25565AGS.js";import"../../chunks/chunk-PVASGBEF.js";import{ensureLink}from"../../chunks/chunk-N54TQNDY.js";import{printProjectNotFoundError}from"../../chunks/chunk-W6GX7PJ4.js";import"../../chunks/chunk-NBTFAXL4.js";import"../../chunks/chunk-TJUZVODP.js";import"../../chunks/chunk-GD7AV7BO.js";import{getRenamedOption}from"../../chunks/chunk-YAODBCTH.js";import"../../chunks/chunk-Y2FVJ7YO.js";import{buildCommand}from"../../chunks/chunk-PY4WWD6Z.js";import"../../chunks/chunk-BPIGFKNN.js";import{toEnumerableError}from"../../chunks/chunk-FSKZU5GL.js";import{help}from"../../chunks/chunk-7KCRYDGK.js";import{remoteText}from"../../chunks/chunk-GLIQ4KNY.js";import"../../chunks/chunk-3G3FQYMW.js";import{detectExplicitScope}from"../../chunks/chunk-UUI3ETQT.js";import{TelemetryClient}from"../../chunks/chunk-KDCODXVL.js";import"../../chunks/chunk-NWGBDBZI.js";import{AGENT_REASON,AGENT_STATUS,buildCommandWithGlobalFlags,writeAgentError}from"../../chunks/chunk-SWYNL72F.js";import"../../chunks/chunk-DTUEHPME.js";import{DEFAULT_VERCEL_CONFIG_FILENAME,VERCEL_DIR,getLinkedProject,getProjectLink,require_dist2 as require_dist5,require_lib,resolveProjectCwd}from"../../chunks/chunk-5HEF6CPE.js";import"../../chunks/chunk-M7FED5YP.js";import"../../chunks/chunk-4HR3I3ML.js";import"../../chunks/chunk-DJZBJC2A.js";import"../../chunks/chunk-LUX4PBJL.js";import{ua_default}from"../../chunks/chunk-MTZYPCZ7.js";import"../../chunks/chunk-OPORM35X.js";import"../../chunks/chunk-D6REP5QQ.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-MY4MONOH.js";import"../../chunks/chunk-7HLAWGY2.js";import"../../chunks/chunk-MXTC4ZAQ.js";import{isArgumentError,parseArguments}from"../../chunks/chunk-LYL26S3N.js";import"../../chunks/chunk-2VBFQZ72.js";import"../../chunks/chunk-6GKP6VUF.js";import"../../chunks/chunk-4NTBYNFR.js";import"../../chunks/chunk-4SAVH3H7.js";import{CantParseJSONFile}from"../../chunks/chunk-GOI2VVI7.js";import{getCommandName,getCommandNamePlain,require_lib as require_lib2}from"../../chunks/chunk-B4KA3ZH2.js";import{pkg_default}from"../../chunks/chunk-BOJDM3O7.js";import{cliErrorFromUnknown,defineDiagnostics,dist_exports,emoji,init_dist,output_manager_default,prependEmoji,recordCliError}from"../../chunks/chunk-AP6DZGTK.js";import"../../chunks/chunk-BLUPZPAS.js";import"../../chunks/chunk-AW33SRYY.js";import{require_build_utils}from"../../chunks/chunk-5MDNVAE6.js";import"../../chunks/chunk-OCR5CRTH.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-SCV7XEEO.js";import"../../chunks/chunk-MCYG7CCE.js";import"../../chunks/chunk-YHPPP3SF.js";import"../../chunks/chunk-24SIHFEW.js";import{getFlagsSpecification,quoteArg}from"../../chunks/chunk-CFJBDBYH.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-BULSRTQE.js";import{__commonJS,__require,__toCommonJS,__toESM}from"../../chunks/chunk-BZENIQ7N.js";var require_build_runner=__commonJS({"../cli-builder-integration/dist/build-runner.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),build_runner_exports={};__export(build_runner_exports,{BuildRunner:()=>BuildRunner3,InprocessBuildRunner:()=>InprocessBuildRunner2});module.exports=__toCommonJS2(build_runner_exports);var BuildRunner3=class{constructor(ctx){this.ctx=ctx}},InprocessBuildRunner2=class extends BuildRunner3{constructor(ctx,builder){super(ctx),this.builder=builder}async build(){return await this.builder.build(this.ctx.buildOptions)}async diagnostics(){return await this.ctx.builderSpan.child("vc.builder.diagnostics").trace(async()=>await this.builder.diagnostics?.(this.ctx.buildOptions))}teardown(){}}}});var require_sort_builders=__commonJS({"../builder-orchestration/dist/sort-builders.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),sort_builders_exports={};__export(sort_builders_exports,{sortBuilders:()=>sortBuilders});module.exports=__toCommonJS2(sort_builders_exports);var import_frameworks=require_frameworks();function sortBuilders(builds){let frameworkRuntimeSet=new Set(import_frameworks.frameworkList.map(f=>f.useRuntime?.use||"@vercel/static-build"));frameworkRuntimeSet.delete("@vercel/go"),frameworkRuntimeSet.delete("@vercel/python"),frameworkRuntimeSet.delete("@vercel/ruby"),frameworkRuntimeSet.delete("@vercel/rust");let toNumber=build2=>build2.use==="@vercel/go"||build2.use==="@vercel/python"||build2.use==="@vercel/ruby"||build2.use==="@vercel/rust"?1:frameworkRuntimeSet.has(build2.use)?0:2;return builds.sort((build1,build2)=>toNumber(build1)-toNumber(build2))}}});var require_execute_builder=__commonJS({"../cli-builder-integration/dist/execute-builder.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),execute_builder_exports={};__export(execute_builder_exports,{executeBuilder:()=>executeBuilder2,sortBuildsForExecution:()=>sortBuildsForExecution2});module.exports=__toCommonJS2(execute_builder_exports);var import_sort_builders=require_sort_builders(),import_build_runner2=require_build_runner();async function executeBuilder2({builder,buildOptions,span,isFrontendBuilder,hasDetectedServices,framework,runner}){let buildRunner=runner??new import_build_runner2.InprocessBuildRunner({requirePath:"",buildOptions,cwd:buildOptions.workPath,expectsPreDeploy:!1,builderSpan:span},builder),rawBuildResult=await span.trace(()=>buildRunner.build()),buildResult=builder.version===-1&&"resultVersion"in rawBuildResult?rawBuildResult.result:rawBuildResult;return!hasDetectedServices&&buildOptions.config.zeroConfig&&isFrontendBuilder&&"output"in buildResult&&!buildResult.routes&&framework&&(buildResult.routes=await getFrameworkRoutes(framework,buildOptions.workPath)),{buildResult,rawBuildResult}}var sortBuildsForExecution2=import_sort_builders.sortBuilders;async function getFrameworkRoutes(framework,dirPrefix){return typeof framework.defaultRoutes=="function"?framework.defaultRoutes(dirPrefix):Array.isArray(framework.defaultRoutes)?framework.defaultRoutes:[]}}});var require_is_outside=__commonJS({"../cli-builder-integration/dist/is-outside.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),is_outside_exports={};__export(is_outside_exports,{isOutside:()=>isOutside});module.exports=__toCommonJS2(is_outside_exports);var import_path2=__require("path");function isOutside(directory,path){let relativePath=(0,import_path2.relative)(directory,path);return(0,import_path2.isAbsolute)(relativePath)||relativePath===".."||relativePath.startsWith(`..${import_path2.sep}`)}}});var require_schedule_services=__commonJS({"../cli-builder-integration/dist/schedule-services.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),schedule_services_exports={};__export(schedule_services_exports,{planScheduleServices:()=>planScheduleServices,rejectScheduleServiceNameConflicts:()=>rejectScheduleServiceNameConflicts});module.exports=__toCommonJS2(schedule_services_exports);var import_node_fs2=__require("node:fs"),import_promises=__require("node:fs/promises"),import_node_path2=__require("node:path"),import_build_utils3=__require("@vercel/build-utils"),import_fs_detectors=require_dist3(),import_entrypoint=require_entrypoint(),import_is_outside=require_is_outside(),EXPERIMENTS={python:{runtime:"Python",env:"VERCEL_EXPERIMENTAL_PYTHON_SCHEDULES",code:"PYTHON_SCHEDULES_NOT_ENABLED"},node:{runtime:"Node.js",env:"VERCEL_EXPERIMENTAL_NODE_SCHEDULES",code:"NODE_SCHEDULES_NOT_ENABLED"}},FUNCTIONS_HINTS={command:"Dockerfile, but schedules run as services and don't use top-level `functions`. Remove it. Per-schedule settings such as `maxDuration` and `regions` aren't available yet.",python:"module, but schedules run as services and don't use top-level `functions`. Remove it, and set `max_duration` and `regions` on `@schedule` instead.",node:"entrypoint, but schedules run as services and don't use top-level `functions`. Remove it, and set `maxDuration` and `regions` in its `export const config` instead."};async function planScheduleServices({schedules,workPath,repoRootPath=workPath,files,functions={}}){let services=[],targets=new Map,sourceFiles=[],fs2=new import_fs_detectors.LocalFileSystemDetector(workPath),projectRoot=await(0,import_promises.realpath)(workPath),repoRoot=await(0,import_promises.realpath)(repoRootPath);for(let schedule of schedules){if(!(0,import_build_utils3.isServiceSchedule)(schedule))continue;let{name,root,entrypoint}=schedule,kind="run"in schedule?"command":schedule.runtime,invalid=message=>new import_build_utils3.NowBuildError({code:"INVALID_SCHEDULE_SERVICE",message:`Can't build schedule "${name}": ${message}`}),experiment=kind==="command"?void 0:EXPERIMENTS[kind];if(experiment&&process.env[experiment.env]!=="1")throw new import_build_utils3.NowBuildError({code:experiment.code,message:`Can't build schedule "${name}": ${experiment.runtime} schedules are experimental. Set the environment variable ${experiment.env}=1 to build them.`});if((0,import_node_path2.isAbsolute)(root))throw invalid(`\`root\` "${root}" must be a relative path.`);let config={root,runtime:"container",entrypoint,functions:{}},{service,error}=kind==="command"?await(0,import_fs_detectors.resolveConfiguredServiceV2)(name,config,fs2):kind==="node"?resolveNodeScheduleService(schedule):resolvePythonScheduleService(schedule,workPath,files);if(!service)throw invalid(error.message);let source=service.builder.src,aboveProject=service.root===".."||service.root.startsWith("../"),notInProject=invalid(`"${source}" isn't in the project files. Check \`root\` and \`entrypoint\`, and that .vercelignore doesn't exclude it.`);if(!aboveProject&&!files.includes(source))throw notInProject;let[realRoot,realSource]=await Promise.all([(0,import_promises.realpath)((0,import_node_path2.join)(workPath,service.root)),(0,import_promises.realpath)((0,import_node_path2.join)(workPath,source))]).catch(()=>{throw notInProject}),boundary=aboveProject?repoRoot:projectRoot;if((0,import_is_outside.isOutside)(boundary,realRoot))throw invalid(aboveProject?`\`root\` "${root}" is outside the repository.`:`\`root\` "${root}" is a symlink to a directory outside the project.`);if((0,import_is_outside.isOutside)(boundary,realSource))throw invalid(aboveProject?`"${source}" is outside the repository.`:`"${source}" is a symlink to a file outside the project.`);if(Object.prototype.hasOwnProperty.call(functions,source))throw invalid(`\`functions["${source}"]\` names its ${FUNCTIONS_HINTS[kind]}`);if(services.push(service),"run"in schedule){let{run,root:_root,entrypoint:_entrypoint,...rest}=schedule;service.builder.config={...service.builder.config,schedulesCommand:{command:run}},targets.set(name,{...rest,service:name,function:name})}sourceFiles.push(source)}return{services,targets,sourceFiles}}function rejectScheduleServiceNameConflicts({services},serviceNames){let names=new Set(serviceNames),conflict=services.find(({name})=>names.has(name));if(conflict)throw new import_build_utils3.NowBuildError({code:"SCHEDULE_SERVICE_NAME_CONFLICT",message:`Schedule "${conflict.name}" runs as a service of the same name, but the build also has a service named "${conflict.name}". Rename the schedule.`})}function resolvePythonScheduleService({name,root,entrypoint},workPath,files){let parsed=(0,import_entrypoint.parsePythonScheduleModule)(entrypoint);if(!parsed)return{error:{message:`"${entrypoint}" isn't a Python module path.`}};let serviceRoot=(0,import_entrypoint.stripTrailingSlash)(import_node_path2.posix.normalize(root)),candidates=parsed.sourceFiles.map(file=>serviceRoot==="."?file:import_node_path2.posix.join(serviceRoot,file)),source=candidates.find(candidate=>serviceRoot===".."||serviceRoot.startsWith("../")?(0,import_node_fs2.existsSync)((0,import_node_path2.join)(workPath,candidate)):files.includes(candidate));return source?{service:createScheduleService({name,root:serviceRoot,runtime:"python",entrypoint:import_node_path2.posix.relative(serviceRoot,source),use:"@vercel/python",config:{schedulesModule:{module:parsed.moduleName}}})}:{error:{message:`module "${entrypoint}" isn't in the project files. Expected ${candidates.map(candidate=>`"${candidate}"`).join(" or ")}. Check \`root\` and \`entrypoint\`, and that .vercelignore doesn't exclude it.`}}}function resolveNodeScheduleService({name,root,entrypoint}){let file=import_node_path2.posix.normalize(entrypoint);return import_node_path2.posix.isAbsolute(file)||file===".."||file.startsWith("../")?{error:{message:`\`entrypoint\` "${entrypoint}" must be a file inside \`root\` "${root}".`}}:{service:createScheduleService({name,root:(0,import_entrypoint.stripTrailingSlash)(import_node_path2.posix.normalize(root)),runtime:"node",entrypoint:file,use:"@vercel/backends",config:{schedulesEntrypoint:!0}})}}function createScheduleService({name,root,runtime,entrypoint,use,config}){return{schema:"experimentalServicesV2",name,root,runtime,entrypoint,builder:{src:root==="."?entrypoint:import_node_path2.posix.join(root,entrypoint),use,config:{zeroConfig:!0,...root!=="."&&{workspace:root},...config}},functions:{}}}}});var require_get_daemon_builders=__commonJS({"../cli-builder-integration/dist/get-daemon-builders.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),get_daemon_builders_exports={};__export(get_daemon_builders_exports,{getDaemonBuilders:()=>getDaemonBuilders,splitDaemonEntrypoints:()=>splitDaemonEntrypoints,validateDaemonImageRepositories:()=>validateDaemonImageRepositories});module.exports=__toCommonJS2(get_daemon_builders_exports);var import_promises=__require("fs/promises"),import_path2=__require("path"),import_build_utils3=__require("@vercel/build-utils"),import_is_outside=require_is_outside();function splitDaemonEntrypoints(daemons){if(daemons!==void 0)return Object.fromEntries(Object.entries(daemons).map(([name,daemon])=>{let{path,buildTarget}=(0,import_build_utils3.splitDockerfileEntrypoint)(daemon.entrypoint);return[name,buildTarget===void 0?daemon:{...daemon,entrypoint:path,buildTarget}]}))}function validateDaemonImageRepositories(daemons){let owners=new Map;for(let name of Object.keys(daemons??{})){let repository=(0,import_build_utils3.getDaemonImageRepository)(name),owner=owners.get(repository);if(owner!==void 0)throw new import_build_utils3.NowBuildError({code:"INVALID_DAEMONS",message:`Can't build daemon "${name}": daemon "${owner}" uses the same image repository "${repository}". Rename one of them.`});owners.set(repository,name)}}async function getDaemonBuilders({workPath,repoRootPath=workPath,daemons,files}){if(daemons===void 0)return[];let root=await(0,import_promises.realpath)(workPath),repoRoot=await(0,import_promises.realpath)(repoRootPath);return Promise.all(Object.entries(daemons).map(async([name,daemon])=>{let source=(0,import_build_utils3.normalizePath)((0,import_path2.join)(daemon.root,daemon.entrypoint)),aboveProject=source.startsWith("../"),invalidSource=reason=>new import_build_utils3.NowBuildError({code:"INVALID_DAEMON_ROOT",message:`Can't build daemon "${name}": "${source}" ${reason}`}),notInProject=invalidSource("isn't in the project files. Check `root` and `entrypoint`, and that .vercelignore doesn't exclude it.");if((0,import_path2.isAbsolute)(daemon.root)||!aboveProject&&!files.includes(source))throw notInProject;let dockerfile=await(0,import_promises.realpath)((0,import_path2.join)(workPath,source)).catch(()=>{throw notInProject});if((0,import_is_outside.isOutside)(aboveProject?repoRoot:root,dockerfile))throw invalidSource(aboveProject?"is outside the repository.":"is a symlink to a file outside the project.");let invalidRoot=reason=>new import_build_utils3.NowBuildError({code:"INVALID_DAEMON_ROOT",message:`Can't build daemon "${name}": \`root\` "${daemon.root}" ${reason}`}),context=await(0,import_promises.realpath)((0,import_path2.join)(workPath,daemon.root)).catch(()=>{});if(!context||!(await(0,import_promises.stat)(context)).isDirectory())throw invalidRoot("isn't a directory.");if((0,import_is_outside.isOutside)(repoRoot,context))throw invalidRoot("is outside the repository.");return{src:source,use:"@vercel/container",config:{daemon:{name,...daemon}}}}))}}});var require_diagnostics=__commonJS({"../cli-builder-integration/dist/diagnostics.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),diagnostics_exports={};__export(diagnostics_exports,{buildDiagnostics:()=>buildDiagnostics});module.exports=__toCommonJS2(diagnostics_exports);var import_nostics2=(init_dist(),__toCommonJS(dist_exports)),buildDiagnostics=(0,import_nostics2.defineDiagnostics)({codes:{BUILD_BUILDER_LOAD_FAILED:{why:p=>`Failed to load Builder "${p.use}"`,fix:"Check that the builder is installed and spelled correctly in your Vercel configuration."},BUILD_CONCURRENT_INPROCESS:{why:p=>`Internal error: build for "${p.entrypoint}" was scheduled concurrently but cannot run in a subprocess`,fix:"This is a Vercel CLI error. Report it at https://vercel.com/help."},BUILD_WORKER_MULTIPLE_TOPICS:{why:p=>`Worker service "${p.name}" has ${p.topics} topics, but multiple topics are only supported for Python workers.`,fix:"Configure one topic per worker service, or use a Python worker for multiple topics."}}})}});var require_build_concurrency=__commonJS({"../cli-builder-integration/dist/build-concurrency.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),build_concurrency_exports={};__export(build_concurrency_exports,{getInstallScopeKey:()=>getInstallScopeKey,groupIntoScopeChains:()=>groupIntoScopeChains,resolveInstallScopeRoot:()=>resolveInstallScopeRoot,runBuildsWithConcurrency:()=>runBuildsWithConcurrency,runWithConcurrency:()=>runWithConcurrency});module.exports=__toCommonJS2(build_concurrency_exports);var import_node_fs2=__require("node:fs"),import_node_path2=__require("node:path"),import_build_utils3=__require("@vercel/build-utils");async function runWithConcurrency(items,limit,fn,onSecondaryError){let queue=[...items],max=Math.max(limit,1),active=0,failed=!1,firstError;if(await new Promise(finish=>{let enqueue=item=>{queue.push(item),pump()},pump=()=>{for(;active<max&&queue.length>0&&!failed;){let item=queue.shift();active++,fn(item,enqueue).then(()=>{active--,pump()},err=>{active--,failed?onSecondaryError?.(err,item):(failed=!0,firstError=err),pump()})}active===0&&finish()};pump()}),failed)throw firstError}function getInstallScopeKey({toolchain,installDirectory,installCommand}){return JSON.stringify([toolchain,(0,import_node_path2.normalize)(installDirectory),typeof installCommand=="string"?["cmd",installCommand.trim()]:"default"])}var NODE_LOCKFILES=["pnpm-lock.yaml","yarn.lock","package-lock.json","npm-shrinkwrap.json","bun.lock","bun.lockb","vlt-lock.json"];async function isUvWorkspaceRoot(pyprojectPath){if(!await fileExists(pyprojectPath))return!1;let pyproject=await(0,import_build_utils3.readConfigFile)(pyprojectPath,{silent:!0});return pyproject===null||pyproject.tool?.uv?.workspace!==void 0}async function isVltWorkspaceRoot(vltJsonPath){if(!await fileExists(vltJsonPath))return!1;try{let vltJson=JSON.parse(await import_node_fs2.promises.readFile(vltJsonPath,"utf8"));return!vltJson||typeof vltJson!="object"||"workspaces"in vltJson}catch{return!0}}async function fileExists(path){try{return await import_node_fs2.promises.stat(path),!0}catch{return!1}}var SERVICE_DIR_TOOLCHAINS=new Set(["go","ruby","rust","container"]);async function resolveInstallScopeRoot({toolchain,serviceDir,ceilingDir}){if(toolchain!=="node"&&toolchain!=="python")return SERVICE_DIR_TOOLCHAINS.has(toolchain)?(0,import_node_path2.normalize)(serviceDir):(0,import_node_path2.normalize)(ceilingDir);let ceiling=(0,import_node_path2.normalize)(ceilingDir),dir=(0,import_node_path2.normalize)(serviceDir);if(dir!==ceiling&&!dir.startsWith(ceiling+import_node_path2.sep))return dir;let nearestLockfileDir,nearestPackageJsonDir,done=!1;for(;!done;){if(toolchain==="node"){if(nearestLockfileDir===void 0){for(let lockfile of NODE_LOCKFILES)if(await fileExists((0,import_node_path2.join)(dir,lockfile))){nearestLockfileDir=dir;break}}if(await fileExists((0,import_node_path2.join)(dir,"pnpm-workspace.yaml"))||await isVltWorkspaceRoot((0,import_node_path2.join)(dir,"vlt.json")))return dir;try{let pkg=JSON.parse(await import_node_fs2.promises.readFile((0,import_node_path2.join)(dir,"package.json"),"utf8"));if(pkg&&typeof pkg=="object"){if("workspaces"in pkg)return dir;nearestPackageJsonDir??=dir}}catch{}}else if(await isUvWorkspaceRoot((0,import_node_path2.join)(dir,"pyproject.toml")))return dir;let parent=(0,import_node_path2.dirname)(dir);done=dir===ceiling||parent===dir,dir=parent}return nearestLockfileDir??nearestPackageJsonDir??(0,import_node_path2.normalize)(serviceDir)}async function runBuildsWithConcurrency({builds,concurrency,isEligible,resolveScope,forceSingleChain,runBuild,log,reportSecondaryError}){if(concurrency<=1){for(let build2 of builds)await runBuild(build2,!1);return}let parallelBuilds=[],sequentialBuilds=[];for(let build2 of builds)(isEligible(build2)?parallelBuilds:sequentialBuilds).push(build2);if(parallelBuilds.length>0){let chains,siblingsOf,scopeCount;if(forceSingleChain)chains=[parallelBuilds],siblingsOf=new Map,scopeCount=1;else{let scopeByBuild=new Map;for(let build2 of parallelBuilds)scopeByBuild.set(build2,await resolveScope(build2));({chains,siblingsOf}=groupIntoScopeChains(parallelBuilds,build2=>scopeByBuild.get(build2))),scopeCount=new Set(Array.from(scopeByBuild.values(),scope=>scope.outerKey)).size}let atOnce=Math.min(concurrency,chains.reduce((sum,chain)=>sum+Math.max(1,siblingsOf.get(chain[0])?.length??0),0));log(`Running ${parallelBuilds.length} builds across ${scopeCount} install scope${scopeCount===1?"":"s"}, up to ${atOnce} at a time (concurrency ${concurrency})`);let abortedRun=!1,activeBuildOfChain=new Map;await runWithConcurrency(chains,concurrency,async(chain,enqueue)=>{for(let build2 of chain){if(abortedRun)return;activeBuildOfChain.set(chain,build2);try{await runBuild(build2,!0)}catch(err){throw abortedRun=!0,err}let siblings=siblingsOf.get(build2);if(siblings)for(let sibling of siblings)enqueue([sibling])}},(err,chain)=>{let build2=activeBuildOfChain.get(chain);build2!==void 0&&reportSecondaryError(err,build2)})}for(let build2 of sequentialBuilds)await runBuild(build2,!1)}function groupIntoScopeChains(items,scopeOf){let groupByOuter=new Map,scopes=new Map;for(let item of items){let scope=scopeOf(item);scopes.set(item,scope);let group=groupByOuter.get(scope.outerKey)??[];group.push(item),groupByOuter.set(scope.outerKey,group)}let chains=[],siblingsOf=new Map;for(let group of groupByOuter.values()){if(group.every(item=>scopes.get(item).preinstalled)){for(let item of group)chains.push([item]);continue}let[leader,...rest]=group,leaderScope=scopes.get(leader);rest.every(item=>{let scope=scopes.get(item);return scope.innerKey===leaderScope.innerKey&&scope.siblingsSkipInstall})&&rest.length>0?(chains.push([leader]),siblingsOf.set(leader,rest)):chains.push(group)}return{chains,siblingsOf}}}});var require_workspace_install_targets=__commonJS({"../cli-builder-integration/dist/workspace-install-targets.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),workspace_install_targets_exports={};__export(workspace_install_targets_exports,{collectWorkspaceInstallTargets:()=>collectWorkspaceInstallTargets});module.exports=__toCommonJS2(workspace_install_targets_exports);var import_path2=__require("path"),import_build_utils3=__require("@vercel/build-utils"),import_fs_detectors=require_dist3();function isWorkspaceInstallTarget(target){return!!(target&&typeof target=="object"&&typeof target.installRoot=="string"&&typeof target.packageJsonPath=="string"&&typeof target.relativePath=="string")}async function collectWorkspaceInstallTargets({builds,existingTargets,repoRootPath,serviceByBuilder,workPath}){let targets=new Map(Array.isArray(existingTargets)?existingTargets.filter(isWorkspaceInstallTarget).map(target=>[target.packageJsonPath,target]):[]),targetPaths=[];for(let build2 of builds){let service=serviceByBuilder.get(build2);if(build2.use.startsWith("@vercel/node")||build2.use.startsWith("@vercel/backends")||service?.runtime==="node")if(service){let serviceRoot=(0,import_build_utils3.isExperimentalService)(service)?service.workspace:service.root;targetPaths.push(serviceRoot&&serviceRoot!=="."?(0,import_path2.join)(workPath,serviceRoot):workPath)}else typeof build2.src=="string"&&targetPaths.push((0,import_path2.join)(workPath,(0,import_path2.dirname)(build2.src)))}let installScopes=new Map;return await Promise.all(targetPaths.map(async targetPath=>{let{cliType,lockfilePath}=await(0,import_build_utils3.scanParentDirs)(targetPath,!1,repoRootPath);if(!lockfilePath||cliType!=="npm"&&cliType!=="pnpm"&&cliType!=="yarn"&&cliType!=="bun")return;let installRoot=(0,import_path2.dirname)(lockfilePath),scope=installScopes.get(installRoot)??{paths:[],type:cliType};scope.paths.push((0,import_path2.relative)(installRoot,targetPath)),installScopes.set(installRoot,scope)})),await Promise.all(Array.from(installScopes,async([installRoot,{paths,type}])=>{let resolved=await(0,import_fs_detectors.resolveWorkspacePackageTargets)({fs:new import_fs_detectors.LocalFileSystemDetector(installRoot),targetPaths:paths,type});if(!resolved){for(let[packageJsonPath,target]of targets)target.installRoot===installRoot&&targets.delete(packageJsonPath);return}for(let target of resolved){let packageJsonPath=(0,import_path2.join)(installRoot,target.packageJsonPath);targets.set(packageJsonPath,{...target,installRoot,packageJsonPath})}})),Array.from(targets.values())}}});var require_shared_workspace_install=__commonJS({"../cli-builder-integration/dist/shared-workspace-install.js"(exports,module){"use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM2=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),shared_workspace_install_exports={};__export(shared_workspace_install_exports,{planSharedWorkspaceInstalls:()=>planSharedWorkspaceInstalls,runSharedWorkspaceInstall:()=>runSharedWorkspaceInstall});module.exports=__toCommonJS2(shared_workspace_install_exports);var import_node_fs2=__require("node:fs"),import_node_path2=__require("node:path"),import_node_stream=__require("node:stream"),import_semver=__toESM2(require_semver()),import_build_utils3=__require("@vercel/build-utils"),import_fs_detectors=require_dist3(),import_build_concurrency=require_build_concurrency(),SHARED_INSTALL_BUILDERS=["@vercel/next","@vercel/backends","@vercel/node","@vercel/static-build"],PRE_INSTALL_PATCHED_FRAMEWORKS=new Set(["nuxtjs","gatsby"]),LAST_LEGACY_NEXT_VERSION="7.0.2";function hasWorkspacesField(rootPackageJson){return!!(rootPackageJson&&typeof rootPackageJson=="object"&&rootPackageJson.workspaces)}var INSTALLS_EVERY_WORKSPACE={async definesWorkspace(_installRoot,rootPackageJson){return hasWorkspacesField(rootPackageJson)},async installsWholeWorkspace(){return!0}},WORKSPACE_STRATEGIES={pnpm:{async definesWorkspace(installRoot){return await readFileOrNull((0,import_node_path2.join)(installRoot,"pnpm-workspace.yaml"))!==null},async installsWholeWorkspace(installRoot,env){let stdout=await captureStdout("pnpm",["config","get","recursive-install"],installRoot,env);return stdout!==null&&["","undefined","true"].includes(stdout)}},npm:{async definesWorkspace(_installRoot,rootPackageJson){return hasWorkspacesField(rootPackageJson)},async installsWholeWorkspace(installRoot,env){let stdout=await captureStdout("npm",["config","list","--json"],installRoot,env);if(stdout===null)return!1;try{let{workspace}=JSON.parse(stdout);return workspace==null||Array.isArray(workspace)&&workspace.length===0}catch{return!1}}},yarn:{...INSTALLS_EVERY_WORKSPACE,async installsWholeWorkspace(installRoot,env){return!await isYarnClassic(installRoot)||!await mentionsYarnFocus(installRoot,env)},async runsServiceScripts({rootPackageJsonPath,servicePackageJsonPaths}){if(!await isYarnClassic((0,import_node_path2.dirname)(rootPackageJsonPath)))return!0;if(!servicePackageJsonPaths.has(rootPackageJsonPath)&&await runsInstallCwdScripts(rootPackageJsonPath))return!1;for(let path of servicePackageJsonPaths)if(path!==rootPackageJsonPath&&await runsInstallCwdScripts(path))return!1;return!0}},bun:INSTALLS_EVERY_WORKSPACE},YARN_FOCUS_SETTING=/^[^#]*--(?:install\.)?focus\b/m;function getYarnRcPaths(cwd,env){let paths=[];for(let dir=cwd;paths.unshift((0,import_node_path2.join)(dir,".yarnrc"),(0,import_node_path2.join)(dir,".yarnrc.yml")),(0,import_node_path2.dirname)(dir)!==dir;dir=(0,import_node_path2.dirname)(dir));process.platform!=="win32"&&paths.push("/etc/yarn/config","/etc/yarnrc");let home=process.platform==="win32"?env.USERPROFILE:env.HOME;return home&&paths.push((0,import_node_path2.join)(home,".config","yarn","config"),(0,import_node_path2.join)(home,".yarn","config"),(0,import_node_path2.join)(home,".yarnrc"),(0,import_node_path2.join)(home,".yarnrc.yml")),env.YARN_CONFIG&&paths.push(env.YARN_CONFIG),paths}async function mentionsYarnFocus(installRoot,env){for(let path of getYarnRcPaths(installRoot,env)){let rc=await readFileOrNull(path);if(rc!==null&&YARN_FOCUS_SETTING.test(rc))return!0}return!1}async function isYarnClassic(installRoot){if((await readFileOrNull((0,import_node_path2.join)(installRoot,"yarn.lock")))?.includes("__metadata:"))return!1;let raw=await readFileOrNull((0,import_node_path2.join)(installRoot,"package.json"));try{let packageManager=JSON.parse(raw??"{}")?.packageManager,major=/^yarn@(\d+)/.exec(String(packageManager??""))?.[1];return major===void 0||Number(major)<2}catch{return!0}}var INSTALL_CWD_SCRIPTS=["prepare","prepublish","preinstall","install","postinstall"];async function runsInstallCwdScripts(packageJsonPath){return await hasScripts(packageJsonPath,INSTALL_CWD_SCRIPTS)||await readFileOrNull((0,import_node_path2.join)((0,import_node_path2.dirname)(packageJsonPath),"binding.gyp"))!==null}async function hasScripts(packageJsonPath,names){let raw=await readFileOrNull(packageJsonPath);if(raw===null)return!0;try{let scripts=JSON.parse(raw)?.scripts;return names.some(name=>typeof scripts?.[name]=="string")}catch{return!0}}function isWorkspaceType(cliType){return cliType in WORKSPACE_STRATEGIES}async function readFileOrNull(path){try{return await import_node_fs2.promises.readFile(path,"utf8")}catch{return null}}async function captureStdout(command,args,cwd,env){let stdout="";try{await(0,import_build_utils3.spawnAsync)(command,args,{cwd,env,timeout:6e4,outputStream:new import_node_stream.Writable({write(chunk,_encoding,callback){stdout+=chunk.toString(),callback()}}),errorStream:new import_node_stream.Writable({write(_chunk,_encoding,callback){callback()}})})}catch{return null}return stdout.trim()}function isBuilder(builderUse,name){return builderUse===name||builderUse.startsWith(`${name}@`)}function canShareInstall(candidate){return candidate.defaultInstall?isBuilder(candidate.builderUse,"@vercel/static-build")?typeof candidate.framework=="string"&&!PRE_INSTALL_PATCHED_FRAMEWORKS.has(candidate.framework):SHARED_INSTALL_BUILDERS.some(name=>isBuilder(candidate.builderUse,name)):!1}async function usesLegacyNext(installDir){let raw=await readFileOrNull((0,import_node_path2.join)(installDir,"package.json"));if(raw===null)return!1;let range;try{let pkg=JSON.parse(raw);range=pkg?.dependencies?.next??pkg?.devDependencies?.next}catch{return!1}return typeof range=="string"&&import_semver.default.validRange(range)!==null&&import_semver.default.intersects(range,`<=${LAST_LEGACY_NEXT_VERSION}`)}async function planSharedWorkspaceInstalls({candidates,repoRootPath,config,meta,projectCreatedAt,workspaceInstallTargets=[],onSkip}){let groups=new Map;for(let candidate of candidates){let installRoot=await(0,import_build_concurrency.resolveInstallScopeRoot)({toolchain:"node",serviceDir:candidate.serviceDir,ceilingDir:repoRootPath}),group=groups.get(installRoot)??[];group.push(candidate),groups.set(installRoot,group)}let installs=[];for(let[installRoot,group]of groups){let install=await planGroup({installRoot,group,repoRootPath,config,meta,projectCreatedAt,targetPaths:new Set(workspaceInstallTargets.filter(target=>target.installRoot&&(0,import_node_path2.normalize)(target.installRoot)===installRoot).map(target=>(0,import_node_path2.normalize)(target.packageJsonPath)))});typeof install=="string"?onSkip?.(installRoot,install):install&&installs.push(install)}return installs}function describeService(candidate,repoRootPath){return`"${(0,import_node_path2.relative)(repoRootPath,candidate.serviceDir)||"."}"`}function getUnsharedInstallReason(candidate,repoRootPath){if(canShareInstall(candidate))return;let service=describeService(candidate,repoRootPath);return candidate.defaultInstall?isBuilder(candidate.builderUse,"@vercel/static-build")?typeof candidate.framework=="string"?`${service} uses ${candidate.framework}, whose build changes package.json before installing`:`${service} has no detected framework`:`${service} is built by ${candidate.builderUse}, which runs its own install`:`${service} has its own install command`}async function planGroup({installRoot,group,repoRootPath,config,meta,projectCreatedAt,targetPaths}){let[first]=group;if(!first||group.length<2)return;for(let candidate of group){let reason=getUnsharedInstallReason(candidate,repoRootPath);if(reason)return reason}if(new Set(group.map(c=>(0,import_node_path2.normalize)(c.serviceDir))).size!==group.length)return"several services build from the same directory";let rootPackageJsonPath=(0,import_node_path2.join)(installRoot,"package.json"),rawRootPackageJson=await readFileOrNull(rootPackageJsonPath),rootPackageJson;try{rootPackageJson=rawRootPackageJson===null?null:JSON.parse(rawRootPackageJson)}catch{rootPackageJson=null}if(rootPackageJson===null)return"the workspace root has no readable package.json";let packageJsonPaths=new Set([rootPackageJsonPath]),servicePackageJsonPaths=new Set,workspaceType;for(let candidate of group){let service=describeService(candidate,repoRootPath);if(isBuilder(candidate.builderUse,"@vercel/next")&&await usesLegacyNext(candidate.installDir))return`${service} uses a legacy Next.js version`;let{cliType,lockfilePath,packageJsonPath}=await(0,import_build_utils3.scanParentDirs)(candidate.installDir,!1,repoRootPath);if(!isWorkspaceType(cliType))return`${service} installs with ${cliType}, which doesn't support a shared install`;if(workspaceType!==void 0&&cliType!==workspaceType)return"the services install with different package managers";if(!lockfilePath||(0,import_node_path2.normalize)((0,import_node_path2.dirname)(lockfilePath))!==installRoot||!packageJsonPath)return`${service} doesn't install from the workspace root's lockfile`;workspaceType=cliType,packageJsonPaths.add((0,import_node_path2.normalize)(packageJsonPath)),servicePackageJsonPaths.add((0,import_node_path2.normalize)(packageJsonPath))}if(!workspaceType)return;let strategy=WORKSPACE_STRATEGIES[workspaceType];if(!await strategy.definesWorkspace(installRoot,rootPackageJson))return`the workspace root doesn't define a ${workspaceType} workspace`;if(strategy.runsServiceScripts&&!await strategy.runsServiceScripts({rootPackageJsonPath,servicePackageJsonPaths}))return`a ${workspaceType} install at the workspace root would run different lifecycle scripts than each service's own install`;let memberDirs=Array.from(packageJsonPaths).filter(path=>path!==rootPackageJsonPath).map(path=>(0,import_node_path2.relative)(installRoot,(0,import_node_path2.dirname)(path)));if(memberDirs.length>0){let members=await(0,import_fs_detectors.resolveWorkspacePackageTargets)({fs:new import_fs_detectors.LocalFileSystemDetector(installRoot),targetPaths:memberDirs,type:workspaceType});if(!members)return"a service is not a member of the workspace";if(workspaceType==="bun"&&members.some(member=>!member.isRoot&&!member.name))return"a service's package has no name"}if(targetPaths.size>0){for(let path of packageJsonPaths)if(!targetPaths.has(path))return"the workspace-scoped install would not cover every service";for(let path of targetPaths)packageJsonPaths.add(path)}for(let candidate of group){let configPath=await findMemberPackageManagerConfig(candidate.installDir,installRoot);if(configPath)return`${describeService(candidate,repoRootPath)} has its own package-manager config (${(0,import_node_path2.relative)(repoRootPath,configPath)})`}let nodeVersion;for(let candidate of group){let candidateVersion=await(0,import_build_utils3.getNodeVersion)(getNodeVersionDir(candidate),void 0,config,meta);if(nodeVersion&&candidateVersion.runtime!==nodeVersion.runtime)return`the services need different Node.js versions (${nodeVersion.range} and ${candidateVersion.range})`;nodeVersion=candidateVersion}let env=await getInstallEnv({installRoot,nodeVersion,projectCreatedAt});return await strategy.installsWholeWorkspace(installRoot,env)?{installRoot,builds:group.map(c=>c.build),env,packageJsonPaths:Array.from(packageJsonPaths)}:`couldn't confirm that a ${workspaceType} install at the workspace root installs every service`}function getNodeVersionDir(candidate){return isBuilder(candidate.builderUse,"@vercel/backends")?candidate.serviceDir:candidate.installDir}var PACKAGE_MANAGER_CONFIG_FILES=[".npmrc",".yarnrc",".yarnrc.yml"];async function findMemberPackageManagerConfig(installDir,installRoot){let dir=(0,import_node_path2.normalize)(installDir);for(;dir.startsWith(installRoot+import_node_path2.sep);){for(let file of PACKAGE_MANAGER_CONFIG_FILES){let path=(0,import_node_path2.join)(dir,file);if(await readFileOrNull(path)!==null)return path}let parent=(0,import_node_path2.dirname)(dir);if(parent===dir)break;dir=parent}}async function getInstallEnv({installRoot,nodeVersion,projectCreatedAt}){let{cliType,lockfileVersion,packageJsonPackageManager,packageJsonDevEngines,turboSupportsCorepackHome}=await(0,import_build_utils3.scanParentDirs)(installRoot,!0);return(0,import_build_utils3.getEnvForPackageManager)({cliType,lockfileVersion,packageJsonPackageManager,packageJsonDevEngines,nodeVersion,env:process.env,turboSupportsCorepackHome,projectCreatedAt})}async function runSharedWorkspaceInstall({install,meta,projectCreatedAt,workspaceInstallTargets=[]}){await(0,import_build_utils3.runNpmInstall)(install.installRoot,[],{env:install.env},{runNpmInstallSet:new Set},projectCreatedAt,void 0,{targets:workspaceInstallTargets});let installed=meta.runNpmInstallSet instanceof Set?meta.runNpmInstallSet:new Set;for(let path of install.packageJsonPaths)installed.add(path);meta.runNpmInstallSet=installed}}});var require_uv_workspace_builds=__commonJS({"../cli-builder-integration/dist/uv-workspace-builds.js"(exports,module){"use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM2=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),uv_workspace_builds_exports={};__export(uv_workspace_builds_exports,{planUvWorkspaceBuilds:()=>planUvWorkspaceBuilds});module.exports=__toCommonJS2(uv_workspace_builds_exports);var import_node_fs2=__require("node:fs"),import_node_path2=__require("node:path"),import_minimatch=__toESM2(require_minimatch()),import_smol_toml=require_dist(),import_build_utils3=__require("@vercel/build-utils"),import_build_concurrency=require_build_concurrency(),INSTALL_SCRIPTS=["vercel-install","now-install","install"],BUILD_SCRIPTS=["vercel-build","now-build","build"],RUNS_UV=/\buv\b/i,PYTHON_MANIFESTS=["pyproject.toml","Pipfile.lock","Pipfile","requirements.frozen.txt","requirements-frozen.txt","requirements.txt","requirements.in",(0,import_node_path2.join)("requirements","prod.txt")];function readPyproject(path){return(0,import_build_utils3.readConfigFile)(path,{silent:!0})}function normalizeName(name){return name.toLowerCase().replace(/[-_.]+/g,"-")}function strings(value){return typeof value=="string"?[value]:Array.isArray(value)?value.flatMap(strings):value&&typeof value=="object"?Object.values(value).flatMap(strings):[]}function hasAnyKey(value,keys){return!value||typeof value!="object"?!1:Object.entries(value).some(([key,nested])=>keys.includes(key)||hasAnyKey(nested,keys))}async function buildsWithoutExtraRequirements(pyproject,serviceDir){let buildSystem=pyproject["build-system"];if((pyproject.tool?.uv?.package??buildSystem!==void 0)===!1)return!0;if(buildSystem?.["backend-path"]!==void 0)return!1;switch(buildSystem?.["build-backend"]){case"uv_build":case"flit_core.buildapi":return!0;case"hatchling.build":{let hatch=pyproject.tool?.hatch;return!hasAnyKey(hatch?.build,["dependencies","hooks"])&&!hasAnyKey(hatch?.metadata,["hooks"])&&!await exists((0,import_node_path2.join)(serviceDir,"hatch.toml"))&&!await exists((0,import_node_path2.join)(serviceDir,"hatch_build.py"))}default:return!1}}function hasDynamicDependencies(pyproject){if(!pyproject)return!0;let dynamic=pyproject.project?.dynamic;return Array.isArray(dynamic)&&dynamic.some(field=>field==="dependencies"||field==="optional-dependencies")}var LOCAL_DIRECT_REFERENCE=/@\s*(?:file:|\.{0,2}[\\/]|[A-Za-z]:[\\/])/;function usesLocalPackages(pyproject){let hasLocalSource=Object.values(pyproject.tool?.uv?.sources??{}).some(entry=>(Array.isArray(entry)?entry:[entry]).some(source=>!!source&&typeof source=="object"&&("workspace"in source||"path"in source||/^file:/i.test(String(source.url??""))))),uv=pyproject.tool?.uv,requirements=strings([pyproject.project?.dependencies,pyproject.project?.["optional-dependencies"],pyproject["dependency-groups"],pyproject["build-system"]?.requires,uv?.["dev-dependencies"],uv?.["override-dependencies"],uv?.["constraint-dependencies"],uv?.["build-constraint-dependencies"],uv?.["extra-build-dependencies"]]);return hasLocalSource||requirements.some(requirement=>LOCAL_DIRECT_REFERENCE.test(requirement))}async function lockSharesLocalPackages(root,serviceDirs){let lock;try{lock=(0,import_smol_toml.parse)(await import_node_fs2.promises.readFile((0,import_node_path2.join)(root,"uv.lock"),"utf8"))}catch{return!0}if(!Array.isArray(lock.package))return!0;let packages=lock.package.filter(pkg=>!!pkg&&typeof pkg=="object"&&typeof pkg.name=="string"),serviceNames=new Set,sharedLocalNames=new Set;for(let pkg of packages){let name=normalizeName(pkg.name);for(let kind of["directory","editable","path","virtual"]){let sourcePath=pkg.source?.[kind];typeof sourcePath=="string"&&(serviceDirs.has((0,import_node_path2.resolve)(root,sourcePath))?serviceNames.add(name):kind!=="virtual"&&sharedLocalNames.add(name))}}for(let pkg of packages){let self=normalizeName(pkg.name),dependencyNames=[pkg.dependencies,pkg["optional-dependencies"],pkg["dev-dependencies"]].flatMap(value=>(Array.isArray(value)?[value]:Object.values(value??{})).flatMap(list=>Array.isArray(list)?list.flatMap(dep=>dep&&typeof dep.name=="string"?[normalizeName(dep.name)]:[]):[]));for(let dependency of dependencyNames)if(sharedLocalNames.has(dependency)||serviceNames.has(dependency)&&dependency!==self)return!0}return!1}function stringList(value){return Array.isArray(value)?value.filter(item=>typeof item=="string"):[]}function isWorkspaceMember(workspace,root,dir){let path=(0,import_node_path2.relative)(root,dir).split(import_node_path2.sep).join("/"),matches=pattern=>(0,import_minimatch.default)(path,pattern.replace(/^\.\//,"").replace(/\/$/,""));return stringList(workspace.members).some(matches)&&!stringList(workspace.exclude).some(matches)}async function exists(path){try{return await import_node_fs2.promises.stat(path),!0}catch{return!1}}function isPythonBuilder(builderUse){return builderUse==="@vercel/python"||builderUse.startsWith("@vercel/python@")}async function installsOwnMember(candidate){if(!candidate.defaultInstall||!isPythonBuilder(candidate.builderUse))return!1;let serviceDir=(0,import_node_path2.normalize)(candidate.serviceDir),dir=(0,import_node_path2.normalize)(candidate.entrypointDir);if(dir!==serviceDir&&!dir.startsWith(serviceDir+import_node_path2.sep))return!1;for(;dir!==serviceDir;){for(let manifest of PYTHON_MANIFESTS)if(await exists((0,import_node_path2.join)(dir,manifest)))return!1;dir=(0,import_node_path2.dirname)(dir)}let pyprojectPath=(0,import_node_path2.join)(serviceDir,"pyproject.toml");if(!await exists(pyprojectPath))return!1;let pyproject=await readPyproject(pyprojectPath);if(!pyproject||typeof pyproject.project?.name!="string"||usesLocalPackages(pyproject)||!await buildsWithoutExtraRequirements(pyproject,serviceDir))return!1;let scripts=pyproject.tool?.vercel?.scripts??{};return INSTALL_SCRIPTS.some(name=>!!scripts[name])?!1:![candidate.buildCommand,...BUILD_SCRIPTS.map(name=>scripts[name])].some(command=>typeof command=="string"&&RUNS_UV.test(command))}async function planUvWorkspaceBuilds({candidates,repoRootPath}){let groups=new Map;for(let candidate of candidates){let root=await(0,import_build_concurrency.resolveInstallScopeRoot)({toolchain:"python",serviceDir:candidate.serviceDir,ceilingDir:repoRootPath}),group=groups.get(root)??[];group.push(candidate),groups.set(root,group)}let independent=new Set,lockedByFirst=new Set;for(let[root,group]of groups){if(group.length<2)continue;let serviceDirs=new Set(group.map(c=>(0,import_node_path2.normalize)(c.serviceDir)));if(serviceDirs.size!==group.length||serviceDirs.has(root))continue;let rootPyproject=await readPyproject((0,import_node_path2.join)(root,"pyproject.toml")),workspace=rootPyproject?.tool?.uv?.workspace;if(!(!rootPyproject||!workspace||usesLocalPackages(rootPyproject)||![...serviceDirs].every(dir=>isWorkspaceMember(workspace,root,dir))||!(await Promise.all(group.map(installsOwnMember))).every(Boolean)))if(await exists((0,import_node_path2.join)(root,"uv.lock"))){if(await lockSharesLocalPackages(root,serviceDirs))continue;for(let candidate of group)independent.add(candidate.build)}else{let pyprojects=await Promise.all([...serviceDirs].map(dir=>readPyproject((0,import_node_path2.join)(dir,"pyproject.toml"))));if([rootPyproject,...pyprojects].some(hasDynamicDependencies))continue;for(let candidate of group)lockedByFirst.add(candidate.build)}}return{independent,lockedByFirst}}}});var require_backend_rewrite_warning=__commonJS({"../cli-builder-integration/dist/backend-rewrite-warning.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),backend_rewrite_warning_exports={};__export(backend_rewrite_warning_exports,{BACKEND_REWRITE_BEHAVIOR_WARNING:()=>BACKEND_REWRITE_BEHAVIOR_WARNING,hasBackendRewriteBehaviorChange:()=>hasBackendRewriteBehaviorChange});module.exports=__toCommonJS2(backend_rewrite_warning_exports);var import_build_utils3=__require("@vercel/build-utils"),BACKEND_REWRITE_BEHAVIOR_WARNING="Internal rewrites in backend framework projects now route requests using the rewritten destination path. This behavior was previously unsupported and may change which application route handles a request. Review your rewrite configuration to ensure this behavior is expected.";function hasInternalPathRewrite(rewrites){return rewrites?.some(rewrite=>typeof rewrite.destination=="string"&&rewrite.destination.startsWith("/"))??!1}function isAffectedFramework(framework){return framework==="go"||framework==="container"||(0,import_build_utils3.isPythonFramework)(framework)||(0,import_build_utils3.isNodeBackendFramework)(framework)}function hasBackendRewriteBehaviorChange({projectRewrites,builders}){return hasInternalPathRewrite(projectRewrites)&&(builders??[]).some(builder=>isAffectedFramework(builder.config?.framework))}}});var require_service_route_ownership=__commonJS({"../cli-builder-integration/dist/service-route-ownership.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),service_route_ownership_exports={};__export(service_route_ownership_exports,{scopeRoutesToServiceOwnership:()=>scopeRoutesToServiceOwnership});module.exports=__toCommonJS2(service_route_ownership_exports);var import_routing_utils=require_dist2();function isWebServiceWithPrefix(service){return service.type==="web"&&typeof service.routePrefix=="string"}function getWebRoutePrefixes(services){let unique=new Set;for(let service of services)isWebServiceWithPrefix(service)&&unique.add((0,import_routing_utils.normalizeRoutePrefix)(service.routePrefix));return Array.from(unique)}function scopeRoutesToServiceOwnership({routes,owner,allServices}){if(!isWebServiceWithPrefix(owner))return routes;let allWebPrefixes=getWebRoutePrefixes(allServices),ownershipGuard=(0,import_routing_utils.getOwnershipGuard)(owner.routePrefix,allWebPrefixes);return ownershipGuard?routes.map(route=>"handle"in route||typeof route.src!="string"?route:{...route,src:(0,import_routing_utils.scopeRouteSourceToOwnership)(route.src,ownershipGuard)}):routes}}});var require_validate_cron_secret=__commonJS({"../cli-builder-integration/dist/validate-cron-secret.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),validate_cron_secret_exports={};__export(validate_cron_secret_exports,{validateCronSecret:()=>validateCronSecret});module.exports=__toCommonJS2(validate_cron_secret_exports);var import_build_utils3=__require("@vercel/build-utils");function validateCronSecret(cronSecret){if(!cronSecret)return null;if(cronSecret!==cronSecret.trim())return new import_build_utils3.NowBuildError({code:"INVALID_CRON_SECRET",message:"The `CRON_SECRET` environment variable contains leading or trailing whitespace, which is not allowed in HTTP header values.",link:"https://vercel.link/securing-cron-jobs",action:"Learn More"});let invalidChars=[];for(let i=0;i<cronSecret.length;i++){let code=cronSecret.charCodeAt(i);code===9||code>=32&&code<=126||invalidChars.push({char:cronSecret[i],index:i,code})}if(invalidChars.length>0){let descriptions=invalidChars.slice(0,3).map(({code,index})=>code<32?`control character (0x${code.toString(16).padStart(2,"0")}) at position ${index}`:code===127?`DEL character at position ${index}`:`non-ASCII character (0x${code.toString(16).padStart(2,"0")}) at position ${index}`),moreCount=invalidChars.length-3,moreText=moreCount>0?`, and ${moreCount} more`:"";return new import_build_utils3.NowBuildError({code:"INVALID_CRON_SECRET",message:`The \`CRON_SECRET\` environment variable contains characters that are not valid in HTTP headers: ${descriptions.join(", ")}${moreText}. Only visible ASCII characters (letters, digits, symbols), spaces, and tabs are allowed.`,link:"https://vercel.link/securing-cron-jobs",action:"Learn More"})}return null}}});var require_workload_root_static_app=__commonJS({"../cli-builder-integration/dist/workload-root-static-app.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),workload_root_static_app_exports={};__export(workload_root_static_app_exports,{omitStaticAppAtWorkloadRoot:()=>omitStaticAppAtWorkloadRoot});module.exports=__toCommonJS2(workload_root_static_app_exports);var import_promises=__require("node:fs/promises"),import_node_path2=__require("node:path"),import_build_utils3=__require("@vercel/build-utils"),import_fs_detectors=require_dist3(),realpathOrSelf=path=>(0,import_promises.realpath)(path).catch(()=>path);function isProjectRoot(outputDirectory){return import_node_path2.posix.normalize(`${outputDirectory}/`)==="./"}async function omitStaticAppAtWorkloadRoot({builds,serviceBuilds,workPath,workloads,outputDirectory,output}){let rootStaticBuilds=builds.filter(build2=>!serviceBuilds.has(build2)&&(0,import_fs_detectors.isOfficialRuntime)("static",build2.use)&&!build2.config?.outputDirectory);if(rootStaticBuilds.length===0||workloads.length===0||typeof outputDirectory=="string"&&isProjectRoot(outputDirectory))return builds;let[projectRoot,...roots]=await Promise.all([realpathOrSelf(workPath),...workloads.map(({root})=>realpathOrSelf((0,import_node_path2.join)(workPath,root)))]),workload=workloads.find((_,i)=>roots[i]===projectRoot);if(!workload)return builds;let rootOf=`"." is the root of ${workload.kind} "${workload.name}"`;if(outputDirectory)throw new import_build_utils3.NowBuildError({code:"EMPTY_OUTPUT_DIRECTORY",message:`Can't publish static files: outputDirectory "${outputDirectory}" is missing or empty, and ${rootOf}. Put the static files in "${outputDirectory}", or remove outputDirectory to deploy without static files.`});return output.log(`Not publishing static files: ${rootOf}. To publish static files, set outputDirectory to a directory that contains only static files.`),builds.filter(build2=>!rootStaticBuilds.includes(build2))}}});var require_validate_package_manifest=__commonJS({"../cli-builder-integration/dist/validate-package-manifest.js"(exports,module){"use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM2=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),validate_package_manifest_exports={};__export(validate_package_manifest_exports,{validatePackageManifest:()=>validatePackageManifest});module.exports=__toCommonJS2(validate_package_manifest_exports);var import_ajv=__toESM2(require_ajv()),import_build_utils3=__require("@vercel/build-utils"),ajv=new import_ajv.default,validate=ajv.compile(import_build_utils3.packageManifestSchema);function validatePackageManifest(data){return validate(data)?null:(validate.errors??[]).map(e=>`${e.dataPath||"(root)"} ${e.message}`).join("; ")}}});var require_framework=__commonJS({"../runtimes/dist/framework.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),framework_exports={};__export(framework_exports,{DETECTION_FRAMEWORKS:()=>DETECTION_FRAMEWORKS,filterFrameworksByRuntime:()=>filterFrameworksByRuntime,frameworksBySlug:()=>frameworksBySlug,getRuntimeFramework:()=>getRuntimeFramework,inferBuilderRuntimeFromFramework:()=>inferBuilderRuntimeFromFramework,inferRuntimeFromFramework:()=>inferRuntimeFromFramework,inferServerRuntimeFromFramework:()=>inferServerRuntimeFromFramework,isBFFFramework:()=>isBFFFramework,isFrontendFramework:()=>isFrontendFramework});module.exports=__toCommonJS2(framework_exports);var import_build_utils3=__require("@vercel/build-utils"),import_frameworks=require_frameworks(),import_constants=require_constants(),frameworksBySlug=new Map(import_frameworks.frameworkList.flatMap(f=>typeof f.slug=="string"?[[f.slug,f]]:[])),DETECTION_FRAMEWORKS=import_frameworks.frameworkList.filter(framework=>!framework.experimental||framework.runtimeFramework);function inferRuntimeFromFramework(framework){if(framework){if(framework in import_constants.RUNTIME_BUILDERS)return framework;if((0,import_build_utils3.isPythonFramework)(framework))return"python";if((0,import_build_utils3.isBackendFramework)(framework))return"node"}}var STATIC_BUILDER_RUNTIMES={hugo:"go",jekyll:"ruby",middleman:"ruby",zola:"rust"};function inferServerRuntimeFromFramework(framework){if(!framework||framework==="services")return;let builder=frameworksBySlug.get(framework)?.useRuntime?.use;if(builder)return import_constants.BUILDER_RUNTIMES[builder]??"node"}function inferBuilderRuntimeFromFramework(framework){if(!framework||framework==="container"||framework==="services")return;let f=frameworksBySlug.get(framework);if(!f)return;let declaredBuilder=f.useRuntime?.use;return declaredBuilder?import_constants.BUILDER_RUNTIMES[declaredBuilder]:STATIC_BUILDER_RUNTIMES[framework]??"node"}function isFrontendFramework(framework){return!!framework&&!inferRuntimeFromFramework(framework)}var BFF_FRAMEWORKS=new Set(["nextjs","nuxtjs","sveltekit","remix","solidstart"]);function isBFFFramework(framework){return!!framework&&BFF_FRAMEWORKS.has(framework)}function filterFrameworksByRuntime(frameworks,runtime){return runtime?frameworks.filter(f=>inferRuntimeFromFramework(f.slug)===runtime):[...frameworks]}function getRuntimeFramework(runtime){if(runtime)return frameworksBySlug.get(runtime)?.runtimeFramework?runtime:void 0}}});var require_manifest=__commonJS({"../cli-builder-integration/dist/manifest.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),manifest_exports={};__export(manifest_exports,{getBuildDiagnosticsFramework:()=>getBuildDiagnosticsFramework,getManifestBuildKey:()=>getManifestBuildKey,writeManifests:()=>writeManifests});module.exports=__toCommonJS2(manifest_exports);var import_path2=__require("path"),import_build_utils3=__require("@vercel/build-utils"),import_framework=require_framework();function getManifestBuildKey(builderUse,workspace,daemonName){return daemonName===void 0?`${builderUse}:${workspace}`:`${builderUse}:daemon:${daemonName}`}async function writeManifests(packageManifests,diagnostics,ops,outputDir){if(packageManifests.length===0)return;let projectManifest={},deployManifestBuilds={},deployManifestServices={};for(let{workspace,root,key,diagnosticsValues,manifest,service,builderUse}of packageManifests){let framework=diagnosticsValues?.framework??manifest.framework;projectManifest[key]={...manifest,workspace,builder:builderUse,framework,serviceName:service?.name,serviceType:service&&(0,import_build_utils3.isExperimentalService)(service)?service.type:void 0,routePrefix:service&&(0,import_build_utils3.isExperimentalService)(service)?service.routePrefix:void 0};let{version:_version,...manifestWithoutVersion}=manifest;if(deployManifestBuilds[key]={...manifestWithoutVersion,framework,root,workspace,builder:builderUse},service){let existing=deployManifestServices[service.name];existing?existing.builds.push(key):deployManifestServices[service.name]={builds:[key],bindings:(0,import_build_utils3.isExperimentalServiceV2)(service)?service.bindings:void 0}}}if(Object.keys(projectManifest).length===0)return;let projectManifestBlob=new import_build_utils3.FileBlob({data:JSON.stringify(projectManifest)});diagnostics["project-manifest.json"]=projectManifestBlob,ops.push((0,import_build_utils3.downloadFile)(projectManifestBlob,(0,import_path2.join)(outputDir,"diagnostics","project-manifest.json")).then(()=>{},err=>err));let deployManifestBlob=new import_build_utils3.FileBlob({data:JSON.stringify({manifestVersion:"2.0",builds:deployManifestBuilds,services:deployManifestServices})});diagnostics["deploy-manifest.json"]=deployManifestBlob,ops.push((0,import_build_utils3.downloadFile)(deployManifestBlob,(0,import_path2.join)(outputDir,"diagnostics","deploy-manifest.json")).then(()=>{},err=>err))}function getBuildDiagnosticsFramework({service,configFramework,detectedFramework}){return service?.framework??(configFramework==="services"?void 0:configFramework)??(0,import_framework.getRuntimeFramework)(service?.runtime)??detectedFramework}}});var require_build_embedding=__commonJS({"../cli-builder-integration/dist/build-embedding.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),build_embedding_exports={};__export(build_embedding_exports,{shouldEmbedFlagsDefinitions:()=>shouldEmbedFlagsDefinitions});module.exports=__toCommonJS2(build_embedding_exports);var import_build_utils3=__require("@vercel/build-utils");function isFlagsEmbedOption(input){return input==="force-on"||input==="force-off"}var SDK_KEY_REGEX=/^vf_(?:server|client)_/;function envHasSdkKey(){for(let value of Object.values(process.env))if(typeof value=="string"&&SDK_KEY_REGEX.test(value))return!0}async function shouldEmbedFlagsDefinitions(cwd,packageJson,vercelFlags){if(process.env.VERCEL_FLAGS_DISABLE_DEFINITION_EMBEDDING==="1")return!1;if(isFlagsEmbedOption(process.env.VERCEL_FLAGS_EMBED_DEFINITIONS))return process.env.VERCEL_FLAGS_EMBED_DEFINITIONS==="force-on";if(vercelFlags?.enabledAt!==void 0||envHasSdkKey())return!0;let hasVercelFlags=await(0,import_build_utils3.isPackageInstalled)("@flags-sdk/vercel",cwd),hasFlagsCore=await(0,import_build_utils3.isPackageInstalled)("@vercel/flags-core",cwd);if(hasVercelFlags||hasFlagsCore)return!0;let dependencies={...packageJson?.dependencies,...packageJson?.devDependencies,...packageJson?.optionalDependencies};return!!(dependencies["@flags-sdk/vercel"]||dependencies["@vercel/flags-core"])}}});var require_validate_build_output=__commonJS({"../cli-builder-integration/dist/validate-build-output.js"(exports,module){"use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM2=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),validate_build_output_exports={};__export(validate_build_output_exports,{reportBuildOutputProblems:()=>reportBuildOutputProblems,validateBuildOutput:()=>validateBuildOutput});module.exports=__toCommonJS2(validate_build_output_exports);var import_fs_extra2=__toESM2(require_lib()),import_path2=__require("path"),import_build_utils3=__require("@vercel/build-utils");function logDebug(message,output){output?.debug(message),(0,import_build_utils3.debug)(message)}async function validateOutputConfig(configPath,label,problems){if(!await import_fs_extra2.default.pathExists(configPath)){problems.push({severity:"error",message:`${label} is missing config.json.`});return}let config;try{config=await import_fs_extra2.default.readJSON(configPath)}catch(err){problems.push({severity:"error",message:`${label} config.json is not valid JSON: ${err instanceof Error?err.message:String(err)}.`});return}config&&config.version!==3&&problems.push({severity:"warning",message:`${label} config.json has unexpected version "${config.version}" (expected 3).`})}async function validateBuildOutput(outputDir,output){let problems=[];logDebug(`Validating build output at "${outputDir}"`,output);try{await validateOutputConfig((0,import_path2.join)(outputDir,"config.json"),"Build output",problems);let servicesDir=(0,import_path2.join)(outputDir,"services"),serviceNames=[];try{serviceNames=(await import_fs_extra2.default.readdir(servicesDir,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch(err){if(err?.code!=="ENOENT")throw err}let[hasFunctions,hasStatic,hasDaemons]=await Promise.all([import_fs_extra2.default.pathExists((0,import_path2.join)(outputDir,"functions")),import_fs_extra2.default.pathExists((0,import_path2.join)(outputDir,"static")),import_fs_extra2.default.pathExists((0,import_path2.join)(outputDir,"daemons"))]),hasServices=serviceNames.length>0;!hasFunctions&&!hasStatic&&!hasServices&&!hasDaemons&&problems.push({severity:"warning",message:'Build output contains no "functions", "static", or "services" directory; the build may not have produced any deployable output.'});for(let name of serviceNames){let serviceDir=(0,import_path2.join)(servicesDir,name),label=`Build output service "${name}"`;await validateOutputConfig((0,import_path2.join)(serviceDir,"config.json"),label,problems);let[svcHasFunctions,svcHasStatic]=await Promise.all([import_fs_extra2.default.pathExists((0,import_path2.join)(serviceDir,"functions")),import_fs_extra2.default.pathExists((0,import_path2.join)(serviceDir,"static"))]);!svcHasFunctions&&!svcHasStatic&&problems.push({severity:"warning",message:`${label} contains no "functions" or "static" directory; the service may not have produced any deployable output.`})}return logDebug(`Build output validation found ${problems.length} problem(s)`+(problems.length?`: ${problems.map(p=>`${p.severity}: ${p.message}`).join("; ")}`:""),output),problems}catch(err){return[{severity:"error",message:`Unexpected error while validating build output: ${err instanceof Error?err.message:String(err)}.`}]}}function reportBuildOutputProblems(problems,output){for(let problem of problems)problem.severity==="error"?output.error(problem.message):output.warn(problem.message)}}});var require_framework_detection=__commonJS({"../cli-builder-integration/dist/framework-detection.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),framework_detection_exports={};__export(framework_detection_exports,{detectAllFrameworks:()=>detectAllFrameworks,detectFirstDeploymentFramework:()=>detectFirstDeploymentFramework,isFirstDeployment:()=>isFirstDeployment,isFrameworkDetectionEnabled:()=>isFrameworkDetectionEnabled,warnIfFrameworkMismatch:()=>warnIfFrameworkMismatch});module.exports=__toCommonJS2(framework_detection_exports);var import_fs_detectors=require_dist3(),import_frameworks=require_frameworks(),import_build_utils3=__require("@vercel/build-utils");function logDebug(message,output){output?.debug(message),(0,import_build_utils3.debug)(message)}function isFrameworkDetectionEnabled(output){let raw=process.env.VERCEL_FRAMEWORK_DETECTION,enabled=raw==="1";return logDebug(`Framework detection: VERCEL_FRAMEWORK_DETECTION=${raw===void 0?"<unset>":JSON.stringify(raw)} -> ${enabled?"enabled":"disabled"}`,output),enabled}function isFirstDeployment(output){let raw=process.env.VERCEL_FIRST_DEPLOYMENT,result=raw==="1";return logDebug(`isFirstDeployment: VERCEL_FIRST_DEPLOYMENT=${raw===void 0?"<unset>":JSON.stringify(raw)} -> ${result}`,output),result}async function detectFirstDeploymentFramework(options){let{workPath,projectSettings,frameworkExplicitlyConfigured,output}=options;if(logDebug(`First deployment: evaluating framework detection (workPath="${workPath}", configuredFramework=${projectSettings.framework?`"${projectSettings.framework}"`:"<none>"})`,output),!isFirstDeployment(output))return logDebug("First deployment: skipping framework detection because this is not a first deployment",output),{status:"skipped"};if(frameworkExplicitlyConfigured||projectSettings.framework)return logDebug(`First deployment: skipping framework detection because a framework is already configured ("${projectSettings.framework}")`,output),{status:"skipped"};logDebug(`First deployment: no framework configured; detecting from source at "${workPath}"`,output);let detected=await(0,import_fs_detectors.detectFrameworkRecord)({fs:new import_fs_detectors.LocalFileSystemDetector(workPath),frameworkList:import_frameworks.frameworkList});if(!detected||!detected.slug)return logDebug("First deployment: no framework detected from source code",output),{status:"not-detected"};let{slug}=detected;return projectSettings.framework=slug,logDebug(`First deployment: detected framework "${slug}"${detected.detectedVersion?` (version ${detected.detectedVersion})`:""}; applied to project settings for this build`,output),{status:"detected",slug,...detected.detectedVersion&&{version:detected.detectedVersion}}}async function detectAllFrameworks(workPath,customFrameworkList,output){logDebug(`Framework cross-check: detecting frameworks at "${workPath}"`,output);let slugs=(await(0,import_fs_detectors.detectFrameworks)({fs:new import_fs_detectors.LocalFileSystemDetector(workPath),frameworkList:customFrameworkList??import_frameworks.frameworkList})).map(f=>f.slug).filter(slug=>!!slug);return logDebug(`Framework cross-check: detected [${slugs.join(", ")||"<none>"}]`,output),slugs}function isHighConfidenceDetection(slug){return import_frameworks.frameworkList.find(f=>f.slug===slug)?.detectionConfidence!=="weak"}function warnIfFrameworkMismatch(options,output){let{configuredFramework,detectedFrameworks,usedBuilders=[],usedFrameworks=[]}=options;if(detectedFrameworks.length===0)return logDebug("Framework cross-check: nothing detected from source; skipping validation",output),"none-detected";let confidentFrameworks=detectedFrameworks.filter(isHighConfidenceDetection);if(configuredFramework)return detectedFrameworks.includes(configuredFramework)?(logDebug(`Framework cross-check: configured framework "${configuredFramework}" matches detected frameworks; no mismatch`,output),"match"):confidentFrameworks.length===0?(logDebug(`Framework cross-check: configured framework "${configuredFramework}" not among detected [${detectedFrameworks.join(", ")}], but all detections are low-confidence; skipping warning`,output),"low-confidence"):(logDebug(`Framework cross-check: configured framework "${configuredFramework}" not among detected [${confidentFrameworks.join(", ")}]; warning`,output),output?.warn(`Your project is configured to use the "${configuredFramework}" framework, but the source code looks like it's for: ${confidentFrameworks.join(", ")}. This may be a misconfiguration.`,null,"https://vercel.com/docs/project-configuration","Learn More"),"configured-mismatch");if(detectedFrameworks.some(slug=>{if(usedFrameworks.includes(slug))return!0;let expectedBuilder=import_frameworks.frameworkList.find(f=>f.slug===slug)?.useRuntime?.use;return expectedBuilder?usedBuilders.some(use=>use===expectedBuilder||use.startsWith(`${expectedBuilder}@`)):!1}))return logDebug(`Framework cross-check: no framework configured, but the build used one of the detected frameworks [${detectedFrameworks.join(", ")}]; no mismatch`,output),"match";let warnableFrameworks=confidentFrameworks.filter(slug=>!!import_frameworks.frameworkList.find(f=>f.slug===slug)?.useRuntime?.use);return warnableFrameworks.length===0?(logDebug(`Framework cross-check: no framework configured and detections [${detectedFrameworks.join(", ")}] are low-confidence or have no dedicated runtime builder; skipping warning`,output),"low-confidence"):(logDebug(`Framework cross-check: no framework configured and the build did not use any of the detected frameworks [${warnableFrameworks.join(", ")}] (used builders: [${usedBuilders.join(", ")||"<none>"}]); warning`,output),output?.warn(`The source code looks like it's for: ${warnableFrameworks.join(", ")}, but no framework is configured for this project and the build did not use ${warnableFrameworks.length===1?"its builder":"their builders"}. Set the framework in your Project Settings if this is unexpected.`,null,"https://vercel.com/docs/project-configuration","Learn More"),"unused-mismatch")}}});var require_runtime=__commonJS({"../runtimes/dist/runtime.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),runtime_exports={};__export(runtime_exports,{getBuilderForRuntime:()=>getBuilderForRuntime,inferRuntime:()=>inferRuntime});module.exports=__toCommonJS2(runtime_exports);var import_constants=require_constants(),import_framework=require_framework();function getBuilderForRuntime(runtime){let builder=import_constants.RUNTIME_BUILDERS[runtime];if(!builder)throw new Error(`Unknown runtime: ${runtime}`);return builder}function inferRuntime(config){if(config.runtime&&config.runtime in import_constants.RUNTIME_BUILDERS)return config.runtime;let frameworkRuntime=(0,import_framework.inferRuntimeFromFramework)(config.framework);if(frameworkRuntime)return frameworkRuntime;if(config.builder){for(let[runtime,builderName]of Object.entries(import_constants.RUNTIME_BUILDERS))if(config.builder===builderName)return runtime}if(config.entrypoint){if(config.entrypoint==="pyproject.toml"||config.entrypoint.endsWith("/pyproject.toml"))return"python";for(let[ext,runtime]of Object.entries(import_constants.ENTRYPOINT_EXTENSIONS))if(config.entrypoint.endsWith(ext))return runtime}}}});var require_monorepo=__commonJS({"../cli-builder-integration/dist/monorepo.js"(exports,module){"use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM2=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),monorepo_exports={};__export(monorepo_exports,{applyServicesMonorepoDefaults:()=>applyServicesMonorepoDefaults,setMonorepoDefaultSettings:()=>setMonorepoDefaultSettings});module.exports=__toCommonJS2(monorepo_exports);var import_path2=__require("path"),import_fs_detectors=require_dist3(),import_runtime=require_runtime(),import_title=__toESM2(require_lib2()),import_fs_extra2=__toESM2(require_lib()),import_build_utils3=__require("@vercel/build-utils");async function setMonorepoDefaultSettings(cwd,workPath,projectSettings,output){let localFileSystem=new import_fs_detectors.LocalFileSystemDetector(cwd),projectName=(0,import_path2.basename)(workPath),relativeToRoot=(0,import_path2.relative)(workPath,cwd),setCommand=(command,value)=>{projectSettings[command]?(0,import_build_utils3.debug)(`Skipping auto-assignment of ${command} as it is already set via project settings or configuration overrides.`):projectSettings[command]=value};try{let result=await(0,import_fs_detectors.getMonorepoDefaultSettings)(projectName,(0,import_path2.relative)(cwd,workPath),relativeToRoot,localFileSystem);if(result===null)return;projectSettings.monorepoManager=result.monorepoManager;let{monorepoManager,...commands}=result;output.log(`Detected ${(0,import_title.default)(monorepoManager)}. Adjusting default settings...`),commands.buildCommand&&setCommand("buildCommand",commands.buildCommand),commands.installCommand&&setCommand("installCommand",commands.installCommand),commands.commandForIgnoringBuildStep&&setCommand("commandForIgnoringBuildStep",commands.commandForIgnoringBuildStep)}catch(error){if(error instanceof import_fs_detectors.MissingBuildPipeline||error instanceof import_fs_detectors.MissingBuildTarget){output.warn(`${error.message} Skipping automatic setting assignment.`);return}throw error}}async function hasVercelBuildScript(serviceRoot){try{return(await import_fs_extra2.default.readJSON((0,import_path2.join)(serviceRoot,"package.json")))?.scripts?.["vercel-build"]!==void 0}catch{return!1}}async function applyServicesMonorepoDefaults(cwd,workPath,services,projectSettings,output){let localFileSystem=new import_fs_detectors.LocalFileSystemDetector(cwd),result,announced=!1;for(let[name,config]of Object.entries(services)){if(config.buildCommand){(0,import_build_utils3.debug)(`Skipping auto-assignment of buildCommand for service "${name}" as it is already set in the services configuration.`);continue}let runtime=(0,import_runtime.inferRuntime)({runtime:config.runtime,framework:config.framework,entrypoint:config.entrypoint});if(runtime!==void 0&&runtime!=="node"){(0,import_build_utils3.debug)(`Skipping monorepo defaults for service "${name}": runtime "${runtime}" does not build via the monorepo task graph.`);continue}let serviceRoot=(0,import_path2.resolve)(workPath,config.root??"."),projectPath=(0,import_path2.relative)(cwd,serviceRoot);if((0,import_path2.isAbsolute)(projectPath)||projectPath===".."||projectPath.startsWith(`..${import_path2.sep}`)){(0,import_build_utils3.debug)(`Skipping monorepo defaults for service "${name}": root "${config.root}" is outside "${cwd}".`);continue}if(await hasVercelBuildScript(serviceRoot)){(0,import_build_utils3.debug)(`Skipping monorepo defaults for service "${name}": a \`vercel-build\` script is defined in its root package.json.`);continue}let posixProjectPath=(0,import_build_utils3.normalizePath)(projectPath),posixRelativeToRoot=(0,import_build_utils3.normalizePath)((0,import_path2.relative)(serviceRoot,cwd)),settings;try{settings=await(0,import_fs_detectors.getMonorepoDefaultSettings)((0,import_path2.basename)(serviceRoot),posixProjectPath||"/",posixRelativeToRoot,localFileSystem)}catch(error){if(error instanceof import_fs_detectors.MissingBuildPipeline){output.warn(`${error.message} Skipping automatic setting assignment.`);break}if(error instanceof import_fs_detectors.MissingBuildTarget){output.warn(`Service "${name}": ${error.message} Skipping automatic setting assignment.`);continue}throw error}if(settings===null)break;projectSettings.monorepoManager=settings.monorepoManager,settings.buildCommand&&(announced||(output.log(`Detected ${(0,import_title.default)(settings.monorepoManager)}. Adjusting default settings...`),announced=!0),(0,import_build_utils3.debug)(`Assigning buildCommand "${settings.buildCommand}" to service "${name}".`),result??={...services},result[name]={...config,buildCommand:settings.buildCommand})}return result??services}}});var require_corepack=__commonJS({"../cli-builder-integration/dist/corepack.js"(exports,module){"use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM2=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),corepack_exports={};__export(corepack_exports,{cleanupCorepack:()=>cleanupCorepack,initCorepack:()=>initCorepack});module.exports=__toCommonJS2(corepack_exports);var import_path2=__require("path"),import_build_utils3=__require("@vercel/build-utils"),import_fs_extra2=__toESM2(require_lib());async function initCorepack({repoRootPath,output,readJSONFile:readJSONFile2,isCantParseJSONFile,warmPackageManager=!1}){if(process.env.ENABLE_EXPERIMENTAL_COREPACK!=="1")return null;let pkg=await readJSONFile2((0,import_path2.join)(repoRootPath,"package.json"));if(isCantParseJSONFile(pkg))output.warn("Warning: Could not enable corepack because package.json is invalid JSON",pkg.meta?.parseErrorLocation??pkg.message);else if(!pkg?.packageManager)output.warn('Warning: Could not enable corepack because package.json is missing "packageManager" property');else{output.log(`Detected ENABLE_EXPERIMENTAL_COREPACK=1 and "${pkg.packageManager}" in package.json`);let corepackRootDir=(0,import_path2.join)(repoRootPath,".vercel","cache","corepack"),corepackHomeDir=(0,import_path2.join)(corepackRootDir,"home"),corepackShimDir=(0,import_path2.join)(corepackRootDir,"shim");await import_fs_extra2.default.mkdirp(corepackHomeDir),await import_fs_extra2.default.mkdirp(corepackShimDir),process.env.COREPACK_HOME=corepackHomeDir,process.env.PATH=`${corepackShimDir}${import_path2.delimiter}${process.env.PATH}`;let pkgManagerName=pkg.packageManager.split("@")[0];if(await(0,import_build_utils3.spawnAsync)("corepack",["enable",pkgManagerName,"--install-directory",corepackShimDir],{prettyCommand:`corepack enable ${pkgManagerName}`}),warmPackageManager)try{await(0,import_build_utils3.spawnAsync)(pkgManagerName,["--version"],{prettyCommand:`${pkgManagerName} --version`,stdio:"pipe"})}catch(err){output.debug(`Failed to pre-download "${pkg.packageManager}" via corepack: ${err instanceof Error?err.message:String(err)}`)}return corepackShimDir}return null}function cleanupCorepack(corepackShimDir){process.env.COREPACK_HOME&&delete process.env.COREPACK_HOME,process.env.PATH&&(process.env.PATH=process.env.PATH.replace(`${corepackShimDir}${import_path2.delimiter}`,""))}}});var require_do_build=__commonJS({"../cli-builder-integration/dist/do-build.js"(exports,module){"use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM2=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),do_build_exports={};__export(do_build_exports,{doBuild:()=>doBuild3,mergeDeploymentId:()=>mergeDeploymentId});module.exports=__toCommonJS2(do_build_exports);var import_fs_extra2=__toESM2(require_lib()),import_minimatch=__toESM2(require_minimatch()),import_path2=__require("path"),import_semver=__toESM2(require_semver()),import_build_utils3=__require("@vercel/build-utils"),import_client=require_dist5(),import_frameworks=require_frameworks(),import_fs_detectors=require_dist3(),import_service_topology=require_dist4(),import_detect_builders_with_services=require_detect_builders_with_services(),import_schedule_services=require_schedule_services(),import_get_daemon_builders=require_get_daemon_builders(),import_routing_utils=require_dist2(),import_write_build_result3=require_write_build_result(),import_build_runner2=require_build_runner(),import_execute_builder=require_execute_builder(),import_diagnostics3=require_diagnostics(),import_build_concurrency=require_build_concurrency(),import_workspace_install_targets=require_workspace_install_targets(),import_shared_workspace_install=require_shared_workspace_install(),import_uv_workspace_builds=require_uv_workspace_builds(),import_backend_rewrite_warning=require_backend_rewrite_warning(),import_service_route_ownership=require_service_route_ownership(),import_service_schedules=require_service_schedules(),import_validate_cron_secret=require_validate_cron_secret(),import_workload_root_static_app=require_workload_root_static_app(),import_validate_package_manifest=require_validate_package_manifest(),import_manifest=require_manifest(),import_build_embedding=require_build_embedding(),import_get_files=require_get_files(),import_validate_build_output=require_validate_build_output(),import_framework_detection=require_framework_detection(),import_monorepo=require_monorepo(),import_corepack=require_corepack();function pickOverrides(config){let overrides={};for(let property of["buildCommand","devCommand","framework","ignoreCommand","installCommand","outputDirectory"])config[property]!==void 0&&(overrides[property==="ignoreCommand"?"commandForIgnoringBuildStep":property]=config[property]);return overrides}var SERVICE_BUILD_IMMUTABLE_ENV_VARS=["VERCEL_IMMUTABLE_STATIC_FILES_ENABLED"];function hasNonEmptyObject(value){return value!=null&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length>0}function getGeneratedServiceAlreadyBuiltWarning(service){let framework=service.framework??"unknown",entrypoint=service.entrypoint??service.builder.src??"unknown";return`Detected already-built service "${service.name}" from lazily generated \`.vercel/output/config.json\` (framework: ${framework}, entrypoint: ${entrypoint}). It will not be treated as a service because its build output already exists at the top level. Configure it in \`vercel.json\` as a \`services\` entry to remove this warning.`}async function doBuild3(request,dependencies){let{project,buildsJson,cwd,outputDir,span,standalone=!1,localConfigPath,cliVersion,userAgent}=request,{output,createBuildRunner:createBuildRunner2,canBuildInSubprocess:canBuildInSubprocess2,importBuilders:importBuilders2,formatResolvedBuilders:formatResolvedBuilders2,writeBuildResult:writeBuildResult2,toEnumerableError:toEnumerableError2,readJSONFile:readJSONFile2,isCantParseJSONFile,validateConfig:validateConfig2,compileVercelConfig:compileVercelConfig2,findSourceVercelConfigFile:findSourceVercelConfigFile2,defaultVercelConfigFilename,startBuildTiming}=dependencies,VALID_DEPLOYMENT_ID_PATTERN=/^[a-zA-Z0-9_-]+$/,workPath=(0,import_path2.join)(cwd,project.settings.rootDirectory||"."),repoRootPath=cwd,sourceConfigFile=await findSourceVercelConfigFile2(workPath),corepackShimDir;if(sourceConfigFile){corepackShimDir=await(0,import_corepack.initCorepack)({repoRootPath,output,readJSONFile:readJSONFile2,isCantParseJSONFile,warmPackageManager:(0,import_build_utils3.resolveBuildConcurrency)()>1});let installDepsSpan=span.child("vc.installDeps"),installRan=!1;try{let installCommand=project.settings.installCommand;typeof installCommand=="string"?installCommand.trim()?(output.log("Running install command before config compilation..."),installRan=await(0,import_build_utils3.runCustomInstallCommand)({destPath:workPath,installCommand,spawnOpts:{env:process.env},projectCreatedAt:project.settings.createdAt})):output.debug("Skipping empty install command"):(output.log("Installing dependencies before config compilation..."),installRan=await(0,import_build_utils3.runNpmInstall)(workPath,[],{env:process.env},void 0,project.settings.createdAt))}finally{installDepsSpan.stop()}if(installRan){let{packageJsonPath}=await(0,import_build_utils3.scanParentDirs)(workPath,!1);packageJsonPath&&(process.env.VERCEL_INSTALL_COMPLETED_PATH=packageJsonPath),process.env.VERCEL_INSTALL_COMPLETED="1"}}let compileResult=await span.child("vc.compileVercelConfig").trace(()=>compileVercelConfig2(workPath)),vercelConfigPath=localConfigPath||compileResult.configPath||(0,import_path2.join)(workPath,"vercel.json"),[pkg,vercelConfig,hasInstrumentation]=await span.child("vc.readConfigInputs").trace(()=>Promise.all([readJSONFile2((0,import_path2.join)(workPath,"package.json")),readJSONFile2(vercelConfigPath),(0,import_fs_detectors.detectInstrumentation)(new import_fs_detectors.LocalFileSystemDetector(workPath))]));if(isCantParseJSONFile(pkg))throw pkg;if(isCantParseJSONFile(vercelConfig))throw vercelConfig;hasInstrumentation&&(output.debug("OpenTelemetry instrumentation detected. Automatic fetch instrumentation will be disabled."),process.env.VERCEL_TRACING_DISABLE_AUTOMATIC_FETCH_INSTRUMENTATION="1"),vercelConfig&&(vercelConfig[import_client.fileNameSymbol]=compileResult.wasCompiled?compileResult.sourceFile||defaultVercelConfigFilename:"vercel.json");let localConfig=vercelConfig||{},validateError=validateConfig2(localConfig);if(validateError)throw validateError;let authoredSchedules=(0,import_build_utils3.getNamedSchedules)(localConfig.schedules),daemonNames=(0,import_build_utils3.getDaemonNames)(localConfig),daemons=(0,import_get_daemon_builders.splitDaemonEntrypoints)(daemonNames.length>0?localConfig.daemons:void 0);if((0,import_get_daemon_builders.validateDaemonImageRepositories)(daemons),localConfig.crons&&localConfig.crons.length>0){let cronSecretError=(0,import_validate_cron_secret.validateCronSecret)(process.env.CRON_SECRET);if(cronSecretError)throw cronSecretError}let projectSettings={...project.settings,...pickOverrides(localConfig)};buildsJson.detectedFramework=await span.child("vc.detectFirstDeploymentFramework",{firstDeployment:String(process.env.VERCEL_FIRST_DEPLOYMENT==="1"),configuredFramework:projectSettings.framework??void 0}).trace(async s=>{let result=await(0,import_framework_detection.detectFirstDeploymentFramework)({workPath,projectSettings,frameworkExplicitlyConfigured:Object.prototype.hasOwnProperty.call(localConfig,"framework"),output});return s.setAttributes({detectionStatus:result.status,detectedFramework:result.slug,detectedFrameworkVersion:result.version}),result});let buildpackCommands={installCommand:projectSettings.installCommand??void 0,buildCommand:projectSettings.buildCommand??void 0};process.env.VERCEL_BUILD_MONOREPO_SUPPORT==="1"&&pkg?.scripts?.["vercel-build"]===void 0&&projectSettings.rootDirectory!==null&&projectSettings.rootDirectory!=="."&&await span.child("vc.setMonorepoDefaultSettings").trace(()=>(0,import_monorepo.setMonorepoDefaultSettings)(cwd,workPath,projectSettings,output)),await span.child("vc.prepareFlagsDefinitions").trace(async s=>{let shouldEmbed=await(0,import_build_embedding.shouldEmbedFlagsDefinitions)(cwd,pkg,projectSettings.vercelFlags);if(s.setAttributes({shouldEmbed:String(shouldEmbed)}),!shouldEmbed)return;let{prepareFlagsDefinitions}=await import("../../chunks/dist-33WTJLVQ.js");await prepareFlagsDefinitions({cwd,env:process.env,userAgentSuffix:userAgent,output})});let files=await span.child("vc.getFiles").trace(async s=>{let result=(await(0,import_get_files.staticFiles)(workPath,{},output)).map(f=>(0,import_build_utils3.normalizePath)((0,import_path2.relative)(workPath,f)));return s.setAttributes({fileCount:String(result.length)}),result}),scheduleServicePlan=await(0,import_schedule_services.planScheduleServices)({schedules:authoredSchedules,workPath,repoRootPath,files,functions:localConfig.functions}),scheduleServiceBuilds=new Set(scheduleServicePlan.services.map(service=>service.builder)),reservedServiceFiles=scheduleServicePlan.sourceFiles,detectedFrameworksPromise=span.child("vc.detectAllFrameworks",{enabled:String((0,import_framework_detection.isFrameworkDetectionEnabled)(output))}).trace(async s=>{if(!(0,import_framework_detection.isFrameworkDetectionEnabled)(output))return[];try{let slugs=await(0,import_framework_detection.detectAllFrameworks)(workPath,void 0,output);return s.setAttributes({detectedFrameworks:slugs.join(",")||void 0,detectedFrameworkCount:String(slugs.length)}),slugs}catch(err){return output.debug(`Framework cross-check detection failed: ${err}`),s.setAttributes({error:err instanceof Error?err.message:String(err)}),[]}}),routesResult=(0,import_routing_utils.getTransformedRoutes)(localConfig);if(routesResult.error)throw routesResult.error;if(localConfig.builds&&localConfig.functions)throw new import_build_utils3.NowBuildError({code:"bad_request",message:"The `functions` property cannot be used in conjunction with the `builds` property. Please remove one of them.",link:"https://vercel.link/functions-and-builds"});let daemonBuilds=await(0,import_get_daemon_builders.getDaemonBuilders)({workPath,repoRootPath,daemons,files}),builds=localConfig.builds||[],zeroConfigRoutes=[],zeroConfigFallbackRoutes=[],detectedServices,detectedResolvedServices,servicesToRecord,hasExperimentalServicesV1ConfiguredInVercelConfig=hasNonEmptyObject(localConfig.experimentalServices),hasExperimentalServicesV2ConfiguredInVercelConfig=hasNonEmptyObject(localConfig.services??localConfig.experimentalServicesV2);hasExperimentalServicesV1ConfiguredInVercelConfig&&output.warn("The `experimentalServices` property is deprecated. Migrate to `services`.");let configuredExperimentalServicesV2=hasExperimentalServicesV2ConfiguredInVercelConfig&&(localConfig.services??localConfig.experimentalServicesV2)?localConfig.services??localConfig.experimentalServicesV2:void 0,nestExperimentalServicesV2Output=hasExperimentalServicesV2ConfiguredInVercelConfig,detectedExperimentalServicesV1Config,detectedExperimentalServicesV2Config=configuredExperimentalServicesV2,monorepoDefaultedServices=new Set,isZeroConfig=!1;if(builds.length>0)output.warn("Due to `builds` existing in your configuration file, the Build and Development Settings defined in your Project Settings will not apply. Learn More: https://vercel.link/unused-build-settings"),builds=builds.flatMap(b=>expandBuild(files,b));else{isZeroConfig=!0;let servicesForDetection=configuredExperimentalServicesV2;if(process.env.VERCEL_BUILD_MONOREPO_SUPPORT==="1"&&configuredExperimentalServicesV2){servicesForDetection=await span.child("vc.applyServicesMonorepoDefaults").trace(()=>(0,import_monorepo.applyServicesMonorepoDefaults)(cwd,workPath,configuredExperimentalServicesV2,projectSettings,output));for(let[name,config2]of Object.entries(servicesForDetection))config2.buildCommand!==configuredExperimentalServicesV2[name]?.buildCommand&&monorepoDefaultedServices.add(name)}let detectedBuilders=await span.child("vc.detectBuilders").trace(()=>(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,{...localConfig,reservedServiceFiles,services:void 0,experimentalServicesV2:servicesForDetection,projectSettings,ignoreBuildScript:!0,featHandleMiss:!0,workPath}));if(detectedBuilders.errors&&detectedBuilders.errors.length>0)throw detectedBuilders.errors[0];for(let w of detectedBuilders.warnings)output.warn(w.message,null,w.link,w.action||"Learn More");detectedBuilders.builders?builds=detectedBuilders.builders:builds=[{src:"**",use:"@vercel/static"}],builds=await(0,import_workload_root_static_app.omitStaticAppAtWorkloadRoot)({builds,serviceBuilds:new Set(detectedBuilders.services?.map(service=>service.builder)),workPath,workloads:[...Object.entries(daemons??{}).map(([name,{root}])=>({kind:"daemon",name,root})),...scheduleServicePlan.services.map(({name,root})=>({kind:"schedule",name,root}))],outputDirectory:projectSettings.outputDirectory,output}),detectedResolvedServices=detectedBuilders.services,servicesToRecord=detectedResolvedServices,detectedServices=detectedBuilders.services?.filter(import_build_utils3.isExperimentalService);let autoDetectedV2Config=detectedBuilders.experimentalServicesV2;if(!hasExperimentalServicesV2ConfiguredInVercelConfig&&autoDetectedV2Config&&(nestExperimentalServicesV2Output=!0,detectedExperimentalServicesV2Config=autoDetectedV2Config),detectedBuilders.useImplicitEnvInjection&&detectedServices&&detectedServices.length>0){let serviceUrlEnvVars=(0,import_build_utils3.getExperimentalServiceUrlEnvVars)({services:detectedServices,frameworkList:import_frameworks.frameworkList,currentEnv:process.env,deploymentUrl:process.env.VERCEL_URL});for(let[key,value]of Object.entries(serviceUrlEnvVars))process.env[key]=value,output.debug(`Injected service URL env var: ${key}=${value}`)}let serviceRewrites=detectedBuilders.serviceRewrites,serviceRewriteRoutes=serviceRewrites&&serviceRewrites.length>0?(0,import_routing_utils.convertRewrites)(serviceRewrites):null;zeroConfigRoutes.push(...detectedBuilders.redirectRoutes||[]);let detectedHostRewriteRoutes=detectedBuilders.hostRewriteRoutes;zeroConfigRoutes=(0,import_routing_utils.appendRoutesToPhase)({routes:zeroConfigRoutes,newRoutes:detectedHostRewriteRoutes??null,phase:null});let detectedServiceRewriteRoutes=nestExperimentalServicesV2Output?[]:detectedBuilders.rewriteRoutes;zeroConfigRoutes.push(...(0,import_routing_utils.appendRoutesToPhase)({routes:[],newRoutes:[...detectedServiceRewriteRoutes||[],...serviceRewriteRoutes||[]],phase:"filesystem"})),zeroConfigRoutes=(0,import_routing_utils.appendRoutesToPhase)({routes:zeroConfigRoutes,newRoutes:detectedBuilders.errorRoutes,phase:"error"}),nestExperimentalServicesV2Output||(zeroConfigRoutes.push(...detectedBuilders.defaultRoutes||[]),zeroConfigFallbackRoutes=detectedBuilders.fallbackRoutes||[])}builds.push(...daemonBuilds),(0,import_backend_rewrite_warning.hasBackendRewriteBehaviorChange)({projectRewrites:localConfig.rewrites,builders:builds})&&output.warn(import_backend_rewrite_warning.BACKEND_REWRITE_BEHAVIOR_WARNING);let checkScheduleServiceNames=()=>(0,import_schedule_services.rejectScheduleServiceNameConflicts)(scheduleServicePlan,[...(servicesToRecord??[]).map(service=>service.name),...Object.keys(detectedExperimentalServicesV1Config??{}),...Object.keys(detectedExperimentalServicesV2Config??{})]);checkScheduleServiceNames(),builds.push(...scheduleServiceBuilds);let builderSpecs=new Set(builds.map(b=>b.use)),buildersWithPkgs=await span.child("vc.importBuilders").trace(async s=>{let builders=await importBuilders2(builderSpecs,cwd,s);return s.setAttributes({resolved:formatResolvedBuilders2(builders)}),builders}),filesMap=await span.child("vc.populateFilesMap").trace(async s=>{let map={};for(let path of files){let fsPath=(0,import_path2.join)(workPath,path),{mode}=await import_fs_extra2.default.stat(fsPath);map[path]=new import_build_utils3.FileFsRef({mode,fsPath})}return s.setAttributes({fileCount:String(files.length)}),map}),buildStamp=startBuildTiming();await import_fs_extra2.default.mkdirp(outputDir);let ops=[],buildsJsonBuilds=new Map,ensureBuildersImported=async buildsToImport=>{let missingBuilderSpecs=new Set(buildsToImport.map(build2=>build2.use).filter(builderSpec=>!buildersWithPkgs.has(builderSpec)));if(missingBuilderSpecs.size===0)return;let importedBuilders=await span.child("vc.importBuilders").trace(async s=>{let builders=await importBuilders2(missingBuilderSpecs,cwd,s);return s.setAttributes({resolved:formatResolvedBuilders2(builders)}),builders});buildersWithPkgs=new Map([...buildersWithPkgs.entries(),...importedBuilders.entries()])},addBuildsToBuildJson=async buildsToAdd=>{await ensureBuildersImported(buildsToAdd);for(let build2 of buildsToAdd){if(buildsJsonBuilds.has(build2))continue;let builderWithPkg=buildersWithPkgs.get(build2.use);if(!builderWithPkg)throw import_diagnostics3.buildDiagnostics.BUILD_BUILDER_LOAD_FAILED({use:build2.use});let{builder,pkg:builderPkg}=builderWithPkg;buildsJsonBuilds.set(build2,{require:builderPkg.name,requirePath:builderWithPkg.path,apiVersion:builder.version,...build2})}buildsJson.builds=Array.from(buildsJsonBuilds.values()),await writeBuildJson(buildsJson,outputDir)},meta={skipDownload:!0,cliVersion,runNpmInstallSet:new Set,...daemons&&{daemonContext:{projectRoot:workPath,daemons}}},scheduleServices=scheduleServicePlan.services.map(({name,root,entrypoint})=>({name,root,entrypoint})),setServicesContext=services=>{let v2Services=(services??[]).filter(import_build_utils3.isExperimentalServiceV2),protectedServices=[...scheduleServices,...v2Services.length>1?v2Services.map(service=>({name:service.name,root:service.root})):[]];protectedServices.length>0?meta.servicesContext={projectRoot:workPath,services:protectedServices}:delete meta.servicesContext};setServicesContext(detectedResolvedServices);let executedBuilds=[],buildResults=new Map,overrides=[];corepackShimDir||(corepackShimDir=await(0,import_corepack.initCorepack)({repoRootPath,output,readJSONFile:readJSONFile2,isCantParseJSONFile,warmPackageManager:(0,import_build_utils3.resolveBuildConcurrency)()>1}));let diagnostics={},packageManifests=[],apiDirFrameworkDetector=createApiDirFrameworkDetector((workPath2,frameworks)=>(0,import_framework_detection.detectAllFrameworks)(workPath2,frameworks,output)),getHasDetectedServices=()=>detectedResolvedServices!==void 0&&detectedResolvedServices.length>0,synthesizedServiceCrons=[],serviceByBuilder=new Map,serviceFileOverrides=new Map;if(getHasDetectedServices())for(let service of detectedResolvedServices)serviceByBuilder.set(service.builder,service);for(let service of scheduleServicePlan.services)serviceByBuilder.set(service.builder,service);let isNestedServiceBuild=build2=>scheduleServiceBuilds.has(build2)||nestExperimentalServicesV2Output&&serviceByBuilder.has(build2),preDeployEntries=[],liveRunners=new Set,buildOrdinals=new Map,generatedRootRoutes,buildDurationsMs=[],buildersWallMs=0,buildConcurrency,getUvWorkspaceCandidates=(builds2,getContext)=>{let candidates=[];for(let build2 of builds2){let context=getContext(build2);if(!context||context.toolchain!=="python"||typeof build2.src!="string")continue;let{service,serviceDir}=context,hasFunctionInstall=(0,import_build_utils3.isExperimentalServiceV2)(service)&&Object.values(service.functions??{}).some(fn=>typeof fn.installCommand=="string");candidates.push({build:build2,builderUse:build2.use,serviceDir,entrypointDir:(0,import_path2.join)(workPath,(0,import_path2.dirname)(build2.src)),defaultInstall:!service.installCommand?.trim()&&!hasFunctionInstall,buildCommand:service.buildCommand})}return candidates},installSharedWorkspaces=async(builds2,getContext)=>{let preinstalled=new Set,logKeptInstalls=(location,reason)=>output.log(`Services in "${location}" keep their own dependency installs and build one after another: ${reason}`),candidates=[];for(let build2 of builds2){let context=getContext(build2);if(!context||typeof build2.src!="string")return preinstalled;if(context.toolchain!=="node")continue;let{service,serviceDir}=context,hasFunctionInstall=(0,import_build_utils3.isExperimentalServiceV2)(service)&&Object.values(service.functions??{}).some(fn=>typeof fn.installCommand=="string");candidates.push({build:build2,builderUse:build2.use,framework:service.framework,serviceDir,installDir:(0,import_path2.join)(workPath,(0,import_path2.dirname)(build2.src)),defaultInstall:service.installCommand==null&&!hasFunctionInstall})}if(candidates.length<2)return preinstalled;if(process.env.NPM_AUTH_TOKEN)return output.log("Services keep their own dependency installs: NPM_AUTH_TOKEN is set"),preinstalled;if(process.env.VERCEL_INSTALL_COMPLETED==="1"&&typeof projectSettings.installCommand=="string")return output.log("Services keep their own dependency installs: the project ran its own install command first"),preinstalled;let workspaceInstallTargets=Array.isArray(meta.workspaceInstallTargets)?meta.workspaceInstallTargets:[],installs=await(0,import_shared_workspace_install.planSharedWorkspaceInstalls)({candidates,repoRootPath,config:{nodeVersion:projectSettings.nodeVersion??void 0,bunVersion:localConfig.bunVersion??void 0},meta,projectCreatedAt:projectSettings.createdAt,workspaceInstallTargets,onSkip:(installRoot,reason)=>logKeptInstalls((0,import_path2.relative)(repoRootPath,installRoot)||".",reason)});for(let install of installs){let location=(0,import_path2.relative)(repoRootPath,install.installRoot)||".";output.log(`Sharing one dependency install across ${install.builds.length} services in "${location}"`),await span.child("vc.sharedWorkspaceInstall",{services:String(install.builds.length)}).trace(()=>(0,import_shared_workspace_install.runSharedWorkspaceInstall)({install,meta,projectCreatedAt:projectSettings.createdAt,workspaceInstallTargets}));for(let build2 of install.builds)preinstalled.add(build2)}return preinstalled},runBuilders=async buildsToRun=>{await addBuildsToBuildJson(buildsToRun),process.env.VERCEL_EXPERIMENTAL_WORKSPACE_SCOPED_INSTALLS==="1"&&(meta.workspaceInstallTargets=await(0,import_workspace_install_targets.collectWorkspaceInstallTargets)({builds:buildsToRun,existingTargets:meta.workspaceInstallTargets,repoRootPath,serviceByBuilder,workPath}));let buildOne=async(build2,concurrent)=>{if(typeof build2.src!="string")return;let builderWithPkg=buildersWithPkgs.get(build2.use);if(!builderWithPkg)throw import_diagnostics3.buildDiagnostics.BUILD_BUILDER_LOAD_FAILED({use:build2.use});try{let{builder,pkg:builderPkg}=builderWithPkg,service=serviceByBuilder.get(build2),legacyExperimentalService=service&&(0,import_build_utils3.isExperimentalService)(service)?service:void 0,serviceWorkspace=service?(0,import_build_utils3.isExperimentalService)(service)?service.workspace:service.root:void 0,stripServiceRoutePrefix=!!legacyExperimentalService?.routePrefix&&legacyExperimentalService.routePrefix!=="/",buildWorkPath=workPath,buildEntrypoint=build2.src,buildFiles=filesMap;if(service&&serviceWorkspace&&serviceWorkspace!=="."){let wsPrefix=serviceWorkspace+"/";buildWorkPath=(0,import_path2.join)(workPath,serviceWorkspace),buildEntrypoint=build2.src.startsWith(wsPrefix)?build2.src.slice(wsPrefix.length):build2.src,buildFiles={};for(let[filePath,file]of Object.entries(filesMap))filePath.startsWith(wsPrefix)&&(buildFiles[filePath.slice(wsPrefix.length)]=file);output.debug(`Service "${service.name}": workspace-rooted build at "${buildWorkPath}", entrypoint "${buildEntrypoint}" (original: "${build2.src}")`)}let daemon=build2.config?.daemon;if(daemon&&!daemonBuilds.includes(build2))throw new import_build_utils3.NowBuildError({code:"INVALID_BUILDS_CONFIG",message:"Daemons are declared in `daemons`; `daemon` is not a `builds` configuration option."});if(daemon){buildWorkPath=(0,import_path2.join)(workPath,daemon.root),buildEntrypoint=daemon.entrypoint;let root=(0,import_build_utils3.normalizePath)((0,import_path2.relative)(workPath,buildWorkPath));if(root!==""){let prefix=`${root}/`;buildFiles={};for(let[filePath,file]of Object.entries(filesMap))filePath.startsWith(prefix)&&(buildFiles[filePath.slice(prefix.length)]=file)}}let restoreEnv=new Map,perBuildEnv=concurrent?{...process.env}:process.env,setBuildEnv=(key,value)=>{concurrent||restoreEnv.set(key,process.env[key]),value===void 0?delete perBuildEnv[key]:perBuildEnv[key]=value},settingsForEnv=service?{buildCommand:service.buildCommand??void 0,installCommand:service.installCommand??void 0,outputDirectory:projectSettings.outputDirectory??void 0,nodeVersion:projectSettings.nodeVersion??void 0}:projectSettings;for(let key of["buildCommand","installCommand","outputDirectory","nodeVersion"]){let value=settingsForEnv[key],envKey="VERCEL_PROJECT_SETTINGS_"+key.replace(/[A-Z]/g,letter=>`_${letter}`).toUpperCase();setBuildEnv(envKey,typeof value=="string"?value:void 0),typeof value=="string"&&output.debug(`Setting env ${envKey} to "${value}"`)}let isFrontendBuilder=build2.config&&"framework"in build2.config,builderFramework=build2.config?.framework??projectSettings.framework,isApiDir=isZeroConfig&&!service&&!isFrontendBuilder&&!daemon,detectFrameworkDir=daemon?(0,import_path2.join)(workPath,daemon.root):isApiDir?buildWorkPath:void 0,detectedFramework=detectFrameworkDir?await apiDirFrameworkDetector.detect(build2.use??"",detectFrameworkDir):void 0,buildConfig;if(isZeroConfig)if(service){let serviceBuildCommand=build2.config?.buildpack&&monorepoDefaultedServices.has(service.name)?void 0:service.buildCommand;buildConfig={...build2.config,...(0,import_build_utils3.isExperimentalServiceV2)(service)&&service.functions?{functions:service.functions,serviceName:service.name}:void 0,projectSettings:{...projectSettings,framework:service.framework??null,buildCommand:serviceBuildCommand??null,installCommand:service.installCommand??null},installCommand:service.installCommand??void 0,buildCommand:serviceBuildCommand??void 0,preDeployCommand:legacyExperimentalService?.preDeployCommand??void 0,framework:builderFramework,nodeVersion:projectSettings.nodeVersion,bunVersion:localConfig.bunVersion??void 0}}else buildConfig={outputDirectory:projectSettings.outputDirectory??void 0,...build2.config,projectSettings,installCommand:projectSettings.installCommand??void 0,devCommand:projectSettings.devCommand??void 0,buildCommand:projectSettings.buildCommand??void 0,...build2.config?.buildpack?buildpackCommands:void 0,framework:isFrontendBuilder?projectSettings.framework:void 0,nodeVersion:projectSettings.nodeVersion,bunVersion:localConfig.bunVersion??void 0};else buildConfig={...build2.config||{},bunVersion:localConfig.bunVersion??void 0};let diagnosticsFramework=(0,import_manifest.getBuildDiagnosticsFramework)({service,configFramework:buildConfig.framework,detectedFramework}),diagnosticsValues=diagnosticsFramework?{framework:diagnosticsFramework}:void 0,builderSpan=span.child("vc.builder",{"builder.name":builderPkg.name,"builder.version":builderPkg.version,"builder.dynamicallyInstalled":String(builderWithPkg.dynamicallyInstalled)}),daemonName=build2.config?.daemon?.name;(service||daemonName)&&builderSpan.setAttributes({"service.name":service?.name??daemonName,"service.runtime":getBuildToolchain(build2,service),"service.kind":service?"service":"daemon"});let serviceRoutePrefix=build2.config?.routePrefix,serviceConfigWorkspace=build2.config?.workspace,preDeployCmd=legacyExperimentalService?.preDeployCommand?.trim(),preDeployEntry=preDeployCmd&&service?{ordinal:buildOrdinals.get(build2)??Number.MAX_SAFE_INTEGER,service:service.name}:void 0;preDeployEntry&&preDeployEntries.push(preDeployEntry);let buildOptions={files:buildFiles,entrypoint:buildEntrypoint,workPath:buildWorkPath,repoRootPath,config:buildConfig,meta,span:builderSpan,...diagnosticsValues?{diagnosticsValues}:void 0,...preDeployCmd?{registerPreDeploy:callback=>{preDeployEntry.callback=callback}}:void 0,...service?{service:{name:service.name,...scheduleServiceBuilds.has(build2)?{type:"job",trigger:"schedule"}:void 0,...legacyExperimentalService?{type:legacyExperimentalService.type,trigger:legacyExperimentalService.trigger}:void 0,routePrefix:typeof serviceRoutePrefix=="string"?serviceRoutePrefix:void 0,workspace:typeof serviceConfigWorkspace=="string"?serviceConfigWorkspace:serviceWorkspace,...legacyExperimentalService?{schedule:legacyExperimentalService.schedule}:void 0}}:void 0};if(output.debug(`Building entrypoint "${build2.src}" with "${builderPkg.name}"`),detectedServices&&legacyExperimentalService?.env){let perServiceEnv=(0,import_build_utils3.getServiceUrlEnvVars)({requestedEnv:legacyExperimentalService.env,consumerService:legacyExperimentalService,services:detectedServices,frameworkList:import_frameworks.frameworkList,currentEnv:process.env,deploymentUrl:process.env.VERCEL_URL});for(let[key,value]of Object.entries(perServiceEnv))key in process.env||(setBuildEnv(key,value),output.debug(`Injected service URL env var: ${key}=${value}`))}if(service)for(let key of SERVICE_BUILD_IMMUTABLE_ENV_VARS)setBuildEnv(key,void 0);let buildResult,rawBuildResult,runnerContext={requirePath:builderWithPkg.path,buildOptions,cwd:buildWorkPath,expectsPreDeploy:!!preDeployCmd,builderSpan,serviceName:service?.name,env:perBuildEnv},runner=createBuildRunner2?.({ctx:runnerContext,builder,hasDetectedServices:getHasDetectedServices(),builderPath:builderWithPkg.path,hasBuildCallback:!!buildOptions.buildCallback})??new import_build_runner2.InprocessBuildRunner(runnerContext,builder);if(concurrent&&runner instanceof import_build_runner2.InprocessBuildRunner)throw import_diagnostics3.buildDiagnostics.BUILD_CONCURRENT_INPROCESS({entrypoint:buildOptions.entrypoint});liveRunners.add(runner);try{({buildResult,rawBuildResult}=await(0,import_execute_builder.executeBuilder)({builder,buildOptions,span:builderSpan,isFrontendBuilder,hasDetectedServices:getHasDetectedServices(),framework:import_frameworks.frameworkList.find(framework2=>framework2.slug===buildConfig.framework),runner}))}finally{builderSpan.duration!==void 0&&buildDurationsMs.push(builderSpan.duration/1e3);for(let[key,prior]of restoreEnv)prior===void 0?delete process.env[key]:process.env[key]=prior;try{let builderDiagnostics=await runner.diagnostics();if(builderDiagnostics){let prefix=service&&serviceWorkspace&&serviceWorkspace!=="."?serviceWorkspace+"/"+builderPkg.name+"/":"";for(let[key,value]of Object.entries(builderDiagnostics)){let fullKey=prefix+key;if(key.endsWith("package-manifest.json"))try{let data;value.type==="FileBlob"?data=value.data.toString():data=await streamToString(value.toStream());let packageManifest=JSON.parse(data),validationError=(0,import_validate_package_manifest.validatePackageManifest)(packageManifest);if(validationError)output.warn(`Invalid package-manifest.json from ${fullKey}: ${validationError}`);else{let workspace=service&&serviceWorkspace&&serviceWorkspace!=="."?serviceWorkspace:".",root=daemon?(0,import_build_utils3.normalizePath)((0,import_path2.join)(daemon.root,".")):workspace,buildType=packageManifest.buildType??(buildConfig.middleware===!0?"middleware":daemon?"daemon":isApiDir?"api-dir":"app"),entry={ordinal:buildOrdinals.get(build2)??Number.MAX_SAFE_INTEGER,workspace,root,key:(0,import_manifest.getManifestBuildKey)(builderPkg.name,workspace,daemon?.name),diagnosticsValues,manifest:{...packageManifest,buildType},service,builderUse:builderPkg.name},existingIndex=packageManifests.findIndex(m=>m.key===entry.key),existing=existingIndex===-1?void 0:packageManifests[existingIndex];existing?entry.ordinal<existing.ordinal&&(packageManifests[existingIndex]=entry):packageManifests.push(entry)}}catch(e){output.debug(`Failed to parse ${fullKey}: ${e instanceof Error?e.message:String(e)}`)}else diagnostics[fullKey]=value}}}catch(error){output.error("Collecting diagnostics failed"),output.debug(error)}}if(buildResult&&"output"in buildResult&&"runtime"in buildResult.output&&"type"in buildResult.output&&buildResult.output.type==="Lambda"){let lambdaRuntime=buildResult.output.runtime;if((0,import_build_utils3.getDiscontinuedNodeVersions)().some(o=>o.runtime===lambdaRuntime))throw new import_build_utils3.NowBuildError({code:"NODEJS_DISCONTINUED_VERSION",message:`The Runtime "${build2.use}" is using "${lambdaRuntime}", which is discontinued. Please upgrade your Runtime to a more recent version or consult the author for more details.`,link:"https://vercel.link/function-runtimes"})}if("output"in buildResult&&buildResult.output&&((0,import_build_utils3.isBackendBuilder)(build2)||build2.use==="@vercel/python")){let routesJsonPath=(0,import_path2.join)(buildWorkPath,".vercel","routes.json");if((0,import_fs_extra2.existsSync)(routesJsonPath))try{let routesJson=await readJSONFile2(routesJsonPath);if(routesJson&&typeof routesJson=="object"&&"routes"in routesJson&&Array.isArray(routesJson.routes)){let indexLambda="index"in buildResult.output?buildResult.output.index:void 0,convertedRoutes=[],convertedOutputs=indexLambda?{index:indexLambda}:{};for(let route of routesJson.routes){if(typeof route.source!="string")continue;let{src}=(0,import_routing_utils.sourceToRegex)(route.source),newRoute={src,dest:route.source};route.methods&&(newRoute.methods=route.methods),route.source!=="/"&&(indexLambda&&(convertedOutputs[route.source]=indexLambda),convertedRoutes.push(newRoute))}buildResult.routes=[{handle:"filesystem"},...convertedRoutes,{src:"/(.*)",dest:"/"}],indexLambda&&(buildResult.output=convertedOutputs)}}catch(error){output.error(`Failed to read routes.json: ${error}`)}}if(getHasDetectedServices()&&service&&legacyExperimentalService&&"routes"in buildResult&&Array.isArray(buildResult.routes)&&detectedServices&&(buildResult.routes=(0,import_service_route_ownership.scopeRoutesToServiceOwnership)({routes:buildResult.routes,owner:legacyExperimentalService,allServices:detectedServices})),legacyExperimentalService&&(0,import_build_utils3.isQueueBackedService)(legacyExperimentalService)&&"output"in buildResult&&attachQueueServiceTrigger(buildResult.output,legacyExperimentalService),legacyExperimentalService&&(0,import_build_utils3.isScheduleTriggeredService)(legacyExperimentalService)&&!("crons"in buildResult&&buildResult.crons?.length)){let staticSchedules=(0,import_service_schedules.getStaticServiceSchedules)(legacyExperimentalService.schedule);if(typeof legacyExperimentalService.runtime=="string"&&staticSchedules.length>0){let cronEntrypoint=legacyExperimentalService.entrypoint||legacyExperimentalService.builder.src||"index";for(let schedule of staticSchedules)synthesizedServiceCrons.push({ordinal:buildOrdinals.get(build2)??Number.MAX_SAFE_INTEGER,cron:{path:(0,import_build_utils3.getInternalServiceCronPath)(legacyExperimentalService.name,cronEntrypoint,legacyExperimentalService.handlerFunction||"cron"),schedule}})}else throw new import_build_utils3.NowBuildError({code:"CRON_SERVICE_NO_CRONS",message:`Scheduled service "${legacyExperimentalService.name}" did not produce any cron entries. The builder "${builderPkg.name}" may not support scheduled services.`})}let mergedBuildResult=buildResult;if("buildOutputPath"in buildResult){let buildOutputConfigPath=(0,import_path2.join)(buildResult.buildOutputPath,"config.json"),buildOutputConfig=await readJSONFile2(buildOutputConfigPath);if(isCantParseJSONFile(buildOutputConfig))throw buildOutputConfig;if(buildOutputConfig){if(buildResult.framework&&!buildOutputConfig.framework&&(buildOutputConfig.framework=buildResult.framework),!hasExperimentalServicesV1ConfiguredInVercelConfig&&!hasExperimentalServicesV2ConfiguredInVercelConfig){let outputConfigPath=(0,import_path2.join)(outputDir,"config.json"),outputConfig=await readJSONFile2(outputConfigPath);if(isCantParseJSONFile(outputConfig))throw outputConfig;let shouldMergeGeneratedOutputRoutes=!1;hasNonEmptyObject(outputConfig?.experimentalServices)&&!hasNonEmptyObject(buildOutputConfig.experimentalServices)&&(buildOutputConfig.experimentalServices=outputConfig.experimentalServices,shouldMergeGeneratedOutputRoutes=!0),hasNonEmptyObject(outputConfig?.experimentalServicesV2)&&!hasNonEmptyObject(buildOutputConfig.experimentalServicesV2)&&(buildOutputConfig.experimentalServicesV2=outputConfig.experimentalServicesV2,shouldMergeGeneratedOutputRoutes=!0),hasGeneratedServicesConfig(outputConfig)&&!hasGeneratedServicesConfig(buildOutputConfig)&&(buildOutputConfig.services=outputConfig.services,shouldMergeGeneratedOutputRoutes=!0),shouldMergeGeneratedOutputRoutes&&Array.isArray(outputConfig?.routes)&&(buildOutputConfig.routes=prependMissingBuildOutputRoutes(outputConfig.routes,buildOutputConfig.routes),generatedRootRoutes??=outputConfig.routes),(hasNonEmptyObject(buildOutputConfig.experimentalServices)||hasNonEmptyObject(buildOutputConfig.experimentalServicesV2)||hasGeneratedServicesConfig(buildOutputConfig))&&await import_fs_extra2.default.writeJSON(buildOutputConfigPath,buildOutputConfig,{spaces:2})}getHasDetectedServices()&&service&&legacyExperimentalService&&Array.isArray(buildOutputConfig.routes)&&detectedServices&&(buildOutputConfig.routes=(0,import_service_route_ownership.scopeRoutesToServiceOwnership)({routes:buildOutputConfig.routes,owner:legacyExperimentalService,allServices:detectedServices})),mergedBuildResult=buildOutputConfig}}buildResults.set(build2,mergedBuildResult),executedBuilds.push(build2);let buildOutputLength=0;"output"in buildResult&&(buildOutputLength=Array.isArray(buildResult.output)?buildResult.output.length:1);let writeBuildResultPromise=builderSpan.child("vc.builder.writeBuildResult",{buildOutputLength:String(buildOutputLength)}).trace(writeSpan=>writeBuildResult2({repoRootPath,outputDir,buildResult:rawBuildResult,build:build2,builder,builderPkg,vercelConfig:localConfig,standalone,workPath:buildWorkPath,service,nestServiceOutput:isNestedServiceBuild(build2),stripServiceRoutePrefix,span:writeSpan}));if(service&&isNestedServiceBuild(build2)){let override=await writeBuildResultPromise;override&&serviceFileOverrides.set(build2,override)}else ops.push(writeBuildResultPromise.then(override=>{override&&overrides.push({ordinal:buildOrdinals.get(build2)??Number.MAX_SAFE_INTEGER,override})},err=>err))}catch(err){let buildJsonBuild=buildsJsonBuilds.get(build2);throw buildJsonBuild&&(buildJsonBuild.error=toEnumerableError2(err)),err}finally{ops.push((0,import_build_utils3.download)(diagnostics,(0,import_path2.join)(outputDir,"diagnostics")).then(()=>{},err=>err))}},sortedBuilds=(0,import_execute_builder.sortBuildsForExecution)(buildsToRun);for(let build2 of sortedBuilds)buildOrdinals.has(build2)||buildOrdinals.set(build2,buildOrdinals.size);let concurrency=createBuildRunner2&&canBuildInSubprocess2?(0,import_build_utils3.resolveBuildConcurrency)():1,isEligible=build2=>{let bp=typeof build2.src=="string"?buildersWithPkgs.get(build2.use):void 0;return!!bp&&!!canBuildInSubprocess2&&canBuildInSubprocess2({hasDetectedServices:getHasDetectedServices(),builderPath:bp.path})},forceSingleChain=!hasExperimentalServicesV1ConfiguredInVercelConfig&&!hasExperimentalServicesV2ConfiguredInVercelConfig,getServiceBuildContext=build2=>{let service=getHasDetectedServices()&&typeof build2.src=="string"?serviceByBuilder.get(build2):void 0;if(!service)return;let serviceWorkspace=(0,import_build_utils3.isExperimentalService)(service)?service.workspace:service.root,serviceDir=serviceWorkspace&&serviceWorkspace!=="."?(0,import_path2.join)(workPath,serviceWorkspace):workPath,toolchain=getBuildToolchain(build2,service);return{service,serviceDir,toolchain}};buildConcurrency=concurrency;let buildersStart=performance.now();try{let preinstalledBuilds=concurrency>1&&!forceSingleChain?await installSharedWorkspaces(sortedBuilds.filter(isEligible),getServiceBuildContext):new Set,uvWorkspaceBuilds={independent:new Set,lockedByFirst:new Set};if(concurrency>1&&!forceSingleChain)try{uvWorkspaceBuilds=await(0,import_uv_workspace_builds.planUvWorkspaceBuilds)({candidates:getUvWorkspaceCandidates(sortedBuilds.filter(isEligible),getServiceBuildContext),repoRootPath})}catch(error){output.debug(`Building uv workspace services in order: ${error instanceof Error?error.message:String(error)}`)}await(0,import_build_concurrency.runBuildsWithConcurrency)({builds:sortedBuilds,concurrency,isEligible,forceSingleChain,resolveScope:async build2=>{let context=getServiceBuildContext(build2);if(!context){let key="no-service-context";return{outerKey:key,innerKey:`${key}:${build2.use}:${String(build2.src)}`,siblingsSkipInstall:!1}}let{service,serviceDir,toolchain}=context,customInstall=!!service.installCommand?.trim(),installRoot=await(0,import_build_concurrency.resolveInstallScopeRoot)({toolchain,serviceDir,ceilingDir:repoRootPath});return uvWorkspaceBuilds.independent.has(build2)||uvWorkspaceBuilds.lockedByFirst.has(build2)?{outerKey:`${toolchain}:${installRoot}`,innerKey:`uv-workspace:${installRoot}`,siblingsSkipInstall:!0,preinstalled:uvWorkspaceBuilds.independent.has(build2)}:{outerKey:`${toolchain}:${installRoot}`,innerKey:(0,import_build_concurrency.getInstallScopeKey)({toolchain,installDirectory:serviceDir,installCommand:service.installCommand}),siblingsSkipInstall:toolchain==="node"&&!customInstall,preinstalled:preinstalledBuilds.has(build2)}},runBuild:(build2,concurrent)=>buildOne(build2,concurrent),log:message=>output.log(message),reportSecondaryError:(err,build2)=>{output.error(`Build failed for "${build2.src}": ${err instanceof Error?err.message:String(err)}`)}})}finally{buildersWallMs+=performance.now()-buildersStart}},flushOps=async()=>{let errors=await Promise.all(ops.splice(0));for(let error of errors)if(error)throw error},normalizeBuilderSrc=src=>typeof src=="string"?(0,import_build_utils3.normalizePath)(src).replace(/^\.\//,""):void 0,getBuilderIdentity=build2=>{let normalizedSrc=normalizeBuilderSrc(build2.src);if(!normalizedSrc)return;let buildTarget=build2.config?.buildTarget;return typeof buildTarget=="string"?`${build2.use}:${normalizedSrc}#${buildTarget}`:`${build2.use}:${normalizedSrc}`},getAlreadyExecutedBuild=candidate=>{let candidateIdentity=getBuilderIdentity(candidate);if(candidateIdentity)return executedBuilds.find(build2=>!build2.config?.daemon&&!scheduleServiceBuilds.has(build2)&&getBuilderIdentity(build2)===candidateIdentity)},appendExperimentalServicesV1Routes=services=>{let serviceRoutes=(0,import_service_topology.generateServicesRoutes)(services);zeroConfigRoutes=(0,import_routing_utils.appendRoutesToPhase)({routes:zeroConfigRoutes,newRoutes:serviceRoutes.hostRewrites.length?serviceRoutes.hostRewrites:null,phase:null});let serviceRewriteRoutes=nestExperimentalServicesV2Output?[]:[...serviceRoutes.rewrites,...serviceRoutes.workers,...serviceRoutes.crons];zeroConfigRoutes.push(...(0,import_routing_utils.appendRoutesToPhase)({routes:[],newRoutes:serviceRewriteRoutes,phase:"filesystem"})),nestExperimentalServicesV2Output||(zeroConfigRoutes.push(...serviceRoutes.defaults),zeroConfigFallbackRoutes.push(...serviceRoutes.fallbacks))},sortBuildResultsByOrdinal=()=>{let orderedResults=Array.from(buildResults.entries()).sort(([a],[b])=>(buildOrdinals.get(a)??Number.MAX_SAFE_INTEGER)-(buildOrdinals.get(b)??Number.MAX_SAFE_INTEGER));buildResults.clear();for(let[build2,result]of orderedResults)buildResults.set(build2,result)};try{if(await runBuilders(builds),await flushOps(),sortBuildResultsByOrdinal(),!hasExperimentalServicesV1ConfiguredInVercelConfig&&!hasExperimentalServicesV2ConfiguredInVercelConfig){let generatedConfigPath=(0,import_path2.join)(outputDir,"config.json"),generatedConfig=await readJSONFile2(generatedConfigPath);if(isCantParseJSONFile(generatedConfig))throw generatedConfig;let defaultGeneratedOutputDir=(0,import_path2.join)(workPath,import_write_build_result3.OUTPUT_DIR),generatedConfigs=[generatedConfig];if((0,import_path2.resolve)(outputDir)!==(0,import_path2.resolve)(defaultGeneratedOutputDir)){let defaultGeneratedConfig=await readJSONFile2((0,import_path2.join)(defaultGeneratedOutputDir,"config.json"));if(isCantParseJSONFile(defaultGeneratedConfig))throw defaultGeneratedConfig;generatedConfigs.push(defaultGeneratedConfig)}let generatedServicesConfig=getGeneratedServicesConfig([...generatedConfigs,...buildResults.values()]),generatedExperimentalServicesV1Config=getGeneratedExperimentalServicesV1Config([...generatedConfigs,...buildResults.values()]);if(generatedServicesConfig||generatedExperimentalServicesV1Config){generatedServicesConfig&&(nestExperimentalServicesV2Output=!0),detectedExperimentalServicesV1Config=generatedExperimentalServicesV1Config,detectedExperimentalServicesV2Config=generatedServicesConfig;let generatedRootRoutesConfig=generatedServicesConfig?generatedConfigs.find(config2=>(hasGeneratedServicesConfig(config2)||hasNonEmptyObject(config2?.experimentalServicesV2))&&Array.isArray(config2?.routes)):void 0;generatedRootRoutesConfig?.routes&&(generatedRootRoutes??=generatedRootRoutesConfig.routes);let generatedBuilders=await span.child("vc.detectGeneratedServices").trace(()=>(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,{...localConfig,reservedServiceFiles,...generatedServicesConfig?{services:generatedServicesConfig,experimentalServicesV2:void 0}:{experimentalServicesV2:void 0,experimentalServices:generatedExperimentalServicesV1Config},projectSettings,ignoreBuildScript:!0,featHandleMiss:!0,workPath}));if(generatedBuilders.errors&&generatedBuilders.errors.length>0)throw generatedBuilders.errors[0];for(let w of generatedBuilders.warnings)output.warn(w.message,null,w.link,w.action||"Learn More");if(detectedResolvedServices=generatedBuilders.services,setServicesContext(detectedResolvedServices),!detectedResolvedServices||detectedResolvedServices.length===0?(detectedResolvedServices=void 0,detectedServices=void 0):(detectedServices=detectedResolvedServices.filter(import_build_utils3.isExperimentalService),detectedServices.length>0&&appendExperimentalServicesV1Routes(detectedServices)),detectedServices&&detectedServices.length>0&&generatedBuilders.useImplicitEnvInjection){let serviceUrlEnvVars=(0,import_build_utils3.getExperimentalServiceUrlEnvVars)({services:detectedServices,frameworkList:import_frameworks.frameworkList,currentEnv:process.env,deploymentUrl:process.env.VERCEL_URL});for(let[key,value]of Object.entries(serviceUrlEnvVars))process.env[key]=value,output.debug(`Injected service URL env var: ${key}=${value}`)}let buildsToRun=[],seenBuildsToRun=new Set,recordedServices2=[];for(let service of detectedResolvedServices||[]){let alreadyExecutedBuild=getAlreadyExecutedBuild(service.builder);if(alreadyExecutedBuild){if(generatedServicesConfig){output.warn(getGeneratedServiceAlreadyBuiltWarning(service));continue}serviceByBuilder.set(alreadyExecutedBuild,service),recordedServices2.push(service);continue}let serviceBuilderIdentity=getBuilderIdentity(service.builder);serviceBuilderIdentity&&!seenBuildsToRun.has(serviceBuilderIdentity)&&(serviceByBuilder.set(service.builder,service),seenBuildsToRun.add(serviceBuilderIdentity),buildsToRun.push(service.builder)),recordedServices2.push(service)}servicesToRecord=recordedServices2.length>0?recordedServices2:void 0,buildsToRun.length>0&&await runBuilders(buildsToRun)}}preDeployEntries.sort((a,b)=>a.ordinal-b.ordinal);for(let entry of preDeployEntries)entry.callback?await entry.callback():output.warn(`Service "${entry.service}" has a preDeployCommand but its builder does not support it. The command was not executed.`)}finally{let servicesCount=detectedResolvedServices?.length??0;(servicesCount>0||daemonBuilds.length>0)&&span.setAttributes({"services.count":String(servicesCount),"daemons.count":String(daemonBuilds.length),"build.concurrency":buildConcurrency===void 0?void 0:String(buildConcurrency),"services.build_ms.sum":String(Math.round(buildDurationsMs.reduce((sum,ms)=>sum+ms,0))),"services.build_ms.max":String(Math.round(Math.max(0,...buildDurationsMs))),"services.build_ms.wall":String(Math.round(buildersWallMs))});let settled=await Promise.all(ops.splice(0));for(let err of settled)err&&ops.push(Promise.resolve(err));for(let runner of liveRunners)try{runner.teardown()}catch(err){output.debug(`Runner teardown failed: ${err instanceof Error?err.message:String(err)}`)}}sortBuildResultsByOrdinal(),packageManifests.sort((a,b)=>a.ordinal-b.ordinal),await(0,import_manifest.writeManifests)(packageManifests,diagnostics,ops,outputDir),corepackShimDir&&(0,import_corepack.cleanupCorepack)(corepackShimDir);let collectSpan=span.child("vc.finalizeBuildOutput");await flushOps();let needBuildsJsonOverride=!1,speedInsightsVersion=await(0,import_build_utils3.getInstalledPackageVersion)("@vercel/speed-insights");speedInsightsVersion&&(buildsJson.features={...buildsJson.features??{},speedInsightsVersion},needBuildsJsonOverride=!0);let webAnalyticsVersion=await(0,import_build_utils3.getInstalledPackageVersion)("@vercel/analytics");webAnalyticsVersion&&(buildsJson.features={...buildsJson.features??{},webAnalyticsVersion},needBuildsJsonOverride=!0),needBuildsJsonOverride&&await writeBuildJson(buildsJson,outputDir);let configPath=(0,import_path2.join)(outputDir,"config.json"),existingConfig=await readJSONFile2(configPath);if(isCantParseJSONFile(existingConfig))throw existingConfig;if(existingConfig){if("deploymentId"in existingConfig&&typeof existingConfig.deploymentId=="string"){let deploymentId=existingConfig.deploymentId;if(deploymentId.length>32)throw new import_build_utils3.NowBuildError({code:"INVALID_DEPLOYMENT_ID",message:`The deploymentId "${deploymentId}" must be 32 characters or less. Please choose a shorter deploymentId in your config.`,link:"https://vercel.com/docs/skew-protection#custom-skew-protection-deployment-id"});if(!VALID_DEPLOYMENT_ID_PATTERN.test(deploymentId))throw new import_build_utils3.NowBuildError({code:"INVALID_DEPLOYMENT_ID",message:`The deploymentId "${deploymentId}" contains invalid characters. Only alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (_) are allowed.`,link:"https://vercel.com/docs/skew-protection#custom-skew-protection-deployment-id"})}existingConfig.overrides&&!nestExperimentalServicesV2Output&&overrides.push({ordinal:Number.MAX_SAFE_INTEGER,override:existingConfig.overrides})}let topLevelBuildResults=nestExperimentalServicesV2Output||scheduleServicePlan.services.length>0?new Map(Array.from(buildResults.entries()).filter(([build2])=>!isNestedServiceBuild(build2))):buildResults,builderRoutes=Array.from(topLevelBuildResults.entries()).filter(b=>"routes"in b[1]&&Array.isArray(b[1].routes)).map(b=>{let build2=b[0],buildResult=b[1],entrypoint=build2.src;if(getHasDetectedServices()&&typeof build2.src=="string"){let service=serviceByBuilder.get(build2);service&&(0,import_build_utils3.isExperimentalService)(service)&&service.type==="web"&&typeof service.routePrefix=="string"&&(entrypoint=getServicesMergeEntrypoint(service,build2.src))}return{use:build2.use,entrypoint,routes:buildResult.routes,projectMiddleware:build2.config?.middleware===!0}});zeroConfigRoutes.length&&builderRoutes.unshift({use:"@vercel/zero-config-routes",entrypoint:"/",routes:zeroConfigRoutes});let mergedRoutes=(0,import_routing_utils.mergeRoutes)({userRoutes:routesResult.routes,builds:builderRoutes});zeroConfigFallbackRoutes.length&&(mergedRoutes=(0,import_routing_utils.appendRoutesToPhase)({routes:mergedRoutes,newRoutes:zeroConfigFallbackRoutes,phase:"filesystem"}));let mergedImages=mergeImages(localConfig.images,topLevelBuildResults.values()),orderedServiceCrons=synthesizedServiceCrons.slice().sort((a,b)=>a.ordinal-b.ordinal).map(entry=>entry.cron),mergedCrons=mergeCrons([...localConfig.crons||[],...orderedServiceCrons],buildResults.values()),mergedWildcard=mergeWildcard(topLevelBuildResults.values()),mergedDeploymentId=await mergeDeploymentId(existingConfig?.deploymentId,topLevelBuildResults.values(),workPath,projectSettings.outputDirectory,readJSONFile2,isCantParseJSONFile);if(mergedDeploymentId){if(mergedDeploymentId.length>32)throw new import_build_utils3.NowBuildError({code:"INVALID_DEPLOYMENT_ID",message:`The deploymentId "${mergedDeploymentId}" must be 32 characters or less. Please choose a shorter deploymentId in your config.`,link:"https://vercel.com/docs/skew-protection#custom-skew-protection-deployment-id"});if(!VALID_DEPLOYMENT_ID_PATTERN.test(mergedDeploymentId))throw new import_build_utils3.NowBuildError({code:"INVALID_DEPLOYMENT_ID",message:`The deploymentId "${mergedDeploymentId}" contains invalid characters. Only alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (_) are allowed.`,link:"https://vercel.com/docs/skew-protection#custom-skew-protection-deployment-id"})}let topLevelBuildResultOverrides=Array.from(topLevelBuildResults.values()).map(result=>"overrides"in result?result.overrides:void 0).filter(value=>!!value),orderedOverrides=overrides.slice().sort((a,b)=>a.ordinal-b.ordinal).map(entry=>entry.override),mergedOverrides=overrides.length>0||topLevelBuildResultOverrides.length>0?Object.assign({},...orderedOverrides,...topLevelBuildResultOverrides):void 0,framework=topLevelBuildResults.size>0?await getFramework(workPath,topLevelBuildResults):void 0,rootRoutesToAppend=Array.from(topLevelBuildResults.values()).some(result=>(hasGeneratedServicesConfig(result)||"experimentalServicesV2"in result&&hasNonEmptyObject(result.experimentalServicesV2))&&"routes"in result&&Array.isArray(result.routes))?void 0:generatedRootRoutes??existingConfig?.routes,explicitRootRoutes=appendBuildOutputRouteTables(routesResult.routes,rootRoutesToAppend),mergedRoutesWithGeneratedServicesV2Routes=nestExperimentalServicesV2Output?appendBuildOutputRouteTables(mergedRoutes,rootRoutesToAppend):mergedRoutes,resolvedSchedules=mergeSchedules(authoredSchedules.flatMap(schedule=>(0,import_build_utils3.isServiceSchedule)(schedule)?scheduleServicePlan.targets.get(schedule.name)??[]:schedule),buildResults,build2=>isNestedServiceBuild(build2)?serviceByBuilder.get(build2)?.name:void 0);await writeDaemonDescriptors(outputDir,daemons,buildResults),checkScheduleServiceNames();let recordedServices=[...servicesToRecord??[],...scheduleServicePlan.services.map(({builder,...service})=>({...service,builder:{src:builder.src,use:builder.use}}))],outputServices={...detectedExperimentalServicesV2Config,...Object.fromEntries(scheduleServicePlan.services.map(service=>[service.name,{root:service.root,runtime:service.runtime,entrypoint:service.entrypoint}]))},config={version:3,daemons:Object.fromEntries(Object.keys(daemons??{}).map(name=>[name,{}])),routes:mergedRoutesWithGeneratedServicesV2Routes??explicitRootRoutes,afterCacheBypass:mergeAfterCacheBypass(topLevelBuildResults.values())??existingConfig?.afterCacheBypass,images:mergedImages,wildcard:mergedWildcard,overrides:mergedOverrides,framework,crons:mergedCrons,...resolvedSchedules.length>0&&{schedules:(0,import_build_utils3.toScheduleRecord)(resolvedSchedules)},...detectedExperimentalServicesV1Config&&Object.keys(detectedExperimentalServicesV1Config).length>0&&{experimentalServices:detectedExperimentalServicesV1Config},...Object.keys(outputServices).length>0&&{experimentalServicesV2:outputServices},...(!detectedExperimentalServicesV1Config||scheduleServicePlan.services.length>0)&&recordedServices.length>0&&{services:recordedServices},...mergedDeploymentId&&{deploymentId:mergedDeploymentId}};return await import_fs_extra2.default.writeJSON((0,import_path2.join)(outputDir,"config.json"),config,{spaces:2}),(nestExperimentalServicesV2Output||scheduleServicePlan.services.length>0)&&await writeServiceConfigs(outputDir,buildResults,new Map([...serviceByBuilder].filter(([build2])=>isNestedServiceBuild(build2))),serviceFileOverrides,detectedExperimentalServicesV2Config,readJSONFile2,isCantParseJSONFile),await writeFlagsJSON(buildResults.values(),outputDir,output),await span.child("vc.frameworkCrossCheck").trace(async s=>{let detectedFrameworks=await detectedFrameworksPromise,executedBuilders=Array.from(buildResults.keys()),usedBuilders=executedBuilders.map(b=>b.use).filter(use=>!!use),mismatchResult=(0,import_framework_detection.warnIfFrameworkMismatch)({configuredFramework:projectSettings.framework,detectedFrameworks,usedBuilders,usedFrameworks:executedBuilders.map(b=>b.config?.framework)},output);s.setAttributes({result:mismatchResult,configuredFramework:projectSettings.framework??void 0,detectedFrameworks:detectedFrameworks.join(",")||void 0,usedBuilders:usedBuilders.join(",")||void 0})}),await span.child("vc.validateBuildOutput").trace(async s=>{let outputProblems=await(0,import_validate_build_output.validateBuildOutput)(outputDir,output);s.setAttributes({problemCount:String(outputProblems.length),problems:outputProblems.map(p=>`${p.severity}: ${p.message}`).join("; ")||void 0}),(0,import_validate_build_output.reportBuildOutputProblems)(outputProblems,output)}),collectSpan.stop(),{buildDuration:buildStamp()}}async function getFramework(cwd,buildResults){let detectedFramework=await(0,import_fs_detectors.detectFrameworkRecord)({fs:new import_fs_detectors.LocalFileSystemDetector(cwd),frameworkList:import_frameworks.frameworkList});if(!detectedFramework){for(let buildResult of buildResults.values())if("framework"in buildResult&&buildResult.framework)return{slug:buildResult.framework.slug,version:buildResult.framework.version};return}if(detectedFramework.useRuntime){for(let[build2,buildResult]of buildResults.entries())if("framework"in buildResult&&build2.use===detectedFramework.useRuntime.use)return buildResult.framework?{slug:buildResult.framework.slug,version:buildResult.framework.version}:void 0}if(detectedFramework.slug){if(detectedFramework.detectedVersion&&import_semver.default.valid(detectedFramework.detectedVersion))return{slug:detectedFramework.slug,version:detectedFramework.detectedVersion};let frameworkVersion=(0,import_fs_detectors.detectFrameworkVersion)(detectedFramework);if(frameworkVersion)return{slug:detectedFramework.slug,version:frameworkVersion}}}function expandBuild(files,build2){if(!build2.use)throw new import_build_utils3.NowBuildError({code:"invalid_build_specification",message:"Field `use` is missing in build specification",link:"https://vercel.com/docs/concepts/projects/project-configuration#builds",action:"View Documentation"});let src=(0,import_path2.normalize)(build2.src||"**").split(import_path2.sep).join("/");if(src==="."||src==="./")throw new import_build_utils3.NowBuildError({code:"invalid_build_specification",message:"A build `src` path resolves to an empty string",link:"https://vercel.com/docs/concepts/projects/project-configuration#builds",action:"View Documentation"});return src[0]==="/"&&(src=src.substring(1)),files.filter(name=>name===src||(0,import_minimatch.default)(name,src,{dot:!0})).map(m=>({...build2,src:m}))}function mergeImages(images,buildResults){for(let result of buildResults)"images"in result&&result.images&&(images=Object.assign({},images,result.images));return images}function mergeCrons(crons=[],buildResults){for(let result of buildResults)"crons"in result&&result.crons&&(crons=crons.concat(result.crons));return crons}function mergeSchedules(authored,buildResults,getNestedServiceName){let schedules=[...authored],sources=new Map,claim=(schedule,source)=>{let{name}=schedule,existing=sources.get(name);if(existing)throw new import_build_utils3.NowBuildError({code:"SCHEDULE_NAME_CONFLICT",message:`Schedule "${name}" is defined by both ${existing} and ${source}. Schedule names must be unique within a deployment.`});sources.set(name,source)};for(let schedule of schedules)claim(schedule,"vercel.json");for(let[build2,result]of buildResults){if(!("schedules"in result)||result.schedules===void 0)continue;let source=`the build output of "${build2.use}"${build2.src?` for "${build2.src}"`:""}`,invalid=message=>new import_build_utils3.NowBuildError({code:"INVALID_BUILD_OUTPUT_SCHEDULE",message:`Schedules in ${source} ${message}`});if(!isPlainObject(result.schedules))throw invalid("must be an object keyed by schedule name.");let entries=Object.entries(result.schedules);if(entries.length===0)continue;let service=getNestedServiceName(build2);for(let[key,schedule]of entries){if(!isPlainObject(schedule))throw invalid("must be objects.");if("entrypoint"in schedule)throw invalid("cannot use `entrypoint`. Build Output schedules must target a `function`, `path`, or `topic`.");if("name"in schedule)throw invalid(`cannot set \`name\` on "${key}". The schedule's key is its name.`);if(service!==void 0){if(!("function"in schedule))throw invalid(`must target a \`function\`. "${key}" is in the build output of service "${service}", so it can only invoke that service's functions.`);if("service"in schedule)throw invalid(`cannot set \`service\` on "${key}". It is set to "${service}", the service that built it.`)}let named={name:key,...schedule,...service!==void 0&&{service}};claim(named,source),schedules.push(named)}}return schedules}function isPlainObject(value){return value!=null&&typeof value=="object"&&!Array.isArray(value)}function mergeWildcard(buildResults){let wildcard;for(let result of buildResults)"wildcard"in result&&result.wildcard&&(wildcard||(wildcard=[]),wildcard.push(...result.wildcard));return wildcard}function mergeAfterCacheBypass(buildResults){let rules;for(let result of buildResults)"afterCacheBypass"in result&&result.afterCacheBypass&&(rules=(rules??[]).concat(result.afterCacheBypass));return rules}function appendBuildOutputRouteTables(...routeTables){let routes=[];for(let routeTable of routeTables){if(!Array.isArray(routeTable)||routeTable.length===0)continue;let phase=null,phaseRoutes=[],flushPhase=()=>{phaseRoutes.length!==0&&(routes=(0,import_routing_utils.appendRoutesToPhase)({routes,newRoutes:phaseRoutes,phase}),phaseRoutes=[])};for(let route of routeTable)(0,import_routing_utils.isHandler)(route)?(flushPhase(),phase=route.handle):phaseRoutes.push(route);flushPhase()}return routes.length>0?routes:void 0}function appendServiceRouteTables(configuredRoutes,...builderRouteTables){if(!configuredRoutes.some(route=>!(0,import_routing_utils.isHandler)(route)&&route.transforms?.some(transform=>transform.type==="request.path")))return appendBuildOutputRouteTables(configuredRoutes,...builderRouteTables);let builderRoutesWithRequestPathFallbacks=builderRouteTables.map(routes=>routes?.map(route=>(0,import_routing_utils.isHandler)(route)||route.dest===void 0||!route.transforms||!route.transforms.some(transform=>transform.type==="request.path")?route:{...route,transforms:route.transforms.map(transform=>transform.type==="request.path"?{...transform,fallback:!0}:transform)}));return appendBuildOutputRouteTables(configuredRoutes,...builderRoutesWithRequestPathFallbacks)}function prependMissingBuildOutputRoutes(routesToPrepend,existingRoutes){if(!Array.isArray(routesToPrepend)||routesToPrepend.length===0)return existingRoutes;let existingRouteKeys=new Set((existingRoutes??[]).map(route=>JSON.stringify(route))),missingRoutes=routesToPrepend.filter(route=>!existingRouteKeys.has(JSON.stringify(route)));return appendBuildOutputRouteTables(missingRoutes,existingRoutes)}async function writeServiceConfigs(outputDir,buildResults,serviceByBuilder,serviceFileOverrides,experimentalServicesV2,readJSONFile2,isCantParseJSONFile){let serviceResults=new Map,serviceOverrides=new Map;for(let[build2,buildResult]of buildResults){let service=serviceByBuilder.get(build2);if(!service)continue;let results=serviceResults.get(service.name)||[];results.push(buildResult),serviceResults.set(service.name,results);let fileOverrides=serviceFileOverrides.get(build2);if(fileOverrides){let overrides=serviceOverrides.get(service.name)||[];overrides.push(fileOverrides),serviceOverrides.set(service.name,overrides)}}await Promise.all(Array.from(serviceResults.entries()).map(async([serviceName,results])=>{let configPath=(0,import_path2.join)(outputDir,"services",serviceName,"config.json"),existingConfig=await readJSONFile2(configPath);if(isCantParseJSONFile(existingConfig))throw existingConfig;let routes=results.flatMap(result=>"routes"in result&&Array.isArray(result.routes)?result.routes:[]),existingRoutes=routes.length>0?void 0:existingConfig?.routes,existingCrons=results.some(result=>"crons"in result&&result.crons?.length)?void 0:existingConfig?.crons,configuredRoutes=experimentalServicesV2?.[serviceName]?getExperimentalServicesV2Routes(experimentalServicesV2[serviceName]):[],overrides=[...results.map(result=>"overrides"in result?result.overrides:void 0).filter(value=>!!value),...serviceOverrides.get(serviceName)||[]],framework=results.find(result=>"framework"in result&&!!result.framework)?.framework,mergedRoutes=appendServiceRouteTables(configuredRoutes,routes,existingRoutes),config={...existingConfig,version:3,routes:mergedRoutes,afterCacheBypass:mergeAfterCacheBypass(results)??existingConfig?.afterCacheBypass,images:mergeImages(existingConfig?.images,results),wildcard:mergeWildcard(results)||existingConfig?.wildcard,overrides:overrides.length>0?Object.assign({},existingConfig?.overrides,...overrides):existingConfig?.overrides,framework:framework||existingConfig?.framework,crons:mergeCrons(existingCrons,results),services:void 0,experimentalServices:void 0,experimentalServicesV2:void 0};await import_fs_extra2.default.writeJSON(configPath,config,{spaces:2})}))}function getExperimentalServicesV2Routes(serviceConfig){let routesResult=(0,import_routing_utils.getTransformedRoutes)({routes:serviceConfig.routes,cleanUrls:serviceConfig.cleanUrls,trailingSlash:serviceConfig.trailingSlash,headers:serviceConfig.headers,redirects:serviceConfig.redirects,rewrites:serviceConfig.rewrites});if(routesResult.error)throw routesResult.error;return routesResult.routes??[]}function getGeneratedExperimentalServicesV1Config(buildResults){for(let result of buildResults)if(result&&"experimentalServices"in result&&hasNonEmptyObject(result.experimentalServices))return result.experimentalServices}function hasGeneratedServicesConfig(result){return result!=null&&"services"in result&&hasNonEmptyObject(result.services)}function getGeneratedServicesConfig(buildResults){for(let result of buildResults){if(hasGeneratedServicesConfig(result))return result.services;if(result&&"experimentalServicesV2"in result&&hasNonEmptyObject(result.experimentalServicesV2))return result.experimentalServicesV2}}async function mergeDeploymentId(existingDeploymentId,buildResults,workPath,outputDirectory,readJSONFile2,isCantParseJSONFile){if(existingDeploymentId)return existingDeploymentId;for(let result of buildResults)if("deploymentId"in result&&result.deploymentId)return result.deploymentId;let nextOutputDirs=new Set([outputDirectory,".next"].filter(dir=>!!dir));for(let nextOutputDir of nextOutputDirs)try{let routesManifestPath=(0,import_path2.join)(workPath,nextOutputDir,"routes-manifest.json");if(await import_fs_extra2.default.pathExists(routesManifestPath)){let routesManifest=await readJSONFile2(routesManifestPath);if(routesManifest&&!isCantParseJSONFile(routesManifest)&&routesManifest.deploymentId)return routesManifest.deploymentId}}catch{}}async function writeFlagsJSON(buildResults,outputDir,output){let flagsFilePath=(0,import_path2.join)(outputDir,"flags.json"),hasFlags=!0,flags=await import_fs_extra2.default.readJSON(flagsFilePath).catch(error=>{if(error.code==="ENOENT")return hasFlags=!1,{definitions:{}};throw error});for(let result of buildResults)if(!(!("flags"in result)||!result.flags||!result.flags.definitions))for(let[key,definition]of Object.entries(result.flags.definitions)){if(result.flags.definitions[key]){output.warn(`The flag "${key}" was found multiple times. Only its first occurrence will be considered.`);continue}hasFlags=!0,flags.definitions[key]=definition}hasFlags&&await import_fs_extra2.default.writeJSON(flagsFilePath,flags,{spaces:2})}function createApiDirFrameworkDetector(detectAllFrameworks2){let cache=new Map;return{detect(builderUse,workPath){let cacheKey=`${builderUse}:${workPath}`,cached=cache.get(cacheKey);return cached||(cached=detectApiDirFramework(builderUse,workPath,detectAllFrameworks2),cache.set(cacheKey,cached)),cached}}}async function detectApiDirFramework(builderUse,workPath,detectAllFrameworks2){let runtimeFrameworks=import_fs_detectors.builderToFrameworks.get(builderUse)??[];if(runtimeFrameworks.length===0)return;let detectedSlugs=await detectAllFrameworks2(workPath,runtimeFrameworks).catch(()=>[]);return detectedSlugs.length===1?detectedSlugs[0]:void 0}async function writeDaemonDescriptors(outputDir,daemons,buildResults){let namePattern=new RegExp(import_build_utils3.DAEMON_NAME_PATTERN),descriptors=new Map;for(let[build2,result]of buildResults){let returned="output"in result&&"daemons"in result?result.daemons:void 0;for(let[name,descriptor]of Object.entries(returned??{})){if(name!==build2.config?.daemon?.name||!namePattern.test(name))throw new Error(`Builder "${build2.use}" returned an unexpected daemon descriptor "${name}".`);descriptors.set(name,descriptor)}}for(let name of Object.keys(daemons??{})){let descriptor=descriptors.get(name);if(!descriptor)throw new import_build_utils3.NowBuildError({code:"MISSING_DAEMON_OUTPUT",message:`Failed to build daemon "${name}": its build returned no daemon descriptor.`});await import_fs_extra2.default.outputJSON((0,import_path2.join)(outputDir,"daemons",name,".vc-config.json"),descriptor,{spaces:2})}}async function writeBuildJson(buildsJson,outputDir){await import_fs_extra2.default.writeJSON((0,import_path2.join)(outputDir,"builds.json"),buildsJson,{spaces:2})}function getBuildToolchain(build2,service){return service?.runtime??["python","go","ruby","rust","container"].find(t=>build2.use.startsWith(`@vercel/${t}`))??"node"}function normalizeServiceRoutePrefix(routePrefix){let prefix=routePrefix.startsWith("/")?routePrefix:`/${routePrefix}`;return prefix!=="/"&&prefix.endsWith("/")&&(prefix=prefix.slice(0,-1)),prefix}function getServicesMergeEntrypoint(service,buildSrc){let routePrefix=typeof service.routePrefix=="string"?service.routePrefix:"/",normalized=normalizeServiceRoutePrefix(routePrefix);return`svc:${String(1e4-normalized.length).padStart(5,"0")}:${normalized}:${service.name}:${buildSrc}`}function attachQueueServiceTrigger(buildOutput,service){let topics=(0,import_build_utils3.getServiceQueueTopicConfigs)(service),consumer=(0,import_build_utils3.sanitizeConsumerName)((0,import_build_utils3.getInternalServiceFunctionPath)(service.name));if(service.builder.use!=="@vercel/python"&&topics.length>1)throw import_diagnostics3.buildDiagnostics.BUILD_WORKER_MULTIPLE_TOPICS({name:service.name,topics:topics.length});for(let topicConfig of topics){let trigger={type:"queue/v2beta",topic:topicConfig.topic,consumer};if(topicConfig.retryAfterSeconds!==void 0&&(trigger.retryAfterSeconds=topicConfig.retryAfterSeconds),topicConfig.initialDelaySeconds!==void 0&&(trigger.initialDelaySeconds=topicConfig.initialDelaySeconds),(0,import_write_build_result3.isLambda)(buildOutput))appendTrigger(buildOutput,trigger);else for(let output of Object.values(buildOutput))(0,import_write_build_result3.isLambda)(output)&&appendTrigger(output,trigger)}}function triggerMatches(trigger,existingTrigger){return trigger.type==="schedule/v1beta"?trigger.type===existingTrigger.type:trigger.type===existingTrigger.type&&trigger.topic===existingTrigger.topic&&trigger.consumer===existingTrigger.consumer}function appendTrigger(lambda,trigger){let existingTriggers=Array.isArray(lambda.experimentalTriggers)?lambda.experimentalTriggers:[];existingTriggers.some(existing=>triggerMatches(trigger,existing))||(lambda.experimentalTriggers=[...existingTriggers,trigger])}async function streamToString(stream){let chunks=[];for await(let chunk of stream){let buffer=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);chunks.push(Uint8Array.from(buffer))}return Buffer.concat(chunks).toString("utf-8")}}});var require_dist6=__commonJS({"../cli-builder-integration/dist/index.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS2=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),src_exports={};__export(src_exports,{BuildRunner:()=>import_build_runner2.BuildRunner,InprocessBuildRunner:()=>import_build_runner2.InprocessBuildRunner,doBuild:()=>import_do_build.doBuild,executeBuilder:()=>import_execute_builder.executeBuilder,sortBuildsForExecution:()=>import_execute_builder.sortBuildsForExecution});module.exports=__toCommonJS2(src_exports);var import_build_runner2=require_build_runner(),import_execute_builder=require_execute_builder(),import_do_build=require_do_build()}});var import_chalk=__toESM(require_source(),1),import_dotenv=__toESM(require_main(),1),import_fs_extra=__toESM(require_lib(),1),import_build_utils2=__toESM(require_build_utils(),1);import{dirname,join as join2,relative,resolve}from"path";import{readdirSync,statSync}from"fs";var import_cli_builder_integration=__toESM(require_dist6(),1);var import_build_utils=__toESM(require_build_utils(),1),import_build_runner=__toESM(require_build_runner(),1);import{fork}from"node:child_process";import{readFileSync,unlinkSync}from"node:fs";import{join}from"node:path";function toError(error){return error instanceof Error?error:Object.assign(new Error,error)}function mergeWorkerMeta(target,workerMeta){for(let[key,value]of Object.entries(workerMeta)){let existing=target[key];if(existing instanceof Set&&value instanceof Set)for(let entry of value)existing.add(entry);else existing===!0&&typeof value!="object"||(target[key]=value)}}function canBuildInSubprocess({hasDetectedServices,builderPath}){return hasDetectedServices&&!!builderPath}function rehydrateFile(obj){if(obj.type==="FileBlob"){let blob=Object.assign(Object.create(import_build_utils.FileBlob.prototype),obj);if(obj.dataPath){blob.data=readFileSync(obj.dataPath);try{unlinkSync(obj.dataPath)}catch{}delete blob.dataPath}return blob}return obj.type==="FileRef"?Object.assign(Object.create(import_build_utils.FileRef.prototype),obj):Object.assign(Object.create(import_build_utils.FileFsRef.prototype),obj)}function rehydrateFiles(files){if(files)for(let name of Object.keys(files))files[name]=rehydrateFile(files[name])}function rehydrateDiagnostics(diagnostics){let result={};for(let[name,file]of Object.entries(diagnostics))result[name]=rehydrateFile(file);return result}function rehydrateOutput(output,seen){if(!output||typeof output!="object"||seen.has(output))return;seen.add(output);let obj=output;if(obj.type==="Lambda")rehydrateFiles(obj.files),Object.setPrototypeOf(obj,import_build_utils.Lambda.prototype);else if(obj.type==="EdgeFunction")rehydrateFiles(obj.files);else if(obj.type==="Prerender")obj.lambda&&rehydrateOutput(obj.lambda,seen),obj.fallback&&rehydrateOutput(obj.fallback,seen);else if(obj.type==="FileFsRef"||obj.type==="FileBlob"||obj.type==="FileRef"){let rehydrated=rehydrateFile(obj);Object.assign(obj,rehydrated),Object.setPrototypeOf(obj,Object.getPrototypeOf(rehydrated))}}function rehydrateResult(result,outputVersion){let output=(result&&"resultVersion"in result?result.result:result).output;if(!output)return;let seen=new Set;if(outputVersion===3)rehydrateOutput(output,seen);else for(let value of Object.values(output))rehydrateOutput(value,seen)}function createServiceLinePrefixer(serviceName,dest){let tag=`[vc:service:${serviceName}] `,pending="";return{onData(chunk){pending+=chunk;let newlineIndex=pending.lastIndexOf(`
8
8
  `);if(newlineIndex===-1)return;let complete=pending.slice(0,newlineIndex+1);pending=pending.slice(newlineIndex+1);let tagged=complete.split(`
9
9
  `).slice(0,-1).map(line=>`${tag}${line}`).join(`
10
10
  `);dest.write(`${tagged}