@vercel/cli-support 65.8.0 → 65.9.0-snapshot-c4002eb2617b
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.
- package/dist/chunks/add-EHNDQSPH.js +8 -0
- package/dist/chunks/add-QINN2GTA.js +8 -0
- package/dist/chunks/add-SEQOVWYP.js +8 -0
- package/dist/chunks/build-ATYGR3HB.js +7 -0
- package/dist/chunks/{chunk-O7IYJGOR.js → chunk-25B5SV4V.js} +1 -1
- package/dist/chunks/chunk-2CSCY66I.js +11 -0
- package/dist/chunks/{chunk-FQVSBXRY.js → chunk-2H4DUZJZ.js} +1 -1
- package/dist/chunks/{chunk-44XDCARR.js → chunk-2RXUQ72I.js} +1 -1
- package/dist/chunks/{chunk-EZL4AJXH.js → chunk-32AS5X7G.js} +1 -1
- package/dist/chunks/chunk-32NXYHYC.js +10 -0
- package/dist/chunks/{chunk-OTJNOMRV.js → chunk-375JVQYK.js} +1 -1
- package/dist/chunks/chunk-3H7HEK63.js +10 -0
- package/dist/chunks/{chunk-CJLRNGWY.js → chunk-3QECUY4S.js} +1 -1
- package/dist/chunks/{chunk-GKUHMS3A.js → chunk-3Y3FZLFN.js} +1 -1
- package/dist/chunks/{chunk-BLFPDEXE.js → chunk-46XT5J5W.js} +1 -1
- package/dist/chunks/{chunk-IECNFRTK.js → chunk-4BZ3DNGM.js} +1 -1
- package/dist/chunks/chunk-4CQKN5TW.js +10 -0
- package/dist/chunks/{chunk-FNOCIKAU.js → chunk-4HIRAB5V.js} +1 -1
- package/dist/chunks/{chunk-4UIMSZZB.js → chunk-4KM733OB.js} +1 -1
- package/dist/chunks/chunk-4ND2DRU5.js +15 -0
- package/dist/chunks/{chunk-6KCYUYUM.js → chunk-4VF5BZJP.js} +1 -1
- package/dist/chunks/{chunk-XUJA3RZD.js → chunk-4XFUHNFR.js} +1 -1
- package/dist/chunks/chunk-4Z3APEBF.js +7 -0
- package/dist/chunks/chunk-5CVEW3HD.js +12 -0
- package/dist/chunks/{chunk-LFOWP74R.js → chunk-5DXC4TE2.js} +1 -1
- package/dist/chunks/{chunk-KARAZGCO.js → chunk-5KKRDN5F.js} +1 -1
- package/dist/chunks/{constants-JAB7MRSK.js → chunk-5MDNVAE6.js} +1 -1
- package/dist/chunks/{chunk-HA2ICIB5.js → chunk-5TI3ZXW3.js} +1 -1
- package/dist/chunks/{chunk-PY5A73YH.js → chunk-5WFOL3XX.js} +1 -1
- package/dist/chunks/{chunk-IHNEF3BG.js → chunk-5XPWRDZN.js} +1 -1
- package/dist/chunks/chunk-5ZEROVK5.js +7 -0
- package/dist/chunks/{chunk-3LQ2ADXO.js → chunk-64UCX5JM.js} +1 -1
- package/dist/chunks/{chunk-A67TLHES.js → chunk-7FAO6DXJ.js} +1 -1
- package/dist/chunks/{chunk-AQA4JVKA.js → chunk-7JNBF5SB.js} +1 -1
- package/dist/chunks/{chunk-A6F3EE2O.js → chunk-7ULVGK67.js} +1 -1
- package/dist/chunks/{chunk-MCP63EVQ.js → chunk-7WY7ASKE.js} +1 -1
- package/dist/chunks/{chunk-LD42X7ZH.js → chunk-AX3V7N44.js} +1 -1
- package/dist/chunks/{chunk-753RQ6WV.js → chunk-BEAH4TA2.js} +1 -1
- package/dist/chunks/chunk-BRETAWE7.js +10 -0
- package/dist/chunks/{chunk-T2SRGJPU.js → chunk-BT5C6MCY.js} +1 -1
- package/dist/chunks/{chunk-H4DE2OFO.js → chunk-BV2JBHT5.js} +1 -1
- package/dist/chunks/{chunk-D3GYYGSS.js → chunk-BWS3ZOHJ.js} +1 -1
- package/dist/chunks/{chunk-QZEZCUUZ.js → chunk-CBA2KGXG.js} +13 -13
- package/dist/chunks/chunk-CBVVVYUP.js +10 -0
- package/dist/chunks/{chunk-KIMIK4SG.js → chunk-CGTD4QFC.js} +1 -1
- package/dist/chunks/{chunk-QR7PY5JS.js → chunk-CH5325V5.js} +1 -1
- package/dist/chunks/{chunk-5MHRCRIN.js → chunk-CMHL66LK.js} +1 -1
- package/dist/chunks/{chunk-WRC5CTUD.js → chunk-D4TD2KWH.js} +1 -1
- package/dist/chunks/{chunk-XBOGVOV5.js → chunk-D4ZEJM3T.js} +1 -1
- package/dist/chunks/{chunk-5O7CRJE5.js → chunk-D6REP5QQ.js} +1 -1
- package/dist/chunks/chunk-DASHFOKO.js +8 -0
- package/dist/chunks/{chunk-63DO6KMD.js → chunk-DL5B5I2H.js} +3 -3
- package/dist/chunks/{chunk-M4TIOVOP.js → chunk-DUPAU76G.js} +1 -1
- package/dist/chunks/{chunk-APNR444T.js → chunk-E7DYXF6G.js} +1 -1
- package/dist/chunks/{chunk-GP5MFCGO.js → chunk-ECQKK4JU.js} +1 -1
- package/dist/chunks/{chunk-JULKMXVP.js → chunk-EEFLZK52.js} +1 -1
- package/dist/chunks/{chunk-GP2FXUFE.js → chunk-EJ2RWXUL.js} +1 -1
- package/dist/chunks/{chunk-U3J7VS56.js → chunk-FBYA6LLM.js} +1 -1
- package/dist/chunks/{chunk-SOCGBVML.js → chunk-FVVOHGQE.js} +1 -1
- package/dist/chunks/{chunk-QLW5DCM4.js → chunk-FWTBSC7Z.js} +1 -1
- package/dist/chunks/{chunk-2OET5FWH.js → chunk-G2BNLRPU.js} +1 -1
- package/dist/chunks/{chunk-DBV6AB6T.js → chunk-G3LWP5CH.js} +1 -1
- package/dist/chunks/{chunk-YIOT5B5Z.js → chunk-G6HUSV7F.js} +1 -1
- package/dist/chunks/{chunk-7V2PXIVW.js → chunk-GCPPL24C.js} +1 -1
- package/dist/chunks/{chunk-3AXMZRAB.js → chunk-GCXUSXB4.js} +1 -1
- package/dist/chunks/{chunk-GZWYJT4C.js → chunk-GHEGWXH2.js} +1 -1
- package/dist/chunks/{chunk-YKNHA3RN.js → chunk-GIFIOAOW.js} +1 -1
- package/dist/chunks/{chunk-JRBPVMQO.js → chunk-GJCVOEC2.js} +1 -1
- package/dist/chunks/{chunk-ELQBQ2O5.js → chunk-GN5IAG3M.js} +1 -1
- package/dist/chunks/{chunk-HTFQFHPR.js → chunk-H34SGIVS.js} +1 -1
- package/dist/chunks/chunk-IDP63TCP.js +10 -0
- package/dist/chunks/{pkg-EDJQLCNP.js → chunk-ITQPDXXA.js} +1 -1
- package/dist/chunks/{chunk-XK3W6Q5I.js → chunk-IZ4GFKGR.js} +1 -1
- package/dist/chunks/{chunk-62FZFXPJ.js → chunk-JB6T3XEF.js} +1 -1
- package/dist/chunks/{chunk-TSKFDJ77.js → chunk-JJ2JHAGW.js} +1 -1
- package/dist/chunks/{chunk-V5A4EBV3.js → chunk-JOXGYP5S.js} +1 -1
- package/dist/chunks/{chunk-3DDEBTCC.js → chunk-JYWHC7YX.js} +1 -1
- package/dist/chunks/{chunk-YTZPQVGF.js → chunk-K3VUXKMV.js} +1 -1
- package/dist/chunks/{chunk-2QSNFVB6.js → chunk-K5YO4UD7.js} +1 -1
- package/dist/chunks/{chunk-TCEEQLD4.js → chunk-KHG6CZLZ.js} +1 -1
- package/dist/chunks/{chunk-KL6HNOFN.js → chunk-KOLCO2RH.js} +1 -1
- package/dist/chunks/{chunk-WZ2R4Z7N.js → chunk-KRPY5FHJ.js} +1 -1
- package/dist/chunks/{chunk-7E6UJXLR.js → chunk-KV2DYFUG.js} +1 -1
- package/dist/chunks/{chunk-3KSTUMR6.js → chunk-M73W4XNR.js} +1 -1
- package/dist/chunks/{chunk-EKB2DYCQ.js → chunk-MCJ5OFNP.js} +1 -1
- package/dist/chunks/{chunk-LOEU4R4Z.js → chunk-MOW3KNCP.js} +1 -1
- package/dist/chunks/chunk-MY4MONOH.js +7 -0
- package/dist/chunks/{chunk-SBBD2Q5A.js → chunk-NAU6URTI.js} +1 -1
- package/dist/chunks/{chunk-B3ETPBO4.js → chunk-NEUQZYBL.js} +2 -2
- package/dist/chunks/chunk-NFASCUXE.js +8 -0
- package/dist/chunks/{chunk-3P4Y46MS.js → chunk-NIS66BFX.js} +2 -2
- package/dist/chunks/chunk-NTUDWWSL.js +14 -0
- package/dist/chunks/{chunk-AEOG4E5G.js → chunk-O4CQRV2G.js} +1 -1
- package/dist/chunks/{chunk-4MP4HVBG.js → chunk-O7NJQXN6.js} +1 -1
- package/dist/chunks/{chunk-5GOQ3FBV.js → chunk-OVWDOWRV.js} +1 -1
- package/dist/chunks/{chunk-7EJ3BZ67.js → chunk-PLJKMCXU.js} +1 -1
- package/dist/chunks/{chunk-P2HBUDGR.js → chunk-Q4WEODW3.js} +1 -1
- package/dist/chunks/{chunk-KUNFE2M6.js → chunk-QANIGEPP.js} +1 -1
- package/dist/chunks/{chunk-T3S63EA3.js → chunk-QBOY2CXL.js} +1 -1
- package/dist/chunks/{chunk-37DIJCWK.js → chunk-QQA2OMXJ.js} +1 -1
- package/dist/chunks/{chunk-HNOZM6D4.js → chunk-QYNJCJYZ.js} +1 -1
- package/dist/chunks/{chunk-K2R3QPOC.js → chunk-R5ZLTWKB.js} +1 -1
- package/dist/chunks/chunk-RBIHS5QI.js +7 -0
- package/dist/chunks/{chunk-QTCS2HDX.js → chunk-RCFJTXSB.js} +1 -1
- package/dist/chunks/{chunk-T34C75TI.js → chunk-RCUDI7OF.js} +1 -1
- package/dist/chunks/{chunk-KDRCBWRY.js → chunk-RTJOQK2R.js} +1 -1
- package/dist/chunks/{chunk-FXEMEIST.js → chunk-T2FCF46I.js} +1 -1
- package/dist/chunks/{chunk-IHRM7L23.js → chunk-T5TOBY4D.js} +1 -1
- package/dist/chunks/{chunk-YRK2BCTJ.js → chunk-TD7AL545.js} +1 -1
- package/dist/chunks/{chunk-MDWYXLDB.js → chunk-TGQSMRQZ.js} +3 -3
- package/dist/chunks/{chunk-6V67VZJD.js → chunk-TMXIVQ45.js} +1 -1
- package/dist/chunks/{chunk-J52UJYOK.js → chunk-TRZDIAX3.js} +1 -1
- package/dist/chunks/{chunk-7BML2OR6.js → chunk-U6KJOCXX.js} +1 -1
- package/dist/chunks/{chunk-Y55DGB3L.js → chunk-UIJYRI3G.js} +1 -1
- package/dist/chunks/{chunk-NAXFG37F.js → chunk-UNASHUWQ.js} +1 -1
- package/dist/chunks/{chunk-3RXEJWYM.js → chunk-UZTDRGCW.js} +1 -1
- package/dist/chunks/{chunk-BHJLCFQ4.js → chunk-VMMSNGPS.js} +1 -1
- package/dist/chunks/{chunk-F76MNMH3.js → chunk-VR5ROBAO.js} +1 -1
- package/dist/chunks/{chunk-JESNVRVR.js → chunk-VRH7LWOC.js} +1 -1
- package/dist/chunks/{chunk-QIPUFI6P.js → chunk-VU3RBRDH.js} +1 -1
- package/dist/chunks/{chunk-ZRJKGAUT.js → chunk-W634OFUG.js} +3 -3
- package/dist/chunks/{chunk-SKLRHAGH.js → chunk-WFCGAYP5.js} +1 -1
- package/dist/chunks/{chunk-C4XT3PG4.js → chunk-WKYFWE37.js} +1 -1
- package/dist/chunks/{chunk-G7X2TVUO.js → chunk-WQQTVQZK.js} +1 -1
- package/dist/chunks/{chunk-YHFZIUXF.js → chunk-XBWISZCG.js} +1 -1
- package/dist/chunks/{chunk-RIAOB3RF.js → chunk-XOBLL6JP.js} +1 -1
- package/dist/chunks/chunk-XRIM4BUF.js +7 -0
- package/dist/chunks/{chunk-ZBJ44DRL.js → chunk-Y3ZO6WB7.js} +1 -1
- package/dist/chunks/chunk-Y5YXAXK3.js +13 -0
- package/dist/chunks/{chunk-YEPB52XE.js → chunk-Y6WXTTZS.js} +1 -1
- package/dist/chunks/{chunk-OV7G6RIQ.js → chunk-Y7YULJK7.js} +1 -1
- package/dist/chunks/{chunk-UAUVCOGS.js → chunk-YJQW3DDY.js} +1 -1
- package/dist/chunks/chunk-YYMLVSE2.js +12 -0
- package/dist/chunks/{chunk-45UDRX4C.js → chunk-ZBZPCKTW.js} +1 -1
- package/dist/chunks/{chunk-2B7U6BB5.js → chunk-ZGKJLJ47.js} +1 -1
- package/dist/chunks/chunk-ZS2WS4AM.js +7 -0
- package/dist/chunks/clear-BJBNWJJB.js +8 -0
- package/dist/chunks/compile-vercel-config-QH77NQ4B.js +7 -0
- package/dist/chunks/config-354DFLQE.js +8 -0
- package/dist/chunks/config-AXK2BGCA.js +7 -0
- package/dist/chunks/connect-git-provider-AWEOEEOO.js +7 -0
- package/dist/chunks/delete-GO7DLOJ3.js +9 -0
- package/dist/chunks/delete-IYWVEDBG.js +10 -0
- package/dist/chunks/{detect-projects-A4H2ZEAP.js → detect-projects-K7SVMH5T.js} +1 -1
- package/dist/chunks/detect-services-5P7KCKFK.js +7 -0
- package/dist/chunks/disable-LGVOQE3T.js +7 -0
- package/dist/chunks/discard-27X77XQE.js +14 -0
- package/dist/chunks/edit-2XY4JHTX.js +8 -0
- package/dist/chunks/edit-IECKJW64.js +9 -0
- package/dist/chunks/enable-AFDKCU3L.js +7 -0
- package/dist/chunks/{exec-7LB36K52.js → exec-UV73J2ZB.js} +1 -1
- package/dist/chunks/{export-AI2O22W5.js → export-K7JNA5NA.js} +1 -1
- package/dist/chunks/future-FFWMSADT.js +7 -0
- package/dist/chunks/generate-cert-for-deploy-SY44OYEY.js +7 -0
- package/dist/chunks/image-D54UXO4P.js +7 -0
- package/dist/chunks/import-builders-4DYFWAOD.js +7 -0
- package/dist/chunks/{inspect-OM5S5YQ2.js → inspect-3DLXFK6E.js} +1 -1
- package/dist/chunks/{inspect-4A67JORH.js → inspect-A2LKZQMT.js} +1 -1
- package/dist/chunks/{inspect-3NMNI7GY.js → inspect-H2EHB6IO.js} +1 -1
- package/dist/chunks/inspect-HCBQIEZG.js +13 -0
- package/dist/chunks/inspect-XRCF2YRP.js +9 -0
- package/dist/chunks/{list-TUJ7HCQK.js → list-AB25WHGO.js} +1 -1
- package/dist/chunks/list-CU66L4ZB.js +12 -0
- package/dist/chunks/{list-NEV4FBTY.js → list-HUCI73LP.js} +1 -1
- package/dist/chunks/login-5GIPMHCM.js +9 -0
- package/dist/chunks/login-XD3H356W.js +7 -0
- package/dist/chunks/logs-MCYUVB2U.js +7 -0
- package/dist/chunks/ls-46HG3NM2.js +8 -0
- package/dist/chunks/{ls-COOTTCRW.js → ls-DZTI7O7V.js} +1 -1
- package/dist/chunks/ls-FVI4QA2G.js +11 -0
- package/dist/chunks/{ls-OVM2DZYL.js → ls-GFWMSKJI.js} +1 -1
- package/dist/chunks/{ls-UY3KCDSF.js → ls-GVHHJ6PD.js} +1 -1
- package/dist/chunks/{ls-CVO4MCX5.js → ls-IMQKQEA5.js} +1 -1
- package/dist/chunks/ls-SNGWJI57.js +8 -0
- package/dist/chunks/mutate-AATP3ZZW.js +9 -0
- package/dist/chunks/native-self-update-75UJCHGZ.js +7 -0
- package/dist/chunks/notifications-X76ITPCJ.js +7 -0
- package/dist/chunks/open-FVOQGEWM.js +7 -0
- package/dist/chunks/openapi-KYC6JIXI.js +7 -0
- package/dist/chunks/permissions-N6JJSYGS.js +7 -0
- package/dist/chunks/{plugin-offer-4YTKDZGS.js → plugin-offer-UXUZ3PRE.js} +1 -1
- package/dist/chunks/prompt-missing-credentials-7UX2S26W.js +7 -0
- package/dist/chunks/publish-BG3UKM2Q.js +15 -0
- package/dist/chunks/pull-3NAMWMU6.js +7 -0
- package/dist/chunks/purchase-domain-if-available-7UQPSITN.js +7 -0
- package/dist/chunks/push-TZAIOAX5.js +7 -0
- package/dist/chunks/{query-NIMDIFLO.js → query-R7M64JYQ.js} +1 -1
- package/dist/chunks/reauthenticate-TOILE7L6.js +7 -0
- package/dist/chunks/reorder-V47PIQFO.js +10 -0
- package/dist/chunks/reply-5QZVOLHI.js +9 -0
- package/dist/chunks/resolve-7VONHDWK.js +12 -0
- package/dist/chunks/resolve-agent-team-DHPOJEQE.js +7 -0
- package/dist/chunks/restore-JLME37UW.js +16 -0
- package/dist/chunks/rm-2GT4SSDQ.js +8 -0
- package/dist/chunks/rm-4EPE3LBT.js +8 -0
- package/dist/chunks/rm-5B7XAOK3.js +8 -0
- package/dist/chunks/rm-JY3ACRPF.js +8 -0
- package/dist/chunks/rm-V2A5HTIT.js +8 -0
- package/dist/chunks/routes-S75L7Z7A.js +7 -0
- package/dist/chunks/rule-inspect-VPH5ZZ23.js +8 -0
- package/dist/chunks/schema-DYNINJQ7.js +14 -0
- package/dist/chunks/{schema-44U7GOQE.js → schema-I73FHHZS.js} +1 -1
- package/dist/chunks/select-org-DUL7FO5S.js +7 -0
- package/dist/chunks/set-YZA622KE.js +7 -0
- package/dist/chunks/setup-and-link-ZDP5OPLK.js +7 -0
- package/dist/chunks/{skills-XOH4Q7KK.js → skills-DZYJV7BE.js} +3 -3
- package/dist/chunks/statuspage-45LJ2XYT.js +7 -0
- package/dist/chunks/tags-DYVP7Q2S.js +7 -0
- package/dist/chunks/{types-6W3KAE2A.js → types-YA6BOCRV.js} +1 -1
- package/dist/chunks/{update-YLFMSPQF.js → update-T3W6JMTU.js} +1 -1
- package/dist/chunks/validate-config-XWZ7ZZ3G.js +7 -0
- package/dist/commands/build/index.js +1 -6
- package/dist/commands/deploy/index.js +14 -14
- package/dist/commands/dev/index.js +3 -3
- package/dist/commands/env/index.js +1 -1
- package/dist/commands/link/index.js +1 -1
- package/dist/commands/list/index.js +1 -1
- package/dist/commands/project/index.js +1 -1
- package/dist/commands-account.js +112 -91
- package/dist/commands-ai.js +2 -2
- package/dist/commands-blob.js +1 -1
- package/dist/commands-core.js +62 -44
- package/dist/commands-deployments.js +9 -6
- package/dist/commands-flags.js +4 -3
- package/dist/commands-integrations.js +98 -74
- package/dist/commands-observability.js +5 -5
- package/dist/commands-routing.js +154 -162
- package/dist/help.js +1 -1
- package/dist/index.js +5 -5
- package/dist/internal-build.js +1 -1
- package/dist/native-download.js +1 -1
- package/dist/package.json +57 -58
- package/dist/root-help-commands.mjs +1 -1
- package/dist/version.mjs +1 -1
- package/package.json +50 -51
- package/dist/chunks/add-3MWFJH54.js +0 -8
- package/dist/chunks/add-CJWCA3MM.js +0 -8
- package/dist/chunks/add-GLCVYEEN.js +0 -8
- package/dist/chunks/build-6RK6VECG.js +0 -7
- package/dist/chunks/chunk-2PYFJXKS.js +0 -14
- package/dist/chunks/chunk-5SMV2PPI.js +0 -10
- package/dist/chunks/chunk-7A5WO5KA.js +0 -8
- package/dist/chunks/chunk-CJHVHB2F.js +0 -8
- package/dist/chunks/chunk-EGPVNTKP.js +0 -7
- package/dist/chunks/chunk-GJB72ITS.js +0 -12
- package/dist/chunks/chunk-H3SJJO6S.js +0 -10
- package/dist/chunks/chunk-INH6RXBH.js +0 -9
- package/dist/chunks/chunk-IU6PHFPQ.js +0 -7
- package/dist/chunks/chunk-KAUKCHQF.js +0 -10
- package/dist/chunks/chunk-NDWGYZRT.js +0 -10
- package/dist/chunks/chunk-OLAG7Y3P.js +0 -10
- package/dist/chunks/chunk-TK2ILW2O.js +0 -21
- package/dist/chunks/chunk-WKZ6JSGZ.js +0 -7
- package/dist/chunks/chunk-X65XZSWS.js +0 -10
- package/dist/chunks/cjs-2SMN43VH.js +0 -54
- package/dist/chunks/clear-375VKVXY.js +0 -8
- package/dist/chunks/compile-vercel-config-LNRUSKTH.js +0 -7
- package/dist/chunks/config-GOYBATSI.js +0 -8
- package/dist/chunks/config-VAW454ZH.js +0 -7
- package/dist/chunks/connect-git-provider-7KRYVDFS.js +0 -7
- package/dist/chunks/delete-3SN6XFOW.js +0 -10
- package/dist/chunks/delete-W6BZHLGP.js +0 -9
- package/dist/chunks/detect-services-6L57MV5F.js +0 -7
- package/dist/chunks/disable-UUV5MYYH.js +0 -7
- package/dist/chunks/discard-Y6ZITZ2P.js +0 -14
- package/dist/chunks/edit-CVMUITFG.js +0 -9
- package/dist/chunks/edit-LLRI57RF.js +0 -8
- package/dist/chunks/enable-TFA6XWAA.js +0 -7
- package/dist/chunks/future-EZEU2CBY.js +0 -7
- package/dist/chunks/generate-cert-for-deploy-QP5BUOJL.js +0 -7
- package/dist/chunks/image-YLUF7SHR.js +0 -7
- package/dist/chunks/import-builders-ANLKHIYK.js +0 -7
- package/dist/chunks/inspect-3TRAN3SP.js +0 -9
- package/dist/chunks/inspect-VEUY4QJ2.js +0 -13
- package/dist/chunks/list-DJKKVFUL.js +0 -12
- package/dist/chunks/login-4HCFKDKL.js +0 -7
- package/dist/chunks/login-EPBJQDEK.js +0 -9
- package/dist/chunks/logs-Q7XXVFR3.js +0 -7
- package/dist/chunks/ls-3TKRCF4T.js +0 -8
- package/dist/chunks/ls-LS5J5ERG.js +0 -11
- package/dist/chunks/ls-OQQTUQFN.js +0 -8
- package/dist/chunks/mutate-I6QWCURL.js +0 -9
- package/dist/chunks/notifications-UKC5Z6AH.js +0 -7
- package/dist/chunks/open-CYATUDTT.js +0 -7
- package/dist/chunks/openapi-B7WSK7AU.js +0 -7
- package/dist/chunks/permissions-4ZYPHPOZ.js +0 -7
- package/dist/chunks/prompt-missing-credentials-4OKJMYW5.js +0 -7
- package/dist/chunks/publish-N6E7VTRK.js +0 -15
- package/dist/chunks/pull-LPIT3XUR.js +0 -7
- package/dist/chunks/purchase-domain-if-available-IS6UDPJT.js +0 -7
- package/dist/chunks/push-ETLU6OCC.js +0 -7
- package/dist/chunks/reauthenticate-TESIUM6U.js +0 -7
- package/dist/chunks/reorder-PQU2BQEE.js +0 -10
- package/dist/chunks/reply-RKDDYV5I.js +0 -9
- package/dist/chunks/resolve-ZF7BFXIW.js +0 -12
- package/dist/chunks/resolve-agent-team-QSIJ665W.js +0 -7
- package/dist/chunks/restore-U5A3BEFQ.js +0 -16
- package/dist/chunks/rm-7H5O3T7G.js +0 -8
- package/dist/chunks/rm-EPPMQEAV.js +0 -8
- package/dist/chunks/rm-FNMW2FPM.js +0 -8
- package/dist/chunks/rm-OZIA3DFM.js +0 -8
- package/dist/chunks/rm-W3VOR2ED.js +0 -8
- package/dist/chunks/routes-BLE5XZJE.js +0 -7
- package/dist/chunks/rule-inspect-YAVRRGAP.js +0 -8
- package/dist/chunks/schema-6SAZ7T2S.js +0 -14
- package/dist/chunks/select-org-L5FJVL5Q.js +0 -7
- package/dist/chunks/set-3NQXDGJV.js +0 -7
- package/dist/chunks/setup-and-link-H36NRP3A.js +0 -7
- package/dist/chunks/tags-CRG27GFL.js +0 -7
- /package/dist/chunks/{chunk-OO572JUC.js → chunk-DBT6PGEH.js} +0 -0
|
@@ -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{displayDetectedServices,readConfig,setupAndLink}from"../../chunks/chunk-63DO6KMD.js";import"../../chunks/chunk-4UIMSZZB.js";import{loadVercelConfig,tryDetectServices}from"../../chunks/chunk-GJB72ITS.js";import"../../chunks/chunk-COD3WAUI.js";import{FIX_BY_CODE,createErrorReporter,import_write_build_result,require_detect_builders_with_services,require_get_files,require_mime_types,require_schedule_entrypoint,require_service_schedules,toDiagnostic}from"../../chunks/chunk-TCEEQLD4.js";import{importBuilders,require_npa}from"../../chunks/chunk-BLFPDEXE.js";import"../../chunks/chunk-4CACOKMS.js";import"../../chunks/chunk-QHJLRTVY.js";import{decodeJwt}from"../../chunks/chunk-S3L2OHPO.js";import{require_fast_deep_equal}from"../../chunks/chunk-MCRKBVZA.js";import{LOCAL_SCHEDULES_SESSION_HEADER,createLocalSchedulesSession}from"../../chunks/chunk-SF4E3AQ3.js";import"../../chunks/chunk-KL6HNOFN.js";import{promptExperimentalServicesMigration}from"../../chunks/chunk-QTCS2HDX.js";import{validateConfig}from"../../chunks/chunk-EGPVNTKP.js";import{require_brace_expansion,require_dist as require_dist3,require_dist2 as require_dist4,require_minimatch}from"../../chunks/chunk-3P4Y46MS.js";import{pickOverrides}from"../../chunks/chunk-FNOCIKAU.js";import{require_raw_body}from"../../chunks/chunk-XOETL6DB.js";import{VERCEL_OIDC_TOKEN}from"../../chunks/chunk-KUNFE2M6.js";import{pullEnvRecords}from"../../chunks/chunk-PY5A73YH.js";import{require_frameworks}from"../../chunks/chunk-6Y2ZL5XJ.js";import"../../chunks/chunk-WRC5CTUD.js";import{readJSONFile}from"../../chunks/chunk-KARAZGCO.js";import{require_json_parse_better_errors}from"../../chunks/chunk-25565AGS.js";import{require_main}from"../../chunks/chunk-BHJLCFQ4.js";import"../../chunks/chunk-7YKFF6CE.js";import"../../chunks/chunk-JULKMXVP.js";import"../../chunks/chunk-YRK2BCTJ.js";import"../../chunks/chunk-IHNEF3BG.js";import{getUpdateCommand}from"../../chunks/chunk-GKUHMS3A.js";import"../../chunks/chunk-BPUANOGW.js";import"../../chunks/chunk-NAXFG37F.js";import"../../chunks/chunk-4ELZOAQH.js";import"../../chunks/chunk-JUAHDOL6.js";import"../../chunks/chunk-UI2H2EIM.js";import"../../chunks/chunk-UUDE44NV.js";import{getEnabledProtection}from"../../chunks/chunk-AEOG4E5G.js";import"../../chunks/chunk-VT6RIZJH.js";import"../../chunks/chunk-NDWGYZRT.js";import"../../chunks/chunk-QIPUFI6P.js";import"../../chunks/chunk-6KCYUYUM.js";import"../../chunks/chunk-PVASGBEF.js";import{printProjectNotFoundError}from"../../chunks/chunk-ZBJ44DRL.js";import"../../chunks/chunk-7A5WO5KA.js";import"../../chunks/chunk-J24BABG4.js";import"../../chunks/chunk-U4Z2MMOF.js";import{external_exports}from"../../chunks/chunk-2NABMKFV.js";import"../../chunks/chunk-IQ7FPAI4.js";import"../../chunks/chunk-T34C75TI.js";import"../../chunks/chunk-GD7AV7BO.js";import"../../chunks/chunk-OTJNOMRV.js";import"../../chunks/chunk-2QSNFVB6.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import{getTeams}from"../../chunks/chunk-YEPB52XE.js";import{DEV_QUEUE_API_PREFIX,DEV_QUEUE_DEFAULT_PORT,DEV_QUEUE_PROXY_PREFIX,DEV_RESOURCE_TOKEN,DEV_RUNTIME_CACHE_DEFAULT_PORT,DEV_SCHEDULES_DEFAULT_PORT,DEV_SCHEDULES_PROXY_PREFIX,devCommand,getDevQueueEnv,getDevSchedulesEnv,isValidDevResourceHost,listenOnDevResourcePort}from"../../chunks/chunk-7E6UJXLR.js";import{require_dist as require_dist2}from"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-7V2PXIVW.js";import{printError}from"../../chunks/chunk-D3GYYGSS.js";import{help,remoteText}from"../../chunks/chunk-33U57CNE.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import{detectExplicitScope}from"../../chunks/chunk-IU6PHFPQ.js";import{TelemetryClient}from"../../chunks/chunk-SBBD2Q5A.js";import"../../chunks/chunk-2EYYB6YN.js";import{isNativeBinaryInstall}from"../../chunks/chunk-NWGBDBZI.js";import{buildCommandWithYes,outputActionRequired}from"../../chunks/chunk-KAUKCHQF.js";import"../../chunks/chunk-QLW5DCM4.js";import{VERCEL_DIR,findRepoRoot,getLinkedProject,getLocalPathConfig,getUser,getVercelDirectory,highlight,localConfigFlagPath,require_dist2 as require_dist5,require_lib,require_pluralize,resolveProjectCwd,ua_default}from"../../chunks/chunk-QZEZCUUZ.js";import{printAlignedLabel}from"../../chunks/chunk-3LQ2ADXO.js";import{getGlobalPathConfig}from"../../chunks/chunk-MCP63EVQ.js";import"../../chunks/chunk-4NTBYNFR.js";import{parseArguments}from"../../chunks/chunk-KIMIK4SG.js";import"../../chunks/chunk-F53OKXYI.js";import{warnDeprecatedSubcommand}from"../../chunks/chunk-JRBPVMQO.js";import"../../chunks/chunk-LUX4PBJL.js";import"../../chunks/chunk-OPORM35X.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import"../../chunks/chunk-OCR5CRTH.js";import"../../chunks/chunk-4SAVH3H7.js";import{APIError,CantParseJSONFile,LambdaSizeExceededError,MissingDotenvVarsError,NowError,isAPIError,require_bytes}from"../../chunks/chunk-FXEMEIST.js";import{cmd,getCommandName,getCommandNamePlain,getTitleName}from"../../chunks/chunk-JESNVRVR.js";import{Diagnostic,defineDiagnostics,init_dist,link_default,output_manager_default,require_build_utils}from"../../chunks/chunk-ZRJKGAUT.js";import"../../chunks/chunk-BLUPZPAS.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import"../../chunks/chunk-YHPPP3SF.js";import{pkg_default}from"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-PUKYAALC.js";import{getFlagsSpecification}from"../../chunks/chunk-YPPDRKVC.js";import{chars_default}from"../../chunks/chunk-2BKALEOP.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import{require_supports_color}from"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BULSRTQE.js";import"../../chunks/chunk-BRQUZ5NC.js";import"../../chunks/chunk-5O7CRJE5.js";import{directFetch,getFetchDispatcher}from"../../chunks/chunk-U3J7VS56.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-SCV7XEEO.js";import{__commonJS,__require,__toESM}from"../../chunks/chunk-BZENIQ7N.js";var require_eventemitter3=__commonJS({"../../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(exports,module){"use strict";var has=Object.prototype.hasOwnProperty,prefix="~";function Events(){}Object.create&&(Events.prototype=Object.create(null),new Events().__proto__||(prefix=!1));function EE(fn,context,once2){this.fn=fn,this.context=context,this.once=once2||!1}function addListener(emitter,event,fn,context,once2){if(typeof fn!="function")throw new TypeError("The listener must be a function");var listener=new EE(fn,context||emitter,once2),evt=prefix?prefix+event:event;return emitter._events[evt]?emitter._events[evt].fn?emitter._events[evt]=[emitter._events[evt],listener]:emitter._events[evt].push(listener):(emitter._events[evt]=listener,emitter._eventsCount++),emitter}function clearEvent(emitter,evt){--emitter._eventsCount===0?emitter._events=new Events:delete emitter._events[evt]}function EventEmitter(){this._events=new Events,this._eventsCount=0}EventEmitter.prototype.eventNames=function(){var names=[],events,name;if(this._eventsCount===0)return names;for(name in events=this._events)has.call(events,name)&&names.push(prefix?name.slice(1):name);return Object.getOwnPropertySymbols?names.concat(Object.getOwnPropertySymbols(events)):names};EventEmitter.prototype.listeners=function(event){var evt=prefix?prefix+event:event,handlers=this._events[evt];if(!handlers)return[];if(handlers.fn)return[handlers.fn];for(var i=0,l=handlers.length,ee=new Array(l);i<l;i++)ee[i]=handlers[i].fn;return ee};EventEmitter.prototype.listenerCount=function(event){var evt=prefix?prefix+event:event,listeners=this._events[evt];return listeners?listeners.fn?1:listeners.length:0};EventEmitter.prototype.emit=function(event,a1,a2,a3,a4,a5){var evt=prefix?prefix+event:event;if(!this._events[evt])return!1;var listeners=this._events[evt],len=arguments.length,args,i;if(listeners.fn){switch(listeners.once&&this.removeListener(event,listeners.fn,void 0,!0),len){case 1:return listeners.fn.call(listeners.context),!0;case 2:return listeners.fn.call(listeners.context,a1),!0;case 3:return listeners.fn.call(listeners.context,a1,a2),!0;case 4:return listeners.fn.call(listeners.context,a1,a2,a3),!0;case 5:return listeners.fn.call(listeners.context,a1,a2,a3,a4),!0;case 6:return listeners.fn.call(listeners.context,a1,a2,a3,a4,a5),!0}for(i=1,args=new Array(len-1);i<len;i++)args[i-1]=arguments[i];listeners.fn.apply(listeners.context,args)}else{var length=listeners.length,j;for(i=0;i<length;i++)switch(listeners[i].once&&this.removeListener(event,listeners[i].fn,void 0,!0),len){case 1:listeners[i].fn.call(listeners[i].context);break;case 2:listeners[i].fn.call(listeners[i].context,a1);break;case 3:listeners[i].fn.call(listeners[i].context,a1,a2);break;case 4:listeners[i].fn.call(listeners[i].context,a1,a2,a3);break;default:if(!args)for(j=1,args=new Array(len-1);j<len;j++)args[j-1]=arguments[j];listeners[i].fn.apply(listeners[i].context,args)}}return!0};EventEmitter.prototype.on=function(event,fn,context){return addListener(this,event,fn,context,!1)};EventEmitter.prototype.once=function(event,fn,context){return addListener(this,event,fn,context,!0)};EventEmitter.prototype.removeListener=function(event,fn,context,once2){var evt=prefix?prefix+event:event;if(!this._events[evt])return this;if(!fn)return clearEvent(this,evt),this;var listeners=this._events[evt];if(listeners.fn)listeners.fn===fn&&(!once2||listeners.once)&&(!context||listeners.context===context)&&clearEvent(this,evt);else{for(var i=0,events=[],length=listeners.length;i<length;i++)(listeners[i].fn!==fn||once2&&!listeners[i].once||context&&listeners[i].context!==context)&&events.push(listeners[i]);events.length?this._events[evt]=events.length===1?events[0]:events:clearEvent(this,evt)}return this};EventEmitter.prototype.removeAllListeners=function(event){var evt;return event?(evt=prefix?prefix+event:event,this._events[evt]&&clearEvent(this,evt)):(this._events=new Events,this._eventsCount=0),this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.addListener=EventEmitter.prototype.on;EventEmitter.prefixed=prefix;EventEmitter.EventEmitter=EventEmitter;typeof module<"u"&&(module.exports=EventEmitter)}});var require_requires_port=__commonJS({"../../node_modules/.pnpm/requires-port@1.0.0/node_modules/requires-port/index.js"(exports,module){"use strict";module.exports=function(port,protocol){if(protocol=protocol.split(":")[0],port=+port,!port)return!1;switch(protocol){case"http":case"ws":return port!==80;case"https":case"wss":return port!==443;case"ftp":return port!==21;case"gopher":return port!==70;case"file":return!1}return port!==0}}});var require_common=__commonJS({"../../node_modules/.pnpm/http-proxy-node16@1.0.6_debug@3.1.0/node_modules/http-proxy-node16/lib/http-proxy/common.js"(exports){var common=exports,url4=__require("url"),extend=Object.assign,required=require_requires_port(),upgradeHeader=/(^|,)\s*upgrade\s*($|,)/i,isSSL=/^https|wss/;common.isSSL=isSSL;common.setupOutgoing=function(outgoing,options,req,forward){outgoing.port=options[forward||"target"].port||(isSSL.test(options[forward||"target"].protocol)?443:80),["host","hostname","socketPath","pfx","key","passphrase","cert","ca","ciphers","secureProtocol"].forEach(function(e){outgoing[e]=options[forward||"target"][e]}),outgoing.method=options.method||req.method,outgoing.headers=extend({},req.headers),options.headers&&extend(outgoing.headers,options.headers),options.auth&&(outgoing.auth=options.auth),options.ca&&(outgoing.ca=options.ca),isSSL.test(options[forward||"target"].protocol)&&(outgoing.rejectUnauthorized=typeof options.secure>"u"?!0:options.secure),outgoing.agent=options.agent||!1,outgoing.localAddress=options.localAddress,outgoing.agent||(outgoing.headers=outgoing.headers||{},(typeof outgoing.headers.connection!="string"||!upgradeHeader.test(outgoing.headers.connection))&&(outgoing.headers.connection="close"));var target=options[forward||"target"],targetPath=target&&options.prependPath!==!1&&target.path||"",outgoingPath=options.toProxy?req.url:url4.parse(req.url).path||"";return outgoingPath=options.ignorePath?"":outgoingPath,outgoing.path=common.urlJoin(targetPath,outgoingPath),options.changeOrigin&&(outgoing.headers.host=required(outgoing.port,options[forward||"target"].protocol)&&!hasPort(outgoing.host)?outgoing.host+":"+outgoing.port:outgoing.host),outgoing};common.setupSocket=function(socket){return socket.setTimeout(0),socket.setNoDelay(!0),socket.setKeepAlive(!0,0),socket};common.getPort=function(req){var res=req.headers.host?req.headers.host.match(/:(\d+)/):"";return res?res[1]:common.hasEncryptedConnection(req)?"443":"80"};common.hasEncryptedConnection=function(req){return!!(req.connection.encrypted||req.connection.pair)};common.urlJoin=function(){var args=Array.prototype.slice.call(arguments),queryParams=[],queryParamRaw="",retSegs;return args.forEach((url5,index)=>{var qpStart=url5.indexOf("?");qpStart!==-1&&(queryParams.push(url5.substring(qpStart+1)),args[index]=url5.substring(0,qpStart))}),queryParamRaw=queryParams.filter(Boolean).join("&"),retSegs=args.filter(Boolean).join("/").replace(/\/+/g,"/").replace("http:/","http://").replace("https:/","https://"),queryParamRaw?retSegs+"?"+queryParamRaw:retSegs};common.rewriteCookieProperty=function rewriteCookieProperty(header,config,property){return Array.isArray(header)?header.map(function(headerElement){return rewriteCookieProperty(headerElement,config,property)}):header.replace(new RegExp("(;\\s*"+property+"=)([^;]+)","i"),function(match,prefix,previousValue){var newValue;if(previousValue in config)newValue=config[previousValue];else if("*"in config)newValue=config["*"];else return match;return newValue?prefix+newValue:""})};function hasPort(host){return!!~host.indexOf(":")}}});var require_web_outgoing=__commonJS({"../../node_modules/.pnpm/http-proxy-node16@1.0.6_debug@3.1.0/node_modules/http-proxy-node16/lib/http-proxy/passes/web-outgoing.js"(exports,module){var url4=__require("url"),common=require_common(),redirectRegex=/^201|30(1|2|7|8)$/;module.exports={removeChunked:function(req,res,proxyRes){req.httpVersion==="1.0"&&delete proxyRes.headers["transfer-encoding"]},setConnection:function(req,res,proxyRes){req.httpVersion==="1.0"?proxyRes.headers.connection=req.headers.connection||"close":req.httpVersion!=="2.0"&&!proxyRes.headers.connection&&(proxyRes.headers.connection=req.headers.connection||"keep-alive")},setRedirectHostRewrite:function(req,res,proxyRes,options){if((options.hostRewrite||options.autoRewrite||options.protocolRewrite)&&proxyRes.headers.location&&redirectRegex.test(proxyRes.statusCode)){var target=url4.parse(options.target),u=url4.parse(proxyRes.headers.location);if(target.host!=u.host)return;options.hostRewrite?u.host=options.hostRewrite:options.autoRewrite&&(u.host=req.headers.host),options.protocolRewrite&&(u.protocol=options.protocolRewrite),proxyRes.headers.location=u.format()}},writeHeaders:function(req,res,proxyRes,options){var rewriteCookieDomainConfig=options.cookieDomainRewrite,rewriteCookiePathConfig=options.cookiePathRewrite,preserveHeaderKeyCase=options.preserveHeaderKeyCase,rawHeaderKeyMap,setHeader=function(key2,header){header!=null&&(rewriteCookieDomainConfig&&key2.toLowerCase()==="set-cookie"&&(header=common.rewriteCookieProperty(header,rewriteCookieDomainConfig,"domain")),rewriteCookiePathConfig&&key2.toLowerCase()==="set-cookie"&&(header=common.rewriteCookieProperty(header,rewriteCookiePathConfig,"path")),res.setHeader(String(key2).trim(),header))};if(typeof rewriteCookieDomainConfig=="string"&&(rewriteCookieDomainConfig={"*":rewriteCookieDomainConfig}),typeof rewriteCookiePathConfig=="string"&&(rewriteCookiePathConfig={"*":rewriteCookiePathConfig}),preserveHeaderKeyCase&&proxyRes.rawHeaders!=null){rawHeaderKeyMap={};for(var i=0;i<proxyRes.rawHeaders.length;i+=2){var key=proxyRes.rawHeaders[i];rawHeaderKeyMap[key.toLowerCase()]=key}}Object.keys(proxyRes.headers).forEach(function(key2){var header=proxyRes.headers[key2];preserveHeaderKeyCase&&rawHeaderKeyMap&&(key2=rawHeaderKeyMap[key2]||key2),setHeader(key2,header)})},writeStatusCode:function(req,res,proxyRes){proxyRes.statusMessage?(res.statusCode=proxyRes.statusCode,res.statusMessage=proxyRes.statusMessage):res.statusCode=proxyRes.statusCode}}}});var require_ms2=__commonJS({"../../node_modules/.pnpm/ms@2.0.0/node_modules/ms/index.js"(exports,module){var s=1e3,m=s*60,h=m*60,d=h*24,y=d*365.25;module.exports=function(val,options){options=options||{};var type=typeof val;if(type==="string"&&val.length>0)return parse2(val);if(type==="number"&&isNaN(val)===!1)return options.long?fmtLong(val):fmtShort(val);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(val))};function parse2(str){if(str=String(str),!(str.length>100)){var match=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);if(match){var n=parseFloat(match[1]),type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function fmtShort(ms9){return ms9>=d?Math.round(ms9/d)+"d":ms9>=h?Math.round(ms9/h)+"h":ms9>=m?Math.round(ms9/m)+"m":ms9>=s?Math.round(ms9/s)+"s":ms9+"ms"}function fmtLong(ms9){return plural3(ms9,d,"day")||plural3(ms9,h,"hour")||plural3(ms9,m,"minute")||plural3(ms9,s,"second")||ms9+" ms"}function plural3(ms9,n,name){if(!(ms9<n))return ms9<n*1.5?Math.floor(ms9/n)+" "+name:Math.ceil(ms9/n)+" "+name+"s"}}});var require_debug=__commonJS({"../../node_modules/.pnpm/debug@3.1.0/node_modules/debug/src/debug.js"(exports,module){exports=module.exports=createDebug.debug=createDebug.default=createDebug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=require_ms2();exports.instances=[];exports.names=[];exports.skips=[];exports.formatters={};function selectColor(namespace){var hash=0,i;for(i in namespace)hash=(hash<<5)-hash+namespace.charCodeAt(i),hash|=0;return exports.colors[Math.abs(hash)%exports.colors.length]}function createDebug(namespace){var prevTime;function debug(){if(debug.enabled){var self2=debug,curr=+new Date,ms9=curr-(prevTime||curr);self2.diff=ms9,self2.prev=prevTime,self2.curr=curr,prevTime=curr;for(var args=new Array(arguments.length),i=0;i<args.length;i++)args[i]=arguments[i];args[0]=exports.coerce(args[0]),typeof args[0]!="string"&&args.unshift("%O");var index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,function(match,format){if(match==="%%")return match;index++;var formatter=exports.formatters[format];if(typeof formatter=="function"){var val=args[index];match=formatter.call(self2,val),args.splice(index,1),index--}return match}),exports.formatArgs.call(self2,args);var logFn=debug.log||exports.log||console.log.bind(console);logFn.apply(self2,args)}}return debug.namespace=namespace,debug.enabled=exports.enabled(namespace),debug.useColors=exports.useColors(),debug.color=selectColor(namespace),debug.destroy=destroy,typeof exports.init=="function"&&exports.init(debug),exports.instances.push(debug),debug}function destroy(){var index=exports.instances.indexOf(this);return index!==-1?(exports.instances.splice(index,1),!0):!1}function enable(namespaces){exports.save(namespaces),exports.names=[],exports.skips=[];var i,split=(typeof namespaces=="string"?namespaces:"").split(/[\s,]+/),len=split.length;for(i=0;i<len;i++)split[i]&&(namespaces=split[i].replace(/\*/g,".*?"),namespaces[0]==="-"?exports.skips.push(new RegExp("^"+namespaces.substr(1)+"$")):exports.names.push(new RegExp("^"+namespaces+"$")));for(i=0;i<exports.instances.length;i++){var instance=exports.instances[i];instance.enabled=exports.enabled(instance.namespace)}}function disable(){exports.enable("")}function enabled(name){if(name[name.length-1]==="*")return!0;var i,len;for(i=0,len=exports.skips.length;i<len;i++)if(exports.skips[i].test(name))return!1;for(i=0,len=exports.names.length;i<len;i++)if(exports.names[i].test(name))return!0;return!1}function coerce(val){return val instanceof Error?val.stack||val.message:val}}});var require_browser=__commonJS({"../../node_modules/.pnpm/debug@3.1.0/node_modules/debug/src/browser.js"(exports,module){exports=module.exports=require_debug();exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.storage=typeof chrome<"u"&&typeof chrome.storage<"u"?chrome.storage.local:localstorage();exports.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function useColors(){return typeof window<"u"&&window.process&&window.process.type==="renderer"?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}exports.formatters.j=function(v){try{return JSON.stringify(v)}catch(err){return"[UnexpectedJSONParseError]: "+err.message}};function formatArgs(args){var useColors2=this.useColors;if(args[0]=(useColors2?"%c":"")+this.namespace+(useColors2?" %c":" ")+args[0]+(useColors2?"%c ":" ")+"+"+exports.humanize(this.diff),!!useColors2){var c="color: "+this.color;args.splice(1,0,c,"color: inherit");var index=0,lastC=0;args[0].replace(/%[a-zA-Z%]/g,function(match){match!=="%%"&&(index++,match==="%c"&&(lastC=index))}),args.splice(lastC,0,c)}}function log(){return typeof console=="object"&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{namespaces==null?exports.storage.removeItem("debug"):exports.storage.debug=namespaces}catch{}}function load(){var r;try{r=exports.storage.debug}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}exports.enable(load());function localstorage(){try{return window.localStorage}catch{}}}});var require_node=__commonJS({"../../node_modules/.pnpm/debug@3.1.0/node_modules/debug/src/node.js"(exports,module){var tty=__require("tty"),util=__require("util");exports=module.exports=require_debug();exports.init=init;exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.colors=[6,2,3,4,5,1];try{supportsColor=require_supports_color(),supportsColor&&supportsColor.level>=2&&(exports.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}var supportsColor;exports.inspectOpts=Object.keys(process.env).filter(function(key){return/^debug_/i.test(key)}).reduce(function(obj,key){var prop=key.substring(6).toLowerCase().replace(/_([a-z])/g,function(_,k){return k.toUpperCase()}),val=process.env[key];return/^(yes|on|true|enabled)$/i.test(val)?val=!0:/^(no|off|false|disabled)$/i.test(val)?val=!1:val==="null"?val=null:val=Number(val),obj[prop]=val,obj},{});function useColors(){return"colors"in exports.inspectOpts?!!exports.inspectOpts.colors:tty.isatty(process.stderr.fd)}exports.formatters.o=function(v){return this.inspectOpts.colors=this.useColors,util.inspect(v,this.inspectOpts).split(`
|
|
7
|
+
import{displayDetectedServices,readConfig,setupAndLink}from"../../chunks/chunk-DL5B5I2H.js";import{loadVercelConfig,tryDetectServices}from"../../chunks/chunk-YYMLVSE2.js";import"../../chunks/chunk-4KM733OB.js";import{FIX_BY_CODE,createErrorReporter,import_write_build_result,require_detect_builders_with_services,require_get_files,require_mime_types,require_schedule_entrypoint,require_service_schedules,toDiagnostic}from"../../chunks/chunk-KHG6CZLZ.js";import{importBuilders,require_npa}from"../../chunks/chunk-46XT5J5W.js";import"../../chunks/chunk-4CACOKMS.js";import"../../chunks/chunk-QHJLRTVY.js";import"../../chunks/chunk-COD3WAUI.js";import{decodeJwt}from"../../chunks/chunk-S3L2OHPO.js";import{require_fast_deep_equal}from"../../chunks/chunk-MCRKBVZA.js";import{LOCAL_SCHEDULES_SESSION_HEADER,createLocalSchedulesSession}from"../../chunks/chunk-SF4E3AQ3.js";import{hasDeployment}from"../../chunks/chunk-2CSCY66I.js";import"../../chunks/chunk-KOLCO2RH.js";import{promptExperimentalServicesMigration}from"../../chunks/chunk-RCFJTXSB.js";import"../../chunks/chunk-XRIM4BUF.js";import{validateConfig}from"../../chunks/chunk-RBIHS5QI.js";import{require_brace_expansion,require_dist as require_dist3,require_dist2 as require_dist4,require_minimatch}from"../../chunks/chunk-NIS66BFX.js";import{pickOverrides}from"../../chunks/chunk-4HIRAB5V.js";import{require_raw_body}from"../../chunks/chunk-XOETL6DB.js";import{VERCEL_OIDC_TOKEN}from"../../chunks/chunk-QANIGEPP.js";import{pullEnvRecords}from"../../chunks/chunk-5WFOL3XX.js";import{require_frameworks}from"../../chunks/chunk-6Y2ZL5XJ.js";import"../../chunks/chunk-D4TD2KWH.js";import{require_main}from"../../chunks/chunk-VMMSNGPS.js";import"../../chunks/chunk-7YKFF6CE.js";import"../../chunks/chunk-EEFLZK52.js";import"../../chunks/chunk-TD7AL545.js";import"../../chunks/chunk-5XPWRDZN.js";import{getUpdateCommand}from"../../chunks/chunk-3Y3FZLFN.js";import"../../chunks/chunk-BPUANOGW.js";import{readJSONFile}from"../../chunks/chunk-5KKRDN5F.js";import{require_json_parse_better_errors}from"../../chunks/chunk-25565AGS.js";import"../../chunks/chunk-UNASHUWQ.js";import"../../chunks/chunk-4ELZOAQH.js";import"../../chunks/chunk-JUAHDOL6.js";import"../../chunks/chunk-UI2H2EIM.js";import"../../chunks/chunk-UUDE44NV.js";import{getEnabledProtection}from"../../chunks/chunk-O4CQRV2G.js";import"../../chunks/chunk-VT6RIZJH.js";import"../../chunks/chunk-IDP63TCP.js";import"../../chunks/chunk-VU3RBRDH.js";import"../../chunks/chunk-4VF5BZJP.js";import"../../chunks/chunk-PVASGBEF.js";import{printProjectNotFoundError}from"../../chunks/chunk-Y3ZO6WB7.js";import"../../chunks/chunk-NFASCUXE.js";import"../../chunks/chunk-J24BABG4.js";import"../../chunks/chunk-U4Z2MMOF.js";import{external_exports}from"../../chunks/chunk-2NABMKFV.js";import"../../chunks/chunk-IQ7FPAI4.js";import"../../chunks/chunk-RCUDI7OF.js";import"../../chunks/chunk-GD7AV7BO.js";import"../../chunks/chunk-375JVQYK.js";import"../../chunks/chunk-K5YO4UD7.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import{getTeams}from"../../chunks/chunk-Y6WXTTZS.js";import{DEV_QUEUE_API_PREFIX,DEV_QUEUE_DEFAULT_PORT,DEV_QUEUE_PROXY_PREFIX,DEV_RESOURCE_TOKEN,DEV_RUNTIME_CACHE_DEFAULT_PORT,DEV_SCHEDULES_DEFAULT_PORT,DEV_SCHEDULES_PROXY_PREFIX,devCommand,getDevQueueEnv,getDevSchedulesEnv,isValidDevResourceHost,listenOnDevResourcePort}from"../../chunks/chunk-KV2DYFUG.js";import{require_dist as require_dist2}from"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-GCPPL24C.js";import{printError}from"../../chunks/chunk-BWS3ZOHJ.js";import{help,remoteText}from"../../chunks/chunk-33U57CNE.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import{detectExplicitScope}from"../../chunks/chunk-5ZEROVK5.js";import{TelemetryClient}from"../../chunks/chunk-NAU6URTI.js";import"../../chunks/chunk-2EYYB6YN.js";import{isNativeBinaryInstall}from"../../chunks/chunk-NWGBDBZI.js";import{buildCommandWithYes,outputActionRequired}from"../../chunks/chunk-32NXYHYC.js";import"../../chunks/chunk-FWTBSC7Z.js";import{VERCEL_DIR,findRepoRoot,getLinkedProject,getLocalPathConfig,getUser,getVercelDirectory,highlight,localConfigFlagPath,require_dist2 as require_dist5,require_lib,require_pluralize,resolveProjectCwd}from"../../chunks/chunk-CBA2KGXG.js";import{printAlignedLabel}from"../../chunks/chunk-64UCX5JM.js";import{ua_default}from"../../chunks/chunk-ITQPDXXA.js";import{getGlobalPathConfig}from"../../chunks/chunk-7WY7ASKE.js";import"../../chunks/chunk-4NTBYNFR.js";import{parseArguments}from"../../chunks/chunk-CGTD4QFC.js";import"../../chunks/chunk-F53OKXYI.js";import{warnDeprecatedSubcommand}from"../../chunks/chunk-GJCVOEC2.js";import"../../chunks/chunk-LUX4PBJL.js";import"../../chunks/chunk-OPORM35X.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import"../../chunks/chunk-4SAVH3H7.js";import{APIError,CantParseJSONFile,LambdaSizeExceededError,MissingDotenvVarsError,NowError,isAPIError,require_bytes}from"../../chunks/chunk-T2FCF46I.js";import{cmd,getCommandName,getCommandNamePlain,getTitleName}from"../../chunks/chunk-VRH7LWOC.js";import{pkg_default}from"../../chunks/chunk-DBT6PGEH.js";import{Diagnostic,defineDiagnostics,init_dist,link_default,output_manager_default}from"../../chunks/chunk-W634OFUG.js";import"../../chunks/chunk-BLUPZPAS.js";import"../../chunks/chunk-ZS2WS4AM.js";import{require_build_utils}from"../../chunks/chunk-5MDNVAE6.js";import"../../chunks/chunk-OCR5CRTH.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import"../../chunks/chunk-YHPPP3SF.js";import"../../chunks/chunk-PUKYAALC.js";import{getFlagsSpecification}from"../../chunks/chunk-YPPDRKVC.js";import{chars_default}from"../../chunks/chunk-2BKALEOP.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import{require_supports_color}from"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BULSRTQE.js";import"../../chunks/chunk-BRQUZ5NC.js";import"../../chunks/chunk-D6REP5QQ.js";import"../../chunks/chunk-FBYA6LLM.js";import{directFetch,getFetchDispatcher}from"../../chunks/chunk-MY4MONOH.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-SCV7XEEO.js";import{__commonJS,__require,__toESM}from"../../chunks/chunk-BZENIQ7N.js";var require_eventemitter3=__commonJS({"../../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(exports,module){"use strict";var has=Object.prototype.hasOwnProperty,prefix="~";function Events(){}Object.create&&(Events.prototype=Object.create(null),new Events().__proto__||(prefix=!1));function EE(fn,context,once2){this.fn=fn,this.context=context,this.once=once2||!1}function addListener(emitter,event,fn,context,once2){if(typeof fn!="function")throw new TypeError("The listener must be a function");var listener=new EE(fn,context||emitter,once2),evt=prefix?prefix+event:event;return emitter._events[evt]?emitter._events[evt].fn?emitter._events[evt]=[emitter._events[evt],listener]:emitter._events[evt].push(listener):(emitter._events[evt]=listener,emitter._eventsCount++),emitter}function clearEvent(emitter,evt){--emitter._eventsCount===0?emitter._events=new Events:delete emitter._events[evt]}function EventEmitter(){this._events=new Events,this._eventsCount=0}EventEmitter.prototype.eventNames=function(){var names=[],events,name;if(this._eventsCount===0)return names;for(name in events=this._events)has.call(events,name)&&names.push(prefix?name.slice(1):name);return Object.getOwnPropertySymbols?names.concat(Object.getOwnPropertySymbols(events)):names};EventEmitter.prototype.listeners=function(event){var evt=prefix?prefix+event:event,handlers=this._events[evt];if(!handlers)return[];if(handlers.fn)return[handlers.fn];for(var i=0,l=handlers.length,ee=new Array(l);i<l;i++)ee[i]=handlers[i].fn;return ee};EventEmitter.prototype.listenerCount=function(event){var evt=prefix?prefix+event:event,listeners=this._events[evt];return listeners?listeners.fn?1:listeners.length:0};EventEmitter.prototype.emit=function(event,a1,a2,a3,a4,a5){var evt=prefix?prefix+event:event;if(!this._events[evt])return!1;var listeners=this._events[evt],len=arguments.length,args,i;if(listeners.fn){switch(listeners.once&&this.removeListener(event,listeners.fn,void 0,!0),len){case 1:return listeners.fn.call(listeners.context),!0;case 2:return listeners.fn.call(listeners.context,a1),!0;case 3:return listeners.fn.call(listeners.context,a1,a2),!0;case 4:return listeners.fn.call(listeners.context,a1,a2,a3),!0;case 5:return listeners.fn.call(listeners.context,a1,a2,a3,a4),!0;case 6:return listeners.fn.call(listeners.context,a1,a2,a3,a4,a5),!0}for(i=1,args=new Array(len-1);i<len;i++)args[i-1]=arguments[i];listeners.fn.apply(listeners.context,args)}else{var length=listeners.length,j;for(i=0;i<length;i++)switch(listeners[i].once&&this.removeListener(event,listeners[i].fn,void 0,!0),len){case 1:listeners[i].fn.call(listeners[i].context);break;case 2:listeners[i].fn.call(listeners[i].context,a1);break;case 3:listeners[i].fn.call(listeners[i].context,a1,a2);break;case 4:listeners[i].fn.call(listeners[i].context,a1,a2,a3);break;default:if(!args)for(j=1,args=new Array(len-1);j<len;j++)args[j-1]=arguments[j];listeners[i].fn.apply(listeners[i].context,args)}}return!0};EventEmitter.prototype.on=function(event,fn,context){return addListener(this,event,fn,context,!1)};EventEmitter.prototype.once=function(event,fn,context){return addListener(this,event,fn,context,!0)};EventEmitter.prototype.removeListener=function(event,fn,context,once2){var evt=prefix?prefix+event:event;if(!this._events[evt])return this;if(!fn)return clearEvent(this,evt),this;var listeners=this._events[evt];if(listeners.fn)listeners.fn===fn&&(!once2||listeners.once)&&(!context||listeners.context===context)&&clearEvent(this,evt);else{for(var i=0,events=[],length=listeners.length;i<length;i++)(listeners[i].fn!==fn||once2&&!listeners[i].once||context&&listeners[i].context!==context)&&events.push(listeners[i]);events.length?this._events[evt]=events.length===1?events[0]:events:clearEvent(this,evt)}return this};EventEmitter.prototype.removeAllListeners=function(event){var evt;return event?(evt=prefix?prefix+event:event,this._events[evt]&&clearEvent(this,evt)):(this._events=new Events,this._eventsCount=0),this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.addListener=EventEmitter.prototype.on;EventEmitter.prefixed=prefix;EventEmitter.EventEmitter=EventEmitter;typeof module<"u"&&(module.exports=EventEmitter)}});var require_requires_port=__commonJS({"../../node_modules/.pnpm/requires-port@1.0.0/node_modules/requires-port/index.js"(exports,module){"use strict";module.exports=function(port,protocol){if(protocol=protocol.split(":")[0],port=+port,!port)return!1;switch(protocol){case"http":case"ws":return port!==80;case"https":case"wss":return port!==443;case"ftp":return port!==21;case"gopher":return port!==70;case"file":return!1}return port!==0}}});var require_common=__commonJS({"../../node_modules/.pnpm/http-proxy-node16@1.0.6_debug@3.1.0/node_modules/http-proxy-node16/lib/http-proxy/common.js"(exports){var common=exports,url4=__require("url"),extend=Object.assign,required=require_requires_port(),upgradeHeader=/(^|,)\s*upgrade\s*($|,)/i,isSSL=/^https|wss/;common.isSSL=isSSL;common.setupOutgoing=function(outgoing,options,req,forward){outgoing.port=options[forward||"target"].port||(isSSL.test(options[forward||"target"].protocol)?443:80),["host","hostname","socketPath","pfx","key","passphrase","cert","ca","ciphers","secureProtocol"].forEach(function(e){outgoing[e]=options[forward||"target"][e]}),outgoing.method=options.method||req.method,outgoing.headers=extend({},req.headers),options.headers&&extend(outgoing.headers,options.headers),options.auth&&(outgoing.auth=options.auth),options.ca&&(outgoing.ca=options.ca),isSSL.test(options[forward||"target"].protocol)&&(outgoing.rejectUnauthorized=typeof options.secure>"u"?!0:options.secure),outgoing.agent=options.agent||!1,outgoing.localAddress=options.localAddress,outgoing.agent||(outgoing.headers=outgoing.headers||{},(typeof outgoing.headers.connection!="string"||!upgradeHeader.test(outgoing.headers.connection))&&(outgoing.headers.connection="close"));var target=options[forward||"target"],targetPath=target&&options.prependPath!==!1&&target.path||"",outgoingPath=options.toProxy?req.url:url4.parse(req.url).path||"";return outgoingPath=options.ignorePath?"":outgoingPath,outgoing.path=common.urlJoin(targetPath,outgoingPath),options.changeOrigin&&(outgoing.headers.host=required(outgoing.port,options[forward||"target"].protocol)&&!hasPort(outgoing.host)?outgoing.host+":"+outgoing.port:outgoing.host),outgoing};common.setupSocket=function(socket){return socket.setTimeout(0),socket.setNoDelay(!0),socket.setKeepAlive(!0,0),socket};common.getPort=function(req){var res=req.headers.host?req.headers.host.match(/:(\d+)/):"";return res?res[1]:common.hasEncryptedConnection(req)?"443":"80"};common.hasEncryptedConnection=function(req){return!!(req.connection.encrypted||req.connection.pair)};common.urlJoin=function(){var args=Array.prototype.slice.call(arguments),queryParams=[],queryParamRaw="",retSegs;return args.forEach((url5,index)=>{var qpStart=url5.indexOf("?");qpStart!==-1&&(queryParams.push(url5.substring(qpStart+1)),args[index]=url5.substring(0,qpStart))}),queryParamRaw=queryParams.filter(Boolean).join("&"),retSegs=args.filter(Boolean).join("/").replace(/\/+/g,"/").replace("http:/","http://").replace("https:/","https://"),queryParamRaw?retSegs+"?"+queryParamRaw:retSegs};common.rewriteCookieProperty=function rewriteCookieProperty(header,config,property){return Array.isArray(header)?header.map(function(headerElement){return rewriteCookieProperty(headerElement,config,property)}):header.replace(new RegExp("(;\\s*"+property+"=)([^;]+)","i"),function(match,prefix,previousValue){var newValue;if(previousValue in config)newValue=config[previousValue];else if("*"in config)newValue=config["*"];else return match;return newValue?prefix+newValue:""})};function hasPort(host){return!!~host.indexOf(":")}}});var require_web_outgoing=__commonJS({"../../node_modules/.pnpm/http-proxy-node16@1.0.6_debug@3.1.0/node_modules/http-proxy-node16/lib/http-proxy/passes/web-outgoing.js"(exports,module){var url4=__require("url"),common=require_common(),redirectRegex=/^201|30(1|2|7|8)$/;module.exports={removeChunked:function(req,res,proxyRes){req.httpVersion==="1.0"&&delete proxyRes.headers["transfer-encoding"]},setConnection:function(req,res,proxyRes){req.httpVersion==="1.0"?proxyRes.headers.connection=req.headers.connection||"close":req.httpVersion!=="2.0"&&!proxyRes.headers.connection&&(proxyRes.headers.connection=req.headers.connection||"keep-alive")},setRedirectHostRewrite:function(req,res,proxyRes,options){if((options.hostRewrite||options.autoRewrite||options.protocolRewrite)&&proxyRes.headers.location&&redirectRegex.test(proxyRes.statusCode)){var target=url4.parse(options.target),u=url4.parse(proxyRes.headers.location);if(target.host!=u.host)return;options.hostRewrite?u.host=options.hostRewrite:options.autoRewrite&&(u.host=req.headers.host),options.protocolRewrite&&(u.protocol=options.protocolRewrite),proxyRes.headers.location=u.format()}},writeHeaders:function(req,res,proxyRes,options){var rewriteCookieDomainConfig=options.cookieDomainRewrite,rewriteCookiePathConfig=options.cookiePathRewrite,preserveHeaderKeyCase=options.preserveHeaderKeyCase,rawHeaderKeyMap,setHeader=function(key2,header){header!=null&&(rewriteCookieDomainConfig&&key2.toLowerCase()==="set-cookie"&&(header=common.rewriteCookieProperty(header,rewriteCookieDomainConfig,"domain")),rewriteCookiePathConfig&&key2.toLowerCase()==="set-cookie"&&(header=common.rewriteCookieProperty(header,rewriteCookiePathConfig,"path")),res.setHeader(String(key2).trim(),header))};if(typeof rewriteCookieDomainConfig=="string"&&(rewriteCookieDomainConfig={"*":rewriteCookieDomainConfig}),typeof rewriteCookiePathConfig=="string"&&(rewriteCookiePathConfig={"*":rewriteCookiePathConfig}),preserveHeaderKeyCase&&proxyRes.rawHeaders!=null){rawHeaderKeyMap={};for(var i=0;i<proxyRes.rawHeaders.length;i+=2){var key=proxyRes.rawHeaders[i];rawHeaderKeyMap[key.toLowerCase()]=key}}Object.keys(proxyRes.headers).forEach(function(key2){var header=proxyRes.headers[key2];preserveHeaderKeyCase&&rawHeaderKeyMap&&(key2=rawHeaderKeyMap[key2]||key2),setHeader(key2,header)})},writeStatusCode:function(req,res,proxyRes){proxyRes.statusMessage?(res.statusCode=proxyRes.statusCode,res.statusMessage=proxyRes.statusMessage):res.statusCode=proxyRes.statusCode}}}});var require_ms2=__commonJS({"../../node_modules/.pnpm/ms@2.0.0/node_modules/ms/index.js"(exports,module){var s=1e3,m=s*60,h=m*60,d=h*24,y=d*365.25;module.exports=function(val,options){options=options||{};var type=typeof val;if(type==="string"&&val.length>0)return parse2(val);if(type==="number"&&isNaN(val)===!1)return options.long?fmtLong(val):fmtShort(val);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(val))};function parse2(str){if(str=String(str),!(str.length>100)){var match=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);if(match){var n=parseFloat(match[1]),type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function fmtShort(ms9){return ms9>=d?Math.round(ms9/d)+"d":ms9>=h?Math.round(ms9/h)+"h":ms9>=m?Math.round(ms9/m)+"m":ms9>=s?Math.round(ms9/s)+"s":ms9+"ms"}function fmtLong(ms9){return plural3(ms9,d,"day")||plural3(ms9,h,"hour")||plural3(ms9,m,"minute")||plural3(ms9,s,"second")||ms9+" ms"}function plural3(ms9,n,name){if(!(ms9<n))return ms9<n*1.5?Math.floor(ms9/n)+" "+name:Math.ceil(ms9/n)+" "+name+"s"}}});var require_debug=__commonJS({"../../node_modules/.pnpm/debug@3.1.0/node_modules/debug/src/debug.js"(exports,module){exports=module.exports=createDebug.debug=createDebug.default=createDebug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=require_ms2();exports.instances=[];exports.names=[];exports.skips=[];exports.formatters={};function selectColor(namespace){var hash=0,i;for(i in namespace)hash=(hash<<5)-hash+namespace.charCodeAt(i),hash|=0;return exports.colors[Math.abs(hash)%exports.colors.length]}function createDebug(namespace){var prevTime;function debug(){if(debug.enabled){var self2=debug,curr=+new Date,ms9=curr-(prevTime||curr);self2.diff=ms9,self2.prev=prevTime,self2.curr=curr,prevTime=curr;for(var args=new Array(arguments.length),i=0;i<args.length;i++)args[i]=arguments[i];args[0]=exports.coerce(args[0]),typeof args[0]!="string"&&args.unshift("%O");var index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,function(match,format){if(match==="%%")return match;index++;var formatter=exports.formatters[format];if(typeof formatter=="function"){var val=args[index];match=formatter.call(self2,val),args.splice(index,1),index--}return match}),exports.formatArgs.call(self2,args);var logFn=debug.log||exports.log||console.log.bind(console);logFn.apply(self2,args)}}return debug.namespace=namespace,debug.enabled=exports.enabled(namespace),debug.useColors=exports.useColors(),debug.color=selectColor(namespace),debug.destroy=destroy,typeof exports.init=="function"&&exports.init(debug),exports.instances.push(debug),debug}function destroy(){var index=exports.instances.indexOf(this);return index!==-1?(exports.instances.splice(index,1),!0):!1}function enable(namespaces){exports.save(namespaces),exports.names=[],exports.skips=[];var i,split=(typeof namespaces=="string"?namespaces:"").split(/[\s,]+/),len=split.length;for(i=0;i<len;i++)split[i]&&(namespaces=split[i].replace(/\*/g,".*?"),namespaces[0]==="-"?exports.skips.push(new RegExp("^"+namespaces.substr(1)+"$")):exports.names.push(new RegExp("^"+namespaces+"$")));for(i=0;i<exports.instances.length;i++){var instance=exports.instances[i];instance.enabled=exports.enabled(instance.namespace)}}function disable(){exports.enable("")}function enabled(name){if(name[name.length-1]==="*")return!0;var i,len;for(i=0,len=exports.skips.length;i<len;i++)if(exports.skips[i].test(name))return!1;for(i=0,len=exports.names.length;i<len;i++)if(exports.names[i].test(name))return!0;return!1}function coerce(val){return val instanceof Error?val.stack||val.message:val}}});var require_browser=__commonJS({"../../node_modules/.pnpm/debug@3.1.0/node_modules/debug/src/browser.js"(exports,module){exports=module.exports=require_debug();exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.storage=typeof chrome<"u"&&typeof chrome.storage<"u"?chrome.storage.local:localstorage();exports.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function useColors(){return typeof window<"u"&&window.process&&window.process.type==="renderer"?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}exports.formatters.j=function(v){try{return JSON.stringify(v)}catch(err){return"[UnexpectedJSONParseError]: "+err.message}};function formatArgs(args){var useColors2=this.useColors;if(args[0]=(useColors2?"%c":"")+this.namespace+(useColors2?" %c":" ")+args[0]+(useColors2?"%c ":" ")+"+"+exports.humanize(this.diff),!!useColors2){var c="color: "+this.color;args.splice(1,0,c,"color: inherit");var index=0,lastC=0;args[0].replace(/%[a-zA-Z%]/g,function(match){match!=="%%"&&(index++,match==="%c"&&(lastC=index))}),args.splice(lastC,0,c)}}function log(){return typeof console=="object"&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{namespaces==null?exports.storage.removeItem("debug"):exports.storage.debug=namespaces}catch{}}function load(){var r;try{r=exports.storage.debug}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}exports.enable(load());function localstorage(){try{return window.localStorage}catch{}}}});var require_node=__commonJS({"../../node_modules/.pnpm/debug@3.1.0/node_modules/debug/src/node.js"(exports,module){var tty=__require("tty"),util=__require("util");exports=module.exports=require_debug();exports.init=init;exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.colors=[6,2,3,4,5,1];try{supportsColor=require_supports_color(),supportsColor&&supportsColor.level>=2&&(exports.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}var supportsColor;exports.inspectOpts=Object.keys(process.env).filter(function(key){return/^debug_/i.test(key)}).reduce(function(obj,key){var prop=key.substring(6).toLowerCase().replace(/_([a-z])/g,function(_,k){return k.toUpperCase()}),val=process.env[key];return/^(yes|on|true|enabled)$/i.test(val)?val=!0:/^(no|off|false|disabled)$/i.test(val)?val=!1:val==="null"?val=null:val=Number(val),obj[prop]=val,obj},{});function useColors(){return"colors"in exports.inspectOpts?!!exports.inspectOpts.colors:tty.isatty(process.stderr.fd)}exports.formatters.o=function(v){return this.inspectOpts.colors=this.useColors,util.inspect(v,this.inspectOpts).split(`
|
|
8
8
|
`).map(function(str){return str.trim()}).join(" ")};exports.formatters.O=function(v){return this.inspectOpts.colors=this.useColors,util.inspect(v,this.inspectOpts)};function formatArgs(args){var name=this.namespace,useColors2=this.useColors;if(useColors2){var c=this.color,colorCode="\x1B[3"+(c<8?c:"8;5;"+c),prefix=" "+colorCode+";1m"+name+" \x1B[0m";args[0]=prefix+args[0].split(`
|
|
9
9
|
`).join(`
|
|
10
10
|
`+prefix),args.push(colorCode+"m+"+exports.humanize(this.diff)+"\x1B[0m")}else args[0]=getDate()+name+" "+args[0]}function getDate(){return exports.inspectOpts.hideDate?"":new Date().toISOString()+" "}function log(){return process.stderr.write(util.format.apply(util,arguments)+`
|
|
@@ -39,7 +39,7 @@ ${partHeaders}\r
|
|
|
39
39
|
`)))}parts.push(Uint8Array.from(Buffer.from(`--${boundary}--\r
|
|
40
40
|
`)));let body=Buffer.concat(parts);res.writeHead(200,{"Content-Type":`multipart/mixed; boundary=${boundary}`,"Content-Length":body.length}),res.end(body);return}let leaseMatch=topicPath.match(/^([A-Za-z0-9_-]+)\/consumer\/([A-Za-z0-9_-]+)\/lease\/([^/]+)(?:\/visibility)?$/);if(leaseMatch&&(req.method==="DELETE"||req.method==="PATCH")){let[,,consumer,receiptHandle]=leaseMatch,messageId=this.queueBroker.findMessageIdByReceiptHandle(consumer,receiptHandle);if(!messageId){res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Message not found"}));return}if(req.method==="DELETE"){this.queueBroker.acknowledge(messageId,consumer,receiptHandle),res.writeHead(204),res.end();return}let body=await(0,import_raw_body2.default)(req),timeoutSeconds=DEV_QUEUES_DEFAULT_VISIBILITY_TIMEOUT_SECONDS;try{let parsed=JSON.parse(body.toString());typeof parsed.visibilityTimeoutSeconds=="number"&&parsed.visibilityTimeoutSeconds>=0&&(timeoutSeconds=parsed.visibilityTimeoutSeconds)}catch(err){output_manager_default.debug(`queues: failed to parse visibility timeout body: ${err}`)}this.queueBroker.changeVisibility(messageId,consumer,receiptHandle,timeoutSeconds),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({success:!0}));return}res.writeHead(404),res.end("Not Found")};this.handleRuntimeCacheRoute=async(req,res,pathname)=>{let store=this.runtimeCache;if(!store){res.writeHead(503),res.end("Runtime Cache not initialized");return}if(!pathname.startsWith(DEV_RUNTIME_CACHE_API_PREFIX)){res.writeHead(404),res.end("Not Found");return}let itemPath=pathname.slice(DEV_RUNTIME_CACHE_API_PREFIX.length),searchParams=new URL2(req.url||"/","http://localhost").searchParams;if(itemPath==="revalidate"){if(req.method!=="POST"){res.writeHead(405),res.end("Method Not Allowed");return}let tags=(searchParams.get("tags")||"").split(",").map(tag=>tag.trim()).filter(Boolean),itemId=searchParams.get("itemId")||void 0;if(tags.length===0&&!itemId){res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"No tags or itemId provided"}));return}tags.length>0&&(store.expireTags(tags),output_manager_default.debug(`runtime cache: expired tags "${tags.join(",")}"`)),itemId&&(store.delete(itemId),output_manager_default.debug(`runtime cache: expired item "${itemId}"`)),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({revalidated:!0}));return}let key;try{key=decodeURIComponent(itemPath)}catch{res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Invalid cache key"}));return}if(!key){res.writeHead(404),res.end("Not Found");return}if(req.method==="GET"){let hit=store.get(key);if(!hit){output_manager_default.debug(`runtime cache: MISS "${key}"`),res.writeHead(404),res.end("Not Found");return}output_manager_default.debug(`runtime cache: HIT "${key}"`);let headers={"Content-Type":"application/json","Content-Length":hit.value.length,[HEADER_CACHE_STATE]:"fresh",Age:String(hit.ageSeconds)};hit.tags.length>0&&(headers[HEADER_CACHE_TAGS]=hit.tags.join(",")),res.writeHead(200,headers),res.end(hit.value);return}if(req.method==="POST"){let revalidateHeader=req.headers[HEADER_REVALIDATE],ttlSeconds;if(revalidateHeader)if(revalidateHeader==="Infinity"||["false","False","FALSE","f","F"].includes(revalidateHeader))ttlSeconds=DEV_RUNTIME_CACHE_ONE_YEAR_SECONDS;else if(/^[+-]?\d+$/.test(revalidateHeader)){let parsedRevalidate=Number(revalidateHeader);if(!Number.isSafeInteger(parsedRevalidate)||parsedRevalidate<0){res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Invalid revalidate value"}));return}if(parsedRevalidate===0){res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({success:!0}));return}ttlSeconds=parsedRevalidate}else{res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Invalid revalidate value"}));return}let value;try{value=await(0,import_raw_body2.default)(req,{limit:DEV_RUNTIME_CACHE_MAX_ITEM_SIZE})}catch(err){if(err.statusCode===413){res.writeHead(413,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Cache item is too large"}));return}throw err}let tagsHeader=req.headers[HEADER_CACHE_TAGS];store.set(key,value,{ttlSeconds,tags:(tagsHeader||"").split(",").map(tag=>tag.trim()).filter(Boolean)});let name=req.headers[HEADER_CACHE_ITEM_NAME];output_manager_default.debug(`runtime cache: SET "${key}"${name?` (${name})`:""} ${value.length} bytes`),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({success:!0}));return}if(req.method==="DELETE"){store.delete(key),output_manager_default.debug(`runtime cache: DELETE "${key}"`),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({success:!0}));return}res.writeHead(405),res.end("Method Not Allowed")};this.serveProjectAsNowV2=async(req,res,requestId,vercelConfig,routes=vercelConfig.routes,callLevel=0)=>{let{debug}=output_manager_default;if(callLevel===0&&await this.handleSchedulesProxyRequest(req,res))return;let parsed=url3.parse(req.url||"/");if(typeof parsed.pathname=="string"&&parsed.pathname.includes("//")){let location=parsed.pathname.replace(/\/+/g,"/");if(parsed.search&&(location+=parsed.search),req.method==="GET"){await this.sendRedirect(req,res,requestId,location,301);return}debug(`Rewriting URL from "${req.url}" to "${location}"`),req.url=location}let queueProxyPrefix=`${DEV_QUEUE_PROXY_PREFIX}/${this.resourceProxyToken}`,runtimeCacheProxyPrefix=`${DEV_RUNTIME_CACHE_PREFIX}${this.resourceProxyToken}`;if(callLevel===0&&this.queueBroker){let pathname=parsed.pathname||"/";if(pathname.startsWith(`${queueProxyPrefix}/`)){if(!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}await this.handleQueuesRoute(req,res,pathname.slice(queueProxyPrefix.length));return}}if(callLevel===0){let pathname=parsed.pathname||"/";if(pathname.startsWith(`${runtimeCacheProxyPrefix}/`)){if(!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}await this.handleRuntimeCacheRoute(req,res,pathname.slice(runtimeCacheProxyPrefix.length));return}}if(callLevel===0&&this.bulkRedirects){let bulkMatch=resolveBulkRedirect(this.bulkRedirects,req.url||"/",typeof req.headers.host=="string"?req.headers.host:void 0);if(bulkMatch){debug(`Bulk redirect ${bulkMatch.statusCode}: ${req.url} -> ${bulkMatch.location}`),await this.sendRedirect(req,res,requestId,bulkMatch.location,bulkMatch.statusCode);return}}if(callLevel===0&&this.orchestrator){let pathname=parsed.pathname||"/",service=this.orchestrator.getServiceForRoute(pathname);if(service){debug(`Found service: ${service.name}`);let upstream=`http://${service.host}:${service.port}`;debug(`Proxying to service "${service.name}": ${upstream}`);let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.setResponseHeaders(res,requestId),proxyPass(req,res,upstream,this,requestId,!1)}}callLevel===0&&await this.updateBuildMatches(vercelConfig),this.blockingBuildsPromise&&(debug("Waiting for builds to complete before handling request"),await this.blockingBuildsPromise);let getReqUrl=rr=>{if(rr.dest){if(rr.query){let destParsed=url3.parse(rr.dest),destQuery=parseQueryString(destParsed.search);return Object.assign(destQuery,rr.query),destParsed.search=formatQueryString(destQuery),url3.format(destParsed)}return rr.dest}return req.url},handleMap=getRoutesTypes(routes),missRoutes=handleMap.get("miss")||[],hitRoutes=handleMap.get("hit")||[],errorRoutes=handleMap.get("error")||[],filesystemRoutes=handleMap.get("filesystem")||[],phases=[null,"filesystem"],routeResult=null,match=null,statusCode,prevUrl=req.url,prevHeaders={},requestTransforms=[],responseTransforms,middlewares=[...this.buildMatches.values()].filter(m=>m.config?.middleware===!0);for(let middleware of middlewares){let startMiddlewareResult,middlewarePid,{envConfigs,files,devCacheDir,cwd:workPath}=this;try{let{builder:builder2}=middleware.builderWithPkg;if(typeof builder2.startDevServer=="function"&&(startMiddlewareResult=await builder2.startDevServer({files,entrypoint:middleware.entrypoint,workPath,repoRootPath:this.repoRoot,config:{projectSettings:this.projectSettings,...middleware.config},meta:{isDev:!0,...this.getDevResourceMeta(),devCacheDir,requestUrl:req.url,env:this.getBuilderDevEnv(middleware,envConfigs.runEnv),buildEnv:{...envConfigs.buildEnv}}})),startMiddlewareResult){let{port,pid,shutdown}=startMiddlewareResult;middlewarePid=pid,this.shutdownCallbacks.set(pid,shutdown),debug(`Invoking middleware "${middleware.src}" (port=${port})`);let middlewareReqHeaders=nodeHeadersToFetchHeaders(req.headers),proxyHeaders=this.getProxyHeaders(req,requestId,!0);for(let[name,value]of nodeHeadersToFetchHeaders(proxyHeaders))middlewareReqHeaders.set(name,value);let middlewareReqPath=url3.parse(req.url||"/").path||"/",middlewareRes=await directFetch(`http://127.0.0.1:${port}${middlewareReqPath}`,{headers:middlewareReqHeaders,method:req.method,redirect:"manual"}),middlewareBody=Buffer.from(await middlewareRes.arrayBuffer());if(middlewareRes.status===500&&middlewareBody.byteLength===0){await this.sendError(req,res,requestId,"EDGE_FUNCTION_INVOCATION_FAILED",500);return}res.statusCode=middlewareRes.status;let rewritePath="",contentType2="",shouldContinue=!1,skipMiddlewareHeaders=new Set(["date","connection","content-length","transfer-encoding"]),middlewareHeaders=applyOverriddenHeaders(req.headers,middlewareRes.headers);for(let[name,value]of middlewareHeaders)name==="x-middleware-next"?shouldContinue=value==="1":name==="x-middleware-rewrite"?(rewritePath=value,shouldContinue=!0):name==="content-type"?contentType2=value:skipMiddlewareHeaders.has(name)||(applyChainResponseHeader(res,name,value),req.headers[name]=value);if(!shouldContinue){this.setResponseHeaders(res,requestId),middlewareBody.length>0?(res.setHeader("content-length",middlewareBody.length),contentType2&&res.setHeader("content-type",contentType2),res.end(middlewareBody)):res.end();return}if(rewritePath){debug(`Detected rewrite path from middleware: "${rewritePath}"`),prevUrl=rewritePath;let beforeRewriteUrl=req.url||"/";if(isURL(rewritePath)){let rewriteUrlParsed=new URL2(rewritePath);if(this.address.origin===rewriteUrlParsed.origin)req.url=rewritePath.slice(rewriteUrlParsed.origin.length)||"/",prevUrl=req.url;else{debug(`ProxyPass: ${rewritePath}`),this.setResponseHeaders(res,requestId),proxyPass(req,res,rewritePath,this,requestId);return}}else{let rewriteUrlParsed=url3.parse(beforeRewriteUrl);rewriteUrlParsed.search=url3.parse(rewritePath).search,req.url=url3.format(rewriteUrlParsed)}debug(`Rewrote incoming HTTP URL from "${beforeRewriteUrl}" to "${req.url}"`)}}}catch(err){(0,import_error_utils2.isSpawnError)(err)&&err.code==="ENOENT"&&(err.message=`Command not found: ${import_chalk2.default.cyan(err.path,...err.spawnargs)}
|
|
41
41
|
Please ensure that ${cmd(err.path)} is properly installed`,err.link="https://vercel.link/command-not-found"),output_manager_default.prettyError(err),await this.sendError(req,res,requestId,"MIDDLEWARE_INVOCATION_FAILED",500);return}finally{middlewarePid&&this.killBuilderDevServer(middlewarePid)}}for(let phase of phases){statusCode=void 0;let phaseRoutes=handleMap.get(phase)||[];if(routeResult=await devRouter(prevUrl,req.method,phaseRoutes,this,vercelConfig,prevHeaders,missRoutes,phase),routeResult.requestTransforms&&requestTransforms.push(...routeResult.requestTransforms),routeResult.responseTransforms&&(responseTransforms=routeResult.responseTransforms),routeResult.continue&&(routeResult.dest&&(prevUrl=getReqUrl(routeResult)),routeResult.headers&&(prevHeaders=routeResult.headers)),callLevel===0&&this.orchestrator&&!routeResult.continue&&isServiceDestination(routeResult.matched_route))return this.delegateToService(req,res,requestId,routeResult.matched_route,vercelConfig,requestTransforms,responseTransforms);if(routeResult.isDestUrl){let destParsed=url3.parse(routeResult.dest),destQuery=parseQueryString(destParsed.search);Object.assign(destQuery,routeResult.query),destParsed.search=formatQueryString(destQuery);let destUrl=url3.format(destParsed);return this.prepareTransforms(req,requestTransforms,responseTransforms),debug(`ProxyPass: ${destUrl}`),this.setResponseHeaders(res,requestId),proxyPass(req,res,destUrl,this,requestId)}if(match=await findBuildMatch(this.buildMatches,this.files,routeResult.dest,this,vercelConfig),await this.exitWithStatus(match,routeResult,phase,req,res,requestId,responseTransforms))return;if(!match&&missRoutes.length>0){if(routeResult=await devRouter(getReqUrl(routeResult),req.method,missRoutes,this,vercelConfig,routeResult.headers,[],"miss"),routeResult.requestTransforms&&requestTransforms.push(...routeResult.requestTransforms),routeResult.responseTransforms&&(responseTransforms=routeResult.responseTransforms),match=await findBuildMatch(this.buildMatches,this.files,routeResult.dest,this,vercelConfig),await this.exitWithStatus(match,routeResult,phase,req,res,requestId,responseTransforms))return}else if(match&&hitRoutes.length>0){let prevStatus=routeResult.status;routeResult=await devRouter(getReqUrl(routeResult),req.method,hitRoutes,this,vercelConfig,routeResult.headers,[],"hit"),routeResult.status=prevStatus,routeResult.requestTransforms&&requestTransforms.push(...routeResult.requestTransforms),routeResult.responseTransforms&&(responseTransforms=routeResult.responseTransforms)}if(statusCode=routeResult.status,match||phase===null&&filesystemRoutes.length===0)break}if(!match&&routeResult&&errorRoutes.length>0){let routeResultForError=await devRouter(getReqUrl(routeResult),req.method,errorRoutes,this,vercelConfig,routeResult.headers,[],"error"),{matched_route}=routeResultForError,matchForError=await findBuildMatch(this.buildMatches,this.files,routeResultForError.dest,this,vercelConfig);if(matchForError)debug("Route match detected in error phase, breaking loop"),routeResult=routeResultForError,statusCode=routeResultForError.status,match=matchForError,routeResult.requestTransforms&&requestTransforms.push(...routeResult.requestTransforms),routeResult.responseTransforms&&(responseTransforms=routeResult.responseTransforms);else if(matched_route&&matched_route.src&&!matched_route.dest&&(debug("Route without `dest` detected in error phase, attempting to exit early"),await this.exitWithStatus(matchForError,routeResultForError,"error",req,res,requestId,responseTransforms)))return}if(!routeResult)throw dev.DEV_INTERNAL_NO_ROUTE_RESULT();let{dest,query,headers}=routeResult;for(let[name,value]of Object.entries(headers))res.setHeader(name,value);statusCode&&Object.defineProperty(res,"statusCode",{get(){return statusCode},set(_){}});let requestPath=dest.replace(/^\//,"");if(!match){if(this.devProcessOrigin){let upstream=this.devProcessOrigin;debug(`Proxying to frontend dev server: ${upstream}`);let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;this.setResponseHeaders(res,requestId);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);return origUrl.pathname=dest,Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format(origUrl),this.prepareTransforms(req,requestTransforms,responseTransforms),proxyPass(req,res,upstream,this,requestId,!1)}(statusCode===404&&routeResult.phase==="miss"||!this.renderDirectoryListing(req,res,requestPath,requestId))&&await this.send404(req,res,requestId);return}let buildRequestPath=match.buildResults.has(null)?null:requestPath,buildResult=match.buildResults.get(buildRequestPath);if(buildResult&&Array.isArray(buildResult.routes)&&buildResult.routes.length>0){let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);origUrl.pathname=dest,Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery);let newUrl=url3.format(origUrl);debug(`Checking build result's ${buildResult.routes.length} \`routes\` to match ${newUrl}`);let matchedRoute=await devRouter(newUrl,req.method,buildResult.routes,this,vercelConfig);if(matchedRoute.found&&callLevel===0){debug(`Found matching route ${matchedRoute.dest} for ${newUrl}`),req.url=newUrl,await this.serveProjectAsNowV2(req,res,requestId,vercelConfig,buildResult.routes,callLevel+1);return}}let{builder,pkg:builderPkg}=match.builderWithPkg;if(typeof builder.startDevServer=="function"){let devServerResult=null;try{devServerResult=await this.startBuildMatchDevServer(match,requestPath)}catch(err){(0,import_error_utils2.isSpawnError)(err)&&err.code==="ENOENT"&&(err.message=`Command not found: ${import_chalk2.default.cyan(err.path,...err.spawnargs)}
|
|
42
|
-
Please ensure that ${cmd(err.path)} is properly installed`,err.link="https://vercel.link/command-not-found"),output_manager_default.prettyError(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}if(devServerResult){requestId=generateRequestId(this.podId,!0);let{port,pid,shutdown,persistent}=devServerResult;this.shutdownCallbacks.set(pid,shutdown),persistent||res.once("close",()=>{this.killBuilderDevServer(pid)}),debug(`Proxying to "${builderPkg.name}" dev server (port=${port}, pid=${pid})`);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search});let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.prepareTransforms(req,requestTransforms,responseTransforms),this.setResponseHeaders(res,requestId),proxyPass(req,res,`http://127.0.0.1:${port}`,this,requestId,!1)}else debug(`Skipping \`startDevServer()\` for ${match.entrypoint}`)}let foundAsset=findAsset(match,requestPath,vercelConfig);if(!foundAsset&&callLevel===0&&(await this.triggerBuild(match,buildRequestPath,req,vercelConfig),foundAsset=findAsset(match,requestPath,vercelConfig)),this.devProcessOrigin&&(!foundAsset||foundAsset&&foundAsset.asset.type!=="Lambda")){debug("Proxying to frontend dev server");let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.prepareTransforms(req,requestTransforms,responseTransforms),this.setResponseHeaders(res,requestId),proxyPass(req,res,this.devProcessOrigin,this,requestId,!1)}if(!foundAsset){await this.send404(req,res,requestId);return}let{asset:asset2,assetKey}=foundAsset;switch(debug(`Serving asset: [${asset2.type}] ${assetKey} ${asset2.contentType||""}`),asset2.type){case"FileFsRef":this.setResponseHeaders(res,requestId);let staticResHeaders={};applyResponseTransforms(staticResHeaders,responseTransforms??[]);for(let[name,value]of Object.entries(staticResHeaders))value!==void 0&&res.setHeader(name,value);return req.url=`/${basename(asset2.fsPath)}`,serveStaticFile(req,res,dirname3(asset2.fsPath),{headers:[{source:"**/*",headers:[{key:"Content-Type",value:asset2.contentType||getMimeType(assetKey)}]}]});case"FileBlob":let headers2={"Content-Length":asset2.data.length,"Content-Type":asset2.contentType||getMimeType(assetKey)};applyResponseTransforms(headers2,responseTransforms??[]),this.setResponseHeaders(res,requestId,headers2),res.end(asset2.data);return;case"Lambda":if(!asset2.fn){await this.sendError(req,res,requestId,"INTERNAL_LAMBDA_NOT_FOUND");return}requestId=generateRequestId(this.podId,!0);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search}),applyRequestTransforms(req,requestTransforms);let path6=req.url||"/",body=await(0,import_raw_body2.default)(req);debug(`Invoking lambda: "${assetKey}" with ${path6}`);let result;try{result=await this.invokeBuiltLambda(asset2,req,requestId,body)}catch(err){console.error(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}statusCode||(res.statusCode=result.statusCode);let lambdaHeaders=result.headers??{};applyResponseTransforms(lambdaHeaders,responseTransforms??[]),this.setResponseHeaders(res,requestId,lambdaHeaders);let resBody;return result.encoding==="base64"&&typeof result.body=="string"?resBody=Buffer.from(result.body,"base64"):resBody=result.body,res.end(resBody);default:await this.sendError(req,res,requestId,"UNKNOWN_ASSET_TYPE")}};if(this.cwd=cwd,this.repoRoot=options.repoRoot??cwd,this.envConfigs={buildEnv:{},runEnv:{},allEnv:{}},this.envValues=options.envValues||{},this.projectId=options.projectId,this.orgId=options.orgId,this.queuePort=options.queuePort,this.runtimeCachePort=options.runtimeCachePort,this.schedulesPort=options.schedulesPort,this.routing=options.routing??!0,this.devCommandPort=options.devCommandPort,this.onConfig=options.onConfig,!this.routing&&!this.devCommandPort)throw new Error("Running without the router needs a `devCommandPort`");this.scheduleBroker=new import_local_schedules2.ScheduleBroker({ownerId:this.orgId??"team_local",projectId:this.projectId??"prj_local",trackId:"development",dispatch:invocation=>this.dispatchSchedule(invocation),onError:(err,invocation)=>{try{output_manager_default.error(`Failed to dispatch schedule "${invocation.schedule.name}": ${(0,import_error_utils2.errorToString)(err)}`)}catch{}}}),this.resourceProxyToken=randomBytes2(32).toString("base64url"),this.reportError=createErrorReporter2(code=>options.onErrorCode?.(code)),this.files={},this.originalProjectSettings=options.projectSettings,this.projectSettings=options.projectSettings,this.services=options.services,this.useImplicitServicesEnvInjection=options.useImplicitServicesEnvInjection??!0,this.caseSensitive=!1,this.apiDir=null,this.apiExtensions=new Set,this.proxy=import_http_proxy_node16.default.createProxyServer({changeOrigin:!0,ws:!0,xfwd:!0}),this.proxy.on("proxyRes",(proxyRes,req)=>{proxyRes.headers.server="Vercel";let responseTransforms=this.responseTransformsByReq.get(req);responseTransforms&&(this.responseTransformsByReq.delete(req),applyResponseTransforms(proxyRes.headers,responseTransforms))}),this.proxy.on("error",(err,req,res)=>{if(output_manager_default.debug(`Proxy error for ${req?.url??"unknown request"}: ${(0,import_error_utils2.errorToString)(err)}`),!!res){if("destroy"in res&&typeof res.destroy=="function"){res.destroy();return}res instanceof http.ServerResponse&&(res.headersSent||res.writeHead(502),res.end())}}),this.server=http.createServer(this.devServerHandler),this.server.timeout=0,this.queueServer=http.createServer((req,res)=>{this.handleResourceServerRequest(req,res,this.queueOrigin,this.handleQueuesRoute)}),this.runtimeCacheServer=http.createServer((req,res)=>{this.handleResourceServerRequest(req,res,this.runtimeCacheOrigin,this.handleRuntimeCacheRoute)}),this.schedulesServer=http.createServer((req,res)=>{this.schedulesSession&&res.setHeader(LOCAL_SCHEDULES_SESSION_HEADER,this.schedulesSession.session.id),this.handleResourceServerRequest(req,res,this.schedulesOrigin,this.handleSchedulesRoute)}),this.stopping=!1,this.buildMatches=new Map,this.inProgressBuilds=new Map,this.devCacheDir=join5(getVercelDirectory(cwd),"cache"),this.vercelConfigWarning=!1,this.getVercelConfigPromise=null,this.blockingBuildsPromise=null,this.startPromise=null,this.bulkRedirects=null,this.bulkRedirectsSignature=null,this.bulkRedirectsLastPath=null,this.bulkRedirectsResolvedPath=null,this.bulkRedirectsDirty=!0,this.watchAggregationId=null,this.watchAggregationEvents=[],this.watchAggregationTimeout=500,this.filter=path6=>!!path6,this.podId=Math.random().toString(32).slice(-5),this.shutdownCallbacks=new Map}get address(){if(!this._address)throw dev.DEV_INTERNAL_ADDRESS_UNAVAILABLE();return this._address}shouldUseServicesOrchestrator(){return!!(this.services&&this.services.length>0)}hasSubscribers(){return!!this.sidecars?.length}getDevQueueEnv(){return this.queueOrigin?getDevQueueEnv(this.queueOrigin,this.hasSubscribers()):{}}getDevRuntimeCacheEnv(env){return!this.runtimeCacheOrigin||env.RUNTIME_CACHE_ENDPOINT?{}:process.env.RUNTIME_CACHE_ENDPOINT?{RUNTIME_CACHE_ENDPOINT:process.env.RUNTIME_CACHE_ENDPOINT,...process.env.RUNTIME_CACHE_HEADERS?{RUNTIME_CACHE_HEADERS:process.env.RUNTIME_CACHE_HEADERS}:{}}:getDevRuntimeCacheEnv(this.runtimeCacheOrigin,DEV_RUNTIME_CACHE_API_PREFIX)}get resourceEndpoints(){if(!this.queueOrigin||!this.runtimeCacheOrigin)throw new Error("Local resource servers have not started");let proxied=(direct,path6)=>this.routing?`${this.address.origin}${path6}`:direct,runtimeCache=`${this.runtimeCacheOrigin}${DEV_RUNTIME_CACHE_API_PREFIX}`;return{queues:{direct:this.queueOrigin,proxy:proxied(this.queueOrigin,`${DEV_QUEUE_PROXY_PREFIX}/${this.resourceProxyToken}`)},runtimeCache:{direct:runtimeCache,proxy:proxied(runtimeCache,`${DEV_RUNTIME_CACHE_PREFIX}${this.resourceProxyToken}${DEV_RUNTIME_CACHE_API_PREFIX}`)},...this.schedulesOrigin?{schedules:{direct:this.schedulesOrigin,proxy:proxied(this.schedulesOrigin,`${DEV_SCHEDULES_PROXY_PREFIX}/${this.resourceProxyToken}`)}}:{}}}getDevResourceMeta(){return{devResourceEndpoints:this.resourceEndpoints}}handleResourceServerRequest(req,res,origin,handler){if(!origin||!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}if(!isValidDevResourceHost(origin,req.headers.host)){res.writeHead(403),res.end("Forbidden");return}let pathname=new URL2(req.url||"/","http://127.0.0.1").pathname;handler(req,res,pathname).catch(err=>{output_manager_default.debug(`Local resource request failed for ${req.url||"/"}: ${(0,import_error_utils2.errorToString)(err)}`),res.headersSent||res.writeHead(500),res.end("Internal Server Error")})}isAuthorizedResourceRequest(req,token){let authorization=req.headers.authorization;if(typeof authorization!="string")return!1;let encoder=new TextEncoder,actual=encoder.encode(authorization),expected=encoder.encode(`Bearer ${token}`);return actual.length===expected.length&&timingSafeEqual(actual,expected)}getBuilderDevEnv(match,env){let result={...env,...getDevSchedulesEnv(this.schedulesOrigin)};if(match.builderWithPkg.pkg.name!=="@vercel/container")return result;let endpoints=this.resourceEndpoints;return Object.assign(result,getDevSchedulesEnv(endpoints.schedules?.proxy,!0)),result.VERCEL_QUEUE_BASE_URL===endpoints.queues.direct&&Object.assign(result,getDevQueueEnv(endpoints.queues.proxy,result.VERCEL_HAS_WORKER_SERVICES!==void 0)),result.RUNTIME_CACHE_ENDPOINT===endpoints.runtimeCache.direct&&Object.assign(result,getDevRuntimeCacheEnv(endpoints.runtimeCache.proxy,"")),result}getSidecarDevMeta(match){let serviceCount=(this.sidecars??[]).filter(sidecar=>sidecar.builder.use!==match.use?!1:!sidecar.workspace||sidecar.workspace===".").length;return serviceCount>0?{serviceCount}:{}}async setupBuilderDevSidecars(){if(this.shouldUseServicesOrchestrator())return;let sidecars=this.sidecars??[];if(sidecars.length===0)return;Object.assign(this.envConfigs.runEnv,this.getDevQueueEnv());let services=sidecars.map(toOrchestratorService),orchestrator=new ServicesOrchestrator({services,cwd:this.cwd,repoRoot:this.repoRoot,env:this.envConfigs.allEnv,proxyOrigin:this.address.origin,resourceEndpoints:this.resourceEndpoints,useImplicitEnvInjection:!1,preferServiceBuilder:!0,onQueueSubscriptions:(serviceName,subscriptions)=>this.queueBroker?.updateServiceSubscriptions(serviceName,subscriptions)});this.sidecarOrchestrator=orchestrator,this.queueBroker?.registerServices(services);try{await orchestrator.startAll()}catch(err){throw await orchestrator.stopAll(),this.sidecarOrchestrator=void 0,this.sidecars=[],err}output_manager_default.log(`Started ${sidecars.length} development ${(0,import_pluralize2.default)("sidecar",sidecars.length)}`)}async exit(code=1){await this.stop(code),process.exit(code)}enqueueFsEvent(type,path6){this.bulkRedirectsResolvedPath&&(path6===this.bulkRedirectsResolvedPath||path6.startsWith(this.bulkRedirectsResolvedPath+sep2))&&(this.bulkRedirectsDirty=!0),this.watchAggregationEvents.push({type,path:path6}),this.watchAggregationId===null&&(this.watchAggregationId=setTimeout(()=>{let events=this.watchAggregationEvents.slice();this.watchAggregationEvents.length=0,this.watchAggregationId=null,this.handleFilesystemEvents(events).catch(err=>{output_manager_default.prettyError(err),(0,import_error_utils2.isError)(err)&&typeof err.stack=="string"&&output_manager_default.debug(err.stack)})},this.watchAggregationTimeout))}async handleFilesystemEvents(events){if(this.stopping)return;output_manager_default.debug(`Filesystem watcher notified of ${events.length} events`);let filesChanged=new Set,filesRemoved=new Set,distPaths=[];for(let buildMatch of this.buildMatches.values())for(let buildResult of buildMatch.buildResults.values())buildResult.distPath&&distPaths.push(buildResult.distPath);if(events=events.filter(event=>distPaths.every(distPath=>!event.path.startsWith(distPath))),events.length!==0){this.functionReconciliations++;try{this.configGeneration++,this.functionDiscovery=void 0;for(let event of events)event.type==="add"?await this.handleFileCreated(event.path,filesChanged,filesRemoved):event.type==="unlink"?this.handleFileDeleted(event.path,filesChanged,filesRemoved):event.type==="change"&&await this.handleFileModified(event.path,filesChanged,filesRemoved);let vercelConfig=await this.getVercelConfig();if(this.stopping)return;await this.updateBuildMatches(vercelConfig);let filesChangedArray=[...filesChanged],filesRemovedArray=[...filesRemoved],needsRebuild=new Map;for(let match of this.buildMatches.values()){this.canonicalizeFunctionBuild(match);for(let[requestPath,result]of match.buildResults)if(!needsRebuild.has(result)&&Array.isArray(result.watch)){for(let pattern of result.watch)if(minimatches(filesChangedArray,pattern)||minimatches(filesRemovedArray,pattern)){needsRebuild.set(result,[requestPath,match]);break}}}if(needsRebuild.size>0){output_manager_default.debug(`Triggering ${needsRebuild.size} rebuilds`),filesChangedArray.length>0&&output_manager_default.debug(`Files changed: ${filesChangedArray.join(", ")}`),filesRemovedArray.length>0&&output_manager_default.debug(`Files removed: ${filesRemovedArray.join(", ")}`);for(let[result,[requestPath,match]]of needsRebuild)requestPath===null||await shouldServe(match,this.files,requestPath,this,vercelConfig)?this.triggerBuild(match,requestPath,null,vercelConfig,result,filesChangedArray,filesRemovedArray).catch(err=>{output_manager_default.warn(`An error occurred while rebuilding \`${match.src}\`:`),console.error(err.stack)}):output_manager_default.debug(`Not rebuilding because \`shouldServe()\` returned \`false\` for "${match.use}" request path "${requestPath}"`)}}finally{this.functionReconciliations--}}}async handleFileCreated(fsPath,changed,removed){let name=relative(this.cwd,fsPath);try{await this.getVercelConfig(),this.files[name]=await import_build_utils9.FileFsRef.fromFsPath({fsPath});let extensionless=this.getExtensionlessFile(name);extensionless&&(this.files[extensionless]=await import_build_utils9.FileFsRef.fromFsPath({fsPath})),fileChanged(name,changed,removed),output_manager_default.debug(`File created: ${name}`)}catch(err){if((0,import_error_utils2.isErrnoException)(err)&&err.code==="ENOENT")output_manager_default.debug(`File created, but has since been deleted: ${name}`),fileRemoved(name,this.files,changed,removed);else throw err}}handleFileDeleted(fsPath,changed,removed){let name=relative(this.cwd,fsPath);output_manager_default.debug(`File deleted: ${name}`),fileRemoved(name,this.files,changed,removed);let extensionless=this.getExtensionlessFile(name);extensionless&&(output_manager_default.debug(`File deleted: ${extensionless}`),fileRemoved(extensionless,this.files,changed,removed))}async handleFileModified(fsPath,changed,removed){let name=relative(this.cwd,fsPath);try{this.files[name]=await import_build_utils9.FileFsRef.fromFsPath({fsPath}),fileChanged(name,changed,removed),output_manager_default.debug(`File modified: ${name}`)}catch(err){if((0,import_error_utils2.isErrnoException)(err)&&err.code==="ENOENT")output_manager_default.debug(`File modified, but has since been deleted: ${name}`),fileRemoved(name,this.files,changed,removed);else throw err}}async updateBuildMatches(vercelConfig,isInitial=!1){let fileList=this.resolveBuildFiles(this.files),matches=await getBuildMatches(vercelConfig,this.cwd,this,fileList),sources=matches.map(m=>m.src);isInitial&&fileList.length===0&&output_manager_default.warn("There are no files inside your deployment.");let ops=[];for(let src of this.buildMatches.keys())if(!sources.includes(src)){output_manager_default.debug(`Removing build match for "${src}"`);let match=this.buildMatches.get(src);match&&ops.push(shutdownBuilder(match)),this.buildMatches.delete(src)}await Promise.all(ops);let blockingBuilds=[];for(let match of matches){let currentMatch=this.buildMatches.get(match.src);if(!buildMatchEquals(currentMatch,match)&&(output_manager_default.debug(`Adding build match for "${match.src}" with "${match.use}"`),this.buildMatches.set(match.src,match),!isInitial&&needsBlockingBuild(match))){let buildPromise=executeBuild(vercelConfig,this,this.files,match,null,!1);blockingBuilds.push(buildPromise)}}if(blockingBuilds.length>0&&(output_manager_default.debug(`Waiting for ${blockingBuilds.length} "blocking builds"`),this.blockingBuildsPromise=Promise.all(blockingBuilds).then(()=>{output_manager_default.debug('Cleaning up "blockingBuildsPromise" after successful resolve'),this.blockingBuildsPromise=null}).catch(err=>{output_manager_default.debug(`Cleaning up "blockingBuildsPromise" after error: ${err}`),this.blockingBuildsPromise=null,err&&output_manager_default.prettyError(err)})),this.buildMatches=new Map([...this.buildMatches.entries()].sort((matchA,matchB)=>sortBuilders(matchA[1],matchB[1]))),isInitial){let warnings=new Set;for(let match of this.buildMatches.values()){let{builder}=match.builderWithPkg;if(!builder.getDevWarnings)continue;let builderWarnings=await builder.getDevWarnings({files:this.files,entrypoint:match.entrypoint,workPath:this.cwd,repoRootPath:this.repoRoot,config:{projectSettings:this.projectSettings,...match.config},meta:{isDev:!0,env:this.getBuilderDevEnv(match,this.envConfigs.runEnv),buildEnv:{...this.envConfigs.buildEnv}}});for(let warning of builderWarnings)warnings.add(warning)}for(let warning of warnings)output_manager_default.warn(warning)}}async getLocalEnv(fileName,base){let filePath=join5(this.cwd,fileName),env={};try{let dotenv=await import_fs_extra.default.readFile(filePath,"utf8");output_manager_default.debug(`Using local env: ${filePath}`),env=(0,import_dotenv.parse)(dotenv),env=this.injectSystemValuesInDotenv(env)}catch(err){if(!(0,import_error_utils2.isErrnoException)(err)||err.code!=="ENOENT")throw err}try{return{...this.validateEnvConfig(fileName,base||{},env)}}catch(err){if(err instanceof MissingDotenvVarsError)this.reportError(err),await this.exit();else throw err}return{}}getVercelConfig(){if(this.getVercelConfigPromise)return this.getVercelConfigPromise;this.getVercelConfigPromise=(async()=>{for(;;){let generation=this.configGeneration;try{let config=await this._getVercelConfig();if(this.stopping||generation===this.configGeneration)return config}catch(err){if(this.stopping||generation===this.configGeneration)throw err}this.functionDiscovery=void 0}})();let clear=this.clearVercelConfigPromise;return this.getVercelConfigPromise.then(clear,clear),this.getVercelConfigPromise}get devCommand(){return this.getDevCommand(this.projectSettings)}get devCommandOrigin(){return this.devProcessOrigin}getDevCommand(projectSettings){if(projectSettings?.devCommand)return projectSettings.devCommand;if(projectSettings?.framework){let frameworkSlug=projectSettings.framework,framework=import_frameworks3.frameworkList.find(f=>f.slug===frameworkSlug);if(framework){let defaults=framework.settings.devCommand.value;if(defaults)return defaults}if((0,import_build_utils9.shouldUseExperimentalBackends)(frameworkSlug))return"npx @vercel/cervel dev"}}getFunctionDiscovery(options){let key=JSON.stringify(options);if(!this.functionDiscovery||this.functionDiscovery.key!==key){let promise=collectDevFunctions(options);this.functionDiscovery={key,promise},promise.catch(()=>{this.functionDiscovery?.promise===promise&&(this.functionDiscovery=void 0)})}return this.functionDiscovery.promise}getDevFunction(outputPath){return this.functionRegistry.functions.get(outputPath)}getDevSchedules(){return this.functionRegistry.schedules}async dispatchSchedule({delivery,signal}){if(signal.throwIfAborted(),this.stopping)throw new Error("Local Schedules is stopping");if(delivery.type==="queue"){if(!this.queueBroker)throw new Error("Local Queue broker is not ready");this.queueBroker.enqueue(delivery.topic,Buffer.from(JSON.stringify(delivery.message)),"application/json");return}if(delivery.type==="path"){if(!this._address)throw new Error(`Schedule path "${delivery.path}" is not ready because vercel dev is not listening yet`);signal.throwIfAborted();let cronSecret=this.envConfigs.runEnv.CRON_SECRET??process.env.CRON_SECRET,response=await directFetch(`${this._address.origin}${delivery.path}`,{method:delivery.requestMethod,headers:{...delivery.headers,...cronSecret?{authorization:`Bearer ${cronSecret}`}:{}},signal});if(!response.ok)throw new Error(`Schedule path "${delivery.path}" returned HTTP ${response.status}`);return}let invoke=this.resolveDevFunction(delivery.function);if(!invoke)throw new Error(`Schedule function "${delivery.function}" is missing or not ready`);signal.throwIfAborted();let onAbort=()=>{},aborted=new Promise((_,reject)=>{onAbort=()=>reject(signal.reason),signal.addEventListener("abort",onAbort,{once:!0})});try{let result=await Promise.race([aborted,invoke({method:"POST",headers:delivery.headers,body:Buffer.alloc(0),signal})]);if(!result)throw new Error(`Schedule function "${delivery.function}" is missing or not ready`);if(!result.ok)throw new Error(`Schedule function "${delivery.function}" returned HTTP ${result.status}`)}finally{signal.removeEventListener("abort",onAbort)}}resolveDevFunction(outputPath){let fn=this.getDevFunction(outputPath);if(!fn||this.stopping)return null;if(fn.invocation.type==="http"){if(!this.devProcessOrigin)return null}else if(!this.functionDispatchReady||this.functionReconciliations>0||!this.getDevFunctionMatch(fn))return null;return request3=>this.invokeDevFunction(outputPath,request3)}getDevFunctionMatch(fn){if(fn.invocation.type!=="entrypoint"||fn.scope.target!=="builder")return;let{entrypoint}=fn.invocation;return[...this.buildMatches.values()].find(match=>match.entrypoint===entrypoint&&match.use===fn.scope.build.use&&(0,import_fast_deep_equal.default)(match.config??{},fn.scope.build.config??{}))}canonicalizeFunctionBuild(match){if(![...this.functionRegistry.functions.values()].some(fn=>this.getDevFunctionMatch(fn)===match))return!1;if(match.buildResults.size&&!(match.buildResults.size===1&&match.buildResults.has(null))){let results=[...match.buildResults.values()],result=results[results.length-1];result.watch=[...new Set(results.flatMap(result2=>result2.watch))],match.buildResults.clear(),match.buildResults.set(null,result)}return!0}async invokeDevFunction(outputPath,request3){request3.signal?.throwIfAborted();let fn=this.getDevFunction(outputPath);if(!fn||!this.resolveDevFunction(outputPath))return null;let generation=this.configGeneration,isCurrent=()=>!this.stopping&&generation===this.configGeneration&&this.getDevFunction(outputPath)===fn;if(fn.invocation.type==="http"){let response=await directFetch(`${this.devProcessOrigin}${fn.invocation.pathname}`,{...request3,redirect:"manual"});return await response.arrayBuffer(),{ok:response.ok,status:response.status}}let match=this.getDevFunctionMatch(fn),config=this.functionConfig,req=new http.IncomingMessage(new Socket);req.method=request3.method,req.url=`/${outputPath}`,req.headers={host:this.address.host,...request3.headers};let requestId=generateRequestId(this.podId,!0),currentMatch=()=>!request3.signal?.aborted&&isCurrent()&&this.getDevFunctionMatch(fn)===match,devServerResult=await this.startBuildMatchDevServer(match,outputPath);if(devServerResult){let{port,pid,shutdown,persistent}=devServerResult;this.shutdownCallbacks.set(pid,shutdown);try{if(!currentMatch())return null;let response=await directFetch(`http://127.0.0.1:${port}/${outputPath}`,{...request3,headers:nodeHeadersToFetchHeaders({...req.headers,...this.getProxyHeaders(req,requestId,!0)}),redirect:"manual"});return await response.arrayBuffer(),{ok:response.ok,status:response.status}}finally{let current=this.getDevFunction(outputPath);(this.stopping||!persistent||!current||this.getDevFunctionMatch(current)!==match)&&this.shutdownCallbacks.has(pid)&&await this.killBuilderDevServer(pid)}}if(!currentMatch())return null;let{entrypoint}=fn.invocation,getAsset=()=>match.buildOutput[(match.buildResultVersion??match.builderWithPkg.builder.version)===2?outputPath:entrypoint];this.canonicalizeFunctionBuild(match);let asset2=getAsset();if((!asset2||this.inProgressBuilds.get(match)?.size)&&(await this.triggerBuild(match,null,null,config),asset2=getAsset()),!currentMatch())return null;if(!asset2||asset2.type!=="Lambda"||!asset2.fn)return{ok:!1,status:404};let result=await this.invokeBuiltLambda(asset2,req,requestId,request3.body);return{ok:result.statusCode>=200&&result.statusCode<300,status:result.statusCode}}async startBuildMatchDevServer(match,requestPath){let{builder}=match.builderWithPkg;if(!builder.startDevServer)return null;let{envConfigs,files,devCacheDir,cwd:workPath}=this;return builder.startDevServer({files,entrypoint:match.entrypoint,workPath,config:match.config||{},repoRootPath:this.repoRoot,meta:{isDev:!0,...this.getDevResourceMeta(),requestPath,devCacheDir,...this.getSidecarDevMeta(match),env:this.getBuilderDevEnv(match,{...envConfigs.runEnv,VERCEL_DEBUG_PREFIX:output_manager_default.debugEnabled?"[builder]":void 0}),buildEnv:{...envConfigs.buildEnv}}})}invokeBuiltLambda(asset2,req,requestId,body){let payload={method:req.method||"GET",host:req.headers.host,path:req.url||"/",headers:{...req.headers,...this.getProxyHeaders(req,requestId,!0)},encoding:"base64",body:body.toString("base64")};return asset2.fn({Action:"Invoke",body:JSON.stringify(payload)})}async _getVercelConfig(){let generation=this.configGeneration,configPath=localConfigFlagPath();if(!configPath){let{compileVercelConfig}=await import("../../chunks/compile-vercel-config-LNRUSKTH.js"),compiled=await compileVercelConfig(this.cwd);configPath=getLocalPathConfig(this.cwd,!!compiled.sourceFile)}let[pkg=null,vercelConfig={version:2,[import_client.fileNameSymbol]:"vercel.json"}]=await Promise.all([this.readJsonFile("package.json"),this.readJsonFile(configPath,!0)]);await this.validateVercelConfig(vercelConfig);let functionConfig=structuredClone(vercelConfig),sourceFiles;for(let[name,service]of Object.entries(this.queueBroker?vercelConfig.services??vercelConfig.experimentalServicesV2??{}:{}))if(Object.values(service.functions??{}).some(fn=>fn.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta")))throw dev.DEV_QUEUE_FUNCTION_UNSUPPORTED({sourceFile:`services.${name}.functions`,reason:"service-hosted function queue triggers are not supported locally yet"});let nextProjectSettings={...this.originalProjectSettings,...pickOverrides(vercelConfig)},{error:routeError,routes:maybeRoutes}=(0,import_routing_utils3.getTransformedRoutes)(vercelConfig);routeError&&(this.reportError(routeError),await this.exit()),vercelConfig.routes=maybeRoutes||[];let hasServices=(this.services?.length??0)>0,hasResolvedServices=!!this.services&&this.services.length>0,schedules=(0,import_build_utils9.getNamedSchedules)(functionConfig.schedules),scheduleEntrypointPlan;if(!hasResolvedServices&&schedules.some(import_schedule_entrypoint.hasScheduleEntrypointTarget)&&(sourceFiles=(await staticFiles(this.cwd,{})).map(f=>relative(this.cwd,f)),scheduleEntrypointPlan=(0,import_schedule_entrypoint.planScheduleEntrypoints)({schedules,files:sourceFiles,framework:nextProjectSettings.framework,functions:functionConfig.functions})),!vercelConfig.experimentalServices&&!hasResolvedServices&&(!vercelConfig.builds||vercelConfig.builds.length===0)){let{projectSettings,cleanUrls,trailingSlash}=vercelConfig,files=sourceFiles??(await staticFiles(this.cwd,{})).map(f=>relative(this.cwd,f));sourceFiles=files;let detectionOptions={tag:"latest",reservedFunctionFiles:scheduleEntrypointPlan?.reservedFunctionFiles,bunVersion:vercelConfig.bunVersion,functions:vercelConfig.functions,projectSettings:projectSettings||nextProjectSettings,featHandleMiss:!0,cleanUrls,trailingSlash,proxy:vercelConfig.proxy,workPath:this.cwd},detectedBuilders=await(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,detectionOptions);for(;detectedBuilders.errors?.length===1&&detectedBuilders.errors[0].code==="unused_function";){let error3=detectedBuilders.errors[0],unmatchedTrigger=Object.entries(detectionOptions.functions??{}).find(([pattern,fn])=>error3.message.startsWith(`The pattern "${pattern}" defined in \`functions\` `)&&fn.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta"||trigger.type==="schedule/v1beta"));if(!unmatchedTrigger)break;detectionOptions.functions={...detectionOptions.functions},delete detectionOptions.functions[unmatchedTrigger[0]],detectedBuilders=await(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,detectionOptions)}let{builders,warnings,errors,defaultRoutes,redirectRoutes,rewriteRoutes,errorRoutes}=detectedBuilders,hostRewriteRoutes=detectedBuilders.hostRewriteRoutes;if(errors){if(this.functionConfig)throw errors[0];this.reportError(errors[0]),await this.exit()}if(warnings?.length>0&&warnings.forEach(warning=>output_manager_default.warn(warning.message,null,warning.link,warning.action)),builders){let buildpackRuntime=builders.map(getBuildpackRuntime).find(runtime=>runtime!==void 0);if(buildpackRuntime)throw buildpackDevUnsupportedError(buildpackRuntime);vercelConfig.builds=vercelConfig.builds||[],vercelConfig.builds.push(...builders),delete vercelConfig.functions}let serviceRewrites=detectedBuilders.serviceRewrites,serviceRewriteRoutes=serviceRewrites&&serviceRewrites.length>0?(0,import_routing_utils3.convertRewrites)(serviceRewrites):null,routes=[];routes.push(...redirectRoutes||[]),routes=(0,import_routing_utils3.appendRoutesToPhase)({routes,newRoutes:hostRewriteRoutes??null,phase:null}),routes.push(...(0,import_routing_utils3.appendRoutesToPhase)({routes:vercelConfig.routes,newRoutes:[...rewriteRoutes||[],...serviceRewriteRoutes||[]],phase:"filesystem"})),routes=(0,import_routing_utils3.appendRoutesToPhase)({routes,newRoutes:errorRoutes,phase:"error"}),routes.push(...defaultRoutes||[]),vercelConfig.routes=routes}else if(hasResolvedServices&&vercelConfig.proxy){let{entrypoint}=vercelConfig.proxy;await import_fs_extra.default.pathExists(join5(this.cwd,entrypoint))||(output_manager_default.error(`The proxy entrypoint \`${entrypoint}\` does not exist. Set \`proxy.entrypoint\` to an existing \`.js\` or \`.ts\` file.`),await this.exit()),vercelConfig.builds=vercelConfig.builds||[],vercelConfig.builds.push((0,import_fs_detectors2.getProxyBuilder)(vercelConfig.proxy,"latest",vercelConfig.functions))}if(this.sidecars===void 0){let services=(this.services??[]).filter(import_build_utils9.isExperimentalServiceV2);this.sidecars=await collectBuilderDevSidecars({builds:this.shouldUseServicesOrchestrator()?services.map(service=>service.builder):vercelConfig.builds??[],workPath:this.cwd,services})}scheduleEntrypointPlan&&(vercelConfig.builds??=[{src:"**",use:"@vercel/static"}],(0,import_schedule_entrypoint.assertNoScheduleEntrypointSourceConflict)(vercelConfig.builds,scheduleEntrypointPlan),vercelConfig.builds.push(...scheduleEntrypointPlan.builds));let functionBuilds=[...vercelConfig.builds??[]];Array.isArray(vercelConfig.builds)&&((this.getDevCommand(nextProjectSettings)||hasServices)&&(vercelConfig.builds=vercelConfig.builds.filter(this.shouldBuildInDev)),vercelConfig.builds.sort(sortBuilders)),vercelConfig.routes=(vercelConfig.routes||[]).filter(route=>"has"in route?(this.vercelConfigWarning||(this.vercelConfigWarning=!0,output_manager_default.warn(`The "has" property in ${vercelConfig[import_client.fileNameSymbol]} will be ignored during development. Deployments will work as expected.`)),!1):!0);let[runEnv,buildEnv]=await Promise.all([this.getLocalEnv(".env",vercelConfig.env),this.getLocalEnv(".env.build",vercelConfig.build?.env)]),allEnv={...buildEnv,...runEnv},envFromCloud=Object.keys(allEnv).length===0;if(envFromCloud){let envValues={...this.envValues};this.address.host&&(envValues.VERCEL_URL=this.address.host),allEnv={...envValues},runEnv={...envValues},buildEnv={...envValues}}runEnv.NODE_ENV??=process.env.NODE_ENV??"development",allEnv.NODE_ENV??=runEnv.NODE_ENV,runEnv.NOW_REGION="dev1",buildEnv.NOW_REGION="dev1",allEnv.NOW_REGION="dev1",allEnv.VERCEL_ENV="development",allEnv.VERCEL="1",this.projectId&&!process.env.VERCEL_PROJECT_ID&&("VERCEL_PROJECT_ID"in allEnv||(allEnv.VERCEL_PROJECT_ID=this.projectId),"VERCEL_PROJECT_ID"in runEnv||(runEnv.VERCEL_PROJECT_ID=this.projectId)),this.orgId&&!process.env.VERCEL_ORG_ID&&("VERCEL_ORG_ID"in allEnv||(allEnv.VERCEL_ORG_ID=this.orgId),"VERCEL_ORG_ID"in runEnv||(runEnv.VERCEL_ORG_ID=this.orgId)),nextProjectSettings?.autoExposeSystemEnvs&&(runEnv.VERCEL_REGION="dev1"),runEnv.VERCEL_CLI_VERSION=pkg_default.version,Object.assign(runEnv,this.getDevQueueEnv()),Object.assign(runEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(allEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(runEnv,this.getDevRuntimeCacheEnv(runEnv));let hasQueueFunctions=Object.values(functionConfig.functions??{}).some(fn=>fn.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta"));if(this.queueBroker&&hasQueueFunctions&&hasResolvedServices)throw dev.DEV_QUEUE_FUNCTION_UNSUPPORTED({sourceFile:"functions",reason:"service-hosted function queue triggers are not supported locally yet"});let registry=await this.getFunctionDiscovery({scopes:(hasResolvedServices?[]:functionBuilds).map(build=>({build,target:vercelConfig.builds?.includes(build)?"builder":"framework"})),workPath:this.cwd,files:(sourceFiles??(await staticFiles(this.cwd,{})).map(f=>relative(this.cwd,f))).sort(),config:functionConfig,env:{...process.env,...allEnv,...this.getDevQueueEnv(),...getDevSchedulesEnv(this.schedulesOrigin),...this.getDevRuntimeCacheEnv(allEnv)}}),subscriptions,staticSchedules,sourceChanged;try{subscriptions=deriveQueueSubscriptions(registry),this.queueBroker?.validateFunctionSubscriptions(subscriptions),staticSchedules=collectStaticSchedules(scheduleEntrypointPlan?(0,import_schedule_entrypoint.resolveScheduleEntrypointTargets)(schedules,scheduleEntrypointPlan):schedules,registry),sourceChanged=!(0,import_fast_deep_equal.default)(this.staticSchedulesSnapshot,staticSchedules),sourceChanged&&this.scheduleBroker.validateStatic(staticSchedules)}catch(err){throw this.functionDiscovery=void 0,err}let{unmatchedPatterns}=registry;if(await this.refreshBulkRedirects(vercelConfig.bulkRedirectsPath),this.devCommandStarts.size&&await Promise.all(this.devCommandStarts),this.stopping||generation!==this.configGeneration)return vercelConfig;let restartForFunctionEnv=!!(this.devCommandEnv&&[...registry.functions.values()].some(fn=>fn.invocation.type==="http")&&!(0,import_fast_deep_equal.default)(this.devCommandEnv,allEnv)),previousProcess=this.devProcess,previousOrigin=this.devProcessOrigin,previousCommand=this.currentDevCommand,previousEnv=this.devCommandEnv,previousRuntime={projectSettings:this.projectSettings,allEnv:previousEnv??this.envConfigs.allEnv},restarted,validated=!1;try{if(this.initialDevCommandStarted&&await this.runDevCommand(restartForFunctionEnv,{projectSettings:nextProjectSettings,allEnv},origin=>{restarted={origin}}),this.stopping||generation!==this.configGeneration)return vercelConfig;this.queueBroker?.validateFunctionSubscriptions(subscriptions),sourceChanged=!(0,import_fast_deep_equal.default)(this.staticSchedulesSnapshot,staticSchedules),sourceChanged&&(this.scheduleBroker.validateStatic(staticSchedules),this.scheduleBroker.reconcileStatic(staticSchedules),this.staticSchedulesSnapshot=structuredClone(staticSchedules)),validated=!0}finally{!this.stopping&&!validated&&(this.devProcess!==previousProcess||this.devProcessOrigin!==previousOrigin||this.currentDevCommand!==previousCommand||this.devCommandEnv!==previousEnv)&&await this.runDevCommand(!0,previousRuntime)}this.projectSettings=nextProjectSettings,this.caseSensitive=hasNewRoutingProperties(vercelConfig),this.apiDir=(0,import_fs_detectors2.detectApiDirectory)(vercelConfig.builds||[]),this.apiExtensions=(0,import_fs_detectors2.detectApiExtensions)(vercelConfig.builds||[]),this.envConfigs={buildEnv,runEnv,allEnv},this.envFromCloud=envFromCloud,this.functionRegistry=registry,this.functionConfig=vercelConfig,restarted&&(this.devProcessOrigin=restarted.origin),this.queueBroker?.setFunctionSubscriptions(subscriptions,outputPath=>this.resolveDevFunction(outputPath));for(let pattern of unmatchedPatterns)if(!this.unmatchedQueuePatterns.has(pattern)){let warning=dev.DEV_QUEUE_FUNCTION_UNMATCHED({pattern});output_manager_default.warn(`[${warning.name}] ${warning.message} ${warning.fix}`)}return this.unmatchedQueuePatterns=new Set(unmatchedPatterns),this.onConfig?.(functionConfig),vercelConfig}async refreshBulkRedirects(bulkRedirectsPath){let configPath=bulkRedirectsPath??null;if(configPath===this.bulkRedirectsLastPath&&!this.bulkRedirectsDirty)return;if(this.bulkRedirectsLastPath=configPath,this.bulkRedirectsDirty=!1,this.bulkRedirectsResolvedPath=configPath?resolveBulkRedirectsPath(this.cwd,configPath):null,!configPath){this.bulkRedirects=null,this.bulkRedirectsSignature=null;return}let signature=await getBulkRedirectsSignature(this.cwd,configPath);if(signature!==this.bulkRedirectsSignature){this.bulkRedirectsSignature=signature;try{let result=await loadBulkRedirects(this.cwd,configPath);this.bulkRedirects=result.table;for(let warning of result.warnings)output_manager_default.warn(warning);let count=result.table.size;count>0&&output_manager_default.log(`Loaded ${count} bulk ${(0,import_pluralize2.default)("redirect",count)} from ${configPath}`)}catch(err){this.bulkRedirects=null,output_manager_default.warn(`Failed to load bulk redirects from "${configPath}": ${(0,import_error_utils2.errorToString)(err)}`)}}}async readJsonFile(filePath,strict=!1){let rel,abs;isAbsolute3(filePath)?(rel=path4.relative(this.cwd,filePath),abs=filePath):(rel=filePath,abs=join5(this.cwd,filePath)),output_manager_default.debug(`Reading \`${rel}\` file`);try{let raw=await import_fs_extra.default.readFile(abs,"utf8"),parsed=(0,import_json_parse_better_errors.default)(raw);return parsed[import_client.fileNameSymbol]=rel,parsed}catch(err){if(strict&&!((0,import_error_utils2.isErrnoException)(err)&&err.code==="ENOENT"))throw err;if((0,import_error_utils2.isError)(err))(0,import_error_utils2.isErrnoException)(err)&&err.code==="ENOENT"?output_manager_default.debug(`No \`${rel}\` file present`):err.name==="SyntaxError"&&output_manager_default.warn(`There is a syntax error in the \`${rel}\` file: ${err.message}`);else throw err}}async tryValidateOrExit(config,validate){let message=validate(config);message&&(output_manager_default.error(message),await this.exit(1))}async validateVercelConfig(config){if(config.version===1){if(this.functionConfig)throw dev.DEV_UNSUPPORTED_CONFIG_VERSION();this.reportError(dev.DEV_UNSUPPORTED_CONFIG_VERSION()),await this.exit(1);return}let error3=validateConfig(config);if(error3){if(this.functionConfig)throw error3;this.reportError(error3),await this.exit(1)}}validateEnvConfig(type,env={},localEnv={}){let missing=Object.entries(env).filter(([name,value])=>typeof value=="string"&&value.startsWith("@")&&!hasProp(localEnv,name)).map(([name])=>name);if(missing.length>0)throw new MissingDotenvVarsError(type,missing);let merged={...env,...localEnv},hasInvalidName=!1;for(let key of Object.keys(merged))/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)||(output_manager_default.warn(`Ignoring ${type.split(".").slice(1).reverse().join(" ")} var ${JSON.stringify(key)} because name is invalid`),hasInvalidName=!0,delete merged[key]);return hasInvalidName&&output_manager_default.log("The name contains invalid characters. Only letters, digits, and underscores are allowed. Furthermore, the name should not start with a digit"),merged}injectSystemValuesInDotenv(env){for(let name of Object.keys(env))name==="VERCEL_URL"?env.VERCEL_URL=this.address.host:name==="VERCEL_REGION"&&(env.VERCEL_REGION="dev1");return env}resolveBuildFiles(files){return Object.keys(files).filter(this.filter)}isWatcherIgnored(fsPath){let relativePath=relative(this.cwd,fsPath);return relativePath===""?!1:!this.filter(relativePath)}start(...listenSpec){return this.startPromise||(this.startPromise=this._start(...listenSpec).catch(async err=>{throw await this.stop(),err})),this.startPromise}async _start(...listenSpec){if(this.stopping)return;if(!import_fs_extra.default.existsSync(this.cwd))throw dev.DEV_CWD_NOT_FOUND({cwd:this.cwd});if(!import_fs_extra.default.lstatSync(this.cwd).isDirectory())throw dev.DEV_CWD_NOT_DIRECTORY({cwd:this.cwd});let{ig}=await(0,import_client.getVercelIgnore)(this.cwd);this.filter=ig.createFilter();let address=this.routing?null:`http://localhost:${this.devCommandPort}`;for(;typeof address!="string";){if(this.stopping)return;try{address=(await(this.listenerStartup=(0,import_async_listen.listen)(this.server,...listenSpec))).toString()}catch(err){if((0,import_error_utils2.isErrnoException)(err))if(output_manager_default.debug(`Got listen error: ${err.code}`),err.code==="EADDRINUSE")typeof listenSpec[0]=="number"?(output_manager_default.note(`Requested port ${import_chalk2.default.yellow(String(listenSpec[0]))} is already in use`),listenSpec[0]++):(this.reportError(dev.DEV_LISTEN_ADDRESS_IN_USE({address:String(listenSpec[0])})),process.exit(1));else throw err;else throw err}}if(this.stopping)return;this._address=new URL2(replaceLocalhost(address)),this.runtimeCache=new RuntimeCacheStore;let devCommandPorts=this.devCommandPort?[this.devCommandPort]:[],runtimeCacheListener=await(this.listenerStartup=listenOnDevResourcePort(this.runtimeCacheServer,{name:"Runtime Cache",flag:"--runtime-cache-port",defaultPort:DEV_RUNTIME_CACHE_DEFAULT_PORT,port:this.runtimeCachePort,reservedPorts:[this.queuePort,this.schedulesPort??DEV_SCHEDULES_DEFAULT_PORT,...devCommandPorts].filter(port=>port!==void 0&&port!==0)}));if(this.stopping)return;this.runtimeCacheOrigin=runtimeCacheListener.origin,runtimeCacheListener.defaultPort!==void 0&&output_manager_default.warn(`Runtime Cache default port ${runtimeCacheListener.defaultPort} is unavailable; listening on ${runtimeCacheListener.port} instead.
|
|
42
|
+
Please ensure that ${cmd(err.path)} is properly installed`,err.link="https://vercel.link/command-not-found"),output_manager_default.prettyError(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}if(devServerResult){requestId=generateRequestId(this.podId,!0);let{port,pid,shutdown,persistent}=devServerResult;this.shutdownCallbacks.set(pid,shutdown),persistent||res.once("close",()=>{this.killBuilderDevServer(pid)}),debug(`Proxying to "${builderPkg.name}" dev server (port=${port}, pid=${pid})`);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search});let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.prepareTransforms(req,requestTransforms,responseTransforms),this.setResponseHeaders(res,requestId),proxyPass(req,res,`http://127.0.0.1:${port}`,this,requestId,!1)}else debug(`Skipping \`startDevServer()\` for ${match.entrypoint}`)}let foundAsset=findAsset(match,requestPath,vercelConfig);if(!foundAsset&&callLevel===0&&(await this.triggerBuild(match,buildRequestPath,req,vercelConfig),foundAsset=findAsset(match,requestPath,vercelConfig)),this.devProcessOrigin&&(!foundAsset||foundAsset&&foundAsset.asset.type!=="Lambda")){debug("Proxying to frontend dev server");let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.prepareTransforms(req,requestTransforms,responseTransforms),this.setResponseHeaders(res,requestId),proxyPass(req,res,this.devProcessOrigin,this,requestId,!1)}if(!foundAsset){await this.send404(req,res,requestId);return}let{asset:asset2,assetKey}=foundAsset;switch(debug(`Serving asset: [${asset2.type}] ${assetKey} ${asset2.contentType||""}`),asset2.type){case"FileFsRef":this.setResponseHeaders(res,requestId);let staticResHeaders={};applyResponseTransforms(staticResHeaders,responseTransforms??[]);for(let[name,value]of Object.entries(staticResHeaders))value!==void 0&&res.setHeader(name,value);return req.url=`/${basename(asset2.fsPath)}`,serveStaticFile(req,res,dirname3(asset2.fsPath),{headers:[{source:"**/*",headers:[{key:"Content-Type",value:asset2.contentType||getMimeType(assetKey)}]}]});case"FileBlob":let headers2={"Content-Length":asset2.data.length,"Content-Type":asset2.contentType||getMimeType(assetKey)};applyResponseTransforms(headers2,responseTransforms??[]),this.setResponseHeaders(res,requestId,headers2),res.end(asset2.data);return;case"Lambda":if(!asset2.fn){await this.sendError(req,res,requestId,"INTERNAL_LAMBDA_NOT_FOUND");return}requestId=generateRequestId(this.podId,!0);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search}),applyRequestTransforms(req,requestTransforms);let path6=req.url||"/",body=await(0,import_raw_body2.default)(req);debug(`Invoking lambda: "${assetKey}" with ${path6}`);let result;try{result=await this.invokeBuiltLambda(asset2,req,requestId,body)}catch(err){console.error(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}statusCode||(res.statusCode=result.statusCode);let lambdaHeaders=result.headers??{};applyResponseTransforms(lambdaHeaders,responseTransforms??[]),this.setResponseHeaders(res,requestId,lambdaHeaders);let resBody;return result.encoding==="base64"&&typeof result.body=="string"?resBody=Buffer.from(result.body,"base64"):resBody=result.body,res.end(resBody);default:await this.sendError(req,res,requestId,"UNKNOWN_ASSET_TYPE")}};if(this.cwd=cwd,this.repoRoot=options.repoRoot??cwd,this.envConfigs={buildEnv:{},runEnv:{},allEnv:{}},this.envValues=options.envValues||{},this.projectId=options.projectId,this.orgId=options.orgId,this.queuePort=options.queuePort,this.runtimeCachePort=options.runtimeCachePort,this.schedulesPort=options.schedulesPort,this.routing=options.routing??!0,this.devCommandPort=options.devCommandPort,this.onConfig=options.onConfig,!this.routing&&!this.devCommandPort)throw new Error("Running without the router needs a `devCommandPort`");this.scheduleBroker=new import_local_schedules2.ScheduleBroker({ownerId:this.orgId??"team_local",projectId:this.projectId??"prj_local",trackId:"development",dispatch:invocation=>this.dispatchSchedule(invocation),onError:(err,invocation)=>{try{output_manager_default.error(`Failed to dispatch schedule "${invocation.schedule.name}": ${(0,import_error_utils2.errorToString)(err)}`)}catch{}}}),this.resourceProxyToken=randomBytes2(32).toString("base64url"),this.reportError=createErrorReporter2(code=>options.onErrorCode?.(code)),this.files={},this.originalProjectSettings=options.projectSettings,this.projectSettings=options.projectSettings,this.services=options.services,this.useImplicitServicesEnvInjection=options.useImplicitServicesEnvInjection??!0,this.caseSensitive=!1,this.apiDir=null,this.apiExtensions=new Set,this.proxy=import_http_proxy_node16.default.createProxyServer({changeOrigin:!0,ws:!0,xfwd:!0}),this.proxy.on("proxyRes",(proxyRes,req)=>{proxyRes.headers.server="Vercel";let responseTransforms=this.responseTransformsByReq.get(req);responseTransforms&&(this.responseTransformsByReq.delete(req),applyResponseTransforms(proxyRes.headers,responseTransforms))}),this.proxy.on("error",(err,req,res)=>{if(output_manager_default.debug(`Proxy error for ${req?.url??"unknown request"}: ${(0,import_error_utils2.errorToString)(err)}`),!!res){if("destroy"in res&&typeof res.destroy=="function"){res.destroy();return}res instanceof http.ServerResponse&&(res.headersSent||res.writeHead(502),res.end())}}),this.server=http.createServer(this.devServerHandler),this.server.timeout=0,this.queueServer=http.createServer((req,res)=>{this.handleResourceServerRequest(req,res,this.queueOrigin,this.handleQueuesRoute)}),this.runtimeCacheServer=http.createServer((req,res)=>{this.handleResourceServerRequest(req,res,this.runtimeCacheOrigin,this.handleRuntimeCacheRoute)}),this.schedulesServer=http.createServer((req,res)=>{this.schedulesSession&&res.setHeader(LOCAL_SCHEDULES_SESSION_HEADER,this.schedulesSession.session.id),this.handleResourceServerRequest(req,res,this.schedulesOrigin,this.handleSchedulesRoute)}),this.stopping=!1,this.buildMatches=new Map,this.inProgressBuilds=new Map,this.devCacheDir=join5(getVercelDirectory(cwd),"cache"),this.vercelConfigWarning=!1,this.getVercelConfigPromise=null,this.blockingBuildsPromise=null,this.startPromise=null,this.bulkRedirects=null,this.bulkRedirectsSignature=null,this.bulkRedirectsLastPath=null,this.bulkRedirectsResolvedPath=null,this.bulkRedirectsDirty=!0,this.watchAggregationId=null,this.watchAggregationEvents=[],this.watchAggregationTimeout=500,this.filter=path6=>!!path6,this.podId=Math.random().toString(32).slice(-5),this.shutdownCallbacks=new Map}get address(){if(!this._address)throw dev.DEV_INTERNAL_ADDRESS_UNAVAILABLE();return this._address}shouldUseServicesOrchestrator(){return!!(this.services&&this.services.length>0)}hasSubscribers(){return!!this.sidecars?.length}getDevQueueEnv(){return this.queueOrigin?getDevQueueEnv(this.queueOrigin,this.hasSubscribers()):{}}getDevRuntimeCacheEnv(env){return!this.runtimeCacheOrigin||env.RUNTIME_CACHE_ENDPOINT?{}:process.env.RUNTIME_CACHE_ENDPOINT?{RUNTIME_CACHE_ENDPOINT:process.env.RUNTIME_CACHE_ENDPOINT,...process.env.RUNTIME_CACHE_HEADERS?{RUNTIME_CACHE_HEADERS:process.env.RUNTIME_CACHE_HEADERS}:{}}:getDevRuntimeCacheEnv(this.runtimeCacheOrigin,DEV_RUNTIME_CACHE_API_PREFIX)}get resourceEndpoints(){if(!this.queueOrigin||!this.runtimeCacheOrigin)throw new Error("Local resource servers have not started");let proxied=(direct,path6)=>this.routing?`${this.address.origin}${path6}`:direct,runtimeCache=`${this.runtimeCacheOrigin}${DEV_RUNTIME_CACHE_API_PREFIX}`;return{queues:{direct:this.queueOrigin,proxy:proxied(this.queueOrigin,`${DEV_QUEUE_PROXY_PREFIX}/${this.resourceProxyToken}`)},runtimeCache:{direct:runtimeCache,proxy:proxied(runtimeCache,`${DEV_RUNTIME_CACHE_PREFIX}${this.resourceProxyToken}${DEV_RUNTIME_CACHE_API_PREFIX}`)},...this.schedulesOrigin?{schedules:{direct:this.schedulesOrigin,proxy:proxied(this.schedulesOrigin,`${DEV_SCHEDULES_PROXY_PREFIX}/${this.resourceProxyToken}`)}}:{}}}getDevResourceMeta(){return{devResourceEndpoints:this.resourceEndpoints}}handleResourceServerRequest(req,res,origin,handler){if(!origin||!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}if(!isValidDevResourceHost(origin,req.headers.host)){res.writeHead(403),res.end("Forbidden");return}let pathname=new URL2(req.url||"/","http://127.0.0.1").pathname;handler(req,res,pathname).catch(err=>{output_manager_default.debug(`Local resource request failed for ${req.url||"/"}: ${(0,import_error_utils2.errorToString)(err)}`),res.headersSent||res.writeHead(500),res.end("Internal Server Error")})}isAuthorizedResourceRequest(req,token){let authorization=req.headers.authorization;if(typeof authorization!="string")return!1;let encoder=new TextEncoder,actual=encoder.encode(authorization),expected=encoder.encode(`Bearer ${token}`);return actual.length===expected.length&&timingSafeEqual(actual,expected)}getBuilderDevEnv(match,env){let result={...env,...getDevSchedulesEnv(this.schedulesOrigin)};if(match.builderWithPkg.pkg.name!=="@vercel/container")return result;let endpoints=this.resourceEndpoints;return Object.assign(result,getDevSchedulesEnv(endpoints.schedules?.proxy,!0)),result.VERCEL_QUEUE_BASE_URL===endpoints.queues.direct&&Object.assign(result,getDevQueueEnv(endpoints.queues.proxy,result.VERCEL_HAS_WORKER_SERVICES!==void 0)),result.RUNTIME_CACHE_ENDPOINT===endpoints.runtimeCache.direct&&Object.assign(result,getDevRuntimeCacheEnv(endpoints.runtimeCache.proxy,"")),result}getSidecarDevMeta(match){let serviceCount=(this.sidecars??[]).filter(sidecar=>sidecar.builder.use!==match.use?!1:!sidecar.workspace||sidecar.workspace===".").length;return serviceCount>0?{serviceCount}:{}}async setupBuilderDevSidecars(){if(this.shouldUseServicesOrchestrator())return;let sidecars=this.sidecars??[];if(sidecars.length===0)return;Object.assign(this.envConfigs.runEnv,this.getDevQueueEnv());let services=sidecars.map(toOrchestratorService),orchestrator=new ServicesOrchestrator({services,cwd:this.cwd,repoRoot:this.repoRoot,env:this.envConfigs.allEnv,proxyOrigin:this.address.origin,resourceEndpoints:this.resourceEndpoints,useImplicitEnvInjection:!1,preferServiceBuilder:!0,onQueueSubscriptions:(serviceName,subscriptions)=>this.queueBroker?.updateServiceSubscriptions(serviceName,subscriptions)});this.sidecarOrchestrator=orchestrator,this.queueBroker?.registerServices(services);try{await orchestrator.startAll()}catch(err){throw await orchestrator.stopAll(),this.sidecarOrchestrator=void 0,this.sidecars=[],err}output_manager_default.log(`Started ${sidecars.length} development ${(0,import_pluralize2.default)("sidecar",sidecars.length)}`)}async exit(code=1){await this.stop(code),process.exit(code)}enqueueFsEvent(type,path6){this.bulkRedirectsResolvedPath&&(path6===this.bulkRedirectsResolvedPath||path6.startsWith(this.bulkRedirectsResolvedPath+sep2))&&(this.bulkRedirectsDirty=!0),this.watchAggregationEvents.push({type,path:path6}),this.watchAggregationId===null&&(this.watchAggregationId=setTimeout(()=>{let events=this.watchAggregationEvents.slice();this.watchAggregationEvents.length=0,this.watchAggregationId=null,this.handleFilesystemEvents(events).catch(err=>{output_manager_default.prettyError(err),(0,import_error_utils2.isError)(err)&&typeof err.stack=="string"&&output_manager_default.debug(err.stack)})},this.watchAggregationTimeout))}async handleFilesystemEvents(events){if(this.stopping)return;output_manager_default.debug(`Filesystem watcher notified of ${events.length} events`);let filesChanged=new Set,filesRemoved=new Set,distPaths=[];for(let buildMatch of this.buildMatches.values())for(let buildResult of buildMatch.buildResults.values())buildResult.distPath&&distPaths.push(buildResult.distPath);if(events=events.filter(event=>distPaths.every(distPath=>!event.path.startsWith(distPath))),events.length!==0){this.functionReconciliations++;try{this.configGeneration++,this.functionDiscovery=void 0;for(let event of events)event.type==="add"?await this.handleFileCreated(event.path,filesChanged,filesRemoved):event.type==="unlink"?this.handleFileDeleted(event.path,filesChanged,filesRemoved):event.type==="change"&&await this.handleFileModified(event.path,filesChanged,filesRemoved);let vercelConfig=await this.getVercelConfig();if(this.stopping)return;await this.updateBuildMatches(vercelConfig);let filesChangedArray=[...filesChanged],filesRemovedArray=[...filesRemoved],needsRebuild=new Map;for(let match of this.buildMatches.values()){this.canonicalizeFunctionBuild(match);for(let[requestPath,result]of match.buildResults)if(!needsRebuild.has(result)&&Array.isArray(result.watch)){for(let pattern of result.watch)if(minimatches(filesChangedArray,pattern)||minimatches(filesRemovedArray,pattern)){needsRebuild.set(result,[requestPath,match]);break}}}if(needsRebuild.size>0){output_manager_default.debug(`Triggering ${needsRebuild.size} rebuilds`),filesChangedArray.length>0&&output_manager_default.debug(`Files changed: ${filesChangedArray.join(", ")}`),filesRemovedArray.length>0&&output_manager_default.debug(`Files removed: ${filesRemovedArray.join(", ")}`);for(let[result,[requestPath,match]]of needsRebuild)requestPath===null||await shouldServe(match,this.files,requestPath,this,vercelConfig)?this.triggerBuild(match,requestPath,null,vercelConfig,result,filesChangedArray,filesRemovedArray).catch(err=>{output_manager_default.warn(`An error occurred while rebuilding \`${match.src}\`:`),console.error(err.stack)}):output_manager_default.debug(`Not rebuilding because \`shouldServe()\` returned \`false\` for "${match.use}" request path "${requestPath}"`)}}finally{this.functionReconciliations--}}}async handleFileCreated(fsPath,changed,removed){let name=relative(this.cwd,fsPath);try{await this.getVercelConfig(),this.files[name]=await import_build_utils9.FileFsRef.fromFsPath({fsPath});let extensionless=this.getExtensionlessFile(name);extensionless&&(this.files[extensionless]=await import_build_utils9.FileFsRef.fromFsPath({fsPath})),fileChanged(name,changed,removed),output_manager_default.debug(`File created: ${name}`)}catch(err){if((0,import_error_utils2.isErrnoException)(err)&&err.code==="ENOENT")output_manager_default.debug(`File created, but has since been deleted: ${name}`),fileRemoved(name,this.files,changed,removed);else throw err}}handleFileDeleted(fsPath,changed,removed){let name=relative(this.cwd,fsPath);output_manager_default.debug(`File deleted: ${name}`),fileRemoved(name,this.files,changed,removed);let extensionless=this.getExtensionlessFile(name);extensionless&&(output_manager_default.debug(`File deleted: ${extensionless}`),fileRemoved(extensionless,this.files,changed,removed))}async handleFileModified(fsPath,changed,removed){let name=relative(this.cwd,fsPath);try{this.files[name]=await import_build_utils9.FileFsRef.fromFsPath({fsPath}),fileChanged(name,changed,removed),output_manager_default.debug(`File modified: ${name}`)}catch(err){if((0,import_error_utils2.isErrnoException)(err)&&err.code==="ENOENT")output_manager_default.debug(`File modified, but has since been deleted: ${name}`),fileRemoved(name,this.files,changed,removed);else throw err}}async updateBuildMatches(vercelConfig,isInitial=!1){let fileList=this.resolveBuildFiles(this.files),matches=await getBuildMatches(vercelConfig,this.cwd,this,fileList),sources=matches.map(m=>m.src);isInitial&&fileList.length===0&&output_manager_default.warn("There are no files inside your deployment.");let ops=[];for(let src of this.buildMatches.keys())if(!sources.includes(src)){output_manager_default.debug(`Removing build match for "${src}"`);let match=this.buildMatches.get(src);match&&ops.push(shutdownBuilder(match)),this.buildMatches.delete(src)}await Promise.all(ops);let blockingBuilds=[];for(let match of matches){let currentMatch=this.buildMatches.get(match.src);if(!buildMatchEquals(currentMatch,match)&&(output_manager_default.debug(`Adding build match for "${match.src}" with "${match.use}"`),this.buildMatches.set(match.src,match),!isInitial&&needsBlockingBuild(match))){let buildPromise=executeBuild(vercelConfig,this,this.files,match,null,!1);blockingBuilds.push(buildPromise)}}if(blockingBuilds.length>0&&(output_manager_default.debug(`Waiting for ${blockingBuilds.length} "blocking builds"`),this.blockingBuildsPromise=Promise.all(blockingBuilds).then(()=>{output_manager_default.debug('Cleaning up "blockingBuildsPromise" after successful resolve'),this.blockingBuildsPromise=null}).catch(err=>{output_manager_default.debug(`Cleaning up "blockingBuildsPromise" after error: ${err}`),this.blockingBuildsPromise=null,err&&output_manager_default.prettyError(err)})),this.buildMatches=new Map([...this.buildMatches.entries()].sort((matchA,matchB)=>sortBuilders(matchA[1],matchB[1]))),isInitial){let warnings=new Set;for(let match of this.buildMatches.values()){let{builder}=match.builderWithPkg;if(!builder.getDevWarnings)continue;let builderWarnings=await builder.getDevWarnings({files:this.files,entrypoint:match.entrypoint,workPath:this.cwd,repoRootPath:this.repoRoot,config:{projectSettings:this.projectSettings,...match.config},meta:{isDev:!0,env:this.getBuilderDevEnv(match,this.envConfigs.runEnv),buildEnv:{...this.envConfigs.buildEnv}}});for(let warning of builderWarnings)warnings.add(warning)}for(let warning of warnings)output_manager_default.warn(warning)}}async getLocalEnv(fileName,base){let filePath=join5(this.cwd,fileName),env={};try{let dotenv=await import_fs_extra.default.readFile(filePath,"utf8");output_manager_default.debug(`Using local env: ${filePath}`),env=(0,import_dotenv.parse)(dotenv),env=this.injectSystemValuesInDotenv(env)}catch(err){if(!(0,import_error_utils2.isErrnoException)(err)||err.code!=="ENOENT")throw err}try{return{...this.validateEnvConfig(fileName,base||{},env)}}catch(err){if(err instanceof MissingDotenvVarsError)this.reportError(err),await this.exit();else throw err}return{}}getVercelConfig(){if(this.getVercelConfigPromise)return this.getVercelConfigPromise;this.getVercelConfigPromise=(async()=>{for(;;){let generation=this.configGeneration;try{let config=await this._getVercelConfig();if(this.stopping||generation===this.configGeneration)return config}catch(err){if(this.stopping||generation===this.configGeneration)throw err}this.functionDiscovery=void 0}})();let clear=this.clearVercelConfigPromise;return this.getVercelConfigPromise.then(clear,clear),this.getVercelConfigPromise}get devCommand(){return this.getDevCommand(this.projectSettings)}get devCommandOrigin(){return this.devProcessOrigin}getDevCommand(projectSettings){if(projectSettings?.devCommand)return projectSettings.devCommand;if(projectSettings?.framework){let frameworkSlug=projectSettings.framework,framework=import_frameworks3.frameworkList.find(f=>f.slug===frameworkSlug);if(framework){let defaults=framework.settings.devCommand.value;if(defaults)return defaults}if((0,import_build_utils9.shouldUseExperimentalBackends)(frameworkSlug))return"npx @vercel/cervel dev"}}getFunctionDiscovery(options){let key=JSON.stringify(options);if(!this.functionDiscovery||this.functionDiscovery.key!==key){let promise=collectDevFunctions(options);this.functionDiscovery={key,promise},promise.catch(()=>{this.functionDiscovery?.promise===promise&&(this.functionDiscovery=void 0)})}return this.functionDiscovery.promise}getDevFunction(outputPath){return this.functionRegistry.functions.get(outputPath)}getDevSchedules(){return this.functionRegistry.schedules}async dispatchSchedule({delivery,signal}){if(signal.throwIfAborted(),this.stopping)throw new Error("Local Schedules is stopping");if(delivery.type==="queue"){if(!this.queueBroker)throw new Error("Local Queue broker is not ready");this.queueBroker.enqueue(delivery.topic,Buffer.from(JSON.stringify(delivery.message)),"application/json");return}if(delivery.type==="path"){if(!this._address)throw new Error(`Schedule path "${delivery.path}" is not ready because vercel dev is not listening yet`);signal.throwIfAborted();let cronSecret=this.envConfigs.runEnv.CRON_SECRET??process.env.CRON_SECRET,response=await directFetch(`${this._address.origin}${delivery.path}`,{method:delivery.requestMethod,headers:{...delivery.headers,...cronSecret?{authorization:`Bearer ${cronSecret}`}:{}},signal});if(!response.ok)throw new Error(`Schedule path "${delivery.path}" returned HTTP ${response.status}`);return}let invoke=this.resolveDevFunction(delivery.function);if(!invoke)throw new Error(`Schedule function "${delivery.function}" is missing or not ready`);signal.throwIfAborted();let onAbort=()=>{},aborted=new Promise((_,reject)=>{onAbort=()=>reject(signal.reason),signal.addEventListener("abort",onAbort,{once:!0})});try{let result=await Promise.race([aborted,invoke({method:"POST",headers:delivery.headers,body:Buffer.alloc(0),signal})]);if(!result)throw new Error(`Schedule function "${delivery.function}" is missing or not ready`);if(!result.ok)throw new Error(`Schedule function "${delivery.function}" returned HTTP ${result.status}`)}finally{signal.removeEventListener("abort",onAbort)}}resolveDevFunction(outputPath){let fn=this.getDevFunction(outputPath);if(!fn||this.stopping)return null;if(fn.invocation.type==="http"){if(!this.devProcessOrigin)return null}else if(!this.functionDispatchReady||this.functionReconciliations>0||!this.getDevFunctionMatch(fn))return null;return request3=>this.invokeDevFunction(outputPath,request3)}getDevFunctionMatch(fn){if(fn.invocation.type!=="entrypoint"||fn.scope.target!=="builder")return;let{entrypoint}=fn.invocation;return[...this.buildMatches.values()].find(match=>match.entrypoint===entrypoint&&match.use===fn.scope.build.use&&(0,import_fast_deep_equal.default)(match.config??{},fn.scope.build.config??{}))}canonicalizeFunctionBuild(match){if(![...this.functionRegistry.functions.values()].some(fn=>this.getDevFunctionMatch(fn)===match))return!1;if(match.buildResults.size&&!(match.buildResults.size===1&&match.buildResults.has(null))){let results=[...match.buildResults.values()],result=results[results.length-1];result.watch=[...new Set(results.flatMap(result2=>result2.watch))],match.buildResults.clear(),match.buildResults.set(null,result)}return!0}async invokeDevFunction(outputPath,request3){request3.signal?.throwIfAborted();let fn=this.getDevFunction(outputPath);if(!fn||!this.resolveDevFunction(outputPath))return null;let generation=this.configGeneration,isCurrent=()=>!this.stopping&&generation===this.configGeneration&&this.getDevFunction(outputPath)===fn;if(fn.invocation.type==="http"){let response=await directFetch(`${this.devProcessOrigin}${fn.invocation.pathname}`,{...request3,redirect:"manual"});return await response.arrayBuffer(),{ok:response.ok,status:response.status}}let match=this.getDevFunctionMatch(fn),config=this.functionConfig,req=new http.IncomingMessage(new Socket);req.method=request3.method,req.url=`/${outputPath}`,req.headers={host:this.address.host,...request3.headers};let requestId=generateRequestId(this.podId,!0),currentMatch=()=>!request3.signal?.aborted&&isCurrent()&&this.getDevFunctionMatch(fn)===match,devServerResult=await this.startBuildMatchDevServer(match,outputPath);if(devServerResult){let{port,pid,shutdown,persistent}=devServerResult;this.shutdownCallbacks.set(pid,shutdown);try{if(!currentMatch())return null;let response=await directFetch(`http://127.0.0.1:${port}/${outputPath}`,{...request3,headers:nodeHeadersToFetchHeaders({...req.headers,...this.getProxyHeaders(req,requestId,!0)}),redirect:"manual"});return await response.arrayBuffer(),{ok:response.ok,status:response.status}}finally{let current=this.getDevFunction(outputPath);(this.stopping||!persistent||!current||this.getDevFunctionMatch(current)!==match)&&this.shutdownCallbacks.has(pid)&&await this.killBuilderDevServer(pid)}}if(!currentMatch())return null;let{entrypoint}=fn.invocation,getAsset=()=>match.buildOutput[(match.buildResultVersion??match.builderWithPkg.builder.version)===2?outputPath:entrypoint];this.canonicalizeFunctionBuild(match);let asset2=getAsset();if((!asset2||this.inProgressBuilds.get(match)?.size)&&(await this.triggerBuild(match,null,null,config),asset2=getAsset()),!currentMatch())return null;if(!asset2||asset2.type!=="Lambda"||!asset2.fn)return{ok:!1,status:404};let result=await this.invokeBuiltLambda(asset2,req,requestId,request3.body);return{ok:result.statusCode>=200&&result.statusCode<300,status:result.statusCode}}async startBuildMatchDevServer(match,requestPath){let{builder}=match.builderWithPkg;if(!builder.startDevServer)return null;let{envConfigs,files,devCacheDir,cwd:workPath}=this;return builder.startDevServer({files,entrypoint:match.entrypoint,workPath,config:match.config||{},repoRootPath:this.repoRoot,meta:{isDev:!0,...this.getDevResourceMeta(),requestPath,devCacheDir,...this.getSidecarDevMeta(match),env:this.getBuilderDevEnv(match,{...envConfigs.runEnv,VERCEL_DEBUG_PREFIX:output_manager_default.debugEnabled?"[builder]":void 0}),buildEnv:{...envConfigs.buildEnv}}})}invokeBuiltLambda(asset2,req,requestId,body){let payload={method:req.method||"GET",host:req.headers.host,path:req.url||"/",headers:{...req.headers,...this.getProxyHeaders(req,requestId,!0)},encoding:"base64",body:body.toString("base64")};return asset2.fn({Action:"Invoke",body:JSON.stringify(payload)})}async _getVercelConfig(){let generation=this.configGeneration,configPath=localConfigFlagPath();if(!configPath){let{compileVercelConfig}=await import("../../chunks/compile-vercel-config-QH77NQ4B.js"),compiled=await compileVercelConfig(this.cwd);configPath=getLocalPathConfig(this.cwd,!!compiled.sourceFile)}let[pkg=null,vercelConfig={version:2,[import_client.fileNameSymbol]:"vercel.json"}]=await Promise.all([this.readJsonFile("package.json"),this.readJsonFile(configPath,!0)]);await this.validateVercelConfig(vercelConfig);let functionConfig=structuredClone(vercelConfig),sourceFiles;for(let[name,service]of Object.entries(this.queueBroker?vercelConfig.services??vercelConfig.experimentalServicesV2??{}:{}))if(Object.values(service.functions??{}).some(fn=>fn.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta")))throw dev.DEV_QUEUE_FUNCTION_UNSUPPORTED({sourceFile:`services.${name}.functions`,reason:"service-hosted function queue triggers are not supported locally yet"});let nextProjectSettings={...this.originalProjectSettings,...pickOverrides(vercelConfig)},{error:routeError,routes:maybeRoutes}=(0,import_routing_utils3.getTransformedRoutes)(vercelConfig);routeError&&(this.reportError(routeError),await this.exit()),vercelConfig.routes=maybeRoutes||[];let hasServices=(this.services?.length??0)>0,hasResolvedServices=!!this.services&&this.services.length>0,schedules=(0,import_build_utils9.getNamedSchedules)(functionConfig.schedules),scheduleEntrypointPlan;if(!hasResolvedServices&&schedules.some(import_schedule_entrypoint.hasScheduleEntrypointTarget)&&(sourceFiles=(await staticFiles(this.cwd,{})).map(f=>relative(this.cwd,f)),scheduleEntrypointPlan=(0,import_schedule_entrypoint.planScheduleEntrypoints)({schedules,files:sourceFiles,framework:nextProjectSettings.framework,functions:functionConfig.functions})),!vercelConfig.experimentalServices&&!hasResolvedServices&&(!vercelConfig.builds||vercelConfig.builds.length===0)){let{projectSettings,cleanUrls,trailingSlash}=vercelConfig,files=sourceFiles??(await staticFiles(this.cwd,{})).map(f=>relative(this.cwd,f));sourceFiles=files;let detectionOptions={tag:"latest",reservedFunctionFiles:scheduleEntrypointPlan?.reservedFunctionFiles,bunVersion:vercelConfig.bunVersion,functions:vercelConfig.functions,projectSettings:projectSettings||nextProjectSettings,featHandleMiss:!0,cleanUrls,trailingSlash,proxy:vercelConfig.proxy,workPath:this.cwd},detectedBuilders=await(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,detectionOptions);for(;detectedBuilders.errors?.length===1&&detectedBuilders.errors[0].code==="unused_function";){let error3=detectedBuilders.errors[0],unmatchedTrigger=Object.entries(detectionOptions.functions??{}).find(([pattern,fn])=>error3.message.startsWith(`The pattern "${pattern}" defined in \`functions\` `)&&fn.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta"||trigger.type==="schedule/v1beta"));if(!unmatchedTrigger)break;detectionOptions.functions={...detectionOptions.functions},delete detectionOptions.functions[unmatchedTrigger[0]],detectedBuilders=await(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,detectionOptions)}let{builders,warnings,errors,defaultRoutes,redirectRoutes,rewriteRoutes,errorRoutes}=detectedBuilders,hostRewriteRoutes=detectedBuilders.hostRewriteRoutes;if(errors){if(this.functionConfig)throw errors[0];this.reportError(errors[0]),await this.exit()}if(warnings?.length>0&&warnings.forEach(warning=>output_manager_default.warn(warning.message,null,warning.link,warning.action)),builders){let buildpackRuntime=builders.map(getBuildpackRuntime).find(runtime=>runtime!==void 0);if(buildpackRuntime)throw buildpackDevUnsupportedError(buildpackRuntime);vercelConfig.builds=vercelConfig.builds||[],vercelConfig.builds.push(...builders),delete vercelConfig.functions}let serviceRewrites=detectedBuilders.serviceRewrites,serviceRewriteRoutes=serviceRewrites&&serviceRewrites.length>0?(0,import_routing_utils3.convertRewrites)(serviceRewrites):null,routes=[];routes.push(...redirectRoutes||[]),routes=(0,import_routing_utils3.appendRoutesToPhase)({routes,newRoutes:hostRewriteRoutes??null,phase:null}),routes.push(...(0,import_routing_utils3.appendRoutesToPhase)({routes:vercelConfig.routes,newRoutes:[...rewriteRoutes||[],...serviceRewriteRoutes||[]],phase:"filesystem"})),routes=(0,import_routing_utils3.appendRoutesToPhase)({routes,newRoutes:errorRoutes,phase:"error"}),routes.push(...defaultRoutes||[]),vercelConfig.routes=routes}else if(hasResolvedServices&&vercelConfig.proxy){let{entrypoint}=vercelConfig.proxy;await import_fs_extra.default.pathExists(join5(this.cwd,entrypoint))||(output_manager_default.error(`The proxy entrypoint \`${entrypoint}\` does not exist. Set \`proxy.entrypoint\` to an existing \`.js\` or \`.ts\` file.`),await this.exit()),vercelConfig.builds=vercelConfig.builds||[],vercelConfig.builds.push((0,import_fs_detectors2.getProxyBuilder)(vercelConfig.proxy,"latest",vercelConfig.functions))}if(this.sidecars===void 0){let services=(this.services??[]).filter(import_build_utils9.isExperimentalServiceV2);this.sidecars=await collectBuilderDevSidecars({builds:this.shouldUseServicesOrchestrator()?services.map(service=>service.builder):vercelConfig.builds??[],workPath:this.cwd,services})}scheduleEntrypointPlan&&(vercelConfig.builds??=[{src:"**",use:"@vercel/static"}],(0,import_schedule_entrypoint.assertNoScheduleEntrypointSourceConflict)(vercelConfig.builds,scheduleEntrypointPlan),vercelConfig.builds.push(...scheduleEntrypointPlan.builds));let functionBuilds=[...vercelConfig.builds??[]];Array.isArray(vercelConfig.builds)&&((this.getDevCommand(nextProjectSettings)||hasServices)&&(vercelConfig.builds=vercelConfig.builds.filter(this.shouldBuildInDev)),vercelConfig.builds.sort(sortBuilders)),vercelConfig.routes=(vercelConfig.routes||[]).filter(route=>"has"in route?(this.vercelConfigWarning||(this.vercelConfigWarning=!0,output_manager_default.warn(`The "has" property in ${vercelConfig[import_client.fileNameSymbol]} will be ignored during development. Deployments will work as expected.`)),!1):!0);let[runEnv,buildEnv]=await Promise.all([this.getLocalEnv(".env",vercelConfig.env),this.getLocalEnv(".env.build",vercelConfig.build?.env)]),allEnv={...buildEnv,...runEnv},envFromCloud=Object.keys(allEnv).length===0;if(envFromCloud){let envValues={...this.envValues};this.address.host&&(envValues.VERCEL_URL=this.address.host),allEnv={...envValues},runEnv={...envValues},buildEnv={...envValues}}runEnv.NODE_ENV??=process.env.NODE_ENV??"development",allEnv.NODE_ENV??=runEnv.NODE_ENV,runEnv.NOW_REGION="dev1",buildEnv.NOW_REGION="dev1",allEnv.NOW_REGION="dev1",allEnv.VERCEL_ENV="development",allEnv.VERCEL="1",this.projectId&&!process.env.VERCEL_PROJECT_ID&&("VERCEL_PROJECT_ID"in allEnv||(allEnv.VERCEL_PROJECT_ID=this.projectId),"VERCEL_PROJECT_ID"in runEnv||(runEnv.VERCEL_PROJECT_ID=this.projectId)),this.orgId&&!process.env.VERCEL_ORG_ID&&("VERCEL_ORG_ID"in allEnv||(allEnv.VERCEL_ORG_ID=this.orgId),"VERCEL_ORG_ID"in runEnv||(runEnv.VERCEL_ORG_ID=this.orgId)),nextProjectSettings?.autoExposeSystemEnvs&&(runEnv.VERCEL_REGION="dev1"),runEnv.VERCEL_CLI_VERSION=pkg_default.version,Object.assign(runEnv,this.getDevQueueEnv()),Object.assign(runEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(allEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(runEnv,this.getDevRuntimeCacheEnv(runEnv));let hasQueueFunctions=Object.values(functionConfig.functions??{}).some(fn=>fn.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta"));if(this.queueBroker&&hasQueueFunctions&&hasResolvedServices)throw dev.DEV_QUEUE_FUNCTION_UNSUPPORTED({sourceFile:"functions",reason:"service-hosted function queue triggers are not supported locally yet"});let registry=await this.getFunctionDiscovery({scopes:(hasResolvedServices?[]:functionBuilds).map(build=>({build,target:vercelConfig.builds?.includes(build)?"builder":"framework"})),workPath:this.cwd,files:(sourceFiles??(await staticFiles(this.cwd,{})).map(f=>relative(this.cwd,f))).sort(),config:functionConfig,env:{...process.env,...allEnv,...this.getDevQueueEnv(),...getDevSchedulesEnv(this.schedulesOrigin),...this.getDevRuntimeCacheEnv(allEnv)}}),subscriptions,staticSchedules,sourceChanged;try{subscriptions=deriveQueueSubscriptions(registry),this.queueBroker?.validateFunctionSubscriptions(subscriptions),staticSchedules=collectStaticSchedules(scheduleEntrypointPlan?(0,import_schedule_entrypoint.resolveScheduleEntrypointTargets)(schedules,scheduleEntrypointPlan):schedules,registry),sourceChanged=!(0,import_fast_deep_equal.default)(this.staticSchedulesSnapshot,staticSchedules),sourceChanged&&this.scheduleBroker.validateStatic(staticSchedules)}catch(err){throw this.functionDiscovery=void 0,err}let{unmatchedPatterns}=registry;if(await this.refreshBulkRedirects(vercelConfig.bulkRedirectsPath),this.devCommandStarts.size&&await Promise.all(this.devCommandStarts),this.stopping||generation!==this.configGeneration)return vercelConfig;let restartForFunctionEnv=!!(this.devCommandEnv&&[...registry.functions.values()].some(fn=>fn.invocation.type==="http")&&!(0,import_fast_deep_equal.default)(this.devCommandEnv,allEnv)),previousProcess=this.devProcess,previousOrigin=this.devProcessOrigin,previousCommand=this.currentDevCommand,previousEnv=this.devCommandEnv,previousRuntime={projectSettings:this.projectSettings,allEnv:previousEnv??this.envConfigs.allEnv},restarted,validated=!1;try{if(this.initialDevCommandStarted&&await this.runDevCommand(restartForFunctionEnv,{projectSettings:nextProjectSettings,allEnv},origin=>{restarted={origin}}),this.stopping||generation!==this.configGeneration)return vercelConfig;this.queueBroker?.validateFunctionSubscriptions(subscriptions),sourceChanged=!(0,import_fast_deep_equal.default)(this.staticSchedulesSnapshot,staticSchedules),sourceChanged&&(this.scheduleBroker.validateStatic(staticSchedules),this.scheduleBroker.reconcileStatic(staticSchedules),this.staticSchedulesSnapshot=structuredClone(staticSchedules)),validated=!0}finally{!this.stopping&&!validated&&(this.devProcess!==previousProcess||this.devProcessOrigin!==previousOrigin||this.currentDevCommand!==previousCommand||this.devCommandEnv!==previousEnv)&&await this.runDevCommand(!0,previousRuntime)}this.projectSettings=nextProjectSettings,this.caseSensitive=hasNewRoutingProperties(vercelConfig),this.apiDir=(0,import_fs_detectors2.detectApiDirectory)(vercelConfig.builds||[]),this.apiExtensions=(0,import_fs_detectors2.detectApiExtensions)(vercelConfig.builds||[]),this.envConfigs={buildEnv,runEnv,allEnv},this.envFromCloud=envFromCloud,this.functionRegistry=registry,this.functionConfig=vercelConfig,restarted&&(this.devProcessOrigin=restarted.origin),this.queueBroker?.setFunctionSubscriptions(subscriptions,outputPath=>this.resolveDevFunction(outputPath));for(let pattern of unmatchedPatterns)if(!this.unmatchedQueuePatterns.has(pattern)){let warning=dev.DEV_QUEUE_FUNCTION_UNMATCHED({pattern});output_manager_default.warn(`[${warning.name}] ${warning.message} ${warning.fix}`)}return this.unmatchedQueuePatterns=new Set(unmatchedPatterns),this.onConfig?.(functionConfig),vercelConfig}async refreshBulkRedirects(bulkRedirectsPath){let configPath=bulkRedirectsPath??null;if(configPath===this.bulkRedirectsLastPath&&!this.bulkRedirectsDirty)return;if(this.bulkRedirectsLastPath=configPath,this.bulkRedirectsDirty=!1,this.bulkRedirectsResolvedPath=configPath?resolveBulkRedirectsPath(this.cwd,configPath):null,!configPath){this.bulkRedirects=null,this.bulkRedirectsSignature=null;return}let signature=await getBulkRedirectsSignature(this.cwd,configPath);if(signature!==this.bulkRedirectsSignature){this.bulkRedirectsSignature=signature;try{let result=await loadBulkRedirects(this.cwd,configPath);this.bulkRedirects=result.table;for(let warning of result.warnings)output_manager_default.warn(warning);let count=result.table.size;count>0&&output_manager_default.log(`Loaded ${count} bulk ${(0,import_pluralize2.default)("redirect",count)} from ${configPath}`)}catch(err){this.bulkRedirects=null,output_manager_default.warn(`Failed to load bulk redirects from "${configPath}": ${(0,import_error_utils2.errorToString)(err)}`)}}}async readJsonFile(filePath,strict=!1){let rel,abs;isAbsolute3(filePath)?(rel=path4.relative(this.cwd,filePath),abs=filePath):(rel=filePath,abs=join5(this.cwd,filePath)),output_manager_default.debug(`Reading \`${rel}\` file`);try{let raw=await import_fs_extra.default.readFile(abs,"utf8"),parsed=(0,import_json_parse_better_errors.default)(raw);return parsed[import_client.fileNameSymbol]=rel,parsed}catch(err){if(strict&&!((0,import_error_utils2.isErrnoException)(err)&&err.code==="ENOENT"))throw err;if((0,import_error_utils2.isError)(err))(0,import_error_utils2.isErrnoException)(err)&&err.code==="ENOENT"?output_manager_default.debug(`No \`${rel}\` file present`):err.name==="SyntaxError"&&output_manager_default.warn(`There is a syntax error in the \`${rel}\` file: ${err.message}`);else throw err}}async tryValidateOrExit(config,validate){let message=validate(config);message&&(output_manager_default.error(message),await this.exit(1))}async validateVercelConfig(config){if(config.version===1){if(this.functionConfig)throw dev.DEV_UNSUPPORTED_CONFIG_VERSION();this.reportError(dev.DEV_UNSUPPORTED_CONFIG_VERSION()),await this.exit(1);return}let error3=validateConfig(config);if(error3){if(this.functionConfig)throw error3;this.reportError(error3),await this.exit(1)}}validateEnvConfig(type,env={},localEnv={}){let missing=Object.entries(env).filter(([name,value])=>typeof value=="string"&&value.startsWith("@")&&!hasProp(localEnv,name)).map(([name])=>name);if(missing.length>0)throw new MissingDotenvVarsError(type,missing);let merged={...env,...localEnv},hasInvalidName=!1;for(let key of Object.keys(merged))/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)||(output_manager_default.warn(`Ignoring ${type.split(".").slice(1).reverse().join(" ")} var ${JSON.stringify(key)} because name is invalid`),hasInvalidName=!0,delete merged[key]);return hasInvalidName&&output_manager_default.log("The name contains invalid characters. Only letters, digits, and underscores are allowed. Furthermore, the name should not start with a digit"),merged}injectSystemValuesInDotenv(env){for(let name of Object.keys(env))name==="VERCEL_URL"?env.VERCEL_URL=this.address.host:name==="VERCEL_REGION"&&(env.VERCEL_REGION="dev1");return env}resolveBuildFiles(files){return Object.keys(files).filter(this.filter)}isWatcherIgnored(fsPath){let relativePath=relative(this.cwd,fsPath);return relativePath===""?!1:!this.filter(relativePath)}start(...listenSpec){return this.startPromise||(this.startPromise=this._start(...listenSpec).catch(async err=>{throw await this.stop(),err})),this.startPromise}async _start(...listenSpec){if(this.stopping)return;if(!import_fs_extra.default.existsSync(this.cwd))throw dev.DEV_CWD_NOT_FOUND({cwd:this.cwd});if(!import_fs_extra.default.lstatSync(this.cwd).isDirectory())throw dev.DEV_CWD_NOT_DIRECTORY({cwd:this.cwd});let{ig}=await(0,import_client.getVercelIgnore)(this.cwd);this.filter=ig.createFilter();let address=this.routing?null:`http://localhost:${this.devCommandPort}`;for(;typeof address!="string";){if(this.stopping)return;try{address=(await(this.listenerStartup=(0,import_async_listen.listen)(this.server,...listenSpec))).toString()}catch(err){if((0,import_error_utils2.isErrnoException)(err))if(output_manager_default.debug(`Got listen error: ${err.code}`),err.code==="EADDRINUSE")typeof listenSpec[0]=="number"?(output_manager_default.note(`Requested port ${import_chalk2.default.yellow(String(listenSpec[0]))} is already in use`),listenSpec[0]++):(this.reportError(dev.DEV_LISTEN_ADDRESS_IN_USE({address:String(listenSpec[0])})),process.exit(1));else throw err;else throw err}}if(this.stopping)return;this._address=new URL2(replaceLocalhost(address)),this.runtimeCache=new RuntimeCacheStore;let devCommandPorts=this.devCommandPort?[this.devCommandPort]:[],runtimeCacheListener=await(this.listenerStartup=listenOnDevResourcePort(this.runtimeCacheServer,{name:"Runtime Cache",flag:"--runtime-cache-port",defaultPort:DEV_RUNTIME_CACHE_DEFAULT_PORT,port:this.runtimeCachePort,reservedPorts:[this.queuePort,this.schedulesPort??DEV_SCHEDULES_DEFAULT_PORT,...devCommandPorts].filter(port=>port!==void 0&&port!==0)}));if(this.stopping)return;this.runtimeCacheOrigin=runtimeCacheListener.origin,runtimeCacheListener.defaultPort!==void 0&&output_manager_default.warn(`Runtime Cache default port ${runtimeCacheListener.defaultPort} is unavailable; listening on ${runtimeCacheListener.port} instead.
|
|
43
43
|
External clients configured for ${runtimeCacheListener.defaultPort} will not reach this dev server. Pin a port with --runtime-cache-port.`);let queueListener=await(this.listenerStartup=listenOnDevResourcePort(this.queueServer,{name:"Vercel Queues",flag:"--queue-port",defaultPort:DEV_QUEUE_DEFAULT_PORT,port:this.queuePort,reservedPorts:[this.schedulesPort??DEV_SCHEDULES_DEFAULT_PORT,...devCommandPorts]}));if(this.stopping)return;this.queueOrigin=queueListener.origin,queueListener.defaultPort!==void 0&&output_manager_default.warn(`Vercel Queues default port ${queueListener.defaultPort} is unavailable; listening on ${queueListener.port} instead.
|
|
44
44
|
External clients configured for ${queueListener.defaultPort} will not reach this dev server. Pin a port with --queue-port.`),this.queueBroker=new QueueBroker([],name=>this.orchestrator?.getServiceOrigin(name)??this.sidecarOrchestrator?.getServiceOrigin(name)??null);let schedulesListener=await(this.listenerStartup=listenOnDevResourcePort(this.schedulesServer,{name:"Vercel Schedules",flag:"--schedules-port",defaultPort:DEV_SCHEDULES_DEFAULT_PORT,port:this.schedulesPort,reservedPorts:devCommandPorts}));if(this.stopping||(this.schedulesOrigin=schedulesListener.origin,this.schedulesSessionPublication=createLocalSchedulesSession(this.cwd,`http://127.0.0.1:${schedulesListener.port}`,this.projectId??"prj_local").then(async published=>{this.stopping?await published.dispose():this.schedulesSession=published}),await this.schedulesSessionPublication,this.stopping))return;schedulesListener.defaultPort!==void 0&&output_manager_default.print(import_chalk2.default.yellow(`! Vercel Schedules default port ${schedulesListener.defaultPort} is unavailable; listening on ${schedulesListener.port} instead.
|
|
45
45
|
Pin a port with --schedules-port for clients outside the dev server.
|
|
@@ -61,7 +61,7 @@ ${error_code}
|
|
|
61
61
|
`}}var RELEASE_TIMEOUT_MS=2e3;async function reserveAlias(client,org,projectId,alias){try{return await client.fetch("/v1/dev-tunnel/aliases",{method:"POST",accountId:org.id,body:{projectId,alias}}),"reserved"}catch(err){if(isAPIError(err)&&err.status===409)return"held";if(isAPIError(err)&&err.status===404)return"unsupported";throw err}}async function releaseAlias(client,org,projectId,alias){try{await client.fetch(`/v1/dev-tunnel/aliases/${encodeURIComponent(alias)}?projectId=${encodeURIComponent(projectId)}`,{method:"DELETE",accountId:org.id,signal:AbortSignal.timeout(RELEASE_TIMEOUT_MS)})}catch(err){output_manager_default.debug(`Could not release the tunnel's lease on ${alias}: ${err}`)}}import{createHash as createHash2}from"node:crypto";import{mkdir,readFile as readFile2,writeFile}from"node:fs/promises";import{dirname as dirname4,join as join6}from"node:path";function proxyKey(parts){return createHash2("sha256").update(JSON.stringify(parts)).digest("hex")}function proxyRecordPath(orgId,projectId,globalDir=getGlobalPathConfig()){return join6(globalDir,"dev-tunnels",`${orgId}.${projectId}.json`)}var PROXY_MAX_AGE_MS=7*24*60*60*1e3;async function readProxy(path6){try{let proxy=JSON.parse(await readFile2(path6,"utf8"));if(!proxy.key||!proxy.id||!proxy.url)return;let replaces=(Array.isArray(proxy.replaces)?proxy.replaces:[proxy.replaces]).filter(id=>typeof id=="string");return{key:proxy.key,id:proxy.id,url:proxy.url,...replaces.length>0&&{replaces}}}catch{return}}async function isReusable(proxy,key,getDeployment,now=Date.now()){if(proxy.key!==key)return!1;try{let{readyState,createdAt,target}=await getDeployment(proxy.id);return target!=="production"&&readyState==="READY"&&createdAt!==void 0&&now-createdAt<PROXY_MAX_AGE_MS}catch{return!1}}async function rememberProxy(path6,proxy){try{await mkdir(dirname4(path6),{recursive:!0}),await writeFile(path6,`${JSON.stringify(proxy,null,2)}
|
|
62
62
|
`)}catch{}}function proxyDeployer(options){let{client,org,projectId,projectName,rootDirectory,env,signal,alias:tunnelAlias}=options,record=options.record??proxyRecordPath(org.id,projectId),current,currentUrl="",ours=new Set,claimed=!1,deployedBefore=!1,leased,urlOf=async({id,url:url4})=>{if(!tunnelAlias)return url4;let alias=aliasUnder(tunnelAlias.label,url4);try{let lease=tunnelAlias.chosen?await reserveAlias(client,org,projectId,alias):"unsupported";if(lease==="held")throw new TunnelError(`Can't use ${alias} for the tunnel. Another developer's tunnel holds it.`);if(lease==="reserved"&&(leased=alias),await aliasHeldElsewhere(client,org,alias,{userId:tunnelAlias.userId,ours,leased:lease==="reserved"}))throw lease==="reserved"&&(await releaseAlias(client,org,projectId,alias),leased=void 0),new TunnelError(`Can't use ${alias} for the tunnel. It points at another deployment.`);return await assignAlias(client,org,id,alias),claimed=!0,`https://${alias}`}catch(err){if(tunnelAlias.chosen&&!tunnelAlias.resumed&&!claimed)throw leased&&(await releaseAlias(client,org,projectId,leased),leased=void 0),err instanceof TunnelError?err:new TunnelError(`Couldn't use ${alias} for the tunnel.`,{remote:{source:"Vercel API",message:isAPIError(err)?err.serverMessage:err instanceof Error?err.message:String(err)}});return output_manager_default.warning(err instanceof TunnelError?`${err.message} The tunnel's URL changes with each deploy.`:formatTunnelError(`Couldn't point ${alias} at the tunnel's proxy, so its URL changes with each deploy.`,err)),url4}};return Object.assign(async routes=>{let files=tunnelDeploymentFiles(routes),key=proxyKey({files,env,rootDirectory:rootDirectory??null});if(current?.key===key)return currentUrl;let previous=current??await readProxy(record),stale=previous?.replaces??[];previous&&ours.add(previous.id);for(let id2 of stale)ours.add(id2);let moved=()=>!tunnelAlias||currentUrl!==current?.url,replaceAll=async ids=>{let leftover=[...new Set(ids)].filter(old=>old!==current?.id);if(moved())for(let old of leftover)deleteProxy(client,org,old);else current&&leftover.length>0&&(current={...current,replaces:leftover});current&&await rememberProxy(record,current)};if(previous&&await isReusable(previous,key,id2=>client.fetch(`/v13/deployments/${encodeURIComponent(id2)}`,{accountId:org.id})))return current={key:previous.key,id:previous.id,url:previous.url},currentUrl=await urlOf(current),stale.length>0&&await replaceAll(stale),currentUrl;let replaced=previous?[previous.id,...stale]:[];if(signal?.throwIfAborted(),deployedBefore||=await hasDeployment(client,org,projectId),!deployedBefore)throw new TunnelError(`Can't deploy the tunnel proxy. ${projectName} has never been deployed, so its first deployment would be production. Deploy it once with \`vercel deploy\`, then run \`vercel dev --tunnel\` again.`);output_manager_default.print(` Deploying the tunnel proxy
|
|
63
63
|
`);let{id,url:url4}=await deployProxy(client,org,projectName,await materializeDeployment(files,rootDirectory),env,{signal,onCreated:created=>{let replaces=[...new Set(replaced)].filter(id2=>id2!==created.id);return rememberProxy(record,{key,...created,...replaces.length>0&&{replaces}})}});ours.add(id);let replacing=current!==void 0;return current={key,id,url:url4},currentUrl=await urlOf(current),await replaceAll(replaced),replacing&¤tUrl!==url4&&output_manager_default.print(` The tunnel serves the new routes
|
|
64
|
-
`),currentUrl},{async release(){leased&&await releaseAlias(client,org,projectId,leased)}})}async function materializeDeployment(files,rootDirectory){let dir=await mkdtemp(join7(tmpdir(),"vc-dev-tunnel-")),base=rootDirectory?join7(dir,rootDirectory):dir;for(let[relative3,contents]of Object.entries(files)){let file=join7(base,relative3);await mkdir2(dirname5(file),{recursive:!0}),await writeFile2(file,contents)}return dir}async function deployProxy(client,org,projectName,path6,env,{signal,onCreated}={}){let token=client.authConfig.token;if(!token)throw new Error("Missing authentication token");let inspectorUrl,events=(0,import_client2.createDeployment)({teamId:org.type==="team"?org.id:void 0,apiUrl:client.apiUrl,token,getAuthHeaders:client.getAuthHeaders,userAgent:ua_default,path:path6,projectName,skipAutoDetectionConfirmation:!0,dispatcher:getFetchDispatcher(),debug:output_manager_default.isDebugEnabled()},{name:projectName,env,meta:PROXY_META,projectSettings:{framework:null,buildCommand:null,installCommand:null,outputDirectory:null,devCommand:null}});try{for(;;){let next=await untilAborted(events.next(),signal);if(next.done)break;let event=next.value;if(event.type==="created")inspectorUrl=event.payload.inspectorUrl??void 0,await onCreated?.({id:event.payload.id,url:`https://${event.payload.url}`});else{if(event.type==="ready")return{id:event.payload.id,url:`https://${event.payload.url}`};if(event.type==="canceled")throw new TunnelError("The tunnel proxy deployment was canceled.",{inspectorUrl});if(event.type==="error"){let message=event.payload?.message;throw new TunnelError("Failed to deploy the tunnel proxy.",{...message&&{remote:{source:"Deployment",message}},inspectorUrl})}}}}finally{events.return?.(void 0)}throw new TunnelError("The tunnel proxy deployment never became ready.",{inspectorUrl})}function untilAborted(promise,signal){return signal?(signal.throwIfAborted(),new Promise((resolve3,reject)=>{let onAbort=()=>reject(signal.reason);signal.addEventListener("abort",onAbort,{once:!0}),promise.then(value=>{signal.removeEventListener("abort",onAbort),resolve3(value)},err=>{signal.removeEventListener("abort",onAbort),reject(err)})})):promise}async function hasDeployment(client,org,projectId){let{deployments}=await client.fetch(`/v6/deployments?projectId=${encodeURIComponent(projectId)}&limit=1`,{accountId:org.id});return deployments.length>0}async function deleteProxy(client,org,id){let url4=`/v13/deployments/${encodeURIComponent(id)}`;try{let{target}=await client.fetch(url4,{accountId:org.id});if(target==="production"){output_manager_default.debug(`Keeping the replaced tunnel proxy ${id}: it's production`);return}await client.fetch(url4,{method:"DELETE",accountId:org.id})}catch(err){output_manager_default.debug(`Could not delete the replaced tunnel proxy ${id}: ${err}`)}}function reserveTunnel(client,org,projectId){return client.fetch("/v1/dev-tunnel",{method:"POST",accountId:org.id,body:{projectId}})}async function startTunnel(options){let{client,org,projectId,projectName,rootDirectory,target}=options;output_manager_default.debug("Connecting tunnel");let reservation=await reserveTunnel(client,org,projectId),tunnel=connectTunnel({relayUrl:reservation.relayUrl,clientToken:reservation.clientToken,renewToken:async()=>{let renewed=await reserveTunnel(client,org,projectId);if(renewed.serverToken!==reservation.serverToken||renewed.relayUrl!==reservation.relayUrl)throw new TunnelReplacedError;return renewed.clientToken},target});try{await tunnel.ready;let user=await getUser(client),proxyFor=proxyDeployer({client,org,projectId,projectName,rootDirectory,signal:options.signal,alias:{label:options.aliasLabel??tunnelAliasLabel(projectName,user.username,org),chosen:options.aliasLabel!==void 0,resumed:options.resumed,userId:user.id},env:{[RELAY_URL_ENV]:reservation.relayUrl,[SERVER_TOKEN_ENV]:reservation.serverToken,[PORT_ENV]:String(targetPort(target))}}),url4=await proxyFor(options.routes??[]),deploys=Promise.resolve();return{...tunnel,url:url4,setRoutes:routes=>{let deployed=deploys.then(()=>proxyFor(routes));return deploys=deployed.catch(()=>{}),deployed},release:()=>proxyFor.release()}}catch(err){throw tunnel.close(),err}}import{setTimeout as setTimeout2}from"node:timers/promises";var import_ms7=__toESM(require_ms(),1);import{performance as performance2}from"perf_hooks";var REFRESH_BEFORE_EXPIRY_MILLIS=getMs((0,import_ms7.default)("15m"),process.env.REFRESH_VERCEL_OIDC_TOKEN_BEFORE_EXPIRY_MILLIS),THROTTLE_MILLIS=getMs((0,import_ms7.default)("1m"),process.env.REFRESH_VERCEL_OIDC_TOKEN_THROTTLE_MILLIS);function getMs(defaultValue,overrideValue){if(overrideValue){let result=(0,import_ms7.default)(overrideValue);if(Number.isFinite(result)&&result>0)return result}return defaultValue}async function*refreshOidcToken(signal,client,projectId,envValues,source,throttleMillis){throttleMillis??=THROTTLE_MILLIS;let lastPulledEnvAt=clock(),refreshCount=0;for(;!signal.aborted;){let oidcToken=envValues[VERCEL_OIDC_TOKEN];if(!oidcToken){output_manager_default.debug(`${VERCEL_OIDC_TOKEN} is absent; disabling refreshes`);return}let now=clock(),expiresAfterMillis;try{let{exp}=decodeJwt(oidcToken);expiresAfterMillis=exp!==void 0?exp*1e3-now:void 0}catch{}if(expiresAfterMillis===void 0||!Number.isFinite(expiresAfterMillis)){output_manager_default.debug(`${VERCEL_OIDC_TOKEN} is invalid; disabling refreshes`);return}refreshCount++>0&&expiresAfterMillis>0&&(yield oidcToken);let refreshAfterMillis=Math.max(0,expiresAfterMillis-REFRESH_BEFORE_EXPIRY_MILLIS);now+refreshAfterMillis-lastPulledEnvAt<throttleMillis&&(refreshAfterMillis=throttleMillis);let expiresAfterSecs=Math.abs(Math.round(millisToSecs(expiresAfterMillis))),refreshAfterSecs=Math.round(millisToSecs(refreshAfterMillis));expiresAfterMillis<0?output_manager_default.debug(`${VERCEL_OIDC_TOKEN} expired ${expiresAfterSecs}s ago; refreshing in ${refreshAfterSecs}s`):output_manager_default.debug(`${VERCEL_OIDC_TOKEN} expires in ${expiresAfterSecs}s; refreshing in ${refreshAfterSecs}s`),await setTimeout2(refreshAfterMillis,void 0,{signal});let envValuesOrNull=await pullEnvValuesUntilSuccessful(signal,client,projectId,source,throttleMillis);if(!envValuesOrNull)return;envValues=envValuesOrNull,lastPulledEnvAt=clock()}}async function pullEnvValuesUntilSuccessful(signal,client,projectId,source,millis){for(;!signal.aborted;)try{return(await pullEnvRecords(client,projectId,source)).env}catch{output_manager_default.debug(`Failed to pull environment; trying again in ${Math.round(millisToSecs(millis))}s`),await setTimeout2(millis,void 0,{signal})}return null}function clock(){return performance2.timeOrigin+performance2.now()}function millisToSecs(millis){return millis/1e3}import{join as join8}from"path";import{mkdir as mkdir3,open,unlink,readFile as readFile3}from"fs/promises";import{unlinkSync as unlinkSync2,constants as constants2}from"fs";var DEV_LOCK_FILE="dev.lock";function isProcessRunning(pid){try{return process.kill(pid,0),!0}catch{return!1}}async function tryCreateLockFile(lockPath,content){try{let fd=await open(lockPath,constants2.O_CREAT|constants2.O_EXCL|constants2.O_WRONLY);return await fd.writeFile(content,"utf8"),await fd.close(),!0}catch(err){if(err.code==="EEXIST")return!1;throw err}}async function tryReadLockFile(lockPath){try{let content=await readFile3(lockPath,"utf8");return JSON.parse(content)}catch{return null}}async function acquireDevLock(projectRoot,port){let vercelDir=join8(projectRoot,VERCEL_DIR),lockPath=join8(vercelDir,DEV_LOCK_FILE);await mkdir3(vercelDir,{recursive:!0});let lockData={pid:process.pid,port,startedAt:Date.now(),cwd:projectRoot},lockContent=JSON.stringify(lockData);try{if(await tryCreateLockFile(lockPath,lockContent))return{acquired:!0}}catch(err){output_manager_default.debug(`Failed to create lock file: ${err}`)}let existingLock=await tryReadLockFile(lockPath);if(existingLock){if(isProcessRunning(existingLock.pid))return{acquired:!1,existingLock};output_manager_default.debug(`Removing stale lock from PID ${existingLock.pid}`);try{await unlink(lockPath)}catch(err){output_manager_default.debug(`Failed to remove stale lock file: ${err}`)}try{if(await tryCreateLockFile(lockPath,lockContent))return{acquired:!0}}catch(err){output_manager_default.debug(`Failed to create lock after removing stale: ${err}`)}let newLock=await tryReadLockFile(lockPath);if(newLock)return{acquired:!1,existingLock:newLock}}else output_manager_default.debug("Lock file exists but cannot be read");return{acquired:!1,existingLock:null,reason:`The lock file at \`${lockPath}\` could not be read. If no other \`vercel dev\` is running, remove it and retry.`}}function releaseDevLock(projectRoot){let lockPath=join8(projectRoot,VERCEL_DIR,DEV_LOCK_FILE);try{unlinkSync2(lockPath)}catch(err){output_manager_default.debug(`Failed to release lock: ${err}`)}}function parseResourcePort(value,flag){if(value===void 0)return;if(!/^\d+$/.test(value))throw new Error(`${flag} must be an integer between 0 and 65535`);let port=Number(value);if(!Number.isSafeInteger(port)||port>65535)throw new Error(`${flag} must be an integer between 0 and 65535`);return port}async function dev2(client,opts,args,telemetry,localConfig){let[dir="."]=args,cwd=resolve2(dir),localConfigCwd=cwd,listen2=parseListen(opts["--listen"]||"3000"),queuePort=parseResourcePort(opts["--queue-port"],"--queue-port"),runtimeCachePort=parseResourcePort(opts["--runtime-cache-port"],"--runtime-cache-port"),schedulesPort=parseResourcePort(opts["--schedules-port"],"--schedules-port"),resourcePorts=[["--queue-port",queuePort],["--runtime-cache-port",runtimeCachePort],["--schedules-port",schedulesPort]];for(let[index,[flag,port]]of resourcePorts.entries()){let duplicate=resourcePorts.slice(0,index).find(([,otherPort])=>port!==void 0&&port!==0&&port===otherPort);if(duplicate)throw new Error(`${duplicate[0]} and ${flag} must use different ports`)}cwd=await resolveProjectCwd(cwd);let projectNameOrId=opts["--project"],reportError=createErrorReporter2(code=>telemetry.trackError(code)),link=await getLinkedProject(client,{cwd,projectName:projectNameOrId,projectNameIsExplicit:!!projectNameOrId,scopeIsExplicit:detectExplicitScope(client)});if(link.status==="not_linked"&&!process.env.__VERCEL_SKIP_DEV_CMD)if(opts["--local"])output_manager_default.warn(`Running dev server in local mode without a project setup:
|
|
64
|
+
`),currentUrl},{async release(){leased&&await releaseAlias(client,org,projectId,leased)}})}async function materializeDeployment(files,rootDirectory){let dir=await mkdtemp(join7(tmpdir(),"vc-dev-tunnel-")),base=rootDirectory?join7(dir,rootDirectory):dir;for(let[relative3,contents]of Object.entries(files)){let file=join7(base,relative3);await mkdir2(dirname5(file),{recursive:!0}),await writeFile2(file,contents)}return dir}async function deployProxy(client,org,projectName,path6,env,{signal,onCreated}={}){let token=client.authConfig.token;if(!token)throw new Error("Missing authentication token");let inspectorUrl,events=(0,import_client2.createDeployment)({teamId:org.type==="team"?org.id:void 0,apiUrl:client.apiUrl,token,getAuthHeaders:client.getAuthHeaders,userAgent:ua_default,path:path6,projectName,skipAutoDetectionConfirmation:!0,dispatcher:getFetchDispatcher(),debug:output_manager_default.isDebugEnabled()},{name:projectName,env,meta:PROXY_META,projectSettings:{framework:null,buildCommand:null,installCommand:null,outputDirectory:null,devCommand:null}});try{for(;;){let next=await untilAborted(events.next(),signal);if(next.done)break;let event=next.value;if(event.type==="created")inspectorUrl=event.payload.inspectorUrl??void 0,await onCreated?.({id:event.payload.id,url:`https://${event.payload.url}`});else{if(event.type==="ready")return{id:event.payload.id,url:`https://${event.payload.url}`};if(event.type==="canceled")throw new TunnelError("The tunnel proxy deployment was canceled.",{inspectorUrl});if(event.type==="error"){let message=event.payload?.message;throw new TunnelError("Failed to deploy the tunnel proxy.",{...message&&{remote:{source:"Deployment",message}},inspectorUrl})}}}}finally{events.return?.(void 0)}throw new TunnelError("The tunnel proxy deployment never became ready.",{inspectorUrl})}function untilAborted(promise,signal){return signal?(signal.throwIfAborted(),new Promise((resolve3,reject)=>{let onAbort=()=>reject(signal.reason);signal.addEventListener("abort",onAbort,{once:!0}),promise.then(value=>{signal.removeEventListener("abort",onAbort),resolve3(value)},err=>{signal.removeEventListener("abort",onAbort),reject(err)})})):promise}async function deleteProxy(client,org,id){let url4=`/v13/deployments/${encodeURIComponent(id)}`;try{let{target}=await client.fetch(url4,{accountId:org.id});if(target==="production"){output_manager_default.debug(`Keeping the replaced tunnel proxy ${id}: it's production`);return}await client.fetch(url4,{method:"DELETE",accountId:org.id})}catch(err){output_manager_default.debug(`Could not delete the replaced tunnel proxy ${id}: ${err}`)}}function reserveTunnel(client,org,projectId){return client.fetch("/v1/dev-tunnel",{method:"POST",accountId:org.id,body:{projectId}})}async function startTunnel(options){let{client,org,projectId,projectName,rootDirectory,target}=options;output_manager_default.debug("Connecting tunnel");let reservation=await reserveTunnel(client,org,projectId),tunnel=connectTunnel({relayUrl:reservation.relayUrl,clientToken:reservation.clientToken,renewToken:async()=>{let renewed=await reserveTunnel(client,org,projectId);if(renewed.serverToken!==reservation.serverToken||renewed.relayUrl!==reservation.relayUrl)throw new TunnelReplacedError;return renewed.clientToken},target});try{await tunnel.ready;let user=await getUser(client),proxyFor=proxyDeployer({client,org,projectId,projectName,rootDirectory,signal:options.signal,alias:{label:options.aliasLabel??tunnelAliasLabel(projectName,user.username,org),chosen:options.aliasLabel!==void 0,resumed:options.resumed,userId:user.id},env:{[RELAY_URL_ENV]:reservation.relayUrl,[SERVER_TOKEN_ENV]:reservation.serverToken,[PORT_ENV]:String(targetPort(target))}}),url4=await proxyFor(options.routes??[]),deploys=Promise.resolve();return{...tunnel,url:url4,setRoutes:routes=>{let deployed=deploys.then(()=>proxyFor(routes));return deploys=deployed.catch(()=>{}),deployed},release:()=>proxyFor.release()}}catch(err){throw tunnel.close(),err}}import{setTimeout as setTimeout2}from"node:timers/promises";var import_ms7=__toESM(require_ms(),1);import{performance as performance2}from"perf_hooks";var REFRESH_BEFORE_EXPIRY_MILLIS=getMs((0,import_ms7.default)("15m"),process.env.REFRESH_VERCEL_OIDC_TOKEN_BEFORE_EXPIRY_MILLIS),THROTTLE_MILLIS=getMs((0,import_ms7.default)("1m"),process.env.REFRESH_VERCEL_OIDC_TOKEN_THROTTLE_MILLIS);function getMs(defaultValue,overrideValue){if(overrideValue){let result=(0,import_ms7.default)(overrideValue);if(Number.isFinite(result)&&result>0)return result}return defaultValue}async function*refreshOidcToken(signal,client,projectId,envValues,source,throttleMillis){throttleMillis??=THROTTLE_MILLIS;let lastPulledEnvAt=clock(),refreshCount=0;for(;!signal.aborted;){let oidcToken=envValues[VERCEL_OIDC_TOKEN];if(!oidcToken){output_manager_default.debug(`${VERCEL_OIDC_TOKEN} is absent; disabling refreshes`);return}let now=clock(),expiresAfterMillis;try{let{exp}=decodeJwt(oidcToken);expiresAfterMillis=exp!==void 0?exp*1e3-now:void 0}catch{}if(expiresAfterMillis===void 0||!Number.isFinite(expiresAfterMillis)){output_manager_default.debug(`${VERCEL_OIDC_TOKEN} is invalid; disabling refreshes`);return}refreshCount++>0&&expiresAfterMillis>0&&(yield oidcToken);let refreshAfterMillis=Math.max(0,expiresAfterMillis-REFRESH_BEFORE_EXPIRY_MILLIS);now+refreshAfterMillis-lastPulledEnvAt<throttleMillis&&(refreshAfterMillis=throttleMillis);let expiresAfterSecs=Math.abs(Math.round(millisToSecs(expiresAfterMillis))),refreshAfterSecs=Math.round(millisToSecs(refreshAfterMillis));expiresAfterMillis<0?output_manager_default.debug(`${VERCEL_OIDC_TOKEN} expired ${expiresAfterSecs}s ago; refreshing in ${refreshAfterSecs}s`):output_manager_default.debug(`${VERCEL_OIDC_TOKEN} expires in ${expiresAfterSecs}s; refreshing in ${refreshAfterSecs}s`),await setTimeout2(refreshAfterMillis,void 0,{signal});let envValuesOrNull=await pullEnvValuesUntilSuccessful(signal,client,projectId,source,throttleMillis);if(!envValuesOrNull)return;envValues=envValuesOrNull,lastPulledEnvAt=clock()}}async function pullEnvValuesUntilSuccessful(signal,client,projectId,source,millis){for(;!signal.aborted;)try{return(await pullEnvRecords(client,projectId,source)).env}catch{output_manager_default.debug(`Failed to pull environment; trying again in ${Math.round(millisToSecs(millis))}s`),await setTimeout2(millis,void 0,{signal})}return null}function clock(){return performance2.timeOrigin+performance2.now()}function millisToSecs(millis){return millis/1e3}import{join as join8}from"path";import{mkdir as mkdir3,open,unlink,readFile as readFile3}from"fs/promises";import{unlinkSync as unlinkSync2,constants as constants2}from"fs";var DEV_LOCK_FILE="dev.lock";function isProcessRunning(pid){try{return process.kill(pid,0),!0}catch{return!1}}async function tryCreateLockFile(lockPath,content){try{let fd=await open(lockPath,constants2.O_CREAT|constants2.O_EXCL|constants2.O_WRONLY);return await fd.writeFile(content,"utf8"),await fd.close(),!0}catch(err){if(err.code==="EEXIST")return!1;throw err}}async function tryReadLockFile(lockPath){try{let content=await readFile3(lockPath,"utf8");return JSON.parse(content)}catch{return null}}async function acquireDevLock(projectRoot,port){let vercelDir=join8(projectRoot,VERCEL_DIR),lockPath=join8(vercelDir,DEV_LOCK_FILE);await mkdir3(vercelDir,{recursive:!0});let lockData={pid:process.pid,port,startedAt:Date.now(),cwd:projectRoot},lockContent=JSON.stringify(lockData);try{if(await tryCreateLockFile(lockPath,lockContent))return{acquired:!0}}catch(err){output_manager_default.debug(`Failed to create lock file: ${err}`)}let existingLock=await tryReadLockFile(lockPath);if(existingLock){if(isProcessRunning(existingLock.pid))return{acquired:!1,existingLock};output_manager_default.debug(`Removing stale lock from PID ${existingLock.pid}`);try{await unlink(lockPath)}catch(err){output_manager_default.debug(`Failed to remove stale lock file: ${err}`)}try{if(await tryCreateLockFile(lockPath,lockContent))return{acquired:!0}}catch(err){output_manager_default.debug(`Failed to create lock after removing stale: ${err}`)}let newLock=await tryReadLockFile(lockPath);if(newLock)return{acquired:!1,existingLock:newLock}}else output_manager_default.debug("Lock file exists but cannot be read");return{acquired:!1,existingLock:null,reason:`The lock file at \`${lockPath}\` could not be read. If no other \`vercel dev\` is running, remove it and retry.`}}function releaseDevLock(projectRoot){let lockPath=join8(projectRoot,VERCEL_DIR,DEV_LOCK_FILE);try{unlinkSync2(lockPath)}catch(err){output_manager_default.debug(`Failed to release lock: ${err}`)}}function parseResourcePort(value,flag){if(value===void 0)return;if(!/^\d+$/.test(value))throw new Error(`${flag} must be an integer between 0 and 65535`);let port=Number(value);if(!Number.isSafeInteger(port)||port>65535)throw new Error(`${flag} must be an integer between 0 and 65535`);return port}async function dev2(client,opts,args,telemetry,localConfig){let[dir="."]=args,cwd=resolve2(dir),localConfigCwd=cwd,listen2=parseListen(opts["--listen"]||"3000"),queuePort=parseResourcePort(opts["--queue-port"],"--queue-port"),runtimeCachePort=parseResourcePort(opts["--runtime-cache-port"],"--runtime-cache-port"),schedulesPort=parseResourcePort(opts["--schedules-port"],"--schedules-port"),resourcePorts=[["--queue-port",queuePort],["--runtime-cache-port",runtimeCachePort],["--schedules-port",schedulesPort]];for(let[index,[flag,port]]of resourcePorts.entries()){let duplicate=resourcePorts.slice(0,index).find(([,otherPort])=>port!==void 0&&port!==0&&port===otherPort);if(duplicate)throw new Error(`${duplicate[0]} and ${flag} must use different ports`)}cwd=await resolveProjectCwd(cwd);let projectNameOrId=opts["--project"],reportError=createErrorReporter2(code=>telemetry.trackError(code)),link=await getLinkedProject(client,{cwd,projectName:projectNameOrId,projectNameIsExplicit:!!projectNameOrId,scopeIsExplicit:detectExplicitScope(client)});if(link.status==="not_linked"&&!process.env.__VERCEL_SKIP_DEV_CMD)if(opts["--local"])output_manager_default.warn(`Running dev server in local mode without a project setup:
|
|
65
65
|
- Environment variables will not be pulled from Vercel
|
|
66
66
|
- Project settings are defined by local configuration
|
|
67
67
|
|
|
@@ -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{require_dist as require_dist3}from"../../chunks/chunk-JELLVPCM.js";import{readStandardInput}from"../../chunks/chunk-PSOVLGHP.js";import"../../chunks/chunk-XOETL6DB.js";import{ENV_VISIBILITY_DEPRECATION_MESSAGE,SENSITIVE_ENV_VALUE_PLACEHOLDER,formatVisibilityLabel,getApiPublicPrefix,getEnvKeyWarnings,getFrameworkPublicPrefix,getLocalSecretFallbackMessage,getLocalSvelteKitPublicPrefixes,getPublicPrefix,getPublicPrefixSecretVisibilityError,getUnavailableSecretValuesMessage,isFlagsSecretNeedingSplit,isSecretEnvVar,looksLikeSecret,looksLikeSecretValue,normalizeStdinEnvValue,pull,removePublicPrefix,resolveEnvVarTypeOption,resolveEnvVarVisibility,shouldConfirmRotationBeforeDelete,validateEnvValue}from"../../chunks/chunk-KUNFE2M6.js";import{getCustomEnvironments}from"../../chunks/chunk-F7AVGV4Y.js";import{getEnvRecords,pullEnvRecords}from"../../chunks/chunk-PY5A73YH.js";import"../../chunks/chunk-6Y2ZL5XJ.js";import{suggestNextCommands}from"../../chunks/chunk-XK3W6Q5I.js";import{parseTarget}from"../../chunks/chunk-WRC5CTUD.js";import"../../chunks/chunk-25565AGS.js";import{formatEnvironment}from"../../chunks/chunk-F76MNMH3.js";import{STANDARD_ENVIRONMENTS}from"../../chunks/chunk-7YKFF6CE.js";import{resolveProjectContext}from"../../chunks/chunk-JULKMXVP.js";import{formatProject}from"../../chunks/chunk-YRK2BCTJ.js";import{isGuidanceEnabled}from"../../chunks/chunk-TAAWMNNL.js";import"../../chunks/chunk-IHNEF3BG.js";import{ellipsis}from"../../chunks/chunk-AKOYIH3A.js";import"../../chunks/chunk-TOTTVS5P.js";import"../../chunks/chunk-NDWGYZRT.js";import"../../chunks/chunk-QIPUFI6P.js";import"../../chunks/chunk-6KCYUYUM.js";import"../../chunks/chunk-PVASGBEF.js";import"../../chunks/chunk-ZBJ44DRL.js";import{CHECKBOX_INSTRUCTIONS}from"../../chunks/chunk-OFDTADPQ.js";import{require_execa}from"../../chunks/chunk-T34C75TI.js";import"../../chunks/chunk-GD7AV7BO.js";import{validateLsArgs}from"../../chunks/chunk-T2SRGJPU.js";import{getInvalidSubcommand}from"../../chunks/chunk-TG2RCYTH.js";import{formatTable}from"../../chunks/chunk-44XDCARR.js";import{stamp_default}from"../../chunks/chunk-A2RZZQEP.js";import"../../chunks/chunk-OTJNOMRV.js";import"../../chunks/chunk-2QSNFVB6.js";import"../../chunks/chunk-Q7D7RGXM.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-YEPB52XE.js";import{getCommandAliases}from"../../chunks/chunk-2PYFJXKS.js";import"../../chunks/chunk-3KSTUMR6.js";import"../../chunks/chunk-EZL4AJXH.js";import"../../chunks/chunk-45UDRX4C.js";import"../../chunks/chunk-J52UJYOK.js";import"../../chunks/chunk-GZWYJT4C.js";import"../../chunks/chunk-3AXMZRAB.js";import"../../chunks/chunk-FQVSBXRY.js";import"../../chunks/chunk-GP5MFCGO.js";import"../../chunks/chunk-V5A4EBV3.js";import"../../chunks/chunk-IECNFRTK.js";import"../../chunks/chunk-A6F3EE2O.js";import"../../chunks/chunk-K2R3QPOC.js";import"../../chunks/chunk-IHRM7L23.js";import"../../chunks/chunk-HTFQFHPR.js";import"../../chunks/chunk-LFOWP74R.js";import"../../chunks/chunk-DBV6AB6T.js";import"../../chunks/chunk-37DIJCWK.js";import"../../chunks/chunk-7E6UJXLR.js";import"../../chunks/chunk-JALVF3C2.js";import{addSubcommand,envCommand,envTargetChoices,getEnvTargetPlaceholder,isValidEnvTarget,listSubcommand,parseEnvTargetArg,pullSubcommand,removeSubcommand,resolveEnvTargetInput,runSubcommand,updateSubcommand}from"../../chunks/chunk-7V2PXIVW.js";import{printError}from"../../chunks/chunk-D3GYYGSS.js";import{help}from"../../chunks/chunk-33U57CNE.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import"../../chunks/chunk-IU6PHFPQ.js";import{TelemetryClient}from"../../chunks/chunk-SBBD2Q5A.js";import"../../chunks/chunk-2EYYB6YN.js";import"../../chunks/chunk-NWGBDBZI.js";import{buildCommandWithYes,buildEnvAddCommandWithPreservedArgs,buildEnvRmCommandWithPreservedArgs,buildEnvUpdateCommandWithPreservedArgs,getLinkSuggestionArgs,getPreservedArgsForEnvAdd,getPreservedArgsForEnvRm,getPreservedArgsForEnvUpdate,outputActionRequired,outputAgentError,redactEnvValueArgs,withGlobalFlags}from"../../chunks/chunk-KAUKCHQF.js";import"../../chunks/chunk-QLW5DCM4.js";import{getLinkFromDir,getVercelDirectory}from"../../chunks/chunk-QZEZCUUZ.js";import{printAlignedLabel}from"../../chunks/chunk-3LQ2ADXO.js";import"../../chunks/chunk-MCP63EVQ.js";import"../../chunks/chunk-4NTBYNFR.js";import{parseArguments}from"../../chunks/chunk-KIMIK4SG.js";import{getTeamByIdOrSlug,quoteArg}from"../../chunks/chunk-F53OKXYI.js";import{validateJsonOutput}from"../../chunks/chunk-JRBPVMQO.js";import"../../chunks/chunk-LUX4PBJL.js";import"../../chunks/chunk-OPORM35X.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import"../../chunks/chunk-OCR5CRTH.js";import"../../chunks/chunk-4SAVH3H7.js";import{isAPIError}from"../../chunks/chunk-FXEMEIST.js";import{getCommandName,getCommandNamePlain,require_lib}from"../../chunks/chunk-JESNVRVR.js";import{emoji,output_manager_default,prependEmoji,require_build_utils}from"../../chunks/chunk-ZRJKGAUT.js";import"../../chunks/chunk-BLUPZPAS.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import"../../chunks/chunk-YHPPP3SF.js";import"../../chunks/chunk-OO572JUC.js";import{require_dist as require_dist2}from"../../chunks/chunk-PUKYAALC.js";import{getFlagsSpecification,getGlobalFlagsFromArgs}from"../../chunks/chunk-YPPDRKVC.js";import"../../chunks/chunk-2BKALEOP.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BULSRTQE.js";import"../../chunks/chunk-BRQUZ5NC.js";import"../../chunks/chunk-5O7CRJE5.js";import"../../chunks/chunk-U3J7VS56.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-SCV7XEEO.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_chalk=__toESM(require_source(),1);var import_constants=__toESM(require_dist2(),1);async function addEnvRecord(client,projectId,upsert,type,key,value,targets,gitBranch,visibility){let actionWord=upsert?"Overriding":"Adding";output_manager_default.debug(`${actionWord} ${type} Environment Variable ${key} to ${targets.length} targets`);let target=[],customEnvironmentIds=[];for(let t of targets)(import_constants.PROJECT_ENV_TARGET.includes(t)?target:customEnvironmentIds).push(t);let body={type,key,value,target,customEnvironmentIds:customEnvironmentIds.length>0?customEnvironmentIds:void 0,gitBranch:gitBranch||void 0,...visibility!==void 0?{visibility}:{}},args=upsert?`?upsert=${upsert}`:"",url=`/v10/projects/${projectId}/env${args}`;await client.fetch(url,{method:"POST",body})}var import_error_utils=__toESM(require_dist(),1),knownErrorsCodes=new Set(["BAD_REQUEST","ENV_ALREADY_EXISTS","ENV_CONFLICT","EXISTING_KEY_AND_TARGET","FORBIDDEN","ID_NOT_FOUND","INVALID_KEY","INVALID_VALUE","KEY_INVALID_CHARACTERS","KEY_INVALID_LENGTH","KEY_RESERVED","RESERVED_ENV_VARIABLE","MAX_ENVS_EXCEEDED","MISSING_ID","MISSING_KEY","MISSING_TARGET","MISSING_VALUE","NOT_AUTHORIZED","NOT_DECRYPTABLE","SYSTEM_ENV_WITH_VALUE","TEAM_NOT_FOUND","TOO_MANY_IDS","TOO_MANY_KEYS","UNKNOWN_ERROR","VALUE_INVALID_LENGTH","VALUE_INVALID_TYPE"]);function isKnownError(error){let code=(0,import_error_utils.isErrnoException)(error)?error.code:null;return code?knownErrorsCodes.has(code.toUpperCase()):!1}var EnvAddTelemetryClient=class extends TelemetryClient{trackCliArgumentName(name){name&&this.trackCliArgument({arg:"name",value:this.redactedValue})}trackCliArgumentEnvironment(environment){if(environment){let allStandard=environment.split(",").map(t=>t.trim()).every(t=>STANDARD_ENVIRONMENTS.includes(t));this.trackCliArgument({arg:"environment",value:allStandard?environment:this.redactedValue})}}trackCliArgumentGitBranch(gitBranch){gitBranch&&this.trackCliArgument({arg:"git-branch",value:this.redactedValue})}trackCliOptionGitBranch(gitBranch){gitBranch&&this.trackCliOption({option:"git-branch",value:this.redactedValue})}trackCliOptionEnvironment(environments){if(environments&&environments.length>0){let allStandard=environments.flatMap(environment=>environment.split(",")).map(t=>t.trim()).every(t=>STANDARD_ENVIRONMENTS.includes(t));this.trackCliOption({option:"environment",value:allStandard?environments.join(","):this.redactedValue})}}trackCliOptionValue(value){value&&this.trackCliOption({option:"value",value:this.redactedValue})}trackCliOptionVisibility(visibility){if(visibility){let validVisibilities=["config","secret"];this.trackCliOption({option:"visibility",value:validVisibilities.includes(visibility)?visibility:this.redactedValue})}}trackCliOptionType(type){if(type){let validTypes=["config","secret"];this.trackCliOption({option:"type",value:validTypes.includes(type)?type:this.redactedValue})}}trackCliFlagSensitive(sensitive){sensitive&&this.trackCliFlag("sensitive")}trackCliFlagNoSensitive(noSensitive){noSensitive&&this.trackCliFlag("no-sensitive")}trackCliFlagForce(force){force&&this.trackCliFlag("force")}trackCliFlagGuidance(guidance){guidance&&this.trackCliFlag("guidance")}trackCliFlagYes(yes){yes&&this.trackCliFlag("yes")}};import{determineAgent}from"@vercel/detect-agent";function includesDevelopment(targets){return targets.length===0||targets.includes("development")}function getProductionSecretPolicyErrorKind(message){return/production secrets?.*different value|different value.*production secrets?/i.test(message)?"different-values":/production secrets?.*(?:own environment group|separat)|(?:own environment group|separat).*production secrets?/i.test(message)?"separate-environments":null}function getProductionSecretPolicyRecovery(kind){return kind==="different-values"?"Use different Secret values for Production and non-Production.":"Create separate Production and non-Production variables with different values."}function getSecretStorageChoice(targets,recommendedReason){let availability=includesDevelopment(targets)?"hidden in the dashboard; Development values can be pulled":"hidden in the dashboard and unavailable to pulls",recommendation=recommendedReason?`; recommended ${recommendedReason}`:"";return`Secret (${availability}${recommendation})`}function getDefaultSecretStorageGuidance(targets){return includesDevelopment(targets)?"Stored as Secret by default. This value is hidden in the dashboard; Development values can be pulled. Use `--type config` for other values you need to read later.":"Stored as Secret by default. This value is hidden in the dashboard and unavailable to pulls; use `--type config` for values you need to read later."}function looksLikeCredentialName(key,publicPrefix=getPublicPrefix(key)){return looksLikeSecret(publicPrefix?key.slice(publicPrefix.length):key)}function filterEnvChoicesForSensitivity(choices,opts){return opts.policyOn?choices.filter(c=>c.value==="development"):choices}function getTargetCompatibilityError(envTargets,isSensitive,policyOn){let hasSensitiveCapable=envTargets.some(t=>t!=="development");return!isSensitive&&policyOn&&hasSensitiveCapable?`Your team requires sensitive Environment Variables for Production and Preview. To add a non-sensitive value, add it to the Development Environment only. Run ${getCommandName("env add --environment development")} instead.`:null}function resolveFinalType(envTargets,isSensitive,opts){return envTargets.includes("development")&&!isSensitive||opts.forceEncrypted&&!opts.policyOn?"encrypted":isSensitive||opts.forceSensitive||opts.policyOn?"sensitive":"encrypted"}function fillEnvAddTemplate(template,opts){let targetPlaceholder=getEnvTargetPlaceholder();return template.replace(/<name>/g,opts.envName?quoteArg(opts.envName):"<name>").split(targetPlaceholder).join(opts.envTargetArg?quoteArg(opts.envTargetArg):targetPlaceholder).replace(/<BRANCH>/g,opts.envGitBranch?quoteArg(opts.envGitBranch):"<BRANCH>").replace(/<value>/g,"<value>")}function multiTargetSuggestion(argv,envName,targets,addNoSensitive){let flag=addNoSensitive?" --no-sensitive":"";return{command:buildEnvAddCommandWithPreservedArgs(argv,`env add ${envName} --environment ${targets.join(",")} --value "<value>"${flag} --yes`),when:addNoSensitive?"Add one non-sensitive variable to all listed environments":"Add one variable to multiple environments"}}function filterSensitiveMultiTargetSuggestionTargets(targets,_opts){return targets}function projectLabel(link){return`${link.org.slug}/${link.project.name}`}function formatEnvironmentTarget(target,customEnvironments){let standardTarget=envTargetChoices.find(choice=>choice.value===target);return standardTarget?standardTarget.name:customEnvironments.find(env=>env.id===target||env.slug===target)?.slug??target}function formatEnvironmentTargets(envTargets,customEnvironments){return envTargets.map(target=>formatEnvironmentTarget(target,customEnvironments)).join(", ")}function printEnvAddResult(link,envName,envTargets,envGitBranch,customEnvironments,finalType,force,visibility){output_manager_default.print(`
|
|
7
|
+
import{require_dist as require_dist3}from"../../chunks/chunk-JELLVPCM.js";import{readStandardInput}from"../../chunks/chunk-PSOVLGHP.js";import"../../chunks/chunk-XOETL6DB.js";import{ENV_VISIBILITY_DEPRECATION_MESSAGE,SENSITIVE_ENV_VALUE_PLACEHOLDER,formatVisibilityLabel,getApiPublicPrefix,getEnvKeyWarnings,getFrameworkPublicPrefix,getLocalSecretFallbackMessage,getLocalSvelteKitPublicPrefixes,getPublicPrefix,getPublicPrefixSecretVisibilityError,getUnavailableSecretValuesMessage,isFlagsSecretNeedingSplit,isSecretEnvVar,looksLikeSecret,looksLikeSecretValue,normalizeStdinEnvValue,pull,removePublicPrefix,resolveEnvVarTypeOption,resolveEnvVarVisibility,shouldConfirmRotationBeforeDelete,validateEnvValue}from"../../chunks/chunk-QANIGEPP.js";import{getCustomEnvironments}from"../../chunks/chunk-F7AVGV4Y.js";import{getEnvRecords,pullEnvRecords}from"../../chunks/chunk-5WFOL3XX.js";import"../../chunks/chunk-6Y2ZL5XJ.js";import{suggestNextCommands}from"../../chunks/chunk-IZ4GFKGR.js";import{parseTarget}from"../../chunks/chunk-D4TD2KWH.js";import{formatEnvironment}from"../../chunks/chunk-VR5ROBAO.js";import{STANDARD_ENVIRONMENTS}from"../../chunks/chunk-7YKFF6CE.js";import{resolveProjectContext}from"../../chunks/chunk-EEFLZK52.js";import{formatProject}from"../../chunks/chunk-TD7AL545.js";import{isGuidanceEnabled}from"../../chunks/chunk-TAAWMNNL.js";import"../../chunks/chunk-5XPWRDZN.js";import"../../chunks/chunk-25565AGS.js";import{ellipsis}from"../../chunks/chunk-AKOYIH3A.js";import"../../chunks/chunk-TOTTVS5P.js";import"../../chunks/chunk-IDP63TCP.js";import"../../chunks/chunk-VU3RBRDH.js";import"../../chunks/chunk-4VF5BZJP.js";import"../../chunks/chunk-PVASGBEF.js";import"../../chunks/chunk-Y3ZO6WB7.js";import{CHECKBOX_INSTRUCTIONS}from"../../chunks/chunk-OFDTADPQ.js";import{require_execa}from"../../chunks/chunk-RCUDI7OF.js";import"../../chunks/chunk-GD7AV7BO.js";import{validateLsArgs}from"../../chunks/chunk-BT5C6MCY.js";import{getInvalidSubcommand}from"../../chunks/chunk-TG2RCYTH.js";import{formatTable}from"../../chunks/chunk-2RXUQ72I.js";import{stamp_default}from"../../chunks/chunk-A2RZZQEP.js";import"../../chunks/chunk-375JVQYK.js";import"../../chunks/chunk-K5YO4UD7.js";import"../../chunks/chunk-Q7D7RGXM.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-Y6WXTTZS.js";import{getCommandAliases}from"../../chunks/chunk-NTUDWWSL.js";import"../../chunks/chunk-M73W4XNR.js";import"../../chunks/chunk-32AS5X7G.js";import"../../chunks/chunk-ZBZPCKTW.js";import"../../chunks/chunk-TRZDIAX3.js";import"../../chunks/chunk-GHEGWXH2.js";import"../../chunks/chunk-GCXUSXB4.js";import"../../chunks/chunk-2H4DUZJZ.js";import"../../chunks/chunk-ECQKK4JU.js";import"../../chunks/chunk-JOXGYP5S.js";import"../../chunks/chunk-7ULVGK67.js";import"../../chunks/chunk-4BZ3DNGM.js";import"../../chunks/chunk-R5ZLTWKB.js";import"../../chunks/chunk-T5TOBY4D.js";import"../../chunks/chunk-H34SGIVS.js";import"../../chunks/chunk-5DXC4TE2.js";import"../../chunks/chunk-G3LWP5CH.js";import"../../chunks/chunk-QQA2OMXJ.js";import"../../chunks/chunk-KV2DYFUG.js";import"../../chunks/chunk-JALVF3C2.js";import{addSubcommand,envCommand,envTargetChoices,getEnvTargetPlaceholder,isValidEnvTarget,listSubcommand,parseEnvTargetArg,pullSubcommand,removeSubcommand,resolveEnvTargetInput,runSubcommand,updateSubcommand}from"../../chunks/chunk-GCPPL24C.js";import{printError}from"../../chunks/chunk-BWS3ZOHJ.js";import{help}from"../../chunks/chunk-33U57CNE.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import"../../chunks/chunk-5ZEROVK5.js";import{TelemetryClient}from"../../chunks/chunk-NAU6URTI.js";import"../../chunks/chunk-2EYYB6YN.js";import"../../chunks/chunk-NWGBDBZI.js";import{buildCommandWithYes,buildEnvAddCommandWithPreservedArgs,buildEnvRmCommandWithPreservedArgs,buildEnvUpdateCommandWithPreservedArgs,getLinkSuggestionArgs,getPreservedArgsForEnvAdd,getPreservedArgsForEnvRm,getPreservedArgsForEnvUpdate,outputActionRequired,outputAgentError,redactEnvValueArgs,withGlobalFlags}from"../../chunks/chunk-32NXYHYC.js";import"../../chunks/chunk-FWTBSC7Z.js";import{getLinkFromDir,getVercelDirectory}from"../../chunks/chunk-CBA2KGXG.js";import{printAlignedLabel}from"../../chunks/chunk-64UCX5JM.js";import"../../chunks/chunk-ITQPDXXA.js";import"../../chunks/chunk-7WY7ASKE.js";import"../../chunks/chunk-4NTBYNFR.js";import{parseArguments}from"../../chunks/chunk-CGTD4QFC.js";import{getTeamByIdOrSlug,quoteArg}from"../../chunks/chunk-F53OKXYI.js";import{validateJsonOutput}from"../../chunks/chunk-GJCVOEC2.js";import"../../chunks/chunk-LUX4PBJL.js";import"../../chunks/chunk-OPORM35X.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import"../../chunks/chunk-4SAVH3H7.js";import{isAPIError}from"../../chunks/chunk-T2FCF46I.js";import{getCommandName,getCommandNamePlain,require_lib}from"../../chunks/chunk-VRH7LWOC.js";import"../../chunks/chunk-DBT6PGEH.js";import{emoji,output_manager_default,prependEmoji}from"../../chunks/chunk-W634OFUG.js";import"../../chunks/chunk-BLUPZPAS.js";import"../../chunks/chunk-ZS2WS4AM.js";import{require_build_utils}from"../../chunks/chunk-5MDNVAE6.js";import"../../chunks/chunk-OCR5CRTH.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_dist as require_dist2}from"../../chunks/chunk-PUKYAALC.js";import{getFlagsSpecification,getGlobalFlagsFromArgs}from"../../chunks/chunk-YPPDRKVC.js";import"../../chunks/chunk-2BKALEOP.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BULSRTQE.js";import"../../chunks/chunk-BRQUZ5NC.js";import"../../chunks/chunk-D6REP5QQ.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-MY4MONOH.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-SCV7XEEO.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_chalk=__toESM(require_source(),1);var import_constants=__toESM(require_dist2(),1);async function addEnvRecord(client,projectId,upsert,type,key,value,targets,gitBranch,visibility){let actionWord=upsert?"Overriding":"Adding";output_manager_default.debug(`${actionWord} ${type} Environment Variable ${key} to ${targets.length} targets`);let target=[],customEnvironmentIds=[];for(let t of targets)(import_constants.PROJECT_ENV_TARGET.includes(t)?target:customEnvironmentIds).push(t);let body={type,key,value,target,customEnvironmentIds:customEnvironmentIds.length>0?customEnvironmentIds:void 0,gitBranch:gitBranch||void 0,...visibility!==void 0?{visibility}:{}},args=upsert?`?upsert=${upsert}`:"",url=`/v10/projects/${projectId}/env${args}`;await client.fetch(url,{method:"POST",body})}var import_error_utils=__toESM(require_dist(),1),knownErrorsCodes=new Set(["BAD_REQUEST","ENV_ALREADY_EXISTS","ENV_CONFLICT","EXISTING_KEY_AND_TARGET","FORBIDDEN","ID_NOT_FOUND","INVALID_KEY","INVALID_VALUE","KEY_INVALID_CHARACTERS","KEY_INVALID_LENGTH","KEY_RESERVED","RESERVED_ENV_VARIABLE","MAX_ENVS_EXCEEDED","MISSING_ID","MISSING_KEY","MISSING_TARGET","MISSING_VALUE","NOT_AUTHORIZED","NOT_DECRYPTABLE","SYSTEM_ENV_WITH_VALUE","TEAM_NOT_FOUND","TOO_MANY_IDS","TOO_MANY_KEYS","UNKNOWN_ERROR","VALUE_INVALID_LENGTH","VALUE_INVALID_TYPE"]);function isKnownError(error){let code=(0,import_error_utils.isErrnoException)(error)?error.code:null;return code?knownErrorsCodes.has(code.toUpperCase()):!1}var EnvAddTelemetryClient=class extends TelemetryClient{trackCliArgumentName(name){name&&this.trackCliArgument({arg:"name",value:this.redactedValue})}trackCliArgumentEnvironment(environment){if(environment){let allStandard=environment.split(",").map(t=>t.trim()).every(t=>STANDARD_ENVIRONMENTS.includes(t));this.trackCliArgument({arg:"environment",value:allStandard?environment:this.redactedValue})}}trackCliArgumentGitBranch(gitBranch){gitBranch&&this.trackCliArgument({arg:"git-branch",value:this.redactedValue})}trackCliOptionGitBranch(gitBranch){gitBranch&&this.trackCliOption({option:"git-branch",value:this.redactedValue})}trackCliOptionEnvironment(environments){if(environments&&environments.length>0){let allStandard=environments.flatMap(environment=>environment.split(",")).map(t=>t.trim()).every(t=>STANDARD_ENVIRONMENTS.includes(t));this.trackCliOption({option:"environment",value:allStandard?environments.join(","):this.redactedValue})}}trackCliOptionValue(value){value&&this.trackCliOption({option:"value",value:this.redactedValue})}trackCliOptionVisibility(visibility){if(visibility){let validVisibilities=["config","secret"];this.trackCliOption({option:"visibility",value:validVisibilities.includes(visibility)?visibility:this.redactedValue})}}trackCliOptionType(type){if(type){let validTypes=["config","secret"];this.trackCliOption({option:"type",value:validTypes.includes(type)?type:this.redactedValue})}}trackCliFlagSensitive(sensitive){sensitive&&this.trackCliFlag("sensitive")}trackCliFlagNoSensitive(noSensitive){noSensitive&&this.trackCliFlag("no-sensitive")}trackCliFlagForce(force){force&&this.trackCliFlag("force")}trackCliFlagGuidance(guidance){guidance&&this.trackCliFlag("guidance")}trackCliFlagYes(yes){yes&&this.trackCliFlag("yes")}};import{determineAgent}from"@vercel/detect-agent";function includesDevelopment(targets){return targets.length===0||targets.includes("development")}function getProductionSecretPolicyErrorKind(message){return/production secrets?.*different value|different value.*production secrets?/i.test(message)?"different-values":/production secrets?.*(?:own environment group|separat)|(?:own environment group|separat).*production secrets?/i.test(message)?"separate-environments":null}function getProductionSecretPolicyRecovery(kind){return kind==="different-values"?"Use different Secret values for Production and non-Production.":"Create separate Production and non-Production variables with different values."}function getSecretStorageChoice(targets,recommendedReason){let availability=includesDevelopment(targets)?"hidden in the dashboard; Development values can be pulled":"hidden in the dashboard and unavailable to pulls",recommendation=recommendedReason?`; recommended ${recommendedReason}`:"";return`Secret (${availability}${recommendation})`}function getDefaultSecretStorageGuidance(targets){return includesDevelopment(targets)?"Stored as Secret by default. This value is hidden in the dashboard; Development values can be pulled. Use `--type config` for other values you need to read later.":"Stored as Secret by default. This value is hidden in the dashboard and unavailable to pulls; use `--type config` for values you need to read later."}function looksLikeCredentialName(key,publicPrefix=getPublicPrefix(key)){return looksLikeSecret(publicPrefix?key.slice(publicPrefix.length):key)}function filterEnvChoicesForSensitivity(choices,opts){return opts.policyOn?choices.filter(c=>c.value==="development"):choices}function getTargetCompatibilityError(envTargets,isSensitive,policyOn){let hasSensitiveCapable=envTargets.some(t=>t!=="development");return!isSensitive&&policyOn&&hasSensitiveCapable?`Your team requires sensitive Environment Variables for Production and Preview. To add a non-sensitive value, add it to the Development Environment only. Run ${getCommandName("env add --environment development")} instead.`:null}function resolveFinalType(envTargets,isSensitive,opts){return envTargets.includes("development")&&!isSensitive||opts.forceEncrypted&&!opts.policyOn?"encrypted":isSensitive||opts.forceSensitive||opts.policyOn?"sensitive":"encrypted"}function fillEnvAddTemplate(template,opts){let targetPlaceholder=getEnvTargetPlaceholder();return template.replace(/<name>/g,opts.envName?quoteArg(opts.envName):"<name>").split(targetPlaceholder).join(opts.envTargetArg?quoteArg(opts.envTargetArg):targetPlaceholder).replace(/<BRANCH>/g,opts.envGitBranch?quoteArg(opts.envGitBranch):"<BRANCH>").replace(/<value>/g,"<value>")}function multiTargetSuggestion(argv,envName,targets,addNoSensitive){let flag=addNoSensitive?" --no-sensitive":"";return{command:buildEnvAddCommandWithPreservedArgs(argv,`env add ${envName} --environment ${targets.join(",")} --value "<value>"${flag} --yes`),when:addNoSensitive?"Add one non-sensitive variable to all listed environments":"Add one variable to multiple environments"}}function filterSensitiveMultiTargetSuggestionTargets(targets,_opts){return targets}function projectLabel(link){return`${link.org.slug}/${link.project.name}`}function formatEnvironmentTarget(target,customEnvironments){let standardTarget=envTargetChoices.find(choice=>choice.value===target);return standardTarget?standardTarget.name:customEnvironments.find(env=>env.id===target||env.slug===target)?.slug??target}function formatEnvironmentTargets(envTargets,customEnvironments){return envTargets.map(target=>formatEnvironmentTarget(target,customEnvironments)).join(", ")}function printEnvAddResult(link,envName,envTargets,envGitBranch,customEnvironments,finalType,force,visibility){output_manager_default.print(`
|
|
8
8
|
`),printAlignedLabel(force?"Overrode":"Added",envName,{gutter:"\u2713"}),printAlignedLabel("Project",projectLabel(link)),printAlignedLabel("Environments",formatEnvironmentTargets(envTargets,customEnvironments)),envGitBranch&&printAlignedLabel("Branch",envGitBranch);let visibilityLabel=formatVisibilityLabel(visibility,finalType);visibilityLabel&&printAlignedLabel("Type",visibilityLabel)}function printEnvAddWarning(message){output_manager_default.print(`${import_chalk.default.yellow("!")} ${message}
|
|
9
9
|
`)}function promptEnvValue(client,opts){return client.input.text({message:"Value?",...opts.isSensitive?{transformer:value=>"*".repeat(value.length)}:{}})}function buildHumanEnvAddCommand(argv,commandTemplate){let globalFlags=getGlobalFlagsFromArgs(argv.slice(2),{preserveProject:!0}).filter(flag=>!flag.startsWith("--non-interactive")),suffix=globalFlags.length>0?` ${globalFlags.map(quoteArg).join(" ")}`:"";return getCommandNamePlain(`${commandTemplate}${suffix}`)}function isBranchNotFoundError(err){if([err.code,err.slug].filter(v=>typeof v=="string").some(c=>c.toLowerCase()==="branch_not_found"))return!0;let message=(err.serverMessage??"").toLowerCase();return message.includes("branch")&&/not found|(?:doesn't|does not) exist/.test(message)}function branchNotFoundMessage(branch){return`Branch ${branch} was not found in the connected Git repository.`}function branchNotFoundRecovery(branch){return`Push ${branch} to the remote, then run the command again. Or omit --git-branch to apply the variable to all Preview branches.`}function omitGitBranchArgs(argv){let out=[];for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg==="--git-branch"){i+1<argv.length&&!argv[i+1].startsWith("-")&&i++;continue}arg.startsWith("--git-branch=")||out.push(arg)}return out}function buildBranchNotFoundNext(argv,envName,branch){let name=quoteArg(envName);return[{command:buildEnvAddCommandWithPreservedArgs(argv,`env add ${name} --environment preview --git-branch ${quoteArg(branch)} --value "<value>"`),when:`Add the variable after pushing ${branch} to the remote`},{command:buildEnvAddCommandWithPreservedArgs(omitGitBranchArgs(argv),`env add ${name} --environment preview --value "<value>"`),when:"Add the variable to all Preview branches"}]}async function add(client,argv){let parsedArgs,flagsSpecification=getFlagsSpecification(addSubcommand.options);try{parsedArgs=parseArguments(argv,flagsSpecification)}catch(err){return client.nonInteractive&&outputAgentError(client,{status:"error",reason:"invalid_arguments",message:err instanceof Error?err.message:String(err)},2),printError(err),2}let{args,flags:opts}=parsedArgs,valueFromFlag=typeof opts["--value"]=="string"?opts["--value"]:void 0,stdInput=valueFromFlag===void 0?await readStandardInput(client.stdin):"",[envName]=args,positionalEnvironment=args[1],positionalGitBranch=args[2],optionGitBranch=typeof opts["--git-branch"]=="string"?opts["--git-branch"]:void 0,forceSensitive=!!opts["--sensitive"],forceEncrypted=!!opts["--no-sensitive"],typeOption=resolveEnvVarTypeOption({type:typeof opts["--type"]=="string"?opts["--type"]:void 0,visibility:typeof opts["--visibility"]=="string"?opts["--visibility"]:void 0}),explicitType=typeOption.explicitVisibility,typeSource=explicitType||forceSensitive||forceEncrypted?"argv":void 0,telemetryClient=new EnvAddTelemetryClient({opts:{store:client.telemetryEventStore}});if(telemetryClient.trackCliArgumentName(envName),telemetryClient.trackCliArgumentEnvironment(positionalEnvironment),telemetryClient.trackCliArgumentGitBranch(positionalGitBranch),telemetryClient.trackCliOptionEnvironment(opts["--environment"]),telemetryClient.trackCliOptionGitBranch(optionGitBranch),telemetryClient.trackCliOptionValue(valueFromFlag===void 0?void 0:"<redacted>"),telemetryClient.trackCliFlagSensitive(opts["--sensitive"]),telemetryClient.trackCliFlagNoSensitive(opts["--no-sensitive"]),telemetryClient.trackCliFlagForce(opts["--force"]),telemetryClient.trackCliFlagGuidance(opts["--guidance"]),telemetryClient.trackCliFlagYes(opts["--yes"]),telemetryClient.trackCliOptionType(typeof opts["--type"]=="string"?opts["--type"]:void 0),telemetryClient.trackCliOptionVisibility(typeof opts["--visibility"]=="string"?opts["--visibility"]:void 0),telemetryClient.trackCliOptionProject(opts["--project"]),typeOption.error)return client.nonInteractive&&outputAgentError(client,{status:"error",reason:typeOption.errorReason??"invalid_type",message:typeOption.error},1),output_manager_default.fatal(typeOption.error),1;typeOption.usedDeprecatedVisibility&&printEnvAddWarning(ENV_VISIBILITY_DEPRECATION_MESSAGE);let typeConflictMessage=forceSensitive?forceEncrypted?"`--sensitive` and `--no-sensitive` cannot be used together. Pick one.":explicitType==="config"?"`--type config` cannot be used with `--sensitive`. Pick one.":null:forceEncrypted&&explicitType==="secret"?"`--type secret` cannot be used with `--no-sensitive`. Pick one.":null;if(typeConflictMessage)return client.nonInteractive&&outputAgentError(client,{status:"error",reason:"conflicting_type_flags",message:typeConflictMessage},2),output_manager_default.fatal(typeConflictMessage),2;if(positionalEnvironment!==void 0&&!parseEnvTargetArg(positionalEnvironment).every(part=>isValidEnvTarget(part))){let message="The environment argument accepts only production, preview, or development. Use --environment for custom environments, and pass the value with --value or stdin.",command=buildEnvAddCommandWithPreservedArgs(redactEnvValueArgs(client.argv),`env add ${envName?quoteArg(envName):"<name>"} --environment ${getEnvTargetPlaceholder()} --value "<value>"`);return client.nonInteractive&&outputAgentError(client,{status:"error",reason:"invalid_arguments",message,next:[{command,when:"replace the placeholders, then run"}]},2),output_manager_default.error(message),output_manager_default.print(`
|
|
10
10
|
Replace the placeholders, then run:
|