@vercel/cli-support 65.3.1 → 65.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/chunks/add-7NS6HIWC.js +8 -0
- package/dist/chunks/add-NMYFDVXW.js +8 -0
- package/dist/chunks/add-PMJ5BECU.js +8 -0
- package/dist/chunks/build-BCY6HQJG.js +7 -0
- package/dist/chunks/{chunk-SKYDLHEZ.js → chunk-2K3ISCQ6.js} +1 -1
- package/dist/chunks/{chunk-BL3HBRF6.js → chunk-2TUVL6WE.js} +1 -1
- package/dist/chunks/{chunk-22FDWPWY.js → chunk-363SJ4TN.js} +1 -1
- package/dist/chunks/chunk-462YCCJZ.js +7 -0
- package/dist/chunks/{chunk-KNLGWGUE.js → chunk-4N6LMERQ.js} +6 -6
- package/dist/chunks/chunk-527GBU3K.js +7 -0
- package/dist/chunks/chunk-5IWFRZQT.js +10 -0
- package/dist/chunks/chunk-5KUUMQ3M.js +7 -0
- package/dist/chunks/{chunk-IVSC7ZFJ.js → chunk-5V53NA6C.js} +1 -1
- package/dist/chunks/chunk-6I6QJHCY.js +7 -0
- package/dist/chunks/chunk-6TXEVQA4.js +7 -0
- package/dist/chunks/{chunk-2PKEEQ5W.js → chunk-6YXIWZ3X.js} +1 -1
- package/dist/chunks/{chunk-7HV7O6DM.js → chunk-7E3WREH5.js} +1 -1
- package/dist/chunks/{chunk-Y6AGOERS.js → chunk-7L5QUDUR.js} +1 -1
- package/dist/chunks/{chunk-X4762EE4.js → chunk-7QAGSRCU.js} +1 -1
- package/dist/chunks/{chunk-NTZ5WWYV.js → chunk-7R6TRRG5.js} +1 -1
- package/dist/chunks/{chunk-WCWP4GBR.js → chunk-AYUUSAB7.js} +1 -1
- package/dist/chunks/chunk-BVGGTBYE.js +7 -0
- package/dist/chunks/{chunk-YN3C5BL5.js → chunk-C7FQMC6D.js} +1 -1
- package/dist/chunks/{chunk-2U7DJZSQ.js → chunk-CBVKB3DT.js} +1 -1
- package/dist/chunks/{chunk-FDNYYENK.js → chunk-CC6FLKIP.js} +1 -1
- package/dist/chunks/chunk-CR3NBTHV.js +7 -0
- package/dist/chunks/{chunk-BBKEP7RO.js → chunk-CWM2F235.js} +1 -1
- package/dist/chunks/{chunk-IUXSJWL3.js → chunk-DKJL2KV7.js} +1 -1
- package/dist/chunks/{chunk-2ACMWVTB.js → chunk-DQ2SVW4R.js} +1 -1
- package/dist/chunks/{chunk-SLI2O5X7.js → chunk-EAXMWCOL.js} +2 -2
- package/dist/chunks/{chunk-LRYGNQ6C.js → chunk-ECEDD646.js} +1 -1
- package/dist/chunks/{chunk-IGDG5CWT.js → chunk-EEUJLJEJ.js} +1 -1
- package/dist/chunks/{chunk-VQSLPYAF.js → chunk-EGNR2DEI.js} +1 -1
- package/dist/chunks/chunk-EISD3RG7.js +11 -0
- package/dist/chunks/{chunk-GVTXA6HG.js → chunk-EKZTFGDX.js} +1 -1
- package/dist/chunks/{chunk-CEMPU323.js → chunk-EU2GBIPC.js} +1 -1
- package/dist/chunks/{chunk-3ADDGPEN.js → chunk-F6EBOT64.js} +1 -1
- package/dist/chunks/chunk-FHU2O7ZJ.js +8 -0
- package/dist/chunks/{chunk-KH6565YH.js → chunk-FLHO75XC.js} +1 -1
- package/dist/chunks/chunk-FSPPKNKN.js +7 -0
- package/dist/chunks/{chunk-43GBAKL2.js → chunk-GCZVIDNG.js} +1 -1
- package/dist/chunks/{chunk-G4T7VBGN.js → chunk-HSFKISDH.js} +1 -1
- package/dist/chunks/{chunk-OQCMRU3J.js → chunk-HTXDC7E2.js} +2 -2
- package/dist/chunks/{chunk-76SVVWPH.js → chunk-IOZ3I765.js} +1 -1
- package/dist/chunks/{chunk-UKQMYTWW.js → chunk-JLE7K4SY.js} +1 -1
- package/dist/chunks/{chunk-3JGBBS6V.js → chunk-JP33AIDQ.js} +1 -1
- package/dist/chunks/{chunk-ULHNMQ7C.js → chunk-JRPNHWA3.js} +1 -1
- package/dist/chunks/{chunk-D2BZMGHP.js → chunk-JUSR7V2L.js} +1 -1
- package/dist/chunks/{chunk-XB4SKARZ.js → chunk-JWCEHQQF.js} +1 -1
- package/dist/chunks/chunk-K5U47EVH.js +7 -0
- package/dist/chunks/{chunk-VOCZ34ON.js → chunk-KCKYPLIH.js} +1 -1
- package/dist/chunks/{chunk-2WYYGGEO.js → chunk-KGBIRIFF.js} +1 -1
- package/dist/chunks/{chunk-RRREFECI.js → chunk-KJA2GKPT.js} +1 -1
- package/dist/chunks/{chunk-S5IWVPYT.js → chunk-KPQLUGFI.js} +1 -1
- package/dist/chunks/{chunk-S4SJ7GIZ.js → chunk-KQCFC2JL.js} +1 -1
- package/dist/chunks/{chunk-XXXRTHTP.js → chunk-KQCROPL3.js} +1 -1
- package/dist/chunks/{chunk-3KKFLKQG.js → chunk-KY335KWI.js} +1 -1
- package/dist/chunks/{chunk-OWOWPOIE.js → chunk-L3JYCXVB.js} +1 -1
- package/dist/chunks/chunk-LFOWP74R.js +7 -0
- package/dist/chunks/{chunk-PFNYWWLI.js → chunk-LOBA3E72.js} +1 -1
- package/dist/chunks/{chunk-XZV4BFM5.js → chunk-LQVSU5HR.js} +1 -1
- package/dist/chunks/{chunk-2H3SB5RP.js → chunk-LW4N3CW6.js} +1 -1
- package/dist/chunks/{chunk-6ISAISGD.js → chunk-M2NXKZKX.js} +1 -1
- package/dist/chunks/{chunk-F2SWJEYV.js → chunk-MBEKRUTQ.js} +1 -1
- package/dist/chunks/{chunk-UJSW56GS.js → chunk-N2FLYCCO.js} +1 -1
- package/dist/chunks/{chunk-ZH6KHD55.js → chunk-N6JBQMOF.js} +2 -2
- package/dist/chunks/{chunk-OCQPXOTX.js → chunk-NAX6IARA.js} +1 -1
- package/dist/chunks/{chunk-4UGHFESV.js → chunk-NGKO2OOU.js} +1 -1
- package/dist/chunks/chunk-NW7WWUCQ.js +9 -0
- package/dist/chunks/chunk-O4WNSKQR.js +15 -0
- package/dist/chunks/{chunk-7Z3WUAO5.js → chunk-O72YDZKD.js} +1 -1
- package/dist/chunks/{chunk-LKLH6DZP.js → chunk-OHEOYFBU.js} +1 -1
- package/dist/chunks/{chunk-LJBUJ23M.js → chunk-OZCQTXI4.js} +1 -1
- package/dist/chunks/{chunk-LCHECISY.js → chunk-Q4KTAQB3.js} +1 -1
- package/dist/chunks/{chunk-TZFDVQ72.js → chunk-QIVX6SCR.js} +1 -1
- package/dist/chunks/{chunk-7Y46LB43.js → chunk-QVHXFHBV.js} +1 -1
- package/dist/chunks/chunk-QVXS234E.js +7 -0
- package/dist/chunks/{chunk-SXOSF4O6.js → chunk-QVZAAMGQ.js} +1 -1
- package/dist/chunks/chunk-R2BUF6Z7.js +7 -0
- package/dist/chunks/{chunk-OGPENBY2.js → chunk-R2XHJDAP.js} +1 -1
- package/dist/chunks/{chunk-E6CO6TUM.js → chunk-RMZTB2IU.js} +1 -1
- package/dist/chunks/{chunk-LT3UK4K6.js → chunk-SLGUYM42.js} +1 -1
- package/dist/chunks/{chunk-7BGKE3JW.js → chunk-SYFG2RM6.js} +1 -1
- package/dist/chunks/chunk-T6243EDS.js +7 -0
- package/dist/chunks/chunk-TAISZMA2.js +7 -0
- package/dist/chunks/{chunk-TO5PJDEN.js → chunk-TEYREL44.js} +1 -1
- package/dist/chunks/{chunk-6KVHNQW4.js → chunk-TIPQQ4TG.js} +1 -1
- package/dist/chunks/{chunk-DUT4U5YY.js → chunk-U2OBPULW.js} +1 -1
- package/dist/chunks/{chunk-OQPXJCMK.js → chunk-UGNIIDHR.js} +1 -1
- package/dist/chunks/{chunk-NQWGRKF4.js → chunk-UHBMX3OK.js} +1 -1
- package/dist/chunks/{chunk-QMCHGGDX.js → chunk-VNIKIQVE.js} +1 -1
- package/dist/chunks/{chunk-DGYHWXD2.js → chunk-WDXW6A4H.js} +2 -2
- package/dist/chunks/{chunk-L4NSF346.js → chunk-WEH6XC4Y.js} +1 -1
- package/dist/chunks/{chunk-TKBORMUF.js → chunk-WKZ6JSGZ.js} +1 -1
- package/dist/chunks/{chunk-WGXKX24Q.js → chunk-WVHCBDTB.js} +1 -1
- package/dist/chunks/{chunk-COM5YCHF.js → chunk-XC46OAAT.js} +1 -1
- package/dist/chunks/{chunk-WBF36MYT.js → chunk-XVDRGWXM.js} +1 -1
- package/dist/chunks/{chunk-IKQTP764.js → chunk-Y5ZMKL7E.js} +1 -1
- package/dist/chunks/{chunk-NEFDNROD.js → chunk-YEZJNXQX.js} +1 -1
- package/dist/chunks/{chunk-VMMMBWD3.js → chunk-YHULP2KK.js} +1 -1
- package/dist/chunks/{chunk-OMCGXRSA.js → chunk-YMZ6WBKB.js} +2 -2
- package/dist/chunks/{chunk-URPEIX6M.js → chunk-ZN6CQWVP.js} +1 -1
- package/dist/chunks/{chunk-YK7XLFU2.js → chunk-ZQBSAMFL.js} +1 -1
- package/dist/chunks/clear-FKVWDCVA.js +8 -0
- package/dist/chunks/{compile-vercel-config-3IYM2CHC.js → compile-vercel-config-GWAJE44R.js} +1 -1
- package/dist/chunks/config-5WVLG5SE.js +8 -0
- package/dist/chunks/{config-ZFIC7N4D.js → config-RMOHN5YT.js} +1 -1
- package/dist/chunks/config-validator.mjs +1 -1
- package/dist/chunks/{constants-ICJL2EO5.js → constants-JAB7MRSK.js} +1 -1
- package/dist/chunks/delete-5WMB4WFR.js +9 -0
- package/dist/chunks/delete-EM4JZPFA.js +10 -0
- package/dist/chunks/{detect-services-MOXTX5XG.js → detect-services-BSJGB4RM.js} +1 -1
- package/dist/chunks/disable-QOM7UHQC.js +7 -0
- package/dist/chunks/discard-L5ZH7P5B.js +14 -0
- package/dist/chunks/edit-F3VJGCG2.js +9 -0
- package/dist/chunks/edit-TM7YCWBU.js +8 -0
- package/dist/chunks/enable-72C3QX34.js +7 -0
- package/dist/chunks/{export-MHSH7QCX.js → export-EPLYZF2Q.js} +1 -1
- package/dist/chunks/{future-FFOGTKMF.js → future-V77DRMQG.js} +1 -1
- package/dist/chunks/generate-cert-for-deploy-Y3YHBMPU.js +7 -0
- package/dist/chunks/{image-7METSS6F.js → image-CVXEXU5R.js} +1 -1
- package/dist/chunks/{import-builders-GM2SERWV.js → import-builders-PGRKJOOE.js} +1 -1
- package/dist/chunks/inspect-BTRNXRJT.js +9 -0
- package/dist/chunks/{inspect-IAWVHJXQ.js → inspect-CZ7WXYE5.js} +1 -1
- package/dist/chunks/inspect-FGDVWAQP.js +13 -0
- package/dist/chunks/{inspect-A7WJQQZO.js → inspect-HFDGZNWC.js} +1 -1
- package/dist/chunks/{inspect-DI434TAM.js → inspect-T2AIREYK.js} +1 -1
- package/dist/chunks/list-CKRRHAOE.js +12 -0
- package/dist/chunks/{list-WWU734RK.js → list-FLREMGJR.js} +1 -1
- package/dist/chunks/{list-INRPH25K.js → list-ON4YTQRN.js} +1 -1
- package/dist/chunks/login-55LJ5ZA6.js +9 -0
- package/dist/chunks/{login-R5NQRPQC.js → login-DQRZSD4Z.js} +1 -1
- package/dist/chunks/logs-2HQXWOHM.js +7 -0
- package/dist/chunks/{ls-S5E2NQMI.js → ls-2HUJHVLA.js} +1 -1
- package/dist/chunks/{ls-V2ZSIVO3.js → ls-3DVM5HLK.js} +1 -1
- package/dist/chunks/ls-4B3QYHCI.js +8 -0
- package/dist/chunks/{ls-MCQ2NS65.js → ls-A7K4XDQB.js} +1 -1
- package/dist/chunks/{ls-LIGIBVAT.js → ls-FK5XEJEU.js} +1 -1
- package/dist/chunks/{ls-VXH4QYF5.js → ls-QGUKJJY5.js} +1 -1
- package/dist/chunks/ls-VTKHPDWS.js +11 -0
- package/dist/chunks/mutate-7ADZBCZM.js +9 -0
- package/dist/chunks/{notifications-KFZ333V5.js → notifications-XZJXE2K4.js} +1 -1
- package/dist/chunks/open-EE5IZQD7.js +7 -0
- package/dist/chunks/{openapi-JGYEFJJV.js → openapi-QBX62ZXC.js} +1 -1
- package/dist/chunks/{permissions-ZSHKMXBZ.js → permissions-VYJ4LL5R.js} +1 -1
- package/dist/chunks/{plugin-offer-Z6FCPQFD.js → plugin-offer-TEGYA3TA.js} +1 -1
- package/dist/chunks/{prompt-missing-credentials-KOA7C4QC.js → prompt-missing-credentials-VP6OVCFM.js} +1 -1
- package/dist/chunks/publish-2HEK5UMJ.js +15 -0
- package/dist/chunks/pull-WRTTSY7J.js +7 -0
- package/dist/chunks/purchase-domain-if-available-6S3NLTUI.js +7 -0
- package/dist/chunks/push-L3QRGGLC.js +7 -0
- package/dist/chunks/{query-JGPO7TNY.js → query-FXXLX6UB.js} +3 -3
- package/dist/chunks/{reauthenticate-OZRQFR66.js → reauthenticate-IXQDC4UZ.js} +1 -1
- package/dist/chunks/reorder-B4OXSYCI.js +10 -0
- package/dist/chunks/reply-F637K6XH.js +9 -0
- package/dist/chunks/resolve-E3F6NYQZ.js +12 -0
- package/dist/chunks/{resolve-agent-team-KX77HEAF.js → resolve-agent-team-EIPCH766.js} +1 -1
- package/dist/chunks/restore-Q25KRZPH.js +16 -0
- package/dist/chunks/rm-FWD2NUGX.js +8 -0
- package/dist/chunks/rm-JMQ4QKCC.js +8 -0
- package/dist/chunks/rm-PPG7P3GN.js +8 -0
- package/dist/chunks/rm-SH3DYKNS.js +8 -0
- package/dist/chunks/rm-UEBLKFVC.js +8 -0
- package/dist/chunks/{routes-P6LKQCWH.js → routes-PKTWMDWQ.js} +1 -1
- package/dist/chunks/rule-inspect-LKQA5I4V.js +8 -0
- package/dist/chunks/{schema-YOEAK4VX.js → schema-FBV42W7N.js} +1 -1
- package/dist/chunks/{schema-BEUO7G52.js → schema-ZWE5MNMG.js} +1 -1
- package/dist/chunks/{select-org-OMLGQEKK.js → select-org-WMB752Z6.js} +1 -1
- package/dist/chunks/set-UTYIPOLC.js +7 -0
- package/dist/chunks/setup-and-link-ZLY5XQW5.js +7 -0
- package/dist/chunks/{skills-4J2NC2QI.js → skills-RKIGVVNM.js} +2 -2
- package/dist/chunks/{tags-ZXZQEXOV.js → tags-UCLZ5UMX.js} +1 -1
- package/dist/chunks/{types-SK6J2HFE.js → types-YM7TMHXW.js} +1 -1
- package/dist/chunks/{update-25CKNOY5.js → update-BGDQ5TXO.js} +1 -1
- package/dist/commands/build/index.js +1 -1
- package/dist/commands/deploy/index.js +4 -4
- package/dist/commands/dev/index.js +4 -4
- 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 +8 -8
- package/dist/commands-account.js +8 -8
- package/dist/commands-ai.js +12 -12
- package/dist/commands-blob.js +8 -8
- package/dist/commands-core.js +11 -11
- package/dist/commands-deployments.js +1 -1
- package/dist/commands-flags.js +6 -6
- package/dist/commands-integrations.js +16 -16
- package/dist/commands-observability.js +5 -5
- package/dist/commands-routing.js +18 -18
- package/dist/help.js +1 -1
- package/dist/index.js +5 -3
- package/dist/internal-build.js +1 -1
- package/dist/package.json +60 -61
- package/dist/root-help-commands.mjs +1 -1
- package/dist/vc.js +148 -137
- package/dist/version.mjs +1 -1
- package/package.json +54 -54
- package/dist/chunks/add-5YZQTIQM.js +0 -8
- package/dist/chunks/add-A524QQ2H.js +0 -8
- package/dist/chunks/add-V4JMUHKO.js +0 -8
- package/dist/chunks/build-K2PVDJZ4.js +0 -7
- package/dist/chunks/chunk-3AYYFYZG.js +0 -7
- package/dist/chunks/chunk-5IASAERQ.js +0 -7
- package/dist/chunks/chunk-76KGQU2G.js +0 -7
- package/dist/chunks/chunk-ABZEMNDR.js +0 -7
- package/dist/chunks/chunk-APZULWJC.js +0 -8
- package/dist/chunks/chunk-AWMQGOS2.js +0 -7
- package/dist/chunks/chunk-B4UE4LVE.js +0 -7
- package/dist/chunks/chunk-B4YYOSPY.js +0 -7
- package/dist/chunks/chunk-E2SADN6I.js +0 -7
- package/dist/chunks/chunk-IA3MXJRC.js +0 -8
- package/dist/chunks/chunk-IEPW2YRH.js +0 -7
- package/dist/chunks/chunk-LUBUI5GF.js +0 -7
- package/dist/chunks/chunk-OKEBIUKZ.js +0 -7
- package/dist/chunks/chunk-QZX7VG2V.js +0 -9
- package/dist/chunks/chunk-RUXO73ON.js +0 -7
- package/dist/chunks/chunk-TPNOSQZ3.js +0 -15
- package/dist/chunks/chunk-UNEGQPD3.js +0 -7
- package/dist/chunks/chunk-V7BEC3E4.js +0 -10
- package/dist/chunks/chunk-YHQ7PPXP.js +0 -7
- package/dist/chunks/clear-ZS4KQ7OT.js +0 -8
- package/dist/chunks/config-N2SBVW4T.js +0 -8
- package/dist/chunks/delete-2ZE2NVHI.js +0 -10
- package/dist/chunks/delete-AL57HZDQ.js +0 -9
- package/dist/chunks/disable-MKI3BKNH.js +0 -7
- package/dist/chunks/discard-SI4H7ST3.js +0 -14
- package/dist/chunks/edit-DNWH6SPE.js +0 -8
- package/dist/chunks/edit-WYNWDFUJ.js +0 -9
- package/dist/chunks/enable-J6MMYPYF.js +0 -7
- package/dist/chunks/generate-cert-for-deploy-YZKNGAEQ.js +0 -7
- package/dist/chunks/inspect-H2Q7XOWN.js +0 -13
- package/dist/chunks/inspect-H5JC2XKI.js +0 -9
- package/dist/chunks/list-ELEUTZWJ.js +0 -12
- package/dist/chunks/login-ZF2TLCQB.js +0 -9
- package/dist/chunks/logs-UD7FEXZ7.js +0 -7
- package/dist/chunks/ls-5ZEAKKPQ.js +0 -8
- package/dist/chunks/ls-IXRLAJ4L.js +0 -11
- package/dist/chunks/mutate-OQWOKLIW.js +0 -9
- package/dist/chunks/open-HH6K7ZRC.js +0 -7
- package/dist/chunks/publish-FPNQ2US4.js +0 -15
- package/dist/chunks/pull-7OGOIKB3.js +0 -7
- package/dist/chunks/purchase-domain-if-available-F4LKHVBD.js +0 -7
- package/dist/chunks/push-NY3SIK2C.js +0 -7
- package/dist/chunks/reorder-4J2STFUS.js +0 -10
- package/dist/chunks/reply-EO4NTTPW.js +0 -9
- package/dist/chunks/resolve-RPHHRPNM.js +0 -12
- package/dist/chunks/restore-TEA6TSVK.js +0 -16
- package/dist/chunks/rm-BPILSPUI.js +0 -8
- package/dist/chunks/rm-F6XVUDBM.js +0 -8
- package/dist/chunks/rm-JCPXV2FN.js +0 -8
- package/dist/chunks/rm-LPQRGX7N.js +0 -8
- package/dist/chunks/rm-WHUGT6TE.js +0 -8
- package/dist/chunks/rule-inspect-BOETGPFO.js +0 -8
- package/dist/chunks/set-5XY27S7R.js +0 -7
- package/dist/chunks/setup-and-link-A7M3QT52.js +0 -7
package/README.md
CHANGED
|
@@ -34,7 +34,7 @@ For details on how to use Vercel CLI, check out our [documentation](https://verc
|
|
|
34
34
|
|
|
35
35
|
To manage schedules in a running development session, see [local schedules](docs/local-schedules.md).
|
|
36
36
|
|
|
37
|
-
For
|
|
37
|
+
For how `vercel` picks the runtime for each platform, see [launcher](docs/launcher.md).
|
|
38
38
|
|
|
39
39
|
## Local Development
|
|
40
40
|
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{emitVcrArgParseError,handleVcrApiError,resolveVcrScope,validateVcrJsonOutput}from"./chunk-SYFG2RM6.js";import{outputError}from"./chunk-RW3X523R.js";import"./chunk-BUJITHGZ.js";import"./chunk-FBYA6LLM.js";import"./chunk-GD7AV7BO.js";import"./chunk-SCV7XEEO.js";import{addSubcommand}from"./chunk-527GBU3K.js";import"./chunk-CR3NBTHV.js";import"./chunk-BVGGTBYE.js";import"./chunk-6TXEVQA4.js";import{printError}from"./chunk-HSFKISDH.js";import"./chunk-K5U47EVH.js";import"./chunk-MXTC4ZAQ.js";import{AGENT_REASON,buildCommandWithGlobalFlags,outputAgentError}from"./chunk-WDXW6A4H.js";import"./chunk-DKJL2KV7.js";import"./chunk-4N6LMERQ.js";import"./chunk-ADLBLGT3.js";import"./chunk-CWM2F235.js";import"./chunk-4NTBYNFR.js";import{parseArguments}from"./chunk-KCKYPLIH.js";import"./chunk-F53OKXYI.js";import{getFlagsSpecification}from"./chunk-QVXS234E.js";import"./chunk-FUX6LKNP.js";import"./chunk-OPORM35X.js";import"./chunk-4SAVH3H7.js";import{isAPIError}from"./chunk-6VH56CX2.js";import{packageName}from"./chunk-JESNVRVR.js";import{output_manager_default}from"./chunk-XP3FT56R.js";import"./chunk-BLUPZPAS.js";import"./chunk-RM3ZDRYE.js";import"./chunk-OO572JUC.js";import"./chunk-D3AHZ5LI.js";import"./chunk-2GHZGOWT.js";import"./chunk-YHPPP3SF.js";import"./chunk-NB2WLB3J.js";import"./chunk-ISWW3DKF.js";import"./chunk-BRQUZ5NC.js";import"./chunk-BZENIQ7N.js";async function add(client,argv,telemetry){let parsedArgs;try{parsedArgs=parseArguments(argv,getFlagsSpecification(addSubcommand.options))}catch(err){return emitVcrArgParseError(client,err,"vcr create <name> --project <name-or-id>"),printError(err),2}let fr=validateVcrJsonOutput(client,parsedArgs.flags);if(typeof fr=="number")return fr;let name=parsedArgs.args[0],project=parsedArgs.flags["--project"];if(telemetry.trackCliOptionProject(project),telemetry.trackCliOptionFormat(parsedArgs.flags["--format"]),!name)return outputAgentError(client,{status:"error",reason:AGENT_REASON.MISSING_ARGUMENTS,message:`Missing repository name. Example: ${packageName} vcr create <name>`,next:[{command:buildCommandWithGlobalFlags(client.argv,"vcr create <name>"),when:"Replace <name> with the repository name to create"}]},2),outputError(client,fr.jsonOutput,"MISSING_ARGUMENTS","Usage: `vercel vcr create <name>`");let scope=await resolveVcrScope(client,{project,jsonOutput:fr.jsonOutput});if(typeof scope=="number")return scope;let path=`/v1/vcr/repository?teamId=${encodeURIComponent(scope.teamId)}`;output_manager_default.spinner("Creating repository...");try{let created=await client.fetch(path,{method:"POST",body:{projectId:scope.projectId,name}});return fr.jsonOutput?client.stdout.write(`${JSON.stringify(created,null,2)}
|
|
8
|
+
`):output_manager_default.success(`Created repository ${created.repository?.name??name}`),0}catch(err){if(isAPIError(err))return handleVcrApiError(client,err,fr.jsonOutput,{retry:{command:buildCommandWithGlobalFlags(client.argv,"vcr ls"),when:"List existing repositories (a name conflict means it already exists)"}});throw err}finally{output_manager_default.stopSpinner()}}export{add as default};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{parseTeamRefs,teamRefBody}from"./chunk-LSF7FY6X.js";import{repositoryPermissionsPath}from"./chunk-DFVNL5ML.js";import{emitVcrArgParseError,resolveVcrScope,validateVcrJsonOutput}from"./chunk-SYFG2RM6.js";import{outputError}from"./chunk-RW3X523R.js";import{require_async_sema}from"./chunk-NZ2TFADV.js";import"./chunk-BUJITHGZ.js";import"./chunk-FBYA6LLM.js";import"./chunk-GD7AV7BO.js";import"./chunk-SCV7XEEO.js";import{permissionsAddSubcommand}from"./chunk-CR3NBTHV.js";import{printError}from"./chunk-HSFKISDH.js";import"./chunk-K5U47EVH.js";import"./chunk-MXTC4ZAQ.js";import{AGENT_REASON,buildCommandWithGlobalFlags,outputAgentError}from"./chunk-WDXW6A4H.js";import"./chunk-DKJL2KV7.js";import"./chunk-4N6LMERQ.js";import"./chunk-ADLBLGT3.js";import"./chunk-CWM2F235.js";import"./chunk-4NTBYNFR.js";import{parseArguments}from"./chunk-KCKYPLIH.js";import"./chunk-F53OKXYI.js";import{getFlagsSpecification}from"./chunk-QVXS234E.js";import"./chunk-FUX6LKNP.js";import"./chunk-OPORM35X.js";import"./chunk-4SAVH3H7.js";import{isAPIError}from"./chunk-6VH56CX2.js";import{packageName}from"./chunk-JESNVRVR.js";import{output_manager_default}from"./chunk-XP3FT56R.js";import"./chunk-BLUPZPAS.js";import"./chunk-RM3ZDRYE.js";import"./chunk-OO572JUC.js";import"./chunk-D3AHZ5LI.js";import"./chunk-2GHZGOWT.js";import"./chunk-YHPPP3SF.js";import"./chunk-NB2WLB3J.js";import"./chunk-ISWW3DKF.js";import"./chunk-BRQUZ5NC.js";import{__toESM}from"./chunk-BZENIQ7N.js";var import_async_sema=__toESM(require_async_sema(),1);var USAGE="vcr permissions <repository> add <team>[,<team>...]";async function add(client,argv,telemetry){let parsedArgs;try{parsedArgs=parseArguments(argv,getFlagsSpecification(permissionsAddSubcommand.options))}catch(err){return emitVcrArgParseError(client,err,USAGE),printError(err),2}let fr=validateVcrJsonOutput(client,parsedArgs.flags);if(typeof fr=="number")return fr;let repository=parsedArgs.args[0],teamRefs=parseTeamRefs(parsedArgs.args.slice(2)),project=parsedArgs.flags["--project"];if(telemetry.trackCliOptionProject(project),telemetry.trackCliOptionFormat(parsedArgs.flags["--format"]),teamRefs.length===0)return outputAgentError(client,{status:"error",reason:AGENT_REASON.MISSING_ARGUMENTS,message:`Missing team. Example: ${packageName} vcr permissions ${repository} add team_1a2b3c4d`,next:[{command:buildCommandWithGlobalFlags(client.argv,USAGE),when:"Replace <team> with a team id or slug (comma-separate multiple teams)"}]},2),outputError(client,fr.jsonOutput,"MISSING_ARGUMENTS",`Usage: \`vercel ${USAGE}\``);let scope=await resolveVcrScope(client,{project,jsonOutput:fr.jsonOutput});if(typeof scope=="number")return scope;let path=repositoryPermissionsPath(scope,repository),added=[],failed=[];output_manager_default.spinner(`Sharing ${repository} with ${teamRefs.length===1?teamRefs[0]:`${teamRefs.length} teams`}...`);let sema=new import_async_sema.default(10),results;try{results=await Promise.all(teamRefs.map(async team=>{await sema.acquire();try{let result=await client.fetch(path,{method:"POST",body:teamRefBody(team)});return{ok:!0,team,permission:result.permission}}catch(err){if(!isAPIError(err))throw err;let message=err.serverMessage||`API error (${err.status}).`;return{ok:!1,team,failure:{team,code:err.code||"API_ERROR",message}}}finally{sema.release()}}))}finally{output_manager_default.stopSpinner()}for(let result of results)result.ok?(added.push(result.permission),fr.jsonOutput||output_manager_default.success(`Shared ${repository} with ${result.permission?.teamSlug??result.team}`)):(failed.push(result.failure),fr.jsonOutput||output_manager_default.error(`Failed to share ${repository} with ${result.team}: ${result.failure.message}`));return failed.length>0&&outputAgentError(client,{status:"error",reason:AGENT_REASON.API_ERROR,message:`Failed to share ${repository} with ${failed.map(f=>`${f.team} (${f.message})`).join(", ")}`},1),fr.jsonOutput&&client.stdout.write(`${JSON.stringify({permissions:added,failed},null,2)}
|
|
8
|
+
`),failed.length>0?1:0}export{add as default};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{printRuleMutationReceipt}from"./chunk-QVZAAMGQ.js";import"./chunk-3XW7N4W3.js";import{resolveRulesProject,resolveRulesTeam}from"./chunk-RMZTB2IU.js";import"./chunk-KGBIRIFF.js";import{emitRulesArgParseError,getBodyType,handleRulesApiError,outputRulesError,readRuleBody,rulesCollectionPath}from"./chunk-XC46OAAT.js";import"./chunk-GHAY4PSD.js";import"./chunk-RW3X523R.js";import"./chunk-ID663OJ7.js";import"./chunk-HRR57QNP.js";import"./chunk-GZNDA6SV.js";import"./chunk-PFD7LETF.js";import{monitorsAddSubcommand}from"./chunk-NW7WWUCQ.js";import"./chunk-773GOZIR.js";import{printError}from"./chunk-HSFKISDH.js";import"./chunk-67GZ5REA.js";import"./chunk-BS32OUOC.js";import"./chunk-K5U47EVH.js";import"./chunk-MXTC4ZAQ.js";import"./chunk-WDXW6A4H.js";import"./chunk-DKJL2KV7.js";import"./chunk-4N6LMERQ.js";import"./chunk-ADLBLGT3.js";import"./chunk-CWM2F235.js";import"./chunk-4NTBYNFR.js";import{parseArguments}from"./chunk-KCKYPLIH.js";import"./chunk-F53OKXYI.js";import{getFlagsSpecification,validateJsonOutput}from"./chunk-QVXS234E.js";import"./chunk-FUX6LKNP.js";import"./chunk-OPORM35X.js";import"./chunk-4SAVH3H7.js";import{isAPIError}from"./chunk-6VH56CX2.js";import"./chunk-JESNVRVR.js";import{output_manager_default}from"./chunk-XP3FT56R.js";import"./chunk-BLUPZPAS.js";import"./chunk-RM3ZDRYE.js";import"./chunk-OO572JUC.js";import"./chunk-D3AHZ5LI.js";import"./chunk-2GHZGOWT.js";import"./chunk-YHPPP3SF.js";import"./chunk-NB2WLB3J.js";import"./chunk-ISWW3DKF.js";import"./chunk-BRQUZ5NC.js";import"./chunk-BZENIQ7N.js";function applyScopeFlag(client,body,type,scope,flags,jsonOutput){if(Object.hasOwn(body,"ruleScope"))return flags["--project"]||flags["--all"]?outputRulesError(client,jsonOutput,"SCOPE_CONFLICT","Specify monitor scope either in the body or with --project/--all, not both."):void 0;if(flags["--project"]){body.ruleScope=type==="custom"?{type:"project",projectId:scope.projectId}:{type:"include",projectIds:[scope.projectId]};return}if(flags["--all"]){if(type==="custom")return outputRulesError(client,jsonOutput,"INVALID_SCOPE","Custom monitors must target one project. Use --project <name-or-id>.");body.ruleScope={type:"all"};return}return outputRulesError(client,jsonOutput,"MISSING_SCOPE","Missing monitor scope. Add ruleScope to the body, or pass --project or --all.")}async function resolveCreateScope(client,flags,jsonOutput){return flags["--project"]&&flags["--all"]?outputRulesError(client,jsonOutput,"MUTUAL_EXCLUSIVITY","Cannot specify both --all and --project. Use one or the other."):flags["--project"]?resolveRulesProject(client,flags["--project"],jsonOutput,"monitors add"):resolveRulesTeam(client,jsonOutput)}async function add(client,argv,api){let parsedArgs;try{parsedArgs=parseArguments(argv,getFlagsSpecification(monitorsAddSubcommand.options))}catch(error){return emitRulesArgParseError(client,error,"monitors add --project <name-or-id> --body <path>"),printError(error),2}let flags=parsedArgs.flags,format=validateJsonOutput(flags);if(!format.valid)return outputRulesError(client,!1,"INVALID_ARGUMENTS",format.error);if(!flags["--body"])return outputRulesError(client,format.jsonOutput,"MISSING_ARGUMENTS","Missing required flag: --body <PATH>.");let body=readRuleBody(client,flags["--body"],format.jsonOutput);if(typeof body=="number")return body;let type=getBodyType(body);if(!type)return outputRulesError(client,format.jsonOutput,"INVALID_RULE_TYPE","Create body must set a supported monitor type.");if(Object.hasOwn(body,"ruleScope")&&(flags["--project"]||flags["--all"]))return outputRulesError(client,format.jsonOutput,"SCOPE_CONFLICT","Specify monitor scope either in the body or with --project/--all, not both.");if(type==="custom"&&flags["--all"])return outputRulesError(client,format.jsonOutput,"INVALID_SCOPE","Custom monitors must target one project. Use --project <name-or-id>.");let scope=await resolveCreateScope(client,flags,format.jsonOutput);if(typeof scope=="number")return scope;let scopeError=applyScopeFlag(client,body,type,scope,flags,format.jsonOutput);if(scopeError!==void 0)return scopeError;output_manager_default.spinner("Creating monitor\u2026");try{let response=await client.fetch(rulesCollectionPath(api,scope.teamId),{method:"POST",body});return format.jsonOutput?client.stdout.write(`${JSON.stringify(response,null,2)}
|
|
8
|
+
`):printRuleMutationReceipt("Created",response[api.itemKey],client.argv),0}catch(error){if(isAPIError(error))return handleRulesApiError(client,error,format.jsonOutput);throw error}finally{output_manager_default.stopSpinner()}}export{add as default};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{DEFAULT_TAG,buildRepositoryReference,parseNameArg,validateImageParts}from"./chunk-HEGJZJO7.js";import{VCR_ENGINES,emitVcrArgParseError,isBuildxAvailable,isEngineInstalled,pushCompressionArgs,reportEngineCommandFailure,reportEnginePushFailure,resolveRegistry,resolveVcrScope,runEngine,splitPassthrough,validateVcrChoice}from"./chunk-SYFG2RM6.js";import{outputError}from"./chunk-RW3X523R.js";import"./chunk-BUJITHGZ.js";import"./chunk-FBYA6LLM.js";import"./chunk-GD7AV7BO.js";import"./chunk-SCV7XEEO.js";import{buildSubcommand}from"./chunk-527GBU3K.js";import"./chunk-CR3NBTHV.js";import"./chunk-BVGGTBYE.js";import"./chunk-6TXEVQA4.js";import{printError}from"./chunk-HSFKISDH.js";import"./chunk-K5U47EVH.js";import"./chunk-MXTC4ZAQ.js";import{AGENT_REASON,buildCommandWithGlobalFlags,outputAgentError}from"./chunk-WDXW6A4H.js";import"./chunk-DKJL2KV7.js";import"./chunk-4N6LMERQ.js";import"./chunk-ADLBLGT3.js";import"./chunk-CWM2F235.js";import"./chunk-4NTBYNFR.js";import{parseArguments}from"./chunk-KCKYPLIH.js";import"./chunk-F53OKXYI.js";import{getFlagsSpecification}from"./chunk-QVXS234E.js";import"./chunk-FUX6LKNP.js";import"./chunk-OPORM35X.js";import"./chunk-4SAVH3H7.js";import"./chunk-6VH56CX2.js";import"./chunk-JESNVRVR.js";import{output_manager_default}from"./chunk-XP3FT56R.js";import"./chunk-BLUPZPAS.js";import"./chunk-RM3ZDRYE.js";import"./chunk-OO572JUC.js";import"./chunk-D3AHZ5LI.js";import"./chunk-2GHZGOWT.js";import"./chunk-YHPPP3SF.js";import"./chunk-NB2WLB3J.js";import"./chunk-ISWW3DKF.js";import"./chunk-BRQUZ5NC.js";import"./chunk-BZENIQ7N.js";var DEFAULT_PLATFORM="linux/amd64";async function build(client,telemetry){let{own,passthrough}=splitPassthrough(client.argv),parsedArgs;try{parsedArgs=parseArguments(own,getFlagsSpecification(buildSubcommand.options))}catch(err){return emitVcrArgParseError(client,err,"vcr build <engine> [path] [name[:tag]]"),printError(err),2}let[engineArg,pathArg,nameArg]=parsedArgs.args.slice(2),project=parsedArgs.flags["--project"],platform=parsedArgs.flags["--platform"],push=!!parsedArgs.flags["--push"];if(telemetry.trackCliArgumentEngine(engineArg),telemetry.trackCliArgumentPath(pathArg),telemetry.trackCliArgumentName(nameArg),telemetry.trackCliOptionProject(project),telemetry.trackCliOptionPlatform(platform),telemetry.trackCliFlagPush(push),!engineArg){let message=`Missing engine. Choose one of: ${VCR_ENGINES.join(", ")}.`;return outputAgentError(client,{status:"error",reason:AGENT_REASON.MISSING_ARGUMENTS,message,next:[{command:buildCommandWithGlobalFlags(client.argv,"vcr build docker"),when:"Replace docker with the container tool you use"}]},2),outputError(client,!1,"MISSING_ARGUMENTS",message)}let choiceError=validateVcrChoice(client,"engine",engineArg,VCR_ENGINES,!1);if(typeof choiceError=="number")return choiceError;let engine=engineArg;if(!isEngineInstalled(engine)){let message=`\`${engine}\` is not installed or not on your PATH. Install it and try again.`;return outputAgentError(client,{status:"error",reason:"engine_not_found",message},1),outputError(client,!1,"ENGINE_NOT_FOUND",message)}let scope=await resolveVcrScope(client,{project,jsonOutput:!1});if(typeof scope=="number")return scope;let parsed=parseNameArg(nameArg,scope.projectName);if("error"in parsed)return outputAgentError(client,{status:"error",reason:AGENT_REASON.INVALID_ARGUMENTS,message:parsed.error},2),outputError(client,!1,"INVALID_ARGUMENTS",parsed.error);let validationError=validateImageParts(parsed);if(validationError)return outputAgentError(client,{status:"error",reason:AGENT_REASON.INVALID_ARGUMENTS,message:validationError},2),outputError(client,!1,"INVALID_ARGUMENTS",validationError);let ref=`${buildRepositoryReference({registry:resolveRegistry(),teamSlug:scope.teamSlug,projectName:scope.projectName,repository:parsed.repository})}:${parsed.tag??DEFAULT_TAG}`,contextPath=pathArg??".",buildPlatform=platform??DEFAULT_PLATFORM;if(push&&engine==="docker"&&await isBuildxAvailable()){let outputSpec=`type=image,name=${ref},push=true,oci-mediatypes=true,compression=zstd,compression-level=3,force-compression=true`,engineArgs2=["buildx","build","--platform",buildPlatform,"--output",outputSpec,...passthrough,contextPath];output_manager_default.log(`Running: ${engine} ${engineArgs2.join(" ")}`);let result2=await runEngine(engine,engineArgs2,{cwd:client.cwd,captureStderr:!0});return result2.exitCode!==0?reportEnginePushFailure(client,engine,"buildx build",result2):(output_manager_default.success(`Built and pushed ${ref} (zstd compression)`),0)}push&&engine==="docker"&&output_manager_default.warn("Docker Buildx is not available; building and pushing without zstd compression. Install Buildx for smaller, faster image pushes.");let engineArgs=["build","--platform",buildPlatform,"--tag",ref,...passthrough,contextPath];output_manager_default.log(`Running: ${engine} ${engineArgs.join(" ")}`);let result=await runEngine(engine,engineArgs,{cwd:client.cwd});if(result.exitCode!==0)return reportEngineCommandFailure(client,engine,"build",result);if(!push)return output_manager_default.success(`Built ${ref}`),output_manager_default.log(`Push it with \`${buildCommandWithGlobalFlags(client.argv,`vcr push ${engine}${nameArg?` ${nameArg}`:""}`)}\`.`),0;let pushArgs=["push",...pushCompressionArgs(engine),ref];output_manager_default.log(`Running: ${engine} ${pushArgs.join(" ")}`);let pushResult=await runEngine(engine,pushArgs,{cwd:client.cwd,captureStderr:!0});if(pushResult.exitCode!==0)return reportEnginePushFailure(client,engine,"push",pushResult);let compressed=engine!=="docker";return output_manager_default.success(`Built and pushed ${ref}${compressed?" (zstd compression)":""}`),0}export{build as default};
|
|
@@ -4,4 +4,4 @@ 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{getScope}from"./chunk-
|
|
7
|
+
import{getScope}from"./chunk-K5U47EVH.js";import{DeploymentNotFound,DeploymentPermissionDenied,InvalidDeploymentId,isAPIError}from"./chunk-6VH56CX2.js";async function getAliases(client,deploymentId,next,limit=20){let aliasUrl=`/v3/now/aliases?limit=${limit}`;next&&(aliasUrl+=`&until=${next}`);let to=deploymentId?`/now/deployments/${deploymentId}/aliases`:aliasUrl;try{return await client.fetch(to)}catch(err){if(isAPIError(err)){let contextName=await getScope(client).then(scope=>scope.contextName);if(err.status===404)throw new DeploymentNotFound({id:deploymentId,context:contextName});if(err.status===403&&deploymentId)throw new DeploymentPermissionDenied(deploymentId,contextName);if(err.status===400&&err.message.includes("`id`")&&deploymentId)throw new InvalidDeploymentId(deploymentId)}throw err}}export{getAliases};
|
|
@@ -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{getScope}from"./chunk-
|
|
7
|
+
import{getScope}from"./chunk-K5U47EVH.js";import{AGENT_REASON,AGENT_STATUS,buildCommandWithGlobalFlags,outputAgentError,shouldEmitNonInteractiveCommandError}from"./chunk-WDXW6A4H.js";import{getOrgById}from"./chunk-4N6LMERQ.js";import{suggestCorrection}from"./chunk-KCKYPLIH.js";import{output_manager_default}from"./chunk-XP3FT56R.js";async function findSimilarProjectName(client,name,orgId){try{let{projects}=await client.fetch("/v9/projects?limit=100",{accountId:orgId});return suggestCorrection(name,projects.map(project=>project.name).filter(projectName=>/^[a-z0-9._-]+$/i.test(projectName)))}catch(err){output_manager_default.debug(`Project suggestion lookup failed: ${err}`);return}}async function printProjectNotFoundError(client,projectNameOrId,commandName,orgId,{createCommand}={}){let contextName;try{orgId?contextName=(await getOrgById(client,orgId))?.slug??orgId:contextName=(await getScope(client)).contextName}catch(err){contextName=orgId,output_manager_default.debug(`Scope lookup failed during error reporting: ${err}`)}let scopeClause=contextName?` (${contextName})`:"",headline=`Project "${projectNameOrId}" was not found in the current scope${scopeClause}.`,suggestion=createCommand?await findSimilarProjectName(client,projectNameOrId,orgId):void 0,suggestionLine=suggestion?` Did you mean ${suggestion}?`:"",createNote=createCommand?.note;if(output_manager_default.error(`${headline}${suggestionLine}
|
|
8
8
|
|
|
9
9
|
`+(createCommand?`To create it${createNote?`, ${createNote}`:""}:
|
|
10
10
|
${createCommand.command}
|
|
@@ -4,4 +4,4 @@ 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{getGlobalPathConfig}from"./chunk-
|
|
7
|
+
import{getGlobalPathConfig}from"./chunk-CWM2F235.js";import{output_manager_default}from"./chunk-XP3FT56R.js";var OPENAPI_URL="https://openapi.vercel.sh/",SSO_API_URL="https://vercel.com/sso-api",CACHE_FILE="openapi-spec.json",CACHE_TTL_MS=864e5,FETCH_TIMEOUT_MS=1e4,MAX_OPENAPI_SPEC_BYTES=52428800,VERCEL_CLI_ROOT_DISPLAY_KEY="__root__";async function readSpecResponse(response,url,maxBytes=52428800){let contentLength=response.headers.get("content-length");if(contentLength){let bytes=Number(contentLength);if(Number.isFinite(bytes)&&bytes>maxBytes)throw new Error(`OpenAPI spec from ${url} exceeds the ${maxBytes} byte limit.`)}if(!response.body)throw new Error(`OpenAPI spec from ${url} returned an empty response.`);let reader=response.body.getReader(),chunks=[],totalBytes=0;for(;;){let{done,value}=await reader.read();if(done)break;if(value){if(totalBytes+=value.byteLength,totalBytes>maxBytes)throw await reader.cancel(),new Error(`OpenAPI spec from ${url} exceeds the ${maxBytes} byte limit.`);chunks.push(value)}}let buffer=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)buffer.set(chunk,offset),offset+=chunk.byteLength;return JSON.parse(new TextDecoder().decode(buffer))}var ALLOWED_SPEC_HOSTS=["vercel.sh","vercel.tools"];function assertAllowedSpecUrl(specUrl){let parsedUrl=new URL(specUrl);if(parsedUrl.protocol!=="https:")throw new Error("OpenAPI spec URL must use https");if(!ALLOWED_SPEC_HOSTS.some(host=>isHostOrSubdomain(parsedUrl,host)))throw new Error("OpenAPI spec URL must be on an allowed origin.");return parsedUrl}function isHostOrSubdomain(url,host){return url.hostname===host||url.hostname.endsWith(`.${host}`)}import{join}from"path";import{readFile,writeFile,mkdir}from"fs/promises";var OpenApiCache=class{constructor(options){this.spec=null;this.error=null;this.cachePath=join(getGlobalPathConfig(),CACHE_FILE),this.specUrl=options?.specUrl,this.fetchSpecUrl=options?.fetchSpecUrl}get isLoaded(){return this.spec!==null}get loadError(){return this.error}async load(forceRefresh=!1){return this.loadSpec(forceRefresh)}async loadSpec(forceRefresh=!1){if(this.error=null,this.specUrl)return this.loadCustomSpec(this.specUrl);if(!forceRefresh){let cached=await this.readCache(this.cachePath);if(cached&&!this.isExpired(cached.fetchedAt))return output_manager_default.debug("Using cached OpenAPI spec"),this.spec=cached.spec,!0}try{return output_manager_default.debug("Fetching OpenAPI spec from "+OPENAPI_URL),this.spec=await this.fetchSpec(OPENAPI_URL),await this.saveCache(this.cachePath,this.spec),!0}catch(err){output_manager_default.debug(`Failed to fetch OpenAPI spec: ${err}`);let stale=await this.readCache(this.cachePath);return stale?(output_manager_default.debug("Using stale cached OpenAPI spec"),this.spec=stale.spec,!0):!1}}async loadCustomSpec(specUrl){try{assertAllowedSpecUrl(specUrl),output_manager_default.debug("Fetching OpenAPI spec from "+specUrl);let spec=this.fetchSpecUrl?await this.fetchSpecUrl(specUrl):await this.fetchSpec(specUrl);return spec?(this.validateSpec(spec,specUrl),this.spec=spec,!!this.spec):(this.error=`Could not load OpenAPI spec from ${specUrl}.`,!1)}catch(err){let message=err instanceof Error?err.message:String(err);return this.error=message,output_manager_default.debug(`Failed to fetch OpenAPI spec from ${specUrl}: ${message}`),!1}}async loadWithSpinner(forceRefresh=!1){output_manager_default.spinner(forceRefresh?"Refreshing API endpoints...":"Loading API endpoints...");let success=await this.load(forceRefresh);return output_manager_default.stopSpinner(),success}getEndpoints(){this.ensureLoaded();let endpoints=this.extractEndpoints();return this.sortEndpoints(endpoints)}getBodyFields(endpoint){if(this.ensureLoaded(),!endpoint.requestBody?.content)return[];let jsonContent=endpoint.requestBody.content["application/json"];if(!jsonContent?.schema)return[];let schema=this.resolveSchemaRef(jsonContent.schema);if(!schema?.properties)return[];let requiredFields=new Set(schema.required||[]),fields=[];for(let[name,propSchema]of Object.entries(schema.properties)){let resolvedProp=this.resolveSchemaRef(propSchema),enumValues=resolvedProp?.enum||propSchema.enum;if(!enumValues&&(resolvedProp?.type==="array"||propSchema.type==="array")){let items=resolvedProp?.items||propSchema.items;items&&(enumValues=this.resolveSchemaRef(items)?.enum||items.enum)}fields.push({name,required:requiredFields.has(name),description:resolvedProp?.description||propSchema.description,type:resolvedProp?.type||propSchema.type,enumValues})}return fields.sort((a,b)=>a.required!==b.required?a.required?-1:1:a.name.localeCompare(b.name)),fields}getDisplayColumns(endpoint){this.ensureLoaded();let pathItem=this.spec.paths[endpoint.path];if(!pathItem)return null;let operation=pathItem[endpoint.method.toLowerCase()];if(!operation?.responses)return null;let ok=operation.responses[200]||operation.responses[201];if(!ok)return null;let jsonContent=ok.content?.["application/json"];return jsonContent?.schema?this.findDisplayColumns(jsonContent.schema):null}findDisplayColumns(schema){let xCli=schema["x-vercel-cli"];if(xCli?.displayColumns)return xCli.displayColumns;for(let key of["oneOf","allOf","anyOf"]){let variants=schema[key];if(variants)for(let sub of variants){let found=this.findDisplayColumns(sub);if(found)return found}}return null}ensureLoaded(){if(!this.spec)throw new Error("OpenAPI spec not loaded. Call load() or loadWithSpinner() first.")}async readCache(cachePath){try{let content=await readFile(cachePath,"utf-8");return JSON.parse(content)}catch{return null}}async saveCache(cachePath,spec){let cached={fetchedAt:Date.now(),spec},dir=join(cachePath,"..");await mkdir(dir,{recursive:!0}),await writeFile(cachePath,JSON.stringify(cached)),output_manager_default.debug("Saved OpenAPI spec to cache")}async fetchSpec(url){let controller=new AbortController,timeoutId=setTimeout(()=>controller.abort(),1e4);try{let response=await fetch(url,{signal:controller.signal});if(!response.ok)throw new Error(`Failed to fetch OpenAPI spec: ${response.status}`);let spec=await readSpecResponse(response,url);return this.validateSpec(spec,url),spec}finally{clearTimeout(timeoutId)}}validateSpec(spec,url){if(!spec||typeof spec!="object")throw new Error(`Invalid OpenAPI spec from ${url}: expected a JSON object.`);if(typeof spec.openapi!="string"||!spec.openapi.startsWith("3."))throw new Error(`Invalid OpenAPI spec from ${url}: expected an OpenAPI 3.x document with an "openapi" field.`);if(!spec.paths||typeof spec.paths!="object")throw new Error(`Invalid OpenAPI spec from ${url}: expected a "paths" object.`);for(let path of Object.keys(spec.paths))if(!path.startsWith("/")||path.startsWith("//"))throw new Error(`Invalid OpenAPI spec from ${url}: path "${path}" must be a relative API path.`)}isExpired(fetchedAt){return Date.now()-fetchedAt>864e5}sortEndpoints(endpoints){return endpoints.sort((a,b)=>{let pathCompare=a.path.localeCompare(b.path);return pathCompare!==0?pathCompare:a.method.localeCompare(b.method)})}extractEndpoints(){let endpoints=[];for(let[path,pathItem]of Object.entries(this.spec.paths)){let methods=["get","post","put","patch","delete"];for(let method of methods){let operation=pathItem[method];if(operation){let pathParams=pathItem.parameters||[],opParams=operation.parameters||[],allParams=[...pathParams,...opParams];endpoints.push({path,method:method.toUpperCase(),summary:operation.summary||pathItem.summary||"",description:operation.description||pathItem.description||"",operationId:operation.operationId||"",tags:operation.tags||[],parameters:allParams,requestBody:operation.requestBody})}}}return endpoints}resolveSchemaRef(schema,spec=this.spec){if(schema){if(schema.$ref){let match=schema.$ref.match(/^#\/components\/schemas\/(.+)$/);if(match&&spec.components?.schemas){let resolved=spec.components.schemas[match[1]];return this.resolveSchemaRef(resolved,spec)}return}if(schema.allOf&&schema.allOf.length>0){let merged={type:"object",properties:{},required:[]};for(let subSchema of schema.allOf){let resolved=this.resolveSchemaRef(subSchema,spec);resolved&&(resolved.properties&&(merged.properties={...merged.properties,...resolved.properties}),resolved.required&&(merged.required=[...merged.required||[],...resolved.required]))}return merged}return schema}}};async function matchesCliApiTag(tagHint){if(!tagHint||tagHint.startsWith("-")||tagHint.includes("/"))return!1;let cache=new OpenApiCache;if(!await cache.load())return!1;let endpoints=cache.getEndpoints(),lower=tagHint.toLowerCase();return endpoints.some(ep=>ep.tags.some(t=>t.toLowerCase()===lower))}async function resolveOpenApiTagForProjectsCli(){return await matchesCliApiTag("projects")?"projects":await matchesCliApiTag("project")?"project":null}async function resolveOpenApiTagForTeamsCli(){return await matchesCliApiTag("teams")?"teams":await matchesCliApiTag("team")?"team":null}export{OPENAPI_URL,SSO_API_URL,CACHE_FILE,CACHE_TTL_MS,FETCH_TIMEOUT_MS,MAX_OPENAPI_SPEC_BYTES,VERCEL_CLI_ROOT_DISPLAY_KEY,readSpecResponse,assertAllowedSpecUrl,OpenApiCache,matchesCliApiTag,resolveOpenApiTagForProjectsCli,resolveOpenApiTagForTeamsCli};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{jsonOption,limitOption,projectOption,yesOption}from"./chunk-QVXS234E.js";import{packageName}from"./chunk-JESNVRVR.js";var listSubcommand={name:"list",aliases:["ls"],description:"List all routing rules for the current project. These routes apply to all deployments and environments.",arguments:[],options:[projectOption,jsonOption,{name:"query",description:"Search by name, description, source, or destination",shorthand:"q",type:String,argument:"TEXT",deprecated:!1},{name:"search",description:"Deprecated alias for `--query`",shorthand:"s",type:String,argument:"QUERY",deprecated:!0},{name:"type",description:"Filter by type: rewrite, redirect, set_status, transform",shorthand:null,type:String,argument:"TYPE",deprecated:!1},{name:"filter",description:"Deprecated alias for `--type`",shorthand:"f",type:String,argument:"TYPE",deprecated:!0},{name:"production",description:"List routes from the live production version",shorthand:null,type:Boolean,deprecated:!1},{name:"routes-version",description:"List routes from a specific version",shorthand:null,type:String,argument:"VERSION",deprecated:!1},{name:"version-id",description:"Deprecated alias for `--routes-version`",shorthand:null,type:String,argument:"VERSION_ID",deprecated:!0},{name:"diff",description:"Compare staged changes against production. Use with --routes-version to compare a specific version.",shorthand:null,type:Boolean,deprecated:!1},{name:"expand",description:"Show expanded details for each route",shorthand:null,deprecatedShorthand:"e",type:Boolean,deprecated:!1}],examples:[{name:"List all routes",value:`${packageName} routes list`},{name:"Search for routes",value:`${packageName} routes list --query "api"`},{name:"Filter by type",value:`${packageName} routes list --type rewrite`},{name:"Show staged changes",value:`${packageName} routes list --diff`},{name:"Show live production routes",value:`${packageName} routes list --production`},{name:"Show expanded details",value:`${packageName} routes list --expand`}]},listVersionsSubcommand={name:"list-versions",aliases:["ls-versions"],description:"List all versions of routing rules",arguments:[],options:[projectOption,jsonOption,{...limitOption,description:"Number of versions to fetch (default: 20, max: 100)"},{name:"count",description:"Deprecated alias for `--limit`",shorthand:null,type:Number,argument:"NUMBER",deprecated:!0}],examples:[{name:"List route versions",value:`${packageName} routes list-versions`},{name:"List more versions",value:`${packageName} routes list-versions --limit 50`}]},inspectSubcommand={name:"inspect",aliases:[],description:"Show detailed information about a specific route",arguments:[{name:"name-or-id",required:!0}],options:[projectOption,jsonOption,{name:"diff",description:"Compare staged changes against production for this route",shorthand:null,type:Boolean,deprecated:!1}],examples:[{name:"Inspect a route by name",value:`${packageName} routes inspect "API rewrite"`},{name:"Inspect a route by ID",value:`${packageName} routes inspect abc123`},{name:"Show staged changes for a route",value:`${packageName} routes inspect "My route" --diff`}]},addSubcommand={name:"add",aliases:[],description:"Add a new routing rule to the project",arguments:[{name:"name",required:!1}],options:[projectOption,{name:"src",description:"Path pattern (required in non-interactive mode)",shorthand:null,type:String,argument:"PATTERN",deprecated:!1},{name:"src-syntax",description:"Path syntax: regex, path-to-regexp, equals (default: regex)",shorthand:null,type:String,argument:"TYPE",deprecated:!1},{name:"action",description:"Action type: rewrite, redirect, or set-status (required with --dest/--status)",shorthand:null,type:String,argument:"TYPE",deprecated:!1},{name:"dest",description:"Destination URL for rewrite or redirect",shorthand:null,type:String,argument:"URL",deprecated:!1},{name:"status",description:"Status code (301/302/307/308 for redirect, or any for set-status)",shorthand:null,type:Number,argument:"CODE",deprecated:!1},{name:"set-response-header",description:"Set response header: key=value (repeatable)",shorthand:null,type:[String],argument:"HEADER",deprecated:!1},{name:"append-response-header",description:"Append to response header: key=value (repeatable)",shorthand:null,type:[String],argument:"HEADER",deprecated:!1},{name:"delete-response-header",description:"Delete response header: key (repeatable)",shorthand:null,type:[String],argument:"KEY",deprecated:!1},{name:"set-request-header",description:"Set request header: key=value (repeatable)",shorthand:null,type:[String],argument:"HEADER",deprecated:!1},{name:"append-request-header",description:"Append to request header: key=value (repeatable)",shorthand:null,type:[String],argument:"HEADER",deprecated:!1},{name:"delete-request-header",description:"Delete request header: key (repeatable)",shorthand:null,type:[String],argument:"KEY",deprecated:!1},{name:"set-request-query",description:"Set query parameter: key=value (repeatable)",shorthand:null,type:[String],argument:"PARAM",deprecated:!1},{name:"append-request-query",description:"Append to query parameter: key=value (repeatable)",shorthand:null,type:[String],argument:"PARAM",deprecated:!1},{name:"delete-request-query",description:"Delete query parameter: key (repeatable)",shorthand:null,type:[String],argument:"KEY",deprecated:!1},{name:"has",description:"Condition that must match: type:key or type:key:value (repeatable)",shorthand:null,type:[String],argument:"CONDITION",deprecated:!1},{name:"missing",description:'"Does not have" condition: type:key or type:key:value (repeatable)',shorthand:null,type:[String],argument:"CONDITION",deprecated:!1},{name:"description",description:"Route description (max 1024 chars)",shorthand:null,type:String,argument:"TEXT",deprecated:!1},{name:"no-enable",description:"Add the route turned off (default: on)",shorthand:null,type:Boolean,deprecated:!1},{name:"disabled",description:"Deprecated alias for `--no-enable`",shorthand:null,type:Boolean,deprecated:!0},{name:"ai",description:"Generate route from a natural language description (AI-powered)",shorthand:null,type:String,argument:"PROMPT",deprecated:!1},{name:"position",description:"Position: start, end, after:<id>, before:<id>",shorthand:null,type:String,argument:"POSITION",deprecated:!1},{name:"yes",description:"Skip confirmation prompts",shorthand:"y",type:Boolean,deprecated:!1}],examples:[{name:"Interactive mode",value:`${packageName} routes add`},{name:"Create with AI",value:`${packageName} routes add --ai "Rewrite /api/* to https://backend.internal/*"`},{name:"Add a rewrite",value:`${packageName} routes add "API Proxy" --src "/api/:path*" --src-syntax path-to-regexp --action rewrite --dest "https://api.example.com/:path*" --yes`},{name:"Add a redirect",value:`${packageName} routes add "Old Blog" --src "/blog" --src-syntax equals --action redirect --dest "/articles" --status 301 --yes`},{name:"Add CORS headers",value:`${packageName} routes add "CORS" --src "^/api/.*$" --set-response-header "Access-Control-Allow-Origin=*" --yes`},{name:"Block access (set status)",value:`${packageName} routes add "Block Admin" --src "^/admin/.*$" --action set-status --status 403 --yes`},{name:"Conditional redirect",value:`${packageName} routes add "Auth Required" --src "/protected/:path*" --src-syntax path-to-regexp --action redirect --dest "/login" --status 307 --missing "cookie:session" --yes`},{name:"Rewrite with request headers",value:`${packageName} routes add "Backend Proxy" --src "/backend/:path*" --src-syntax path-to-regexp --action rewrite --dest "https://internal.example.com/:path*" --set-request-header "X-Forwarded-Host=myapp.com" --yes`},{name:"Add route at start",value:`${packageName} routes add "Priority Route" --src "/priority" --src-syntax equals --action rewrite --dest "/handler" --position start --yes`}]},publishSubcommand={name:"publish",aliases:[],description:"Publish all staged routing changes to production",arguments:[],options:[projectOption,{...yesOption,description:"Skip the confirmation prompt when publishing"}],examples:[{name:"Publish staged changes",value:`${packageName} routes publish`},{name:"Publish without confirmation",value:`${packageName} routes publish --yes`}]},restoreSubcommand={name:"restore",aliases:[],description:"Restore a previous routing version to production",arguments:[{name:"version-id",required:!0}],options:[projectOption,{...yesOption,description:"Skip the confirmation prompt when restoring"}],examples:[{name:"Restore a previous version",value:`${packageName} routes restore <version-id>`},{name:"Restore without confirmation",value:`${packageName} routes restore <version-id> --yes`}]},discardSubcommand={name:"discard-staging",aliases:[],description:"Discard staged routing changes",arguments:[],options:[projectOption,{...yesOption,description:"Skip the confirmation prompt when discarding"}],examples:[{name:"Discard staged changes",value:`${packageName} routes discard-staging`},{name:"Discard without confirmation",value:`${packageName} routes discard-staging --yes`}]},deleteSubcommand={name:"remove",aliases:["rm","delete"],description:"Remove one or more routing rules",arguments:[{name:"name-or-id",required:!0,multiple:!0}],options:[projectOption,{...yesOption,description:"Skip the confirmation prompt when removing"}],examples:[{name:"Remove a route by name",value:`${packageName} routes remove "Old Redirect"`},{name:"Remove a route by ID",value:`${packageName} routes remove abc123`},{name:"Remove multiple routes",value:`${packageName} routes remove "Route A" "Route B"`},{name:"Remove without confirmation",value:`${packageName} routes remove "Old Route" --yes`}]},enableSubcommand={name:"enable",aliases:[],description:"Enable a disabled routing rule",arguments:[{name:"name-or-id",required:!0}],options:[projectOption],examples:[{name:"Enable a route by name",value:`${packageName} routes enable "API Proxy"`},{name:"Enable a route by ID",value:`${packageName} routes enable abc123`}]},disableSubcommand={name:"disable",aliases:[],description:"Disable a routing rule without deleting it",arguments:[{name:"name-or-id",required:!0}],options:[projectOption],examples:[{name:"Disable a route by name",value:`${packageName} routes disable "API Proxy"`},{name:"Disable a route by ID",value:`${packageName} routes disable abc123`}]},reorderSubcommand={name:"move",aliases:["reorder"],description:"Move a routing rule to a different position",arguments:[{name:"name-or-id",required:!0}],options:[projectOption,{name:"position",description:"Target position: start, end, a number (1-based), before:<id>, after:<id>",shorthand:null,type:String,argument:"POSITION",deprecated:!1},{name:"first",description:"Move to the first position (highest priority)",shorthand:null,type:Boolean,deprecated:!1},{name:"last",description:"Move to the last position (lowest priority)",shorthand:null,type:Boolean,deprecated:!1},{...yesOption,description:"Skip the confirmation prompt when moving"}],examples:[{name:"Move to first position",value:`${packageName} routes move "Catch All" --first`},{name:"Move to last position",value:`${packageName} routes move "Catch All" --last`},{name:"Move to a specific position",value:`${packageName} routes move "API Proxy" --position 3`},{name:"Move after another route",value:`${packageName} routes move "API Proxy" --position after:route-id-123`},{name:"Interactive move (prompts for position)",value:`${packageName} routes move "API Proxy"`}]},editSubcommand={name:"update",aliases:["edit"],description:"Update an existing routing rule",arguments:[{name:"name-or-id",required:!0}],options:[projectOption,{name:"name",description:"Change route name",shorthand:null,type:String,argument:"NAME",deprecated:!1},{name:"description",description:'Change description (use "" to clear)',shorthand:null,type:String,argument:"TEXT",deprecated:!1},{name:"src",description:"Change source path pattern",shorthand:null,type:String,argument:"PATTERN",deprecated:!1},{name:"src-syntax",description:"Change path syntax: regex, path-to-regexp, equals",shorthand:null,type:String,argument:"TYPE",deprecated:!1},{name:"action",description:"Set action type: rewrite, redirect, or set-status (required when switching types)",shorthand:null,type:String,argument:"TYPE",deprecated:!1},{name:"dest",description:"Set destination URL",shorthand:null,type:String,argument:"URL",deprecated:!1},{name:"status",description:"Set status code",shorthand:null,type:Number,argument:"CODE",deprecated:!1},{name:"no-dest",description:"Remove destination",shorthand:null,type:Boolean,deprecated:!1},{name:"no-status",description:"Remove status code",shorthand:null,type:Boolean,deprecated:!1},{name:"set-response-header",description:"Set response header: key=value (repeatable)",shorthand:null,type:[String],argument:"HEADER",deprecated:!1},{name:"append-response-header",description:"Append to response header: key=value (repeatable)",shorthand:null,type:[String],argument:"HEADER",deprecated:!1},{name:"delete-response-header",description:"Delete response header: key (repeatable)",shorthand:null,type:[String],argument:"KEY",deprecated:!1},{name:"set-request-header",description:"Set request header: key=value (repeatable)",shorthand:null,type:[String],argument:"HEADER",deprecated:!1},{name:"append-request-header",description:"Append to request header: key=value (repeatable)",shorthand:null,type:[String],argument:"HEADER",deprecated:!1},{name:"delete-request-header",description:"Delete request header: key (repeatable)",shorthand:null,type:[String],argument:"KEY",deprecated:!1},{name:"set-request-query",description:"Set query parameter: key=value (repeatable)",shorthand:null,type:[String],argument:"PARAM",deprecated:!1},{name:"append-request-query",description:"Append to query parameter: key=value (repeatable)",shorthand:null,type:[String],argument:"PARAM",deprecated:!1},{name:"delete-request-query",description:"Delete query parameter: key (repeatable)",shorthand:null,type:[String],argument:"KEY",deprecated:!1},{name:"has",description:"Add a has condition: type:key or type:key:value (repeatable)",shorthand:null,type:[String],argument:"CONDITION",deprecated:!1},{name:"missing",description:'Add a "does not have" condition: type:key or type:key:value (repeatable)',shorthand:null,type:[String],argument:"CONDITION",deprecated:!1},{name:"clear-conditions",description:"Remove all has/does-not-have conditions",shorthand:null,type:Boolean,deprecated:!1},{name:"clear-headers",description:"Remove all response headers",shorthand:null,type:Boolean,deprecated:!1},{name:"clear-transforms",description:"Remove all transforms (request headers, request query)",shorthand:null,type:Boolean,deprecated:!1},{name:"ai",description:"Describe changes using natural language (AI-powered)",shorthand:null,type:String,argument:"PROMPT",deprecated:!1},{...yesOption,description:"Skip confirmation prompts"}],examples:[{name:"Interactive mode",value:`${packageName} routes update "API Proxy"`},{name:"Update with AI",value:`${packageName} routes update "API Proxy" --ai "Add CORS headers and change status to 308"`},{name:"Change destination",value:`${packageName} routes update "API Proxy" --dest "https://new-api.example.com/:path*"`},{name:"Switch to redirect",value:`${packageName} routes update "Old Route" --action redirect --dest "/new" --status 301`},{name:"Add a response header",value:`${packageName} routes update "My Route" --set-response-header "Cache-Control=public, max-age=3600"`},{name:"Clear all conditions and add new ones",value:`${packageName} routes update "My Route" --clear-conditions --has "header:Authorization"`}]},exportSubcommand={name:"export",aliases:[],description:"Export routes to a vercel.json or vercel.ts file",arguments:[{name:"name-or-id",required:!1}],options:[projectOption,{name:"output",description:"Output file format: .json or .ts (default: .json)",shorthand:"o",type:String,argument:"json|ts",deprecated:!1}],examples:[{name:"Export as vercel.json format",value:`${packageName} routes export`},{name:"Export as vercel.ts format",value:`${packageName} routes export --output ts`},{name:"Export a specific route",value:`${packageName} routes export "API Proxy"`},{name:"Export to a file",value:`${packageName} routes export > routes.json`}]},routesCommand={name:"routes",aliases:[],description:"Manage routing rules for a project. Routes managed at the project level apply to all deployments and environments.",arguments:[],subcommands:[listSubcommand,listVersionsSubcommand,inspectSubcommand,addSubcommand,editSubcommand,deleteSubcommand,enableSubcommand,disableSubcommand,reorderSubcommand,exportSubcommand,publishSubcommand,restoreSubcommand,discardSubcommand],options:[],examples:[]};export{listSubcommand,listVersionsSubcommand,inspectSubcommand,addSubcommand,publishSubcommand,restoreSubcommand,discardSubcommand,deleteSubcommand,enableSubcommand,disableSubcommand,reorderSubcommand,editSubcommand,exportSubcommand,routesCommand};
|
|
@@ -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{printAlignedLabel}from"./chunk-ADLBLGT3.js";import{getGlobalPathConfig}from"./chunk-
|
|
7
|
+
import{printAlignedLabel}from"./chunk-ADLBLGT3.js";import{getGlobalPathConfig}from"./chunk-CWM2F235.js";import{require_graceful_fs,require_load_json_file}from"./chunk-4NTBYNFR.js";import{parseArguments}from"./chunk-KCKYPLIH.js";import{getTeamByIdOrSlug}from"./chunk-F53OKXYI.js";import{fetch,require_lib}from"./chunk-FUX6LKNP.js";import{require_cli_config}from"./chunk-4SAVH3H7.js";import{APIError,ConflictingConfigFiles,DeprecatedNowJson,InvalidLocalConfig,InvalidToken,MissingUser,NowError,ProjectNotFound,code,isAPIError}from"./chunk-6VH56CX2.js";import{emoji,link_default,output_manager_default,prependEmoji,require_build_utils}from"./chunk-XP3FT56R.js";import{require_dist}from"./chunk-RM3ZDRYE.js";import{pkg_default}from"./chunk-OO572JUC.js";import{require_source}from"./chunk-NB2WLB3J.js";import{__commonJS,__require,__toESM}from"./chunk-BZENIQ7N.js";var require_universalify=__commonJS({"../../node_modules/.pnpm/universalify@2.0.1/node_modules/universalify/index.js"(exports){"use strict";exports.fromCallback=function(fn){return Object.defineProperty(function(...args){if(typeof args[args.length-1]=="function")fn.apply(this,args);else return new Promise((resolve6,reject)=>{args.push((err,res)=>err!=null?reject(err):resolve6(res)),fn.apply(this,args)})},"name",{value:fn.name})};exports.fromPromise=function(fn){return Object.defineProperty(function(...args){let cb=args[args.length-1];if(typeof cb!="function")return fn.apply(this,args);args.pop(),fn.apply(this,args).then(r=>cb(null,r),cb)},"name",{value:fn.name})}}});var require_fs=__commonJS({"../../node_modules/.pnpm/fs-extra@10.0.0/node_modules/fs-extra/lib/fs/index.js"(exports){"use strict";var u=require_universalify().fromCallback,fs4=require_graceful_fs(),api=["access","appendFile","chmod","chown","close","copyFile","fchmod","fchown","fdatasync","fstat","fsync","ftruncate","futimes","lchmod","lchown","link","lstat","mkdir","mkdtemp","open","opendir","readdir","readFile","readlink","realpath","rename","rm","rmdir","stat","symlink","truncate","unlink","utimes","writeFile"].filter(key=>typeof fs4[key]=="function");Object.assign(exports,fs4);api.forEach(method=>{exports[method]=u(fs4[method])});exports.realpath.native=u(fs4.realpath.native);exports.exists=function(filename,callback){return typeof callback=="function"?fs4.exists(filename,callback):new Promise(resolve6=>fs4.exists(filename,resolve6))};exports.read=function(fd,buffer,offset,length,position,callback){return typeof callback=="function"?fs4.read(fd,buffer,offset,length,position,callback):new Promise((resolve6,reject)=>{fs4.read(fd,buffer,offset,length,position,(err,bytesRead,buffer2)=>{if(err)return reject(err);resolve6({bytesRead,buffer:buffer2})})})};exports.write=function(fd,buffer,...args){return typeof args[args.length-1]=="function"?fs4.write(fd,buffer,...args):new Promise((resolve6,reject)=>{fs4.write(fd,buffer,...args,(err,bytesWritten,buffer2)=>{if(err)return reject(err);resolve6({bytesWritten,buffer:buffer2})})})};typeof fs4.writev=="function"&&(exports.writev=function(fd,buffers,...args){return typeof args[args.length-1]=="function"?fs4.writev(fd,buffers,...args):new Promise((resolve6,reject)=>{fs4.writev(fd,buffers,...args,(err,bytesWritten,buffers2)=>{if(err)return reject(err);resolve6({bytesWritten,buffers:buffers2})})})})}});var require_utils=__commonJS({"../../node_modules/.pnpm/fs-extra@10.0.0/node_modules/fs-extra/lib/mkdirs/utils.js"(exports,module){"use strict";var path2=__require("path");module.exports.checkPath=function(pth){if(process.platform==="win32"&&/[<>:"|?*]/.test(pth.replace(path2.parse(pth).root,""))){let error=new Error(`Path contains invalid characters: ${pth}`);throw error.code="EINVAL",error}}}});var require_make_dir=__commonJS({"../../node_modules/.pnpm/fs-extra@10.0.0/node_modules/fs-extra/lib/mkdirs/make-dir.js"(exports,module){"use strict";var fs4=require_fs(),{checkPath}=require_utils(),getMode=options=>{let defaults={mode:511};return typeof options=="number"?options:{...defaults,...options}.mode};module.exports.makeDir=async(dir,options)=>(checkPath(dir),fs4.mkdir(dir,{mode:getMode(options),recursive:!0}));module.exports.makeDirSync=(dir,options)=>(checkPath(dir),fs4.mkdirSync(dir,{mode:getMode(options),recursive:!0}))}});var require_mkdirs=__commonJS({"../../node_modules/.pnpm/fs-extra@10.0.0/node_modules/fs-extra/lib/mkdirs/index.js"(exports,module){"use strict";var u=require_universalify().fromPromise,{makeDir:_makeDir,makeDirSync}=require_make_dir(),makeDir=u(_makeDir);module.exports={mkdirs:makeDir,mkdirsSync:makeDirSync,mkdirp:makeDir,mkdirpSync:makeDirSync,ensureDir:makeDir,ensureDirSync:makeDirSync}}});var require_utimes=__commonJS({"../../node_modules/.pnpm/fs-extra@10.0.0/node_modules/fs-extra/lib/util/utimes.js"(exports,module){"use strict";var fs4=require_graceful_fs();function utimesMillis(path2,atime,mtime,callback){fs4.open(path2,"r+",(err,fd)=>{if(err)return callback(err);fs4.futimes(fd,atime,mtime,futimesErr=>{fs4.close(fd,closeErr=>{callback&&callback(futimesErr||closeErr)})})})}function utimesMillisSync(path2,atime,mtime){let fd=fs4.openSync(path2,"r+");return fs4.futimesSync(fd,atime,mtime),fs4.closeSync(fd)}module.exports={utimesMillis,utimesMillisSync}}});var require_stat=__commonJS({"../../node_modules/.pnpm/fs-extra@10.0.0/node_modules/fs-extra/lib/util/stat.js"(exports,module){"use strict";var fs4=require_fs(),path2=__require("path"),util=__require("util");function getStats(src,dest,opts){let statFunc=opts.dereference?file=>fs4.stat(file,{bigint:!0}):file=>fs4.lstat(file,{bigint:!0});return Promise.all([statFunc(src),statFunc(dest).catch(err=>{if(err.code==="ENOENT")return null;throw err})]).then(([srcStat,destStat])=>({srcStat,destStat}))}function getStatsSync(src,dest,opts){let destStat,statFunc=opts.dereference?file=>fs4.statSync(file,{bigint:!0}):file=>fs4.lstatSync(file,{bigint:!0}),srcStat=statFunc(src);try{destStat=statFunc(dest)}catch(err){if(err.code==="ENOENT")return{srcStat,destStat:null};throw err}return{srcStat,destStat}}function checkPaths(src,dest,funcName,opts,cb){util.callbackify(getStats)(src,dest,opts,(err,stats)=>{if(err)return cb(err);let{srcStat,destStat}=stats;if(destStat){if(areIdentical(srcStat,destStat)){let srcBaseName=path2.basename(src),destBaseName=path2.basename(dest);return funcName==="move"&&srcBaseName!==destBaseName&&srcBaseName.toLowerCase()===destBaseName.toLowerCase()?cb(null,{srcStat,destStat,isChangingCase:!0}):cb(new Error("Source and destination must not be the same."))}if(srcStat.isDirectory()&&!destStat.isDirectory())return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`));if(!srcStat.isDirectory()&&destStat.isDirectory())return cb(new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`))}return srcStat.isDirectory()&&isSrcSubdir(src,dest)?cb(new Error(errMsg(src,dest,funcName))):cb(null,{srcStat,destStat})})}function checkPathsSync(src,dest,funcName,opts){let{srcStat,destStat}=getStatsSync(src,dest,opts);if(destStat){if(areIdentical(srcStat,destStat)){let srcBaseName=path2.basename(src),destBaseName=path2.basename(dest);if(funcName==="move"&&srcBaseName!==destBaseName&&srcBaseName.toLowerCase()===destBaseName.toLowerCase())return{srcStat,destStat,isChangingCase:!0};throw new Error("Source and destination must not be the same.")}if(srcStat.isDirectory()&&!destStat.isDirectory())throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`);if(!srcStat.isDirectory()&&destStat.isDirectory())throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)}if(srcStat.isDirectory()&&isSrcSubdir(src,dest))throw new Error(errMsg(src,dest,funcName));return{srcStat,destStat}}function checkParentPaths(src,srcStat,dest,funcName,cb){let srcParent=path2.resolve(path2.dirname(src)),destParent=path2.resolve(path2.dirname(dest));if(destParent===srcParent||destParent===path2.parse(destParent).root)return cb();fs4.stat(destParent,{bigint:!0},(err,destStat)=>err?err.code==="ENOENT"?cb():cb(err):areIdentical(srcStat,destStat)?cb(new Error(errMsg(src,dest,funcName))):checkParentPaths(src,srcStat,destParent,funcName,cb))}function checkParentPathsSync(src,srcStat,dest,funcName){let srcParent=path2.resolve(path2.dirname(src)),destParent=path2.resolve(path2.dirname(dest));if(destParent===srcParent||destParent===path2.parse(destParent).root)return;let destStat;try{destStat=fs4.statSync(destParent,{bigint:!0})}catch(err){if(err.code==="ENOENT")return;throw err}if(areIdentical(srcStat,destStat))throw new Error(errMsg(src,dest,funcName));return checkParentPathsSync(src,srcStat,destParent,funcName)}function areIdentical(srcStat,destStat){return destStat.ino&&destStat.dev&&destStat.ino===srcStat.ino&&destStat.dev===srcStat.dev}function isSrcSubdir(src,dest){let srcArr=path2.resolve(src).split(path2.sep).filter(i=>i),destArr=path2.resolve(dest).split(path2.sep).filter(i=>i);return srcArr.reduce((acc,cur,i)=>acc&&destArr[i]===cur,!0)}function errMsg(src,dest,funcName){return`Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`}module.exports={checkPaths,checkPathsSync,checkParentPaths,checkParentPathsSync,isSrcSubdir,areIdentical}}});var require_copy_sync=__commonJS({"../../node_modules/.pnpm/fs-extra@10.0.0/node_modules/fs-extra/lib/copy-sync/copy-sync.js"(exports,module){"use strict";var fs4=require_graceful_fs(),path2=__require("path"),mkdirsSync=require_mkdirs().mkdirsSync,utimesMillisSync=require_utimes().utimesMillisSync,stat2=require_stat();function copySync(src,dest,opts){typeof opts=="function"&&(opts={filter:opts}),opts=opts||{},opts.clobber="clobber"in opts?!!opts.clobber:!0,opts.overwrite="overwrite"in opts?!!opts.overwrite:opts.clobber,opts.preserveTimestamps&&process.arch==="ia32"&&console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;
|
|
8
8
|
|
|
9
9
|
see https://github.com/jprichardson/node-fs-extra/issues/269`);let{srcStat,destStat}=stat2.checkPathsSync(src,dest,"copy",opts);return stat2.checkParentPathsSync(src,srcStat,dest,"copy"),handleFilterAndCopy(destStat,src,dest,opts)}function handleFilterAndCopy(destStat,src,dest,opts){if(opts.filter&&!opts.filter(src,dest))return;let destParent=path2.dirname(dest);return fs4.existsSync(destParent)||mkdirsSync(destParent),getStats(destStat,src,dest,opts)}function startCopy(destStat,src,dest,opts){if(!(opts.filter&&!opts.filter(src,dest)))return getStats(destStat,src,dest,opts)}function getStats(destStat,src,dest,opts){let srcStat=(opts.dereference?fs4.statSync:fs4.lstatSync)(src);if(srcStat.isDirectory())return onDir(srcStat,destStat,src,dest,opts);if(srcStat.isFile()||srcStat.isCharacterDevice()||srcStat.isBlockDevice())return onFile(srcStat,destStat,src,dest,opts);if(srcStat.isSymbolicLink())return onLink(destStat,src,dest,opts);throw srcStat.isSocket()?new Error(`Cannot copy a socket file: ${src}`):srcStat.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${src}`):new Error(`Unknown file: ${src}`)}function onFile(srcStat,destStat,src,dest,opts){return destStat?mayCopyFile(srcStat,src,dest,opts):copyFile(srcStat,src,dest,opts)}function mayCopyFile(srcStat,src,dest,opts){if(opts.overwrite)return fs4.unlinkSync(dest),copyFile(srcStat,src,dest,opts);if(opts.errorOnExist)throw new Error(`'${dest}' already exists`)}function copyFile(srcStat,src,dest,opts){return fs4.copyFileSync(src,dest),opts.preserveTimestamps&&handleTimestamps(srcStat.mode,src,dest),setDestMode(dest,srcStat.mode)}function handleTimestamps(srcMode,src,dest){return fileIsNotWritable(srcMode)&&makeFileWritable(dest,srcMode),setDestTimestamps(src,dest)}function fileIsNotWritable(srcMode){return(srcMode&128)===0}function makeFileWritable(dest,srcMode){return setDestMode(dest,srcMode|128)}function setDestMode(dest,srcMode){return fs4.chmodSync(dest,srcMode)}function setDestTimestamps(src,dest){let updatedSrcStat=fs4.statSync(src);return utimesMillisSync(dest,updatedSrcStat.atime,updatedSrcStat.mtime)}function onDir(srcStat,destStat,src,dest,opts){return destStat?copyDir(src,dest,opts):mkDirAndCopy(srcStat.mode,src,dest,opts)}function mkDirAndCopy(srcMode,src,dest,opts){return fs4.mkdirSync(dest),copyDir(src,dest,opts),setDestMode(dest,srcMode)}function copyDir(src,dest,opts){fs4.readdirSync(src).forEach(item=>copyDirItem(item,src,dest,opts))}function copyDirItem(item,src,dest,opts){let srcItem=path2.join(src,item),destItem=path2.join(dest,item),{destStat}=stat2.checkPathsSync(srcItem,destItem,"copy",opts);return startCopy(destStat,srcItem,destItem,opts)}function onLink(destStat,src,dest,opts){let resolvedSrc=fs4.readlinkSync(src);if(opts.dereference&&(resolvedSrc=path2.resolve(process.cwd(),resolvedSrc)),destStat){let resolvedDest;try{resolvedDest=fs4.readlinkSync(dest)}catch(err){if(err.code==="EINVAL"||err.code==="UNKNOWN")return fs4.symlinkSync(resolvedSrc,dest);throw err}if(opts.dereference&&(resolvedDest=path2.resolve(process.cwd(),resolvedDest)),stat2.isSrcSubdir(resolvedSrc,resolvedDest))throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`);if(fs4.statSync(dest).isDirectory()&&stat2.isSrcSubdir(resolvedDest,resolvedSrc))throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`);return copyLink(resolvedSrc,dest)}else return fs4.symlinkSync(resolvedSrc,dest)}function copyLink(resolvedSrc,dest){return fs4.unlinkSync(dest),fs4.symlinkSync(resolvedSrc,dest)}module.exports=copySync}});var require_copy_sync2=__commonJS({"../../node_modules/.pnpm/fs-extra@10.0.0/node_modules/fs-extra/lib/copy-sync/index.js"(exports,module){"use strict";module.exports={copySync:require_copy_sync()}}});var require_path_exists=__commonJS({"../../node_modules/.pnpm/fs-extra@10.0.0/node_modules/fs-extra/lib/path-exists/index.js"(exports,module){"use strict";var u=require_universalify().fromPromise,fs4=require_fs();function pathExists2(path2){return fs4.access(path2).then(()=>!0).catch(()=>!1)}module.exports={pathExists:u(pathExists2),pathExistsSync:fs4.existsSync}}});var require_copy=__commonJS({"../../node_modules/.pnpm/fs-extra@10.0.0/node_modules/fs-extra/lib/copy/copy.js"(exports,module){"use strict";var fs4=require_graceful_fs(),path2=__require("path"),mkdirs=require_mkdirs().mkdirs,pathExists2=require_path_exists().pathExists,utimesMillis=require_utimes().utimesMillis,stat2=require_stat();function copy(src,dest,opts,cb){typeof opts=="function"&&!cb?(cb=opts,opts={}):typeof opts=="function"&&(opts={filter:opts}),cb=cb||function(){},opts=opts||{},opts.clobber="clobber"in opts?!!opts.clobber:!0,opts.overwrite="overwrite"in opts?!!opts.overwrite:opts.clobber,opts.preserveTimestamps&&process.arch==="ia32"&&console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;
|
|
10
10
|
|
|
@@ -16,8 +16,8 @@ import{printAlignedLabel}from"./chunk-ADLBLGT3.js";import{getGlobalPathConfig}fr
|
|
|
16
16
|
${(0,import_error_utils.errorToString)(error)}`);return}let gitConfigPath=join2(gitRoot||directory,".git/config"),remoteUrl;if(project?.link){let{repo}=project.link,remoteUrls=await getRemoteUrls(gitConfigPath);if(remoteUrls)for(let urlValue of Object.values(remoteUrls))urlValue.includes(repo)&&(remoteUrl=urlValue)}remoteUrl||(remoteUrl=await getOriginUrl(gitConfigPath));let[commitResult,dirtyResult]=await metadata;if(commitResult.status==="rejected"){output_manager_default.debug(`Failed to get last commit. The directory is likely not a Git repo, there are no latest commits, or it is corrupted.
|
|
17
17
|
${commitResult.reason}`);return}if(dirtyResult.status==="rejected"){output_manager_default.debug(`Failed to determine if Git repo has been modified:
|
|
18
18
|
${dirtyResult.reason}`);return}let dirty=dirtyResult.value,commit=commitResult.value;return{remoteUrl:remoteUrl||void 0,commitAuthorName:commit.author.name,commitAuthorEmail:commit.author.email,commitMessage:commit.subject,commitRef:branch,commitSha:commit.hash,dirty,rootDirectory:getRootDirectory(directory,gitRoot)}}function getRootDirectory(directory,gitRoot=getGitRootDirectory({cwd:directory})){if(!gitRoot)return;let rootDirectory=relative(gitRoot,resolve4(directory)).replace(/\\/g,"/");if(!(rootDirectory===".."||rootDirectory.startsWith("../")))return rootDirectory==="."?"":rootDirectory}async function getLastCommit(directory,git){let commit=await execFileAsync(git,["log","-1","--format=%H%x00%s%x00%an%x00%ae"],{cwd:directory});if(commit.stderr)throw new Error(commit.stderr);let[hash,subject,name,email]=commit.stdout.replace(/\r?\n$/,"").split("\0");return{hash,subject,author:{name,email}}}async function isDirty(directory){let git=await getGitExecutable(directory);return new Promise((resolve6,reject)=>{execFile2(git,["--no-optional-locks","status","-s"],{cwd:directory},function(err,stdout,stderr){if(err)return reject(err);if(stderr!==void 0&&stderr.trim().length>0)return reject(new Error(stderr));resolve6(stdout.trim().length>0)})})}async function parseGitConfig(configPath){try{return import_ini.default.parse(await import_fs_extra.default.readFile(configPath,"utf-8"))}catch(err){output_manager_default.debug(`Error while parsing repo data: ${(0,import_error_utils.errorToString)(err)}`)}}function pluckRemoteUrls(gitConfig){let remoteUrls={};for(let key of Object.keys(gitConfig))if(key.includes("remote")){let remoteName=key.match(/(?<=").*(?=")/g)?.[0],remoteUrl=gitConfig[key]?.url;remoteName&&remoteUrl&&(remoteUrls[remoteName]=remoteUrl)}if(Object.keys(remoteUrls).length!==0)return remoteUrls}async function getRemoteUrls(configPath){let config2=await parseGitConfig(configPath);return config2?pluckRemoteUrls(config2):void 0}function pluckOriginUrl(gitConfig){return gitConfig['remote "origin"']?.url}async function getOriginUrl(configPath){let gitConfig=await parseGitConfig(configPath);if(!gitConfig)return null;let originUrl=pluckOriginUrl(gitConfig);return originUrl||null}var import_fs_extra5=__toESM(require_lib2(),1);import os2 from"os";import{join as join8}from"path";var import_fs_extra4=__toESM(require_lib2(),1);import fs3 from"fs";import{join as join7,relative as relative2}from"path";import{promisify}from"util";var import_chalk3=__toESM(require_source(),1),import_cli_config=__toESM(require_cli_config(),1),import_async_retry=__toESM(require_dist2(),1);import{join as join4,resolve as resolve5}from"node:path";import{EventEmitter}from"events";import{URL as URL2}from"url";async function responseError(res,fallbackMessage=null,parsedBody={}){let bodyError;if(!res.ok){let body;try{body=await res.json()}catch{body=parsedBody}bodyError=body.error||body.err||body}let msg=bodyError?.message||fallbackMessage||"Response Error";return new APIError(msg,res,bodyError)}var import_chalk2=__toESM(require_source(),1);function printIndications(res){let indications=new Set(["warning","notice","tip"]),regex=/^x-(?:vercel|now)-(warning|notice|tip)-(.*)$/;for(let[name,payload]of res.headers){let match=name.match(regex);if(match){let[,type,identifier]=match,action=res.headers.get(`x-vercel-action-${identifier}`),link=res.headers.get(`x-vercel-link-${identifier}`);if(indications.has(type)){let newline=`
|
|
19
|
-
`,message=prependEmoji(import_chalk2.default.dim(payload),emoji(type))+newline,finalLink="";link&&(finalLink=import_chalk2.default.dim(`${action||"Learn More"}: ${link_default(link)}`)+newline),output_manager_default.print(message+finalLink)}}}}var import_load_json_file=__toESM(require_load_json_file(),1),config=__toESM(require_cli_config(),1),import_error_utils2=__toESM(require_dist(),1),import_types=__toESM(require_types(),1);import{join as join3,basename,dirname}from"path";import{accessSync as accessSync2,constants as constants2}from"fs";import{persistCliAuthConfig,readCliAuthConfig}from"@vercel/cli-auth/credentials-store.js";import path from"path";import{existsSync}from"fs";function localConfigFlagPath(){let customPath=parseArguments(process.argv.slice(2),{},{permissive:!0}).flags["--local-config"];if(customPath){if(typeof customPath!="string")throw new InvalidLocalConfig(customPath);return path.resolve(process.cwd(),customPath)}}function getLocalPathConfig(prefix,useCompiledConfig=!0){let customPath=localConfigFlagPath();if(customPath)return customPath;let vercelConfigPath=path.join(prefix,"vercel.json"),vercelTomlPath=path.join(prefix,"vercel.toml"),nowConfigPath=path.join(prefix,"now.json"),vercelConfigExists=existsSync(vercelConfigPath),vercelTomlExists=existsSync(vercelTomlPath),nowConfigExists=existsSync(nowConfigPath),foundConfigs=[];if(vercelConfigExists&&foundConfigs.push(vercelConfigPath),vercelTomlExists&&foundConfigs.push(vercelTomlPath),nowConfigExists)throw new DeprecatedNowJson(nowConfigPath);if(foundConfigs.length>1)throw new ConflictingConfigFiles(foundConfigs);let compiledConfigPath=path.join(prefix,VERCEL_DIR,"vercel.json"),compiledConfigExists=existsSync(compiledConfigPath);return useCompiledConfig&&compiledConfigExists?compiledConfigPath:vercelConfigPath}var VERCEL_CONFIG_EXTENSIONS=["ts","mts","js","mjs","cjs"],DEFAULT_VERCEL_CONFIG_FILENAME="Vercel config";var globalDir,getVercelDir=()=>globalDir??=getGlobalPathConfig(),readConfigFile=()=>config.readGlobalConfigFile(getConfigFilePath2()),writeToConfigFile=stuff=>{try{config.writeGlobalConfigFile(getConfigFilePath2(),stuff)}catch(err){throw(0,import_error_utils2.isErrnoException)(err)&&((0,import_error_utils2.isErrnoException)(err)&&err.code==="EPERM"?(output_manager_default.error(`Not able to create ${highlight(getConfigFilePath2())} (operation not permitted).`),process.exit(1)):err.code==="EBADF"&&(output_manager_default.error(`Not able to create ${highlight(getConfigFilePath2())} (bad file descriptor).`),process.exit(1))),err}},readAuthConfigFile=_globalConfig=>({...config.getDefaultAuthConfig(),...readCliAuthConfig(getVercelDir())}),persistAuthConfig=(authConfig,_globalConfig)=>{try{return persistCliAuthConfig(getVercelDir(),authConfig)}catch(err){let wrappedError=new Error(`Not able to create ${humanizePath(getAuthConfigFilePath2())} (${(0,import_error_utils2.errorToStringFriendly)(err)}).`);throw wrappedError.cause=err,wrappedError}};function getConfigFilePath2(){return config.getConfigFilePath(getVercelDir())}function getAuthConfigFilePath2(){return config.getAuthConfigFilePath(getVercelDir())}function readLocalConfig(prefix=process.cwd()){let config2,target="";try{target=getLocalPathConfig(prefix)}catch(err){if(err instanceof NowError)output_manager_default.error(err.message),process.exit(1);else throw err}if(!target)return;try{accessSync2(target,constants2.F_OK),config2=import_load_json_file.default.sync(target)}catch(err){if(!((0,import_error_utils2.isErrnoException)(err)&&err.code==="ENOENT"))if((0,import_error_utils2.isError)(err)&&err.name==="JSONError")output_manager_default.error(err.message),process.exit(1);else if((0,import_error_utils2.isErrnoException)(err)){let code2=err.code?` (${err.code})`:"";output_manager_default.error(`Failed to read config file: ${target}${code2}`),process.exit(1)}else output_manager_default.prettyError(err),process.exit(1)}if(!config2)return;if(basename(target)==="vercel.json"&&basename(dirname(target))===VERCEL_DIR){let workPath=dirname(dirname(target)),sourceFile=null;for(let ext of VERCEL_CONFIG_EXTENSIONS){let configPath=join3(workPath,`vercel.${ext}`);try{accessSync2(configPath,constants2.F_OK),sourceFile=basename(configPath);break}catch{}}if(!sourceFile){let tomlPath=join3(workPath,"vercel.toml");try{accessSync2(tomlPath,constants2.F_OK),sourceFile="vercel.toml"}catch{}}config2[import_types.fileNameSymbol]=sourceFile||DEFAULT_VERCEL_CONFIG_FILENAME}else config2[import_types.fileNameSymbol]=basename(target);return config2}function sharedPromise(fn){let promise=null;return function(...args){return promise||(promise=fn.apply(this,args),promise.finally(()=>{promise=null})),promise}}var import_error_utils3=__toESM(require_dist(),1);function sleep(ms){return new Promise(resolve6=>{setTimeout(resolve6,ms)})}import{hostname}from"os";var VERCEL_ISSUER=new URL("https://vercel.com"),VERCEL_CLI_CLIENT_ID="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",userAgent=`${hostname()} @ ${ua_default}`,_as;async function as(){if(!_as){let discoveryResponse=await discoveryEndpointRequest(VERCEL_ISSUER),[discoveryResponseError,as2]=await processDiscoveryEndpointResponse(discoveryResponse);if(discoveryResponseError)throw discoveryResponseError;_as=as2}return _as}async function discoveryEndpointRequest(issuer){return await fetch(new URL(".well-known/openid-configuration",issuer),{headers:{"Content-Type":"application/json","user-agent":userAgent}})}async function processDiscoveryEndpointResponse(response){let json=await response.json();if(!response.ok)return[new Error("Discovery endpoint request failed")];if(typeof json!="object"||json===null||!canParseURL(json.issuer)||!canParseURL(json.device_authorization_endpoint)||!canParseURL(json.token_endpoint)||!canParseURL(json.revocation_endpoint)||!canParseURL(json.jwks_uri)||!canParseURL(json.introspection_endpoint))return[new TypeError("Invalid discovery response")];let issuer=new URL(json.issuer);return issuer.href!==VERCEL_ISSUER.href?[new Error("Issuer mismatch")]:[null,{issuer,device_authorization_endpoint:new URL(json.device_authorization_endpoint),token_endpoint:new URL(json.token_endpoint),revocation_endpoint:new URL(json.revocation_endpoint),jwks_uri:new URL(json.jwks_uri),introspection_endpoint:new URL(json.introspection_endpoint)}]}async function deviceAuthorizationRequest(options){let body=new URLSearchParams({client_id:VERCEL_CLI_CLIENT_ID});return options?.refresh_token?(body.set("refresh_token",options.refresh_token),options.acr_values&&body.set("acr_values",options.acr_values)):body.set("scope","openid offline_access"),await fetch((await as()).device_authorization_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":userAgent},body})}async function processDeviceAuthorizationResponse(response){let json=await response.json();return response.ok?typeof json!="object"||json===null?[new TypeError("Expected response to be an object")]:!("device_code"in json)||typeof json.device_code!="string"?[new TypeError("Expected `device_code` to be a string")]:!("user_code"in json)||typeof json.user_code!="string"?[new TypeError("Expected `user_code` to be a string")]:!("verification_uri"in json)||typeof json.verification_uri!="string"||!canParseURL(json.verification_uri)?[new TypeError("Expected `verification_uri` to be a string")]:!("verification_uri_complete"in json)||typeof json.verification_uri_complete!="string"||!canParseURL(json.verification_uri_complete)?[new TypeError("Expected `verification_uri_complete` to be a string")]:!("expires_in"in json)||typeof json.expires_in!="number"?[new TypeError("Expected `expires_in` to be a number")]:!("interval"in json)||typeof json.interval!="number"?[new TypeError("Expected `interval` to be a number")]:[null,{device_code:json.device_code,user_code:json.user_code,verification_uri:json.verification_uri,verification_uri_complete:json.verification_uri_complete,expiresAt:Date.now()+json.expires_in*1e3,interval:json.interval}]:[new OAuthError("Device authorization request failed",json)]}async function deviceAccessTokenRequest(options){try{return[null,await fetch((await as()).token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":userAgent},body:new URLSearchParams({client_id:VERCEL_CLI_CLIENT_ID,grant_type:"urn:ietf:params:oauth:grant-type:device_code",...options}),signal:AbortSignal.timeout(10*1e3)})]}catch(error){return error instanceof Error?[error]:[new Error("An unknown error occurred. See the logs for details.",{cause:error})]}}async function processTokenResponse(response){let json=await response.json();return response.ok?typeof json!="object"||json===null?[new TypeError("Expected response to be an object")]:!("access_token"in json)||typeof json.access_token!="string"?[new TypeError("Expected `access_token` to be a string")]:!("token_type"in json)||json.token_type!=="Bearer"?[new TypeError('Expected `token_type` to be "Bearer"')]:!("expires_in"in json)||typeof json.expires_in!="number"?[new TypeError("Expected `expires_in` to be a number")]:"refresh_token"in json&&(typeof json.refresh_token!="string"||!json.refresh_token)?[new TypeError("Expected `refresh_token` to be a string")]:"scope"in json&&typeof json.scope!="string"?[new TypeError("Expected `scope` to be a string")]:[null,json]:[new OAuthError("Device access token request failed",json)]}async function revocationRequest(options){return await fetch((await as()).revocation_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":userAgent},body:new URLSearchParams({...options,client_id:VERCEL_CLI_CLIENT_ID})})}async function processRevocationResponse(response){if(response.ok)return[null,null];let json=await response.json();return[new OAuthError("Revocation request failed",json)]}async function refreshTokenRequest(options){return await fetch((await as()).token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":userAgent},body:new URLSearchParams({client_id:VERCEL_CLI_CLIENT_ID,grant_type:"refresh_token",...options})})}function processOAuthErrorResponse(json){return typeof json!="object"||json===null?new TypeError("Expected response to be an object"):!("error"in json)||typeof json.error!="string"?new TypeError("Expected `error` to be a string"):"error_description"in json&&typeof json.error_description!="string"?new TypeError("Expected `error_description` to be a string"):"error_uri"in json&&typeof json.error_uri!="string"?new TypeError("Expected `error_uri` to be a string"):json}var OAuthError=class extends Error{constructor(message,response){var __super=(...args)=>{super(...args)};let error=processOAuthErrorResponse(response);if(error instanceof TypeError){let message2=`Unexpected server response: ${JSON.stringify(response)}`;__super(message2),this.cause=new Error(message2,{cause:error}),this.code="server_error";return}let cause=error.error;error.error_description&&(cause+=`: ${error.error_description}`),error.error_uri&&(cause+=` (${error.error_uri})`),__super(message,{cause}),this.cause=new Error(cause),this.code=error.error}};function isOAuthError(error){return error instanceof OAuthError}function canParseURL(url){try{return!!new URL(url)}catch{return!1}}async function inspectTokenRequest(token){return fetch((await as()).introspection_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":userAgent},body:new URLSearchParams({token})})}async function processInspectTokenResponse(response){try{let token=await response.json();if(!token||typeof token!="object"||!("active"in token))throw new IntrospectionError("Invalid token introspection response");return[null,token]}catch(cause){return[new IntrospectionError("Could not introspect token.",{cause})]}}var IntrospectionError=class extends Error{constructor(){super(...arguments);this.name="IntrospectionError"}};var PromptCanceledError=class extends Error{constructor(){super("Prompt canceled"),this.name="PromptCanceledError"}},PromptBackError=class extends Error{constructor(){super("Prompt back"),this.name="PromptBackError"}};function isPromptBackError(error){return error instanceof PromptBackError}function isPromptCanceledError(error){return error instanceof PromptCanceledError?!0:error instanceof Error&&error.message.includes("User force closed the prompt")}var TEAM_NOT_CHOSEN="",DOMAINS_API_PATH=/^\/v\d+\/(?:domains|registrar)(?:\/|$)/,isSAMLError=v=>v&&v.saml,isJSONObject=v=>v&&typeof v=="object"&&v.constructor===Object;function isValidAccessToken(authConfig){if(!authConfig.token)return!1;if(typeof authConfig.expiresAt!="number")return!0;let nowInSeconds=Math.floor(Date.now()/1e3);return authConfig.expiresAt>=nowInSeconds}function hasRefreshToken(authConfig){return"refreshToken"in authConfig}var Client=class extends EventEmitter{constructor(opts){super();this._argv=[];this._loggedTokenSource=!1;this.escapePromptCancellationDepth=0;this.promptBackNavigationDepth=0;this.reauthenticate=sharedPromise(async function(error){let{default:reauthenticate}=await import("./reauthenticate-OZRQFR66.js");if(typeof await reauthenticate(this,error)=="number")throw error instanceof APIError?output_manager_default.prettyError(error):output_manager_default.error(`Failed to re-authenticate for ${(0,import_chalk3.bold)(error.scope)} scope`),error});this._onRetry=error=>{output_manager_default.debug(`Retrying: ${error}
|
|
20
|
-
${error.stack}`)};this.setArgv(opts.argv),this.apiUrl=opts.apiUrl,this.authConfig=opts.authConfig,this.stdin=opts.stdin,this.stdout=opts.stdout,this.stderr=opts.stderr,this.config=opts.config,this.savedTeam=opts.config.currentTeam,this.localConfig=opts.localConfig,this.localConfigPath=opts.localConfigPath,this.requestIdCounter=1,this.telemetryEventStore=opts.telemetryEventStore,this.isAgent=opts.isAgent??!1,this.agentName=opts.agentName,this.nonInteractive=opts.nonInteractive??this.isAgent,this.ignoresSavedTeam=this.isAgent&&this.nonInteractive,this.dangerouslySkipPermissions=opts.dangerouslySkipPermissions??!1;let theme={prefix:(0,import_chalk3.gray)("?"),style:{answer:import_chalk3.gray}};this.input={text:async opts2=>{let{default:input}=await import("./esm-IF453UWS.js");return this.runPrompt(input({theme,...opts2},{input:this.stdin,output:this.stderr}))},password:async opts2=>{let{default:password}=await import("./esm-LABWDJ72.js");return this.runPrompt(password({theme,...opts2},{input:this.stdin,output:this.stderr}))},checkbox:async opts2=>{let{default:checkbox}=await import("./esm-BYG5BWYH.js");return this.runPrompt(checkbox({theme,...opts2},{input:this.stdin,output:this.stderr}))},expand:async opts2=>{let{default:expand}=await import("./esm-TG37FXTU.js");return this.runPrompt(expand({theme,...opts2},{input:this.stdin,output:this.stderr}))},confirm:async(message,default_value,opts2)=>{let{default:confirm}=await import("./esm-33752ISR.js"),prompt=confirm({theme,message,default:default_value},{input:this.stdin,output:this.stderr}),signal=opts2?.signal,cancel=()=>prompt.cancel();return signal?.aborted&&cancel(),signal?.addEventListener("abort",cancel,{once:!0}),this.runPrompt(prompt).finally(()=>signal?.removeEventListener("abort",cancel))},select:async opts2=>{let{default:select}=await import("./esm-4JKEE7PC.js");return this.runPrompt(select({theme,...opts2},{input:this.stdin,output:this.stderr}))},search:async opts2=>{let{default:search}=await import("./esm-DFFBNKNU.js");return this.runPrompt(search({theme,...opts2},{input:this.stdin,output:this.stderr}))}}}async withEscapePromptCancellation(run){this.escapePromptCancellationDepth++;try{return await run()}finally{this.escapePromptCancellationDepth--}}async withPromptBackNavigation(run){this.promptBackNavigationDepth++;try{return await run()}finally{this.promptBackNavigationDepth--}}runPrompt(prompt){let escapeCancellationEnabled=this.escapePromptCancellationDepth>0,backNavigationEnabled=this.promptBackNavigationDepth>0;if(!escapeCancellationEnabled&&!backNavigationEnabled||!this.stdin.isTTY||!prompt.cancel)return prompt;let cancellation,onKeypress=(_input,key)=>{key?.name==="escape"&&escapeCancellationEnabled&&!cancellation?(cancellation="escape",prompt.cancel?.()):key?.name==="up"&&backNavigationEnabled&&!cancellation&&(cancellation="back",prompt.cancel?.())};return this.stdin.on("keypress",onKeypress),prompt.catch(error=>{throw cancellation==="escape"?new PromptCanceledError:cancellation==="back"?new PromptBackError:error}).finally(()=>{this.stdin.off("keypress",onKeypress)})}get argv(){return this._argv}setArgv(argvOrFirst,...rest){let argv=Array.isArray(argvOrFirst)?argvOrFirst:[argvOrFirst,...rest];this._argv=argv,this._parsedArgsCache=void 0}getParsedArgs(){return this._parsedArgsCache||(this._parsedArgsCache=parseArguments(this.argv.slice(2),{},{permissive:!0})),this._parsedArgsCache}retry(fn,{retries=3,maxTimeout=1/0}={}){return(0,import_async_retry.default)(fn,{retries,maxTimeout,onRetry:this._onRetry})}async ensureAuthorized(){let{authConfig}=this;if(isValidAccessToken(authConfig)){this._loggedTokenSource||(authConfig.tokenSource==="flag"?output_manager_default.debug("Using token from `--token` argument, skipping token refresh."):authConfig.tokenSource==="env"?output_manager_default.debug("Using token from VERCEL_TOKEN environment variable, skipping token refresh."):output_manager_default.debug("Valid access token, skipping token refresh."),this._loggedTokenSource=!0);return}if(!hasRefreshToken(authConfig)){output_manager_default.debug("No refresh token found, emptying auth config."),this.emptyAuthConfig(),this.persistAuthConfig();return}let tokenResponse=await refreshTokenRequest({refresh_token:authConfig.refreshToken}),[tokensError,tokens]=await processTokenResponse(tokenResponse);if(isOAuthError(tokensError)&&tokensError.code==="invalid_grant"&&!authConfig.tokenSource&&this.stdin.isTTY&&!this.nonInteractive){output_manager_default.debug(`Stored session refresh failed: ${tokensError.cause.message}`),output_manager_default.log("Couldn't refresh the saved login. Starting a new login.");let{performDeviceCodeFlow}=await import("./future-
|
|
19
|
+
`,message=prependEmoji(import_chalk2.default.dim(payload),emoji(type))+newline,finalLink="";link&&(finalLink=import_chalk2.default.dim(`${action||"Learn More"}: ${link_default(link)}`)+newline),output_manager_default.print(message+finalLink)}}}}var import_load_json_file=__toESM(require_load_json_file(),1),config=__toESM(require_cli_config(),1),import_error_utils2=__toESM(require_dist(),1),import_types=__toESM(require_types(),1);import{join as join3,basename,dirname}from"path";import{accessSync as accessSync2,constants as constants2}from"fs";import{persistCliAuthConfig,readCliAuthConfig}from"@vercel/cli-auth/credentials-store.js";import path from"path";import{existsSync}from"fs";function localConfigFlagPath(){let customPath=parseArguments(process.argv.slice(2),{},{permissive:!0}).flags["--local-config"];if(customPath){if(typeof customPath!="string")throw new InvalidLocalConfig(customPath);return path.resolve(process.cwd(),customPath)}}function getLocalPathConfig(prefix,useCompiledConfig=!0){let customPath=localConfigFlagPath();if(customPath)return customPath;let vercelConfigPath=path.join(prefix,"vercel.json"),vercelTomlPath=path.join(prefix,"vercel.toml"),nowConfigPath=path.join(prefix,"now.json"),vercelConfigExists=existsSync(vercelConfigPath),vercelTomlExists=existsSync(vercelTomlPath),nowConfigExists=existsSync(nowConfigPath),foundConfigs=[];if(vercelConfigExists&&foundConfigs.push(vercelConfigPath),vercelTomlExists&&foundConfigs.push(vercelTomlPath),nowConfigExists)throw new DeprecatedNowJson(nowConfigPath);if(foundConfigs.length>1)throw new ConflictingConfigFiles(foundConfigs);let compiledConfigPath=path.join(prefix,VERCEL_DIR,"vercel.json"),compiledConfigExists=existsSync(compiledConfigPath);return useCompiledConfig&&compiledConfigExists?compiledConfigPath:vercelConfigPath}var VERCEL_CONFIG_EXTENSIONS=["ts","mts","js","mjs","cjs"],DEFAULT_VERCEL_CONFIG_FILENAME="Vercel config";var globalDir,getVercelDir=()=>globalDir??=getGlobalPathConfig(),readConfigFile=()=>config.readGlobalConfigFile(getConfigFilePath2()),writeToConfigFile=stuff=>{try{config.writeGlobalConfigFile(getConfigFilePath2(),stuff)}catch(err){throw(0,import_error_utils2.isErrnoException)(err)&&((0,import_error_utils2.isErrnoException)(err)&&err.code==="EPERM"?(output_manager_default.error(`Not able to create ${highlight(getConfigFilePath2())} (operation not permitted).`),process.exit(1)):err.code==="EBADF"&&(output_manager_default.error(`Not able to create ${highlight(getConfigFilePath2())} (bad file descriptor).`),process.exit(1))),err}},readAuthConfigFile=_globalConfig=>({...config.getDefaultAuthConfig(),...readCliAuthConfig(getVercelDir())}),persistAuthConfig=(authConfig,_globalConfig)=>{try{return persistCliAuthConfig(getVercelDir(),authConfig)}catch(err){let wrappedError=new Error(`Not able to create ${humanizePath(getAuthConfigFilePath2())} (${(0,import_error_utils2.errorToStringFriendly)(err)}).`);throw wrappedError.cause=err,wrappedError}};function getConfigFilePath2(){return config.getConfigFilePath(getVercelDir())}function getAuthConfigFilePath2(){return config.getAuthConfigFilePath(getVercelDir())}function readLocalConfig(prefix=process.cwd()){let config2,target="";try{target=getLocalPathConfig(prefix)}catch(err){if(err instanceof NowError)output_manager_default.error(err.message),process.exit(1);else throw err}if(!target)return;try{accessSync2(target,constants2.F_OK),config2=import_load_json_file.default.sync(target)}catch(err){if(!((0,import_error_utils2.isErrnoException)(err)&&err.code==="ENOENT"))if((0,import_error_utils2.isError)(err)&&err.name==="JSONError")output_manager_default.error(err.message),process.exit(1);else if((0,import_error_utils2.isErrnoException)(err)){let code2=err.code?` (${err.code})`:"";output_manager_default.error(`Failed to read config file: ${target}${code2}`),process.exit(1)}else output_manager_default.prettyError(err),process.exit(1)}if(!config2)return;if(basename(target)==="vercel.json"&&basename(dirname(target))===VERCEL_DIR){let workPath=dirname(dirname(target)),sourceFile=null;for(let ext of VERCEL_CONFIG_EXTENSIONS){let configPath=join3(workPath,`vercel.${ext}`);try{accessSync2(configPath,constants2.F_OK),sourceFile=basename(configPath);break}catch{}}if(!sourceFile){let tomlPath=join3(workPath,"vercel.toml");try{accessSync2(tomlPath,constants2.F_OK),sourceFile="vercel.toml"}catch{}}config2[import_types.fileNameSymbol]=sourceFile||DEFAULT_VERCEL_CONFIG_FILENAME}else config2[import_types.fileNameSymbol]=basename(target);return config2}function sharedPromise(fn){let promise=null;return function(...args){return promise||(promise=fn.apply(this,args),promise.finally(()=>{promise=null})),promise}}var import_error_utils3=__toESM(require_dist(),1);function sleep(ms){return new Promise(resolve6=>{setTimeout(resolve6,ms)})}import{hostname}from"os";var VERCEL_ISSUER=new URL("https://vercel.com"),VERCEL_CLI_CLIENT_ID="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",userAgent=`${hostname()} @ ${ua_default}`,_as;async function as(){if(!_as){let discoveryResponse=await discoveryEndpointRequest(VERCEL_ISSUER),[discoveryResponseError,as2]=await processDiscoveryEndpointResponse(discoveryResponse);if(discoveryResponseError)throw discoveryResponseError;_as=as2}return _as}async function discoveryEndpointRequest(issuer){return await fetch(new URL(".well-known/openid-configuration",issuer),{headers:{"Content-Type":"application/json","user-agent":userAgent}})}async function processDiscoveryEndpointResponse(response){let json=await response.json();if(!response.ok)return[new Error("Discovery endpoint request failed")];if(typeof json!="object"||json===null||!canParseURL(json.issuer)||!canParseURL(json.device_authorization_endpoint)||!canParseURL(json.token_endpoint)||!canParseURL(json.revocation_endpoint)||!canParseURL(json.jwks_uri)||!canParseURL(json.introspection_endpoint))return[new TypeError("Invalid discovery response")];let issuer=new URL(json.issuer);return issuer.href!==VERCEL_ISSUER.href?[new Error("Issuer mismatch")]:[null,{issuer,device_authorization_endpoint:new URL(json.device_authorization_endpoint),token_endpoint:new URL(json.token_endpoint),revocation_endpoint:new URL(json.revocation_endpoint),jwks_uri:new URL(json.jwks_uri),introspection_endpoint:new URL(json.introspection_endpoint)}]}async function deviceAuthorizationRequest(options){let body=new URLSearchParams({client_id:VERCEL_CLI_CLIENT_ID});return options?.refresh_token?(body.set("refresh_token",options.refresh_token),options.acr_values&&body.set("acr_values",options.acr_values)):body.set("scope","openid offline_access"),await fetch((await as()).device_authorization_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":userAgent},body})}async function processDeviceAuthorizationResponse(response){let json=await response.json();return response.ok?typeof json!="object"||json===null?[new TypeError("Expected response to be an object")]:!("device_code"in json)||typeof json.device_code!="string"?[new TypeError("Expected `device_code` to be a string")]:!("user_code"in json)||typeof json.user_code!="string"?[new TypeError("Expected `user_code` to be a string")]:!("verification_uri"in json)||typeof json.verification_uri!="string"||!canParseURL(json.verification_uri)?[new TypeError("Expected `verification_uri` to be a string")]:!("verification_uri_complete"in json)||typeof json.verification_uri_complete!="string"||!canParseURL(json.verification_uri_complete)?[new TypeError("Expected `verification_uri_complete` to be a string")]:!("expires_in"in json)||typeof json.expires_in!="number"?[new TypeError("Expected `expires_in` to be a number")]:!("interval"in json)||typeof json.interval!="number"?[new TypeError("Expected `interval` to be a number")]:[null,{device_code:json.device_code,user_code:json.user_code,verification_uri:json.verification_uri,verification_uri_complete:json.verification_uri_complete,expiresAt:Date.now()+json.expires_in*1e3,interval:json.interval}]:[new OAuthError("Device authorization request failed",json)]}async function deviceAccessTokenRequest(options){try{return[null,await fetch((await as()).token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":userAgent},body:new URLSearchParams({client_id:VERCEL_CLI_CLIENT_ID,grant_type:"urn:ietf:params:oauth:grant-type:device_code",...options}),signal:AbortSignal.timeout(10*1e3)})]}catch(error){return error instanceof Error?[error]:[new Error("An unknown error occurred. See the logs for details.",{cause:error})]}}async function processTokenResponse(response){let json=await response.json();return response.ok?typeof json!="object"||json===null?[new TypeError("Expected response to be an object")]:!("access_token"in json)||typeof json.access_token!="string"?[new TypeError("Expected `access_token` to be a string")]:!("token_type"in json)||json.token_type!=="Bearer"?[new TypeError('Expected `token_type` to be "Bearer"')]:!("expires_in"in json)||typeof json.expires_in!="number"?[new TypeError("Expected `expires_in` to be a number")]:"refresh_token"in json&&(typeof json.refresh_token!="string"||!json.refresh_token)?[new TypeError("Expected `refresh_token` to be a string")]:"scope"in json&&typeof json.scope!="string"?[new TypeError("Expected `scope` to be a string")]:[null,json]:[new OAuthError("Device access token request failed",json)]}async function revocationRequest(options){return await fetch((await as()).revocation_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":userAgent},body:new URLSearchParams({...options,client_id:VERCEL_CLI_CLIENT_ID})})}async function processRevocationResponse(response){if(response.ok)return[null,null];let json=await response.json();return[new OAuthError("Revocation request failed",json)]}async function refreshTokenRequest(options){return await fetch((await as()).token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":userAgent},body:new URLSearchParams({client_id:VERCEL_CLI_CLIENT_ID,grant_type:"refresh_token",...options})})}function processOAuthErrorResponse(json){return typeof json!="object"||json===null?new TypeError("Expected response to be an object"):!("error"in json)||typeof json.error!="string"?new TypeError("Expected `error` to be a string"):"error_description"in json&&typeof json.error_description!="string"?new TypeError("Expected `error_description` to be a string"):"error_uri"in json&&typeof json.error_uri!="string"?new TypeError("Expected `error_uri` to be a string"):json}var OAuthError=class extends Error{constructor(message,response){var __super=(...args)=>{super(...args)};let error=processOAuthErrorResponse(response);if(error instanceof TypeError){let message2=`Unexpected server response: ${JSON.stringify(response)}`;__super(message2),this.cause=new Error(message2,{cause:error}),this.code="server_error";return}let cause=error.error;error.error_description&&(cause+=`: ${error.error_description}`),error.error_uri&&(cause+=` (${error.error_uri})`),__super(message,{cause}),this.cause=new Error(cause),this.code=error.error}};function isOAuthError(error){return error instanceof OAuthError}function canParseURL(url){try{return!!new URL(url)}catch{return!1}}async function inspectTokenRequest(token){return fetch((await as()).introspection_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":userAgent},body:new URLSearchParams({token})})}async function processInspectTokenResponse(response){try{let token=await response.json();if(!token||typeof token!="object"||!("active"in token))throw new IntrospectionError("Invalid token introspection response");return[null,token]}catch(cause){return[new IntrospectionError("Could not introspect token.",{cause})]}}var IntrospectionError=class extends Error{constructor(){super(...arguments);this.name="IntrospectionError"}};var PromptCanceledError=class extends Error{constructor(){super("Prompt canceled"),this.name="PromptCanceledError"}},PromptBackError=class extends Error{constructor(){super("Prompt back"),this.name="PromptBackError"}};function isPromptBackError(error){return error instanceof PromptBackError}function isPromptCanceledError(error){return error instanceof PromptCanceledError?!0:error instanceof Error&&error.message.includes("User force closed the prompt")}var TEAM_NOT_CHOSEN="",DOMAINS_API_PATH=/^\/v\d+\/(?:domains|registrar)(?:\/|$)/,isSAMLError=v=>v&&v.saml,isJSONObject=v=>v&&typeof v=="object"&&v.constructor===Object;function isValidAccessToken(authConfig){if(!authConfig.token)return!1;if(typeof authConfig.expiresAt!="number")return!0;let nowInSeconds=Math.floor(Date.now()/1e3);return authConfig.expiresAt>=nowInSeconds}function hasRefreshToken(authConfig){return"refreshToken"in authConfig}var Client=class extends EventEmitter{constructor(opts){super();this._argv=[];this._loggedTokenSource=!1;this.escapePromptCancellationDepth=0;this.promptBackNavigationDepth=0;this.reauthenticate=sharedPromise(async function(error){let{default:reauthenticate}=await import("./reauthenticate-IXQDC4UZ.js");if(typeof await reauthenticate(this,error)=="number")throw error instanceof APIError?output_manager_default.prettyError(error):output_manager_default.error(`Failed to re-authenticate for ${(0,import_chalk3.bold)(error.scope)} scope`),error});this._onRetry=error=>{output_manager_default.debug(`Retrying: ${error}
|
|
20
|
+
${error.stack}`)};this.setArgv(opts.argv),this.apiUrl=opts.apiUrl,this.authConfig=opts.authConfig,this.stdin=opts.stdin,this.stdout=opts.stdout,this.stderr=opts.stderr,this.config=opts.config,this.savedTeam=opts.config.currentTeam,this.localConfig=opts.localConfig,this.localConfigPath=opts.localConfigPath,this.requestIdCounter=1,this.telemetryEventStore=opts.telemetryEventStore,this.isAgent=opts.isAgent??!1,this.agentName=opts.agentName,this.nonInteractive=opts.nonInteractive??this.isAgent,this.ignoresSavedTeam=this.isAgent&&this.nonInteractive,this.dangerouslySkipPermissions=opts.dangerouslySkipPermissions??!1;let theme={prefix:(0,import_chalk3.gray)("?"),style:{answer:import_chalk3.gray}};this.input={text:async opts2=>{let{default:input}=await import("./esm-IF453UWS.js");return this.runPrompt(input({theme,...opts2},{input:this.stdin,output:this.stderr}))},password:async opts2=>{let{default:password}=await import("./esm-LABWDJ72.js");return this.runPrompt(password({theme,...opts2},{input:this.stdin,output:this.stderr}))},checkbox:async opts2=>{let{default:checkbox}=await import("./esm-BYG5BWYH.js");return this.runPrompt(checkbox({theme,...opts2},{input:this.stdin,output:this.stderr}))},expand:async opts2=>{let{default:expand}=await import("./esm-TG37FXTU.js");return this.runPrompt(expand({theme,...opts2},{input:this.stdin,output:this.stderr}))},confirm:async(message,default_value,opts2)=>{let{default:confirm}=await import("./esm-33752ISR.js"),prompt=confirm({theme,message,default:default_value},{input:this.stdin,output:this.stderr}),signal=opts2?.signal,cancel=()=>prompt.cancel();return signal?.aborted&&cancel(),signal?.addEventListener("abort",cancel,{once:!0}),this.runPrompt(prompt).finally(()=>signal?.removeEventListener("abort",cancel))},select:async opts2=>{let{default:select}=await import("./esm-4JKEE7PC.js");return this.runPrompt(select({theme,...opts2},{input:this.stdin,output:this.stderr}))},search:async opts2=>{let{default:search}=await import("./esm-DFFBNKNU.js");return this.runPrompt(search({theme,...opts2},{input:this.stdin,output:this.stderr}))}}}async withEscapePromptCancellation(run){this.escapePromptCancellationDepth++;try{return await run()}finally{this.escapePromptCancellationDepth--}}async withPromptBackNavigation(run){this.promptBackNavigationDepth++;try{return await run()}finally{this.promptBackNavigationDepth--}}runPrompt(prompt){let escapeCancellationEnabled=this.escapePromptCancellationDepth>0,backNavigationEnabled=this.promptBackNavigationDepth>0;if(!escapeCancellationEnabled&&!backNavigationEnabled||!this.stdin.isTTY||!prompt.cancel)return prompt;let cancellation,onKeypress=(_input,key)=>{key?.name==="escape"&&escapeCancellationEnabled&&!cancellation?(cancellation="escape",prompt.cancel?.()):key?.name==="up"&&backNavigationEnabled&&!cancellation&&(cancellation="back",prompt.cancel?.())};return this.stdin.on("keypress",onKeypress),prompt.catch(error=>{throw cancellation==="escape"?new PromptCanceledError:cancellation==="back"?new PromptBackError:error}).finally(()=>{this.stdin.off("keypress",onKeypress)})}get argv(){return this._argv}setArgv(argvOrFirst,...rest){let argv=Array.isArray(argvOrFirst)?argvOrFirst:[argvOrFirst,...rest];this._argv=argv,this._parsedArgsCache=void 0}getParsedArgs(){return this._parsedArgsCache||(this._parsedArgsCache=parseArguments(this.argv.slice(2),{},{permissive:!0})),this._parsedArgsCache}retry(fn,{retries=3,maxTimeout=1/0}={}){return(0,import_async_retry.default)(fn,{retries,maxTimeout,onRetry:this._onRetry})}async ensureAuthorized(){let{authConfig}=this;if(isValidAccessToken(authConfig)){this._loggedTokenSource||(authConfig.tokenSource==="flag"?output_manager_default.debug("Using token from `--token` argument, skipping token refresh."):authConfig.tokenSource==="env"?output_manager_default.debug("Using token from VERCEL_TOKEN environment variable, skipping token refresh."):output_manager_default.debug("Valid access token, skipping token refresh."),this._loggedTokenSource=!0);return}if(!hasRefreshToken(authConfig)){output_manager_default.debug("No refresh token found, emptying auth config."),this.emptyAuthConfig(),this.persistAuthConfig();return}let tokenResponse=await refreshTokenRequest({refresh_token:authConfig.refreshToken}),[tokensError,tokens]=await processTokenResponse(tokenResponse);if(isOAuthError(tokensError)&&tokensError.code==="invalid_grant"&&!authConfig.tokenSource&&this.stdin.isTTY&&!this.nonInteractive){output_manager_default.debug(`Stored session refresh failed: ${tokensError.cause.message}`),output_manager_default.log("Couldn't refresh the saved login. Starting a new login.");let{performDeviceCodeFlow}=await import("./future-V77DRMQG.js"),recoveredTokens=await performDeviceCodeFlow(this);if(recoveredTokens){this.updateAuthConfig({token:recoveredTokens.access_token,userId:void 0,expiresAt:Math.floor(Date.now()/1e3)+recoveredTokens.expires_in,refreshToken:recoveredTokens.refresh_token}),this.persistAuthConfig();return}}if(tokensError){output_manager_default.debug("Error refreshing token, emptying auth config."),this.emptyAuthConfig(),this.persistAuthConfig();return}this.updateAuthConfig({token:tokens.access_token,expiresAt:Math.floor(Date.now()/1e3)+tokens.expires_in}),tokens.refresh_token&&this.updateAuthConfig({refreshToken:tokens.refresh_token}),this.persistAuthConfig(),this.writeToConfigFile(),output_manager_default.debug("Tokens refreshed successfully.")}getGlobalPathConfig(){let confFlag=this.getParsedArgs().flags["--global-config"];return typeof confFlag=="string"?resolve5(this.cwd,confFlag):(0,import_cli_config.getGlobalPathConfig)()}async readConfig(fileName,schema){let filePath=join4(this.getGlobalPathConfig(),fileName);return(0,import_cli_config.readConfigFile)(filePath,schema)}async maybeReadConfig(fileName,schema){try{return await this.readConfig(fileName,schema)}catch{return null}}async writeConfig(fileName,schema,value){let filePath=join4(this.getGlobalPathConfig(),fileName);(0,import_cli_config.writeConfigFile)(filePath,schema,value)}updateConfig(config2){this.config={...this.config,...config2},"currentTeam"in config2&&(this.savedTeam=config2.currentTeam)}writeToConfigFile(config2=this.config){writeToConfigFile(this.ignoresSavedTeam?{...config2,currentTeam:this.savedTeam}:config2)}isTeamUnchosen(){return this.ignoresSavedTeam&&this.config.currentTeam===TEAM_NOT_CHOSEN}needsTeamChoice(url,opts){return this.isTeamUnchosen()&&!opts.teamOptional&&!opts.accountId&&opts.useCurrentTeam!==!1&&!new URL2(url,this.apiUrl).searchParams.has("teamId")}chooseTeam({ask=!0}={}){return ask?(this.teamChoice??=this.applyTeamChoice(!0).finally(()=>{this.teamChoice=void 0}),this.teamChoice):this.applyTeamChoice(!1)}async applyTeamChoice(ask){let{resolveAgentTeam}=await import("./resolve-agent-team-EIPCH766.js"),team=await resolveAgentTeam(this,{ask});team!==null&&this.isTeamUnchosen()&&(this.config.currentTeam=team)}async resolveCurrentTeam({ask=!0}={}){return this.isTeamUnchosen()&&await this.chooseTeam({ask}),this.isTeamUnchosen()?void 0:this.config.currentTeam}updateAuthConfig(authConfig){authConfig.token&&authConfig.token!==this.authConfig.token&&(this.user=void 0,this.userPromise=void 0,this.teams=void 0,this.teamsPromise=void 0),this.authConfig={...this.authConfig,...authConfig}}emptyAuthConfig(){this.user=void 0,this.userPromise=void 0,this.teams=void 0,this.teamsPromise=void 0,this.authConfig=this.authConfig.skipWrite?{skipWrite:!0}:{}}persistAuthConfig(){persistAuthConfig(this.authConfig,this.config)}async confirmMutatingOperation(url,method){if(!((method||"GET").toUpperCase()==="DELETE"))return!0;if(this.isAgent&&this.dangerouslySkipPermissions){let agentInfo=this.agentName?` (${this.agentName})`:"";output_manager_default.print(`
|
|
21
21
|
`),output_manager_default.print((0,import_chalk3.bgRed)((0,import_chalk3.white)((0,import_chalk3.bold)(" \u26A0 WARNING ")))+(0,import_chalk3.red)((0,import_chalk3.bold)(` AGENT MODE - DELETE CONFIRMATION BYPASSED
|
|
22
22
|
`))),output_manager_default.print((0,import_chalk3.yellow)(` An AI agent${agentInfo} is executing a ${(0,import_chalk3.bold)("DELETE")} request with --dangerously-skip-permissions flag.
|
|
23
23
|
`)),output_manager_default.print((0,import_chalk3.yellow)(` This operation will delete data: ${(0,import_chalk3.bold)(url)}
|
|
@@ -29,14 +29,14 @@ ${error.stack}`)};this.setArgv(opts.argv),this.apiUrl=opts.apiUrl,this.authConfi
|
|
|
29
29
|
Are you sure you want to proceed?`;output_manager_default.print(`
|
|
30
30
|
`);let confirmed=await this.input.confirm(message,!1);return output_manager_default.print(`
|
|
31
31
|
`),confirmed||output_manager_default.log("Operation canceled by user."),confirmed}async _fetch(_url,opts={}){let url=new URL2(_url,this.apiUrl);(opts.accountId||opts.useCurrentTeam!==!1)&&(opts.accountId?opts.accountId.startsWith("team_")?url.searchParams.set("teamId",opts.accountId):url.searchParams.delete("teamId"):opts.useCurrentTeam!==!1&&this.config.currentTeam&&!url.searchParams.has("teamId")&&url.searchParams.set("teamId",this.config.currentTeam));let headers=new globalThis.Headers(opts.headers);headers.set("user-agent",ua_default),DOMAINS_API_PATH.test(url.pathname)&&headers.set("x-vercel-cli-version",pkg_default.version),this.agentName&&headers.set("x-ai-agent",this.agentName),headers.set("x-vercel-cli-session-id",this.telemetryEventStore.currentSessionId),headers.set("x-vercel-cli-invocation-id",this.telemetryEventStore.currentInvocationId),await this.ensureAuthorized(),this.authConfig.token&&headers.set("authorization",`Bearer ${this.authConfig.token}`);let body;isJSONObject(opts.body)?(body=JSON.stringify(opts.body),headers.set("content-type","application/json; charset=utf-8")):body=opts.body;let requestId=this.requestIdCounter++;return output_manager_default.time(res=>res?`#${requestId} \u2190 ${res.status} ${res.statusText}: ${res.headers.get("x-vercel-id")}`:`#${requestId} \u2192 ${opts.method||"GET"} ${url.href}`,fetch(url,{...opts,headers,body}))}async fetch(url,opts={}){return this.needsTeamChoice(url,opts)&&await this.chooseTeam(),this.retry(async bail=>{let res;try{res=await this._fetch(url,opts)}catch(err){if(err instanceof Error&&(err.name==="AbortError"||err.name==="TimeoutError"))return bail(err);throw err}if(printIndications(res),!res.ok){if(opts.redirect==="manual"&&res.status>=300&&res.status<400)return res;let error=await responseError(res);if(isSAMLError(error)&&error.teamId)try{await this.reauthenticate(error)}catch(reauthError){return bail((0,import_error_utils3.normalizeError)(reauthError))}else{if(res.status===429&&opts.bailOn429)return bail(error);if(typeof error.retryAfterMs=="number"){if(opts.retry?.retries===0)return bail(error);let randomSkewMs=3e4*Math.random();await sleep(error.retryAfterMs+randomSkewMs)}else if(res.status>=400&&res.status<500)return bail(error)}throw error}if(opts.json===!1)return res;let contentType=res.headers.get("content-type");return contentType?contentType.includes("application/json")?res.json():res:null},opts.retry)}async*fetchPaginated(url,opts){let endpoint=typeof url=="string"?new URL2(url,this.apiUrl):new URL2(url.href);endpoint.searchParams.has("limit")||endpoint.searchParams.set("limit","100");let next;do{next&&(await sleep(100),endpoint.searchParams.set("until",String(next)));let res=await this.fetch(endpoint.href,opts);yield res,next=res.pagination?.next}while(next)}get cwd(){return process.cwd()}set cwd(v){process.chdir(v)}};function getCachedUsername(authConfig){let{cachedUser,userId}=authConfig;if(!(!cachedUser||cachedUser.id!==userId)&&!(!isValidAccessToken(authConfig)&&!hasRefreshToken(authConfig)))return cachedUser.username}async function getUser(client){return client.user?client.user:(client.userPromise||(client.userPromise=fetchUser(client).finally(()=>{client.userPromise=void 0})),client.userPromise)}async function fetchUser(client){try{let res=await client.fetch("/v2/user",{useCurrentTeam:!1});if(!res.user)throw new MissingUser;let{userId,cachedUser}=client.authConfig;if(userId!==res.user.id||cachedUser?.id!==res.user.id||cachedUser.username!==res.user.username){client.updateAuthConfig({userId:res.user.id,cachedUser:{id:res.user.id,username:res.user.username}});try{client.persistAuthConfig()}catch{output_manager_default.debug("Failed to persist cached userId to auth config.")}}return client.telemetryEventStore.updateUserId(res.user.id),client.user=res.user,res.user}catch(error){if(error instanceof APIError&&error.status===403){if(client.user=void 0,client.userPromise=void 0,client.authConfig.userId||client.authConfig.cachedUser){client.updateAuthConfig({userId:void 0,cachedUser:void 0});try{client.persistAuthConfig()}catch{output_manager_default.debug("Failed to persist cached userId to auth config.")}}throw new InvalidToken(client.authConfig.tokenSource)}throw error}}async function getOrgById(client,orgId){if(orgId.startsWith("team_"))try{let team=await getTeamByIdOrSlug(client,orgId,{useCurrentTeam:!1});return team?{type:"team",id:team.id,slug:team.slug}:null}catch(err){if(isAPIError(err)&&(err.status===404||err.code==="not_found"||err.code==="mock_unimplemented"))return null;throw err}let user=await getUser(client);return user.id!==orgId?null:{type:"user",id:orgId,slug:user.username}}var import_build_utils2=__toESM(require_build_utils(),1);var import_error_utils4=__toESM(require_dist(),1);var import_chalk4=__toESM(require_source(),1),import_pluralize=__toESM(require_pluralize(),1),import_build_utils=__toESM(require_build_utils(),1),import_fs_extra2=__toESM(require_lib2(),1);import{homedir as homedir2}from"os";import{basename as basename2,join as join5}from"path";var home=homedir2();async function getRepoLink(client,cwd){let rootPath=await findRepoRoot(cwd);if(!rootPath)return;let repoConfigPath=join5(rootPath,VERCEL_DIR,VERCEL_DIR_REPO),repoConfig=await(0,import_fs_extra2.readJSON)(repoConfigPath).catch(err=>{if(err.code!=="ENOENT")throw err});return{rootPath,repoConfig,repoConfigPath}}async function resolveGitRemote(client,rootPath,{yes,existingRemoteName}){let gitConfigPath=getGitConfigPath({cwd:rootPath})??join5(rootPath,".git/config"),remoteUrls=await getRemoteUrls(gitConfigPath);if(!remoteUrls)return;let remoteName;if(existingRemoteName){if(remoteName=existingRemoteName,!remoteUrls[remoteName])throw new Error(`Git remote "${remoteName}" from repo.json no longer exists`)}else remoteName=await selectGitRemote(client,Object.keys(remoteUrls),yes);return{rootPath,remoteName,repoUrl:remoteUrls[remoteName]}}async function selectGitRemote(client,names,yes=!1){let remoteNames=[...names].sort(),defaultRemote=remoteNames.includes("origin")?"origin":remoteNames[0];return remoteNames.length===1||yes?defaultRemote:client.input.select({message:"Which Git remote should be used?",choices:remoteNames.map(name=>({name,value:name})),default:defaultRemote})}async function fetchProjectsForRepoUrl(client,repoUrl,orgId){let query=new URLSearchParams({repoUrl}),projectsIterator=client.fetchPaginated(`/v9/projects?${query}`,{accountId:orgId}),projects=[];for await(let chunk of projectsIterator)projects=projects.concat(chunk.projects);return projects}async function linkRepoProject(client,cwd,{project,orgId,orgSlug,remoteName,successEmoji="link"}){let repoLink=await getRepoLink(client,cwd);if(!repoLink)throw new Error("Could not determine Git repository root directory");let directory=(0,import_build_utils.normalizePath)(project.rootDirectory||"."),projectConfig={id:project.id,name:project.name,directory,orgId},filteredProjects=(repoLink.repoConfig?.projects??[]).filter(p=>p.id!==project.id&&(0,import_build_utils.normalizePath)(p.directory)!==directory),repoConfig={remoteName,projects:[...filteredProjects,projectConfig]};return await(0,import_fs_extra2.outputJSON)(repoLink.repoConfigPath,repoConfig,{spaces:2}),await writeReadme(repoLink.rootPath),await addToGitIgnore(repoLink.rootPath),output_manager_default.print(`
|
|
32
|
-
`),printAlignedLabel("Linked",`${orgSlug}/${project.name}`,{gutter:"\u2713"}),{repoConfig,repoConfigPath:repoLink.repoConfigPath,rootPath:repoLink.rootPath}}async function discoverRepoProjects(client,rootPath,{yes,existingProjectIds,existingDirectories,existingRemoteName}){let{Separator}=await import("./esm-BYG5BWYH.js"),{default:slugify}=await import("./slugify-NMMUASYK.js"),{default:selectOrg}=await import("./select-org-
|
|
32
|
+
`),printAlignedLabel("Linked",`${orgSlug}/${project.name}`,{gutter:"\u2713"}),{repoConfig,repoConfigPath:repoLink.repoConfigPath,rootPath:repoLink.rootPath}}async function discoverRepoProjects(client,rootPath,{yes,existingProjectIds,existingDirectories,existingRemoteName}){let{Separator}=await import("./esm-BYG5BWYH.js"),{default:slugify}=await import("./slugify-NMMUASYK.js"),{default:selectOrg}=await import("./select-org-WMB752Z6.js"),{default:createProject}=await import("./create-project-IKCB6MB2.js"),{repoInfoToUrl}=await import("./repo-info-to-url-XQSULSEO.js"),{connectGitProvider,parseRepoUrl}=await import("./connect-git-provider-FS5Q2HO4.js"),detectedProjectsPromise=import("./detect-projects-OD4JEAW2.js").then(({detectProjects})=>detectProjects(rootPath)).catch(err=>(output_manager_default.debug(`Failed to detect local projects: ${err}`),new Map)),confirmMessage=(existingRemoteName?"add":"link")==="add"?`Add Project(s) for Git repository at ${import_chalk4.default.dim(`"${humanizePath(rootPath)}"`)}?`:`Link Git repository at ${import_chalk4.default.dim(`"${humanizePath(rootPath)}"`)} to your Project(s)?`;if(!(yes||await client.input.confirm(confirmMessage,!0))){output_manager_default.print(` Canceled. Repository not linked.
|
|
33
33
|
`);return}let org=await selectOrg(client,"Which team?",yes);client.config.currentTeam=org.type==="team"?org.id:void 0;let remote=await resolveGitRemote(client,rootPath,{yes,existingRemoteName});if(!remote)throw new Error("Could not determine Git remote URLs");let{remoteName,repoUrl}=remote,parsedRepoUrl=parseRepoUrl(repoUrl);if(!parsedRepoUrl)throw new Error(`Failed to parse Git URL: ${repoUrl}`);let repoUrlLink=output_manager_default.link(repoUrl,repoInfoToUrl(parsedRepoUrl),{fallback:()=>link_default(repoUrl)});output_manager_default.spinner(`Fetching Projects for ${repoUrlLink} under ${import_chalk4.default.bold(org.slug)}\u2026`);let detectedProjects=await detectedProjectsPromise,projects=await fetchProjectsForRepoUrl(client,repoUrl,org.id);(existingProjectIds||existingDirectories)&&(projects=projects.filter(p=>!(existingProjectIds?.has(p.id)||existingDirectories?.has((0,import_build_utils.normalizePath)(p.rootDirectory||"."))))),projects.length===0?output_manager_default.print(` No Projects are linked to ${repoUrlLink} under ${import_chalk4.default.bold(org.slug)}.
|
|
34
34
|
`):output_manager_default.print(` Found ${(0,import_pluralize.default)("Project",projects.length,!0)} linked to ${repoUrlLink} under ${import_chalk4.default.bold(org.slug)}
|
|
35
35
|
`);for(let project of projects)detectedProjects.delete(project.rootDirectory??"");if(existingDirectories)for(let dir of existingDirectories)detectedProjects.delete(dir==="."?"":dir);let detectedProjectsCount=Array.from(detectedProjects.values()).reduce((o,f)=>o+f.length,0);detectedProjectsCount>0&&output_manager_default.print(` Detected ${(0,import_pluralize.default)("new Project",detectedProjectsCount,!0)} that may be created.
|
|
36
36
|
`);let selected;if(yes)selected=projects;else{let addSeparators=projects.length>0&&detectedProjectsCount>0;selected=await client.input.checkbox({message:`Which Projects should be ${projects.length?"linked to":"created"}?`,choices:[...addSeparators?[new Separator("----- Existing Projects -----")]:[],...projects.map(project=>{let dir=project.rootDirectory||".";return{name:`${org.slug}/${project.name} ${import_chalk4.default.gray(`(${dir})`)}`,value:project,checked:!0}}),...addSeparators?[new Separator("----- New Projects to be created -----")]:[],...Array.from(detectedProjects.entries()).flatMap(([rootDirectory,frameworks])=>frameworks.map((framework,i)=>{let name=slugify([basename2(rootDirectory)||basename2(rootPath),i>0?framework.slug:""].filter(Boolean).join("-"));return{name:`${org.slug}/${name} ${import_chalk4.default.gray(`(${rootDirectory||"."} \xB7 ${framework.name})`)}`,value:{newProject:!0,rootDirectory,name,framework},checked:projects.length===0}}))]})}if(selected.length===0){output_manager_default.print(` No Projects were selected. Repository not linked.
|
|
37
37
|
`);return}for(let i=0;i<selected.length;i++){let selection=selected[i];if(!("newProject"in selection&&selection.newProject))continue;let orgAndName=`${org.slug}/${selection.name}`;output_manager_default.spinner(`Creating new Project: ${orgAndName}`),delete selection.newProject,selection.rootDirectory||delete selection.rootDirectory;let project=selected[i]=await createProject(client,{...selection,framework:selection.framework.slug});await connectGitProvider(client,project.id,parsedRepoUrl.provider,`${parsedRepoUrl.org}/${parsedRepoUrl.repo}`),output_manager_default.print(` Created new Project: ${output_manager_default.link(orgAndName,`https://vercel.com/${orgAndName}`,{fallback:!1})}
|
|
38
38
|
`)}let repoProjects=selected.map(project=>{if(!("id"in project))throw new TypeError(`Not a Project: ${JSON.stringify(project)}`);return{id:project.id,name:project.name,directory:(0,import_build_utils.normalizePath)(project.rootDirectory||"."),orgId:org.id}});return{remoteName,projects:repoProjects,orgSlug:org.slug}}async function ensureRepoLink(client,cwd,{yes,overwrite}){let repoLink=await getRepoLink(client,cwd);if(repoLink)output_manager_default.debug(`Found Git repository root directory: ${repoLink.rootPath}`);else throw new Error("Could not determine Git repository root directory");let{rootPath,repoConfig,repoConfigPath}=repoLink;if(overwrite||!repoConfig){let result=await discoverRepoProjects(client,rootPath,{yes});if(!result)return;repoConfig={remoteName:result.remoteName,projects:result.projects},await(0,import_fs_extra2.outputJSON)(repoConfigPath,repoConfig,{spaces:2}),await writeReadme(rootPath),await addToGitIgnore(rootPath),printAlignedLabel("Linked",`${(0,import_pluralize.default)("Project",result.projects.length,!0)} under ${result.orgSlug}`,{gutter:"\u2713"})}return{repoConfig,repoConfigPath,rootPath}}async function addRepoLink(client,cwd,{yes}){let repoLink=await getRepoLink(client,cwd);if(!repoLink)throw new Error("Could not determine Git repository root directory");let{rootPath,repoConfig,repoConfigPath}=repoLink;if(!repoConfig)throw new Error("No existing repository link found. Run `vc link --repo` first to link the repository.");output_manager_default.debug(`Found Git repository root directory: ${rootPath}`);let existingProjectIds=new Set(repoConfig.projects.map(p=>p.id)),existingDirectories=new Set(repoConfig.projects.map(p=>p.directory)),result=await discoverRepoProjects(client,rootPath,{yes,existingProjectIds,existingDirectories,existingRemoteName:repoConfig.remoteName});if(!result)return;if(result.projects.length===0)return output_manager_default.print(` No new Projects were added.
|
|
39
|
-
`),{repoConfig,repoConfigPath,rootPath};let mergedProjects=[...repoConfig.projects];for(let project of result.projects)existingProjectIds.has(project.id)||mergedProjects.push(project);let updatedConfig={...repoConfig,projects:mergedProjects};return await(0,import_fs_extra2.outputJSON)(repoConfigPath,updatedConfig,{spaces:2}),printAlignedLabel("Added",`${(0,import_pluralize.default)("Project",result.projects.length,!0)} under ${result.orgSlug}`,{gutter:"\u2713"}),{repoConfig:updatedConfig,repoConfigPath,rootPath}}async function findRepoRoot(start){let{debug}=output_manager_default,REPO_JSON_PATH=join5(VERCEL_DIR,VERCEL_DIR_REPO);for(let current of(0,import_build_utils.traverseUpDirectories)({start})){if(current===home){debug("Arrived at home directory");break}let repoConfigPath=join5(current,REPO_JSON_PATH);if(await(0,import_fs_extra2.lstat)(repoConfigPath).catch(err=>{if(err.code!=="ENOENT")throw err}))return debug(`Found "${REPO_JSON_PATH}" - detected "${current}" as repo root`),current}let gitRoot=getGitRootDirectory({cwd:start});if(gitRoot)return debug(`Found git root via "git rev-parse --show-toplevel" - detected "${gitRoot}" as repo root`),gitRoot;for(let current of(0,import_build_utils.traverseUpDirectories)({start})){if(current===home){debug("Arrived at home directory");break}let gitPath=join5(current,".git");if(await(0,import_fs_extra2.lstat)(gitPath).catch(err=>{if(err.code!=="ENOENT")throw err}))return debug(`Found ".git" - detected "${current}" as repo root`),current}debug("Aborting search for repo root")}function sortByDirectory(a,b){let aParts=a.directory.split("/");return b.directory.split("/").length-aParts.length}function findProjectsFromPath(projects,path2){let normalizedPath=(0,import_build_utils.normalizePath)(path2),matches=projects.slice().sort(sortByDirectory).filter(project=>project.directory==="."?!0:normalizedPath===project.directory||normalizedPath.startsWith(`${project.directory}/`)),firstMatch=matches[0];return firstMatch?matches.filter(match=>match.directory===firstMatch.directory):[]}var import_chalk5=__toESM(require_source(),1),import_fs_extra3=__toESM(require_lib2(),1);import{stat}from"fs/promises";import{join as join6,dirname as dirname2}from"path";async function findProjectRoot(startDir){let cwdDev;try{cwdDev=(await stat(startDir)).dev}catch{return null}let dir=dirname2(startDir);for(;dirname2(dir)!==dir;){try{if((await stat(dir)).dev!==cwdDev)return null}catch{return null}let hasVercelDir=await(0,import_fs_extra3.pathExists)(join6(dir,".vercel")),hasVercelJson=await(0,import_fs_extra3.pathExists)(join6(dir,"vercel.json")),hasVercelToml=await(0,import_fs_extra3.pathExists)(join6(dir,"vercel.toml")),hasGit=await(0,import_fs_extra3.pathExists)(join6(dir,".git"));if(hasVercelDir||hasVercelJson||hasVercelToml||hasGit)return dir;dir=dirname2(dir)}return null}async function resolveProjectCwd(cwd){let projectRoot=await findProjectRoot(cwd);if(!projectRoot||projectRoot===cwd)return cwd;let{isExperimentalServicesEnabled,tryDetectServices}=await import("./detect-services-
|
|
39
|
+
`),{repoConfig,repoConfigPath,rootPath};let mergedProjects=[...repoConfig.projects];for(let project of result.projects)existingProjectIds.has(project.id)||mergedProjects.push(project);let updatedConfig={...repoConfig,projects:mergedProjects};return await(0,import_fs_extra2.outputJSON)(repoConfigPath,updatedConfig,{spaces:2}),printAlignedLabel("Added",`${(0,import_pluralize.default)("Project",result.projects.length,!0)} under ${result.orgSlug}`,{gutter:"\u2713"}),{repoConfig:updatedConfig,repoConfigPath,rootPath}}async function findRepoRoot(start){let{debug}=output_manager_default,REPO_JSON_PATH=join5(VERCEL_DIR,VERCEL_DIR_REPO);for(let current of(0,import_build_utils.traverseUpDirectories)({start})){if(current===home){debug("Arrived at home directory");break}let repoConfigPath=join5(current,REPO_JSON_PATH);if(await(0,import_fs_extra2.lstat)(repoConfigPath).catch(err=>{if(err.code!=="ENOENT")throw err}))return debug(`Found "${REPO_JSON_PATH}" - detected "${current}" as repo root`),current}let gitRoot=getGitRootDirectory({cwd:start});if(gitRoot)return debug(`Found git root via "git rev-parse --show-toplevel" - detected "${gitRoot}" as repo root`),gitRoot;for(let current of(0,import_build_utils.traverseUpDirectories)({start})){if(current===home){debug("Arrived at home directory");break}let gitPath=join5(current,".git");if(await(0,import_fs_extra2.lstat)(gitPath).catch(err=>{if(err.code!=="ENOENT")throw err}))return debug(`Found ".git" - detected "${current}" as repo root`),current}debug("Aborting search for repo root")}function sortByDirectory(a,b){let aParts=a.directory.split("/");return b.directory.split("/").length-aParts.length}function findProjectsFromPath(projects,path2){let normalizedPath=(0,import_build_utils.normalizePath)(path2),matches=projects.slice().sort(sortByDirectory).filter(project=>project.directory==="."?!0:normalizedPath===project.directory||normalizedPath.startsWith(`${project.directory}/`)),firstMatch=matches[0];return firstMatch?matches.filter(match=>match.directory===firstMatch.directory):[]}var import_chalk5=__toESM(require_source(),1),import_fs_extra3=__toESM(require_lib2(),1);import{stat}from"fs/promises";import{join as join6,dirname as dirname2}from"path";async function findProjectRoot(startDir){let cwdDev;try{cwdDev=(await stat(startDir)).dev}catch{return null}let dir=dirname2(startDir);for(;dirname2(dir)!==dir;){try{if((await stat(dir)).dev!==cwdDev)return null}catch{return null}let hasVercelDir=await(0,import_fs_extra3.pathExists)(join6(dir,".vercel")),hasVercelJson=await(0,import_fs_extra3.pathExists)(join6(dir,"vercel.json")),hasVercelToml=await(0,import_fs_extra3.pathExists)(join6(dir,"vercel.toml")),hasGit=await(0,import_fs_extra3.pathExists)(join6(dir,".git"));if(hasVercelDir||hasVercelJson||hasVercelToml||hasGit)return dir;dir=dirname2(dir)}return null}async function resolveProjectCwd(cwd){let projectRoot=await findProjectRoot(cwd);if(!projectRoot||projectRoot===cwd)return cwd;let{isExperimentalServicesEnabled,tryDetectServices}=await import("./detect-services-BSJGB4RM.js");if(!await isExperimentalServicesEnabled(projectRoot))return cwd;let result=await tryDetectServices(projectRoot);return result&&(result.services?.length??0)>0?(output_manager_default.debug(`Running from project root: ${import_chalk5.default.cyan(projectRoot)}`),projectRoot):cwd}var readFile=promisify(fs3.readFile),writeFile=promisify(fs3.writeFile),VERCEL_DIR=".vercel",VERCEL_DIR_FALLBACK=".now",VERCEL_DIR_README="README.txt",VERCEL_DIR_PROJECT="project.json",VERCEL_DIR_REPO="repo.json";function isOwnerLookupUnavailableLink(link){return"ownerLookupUnavailable"in link&&link.ownerLookupUnavailable===!0}function isRemoteLookupSkippedLink(link){return"remoteLookupSkipped"in link&&link.remoteLookupSkipped===!0}function isOwnerLookupUnavailableError(error){return isAPIError(error)&&error.status===403&&error.code==="team_unauthorized"}function isValidProjectLink(value){if(!value||typeof value!="object"||Array.isArray(value))return!1;let link=value;return typeof link.projectId=="string"&&link.projectId.length>0&&typeof link.orgId=="string"&&link.orgId.length>0&&(link.projectName===void 0||typeof link.projectName=="string"&&link.projectName.length>0)}function getVercelDirectory(cwd){let possibleDirs=[join7(cwd,VERCEL_DIR),join7(cwd,VERCEL_DIR_FALLBACK)],existingDirs=possibleDirs.filter(d=>isDirectory(d));if(existingDirs.length>1)throw new import_build_utils2.NowBuildError({code:"CONFLICTING_CONFIG_DIRECTORIES",message:"Both `.vercel` and `.now` directories exist. Please remove the `.now` directory.",link:"https://vercel.link/combining-old-and-new-config"});return existingDirs[0]||possibleDirs[0]}async function getProjectLink(client,path2,projectName,projectNameIsExplicit){let dirLink=await getLinkFromDir(getVercelDirectory(path2));return dirLink&&(!projectNameIsExplicit||!projectName||dirLink.projectId===projectName||dirLink.projectName===projectName)?dirLink:await getProjectLinkFromRepoLink(client,path2,projectName,projectNameIsExplicit)}async function getProjectLinkFromRepoLink(client,path2,projectName,projectNameIsExplicit){let repoLink=await getRepoLink(client,path2);if(!repoLink?.repoConfig)return null;let projects=findProjectsFromPath(repoLink.repoConfig.projects,relative2(repoLink.rootPath,path2)),project;if(projectName&&projectNameIsExplicit)project=repoLink.repoConfig.projects.find(p=>p.id===projectName||p.name===projectName);else if(projects.length===1)project=projects[0];else{let selectableProjects=projects.length>0?projects:repoLink.repoConfig.projects;if(projectName&&(project=selectableProjects.find(p=>p.id===projectName||p.name===projectName)),!project)if(client.nonInteractive)if(selectableProjects.length===1)project=selectableProjects[0];else return null;else project=await client.input.select({message:"Please select a Project:",choices:selectableProjects.map(p=>({value:p,name:p.name}))})}if(project){let orgId=project.orgId??repoLink.repoConfig.orgId;if(!orgId){let projectInfo=[project.name?`name: "${project.name}"`:"",project.directory?`directory: "${project.directory}"`:""].filter(Boolean).join(", "),details=projectInfo?` Project: { ${projectInfo} }.`:"";throw new Error(`Could not determine org ID from repo.json config at "${repoLink.repoConfigPath}".${details} Please re-link the repository.`)}return{repoRoot:repoLink.rootPath,orgId,projectId:project.id,projectName:project.name,projectRootDirectory:project.directory}}return null}function getLinkedProjectIdSync(dir){try{let link=JSON.parse(fs3.readFileSync(join7(dir,VERCEL_DIR_PROJECT),"utf8"));return isValidProjectLink(link)?link.projectId:void 0}catch{return}}async function getLinkFromDir(dir){try{let json=await readFile(join7(dir,VERCEL_DIR_PROJECT),"utf8"),link=JSON.parse(json);if(!isValidProjectLink(link)){let raw=link,projectId=raw.projectId,orgId=raw.orgId;if(!(typeof projectId=="string"&&projectId.length>0&&typeof orgId=="string"&&orgId.length>0))return null;throw new Error(`Project Settings are invalid. To link your project again, remove the ${dir} directory.`)}return link}catch(err){if((0,import_error_utils4.isErrnoException)(err)&&err.code&&["ENOENT","ENOTDIR"].includes(err.code))return null;throw(0,import_error_utils4.isError)(err)&&err.name==="SyntaxError"?new Error(`Project Settings could not be retrieved. To link your project again, remove the ${dir} directory.`):err}}async function hasLocalProjectLink(client,cwd){try{if(await getLinkFromDir(getVercelDirectory(cwd)))return!0}catch{}try{let repoLink=await getRepoLink(client,cwd);return repoLink?.repoConfig?findProjectsFromPath(repoLink.repoConfig.projects,relative2(repoLink.rootPath,cwd)).length>0:!1}catch{return!1}}async function hasProjectLink(client,projectLink,path2){let VERCEL_ORG_ID=(0,import_build_utils2.getPlatformEnv)("ORG_ID"),VERCEL_PROJECT_ID=(0,import_build_utils2.getPlatformEnv)("PROJECT_ID");if(VERCEL_ORG_ID===projectLink.orgId&&VERCEL_PROJECT_ID===projectLink.projectId)return!0;let repoLink=await getRepoLink(client,path2);if(repoLink?.repoConfig){let matchingProject=repoLink.repoConfig.projects.find(p=>p.id===projectLink.projectId);if(matchingProject){let orgId=matchingProject.orgId??repoLink.repoConfig.orgId;if(!orgId)throw new Error(`Invalid "repo.json": missing "orgId" for project "${matchingProject.id}" and no top-level "orgId" is defined.`);if(orgId===projectLink.orgId)return!0}}let link=await getLinkFromDir(getVercelDirectory(path2));return!!(link&&link.orgId===projectLink.orgId&&link.projectId===projectLink.projectId)}async function getLinkedProject(client,options={}){let path2=options.cwd??client.cwd;options.skipProjectRootResolution||(path2=await resolveProjectCwd(path2));let VERCEL_ORG_ID=(0,import_build_utils2.getPlatformEnv)("ORG_ID"),VERCEL_PROJECT_ID=(0,import_build_utils2.getPlatformEnv)("PROJECT_ID"),shouldUseEnv=!!(VERCEL_ORG_ID&&VERCEL_PROJECT_ID),projectName=options.projectName,projectNameIsExplicit=options.projectNameIsExplicit===!0,explicitProjectName=projectNameIsExplicit?projectName:void 0,hasExplicitProject=!!explicitProjectName,shouldUseEnvContext=shouldUseEnv&&!hasExplicitProject;if(!hasExplicitProject&&(VERCEL_ORG_ID||VERCEL_PROJECT_ID)&&!shouldUseEnv)return options.quiet||output_manager_default.error(`You specified ${VERCEL_ORG_ID?"`VERCEL_ORG_ID`":"`VERCEL_PROJECT_ID`"} but you forgot to specify ${VERCEL_ORG_ID?"`VERCEL_PROJECT_ID`":"`VERCEL_ORG_ID`"}. You need to specify both to deploy to a custom project.
|
|
40
40
|
`),{status:"error",exitCode:1};let link,explicitlyResolvedProject=null,orgId;if(explicitProjectName){let hasExplicitScope=options.scopeIsExplicit===!0,matchingLocalLink=hasExplicitScope||shouldUseEnv?null:await getProjectLink(client,path2,explicitProjectName,!0),fallbackOrgId=shouldUseEnv?VERCEL_ORG_ID:matchingLocalLink?.orgId??client.config.currentTeam,lookupOrgId=hasExplicitScope?client.config.currentTeam:fallbackOrgId;orgId=lookupOrgId;let apiProject=await getProjectByNameOrId(client,explicitProjectName,lookupOrgId);if(explicitlyResolvedProject=apiProject instanceof ProjectNotFound?null:apiProject,explicitlyResolvedProject===null)link=null;else{let resolvedOrgId=explicitlyResolvedProject.accountId??lookupOrgId??matchingLocalLink?.orgId,localLink=matchingLocalLink?.projectId===explicitlyResolvedProject.id?matchingLocalLink:null;if(!localLink)try{localLink=await getProjectLink(client,path2,explicitlyResolvedProject.id,!0)}catch(err){output_manager_default.debug(`Ignoring local project metadata after explicit project resolution: ${err}`)}link=resolvedOrgId?{...localLink?.projectId===explicitlyResolvedProject.id&&localLink.orgId===resolvedOrgId?localLink:{},projectId:explicitlyResolvedProject.id,orgId:resolvedOrgId}:null}}else link=shouldUseEnvContext?{orgId:VERCEL_ORG_ID,projectId:VERCEL_PROJECT_ID}:await getProjectLink(client,path2,projectName,projectNameIsExplicit),link&&(orgId=link.orgId);if(!link)return{status:"not_linked",org:null,project:null,orgId};if(options.skipRemoteLookup&&link.projectName){let settings=link.settings,localRootDirectory=link.projectRootDirectory??settings?.rootDirectory??null,rootDirectory=localRootDirectory==="."?null:localRootDirectory,project2={...settings,id:link.projectId,accountId:link.orgId,name:link.projectName,createdAt:settings?.createdAt??0,updatedAt:settings?.updatedAt??settings?.createdAt??0,rootDirectory};return{...{status:"linked",org:{type:link.orgId.startsWith("team_")?"team":"user",id:link.orgId,slug:""},project:project2,repoRoot:link.repoRoot,remoteLookupSkipped:!0},projectRootDirectory:link.projectRootDirectory,orgId:link.orgId}}options.quiet||output_manager_default.spinner("Retrieving project\u2026",1e3);let org=null,project=null,ownerLookupUnavailable=!1;try{let[orgResult,projectResult]=await Promise.allSettled([options.skipOwnerLookup?Promise.resolve({type:link.orgId.startsWith("team_")?"team":"user",id:link.orgId,slug:""}):getOrgById(client,link.orgId),explicitlyResolvedProject?Promise.resolve(explicitlyResolvedProject):getProjectByNameOrId(client,link.projectId,link.orgId)]);if(orgResult.status==="fulfilled")org=orgResult.value;else if(isAPIError(orgResult.reason)&&(orgResult.reason.status===404||orgResult.reason.code==="not_found"||orgResult.reason.code==="mock_unimplemented"))org=null;else if(options.allowOwnerLookupFallback&&isOwnerLookupUnavailableError(orgResult.reason))ownerLookupUnavailable=!0;else throw orgResult.reason;if(projectResult.status==="fulfilled")project=projectResult.value;else if(isAPIError(projectResult.reason)&&(projectResult.reason.status===404||projectResult.reason.code==="not_found"||projectResult.reason.code==="mock_unimplemented"))project=new ProjectNotFound(link.projectId);else throw projectResult.reason}catch(err){if(isAPIError(err)&&err.status===403){if(output_manager_default.stopSpinner(),err.missingToken||err.invalidToken)throw new InvalidToken(client.authConfig.tokenSource);if(err.code==="forbidden"||err.code==="team_unauthorized")throw new import_build_utils2.NowBuildError({message:`Could not retrieve Project Settings. To link your Project, remove the ${code(VERCEL_DIR)} directory and deploy again.`,code:"PROJECT_UNAUTHORIZED",link:"https://vercel.link/cannot-load-project-settings"})}throw err}finally{output_manager_default.stopSpinner()}if(ownerLookupUnavailable&&project&&!(project instanceof ProjectNotFound)){let ownerId=project.accountId||link.orgId;return{status:"linked",org:{type:ownerId.startsWith("team_")?"team":"user",id:ownerId,slug:ownerId},project,repoRoot:link.repoRoot,projectRootDirectory:link.projectRootDirectory,orgId:link.orgId,ownerLookupUnavailable:!0}}return!org||!project||project instanceof ProjectNotFound?shouldUseEnvContext?(options.quiet||output_manager_default.error(`Project not found (${JSON.stringify({VERCEL_PROJECT_ID,VERCEL_ORG_ID})})
|
|
41
41
|
`),{status:"error",exitCode:1,orgId}):(options.quiet||output_manager_default.print(prependEmoji(`Your Project was either deleted, transferred to a new Team, or you don\u2019t have access to it anymore.
|
|
42
42
|
`,emoji("warning"))),{status:"not_linked",org:null,project:null,orgId:link.orgId}):{status:"linked",org,project,repoRoot:link.repoRoot,projectRootDirectory:link.projectRootDirectory,orgId:link.orgId}}var VERCEL_DIR_README_CONTENT=`> Why do I have a folder named ".vercel" in my project?
|
|
@@ -52,6 +52,6 @@ No, you should not share the ".vercel" folder with anyone.
|
|
|
52
52
|
Upon creation, it will be automatically added to your ".gitignore" file.
|
|
53
53
|
`;async function writeReadme(path2){await writeFile(join7(path2,VERCEL_DIR,VERCEL_DIR_README),VERCEL_DIR_README_CONTENT)}async function linkFolderToProject(client,path2,projectLink,projectName,orgSlug,successEmoji="link",autoConfirm=!1,pullEnv=!0,resultLabel="Linked"){if(await hasProjectLink(client,projectLink,path2))return;try{await(0,import_fs_extra4.ensureDir)(join7(path2,VERCEL_DIR))}catch(err){if((0,import_error_utils4.isErrnoException)(err)&&err.code==="ENOTDIR")return;throw err}if(await writeFile(join7(path2,VERCEL_DIR,VERCEL_DIR_PROJECT),JSON.stringify({...projectLink,projectName})),await writeReadme(path2),await addToGitIgnore(path2),output_manager_default.print(`
|
|
54
54
|
`),printAlignedLabel(resultLabel,`${orgSlug}/${projectName}`,{gutter:"\u2713"}),!pullEnv||!client.stdin.isTTY||client.nonInteractive)return;if(output_manager_default.print(`
|
|
55
|
-
`),autoConfirm||await client.input.confirm("Pull development environment variables into .env.local?",!0)){let originalCwd=client.cwd;try{client.cwd=path2;let args=autoConfirm?["--yes"]:[],{default:pull}=await import("./pull-
|
|
55
|
+
`),autoConfirm||await client.input.confirm("Pull development environment variables into .env.local?",!0)){let originalCwd=client.cwd;try{client.cwd=path2;let args=autoConfirm?["--yes"]:[],{default:pull}=await import("./pull-WRTTSY7J.js");await pull(client,args,"vercel-cli:link")!==0&&output_manager_default.error("Failed to pull environment variables. You can run `vc env pull` manually.")}catch{output_manager_default.error("Failed to pull environment variables. You can run `vc env pull` manually.")}finally{client.cwd=originalCwd}}}async function addToGitIgnore(path2,ignore=VERCEL_DIR){let isGitIgnoreUpdated=!1;try{let gitIgnorePath=join8(path2,".gitignore"),gitIgnore=await(0,import_fs_extra5.readFile)(gitIgnorePath,"utf8").catch(()=>null)??"",EOL=gitIgnore.includes(`\r
|
|
56
56
|
`)?`\r
|
|
57
57
|
`:os2.EOL,contentModified=!1;gitIgnore.split(EOL).includes(ignore)||(gitIgnore+=`${gitIgnore.endsWith(EOL)||gitIgnore.length===0?"":EOL}${ignore}${EOL}`,contentModified=!0),contentModified&&(await(0,import_fs_extra5.writeFile)(gitIgnorePath,gitIgnore),isGitIgnoreUpdated=!0)}catch{}return isGitIgnoreUpdated}export{require_lib2 as require_lib,humanizePath,highlight,require_dist2 as require_dist,ua_default,responseError,printIndications,require_types,getProjectByNameOrId,getOrgById,isDirectory,require_pluralize,execFileAsync,getGitExecutable,getGitConfigPath,createGitMeta,parseGitConfig,pluckRemoteUrls,getRemoteUrls,addToGitIgnore,getRepoLink,resolveGitRemote,selectGitRemote,fetchProjectsForRepoUrl,linkRepoProject,ensureRepoLink,addRepoLink,findRepoRoot,findProjectsFromPath,VERCEL_CONFIG_EXTENSIONS,DEFAULT_VERCEL_CONFIG_FILENAME,resolveProjectCwd,deviceAuthorizationRequest,processDeviceAuthorizationResponse,deviceAccessTokenRequest,processTokenResponse,revocationRequest,processRevocationResponse,isOAuthError,inspectTokenRequest,processInspectTokenResponse,isPromptBackError,isPromptCanceledError,VERCEL_DIR,VERCEL_DIR_README,VERCEL_DIR_PROJECT,isOwnerLookupUnavailableLink,isRemoteLookupSkippedLink,getVercelDirectory,getProjectLink,getLinkedProjectIdSync,getLinkFromDir,hasLocalProjectLink,getLinkedProject,linkFolderToProject,localConfigFlagPath,getLocalPathConfig,readConfigFile,writeToConfigFile,readAuthConfigFile,persistAuthConfig,getConfigFilePath2 as getConfigFilePath,getAuthConfigFilePath2 as getAuthConfigFilePath,readLocalConfig,sleep,TEAM_NOT_CHOSEN,isJSONObject,isValidAccessToken,Client,getCachedUsername,getUser};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{permissionsAggregateCommand}from"./chunk-CR3NBTHV.js";import{tagsAggregateCommand}from"./chunk-BVGGTBYE.js";import{imageAggregateCommand}from"./chunk-6TXEVQA4.js";import{formatOption,jsonOption,limitOption,projectOption,yesOption}from"./chunk-QVXS234E.js";import{packageName}from"./chunk-JESNVRVR.js";var projectScopeOption={...projectOption,shorthand:"p",description:"Project name or ID (default: linked project)."},nextOption={name:"next",shorthand:null,type:String,deprecated:!1,description:"Show the next page using the cursor from the previous output",argument:"CURSOR"},cursorOption={name:"cursor",shorthand:"c",type:String,deprecated:!0,description:"Cursor from a previous page to continue listing from",argument:"STRING"},platformOption={name:"platform",shorthand:null,type:String,deprecated:!1,description:"Target platform for the build (default: linux/amd64).",argument:"PLATFORM"},pushOption={name:"push",shorthand:null,type:Boolean,deprecated:!1,description:"Push the image after building. With Docker this builds and pushes in one step (Buildx enables zstd compression); Podman and Buildah build, then push with zstd compression."},publicOption={name:"public",shorthand:null,type:Boolean,deprecated:!1,description:"Make the repository public.",legacyValues:{on:"true",off:"false"}},noPublicOption={name:"no-public",shorthand:null,type:Boolean,deprecated:!1,description:"Make the repository private."},listSubcommand={name:"ls",aliases:["list"],description:"List container registry repositories for a project",arguments:[],options:[projectScopeOption,limitOption,nextOption,cursorOption,formatOption,jsonOption],examples:[{name:"List repositories in the linked project",value:`${packageName} vcr ls`},{name:"List repositories for a specific project as JSON",value:`${packageName} vcr ls --project my-app --json`}]},inspectSubcommand={name:"inspect",aliases:["get"],description:"Show details for a single repository",arguments:[{name:"repository",required:!0}],options:[projectScopeOption,formatOption,jsonOption],examples:[{name:"Inspect a repository by name",value:`${packageName} vcr inspect my-repository`}]},addSubcommand={name:"create",aliases:["add"],description:"Create a container registry repository",arguments:[{name:"name",required:!0}],options:[projectScopeOption,formatOption,jsonOption],examples:[{name:"Create a repository",value:`${packageName} vcr create my-repository`}]},configSubcommand={name:"update",aliases:["config"],description:"Update a container registry repository, such as the repository's visibility",arguments:[{name:"repository",required:!0}],options:[publicOption,noPublicOption,projectScopeOption,formatOption,jsonOption],examples:[{name:"Make a repository public",value:`${packageName} vcr update my-repository --public`},{name:"Make a repository private",value:`${packageName} vcr update my-repository --no-public`}]},removeSubcommand={name:"delete",aliases:["rm","del","remove"],description:"Delete a container registry repository",arguments:[{name:"repository",required:!0}],options:[projectScopeOption,yesOption,formatOption,jsonOption],examples:[{name:"Delete a repository",value:`${packageName} vcr delete my-repository`},{name:"Delete a repository without the confirmation prompt",value:`${packageName} vcr delete my-repository --yes`}]},loginSubcommand={name:"login",aliases:[],description:"Authenticate a container tool (docker, podman, or buildah) with the Vercel Container Registry",arguments:[{name:"engine",required:!0}],options:[projectScopeOption,formatOption,jsonOption],examples:[{name:"Log in with Docker",value:`${packageName} vcr login docker`},{name:"Log in with Podman",value:`${packageName} vcr login podman`},{name:"Log in with Buildah",value:`${packageName} vcr login buildah`},{name:"Log in for a specific project",value:`${packageName} vcr login docker --project my-app`}]},buildSubcommand={name:"build",aliases:[],description:"Build a container image tagged for the Vercel Container Registry by shelling out to your container tool (docker, podman, or buildah)",arguments:[{name:"engine",required:!0},{name:"path",required:!1},{name:"name",required:!1}],options:[projectScopeOption,platformOption,pushOption],examples:[{name:"Build the current directory into the linked project (repository defaults to the project name, tag to latest)",value:`${packageName} vcr build docker`},{name:"Build and push in one step (Docker Buildx enables zstd compression)",value:`${packageName} vcr build docker --push`},{name:"Build a specific context path with a repository and tag",value:`${packageName} vcr build docker ./app my-api:1.2.3`},{name:"Pass extra flags through to the container tool",value:`${packageName} vcr build docker . -- --no-cache --build-arg KEY=value`}]},pushSubcommand={name:"push",aliases:[],description:"Push a container image to the Vercel Container Registry by shelling out to your container tool (docker, podman, or buildah)",arguments:[{name:"engine",required:!0},{name:"name",required:!1}],options:[projectScopeOption],examples:[{name:"Push the linked project image (repository defaults to the project name, tag to latest)",value:`${packageName} vcr push docker`},{name:"Push a specific repository and tag",value:`${packageName} vcr push docker my-api:1.2.3`}]},vcrCommand={name:"vcr",aliases:[],description:"Manage Vercel Container Registry repositories and images (see `vcr image`).",arguments:[],subcommands:[listSubcommand,inspectSubcommand,addSubcommand,configSubcommand,removeSubcommand,loginSubcommand,buildSubcommand,pushSubcommand,tagsAggregateCommand,imageAggregateCommand,permissionsAggregateCommand],options:[],examples:[{name:"List repositories in the linked project",value:`${packageName} vcr ls`},{name:"Create a repository",value:`${packageName} vcr create my-app`},{name:"List images in a repository",value:`${packageName} vcr image ls my-app`}]};export{listSubcommand,inspectSubcommand,addSubcommand,configSubcommand,removeSubcommand,loginSubcommand,buildSubcommand,pushSubcommand,vcrCommand};
|