@vercel/cli-support 66.2.0 → 66.3.0-snapshot-3206bcf0afd3

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 (37) hide show
  1. package/dist/chunks/{alerts-NLLCERTK.js → alerts-MDU5KBQL.js} +1 -1
  2. package/dist/chunks/{chunk-6U7TRWBO.js → chunk-HVFGIJ44.js} +2 -2
  3. package/dist/chunks/chunk-KMTHGHJV.js +8 -0
  4. package/dist/chunks/{chunk-56QPAEAW.js → chunk-LXZ45FUT.js} +1 -1
  5. package/dist/chunks/{chunk-YALFS5SH.js → chunk-PX55WGPZ.js} +1 -1
  6. package/dist/chunks/{chunk-EIBQNIN7.js → chunk-TIOZWOR5.js} +1 -1
  7. package/dist/chunks/chunk-TUB3APDV.js +7 -0
  8. package/dist/chunks/chunk-VKVH7LHB.js +7 -0
  9. package/dist/chunks/{chunk-WHL4PWDW.js → chunk-XLYO5QNG.js} +1 -1
  10. package/dist/chunks/{chunk-YON6DNQB.js → chunk-ZGATYK5C.js} +1 -1
  11. package/dist/chunks/cli-embedded-FD3CAPRY.js +84 -0
  12. package/dist/chunks/{config-BYHUSTMY.js → config-ARJS37DC.js} +1 -1
  13. package/dist/chunks/{engine-I887QHnP-RUEEKCKH.js → engine-D8YAsQS_-WNPHYRQF.js} +2 -2
  14. package/dist/chunks/{image-H4HIURNR.js → image-PJBSA7SU.js} +1 -1
  15. package/dist/chunks/serving-aOQsBok0-OL36TMZU.js +8 -0
  16. package/dist/commands/deploy/index.js +1 -1
  17. package/dist/commands/env/index.js +1 -1
  18. package/dist/commands/link/index.js +1 -1
  19. package/dist/commands/project/index.js +1 -1
  20. package/dist/commands-account.js +2 -2
  21. package/dist/commands-ai.js +1 -1
  22. package/dist/commands-blob.js +1 -1
  23. package/dist/commands-core.js +15 -11
  24. package/dist/commands-deployments.js +1 -1
  25. package/dist/commands-flags.js +1 -1
  26. package/dist/commands-integrations.js +1 -1
  27. package/dist/commands-observability.js +2 -2
  28. package/dist/commands-routing.js +15 -3
  29. package/dist/index.js +1 -1
  30. package/dist/package.json +1 -1
  31. package/dist/version.mjs +1 -1
  32. package/package.json +12 -12
  33. package/dist/chunks/chunk-MGZ3Z4PF.js +0 -8
  34. package/dist/chunks/chunk-PQSW6EAL.js +0 -7
  35. package/dist/chunks/chunk-UFCL2VBD.js +0 -7
  36. package/dist/chunks/cli-embedded-KDIRH75G.js +0 -81
  37. package/dist/chunks/serving-Bulte-NO-VPBE6F4V.js +0 -8
@@ -4,4 +4,4 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{getSubcommand}from"./chunk-ETV3C2CV.js";import{getCommandAliases}from"./chunk-6U7TRWBO.js";import"./chunk-QOLGACFD.js";import{tracesCommand}from"./chunk-DDPH26ZO.js";import{lsSubcommand,rmSubcommand,setSubcommand,tracesConfigCommand}from"./chunk-PIDEH4SJ.js";import"./chunk-IIK6GUVI.js";import"./chunk-C35SG42R.js";import"./chunk-2GBU6ULJ.js";import"./chunk-EJLYDHT7.js";import"./chunk-DOBV3XLO.js";import"./chunk-UFCL2VBD.js";import"./chunk-BMIYC2MH.js";import"./chunk-6CJFPT4F.js";import"./chunk-ZZD5W5KT.js";import"./chunk-VHSAI6FS.js";import"./chunk-F7L5SXJM.js";import"./chunk-GLCSWIB4.js";import"./chunk-XECELSF5.js";import"./chunk-6FYPSSL4.js";import"./chunk-UQZZX2J7.js";import"./chunk-UDZJCD5W.js";import"./chunk-5ZCSFPWG.js";import"./chunk-PY4WWD6Z.js";import"./chunk-XDYVJWGX.js";import"./chunk-JALVF3C2.js";import"./chunk-BPIGFKNN.js";import"./chunk-AB4WXRCO.js";import"./chunk-SYJXONEV.js";import"./chunk-KK5C7HVP.js";import{help}from"./chunk-7KCRYDGK.js";import"./chunk-GLIQ4KNY.js";import{TelemetryClient}from"./chunk-KDCODXVL.js";import"./chunk-NWGBDBZI.js";import"./chunk-DTUEHPME.js";import{warnDeprecatedSubcommand}from"./chunk-6GKP6VUF.js";import"./chunk-4NTBYNFR.js";import"./chunk-4SAVH3H7.js";import"./chunk-B4KA3ZH2.js";import"./chunk-BOJDM3O7.js";import{output_manager_default}from"./chunk-AP6DZGTK.js";import"./chunk-BLUPZPAS.js";import"./chunk-5MDNVAE6.js";import"./chunk-MCYG7CCE.js";import"./chunk-YHPPP3SF.js";import"./chunk-24SIHFEW.js";import"./chunk-CFJBDBYH.js";import"./chunk-2BKALEOP.js";import"./chunk-NB2WLB3J.js";import"./chunk-ISWW3DKF.js";import"./chunk-BRQUZ5NC.js";import"./chunk-BULSRTQE.js";import"./chunk-BZENIQ7N.js";var TracesConfigTelemetryClient=class extends TelemetryClient{trackCliSubcommandLs(actual){this.trackCliSubcommand({subcommand:"ls",value:actual})}trackCliSubcommandSet(actual){this.trackCliSubcommand({subcommand:"set",value:actual})}trackCliSubcommandRemove(actual){this.trackCliSubcommand({subcommand:"remove",value:actual})}};var COMMAND_CONFIG={ls:getCommandAliases(lsSubcommand),set:getCommandAliases(setSubcommand),remove:getCommandAliases(rmSubcommand)},SUBCOMMAND_METADATA={ls:lsSubcommand,set:setSubcommand,remove:rmSubcommand};async function config(client,{args,needHelp,subcommandOriginal,telemetry}){let{subcommand:action,subcommandOriginal:actionOriginal}=getSubcommand(args,COMMAND_CONFIG),actionMetadata=typeof action=="string"?SUBCOMMAND_METADATA[action]:void 0;function printHelp(command){return output_manager_default.print(help(command,{stream:client.stderr,parent:tracesCommand,columns:client.stderr.columns})),needHelp?0:2}if(needHelp)return telemetry.trackCliFlagHelp("traces",subcommandOriginal),printHelp(actionMetadata||tracesConfigCommand);telemetry.trackCliSubcommandConfig(subcommandOriginal);let configTelemetry=new TracesConfigTelemetryClient({opts:{store:client.telemetryEventStore}});switch(action){case"ls":return configTelemetry.trackCliSubcommandLs(actionOriginal),(await import("./ls-JDKTIVX6.js")).default(client);case"set":return configTelemetry.trackCliSubcommandSet(actionOriginal),(await import("./set-MMOLNY72.js")).default(client);case"remove":return configTelemetry.trackCliSubcommandRemove(actionOriginal),actionOriginal==="delete"&&warnDeprecatedSubcommand(client,"traces config delete","traces config remove"),(await import("./rm-QFQTQKZL.js")).default(client);default:return printHelp(tracesConfigCommand)}}export{config as default};
7
+ import{getSubcommand}from"./chunk-ETV3C2CV.js";import{getCommandAliases}from"./chunk-HVFGIJ44.js";import"./chunk-QOLGACFD.js";import{tracesCommand}from"./chunk-DDPH26ZO.js";import{lsSubcommand,rmSubcommand,setSubcommand,tracesConfigCommand}from"./chunk-PIDEH4SJ.js";import"./chunk-IIK6GUVI.js";import"./chunk-C35SG42R.js";import"./chunk-2GBU6ULJ.js";import"./chunk-EJLYDHT7.js";import"./chunk-DOBV3XLO.js";import"./chunk-TUB3APDV.js";import"./chunk-BMIYC2MH.js";import"./chunk-6CJFPT4F.js";import"./chunk-ZZD5W5KT.js";import"./chunk-VHSAI6FS.js";import"./chunk-F7L5SXJM.js";import"./chunk-GLCSWIB4.js";import"./chunk-XECELSF5.js";import"./chunk-6FYPSSL4.js";import"./chunk-UQZZX2J7.js";import"./chunk-UDZJCD5W.js";import"./chunk-5ZCSFPWG.js";import"./chunk-PY4WWD6Z.js";import"./chunk-XDYVJWGX.js";import"./chunk-JALVF3C2.js";import"./chunk-BPIGFKNN.js";import"./chunk-AB4WXRCO.js";import"./chunk-SYJXONEV.js";import"./chunk-KK5C7HVP.js";import{help}from"./chunk-7KCRYDGK.js";import"./chunk-GLIQ4KNY.js";import{TelemetryClient}from"./chunk-KDCODXVL.js";import"./chunk-NWGBDBZI.js";import"./chunk-DTUEHPME.js";import{warnDeprecatedSubcommand}from"./chunk-6GKP6VUF.js";import"./chunk-4NTBYNFR.js";import"./chunk-4SAVH3H7.js";import"./chunk-B4KA3ZH2.js";import"./chunk-BOJDM3O7.js";import{output_manager_default}from"./chunk-AP6DZGTK.js";import"./chunk-BLUPZPAS.js";import"./chunk-5MDNVAE6.js";import"./chunk-MCYG7CCE.js";import"./chunk-YHPPP3SF.js";import"./chunk-24SIHFEW.js";import"./chunk-CFJBDBYH.js";import"./chunk-2BKALEOP.js";import"./chunk-NB2WLB3J.js";import"./chunk-ISWW3DKF.js";import"./chunk-BRQUZ5NC.js";import"./chunk-BULSRTQE.js";import"./chunk-BZENIQ7N.js";var TracesConfigTelemetryClient=class extends TelemetryClient{trackCliSubcommandLs(actual){this.trackCliSubcommand({subcommand:"ls",value:actual})}trackCliSubcommandSet(actual){this.trackCliSubcommand({subcommand:"set",value:actual})}trackCliSubcommandRemove(actual){this.trackCliSubcommand({subcommand:"remove",value:actual})}};var COMMAND_CONFIG={ls:getCommandAliases(lsSubcommand),set:getCommandAliases(setSubcommand),remove:getCommandAliases(rmSubcommand)},SUBCOMMAND_METADATA={ls:lsSubcommand,set:setSubcommand,remove:rmSubcommand};async function config(client,{args,needHelp,subcommandOriginal,telemetry}){let{subcommand:action,subcommandOriginal:actionOriginal}=getSubcommand(args,COMMAND_CONFIG),actionMetadata=typeof action=="string"?SUBCOMMAND_METADATA[action]:void 0;function printHelp(command){return output_manager_default.print(help(command,{stream:client.stderr,parent:tracesCommand,columns:client.stderr.columns})),needHelp?0:2}if(needHelp)return telemetry.trackCliFlagHelp("traces",subcommandOriginal),printHelp(actionMetadata||tracesConfigCommand);telemetry.trackCliSubcommandConfig(subcommandOriginal);let configTelemetry=new TracesConfigTelemetryClient({opts:{store:client.telemetryEventStore}});switch(action){case"ls":return configTelemetry.trackCliSubcommandLs(actionOriginal),(await import("./ls-JDKTIVX6.js")).default(client);case"set":return configTelemetry.trackCliSubcommandSet(actionOriginal),(await import("./set-MMOLNY72.js")).default(client);case"remove":return configTelemetry.trackCliSubcommandRemove(actionOriginal),actionOriginal==="delete"&&warnDeprecatedSubcommand(client,"traces config delete","traces config remove"),(await import("./rm-QFQTQKZL.js")).default(client);default:return printHelp(tracesConfigCommand)}}export{config as default};
@@ -4,11 +4,11 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{DroppedError,ExternalEvent,ExternalLocation,actorParts,afterRetry,byVercelBot,channelOf,derivedId,displayText,extractMentions,isEmail,isThreadTarget,platformProfile,replaceMentions,shownName,vercelDeployments,viaText,waitUntil}from"./chunk-WHL4PWDW.js";import{ChannelPath,HttpError,LabelKey,MESSAGE_TEXT_MAX,NewLabels,badRequest,canonicalEmoji,fileSize,notFound,toStorable,typeOf}from"./chunk-MGZ3Z4PF.js";import{external_exports}from"./chunk-2AMO2VMV.js";import"./chunk-BZENIQ7N.js";var ROUTES=Symbol.for("board.syncRoutes");var ResolvedTarget=external_exports.object({target:external_exports.string().min(1),channel:external_exports.string().min(1),kind:external_exports.enum(["channel","thread"])}).strict(),UnreadableError=class extends Error{code;constructor(code,message){super(message),this.code=code}},channelMissing=error=>error instanceof UnreadableError&&error.code==="channel_not_found",ReceivedEvent=external_exports.object({event:ExternalEvent,raw:external_exports.unknown(),dedupe:external_exports.string().min(1)}),routed=new WeakMap,routesFor=provider=>routed.get(provider);var opensBlock=text=>/^(```|~~~|[-*+] |\d+[.)] |#{1,6} |>|\|)/.test(text),EventBase=external_exports.object({id:external_exports.string().min(1),platform:external_exports.string().min(1),key:external_exports.string().min(1),...ExternalLocation.shape,raw:external_exports.unknown()});var SyncOverrides=external_exports.object({root:external_exports.custom(value=>typeof value=="function").optional(),text:external_exports.string().optional(),labels:NewLabels.optional(),unset:external_exports.array(LabelKey).optional(),noSync:external_exports.boolean().optional()}).strict();function immutable(value){if(value&&typeof value=="object"){for(let item of Object.values(value))immutable(item);Object.freeze(value)}return value}var clampText=(raw,files=!1)=>{let text=toStorable(raw),trimmed=text.trim()===""?files?"":"(no text)":text;return trimmed.length>1e4?`${trimmed.slice(0,MESSAGE_TEXT_MAX-1).toWellFormed()}\u2026`:trimmed},fileNote=(file,why,name=file.name??"a file")=>`\u{1F4CE} ${name}${file.size!==void 0?` (${fileSize(file.size)})`:""} didn't come over: ${why}`,keepsNoFiles=error=>error instanceof HttpError&&error.code==="no_files",fileLink=(file,why)=>{let name=file.name??"a file";if(!file.url||!/^https?:\/\//.test(file.url))return fileNote(file,why);let label=name.replace(/[[\]\\]/g,char=>`\\${char}`),url=file.url.replace(/[ ()]/g,char=>`%${char.charCodeAt(0).toString(16).toUpperCase()}`);return fileNote(file,why,`[${label}](${url})`)},withNotes=(text,notes)=>notes.length?`${text.trim()?`${text}
7
+ import{DroppedError,ExternalEvent,ExternalLocation,actorParts,afterRetry,byVercelBot,channelOf,derivedId,displayText,extractMentions,isEmail,isThreadTarget,platformProfile,replaceMentions,shownName,vercelDeployments,viaText,waitUntil}from"./chunk-XLYO5QNG.js";import{ChannelPath,HttpError,LabelKey,MESSAGE_TEXT_MAX,NewLabels,badRequest,canonicalEmoji,fileSize,importedFileName,notFound,toStorable,typeOf}from"./chunk-KMTHGHJV.js";import{external_exports}from"./chunk-2AMO2VMV.js";import"./chunk-BZENIQ7N.js";var ROUTES=Symbol.for("board.syncRoutes");var ResolvedTarget=external_exports.object({target:external_exports.string().min(1),channel:external_exports.string().min(1),kind:external_exports.enum(["channel","thread"])}).strict(),UnreadableError=class extends Error{code;constructor(code,message){super(message),this.code=code}},channelMissing=error=>error instanceof UnreadableError&&error.code==="channel_not_found",ReceivedEvent=external_exports.object({event:ExternalEvent,raw:external_exports.unknown(),dedupe:external_exports.string().min(1)}),routed=new WeakMap,routesFor=provider=>routed.get(provider);var opensBlock=text=>/^(```|~~~|[-*+] |\d+[.)] |#{1,6} |>|\|)/.test(text),EventBase=external_exports.object({id:external_exports.string().min(1),platform:external_exports.string().min(1),key:external_exports.string().min(1),...ExternalLocation.shape,raw:external_exports.unknown()});var SyncOverrides=external_exports.object({root:external_exports.custom(value=>typeof value=="function").optional(),text:external_exports.string().optional(),labels:NewLabels.optional(),unset:external_exports.array(LabelKey).optional(),noSync:external_exports.boolean().optional()}).strict();function immutable(value){if(value&&typeof value=="object"){for(let item of Object.values(value))immutable(item);Object.freeze(value)}return value}var clampText=(raw,files=!1)=>{let text=toStorable(raw),trimmed=text.trim()===""?files?"":"(no text)":text;return trimmed.length>1e4?`${trimmed.slice(0,MESSAGE_TEXT_MAX-1).toWellFormed()}\u2026`:trimmed},fileNote=(file,why,name=file.name??"a file")=>`\u{1F4CE} ${name}${file.size!==void 0?` (${fileSize(file.size)})`:""} didn't come over: ${why}`,keepsNoFiles=error=>error instanceof HttpError&&error.code==="no_files",fileLink=(file,why)=>{let name=file.name??"a file";if(!file.url||!/^https?:\/\//.test(file.url))return fileNote(file,why);let label=name.replace(/[[\]\\]/g,char=>`\\${char}`),url=file.url.replace(/[ ()]/g,char=>`%${char.charCodeAt(0).toString(16).toUpperCase()}`);return fileNote(file,why,`[${label}](${url})`)},withNotes=(text,notes)=>notes.length?`${text.trim()?`${text}
8
8
 
9
9
  `:""}${notes.join(`
10
10
  `)}`:text,notesIn=text=>text.split(`
11
- `).filter(line=>/^📎 .* didn't come over: /u.test(line)),linkKey=link=>JSON.stringify([link.url,link.message,link.snapshot,link.unavailable]),sameLinks=(a,b)=>a.length===b.length&&a.every((link,i)=>linkKey(link)===linkKey(b[i])),FILE_ATTEMPTS=3,EMAIL_TTL_MS=3e5,EMAIL_LOOKUPS_PER_MESSAGE_MAX=10,GATE_WAIT_MS=2e3,DELIVERY_ATTEMPTS=5,PULL_MS=24e4,NEVER=new AbortController().signal,jsonSafe=value=>{try{return JSON.parse(JSON.stringify(value??null))}catch{return null}},storableJson=value=>typeof value=="string"?toStorable(value):Array.isArray(value)?value.map(storableJson):value!==null&&typeof value=="object"?Object.fromEntries(Object.entries(value).map(([key,item])=>[toStorable(key),storableJson(item)])):value,describe=error=>{let code=error?.data?.error,text=typeof code=="string"?code:error instanceof Error?error.message:String(error);return toStorable(text.slice(0,500))||"unknown error"},missing=error=>error instanceof HttpError&&error.status===404;function keyedId(key,platform,id){return id.startsWith(`${key}:`)?id:`${key}:${id.startsWith(`${platform}:`)?id.slice(platform.length+1):id}`}function keyedText(key,platform,text){return key===platform?text:replaceMentions(text,token=>token.kind==="actor"&&token.actor.startsWith(`${platform}:`)?`@[${keyedId(key,platform,token.actor)}]`:null)}function keyedEvent(key,platform,event){if(!("author"in event))return event;let author={...event.author,id:keyedId(key,platform,event.author.id)};return event.kind!=="message"&&event.kind!=="edited"||key===platform?{...event,author}:{...event,author,...event.mentioned?{mentioned:event.mentioned.map(user=>({...user,id:keyedId(key,platform,user.id)}))}:{},text:keyedText(key,platform,event.text)}}function createSyncEngine(entries){let bound=null,host=()=>{if(!bound)throw new Error("sync used before board() bound it");return bound},me={self:"sync",origin:{via:{kind:"engine"}}};function call(method,input,signal=NEVER,caller=me){let backend=host().backend;return backend[method].call(backend,caller,input,signal)}let platformOf=key=>{let platform=entries[key];if(!platform)throw badRequest(`no sync entry named ${key}`);return platform},keyOf=target=>target.slice(0,target.indexOf(":")),here=key=>host().syncedHere(key),ours=async target=>entries[keyOf(target)]!==void 0&&await here(keyOf(target)),native=external=>external.slice(external.indexOf(":")+1);async function syncOf(thread){try{return await call("syncThread",{thread})}catch(error){if(missing(error))return null;throw error}}async function threadOf(root){try{let{message,replies}=await call("message",{id:root});return[message,...replies]}catch(error){if(missing(error))return[];throw error}}async function messageOf(id){return(await threadOf(id)).find(message=>message.id===id)??null}async function copiesOf(ids){return ids.length===0?{}:(await call("syncCopies",{message:[...new Set(ids)]})).copies}let find=(query,signal)=>call("syncFind",query,signal),principal=null;function principalNow(){if(principal)return principal;let asked=call("me",{}).then(me2=>me2.principal);return principal=asked,asked.catch(()=>{principal===asked&&(principal=null)}),asked}async function actorsNow(){let[{actors},me2]=await Promise.all([call("actors",{}),principalNow().catch(()=>null)]),state={byId:{},principal:me2};for(let actor of actors)state.byId[actor.id]={id:actor.id,kind:actor.kind,handle:actor.handle,name:actor.name,avatar:actor.avatar,...actor.via?{via:{...actor.via}}:{},...actor.platform?{platform:actor.platform}:{},...actor.verified?{verified:!0}:{}};return state}let RETRY_MS=6e4,resolutions=new Map;function resolve(key,name){let at=`${key}:${name}`,cached=resolutions.get(at);if(cached&&(!cached.failed||Date.now()-cached.at<RETRY_MS))return cached.id;let entry={id:platformOf(key).resolveChannel(name),failed:!1,at:Date.now()};return entry.id.catch(error=>{entry.failed=!0;let missing2=channelMissing(error);!missing2&&resolutions.get(at)===entry&&resolutions.delete(at),console.warn(`[board] sync ${key}: ${missing2?"skipping":"couldn't resolve"} ${name}: ${error.message}`)}),resolutions.set(at,entry),entry.id}function channelIn(key,target){if(!isThreadTarget(target))return native(target);try{let channel=platformOf(key).inboxChannel(key,target);return channel===null?null:native(channel)}catch{return null}}let emails=new Map;function emailMention(key,email){let at=`${key}${email.toLowerCase()}`,cached=emails.get(at);if(cached&&Date.now()-cached.at<EMAIL_TTL_MS)return cached.mention;emails.size>=1e3&&emails.clear();let platform=platformOf(key),mention=platform.findByEmail(email).then(user=>user?platform.mention({id:user.id,kind:"external",handle:user.handle,name:user.name,avatar:user.avatar}):null,()=>null);return emails.set(at,{at:Date.now(),mention}),mention}async function normalizeTarget(target){let at=target.indexOf(":");if(at<=0)throw badRequest(`sync targets look like <key>:<channel or thread>, got: ${target}`);let key=target.slice(0,at),platform=platformOf(key);try{let resolved=ResolvedTarget.parse(await platform.resolveTarget(target.slice(at+1)));if(resolved.kind==="channel"&&!platform.canStartThreads)throw new Error(`${platform.platform} cannot start threads; use an existing thread`);return{target:`${key}:${resolved.target}`,kind:resolved.kind}}catch(error){throw badRequest(`can't sync to ${target}: ${error.message}`)}}async function intake(key,received){let{event,raw,dedupe}=ReceivedEvent.parse(storableJson({...received,raw:jsonSafe(received.raw)}));for(let location of[event.channel,event.thread,"subthread"in event?event.subthread:null])if(location!==null&&!location.startsWith(`${key}:`))throw badRequest(`provider locations must belong to sync entry ${key}`);let routes=routesFor(platformOf(key)),kept=routes&&await routes(native(event.channel),name=>resolve(key,name)).catch(async error=>{if(await syncsThread(event.thread))return!0;throw error});routes&&!kept&&!await syncsThread(event.thread)||await call("inboxPush",{key,events:[{id:dedupe,event,raw}]})}async function syncsThread(thread){try{return(await find({thread},AbortSignal.timeout(GATE_WAIT_MS))).thread!==null}catch(error){let name=error?.name;if(name==="TimeoutError"||name==="AbortError")return!0;throw error}}async function handleWebhook(key,request){let platform=entries[key];if(!platform)throw notFound(`no sync entry named ${key}`);if(!await here(key))return new Response(null,{status:200});let response;try{response=await platform.receive(key,request,received=>intake(key,received))}catch(error){return error instanceof HttpError&&error.status===400?(console.error("[board] dropped an event the board refuses",error),new Response(null,{status:200})):(console.error("[board] intake failed",error),new Response("intake failed",{status:500}))}let pulling=pull([key]).catch(error=>console.error(`[board] couldn't pull ${key}'s inbox:`,describe(error)));return waitUntil(pulling),response}async function pull(keys=Object.keys(entries)){let ran=0,until=Date.now()+PULL_MS;for(let key of keys)if(await here(key))for(;Date.now()<until;){let{items}=await call("inboxNext",{key,limit:10});if(items.length===0)break;await Promise.all(items.map(item=>runItem(key,item))),ran+=items.length}return ran}async function runItem(key,item){let error;try{await inbound(key,{event:item.event,raw:item.raw},{id:item.id,attempt:item.attempt+1})}catch(failure){console.error(`[board] sync ${key} couldn't import ${item.id}:`,describe(failure)),error=describe(failure)}await call("inboxAck",{key,id:item.id,lease:item.lease,...error!==void 0?{error}:{}}).catch(failure=>console.error("[board] couldn't ack an inbox event:",describe(failure)))}async function resolveLinks(platform,links,linker,channel,previous=[]){if(links.length===0)return[];let resolved=[];for(let link of links){if(resolved.some(done=>done.url===link.url))continue;let id=(await find({thread:link.thread,message:link.message})).message,copy=id===null?null:await messageOf(id);if(copy&&!copy.deleted&&copy.channel===channel){resolved.push({url:link.url,message:copy.id,unavailable:null,snapshot:{author:copy.author?shownName(copy.author):copy.by.actor,text:copy.text,createdAt:copy.createdAt,files:copy.attachments.map(file=>({name:file.name,url:null}))}});continue}if(link.snapshot){resolved.push({url:link.url,message:null,snapshot:link.snapshot,unavailable:null});continue}let kept=previous.find(earlier=>earlier.url===link.url&&earlier.snapshot&&earlier.message===null);if(kept){resolved.push(kept);continue}let fetched=await platform.fetchLink(link,linker).catch(error=>({snapshot:null,unavailable:describe(error)}));resolved.push({url:link.url,message:null,snapshot:fetched.snapshot,unavailable:fetched.snapshot?null:(fetched.unavailable??"unknown").slice(0,300)})}return storableJson(resolved)}async function importFiles(platform,files,attempt){let attachments=[],notes=[],noFiles=null;for(let file of files.slice(0,10)){if(noFiles!==null){notes.push(fileLink(file,noFiles));continue}if(file.size!==void 0&&file.size>26214400){notes.push(fileNote(file,`over ${26214400/1024/1024} MB`));continue}let data;try{let fetched=await platform.fetchFile(file);if(fetched===null){notes.push(fileNote(file,`${platform.platform} can't hand it over`));continue}data=fetched}catch(error){if(attempt<FILE_ATTEMPTS)throw error;console.warn(`[board] couldn't fetch ${file.name??"a file"} from ${platform.platform}:`,describe(error)),notes.push(fileNote(file,`${platform.platform} wouldn't hand it over`));continue}if(data.byteLength>26214400){notes.push(fileNote(file,`over ${26214400/1024/1024} MB`));continue}if(data.byteLength===0){notes.push(fileNote(file,"it was empty"));continue}let name=file.name??`${file.type}`;try{attachments.push((await call("upload",{data,name,type:file.mimeType||typeOf(name)})).attachment)}catch(error){if(error instanceof HttpError&&(error.code==="too_large"||error.code==="no_direct_uploads")){notes.push(fileNote(file,`over ${4194304/1024/1024} MB`));continue}if(!keepsNoFiles(error))throw error;noFiles=error.message,notes.push(fileLink(file,noFiles))}}for(let file of files.slice(10))notes.push(fileNote(file,"a message carries at most 10"));return{attachments,notes}}async function inbound(key,received,meta){let platform=platformOf(key),item={...received,event:keyedEvent(key,platform.platform,received.event)},{event,raw}=item,linked=(await find({thread:event.thread})).thread??void 0;if(event.kind==="message"){let copied=(await find({thread:event.subthread??event.thread,message:event.message})).message;if(copied!==null){let origin=(await messageOf(copied))?.origin;if(!origin||origin.message!==event.message||(origin.subthread??origin.thread)!==(event.subthread??event.thread))return}}let author="author"in event?event.author:{id:`${key}:system`,handle:platform.platform,name:platform.platform,avatar:null,isBot:!0},typed,typedEvent=()=>typed??=immutable(platform.event({id:meta.id,key,event,raw})),imported,link,active=!0,sync={direction:"in",key,channel:native(event.channel),get event(){return typedEvent()},board:host().client({author,key,...originOf(key,event)},meta.id),import(channel,overrides={}){if(!active)throw badRequest("the sync function has finished");return imported??=importEvent(key,item,meta,linked,channel,overrides),imported},permalink(){let promise=link??platform.permalink(typedEvent());return link=promise,promise.catch(()=>{link===promise&&(link=void 0)}),promise},resolve:name=>resolve(key,name)};try{await platform.sync(sync),await imported}finally{active=!1}}async function importEvent(key,item,meta,linked,channel,overrides){let where=channel??(linked?(await syncOf(linked))?.channel:void 0);if(where===void 0)return{root:null,message:null};try{return await applyIncoming(key,item,meta,ChannelPath.parse(where),SyncOverrides.parse(overrides))}catch(error){if(!(error instanceof DroppedError))throw error;let thread=(await find({thread:item.event.thread})).thread;return{root:thread===null?null:(await syncOf(thread))?.root??null,message:null}}}function originOf(key,event){let platform=platformOf(key),thread=("subthread"in event?event.subthread:null)??event.thread;return{via:{kind:"sync",key,platform:platform.platform,channel:event.channel,thread},respond:async text=>{await platform.post(native(thread),"thread",{markdown:text})}}}async function applyIncoming(key,item,meta,channel,overrides){let{event,raw}=item,source=originOf(key,event),platform=platformOf(key),threadKey=(await find({thread:event.thread})).thread??void 0,synced=threadKey?await syncOf(threadKey):null,rootId=synced?.root,writeId=n=>derivedId("board-inbound",meta.id,String(n)),from={key,channel:source.via.channel,thread:source.via.thread},screened=async answer=>{if(!answer.dropped)return answer.message;for(let text of answer.dropped)await source.respond(text);throw new DroppedError(answer.dropped)},post=async({attachments=[],...input})=>({id:await screened(await call("syncImport",{op:"post",from:key,source:from,...input,origin:input.origin??null,...attachments.length?{attachments:attachments.map(file=>file.id)}:{}})),re:input.re??null}),result=message=>({root:message.re??message.id,message:message.id}),labels=(defaults={})=>{let merged={...defaults,...overrides.labels};for(let key2 of overrides.unset??[])delete merged[key2];return merged},rootDraft=draft=>{if(!overrides.root)return draft;let patch=overrides.root(immutable(structuredClone(draft)));if(patch&&typeof patch=="object"&&"then"in patch)throw badRequest("root overrides must be synchronous");let checked=SyncOverrides.pick({text:!0,labels:!0}).parse(patch);return{...draft,text:checked.text??draft.text,labels:{...draft.labels,...checked.labels}}},setLabels=(author,set,unset)=>call("syncImport",{op:"labels",author,from:key,origin:{thread:event.thread},set,unset}),setExtraLabels=async(author,id)=>{if(!overrides.labels&&!overrides.unset)return;let root=await messageOf(id),set=Object.fromEntries(Object.entries(overrides.labels??{}).filter(([key2,value])=>root?.labels[key2]!==value)),unset=(overrides.unset??[]).filter(key2=>root?.labels[key2]!==void 0);(Object.keys(set).length||unset.length)&&await setLabels(author,set,unset)};switch(event.kind){case"message":{let existing=(await find({thread:event.subthread??event.thread,message:event.message})).message;if(existing!==null)return{root:rootId??existing,message:existing};let{attachments,notes}=event.files?.length?await importFiles(platform,event.files,meta.attempt):{attachments:[],notes:[]},links=await resolveLinks(platform,event.links??[],{thread:event.subthread??event.thread,message:event.message},synced?.channel??channel),base={...links.length?{links}:{},...event.mentioned?.length?{mentioned:event.mentioned}:{},author:event.author,text:clampText(withNotes(overrides.text??event.text,notes),attachments.length>0),...attachments.length?{attachments}:{},origin:{channel:event.channel,thread:event.thread,subthread:event.subthread,message:event.message,context:event.context},id:await writeId(0)},reply={...base,...overrides.noSync?{noSync:!0}:{}};if(rootId!==void 0)return await setExtraLabels(event.author,rootId),result(await post({...reply,re:rootId}));let fetched=await platform.fetchRoot(native(event.thread));if(fetched===null){let draft2=rootDraft({text:event.text,labels:{},author:event.author,raw});return result(await post({...base,channel,text:clampText(withNotes(overrides.text??draft2.text,notes),attachments.length>0),labels:labels(draft2.labels)}))}let draft=rootDraft({...fetched,raw:fetched.raw??null}),root=await post({author:{...fetched.author,id:keyedId(key,platform.platform,fetched.author.id)},channel,text:clampText(draft.text),labels:labels(draft.labels),origin:{channel:event.channel,thread:event.thread,subthread:null,message:`root:${meta.id}`,context:null},id:await writeId(1)});return result(await post({...reply,re:root.id}))}case"edited":case"deleted":case"reaction":{let id=(await find({thread:event.subthread??event.thread,message:event.message})).message;if(id===null)return{root:rootId??null,message:null};let author="author"in event?event.author:{id:`${key}:system`,handle:platform.platform,name:platform.platform,avatar:null,isBot:!0},origin={thread:event.subthread??event.thread,message:event.message};if(rootId!==void 0&&await setExtraLabels(author,rootId),event.kind==="deleted")await call("syncImport",{op:"delete",author,from:key,origin});else if(event.kind==="edited"){let stored=await messageOf(id),text=clampText(withNotes(overrides.text??event.text,stored?notesIn(stored.text):[]),(stored?.attachments.length??0)>0),mentioned=event.mentioned?.length?{mentioned:event.mentioned}:{};stored&&!event.linksOnly&&stored.text!==text&&await screened(await call("syncImport",{op:"edit",author,from:key,origin,text,source:from,...mentioned}));let links=stored?await resolveLinks(platform,event.links??[],origin,stored.channel,stored.links):[];stored&&!sameLinks(links,stored.links)&&await call("syncImport",{op:"links",author,from:key,origin,links})}else{if(platform.singleReaction){let emoji=canonicalEmoji(event.emoji),as=new Set([author.id,`${await principalNow()}+${author.id}`]);for(let[held,actors]of Object.entries((await messageOf(id))?.reactions??{}))actors.some(actor=>as.has(actor))&&!(event.added&&held===emoji)&&await call("syncImport",{op:"react",author,from:key,origin,emoji:held,remove:!0})}(!platform.singleReaction||event.added)&&await call("syncImport",{op:"react",author,from:key,origin,emoji:event.emoji,remove:!event.added})}return{root:rootId??null,message:id}}case"lifecycle":{if(rootId!==void 0){let root2=await messageOf(rootId),createdHere=root2?.origin?.message===`lifecycle:${meta.id}`,desired=labels((createdHere?rootDraft({text:lifecycleText(event),labels:event.labels,author:event.author,raw}):null)?.labels??event.labels),owned=key2=>event.owns?.some(prefix=>key2.startsWith(prefix))??!1,set=Object.fromEntries(Object.entries(desired).filter(([key2,value])=>root2?.labels[key2]!==value)),unset=Object.keys(root2?.labels??{}).filter(key2=>!(key2 in desired)&&(event.unset.includes(key2)||overrides.unset?.includes(key2)||owned(key2)));if(root2&&!root2.deleted&&(Object.keys(set).length||unset.length)&&await setLabels(event.author,set,unset),event.retitled&&root2&&!root2.deleted&&root2.from===key&&root2.origin?.thread===event.thread){let text=clampText(overrides.text??rootDraft({text:lifecycleText(event),labels:root2.labels,author:event.author,raw}).text);root2.text!==text&&await screened(await call("syncImport",{op:"edit",author:event.author,from:key,origin:{thread:root2.origin.thread,message:root2.origin.message},text}))}return event.reply?result(await post({author:event.author,re:rootId,text:clampText(overrides.text??event.reply),...overrides.noSync?{noSync:!0}:{},id:await writeId(1)})):{root:rootId,message:createdHere?rootId:null}}if(!event.createRoot)return{root:null,message:null};let draft=rootDraft({text:lifecycleText(event),labels:event.labels,author:event.author,raw}),root=await post({author:event.author,channel,text:clampText(event.reply?draft.text:overrides.text??draft.text),labels:labels(draft.labels),origin:{channel:event.channel,thread:event.thread,subthread:null,message:`lifecycle:${meta.id}`,context:null},id:await writeId(0)});return event.reply?result(await post({author:event.author,re:root.id,text:clampText(overrides.text??event.reply),...overrides.noSync?{noSync:!0}:{},id:await writeId(1)})):result(root)}}}async function textFor(key,actors,text){let exact=extractMentions(text).flatMap(token=>token.kind==="actor"?[token.actor]:[]);if(exact.length===0)return text;let found=new Map,asked=0;for(let named of exact)actors.byId[named]||!isEmail(named)||found.has(named)||found.set(named,asked++<EMAIL_LOOKUPS_PER_MESSAGE_MAX?await emailMention(key,named):null);return replaceMentions(text,token=>{if(token.kind==="handle")return null;if(found.has(token.actor))return found.get(token.actor)??token.actor;let actor=actorNamed(token.actor,actors);return actor?nativeMention(key,actor.id,actors)??actor.name:unmetMention(key,token.actor,actors)})}function unmetMention(key,id,actors){let user=userOf(key,id,actors);if(user===null)return null;let platform=platformOf(key);return platform.mentionById(`${platform.platform}:${user}`)}function actorNamed(id,actors){return actors.byId[id]??(actors.principal?actors.byId[`${actors.principal}+${id}`]:void 0)??null}function userOf(key,actor,actors){let{principal:principal2,profile}=actorParts(actor),id=profile===null?actor:platformProfile(profile)!==null&&principal2===actors.principal?profile:null;return id?.startsWith(`${key}:`)?id.slice(key.length+1):null}function nativeMention(key,actor,actors){let account=actors.byId[actor],user=account?userOf(key,actor,actors):null;if(user===null)return null;let platform=platformOf(key);return platform.mention({...account,id:`${platform.platform}:${user}`})}async function render(key,target,message,actors,renderer){let actor=actors.byId[message.by.actor],own=actor?.name??message.by.actor,after=`${actor?.via?` ${viaText(actor.via)}`:""}${message.from?` (${actor?.platform??entries[message.from]?.platform??message.from})`:""}`,environment=actor?.kind==="deployment"&&!actor.via?/(?:@[^@/]+| \([^()]+\))$/.exec(own)?.[0]??"":"",name=`${own}${after}`,attribution=`${environment}${after}`,platform=platformOf(key),bot=byVercelBot(message,actor),body=(renderer??(input=>platform.render(input)))(immutable({message:{...structuredClone(message),text:displayText(message.text,bot)},author:actor?{...actor}:null,mentionOf:id=>nativeMention(key,id,actors),label:name,target}));if(typeof body!="string")throw badRequest("a provider renderer must return markdown");let labeled=`**${name}**: `,markdown=await textFor(key,actors,body.startsWith(labeled)&&opensBlock(body.slice(labeled.length))?`**${name}**:
11
+ `).filter(line=>/^📎 .* didn't come over: /u.test(line)),linkKey=link=>JSON.stringify([link.url,link.message,link.snapshot,link.unavailable]),sameLinks=(a,b)=>a.length===b.length&&a.every((link,i)=>linkKey(link)===linkKey(b[i])),FILE_ATTEMPTS=3,EMAIL_TTL_MS=3e5,EMAIL_LOOKUPS_PER_MESSAGE_MAX=10,GATE_WAIT_MS=2e3,DELIVERY_ATTEMPTS=5,PULL_MS=24e4,NEVER=new AbortController().signal,jsonSafe=value=>{try{return JSON.parse(JSON.stringify(value??null))}catch{return null}},storableJson=value=>typeof value=="string"?toStorable(value):Array.isArray(value)?value.map(storableJson):value!==null&&typeof value=="object"?Object.fromEntries(Object.entries(value).map(([key,item])=>[toStorable(key),storableJson(item)])):value,describe=error=>{let code=error?.data?.error,text=typeof code=="string"?code:error instanceof Error?error.message:String(error);return toStorable(text.slice(0,500))||"unknown error"},missing=error=>error instanceof HttpError&&error.status===404;function keyedId(key,platform,id){return id.startsWith(`${key}:`)?id:`${key}:${id.startsWith(`${platform}:`)?id.slice(platform.length+1):id}`}function keyedText(key,platform,text){return key===platform?text:replaceMentions(text,token=>token.kind==="actor"&&token.actor.startsWith(`${platform}:`)?`@[${keyedId(key,platform,token.actor)}]`:null)}function keyedEvent(key,platform,event){if(!("author"in event))return event;let author={...event.author,id:keyedId(key,platform,event.author.id)};return event.kind!=="message"&&event.kind!=="edited"||key===platform?{...event,author}:{...event,author,...event.mentioned?{mentioned:event.mentioned.map(user=>({...user,id:keyedId(key,platform,user.id)}))}:{},text:keyedText(key,platform,event.text)}}function createSyncEngine(entries){let bound=null,host=()=>{if(!bound)throw new Error("sync used before board() bound it");return bound},me={self:"sync",origin:{via:{kind:"engine"}}};function call(method,input,signal=NEVER,caller=me){let backend=host().backend;return backend[method].call(backend,caller,input,signal)}let platformOf=key=>{let platform=entries[key];if(!platform)throw badRequest(`no sync entry named ${key}`);return platform},keyOf=target=>target.slice(0,target.indexOf(":")),here=key=>host().syncedHere(key),ours=async target=>entries[keyOf(target)]!==void 0&&await here(keyOf(target)),native=external=>external.slice(external.indexOf(":")+1);async function syncOf(thread){try{return await call("syncThread",{thread})}catch(error){if(missing(error))return null;throw error}}async function threadOf(root){try{let{message,replies}=await call("message",{id:root});return[message,...replies]}catch(error){if(missing(error))return[];throw error}}async function messageOf(id){return(await threadOf(id)).find(message=>message.id===id)??null}async function copiesOf(ids){return ids.length===0?{}:(await call("syncCopies",{message:[...new Set(ids)]})).copies}let find=(query,signal)=>call("syncFind",query,signal),principal=null;function principalNow(){if(principal)return principal;let asked=call("me",{}).then(me2=>me2.principal);return principal=asked,asked.catch(()=>{principal===asked&&(principal=null)}),asked}async function actorsNow(){let[{actors},me2]=await Promise.all([call("actors",{}),principalNow().catch(()=>null)]),state={byId:{},principal:me2};for(let actor of actors)state.byId[actor.id]={id:actor.id,kind:actor.kind,handle:actor.handle,name:actor.name,avatar:actor.avatar,...actor.via?{via:{...actor.via}}:{},...actor.platform?{platform:actor.platform}:{},...actor.verified?{verified:!0}:{}};return state}let RETRY_MS=6e4,resolutions=new Map;function resolve(key,name){let at=`${key}:${name}`,cached=resolutions.get(at);if(cached&&(!cached.failed||Date.now()-cached.at<RETRY_MS))return cached.id;let entry={id:platformOf(key).resolveChannel(name),failed:!1,at:Date.now()};return entry.id.catch(error=>{entry.failed=!0;let missing2=channelMissing(error);!missing2&&resolutions.get(at)===entry&&resolutions.delete(at),console.warn(`[board] sync ${key}: ${missing2?"skipping":"couldn't resolve"} ${name}: ${error.message}`)}),resolutions.set(at,entry),entry.id}function channelIn(key,target){if(!isThreadTarget(target))return native(target);try{let channel=platformOf(key).inboxChannel(key,target);return channel===null?null:native(channel)}catch{return null}}let emails=new Map;function emailMention(key,email){let at=`${key}${email.toLowerCase()}`,cached=emails.get(at);if(cached&&Date.now()-cached.at<EMAIL_TTL_MS)return cached.mention;emails.size>=1e3&&emails.clear();let platform=platformOf(key),mention=platform.findByEmail(email).then(user=>user?platform.mention({id:user.id,kind:"external",handle:user.handle,name:user.name,avatar:user.avatar}):null,()=>null);return emails.set(at,{at:Date.now(),mention}),mention}async function normalizeTarget(target){let at=target.indexOf(":");if(at<=0)throw badRequest(`sync targets look like <key>:<channel or thread>, got: ${target}`);let key=target.slice(0,at),platform=platformOf(key);try{let resolved=ResolvedTarget.parse(await platform.resolveTarget(target.slice(at+1)));if(resolved.kind==="channel"&&!platform.canStartThreads)throw new Error(`${platform.platform} cannot start threads; use an existing thread`);return{target:`${key}:${resolved.target}`,kind:resolved.kind}}catch(error){throw badRequest(`can't sync to ${target}: ${error.message}`)}}async function intake(key,received){let{event,raw,dedupe}=ReceivedEvent.parse(storableJson({...received,raw:jsonSafe(received.raw)}));for(let location of[event.channel,event.thread,"subthread"in event?event.subthread:null])if(location!==null&&!location.startsWith(`${key}:`))throw badRequest(`provider locations must belong to sync entry ${key}`);let routes=routesFor(platformOf(key)),kept=routes&&await routes(native(event.channel),name=>resolve(key,name)).catch(async error=>{if(await syncsThread(event.thread))return!0;throw error});routes&&!kept&&!await syncsThread(event.thread)||await call("inboxPush",{key,events:[{id:dedupe,event,raw}]})}async function syncsThread(thread){try{return(await find({thread},AbortSignal.timeout(GATE_WAIT_MS))).thread!==null}catch(error){let name=error?.name;if(name==="TimeoutError"||name==="AbortError")return!0;throw error}}async function handleWebhook(key,request){let platform=entries[key];if(!platform)throw notFound(`no sync entry named ${key}`);if(!await here(key))return new Response(null,{status:200});let response;try{response=await platform.receive(key,request,received=>intake(key,received))}catch(error){return error instanceof HttpError&&error.status===400?(console.error("[board] dropped an event the board refuses",error),new Response(null,{status:200})):(console.error("[board] intake failed",error),new Response("intake failed",{status:500}))}let pulling=pull([key]).catch(error=>console.error(`[board] couldn't pull ${key}'s inbox:`,describe(error)));return waitUntil(pulling),response}async function pull(keys=Object.keys(entries)){let ran=0,until=Date.now()+PULL_MS;for(let key of keys)if(await here(key))for(;Date.now()<until;){let{items}=await call("inboxNext",{key,limit:10});if(items.length===0)break;await Promise.all(items.map(item=>runItem(key,item))),ran+=items.length}return ran}async function runItem(key,item){let error;try{await inbound(key,{event:item.event,raw:item.raw},{id:item.id,attempt:item.attempt+1})}catch(failure){console.error(`[board] sync ${key} couldn't import ${item.id}:`,describe(failure)),error=describe(failure)}await call("inboxAck",{key,id:item.id,lease:item.lease,...error!==void 0?{error}:{}}).catch(failure=>console.error("[board] couldn't ack an inbox event:",describe(failure)))}async function resolveLinks(platform,links,linker,channel,previous=[]){if(links.length===0)return[];let resolved=[];for(let link of links){if(resolved.some(done=>done.url===link.url))continue;let id=(await find({thread:link.thread,message:link.message})).message,copy=id===null?null:await messageOf(id);if(copy&&!copy.deleted&&copy.channel===channel){resolved.push({url:link.url,message:copy.id,unavailable:null,snapshot:{author:copy.author?shownName(copy.author):copy.by.actor,text:copy.text,createdAt:copy.createdAt,files:copy.attachments.map(file=>({name:file.name,url:null}))}});continue}if(link.snapshot){resolved.push({url:link.url,message:null,snapshot:link.snapshot,unavailable:null});continue}let kept=previous.find(earlier=>earlier.url===link.url&&earlier.snapshot&&earlier.message===null);if(kept){resolved.push(kept);continue}let fetched=await platform.fetchLink(link,linker).catch(error=>({snapshot:null,unavailable:describe(error)}));resolved.push({url:link.url,message:null,snapshot:fetched.snapshot,unavailable:fetched.snapshot?null:(fetched.unavailable??"unknown").slice(0,300)})}return storableJson(resolved)}async function importFiles(platform,files,attempt){let attachments=[],notes=[],noFiles=null;for(let file of files.slice(0,10)){if(noFiles!==null){notes.push(fileLink(file,noFiles));continue}if(file.size!==void 0&&file.size>26214400){notes.push(fileNote(file,`over ${26214400/1024/1024} MB`));continue}let data;try{let fetched=await platform.fetchFile(file);if(fetched===null){notes.push(fileNote(file,`${platform.platform} can't hand it over`));continue}data=fetched}catch(error){if(attempt<FILE_ATTEMPTS)throw error;console.warn(`[board] couldn't fetch ${file.name??"a file"} from ${platform.platform}:`,describe(error)),notes.push(fileNote(file,`${platform.platform} wouldn't hand it over`));continue}if(data.byteLength>26214400){notes.push(fileNote(file,`over ${26214400/1024/1024} MB`));continue}if(data.byteLength===0){notes.push(fileNote(file,"it was empty"));continue}let name=importedFileName(file.name??`${file.type}`);try{attachments.push((await call("upload",{data,name,type:file.mimeType||typeOf(name)})).attachment)}catch(error){if(error instanceof HttpError&&(error.code==="too_large"||error.code==="no_direct_uploads")){notes.push(fileNote(file,`over ${4194304/1024/1024} MB`));continue}if(!keepsNoFiles(error))throw error;noFiles=error.message,notes.push(fileLink(file,noFiles))}}for(let file of files.slice(10))notes.push(fileNote(file,"a message carries at most 10"));return{attachments,notes}}async function inbound(key,received,meta){let platform=platformOf(key),item={...received,event:keyedEvent(key,platform.platform,received.event)},{event,raw}=item,linked=(await find({thread:event.thread})).thread??void 0;if(event.kind==="message"){let copied=(await find({thread:event.subthread??event.thread,message:event.message})).message;if(copied!==null){let origin=(await messageOf(copied))?.origin;if(!origin||origin.message!==event.message||(origin.subthread??origin.thread)!==(event.subthread??event.thread))return}}let author="author"in event?event.author:{id:`${key}:system`,handle:platform.platform,name:platform.platform,avatar:null,isBot:!0},typed,typedEvent=()=>typed??=immutable(platform.event({id:meta.id,key,event,raw})),imported,link,active=!0,sync={direction:"in",key,channel:native(event.channel),get event(){return typedEvent()},board:host().client({author,key,...originOf(key,event)},meta.id),import(channel,overrides={}){if(!active)throw badRequest("the sync function has finished");return imported??=importEvent(key,item,meta,linked,channel,overrides),imported},permalink(){let promise=link??platform.permalink(typedEvent());return link=promise,promise.catch(()=>{link===promise&&(link=void 0)}),promise},resolve:name=>resolve(key,name)};try{await platform.sync(sync),await imported}finally{active=!1}}async function importEvent(key,item,meta,linked,channel,overrides){let where=channel??(linked?(await syncOf(linked))?.channel:void 0);if(where===void 0)return{root:null,message:null};try{return await applyIncoming(key,item,meta,ChannelPath.parse(where),SyncOverrides.parse(overrides))}catch(error){if(!(error instanceof DroppedError))throw error;let thread=(await find({thread:item.event.thread})).thread;return{root:thread===null?null:(await syncOf(thread))?.root??null,message:null}}}function originOf(key,event){let platform=platformOf(key),thread=("subthread"in event?event.subthread:null)??event.thread;return{via:{kind:"sync",key,platform:platform.platform,channel:event.channel,thread},respond:async text=>{await platform.post(native(thread),"thread",{markdown:text})}}}async function applyIncoming(key,item,meta,channel,overrides){let{event,raw}=item,source=originOf(key,event),platform=platformOf(key),threadKey=(await find({thread:event.thread})).thread??void 0,synced=threadKey?await syncOf(threadKey):null,rootId=synced?.root,writeId=n=>derivedId("board-inbound",meta.id,String(n)),from={key,channel:source.via.channel,thread:source.via.thread},screened=async answer=>{if(!answer.dropped)return answer.message;for(let text of answer.dropped)await source.respond(text);throw new DroppedError(answer.dropped)},post=async({attachments=[],...input})=>({id:await screened(await call("syncImport",{op:"post",from:key,source:from,...input,origin:input.origin??null,...attachments.length?{attachments:attachments.map(file=>file.id)}:{}})),re:input.re??null}),result=message=>({root:message.re??message.id,message:message.id}),labels=(defaults={})=>{let merged={...defaults,...overrides.labels};for(let key2 of overrides.unset??[])delete merged[key2];return merged},rootDraft=draft=>{if(!overrides.root)return draft;let patch=overrides.root(immutable(structuredClone(draft)));if(patch&&typeof patch=="object"&&"then"in patch)throw badRequest("root overrides must be synchronous");let checked=SyncOverrides.pick({text:!0,labels:!0}).parse(patch);return{...draft,text:checked.text??draft.text,labels:{...draft.labels,...checked.labels}}},setLabels=(author,set,unset)=>call("syncImport",{op:"labels",author,from:key,origin:{thread:event.thread},set,unset}),setExtraLabels=async(author,id)=>{if(!overrides.labels&&!overrides.unset)return;let root=await messageOf(id),set=Object.fromEntries(Object.entries(overrides.labels??{}).filter(([key2,value])=>root?.labels[key2]!==value)),unset=(overrides.unset??[]).filter(key2=>root?.labels[key2]!==void 0);(Object.keys(set).length||unset.length)&&await setLabels(author,set,unset)};switch(event.kind){case"message":{let existing=(await find({thread:event.subthread??event.thread,message:event.message})).message;if(existing!==null)return{root:rootId??existing,message:existing};let{attachments,notes}=event.files?.length?await importFiles(platform,event.files,meta.attempt):{attachments:[],notes:[]},links=await resolveLinks(platform,event.links??[],{thread:event.subthread??event.thread,message:event.message},synced?.channel??channel),base={...links.length?{links}:{},...event.mentioned?.length?{mentioned:event.mentioned}:{},author:event.author,text:clampText(withNotes(overrides.text??event.text,notes),attachments.length>0),...attachments.length?{attachments}:{},origin:{channel:event.channel,thread:event.thread,subthread:event.subthread,message:event.message,context:event.context},id:await writeId(0)},reply={...base,...overrides.noSync?{noSync:!0}:{}};if(rootId!==void 0)return await setExtraLabels(event.author,rootId),result(await post({...reply,re:rootId}));let fetched=await platform.fetchRoot(native(event.thread));if(fetched===null){let draft2=rootDraft({text:event.text,labels:{},author:event.author,raw});return result(await post({...base,channel,text:clampText(withNotes(overrides.text??draft2.text,notes),attachments.length>0),labels:labels(draft2.labels)}))}let draft=rootDraft({...fetched,raw:fetched.raw??null}),root=await post({author:{...fetched.author,id:keyedId(key,platform.platform,fetched.author.id)},channel,text:clampText(draft.text),labels:labels(draft.labels),origin:{channel:event.channel,thread:event.thread,subthread:null,message:`root:${meta.id}`,context:null},id:await writeId(1)});return result(await post({...reply,re:root.id}))}case"edited":case"deleted":case"reaction":{let id=(await find({thread:event.subthread??event.thread,message:event.message})).message;if(id===null)return{root:rootId??null,message:null};let author="author"in event?event.author:{id:`${key}:system`,handle:platform.platform,name:platform.platform,avatar:null,isBot:!0},origin={thread:event.subthread??event.thread,message:event.message};if(rootId!==void 0&&await setExtraLabels(author,rootId),event.kind==="deleted")await call("syncImport",{op:"delete",author,from:key,origin});else if(event.kind==="edited"){let stored=await messageOf(id),text=clampText(withNotes(overrides.text??event.text,stored?notesIn(stored.text):[]),(stored?.attachments.length??0)>0),mentioned=event.mentioned?.length?{mentioned:event.mentioned}:{};stored&&!event.linksOnly&&stored.text!==text&&await screened(await call("syncImport",{op:"edit",author,from:key,origin,text,source:from,...mentioned}));let links=stored?await resolveLinks(platform,event.links??[],origin,stored.channel,stored.links):[];stored&&!sameLinks(links,stored.links)&&await call("syncImport",{op:"links",author,from:key,origin,links})}else{if(platform.singleReaction){let emoji=canonicalEmoji(event.emoji),as=new Set([author.id,`${await principalNow()}+${author.id}`]);for(let[held,actors]of Object.entries((await messageOf(id))?.reactions??{}))actors.some(actor=>as.has(actor))&&!(event.added&&held===emoji)&&await call("syncImport",{op:"react",author,from:key,origin,emoji:held,remove:!0})}(!platform.singleReaction||event.added)&&await call("syncImport",{op:"react",author,from:key,origin,emoji:event.emoji,remove:!event.added})}return{root:rootId??null,message:id}}case"lifecycle":{if(rootId!==void 0){let root2=await messageOf(rootId),createdHere=root2?.origin?.message===`lifecycle:${meta.id}`,desired=labels((createdHere?rootDraft({text:lifecycleText(event),labels:event.labels,author:event.author,raw}):null)?.labels??event.labels),owned=key2=>event.owns?.some(prefix=>key2.startsWith(prefix))??!1,set=Object.fromEntries(Object.entries(desired).filter(([key2,value])=>root2?.labels[key2]!==value)),unset=Object.keys(root2?.labels??{}).filter(key2=>!(key2 in desired)&&(event.unset.includes(key2)||overrides.unset?.includes(key2)||owned(key2)));if(root2&&!root2.deleted&&(Object.keys(set).length||unset.length)&&await setLabels(event.author,set,unset),event.retitled&&root2&&!root2.deleted&&root2.from===key&&root2.origin?.thread===event.thread){let text=clampText(overrides.text??rootDraft({text:lifecycleText(event),labels:root2.labels,author:event.author,raw}).text);root2.text!==text&&await screened(await call("syncImport",{op:"edit",author:event.author,from:key,origin:{thread:root2.origin.thread,message:root2.origin.message},text}))}return event.reply?result(await post({author:event.author,re:rootId,text:clampText(overrides.text??event.reply),...overrides.noSync?{noSync:!0}:{},id:await writeId(1)})):{root:rootId,message:createdHere?rootId:null}}if(!event.createRoot)return{root:null,message:null};let draft=rootDraft({text:lifecycleText(event),labels:event.labels,author:event.author,raw}),root=await post({author:event.author,channel,text:clampText(event.reply?draft.text:overrides.text??draft.text),labels:labels(draft.labels),origin:{channel:event.channel,thread:event.thread,subthread:null,message:`lifecycle:${meta.id}`,context:null},id:await writeId(0)});return event.reply?result(await post({author:event.author,re:root.id,text:clampText(overrides.text??event.reply),...overrides.noSync?{noSync:!0}:{},id:await writeId(1)})):result(root)}}}async function textFor(key,actors,text){let exact=extractMentions(text).flatMap(token=>token.kind==="actor"?[token.actor]:[]);if(exact.length===0)return text;let found=new Map,asked=0;for(let named of exact)actors.byId[named]||!isEmail(named)||found.has(named)||found.set(named,asked++<EMAIL_LOOKUPS_PER_MESSAGE_MAX?await emailMention(key,named):null);return replaceMentions(text,token=>{if(token.kind==="handle")return null;if(found.has(token.actor))return found.get(token.actor)??token.actor;let actor=actorNamed(token.actor,actors);return actor?nativeMention(key,actor.id,actors)??actor.name:unmetMention(key,token.actor,actors)})}function unmetMention(key,id,actors){let user=userOf(key,id,actors);if(user===null)return null;let platform=platformOf(key);return platform.mentionById(`${platform.platform}:${user}`)}function actorNamed(id,actors){return actors.byId[id]??(actors.principal?actors.byId[`${actors.principal}+${id}`]:void 0)??null}function userOf(key,actor,actors){let{principal:principal2,profile}=actorParts(actor),id=profile===null?actor:platformProfile(profile)!==null&&principal2===actors.principal?profile:null;return id?.startsWith(`${key}:`)?id.slice(key.length+1):null}function nativeMention(key,actor,actors){let account=actors.byId[actor],user=account?userOf(key,actor,actors):null;if(user===null)return null;let platform=platformOf(key);return platform.mention({...account,id:`${platform.platform}:${user}`})}async function render(key,target,message,actors,renderer){let actor=actors.byId[message.by.actor],own=actor?.name??message.by.actor,after=`${actor?.via?` ${viaText(actor.via)}`:""}${message.from?` (${actor?.platform??entries[message.from]?.platform??message.from})`:""}`,environment=actor?.kind==="deployment"&&!actor.via?/(?:@[^@/]+| \([^()]+\))$/.exec(own)?.[0]??"":"",name=`${own}${after}`,attribution=`${environment}${after}`,platform=platformOf(key),bot=byVercelBot(message,actor),body=(renderer??(input=>platform.render(input)))(immutable({message:{...structuredClone(message),text:displayText(message.text,bot)},author:actor?{...actor}:null,mentionOf:id=>nativeMention(key,id,actors),label:name,target}));if(typeof body!="string")throw badRequest("a provider renderer must return markdown");let labeled=`**${name}**: `,markdown=await textFor(key,actors,body.startsWith(labeled)&&opensBlock(body.slice(labeled.length))?`**${name}**:
12
12
 
13
13
  ${body.slice(labeled.length)}`:body),deployments=bot?vercelDeployments(message.text):null;return{markdown,...actor?.verified?{as:{name,avatar:senderAvatar(message,actor),attribution}}:{},...deployments?{deployments}:{}}}function senderAvatar(message,actor){let builtIn=avatar=>!avatar||/\/avatars\/[a-z0-9-]+$/.test(avatar),own=actor?.avatar??null;if(!builtIn(own))return own;let username=actor?.handle.split("/")[0]??"",id=message.by.principal.slice(12);return!message.by.principal.startsWith("vercel:user:")||!username||/^user-/.test(username)||username.toLowerCase()===id.toLowerCase()?own:`https://vercel.com/api/www/avatar?u=${encodeURIComponent(username)}&s=64&format=png`}let attachmentNotes=message=>message.attachments.map(a=>`
14
14
  \u{1F4CE} ${a.name} (${fileSize(a.size)}, on the board: #${message.id})`).join(""),renderFor=async(target,message,actors,noted=!1,renderer)=>{let key=keyOf(target),{markdown,...rest}=await render(key,target,message,actors,renderer);return{markdown:message.attachments.length>0&&(noted||!platformOf(key).uploadsFiles)?`${markdown}
@@ -4,4 +4,4 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{getInvalidSubcommand}from"./chunk-TG2RCYTH.js";import{getSubcommand}from"./chunk-ETV3C2CV.js";import{getCommandAliases}from"./chunk-6U7TRWBO.js";import"./chunk-QOLGACFD.js";import"./chunk-DDPH26ZO.js";import"./chunk-PIDEH4SJ.js";import"./chunk-IIK6GUVI.js";import"./chunk-C35SG42R.js";import"./chunk-2GBU6ULJ.js";import"./chunk-EJLYDHT7.js";import"./chunk-DOBV3XLO.js";import"./chunk-UFCL2VBD.js";import"./chunk-BMIYC2MH.js";import"./chunk-6CJFPT4F.js";import"./chunk-ZZD5W5KT.js";import{imageRmSubcommand}from"./chunk-VHSAI6FS.js";import"./chunk-F7L5SXJM.js";import"./chunk-GLCSWIB4.js";import"./chunk-XECELSF5.js";import"./chunk-6FYPSSL4.js";import"./chunk-UQZZX2J7.js";import"./chunk-UDZJCD5W.js";import"./chunk-5ZCSFPWG.js";import"./chunk-PY4WWD6Z.js";import"./chunk-XDYVJWGX.js";import"./chunk-JALVF3C2.js";import"./chunk-BPIGFKNN.js";import"./chunk-AB4WXRCO.js";import"./chunk-SYJXONEV.js";import"./chunk-KK5C7HVP.js";import"./chunk-7KCRYDGK.js";import"./chunk-GLIQ4KNY.js";import{AGENT_REASON,buildCommandWithGlobalFlags,outputAgentError}from"./chunk-PNWRO3XW.js";import"./chunk-DTUEHPME.js";import"./chunk-2VBFQZ72.js";import{warnDeprecatedSubcommand}from"./chunk-6GKP6VUF.js";import"./chunk-GOI2VVI7.js";import"./chunk-B4KA3ZH2.js";import"./chunk-BOJDM3O7.js";import{output_manager_default}from"./chunk-AP6DZGTK.js";import"./chunk-BLUPZPAS.js";import"./chunk-5MDNVAE6.js";import"./chunk-MCYG7CCE.js";import"./chunk-YHPPP3SF.js";import"./chunk-24SIHFEW.js";import"./chunk-CFJBDBYH.js";import"./chunk-2BKALEOP.js";import"./chunk-NB2WLB3J.js";import"./chunk-ISWW3DKF.js";import"./chunk-BRQUZ5NC.js";import"./chunk-BULSRTQE.js";import"./chunk-BZENIQ7N.js";var IMAGE_CONFIG={ls:["ls","list"],inspect:["inspect","get"],delete:getCommandAliases(imageRmSubcommand)};async function image(client,argv,telemetry){let{subcommand,args,subcommandOriginal}=getSubcommand(argv,IMAGE_CONFIG);if(subcommand==null){let message=argv.length===0?getInvalidSubcommand(IMAGE_CONFIG):`Unknown "vcr image" subcommand "${argv[0]}".`;return outputAgentError(client,{status:"error",reason:AGENT_REASON.INVALID_ARGUMENTS,message,next:[{command:buildCommandWithGlobalFlags(client.argv,"vcr image --help"),when:"Show valid image subcommands"}]},2),output_manager_default.error(`${message} Run \`vercel vcr image --help\`.`),2}switch(subcommand){case"ls":return(await import("./ls-ZW2V7TME.js")).default(client,args,telemetry);case"inspect":return subcommandOriginal==="get"&&warnDeprecatedSubcommand(client,"vcr image get","vcr image inspect"),(await import("./inspect-73R4TFWK.js")).default(client,args,telemetry);case"delete":return subcommandOriginal==="remove"&&warnDeprecatedSubcommand(client,"vcr image remove","vcr image delete"),(await import("./rm-PO6GFUKD.js")).default(client,args,telemetry);default:return output_manager_default.error(`Unhandled image subcommand: ${subcommand}`),1}}export{image as default};
7
+ import{getInvalidSubcommand}from"./chunk-TG2RCYTH.js";import{getSubcommand}from"./chunk-ETV3C2CV.js";import{getCommandAliases}from"./chunk-HVFGIJ44.js";import"./chunk-QOLGACFD.js";import"./chunk-DDPH26ZO.js";import"./chunk-PIDEH4SJ.js";import"./chunk-IIK6GUVI.js";import"./chunk-C35SG42R.js";import"./chunk-2GBU6ULJ.js";import"./chunk-EJLYDHT7.js";import"./chunk-DOBV3XLO.js";import"./chunk-TUB3APDV.js";import"./chunk-BMIYC2MH.js";import"./chunk-6CJFPT4F.js";import"./chunk-ZZD5W5KT.js";import{imageRmSubcommand}from"./chunk-VHSAI6FS.js";import"./chunk-F7L5SXJM.js";import"./chunk-GLCSWIB4.js";import"./chunk-XECELSF5.js";import"./chunk-6FYPSSL4.js";import"./chunk-UQZZX2J7.js";import"./chunk-UDZJCD5W.js";import"./chunk-5ZCSFPWG.js";import"./chunk-PY4WWD6Z.js";import"./chunk-XDYVJWGX.js";import"./chunk-JALVF3C2.js";import"./chunk-BPIGFKNN.js";import"./chunk-AB4WXRCO.js";import"./chunk-SYJXONEV.js";import"./chunk-KK5C7HVP.js";import"./chunk-7KCRYDGK.js";import"./chunk-GLIQ4KNY.js";import{AGENT_REASON,buildCommandWithGlobalFlags,outputAgentError}from"./chunk-PNWRO3XW.js";import"./chunk-DTUEHPME.js";import"./chunk-2VBFQZ72.js";import{warnDeprecatedSubcommand}from"./chunk-6GKP6VUF.js";import"./chunk-GOI2VVI7.js";import"./chunk-B4KA3ZH2.js";import"./chunk-BOJDM3O7.js";import{output_manager_default}from"./chunk-AP6DZGTK.js";import"./chunk-BLUPZPAS.js";import"./chunk-5MDNVAE6.js";import"./chunk-MCYG7CCE.js";import"./chunk-YHPPP3SF.js";import"./chunk-24SIHFEW.js";import"./chunk-CFJBDBYH.js";import"./chunk-2BKALEOP.js";import"./chunk-NB2WLB3J.js";import"./chunk-ISWW3DKF.js";import"./chunk-BRQUZ5NC.js";import"./chunk-BULSRTQE.js";import"./chunk-BZENIQ7N.js";var IMAGE_CONFIG={ls:["ls","list"],inspect:["inspect","get"],delete:getCommandAliases(imageRmSubcommand)};async function image(client,argv,telemetry){let{subcommand,args,subcommandOriginal}=getSubcommand(argv,IMAGE_CONFIG);if(subcommand==null){let message=argv.length===0?getInvalidSubcommand(IMAGE_CONFIG):`Unknown "vcr image" subcommand "${argv[0]}".`;return outputAgentError(client,{status:"error",reason:AGENT_REASON.INVALID_ARGUMENTS,message,next:[{command:buildCommandWithGlobalFlags(client.argv,"vcr image --help"),when:"Show valid image subcommands"}]},2),output_manager_default.error(`${message} Run \`vercel vcr image --help\`.`),2}switch(subcommand){case"ls":return(await import("./ls-ZW2V7TME.js")).default(client,args,telemetry);case"inspect":return subcommandOriginal==="get"&&warnDeprecatedSubcommand(client,"vcr image get","vcr image inspect"),(await import("./inspect-73R4TFWK.js")).default(client,args,telemetry);case"delete":return subcommandOriginal==="remove"&&warnDeprecatedSubcommand(client,"vcr image remove","vcr image delete"),(await import("./rm-PO6GFUKD.js")).default(client,args,telemetry);default:return output_manager_default.error(`Unhandled image subcommand: ${subcommand}`),1}}export{image as default};
@@ -0,0 +1,8 @@
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ import { fileURLToPath as __fileURLToPath } from 'node:url';
3
+ import { dirname as __dirname_ } from 'node:path';
4
+ const require = __createRequire(import.meta.url);
5
+ const __filename = __fileURLToPath(import.meta.url);
6
+ const __dirname = __dirname_(__filename);
7
+ import{TOKENS,VERCEL_ISSUER,createRemoteJWKSet,decodeJwt,issuerName,jwtVerify,markVerified,privateHost,subFits,trustedIssuers}from"./chunk-VKVH7LHB.js";import{unauthorized}from"./chunk-KMTHGHJV.js";import"./chunk-2AMO2VMV.js";import"./chunk-BZENIQ7N.js";var fromDisk;function readLinkedProject(){return fromDisk??=(async()=>{try{let{readFile}=await import("node:fs/promises"),{join}=await import("node:path"),raw=await readFile(join(process.cwd(),".vercel","project.json"),"utf8"),{projectId,orgId}=JSON.parse(raw);return{projectId:projectId??null,teamId:orgId??null}}catch{return{projectId:null,teamId:null}}})(),fromDisk}async function ownProjectId(){return process.env.VERCEL_PROJECT_ID?process.env.VERCEL_PROJECT_ID:(await readLinkedProject()).projectId}async function ownTeamId(){return process.env.VERCEL_ORG_ID?process.env.VERCEL_ORG_ID:(await readLinkedProject()).teamId}async function discoveryIdentity(headers){let projectId=await ownProjectId(),header=headers?.get("x-vercel-oidc-token");if(header)try{let claims=decodeJwt(header);if(typeof claims.owner_id=="string")return{projectId,teamId:claims.owner_id}}catch{}return process.env.VERCEL_ORG_ID?{projectId,teamId:process.env.VERCEL_ORG_ID}:{projectId,teamId:(await readLinkedProject()).teamId}}var REGISTERED=new Set(["aud","exp","iat","nbf","jti"]);function factsOf(issuer,iss,claims){let kept={};for(let[name,value]of Object.entries(claims))REGISTERED.has(name)||Object.keys(kept).length>=64||(typeof value=="number"||typeof value=="boolean"||typeof value=="string"&&value.length<=1e3)&&(kept[name]=value);return{issuer,iss,claims:kept}}var issuerMatches=(iss,accepted)=>typeof accepted=="string"?iss===accepted:accepted.test(iss),remoteKeys=new Map,loading=new Map,REMOTE_KEYS_MAX=100,DISCOVERY_TIMEOUT_MS=5e3;function keysFor(iss){let cached=remoteKeys.get(iss);if(cached)return remoteKeys.delete(iss),remoteKeys.set(iss,cached),Promise.resolve(cached);let pending=loading.get(iss);return pending||(pending=discover(iss).finally(()=>loading.delete(iss)),loading.set(iss,pending)),pending}async function discover(iss){let unknown=why=>unauthorized(`cannot load keys for issuer ${iss}: ${why}`),response=await fetch(`${iss.replace(/\/+$/,"")}/.well-known/openid-configuration`,{redirect:"manual",signal:AbortSignal.timeout(DISCOVERY_TIMEOUT_MS)}).catch(()=>{throw unknown("its discovery did not answer")});if(response.status!==200)throw unknown(`its discovery answered ${response.status}`);let config=await response.json().catch(()=>null);if(config?.issuer!==iss)throw unknown("its discovery names another issuer");let jwks=typeof config.jwks_uri=="string"?URL.parse(config.jwks_uri):null;if(jwks?.protocol!=="https:"||privateHost(jwks.hostname))throw unknown("its jwks_uri isn't an https URL on the internet");let keys=createRemoteJWKSet(jwks,{timeoutDuration:DISCOVERY_TIMEOUT_MS});return remoteKeys.size>=REMOTE_KEYS_MAX&&remoteKeys.delete(remoteKeys.keys().next().value),remoteKeys.set(iss,keys),keys}function createVerifier(options){let vercelIssuer=options.auth?.vercel??{issuer:VERCEL_ISSUER},githubIssuer=options.auth?.github??{issuer:"https://token.actions.githubusercontent.com"},oidcIssuers=trustedIssuers(options.issuers);async function verify(token,audience){let iss;try{iss=String(decodeJwt(token).iss??"")}catch{throw unauthorized("malformed token")}let local=options.auth?.local;if(local&&iss===local.issuer)return localPerson(token,local,audience);let isVercel=issuerMatches(iss,vercelIssuer.issuer),isGitHub=!isVercel&&issuerMatches(iss,githubIssuer.issuer),isOidc=!isVercel&&!isGitHub&&oidcIssuers.has(iss);if(!isVercel&&!isGitHub&&!isOidc)throw unauthorized(`untrusted issuer: ${iss||"(none)"}`);let claims;try{let keys=isOidc?options.auth?.oidc?.[iss]??await keysFor(iss):(isVercel?vercelIssuer:githubIssuer).jwks??await keysFor(iss);({payload:claims}=await jwtVerify(token,keys,{issuer:iss,audience}))}catch(error){throw error.status===401?error:unauthorized(`invalid token: ${error.message}`)}let facts=factsOf(isOidc?"oidc":isGitHub?"github":"vercel",iss,claims),expiresAt=claims.exp?new Date(claims.exp*1e3):null;if(isOidc){if(typeof claims.sub!="string"||claims.sub==="")throw unauthorized(`token from ${iss} without sub`);if(!subFits(claims.sub))throw unauthorized(`token from ${iss} has a sub with a +, a ], or a space, which a principal's ID can't hold`);return{id:`oidc:${issuerName(iss)}:${claims.sub}`,kind:"workflow",handle:claims.sub.slice(0,128),expiresAt,facts}}if(isGitHub)return{id:`github:repo:${String(claims.repository_id)}`,kind:"workflow",handle:String(claims.repository),expiresAt,facts};let environment=String(claims.environment??""),project=String(claims.project??""),ownProject=await options.projectId()??null;if(ownProject!==null&&claims.project_id===ownProject&&environment==="development"){if(typeof claims.user_id!="string")throw unauthorized("development token without user_id");return{id:`vercel:user:${claims.user_id}`,kind:"person",handle:claims.user_id,expiresAt}}return deployment(facts,project,environment,expiresAt)}return{verify}}var LOCAL_SUB=/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/;async function localPerson(token,local,audience){let claims;try{({payload:claims}=await jwtVerify(token,local.jwks,{issuer:local.issuer,audience}))}catch(error){throw unauthorized(`invalid token: ${error.message}`)}let sub=String(claims.sub??"");if(!LOCAL_SUB.test(sub))throw unauthorized("local token without a valid sub");return{id:`local:user:${sub}`,kind:"person",handle:sub,expiresAt:claims.exp?new Date(claims.exp*1e3):null}}var deployment=(facts,project,environment,expiresAt)=>({id:`vercel:project:${String(facts.claims.project_id)}:${environment}`,kind:"deployment",handle:project,expiresAt,facts}),environmentBoard={project:async()=>({id:await ownProjectId(),teamId:await ownTeamId()}),issuers:[]};function oidcTokens(options={}){let made=null;return Object.assign(async request=>{if(request.credential===null)return null;let board=request.board??environmentBoard,issuers=board.issuers.join(`
8
+ `);return(made?.board!==board||made.issuers!==issuers)&&(made={board,issuers,verify:createVerifier({projectId:async()=>(await board.project()).id,issuers:board.issuers,auth:options}).verify}),markVerified(await made.verify(request.credential,request.audience))},{[TOKENS]:!0})}export{discoveryIdentity,oidcTokens,ownProjectId,ownTeamId};
@@ -4,7 +4,7 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{validatePaths,validateRootDirectory}from"../../chunks/chunk-UWISBHZI.js";import{getBuildMachineResourceConfig}from"../../chunks/chunk-ZF27J6FQ.js";import{aliasLonePageInOutput,isIgnoredFile,isStaticFolderDeploy,resolveSingleFileProject,singleFileConfig,singleFileMeta,singleFileProjectSettings,singleFileTargetArgs,stageSingleFile}from"../../chunks/chunk-O3IQMUYI.js";import{FIRST_DEPLOYMENT_PRODUCTION_NOTICE,hasEarlierDeployment,isNonProductionTarget,refuseFirstDeployment}from"../../chunks/chunk-UEJ332R4.js";import"../../chunks/chunk-COD3WAUI.js";import{pickOverrides}from"../../chunks/chunk-A72AM25W.js";import{BLOCKED_DEPLOYMENT_REASON,DeployTelemetryClient,Now,UploadErrorMissingArchive,formatVerificationFailure,getBlockedDeploymentDetails,getBlockedDeploymentMessage,getBlockedDeploymentNext,getDeploymentEnvironment,getDeploymentEnvironmentLabel,isBlockedDeployment,printBlockedDeployment,printDeploymentStatus,printPrebuiltFilePathMapIgnoreWarning,verifyDeployment}from"../../chunks/chunk-YALFS5SH.js";import"../../chunks/chunk-ZFRNVIHI.js";import"../../chunks/chunk-3FMDKPIO.js";import{PROJECT_EXPIRATION_TIMEFRAMES}from"../../chunks/chunk-ANIA2G6F.js";import"../../chunks/chunk-UUBPAYTG.js";import"../../chunks/chunk-AMH5MXDW.js";import{parseMeta}from"../../chunks/chunk-CZSOZKHX.js";import{compileVercelConfig,findSourceVercelConfigFile}from"../../chunks/chunk-WCCKCQ43.js";import"../../chunks/chunk-TVELM5HH.js";import"../../chunks/chunk-U56NHYAH.js";import{getEnabledProtection,getProtectionForDeployment}from"../../chunks/chunk-B7GCRM5I.js";import{getProductionUrl}from"../../chunks/chunk-VT6RIZJH.js";import{formatDate}from"../../chunks/chunk-HRR57QNP.js";import{stamp_default}from"../../chunks/chunk-A2RZZQEP.js";import"../../chunks/chunk-Q7D7RGXM.js";import{parseEnv}from"../../chunks/chunk-KR4DMT3I.js";import{applyDeprecatedTargetFlag,parseTarget}from"../../chunks/chunk-HAGBKLAS.js";import{isGuidanceEnabled}from"../../chunks/chunk-TAAWMNNL.js";import{ensureLink}from"../../chunks/chunk-O4WJDJIL.js";import"../../chunks/chunk-A5FPKXEK.js";import{getDeployment}from"../../chunks/chunk-NBTFAXL4.js";import{mapCertError}from"../../chunks/chunk-TJUZVODP.js";import"../../chunks/chunk-PFD7LETF.js";import"../../chunks/chunk-IQ7FPAI4.js";import{trackCreatedId}from"../../chunks/chunk-YJNMDXEG.js";import{getRenamedOption,reportRenamedOptionError}from"../../chunks/chunk-FSZJSIOF.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import{getCommandAliases}from"../../chunks/chunk-6U7TRWBO.js";import"../../chunks/chunk-QOLGACFD.js";import"../../chunks/chunk-DDPH26ZO.js";import"../../chunks/chunk-PIDEH4SJ.js";import"../../chunks/chunk-IIK6GUVI.js";import"../../chunks/chunk-C35SG42R.js";import"../../chunks/chunk-2GBU6ULJ.js";import"../../chunks/chunk-EJLYDHT7.js";import{continueSubcommand,deployCommand,deprecatedArchiveSplitTgz,describeSubcommand,initSubcommand}from"../../chunks/chunk-DOBV3XLO.js";import"../../chunks/chunk-UFCL2VBD.js";import"../../chunks/chunk-BMIYC2MH.js";import"../../chunks/chunk-6CJFPT4F.js";import"../../chunks/chunk-ZZD5W5KT.js";import"../../chunks/chunk-VHSAI6FS.js";import"../../chunks/chunk-F7L5SXJM.js";import"../../chunks/chunk-GLCSWIB4.js";import"../../chunks/chunk-XECELSF5.js";import"../../chunks/chunk-6FYPSSL4.js";import"../../chunks/chunk-UQZZX2J7.js";import"../../chunks/chunk-UDZJCD5W.js";import"../../chunks/chunk-5ZCSFPWG.js";import"../../chunks/chunk-PY4WWD6Z.js";import"../../chunks/chunk-XDYVJWGX.js";import"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-BPIGFKNN.js";import"../../chunks/chunk-AB4WXRCO.js";import"../../chunks/chunk-SYJXONEV.js";import{printError}from"../../chunks/chunk-CY5KJ42N.js";import"../../chunks/chunk-KK5C7HVP.js";import{help}from"../../chunks/chunk-7KCRYDGK.js";import"../../chunks/chunk-GLIQ4KNY.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import"../../chunks/chunk-YJP25FL6.js";import{require_ci_info}from"../../chunks/chunk-KDCODXVL.js";import"../../chunks/chunk-NWGBDBZI.js";import{AGENT_REASON,AGENT_STATUS,argvHasNonInteractive,buildCommandWithYes,outputActionRequired,outputAgentError,withGlobalFlags,writeAgentError}from"../../chunks/chunk-PNWRO3XW.js";import"../../chunks/chunk-DTUEHPME.js";import{VERCEL_DIR,VERCEL_DIR_PROJECT,addToGitIgnore,createGitMeta,getGitConfigPath,getGitExecutable,getLinkFromDir,getRepoLink,getVercelDirectory,highlight,isOwnerLookupUnavailableLink,isProjectReadLink,isRemoteLookupSkippedLink,linkFolderToProject,parseGitConfig,pluckRemoteUrls,readLocalConfig,require_dist2,require_lib}from"../../chunks/chunk-XL2PHD4X.js";import{printAlignedLabel}from"../../chunks/chunk-M7FED5YP.js";import"../../chunks/chunk-4HR3I3ML.js";import{getProjectByNameOrId}from"../../chunks/chunk-LOA7SZWH.js";import"../../chunks/chunk-LUX4PBJL.js";import"../../chunks/chunk-MTZYPCZ7.js";import"../../chunks/chunk-OPORM35X.js";import"../../chunks/chunk-D6REP5QQ.js";import"../../chunks/chunk-FBYA6LLM.js";import{getFetchDispatcher}from"../../chunks/chunk-MY4MONOH.js";import"../../chunks/chunk-7HLAWGY2.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import{parseArguments}from"../../chunks/chunk-LYL26S3N.js";import"../../chunks/chunk-2VBFQZ72.js";import{validateJsonOutput,warnDeprecatedInput}from"../../chunks/chunk-6GKP6VUF.js";import"../../chunks/chunk-4NTBYNFR.js";import"../../chunks/chunk-4SAVH3H7.js";import{AliasDomainConfigured,BuildError,BuildsRateLimited,ConflictingConfigFiles,ConflictingFilePath,ConflictingPathSegment,DeploymentNotFound,DeploymentsRateLimited,DeprecatedNowJson,DomainNotFound,DomainNotVerified,DomainPermissionDenied,DomainVerificationFailed,InvalidDomain,MissingBuildScript,NotDomainOwner,NowError,ProjectNotFound,SchemaValidationFailed,TooManyRequests,UserAborted,code,isAPIError,require_bytes}from"../../chunks/chunk-GOI2VVI7.js";import{getCommandName,getCommandNamePlain,packageName}from"../../chunks/chunk-B4KA3ZH2.js";import"../../chunks/chunk-BOJDM3O7.js";import{cliErrorFromUnknown,emoji,link_default,output_manager_default,prependEmoji,recordCliError}from"../../chunks/chunk-AP6DZGTK.js";import"../../chunks/chunk-BLUPZPAS.js";import{require_types}from"../../chunks/chunk-AW33SRYY.js";import{require_build_utils}from"../../chunks/chunk-5MDNVAE6.js";import"../../chunks/chunk-OCR5CRTH.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-SCV7XEEO.js";import{require_dist}from"../../chunks/chunk-MCYG7CCE.js";import"../../chunks/chunk-YHPPP3SF.js";import"../../chunks/chunk-24SIHFEW.js";import{getFlagsSpecification,quoteArg,stripSensitiveAuthArgs}from"../../chunks/chunk-CFJBDBYH.js";import"../../chunks/chunk-2BKALEOP.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import"../../chunks/chunk-BULSRTQE.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_build_utils2=__toESM(require_build_utils(),1),import_client=__toESM(require_dist2(),1),import_error_utils2=__toESM(require_dist(),1);var import_bytes=__toESM(require_bytes(),1),import_chalk=__toESM(require_source(),1),import_fs_extra4=__toESM(require_lib(),1),import_ms=__toESM(require_ms(),1);import{tmpdir}from"os";import{basename,dirname,extname,join as join4,resolve as resolve2}from"path";async function createDeploy(client,now,contextName,path,createArgs,org,isSettingUpProject,archive){try{return await now.create(path,createArgs,org,isSettingUpProject,archive)}catch(err){if(isAPIError(err)){if(err.code==="rate_limited")throw new DeploymentsRateLimited(err.message);if(err.code==="domain_missing")throw new DomainNotFound(err.value);if(err.code==="domain_not_found"&&err.domain)throw new DomainNotFound(err.domain);if(err.code==="domain_not_verified"&&err.domain)throw new DomainNotVerified(err.domain);if(err.code==="domain_not_verified"&&err.value)throw new DomainVerificationFailed(err.value);if(err.code==="not_domain_owner")throw new NotDomainOwner(err.message);if(err.code==="builds_rate_limited")throw new BuildsRateLimited(err.message,{ctaLabel:err.ctaLabel,ctaUrl:err.ctaUrl,action:err.action,link:err.link});if(err.code==="forbidden")throw new DomainPermissionDenied(err.value,contextName);if(err.code==="bad_request"&&err.keyword)throw new SchemaValidationFailed(err.message,err.keyword,err.dataPath,err.params);if(err.code==="domain_configured")throw new AliasDomainConfigured(err);if(err.code==="missing_build_script")throw new MissingBuildScript(err);if(err.code==="conflicting_file_path")throw new ConflictingFilePath(err);if(err.code==="conflicting_path_segment")throw new ConflictingPathSegment(err);if(err.code==="cert_missing"){let{default:generateCertForDeploy}=await import("../../chunks/generate-cert-for-deploy-FQQZEMTU.js"),result=await generateCertForDeploy(client,contextName,err.value);return result instanceof NowError?result:createDeploy(client,now,contextName,path,createArgs,org,isSettingUpProject)}if(err.code==="not_found")throw new DeploymentNotFound({context:contextName});let certError=mapCertError(err);if(certError)return certError}throw err}}var ENV_PAIR_FLAGS=["--env","--build-env"],ENV_VALUE_PLACEHOLDER="<VALUE>",PROJECT_PLACEHOLDER="<PROJECT>",CANONICAL_FLAGS={"--token":null,"--confirm":"--yes","--target":"--environment","--team":"--scope","--name":null,"--no-clipboard":null,"--no-logs":null};function buildCreateIfMissingCommand(positionals,flags,argv,{createIfMissing=!0,addProjectPlaceholder=!1}={}){let out=["deploy",...positionals],seen=new Set,hasPlaceholder=!1;for(let[typedName,value]of Object.entries(flags)){let name=typedName in CANONICAL_FLAGS?CANONICAL_FLAGS[typedName]:typedName;if(!(!name||name==="--create-if-missing"||seen.has(name))){if(seen.add(name),name==="--non-interactive"){out.push(argvHasNonInteractive(argv)?"--non-interactive":"--non-interactive=false");continue}for(let item of Array.isArray(value)?value:[value])if(item===!0)out.push(name);else if(typeof item=="string"||typeof item=="number"){let text=String(item),shown=ENV_PAIR_FLAGS.includes(name)?withPlaceholder(text):text;hasPlaceholder||=shown!==text,out.push(name,shown)}}}addProjectPlaceholder&&out.push("--project",PROJECT_PLACEHOLDER),createIfMissing&&out.push("--create-if-missing");let command=[packageName,...out.map(quoteToken)].join(" "),notes=[...addProjectPlaceholder?[`replace ${PROJECT_PLACEHOLDER} with the project name`]:[],...hasPlaceholder?[`replace each ${ENV_VALUE_PLACEHOLDER} with the Environment Variable's value`]:[]];return notes.length?{command,note:notes.join(", and ")}:{command}}function findEnvPlaceholder(flags){for(let flag of ENV_PAIR_FLAGS){let value=flags[flag];for(let pair of Array.isArray(value)?value:[value])if(typeof pair=="string"&&pair.endsWith(`=${ENV_VALUE_PLACEHOLDER}`))return{flag,key:pair.slice(0,pair.indexOf("="))}}}function withPlaceholder(pair){let equals=pair.indexOf("=");return equals>=0?`${pair.slice(0,equals)}=${ENV_VALUE_PLACEHOLDER}`:pair}function quoteToken(token){return token===PROJECT_PLACEHOLDER||/^[A-Za-z0-9_./@:=,+-]+$/.test(token)?token:quoteArg(token)}async function getDeploymentChecks(client,deploymentId){return await client.fetch(`/v1/deployments/${encodeURIComponent(deploymentId)}/checks`)}async function getDeploymentCheckRuns(client,deploymentId){return await client.fetch(`/v2/deployments/${encodeURIComponent(deploymentId)}/check-runs`)}function parseNdjson(text){let entries=[];for(let line of text.split(`
7
+ import{validatePaths,validateRootDirectory}from"../../chunks/chunk-UWISBHZI.js";import{getBuildMachineResourceConfig}from"../../chunks/chunk-ZF27J6FQ.js";import{aliasLonePageInOutput,isIgnoredFile,isStaticFolderDeploy,resolveSingleFileProject,singleFileConfig,singleFileMeta,singleFileProjectSettings,singleFileTargetArgs,stageSingleFile}from"../../chunks/chunk-O3IQMUYI.js";import{FIRST_DEPLOYMENT_PRODUCTION_NOTICE,hasEarlierDeployment,isNonProductionTarget,refuseFirstDeployment}from"../../chunks/chunk-UEJ332R4.js";import"../../chunks/chunk-COD3WAUI.js";import{pickOverrides}from"../../chunks/chunk-A72AM25W.js";import{BLOCKED_DEPLOYMENT_REASON,DeployTelemetryClient,Now,UploadErrorMissingArchive,formatVerificationFailure,getBlockedDeploymentDetails,getBlockedDeploymentMessage,getBlockedDeploymentNext,getDeploymentEnvironment,getDeploymentEnvironmentLabel,isBlockedDeployment,printBlockedDeployment,printDeploymentStatus,printPrebuiltFilePathMapIgnoreWarning,verifyDeployment}from"../../chunks/chunk-PX55WGPZ.js";import"../../chunks/chunk-ZFRNVIHI.js";import"../../chunks/chunk-3FMDKPIO.js";import{PROJECT_EXPIRATION_TIMEFRAMES}from"../../chunks/chunk-ANIA2G6F.js";import"../../chunks/chunk-UUBPAYTG.js";import"../../chunks/chunk-AMH5MXDW.js";import{parseMeta}from"../../chunks/chunk-CZSOZKHX.js";import{compileVercelConfig,findSourceVercelConfigFile}from"../../chunks/chunk-WCCKCQ43.js";import"../../chunks/chunk-TVELM5HH.js";import"../../chunks/chunk-U56NHYAH.js";import{getEnabledProtection,getProtectionForDeployment}from"../../chunks/chunk-B7GCRM5I.js";import{getProductionUrl}from"../../chunks/chunk-VT6RIZJH.js";import{formatDate}from"../../chunks/chunk-HRR57QNP.js";import{stamp_default}from"../../chunks/chunk-A2RZZQEP.js";import"../../chunks/chunk-Q7D7RGXM.js";import{parseEnv}from"../../chunks/chunk-KR4DMT3I.js";import{applyDeprecatedTargetFlag,parseTarget}from"../../chunks/chunk-HAGBKLAS.js";import{isGuidanceEnabled}from"../../chunks/chunk-TAAWMNNL.js";import{ensureLink}from"../../chunks/chunk-O4WJDJIL.js";import"../../chunks/chunk-A5FPKXEK.js";import{getDeployment}from"../../chunks/chunk-NBTFAXL4.js";import{mapCertError}from"../../chunks/chunk-TJUZVODP.js";import"../../chunks/chunk-PFD7LETF.js";import"../../chunks/chunk-IQ7FPAI4.js";import{trackCreatedId}from"../../chunks/chunk-YJNMDXEG.js";import{getRenamedOption,reportRenamedOptionError}from"../../chunks/chunk-FSZJSIOF.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import{getCommandAliases}from"../../chunks/chunk-HVFGIJ44.js";import"../../chunks/chunk-QOLGACFD.js";import"../../chunks/chunk-DDPH26ZO.js";import"../../chunks/chunk-PIDEH4SJ.js";import"../../chunks/chunk-IIK6GUVI.js";import"../../chunks/chunk-C35SG42R.js";import"../../chunks/chunk-2GBU6ULJ.js";import"../../chunks/chunk-EJLYDHT7.js";import{continueSubcommand,deployCommand,deprecatedArchiveSplitTgz,describeSubcommand,initSubcommand}from"../../chunks/chunk-DOBV3XLO.js";import"../../chunks/chunk-TUB3APDV.js";import"../../chunks/chunk-BMIYC2MH.js";import"../../chunks/chunk-6CJFPT4F.js";import"../../chunks/chunk-ZZD5W5KT.js";import"../../chunks/chunk-VHSAI6FS.js";import"../../chunks/chunk-F7L5SXJM.js";import"../../chunks/chunk-GLCSWIB4.js";import"../../chunks/chunk-XECELSF5.js";import"../../chunks/chunk-6FYPSSL4.js";import"../../chunks/chunk-UQZZX2J7.js";import"../../chunks/chunk-UDZJCD5W.js";import"../../chunks/chunk-5ZCSFPWG.js";import"../../chunks/chunk-PY4WWD6Z.js";import"../../chunks/chunk-XDYVJWGX.js";import"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-BPIGFKNN.js";import"../../chunks/chunk-AB4WXRCO.js";import"../../chunks/chunk-SYJXONEV.js";import{printError}from"../../chunks/chunk-CY5KJ42N.js";import"../../chunks/chunk-KK5C7HVP.js";import{help}from"../../chunks/chunk-7KCRYDGK.js";import"../../chunks/chunk-GLIQ4KNY.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import"../../chunks/chunk-YJP25FL6.js";import{require_ci_info}from"../../chunks/chunk-KDCODXVL.js";import"../../chunks/chunk-NWGBDBZI.js";import{AGENT_REASON,AGENT_STATUS,argvHasNonInteractive,buildCommandWithYes,outputActionRequired,outputAgentError,withGlobalFlags,writeAgentError}from"../../chunks/chunk-PNWRO3XW.js";import"../../chunks/chunk-DTUEHPME.js";import{VERCEL_DIR,VERCEL_DIR_PROJECT,addToGitIgnore,createGitMeta,getGitConfigPath,getGitExecutable,getLinkFromDir,getRepoLink,getVercelDirectory,highlight,isOwnerLookupUnavailableLink,isProjectReadLink,isRemoteLookupSkippedLink,linkFolderToProject,parseGitConfig,pluckRemoteUrls,readLocalConfig,require_dist2,require_lib}from"../../chunks/chunk-XL2PHD4X.js";import{printAlignedLabel}from"../../chunks/chunk-M7FED5YP.js";import"../../chunks/chunk-4HR3I3ML.js";import{getProjectByNameOrId}from"../../chunks/chunk-LOA7SZWH.js";import"../../chunks/chunk-LUX4PBJL.js";import"../../chunks/chunk-MTZYPCZ7.js";import"../../chunks/chunk-OPORM35X.js";import"../../chunks/chunk-D6REP5QQ.js";import"../../chunks/chunk-FBYA6LLM.js";import{getFetchDispatcher}from"../../chunks/chunk-MY4MONOH.js";import"../../chunks/chunk-7HLAWGY2.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import{parseArguments}from"../../chunks/chunk-LYL26S3N.js";import"../../chunks/chunk-2VBFQZ72.js";import{validateJsonOutput,warnDeprecatedInput}from"../../chunks/chunk-6GKP6VUF.js";import"../../chunks/chunk-4NTBYNFR.js";import"../../chunks/chunk-4SAVH3H7.js";import{AliasDomainConfigured,BuildError,BuildsRateLimited,ConflictingConfigFiles,ConflictingFilePath,ConflictingPathSegment,DeploymentNotFound,DeploymentsRateLimited,DeprecatedNowJson,DomainNotFound,DomainNotVerified,DomainPermissionDenied,DomainVerificationFailed,InvalidDomain,MissingBuildScript,NotDomainOwner,NowError,ProjectNotFound,SchemaValidationFailed,TooManyRequests,UserAborted,code,isAPIError,require_bytes}from"../../chunks/chunk-GOI2VVI7.js";import{getCommandName,getCommandNamePlain,packageName}from"../../chunks/chunk-B4KA3ZH2.js";import"../../chunks/chunk-BOJDM3O7.js";import{cliErrorFromUnknown,emoji,link_default,output_manager_default,prependEmoji,recordCliError}from"../../chunks/chunk-AP6DZGTK.js";import"../../chunks/chunk-BLUPZPAS.js";import{require_types}from"../../chunks/chunk-AW33SRYY.js";import{require_build_utils}from"../../chunks/chunk-5MDNVAE6.js";import"../../chunks/chunk-OCR5CRTH.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-SCV7XEEO.js";import{require_dist}from"../../chunks/chunk-MCYG7CCE.js";import"../../chunks/chunk-YHPPP3SF.js";import"../../chunks/chunk-24SIHFEW.js";import{getFlagsSpecification,quoteArg,stripSensitiveAuthArgs}from"../../chunks/chunk-CFJBDBYH.js";import"../../chunks/chunk-2BKALEOP.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import"../../chunks/chunk-BULSRTQE.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_build_utils2=__toESM(require_build_utils(),1),import_client=__toESM(require_dist2(),1),import_error_utils2=__toESM(require_dist(),1);var import_bytes=__toESM(require_bytes(),1),import_chalk=__toESM(require_source(),1),import_fs_extra4=__toESM(require_lib(),1),import_ms=__toESM(require_ms(),1);import{tmpdir}from"os";import{basename,dirname,extname,join as join4,resolve as resolve2}from"path";async function createDeploy(client,now,contextName,path,createArgs,org,isSettingUpProject,archive){try{return await now.create(path,createArgs,org,isSettingUpProject,archive)}catch(err){if(isAPIError(err)){if(err.code==="rate_limited")throw new DeploymentsRateLimited(err.message);if(err.code==="domain_missing")throw new DomainNotFound(err.value);if(err.code==="domain_not_found"&&err.domain)throw new DomainNotFound(err.domain);if(err.code==="domain_not_verified"&&err.domain)throw new DomainNotVerified(err.domain);if(err.code==="domain_not_verified"&&err.value)throw new DomainVerificationFailed(err.value);if(err.code==="not_domain_owner")throw new NotDomainOwner(err.message);if(err.code==="builds_rate_limited")throw new BuildsRateLimited(err.message,{ctaLabel:err.ctaLabel,ctaUrl:err.ctaUrl,action:err.action,link:err.link});if(err.code==="forbidden")throw new DomainPermissionDenied(err.value,contextName);if(err.code==="bad_request"&&err.keyword)throw new SchemaValidationFailed(err.message,err.keyword,err.dataPath,err.params);if(err.code==="domain_configured")throw new AliasDomainConfigured(err);if(err.code==="missing_build_script")throw new MissingBuildScript(err);if(err.code==="conflicting_file_path")throw new ConflictingFilePath(err);if(err.code==="conflicting_path_segment")throw new ConflictingPathSegment(err);if(err.code==="cert_missing"){let{default:generateCertForDeploy}=await import("../../chunks/generate-cert-for-deploy-FQQZEMTU.js"),result=await generateCertForDeploy(client,contextName,err.value);return result instanceof NowError?result:createDeploy(client,now,contextName,path,createArgs,org,isSettingUpProject)}if(err.code==="not_found")throw new DeploymentNotFound({context:contextName});let certError=mapCertError(err);if(certError)return certError}throw err}}var ENV_PAIR_FLAGS=["--env","--build-env"],ENV_VALUE_PLACEHOLDER="<VALUE>",PROJECT_PLACEHOLDER="<PROJECT>",CANONICAL_FLAGS={"--token":null,"--confirm":"--yes","--target":"--environment","--team":"--scope","--name":null,"--no-clipboard":null,"--no-logs":null};function buildCreateIfMissingCommand(positionals,flags,argv,{createIfMissing=!0,addProjectPlaceholder=!1}={}){let out=["deploy",...positionals],seen=new Set,hasPlaceholder=!1;for(let[typedName,value]of Object.entries(flags)){let name=typedName in CANONICAL_FLAGS?CANONICAL_FLAGS[typedName]:typedName;if(!(!name||name==="--create-if-missing"||seen.has(name))){if(seen.add(name),name==="--non-interactive"){out.push(argvHasNonInteractive(argv)?"--non-interactive":"--non-interactive=false");continue}for(let item of Array.isArray(value)?value:[value])if(item===!0)out.push(name);else if(typeof item=="string"||typeof item=="number"){let text=String(item),shown=ENV_PAIR_FLAGS.includes(name)?withPlaceholder(text):text;hasPlaceholder||=shown!==text,out.push(name,shown)}}}addProjectPlaceholder&&out.push("--project",PROJECT_PLACEHOLDER),createIfMissing&&out.push("--create-if-missing");let command=[packageName,...out.map(quoteToken)].join(" "),notes=[...addProjectPlaceholder?[`replace ${PROJECT_PLACEHOLDER} with the project name`]:[],...hasPlaceholder?[`replace each ${ENV_VALUE_PLACEHOLDER} with the Environment Variable's value`]:[]];return notes.length?{command,note:notes.join(", and ")}:{command}}function findEnvPlaceholder(flags){for(let flag of ENV_PAIR_FLAGS){let value=flags[flag];for(let pair of Array.isArray(value)?value:[value])if(typeof pair=="string"&&pair.endsWith(`=${ENV_VALUE_PLACEHOLDER}`))return{flag,key:pair.slice(0,pair.indexOf("="))}}}function withPlaceholder(pair){let equals=pair.indexOf("=");return equals>=0?`${pair.slice(0,equals)}=${ENV_VALUE_PLACEHOLDER}`:pair}function quoteToken(token){return token===PROJECT_PLACEHOLDER||/^[A-Za-z0-9_./@:=,+-]+$/.test(token)?token:quoteArg(token)}async function getDeploymentChecks(client,deploymentId){return await client.fetch(`/v1/deployments/${encodeURIComponent(deploymentId)}/checks`)}async function getDeploymentCheckRuns(client,deploymentId){return await client.fetch(`/v2/deployments/${encodeURIComponent(deploymentId)}/check-runs`)}function parseNdjson(text){let entries=[];for(let line of text.split(`
8
8
  `))if(line.trim())try{entries.push(JSON.parse(line))}catch{}return entries}async function getDeploymentCheckRunLogs(client,deploymentId,checkRunId){let url=`/v2/deployments/${encodeURIComponent(deploymentId)}/check-runs/${encodeURIComponent(checkRunId)}/logs`;await new Promise(resolve3=>setTimeout(resolve3,1e3));for(let attempt=0;attempt<5;attempt++){attempt>0&&await new Promise(resolve3=>setTimeout(resolve3,2e3));let res=await client.fetch(url,{json:!1}),text=typeof res=="string"?res:await res.text(),entries=parseNdjson(text);if(entries.some(e=>e.level==="eof"))return entries.filter(e=>e.level!=="eof"&&e.level!=="debug").map(({level,timestamp,message})=>({level,timestamp,message}))}return[]}var import_fs_extra=__toESM(require_lib(),1);import{join}from"path";async function getPrebuiltJson(directory){try{return await import_fs_extra.default.readJSON(join(directory,"builds.json"))}catch{}return null}import{resolve}from"path";var SUPPORTED_PROVIDERS=new Set(["github","gitlab","bitbucket"]),defaultDeps={getGitConfigPath,parseGitConfig,fetchProject:(client,project)=>client.fetch(`/v9/projects/${encodeURIComponent(project.id)}`,{accountId:project.accountId}),buildCommand:(client,command)=>withGlobalFlags(client,command,{preserveProject:!0})};async function getGitConnectRecommendation(client,cwd,project,options={}){let{alreadyOffered=!1,fetchedProject,deps=defaultDeps}=options;try{if(project.link||alreadyOffered)return;let gitConfigPath=deps.getGitConfigPath({cwd});if(!gitConfigPath)return;let gitConfig=await deps.parseGitConfig(gitConfigPath),remoteUrls=gitConfig&&pluckRemoteUrls(gitConfig);if(!remoteUrls)return;let remotes=Object.values(remoteUrls),{parseRepoUrl}=await import("../../chunks/connect-git-provider-CIRRFPI2.js");if(!remotes.some(remoteUrl=>{let repo=parseRepoUrl(remoteUrl);return repo&&SUPPORTED_PROVIDERS.has(repo.provider)})||client.nonInteractive&&remotes.length!==1||(fetchedProject??await deps.fetchProject(client,project)).link)return;let cwdFlag=resolve(cwd)===resolve(client.cwd)?"":` --cwd ${quoteArg(cwd)}`;return deps.buildCommand(client,`git connect${cwdFlag}`)}catch(error){output_manager_default.debug(`Failed to resolve Git connection guidance: ${error}`);return}}var import_types=__toESM(require_types(),1),validArchiveFormats=new Set(import_types.VALID_ARCHIVE_FORMATS);function isValidArchive(archive){return validArchiveFormats.has(archive)}var DEPRECATED_SHORTHANDS={"-e":"--env","-b":"--build-env"};function getDeployFlagsSpecification(options){return{...getFlagsSpecification(options),...DEPRECATED_SHORTHANDS}}function warnDeprecatedShorthands(client,options){let flags;try{({flags}=parseArguments(client.argv.slice(2),{...getFlagsSpecification(options),"-e":[String],"-b":[String]},{permissive:!0}))}catch{return}for(let[shorthand,name]of Object.entries(DEPRECATED_SHORTHANDS))flags[shorthand]!==void 0&&warnDeprecatedInput(client,shorthand,name)}function getErrorCta(source){if(typeof source.ctaLabel=="string"&&typeof source.ctaUrl=="string")return{label:source.ctaLabel,url:source.ctaUrl};if(typeof source.action=="string"&&typeof source.link=="string")return{label:source.action,url:source.link}}import{readFile}from"fs/promises";async function promptExperimentalServicesMigration(options){return await mayHaveLegacyServicesConfig(options)?(await import("../../chunks/migrate-experimental-services-XEKA373Q.js")).promptExperimentalServicesMigration(options):!1}async function mayHaveLegacyServicesConfig({cwd,allowConfigExecution=!0}){try{if(!allowConfigExecution||await findSourceVercelConfigFile(cwd))return!0;let{configPath}=await compileVercelConfig(cwd);return configPath?(await readFile(configPath,"utf8")).includes("experimentalServices"):!1}catch{return!0}}var import_fs_extra3=__toESM(require_lib(),1);import{join as join3}from"path";var import_fs_extra2=__toESM(require_lib(),1),import_ci_info=__toESM(require_ci_info(),1),import_build_utils=__toESM(require_build_utils(),1),import_error_utils=__toESM(require_dist(),1);import{join as join2}from"path";var VERCEL_DIR_ANONYMOUS="anonymous.json";function anonymousStatePath(cwd){return join2(cwd,VERCEL_DIR,VERCEL_DIR_ANONYMOUS)}async function readAnonymousState(cwd){try{let state=await(0,import_fs_extra2.readJSON)(anonymousStatePath(cwd));if(typeof state?.projectId=="string"&&typeof state.token=="string"&&typeof state.claimUrl=="string"&&typeof state.expiresAt=="number")return state}catch{}return null}async function writeAnonymousState(cwd,state){let path=anonymousStatePath(cwd);await(0,import_fs_extra2.outputJSON)(path,state,{spaces:2,mode:384}),await(0,import_fs_extra2.chmod)(path,384),await addToGitIgnore(cwd)}async function clearAnonymousState(cwd){await(0,import_fs_extra2.remove)(anonymousStatePath(cwd))}async function bootstrapAnonymousProject(client){let{projectId,token,claimUrl,expiresAt}=await client.fetch("/v1/anonymous/projects?surface=cli",{method:"POST",body:{},useCurrentTeam:!1,retry:{retries:0}});return{projectId,token,claimUrl,expiresAt}}async function ensureAnonymousLink(client,cwd,{requireExistingState=!1,confirmed=!0}={}){if(import_ci_info.default.isCI||!!((0,import_build_utils.getPlatformEnv)("ORG_ID")&&(0,import_build_utils.getPlatformEnv)("PROJECT_ID"))||!!await getLinkFromDir(getVercelDirectory(cwd))||!!(await getRepoLink(client,cwd))?.repoConfig)return"refused";let state=await readAnonymousState(cwd);if(state&&state.expiresAt<=Date.now())return output_manager_default.prettyError({message:`Your temporary deployment has expired. Run ${getCommandName("login")} to create an account and keep deploying this app.`}),"failed";if(!state&&requireExistingState)return"refused";if(!confirmed&&!state)return"confirmation-required";if(!state){try{state=await bootstrapAnonymousProject(client),trackCreatedId(client,"project",state.projectId)}catch(err){return output_manager_default.debug(`Anonymous bootstrap failed: ${(0,import_error_utils.errorToString)(err)}`),"refused"}await writeAnonymousState(cwd,state),output_manager_default.log("Not authenticated. Deploying anonymously.")}return client.authConfig={token:state.token,skipWrite:!0},delete process.env.VERCEL_TEAM_ID,{status:"linked",anonymous:!0,expiresAt:state.expiresAt,claimUrl:state.claimUrl,org:{type:"user",id:"",slug:"anonymous"},project:{id:state.projectId,name:state.projectId}}}function validateAnonymousTarget(isAnonymous,target){return isAnonymous&&target&&target!=="production"?(output_manager_default.error(`Anonymous deployments always target production, so "${target}" is not available. Remove the ${param("--environment")} option, or run ${getCommandName("login")} to deploy to other environments.`),!1):!0}async function setupAnonymousDeployment(client,cwd,{isAnonymous,dryRun}){isAnonymous||await clearAnonymousState(cwd);let anonymousLink;if(isAnonymous){let anonymous=await ensureAnonymousLink(client,cwd,{requireExistingState:dryRun});if(anonymous==="refused"){output_manager_default.log("Temporary deployments aren't available for this attempt. Log in to continue.");let{default:promptMissingCredentials}=await import("../../chunks/prompt-missing-credentials-RJS5U5IJ.js"),loginExitCode=await promptMissingCredentials(client);if(loginExitCode!==0)return loginExitCode;isAnonymous=!1}else{if(anonymous==="failed")return 1;if(anonymous==="confirmation-required")return 1;anonymousLink=anonymous}}return{isAnonymous,anonymousLink}}async function handleAnonymousDeploymentError({client,cwd,error,link,isV0,retry}){if(!(!link||!isAPIError(error))){if(error.code==="anonymous_project_claimed"){if(client.nonInteractive||!client.stdin.isTTY)return output_manager_default.prettyError({message:`This project was claimed successfully. Run ${getCommandName("login")} to continue deploying it.`}),1;output_manager_default.log("This project was claimed successfully. Log in to continue deploying it.");let loginExitCode;try{let{default:login}=await import("../../chunks/login-JSDPVUSB.js");loginExitCode=await login(client,{shouldParseArgs:!1})}catch(loginError){return printError(loginError),1}if(loginExitCode!==0)return loginExitCode;let claimedProjectLink=await ensureLink("deploy",client,cwd,{autoConfirm:!0,projectName:link.project.id,failIfNotFound:!0,allowOwnerLookupFallback:!0,v0:isV0});return typeof claimedProjectLink=="number"?claimedProjectLink:(await linkFolderToProject(client,cwd,{projectId:claimedProjectLink.project.id,orgId:claimedProjectLink.org.id},claimedProjectLink.project.name,claimedProjectLink.org.slug,"link",!0,!1),await clearAnonymousState(cwd),retry())}if(error.status===401||error.status===410)return await clearAnonymousState(cwd),output_manager_default.prettyError({message:`Your temporary deployment has expired. Run ${getCommandName("login")} to create an account and keep deploying this app.`}),1}}async function runImplicitBuild(client,cwd){let projectJsonPath=join3(cwd,VERCEL_DIR,VERCEL_DIR_PROJECT),projectJsonExists=await import_fs_extra3.default.pathExists(projectJsonPath);projectJsonExists||await import_fs_extra3.default.outputJSON(projectJsonPath,{settings:{}},{spaces:2}),await import_fs_extra3.default.pathExists(join3(cwd,"package.json"))&&output_manager_default.log("Building your project locally\u2026");let originalArgv=client.argv,originalCwd=client.cwd,originalStdout=client.stdout,previousVercelFirstDeployment=process.env.VERCEL_FIRST_DEPLOYMENT;client.cwd=cwd,client.setArgv([...originalArgv.slice(0,2),"build","--prod","--yes"]),process.env.VERCEL_FIRST_DEPLOYMENT="1",client.stdout=createSinkStream();try{let build=(await import("../build/index.js")).default;return await build(client)}finally{client.setArgv(originalArgv),client.cwd=originalCwd,client.stdout=originalStdout,previousVercelFirstDeployment===void 0?delete process.env.VERCEL_FIRST_DEPLOYMENT:process.env.VERCEL_FIRST_DEPLOYMENT=previousVercelFirstDeployment,projectJsonExists||await import_fs_extra3.default.remove(projectJsonPath)}}function createSinkStream(){return{isTTY:!1,write:()=>!0}}var COMMAND_CONFIG={init:getCommandAliases(initSubcommand),continue:getCommandAliases(continueSubcommand),describe:getCommandAliases(describeSubcommand)},deploy_default=async client=>{let telemetryClient=new DeployTelemetryClient({opts:{store:client.telemetryEventStore}}),parsedArguments=null,flagsSpecification=getDeployFlagsSpecification(deployCommand.options);try{parsedArguments=parseArguments(client.argv.slice(2),flagsSpecification,{permissive:!0})}catch(error){return printError(error),2}let subArgs=parsedArguments.args[0]===deployCommand.name?parsedArguments.args.slice(1):parsedArguments.args,{subcommand,subcommandOriginal}=getSubcommand(subArgs,COMMAND_CONFIG);function printSubcommandHelp(command){output_manager_default.print(help(command,{stream:client.stderr,parent:deployCommand,columns:client.stderr.columns}))}switch(subcommand){case"init":return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy",subcommandOriginal),printSubcommandHelp(initSubcommand),0):(telemetryClient.trackCliSubcommandInit(subcommandOriginal),handleInitDeployment(client,telemetryClient));case"continue":return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy",subcommandOriginal),printSubcommandHelp(continueSubcommand),0):(telemetryClient.trackCliSubcommandContinue(subcommandOriginal),handleContinueSubcommand(client,telemetryClient));case"describe":return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy",subcommandOriginal),printSubcommandHelp(describeSubcommand),0):(telemetryClient.trackCliSubcommandDescribe(subcommandOriginal),(await import("../../chunks/describe-Z6RRPRGF.js")).default(client));default:return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy"),output_manager_default.print(help(deployCommand,{stream:client.stderr,columns:client.stderr.columns})),0):handleDefaultDeploy(client,telemetryClient)}};async function handleInitDeployment(client,telemetryClient){let flagsSpecification=getDeployFlagsSpecification(initSubcommand.options),parsedArguments;try{parsedArguments=parseArguments(client.argv.slice(2),flagsSpecification)}catch(error2){return printError(error2),2}warnDeprecatedShorthands(client,initSubcommand.options),telemetryClient.trackCliFlagJson(parsedArguments.flags["--json"]),telemetryClient.trackCliOptionFormat(parsedArguments.flags["--format"]),telemetryClient.trackCliOptionProject(parsedArguments.flags["--project"]);let projectNameOrId=parsedArguments.flags["--project"],formatResult=validateJsonOutput(parsedArguments.flags);if(!formatResult.valid)return output_manager_default.error(formatResult.error),2;let asJson=formatResult.jsonOutput||client.nonInteractive;if(!applyDeprecatedTargetFlag(client,parsedArguments.flags))return 2;let envPlaceholderExit=rejectEnvPlaceholder(client,parsedArguments.flags,"deploy init --help");if(envPlaceholderExit!==void 0)return envPlaceholderExit;let args=parsedArguments.args;args[0]==="deploy"&&(args=args.slice(1)),args[0]==="init"&&(args=args.slice(1));let paths;args.length>0?(paths=args.map(item=>resolve2(client.cwd,item)),telemetryClient.trackCliArgumentProjectPath(paths[0])):paths=[client.cwd];let pathValidation=await validatePaths(client,paths);if(!pathValidation.valid)return pathValidation.exitCode;await compileVercelConfig(paths[0]);let localConfig=paths[0]===client.cwd?client.localConfig||readLocalConfig(paths[0]):readLocalConfig(paths[0]);if(localConfig){client.localConfig=localConfig;let{version}=localConfig,file=highlight(localConfig[import_client.fileNameSymbol]),prop=code("version");if(version)if(typeof version=="number"){if(version!==2){let two=code(String(2));return output_manager_default.error(`The value of the ${prop} property within ${file} can only be ${two}.`),1}}else return output_manager_default.error(`The ${prop} property inside your ${file} file must be a number.`),1}let{log,debug,error}=output_manager_default,quiet=!client.stdout.isTTY,{path:cwd}=pathValidation,autoConfirm=parsedArguments.flags["--yes"],target=parseTarget({flagName:"environment",flags:parsedArguments.flags});telemetryClient.trackTargetEnvironment(target);let parsedArchive=parsedArguments.flags["--archive"];if(typeof parsedArchive=="string"&&!(isValidArchive(parsedArchive)||parsedArchive===deprecatedArchiveSplitTgz))return output_manager_default.error(`Format must be one of: ${import_client.VALID_ARCHIVE_FORMATS.join(", ")}`),2;parsedArchive===deprecatedArchiveSplitTgz&&output_manager_default.print(`${prependEmoji(`${param("--archive=tgz")} now has the same behavior as ${param("--archive=split-tgz")}. Please use ${param("--archive=tgz")} instead.`,emoji("warning"))}
9
9
  `);let cliMeta=parseMeta(parsedArguments.flags["--meta"]),isV0=cliMeta.v0==="true";getGitExecutable(cwd);let refuseInitFirstDeployment=newProject=>refuseFirstDeployment(client,{target,newProject,prodCommand:buildProdCommand(["init",...args],parsedArguments.flags,client.argv)}),link=await ensureLink("deploy",client,cwd,{autoConfirm,projectName:projectNameOrId??localConfig?.name,failIfNotFound:!!projectNameOrId,v0:isV0,beforeCreateProject:isNonProductionTarget(target)?()=>refuseInitFirstDeployment(!0):void 0});if(typeof link=="number")return link;let{org,project}=link,rootDirectory=project.rootDirectory,sourceFilesOutsideRootDirectory=project.sourceFilesOutsideRootDirectory??!0;link.repoRoot&&(cwd=link.repoRoot);let contextName=org.slug;if(client.config.currentTeam=org.type==="team"?org.id:void 0,isNonProductionTarget(target)&&!await hasEarlierDeployment(client,org,project.id,isRemoteLookupSkippedLink(link)?void 0:project.latestDeployments))return refuseInitFirstDeployment(!1);if(rootDirectory&&await validateRootDirectory(cwd,join4(cwd,rootDirectory),project?`To change your Project Settings, go to https://vercel.com/${org?.slug}/${project.name}/settings`:"")===!1)return 1;if(await promptExperimentalServicesMigration({client,cwd:join4(cwd,rootDirectory||""),autoConfirm:!!parsedArguments.flags["--yes"],nonInteractive:client.nonInteractive})&&(localConfig=readLocalConfig(join4(cwd,rootDirectory||""))),rootDirectory){let rootDirectoryPath=join4(cwd,rootDirectory);await compileVercelConfig(rootDirectoryPath);let rootDirectoryConfig=readLocalConfig(rootDirectoryPath);rootDirectoryConfig?(debug(`Read local config from root directory (${rootDirectory})`),localConfig=rootDirectoryConfig):localConfig&&output_manager_default.print(`${prependEmoji(`The ${highlight(localConfig[import_client.fileNameSymbol])} file should be inside of the provided root directory.`,emoji("warning"))}
10
10
  `)}localConfig=localConfig||{},localConfig.name&&output_manager_default.print(`${prependEmoji(`The ${code("name")} property in ${highlight(localConfig[import_client.fileNameSymbol])} is deprecated (https://vercel.link/name-prop)`,emoji("warning"))}
@@ -4,7 +4,7 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{require_dist as require_dist3}from"../../chunks/chunk-JELLVPCM.js";import{getCustomEnvironments}from"../../chunks/chunk-Z73UJVGD.js";import{suggestNextCommands}from"../../chunks/chunk-AMH5MXDW.js";import{formatEnvironment}from"../../chunks/chunk-YEUIG3JC.js";import{ellipsis}from"../../chunks/chunk-AKOYIH3A.js";import"../../chunks/chunk-TOTTVS5P.js";import{CHECKBOX_INSTRUCTIONS}from"../../chunks/chunk-OFDTADPQ.js";import{readStandardInput}from"../../chunks/chunk-PSOVLGHP.js";import"../../chunks/chunk-XOETL6DB.js";import{jsonNextStep,runWithJsonOutput,writeJsonResult}from"../../chunks/chunk-IL27CVNF.js";import{require_execa}from"../../chunks/chunk-M32HBBPK.js";import{formatTable}from"../../chunks/chunk-YIOMTAUF.js";import"../../chunks/chunk-7THDUCSM.js";import{stamp_default}from"../../chunks/chunk-A2RZZQEP.js";import"../../chunks/chunk-Q7D7RGXM.js";import{ENV_VISIBILITY_DEPRECATION_MESSAGE,SENSITIVE_ENV_VALUE_PLACEHOLDER,VERCEL_OIDC_TOKEN,formatVisibilityLabel,getApiPublicPrefix,getEnvKeyWarnings,getFrameworkPublicPrefix,getLocalSecretFallbackMessage,getLocalSvelteKitPublicPrefixes,getPublicPrefix,getPublicPrefixSecretVisibilityError,getUnavailableSecretValuesMessage,isFlagsSecretNeedingSplit,isSecretEnvVar,looksLikeSecret,looksLikeSecretValue,normalizeStdinEnvValue,pull,removePublicPrefix,resolveEnvVarTypeOption,resolveEnvVarVisibility,shouldConfirmRotationBeforeDelete,validateEnvValue,visibilityFromEnvType}from"../../chunks/chunk-G56HLQLB.js";import{getEnvRecords,pullEnvRecords}from"../../chunks/chunk-O2HDXF5B.js";import"../../chunks/chunk-ZKNEIE44.js";import"../../chunks/chunk-KR4DMT3I.js";import{parseTarget}from"../../chunks/chunk-HAGBKLAS.js";import"../../chunks/chunk-TT4PL5J2.js";import"../../chunks/chunk-POKRDE5J.js";import{resolveProjectContext}from"../../chunks/chunk-QQNN5X7M.js";import{STANDARD_ENVIRONMENTS}from"../../chunks/chunk-7YKFF6CE.js";import{formatProject}from"../../chunks/chunk-3UZE566G.js";import"../../chunks/chunk-SZO73QV5.js";import{isGuidanceEnabled}from"../../chunks/chunk-TAAWMNNL.js";import"../../chunks/chunk-25565AGS.js";import"../../chunks/chunk-PVASGBEF.js";import"../../chunks/chunk-O4WJDJIL.js";import"../../chunks/chunk-A5FPKXEK.js";import"../../chunks/chunk-NBTFAXL4.js";import"../../chunks/chunk-TJUZVODP.js";import"../../chunks/chunk-GD7AV7BO.js";import{buildApprovalCommand,requireApproval}from"../../chunks/chunk-JGUMBEQH.js";import"../../chunks/chunk-IG5ACFU6.js";import"../../chunks/chunk-Y4D7IX3M.js";import{getInvalidSubcommand}from"../../chunks/chunk-TG2RCYTH.js";import"../../chunks/chunk-IQ7FPAI4.js";import{trackCreatedId}from"../../chunks/chunk-YJNMDXEG.js";import{withWarnings}from"../../chunks/chunk-FSZJSIOF.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import{validateLsArgs}from"../../chunks/chunk-Q66LJNIV.js";import"../../chunks/chunk-CJZE7647.js";import"../../chunks/chunk-D44WCAOX.js";import"../../chunks/chunk-Y2FVJ7YO.js";import{getCommandAliases}from"../../chunks/chunk-6U7TRWBO.js";import"../../chunks/chunk-QOLGACFD.js";import"../../chunks/chunk-DDPH26ZO.js";import"../../chunks/chunk-PIDEH4SJ.js";import"../../chunks/chunk-IIK6GUVI.js";import"../../chunks/chunk-C35SG42R.js";import"../../chunks/chunk-2GBU6ULJ.js";import"../../chunks/chunk-EJLYDHT7.js";import"../../chunks/chunk-DOBV3XLO.js";import"../../chunks/chunk-UFCL2VBD.js";import"../../chunks/chunk-BMIYC2MH.js";import"../../chunks/chunk-6CJFPT4F.js";import"../../chunks/chunk-ZZD5W5KT.js";import"../../chunks/chunk-VHSAI6FS.js";import"../../chunks/chunk-F7L5SXJM.js";import"../../chunks/chunk-GLCSWIB4.js";import"../../chunks/chunk-XECELSF5.js";import"../../chunks/chunk-6FYPSSL4.js";import"../../chunks/chunk-UQZZX2J7.js";import"../../chunks/chunk-UDZJCD5W.js";import"../../chunks/chunk-5ZCSFPWG.js";import"../../chunks/chunk-PY4WWD6Z.js";import"../../chunks/chunk-XDYVJWGX.js";import"../../chunks/chunk-JALVF3C2.js";import{addSubcommand,envCommand,envTargetChoices,getEnvTargetPlaceholder,isValidEnvTarget,listSubcommand,parseEnvTargetArg,pullSubcommand,removeSubcommand,resolveEnvTargetInput,runSubcommand,updateSubcommand}from"../../chunks/chunk-BPIGFKNN.js";import"../../chunks/chunk-AB4WXRCO.js";import"../../chunks/chunk-SYJXONEV.js";import{printError}from"../../chunks/chunk-CY5KJ42N.js";import"../../chunks/chunk-KK5C7HVP.js";import{help}from"../../chunks/chunk-7KCRYDGK.js";import"../../chunks/chunk-GLIQ4KNY.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import"../../chunks/chunk-YJP25FL6.js";import{TelemetryClient,readLaunch}from"../../chunks/chunk-KDCODXVL.js";import"../../chunks/chunk-NWGBDBZI.js";import{buildCommandWithYes,buildEnvAddCommandWithPreservedArgs,buildEnvRmCommandWithPreservedArgs,buildEnvUpdateCommandWithPreservedArgs,getLinkSuggestionArgs,getPreservedArgsForEnvAdd,getPreservedArgsForEnvRm,getPreservedArgsForEnvUpdate,outputActionRequired,outputAgentError,redactEnvValueArgs,withGlobalFlags}from"../../chunks/chunk-PNWRO3XW.js";import"../../chunks/chunk-DTUEHPME.js";import{getLinkFromDir,getVercelDirectory}from"../../chunks/chunk-XL2PHD4X.js";import{printAlignedLabel}from"../../chunks/chunk-M7FED5YP.js";import"../../chunks/chunk-4HR3I3ML.js";import"../../chunks/chunk-LOA7SZWH.js";import"../../chunks/chunk-LUX4PBJL.js";import"../../chunks/chunk-MTZYPCZ7.js";import"../../chunks/chunk-OPORM35X.js";import"../../chunks/chunk-D6REP5QQ.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-MY4MONOH.js";import"../../chunks/chunk-7HLAWGY2.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import{parseArguments}from"../../chunks/chunk-LYL26S3N.js";import{getTeamByIdOrSlug}from"../../chunks/chunk-2VBFQZ72.js";import{validateJsonOutput}from"../../chunks/chunk-6GKP6VUF.js";import"../../chunks/chunk-4NTBYNFR.js";import"../../chunks/chunk-4SAVH3H7.js";import{isAPIError}from"../../chunks/chunk-GOI2VVI7.js";import{getCommandName,getCommandNamePlain,require_lib}from"../../chunks/chunk-B4KA3ZH2.js";import"../../chunks/chunk-BOJDM3O7.js";import{emoji,output_manager_default,prependEmoji}from"../../chunks/chunk-AP6DZGTK.js";import"../../chunks/chunk-BLUPZPAS.js";import"../../chunks/chunk-AW33SRYY.js";import{require_build_utils}from"../../chunks/chunk-5MDNVAE6.js";import"../../chunks/chunk-OCR5CRTH.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-SCV7XEEO.js";import{require_dist}from"../../chunks/chunk-MCYG7CCE.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_dist as require_dist2}from"../../chunks/chunk-24SIHFEW.js";import{getFlagsSpecification,getGlobalFlagsFromArgs,quoteArg}from"../../chunks/chunk-CFJBDBYH.js";import"../../chunks/chunk-2BKALEOP.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import{require_strip_ansi}from"../../chunks/chunk-BULSRTQE.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_chalk=__toESM(require_source(),1);var import_constants=__toESM(require_dist2(),1);async function addEnvRecord(client,projectId,upsert,type,key,value,targets,gitBranch,visibility){let actionWord=upsert?"Overriding":"Adding";output_manager_default.debug(`${actionWord} ${type} Environment Variable ${key} to ${targets.length} targets`);let target=[],customEnvironmentIds=[];for(let t of targets)(import_constants.PROJECT_ENV_TARGET.includes(t)?target:customEnvironmentIds).push(t);let body={type,key,value,target,customEnvironmentIds:customEnvironmentIds.length>0?customEnvironmentIds:void 0,gitBranch:gitBranch||void 0,...visibility!==void 0?{visibility}:{}},args=upsert?`?upsert=${upsert}`:"",url=`/v10/projects/${projectId}/env${args}`,result=await client.fetch(url,{method:"POST",body});trackCreatedId(client,"env-var",result?.created?.id)}var import_error_utils=__toESM(require_dist(),1),knownErrorsCodes=new Set(["BAD_REQUEST","ENV_ALREADY_EXISTS","ENV_CONFLICT","EXISTING_KEY_AND_TARGET","FORBIDDEN","ID_NOT_FOUND","INVALID_KEY","INVALID_VALUE","KEY_INVALID_CHARACTERS","KEY_INVALID_LENGTH","KEY_RESERVED","RESERVED_ENV_VARIABLE","MAX_ENVS_EXCEEDED","MISSING_ID","MISSING_KEY","MISSING_TARGET","MISSING_VALUE","NOT_AUTHORIZED","NOT_DECRYPTABLE","SYSTEM_ENV_WITH_VALUE","TEAM_NOT_FOUND","TOO_MANY_IDS","TOO_MANY_KEYS","UNKNOWN_ERROR","VALUE_INVALID_LENGTH","VALUE_INVALID_TYPE"]);function isKnownError(error){let code=(0,import_error_utils.isErrnoException)(error)?error.code:null;return code?knownErrorsCodes.has(code.toUpperCase()):!1}var EnvAddTelemetryClient=class extends TelemetryClient{trackCliArgumentName(name){name&&this.trackCliArgument({arg:"name",value:this.redactedValue})}trackCliArgumentEnvironment(environment){if(environment){let allStandard=environment.split(",").map(t=>t.trim()).every(t=>STANDARD_ENVIRONMENTS.includes(t));this.trackCliArgument({arg:"environment",value:allStandard?environment:this.redactedValue})}}trackCliArgumentGitBranch(gitBranch){gitBranch&&this.trackCliArgument({arg:"git-branch",value:this.redactedValue})}trackCliOptionGitBranch(gitBranch){gitBranch&&this.trackCliOption({option:"git-branch",value:this.redactedValue})}trackCliOptionEnvironment(environments){if(environments&&environments.length>0){let allStandard=environments.flatMap(environment=>environment.split(",")).map(t=>t.trim()).every(t=>STANDARD_ENVIRONMENTS.includes(t));this.trackCliOption({option:"environment",value:allStandard?environments.join(","):this.redactedValue})}}trackCliOptionValue(value){value&&this.trackCliOption({option:"value",value:this.redactedValue})}trackCliOptionVisibility(visibility){if(visibility){let validVisibilities=["config","secret"];this.trackCliOption({option:"visibility",value:validVisibilities.includes(visibility)?visibility:this.redactedValue})}}trackCliOptionType(type){if(type){let validTypes=["config","secret"];this.trackCliOption({option:"type",value:validTypes.includes(type)?type:this.redactedValue})}}trackCliFlagSensitive(sensitive){sensitive&&this.trackCliFlag("sensitive")}trackCliFlagNoSensitive(noSensitive){noSensitive&&this.trackCliFlag("no-sensitive")}trackCliFlagForce(force){force&&this.trackCliFlag("force")}trackCliFlagGuidance(guidance){guidance&&this.trackCliFlag("guidance")}trackCliFlagYes(yes){yes&&this.trackCliFlag("yes")}trackCliFlagJson(json){json&&this.trackCliFlag("json")}};import{determineAgent}from"@vercel/detect-agent";function includesDevelopment(targets){return targets.length===0||targets.includes("development")}function getProductionSecretPolicyErrorKind(message){return/production secrets?.*different value|different value.*production secrets?/i.test(message)?"different-values":/production secrets?.*(?:own environment group|separat)|(?:own environment group|separat).*production secrets?/i.test(message)?"separate-environments":null}function getProductionSecretPolicyRecovery(kind){return kind==="different-values"?"Use different Secret values for Production and non-Production.":"Create separate Production and non-Production variables with different values."}function getSecretStorageChoice(targets,recommendedReason){let availability=includesDevelopment(targets)?"hidden in the dashboard; Development values can be pulled":"hidden in the dashboard and unavailable to pulls",recommendation=recommendedReason?`; recommended ${recommendedReason}`:"";return`Secret (${availability}${recommendation})`}function getDefaultSecretStorageGuidance(targets){return includesDevelopment(targets)?"Stored as Secret by default. This value is hidden in the dashboard; Development values can be pulled. Use `--type config` for other values you need to read later.":"Stored as Secret by default. This value is hidden in the dashboard and unavailable to pulls; use `--type config` for values you need to read later."}var import_strip_ansi=__toESM(require_strip_ansi(),1);function looksLikeCredentialName(key,publicPrefix=getPublicPrefix(key)){return looksLikeSecret(publicPrefix?key.slice(publicPrefix.length):key)}function filterEnvChoicesForSensitivity(choices,opts){return opts.policyOn?choices.filter(c=>c.value==="development"):choices}function getTargetCompatibilityError(envTargets,isSensitive,policyOn){let hasSensitiveCapable=envTargets.some(t=>t!=="development");return!isSensitive&&policyOn&&hasSensitiveCapable?`Your team requires sensitive Environment Variables for Production and Preview. To add a non-sensitive value, add it to the Development Environment only. Run ${getCommandName("env add --environment development")} instead.`:null}function resolveFinalType(envTargets,isSensitive,opts){return envTargets.includes("development")&&!isSensitive||opts.forceEncrypted&&!opts.policyOn?"encrypted":isSensitive||opts.forceSensitive||opts.policyOn?"sensitive":"encrypted"}function fillEnvAddTemplate(template,opts){let targetPlaceholder=getEnvTargetPlaceholder();return template.replace(/<name>/g,opts.envName?quoteArg(opts.envName):"<name>").split(targetPlaceholder).join(opts.envTargetArg?quoteArg(opts.envTargetArg):targetPlaceholder).replace(/<BRANCH>/g,opts.envGitBranch?quoteArg(opts.envGitBranch):"<BRANCH>").replace(/<value>/g,"<value>")}function multiTargetSuggestion(argv,envName,targets,addNoSensitive){let flag=addNoSensitive?" --no-sensitive":"";return{command:buildEnvAddCommandWithPreservedArgs(argv,`env add ${envName} --environment ${targets.join(",")} --value "<value>"${flag} --yes`),when:addNoSensitive?"Add one non-sensitive variable to all listed environments":"Add one variable to multiple environments"}}function filterSensitiveMultiTargetSuggestionTargets(targets,_opts){return targets}function projectLabel(link){return`${link.org.slug}/${link.project.name}`}function formatEnvironmentTarget(target,customEnvironments){let standardTarget=envTargetChoices.find(choice=>choice.value===target);return standardTarget?standardTarget.name:customEnvironments.find(env=>env.id===target||env.slug===target)?.slug??target}function formatEnvironmentTargets(envTargets,customEnvironments){return envTargets.map(target=>formatEnvironmentTarget(target,customEnvironments)).join(", ")}function printEnvAddResult(link,envName,envTargets,envGitBranch,customEnvironments,finalType,force,visibility){output_manager_default.print(`
7
+ import{require_dist as require_dist3}from"../../chunks/chunk-JELLVPCM.js";import{getCustomEnvironments}from"../../chunks/chunk-Z73UJVGD.js";import{suggestNextCommands}from"../../chunks/chunk-AMH5MXDW.js";import{formatEnvironment}from"../../chunks/chunk-YEUIG3JC.js";import{ellipsis}from"../../chunks/chunk-AKOYIH3A.js";import"../../chunks/chunk-TOTTVS5P.js";import{CHECKBOX_INSTRUCTIONS}from"../../chunks/chunk-OFDTADPQ.js";import{readStandardInput}from"../../chunks/chunk-PSOVLGHP.js";import"../../chunks/chunk-XOETL6DB.js";import{jsonNextStep,runWithJsonOutput,writeJsonResult}from"../../chunks/chunk-IL27CVNF.js";import{require_execa}from"../../chunks/chunk-M32HBBPK.js";import{formatTable}from"../../chunks/chunk-YIOMTAUF.js";import"../../chunks/chunk-7THDUCSM.js";import{stamp_default}from"../../chunks/chunk-A2RZZQEP.js";import"../../chunks/chunk-Q7D7RGXM.js";import{ENV_VISIBILITY_DEPRECATION_MESSAGE,SENSITIVE_ENV_VALUE_PLACEHOLDER,VERCEL_OIDC_TOKEN,formatVisibilityLabel,getApiPublicPrefix,getEnvKeyWarnings,getFrameworkPublicPrefix,getLocalSecretFallbackMessage,getLocalSvelteKitPublicPrefixes,getPublicPrefix,getPublicPrefixSecretVisibilityError,getUnavailableSecretValuesMessage,isFlagsSecretNeedingSplit,isSecretEnvVar,looksLikeSecret,looksLikeSecretValue,normalizeStdinEnvValue,pull,removePublicPrefix,resolveEnvVarTypeOption,resolveEnvVarVisibility,shouldConfirmRotationBeforeDelete,validateEnvValue,visibilityFromEnvType}from"../../chunks/chunk-G56HLQLB.js";import{getEnvRecords,pullEnvRecords}from"../../chunks/chunk-O2HDXF5B.js";import"../../chunks/chunk-ZKNEIE44.js";import"../../chunks/chunk-KR4DMT3I.js";import{parseTarget}from"../../chunks/chunk-HAGBKLAS.js";import"../../chunks/chunk-TT4PL5J2.js";import"../../chunks/chunk-POKRDE5J.js";import{resolveProjectContext}from"../../chunks/chunk-QQNN5X7M.js";import{STANDARD_ENVIRONMENTS}from"../../chunks/chunk-7YKFF6CE.js";import{formatProject}from"../../chunks/chunk-3UZE566G.js";import"../../chunks/chunk-SZO73QV5.js";import{isGuidanceEnabled}from"../../chunks/chunk-TAAWMNNL.js";import"../../chunks/chunk-25565AGS.js";import"../../chunks/chunk-PVASGBEF.js";import"../../chunks/chunk-O4WJDJIL.js";import"../../chunks/chunk-A5FPKXEK.js";import"../../chunks/chunk-NBTFAXL4.js";import"../../chunks/chunk-TJUZVODP.js";import"../../chunks/chunk-GD7AV7BO.js";import{buildApprovalCommand,requireApproval}from"../../chunks/chunk-JGUMBEQH.js";import"../../chunks/chunk-IG5ACFU6.js";import"../../chunks/chunk-Y4D7IX3M.js";import{getInvalidSubcommand}from"../../chunks/chunk-TG2RCYTH.js";import"../../chunks/chunk-IQ7FPAI4.js";import{trackCreatedId}from"../../chunks/chunk-YJNMDXEG.js";import{withWarnings}from"../../chunks/chunk-FSZJSIOF.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import{validateLsArgs}from"../../chunks/chunk-Q66LJNIV.js";import"../../chunks/chunk-CJZE7647.js";import"../../chunks/chunk-D44WCAOX.js";import"../../chunks/chunk-Y2FVJ7YO.js";import{getCommandAliases}from"../../chunks/chunk-HVFGIJ44.js";import"../../chunks/chunk-QOLGACFD.js";import"../../chunks/chunk-DDPH26ZO.js";import"../../chunks/chunk-PIDEH4SJ.js";import"../../chunks/chunk-IIK6GUVI.js";import"../../chunks/chunk-C35SG42R.js";import"../../chunks/chunk-2GBU6ULJ.js";import"../../chunks/chunk-EJLYDHT7.js";import"../../chunks/chunk-DOBV3XLO.js";import"../../chunks/chunk-TUB3APDV.js";import"../../chunks/chunk-BMIYC2MH.js";import"../../chunks/chunk-6CJFPT4F.js";import"../../chunks/chunk-ZZD5W5KT.js";import"../../chunks/chunk-VHSAI6FS.js";import"../../chunks/chunk-F7L5SXJM.js";import"../../chunks/chunk-GLCSWIB4.js";import"../../chunks/chunk-XECELSF5.js";import"../../chunks/chunk-6FYPSSL4.js";import"../../chunks/chunk-UQZZX2J7.js";import"../../chunks/chunk-UDZJCD5W.js";import"../../chunks/chunk-5ZCSFPWG.js";import"../../chunks/chunk-PY4WWD6Z.js";import"../../chunks/chunk-XDYVJWGX.js";import"../../chunks/chunk-JALVF3C2.js";import{addSubcommand,envCommand,envTargetChoices,getEnvTargetPlaceholder,isValidEnvTarget,listSubcommand,parseEnvTargetArg,pullSubcommand,removeSubcommand,resolveEnvTargetInput,runSubcommand,updateSubcommand}from"../../chunks/chunk-BPIGFKNN.js";import"../../chunks/chunk-AB4WXRCO.js";import"../../chunks/chunk-SYJXONEV.js";import{printError}from"../../chunks/chunk-CY5KJ42N.js";import"../../chunks/chunk-KK5C7HVP.js";import{help}from"../../chunks/chunk-7KCRYDGK.js";import"../../chunks/chunk-GLIQ4KNY.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import"../../chunks/chunk-YJP25FL6.js";import{TelemetryClient,readLaunch}from"../../chunks/chunk-KDCODXVL.js";import"../../chunks/chunk-NWGBDBZI.js";import{buildCommandWithYes,buildEnvAddCommandWithPreservedArgs,buildEnvRmCommandWithPreservedArgs,buildEnvUpdateCommandWithPreservedArgs,getLinkSuggestionArgs,getPreservedArgsForEnvAdd,getPreservedArgsForEnvRm,getPreservedArgsForEnvUpdate,outputActionRequired,outputAgentError,redactEnvValueArgs,withGlobalFlags}from"../../chunks/chunk-PNWRO3XW.js";import"../../chunks/chunk-DTUEHPME.js";import{getLinkFromDir,getVercelDirectory}from"../../chunks/chunk-XL2PHD4X.js";import{printAlignedLabel}from"../../chunks/chunk-M7FED5YP.js";import"../../chunks/chunk-4HR3I3ML.js";import"../../chunks/chunk-LOA7SZWH.js";import"../../chunks/chunk-LUX4PBJL.js";import"../../chunks/chunk-MTZYPCZ7.js";import"../../chunks/chunk-OPORM35X.js";import"../../chunks/chunk-D6REP5QQ.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-MY4MONOH.js";import"../../chunks/chunk-7HLAWGY2.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import{parseArguments}from"../../chunks/chunk-LYL26S3N.js";import{getTeamByIdOrSlug}from"../../chunks/chunk-2VBFQZ72.js";import{validateJsonOutput}from"../../chunks/chunk-6GKP6VUF.js";import"../../chunks/chunk-4NTBYNFR.js";import"../../chunks/chunk-4SAVH3H7.js";import{isAPIError}from"../../chunks/chunk-GOI2VVI7.js";import{getCommandName,getCommandNamePlain,require_lib}from"../../chunks/chunk-B4KA3ZH2.js";import"../../chunks/chunk-BOJDM3O7.js";import{emoji,output_manager_default,prependEmoji}from"../../chunks/chunk-AP6DZGTK.js";import"../../chunks/chunk-BLUPZPAS.js";import"../../chunks/chunk-AW33SRYY.js";import{require_build_utils}from"../../chunks/chunk-5MDNVAE6.js";import"../../chunks/chunk-OCR5CRTH.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-SCV7XEEO.js";import{require_dist}from"../../chunks/chunk-MCYG7CCE.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_dist as require_dist2}from"../../chunks/chunk-24SIHFEW.js";import{getFlagsSpecification,getGlobalFlagsFromArgs,quoteArg}from"../../chunks/chunk-CFJBDBYH.js";import"../../chunks/chunk-2BKALEOP.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import{require_strip_ansi}from"../../chunks/chunk-BULSRTQE.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_chalk=__toESM(require_source(),1);var import_constants=__toESM(require_dist2(),1);async function addEnvRecord(client,projectId,upsert,type,key,value,targets,gitBranch,visibility){let actionWord=upsert?"Overriding":"Adding";output_manager_default.debug(`${actionWord} ${type} Environment Variable ${key} to ${targets.length} targets`);let target=[],customEnvironmentIds=[];for(let t of targets)(import_constants.PROJECT_ENV_TARGET.includes(t)?target:customEnvironmentIds).push(t);let body={type,key,value,target,customEnvironmentIds:customEnvironmentIds.length>0?customEnvironmentIds:void 0,gitBranch:gitBranch||void 0,...visibility!==void 0?{visibility}:{}},args=upsert?`?upsert=${upsert}`:"",url=`/v10/projects/${projectId}/env${args}`,result=await client.fetch(url,{method:"POST",body});trackCreatedId(client,"env-var",result?.created?.id)}var import_error_utils=__toESM(require_dist(),1),knownErrorsCodes=new Set(["BAD_REQUEST","ENV_ALREADY_EXISTS","ENV_CONFLICT","EXISTING_KEY_AND_TARGET","FORBIDDEN","ID_NOT_FOUND","INVALID_KEY","INVALID_VALUE","KEY_INVALID_CHARACTERS","KEY_INVALID_LENGTH","KEY_RESERVED","RESERVED_ENV_VARIABLE","MAX_ENVS_EXCEEDED","MISSING_ID","MISSING_KEY","MISSING_TARGET","MISSING_VALUE","NOT_AUTHORIZED","NOT_DECRYPTABLE","SYSTEM_ENV_WITH_VALUE","TEAM_NOT_FOUND","TOO_MANY_IDS","TOO_MANY_KEYS","UNKNOWN_ERROR","VALUE_INVALID_LENGTH","VALUE_INVALID_TYPE"]);function isKnownError(error){let code=(0,import_error_utils.isErrnoException)(error)?error.code:null;return code?knownErrorsCodes.has(code.toUpperCase()):!1}var EnvAddTelemetryClient=class extends TelemetryClient{trackCliArgumentName(name){name&&this.trackCliArgument({arg:"name",value:this.redactedValue})}trackCliArgumentEnvironment(environment){if(environment){let allStandard=environment.split(",").map(t=>t.trim()).every(t=>STANDARD_ENVIRONMENTS.includes(t));this.trackCliArgument({arg:"environment",value:allStandard?environment:this.redactedValue})}}trackCliArgumentGitBranch(gitBranch){gitBranch&&this.trackCliArgument({arg:"git-branch",value:this.redactedValue})}trackCliOptionGitBranch(gitBranch){gitBranch&&this.trackCliOption({option:"git-branch",value:this.redactedValue})}trackCliOptionEnvironment(environments){if(environments&&environments.length>0){let allStandard=environments.flatMap(environment=>environment.split(",")).map(t=>t.trim()).every(t=>STANDARD_ENVIRONMENTS.includes(t));this.trackCliOption({option:"environment",value:allStandard?environments.join(","):this.redactedValue})}}trackCliOptionValue(value){value&&this.trackCliOption({option:"value",value:this.redactedValue})}trackCliOptionVisibility(visibility){if(visibility){let validVisibilities=["config","secret"];this.trackCliOption({option:"visibility",value:validVisibilities.includes(visibility)?visibility:this.redactedValue})}}trackCliOptionType(type){if(type){let validTypes=["config","secret"];this.trackCliOption({option:"type",value:validTypes.includes(type)?type:this.redactedValue})}}trackCliFlagSensitive(sensitive){sensitive&&this.trackCliFlag("sensitive")}trackCliFlagNoSensitive(noSensitive){noSensitive&&this.trackCliFlag("no-sensitive")}trackCliFlagForce(force){force&&this.trackCliFlag("force")}trackCliFlagGuidance(guidance){guidance&&this.trackCliFlag("guidance")}trackCliFlagYes(yes){yes&&this.trackCliFlag("yes")}trackCliFlagJson(json){json&&this.trackCliFlag("json")}};import{determineAgent}from"@vercel/detect-agent";function includesDevelopment(targets){return targets.length===0||targets.includes("development")}function getProductionSecretPolicyErrorKind(message){return/production secrets?.*different value|different value.*production secrets?/i.test(message)?"different-values":/production secrets?.*(?:own environment group|separat)|(?:own environment group|separat).*production secrets?/i.test(message)?"separate-environments":null}function getProductionSecretPolicyRecovery(kind){return kind==="different-values"?"Use different Secret values for Production and non-Production.":"Create separate Production and non-Production variables with different values."}function getSecretStorageChoice(targets,recommendedReason){let availability=includesDevelopment(targets)?"hidden in the dashboard; Development values can be pulled":"hidden in the dashboard and unavailable to pulls",recommendation=recommendedReason?`; recommended ${recommendedReason}`:"";return`Secret (${availability}${recommendation})`}function getDefaultSecretStorageGuidance(targets){return includesDevelopment(targets)?"Stored as Secret by default. This value is hidden in the dashboard; Development values can be pulled. Use `--type config` for other values you need to read later.":"Stored as Secret by default. This value is hidden in the dashboard and unavailable to pulls; use `--type config` for values you need to read later."}var import_strip_ansi=__toESM(require_strip_ansi(),1);function looksLikeCredentialName(key,publicPrefix=getPublicPrefix(key)){return looksLikeSecret(publicPrefix?key.slice(publicPrefix.length):key)}function filterEnvChoicesForSensitivity(choices,opts){return opts.policyOn?choices.filter(c=>c.value==="development"):choices}function getTargetCompatibilityError(envTargets,isSensitive,policyOn){let hasSensitiveCapable=envTargets.some(t=>t!=="development");return!isSensitive&&policyOn&&hasSensitiveCapable?`Your team requires sensitive Environment Variables for Production and Preview. To add a non-sensitive value, add it to the Development Environment only. Run ${getCommandName("env add --environment development")} instead.`:null}function resolveFinalType(envTargets,isSensitive,opts){return envTargets.includes("development")&&!isSensitive||opts.forceEncrypted&&!opts.policyOn?"encrypted":isSensitive||opts.forceSensitive||opts.policyOn?"sensitive":"encrypted"}function fillEnvAddTemplate(template,opts){let targetPlaceholder=getEnvTargetPlaceholder();return template.replace(/<name>/g,opts.envName?quoteArg(opts.envName):"<name>").split(targetPlaceholder).join(opts.envTargetArg?quoteArg(opts.envTargetArg):targetPlaceholder).replace(/<BRANCH>/g,opts.envGitBranch?quoteArg(opts.envGitBranch):"<BRANCH>").replace(/<value>/g,"<value>")}function multiTargetSuggestion(argv,envName,targets,addNoSensitive){let flag=addNoSensitive?" --no-sensitive":"";return{command:buildEnvAddCommandWithPreservedArgs(argv,`env add ${envName} --environment ${targets.join(",")} --value "<value>"${flag} --yes`),when:addNoSensitive?"Add one non-sensitive variable to all listed environments":"Add one variable to multiple environments"}}function filterSensitiveMultiTargetSuggestionTargets(targets,_opts){return targets}function projectLabel(link){return`${link.org.slug}/${link.project.name}`}function formatEnvironmentTarget(target,customEnvironments){let standardTarget=envTargetChoices.find(choice=>choice.value===target);return standardTarget?standardTarget.name:customEnvironments.find(env=>env.id===target||env.slug===target)?.slug??target}function formatEnvironmentTargets(envTargets,customEnvironments){return envTargets.map(target=>formatEnvironmentTarget(target,customEnvironments)).join(", ")}function printEnvAddResult(link,envName,envTargets,envGitBranch,customEnvironments,finalType,force,visibility){output_manager_default.print(`
8
8
  `),printAlignedLabel(force?"Overrode":"Added",envName,{gutter:"\u2713"}),printAlignedLabel("Project",projectLabel(link)),printAlignedLabel("Environments",formatEnvironmentTargets(envTargets,customEnvironments)),envGitBranch&&printAlignedLabel("Branch",envGitBranch);let visibilityLabel=formatVisibilityLabel(visibility,finalType);visibilityLabel&&printAlignedLabel("Type",visibilityLabel)}var jsonWarnings;function printEnvAddWarning(message,reason){jsonWarnings?.push({reason,message:(0,import_strip_ansi.default)(message)}),output_manager_default.print(`${import_chalk.default.yellow("!")} ${message}
9
9
  `)}function promptEnvValue(client,opts){return client.input.text({message:"Value?",...opts.isSensitive?{transformer:value=>"*".repeat(value.length)}:{}})}function buildHumanEnvAddCommand(argv,commandTemplate){let globalFlags=getGlobalFlagsFromArgs(argv.slice(2),{preserveProject:!0}).filter(flag=>!flag.startsWith("--non-interactive")),suffix=globalFlags.length>0?` ${globalFlags.map(quoteArg).join(" ")}`:"";return getCommandNamePlain(`${commandTemplate}${suffix}`)}function isBranchNotFoundError(err){if([err.code,err.slug].filter(v=>typeof v=="string").some(c=>c.toLowerCase()==="branch_not_found"))return!0;let message=(err.serverMessage??"").toLowerCase();return message.includes("branch")&&/not found|(?:doesn't|does not) exist/.test(message)}function branchNotFoundMessage(branch){return`Branch ${branch} was not found in the connected Git repository.`}function branchNotFoundRecovery(branch){return`Push ${branch} to the remote, then run the command again. Or omit --git-branch to apply the variable to all Preview branches.`}function omitGitBranchArgs(argv){let out=[];for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg==="--git-branch"){i+1<argv.length&&!argv[i+1].startsWith("-")&&i++;continue}arg.startsWith("--git-branch=")||out.push(arg)}return out}function buildBranchNotFoundNext(argv,envName,branch){let name=quoteArg(envName);return[{command:buildEnvAddCommandWithPreservedArgs(argv,`env add ${name} --environment preview --git-branch ${quoteArg(branch)} --value "<value>"`),when:`Add the variable after pushing ${branch} to the remote`},{command:buildEnvAddCommandWithPreservedArgs(omitGitBranchArgs(argv),`env add ${name} --environment preview --value "<value>"`),when:"Add the variable to all Preview branches"}]}async function add(client,argv){if(argv.includes("--json")){jsonWarnings=[];try{return await runWithJsonOutput(client,()=>addEnv(client,argv,!0))}finally{jsonWarnings=void 0}}return addEnv(client,argv,!1)}async function addEnv(client,argv,json){let parsedArgs,flagsSpecification=getFlagsSpecification(addSubcommand.options);try{parsedArgs=parseArguments(argv,flagsSpecification)}catch(err){return client.nonInteractive&&outputAgentError(client,{status:"error",reason:"invalid_arguments",message:err instanceof Error?err.message:String(err)},2),printError(err),2}let{args,flags:opts}=parsedArgs,valueFromFlag=typeof opts["--value"]=="string"?opts["--value"]:void 0,stdInput=valueFromFlag===void 0?await readStandardInput(client.stdin):"",[envName]=args,positionalEnvironment=args[1],positionalGitBranch=args[2],optionGitBranch=typeof opts["--git-branch"]=="string"?opts["--git-branch"]:void 0,forceSensitive=!!opts["--sensitive"],forceEncrypted=!!opts["--no-sensitive"],typeOption=resolveEnvVarTypeOption({type:typeof opts["--type"]=="string"?opts["--type"]:void 0,visibility:typeof opts["--visibility"]=="string"?opts["--visibility"]:void 0}),explicitType=typeOption.explicitVisibility,typeSource=explicitType||forceSensitive||forceEncrypted?"argv":void 0,telemetryClient=new EnvAddTelemetryClient({opts:{store:client.telemetryEventStore}});if(telemetryClient.trackCliArgumentName(envName),telemetryClient.trackCliArgumentEnvironment(positionalEnvironment),telemetryClient.trackCliArgumentGitBranch(positionalGitBranch),telemetryClient.trackCliOptionEnvironment(opts["--environment"]),telemetryClient.trackCliOptionGitBranch(optionGitBranch),telemetryClient.trackCliOptionValue(valueFromFlag===void 0?void 0:"<redacted>"),telemetryClient.trackCliFlagSensitive(opts["--sensitive"]),telemetryClient.trackCliFlagNoSensitive(opts["--no-sensitive"]),telemetryClient.trackCliFlagForce(opts["--force"]),telemetryClient.trackCliFlagGuidance(opts["--guidance"]),telemetryClient.trackCliFlagYes(opts["--yes"]),telemetryClient.trackCliOptionType(typeof opts["--type"]=="string"?opts["--type"]:void 0),telemetryClient.trackCliOptionVisibility(typeof opts["--visibility"]=="string"?opts["--visibility"]:void 0),telemetryClient.trackCliOptionProject(opts["--project"]),telemetryClient.trackCliFlagJson(opts["--json"]),typeOption.error)return client.nonInteractive&&outputAgentError(client,{status:"error",reason:typeOption.errorReason??"invalid_type",message:typeOption.error},1),output_manager_default.fatal(typeOption.error),1;typeOption.usedDeprecatedVisibility&&printEnvAddWarning(ENV_VISIBILITY_DEPRECATION_MESSAGE,"deprecated");let typeConflictMessage=forceSensitive?forceEncrypted?"`--sensitive` and `--no-sensitive` cannot be used together. Pick one.":explicitType==="config"?"`--type config` cannot be used with `--sensitive`. Pick one.":null:forceEncrypted&&explicitType==="secret"?"`--type secret` cannot be used with `--no-sensitive`. Pick one.":null;if(typeConflictMessage)return client.nonInteractive&&outputAgentError(client,{status:"error",reason:"conflicting_type_flags",message:typeConflictMessage},2),output_manager_default.fatal(typeConflictMessage),2;if(positionalEnvironment!==void 0&&!parseEnvTargetArg(positionalEnvironment).every(part=>isValidEnvTarget(part))){let message="The environment argument accepts only production, preview, or development. Use --environment for custom environments, and pass the value with --value or stdin.",command=buildEnvAddCommandWithPreservedArgs(redactEnvValueArgs(client.argv),`env add ${envName?quoteArg(envName):"<name>"} --environment ${getEnvTargetPlaceholder()} --value "<value>"`);return client.nonInteractive&&outputAgentError(client,{status:"error",reason:"invalid_arguments",message,next:[{command,when:"replace the placeholders, then run"}]},2),output_manager_default.error(message),output_manager_default.print(`
10
10
  Replace the placeholders, then run:
@@ -4,7 +4,7 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{promptExperimentalServicesMigration}from"../../chunks/chunk-HIV3C763.js";import"../../chunks/chunk-DMZLFZBX.js";import"../../chunks/chunk-A7E3EGDM.js";import"../../chunks/chunk-WCCKCQ43.js";import"../../chunks/chunk-U4Z2MMOF.js";import"../../chunks/chunk-J24BABG4.js";import{jsonNextStep,runWithJsonOutput,writeJsonResult,writeJsonUsageError}from"../../chunks/chunk-IL27CVNF.js";import"../../chunks/chunk-7THDUCSM.js";import"../../chunks/chunk-AMOI3EAW.js";import"../../chunks/chunk-REJLEESP.js";import"../../chunks/chunk-ISSNEDG5.js";import{pull}from"../../chunks/chunk-G56HLQLB.js";import"../../chunks/chunk-O2HDXF5B.js";import"../../chunks/chunk-ZKNEIE44.js";import"../../chunks/chunk-KR4DMT3I.js";import"../../chunks/chunk-HAGBKLAS.js";import"../../chunks/chunk-TT4PL5J2.js";import"../../chunks/chunk-POKRDE5J.js";import"../../chunks/chunk-QQNN5X7M.js";import"../../chunks/chunk-7YKFF6CE.js";import"../../chunks/chunk-3UZE566G.js";import"../../chunks/chunk-SZO73QV5.js";import"../../chunks/chunk-TAAWMNNL.js";import"../../chunks/chunk-25565AGS.js";import"../../chunks/chunk-PVASGBEF.js";import{ensureLink}from"../../chunks/chunk-O4WJDJIL.js";import"../../chunks/chunk-A5FPKXEK.js";import"../../chunks/chunk-NBTFAXL4.js";import"../../chunks/chunk-TJUZVODP.js";import"../../chunks/chunk-FSZJSIOF.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-Y2FVJ7YO.js";import{getCommandAliases}from"../../chunks/chunk-6U7TRWBO.js";import"../../chunks/chunk-QOLGACFD.js";import"../../chunks/chunk-DDPH26ZO.js";import"../../chunks/chunk-PIDEH4SJ.js";import"../../chunks/chunk-IIK6GUVI.js";import"../../chunks/chunk-C35SG42R.js";import"../../chunks/chunk-2GBU6ULJ.js";import"../../chunks/chunk-EJLYDHT7.js";import"../../chunks/chunk-DOBV3XLO.js";import"../../chunks/chunk-UFCL2VBD.js";import"../../chunks/chunk-BMIYC2MH.js";import"../../chunks/chunk-6CJFPT4F.js";import"../../chunks/chunk-ZZD5W5KT.js";import"../../chunks/chunk-VHSAI6FS.js";import"../../chunks/chunk-F7L5SXJM.js";import"../../chunks/chunk-GLCSWIB4.js";import"../../chunks/chunk-XECELSF5.js";import"../../chunks/chunk-6FYPSSL4.js";import"../../chunks/chunk-UQZZX2J7.js";import"../../chunks/chunk-UDZJCD5W.js";import"../../chunks/chunk-5ZCSFPWG.js";import"../../chunks/chunk-PY4WWD6Z.js";import"../../chunks/chunk-XDYVJWGX.js";import"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-BPIGFKNN.js";import"../../chunks/chunk-AB4WXRCO.js";import"../../chunks/chunk-SYJXONEV.js";import{printError}from"../../chunks/chunk-CY5KJ42N.js";import"../../chunks/chunk-KK5C7HVP.js";import{help}from"../../chunks/chunk-7KCRYDGK.js";import"../../chunks/chunk-GLIQ4KNY.js";import"../../chunks/chunk-3G3FQYMW.js";import{detectExplicitScope,getScope}from"../../chunks/chunk-YJP25FL6.js";import{TelemetryClient}from"../../chunks/chunk-KDCODXVL.js";import"../../chunks/chunk-NWGBDBZI.js";import{AGENT_REASON,AGENT_STATUS,buildCommandWithYes,getExitCodeForReason,writeActionRequired}from"../../chunks/chunk-PNWRO3XW.js";import{addSubcommand,linkCommand}from"../../chunks/chunk-DTUEHPME.js";import{addRepoLink,ensureRepoLink,findRepoRoot,getLinkedProjectIdSync,getVercelDirectory,isPromptCanceledError,resolveProjectCwd}from"../../chunks/chunk-XL2PHD4X.js";import"../../chunks/chunk-M7FED5YP.js";import"../../chunks/chunk-4HR3I3ML.js";import"../../chunks/chunk-LOA7SZWH.js";import"../../chunks/chunk-LUX4PBJL.js";import"../../chunks/chunk-MTZYPCZ7.js";import"../../chunks/chunk-OPORM35X.js";import"../../chunks/chunk-D6REP5QQ.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-MY4MONOH.js";import"../../chunks/chunk-7HLAWGY2.js";import"../../chunks/chunk-MXTC4ZAQ.js";import{parseArguments}from"../../chunks/chunk-LYL26S3N.js";import"../../chunks/chunk-2VBFQZ72.js";import"../../chunks/chunk-6GKP6VUF.js";import"../../chunks/chunk-4NTBYNFR.js";import"../../chunks/chunk-4SAVH3H7.js";import"../../chunks/chunk-GOI2VVI7.js";import{cmd}from"../../chunks/chunk-B4KA3ZH2.js";import"../../chunks/chunk-BOJDM3O7.js";import{output_manager_default}from"../../chunks/chunk-AP6DZGTK.js";import"../../chunks/chunk-BLUPZPAS.js";import"../../chunks/chunk-AW33SRYY.js";import{require_build_utils}from"../../chunks/chunk-5MDNVAE6.js";import"../../chunks/chunk-OCR5CRTH.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-SCV7XEEO.js";import"../../chunks/chunk-MCYG7CCE.js";import"../../chunks/chunk-YHPPP3SF.js";import"../../chunks/chunk-24SIHFEW.js";import{getFlagsSpecification}from"../../chunks/chunk-CFJBDBYH.js";import"../../chunks/chunk-2BKALEOP.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import"../../chunks/chunk-BULSRTQE.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_chalk=__toESM(require_source(),1);import{join}from"path";var LinkTelemetryClient=class extends TelemetryClient{trackCliArgumentCwd(){this.trackCliArgument({arg:"cwd",value:this.redactedValue})}trackCliFlagRepo(flag){flag&&this.trackCliFlag("repo")}trackCliFlagYes(yes){yes&&this.trackCliFlag("yes")}trackCliFlagConfirm(flag){flag&&this.trackCliFlag("confirm")}trackCliOptionTeam(value){value&&this.trackCliOption({option:"team",value:this.redactedValue})}trackCliOptionProjectId(value){value&&this.trackCliOption({option:"project-id",value:this.redactedValue})}trackCliSubcommandAdd(actual){this.trackCliSubcommand({subcommand:"add",value:actual})}trackCliFlagJson(json){json&&this.trackCliFlag("json")}};var import_build_utils=__toESM(require_build_utils(),1);var COMMAND_CONFIG={add:getCommandAliases(addSubcommand)};function warnOidcRefreshFailed(){output_manager_default.print(`${import_chalk.default.yellow("!")} Linked project, but failed to refresh VERCEL_OIDC_TOKEN in .env.local. Rerun the link command to retry.
7
+ import{promptExperimentalServicesMigration}from"../../chunks/chunk-HIV3C763.js";import"../../chunks/chunk-DMZLFZBX.js";import"../../chunks/chunk-A7E3EGDM.js";import"../../chunks/chunk-WCCKCQ43.js";import"../../chunks/chunk-U4Z2MMOF.js";import"../../chunks/chunk-J24BABG4.js";import{jsonNextStep,runWithJsonOutput,writeJsonResult,writeJsonUsageError}from"../../chunks/chunk-IL27CVNF.js";import"../../chunks/chunk-7THDUCSM.js";import"../../chunks/chunk-AMOI3EAW.js";import"../../chunks/chunk-REJLEESP.js";import"../../chunks/chunk-ISSNEDG5.js";import{pull}from"../../chunks/chunk-G56HLQLB.js";import"../../chunks/chunk-O2HDXF5B.js";import"../../chunks/chunk-ZKNEIE44.js";import"../../chunks/chunk-KR4DMT3I.js";import"../../chunks/chunk-HAGBKLAS.js";import"../../chunks/chunk-TT4PL5J2.js";import"../../chunks/chunk-POKRDE5J.js";import"../../chunks/chunk-QQNN5X7M.js";import"../../chunks/chunk-7YKFF6CE.js";import"../../chunks/chunk-3UZE566G.js";import"../../chunks/chunk-SZO73QV5.js";import"../../chunks/chunk-TAAWMNNL.js";import"../../chunks/chunk-25565AGS.js";import"../../chunks/chunk-PVASGBEF.js";import{ensureLink}from"../../chunks/chunk-O4WJDJIL.js";import"../../chunks/chunk-A5FPKXEK.js";import"../../chunks/chunk-NBTFAXL4.js";import"../../chunks/chunk-TJUZVODP.js";import"../../chunks/chunk-FSZJSIOF.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-Y2FVJ7YO.js";import{getCommandAliases}from"../../chunks/chunk-HVFGIJ44.js";import"../../chunks/chunk-QOLGACFD.js";import"../../chunks/chunk-DDPH26ZO.js";import"../../chunks/chunk-PIDEH4SJ.js";import"../../chunks/chunk-IIK6GUVI.js";import"../../chunks/chunk-C35SG42R.js";import"../../chunks/chunk-2GBU6ULJ.js";import"../../chunks/chunk-EJLYDHT7.js";import"../../chunks/chunk-DOBV3XLO.js";import"../../chunks/chunk-TUB3APDV.js";import"../../chunks/chunk-BMIYC2MH.js";import"../../chunks/chunk-6CJFPT4F.js";import"../../chunks/chunk-ZZD5W5KT.js";import"../../chunks/chunk-VHSAI6FS.js";import"../../chunks/chunk-F7L5SXJM.js";import"../../chunks/chunk-GLCSWIB4.js";import"../../chunks/chunk-XECELSF5.js";import"../../chunks/chunk-6FYPSSL4.js";import"../../chunks/chunk-UQZZX2J7.js";import"../../chunks/chunk-UDZJCD5W.js";import"../../chunks/chunk-5ZCSFPWG.js";import"../../chunks/chunk-PY4WWD6Z.js";import"../../chunks/chunk-XDYVJWGX.js";import"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-BPIGFKNN.js";import"../../chunks/chunk-AB4WXRCO.js";import"../../chunks/chunk-SYJXONEV.js";import{printError}from"../../chunks/chunk-CY5KJ42N.js";import"../../chunks/chunk-KK5C7HVP.js";import{help}from"../../chunks/chunk-7KCRYDGK.js";import"../../chunks/chunk-GLIQ4KNY.js";import"../../chunks/chunk-3G3FQYMW.js";import{detectExplicitScope,getScope}from"../../chunks/chunk-YJP25FL6.js";import{TelemetryClient}from"../../chunks/chunk-KDCODXVL.js";import"../../chunks/chunk-NWGBDBZI.js";import{AGENT_REASON,AGENT_STATUS,buildCommandWithYes,getExitCodeForReason,writeActionRequired}from"../../chunks/chunk-PNWRO3XW.js";import{addSubcommand,linkCommand}from"../../chunks/chunk-DTUEHPME.js";import{addRepoLink,ensureRepoLink,findRepoRoot,getLinkedProjectIdSync,getVercelDirectory,isPromptCanceledError,resolveProjectCwd}from"../../chunks/chunk-XL2PHD4X.js";import"../../chunks/chunk-M7FED5YP.js";import"../../chunks/chunk-4HR3I3ML.js";import"../../chunks/chunk-LOA7SZWH.js";import"../../chunks/chunk-LUX4PBJL.js";import"../../chunks/chunk-MTZYPCZ7.js";import"../../chunks/chunk-OPORM35X.js";import"../../chunks/chunk-D6REP5QQ.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-MY4MONOH.js";import"../../chunks/chunk-7HLAWGY2.js";import"../../chunks/chunk-MXTC4ZAQ.js";import{parseArguments}from"../../chunks/chunk-LYL26S3N.js";import"../../chunks/chunk-2VBFQZ72.js";import"../../chunks/chunk-6GKP6VUF.js";import"../../chunks/chunk-4NTBYNFR.js";import"../../chunks/chunk-4SAVH3H7.js";import"../../chunks/chunk-GOI2VVI7.js";import{cmd}from"../../chunks/chunk-B4KA3ZH2.js";import"../../chunks/chunk-BOJDM3O7.js";import{output_manager_default}from"../../chunks/chunk-AP6DZGTK.js";import"../../chunks/chunk-BLUPZPAS.js";import"../../chunks/chunk-AW33SRYY.js";import{require_build_utils}from"../../chunks/chunk-5MDNVAE6.js";import"../../chunks/chunk-OCR5CRTH.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-SCV7XEEO.js";import"../../chunks/chunk-MCYG7CCE.js";import"../../chunks/chunk-YHPPP3SF.js";import"../../chunks/chunk-24SIHFEW.js";import{getFlagsSpecification}from"../../chunks/chunk-CFJBDBYH.js";import"../../chunks/chunk-2BKALEOP.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import"../../chunks/chunk-BULSRTQE.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_chalk=__toESM(require_source(),1);import{join}from"path";var LinkTelemetryClient=class extends TelemetryClient{trackCliArgumentCwd(){this.trackCliArgument({arg:"cwd",value:this.redactedValue})}trackCliFlagRepo(flag){flag&&this.trackCliFlag("repo")}trackCliFlagYes(yes){yes&&this.trackCliFlag("yes")}trackCliFlagConfirm(flag){flag&&this.trackCliFlag("confirm")}trackCliOptionTeam(value){value&&this.trackCliOption({option:"team",value:this.redactedValue})}trackCliOptionProjectId(value){value&&this.trackCliOption({option:"project-id",value:this.redactedValue})}trackCliSubcommandAdd(actual){this.trackCliSubcommand({subcommand:"add",value:actual})}trackCliFlagJson(json){json&&this.trackCliFlag("json")}};var import_build_utils=__toESM(require_build_utils(),1);var COMMAND_CONFIG={add:getCommandAliases(addSubcommand)};function warnOidcRefreshFailed(){output_manager_default.print(`${import_chalk.default.yellow("!")} Linked project, but failed to refresh VERCEL_OIDC_TOKEN in .env.local. Rerun the link command to retry.
8
8
  `)}async function refreshOidcTokenAfterLink(client,cwd){let originalCwd=client.cwd;try{return client.cwd=await resolveProjectCwd(cwd),output_manager_default.print(`
9
9
  `),await pull(client,["--yes"],"vercel-cli:link",{oidcTokenOnly:!0})!==0?(warnOidcRefreshFailed(),!1):!0}catch{return warnOidcRefreshFailed(),!1}finally{client.cwd=originalCwd}}var OIDC_REFRESH_FAILED_WARNING={reason:"oidc_token_not_refreshed",message:"Linked project, but failed to refresh VERCEL_OIDC_TOKEN in .env.local. Rerun the link command to retry."};async function link(client){try{return await client.withEscapePromptCancellation(()=>linkProject(client))}catch(error){if(isPromptCanceledError(error))return output_manager_default.print(` Canceled.
10
10
  `),0;throw error}}async function linkProject(client){let parsedArgs=null,flagsSpecification=getFlagsSpecification(linkCommand.options);try{parsedArgs=parseArguments(client.argv.slice(2),flagsSpecification,{permissive:!0})}catch(error){return printError(error),2}let{subcommand,subcommandOriginal}=getSubcommand(parsedArgs.args.slice(1),COMMAND_CONFIG),telemetry=new LinkTelemetryClient({opts:{store:client.telemetryEventStore}});function printHelp(command){output_manager_default.print(help(command,{stream:client.stderr,parent:linkCommand,columns:client.stderr.columns}))}if(subcommand==="add"){if(parsedArgs.flags["--help"])return telemetry.trackCliFlagHelp("link",subcommandOriginal),printHelp(addSubcommand),0;telemetry.trackCliSubcommandAdd(subcommandOriginal);let yes=!!parsedArgs.flags["--yes"];try{await addRepoLink(client,client.cwd,{yes})}catch(err){if(isPromptCanceledError(err))throw err;return output_manager_default.prettyError(err),1}return 0}try{parsedArgs=parseArguments(client.argv.slice(2),flagsSpecification)}catch(error){return client.argv.includes("--json")?writeJsonUsageError(client,error):(printError(error),2)}if(parsedArgs.flags["--help"])return telemetry.trackCliFlagHelp("link"),output_manager_default.print(help(linkCommand,{stream:client.stderr,columns:client.stderr.columns})),0;telemetry.trackCliFlagRepo(parsedArgs.flags["--repo"]),telemetry.trackCliFlagYes(parsedArgs.flags["--yes"]),telemetry.trackCliOptionProject(parsedArgs.flags["--project"]),telemetry.trackCliFlagJson(parsedArgs.flags["--json"]);let flags=parsedArgs.flags,argument=parsedArgs.args[1],json=!!flags["--json"],run=()=>linkDirectory(client,telemetry,flags,argument,json);return json?runWithJsonOutput(client,run):run()}async function linkDirectory(client,telemetry,flags,argument,json){"--confirm"in flags&&(telemetry.trackCliFlagConfirm(flags["--confirm"]),output_manager_default.warn("`--confirm` is deprecated, please use `--yes` instead"),flags["--yes"]=flags["--confirm"]);let yes=!!flags["--yes"],cwd=argument;if(cwd?(telemetry.trackCliArgumentCwd(),output_manager_default.warn(`The ${cmd("vc link <directory>")} syntax is deprecated, please use ${cmd(`vc link --cwd ${cwd}`)} instead`)):cwd=client.cwd,flags["--repo"]){if(json&&!yes)return writeActionRequired(client,{status:AGENT_STATUS.ACTION_REQUIRED,reason:AGENT_REASON.CONFIRMATION_REQUIRED,message:"Can't link the repository without --yes in non-interactive mode. --yes links its projects with the default team and settings.",next:[{command:buildCommandWithYes(client.argv)}]}),getExitCodeForReason(AGENT_REASON.CONFIRMATION_REQUIRED);output_manager_default.warn(`The ${cmd("--repo")} option is in alpha, please report issues`);let repoLink;try{repoLink=await ensureRepoLink(client,cwd,{yes,overwrite:!0})}catch(err){if(isPromptCanceledError(err)||json)throw err;return output_manager_default.prettyError(err),1}if(json)return writeJsonResult(client,repoLink?.repoConfig?{repoLink:{directory:repoLink.rootPath,remoteName:repoLink.repoConfig.remoteName,projects:repoLink.repoConfig.projects},outcome:"linked",next:[jsonNextStep(client,["project","list"],"List projects")]}:{repoLink:null,outcome:"unchanged"})}else{let selectedOrg=detectExplicitScope(client)?(await getScope(client,{resolveLocalScope:!0})).org:void 0,linkNonInteractive=client.nonInteractive||client.argv.includes("--non-interactive"),previousProjectId=json?getLinkedProjectIdSync(getVercelDirectory(await resolveProjectCwd(cwd))):void 0,link2=await ensureLink("link",client,cwd,{autoConfirm:yes,forceDelete:!0,selectedOrg,projectName:flags["--project"],successEmoji:"success",nonInteractive:linkNonInteractive,pullEnv:!1});if(typeof link2=="number")return link2;let projectCwd=await resolveProjectCwd(cwd),rootDirectory=link2.project.rootDirectory,repoRoot=link2.repoRoot??(rootDirectory?await findRepoRoot(projectCwd):void 0);await promptExperimentalServicesMigration({client,cwd:rootDirectory?join(repoRoot??projectCwd,rootDirectory):link2.repoRoot??projectCwd,autoConfirm:yes,nonInteractive:linkNonInteractive,allowConfigExecution:!1});let oidcRefreshed=await refreshOidcTokenAfterLink(client,cwd);if(json){let unchanged=!!((0,import_build_utils.getPlatformEnv)("ORG_ID")&&(0,import_build_utils.getPlatformEnv)("PROJECT_ID"))||previousProjectId===link2.project.id;return writeJsonResult(client,{link:{teamId:link2.org.id,projectId:link2.project.id,projectName:link2.project.name,directory:projectCwd},outcome:unchanged?"unchanged":"linked",projectCreated:!!link2.projectCreated,previousProjectId:!unchanged&&previousProjectId?previousProjectId:null,...oidcRefreshed?{}:{warnings:[OIDC_REFRESH_FAILED_WARNING]},next:[jsonNextStep(client,["project","inspect",link2.project.name],"Inspect the project")]})}}return 0}export{link as default};
@@ -4,7 +4,7 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{apiServerMessage}from"../../chunks/chunk-FCTTEFC5.js";import{createProject}from"../../chunks/chunk-ANIA2G6F.js";import{handleCommandTypo}from"../../chunks/chunk-SW26TCUB.js";import{getProjectByCwdOrLink}from"../../chunks/chunk-7KPAYK2N.js";import{joinWords}from"../../chunks/chunk-4VFYJU37.js";import{tryOpenApiFallback}from"../../chunks/chunk-QYUKDP2E.js";import"../../chunks/chunk-GHAY4PSD.js";import{formatRepository}from"../../chunks/chunk-3FVMCV7T.js";import{formatProvider,parseRepoUrl}from"../../chunks/chunk-L75A5BMY.js";import"../../chunks/chunk-5TMHRECT.js";import"../../chunks/chunk-JUAHDOL6.js";import"../../chunks/chunk-YTRKHRL3.js";import"../../chunks/chunk-54FY6GJ5.js";import{did_you_mean_default}from"../../chunks/chunk-DWZBL4NK.js";import{resolveOpenApiTagForProjectsCli}from"../../chunks/chunk-JWKFVECK.js";import{getNetworkFailureCause,isRequestNotSent}from"../../chunks/chunk-KXK4TF6L.js";import{email}from"../../chunks/chunk-6IDNVZZR.js";import{require_async_sema}from"../../chunks/chunk-NZ2TFADV.js";import{INVALID_NEXT_MESSAGE,InvalidNextError,getPaginationOpts,parseNumericCursor}from"../../chunks/chunk-C6GY2G73.js";import{formatDate}from"../../chunks/chunk-HRR57QNP.js";import{stamp_default}from"../../chunks/chunk-A2RZZQEP.js";import"../../chunks/chunk-Q7D7RGXM.js";import{require_frameworks}from"../../chunks/chunk-ZKNEIE44.js";import{resolveProjectContext}from"../../chunks/chunk-QQNN5X7M.js";import{formatProject}from"../../chunks/chunk-3UZE566G.js";import"../../chunks/chunk-O4WJDJIL.js";import"../../chunks/chunk-A5FPKXEK.js";import{readOnOffOption,rewriteLegacyOnOffValues}from"../../chunks/chunk-CFQPIYKY.js";import{requireApproval}from"../../chunks/chunk-JGUMBEQH.js";import"../../chunks/chunk-IG5ACFU6.js";import"../../chunks/chunk-Y4D7IX3M.js";import{getCommandFlags}from"../../chunks/chunk-XGTKHQTT.js";import"../../chunks/chunk-PFD7LETF.js";import{getInvalidSubcommand}from"../../chunks/chunk-TG2RCYTH.js";import{canPrompt}from"../../chunks/chunk-IQ7FPAI4.js";import{trackCreatedId}from"../../chunks/chunk-YJNMDXEG.js";import{getRenamedOption,renameOptionInArgs,reportRenamedOptionError,withWarnings}from"../../chunks/chunk-FSZJSIOF.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import{table}from"../../chunks/chunk-CJZE7647.js";import{getNextPageCommand,printNextPageCommand}from"../../chunks/chunk-D44WCAOX.js";import{getTeams}from"../../chunks/chunk-Y2FVJ7YO.js";import{PROJECT_MEMBER_ROLES,accessGroupsSubcommand,accessSummarySubcommand,addSubcommand8 as addSubcommand,checksAddFlags,checksRemoveFlags,checksSubcommand,dangerouslyDeleteImmutableStaticAssetSubcommand,getCommandAliases,inspectSubcommand15 as inspectSubcommand,keepSubcommand,listSubcommand19 as listSubcommand,membersAddFlags,membersRemoveFlags,membersSubcommand,observabilityDisableSubcommand,observabilitySubcommand,pauseSubcommand2 as pauseSubcommand,prioritySubcommand,projectCommand,protectionEnableSubcommand,protectionSubcommand,removeSubcommand13 as removeSubcommand,renameSubcommand,resumeSubcommand2 as resumeSubcommand,speedInsightsSubcommand,tokenSubcommand2 as tokenSubcommand,updateSubcommand10 as updateSubcommand,webAnalyticsDisableSubcommand,webAnalyticsSubcommand}from"../../chunks/chunk-6U7TRWBO.js";import"../../chunks/chunk-QOLGACFD.js";import"../../chunks/chunk-DDPH26ZO.js";import"../../chunks/chunk-PIDEH4SJ.js";import"../../chunks/chunk-IIK6GUVI.js";import"../../chunks/chunk-C35SG42R.js";import"../../chunks/chunk-2GBU6ULJ.js";import"../../chunks/chunk-EJLYDHT7.js";import"../../chunks/chunk-DOBV3XLO.js";import"../../chunks/chunk-UFCL2VBD.js";import"../../chunks/chunk-BMIYC2MH.js";import"../../chunks/chunk-6CJFPT4F.js";import"../../chunks/chunk-ZZD5W5KT.js";import"../../chunks/chunk-VHSAI6FS.js";import"../../chunks/chunk-F7L5SXJM.js";import"../../chunks/chunk-GLCSWIB4.js";import"../../chunks/chunk-XECELSF5.js";import"../../chunks/chunk-6FYPSSL4.js";import"../../chunks/chunk-UQZZX2J7.js";import"../../chunks/chunk-UDZJCD5W.js";import"../../chunks/chunk-5ZCSFPWG.js";import"../../chunks/chunk-PY4WWD6Z.js";import"../../chunks/chunk-XDYVJWGX.js";import"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-BPIGFKNN.js";import"../../chunks/chunk-AB4WXRCO.js";import"../../chunks/chunk-SYJXONEV.js";import{printError}from"../../chunks/chunk-CY5KJ42N.js";import"../../chunks/chunk-KK5C7HVP.js";import{help}from"../../chunks/chunk-7KCRYDGK.js";import{remoteText}from"../../chunks/chunk-GLIQ4KNY.js";import"../../chunks/chunk-3G3FQYMW.js";import{getContextName,getScope,scopeFlagPassed}from"../../chunks/chunk-YJP25FL6.js";import{TelemetryClient}from"../../chunks/chunk-KDCODXVL.js";import"../../chunks/chunk-NWGBDBZI.js";import{AGENT_ACTION,AGENT_REASON,AGENT_STATUS,BUY_PRO_COMMAND,PRIORITY_PROJECT_ENABLE_COMMAND,buildCommandWithGlobalFlags,buildCommandWithYes,buyProFix,exitWithNonInteractiveError,getErrorRecovery,getExitCodeForReason,isInvalidTokenApiError,isProOrEnterprisePlan,outputActionRequired,outputAgentError,shouldEmitNonInteractiveCommandError,targetRecovery,withGlobalFlags,writeAgentError}from"../../chunks/chunk-PNWRO3XW.js";import"../../chunks/chunk-DTUEHPME.js";import{getUser,sleep}from"../../chunks/chunk-XL2PHD4X.js";import{printAlignedLabel}from"../../chunks/chunk-M7FED5YP.js";import{require_pluralize}from"../../chunks/chunk-4HR3I3ML.js";import{getProjectByNameOrId}from"../../chunks/chunk-LOA7SZWH.js";import"../../chunks/chunk-LUX4PBJL.js";import"../../chunks/chunk-MTZYPCZ7.js";import"../../chunks/chunk-OPORM35X.js";import"../../chunks/chunk-D6REP5QQ.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-MY4MONOH.js";import"../../chunks/chunk-7HLAWGY2.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import{getTypedOptionName,parseArguments}from"../../chunks/chunk-LYL26S3N.js";import{getTeamByIdOrSlug}from"../../chunks/chunk-2VBFQZ72.js";import{validateJsonOutput,wantsMachineReadableOutput,warnDeprecatedSubcommand}from"../../chunks/chunk-6GKP6VUF.js";import"../../chunks/chunk-4NTBYNFR.js";import"../../chunks/chunk-4SAVH3H7.js";import{LinkRequiredError,ProjectNotFound,isAPIError}from"../../chunks/chunk-GOI2VVI7.js";import{getCommandName,getCommandNamePlain,packageName}from"../../chunks/chunk-B4KA3ZH2.js";import"../../chunks/chunk-BOJDM3O7.js";import{emoji,output_manager_default,prependEmoji}from"../../chunks/chunk-AP6DZGTK.js";import"../../chunks/chunk-BLUPZPAS.js";import"../../chunks/chunk-AW33SRYY.js";import{require_build_utils}from"../../chunks/chunk-5MDNVAE6.js";import"../../chunks/chunk-OCR5CRTH.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-SCV7XEEO.js";import"../../chunks/chunk-MCYG7CCE.js";import"../../chunks/chunk-YHPPP3SF.js";import"../../chunks/chunk-24SIHFEW.js";import{getFlagsSpecification,getGlobalFlagsFromArgs,quoteArg}from"../../chunks/chunk-CFJBDBYH.js";import"../../chunks/chunk-2BKALEOP.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import"../../chunks/chunk-BULSRTQE.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_chalk=__toESM(require_source(),1),import_ms=__toESM(require_ms(),1);var ProjectAddTelemetryClient=class extends TelemetryClient{trackCliArgumentName(name){name&&this.trackCliArgument({arg:"name",value:this.redactedValue})}};async function add(client,argv){let telemetryClient=new ProjectAddTelemetryClient({opts:{store:client.telemetryEventStore}}),parsedArgs,flagsSpecification=getFlagsSpecification(addSubcommand.options);try{parsedArgs=parseArguments(argv,flagsSpecification)}catch(error){return printError(error),2}let{args}=parsedArgs;if(args.length!==1){if(output_manager_default.error(`Invalid number of arguments. Usage: ${import_chalk.default.cyan(`${getCommandName("project create <name>")}`)}`),args.length>1){let example=import_chalk.default.cyan(`${getCommandName(`project create "${args.join(" ")}"`)}`);output_manager_default.log(`If your project name has spaces, make sure to wrap it in quotes. Example:
7
+ import{apiServerMessage}from"../../chunks/chunk-FCTTEFC5.js";import{createProject}from"../../chunks/chunk-ANIA2G6F.js";import{handleCommandTypo}from"../../chunks/chunk-SW26TCUB.js";import{getProjectByCwdOrLink}from"../../chunks/chunk-7KPAYK2N.js";import{joinWords}from"../../chunks/chunk-4VFYJU37.js";import{tryOpenApiFallback}from"../../chunks/chunk-QYUKDP2E.js";import"../../chunks/chunk-GHAY4PSD.js";import{formatRepository}from"../../chunks/chunk-3FVMCV7T.js";import{formatProvider,parseRepoUrl}from"../../chunks/chunk-L75A5BMY.js";import"../../chunks/chunk-5TMHRECT.js";import"../../chunks/chunk-JUAHDOL6.js";import"../../chunks/chunk-YTRKHRL3.js";import"../../chunks/chunk-54FY6GJ5.js";import{did_you_mean_default}from"../../chunks/chunk-DWZBL4NK.js";import{resolveOpenApiTagForProjectsCli}from"../../chunks/chunk-JWKFVECK.js";import{getNetworkFailureCause,isRequestNotSent}from"../../chunks/chunk-KXK4TF6L.js";import{email}from"../../chunks/chunk-6IDNVZZR.js";import{require_async_sema}from"../../chunks/chunk-NZ2TFADV.js";import{INVALID_NEXT_MESSAGE,InvalidNextError,getPaginationOpts,parseNumericCursor}from"../../chunks/chunk-C6GY2G73.js";import{formatDate}from"../../chunks/chunk-HRR57QNP.js";import{stamp_default}from"../../chunks/chunk-A2RZZQEP.js";import"../../chunks/chunk-Q7D7RGXM.js";import{require_frameworks}from"../../chunks/chunk-ZKNEIE44.js";import{resolveProjectContext}from"../../chunks/chunk-QQNN5X7M.js";import{formatProject}from"../../chunks/chunk-3UZE566G.js";import"../../chunks/chunk-O4WJDJIL.js";import"../../chunks/chunk-A5FPKXEK.js";import{readOnOffOption,rewriteLegacyOnOffValues}from"../../chunks/chunk-CFQPIYKY.js";import{requireApproval}from"../../chunks/chunk-JGUMBEQH.js";import"../../chunks/chunk-IG5ACFU6.js";import"../../chunks/chunk-Y4D7IX3M.js";import{getCommandFlags}from"../../chunks/chunk-XGTKHQTT.js";import"../../chunks/chunk-PFD7LETF.js";import{getInvalidSubcommand}from"../../chunks/chunk-TG2RCYTH.js";import{canPrompt}from"../../chunks/chunk-IQ7FPAI4.js";import{trackCreatedId}from"../../chunks/chunk-YJNMDXEG.js";import{getRenamedOption,renameOptionInArgs,reportRenamedOptionError,withWarnings}from"../../chunks/chunk-FSZJSIOF.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import{table}from"../../chunks/chunk-CJZE7647.js";import{getNextPageCommand,printNextPageCommand}from"../../chunks/chunk-D44WCAOX.js";import{getTeams}from"../../chunks/chunk-Y2FVJ7YO.js";import{PROJECT_MEMBER_ROLES,accessGroupsSubcommand,accessSummarySubcommand,addSubcommand8 as addSubcommand,checksAddFlags,checksRemoveFlags,checksSubcommand,dangerouslyDeleteImmutableStaticAssetSubcommand,getCommandAliases,inspectSubcommand15 as inspectSubcommand,keepSubcommand,listSubcommand19 as listSubcommand,membersAddFlags,membersRemoveFlags,membersSubcommand,observabilityDisableSubcommand,observabilitySubcommand,pauseSubcommand2 as pauseSubcommand,prioritySubcommand,projectCommand,protectionEnableSubcommand,protectionSubcommand,removeSubcommand13 as removeSubcommand,renameSubcommand,resumeSubcommand2 as resumeSubcommand,speedInsightsSubcommand,tokenSubcommand2 as tokenSubcommand,updateSubcommand10 as updateSubcommand,webAnalyticsDisableSubcommand,webAnalyticsSubcommand}from"../../chunks/chunk-HVFGIJ44.js";import"../../chunks/chunk-QOLGACFD.js";import"../../chunks/chunk-DDPH26ZO.js";import"../../chunks/chunk-PIDEH4SJ.js";import"../../chunks/chunk-IIK6GUVI.js";import"../../chunks/chunk-C35SG42R.js";import"../../chunks/chunk-2GBU6ULJ.js";import"../../chunks/chunk-EJLYDHT7.js";import"../../chunks/chunk-DOBV3XLO.js";import"../../chunks/chunk-TUB3APDV.js";import"../../chunks/chunk-BMIYC2MH.js";import"../../chunks/chunk-6CJFPT4F.js";import"../../chunks/chunk-ZZD5W5KT.js";import"../../chunks/chunk-VHSAI6FS.js";import"../../chunks/chunk-F7L5SXJM.js";import"../../chunks/chunk-GLCSWIB4.js";import"../../chunks/chunk-XECELSF5.js";import"../../chunks/chunk-6FYPSSL4.js";import"../../chunks/chunk-UQZZX2J7.js";import"../../chunks/chunk-UDZJCD5W.js";import"../../chunks/chunk-5ZCSFPWG.js";import"../../chunks/chunk-PY4WWD6Z.js";import"../../chunks/chunk-XDYVJWGX.js";import"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-BPIGFKNN.js";import"../../chunks/chunk-AB4WXRCO.js";import"../../chunks/chunk-SYJXONEV.js";import{printError}from"../../chunks/chunk-CY5KJ42N.js";import"../../chunks/chunk-KK5C7HVP.js";import{help}from"../../chunks/chunk-7KCRYDGK.js";import{remoteText}from"../../chunks/chunk-GLIQ4KNY.js";import"../../chunks/chunk-3G3FQYMW.js";import{getContextName,getScope,scopeFlagPassed}from"../../chunks/chunk-YJP25FL6.js";import{TelemetryClient}from"../../chunks/chunk-KDCODXVL.js";import"../../chunks/chunk-NWGBDBZI.js";import{AGENT_ACTION,AGENT_REASON,AGENT_STATUS,BUY_PRO_COMMAND,PRIORITY_PROJECT_ENABLE_COMMAND,buildCommandWithGlobalFlags,buildCommandWithYes,buyProFix,exitWithNonInteractiveError,getErrorRecovery,getExitCodeForReason,isInvalidTokenApiError,isProOrEnterprisePlan,outputActionRequired,outputAgentError,shouldEmitNonInteractiveCommandError,targetRecovery,withGlobalFlags,writeAgentError}from"../../chunks/chunk-PNWRO3XW.js";import"../../chunks/chunk-DTUEHPME.js";import{getUser,sleep}from"../../chunks/chunk-XL2PHD4X.js";import{printAlignedLabel}from"../../chunks/chunk-M7FED5YP.js";import{require_pluralize}from"../../chunks/chunk-4HR3I3ML.js";import{getProjectByNameOrId}from"../../chunks/chunk-LOA7SZWH.js";import"../../chunks/chunk-LUX4PBJL.js";import"../../chunks/chunk-MTZYPCZ7.js";import"../../chunks/chunk-OPORM35X.js";import"../../chunks/chunk-D6REP5QQ.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-MY4MONOH.js";import"../../chunks/chunk-7HLAWGY2.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import{getTypedOptionName,parseArguments}from"../../chunks/chunk-LYL26S3N.js";import{getTeamByIdOrSlug}from"../../chunks/chunk-2VBFQZ72.js";import{validateJsonOutput,wantsMachineReadableOutput,warnDeprecatedSubcommand}from"../../chunks/chunk-6GKP6VUF.js";import"../../chunks/chunk-4NTBYNFR.js";import"../../chunks/chunk-4SAVH3H7.js";import{LinkRequiredError,ProjectNotFound,isAPIError}from"../../chunks/chunk-GOI2VVI7.js";import{getCommandName,getCommandNamePlain,packageName}from"../../chunks/chunk-B4KA3ZH2.js";import"../../chunks/chunk-BOJDM3O7.js";import{emoji,output_manager_default,prependEmoji}from"../../chunks/chunk-AP6DZGTK.js";import"../../chunks/chunk-BLUPZPAS.js";import"../../chunks/chunk-AW33SRYY.js";import{require_build_utils}from"../../chunks/chunk-5MDNVAE6.js";import"../../chunks/chunk-OCR5CRTH.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-SCV7XEEO.js";import"../../chunks/chunk-MCYG7CCE.js";import"../../chunks/chunk-YHPPP3SF.js";import"../../chunks/chunk-24SIHFEW.js";import{getFlagsSpecification,getGlobalFlagsFromArgs,quoteArg}from"../../chunks/chunk-CFJBDBYH.js";import"../../chunks/chunk-2BKALEOP.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import"../../chunks/chunk-BULSRTQE.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_chalk=__toESM(require_source(),1),import_ms=__toESM(require_ms(),1);var ProjectAddTelemetryClient=class extends TelemetryClient{trackCliArgumentName(name){name&&this.trackCliArgument({arg:"name",value:this.redactedValue})}};async function add(client,argv){let telemetryClient=new ProjectAddTelemetryClient({opts:{store:client.telemetryEventStore}}),parsedArgs,flagsSpecification=getFlagsSpecification(addSubcommand.options);try{parsedArgs=parseArguments(argv,flagsSpecification)}catch(error){return printError(error),2}let{args}=parsedArgs;if(args.length!==1){if(output_manager_default.error(`Invalid number of arguments. Usage: ${import_chalk.default.cyan(`${getCommandName("project create <name>")}`)}`),args.length>1){let example=import_chalk.default.cyan(`${getCommandName(`project create "${args.join(" ")}"`)}`);output_manager_default.log(`If your project name has spaces, make sure to wrap it in quotes. Example:
8
8
  ${example} `)}return 2}let start=Date.now(),[name]=args;telemetryClient.trackCliArgumentName(name);try{await createProject(client,{name})}catch(err){if(isAPIError(err)&&err.code==="too_many_projects")return output_manager_default.prettyError(err),1;if(!(isAPIError(err)&&err.status===409))throw err}let elapsed=(0,import_ms.default)(Date.now()-start),contextName=await getContextName(client);return output_manager_default.log(`${import_chalk.default.cyan("Success!")} Project ${import_chalk.default.bold(name.toLowerCase())} added (${import_chalk.default.bold(contextName)}) ${import_chalk.default.gray(`[${elapsed}]`)}`),0}var import_chalk2=__toESM(require_source(),1);async function accessSummary(client,argv){let parsedArgs,flagsSpecification=getFlagsSpecification(accessSummarySubcommand.options);try{parsedArgs=parseArguments(argv,flagsSpecification)}catch(error){return client.nonInteractive&&outputAgentError(client,{status:"error",reason:"invalid_arguments",message:error instanceof Error?error.message:String(error)},2),printError(error),2}if(parsedArgs.args.length>1)return output_manager_default.error("Invalid number of arguments. Usage: `vercel project access-summary [name]`"),2;let formatResult=validateJsonOutput(parsedArgs.flags);if(!formatResult.valid)return output_manager_default.error(formatResult.error),2;let asJson=formatResult.jsonOutput,summary;try{let project=await getProjectByCwdOrLink({client,commandName:"project access-summary",projectNameOrId:parsedArgs.args[0],forReadOnlyCommand:!0});summary=await client.fetch(`/v1/projects/${encodeURIComponent(project.id)}/members/summary`)}catch(err){return exitWithNonInteractiveError(client,err,1,{variant:"access-summary"}),printError(err),1}if(asJson)return client.stdout.write(`${JSON.stringify(summary,null,2)}
9
9
  `),0;let entries=Object.entries(summary).sort(([a],[b])=>a.localeCompare(b));if(entries.length===0)return output_manager_default.log("No summary data returned."),0;let rows=[["Role","Count"].map(h=>(0,import_chalk2.gray)(h)),...entries.map(([role,count])=>[role,String(count)])];return client.stderr.write(`${table(rows,{hsep:3})}
10
10
  `),0}var import_chalk3=__toESM(require_source(),1);import{readFileSync}from"fs";import{resolve}from"path";var REQUIRES=["build-ready","deployment-url","none"],BLOCKING_STAGES=["build-start","deployment-start","deployment-alias","deployment-promotion","none"];function emitValidationError(client,message,exitCode,extra){outputAgentError(client,{status:"error",reason:AGENT_REASON.INVALID_ARGUMENTS,message,...extra},exitCode)}async function checksAdd(client,argv){let parsedArgs,flagsSpecification=getFlagsSpecification([...checksAddFlags]);try{parsedArgs=parseArguments(argv,flagsSpecification)}catch(error){return client.nonInteractive&&outputAgentError(client,{status:"error",reason:AGENT_REASON.INVALID_ARGUMENTS,message:error instanceof Error?error.message:String(error)},2),printError(error),2}if(parsedArgs.args.length>1)return emitValidationError(client,"Invalid number of arguments. Usage: `vercel project checks add [name]`",2),output_manager_default.error("Invalid number of arguments. Usage: `vercel project checks add [name]`"),2;let formatResult=validateJsonOutput(parsedArgs.flags);if(!formatResult.valid)return client.nonInteractive&&emitValidationError(client,formatResult.error,1),output_manager_default.error(formatResult.error),1;let asJson=formatResult.jsonOutput||!!client.nonInteractive,filePath=parsedArgs.flags["--file"],checkName=parsedArgs.flags["--check-name"],requires=parsedArgs.flags["--requires"],blocksFlag=parsedArgs.flags["--blocks"],timeout=parsedArgs.flags["--timeout"],targetsRaw=parsedArgs.flags["--targets"],sourceRaw=parsedArgs.flags["--source"],body;if(typeof filePath=="string"&&filePath.length>0)try{let raw=readFileSync(resolve(client.cwd,filePath),"utf8"),parsed=JSON.parse(raw);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))return emitValidationError(client,"`--file` must contain a JSON object.",1),output_manager_default.error("`--file` must contain a JSON object."),1;body=parsed}catch(err){let msg=err instanceof Error?err.message:String(err);return emitValidationError(client,`Failed to read \`--file\`: ${msg}`,1),output_manager_default.error(`Failed to read \`--file\`: ${msg}`),1}else{if(typeof checkName!="string"||!checkName.trim())return emitValidationError(client,"Provide `--check-name` and `--requires`, or a `--file` with the full JSON body.",1,{hint:'See `vercel project checks --help` and the REST API "Create a check" documentation.',next:[{command:buildCommandWithGlobalFlags(client.argv,"project checks add <name> --file <path>"),when:"Create from a JSON file (replace paths)"}]}),output_manager_default.error("Provide `--check-name` and `--requires`, or a `--file` with the full JSON body. See `vercel project checks add --help`."),1;if(typeof requires!="string"||!requires.trim())return emitValidationError(client,"`--requires` is required when using `--check-name` (build-ready, deployment-url, or none).",1),output_manager_default.error("`--requires` is required when using `--check-name` (build-ready, deployment-url, or none)."),2;if(!REQUIRES.includes(requires))return emitValidationError(client,`\`--requires\` must be one of: ${REQUIRES.join(", ")}`,1),output_manager_default.error(`\`--requires\` must be one of: ${REQUIRES.join(", ")}`),2;if(body={name:checkName.trim(),requires:requires.trim()},typeof blocksFlag=="string"&&blocksFlag.length>0){if(!BLOCKING_STAGES.includes(blocksFlag))return emitValidationError(client,`\`--blocks\` must be one of: ${BLOCKING_STAGES.join(", ")}`,1),output_manager_default.error(`\`--blocks\` must be one of: ${BLOCKING_STAGES.join(", ")}`),2;body.blocks=blocksFlag}if(typeof timeout=="number"&&(body.timeout=timeout),typeof targetsRaw=="string"&&targetsRaw.trim()&&(body.targets=targetsRaw.split(",").map(s=>s.trim()).filter(Boolean)),typeof sourceRaw=="string"&&sourceRaw.trim())try{body.source=JSON.parse(sourceRaw)}catch{return emitValidationError(client,"`--source` must be valid JSON.",1),output_manager_default.error("`--source` must be valid JSON."),1}}try{let project=await getProjectByCwdOrLink({client,commandName:"project checks add",projectNameOrId:parsedArgs.args[0],forReadOnlyCommand:!0}),result=await client.fetch(`/v2/projects/${encodeURIComponent(project.id)}/checks`,{method:"POST",body});if(trackCreatedId(client,"check",typeof result.id=="string"?result.id:void 0),asJson){let id2=String(result.id??"");return client.nonInteractive?client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.OK,check:result,projectId:project.id,projectName:project.name,message:id2?`Created deployment check ${id2} on ${project.name}.`:`Created deployment check on ${project.name}.`,next:[{command:buildCommandWithGlobalFlags(client.argv,"project checks"),when:"List checks for this project"},{command:buildCommandWithGlobalFlags(client.argv,"project checks remove <check_id>"),when:"Remove a check by id if needed"}]},null,2)}