@vercel/cli-support 68.3.0-snapshot-4bb5562899c1 → 68.3.0-snapshot-24d117b8c08a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/dist/chunks/{add-OVCKUCKJ.js → add-K63YQ4KL.js} +1 -1
  2. package/dist/chunks/{add-WXYF62BV.js → add-U4WWFW6A.js} +1 -1
  3. package/dist/chunks/{add-JGXB7TKO.js → add-UC3PDROQ.js} +1 -1
  4. package/dist/chunks/{alerts-XC3HSFNS.js → alerts-TCS56TZU.js} +1 -1
  5. package/dist/chunks/{build-EOC2F5EB.js → build-62AFJDRZ.js} +1 -1
  6. package/dist/chunks/{chunk-EQQJB7MI.js → chunk-26HAXM56.js} +1 -1
  7. package/dist/chunks/{chunk-HFX56MAE.js → chunk-2A7TTZJ4.js} +1 -1
  8. package/dist/chunks/{chunk-Y3VTP4NX.js → chunk-2I4XYW65.js} +1 -1
  9. package/dist/chunks/{chunk-JOKL5GT4.js → chunk-3RPOSTE4.js} +1 -1
  10. package/dist/chunks/{chunk-LYWMEQRT.js → chunk-4KEWLHYF.js} +1 -1
  11. package/dist/chunks/{chunk-JW522BFH.js → chunk-4U2H6XBH.js} +1 -1
  12. package/dist/chunks/{chunk-QV2PDKZY.js → chunk-55EEFTI7.js} +1 -1
  13. package/dist/chunks/{chunk-B6G3V7C7.js → chunk-5KTOBHJR.js} +1 -1
  14. package/dist/chunks/{chunk-S5IZAQDU.js → chunk-7VFMF2X2.js} +1 -1
  15. package/dist/chunks/{chunk-CZC5QGI5.js → chunk-AHAT5QYP.js} +1 -1
  16. package/dist/chunks/{chunk-OZLK3WML.js → chunk-ALRMGYWE.js} +1 -1
  17. package/dist/chunks/{chunk-JOV747QS.js → chunk-BAHTCIMJ.js} +1 -1
  18. package/dist/chunks/{chunk-LUK3POIP.js → chunk-BVHXBPKR.js} +1 -1
  19. package/dist/chunks/{chunk-62IAZJKT.js → chunk-CEJO447T.js} +1 -1
  20. package/dist/chunks/{chunk-O5SIUXE6.js → chunk-CM2HJYDA.js} +1 -1
  21. package/dist/chunks/{chunk-QUE6QJJL.js → chunk-CMAZDLNJ.js} +1 -1
  22. package/dist/chunks/{chunk-USTT3CON.js → chunk-CYBPBS37.js} +1 -1
  23. package/dist/chunks/{chunk-4IJ6MNTE.js → chunk-DBPL6EVR.js} +2 -2
  24. package/dist/chunks/{chunk-X24LA5TL.js → chunk-DFZRZPCJ.js} +2 -2
  25. package/dist/chunks/{chunk-HPAGXT6E.js → chunk-E7R5SQDA.js} +2 -2
  26. package/dist/chunks/{chunk-MQAI6NJ5.js → chunk-EEH7JGGG.js} +1 -1
  27. package/dist/chunks/{chunk-F5HOZBY3.js → chunk-EYSD2ULB.js} +1 -1
  28. package/dist/chunks/{chunk-VL2DQ4JF.js → chunk-FJPYSIUV.js} +1 -1
  29. package/dist/chunks/{chunk-ZTTGEYEE.js → chunk-GEBGZ3EG.js} +1 -1
  30. package/dist/chunks/{chunk-FSKAAYPW.js → chunk-GGRFONYT.js} +1 -1
  31. package/dist/chunks/{chunk-GTZ6ASHD.js → chunk-H3HSH5FW.js} +1 -1
  32. package/dist/chunks/{chunk-4YGSXM2T.js → chunk-H4BQDKOU.js} +4 -4
  33. package/dist/chunks/{chunk-O45CPVEL.js → chunk-HPYP2LC3.js} +1 -1
  34. package/dist/chunks/{chunk-L52TWK6B.js → chunk-IFSD556O.js} +1 -1
  35. package/dist/chunks/{chunk-JATIYY4H.js → chunk-ILX4D2PP.js} +1 -1
  36. package/dist/chunks/{chunk-VSXHIE2L.js → chunk-J3DYBDSK.js} +1 -1
  37. package/dist/chunks/{chunk-Q4B2ICJM.js → chunk-JJ4DOHP4.js} +1 -1
  38. package/dist/chunks/{chunk-7KWH24QW.js → chunk-JMJ2FVX3.js} +1 -1
  39. package/dist/chunks/{chunk-DKDYIUCY.js → chunk-KVX64ZHU.js} +1 -1
  40. package/dist/chunks/{chunk-LM3VCTGL.js → chunk-M345GUX4.js} +1 -1
  41. package/dist/chunks/{chunk-CYEMSHQ4.js → chunk-MADCVSMW.js} +1 -1
  42. package/dist/chunks/{chunk-ZJNJZSJA.js → chunk-MUCHLKSG.js} +1 -1
  43. package/dist/chunks/{chunk-OWO23BQ5.js → chunk-O5RWOOY4.js} +1 -1
  44. package/dist/chunks/{chunk-IGUBYNVC.js → chunk-OBSOJQH7.js} +1 -1
  45. package/dist/chunks/{chunk-JZIVQAEF.js → chunk-OIIOMP67.js} +1 -1
  46. package/dist/chunks/{chunk-XBMLLP4J.js → chunk-PUNGYINC.js} +1 -1
  47. package/dist/chunks/{chunk-FKX3DSV3.js → chunk-PVXBOZ45.js} +1 -1
  48. package/dist/chunks/{chunk-MECG6WLF.js → chunk-Q45WRPBA.js} +1 -1
  49. package/dist/chunks/{chunk-O2CAD56C.js → chunk-Q4WSTT5G.js} +1 -1
  50. package/dist/chunks/{chunk-UGHEH4LA.js → chunk-R3BZ4IDA.js} +1 -1
  51. package/dist/chunks/{chunk-PB6T5FH2.js → chunk-S5TWKTHV.js} +1 -1
  52. package/dist/chunks/{chunk-R2UVL57S.js → chunk-T2DXWRDM.js} +1 -1
  53. package/dist/chunks/{chunk-S3HHQBZN.js → chunk-T52PWZNS.js} +1 -1
  54. package/dist/chunks/{chunk-L6QX3T3V.js → chunk-TAIREW55.js} +1 -1
  55. package/dist/chunks/{chunk-KW7G66ZY.js → chunk-UITNWLE7.js} +2 -2
  56. package/dist/chunks/{chunk-IZL4EP7R.js → chunk-VNTREJRW.js} +1 -1
  57. package/dist/chunks/{chunk-577HHXC7.js → chunk-VTA5KIL5.js} +1 -1
  58. package/dist/chunks/{chunk-FA7WAHGX.js → chunk-VZX47KDU.js} +1 -1
  59. package/dist/chunks/{chunk-75GXMKCF.js → chunk-WBYRQHSP.js} +1 -1
  60. package/dist/chunks/{chunk-6E6TYIDT.js → chunk-WYSNAEMX.js} +1 -1
  61. package/dist/chunks/{chunk-PIK7YTVD.js → chunk-XCEO6325.js} +1 -1
  62. package/dist/chunks/{chunk-DXG5ITSX.js → chunk-XRCHG3IF.js} +1 -1
  63. package/dist/chunks/{chunk-OIHLZ4IA.js → chunk-Y7JAJKAJ.js} +1 -1
  64. package/dist/chunks/{chunk-STMC2M6P.js → chunk-YBE2G3LP.js} +1 -1
  65. package/dist/chunks/{chunk-2YE7HO7L.js → chunk-Z3QJKD32.js} +1 -1
  66. package/dist/chunks/{chunk-KI2DDO2M.js → chunk-ZJTN7U74.js} +1 -1
  67. package/dist/chunks/{clear-XM6U2LZG.js → clear-JOCTJFHZ.js} +1 -1
  68. package/dist/chunks/{compile-vercel-config-7HTV3XDT.js → compile-vercel-config-H5MLKZB5.js} +1 -1
  69. package/dist/chunks/{config-WAYNH5FH.js → config-4IL23FDT.js} +1 -1
  70. package/dist/chunks/{config-H7B62N7P.js → config-WY56RPZJ.js} +1 -1
  71. package/dist/chunks/{delete-3GLZUBWG.js → delete-PWULSIJU.js} +1 -1
  72. package/dist/chunks/{delete-HNJEM6SL.js → delete-SN7E5MTV.js} +1 -1
  73. package/dist/chunks/{describe-L7HZBSWX.js → describe-II22LJP3.js} +1 -1
  74. package/dist/chunks/{detect-services-QQWDDXR4.js → detect-services-VIJ4XLRR.js} +1 -1
  75. package/dist/chunks/{disable-7NRBTCQH.js → disable-7PWT4ILT.js} +1 -1
  76. package/dist/chunks/{discard-F7N2DAVD.js → discard-GL42ZPA7.js} +1 -1
  77. package/dist/chunks/{edit-WTJMNCAV.js → edit-JCJDO73Y.js} +1 -1
  78. package/dist/chunks/{edit-ILM7AU2K.js → edit-SJH6BCRY.js} +1 -1
  79. package/dist/chunks/{enable-3QT356KG.js → enable-G7RZ5VV4.js} +1 -1
  80. package/dist/chunks/{export-EUDVMKNC.js → export-CUKYNL3C.js} +1 -1
  81. package/dist/chunks/{future-VI6GFQ5S.js → future-PAAXGZTN.js} +1 -1
  82. package/dist/chunks/{generate-cert-for-deploy-B5SEDLVP.js → generate-cert-for-deploy-ZAMSUCFF.js} +1 -1
  83. package/dist/chunks/{group-actions-RKKQ4N3U.js → group-actions-O76SXUUJ.js} +1 -1
  84. package/dist/chunks/{image-4LT5EYSE.js → image-QDQO36EW.js} +1 -1
  85. package/dist/chunks/{import-builders-6RQ33NP7.js → import-builders-EFVZQWHA.js} +1 -1
  86. package/dist/chunks/{inspect-O7ACMOY7.js → inspect-AGC7W3OS.js} +1 -1
  87. package/dist/chunks/{inspect-6QOQ34XR.js → inspect-BSLSCH4L.js} +1 -1
  88. package/dist/chunks/{inspect-IFCFRG5Q.js → inspect-KPAFRFZA.js} +1 -1
  89. package/dist/chunks/{inspect-FK3DKMSD.js → inspect-XXQ7X2W7.js} +1 -1
  90. package/dist/chunks/{inspect-4KPVCIE6.js → inspect-XYVW6J2E.js} +1 -1
  91. package/dist/chunks/{list-XP5PWPPV.js → list-2KYHARKO.js} +1 -1
  92. package/dist/chunks/{list-USYKOYNK.js → list-RYYPFUX4.js} +1 -1
  93. package/dist/chunks/{list-YFYMW3PF.js → list-X6EO34N6.js} +1 -1
  94. package/dist/chunks/{login-N6NXJVOY.js → login-6VVAMBOA.js} +1 -1
  95. package/dist/chunks/{login-WJMEDLYY.js → login-IPMI6XEL.js} +1 -1
  96. package/dist/chunks/{logs-K224ET3X.js → logs-UQPPRXTB.js} +1 -1
  97. package/dist/chunks/{ls-CZQQSAWN.js → ls-5SH4HSZ5.js} +1 -1
  98. package/dist/chunks/{ls-UJYVIGPU.js → ls-6GPP7PTK.js} +1 -1
  99. package/dist/chunks/{ls-DTQQXLRH.js → ls-FR5KWP4I.js} +1 -1
  100. package/dist/chunks/{ls-D5BBVUGJ.js → ls-KAPV4POT.js} +1 -1
  101. package/dist/chunks/{ls-N7WA56X3.js → ls-KITNPWDE.js} +1 -1
  102. package/dist/chunks/{ls-IVDRION6.js → ls-QQ3F6OJ3.js} +1 -1
  103. package/dist/chunks/{ls-V5NG5442.js → ls-WRJ6GDUR.js} +1 -1
  104. package/dist/chunks/{migrate-experimental-services-NVNIIL5I.js → migrate-experimental-services-BORV5SUM.js} +1 -1
  105. package/dist/chunks/{mutate-F35S2QC7.js → mutate-TER55VAA.js} +1 -1
  106. package/dist/chunks/{notifications-VIH6IT6O.js → notifications-SUB7P4EX.js} +1 -1
  107. package/dist/chunks/{open-XCUBKH5P.js → open-GANU5JWA.js} +1 -1
  108. package/dist/chunks/{permissions-3JSUIIVW.js → permissions-V4UHHOV2.js} +1 -1
  109. package/dist/chunks/{plugin-offer-IGID5HXG.js → plugin-offer-SFFLTT66.js} +1 -1
  110. package/dist/chunks/{prompt-missing-credentials-6XVEA3P5.js → prompt-missing-credentials-CVIIFJ6S.js} +1 -1
  111. package/dist/chunks/{publish-GWDTWIM6.js → publish-MV3RCHJM.js} +1 -1
  112. package/dist/chunks/{pull-4TPB2B5E.js → pull-JGTNLAF3.js} +1 -1
  113. package/dist/chunks/{purchase-domain-if-available-2A5QEP5U.js → purchase-domain-if-available-OO533ARB.js} +1 -1
  114. package/dist/chunks/{push-OKQJWOA5.js → push-FJZEB3K2.js} +1 -1
  115. package/dist/chunks/{query-7XT3JVXP.js → query-3HB7DLVE.js} +1 -1
  116. package/dist/chunks/{raw-query-K3NOPCB2.js → raw-query-PNZO3D3S.js} +1 -1
  117. package/dist/chunks/{reauthenticate-UNE3JLFT.js → reauthenticate-6TPAZX5R.js} +1 -1
  118. package/dist/chunks/{remove-3ZHQO7AX.js → remove-76ZLLEHO.js} +1 -1
  119. package/dist/chunks/{reorder-YLJYY5ZS.js → reorder-ZZRQMWQO.js} +1 -1
  120. package/dist/chunks/{reply-2MPQ4RQW.js → reply-LWX3Q77Y.js} +1 -1
  121. package/dist/chunks/{resolve-MKHP5X4E.js → resolve-K72DNP5D.js} +1 -1
  122. package/dist/chunks/{resolve-agent-team-JCV6SHFD.js → resolve-agent-team-75QSXK3C.js} +1 -1
  123. package/dist/chunks/{restore-OYFENAAK.js → restore-CMVVFIY3.js} +1 -1
  124. package/dist/chunks/{rm-VKTDKTBV.js → rm-4W2E3LPX.js} +1 -1
  125. package/dist/chunks/{rm-63TJ62IW.js → rm-7Q6CRYDP.js} +1 -1
  126. package/dist/chunks/{rm-HBL4R7OM.js → rm-KGIBQFXK.js} +1 -1
  127. package/dist/chunks/{rm-2QUJ4MTD.js → rm-MRH5RXBQ.js} +1 -1
  128. package/dist/chunks/{rm-4YDKARD4.js → rm-TELAXNYE.js} +1 -1
  129. package/dist/chunks/{rule-inspect-ZD4EP6N4.js → rule-inspect-2Z7XXWVB.js} +1 -1
  130. package/dist/chunks/{schema-XS3JIJUY.js → schema-5OJQWJJ6.js} +1 -1
  131. package/dist/chunks/{schema-6FBKE5HK.js → schema-QAYQPSHG.js} +1 -1
  132. package/dist/chunks/{select-org-33F2CJEO.js → select-org-CRZAHEXQ.js} +1 -1
  133. package/dist/chunks/{set-D5IT5H2E.js → set-AQP6ILFQ.js} +1 -1
  134. package/dist/chunks/{setup-and-link-JACRSC6H.js → setup-and-link-EFNAHZR4.js} +1 -1
  135. package/dist/chunks/{skills-VLGGLIV3.js → skills-MTZCIW44.js} +1 -1
  136. package/dist/chunks/{tags-IYGDEHIO.js → tags-EHN3GJUF.js} +1 -1
  137. package/dist/chunks/{update-GBXFXO7R.js → update-2CVWFAVE.js} +1 -1
  138. package/dist/chunks/{usage-P3LBOYE7.js → usage-LE5BHDUT.js} +1 -1
  139. package/dist/chunks/{views-HCN2WBW7.js → views-AKV4QHMO.js} +1 -1
  140. package/dist/commands/build/index.js +1 -1
  141. package/dist/commands/deploy/index.js +5 -5
  142. package/dist/commands/dev/index.js +2 -2
  143. package/dist/commands/env/index.js +1 -1
  144. package/dist/commands/link/index.js +1 -1
  145. package/dist/commands/list/index.js +1 -1
  146. package/dist/commands/project/index.js +1 -1
  147. package/dist/commands/tunnel/index.js +1 -1
  148. package/dist/commands-account.js +2 -2
  149. package/dist/commands-ai.js +9 -9
  150. package/dist/commands-blob.js +1 -1
  151. package/dist/commands-core.js +5 -5
  152. package/dist/commands-deployments.js +1 -1
  153. package/dist/commands-flags.js +1 -1
  154. package/dist/commands-integrations.js +1 -1
  155. package/dist/commands-observability.js +40 -30
  156. package/dist/commands-routing.js +2 -2
  157. package/dist/index.js +3 -3
  158. package/dist/internal-build.js +1 -1
  159. package/dist/package.json +40 -40
  160. package/dist/version.mjs +1 -1
  161. package/package.json +41 -41
@@ -4,5 +4,5 @@ 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{printRuleMutationReceipt}from"./chunk-NKACWBO3.js";import"./chunk-QOIG2FJP.js";import{resolveRulesProject,resolveRulesTeam}from"./chunk-CYEMSHQ4.js";import"./chunk-DKDYIUCY.js";import{emitRulesArgParseError,getBodyType,handleRulesApiError,outputRulesError,resolveRuleBodyInput,rulesCollectionPath}from"./chunk-LYWMEQRT.js";import"./chunk-DRDY2UZX.js";import"./chunk-GHAY4PSD.js";import"./chunk-EL65DTVZ.js";import"./chunk-6JY43KSR.js";import"./chunk-FIICEEXO.js";import"./chunk-46R47IE5.js";import"./chunk-GZNDA6SV.js";import"./chunk-OM6NML7C.js";import{trackCreatedId}from"./chunk-ILNTOWHG.js";import{withWarnings}from"./chunk-237WN2MK.js";import"./chunk-QCYCLWNG.js";import{monitorsAddSubcommand}from"./chunk-X2UJGCIC.js";import"./chunk-GTZ6ASHD.js";import"./chunk-QROPMCL2.js";import"./chunk-4YGSXM2T.js";import"./chunk-SUD5V67L.js";import"./chunk-7TRHPXCG.js";import"./chunk-VO5M6G7M.js";import"./chunk-QRPBDCDH.js";import"./chunk-2GXP676X.js";import"./chunk-K5GE24PG.js";import"./chunk-IFMPBA4K.js";import"./chunk-KHJWQ4WP.js";import"./chunk-MY4MONOH.js";import"./chunk-YATYCZQJ.js";import"./chunk-2ILZM77F.js";import{printError}from"./chunk-QI7BWXRV.js";import{parseArguments}from"./chunk-E7ICSU45.js";import"./chunk-3QTP26QS.js";import{validateJsonOutput}from"./chunk-BDLZ6WL2.js";import"./chunk-PH2MLBQO.js";import"./chunk-DCFCPAFQ.js";import"./chunk-GOXGA37R.js";import{isAPIError}from"./chunk-UNAQQ5DF.js";import"./chunk-EFGZK6OY.js";import"./chunk-JCDPMWKO.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import"./chunk-7Y572CPZ.js";import"./chunk-BVFFSUG3.js";import"./chunk-RRX2AMWY.js";import"./chunk-GUFRGEM5.js";import"./chunk-SUT2PTL3.js";import"./chunk-AX6UCTOC.js";import"./chunk-4SIQE2W4.js";import"./chunk-MF43WTDT.js";import"./chunk-7QHUMMBA.js";import"./chunk-AUCQKYL2.js";import{getFlagsSpecification}from"./chunk-CUO3CYU3.js";import"./chunk-2BKALEOP.js";import"./chunk-UJ7YUIEJ.js";import"./chunk-L6MWUMWZ.js";import"./chunk-L4CSJDG7.js";import"./chunk-YHZXIBS7.js";import"./chunk-LPYHYTYI.js";import"./chunk-NBPLUP7C.js";function applyScopeFlag(client,body,type,scope,flags,jsonOutput,warnings){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.",{warnings}):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>.",{warnings});body.ruleScope={type:"all"};return}return outputRulesError(client,jsonOutput,"MISSING_SCOPE","Missing monitor scope. Add ruleScope to the body, or pass --project or --all.",{warnings})}async function resolveCreateScope(client,flags,jsonOutput,warnings){return flags["--project"]&&flags["--all"]?outputRulesError(client,jsonOutput,"MUTUAL_EXCLUSIVITY","Cannot specify both --all and --project. Use one or the other.",{warnings}):flags["--project"]?resolveRulesProject(client,flags["--project"],jsonOutput,"monitors add"):resolveRulesTeam(client,jsonOutput)}async function add(client,argv,api,telemetry){let parsedArgs;try{parsedArgs=parseArguments(argv,getFlagsSpecification(monitorsAddSubcommand.options))}catch(error){return emitRulesArgParseError(client,error,"monitors add --project <name-or-id> --file <path>"),printError(error),2}let flags=parsedArgs.flags;telemetry?.trackCliFlagAll(flags["--all"]),telemetry?.trackCliFlagJson(flags["--json"]),telemetry?.trackCliOptionFile(flags["--file"]),telemetry?.trackCliOptionData(flags["--data"]),telemetry?.trackCliOptionBody(flags["--body"]);let format=validateJsonOutput(flags);if(!format.valid)return outputRulesError(client,!1,"INVALID_ARGUMENTS",format.error);let resolvedInput=await resolveRuleBodyInput(client,parsedArgs.flags,format.jsonOutput,{required:!0,missingMessage:"Missing required option: --file <PATH> or --data <JSON>."});if(typeof resolvedInput=="number")return resolvedInput;let{body,warnings}=resolvedInput,type=getBodyType(body);if(!type)return outputRulesError(client,format.jsonOutput,"INVALID_RULE_TYPE","Create body must set a supported monitor type.",{warnings});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.",{warnings});if(type==="custom"&&flags["--all"])return outputRulesError(client,format.jsonOutput,"INVALID_SCOPE","Custom monitors must target one project. Use --project <name-or-id>.",{warnings});let scope=await resolveCreateScope(client,flags,format.jsonOutput,warnings);if(typeof scope=="number")return scope;let scopeError=applyScopeFlag(client,body,type,scope,flags,format.jsonOutput,warnings);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 trackCreatedId(client,"monitor",response[api.itemKey]?.id),format.jsonOutput?client.stdout.write(`${JSON.stringify(withWarnings(response,warnings),null,2)}
7
+ import{printRuleMutationReceipt}from"./chunk-NKACWBO3.js";import"./chunk-QOIG2FJP.js";import{resolveRulesProject,resolveRulesTeam}from"./chunk-MADCVSMW.js";import"./chunk-KVX64ZHU.js";import{emitRulesArgParseError,getBodyType,handleRulesApiError,outputRulesError,resolveRuleBodyInput,rulesCollectionPath}from"./chunk-4KEWLHYF.js";import"./chunk-DRDY2UZX.js";import"./chunk-GHAY4PSD.js";import"./chunk-EL65DTVZ.js";import"./chunk-6JY43KSR.js";import"./chunk-FIICEEXO.js";import"./chunk-46R47IE5.js";import"./chunk-GZNDA6SV.js";import"./chunk-OM6NML7C.js";import{trackCreatedId}from"./chunk-ILNTOWHG.js";import{withWarnings}from"./chunk-237WN2MK.js";import"./chunk-QCYCLWNG.js";import{monitorsAddSubcommand}from"./chunk-X2UJGCIC.js";import"./chunk-H3HSH5FW.js";import"./chunk-QROPMCL2.js";import"./chunk-H4BQDKOU.js";import"./chunk-SUD5V67L.js";import"./chunk-7TRHPXCG.js";import"./chunk-VO5M6G7M.js";import"./chunk-QRPBDCDH.js";import"./chunk-2GXP676X.js";import"./chunk-K5GE24PG.js";import"./chunk-IFMPBA4K.js";import"./chunk-KHJWQ4WP.js";import"./chunk-MY4MONOH.js";import"./chunk-YATYCZQJ.js";import"./chunk-2ILZM77F.js";import{printError}from"./chunk-QI7BWXRV.js";import{parseArguments}from"./chunk-E7ICSU45.js";import"./chunk-3QTP26QS.js";import{validateJsonOutput}from"./chunk-BDLZ6WL2.js";import"./chunk-PH2MLBQO.js";import"./chunk-DCFCPAFQ.js";import"./chunk-GOXGA37R.js";import{isAPIError}from"./chunk-UNAQQ5DF.js";import"./chunk-EFGZK6OY.js";import"./chunk-JCDPMWKO.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import"./chunk-7Y572CPZ.js";import"./chunk-BVFFSUG3.js";import"./chunk-RRX2AMWY.js";import"./chunk-GUFRGEM5.js";import"./chunk-SUT2PTL3.js";import"./chunk-AX6UCTOC.js";import"./chunk-4SIQE2W4.js";import"./chunk-MF43WTDT.js";import"./chunk-7QHUMMBA.js";import"./chunk-AUCQKYL2.js";import{getFlagsSpecification}from"./chunk-CUO3CYU3.js";import"./chunk-2BKALEOP.js";import"./chunk-UJ7YUIEJ.js";import"./chunk-L6MWUMWZ.js";import"./chunk-L4CSJDG7.js";import"./chunk-YHZXIBS7.js";import"./chunk-LPYHYTYI.js";import"./chunk-NBPLUP7C.js";function applyScopeFlag(client,body,type,scope,flags,jsonOutput,warnings){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.",{warnings}):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>.",{warnings});body.ruleScope={type:"all"};return}return outputRulesError(client,jsonOutput,"MISSING_SCOPE","Missing monitor scope. Add ruleScope to the body, or pass --project or --all.",{warnings})}async function resolveCreateScope(client,flags,jsonOutput,warnings){return flags["--project"]&&flags["--all"]?outputRulesError(client,jsonOutput,"MUTUAL_EXCLUSIVITY","Cannot specify both --all and --project. Use one or the other.",{warnings}):flags["--project"]?resolveRulesProject(client,flags["--project"],jsonOutput,"monitors add"):resolveRulesTeam(client,jsonOutput)}async function add(client,argv,api,telemetry){let parsedArgs;try{parsedArgs=parseArguments(argv,getFlagsSpecification(monitorsAddSubcommand.options))}catch(error){return emitRulesArgParseError(client,error,"monitors add --project <name-or-id> --file <path>"),printError(error),2}let flags=parsedArgs.flags;telemetry?.trackCliFlagAll(flags["--all"]),telemetry?.trackCliFlagJson(flags["--json"]),telemetry?.trackCliOptionFile(flags["--file"]),telemetry?.trackCliOptionData(flags["--data"]),telemetry?.trackCliOptionBody(flags["--body"]);let format=validateJsonOutput(flags);if(!format.valid)return outputRulesError(client,!1,"INVALID_ARGUMENTS",format.error);let resolvedInput=await resolveRuleBodyInput(client,parsedArgs.flags,format.jsonOutput,{required:!0,missingMessage:"Missing required option: --file <PATH> or --data <JSON>."});if(typeof resolvedInput=="number")return resolvedInput;let{body,warnings}=resolvedInput,type=getBodyType(body);if(!type)return outputRulesError(client,format.jsonOutput,"INVALID_RULE_TYPE","Create body must set a supported monitor type.",{warnings});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.",{warnings});if(type==="custom"&&flags["--all"])return outputRulesError(client,format.jsonOutput,"INVALID_SCOPE","Custom monitors must target one project. Use --project <name-or-id>.",{warnings});let scope=await resolveCreateScope(client,flags,format.jsonOutput,warnings);if(typeof scope=="number")return scope;let scopeError=applyScopeFlag(client,body,type,scope,flags,format.jsonOutput,warnings);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 trackCreatedId(client,"monitor",response[api.itemKey]?.id),format.jsonOutput?client.stdout.write(`${JSON.stringify(withWarnings(response,warnings),null,2)}
8
8
  `):printRuleMutationReceipt("Created",response[api.itemKey],client.argv),0}catch(error){if(isAPIError(error))return handleRulesApiError(client,error,format.jsonOutput,warnings);throw error}finally{output_manager_default.stopSpinner()}}export{add as default};
@@ -4,5 +4,5 @@ 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{emitVcrArgParseError,handleVcrApiError,resolveVcrScope,validateVcrJsonOutput}from"./chunk-JZIVQAEF.js";import{outputError}from"./chunk-6JY43KSR.js";import"./chunk-3WXQHKSS.js";import"./chunk-FIICEEXO.js";import"./chunk-RFD7CEL6.js";import{trackCreatedId}from"./chunk-ILNTOWHG.js";import{addSubcommand}from"./chunk-CHTFRAXA.js";import"./chunk-T2IZUTGY.js";import"./chunk-3F3WNT5K.js";import"./chunk-P7GA2C6N.js";import"./chunk-GTZ6ASHD.js";import"./chunk-QROPMCL2.js";import"./chunk-4YGSXM2T.js";import"./chunk-SUD5V67L.js";import"./chunk-7TRHPXCG.js";import"./chunk-VO5M6G7M.js";import"./chunk-QRPBDCDH.js";import"./chunk-2GXP676X.js";import"./chunk-K5GE24PG.js";import"./chunk-IFMPBA4K.js";import"./chunk-KHJWQ4WP.js";import"./chunk-MY4MONOH.js";import"./chunk-YATYCZQJ.js";import"./chunk-2ILZM77F.js";import{printError}from"./chunk-QI7BWXRV.js";import{parseArguments}from"./chunk-E7ICSU45.js";import{AGENT_REASON,buildCommandWithGlobalFlags,outputAgentError}from"./chunk-3QTP26QS.js";import"./chunk-BDLZ6WL2.js";import"./chunk-PH2MLBQO.js";import"./chunk-DCFCPAFQ.js";import"./chunk-GOXGA37R.js";import{isAPIError}from"./chunk-UNAQQ5DF.js";import{packageName}from"./chunk-EFGZK6OY.js";import"./chunk-JCDPMWKO.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import"./chunk-7Y572CPZ.js";import"./chunk-BVFFSUG3.js";import"./chunk-RRX2AMWY.js";import"./chunk-GUFRGEM5.js";import"./chunk-SUT2PTL3.js";import"./chunk-AX6UCTOC.js";import"./chunk-4SIQE2W4.js";import"./chunk-MF43WTDT.js";import"./chunk-7QHUMMBA.js";import"./chunk-AUCQKYL2.js";import{getFlagsSpecification}from"./chunk-CUO3CYU3.js";import"./chunk-2BKALEOP.js";import"./chunk-UJ7YUIEJ.js";import"./chunk-L6MWUMWZ.js";import"./chunk-L4CSJDG7.js";import"./chunk-YHZXIBS7.js";import"./chunk-LPYHYTYI.js";import"./chunk-NBPLUP7C.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 trackCreatedId(client,"vcr-repository",created.repository?.id),fr.jsonOutput?client.stdout.write(`${JSON.stringify(created,null,2)}
7
+ import{emitVcrArgParseError,handleVcrApiError,resolveVcrScope,validateVcrJsonOutput}from"./chunk-OIIOMP67.js";import{outputError}from"./chunk-6JY43KSR.js";import"./chunk-3WXQHKSS.js";import"./chunk-FIICEEXO.js";import"./chunk-RFD7CEL6.js";import{trackCreatedId}from"./chunk-ILNTOWHG.js";import{addSubcommand}from"./chunk-CHTFRAXA.js";import"./chunk-T2IZUTGY.js";import"./chunk-3F3WNT5K.js";import"./chunk-P7GA2C6N.js";import"./chunk-H3HSH5FW.js";import"./chunk-QROPMCL2.js";import"./chunk-H4BQDKOU.js";import"./chunk-SUD5V67L.js";import"./chunk-7TRHPXCG.js";import"./chunk-VO5M6G7M.js";import"./chunk-QRPBDCDH.js";import"./chunk-2GXP676X.js";import"./chunk-K5GE24PG.js";import"./chunk-IFMPBA4K.js";import"./chunk-KHJWQ4WP.js";import"./chunk-MY4MONOH.js";import"./chunk-YATYCZQJ.js";import"./chunk-2ILZM77F.js";import{printError}from"./chunk-QI7BWXRV.js";import{parseArguments}from"./chunk-E7ICSU45.js";import{AGENT_REASON,buildCommandWithGlobalFlags,outputAgentError}from"./chunk-3QTP26QS.js";import"./chunk-BDLZ6WL2.js";import"./chunk-PH2MLBQO.js";import"./chunk-DCFCPAFQ.js";import"./chunk-GOXGA37R.js";import{isAPIError}from"./chunk-UNAQQ5DF.js";import{packageName}from"./chunk-EFGZK6OY.js";import"./chunk-JCDPMWKO.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import"./chunk-7Y572CPZ.js";import"./chunk-BVFFSUG3.js";import"./chunk-RRX2AMWY.js";import"./chunk-GUFRGEM5.js";import"./chunk-SUT2PTL3.js";import"./chunk-AX6UCTOC.js";import"./chunk-4SIQE2W4.js";import"./chunk-MF43WTDT.js";import"./chunk-7QHUMMBA.js";import"./chunk-AUCQKYL2.js";import{getFlagsSpecification}from"./chunk-CUO3CYU3.js";import"./chunk-2BKALEOP.js";import"./chunk-UJ7YUIEJ.js";import"./chunk-L6MWUMWZ.js";import"./chunk-L4CSJDG7.js";import"./chunk-YHZXIBS7.js";import"./chunk-LPYHYTYI.js";import"./chunk-NBPLUP7C.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 trackCreatedId(client,"vcr-repository",created.repository?.id),fr.jsonOutput?client.stdout.write(`${JSON.stringify(created,null,2)}
8
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};
@@ -4,5 +4,5 @@ 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{parseTeamRefs,teamRefBody}from"./chunk-LSF7FY6X.js";import{repositoryPermissionsPath}from"./chunk-DFVNL5ML.js";import{emitVcrArgParseError,resolveVcrScope,validateVcrJsonOutput}from"./chunk-JZIVQAEF.js";import{require_async_sema}from"./chunk-ZOJI7HYA.js";import{outputError}from"./chunk-6JY43KSR.js";import"./chunk-3WXQHKSS.js";import"./chunk-FIICEEXO.js";import"./chunk-RFD7CEL6.js";import{permissionsAddSubcommand}from"./chunk-T2IZUTGY.js";import{getCachedTeamSlug,hasExplicitScopeValue}from"./chunk-GTZ6ASHD.js";import"./chunk-4YGSXM2T.js";import"./chunk-SUD5V67L.js";import"./chunk-7TRHPXCG.js";import"./chunk-VO5M6G7M.js";import"./chunk-QRPBDCDH.js";import"./chunk-2GXP676X.js";import"./chunk-K5GE24PG.js";import"./chunk-IFMPBA4K.js";import"./chunk-KHJWQ4WP.js";import"./chunk-MY4MONOH.js";import"./chunk-YATYCZQJ.js";import"./chunk-2ILZM77F.js";import{printError}from"./chunk-QI7BWXRV.js";import{parseArguments}from"./chunk-E7ICSU45.js";import{AGENT_REASON,buildCommandWithGlobalFlags,outputAgentError,quoteSuggestionToken}from"./chunk-3QTP26QS.js";import"./chunk-BDLZ6WL2.js";import"./chunk-PH2MLBQO.js";import"./chunk-DCFCPAFQ.js";import"./chunk-GOXGA37R.js";import{isAPIError}from"./chunk-UNAQQ5DF.js";import{packageName}from"./chunk-EFGZK6OY.js";import"./chunk-JCDPMWKO.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import"./chunk-7Y572CPZ.js";import"./chunk-BVFFSUG3.js";import"./chunk-RRX2AMWY.js";import"./chunk-GUFRGEM5.js";import"./chunk-SUT2PTL3.js";import"./chunk-AX6UCTOC.js";import"./chunk-4SIQE2W4.js";import"./chunk-MF43WTDT.js";import{remoteText}from"./chunk-AUCQKYL2.js";import{getFlagsSpecification}from"./chunk-CUO3CYU3.js";import"./chunk-2BKALEOP.js";import"./chunk-UJ7YUIEJ.js";import"./chunk-L6MWUMWZ.js";import"./chunk-L4CSJDG7.js";import"./chunk-YHZXIBS7.js";import"./chunk-LPYHYTYI.js";import{__toESM}from"./chunk-NBPLUP7C.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 scopeIsExplicit=hasExplicitScopeValue(client),selectedTeamId=client.config.currentTeam,scope=await resolveVcrScope(client,{project,jsonOutput:fr.jsonOutput});if(typeof scope=="number")return scope;let projectTeamId=scope.teamId.startsWith("team_")?scope.teamId:void 0;if(scopeIsExplicit&&projectTeamId!==selectedTeamId){let selected=selectedTeamId?`the team --scope selects (${remoteText(getCachedTeamSlug(client.config,selectedTeamId)??selectedTeamId)})`:"the personal account --scope selects",recovery=selectedTeamId?"pass --project for a project in the selected team":"select the linked project's team with --scope",message=`This directory's linked project is in "${remoteText(scope.teamSlug)}", which is not ${selected}. No permission was added. Run \`vercel link\` to relink the directory, or ${recovery}.`;return outputAgentError(client,{status:"error",reason:AGENT_REASON.CONFLICT,message,...selectedTeamId&&{next:[{command:buildCommandWithGlobalFlags(client.argv,`vcr permissions ${quoteSuggestionToken(repository)} add ${quoteSuggestionToken(teamRefs.join(","))} --project <name_or_id>`),when:"share the repository from a project in the selected team"}]}},1),outputError(client,fr.jsonOutput,"SCOPE_MISMATCH",message)}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)}
7
+ import{parseTeamRefs,teamRefBody}from"./chunk-LSF7FY6X.js";import{repositoryPermissionsPath}from"./chunk-DFVNL5ML.js";import{emitVcrArgParseError,resolveVcrScope,validateVcrJsonOutput}from"./chunk-OIIOMP67.js";import{require_async_sema}from"./chunk-ZOJI7HYA.js";import{outputError}from"./chunk-6JY43KSR.js";import"./chunk-3WXQHKSS.js";import"./chunk-FIICEEXO.js";import"./chunk-RFD7CEL6.js";import{permissionsAddSubcommand}from"./chunk-T2IZUTGY.js";import{getCachedTeamSlug,hasExplicitScopeValue}from"./chunk-H3HSH5FW.js";import"./chunk-H4BQDKOU.js";import"./chunk-SUD5V67L.js";import"./chunk-7TRHPXCG.js";import"./chunk-VO5M6G7M.js";import"./chunk-QRPBDCDH.js";import"./chunk-2GXP676X.js";import"./chunk-K5GE24PG.js";import"./chunk-IFMPBA4K.js";import"./chunk-KHJWQ4WP.js";import"./chunk-MY4MONOH.js";import"./chunk-YATYCZQJ.js";import"./chunk-2ILZM77F.js";import{printError}from"./chunk-QI7BWXRV.js";import{parseArguments}from"./chunk-E7ICSU45.js";import{AGENT_REASON,buildCommandWithGlobalFlags,outputAgentError,quoteSuggestionToken}from"./chunk-3QTP26QS.js";import"./chunk-BDLZ6WL2.js";import"./chunk-PH2MLBQO.js";import"./chunk-DCFCPAFQ.js";import"./chunk-GOXGA37R.js";import{isAPIError}from"./chunk-UNAQQ5DF.js";import{packageName}from"./chunk-EFGZK6OY.js";import"./chunk-JCDPMWKO.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import"./chunk-7Y572CPZ.js";import"./chunk-BVFFSUG3.js";import"./chunk-RRX2AMWY.js";import"./chunk-GUFRGEM5.js";import"./chunk-SUT2PTL3.js";import"./chunk-AX6UCTOC.js";import"./chunk-4SIQE2W4.js";import"./chunk-MF43WTDT.js";import{remoteText}from"./chunk-AUCQKYL2.js";import{getFlagsSpecification}from"./chunk-CUO3CYU3.js";import"./chunk-2BKALEOP.js";import"./chunk-UJ7YUIEJ.js";import"./chunk-L6MWUMWZ.js";import"./chunk-L4CSJDG7.js";import"./chunk-YHZXIBS7.js";import"./chunk-LPYHYTYI.js";import{__toESM}from"./chunk-NBPLUP7C.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 scopeIsExplicit=hasExplicitScopeValue(client),selectedTeamId=client.config.currentTeam,scope=await resolveVcrScope(client,{project,jsonOutput:fr.jsonOutput});if(typeof scope=="number")return scope;let projectTeamId=scope.teamId.startsWith("team_")?scope.teamId:void 0;if(scopeIsExplicit&&projectTeamId!==selectedTeamId){let selected=selectedTeamId?`the team --scope selects (${remoteText(getCachedTeamSlug(client.config,selectedTeamId)??selectedTeamId)})`:"the personal account --scope selects",recovery=selectedTeamId?"pass --project for a project in the selected team":"select the linked project's team with --scope",message=`This directory's linked project is in "${remoteText(scope.teamSlug)}", which is not ${selected}. No permission was added. Run \`vercel link\` to relink the directory, or ${recovery}.`;return outputAgentError(client,{status:"error",reason:AGENT_REASON.CONFLICT,message,...selectedTeamId&&{next:[{command:buildCommandWithGlobalFlags(client.argv,`vcr permissions ${quoteSuggestionToken(repository)} add ${quoteSuggestionToken(teamRefs.join(","))} --project <name_or_id>`),when:"share the repository from a project in the selected team"}]}},1),outputError(client,fr.jsonOutput,"SCOPE_MISMATCH",message)}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
8
  `),failed.length>0?1:0}export{add as default};
@@ -4,5 +4,5 @@ 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{loadScopeNames,printBudgetAlertsTable,scopeNameOf}from"./chunk-EHA24PIE.js";import{organizationTarget,parseBudgetFilterOptions,rejectUnexpectedArgs,resolveBudgetFilter,resolveBudgetOwner,trackScopeOptions,typeFilter}from"./chunk-ZUCLG4ML.js";import"./chunk-46DSHEHL.js";import"./chunk-PL2KOT4Q.js";import"./chunk-LKFQMY5V.js";import{handleValidationError,outputError,validateOptionalIntegerRange,validateTimeBound,validateTimeOrder}from"./chunk-6JY43KSR.js";import{INVALID_NEXT_MESSAGE}from"./chunk-C6GY2G73.js";import"./chunk-64GNDWWX.js";import"./chunk-FIICEEXO.js";import{budgetAlertJson,listBudgetAlerts,ownerJson}from"./chunk-ZUWIJMH2.js";import{getSubcommand}from"./chunk-ETV3C2CV.js";import"./chunk-QCYCLWNG.js";import{MAX_LIST_LIMIT,getNextPageCommand,printNextPageCommand}from"./chunk-WS6UOPMS.js";import{getCommandAliases}from"./chunk-X24LA5TL.js";import"./chunk-XHWA436J.js";import"./chunk-4MAA4BQD.js";import"./chunk-OXQKWOLS.js";import"./chunk-GO64LSUW.js";import{alertsListSubcommand,alertsSubcommand}from"./chunk-M3LYYAQ6.js";import"./chunk-TUPVVZ4I.js";import"./chunk-HXIOR7P6.js";import"./chunk-CHTFRAXA.js";import"./chunk-T2IZUTGY.js";import"./chunk-3F3WNT5K.js";import"./chunk-P7GA2C6N.js";import"./chunk-RPYIWRSN.js";import"./chunk-CDO5IECP.js";import"./chunk-6XXXPJBV.js";import{isBudgetScope}from"./chunk-L74PQVPL.js";import"./chunk-HT5EXCYX.js";import"./chunk-TTJWZ3ZW.js";import"./chunk-R3ZPLQDI.js";import"./chunk-QPPFQREO.js";import"./chunk-X2UJGCIC.js";import"./chunk-XZYVBYUY.js";import"./chunk-EZ3HXFLB.js";import"./chunk-WMIZ6Y4E.js";import"./chunk-QPNYOR6O.js";import"./chunk-JGEJY7AC.js";import"./chunk-LBJ7EOZM.js";import{TelemetryClient}from"./chunk-QROPMCL2.js";import{require_pluralize}from"./chunk-7TRHPXCG.js";import"./chunk-VO5M6G7M.js";import"./chunk-2ILZM77F.js";import{printError}from"./chunk-QI7BWXRV.js";import{parseArguments,takeCommand}from"./chunk-E7ICSU45.js";import{AGENT_REASON}from"./chunk-3QTP26QS.js";import{validateJsonOutput}from"./chunk-BDLZ6WL2.js";import"./chunk-GOXGA37R.js";import{isAPIError}from"./chunk-UNAQQ5DF.js";import"./chunk-EFGZK6OY.js";import"./chunk-JCDPMWKO.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import"./chunk-7Y572CPZ.js";import"./chunk-BVFFSUG3.js";import"./chunk-4SIQE2W4.js";import"./chunk-MF43WTDT.js";import"./chunk-FUH5PBGR.js";import"./chunk-7TREJIPV.js";import"./chunk-7QHUMMBA.js";import"./chunk-AUCQKYL2.js";import{getFlagsSpecification}from"./chunk-CUO3CYU3.js";import"./chunk-2BKALEOP.js";import"./chunk-UJ7YUIEJ.js";import"./chunk-L6MWUMWZ.js";import"./chunk-L4CSJDG7.js";import"./chunk-YHZXIBS7.js";import"./chunk-LPYHYTYI.js";import{__toESM}from"./chunk-NBPLUP7C.js";var import_pluralize=__toESM(require_pluralize(),1);function encodeBudgetAlertsCursor(value){return Buffer.from(JSON.stringify({c:value.cursor,t:value.teamId,o:value.owner==="organization"?value.owner:void 0,s:value.since,u:value.until,sc:value.selector?.scope,si:value.selector&&"scopeId"in value.selector?value.selector.scopeId:void 0})).toString("base64url")}function decodeBudgetAlertsCursor(value){if(value===void 0)return{valid:!0,value:void 0};let invalid={valid:!1,code:"INVALID_NEXT",message:INVALID_NEXT_MESSAGE},raw;try{raw=JSON.parse(Buffer.from(value,"base64url").toString("utf8"))}catch{return invalid}if(typeof raw!="object"||raw===null)return invalid;let{c,t,o,s,u,sc,si}=raw;if(typeof c!="string"||typeof t!="string"||!(o===void 0||o==="organization"&&sc==="organization"&&si===void 0)||!isOptionalMs(s)||!isOptionalMs(u)||!(sc===void 0||isBudgetScope(sc)||isScopeList(sc))||!(si===void 0||typeof si=="string"&&isBudgetScope(sc)))return invalid;let selector;return isScopeList(sc)?selector={scope:sc}:isBudgetScope(sc)&&(selector=si===void 0?{scope:sc}:{scope:sc,scopeId:si}),o==="organization"?{valid:!0,value:{cursor:c,teamId:t,owner:o,since:s,until:u,selector:{scope:"organization",orgId:t}}}:{valid:!0,value:{cursor:c,teamId:t,since:s,until:u,selector}}}function isScopeList(value){return Array.isArray(value)&&value.length>0&&value.every(isBudgetScope)}function isOptionalMs(value){return value===void 0||Number.isFinite(value)}var BudgetAlertsTelemetryClient=class extends TelemetryClient{trackCliOptionOrganization(organization){organization&&this.trackCliOption({option:"organization",value:this.redactedValue})}trackCliOptionProject(project){project&&this.trackCliOption({option:"project",value:this.redactedValue})}trackCliOptionType(types){types?.length&&this.trackCliOption({option:"type",value:types.join(",")})}trackCliOptionProduct(product){product&&this.trackCliOption({option:"product",value:this.redactedValue})}trackCliSubcommandList(actual){this.trackCliSubcommand({subcommand:"list",value:actual})}trackCliOptionSince(since){since&&this.trackCliOption({option:"since",value:this.redactedValue})}trackCliOptionUntil(until){until&&this.trackCliOption({option:"until",value:this.redactedValue})}trackCliOptionLimit(limit){limit!==void 0&&this.trackCliOption({option:"limit",value:String(limit)})}trackCliOptionNext(next){next&&this.trackCliOption({option:"next",value:this.redactedValue})}trackCliOptionFormat(format){format&&this.trackCliOption({option:"format",value:format})}trackCliFlagJson(json){json&&this.trackCliFlag("json")}};async function alerts(client,argv){let telemetry=new BudgetAlertsTelemetryClient({opts:{store:client.telemetryEventStore}}),action,parsedArgs,flagsSpecification=getFlagsSpecification(alertsSubcommand.options);try{let selected=takeCommand(argv,flagsSpecification);action=getSubcommand(selected.command?[selected.command]:[],{list:getCommandAliases(alertsListSubcommand)}),parsedArgs=parseArguments(action.subcommand?selected.args:argv,flagsSpecification)}catch(error){return printError(error),2}let{flags:opts,args}=parsedArgs;action.subcommand==="list"&&telemetry.trackCliSubcommandList(action.subcommandOriginal);let formatResult=validateJsonOutput(opts);if(!formatResult.valid)return output_manager_default.error(formatResult.error),2;let asJson=formatResult.jsonOutput;if(rejectUnexpectedArgs(args,"billing budgets alerts"))return 2;let scopeArgs=parseBudgetFilterOptions(opts);if("error"in scopeArgs)return outputError(client,asJson,"INVALID_ARGUMENTS",scopeArgs.error);trackScopeOptions(telemetry,opts),telemetry.trackCliOptionType(opts["--type"]),telemetry.trackCliOptionSince(opts["--since"]),telemetry.trackCliOptionUntil(opts["--until"]),telemetry.trackCliOptionLimit(opts["--limit"]),telemetry.trackCliOptionNext(opts["--next"]),telemetry.trackCliOptionFormat(opts["--format"]?"json":void 0),telemetry.trackCliFlagJson(opts["--json"]);let nextResult=decodeBudgetAlertsCursor(opts["--next"]);if(!nextResult.valid)return handleValidationError(nextResult,asJson,client);let cursor=nextResult.value,{types}=scopeArgs.value;if(cursor&&types&&!sameSelector(cursor.selector,{scope:types}))return outputError(client,asJson,"INVALID_NEXT",OTHER_FILTER_CURSOR);let warnings=[],limit=opts["--limit"];if(typeof limit=="number"&&Number.isInteger(limit)&&limit>MAX_LIST_LIMIT){let message=`--limit ${limit} is above the maximum of ${MAX_LIST_LIMIT}. Using ${MAX_LIST_LIMIT}.`;warnings.push({reason:AGENT_REASON.LIMIT_CLAMPED,message}),asJson||output_manager_default.warning(message),limit=MAX_LIST_LIMIT}let limitResult=validateOptionalIntegerRange(limit,{flag:"--limit",min:1,max:MAX_LIST_LIMIT});if(!limitResult.valid)return handleValidationError(limitResult,asJson,client);let sinceResult=validateTimeBound(opts["--since"]);if(!sinceResult.valid)return handleValidationError(sinceResult,asJson,client);let untilResult=validateTimeBound(opts["--until"]);if(!untilResult.valid)return handleValidationError(untilResult,asJson,client);let order=validateTimeOrder(sinceResult.value,untilResult.value);if(!order.valid)return handleValidationError(order,asJson,client);let resolvedOwner=await resolveBudgetOwner(client,scopeArgs.value.input??(cursor?.owner==="organization"?{scope:"organization",value:cursor.teamId}:null));if(!resolvedOwner)return 2;if("error"in resolvedOwner)return outputError(client,asJson,resolvedOwner.usage?"INVALID_ARGUMENTS":"API_ERROR",resolvedOwner.error);let owner=resolvedOwner.value;if(cursor&&cursor.teamId!==owner.id)return outputError(client,asJson,"INVALID_NEXT",`This --next cursor is from another team or organization, not ${owner.slug}. Use the --scope or --organization it was printed with.`);let since=cursor?cursor.since:sinceResult.value?.getTime(),until=cursor?cursor.until:untilResult.value?.getTime();output_manager_default.spinner("Fetching budget alerts\u2026");let resolved=cursor&&!scopeArgs.value.input&&!scopeArgs.value.types?{value:cursorFilter(owner,cursor.selector)}:await resolveBudgetFilter(client,owner,scopeArgs.value);if("error"in resolved)return output_manager_default.stopSpinner(),outputError(client,asJson,resolved.usage?"INVALID_ARGUMENTS":"API_ERROR",resolved.error);let filter=resolved.value;if(cursor&&!sameSelector(cursor.selector,filter.selector))return output_manager_default.stopSpinner(),outputError(client,asJson,"INVALID_NEXT",OTHER_FILTER_CURSOR);let page;try{page=await listBudgetAlerts(client,filter.selector,{since,until,limit:limitResult.value,next:cursor?.cursor})}catch(err){if(output_manager_default.stopSpinner(),isAPIError(err))return err.code==="invalid_cursor"?outputError(client,asJson,"INVALID_NEXT",INVALID_NEXT_MESSAGE):outputError(client,asJson,err.code||"API_ERROR",err.message);throw err}let names=await loadScopeNames(client,owner,page.data);output_manager_default.stopSpinner();let next=page.next?encodeBudgetAlertsCursor({cursor:page.next,teamId:owner.id,owner:owner.type,since,until,selector:filter.selector}):null;if(asJson)return client.stdout.write(`${JSON.stringify({...ownerJson(owner),...filter.selector?{filter:filter.json}:{},alerts:page.data.map(alert=>budgetAlertJson(alert,scopeNameOf(names,alert))),pagination:{next},...warnings.length>0?{warnings}:{}},null,2)}
7
+ import{loadScopeNames,printBudgetAlertsTable,scopeNameOf}from"./chunk-EHA24PIE.js";import{organizationTarget,parseBudgetFilterOptions,rejectUnexpectedArgs,resolveBudgetFilter,resolveBudgetOwner,trackScopeOptions,typeFilter}from"./chunk-ZUCLG4ML.js";import"./chunk-46DSHEHL.js";import"./chunk-PL2KOT4Q.js";import"./chunk-LKFQMY5V.js";import{handleValidationError,outputError,validateOptionalIntegerRange,validateTimeBound,validateTimeOrder}from"./chunk-6JY43KSR.js";import{INVALID_NEXT_MESSAGE}from"./chunk-C6GY2G73.js";import"./chunk-64GNDWWX.js";import"./chunk-FIICEEXO.js";import{budgetAlertJson,listBudgetAlerts,ownerJson}from"./chunk-ZUWIJMH2.js";import{getSubcommand}from"./chunk-ETV3C2CV.js";import"./chunk-QCYCLWNG.js";import{MAX_LIST_LIMIT,getNextPageCommand,printNextPageCommand}from"./chunk-WS6UOPMS.js";import{getCommandAliases}from"./chunk-DFZRZPCJ.js";import"./chunk-XHWA436J.js";import"./chunk-4MAA4BQD.js";import"./chunk-OXQKWOLS.js";import"./chunk-GO64LSUW.js";import{alertsListSubcommand,alertsSubcommand}from"./chunk-M3LYYAQ6.js";import"./chunk-TUPVVZ4I.js";import"./chunk-HXIOR7P6.js";import"./chunk-CHTFRAXA.js";import"./chunk-T2IZUTGY.js";import"./chunk-3F3WNT5K.js";import"./chunk-P7GA2C6N.js";import"./chunk-RPYIWRSN.js";import"./chunk-CDO5IECP.js";import"./chunk-6XXXPJBV.js";import{isBudgetScope}from"./chunk-L74PQVPL.js";import"./chunk-HT5EXCYX.js";import"./chunk-TTJWZ3ZW.js";import"./chunk-R3ZPLQDI.js";import"./chunk-QPPFQREO.js";import"./chunk-X2UJGCIC.js";import"./chunk-XZYVBYUY.js";import"./chunk-EZ3HXFLB.js";import"./chunk-WMIZ6Y4E.js";import"./chunk-QPNYOR6O.js";import"./chunk-JGEJY7AC.js";import"./chunk-LBJ7EOZM.js";import{TelemetryClient}from"./chunk-QROPMCL2.js";import{require_pluralize}from"./chunk-7TRHPXCG.js";import"./chunk-VO5M6G7M.js";import"./chunk-2ILZM77F.js";import{printError}from"./chunk-QI7BWXRV.js";import{parseArguments,takeCommand}from"./chunk-E7ICSU45.js";import{AGENT_REASON}from"./chunk-3QTP26QS.js";import{validateJsonOutput}from"./chunk-BDLZ6WL2.js";import"./chunk-GOXGA37R.js";import{isAPIError}from"./chunk-UNAQQ5DF.js";import"./chunk-EFGZK6OY.js";import"./chunk-JCDPMWKO.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import"./chunk-7Y572CPZ.js";import"./chunk-BVFFSUG3.js";import"./chunk-4SIQE2W4.js";import"./chunk-MF43WTDT.js";import"./chunk-FUH5PBGR.js";import"./chunk-7TREJIPV.js";import"./chunk-7QHUMMBA.js";import"./chunk-AUCQKYL2.js";import{getFlagsSpecification}from"./chunk-CUO3CYU3.js";import"./chunk-2BKALEOP.js";import"./chunk-UJ7YUIEJ.js";import"./chunk-L6MWUMWZ.js";import"./chunk-L4CSJDG7.js";import"./chunk-YHZXIBS7.js";import"./chunk-LPYHYTYI.js";import{__toESM}from"./chunk-NBPLUP7C.js";var import_pluralize=__toESM(require_pluralize(),1);function encodeBudgetAlertsCursor(value){return Buffer.from(JSON.stringify({c:value.cursor,t:value.teamId,o:value.owner==="organization"?value.owner:void 0,s:value.since,u:value.until,sc:value.selector?.scope,si:value.selector&&"scopeId"in value.selector?value.selector.scopeId:void 0})).toString("base64url")}function decodeBudgetAlertsCursor(value){if(value===void 0)return{valid:!0,value:void 0};let invalid={valid:!1,code:"INVALID_NEXT",message:INVALID_NEXT_MESSAGE},raw;try{raw=JSON.parse(Buffer.from(value,"base64url").toString("utf8"))}catch{return invalid}if(typeof raw!="object"||raw===null)return invalid;let{c,t,o,s,u,sc,si}=raw;if(typeof c!="string"||typeof t!="string"||!(o===void 0||o==="organization"&&sc==="organization"&&si===void 0)||!isOptionalMs(s)||!isOptionalMs(u)||!(sc===void 0||isBudgetScope(sc)||isScopeList(sc))||!(si===void 0||typeof si=="string"&&isBudgetScope(sc)))return invalid;let selector;return isScopeList(sc)?selector={scope:sc}:isBudgetScope(sc)&&(selector=si===void 0?{scope:sc}:{scope:sc,scopeId:si}),o==="organization"?{valid:!0,value:{cursor:c,teamId:t,owner:o,since:s,until:u,selector:{scope:"organization",orgId:t}}}:{valid:!0,value:{cursor:c,teamId:t,since:s,until:u,selector}}}function isScopeList(value){return Array.isArray(value)&&value.length>0&&value.every(isBudgetScope)}function isOptionalMs(value){return value===void 0||Number.isFinite(value)}var BudgetAlertsTelemetryClient=class extends TelemetryClient{trackCliOptionOrganization(organization){organization&&this.trackCliOption({option:"organization",value:this.redactedValue})}trackCliOptionProject(project){project&&this.trackCliOption({option:"project",value:this.redactedValue})}trackCliOptionType(types){types?.length&&this.trackCliOption({option:"type",value:types.join(",")})}trackCliOptionProduct(product){product&&this.trackCliOption({option:"product",value:this.redactedValue})}trackCliSubcommandList(actual){this.trackCliSubcommand({subcommand:"list",value:actual})}trackCliOptionSince(since){since&&this.trackCliOption({option:"since",value:this.redactedValue})}trackCliOptionUntil(until){until&&this.trackCliOption({option:"until",value:this.redactedValue})}trackCliOptionLimit(limit){limit!==void 0&&this.trackCliOption({option:"limit",value:String(limit)})}trackCliOptionNext(next){next&&this.trackCliOption({option:"next",value:this.redactedValue})}trackCliOptionFormat(format){format&&this.trackCliOption({option:"format",value:format})}trackCliFlagJson(json){json&&this.trackCliFlag("json")}};async function alerts(client,argv){let telemetry=new BudgetAlertsTelemetryClient({opts:{store:client.telemetryEventStore}}),action,parsedArgs,flagsSpecification=getFlagsSpecification(alertsSubcommand.options);try{let selected=takeCommand(argv,flagsSpecification);action=getSubcommand(selected.command?[selected.command]:[],{list:getCommandAliases(alertsListSubcommand)}),parsedArgs=parseArguments(action.subcommand?selected.args:argv,flagsSpecification)}catch(error){return printError(error),2}let{flags:opts,args}=parsedArgs;action.subcommand==="list"&&telemetry.trackCliSubcommandList(action.subcommandOriginal);let formatResult=validateJsonOutput(opts);if(!formatResult.valid)return output_manager_default.error(formatResult.error),2;let asJson=formatResult.jsonOutput;if(rejectUnexpectedArgs(args,"billing budgets alerts"))return 2;let scopeArgs=parseBudgetFilterOptions(opts);if("error"in scopeArgs)return outputError(client,asJson,"INVALID_ARGUMENTS",scopeArgs.error);trackScopeOptions(telemetry,opts),telemetry.trackCliOptionType(opts["--type"]),telemetry.trackCliOptionSince(opts["--since"]),telemetry.trackCliOptionUntil(opts["--until"]),telemetry.trackCliOptionLimit(opts["--limit"]),telemetry.trackCliOptionNext(opts["--next"]),telemetry.trackCliOptionFormat(opts["--format"]?"json":void 0),telemetry.trackCliFlagJson(opts["--json"]);let nextResult=decodeBudgetAlertsCursor(opts["--next"]);if(!nextResult.valid)return handleValidationError(nextResult,asJson,client);let cursor=nextResult.value,{types}=scopeArgs.value;if(cursor&&types&&!sameSelector(cursor.selector,{scope:types}))return outputError(client,asJson,"INVALID_NEXT",OTHER_FILTER_CURSOR);let warnings=[],limit=opts["--limit"];if(typeof limit=="number"&&Number.isInteger(limit)&&limit>MAX_LIST_LIMIT){let message=`--limit ${limit} is above the maximum of ${MAX_LIST_LIMIT}. Using ${MAX_LIST_LIMIT}.`;warnings.push({reason:AGENT_REASON.LIMIT_CLAMPED,message}),asJson||output_manager_default.warning(message),limit=MAX_LIST_LIMIT}let limitResult=validateOptionalIntegerRange(limit,{flag:"--limit",min:1,max:MAX_LIST_LIMIT});if(!limitResult.valid)return handleValidationError(limitResult,asJson,client);let sinceResult=validateTimeBound(opts["--since"]);if(!sinceResult.valid)return handleValidationError(sinceResult,asJson,client);let untilResult=validateTimeBound(opts["--until"]);if(!untilResult.valid)return handleValidationError(untilResult,asJson,client);let order=validateTimeOrder(sinceResult.value,untilResult.value);if(!order.valid)return handleValidationError(order,asJson,client);let resolvedOwner=await resolveBudgetOwner(client,scopeArgs.value.input??(cursor?.owner==="organization"?{scope:"organization",value:cursor.teamId}:null));if(!resolvedOwner)return 2;if("error"in resolvedOwner)return outputError(client,asJson,resolvedOwner.usage?"INVALID_ARGUMENTS":"API_ERROR",resolvedOwner.error);let owner=resolvedOwner.value;if(cursor&&cursor.teamId!==owner.id)return outputError(client,asJson,"INVALID_NEXT",`This --next cursor is from another team or organization, not ${owner.slug}. Use the --scope or --organization it was printed with.`);let since=cursor?cursor.since:sinceResult.value?.getTime(),until=cursor?cursor.until:untilResult.value?.getTime();output_manager_default.spinner("Fetching budget alerts\u2026");let resolved=cursor&&!scopeArgs.value.input&&!scopeArgs.value.types?{value:cursorFilter(owner,cursor.selector)}:await resolveBudgetFilter(client,owner,scopeArgs.value);if("error"in resolved)return output_manager_default.stopSpinner(),outputError(client,asJson,resolved.usage?"INVALID_ARGUMENTS":"API_ERROR",resolved.error);let filter=resolved.value;if(cursor&&!sameSelector(cursor.selector,filter.selector))return output_manager_default.stopSpinner(),outputError(client,asJson,"INVALID_NEXT",OTHER_FILTER_CURSOR);let page;try{page=await listBudgetAlerts(client,filter.selector,{since,until,limit:limitResult.value,next:cursor?.cursor})}catch(err){if(output_manager_default.stopSpinner(),isAPIError(err))return err.code==="invalid_cursor"?outputError(client,asJson,"INVALID_NEXT",INVALID_NEXT_MESSAGE):outputError(client,asJson,err.code||"API_ERROR",err.message);throw err}let names=await loadScopeNames(client,owner,page.data);output_manager_default.stopSpinner();let next=page.next?encodeBudgetAlertsCursor({cursor:page.next,teamId:owner.id,owner:owner.type,since,until,selector:filter.selector}):null;if(asJson)return client.stdout.write(`${JSON.stringify({...ownerJson(owner),...filter.selector?{filter:filter.json}:{},alerts:page.data.map(alert=>budgetAlertJson(alert,scopeNameOf(names,alert))),pagination:{next},...warnings.length>0?{warnings}:{}},null,2)}
8
8
  `),0;let{where}=filter;return page.data.length===0?(output_manager_default.log(cursor?`No more budget alerts ${where}.`:`No budget alerts found ${where}.`),0):(output_manager_default.log(`${(0,import_pluralize.default)("budget alert",page.data.length,!0)} ${where}`),client.stdout.write(printBudgetAlertsTable(page.data,names)),next&&printNextPageCommand(getNextPageCommand(client.argv,next,WINDOW_FLAGS)),0)}function cursorFilter(owner,selector){if(owner.type==="organization")return organizationTarget(owner);if(!selector)return typeFilter(owner,null);if(Array.isArray(selector.scope))return typeFilter(owner,selector.scope);let{scope}=selector,scopeId="scopeId"in selector?selector.scopeId:void 0;return{selector,args:"",where:scopeId?`on ${scope} ${scopeId}`:`on ${scope}`,json:{scope,scopeId:scopeId??null,name:null}}}var OTHER_FILTER_CURSOR="This --next cursor is from a list with a different --type, --organization, --project, or --product. Use the options it was printed with.";function sameSelector(a,b){return queryKey(a)===queryKey(b)}function queryKey(query){return query?Array.isArray(query.scope)?query.scope.join(","):"scopeId"in query&&query.scopeId?`${query.scope}:${query.scopeId}`:query.scope:""}var WINDOW_FLAGS=["--since","-s","--until","-u"];export{alerts 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{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-JZIVQAEF.js";import{outputError}from"./chunk-6JY43KSR.js";import"./chunk-3WXQHKSS.js";import"./chunk-FIICEEXO.js";import"./chunk-RFD7CEL6.js";import{buildSubcommand}from"./chunk-CHTFRAXA.js";import"./chunk-T2IZUTGY.js";import"./chunk-3F3WNT5K.js";import"./chunk-P7GA2C6N.js";import"./chunk-GTZ6ASHD.js";import"./chunk-4YGSXM2T.js";import"./chunk-SUD5V67L.js";import"./chunk-7TRHPXCG.js";import"./chunk-VO5M6G7M.js";import"./chunk-QRPBDCDH.js";import"./chunk-2GXP676X.js";import"./chunk-K5GE24PG.js";import"./chunk-IFMPBA4K.js";import"./chunk-KHJWQ4WP.js";import"./chunk-MY4MONOH.js";import"./chunk-YATYCZQJ.js";import"./chunk-2ILZM77F.js";import{printError}from"./chunk-QI7BWXRV.js";import{parseArguments}from"./chunk-E7ICSU45.js";import{AGENT_REASON,buildCommandWithGlobalFlags,outputAgentError}from"./chunk-3QTP26QS.js";import"./chunk-BDLZ6WL2.js";import"./chunk-PH2MLBQO.js";import"./chunk-DCFCPAFQ.js";import"./chunk-GOXGA37R.js";import"./chunk-UNAQQ5DF.js";import"./chunk-EFGZK6OY.js";import"./chunk-JCDPMWKO.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import"./chunk-7Y572CPZ.js";import"./chunk-BVFFSUG3.js";import"./chunk-RRX2AMWY.js";import"./chunk-GUFRGEM5.js";import"./chunk-SUT2PTL3.js";import"./chunk-AX6UCTOC.js";import"./chunk-4SIQE2W4.js";import"./chunk-MF43WTDT.js";import"./chunk-AUCQKYL2.js";import{getFlagsSpecification}from"./chunk-CUO3CYU3.js";import"./chunk-2BKALEOP.js";import"./chunk-UJ7YUIEJ.js";import"./chunk-L6MWUMWZ.js";import"./chunk-L4CSJDG7.js";import"./chunk-YHZXIBS7.js";import"./chunk-LPYHYTYI.js";import"./chunk-NBPLUP7C.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} buildx build ${ref}`);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} build ${ref}`);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};
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-OIIOMP67.js";import{outputError}from"./chunk-6JY43KSR.js";import"./chunk-3WXQHKSS.js";import"./chunk-FIICEEXO.js";import"./chunk-RFD7CEL6.js";import{buildSubcommand}from"./chunk-CHTFRAXA.js";import"./chunk-T2IZUTGY.js";import"./chunk-3F3WNT5K.js";import"./chunk-P7GA2C6N.js";import"./chunk-H3HSH5FW.js";import"./chunk-H4BQDKOU.js";import"./chunk-SUD5V67L.js";import"./chunk-7TRHPXCG.js";import"./chunk-VO5M6G7M.js";import"./chunk-QRPBDCDH.js";import"./chunk-2GXP676X.js";import"./chunk-K5GE24PG.js";import"./chunk-IFMPBA4K.js";import"./chunk-KHJWQ4WP.js";import"./chunk-MY4MONOH.js";import"./chunk-YATYCZQJ.js";import"./chunk-2ILZM77F.js";import{printError}from"./chunk-QI7BWXRV.js";import{parseArguments}from"./chunk-E7ICSU45.js";import{AGENT_REASON,buildCommandWithGlobalFlags,outputAgentError}from"./chunk-3QTP26QS.js";import"./chunk-BDLZ6WL2.js";import"./chunk-PH2MLBQO.js";import"./chunk-DCFCPAFQ.js";import"./chunk-GOXGA37R.js";import"./chunk-UNAQQ5DF.js";import"./chunk-EFGZK6OY.js";import"./chunk-JCDPMWKO.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import"./chunk-7Y572CPZ.js";import"./chunk-BVFFSUG3.js";import"./chunk-RRX2AMWY.js";import"./chunk-GUFRGEM5.js";import"./chunk-SUT2PTL3.js";import"./chunk-AX6UCTOC.js";import"./chunk-4SIQE2W4.js";import"./chunk-MF43WTDT.js";import"./chunk-AUCQKYL2.js";import{getFlagsSpecification}from"./chunk-CUO3CYU3.js";import"./chunk-2BKALEOP.js";import"./chunk-UJ7YUIEJ.js";import"./chunk-L6MWUMWZ.js";import"./chunk-L4CSJDG7.js";import"./chunk-YHZXIBS7.js";import"./chunk-LPYHYTYI.js";import"./chunk-NBPLUP7C.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} buildx build ${ref}`);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} build ${ref}`);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,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{VERCEL_CONFIG_EXTENSIONS,VERCEL_DIR,localConfigFlagPath}from"./chunk-4YGSXM2T.js";import{ConflictingConfigFiles,DeprecatedNowJson}from"./chunk-UNAQQ5DF.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import{require_build_utils}from"./chunk-BVFFSUG3.js";import{__commonJS,__require,__toESM}from"./chunk-NBPLUP7C.js";var require_main=__commonJS({"../../node_modules/.pnpm/dotenv@4.0.0/node_modules/dotenv/lib/main.js"(exports,module){"use strict";var fs=__require("fs");function parse(src){var obj={};return src.toString().split(`
7
+ import{VERCEL_CONFIG_EXTENSIONS,VERCEL_DIR,localConfigFlagPath}from"./chunk-H4BQDKOU.js";import{ConflictingConfigFiles,DeprecatedNowJson}from"./chunk-UNAQQ5DF.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import{require_build_utils}from"./chunk-BVFFSUG3.js";import{__commonJS,__require,__toESM}from"./chunk-NBPLUP7C.js";var require_main=__commonJS({"../../node_modules/.pnpm/dotenv@4.0.0/node_modules/dotenv/lib/main.js"(exports,module){"use strict";var fs=__require("fs");function parse(src){var obj={};return src.toString().split(`
8
8
  `).forEach(function(line){var keyValueArr=line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/);if(keyValueArr!=null){var key=keyValueArr[1],value=keyValueArr[2]?keyValueArr[2]:"",len=value?value.length:0;len>0&&value.charAt(0)==='"'&&value.charAt(len-1)==='"'&&(value=value.replace(/\\n/gm,`
9
9
  `)),value=value.replace(/(^['"]|['"]$)/g,"").trim(),obj[key]=value}}),obj}function config(options){var path=".env",encoding="utf8";options&&(options.path&&(path=options.path),options.encoding&&(encoding=options.encoding));try{var parsedObj=parse(fs.readFileSync(path,{encoding}));return Object.keys(parsedObj).forEach(function(key){process.env[key]=process.env[key]||parsedObj[key]}),{parsed:parsedObj}}catch(e){return{error:e}}}module.exports.config=config;module.exports.load=config;module.exports.parse=parse}});var import_dotenv=__toESM(require_main(),1);import{mkdir,readFile,writeFile,unlink,access}from"fs/promises";import{join,basename}from"path";import{fork}from"child_process";async function loadEsbuild(){let nativeLoader=Reflect.get(globalThis,Symbol.for("vercel.cli.loadEsbuild"));return typeof nativeLoader=="function"?nativeLoader():import("esbuild")}var import_build_utils=__toESM(require_build_utils(),1);function toRouteFormat(item){if("src"in item)return item;let{source,destination,headers,statusCode,permanent,...rest}=item,route={src:source,...rest};return destination&&(route.dest=destination),headers&&(route.headers=Object.fromEntries(headers.map(h=>[h.key,h.value]))),statusCode!==void 0?route.status=statusCode:permanent!==void 0&&(route.status=permanent?308:307),route}function normalizeConfig(config){let normalized={...config},{rewrites,redirects,headers}=normalized,allRoutes=normalized.routes||[],hasRoutes=allRoutes.length>0,hasRewrites=(rewrites?.length??0)>0,hasRedirects=(redirects?.length??0)>0,hasHeaders=(headers?.length??0)>0;function hasRouteFormat(items){return items?.some(item=>"src"in item)??!1}if(hasRoutes&&(hasRewrites||hasRedirects||hasHeaders))return normalized;let shouldConvertRewrites=hasRewrites&&hasRouteFormat(rewrites),shouldConvertRedirects=hasRedirects&&hasRouteFormat(redirects),shouldConvertHeaders=hasHeaders&&hasRouteFormat(headers);if((shouldConvertRewrites||shouldConvertRedirects||shouldConvertHeaders)&&(hasRewrites&&!shouldConvertRewrites||hasRedirects&&!shouldConvertRedirects||hasHeaders&&!shouldConvertHeaders))throw new import_build_utils.NowBuildError({code:"INVALID_VERCEL_CONFIG",message:"Transforms (e.g., requestHeaders) require the `routes` format, which cannot be used alongside `rewrites`, `redirects`, or `headers`. Move everything into the `routes` array instead.",link:"https://vercel.com/docs/projects/project-configuration#routes"});return rewrites&&shouldConvertRewrites&&(allRoutes=[...allRoutes,...rewrites.map(toRouteFormat)],delete normalized.rewrites),redirects&&shouldConvertRedirects&&(allRoutes=[...allRoutes,...redirects.map(redirect=>{let route=toRouteFormat(redirect);return!("src"in redirect)&&route.status===void 0&&(route.status=308),route})],delete normalized.redirects),headers&&shouldConvertHeaders&&(allRoutes=[...allRoutes,...headers.map(toRouteFormat)],delete normalized.headers),allRoutes.length>0&&(normalized.routes=allRoutes.map(toRouteFormat)),normalized}async function fileExists(filePath){try{return await access(filePath),!0}catch{return!1}}async function findAllVercelConfigFiles(workPath){let foundFiles=[];for(let ext of VERCEL_CONFIG_EXTENSIONS){let configPath=join(workPath,`vercel.${ext}`);await fileExists(configPath)&&foundFiles.push(configPath)}return foundFiles}async function findSourceVercelConfigFile(workPath){for(let ext of VERCEL_CONFIG_EXTENSIONS){let configPath=join(workPath,`vercel.${ext}`);if(await fileExists(configPath))return basename(configPath)}let tomlPath=join(workPath,"vercel.toml");return await fileExists(tomlPath)?"vercel.toml":null}async function findVercelConfigFile(workPath){let foundFiles=await findAllVercelConfigFiles(workPath);if(foundFiles.length>1)throw new ConflictingConfigFiles(foundFiles,"Multiple vercel config files found. Please use only one configuration file.","https://vercel.com/docs/projects/project-configuration");return foundFiles[0]||null}function parseConfigLoaderError(stderr){if(!stderr.trim())return"";let moduleNotFoundMatch=stderr.match(/Error \[ERR_MODULE_NOT_FOUND\]: Cannot find package '([^']+)'/);if(moduleNotFoundMatch)return`Cannot find package '${moduleNotFoundMatch[1]}'. Make sure it's installed in your project dependencies.`;let syntaxErrorMatch=stderr.match(/SyntaxError: (.+?)(?:\n|$)/);if(syntaxErrorMatch)return`Syntax error: ${syntaxErrorMatch[1]}`;let errorMatch=stderr.match(/^(?:Error|TypeError|ReferenceError): (.+?)(?:\n|$)/m);return errorMatch?errorMatch[1]:stderr.trim()}async function compileVercelConfig(workPath){let explicitConfigPath=localConfigFlagPath();if(explicitConfigPath)return{configPath:explicitConfigPath,wasCompiled:!1};let vercelJsonPath=join(workPath,"vercel.json"),nowJsonPath=join(workPath,"now.json"),vercelTomlPath=join(workPath,"vercel.toml"),hasVercelJson=await fileExists(vercelJsonPath),hasNowJson=await fileExists(nowJsonPath),hasVercelToml=await fileExists(vercelTomlPath),vercelConfigPath=await findVercelConfigFile(workPath),vercelDir=join(workPath,VERCEL_DIR),compiledConfigPath=join(vercelDir,"vercel.json");if(hasNowJson)throw new DeprecatedNowJson(nowJsonPath);let foundConfigs=[];if(hasVercelJson&&foundConfigs.push(vercelJsonPath),hasVercelToml&&foundConfigs.push(vercelTomlPath),vercelConfigPath&&foundConfigs.push(vercelConfigPath),foundConfigs.length>1)throw new ConflictingConfigFiles(foundConfigs,`Multiple config files found: ${foundConfigs.map(f=>basename(f)).join(", ")}. Please use only one configuration method.`,"https://vercel.com/docs/projects/project-configuration");if(!vercelConfigPath&&!hasVercelToml)return hasVercelJson?{configPath:vercelJsonPath,wasCompiled:!1}:await fileExists(compiledConfigPath)?{configPath:compiledConfigPath,wasCompiled:!0,sourceFile:await findSourceVercelConfigFile(workPath)??void 0}:{configPath:null,wasCompiled:!1};if(hasVercelToml)try{let{parse:tomlParse}=await import("./dist-S7GEJ656.js"),tomlContent=await readFile(vercelTomlPath,"utf8"),config=tomlParse(tomlContent),normalizedConfig=normalizeConfig(config);return await mkdir(vercelDir,{recursive:!0}),await writeFile(compiledConfigPath,JSON.stringify(normalizedConfig,null,2),"utf-8"),output_manager_default.debug(`Compiled ${vercelTomlPath} -> ${compiledConfigPath}`),{configPath:compiledConfigPath,wasCompiled:!0,sourceFile:"vercel.toml"}}catch(error){throw new import_build_utils.NowBuildError({code:error.code??"vercel_toml_parse_failed",message:`Failed to parse vercel.toml: ${error.message}`,link:error.link??"https://vercel.com/docs/projects/project-configuration"})}let sourceConfigPath=vercelConfigPath;(0,import_dotenv.config)({path:join(workPath,".env")}),(0,import_dotenv.config)({path:join(workPath,".env.local")});let tempOutPath=join(vercelDir,"vercel-temp.mjs"),loaderPath=join(vercelDir,"vercel-loader.mjs");try{let{build}=await loadEsbuild();await mkdir(vercelDir,{recursive:!0}),await build({entryPoints:[sourceConfigPath],bundle:!0,platform:"node",format:"esm",outfile:tempOutPath,packages:"external",target:"node20",sourcemap:"inline"}),await writeFile(loaderPath,`
10
10
  import { pathToFileURL } from 'url';
@@ -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{pull}from"./chunk-XBMLLP4J.js";import{indent_default}from"./chunk-GZNDA6SV.js";import{getLinkedProject,warnEnvFileSymlink}from"./chunk-4YGSXM2T.js";import{EnvFileSymlinkError}from"./chunk-UNAQQ5DF.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import{require_source}from"./chunk-UJ7YUIEJ.js";import{__toESM}from"./chunk-NBPLUP7C.js";async function createBlobStore(client,input,accountId,requestOptions){let result=await client.fetch("/v1/storage/stores/blob",{...requestOptions,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(input),accountId});if(!result.store?.id)throw new Error("Blob creation returned no store ID.");return{id:result.store.id,region:result.store.region}}async function connectResourceToProject(client,projectId,storeId,environments,options){let path=`/v1/storage/stores/${encodeURIComponent(storeId)}/connections`;return client.fetch(path,{retry:options?.retry,bailOn429:options?.bailOn429,signal:options?.signal,json:!0,method:"POST",body:{envVarEnvironments:environments,projectId,type:"integration",...options?.envVarPrefix!==void 0?{envVarPrefix:options.envVarPrefix}:{}},accountId:options?.accountId})}var import_chalk=__toESM(require_source(),1);var VALID_ENVIRONMENTS=["production","preview","development"],ENV_PULL_FAILED_MESSAGE="Failed to pull environment variables. You can run `vercel env pull` manually.";function validateEnvironments(environments){let invalid=environments.filter(env=>!VALID_ENVIRONMENTS.includes(env));return invalid.length>0?{valid:!1,invalid}:{valid:!0}}async function postProvisionSetup(client,resourceName,resourceId,contextName,options={}){let dashboardUrl=options.integrationSlug&&options.installationId?`https://vercel.com/d/dashboard/integrations/${options.integrationSlug}/${options.installationId}/resources/${resourceId}`:`https://vercel.com/${contextName}/~/stores/integration/${resourceId}`;output_manager_default.log(indent_default(`Dashboard: ${output_manager_default.link(dashboardUrl,dashboardUrl,{fallback:!1})}`,4));let baseResult={exitCode:0,dashboardUrl,connected:!1,environments:[],envPulled:!1};if(options.noConnect)return baseResult;let linkedProject=await getLinkedProject(client);if(linkedProject.status==="error")return{...baseResult,exitCode:linkedProject.exitCode};if(linkedProject.status==="not_linked")return baseResult;let{project}=linkedProject,environments=[...new Set(options.environments&&options.environments.length>0?options.environments:[...VALID_ENVIRONMENTS])];output_manager_default.debug(`Selected environments: ${JSON.stringify(environments)}`),output_manager_default.spinner(`Connecting ${import_chalk.default.bold(resourceName)} to ${import_chalk.default.bold(project.name)}...`),output_manager_default.debug(`Connecting resource ${resourceId} to project ${project.id}`);try{await connectResourceToProject(client,project.id,resourceId,environments,options.prefix?{envVarPrefix:options.prefix}:void 0)}catch(error){return output_manager_default.stopSpinner(),options.onProjectConnectFailed?.(project.id,error),output_manager_default.error(`Failed to connect: ${error.message}`),{...baseResult,exitCode:1,project:{id:project.id,name:project.name},environments,connectError:error.message}}output_manager_default.stopSpinner(),output_manager_default.log(`${import_chalk.default.bold(resourceName)} successfully connected to ${import_chalk.default.bold(project.name)}`),options.onProjectConnected?.(project.id);let envPulled=!1;if(!options.noEnvPull)try{await pull(client,["--yes"],"vercel-cli:integration:add")!==0?output_manager_default.warn(ENV_PULL_FAILED_MESSAGE):envPulled=!0}catch(err){if(!(err instanceof EnvFileSymlinkError))throw err;warnEnvFileSymlink(client,err)}return{...baseResult,project:{id:project.id,name:project.name},connected:!0,environments,envPulled}}async function getLinkedProjectField(client,noConnect,field="name"){if(noConnect)return{value:void 0};let linkedProject=await getLinkedProject(client);return linkedProject.status==="error"?{value:void 0,exitCode:linkedProject.exitCode}:linkedProject.status==="linked"?{value:linkedProject.project[field]}:{value:void 0}}export{createBlobStore,connectResourceToProject,VALID_ENVIRONMENTS,ENV_PULL_FAILED_MESSAGE,validateEnvironments,postProvisionSetup,getLinkedProjectField};
7
+ import{pull}from"./chunk-PUNGYINC.js";import{indent_default}from"./chunk-GZNDA6SV.js";import{getLinkedProject,warnEnvFileSymlink}from"./chunk-H4BQDKOU.js";import{EnvFileSymlinkError}from"./chunk-UNAQQ5DF.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import{require_source}from"./chunk-UJ7YUIEJ.js";import{__toESM}from"./chunk-NBPLUP7C.js";async function createBlobStore(client,input,accountId,requestOptions){let result=await client.fetch("/v1/storage/stores/blob",{...requestOptions,method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(input),accountId});if(!result.store?.id)throw new Error("Blob creation returned no store ID.");return{id:result.store.id,region:result.store.region}}async function connectResourceToProject(client,projectId,storeId,environments,options){let path=`/v1/storage/stores/${encodeURIComponent(storeId)}/connections`;return client.fetch(path,{retry:options?.retry,bailOn429:options?.bailOn429,signal:options?.signal,json:!0,method:"POST",body:{envVarEnvironments:environments,projectId,type:"integration",...options?.envVarPrefix!==void 0?{envVarPrefix:options.envVarPrefix}:{}},accountId:options?.accountId})}var import_chalk=__toESM(require_source(),1);var VALID_ENVIRONMENTS=["production","preview","development"],ENV_PULL_FAILED_MESSAGE="Failed to pull environment variables. You can run `vercel env pull` manually.";function validateEnvironments(environments){let invalid=environments.filter(env=>!VALID_ENVIRONMENTS.includes(env));return invalid.length>0?{valid:!1,invalid}:{valid:!0}}async function postProvisionSetup(client,resourceName,resourceId,contextName,options={}){let dashboardUrl=options.integrationSlug&&options.installationId?`https://vercel.com/d/dashboard/integrations/${options.integrationSlug}/${options.installationId}/resources/${resourceId}`:`https://vercel.com/${contextName}/~/stores/integration/${resourceId}`;output_manager_default.log(indent_default(`Dashboard: ${output_manager_default.link(dashboardUrl,dashboardUrl,{fallback:!1})}`,4));let baseResult={exitCode:0,dashboardUrl,connected:!1,environments:[],envPulled:!1};if(options.noConnect)return baseResult;let linkedProject=await getLinkedProject(client);if(linkedProject.status==="error")return{...baseResult,exitCode:linkedProject.exitCode};if(linkedProject.status==="not_linked")return baseResult;let{project}=linkedProject,environments=[...new Set(options.environments&&options.environments.length>0?options.environments:[...VALID_ENVIRONMENTS])];output_manager_default.debug(`Selected environments: ${JSON.stringify(environments)}`),output_manager_default.spinner(`Connecting ${import_chalk.default.bold(resourceName)} to ${import_chalk.default.bold(project.name)}...`),output_manager_default.debug(`Connecting resource ${resourceId} to project ${project.id}`);try{await connectResourceToProject(client,project.id,resourceId,environments,options.prefix?{envVarPrefix:options.prefix}:void 0)}catch(error){return output_manager_default.stopSpinner(),options.onProjectConnectFailed?.(project.id,error),output_manager_default.error(`Failed to connect: ${error.message}`),{...baseResult,exitCode:1,project:{id:project.id,name:project.name},environments,connectError:error.message}}output_manager_default.stopSpinner(),output_manager_default.log(`${import_chalk.default.bold(resourceName)} successfully connected to ${import_chalk.default.bold(project.name)}`),options.onProjectConnected?.(project.id);let envPulled=!1;if(!options.noEnvPull)try{await pull(client,["--yes"],"vercel-cli:integration:add")!==0?output_manager_default.warn(ENV_PULL_FAILED_MESSAGE):envPulled=!0}catch(err){if(!(err instanceof EnvFileSymlinkError))throw err;warnEnvFileSymlink(client,err)}return{...baseResult,project:{id:project.id,name:project.name},connected:!0,environments,envPulled}}async function getLinkedProjectField(client,noConnect,field="name"){if(noConnect)return{value:void 0};let linkedProject=await getLinkedProject(client);return linkedProject.status==="error"?{value:void 0,exitCode:linkedProject.exitCode}:linkedProject.status==="linked"?{value:linkedProject.project[field]}:{value:void 0}}export{createBlobStore,connectResourceToProject,VALID_ENVIRONMENTS,ENV_PULL_FAILED_MESSAGE,validateEnvironments,postProvisionSetup,getLinkedProjectField};
@@ -4,7 +4,7 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{require_xdg_app_paths}from"./chunk-BFS4K2RF.js";import{getNativePackageName}from"./chunk-7PK2JFEH.js";import{HOMEBREW_UPGRADE_COMMAND,execPackageManager,findTrustedExecutable,getUpdateCommandInfo,getUpgradePackageManager,isGlobal,packageManagerInvocation,requireTrustedUpgradeDirectory,trustedUpgradeEnvironment,withEnvironmentOverrides}from"./chunk-USTT3CON.js";import{withDirectoryLock}from"./chunk-TABMJZVW.js";import{progress}from"./chunk-U56NHYAH.js";import{getInstallRoot,isNativeBinaryInstall}from"./chunk-5F4RJ32E.js";import{require_semver}from"./chunk-IZV6K7RR.js";import{require_ci_info}from"./chunk-QROPMCL2.js";import{getCachedUsername,require_lib}from"./chunk-4YGSXM2T.js";import{pkg_default}from"./chunk-JCDPMWKO.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import{__commonJS,__require,__toESM}from"./chunk-NBPLUP7C.js";var require_fetch_dist_tags=__commonJS({"src/util/get-latest-version/fetch-dist-tags.cjs"(exports,module){"use strict";var https=__require("https");function fetchDistTags(name,options){let timeout=options&&options.timeout||3e3,agent=new https.Agent({keepAlive:!0,maxSockets:15}),headers={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"},url=`https://registry.npmjs.org/-/package/${name}/dist-tags`;return new Promise(resolve2=>{let timer=setTimeout(()=>{req.destroy(),resolve2(void 0)},timeout),req=https.get(url,{agent,headers},res=>{let buf="";res.on("data",chunk=>{buf+=chunk}),res.on("end",()=>{clearTimeout(timer);try{if(res.statusCode&&res.statusCode>=400){resolve2(void 0);return}resolve2(JSON.parse(buf))}catch{resolve2(void 0)}})});req.on("error",()=>{clearTimeout(timer),resolve2(void 0)})})}module.exports={fetchDistTags}}});function getWhoamiCachedAnswer(args,authConfig){return args.includes("--cached")?getCachedUsername(authConfig):void 0}var import_semver=__toESM(require_semver(),1);import{spawn}from"child_process";function renderUpgradeProgress(current,total,phase){let bar=progress(current,total);output_manager_default.spinner(bar?`Upgrading Vercel CLI [${bar}] (${current}/${total})${phase?` ${phase}`:""}`:phase||"Upgrading Vercel CLI\u2026",0)}function packageManagerEnvironment(packageManager,env){return withEnvironmentOverrides(env,getUpgradePackageManager(packageManager).env)}async function requireExecutable(name,env){let executable=await findTrustedExecutable(name,env);if(!executable)throw new Error(`${name} is not in a directory that PATH names in full`);return executable}async function execFileStdout(packageManager,args,cwd,env=trustedUpgradeEnvironment){return execPackageManager(await requireExecutable(packageManager,env),args,{cwd,env:packageManagerEnvironment(packageManager,env),timeout:15e3})}function parseVersionOutput(stdout){for(let line of[stdout.trim(),...stdout.trim().split(`
7
+ import{require_xdg_app_paths}from"./chunk-BFS4K2RF.js";import{getNativePackageName}from"./chunk-7PK2JFEH.js";import{HOMEBREW_UPGRADE_COMMAND,execPackageManager,findTrustedExecutable,getUpdateCommandInfo,getUpgradePackageManager,isGlobal,packageManagerInvocation,requireTrustedUpgradeDirectory,trustedUpgradeEnvironment,withEnvironmentOverrides}from"./chunk-CYBPBS37.js";import{withDirectoryLock}from"./chunk-TABMJZVW.js";import{progress}from"./chunk-U56NHYAH.js";import{getInstallRoot,isNativeBinaryInstall}from"./chunk-5F4RJ32E.js";import{require_semver}from"./chunk-IZV6K7RR.js";import{require_ci_info}from"./chunk-QROPMCL2.js";import{getCachedUsername,require_lib}from"./chunk-H4BQDKOU.js";import{pkg_default}from"./chunk-JCDPMWKO.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import{__commonJS,__require,__toESM}from"./chunk-NBPLUP7C.js";var require_fetch_dist_tags=__commonJS({"src/util/get-latest-version/fetch-dist-tags.cjs"(exports,module){"use strict";var https=__require("https");function fetchDistTags(name,options){let timeout=options&&options.timeout||3e3,agent=new https.Agent({keepAlive:!0,maxSockets:15}),headers={accept:"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"},url=`https://registry.npmjs.org/-/package/${name}/dist-tags`;return new Promise(resolve2=>{let timer=setTimeout(()=>{req.destroy(),resolve2(void 0)},timeout),req=https.get(url,{agent,headers},res=>{let buf="";res.on("data",chunk=>{buf+=chunk}),res.on("end",()=>{clearTimeout(timer);try{if(res.statusCode&&res.statusCode>=400){resolve2(void 0);return}resolve2(JSON.parse(buf))}catch{resolve2(void 0)}})});req.on("error",()=>{clearTimeout(timer),resolve2(void 0)})})}module.exports={fetchDistTags}}});function getWhoamiCachedAnswer(args,authConfig){return args.includes("--cached")?getCachedUsername(authConfig):void 0}var import_semver=__toESM(require_semver(),1);import{spawn}from"child_process";function renderUpgradeProgress(current,total,phase){let bar=progress(current,total);output_manager_default.spinner(bar?`Upgrading Vercel CLI [${bar}] (${current}/${total})${phase?` ${phase}`:""}`:phase||"Upgrading Vercel CLI\u2026",0)}function packageManagerEnvironment(packageManager,env){return withEnvironmentOverrides(env,getUpgradePackageManager(packageManager).env)}async function requireExecutable(name,env){let executable=await findTrustedExecutable(name,env);if(!executable)throw new Error(`${name} is not in a directory that PATH names in full`);return executable}async function execFileStdout(packageManager,args,cwd,env=trustedUpgradeEnvironment){return execPackageManager(await requireExecutable(packageManager,env),args,{cwd,env:packageManagerEnvironment(packageManager,env),timeout:15e3})}function parseVersionOutput(stdout){for(let line of[stdout.trim(),...stdout.trim().split(`
8
8
  `).reverse()])try{let value=JSON.parse(line),parsed=Array.isArray(value)&&value.length===1?value[0]:value,version=typeof parsed=="string"?parsed:typeof parsed?.data=="string"?parsed.data:void 0;if(version&&import_semver.default.valid(version))return version}catch{let version=line.trim();if(import_semver.default.valid(version))return version}}async function getLatestPackageVersion(packageManager,installArgs,cwd,global,env,bypassMinReleaseAge=!0){let packageSpecifier=installArgs.find(arg=>arg.endsWith("@latest"));if(!packageSpecifier)return;let manager=getUpgradePackageManager(packageManager),queryArgs=[...manager.metadataArgs(packageSpecifier),...bypassMinReleaseAge?manager.releaseAgeBypassArgs:[]];try{let stdout=await execFileStdout(packageManager,queryArgs,cwd,env);return parseVersionOutput(stdout)}catch(error){output_manager_default.debug(`Failed to resolve the latest Vercel CLI version: ${error instanceof Error?error.message:String(error)}`);return}}async function getInstalledPackageVersion(packageManager,installArgs,cwd,global){let packageSpecifier=installArgs.find(arg=>arg.endsWith("@latest"));if(!packageSpecifier)return;let packageName=packageSpecifier.slice(0,-7);try{let stdout=await execFileStdout(packageManager,["list",packageName,"--depth=0","--json",...global?["--global"]:[]],cwd),parsed=JSON.parse(stdout),projects=Array.isArray(parsed)?parsed:[parsed];for(let project of projects){let version=project?.dependencies?.[packageName]?.version??project?.devDependencies?.[packageName]?.version??project?.optionalDependencies?.[packageName]?.version;if(typeof version=="string"&&import_semver.default.valid(version))return version}}catch(error){output_manager_default.debug(`Failed to read the installed Vercel CLI version: ${error instanceof Error?error.message:String(error)}`)}}function isVersionCurrent(current,latest){return import_semver.default.valid(current)&&import_semver.default.valid(latest)?import_semver.default.gte(current,latest):current===latest}function pinPackageVersion(args,version){return args.map(arg=>arg.endsWith("@latest")?`${arg.slice(0,-6)}${version}`:arg)}async function getMinReleaseAgeContext(packageManager,cwd,global){let setting=packageManager==="pnpm"?"minimumReleaseAge":"min-release-age";try{let raw=(await execFileStdout(packageManager,["config","get",setting,"--json",...global?["--global"]:[]],cwd)).trim(),value=raw===""||raw==="undefined"?void 0:JSON.parse(raw);if(!(value==null||value===""||value==="undefined")){let age=typeof value=="number"||typeof value=="string"&&value.trim()!==""?Number(value):NaN;if(!Number.isFinite(age)||age<0)return`Could not determine ${packageManager}'s configured minimum release age.`;let minutes=packageManager==="pnpm"?age:age*1440,duration=minutes>0&&minutes%60===0?`${minutes/60} ${minutes===60?"hour":"hours"}`:`${minutes} ${minutes===1?"minute":"minutes"}`;return`${packageManager} ${setting} is configured to ${duration}.`}if(packageManager==="pnpm"){let version=parseVersionOutput(await execFileStdout(packageManager,["--version"],cwd));if(version&&!import_semver.default.prerelease(version)&&import_semver.default.gte(version,"11.0.0"))return`pnpm ${version} defaults to a minimum release age of 24 hours (1440 minutes); no explicit minimumReleaseAge setting was reported.`}return`${packageManager} did not report a configured minimum release age.`}catch{return`Could not determine ${packageManager}'s configured minimum release age.`}}function isMinReleaseAgeError(packageManager,stdout,stderr){let installerOutput=`${stdout}
9
9
  ${stderr}`;return packageManager==="pnpm"?installerOutput.includes("ERR_PNPM_NO_MATURE_MATCHING_VERSION")||installerOutput.includes("ERR_PNPM_NO_MATCHING_VERSION")&&installerOutput.includes("satisfies the specs but was released at"):packageManager==="npm"?/\bETARGET\b/.test(installerOutput)&&installerOutput.includes("with a date before")||/min-release-age cannot be provided/i.test(installerOutput):!1}function setMinReleaseAgeBypass(client,enabled){client.config={...client.config,updates:{...client.config.updates,bypassMinReleaseAge:enabled}},client.writeToConfigFile()}async function executeHomebrewUpgrade(env=trustedUpgradeEnvironment){let[brew,...args]=HOMEBREW_UPGRADE_COMMAND.split(" "),cwd=requireTrustedUpgradeDirectory();output_manager_default.debug(`Executing: ${HOMEBREW_UPGRADE_COMMAND}`);let executable=await requireExecutable(brew,env).catch(error=>error),result=await new Promise(resolve2=>{if(typeof executable!="string"){resolve2({code:1,spawnError:executable});return}let settled=!1,brewProcess=spawn(executable,args,{cwd,env:{...env},stdio:"inherit",shell:!1});brewProcess.on("error",spawnError=>{settled||(settled=!0,resolve2({code:1,spawnError}))}),brewProcess.on("close",code=>{settled||(settled=!0,resolve2({code:code??1}))})});return result.spawnError?(output_manager_default.error(`Failed to run Homebrew: ${result.spawnError.message}`),output_manager_default.log(`You can try running the command manually: ${HOMEBREW_UPGRADE_COMMAND}`),1):(result.code!==0&&(output_manager_default.error(`Homebrew upgrade failed with exit code ${result.code}`),output_manager_default.log(`You can try running the command manually: ${HOMEBREW_UPGRADE_COMMAND}`)),result.code)}function executeAutomaticUpgrade(client,env=trustedUpgradeEnvironment){return executeUpgrade("latest",client,!1,!0,env,"package-manager")}async function executeUpgrade(targetVersion,client,bypassMinReleaseAge=!1,explicitTarget=!1,env=trustedUpgradeEnvironment,releaseAgePolicy="newest",outcome){let totalSteps=targetVersion?2:3;renderUpgradeProgress(0,totalSteps,"Resolving installer\u2026");let{command:updateCommand,global,packageManager}=await getUpdateCommandInfo(env).catch(error=>{throw output_manager_default.stopSpinner(),error}),[command,...args]=updateCommand.split(" "),cwd=global?requireTrustedUpgradeDirectory():process.cwd(),executable=await requireExecutable(command,env).catch(error=>error),bypassArgs=getUpgradePackageManager(packageManager).releaseAgeBypassArgs;if(bypassMinReleaseAge&&bypassArgs.length===0)return output_manager_default.stopSpinner(),output_manager_default.error(`Minimum release-age bypass is not supported for ${packageManager}. Run the upgrade without --bypass-min-release-age, or configure release-age settings in ${packageManager} directly.`),1;bypassMinReleaseAge&&client&&client.config.updates?.bypassMinReleaseAge!==!0&&setMinReleaseAgeBypass(client,!0);let versionBefore=pkg_default.version,installLatestTag=explicitTarget&&targetVersion==="latest",resolvedTargetVersion=installLatestTag?void 0:targetVersion;if(targetVersion||(renderUpgradeProgress(1,totalSteps,"Checking for updates\u2026"),resolvedTargetVersion=await getLatestPackageVersion(packageManager,args,cwd,global,env,releaseAgePolicy==="newest")),!resolvedTargetVersion&&!installLatestTag)return output_manager_default.stopSpinner(),output_manager_default.error("Failed to resolve the latest Vercel CLI version."),1;if(!explicitTarget&&resolvedTargetVersion&&isVersionCurrent(versionBefore,resolvedTargetVersion))return renderUpgradeProgress(totalSteps,totalSteps),output_manager_default.stopSpinner(),output_manager_default.log(`No upgrade available. Vercel CLI is already up to date (v${versionBefore}).`),0;let installArgs=resolvedTargetVersion?pinPackageVersion(args,resolvedTargetVersion):args,shouldBypass=releaseAgePolicy==="newest"&&bypassArgs.length>0&&(bypassMinReleaseAge||client?.config.updates?.bypassMinReleaseAge===!0);shouldBypass&&(installArgs=[...installArgs,...bypassArgs]);let runInstall=currentArgs=>{let installCommand=[command,...currentArgs].join(" ");return output_manager_default.debug(`Executing: ${installCommand} (cwd: ${cwd})`),new Promise(resolve2=>{let stdout=[],stderr=[],invocation;try{if(typeof executable!="string")throw executable;invocation=packageManagerInvocation(executable,currentArgs,env)}catch(spawnError){resolve2({code:1,stdout:"",stderr:"",spawnError});return}let upgradeProcess=spawn(invocation.file,invocation.args,{cwd,env:packageManagerEnvironment(packageManager,env),stdio:["inherit","pipe","pipe"],shell:!1,windowsVerbatimArguments:invocation.windowsVerbatimArguments});upgradeProcess.stdout?.on("data",data=>{stdout.push(Uint8Array.from(data)),output_manager_default.debug(`[upgrade stdout] ${data.toString().trimEnd()}`)}),upgradeProcess.stderr?.on("data",data=>{stderr.push(Uint8Array.from(data)),output_manager_default.debug(`[upgrade stderr] ${data.toString().trimEnd()}`)});let settled=!1;upgradeProcess.on("error",spawnError=>{settled||(settled=!0,resolve2({code:1,stdout:"",stderr:"",spawnError}))}),upgradeProcess.on("close",code=>{settled||(settled=!0,resolve2({code:code??1,stdout:Buffer.concat(stdout).toString(),stderr:Buffer.concat(stderr).toString()}))})})};renderUpgradeProgress(targetVersion?1:2,totalSteps,"Installing\u2026");let result=await runInstall(installArgs),usedAllowedRelease=!1;if(result.code!==0&&!result.spawnError&&releaseAgePolicy==="newest"&&!shouldBypass&&bypassArgs.length>0&&isMinReleaseAgeError(packageManager,result.stdout,result.stderr)){let context=await getMinReleaseAgeContext(packageManager,cwd,global);output_manager_default.stopSpinner();let blockedMessage=`The package manager blocked this Vercel CLI release because of its minimum release-age setting. ${context}`;if(!client||client.nonInteractive||!client.stdin.isTTY)return output_manager_default.error(`${blockedMessage}
10
10
  To install the newest release allowed by your settings:
@@ -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{require_json_parse_better_errors}from"./chunk-K7YK4PZP.js";import{require_lib}from"./chunk-4YGSXM2T.js";import{CantParseJSONFile}from"./chunk-UNAQQ5DF.js";import{require_dist}from"./chunk-4SIQE2W4.js";import{__toESM}from"./chunk-NBPLUP7C.js";var import_fs_extra=__toESM(require_lib(),1);var import_json_parse_better_errors=__toESM(require_json_parse_better_errors(),1),import_error_utils=__toESM(require_dist(),1);async function readJSONFile(file){let content=await readFileSafe(file);if(content===null)return content;try{return(0,import_json_parse_better_errors.default)(content)}catch(error){return new CantParseJSONFile(file,(0,import_error_utils.errorToString)(error))}}async function readFileSafe(file){try{return await import_fs_extra.default.readFile(file,"utf8")}catch{return null}}export{readJSONFile};
7
+ import{require_json_parse_better_errors}from"./chunk-K7YK4PZP.js";import{require_lib}from"./chunk-H4BQDKOU.js";import{CantParseJSONFile}from"./chunk-UNAQQ5DF.js";import{require_dist}from"./chunk-4SIQE2W4.js";import{__toESM}from"./chunk-NBPLUP7C.js";var import_fs_extra=__toESM(require_lib(),1);var import_json_parse_better_errors=__toESM(require_json_parse_better_errors(),1),import_error_utils=__toESM(require_dist(),1);async function readJSONFile(file){let content=await readFileSafe(file);if(content===null)return content;try{return(0,import_json_parse_better_errors.default)(content)}catch(error){return new CantParseJSONFile(file,(0,import_error_utils.errorToString)(error))}}async function readFileSafe(file){try{return await import_fs_extra.default.readFile(file,"utf8")}catch{return null}}export{readJSONFile};
@@ -4,6 +4,6 @@ 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{readStdinToEnd}from"./chunk-DRDY2UZX.js";import{getExitCodeForErrorCode}from"./chunk-6JY43KSR.js";import{getRenamedOption,withWarnings}from"./chunk-237WN2MK.js";import{isJSONObject}from"./chunk-4YGSXM2T.js";import{AGENT_REASON,buildCommandWithGlobalFlags,getExitCodeForReason,outputAgentError}from"./chunk-3QTP26QS.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import{readFileSync}from"fs";import{resolve}from"path";var MONITORS_API={basePath:"/alerts/v3/monitors",itemKey:"monitor",listKey:"monitors",typesKey:"monitorTypes",idKey:"monitorId"},ALERT_RULES_API={basePath:"/alerts/v3/alert-rules",itemKey:"rule",listKey:"rules",typesKey:"ruleTypes",idKey:"ruleId"};function rulesCollectionPath(api,teamId,options={}){let query=new URLSearchParams({teamId});return options.limit!==void 0&&query.set("limit",String(options.limit)),options.cursor&&query.set("cursor",options.cursor),options.projectId&&query.set("projectId",options.projectId),options.type&&query.set("type",options.type),`${api.basePath}?${query.toString()}`}function rulesItemPath(api,teamId,ruleId){let query=new URLSearchParams({teamId});return`${api.basePath}/${encodeURIComponent(ruleId)}?${query.toString()}`}function ruleNotificationsPath(api,teamId,ruleId){let query=new URLSearchParams({teamId});return`${api.basePath}/${encodeURIComponent(ruleId)}/notifications?${query.toString()}`}function rulesNotificationsPath(api,teamId,options={}){let query=new URLSearchParams({teamId});return options.limit!==void 0&&query.set("limit",String(options.limit)),options.cursor&&query.set("cursor",options.cursor),`${api.basePath}/notifications?${query.toString()}`}function rulesNotificationLinksPath(api,teamId,ruleId){let query=new URLSearchParams({teamId});return`${api.basePath}/${encodeURIComponent(ruleId)}/notifications/links?${query.toString()}`}function rulesSchemaPath(api,teamId,type){let query=new URLSearchParams({teamId});return type&&query.set("type",type),`${api.basePath}/schema?${query.toString()}`}async function fetchRule(client,api,scope,ruleId){return(await client.fetch(rulesItemPath(api,scope.teamId,ruleId)))[api.itemKey]}function getIssues(error){return Array.isArray(error.issues)?error.issues.filter(issue=>isJSONObject(issue)&&typeof issue.path=="string"&&typeof issue.message=="string"):[]}function outputRulesError(client,jsonOutput,code,message,options={}){let issues=options.issues??[],issueSummary=issues.slice(0,5).map(issue=>`${issue.path||"body"}: ${issue.message}`).join("; "),exitCode=options.reason!==void 0?getExitCodeForReason(options.reason):getExitCodeForErrorCode(code);return outputAgentError(client,{status:"error",reason:options.reason??AGENT_REASON.INVALID_ARGUMENTS,message,hint:options.hint??(issueSummary||void 0)},exitCode),jsonOutput?client.stdout.write(`${JSON.stringify(withWarnings({error:{code,message,...issues.length?{issues}:{}}},options.warnings??[]),null,2)}
7
+ import{readStdinToEnd}from"./chunk-DRDY2UZX.js";import{getExitCodeForErrorCode}from"./chunk-6JY43KSR.js";import{getRenamedOption,withWarnings}from"./chunk-237WN2MK.js";import{isJSONObject}from"./chunk-H4BQDKOU.js";import{AGENT_REASON,buildCommandWithGlobalFlags,getExitCodeForReason,outputAgentError}from"./chunk-3QTP26QS.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import{readFileSync}from"fs";import{resolve}from"path";var MONITORS_API={basePath:"/alerts/v3/monitors",itemKey:"monitor",listKey:"monitors",typesKey:"monitorTypes",idKey:"monitorId"},ALERT_RULES_API={basePath:"/alerts/v3/alert-rules",itemKey:"rule",listKey:"rules",typesKey:"ruleTypes",idKey:"ruleId"};function rulesCollectionPath(api,teamId,options={}){let query=new URLSearchParams({teamId});return options.limit!==void 0&&query.set("limit",String(options.limit)),options.cursor&&query.set("cursor",options.cursor),options.projectId&&query.set("projectId",options.projectId),options.type&&query.set("type",options.type),`${api.basePath}?${query.toString()}`}function rulesItemPath(api,teamId,ruleId){let query=new URLSearchParams({teamId});return`${api.basePath}/${encodeURIComponent(ruleId)}?${query.toString()}`}function ruleNotificationsPath(api,teamId,ruleId){let query=new URLSearchParams({teamId});return`${api.basePath}/${encodeURIComponent(ruleId)}/notifications?${query.toString()}`}function rulesNotificationsPath(api,teamId,options={}){let query=new URLSearchParams({teamId});return options.limit!==void 0&&query.set("limit",String(options.limit)),options.cursor&&query.set("cursor",options.cursor),`${api.basePath}/notifications?${query.toString()}`}function rulesNotificationLinksPath(api,teamId,ruleId){let query=new URLSearchParams({teamId});return`${api.basePath}/${encodeURIComponent(ruleId)}/notifications/links?${query.toString()}`}function rulesSchemaPath(api,teamId,type){let query=new URLSearchParams({teamId});return type&&query.set("type",type),`${api.basePath}/schema?${query.toString()}`}async function fetchRule(client,api,scope,ruleId){return(await client.fetch(rulesItemPath(api,scope.teamId,ruleId)))[api.itemKey]}function getIssues(error){return Array.isArray(error.issues)?error.issues.filter(issue=>isJSONObject(issue)&&typeof issue.path=="string"&&typeof issue.message=="string"):[]}function outputRulesError(client,jsonOutput,code,message,options={}){let issues=options.issues??[],issueSummary=issues.slice(0,5).map(issue=>`${issue.path||"body"}: ${issue.message}`).join("; "),exitCode=options.reason!==void 0?getExitCodeForReason(options.reason):getExitCodeForErrorCode(code);return outputAgentError(client,{status:"error",reason:options.reason??AGENT_REASON.INVALID_ARGUMENTS,message,hint:options.hint??(issueSummary||void 0)},exitCode),jsonOutput?client.stdout.write(`${JSON.stringify(withWarnings({error:{code,message,...issues.length?{issues}:{}}},options.warnings??[]),null,2)}
8
8
  `):output_manager_default.fatal([message,...issues.map(issue=>` ${issue.path}: ${issue.message}`)].join(`
9
9
  `)),exitCode}function handleRulesApiError(client,err,jsonOutput,warnings){let message=err.status===401?"You do not have access to monitors in this team. Ensure your role can manage Alert Rules, or pass --token and --scope.":err.status===403?err.serverMessage||"You do not have permission to manage monitors in this team.":err.status>=500?`The monitors endpoint failed (${err.status}). Re-run with --debug and share the x-vercel-id from the failed request.`:err.serverMessage||`API error (${err.status}).`;return outputRulesError(client,jsonOutput,err.code||"API_ERROR",message,{reason:err.status===401?"not_authorized":err.status===403?"forbidden":err.status===404?AGENT_REASON.NOT_FOUND:err.status===429?"rate_limited":AGENT_REASON.API_ERROR,issues:getIssues(err),warnings,hint:err.status===401||err.status===403?"Confirm the team with `vercel whoami`; use --scope <team-slug> if the monitor belongs to another team.":void 0})}var LEGACY_BODY_FIELDS=["alertTypes","customAlert","queryJsonString"];function parseRuleBodyJson(client,raw,jsonOutput,source,warnings){let parsed;try{parsed=JSON.parse(raw)}catch{return outputRulesError(client,jsonOutput,"INVALID_ARGUMENTS",source==="stdin"?"Invalid JSON from stdin.":source==="--data"?"Invalid JSON in --data.":`Invalid JSON in ${source} file.`,{warnings})}return isJSONObject(parsed)?LEGACY_BODY_FIELDS.some(field=>Object.hasOwn(parsed,field))?outputRulesError(client,jsonOutput,"LEGACY_ALERT_RULE_BODY","This body uses the previous alert-rules shape. Rewrite it using the current schema.",{hint:"Run `vercel monitors schema --type built-in` for examples.",warnings}):parsed:outputRulesError(client,jsonOutput,"INVALID_ARGUMENTS",source==="stdin"?"Stdin input must be a JSON object.":source==="--data"?"The --data value must be a JSON object.":`The ${source} file must contain a JSON object.`,{warnings})}async function readRuleBodyFromFile(client,filePath,jsonOutput,source,warnings){if(filePath==="-"){let raw2=await readStdinToEnd(client.stdin);return raw2.trim()?parseRuleBodyJson(client,raw2,jsonOutput,"stdin",warnings):outputRulesError(client,jsonOutput,"INVALID_ARGUMENTS",`No JSON received on stdin for ${source} -.`,{warnings})}let raw;try{raw=readFileSync(resolve(client.cwd,filePath),"utf8")}catch(err){let detail=err instanceof Error?err.message:String(err);return outputRulesError(client,jsonOutput,"INVALID_ARGUMENTS",`Could not read ${source} path "${filePath}": ${detail}`,{warnings})}return raw.trim()?parseRuleBodyJson(client,raw,jsonOutput,source,warnings):outputRulesError(client,jsonOutput,"INVALID_ARGUMENTS",`The ${source} path is empty: ${filePath}`,{warnings})}async function readRuleBodyFromData(client,data,jsonOutput){if(data==="-"){let raw=await readStdinToEnd(client.stdin);return raw.trim()?parseRuleBodyJson(client,raw,jsonOutput,"--data"):outputRulesError(client,jsonOutput,"INVALID_ARGUMENTS","No JSON received on stdin for --data -.")}return data.trim()?data.startsWith("@")?outputRulesError(client,jsonOutput,"INVALID_ARGUMENTS","Invalid JSON in --data. Use --file <PATH> to read from a file."):parseRuleBodyJson(client,data,jsonOutput,"--data"):outputRulesError(client,jsonOutput,"INVALID_ARGUMENTS","The --data option requires a non-empty JSON object.")}async function resolveRuleBodyInput(client,parsedFlags,jsonOutput,options){let hasFile=parsedFlags["--file"]!==void 0,hasBody=parsedFlags["--body"]!==void 0,hasData=parsedFlags["--data"]!==void 0;if(hasData&&(hasFile||hasBody))return outputRulesError(client,jsonOutput,"MUTUAL_EXCLUSIVITY",hasFile?"Cannot specify both --file and --data. Use one or the other.":"Cannot specify both --body and --data. Use --file or --data.");let fileOption=getRenamedOption(parsedFlags,"--file","--body",{json:jsonOutput});if("error"in fileOption)return outputRulesError(client,jsonOutput,hasFile&&hasBody?"MUTUAL_EXCLUSIVITY":"INVALID_ARGUMENTS",fileOption.error);let warnings=[fileOption.warning];if(fileOption.value===void 0&&!hasData)return options.required?outputRulesError(client,jsonOutput,"MISSING_ARGUMENTS",options.missingMessage??"Missing required option: --file <PATH> or --data <JSON>."):{body:void 0,warnings:[]};let body=hasData?await readRuleBodyFromData(client,parsedFlags["--data"],jsonOutput):await readRuleBodyFromFile(client,fileOption.value,jsonOutput,hasBody?"--body":"--file",warnings);return typeof body=="number"?body:{body,warnings}}function getBodyType(body){return body.type==="built-in"||body.type==="custom"?body.type:void 0}function emitRulesArgParseError(client,err,recoverWithProjectFlag){let message=err instanceof Error?err.message:String(err),projectFlagMissingArg=message.includes("--project")&&message.includes("requires argument");outputAgentError(client,{status:"error",reason:AGENT_REASON.INVALID_ARGUMENTS,message:projectFlagMissingArg?"`--project` requires a project name or id (for example `--project my-app`).":message,next:[{command:buildCommandWithGlobalFlags(client.argv,projectFlagMissingArg?recoverWithProjectFlag:"monitors --help"),when:projectFlagMissingArg?"Retry with a project name or id":"See valid `monitors` subcommands"}]},2)}export{MONITORS_API,ALERT_RULES_API,rulesCollectionPath,rulesItemPath,ruleNotificationsPath,rulesNotificationsPath,rulesNotificationLinksPath,rulesSchemaPath,fetchRule,outputRulesError,handleRulesApiError,resolveRuleBodyInput,getBodyType,emitRulesArgParseError};
@@ -4,7 +4,7 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{require_dist as require_dist2}from"./chunk-MX66ZGZL.js";import{validateConfig}from"./chunk-VSWANERN.js";import{compileVercelConfig,findSourceVercelConfigFile}from"./chunk-EQQJB7MI.js";import{init_dist,stringify}from"./chunk-XKVKG7CW.js";import{applyEdits,findNodeAtLocation,init_main,modify,parse,parseTree}from"./chunk-6G2AZBW5.js";import{require_dist}from"./chunk-P5TIDWPF.js";import{printAlignedLabel}from"./chunk-SUD5V67L.js";import{code}from"./chunk-UNAQQ5DF.js";import{link_default,output_manager_default}from"./chunk-RIXTYUYN.js";import{require_build_utils}from"./chunk-BVFFSUG3.js";import{require_source}from"./chunk-UJ7YUIEJ.js";import{__toESM}from"./chunk-NBPLUP7C.js";var import_chalk=__toESM(require_source(),1);init_main();init_dist();var import_build_utils=__toESM(require_build_utils(),1),import_fs_detectors=__toESM(require_dist(),1),import_service_topology=__toESM(require_dist2(),1);import{readFile,writeFile}from"fs/promises";import{basename}from"path";var EXPERIMENTAL_SERVICES_DOCS_URL="https://vercel.com/docs/services/experimental";async function prepareExperimentalServicesMigration(cwd,detectServicesResult){let compileResult=await compileVercelConfig(cwd);if(!compileResult.configPath)return null;let rawConfig=await readFile(compileResult.configPath,"utf8"),config=parse(rawConfig);if(!config||!(0,import_service_topology.hasLegacyServicesConfig)(config))return null;let resolvedServices=detectServicesResult?.resolved?.source==="configured"?detectServicesResult.services.filter(s=>(0,import_build_utils.isExperimentalService)(s)):void 0,plan=await(0,import_service_topology.migrateExperimentalServices)({fs:new import_fs_detectors.LocalFileSystemDetector(cwd),config,resolvedServices:resolvedServices&&resolvedServices.length>0?resolvedServices:void 0}),sourceFile=compileResult.sourceFile??basename(compileResult.configPath),preparation={plan,sourceFile,snippet:renderSnippet(sourceFile,plan)};if(plan.errors.length>0)return preparation;if(compileResult.wasCompiled)return preparation.writeBlocker=`${sourceFile} can't be updated automatically.`,preparation;let content=applyPlanToJson(rawConfig,config,plan),parseErrors=[],nextConfig=parse(content,parseErrors);if(parseErrors.length>0)return preparation.writeBlocker=`Couldn't produce a valid ${sourceFile}.`,preparation;let validationError=validateConfig(nextConfig);return validationError?(preparation.writeBlocker=validationError.message,preparation):(preparation.write={configPath:compileResult.configPath,content},preparation)}function applyPlanToJson(rawConfig,config,plan){let eol=rawConfig.includes(`\r
7
+ import{require_dist as require_dist2}from"./chunk-MX66ZGZL.js";import{validateConfig}from"./chunk-VSWANERN.js";import{compileVercelConfig,findSourceVercelConfigFile}from"./chunk-26HAXM56.js";import{init_dist,stringify}from"./chunk-XKVKG7CW.js";import{applyEdits,findNodeAtLocation,init_main,modify,parse,parseTree}from"./chunk-6G2AZBW5.js";import{require_dist}from"./chunk-P5TIDWPF.js";import{printAlignedLabel}from"./chunk-SUD5V67L.js";import{code}from"./chunk-UNAQQ5DF.js";import{link_default,output_manager_default}from"./chunk-RIXTYUYN.js";import{require_build_utils}from"./chunk-BVFFSUG3.js";import{require_source}from"./chunk-UJ7YUIEJ.js";import{__toESM}from"./chunk-NBPLUP7C.js";var import_chalk=__toESM(require_source(),1);init_main();init_dist();var import_build_utils=__toESM(require_build_utils(),1),import_fs_detectors=__toESM(require_dist(),1),import_service_topology=__toESM(require_dist2(),1);import{readFile,writeFile}from"fs/promises";import{basename}from"path";var EXPERIMENTAL_SERVICES_DOCS_URL="https://vercel.com/docs/services/experimental";async function prepareExperimentalServicesMigration(cwd,detectServicesResult){let compileResult=await compileVercelConfig(cwd);if(!compileResult.configPath)return null;let rawConfig=await readFile(compileResult.configPath,"utf8"),config=parse(rawConfig);if(!config||!(0,import_service_topology.hasLegacyServicesConfig)(config))return null;let resolvedServices=detectServicesResult?.resolved?.source==="configured"?detectServicesResult.services.filter(s=>(0,import_build_utils.isExperimentalService)(s)):void 0,plan=await(0,import_service_topology.migrateExperimentalServices)({fs:new import_fs_detectors.LocalFileSystemDetector(cwd),config,resolvedServices:resolvedServices&&resolvedServices.length>0?resolvedServices:void 0}),sourceFile=compileResult.sourceFile??basename(compileResult.configPath),preparation={plan,sourceFile,snippet:renderSnippet(sourceFile,plan)};if(plan.errors.length>0)return preparation;if(compileResult.wasCompiled)return preparation.writeBlocker=`${sourceFile} can't be updated automatically.`,preparation;let content=applyPlanToJson(rawConfig,config,plan),parseErrors=[],nextConfig=parse(content,parseErrors);if(parseErrors.length>0)return preparation.writeBlocker=`Couldn't produce a valid ${sourceFile}.`,preparation;let validationError=validateConfig(nextConfig);return validationError?(preparation.writeBlocker=validationError.message,preparation):(preparation.write={configPath:compileResult.configPath,content},preparation)}function applyPlanToJson(rawConfig,config,plan){let eol=rawConfig.includes(`\r
8
8
  `)?`\r
9
9
  `:`
10
10
  `,indent2=/^([ \t]+)\S/m.exec(rawConfig)?.[1]??" ",formattingOptions={eol,insertSpaces:!indent2.startsWith(" "),tabSize:indent2.startsWith(" ")?1:indent2.length},legacyKey=config.experimentalServices?"experimentalServices":"experimentalServicesV2",key=findNodeAtLocation(parseTree(rawConfig),[legacyKey]).parent.children[0],text=applyEdits(rawConfig,[{offset:key.offset,length:key.length,content:'"services"'}]);text=applyEdits(text,modify(text,["services"],plan.patch.services,{formattingOptions}));for(let key2 of plan.removeKeys)key2!==legacyKey&&(text=applyEdits(text,modify(text,[key2],void 0,{formattingOptions})));for(let[key2,value]of Object.entries(plan.patch.build?.env??{}))text=applyEdits(text,modify(text,["build","env",key2],value,{formattingOptions}));if(plan.patch.rewrites.length>0)if(Array.isArray(config.rewrites))for(let rewrite of plan.patch.rewrites)text=applyEdits(text,modify(text,["rewrites",-1],rewrite,{formattingOptions}));else text=applyEdits(text,modify(text,["rewrites"],plan.patch.rewrites,{formattingOptions,getInsertionIndex:keys=>keys.indexOf("services")+1}));return text.endsWith(`
@@ -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{markOnboardingSeen}from"./chunk-UGHEH4LA.js";import{isInteractiveHumanRun}from"./chunk-O256QMQM.js";import{require_open}from"./chunk-CSU46B7Q.js";import{isGuidanceEnabled}from"./chunk-TAAWMNNL.js";import{getTeams}from"./chunk-HPXRESOF.js";import{TelemetryClient}from"./chunk-QROPMCL2.js";import{createDpopKey,deleteDpopKey,deviceAccessTokenRequest,deviceAuthorizationRequest,getCachedUsername,getUser,isDpopLoginEnabled,isOAuthError,processDeviceAuthorizationResponse,processTokenResponse}from"./chunk-4YGSXM2T.js";import{printError}from"./chunk-QI7BWXRV.js";import{parseArguments}from"./chunk-E7ICSU45.js";import{getTeamByIdOrSlug}from"./chunk-3QTP26QS.js";import{humanizePath}from"./chunk-UNAQQ5DF.js";import{getCommandName}from"./chunk-EFGZK6OY.js";import{SPINNER,countRows,output_manager_default}from"./chunk-RIXTYUYN.js";import{require_dist}from"./chunk-4SIQE2W4.js";import{require_ansi_escapes}from"./chunk-MF43WTDT.js";import{require_source}from"./chunk-UJ7YUIEJ.js";import{require_strip_ansi}from"./chunk-LPYHYTYI.js";import{__toESM}from"./chunk-NBPLUP7C.js";var import_chalk3=__toESM(require_source(),1),import_error_utils=__toESM(require_dist(),1),open=__toESM(require_open(),1),import_ansi_escapes=__toESM(require_ansi_escapes(),1);import readline from"node:readline";import{KNOWN_AGENTS}from"@vercel/detect-agent";async function updateCurrentTeamAfterLogin(client,ssoTeamId){if(ssoTeamId)client.updateConfig({currentTeam:ssoTeamId});else{let user=null;try{user=await getUser(client)}catch{return output_manager_default.error("Failed to fetch the logged in user. Please try again."),1}client.updateConfig({currentTeam:user.version==="northstar"&&user.defaultTeamId?user.defaultTeamId:void 0})}}var LoginTelemetryClient=class extends TelemetryClient{trackState(...args){this.trackLoginState(...args)}trackDpopKey(storage){this.trackDpopKeyStorage(storage)}};import{performance}from"node:perf_hooks";var{waitingFrame,settledFrame,entrance,period,finishFrame,finishDuration}=(()=>{let TURN=Math.PI*2.5,SPIN2=2,BIRTH=.02,LAG=.045,GROW=.34,PEAK=TURN*2.4/SPIN2,SETTLE=.5,DRAG=3,REACH=24,LABEL_AT=1.95,TYPE=.045,FADE=.1,T0=1.56,DWELL=.8,CLIMB=.12,PUSH=.7,LATE=.5,GLOW=.3,SHEEN=.85,LEN=Math.hypot(.507,.862),LX=-.507/LEN,LZ=-.862/LEN,LIT=-LZ,S=Math.SQRT1_2,NORMALS=[[0,-1],[S,-S],[1,0],[S,S],[0,1],[-S,S],[-1,0],[-S,-S]],entrance2=2.4,period2=7,clamp2=(n,lo=0,hi=1)=>Math.min(hi,Math.max(lo,n)),smooth=n=>n*n*(3-2*n),easeOut=n=>1-(1-n)**3,lerp=(a,b,s)=>a*(1-s)+b*s,toneOf=n=>Math.max(0,Math.min(255,Math.round(n))),bit=(u,r)=>{let h=Math.imul(u,374761393)^Math.imul(r+11,668265263);return h=Math.imul(h^h>>>13,1274126177),h>>>15&1?"1":"0"},checkTime=time=>{if(typeof time!="number"||!Number.isFinite(time)||time<0)throw new RangeError("time must be a finite number of seconds >= 0")},checkLayout=(width,alignment)=>{if(width!==30&&width!==60)throw new RangeError("width must be 30 or 60");if(alignment!=="left"&&alignment!=="center")throw new RangeError("alignment must be left or center")};function rowAt(t,r){let tau=t-BIRTH-(7-r)*LAG,q=1-clamp2(tau/SPIN2),E=TURN*(8*q**3-3*q**4)/5,vE=tau>0&&tau<SPIN2?-TURN*(24*q*q-12*q**3)/(5*SPIN2):0,phi=(t-T0-(8-1-r)*CLIMB)/period2,f=phi-Math.floor(phi),w=2*Math.PI*f,turn=(1-Math.cos(w))/2,g=easeOut(clamp2(tau/GROW)),settle=1-smooth(clamp2((tau-SPIN2+SETTLE)/SETTLE));return{th:E-Math.PI*f+DWELL/2*Math.sin(w),v:vE-Math.PI/period2*(1-DWELL*Math.cos(w)),g,e:g*Math.min(1,Math.abs(vE)/PEAK+GLOW*turn),live:settle+(1-settle)*SHEEN*turn,drag:E-PUSH*(1-Math.cos(w-LATE))/2,reach:tau/.45}}let restRow=()=>({th:0,v:0,g:1,e:0,live:0,drag:0,reach:9});function labelAt(t){let mix=[];for(let i=0;i<6;i++){let start=LABEL_AT+i*TYPE;mix.push(t<start?0:smooth(clamp2((t-start)/FADE)))}return{mix,keep:t<LABEL_AT?1:1-smooth(clamp2((t-LABEL_AT)/FADE))}}function render(rows,mix,keep,width,alignment){let c=alignment==="left"?12:width/2-4,span=Math.max(c,width-c),grid=[];for(let r=0;r<8;r++){let{th,g,e,live,drag,reach}=rows[r],row=[];for(let x=0;x<width;x++){let dx=x+.5-c,nx=dx/span,k=.35+.65/(1+(dx/REACH)**2),vis=smooth(clamp2((reach-Math.abs(nx))/.3)),tone=toneOf((20+30*e*k)*(1-.72*nx*nx)*vis);row.push(tone>=3?[bit(x-Math.round(drag*DRAG*k),r),tone]:[" ",0])}if(g>0){let hw=10.5*(r+.5)/8*g,hd=8/2*g,ch=Math.min(.5*g,hw/2,hd/2),cs=Math.cos(th),sn=Math.sin(th),at=(px,pz)=>c+px*cs+pz*sn,front=244-2.6*r,fade=.5+.5*g,loop=[[-hw+ch,-hd],[hw-ch,-hd],[hw,-hd+ch],[hw,hd-ch],[hw-ch,hd],[-hw+ch,hd],[-hw,hd-ch],[-hw,-hd+ch]],faces=[];for(let i=0;i<8;i++){let[n0,n1]=NORMALS[i],nx=n0*cs+n1*sn,nz=-n0*sn+n1*cs;if(nz>=-1e-9)continue;let lit=Math.max(0,nx*LX+nz*LZ),tone;i%4===0?tone=56+(front-56)*Math.min(1,lit/LIT)+12*smooth(clamp2((lit-LIT)/(1-LIT))):i%4===2?tone=40+104*lit:tone=front+(48+207*lit**6-front)*live;let p=at(...loop[i]),q=at(...loop[(i+1)%8]);faces.push([Math.min(p,q),Math.max(p,q),tone*fade])}let lo=1/0,hi=-1/0;for(let f of faces)lo=Math.min(lo,f[0]),hi=Math.max(hi,f[1]);let first=-1,last=-1;for(let x=Math.max(0,Math.floor(lo));x<Math.min(width,Math.ceil(hi));x++){let cover=0,ink=0;for(let[l,h,tone2]of faces){let k=Math.max(0,Math.min(x+1,h)-Math.max(x,l));cover+=k,ink+=k*tone2}if(cover<.34)continue;let tone=ink/cover,cell;cover>=.72?cell=["\u2588",tone]:lo>x&&hi>=x+1?cell=["\u2590",tone]:hi<x+1&&lo<=x?cell=["\u258C",tone]:cell=["\u2588",tone*cover];let v=toneOf(cell[1]);v<=0||(row[x]=[cell[0],v],first<0&&(first=x),last=x)}first>0&&(row[first-1]=[" ",0]),last>=0&&last<width-1&&(row[last+1]=[" ",0])}grid.push(row)}let ly=7,lx=c+12;for(let x of[lx-1,lx+6,lx+7]){if(x<0||x>=width)continue;let tone=toneOf(grid[ly][x][1]*keep);grid[ly][x]=tone>=3?[grid[ly][x][0],tone]:[" ",0]}for(let i=0;i<6;i++){let m=mix[i];if(m<=0)continue;let tone=toneOf(grid[ly][lx+i][1]*(1-m)+176*m);grid[ly][lx+i]=tone>0?["Vercel"[i],tone]:[" ",0]}return grid}function waitingFrame2(time,width=60,alignment="left"){checkTime(time),checkLayout(width,alignment);let rows=[];for(let r=0;r<8;r++)rows.push(rowAt(time,r));let{mix,keep}=labelAt(time);return render(rows,mix,keep,width,alignment)}function settledFrame2(width=60,alignment="left"){return checkLayout(width,alignment),render(Array.from({length:8},restRow),[1,1,1,1,1,1],0,width,alignment)}let finishDuration2=3,STEP=1/30,COMMIT=.25,DRIVE=.4,DRIVE_PER=.6,CATCH=2.1,SEAT=.4,LET_GO=.35,RISE=.5,SPEC=1,WARM=.5,WAKE=.9,INK_AT=.3,INK_LEN=.4,PEAK_N=60*.4**2*.6**3,A=s=>1-6*s*s+8*s**3-3*s**4,B=s=>4*s**3-3*s**4,N=s=>60*s*s*(1-s)**3,IA=s=>s-2*s**3+2*s**4-.6*s**5,IB=s=>s**4-.6*s**5,IN=s=>20*s**3-45*s**4+36*s**5-10*s**6,checkProgress=progress=>{if(typeof progress!="number"||!Number.isFinite(progress)||progress<0||progress>1)throw new RangeError("progress must be a number from 0 to 1")};function plan(time){let rows=[],sx=0,sy=0;for(let r=0;r<8;r++){let a=rowAt(time,r),lead=(8-1-r)*STEP,th=a.th+a.v*lead;rows.push({a,lead,th}),sx+=Math.cos(2*th),sy+=Math.sin(2*th)}let mean=Math.atan2(sy,sx)/2,travel=mean-Math.PI*Math.floor(mean/Math.PI);for(travel<COMMIT*Math.PI&&(travel+=Math.PI);;){let drive=DRIVE+DRIVE_PER*travel/Math.PI,forward=!0;for(let row of rows){row.target=Math.PI*Math.round((row.th-travel)/Math.PI),row.from=row.th-row.target,row.k=-row.from/drive-.4*(row.a.v-CATCH);for(let i=0;i<=64&&forward;i++){let s=i/64;row.a.v*A(s)-CATCH*B(s)+row.k*N(s)>0&&(forward=!1)}}if(forward)return{rows,travel,drive,rest:7*STEP+drive+SEAT};travel+=Math.PI}}function poseAt(p,t){let handover=smooth(clamp2(t/LET_GO)),rise=smooth(clamp2(t/RISE)),drive=p.drive;return p.rows.map(({a,lead,target,from,k})=>{let tau=t-lead;if(tau>=drive+SEAT)return{...restRow(),angle:target};let u,v,env=0,wake=0;if(tau<0)u=a.th+a.v*t-target,v=a.v;else if(tau<drive){let s=tau/drive;u=from+drive*(a.v*IA(s)-CATCH*IB(s)+k*IN(s)),v=a.v*A(s)-CATCH*B(s)+k*N(s),env=N(s)/PEAK_N,wake=16*s*s*(1-s)**2}else{let x=(tau-drive)/SEAT;u=-CATCH*SEAT*x*(1-x)**3,v=-CATCH*(1-x)**2*(1-4*x)}return{th:u,v,angle:target+u,g:lerp(a.g,1,rise),e:lerp(a.e,WARM*env,handover),live:lerp(a.live,SPEC*env,handover),drag:a.drag*(1-handover)-WAKE*p.travel/Math.PI*wake,reach:lerp(Math.min(a.reach,9),9,rise)}})}function finishFrame2(time,progress,width=60,alignment="left"){if(checkTime(time),checkLayout(width,alignment),checkProgress(progress),progress===0)return waitingFrame2(time,width,alignment);let p=plan(time),t=progress*finishDuration2;if(progress===1||t>=p.rest)return settledFrame2(width,alignment);let label=labelAt(time),mix=label.mix.map((m0,i)=>lerp(m0,1,smooth(clamp2((t-INK_AT-i*TYPE)/INK_LEN))));return render(poseAt(p,t),mix,lerp(label.keep,0,smooth(clamp2(t/(INK_AT+INK_LEN)))),width,alignment)}return{waitingFrame:waitingFrame2,settledFrame:settledFrame2,entrance:entrance2,period:period2,finishFrame:finishFrame2,finishDuration:finishDuration2}})(),BREATH=.3,VISIT=.5,LEAD=.2,STATUS=.6,SPIN=BREATH+LEAD+STATUS/2,revealDuration=BREATH+LEAD+STATUS,clamp=n=>Math.min(1,Math.max(0,n)),ramp=(time,start,length)=>{let s=clamp((time-start)/length);return s*s*(3-2*s)};function revealFrame(time,reduced=!1){if(typeof time!="number"||!Number.isFinite(time))throw new TypeError("time must be a finite number of seconds");if(typeof reduced!="boolean")throw new TypeError("reduced must be a boolean");return reduced?{visit:1,status:1,spinner:!1,ready:!0}:time>=revealDuration?{visit:1,status:1,spinner:!0,ready:!0}:{visit:ramp(time,BREATH,VISIT),status:ramp(time,BREATH+LEAD,STATUS),spinner:time>=SPIN,ready:!1}}var import_chalk=__toESM(require_source(),1);function encodeGrid(grid,width,colors){return grid.map((row,y)=>{let result="",previous="";for(let x=0;x<width;x++){let[ch,n]=row[x];if(ch===" "||n===0){result+=" ";continue}if(!colors&&(ch==="0"||ch==="1")){let h=Math.imul(x+1,73244475)^Math.imul(y+1,668265261);if(h=Math.imul(h^h>>>16,73244475),((h^h>>>16)>>>0)/4294967296>=n/96){result+=" ";continue}}let style=colors?`\x1B[22;38;2;${colors.background.map((bg,i)=>Math.round(bg+(colors.foreground[i]-bg)*n/255)).join(";")}m`:n<96?"\x1B[2;39m":"\x1B[22;39m";style!==previous&&(result+=style,previous=style),result+=ch}return"\r\x1B[2K"+result.trimEnd()+`\x1B[0m
7
+ import{markOnboardingSeen}from"./chunk-R3BZ4IDA.js";import{isInteractiveHumanRun}from"./chunk-O256QMQM.js";import{require_open}from"./chunk-CSU46B7Q.js";import{isGuidanceEnabled}from"./chunk-TAAWMNNL.js";import{getTeams}from"./chunk-HPXRESOF.js";import{TelemetryClient}from"./chunk-QROPMCL2.js";import{createDpopKey,deleteDpopKey,deviceAccessTokenRequest,deviceAuthorizationRequest,getCachedUsername,getUser,isDpopLoginEnabled,isOAuthError,processDeviceAuthorizationResponse,processTokenResponse}from"./chunk-H4BQDKOU.js";import{printError}from"./chunk-QI7BWXRV.js";import{parseArguments}from"./chunk-E7ICSU45.js";import{getTeamByIdOrSlug}from"./chunk-3QTP26QS.js";import{humanizePath}from"./chunk-UNAQQ5DF.js";import{getCommandName}from"./chunk-EFGZK6OY.js";import{SPINNER,countRows,output_manager_default}from"./chunk-RIXTYUYN.js";import{require_dist}from"./chunk-4SIQE2W4.js";import{require_ansi_escapes}from"./chunk-MF43WTDT.js";import{require_source}from"./chunk-UJ7YUIEJ.js";import{require_strip_ansi}from"./chunk-LPYHYTYI.js";import{__toESM}from"./chunk-NBPLUP7C.js";var import_chalk3=__toESM(require_source(),1),import_error_utils=__toESM(require_dist(),1),open=__toESM(require_open(),1),import_ansi_escapes=__toESM(require_ansi_escapes(),1);import readline from"node:readline";import{KNOWN_AGENTS}from"@vercel/detect-agent";async function updateCurrentTeamAfterLogin(client,ssoTeamId){if(ssoTeamId)client.updateConfig({currentTeam:ssoTeamId});else{let user=null;try{user=await getUser(client)}catch{return output_manager_default.error("Failed to fetch the logged in user. Please try again."),1}client.updateConfig({currentTeam:user.version==="northstar"&&user.defaultTeamId?user.defaultTeamId:void 0})}}var LoginTelemetryClient=class extends TelemetryClient{trackState(...args){this.trackLoginState(...args)}trackDpopKey(storage){this.trackDpopKeyStorage(storage)}};import{performance}from"node:perf_hooks";var{waitingFrame,settledFrame,entrance,period,finishFrame,finishDuration}=(()=>{let TURN=Math.PI*2.5,SPIN2=2,BIRTH=.02,LAG=.045,GROW=.34,PEAK=TURN*2.4/SPIN2,SETTLE=.5,DRAG=3,REACH=24,LABEL_AT=1.95,TYPE=.045,FADE=.1,T0=1.56,DWELL=.8,CLIMB=.12,PUSH=.7,LATE=.5,GLOW=.3,SHEEN=.85,LEN=Math.hypot(.507,.862),LX=-.507/LEN,LZ=-.862/LEN,LIT=-LZ,S=Math.SQRT1_2,NORMALS=[[0,-1],[S,-S],[1,0],[S,S],[0,1],[-S,S],[-1,0],[-S,-S]],entrance2=2.4,period2=7,clamp2=(n,lo=0,hi=1)=>Math.min(hi,Math.max(lo,n)),smooth=n=>n*n*(3-2*n),easeOut=n=>1-(1-n)**3,lerp=(a,b,s)=>a*(1-s)+b*s,toneOf=n=>Math.max(0,Math.min(255,Math.round(n))),bit=(u,r)=>{let h=Math.imul(u,374761393)^Math.imul(r+11,668265263);return h=Math.imul(h^h>>>13,1274126177),h>>>15&1?"1":"0"},checkTime=time=>{if(typeof time!="number"||!Number.isFinite(time)||time<0)throw new RangeError("time must be a finite number of seconds >= 0")},checkLayout=(width,alignment)=>{if(width!==30&&width!==60)throw new RangeError("width must be 30 or 60");if(alignment!=="left"&&alignment!=="center")throw new RangeError("alignment must be left or center")};function rowAt(t,r){let tau=t-BIRTH-(7-r)*LAG,q=1-clamp2(tau/SPIN2),E=TURN*(8*q**3-3*q**4)/5,vE=tau>0&&tau<SPIN2?-TURN*(24*q*q-12*q**3)/(5*SPIN2):0,phi=(t-T0-(8-1-r)*CLIMB)/period2,f=phi-Math.floor(phi),w=2*Math.PI*f,turn=(1-Math.cos(w))/2,g=easeOut(clamp2(tau/GROW)),settle=1-smooth(clamp2((tau-SPIN2+SETTLE)/SETTLE));return{th:E-Math.PI*f+DWELL/2*Math.sin(w),v:vE-Math.PI/period2*(1-DWELL*Math.cos(w)),g,e:g*Math.min(1,Math.abs(vE)/PEAK+GLOW*turn),live:settle+(1-settle)*SHEEN*turn,drag:E-PUSH*(1-Math.cos(w-LATE))/2,reach:tau/.45}}let restRow=()=>({th:0,v:0,g:1,e:0,live:0,drag:0,reach:9});function labelAt(t){let mix=[];for(let i=0;i<6;i++){let start=LABEL_AT+i*TYPE;mix.push(t<start?0:smooth(clamp2((t-start)/FADE)))}return{mix,keep:t<LABEL_AT?1:1-smooth(clamp2((t-LABEL_AT)/FADE))}}function render(rows,mix,keep,width,alignment){let c=alignment==="left"?12:width/2-4,span=Math.max(c,width-c),grid=[];for(let r=0;r<8;r++){let{th,g,e,live,drag,reach}=rows[r],row=[];for(let x=0;x<width;x++){let dx=x+.5-c,nx=dx/span,k=.35+.65/(1+(dx/REACH)**2),vis=smooth(clamp2((reach-Math.abs(nx))/.3)),tone=toneOf((20+30*e*k)*(1-.72*nx*nx)*vis);row.push(tone>=3?[bit(x-Math.round(drag*DRAG*k),r),tone]:[" ",0])}if(g>0){let hw=10.5*(r+.5)/8*g,hd=8/2*g,ch=Math.min(.5*g,hw/2,hd/2),cs=Math.cos(th),sn=Math.sin(th),at=(px,pz)=>c+px*cs+pz*sn,front=244-2.6*r,fade=.5+.5*g,loop=[[-hw+ch,-hd],[hw-ch,-hd],[hw,-hd+ch],[hw,hd-ch],[hw-ch,hd],[-hw+ch,hd],[-hw,hd-ch],[-hw,-hd+ch]],faces=[];for(let i=0;i<8;i++){let[n0,n1]=NORMALS[i],nx=n0*cs+n1*sn,nz=-n0*sn+n1*cs;if(nz>=-1e-9)continue;let lit=Math.max(0,nx*LX+nz*LZ),tone;i%4===0?tone=56+(front-56)*Math.min(1,lit/LIT)+12*smooth(clamp2((lit-LIT)/(1-LIT))):i%4===2?tone=40+104*lit:tone=front+(48+207*lit**6-front)*live;let p=at(...loop[i]),q=at(...loop[(i+1)%8]);faces.push([Math.min(p,q),Math.max(p,q),tone*fade])}let lo=1/0,hi=-1/0;for(let f of faces)lo=Math.min(lo,f[0]),hi=Math.max(hi,f[1]);let first=-1,last=-1;for(let x=Math.max(0,Math.floor(lo));x<Math.min(width,Math.ceil(hi));x++){let cover=0,ink=0;for(let[l,h,tone2]of faces){let k=Math.max(0,Math.min(x+1,h)-Math.max(x,l));cover+=k,ink+=k*tone2}if(cover<.34)continue;let tone=ink/cover,cell;cover>=.72?cell=["\u2588",tone]:lo>x&&hi>=x+1?cell=["\u2590",tone]:hi<x+1&&lo<=x?cell=["\u258C",tone]:cell=["\u2588",tone*cover];let v=toneOf(cell[1]);v<=0||(row[x]=[cell[0],v],first<0&&(first=x),last=x)}first>0&&(row[first-1]=[" ",0]),last>=0&&last<width-1&&(row[last+1]=[" ",0])}grid.push(row)}let ly=7,lx=c+12;for(let x of[lx-1,lx+6,lx+7]){if(x<0||x>=width)continue;let tone=toneOf(grid[ly][x][1]*keep);grid[ly][x]=tone>=3?[grid[ly][x][0],tone]:[" ",0]}for(let i=0;i<6;i++){let m=mix[i];if(m<=0)continue;let tone=toneOf(grid[ly][lx+i][1]*(1-m)+176*m);grid[ly][lx+i]=tone>0?["Vercel"[i],tone]:[" ",0]}return grid}function waitingFrame2(time,width=60,alignment="left"){checkTime(time),checkLayout(width,alignment);let rows=[];for(let r=0;r<8;r++)rows.push(rowAt(time,r));let{mix,keep}=labelAt(time);return render(rows,mix,keep,width,alignment)}function settledFrame2(width=60,alignment="left"){return checkLayout(width,alignment),render(Array.from({length:8},restRow),[1,1,1,1,1,1],0,width,alignment)}let finishDuration2=3,STEP=1/30,COMMIT=.25,DRIVE=.4,DRIVE_PER=.6,CATCH=2.1,SEAT=.4,LET_GO=.35,RISE=.5,SPEC=1,WARM=.5,WAKE=.9,INK_AT=.3,INK_LEN=.4,PEAK_N=60*.4**2*.6**3,A=s=>1-6*s*s+8*s**3-3*s**4,B=s=>4*s**3-3*s**4,N=s=>60*s*s*(1-s)**3,IA=s=>s-2*s**3+2*s**4-.6*s**5,IB=s=>s**4-.6*s**5,IN=s=>20*s**3-45*s**4+36*s**5-10*s**6,checkProgress=progress=>{if(typeof progress!="number"||!Number.isFinite(progress)||progress<0||progress>1)throw new RangeError("progress must be a number from 0 to 1")};function plan(time){let rows=[],sx=0,sy=0;for(let r=0;r<8;r++){let a=rowAt(time,r),lead=(8-1-r)*STEP,th=a.th+a.v*lead;rows.push({a,lead,th}),sx+=Math.cos(2*th),sy+=Math.sin(2*th)}let mean=Math.atan2(sy,sx)/2,travel=mean-Math.PI*Math.floor(mean/Math.PI);for(travel<COMMIT*Math.PI&&(travel+=Math.PI);;){let drive=DRIVE+DRIVE_PER*travel/Math.PI,forward=!0;for(let row of rows){row.target=Math.PI*Math.round((row.th-travel)/Math.PI),row.from=row.th-row.target,row.k=-row.from/drive-.4*(row.a.v-CATCH);for(let i=0;i<=64&&forward;i++){let s=i/64;row.a.v*A(s)-CATCH*B(s)+row.k*N(s)>0&&(forward=!1)}}if(forward)return{rows,travel,drive,rest:7*STEP+drive+SEAT};travel+=Math.PI}}function poseAt(p,t){let handover=smooth(clamp2(t/LET_GO)),rise=smooth(clamp2(t/RISE)),drive=p.drive;return p.rows.map(({a,lead,target,from,k})=>{let tau=t-lead;if(tau>=drive+SEAT)return{...restRow(),angle:target};let u,v,env=0,wake=0;if(tau<0)u=a.th+a.v*t-target,v=a.v;else if(tau<drive){let s=tau/drive;u=from+drive*(a.v*IA(s)-CATCH*IB(s)+k*IN(s)),v=a.v*A(s)-CATCH*B(s)+k*N(s),env=N(s)/PEAK_N,wake=16*s*s*(1-s)**2}else{let x=(tau-drive)/SEAT;u=-CATCH*SEAT*x*(1-x)**3,v=-CATCH*(1-x)**2*(1-4*x)}return{th:u,v,angle:target+u,g:lerp(a.g,1,rise),e:lerp(a.e,WARM*env,handover),live:lerp(a.live,SPEC*env,handover),drag:a.drag*(1-handover)-WAKE*p.travel/Math.PI*wake,reach:lerp(Math.min(a.reach,9),9,rise)}})}function finishFrame2(time,progress,width=60,alignment="left"){if(checkTime(time),checkLayout(width,alignment),checkProgress(progress),progress===0)return waitingFrame2(time,width,alignment);let p=plan(time),t=progress*finishDuration2;if(progress===1||t>=p.rest)return settledFrame2(width,alignment);let label=labelAt(time),mix=label.mix.map((m0,i)=>lerp(m0,1,smooth(clamp2((t-INK_AT-i*TYPE)/INK_LEN))));return render(poseAt(p,t),mix,lerp(label.keep,0,smooth(clamp2(t/(INK_AT+INK_LEN)))),width,alignment)}return{waitingFrame:waitingFrame2,settledFrame:settledFrame2,entrance:entrance2,period:period2,finishFrame:finishFrame2,finishDuration:finishDuration2}})(),BREATH=.3,VISIT=.5,LEAD=.2,STATUS=.6,SPIN=BREATH+LEAD+STATUS/2,revealDuration=BREATH+LEAD+STATUS,clamp=n=>Math.min(1,Math.max(0,n)),ramp=(time,start,length)=>{let s=clamp((time-start)/length);return s*s*(3-2*s)};function revealFrame(time,reduced=!1){if(typeof time!="number"||!Number.isFinite(time))throw new TypeError("time must be a finite number of seconds");if(typeof reduced!="boolean")throw new TypeError("reduced must be a boolean");return reduced?{visit:1,status:1,spinner:!1,ready:!0}:time>=revealDuration?{visit:1,status:1,spinner:!0,ready:!0}:{visit:ramp(time,BREATH,VISIT),status:ramp(time,BREATH+LEAD,STATUS),spinner:time>=SPIN,ready:!1}}var import_chalk=__toESM(require_source(),1);function encodeGrid(grid,width,colors){return grid.map((row,y)=>{let result="",previous="";for(let x=0;x<width;x++){let[ch,n]=row[x];if(ch===" "||n===0){result+=" ";continue}if(!colors&&(ch==="0"||ch==="1")){let h=Math.imul(x+1,73244475)^Math.imul(y+1,668265261);if(h=Math.imul(h^h>>>16,73244475),((h^h>>>16)>>>0)/4294967296>=n/96){result+=" ";continue}}let style=colors?`\x1B[22;38;2;${colors.background.map((bg,i)=>Math.round(bg+(colors.foreground[i]-bg)*n/255)).join(";")}m`:n<96?"\x1B[2;39m":"\x1B[22;39m";style!==previous&&(result+=style,previous=style),result+=ch}return"\r\x1B[2K"+result.trimEnd()+`\x1B[0m
8
8
  `}).join("")}function createSignInWelcome(stream,closeInputOnSignal,colors=()=>{},onShown,layout){let columns=stream.columns,rows=stream.rows,width=columns>=61?60:30,footerRows=layout?.footerRows??0,ownedRows=9+footerRows,skipFooter=footerRows?`\x1B[${footerRows}B\r`:"",spinnerIndex=0,formatSpinnerFrame=()=>`${import_chalk.default.gray(SPINNER.frames[spinnerIndex])} ${import_chalk.default.gray("Waiting for authentication...")}`,spinnerFrame=formatSpinnerFrame(),spinnerUpdated=0,shown=!1,stopped=!1,failed=!1,timer,start=0,finishStart,finishFrom=0,keepFinal=!1,finishPromise,resolveFinish,receipt,receiptRows=0,receiptPrinted=!1,receiptQueued=!1,onReceiptShown,authComplete=!1,instructionsReady=!1,instructionsVisible=!1,skipCompletion=!1,finishDeadline,pendingWrites=0,release;function releaseErrorsWhenIdle(){!stopped||pendingWrites||release||(release=setImmediate(()=>{release=void 0,stopped&&!pendingWrites&&stream.removeListener("error",errored)}))}function writePacket(packet,next){pendingWrites++;try{stream.write(packet,error=>{pendingWrites--,error?errored():next?.(),releaseErrorsWhenIdle()})}catch{pendingWrites--,errored(),releaseErrorsWhenIdle()}}let stop=()=>{if(stopped)return;stopped=!0,clearTimeout(timer),clearTimeout(finishDeadline),stream.removeListener("resize",resized),process.removeListener("exit",exiting),process.removeListener("SIGINT",finishInterrupted);for(let[signal,handler]of signals)process.removeListener(signal,handler);let showInstructions=!authComplete&&layout?.instructions&&!instructionsVisible;shown&&!keepFinal&&!receiptQueued&&!failed&&stream.columns===columns&&stream.rows===rows&&writePacket(layout?`\x1B[${ownedRows}A`+`\r\x1B[2K
9
9
  `.repeat(8)+(showInstructions?layout.instructions:authComplete?`\r\x1B[2K
10
10
  `.repeat(footerRows):skipFooter)+"\r\x1B[2K\x1B[0m":"\x1B[9A"+`\r\x1B[2K
@@ -4,7 +4,7 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{require_slugify}from"./chunk-BNWEJZAC.js";import{createProject}from"./chunk-C2R5IEN6.js";import{printProjectNotFoundError}from"./chunk-O45CPVEL.js";import{canPrompt}from"./chunk-IQ7FPAI4.js";import{detectExplicitScope,getScope,resolveOrg}from"./chunk-GTZ6ASHD.js";import{getLinkedProject,getOrgById,isOwnerLookupUnavailableLink,require_dist2 as require_dist,require_lib}from"./chunk-4YGSXM2T.js";import{printAlignedLabel}from"./chunk-SUD5V67L.js";import{printError}from"./chunk-QI7BWXRV.js";import{AGENT_REASON,AGENT_STATUS,writeAgentError,writeTrackedActionRequired}from"./chunk-3QTP26QS.js";import{isAPIError}from"./chunk-UNAQQ5DF.js";import{packageName}from"./chunk-EFGZK6OY.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import{require_build_utils}from"./chunk-BVFFSUG3.js";import{normalizeFlagName,quoteArg,stripSensitiveAuthArgs}from"./chunk-CUO3CYU3.js";import{__toESM}from"./chunk-NBPLUP7C.js";var import_fs_extra=__toESM(require_lib(),1);import{readdir}from"fs/promises";import{join}from"path";function isStaticFolderDeploy(project,localConfig,rootDirectory){if(rootDirectory||localConfig.builds?.length||localConfig.routes?.length||localConfig.rewrites?.length||localConfig.proxy)return!1;let setting=key=>Object.hasOwn(localConfig,key)?localConfig[key]:project[key],outputDirectory=setting("outputDirectory");return!setting("framework")&&!setting("buildCommand")&&(!outputDirectory||outputDirectory===".")}async function aliasLonePageInOutput(outputDir){if(!await isPlainStaticOutput(outputDir))return;let staticDir=join(outputDir,"static"),entries;try{entries=(await readdir(staticDir,{recursive:!0})).map(entry=>entry.split("\\").join("/"))}catch{return}let pages=entries.filter(entry=>/\.html?$/i.test(entry));if(pages.length!==1)return;let[page]=pages;page.includes("/")||page==="index.html"||page==="index.htm"||(await import_fs_extra.default.stat(join(staticDir,page))).isFile()&&await writeIndexCopy(staticDir,page)}async function isPlainStaticOutput(outputDir){if(await import_fs_extra.default.pathExists(join(outputDir,"functions")))return!1;let readJSON=name=>import_fs_extra.default.readJSON(join(outputDir,name)).catch(()=>null),builds=(await readJSON("builds.json"))?.builds;if(!Array.isArray(builds)||builds.length===0||builds.some(build=>build?.use!=="@vercel/static"))return!1;let config=await readJSON("config.json"),routes=config?.routes??[];return!config||!Array.isArray(routes)?!1:routes.findIndex(route=>route?.handle==="error")===0||routes.length===0}async function writeIndexCopy(dir,name){let page=join(dir,name),index=join(dir,"index.html"),existing=await import_fs_extra.default.stat(index).catch(()=>null);if(existing&&existing.ino===(await import_fs_extra.default.stat(page)).ino){await import_fs_extra.default.rename(page,index);return}await import_fs_extra.default.copy(page,index)}var import_fs_extra2=__toESM(require_lib(),1),import_slugify=__toESM(require_slugify(),1),import_build_utils=__toESM(require_build_utils(),1),import_client=__toESM(require_dist(),1);import{basename,dirname,extname,isAbsolute,join as join2,relative,sep}from"path";var singleFileConfig={framework:null,buildCommand:"",installCommand:"",outputDirectory:null},singleFileProjectSettings={...singleFileConfig,rootDirectory:null};async function stageSingleFile(file,dir){let name=basename(file);await import_fs_extra2.default.copy(file,join2(dir,name)),servesAtRoot(name)&&await writeIndexCopy(dir,name)}function getSingleFileNameError(name){if(name.includes("\\"))return"Can't deploy a file with a backslash in its name. Rename the file, or deploy its directory.";if(name===".vc-config.json")return"Can't deploy a file named .vc-config.json on its own, because Vercel reads that name as a function config. Rename the file, or deploy its directory."}function servesAtRoot(name){let ext=extname(name).toLowerCase();return(ext===".html"||ext===".htm")&&name!=="index.html"&&name!=="index.htm"}async function isIgnoredFile(file,cwd){let roots=new Set([dirname(file)]),fromCwd=relative(cwd,file);fromCwd&&!fromCwd.startsWith(`..${sep}`)&&!isAbsolute(fromCwd)&&roots.add(cwd);for(let root of roots){let{ig}=await(0,import_client.getVercelIgnore)(root);if(ig.ignores(relative(root,file).split(sep).join("/")))return!0}return!1}function getSingleFileProjectName(file){return(0,import_slugify.default)(basename(file,extname(file))).slice(0,100).replace(/-+$/,"")||void 0}var PROJECT_NAME_RULES="Project names can be up to 100 characters long and must be lowercase. They can include letters, digits, and the following characters: '.', '_', '-'. However, they cannot contain the sequence '---'.";function isValidProjectName(name){return/^[a-z0-9._-]{1,100}$/.test(name)&&!name.includes("---")}var singleFileMeta={singleFile:"1"};function isStaticProject(project){if(project.framework||project.link||project.rootDirectory||project.buildCommand||project.installCommand)return!1;if(project.outputDirectory===".")return!0;if(project.outputDirectory)return!1;let served=project.targets?.production??project.latestDeployments?.[0];return!served||served.meta?.singleFile===singleFileMeta.singleFile}var PROJECT_FLAGS=["--project","--name","-n"],SCOPE_FLAGS=["--scope","--team","-S","-T"];function rawArgsWithout(client,flags){let args=stripSensitiveAuthArgs(client.argv.slice(2)),kept=[];for(let i=0;i<args.length;i++){let arg=args[i];if(flags.includes(normalizeFlagName(arg))){arg.includes("=")||i++;continue}kept.push(arg)}return kept}function argsWithout(client,flags){return rawArgsWithout(client,flags).map(quoteArg).join(" ")}function retryWithProject(client,project){return`${packageName} ${argsWithout(client,PROJECT_FLAGS)} --project ${project}`}function singleFileTargetArgs(client,link){let{org,project}=link,scope=!detectExplicitScope(client)&&org.type==="team"&&org.slug&&!isOwnerLookupUnavailableLink(link)?` --scope ${quoteArg(org.slug)}`:"";return` --project ${quoteArg(project.id)}${scope}`}async function applyNameScope(client){if(detectExplicitScope(client))return;if(client.ignoresSavedTeam){await client.resolveCurrentTeam();return}let envOrgId=(0,import_build_utils.getPlatformEnv)("ORG_ID");if(envOrgId){client.config.currentTeam=envOrgId.startsWith("team_")?envOrgId:void 0;return}if(!client.config.currentTeam)try{await getScope(client)}catch(err){output_manager_default.debug(`Using the token's scope for single-file deploys: ${err}`)}}function fail(client,asJson,{headline,detail,next=[],...failure},exitCode){if(asJson){let{status,...rest}=failure,payload={...rest,message:detail?`${headline} ${detail}`:headline,...next.length>0&&{next:next.map(({command,when})=>({command,when}))}};status===AGENT_STATUS.ERROR?writeAgentError(client,{...payload,status}):writeTrackedActionRequired(client,{...payload,status})}else{output_manager_default.fatal(detail?`${headline}
7
+ import{require_slugify}from"./chunk-BNWEJZAC.js";import{createProject}from"./chunk-C2R5IEN6.js";import{printProjectNotFoundError}from"./chunk-HPYP2LC3.js";import{canPrompt}from"./chunk-IQ7FPAI4.js";import{detectExplicitScope,getScope,resolveOrg}from"./chunk-H3HSH5FW.js";import{getLinkedProject,getOrgById,isOwnerLookupUnavailableLink,require_dist2 as require_dist,require_lib}from"./chunk-H4BQDKOU.js";import{printAlignedLabel}from"./chunk-SUD5V67L.js";import{printError}from"./chunk-QI7BWXRV.js";import{AGENT_REASON,AGENT_STATUS,writeAgentError,writeTrackedActionRequired}from"./chunk-3QTP26QS.js";import{isAPIError}from"./chunk-UNAQQ5DF.js";import{packageName}from"./chunk-EFGZK6OY.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import{require_build_utils}from"./chunk-BVFFSUG3.js";import{normalizeFlagName,quoteArg,stripSensitiveAuthArgs}from"./chunk-CUO3CYU3.js";import{__toESM}from"./chunk-NBPLUP7C.js";var import_fs_extra=__toESM(require_lib(),1);import{readdir}from"fs/promises";import{join}from"path";function isStaticFolderDeploy(project,localConfig,rootDirectory){if(rootDirectory||localConfig.builds?.length||localConfig.routes?.length||localConfig.rewrites?.length||localConfig.proxy)return!1;let setting=key=>Object.hasOwn(localConfig,key)?localConfig[key]:project[key],outputDirectory=setting("outputDirectory");return!setting("framework")&&!setting("buildCommand")&&(!outputDirectory||outputDirectory===".")}async function aliasLonePageInOutput(outputDir){if(!await isPlainStaticOutput(outputDir))return;let staticDir=join(outputDir,"static"),entries;try{entries=(await readdir(staticDir,{recursive:!0})).map(entry=>entry.split("\\").join("/"))}catch{return}let pages=entries.filter(entry=>/\.html?$/i.test(entry));if(pages.length!==1)return;let[page]=pages;page.includes("/")||page==="index.html"||page==="index.htm"||(await import_fs_extra.default.stat(join(staticDir,page))).isFile()&&await writeIndexCopy(staticDir,page)}async function isPlainStaticOutput(outputDir){if(await import_fs_extra.default.pathExists(join(outputDir,"functions")))return!1;let readJSON=name=>import_fs_extra.default.readJSON(join(outputDir,name)).catch(()=>null),builds=(await readJSON("builds.json"))?.builds;if(!Array.isArray(builds)||builds.length===0||builds.some(build=>build?.use!=="@vercel/static"))return!1;let config=await readJSON("config.json"),routes=config?.routes??[];return!config||!Array.isArray(routes)?!1:routes.findIndex(route=>route?.handle==="error")===0||routes.length===0}async function writeIndexCopy(dir,name){let page=join(dir,name),index=join(dir,"index.html"),existing=await import_fs_extra.default.stat(index).catch(()=>null);if(existing&&existing.ino===(await import_fs_extra.default.stat(page)).ino){await import_fs_extra.default.rename(page,index);return}await import_fs_extra.default.copy(page,index)}var import_fs_extra2=__toESM(require_lib(),1),import_slugify=__toESM(require_slugify(),1),import_build_utils=__toESM(require_build_utils(),1),import_client=__toESM(require_dist(),1);import{basename,dirname,extname,isAbsolute,join as join2,relative,sep}from"path";var singleFileConfig={framework:null,buildCommand:"",installCommand:"",outputDirectory:null},singleFileProjectSettings={...singleFileConfig,rootDirectory:null};async function stageSingleFile(file,dir){let name=basename(file);await import_fs_extra2.default.copy(file,join2(dir,name)),servesAtRoot(name)&&await writeIndexCopy(dir,name)}function getSingleFileNameError(name){if(name.includes("\\"))return"Can't deploy a file with a backslash in its name. Rename the file, or deploy its directory.";if(name===".vc-config.json")return"Can't deploy a file named .vc-config.json on its own, because Vercel reads that name as a function config. Rename the file, or deploy its directory."}function servesAtRoot(name){let ext=extname(name).toLowerCase();return(ext===".html"||ext===".htm")&&name!=="index.html"&&name!=="index.htm"}async function isIgnoredFile(file,cwd){let roots=new Set([dirname(file)]),fromCwd=relative(cwd,file);fromCwd&&!fromCwd.startsWith(`..${sep}`)&&!isAbsolute(fromCwd)&&roots.add(cwd);for(let root of roots){let{ig}=await(0,import_client.getVercelIgnore)(root);if(ig.ignores(relative(root,file).split(sep).join("/")))return!0}return!1}function getSingleFileProjectName(file){return(0,import_slugify.default)(basename(file,extname(file))).slice(0,100).replace(/-+$/,"")||void 0}var PROJECT_NAME_RULES="Project names can be up to 100 characters long and must be lowercase. They can include letters, digits, and the following characters: '.', '_', '-'. However, they cannot contain the sequence '---'.";function isValidProjectName(name){return/^[a-z0-9._-]{1,100}$/.test(name)&&!name.includes("---")}var singleFileMeta={singleFile:"1"};function isStaticProject(project){if(project.framework||project.link||project.rootDirectory||project.buildCommand||project.installCommand)return!1;if(project.outputDirectory===".")return!0;if(project.outputDirectory)return!1;let served=project.targets?.production??project.latestDeployments?.[0];return!served||served.meta?.singleFile===singleFileMeta.singleFile}var PROJECT_FLAGS=["--project","--name","-n"],SCOPE_FLAGS=["--scope","--team","-S","-T"];function rawArgsWithout(client,flags){let args=stripSensitiveAuthArgs(client.argv.slice(2)),kept=[];for(let i=0;i<args.length;i++){let arg=args[i];if(flags.includes(normalizeFlagName(arg))){arg.includes("=")||i++;continue}kept.push(arg)}return kept}function argsWithout(client,flags){return rawArgsWithout(client,flags).map(quoteArg).join(" ")}function retryWithProject(client,project){return`${packageName} ${argsWithout(client,PROJECT_FLAGS)} --project ${project}`}function singleFileTargetArgs(client,link){let{org,project}=link,scope=!detectExplicitScope(client)&&org.type==="team"&&org.slug&&!isOwnerLookupUnavailableLink(link)?` --scope ${quoteArg(org.slug)}`:"";return` --project ${quoteArg(project.id)}${scope}`}async function applyNameScope(client){if(detectExplicitScope(client))return;if(client.ignoresSavedTeam){await client.resolveCurrentTeam();return}let envOrgId=(0,import_build_utils.getPlatformEnv)("ORG_ID");if(envOrgId){client.config.currentTeam=envOrgId.startsWith("team_")?envOrgId:void 0;return}if(!client.config.currentTeam)try{await getScope(client)}catch(err){output_manager_default.debug(`Using the token's scope for single-file deploys: ${err}`)}}function fail(client,asJson,{headline,detail,next=[],...failure},exitCode){if(asJson){let{status,...rest}=failure,payload={...rest,message:detail?`${headline} ${detail}`:headline,...next.length>0&&{next:next.map(({command,when})=>({command,when}))}};status===AGENT_STATUS.ERROR?writeAgentError(client,{...payload,status}):writeTrackedActionRequired(client,{...payload,status})}else{output_manager_default.fatal(detail?`${headline}
8
8
  ${detail}`:headline);for(let{instruction,command}of next)output_manager_default.print(`
9
9
  ${instruction}:
10
10
  ${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{ensureLink}from"./chunk-KW7G66ZY.js";import{getTeams}from"./chunk-HPXRESOF.js";import{scopeFlagPassed}from"./chunk-GTZ6ASHD.js";import{getLinkedProject,getUser,resolveProjectCwd}from"./chunk-4YGSXM2T.js";import{getProjectByNameOrId}from"./chunk-VO5M6G7M.js";import{parseArguments}from"./chunk-E7ICSU45.js";import{argvHasNonInteractive}from"./chunk-3QTP26QS.js";import{LinkRequiredError,ProjectNotFound}from"./chunk-UNAQQ5DF.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import{require_build_utils}from"./chunk-BVFFSUG3.js";import{__toESM}from"./chunk-NBPLUP7C.js";async function getProjectByCwdOrLink({autoConfirm,nonInteractive,client,commandName,cwd,projectNameOrId,forReadOnlyCommand,skipOwnerLookup}){if(projectNameOrId){let project=await getProjectByNameOrId(client,projectNameOrId);if(project instanceof ProjectNotFound)throw project;return project}let effectiveNonInteractive=nonInteractive??client.nonInteractive??argvHasNonInteractive(client.argv);if(forReadOnlyCommand&&effectiveNonInteractive){let resolvedCwd=await resolveProjectCwd(cwd??client.cwd),link=await getLinkedProject(client,{cwd:resolvedCwd,skipOwnerLookup});if(link.status==="linked"&&link.project)return link.project;if(link.status==="error"){let err=new Error("Link project error");throw err.code="ERR_LINK_PROJECT",err}throw new LinkRequiredError}let linkedProject=await ensureLink(commandName,client,cwd??client.cwd,{autoConfirm,nonInteractive,skipOwnerLookup});if(typeof linkedProject=="number"){let err=new Error("Link project error");throw err.code="ERR_LINK_PROJECT",err}return linkedProject.project}var import_build_utils=__toESM(require_build_utils(),1);async function isTeamExplicit(client){if(scopeFlagPassed(client.argv)){let{flags}=parseArguments(client.argv.slice(2),{},{permissive:!0});if(flags["--scope"]||flags["--team"])return!0}let team=await client.resolveCurrentTeam({ask:!1});if(!team&&client.isTeamUnchosen())return!1;let orgId=(0,import_build_utils.getPlatformEnv)("ORG_ID");try{if(!team)return orgId?orgId===(await getUser(client)).id:(await getTeams(client)).length===0;if(orgId)return orgId===team;let teams=await getTeams(client);return teams.length===1&&teams[0].id===team}catch(err){return output_manager_default.debug(`Couldn't check the scope: ${err}`),!1}}export{getProjectByCwdOrLink,isTeamExplicit};
7
+ import{ensureLink}from"./chunk-UITNWLE7.js";import{getTeams}from"./chunk-HPXRESOF.js";import{scopeFlagPassed}from"./chunk-H3HSH5FW.js";import{getLinkedProject,getUser,resolveProjectCwd}from"./chunk-H4BQDKOU.js";import{getProjectByNameOrId}from"./chunk-VO5M6G7M.js";import{parseArguments}from"./chunk-E7ICSU45.js";import{argvHasNonInteractive}from"./chunk-3QTP26QS.js";import{LinkRequiredError,ProjectNotFound}from"./chunk-UNAQQ5DF.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import{require_build_utils}from"./chunk-BVFFSUG3.js";import{__toESM}from"./chunk-NBPLUP7C.js";async function getProjectByCwdOrLink({autoConfirm,nonInteractive,client,commandName,cwd,projectNameOrId,forReadOnlyCommand,skipOwnerLookup}){if(projectNameOrId){let project=await getProjectByNameOrId(client,projectNameOrId);if(project instanceof ProjectNotFound)throw project;return project}let effectiveNonInteractive=nonInteractive??client.nonInteractive??argvHasNonInteractive(client.argv);if(forReadOnlyCommand&&effectiveNonInteractive){let resolvedCwd=await resolveProjectCwd(cwd??client.cwd),link=await getLinkedProject(client,{cwd:resolvedCwd,skipOwnerLookup});if(link.status==="linked"&&link.project)return link.project;if(link.status==="error"){let err=new Error("Link project error");throw err.code="ERR_LINK_PROJECT",err}throw new LinkRequiredError}let linkedProject=await ensureLink(commandName,client,cwd??client.cwd,{autoConfirm,nonInteractive,skipOwnerLookup});if(typeof linkedProject=="number"){let err=new Error("Link project error");throw err.code="ERR_LINK_PROJECT",err}return linkedProject.project}var import_build_utils=__toESM(require_build_utils(),1);async function isTeamExplicit(client){if(scopeFlagPassed(client.argv)){let{flags}=parseArguments(client.argv.slice(2),{},{permissive:!0});if(flags["--scope"]||flags["--team"])return!0}let team=await client.resolveCurrentTeam({ask:!1});if(!team&&client.isTeamUnchosen())return!1;let orgId=(0,import_build_utils.getPlatformEnv)("ORG_ID");try{if(!team)return orgId?orgId===(await getUser(client)).id:(await getTeams(client)).length===0;if(orgId)return orgId===team;let teams=await getTeams(client);return teams.length===1&&teams[0].id===team}catch(err){return output_manager_default.debug(`Couldn't check the scope: ${err}`),!1}}export{getProjectByCwdOrLink,isTeamExplicit};
@@ -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{performDeviceCodeFlow}from"./chunk-QV2PDKZY.js";import{isAPIError}from"./chunk-UNAQQ5DF.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import{URLSearchParams}from"url";var RECOVERABLE_CHALLENGE_CODES=new Set(["challenge_required","challenge_required_email_otp","user_auth_required"]);async function withEnvChallengeRecovery(client,fn){let hadStoredSession=!!(client.authConfig.token||client.authConfig.refreshToken);try{return await fn()}catch(error){if(!isAPIError(error))throw error;let isRecoverableChallenge=RECOVERABLE_CHALLENGE_CODES.has(error.code),isRejectedStoredSession=hadStoredSession&&error.invalidToken===!0;if(!isRecoverableChallenge&&!isRejectedStoredSession||client.authConfig.tokenSource||!client.stdin.isTTY||client.nonInteractive)throw error;output_manager_default.stopSpinner(),output_manager_default.log("Sensitive Environment Variables require fresh authentication.");let refreshToken=client.authConfig.refreshToken,acrValues=getAcrValuesFromWWWAuthenticate(error.wwwAuthenticate),tokens=isRecoverableChallenge&&refreshToken&&acrValues?await performDeviceCodeFlow(client,{refreshToken,acrValues,fallbackToLoginOnStepUpFailure:!0}):await performDeviceCodeFlow(client);if(!tokens)throw error;return client.updateAuthConfig({token:tokens.access_token,userId:void 0,expiresAt:Math.floor(Date.now()/1e3)+tokens.expires_in,refreshToken:tokens.refresh_token,dpop:tokens.dpop}),client.persistAuthConfig(),await fn()}}function getAcrValuesFromWWWAuthenticate(header){if(!header)return;let lowerHeader=header.toLowerCase(),scheme=lowerHeader.includes("bearer")?"bearer":"dpop",schemeIndex=lowerHeader.indexOf(scheme);if(schemeIndex===-1)return;let match=header.slice(schemeIndex+scheme.length).match(/(?:^|[,\s])acr_values=(?:"((?:\\.|[^"\\])*)"|([^,\s]+))/i);return match?.[1]?.replace(/\\(.)/g,"$1")??match?.[2]}async function getEnvRecords(client,projectId,source,{target,gitBranch,decrypt}={}){output_manager_default.debug(`Fetching Environment Variables of project ${projectId} and target ${target}`);let query=new URLSearchParams;if(target){let targetParam="target";target!=="production"&&target!=="preview"&&target!=="development"&&(targetParam="customEnvironmentId"),query.set(targetParam,target)}gitBranch&&query.set("gitBranch",gitBranch),decrypt&&query.set("decrypt",decrypt.toString()),source&&query.set("source",source);let url=`/v10/projects/${projectId}/env?${query}`;return withEnvChallengeRecovery(client,()=>client.fetch(url))}async function pullEnvRecords(client,projectIdOrDeploymentId,source,{target,gitBranch}={}){output_manager_default.debug(`Fetching Environment Variables of ${projectIdOrDeploymentId} and target ${target}`);let query=new URLSearchParams,url=`/v3/env/pull/${projectIdOrDeploymentId}`;return projectIdOrDeploymentId.startsWith("dpl_")||target&&(url+=`/${encodeURIComponent(target)}`,gitBranch&&(url+=`/${encodeURIComponent(gitBranch)}`)),source&&query.set("source",source),Array.from(query).length>0&&(url+=`?${query}`),withEnvChallengeRecovery(client,()=>client.fetch(url))}export{getEnvRecords,pullEnvRecords};
7
+ import{performDeviceCodeFlow}from"./chunk-55EEFTI7.js";import{isAPIError}from"./chunk-UNAQQ5DF.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import{URLSearchParams}from"url";var RECOVERABLE_CHALLENGE_CODES=new Set(["challenge_required","challenge_required_email_otp","user_auth_required"]);async function withEnvChallengeRecovery(client,fn){let hadStoredSession=!!(client.authConfig.token||client.authConfig.refreshToken);try{return await fn()}catch(error){if(!isAPIError(error))throw error;let isRecoverableChallenge=RECOVERABLE_CHALLENGE_CODES.has(error.code),isRejectedStoredSession=hadStoredSession&&error.invalidToken===!0;if(!isRecoverableChallenge&&!isRejectedStoredSession||client.authConfig.tokenSource||!client.stdin.isTTY||client.nonInteractive)throw error;output_manager_default.stopSpinner(),output_manager_default.log("Sensitive Environment Variables require fresh authentication.");let refreshToken=client.authConfig.refreshToken,acrValues=getAcrValuesFromWWWAuthenticate(error.wwwAuthenticate),tokens=isRecoverableChallenge&&refreshToken&&acrValues?await performDeviceCodeFlow(client,{refreshToken,acrValues,fallbackToLoginOnStepUpFailure:!0}):await performDeviceCodeFlow(client);if(!tokens)throw error;return client.updateAuthConfig({token:tokens.access_token,userId:void 0,expiresAt:Math.floor(Date.now()/1e3)+tokens.expires_in,refreshToken:tokens.refresh_token,dpop:tokens.dpop}),client.persistAuthConfig(),await fn()}}function getAcrValuesFromWWWAuthenticate(header){if(!header)return;let lowerHeader=header.toLowerCase(),scheme=lowerHeader.includes("bearer")?"bearer":"dpop",schemeIndex=lowerHeader.indexOf(scheme);if(schemeIndex===-1)return;let match=header.slice(schemeIndex+scheme.length).match(/(?:^|[,\s])acr_values=(?:"((?:\\.|[^"\\])*)"|([^,\s]+))/i);return match?.[1]?.replace(/\\(.)/g,"$1")??match?.[2]}async function getEnvRecords(client,projectId,source,{target,gitBranch,decrypt}={}){output_manager_default.debug(`Fetching Environment Variables of project ${projectId} and target ${target}`);let query=new URLSearchParams;if(target){let targetParam="target";target!=="production"&&target!=="preview"&&target!=="development"&&(targetParam="customEnvironmentId"),query.set(targetParam,target)}gitBranch&&query.set("gitBranch",gitBranch),decrypt&&query.set("decrypt",decrypt.toString()),source&&query.set("source",source);let url=`/v10/projects/${projectId}/env?${query}`;return withEnvChallengeRecovery(client,()=>client.fetch(url))}async function pullEnvRecords(client,projectIdOrDeploymentId,source,{target,gitBranch}={}){output_manager_default.debug(`Fetching Environment Variables of ${projectIdOrDeploymentId} and target ${target}`);let query=new URLSearchParams,url=`/v3/env/pull/${projectIdOrDeploymentId}`;return projectIdOrDeploymentId.startsWith("dpl_")||target&&(url+=`/${encodeURIComponent(target)}`,gitBranch&&(url+=`/${encodeURIComponent(gitBranch)}`)),source&&query.set("source",source),Array.from(query).length>0&&(url+=`?${query}`),withEnvChallengeRecovery(client,()=>client.fetch(url))}export{getEnvRecords,pullEnvRecords};
@@ -4,5 +4,5 @@ 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{canPrompt}from"./chunk-IQ7FPAI4.js";import{require_lib}from"./chunk-4YGSXM2T.js";import{AGENT_REASON,AGENT_STATUS,outputActionRequired}from"./chunk-3QTP26QS.js";import{humanizePath}from"./chunk-UNAQQ5DF.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import{require_source}from"./chunk-UJ7YUIEJ.js";import{__toESM}from"./chunk-NBPLUP7C.js";var import_fs_extra=__toESM(require_lib(),1),import_chalk=__toESM(require_source(),1);import{homedir}from"os";import{resolve,sep}from"path";import{realpath as realpathCallback}from"node:fs";import*as fs from"node:fs/promises";import{promisify}from"node:util";var realpathInJavaScript=promisify(realpathCallback);async function validateRootDirectory(cwd,path,errorSuffix=""){let pathStat=await(0,import_fs_extra.lstat)(path).catch(()=>null),suffix=errorSuffix?` ${errorSuffix}`:"";return pathStat?pathStat.isDirectory()?await resolvesInside(cwd,path)?!0:(output_manager_default.error(`The provided path ${import_chalk.default.cyan(`\u201C${humanizePath(path)}\u201D`)} is outside of the project.${suffix}`),!1):(output_manager_default.error(`The provided path ${import_chalk.default.cyan(`\u201C${humanizePath(path)}\u201D`)} is a file, but expected a directory.${suffix}`),!1):(output_manager_default.error(`The provided path ${import_chalk.default.cyan(`\u201C${humanizePath(path)}\u201D`)} does not exist.${suffix}`),!1)}async function validatePaths(client,paths,{allowFiles=!1}={}){if(paths.length>1)return output_manager_default.error("Can't deploy more than one path."),{valid:!1,exitCode:1};let path=paths[0],pathStat=await(0,import_fs_extra.lstat)(path).catch(()=>null);if(!pathStat)return output_manager_default.error(`Could not find ${import_chalk.default.cyan(`\u201C${humanizePath(path)}\u201D`)}`),{valid:!1,exitCode:1};let isFile=pathStat.isFile();if(!pathStat.isDirectory()&&!(allowFiles&&isFile))return output_manager_default.fatal(allowFiles?"Deploy a regular file or directory. Symbolic links and special files are not supported as deployment paths.":"This command requires a directory. Use `vercel <file>` to deploy a single file."),{valid:!1,exitCode:1};let refusal=await confirmHomeDirectory(client,path);return refusal||{valid:!0,path,isFile}}async function validateUploadRoot(client,path,repoRoot){if(!repoRoot||repoRoot===path)return{valid:!0,path};let[resolvedRoot,resolvedPath]=await Promise.all([resolveLinks(repoRoot),resolveLinks(path)]);return resolvedRoot===resolvedPath?{valid:!0,path:repoRoot}:rootContains(repoRoot,path,resolvedRoot,resolvedPath)?await confirmHomeDirectory(client,repoRoot,`The repository link ${humanizePath(resolve(repoRoot,".vercel","repo.json"))} makes your home directory the directory to deploy.`)??{valid:!0,path:repoRoot}:(output_manager_default.error(repoRootOutsideMessage("deploy",path,repoRoot)),{valid:!1,exitCode:1})}async function repoRootContains(repoRoot,path){let[resolvedRoot,resolvedPath]=await Promise.all([resolveLinks(repoRoot),resolveLinks(path)]);return rootContains(repoRoot,path,resolvedRoot,resolvedPath)}function rootContains(repoRoot,path,resolvedRoot,resolvedPath){return isInside(repoRoot,path)||isInside(resolvedRoot,resolvedPath)}function repoRootOutsideMessage(action,path,repoRoot){return`Can't ${action} ${humanizePath(path)}. Git reports the repository root ${humanizePath(repoRoot)}, which does not contain this directory. Check \`core.worktree\` in the Git configuration and the \`GIT_WORK_TREE\` environment variable.`}async function resolvesInside(directory,path){let[base,target]=await Promise.all([resolveExisting(directory),resolveExisting(path)]);return base!==null&&target!==null&&isInside(base,target)}async function resolvesToDirectoryInside(directory,path){return!!(await fs.stat(path).catch(()=>null))?.isDirectory()&&await resolvesInside(directory,path)}async function resolveExisting(path){try{return await fs.realpath(path)}catch{return realpathInJavaScript(path).catch(()=>null)}}async function confirmHomeDirectory(client,path,cause){if(!await isHomeDirectory(path))return null;if(!canPrompt(client)){let message=`Can't deploy your home directory without interactive confirmation. ${cause?`${cause} Run`:"Run from your project directory, or run"} in a terminal to confirm deploying your home directory.`;return outputActionRequired(client,{status:AGENT_STATUS.ACTION_REQUIRED,reason:AGENT_REASON.INTERACTIVE_CONFIRMATION_REQUIRED,message,userActionRequired:!0},2),output_manager_default.error(message),{valid:!1,exitCode:2}}return cause&&output_manager_default.warning(cause),await client.input.confirm("You are deploying your home directory. Do you want to continue?",!1)?null:(output_manager_default.print(`Canceled
7
+ import{canPrompt}from"./chunk-IQ7FPAI4.js";import{require_lib}from"./chunk-H4BQDKOU.js";import{AGENT_REASON,AGENT_STATUS,outputActionRequired}from"./chunk-3QTP26QS.js";import{humanizePath}from"./chunk-UNAQQ5DF.js";import{output_manager_default}from"./chunk-RIXTYUYN.js";import{require_source}from"./chunk-UJ7YUIEJ.js";import{__toESM}from"./chunk-NBPLUP7C.js";var import_fs_extra=__toESM(require_lib(),1),import_chalk=__toESM(require_source(),1);import{homedir}from"os";import{resolve,sep}from"path";import{realpath as realpathCallback}from"node:fs";import*as fs from"node:fs/promises";import{promisify}from"node:util";var realpathInJavaScript=promisify(realpathCallback);async function validateRootDirectory(cwd,path,errorSuffix=""){let pathStat=await(0,import_fs_extra.lstat)(path).catch(()=>null),suffix=errorSuffix?` ${errorSuffix}`:"";return pathStat?pathStat.isDirectory()?await resolvesInside(cwd,path)?!0:(output_manager_default.error(`The provided path ${import_chalk.default.cyan(`\u201C${humanizePath(path)}\u201D`)} is outside of the project.${suffix}`),!1):(output_manager_default.error(`The provided path ${import_chalk.default.cyan(`\u201C${humanizePath(path)}\u201D`)} is a file, but expected a directory.${suffix}`),!1):(output_manager_default.error(`The provided path ${import_chalk.default.cyan(`\u201C${humanizePath(path)}\u201D`)} does not exist.${suffix}`),!1)}async function validatePaths(client,paths,{allowFiles=!1}={}){if(paths.length>1)return output_manager_default.error("Can't deploy more than one path."),{valid:!1,exitCode:1};let path=paths[0],pathStat=await(0,import_fs_extra.lstat)(path).catch(()=>null);if(!pathStat)return output_manager_default.error(`Could not find ${import_chalk.default.cyan(`\u201C${humanizePath(path)}\u201D`)}`),{valid:!1,exitCode:1};let isFile=pathStat.isFile();if(!pathStat.isDirectory()&&!(allowFiles&&isFile))return output_manager_default.fatal(allowFiles?"Deploy a regular file or directory. Symbolic links and special files are not supported as deployment paths.":"This command requires a directory. Use `vercel <file>` to deploy a single file."),{valid:!1,exitCode:1};let refusal=await confirmHomeDirectory(client,path);return refusal||{valid:!0,path,isFile}}async function validateUploadRoot(client,path,repoRoot){if(!repoRoot||repoRoot===path)return{valid:!0,path};let[resolvedRoot,resolvedPath]=await Promise.all([resolveLinks(repoRoot),resolveLinks(path)]);return resolvedRoot===resolvedPath?{valid:!0,path:repoRoot}:rootContains(repoRoot,path,resolvedRoot,resolvedPath)?await confirmHomeDirectory(client,repoRoot,`The repository link ${humanizePath(resolve(repoRoot,".vercel","repo.json"))} makes your home directory the directory to deploy.`)??{valid:!0,path:repoRoot}:(output_manager_default.error(repoRootOutsideMessage("deploy",path,repoRoot)),{valid:!1,exitCode:1})}async function repoRootContains(repoRoot,path){let[resolvedRoot,resolvedPath]=await Promise.all([resolveLinks(repoRoot),resolveLinks(path)]);return rootContains(repoRoot,path,resolvedRoot,resolvedPath)}function rootContains(repoRoot,path,resolvedRoot,resolvedPath){return isInside(repoRoot,path)||isInside(resolvedRoot,resolvedPath)}function repoRootOutsideMessage(action,path,repoRoot){return`Can't ${action} ${humanizePath(path)}. Git reports the repository root ${humanizePath(repoRoot)}, which does not contain this directory. Check \`core.worktree\` in the Git configuration and the \`GIT_WORK_TREE\` environment variable.`}async function resolvesInside(directory,path){let[base,target]=await Promise.all([resolveExisting(directory),resolveExisting(path)]);return base!==null&&target!==null&&isInside(base,target)}async function resolvesToDirectoryInside(directory,path){return!!(await fs.stat(path).catch(()=>null))?.isDirectory()&&await resolvesInside(directory,path)}async function resolveExisting(path){try{return await fs.realpath(path)}catch{return realpathInJavaScript(path).catch(()=>null)}}async function confirmHomeDirectory(client,path,cause){if(!await isHomeDirectory(path))return null;if(!canPrompt(client)){let message=`Can't deploy your home directory without interactive confirmation. ${cause?`${cause} Run`:"Run from your project directory, or run"} in a terminal to confirm deploying your home directory.`;return outputActionRequired(client,{status:AGENT_STATUS.ACTION_REQUIRED,reason:AGENT_REASON.INTERACTIVE_CONFIRMATION_REQUIRED,message,userActionRequired:!0},2),output_manager_default.error(message),{valid:!1,exitCode:2}}return cause&&output_manager_default.warning(cause),await client.input.confirm("You are deploying your home directory. Do you want to continue?",!1)?null:(output_manager_default.print(`Canceled
8
8
  `),{valid:!1,exitCode:0})}async function isHomeDirectory(path){let home=homedir();return path===home||await resolveLinks(path)===await resolveLinks(home)}function resolveLinks(path){return fs.realpath(path).catch(()=>path)}function isInside(directory,path){let base=resolve(directory),target=resolve(path);return target===base||target.startsWith(base.endsWith(sep)?base:base+sep)}export{validateRootDirectory,validatePaths,validateUploadRoot,repoRootContains,repoRootOutsideMessage,resolvesInside,resolvesToDirectoryInside};