@vercel/cli-support 66.2.0 → 66.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (201) hide show
  1. package/dist/chunks/{add-U6KDXZT2.js → add-AA7ATWNJ.js} +1 -1
  2. package/dist/chunks/{add-ECNHL7CN.js → add-D7V4UY7M.js} +1 -1
  3. package/dist/chunks/{add-3P4HAZZZ.js → add-IRTM2Q6Q.js} +1 -1
  4. package/dist/chunks/{alerts-NLLCERTK.js → alerts-HNX4G7UF.js} +1 -1
  5. package/dist/chunks/{build-HM5K3QD7.js → build-3TNPGMCK.js} +1 -1
  6. package/dist/chunks/{chunk-TT4PL5J2.js → chunk-2DNOJRZY.js} +1 -1
  7. package/dist/chunks/{chunk-6QEQI5SY.js → chunk-3JP2EUHQ.js} +1 -1
  8. package/dist/chunks/{chunk-IL27CVNF.js → chunk-3LNBGHWC.js} +1 -1
  9. package/dist/chunks/{chunk-TSLAMIUI.js → chunk-3SAOTU5Z.js} +1 -1
  10. package/dist/chunks/{chunk-FDVLR2HV.js → chunk-3UR42KVA.js} +1 -1
  11. package/dist/chunks/{chunk-5O77DSX4.js → chunk-47ZBTGAH.js} +1 -1
  12. package/dist/chunks/{chunk-EA55QLHA.js → chunk-4AET2E4U.js} +1 -1
  13. package/dist/chunks/{chunk-QZMBBLOQ.js → chunk-4FKAPGH3.js} +1 -1
  14. package/dist/chunks/{chunk-5VGAD2ZS.js → chunk-4OC4CVBM.js} +1 -1
  15. package/dist/chunks/{chunk-76VUFE3K.js → chunk-5GDRVPSL.js} +1 -1
  16. package/dist/chunks/{chunk-XL2PHD4X.js → chunk-5HEF6CPE.js} +5 -5
  17. package/dist/chunks/{chunk-F52YOIDM.js → chunk-5PFQCTFC.js} +1 -1
  18. package/dist/chunks/{chunk-R5U4P7WK.js → chunk-5VI33HDO.js} +1 -1
  19. package/dist/chunks/{chunk-RX5HH3T6.js → chunk-5XBV4XTK.js} +1 -1
  20. package/dist/chunks/{chunk-6FDTVIJM.js → chunk-6JYMXLQZ.js} +1 -1
  21. package/dist/chunks/{chunk-YALFS5SH.js → chunk-7J7LHIO4.js} +3 -3
  22. package/dist/chunks/{chunk-HQWR3EDU.js → chunk-A3ZPQUWM.js} +1 -1
  23. package/dist/chunks/{chunk-ZXNR7CNU.js → chunk-AIAS6KAV.js} +1 -1
  24. package/dist/chunks/{chunk-FRKDI2ZH.js → chunk-AYAUO37X.js} +1 -1
  25. package/dist/chunks/{chunk-WCCKCQ43.js → chunk-B7VPXDY2.js} +1 -1
  26. package/dist/chunks/{chunk-7THDUCSM.js → chunk-BLNGQEOB.js} +1 -1
  27. package/dist/chunks/{chunk-POKRDE5J.js → chunk-BQXFIDDA.js} +1 -1
  28. package/dist/chunks/{chunk-O3IQMUYI.js → chunk-CV7TBU72.js} +1 -1
  29. package/dist/chunks/{chunk-66VYZZTY.js → chunk-DGM7TXOL.js} +1 -1
  30. package/dist/chunks/{chunk-LOA7SZWH.js → chunk-DJZBJC2A.js} +1 -1
  31. package/dist/chunks/{chunk-O2HDXF5B.js → chunk-DLNT37B7.js} +1 -1
  32. package/dist/chunks/{chunk-KKO6DF57.js → chunk-DMNXLZPG.js} +1 -1
  33. package/dist/chunks/{chunk-HIV3C763.js → chunk-E3AER2ZV.js} +1 -1
  34. package/dist/chunks/{chunk-QQNN5X7M.js → chunk-EKZCZAUD.js} +1 -1
  35. package/dist/chunks/{chunk-UWISBHZI.js → chunk-FCYAT6R3.js} +1 -1
  36. package/dist/chunks/{chunk-NGHAU23V.js → chunk-FFOUIGIX.js} +1 -1
  37. package/dist/chunks/{chunk-CY5KJ42N.js → chunk-FSKZU5GL.js} +1 -1
  38. package/dist/chunks/{chunk-FZBYQQQQ.js → chunk-FXQUNFSH.js} +1 -1
  39. package/dist/chunks/{chunk-QYUKDP2E.js → chunk-G2PXZASE.js} +1 -1
  40. package/dist/chunks/{chunk-Q2R3VQER.js → chunk-G6RUNMW3.js} +1 -1
  41. package/dist/chunks/{chunk-7ECYJHY4.js → chunk-GKAL5XJ2.js} +1 -1
  42. package/dist/chunks/{chunk-KBJNREND.js → chunk-H5HAY5QD.js} +1 -1
  43. package/dist/chunks/{chunk-6U7TRWBO.js → chunk-HVFGIJ44.js} +2 -2
  44. package/dist/chunks/{chunk-POFKUONR.js → chunk-I5JHC377.js} +1 -1
  45. package/dist/chunks/{chunk-UEJ332R4.js → chunk-IE3NP5SP.js} +1 -1
  46. package/dist/chunks/{chunk-TVELM5HH.js → chunk-IIIUFOO3.js} +1 -1
  47. package/dist/chunks/{chunk-SW26TCUB.js → chunk-IQDX4HQ6.js} +1 -1
  48. package/dist/chunks/{chunk-WOD4NOA2.js → chunk-IRWUACWI.js} +1 -1
  49. package/dist/chunks/{chunk-APSIPJAY.js → chunk-K4G4U7DO.js} +1 -1
  50. package/dist/chunks/{chunk-7OMVAZSA.js → chunk-K67DPRBW.js} +1 -1
  51. package/dist/chunks/{chunk-UMGQUJYO.js → chunk-K7Y5XK5I.js} +1 -1
  52. package/dist/chunks/chunk-KMTHGHJV.js +8 -0
  53. package/dist/chunks/{chunk-PB7GGE3Q.js → chunk-L6MIF7TR.js} +1 -1
  54. package/dist/chunks/{chunk-ZPXTTQJT.js → chunk-L77Q4FMH.js} +1 -1
  55. package/dist/chunks/{chunk-A3MC5BEZ.js → chunk-LEVOFTD6.js} +1 -1
  56. package/dist/chunks/{chunk-BLLDEVSD.js → chunk-MGG3COFN.js} +1 -1
  57. package/dist/chunks/{chunk-O4WJDJIL.js → chunk-N54TQNDY.js} +2 -2
  58. package/dist/chunks/{chunk-IWIXET6Q.js → chunk-OJHP5UDW.js} +1 -1
  59. package/dist/chunks/{chunk-2WQCAJBU.js → chunk-OZREKEPK.js} +1 -1
  60. package/dist/chunks/{chunk-G56HLQLB.js → chunk-P3MT7Z74.js} +1 -1
  61. package/dist/chunks/{chunk-KLETLUS6.js → chunk-PK5SI25Q.js} +1 -1
  62. package/dist/chunks/{chunk-K4KP5UR3.js → chunk-QRGX7HHA.js} +1 -1
  63. package/dist/chunks/{chunk-OYQOYJSJ.js → chunk-RS32ZNRX.js} +1 -1
  64. package/dist/chunks/{chunk-2HW7KKB5.js → chunk-SVU3REDI.js} +1 -1
  65. package/dist/chunks/{chunk-PNWRO3XW.js → chunk-SWYNL72F.js} +1 -1
  66. package/dist/chunks/chunk-TUB3APDV.js +7 -0
  67. package/dist/chunks/{chunk-MU3DV4IW.js → chunk-TY3WOAB2.js} +1 -1
  68. package/dist/chunks/{chunk-Y4D7IX3M.js → chunk-U65RJEYM.js} +1 -1
  69. package/dist/chunks/{chunk-KTWGUBNP.js → chunk-ULJ4OAE3.js} +1 -1
  70. package/dist/chunks/chunk-ULUC26PZ.js +13 -0
  71. package/dist/chunks/chunk-UUI3ETQT.js +7 -0
  72. package/dist/chunks/{chunk-2ANPVGOC.js → chunk-UVC7YBW6.js} +1 -1
  73. package/dist/chunks/{chunk-X26PXKHC.js → chunk-V3E3S5NZ.js} +1 -1
  74. package/dist/chunks/chunk-VKVH7LHB.js +7 -0
  75. package/dist/chunks/{chunk-JGUMBEQH.js → chunk-VQUHN5HW.js} +1 -1
  76. package/dist/chunks/{chunk-A5FPKXEK.js → chunk-W6GX7PJ4.js} +1 -1
  77. package/dist/chunks/{chunk-ECQIO5K3.js → chunk-WNB3JZMX.js} +1 -1
  78. package/dist/chunks/{chunk-M23GYM4J.js → chunk-WWUJJI47.js} +2 -2
  79. package/dist/chunks/{chunk-EIBQNIN7.js → chunk-X36G7TQ3.js} +1 -1
  80. package/dist/chunks/{chunk-WHL4PWDW.js → chunk-XLYO5QNG.js} +1 -1
  81. package/dist/chunks/{chunk-3FMDKPIO.js → chunk-XWCYHZL4.js} +1 -1
  82. package/dist/chunks/{chunk-56QPAEAW.js → chunk-XX6VYGGD.js} +1 -1
  83. package/dist/chunks/{chunk-FSZJSIOF.js → chunk-YAODBCTH.js} +1 -1
  84. package/dist/chunks/{chunk-CRX7RINU.js → chunk-YT5VHDJF.js} +1 -1
  85. package/dist/chunks/{chunk-7KPAYK2N.js → chunk-ZBOHFQ7B.js} +1 -1
  86. package/dist/chunks/{chunk-A72AM25W.js → chunk-ZEXRYJPK.js} +1 -1
  87. package/dist/chunks/{chunk-3HCRJO4D.js → chunk-ZLUNCQCF.js} +1 -1
  88. package/dist/chunks/{clear-YJRG7CEK.js → clear-LAQS2IZP.js} +1 -1
  89. package/dist/chunks/cli-embedded-FD3CAPRY.js +84 -0
  90. package/dist/chunks/{compile-vercel-config-GB4X7U3B.js → compile-vercel-config-BSZPZNDE.js} +1 -1
  91. package/dist/chunks/{config-BYHUSTMY.js → config-RACUYTCP.js} +1 -1
  92. package/dist/chunks/{config-L6EQFXGH.js → config-WSYXQGDJ.js} +1 -1
  93. package/dist/chunks/{contract-UAIZFVBK.js → contract-L74DC7DR.js} +1 -1
  94. package/dist/chunks/{delete-CBLBTPK2.js → delete-2IXAHPKT.js} +1 -1
  95. package/dist/chunks/{delete-SY56OAFL.js → delete-PAG6CX7J.js} +1 -1
  96. package/dist/chunks/{describe-Z6RRPRGF.js → describe-FML7BGM3.js} +1 -1
  97. package/dist/chunks/{detect-services-PFR6C4LZ.js → detect-services-77BZUFRQ.js} +1 -1
  98. package/dist/chunks/{disable-E6GTV4NN.js → disable-SINBS6QV.js} +1 -1
  99. package/dist/chunks/{discard-NW6RI3KK.js → discard-DSPG3AGG.js} +1 -1
  100. package/dist/chunks/{edit-K7NN4KRI.js → edit-IGUAZVMB.js} +1 -1
  101. package/dist/chunks/{edit-E4SQL4UK.js → edit-QE652JLN.js} +1 -1
  102. package/dist/chunks/{enable-AY4NQ65W.js → enable-EI22EQNY.js} +1 -1
  103. package/dist/chunks/{engine-I887QHnP-RUEEKCKH.js → engine-D8YAsQS_-WNPHYRQF.js} +2 -2
  104. package/dist/chunks/{export-CW5Q5MDC.js → export-4GR6ROVX.js} +1 -1
  105. package/dist/chunks/{future-3QDT3U5W.js → future-SZN7PTD5.js} +1 -1
  106. package/dist/chunks/{generate-cert-for-deploy-FQQZEMTU.js → generate-cert-for-deploy-OVN7FAM7.js} +1 -1
  107. package/dist/chunks/{image-H4HIURNR.js → image-VRVPLM2G.js} +1 -1
  108. package/dist/chunks/{import-builders-K6D5OFHY.js → import-builders-EO654C2B.js} +1 -1
  109. package/dist/chunks/{inspect-G6ATTJHN.js → inspect-3I4RQZKD.js} +1 -1
  110. package/dist/chunks/{inspect-DO5J2KGE.js → inspect-3UU22APK.js} +1 -1
  111. package/dist/chunks/{inspect-K23UNJUJ.js → inspect-J77GNR6J.js} +1 -1
  112. package/dist/chunks/{inspect-QXRA3OU5.js → inspect-LOUW7DBU.js} +1 -1
  113. package/dist/chunks/{inspect-73R4TFWK.js → inspect-YRVZB5KK.js} +1 -1
  114. package/dist/chunks/{inspect-WHGJZAK3.js → inspect-YX57D7BT.js} +1 -1
  115. package/dist/chunks/{list-EUJMPCD6.js → list-4PTMG4PX.js} +1 -1
  116. package/dist/chunks/{list-ARMBYZH7.js → list-JZB7VBAL.js} +1 -1
  117. package/dist/chunks/{list-G6GK67GL.js → list-TLRTYR4T.js} +1 -1
  118. package/dist/chunks/{list-LRV6CWNG.js → list-VEWDGHHC.js} +1 -1
  119. package/dist/chunks/{login-JSDPVUSB.js → login-DTBPOVNW.js} +1 -1
  120. package/dist/chunks/{login-UIKDCM7X.js → login-FLRZ2P3G.js} +1 -1
  121. package/dist/chunks/{logs-NICAAFXU.js → logs-YAOOFTTO.js} +1 -1
  122. package/dist/chunks/{ls-ZW2V7TME.js → ls-7SAXJ6II.js} +1 -1
  123. package/dist/chunks/{ls-JDKTIVX6.js → ls-B2FU3Q52.js} +1 -1
  124. package/dist/chunks/{ls-E4Q4XPAI.js → ls-F66X3XB6.js} +1 -1
  125. package/dist/chunks/{ls-5STG344U.js → ls-HHF5ND74.js} +1 -1
  126. package/dist/chunks/{ls-H7YD27XH.js → ls-KWOOKVQC.js} +1 -1
  127. package/dist/chunks/{ls-HJVYRGQ3.js → ls-RDCIIYGZ.js} +1 -1
  128. package/dist/chunks/{ls-5ULLIYRA.js → ls-XI622GX2.js} +1 -1
  129. package/dist/chunks/{migrate-experimental-services-XEKA373Q.js → migrate-experimental-services-TJAX4SUC.js} +1 -1
  130. package/dist/chunks/{mutate-2GXUWHWY.js → mutate-GXHWSVRX.js} +1 -1
  131. package/dist/chunks/{notifications-YG44KHCP.js → notifications-JX5GDVGX.js} +1 -1
  132. package/dist/chunks/{open-GGWBQAKT.js → open-3KATFISG.js} +1 -1
  133. package/dist/chunks/{openapi-4KMLRPJV.js → openapi-6GESF6CU.js} +1 -1
  134. package/dist/chunks/{permissions-SJVEJGPH.js → permissions-7YZ7DUQ4.js} +1 -1
  135. package/dist/chunks/{plugin-offer-VNXKPNBY.js → plugin-offer-FWU44GUW.js} +1 -1
  136. package/dist/chunks/{prompt-missing-credentials-RJS5U5IJ.js → prompt-missing-credentials-QT37RTID.js} +1 -1
  137. package/dist/chunks/{publish-GGFL7JVW.js → publish-JP47GZSB.js} +1 -1
  138. package/dist/chunks/{pull-36Z6T5C7.js → pull-IKI7CJFO.js} +1 -1
  139. package/dist/chunks/{purchase-domain-if-available-IS62APPK.js → purchase-domain-if-available-GDQAK76N.js} +1 -1
  140. package/dist/chunks/{push-I37EBJMR.js → push-N6X5C74J.js} +1 -1
  141. package/dist/chunks/query-R2JV3ZQW.js +7 -0
  142. package/dist/chunks/raw-query-WIFJFDOU.js +8 -0
  143. package/dist/chunks/{reauthenticate-U3XWAOMM.js → reauthenticate-MWLCQBQI.js} +1 -1
  144. package/dist/chunks/{remove-T4EBT5XK.js → remove-FS3G7IMA.js} +1 -1
  145. package/dist/chunks/{reorder-JC3L7CJO.js → reorder-6VMRUXNV.js} +1 -1
  146. package/dist/chunks/{reply-5KJBWMPI.js → reply-OCGJHB2J.js} +1 -1
  147. package/dist/chunks/{resolve-3ZU3DHFZ.js → resolve-FRTWFQDV.js} +1 -1
  148. package/dist/chunks/resolve-agent-team-425ASUR4.js +7 -0
  149. package/dist/chunks/{restore-S4AWLRK7.js → restore-W746CAPM.js} +1 -1
  150. package/dist/chunks/{rm-QFQTQKZL.js → rm-2XTFNLPM.js} +1 -1
  151. package/dist/chunks/{rm-YAKU3AIF.js → rm-6BVGVK4Q.js} +1 -1
  152. package/dist/chunks/{rm-X47BKCHC.js → rm-GWRCFCWV.js} +1 -1
  153. package/dist/chunks/{rm-PO6GFUKD.js → rm-PS3ZQPQQ.js} +1 -1
  154. package/dist/chunks/{rm-FXS5DZLW.js → rm-VDSIAKZH.js} +1 -1
  155. package/dist/chunks/{rule-inspect-DTHMNVKJ.js → rule-inspect-RZEYDPVH.js} +1 -1
  156. package/dist/chunks/{schema-DB45ARBN.js → schema-DT5Z3KOQ.js} +1 -1
  157. package/dist/chunks/schema-Q6BY2KQG.js +14 -0
  158. package/dist/chunks/{select-org-MUG3UCJA.js → select-org-BU6WWRYV.js} +1 -1
  159. package/dist/chunks/serving-aOQsBok0-OL36TMZU.js +8 -0
  160. package/dist/chunks/{set-PKLCP3YM.js → set-JXOXE3GL.js} +1 -1
  161. package/dist/chunks/{set-MMOLNY72.js → set-KSFGCBXX.js} +1 -1
  162. package/dist/chunks/{setup-and-link-5OA6HGVD.js → setup-and-link-JVP4U43T.js} +1 -1
  163. package/dist/chunks/{skills-DO7WMK5K.js → skills-Y6SPYENI.js} +1 -1
  164. package/dist/chunks/{tags-GBA56ZTZ.js → tags-HFUSHLEB.js} +1 -1
  165. package/dist/chunks/{types-S7I5EBVX.js → types-FHWBRHGN.js} +1 -1
  166. package/dist/chunks/{update-7H2XLOJU.js → update-VQ2EGHJV.js} +1 -1
  167. package/dist/chunks/{usage-V2GS5NFF.js → usage-HI2Z6IKN.js} +1 -1
  168. package/dist/commands/build/index.js +1 -1
  169. package/dist/commands/deploy/index.js +4 -4
  170. package/dist/commands/dev/index.js +2 -2
  171. package/dist/commands/env/index.js +1 -1
  172. package/dist/commands/link/index.js +1 -1
  173. package/dist/commands/list/index.js +1 -1
  174. package/dist/commands/project/index.js +21 -6
  175. package/dist/commands/tunnel/index.js +1 -1
  176. package/dist/commands-account.js +2 -2
  177. package/dist/commands-ai.js +2 -2
  178. package/dist/commands-blob.js +1 -1
  179. package/dist/commands-core.js +20 -16
  180. package/dist/commands-deployments.js +1 -1
  181. package/dist/commands-flags.js +1 -1
  182. package/dist/commands-integrations.js +16 -7
  183. package/dist/commands-observability.js +2 -2
  184. package/dist/commands-routing.js +16 -4
  185. package/dist/index.js +5 -5
  186. package/dist/internal-build.js +1 -1
  187. package/dist/package.json +1 -1
  188. package/dist/version.mjs +1 -1
  189. package/package.json +12 -12
  190. package/dist/chunks/chunk-5IZI5QH6.js +0 -8
  191. package/dist/chunks/chunk-MGZ3Z4PF.js +0 -8
  192. package/dist/chunks/chunk-PQSW6EAL.js +0 -7
  193. package/dist/chunks/chunk-UFCL2VBD.js +0 -7
  194. package/dist/chunks/chunk-YJP25FL6.js +0 -7
  195. package/dist/chunks/chunk-YON6DNQB.js +0 -13
  196. package/dist/chunks/cli-embedded-KDIRH75G.js +0 -81
  197. package/dist/chunks/query-UEIQYCYU.js +0 -7
  198. package/dist/chunks/raw-query-AY5G6GUK.js +0 -8
  199. package/dist/chunks/resolve-agent-team-XPLMABIA.js +0 -7
  200. package/dist/chunks/schema-NMGD2R2B.js +0 -14
  201. package/dist/chunks/serving-Bulte-NO-VPBE6F4V.js +0 -8
@@ -1,7 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module';
2
- import { fileURLToPath as __fileURLToPath } from 'node:url';
3
- import { dirname as __dirname_ } from 'node:path';
4
- const require = __createRequire(import.meta.url);
5
- const __filename = __fileURLToPath(import.meta.url);
6
- const __dirname = __dirname_(__filename);
7
- import{CAN_MAX,ChannelPath,HttpError,forbidden,unauthorized}from"./chunk-MGZ3Z4PF.js";var PERMISSIONS=["read","post","react","label","sync","manage"],InvalidCan=class extends Error{code="invalid_can";constructor(message2){super(message2),this.name="InvalidCan"}},IMPLIES={read:[],post:[],react:["read"],label:["read"],sync:["read"],manage:["read","post","react","label","sync"]},ORDER=new Map(PERMISSIONS.map((permission,index)=>[permission,index])),SHAPE="write *, a channel, or a channel and its subtree (feedback/)";function parsePattern(pattern){if(pattern==="*")return{kind:"all"};if(pattern.includes("*")){let before=pattern.slice(0,pattern.indexOf("*")).replace(/\/+$/,"");throw new InvalidCan(`invalid channel pattern ${pattern}: ${before===""?"write * for every channel":ChannelPath.safeParse(before).success?`write ${before}/ for ${before} and its subtree`:SHAPE}`)}let subtree=pattern.endsWith("/"),path=subtree?pattern.slice(0,-1):pattern;if(!ChannelPath.safeParse(path).success)throw new InvalidCan(`invalid channel pattern ${pattern||"(empty)"}: ${SHAPE}`);return subtree?{kind:"subtree",path}:{kind:"exact",path}}var key=pattern=>pattern.kind==="all"?"*":pattern.kind==="subtree"?`${pattern.path}/`:pattern.path;function expand(grant){let out=new Set,add=permission=>{if(!ORDER.has(permission))throw new InvalidCan(`unknown permission ${String(permission)}: use ${PERMISSIONS.join(", ")}`);if(!out.has(permission)){out.add(permission);for(let implied of IMPLIES[permission])add(implied)}};for(let permission of grant==="all"?PERMISSIONS:grant)add(permission);return out}var NOTHING=new Set;function compile(entries){let all=null,exact=new Map,subtrees=[];for(let[pattern,permissions]of entries)pattern.kind==="all"?all=permissions:pattern.kind==="exact"?exact.set(pattern.path,permissions):subtrees.push([pattern.path,permissions]);return subtrees.sort((a,b)=>b[0].length-a[0].length),{all,exact,subtrees}}var under=(channel,path)=>channel===path||channel.startsWith(`${path}/`);function resolve(rules,channel,subtreeOnly=!1){if(!subtreeOnly){let exact=rules.exact.get(channel);if(exact)return exact}for(let[path,permissions]of rules.subtrees)if(under(channel,path))return permissions;return rules.all??NOTHING}var at=(rules,pattern)=>pattern.kind==="all"?rules.all??NOTHING:resolve(rules,pattern.path,pattern.kind==="subtree"),equal=(a,b)=>a.size===b.size&&[...a].every(permission=>b.has(permission));function parent(rules,pattern){if(pattern.kind==="exact")return resolve(rules,pattern.path,!0);if(pattern.kind==="subtree"){for(let[path,permissions]of rules.subtrees)if(path!==pattern.path&&under(pattern.path,path))return permissions}return rules.all??NOTHING}function canonical(entries){let rules=compile(entries);return compile(entries.filter(([pattern,permissions])=>pattern.kind==="all"?permissions.size>0:!equal(permissions,parent(rules,pattern))))}function entriesOf(can){return can==="all"||Array.isArray(can)?[[{kind:"all"},expand(can)]]:Object.entries(can).map(([pattern,grant])=>[parsePattern(pattern),expand(grant)])}var entriesIn=rules=>[...rules.all?[[{kind:"all"},rules.all]]:[],...rules.subtrees.map(([path,permissions])=>[{kind:"subtree",path},permissions]),...[...rules.exact].map(([path,permissions])=>[{kind:"exact",path},permissions])],RULES=Symbol("board.access"),READABLE_MAX=4096,isAccess=value=>typeof value=="object"&&RULES in value;function fromRules(rules){let entries=entriesIn(rules),everywhere=permission=>(rules.all?.has(permission)??!1)&&entries.every(([,permissions])=>permissions.has(permission)),uniform=rules.exact.size===0&&rules.subtrees.length===0?rules.all?.has("read")??!1:null,readable=new Map,compiled={[RULES]:rules,can:(permission,channel)=>resolve(rules,channel).has(permission),readable(channel){if(uniform!==null)return uniform;let found=readable.get(channel);return found===void 0&&(readable.size>=READABLE_MAX&&readable.clear(),readable.set(channel,found=resolve(rules,channel).has("read"))),found},readsAll:everywhere("read"),everywhere,anywhere:permission=>entries.some(([,permissions])=>permissions.has(permission)),at:(permission,pattern)=>at(rules,parsePattern(pattern)).has(permission),narrow(scope){let other=isAccess(scope)?scope[RULES]:canonical(entriesOf(scope)),patterns=new Map([["*",{kind:"all"}]]);for(let[pattern]of[...entries,...entriesIn(other)])patterns.set(key(pattern),pattern);return fromRules(canonical([...patterns.values()].map(pattern=>{let theirs=at(other,pattern);return[pattern,new Set([...at(rules,pattern)].filter(permission=>theirs.has(permission)))]})))},summary(){let named=entries.map(([pattern,permissions])=>[key(pattern),permissions]);named.sort(([a],[b])=>a==="*"?-1:b==="*"?1:a.localeCompare(b));let out={};for(let[name,permissions]of named)out[name]=[...permissions].sort((a,b)=>ORDER.get(a)-ORDER.get(b));return out}};return Object.freeze(compiled)}function compileAccess(can){return fromRules(canonical(entriesOf(can)))}var FULL_ACCESS=compileAccess("all"),NO_ACCESS=compileAccess([]);var RANK=new Map(["principal","group","everyone"].map((level,index)=>[level,index])),namedIn=can=>entriesOf(can);function closest(matched){let byPattern=new Map;for(let grant of matched)for(let[pattern,permissions]of namedIn(grant.can)){let name=key(pattern),found=byPattern.get(name);if(!found||RANK.get(grant.level)<RANK.get(found.level))byPattern.set(name,{pattern,level:grant.level,permissions:new Set(permissions),sources:[grant.source]});else if(found.level===grant.level){for(let permission of permissions)found.permissions.add(permission);found.sources.includes(grant.source)||found.sources.push(grant.source)}}return byPattern}function combine(matched){return fromRules(canonical([...closest(matched).values()].map(({pattern,permissions})=>[pattern,permissions])))}function decide(matched,channel){let covering=[...closest(matched).values()].filter(({pattern})=>pattern.kind==="all"?!0:pattern.kind==="exact"?pattern.path===channel:under(channel,pattern.path)),specificity=({pattern})=>pattern.kind==="exact"?1/0:pattern.kind==="subtree"?pattern.path.length:-1,[winner,...beaten]=covering.sort((a,b)=>specificity(b)-specificity(a));return winner?{pattern:key(winner.pattern),over:beaten.map(({pattern})=>key(pattern)),level:winner.level,sources:winner.sources,permissions:[...winner.permissions].sort((a,b)=>ORDER.get(a)-ORDER.get(b))}:{pattern:null,over:[],level:null,sources:[],permissions:[]}}function canText(access){let entries=Object.entries(access.summary()).map(([pattern,permissions])=>`${pattern}=${permissions.join(",")}`);return entries.length>0?entries.join(";"):"*="}function parseCan(header,name="x-board-can"){if(header.length>4e3)throw new InvalidCan(`${name} is longer than ${CAN_MAX} characters`);let out={},entries=header.split(";").map(entry=>entry.trim());if(entries.every(entry=>entry===""))throw new InvalidCan(`${name} is empty: write pattern=permissions, like dev/=read,post`);for(let entry of entries){if(entry==="")continue;let split=entry.indexOf("=");if(split<0)throw new InvalidCan(`${name} entry ${entry} needs =: write pattern=permissions, like dev/=read,post`);let pattern=entry.slice(0,split).trim(),list=entry.slice(split+1).trim();if(Object.hasOwn(out,pattern))throw new InvalidCan(`${name} lists ${pattern} twice`);parsePattern(pattern);let permissions=list===""?[]:list.split(",").map(permission=>permission.trim());if(permissions.length===1&&permissions[0]==="all"){out[pattern]="all";continue}for(let permission of permissions)if(!ORDER.has(permission))throw new InvalidCan(`${name}: unknown permission ${permission||"(empty)"}: use ${PERMISSIONS.join(", ")}, or all`);out[pattern]=permissions}return out}function levelOf(principal,facts){let{caller}=facts;switch(principal.kind){case"everyone":return"everyone";case"all-users":return caller.kind==="user"&&facts.member===!0?"group":null;case"user":return caller.kind==="user"&&caller.userId===principal.userId?"principal":null;case"all-projects":return caller.kind==="project"&&facts.teamProject===!0&&principal.environments.includes(caller.environment)?"group":null;case"project":return caller.kind==="project"&&caller.projectId===principal.projectId&&(principal.teamId===void 0||caller.teamId===void 0||caller.teamId===principal.teamId)&&principal.environments.includes(caller.environment)?"principal":null;case"github":{if(caller.kind!=="github")return null;let same=principal.repositoryId!==void 0?caller.repositoryId===principal.repositoryId:caller.repository===principal.repository,workflow=principal.workflow===void 0||caller.ref!==void 0&&caller.workflowRef===`${caller.repository}/${principal.workflow}@${caller.ref}`,branch=principal.branch===void 0||caller.ref===`refs/heads/${principal.branch}`,event=principal.event===void 0||caller.event===principal.event;return same&&workflow&&branch&&event?"principal":null}case"app":return caller.kind==="app"&&caller.clientId===principal.clientId?"principal":null;case"all-apps":return caller.kind==="app"&&facts.teamApp===!0?"group":null;case"oidc":return caller.kind==="oidc"&&caller.issuer===principal.issuer&&Object.entries(principal.claims).every(([name,allowed])=>{let value=caller.claims[name];return value===void 0?!1:typeof allowed=="string"?String(value)===allowed:allowed.includes(String(value))})?"principal":null}}var RANK2={principal:0,group:1,everyone:2};function matchedFor(facts,own=!1){let matched=[];for(let grant of facts.grants){let best=null;for(let principal of grant.principals){if(own&&principal.kind==="everyone")continue;let level=levelOf(principal,facts);level!==null&&(best===null||RANK2[level]<RANK2[best])&&(best=level)}best!==null&&matched.push({level:best,can:grant.can,source:{grant}})}return matched}function admits(facts,matched=matchedFor(facts)){return facts.caller.kind==="user"&&facts.member===!0?!0:matched.some(found=>found.level!=="everyone")}function limited(access,facts){let out=facts.cap===void 0?access:access.narrow({"*":[...facts.cap]});return facts.can!==void 0&&(out=out.narrow(compileAccess(facts.can))),out}function grantAccess(facts){let matched=matchedFor(facts);return admits(facts,matched)?{caller:limited(combine(matched),facts),own:limited(combine(matchedFor(facts,!0)),facts)}:null}function explainGrants(facts,channel){let matched=matchedFor(facts);if(!admits(facts,matched))return{pattern:null,over:[],level:null,grants:[],capped:!1,permissions:[]};let decision=decide(matched,channel),cap=facts.cap===void 0?null:compileAccess({"*":[...facts.cap]}),capped=cap?decision.permissions.filter(permission=>cap.can(permission,channel)):[...decision.permissions],token=facts.can===void 0?null:compileAccess(facts.can);return{pattern:decision.pattern,over:[...decision.over],level:decision.level,grants:decision.sources.map(source=>source.grant),capped:capped.length<decision.permissions.length,permissions:token?capped.filter(permission=>token.can(permission,channel)):capped}}var VERCEL_ISSUER=/^https:\/\/oidc\.vercel\.com(?:\/[a-z0-9-]+)?$/;var issuerName=iss=>{let url=new URL(iss);return`${url.host}${url.pathname.replace(/\/+$/,"")}`.replace(/[%:]/g,char=>char==="%"?"%25":"%3A")};function trustedIssuers(issuers){let named=new Map;for(let iss of issuers){let name=issuerName(iss),other=named.get(name);if(other!==void 0&&other!==iss)throw new Error(`oidc issuers ${other} and ${iss} name the same principals, oidc:${name}:<sub>: pin one of them`);named.set(name,iss)}return new Set(issuers)}var DEFAULT_CAN=Object.freeze({"*":Object.freeze(["read","post","react","label"])});function privateHost(host){let name=host.toLowerCase().replace(/\.$/,"");return name.startsWith("[")||/^\d+(\.\d+){3}$/.test(name)||/^\d+$/.test(name)||!name.includes(".")||name==="localhost"?!0:/\.(localhost|local|internal|home|lan|corp|intranet)$/.test(name)}var userIdOf=id=>id.split(":").slice(2).join(":");function callerFacts(principal,facts,team){let claims=facts?.claims??{};return principal.kind==="person"?{caller:{kind:"user",userId:userIdOf(principal.id)},member:!0}:facts?.issuer==="vercel"?{caller:{kind:"project",projectId:String(claims.project_id??""),environment:String(claims.environment??""),...typeof claims.owner_id=="string"?{teamId:claims.owner_id}:{}},teamProject:team!==null&&claims.owner_id===team}:facts?.issuer==="github"?{caller:{kind:"github",repository:String(claims.repository??""),...claims.repository_id!==void 0?{repositoryId:String(claims.repository_id)}:{},...claims.workflow_ref!==void 0?{workflowRef:String(claims.workflow_ref)}:{},...claims.ref!==void 0?{ref:String(claims.ref)}:{},...claims.event_name!==void 0?{event:String(claims.event_name)}:{}}}:facts?.issuer==="oidc"?{caller:{kind:"oidc",issuer:facts.iss,claims}}:null}function verifiedIssuers(base,granted){let taken=new Set(base.map(issuerName)),issuers=[...base];for(let issuer of granted){if(base.includes(issuer))continue;let url=URL.parse(issuer);if(url?.protocol!=="https:"||privateHost(url.hostname))continue;let name=issuerName(issuer);taken.has(name)||(taken.add(name),issuers.push(issuer))}return issuers}var grantIssuers=grants=>[...new Set(grants.flatMap(grant=>grant.principals.flatMap(principal=>principal.kind==="oidc"?[principal.issuer]:[])))],notGranted=(who,grant)=>new HttpError(403,"forbidden",`this token can't use this board: no grant lets in ${who}`,{hint:`Grant it: vb grants create ${grant}`});function createAuthority(options){async function factsFor(principal,facts,team,snapshot){let grants=snapshot??(options.grants?await options.grants():[]),known=callerFacts(principal,facts,team);return{grants,facts:known?{...known,grants}:null}}async function byGrants(principal,facts,snapshot){let claims=facts?.claims??{},own=facts?.issuer==="vercel"?await options.project():null,environment=String(claims.environment??""),here=boardEnvironment(),ownDeployment=own!==null&&own.id!==null&&claims.project_id===own.id;if(ownDeployment&&here!==null&&environment===here)return{fixed:FULL_ACCESS};if(!facts)throw forbidden("this token can't use this board");let{grants,facts:found}=await factsFor(principal,facts,own?.teamId??null,snapshot);if(found&&admits(found))return{facts:found};if(facts.issuer==="oidc"&&!grantIssuers(grants).includes(facts.iss))throw unauthorized(`untrusted issuer: ${facts.iss}`);if(facts.issuer==="oidc")throw forbidden("this token can't use this board: no grant lets in its claims");if(facts.issuer==="github"){let repository=String(claims.repository??"");throw notGranted(repository||"its repository",`--github ${repository||"<OWNER/REPO>"}`)}let project=String(claims.project_id??"")||"<PROJECT_ID>",grant2=`--project ${project} --environment ${environment||"<ENVIRONMENT>"}`;throw ownDeployment?new HttpError(403,"forbidden",`this token can't use this board: it runs in ${here??"no Vercel environment"}, and its ${environment||"unnamed"} deployments need a grant`,{hint:`Grant them: vb grants create ${grant2}`}):notGranted(`project ${project} in ${environment||"no environment"}`,grant2)}async function resolve2(principal,snapshot){let hosted=principal.facts?.issuer==="host";if(principal.id.startsWith("board:")||principal.kind==="external"&&!hosted)return{fixed:FULL_ACCESS};if(hosted){if(!options.hosts)throw forbidden("this token can't use this board: its board no longer takes a host's principals");let{exp}=principal.facts.claims;if(typeof exp=="number"&&exp*1e3<=Date.now())throw unauthorized("token expired")}if(principal.kind==="person"){if(!options.grants)return{fixed:FULL_ACCESS};let{facts}=await factsFor(principal,null,null,snapshot);return{facts}}return byGrants(principal,(hosted?void 0:principal.facts)??factsFromId(principal.id),snapshot)}async function grant(principal,snapshot){let resolved=await resolve2(principal,snapshot),scope=principal.scope===void 0?void 0:parseCan(principal.scope);if("fixed"in resolved)return scope===void 0?resolved.fixed:resolved.fixed.narrow(scope);let decided=grantAccess({...resolved.facts,...scope!==void 0?{can:scope}:{}});if(!decided)throw forbidden("this token can't use this board");return decided.caller}async function accessNow(principal,snapshot){try{return await grant(principal,snapshot)}catch(error){let status=error.status;if(status===401||status===403)return null;throw error}}return{grant,accessNow,resolve:resolve2}}var boardEnvironment=()=>process.env.VERCEL_TARGET_ENV||process.env.VERCEL_ENV||null;function factsFromId(id){let deployment=id.match(/^vercel:project:([^:]+):([^:]+)$/);return deployment?{issuer:"vercel",iss:"",claims:{project_id:deployment[1],environment:deployment[2]}}:null}var TOKENS=Symbol("board.oidcTokens"),LOGINS=Symbol("board.logins"),namesByLogin=authenticate=>LOGINS in authenticate,verifiedTokens=new WeakSet;function markVerified(principal){return verifiedTokens.add(principal),principal}var verifiesTokens=authenticate=>TOKENS in authenticate,fromTokens=principal=>verifiedTokens.has(principal),PRINCIPAL_ID=/^[a-z][a-z0-9-]*:[a-z][a-z0-9-]*:[^\s+\]]{1,200}$/,KINDS=["person","deployment","workflow","external"];function hostPrincipal(value){let fail=why=>{throw new TypeError(`authenticate returned an invalid principal: ${why}`)};(typeof value!="object"||value===null)&&fail("not an object"),(typeof value.id!="string"||!PRINCIPAL_ID.test(value.id)||value.id.startsWith("board:"))&&fail(`id must look like \`vercel:user:<id>\`, got ${JSON.stringify(value.id)}`),KINDS.includes(value.kind)||fail(`kind must be one of ${KINDS.join(", ")}`),(typeof value.handle!="string"||!/^\S{1,64}$/.test(value.handle))&&fail("handle must be 1-64 characters, no spaces");let expiresAt=value.expiresAt??null;if(expiresAt!==null&&(!(expiresAt instanceof Date)||Number.isNaN(expiresAt.getTime()))&&fail("expiresAt must be a Date or null"),expiresAt!==null&&expiresAt.getTime()<=Date.now())throw unauthorized("token expired");let claims=expiresAt===null?{}:{exp:Math.floor(expiresAt.getTime()/1e3)};return{id:value.id,kind:value.kind,handle:value.handle,expiresAt,facts:{issuer:"host",iss:"",claims}}}var JOSEError=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(message2,options){super(message2,options),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},JWTClaimValidationFailed=class extends JOSEError{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(message2,payload,claim="unspecified",reason="unspecified"){super(message2,{cause:{claim,reason,payload}}),this.claim=claim,this.reason=reason,this.payload=payload}},JWTExpired=class extends JOSEError{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(message2,payload,claim="unspecified",reason="unspecified"){super(message2,{cause:{claim,reason,payload}}),this.claim=claim,this.reason=reason,this.payload=payload}},JOSEAlgNotAllowed=class extends JOSEError{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},JOSENotSupported=class extends JOSEError{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"};var JWSInvalid=class extends JOSEError{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},JWTInvalid=class extends JOSEError{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"};var JWKSInvalid=class extends JOSEError{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},JWKSNoMatchingKey=class extends JOSEError{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(message2="no applicable key found in the JSON Web Key Set",options){super(message2,options)}},JWKSMultipleMatchingKeys=class extends JOSEError{[Symbol.asyncIterator]=async function*(){};static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(message2="multiple matching keys found in the JSON Web Key Set",options){super(message2,options)}},JWKSTimeout=class extends JOSEError{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(message2="request timed out",options){super(message2,options)}},JWSSignatureVerificationFailed=class extends JOSEError{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(message2="signature verification failed",options){super(message2,options)}};function table(entries){let out={__proto__:null};for(let alg in entries)out[alg]={...entries[alg],alg};return out}var sig=[["verify"],["sign"]];function hmac(bits){let subtle={name:"HMAC",hash:`SHA-${bits}`};return{kty:["oct"],secret:!0,subtle,signing:subtle,usages:sig}}function rsa(bits,saltLength){let subtle={name:saltLength?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${bits}`};return{kty:["RSA"],subtle,signing:saltLength?{...subtle,saltLength}:subtle,usages:sig,minRsaBits:2048}}function ecdsa(crv,bits){return{kty:["EC"],crv,subtle:{name:"ECDSA",namedCurve:crv},signing:{name:"ECDSA",hash:`SHA-${bits}`},usages:sig}}function eddsa(){let subtle={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle,signing:subtle,usages:sig}}function mldsa(parameterSet){let subtle={name:`ML-DSA-${parameterSet}`};return{kty:["AKP"],subtle,signing:subtle,usages:sig}}var JWS=table({HS256:hmac(256),HS384:hmac(384),HS512:hmac(512),RS256:rsa(256),RS384:rsa(384),RS512:rsa(512),PS256:rsa(256,32),PS384:rsa(384,48),PS512:rsa(512,64),ES256:ecdsa("P-256",256),ES384:ecdsa("P-384",384),ES512:ecdsa("P-521",512),EdDSA:eddsa(),Ed25519:eddsa(),"ML-DSA-44":mldsa(44),"ML-DSA-65":mldsa(65),"ML-DSA-87":mldsa(87)});function jwsAlgorithm(alg){let entry=typeof alg=="string"?JWS[alg]:void 0;if(!entry)throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);return entry}var encoder=new TextEncoder,decoder=new TextDecoder,strictDecoder=new TextDecoder("utf-8",{fatal:!0}),UINT32_RANGE=2**32;function concat(...buffers){let size=buffers.reduce((acc,{length})=>acc+length,0),buf=new Uint8Array(size),i=0;for(let buffer of buffers)buf.set(buffer,i),i+=buffer.length;return buf}var NON_ASCII=/[^\x00-\x7f]/;function encode(string){if(typeof string=="string"&&string.length>=128){if(NON_ASCII.test(string))throw new TypeError("non-ASCII string encountered in encode()");return encoder.encode(string)}let bytes=new Uint8Array(string.length);for(let i=0;i<string.length;i++){let code=string.charCodeAt(i);if(code>127)throw new TypeError("non-ASCII string encountered in encode()");bytes[i]=code}return bytes}function decodeBase64(encoded,url=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(encoded,{alphabet:url?"base64url":"base64"});if(url){if(encoded.includes("+")||encoded.includes("/"))throw new TypeError("Invalid base64url");encoded=encoded.replace(/-/g,"+").replace(/_/g,"/")}let binary=atob(encoded),bytes=new Uint8Array(binary.length);for(let i=0;i<binary.length;i++)bytes[i]=binary.charCodeAt(i);return bytes}var invalid="The input to be decoded is not correctly encoded.";function decode(input){try{return decodeBase64(typeof input=="string"?input:decoder.decode(input),!0)}catch(cause){throw new TypeError(invalid,{cause})}}function isObject(input){if(typeof input!="object"||input===null||Object.prototype.toString.call(input)!=="[object Object]")return!1;let prototype=Object.getPrototypeOf(input);return prototype===null||Object.getPrototypeOf(prototype)===null}function isJwkSet(input){return isObject(input)&&Array.isArray(input.keys)&&Array.from(input.keys).every(isObject)}function isDisjoint(...headers){let parameters=new Set;for(let header of headers)if(header)for(let parameter of Object.keys(header)){if(parameters.has(parameter))return!1;parameters.add(parameter)}return!0}function decodeBase64url(value,label,ErrorClass){try{return decode(value)}catch(cause){throw new ErrorClass(`Failed to base64url decode the ${label}`,{cause})}}function encodeAsciiMember(value,label,ErrorClass){try{return encode(value)}catch(cause){throw new ErrorClass(`The ${label} is not a valid base64url string`,{cause})}}function parseJoseHeader(encodedProtectedHeader,ErrorClass,message2){let parsed;try{parsed=JSON.parse(strictDecoder.decode(decode(encodedProtectedHeader)))}catch(cause){throw new ErrorClass(message2,{cause})}if(!isObject(parsed))throw new ErrorClass(message2);return parsed}var JWS_RECOGNIZED={__proto__:null,b64:!0};function validateAlgorithms(option,algorithms){if(algorithms!==void 0&&(!Array.isArray(algorithms)||algorithms.some(s=>typeof s!="string")))throw new TypeError(`"${option}" option must be an array of strings`);return algorithms===void 0?void 0:new Set(algorithms)}function validateCrit(Err,recognizedDefault,recognizedOption,protectedHeader,joseHeader){if(joseHeader.crit!==void 0&&protectedHeader?.crit===void 0)throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');if(!protectedHeader||protectedHeader.crit===void 0)return[];if(!Array.isArray(protectedHeader.crit)||protectedHeader.crit.length===0||protectedHeader.crit.some(input=>typeof input!="string"||input.length===0))throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let recognized=recognizedOption===void 0?recognizedDefault:{__proto__:null,...recognizedOption,...recognizedDefault};for(let parameter of protectedHeader.crit){if(!(parameter in recognized))throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);if(!Object.hasOwn(joseHeader,parameter)||joseHeader[parameter]===void 0)throw new Err(`Extension Header Parameter "${parameter}" is missing`);if(recognized[parameter]&&(!Object.hasOwn(protectedHeader,parameter)||protectedHeader[parameter]===void 0))throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`)}return protectedHeader.crit}function validateB64(protectedHeader,extensions){if(extensions.includes("b64")){let b64=protectedHeader.b64;if(typeof b64!="boolean")throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return b64}return!0}var tag=key2=>key2[Symbol.toStringTag],jwkMatchesOp=(entry,key2,usage)=>{let{alg}=entry;if(key2.use!==void 0){let expected=usage==="sign"||usage==="verify"?"sig":"enc";if(key2.use!==expected)throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`)}if(key2.alg!==void 0&&key2.alg!==alg)throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);if(Array.isArray(key2.key_ops)){let expectedKeyOp=usage==="encrypt"||usage==="decrypt"?entry.ops?.[usage==="encrypt"?0:1]:usage;if(expectedKeyOp&&!key2.key_ops.includes(expectedKeyOp))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`)}};async function prepareKey(entry,key2,usage){let{alg,secret}=entry,requiresPrivateKey=usage==="decrypt"||usage==="sign";if(secret&&key2 instanceof Uint8Array)return key2;let normalized,keyObject;if(isObject(key2)){if(normalized=normalizeJwk(key2),typeof normalized.kty!="string")throw invalidKeyType(alg,key2,secret);if(!(secret?normalized.kty==="oct"&&typeof normalized.k=="string":normalized.kty!=="oct"&&(requiresPrivateKey?normalized.kty==="AKP"&&typeof normalized.priv=="string"||typeof normalized.d=="string":normalized.d===void 0&&normalized.priv===void 0)))throw new TypeError(secret?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${requiresPrivateKey?"private":"public"} JWK`);if(jwkMatchesOp(entry,normalized,usage),normalized.kty==="oct")return decode(normalized.k);if(!Object.isFrozen(key2)){let{key_ops}=key2;Array.isArray(key_ops)&&Object.freeze(key_ops),Object.freeze(key2)}}else{if(!isKeyLike(key2))throw invalidKeyType(alg,key2,secret);let expectedType=secret?"secret":requiresPrivateKey?"private":"public";if(key2.type!==expectedType&&(secret||["secret","public","private"].includes(key2.type)))throw new TypeError(`${tag(key2)} instances must be of type "${expectedType}" for the ${alg} algorithm`);if(isCryptoKey(key2))return key2;if(keyObject=key2,keyObject.type==="secret")return keyObject.export()}cache||=new WeakMap;let cacheKey=key2,cached=cache.get(cacheKey);if(cached?.[alg])return cached[alg];if(cached||cache.set(cacheKey,cached={}),keyObject&&typeof keyObject.toCryptoKey=="function"){let isPublic=keyObject.type==="public",crv=nist[keyObject.asymmetricKeyDetails?.namedCurve],params=entry.resolve?.({crv,asymmetricKeyType:keyObject.asymmetricKeyType})??entry.subtle;return cached[alg]=keyObject.toCryptoKey(params,isPublic,entry.usages[isPublic?0:1])}return normalized??=keyObject.export({format:"jwk"}),normalized.alg=alg,cached[alg]=await jwkToKey(entry,normalized)}var cache,nist={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};var isCryptoKey=key2=>{if(key2?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return key2 instanceof CryptoKey}catch{return!1}},isKeyObject=key2=>key2?.[Symbol.toStringTag]==="KeyObject",isKeyLike=key2=>isCryptoKey(key2)||isKeyObject(key2);function message(msg,actual,...types){if(types.length>2){let last=types.pop();msg+=`one of type ${types.join(", ")}, or ${last}.`}else types.length===2?msg+=`one of type ${types[0]} or ${types[1]}.`:msg+=`of type ${types[0]}.`;return actual==null?msg+=` Received ${actual}`:typeof actual=="function"&&actual.name?msg+=` Received function ${actual.name}`:typeof actual=="object"&&actual!=null&&actual.constructor?.name&&(msg+=` Received an instance of ${actual.constructor.name}`),msg}function invalidKeyType(alg,actual,secret){let types=["CryptoKey","KeyObject","JSON Web Key"];return secret&&types.push("Uint8Array"),new TypeError(message(`Key for the ${alg} algorithm must be `,actual,...types))}var unusable=(name,prop="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);function checkUsage(key2,usage){if(usage&&!key2.usages.includes(usage))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`)}function checkModulusLength(alg,key2){let{modulusLength}=key2.algorithm;if(typeof modulusLength!="number"||modulusLength<2048)throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`)}function checkCryptoKey(key2,expected,usage){let algorithm=key2.algorithm;if(algorithm.name!==expected.name)throw unusable(expected.name);if(expected.hash&&algorithm.hash?.name!==expected.hash)throw unusable(expected.hash,"algorithm.hash");if(expected.namedCurve&&algorithm.namedCurve!==expected.namedCurve)throw unusable(expected.namedCurve,"algorithm.namedCurve");if(expected.length!==void 0&&algorithm.length!==expected.length)throw unusable(expected.length,"algorithm.length");checkUsage(key2,usage)}function snapshotJwk(jwk){return{__proto__:null,...jwk}}function normalizeJwk(jwk){let normalized=snapshotJwk(jwk);if(normalized.ext!==void 0&&typeof normalized.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(normalized.key_ops!==void 0){let value=normalized.key_ops,keyOps=Array.isArray(value)?[...value]:void 0;if(!keyOps||keyOps.some(operation=>typeof operation!="string")||new Set(keyOps).size!==keyOps.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');normalized.key_ops=keyOps}return normalized}async function jwkToKey(entry,jwk,extractable){if(!entry.kty.includes(jwk.kty))throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let algorithm=entry.resolve?.({kty:jwk.kty,crv:jwk.crv})??entry.subtle,isPrivate=!!(jwk.d||jwk.priv),keyData={...jwk,ext:extractable??jwk.ext};return keyData.kty!=="AKP"&&delete keyData.alg,delete keyData.use,crypto.subtle.importKey("jwk",keyData,algorithm,keyData.ext??!isPrivate,jwk.key_ops??entry.usages[isPrivate?1:0])}async function rawKey(key2,expected,usage,extractable=!1){return key2 instanceof Uint8Array&&(key2=await crypto.subtle.importKey("raw",key2,expected,extractable,[usage])),checkCryptoKey(key2,expected,usage),key2}function prepareVerify(options){return[options&&validateAlgorithms("algorithms",options.algorithms),options?.crit]}function parseProtectedHeader(encodedProtectedHeader){return encodedProtectedHeader===void 0?{}:parseJoseHeader(encodedProtectedHeader,JWSInvalid,"JWS Protected Header is invalid")}function encodeCompactUnencodedPayload(payload){try{return encode(payload)}catch(cause){throw new JWSInvalid("JWS Compact Serialization payload must use only ASCII characters",{cause})}}async function verifySignature(jws,shared,key2,encodeUnencodedPayload,parsedProtected){let{protected:encodedProtectedHeader,header,payload:inputPayload}=jws,protectedHeader=parsedProtected??parseProtectedHeader(encodedProtectedHeader);if(!isDisjoint(protectedHeader,header))throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let joseHeader={...protectedHeader,...header},b64=validateB64(protectedHeader,validateCrit(JWSInvalid,JWS_RECOGNIZED,shared[1],protectedHeader,joseHeader)),{alg}=joseHeader;if(typeof alg!="string"||!alg)throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(shared[0]&&!shared[0].has(alg))throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');if(b64){if(typeof inputPayload!="string")throw new JWSInvalid("JWS Payload must be a string")}else if(typeof inputPayload!="string"&&!(inputPayload instanceof Uint8Array))throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");let signingPayload=b64||typeof inputPayload!="string"?inputPayload:encodeUnencodedPayload(inputPayload),resolvedKey=!1;typeof key2=="function"&&(key2=await key2(protectedHeader,jws),resolvedKey=!0);let entry=jwsAlgorithm(alg),signingInput=concat(encodedProtectedHeader!==void 0?encode(encodedProtectedHeader):new Uint8Array,encode("."),typeof signingPayload=="string"?shared[2]??=encodeAsciiMember(signingPayload,"payload",JWSInvalid):signingPayload),signature=decodeBase64url(jws.signature,"signature",JWSInvalid),verificationKey=await prepareKey(entry,key2,"verify"),cryptoKey=await rawKey(verificationKey,entry.subtle,"verify");entry.minRsaBits&&checkModulusLength(entry.alg,cryptoKey);let verified=!1;try{verified=await crypto.subtle.verify(entry.signing,cryptoKey,signature,signingInput)}catch(cause){throw new JWSSignatureVerificationFailed(void 0,{cause})}if(!verified)throw new JWSSignatureVerificationFailed;let result={payload:typeof signingPayload=="string"?decodeBase64url(signingPayload,"payload",JWSInvalid):signingPayload};return encodedProtectedHeader!==void 0&&(result.protectedHeader=protectedHeader),header!==void 0&&(result.unprotectedHeader=header),resolvedKey?[{...result,key:verificationKey},b64]:[result,b64]}async function verifyCompact(jws,shared,key2){if(jws instanceof Uint8Array&&(jws=decoder.decode(jws)),typeof jws!="string")throw new JWSInvalid("Compact JWS must be a string or Uint8Array");let{0:protectedHeader,1:payload,2:signature,length}=jws.split(".");if(length!==3)throw new JWSInvalid("Invalid Compact JWS");return verifySignature({payload,protected:protectedHeader,signature},shared,key2,encodeCompactUnencodedPayload)}var epoch=date=>Math.floor(date.getTime()/1e3),multipliers={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},REGEX=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,checkFailed="check_failed";function invalidDuration(){throw new TypeError("Invalid time period format")}function secs(str){typeof str!="string"&&invalidDuration();let matched=REGEX.exec(str);(!matched||matched[4]&&matched[1])&&invalidDuration();let value=parseFloat(matched[2]),durationSeconds=Math.round(value*multipliers[matched[3][0].toLowerCase()]);return Number.isFinite(durationSeconds)||invalidDuration(),matched[1]==="-"||matched[4]==="ago"?-durationSeconds:durationSeconds}function validateInput(label,input){if(!Number.isFinite(input))throw new TypeError(`Invalid ${label} input`);return input}var normalizeTyp=value=>{let normalized=value.toLowerCase();return value.includes("/")?normalized:`application/${normalized}`},checkAudiencePresence=(audPayload,audOption)=>typeof audPayload=="string"?audOption.includes(audPayload):Array.isArray(audPayload)?audOption.some(aud=>audPayload.includes(aud)):!1;function validateNumericDate(claimsSet,claim,required=!1){let value=claimsSet[claim];if(!(value===void 0&&!required)){if(typeof value!="number")throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`,claimsSet,claim,"invalid");return value}}function unexpectedClaim(claimsSet,claim){throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`,claimsSet,claim,checkFailed)}function validateClaimsSet(protectedHeader,claimsSetBytes,options={}){let claimsSet;try{claimsSet=JSON.parse(strictDecoder.decode(claimsSetBytes))}catch(cause){throw new JWTInvalid("JWT Claims Set must be a top-level JSON object",{cause})}if(!isObject(claimsSet))throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");let{typ}=options;if(typ!==void 0&&(typeof protectedHeader.typ!="string"||normalizeTyp(protectedHeader.typ)!==normalizeTyp(typ)))throw new JWTClaimValidationFailed('unexpected "typ" JWT header value',claimsSet,"typ",checkFailed);let{requiredClaims=[],issuer,subject,audience,maxTokenAge}=options,presenceCheck=[...requiredClaims];maxTokenAge!==void 0&&presenceCheck.push("iat"),audience!==void 0&&presenceCheck.push("aud"),subject!==void 0&&presenceCheck.push("sub"),issuer!==void 0&&presenceCheck.push("iss");for(let claim of new Set(presenceCheck.reverse()))if(!Object.hasOwn(claimsSet,claim))throw new JWTClaimValidationFailed(`missing required "${claim}" claim`,claimsSet,claim,"missing");issuer!==void 0&&!(Array.isArray(issuer)?issuer:[issuer]).includes(claimsSet.iss)&&unexpectedClaim(claimsSet,"iss"),subject!==void 0&&claimsSet.sub!==subject&&unexpectedClaim(claimsSet,"sub"),audience!==void 0&&!checkAudiencePresence(claimsSet.aud,typeof audience=="string"?[audience]:audience)&&unexpectedClaim(claimsSet,"aud");let{clockTolerance}=options,tolerance=0;if(typeof clockTolerance=="string")tolerance=secs(clockTolerance);else if(clockTolerance!==void 0){if(typeof clockTolerance!="number")throw new TypeError("Invalid clockTolerance option type");tolerance=clockTolerance}validateInput("clockTolerance option",tolerance);let{currentDate}=options,now=validateInput("currentDate option",epoch(currentDate===void 0?new Date:currentDate)),iat=validateNumericDate(claimsSet,"iat",maxTokenAge!==void 0),nbf=validateNumericDate(claimsSet,"nbf");if(nbf!==void 0&&nbf>now+tolerance)throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed',claimsSet,"nbf",checkFailed);let exp=validateNumericDate(claimsSet,"exp");if(exp!==void 0&&exp<=now-tolerance)throw new JWTExpired('"exp" claim timestamp check failed',claimsSet,"exp",checkFailed);if(maxTokenAge!==void 0){let age=now-iat,max=validateInput("maxTokenAge option",typeof maxTokenAge=="number"?maxTokenAge:secs(maxTokenAge));if(age-tolerance>max)throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)',claimsSet,"iat",checkFailed);if(age<-tolerance)throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)',claimsSet,"iat",checkFailed)}return claimsSet}async function jwtVerify(jwt,key2,options){let[verified,b64]=await verifyCompact(jwt,prepareVerify(options),key2);if(!b64)throw new JWTInvalid("JWTs MUST NOT use unencoded payload");let payload=validateClaimsSet(verified.protectedHeader,verified.payload,options);return{...verified,payload}}function isUsableJWK(jwk,entry,alg,kid){let{kty,key_ops:keyOps,ext,kid:jwkKid,alg:jwkAlg,use,crv}=jwk;return(ext===void 0||typeof ext=="boolean")&&(keyOps===void 0||Array.isArray(keyOps)&&keyOps.every((operation,index)=>typeof operation=="string"&&keyOps.indexOf(operation)===index)&&keyOps.includes("verify"))&&entry.kty.includes(kty)&&(kid===void 0||typeof kid=="string"&&kid===jwkKid)&&(jwkAlg===void 0?kty!=="AKP":alg===jwkAlg)&&(use===void 0||use==="sig")&&(!entry.crv||crv===entry.crv)}async function importWithAlgCache(cache2,jwk,entry){let cached=cache2.get(jwk)||cache2.set(jwk,{}).get(jwk),{alg}=entry;if(cached[alg]===void 0){let pending=jwkToKey(entry,jwk,!0).then(key2=>{if(key2.type!=="public")throw new JWKSInvalid("JSON Web Key Set members must be public keys");return cached[alg]=key2,key2}).catch(error=>{throw cached[alg]===pending&&delete cached[alg],error});cached[alg]=pending}return cached[alg]}function createLocalJWKSet(jwks){let snapshot;try{snapshot=structuredClone(jwks)}catch(cause){throw new JWKSInvalid("JSON Web Key Set malformed",{cause})}if(!isJwkSet(snapshot))throw new JWKSInvalid("JSON Web Key Set malformed");let metadata=snapshot.keys.map(jwk=>{let normalized=snapshotJwk(jwk);return Array.isArray(normalized.key_ops)&&(normalized.key_ops=[...normalized.key_ops]),normalized}),cached=new WeakMap;return Object.defineProperty(async(protectedHeader,token)=>{let{alg,kid}={...protectedHeader,...token?.header},entry=typeof alg=="string"?JWS[alg]:void 0;if(!entry||entry.secret)throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');let candidates=snapshot.keys.filter((_,index)=>isUsableJWK(metadata[index],entry,alg,kid)),{0:jwk,length}=candidates;if(!length)throw new JWKSNoMatchingKey;if(length!==1){let error=new JWKSMultipleMatchingKeys;throw error[Symbol.asyncIterator]=async function*(){for(let jwk2 of candidates)try{yield await importWithAlgCache(cached,jwk2,entry)}catch{}},error}return importWithAlgCache(cached,jwk,entry)},"jwks",{value:()=>structuredClone(snapshot)})}function isCloudflareWorkers(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var USER_AGENT;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(USER_AGENT="jose/v6.2.14");var customFetch=Symbol();async function fetchJwks(url,headers,signal,fetchImpl=fetch){let response=await fetchImpl(url,{method:"GET",signal,redirect:"manual",headers}).catch(err=>{throw err.name==="TimeoutError"?new JWKSTimeout(void 0,{cause:err}):err});if(response.status!==200)throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await response.json()}catch(cause){throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON",{cause})}}var jwksCache=Symbol();function isFreshFor(timestamp,duration){return Number.isFinite(timestamp)&&Date.now()<timestamp+duration}function validateDuration(value,fallback,option){if(Number.isNaN(value))throw new TypeError(`"${option}" option must not be NaN`);return typeof value=="number"?value:fallback}function createRemoteJWKSet(url,options){if(!(url instanceof URL))throw new TypeError("url must be an instance of URL");let href=new URL(url.href).href,opts=options??{},timeoutOption=opts.timeoutDuration;if(typeof timeoutOption=="number"&&(!Number.isInteger(timeoutOption)||timeoutOption<0))throw new TypeError('"timeoutDuration" option must be a non-negative integer');let timeoutDuration=typeof timeoutOption=="number"?timeoutOption:5e3,cooldownDuration=validateDuration(opts.cooldownDuration,3e4,"cooldownDuration"),cacheMaxAge=validateDuration(opts.cacheMaxAge,6e5,"cacheMaxAge"),headers=new Headers(opts.headers);USER_AGENT&&!headers.has("User-Agent")&&headers.set("User-Agent",USER_AGENT),headers.has("accept")||headers.set("accept","application/json, application/jwk-set+json");let fetchImpl=opts[customFetch],cache2=opts[jwksCache],jwksTimestamp,pendingFetch,reloadSequence=0,appliedSequence=0,local;if(cache2&&typeof cache2=="object"){let{uat,jwks}=cache2;isFreshFor(uat,cacheMaxAge)&&isJwkSet(jwks)&&(jwksTimestamp=uat,local=createLocalJWKSet(jwks))}let reload=async()=>{if(pendingFetch&&isCloudflareWorkers()&&(pendingFetch=void 0),!pendingFetch){let sequence=++reloadSequence,current=pendingFetch=fetchJwks(href,headers,AbortSignal.timeout(timeoutDuration),fetchImpl).then(json=>{let next=createLocalJWKSet(json);if(sequence<=appliedSequence)return;local=next;let updatedAt=Date.now();cache2&&(cache2.uat=updatedAt,cache2.jwks=json),jwksTimestamp=updatedAt,appliedSequence=sequence}).finally(()=>{pendingFetch===current&&(pendingFetch=void 0)})}await pendingFetch};return Object.defineProperties(async(protectedHeader,token)=>{(!local||!isFreshFor(jwksTimestamp,cacheMaxAge))&&await reload();try{return await local(protectedHeader,token)}catch(err){if(err instanceof JWKSNoMatchingKey&&!isFreshFor(jwksTimestamp,cooldownDuration))return await reload(),local(protectedHeader,token);throw err}},{coolingDown:{get:()=>isFreshFor(jwksTimestamp,cooldownDuration),enumerable:!0},fresh:{get:()=>isFreshFor(jwksTimestamp,cacheMaxAge),enumerable:!0},reload:{value:reload,enumerable:!0},reloading:{get:()=>!!pendingFetch,enumerable:!0},jwks:{value:()=>local?.jwks(),enumerable:!0}})}function decodeJwt(jwt){if(typeof jwt!="string")throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");let{1:encodedPayload,length}=jwt.split(".");if(length===5)throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");if(length!==3)throw new JWTInvalid("Invalid JWT");if(!encodedPayload)throw new JWTInvalid("JWTs must contain a payload");let claimsSetBytes;try{claimsSetBytes=decode(encodedPayload)}catch(cause){throw new JWTInvalid("Failed to base64url decode the payload",{cause})}let claimsSet;try{claimsSet=JSON.parse(strictDecoder.decode(claimsSetBytes))}catch(cause){throw new JWTInvalid("Failed to parse the decoded payload as JSON",{cause})}if(!isObject(claimsSet))throw new JWTInvalid("Invalid JWT Claims Set");return claimsSet}export{PERMISSIONS,InvalidCan,parsePattern,compileAccess,FULL_ACCESS,canText,parseCan,explainGrants,VERCEL_ISSUER,issuerName,trustedIssuers,DEFAULT_CAN,privateHost,verifiedIssuers,grantIssuers,createAuthority,TOKENS,namesByLogin,markVerified,verifiesTokens,fromTokens,hostPrincipal,jwtVerify,createRemoteJWKSet,decodeJwt};
@@ -1,7 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module';
2
- import { fileURLToPath as __fileURLToPath } from 'node:url';
3
- import { dirname as __dirname_ } from 'node:path';
4
- const require = __createRequire(import.meta.url);
5
- const __filename = __fileURLToPath(import.meta.url);
6
- const __dirname = __dirname_(__filename);
7
- var options={re:{type:"string",value:"id",description:"in a thread: its root's ID"},by:{type:"string",value:"handle",description:"by an author: a handle, me, or an actor ID"},mentions:{type:"string",value:"@handle",optionalValue:!0,description:"mentioning a handle or email, or you without one"},label:{type:"string",multiple:!0,value:"k[=v|w]",description:"with a label on the message or its thread's root"},source:{type:"string",value:"source",description:"from a source: a sync key such as slack, or board"},text:{type:"string",value:"words",description:"containing this text, as one phrase (a substring, not word search)"},after:{type:"string",value:"id",description:"only what came after a message or a cursor (read and wait print one)"},url:{type:"string",value:"url",description:"the board at this URL, not the one the environment points at"},scope:{type:"string",value:"team",description:"a team's board in Vercel's API, by its slug or ID"},name:{type:"string",value:"board",description:"the team's board with this name, on --scope's team"},ensure:{type:"boolean",description:"with --name: make that board if the team has none by that name"},team:{type:"string",value:"team",description:"the same as --scope",hidden:!0},as:{type:"string",value:"profile",description:"write as a profile, such as an agent's name"},avatar:{type:"string",value:"url",description:"the profile's avatar, with --as"},json:{type:"boolean",description:"JSON, for programs"},help:{type:"boolean",short:"h",description:"this help, or a command's"},version:{type:"boolean",short:"v",description:"the CLI's version"},limit:{type:"string",short:"n",value:"N",description:"how many"},"idempotency-key":{type:"string",value:"key",description:"sending the same one again posts once"},sync:{type:"string",multiple:!0,value:"target",description:"sync the new thread to a target too, e.g. slack:#incidents"},"no-sync":{type:"boolean",description:"keep it on the board: sync it nowhere"},attach:{type:"string",multiple:!0,value:"file",description:"attach a file: up to 10 per message, each up to 100 MB (4 MB on some boards)"},file:{type:"string",value:"path",description:"from a file: - reads stdin"},data:{type:"string",value:"json",description:"as JSON, written inline"},unset:{type:"string",multiple:!0,value:"k",description:"remove a label"},if:{type:"string",multiple:!0,value:"k=v",description:"only while the message has this label now"},"if-unset":{type:"string",multiple:!0,value:"k",description:"only while the message doesn't have this label"},"if-revision":{type:"string",value:"N",description:"only if it is still at this revision, as read --json shows it"},channel:{type:"string",value:"c",description:"in a channel"},remove:{type:"boolean",description:"take the reaction back"},all:{type:"boolean",short:"a",description:"everything, not only what most want"},timeout:{type:"string",value:"duration",description:"how long to wait: 30s, 10m, or a bare number of seconds (default: 30m)"},"no-open":{type:"boolean",description:"don't open the browser"},"allow-host":{type:"string",multiple:!0,value:"host",description:"also answer requests for this host, from a proxy in front: whoever reaches it there acts as you"},tailscale:{type:"string",multiple:!0,value:"host",description:"also answer requests for this host, the board's name on your tailnet behind tailscale serve: whoever Tailscale says is calling is a person on the board"},in:{type:"string",value:"duration",description:"once, this long from now, e.g. 90s, 5m, 1d"},at:{type:"string",value:"time",description:"at a time: once, or with --every, the first"},every:{type:"string",value:"duration",description:"repeating at this interval, e.g. 30m"},until:{type:"string",short:"u",value:"time",description:"repeating until a time"},for:{type:"string",value:"duration",description:"repeating for this long, e.g. 24h"},times:{type:"string",value:"N",description:"repeating this many times"},can:{type:"string",multiple:!0,value:"pattern=perms",description:"what they may do, repeated: perms, all, or none"},"lock-me-out":{type:"boolean",description:"go ahead with a change you couldn't take back"},user:{type:"string",multiple:!0,value:"email",description:"a person on the team"},project:{type:"string",multiple:!0,short:"p",value:"name|id",description:"a project's deployments"},github:{type:"string",multiple:!0,value:"owner/repo",description:"GitHub Actions' runs in a repository"},oidc:{type:"string",multiple:!0,value:"issuer",description:"an issuer's tokens, by its URL"},"all-users":{type:"boolean",description:"every person on the team"},"all-projects":{type:"boolean",description:"every project's deployments on the team"},app:{type:"string",multiple:!0,value:"app",description:"an app installed on the team"},"all-apps":{type:"boolean",description:"every app installed on the team"},everyone:{type:"boolean",description:"everyone let in some other way, and no one new"},environment:{type:"string",multiple:!0,short:"e",value:"environment",description:"where its --project runs"},workflow:{type:"string",multiple:!0,value:"file",description:"its --github's workflow, e.g. ci.yml"},"git-branch":{type:"string",multiple:!0,value:"branch",description:"its --github's branch"},event:{type:"string",multiple:!0,value:"event",description:"its --github's event, e.g. push"},claim:{type:"string",multiple:!0,value:"k=v",description:"a claim its --oidc's tokens carry"},"add-user":{type:"string",multiple:!0,value:"email",description:"add a person"},"add-project":{type:"string",multiple:!0,value:"name|id",description:"add a project's deployments"},"add-github":{type:"string",multiple:!0,value:"owner/repo",description:"add a repository's runs"},"add-oidc":{type:"string",multiple:!0,value:"issuer",description:"add an issuer's tokens"},"add-all-users":{type:"boolean",description:"add every person on the team"},"add-all-projects":{type:"boolean",description:"add every project on the team"},"add-app":{type:"string",multiple:!0,value:"app",description:"add an app"},"add-all-apps":{type:"boolean",description:"add every app on the team"},"add-everyone":{type:"boolean",description:"add everyone something else lets in"},"remove-user":{type:"string",multiple:!0,value:"email",description:"remove a person"},"remove-project":{type:"string",multiple:!0,value:"name|id",description:"remove a project, whatever its environments"},"remove-github":{type:"string",multiple:!0,value:"owner/repo",description:"remove a repository's runs"},"remove-oidc":{type:"string",multiple:!0,value:"issuer",description:"remove an issuer's tokens"},"remove-all-users":{type:"boolean",description:"remove every person on the team"},"remove-all-projects":{type:"boolean",description:"remove every project on the team"},"remove-app":{type:"string",multiple:!0,value:"app",description:"remove an app"},"remove-all-apps":{type:"boolean",description:"remove every app on the team"},"remove-everyone":{type:"boolean",description:"remove everyone"},private:{type:"boolean",description:"closed to everyone but you, in the same write"},schema:{type:"string",value:"schema",description:"the text is JSON for this schema, such as sandbox@1"},description:{type:"string",value:"text",description:"what it holds, in a sentence"},port:{type:"string",value:"N",description:"the port to listen on"},dir:{type:"string",value:"dir",description:"where the board keeps its log (default: .board/)"},"no-inspect":{type:"boolean",description:"don't start the inspector"},state:{type:"string",value:"state",description:"in a state: waiting, ready, claimed, blocked, completed, failed, canceled, open, or all (default: open)"},needs:{type:"string",multiple:!0,value:"id",description:"wait for a task to complete first"},ready:{type:"boolean",description:"the oldest ready task in a channel, or under a prefix (work/)"},from:{type:"string",multiple:!0,value:"id",description:"with --ready: take this owner's tasks too, by their ID"},wait:{type:"string",value:"duration",description:"with --ready: how long to wait for one, e.g. 10m"},lease:{type:"string",value:"duration",description:"how long to hold it: 30s to 1h (default: 15m, or what the board gives)"},result:{type:"string",value:"text",description:"what it came to, when the command exits 0"},kind:{type:"string",value:"kind",description:"what the hold is for: needs_input, awaiting_approval"},pool:{type:"boolean",description:"back to anyone who may claim it"},none:{type:"boolean",description:"wait for nothing"},agent:{type:"string",value:"name",description:"the agent whose turn ended",hidden:!0}},option=(name,description,value)=>({name,...options[name],...description?{description}:{},...value?{value}:{}}),filters=["re","by","source","label","text","mentions","after"].map(name=>option(name)),globalOptions=["url","scope","name","ensure","team","as","avatar","json","help","version"].map(name=>option(name)),id=(description="a message ID, as read shows it (#812)")=>({name:"id",required:!0,description}),text=(description="what it says: - reads it from stdin, and it may be left out when you --attach or --file")=>({name:"text",required:!1,description}),task=(description="a task's ID, as tasks shows it (#812)")=>({name:"id",required:!0,description}),claimNow={name:"claim",type:"boolean",description:"claim it in the same write"},AFTER="a reply only while this is the thread's newest message",groups=["you","the board","messages","agents","live"],commands=[{group:"you",name:"whoami",description:"who am I, on which board, with which credential, and what I can do",arguments:[],options:[],examples:[{name:"see who you are on the board",value:"whoami"}]},{group:"the board",name:"grants",description:"who may do what where, grant by grant",arguments:[],options:[],runsWithoutSubcommand:!0,examples:[{name:"list the grants",value:"grants"}],subcommands:[{name:"list",default:!0,description:"the board's grants",arguments:[],options:[],examples:[{name:"list the grants",value:"grants list"}]},{name:"create",description:"let principals do what --can says, where it says",arguments:[],options:[...["user","project","github","oidc","app","all-users","all-projects","all-apps","everyone"].map(name=>option(name)),option("environment","where its --project runs (default: production)"),...["workflow","git-branch","event","claim"].map(name=>option(name)),option("can","what they may do, repeated: perms, all, or none","pattern=perms"),option("file","several grants, made in one write, from a JSON file: - reads stdin"),option("lock-me-out")],examples:[{name:"let two people into security/",value:"grants create --user alice@acme.com --user bob@acme.com --can 'security/=all'"},{name:"then close it to everyone else",value:"grants create --everyone --can 'security/=none'"},{name:"several grants in one write, from a file",value:"grants create --file grants.json"},{name:"a project's production and previews",value:"grants create --project sec --environment production,preview --can 'security/=read,post'"},{name:"two repositories' workflows",value:"grants create --github acme/web --workflow ci.yml --git-branch main --github acme/api --workflow deploy.yml --can 'ci/=post'"},{name:"another issuer's tokens",value:"grants create --oidc https://gitlab.com --claim project_id=42 --can 'ci/=post'"}]},{name:"update",description:"add or remove principals, or replace its --can",arguments:[{name:"grant",required:!0,description:"its ID, as grants shows it (g3)"}],options:[...["add-user","add-project","add-github","add-oidc","add-app","add-all-users","add-all-projects","add-all-apps","add-everyone","remove-user","remove-project","remove-github","remove-oidc","remove-app","remove-all-users","remove-all-projects","remove-all-apps","remove-everyone","environment","workflow","git-branch","event","claim"].map(name=>option(name)),option("can","replaces what it lets them do","pattern=perms"),option("lock-me-out")],examples:[{name:"let another person in",value:"grants update g4 --add-user carol@acme.com"},{name:"drop a project, and narrow it",value:"grants update g5 --remove-project sec --can 'security/=read'"}]},{name:"explain",description:"which grant decides a channel, for you or anyone",arguments:[{name:"channel",required:!0,description:"a channel, such as security/incidents"}],options:[...["user","project","github","oidc","app","environment","workflow","git-branch","event","claim"].map(name=>option(name))],examples:[{name:"what you may do in a channel",value:"grants explain security/incidents"},{name:"what someone else may",value:"grants explain --user bob@acme.com security/incidents"}]},{name:"revoke",description:"stop letting them in",arguments:[{name:"grant",required:!0,description:"its ID, as grants shows it (g3)"}],options:[option("lock-me-out")],examples:[{name:"revoke a grant",value:"grants revoke g3"}]}]},{group:"the board",name:"channels",description:"channels, grouped by path prefix: a first post makes one, and so does create",arguments:[],options:[],runsWithoutSubcommand:!0,examples:[{name:"list the channels",value:"channels"}],subcommands:[{name:"list",default:!0,description:"channels, grouped by path prefix",arguments:[],options:[],examples:[{name:"list the channels",value:"channels list"}]},{name:"create",description:"a channel, before anything posts to it (one that exists stays as it is)",arguments:[{name:"channel",required:!0,description:"its path, such as dev/alerts"}],options:[option("private")],examples:[{name:"make a channel for alerts",value:"channels create dev/alerts"},{name:"one only you can see, until you grant others",value:"channels create security --private"}]}]},{group:"the board",name:"schemas",description:"schemas for structured data: versions that never change",arguments:[],options:[],runsWithoutSubcommand:!0,examples:[{name:"list the schemas",value:"schemas"}],subcommands:[{name:"list",default:!0,description:"the built-in schemas, then the board's own",arguments:[],options:[],examples:[{name:"list the schemas",value:"schemas list"}]},{name:"inspect",description:"one version, with its JSON Schema",arguments:[{name:"schema",required:!0,description:"its ID, as schemas shows it (sandbox@1)"}],options:[],examples:[{name:"see what a sandbox event holds",value:"schemas inspect sandbox@1"}]},{name:"create",description:"register a version, for good: the same definition again changes nothing",arguments:[{name:"schema",required:!0,description:"its name and version, such as sandbox@1"}],options:[option("file","its JSON Schema, from a file: - reads stdin"),option("data","its JSON Schema, written inline"),option("description")],examples:[{name:"register a version from a file",value:"schemas create sandbox@1 --file sandbox.schema.json --description 'What a sandbox did.'"},{name:"or inline",value:`schemas create ping@1 --data '{"type":"object","required":["at"],"properties":{"at":{"type":"string","format":"date-time"}}}'`}]}]},{group:"the board",name:"actors",description:"actors and their handles",arguments:[],options:[],examples:[{name:"list who has written here",value:"actors"}]},{group:"messages",name:"read",description:"the latest threads, one each (root, replies, latest reply), or one thread, every message",arguments:[{name:"channel|id|link",required:!1,description:"a channel (every channel without one), a message's ID, or a Slack or GitHub link the board synced"}],options:[option("limit","threads to list (default: 50, at most 500)")],filters:!0,examples:[{name:"list a channel's latest threads",value:"read dev"},{name:"read one thread, every message",value:"read 812"},{name:"list the open bugs",value:"read dev --label kind=bug --label state=open"},{name:"only what's new since the cursor an earlier read printed",value:"read dev --after 1042"},{name:"search every channel for a phrase",value:'read --text "times out"'}]},{group:"messages",name:"post",brief:"[--label k=v]... [--attach file]...",description:"a new thread in a channel, or with an ID, a reply in its thread",arguments:[{name:"channel|id",required:!0,description:"a channel, or a message ID to reply in its thread"},text()],options:[option("label","label it","k=v"),option("file","the text, from a file: - reads stdin"),option("schema"),option("attach"),option("sync"),option("no-sync"),option("idempotency-key"),option("after",AFTER)],examples:[{name:"start a thread",value:'post dev "deploys are green again"'},{name:"start a labeled thread",value:'post dev "checkout times out" --label kind=bug'},{name:"post data that matches a schema",value:`post deploys --schema sandbox@1 '{"id":"sbx-123","action":"started"}'`}]},{group:"messages",name:"reply",description:"a reply in a thread",arguments:[id("the ID of a message in the thread"),text()],options:[option("label","label it","k=v"),option("file","the text, from a file: - reads stdin"),option("schema"),option("attach"),option("idempotency-key"),option("no-sync"),option("after",AFTER)],examples:[{name:"reply in a thread",value:'reply 812 "on it"'},{name:"reply with a label",value:'reply 812 "fixed in a1b2c3" --label step=fix'},{name:"reply only if #815 is still the thread's newest",value:'reply 812 "on it" --after 815'}]},{group:"messages",name:"schedule",brief:"(--in 5m | --at time | --every 30m)",description:"post later, as you: once (--in or --at), or repeating (--every) until a stop or until canceled",arguments:[{name:"channel|id",required:!0,description:"a channel, or a message ID to reply in its thread"},text()],options:[option("in"),option("at"),option("every"),option("until"),option("for"),option("times"),option("label","label it","k=v"),option("file","the text, from a file: - reads stdin"),option("schema"),option("attach"),option("no-sync")],examples:[{name:"reply in a thread tomorrow",value:'schedule 812 "still broken?" --in 1d'},{name:"post every morning",value:'schedule dev "standup" --at 2026-11-02T09:00:00Z --every 1d'}],runsWithoutSubcommand:!0,subcommands:[{name:"cancel",description:"stop one (yours, or with manage)",arguments:[{name:"schedule",required:!0,description:"its ID, as schedules shows it (s12)"}],options:[],examples:[{name:"cancel a schedule",value:"schedule cancel s12"}]}]},{group:"messages",name:"schedules",brief:"[--by handle] [--all]",description:"pending schedules, a thread's with a message ID, or one by its own ID",arguments:[{name:"id",required:!1,description:"a message in the thread, or a schedule (s12): sent, canceled, or pending"}],options:[option("by","scheduled by a handle"),option("channel","posting in a channel"),option("all","done and canceled ones too")],examples:[{name:"list pending schedules",value:"schedules"}]},{group:"messages",name:"edit",description:"change a message's text",arguments:[id(),{name:"text",required:!1,description:"its new text: - reads it from stdin, and it may be left out when you --file"}],options:[option("file","the text, from a file: - reads stdin"),option("schema"),option("if-revision")],examples:[{name:"fix a typo",value:'edit 812 "deploys are green again"'},{name:"only if no one changed it since you read it",value:'edit 812 "step 3 of 5" --if-revision 820'}]},{group:"messages",name:"delete",aliases:["rm","del"],description:"delete a message, leaving a tombstone",arguments:[id()],options:[option("if-revision")],examples:[{name:"delete a message",value:"delete 812"}]},{group:"messages",name:"react",description:"react to a message",arguments:[id(),{name:"emoji",required:!0,description:"its name or the emoji itself: eyes, \u{1F440}"}],options:[option("remove")],examples:[{name:"react with eyes",value:"react 812 eyes"}]},{group:"messages",name:"label",brief:"[--if-unset k] [--unset k]",description:"set labels on a message, or remove them",arguments:[id(),{name:"k=v",required:!1,multiple:!0,description:"a label to set: a key of up to 64 lowercase letters, numbers, ., _, and -, starting with a letter or number, and a value of up to 256 characters"}],options:[option("unset"),option("if"),option("if-unset")],examples:[{name:"mark a bug fixed",value:"label 812 state=fixed --unset wip"},{name:"claim a thread, unless someone has",value:"label 812 owner=claude --if-unset owner"},{name:"move it on from open only",value:"label 812 state=fixing --if state=open"}]},{group:"messages",name:"typing",description:"show typing in the thread's synced platform threads",arguments:[id(),{name:"status",required:!1,description:'what Slack shows instead of "Typing\u2026"'}],options:[],examples:[{name:"show typing while you work",value:'typing 812 "looking into it"'}]},{group:"messages",name:"sync",description:"where the thread is synced, or with a target, attach it there (backfilling it)",arguments:[id(),{name:"target",required:!1,description:"where to sync it, e.g. slack:#incidents"}],options:[],examples:[{name:"list where a thread is synced",value:"sync 812"},{name:"sync a thread to a Slack channel",value:"sync 812 slack:#incidents"}]},{group:"messages",name:"inbox",description:"raw platform events, for debugging sync",arguments:[{name:"key",required:!0,description:"the sync entry, e.g. slack"},{name:"channel",required:!1,description:"the board channel its events went to"}],options:[option("limit","events to list")],examples:[{name:"list Slack's latest events",value:"inbox slack"}]},{group:"messages",name:"sources",description:"the board's sources: its sync entries (slack, github, \u2026)",arguments:[{name:"key",required:!1,description:"a sync entry, e.g. slack"}],options:[],runsWithoutSubcommand:!0,argumentsBeforeSubcommand:!0,examples:[{name:"list the board's sources",value:"sources"}],subcommands:[{name:"read",description:"read a source's channel, thread, or message link without syncing it (full access only)",arguments:[{name:"target",required:!0,description:"a channel ('#general'), a thread, or a message link"}],options:[option("limit","messages to read"),option("after","where the last read left off: the cursor it printed")],examples:[{name:"read a Slack channel",value:"sources slack read '#general'"},{name:"read a Linear project's issues",value:"sources linear read https://linear.app/acme/project/checkout-a1b2c3"}]},{name:"join",description:"add the app to a public channel so it can be read, where the board opted in (full access only)",arguments:[{name:"channel",required:!0,description:"a channel or its link"}],options:[],examples:[{name:"join a Slack channel",value:"sources slack join '#general'"}]}]},{group:"messages",name:"download",description:"save an attachment (its name, here, by default; - for stdout)",arguments:[{name:"attachment-id",required:!0,description:"the ID at the end of a file line when you read its thread, not the file's name"},{name:"path",required:!1,description:"where to save it, or - for stdout"}],options:[],examples:[{name:"save an attachment",value:"download Yt2mR8vQ1x0pLk3sF7dA9w"}]},{group:"messages",name:"conformance",description:"check that a board you name speaks the protocol (1 if a check fails): it posts, and deletes what it posted",arguments:[],options:[option("channel","the channel to check in (default: conformance)")],examples:[{name:"check the board",value:"conformance"}]},{group:"agents",name:"tasks",description:"open tasks, oldest first: threads agents are to do, each with a state the board keeps",arguments:[{name:"channel",required:!1,description:"a channel, or a path prefix (work/); every channel without one"}],options:[option("state"),option("label","with a label on its root","k[=v|w]"),option("by","whose root a handle wrote"),option("for","assigned to a profile of yours","profile"),option("after","after a cursor an earlier page printed","cursor"),option("limit","tasks to list (default: 50)")],runsWithoutSubcommand:!0,examples:[{name:"list a queue's open tasks",value:"tasks work/"},{name:"list what is ready to fix",value:"tasks work/ --state ready --label step=fix"}],subcommands:[{name:"create",description:"start a thread as a task, or with an ID, make that thread one: you own it. With --file, a plan of them",arguments:[{name:"channel|id",required:!0,description:"a channel, or a thread's ID to make a task of it as it is"},{name:"text",required:!1,description:"what to do, for a new thread: - reads it from stdin, and --file takes its place"}],options:[option("label","label it, to route it","k=v"),option("needs"),option("for","only this profile of yours claims it","profile"),claimNow,option("lease","with --claim: how long to hold it"),option("file","a plan, from a JSON file (- reads stdin): an array of tasks, each { key?, text, labels?, needs?, for?, noSync?, attachments? }, all made, in as many writes as it takes"),option("no-sync"),option("idempotency-key","sending the same one again makes it once")],examples:[{name:"hand a fix to whoever takes fixes",value:'tasks create work "fix CVE-123 in acme/web" --label step=fix'},{name:"a review that waits for it",value:'tasks create work "review the fix for CVE-123" --label step=review --needs 812'},{name:"make a task of a thread that is there",value:"tasks create 812"},{name:"a plan of tasks that wait for each other",value:"tasks create work --file plan.json --idempotency-key migration-7"}]},{name:"claim",description:"hold a task for a lease, by its ID, or with --ready the oldest ready one in a channel",arguments:[{name:"id|channel",required:!0,description:"a task's ID, or with --ready a channel or a path prefix (work/)"}],options:[option("ready"),option("label","with --ready: one whose root has this label","k=v"),option("from"),option("wait"),option("lease")],examples:[{name:"claim a task",value:"tasks claim 812"},{name:"claim the next fix, waiting for one",value:"tasks claim --ready work/ --label step=fix --wait 10m"}]},{name:"run",description:"claim a task and run a command on it: renew while it runs, complete on exit 0, fail otherwise",arguments:[{name:"id|channel",required:!0,description:"a task's ID, or with --ready a channel or a path prefix"},{name:"cmd",required:!0,multiple:!0,description:"the command, after --: it gets BOARD_TASK, the task's ID"}],options:[option("result"),option("ready"),option("label","with --ready: one whose root has this label","k=v"),option("from"),option("wait"),option("lease")],examples:[{name:"run the tests as a task",value:'tasks run 812 --result "tests pass" -- make test'},{name:"work the next fix",value:"tasks run --ready work/ --label step=fix -- ./fix.sh"}]},{name:"renew",description:"extend the lease of a task you hold, from now",arguments:[task()],options:[option("lease")],examples:[{name:"hold it for another 30 minutes",value:"tasks renew 812 --lease 30m"}]},{name:"release",description:"give a task you hold back: it is ready again",arguments:[task()],options:[],examples:[{name:"give a task back",value:"tasks release 812"}]},{name:"complete",description:"finish a task you hold: what waits only for it is ready",arguments:[task(),{name:"result",required:!1,description:"what it came to, in a line"}],options:[],examples:[{name:"complete a task",value:'tasks complete 812 "fixed in a1b2c3, tests pass"'}]},{name:"fail",description:"give up on a task you hold: what waits for it keeps waiting, until it's reopened",arguments:[task(),{name:"reason",required:!0,description:"why, in a line"}],options:[],examples:[{name:"fail a task",value:'tasks fail 812 "the tests need a database"'}]},{name:"block",description:"hold a task for a person: with your claim, which it ends, or as its owner",arguments:[task(),{name:"reason",required:!0,description:"what you need from them"}],options:[option("kind")],examples:[{name:"ask for approval",value:'tasks block 813 "approve the prod deploy?" --kind awaiting_approval'}]},{name:"unblock",description:"lift a hold, as its owner: ready again, or waiting while a task it needs has not completed",arguments:[task()],options:[],examples:[{name:"lift a hold",value:"tasks unblock 813"}]},{name:"reopen",description:"make a failed task ready again, as its owner",arguments:[task()],options:[],examples:[{name:"retry a failed task",value:"tasks reopen 812"}]},{name:"assign",description:"keep a task for one of its owner's profiles, or with --pool, for anyone who may claim it",arguments:[task(),{name:"profile",required:!1,description:"a profile of the task's owner, such as fixer"}],options:[option("pool")],examples:[{name:"keep it for the fixer",value:"tasks assign 812 fixer"},{name:"back to the pool",value:"tasks assign 812 --pool"}]},{name:"needs",description:"set what a task waits for, as its owner: the tasks named, in place of what it waited for",arguments:[task(),{name:"needs",required:!1,multiple:!0,description:"the tasks it waits for now, by ID"}],options:[option("none")],examples:[{name:"wait for two tasks",value:"tasks needs 814 812 813"},{name:"wait for nothing",value:"tasks needs 814 --none"}]},{name:"cancel",description:"cancel a task that has not completed, as its owner: any claim ends",arguments:[task(),{name:"reason",required:!0,description:"why, in a line"}],options:[],examples:[{name:"cancel a task",value:'tasks cancel 812 "superseded by #820"'}]}]},{group:"agents",name:"hooks",description:"the turn-end hooks an earlier board installed",arguments:[],options:[],examples:[],subcommands:[{name:"uninstall",description:"remove the turn-end hooks an earlier board installed, from every agent or the ones named",arguments:[{name:"agent",required:!1,multiple:!0,description:"claude, codex, cursor, or pi"}],options:[],examples:[{name:"remove every hook",value:"hooks uninstall"}]}]},{group:"agents",name:"hook",description:"what an earlier turn-end hook runs: it does nothing now",arguments:[{name:"event",required:!1,multiple:!0}],options:[option("agent")],examples:[],hidden:!0},{group:"live",name:"tail",description:"what happens, live, until Ctrl-C",arguments:[{name:"channel",required:!1,description:"a channel, or a path prefix (dev/)"}],options:[option("all","delivery receipts too")],filters:!0,examples:[{name:"follow the bugs",value:"tail dev --label kind=bug"}]},{group:"live",name:"wait",brief:"[--after id] [--timeout 10m]",description:"block for the next match and print it",arguments:[{name:"channel|id",required:!1,description:"a channel, a path prefix (dev/), or a message's ID: what comes after it in its thread"}],options:[option("timeout")],filters:!0,examples:[{name:'wait for a mention: when none comes in time it says "Nothing matched" and exits 1',value:"wait dev --mentions --timeout 10m"},{name:"wait for a reply in a thread, from the last message you read so none is missed",value:"wait --re 812 --after 815 --timeout 10m"}]},{group:"live",name:"help",description:"this help, or a command's",arguments:[{name:"command",required:!1,multiple:!0}],options:[],examples:[],hidden:!0}];function usage(path){let words=[];return path.forEach((command,at)=>{let last=at===path.length-1;if(words.push(command.name),last||command.argumentsBeforeSubcommand)for(let argument of command.arguments){let required=argument.required||!last;words.push(`${required?`<${argument.name}>`:`[${argument.name}]`}${argument.multiple?"...":""}`)}}),path.at(-1)?.filters&&words.push("[filters]"),words.join(" ")}export{options,filters,globalOptions,groups,commands,usage};
@@ -1,7 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module';
2
- import { fileURLToPath as __fileURLToPath } from 'node:url';
3
- import { dirname as __dirname_ } from 'node:path';
4
- const require = __createRequire(import.meta.url);
5
- const __filename = __fileURLToPath(import.meta.url);
6
- const __dirname = __dirname_(__filename);
7
- import{AGENT_REASON,outputAgentError}from"./chunk-PNWRO3XW.js";import{findProjectsFromPath,getConfigFilePath,getLinkFromDir,getRepoLink,getUser,getVercelDirectory,inspectTokenRequest,isOwnerLookupUnavailableError,processInspectTokenResponse}from"./chunk-XL2PHD4X.js";import{require_ms}from"./chunk-MXTC4ZAQ.js";import{getTeamByIdOrSlug}from"./chunk-2VBFQZ72.js";import{require_cli_config}from"./chunk-4SAVH3H7.js";import{InvalidToken,TeamDeleted}from"./chunk-GOI2VVI7.js";import{output_manager_default}from"./chunk-AP6DZGTK.js";import{require_build_utils}from"./chunk-5MDNVAE6.js";import{__toESM}from"./chunk-BZENIQ7N.js";var import_build_utils=__toESM(require_build_utils(),1);var VERCEL_API_ORIGIN="https://api.vercel.com";async function introspectToken(client){let token=client.authConfig.token;if(!token)throw new Error("No token to introspect");if(new URL(client.apiUrl).origin!==VERCEL_API_ORIGIN)throw new Error("Token introspection is unavailable for custom API origins");let[error,introspection]=await processInspectTokenResponse(await inspectTokenRequest(token));if(error)throw error;return introspection}function isAppPrincipalEnabled(){return!!process.env.APP_PRINCIPAL_ENABLED}function resolveAppFromToken(token){return!token.active||!token.client_id?null:{id:token.client_id,name:token.client_name}}async function getAppTokenTeamId(client){try{await getUser(client);return}catch{let token=await introspectToken(client).catch(()=>null);return token&&resolveAppFromToken(token)?token.team?.id:void 0}}function assertOrgIdMatchesAppTeam(client,appTeamId){let envOrgId=(0,import_build_utils.getPlatformEnv)("ORG_ID");if(!envOrgId||envOrgId===appTeamId)return;let message=`This token only works with team ${appTeamId}, but VERCEL_ORG_ID is set to ${envOrgId}.`;throw outputAgentError(client,{status:"error",reason:AGENT_REASON.SCOPE_NOT_ACCESSIBLE,message}),new Error(message)}async function resolveAppTokenScope(client,scope){let token=await introspectToken(client).catch(()=>null),app=token?resolveAppFromToken(token):null,team=token?.team;return!app||!team||team.id!==scope&&team.slug!==scope?!1:(client.config.currentTeam=team.id,!0)}async function isActiveAppToken(client){let token=await introspectToken(client).catch(()=>null);return!!(token&&resolveAppFromToken(token))}var import_cli_config=__toESM(require_cli_config(),1),import_ms=__toESM(require_ms(),1);var TEAM_SLUG_TTL_MS=(0,import_ms.default)("1d");function getCachedTeamSlug(config,teamId,now=Date.now()){let saved=config.cachedTeamSlugs?.[teamId];if(!isSavedTeamSlug(saved))return;let age=now-saved.savedAt;return age>=0&&age<TEAM_SLUG_TTL_MS?saved.slug:void 0}function setCachedTeamSlug(client,teamId,slug){if(getCachedTeamSlug(client.config,teamId)===slug)return;let saved={slug,savedAt:Date.now()};updateCachedTeamSlugs(client,slugs=>({...slugs,[teamId]:saved}))}function forgetCachedTeamSlug(client,teamId){let slugs=client.config.cachedTeamSlugs;!slugs||!(teamId in slugs)||updateCachedTeamSlugs(client,saved=>{let rest={...saved};return delete rest[teamId],rest})}function isSavedTeamSlug(value){return typeof value=="object"&&value!==null&&typeof value.slug=="string"&&typeof value.savedAt=="number"}function updateCachedTeamSlugs(client,update){try{let configPath=getConfigFilePath(),savedConfig=(0,import_cli_config.readGlobalConfigFile)(configPath),cachedTeamSlugs=update(savedConfig.cachedTeamSlugs??{}),config={...savedConfig,cachedTeamSlugs};(0,import_cli_config.writeGlobalConfigFile)(configPath,config),client.config.cachedTeamSlugs=cachedTeamSlugs}catch{output_manager_default.debug("Failed to persist cached team slugs.")}}var import_build_utils2=__toESM(require_build_utils(),1);import{relative}from"path";async function getScope(client,opts={}){let{user,app,token}=await getPrincipal(client),defaultTeamId=user?.version==="northstar"&&!client.ignoresSavedTeam?user.defaultTeamId:void 0,appTeamId=!user&&app?token?.team?.id:void 0;if(!user&&app&&opts.getTeam===!1)throw new Error("App principal scope resolution requires a team lookup.");!user&&app&&(client.ignoresSavedTeam&&appTeamId&&assertOrgIdMatchesAppTeam(client,appTeamId),client.config.currentTeam=appTeamId),!client.config.currentTeam&&defaultTeamId&&(client.config.currentTeam=defaultTeamId),client.isTeamUnchosen()&&await client.chooseTeam({ask:opts.chooseTeam!==!1});let teamId=client.config.currentTeam||defaultTeamId,team=teamId&&opts.getTeam!==!1?await getTeam(client,teamId):null,contextName=team?.slug||user?.username||user?.email;if(!contextName)throw new Error("Unable to determine context name");return opts.resolveLocalScope?resolveLocalScopeContext(client,{user,app,team}):{contextName,team,user,app}}async function getContextName(client,opts={}){let teamId=client.config.currentTeam,cachedSlug=teamId&&!client.authConfig.tokenSource?getCachedTeamSlug(client.config,teamId):void 0;if(cachedSlug&&!(opts.resolveLocalScope&&await hasLocalScope(client)))return output_manager_default.debug(`Using saved name "${cachedSlug}" for team ${teamId}`),cachedSlug;let scope;try{scope=opts.resolveLocalScope?await getScope(client,{resolveLocalScope:!0}):await getScope(client)}catch(err){let currentTeam=client.config.currentTeam;if(opts.allowOwnerLookupFallback&&currentTeam&&isOwnerLookupUnavailableError(err))return output_manager_default.debug(`Can't read team ${currentTeam}; using its ID as the name`),currentTeam;throw err}let{contextName,team}=scope;return team&&!client.authConfig.tokenSource&&setCachedTeamSlug(client,team.id,team.slug),contextName}async function hasLocalScope(client){if(detectExplicitScope(client))return!1;let{localOrgId,isCrossTeamRepo}=await findLocalLink(client);return!!localOrgId||isCrossTeamRepo}async function getPrincipal(client){if(!isAppPrincipalEnabled())return{user:await getUser(client),app:null,token:null};let[userResult,tokenResult]=await Promise.allSettled([getUser(client),introspectToken(client)]),token=tokenResult.status==="fulfilled"?tokenResult.value:null,app=token?resolveAppFromToken(token):null;if(userResult.status==="rejected"&&!(app&&userResult.reason instanceof InvalidToken))throw userResult.reason;return{user:userResult.status==="fulfilled"?userResult.value:null,app,token}}async function resolveLocalScopeContext(client,{user,app,team}){let explicitScopeProvided=detectExplicitScope(client)||client.ignoresSavedTeam&&!!(0,import_build_utils2.getPlatformEnv)("ORG_ID"),globalTeamId=client.config.currentTeam,{localOrgId,linkedRepo,isCrossTeamRepo}=await findLocalLink(client),isAppPrincipal=!user&&!!app,effectiveLocalOrgId=isAppPrincipal?void 0:localOrgId,scopeMismatch=!!(effectiveLocalOrgId&&globalTeamId&&globalTeamId!==effectiveLocalOrgId);!isAppPrincipal&&!explicitScopeProvided&&!effectiveLocalOrgId&&isCrossTeamRepo&&output_manager_default.warn("This repository has projects across multiple teams. Use `--scope` to specify which team, or `cd` into a project directory.");let resolvedTeam=!explicitScopeProvided&&effectiveLocalOrgId?await applyLocalOrg(client,effectiveLocalOrgId):team,{org,contextName}=resolveOrg(resolvedTeam,user);return{org,contextName,user,team:resolvedTeam,app,globalTeam:team,linkedRepo,isCrossTeamRepo,localOrgId:effectiveLocalOrgId,scopeMismatch,explicitScopeProvided}}async function applyLocalOrg(client,localOrgId){return client.config.currentTeam=localOrgId.startsWith("team_")?localOrgId:void 0,client.config.currentTeam?await getTeamByIdOrSlug(client,client.config.currentTeam):null}async function getTeam(client,teamId){let team=await getTeamByIdOrSlug(client,teamId);if(!team)throw new TeamDeleted;return team}function resolveOrg(team,user){if(team)return{org:{type:"team",id:team.id,slug:team.slug},contextName:team.slug};if(user)return{org:{type:"user",id:user.id,slug:user.username},contextName:user.username||user.email};throw new Error("Unable to determine scope: no team or personal account is available for this token. Use `--scope` to specify a team.")}async function getLocalOrgId(client){return(await findLocalLink(client)).localOrgId}async function findLocalLink(client){let[projectLink,repoLink]=await Promise.all([findProjectLink(client),findRepoLink(client)]);return{localOrgId:findLocalOrgId(client.cwd,projectLink,repoLink),linkedRepo:repoLink?.repoConfig?{repoConfig:repoLink.repoConfig,rootPath:repoLink.rootPath}:null,isCrossTeamRepo:detectCrossTeamRepo(repoLink?.repoConfig)}}async function findProjectLink(client){try{return await getLinkFromDir(getVercelDirectory(client.cwd))}catch{return null}}async function findRepoLink(client){try{return await getRepoLink(client,client.cwd)}catch{return null}}function findLocalOrgId(cwd,projectLink,repoLink){if(projectLink)return projectLink.orgId;if(repoLink?.repoConfig)return findRepoOrgId(repoLink.repoConfig,relative(repoLink.rootPath,cwd))}function findRepoOrgId(repoConfig,pathFromRepoRoot){let matchedProjects=findProjectsFromPath(repoConfig.projects,pathFromRepoRoot),projects=matchedProjects.length===0&&pathFromRepoRoot===""?repoConfig.projects:matchedProjects,orgIds=new Set(projects.map(p=>p.orgId??repoConfig.orgId??""));if(orgIds.size!==1)return;let[orgId]=orgIds;return orgId||void 0}function scopeFlagPassed(argv){for(let arg of argv){if(arg==="--")break;if(arg==="--scope"||arg==="--team"||arg.startsWith("--scope=")||arg.startsWith("--team=")||arg==="-S"||arg==="-T")return!0}return!1}function detectExplicitScope(client){return scopeFlagPassed(client.argv)||!!client.localConfig?.scope}function detectCrossTeamRepo(repoConfig){if(!repoConfig?.projects||repoConfig.projects.length<2)return!1;let orgIds=new Set;for(let project of repoConfig.projects){let orgId=project.orgId??repoConfig.orgId;orgId&&orgIds.add(orgId)}return orgIds.size>1}export{introspectToken,isAppPrincipalEnabled,resolveAppFromToken,getAppTokenTeamId,assertOrgIdMatchesAppTeam,resolveAppTokenScope,isActiveAppToken,forgetCachedTeamSlug,getScope,getContextName,resolveOrg,getLocalOrgId,scopeFlagPassed,detectExplicitScope};
@@ -1,13 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module';
2
- import { fileURLToPath as __fileURLToPath } from 'node:url';
3
- import { dirname as __dirname_ } from 'node:path';
4
- const require = __createRequire(import.meta.url);
5
- const __filename = __fileURLToPath(import.meta.url);
6
- const __dirname = __dirname_(__filename);
7
- import{getOrCreateDeploymentProtectionToken}from"./chunk-TVELM5HH.js";import{getProtectionForProductionDomain,readEnabledProtection}from"./chunk-B7GCRM5I.js";import{ensureLink}from"./chunk-O4WJDJIL.js";import{toHost}from"./chunk-NBTFAXL4.js";import{getTeams}from"./chunk-Y2FVJ7YO.js";import{curlCommand}from"./chunk-6U7TRWBO.js";import{printError}from"./chunk-CY5KJ42N.js";import{help}from"./chunk-7KCRYDGK.js";import{detectExplicitScope,getScope,introspectToken,isAppPrincipalEnabled,resolveAppFromToken}from"./chunk-YJP25FL6.js";import{TelemetryClient}from"./chunk-KDCODXVL.js";import{getLinkedProject,getUser}from"./chunk-XL2PHD4X.js";import{getGlobalPathConfig}from"./chunk-7HLAWGY2.js";import{parseArguments}from"./chunk-LYL26S3N.js";import{InvalidToken,isAPIError}from"./chunk-GOI2VVI7.js";import{cmd,getCommandName}from"./chunk-B4KA3ZH2.js";import{output_manager_default}from"./chunk-AP6DZGTK.js";import{require_dist}from"./chunk-MCYG7CCE.js";import{getFlagsSpecification}from"./chunk-CFJBDBYH.js";import{require_source}from"./chunk-NB2WLB3J.js";import{__toESM}from"./chunk-BZENIQ7N.js";import{spawn as spawn2}from"child_process";var SECRET_HEADER=/^((?:x-vercel-protection-bypass|cookie):\s*).+$/i,redactSecretHeader=arg=>arg.replace(SECRET_HEADER,"$1[REDACTED]"),requoteArgs=arg=>arg.includes(" ")?arg.includes('"')?`'${arg}'`:`"${arg}"`:arg;var CurlTelemetryClient=class extends TelemetryClient{trackCliArgumentPath(path){if(path){let value=path.startsWith("/")?"slash":"no-slash";this.trackCliArgument({arg:"path",value})}}trackCliOptionDeployment(deploymentId){if(deploymentId){let value=deploymentId.startsWith("http://")||deploymentId.startsWith("https://")?"url":deploymentId.startsWith("dpl_")?"dpl_":"no-prefix";this.trackCliOption({option:"deployment",value})}}trackCliOptionProtectionBypass(secret){secret&&this.trackCliOption({option:"protection-bypass",value:this.redactedValue})}trackCliFlagYes(yes){yes&&this.trackCliFlag("yes")}trackCliFlagTrace(trace2){trace2&&this.trackCliFlag("trace")}trackCliFlagJson(json){json&&this.trackCliFlag("json")}trackCliFlagYesOnProduction(value){value&&this.trackCliFlag("yes-on-production")}};var import_chalk=__toESM(require_source(),1),import_error_utils=__toESM(require_dist(),1);async function getDeploymentAccounts(client){if(detectExplicitScope(client))return client.config.currentTeam?[client.config.currentTeam]:[];if(isAppPrincipalEnabled())try{await getUser(client)}catch(err){if(!(err instanceof InvalidToken))throw err;let token=await introspectToken(client).catch(()=>null);if(!token||!resolveAppFromToken(token))throw err;return token.team?[token.team.id]:[]}let currentTeam=client.config.currentTeam;try{return(await getTeams(client)).filter(team=>!team.limited).map(team=>team.id).sort((a,b)=>+(b===currentTeam)-+(a===currentTeam))}catch(err){if(err instanceof InvalidToken&&currentTeam)return[currentTeam];throw err}}async function resolveDeployment(client,selector,accountId){let hostOrId=selector.includes(".")?toHost(selector):selector,endpoint=`/v13/deployments/${encodeURIComponent(hostOrId)}`,lookup=async accountId2=>{try{let deployment2=await client.fetch(endpoint,{useCurrentTeam:!1,...accountId2?{accountId:accountId2}:{},bailOn429:!0});return deployment2?{...deployment2,ownerId:deployment2.ownerId??deployment2.team?.id}:null}catch(err){if(!isAPIError(err)||err.status!==403&&err.status!==404)throw err;return output_manager_default.debug(`Deployment lookup failed for ${hostOrId}: ${err}`),null}};if(accountId||detectExplicitScope(client))return lookup(accountId??client.config.currentTeam);let deployment=await lookup();if(deployment?.projectId&&deployment.ownerId)return deployment;let accounts;try{accounts=await getDeploymentAccounts(client)}catch(err){if(deployment?.url)return deployment;throw err}for(let account of accounts){let scoped=await lookup(account);if(scoped?.projectId&&scoped.ownerId)return scoped;deployment??=scoped}return deployment}async function getDeploymentUrlById(client,deploymentIdOrUrl,accountId){try{if(deploymentIdOrUrl.startsWith("http://")||deploymentIdOrUrl.startsWith("https://"))try{return new URL(deploymentIdOrUrl).origin}catch{return output_manager_default.debug(`Invalid deployment URL provided: ${deploymentIdOrUrl}`),null}if(deploymentIdOrUrl.includes("vercel.app"))return`https://${deploymentIdOrUrl}`;let fullDeploymentId=deploymentIdOrUrl;fullDeploymentId.startsWith("dpl_")||(fullDeploymentId=`dpl_${deploymentIdOrUrl}`);let deployment=await resolveDeployment(client,fullDeploymentId,accountId);return!deployment||!deployment.url?null:`https://${deployment.url}`}catch(error){return output_manager_default.debug(`Failed to fetch deployment by ID: ${error}`),null}}function looksLikeHostname(path){let firstSegment=path.split("/")[0];return firstSegment.includes(".")&&!firstSegment.startsWith(".")}function orgFromOwner(id,slug=id){return{type:id.startsWith("team_")?"team":"user",id,slug}}var VC_STRING_FLAGS=new Set(["--deployment","--protection-bypass"]),VC_IGNORED_STRING_FLAGS=new Set(["--scope","--team"]),VC_IGNORED_BOOLEAN_FLAGS=new Set(["--debug"]),VC_BOOLEAN_FLAGS=new Set(["--yes","--help","--trace","--json"]);function flagName(arg){let eqIdx=arg.indexOf("=");return eqIdx===-1?arg:arg.slice(0,eqIdx)}function flagValue(args,index){let arg=args[index],eqIdx=arg.indexOf("=");if(eqIdx!==-1)return arg.slice(eqIdx+1);let next=args[index+1];return next&&!next.startsWith("-")?next:void 0}function getCurlLikeArgs(rawArgs,commandName){if(rawArgs[0]===commandName)return rawArgs.slice(1);let commandIndex=0;for(;commandIndex<rawArgs.length;){let arg=rawArgs[commandIndex];if(VC_IGNORED_BOOLEAN_FLAGS.has(flagName(arg))){commandIndex++;continue}if(!VC_IGNORED_STRING_FLAGS.has(flagName(arg)))break;commandIndex++,!arg.includes("=")&&commandIndex<rawArgs.length&&commandIndex++}return rawArgs[commandIndex]===commandName?rawArgs.slice(commandIndex+1):[...rawArgs]}function parseCurlLikeArgs(rawArgs,commandName){let result={target:void 0,deployment:void 0,protectionBypass:void 0,yes:!1,help:!1,trace:!1,json:!1,toolFlags:[]},args=getCurlLikeArgs(rawArgs,commandName),separatorIndex=args.indexOf("--"),beforeSeparator=separatorIndex===-1?args:args.slice(0,separatorIndex),afterSeparator=separatorIndex===-1?[]:args.slice(separatorIndex+1);for(let i=0;i<beforeSeparator.length;i++){let arg=beforeSeparator[i],name=flagName(arg);if(VC_STRING_FLAGS.has(name)){let value=flagValue(beforeSeparator,i);!arg.includes("=")&&value!==void 0&&i++,name==="--deployment"?result.deployment=value:result.protectionBypass=value;continue}if(!VC_IGNORED_BOOLEAN_FLAGS.has(name)){if(VC_IGNORED_STRING_FLAGS.has(name)){let value=flagValue(beforeSeparator,i);!arg.includes("=")&&value!==void 0&&i++;continue}if(VC_BOOLEAN_FLAGS.has(name)){name==="--yes"?result.yes=!0:name==="--trace"?result.trace=!0:name==="--json"?result.json=!0:result.help=!0;continue}if(!result.target&&name==="--url"){let value=flagValue(beforeSeparator,i);!arg.includes("=")&&value!==void 0&&i++,result.target=value;continue}!result.target&&!arg.startsWith("-")?result.target=arg:result.toolFlags.push(arg)}}return result.toolFlags.push(...afterSeparator),result}function setupCurlLikeCommand(client,command,telemetryClient,options={}){let{print}=output_manager_default;if(options.allowFullUrl){let parsed=parseCurlLikeArgs(options.args??client.argv.slice(2),command.name);if(parsed.help)return print(help(command,{stream:client.stderr,columns:client.stderr.columns})),0;let path2=parsed.target;if(telemetryClient.trackCliArgumentPath(path2),parsed.deployment&&telemetryClient.trackCliOptionDeployment(parsed.deployment),parsed.protectionBypass&&telemetryClient.trackCliOptionProtectionBypass(parsed.protectionBypass),!path2)return output_manager_default.error(`${getCommandName(`${command.name} <url|path>`)} requires a URL or API path (e.g., 'https://example.vercel.app/api/hello' or '/api/hello')`),print(help(command,{stream:client.stderr,columns:client.stderr.columns})),2;let isFullUrl2=path2.startsWith("http://")||path2.startsWith("https://");return!isFullUrl2&&looksLikeHostname(path2)&&(isFullUrl2=!0),output_manager_default.debug(`${command.name} options (${parsed.toolFlags.length} args): ${JSON.stringify(parsed.toolFlags)}`),{path:isFullUrl2&&!path2.startsWith("http")?`https://${path2}`:path2,isFullUrl:isFullUrl2,deploymentFlag:parsed.deployment,protectionBypassFlag:parsed.protectionBypass,toolFlags:parsed.toolFlags,yes:parsed.yes,trace:parsed.trace,json:parsed.json}}let parsedArgs=null,flagsSpecification=getFlagsSpecification(command.options);try{parsedArgs=parseArguments(client.argv.slice(2),flagsSpecification)}catch(err){return printError(err),2}let{flags}=parsedArgs;if(parsedArgs.flags["--help"])return print(help(command,{stream:client.stderr,columns:client.stderr.columns})),0;parsedArgs.args[0]===command.name&&parsedArgs.args.shift();let separatorIndex=process.argv.indexOf("--"),path=parsedArgs.args[0];telemetryClient.trackCliArgumentPath(path);let deploymentFlag=flags["--deployment"];deploymentFlag&&telemetryClient.trackCliOptionDeployment(deploymentFlag);let protectionBypassFlag=flags["--protection-bypass"];if(protectionBypassFlag&&telemetryClient.trackCliOptionProtectionBypass(protectionBypassFlag),!path||path==="--"||path.startsWith("-"))return options.allowFullUrl?output_manager_default.error(`${getCommandName(`${command.name} <url|path>`)} requires a URL or API path (e.g., 'https://example.vercel.app/api/hello' or '/api/hello')`):output_manager_default.error(`${getCommandName(`${command.name} <path>`)} requires an API path (e.g., '/' or '/api/hello' or 'api/hello')`),print(help(command,{stream:client.stderr,columns:client.stderr.columns})),1;let isFullUrl=path.startsWith("http://")||path.startsWith("https://");if(!isFullUrl&&looksLikeHostname(path)&&(isFullUrl=!0),isFullUrl&&!options.allowFullUrl)return output_manager_default.error("The <path> argument must be a relative API path (e.g., '/' or '/api/hello'), not a full URL."),output_manager_default.print("To target a specific deployment within the currently linked project, use the --deployment <id|url> option."),print(help(command,{stream:client.stderr,columns:client.stderr.columns})),1;let toolFlags=separatorIndex!==-1?process.argv.slice(separatorIndex+1):[];return output_manager_default.debug(`${command.name} options (${toolFlags.length} args): ${JSON.stringify(toolFlags)}`),{path:isFullUrl&&!path.startsWith("http")?`https://${path}`:path,isFullUrl,deploymentFlag,protectionBypassFlag,toolFlags,yes:!!flags["--yes"],trace:!!flags["--trace"],json:!!flags["--json"]}}async function resolveProjectFromUrl(client,url){let host=toHost(url);try{let deployment=await resolveDeployment(client,host);if(deployment){let link=await linkFromDeployment(client,deployment);if(link)return link}}catch(err){if(output_manager_default.debug(`Deployment lookup failed for ${host}: ${err}`),isAPIError(err)&&err.status===429)return null}try{let aliasUrl=`/now/aliases/${encodeURIComponent(host)}`;try{let alias=await client.fetch(aliasUrl,{useCurrentTeam:!1,...detectExplicitScope(client)?{accountId:client.config.currentTeam}:{}});if(alias.projectId&&alias.ownerId)return{status:"linked",project:await client.fetch(`/v9/projects/${encodeURIComponent(alias.projectId)}`,{accountId:alias.ownerId}),org:orgFromOwner(alias.ownerId)}}catch(err){output_manager_default.debug(`User alias lookup failed for ${host}: ${err}`)}for(let accountId of await getDeploymentAccounts(client))try{let alias=await client.fetch(aliasUrl,{accountId}),projectId=alias.projectId,ownerId=alias.ownerId||accountId;if(projectId)return{status:"linked",project:await client.fetch(`/v9/projects/${encodeURIComponent(projectId)}`,{accountId:ownerId}),org:orgFromOwner(ownerId)}}catch(err){output_manager_default.debug(`Alias lookup failed for ${host} in ${accountId}: ${err}`)}}catch(err){output_manager_default.debug(`Team lookup failed for ${host}: ${err}`)}return null}async function getFullUrlAndToken(client,fullUrl,protectionBypassFlag){if(protectionBypassFlag)return{fullUrl,deploymentProtectionToken:protectionBypassFlag,link:null};if(process.env.VERCEL_AUTOMATION_BYPASS_SECRET)return output_manager_default.debug("Using protection bypass secret from environment variable"),{fullUrl,deploymentProtectionToken:process.env.VERCEL_AUTOMATION_BYPASS_SECRET,link:null};let link=await resolveProjectFromUrl(client,fullUrl),deploymentProtectionToken=null;if(link)try{deploymentProtectionToken=await getOrCreateDeploymentProtectionToken(client,link,{readinessUrl:fullUrl})}catch(err){output_manager_default.debug(`Failed to get deployment protection bypass token: ${err}`)}return{fullUrl,deploymentProtectionToken,link}}async function linkFromDeployment(client,deployment){return!deployment.projectId||!deployment.ownerId?null:{status:"linked",project:await client.fetch(`/v9/projects/${encodeURIComponent(deployment.projectId)}`,{accountId:deployment.ownerId}),org:orgFromOwner(deployment.ownerId)}}async function resolveTargetProject(client,deployment,deploymentFlag){try{let link=await linkFromDeployment(client,deployment);return link||output_manager_default.warn(`Deployment "${deploymentFlag}" is missing project metadata; proceeding without an automatic protection bypass token.`),link}catch(err){return output_manager_default.debug(`Failed to resolve deployment project: ${err}`),output_manager_default.warn(`Failed to load project for deployment "${deploymentFlag}"; proceeding without an automatic protection bypass token.`),null}}async function tryGetDeployment(client,selector){try{return await resolveDeployment(client,selector)}catch(err){return output_manager_default.debug(`Failed to resolve deployment: ${err}`),null}}async function tryLinkFromSelector(client,selector){try{let deployment=await resolveDeployment(client,selector);return deployment?await linkFromDeployment(client,deployment):null}catch(err){return output_manager_default.debug(`Failed to resolve trace project context: ${err}`),null}}async function getLinkedProjectOrNull(client){try{let linked=await getLinkedProject(client,{cwd:client.cwd});return linked.status==="linked"?linked:null}catch(err){return output_manager_default.debug(`Failed to load linked project: ${err}`),null}}function hasAutomationBypassToken(project){return Object.values(project.protectionBypass??{}).some(token=>token.scope==="automation-bypass")}async function getDeploymentUrlAndToken(client,commandName,path,options){let{deploymentFlag,protectionBypassFlag,autoConfirm,resolveProjectForTrace}=options,suppliedProtectionBypass=deploymentFlag?protectionBypassFlag??(process.env.VERCEL_AUTOMATION_BYPASS_SECRET||void 0):protectionBypassFlag,link=null,createProtectionBypassIfMissing=!deploymentFlag,baseUrl;if(deploymentFlag){let requestedBaseUrl=deploymentFlag.startsWith("http://")||deploymentFlag.startsWith("https://")||deploymentFlag.includes("vercel.app")?await getDeploymentUrlById(client,deploymentFlag):null,deploymentSelector=deploymentFlag.includes(".")||deploymentFlag.startsWith("dpl_")?deploymentFlag:`dpl_${deploymentFlag}`;if(suppliedProtectionBypass!==void 0){if(baseUrl=requestedBaseUrl??await getDeploymentUrlById(client,deploymentFlag)??"",!baseUrl)return output_manager_default.error(`No deployment found for ID "${deploymentFlag}"`),1;resolveProjectForTrace&&(link=await tryLinkFromSelector(client,deploymentSelector)??await getLinkedProjectOrNull(client))}else{let deployment=await tryGetDeployment(client,deploymentSelector);if(baseUrl=requestedBaseUrl??(deployment?.url?`https://${deployment.url}`:""),!baseUrl)return output_manager_default.error(`No deployment found for ID "${deploymentFlag}"`),1;deployment?(link=await resolveTargetProject(client,deployment,deploymentFlag),link&&!hasAutomationBypassToken(link.project)&&(createProtectionBypassIfMissing=(await getLinkedProjectOrNull(client))?.project.id===link.project.id)):output_manager_default.warn(`Could not resolve project information for deployment "${deploymentFlag}"; proceeding without an automatic protection bypass token.`)}}else{try{await getScope(client)}catch(err){if((0,import_error_utils.isErrnoException)(err)&&(err.code==="NOT_AUTHORIZED"||err.code==="TEAM_DELETED"))return output_manager_default.error(err.message),1;throw err}let ensuredLink;try{ensuredLink=await ensureLink(commandName,client,client.cwd,{autoConfirm})}catch(err){if((0,import_error_utils.isErrnoException)(err)&&err.code==="NOT_AUTHORIZED")return output_manager_default.error(err.message),1;throw err}if(typeof ensuredLink=="number")return ensuredLink;link=ensuredLink;let{project}=ensuredLink;if(!project.targets&&!project.latestDeployments){let linkedProject=await getLinkedProject(client,{cwd:client.cwd});if(linkedProject.status!=="linked")return output_manager_default.error("This command requires a linked project. Please run:"),output_manager_default.print(" vercel link"),1;if(!linkedProject.project||!linkedProject.org)return output_manager_default.error("Failed to get project information"),1;project=linkedProject.project}let preferredAlias=project.targets?.production?.alias?.[0],backupAlias=project.latestDeployments?.[0]?.url,target=preferredAlias||backupAlias;if(!target)throw new Error("No deployment URL found for the project");baseUrl=`https://${target}`}let fullUrl=`${baseUrl}${path.startsWith("/")?path:`/${path}`}`;output_manager_default.debug(`${import_chalk.default.cyan("Target URL:")} ${import_chalk.default.bold(fullUrl)}`);let deploymentProtectionToken=suppliedProtectionBypass??null;if(suppliedProtectionBypass===void 0&&link?.project.id)try{deploymentProtectionToken=await getOrCreateDeploymentProtectionToken(client,link,{createIfMissing:createProtectionBypassIfMissing,readinessUrl:fullUrl})}catch(err){return output_manager_default.error(`Failed to get deployment protection bypass token: ${err instanceof Error?err.message:String(err)}`),1}return{fullUrl,deploymentProtectionToken,link}}function traceCurl(root){let span=root?.child("vc.cli.curl"),finished=!1;return code=>{finished||(finished=!0,code!==0&&span?.setAttributes({error:"true"}),span?.stop())}}var import_error_utils2=__toESM(require_dist(),1);import{spawn}from"child_process";import{tmpdir}from"os";import{join as join2}from"path";import{mkdtemp,readFile as readFile2,rm}from"fs/promises";async function confirmProduction(client,{deploymentTarget,yes,isTTY}){return deploymentTarget!=="production"||yes?"proceed":isTTY?await client.input.confirm("You are about to capture a trace against a production deployment. Continue?",!1)?"proceed":"declined":(output_manager_default.error("Use --yes to capture traces on production from non-interactive contexts."),"non-tty-no-yes")}import{createHash}from"crypto";import{chmod,mkdir,readFile,unlink,writeFile}from"fs/promises";import{dirname,join}from"path";var FALLBACK_TTL_MS=5*60*1e3,EXPIRY_BUFFER_MS=30*1e3,CACHE_SCHEMA_VERSION=1;function resolveCacheDir(override){return override||join(getGlobalPathConfig(),"cache","traces")}function cacheFilename(teamId,host){let key=`${teamId??""}:${host}`;return`${createHash("sha256").update(key).digest("hex")}.json`}function cachePath(cacheDir,teamId,host){return join(cacheDir,cacheFilename(teamId,host))}async function readCache(path){let raw;try{raw=await readFile(path,"utf8")}catch{return null}try{let parsed=JSON.parse(raw);return!parsed||typeof parsed.token!="string"||typeof parsed.expiresAt!="number"||parsed.schemaVersion!==CACHE_SCHEMA_VERSION?null:parsed}catch{return output_manager_default.debug(`Trace cookie cache file is corrupt at ${path}; re-issuing.`),null}}async function writeCache(path,entry){await mkdir(dirname(path),{recursive:!0}),await writeFile(path,JSON.stringify(entry),{mode:384}),await chmod(path,384)}async function issueToken(client,{teamId,projectId,hostname}){let body=JSON.stringify({projectId,hostname}),response=await client.fetch("/v1/projects/traces/session",{method:"POST",body,headers:{"Content-Type":"application/json"},accountId:teamId});if(!response?.token)throw new Error("Trace session response is missing a token");let expiresAt=typeof response.expiresAt=="number"?response.expiresAt:Date.now()+FALLBACK_TTL_MS;return{token:response.token,expiresAt}}async function getTraceSessionToken({client,teamId,projectId,host,evictedToken,cacheDir}){let dir=resolveCacheDir(cacheDir),hostname=toHost(host),path=cachePath(dir,teamId,hostname),cached=await readCache(path);if(cached&&evictedToken&&cached.token===evictedToken)await unlink(path).catch(()=>{});else if(cached&&Date.now()<cached.expiresAt-EXPIRY_BUFFER_MS)return{token:cached.token,expiresAt:cached.expiresAt,fromCache:!0};let issued=await issueToken(client,{teamId,projectId,hostname});try{await writeCache(path,{token:issued.token,expiresAt:issued.expiresAt,schemaVersion:CACHE_SCHEMA_VERSION})}catch(err){output_manager_default.debug(`Failed to write trace cookie cache: ${err}`)}return{token:issued.token,expiresAt:issued.expiresAt,fromCache:!1}}var TRACE_COOKIE_NAME="_vercel_tracing",SESSION_COOKIE_NAME="_vercel_session";async function lookupDeployment(client,fullUrl,accountId){let deployment=await resolveDeployment(client,fullUrl,accountId);if(!deployment)throw new Error("Deployment not found");return deployment}function resolveTeamId(link,deployment){if(link?.org.type==="team")return link.org.id;if(deployment.ownerId?.startsWith("team_"))return deployment.ownerId}function extractVercelId(headerDump){let lines=headerDump.split(/\r?\n/),lastValue;for(let line of lines){let idx=line.indexOf(":");if(idx===-1)continue;line.slice(0,idx).trim().toLowerCase()==="x-vercel-id"&&(lastValue=line.slice(idx+1).trim())}if(!lastValue)return;let sepIdx=lastValue.lastIndexOf("::");return sepIdx===-1?lastValue:lastValue.slice(sepIdx+2)}function extractFinalStatus(headerDump){let lines=headerDump.split(/\r?\n/),lastStatus;for(let line of lines){let match=line.match(/^HTTP\/[\d.]+\s+(\d{3})/);match&&(lastStatus=Number(match[1]))}return lastStatus}async function runCurlAndCaptureHeaders(client,curlFlags,json){let tmpDir=await mkdtemp(join2(tmpdir(),"vc-curl-trace-")),headerFile=join2(tmpDir,"headers"),flags=["--dump-header",headerFile,...curlFlags];try{let{exitCode,capturedBody}=await new Promise(resolve=>{let finishTrace=traceCurl(client.telemetryEventStore.enabled?client.rootSpan:void 0),child=spawn("curl",flags,{stdio:json?["inherit","pipe","inherit"]:"inherit",shell:!1}),buf="";json&&child.stdout&&(child.stdout.setEncoding("utf8"),child.stdout.on("data",chunk=>{buf+=chunk})),child.on("error",err=>{finishTrace(1),err.code==="ENOENT"?output_manager_default.error("curl command not found. Please install curl."):output_manager_default.error(`Failed to execute curl: ${err.message}`),resolve({exitCode:1,capturedBody:buf})}),child.on("close",code=>{finishTrace(code),resolve({exitCode:code??1,capturedBody:buf})})}),headerDump="";try{headerDump=await readFile2(headerFile,"utf8")}catch(err){output_manager_default.debug(`Failed to read curl header dump: ${err}`)}return{exitCode,headerDump,capturedBody}}finally{await rm(tmpDir,{recursive:!0,force:!0}).catch(()=>{})}}async function trace(client,{fullUrl,link,curlFlags,json,yes,telemetry}){telemetry.trackCliFlagTrace(!0),json&&telemetry.trackCliFlagJson(!0);let accountId=link?.org.id,deployment;try{deployment=await lookupDeployment(client,fullUrl,accountId)}catch(err){return output_manager_default.error(`Failed to look up deployment for tracing: ${err instanceof Error?err.message:String(err)}`),1}let projectId=link?.project.id??deployment.projectId;if(!projectId)return output_manager_default.error("Could not resolve project for trace session. Run `vercel link` and retry."),1;let teamId=resolveTeamId(link,deployment),userId;try{userId=client.authConfig.userId??(await getUser(client)).id}catch(err){return output_manager_default.error(`Failed to resolve user for trace session: ${(0,import_error_utils2.errorToString)(err)}`),1}let deploymentTarget=deployment.target==="production"?"production":"preview",confirmation=await confirmProduction(client,{deploymentTarget,yes,isTTY:!!client.stdin.isTTY});if(confirmation==="non-tty-no-yes")return 1;if(confirmation==="declined")return output_manager_default.log("Trace cancelled."),0;deploymentTarget==="production"&&yes&&telemetry.trackCliFlagYesOnProduction(!0);let session;try{session=await getTraceSessionToken({client,teamId,projectId,host:fullUrl})}catch(err){return output_manager_default.error(`Failed to acquire trace session: ${err instanceof Error?err.message:String(err)}`),1}let{exitCode,headerDump,capturedBody}=await runCurlWithCookie(client,session.token,userId,curlFlags,json);if(session.fromCache&&extractFinalStatus(headerDump)===401&&exitCode===0){output_manager_default.debug("Trace cookie returned 401; evicting cache and retrying.");let refreshed;try{refreshed=await getTraceSessionToken({client,teamId,projectId,host:fullUrl,evictedToken:session.token})}catch(err){return output_manager_default.error(`Failed to refresh trace session after 401: ${err instanceof Error?err.message:String(err)}`),1}({exitCode,headerDump,capturedBody}=await runCurlWithCookie(client,refreshed.token,userId,curlFlags,json))}let requestId=extractVercelId(headerDump);return json?(client.stdout.write(`${JSON.stringify({response:capturedBody,requestId:requestId??null},null,2)}
8
- `),requestId?exitCode:exitCode===0?1:exitCode):requestId?(client.stderr.write(`
9
- Run \`vercel traces inspect ${requestId}\` to fetch the trace.
10
- `),exitCode):(output_manager_default.error("Trace cookie was set but the response did not include an x-vercel-id header."),exitCode===0?1:exitCode)}async function runCurlWithCookie(client,token,userId,curlFlags,json){let flagsWithCookie=["--header",`Cookie: ${TRACE_COOKIE_NAME}=${token}; ${SESSION_COOKIE_NAME}=${userId}`,...curlFlags];return output_manager_default.debug(`Executing: curl ${flagsWithCookie.map(redactSecretHeader).map(requoteArgs).join(" ")}`),runCurlAndCaptureHeaders(client,flagsWithCookie,json)}async function curl(client){return runCurl(client,{})}async function runCurl(client,{forceTrace=!1,args}){let telemetryClient=new CurlTelemetryClient({opts:{store:client.telemetryEventStore}}),setup=setupCurlLikeCommand(client,curlCommand,telemetryClient,{allowFullUrl:!0,args});if(typeof setup=="number")return setup;let{path,isFullUrl,deploymentFlag,protectionBypassFlag,toolFlags,json:jsonFlag}=setup,unsupportedFlag=toolFlags.find(escapesRedirectLimit);if(unsupportedFlag)return output_manager_default.error(`${cmd(unsupportedFlag)} is not supported by ${getCommandName("curl")}.`),2;let traceFlag=forceTrace||setup.trace,result=isFullUrl?await getFullUrlAndToken(client,path,protectionBypassFlag):await getDeploymentUrlAndToken(client,"curl",path,{deploymentFlag,protectionBypassFlag,autoConfirm:setup.yes,resolveProjectForTrace:traceFlag});if(typeof result=="number")return result;let{fullUrl,deploymentProtectionToken}=result,curlFlags=[...toolFlags];return deploymentProtectionToken&&(curlFlags.unshift("--header",`x-vercel-protection-bypass: ${deploymentProtectionToken}`),curlFlags.push("--max-redirs","0")),curlFlags.unshift("--url",fullUrl),traceFlag?trace(client,{fullUrl,link:result.link??null,curlFlags,json:jsonFlag,yes:setup.yes,telemetry:telemetryClient}):(output_manager_default.debug(`Executing: curl ${curlFlags.map(redactSecretHeader).map(requoteArgs).join(" ")}`),deploymentProtectionToken&&bypassesProtection(result.link,fullUrl)&&(output_manager_default.warning("This request bypasses Deployment Protection, so its response doesn't show whether the URL is public."),output_manager_default.print(`
11
- To check public access:
12
- ${cmd(`curl ${shellQuote(fullUrl)}`)}
13
- `)),new Promise(resolve=>{let finishTrace=traceCurl(client.telemetryEventStore.enabled?client.rootSpan:void 0),curlProcess=spawn2("curl",curlFlags,{stdio:"inherit",shell:!1});curlProcess.on("error",err=>{finishTrace(1),"code"in err&&err.code==="ENOENT"?(output_manager_default.error("curl command not found. Please install curl."),resolve(1)):(output_manager_default.error(`Failed to execute curl: ${err.message}`),resolve(1))}),curlProcess.on("close",code=>{finishTrace(code),resolve(code??1)})}))}function bypassesProtection(link,url){if(!link)return!0;let methods=readEnabledProtection(link.project),productionDomain=link.project.targets?.production?.alias?.[0];return(productionDomain&&toHost(url).toLowerCase()===productionDomain?getProtectionForProductionDomain(methods):methods).length>0}var CURL_SHORT_OPTIONS_WITH_VALUE="EKCbcdDFPHhmoUQreXYytzTuAw";function escapesRedirectLimit(flag){if(flag==="--"||flag==="--next"||flag==="--config")return!0;if(!flag.startsWith("-")||flag.startsWith("--"))return!1;for(let option of flag.slice(1)){if(option===":"||option==="K")return!0;if(CURL_SHORT_OPTIONS_WITH_VALUE.includes(option))return!1}return!1}function shellQuote(value){return/^[\w./:@%+=,-]+$/.test(value)?value:`'${value.replace(/'/g,"'\\''")}'`}export{redactSecretHeader,requoteArgs,setupCurlLikeCommand,getDeploymentUrlAndToken,curl,runCurl};