vercel 63.1.1 → 63.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/deploy/index.js +3 -3
- package/dist/version.mjs +1 -1
- package/package.json +13 -13
|
@@ -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{fetchDeploymentBuildEnv,resolvePerDirectoryLinkRoot}from"../../chunks/chunk-WXWBB7LP.js";import{isIgnoredFile,singleFileConfig,singleFileProjectSettings,validatePaths,validateRootDirectory}from"../../chunks/chunk-ACGKBCXE.js";import{promptExperimentalServicesMigration}from"../../chunks/chunk-I4NK2P2D.js";import"../../chunks/chunk-IADIPNJO.js";import{DeployTelemetryClient,Now,UploadErrorMissingArchive,getBuildMachineResourceConfig,getProductionUrl,printDeploymentStatus,printPrebuiltFilePathMapIgnoreWarning}from"../../chunks/chunk-YDRNDY2V.js";import{require_async_sema}from"../../chunks/chunk-NZ2TFADV.js";import"../../chunks/chunk-HVNIW32A.js";import"../../chunks/chunk-V6Y6UK6B.js";import{parseRepoUrl}from"../../chunks/chunk-SYEKOJHT.js";import"../../chunks/chunk-EAUDC24V.js";import{pickOverrides}from"../../chunks/chunk-MJR564B4.js";import{require_dist as require_dist2,require_ignore}from"../../chunks/chunk-GNY6U33Z.js";import"../../chunks/chunk-AVRYIQRF.js";import{compileVercelConfig}from"../../chunks/chunk-46XQIXL7.js";import"../../chunks/chunk-RRDNKB2X.js";import"../../chunks/chunk-MVGTMPMI.js";import"../../chunks/chunk-SACGQMVQ.js";import"../../chunks/chunk-U56NHYAH.js";import{require_ci_info}from"../../chunks/chunk-2EYYB6YN.js";import{require_semver}from"../../chunks/chunk-BPUANOGW.js";import"../../chunks/chunk-3E364MJE.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-MHQ2MW2B.js";import"../../chunks/chunk-O4FDRZ22.js";import"../../chunks/chunk-T3GQAMBJ.js";import"../../chunks/chunk-P2O5DOYE.js";import{isGuidanceEnabled}from"../../chunks/chunk-A5R2HHNK.js";import{stamp_default}from"../../chunks/chunk-A2RZZQEP.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-J24BABG4.js";import{ensureLink,parseEnv}from"../../chunks/chunk-BW64GZ3E.js";import"../../chunks/chunk-WKTIAVGU.js";import"../../chunks/chunk-YCV465P5.js";import"../../chunks/chunk-PVASGBEF.js";import"../../chunks/chunk-MVCAUS4F.js";import{continueSubcommand,deployCommand,deprecatedArchiveSplitTgz,describeSubcommand,getCommandAliases,initSubcommand}from"../../chunks/chunk-6LZ72MNE.js";import"../../chunks/chunk-OH2RT2GN.js";import"../../chunks/chunk-UFXKCETS.js";import"../../chunks/chunk-RZGWCQP7.js";import"../../chunks/chunk-AG5QQNJ3.js";import"../../chunks/chunk-AU42HSQ3.js";import"../../chunks/chunk-L5FUUGYX.js";import"../../chunks/chunk-QC47UKDR.js";import"../../chunks/chunk-QJKJBD2M.js";import"../../chunks/chunk-MYCQIZU6.js";import"../../chunks/chunk-CNU4T7FO.js";import"../../chunks/chunk-LU5O3NH7.js";import"../../chunks/chunk-AMDHTZDV.js";import"../../chunks/chunk-2JBVMF2Y.js";import"../../chunks/chunk-JLXG2XWW.js";import"../../chunks/chunk-B4YYOSPY.js";import"../../chunks/chunk-I3D36ZLJ.js";import"../../chunks/chunk-S7XZC23O.js";import"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-6LXX5P3A.js";import"../../chunks/chunk-MSH7V3FL.js";import"../../chunks/chunk-SCV7XEEO.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import{parseMeta}from"../../chunks/chunk-CZSOZKHX.js";import"../../chunks/chunk-Q7D7RGXM.js";import{parseTarget}from"../../chunks/chunk-XEQT373M.js";import{getDeployment}from"../../chunks/chunk-J2LAZELI.js";import{mapCertError}from"../../chunks/chunk-E6UKNYFF.js";import"../../chunks/chunk-GRTIWUV2.js";import{help}from"../../chunks/chunk-5O2CW3SX.js";import{table}from"../../chunks/chunk-773GOZIR.js";import{printError}from"../../chunks/chunk-WDJFZM7U.js";import{AGENT_REASON,AGENT_STATUS,buildCommandWithYes,outputAgentError,withGlobalFlags}from"../../chunks/chunk-5DXCVG5U.js";import"../../chunks/chunk-67GZ5REA.js";import"../../chunks/chunk-BS32OUOC.js";import{validateJsonOutput,wantsMachineReadableOutput}from"../../chunks/chunk-D4MW3RDW.js";import{highlight,readLocalConfig}from"../../chunks/chunk-67N2NJCF.js";import"../../chunks/chunk-HMS3UIQ2.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import{TelemetryClient}from"../../chunks/chunk-TNZMCRAP.js";import"../../chunks/chunk-VKXEOL4K.js";import"../../chunks/chunk-YYPNUQDI.js";import"../../chunks/chunk-4SAVH3H7.js";import{require_types}from"../../chunks/chunk-ZS2WS4AM.js";import"../../chunks/chunk-AOWWC6WZ.js";import{getFetchDispatcher}from"../../chunks/chunk-MY4MONOH.js";import{isArgumentError,parseArguments}from"../../chunks/chunk-R4VVQRLX.js";import{quoteArg}from"../../chunks/chunk-BKV35LVB.js";import{getFlagsSpecification}from"../../chunks/chunk-5IPBCD7K.js";import{VERCEL_DIR,VERCEL_DIR_PROJECT,addToGitIgnore,createGitMeta,findProjectsFromPath,getGitConfigPath,getGitExecutable,getLinkFromDir,getProjectLink,getRepoLink,getVercelDirectory,isOwnerLookupUnavailableLink,isRemoteLookupSkippedLink,linkFolderToProject,parseGitConfig,pluckRemoteUrls,require_lib}from"../../chunks/chunk-IOJYYPUF.js";import"../../chunks/chunk-ROPQIBWJ.js";import"../../chunks/chunk-VKPZP4LC.js";import"../../chunks/chunk-PPCFQQSU.js";import{printAlignedLabel}from"../../chunks/chunk-N7Q2IESO.js";import"../../chunks/chunk-WPQN5UKR.js";import"../../chunks/chunk-VOZEB6PD.js";import{AliasDomainConfigured,BuildError,BuildsRateLimited,ConflictingConfigFiles,ConflictingFilePath,ConflictingPathSegment,DeploymentNotFound,DeploymentsRateLimited,DeprecatedNowJson,DomainNotFound,DomainNotVerified,DomainPermissionDenied,DomainVerificationFailed,InvalidDomain,InvalidToken,MissingBuildScript,NotDomainOwner,NowError,SchemaValidationFailed,TooManyRequests,UserAborted,code,isAPIError,require_bytes}from"../../chunks/chunk-YIIPBH2D.js";import{getCommandName,packageName}from"../../chunks/chunk-JESNVRVR.js";import{cliErrorFromUnknown,emoji,link_default,output_manager_default,prependEmoji,recordCliError,require_build_utils}from"../../chunks/chunk-75IAMKGV.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-D3AHZ5LI.js";import"../../chunks/chunk-2GHZGOWT.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_build_utils9=__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 as basename3,dirname as
|
|
7
|
+
import{fetchDeploymentBuildEnv,resolvePerDirectoryLinkRoot}from"../../chunks/chunk-WXWBB7LP.js";import{isIgnoredFile,singleFileConfig,singleFileProjectSettings,validatePaths,validateRootDirectory}from"../../chunks/chunk-ACGKBCXE.js";import{promptExperimentalServicesMigration}from"../../chunks/chunk-I4NK2P2D.js";import"../../chunks/chunk-IADIPNJO.js";import{DeployTelemetryClient,Now,UploadErrorMissingArchive,getBuildMachineResourceConfig,getProductionUrl,printDeploymentStatus,printPrebuiltFilePathMapIgnoreWarning}from"../../chunks/chunk-YDRNDY2V.js";import{require_async_sema}from"../../chunks/chunk-NZ2TFADV.js";import"../../chunks/chunk-HVNIW32A.js";import"../../chunks/chunk-V6Y6UK6B.js";import{parseRepoUrl}from"../../chunks/chunk-SYEKOJHT.js";import"../../chunks/chunk-EAUDC24V.js";import{pickOverrides}from"../../chunks/chunk-MJR564B4.js";import{require_dist as require_dist2,require_ignore}from"../../chunks/chunk-GNY6U33Z.js";import"../../chunks/chunk-AVRYIQRF.js";import{compileVercelConfig}from"../../chunks/chunk-46XQIXL7.js";import"../../chunks/chunk-RRDNKB2X.js";import"../../chunks/chunk-MVGTMPMI.js";import"../../chunks/chunk-SACGQMVQ.js";import"../../chunks/chunk-U56NHYAH.js";import{require_ci_info}from"../../chunks/chunk-2EYYB6YN.js";import{require_semver}from"../../chunks/chunk-BPUANOGW.js";import"../../chunks/chunk-3E364MJE.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-MHQ2MW2B.js";import"../../chunks/chunk-O4FDRZ22.js";import"../../chunks/chunk-T3GQAMBJ.js";import"../../chunks/chunk-P2O5DOYE.js";import{isGuidanceEnabled}from"../../chunks/chunk-A5R2HHNK.js";import{stamp_default}from"../../chunks/chunk-A2RZZQEP.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-J24BABG4.js";import{ensureLink,parseEnv}from"../../chunks/chunk-BW64GZ3E.js";import"../../chunks/chunk-WKTIAVGU.js";import"../../chunks/chunk-YCV465P5.js";import"../../chunks/chunk-PVASGBEF.js";import"../../chunks/chunk-MVCAUS4F.js";import{continueSubcommand,deployCommand,deprecatedArchiveSplitTgz,describeSubcommand,getCommandAliases,initSubcommand}from"../../chunks/chunk-6LZ72MNE.js";import"../../chunks/chunk-OH2RT2GN.js";import"../../chunks/chunk-UFXKCETS.js";import"../../chunks/chunk-RZGWCQP7.js";import"../../chunks/chunk-AG5QQNJ3.js";import"../../chunks/chunk-AU42HSQ3.js";import"../../chunks/chunk-L5FUUGYX.js";import"../../chunks/chunk-QC47UKDR.js";import"../../chunks/chunk-QJKJBD2M.js";import"../../chunks/chunk-MYCQIZU6.js";import"../../chunks/chunk-CNU4T7FO.js";import"../../chunks/chunk-LU5O3NH7.js";import"../../chunks/chunk-AMDHTZDV.js";import"../../chunks/chunk-2JBVMF2Y.js";import"../../chunks/chunk-JLXG2XWW.js";import"../../chunks/chunk-B4YYOSPY.js";import"../../chunks/chunk-I3D36ZLJ.js";import"../../chunks/chunk-S7XZC23O.js";import"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-6LXX5P3A.js";import"../../chunks/chunk-MSH7V3FL.js";import"../../chunks/chunk-SCV7XEEO.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import{parseMeta}from"../../chunks/chunk-CZSOZKHX.js";import"../../chunks/chunk-Q7D7RGXM.js";import{parseTarget}from"../../chunks/chunk-XEQT373M.js";import{getDeployment}from"../../chunks/chunk-J2LAZELI.js";import{mapCertError}from"../../chunks/chunk-E6UKNYFF.js";import"../../chunks/chunk-GRTIWUV2.js";import{help}from"../../chunks/chunk-5O2CW3SX.js";import{table}from"../../chunks/chunk-773GOZIR.js";import{printError}from"../../chunks/chunk-WDJFZM7U.js";import{AGENT_REASON,AGENT_STATUS,buildCommandWithYes,outputAgentError,withGlobalFlags}from"../../chunks/chunk-5DXCVG5U.js";import"../../chunks/chunk-67GZ5REA.js";import"../../chunks/chunk-BS32OUOC.js";import{validateJsonOutput,wantsMachineReadableOutput}from"../../chunks/chunk-D4MW3RDW.js";import{highlight,readLocalConfig}from"../../chunks/chunk-67N2NJCF.js";import"../../chunks/chunk-HMS3UIQ2.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import{TelemetryClient}from"../../chunks/chunk-TNZMCRAP.js";import"../../chunks/chunk-VKXEOL4K.js";import"../../chunks/chunk-YYPNUQDI.js";import"../../chunks/chunk-4SAVH3H7.js";import{require_types}from"../../chunks/chunk-ZS2WS4AM.js";import"../../chunks/chunk-AOWWC6WZ.js";import{getFetchDispatcher}from"../../chunks/chunk-MY4MONOH.js";import{isArgumentError,parseArguments}from"../../chunks/chunk-R4VVQRLX.js";import{quoteArg}from"../../chunks/chunk-BKV35LVB.js";import{getFlagsSpecification}from"../../chunks/chunk-5IPBCD7K.js";import{VERCEL_DIR,VERCEL_DIR_PROJECT,addToGitIgnore,createGitMeta,findProjectsFromPath,getGitConfigPath,getGitExecutable,getLinkFromDir,getProjectLink,getRepoLink,getVercelDirectory,isOwnerLookupUnavailableLink,isRemoteLookupSkippedLink,linkFolderToProject,parseGitConfig,pluckRemoteUrls,require_lib}from"../../chunks/chunk-IOJYYPUF.js";import"../../chunks/chunk-ROPQIBWJ.js";import"../../chunks/chunk-VKPZP4LC.js";import"../../chunks/chunk-PPCFQQSU.js";import{printAlignedLabel}from"../../chunks/chunk-N7Q2IESO.js";import"../../chunks/chunk-WPQN5UKR.js";import"../../chunks/chunk-VOZEB6PD.js";import{AliasDomainConfigured,BuildError,BuildsRateLimited,ConflictingConfigFiles,ConflictingFilePath,ConflictingPathSegment,DeploymentNotFound,DeploymentsRateLimited,DeprecatedNowJson,DomainNotFound,DomainNotVerified,DomainPermissionDenied,DomainVerificationFailed,InvalidDomain,InvalidToken,MissingBuildScript,NotDomainOwner,NowError,SchemaValidationFailed,TooManyRequests,UserAborted,code,isAPIError,require_bytes}from"../../chunks/chunk-YIIPBH2D.js";import{getCommandName,packageName}from"../../chunks/chunk-JESNVRVR.js";import{cliErrorFromUnknown,emoji,link_default,output_manager_default,prependEmoji,recordCliError,require_build_utils}from"../../chunks/chunk-75IAMKGV.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-D3AHZ5LI.js";import"../../chunks/chunk-2GHZGOWT.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_build_utils9=__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 as basename3,dirname as dirname3,extname,join as join13,resolve as resolve3}from"path";async function createDeploy(client,now,contextName,path2,createArgs,org,isSettingUpProject,archive){try{return await now.create(path2,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-H5CIDNMW.js"),result=await generateCertForDeploy(client,contextName,err.value);return result instanceof NowError?result:createDeploy(client,now,contextName,path2,createArgs,org,isSettingUpProject)}if(err.code==="not_found")throw new DeploymentNotFound({context:contextName});let certError=mapCertError(err);if(certError)return certError}throw err}}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(resolve4=>setTimeout(resolve4,1e3));for(let attempt=0;attempt<5;attempt++){attempt>0&&await new Promise(resolve4=>setTimeout(resolve4,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}var PROTECTION_METHODS=[{setting:"ssoProtection",id:"vercel_authentication",name:"Vercel Authentication"},{setting:"passwordProtection",id:"password",name:"Password Protection"}];async function getEnabledProtection(client,project){try{let settings=await client.fetch(`/v9/projects/${encodeURIComponent(project.id)}`,{accountId:project.accountId});return PROTECTION_METHODS.filter(method=>settings[method.setting])}catch(err){return output_manager_default.debug(`Could not read Deployment Protection settings: ${err}`),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,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);if(!remotes.some(remoteUrl=>{let repo=parseRepoUrl(remoteUrl);return repo&&SUPPORTED_PROVIDERS.has(repo.provider)})||client.nonInteractive&&remotes.length!==1||(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)}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}}var DescribeError=class extends Error{constructor(reason,message){super(message);this.reason=reason}};var DescribeTelemetryClient=class extends TelemetryClient{trackCliOptionId(value){value&&this.trackCliOption({option:"id",value:this.redactedValue})}trackCliOptionAwsAccountId(value){value&&this.trackCliOption({option:"aws-account-id",value:this.redactedValue})}trackCliFlagJson(value){value&&this.trackCliFlag("json")}};import{createHash as createHash3}from"node:crypto";import{createHash as createHash2}from"node:crypto";function getFunctionConfig(lambda){return{runtime:lambda.runtime,handler:lambda.handler,architecture:lambda.architecture,environment:Object.fromEntries(Object.entries(lambda.environment).filter(entry=>typeof entry[1]=="string")),..."launcherType"in lambda&&lambda.launcherType==="Nodejs"?{launcherType:lambda.launcherType,awsLambdaHandler:lambda.awsLambdaHandler,shouldAddHelpers:lambda.shouldAddHelpers,shouldAddSourcemapSupport:lambda.shouldAddSourcemapSupport,shouldDisableAutomaticFetchInstrumentation:lambda.shouldDisableAutomaticFetchInstrumentation,useWebApi:lambda.useWebApi}:{},memory:lambda.memory,affinity:lambda.affinity,maxConcurrency:lambda.maxConcurrency,maxDuration:lambda.maxDuration,regions:lambda.regions,functionFailoverRegions:lambda.functionFailoverRegions,supportsResponseStreaming:lambda.supportsResponseStreaming,framework:lambda.framework&&{...lambda.framework}}}var import_build_utils=__toESM(require_build_utils(),1),ROOT_BOOTSTRAP_PATH="bootstrap",USER_BOOTSTRAP_PATH="___vc_bootstrap",NATIVELY_WRAPPER_SUPPORTED_FAMILIES=["nodejs","python","ruby","java","dotnetcore","bun","executable"],BOOTSTRAP_SHIM=`#!/bin/sh
|
|
9
9
|
USER_BOOTSTRAP="/var/task/${USER_BOOTSTRAP_PATH}"
|
|
10
10
|
|
|
@@ -16,7 +16,7 @@ if [ -n "\${AWS_LAMBDA_EXEC_WRAPPER:-}" ]; then
|
|
|
16
16
|
fi
|
|
17
17
|
|
|
18
18
|
exec "$USER_BOOTSTRAP" "$@"
|
|
19
|
-
`;function hydrateLambdaFiles(lambda,encryptedEnv){let files=lambda.files??{};if(lambda.runtime==="container"||!encryptedEnv.filename||!encryptedEnv.contentBase64)return files;if(files[encryptedEnv.filename]=new import_build_utils.FileBlob({data:Buffer.from(encryptedEnv.contentBase64,"base64")}),lambda.supportsWrapper!==!0&&!NATIVELY_WRAPPER_SUPPORTED_FAMILIES.some(family=>lambda.runtime.startsWith(family))){if(!lambda.runtime.startsWith("provided"))throw new Error(`Serverless Function runtime ${lambda.runtime} does not support more than 4KB for environment variables`);let userBootstrap=files[ROOT_BOOTSTRAP_PATH];if(!userBootstrap)throw new Error(`Serverless Function runtime ${lambda.runtime} does not support more than 4KB for environment variables`);if(files[USER_BOOTSTRAP_PATH])throw new Error(`Cannot wrap "provided.*" lambda: reserved file path ${USER_BOOTSTRAP_PATH} is already in use. Please rename your file.`);files[USER_BOOTSTRAP_PATH]=userBootstrap,delete files[ROOT_BOOTSTRAP_PATH],files[ROOT_BOOTSTRAP_PATH]=new import_build_utils.FileBlob({data:BOOTSTRAP_SHIM,mode:33261})}return files}import{join as join6}from"node:path";var import_build_utils2=__toESM(require_build_utils(),1);import{join as join2}from"path";import{readFile}from"node:fs/promises";async function maybeReadJSON(path2){let contents;try{contents=await readFile(path2,"utf8")}catch(err){if(err.code!=="ENOENT")throw err;return}try{return JSON.parse(contents.charCodeAt(0)===65279?contents.slice(1):contents)}catch(err){throw err.message=`${path2}: ${err.message}`,err}}async function getBuildOutputConfig(outputDir){let configPath=getBuildOutputConfigPath(outputDir),config=await maybeReadJSON(configPath);if(!config)return;if(config.version!==3)throw new Error(`Expected \`version: 3\` in "${configPath}" file (received \`${config.version}\`)`);validateDeploymentId(config.deploymentId),validateExperimentalServicesV2(config.experimentalServicesV2);let framework=validateFrameworkVersion(config.framework);return{...config,framework}}function getBuildOutputConfigPath(outputDir){return join2(outputDir,"config.json")}var MAX_DEPLOYMENT_ID_LENGTH=32,MAX_FRAMEWORK_SLUG_LENGTH=50,MAX_FRAMEWORK_VERSION_LENGTH=50,VALID_DEPLOYMENT_ID_PATTERN=/^[a-zA-Z0-9_-]+$/;function validateDeploymentId(deploymentId){if(deploymentId&&deploymentId.length>MAX_DEPLOYMENT_ID_LENGTH)throw new import_build_utils2.NowBuildError({message:`The configured deploymentId "${deploymentId}" exceeds the maximum length of ${MAX_DEPLOYMENT_ID_LENGTH} characters. Please use a shorter deploymentId.`,code:"VC_BUILD_INVALID_DEPLOYMENT_ID_LENGTH"});if(deploymentId&&!VALID_DEPLOYMENT_ID_PATTERN.test(deploymentId))throw new import_build_utils2.NowBuildError({message:`The configured deploymentId "${deploymentId}" contains invalid characters. Only alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (_) are allowed.`,code:"VC_BUILD_INVALID_DEPLOYMENT_ID_CHARACTERS"})}function validateFrameworkVersion(framework){if(!framework)return;let{slug,version}=framework;if(typeof slug=="string"){if(typeof version!="string")throw new import_build_utils2.NowBuildError({message:`Invalid config.json: "version" type "${typeof version}" should be "string"`,code:"VC_BUILD_INVALID_CONFIG_JSON_FRAMEWORK_VERSION_TYPE"});if(slug.length>MAX_FRAMEWORK_SLUG_LENGTH){let trimmedSlug=slug.slice(0,MAX_FRAMEWORK_SLUG_LENGTH);throw new import_build_utils2.NowBuildError({message:`Invalid config.json: "framework.slug" length ${slug.length} > ${MAX_FRAMEWORK_SLUG_LENGTH}. "${trimmedSlug}..."`,code:"VC_BUILD_INVALID_CONFIG_JSON_FRAMEWORK_SLUG_LENGTH"})}if(version.length>MAX_FRAMEWORK_VERSION_LENGTH){let trimmedVersion=version.slice(0,MAX_FRAMEWORK_VERSION_LENGTH);throw new import_build_utils2.NowBuildError({message:`Invalid config.json: "framework.version" length ${version.length} > ${MAX_FRAMEWORK_VERSION_LENGTH}. "${trimmedVersion}..."`,code:"VC_BUILD_INVALID_CONFIG_JSON_FRAMEWORK_VERSION_LENGTH"})}return framework}}function validateExperimentalServicesV2(experimentalServicesV2){if(experimentalServicesV2!==void 0&&(!experimentalServicesV2||typeof experimentalServicesV2!="object"||Array.isArray(experimentalServicesV2)))throw new import_build_utils2.NowBuildError({code:"INVALID_BUILD_OUTPUT_CONFIG",message:'Invalid config.json: "experimentalServicesV2" must be an object.'})}async function getBuildOutputConfigOrThrow(outputDir){let config=await getBuildOutputConfig(outputDir);if(config)return config;throw new Error(`Config file was not found at "${getBuildOutputConfigPath(outputDir)}"`)}var import_build_utils3=__toESM(require_build_utils(),1);function isRouteMiddleware(route){return"middlewarePath"in route&&typeof route.middlewarePath=="string"}var cache=new WeakMap;function getMiddlewareRouting(buildResult){let cached=cache.get(buildResult.functions);if(cached&&cached.routes===buildResult.routes)return cached.routing;let routing=new Map,{lambdas,edgeFunctions}=buildResult.functions;for(let route of buildResult.routes){if(!isRouteMiddleware(route))continue;let outputPath=route.middlewarePath;!lambdas.has(outputPath)&&!edgeFunctions.has(outputPath)&&(outputPath=outputPath.replace(/^\//,""));let output=lambdas.get(outputPath)??edgeFunctions.get(outputPath);if(!outputPath||!output)throw new import_build_utils3.NowBuildError({message:`Mapping ${route.middlewarePath} not found. Maybe you provided a wrong middlewarePath?`,code:"middleware_path_not_found"});let index=routing.get(outputPath)?.index??routing.size;routing.set(outputPath,output.type==="EdgeFunction"?{type:"middleware",middlewarePath:route.middlewarePath,outputPath,edgeFunction:output,index}:{type:"middleware-lambda",middlewarePath:route.middlewarePath,outputPath,index})}return cache.set(buildResult.functions,{routes:buildResult.routes,routing}),routing}var import_semver=__toESM(require_semver(),1),import_build_utils4=__toESM(require_build_utils(),1);import{createHash}from"crypto";import fs2 from"fs";var fileSizeCache=new Map,getFileSize=path2=>{if(!path2)return Promise.resolve(0);let cached=fileSizeCache.get(path2);if(cached)return cached;let promise=fs2.promises.lstat(path2).then(stats=>stats.size);return fileSizeCache.set(path2,promise),promise},collectUncompressedSize=async(files,ignoreFn)=>{let size=0;return await Promise.all(Object.keys(files).map(async fileKey=>{if(!ignoreFn?.(fileKey)){if(files[fileKey].type==="FileBlob")size+=files[fileKey].data.length;else if(files[fileKey].type==="FileFsRef"){let curSize=files[fileKey].size??await getFileSize(files[fileKey].fsPath);size+=curSize}}})),size};var MIB=1024*1024,MAX_UNCOMPRESSED_FUNCTION_SIZE_BYTES=250*MIB,LAMBDA_RESERVED_UNCOMPRESSED_SIZE_BYTES=25*MIB,LARGE_FUNCTION_THRESHOLD_BYTES=MAX_UNCOMPRESSED_FUNCTION_SIZE_BYTES-LAMBDA_RESERVED_UNCOMPRESSED_SIZE_BYTES,MANIFEST_FILE_NAMES=["routes-manifest.json","server/pages-manifest.json","server/app-paths-manifest.json","app-path-routes-manifest.json"],TEST_DYNAMIC_ROUTE=/\/\[[^\/]+?\](?=\/|$)/;function isNextjsDynamicRoute(route){return route=route.startsWith("/")?route:`/${route}`,TEST_DYNAMIC_ROUTE.test(route)}function computeLambdaFieldsSignature(lambda,lambdaFields){let parts=[];for(let field of lambdaFields)parts.push(JSON.stringify(lambda[field]));return parts.join("|")}async function getLambdaFileSizeMetadata(lambdaFiles){let fileKeys=Object.keys(lambdaFiles),fileSizes=new Map,uncompressedSize=0;for(let fileKey of fileKeys){let file=lambdaFiles[fileKey];if(file===void 0)throw new Error("Expected lambdaFiles[fileKey] to be defined");let fileSize=0;file.type==="FileBlob"?fileSize=file.data.length:file.type==="FileFsRef"&&(fileSize=await collectUncompressedSize({[fileKey]:file},void 0)),fileSizes.set(fileKey,fileSize),uncompressedSize+=fileSize}return{fileKeys,fileSizes,uncompressedSize}}async function groupLambdas(lambdas,options){let{force}=options,lambdaFields=["allowQuery","affinity","architecture","awsLambdaHandler","environment","experimentalResponseStreaming","experimentalTriggers","framework","handler","maxConcurrency","maxDuration","memory","operationType","regions","runtime","runtimeLanguage","shouldAddHelpers","shouldAddSourcemapSupport","shouldDisableAutomaticFetchInstrumentation","supportsCancellation","supportsMultiPayloads","supportsResponseStreaming","supportsWrapper","useWebApi","functionFailoverRegions"],_typeCheck=lambdaFields,fieldsToCompare=force==="all"?["runtime","maxConcurrency"]:lambdaFields,maxUncompressedFunctionSize=LARGE_FUNCTION_THRESHOLD_BYTES,maxBundleSizeMb=options.maxBundleSizeMb;if(maxBundleSizeMb!==void 0&&Number.isFinite(maxBundleSizeMb)){let customMaxUncompressedFunctionSize=Math.floor(maxBundleSizeMb*MIB);output_manager_default.warn(`Warn: custom max uncompressed function size of ${customMaxUncompressedFunctionSize/MIB}MiB configured`),maxUncompressedFunctionSize=Math.min(customMaxUncompressedFunctionSize,MAX_UNCOMPRESSED_FUNCTION_SIZE_BYTES)}let seenLambdas=new Map;for(let[name,lambda]of Object.entries(lambdas)){if(!lambda.experimentalAllowBundling||!lambda.files)continue;let existingNames=seenLambdas.get(lambda);existingNames?existingNames.push(name):seenLambdas.set(lambda,[name])}let handlerDigestPromiseCache=new Map,getHandlerDigest=handlerFile=>{if(!handlerFile)return Promise.resolve(void 0);let cached=handlerDigestPromiseCache.get(handlerFile);if(cached)return cached;let promise=(async()=>{try{let handlerStream=handlerFile.toStream(),handlerBuffer=await(0,import_build_utils4.streamToBuffer)(handlerStream),handlerBytes=new Uint8Array(handlerBuffer.buffer,handlerBuffer.byteOffset,handlerBuffer.byteLength);return createHash("sha1").update(handlerBytes).digest("hex")}catch{return}})();return handlerDigestPromiseCache.set(handlerFile,promise),promise},bundlesBySignature=new Map,allBundledLambdas=[];for(let[lambda,lambdaNames]of seenLambdas){let lambdaFiles=lambda.files;if(!lambdaFiles)continue;let signature=computeLambdaFieldsSignature(lambda,fieldsToCompare),{fileKeys,fileSizes,uncompressedSize}=await getLambdaFileSizeMetadata(lambdaFiles),handlerDigest=await getHandlerDigest(lambdaFiles[lambda.handler]),compatibleBundles=bundlesBySignature.get(signature),isLarge=uncompressedSize>=LARGE_FUNCTION_THRESHOLD_BYTES,foundMatchingBundle=!1;if(compatibleBundles&&!isLarge)for(let bundleMeta of compatibleBundles){if(bundleMeta.isLarge||!(handlerDigest===bundleMeta.handlerDigest)&&force!=="all")continue;let uncompressedBytesIncrease=0;for(let fileKey of fileKeys){let incomingFileSize=fileSizes.get(fileKey)??0,existingFileSize=bundleMeta.fileSizesByKey.get(fileKey);existingFileSize===void 0?uncompressedBytesIncrease+=incomingFileSize:uncompressedBytesIncrease+=incomingFileSize-existingFileSize}let newTotalSize=bundleMeta.uncompressedBytes+uncompressedBytesIncrease;if(newTotalSize<=maxUncompressedFunctionSize){foundMatchingBundle=!0,bundleMeta.uncompressedBytes=newTotalSize,bundleMeta.lambdaNames.push(...lambdaNames);for(let fileKey of fileKeys)bundleMeta.fileSizesByKey.set(fileKey,fileSizes.get(fileKey)??0);let potentialLambdaFiles=bundleMeta.lambda.files;potentialLambdaFiles&&(bundleMeta.lambda.files=Object.assign(potentialLambdaFiles,lambdaFiles));break}}if(!foundMatchingBundle){let newBundleMeta={lambda,signature,handlerDigest,isLarge,uncompressedBytes:uncompressedSize,fileSizesByKey:new Map(fileSizes),lambdaNames:[...lambdaNames]},signatureBundles=bundlesBySignature.get(signature);signatureBundles||(signatureBundles=[],bundlesBySignature.set(signature,signatureBundles)),signatureBundles.push(newBundleMeta),allBundledLambdas.push(newBundleMeta)}}let finalLambdas=Object.assign({},lambdas);options.debug&&(output_manager_default.debug("GROUP_LAMBDAS: "+JSON.stringify(allBundledLambdas.map(bundleMeta=>({lambdaNames:bundleMeta.lambdaNames,signature:bundleMeta.signature,uncompressedBytes:bundleMeta.uncompressedBytes})),null,2)),output_manager_default.debug(`total grouped lambdas: ${allBundledLambdas.length}`));for(let bundleMeta of allBundledLambdas){let lambda=bundleMeta.lambda;for(let lambdaName of bundleMeta.lambdaNames)finalLambdas[lambdaName]=lambda;if(lambda.framework?.slug==="nextjs"&&lambda.framework.version){let CORRECTED_MANIFESTS_VERSION="v12.2.0";if(import_semver.default.gte(lambda.framework.version,CORRECTED_MANIFESTS_VERSION)){let pageFiles=[],manifestFileKeys={},manifestFileNames=MANIFEST_FILE_NAMES;for(let fileKey of Object.keys(lambda.files||{})){let isPageFile=fileKey.includes("server/pages/"),isAppFile=fileKey.includes("server/app/");if(isPageFile||isAppFile){let relativePageFile=fileKey.split(`server/${isPageFile?"pages":"app"}/`).pop();relativePageFile&&pageFiles.push(relativePageFile)}for(let manifestFileName of manifestFileNames)fileKey.endsWith(`/${manifestFileName}`)&&(manifestFileKeys[manifestFileName]=fileKey)}let appPathRoutesManifestFilesKey=manifestFileKeys["app-path-routes-manifest.json"],appPathRoutesManifestFile=appPathRoutesManifestFilesKey&&lambda.files?.[appPathRoutesManifestFilesKey],appPathRoutesManifest=appPathRoutesManifestFile?await(0,import_build_utils4.streamToBuffer)(appPathRoutesManifestFile.toStream()).then(res=>JSON.parse(res.toString("utf8"))).catch(()=>({})):{};for(let manifestFileName of manifestFileNames){let manifestFilesKey=manifestFileKeys[manifestFileName],manifestFile=manifestFilesKey&&lambda.files?.[manifestFilesKey];if(!manifestFile)continue;let manifestData=JSON.parse((await(0,import_build_utils4.streamToBuffer)(manifestFile.toStream())).toString("utf8")),normalizedPages=new Set(pageFiles.map(page=>(page=`/${page.replace(/\.js$/,"")}`,page==="/index"&&(page="/"),appPathRoutesManifest[page]||page)));switch(manifestFileName){case"routes-manifest.json":{let filterItem=item=>normalizedPages.has(item.page);manifestData.dynamicRoutes=manifestData.dynamicRoutes?.filter(filterItem),manifestData.staticRoutes=manifestData.staticRoutes?.filter(filterItem);break}case"server/pages-manifest.json":{for(let key of Object.keys(manifestData))isNextjsDynamicRoute(key)&&!normalizedPages.has(key)&&delete manifestData[key];break}case"server/app-paths-manifest.json":{if(appPathRoutesManifest)for(let key of Object.keys(manifestData)){let normalizedKey=appPathRoutesManifest[key]||key.replace(/(^|\/)(page|route)$/,"");isNextjsDynamicRoute(normalizedKey)&&!normalizedPages.has(normalizedKey)&&delete manifestData[key]}break}}lambda.files&&(lambda.files[manifestFilesKey]=new import_build_utils4.FileBlob({contentType:"application/json",data:JSON.stringify(manifestData)}))}}}}return finalLambdas}async function groupBundleableLambdas(params){let lambdas={};for(let[path2,lambda]of params.functions.lambdas)lambda.experimentalAllowBundling&&(lambdas[path2]=lambda);for(let[path2,prerender]of params.functions.prerenders)prerender.lambda.experimentalAllowBundling&&(lambdas[path2]=prerender.lambda);if(Object.keys(lambdas).length===0)return;let grouped=await groupLambdas(lambdas,{force:void 0,maxBundleSizeMb:params.options.maxBundleSizeMb,debug:params.options.debugGroupLambdas});for(let[path2,lambda]of Object.entries(grouped))if(params.functions.lambdas.has(path2))params.functions.lambdas.set(path2,lambda);else{let prerender=params.functions.prerenders.get(path2);if(prerender)prerender.lambda=lambda;else throw new Error(`Grouped lambda "${path2}" does not match any build output`)}}var import_build_utils6=__toESM(require_build_utils(),1);import{join as join3,relative}from"path";import{readdir,stat}from"fs/promises";var SUFFIX=".func";async function*createFunctionEntriesIterator(dir,root=dir){let entries;try{entries=await readdir(dir,{withFileTypes:!0})}catch(error){if(!(typeof error=="object"&&error!==null&&"code"in error)||error.code!=="ENOENT"&&error.code!=="ENOTDIR")throw error;entries=[]}let names;for(let entry of entries){let absolutePath=join3(dir,entry.name),isSymbolicLink=entry.isSymbolicLink();if(entry.isDirectory()||isSymbolicLink&&(await stat(absolutePath)).isDirectory())if(entry.name.endsWith(SUFFIX)){names??=new Set(entries.map(e=>e.name));let baseName=entry.name.slice(0,-SUFFIX.length);yield{hasPrerenderConfig:names.has(`${baseName}.prerender-config.json`),isSymbolicLink,path:relative(root,absolutePath.substring(0,absolutePath.length-SUFFIX.length))}}else yield*createFunctionEntriesIterator(absolutePath,root)}}import{dirname,isAbsolute,join as join4,relative as relative2,resolve as resolve2,sep}from"node:path";var import_build_utils5=__toESM(require_build_utils(),1);import{lstat,readlink,realpath,readdir as readdir2,stat as stat2}from"node:fs/promises";import assert from"assert";import path from"path";async function glob(options){if(!path.isAbsolute(options.cwd))throw new Error(`basePath/cwd must be an absolute path (${options.cwd})`);let results={},statCache={},symlinks={},files=await walkAll(options.cwd,!!options.follow,statCache,symlinks),dirs=new Set,dirsWithEntries=new Set;for(let relativePath of files){let fsPath=path.join(options.cwd,relativePath),stats=statCache[fsPath];assert(stats,`statCache does not contain value for ${relativePath}`);let isSymlink=symlinks[fsPath];if(options.follow&&(isSymlink||(await lstat(fsPath)).isSymbolicLink())){let target=await readlink(fsPath),absoluteTarget=path.resolve(path.dirname(fsPath),target);if(path.relative(options.cwd,absoluteTarget).startsWith(`..${path.sep}`))continue}if(isSymlink||stats.isFile()||stats.isDirectory()){isSymlink&&(stats=await lstat(fsPath));let dirname3=path.dirname(relativePath);if(dirsWithEntries.add(dirname3),stats.isDirectory()){dirs.add(relativePath);continue}results[relativePath]=new import_build_utils5.FileFsRef({mode:stats.mode,fsPath,size:stats.size})}}if(options.includeDirectories)for(let relativePath of dirs){if(dirsWithEntries.has(relativePath))continue;let fsPath=path.join(options.cwd,relativePath),stats=statCache[fsPath];results[relativePath]=new import_build_utils5.FileFsRef({mode:stats.mode,fsPath,size:stats.size})}return results}async function walkAll(cwd,follow,statCache,symlinks){let files=[];async function walk(dirAbs,realDir,ancestors){let entries;try{entries=await readdir2(dirAbs,{withFileTypes:!0})}catch(err){let code2=err.code;if(code2==="ENOENT"||code2==="ENOTDIR")return;throw err}await Promise.all(entries.map(async entry=>{let abs=path.join(dirAbs,entry.name);if(entry.isSymbolicLink())if(follow){let stats=await stat2(abs).catch(()=>lstat(abs).catch(()=>null));if(stats===null)return;if(statCache[abs]=stats,files.push(abs),stats.isDirectory()){let real=await realpath(abs).catch(()=>null);real!==null&&!ancestors.has(real)&&await walk(abs,real,new Set(ancestors).add(real))}}else{let stats=await lstat(abs).catch(()=>null);if(stats===null)return;statCache[abs]=stats,symlinks[abs]=!0,files.push(abs)}else if(entry.isDirectory()){let stats=await lstat(abs).catch(()=>null);if(stats===null)return;statCache[abs]=stats,files.push(abs);let real=path.join(realDir,entry.name);await walk(abs,real,new Set(ancestors).add(real))}else{let stats=await lstat(abs).catch(()=>null);if(stats===null)return;statCache[abs]=stats,files.push(abs)}}))}let cwdReal=follow?await realpath(cwd).catch(()=>null):cwd;return cwdReal!==null&&await walk(cwd,cwdReal,new Set([cwdReal])),files.map(abs=>path.relative(cwd,abs)).sort((a,b)=>a.localeCompare(b,"en"))}import{isNativeError}from"node:util/types";import{readlink as readlink2,realpath as realpath2}from"node:fs/promises";async function readFunctions(params){let fileFsRefsCache=new Map,entries=[],functionsDir=join4(params.outputDir,"functions"),iterator=enumerate(createFunctionEntriesIterator(functionsDir));await Promise.all(Array.from({length:params.concurrency??32},async()=>{for await(let[index,entry]of iterator)entries[index]=await deserializeFunctionEntry({prebuilt:params.prebuilt,entry,fileFsRefsCache,functionsDir,repoRootPath:params.repoRootPath})}));let serverActionsManifestPaths=new Set,edgeFunctions=new Map,unsortedPrerenders=new Map,functionSymlinks=new Map,lambdas=new Map;for(let functionEntry of entries)functionEntry.symlinkTarget!==void 0&&functionSymlinks.set(functionEntry.path,functionEntry.symlinkTarget),functionEntry.serverActionsManifestPath&&serverActionsManifestPaths.add(functionEntry.serverActionsManifestPath),functionEntry.output?.type==="Prerender"?unsortedPrerenders.set(functionEntry.path,functionEntry.output):functionEntry.output?.type==="Lambda"?lambdas.set(functionEntry.path,functionEntry.output):functionEntry.output?.type==="EdgeFunction"&&edgeFunctions.set(functionEntry.path,functionEntry.output);for(let[path2,target]of functionSymlinks){let destFunction=unsortedPrerenders.get(target)?.lambda??edgeFunctions.get(target)??lambdas.get(target);if(!destFunction)throw new Error(`Could not find target "${target}" Lambda or EdgeFunction for path "${path2}"`);let srcPrerender=unsortedPrerenders.get(path2);if(!srcPrerender)destFunction.type==="Lambda"?lambdas.set(path2,destFunction):destFunction.type==="EdgeFunction"&&edgeFunctions.set(path2,destFunction);else{if(destFunction.type!=="Lambda")throw new Error(`Unexpected function type "${destFunction.type}" at path "${path2}"`);srcPrerender.lambda=destFunction}}let prerenders=new Map;for(let[path2,prerender]of[...unsortedPrerenders].sort((a,b)=>(a[1].group??0)-(b[1].group??0)))validatePrerender(prerender),prerenders.set(path2,prerender);return{edgeFunctions,lambdas,prerenders,serverActionsManifestPaths}}async function*enumerate(iterable){let index=0;for await(let item of iterable)yield[index++,item]}async function deserializeFunctionEntry(params){let functionDir=join4(params.functionsDir,`${params.entry.path}.func`),prerenderConfigPath=join4(params.functionsDir,`${params.entry.path}.prerender-config.json`),configPromise=params.entry.hasPrerenderConfig?maybeReadJSON(prerenderConfigPath):void 0;configPromise?.catch(()=>{});let lambda,serverActionsManifestPath,symlinkTarget;if(params.entry.isSymbolicLink)symlinkTarget=await readlink2(functionDir).then(link=>join4(dirname(params.entry.path),link).slice(0,-5));else{let functionConfigPath=join4(functionDir,".vc-config.json"),[functionConfig,files]=await Promise.all([maybeReadJSON(functionConfigPath),glob({cwd:functionDir,includeDirectories:!0})]);if(!functionConfig)throw new Error(`Could not load function config: "${functionConfigPath}"`);if(delete files[".vc-config.json"],functionConfig.filePathMap&&await hydrateFilesMap(files,functionConfig.filePathMap,params.repoRootPath,params.fileFsRefsCache,params.prebuilt),"type"in functionConfig&&functionConfig.type==="EdgeFunction"||functionConfig.runtime==="edge")return{path:params.entry.path,output:new import_build_utils6.EdgeFunction({deploymentTarget:"v8-worker",...functionConfig,files})};let supportsResponseStreaming=functionConfig.supportsResponseStreaming??functionConfig.experimentalResponseStreaming;lambda="launcherType"in functionConfig&&functionConfig.launcherType==="Nodejs"?new import_build_utils6.NodejsLambda({...functionConfig,files,supportsResponseStreaming:functionConfig.awsLambdaHandler===void 0||functionConfig.awsLambdaHandler===""||supportsResponseStreaming}):new import_build_utils6.Lambda({...functionConfig,files,supportsResponseStreaming}),serverActionsManifestPath=functionConfig.filePathMap?.[".next/server/server-reference-manifest.json"]}if(configPromise){let prerenderConfig=await configPromise;if(prerenderConfig)return{path:params.entry.path,symlinkTarget,serverActionsManifestPath,output:new import_build_utils6.Prerender({...prerenderConfig,fallback:await deserializePrerenderFallback(prerenderConfigPath,prerenderConfig.fallback,params),initialMetadata:sanitizeInitialMetadata(prerenderConfig.initialMetadata),lambda})}}return{path:params.entry.path,symlinkTarget,output:lambda,serverActionsManifestPath}}function validatePrerender(prerender){if(prerender.lambda===void 0)throw new Error('Prerender "buildResult" is missing "lambda" property')}async function hydrateFilesMap(files,filesMap,repoRootPath,fileFsRefsCache,prebuilt){let rootPath=prebuilt?await realpath2(repoRootPath):void 0;async function hydrateFile(projectPath){let fsPath=join4(repoRootPath,projectPath);rootPath!==void 0&&await validatePrebuiltFilePath(fsPath,rootPath,`file map source "${projectPath}"`,!0);let file=await import_build_utils6.FileFsRef.fromFsPath({fsPath});return fileFsRefsCache.set(projectPath,file),file}let pending;for(let functionPath in filesMap){let projectPath=filesMap[functionPath],cached=fileFsRefsCache.get(projectPath);if(cached&&!(cached instanceof Promise)){files[functionPath]=cached;continue}let filePromise=cached;if(!filePromise){let promise=hydrateFile(projectPath);fileFsRefsCache.set(projectPath,promise),filePromise=promise}(pending??=[]).push(filePromise.then(file=>{files[functionPath]=file}))}pending&&await Promise.all(pending)}async function validatePrebuiltFilePath(fsPath,rootPath,source,enableDanglingSymlinks=!1){let resolvedPath;try{resolvedPath=await realpath2(fsPath)}catch(error){if(!enableDanglingSymlinks||!isNativeError(error)||!("code"in error)||error.code!=="ENOENT")throw error;let target=await readlink2(fsPath),parentPath=await validatePrebuiltFilePath(dirname(fsPath),rootPath,source);resolvedPath=resolve2(parentPath,target)}let sourcePath=relative2(rootPath,resolvedPath);if(sourcePath===".."||sourcePath.startsWith(`..${sep}`)||isAbsolute(sourcePath))throw new import_build_utils6.NowBuildError({code:"INVALID_PREBUILT_FILE_PATH",message:`Prebuilt ${source} must be inside the uploaded project.`});return resolvedPath}function sanitizeInitialMetadata(initialMetadata){try{if(typeof initialMetadata!="object"||initialMetadata===null||Array.isArray(initialMetadata))return;let{compute,htmlSize}=initialMetadata;return compute!=="blocking"&&compute!=="resuming"&&compute!=="static"||htmlSize!==void 0&&(!Number.isSafeInteger(htmlSize)||htmlSize<0)?void 0:{compute,...htmlSize!==void 0&&{htmlSize}}}catch{return}}async function deserializePrerenderFallback(prerenderConfigPath,fallback,options){if(fallback==null)return null;let path2=typeof fallback=="string"?fallback:fallback.fsPath,fsPath=join4(dirname(prerenderConfigPath),path2);return options.prebuilt&&await validatePrebuiltFilePath(fsPath,await realpath2(options.repoRootPath),`prerender fallback "${path2}"`),typeof fallback=="string"?import_build_utils6.FileFsRef.fromFsPath({fsPath}):fallback.mode!==void 0?new import_build_utils6.FileFsRef({mode:fallback.mode,size:fallback.size,contentType:fallback.contentType,fsPath}):import_build_utils6.FileFsRef.fromFsPath({mode:fallback.mode,size:fallback.size,contentType:fallback.contentType,fsPath})}var import_async_sema=__toESM(require_async_sema(),1),import_ignore=__toESM(require_ignore(),1);import{basename,isAbsolute as isAbsolute2,join as join5,relative as relative3,sep as sep2}from"node:path";import{readFile as readFile2,readdir as readdir3,realpath as realpath3,stat as stat3}from"node:fs/promises";function contains(root,path2){let rel=relative3(root,path2);return rel!==".."&&!rel.startsWith(`..${sep2}`)&&!isAbsolute2(rel)}function invalidSource(){throw new DescribeError("invalid_build_output","Build output references files outside the authorized output or includes excluded source files. Remove unsafe links and excluded file mappings, then rebuild.")}var vcs=(0,import_ignore.default)().add([".hg",".git",".gitmodules",".svn","CVS"]),dependencies=(0,import_ignore.default)().add(["node_modules",".next",".yarn/cache",".pnp*",".venv","venv","__pycache__","/target"]);async function readIgnore(root){let read=name=>readFile2(join5(root,name),"utf8").catch(error=>{if(error.code==="ENOENT")return"";throw error}),[vercelignore,nowignore]=await Promise.all([read(".vercelignore"),read(".nowignore")]);if(vercelignore&&nowignore)throw new DescribeError("invalid_build_output","Cannot use both .vercelignore and .nowignore. Remove the deprecated .nowignore file and retry.");return(0,import_ignore.default)().add((vercelignore||nowignore).replace(/(\n|^)\.\//g,"$1"))}async function validateBuildOutput(options){let root=await realpath3(options.repoRootPath),output=await realpath3(options.outputDir),expectedOutput=join5(root,relative3(options.repoRootPath,options.outputDir));(!contains(root,output)||relative3(expectedOutput,output)!=="")&&invalidSource();let project=options.directory?await realpath3(options.directory):root,bases=[root];if(project!==root&&contains(root,project))for(let segment of relative3(root,project).split(sep2))bases.push(join5(bases[bases.length-1],segment));let ignores=await Promise.all(bases.map(async base=>({base,rules:await readIgnore(base)}))),sema=new import_async_sema.default(32),limit=async fn=>{await sema.acquire();try{return await fn()}finally{sema.release()}},checkSource=async path2=>{let resolved=await limit(()=>realpath3(path2));for(let source of[join5(root,relative3(options.repoRootPath,path2)),resolved]){contains(root,source)||invalidSource();let rel=relative3(root,source).split(sep2).join("/");if(rel&&(vcs.ignores(rel)&&invalidSource(),!contains(output,source)))for(let{base,rules}of ignores){if(!contains(base,source))continue;let relToBase=relative3(base,source).split(sep2).join("/");relToBase&&rules.ignores(relToBase)&&!dependencies.ignores(relToBase)&&invalidSource()}}return resolved},checked=new Map,validateSource=path2=>{let result=checked.get(path2);return result||(result=checkSource(path2),checked.set(path2,result)),result},configs=[],visited=new Set;async function walk(dir,ancestors){visited.add(dir);let next=new Set(ancestors).add(dir),entries=await Promise.all((await limit(()=>readdir3(dir))).map(async name=>{let path2=join5(dir,name),resolved=await limit(()=>realpath3(path2));return(!contains(output,resolved)||next.has(resolved))&&invalidSource(),{path:path2,resolved,stats:await limit(()=>stat3(resolved))}}));for(let{path:path2,resolved,stats}of entries)stats.isDirectory()?visited.has(resolved)||await walk(resolved,next):basename(path2)===".vc-config.json"&&configs.push(resolved)}return await walk(output,new Set),await Promise.all(configs.map(async path2=>{let config=JSON.parse(await limit(()=>readFile2(path2,"utf8")));await Promise.all(Object.values(config.filePathMap??{}).map(source=>(typeof source!="string"&&invalidSource(),validateSource(join5(options.repoRootPath,source)))))})),validateSource}async function prepareFunctions(options){await validateBuildOutput(options);let config=await getBuildOutputConfigOrThrow(options.outputDir);if(config.experimentalServicesV2!==void 0)throw new DescribeError("unsupported_output","This build contains service outputs, which describe does not support.");let functions=await readFunctions({outputDir:options.outputDir,repoRootPath:options.repoRootPath,prebuilt:!0});if(functions.edgeFunctions.size)throw new DescribeError("unsupported_output","This build contains Edge Functions, which cannot be provisioned as AWS Lambda functions.");await groupBundleableLambdas({functions,options:{}});let allFunctions=[...functions.lambdas,...functions.prerenders],groups=new Map,middlewarePaths=getMiddlewareRouting({routes:config.routes??[],functions});for(let[path2,output]of allFunctions){let lambda=output.type==="Prerender"?output.lambda:output;if(lambda.runtime==="container")throw new DescribeError("unsupported_output","This build contains container functions. Describe supports native AWS Lambda functions only.");let outputs=groups.get(lambda)??[];groups.set(lambda,outputs),outputs.push({sourceKind:output.type==="Prerender"?"prerender":"lambda",middleware:output.type==="Lambda"&&middlewarePaths.has(path2)?{}:void 0,path:path2})}return[...groups].map(([lambda,outputs])=>({lambda,outputs}))}import{writeFile}from"node:fs/promises";import{z}from"zod/v3";var descriptorSchema=z.object({Architectures:z.array(z.string()).optional(),Environment:z.object({Variables:z.record(z.string())}),EphemeralStorage:z.object({Size:z.number()}).optional(),FunctionName:z.string().min(1),Handler:z.string(),Layers:z.array(z.string()),MemorySize:z.number(),Region:z.string().min(1),ResolvableLayers:z.record(z.object({url:z.string()})),Runtime:z.string(),Tags:z.record(z.string()),Timeout:z.number().optional()});async function describeFunctions(client,params){let functions=await prepareFunctions({directory:params.directory,repoRootPath:params.repoRootPath,outputDir:params.outputDir}),buildEnv=z.object({VERCEL_ENCRYPTED_ENV_FILENAME:z.string().min(1),VERCEL_ENCRYPTED_ENV_CONTENT:z.string().min(1)}).parse((await fetchDeploymentBuildEnv(client,params.deploymentId,{quiet:params.quiet})).buildEnv),lambdas=(await Promise.all(functions.map(async({lambda,outputs})=>{lambda.files=hydrateLambdaFiles(lambda,{filename:buildEnv.VERCEL_ENCRYPTED_ENV_FILENAME,contentBase64:buildEnv.VERCEL_ENCRYPTED_ENV_CONTENT});let zip=await lambda.createZip(),bytes2=new Uint8Array(zip.buffer,zip.byteOffset,zip.byteLength),digest=createHash2("sha256").update(bytes2).digest("hex");await writeFile(join6(params.zipDirectory,`${digest}.zip`),bytes2,{mode:384});let config=getFunctionConfig(lambda),input={...config,framework:config.framework&&{slug:config.framework.slug},digest,size:bytes2.length};return outputs.map(output=>({...output,lambda:input}))}))).flat(),{descriptors}=z.object({descriptors:z.array(z.array(descriptorSchema).min(1))}).parse(await client.fetch(`/v2/deployments/${params.deploymentId}/builds/function-descriptors`,{method:"POST",body:JSON.stringify({lambdas}),headers:{"content-type":"application/json"},accountId:params.teamId,retry:{retries:0}}));if(descriptors.length!==lambdas.length)throw new Error("Descriptor count does not match function outputs");return lambdas.map(({path:path2,lambda},index)=>{let regional=descriptors[index];if(new Set(regional.map(d=>d.FunctionName)).size!==1)throw new Error("Inconsistent regional function name");return{path:path2,digest:lambda.digest,size:lambda.size,regional}})}import{isDeepStrictEqual}from"node:util";import{join as join8}from"node:path";import{mkdir as mkdir2,mkdtemp,rename,rm,stat as stat5,writeFile as writeFile3}from"node:fs/promises";var import_build_utils7=__toESM(require_build_utils(),1);import{basename as basename2,join as join7,relative as relative4,sep as sep3}from"node:path";import{copyFile,cp,mkdir,readFile as readFile3,readdir as readdir4,stat as stat4,writeFile as writeFile2}from"node:fs/promises";async function prepareContinuation(params){let{directory,outputDir,destination,manifest,repoRootPath=directory}=params,validateSource=await validateBuildOutput({directory,outputDir,repoRootPath});await cp(outputDir,destination,{recursive:!0,dereference:!0,filter:path2=>basename2(path2)===".vc-config.json"||!relative4(outputDir,path2).split(sep3).slice(0,-1).some(segment=>segment.endsWith(".func"))}),await writeFile2(join7(destination,"provision.json"),JSON.stringify(manifest));let manifests=new Set(await packageManifests(directory));if(repoRootPath!==directory)for(let path2 of await packageManifests(repoRootPath))manifests.add(path2);for(let path2 of Object.keys(manifest)){let configPath=join7(destination,"functions",`${path2}.func`,".vc-config.json"),config=JSON.parse(await readFile3(configPath,"utf8"));for(let[file,source]of Object.entries(config.filePathMap??{}))basename2(file)==="package.json"&&manifests.add(join7(repoRootPath,source));delete config.filePathMap,await writeFile2(configPath,JSON.stringify({...config,architecture:new import_build_utils7.Lambda({...config,files:{}}).architecture}))}let[firstFunction]=Object.keys(manifest);if(firstFunction!==void 0)for(let[i,path2]of[...manifests].entries()){let target=join7(destination,"functions",`${firstFunction}.func`,"__byoc_security__",String(i));await mkdir(target,{recursive:!0}),await copyFile(await validateSource(path2),join7(target,"package.json"))}}async function packageManifests(root){let modules=join7(root,"node_modules"),names=await readdir4(modules).catch(()=>[]),packages=await Promise.all(names.map(async name=>name.startsWith(".")?[]:name.startsWith("@")?(await readdir4(join7(modules,name)).catch(()=>[])).map(entry=>join7(modules,name,entry)):[join7(modules,name)]));return(await Promise.all([root,...packages.flat()].map(dir=>{let path2=join7(dir,"package.json");return stat4(path2).then(()=>path2,()=>{})}))).filter(p=>p!==void 0)}async function describeDeployment(client,params){let output=join8(params.directory,".vercel",params.deploymentId),buildOutput=join8(params.directory,".vercel/output"),build=join8(output,"build"),repoRootPath=params.repoRootPath??params.directory,source=await exists(buildOutput)&&!await exists(join8(buildOutput,"provision.json"))?buildOutput:build;if(!await exists(join8(source,"config.json")))throw new DescribeError("prebuilt_not_found",`No local build output found. Run \`vercel build --id ${params.deploymentId}\` before \`vercel deploy describe\`.`);await mkdir2(join8(params.directory,".vercel"),{recursive:!0});let staging=await mkdtemp(join8(params.directory,".vercel",`.describe-${params.deploymentId}-`)),removeStaging=!0,functions=new Map,layers={},manifest={};try{await mkdir2(join8(staging,"zips")),await mkdir2(join8(staging,"layers"));let described=await describeFunctions(client,{deploymentId:params.deploymentId,directory:params.directory,repoRootPath,outputDir:source,quiet:params.quiet,teamId:params.teamId,zipDirectory:join8(staging,"zips")});for(let{path:path2,digest,size,regional}of described){for(let descriptor of regional){let layerNames=[];for(let arn of descriptor.Layers){let layer=descriptor.ResolvableLayers[arn];if(!layer)throw new DescribeError("invalid_response","The deployment API did not provide a download URL for a required runtime layer.");let name=createHash3("sha256").update(arn).digest("hex");if(layerNames.push(name),layers[name])continue;let response=await fetch(layer.url,{signal:AbortSignal.timeout(6e4)});if(!response.ok)throw new DescribeError("layer_download_failed","Could not download a required runtime layer. Retry this describe command.");let bytes2=new Uint8Array(await response.arrayBuffer()),file=`layers/${createHash3("sha256").update(bytes2).digest("hex")}.zip`;await writeFile3(join8(staging,file),bytes2,{mode:384}),layers[name]=file}let{Region,Layers,ResolvableLayers,...configuration}=descriptor,fn={code:`zips/${digest}.zip`,region:Region,layers:layerNames,configuration},key=`${descriptor.Region}:${descriptor.FunctionName}`,previous=functions.get(key);if(previous&&!isDeepStrictEqual(previous,fn))throw new DescribeError("invalid_response","Conflicting descriptors for the same regional function");functions.set(key,fn)}manifest[path2]={awsAccountId:params.awsAccountId,digest,functionName:regional[0].FunctionName,regions:[...new Set(regional.map(d=>d.Region))],size}}await writeFile3(join8(staging,"descriptor.json"),JSON.stringify({awsAccountId:params.awsAccountId,deploymentId:params.deploymentId,functions:[...functions.values()],layers,version:1},null,2),{mode:384}),await prepareContinuation({directory:params.directory,repoRootPath,outputDir:source,destination:join8(staging,"output"),manifest}),await mkdir2(output,{recursive:!0,mode:448});let backup=join8(staging,"backup");await mkdir2(backup);let moves=[],move=async(from,to)=>{await rename(from,to),moves.push([from,to])},preserve=async(path2,name)=>{await exists(path2)&&await move(path2,join8(backup,name))};try{for(let name of["zips","layers","descriptor.json"])await preserve(join8(output,name),name),await move(join8(staging,name),join8(output,name));source===buildOutput?(await preserve(build,"build"),await move(buildOutput,build)):await preserve(buildOutput,"output"),await move(join8(staging,"output"),buildOutput)}catch(error){removeStaging=!1;for(let[from,to]of moves.reverse())await rename(to,from);throw removeStaging=!0,error}return output}finally{removeStaging&&await rm(staging,{recursive:!0,force:!0})}}var exists=path2=>stat5(path2).then(()=>!0,error=>{if(error.code==="ENOENT")return!1;throw error});import{join as join10}from"node:path";import{join as join9,relative as relative5}from"node:path";async function resolveDescribeProject(client){try{let link=await getLinkFromDir(join9(client.cwd,".vercel"));if(link){let{repoRoot,resolvedRootDirectory}=resolvePerDirectoryLinkRoot(client.cwd,link.settings?.rootDirectory);return{...link,directory:join9(repoRoot,resolvedRootDirectory),repoRootPath:repoRoot}}let repo=await getRepoLink(client,client.cwd);if(!repo?.repoConfig?.projects.length)throw new DescribeError("not_linked","No linked project found. Run `vercel link`, or restore CI project settings with `vercel pull --yes`.");let matches=findProjectsFromPath(repo.repoConfig.projects,relative5(repo.rootPath,client.cwd)),candidates=matches.length?matches:repo.repoConfig.projects;if(candidates.length!==1)throw new DescribeError("ambiguous_project","Multiple projects are linked here. Run this command from the intended project directory, or pass --cwd <PROJECT_DIRECTORY>.");let project=await getProjectLink(client,client.cwd,candidates[0].id,!0);if(!project?.repoRoot)throw new Error("Project link changed");return{...project,directory:join9(project.repoRoot,project.projectRootDirectory||""),repoRootPath:project.repoRoot}}catch(error){throw error instanceof DescribeError?error:new DescribeError("invalid_project_link","Could not read the local project link. Check that .vercel/project.json or .vercel/repo.json is readable and contains valid project settings.")}}async function describe(client){let asJson=wantsMachineReadableOutput("deploy",client.argv),fail=(reason,message,code2=1)=>(asJson?client.stderr.write(`${JSON.stringify({status:"error",reason,message})}
|
|
19
|
+
`;function hydrateLambdaFiles(lambda,encryptedEnv){let files=lambda.files??{};if(lambda.runtime==="container"||!encryptedEnv.filename||!encryptedEnv.contentBase64)return files;if(files[encryptedEnv.filename]=new import_build_utils.FileBlob({data:Buffer.from(encryptedEnv.contentBase64,"base64")}),lambda.supportsWrapper!==!0&&!NATIVELY_WRAPPER_SUPPORTED_FAMILIES.some(family=>lambda.runtime.startsWith(family))){if(!lambda.runtime.startsWith("provided"))throw new Error(`Serverless Function runtime ${lambda.runtime} does not support more than 4KB for environment variables`);let userBootstrap=files[ROOT_BOOTSTRAP_PATH];if(!userBootstrap)throw new Error(`Serverless Function runtime ${lambda.runtime} does not support more than 4KB for environment variables`);if(files[USER_BOOTSTRAP_PATH])throw new Error(`Cannot wrap "provided.*" lambda: reserved file path ${USER_BOOTSTRAP_PATH} is already in use. Please rename your file.`);files[USER_BOOTSTRAP_PATH]=userBootstrap,delete files[ROOT_BOOTSTRAP_PATH],files[ROOT_BOOTSTRAP_PATH]=new import_build_utils.FileBlob({data:BOOTSTRAP_SHIM,mode:33261})}return files}import{join as join6}from"node:path";var import_build_utils2=__toESM(require_build_utils(),1);import{join as join2}from"path";import{readFile}from"node:fs/promises";async function maybeReadJSON(path2){let contents;try{contents=await readFile(path2,"utf8")}catch(err){if(err.code!=="ENOENT")throw err;return}try{return JSON.parse(contents.charCodeAt(0)===65279?contents.slice(1):contents)}catch(err){throw err.message=`${path2}: ${err.message}`,err}}async function getBuildOutputConfig(outputDir){let configPath=getBuildOutputConfigPath(outputDir),config=await maybeReadJSON(configPath);if(!config)return;if(config.version!==3)throw new Error(`Expected \`version: 3\` in "${configPath}" file (received \`${config.version}\`)`);validateDeploymentId(config.deploymentId),validateExperimentalServicesV2(config.experimentalServicesV2);let framework=validateFrameworkVersion(config.framework);return{...config,framework}}function getBuildOutputConfigPath(outputDir){return join2(outputDir,"config.json")}var MAX_DEPLOYMENT_ID_LENGTH=32,MAX_FRAMEWORK_SLUG_LENGTH=50,MAX_FRAMEWORK_VERSION_LENGTH=50,VALID_DEPLOYMENT_ID_PATTERN=/^[a-zA-Z0-9_-]+$/;function validateDeploymentId(deploymentId){if(deploymentId&&deploymentId.length>MAX_DEPLOYMENT_ID_LENGTH)throw new import_build_utils2.NowBuildError({message:`The configured deploymentId "${deploymentId}" exceeds the maximum length of ${MAX_DEPLOYMENT_ID_LENGTH} characters. Please use a shorter deploymentId.`,code:"VC_BUILD_INVALID_DEPLOYMENT_ID_LENGTH"});if(deploymentId&&!VALID_DEPLOYMENT_ID_PATTERN.test(deploymentId))throw new import_build_utils2.NowBuildError({message:`The configured deploymentId "${deploymentId}" contains invalid characters. Only alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (_) are allowed.`,code:"VC_BUILD_INVALID_DEPLOYMENT_ID_CHARACTERS"})}function validateFrameworkVersion(framework){if(!framework)return;let{slug,version}=framework;if(typeof slug=="string"){if(typeof version!="string")throw new import_build_utils2.NowBuildError({message:`Invalid config.json: "version" type "${typeof version}" should be "string"`,code:"VC_BUILD_INVALID_CONFIG_JSON_FRAMEWORK_VERSION_TYPE"});if(slug.length>MAX_FRAMEWORK_SLUG_LENGTH){let trimmedSlug=slug.slice(0,MAX_FRAMEWORK_SLUG_LENGTH);throw new import_build_utils2.NowBuildError({message:`Invalid config.json: "framework.slug" length ${slug.length} > ${MAX_FRAMEWORK_SLUG_LENGTH}. "${trimmedSlug}..."`,code:"VC_BUILD_INVALID_CONFIG_JSON_FRAMEWORK_SLUG_LENGTH"})}if(version.length>MAX_FRAMEWORK_VERSION_LENGTH){let trimmedVersion=version.slice(0,MAX_FRAMEWORK_VERSION_LENGTH);throw new import_build_utils2.NowBuildError({message:`Invalid config.json: "framework.version" length ${version.length} > ${MAX_FRAMEWORK_VERSION_LENGTH}. "${trimmedVersion}..."`,code:"VC_BUILD_INVALID_CONFIG_JSON_FRAMEWORK_VERSION_LENGTH"})}return framework}}function validateExperimentalServicesV2(experimentalServicesV2){if(experimentalServicesV2!==void 0&&(!experimentalServicesV2||typeof experimentalServicesV2!="object"||Array.isArray(experimentalServicesV2)))throw new import_build_utils2.NowBuildError({code:"INVALID_BUILD_OUTPUT_CONFIG",message:'Invalid config.json: "experimentalServicesV2" must be an object.'})}async function getBuildOutputConfigOrThrow(outputDir){let config=await getBuildOutputConfig(outputDir);if(config)return config;throw new Error(`Config file was not found at "${getBuildOutputConfigPath(outputDir)}"`)}var import_build_utils3=__toESM(require_build_utils(),1);function isRouteMiddleware(route){return"middlewarePath"in route&&typeof route.middlewarePath=="string"}var cache=new WeakMap;function getMiddlewareRouting(buildResult){let cached=cache.get(buildResult.functions);if(cached&&cached.routes===buildResult.routes)return cached.routing;let routing=new Map,{lambdas,edgeFunctions}=buildResult.functions;for(let route of buildResult.routes){if(!isRouteMiddleware(route))continue;let outputPath=route.middlewarePath;!lambdas.has(outputPath)&&!edgeFunctions.has(outputPath)&&(outputPath=outputPath.replace(/^\//,""));let output=lambdas.get(outputPath)??edgeFunctions.get(outputPath);if(!outputPath||!output)throw new import_build_utils3.NowBuildError({message:`Mapping ${route.middlewarePath} not found. Maybe you provided a wrong middlewarePath?`,code:"middleware_path_not_found"});let index=routing.get(outputPath)?.index??routing.size;routing.set(outputPath,output.type==="EdgeFunction"?{type:"middleware",middlewarePath:route.middlewarePath,outputPath,edgeFunction:output,index}:{type:"middleware-lambda",middlewarePath:route.middlewarePath,outputPath,index})}return cache.set(buildResult.functions,{routes:buildResult.routes,routing}),routing}var import_semver=__toESM(require_semver(),1),import_build_utils4=__toESM(require_build_utils(),1);import{createHash}from"crypto";import fs2 from"fs";var fileSizeCache=new Map,getFileSize=path2=>{if(!path2)return Promise.resolve(0);let cached=fileSizeCache.get(path2);if(cached)return cached;let promise=fs2.promises.lstat(path2).then(stats=>stats.size);return fileSizeCache.set(path2,promise),promise},collectUncompressedSize=async(files,ignoreFn)=>{let size=0;return await Promise.all(Object.keys(files).map(async fileKey=>{if(!ignoreFn?.(fileKey)){if(files[fileKey].type==="FileBlob")size+=files[fileKey].data.length;else if(files[fileKey].type==="FileFsRef"){let curSize=files[fileKey].size??await getFileSize(files[fileKey].fsPath);size+=curSize}}})),size};var MIB=1024*1024,MAX_UNCOMPRESSED_FUNCTION_SIZE_BYTES=250*MIB,LAMBDA_RESERVED_UNCOMPRESSED_SIZE_BYTES=25*MIB,LARGE_FUNCTION_THRESHOLD_BYTES=MAX_UNCOMPRESSED_FUNCTION_SIZE_BYTES-LAMBDA_RESERVED_UNCOMPRESSED_SIZE_BYTES,MANIFEST_FILE_NAMES=["routes-manifest.json","server/pages-manifest.json","server/app-paths-manifest.json","app-path-routes-manifest.json"],TEST_DYNAMIC_ROUTE=/\/\[[^\/]+?\](?=\/|$)/;function isNextjsDynamicRoute(route){return route=route.startsWith("/")?route:`/${route}`,TEST_DYNAMIC_ROUTE.test(route)}function computeLambdaFieldsSignature(lambda,lambdaFields){let parts=[];for(let field of lambdaFields)parts.push(JSON.stringify(lambda[field]));return parts.join("|")}async function getLambdaFileSizeMetadata(lambdaFiles){let fileKeys=Object.keys(lambdaFiles),fileSizes=new Map,uncompressedSize=0;for(let fileKey of fileKeys){let file=lambdaFiles[fileKey];if(file===void 0)throw new Error("Expected lambdaFiles[fileKey] to be defined");let fileSize=0;file.type==="FileBlob"?fileSize=file.data.length:file.type==="FileFsRef"&&(fileSize=await collectUncompressedSize({[fileKey]:file},void 0)),fileSizes.set(fileKey,fileSize),uncompressedSize+=fileSize}return{fileKeys,fileSizes,uncompressedSize}}async function groupLambdas(lambdas,options){let{force}=options,lambdaFields=["allowQuery","affinity","architecture","awsLambdaHandler","environment","experimentalResponseStreaming","experimentalTriggers","framework","handler","maxConcurrency","maxDuration","memory","operationType","regions","runtime","runtimeLanguage","shouldAddHelpers","shouldAddSourcemapSupport","shouldDisableAutomaticFetchInstrumentation","supportsCancellation","supportsMultiPayloads","supportsResponseStreaming","supportsWrapper","useWebApi","functionFailoverRegions"],_typeCheck=lambdaFields,fieldsToCompare=force==="all"?["runtime","maxConcurrency"]:lambdaFields,maxUncompressedFunctionSize=LARGE_FUNCTION_THRESHOLD_BYTES,maxBundleSizeMb=options.maxBundleSizeMb;if(maxBundleSizeMb!==void 0&&Number.isFinite(maxBundleSizeMb)){let customMaxUncompressedFunctionSize=Math.floor(maxBundleSizeMb*MIB);output_manager_default.warn(`Warn: custom max uncompressed function size of ${customMaxUncompressedFunctionSize/MIB}MiB configured`),maxUncompressedFunctionSize=Math.min(customMaxUncompressedFunctionSize,MAX_UNCOMPRESSED_FUNCTION_SIZE_BYTES)}let seenLambdas=new Map;for(let[name,lambda]of Object.entries(lambdas)){if(!lambda.experimentalAllowBundling||!lambda.files)continue;let existingNames=seenLambdas.get(lambda);existingNames?existingNames.push(name):seenLambdas.set(lambda,[name])}let handlerDigestPromiseCache=new Map,getHandlerDigest=handlerFile=>{if(!handlerFile)return Promise.resolve(void 0);let cached=handlerDigestPromiseCache.get(handlerFile);if(cached)return cached;let promise=(async()=>{try{let handlerStream=handlerFile.toStream(),handlerBuffer=await(0,import_build_utils4.streamToBuffer)(handlerStream),handlerBytes=new Uint8Array(handlerBuffer.buffer,handlerBuffer.byteOffset,handlerBuffer.byteLength);return createHash("sha1").update(handlerBytes).digest("hex")}catch{return}})();return handlerDigestPromiseCache.set(handlerFile,promise),promise},bundlesBySignature=new Map,allBundledLambdas=[];for(let[lambda,lambdaNames]of seenLambdas){let lambdaFiles=lambda.files;if(!lambdaFiles)continue;let signature=computeLambdaFieldsSignature(lambda,fieldsToCompare),{fileKeys,fileSizes,uncompressedSize}=await getLambdaFileSizeMetadata(lambdaFiles),handlerDigest=await getHandlerDigest(lambdaFiles[lambda.handler]),compatibleBundles=bundlesBySignature.get(signature),isLarge=uncompressedSize>=LARGE_FUNCTION_THRESHOLD_BYTES,foundMatchingBundle=!1;if(compatibleBundles&&!isLarge)for(let bundleMeta of compatibleBundles){if(bundleMeta.isLarge||!(handlerDigest===bundleMeta.handlerDigest)&&force!=="all")continue;let uncompressedBytesIncrease=0;for(let fileKey of fileKeys){let incomingFileSize=fileSizes.get(fileKey)??0,existingFileSize=bundleMeta.fileSizesByKey.get(fileKey);existingFileSize===void 0?uncompressedBytesIncrease+=incomingFileSize:uncompressedBytesIncrease+=incomingFileSize-existingFileSize}let newTotalSize=bundleMeta.uncompressedBytes+uncompressedBytesIncrease;if(newTotalSize<=maxUncompressedFunctionSize){foundMatchingBundle=!0,bundleMeta.uncompressedBytes=newTotalSize,bundleMeta.lambdaNames.push(...lambdaNames);for(let fileKey of fileKeys)bundleMeta.fileSizesByKey.set(fileKey,fileSizes.get(fileKey)??0);let potentialLambdaFiles=bundleMeta.lambda.files;potentialLambdaFiles&&(bundleMeta.lambda.files=Object.assign(potentialLambdaFiles,lambdaFiles));break}}if(!foundMatchingBundle){let newBundleMeta={lambda,signature,handlerDigest,isLarge,uncompressedBytes:uncompressedSize,fileSizesByKey:new Map(fileSizes),lambdaNames:[...lambdaNames]},signatureBundles=bundlesBySignature.get(signature);signatureBundles||(signatureBundles=[],bundlesBySignature.set(signature,signatureBundles)),signatureBundles.push(newBundleMeta),allBundledLambdas.push(newBundleMeta)}}let finalLambdas=Object.assign({},lambdas);options.debug&&(output_manager_default.debug("GROUP_LAMBDAS: "+JSON.stringify(allBundledLambdas.map(bundleMeta=>({lambdaNames:bundleMeta.lambdaNames,signature:bundleMeta.signature,uncompressedBytes:bundleMeta.uncompressedBytes})),null,2)),output_manager_default.debug(`total grouped lambdas: ${allBundledLambdas.length}`));for(let bundleMeta of allBundledLambdas){let lambda=bundleMeta.lambda;for(let lambdaName of bundleMeta.lambdaNames)finalLambdas[lambdaName]=lambda;if(lambda.framework?.slug==="nextjs"&&lambda.framework.version){let CORRECTED_MANIFESTS_VERSION="v12.2.0";if(import_semver.default.gte(lambda.framework.version,CORRECTED_MANIFESTS_VERSION)){let pageFiles=[],manifestFileKeys={},manifestFileNames=MANIFEST_FILE_NAMES;for(let fileKey of Object.keys(lambda.files||{})){let isPageFile=fileKey.includes("server/pages/"),isAppFile=fileKey.includes("server/app/");if(isPageFile||isAppFile){let relativePageFile=fileKey.split(`server/${isPageFile?"pages":"app"}/`).pop();relativePageFile&&pageFiles.push(relativePageFile)}for(let manifestFileName of manifestFileNames)fileKey.endsWith(`/${manifestFileName}`)&&(manifestFileKeys[manifestFileName]=fileKey)}let appPathRoutesManifestFilesKey=manifestFileKeys["app-path-routes-manifest.json"],appPathRoutesManifestFile=appPathRoutesManifestFilesKey&&lambda.files?.[appPathRoutesManifestFilesKey],appPathRoutesManifest=appPathRoutesManifestFile?await(0,import_build_utils4.streamToBuffer)(appPathRoutesManifestFile.toStream()).then(res=>JSON.parse(res.toString("utf8"))).catch(()=>({})):{};for(let manifestFileName of manifestFileNames){let manifestFilesKey=manifestFileKeys[manifestFileName],manifestFile=manifestFilesKey&&lambda.files?.[manifestFilesKey];if(!manifestFile)continue;let manifestData=JSON.parse((await(0,import_build_utils4.streamToBuffer)(manifestFile.toStream())).toString("utf8")),normalizedPages=new Set(pageFiles.map(page=>(page=`/${page.replace(/\.js$/,"")}`,page==="/index"&&(page="/"),appPathRoutesManifest[page]||page)));switch(manifestFileName){case"routes-manifest.json":{let filterItem=item=>normalizedPages.has(item.page);manifestData.dynamicRoutes=manifestData.dynamicRoutes?.filter(filterItem),manifestData.staticRoutes=manifestData.staticRoutes?.filter(filterItem);break}case"server/pages-manifest.json":{for(let key of Object.keys(manifestData))isNextjsDynamicRoute(key)&&!normalizedPages.has(key)&&delete manifestData[key];break}case"server/app-paths-manifest.json":{if(appPathRoutesManifest)for(let key of Object.keys(manifestData)){let normalizedKey=appPathRoutesManifest[key]||key.replace(/(^|\/)(page|route)$/,"");isNextjsDynamicRoute(normalizedKey)&&!normalizedPages.has(normalizedKey)&&delete manifestData[key]}break}}lambda.files&&(lambda.files[manifestFilesKey]=new import_build_utils4.FileBlob({contentType:"application/json",data:JSON.stringify(manifestData)}))}}}}return finalLambdas}async function groupBundleableLambdas(params){let lambdas={};for(let[path2,lambda]of params.functions.lambdas)lambda.experimentalAllowBundling&&(lambdas[path2]=lambda);for(let[path2,prerender]of params.functions.prerenders)prerender.lambda.experimentalAllowBundling&&(lambdas[path2]=prerender.lambda);if(Object.keys(lambdas).length===0)return;let grouped=await groupLambdas(lambdas,{force:void 0,maxBundleSizeMb:params.options.maxBundleSizeMb,debug:params.options.debugGroupLambdas});for(let[path2,lambda]of Object.entries(grouped))if(params.functions.lambdas.has(path2))params.functions.lambdas.set(path2,lambda);else{let prerender=params.functions.prerenders.get(path2);if(prerender)prerender.lambda=lambda;else throw new Error(`Grouped lambda "${path2}" does not match any build output`)}}var import_build_utils6=__toESM(require_build_utils(),1);import{join as join3,relative}from"path";import{readdir,stat}from"fs/promises";var SUFFIX=".func";async function*createFunctionEntriesIterator(dir,root=dir){let entries;try{entries=await readdir(dir,{withFileTypes:!0})}catch(error){if(!(typeof error=="object"&&error!==null&&"code"in error)||error.code!=="ENOENT"&&error.code!=="ENOTDIR")throw error;entries=[]}let names;for(let entry of entries){let absolutePath=join3(dir,entry.name),isSymbolicLink=entry.isSymbolicLink();if(entry.isDirectory()||isSymbolicLink&&(await stat(absolutePath)).isDirectory())if(entry.name.endsWith(SUFFIX)){names??=new Set(entries.map(e=>e.name));let baseName=entry.name.slice(0,-SUFFIX.length);yield{hasPrerenderConfig:names.has(`${baseName}.prerender-config.json`),isSymbolicLink,path:relative(root,absolutePath.substring(0,absolutePath.length-SUFFIX.length))}}else yield*createFunctionEntriesIterator(absolutePath,root)}}import{dirname,isAbsolute,join as join4,relative as relative2,resolve as resolve2,sep}from"node:path";var import_build_utils5=__toESM(require_build_utils(),1);import{lstat,readlink,realpath,readdir as readdir2,stat as stat2}from"node:fs/promises";import assert from"assert";import path from"path";async function glob(options){if(!path.isAbsolute(options.cwd))throw new Error(`basePath/cwd must be an absolute path (${options.cwd})`);let results={},statCache={},symlinks={},files=await walkAll(options.cwd,!!options.follow,statCache,symlinks),dirs=new Set,dirsWithEntries=new Set;for(let relativePath of files){let fsPath=path.join(options.cwd,relativePath),stats=statCache[fsPath];assert(stats,`statCache does not contain value for ${relativePath}`);let isSymlink=symlinks[fsPath];if(options.follow&&(isSymlink||(await lstat(fsPath)).isSymbolicLink())){let target=await readlink(fsPath),absoluteTarget=path.resolve(path.dirname(fsPath),target);if(path.relative(options.cwd,absoluteTarget).startsWith(`..${path.sep}`))continue}if(isSymlink||stats.isFile()||stats.isDirectory()){isSymlink&&(stats=await lstat(fsPath));let dirname4=path.dirname(relativePath);if(dirsWithEntries.add(dirname4),stats.isDirectory()){dirs.add(relativePath);continue}results[relativePath]=new import_build_utils5.FileFsRef({mode:stats.mode,fsPath,size:stats.size})}}if(options.includeDirectories)for(let relativePath of dirs){if(dirsWithEntries.has(relativePath))continue;let fsPath=path.join(options.cwd,relativePath),stats=statCache[fsPath];results[relativePath]=new import_build_utils5.FileFsRef({mode:stats.mode,fsPath,size:stats.size})}return results}async function walkAll(cwd,follow,statCache,symlinks){let files=[];async function walk(dirAbs,realDir,ancestors){let entries;try{entries=await readdir2(dirAbs,{withFileTypes:!0})}catch(err){let code2=err.code;if(code2==="ENOENT"||code2==="ENOTDIR")return;throw err}await Promise.all(entries.map(async entry=>{let abs=path.join(dirAbs,entry.name);if(entry.isSymbolicLink())if(follow){let stats=await stat2(abs).catch(()=>lstat(abs).catch(()=>null));if(stats===null)return;if(statCache[abs]=stats,files.push(abs),stats.isDirectory()){let real=await realpath(abs).catch(()=>null);real!==null&&!ancestors.has(real)&&await walk(abs,real,new Set(ancestors).add(real))}}else{let stats=await lstat(abs).catch(()=>null);if(stats===null)return;statCache[abs]=stats,symlinks[abs]=!0,files.push(abs)}else if(entry.isDirectory()){let stats=await lstat(abs).catch(()=>null);if(stats===null)return;statCache[abs]=stats,files.push(abs);let real=path.join(realDir,entry.name);await walk(abs,real,new Set(ancestors).add(real))}else{let stats=await lstat(abs).catch(()=>null);if(stats===null)return;statCache[abs]=stats,files.push(abs)}}))}let cwdReal=follow?await realpath(cwd).catch(()=>null):cwd;return cwdReal!==null&&await walk(cwd,cwdReal,new Set([cwdReal])),files.map(abs=>path.relative(cwd,abs)).sort((a,b)=>a.localeCompare(b,"en"))}import{isNativeError}from"node:util/types";import{readlink as readlink2,realpath as realpath2}from"node:fs/promises";async function readFunctions(params){let fileFsRefsCache=new Map,entries=[],functionsDir=join4(params.outputDir,"functions"),iterator=enumerate(createFunctionEntriesIterator(functionsDir));await Promise.all(Array.from({length:params.concurrency??32},async()=>{for await(let[index,entry]of iterator)entries[index]=await deserializeFunctionEntry({prebuilt:params.prebuilt,entry,fileFsRefsCache,functionsDir,repoRootPath:params.repoRootPath})}));let serverActionsManifestPaths=new Set,edgeFunctions=new Map,unsortedPrerenders=new Map,functionSymlinks=new Map,lambdas=new Map;for(let functionEntry of entries)functionEntry.symlinkTarget!==void 0&&functionSymlinks.set(functionEntry.path,functionEntry.symlinkTarget),functionEntry.serverActionsManifestPath&&serverActionsManifestPaths.add(functionEntry.serverActionsManifestPath),functionEntry.output?.type==="Prerender"?unsortedPrerenders.set(functionEntry.path,functionEntry.output):functionEntry.output?.type==="Lambda"?lambdas.set(functionEntry.path,functionEntry.output):functionEntry.output?.type==="EdgeFunction"&&edgeFunctions.set(functionEntry.path,functionEntry.output);for(let[path2,target]of functionSymlinks){let destFunction=unsortedPrerenders.get(target)?.lambda??edgeFunctions.get(target)??lambdas.get(target);if(!destFunction)throw new Error(`Could not find target "${target}" Lambda or EdgeFunction for path "${path2}"`);let srcPrerender=unsortedPrerenders.get(path2);if(!srcPrerender)destFunction.type==="Lambda"?lambdas.set(path2,destFunction):destFunction.type==="EdgeFunction"&&edgeFunctions.set(path2,destFunction);else{if(destFunction.type!=="Lambda")throw new Error(`Unexpected function type "${destFunction.type}" at path "${path2}"`);srcPrerender.lambda=destFunction}}let prerenders=new Map;for(let[path2,prerender]of[...unsortedPrerenders].sort((a,b)=>(a[1].group??0)-(b[1].group??0)))validatePrerender(prerender),prerenders.set(path2,prerender);return{edgeFunctions,lambdas,prerenders,serverActionsManifestPaths}}async function*enumerate(iterable){let index=0;for await(let item of iterable)yield[index++,item]}async function deserializeFunctionEntry(params){let functionDir=join4(params.functionsDir,`${params.entry.path}.func`),prerenderConfigPath=join4(params.functionsDir,`${params.entry.path}.prerender-config.json`),configPromise=params.entry.hasPrerenderConfig?maybeReadJSON(prerenderConfigPath):void 0;configPromise?.catch(()=>{});let lambda,serverActionsManifestPath,symlinkTarget;if(params.entry.isSymbolicLink)symlinkTarget=await readlink2(functionDir).then(link=>join4(dirname(params.entry.path),link).slice(0,-5));else{let functionConfigPath=join4(functionDir,".vc-config.json"),[functionConfig,files]=await Promise.all([maybeReadJSON(functionConfigPath),glob({cwd:functionDir,includeDirectories:!0})]);if(!functionConfig)throw new Error(`Could not load function config: "${functionConfigPath}"`);if(delete files[".vc-config.json"],functionConfig.filePathMap&&await hydrateFilesMap(files,functionConfig.filePathMap,params.repoRootPath,params.fileFsRefsCache,params.prebuilt),"type"in functionConfig&&functionConfig.type==="EdgeFunction"||functionConfig.runtime==="edge")return{path:params.entry.path,output:new import_build_utils6.EdgeFunction({deploymentTarget:"v8-worker",...functionConfig,files})};let supportsResponseStreaming=functionConfig.supportsResponseStreaming??functionConfig.experimentalResponseStreaming;lambda="launcherType"in functionConfig&&functionConfig.launcherType==="Nodejs"?new import_build_utils6.NodejsLambda({...functionConfig,files,supportsResponseStreaming:functionConfig.awsLambdaHandler===void 0||functionConfig.awsLambdaHandler===""||supportsResponseStreaming}):new import_build_utils6.Lambda({...functionConfig,files,supportsResponseStreaming}),serverActionsManifestPath=functionConfig.filePathMap?.[".next/server/server-reference-manifest.json"]}if(configPromise){let prerenderConfig=await configPromise;if(prerenderConfig)return{path:params.entry.path,symlinkTarget,serverActionsManifestPath,output:new import_build_utils6.Prerender({...prerenderConfig,fallback:await deserializePrerenderFallback(prerenderConfigPath,prerenderConfig.fallback,params),initialMetadata:sanitizeInitialMetadata(prerenderConfig.initialMetadata),lambda})}}return{path:params.entry.path,symlinkTarget,output:lambda,serverActionsManifestPath}}function validatePrerender(prerender){if(prerender.lambda===void 0)throw new Error('Prerender "buildResult" is missing "lambda" property')}async function hydrateFilesMap(files,filesMap,repoRootPath,fileFsRefsCache,prebuilt){let rootPath=prebuilt?await realpath2(repoRootPath):void 0;async function hydrateFile(projectPath){let fsPath=join4(repoRootPath,projectPath);rootPath!==void 0&&await validatePrebuiltFilePath(fsPath,rootPath,`file map source "${projectPath}"`,!0);let file=await import_build_utils6.FileFsRef.fromFsPath({fsPath});return fileFsRefsCache.set(projectPath,file),file}let pending;for(let functionPath in filesMap){let projectPath=filesMap[functionPath],cached=fileFsRefsCache.get(projectPath);if(cached&&!(cached instanceof Promise)){files[functionPath]=cached;continue}let filePromise=cached;if(!filePromise){let promise=hydrateFile(projectPath);fileFsRefsCache.set(projectPath,promise),filePromise=promise}(pending??=[]).push(filePromise.then(file=>{files[functionPath]=file}))}pending&&await Promise.all(pending)}async function validatePrebuiltFilePath(fsPath,rootPath,source,enableDanglingSymlinks=!1){let resolvedPath;try{resolvedPath=await realpath2(fsPath)}catch(error){if(!enableDanglingSymlinks||!isNativeError(error)||!("code"in error)||error.code!=="ENOENT")throw error;let target=await readlink2(fsPath),parentPath=await validatePrebuiltFilePath(dirname(fsPath),rootPath,source);resolvedPath=resolve2(parentPath,target)}let sourcePath=relative2(rootPath,resolvedPath);if(sourcePath===".."||sourcePath.startsWith(`..${sep}`)||isAbsolute(sourcePath))throw new import_build_utils6.NowBuildError({code:"INVALID_PREBUILT_FILE_PATH",message:`Prebuilt ${source} must be inside the uploaded project.`});return resolvedPath}function sanitizeInitialMetadata(initialMetadata){try{if(typeof initialMetadata!="object"||initialMetadata===null||Array.isArray(initialMetadata))return;let{compute,htmlSize}=initialMetadata;return compute!=="blocking"&&compute!=="resuming"&&compute!=="static"||htmlSize!==void 0&&(!Number.isSafeInteger(htmlSize)||htmlSize<0)?void 0:{compute,...htmlSize!==void 0&&{htmlSize}}}catch{return}}async function deserializePrerenderFallback(prerenderConfigPath,fallback,options){if(fallback==null)return null;let path2=typeof fallback=="string"?fallback:fallback.fsPath,fsPath=join4(dirname(prerenderConfigPath),path2);return options.prebuilt&&await validatePrebuiltFilePath(fsPath,await realpath2(options.repoRootPath),`prerender fallback "${path2}"`),typeof fallback=="string"?import_build_utils6.FileFsRef.fromFsPath({fsPath}):fallback.mode!==void 0?new import_build_utils6.FileFsRef({mode:fallback.mode,size:fallback.size,contentType:fallback.contentType,fsPath}):import_build_utils6.FileFsRef.fromFsPath({mode:fallback.mode,size:fallback.size,contentType:fallback.contentType,fsPath})}var import_async_sema=__toESM(require_async_sema(),1),import_ignore=__toESM(require_ignore(),1);import{basename,isAbsolute as isAbsolute2,join as join5,relative as relative3,sep as sep2}from"node:path";import{readFile as readFile2,readdir as readdir3,realpath as realpath3,stat as stat3}from"node:fs/promises";function contains(root,path2){let rel=relative3(root,path2);return rel!==".."&&!rel.startsWith(`..${sep2}`)&&!isAbsolute2(rel)}function invalidSource(){throw new DescribeError("invalid_build_output","Build output references files outside the authorized output or includes excluded source files. Remove unsafe links and excluded file mappings, then rebuild.")}var vcs=(0,import_ignore.default)().add([".hg",".git",".gitmodules",".svn","CVS"]),dependencies=(0,import_ignore.default)().add(["node_modules",".next",".yarn/cache",".pnp*",".venv","venv","__pycache__","/target"]);async function readIgnore(root){let read=name=>readFile2(join5(root,name),"utf8").catch(error=>{if(error.code==="ENOENT")return"";throw error}),[vercelignore,nowignore]=await Promise.all([read(".vercelignore"),read(".nowignore")]);if(vercelignore&&nowignore)throw new DescribeError("invalid_build_output","Cannot use both .vercelignore and .nowignore. Remove the deprecated .nowignore file and retry.");return(0,import_ignore.default)().add((vercelignore||nowignore).replace(/(\n|^)\.\//g,"$1"))}async function validateBuildOutput(options){let root=await realpath3(options.repoRootPath),output=await realpath3(options.outputDir),expectedOutput=join5(root,relative3(options.repoRootPath,options.outputDir));(!contains(root,output)||relative3(expectedOutput,output)!=="")&&invalidSource();let project=options.directory?await realpath3(options.directory):root,bases=[root];if(project!==root&&contains(root,project))for(let segment of relative3(root,project).split(sep2))bases.push(join5(bases[bases.length-1],segment));let ignores=await Promise.all(bases.map(async base=>({base,rules:await readIgnore(base)}))),sema=new import_async_sema.default(32),limit=async fn=>{await sema.acquire();try{return await fn()}finally{sema.release()}},checkSource=async path2=>{let resolved=await limit(()=>realpath3(path2));for(let source of[join5(root,relative3(options.repoRootPath,path2)),resolved]){contains(root,source)||invalidSource();let rel=relative3(root,source).split(sep2).join("/");if(rel&&(vcs.ignores(rel)&&invalidSource(),!contains(output,source)))for(let{base,rules}of ignores){if(!contains(base,source))continue;let relToBase=relative3(base,source).split(sep2).join("/");relToBase&&rules.ignores(relToBase)&&!dependencies.ignores(relToBase)&&invalidSource()}}return resolved},checked=new Map,validateSource=path2=>{let result=checked.get(path2);return result||(result=checkSource(path2),checked.set(path2,result)),result},configs=[],visited=new Set;async function walk(dir,ancestors){visited.add(dir);let next=new Set(ancestors).add(dir),entries=await Promise.all((await limit(()=>readdir3(dir))).map(async name=>{let path2=join5(dir,name),resolved=await limit(()=>realpath3(path2));return(!contains(output,resolved)||next.has(resolved))&&invalidSource(),{path:path2,resolved,stats:await limit(()=>stat3(resolved))}}));for(let{path:path2,resolved,stats}of entries)stats.isDirectory()?visited.has(resolved)||await walk(resolved,next):basename(path2)===".vc-config.json"&&configs.push(resolved)}return await walk(output,new Set),await Promise.all(configs.map(async path2=>{let config=JSON.parse(await limit(()=>readFile2(path2,"utf8")));await Promise.all(Object.values(config.filePathMap??{}).map(source=>(typeof source!="string"&&invalidSource(),validateSource(join5(options.repoRootPath,source)))))})),validateSource}async function prepareFunctions(options){await validateBuildOutput(options);let config=await getBuildOutputConfigOrThrow(options.outputDir);if(config.experimentalServicesV2!==void 0)throw new DescribeError("unsupported_output","This build contains service outputs, which describe does not support.");let functions=await readFunctions({outputDir:options.outputDir,repoRootPath:options.repoRootPath,prebuilt:!0});if(functions.edgeFunctions.size)throw new DescribeError("unsupported_output","This build contains Edge Functions, which cannot be provisioned as AWS Lambda functions.");await groupBundleableLambdas({functions,options:{}});let allFunctions=[...functions.lambdas,...functions.prerenders],groups=new Map,middlewarePaths=getMiddlewareRouting({routes:config.routes??[],functions});for(let[path2,output]of allFunctions){let lambda=output.type==="Prerender"?output.lambda:output;if(lambda.runtime==="container")throw new DescribeError("unsupported_output","This build contains container functions. Describe supports native AWS Lambda functions only.");let outputs=groups.get(lambda)??[];groups.set(lambda,outputs),outputs.push({sourceKind:output.type==="Prerender"?"prerender":"lambda",middleware:output.type==="Lambda"&&middlewarePaths.has(path2)?{}:void 0,path:path2})}return[...groups].map(([lambda,outputs])=>({lambda,outputs}))}import{writeFile}from"node:fs/promises";import{z}from"zod/v3";var descriptorSchema=z.object({Architectures:z.array(z.string()).optional(),Environment:z.object({Variables:z.record(z.string())}),EphemeralStorage:z.object({Size:z.number()}).optional(),FunctionName:z.string().min(1),Handler:z.string(),Layers:z.array(z.string()),MemorySize:z.number(),Region:z.string().min(1),ResolvableLayers:z.record(z.object({url:z.string()})),Runtime:z.string(),Tags:z.record(z.string()),Timeout:z.number().optional()});async function describeFunctions(client,params){let functions=await prepareFunctions({directory:params.directory,repoRootPath:params.repoRootPath,outputDir:params.outputDir}),buildEnv=z.object({VERCEL_ENCRYPTED_ENV_FILENAME:z.string().min(1),VERCEL_ENCRYPTED_ENV_CONTENT:z.string().min(1)}).parse((await fetchDeploymentBuildEnv(client,params.deploymentId,{quiet:params.quiet})).buildEnv),lambdas=(await Promise.all(functions.map(async({lambda,outputs})=>{lambda.files=hydrateLambdaFiles(lambda,{filename:buildEnv.VERCEL_ENCRYPTED_ENV_FILENAME,contentBase64:buildEnv.VERCEL_ENCRYPTED_ENV_CONTENT});let zip=await lambda.createZip(),bytes2=new Uint8Array(zip.buffer,zip.byteOffset,zip.byteLength),digest=createHash2("sha256").update(bytes2).digest("hex");await writeFile(join6(params.zipDirectory,`${digest}.zip`),bytes2,{mode:384});let config=getFunctionConfig(lambda),input={...config,framework:config.framework&&{slug:config.framework.slug},digest,size:bytes2.length};return outputs.map(output=>({...output,lambda:input}))}))).flat(),{descriptors}=z.object({descriptors:z.array(z.array(descriptorSchema).min(1))}).parse(await client.fetch(`/v2/deployments/${params.deploymentId}/builds/function-descriptors`,{method:"POST",body:JSON.stringify({lambdas}),headers:{"content-type":"application/json"},accountId:params.teamId,retry:{retries:0}}));if(descriptors.length!==lambdas.length)throw new Error("Descriptor count does not match function outputs");return lambdas.map(({path:path2,lambda},index)=>{let regional=descriptors[index];if(new Set(regional.map(d=>d.FunctionName)).size!==1)throw new Error("Inconsistent regional function name");return{path:path2,digest:lambda.digest,size:lambda.size,regional}})}import{isDeepStrictEqual}from"node:util";import{join as join8}from"node:path";import{mkdir as mkdir2,mkdtemp,rename,rm,stat as stat5,writeFile as writeFile3}from"node:fs/promises";var import_build_utils7=__toESM(require_build_utils(),1);import{basename as basename2,dirname as dirname2,join as join7,relative as relative4,sep as sep3}from"node:path";import{copyFile,cp,lstat as lstat2,mkdir,readFile as readFile3,readdir as readdir4,realpath as realpath4,stat as stat4,symlink,writeFile as writeFile2}from"node:fs/promises";async function prepareContinuation(params){let{directory,outputDir,destination,manifest,repoRootPath=directory}=params,validateSource=await validateBuildOutput({directory,outputDir,repoRootPath}),outputRoot=await realpath4(outputDir),functionAliases=[];await cp(outputDir,destination,{recursive:!0,dereference:!0,filter:async(path2,target)=>{let rel=relative4(outputDir,path2);return basename2(path2)!==".vc-config.json"&&rel.split(sep3).slice(0,-1).some(segment=>segment.endsWith(".func"))?!1:rel.startsWith(`functions${sep3}`)&&path2.endsWith(".func")&&(await lstat2(path2)).isSymbolicLink()?(functionAliases.push({path:target,target:join7(destination,relative4(outputRoot,await realpath4(path2)))}),!1):!0}});for(let{path:path2,target}of functionAliases)await mkdir(dirname2(path2),{recursive:!0}),await symlink(relative4(dirname2(path2),target),path2);await writeFile2(join7(destination,"provision.json"),JSON.stringify(manifest));let manifests=new Set(await packageManifests(directory));if(repoRootPath!==directory)for(let path2 of await packageManifests(repoRootPath))manifests.add(path2);for(let path2 of Object.keys(manifest)){let configPath=join7(destination,"functions",`${path2}.func`,".vc-config.json"),config=JSON.parse(await readFile3(configPath,"utf8"));for(let[file,source]of Object.entries(config.filePathMap??{}))basename2(file)==="package.json"&&manifests.add(join7(repoRootPath,source));delete config.filePathMap,await writeFile2(configPath,JSON.stringify({...config,architecture:new import_build_utils7.Lambda({...config,files:{}}).architecture}))}let[firstFunction]=Object.keys(manifest);if(firstFunction!==void 0)for(let[i,path2]of[...manifests].entries()){let target=join7(destination,"functions",`${firstFunction}.func`,"__byoc_security__",String(i));await mkdir(target,{recursive:!0}),await copyFile(await validateSource(path2),join7(target,"package.json"))}}async function packageManifests(root){let modules=join7(root,"node_modules"),names=await readdir4(modules).catch(()=>[]),packages=await Promise.all(names.map(async name=>name.startsWith(".")?[]:name.startsWith("@")?(await readdir4(join7(modules,name)).catch(()=>[])).map(entry=>join7(modules,name,entry)):[join7(modules,name)]));return(await Promise.all([root,...packages.flat()].map(dir=>{let path2=join7(dir,"package.json");return stat4(path2).then(()=>path2,()=>{})}))).filter(p=>p!==void 0)}async function describeDeployment(client,params){let output=join8(params.directory,".vercel",params.deploymentId),buildOutput=join8(params.directory,".vercel/output"),build=join8(output,"build"),repoRootPath=params.repoRootPath??params.directory,source=await exists(buildOutput)&&!await exists(join8(buildOutput,"provision.json"))?buildOutput:build;if(!await exists(join8(source,"config.json")))throw new DescribeError("prebuilt_not_found",`No local build output found. Run \`vercel build --id ${params.deploymentId}\` before \`vercel deploy describe\`.`);await mkdir2(join8(params.directory,".vercel"),{recursive:!0});let staging=await mkdtemp(join8(params.directory,".vercel",`.describe-${params.deploymentId}-`)),removeStaging=!0,functions=new Map,layers={},manifest={};try{await mkdir2(join8(staging,"zips")),await mkdir2(join8(staging,"layers"));let described=await describeFunctions(client,{deploymentId:params.deploymentId,directory:params.directory,repoRootPath,outputDir:source,quiet:params.quiet,teamId:params.teamId,zipDirectory:join8(staging,"zips")});for(let{path:path2,digest,size,regional}of described){for(let descriptor of regional){let layerNames=[];for(let arn of descriptor.Layers){let layer=descriptor.ResolvableLayers[arn];if(!layer)throw new DescribeError("invalid_response","The deployment API did not provide a download URL for a required runtime layer.");let name=createHash3("sha256").update(arn).digest("hex");if(layerNames.push(name),layers[name])continue;let response=await fetch(layer.url,{signal:AbortSignal.timeout(6e4)});if(!response.ok)throw new DescribeError("layer_download_failed","Could not download a required runtime layer. Retry this describe command.");let bytes2=new Uint8Array(await response.arrayBuffer()),file=`layers/${createHash3("sha256").update(bytes2).digest("hex")}.zip`;await writeFile3(join8(staging,file),bytes2,{mode:384}),layers[name]=file}let{Region,Layers,ResolvableLayers,...configuration}=descriptor,fn={code:`zips/${digest}.zip`,region:Region,layers:layerNames,configuration},key=`${descriptor.Region}:${descriptor.FunctionName}`,previous=functions.get(key);if(previous&&!isDeepStrictEqual(previous,fn))throw new DescribeError("invalid_response","Conflicting descriptors for the same regional function");functions.set(key,fn)}manifest[path2]={awsAccountId:params.awsAccountId,digest,functionName:regional[0].FunctionName,regions:[...new Set(regional.map(d=>d.Region))],size}}await writeFile3(join8(staging,"descriptor.json"),JSON.stringify({awsAccountId:params.awsAccountId,deploymentId:params.deploymentId,functions:[...functions.values()],layers,version:1},null,2),{mode:384}),await prepareContinuation({directory:params.directory,repoRootPath,outputDir:source,destination:join8(staging,"output"),manifest}),await mkdir2(output,{recursive:!0,mode:448});let backup=join8(staging,"backup");await mkdir2(backup);let moves=[],move=async(from,to)=>{await rename(from,to),moves.push([from,to])},preserve=async(path2,name)=>{await exists(path2)&&await move(path2,join8(backup,name))};try{for(let name of["zips","layers","descriptor.json"])await preserve(join8(output,name),name),await move(join8(staging,name),join8(output,name));source===buildOutput?(await preserve(build,"build"),await move(buildOutput,build)):await preserve(buildOutput,"output"),await move(join8(staging,"output"),buildOutput)}catch(error){removeStaging=!1;for(let[from,to]of moves.reverse())await rename(to,from);throw removeStaging=!0,error}return output}finally{removeStaging&&await rm(staging,{recursive:!0,force:!0})}}var exists=path2=>stat5(path2).then(()=>!0,error=>{if(error.code==="ENOENT")return!1;throw error});import{join as join10}from"node:path";import{join as join9,relative as relative5}from"node:path";async function resolveDescribeProject(client){try{let link=await getLinkFromDir(join9(client.cwd,".vercel"));if(link){let{repoRoot,resolvedRootDirectory}=resolvePerDirectoryLinkRoot(client.cwd,link.settings?.rootDirectory);return{...link,directory:join9(repoRoot,resolvedRootDirectory),repoRootPath:repoRoot}}let repo=await getRepoLink(client,client.cwd);if(!repo?.repoConfig?.projects.length)throw new DescribeError("not_linked","No linked project found. Run `vercel link`, or restore CI project settings with `vercel pull --yes`.");let matches=findProjectsFromPath(repo.repoConfig.projects,relative5(repo.rootPath,client.cwd)),candidates=matches.length?matches:repo.repoConfig.projects;if(candidates.length!==1)throw new DescribeError("ambiguous_project","Multiple projects are linked here. Run this command from the intended project directory, or pass --cwd <PROJECT_DIRECTORY>.");let project=await getProjectLink(client,client.cwd,candidates[0].id,!0);if(!project?.repoRoot)throw new Error("Project link changed");return{...project,directory:join9(project.repoRoot,project.projectRootDirectory||""),repoRootPath:project.repoRoot}}catch(error){throw error instanceof DescribeError?error:new DescribeError("invalid_project_link","Could not read the local project link. Check that .vercel/project.json or .vercel/repo.json is readable and contains valid project settings.")}}async function describe(client){let asJson=wantsMachineReadableOutput("deploy",client.argv),fail=(reason,message,code2=1)=>(asJson?client.stderr.write(`${JSON.stringify({status:"error",reason,message})}
|
|
20
20
|
`):output_manager_default.error(message),code2),parsed;try{parsed=parseArguments(client.argv.slice(2),getFlagsSpecification(describeSubcommand.options))}catch(error){return fail("invalid_arguments",`${isArgumentError(error)?error.message:"Invalid describe options"}. Run \`vercel deploy describe --help\` for usage.`,2)}asJson=parsed.flags["--json"]===!0;let deploymentId=parsed.flags["--id"],awsAccountId=parsed.flags["--aws-account-id"];if((parsed.args[0]==="deploy"?parsed.args.slice(1):parsed.args).length>1)return fail("invalid_arguments","Unexpected positional arguments. Run `vercel deploy describe --help` for usage.",2);if(!deploymentId||!/^dpl_[a-zA-Z0-9]+$/.test(deploymentId))return fail("invalid_arguments","Provide a deployment ID with --id, such as --id dpl_xxx.",2);if(!awsAccountId||!/^\d{12}$/.test(awsAccountId))return fail("invalid_arguments","Provide a 12-digit AWS account ID with --aws-account-id.",2);if(process.platform==="win32")return fail("unsupported_platform","vercel deploy describe is not supported on Windows yet. Run it on macOS or Linux.");let telemetry=new DescribeTelemetryClient({opts:{store:client.telemetryEventStore}});telemetry.trackCliOptionId(deploymentId),telemetry.trackCliOptionAwsAccountId(awsAccountId),telemetry.trackCliFlagJson(parsed.flags["--json"]);try{let project=await resolveDescribeProject(client),explicitTeam=parsed.flags["--scope"]?client.config.currentTeam:process.env.VERCEL_ORG_ID;if(explicitTeam&&explicitTeam!==project.orgId)return fail("scope_mismatch","The selected team does not match the local project link. Use the linked team, or run `vercel pull --yes` with the intended VERCEL_ORG_ID and VERCEL_PROJECT_ID.");if(process.env.VERCEL_PROJECT_ID&&process.env.VERCEL_PROJECT_ID!==project.projectId)return fail("project_mismatch","VERCEL_PROJECT_ID differs from the linked project. Run `vercel pull --yes` to restore settings for the intended project.");client.config.currentTeam=project.orgId.startsWith("team_")?project.orgId:void 0,asJson||output_manager_default.log(`Preparing ${deploymentId} in team ${project.orgId} for AWS account ${awsAccountId}`);let directory=await describeDeployment(client,{directory:project.directory,repoRootPath:project.repoRootPath,deploymentId,awsAccountId,teamId:project.orgId,quiet:asJson}),descriptor=join10(directory,"descriptor.json");if(asJson)client.stdout.write(`${JSON.stringify({deployment:{id:deploymentId},awsAccountId,directory,descriptor})}
|
|
21
21
|
`);else{client.stdout.write(`${descriptor}
|
|
22
22
|
`),output_manager_default.log(`Prepared function packages in ${directory}`);let cwd=project.directory===client.cwd?"":` --cwd ${quoteArg(project.directory)}`;output_manager_default.log(`Provision the functions in descriptor.json, then run:
|
|
@@ -34,7 +34,7 @@ exec "$USER_BOOTSTRAP" "$@"
|
|
|
34
34
|
${err.stack}`),err instanceof UploadErrorMissingArchive)return output_manager_default.prettyError(err),1;if(err instanceof NotDomainOwner)return recordCliError({code:"not_domain_owner"},{override:!0}),output_manager_default.error(err.message),1;if(err instanceof DomainNotFound||err instanceof DomainNotVerified||err instanceof NotDomainOwner||err instanceof DomainPermissionDenied||err instanceof DomainVerificationFailed||err instanceof SchemaValidationFailed||err instanceof InvalidDomain||err instanceof DeploymentNotFound||err instanceof BuildsRateLimited||err instanceof DeploymentsRateLimited||err instanceof AliasDomainConfigured||err instanceof MissingBuildScript||err instanceof ConflictingFilePath||err instanceof ConflictingPathSegment||err instanceof ConflictingConfigFiles||err instanceof DeprecatedNowJson)return handleCreateDeployError(err,localConfig),1;if(isAPIError(err)&&err.code==="size_limit_exceeded"){let{sizeLimit=0}=err,message=`File size limit exceeded (${(0,import_bytes.default)(sizeLimit)})`;return error(message),1}return printError(err),1}}async function handleContinueSubcommand(client,telemetryClient){let flagsSpecification=getFlagsSpecification(continueSubcommand.options),parsedArguments;try{parsedArguments=parseArguments(client.argv.slice(2),flagsSpecification)}catch(error){return printError(error),2}let idFlag=parsedArguments.flags["--id"],parsedArchive=parsedArguments.flags["--archive"],errorMessage=parsedArguments.flags["--error"];if(typeof parsedArchive=="string"&&!isValidArchive(parsedArchive))return output_manager_default.error(`Format must be one of: ${import_client.VALID_ARCHIVE_FORMATS.join(", ")}`),2;if(telemetryClient.trackCliOptionArchive(parsedArchive),parsedArchive&&errorMessage!==void 0)return output_manager_default.error(`Cannot use ${param("--archive")} with ${param("--error")}`),2;if(errorMessage!==void 0&&errorMessage.trim()==="")return output_manager_default.error(`${param("--error")} requires an error message`),1;if(!idFlag)return client.nonInteractive?(outputAgentError(client,{status:AGENT_STATUS.ERROR,reason:"missing_id",message:"Missing required --id flag. Provide the deployment ID to continue.",next:[{command:withGlobalFlags(client,"deploy continue --id <deployment-id>"),when:"provide deployment ID"}]},2),2):(output_manager_default.error(`Missing required ${param("--id")} flag. Usage: ${getCommandName("deploy continue --id <deployment-id>")}`),2);let paths=[client.cwd],pathValidation=await validatePaths(client,paths);if(!pathValidation.valid)return pathValidation.exitCode;await compileVercelConfig(paths[0]);let localConfig=client.localConfig||readLocalConfig(paths[0]);localConfig&&(client.localConfig=localConfig);let{path:cwd}=pathValidation,link=await ensureLink("deploy",client,cwd,{autoConfirm:!0,projectName:localConfig?.name});if(typeof link=="number")return link;let{org}=link;if(link.repoRoot&&(cwd=link.repoRoot),client.config.currentTeam=org.type==="team"?org.id:void 0,errorMessage!==void 0)try{return await client.fetch(`/deployments/${idFlag}/continue`,{method:"POST",body:{errorMessage}}),output_manager_default.success(`Marked deployment ${idFlag} as errored`),0}catch(error){return printError(error),1}let vercelOutputDir=join13(cwd,".vercel/output");if(link.repoRoot&&link.project.rootDirectory&&(vercelOutputDir=join13(cwd,link.project.rootDirectory,".vercel/output")),!await import_fs_extra4.default.pathExists(vercelOutputDir))return client.nonInteractive?(outputAgentError(client,{status:AGENT_STATUS.ERROR,reason:"prebuilt_not_found",message:'No prebuilt output found in ".vercel/output". Run build first.',next:[{command:withGlobalFlags(client,"build"),when:"generate prebuilt output"},{command:withGlobalFlags(client,`deploy continue --id ${idFlag}`),when:"deploy prebuilt output"}]},1),1):(output_manager_default.error(`No prebuilt output found in ".vercel/output". Run ${getCommandName("build")} to generate a local build.`),1);let deployStamp=stamp_default();return handleContinueDeployment({client,telemetryClient,deploymentId:idFlag,cwd,deployStamp,noWait:!1,org,vercelOutputDir,archive:parsedArchive?"tgz":void 0})}async function handleDefaultDeploy(client,telemetryClient){let tempDirs=[];try{return await runDefaultDeploy(client,telemetryClient,tempDirs)}finally{await Promise.all(tempDirs.map(dir=>import_fs_extra4.default.remove(dir)))}}async function runDefaultDeploy(client,telemetryClient,tempDirs){let flagsSpecification=getFlagsSpecification(deployCommand.options),parsedArguments;try{parsedArguments=parseArguments(client.argv.slice(2),flagsSpecification)}catch(error2){return printError(error2),2}let buildMachine=parsedArguments.flags["--turbo"]?"turbo":void 0;telemetryClient.trackCliOptionArchive(parsedArguments.flags["--archive"]),telemetryClient.trackCliFlagTurbo(parsedArguments.flags["--turbo"]),telemetryClient.trackCliOptionEnv(parsedArguments.flags["--env"]),telemetryClient.trackCliOptionBuildEnv(parsedArguments.flags["--build-env"]),telemetryClient.trackCliOptionMeta(parsedArguments.flags["--meta"]),telemetryClient.trackCliFlagPrebuilt(parsedArguments.flags["--prebuilt"]),telemetryClient.trackCliOptionRegions(parsedArguments.flags["--regions"]),telemetryClient.trackCliFlagNoWait(parsedArguments.flags["--no-wait"]),telemetryClient.trackCliFlagDry(parsedArguments.flags["--dry"]),telemetryClient.trackCliFlagYes(parsedArguments.flags["--yes"]),telemetryClient.trackCliOptionTarget(parsedArguments.flags["--target"]),telemetryClient.trackCliFlagProd(parsedArguments.flags["--prod"]),telemetryClient.trackCliFlagTemporary(parsedArguments.flags["--temporary"]),telemetryClient.trackCliFlagSkipDomain(parsedArguments.flags["--skip-domain"]),telemetryClient.trackCliFlagLogs(parsedArguments.flags["--logs"]),telemetryClient.trackCliFlagNoLogs(parsedArguments.flags["--no-logs"]),telemetryClient.trackCliFlagGuidance(parsedArguments.flags["--guidance"]),telemetryClient.trackCliFlagForce(parsedArguments.flags["--force"]),telemetryClient.trackCliFlagWithCache(parsedArguments.flags["--with-cache"]),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;"--confirm"in parsedArguments.flags&&(telemetryClient.trackCliFlagConfirm(parsedArguments.flags["--confirm"]),output_manager_default.warn("`--confirm` is deprecated, please use `--yes` instead"),parsedArguments.flags["--yes"]=parsedArguments.flags["--confirm"]),"--no-logs"in parsedArguments.flags&&output_manager_default.warn("`--no-logs` is deprecated and now the default behavior."),parsedArguments.args[0]===deployCommand.name&&parsedArguments.args.shift();let paths;parsedArguments.args.length>0?(paths=parsedArguments.args.map(item=>resolve3(client.cwd,item)),telemetryClient.trackCliArgumentProjectPath(paths[0])):paths=[client.cwd];let pathValidation=await validatePaths(client,paths,{allowFiles:!0});if(!pathValidation.valid)return pathValidation.exitCode;let singleFile=pathValidation.isFile?pathValidation.path:void 0;if(singleFile){let incompatibleFlag=["--prebuilt","--archive","--local-config"].find(flag=>parsedArguments.flags[flag]),message=incompatibleFlag?`Single-file deployments don't support ${incompatibleFlag}. Deploy a directory to use this option.`:!client.authConfig.token&&parsedArguments.flags["--temporary"]&&extname(singleFile).toLowerCase()!==".html"?"Temporary single-file deployments support only `.html` files. Log in or deploy a directory to deploy other files.":await isIgnoredFile(singleFile,client.cwd)?`${basename3(singleFile)} matches \`.vercelignore\` or the default ignore list, so it can't be deployed.`:void 0;if(message)return asJson?client.stdout.write(`${JSON.stringify({status:"error",reason:"invalid_file_deployment_option",message})}
|
|
35
35
|
`):output_manager_default.fatal(message),1;if(basename3(singleFile).startsWith(".")&&!parsedArguments.flags["--yes"]&&!parsedArguments.flags["--dry"]){let warning=`${basename3(singleFile)} is a hidden file and will be publicly accessible once deployed.`;if(client.nonInteractive||!client.stdin.isTTY)return asJson?client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.ACTION_REQUIRED,reason:AGENT_REASON.CONFIRMATION_REQUIRED,message:`${warning} Use option --yes to deploy it.`,next:[{command:buildCommandWithYes(client.argv),when:"Deploy the hidden file"}]},null,2)}
|
|
36
36
|
`):output_manager_default.error(`${warning} Use option ${param("--yes")} to deploy it.`),1;if(!await client.input.confirm(`${warning} Continue?`,!1))return output_manager_default.print(`Canceled
|
|
37
|
-
`),0}}try{singleFile||await compileVercelConfig(paths[0])}catch(err){if(err instanceof ConflictingConfigFiles||err instanceof DeprecatedNowJson)return output_manager_default.prettyError(err),1;throw err}let shouldUseEarlyLocalConfig=paths[0]===client.cwd,localConfig=singleFile?{...singleFileConfig}:shouldUseEarlyLocalConfig?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,prettyError}=output_manager_default,quiet=!client.stdout.isTTY,cwd=singleFile?
|
|
37
|
+
`),0}}try{singleFile||await compileVercelConfig(paths[0])}catch(err){if(err instanceof ConflictingConfigFiles||err instanceof DeprecatedNowJson)return output_manager_default.prettyError(err),1;throw err}let shouldUseEarlyLocalConfig=paths[0]===client.cwd,localConfig=singleFile?{...singleFileConfig}:shouldUseEarlyLocalConfig?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,prettyError}=output_manager_default,quiet=!client.stdout.isTTY,cwd=singleFile?dirname3(singleFile):pathValidation.path,autoConfirm=parsedArguments.flags["--yes"]||client.nonInteractive;parsedArguments.flags["--name"]&&(output_manager_default.print(`${prependEmoji(`The ${param("--name")} option is deprecated (https://vercel.link/name-flag)`,emoji("warning"))}
|
|
38
38
|
`),telemetryClient.trackCliOptionName(parsedArguments.flags["--name"])),parsedArguments.flags["--no-clipboard"]&&(output_manager_default.print(`${prependEmoji(`The ${param("--no-clipboard")} option was ignored because it is the default behavior. Please remove it.`,emoji("warning"))}
|
|
39
39
|
`),telemetryClient.trackCliFlagNoClipboard(!0));let isAnonymous=!client.authConfig.token&&!!parsedArguments.flags["--temporary"];if(!client.authConfig.token&&!isAnonymous)return output_manager_default.prettyError({message:`No existing credentials found. Run ${getCommandName("deploy --temporary")} to create a temporary deployment you can claim later, or ${getCommandName("login")} to log in.`,link:"https://err.sh/vercel/no-credentials-found"}),1;let target=parseTarget({flagName:"target",flags:parsedArguments.flags});if(telemetryClient.trackTargetEnvironment(target),!validateAnonymousTarget(isAnonymous,target))return 1;if(parsedArguments.flags["--skip-domain"]&&target!=="production")return output_manager_default.error("The `--skip-domain` option can only be used with production deployments. Use `--prod` or `--target=production`."),1;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"))}
|
|
40
40
|
`);let cliMeta=parseMeta(parsedArguments.flags["--meta"]),isV0=cliMeta.v0==="true";!singleFile&&!parsedArguments.flags["--dry"]&&getGitExecutable(cwd);let anonymousSetup=singleFile&&!isAnonymous?{isAnonymous:!1,anonymousLink:void 0}:await setupAnonymousDeployment(client,cwd,{isAnonymous,dryRun:!!parsedArguments.flags["--dry"]});if(typeof anonymousSetup=="number")return anonymousSetup;isAnonymous=anonymousSetup.isAnonymous;let anonymousLink=anonymousSetup.anonymousLink;anonymousLink&&(target="production");let link=anonymousLink??await ensureLink("deploy",client,cwd,{autoConfirm,singleFile,pullEnv:singleFile?!1:void 0,projectName:projectNameOrId??parsedArguments.flags["--name"]??localConfig?.name,failIfNotFound:!!projectNameOrId,requireExistingLink:parsedArguments.flags["--dry"],allowOwnerLookupFallback:!0,skipRemoteLookup:!parsedArguments.flags["--dry"],v0:isV0});if(typeof link=="number")return link;let redeployCommand=withGlobalFlags(client,singleFile?`deploy ${quoteArg(singleFile)}${isAnonymous?" --temporary":""}`:isAnonymous?"deploy --temporary":"deploy",{preserveProject:!!singleFile}),{org,project}=link,rootDirectory=singleFile?null:project.rootDirectory,sourceFilesOutsideRootDirectory=project.sourceFilesOutsideRootDirectory??!0,projectCwd=cwd;!singleFile&&link.repoRoot&&(cwd=link.repoRoot);let postDeployGuidanceEnabled=!singleFile&&!anonymousLink&&(client.nonInteractive||!asJson)&&isGuidanceEnabled(client,parsedArguments.flags["--guidance"],!0),prebuilt=isAnonymous||!!parsedArguments.flags["--prebuilt"],vercelOutputDir,prebuiltBuild=null,singleFileOutputRoot;if(prebuilt){vercelOutputDir=join13(cwd,".vercel/output"),link.repoRoot&&link.project.rootDirectory&&(vercelOutputDir=join13(cwd,link.project.rootDirectory,".vercel/output"));let prebuiltExists=await import_fs_extra4.default.pathExists(vercelOutputDir);if(singleFile)singleFileOutputRoot=await import_fs_extra4.default.mkdtemp(join13(tmpdir(),"vercel-file-")),tempDirs.push(singleFileOutputRoot),vercelOutputDir=join13(singleFileOutputRoot,".vercel/output"),await import_fs_extra4.default.copy(singleFile,join13(vercelOutputDir,"static",basename3(singleFile))),await import_fs_extra4.default.outputJSON(join13(vercelOutputDir,"config.json"),{version:3}),prebuiltExists=!0;else if(isAnonymous&&!parsedArguments.flags["--prebuilt"]&&!parsedArguments.flags["--dry"]){let buildExitCode=await runImplicitBuild(client,cwd);if(buildExitCode!==0)return buildExitCode;prebuiltExists=await import_fs_extra4.default.pathExists(vercelOutputDir)}if(!prebuiltExists)return error(`The ${param("--prebuilt")} option was used, but no prebuilt output found in ".vercel/output". Run ${getCommandName("build")} to generate a local build.`),1;prebuiltBuild=await getPrebuiltJson(vercelOutputDir);let prebuiltError=prebuiltBuild?.error||prebuiltBuild?.builds?.find(build=>"error"in build)?.error;if(prebuiltError)return output_manager_default.log(`Prebuilt deployment cannot be created because ${getCommandName("build")} failed with error:
|
package/dist/version.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export const version = "63.1.
|
|
1
|
+
export const version = "63.1.2";
|
|
2
2
|
export const buildLabel = "";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vercel",
|
|
3
|
-
"version": "63.1.
|
|
3
|
+
"version": "63.1.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"preferGlobal": true,
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -35,6 +35,7 @@
|
|
|
35
35
|
"undici": "5.29.0",
|
|
36
36
|
"uuid": "14.0.1",
|
|
37
37
|
"zod": "4.1.11",
|
|
38
|
+
"@vercel/backends": "18.0.1",
|
|
38
39
|
"@vercel/build-utils": "14.20.1",
|
|
39
40
|
"@vercel/cli-auth": "0.3.10",
|
|
40
41
|
"@vercel/cli-config": "0.3.1",
|
|
@@ -43,22 +44,21 @@
|
|
|
43
44
|
"@vercel/elysia": "18.0.1",
|
|
44
45
|
"@vercel/express": "18.0.1",
|
|
45
46
|
"@vercel/fastify": "18.0.1",
|
|
46
|
-
"@vercel/go": "21.0.1",
|
|
47
47
|
"@vercel/h3": "18.0.1",
|
|
48
48
|
"@vercel/hono": "18.0.1",
|
|
49
|
+
"@vercel/go": "21.0.1",
|
|
49
50
|
"@vercel/hydrogen": "19.0.1",
|
|
50
51
|
"@vercel/koa": "18.0.1",
|
|
51
52
|
"@vercel/nestjs": "18.0.1",
|
|
52
53
|
"@vercel/next": "22.0.1",
|
|
53
|
-
"@vercel/node": "23.0.1",
|
|
54
54
|
"@vercel/python": "24.0.1",
|
|
55
55
|
"@vercel/python-analysis": "0.14.0",
|
|
56
|
+
"@vercel/node": "23.0.1",
|
|
56
57
|
"@vercel/redwood": "20.0.1",
|
|
57
58
|
"@vercel/remix-builder": "23.0.1",
|
|
58
59
|
"@vercel/ruby": "20.0.1",
|
|
59
60
|
"@vercel/rust": "19.0.1",
|
|
60
|
-
"@vercel/static-build": "20.0.1"
|
|
61
|
-
"@vercel/backends": "18.0.1"
|
|
61
|
+
"@vercel/static-build": "20.0.1"
|
|
62
62
|
},
|
|
63
63
|
"builders": {
|
|
64
64
|
"@vercel/backends": "18.0.1",
|
|
@@ -210,24 +210,24 @@
|
|
|
210
210
|
"@vercel-internals/builder-orchestration": "1.0.18",
|
|
211
211
|
"@vercel-internals/cli-builder-integration": "1.0.21",
|
|
212
212
|
"@vercel-internals/constants": "1.0.4",
|
|
213
|
-
"@vercel-internals/local-schedules": "0.0.4",
|
|
214
213
|
"@vercel-internals/runtimes": "1.1.14",
|
|
214
|
+
"@vercel-internals/local-schedules": "0.0.4",
|
|
215
215
|
"@vercel-internals/service-topology": "1.0.17",
|
|
216
216
|
"@vercel-internals/types": "3.0.22",
|
|
217
217
|
"@vercel/client": "18.8.2",
|
|
218
|
-
"@vercel/error-utils": "2.2.1",
|
|
219
218
|
"@vercel/frameworks": "3.35.0",
|
|
219
|
+
"@vercel/error-utils": "2.2.1",
|
|
220
220
|
"@vercel/fs-detectors": "7.9.6",
|
|
221
221
|
"@vercel/routing-utils": "6.6.0",
|
|
222
222
|
"@vercel-internals/get-package-json": "1.0.0"
|
|
223
223
|
},
|
|
224
224
|
"optionalDependencies": {
|
|
225
|
-
"@vercel/vc-native-darwin-arm64": "63.1.
|
|
226
|
-
"@vercel/vc-native-darwin-x64": "63.1.
|
|
227
|
-
"@vercel/vc-native-linux-arm64": "63.1.
|
|
228
|
-
"@vercel/vc-native-linux-x64": "63.1.
|
|
229
|
-
"@vercel/vc-native-win32-arm64": "63.1.
|
|
230
|
-
"@vercel/vc-native-win32-x64": "63.1.
|
|
225
|
+
"@vercel/vc-native-darwin-arm64": "63.1.2",
|
|
226
|
+
"@vercel/vc-native-darwin-x64": "63.1.2",
|
|
227
|
+
"@vercel/vc-native-linux-arm64": "63.1.2",
|
|
228
|
+
"@vercel/vc-native-linux-x64": "63.1.2",
|
|
229
|
+
"@vercel/vc-native-win32-arm64": "63.1.2",
|
|
230
|
+
"@vercel/vc-native-win32-x64": "63.1.2"
|
|
231
231
|
},
|
|
232
232
|
"scripts": {
|
|
233
233
|
"test": "node scripts/test.mjs --run",
|